answer
stringlengths 17
10.2M
|
|---|
package edu.yu.einstein.wasp.integration.endpoints;
import java.net.URI;
import java.net.URISyntaxException;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.Message;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.transaction.annotation.Transactional;
import edu.yu.einstein.wasp.exception.SampleParentChildException;
import edu.yu.einstein.wasp.exception.SampleTypeException;
import edu.yu.einstein.wasp.exception.WaspException;
import edu.yu.einstein.wasp.exception.WaspRuntimeException;
import edu.yu.einstein.wasp.model.FileGroup;
import edu.yu.einstein.wasp.model.FileGroupMeta;
import edu.yu.einstein.wasp.model.FileHandle;
import edu.yu.einstein.wasp.model.FileHandleMeta;
import edu.yu.einstein.wasp.model.FileType;
import edu.yu.einstein.wasp.model.Job;
import edu.yu.einstein.wasp.model.JobMeta;
import edu.yu.einstein.wasp.model.JobSample;
import edu.yu.einstein.wasp.model.LabUser;
import edu.yu.einstein.wasp.model.Sample;
import edu.yu.einstein.wasp.model.SampleMeta;
import edu.yu.einstein.wasp.model.SampleSource;
import edu.yu.einstein.wasp.model.SampleSubtype;
import edu.yu.einstein.wasp.model.User;
import edu.yu.einstein.wasp.model.Workflow;
import edu.yu.einstein.wasp.plugin.WaspPlugin;
import edu.yu.einstein.wasp.plugin.WaspPluginRegistry;
import edu.yu.einstein.wasp.plugin.cli.CliMessagingTask;
import edu.yu.einstein.wasp.plugin.cli.ClientMessageI;
import edu.yu.einstein.wasp.plugin.supplemental.organism.Build;
import edu.yu.einstein.wasp.plugin.supplemental.organism.Genome;
import edu.yu.einstein.wasp.plugin.supplemental.organism.Organism;
import edu.yu.einstein.wasp.service.FileService;
import edu.yu.einstein.wasp.service.GenomeService;
import edu.yu.einstein.wasp.service.JobService;
import edu.yu.einstein.wasp.service.LabService;
import edu.yu.einstein.wasp.service.SampleService;
import edu.yu.einstein.wasp.service.UserService;
import edu.yu.einstein.wasp.service.WorkflowService;
public class CliSupportingServiceActivator implements ClientMessageI, CliSupporting{
protected Logger logger = LoggerFactory.getLogger(CliSupportingServiceActivator.class);
@Autowired
private GenomeService genomeService;
@Autowired
private WaspPluginRegistry pluginRegistry;
@Autowired
private SampleService sampleService;
@Autowired
private FileService fileService;
@Autowired
private JobService jobService;
@Autowired
private WorkflowService workflowService;
@Autowired
private UserService userService;
@Autowired
private LabService labService;
public CliSupportingServiceActivator() {
}
/**
* ServiceActivator called method
*/
@Override
@Transactional("entityManager")
public Message<?> process(Message<?> m) throws RemoteException {
String payloadStr = m.getPayload().toString();
if (payloadStr.startsWith("{") && payloadStr.endsWith("}")){ // looks like JSON to me
return processImportedFileRegistrationData(new JSONObject(payloadStr));
} else if (payloadStr.equals(CliMessagingTask.LIST_PLUGINS)) {
return listPlugins();
} else if (payloadStr.equals(CliMessagingTask.LIST_GENOME_BUILDS)) {
return listGenomeBuilds();
} else if (payloadStr.equals(CliMessagingTask.LIST_SAMPLE_SUBTYPES)) {
return listSampleSubtypes();
} else if (payloadStr.equals(CliMessagingTask.LIST_CELL_LIBRARIES)) {
return listCellLibraries();
} else if (payloadStr.equals(CliMessagingTask.LIST_FILE_TYPES)) {
return listFileTypes();
} else if (payloadStr.equals(CliMessagingTask.LIST_ASSAY_WORKFLOWS)) {
return listAssayWorkflows();
} else if (payloadStr.equals(CliMessagingTask.LIST_USERS)) {
return listUsers();
} else {
String mstr = "Unknown command: " + m.toString() + "'\n";
return MessageBuilder.withPayload(mstr).build();
}
}
@Override
@Transactional("entityManager")
public Message<String> listPlugins() {
Map<String, String> plugins = new HashMap<>();
List<WaspPlugin> pluginList = new ArrayList<WaspPlugin>(pluginRegistry.getPlugins().values());
for (WaspPlugin plugin : pluginList)
plugins.put(plugin.getIName(), plugin.getDescription());
return MessageBuilder.withPayload(new JSONObject(plugins).toString()).build();
}
@Override
@Transactional("entityManager")
public Message<String> listGenomeBuilds(){
Map<String, String> builds = new HashMap<>();
for (Organism o : genomeService.getOrganisms())
for (Genome g : o.getGenomes().values())
for (Build b : g.getBuilds().values())
builds.put(genomeService.getDelimitedParameterString(b), b.getDescription());
return MessageBuilder.withPayload(new JSONObject(builds).toString()).build();
}
@Override
@Transactional("entityManager")
public Message<String> listSampleSubtypes(){
Map<String, String> sampleSubtypes = new HashMap<>();
for (SampleSubtype sst : sampleService.getSampleSubtypeDao().findAll())
if (sst.getIsActive() == 1)
sampleSubtypes.put(sst.getId().toString(), sst.getName());
return MessageBuilder.withPayload(new JSONObject(sampleSubtypes).toString()).build();
}
@Override
@Transactional("entityManager")
public Message<String> listCellLibraries() {
Map<String, String> cellLibraries = new HashMap<>();
for (SampleSource cellLibrary : sampleService.getCellLibraries()){
Sample library = sampleService.getLibrary(cellLibrary);
String libraryName = library.getName();
Sample cell = sampleService.getCell(cellLibrary);
if (cell != null){
if (!sampleService.isCell(cell))
continue;
try {
libraryName += " (" + sampleService.getPlatformUnitForCell(cell).getName() + " / " + sampleService.getCellIndex(cell) + ")";
} catch (SampleTypeException | SampleParentChildException e) {
// just leave as default empty string
}
}
cellLibraries.put(cellLibrary.getId().toString(), libraryName);
}
return MessageBuilder.withPayload(new JSONObject(cellLibraries).toString()).build();
}
@Override
@Transactional("entityManager")
public Message<String> listFileTypes(){
Map<String, String> fileTypes = new HashMap<>();
for (FileType ft : fileService.getFileTypes())
fileTypes.put(ft.getId().toString(), ft.getIName() + " (" + ft.getName() + ")");
return MessageBuilder.withPayload(new JSONObject(fileTypes).toString()).build();
}
@Override
@Transactional("entityManager")
public Message<String> listAssayWorkflows(){
Map<String, String> workflows = new HashMap<>();
for (Workflow w : workflowService.getWorkflows())
workflows.put(w.getId().toString(), w.getName());
return MessageBuilder.withPayload(new JSONObject(workflows).toString()).build();
}
@Override
@Transactional("entityManager")
public Message<String> listUsers(){
Map<String, String> users = new HashMap<>();
for (LabUser lu : labService.getAllLabUsers()){
String labName = lu.getLab().getName();
User u = lu.getUser();
if (!users.containsKey(u.getId().toString())) // TODO: only selects first lab below but user may be in more than one lab
users.put(u.getId().toString(), u.getLastName() + ", " + u.getFirstName() + " (" + labName + ")");
}
return MessageBuilder.withPayload(new JSONObject(users).toString()).build();
}
@Transactional("entityManager")
@Override
public Message<String> processImportedFileRegistrationData(JSONObject data){
logger.debug("Handling json: " + data.toString());
List<String> headerList = new ArrayList<>();
SampleSource currentCellLibrary = null;
Job currentJob = null;
Sample currentSample = null;
FileGroup currentFileGroup = null;
FileHandle currentFileHandle = null;
for (int i=0; i < data.length(); i++){
JSONArray lineElementList = data.getJSONArray(Integer.toString(i));
for (int j = 0; j < lineElementList.length(); j++){
String attributeVal = lineElementList.getString(j);
if (attributeVal.isEmpty())
continue;
if (i == 0){ // first line
headerList.add(attributeVal);
continue;
}
String heading = headerList.get(j);
String model = heading;
String attributeName = "";
int periodPos = heading.indexOf(".");
if (periodPos != -1){
model = heading.substring(0, periodPos);
attributeName = heading.substring(periodPos + 1);
}
try {
if (model.equals("cellLibraryId")){
logger.debug("getting cellLibrary: " + attributeVal);
Integer id = Integer.parseInt(attributeVal);
if (currentCellLibrary == null || !currentCellLibrary.getId().equals(id))
try{
currentCellLibrary = sampleService.getCellLibraryBySampleSourceId(id);
} catch (SampleTypeException e){
throw new WaspRuntimeException("Unable to get cellLibrary with id=" + attributeVal + ": " + e.getMessage());
}
if (currentCellLibrary == null || currentCellLibrary.getId() == null)
throw new WaspRuntimeException("Unable to get cellLibrary with id=" + attributeVal);
logger.debug("cellLibraryId Id=" + currentCellLibrary.getId());
} else if (model.equals("Job")){
if (attributeName.equals("name")){
if (currentJob == null || !currentJob.getName().equals(attributeVal)){
currentJob = new Job();
currentJob.setName(attributeVal);
currentJob = jobService.getJobDao().save(currentJob);
}
} else if (attributeName.equals("userId")){
User u = userService.getUserDao().findById(Integer.parseInt(attributeVal));
if (u == null || u.getId() == null)
throw new WaspRuntimeException("Unable to get user with id=" + attributeVal);
if (currentJob != null && !u.getId().equals(currentJob.getUserId()) ){
currentJob.setUser(u);
currentJob.setLab(userService.getLabsForUser(u).get(0)); // TODO:: user may be in more than one lab
currentJob.setIsActive(1);
}
} else if (attributeName.equals("workflowId")){
Workflow wf = workflowService.getWorkflowDao().findById(Integer.parseInt(attributeVal));
if (wf == null || wf.getId() == null)
throw new WaspRuntimeException("Unable to get workflow with id=" + attributeVal);
if (currentJob != null && !wf.getId().equals(currentJob.getWorkflowId()) )
currentJob.setWorkflow(wf);
}
} else if (model.equals("JobMeta")){
JobMeta meta = new JobMeta();
meta.setK(attributeName);
meta.setV(attributeVal);
meta.setJob(currentJob);
jobService.getJobMetaDao().setMeta(meta);
} else if (model.equals("Sample")){
if (attributeName.equals("name")){
if (currentSample == null || !currentSample.getName().equals(attributeVal)){
currentSample = new Sample();
currentSample.setName(attributeVal);
currentSample.setSubmitterUserId(currentJob.getUserId());
currentSample.setSubmitterLabId(currentJob.getLabId());
currentSample.setSubmitterJobId(currentJob.getId());
currentSample.setIsActive(1);
currentSample = sampleService.getSampleDao().save(currentSample);
currentCellLibrary = new SampleSource();
currentCellLibrary.setSourceSample(currentSample);
currentCellLibrary = sampleService.getSampleSourceDao().save(currentCellLibrary);
sampleService.setJobForLibraryOnCell(currentCellLibrary, currentJob);
JobSample jobSample = new JobSample();
jobSample.setJob(currentJob);
jobSample.setSample(currentSample);
jobSample = jobService.getJobSampleDao().save(jobSample);
}
} else if (attributeName.equals("sampleSubtypeId")){
SampleSubtype ss = sampleService.getSampleSubtypeById(Integer.parseInt(attributeVal));
if (ss == null || ss.getId() == null)
throw new WaspRuntimeException("Unable to get sampleSubtype with id=" + attributeVal);
if (currentSample != null && !ss.getId().equals(currentSample.getSampleSubtypeId()) ){
currentSample.setSampleSubtype(ss);
currentSample.setSampleTypeId(ss.getSampleTypeId());
}
}
} else if (model.equals("SampleMeta")){
SampleMeta meta = new SampleMeta();
meta.setK(attributeName);
meta.setV(attributeVal);
meta.setSample(currentSample);
sampleService.getSampleMetaDao().setMeta(meta);
} else if (model.equals("FileGroup")){
if (attributeName.equals("description")){
if (currentFileGroup == null || !currentFileGroup.getDescription().equals(attributeVal)){
currentFileGroup = new FileGroup();
currentFileGroup.setDescription(attributeVal);
currentFileGroup.setIsActive(1);
currentFileGroup.setIsArchived(0);
currentFileGroup = fileService.addFileGroup(currentFileGroup);
logger.debug("currentFileGroup Id=" + currentFileGroup.getId());
logger.debug("currentCellLibrary Id=" + currentCellLibrary.getId());
fileService.setSampleSourceFile(currentFileGroup, currentCellLibrary);
}
} else if (attributeName.equals("fileTypeId")){
FileType ft = fileService.getFileType(Integer.parseInt(attributeVal));
if (ft == null || ft.getId() == null)
throw new WaspRuntimeException("Unable to get fileTypeSubtype with id=" + attributeVal);
if (currentFileGroup != null && !ft.getId().equals(currentFileGroup.getId()) )
currentFileGroup.setFileType(ft);
}
}
else if (model.equals("FileGroupMeta")){
FileGroupMeta meta = new FileGroupMeta();
meta.setK(attributeName);
meta.setV(attributeVal);
meta.setFileGroup(currentFileGroup);
List<FileGroupMeta> metaList = new ArrayList<>();
metaList.add(meta);
fileService.saveFileGroupMeta(metaList, currentFileGroup);
} else if (model.equals("FileHandle")){
if (attributeName.equals("name")){
if (currentFileHandle == null || !currentFileHandle.getFileName().equals(attributeVal)){
currentFileHandle = new FileHandle();
currentFileHandle.setFileName(attributeVal);
currentFileHandle.setFileType(currentFileGroup.getFileType());
currentFileHandle = fileService.addFile(currentFileHandle);
currentFileGroup.addFileHandle(currentFileHandle);
}
} else if (attributeName.equals("fileURI")){
currentFileHandle.setFileURI(new URI(attributeVal));
} else if (attributeName.equals("md5hash")){
currentFileHandle.setMd5hash(attributeVal);
}
} else if (model.equals("FileHandleMeta")){
FileHandleMeta meta = new FileHandleMeta();
meta.setK(attributeName);
meta.setV(attributeVal);
meta.setFile(currentFileHandle);
List<FileHandleMeta> metaList = new ArrayList<>();
metaList.add(meta);
fileService.saveFileHandleMeta(metaList, currentFileHandle);
}
} catch (WaspException | URISyntaxException e) {
e.printStackTrace();
throw new WaspRuntimeException("Unable to parse or persist data value for element=" + attributeVal);
}
}
}
return MessageBuilder.withPayload("Update successful\n").build();
}
}
|
package info.bitrich.xchangestream.bitfinex;
import info.bitrich.xchangestream.bitfinex.dto.BitfinexWebSocketAuthOrder;
import info.bitrich.xchangestream.bitfinex.dto.BitfinexWebSocketAuthTrade;
import org.junit.Test;
import org.knowm.xchange.currency.CurrencyPair;
import org.knowm.xchange.dto.Order;
import org.knowm.xchange.dto.Order.OrderStatus;
import org.knowm.xchange.dto.Order.OrderType;
import org.knowm.xchange.dto.trade.LimitOrder;
import org.knowm.xchange.dto.trade.UserTrade;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.Date;
import static org.junit.Assert.assertEquals;
public class BitfinexStreamingAdaptersTest {
@Test
public void testMarketOrder() {
BitfinexWebSocketAuthOrder bitfinexWebSocketAuthOrder = new BitfinexWebSocketAuthOrder(
123123123L,
0L, //groupId,
456456456L, //cid,
"tBTCUSD", //symbol,
1548674205259L, //mtsCreateamount
1548674205259L, //mtsUpdate
new BigDecimal("0.000"), //amount
new BigDecimal("0.004"), //amountOrig
"MARKET", // type
null, //typePrev
"EXECUTED @ 3495.1(0.004)", //orderStatus
new BigDecimal("3495.2"), //price
new BigDecimal("3495.2"), //priceAvg
BigDecimal.ZERO, //priceTrailing
BigDecimal.ZERO, //priceAuxLimit
0, //placedId
0 //flags
);
// support to XChange itself. In the meantime these are returned as limit orders.
Order adaptedOrder = BitfinexStreamingAdapters.adaptOrder(bitfinexWebSocketAuthOrder);
assertEquals("123123123", adaptedOrder.getId());
assertEquals(Order.OrderType.BID, adaptedOrder.getType());
assertEquals(new BigDecimal("3495.2"), adaptedOrder.getAveragePrice());
assertEquals(new BigDecimal("0.004"), adaptedOrder.getCumulativeAmount());
assertEquals(CurrencyPair.BTC_USD, adaptedOrder.getCurrencyPair());
// TODO see above. should be:
//assertEquals(Collections.singleton(BitfinexOrderFlags.MARGIN), adaptedOrder.getOrderFlags());
assertEquals(new BigDecimal("0.004"), adaptedOrder.getOriginalAmount());
assertEquals(new BigDecimal("0.000"), adaptedOrder.getRemainingAmount());
assertEquals(OrderStatus.FILLED, adaptedOrder.getStatus());
assertEquals(new Date(1548674205259L).getTime(), adaptedOrder.getTimestamp().getTime());
}
@Test
public void testStopOrder() {
BitfinexWebSocketAuthOrder bitfinexWebSocketAuthOrder = new BitfinexWebSocketAuthOrder(
123123123L,
0L, //groupId,
456456456L, //cid,
"tBTCUSD", //symbol,
1548674205259L, //mtsCreateamount
1548674205259L, //mtsUpdate
new BigDecimal("0.000"), //amount
new BigDecimal("0.004"), //amountOrig
"STOP", // type
null, //typePrev
"EXECUTED @ 3495.1(0.004)", //orderStatus
new BigDecimal("3495.2"), //price
new BigDecimal("3495.2"), //priceAvg
BigDecimal.ZERO, //priceTrailing
BigDecimal.ZERO, //priceAuxLimit
0, //placedId
0 //flags
);
// support to XChange itself. In the meantime these are returned as limit orders.
Order adaptedOrder = BitfinexStreamingAdapters.adaptOrder(bitfinexWebSocketAuthOrder);
assertEquals("123123123", adaptedOrder.getId());
assertEquals(Order.OrderType.BID, adaptedOrder.getType());
assertEquals(new BigDecimal("3495.2"), adaptedOrder.getAveragePrice());
assertEquals(new BigDecimal("0.004"), adaptedOrder.getCumulativeAmount());
assertEquals(CurrencyPair.BTC_USD, adaptedOrder.getCurrencyPair());
// TODO see above. should be:
//assertEquals(Collections.singleton(BitfinexOrderFlags.MARGIN), adaptedOrder.getOrderFlags());
assertEquals(new BigDecimal("0.004"), adaptedOrder.getOriginalAmount());
assertEquals(new BigDecimal("0.000"), adaptedOrder.getRemainingAmount());
assertEquals(OrderStatus.FILLED, adaptedOrder.getStatus());
assertEquals(new Date(1548674205259L).getTime(), adaptedOrder.getTimestamp().getTime());
}
@Test
public void testNewLimitOrder() {
BitfinexWebSocketAuthOrder bitfinexWebSocketAuthOrder = new BitfinexWebSocketAuthOrder(
123123123L,
0L, //groupId,
456456456L, //cid,
"tBTCUSD", //symbol,
1548674205259L, //mtsCreateamount
1548674205267L, //mtsUpdate
new BigDecimal("0.004"), //amount
new BigDecimal("0.004"), //amountOrig
"EXCHANGE LIMIT", // type
null, //typePrev
"ACTIVE", //orderStatus
new BigDecimal("3495.2"), //price
BigDecimal.ZERO, //priceAvg
BigDecimal.ZERO, //priceTrailing
BigDecimal.ZERO, //priceAuxLimit
0, //placedId
0 //flags
);
LimitOrder adaptedOrder = (LimitOrder) BitfinexStreamingAdapters.adaptOrder(bitfinexWebSocketAuthOrder);
assertEquals("123123123", adaptedOrder.getId());
assertEquals(Order.OrderType.BID, adaptedOrder.getType());
assertEquals(BigDecimal.ZERO, adaptedOrder.getAveragePrice());
assertEquals(0, BigDecimal.ZERO.compareTo(adaptedOrder.getCumulativeAmount()));
assertEquals(CurrencyPair.BTC_USD, adaptedOrder.getCurrencyPair());
assertEquals(new BigDecimal("3495.2"), adaptedOrder.getLimitPrice());
assertEquals(Collections.emptySet(), adaptedOrder.getOrderFlags());
assertEquals(new BigDecimal("0.004"), adaptedOrder.getOriginalAmount());
assertEquals(new BigDecimal("0.004"), adaptedOrder.getRemainingAmount());
assertEquals(OrderStatus.NEW, adaptedOrder.getStatus());
assertEquals(new Date(1548674205259L).getTime(), adaptedOrder.getTimestamp().getTime());
}
@Test
public void testCancelledLimitOrder() {
BitfinexWebSocketAuthOrder bitfinexWebSocketAuthOrder = new BitfinexWebSocketAuthOrder(
123123123L,
0L, //groupId,
456456456L, //cid,
"tBTCUSD", //symbol,
1548674205259L, //mtsCreateamount
1548674205267L, //mtsUpdate
new BigDecimal("-0.004"), //amount
new BigDecimal("-0.004"), //amountOrig
"LIMIT", // type
null, //typePrev
"CANCELED", //orderStatus
new BigDecimal("3495.2"), //price
BigDecimal.ZERO, //priceAvg
BigDecimal.ZERO, //priceTrailing
BigDecimal.ZERO, //priceAuxLimit
0, //placedId
0 //flags
);
LimitOrder adaptedOrder = (LimitOrder) BitfinexStreamingAdapters.adaptOrder(bitfinexWebSocketAuthOrder);
assertEquals("123123123", adaptedOrder.getId());
assertEquals(Order.OrderType.ASK, adaptedOrder.getType());
assertEquals(BigDecimal.ZERO, adaptedOrder.getAveragePrice());
assertEquals(0, BigDecimal.ZERO.compareTo(adaptedOrder.getCumulativeAmount()));
assertEquals(CurrencyPair.BTC_USD, adaptedOrder.getCurrencyPair());
assertEquals(new BigDecimal("3495.2"), adaptedOrder.getLimitPrice());
assertEquals(new BigDecimal("0.004"), adaptedOrder.getOriginalAmount());
assertEquals(new BigDecimal("0.004"), adaptedOrder.getRemainingAmount());
// TODO see above. should be:
//assertEquals(Collections.singleton(BitfinexOrderFlags.MARGIN), adaptedOrder.getOrderFlags());
assertEquals(OrderStatus.CANCELED, adaptedOrder.getStatus());
assertEquals(new Date(1548674205259L).getTime(), adaptedOrder.getTimestamp().getTime());
}
@Test
public void testPartiallyFilledLimitOrder() {
BitfinexWebSocketAuthOrder bitfinexWebSocketAuthOrder = new BitfinexWebSocketAuthOrder(
123123123L,
0L, //groupId,
456456456L, //cid,
"tBTCUSD", //symbol,
1548674205259L, //mtsCreateamount
1548674205267L, //mtsUpdate
new BigDecimal("-0.001"), //amount
new BigDecimal("-0.004"), //amountOrig
"LIMIT", // type
null, //typePrev
"PARTIALLY FILLED @ 3495.1(0.003)", //orderStatus
new BigDecimal("3495.2"), //price
new BigDecimal("3495.1"), //priceAvg
BigDecimal.ZERO, //priceTrailing
BigDecimal.ZERO, //priceAuxLimit
0, //placedId
0 //flags
);
LimitOrder adaptedOrder = (LimitOrder) BitfinexStreamingAdapters.adaptOrder(bitfinexWebSocketAuthOrder);
assertEquals("123123123", adaptedOrder.getId());
assertEquals(Order.OrderType.ASK, adaptedOrder.getType());
assertEquals(new BigDecimal("3495.1"), adaptedOrder.getAveragePrice());
assertEquals(new BigDecimal("0.003"), adaptedOrder.getCumulativeAmount());
assertEquals(CurrencyPair.BTC_USD, adaptedOrder.getCurrencyPair());
assertEquals(new BigDecimal("3495.2"), adaptedOrder.getLimitPrice());
assertEquals(new BigDecimal("0.004"), adaptedOrder.getOriginalAmount());
assertEquals(new BigDecimal("0.001"), adaptedOrder.getRemainingAmount());
// TODO see above. should be:
//assertEquals(Collections.singleton(BitfinexOrderFlags.MARGIN), adaptedOrder.getOrderFlags());
assertEquals(OrderStatus.PARTIALLY_FILLED, adaptedOrder.getStatus());
assertEquals(new Date(1548674205259L).getTime(), adaptedOrder.getTimestamp().getTime());
}
@Test
public void testExecutedLimitOrder() {
BitfinexWebSocketAuthOrder bitfinexWebSocketAuthOrder = new BitfinexWebSocketAuthOrder(
123123123L,
0L, //groupId,
456456456L, //cid,
"tBTCUSD", //symbol,
1548674205259L, //mtsCreateamount
1548674205267L, //mtsUpdate
BigDecimal.ZERO, //amount
new BigDecimal("0.004"), //amountOrig
"EXCHANGE LIMIT", // type
null, //typePrev
"EXECUTED @ 3495.1(0.004): was PARTIALLY FILLED @ 3495.1(0.003)", //orderStatus
new BigDecimal("3495.2"), //price
new BigDecimal("3495.1"), //priceAvg
BigDecimal.ZERO, //priceTrailing
BigDecimal.ZERO, //priceAuxLimit
0, //placedId
0 //flags
);
LimitOrder adaptedOrder = (LimitOrder) BitfinexStreamingAdapters.adaptOrder(bitfinexWebSocketAuthOrder);
assertEquals("123123123", adaptedOrder.getId());
assertEquals(Order.OrderType.BID, adaptedOrder.getType());
assertEquals(new BigDecimal("3495.1"), adaptedOrder.getAveragePrice());
assertEquals(new BigDecimal("0.004"), adaptedOrder.getCumulativeAmount());
assertEquals(CurrencyPair.BTC_USD, adaptedOrder.getCurrencyPair());
assertEquals(new BigDecimal("3495.2"), adaptedOrder.getLimitPrice());
assertEquals(new BigDecimal("0.004"), adaptedOrder.getOriginalAmount());
assertEquals(new BigDecimal("0.000"), adaptedOrder.getRemainingAmount());
assertEquals(Collections.emptySet(), adaptedOrder.getOrderFlags());
assertEquals(OrderStatus.FILLED, adaptedOrder.getStatus());
assertEquals(new Date(1548674205259L).getTime(), adaptedOrder.getTimestamp().getTime());
}
@Test
public void testTradeBuy() {
BitfinexWebSocketAuthTrade bitfinexWebSocketAuthTrade = new BitfinexWebSocketAuthTrade(
335015622L,
"tBTCUSD", //pair
1548674247684L, //mtsCreate
21895093123L, //orderId
new BigDecimal("0.00341448"), //execAmount
new BigDecimal("3495.4"), //execPrice
"buy", //orderType
new BigDecimal("3495.9"), //orderPrice
1548674247683L, //maker
new BigDecimal("-0.00000682896"), //fee
"BTC" //feeCurrency
);
UserTrade adapted = BitfinexStreamingAdapters.adaptUserTrade(bitfinexWebSocketAuthTrade);
assertEquals(CurrencyPair.BTC_USD, adapted.getCurrencyPair());
assertEquals(new BigDecimal("-0.00000682896"), adapted.getFeeAmount());
assertEquals(CurrencyPair.BTC_USD.base, adapted.getFeeCurrency());
assertEquals("335015622", adapted.getId());
assertEquals("21895093123", adapted.getOrderId());
assertEquals(new BigDecimal("0.00341448"), adapted.getOriginalAmount());
assertEquals(new BigDecimal("3495.4"), adapted.getPrice());
assertEquals(new Date(1548674247684L).getTime(), adapted.getTimestamp().getTime());
assertEquals(OrderType.BID, adapted.getType());
}
@Test
public void testTradeSell() {
BitfinexWebSocketAuthTrade bitfinexWebSocketAuthTrade = new BitfinexWebSocketAuthTrade(
335015622L,
"tBTCUSD", //pair
1548674247684L, //mtsCreate
21895093123L, //orderId
new BigDecimal("-0.00341448"), //execAmount
new BigDecimal("3495.4"), //execPrice
"sell", //orderType
new BigDecimal("3495.9"), //orderPrice
1548674247683L, //maker
new BigDecimal("-0.00000682896"), //fee
"BTC" //feeCurrency
);
UserTrade adapted = BitfinexStreamingAdapters.adaptUserTrade(bitfinexWebSocketAuthTrade);
assertEquals(CurrencyPair.BTC_USD, adapted.getCurrencyPair());
assertEquals(new BigDecimal("0.00000682896"), adapted.getFeeAmount());
assertEquals(CurrencyPair.BTC_USD.base, adapted.getFeeCurrency());
assertEquals("335015622", adapted.getId());
assertEquals("21895093123", adapted.getOrderId());
assertEquals(new BigDecimal("0.00341448"), adapted.getOriginalAmount());
assertEquals(new BigDecimal("3495.4"), adapted.getPrice());
assertEquals(new Date(1548674247684L).getTime(), adapted.getTimestamp().getTime());
assertEquals(OrderType.ASK, adapted.getType());
}
}
|
package info.bitrich.xchangestream.kraken;
import org.junit.Assert;
import org.junit.Test;
public class KrakenStreamingServiceTest {
@Test
public void testParseOrderbookSizeReturnsDefaultOnInvalidValue() {
Assert.assertEquals(null, KrakenStreamingService.parseOrderBookSize(new Object[]{"22"}));
Assert.assertEquals((Integer)KrakenStreamingService.ORDER_BOOK_SIZE_DEFAULT, KrakenStreamingService.parseOrderBookSize(new Object[]{22}));
}
@Test
public void testParseOrderbookSizeReturnsCorrectValue() {
Assert.assertEquals(100, (int)KrakenStreamingService.parseOrderBookSize(new Object[]{100}));
}
@Test
public void testParseOrderbookSizeReturnsDefaultWhenNoArgsGiven() {
Assert.assertEquals(null,KrakenStreamingService.parseOrderBookSize(new Object[]{}));
}
}
|
package com.bricechou.weiboclient.model;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Resolving the JSON type data about current all counts list.
*
* @author BriceChou
* @datetime 16-6-16 14:49
*/
public class UserCounts {
/**
* Show the all current user counts list.
*
* @author BriceChou
* @datetime 16-6-16 10:05
*/
public String user_id;
public String followers_count;
public String friends_count;
public String statuses_count;
public static UserCounts parse(String jsonString) {
char[] jsonStringChar = jsonString.substring(0, 1).toCharArray();
char firstChar = jsonStringChar[0];
try {
if (firstChar == '{') {
JSONObject jsonObject = new JSONObject(jsonString);
return UserCounts.parse(jsonObject);
} else if (firstChar == '[') {
JSONArray jsonArray = new JSONArray(jsonString);
return UserCounts.parse(jsonArray);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
public static UserCounts parse(JSONObject jsonObject) {
if (null == jsonObject) {
return null;
}
UserCounts userCounts = new UserCounts();
userCounts.user_id = jsonObject.optString("id", "");
userCounts.followers_count = jsonObject.optString("followers_count", "");
userCounts.friends_count = jsonObject.optString("friends_count", "");
userCounts.statuses_count = jsonObject.optString("statuses_count", "");
return userCounts;
}
public static UserCounts parse(JSONArray jsonArray) {
if (null == jsonArray) {
return null;
}
UserCounts userCounts = new UserCounts();
try {
userCounts = UserCounts.parse(jsonArray.getJSONObject(0));
} catch (JSONException e) {
e.printStackTrace();
}
return userCounts;
}
}
|
package org.xwiki.job.internal;
import java.util.Arrays;
import org.junit.jupiter.api.Test;
import org.xwiki.component.internal.ContextComponentManagerProvider;
import org.xwiki.job.DefaultRequest;
import org.xwiki.job.Job;
import org.xwiki.job.JobGroupPath;
import org.xwiki.job.event.status.JobStatus.State;
import org.xwiki.job.test.TestBasicGroupedJob;
import org.xwiki.test.annotation.ComponentList;
import org.xwiki.test.junit5.mockito.ComponentTest;
import org.xwiki.test.junit5.mockito.InjectMockComponents;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.fail;
/**
* Validate {@link DefaultJobExecutor};
*
* @version $Id$
*/
@ComponentTest
@ComponentList(ContextComponentManagerProvider.class)
public class DefaultJobExecutorTest
{
@InjectMockComponents
private DefaultJobExecutor executor;
private void waitJobWaiting(Job job)
{
waitJobState(State.WAITING, job);
}
private void waitJobFinished(Job job)
{
waitJobState(State.FINISHED, job);
}
private void waitJobState(State expected, Job job)
{
int wait = 0;
do {
if (expected == job.getStatus().getState()) {
return;
}
// Wait a bit
try {
Thread.sleep(1);
} catch (InterruptedException e) {
fail("Job state monitor has been interrupted");
}
wait += 1;
} while (wait < 100);
fail("Job never reached expected state [" + expected + "]. Still [" + job.getStatus().getState()
+ "] after 100 milliseconds");
}
@Test
public void matchingGroupPathAreBlocked()
{
TestBasicGroupedJob jobA = groupedJob("A");
TestBasicGroupedJob jobAB = groupedJob("A", "B");
TestBasicGroupedJob job12 = groupedJob("1", "2");
TestBasicGroupedJob job1 = groupedJob("1");
// Pre-lock all jobs
jobA.lock();
jobAB.lock();
job12.lock();
job1.lock();
// Give first jobs to JobExecutor
this.executor.execute(jobA);
this.executor.execute(job12);
// Give enough time for the jobs to be fully taken into account
waitJobWaiting(jobA);
waitJobWaiting(job12);
// Give following jobs to JobExecutor (to make sure they are actually after since the grouped job executor queue
// is not "fair")
this.executor.execute(jobAB);
this.executor.execute(job1);
// A and A/B
assertSame(State.WAITING, jobA.getStatus().getState());
assertNull(jobAB.getStatus().getState());
// Next job
jobA.unlock();
waitJobWaiting(jobAB);
assertSame(State.FINISHED, jobA.getStatus().getState());
assertSame(State.WAITING, jobAB.getStatus().getState());
// Next job
jobAB.unlock();
waitJobFinished(jobAB);
assertSame(State.FINISHED, jobA.getStatus().getState());
assertSame(State.FINISHED, jobAB.getStatus().getState());
// 1/2 and 1
assertSame(State.WAITING, job12.getStatus().getState());
assertNull(job1.getStatus().getState());
// Next job
job12.unlock();
waitJobWaiting(job1);
assertSame(State.FINISHED, job12.getStatus().getState());
assertSame(State.WAITING, job1.getStatus().getState());
// Next job
job1.unlock();
waitJobFinished(job1);
assertSame(State.FINISHED, job1.getStatus().getState());
assertSame(State.FINISHED, job1.getStatus().getState());
}
private TestBasicGroupedJob groupedJob(String... path)
{
return new TestBasicGroupedJob("type", new JobGroupPath(Arrays.asList(path)), new DefaultRequest());
}
}
|
package com.example.alonsiwek.demomap;
import android.content.pm.PackageManager;
import android.location.Location;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.places.Places;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.OnConnectionFailedListener, GoogleApiClient.ConnectionCallbacks,
LocationListener {
private GoogleMap mMap;
private GoogleApiClient mGoogleApiClient;
private boolean mLocationPermissionGranted;
private final int PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 1;
private Object mCurrentLocation;
private LocationRequest mLocationRequest;
private long UPDATE_INTERVAL_IN_MILLISECONDS = 5000;
private long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS = 5000;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
buildGoogleApiClient(); //connecting google api for my currrnt location
mGoogleApiClient.connect();
}
private synchronized void buildGoogleApiClient() {
// this function build the google api
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this /* FragmentActivity */,
this /* OnConnectionFailedListener */)
.addConnectionCallbacks(this)
.addApi(LocationServices.API)
.addApi(Places.GEO_DATA_API)
.addApi(Places.PLACE_DETECTION_API)
.build();
createLocationRequest();
}
private void getDeviceLocation() {
if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
android.Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mLocationPermissionGranted = true;
} else {
ActivityCompat.requestPermissions(this,
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
}
// A step later in the tutorial adds the code to get the device
// location.
}
@Override
public void onRequestPermissionsResult(int requestCode,
@NonNull String permissions[],
@NonNull int[] grantResults) {
mLocationPermissionGranted = false;
switch (requestCode) {
case PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
mLocationPermissionGranted = true;
}
}
}
updateLocationUI();
}
private void updateLocationUI() {
if (mMap == null) {
return;
}
if (mLocationPermissionGranted) {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat
// int[] grantResults)
// for ActivityCompat
return;
}
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(true);
} else {
mMap.setMyLocationEnabled(false);
mMap.getUiSettings().setMyLocationButtonEnabled(false);
mCurrentLocation = null;
}
}
private void createLocationRequest() {
mLocationRequest = new LocationRequest();
/*
* Sets the desired interval for active location updates. This interval is
* inexact. You may not receive updates at all if no location sources are available, or
* you may receive them slower than requested. You may also receive updates faster than
* requested if other applications are requesting location at a faster interval.
*/
mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
/*
* Sets the fastest rate for active location updates. This interval is exact, and your
* application will never receive updates faster than this value.
*/
mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
// private void getDeviceLocation() {
// mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
// LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,
// mLocationRequest, this);
// } else {
// return;
@Override
public void onLocationChanged(Location location) {
mCurrentLocation = location;
updateMarkers();
}
private void updateMarkers() {
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
//Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
// @Override
// public void onMapReady(GoogleMap map) {
// mMap = map;
// // Do other setup activities here too.
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}
@Override
public void onConnected(Bundle connectionHint) {
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
@Override
public void onConnectionSuspended(int i) {
}
}
|
package com.example.android.sunshine;
import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.XmlResourceParser;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.DrawableContainer;
import android.graphics.drawable.GradientDrawable;
import android.media.Image;
import android.support.annotation.IntRange;
import android.support.annotation.InterpolatorRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.Layout;
import android.transition.Fade;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.AnimationUtils;
import android.view.animation.Interpolator;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import com.example.android.sunshine.utilities.SunshineDateUtils;
public class ImageAnimator {
// private Context mContext;
private ImageView mBackground;
private ImageView mForeground;
private View includeBackground;
private static final int VIEW_DAYTIME_ANIMATION = 2;
private static int PREVIOUS_STATE;
private static final int DAY_TIME = 1;
private static final int SUNSET_TIME = 2;
private static final int NIGHT_TIME = 3;
private static final int OVERCAST_TIME = 4;
private GradientDrawable clear_day_gradient = new GradientDrawable(
GradientDrawable.Orientation.BL_TR,
new int[]{0xFF8deefc, 0xFF1b4297});
private GradientDrawable overcast_day_gradient = new GradientDrawable(
GradientDrawable.Orientation.BL_TR,
new int[]{0xFF5f7286, 0xFF333a4b});
// private GradientDrawable sunset_gradient = new GradientDrawable(
// GradientDrawable.Orientation.BL_TR,
// new int[]{0xFFdaca78, 0xFFff9700});
private GradientDrawable night_gradient = new GradientDrawable(
GradientDrawable.Orientation.BL_TR,
new int[]{0xFF000000, 0xFF0E2351});
private ImageView starView;
private ImageView starView2;
public ImageAnimator(Context context, View includeBackground) {
this.includeBackground = includeBackground;
// mContext = context.getApplicationContext();
mBackground = (ImageView) includeBackground.findViewById(R.id.cloudView);
mForeground = (ImageView) includeBackground.findViewById(R.id.cloudView2);
starView = (ImageView) includeBackground.findViewById(R.id.starView);
starView2 = (ImageView) includeBackground.findViewById(R.id.starView2);
}
public void playAnimation(String weatherId, long date) {
// View view = LayoutInflater.from(mContext).inflate(R.layout.background_clouds, null);
// view.setBackground(mContext.getDrawable(R.drawable.gradient_background_clear));
int TIME = 0;
int dayTime = Integer.valueOf(SunshineDateUtils.getHourlyDetailDate(date, VIEW_DAYTIME_ANIMATION));
Log.e("DAYTIME", "hours of day " + dayTime);
if (dayTime >= 06 && dayTime < 17) {
TIME = DAY_TIME;
// } else if (dayTime >= 18 && dayTime <= 19) {
// TIME = SUNSET_TIME;
} else {
TIME = NIGHT_TIME;
}
if (PREVIOUS_STATE == TIME) {
return;
}
switch (TIME) {
case DAY_TIME:
includeBackground.setBackground(clear_day_gradient);
break;
// case SUNSET_TIME:
// includeBackground.setBackground(sunset_gradient);
// break;
case NIGHT_TIME:
includeBackground.setBackground(night_gradient);
break;
case OVERCAST_TIME:
includeBackground.setBackground(overcast_day_gradient);
break;
default:
includeBackground.setBackground(clear_day_gradient);
}
PREVIOUS_STATE = TIME;
includeBackground.setVisibility(View.VISIBLE);
starView.setVisibility(View.GONE);
starView2.setVisibility(View.GONE);
mForeground.setColorFilter(0);
mBackground.setColorFilter(0);
TranslateAnimation animation = new TranslateAnimation(1200.0f, -1200.0f,
0.0f, 0.0f); // new TranslateAnimation(xFrom,xTo, yFrom,yTo)
animation.setDuration(90000); // animation duration
animation.setRepeatCount(ValueAnimator.INFINITE); // animation repeat count
animation.setRepeatMode(1); // repeat animation (left to right, right to left )
animation.setInterpolator(new LinearInterpolator());
mBackground.startAnimation(animation); // start animation
TranslateAnimation foregroundanimation1 = new TranslateAnimation(900.0f, -1800.0f, 0.0f, 0.0f);//(xFrom,xTo, yFrom,yTo)
foregroundanimation1.setDuration(30000); // animation duration
foregroundanimation1.setRepeatCount(ValueAnimator.INFINITE); // animation repeat count
foregroundanimation1.setRepeatMode(1); // repeat animation (left to right, right to left )
foregroundanimation1.setInterpolator(new LinearInterpolator());
TranslateAnimation foregroundanimation2 = new TranslateAnimation(1800.0f, -1800.0f, 0.0f, 0.0f);//(xFrom,xTo, yFrom,yTo)
foregroundanimation2.setStartOffset(30000);
foregroundanimation2.setDuration(60000); // animation duration
foregroundanimation2.setRepeatCount(ValueAnimator.INFINITE); // animation repeat count
foregroundanimation2.setRepeatMode(1); // repeat animation (left to right, right to left )
foregroundanimation2.setInterpolator(new LinearInterpolator());
AnimationSet fgAs = new AnimationSet(true);
fgAs.addAnimation(foregroundanimation1);
fgAs.addAnimation(foregroundanimation2);
mForeground.startAnimation(fgAs); // start animation
if (TIME == NIGHT_TIME) {
starView.setVisibility(View.VISIBLE);
starView2.setVisibility(View.VISIBLE);
mForeground.setColorFilter(0xFF646E84);
mBackground.setColorFilter(0xFF646E84);
RotateAnimation rotateAnimation1 = new RotateAnimation(0, 360, Animation.RELATIVE_TO_PARENT, 0.5f, Animation.RELATIVE_TO_PARENT, 0.5f);
rotateAnimation1.setInterpolator(new LinearInterpolator());
rotateAnimation1.setRepeatMode(Animation.RESTART);
rotateAnimation1.setRepeatCount(Animation.INFINITE);
rotateAnimation1.setDuration(200000);
RotateAnimation rotateAnimation2 = new RotateAnimation(0, 360, Animation.RELATIVE_TO_PARENT, 0.5f, Animation.RELATIVE_TO_PARENT, 0.5f);
rotateAnimation2.setInterpolator(new LinearInterpolator());
rotateAnimation2.setRepeatMode(Animation.RESTART);
rotateAnimation2.setRepeatCount(Animation.INFINITE);
rotateAnimation2.setDuration(300000);
AlphaAnimation alphaAnimation1 = new AlphaAnimation(0.6f, 0.7f);
alphaAnimation1.setRepeatMode(Animation.REVERSE);
alphaAnimation1.setRepeatCount(Animation.INFINITE);
alphaAnimation1.setDuration(25);
AlphaAnimation alphaAnimation2 = new AlphaAnimation(0.5f, 0.7f);
alphaAnimation2.setRepeatMode(Animation.REVERSE);
alphaAnimation2.setRepeatCount(Animation.INFINITE);
alphaAnimation2.setDuration(75);
AnimationSet set = new AnimationSet(false);
set.addAnimation(rotateAnimation1);
set.addAnimation(alphaAnimation1);
starView.startAnimation(set);
AnimationSet set2 = new AnimationSet(false);
set2.addAnimation(rotateAnimation2);
set2.addAnimation(alphaAnimation2);
starView2.startAnimation(set2);
} else {
starView.clearAnimation();
starView2.clearAnimation();
starView.setVisibility(View.GONE);
starView2.setVisibility(View.GONE);
}
}
}
|
package com.hubspot.baragon.service.edgecache.cloudflare;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.inject.Inject;
import com.hubspot.baragon.models.BaragonRequest;
import com.hubspot.baragon.service.config.EdgeCacheConfiguration;
import com.hubspot.baragon.service.edgecache.EdgeCache;
import com.hubspot.baragon.service.edgecache.cloudflare.client.CloudflareClient;
import com.hubspot.baragon.service.edgecache.cloudflare.client.CloudflareClientException;
import com.hubspot.baragon.service.edgecache.cloudflare.client.models.CloudflareDnsRecord;
import com.hubspot.baragon.service.edgecache.cloudflare.client.models.CloudflareZone;
public class CloudflareEdgeCache implements EdgeCache {
private static final Logger LOG = LoggerFactory.getLogger(CloudflareEdgeCache.class);
private final CloudflareClient cf;
private final EdgeCacheConfiguration edgeCacheConfiguration;
@Inject
public CloudflareEdgeCache(CloudflareClient cf, EdgeCacheConfiguration edgeCacheConfiguration) {
this.cf = cf;
this.edgeCacheConfiguration = edgeCacheConfiguration;
}
/**
* Invalidation will eventually occur when the TTL expires, so it's not a showstopper if this fails.
*/
@Override
public boolean invalidateIfNecessary(BaragonRequest request) {
if (request.getLoadBalancerService().getEdgeCacheDomains().isEmpty()) {
return false;
}
try {
boolean allSucceeded = true;
for (String edgeCacheDNS : request.getLoadBalancerService().getEdgeCacheDomains()) {
List<CloudflareZone> matchingZones = getCloudflareZone(edgeCacheDNS);
if (matchingZones == null || matchingZones.isEmpty()) {
LOG.warn("`edgeCacheDNS` was defined on the request, but no matching Cloudflare Zone was found!");
return false;
}
for (CloudflareZone matchingZone : matchingZones) {
String zoneId = matchingZone.getId();
Optional<CloudflareDnsRecord> matchingDnsRecord = getCloudflareDnsRecord(edgeCacheDNS, zoneId);
if (!matchingDnsRecord.isPresent()) {
LOG.warn("`edgeCacheDNS` was defined on the request, but no matching Cloudflare DNS Record was found!");
return false;
}
if (!matchingDnsRecord.get().isProxied()) {
LOG.warn("`edgeCacheDNS` was defined on the request, but {} is not a proxied DNS record!", edgeCacheDNS);
return false;
}
String cacheTag = String.format(
edgeCacheConfiguration.getIntegrationSettings().get("cacheTagFormat"),
request.getLoadBalancerService().getServiceId()
);
LOG.debug("Sending cache purge request against {} for {} to Cloudflare...", matchingDnsRecord.get().getName(), cacheTag);
allSucceeded = cf.purgeEdgeCache(zoneId, Collections.singletonList(cacheTag)) && allSucceeded;
}
}
return allSucceeded;
} catch (CloudflareClientException e) {
LOG.error("Unable to invalidate Cloudflare cache for request {}", request, e);
return false;
}
}
private Optional<CloudflareDnsRecord> getCloudflareDnsRecord(String edgeCacheDNS, String zoneId) throws CloudflareClientException {
return Optional.ofNullable(cf.getDnsRecord(zoneId, edgeCacheDNS));
}
private List<CloudflareZone> getCloudflareZone(String edgeCacheDNS) throws CloudflareClientException {
String baseDomain = getBaseDomain(edgeCacheDNS);
return cf.getZone(baseDomain);
}
private String getBaseDomain(String dns) {
String[] domainTokens = dns.split("\\.");
return String.format("%s.%s", domainTokens[domainTokens.length - 2], domainTokens[domainTokens.length - 1]);
}
}
|
package com.iuridiniz.checkmyecg;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.widget.ShareActionProvider;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.TextView;
import com.iuridiniz.checkmyecg.filter.GraphFilter2;
import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.OpenCVLoader;
import org.opencv.android.Utils;
import org.opencv.calib3d.Calib3d;
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfDMatch;
import org.opencv.core.MatOfKeyPoint;
import org.opencv.core.MatOfPoint;
import org.opencv.core.MatOfPoint2f;
import org.opencv.core.Point;
import org.opencv.features2d.DMatch;
import org.opencv.features2d.DescriptorExtractor;
import org.opencv.features2d.DescriptorMatcher;
import org.opencv.features2d.FeatureDetector;
import org.opencv.features2d.KeyPoint;
import org.opencv.highgui.Highgui;
import org.opencv.imgproc.Imgproc;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Vector;
public class ResultEkgActivity extends ActionBarActivity {
public static final String EXTRA_PHOTO_URI =
"com.iuridiniz.checkmyecg.ResultEkgActivity.extra.PHOTO_URI;";
public static final String EXTRA_PHOTO_DATA_PATH =
"com.iuridiniz.checkmyecg.ResultEkgActivity.extra.DATA_PATH;";
static final String TAG = "ResultEkg";
private ShareActionProvider mShareActionProvider;
private Uri mImageUri;
private String mImageDataPath;
private ImageView mImageContent;
private TextView mTextContent;
private boolean mOpenCvLoaded = false;
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result_ekg);
final Intent intent = getIntent();
mImageUri = intent.getParcelableExtra(EXTRA_PHOTO_URI);
mImageDataPath = intent.getStringExtra(EXTRA_PHOTO_DATA_PATH);
mImageContent = (ImageView) findViewById(R.id.result_image);
mTextContent = (TextView) findViewById(R.id.result_text);
mTextContent.setText("");
/* init openCV */
if (OpenCVLoader.initDebug()) {
Log.i(TAG, "OpenCV loaded successfully (static initialization)");
mOpenCvLoaded = true;
onReady(savedInstanceState);
return;
}
/* binaries not included, use OpenCV manager */
Log.i(TAG, "OpenCV libs not included on APK, trying async initialization");
OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_10, this, new BaseLoaderCallback(this) {
@Override
public void onManagerConnected(int status) {
switch (status) {
case BaseLoaderCallback.SUCCESS:
Log.i(TAG, "OpenCV loaded successfully (async initialization)");
runOnUiThread(new Runnable() {
@Override
public void run() {
mOpenCvLoaded = true;
onReady(savedInstanceState);
}
});
break;
default:
super.onManagerConnected(status);
break;
}
}
});
}
private void onReady(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.pick_derivation)
.setItems(R.array.derivations_array, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, final int which) {
// The 'which' argument contains the index position
// of the selected item
runOnUiThread(new Runnable() {
@Override
public void run() {
ResultEkgActivity.this.compareWithDerivation(which);
}
});
}
})
.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
ResultEkgActivity.this.finish();
}
});
Dialog d = builder.create();
d.show();
}
private void compareWithDerivation(int derivationIndex) {
String[] derivations = getResources().getStringArray(R.array.derivations_array);
String derivation = derivations[derivationIndex];
Log.i(TAG, String.format("Comparing the ekg derivation '%s' with pathological base", derivation));
//mImageContent.setImageURI(mImageUri);
//mTextContent.setText(R.string.text_ekg_fail);
PathologicalDescriptor query = new PathologicalDescriptor();
query.describe(mImageDataPath);
//PathologicalDescriptor base = new PathologicalDescriptor("Normal");
//try {
// base.describe(Utils.loadResource(this, R.drawable.test, Highgui.CV_LOAD_IMAGE_GRAYSCALE));
//} catch (IOException e) {
// e.printStackTrace();
// finish();
PathologicalMatcher matcher = null;
{
//DataBaseHelper db = new DataBaseHelper(this);
DbAdapter db = new DbAdapter(this);
db.initializeDatabase();
db.open();
matcher = db.getMatcher(derivation);
db.close();
} //catch (IOException e) {
//e.printStackTrace();
//Log.d(TAG, "Error while opening database", e);
//matcher.append(base);
List<PathologicalResult> search = matcher.search(query);
for (PathologicalResult r: search) {
Log.d(TAG, String.format("%s: %f", r.getText(), r.getScore()));
}
mImageContent.setImageURI(mImageUri);
if (search.size() < 1) {
mTextContent.setText(R.string.text_ekg_fail);
} else {
PathologicalResult best_result = search.get(0);
if (best_result.getScore() < 0.5) {
mTextContent.setText(R.string.text_ekg_fail);
} else {
mTextContent.setText(best_result.getText());
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_result_ekg, menu);
// Set up ShareActionProvider's default share intent
MenuItem shareItem = menu.findItem(R.id.action_share);
mShareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(shareItem);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, mTextContent.getText());
mShareActionProvider.setShareIntent(intent);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
return super.onOptionsItemSelected(item);
}
}
class PathologicalResult implements Comparable<PathologicalResult> {
private Double mScore = -1.0;
private String mText = "";
public PathologicalResult(String text, double score) {
this.mText = text;
this.mScore = score;
}
@Override
public int compareTo(PathologicalResult another) {
return this.mScore.compareTo(another.mScore);
}
public Double getScore() {
return mScore;
}
public String getText() {
return mText;
}
}
class PathologicalDescriptor {
private final DescriptorExtractor mDescriptorExtractor;
private final FeatureDetector mFeatureDetector;
private GraphFilter2 graph = null;
private final String mText;
private MatOfKeyPoint mKeyPoints;
private Mat mDescriptors;
public PathologicalDescriptor(String text, int detectorType, int extractorType) {
mText = text;
mFeatureDetector = FeatureDetector.create(detectorType);
mDescriptorExtractor = DescriptorExtractor.create(extractorType);
mKeyPoints = new MatOfKeyPoint();
mDescriptors = new Mat();
}
public PathologicalDescriptor() {
this("");
}
public PathologicalDescriptor(String text) {
this(text, FeatureDetector.STAR, DescriptorExtractor.FREAK);
}
public PathologicalDescriptor describe(String imagePath) {
Mat imageGray = Highgui.imread(imagePath, Highgui.CV_LOAD_IMAGE_GRAYSCALE);
return describe(imageGray);
}
public PathologicalDescriptor describe(Mat imageGray) {
mFeatureDetector.detect(imageGray, mKeyPoints);
mDescriptorExtractor.compute(imageGray, mKeyPoints, mDescriptors);
Mat rgba = new Mat();
Imgproc.cvtColor(imageGray, rgba, Imgproc.COLOR_GRAY2RGBA);
graph = new GraphFilter2(rgba.rows(), rgba.cols());
graph.apply(rgba);
return this;
}
public List<MatOfPoint> getContours(Integer max, Boolean sortIt) {
if (graph == null) {
return null;
}
if (sortIt == null) {
return graph.getContours(max);
}
if (max == null) {
return graph.getContours();
}
return graph.getContours(max, sortIt);
}
public List<MatOfPoint> getContours(int max) {
return getContours(max, null);
}
public List<MatOfPoint> getContours() {
return getContours(null, null);
}
public Mat getDescriptors() {
return mDescriptors;
}
public MatOfKeyPoint getKeyPoints() {
return mKeyPoints;
}
public String getText() {
return mText;
}
}
class PathologicalMatcher {
private Vector<PathologicalDescriptor> mBase;
public PathologicalMatcher() {
mBase = new Vector<PathologicalDescriptor>();
}
public void append(PathologicalDescriptor b) {
mBase.add(b);
}
private double match(PathologicalDescriptor query, PathologicalDescriptor base) {
return match(query.getKeyPoints().toList(), query.getDescriptors(),
base.getKeyPoints().toList(), base.getDescriptors(), 0.7, 50);
}
private double match2(PathologicalDescriptor query, PathologicalDescriptor base) {
return match2(query.getKeyPoints().toList(), query.getDescriptors(),
base.getKeyPoints().toList(), base.getDescriptors());
}
private double matchContours(PathologicalDescriptor query, PathologicalDescriptor base) {
List<MatOfPoint> queryContours = query.getContours(10);
List<MatOfPoint> baseContours = base.getContours(10);
int matchs_close = 0;
int matchs = 0;
int matchs_far = 0;
double sum = 0.0;
double sum_close = 0.0;
int size = 0;
for (int i = 0; i < queryContours.size(); i++) {
for (int j = 0; j < baseContours.size(); j++) {
double score = Imgproc.matchShapes(queryContours.get(i), baseContours.get(j),
Imgproc.CV_CONTOURS_MATCH_I1, 0);
//Log.d(ResultEkgActivity.TAG, String.format("[%d,%d]Score: %f", i, j, score));
if (score <= 0.0) {
matchs++;
} else if (score > 0.0 && score < 1.0) {
matchs_close++;
sum_close += score;
} else if (score > 10.0) {
matchs_far++;
}
size++;
sum += score;
}
}
double mean = -1.0;
double score = -1.0;
double mean_close = -1.0;
if (size > 0) {
mean = sum / size;
score = ((double)matchs_close) / size;
if (matchs_close > 0) {
mean_close = sum_close / matchs_close;
}
/* has equals? impossible: penalty 5% for each, max: 50%*/
score = score * (1 - (0.05 * (matchs<10?matchs:10)));
/* mean elevated */
score = score * (mean < 10 ? 1.0 : 0.5);
}
Log.d(ResultEkgActivity.TAG,
String.format("Size: %d, Matchs: %d, close: %d, far: %d, Mean %f, close: %f, score: %f",
size, matchs, matchs_close, matchs_far, mean, mean_close, score));
return score;
}
public List<PathologicalResult> search(PathologicalDescriptor query) {
Vector<PathologicalResult> result = new Vector<PathologicalResult>();
for (PathologicalDescriptor pathology: mBase) {
double score = matchContours(query, pathology);
result.add(new PathologicalResult(pathology.getText(), score));
}
Collections.sort(result);
Collections.reverse(result);
return result;
}
private double match2(List<KeyPoint> keyPointsQuery, Mat descriptionsQuery,
List<KeyPoint> keyPointsBase, Mat descriptionsBase) {
DescriptorMatcher descriptorMatcher =
DescriptorMatcher.create(DescriptorMatcher.BRUTEFORCE_HAMMING);
MatOfDMatch matches = new MatOfDMatch();
descriptorMatcher.match(descriptionsQuery, descriptionsBase, matches);
List<DMatch> matchesList = matches.toList();
if (matchesList.size() < 4) {
return -1.0;
}
double maxDist = 0.0;
double minDist = Double.MAX_VALUE;
/* calculate distances */
for (DMatch match: matchesList) {
double dist = match.distance;
if (dist < minDist) {
minDist = dist;
}
if (dist > maxDist) {
maxDist = dist;
}
}
if (minDist > 25.0) {
return -1.0;
}
/* good points */
ArrayList<Point> goodQueryPointsList = new ArrayList<Point>();
ArrayList<Point> goodBasePointsList = new ArrayList<Point>();
double maxGoodMatch = 1.75 * minDist;
for (DMatch match: matchesList) {
if (match.distance < maxGoodMatch) {
goodQueryPointsList.add(keyPointsQuery.get(match.queryIdx).pt);
goodBasePointsList.add(keyPointsBase.get(match.trainIdx).pt);
}
}
if (goodQueryPointsList.size() < 4 || goodBasePointsList.size() < 4) {
return -1.0;
}
MatOfPoint2f queryPoints = new MatOfPoint2f();
queryPoints.fromList(goodQueryPointsList);
MatOfPoint2f basePoints = new MatOfPoint2f();
basePoints.fromList(goodBasePointsList);
Mat status = new Mat();
Calib3d.findHomography(basePoints, queryPoints, Calib3d.RANSAC, 4.0, status);
return Core.sumElems(status).val[0]/status.total();
}
private double match(List<KeyPoint> keyPointsQuery, Mat descriptionsQuery,
List<KeyPoint> keyPointsBase, Mat descriptionsBase,
double ratio, int minMatches) {
DescriptorMatcher descriptorMatcher =
DescriptorMatcher.create(DescriptorMatcher.BRUTEFORCE_HAMMING);
Vector<MatOfDMatch> rawMatches = new Vector<MatOfDMatch>();
Vector<Point> matchesQueryPoints = new Vector<Point>();
Vector<Point> matchesTrainPoints = new Vector<Point>();
//descriptorMatcher.knnMatch(descriptionsBase, descriptionsQuery, rawMatches, 2);
for (MatOfDMatch m: rawMatches) {
List<DMatch> l = m.toList();
if (l.size() == 2 && l.get(0).distance < l.get(1).distance * ratio) {
// ptsA
matchesQueryPoints.add(keyPointsQuery.get(l.get(0).trainIdx).pt);
// ptsB
matchesTrainPoints.add(keyPointsBase.get(l.get(0).queryIdx).pt);
}
}
if (matchesQueryPoints.size() > minMatches) {
MatOfPoint2f ptsQuery = new MatOfPoint2f();
ptsQuery.fromList(matchesQueryPoints);
MatOfPoint2f ptsTrain = new MatOfPoint2f();
ptsQuery.fromList(matchesTrainPoints);
Mat status = new Mat();
Calib3d.findHomography(ptsQuery, ptsTrain, Calib3d.RANSAC, 4.0, status);
return Core.sumElems(status).val[0]/status.total();
}
return -1.0;
}
}
class DbAdapter extends SQLiteOpenHelper {
private String DATABASE_PATH = "/data/data/YOUR_PACKAGE/";
public static final String DATABASE_NAME = "pathological.db";
private SQLiteDatabase mDb;
private final Context mContext;
private boolean mCreateDatabase = false;
private boolean mUpgradeDatabase = false;
/**
* Constructor
* Takes and keeps a reference of the passed context in order to access
* the application's assets and resources
* @param context
*/
public DbAdapter(Context context) {
super(context, DATABASE_NAME, null, 1);
mContext = context;
}
public void initializeDatabase() {
DATABASE_PATH = mContext.getApplicationInfo().dataDir +"/databases/";
getWritableDatabase();
if(mUpgradeDatabase) {
mContext.deleteDatabase(DATABASE_NAME);
}
if(mCreateDatabase || mUpgradeDatabase) {
try {
copyDatabase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
private void copyDatabase() throws IOException {
close();
InputStream input = mContext.getAssets().open(DATABASE_NAME);
String outFileName = DATABASE_PATH + DATABASE_NAME;
OutputStream output = new FileOutputStream(outFileName);
// Transfer bytes from the input file to the output file
byte[] buffer = new byte[1024];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
output.flush();
output.close();
input.close();
getWritableDatabase().close();
}
public DbAdapter open() throws SQLException {
mDb = getReadableDatabase();
return this;
}
public void CleanUp() {
mDb.close();
}
@Override
public void onCreate(SQLiteDatabase db) {
mCreateDatabase = true;
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
mUpgradeDatabase = true;
}
/**
* Public helper methods
*/
public PathologicalMatcher getMatcher(String derivation) {
PathologicalMatcher matcher = new PathologicalMatcher();
/* support locales */
String lang = mContext.getResources().getConfiguration().locale.getLanguage();
String column_desc = "description";
if (lang.compareTo("pt") == 0) {
column_desc = "description_pt";
} else if (lang.compareTo("es") == 0) {
column_desc = "description_es";
}
Cursor c = mDb.rawQuery(String.format("SELECT %s,image FROM pathology WHERE derivation = ?", column_desc),
new String[] { derivation });
if (c == null) {
return matcher;
}
while (c.moveToNext()) {
String desc = c.getString(0);
byte[] blob = c.getBlob(1);
/* save to file */
try
{
File outputDir = mContext.getCacheDir(); // context being the Activity pointer
File blobFile = File.createTempFile("temp", ".png", outputDir);
FileOutputStream outStream = new FileOutputStream(blobFile);
InputStream inStream = new ByteArrayInputStream(blob);
int length = -1;
int size = blob.length;
byte[] buffer = new byte[size];
while ((length = inStream.read(buffer)) != -1)
{
outStream.write(buffer, 0, length);
outStream.flush();
}
inStream.close();
outStream.close();
PathologicalDescriptor patho = new PathologicalDescriptor(desc);
patho.describe(blobFile.getAbsolutePath());
matcher.append(patho);
}
catch (Exception e)
{
Log.d(ResultEkgActivity.TAG, "Error while opening database", e);
}
finally
{
}
};
return matcher;
}
}
|
package com.shyamu.translocwidget;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.appwidget.AppWidgetManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.RemoteViews;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.shyamu.translocwidget.TransLocJSON.TransLocAgencies;
import com.shyamu.translocwidget.TransLocJSON.TransLocAgency;
import com.shyamu.translocwidget.TransLocJSON.TransLocArrival;
import com.shyamu.translocwidget.TransLocJSON.TransLocArrivalEstimate;
import com.shyamu.translocwidget.TransLocJSON.TransLocArrivalEstimates;
import com.shyamu.translocwidget.TransLocJSON.TransLocRoute;
import com.shyamu.translocwidget.TransLocJSON.TransLocStop;
import com.shyamu.translocwidget.TransLocJSON.TransLocStops;
import org.joda.time.DateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;
import static android.widget.AdapterView.OnItemSelectedListener;
public class WidgetConfigurationActivity extends Activity {
private static final String AGENCIES_URL = "https://transloc-api-1-2.p.mashape.com/agencies.json";
private static final String ROUTES_URL = "https://transloc-api-1-2.p.mashape.com/routes.json?agencies=";
private static final String STOPS_URL = "https://transloc-api-1-2.p.mashape.com/stops.json?agencies=";
private static final String ARRIVALS_URL = "https://transloc-api-1-2.p.mashape.com/arrival-estimates.json?agencies=";
private static final String TAG = "ConfigActivity";
static SharedPreferences settings;
static SharedPreferences.Editor editor;
private ArrayList<TransLocStop> fullStopList = new ArrayList<TransLocStop>();
private int currentAgencyId;
private int currentRouteId;
private int currentStopId;
private String routeShortName;
private String routeLongName;
private String stopName;
private int mAppWidgetId = 0;
ProgressDialog dialog = null;
RelativeLayout rlPreview;
Button sSelectAgency, sSelectRoute, sSelectStop;
Button bReset, bMakeWidget;
TextView tvHelpMessage;
TextView tvRoutePreview, tvRemainingTimePreview, tvStopPreview, tvMinsPreview;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.v(TAG, "in onCreate");
setContentView(R.layout.activity_configuration);
// references to elements
sSelectAgency = (Button) findViewById(R.id.sSelectAgency);
sSelectRoute = (Button) findViewById(R.id.sSelectRoute);
sSelectStop = (Button) findViewById(R.id.sSelectStop);
bReset = (Button) findViewById(R.id.bReset);
bMakeWidget = (Button) findViewById(R.id.bMakeWidget);
tvHelpMessage = (TextView) findViewById(R.id.tvHelp);
// preview elements
rlPreview = (RelativeLayout) findViewById(R.id.rlPreview);
tvMinsPreview = (TextView) findViewById(R.id.tvMins_preview);
tvRemainingTimePreview = (TextView) findViewById(R.id.tvRemainingTime_preview);
tvRoutePreview = (TextView) findViewById(R.id.tvRoute_preview);
tvStopPreview = (TextView) findViewById(R.id.tvStop_preview);
settings = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
editor = settings.edit();
// Set result initially as cancelled in case user cancels configuration
setResult(RESULT_CANCELED);
// show warning dialog if weekend or outside business hours
DateTime currentTime = new DateTime(System.currentTimeMillis());
// day of of week 6 and 7 = Saturday and Sunday
Log.v(TAG,"day= " + currentTime.getDayOfWeek());
Log.v(TAG,"hour= " + currentTime.getHourOfDay());
if(currentTime.getDayOfWeek() > 5 || currentTime.getHourOfDay() > 18 || currentTime.getHourOfDay() < 6) {
Log.v(TAG,"true");
// show warning dialog
Utils.showAlertDialog(WidgetConfigurationActivity.this,"Warning", "Based on the current time and day of week, many routes may not be running at this time. You can continue to try and make a widget but be advised you may get better results during normal business hours.");
}
// Populate agency spinner
new PopulateAgenciesTask().execute();
// Defining a click event listener for the button "Reset"
OnClickListener setResetClickedListener = new OnClickListener() {
@Override
public void onClick(View v) {
doReset(0);
}
};
// Defining a click event listener for the button "Make Widget"
OnClickListener setMakeWidgetClickedListener = new OnClickListener() {
@Override
public void onClick(View v) {
doMakeWidget();
}
};
// On click listener for help text
OnClickListener setHelpClickedListener = new OnClickListener() {
@Override
public void onClick(View view) {
Utils.showAlertDialog(WidgetConfigurationActivity.this, "Why can't I find my agency?", getString(R.string.help_dialog));
}
};
// On click listener for preview layout
OnClickListener setPreviewClickedListener = new OnClickListener() {
@Override
public void onClick(View view) {
// launch customization activity
Intent intent = new Intent(WidgetConfigurationActivity.this, CustomizeWidgetActivity.class);
intent.putExtra("widgetId",mAppWidgetId);
startActivity(intent);
}
};
// Get widgetId from appwidgetmanager
Intent intent = getIntent();
Bundle extras = intent.getExtras();
if (extras != null) {
mAppWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID,
AppWidgetManager.INVALID_APPWIDGET_ID);
}
// Set the click listeners on the buttons
bReset.setOnClickListener(setResetClickedListener);
bMakeWidget.setOnClickListener(setMakeWidgetClickedListener);
tvHelpMessage.setOnClickListener(setHelpClickedListener);
rlPreview.setOnClickListener(setPreviewClickedListener);
}
@Override
protected void onPause() {
super.onPause();
// prevents force close when device rotates or app is paused while inside asynctask
if(dialog != null) dialog.dismiss();
dialog = null;
}
@Override
protected void onResume() {
super.onResume();
int textColor = settings.getInt("textColor", -1);
int backgroundColor = settings.getInt("backgroundColor",1996554497);
editor.putInt("textColor-" + mAppWidgetId, textColor).commit();
editor.putInt("backgroundColor-" + mAppWidgetId, backgroundColor).commit();
Log.v(TAG,Integer.toString(settings.getInt("textColor-" + mAppWidgetId, -2)));
Log.v(TAG,Integer.toString(settings.getInt("backgroundColor-" + mAppWidgetId, -2)));
// change colors in preview
rlPreview.setBackgroundColor(backgroundColor);
tvStopPreview.setTextColor(textColor);
tvRoutePreview.setTextColor(textColor);
tvRemainingTimePreview.setTextColor(textColor);
tvMinsPreview.setTextColor(textColor);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_about:
// start about activity
Log.v(TAG,"menu option selected");
Intent intent = new Intent(this, AboutActivity.class);
startActivity(intent);
break;
default:
break;
}
return true;
}
// type mapping
// type = 0 --> full reset (bReset)
// type = 1 --> reset only route and stops (agency changed)
// type = 2 --> reset only stop (route changed)
private void doReset(int type) {
// start over
if(type <= 2) {
sSelectStop.setText(R.string.select_stop);
currentStopId= -1;
stopName = null;
sSelectStop.setEnabled(false);
}
if(type <= 1) {
sSelectRoute.setText(R.string.select_route);
currentRouteId = -1;
routeShortName = null;
routeLongName = null;
sSelectRoute.setEnabled(false);
}
if(type == 0) {
sSelectAgency.setText(R.string.select_agency);
currentAgencyId = -1;
bMakeWidget.setEnabled(false);
new PopulateAgenciesTask().execute();
}
}
private void doMakeWidget() {
// Get arrival time and make the widget
new PopulateArrivalTask().execute();
}
private void doErrorMiscHandling() {
bMakeWidget.setEnabled(false);
if(dialog != null) {
dialog.dismiss();
dialog = null;
}
}
private class PopulateAgenciesTask extends AsyncTask<Void, Void, TransLocAgencies> {
@Override
protected void onPreExecute() {
// show dialog
doReset(1);
if(dialog == null) {
// dialog = ProgressDialog.show(WidgetConfigurationActivity.this, "Loading", "Please Wait...");
}
}
protected TransLocAgencies doInBackground(Void... voids) {
try {
return new ObjectMapper().readValue(Utils.getJsonResponse(AGENCIES_URL, getString(R.string.mashape_key)), TransLocAgencies.class);
} catch (Exception e) {
Log.e(TAG, "ERROR in getting JSON data for agencies");
e.printStackTrace();
return null;
}
}
@Override
protected void onPostExecute(final TransLocAgencies agencyList) {
if (agencyList == null) {
Log.e(TAG, "error in getting list of agencies");
doErrorMiscHandling();
Utils.showAlertDialog(WidgetConfigurationActivity.this, "Error - No Data", getString(R.string.error_no_data));
bMakeWidget.setEnabled(false);
}
else {
// sort agency list first
ArrayList<TransLocAgency> sortedList = (ArrayList<TransLocAgency>) agencyList.getData();
// remove unwanted agencies (those that don't have arrival times)
// 72 = NYU, 104 = CTA
for(int i = 0; i < sortedList.size(); i++) {
int agencyId = sortedList.get(i).agencyId;
if(agencyId == 72 || agencyId == 104) {
sortedList.remove(i);
}
}
Collections.sort(sortedList, sortTransLocAgency());
final ArrayAdapter<TransLocAgency> agencyArrayAdapter = new ArrayAdapter<TransLocAgency>(getBaseContext(), android.R.layout.simple_spinner_dropdown_item, agencyList.getData());
// set button spinner click listeners
sSelectAgency.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
new AlertDialog.Builder(WidgetConfigurationActivity.this)
.setTitle("Select an Agency")
.setAdapter(agencyArrayAdapter, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int pos) {
currentAgencyId = agencyList.getData().get(pos).agencyId;
sSelectAgency.setText(agencyList.getData().get(pos).longName);
sSelectRoute.setText(R.string.select_route);
sSelectStop.setText(R.string.select_stop);
new PopulateRoutesTask().execute();
dialog.dismiss();
}
}).create().show();
}
});
}
}
}
// comparator for sorting agencies
private Comparator<TransLocAgency> sortTransLocAgency() {
return new Comparator<TransLocAgency>() {
@Override
public int compare(TransLocAgency transLocAgency, TransLocAgency transLocAgency2) {
return transLocAgency.longName.compareTo(transLocAgency2.longName);
}
};
}
private Comparator<TransLocRoute> sortTransLocRoute() {
return new Comparator<TransLocRoute>() {
@Override
public int compare(TransLocRoute transLocRoute, TransLocRoute transLocRoute2) {
if(Character.isDigit(transLocRoute.shortName.charAt(0)) || Character.isDigit(transLocRoute2.shortName.charAt(0))) {
if(Character.isLetter(transLocRoute.shortName.charAt(0)) || Character.isLetter(transLocRoute.shortName.charAt(transLocRoute.shortName.length()-1))) return -1;
else if(Character.isLetter(transLocRoute2.shortName.charAt(0)) || Character.isLetter(transLocRoute2.shortName.charAt(transLocRoute2.shortName.length()-1))) return 1;
try {
int route1 = Integer.valueOf(transLocRoute.shortName);
int route2 = Integer.valueOf(transLocRoute2.shortName);
if(route1 < route2) return -1;
else if(route1 > route2) return 1;
else return 0;
} catch (NumberFormatException e) {
return transLocRoute.shortName.compareTo(transLocRoute2.shortName);
}
} else {
return transLocRoute.longName.compareTo(transLocRoute2.longName);
}
}
};
}
private class PopulateRoutesTask extends AsyncTask<Void, Void, ArrayList<TransLocRoute>> {
@Override
protected void onPreExecute() {
doReset(2);
sSelectRoute.setEnabled(false);
if(dialog == null) {
// dialog = ProgressDialog.show(WidgetConfigurationActivity.this, "Loading", "Please Wait...");
}
}
@SuppressWarnings("unchecked")
protected ArrayList<TransLocRoute> doInBackground(Void... voids) {
try {
Map<String, Object> routeMap = new ObjectMapper().readValue(Utils.getJsonResponse(ROUTES_URL + currentAgencyId, getString(R.string.mashape_key)), Map.class);
Map<String, Object> agencyMap = (Map) routeMap.get("data");
List<Map<String, Object>> routeList = (List) agencyMap.get(Integer.toString(currentAgencyId));
final ArrayList<TransLocRoute> routesArrayList = new ArrayList<TransLocRoute>();
if (routeList == null) {
// returns empty list
return routesArrayList;
} else {
for (Map<String, Object> route : routeList) {
routesArrayList.add(new TransLocRoute(Integer.parseInt((String) route.get("route_id")), (String) route.get("short_name"), (String) route.get("long_name")));
}
return routesArrayList;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
@Override
protected void onPostExecute(final ArrayList<TransLocRoute> routesArrayList) {
ArrayList<String> arr = new ArrayList<String>();
sSelectRoute.setEnabled(true);
if(routesArrayList == null) {
// no connection
doErrorMiscHandling();
Utils.showAlertDialog(WidgetConfigurationActivity.this, "Error - No Data", getString(R.string.error_no_data));
// empty routes and stops spinner (set to empty array)
}
else if (routesArrayList.isEmpty()) {
Log.e(TAG, "error in getting list of routes - empty list");
doErrorMiscHandling();
Utils.showAlertDialog(WidgetConfigurationActivity.this, "Error - No Routes Available", "No routes are currently available for the agency you have selected. Please try again later when buses are running.");
} else {
// sort only if agency is 116 (UF)
if(currentAgencyId == 116) Collections.sort(routesArrayList, sortTransLocRoute());
final ArrayAdapter<TransLocRoute> routeArrayAdapter = new ArrayAdapter<TransLocRoute>(getBaseContext(), android.R.layout.simple_list_item_1, routesArrayList);
//enable routes button
sSelectRoute.setEnabled(true);
sSelectRoute.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
new AlertDialog.Builder(WidgetConfigurationActivity.this)
.setTitle(R.string.select_route)
.setAdapter(routeArrayAdapter, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int pos) {
currentRouteId = routesArrayList.get(pos).id;
routeLongName = routesArrayList.get(pos).longName;
routeShortName = routesArrayList.get(pos).shortName;
sSelectRoute.setText(routeShortName + " " + routeLongName);
sSelectStop.setText(R.string.select_stop);
new PopulateStopsTask().execute();
dialog.dismiss();
}
}).create().show();
}
});
}
}
}
private class PopulateStopsTask extends AsyncTask<Void, Void, TransLocStops> {
@Override
protected void onPreExecute() {
sSelectStop.setEnabled(false);
if(dialog == null) {
// dialog = ProgressDialog.show(WidgetConfigurationActivity.this, "Loading", "Please Wait...");
}
}
protected TransLocStops doInBackground(Void... voids) {
try {
return new ObjectMapper().readValue(Utils.getJsonResponse(STOPS_URL + currentAgencyId, getString(R.string.mashape_key)), TransLocStops.class);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
@Override
@SuppressWarnings("unchecked")
protected void onPostExecute(TransLocStops stopList) {
fullStopList.clear();
if (stopList != null) {
fullStopList.addAll(stopList.data);
} else {
Log.e(TAG, "error in getting stops list");
doErrorMiscHandling();
// no connection
//Utils.showAlertDialog(WidgetConfigurationActivity.this, "Error - No Data", getString(R.string.error_no_data));
//Utils.showAlertDialog(WidgetConfigurationActivity.this, "Error - No Stops Available", "No stops are currently available for the route you have selected. Please try again later when buses are running.");
}
new FilterStopListTask().execute(fullStopList);
}
}
private class FilterStopListTask extends AsyncTask<ArrayList<TransLocStop>, String, ArrayList<TransLocStop>> {
@Override
protected ArrayList<TransLocStop> doInBackground(ArrayList<TransLocStop>... fullStopList) {
if (fullStopList.length == 1) {
if (fullStopList[0] == null) {
return null;
}
ArrayList<TransLocStop> currentRouteStopList = new ArrayList<TransLocStop>();
for (int i = fullStopList[0].size() - 1; i >= 0; i
if (fullStopList[0].get(i).routes.contains(currentRouteId)) {
currentRouteStopList.add(fullStopList[0].get(i));
}
}
return currentRouteStopList;
} else {
return null;
}
}
@Override
protected void onPostExecute(final ArrayList<TransLocStop> currentRouteStopList) {
ArrayList<String> arr = new ArrayList<String>();
sSelectStop.setEnabled(true);
if(currentRouteStopList == null) {
doErrorMiscHandling();
Utils.showAlertDialog(WidgetConfigurationActivity.this, "Error - No Data", getString(R.string.error_no_data));
// sSelectStop.setAdapter(new ArrayAdapter<String>(WidgetConfigurationActivity.this, android.R.layout.simple_dropdown_item_1line, arr));
}
else if(currentRouteStopList.isEmpty()) {
Log.e(TAG, "error in getting stops list");
doErrorMiscHandling();
// empty stops spinner
//sSelectStop.setAdapter(new ArrayAdapter<String>(WidgetConfigurationActivity.this, android.R.layout.simple_dropdown_item_1line, arr));
Utils.showAlertDialog(WidgetConfigurationActivity.this, "Error - No Stops Available", "No stops are currently available for the route you have selected. Please try again later when buses are running.");
} else {
final ArrayAdapter<TransLocStop> stopArrayAdapter = new ArrayAdapter<TransLocStop>(getBaseContext(), android.R.layout.simple_list_item_1, currentRouteStopList);
sSelectStop.setEnabled(true);
sSelectStop.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
new AlertDialog.Builder(WidgetConfigurationActivity.this)
.setTitle(R.string.select_stop)
.setAdapter(stopArrayAdapter, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int pos) {
currentStopId = currentRouteStopList.get(pos).stopId;
stopName = currentRouteStopList.get(pos).name;
sSelectStop.setText(stopName);
bMakeWidget.setEnabled(true);
dialog.dismiss();
}
}).create().show();
}
});
}
if(dialog != null) {
dialog.dismiss();
dialog = null;
}
}
}
private class PopulateArrivalTask extends AsyncTask<Void, Void, TransLocArrivalEstimates> {
ProgressDialog makeWidgetDialog;
private int minutes = -1;
@Override
protected void onPreExecute() {
makeWidgetDialog = ProgressDialog.show(WidgetConfigurationActivity.this, "Making Widget", "Please Wait...");
}
protected TransLocArrivalEstimates doInBackground(Void... voids) {
String url = ARRIVALS_URL + currentAgencyId + "&routes=" + currentRouteId + "&stops=" + currentStopId;
// URL is stored as urlXX with XX being the appwidget ID
editor.putString("url" + mAppWidgetId, url).commit();
Log.v(TAG, "arrival estimates URL: " + url);
try {
return new ObjectMapper().readValue(Utils.getJsonResponse(url, getString(R.string.mashape_key)), TransLocArrivalEstimates.class);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
@Override
protected void onPostExecute(TransLocArrivalEstimates arrivalEstimatesList) {
Date currentTimeUTC;
Date arrivalTimeUTC;
if(arrivalEstimatesList == null) {
// no connection
Utils.showAlertDialog(WidgetConfigurationActivity.this, "Error - No Data", getString(R.string.error_no_data));
} else if (arrivalEstimatesList.data.isEmpty()) {
Utils.showAlertDialog(WidgetConfigurationActivity.this, "Error - No Arrival Times", "No arrival times are currently available for the route and stop you have selected. Please try again later when buses are running.");
} else {
TransLocArrivalEstimate arrivalEstimate = arrivalEstimatesList.data.get(0);
TransLocArrival arrival = arrivalEstimate.arrivals.get(0);
currentTimeUTC = arrivalEstimatesList.generatedOn;
arrivalTimeUTC = arrival.arrivalAt;
Log.v(TAG, "current time: " + currentTimeUTC + " ... " + "arrival time: " + arrivalTimeUTC);
minutes = Utils.getMinutesBetweenTimes(currentTimeUTC, arrivalTimeUTC);
// Getting an instance of WidgetManager
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(getBaseContext());
// Instantiating the class RemoteViews with widget_layout
RemoteViews views = new RemoteViews(getBaseContext().getPackageName(), R.layout.widget_layout);
//Set the time remaining of the widget
views.setTextViewText(R.id.tvRemainingTime, Integer.toString(minutes));
if (minutes < 1) views.setTextViewText(R.id.tvRemainingTime, "<1");
if (minutes < 2) views.setTextViewText(R.id.tvMins, "min away");
else views.setTextViewText(R.id.tvMins, "mins away");
// commit widget info to preferences and set text on remoteview
// if short name is less than 5 characters, use short name + long name
if (routeShortName.length() < 5 && routeShortName.length() > 0) {
String widgetRouteName = routeShortName + " - " + routeLongName;
editor.putString("routeName" + mAppWidgetId, widgetRouteName).commit();
views.setTextViewText(R.id.tvRoute, widgetRouteName);
} else if(routeShortName.length() == 0) {
editor.putString("routeName" + mAppWidgetId, routeLongName).commit();
views.setTextViewText(R.id.tvRoute, routeLongName);
} else {
editor.putString("routeName" + mAppWidgetId, routeShortName).commit();
views.setTextViewText(R.id.tvRoute, routeShortName);
}
editor.putString("stopName" + mAppWidgetId, stopName).commit();
views.setTextViewText(R.id.tvStop, stopName);
// set colors for widget
int backgroundColor = settings.getInt("backgroundColor",1996554497);
editor.putInt("backgroundColor-" + mAppWidgetId, backgroundColor);
int textColor = settings.getInt("textColor",-1);
views.setInt(R.id.rlWidgetLayout,"setBackgroundColor",backgroundColor);
views.setTextColor(R.id.tvRemainingTime,textColor);
views.setTextColor(R.id.tvMins,textColor);
views.setTextColor(R.id.tvRoute,textColor);
views.setTextColor(R.id.tvStop,textColor);
// setup intent for tap on widget
Intent clickIntent = new Intent(getBaseContext(), TransLocWidgetProvider.class);
clickIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), mAppWidgetId, clickIntent, PendingIntent.FLAG_UPDATE_CURRENT);
// add pending intent to whole widget
views.setOnClickPendingIntent(R.id.rlWidgetLayout, pendingIntent);
// Tell the AppWidgetManager to perform an update on the app widget
appWidgetManager.updateAppWidget(mAppWidgetId, views);
Log.v(TAG, "mappwidgetid: " + mAppWidgetId);
// Return RESULT_OK from this activity
Intent resultValue = new Intent();
resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
setResult(RESULT_OK, resultValue);
editor.putBoolean("configComplete", true);
Toast.makeText(getApplicationContext(), "Tap on the widget to update!", Toast.LENGTH_LONG ).show();
finish();
}
makeWidgetDialog.dismiss();
}
}
}
|
package com.shyamu.translocwidget;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.appwidget.AppWidgetManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.RemoteViews;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.shyamu.translocwidget.TransLocJSON.TransLocAgencies;
import com.shyamu.translocwidget.TransLocJSON.TransLocAgency;
import com.shyamu.translocwidget.TransLocJSON.TransLocArrival;
import com.shyamu.translocwidget.TransLocJSON.TransLocArrivalEstimate;
import com.shyamu.translocwidget.TransLocJSON.TransLocArrivalEstimates;
import com.shyamu.translocwidget.TransLocJSON.TransLocRoute;
import com.shyamu.translocwidget.TransLocJSON.TransLocStop;
import com.shyamu.translocwidget.TransLocJSON.TransLocStops;
import org.joda.time.DateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;
import static android.widget.AdapterView.OnItemSelectedListener;
public class WidgetConfigurationActivity extends Activity {
private static final String AGENCIES_URL = "https://transloc-api-1-2.p.mashape.com/agencies.json";
private static final String ROUTES_URL = "https://transloc-api-1-2.p.mashape.com/routes.json?agencies=";
private static final String STOPS_URL = "https://transloc-api-1-2.p.mashape.com/stops.json?agencies=";
private static final String ARRIVALS_URL = "https://transloc-api-1-2.p.mashape.com/arrival-estimates.json?agencies=";
private static final String TAG = "ConfigActivity";
static SharedPreferences settings;
static SharedPreferences.Editor editor;
private ArrayList<TransLocStop> fullStopList = new ArrayList<TransLocStop>();
private int currentAgencyId;
private int currentRouteId;
private int currentStopId;
private String routeShortName;
private String routeLongName;
private String stopName;
private int mAppWidgetId = 0;
ProgressDialog dialog = null;
RelativeLayout rlPreview;
Button sSelectAgency, sSelectRoute, sSelectStop;
Button bReset, bMakeWidget;
TextView tvHelpMessage;
TextView tvRoutePreview, tvRemainingTimePreview, tvStopPreview, tvMinsPreview;
ProgressBar progressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.v(TAG, "in onCreate");
setContentView(R.layout.activity_configuration);
// references to elements
sSelectAgency = (Button) findViewById(R.id.sSelectAgency);
sSelectRoute = (Button) findViewById(R.id.sSelectRoute);
sSelectStop = (Button) findViewById(R.id.sSelectStop);
bReset = (Button) findViewById(R.id.bReset);
bMakeWidget = (Button) findViewById(R.id.bMakeWidget);
tvHelpMessage = (TextView) findViewById(R.id.tvHelp);
// progress bar
progressBar = (ProgressBar) findViewById(R.id.progressBar);
// preview elements
rlPreview = (RelativeLayout) findViewById(R.id.rlPreview);
tvMinsPreview = (TextView) findViewById(R.id.tvMins_preview);
tvRemainingTimePreview = (TextView) findViewById(R.id.tvRemainingTime_preview);
tvRoutePreview = (TextView) findViewById(R.id.tvRoute_preview);
tvStopPreview = (TextView) findViewById(R.id.tvStop_preview);
settings = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
editor = settings.edit();
// Set result initially as cancelled in case user cancels configuration
setResult(RESULT_CANCELED);
// show warning dialog if weekend or outside business hours
DateTime currentTime = new DateTime(System.currentTimeMillis());
// day of of week 6 and 7 = Saturday and Sunday
Log.v(TAG,"day= " + currentTime.getDayOfWeek());
Log.v(TAG,"hour= " + currentTime.getHourOfDay());
if(currentTime.getDayOfWeek() > 5 || currentTime.getHourOfDay() > 18 || currentTime.getHourOfDay() < 6) {
Log.v(TAG,"true");
// show warning dialog
Utils.showAlertDialog(WidgetConfigurationActivity.this,"Warning", "Based on the current time and day of week, many routes may not be running at this time. You can continue to try and make a widget but be advised you may get better results during normal business hours.");
}
// Populate agency spinner
new PopulateAgenciesTask().execute();
// Defining a click event listener for the button "Reset"
OnClickListener setResetClickedListener = new OnClickListener() {
@Override
public void onClick(View v) {
doReset(0);
}
};
// Defining a click event listener for the button "Make Widget"
OnClickListener setMakeWidgetClickedListener = new OnClickListener() {
@Override
public void onClick(View v) {
doMakeWidget();
}
};
// On click listener for help text
OnClickListener setHelpClickedListener = new OnClickListener() {
@Override
public void onClick(View view) {
Utils.showAlertDialog(WidgetConfigurationActivity.this, "Why can't I find my agency?", getString(R.string.help_dialog));
}
};
// On click listener for preview layout
OnClickListener setPreviewClickedListener = new OnClickListener() {
@Override
public void onClick(View view) {
// launch customization activity
Intent intent = new Intent(WidgetConfigurationActivity.this, CustomizeWidgetActivity.class);
intent.putExtra("widgetId",mAppWidgetId);
startActivity(intent);
}
};
// Get widgetId from appwidgetmanager
Intent intent = getIntent();
Bundle extras = intent.getExtras();
if (extras != null) {
mAppWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID,
AppWidgetManager.INVALID_APPWIDGET_ID);
}
// Set the click listeners on the buttons
bReset.setOnClickListener(setResetClickedListener);
bMakeWidget.setOnClickListener(setMakeWidgetClickedListener);
tvHelpMessage.setOnClickListener(setHelpClickedListener);
rlPreview.setOnClickListener(setPreviewClickedListener);
}
@Override
protected void onPause() {
super.onPause();
// prevents force close when device rotates or app is paused while inside asynctask
if(dialog != null) dialog.dismiss();
dialog = null;
}
@Override
protected void onResume() {
super.onResume();
int textColor = settings.getInt("textColor", -1);
int backgroundColor = settings.getInt("backgroundColor",1996554497);
editor.putInt("textColor-" + mAppWidgetId, textColor).commit();
editor.putInt("backgroundColor-" + mAppWidgetId, backgroundColor).commit();
Log.v(TAG,Integer.toString(settings.getInt("textColor-" + mAppWidgetId, -2)));
Log.v(TAG,Integer.toString(settings.getInt("backgroundColor-" + mAppWidgetId, -2)));
// change colors in preview
rlPreview.setBackgroundColor(backgroundColor);
tvStopPreview.setTextColor(textColor);
tvRoutePreview.setTextColor(textColor);
tvRemainingTimePreview.setTextColor(textColor);
tvMinsPreview.setTextColor(textColor);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_about:
// start about activity
Log.v(TAG,"menu option selected");
Intent intent = new Intent(this, AboutActivity.class);
startActivity(intent);
break;
default:
break;
}
return true;
}
// type mapping
// type = 0 --> full reset (bReset)
// type = 1 --> reset only route and stops (agency changed)
// type = 2 --> reset only stop (route changed)
private void doReset(int type) {
// start over
if(type <= 2) {
sSelectStop.setText(R.string.select_stop);
currentStopId= -1;
stopName = null;
sSelectStop.setEnabled(false);
bMakeWidget.setEnabled(false);
}
if(type <= 1) {
sSelectRoute.setText(R.string.select_route);
currentRouteId = -1;
routeShortName = null;
routeLongName = null;
sSelectRoute.setEnabled(false);
bMakeWidget.setEnabled(false);
}
if(type == 0) {
sSelectAgency.setText(R.string.select_agency);
currentAgencyId = -1;
bMakeWidget.setEnabled(false);
new PopulateAgenciesTask().execute();
}
}
private void doMakeWidget() {
// Get arrival time and make the widget
new PopulateArrivalTask().execute();
}
private void doErrorMiscHandling() {
bMakeWidget.setEnabled(false);
if(dialog != null) {
dialog.dismiss();
dialog = null;
}
}
private class PopulateAgenciesTask extends AsyncTask<Void, Void, TransLocAgencies> {
@Override
protected void onPreExecute() {
progressBar.setVisibility(View.VISIBLE);
sSelectAgency.setText("Loading agencies...");
doReset(1);
}
protected TransLocAgencies doInBackground(Void... voids) {
try {
return new ObjectMapper().readValue(Utils.getJsonResponse(AGENCIES_URL, getString(R.string.mashape_key)), TransLocAgencies.class);
} catch (Exception e) {
Log.e(TAG, "ERROR in getting JSON data for agencies");
e.printStackTrace();
return null;
}
}
@Override
protected void onPostExecute(final TransLocAgencies agencyList) {
progressBar.setVisibility(View.INVISIBLE);
sSelectAgency.setText(R.string.select_agency);
if (agencyList == null) {
Log.e(TAG, "error in getting list of agencies");
doErrorMiscHandling();
Utils.showAlertDialog(WidgetConfigurationActivity.this, "Error - No Data", getString(R.string.error_no_data));
bMakeWidget.setEnabled(false);
}
else {
// sort agency list first
ArrayList<TransLocAgency> sortedList = (ArrayList<TransLocAgency>) agencyList.getData();
// remove unwanted agencies (those that don't have arrival times)
// 72 = NYU, 104 = CTA
for(int i = 0; i < sortedList.size(); i++) {
int agencyId = sortedList.get(i).agencyId;
if(agencyId == 72 || agencyId == 104) {
sortedList.remove(i);
}
}
Collections.sort(sortedList, sortTransLocAgency());
final ArrayAdapter<TransLocAgency> agencyArrayAdapter = new ArrayAdapter<TransLocAgency>(getBaseContext(), android.R.layout.simple_spinner_dropdown_item, agencyList.getData());
// set button spinner click listeners
sSelectAgency.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
new AlertDialog.Builder(WidgetConfigurationActivity.this)
.setTitle("Select an Agency")
.setAdapter(agencyArrayAdapter, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int pos) {
currentAgencyId = agencyList.getData().get(pos).agencyId;
sSelectAgency.setText(agencyList.getData().get(pos).longName);
sSelectRoute.setText(R.string.select_route);
sSelectStop.setText(R.string.select_stop);
new PopulateRoutesTask().execute();
dialog.dismiss();
}
}).create().show();
}
});
}
}
}
// comparator for sorting agencies
private Comparator<TransLocAgency> sortTransLocAgency() {
return new Comparator<TransLocAgency>() {
@Override
public int compare(TransLocAgency transLocAgency, TransLocAgency transLocAgency2) {
return transLocAgency.longName.compareTo(transLocAgency2.longName);
}
};
}
private Comparator<TransLocRoute> sortTransLocRoute() {
return new Comparator<TransLocRoute>() {
@Override
public int compare(TransLocRoute transLocRoute, TransLocRoute transLocRoute2) {
if(Character.isDigit(transLocRoute.shortName.charAt(0)) || Character.isDigit(transLocRoute2.shortName.charAt(0))) {
if(Character.isLetter(transLocRoute.shortName.charAt(0)) || Character.isLetter(transLocRoute.shortName.charAt(transLocRoute.shortName.length()-1))) return -1;
else if(Character.isLetter(transLocRoute2.shortName.charAt(0)) || Character.isLetter(transLocRoute2.shortName.charAt(transLocRoute2.shortName.length()-1))) return 1;
try {
int route1 = Integer.valueOf(transLocRoute.shortName);
int route2 = Integer.valueOf(transLocRoute2.shortName);
if(route1 < route2) return -1;
else if(route1 > route2) return 1;
else return 0;
} catch (NumberFormatException e) {
return transLocRoute.shortName.compareTo(transLocRoute2.shortName);
}
} else {
return transLocRoute.longName.compareTo(transLocRoute2.longName);
}
}
};
}
private class PopulateRoutesTask extends AsyncTask<Void, Void, ArrayList<TransLocRoute>> {
@Override
protected void onPreExecute() {
progressBar.setVisibility(View.VISIBLE);
sSelectRoute.setText("Loading routes...");
bMakeWidget.setEnabled(false);
doReset(2);
sSelectRoute.setEnabled(false);
if(dialog == null) {
// dialog = ProgressDialog.show(WidgetConfigurationActivity.this, "Loading", "Please Wait...");
}
}
@SuppressWarnings("unchecked")
protected ArrayList<TransLocRoute> doInBackground(Void... voids) {
try {
Map<String, Object> routeMap = new ObjectMapper().readValue(Utils.getJsonResponse(ROUTES_URL + currentAgencyId, getString(R.string.mashape_key)), Map.class);
Map<String, Object> agencyMap = (Map) routeMap.get("data");
List<Map<String, Object>> routeList = (List) agencyMap.get(Integer.toString(currentAgencyId));
final ArrayList<TransLocRoute> routesArrayList = new ArrayList<TransLocRoute>();
if (routeList == null) {
// returns empty list
return routesArrayList;
} else {
for (Map<String, Object> route : routeList) {
routesArrayList.add(new TransLocRoute(Integer.parseInt((String) route.get("route_id")), (String) route.get("short_name"), (String) route.get("long_name")));
}
return routesArrayList;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
@Override
protected void onPostExecute(final ArrayList<TransLocRoute> routesArrayList) {
progressBar.setVisibility(View.INVISIBLE);
sSelectRoute.setText(R.string.select_route);
ArrayList<String> arr = new ArrayList<String>();
sSelectRoute.setEnabled(true);
if(routesArrayList == null) {
// no connection
doErrorMiscHandling();
Utils.showAlertDialog(WidgetConfigurationActivity.this, "Error - No Data", getString(R.string.error_no_data));
// empty routes and stops spinner (set to empty array)
}
else if (routesArrayList.isEmpty()) {
Log.e(TAG, "error in getting list of routes - empty list");
doErrorMiscHandling();
Utils.showAlertDialog(WidgetConfigurationActivity.this, "Error - No Routes Available", "No routes are currently available for the agency you have selected. Please try again later when buses are running.");
} else {
// sort only if agency is 116 (UF)
if(currentAgencyId == 116) Collections.sort(routesArrayList, sortTransLocRoute());
final ArrayAdapter<TransLocRoute> routeArrayAdapter = new ArrayAdapter<TransLocRoute>(getBaseContext(), android.R.layout.simple_list_item_1, routesArrayList);
//enable routes button
sSelectRoute.setEnabled(true);
sSelectRoute.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
new AlertDialog.Builder(WidgetConfigurationActivity.this)
.setTitle(R.string.select_route)
.setAdapter(routeArrayAdapter, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int pos) {
currentRouteId = routesArrayList.get(pos).id;
routeLongName = routesArrayList.get(pos).longName;
routeShortName = routesArrayList.get(pos).shortName;
sSelectRoute.setText(routeShortName + " " + routeLongName);
sSelectStop.setText(R.string.select_stop);
new PopulateStopsTask().execute();
dialog.dismiss();
}
}).create().show();
}
});
}
}
}
private class PopulateStopsTask extends AsyncTask<Void, Void, TransLocStops> {
@Override
protected void onPreExecute() {
progressBar.setVisibility(View.VISIBLE);
sSelectStop.setText("Loading stops...");
sSelectStop.setEnabled(false);
if(dialog == null) {
// dialog = ProgressDialog.show(WidgetConfigurationActivity.this, "Loading", "Please Wait...");
}
}
protected TransLocStops doInBackground(Void... voids) {
try {
return new ObjectMapper().readValue(Utils.getJsonResponse(STOPS_URL + currentAgencyId, getString(R.string.mashape_key)), TransLocStops.class);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
@Override
@SuppressWarnings("unchecked")
protected void onPostExecute(TransLocStops stopList) {
fullStopList.clear();
if (stopList != null) {
fullStopList.addAll(stopList.data);
} else {
Log.e(TAG, "error in getting stops list");
doErrorMiscHandling();
// no connection
//Utils.showAlertDialog(WidgetConfigurationActivity.this, "Error - No Data", getString(R.string.error_no_data));
//Utils.showAlertDialog(WidgetConfigurationActivity.this, "Error - No Stops Available", "No stops are currently available for the route you have selected. Please try again later when buses are running.");
}
new FilterStopListTask().execute(fullStopList);
}
}
private class FilterStopListTask extends AsyncTask<ArrayList<TransLocStop>, String, ArrayList<TransLocStop>> {
@Override
protected ArrayList<TransLocStop> doInBackground(ArrayList<TransLocStop>... fullStopList) {
if (fullStopList.length == 1) {
if (fullStopList[0] == null) {
return null;
}
ArrayList<TransLocStop> currentRouteStopList = new ArrayList<TransLocStop>();
for (int i = fullStopList[0].size() - 1; i >= 0; i
if (fullStopList[0].get(i).routes.contains(currentRouteId)) {
currentRouteStopList.add(fullStopList[0].get(i));
}
}
return currentRouteStopList;
} else {
return null;
}
}
@Override
protected void onPostExecute(final ArrayList<TransLocStop> currentRouteStopList) {
progressBar.setVisibility(View.INVISIBLE);
sSelectStop.setText(R.string.select_stop);
ArrayList<String> arr = new ArrayList<String>();
sSelectStop.setEnabled(true);
if(currentRouteStopList == null) {
doErrorMiscHandling();
Utils.showAlertDialog(WidgetConfigurationActivity.this, "Error - No Data", getString(R.string.error_no_data));
// sSelectStop.setAdapter(new ArrayAdapter<String>(WidgetConfigurationActivity.this, android.R.layout.simple_dropdown_item_1line, arr));
}
else if(currentRouteStopList.isEmpty()) {
Log.e(TAG, "error in getting stops list");
doErrorMiscHandling();
// empty stops spinner
//sSelectStop.setAdapter(new ArrayAdapter<String>(WidgetConfigurationActivity.this, android.R.layout.simple_dropdown_item_1line, arr));
Utils.showAlertDialog(WidgetConfigurationActivity.this, "Error - No Stops Available", "No stops are currently available for the route you have selected. Please try again later when buses are running.");
} else {
final ArrayAdapter<TransLocStop> stopArrayAdapter = new ArrayAdapter<TransLocStop>(getBaseContext(), android.R.layout.simple_list_item_1, currentRouteStopList);
sSelectStop.setEnabled(true);
sSelectStop.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
new AlertDialog.Builder(WidgetConfigurationActivity.this)
.setTitle(R.string.select_stop)
.setAdapter(stopArrayAdapter, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int pos) {
currentStopId = currentRouteStopList.get(pos).stopId;
stopName = currentRouteStopList.get(pos).name;
sSelectStop.setText(stopName);
bMakeWidget.setEnabled(true);
Log.v("DEBUG","make widger enabled");
dialog.dismiss();
}
}).create().show();
}
});
}
if(dialog != null) {
dialog.dismiss();
dialog = null;
}
}
}
private class PopulateArrivalTask extends AsyncTask<Void, Void, TransLocArrivalEstimates> {
ProgressDialog makeWidgetDialog;
private int minutes = -1;
@Override
protected void onPreExecute() {
makeWidgetDialog = ProgressDialog.show(WidgetConfigurationActivity.this, "Making Widget", "Please Wait...");
}
protected TransLocArrivalEstimates doInBackground(Void... voids) {
String url = ARRIVALS_URL + currentAgencyId + "&routes=" + currentRouteId + "&stops=" + currentStopId;
// URL is stored as urlXX with XX being the appwidget ID
editor.putString("url" + mAppWidgetId, url).commit();
Log.v(TAG, "arrival estimates URL: " + url);
try {
return new ObjectMapper().readValue(Utils.getJsonResponse(url, getString(R.string.mashape_key)), TransLocArrivalEstimates.class);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
@Override
protected void onPostExecute(TransLocArrivalEstimates arrivalEstimatesList) {
Date currentTimeUTC;
Date arrivalTimeUTC;
if(arrivalEstimatesList == null) {
// no connection
Utils.showAlertDialog(WidgetConfigurationActivity.this, "Error - No Data", getString(R.string.error_no_data));
} else if (arrivalEstimatesList.data.isEmpty()) {
Utils.showAlertDialog(WidgetConfigurationActivity.this, "Error - No Arrival Times", "No arrival times are currently available for the route and stop you have selected. Please try again later when buses are running.");
} else {
TransLocArrivalEstimate arrivalEstimate = arrivalEstimatesList.data.get(0);
TransLocArrival arrival = arrivalEstimate.arrivals.get(0);
currentTimeUTC = arrivalEstimatesList.generatedOn;
arrivalTimeUTC = arrival.arrivalAt;
Log.v(TAG, "current time: " + currentTimeUTC + " ... " + "arrival time: " + arrivalTimeUTC);
minutes = Utils.getMinutesBetweenTimes(currentTimeUTC, arrivalTimeUTC);
// Getting an instance of WidgetManager
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(getBaseContext());
// Instantiating the class RemoteViews with widget_layout
RemoteViews views = new RemoteViews(getBaseContext().getPackageName(), R.layout.widget_layout);
//Set the time remaining of the widget
views.setTextViewText(R.id.tvRemainingTime, Integer.toString(minutes));
if (minutes < 1) views.setTextViewText(R.id.tvRemainingTime, "<1");
if (minutes < 2) views.setTextViewText(R.id.tvMins, "min away");
else views.setTextViewText(R.id.tvMins, "mins away");
// commit widget info to preferences and set text on remoteview
// if short name is less than 5 characters, use short name + long name
if (routeShortName.length() < 5 && routeShortName.length() > 0) {
String widgetRouteName = routeShortName + " - " + routeLongName;
editor.putString("routeName" + mAppWidgetId, widgetRouteName).commit();
views.setTextViewText(R.id.tvRoute, widgetRouteName);
} else if(routeShortName.length() == 0) {
editor.putString("routeName" + mAppWidgetId, routeLongName).commit();
views.setTextViewText(R.id.tvRoute, routeLongName);
} else {
editor.putString("routeName" + mAppWidgetId, routeShortName).commit();
views.setTextViewText(R.id.tvRoute, routeShortName);
}
editor.putString("stopName" + mAppWidgetId, stopName).commit();
views.setTextViewText(R.id.tvStop, stopName);
// set colors for widget
int backgroundColor = settings.getInt("backgroundColor",1996554497);
editor.putInt("backgroundColor-" + mAppWidgetId, backgroundColor);
int textColor = settings.getInt("textColor",-1);
views.setInt(R.id.rlWidgetLayout,"setBackgroundColor",backgroundColor);
views.setTextColor(R.id.tvRemainingTime,textColor);
views.setTextColor(R.id.tvMins,textColor);
views.setTextColor(R.id.tvRoute,textColor);
views.setTextColor(R.id.tvStop,textColor);
// setup intent for tap on widget
Intent clickIntent = new Intent(getBaseContext(), TransLocWidgetProvider.class);
clickIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), mAppWidgetId, clickIntent, PendingIntent.FLAG_UPDATE_CURRENT);
// add pending intent to whole widget
views.setOnClickPendingIntent(R.id.rlWidgetLayout, pendingIntent);
// Tell the AppWidgetManager to perform an update on the app widget
appWidgetManager.updateAppWidget(mAppWidgetId, views);
Log.v(TAG, "mappwidgetid: " + mAppWidgetId);
// Return RESULT_OK from this activity
Intent resultValue = new Intent();
resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
setResult(RESULT_OK, resultValue);
editor.putBoolean("configComplete", true);
Toast.makeText(getApplicationContext(), "Tap on the widget to update!", Toast.LENGTH_LONG ).show();
finish();
}
makeWidgetDialog.dismiss();
}
}
}
|
package com.olivierpayen.popularmovies.model;
import android.os.Parcel;
import android.os.Parcelable;
import com.google.gson.annotations.SerializedName;
import java.util.ArrayList;
import java.util.List;
public class Movie implements Parcelable {
public Boolean adult;
@SerializedName("backdrop_path")
public String backdropPath;
@SerializedName("genre_ids")
public List<Integer> genreIds = new ArrayList<>();
public Integer id;
public String originalLanguage;
@SerializedName("original_title")
public String originalTitle;
public String overview;
@SerializedName("release_date")
public String releaseDate;
@SerializedName("poster_path")
public String posterPath;
public Double popularity;
public String title;
public Boolean video;
@SerializedName("vote_average")
public Double voteAverage;
@SerializedName("vote_count")
public Integer voteCount;
public Movie(String title) {
this.title = title;
}
private static final String BASE_IMG_URL = "http://image.tmdb.org/t/p/";
public String getPosterUrl() {
if (posterPath == null) {
return null;
}
else {
return BASE_IMG_URL + "w185" + posterPath;
}
}
public String getBackdropUrl() {
if (backdropPath == null) {
return null;
}
else {
return BASE_IMG_URL + "w185" + backdropPath;
}
}
protected Movie(Parcel in) {
byte adultVal = in.readByte();
adult = adultVal == 0x02 ? null : adultVal != 0x00;
backdropPath = in.readString();
if (in.readByte() == 0x01) {
genreIds = new ArrayList<>();
in.readList(genreIds, Integer.class.getClassLoader());
} else {
genreIds = null;
}
id = in.readByte() == 0x00 ? null : in.readInt();
originalLanguage = in.readString();
originalTitle = in.readString();
overview = in.readString();
releaseDate = in.readString();
posterPath = in.readString();
popularity = in.readByte() == 0x00 ? null : in.readDouble();
title = in.readString();
byte videoVal = in.readByte();
video = videoVal == 0x02 ? null : videoVal != 0x00;
voteAverage = in.readByte() == 0x00 ? null : in.readDouble();
voteCount = in.readByte() == 0x00 ? null : in.readInt();
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
if (adult == null) {
dest.writeByte((byte) (0x02));
} else {
dest.writeByte((byte) (adult ? 0x01 : 0x00));
}
dest.writeString(backdropPath);
if (genreIds == null) {
dest.writeByte((byte) (0x00));
} else {
dest.writeByte((byte) (0x01));
dest.writeList(genreIds);
}
if (id == null) {
dest.writeByte((byte) (0x00));
} else {
dest.writeByte((byte) (0x01));
dest.writeInt(id);
}
dest.writeString(originalLanguage);
dest.writeString(originalTitle);
dest.writeString(overview);
dest.writeString(releaseDate);
dest.writeString(posterPath);
if (popularity == null) {
dest.writeByte((byte) (0x00));
} else {
dest.writeByte((byte) (0x01));
dest.writeDouble(popularity);
}
dest.writeString(title);
if (video == null) {
dest.writeByte((byte) (0x02));
} else {
dest.writeByte((byte) (video ? 0x01 : 0x00));
}
if (voteAverage == null) {
dest.writeByte((byte) (0x00));
} else {
dest.writeByte((byte) (0x01));
dest.writeDouble(voteAverage);
}
if (voteCount == null) {
dest.writeByte((byte) (0x00));
} else {
dest.writeByte((byte) (0x01));
dest.writeInt(voteCount);
}
}
@SuppressWarnings("unused")
public static final Parcelable.Creator<Movie> CREATOR = new Parcelable.Creator<Movie>() {
@Override
public Movie createFromParcel(Parcel in) {
return new Movie(in);
}
@Override
public Movie[] newArray(int size) {
return new Movie[size];
}
};
}
|
package com.samourai.wallet.util;
import com.samourai.wallet.SamouraiWallet;
public class BlockExplorerUtil {
private static CharSequence[] blockExplorers = { "Smartbit", "UASF Explorer", "Blockchain Reader (Yogh)", "BlockCypher" };
private static CharSequence[] blockExplorerTxUrls = { "https://www.smartbit.com.au/tx/", "https://uasf-explorer.satoshiportal.com/tx/", "http://srv1.yogh.io/
private static CharSequence[] blockExplorerAddressUrls = { "https://www.smartbit.com.au/address/", "https://uasf-explorer.satoshiportal.com/address/", "http://srv1.yogh.io/
private static CharSequence[] tBlockExplorers = { "Smartbit", "BlockCypher" };
private static CharSequence[] tBlockExplorerTxUrls = { "https:
private static CharSequence[] tBlockExplorerAddressUrls = { "https:
private static BlockExplorerUtil instance = null;
private BlockExplorerUtil() { ; }
public static BlockExplorerUtil getInstance() {
if(instance == null) {
instance = new BlockExplorerUtil();
}
return instance;
}
public CharSequence[] getBlockExplorers() {
if(SamouraiWallet.getInstance().isTestNet()) {
return tBlockExplorers;
}
else {
return blockExplorers;
}
}
public CharSequence[] getBlockExplorerTxUrls() {
if(SamouraiWallet.getInstance().isTestNet()) {
return tBlockExplorerTxUrls;
}
else {
return blockExplorerTxUrls;
}
}
public CharSequence[] getBlockExplorerAddressUrls() {
if(SamouraiWallet.getInstance().isTestNet()) {
return tBlockExplorerAddressUrls;
}
else {
return blockExplorerAddressUrls;
}
}
}
|
package com.schaffer.base.common.base;
import android.Manifest;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.app.ActivityManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.support.annotation.DrawableRes;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewAnimationUtils;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import com.schaffer.base.R;
import com.schaffer.base.common.constants.DayNight;
import com.schaffer.base.common.utils.LTUtils;
import com.schaffer.base.helper.DayNightHelper;
import com.schaffer.base.widget.ProgressDialogs;
import org.greenrobot.eventbus.EventBus;
import java.util.ArrayList;
import java.util.List;
public abstract class BaseActivity<V extends BaseView, P extends BasePresenter<V>> extends AppCompatActivity implements BaseView {
private String tag;
private ProgressDialogs mProgressDialogs;
protected Handler handler;
protected boolean mActivityBeShown = false;
private boolean isFirstInit = true;
protected P mPresenter;
private BaseApplication application;
private FrameLayout mFrameContent;
protected boolean eventbusEnable = false;// onCreate()
private static final int REQUEST_CODE_PERMISSIONS = 20;
private static final int REQUEST_CODE_PERMISSION = 19;
public static final String INTENT_DATA_IMG_PATHS = "img_paths";
public static final String INTENT_DATA_IMG_RES = "img_resIds";
public static final String INTENT_DATA_IMG_CURRENT_INDEX = "img_current";
private CountDownTimer countDownTimer;
protected List<TextView> textViews = new ArrayList<>();
protected List<? extends ViewGroup> viewGroups = new ArrayList<>();
protected List<RecyclerView> recyclerViews = new ArrayList<>();
protected List<? extends AdapterView<?>> adapterViews = new ArrayList<>();
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_base);
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//21
// getWindow().setEnterTransition(new Fade());
// getWindow().setExitTransition(new Fade());
mFrameContent = (FrameLayout) findViewById(R.id.layout_group_content);
inflateView(textViews, viewGroups, recyclerViews, adapterViews);
// setToolbar();
initEventBus();
mPresenter = initPresenter();
tag = getClass().getSimpleName();
mProgressDialogs = new ProgressDialogs(this);
application = (BaseApplication) this.getApplication();
application.getActivityManager().pushActivity(this);
}
protected void inflateContent(@LayoutRes int resId) {
inflateContent(resId, null);
}
protected void inflateContent(View inflateView) {
inflateContent(inflateView, null);
}
protected void inflateContent(@LayoutRes int resId, FrameLayout.LayoutParams params) {
inflateContent(View.inflate(this, resId, null), params);
}
protected void inflateContent(View inflateView, FrameLayout.LayoutParams params) {
if (mFrameContent != null && inflateView != null) {
mFrameContent.addView(inflateView, params == null ? new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT) : params);
}
}
/**
* FrameLayout,{@link BaseActivity#inflateContent(int)}
*
* @param textViews TextView
* @param viewGroups ViewGroup
* @param recyclerViews recyclerView
* @param adapterViews adapterView
*/
protected abstract void inflateView(List<TextView> textViews, List<? extends ViewGroup> viewGroups, List<RecyclerView> recyclerViews, List<? extends AdapterView<?>> adapterViews);
/**
* Presenter
*
* @return MVPPresenter
*/
protected abstract P initPresenter();
protected abstract void initData();
protected abstract void refreshData();
@Override
protected void onResume() {
super.onResume();
mActivityBeShown = true;
if (mPresenter != null) {
mPresenter.attach((V) this);
}
if (isFirstInit) {
isFirstInit = false;
initData();
} else {
refreshData();
}
}
@Override
protected void onStart() {
super.onStart();
}
@Override
protected void onStop() {
super.onStop();
mActivityBeShown = false;
}
@Override
protected void onDestroy() {
super.onDestroy();
initEventBus();
if (countDownTimer != null) {
countDownTimer.cancel();
}
if (mPresenter != null) {
mPresenter.detach();
}
if (handler != null) {
handler.removeCallbacksAndMessages(null);
}
if (permissionResultListener != null) permissionResultListener = null;
application.getActivityManager().popActivity(this);
}
private void initEventBus() {
if (!eventbusEnable) return;
if (!EventBus.getDefault().isRegistered(this)) {
EventBus.getDefault().register(this);
} else {
EventBus.clearCaches();
EventBus.getDefault().unregister(this);
}
}
// public void onActivityBack(View v) {
// finish();
// @Override
// public void finish() {
// super.finish();
// overridePendingTransition(R.anim.anim_exit_in, R.anim.anim_exit_out);
// @Override
// public void startActivity(Intent intent) {
// super.startActivity(intent);
// overridePendingTransition(R.anim.anim_enter_in, R.anim.anim_enter_out);
// @Override
// public void startActivityForResult(Intent intent, int requestCode) {
// super.startActivityForResult(intent, requestCode);
// overridePendingTransition(R.anim.anim_enter_in, R.anim.anim_enter_out);
/*@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
public void startActivity(Intent intent) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
super.startActivity(intent, ActivityOptions.makeSceneTransitionAnimation(this)
.toBundle());
}else{
super.startActivity(intent);
}
// overridePendingTransition(R.anim.anim_enter_in, R.anim.anim_enter_out);
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
public void startActivityForResult(Intent intent, int requestCode) {
super.startActivityForResult(intent, requestCode);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
super.startActivityForResult(intent,requestCode, ActivityOptions.makeSceneTransitionAnimation(this)
.toBundle());
}else{
super.startActivityForResult(intent,requestCode);
}
// overridePendingTransition(R.anim.anim_enter_in, R.anim.anim_enter_out);
}*/
// @Override
// protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// super.onActivityResult(requestCode, resultCode, data);
// if (resultCode != RESULT_OK) return;
protected void toActivity(Class toClass) {
toActivity(toClass, -1);
}
protected void toActivity(Class toClass, int requestCode) {
Intent intent = new Intent(this, toClass);
if (requestCode != -1) {
startActivityForResult(intent, requestCode);
} else {
startActivity(intent);
}
}
public void callPhone(final String telephone) {
if (TextUtils.isEmpty(telephone)) return;
StringBuffer sb = new StringBuffer().append(getString(R.string.call)).append(telephone);
new AlertDialog.Builder(this).setMessage(sb.toString())
.setPositiveButton(getString(R.string.ensure), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + telephone));
if (ActivityCompat.checkSelfPermission(BaseActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
return;
}
BaseActivity.this.startActivity(intent);
}
}).setNegativeButton(getString(R.string.cancel), null).create().show();
}
@Override
public void showLog(String msg) {
LTUtils.w(tag, msg);
}
@Override
public void showLog(int resId) {
showLog(getString(resId));
}
@Override
public void showToast(String msg) {
showLog(msg);
LTUtils.showToastShort(this, msg);
}
@Override
public void showToast(int resId) {
showToast(getString(resId));
}
@Override
public void showLoading(String text) {
if (mProgressDialogs != null) {
mProgressDialogs.showDialog(text);
}
}
@Override
public void showLoading() {
showLoading("");
}
@Override
public void dismissLoading() {
if (mProgressDialogs != null) {
mProgressDialogs.closeDialog();
}
}
@Override
public void onSucceed() {
dismissLoading();
}
@Override
public void onFailed() {
dismissLoading();
}
@Override
public void onFailed(Throwable throwable) {
dismissLoading();
showLog(throwable.getMessage() + throwable.getCause());
}
public void showSnackbar(String content, int duration) {
if (duration != Snackbar.LENGTH_SHORT && duration != Snackbar.LENGTH_LONG)
return;
Snackbar.make(mFrameContent, content, duration).show();
}
/**
*
*
* @param second
*/
protected void countDown(int second, final CountDownTimeListener listener) {
if (second <= 0) return;
countDownTimer = new CountDownTimer(second * 1000, 1000) {
@Override
public void onTick(long millisUntilFinished) {
int secondUntilFinished = Math.round(millisUntilFinished / 1000);
if (listener != null)
listener.onCountDownTick(secondUntilFinished);
}
@Override
public void onFinish() {
if (listener != null)
listener.onCountDownFinish();
}
};
countDownTimer.start();
}
public interface CountDownTimeListener {
/**
*
*
* @param secondUntilFinished
*/
void onCountDownTick(int secondUntilFinished);
void onCountDownFinish();
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public void animCircularReveal(View view, int centerX, int centerY, float startRadius, float endRadius, int seconds) {
Animator anim = ViewAnimationUtils.createCircularReveal(view, centerX, centerY, startRadius, endRadius);
anim.setDuration(seconds * 1000);
anim.start();
}
private void clearMemory() {
ActivityManager activityManger = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> appList = activityManger.getRunningAppProcesses();
if (appList != null) {
for (int i = 0; i < appList.size(); i++) {
ActivityManager.RunningAppProcessInfo appInfo = appList.get(i);
String[] pkgList = appInfo.pkgList;
if (appInfo.importance > ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE) {
for (int j = 0; j < pkgList.length; j++) {
activityManger.killBackgroundProcesses(pkgList[j]);
}
}
}
}
}
/**
* UI
*
* @param showStatus
* @param showNavigation
* @param couldCapture
*/
protected void setTranslucentSystemUI(boolean showStatus, boolean showNavigation, boolean couldCapture) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
Window window = getWindow();
if (!showStatus) {
window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
}
if (!showNavigation) {
window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
}
if (!couldCapture) {
window.addFlags(WindowManager.LayoutParams.FLAG_SECURE);
}
}
}
String[] dangerousPermissions = {
Manifest.permission.WRITE_EXTERNAL_STORAGE
, Manifest.permission.CAMERA
, Manifest.permission.WRITE_CONTACTS
, Manifest.permission.CALL_PHONE
, Manifest.permission.SEND_SMS
, Manifest.permission.RECORD_AUDIO
, Manifest.permission.ACCESS_FINE_LOCATION
, Manifest.permission.BODY_SENSORS// 7 SDK 20
, Manifest.permission.WRITE_CALENDAR
};
void requestPermission(String... permissions) {
if (permissions.length > 1) {
ActivityCompat.requestPermissions(this, permissions, REQUEST_CODE_PERMISSIONS);
} else {
ActivityCompat.requestPermissions(this, permissions, REQUEST_CODE_PERMISSION);
}
}
protected void requestPermission(PermissionResultListener listener, String... permissions) {
permissionResultListener = listener;
requestPermission(permissions);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_CODE_PERMISSION) {
if (grantResults.length == 0) return;
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (permissionResultListener != null)
permissionResultListener.onSinglePermissionGranted(permissions[0]);
} else {
if (!ActivityCompat.shouldShowRequestPermissionRationale(this, permissions[0])) {
showSnackbar(",,", Snackbar.LENGTH_LONG);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("?").setPositiveButton("", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
getAppDetailSettingIntent();
}
}).setNegativeButton("", null).create().show();
} else {
if (permissionResultListener != null)
permissionResultListener.onSinglePermissionDenied(permissions[0]);
}
}
}
if (requestCode == REQUEST_CODE_PERMISSIONS) {
if (grantResults.length == 0) return;
List<String> deniedPermissions = new ArrayList<>();
for (int i = 0; i < permissions.length; i++) {
if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
deniedPermissions.add(permissions[i]);
}
}
if (deniedPermissions.size() != 0) {
if (permissionResultListener != null)
permissionResultListener.onPermissionsDenied(deniedPermissions);
} else {
if (permissionResultListener != null)
permissionResultListener.onPermissionsGrantedAll();
}
}
}
PermissionResultListener permissionResultListener;
interface PermissionResultListener {
void onSinglePermissionDenied(String permission);
void onSinglePermissionGranted(String permission);
void onPermissionsGrantedAll();
void onPermissionsDenied(List<String> deniedPermissions);
}
private void getAppDetailSettingIntent() {
Intent localIntent = new Intent();
localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (Build.VERSION.SDK_INT >= 9) {
localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
localIntent.setData(Uri.fromParts("package", getPackageName(), null));
} else if (Build.VERSION.SDK_INT <= 8) {
localIntent.setAction(Intent.ACTION_VIEW);
localIntent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
localIntent.putExtra("com.android.settings.ApplicationPkgName", getPackageName());
}
startActivity(localIntent);
}
public void setToolbar() {
if (findViewById(R.id.layout_toolbar_tb) == null) return;
if (this instanceof AppCompatActivity) {
Toolbar toolbar = (Toolbar) findViewById(R.id.layout_toolbar_tb);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
android.widget.Toolbar toolbar = (android.widget.Toolbar) findViewById(R.id.layout_toolbar_tb);
setActionBar(toolbar);
getActionBar().setDisplayShowTitleEnabled(false);
}
}
setActivityTitle(getTitle());
findViewById(R.id.layout_toolbar_iv_back).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
public void setToolbar(int visibility) {
if (findViewById(R.id.layout_toolbar_tb) == null) return;
findViewById(R.id.layout_toolbar_tb).setVisibility(visibility);
if (this instanceof AppCompatActivity) {
Toolbar toolbar = (Toolbar) findViewById(R.id.layout_toolbar_tb);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
android.widget.Toolbar toolbar = (android.widget.Toolbar) findViewById(R.id.layout_toolbar_tb);
setActionBar(toolbar);
getActionBar().setDisplayShowTitleEnabled(false);
}
}
if (getTitle() != null) {
setActivityTitle(getTitle());
}
findViewById(R.id.layout_toolbar_iv_back).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
protected void setActivityTitle(CharSequence charSequence) {
((TextView) findViewById(R.id.layout_toolbar_tv_title)).setText(charSequence);
}
protected void setRightIcon(@DrawableRes int resId) {
setRightIcon(resId, View.VISIBLE);
}
protected void setRightIcon(@DrawableRes int resId, int visibility) {
setRightIcon(resId, visibility, null);
}
protected void setRightIcon(@DrawableRes int resId, int visibility, View.OnClickListener onClickListener) {
if (resId != 0) {
if (onClickListener != null) {
findViewById(R.id.layout_toolbar_iv_right).setOnClickListener(onClickListener);
}
findViewById(R.id.layout_toolbar_iv_right).setVisibility(visibility);
((ImageView) findViewById(R.id.layout_toolbar_iv_right)).setImageResource(resId);
}
}
protected void setRightText(String content) {
setRightText(content, View.VISIBLE);
}
protected void setRightText(String content, int visibility) {
setRightText(content, visibility, null);
}
protected void setRightText(String content, int visibility, View.OnClickListener onClickListener) {
if (!TextUtils.isEmpty(content)) {
((TextView) findViewById(R.id.layout_toolbar_tv_right)).setText(content);
findViewById(R.id.layout_toolbar_tv_right).setVisibility(visibility == View.VISIBLE ? View.VISIBLE : View.GONE);
findViewById(R.id.layout_toolbar_iv_right).setVisibility(visibility == View.VISIBLE ? View.GONE : View.VISIBLE);
if (onClickListener != null) {
findViewById(R.id.layout_toolbar_tv_right).setOnClickListener(onClickListener);
}
}
}
private void initTheme() {
DayNightHelper helper = new DayNightHelper(this);
if (helper.isDay()) {
setTheme(R.style.AppTheme);
} else {
setTheme(R.style.AppTheme_Night);
}
}
private void toggleThemeSetting() {
DayNightHelper helper = new DayNightHelper(this);
if (helper.isDay()) {
helper.setMode(DayNight.NIGHT);
setTheme(R.style.AppTheme_Night);
} else {
helper.setMode(DayNight.DAY);
setTheme(R.style.AppTheme);
}
}
private void RefreshUIForChangeTheme() {
TypedValue background = new TypedValue();
TypedValue textColor = new TypedValue();
Resources.Theme theme = getTheme();
theme.resolveAttribute(R.attr.clock_background, background, true);
theme.resolveAttribute(R.attr.clock_textColor, textColor, true);
if (textViews.size() > 0) {
for (TextView textView : textViews) {
textView.setBackgroundResource(background.resourceId);
textView.setTextColor(textColor.resourceId);
}
}
if (viewGroups.size() > 0) {
for (ViewGroup viewGroup : viewGroups) {
viewGroup.setBackgroundResource(background.resourceId);
}
}
if (adapterViews.size() > 0) {
//todo adapterViews
}
if (recyclerViews.size() > 0) {
//todo recyclerViews
}
//RecyclerView
// int childCount = mRecyclerView.getChildCount();
// for (int childIndex = 0; childIndex < childCount; childIndex++) {
// ViewGroup childView = (ViewGroup) mRecyclerView.getChildAt(childIndex);
// childView.setBackgroundResource(background.resourceId);
// View infoLayout = childView.findViewById(R.id.info_layout);
// infoLayout.setBackgroundResource(background.resourceId);
// TextView nickName = (TextView) childView.findViewById(R.id.tv_nickname);
// nickName.setBackgroundResource(background.resourceId);
// nickName.setTextColor(resources.getColor(textColor.resourceId));
// TextView motto = (TextView) childView.findViewById(R.id.tv_motto);
// motto.setBackgroundResource(background.resourceId);
// motto.setTextColor(resources.getColor(textColor.resourceId));
// // RecyclerView Pool Item
// //ListView AbsListView RecycleBin clear
// Class<RecyclerView> recyclerViewClass = RecyclerView.class;
// try {
// Field declaredField = recyclerViewClass.getDeclaredField("mRecycler");
// declaredField.setAccessible(true);
// Method declaredMethod = Class.forName(RecyclerView.Recycler.class.getName()).getDeclaredMethod("clear", (Class<?>[]) new Class[0]);
// declaredMethod.setAccessible(true);
// declaredMethod.invoke(declaredField.get(mRecyclerView), new Object[0]);
// RecyclerView.RecycledViewPool recycledViewPool = mRecyclerView.getRecycledViewPool();
// recycledViewPool.clear();
// } catch (NoSuchFieldException e) {
// e.printStackTrace();
// } catch (ClassNotFoundException e) {
// e.printStackTrace();
// } catch (NoSuchMethodException e) {
// e.printStackTrace();
// } catch (InvocationTargetException e) {
// e.printStackTrace();
// e.printStackTrace();
refreshStatusBar();
}
/**
* StatusBar
*/
private void refreshStatusBar() {
if (Build.VERSION.SDK_INT >= 21) {
TypedValue typedValue = new TypedValue();
Resources.Theme theme = getTheme();
theme.resolveAttribute(R.attr.colorPrimary, typedValue, true);
getWindow().setStatusBarColor(getResources().getColor(typedValue.resourceId));
}
}
private void showAnimation() {
final View decorView = getWindow().getDecorView();
Bitmap cacheBitmap = getCacheBitmapFromView(decorView);
if (decorView instanceof ViewGroup && cacheBitmap != null) {
final View view = new View(this);
view.setBackgroundDrawable(new BitmapDrawable(getResources(), cacheBitmap));
ViewGroup.LayoutParams layoutParam = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT);
((ViewGroup) decorView).addView(view, layoutParam);
ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(view, "alpha", 1f, 0f);
objectAnimator.setDuration(300);
objectAnimator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
((ViewGroup) decorView).removeView(view);
}
});
objectAnimator.start();
}
}
/**
* View
*
* @param view
* @return
*/
private Bitmap getCacheBitmapFromView(View view) {
final boolean drawingCacheEnabled = true;
view.setDrawingCacheEnabled(drawingCacheEnabled);
view.buildDrawingCache(drawingCacheEnabled);
final Bitmap drawingCache = view.getDrawingCache();
Bitmap bitmap;
if (drawingCache != null) {
bitmap = Bitmap.createBitmap(drawingCache);
view.setDrawingCacheEnabled(false);
} else {
bitmap = null;
}
return bitmap;
}
public void changeTheme() {
showAnimation();
toggleThemeSetting();
RefreshUIForChangeTheme();
}
/**
* Activity
*/
public void onSplashCreateTaskRootJudgment() {
if (!isTaskRoot()) {
Intent intent = getIntent();
String action = intent.getAction();
if (intent.hasCategory(Intent.CATEGORY_LAUNCHER) && action != null && action.equals(Intent.ACTION_MAIN)) {
finish();
}
}
}
/**
* EventBus
*
* @param enable
*/
protected void setEventbusEnable(boolean enable) {
eventbusEnable = enable;
initEventBus();
}
public static boolean isVisBottom(RecyclerView recyclerView) {
LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
//position
int lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition();
int visibleItemCount = layoutManager.getChildCount();
//RecyclerView
int totalItemCount = layoutManager.getItemCount();
//RecyclerView
int state = recyclerView.getScrollState();
if (visibleItemCount > 0 && lastVisibleItemPosition == totalItemCount - 1 && state == recyclerView.SCROLL_STATE_IDLE) {
return true;
} else {
return false;
}
}
}
|
package de.dakror.vloxlands.game.entity;
import java.util.UUID;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.g3d.Environment;
import com.badlogic.gdx.graphics.g3d.Model;
import com.badlogic.gdx.graphics.g3d.ModelBatch;
import com.badlogic.gdx.graphics.g3d.ModelInstance;
import com.badlogic.gdx.graphics.g3d.utils.AnimationController;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType;
import com.badlogic.gdx.math.Matrix4;
import com.badlogic.gdx.math.Quaternion;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.math.collision.BoundingBox;
import de.dakror.vloxlands.Vloxlands;
import de.dakror.vloxlands.game.world.World;
import de.dakror.vloxlands.util.base.EntityBase;
import de.dakror.vloxlands.util.event.EventDispatcher;
/**
* @author Dakror
*/
public abstract class Entity extends EntityBase
{
public static final int LINES[][] = { { 0, 1 }, { 0, 3 }, { 0, 4 }, { 6, 7 }, { 6, 5 }, { 6, 2 }, { 1, 5 }, { 2, 3 }, { 4, 5 }, { 3, 7 }, { 1, 2 }, { 7, 4 } };
protected Matrix4 transform;
public ModelInstance modelInstance;
protected int id;
protected String name;
protected float weight;
protected float uplift;
public boolean inFrustum;
public boolean hovered;
public boolean wasSelected;
public boolean selected;
protected boolean markedForRemoval;
protected BoundingBox boundingBox;
protected AnimationController animationController;
public final Vector3 posCache = new Vector3();
public final Quaternion rotCache = new Quaternion();
public Entity(float x, float y, float z, String model)
{
id = UUID.randomUUID().hashCode();
modelInstance = new ModelInstance(Vloxlands.assets.get(model, Model.class));
modelInstance.calculateBoundingBox(boundingBox = new BoundingBox());
modelInstance.transform.translate(x, y, z).translate(boundingBox.getDimensions().cpy().scl(0.5f));
animationController = new AnimationController(modelInstance);
markedForRemoval = false;
transform = modelInstance.transform;
transform.getTranslation(posCache);
EventDispatcher.addListener(this);
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public float getWeight()
{
return weight;
}
public void setWeight(float weight)
{
this.weight = weight;
}
public float getUplift()
{
return uplift;
}
public void setUplift(float uplift)
{
this.uplift = uplift;
}
public Matrix4 getTransform()
{
return transform;
}
public int getId()
{
return id;
}
public boolean isMarkedForRemoval()
{
return markedForRemoval;
}
@Override
public void tick(int tick)
{
transform.getTranslation(posCache);
transform.getRotation(rotCache);
inFrustum = Vloxlands.camera.frustum.boundsInFrustum(boundingBox.getCenter().x + posCache.x, boundingBox.getCenter().y + posCache.y, boundingBox.getCenter().z + posCache.z, boundingBox.getDimensions().x / 2, boundingBox.getDimensions().y / 2, boundingBox.getDimensions().z / 2);
}
public void getWorldBoundingBox(BoundingBox bb)
{
bb.min.set(boundingBox.min).add(posCache);
bb.max.set(boundingBox.max).add(posCache);
bb.set(bb.min, bb.max);
}
public void render(ModelBatch batch, Environment environment)
{
batch.render(modelInstance, environment);
renderAdditional(batch, environment);
if (hovered || selected)
{
Gdx.gl.glEnable(GL20.GL_DEPTH_TEST);
Gdx.gl.glLineWidth(selected ? 3 : 2);
Vloxlands.shapeRenderer.setProjectionMatrix(Vloxlands.camera.combined);
Vloxlands.shapeRenderer.identity();
Vloxlands.shapeRenderer.translate(posCache.x, posCache.y - boundingBox.getDimensions().y / 2 + boundingBox.getCenter().y + World.gap, posCache.z);
Vloxlands.shapeRenderer.rotate(1, 0, 0, 90);
Vloxlands.shapeRenderer.begin(ShapeType.Line);
Vloxlands.shapeRenderer.setColor(World.SELECTION);
Vloxlands.shapeRenderer.rect(-(float) Math.ceil(boundingBox.getDimensions().x) / 2, -(float) Math.ceil(boundingBox.getDimensions().z) / 2, (float) Math.ceil(boundingBox.getDimensions().x), (float) Math.ceil(boundingBox.getDimensions().z));
Vloxlands.shapeRenderer.end();
Gdx.gl.glLineWidth(1);
}
if (Vloxlands.debug)
{
Gdx.gl.glEnable(GL20.GL_DEPTH_TEST);
Vloxlands.shapeRenderer.setProjectionMatrix(Vloxlands.camera.combined);
Vloxlands.shapeRenderer.identity();
Vloxlands.shapeRenderer.translate(posCache.x, posCache.y, posCache.z);
Vloxlands.shapeRenderer.begin(ShapeType.Line);
Vloxlands.shapeRenderer.setColor(Color.RED);
Vector3[] crn = boundingBox.getCorners();
for (int i = 0; i < LINES.length; i++)
{
Vector3 v = crn[LINES[i][0]];
Vector3 w = crn[LINES[i][1]];
Vloxlands.shapeRenderer.line(v.x, v.y, v.z, w.x, w.y, w.z, Color.RED, Color.RED);
}
Vloxlands.shapeRenderer.end();
}
}
public void renderAdditional(ModelBatch batch, Environment environment)
{}
public void update()
{
animationController.update(Gdx.graphics.getDeltaTime());
}
@Override
public void dispose()
{
EventDispatcher.removeListener(this);
}
// -- events -- //
public void onSpawn()
{}
// -- abstracts -- //
}
|
package edu.csh.cshwebnews.activities;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import net.danlew.android.joda.JodaTimeAndroid;
import edu.csh.cshwebnews.R;
import edu.csh.cshwebnews.ScrimInsetsFrameLayout;
import edu.csh.cshwebnews.Utility;
import edu.csh.cshwebnews.adapters.DrawerListAdapter;
import edu.csh.cshwebnews.database.WebNewsContract;
import edu.csh.cshwebnews.fragments.PostListFragment;
import edu.csh.cshwebnews.network.WebNewsSyncAdapter;
public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor> {
final int NEWSGROUP_LOADER = 1;
DrawerListAdapter mListAdapter;
ScrimInsetsFrameLayout mInsetsFrameLayout;
ListView drawerListView;
ActionBarDrawerToggle drawerToggle;
Toolbar toolBar;
DrawerLayout drawer;
String newsgroupNameState;
Fragment currentFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebNewsSyncAdapter.syncImmediately(getApplicationContext(), new Bundle());
JodaTimeAndroid.init(this);
toolBar = (Toolbar) findViewById(R.id.tool_bar);
setSupportActionBar(toolBar);
createFragment(savedInstanceState);
createHeader();
createNavigationDrawer();
getSupportLoaderManager().initLoader(NEWSGROUP_LOADER, null, this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString("name",newsgroupNameState);
getSupportFragmentManager().putFragment(outState, "currentFragment", currentFragment);
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
String sortOrder = WebNewsContract.NewsGroupEntry.NAME;
Uri newsgroupUri = WebNewsContract.NewsGroupEntry.CONTENT_URI;
return new CursorLoader(this,
newsgroupUri,
DrawerListAdapter.NEWSGROUP_COLUMNS,
null,
null,
sortOrder);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
mListAdapter.swapCursor(data);
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
mListAdapter.swapCursor(null);
}
private void selectNewsgroup(final long id, int position, final View view) {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
getSupportFragmentManager().beginTransaction().remove(currentFragment).commit();
currentFragment = new PostListFragment();
Bundle args = new Bundle();
args.putString("newsgroup_id", String.valueOf(id));
args.putString("as_threads","false");
currentFragment.setArguments(args);
getSupportFragmentManager().beginTransaction().replace(R.id.frag_container, currentFragment).commit();
TextView newsgroup = (TextView) view.findViewById(R.id.drawer_list_newsgroup_textview);
getSupportActionBar().setTitle(newsgroup.getText());
newsgroupNameState = newsgroup.getText().toString();
}
}, 300);
}
private void createFragment(Bundle savedInstanceState) {
if(savedInstanceState != null){
currentFragment = getSupportFragmentManager().getFragment(savedInstanceState,"currentFragment");
newsgroupNameState = savedInstanceState.getString("name");
getSupportActionBar().setTitle(savedInstanceState.getString("name"));
} else {
currentFragment = new PostListFragment();
Bundle args = new Bundle();
args.putString("newsgroup_id", "null");
args.putString("as_threads","false");
currentFragment.setArguments(args);
getSupportFragmentManager().beginTransaction().replace(R.id.frag_container, currentFragment).commit();
newsgroupNameState = "Home";
getSupportActionBar().setTitle("Home");
}
}
private void createNavigationDrawer() {
mListAdapter = new DrawerListAdapter(this,null,0);
drawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
drawerListView.setItemChecked(position, true);
drawer.closeDrawer(mInsetsFrameLayout);
selectNewsgroup(id,position,view);
}
});
drawerListView.setAdapter(mListAdapter);
drawer = (DrawerLayout) findViewById(R.id.DrawerLayout);
drawer.setStatusBarBackground(R.color.csh_pink_dark);
drawerToggle = new ActionBarDrawerToggle(this,drawer,toolBar,R.string.app_name,R.string.app_name) {
@Override
public void onDrawerSlide(View drawerView, float slideOffset) {
if(drawerView != null){
super.onDrawerSlide(drawerView, 0);
} else {
super.onDrawerSlide(drawerView, slideOffset);
}
}
@Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
@Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
}
};
drawer.setDrawerListener(drawerToggle);
drawerToggle.syncState();
}
private void createHeader() {
mInsetsFrameLayout = (ScrimInsetsFrameLayout) findViewById(R.id.scrimInsetsFrameLayout);
drawerListView = (ListView) findViewById(R.id.drawer_listview);
ViewGroup header = (ViewGroup) getLayoutInflater().inflate(R.layout.drawer_header, drawerListView, false);
TextView username = (TextView) header.findViewById(R.id.drawer_header_name_textview);
TextView email = (TextView) header.findViewById(R.id.drawer_header_email_textview);
ImageView userImage = (ImageView) header.findViewById(R.id.drawer_header_user_imageview);
Cursor cur = getContentResolver().query(WebNewsContract.UserEntry.CONTENT_URI,null,null,null,null);
cur.moveToFirst();
username.setText(cur.getString(WebNewsContract.USER_COL_USERNAME));
String emailStr = cur.getString(WebNewsContract.USER_COL_EMAIL);
email.setText(emailStr);
String emailHash = Utility.md5Hex(emailStr);
Picasso.with(getApplicationContext())
.load("http:
.placeholder(R.drawable.placeholder)
.tag(this)
.into(userImage);
header.setEnabled(false);
header.setOnClickListener(null);
cur.close();
drawerListView.addHeaderView(header);
}
}
|
package nodomain.freeyourgadget.gadgetbridge.service.devices.zetime;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.net.Uri;
import android.widget.Toast;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.UUID;
import nodomain.freeyourgadget.gadgetbridge.GBApplication;
import nodomain.freeyourgadget.gadgetbridge.R;
import nodomain.freeyourgadget.gadgetbridge.database.DBHandler;
import nodomain.freeyourgadget.gadgetbridge.database.DBHelper;
import nodomain.freeyourgadget.gadgetbridge.deviceevents.GBDeviceEventBatteryInfo;
import nodomain.freeyourgadget.gadgetbridge.deviceevents.GBDeviceEventMusicControl;
import nodomain.freeyourgadget.gadgetbridge.deviceevents.GBDeviceEventVersionInfo;
import nodomain.freeyourgadget.gadgetbridge.devices.zetime.ZeTimeConstants;
import nodomain.freeyourgadget.gadgetbridge.devices.zetime.ZeTimeSampleProvider;
import nodomain.freeyourgadget.gadgetbridge.entities.ZeTimeActivitySample;
import nodomain.freeyourgadget.gadgetbridge.impl.GBDevice;
import nodomain.freeyourgadget.gadgetbridge.model.ActivityKind;
import nodomain.freeyourgadget.gadgetbridge.model.Alarm;
import nodomain.freeyourgadget.gadgetbridge.model.BatteryState;
import nodomain.freeyourgadget.gadgetbridge.model.CalendarEventSpec;
import nodomain.freeyourgadget.gadgetbridge.model.CallSpec;
import nodomain.freeyourgadget.gadgetbridge.model.CannedMessagesSpec;
import nodomain.freeyourgadget.gadgetbridge.model.MusicSpec;
import nodomain.freeyourgadget.gadgetbridge.model.MusicStateSpec;
import nodomain.freeyourgadget.gadgetbridge.model.NotificationSpec;
import nodomain.freeyourgadget.gadgetbridge.model.Weather;
import nodomain.freeyourgadget.gadgetbridge.model.WeatherSpec;
import nodomain.freeyourgadget.gadgetbridge.service.btle.AbstractBTLEDeviceSupport;
import nodomain.freeyourgadget.gadgetbridge.service.btle.GattService;
import nodomain.freeyourgadget.gadgetbridge.service.btle.TransactionBuilder;
import nodomain.freeyourgadget.gadgetbridge.service.btle.actions.SetDeviceStateAction;
import nodomain.freeyourgadget.gadgetbridge.util.GB;
public class ZeTimeDeviceSupport extends AbstractBTLEDeviceSupport {
private static final Logger LOG = LoggerFactory.getLogger(ZeTimeDeviceSupport.class);
private final GBDeviceEventBatteryInfo batteryCmd = new GBDeviceEventBatteryInfo();
private final GBDeviceEventVersionInfo versionCmd = new GBDeviceEventVersionInfo();
private final GBDeviceEventMusicControl musicCmd = new GBDeviceEventMusicControl();
private byte[] lastMsg;
private byte msgPart;
private int availableSleepData;
private int availableStepsData;
private int availableHeartRateData;
private int progressSteps;
private int progressSleep;
private int progressHeartRate;
private final int maxMsgLength = 20;
private boolean callIncoming = false;
private String songtitle = null;
private byte musicState = -1;
public byte[] music = null;
public byte volume = 50;
public BluetoothGattCharacteristic notifyCharacteristic = null;
public BluetoothGattCharacteristic writeCharacteristic = null;
public BluetoothGattCharacteristic ackCharacteristic = null;
public BluetoothGattCharacteristic replyCharacteristic = null;
public ZeTimeDeviceSupport(){
super(LOG);
addSupportedService(GattService.UUID_SERVICE_GENERIC_ACCESS);
addSupportedService(GattService.UUID_SERVICE_GENERIC_ATTRIBUTE);
addSupportedService(ZeTimeConstants.UUID_SERVICE_BASE);
addSupportedService(ZeTimeConstants.UUID_SERVICE_EXTEND);
addSupportedService(ZeTimeConstants.UUID_SERVICE_HEART_RATE);
}
@Override
protected TransactionBuilder initializeDevice(TransactionBuilder builder) {
LOG.info("Initializing");
msgPart = 0;
availableStepsData = 0;
availableHeartRateData = 0;
availableSleepData = 0;
progressSteps = 0;
progressSleep = 0;
progressHeartRate = 0;
builder.add(new SetDeviceStateAction(getDevice(), GBDevice.State.INITIALIZING, getContext()));
notifyCharacteristic = getCharacteristic(ZeTimeConstants.UUID_NOTIFY_CHARACTERISTIC);
writeCharacteristic = getCharacteristic(ZeTimeConstants.UUID_WRITE_CHARACTERISTIC);
ackCharacteristic = getCharacteristic(ZeTimeConstants.UUID_ACK_CHARACTERISTIC);
replyCharacteristic = getCharacteristic(ZeTimeConstants.UUID_REPLY_CHARACTERISTIC);
builder.notify(ackCharacteristic, true);
builder.notify(notifyCharacteristic, true);
requestDeviceInfo(builder);
requestBatteryInfo(builder);
requestActivityInfo(builder);
synchronizeTime(builder);
replyMsgToWatch(builder, new byte[]{ZeTimeConstants.CMD_PREAMBLE,
ZeTimeConstants.CMD_MUSIC_CONTROL,
ZeTimeConstants.CMD_REQUEST_RESPOND,
0x02,
0x00,
0x02,
volume,
ZeTimeConstants.CMD_END});
builder.add(new SetDeviceStateAction(getDevice(), GBDevice.State.INITIALIZED, getContext()));
LOG.info("Initialization Done");
return builder;
}
@Override
public void onSendConfiguration(String config) {
}
@Override
public void onDeleteCalendarEvent(byte type, long id) {
}
@Override
public void onHeartRateTest() {
}
@Override
public void onEnableRealtimeSteps(boolean enable) {
}
@Override
public void onFindDevice(boolean start) {
}
@Override
public boolean useAutoConnect() {
return false;
}
@Override
public void onSetHeartRateMeasurementInterval(int seconds) {
}
@Override
public void onSetAlarms(ArrayList<? extends Alarm> alarms) {
}
@Override
public void onAppConfiguration(UUID appUuid, String config, Integer id) {
}
@Override
public void onEnableHeartRateSleepSupport(boolean enable) {
}
@Override
public void onSetMusicInfo(MusicSpec musicSpec) {
songtitle = musicSpec.track;
if(musicState != -1) {
music = new byte[songtitle.getBytes(StandardCharsets.UTF_8).length + 7]; // 7 bytes for status and overhead
music[0] = ZeTimeConstants.CMD_PREAMBLE;
music[1] = ZeTimeConstants.CMD_MUSIC_CONTROL;
music[2] = ZeTimeConstants.CMD_REQUEST_RESPOND;
music[3] = (byte) ((songtitle.getBytes(StandardCharsets.UTF_8).length + 1) & 0xff);
music[4] = (byte) ((songtitle.getBytes(StandardCharsets.UTF_8).length + 1) >> 8);
music[5] = musicState;
System.arraycopy(songtitle.getBytes(StandardCharsets.UTF_8), 0, music, 6, songtitle.getBytes(StandardCharsets.UTF_8).length);
music[music.length - 1] = ZeTimeConstants.CMD_END;
if (music != null) {
try {
TransactionBuilder builder = performInitialized("setMusicStateInfo");
replyMsgToWatch(builder, music);
performConnected(builder.getTransaction());
} catch (IOException e) {
GB.toast(getContext(), "Error setting music state and info: " + e.getLocalizedMessage(), Toast.LENGTH_LONG, GB.ERROR);
}
}
}
}
@Override
public void onSetCallState(CallSpec callSpec) {
int subject_length = 0;
int notification_length = 0;
byte[] subject = null;
byte[] notification = null;
Calendar time = GregorianCalendar.getInstance();
byte[] datetimeBytes = new byte[]{
(byte) ((time.get(Calendar.YEAR) / 1000) + '0'),
(byte) (((time.get(Calendar.YEAR) / 100)%10) + '0'),
(byte) (((time.get(Calendar.YEAR) / 10)%10) + '0'),
(byte) ((time.get(Calendar.YEAR)%10) + '0'),
(byte) (((time.get(Calendar.MONTH)+1)/10) + '0'),
(byte) (((time.get(Calendar.MONTH)+1)%10) + '0'),
(byte) ((time.get(Calendar.DAY_OF_MONTH)/10) + '0'),
(byte) ((time.get(Calendar.DAY_OF_MONTH)%10) + '0'),
(byte) 'T',
(byte) ((time.get(Calendar.HOUR_OF_DAY)/10) + '0'),
(byte) ((time.get(Calendar.HOUR_OF_DAY)%10) + '0'),
(byte) ((time.get(Calendar.MINUTE)/10) + '0'),
(byte) ((time.get(Calendar.MINUTE)%10) + '0'),
(byte) ((time.get(Calendar.SECOND)/10) + '0'),
(byte) ((time.get(Calendar.SECOND)%10) + '0'),
};
if(callIncoming || (callSpec.command == CallSpec.CALL_INCOMING)) {
if (callSpec.command == CallSpec.CALL_INCOMING) {
if (callSpec.name != null) {
notification_length += callSpec.name.getBytes(StandardCharsets.UTF_8).length;
subject_length = callSpec.name.getBytes(StandardCharsets.UTF_8).length;
subject = new byte[subject_length];
System.arraycopy(callSpec.name.getBytes(StandardCharsets.UTF_8), 0, subject, 0, subject_length);
} else if (callSpec.number != null) {
notification_length += callSpec.number.getBytes(StandardCharsets.UTF_8).length;
subject_length = callSpec.number.getBytes(StandardCharsets.UTF_8).length;
subject = new byte[subject_length];
System.arraycopy(callSpec.number.getBytes(StandardCharsets.UTF_8), 0, subject, 0, subject_length);
}
notification_length += datetimeBytes.length + 10; // add message overhead
notification = new byte[notification_length];
notification[0] = ZeTimeConstants.CMD_PREAMBLE;
notification[1] = ZeTimeConstants.CMD_PUSH_EX_MSG;
notification[2] = ZeTimeConstants.CMD_SEND;
notification[3] = (byte) ((notification_length - 6) & 0xff);
notification[4] = (byte) ((notification_length - 6) >> 8);
notification[5] = ZeTimeConstants.NOTIFICATION_INCOME_CALL;
notification[6] = 1;
notification[7] = (byte) subject_length;
notification[8] = (byte) 0;
System.arraycopy(subject, 0, notification, 9, subject_length);
System.arraycopy(datetimeBytes, 0, notification, 9 + subject_length, datetimeBytes.length);
notification[notification_length - 1] = ZeTimeConstants.CMD_END;
callIncoming = true;
} else {
notification_length = datetimeBytes.length + 10; // add message overhead
notification = new byte[notification_length];
notification[0] = ZeTimeConstants.CMD_PREAMBLE;
notification[1] = ZeTimeConstants.CMD_PUSH_EX_MSG;
notification[2] = ZeTimeConstants.CMD_SEND;
notification[3] = (byte) ((notification_length - 6) & 0xff);
notification[4] = (byte) ((notification_length - 6) >> 8);
notification[5] = ZeTimeConstants.NOTIFICATION_CALL_OFF;
notification[6] = 1;
notification[7] = (byte) 0;
notification[8] = (byte) 0;
System.arraycopy(datetimeBytes, 0, notification, 9, datetimeBytes.length);
notification[notification_length - 1] = ZeTimeConstants.CMD_END;
callIncoming = false;
}
if(notification != null)
{
try {
TransactionBuilder builder = performInitialized("setCallState");
sendMsgToWatch(builder, notification);
performConnected(builder.getTransaction());
} catch (IOException e) {
GB.toast(getContext(), "Error set call state: " + e.getLocalizedMessage(), Toast.LENGTH_LONG, GB.ERROR);
}
}
}
}
@Override
public void onAppStart(UUID uuid, boolean start) {
}
@Override
public void onEnableRealtimeHeartRateMeasurement(boolean enable) {
}
@Override
public void onSetConstantVibration(int integer) {
}
@Override
public void onFetchRecordedData(int dataTypes) {
try {
TransactionBuilder builder = performInitialized("fetchActivityData");
requestActivityInfo(builder);
performConnected(builder.getTransaction());
} catch (IOException e) {
GB.toast(getContext(), "Error on fetching activity data: " + e.getLocalizedMessage(), Toast.LENGTH_LONG, GB.ERROR);
}
}
@Override
public void onTestNewFunction() {
}
@Override
public void onSetMusicState(MusicStateSpec stateSpec) {
musicState = stateSpec.state;
if(songtitle != null) {
music = new byte[songtitle.getBytes(StandardCharsets.UTF_8).length + 7]; // 7 bytes for status and overhead
music[0] = ZeTimeConstants.CMD_PREAMBLE;
music[1] = ZeTimeConstants.CMD_MUSIC_CONTROL;
music[2] = ZeTimeConstants.CMD_REQUEST_RESPOND;
music[3] = (byte) ((songtitle.getBytes(StandardCharsets.UTF_8).length + 1) & 0xff);
music[4] = (byte) ((songtitle.getBytes(StandardCharsets.UTF_8).length + 1) >> 8);
if (stateSpec.state == MusicStateSpec.STATE_PLAYING) {
music[5] = 0;
} else {
music[5] = 1;
}
System.arraycopy(songtitle.getBytes(StandardCharsets.UTF_8), 0, music, 6, songtitle.getBytes(StandardCharsets.UTF_8).length);
music[music.length - 1] = ZeTimeConstants.CMD_END;
if (music != null) {
try {
TransactionBuilder builder = performInitialized("setMusicStateInfo");
replyMsgToWatch(builder, music);
performConnected(builder.getTransaction());
} catch (IOException e) {
GB.toast(getContext(), "Error setting music state and info: " + e.getLocalizedMessage(), Toast.LENGTH_LONG, GB.ERROR);
}
}
}
}
@Override
public void onAddCalendarEvent(CalendarEventSpec calendarEventSpec) {
Calendar time = GregorianCalendar.getInstance();
byte[] CalendarEvent = new byte[calendarEventSpec.title.getBytes(StandardCharsets.UTF_8).length + 16]; // 26 bytes for calendar and overhead
time.setTimeInMillis(calendarEventSpec.timestamp);
CalendarEvent[0] = ZeTimeConstants.CMD_PREAMBLE;
CalendarEvent[1] = ZeTimeConstants.CMD_PUSH_CALENDAR_DAY;
CalendarEvent[2] = ZeTimeConstants.CMD_SEND;
CalendarEvent[3] = (byte)((calendarEventSpec.title.getBytes(StandardCharsets.UTF_8).length + 10) & 0xff);
CalendarEvent[4] = (byte)((calendarEventSpec.title.getBytes(StandardCharsets.UTF_8).length + 10) >> 8);
CalendarEvent[5] = (byte)(calendarEventSpec.type + 0x1);
CalendarEvent[6] = (byte)(time.get(Calendar.YEAR) & 0xff);
CalendarEvent[7] = (byte)(time.get(Calendar.YEAR) >> 8);
CalendarEvent[8] = (byte)(time.get(Calendar.MONTH)+1);
CalendarEvent[9] = (byte)time.get(Calendar.DAY_OF_MONTH);
CalendarEvent[10] = (byte) ((time.get(Calendar.HOUR_OF_DAY)/10) + '0');
CalendarEvent[11] = (byte) ((time.get(Calendar.HOUR_OF_DAY)%10) + '0');
CalendarEvent[12] = (byte) ((time.get(Calendar.MINUTE)/10) + '0');
CalendarEvent[13] = (byte) ((time.get(Calendar.MINUTE)%10) + '0');
CalendarEvent[14] = (byte) calendarEventSpec.title.getBytes(StandardCharsets.UTF_8).length;
System.arraycopy(calendarEventSpec.title.getBytes(StandardCharsets.UTF_8), 0, CalendarEvent, 15, calendarEventSpec.title.getBytes(StandardCharsets.UTF_8).length);
CalendarEvent[CalendarEvent.length-1] = ZeTimeConstants.CMD_END;
if(CalendarEvent != null)
{
try {
TransactionBuilder builder = performInitialized("sendCalendarEvenr");
sendMsgToWatch(builder, CalendarEvent);
performConnected(builder.getTransaction());
} catch (IOException e) {
GB.toast(getContext(), "Error sending calendar event: " + e.getLocalizedMessage(), Toast.LENGTH_LONG, GB.ERROR);
}
}
}
@Override
public void onSetTime() {
try {
TransactionBuilder builder = performInitialized("synchronizeTime");
synchronizeTime(builder);
performConnected(builder.getTransaction());
} catch (IOException e) {
GB.toast(getContext(), "Error setting the time: " + e.getLocalizedMessage(), Toast.LENGTH_LONG, GB.ERROR);
}
}
@Override
public void onAppDelete(UUID uuid) {
}
@Override
public void onAppInfoReq() {
}
@Override
public void onSetCannedMessages(CannedMessagesSpec cannedMessagesSpec) {
}
@Override
public void onReboot() {
}
@Override
public void onScreenshotReq() {
}
@Override
public void onSendWeather(WeatherSpec weatherSpec) {
byte[] weather = new byte[weatherSpec.location.getBytes(StandardCharsets.UTF_8).length + 26]; // 26 bytes for weatherdata and overhead
weather[0] = ZeTimeConstants.CMD_PREAMBLE;
weather[1] = ZeTimeConstants.CMD_PUSH_WEATHER_DATA;
weather[2] = ZeTimeConstants.CMD_SEND;
weather[3] = (byte)((weatherSpec.location.getBytes(StandardCharsets.UTF_8).length + 20) & 0xff);
weather[4] = (byte)((weatherSpec.location.getBytes(StandardCharsets.UTF_8).length + 20) >> 8);
weather[5] = 0; // celsius
weather[6] = (byte)(weatherSpec.currentTemp - 273);
weather[7] = (byte)(weatherSpec.todayMinTemp - 273);
weather[8] = (byte)(weatherSpec.todayMaxTemp - 273);
weather[9] = Weather.mapToZeTimeCondition(weatherSpec.currentConditionCode);
for(int forecast = 0; forecast < 3; forecast++) {
weather[10+(forecast*5)] = 0; // celsius
weather[11+(forecast*5)] = (byte) 0xff;
weather[12+(forecast*5)] = (byte) (weatherSpec.forecasts.get(forecast).minTemp - 273);
weather[13+(forecast*5)] = (byte) (weatherSpec.forecasts.get(forecast).maxTemp - 273);
weather[14+(forecast*5)] = Weather.mapToZeTimeCondition(weatherSpec.forecasts.get(forecast).conditionCode);
}
System.arraycopy(weatherSpec.location.getBytes(StandardCharsets.UTF_8), 0, weather, 25, weatherSpec.location.getBytes(StandardCharsets.UTF_8).length);
weather[weather.length-1] = ZeTimeConstants.CMD_END;
if(weather != null)
{
try {
TransactionBuilder builder = performInitialized("sendWeahter");
sendMsgToWatch(builder, weather);
performConnected(builder.getTransaction());
} catch (IOException e) {
GB.toast(getContext(), "Error sending weather: " + e.getLocalizedMessage(), Toast.LENGTH_LONG, GB.ERROR);
}
}
}
@Override
public void onAppReorder(UUID[] uuids) {
}
@Override
public void onInstallApp(Uri uri) {
}
@Override
public void onDeleteNotification(int id) {
}
@Override
public void onNotification(NotificationSpec notificationSpec) {
int subject_length = 0;
int body_length = notificationSpec.body.getBytes(StandardCharsets.UTF_8).length;
if(body_length > 256)
{
body_length = 256;
}
int notification_length = body_length;
byte[] subject = null;
byte[] notification = null;
Calendar time = GregorianCalendar.getInstance();
byte[] datetimeBytes = new byte[]{
(byte) ((time.get(Calendar.YEAR) / 1000) + '0'),
(byte) (((time.get(Calendar.YEAR) / 100)%10) + '0'),
(byte) (((time.get(Calendar.YEAR) / 10)%10) + '0'),
(byte) ((time.get(Calendar.YEAR)%10) + '0'),
(byte) (((time.get(Calendar.MONTH)+1)/10) + '0'),
(byte) (((time.get(Calendar.MONTH)+1)%10) + '0'),
(byte) ((time.get(Calendar.DAY_OF_MONTH)/10) + '0'),
(byte) ((time.get(Calendar.DAY_OF_MONTH)%10) + '0'),
(byte) 'T',
(byte) ((time.get(Calendar.HOUR_OF_DAY)/10) + '0'),
(byte) ((time.get(Calendar.HOUR_OF_DAY)%10) + '0'),
(byte) ((time.get(Calendar.MINUTE)/10) + '0'),
(byte) ((time.get(Calendar.MINUTE)%10) + '0'),
(byte) ((time.get(Calendar.SECOND)/10) + '0'),
(byte) ((time.get(Calendar.SECOND)%10) + '0'),
};
switch(notificationSpec.type)
{
case GENERIC_SMS:
if (notificationSpec.sender != null)
{
notification_length += notificationSpec.sender.getBytes(StandardCharsets.UTF_8).length;
subject_length = notificationSpec.sender.getBytes(StandardCharsets.UTF_8).length;
subject = new byte[subject_length];
System.arraycopy(notificationSpec.sender.getBytes(StandardCharsets.UTF_8), 0, subject, 0, subject_length);
} else if(notificationSpec.phoneNumber != null)
{
notification_length += notificationSpec.phoneNumber.getBytes(StandardCharsets.UTF_8).length;
subject_length = notificationSpec.phoneNumber.getBytes(StandardCharsets.UTF_8).length;
subject = new byte[subject_length];
System.arraycopy(notificationSpec.phoneNumber.getBytes(StandardCharsets.UTF_8), 0, subject, 0, subject_length);
}
notification_length += datetimeBytes.length + 10; // add message overhead
notification = new byte[notification_length];
notification[0] = ZeTimeConstants.CMD_PREAMBLE;
notification[1] = ZeTimeConstants.CMD_PUSH_EX_MSG;
notification[2] = ZeTimeConstants.CMD_SEND;
notification[3] = (byte)((notification_length-6) & 0xff);
notification[4] = (byte)((notification_length-6) >> 8);
notification[5] = ZeTimeConstants.NOTIFICATION_SMS;
notification[6] = 1;
notification[7] = (byte)subject_length;
notification[8] = (byte)body_length;
System.arraycopy(subject, 0, notification, 9, subject_length);
System.arraycopy(notificationSpec.body.getBytes(StandardCharsets.UTF_8), 0, notification, 9+subject_length, body_length);
System.arraycopy(datetimeBytes, 0, notification, 9+subject_length+body_length, datetimeBytes.length);
notification[notification_length-1] = ZeTimeConstants.CMD_END;
break;
case GENERIC_PHONE:
if (notificationSpec.sender != null)
{
notification_length += notificationSpec.sender.getBytes(StandardCharsets.UTF_8).length;
subject_length = notificationSpec.sender.getBytes(StandardCharsets.UTF_8).length;
subject = new byte[subject_length];
System.arraycopy(notificationSpec.sender.getBytes(StandardCharsets.UTF_8), 0, subject, 0, subject_length);
} else if(notificationSpec.phoneNumber != null)
{
notification_length += notificationSpec.phoneNumber.getBytes(StandardCharsets.UTF_8).length;
subject_length = notificationSpec.phoneNumber.getBytes(StandardCharsets.UTF_8).length;
subject = new byte[subject_length];
System.arraycopy(notificationSpec.phoneNumber.getBytes(StandardCharsets.UTF_8), 0, subject, 0, subject_length);
}
notification_length += datetimeBytes.length + 10; // add message overhead
notification = new byte[notification_length];
notification[0] = ZeTimeConstants.CMD_PREAMBLE;
notification[1] = ZeTimeConstants.CMD_PUSH_EX_MSG;
notification[2] = ZeTimeConstants.CMD_SEND;
notification[3] = (byte)((notification_length-6) & 0xff);
notification[4] = (byte)((notification_length-6) >> 8);
notification[5] = ZeTimeConstants.NOTIFICATION_MISSED_CALL;
notification[6] = 1;
notification[7] = (byte)subject_length;
notification[8] = (byte)body_length;
System.arraycopy(subject, 0, notification, 9, subject_length);
System.arraycopy(notificationSpec.body.getBytes(StandardCharsets.UTF_8), 0, notification, 9+subject_length, body_length);
System.arraycopy(datetimeBytes, 0, notification, 9+subject_length+body_length, datetimeBytes.length);
notification[notification_length-1] = ZeTimeConstants.CMD_END;
break;
case GMAIL:
case GOOGLE_INBOX:
case MAILBOX:
case OUTLOOK:
case YAHOO_MAIL:
case GENERIC_EMAIL:
if (notificationSpec.sender != null)
{
notification_length += notificationSpec.sender.getBytes(StandardCharsets.UTF_8).length;
subject_length = notificationSpec.sender.getBytes(StandardCharsets.UTF_8).length;
subject = new byte[subject_length];
System.arraycopy(notificationSpec.sender.getBytes(StandardCharsets.UTF_8), 0, subject, 0, subject_length);
} else if(notificationSpec.subject != null)
{
notification_length += notificationSpec.subject.getBytes(StandardCharsets.UTF_8).length;
subject_length = notificationSpec.subject.getBytes(StandardCharsets.UTF_8).length;
subject = new byte[subject_length];
System.arraycopy(notificationSpec.subject.getBytes(StandardCharsets.UTF_8), 0, subject, 0, subject_length);
}
notification_length += datetimeBytes.length + 10; // add message overhead
notification = new byte[notification_length];
notification[0] = ZeTimeConstants.CMD_PREAMBLE;
notification[1] = ZeTimeConstants.CMD_PUSH_EX_MSG;
notification[2] = ZeTimeConstants.CMD_SEND;
notification[3] = (byte)((notification_length-6) & 0xff);
notification[4] = (byte)((notification_length-6) >> 8);
notification[5] = ZeTimeConstants.NOTIFICATION_EMAIL;
notification[6] = 1;
notification[7] = (byte)subject_length;
notification[8] = (byte)body_length;
System.arraycopy(subject, 0, notification, 9, subject_length);
System.arraycopy(notificationSpec.body.getBytes(StandardCharsets.UTF_8), 0, notification, 9+subject_length, body_length);
System.arraycopy(datetimeBytes, 0, notification, 9+subject_length+body_length, datetimeBytes.length);
notification[notification_length-1] = ZeTimeConstants.CMD_END;
break;
case CONVERSATIONS:
case FACEBOOK_MESSENGER:
case RIOT:
case SIGNAL:
case TELEGRAM:
case THREEMA:
case KONTALK:
case ANTOX:
case WHATSAPP:
case GOOGLE_MESSENGER:
case GOOGLE_HANGOUTS:
case HIPCHAT:
case SKYPE:
case WECHAT:
case KIK:
case KAKAO_TALK:
case SLACK:
case LINE:
case VIBER:
if (notificationSpec.sender != null)
{
notification_length += notificationSpec.sender.getBytes(StandardCharsets.UTF_8).length;
subject_length = notificationSpec.sender.getBytes(StandardCharsets.UTF_8).length;
subject = new byte[subject_length];
System.arraycopy(notificationSpec.sender.getBytes(StandardCharsets.UTF_8), 0, subject, 0, subject_length);
} else if(notificationSpec.subject != null)
{
notification_length += notificationSpec.subject.getBytes(StandardCharsets.UTF_8).length;
subject_length = notificationSpec.subject.getBytes(StandardCharsets.UTF_8).length;
subject = new byte[subject_length];
System.arraycopy(notificationSpec.subject.getBytes(StandardCharsets.UTF_8), 0, subject, 0, subject_length);
}
notification_length += datetimeBytes.length + 10; // add message overhead
notification = new byte[notification_length];
notification[0] = ZeTimeConstants.CMD_PREAMBLE;
notification[1] = ZeTimeConstants.CMD_PUSH_EX_MSG;
notification[2] = ZeTimeConstants.CMD_SEND;
notification[3] = (byte)((notification_length-6) & 0xff);
notification[4] = (byte)((notification_length-6) >> 8);
notification[5] = ZeTimeConstants.NOTIFICATION_MESSENGER;
notification[6] = 1;
notification[7] = (byte)subject_length;
notification[8] = (byte)body_length;
System.arraycopy(subject, 0, notification, 9, subject_length);
System.arraycopy(notificationSpec.body.getBytes(StandardCharsets.UTF_8), 0, notification, 9+subject_length, body_length);
System.arraycopy(datetimeBytes, 0, notification, 9+subject_length+body_length, datetimeBytes.length);
notification[notification_length-1] = ZeTimeConstants.CMD_END;
break;
case FACEBOOK:
case TWITTER:
case SNAPCHAT:
case INSTAGRAM:
case LINKEDIN:
if (notificationSpec.sender != null)
{
notification_length += notificationSpec.sender.getBytes(StandardCharsets.UTF_8).length;
subject_length = notificationSpec.sender.getBytes(StandardCharsets.UTF_8).length;
subject = new byte[subject_length];
System.arraycopy(notificationSpec.sender.getBytes(StandardCharsets.UTF_8), 0, subject, 0, subject_length);
} else if(notificationSpec.subject != null)
{
notification_length += notificationSpec.subject.getBytes(StandardCharsets.UTF_8).length;
subject_length = notificationSpec.subject.getBytes(StandardCharsets.UTF_8).length;
subject = new byte[subject_length];
System.arraycopy(notificationSpec.subject.getBytes(StandardCharsets.UTF_8), 0, subject, 0, subject_length);
}
notification_length += datetimeBytes.length + 10; // add message overhead
notification = new byte[notification_length];
notification[0] = ZeTimeConstants.CMD_PREAMBLE;
notification[1] = ZeTimeConstants.CMD_PUSH_EX_MSG;
notification[2] = ZeTimeConstants.CMD_SEND;
notification[3] = (byte)((notification_length-6) & 0xff);
notification[4] = (byte)((notification_length-6) >> 8);
notification[5] = ZeTimeConstants.NOTIFICATION_SOCIAL;
notification[6] = 1;
notification[7] = (byte)subject_length;
notification[8] = (byte)body_length;
System.arraycopy(subject, 0, notification, 9, subject_length);
System.arraycopy(notificationSpec.body.getBytes(StandardCharsets.UTF_8), 0, notification, 9+subject_length, body_length);
System.arraycopy(datetimeBytes, 0, notification, 9+subject_length+body_length, datetimeBytes.length);
notification[notification_length-1] = ZeTimeConstants.CMD_END;
break;
case GENERIC_CALENDAR:
if (notificationSpec.sender != null)
{
notification_length += notificationSpec.sender.getBytes(StandardCharsets.UTF_8).length;
subject_length = notificationSpec.sender.getBytes(StandardCharsets.UTF_8).length;
subject = new byte[subject_length];
System.arraycopy(notificationSpec.sender.getBytes(StandardCharsets.UTF_8), 0, subject, 0, subject_length);
} else if(notificationSpec.subject != null)
{
notification_length += notificationSpec.subject.getBytes(StandardCharsets.UTF_8).length;
subject_length = notificationSpec.subject.getBytes(StandardCharsets.UTF_8).length;
subject = new byte[subject_length];
System.arraycopy(notificationSpec.subject.getBytes(StandardCharsets.UTF_8), 0, subject, 0, subject_length);
}
notification_length += datetimeBytes.length + 10; // add message overhead
notification = new byte[notification_length];
notification[0] = ZeTimeConstants.CMD_PREAMBLE;
notification[1] = ZeTimeConstants.CMD_PUSH_EX_MSG;
notification[2] = ZeTimeConstants.CMD_SEND;
notification[3] = (byte)((notification_length-6) & 0xff);
notification[4] = (byte)((notification_length-6) >> 8);
notification[5] = ZeTimeConstants.NOTIFICATION_CALENDAR;
notification[6] = 1;
notification[7] = (byte)subject_length;
notification[8] = (byte)body_length;
System.arraycopy(subject, 0, notification, 9, subject_length);
System.arraycopy(notificationSpec.body.getBytes(StandardCharsets.UTF_8), 0, notification, 9+subject_length, body_length);
System.arraycopy(datetimeBytes, 0, notification, 9+subject_length+body_length, datetimeBytes.length);
notification[notification_length-1] = ZeTimeConstants.CMD_END;
break;
default:
break;
}
if(notification != null)
{
try {
TransactionBuilder builder = performInitialized("sendNotification");
//builder.write(writeCharacteristic, notification);
//builder.write(ackCharacteristic, new byte[]{ZeTimeConstants.CMD_ACK_WRITE});
sendMsgToWatch(builder, notification);
performConnected(builder.getTransaction());
} catch (IOException e) {
GB.toast(getContext(), "Error sending notification: " + e.getLocalizedMessage(), Toast.LENGTH_LONG, GB.ERROR);
}
}
}
@Override
public boolean onCharacteristicChanged(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic) {
super.onCharacteristicChanged(gatt, characteristic);
UUID characteristicUUID = characteristic.getUuid();
if (ZeTimeConstants.UUID_ACK_CHARACTERISTIC.equals(characteristicUUID)) {
byte[] data = receiveCompleteMsg(characteristic.getValue());
if(isMsgFormatOK(data)) {
switch (data[1]) {
case ZeTimeConstants.CMD_WATCH_ID:
break;
case ZeTimeConstants.CMD_DEVICE_VERSION:
handleDeviceInfo(data);
break;
case ZeTimeConstants.CMD_BATTERY_POWER:
handleBatteryInfo(data);
break;
case ZeTimeConstants.CMD_SHOCK_STRENGTH:
break;
case ZeTimeConstants.CMD_AVAIABLE_DATA:
handleActivityFetching(data);
break;
case ZeTimeConstants.CMD_GET_STEP_COUNT:
handleStepsData(data);
break;
case ZeTimeConstants.CMD_GET_SLEEP_DATA:
handleSleepData(data);
break;
case ZeTimeConstants.CMD_GET_HEARTRATE_EXDATA:
handleHeartRateData(data);
break;
case ZeTimeConstants.CMD_MUSIC_CONTROL:
handleMusicControl(data);
break;
}
}
return true;
} else if (ZeTimeConstants.UUID_NOTIFY_CHARACTERISTIC.equals(characteristicUUID))
{
byte[] data = receiveCompleteMsg(characteristic.getValue());
if(isMsgFormatOK(data)) {
switch (data[1])
{
case ZeTimeConstants.CMD_MUSIC_CONTROL:
handleMusicControl(data);
break;
}
return true;
}
}
else {
LOG.info("Unhandled characteristic changed: " + characteristicUUID);
logMessageContent(characteristic.getValue());
}
return false;
}
private boolean isMsgFormatOK(byte[] msg)
{
if(msg != null) {
if (msg[0] == ZeTimeConstants.CMD_PREAMBLE) {
if ((msg[3] != 0) || (msg[4] != 0)) {
int payloadSize = (msg[4] << 8)&0xff00 | (msg[3]&0xff);
int msgLength = payloadSize + 6;
if (msgLength == msg.length) {
if (msg[msgLength - 1] == ZeTimeConstants.CMD_END) {
return true;
}
}
}
}
}
return false;
}
private byte[] receiveCompleteMsg(byte[] msg)
{
if(msgPart == 0) {
int payloadSize = (msg[4] << 8)&0xff00 | (msg[3]&0xff);
if (payloadSize > 14) {
lastMsg = new byte[msg.length];
System.arraycopy(msg, 0, lastMsg, 0, msg.length);
msgPart++;
return null;
} else {
return msg;
}
} else
{
byte[] completeMsg = new byte[lastMsg.length + msg.length];
System.arraycopy(lastMsg, 0, completeMsg, 0, lastMsg.length);
System.arraycopy(msg, 0, completeMsg, lastMsg.length, msg.length);
msgPart = 0;
return completeMsg;
}
}
private ZeTimeDeviceSupport requestBatteryInfo(TransactionBuilder builder) {
LOG.debug("Requesting Battery Info!");
builder.write(writeCharacteristic,new byte[]{ZeTimeConstants.CMD_PREAMBLE,
ZeTimeConstants.CMD_BATTERY_POWER,
ZeTimeConstants.CMD_REQUEST,
0x01,
0x00,
0x00,
ZeTimeConstants.CMD_END});
builder.write(ackCharacteristic, new byte[]{ZeTimeConstants.CMD_ACK_WRITE});
return this;
}
private ZeTimeDeviceSupport requestDeviceInfo(TransactionBuilder builder) {
LOG.debug("Requesting Device Info!");
builder.write(writeCharacteristic,new byte[]{ZeTimeConstants.CMD_PREAMBLE,
ZeTimeConstants.CMD_WATCH_ID,
ZeTimeConstants.CMD_REQUEST,
0x01,
0x00,
0x00,
ZeTimeConstants.CMD_END});
builder.write(ackCharacteristic, new byte[]{ZeTimeConstants.CMD_ACK_WRITE});
builder.write(writeCharacteristic,new byte[]{ZeTimeConstants.CMD_PREAMBLE,
ZeTimeConstants.CMD_DEVICE_VERSION,
ZeTimeConstants.CMD_REQUEST,
0x01,
0x00,
0x05,
ZeTimeConstants.CMD_END});
builder.write(ackCharacteristic, new byte[]{ZeTimeConstants.CMD_ACK_WRITE});
builder.write(writeCharacteristic,new byte[]{ZeTimeConstants.CMD_PREAMBLE,
ZeTimeConstants.CMD_DEVICE_VERSION,
ZeTimeConstants.CMD_REQUEST,
0x01,
0x00,
0x02,
ZeTimeConstants.CMD_END});
builder.write(ackCharacteristic, new byte[]{ZeTimeConstants.CMD_ACK_WRITE});
return this;
}
private ZeTimeDeviceSupport requestActivityInfo(TransactionBuilder builder) {
builder.write(writeCharacteristic, new byte[]{ZeTimeConstants.CMD_PREAMBLE,
ZeTimeConstants.CMD_AVAIABLE_DATA,
ZeTimeConstants.CMD_REQUEST,
0x01,
0x00,
0x00,
ZeTimeConstants.CMD_END});
builder.write(ackCharacteristic, new byte[]{ZeTimeConstants.CMD_ACK_WRITE});
return this;
}
private ZeTimeDeviceSupport requestShockStrength(TransactionBuilder builder) {
builder.write(writeCharacteristic, new byte[]{ZeTimeConstants.CMD_PREAMBLE,
ZeTimeConstants.CMD_SHOCK_STRENGTH,
ZeTimeConstants.CMD_REQUEST,
0x01,
0x00,
0x00,
ZeTimeConstants.CMD_END});
builder.write(ackCharacteristic, new byte[]{ZeTimeConstants.CMD_ACK_WRITE});
return this;
}
private void handleBatteryInfo(byte[] value) {
batteryCmd.level = ((short) value[5]);
if(batteryCmd.level <= 25)
{
batteryCmd.state = BatteryState.BATTERY_LOW;
} else
{
batteryCmd.state = BatteryState.BATTERY_NORMAL;
}
handleGBDeviceEvent(batteryCmd);
}
private void handleDeviceInfo(byte[] value) {
value[value.length-1] = 0; // convert the end to a String end
byte[] string = Arrays.copyOfRange(value,6, value.length-1);
if(value[5] == 5)
{
versionCmd.fwVersion = new String(string);
} else{
versionCmd.hwVersion = new String(string);
}
handleGBDeviceEvent(versionCmd);
}
private void handleActivityFetching(byte[] msg)
{
availableStepsData = (int) ((msg[5]&0xff) | (msg[6] << 8)&0xff00);
availableSleepData = (int) ((msg[7]&0xff) | (msg[8] << 8)&0xff00);
availableHeartRateData= (int) ((msg[9]&0xff) | (msg[10] << 8)&0xff00);
if(availableStepsData > 0){
getStepData();
} else if(availableHeartRateData > 0)
{
getHeartRateData();
} else if(availableSleepData > 0)
{
getSleepData();
}
}
private void getStepData()
{
try {
TransactionBuilder builder = performInitialized("fetchStepData");
builder.write(writeCharacteristic, new byte[]{ZeTimeConstants.CMD_PREAMBLE,
ZeTimeConstants.CMD_GET_STEP_COUNT,
ZeTimeConstants.CMD_REQUEST,
0x02,
0x00,
0x00,
0x00,
ZeTimeConstants.CMD_END});
builder.write(ackCharacteristic, new byte[]{ZeTimeConstants.CMD_ACK_WRITE});
performConnected(builder.getTransaction());
} catch (IOException e) {
GB.toast(getContext(), "Error fetching activity data: " + e.getLocalizedMessage(), Toast.LENGTH_LONG, GB.ERROR);
}
}
private void getHeartRateData()
{
try {
TransactionBuilder builder = performInitialized("fetchStepData");
builder.write(writeCharacteristic, new byte[]{ZeTimeConstants.CMD_PREAMBLE,
ZeTimeConstants.CMD_GET_HEARTRATE_EXDATA,
ZeTimeConstants.CMD_REQUEST,
0x01,
0x00,
0x00,
ZeTimeConstants.CMD_END});
builder.write(ackCharacteristic, new byte[]{ZeTimeConstants.CMD_ACK_WRITE});
performConnected(builder.getTransaction());
} catch (IOException e) {
GB.toast(getContext(), "Error fetching activity data: " + e.getLocalizedMessage(), Toast.LENGTH_LONG, GB.ERROR);
}
}
private void getSleepData()
{
try {
TransactionBuilder builder = performInitialized("fetchStepData");
builder.write(writeCharacteristic, new byte[]{ZeTimeConstants.CMD_PREAMBLE,
ZeTimeConstants.CMD_GET_SLEEP_DATA,
ZeTimeConstants.CMD_REQUEST,
0x02,
0x00,
0x00,
0x00,
ZeTimeConstants.CMD_END});
builder.write(ackCharacteristic, new byte[]{ZeTimeConstants.CMD_ACK_WRITE});
performConnected(builder.getTransaction());
} catch (IOException e) {
GB.toast(getContext(), "Error fetching activity data: " + e.getLocalizedMessage(), Toast.LENGTH_LONG, GB.ERROR);
}
}
private void handleStepsData(byte[] msg)
{
ZeTimeActivitySample sample = new ZeTimeActivitySample();
sample.setTimestamp((msg[10] << 24)&0xff000000 | (msg[9] << 16)&0xff0000 | (msg[8] << 8)&0xff00 | (msg[7]&0xff));
sample.setSteps((msg[14] << 24)&0xff000000 | (msg[13] << 16)&0xff0000 | (msg[12] << 8)&0xff00 | (msg[11]&0xff));
sample.setCaloriesBurnt((msg[18] << 24)&0xff000000 | (msg[17] << 16)&0xff0000 | (msg[16] << 8)&0xff00 | (msg[15]&0xff));
sample.setDistanceMeters((msg[22] << 24)&0xff000000 | (msg[21] << 16)&0xff0000 | (msg[20] << 8)&0xff00 | (msg[19]&0xff));
sample.setActiveTimeMinutes((msg[26] << 24)&0xff000000 | (msg[25] << 16)&0xff0000 | (msg[24] << 8)&0xff00 | (msg[23]&0xff));
sample.setRawKind(ActivityKind.TYPE_ACTIVITY);
sample.setRawIntensity(sample.getSteps());
try (DBHandler dbHandler = GBApplication.acquireDB()) {
sample.setUserId(DBHelper.getUser(dbHandler.getDaoSession()).getId());
sample.setDeviceId(DBHelper.getDevice(getDevice(), dbHandler.getDaoSession()).getId());
ZeTimeSampleProvider provider = new ZeTimeSampleProvider(getDevice(), dbHandler.getDaoSession());
provider.addGBActivitySample(sample);
} catch (Exception ex) {
GB.toast(getContext(), "Error saving steps data: " + ex.getLocalizedMessage(), Toast.LENGTH_LONG, GB.ERROR);
GB.updateTransferNotification(null,"Data transfer failed", false, 0, getContext());
}
progressSteps = (msg[5]&0xff) | ((msg[6] << 8)&0xff00);
GB.updateTransferNotification(null, getContext().getString(R.string.busy_task_fetch_activity_data), true, (int) (progressSteps *100 / availableStepsData), getContext());
if (progressSteps == availableStepsData) {
progressSteps = 0;
availableStepsData = 0;
GB.updateTransferNotification(null,"", false, 100, getContext());
if (getDevice().isBusy()) {
getDevice().unsetBusyTask();
getDevice().sendDeviceUpdateIntent(getContext());
}
if(availableHeartRateData > 0) {
getHeartRateData();
} else if(availableSleepData > 0)
{
getSleepData();
}
}
}
private void handleSleepData(byte[] msg)
{
ZeTimeActivitySample sample = new ZeTimeActivitySample();
sample.setTimestamp((msg[10] << 24)&0xff000000 | (msg[9] << 16)&0xff0000 | (msg[8] << 8)&0xff00 | (msg[7]&0xff));
if(msg[11] == 0) {
sample.setRawKind(ActivityKind.TYPE_DEEP_SLEEP);
} else if(msg[11] == 1)
{
sample.setRawKind(ActivityKind.TYPE_LIGHT_SLEEP);
} else
{
sample.setRawKind(ActivityKind.TYPE_UNKNOWN);
}
try (DBHandler dbHandler = GBApplication.acquireDB()) {
sample.setUserId(DBHelper.getUser(dbHandler.getDaoSession()).getId());
sample.setDeviceId(DBHelper.getDevice(getDevice(), dbHandler.getDaoSession()).getId());
ZeTimeSampleProvider provider = new ZeTimeSampleProvider(getDevice(), dbHandler.getDaoSession());
provider.addGBActivitySample(sample);
} catch (Exception ex) {
GB.toast(getContext(), "Error saving steps data: " + ex.getLocalizedMessage(), Toast.LENGTH_LONG, GB.ERROR);
GB.updateTransferNotification(null,"Data transfer failed", false, 0, getContext());
}
progressSleep = (msg[5]&0xff) | (msg[6] << 8)&0xff00;
GB.updateTransferNotification(null, getContext().getString(R.string.busy_task_fetch_activity_data), true, (int) (progressSleep *100 / availableSleepData), getContext());
if (progressSleep == availableSleepData) {
progressSleep = 0;
availableSleepData = 0;
GB.updateTransferNotification(null,"", false, 100, getContext());
if (getDevice().isBusy()) {
getDevice().unsetBusyTask();
getDevice().sendDeviceUpdateIntent(getContext());
}
}
}
private void handleHeartRateData(byte[] msg)
{
ZeTimeActivitySample sample = new ZeTimeActivitySample();
sample.setHeartRate(msg[11]);
sample.setTimestamp((msg[10] << 24)&0xff000000 | (msg[9] << 16)&0xff0000 | (msg[8] << 8)&0xff00 | (msg[7]&0xff));
try (DBHandler dbHandler = GBApplication.acquireDB()) {
sample.setUserId(DBHelper.getUser(dbHandler.getDaoSession()).getId());
sample.setDeviceId(DBHelper.getDevice(getDevice(), dbHandler.getDaoSession()).getId());
ZeTimeSampleProvider provider = new ZeTimeSampleProvider(getDevice(), dbHandler.getDaoSession());
provider.addGBActivitySample(sample);
} catch (Exception ex) {
GB.toast(getContext(), "Error saving steps data: " + ex.getLocalizedMessage(), Toast.LENGTH_LONG, GB.ERROR);
GB.updateTransferNotification(null,"Data transfer failed", false, 0, getContext());
}
progressHeartRate = (msg[5]&0xff) | ((msg[6] << 8)&0xff00);
GB.updateTransferNotification(null, getContext().getString(R.string.busy_task_fetch_activity_data), true, (int) (progressHeartRate *100 / availableHeartRateData), getContext());
if (progressHeartRate == availableHeartRateData) {
progressHeartRate = 0;
availableHeartRateData = 0;
GB.updateTransferNotification(null,"", false, 100, getContext());
if (getDevice().isBusy()) {
getDevice().unsetBusyTask();
getDevice().sendDeviceUpdateIntent(getContext());
}
if(availableSleepData > 0)
{
getSleepData();
}
}
}
private void sendMsgToWatch(TransactionBuilder builder, byte[] msg)
{
if(msg.length > maxMsgLength)
{
int msgpartlength = 0;
byte[] msgpart = null;
do {
if((msg.length - msgpartlength) < maxMsgLength)
{
msgpart = new byte[msg.length - msgpartlength];
System.arraycopy(msg, msgpartlength, msgpart, 0, msg.length - msgpartlength);
msgpartlength += (msg.length - msgpartlength);
} else {
msgpart = new byte[maxMsgLength];
System.arraycopy(msg, msgpartlength, msgpart, 0, maxMsgLength);
msgpartlength += maxMsgLength;
}
builder.write(writeCharacteristic, msgpart);
}while(msgpartlength < msg.length);
} else
{
builder.write(writeCharacteristic, msg);
}
builder.write(ackCharacteristic, new byte[]{ZeTimeConstants.CMD_ACK_WRITE});
}
private void handleMusicControl(byte[] musicControlMsg)
{
if(musicControlMsg[2] == ZeTimeConstants.CMD_SEND) {
switch (musicControlMsg[5]) {
case 0: // play current song
musicCmd.event = GBDeviceEventMusicControl.Event.PLAY;
break;
case 1: // pause current song
musicCmd.event = GBDeviceEventMusicControl.Event.PAUSE;
break;
case 2: // skip to previous song
musicCmd.event = GBDeviceEventMusicControl.Event.PREVIOUS;
break;
case 3: // skip to next song
musicCmd.event = GBDeviceEventMusicControl.Event.NEXT;
break;
case 4: // change volume
if (musicControlMsg[6] > volume) {
musicCmd.event = GBDeviceEventMusicControl.Event.VOLUMEUP;
if(volume < 90) {
volume += 10;
}
} else {
musicCmd.event = GBDeviceEventMusicControl.Event.VOLUMEDOWN;
if(volume > 10) {
volume -= 10;
}
}
try {
TransactionBuilder builder = performInitialized("replyMusicVolume");
replyMsgToWatch(builder, new byte[]{ZeTimeConstants.CMD_PREAMBLE,
ZeTimeConstants.CMD_MUSIC_CONTROL,
ZeTimeConstants.CMD_REQUEST_RESPOND,
0x02,
0x00,
0x02,
volume,
ZeTimeConstants.CMD_END});
performConnected(builder.getTransaction());
} catch (IOException e) {
GB.toast(getContext(), "Error reply the music volume: " + e.getLocalizedMessage(), Toast.LENGTH_LONG, GB.ERROR);
}
break;
}
handleGBDeviceEvent(musicCmd);
} else {
if (music != null) {
music[2] = ZeTimeConstants.CMD_REQUEST_RESPOND;
try {
TransactionBuilder builder = performInitialized("replyMusicState");
replyMsgToWatch(builder, music);
performConnected(builder.getTransaction());
} catch (IOException e) {
GB.toast(getContext(), "Error reply the music state: " + e.getLocalizedMessage(), Toast.LENGTH_LONG, GB.ERROR);
}
}
}
}
private void replyMsgToWatch(TransactionBuilder builder, byte[] msg)
{
if(msg.length > maxMsgLength)
{
int msgpartlength = 0;
byte[] msgpart = null;
do {
if((msg.length - msgpartlength) < maxMsgLength)
{
msgpart = new byte[msg.length - msgpartlength];
System.arraycopy(msg, msgpartlength, msgpart, 0, msg.length - msgpartlength);
msgpartlength += (msg.length - msgpartlength);
} else {
msgpart = new byte[maxMsgLength];
System.arraycopy(msg, msgpartlength, msgpart, 0, maxMsgLength);
msgpartlength += maxMsgLength;
}
builder.write(replyCharacteristic, msgpart);
}while(msgpartlength < msg.length);
} else
{
builder.write(replyCharacteristic, msg);
}
}
private void synchronizeTime(TransactionBuilder builder)
{
Calendar now = GregorianCalendar.getInstance();
byte[] timeSync = new byte[]{ZeTimeConstants.CMD_PREAMBLE,
ZeTimeConstants.CMD_DATE_TIME,
ZeTimeConstants.CMD_SEND,
0x0c,
0x00,
(byte)(now.get(Calendar.YEAR) & 0xff),
(byte)(now.get(Calendar.YEAR) >> 8),
(byte)(now.get(Calendar.MONTH) + 1),
(byte)now.get(Calendar.DAY_OF_MONTH),
(byte)now.get(Calendar.HOUR_OF_DAY),
(byte)now.get(Calendar.MINUTE),
(byte)now.get(Calendar.SECOND),
0x00, // is 24h
0x00, // SetTime after calibration
0x01, // Unit
(byte)((now.get(Calendar.ZONE_OFFSET)/3600000) + (now.get(Calendar.DST_OFFSET)/3600000)), // TimeZone hour + daylight saving
0x00, // TimeZone minute
ZeTimeConstants.CMD_END};
sendMsgToWatch(builder, timeSync);
}
}
|
package com.boronine.husl;
public class HuslConverter {
private static double PI = 3.1415926535897932384626433832795;
private static float m[][] = {{3.2406f, -1.5372f, -0.4986f},
{-0.9689f, 1.8758f, 0.0415f},
{0.0557f, -0.2040f, 1.0570f}};
private static float m_inv[][] = {{0.4124f, 0.3576f, 0.1805f},
{0.2126f, 0.7152f, 0.0722f},
{0.0193f, 0.1192f, 0.9505f}};
// Hard-coded D65 standard illuminant.
private static float refX = 0.95047f;
private static float refY = 1.00000f;
private static float refZ = 1.08883f;
private static float refU = 0.19784f; // 4 * refX / (refX + 15 * refY + 3 * refZ)
private static float refV = 0.46834f; // 9 * refY / (refX + 15 * refY + 3 * refZ)
// CIE LAB and LUV constants.
private static float lab_e = 0.008856f;
private static float lab_k = 903.3f;
private static float maxChroma(float L, float H){
float C, bottom, cosH, hrad, lbottom, m1, m2, m3, rbottom, result, sinH, sub1, sub2, t, top;
int _i, _j, _len, _len1;
float row[];
float _ref[] = {0.0f, 1.0f};
hrad = (float) (H / 360.0f * 2 * PI);
sinH = (float) Math.sin(hrad);
cosH = (float) Math.cos(hrad);
sub1 = (float) (Math.pow(L + 16, 3) / 1560896.0);
sub2 = sub1 > 0.008856 ? sub1 : (float) (L / 903.3);
result = Float.POSITIVE_INFINITY;
for (_i = 0, _len = 3; _i < _len; ++_i) {
row = m[_i];
m1 = row[0];
m2 = row[1];
m3 = row[2];
top = (float) ((0.99915 * m1 + 1.05122 * m2 + 1.14460 * m3) * sub2);
rbottom = (float) (0.86330 * m3 - 0.17266 * m2);
lbottom = (float) (0.12949 * m3 - 0.38848 * m1);
bottom = (rbottom * sinH + lbottom * cosH) * sub2;
for (_j = 0, _len1 = 2; _j < _len1; ++_j) {
t = _ref[_j];
C = (float) (L * (top - 1.05122 * t) / (bottom + 0.17266 * sinH * t));
if (C > 0 && C < result) {
result = C;
}
}
}
return result;
}
private static float dotProduct(float a[], float b[], int len){
int i, _i, _ref;
float ret = 0.0f;
for (i = _i = 0, _ref = len - 1; 0 <= _ref ? _i <= _ref : _i >= _ref; i = 0 <= _ref ? ++_i : --_i) {
ret += a[i] * b[i];
}
return ret;
}
private static float round( float num, int places )
{
float n;
n = (float) Math.pow(10.0f, places);
return (float) (Math.floor(num * n) / n);
}
private static float f( float t )
{
if (t > lab_e) {
return (float) Math.pow(t, 1.0f / 3.0f);
} else {
return (float) (7.787 * t + 16 / 116.0);
}
}
private static float f_inv( float t )
{
if (Math.pow(t, 3) > lab_e) {
return (float) Math.pow(t, 3);
} else {
return (116 * t - 16) / lab_k;
}
}
private static float fromLinear( float c )
{
if (c <= 0.0031308) {
return 12.92f * c;
} else {
return (float) (1.055 * Math.pow(c, 1 / 2.4f) - 0.055);
}
}
private static float toLinear( float c )
{
float a = 0.055f;
if (c > 0.04045) {
return (float) Math.pow((c + a) / (1 + a), 2.4f);
} else {
return (float) (c / 12.92);
}
}
private static float[] rgbPrepare( float tuple[] )
{
int i;
for(i = 0; i < 3; ++i){
tuple[i] = round(tuple[i], 3);
if (tuple[i] < 0 || tuple[i] > 1) {
if(tuple[i] < 0) {
tuple[i] = 0;
}
else {
tuple[i] = 1;
}
}
tuple[i] = round(tuple[i]*255, 0);
}
return tuple;
}
/**
* Converts an XYZ tuple to an RGB one, altering the passed array to represent the output (discarding the input).
*/
private static void unsafeConvertXyzToRgb(float tuple[]) {
float B, G, R;
R = fromLinear(dotProduct(m[0], tuple, 3));
G = fromLinear(dotProduct(m[1], tuple, 3));
B = fromLinear(dotProduct(m[2], tuple, 3));
tuple[0] = R;
tuple[1] = G;
tuple[2] = B;
}
/**
* Converts an XYZ tuple to an RGB one.
*/
public static float[] convertXyzToRgb(float xyzTuple[]) {
// Clone the tuple, to avoid changing the input.
final float[] result = new float[]{xyzTuple[0], xyzTuple[1], xyzTuple[2]};
unsafeConvertXyzToRgb(result);
return result;
}
/**
* Converts an RGB tuple to an XYZ one, altering the passed array to represent the output (discarding the input).
*/
private static void unsafeConvertRgbToXyz(float tuple[]) {
float B, G, R, X, Y, Z;
float rgbl[] = new float[3];
R = tuple[0];
G = tuple[1];
B = tuple[2];
rgbl[0] = toLinear(R);
rgbl[1] = toLinear(G);
rgbl[2] = toLinear(B);
X = dotProduct(m_inv[0], rgbl, 3);
Y = dotProduct(m_inv[1], rgbl, 3);
Z = dotProduct(m_inv[2], rgbl, 3);
tuple[0] = X;
tuple[1] = Y;
tuple[2] = Z;
}
/**
* Converts an RGB tuple to an XYZ one.
*/
public static float[] convertRgbToXyz(float rgbTuple[]) {
// Clone the tuple, to avoid changing the input.
final float[] result = new float[]{rgbTuple[0], rgbTuple[1], rgbTuple[2]};
unsafeConvertRgbToXyz(result);
return result;
}
/**
* Converts an XYZ tuple to an LUV one, altering the passed array to represent the output (discarding the input).
*/
private static void unsafeConvertXyzToLuv(float tuple[]) {
float L, U, V, X, Y, Z, varU, varV;
X = tuple[0];
Y = tuple[1];
Z = tuple[2];
varU = 4 * X / (X + 15f * Y + 3 * Z);
varV = 9 * Y / (X + 15f * Y + 3 * Z);
L = 116 * f(Y / refY) - 16;
U = 13 * L * (varU - refU);
V = 13 * L * (varV - refV);
tuple[0] = L;
tuple[1] = U;
tuple[2] = V;
}
/**
* Converts an XYZ tuple to an LUV one.
*/
public static float[] convertXyzToLuv(float xzyTuple[]) {
// Clone the tuple, to avoid changing the input.
final float[] result = new float[]{xzyTuple[0], xzyTuple[1], xzyTuple[2]};
unsafeConvertXyzToLuv(result);
return result;
}
/**
* Converts an LUV tuple to an XYZ one, altering the passed array to represent the output (discarding the input).
*/
private static void unsafeConvertLuvToXyz(float tuple[]) {
float L, U, V, X, Y, Z, varU, varV, varY;
L = tuple[0];
U = tuple[1];
V = tuple[2];
if (L == 0) {
tuple[2] = tuple[1] = tuple[0] = 0f;
return;
}
varY = f_inv((L + 16) / 116f);
varU = U / (13.0f * L) + refU;
varV = V / (13.0f * L) + refV;
Y = varY * refY;
X = 0 - 9 * Y * varU / ((varU - 4.0f) * varV - varU * varV);
Z = (9 * Y - 15 * varV * Y - varV * X) / (3f * varV);
tuple[0] = X;
tuple[1] = Y;
tuple[2] = Z;
}
/**
* Converts an LUV tuple to an XYZ one.
*/
public static float[] convertLuvToXyz(float luvTuple[]) {
// Clone the tuple, to avoid changing the input.
final float[] result = new float[]{luvTuple[0], luvTuple[1], luvTuple[2]};
unsafeConvertLuvToXyz(result);
return result;
}
/**
* Converts an LUV tuple to an LCH one, altering the passed array to represent the output (discarding the input).
*/
private static void unsafeConvertLuvToLch(float tuple[]) {
float C, H, Hrad, L, U, V;
L = tuple[0];
U = tuple[1];
V = tuple[2];
C = (float) Math.pow(Math.pow(U, 2) + Math.pow(V, 2), 1 / 2.0f);
Hrad = (float) Math.atan2(V, U);
H = (float) (Hrad * 360.0f / 2.0f / PI);
if (H < 0) {
H = 360 + H;
}
tuple[0] = L;
tuple[1] = C;
tuple[2] = H;
}
/**
* Converts an LUV tuple to an LCH one.
*/
public static float[] convertLuvToLch(float luvTuple[]) {
// Clone the tuple, to avoid changing the input.
final float[] result = new float[]{luvTuple[0], luvTuple[1], luvTuple[2]};
unsafeConvertLuvToLch(result);
return result;
}
/**
* Converts an LCH tuple to an LUV one, altering the passed array to represent the output (discarding the input).
*/
private static void unsafeConvertLchToLuv(float tuple[]) {
float C, H, Hrad, L, U, V;
L = tuple[0];
C = tuple[1];
H = tuple[2];
Hrad = (float) (H / 360.0 * 2.0 * PI);
U = (float) (Math.cos(Hrad) * C);
V = (float) (Math.sin(Hrad) * C);
tuple[0] = L;
tuple[1] = U;
tuple[2] = V;
}
/**
* Converts an LCH tuple to an LUV one.
*/
public static float[] convertLchToLuv(float lchTuple[]) {
// Clone the tuple, to avoid changing the input.
final float[] result = new float[]{lchTuple[0], lchTuple[1], lchTuple[2]};
unsafeConvertLchToLuv(result);
return result;
}
/**
* Converts an HUSL tuple to an LCH one, altering the passed array to represent the output (discarding the input).
*/
private static void unsafeConvertHuslToLch(float tuple[]) {
float C, H, L, S, max;
H = tuple[0];
S = tuple[1];
L = tuple[2];
max = maxChroma(L, H);
C = max / 100.0f * S;
tuple[0] = L;
tuple[1] = C;
tuple[2] = H;
}
/**
* Converts an HUSL tuple to an LCH one.
*/
public static float[] convertHuslToLch(float huslTuple[]) {
// Clone the tuple, to avoid changing the input.
final float[] result = new float[]{huslTuple[0], huslTuple[1], huslTuple[2]};
unsafeConvertHuslToLch(result);
return result;
}
/**
* Converts an LCH tuple to an HUSL one, altering the passed array to represent the output (discarding the input).
*/
private static void unsafeConvertLchToHusl(float tuple[]) {
float C, H, L, S, max;
L = tuple[0];
C = tuple[1];
H = tuple[2];
max = maxChroma(L, H);
S = C / max * 100;
tuple[0] = H;
tuple[1] = S;
tuple[2] = L;
}
/**
* Converts an LCH tuple to an HUSL one.
*/
public static float[] convertLchToHusl(float lchTuple[]) {
// Clone the tuple, to avoid changing the input.
final float[] result = new float[]{lchTuple[0], lchTuple[1], lchTuple[2]};
unsafeConvertLchToHusl(result);
return result;
}
/**
* Converts an HUSL tuple to an RGB one.
*/
public static float[] convertHuslToRgb(float huslTuple[]) {
// Clone the tuple, to avoid changing the input.
final float[] result = new float[]{huslTuple[0], huslTuple[1], huslTuple[2]};
// Calculate the LCH values.
convertHuslToLch(result);
// Calculate the LUV values.
convertLchToLuv(result);
// Calculate the XYZ values.
convertLuvToXyz(result);
// Calculate the RGB values.
convertXyzToRgb(result);
return result;
}
/**
* Converts an RGB tuple to an HUSL one.
*/
public static float[] convertRgbToHusl(float rgbTuple[]) {
// Clone the tuple, to avoid changing the input.
final float[] result = new float[]{rgbTuple[0], rgbTuple[1], rgbTuple[2]};
// Calculate the XYZ values.
convertRgbToXyz(result);
// Calculate the LUV values.
convertXyzToLuv(result);
// Calculate the LCH values.
convertLuvToLch(result);
// Calculate the HUSL values.
convertLchToHusl(result);
return result;
}
}
|
package org.fraunhofer.cese.madcap.firebasecloudmessaging;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.util.Log;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
import org.fraunhofer.cese.madcap.MainActivity;
import org.fraunhofer.cese.madcap.R;
import org.fraunhofer.cese.madcap.SignInActivity;
import java.util.Map;
/**
* This class does to Firebase message handling.
*/
public class MadcapFirbaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MFirebaseMsgService";
/**
* Called when message is received.
*
* @param remoteMessage Object representing the message received from Firebase Cloud Messaging.
*/
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// There are two types of messages data messages and notification messages. Data messages are handled
// here in onMessageReceived whether the app is in the foreground or background. Data messages are the type
// traditionally used with GCM. Notification messages are only received here in onMessageReceived when the app
// is in the foreground. When the app is in the background an automatically generated notification is displayed.
// When the user taps on the notification they are returned to the app. Messages containing both notification
// and data payloads are treated as notification messages. The Firebase console always sends notification
// For Madcap we want to make sure only data messages are being received.
// TODO(developer): Handle FCM messages here.
Log.d(TAG, "From: " + remoteMessage.getFrom());
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
processIncomingMessage(remoteMessage.getData());
}
// Check if message contains a notification payload.
// Deprecated
// if (remoteMessage.getNotification() != null) {
// Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
// Also if you intend on generating your own notifications as a result of a received FCM
// message, here is where that should be initiated. See sendNotification method below.
}
/**
* Create and show a simple notification containing the received FCM message.
*
* @param messageBody FCM message body received.
*/
// private void sendNotification(String messageBody) {
// Intent intent = new Intent(this, MainActivity.class);
// intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
// PendingIntent.FLAG_ONE_SHOT);
// Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
// NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
// .setSmallIcon(R.drawable.madcaplogo2)
// .setContentTitle("FCM Message")
// .setContentText(messageBody)
// .setAutoCancel(true)
// .setSound(defaultSoundUri)
// .setContentIntent(pendingIntent);
// NotificationManager notificationManager =
// (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
private void processIncomingMessage(Map<String, String> map){
String type = map.get("type");
switch(type){
case "notification":
String name = map.get("name");
String text = map.get("text");
showUiNotification(name, text);
break;
default:
break;
//TODO: introduce new types according to David Maimons requirements
}
}
private void showUiNotification(String title, String text){
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
mBuilder.setSmallIcon(R.drawable.ic_stat_madcaplogo);
mBuilder.setContentTitle(title);
mBuilder.setContentText(text);
mBuilder.setDefaults(Notification.DEFAULT_ALL);
mBuilder.setPriority(Notification.PRIORITY_MAX);
mBuilder.setAutoCancel(true);
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(this, SignInActivity.class);
// The stack builder object will contain an artificial back stack for the
// started Activity.
// This ensures that navigating backward from the Activity leads out of
// your application to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(SignInActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
mNotificationManager.notify(2, mBuilder.build());
}
}
|
package hudson.init;
import com.google.inject.Injector;
import hudson.model.Hudson;
import jenkins.model.Jenkins;
import org.jvnet.hudson.annotation_indexer.Index;
import org.jvnet.hudson.reactor.Milestone;
import org.jvnet.hudson.reactor.MilestoneImpl;
import org.jvnet.hudson.reactor.Reactor;
import org.jvnet.hudson.reactor.Task;
import org.jvnet.hudson.reactor.TaskBuilder;
import org.jvnet.localizer.ResourceBundleHolder;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.MissingResourceException;
import java.util.Set;
import java.util.logging.Logger;
import static java.util.logging.Level.WARNING;
/**
* @author Kohsuke Kawaguchi
*/
abstract class TaskMethodFinder<T extends Annotation> extends TaskBuilder {
private static final Logger LOGGER = Logger.getLogger(TaskMethodFinder.class.getName());
protected final ClassLoader cl;
private final Set<Method> discovered = new HashSet<Method>();
private final Class<T> type;
private final Class<? extends Enum> milestoneType;
public TaskMethodFinder(Class<T> type, Class<? extends Enum> milestoneType, ClassLoader cl) {
this.type = type;
this.milestoneType = milestoneType;
this.cl = cl;
}
// working around the restriction that Java doesn't allow annotation types to extend interfaces
protected abstract String displayNameOf(T i);
protected abstract String[] requiresOf(T i);
protected abstract String[] attainsOf(T i);
protected abstract Milestone afterOf(T i);
protected abstract Milestone beforeOf(T i);
protected abstract boolean fatalOf(T i);
public Collection<Task> discoverTasks(Reactor session) throws IOException {
List<Task> result = new ArrayList<Task>();
for (Method e : Index.list(type, cl, Method.class)) {
if (filter(e)) continue; // already reported once
if (!Modifier.isStatic(e.getModifiers()))
throw new IOException(e+" is not a static method");
T i = e.getAnnotation(type);
if (i==null) continue; // stale index
result.add(new TaskImpl(i, e));
}
return result;
}
/**
* Return true to ignore this method.
*/
protected boolean filter(Method e) {
return !discovered.add(e);
}
/**
* Obtains the display name of the given initialization task
*/
protected String getDisplayNameOf(Method e, T i) {
Class<?> c = e.getDeclaringClass();
String key = displayNameOf(i);
if (key.length()==0) return c.getSimpleName()+"."+e.getName();
try {
ResourceBundleHolder rb = ResourceBundleHolder.get(
c.getClassLoader().loadClass(c.getPackage().getName() + ".Messages"));
return rb.format(key);
} catch (ClassNotFoundException x) {
LOGGER.log(WARNING, "Failed to load "+x.getMessage()+" for "+e.toString(),x);
return key;
} catch (MissingResourceException x) {
LOGGER.log(WARNING, "Could not find key '" + key + "' in " + c.getPackage().getName() + ".Messages", x);
return key;
}
}
/**
* Invokes the given initialization method.
*/
protected void invoke(Method e) {
try {
Class<?>[] pt = e.getParameterTypes();
Object[] args = new Object[pt.length];
for (int i=0; i<args.length; i++)
args[i] = lookUp(pt[i]);
e.invoke(null,args);
} catch (IllegalAccessException x) {
throw (Error)new IllegalAccessError().initCause(x);
} catch (InvocationTargetException x) {
throw new Error(x);
}
}
/**
* Determines the parameter injection of the initialization method.
*/
private Object lookUp(Class<?> type) {
Jenkins j = Jenkins.getInstance();
assert j != null : "This method is only invoked after the Jenkins singleton instance has been set";
if (type==Jenkins.class || type==Hudson.class)
return j;
Injector i = j.getInjector();
if (i!=null)
return i.getInstance(type);
throw new IllegalArgumentException("Unable to inject "+type);
}
/**
* Task implementation.
*/
public class TaskImpl implements Task {
final Collection<Milestone> requires;
final Collection<Milestone> attains;
private final T i;
private final Method e;
private TaskImpl(T i, Method e) {
this.i = i;
this.e = e;
requires = toMilestones(requiresOf(i), afterOf(i));
attains = toMilestones(attainsOf(i), beforeOf(i));
}
/**
* The annotation on the {@linkplain #getMethod() method}
*/
public T getAnnotation() {
return i;
}
/**
* Static method that runs the initialization, that this task wraps.
*/
public Method getMethod() {
return e;
}
public Collection<Milestone> requires() {
return requires;
}
public Collection<Milestone> attains() {
return attains;
}
public String getDisplayName() {
return getDisplayNameOf(e, i);
}
public boolean failureIsFatal() {
return fatalOf(i);
}
public void run(Reactor session) {
invoke(e);
}
public String toString() {
return e.toString();
}
private Collection<Milestone> toMilestones(String[] tokens, Milestone m) {
List<Milestone> r = new ArrayList<Milestone>();
for (String s : tokens) {
try {
r.add((Milestone)Enum.valueOf(milestoneType,s));
} catch (IllegalArgumentException x) {
r.add(new MilestoneImpl(s));
}
}
r.add(m);
return r;
}
}
}
|
package gof.scut.wechatcontacts;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.gson.Gson;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import gof.scut.common.MyApplication;
import gof.scut.common.utils.BundleNames;
import gof.scut.common.utils.Log;
import gof.scut.common.utils.database.MainTableUtils;
import gof.scut.cwh.models.object.ActivityConstants;
import gof.scut.cwh.models.object.IdObj;
import gof.scut.cwh.models.object.LabelListObj;
import gof.scut.cwh.models.object.Signal;
import roboguice.activity.RoboActivity;
import roboguice.inject.InjectView;
public class AddContactActivity extends RoboActivity {
//constant
private final Context mContext = AddContactActivity.this;
private final static int REQUEST_CODE_SCAN = 1;
private final static int REQUEST_CODE_LABEL = 2;
private MainTableUtils mainTableUtils;
private Gson gson;
@Inject
InputMethodManager imm;
//views
@InjectView(R.id.cancel)
TextView cancel;
@InjectView(R.id.save)
TextView save;
@InjectView(R.id.name)
EditText name;
@InjectView(R.id.add_phone_button)
ImageView addPhone;
@InjectView(R.id.phone)
EditText phone;
@InjectView(R.id.phoneList)
ListView phoneListView;
@InjectView(R.id.new_label_button)
ImageView addLable;
@InjectView(R.id.labelList)
ListView labelListView;
@InjectView(R.id.address)
EditText address;
@InjectView(R.id.addition)
EditText addition;
//values
private List<String> phoneList;
private List<String> labelList;
private MyAdapter phoneAdapter;
private MyAdapter labelAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_contact);
init();
initView();
}
private void init() {
mainTableUtils = new MainTableUtils(mContext);
gson = MyApplication.getGson();
phoneList = new ArrayList<>();
phoneAdapter = new MyAdapter(phoneList);
phoneListView.setAdapter(phoneAdapter);
labelList = new ArrayList<>();
labelAdapter = new MyAdapter(labelList);
labelListView.setAdapter(labelAdapter);
}
private void initView() {
//startActivityForResult
findViewById(R.id.scan_layout).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setClass(AddContactActivity.this, gof.scut.common.zixng.codescan.MipcaActivityCapture.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivityForResult(intent, REQUEST_CODE_SCAN);
}
});
cancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mainTableUtils.insertAll(
name.getText().toString(),
"object.getlPinYin()",
"object.getsPinYin()",
address.getText().toString(),
addition.getText().toString()
);
}
});
//add phone number
addPhone.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String phoneNumber = phone.getText().toString();
if(checkPhone(phoneNumber)){
phoneList.add(phoneNumber);
phoneAdapter.notifyDataSetChanged();
phone.setText("");
}
}
});
//add label number
addLable.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Intent intent = new Intent();
// intent.setClass(mContext, LabelsActivity.class);
// startActivityForResult(intent, REQUEST_CODE_LABEL);
Intent intent = new Intent();
intent.setClass(mContext, EditContactLabelActivity.class);
Bundle bundle = new Bundle();
Signal signal = new Signal(ActivityConstants.ADD_CONTACTS_ACTIVITY, ActivityConstants.EditContactLabelActivity);
bundle.putSerializable(Signal.NAME, signal);
//bundle.putSerializable(BundleNames.ID_OBJ, new IdObj(0));
intent.putExtras(bundle);
startActivityForResult(intent, REQUEST_CODE_LABEL);
}
});
}
private boolean checkPhone(String phoneNumber){
String telRegex = "[1]\\d{10}";//1100-911
if(TextUtils.isEmpty(phoneNumber))
return false;
if (!phoneNumber.matches(telRegex)){
Toast.makeText(mContext, "!",Toast.LENGTH_SHORT).show();
return false;
}
return true;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQUEST_CODE_SCAN:
if (resultCode == RESULT_OK) {
Bundle bundle = data.getExtras();
String resultString = bundle.getString("result");
IdObj object = gson.fromJson(resultString, IdObj.class);
Log.d(null, object.toString());
name.setText(object.getName());
address.setText(object.getAddress());
addition.setText(object.getNotes());
phoneList.addAll(object.getTels());
phoneAdapter.notifyDataSetChanged();
}
break;
case REQUEST_CODE_LABEL:
Bundle bundle = data.getExtras();
LabelListObj labelListObj = (LabelListObj) bundle.getSerializable(BundleNames.LABEL_LIST);
// do nothing if no label chose
//on edit contacts, change database in editlabel activity,
//so when back to edit contact activity, refresh database isn't needed;
// but on new contacts, only change string list in editlabel activity
// so when back to add contact activity, refresh database is needed;
if (labelListObj.getLabels().size() != 0) {
Toast.makeText(this, labelListObj.toString(), Toast.LENGTH_LONG).show();
//TODO REFRESH LABEL LIST, and finally insert id_label records into database
}
break;
default:
break;
}
}
private class MyAdapter extends BaseAdapter {
private List<String> data;
public MyAdapter(List<String> datas) {
data = datas;
}
@Override
public int getCount() {
return data.size();
}
@Override
public Object getItem(int position) {
return data.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(mContext).inflate(R.layout.cell_edit_member_list, parent, false);
holder.name = (TextView) convertView.findViewById(R.id.name);
holder.remove = (Button) convertView.findViewById(R.id.remove_member);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.name.setText(data.get(position));
holder.remove.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
data.remove(position);
MyAdapter.this.notifyDataSetChanged();
}
});
return convertView;
}
}
static class ViewHolder {
Button remove;
TextView name;
}
}
|
package org.csstudio.trends.databrowser.ui;
import java.util.List;
import org.csstudio.platform.data.ITimestamp;
import org.csstudio.platform.model.IArchiveDataSource;
import org.csstudio.platform.model.IProcessVariable;
import org.csstudio.platform.ui.internal.dataexchange.ProcessVariableOrArchiveDataSourceDropTarget;
import org.csstudio.swt.xygraph.figures.Axis;
import org.csstudio.swt.xygraph.figures.IAxisListener;
import org.csstudio.swt.xygraph.figures.ToolbarArmedXYGraph;
import org.csstudio.swt.xygraph.figures.Trace;
import org.csstudio.swt.xygraph.figures.XYGraph;
import org.csstudio.swt.xygraph.figures.XYGraphFlags;
import org.csstudio.swt.xygraph.figures.Trace.PointStyle;
import org.csstudio.swt.xygraph.figures.Trace.TraceType;
import org.csstudio.swt.xygraph.linearscale.Range;
import org.csstudio.swt.xygraph.undo.OperationsManager;
import org.csstudio.swt.xygraph.util.XYGraphMediaFactory;
import org.csstudio.trends.databrowser.Messages;
import org.csstudio.trends.databrowser.model.AxisConfig;
import org.csstudio.trends.databrowser.model.Model;
import org.csstudio.trends.databrowser.model.ModelItem;
import org.eclipse.draw2d.LightweightSystem;
import org.eclipse.jface.action.IAction;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.SWT;
import org.eclipse.swt.dnd.DropTargetEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Display;
/** Data Browser 'Plot' that displays the samples in a {@link Model}.
* <p>
* Underlying XYChart is a Draw2D Figure.
* Plot helps with linking that to an SWT Canvas.
*
* @author Kay Kasemir
*/
public class Plot
{
/** Plot Listener */
private PlotListener listener = null;
/** {@link Display} used by this plot */
final private Display display;
/** Color registry, mapping {@link RGB} values to {@link Color} */
final private ColorRegistry colormap;
// final private Font axis_font;
// final private Font axis_title_font;
/** Plot widget/figure */
final private ToolbarArmedXYGraph plot;
/** XYGraph inside <code>plot</code> */
final private XYGraph xygraph;
/** Button to enable/disable scrolling */
final private ScrollButton scroll_button;
/** Flag to suppress XYGraph events when the plot itself
* changes the time axis
*/
private boolean plot_changes_timeaxis = false;
/** Flag to suppress XYGraph events when the plot itself
* changes a value axis
*/
private boolean plot_changes_valueaxis = false;
/** Initialize plot inside Canvas
* @param canvas Parent {@link Canvas}
*/
public Plot(final Canvas canvas)
{
// Arrange for color disposal
display = canvas.getDisplay();
colormap = new ColorRegistry(canvas);
// // Use system font for axis labels
// axis_font = display.getSystemFont();
// // Use BOLD version for axis title
// final FontData fds[] = axis_font.getFontData();
// for (FontData fd : fds)
// fd.style = SWT.BOLD;
// axis_title_font = XYGraphMediaFactory.getInstance().getFont(fds);
// Create plot with basic configuration
final LightweightSystem lws = new LightweightSystem(canvas);
plot = new ToolbarArmedXYGraph(new XYGraph(),
XYGraphFlags.SEPARATE_ZOOM | XYGraphFlags.STAGGER);
xygraph = plot.getXYGraph();
scroll_button = new ScrollButton(xygraph.getOperationsManager());
plot.addToolbarButton(scroll_button);
// Configure axes
final Axis time_axis = xygraph.primaryXAxis;
time_axis.setDateEnabled(true);
time_axis.setTitle(Messages.Plot_TimeAxisName);
// time_axis.setFont(axis_font);
// time_axis.setTitleFont(axis_title_font);
// xygraph.primaryYAxis.setTitle(Messages.Plot_ValueAxisName);
// xygraph.primaryYAxis.setFont(axis_font);
// xygraph.primaryYAxis.setTitleFont(axis_title_font);
// Forward time axis changes from the GUI to PlotListener
// (Ignore changes from setTimeRange)
time_axis.addListener(new IAxisListener()
{
public void axisRevalidated(final Axis axis)
{
// NOP
}
public void axisRangeChanged(final Axis axis, final Range old_range, final Range new_range)
{ // Check that it's not caused by ourself, and a real change
if (!plot_changes_timeaxis &&
!old_range.equals(new_range) &&
listener != null)
listener.timeAxisChanged((long)new_range.getLower(),
(long)new_range.getUpper());
}
});
xygraph.primaryYAxis.addListener(createValueAxisListener(0));
lws.setContents(plot);
// Allow drag & drop of names into the plot
// new TextAsPVDropTarget(canvas)
// @Override
// public void handleDrop(final String name)
// if (listener != null)
// listener.droppedPVName(name);
new ProcessVariableOrArchiveDataSourceDropTarget(canvas)
{
@Override
public void handleDrop(final IProcessVariable name,
final IArchiveDataSource archive, final DropTargetEvent event)
{
if (listener != null)
listener.droppedPVName(name.getName(), archive);
}
@Override
public void handleDrop(final IArchiveDataSource archive, final DropTargetEvent event)
{
if (listener != null)
listener.droppedPVName(null, archive);
}
@Override
public void handleDrop(final IProcessVariable name, final DropTargetEvent event)
{
handleDrop(name, null, event);
}
@Override
public void handleDrop(final String name, final DropTargetEvent event)
{
if (listener != null)
listener.droppedName(name);
}
};
}
/** Add a listener (currently only one supported) */
public void addListener(final PlotListener listener)
{
if (this.listener != null)
throw new IllegalStateException();
this.listener = listener;
scroll_button.addPlotListener(listener);
}
/** @return Operations manager for undo/redo */
public OperationsManager getOperationsManager()
{
return xygraph.getOperationsManager();
}
/** @return Action to show/hide the tool bar */
public IAction getToggleToolbarAction()
{
return new ToggleToolbarAction(plot);
}
/** Remove all axes and traces */
public void removeAll()
{
// Remove all traces
int N = xygraph.getPlotArea().getTraceList().size();
while (N > 0)
xygraph.removeTrace(xygraph.getPlotArea().getTraceList().get(--N));
// Now that Y axes are unused, remove all except for primary
N = xygraph.getYAxisList().size();
while (N > 1)
xygraph.removeAxis(xygraph.getYAxisList().get(--N));
}
/** @param index Index of Y axis. If it doesn't exist, it will be created.
* @return Y Axis
*/
private Axis getYAxis(final int index)
{
// Get Y Axis, creating new ones if needed
final List<Axis> axes = xygraph.getYAxisList();
while (axes.size() <= index)
{
final int new_axis_index = axes.size();
final Axis axis = new Axis(NLS.bind(Messages.Plot_ValueAxisNameFMT, new_axis_index + 1), true);
// axis.setFont(axis_font);
// axis.setTitleFont(axis_title_font);
xygraph.addAxis(axis);
axis.addListener(createValueAxisListener(new_axis_index));
}
return axes.get(index);
}
/** Create value axis listener
* @param index Index of the axis, 0 ...
* @return IAxisListener
*/
private IAxisListener createValueAxisListener(final int index)
{
return new IAxisListener()
{
public void axisRevalidated(Axis axis)
{
// NOP
}
public void axisRangeChanged(final Axis axis, final Range old_range, final Range new_range)
{
if (plot_changes_valueaxis ||
old_range.equals(new_range) ||
listener == null)
return;
listener.valueAxisChanged(index, new_range.getLower(), new_range.getUpper());
}
};
}
/** Update configuration of axis
* @param index Axis index. Y axes will be created as needed.
* @param config Desired axis configuration
*/
public void updateAxis(final int index, final AxisConfig config)
{
final Axis axis = getYAxis(index);
axis.setTitle(config.getName());
axis.setForegroundColor(colormap.getColor(config.getColor()));
plot_changes_valueaxis = true;
axis.setRange(config.getMin(), config.getMax());
axis.setLogScale(config.isLogScale());
axis.setAutoScale(config.isAutoScale());
plot_changes_valueaxis = false;
}
/** Add a trace to the XYChart
* @param item ModelItem for which to add a trace
*/
public void addTrace(final ModelItem item)
{
final Axis xaxis = xygraph.primaryXAxis;
final Axis yaxis = getYAxis(item.getAxis());
final Trace trace = new Trace(item.getDisplayName(),
xaxis, yaxis, item.getSamples());
trace.setPointStyle(PointStyle.NONE);
setTraceType(item, trace);
trace.setTraceColor(colormap.getColor(item.getColor()));
trace.setLineWidth(item.getLineWidth());
xygraph.addTrace(trace);
}
/** Configure the XYGraph Trace's
* @param item ModelItem whose Trace Type combines the basic line type
* and the error bar display settings
* @param trace Trace to configure
*/
private void setTraceType(final ModelItem item, final Trace trace)
{
switch (item.getTraceType())
{
case AREA:
// None of these seem to cause an immediate redraw, so
// don't bother to check for changes
trace.setTraceType(TraceType.STEP_HORIZONTALLY);
trace.setPointStyle(PointStyle.NONE);
trace.setErrorBarEnabled(true);
trace.setDrawYErrorInArea(true);
break;
case ERROR_BARS:
trace.setTraceType(TraceType.STEP_HORIZONTALLY);
trace.setPointStyle(PointStyle.NONE);
trace.setErrorBarEnabled(true);
trace.setDrawYErrorInArea(false);
break;
case SINGLE_LINE:
trace.setTraceType(TraceType.STEP_HORIZONTALLY);
trace.setPointStyle(PointStyle.NONE);
trace.setErrorBarEnabled(false);
trace.setDrawYErrorInArea(false);
break;
case SQUARES:
trace.setTraceType(TraceType.POINT);
trace.setPointStyle(PointStyle.FILLED_SQUARE);
trace.setPointSize(item.getLineWidth());
trace.setErrorBarEnabled(false);
trace.setDrawYErrorInArea(false);
break;
case CIRCLES:
trace.setTraceType(TraceType.POINT);
trace.setPointStyle(PointStyle.CIRCLE);
trace.setPointSize(item.getLineWidth());
trace.setErrorBarEnabled(false);
trace.setDrawYErrorInArea(false);
break;
case CROSSES:
trace.setTraceType(TraceType.POINT);
trace.setPointStyle(PointStyle.XCROSS);
trace.setPointSize(item.getLineWidth());
trace.setErrorBarEnabled(false);
trace.setDrawYErrorInArea(false);
break;
case DIAMONDS:
trace.setTraceType(TraceType.POINT);
trace.setPointStyle(PointStyle.FILLED_DIAMOND);
trace.setPointSize(item.getLineWidth());
trace.setErrorBarEnabled(false);
trace.setDrawYErrorInArea(false);
break;
case TRIANGLES:
trace.setTraceType(TraceType.POINT);
trace.setPointStyle(PointStyle.FILLED_TRIANGLE);
trace.setPointSize(item.getLineWidth());
trace.setErrorBarEnabled(false);
trace.setDrawYErrorInArea(false);
break;
}
}
/** Remove a trace from the XYChart
* @param item ModelItem to remove
*/
public void removeTrace(final ModelItem item)
{
final Trace trace = findTrace(item);
if (trace == null)
throw new RuntimeException("No trace for " + item.getName()); //$NON-NLS-1$
xygraph.removeTrace(trace);
}
/** Update the configuration of a trace from Model Item
* @param item Item that was previously added to the Plot
*/
public void updateTrace(final ModelItem item)
{
final Trace trace = findTrace(item);
if (trace == null)
throw new RuntimeException("No trace for " + item.getName()); //$NON-NLS-1$
// Update Trace with item's configuration
if (!trace.getName().equals(item.getDisplayName()))
trace.setName(item.getDisplayName());
// These happen to not cause an immediate redraw, so
// set even if no change
trace.setTraceColor(colormap.getColor(item.getColor()));
trace.setLineWidth(item.getLineWidth());
setTraceType(item, trace);
// Locate index of current Y Axis
final Axis axis = trace.getYAxis();
final List<Axis> yaxes = xygraph.getYAxisList();
int axis_index = 0;
for (; axis_index < yaxes.size(); ++axis_index)
if (axis == yaxes.get(axis_index))
break;
final int desired_axis = item.getAxis();
// Change to desired Y Axis?
if (axis_index != desired_axis && desired_axis < yaxes.size())
trace.setYAxis(yaxes.get(desired_axis));
}
/** @param item ModelItem for which to locate the {@link Trace}
* @return Trace
* @throws RuntimeException on error
*/
@SuppressWarnings("nls")
private Trace findTrace(ModelItem item)
{
final List<Trace> traces = xygraph.getPlotArea().getTraceList();
for (Trace trace : traces)
if (trace.getDataProvider() == item.getSamples())
return trace;
throw new RuntimeException("Cannot locate trace for " + item);
}
/** Update plot to given time range.
*
* Can be called from any thread.
* @param start_ms Milliseconds since 1970 for start time
* @param end_ms ... end time
*/
public void setTimeRange(final long start_ms, final long end_ms)
{
display.asyncExec(new Runnable()
{
public void run()
{
plot_changes_timeaxis = true;
xygraph.primaryXAxis.setRange(start_ms, end_ms);
plot_changes_timeaxis = false;
}
});
}
/** Update plot to given time range.
* @param start Start time
* @param end End time
*/
public void setTimeRange(final ITimestamp start, final ITimestamp end)
{
final double start_ms = start.toDouble()*1000;
final double end_ms = end.toDouble()*1000;
plot_changes_timeaxis = true;
xygraph.primaryXAxis.setRange(start_ms, end_ms);
plot_changes_timeaxis = false;
}
/** Update the scroll button
* @param on <code>true</code> when scrolling is 'on'
*/
public void updateScrollButton(final boolean scroll_on)
{
scroll_button.setButtonState(scroll_on);
}
/** Refresh the plot because the data has changed */
public void redrawTraces()
{
display.asyncExec(new Runnable()
{
public void run()
{
xygraph.revalidate();
}
});
}
/** @param color New background color */
public void setBackgroundColor(final RGB color)
{
xygraph.getPlotArea().setBackgroundColor(colormap.getColor(color));
}
public XYGraph getXYGraph()
{
return xygraph;
}
}
|
package me.devsaki.hentoid.util;
import androidx.annotation.Nullable;
import com.android.volley.AuthFailureError;
import com.android.volley.Header;
import com.android.volley.Request;
import com.android.volley.toolbox.BaseHttpStack;
import com.android.volley.toolbox.HttpResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import okhttp3.Call;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
public class VolleyOkHttp3Stack extends BaseHttpStack {
private final OkHttpClient client;
public VolleyOkHttp3Stack(int timeoutMs) {
client = OkHttpClientSingleton.getInstance(timeoutMs);
}
private static void setConnectionParametersForRequest(okhttp3.Request.Builder builder, Request<?> request)
throws AuthFailureError {
switch (request.getMethod()) {
case Request.Method.DEPRECATED_GET_OR_POST:
// Ensure backwards compatibility. Volley assumes a request with a null body is a GET.
byte[] postBody = request.getBody();
if (postBody != null) {
builder.post(RequestBody.create(MediaType.parse(request.getBodyContentType()), postBody));
}
break;
case Request.Method.GET:
builder.get();
break;
case Request.Method.DELETE:
builder.delete(createRequestBody(request));
break;
case Request.Method.POST:
builder.post(createRequestBody(request));
break;
case Request.Method.PUT:
builder.put(createRequestBody(request));
break;
case Request.Method.HEAD:
builder.head();
break;
case Request.Method.OPTIONS:
builder.method("OPTIONS", null);
break;
case Request.Method.TRACE:
builder.method("TRACE", null);
break;
case Request.Method.PATCH:
builder.patch(createRequestBody(request));
break;
default:
throw new IllegalStateException("Unknown method type.");
}
}
@Nullable
private static RequestBody createRequestBody(Request r) throws AuthFailureError {
final byte[] body = r.getBody();
if (body == null) return null;
return RequestBody.create(MediaType.parse(r.getBodyContentType()), body);
}
@Override
public HttpResponse executeRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError {
okhttp3.Request.Builder okHttpRequestBuilder = new okhttp3.Request.Builder();
okHttpRequestBuilder.url(request.getUrl());
Map<String, String> headers = request.getHeaders();
for (Map.Entry<String, String> entry : headers.entrySet()) {
String value = (null == entry.getValue()) ? "" : entry.getValue();
okHttpRequestBuilder.addHeader(entry.getKey(), value);
}
for (Map.Entry<String, String> entry : additionalHeaders.entrySet()) {
String value = (null == entry.getValue()) ? "" : entry.getValue();
okHttpRequestBuilder.addHeader(entry.getKey(), value);
}
setConnectionParametersForRequest(okHttpRequestBuilder, request);
okhttp3.Request okHttpRequest = okHttpRequestBuilder.build();
Call okHttpCall = client.newCall(okHttpRequest);
Response okHttpResponse = okHttpCall.execute();
int code = okHttpResponse.code();
ResponseBody body = okHttpResponse.body();
InputStream content = body == null ? null : body.byteStream();
int contentLength = body == null ? 0 : (int) body.contentLength();
List<Header> responseHeaders = mapHeaders(okHttpResponse.headers());
return new HttpResponse(code, responseHeaders, contentLength, content);
}
private List<Header> mapHeaders(Headers responseHeaders) {
List<Header> headers = new ArrayList<>();
for (int i = 0, len = responseHeaders.size(); i < len; i++) {
final String name = responseHeaders.name(i);
final String value = responseHeaders.value(i);
headers.add(new Header(name, value));
}
return headers;
}
}
|
package org.fraunhofer.cese.madcap;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.method.LinkMovementMethod;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.common.ConnectionResult;
import org.fraunhofer.cese.madcap.authentication.LoginResultCallback;
import org.fraunhofer.cese.madcap.authentication.MadcapAuthManager;
import org.fraunhofer.cese.madcap.services.DataCollectionService;
import javax.inject.Inject;
public class WelcomeActivity extends AppCompatActivity {
private static final String TAG = "WelcomeActivity";
@Inject
MadcapAuthManager madcapAuthManager;
private TextView errorTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//noinspection CastToConcreteClass
((MyApplication) getApplication()).getComponent().inject(this);
MyApplication.madcapLogger.d(TAG, "Welcome created");
setContentView(R.layout.activity_welcome);
errorTextView = (TextView) findViewById(R.id.welcomeErrorTextView);
errorTextView.setMovementMethod(LinkMovementMethod.getInstance());
Button helpButton = (Button) findViewById(R.id.helpButton);
helpButton.setOnClickListener(new View.OnClickListener() {
/**
* Called when a view has been clicked.
*
* @param v The view that was clicked.
*/
@Override
public void onClick(View v) {
MyApplication.madcapLogger.d(TAG, "Help toggled");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("https:
startActivity(intent);
}
});
}
@Override
public void onStart() {
super.onStart();
MyApplication.madcapLogger.d(TAG, "onStart");
GoogleSignInAccount user = madcapAuthManager.getUser();
if (user != null) {
MyApplication.madcapLogger.d(TAG, "User already signed in. Starting MainActivity.");
errorTextView.setText("Welcome " + user.getGivenName() + ' ' + user.getFamilyName());
startActivity(new Intent(this, MainActivity.class));
} else {
final Context context = this;
madcapAuthManager.silentLogin(this, new LoginResultCallback() {
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
errorTextView.setText("Unable to connect to Google Signin services. Error code: " + connectionResult);
MyApplication.madcapLogger.e(TAG, "onStart.onConnectionFailed: Unable to connect to Google Play services. Error code: " + connectionResult);
// TODO: Unregister this listener from mGoogleClientApi in MadcapAuthManager?
}
@Override
public void onConnected(@Nullable Bundle bundle) {
MyApplication.madcapLogger.d(TAG, "onStart.onConnected: successfully connected to Google Play Services.");
errorTextView.setText("Connected to Google Signin services...");
}
@Override
public void onConnectionSuspended(int i) {
MyApplication.madcapLogger.w(TAG, "onStart.onConnectionSuspended: Connection suspended. Error code: " + i);
errorTextView.setText("Lost connection to Google Signin services. Please sign in manually.");
startActivity(new Intent(context, SignInActivity.class));
finish();
}
@Override
public void onServicesUnavailable(int connectionResult) {
String text;
switch(connectionResult) {
case ConnectionResult.SERVICE_MISSING:
text = "Play services not available, please install them.";
break;
case ConnectionResult.SERVICE_UPDATING:
text = "Play services are currently updating, please wait.";
break;
case ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED:
text = "Play services not up to date. Please update.";
break;
case ConnectionResult.SERVICE_DISABLED:
text = "Play services are disabled. Please enable.";
break;
case ConnectionResult.SERVICE_INVALID:
text = "Play services are invalid. Please reinstall them";
break;
default:
text = "Unknown Play Services return code.";
}
MyApplication.madcapLogger.e(TAG, text);
errorTextView.setText(text);
startActivity(new Intent(context, SignInActivity.class));
finish();
}
@Override
public void onLoginResult(GoogleSignInResult signInResult) {
if (signInResult.isSuccess()) {
MyApplication.madcapLogger.d(TAG, "User successfully signed in and authenticated to MADCAP.");
errorTextView.setText("Welcome");
if (PreferenceManager.getDefaultSharedPreferences(context).getBoolean(getString(R.string.data_collection_pref), true)) {
startService(new Intent(context, DataCollectionService.class));
}
startActivity(new Intent(context, MainActivity.class));
} else {
MyApplication.madcapLogger.d(TAG, "User could not be authenticated to MADCAP. Starting SignInActivity.");
startActivity(new Intent(context, SignInActivity.class));
}
finish();
}
});
}
}
}
|
package org.javarosa.core.model;
import org.javarosa.core.model.instance.FormInstance;
import org.javarosa.core.model.instance.TreeElement;
import org.javarosa.core.model.instance.TreeReference;
import org.javarosa.core.model.util.restorable.Restorable;
import org.javarosa.core.model.util.restorable.RestoreUtils;
import org.javarosa.core.services.storage.IMetaData;
import org.javarosa.core.services.storage.Persistable;
import org.javarosa.core.util.externalizable.DeserializationException;
import org.javarosa.core.util.externalizable.ExtUtil;
import org.javarosa.core.util.externalizable.ExtWrapMap;
import org.javarosa.core.util.externalizable.PrototypeFactory;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Hashtable;
/**
* Peristable object representing a CommCare mobile user.
*
* @author ctsims
* @author wspride
*/
public class User implements Persistable, Restorable, IMetaData {
public static final String STORAGE_KEY = "USER";
public static final String ADMINUSER = "admin";
public static final String STANDARD = "standard";
public static final String DEMO_USER = "demo_user";
public static final String KEY_USER_TYPE = "user_type";
public static final String TYPE_DEMO = "demo";
public static final String META_UID = "uid";
public static final String META_USERNAME = "username";
public static final String META_ID = "userid";
public static final String META_WRAPPED_KEY = "wrappedkey";
public static final String META_SYNC_TOKEN = "synctoken";
public int recordId = -1; //record id on device
private String username;
private String passwordHash;
private String uniqueId; //globally-unique id
static private User demo_user;
public boolean rememberMe = false;
public String syncToken;
public byte[] wrappedKey;
public Hashtable<String, String> properties = new Hashtable<String, String>();
public User() {
setUserType(STANDARD);
}
public User(String name, String passw, String uniqueID) {
this(name, passw, uniqueID, STANDARD);
}
public User(String name, String passw, String uniqueID, String userType) {
username = name;
passwordHash = passw;
uniqueId = uniqueID;
setUserType(userType);
rememberMe = false;
}
// fetch the value for the default user and password from the RMS
@Override
public void readExternal(DataInputStream in, PrototypeFactory pf) throws IOException, DeserializationException {
this.username = ExtUtil.readString(in);
this.passwordHash = ExtUtil.readString(in);
this.recordId = ExtUtil.readInt(in);
this.uniqueId = ExtUtil.nullIfEmpty(ExtUtil.readString(in));
this.rememberMe = ExtUtil.readBool(in);
this.syncToken = ExtUtil.nullIfEmpty(ExtUtil.readString(in));
this.properties = (Hashtable)ExtUtil.read(in, new ExtWrapMap(String.class, String.class), pf);
this.wrappedKey = ExtUtil.nullIfEmpty(ExtUtil.readBytes(in));
}
@Override
public void writeExternal(DataOutputStream out) throws IOException {
ExtUtil.writeString(out, username);
ExtUtil.writeString(out, passwordHash);
ExtUtil.writeNumeric(out, recordId);
ExtUtil.writeString(out, ExtUtil.emptyIfNull(uniqueId));
ExtUtil.writeBool(out, rememberMe);
ExtUtil.writeString(out, ExtUtil.emptyIfNull(syncToken));
ExtUtil.write(out, new ExtWrapMap(properties));
ExtUtil.writeBytes(out, ExtUtil.emptyIfNull(wrappedKey));
}
public boolean isAdminUser() {
return ADMINUSER.equals(getUserType());
}
public String getUsername() {
return username;
}
public String getPasswordHash() {
return passwordHash;
}
@Override
public void setID(int recordId) {
this.recordId = recordId;
}
@Override
public int getID() {
return recordId;
}
public String getUserType() {
if (properties.containsKey(KEY_USER_TYPE)) {
return properties.get(KEY_USER_TYPE);
} else {
return null;
}
}
public void setUserType(String userType) {
properties.put(KEY_USER_TYPE, userType);
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String passwordHash) {
this.passwordHash = passwordHash;
}
public void setRememberMe(boolean rememberMe) {
this.rememberMe = rememberMe;
}
public void setUuid(String uuid) {
this.uniqueId = uuid;
}
public String getUniqueId() {
return uniqueId;
}
public Enumeration listProperties() {
return this.properties.keys();
}
public void setProperty(String key, String val) {
this.properties.put(key, val);
}
public String getProperty(String key) {
return this.properties.get(key);
}
public Hashtable<String, String> getProperties() {
return this.properties;
}
@Override
public String getRestorableType() {
return "user";
}
@Override
public void templateData(FormInstance dm, TreeReference parentRef) {
RestoreUtils.applyDataType(dm, "name", parentRef, String.class);
RestoreUtils.applyDataType(dm, "pass", parentRef, String.class);
RestoreUtils.applyDataType(dm, "type", parentRef, String.class);
RestoreUtils.applyDataType(dm, "user-id", parentRef, Integer.class);
RestoreUtils.applyDataType(dm, "uuid", parentRef, String.class);
RestoreUtils.applyDataType(dm, "remember", parentRef, Boolean.class);
}
@Override
public Object getMetaData(String fieldName) {
if (META_UID.equals(fieldName)) {
return uniqueId;
} else if(META_USERNAME.equals(fieldName)) {
return username;
} else if(META_ID.equals(fieldName)) {
return new Integer(recordId);
} else if (META_WRAPPED_KEY.equals(fieldName)) {
return wrappedKey;
} else if (META_SYNC_TOKEN.equals(fieldName)) {
return ExtUtil.emptyIfNull(syncToken);
}
throw new IllegalArgumentException("No metadata field " + fieldName + " for User Models");
}
// TODO: Add META_WRAPPED_KEY back in?
@Override
public String[] getMetaDataFields() {
return new String[] {META_UID, META_USERNAME, META_ID, META_SYNC_TOKEN};
}
//Don't ever save!
private String cachedPwd;
public void setCachedPwd(String password) {
this.cachedPwd = password;
}
public String getCachedPwd() {
return this.cachedPwd;
}
public String getLastSyncToken() {
return syncToken;
}
public void setLastSyncToken(String syncToken) {
this.syncToken = syncToken;
}
public static User FactoryDemoUser() {
if (demo_user == null) {
demo_user = new User();
demo_user.setUsername(User.DEMO_USER); // NOTE: Using a user type as a
// username also!
demo_user.setUserType(User.DEMO_USER);
demo_user.setUuid(User.DEMO_USER);
}
return demo_user;
}
public void setWrappedKey(byte[] key) {
this.wrappedKey = key;
}
public byte[] getWrappedKey() {
return wrappedKey;
}
}
|
package org.telegram.android;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.widget.Toast;
import com.extradea.framework.images.utils.ImageUtils;
import org.telegram.android.ui.pick.PickIntentClickListener;
import org.telegram.android.ui.pick.PickIntentDialog;
import org.telegram.android.ui.pick.PickIntentItem;
import org.telegram.android.video.VideoRecorderActivity;
import java.io.*;
import java.util.*;
public class MediaReceiverFragment extends StelsFragment {
private static final int REQ_M = 5;
private static final int REQUEST_BASE = 100;
private String imageFileName;
private String videoFileName;
private Random rnd = new Random();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
imageFileName = savedInstanceState.getString("picker:imageFileName");
videoFileName = savedInstanceState.getString("picker:videoFileName");
}
}
protected String getUploadTempFile() {
if (Build.VERSION.SDK_INT >= 8) {
try {
//return getExternalCacheDir().getAbsolutePath();
return ((File) StelsApplication.class.getMethod("getExternalCacheDir").invoke(application)).getAbsolutePath() + "/upload_" + rnd.nextLong() + ".jpg";
} catch (Exception e) {
// Log.e(TAG, e);
}
}
return Environment.getExternalStorageDirectory().getAbsolutePath() + "/cache/" + application.getPackageName() + "/upload_" + rnd.nextLong() + ".jpg";
}
protected String getUploadVideoTempFile() {
if (Build.VERSION.SDK_INT >= 8) {
try {
//return getExternalCacheDir().getAbsolutePath();
return ((File) StelsApplication.class.getMethod("getExternalCacheDir").invoke(application)).getAbsolutePath() + "/upload_" + rnd.nextLong() + ".mp4";
} catch (Exception e) {
// Log.e(TAG, e);
}
}
return Environment.getExternalStorageDirectory().getAbsolutePath() + "/cache/" + application.getPackageName() + "/upload_" + rnd.nextLong() + ".mp4";
}
public void requestPhotoChooserWithDelete(final int requestId) {
imageFileName = getUploadTempFile();
final Uri fileUri = Uri.fromFile(new File(imageFileName));
ArrayList<PickIntentItem> items = new ArrayList<PickIntentItem>();
Collections.addAll(items, createPickIntents(new Intent(MediaStore.ACTION_IMAGE_CAPTURE)));
Collections.addAll(items, createPickIntents(new Intent(Intent.ACTION_GET_CONTENT)
/*Uri selectedImageUri = data.getData();
if (selectedImageUri == null) {
}*/
secureCallback(new Runnable() {
@Override
public void run() {
onPhotoCropped(Uri.fromFile(new File(imageFileName)), (requestCode - REQUEST_BASE) / REQ_M);
}
});
} else if (requestCode % REQ_M == 4) {
try {
Integer resourceId = data.getExtras().getInt("redId");
BitmapDrawable drawable = (BitmapDrawable) application.getPackageManager().getResourcesForApplication("com.whatsapp.wallpaper").getDrawable(resourceId);
Bitmap bitmap = drawable.getBitmap();
String fileName = getUploadTempFile();
FileOutputStream outputStream = new FileOutputStream(fileName);
bitmap.compress(Bitmap.CompressFormat.JPEG, 87, outputStream);
outputStream.close();
onPhotoArrived(fileName, bitmap.getWidth(), bitmap.getHeight(), (requestCode - REQUEST_BASE) / REQ_M);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString("picker:imageFileName", imageFileName);
outState.putString("picker:videoFileName", videoFileName);
}
}
|
package org.ovirt.engine.core.searchbackend;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import org.ovirt.engine.core.compat.DateTime;
class DateUtils {
static Date parse(String str) {
for (DateFormat fmt : formats(DateFormat.DEFAULT, DateFormat.FULL, DateFormat.LONG, DateFormat.MEDIUM, DateFormat.SHORT)) {
try {
return fmt.parse(str);
} catch (ParseException e) {
}
}
return null;
}
private static List<DateFormat> formats(int... styles) {
List<DateFormat> formats = new ArrayList<DateFormat>();
for (int style : styles) {
addFormat(formats, style);
}
return formats;
}
private static void addFormat(List<DateFormat> formats, int style) {
formats.add(getFormat(style));
formats.add(getFormat(style, style));
}
public static DateFormat getFormat(int dateStyle) {
return DateFormat.getDateInstance(dateStyle);
}
public static DateFormat getFormat(int dateStyle, int timeStyle) {
return DateFormat.getDateTimeInstance(dateStyle, timeStyle);
}
public static String getDayOfWeek(int addDays) {
Calendar date = Calendar.getInstance();
date.add(Calendar.DATE, addDays);
return DateTime.getDayOfTheWeekAsString(date.get(Calendar.DAY_OF_WEEK)).toUpperCase();
}
}
|
package tech.tablesaw.api;
import com.google.common.base.Preconditions;
import tech.tablesaw.columns.Column;
import java.util.ArrayList;
import java.util.List;
public interface ColumnType {
List<ColumnType> values = new ArrayList<>();
// standard column types
ColumnType BOOLEAN = new StandardColumnType(Byte.MIN_VALUE, 1, "BOOLEAN", "Boolean");
ColumnType STRING = new StandardColumnType("", 4, "STRING", "String");
ColumnType NUMBER = new StandardColumnType(Double.NaN, 8, "NUMBER", "Number");
ColumnType LOCAL_DATE = new StandardColumnType(Integer.MIN_VALUE, 4, "LOCAL_DATE", "Date");
ColumnType LOCAL_DATE_TIME = new StandardColumnType(Long.MIN_VALUE, 8, "LOCAL_DATE_TIME","DateTime");
ColumnType LOCAL_TIME = new StandardColumnType(Integer.MIN_VALUE, 4, "LOCAL_TIME", "Time");
ColumnType SKIP = new StandardColumnType(null, 0, "SKIP", "Skipped");
static void register(ColumnType type) {
values.add(type);
}
static ColumnType[] values() {
return values.toArray(new ColumnType[0]);
}
static ColumnType valueOf(String name) {
Preconditions.checkNotNull(name);
for (ColumnType type : values) {
if (type.name().equals(name)) {
return type;
}
}
throw new IllegalArgumentException(name + " is not a registered column type.");
}
default Column create(String name) {
final String columnTypeName = this.name();
switch (columnTypeName) {
case "BOOLEAN": return BooleanColumn.create(name);
case "STRING": return StringColumn.create(name);
case "NUMBER": return DoubleColumn.create(name);
case "LOCAL_DATE": return DateColumn.create(name);
case "LOCAL_DATE_TIME": return DateTimeColumn.create(name);
case "LOCAL_TIME": return TimeColumn.create(name);
case "SKIP": throw new IllegalArgumentException("Cannot create column of type SKIP");
default:
throw new UnsupportedOperationException("Column type " + name() + " doesn't support column creation");
}
}
String name();
Comparable<?> getMissingValue();
int byteSize();
String getPrinterFriendlyName();
}
|
package org.commcare.dalvik.activities;
import org.commcare.android.database.global.models.ApplicationRecord;
import org.commcare.android.framework.CommCareActivity;
import org.commcare.android.framework.ManagedUi;
import org.commcare.android.framework.UiElement;
import org.commcare.android.framework.WrappingSpinnerAdapter;
import org.commcare.android.javarosa.AndroidLogger;
import org.commcare.android.models.notifications.NotificationMessage;
import org.commcare.android.models.notifications.NotificationMessageFactory;
import org.commcare.android.tasks.ResourceEngineListener;
import org.commcare.android.tasks.ResourceEngineTask;
import org.commcare.android.tasks.ResourceEngineTask.ResourceEngineOutcomes;
import org.commcare.android.util.AndroidCommCarePlatform;
import org.commcare.dalvik.R;
import org.commcare.dalvik.application.CommCareApp;
import org.commcare.dalvik.application.CommCareApplication;
import org.commcare.resources.model.ResourceTable;
import org.commcare.resources.model.UnresolvedResourceException;
import org.javarosa.core.reference.InvalidReferenceException;
import org.javarosa.core.reference.ReferenceManager;
import org.javarosa.core.services.Logger;
import org.javarosa.core.services.locale.Localization;
import org.javarosa.core.util.PropertyUtils;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.PowerManager;
import android.text.InputType;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
/**
* The CommCareStartupActivity is purely responsible for identifying
* the state of the application (uninstalled, installed) and performing
* any necessary setup to get to a place where CommCare can load normally.
*
* If the startup activity identifies that the app is installed properly
* it should not ever require interaction or be visible to the user.
*
* @author ctsims
*
*/
@ManagedUi(R.layout.first_start_screen)
public class CommCareSetupActivity extends CommCareActivity<CommCareSetupActivity> implements ResourceEngineListener{
// public static final String DATABASE_STATE = "database_state";
public static final String RESOURCE_STATE = "resource_state";
public static final String KEY_PROFILE_REF = "app_profile_ref";
public static final String KEY_UPGRADE_MODE = "app_upgrade_mode";
public static final String KEY_ERROR_MODE = "app_error_mode";
public static final String KEY_REQUIRE_REFRESH = "require_referesh";
public static final String KEY_AUTO = "is_auto_update";
public static final String KEY_START_OVER = "start_over_uprgrade";
public static final String KEY_INSTALL_TIME = "last_install_time";
/*
* enum indicating which UI mconfiguration should be shown.
* basic: First install, user can scan barcode and move to ready mode or select advanced mode
* advanced: First install, user can enter bit.ly or URL directly, or return to basic mode
* ready: First install, barcode has been scanned. Can move to advanced mode to inspect URL, or proceed to install
* upgrade: App installed already. Buttons aren't shown, trying to update app with no user input
* error: Installation or Upgrade has failed, offer to retry or restart. upgrade/install differentiated with inUpgradeMode boolean
*/
public enum UiState { advanced, basic, ready, error, upgrade};
public UiState uiState = UiState.basic;
public static final int MODE_BASIC = Menu.FIRST;
public static final int MODE_ADVANCED = Menu.FIRST + 1;
public static final int MODE_ARCHIVE = Menu.FIRST + 2;
public static final int DIALOG_INSTALL_PROGRESS = 0;
public static final int BARCODE_CAPTURE = 1;
public static final int MISSING_MEDIA_ACTIVITY=2;
public static final int ARCHIVE_INSTALL = 3;
public static final int RETRY_LIMIT = 20;
boolean startAllowed = true;
boolean inUpgradeMode = false;
int dbState;
int resourceState;
int retryCount=0;
public String incomingRef;
public boolean canRetry;
public String displayMessage;
@UiElement(R.id.advanced_panel)
View advancedView;
@UiElement(R.id.screen_first_start_bottom)
View buttonView;
@UiElement(R.id.edit_profile_location)
EditText editProfileRef;
@UiElement(R.id.str_setup_message)
TextView mainMessage;
@UiElement(R.id.url_spinner)
Spinner urlSpinner;
@UiElement(R.id.start_install)
Button installButton;
@UiElement(R.id.btn_fetch_uri)
Button mScanBarcodeButton;
@UiElement(R.id.enter_app_location)
Button addressEntryButton;
@UiElement(R.id.start_over)
Button startOverButton;
@UiElement(R.id.retry_install)
Button retryButton;
@UiElement(R.id.screen_first_start_banner)
View banner;
String [] urlVals;
int previousUrlPosition=0;
boolean partialMode = false;
CommCareApp ccApp;
//Whether this needs to be interactive (if it's automatic, we want to skip a lot of the UI stuff
boolean isAuto = false;
//fields for installation retry
long lastInstallTime;
boolean startOverInstall;
static final long START_OVER_THRESHOLD = 604800000; //1 week in milliseconds
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
CommCareSetupActivity oldActivity = (CommCareSetupActivity)this.getDestroyedActivityState();
//Retrieve instance state
if(savedInstanceState == null) {
if(Intent.ACTION_VIEW.equals(this.getIntent().getAction())) {
//We got called from an outside application, it's gonna be a wild ride!
incomingRef = this.getIntent().getData().toString();
if(incomingRef.contains(".ccz")){
// make sure this is in the file system
boolean isFile = incomingRef.contains("file:
if(isFile){
// remove file:// prepend
incomingRef = incomingRef.substring(incomingRef.indexOf("
Intent i = new Intent(this, InstallArchiveActivity.class);
i.putExtra(InstallArchiveActivity.ARCHIVE_REFERENCE, incomingRef);
startActivityForResult(i, ARCHIVE_INSTALL);
}
else{
fail(NotificationMessageFactory.message(NotificationMessageFactory.StockMessages.Bad_Archive_File), true, false);
}
}
else{
this.uiState=uiState.ready;
//Now just start up normally.
}
} else{
incomingRef = this.getIntent().getStringExtra(KEY_PROFILE_REF);
}
inUpgradeMode = this.getIntent().getBooleanExtra(KEY_UPGRADE_MODE, false);
isAuto = this.getIntent().getBooleanExtra(KEY_AUTO, false);
} else {
String uiStateEncoded = savedInstanceState.getString("advanced");
this.uiState = uiStateEncoded == null ? UiState.basic : UiState.valueOf(UiState.class, uiStateEncoded);
incomingRef = savedInstanceState.getString("profileref");
inUpgradeMode = savedInstanceState.getBoolean(KEY_UPGRADE_MODE);
isAuto = savedInstanceState.getBoolean(KEY_AUTO);
//added
startOverInstall = savedInstanceState.getBoolean(KEY_START_OVER);
lastInstallTime = savedInstanceState.getLong(KEY_INSTALL_TIME);
//Uggggh, this might not be 100% legit depending on timing, what if we've already reconnected and shut down the dialog?
startAllowed = savedInstanceState.getBoolean("startAllowed");
}
// if we are in upgrade mode we want the UiState to reflect that, unless we are showing an error
if(inUpgradeMode && this.uiState != UiState.error){
this.uiState = UiState.upgrade;
}
editProfileRef.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
urlSpinner.setAdapter(new WrappingSpinnerAdapter(urlSpinner.getAdapter(), getResources().getStringArray(R.array.url_list_selected_display)));
urlVals = getResources().getStringArray(R.array.url_vals);
urlSpinner.setOnItemSelectedListener(new OnItemSelectedListener(){
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
if((previousUrlPosition == 0 || previousUrlPosition == 1) && arg2 == 2){
editProfileRef.setText(R.string.default_app_server);
}
else if(previousUrlPosition == 2 && (arg2 == 0 || arg2 == 1)){
editProfileRef.setText("");
}
previousUrlPosition = arg2;
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {}
});
//First, identify the binary state
dbState = CommCareApplication._().getDatabaseState();
resourceState = CommCareApplication._().getAppResourceState();
if(!Intent.ACTION_VIEW.equals(this.getIntent().getAction())) {
//Otherwise we're starting up being called from inside the app. Check to see if everything is set
//and we can just skip this unless it's upgradeMode
if(dbState == CommCareApplication.STATE_READY && resourceState == CommCareApplication.STATE_READY && !inUpgradeMode) {
Intent i = new Intent(getIntent());
setResult(RESULT_OK, i);
finish();
return;
}
}
mScanBarcodeButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
try {
Intent i = new Intent("com.google.zxing.client.android.SCAN");
//Barcode only
i.putExtra("SCAN_FORMATS","QR_CODE");
CommCareSetupActivity.this.startActivityForResult(i, BARCODE_CAPTURE);
} catch (ActivityNotFoundException e) {
Toast.makeText(CommCareSetupActivity.this,"No barcode scanner installed on phone!", Toast.LENGTH_SHORT).show();
mScanBarcodeButton.setVisibility(View.GONE);
}
}
});
addressEntryButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
setUiState(UiState.advanced);
refreshView();
}
});
addressEntryButton.setText(Localization.get("install.button.enter"));
startOverButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if(inUpgradeMode) {
startResourceInstall(true);
} else {
retryCount = 0;
partialMode = false;
setUiState(UiState.basic);
refreshView();
}
}
});
retryButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
partialMode = true;
startResourceInstall(false);
}
});
installButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//Now check on the resources
if(resourceState == CommCareApplication.STATE_READY) {
if(!inUpgradeMode || uiState != UiState.error) {
fail(NotificationMessageFactory.message(ResourceEngineOutcomes.StatusFailState), true);
}
} else if(resourceState == CommCareApplication.STATE_UNINSTALLED ||
(resourceState == CommCareApplication.STATE_UPGRADE && inUpgradeMode)) {
startResourceInstall();
}
}
});
final View activityRootView = findViewById(R.id.screen_first_start_main);
activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
int hideAll = CommCareSetupActivity.this.getResources().getInteger(R.integer.login_screen_hide_all_cuttoff);
int hideBanner = CommCareSetupActivity.this.getResources().getInteger(R.integer.login_screen_hide_banner_cuttoff);
int height = activityRootView.getHeight();
if(height < hideAll) {
banner.setVisibility(View.GONE);
} else if(height < hideBanner) {
banner.setVisibility(View.GONE);
} else {
banner.setVisibility(View.VISIBLE);
}
}
});
// reclaim ccApp for resuming installation
if(oldActivity != null) {
this.ccApp = oldActivity.ccApp;
}
refreshView();
//prevent the keyboard from popping up on entry by refocusing on the main layout
findViewById(R.id.mainLayout).requestFocus();
}
public void refreshView(){
switch(uiState){
case basic:
this.setModeToBasic();
break;
case advanced:
this.setModeToAdvanced();
break;
case error:
this.setModeToError(true);
break;
case upgrade:
this.setModeToAutoUpgrade();
break;
case ready:
this.setModeToReady(incomingRef);
break;
}
}
/*
* (non-Javadoc)
* @see android.support.v4.app.FragmentActivity#onStart()
*/
@Override
protected void onStart() {
super.onStart();
//Moved here to properly attach fragments and such.
//NOTE: May need to do so elsewhere as well
if(uiState == UiState.upgrade) {
refreshView();
mainMessage.setText(Localization.get("updates.check"));
startResourceInstall();
}
}
/* (non-Javadoc)
* @see org.commcare.android.framework.CommCareActivity#getWakeLockingLevel()
*/
@Override
protected int getWakeLockingLevel() {
return PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE;
}
/*
* (non-Javadoc)
*
* @see android.app.Activity#onSaveInstanceState(android.os.Bundle)
*/
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString("advanced", uiState.toString());
outState.putString("profileref", incomingRef);
outState.putBoolean(KEY_AUTO, isAuto);
outState.putBoolean("startAllowed", startAllowed);
outState.putBoolean(KEY_UPGRADE_MODE, inUpgradeMode);
outState.putBoolean(KEY_START_OVER, startOverInstall);
outState.putLong(KEY_INSTALL_TIME, lastInstallTime);
}
/* (non-Javadoc)
* @see android.app.Activity#onActivityResult(int, int, android.content.Intent)
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == BARCODE_CAPTURE) {
if(resultCode == Activity.RESULT_CANCELED) {
//Basically nothing
} else if(resultCode == Activity.RESULT_OK) {
String result = data.getStringExtra("SCAN_RESULT");
incomingRef = result;
//Definitely have a URI now.
try{
ReferenceManager._().DeriveReference(incomingRef);
}
catch(InvalidReferenceException ire){
this.setModeToBasic(Localization.get("install.bad.ref"));
return;
}
setUiState(UiState.ready);
this.refreshView();
}
}
if(requestCode == ARCHIVE_INSTALL){
if(resultCode == Activity.RESULT_CANCELED) {
//Basically nothing
} else if(resultCode == Activity.RESULT_OK) {
String result = data.getStringExtra(InstallArchiveActivity.ARCHIVE_REFERENCE);
incomingRef = result;
//Definitely have a URI now.
try{
ReferenceManager._().DeriveReference(incomingRef);
}
catch(InvalidReferenceException ire){
this.setModeToBasic(Localization.get("install.bad.ref"));
return;
}
setUiState(UiState.ready);
this.refreshView();
}
}
}
private String getRef(){
String ref;
if(this.uiState == UiState.advanced) {
int selectedIndex = urlSpinner.getSelectedItemPosition();
String selectedString = urlVals[selectedIndex];
if(previousUrlPosition != 2){
ref = selectedString + editProfileRef.getText().toString();
}
else{
ref = editProfileRef.getText().toString();
}
}
else{
ref = incomingRef;
}
return ref;
}
private CommCareApp getCommCareApp(){
CommCareApp app = null;
// we are in upgrade mode, just send back current app
if(inUpgradeMode){
app = CommCareApplication._().getCurrentApp();
return app;
}
//we have a clean slate, create a new app
if(partialMode){
return ccApp;
}
else{
ApplicationRecord newRecord = new ApplicationRecord(PropertyUtils.genUUID().replace("-",""), ApplicationRecord.STATUS_UNINITIALIZED);
app = new CommCareApp(newRecord);
return app;
}
}
private void startResourceInstall() {
if (System.currentTimeMillis() - lastInstallTime > START_OVER_THRESHOLD) {
/*If we are triggering a start over install due to the time threshold
* when there is a partial resource table that we could be using, send
* a message to log this.
*/
AndroidCommCarePlatform platform = getCommCareApp().getCommCarePlatform();
ResourceTable temporary = platform.getUpgradeResourceTable();
if (temporary.getTableReadiness() == ResourceTable.RESOURCE_TABLE_PARTIAL) {
Logger.log(AndroidLogger.TYPE_RESOURCES, "A start-over on installation has been "
+ "triggered by the time threshold when there is an existing partial "
+ "resource table that could be used.");
}
startResourceInstall(true);
}
else {
startResourceInstall(this.startOverInstall);
}
}
/* (non-Javadoc)
* @see org.commcare.android.tasks.templates.CommCareTaskConnector#startBlockingForTask()
*/
@Override
public void startBlockingForTask(int id) {
super.startBlockingForTask(id);
this.startAllowed = false;
}
/* (non-Javadoc)
* @see org.commcare.android.tasks.templates.CommCareTaskConnector#stopBlockingForTask()
*/
@Override
public void stopBlockingForTask(int id) {
super.stopBlockingForTask(id);
this.startAllowed = true;
}
/**
* @param startOverUpgrade - what determines whether CommCarePlatform.stageUpgradeTable()
* reuses the last version of the upgrade table, or starts over
*/
private void startResourceInstall(boolean startOverUpgrade) {
if(startAllowed) {
String ref = getRef();
CommCareApp app = getCommCareApp();
ccApp = app;
ResourceEngineTask<CommCareSetupActivity> task = new ResourceEngineTask<CommCareSetupActivity>(this, inUpgradeMode, partialMode, app, startOverUpgrade,DIALOG_INSTALL_PROGRESS) {
@Override
protected void deliverResult(CommCareSetupActivity receiver, org.commcare.android.tasks.ResourceEngineTask.ResourceEngineOutcomes result) {
lastInstallTime = System.currentTimeMillis();
if(result == ResourceEngineOutcomes.StatusInstalled){
receiver.reportSuccess(true);
receiver.startOverInstall = false;
} else if(result == ResourceEngineOutcomes.StatusUpToDate){
receiver.reportSuccess(false);
receiver.startOverInstall = false;
} else if(result == ResourceEngineOutcomes.StatusMissing || result == ResourceEngineOutcomes.StatusMissingDetails){
receiver.failMissingResource(this.missingResourceException, result);
receiver.startOverInstall = false;
} else if(result == ResourceEngineOutcomes.StatusBadReqs){
receiver.failBadReqs(badReqCode, vRequired, vAvailable, majorIsProblem);
receiver.startOverInstall = false;
} else if(result == ResourceEngineOutcomes.StatusFailState){
receiver.failWithNotification(ResourceEngineOutcomes.StatusFailState);
receiver.startOverInstall = true;
} else if(result == ResourceEngineOutcomes.StatusNoLocalStorage) {
receiver.failWithNotification(ResourceEngineOutcomes.StatusNoLocalStorage);
receiver.startOverInstall = true;
} else if(result == ResourceEngineOutcomes.StatusBadCertificate){
receiver.failWithNotification(ResourceEngineOutcomes.StatusBadCertificate);
receiver.startOverInstall = false;
} else {
receiver.failUnknown(ResourceEngineOutcomes.StatusFailUnknown);
receiver.startOverInstall = true;
}
}
@Override
protected void deliverUpdate(CommCareSetupActivity receiver, int[]... update) {
receiver.updateProgress(update[0][0], update[0][1], update[0][2]);
}
@Override
protected void deliverError(CommCareSetupActivity receiver, Exception e) {
receiver.failUnknown(ResourceEngineOutcomes.StatusFailUnknown);
}
};
task.connect(this);
task.execute(ref);
} else {
Log.i("commcare-install", "Blocked a resource install press since a task was already running");
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(0, MODE_BASIC, 0, Localization.get("menu.basic")).setIcon(android.R.drawable.ic_menu_help);
menu.add(0, MODE_ADVANCED, 0, Localization.get("menu.advanced")).setIcon(android.R.drawable.ic_menu_edit);
menu.add(0, MODE_ARCHIVE, 0, Localization.get("menu.archive")).setIcon(android.R.drawable.ic_menu_upload);
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
MenuItem basic = menu.findItem(MODE_BASIC);
MenuItem advanced = menu.findItem(MODE_ADVANCED);
if(uiState == UiState.advanced) {
basic.setVisible(true);
advanced.setVisible(false);
} else if(uiState == UiState.ready){
basic.setVisible(false);
advanced.setVisible(true);
} else if(uiState == UiState.basic){
basic.setVisible(false);
advanced.setVisible(true);
} else{
basic.setVisible(false);
advanced.setVisible(false);
}
return true;
}
public void setModeToAutoUpgrade(){
retryButton.setText(Localization.get("upgrade.button.retry"));
startOverButton.setText(Localization.get("upgrade.button.startover"));
buttonView.setVisibility(View.INVISIBLE);
}
public void setModeToReady(String incomingRef) {
buttonView.setVisibility(View.VISIBLE);
mainMessage.setText(Localization.get("install.ready"));
editProfileRef.setText(incomingRef);
advancedView.setVisibility(View.GONE);
mScanBarcodeButton.setVisibility(View.GONE);
installButton.setVisibility(View.VISIBLE);
startOverButton.setText(Localization.get("install.button.startover"));
startOverButton.setVisibility(View.VISIBLE);
addressEntryButton.setVisibility(View.GONE);
retryButton.setVisibility(View.GONE);
}
public void setModeToError(boolean canRetry){
buttonView.setVisibility(View.VISIBLE);
advancedView.setVisibility(View.GONE);
mScanBarcodeButton.setVisibility(View.GONE);
installButton.setVisibility(View.GONE);
startOverButton.setVisibility(View.VISIBLE);
addressEntryButton.setVisibility(View.GONE);
if(canRetry){
retryButton.setVisibility(View.VISIBLE);
}
else{
retryButton.setVisibility(View.GONE);
}
}
public void setModeToBasic(){
this.setModeToBasic(Localization.get("install.barcode"));
}
public void setModeToBasic(String message){
buttonView.setVisibility(View.VISIBLE);
editProfileRef.setText("");
this.incomingRef = null;
mainMessage.setText(message);
addressEntryButton.setVisibility(View.VISIBLE);
advancedView.setVisibility(View.GONE);
mScanBarcodeButton.setVisibility(View.VISIBLE);
startOverButton.setVisibility(View.GONE);
installButton.setVisibility(View.GONE);
retryButton.setVisibility(View.GONE);
retryButton.setText(Localization.get("install.button.retry"));
startOverButton.setText(Localization.get("install.button.startover"));
}
public void setModeToAdvanced(){
buttonView.setVisibility(View.VISIBLE);
mainMessage.setText(Localization.get("install.manual"));
advancedView.setVisibility(View.VISIBLE);
mScanBarcodeButton.setVisibility(View.GONE);
addressEntryButton.setVisibility(View.GONE);
installButton.setVisibility(View.VISIBLE);
startOverButton.setText(Localization.get("install.button.startover"));
startOverButton.setVisibility(View.VISIBLE);
installButton.setEnabled(true);
retryButton.setVisibility(View.GONE);
retryButton.setText(Localization.get("install.button.retry"));
startOverButton.setText(Localization.get("install.button.startover"));
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MODE_BASIC:
setUiState(UiState.basic);
break;
case MODE_ADVANCED:
setUiState(UiState.advanced);
break;
case MODE_ARCHIVE:
Intent i = new Intent(getApplicationContext(), InstallArchiveActivity.class);
startActivityForResult(i, ARCHIVE_INSTALL);
break;
}
refreshView();
return true;
}
/* (non-Javadoc)
* @see android.app.Activity#onCreateDialog(int)
*/
@Override
protected Dialog onCreateDialog(int id) {
if(id == DIALOG_INSTALL_PROGRESS) {
ProgressDialog mProgressDialog = new ProgressDialog(this) {
/* (non-Javadoc)
* @see android.app.Dialog#onWindowFocusChanged(boolean)
*/
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
//TODO: Should we generalize this in some way? Not sure if it's happening elsewhere.
if(hasFocus && Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
try {
getWindow().getDecorView().invalidate();
getWindow().getDecorView().requestLayout();
} catch(Exception e){
e.printStackTrace();
Log.i("CommCare", "Error came up while forcing re-layout for dialog box");
}
}
}
};
if(uiState == UiState.upgrade) {
mProgressDialog.setTitle(Localization.get("updates.title"));
mProgressDialog.setMessage(Localization.get("updates.checking"));
refreshView();
} else {
mProgressDialog.setTitle(Localization.get("updates.resources.initialization"));
mProgressDialog.setMessage(Localization.get("updates.resources.profile"));
refreshView();
}
mProgressDialog.setIndeterminate(true);
mProgressDialog.setCancelable(false);
return mProgressDialog;
}
return null;
}
public void updateProgress(int done, int total, int phase) {
if(inUpgradeMode) {
if(phase == ResourceEngineTask.PHASE_DOWNLOAD) {
updateProgress(DIALOG_INSTALL_PROGRESS, Localization.get("updates.found", new String[] {""+done,""+total}));
} if(phase == ResourceEngineTask.PHASE_COMMIT) {
updateProgress(DIALOG_INSTALL_PROGRESS,Localization.get("updates.downloaded"));
}
}
else {
updateProgress(DIALOG_INSTALL_PROGRESS, Localization.get("profile.found", new String[]{""+done,""+total}));
}
}
public void done(boolean requireRefresh) {
//TODO: We might have gotten here due to being called from the outside, in which
//case we should manually start up the home activity
if(Intent.ACTION_VIEW.equals(CommCareSetupActivity.this.getIntent().getAction())) {
//Call out to CommCare Home
Intent i = new Intent(getApplicationContext(), CommCareHomeActivity.class);
i.putExtra(KEY_REQUIRE_REFRESH, requireRefresh);
startActivity(i);
finish();
return;
} else {
//Good to go
Intent i = new Intent(getIntent());
i.putExtra(KEY_REQUIRE_REFRESH, requireRefresh);
setResult(RESULT_OK, i);
finish();
return;
}
}
public void fail(NotificationMessage message) {
fail(message, false);
}
public void fail(NotificationMessage message, boolean alwaysNotify) {
fail(message, alwaysNotify, true);
}
public void fail(NotificationMessage message, boolean alwaysNotify, boolean canRetry){
Toast.makeText(this, message.getTitle(), Toast.LENGTH_LONG).show();
setUiState(UiState.error);
retryCount++;
if(retryCount > RETRY_LIMIT){
canRetry = false;
}
if(isAuto || alwaysNotify) {
CommCareApplication._().reportNotificationMessage(message);
}
if(isAuto) {
done(false);
} else {
if(alwaysNotify) {
this.displayMessage= Localization.get("notification.for.details.wrapper", new String[] {message.getDetails()});
this.canRetry = canRetry;
mainMessage.setText(displayMessage);
} else {
this.displayMessage= message.getDetails();
this.canRetry = canRetry;
String fullErrorMessage = message.getDetails();
if(alwaysNotify){
fullErrorMessage = fullErrorMessage + message.getAction();
}
mainMessage.setText(fullErrorMessage);
}
}
refreshView();
}
/**
* Sets the state of the Ui and handles one-off changes that might need
* to happen between certain states.
* @param newUiState
*/
public void setUiState(UiState newUiState){
//We might want to do some one-off configuration
//stuff if we're undergoing certain transitions
//Ready -> Advanced: Set up the URL Spinner appropriately.
if(this.uiState == UiState.ready && newUiState == UiState.advanced){
previousUrlPosition = -1;
urlSpinner.setSelection(2);
}
this.uiState = newUiState;
}
// All final paths from the Update are handled here (Important! Some interaction modes should always auto-exit this activity)
// Everything here should call one of: fail() or done()
public void reportSuccess(boolean appChanged) {
//If things worked, go ahead and clear out any warnings to the contrary
CommCareApplication._().clearNotifications("install_update");
if(!appChanged) {
Toast.makeText(this, Localization.get("updates.success"), Toast.LENGTH_LONG).show();
}
done(appChanged);
}
public void failMissingResource(UnresolvedResourceException ure, ResourceEngineOutcomes statusMissing) {
fail(NotificationMessageFactory.message(statusMissing, new String[] {null, ure.getResource().getDescriptor(), ure.getMessage()}), ure.isMessageUseful());
}
public void failBadReqs(int code, String vRequired, String vAvailable, boolean majorIsProblem) {
String versionMismatch = Localization.get("install.version.mismatch", new String[] {vRequired,vAvailable});
String error = "";
if(majorIsProblem){
error=Localization.get("install.major.mismatch");
}
else{
error=Localization.get("install.minor.mismatch");
}
fail(NotificationMessageFactory.message(ResourceEngineOutcomes.StatusBadReqs, new String[] {null, versionMismatch, error}), true);
}
public void failUnknown(ResourceEngineOutcomes unknown) {
fail(NotificationMessageFactory.message(unknown));
}
public void failWithNotification(ResourceEngineOutcomes statusfailstate) {
fail(NotificationMessageFactory.message(statusfailstate), true);
}
@Override
public void onBackPressed(){
if(uiState == UiState.advanced) {
setUiState(UiState.basic);
setModeToBasic();
} else if(uiState == UiState.ready){
setUiState(UiState.basic);
setModeToBasic();
} else{
super.onBackPressed();
}
}
}
|
package org.intermine.bio.dataconversion;
import java.io.File;
import java.io.StringReader;
import java.util.Collections;
import java.util.HashMap;
import java.util.Set;
import org.apache.commons.io.IOUtils;
import org.intermine.dataconversion.ItemsTestCase;
import org.intermine.dataconversion.MockItemWriter;
import org.intermine.metadata.Model;
public class EnsemblComparaConverterTest extends ItemsTestCase
{
Model model = Model.getInstanceByName("genomic");
EnsemblComparaConverter converter;
MockItemWriter itemWriter;
private String TEST_FILE = "7227_9606";
public EnsemblComparaConverterTest(String arg) {
super(arg);
}
public void setUp() throws Exception {
super.setUp();
itemWriter = new MockItemWriter(new HashMap());
converter = new EnsemblComparaConverter(itemWriter, model);
MockIdResolverFactory resolverFactory = new MockIdResolverFactory("Gene");
resolverFactory.addResolverEntry("7227", "FBgn001", Collections.singleton("FBgn001"));
resolverFactory.addResolverEntry("7227", "FBgn003", Collections.singleton("FBgn002"));
converter.resolver = resolverFactory.getIdResolver(false);
}
public void testProcess() throws Exception {
ClassLoader loader = getClass().getClassLoader();
String input = IOUtils.toString(loader.getResourceAsStream(TEST_FILE));
File currentFile = new File(getClass().getClassLoader().getResource(TEST_FILE).toURI());
converter.setCurrentFile(currentFile);
converter.setEnsemblComparaOrganisms("10116 6239 7227");
converter.setEnsemblComparaHomologues("9606");
converter.process(new StringReader(input));
converter.close();
// uncomment to write out a new target items file
//writeItemsFile(itemWriter.getItems(), "ensembl-compara-tgt-items.xml");
Set expected = readItemSet("EnsemblComparaConverterTest_tgt.xml");
// FIXME
// assertEquals(expected, itemWriter.getItems());
}
}
|
package eu.kanade.mangafeed;
import org.junit.Before;
import org.junit.Test;
import eu.kanade.mangafeed.data.database.models.Chapter;
import eu.kanade.mangafeed.data.database.models.Manga;
import eu.kanade.mangafeed.util.ChapterRecognition;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
public class ChapterRecognitionTest {
Manga randomManga;
private Chapter createChapter(String title) {
Chapter chapter = Chapter.create();
chapter.name = title;
return chapter;
}
@Before
public void setUp() {
randomManga = new Manga();
randomManga.title = "Something";
}
@Test
public void testWithOneDigit() {
Chapter c = createChapter("Ch.3: Self-proclaimed Genius");
ChapterRecognition.parseChapterNumber(c, randomManga);
assertThat(c.chapter_number, is(3f));
}
@Test
public void testWithVolumeBefore() {
Chapter c = createChapter("Vol.1 Ch.4: Misrepresentation");
ChapterRecognition.parseChapterNumber(c, randomManga);
assertThat(c.chapter_number, is(4f));
}
@Test
public void testWithVolumeAndVersionNumber() {
Chapter c = createChapter("Vol.1 Ch.3 (v2) Read Online");
ChapterRecognition.parseChapterNumber(c, randomManga);
assertThat(c.chapter_number, is(3f));
}
@Test
public void testWithVolumeAndNumberInTitle() {
Chapter c = createChapter("Vol.15 Ch.90: Here Blooms the Daylily, Part 4");
ChapterRecognition.parseChapterNumber(c, randomManga);
assertThat(c.chapter_number, is(90f));
}
@Test
public void testWithVolumeAndSpecialChapter() {
Chapter c = createChapter("Vol.10 Ch.42.5: Homecoming (Beginning)");
ChapterRecognition.parseChapterNumber(c, randomManga);
assertThat(c.chapter_number, is(42.5f));
}
@Test
public void testWithJustANumber() {
Chapter c = createChapter("Homecoming (Beginning) 42");
ChapterRecognition.parseChapterNumber(c, randomManga);
assertThat(c.chapter_number, is(42f));
}
@Test
public void testWithJustASpecialChapter() {
Chapter c = createChapter("Homecoming (Beginning) 42.5");
ChapterRecognition.parseChapterNumber(c, randomManga);
assertThat(c.chapter_number, is(42.5f));
}
@Test
public void testWithNumberinMangaTitle() {
Chapter c = createChapter("3x3 Eyes 96");
Manga m = new Manga();
m.title = "3x3 Eyes";
ChapterRecognition.parseChapterNumber(c, m);
assertThat(c.chapter_number, is(96f));
}
}
|
package me.exphc.AtmosphericHeights;
import java.util.Collections;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.UUID;
import java.util.Iterator;
import java.util.logging.Logger;
import java.util.concurrent.ConcurrentHashMap;
import java.util.Formatter;
import java.util.Random;
import java.lang.Byte;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.io.*;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.plugin.*;
import org.bukkit.event.*;
import org.bukkit.event.block.*;
import org.bukkit.event.player.*;
import org.bukkit.event.entity.*;
import org.bukkit.Material.*;
import org.bukkit.material.*;
import org.bukkit.block.*;
import org.bukkit.entity.*;
import org.bukkit.command.*;
import org.bukkit.inventory.*;
import org.bukkit.configuration.*;
import org.bukkit.configuration.file.*;
import org.bukkit.scheduler.*;
import org.bukkit.enchantments.*;
import org.bukkit.*;
import net.minecraft.server.CraftingManager;
import org.bukkit.craftbukkit.enchantments.CraftEnchantment;
import org.bukkit.craftbukkit.inventory.CraftItemStack;
class AtmosphericHeightsListener implements Listener {
AtmosphericHeights plugin;
Random random;
final int tropopause, mesopause, magnetopause;
public AtmosphericHeightsListener(AtmosphericHeights plugin) {
this.plugin = plugin;
tropopause = plugin.getConfig().getInt("tropopause", 128);
mesopause = plugin.getConfig().getInt("mesopause", 256);
magnetopause = plugin.getConfig().getInt("magnetopause", 512);
// for inspiration see http://en.wikipedia.org/wiki/Earth%27s_atmosphere#Principal_layers
random = new Random();
Bukkit.getServer().getPluginManager().registerEvents(this, plugin);
}
@EventHandler(priority=EventPriority.MONITOR, ignoreCancelled=true)
public void onFoodLevelChange(FoodLevelChangeEvent event) {
HumanEntity entity = event.getEntity();
if (!(entity instanceof Player)) {
return;
}
Player player = (Player)entity;
int oldLevel = player.getFoodLevel();
int newLevel = event.getFoodLevel();
// hunger change in half hearts
int delta = oldLevel - newLevel;
plugin.log("Hunger change: " + oldLevel + " -> " + newLevel + " (delta = "+delta+")");
if (delta < 0) {
// increased = ate, do nothing
return;
}
int height = player.getLocation().getBlockY();
if (height > tropopause) {
applyHunger(player, event, delta, height, oldLevel);
}
if (height > mesopause) {
applySuffocation(player, height);
}
if (height > magnetopause) {
applyFire(player, height);
}
}
@EventHandler(priority=EventPriority.MONITOR, ignoreCancelled=true)
public void onPlayerMove(PlayerMoveEvent event) {
int height = event.getTo().getBlockY();
if (height > mesopause) {
applySuffocation(event.getPlayer(), height);
}
if (height > magnetopause) {
applyFire(event.getPlayer(), height);
}
}
// Thinner air, hungrier
private void applyHunger(Player player, FoodLevelChangeEvent event, int delta, int height, int oldLevel) {
double moreHunger = Math.ceil((height - tropopause) / plugin.getConfig().getDouble("hungerPerMeter", 10.0));
delta += moreHunger;
plugin.log("Above tropopause, new hunger delta = " + delta);
int newLevel = oldLevel - delta;
plugin.log("set level: " + newLevel);
event.setFoodLevel(newLevel);
}
// Meteors or no air, suffocating
private void applySuffocation(Player player, int height) {
if (random.nextInt(plugin.getConfig().getInt("damageChance", 10)) != 0) {
// lucked out
return;
}
int damage = (int)Math.ceil((height - mesopause) / plugin.getConfig().getDouble("damagePerMeter", 10.0));
damage = Math.max(damage, plugin.getConfig().getInt("damageMax", 10));
if (player.getHealth() - damage < plugin.getConfig().getInt("damageHealthMin", 2)) {
return; // you've been spared - can't go further
}
if (hasOxygenMask(player)) {
//plugin.log("Player "+player+" wearing oxygen mask, avoided suffocation damage "+damage);
return;
}
player.damage(damage);
player.setLastDamageCause(new EntityDamageEvent(player, EntityDamageEvent.DamageCause.SUFFOCATION, damage));
plugin.log("Above mesopause, suffocation damage = " + damage);
}
// Cosmic rays, unprotected from earth's magnetic field, set aflame
private void applyFire(Player player, int height) {
if (random.nextInt(plugin.getConfig().getInt("fireChance", 5)) != 0) {
return;
}
player.setFireTicks(plugin.getConfig().getInt("fireTicks", 20*2));
}
final Enchantment RESPIRATION = Enchantment.OXYGEN;
private boolean hasOxygenMask(Player player) {
ItemStack helmet = player.getInventory().getHelmet();
return helmet != null
&& plugin.getConfig().getBoolean("oxygenMaskEnabled", true)
&& helmet.containsEnchantment(RESPIRATION)
&& helmet.getEnchantmentLevel(RESPIRATION) >= plugin.getConfig().getInt("oxygenMaskMinLevel", 1);
}
private boolean hasSpacesuit(Player player) {
return false; // TODO
}
}
public class AtmosphericHeights extends JavaPlugin implements Listener {
Logger log = Logger.getLogger("Minecraft");
public void onEnable() {
getConfig().options().copyDefaults(true);
saveConfig();
reloadConfig();
new AtmosphericHeightsListener(this);
}
public void onDisable() {
}
public void log(String message) {
if (getConfig().getBoolean("verbose", true)) {
log.info(message);
}
}
}
|
package org.eclipse.birt.chart.ui.swt.wizard;
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.Axis;
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.StockSeries;
import org.eclipse.birt.chart.plugin.ChartEnginePlugin;
import org.eclipse.birt.chart.ui.extension.i18n.Messages;
import org.eclipse.birt.chart.ui.swt.interfaces.IDataServiceProvider;
import org.eclipse.birt.chart.ui.swt.interfaces.ISelectDataCustomizeUI;
import org.eclipse.birt.chart.ui.swt.interfaces.ITaskChangeListener;
import org.eclipse.birt.chart.ui.swt.wizard.data.SelectDataDynamicArea;
import org.eclipse.birt.chart.ui.swt.wizard.internal.ChartPreviewPainter;
import org.eclipse.birt.chart.ui.swt.wizard.internal.ColorPalette;
import org.eclipse.birt.chart.ui.swt.wizard.internal.CustomPreviewTable;
import org.eclipse.birt.chart.ui.swt.wizard.internal.DataDefinitionTextManager;
import org.eclipse.birt.chart.ui.util.ChartUIUtil;
import org.eclipse.birt.core.ui.frameworks.taskwizard.SimpleTask;
import org.eclipse.emf.common.notify.Notification;
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.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Canvas;
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.Menu;
import org.eclipse.swt.widgets.MenuItem;
public class TaskSelectData extends SimpleTask
implements
SelectionListener,
DisposeListener,
ITaskChangeListener,
Listener
{
private final static int CENTER_WIDTH_HINT = 400;
private transient ChartPreviewPainter previewPainter = null;
private transient Composite cmpTask = null;
private transient Composite cmpPreview = null;
private transient Canvas previewCanvas = null;
private transient Button btnUseReportData = null;
private transient Button btnUseDataSet = null;
private transient Combo cmbDataSet = null;
private transient Button btnNewData = null;
private transient CustomPreviewTable tablePreview = null;
private transient Button btnFilters = null;
private transient Button btnParameters = null;
private transient SelectDataDynamicArea dynamicArea;
// private SampleData oldSample = null;
public TaskSelectData( )
{
super( Messages.getString( "TaskSelectData.TaskExp" ) ); //$NON-NLS-1$
}
public Composite getUI( Composite parent )
{
if ( cmpTask == null || cmpTask.isDisposed( ) )
{
cmpTask = new Composite( parent, SWT.NONE );
GridLayout gridLayout = new GridLayout( 3, false );
gridLayout.marginWidth = 10;
gridLayout.marginHeight = 10;
cmpTask.setLayout( gridLayout );
cmpTask.setLayoutData( new GridData( GridData.GRAB_HORIZONTAL
| GridData.GRAB_VERTICAL ) );
cmpTask.addDisposeListener( this );
dynamicArea = new SelectDataDynamicArea( this );
getCustomizeUI( ).init( );
placeComponents( );
createPreviewPainter( );
init( );
}
else
{
customizeUI( );
}
doLivePreview( );
// Refresh all data definitino text
DataDefinitionTextManager.getInstance( ).refreshAll( );
return cmpTask;
}
protected void customizeUI( )
{
getCustomizeUI( ).init( );
refreshLeftArea( );
refreshRightArea( );
refreshBottomArea( );
getCustomizeUI( ).layoutAll( );
}
private void refreshLeftArea( )
{
getCustomizeUI( ).refreshLeftBindingArea( );
getCustomizeUI( ).selectLeftBindingArea( true, null );
}
private void refreshRightArea( )
{
getCustomizeUI( ).refreshRightBindingArea( );
getCustomizeUI( ).selectRightBindingArea( true, null );
}
private void refreshBottomArea( )
{
getCustomizeUI( ).refreshBottomBindingArea( );
getCustomizeUI( ).selectBottomBindingArea( true, null );
}
private void placeComponents( )
{
ChartAdapter.ignoreNotifications( true );
try
{
createHeadArea( );// place two rows
new Label( cmpTask, SWT.NONE );
createDataSetArea( cmpTask );
new Label( cmpTask, SWT.NONE );
new Label( cmpTask, SWT.NONE );
createDataPreviewTableArea( cmpTask );
createDataPreviewButtonArea( cmpTask );
new Label( cmpTask, SWT.NONE );
Label description = new Label( cmpTask, SWT.WRAP );
{
GridData gd = new GridData( );
gd.widthHint = CENTER_WIDTH_HINT;
description.setLayoutData( gd );
description.setText( Messages.getString( "TaskSelectData.Label.ToBindADataColumn" ) ); //$NON-NLS-1$
}
new Label( cmpTask, SWT.NONE );
}
finally
{
// THIS IS IN A FINALLY BLOCK TO ENSURE THAT NOTIFICATIONS ARE
// ENABLED EVEN IF ERRORS OCCUR DURING UI INITIALIZATION
ChartAdapter.ignoreNotifications( false );
}
}
private void createHeadArea( )
{
{
Composite cmpLeftContainer = ChartUIUtil.createCompositeWrapper( cmpTask );
GridData gridData = new GridData( GridData.FILL_HORIZONTAL
| GridData.VERTICAL_ALIGN_CENTER );
gridData.verticalSpan = 2;
cmpLeftContainer.setLayoutData( gridData );
getCustomizeUI( ).createLeftBindingArea( cmpLeftContainer );
}
createPreviewArea( );
{
Composite cmpRightContainer = ChartUIUtil.createCompositeWrapper( cmpTask );
GridData gridData = new GridData( GridData.FILL_HORIZONTAL
| GridData.VERTICAL_ALIGN_CENTER );
gridData.verticalSpan = 2;
cmpRightContainer.setLayoutData( gridData );
getCustomizeUI( ).createRightBindingArea( cmpRightContainer );
}
{
Composite cmpBottomContainer = ChartUIUtil.createCompositeWrapper( cmpTask );
GridData gridData = new GridData( GridData.FILL_HORIZONTAL
| GridData.VERTICAL_ALIGN_BEGINNING );
cmpBottomContainer.setLayoutData( gridData );
getCustomizeUI( ).createBottomBindingArea( cmpBottomContainer );
}
}
private void createPreviewArea( )
{
cmpPreview = ChartUIUtil.createCompositeWrapper( cmpTask );
{
GridData gridData = new GridData( GridData.FILL_BOTH );
gridData.widthHint = CENTER_WIDTH_HINT;
gridData.heightHint = 200;
cmpPreview.setLayoutData( gridData );
}
Label label = new Label( cmpPreview, SWT.NONE );
{
label.setFont( JFaceResources.getBannerFont( ) );
label.setText( Messages.getString( "TaskSelectData.Label.ChartPreview" ) ); //$NON-NLS-1$
}
previewCanvas = new Canvas( cmpPreview, SWT.BORDER );
{
GridData gd = new GridData( GridData.FILL_BOTH );
previewCanvas.setLayoutData( gd );
previewCanvas.setBackground( Display.getDefault( )
.getSystemColor( SWT.COLOR_WHITE ) );
}
}
private void createDataSetArea( 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( "TaskSelectData.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 comp = ChartUIUtil.createCompositeWrapper( cmpDetail );
btnUseReportData = new Button( comp, SWT.RADIO );
btnUseReportData.setText( Messages.getString( "TaskSelectData.Label.UseReportData" ) ); //$NON-NLS-1$
btnUseReportData.addSelectionListener( this );
btnUseDataSet = new Button( comp, SWT.RADIO );
btnUseDataSet.setText( Messages.getString( "TaskSelectData.Label.UseDataSet" ) ); //$NON-NLS-1$
btnUseDataSet.addSelectionListener( this );
cmbDataSet = new Combo( cmpDetail, SWT.DROP_DOWN | SWT.READ_ONLY );
cmbDataSet.setLayoutData( new GridData( GridData.VERTICAL_ALIGN_END
| GridData.FILL_HORIZONTAL ) );
cmbDataSet.addSelectionListener( this );
btnNewData = new Button( cmpDetail, SWT.NONE );
{
btnNewData.setLayoutData( new GridData( GridData.VERTICAL_ALIGN_END ) );
btnNewData.setText( Messages.getString( "TaskSelectData.Label.CreateNew" ) ); //$NON-NLS-1$
btnNewData.setToolTipText( Messages.getString( "TaskSelectData.Tooltip.CreateNewDataset" ) ); //$NON-NLS-1$
btnNewData.addSelectionListener( this );
}
}
private void createDataPreviewTableArea( Composite parent )
{
Composite composite = ChartUIUtil.createCompositeWrapper( parent );
{
composite.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
}
Label label = new Label( composite, SWT.NONE );
{
label.setText( Messages.getString( "TaskSelectData.Label.DataPreview" ) ); //$NON-NLS-1$
label.setFont( JFaceResources.getBannerFont( ) );
}
tablePreview = new CustomPreviewTable( composite, SWT.SINGLE
| SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION );
{
GridData gridData = new GridData( GridData.FILL_HORIZONTAL );
gridData.widthHint = CENTER_WIDTH_HINT;
gridData.heightHint = 150;
tablePreview.setLayoutData( gridData );
tablePreview.setHeaderAlignment( SWT.LEFT );
tablePreview.addListener( CustomPreviewTable.MOUSE_RIGHT_CLICK_TYPE,
this );
}
dynamicArea.setCustomPreviewTable( tablePreview );
}
private void createDataPreviewButtonArea( Composite parent )
{
Composite composite = ChartUIUtil.createCompositeWrapper( parent );
{
composite.setLayoutData( new GridData( GridData.VERTICAL_ALIGN_END ) );
}
btnFilters = new Button( composite, SWT.NONE );
{
btnFilters.setAlignment( SWT.CENTER );
GridData gridData = new GridData( );
gridData.widthHint = 80;
btnFilters.setLayoutData( gridData );
btnFilters.setText( Messages.getString( "TaskSelectData.Label.Filters" ) ); //$NON-NLS-1$
btnFilters.addSelectionListener( this );
}
btnParameters = new Button( composite, SWT.NONE );
{
btnParameters.setAlignment( SWT.CENTER );
GridData gridData = new GridData( );
gridData.widthHint = 80;
btnParameters.setLayoutData( gridData );
btnParameters.setText( Messages.getString( "TaskSelectData.Label.Parameters" ) ); //$NON-NLS-1$
btnParameters.addSelectionListener( this );
}
}
protected void init( )
{
// Create data set list
String currentDataSet = getDataServiceProvider( ).getBoundDataSet( );
if ( currentDataSet != null )
{
cmbDataSet.setItems( getDataServiceProvider( ).getAllDataSets( ) );
cmbDataSet.setText( currentDataSet );
useReportDataSet( false );
switchDataTable( cmbDataSet.getText( ) );
}
else
{
useReportDataSet( true );
String reportDataSet = getDataServiceProvider( ).getReportDataSet( );
if ( reportDataSet != null )
{
switchDataTable( reportDataSet );
}
}
btnFilters.setEnabled( hasDataSet( ) );
btnParameters.setEnabled( hasDataSet( ) );
}
private void useReportDataSet( boolean bDS )
{
btnUseReportData.setSelection( bDS );
btnUseDataSet.setSelection( !bDS );
cmbDataSet.setEnabled( !bDS );
btnNewData.setEnabled( !bDS );
}
private void refreshTableColor( )
{
// Reset column color
for ( int i = 0; i < tablePreview.getColumnNumber( ); i++ )
{
tablePreview.setColumnColor( i,
ColorPalette.getInstance( )
.getColor( ChartUIUtil.getExpressionString( tablePreview.getColumnHeading( i ) ) ) );
}
}
private void switchDataTable( String datasetName )
{
try
{
// Add data header
String[] header = getDataServiceProvider( ).getPreviewHeader( );
if ( header == null )
{
tablePreview.setEnabled( false );
tablePreview.createDummyTable( );
}
else
{
tablePreview.setEnabled( true );
tablePreview.setColumns( header );
refreshTableColor( );
// Add data value
List dataList = getDataServiceProvider( ).getPreviewData( );
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 );
}
}
}
}
catch ( ChartException e )
{
ChartWizard.displayException( e );
}
}
private void createPreviewPainter( )
{
previewPainter = new ChartPreviewPainter( (ChartWizardContext) getContext( ) );
previewCanvas.addPaintListener( previewPainter );
previewCanvas.addControlListener( previewPainter );
previewPainter.setPreview( previewCanvas );
}
protected Chart getChartModel( )
{
if ( getContext( ) == null )
{
return null;
}
return ( (ChartWizardContext) getContext( ) ).getModel( );
}
private void switchDataSet( String datasetName ) throws ChartException
{
try
{
getDataServiceProvider( ).setDataSet( datasetName );
tablePreview.clearContents( );
// Try to get report data set
if ( datasetName == null )
{
datasetName = getDataServiceProvider( ).getReportDataSet( );
}
if ( datasetName != null )
{
switchDataTable( datasetName );
}
else
{
tablePreview.createDummyTable( );
}
tablePreview.layout( );
}
catch ( Throwable t )
{
throw new ChartException( ChartEnginePlugin.ID,
ChartException.DATA_BINDING,
t );
}
DataDefinitionTextManager.getInstance( ).refreshAll( );
doLivePreview( );
}
public void widgetSelected( SelectionEvent e )
{
if ( e.getSource( ).equals( btnUseReportData ) )
{
// Skip when selection is false
if ( !btnUseReportData.getSelection( ) )
{
return;
}
try
{
switchDataSet( null );
}
catch ( ChartException e1 )
{
ChartWizard.displayException( e1 );
}
cmbDataSet.setEnabled( false );
btnNewData.setEnabled( false );
btnFilters.setEnabled( hasDataSet( ) );
btnParameters.setEnabled( hasDataSet( ) );
}
else if ( e.getSource( ).equals( btnUseDataSet ) )
{
// Skip when selection is false
if ( !btnUseDataSet.getSelection( ) )
{
return;
}
if ( cmbDataSet.getText( ).length( ) == 0 )
{
cmbDataSet.setItems( getDataServiceProvider( ).getAllDataSets( ) );
cmbDataSet.select( 0 );
}
if ( cmbDataSet.getText( ).length( ) != 0 )
{
try
{
switchDataSet( cmbDataSet.getText( ) );
}
catch ( ChartException e1 )
{
ChartWizard.displayException( e1 );
}
}
cmbDataSet.setEnabled( true );
btnNewData.setEnabled( true );
btnFilters.setEnabled( hasDataSet( ) );
btnParameters.setEnabled( hasDataSet( ) );
}
else if ( e.getSource( ).equals( cmbDataSet ) )
{
try
{
ColorPalette.getInstance( ).restore( );
switchDataSet( cmbDataSet.getText( ) );
}
catch ( ChartException e1 )
{
ChartWizard.displayException( e1 );
}
}
else if ( e.getSource( ).equals( btnNewData ) )
{
String[] sAllDS = getDataServiceProvider( ).getAllDataSets( );
String sCurrentDS = ""; //$NON-NLS-1$
if ( sAllDS.length > 0 )
{
sCurrentDS = getDataServiceProvider( ).getBoundDataSet( );
}
getDataServiceProvider( ).invoke( IDataServiceProvider.COMMAND_NEW_DATASET );
sAllDS = ( (ChartWizardContext) context ).getDataServiceProvider( )
.getAllDataSets( );
// Update UI with DS list
cmbDataSet.setItems( sAllDS );
if ( sCurrentDS.length( ) > 0 )
{
cmbDataSet.setText( sCurrentDS );
}
else if ( sAllDS.length > 0 )
{
// If at least one dataset is defined in the report design...AND
// if a dataset had not already been bound to the chart...
// bind the first dataset in the list to the chart
cmbDataSet.setText( sAllDS[0] );
try
{
switchDataSet( sAllDS[0] );
}
catch ( ChartException e1 )
{
ChartWizard.displayException( e1 );
}
}
}
else if ( e.getSource( ).equals( btnFilters ) )
{
if ( getDataServiceProvider( ).invoke( IDataServiceProvider.COMMAND_EDIT_FILTER ) == Window.OK )
{
refreshTablePreview( );
doLivePreview( );
}
}
else if ( e.getSource( ).equals( btnParameters ) )
{
if ( getDataServiceProvider( ).invoke( IDataServiceProvider.COMMAND_EDIT_PARAMETER ) == Window.OK )
{
refreshTablePreview( );
doLivePreview( );
}
}
else if ( e.getSource( ) instanceof MenuItem )
{
MenuItem item = (MenuItem) e.getSource( );
IAction action = (IAction) item.getData( );
action.setChecked( !action.isChecked( ) );
action.run( );
}
}
private void refreshTablePreview( )
{
tablePreview.clearContents( );
if ( cmbDataSet.getText( ) != null )
{
switchDataTable( cmbDataSet.getText( ) );
}
tablePreview.layout( );
}
protected IDataServiceProvider getDataServiceProvider( )
{
return ( (ChartWizardContext) getContext( ) ).getDataServiceProvider( );
}
public void widgetDefaultSelected( SelectionEvent e )
{
}
private boolean hasDataSet( )
{
return getDataServiceProvider( ).getReportDataSet( ) != null
|| getDataServiceProvider( ).getBoundDataSet( ) != null;
}
public void widgetDisposed( DisposeEvent e )
{
super.dispose( );
// No need to dispose other widgets
cmpTask = null;
previewPainter.dispose( );
previewPainter = null;
dynamicArea.dispose( );
dynamicArea = null;
// oldSample = null;
// Restore color registry
ColorPalette.getInstance( ).restore( );
// Remove all registered data definition text
DataDefinitionTextManager.getInstance( ).removeAll( );
}
private ISelectDataCustomizeUI getCustomizeUI( )
{
return dynamicArea;
}
class CategoryXAxisAction extends Action
{
CategoryXAxisAction( )
{
super( getBaseSeriesTitle( getChartModel( ) ) );
}
public void run( )
{
Query query = ( (Query) ( (SeriesDefinition) ChartUIUtil.getBaseSeriesDefinitions( getChartModel( ) )
.get( 0 ) ).getDesignTimeSeries( )
.getDataDefinition( )
.get( 0 ) );
manageColorAndQuery( query );
refreshBottomArea( );
// Refresh all data definitino text
DataDefinitionTextManager.getInstance( ).refreshAll( );
}
}
class GroupYSeriesAction extends Action
{
Query query;
GroupYSeriesAction( Query query )
{
super( getGroupSeriesTitle( getChartModel( ) ) );
this.query = query;
}
public void run( )
{
// Use the first group, and copy to the all groups
ChartAdapter.ignoreNotifications( true );
ChartUIUtil.setAllGroupingQueryExceptFirst( getChartModel( ),
ChartUIUtil.getExpressionString( tablePreview.getCurrentColumnHeading( ) ) );
ChartAdapter.ignoreNotifications( false );
manageColorAndQuery( query );
refreshRightArea( );
// Refresh all data definitino text
DataDefinitionTextManager.getInstance( ).refreshAll( );
}
}
class ValueYSeriesAction extends Action
{
Query query;
ValueYSeriesAction( Query query )
{
super( getOrthogonalSeriesTitle( getChartModel( ) ) );
this.query = query;
}
public void run( )
{
manageColorAndQuery( query );
refreshLeftArea( );
// Refresh all data definitino text
DataDefinitionTextManager.getInstance( ).refreshAll( );
}
}
class HeaderShowAction extends Action
{
HeaderShowAction( )
{
super( tablePreview.getCurrentColumnHeading( ) );
setEnabled( false );
}
}
public void handleEvent( Event event )
{
if ( event.type == CustomPreviewTable.MOUSE_RIGHT_CLICK_TYPE
&& ( getDataServiceProvider( ).getBoundDataSet( ) != null || getDataServiceProvider( ).getReportDataSet( ) != null ) )
{
MenuManager menuManager = new MenuManager( );
menuManager.setRemoveAllWhenShown( true );
menuManager.addMenuListener( new IMenuListener( ) {
public void menuAboutToShow( IMenuManager manager )
{
addMenu( manager, new HeaderShowAction( ) );
addMenu( manager, getBaseSeriesMenu( getChartModel( ) ) );
addMenu( manager,
getOrthogonalSeriesMenu( getChartModel( ) ) );
addMenu( manager, getGroupSeriesMenu( getChartModel( ) ) );
// manager.add( actionInsertAggregation );
}
private void addMenu( IMenuManager manager, Object item )
{
if ( item instanceof IAction )
{
manager.add( (IAction) item );
}
else if ( item instanceof IContributionItem )
{
manager.add( (IContributionItem) item );
}
}
} );
Menu menu = menuManager.createContextMenu( tablePreview );
menu.setVisible( true );
}
}
private Object getBaseSeriesMenu( Chart chart )
{
EList sds = ChartUIUtil.getBaseSeriesDefinitions( chart );
if ( sds.size( ) == 1 )
{
return new CategoryXAxisAction( );
}
return null;
}
private Object getOrthogonalSeriesMenu( Chart chart )
{
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 ) );
action.setText( ChartUIUtil.getStockTitle( j )
+ Messages.getString( "TaskSelectData.Label.Component" ) ); //$NON-NLS-1$
secondManager.add( action );
}
}
else
{
IAction action = new ValueYSeriesAction( (Query) dataDefns.get( 0 ) );
if ( axisNum == 1 && sds.size( ) == 1 )
{
// Simplify cascade menu
return action;
}
action.setText( getSecondMenuText( axisIndex, i, series ) );
topManager.add( action );
}
}
}
return topManager;
}
private Object getGroupSeriesMenu( Chart chart )
{
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( ) );
// ONLY USE FIRST GROUPING SERIES FOR CHART ENGINE SUPPORT
// if ( axisNum == 1 && sds.size( ) == 1 )
{
// Simply cascade menu
return action;
}
// action.setText( getSecondMenuText( axisIndex,
// sd.getDesignTimeSeries( ) ) );
// topManager.add( action );
}
}
return topManager;
}
private String getSecondMenuText( int axisIndex, int seriesIndex,
Series series )
{
String text = axisIndex == 0
? "" : Messages.getString( "TaskSelectData.Label.Overlay" ); //$NON-NLS-1$ //$NON-NLS-2$
text += Messages.getString( "TaskSelectData.Label.Series" ) //$NON-NLS-1$
+ ( seriesIndex + 1 ) + " (" + series.getDisplayName( ) + ")"; //$NON-NLS-1$ //$NON-NLS-2$
return text;
}
private String getBaseSeriesTitle( Chart chart )
{
if ( chart instanceof ChartWithAxes )
{
return Messages.getString( "TaskSelectData.Label.UseAsCategoryXAxis" ); //$NON-NLS-1$
}
return Messages.getString( "TaskSelectData.Label.UseAsCategorySeries" ); //$NON-NLS-1$
}
private String getOrthogonalSeriesTitle( Chart chart )
{
if ( chart instanceof ChartWithAxes )
{
return Messages.getString( "TaskSelectData.Label.PlotAsValueYSeries" ); //$NON-NLS-1$
}
else if ( chart instanceof DialChart )
{
return Messages.getString( "TaskSelectData.Label.PlotAsGaugeValue" ); //$NON-NLS-1$
}
return Messages.getString( "TaskSelectData.Label.PlotAsValueSeries" ); //$NON-NLS-1$
}
private String getGroupSeriesTitle( Chart chart )
{
if ( chart instanceof ChartWithAxes )
{
return Messages.getString( "TaskSelectData.Label.UseToGroupYSeries" ); //$NON-NLS-1$
}
return Messages.getString( "TaskSelectData.Label.UseToGroupValueSeries" ); //$NON-NLS-1$
}
public void changeTask( Notification notification )
{
if ( previewPainter != null )
{
// Query and series change need to update Live Preview
if ( notification.getNotifier( ) instanceof Query
|| notification.getNotifier( ) instanceof Axis
|| notification.getNotifier( ) instanceof SeriesDefinition )
{
doLivePreview( );
}
else if ( ChartPreviewPainter.isLivePreviewActive( ) )
{
ChartAdapter.ignoreNotifications( true );
ChartUIUtil.syncRuntimeSeries( getChartModel( ) );
ChartAdapter.ignoreNotifications( false );
previewPainter.renderModel( getChartModel( ) );
}
else
{
previewPainter.renderModel( getChartModel( ) );
}
}
}
private void manageColorAndQuery( Query query )
{
// If it's last element, remove color binding
if ( DataDefinitionTextManager.getInstance( )
.getNumberOfSameDataDefinition( query.getDefinition( ) ) == 1 )
{
ColorPalette.getInstance( ).retrieveColor( query.getDefinition( ) );
}
query.setDefinition( ChartUIUtil.getExpressionString( tablePreview.getCurrentColumnHeading( ) ) );
ColorPalette.getInstance( ).putColor( query.getDefinition( ) );
// Reset table column color
refreshTableColor( );
}
private void doLivePreview( )
{
if ( getDataServiceProvider( ).isLivePreviewEnabled( )
&& ChartUIUtil.checkDataBinding( getChartModel( ) )
&& hasDataSet( ) )
{
// Enable live preview
ChartPreviewPainter.activateLivePreview( true );
// Make sure not affect model changed
ChartAdapter.ignoreNotifications( true );
try
{
ChartUIUtil.doLivePreview( getChartModel( ),
getDataServiceProvider( ) );
}
// Includes RuntimeException
catch ( Exception e )
{
// Enable sample data instead
ChartPreviewPainter.activateLivePreview( false );
}
ChartAdapter.ignoreNotifications( false );
}
else
{
// Disable live preview
ChartPreviewPainter.activateLivePreview( false );
}
previewPainter.renderModel( getChartModel( ) );
}
}
|
package org.eclipse.birt.chart.ui.swt.wizard;
import java.util.ArrayList;
import java.util.Collection;
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.attribute.AxisType;
import org.eclipse.birt.chart.model.attribute.DataType;
import org.eclipse.birt.chart.model.component.Axis;
import org.eclipse.birt.chart.model.component.MarkerLine;
import org.eclipse.birt.chart.model.component.MarkerRange;
import org.eclipse.birt.chart.model.component.Series;
import org.eclipse.birt.chart.model.data.BaseSampleData;
import org.eclipse.birt.chart.model.data.OrthogonalSampleData;
import org.eclipse.birt.chart.model.data.Query;
import org.eclipse.birt.chart.model.data.SeriesDefinition;
import org.eclipse.birt.chart.model.data.SeriesGrouping;
import org.eclipse.birt.chart.ui.extension.i18n.Messages;
import org.eclipse.birt.chart.ui.swt.ChartPreviewPainter;
import org.eclipse.birt.chart.ui.swt.ColorPalette;
import org.eclipse.birt.chart.ui.swt.DataDefinitionTextManager;
import org.eclipse.birt.chart.ui.swt.interfaces.IChartDataSheet;
import org.eclipse.birt.chart.ui.swt.interfaces.IChartPreviewPainter;
import org.eclipse.birt.chart.ui.swt.interfaces.IDataServiceProvider;
import org.eclipse.birt.chart.ui.swt.interfaces.ISelectDataCustomizeUI;
import org.eclipse.birt.chart.ui.swt.interfaces.ISeriesUIProvider;
import org.eclipse.birt.chart.ui.swt.interfaces.ITaskChangeListener;
import org.eclipse.birt.chart.ui.swt.interfaces.ITaskPreviewable;
import org.eclipse.birt.chart.ui.swt.type.GanttChart;
import org.eclipse.birt.chart.ui.swt.wizard.data.BaseDataDefinitionComponent;
import org.eclipse.birt.chart.ui.swt.wizard.data.SelectDataDynamicArea;
import org.eclipse.birt.chart.ui.util.ChartHelpContextIds;
import org.eclipse.birt.chart.ui.util.ChartUIConstants;
import org.eclipse.birt.chart.ui.util.ChartUIUtil;
import org.eclipse.birt.chart.ui.util.UIHelper;
import org.eclipse.birt.chart.util.ChartUtil;
import org.eclipse.birt.core.ui.frameworks.taskwizard.SimpleTask;
import org.eclipse.birt.core.ui.frameworks.taskwizard.WizardBase;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.custom.ScrolledComposite;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Canvas;
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;
/**
* This task is used for data binding. The UI is mainly managed by
* SelectDataDynamicArea. For the sake of customization, use IChartDataSheet
* implementation to create specific UI sections.
*
*/
public class TaskSelectData extends SimpleTask implements
ITaskChangeListener,
ITaskPreviewable,
Listener
{
private final static int CENTER_WIDTH_HINT = 400;
protected IChartPreviewPainter previewPainter = null;
private Canvas previewCanvas = null;
private ISelectDataCustomizeUI dynamicArea;
private SashForm foSashForm;
private Point fLeftSize;
private Point fRightSize;
private final int DEFAULT_HEIGHT = 580;
private Composite fHeaderArea;
private ScrolledComposite fDataArea;
public TaskSelectData( )
{
super( Messages.getString( "TaskSelectData.TaskExp" ) ); //$NON-NLS-1$
setDescription( Messages.getString( "TaskSelectData.Task.Description" ) ); //$NON-NLS-1$
}
public void createControl( Composite parent )
{
getDataSheet( ).setChartModel( getChartModel( ) );
getDataSheet( ).addListener( this );
if ( topControl == null || topControl.isDisposed( ) )
{
topControl = new Composite( parent, SWT.NONE );
GridLayout gridLayout = new GridLayout( 3, false );
gridLayout.marginWidth = 0;
gridLayout.marginHeight = 0;
topControl.setLayout( gridLayout );
topControl.setLayoutData( new GridData( GridData.GRAB_HORIZONTAL
| GridData.GRAB_VERTICAL ) );
dynamicArea = createDataComponentsUI( );
getCustomizeUI( ).init( );
foSashForm = new SashForm( topControl, SWT.VERTICAL );
{
GridLayout layout = new GridLayout( );
foSashForm.setLayout( layout );
GridData gridData = new GridData( GridData.FILL_BOTH );
// gridData.heightHint = DEFAULT_HEIGHT;
foSashForm.setLayoutData( gridData );
}
foSashForm.addListener( SWT.Resize, this );
placeComponents( );
previewPainter = createPreviewPainter( );
// init( );
}
else
{
customizeUI( );
}
resize( );
List<String> errorMsgs = null;
if ( getChartModel( ) instanceof ChartWithAxes )
{
errorMsgs = checkDataTypeForChartWithAxes( );
}
doPreview( errorMsgs );
// Refresh all data definition text
DataDefinitionTextManager.getInstance( ).refreshAll( );
ChartUIUtil.checkGroupType( (ChartWizardContext) getContext( ),
getChartModel( ) );
ChartUIUtil.checkAggregateType( (ChartWizardContext) getContext( ) );
bindHelp( );
}
protected void bindHelp( )
{
ChartUIUtil.bindHelp( getControl( ),
ChartHelpContextIds.TASK_SELECT_DATA );
}
protected void customizeUI( )
{
getCustomizeUI( ).init( );
refreshLeftArea( );
refreshRightArea( );
refreshBottomArea( );
resize( );
getCustomizeUI( ).layoutAll( );
}
protected ISelectDataCustomizeUI createDataComponentsUI( )
{
return new SelectDataDynamicArea( this );
}
private void resize( )
{
Point headerSize = computeHeaderAreaSize( );
int weight[] = foSashForm.getWeights( );
if ( headerSize.y > DEFAULT_HEIGHT / 2 )
{
weight[0] = headerSize.y;
weight[1] = DEFAULT_HEIGHT / 2;
( (GridData) foSashForm.getLayoutData( ) ).heightHint = weight[0]
+ weight[1];
}
else
{
weight[0] = 200;
weight[1] = 200;
( (GridData) foSashForm.getLayoutData( ) ).heightHint = DEFAULT_HEIGHT;
}
}
private void refreshLeftArea( )
{
getCustomizeUI( ).refreshLeftBindingArea( );
getCustomizeUI( ).selectLeftBindingArea( true, null );
}
private void refreshRightArea( )
{
getCustomizeUI( ).refreshRightBindingArea( );
getCustomizeUI( ).selectRightBindingArea( true, null );
}
private void refreshBottomArea( )
{
getCustomizeUI( ).refreshBottomBindingArea( );
getCustomizeUI( ).selectBottomBindingArea( true, null );
}
private void placeComponents( )
{
ChartAdapter.beginIgnoreNotifications( );
try
{
createHeadArea( );// place two rows
createDataArea( );
}
finally
{
// THIS IS IN A FINALLY BLOCK TO ENSURE THAT NOTIFICATIONS ARE
// ENABLED EVEN IF ERRORS OCCUR DURING UI INITIALIZATION
ChartAdapter.endIgnoreNotifications( );
}
}
private void createDataArea( )
{
fDataArea = new ScrolledComposite( foSashForm, SWT.VERTICAL );
{
GridLayout gl = new GridLayout( );
fDataArea.setLayout( gl );
GridData gd = new GridData( GridData.FILL_VERTICAL );
fDataArea.setLayoutData( gd );
fDataArea.setExpandHorizontal( true );
fDataArea.setExpandVertical( true );
}
Composite dataComposite = new Composite( fDataArea, SWT.NONE );
{
GridLayout gl = new GridLayout( 3, false );
dataComposite.setLayout( gl );
GridData gd = new GridData( GridData.FILL_BOTH );
dataComposite.setLayoutData( gd );
}
fDataArea.setContent( dataComposite );
GridData gd = new GridData( GridData.FILL_HORIZONTAL );
gd.widthHint = fLeftSize.x;
new Label( dataComposite, SWT.NONE ).setLayoutData( gd );
getDataSheet( ).createDataSelector( dataComposite );
gd = new GridData( GridData.FILL_HORIZONTAL );
gd.widthHint = fRightSize.x;
new Label( dataComposite, SWT.NONE ).setLayoutData( gd );
new Label( dataComposite, SWT.NONE );
getDataSheet( ).createDataDragSource( dataComposite );
getDataSheet( ).createActionButtons( dataComposite );
new Label( dataComposite, SWT.NONE );
Point size = dataComposite.computeSize( SWT.DEFAULT, SWT.DEFAULT );
fDataArea.setMinSize( size );
}
private void createHeadArea( )
{
// Create header area.
fHeaderArea = new Composite( foSashForm, SWT.NONE );
{
GridLayout layout = new GridLayout( 3, false );
fHeaderArea.setLayout( layout );
GridData gd = new GridData( GridData.FILL_HORIZONTAL );
fHeaderArea.setLayoutData( gd );
}
{
Composite cmpLeftContainer = ChartUIUtil.createCompositeWrapper( fHeaderArea );
GridData gridData = new GridData( GridData.FILL_HORIZONTAL
| GridData.VERTICAL_ALIGN_CENTER );
gridData.verticalSpan = 2;
cmpLeftContainer.setLayoutData( gridData );
getCustomizeUI( ).createLeftBindingArea( cmpLeftContainer );
fLeftSize = cmpLeftContainer.computeSize( SWT.DEFAULT, SWT.DEFAULT );
}
createPreviewArea( fHeaderArea );
{
Composite cmpRightContainer = ChartUIUtil.createCompositeWrapper( fHeaderArea );
GridData gridData = new GridData( GridData.FILL_HORIZONTAL
| GridData.VERTICAL_ALIGN_CENTER );
gridData.verticalSpan = 2;
cmpRightContainer.setLayoutData( gridData );
getCustomizeUI( ).createRightBindingArea( cmpRightContainer );
fRightSize = cmpRightContainer.computeSize( SWT.DEFAULT,
SWT.DEFAULT );
}
{
Composite cmpBottomContainer = ChartUIUtil.createCompositeWrapper( fHeaderArea );
GridData gridData = new GridData( GridData.FILL_HORIZONTAL
| GridData.VERTICAL_ALIGN_BEGINNING );
cmpBottomContainer.setLayoutData( gridData );
getCustomizeUI( ).createBottomBindingArea( cmpBottomContainer );
}
}
private Point computeHeaderAreaSize( )
{
return fHeaderArea.computeSize( SWT.DEFAULT, SWT.DEFAULT );
}
private Point computeDataAreaSize( )
{
return fDataArea.computeSize( SWT.DEFAULT, SWT.DEFAULT );
}
private void createPreviewArea( Composite parent )
{
Composite cmpPreview = ChartUIUtil.createCompositeWrapper( parent );
{
GridData gridData = new GridData( GridData.FILL_BOTH );
gridData.widthHint = CENTER_WIDTH_HINT;
gridData.heightHint = 200;
cmpPreview.setLayoutData( gridData );
}
Label label = new Label( cmpPreview, SWT.NONE );
{
label.setFont( JFaceResources.getBannerFont( ) );
label.setText( Messages.getString( "TaskSelectData.Label.ChartPreview" ) ); //$NON-NLS-1$
}
previewCanvas = new Canvas( cmpPreview, SWT.BORDER );
{
GridData gd = new GridData( GridData.FILL_BOTH );
previewCanvas.setLayoutData( gd );
previewCanvas.setBackground( Display.getDefault( )
.getSystemColor( SWT.COLOR_WIDGET_BACKGROUND ) );
}
}
public IChartPreviewPainter createPreviewPainter( )
{
ChartPreviewPainter painter = new ChartPreviewPainter( (ChartWizardContext) getContext( ) );
getPreviewCanvas( ).addPaintListener( painter );
getPreviewCanvas( ).addControlListener( painter );
painter.setPreview( getPreviewCanvas( ) );
return painter;
}
protected Chart getChartModel( )
{
if ( getContext( ) == null )
{
return null;
}
return ( (ChartWizardContext) getContext( ) ).getModel( );
}
protected IDataServiceProvider getDataServiceProvider( )
{
return ( (ChartWizardContext) getContext( ) ).getDataServiceProvider( );
}
public void dispose( )
{
super.dispose( );
// No need to dispose other widgets
if ( previewPainter != null )
{
previewPainter.dispose( );
}
previewPainter = null;
if ( dynamicArea != null )
{
dynamicArea.dispose( );
}
dynamicArea = null;
// Restore color registry
ColorPalette.getInstance( ).restore( );
// Remove all registered data definition text
DataDefinitionTextManager.getInstance( ).removeAll( );
}
private ISelectDataCustomizeUI getCustomizeUI( )
{
return dynamicArea;
}
public void handleEvent( Event event )
{
if ( event.data == getDataSheet( )
|| event.data instanceof BaseDataDefinitionComponent )
{
if ( event.type == IChartDataSheet.EVENT_PREVIEW )
{
doPreview( );
updateApplyButton( );
}
else if ( event.type == IChartDataSheet.EVENT_QUERY )
{
getCustomizeUI( ).refreshBottomBindingArea( );
getCustomizeUI( ).refreshLeftBindingArea( );
getCustomizeUI( ).refreshRightBindingArea( );
// Above statements might create Text or Combo widgets for
// expression, so here must invoke refreshAll to clear old
// widgets info.
DataDefinitionTextManager.getInstance( ).refreshAll( );
}
}
if ( event.type == IChartDataSheet.EVENT_QUERY )
{
if ( ChartUIConstants.QUERY_CATEGORY.equals( event.data ) )
{
getCustomizeUI( ).refreshBottomBindingArea( );
}
else if ( ChartUIConstants.QUERY_OPTIONAL.equals( event.data ) )
{
getCustomizeUI( ).refreshRightBindingArea( );
}
else if ( ChartUIConstants.QUERY_VALUE.equals( event.data ) )
{
getCustomizeUI( ).refreshLeftBindingArea( );
}
DataDefinitionTextManager.getInstance( ).refreshAll( );
}
else if ( event.type == SWT.Resize )
{
autoSash( );
}
}
private void autoSash( )
{
int headerHeight = computeHeaderAreaSize( ).y;
int dataHeight = computeDataAreaSize( ).y;
int height = foSashForm.getClientArea( ).height;
int weight[] = foSashForm.getWeights( );
if ( height > headerHeight && height > dataHeight )
{
if ( height > headerHeight + dataHeight )
{
weight[0] = height - dataHeight;
weight[1] = dataHeight + 1;
}
else
{
weight[0] = headerHeight;
weight[1] = height - headerHeight;
}
}
foSashForm.setWeights( weight );
}
public void changeTask( Notification notification )
{
if ( previewPainter != null )
{
if ( notification == null )
{
if ( getChartModel( ) instanceof ChartWithAxes )
{
checkDataTypeForChartWithAxes( );
}
return;
}
List<String> errorMsgs = new ArrayList<String>( 2 );
// Only data definition query (not group query) will be validated
if ( ( notification.getNotifier( ) instanceof Query && ( (Query) notification.getNotifier( ) ).eContainer( ) instanceof Series ) )
{
errorMsgs.addAll( checkDataType( (Query) notification.getNotifier( ),
(Series) ( (Query) notification.getNotifier( ) ).eContainer( ) ) );
// add default category grouping for data set binding
if ( !( ( (ChartWizardContext) getContext( ) ).getChartType( ) instanceof GanttChart )
&& !getDataServiceProvider( ).checkState( IDataServiceProvider.SHARE_QUERY )
&& getDataServiceProvider( ).checkState( IDataServiceProvider.HAS_DATA_SET ) )
{
if ( getChartModel( ) instanceof ChartWithAxes )
{
Axis axisWithCurrentQuery = (Axis) ( (Query) notification.getNotifier( ) ).eContainer( )
.eContainer( )
.eContainer( );
// after adding definition on value series
if ( ChartUIUtil.getAxisXForProcessing( (ChartWithAxes) getChartModel( ) )
.isCategoryAxis( )
&& axisWithCurrentQuery.eContainer( ) instanceof Axis )
{
SeriesDefinition base = ChartUIUtil.getBaseSeriesDefinitions( getChartModel( ) )
.get( 0 );
// has no grouping
if ( !base.getGrouping( ).isEnabled( ) )
{
base.getGrouping( ).setEnabled( true );
}
// if it's date time type, set the 'first'
// aggregation.
if ( axisWithCurrentQuery.getType( ) == AxisType.DATE_TIME_LITERAL )
{
SeriesDefinition valueSdWithCurrQuery = (SeriesDefinition) ( (Query) notification.getNotifier( ) ).eContainer( )
.eContainer( );
valueSdWithCurrQuery.getGrouping( )
.setEnabled( true );
valueSdWithCurrQuery.getGrouping( )
.setAggregateExpression( "First" ); //$NON-NLS-1$
}
}
}
else
{
if ( ( (Query) notification.getNotifier( ) ).eContainer( )
.eContainer( )
.eContainer( ) instanceof SeriesDefinition )
{
SeriesDefinition base = ChartUIUtil.getBaseSeriesDefinitions( getChartModel( ) )
.get( 0 );
// has no grouping
if ( !base.getGrouping( ).isEnabled( ) )
{
base.getGrouping( ).setEnabled( true );
}
}
}
}
}
if ( notification.getNotifier( ) instanceof SeriesDefinition
&& getChartModel( ) instanceof ChartWithAxes )
{
errorMsgs.addAll( checkDataTypeForChartWithAxes( ) );
}
// In old logic, the following statements are used to disable
// aggregate button if category grouping is canceled?
// But new logic is that aggregate button is still enabled, so
// remove code below.(Bugzilla#216082, 2008/1/23)
// Update Grouping aggregation button
// if ( notification.getNewValue( ) instanceof SeriesGrouping )
// getCustomizeUI( ).refreshLeftBindingArea( );
// Query and series change need to update Live Preview
if ( notification.getNotifier( ) instanceof Query
|| notification.getNotifier( ) instanceof Axis
|| notification.getNotifier( ) instanceof SeriesDefinition
|| notification.getNotifier( ) instanceof SeriesGrouping )
{
doPreview( errorMsgs );
}
else if ( ChartPreviewPainter.isLivePreviewActive( ) )
{
ChartAdapter.beginIgnoreNotifications( );
ChartUIUtil.syncRuntimeSeries( getChartModel( ) );
ChartAdapter.endIgnoreNotifications( );
doPreview( errorMsgs );
}
else
{
doPreview( errorMsgs );
}
}
}
private List<String> checkDataType( Query query, Series series )
{
List<String> errorMsgs = new ArrayList<String>( 2 );
String expression = query.getDefinition( );
Axis axis = null;
for ( EObject o = query; o != null; )
{
o = o.eContainer( );
if ( o instanceof Axis )
{
axis = (Axis) o;
break;
}
}
Collection<ISeriesUIProvider> cRegisteredEntries = ChartUIExtensionsImpl.instance( )
.getSeriesUIComponents( getContext( ).getClass( )
.getSimpleName( ) );
Iterator<ISeriesUIProvider> iterEntries = cRegisteredEntries.iterator( );
String sSeries = null;
while ( iterEntries.hasNext( ) )
{
ISeriesUIProvider provider = iterEntries.next( );
sSeries = provider.getSeriesClass( );
if ( sSeries.equals( series.getClass( ).getName( ) ) )
{
if ( getChartModel( ) instanceof ChartWithAxes )
{
DataType dataType = getDataServiceProvider( ).getDataType( expression );
SeriesDefinition baseSD = (SeriesDefinition) ( ChartUIUtil.getBaseSeriesDefinitions( getChartModel( ) ).get( 0 ) );
SeriesDefinition orthSD = null;
orthSD = (SeriesDefinition) series.eContainer( );
boolean hasException = false;
String aggFunc = null;
try
{
aggFunc = ChartUtil.getAggregateFuncExpr( orthSD,
baseSD );
}
catch ( ChartException e )
{
hasException = true;
WizardBase.showException( e.getLocalizedMessage( ) );
errorMsgs.add( e.getLocalizedMessage( ) );
}
if ( !hasException )
{
WizardBase.removeException( );
}
if ( baseSD != orthSD && baseSD.eContainer( ) != axis
// not
// without
// axis
// chart.
&& ChartUtil.isMagicAggregate( aggFunc ) )
{
// Only check aggregation is count in Y axis
dataType = DataType.NUMERIC_LITERAL;
}
if ( isValidatedAxis( dataType, axis.getType( ) ) )
{
break;
}
AxisType[] axisTypes = provider.getCompatibleAxisType( series );
int[] validationIndex = provider.validationIndex( series );
boolean needValidate = false;
for ( int i = 0; i < validationIndex.length; i++ )
{
if ( query == series.getDataDefinition( ).get( i ) )
{
needValidate = true;
break;
}
}
SeriesDefinition sd = (SeriesDefinition) series.eContainer( );
if ( ( (Axis) sd.eContainer( ) ).getSeriesDefinitions( )
.indexOf( sd ) > 0 )
{
needValidate = false;
}
if ( needValidate )
{
for ( int i = 0; i < axisTypes.length; i++ )
{
if ( isValidatedAxis( dataType, axisTypes[i] ) )
{
axisNotification( axis, axisTypes[i] );
axis.setType( axisTypes[i] );
break;
}
}
}
}
boolean bException = false;
try
{
provider.validateSeriesBindingType( series,
getDataServiceProvider( ) );
}
catch ( ChartException ce )
{
bException = true;
String errMsg = Messages.getFormattedString( "TaskSelectData.Warning.TypeCheck",//$NON-NLS-1$
new String[]{
ce.getLocalizedMessage( ),
series.getDisplayName( )
} );
WizardBase.showException( errMsg );
errorMsgs.add( errMsg );
}
if ( !bException )
{
WizardBase.removeException( );
}
break;
}
}
return errorMsgs;
}
private boolean isValidatedAxis( DataType dataType, AxisType axisType )
{
if ( dataType == null )
{
return true;
}
else if ( ( dataType == DataType.DATE_TIME_LITERAL )
&& ( axisType == AxisType.DATE_TIME_LITERAL ) )
{
return true;
}
else if ( ( dataType == DataType.NUMERIC_LITERAL )
&& ( ( axisType == AxisType.LINEAR_LITERAL ) || ( axisType == AxisType.LOGARITHMIC_LITERAL ) ) )
{
return true;
}
else if ( ( dataType == DataType.TEXT_LITERAL )
&& ( axisType == AxisType.TEXT_LITERAL ) )
{
return true;
}
return false;
}
private void axisNotification( Axis axis, AxisType type )
{
ChartAdapter.beginIgnoreNotifications( );
{
convertSampleData( axis, type );
axis.setFormatSpecifier( null );
EList markerLines = axis.getMarkerLines( );
for ( int i = 0; i < markerLines.size( ); i++ )
{
( (MarkerLine) markerLines.get( i ) ).setFormatSpecifier( null );
}
EList markerRanges = axis.getMarkerRanges( );
for ( int i = 0; i < markerRanges.size( ); i++ )
{
( (MarkerRange) markerRanges.get( i ) ).setFormatSpecifier( null );
}
}
ChartAdapter.endIgnoreNotifications( );
}
private void convertSampleData( Axis axis, AxisType axisType )
{
if ( ( axis.getAssociatedAxes( ) != null )
&& ( axis.getAssociatedAxes( ).size( ) != 0 ) )
{
BaseSampleData bsd = (BaseSampleData) getChartModel( ).getSampleData( )
.getBaseSampleData( )
.get( 0 );
bsd.setDataSetRepresentation( ChartUIUtil.getConvertedSampleDataRepresentation( axisType,
bsd.getDataSetRepresentation( ),
0 ) );
}
else
{
int iStartIndex = getFirstSeriesDefinitionIndexForAxis( axis );
int iEndIndex = iStartIndex + axis.getSeriesDefinitions( ).size( );
int iOSDSize = getChartModel( ).getSampleData( )
.getOrthogonalSampleData( )
.size( );
for ( int i = 0; i < iOSDSize; i++ )
{
OrthogonalSampleData osd = (OrthogonalSampleData) getChartModel( ).getSampleData( )
.getOrthogonalSampleData( )
.get( i );
if ( osd.getSeriesDefinitionIndex( ) >= iStartIndex
&& osd.getSeriesDefinitionIndex( ) < iEndIndex )
{
osd.setDataSetRepresentation( ChartUIUtil.getConvertedSampleDataRepresentation( axisType,
osd.getDataSetRepresentation( ),
i ) );
}
}
}
}
private int getFirstSeriesDefinitionIndexForAxis( Axis axis )
{
List axisList = ( (Axis) ( (ChartWithAxes) getChartModel( ) ).getAxes( )
.get( 0 ) ).getAssociatedAxes( );
int index = 0;
for ( int i = 0; i < axisList.size( ); i++ )
{
if ( axis.equals( axisList.get( i ) ) )
{
index = i;
break;
}
}
int iTmp = 0;
for ( int i = 0; i < index; i++ )
{
iTmp += ChartUIUtil.getAxisYForProcessing( (ChartWithAxes) getChartModel( ),
i )
.getSeriesDefinitions( )
.size( );
}
return iTmp;
}
private void updateApplyButton( )
{
if ( container != null && container instanceof ChartWizard )
{
( (ChartWizard) container ).updateApplyButton( );
}
}
private List<String> checkDataTypeForChartWithAxes( )
{
List<String> errorMsgs = new ArrayList<String>( 2 );
List osds = ChartUIUtil.getAllOrthogonalSeriesDefinitions( getChartModel( ) );
for ( int i = 0; i < osds.size( ); i++ )
{
SeriesDefinition sd = (SeriesDefinition) osds.get( i );
Series series = sd.getDesignTimeSeries( );
errorMsgs.addAll( checkDataType( ChartUIUtil.getDataQuery( sd, 0 ),
series ) );
}
return errorMsgs;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.core.ui.frameworks.taskwizard.SimpleTask#getImage()
*/
public Image getImage( )
{
return UIHelper.getImage( ChartUIConstants.IMAGE_TASK_DATA );
}
private IChartDataSheet getDataSheet( )
{
return ( (ChartWizardContext) getContext( ) ).getDataSheet( );
}
/**
* Do chart preview.
*
* @param errorMsgs
*/
protected void doPreview( List<String> errorMsgs )
{
List<String> msgs = ChartUIUtil.prepareLivePreview( getChartModel( ),
getDataServiceProvider( ) );
if ( errorMsgs != null )
{
msgs.addAll( 0, errorMsgs );
}
if ( msgs.size( ) > 0 )
{
WizardBase.showException( msgs.get( 0 ) );
}
else
{
WizardBase.removeException( );
}
previewPainter.renderModel( getChartModel( ) );
}
public void doPreview( )
{
ChartUIUtil.prepareLivePreview( getChartModel( ),
getDataServiceProvider( ) );
previewPainter.renderModel( getChartModel( ) );
}
public Canvas getPreviewCanvas( )
{
return previewCanvas;
}
public boolean isPreviewable( )
{
return true;
}
}
|
package org.realityforge.replicant.client.transport;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.function.Consumer;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.realityforge.replicant.client.Change;
import org.realityforge.replicant.client.ChangeMapper;
import org.realityforge.replicant.client.ChangeSet;
import org.realityforge.replicant.client.ChannelAction;
import org.realityforge.replicant.client.ChannelDescriptor;
import org.realityforge.replicant.client.ChannelSubscriptionEntry;
import org.realityforge.replicant.client.EntityChangeBroker;
import org.realityforge.replicant.client.EntityRepository;
import org.realityforge.replicant.client.EntityRepositoryDebugger;
import org.realityforge.replicant.client.EntityRepositoryValidator;
import org.realityforge.replicant.client.EntitySubscriptionEntry;
import org.realityforge.replicant.client.EntitySubscriptionManager;
import org.realityforge.replicant.client.EntitySystem;
import org.realityforge.replicant.client.Linkable;
/**
* Class from which to extend to implement a service that loads data from a change set.
* Data can be loaded by bulk or incrementally and the load can be broken up into several
* steps to avoid locking a thread such as in GWT.
*/
@SuppressWarnings( { "WeakerAccess", "unused" } )
public abstract class AbstractDataLoaderService
implements DataLoaderService
{
protected static final Logger LOG = Logger.getLogger( AbstractDataLoaderService.class.getName() );
private static final int DEFAULT_CHANGES_TO_PROCESS_PER_TICK = 100;
private static final int DEFAULT_LINKS_TO_PROCESS_PER_TICK = 100;
private DataLoadAction _currentAction;
private AreaOfInterestEntry _currentAoiAction;
private int _changesToProcessPerTick = DEFAULT_CHANGES_TO_PROCESS_PER_TICK;
private int _linksToProcessPerTick = DEFAULT_LINKS_TO_PROCESS_PER_TICK;
private boolean _incrementalDataLoadInProgress;
private final DataLoaderListenerSupport _listenerSupport = new DataLoaderListenerSupport();
/**
* Action invoked after current action completes to reset session state.
*/
private Runnable _resetAction;
@Nonnull
private State _state = State.DISCONNECTED;
private ClientSession _session;
@Nonnull
@Override
public String getKey()
{
return getSessionContext().getKey();
}
@Nonnull
@Override
public State getState()
{
return _state;
}
@SuppressWarnings( "ConstantConditions" )
protected void setState( @Nonnull final State state )
{
assert null != state;
_state = state;
}
@Nonnull
protected DataLoaderListener getListener()
{
return _listenerSupport;
}
@Override
public boolean addDataLoaderListener( @Nonnull final DataLoaderListener listener )
{
return _listenerSupport.addListener( listener );
}
@Override
public boolean removeDataLoaderListener( @Nonnull final DataLoaderListener listener )
{
return _listenerSupport.removeListener( listener );
}
@Nonnull
protected abstract SessionContext getSessionContext();
@Nonnull
protected abstract CacheService getCacheService();
@Nonnull
protected EntityChangeBroker getChangeBroker()
{
return getEntitySystem().getChangeBroker();
}
@Nonnull
protected abstract ChangeMapper getChangeMapper();
@Nonnull
protected EntitySubscriptionManager getSubscriptionManager()
{
return getEntitySystem().getSubscriptionManager();
}
@Nonnull
protected EntityRepository getRepository()
{
return getEntitySystem().getRepository();
}
protected abstract EntitySystem getEntitySystem();
protected boolean shouldPurgeOnSessionChange()
{
return true;
}
protected void setSession( @Nullable final ClientSession session, @Nullable final Runnable postAction )
{
final Runnable runnable = () -> doSetSession( session, postAction );
if ( null == _currentAction )
{
runnable.run();
}
else
{
_resetAction = runnable;
}
}
protected void doSetSession( @Nullable final ClientSession session, @Nullable final Runnable postAction )
{
if ( session != _session )
{
_session = session;
// This should probably be moved elsewhere ... but where?
getSessionContext().setSession( session );
if ( shouldPurgeOnSessionChange() )
{
final boolean enabled = getChangeBroker().isEnabled();
if ( enabled )
{
getChangeBroker().disable( getChangeBrokerKey() );
}
//TODO: else schedule action so that it runs in loop
// until it can disable broker. This will involve replacing _resetAction
// with something more like existing action setup.
purgeSubscriptions();
if ( enabled )
{
getChangeBroker().enable( getChangeBrokerKey() );
}
}
}
if ( null != postAction )
{
postAction.run();
}
}
@Nonnull
protected String getChangeBrokerKey()
{
return getGraphType().getSimpleName();
}
/**
* {@inheritDoc}
*/
@Nullable
@Override
public ClientSession getSession()
{
return _session;
}
/**
* {@inheritDoc}
*/
@Nonnull
public abstract ClientSession ensureSession();
/**
* Return the id of the session associated with the service.
*
* @return the id of the session associated with the service.
* @throws RuntimeException if the service is not currently associated with the session.
*/
protected String getSessionID()
{
return ensureSession().getSessionID();
}
protected void purgeSubscriptions()
{
/*
* Ensure that we only purge subscriptions that are managed by this data loader.
*/
final Class graphClass = getGraphType();
final EntitySubscriptionManager subscriptionManager = getSubscriptionManager();
for ( final Enum graph : sortGraphs( subscriptionManager.getInstanceSubscriptionKeys() ) )
{
if ( graph.getClass().equals( graphClass ) )
{
unsubscribeInstanceGraphs( graph );
}
}
for ( final Enum graph : sortGraphs( subscriptionManager.getTypeSubscriptions() ) )
{
if ( graph.getClass().equals( graphClass ) )
{
final ChannelSubscriptionEntry entry = subscriptionManager.removeSubscription( new ChannelDescriptor( graph ) );
deregisterUnOwnedEntities( entry );
}
}
}
protected void unsubscribeInstanceGraphs( @Nonnull final Enum graph )
{
final EntitySubscriptionManager subscriptionManager = getSubscriptionManager();
for ( final Object id : new ArrayList<>( subscriptionManager.getInstanceSubscriptions( graph ) ) )
{
deregisterUnOwnedEntities( subscriptionManager.removeSubscription( new ChannelDescriptor( graph, id ) ) );
}
}
@SuppressWarnings( "unchecked" )
@Nonnull
private ArrayList<Enum> sortGraphs( @Nonnull final Set<Enum> enums )
{
final ArrayList<Enum> list = new ArrayList<>( enums );
Collections.sort( list );
Collections.reverse( list );
return list;
}
/**
* Schedule data loads using incremental scheduler.
*/
@Override
public void scheduleDataLoad()
{
if ( !_incrementalDataLoadInProgress )
{
_incrementalDataLoadInProgress = true;
doScheduleDataLoad();
}
}
/**
* Perform a single step in incremental data load process.
*
* @return true if more work is to be done.
*/
protected boolean stepDataLoad()
{
try
{
final boolean aoiActionProgressed = progressAreaOfInterestActions();
final boolean dataActionProgressed = progressDataLoad();
_incrementalDataLoadInProgress = aoiActionProgressed || dataActionProgressed;
}
catch ( final Exception e )
{
getListener().onDataLoadFailure( this, e );
_incrementalDataLoadInProgress = false;
return false;
}
return _incrementalDataLoadInProgress;
}
/**
* Actually perform the scheduling of the data load action.
*/
protected abstract void doScheduleDataLoad();
protected void setChangesToProcessPerTick( final int changesToProcessPerTick )
{
_changesToProcessPerTick = changesToProcessPerTick;
}
protected void setLinksToProcessPerTick( final int linksToProcessPerTick )
{
_linksToProcessPerTick = linksToProcessPerTick;
}
@Nonnull
protected abstract ChangeSet parseChangeSet( @Nonnull String rawJsonData );
protected boolean progressAreaOfInterestActions()
{
if ( null == _currentAoiAction )
{
final LinkedList<AreaOfInterestEntry> actions = ensureSession().getPendingAreaOfInterestActions();
if ( 0 == actions.size() )
{
return false;
}
_currentAoiAction = actions.removeFirst();
}
if ( _currentAoiAction.isInProgress() )
{
return false;
}
else
{
_currentAoiAction.markAsInProgress();
final ChannelDescriptor descriptor = _currentAoiAction.getDescriptor();
final Object filterParameter = _currentAoiAction.getFilterParameter();
final String label = getKey() + ":" + descriptor + ( null == filterParameter ? "" : "[" + filterParameter + "]" );
final String cacheKey = _currentAoiAction.getCacheKey();
final AreaOfInterestAction action = _currentAoiAction.getAction();
if ( action == AreaOfInterestAction.ADD )
{
final ChannelSubscriptionEntry entry = getSubscriptionManager().findSubscription( descriptor );
//Already subscribed
if ( null != entry )
{
if ( entry.isExplicitSubscription() )
{
LOG.warning( "Subscription to " + label + " requested but already subscribed." );
completeAoiAction();
return true;
}
else
{
LOG.warning( "Existing subscription to " + label + " converted to a explicit subscription." );
entry.setExplicitSubscription( true );
completeAoiAction();
return true;
}
}
final CacheEntry cacheEntry = getCacheService().lookup( cacheKey );
final String eTag;
final Consumer<Runnable> cacheAction;
if ( null != cacheEntry )
{
eTag = cacheEntry.getETag();
LOG.info( "Found locally cached data for graph " + label + " with etag " + eTag + "." );
cacheAction = a ->
{
LOG.info( "Loading cached data for graph " + label + " with etag " + eTag );
final Runnable completeAoiAction = () ->
{
LOG.info( "Completed load of cached data for graph " + label + " with etag " + eTag + "." );
completeAoiAction();
a.run();
};
//TODO: Figure out how to make the bulkLoad configurable
ensureSession().enqueueOOB( cacheEntry.getContent(), completeAoiAction, true );
};
}
else
{
eTag = null;
cacheAction = null;
}
final Consumer<Runnable> completionAction = a ->
{
LOG.info( "Subscription to " + label + " completed." );
completeAoiAction();
a.run();
};
LOG.info( "Subscription to " + label + " requested." );
requestSubscribeToGraph( descriptor, filterParameter, eTag, cacheAction, completionAction );
return true;
}
else if ( action == AreaOfInterestAction.REMOVE )
{
final ChannelSubscriptionEntry entry = getSubscriptionManager().findSubscription( descriptor );
//Not subscribed
if ( null == entry )
{
LOG.warning( "Unsubscribe from " + label + " requested but not subscribed." );
completeAoiAction();
return true;
}
else if ( !entry.isExplicitSubscription() )
{
LOG.warning( "Unsubscribe from " + label + " requested but not explicitly subscribed." );
completeAoiAction();
return true;
}
LOG.info( "Unsubscribe from " + label + " requested." );
final Consumer<Runnable> completionAction = a ->
{
LOG.info( "Unsubscribe from " + label + " completed." );
entry.setExplicitSubscription( false );
completeAoiAction();
a.run();
};
requestUnsubscribeFromGraph( descriptor, completionAction );
return true;
}
else
{
final ChannelSubscriptionEntry entry = getSubscriptionManager().findSubscription( descriptor );
//Not subscribed
if ( null == entry )
{
LOG.warning( "Subscription update of " + label + " requested but not subscribed." );
completeAoiAction();
return true;
}
final Consumer<Runnable> completionAction = a ->
{
LOG.warning( "Subscription update of " + label + " completed." );
completeAoiAction();
a.run();
};
LOG.warning( "Subscription update of " + label + " requested." );
assert null != filterParameter;
requestUpdateSubscription( descriptor, filterParameter, completionAction );
return true;
}
}
}
private void completeAoiAction()
{
scheduleDataLoad();
_currentAoiAction.markAsComplete();
_currentAoiAction = null;
}
protected abstract void requestSubscribeToGraph( @Nonnull ChannelDescriptor descriptor,
@Nullable Object filterParameter,
@Nullable String eTag,
@Nullable Consumer<Runnable> cacheAction,
@Nonnull Consumer<Runnable> completionAction );
protected abstract void requestUnsubscribeFromGraph( @Nonnull ChannelDescriptor descriptor,
@Nonnull Consumer<Runnable> completionAction );
protected abstract void requestUpdateSubscription( @Nonnull ChannelDescriptor descriptor,
@Nonnull Object filterParameter,
@Nonnull Consumer<Runnable> completionAction );
@Override
public boolean isSubscribed( @Nonnull final ChannelDescriptor descriptor )
{
return null != getSubscriptionManager().findSubscription( descriptor );
}
@Override
public boolean isAreaOfInterestActionPending( @Nonnull final AreaOfInterestAction action,
@Nonnull final ChannelDescriptor descriptor,
@Nullable final Object filter )
{
final ClientSession session = getSession();
return
null != _currentAoiAction && _currentAoiAction.match( action, descriptor, filter ) ||
(
null != session &&
session.getPendingAreaOfInterestActions().stream().
anyMatch( a -> a.match( action, descriptor, filter ) )
);
}
// Method only used in tests
DataLoadAction getCurrentAction()
{
return _currentAction;
}
protected boolean progressDataLoad()
{
final ClientSession session = ensureSession();
// Step: Retrieve any out of band actions
final LinkedList<DataLoadAction> oobActions = session.getOobActions();
if ( null == _currentAction && !oobActions.isEmpty() )
{
_currentAction = oobActions.removeFirst();
return true;
}
//Step: Retrieve the action from the parsed queue if it is the next in the sequence
final LinkedList<DataLoadAction> parsedActions = session.getParsedActions();
if ( null == _currentAction && !parsedActions.isEmpty() )
{
final DataLoadAction action = parsedActions.get( 0 );
final ChangeSet changeSet = action.getChangeSet();
assert null != changeSet;
if ( action.isOob() || session.getLastRxSequence() + 1 == changeSet.getSequence() )
{
_currentAction = parsedActions.remove();
if ( LOG.isLoggable( getLogLevel() ) )
{
LOG.log( getLogLevel(), "Parsed Action Selected: " + _currentAction );
}
return true;
}
}
// Abort if there is no pending data load actions to take
final LinkedList<DataLoadAction> pendingActions = session.getPendingActions();
if ( null == _currentAction && pendingActions.isEmpty() )
{
if ( LOG.isLoggable( getLogLevel() ) )
{
LOG.log( getLogLevel(), "No data to load. Terminating incremental load process." );
}
onTerminatingIncrementalDataLoadProcess();
return false;
}
//Step: Retrieve the action from the un-parsed queue
if ( null == _currentAction )
{
_currentAction = pendingActions.remove();
if ( LOG.isLoggable( getLogLevel() ) )
{
LOG.log( getLogLevel(), "Un-parsed Action Selected: " + _currentAction );
}
return true;
}
//Step: Parse the json
final String rawJsonData = _currentAction.getRawJsonData();
if ( null != rawJsonData )
{
if ( LOG.isLoggable( getLogLevel() ) )
{
LOG.log( getLogLevel(), "Parsing JSON: " + _currentAction );
}
final ChangeSet changeSet = parseChangeSet( _currentAction.getRawJsonData() );
// OOB messages are not in response to requests as such
final String requestID = _currentAction.isOob() ? null : changeSet.getRequestID();
// OOB messages have no etags as from local cache or generated locally
final String eTag = _currentAction.isOob() ? null : changeSet.getETag();
final int sequence = _currentAction.isOob() ? 0 : changeSet.getSequence();
if ( LOG.isLoggable( getLogLevel() ) )
{
LOG.log( getLogLevel(),
"Parsed ChangeSet:" +
" oob=" + _currentAction.isOob() +
" seq=" + sequence +
" requestID=" + requestID +
" eTag=" + eTag +
" changeCount=" + changeSet.getChangeCount()
);
}
final RequestEntry request;
if ( _currentAction.isOob() )
{
request = null;
}
else
{
request = null != requestID ? session.getRequest( requestID ) : null;
if ( null == request && null != requestID )
{
final String message =
"Unable to locate requestID '" + requestID + "' specified for ChangeSet: seq=" + sequence +
" Existing Requests: " + session.getRequests();
if ( LOG.isLoggable( Level.WARNING ) )
{
LOG.warning( message );
}
throw new IllegalStateException( message );
}
else if ( null != request )
{
final String cacheKey = request.getCacheKey();
if ( null != eTag && null != cacheKey )
{
if ( LOG.isLoggable( getLogLevel() ) )
{
LOG.log( getLogLevel(), "Caching ChangeSet: seq=" + sequence + " cacheKey=" + cacheKey );
}
getCacheService().store( cacheKey, eTag, rawJsonData );
}
}
}
_currentAction.setChangeSet( changeSet, request );
parsedActions.add( _currentAction );
Collections.sort( parsedActions );
_currentAction = null;
return true;
}
//Step: Setup the change recording state
if ( _currentAction.needsBrokerPause() )
{
if ( getChangeBroker().isInTransaction() )
{
// Another DataLoaderService has temporarily paused/disabled the broker. So we will
// just spin waiting for it to be released.
return true;
}
_currentAction.markBrokerPaused();
if ( _currentAction.isBulkLoad() )
{
getChangeBroker().disable( getChangeBrokerKey() );
}
else
{
getChangeBroker().pause( getChangeBrokerKey() );
}
return true;
}
if ( _currentAction.needsChannelActionsProcessed() )
{
_currentAction.markChannelActionsProcessed();
final ChangeSet changeSet = _currentAction.getChangeSet();
assert null != changeSet;
final int channelActionCount = changeSet.getChannelActionCount();
for ( int i = 0; i < channelActionCount; i++ )
{
final ChannelAction action = changeSet.getChannelAction( i );
final ChannelDescriptor descriptor = toChannelDescriptor( action );
final Object filter = action.getChannelFilter();
final ChannelAction.Action actionType = action.getAction();
if ( LOG.isLoggable( getLogLevel() ) )
{
final String message = "ChannelAction:: " + actionType.name() + " " + descriptor + " filter=" + filter;
LOG.log( getLogLevel(), message );
}
if ( ChannelAction.Action.ADD == actionType )
{
_currentAction.recordChannelSubscribe( new ChannelChangeStatus( descriptor, filter, 0 ) );
boolean explicitSubscribe = false;
if ( null != _currentAoiAction &&
_currentAoiAction.isInProgress() &&
_currentAoiAction.getDescriptor().equals( descriptor ) )
{
if ( LOG.isLoggable( getLogLevel() ) )
{
LOG.log( getLogLevel(), "Recording explicit subscription for " + descriptor );
}
explicitSubscribe = true;
}
getSubscriptionManager().recordSubscription( descriptor, filter, explicitSubscribe );
}
else if ( ChannelAction.Action.REMOVE == actionType )
{
final ChannelSubscriptionEntry entry = getSubscriptionManager().removeSubscription( descriptor );
final int removedEntities = deregisterUnOwnedEntities( entry );
_currentAction.recordChannelUnsubscribe( new ChannelChangeStatus( descriptor, filter, removedEntities ) );
}
else if ( ChannelAction.Action.UPDATE == actionType )
{
final ChannelSubscriptionEntry entry = getSubscriptionManager().updateSubscription( descriptor, filter );
final int removedEntities = updateSubscriptionForFilteredEntities( entry, filter );
final ChannelChangeStatus status = new ChannelChangeStatus( descriptor, filter, removedEntities );
_currentAction.recordChannelSubscriptionUpdate( status );
}
else
{
throw new IllegalStateException();
}
}
return true;
}
//Step: Process a chunk of changes
if ( _currentAction.areChangesPending() )
{
if ( LOG.isLoggable( getLogLevel() ) )
{
LOG.log( getLogLevel(), "Processing ChangeSet: " + _currentAction );
}
Change change;
for ( int i = 0; i < _changesToProcessPerTick && null != ( change = _currentAction.nextChange() ); i++ )
{
final Object entity = getChangeMapper().applyChange( change );
if ( LOG.isLoggable( Level.INFO ) )
{
if ( change.isUpdate() )
{
_currentAction.incUpdateCount();
}
else
{
_currentAction.incRemoveCount();
}
}
_currentAction.changeProcessed( change.isUpdate(), entity );
}
return true;
}
//Step: Calculate the entities that need to be linked
if ( !_currentAction.areEntityLinksCalculated() )
{
if ( LOG.isLoggable( getLogLevel() ) )
{
LOG.log( getLogLevel(), "Calculating Link list: " + _currentAction );
}
_currentAction.calculateEntitiesToLink();
return true;
}
//Step: Process a chunk of links
if ( _currentAction.areEntityLinksPending() )
{
if ( LOG.isLoggable( getLogLevel() ) )
{
LOG.log( getLogLevel(), "Linking Entities: " + _currentAction );
}
Linkable linkable;
for ( int i = 0; i < _linksToProcessPerTick && null != ( linkable = _currentAction.nextEntityToLink() ); i++ )
{
linkable.link();
if ( LOG.isLoggable( Level.INFO ) )
{
_currentAction.incLinkCount();
}
}
return true;
}
final ChangeSet set = _currentAction.getChangeSet();
assert null != set;
//Step: Finalize the change set
if ( !_currentAction.hasWorldBeenNotified() )
{
_currentAction.markWorldAsNotified();
if ( LOG.isLoggable( getLogLevel() ) )
{
LOG.log( getLogLevel(), "Finalizing action: " + _currentAction );
}
// OOB messages are not sequenced
if ( !_currentAction.isOob() )
{
session.setLastRxSequence( set.getSequence() );
}
if ( _currentAction.isBulkLoad() )
{
if ( _currentAction.hasBrokerBeenPaused() )
{
getChangeBroker().enable( getChangeBrokerKey() );
}
}
else
{
if ( _currentAction.hasBrokerBeenPaused() )
{
getChangeBroker().resume( getChangeBrokerKey() );
}
}
if ( repositoryDebugOutputEnabled() )
{
outputRepositoryDebug();
}
if ( subscriptionsDebugOutputEnabled() )
{
outputSubscriptionDebug();
}
if ( shouldValidateOnLoad() )
{
validateRepository();
}
return true;
}
final DataLoadStatus status = _currentAction.toStatus( getKey() );
if ( LOG.isLoggable( Level.INFO ) )
{
LOG.info( status.getSystemKey() + ": ChangeSet " + set.getSequence() + " involved " +
status.getChannelAdds().size() + " subscribes, " +
status.getChannelUpdates().size() + " subscription updates, " +
status.getChannelRemoves().size() + " un-subscribes, " +
status.getEntityUpdateCount() + " updates, " +
status.getEntityRemoveCount() + " removes and " +
status.getEntityLinkCount() + " links." );
for ( final ChannelChangeStatus changeStatus : status.getChannelUpdates() )
{
LOG.info( status.getSystemKey() + ": ChangeSet " + set.getSequence() + " subscription update " +
changeStatus.getDescriptor() + " caused " +
changeStatus.getEntityRemoveCount() + " entity removes." );
}
for ( final ChannelChangeStatus changeStatus : status.getChannelRemoves() )
{
LOG.info( status.getSystemKey() + ": ChangeSet " + set.getSequence() + " un-subscribe " +
changeStatus.getDescriptor() + " caused " +
changeStatus.getEntityRemoveCount() + " entity removes." );
}
}
//Step: Run the post actions
if ( LOG.isLoggable( getLogLevel() ) )
{
LOG.log( getLogLevel(), "Running post action and cleaning action: " + _currentAction );
}
final RequestEntry request = _currentAction.getRequest();
if ( null != request )
{
request.markResultsAsArrived();
}
final Runnable runnable = _currentAction.getRunnable();
if ( null != runnable )
{
runnable.run();
// OOB messages are not in response to requests as such
final String requestID = _currentAction.isOob() ? null : _currentAction.getChangeSet().getRequestID();
if ( null != requestID )
{
// We can remove the request because this side ran second and the
// RPC channel has already returned.
final boolean removed = session.removeRequest( requestID );
if ( !removed )
{
LOG.severe( "ChangeSet " + set.getSequence() + " expected to complete request '" +
requestID + "' but no request was registered with session." );
}
if ( requestDebugOutputEnabled() )
{
outputRequestDebug();
}
}
}
onDataLoadComplete( status );
_currentAction = null;
if ( null != _resetAction )
{
_resetAction.run();
_resetAction = null;
}
return true;
}
@Nonnull
private ChannelDescriptor toChannelDescriptor( final ChannelAction action )
{
final int channel = action.getChannelID();
final Object subChannelID = action.getSubChannelID();
final Enum graph = channelToGraph( channel );
return new ChannelDescriptor( graph, subChannelID );
}
private int deregisterUnOwnedEntities( @Nonnull final ChannelSubscriptionEntry entry )
{
int removedEntities = 0;
for ( final Entry<Class<?>, Map<Object, EntitySubscriptionEntry>> entitySet : entry.getEntities().entrySet() )
{
final Class<?> type = entitySet.getKey();
for ( final Entry<Object, EntitySubscriptionEntry> entityEntry : entitySet.getValue().entrySet() )
{
final Object entityID = entityEntry.getKey();
final EntitySubscriptionEntry entitySubscription = entityEntry.getValue();
final ChannelSubscriptionEntry element = entitySubscription.deregisterGraph( entry.getDescriptor() );
if ( null != element && 0 == entitySubscription.getGraphSubscriptions().size() )
{
removedEntities += 1;
final Object entity = getRepository().deregisterEntity( type, entityID );
getChangeBroker().removeAllChangeListeners( entity );
}
}
}
return removedEntities;
}
@Nonnull
public abstract Class<? extends Enum> getGraphType();
protected abstract int updateSubscriptionForFilteredEntities( @Nonnull ChannelSubscriptionEntry graphEntry,
@Nullable Object filter );
protected int updateSubscriptionForFilteredEntities( @Nonnull final ChannelSubscriptionEntry graphEntry,
@Nullable final Object filter,
@Nonnull final Collection<EntitySubscriptionEntry> entities )
{
int removedEntities = 0;
final ChannelDescriptor descriptor = graphEntry.getDescriptor();
final EntitySubscriptionEntry[] subscriptionEntries =
entities.toArray( new EntitySubscriptionEntry[ entities.size() ] );
for ( final EntitySubscriptionEntry entry : subscriptionEntries )
{
final Class<?> entityType = entry.getType();
final Object entityID = entry.getID();
if ( !doesEntityMatchFilter( descriptor, filter, entityType, entityID ) )
{
final EntitySubscriptionEntry entityEntry =
getSubscriptionManager().removeEntityFromGraph( entityType, entityID, descriptor );
final boolean deregisterEntity = 0 == entityEntry.getGraphSubscriptions().size();
if ( LOG.isLoggable( getLogLevel() ) )
{
LOG.log( getLogLevel(),
"Removed entity " + entityType.getSimpleName() + "/" + entityID +
" from graph " + descriptor + " resulting in " +
entityEntry.getGraphSubscriptions().size() + " subscriptions left for entity." +
( deregisterEntity ? " De-registering entity!" : "" ) );
}
// If there is only one subscriber then lets delete it
if ( deregisterEntity )
{
getSubscriptionManager().removeEntity( entityType, entityID );
getRepository().deregisterEntity( entityType, entityID );
removedEntities += 1;
}
}
}
return removedEntities;
}
protected abstract boolean doesEntityMatchFilter( @Nonnull ChannelDescriptor descriptor,
@Nullable Object filter,
@Nonnull Class<?> entityType,
@Nonnull Object entityID );
@Override
public void connect()
{
if ( null == getSession() )
{
performConnect();
}
}
private void performConnect()
{
State state = State.ERROR;
try
{
doConnect( this::completeConnect );
state = State.CONNECTING;
}
finally
{
setState( state );
}
}
private void completeConnect()
{
setState( State.CONNECTED );
getListener().onConnect( this );
}
protected abstract void doConnect( @Nullable Runnable runnable );
protected void handleInvalidConnect( @Nonnull final Throwable exception )
{
setState( State.ERROR );
getListener().onInvalidConnect( this, exception );
}
protected void handleInvalidDisconnect( @Nonnull final Throwable exception )
{
setState( State.ERROR );
getListener().onInvalidDisconnect( this, exception );
}
@Override
public void disconnect()
{
final ClientSession session = getSession();
if ( null != session )
{
setState( State.DISCONNECTING );
doDisconnect( session, this::onDisconnect );
}
}
private void onDisconnect()
{
setState( State.DISCONNECTED );
getListener().onDisconnect( this );
}
protected abstract void doDisconnect( @Nonnull ClientSession session, @Nullable Runnable runnable );
@Nonnull
protected Enum channelToGraph( final int channel )
throws IllegalArgumentException
{
assert getGraphType().isEnum();
return getGraphType().getEnumConstants()[ channel ];
}
/**
* Template method invoked when progressDataLoad() is about to return false and terminate load process.
*/
protected void onTerminatingIncrementalDataLoadProcess()
{
}
/**
* Invoked when a change set has been completely processed.
*
* @param status the status describing the results of data load.
*/
protected void onDataLoadComplete( @Nonnull final DataLoadStatus status )
{
getListener().onDataLoadComplete( this, status );
}
@Nonnull
protected Level getLogLevel()
{
return Level.FINEST;
}
/**
* @return true if a load action should result in the EntityRepository being validated.
*/
protected boolean shouldValidateOnLoad()
{
return false;
}
/**
* Perform a validation of the EntityRepository.
*/
protected void validateRepository()
{
getEntityRepositoryValidator().validate( getRepository() );
}
@Nonnull
protected EntityRepositoryValidator getEntityRepositoryValidator()
{
return new EntityRepositoryValidator();
}
protected boolean requestDebugOutputEnabled()
{
return false;
}
protected boolean subscriptionsDebugOutputEnabled()
{
return false;
}
protected boolean repositoryDebugOutputEnabled()
{
return false;
}
protected void outputRepositoryDebug()
{
getEntityRepositoryDebugger().outputRepository( getRepository() );
}
@Nonnull
protected EntityRepositoryDebugger getEntityRepositoryDebugger()
{
return new EntityRepositoryDebugger();
}
protected void outputSubscriptionDebug()
{
getSubscriptionDebugger().outputSubscriptionManager( getSubscriptionManager() );
}
@Nonnull
protected EntitySubscriptionDebugger getSubscriptionDebugger()
{
return new EntitySubscriptionDebugger();
}
protected void outputRequestDebug()
{
getRequestDebugger().outputRequests( getKey() + ":", ensureSession() );
}
@Nonnull
protected RequestDebugger getRequestDebugger()
{
return new RequestDebugger();
}
}
|
// This source code is available under agreement available at
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
package org.talend.components.salesforce;
import static org.junit.Assert.*;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.talend.components.ComponentTestUtils;
import org.talend.components.api.properties.ComponentProperties;
import org.talend.components.api.properties.presentation.Form;
import org.talend.components.api.schema.SchemaElement;
import org.talend.components.api.service.ComponentService;
import org.talend.components.api.service.internal.ComponentServiceImpl;
import org.talend.components.common.oauth.OauthProperties;
import org.talend.components.salesforce.tsalesforceconnection.TSalesforceConnectionDefinition;
import org.talend.components.salesforce.tsalesforceinput.TSalesforceInputDefinition;
import org.talend.components.salesforce.tsalesforceinput.TSalesforceInputProperties;
public class SalesforceLocalComponentTest {
ComponentService componentService = new ComponentServiceImpl(null);
@BeforeClass public static void init() {
ComponentTestUtils.setupGlobalContext();
}
@AfterClass public static void unset() {
ComponentTestUtils.unsetGlobalContext();
}
public SalesforceLocalComponentTest() {
}
protected ComponentProperties checkAndBefore(Form form, String propName, ComponentProperties props) throws Throwable {
assertTrue(form.getWidget(propName).isCallBefore());
return componentService.beforeProperty(propName, props);
}
protected ComponentProperties checkAndAfter(Form form, String propName, ComponentProperties props) throws Throwable {
assertTrue(form.getWidget(propName).isCallAfter());
return componentService.afterProperty(propName, props);
}
protected ComponentProperties checkAndValidate(Form form, String propName, ComponentProperties props) throws Throwable {
assertTrue(form.getWidget(propName).isCallValidate());
return componentService.validateProperty(propName, props);
}
@Test public void testGetProps() {
ComponentProperties props = new TSalesforceConnectionDefinition().createProperties();
Form f = props.getForm(Form.MAIN);
ComponentTestUtils.checkSerialize(props);
System.out.println(f);
System.out.println(props);
assertEquals(Form.MAIN, f.getName());
}
@Test public void testAfterLoginType() throws Throwable {
ComponentProperties props;
props = new TSalesforceConnectionDefinition().createProperties();
ComponentTestUtils.checkSerialize(props);
SchemaElement loginType = props.getProperty("loginType");
System.out.println(loginType.getPossibleValues());
assertEquals("Basic", loginType.getPossibleValues().get(0).toString());
assertEquals("OAuth", loginType.getPossibleValues().get(1).toString());
assertEquals(SalesforceConnectionProperties.LOGIN_BASIC, props.getValue(loginType));
Form mainForm = props.getForm(Form.MAIN);
assertEquals("Salesforce Connection Settings", mainForm.getTitle());
assertTrue(mainForm.getWidget(SalesforceUserPasswordProperties.class).isVisible());
assertFalse(mainForm.getWidget(OauthProperties.class).isVisible());
props.setValue(loginType, SalesforceConnectionProperties.LOGIN_OAUTH);
props = checkAndAfter(mainForm, "loginType", props);
mainForm = props.getForm(Form.MAIN);
assertTrue(mainForm.isRefreshUI());
assertFalse(mainForm.getWidget(SalesforceUserPasswordProperties.class).isVisible());
assertTrue(mainForm.getWidget(OauthProperties.class).isVisible());
}
@Test public void testInputProps() throws Throwable {
TSalesforceInputProperties props = (TSalesforceInputProperties) new TSalesforceInputDefinition().createProperties();
assertEquals(2, props.queryMode.getPossibleValues().size());
SchemaElement returns = props.getProperty(ComponentProperties.RETURNS);
assertEquals("NB_LINE", returns.getChildren().get(0).getName());
}
}
|
/**
@author Andrew McCallum <a href="mailto:mccallum@cs.umass.edu">mccallum@cs.umass.edu</a>
*/
package cc.mallet.util;
import java.io.*;
import java.lang.CharSequence;
import java.util.Iterator;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.io.*;
import cc.mallet.util.Lexer;
public class CharSequenceLexer implements Lexer, Serializable
{
// Some predefined lexing rules
public static final Pattern LEX_ALPHA = Pattern.compile ("\\p{Alpha}+");
public static final Pattern LEX_WORDS = Pattern.compile ("\\w+");
public static final Pattern LEX_NONWHITESPACE_TOGETHER = Pattern.compile ("\\S+");
public static final Pattern LEX_WORD_CLASSES =
Pattern.compile ("\\p{Alpha}+|\\p{Digit}+");
public static final Pattern LEX_NONWHITESPACE_CLASSES =
Pattern.compile ("\\p{Alpha}+|\\p{Digit}+|\\p{Punct}");
// Lowercase letters and uppercase letters
public static final Pattern UNICODE_LETTERS =
Pattern.compile("[\\u{Ll}&&\\u{Lu}]+");
Pattern regex;
Matcher matcher = null;
CharSequence input;
String matchText;
boolean matchTextFresh;
public CharSequenceLexer ()
{
this (LEX_ALPHA);
}
public CharSequenceLexer (Pattern regex)
{
this.regex = regex;
setCharSequence (null);
}
public CharSequenceLexer (String regex)
{
this (Pattern.compile (regex));
}
public CharSequenceLexer (CharSequence input, Pattern regex)
{
this (regex);
setCharSequence (input);
}
public CharSequenceLexer (CharSequence input, String regex)
{
this (input, Pattern.compile (regex));
}
public void setCharSequence (CharSequence input)
{
this.input = input;
this.matchText = null;
this.matchTextFresh = false;
if (input != null)
this.matcher = regex.matcher(input);
}
public CharSequence getCharSequence()
{
return input;
}
public String getPattern()
{
return regex.pattern();
}
public void setPattern(String reg)// added by Fuchun
{
if(!regex.equals( getPattern() )){
this.regex = Pattern.compile(reg);
// this.matcher = regex.matcher(input);
}
}
public int getStartOffset ()
{
if (matchText == null)
return -1;
return matcher.start();
}
public int getEndOffset ()
{
if (matchText == null)
return -1;
return matcher.end();
}
public String getTokenString ()
{
return matchText;
}
// Iterator interface methods
private void updateMatchText ()
{
if (matcher != null && matcher.find()) {
matchText = matcher.group();
if (matchText.length() == 0) {
// xxx Why would this happen?
// It is happening to me when I use the regex ".*" in an attempt to make
// Token's out of entire lines of text. -akm.
updateMatchText();
//System.err.println ("Match text is empty!");
}
//matchText = input.subSequence (matcher.start(), matcher.end()).toString ();
} else
matchText = null;
matchTextFresh = true;
}
public boolean hasNext ()
{
if (! matchTextFresh)
updateMatchText ();
return (matchText != null);
}
public Object next ()
{
if (! matchTextFresh)
updateMatchText ();
matchTextFresh = false;
return matchText;
}
public void remove ()
{
throw new UnsupportedOperationException ();
}
// Serialization
private static final long serialVersionUID = 1;
private static final int CURRENT_SERIAL_VERSION = 1;
private void writeObject (ObjectOutputStream out) throws IOException {
out.writeInt (CURRENT_SERIAL_VERSION);
// xxx hmph... Pattern.java seems to have serialization
// problems. Work around: serialize the String and flags
// representing the regex, and recompile Pattern.
if (CURRENT_SERIAL_VERSION == 0)
out.writeObject (regex);
else if (CURRENT_SERIAL_VERSION == 1) {
out.writeObject (regex.pattern());
out.writeInt (regex.flags());
//out.writeBoolean(matchTextFresh);
}
out.writeBoolean (matchTextFresh);
}
private void readObject (ObjectInputStream in) throws IOException, ClassNotFoundException {
int version = in.readInt ();
if (version == 0)
regex = (Pattern) in.readObject();
else if (version == 1) {
String p = (String) in.readObject();
int flags = in.readInt();
regex = Pattern.compile (p, flags);
}
matchTextFresh = in.readBoolean();
}
public static void main (String[] args)
{
try {
BufferedReader in
= new BufferedReader(new FileReader(args[0]));
for (String line = in.readLine(); line != null; line = in.readLine()) {
CharSequenceLexer csl =
new CharSequenceLexer (line, LEX_NONWHITESPACE_CLASSES );
while (csl.hasNext())
System.out.println (csl.next());
}
} catch (Exception e) {
System.out.println (e.toString());
}
}
}
|
package org.csstudio.platform.internal.simpledal;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import org.csstudio.platform.internal.simpledal.converters.ConverterUtil;
import org.csstudio.platform.logging.CentralLogger;
import org.csstudio.platform.model.IProcessVariable;
import org.csstudio.platform.model.pvs.IProcessVariableAddress;
import org.csstudio.platform.model.pvs.IProcessVariableAdressProvider;
import org.csstudio.platform.simpledal.ConnectionState;
import org.csstudio.platform.simpledal.IConnector;
import org.csstudio.platform.simpledal.IProcessVariableValueListener;
import org.csstudio.platform.simpledal.IProcessVariableWriteListener;
import org.csstudio.platform.simpledal.SettableState;
import org.csstudio.platform.simpledal.ValueType;
import org.eclipse.core.runtime.Platform;
import org.epics.css.dal.Timestamp;
/**
* Base class for connectors. A connector encapsulates all program logic that is needed to use a
* certain application layer that accesses process variables.
*
* A connector can be used for one-time-action, e.g. getting or setting a process variables value
* as well for permanent-action which means to register listeners for updates of process variables
* values.
*
* For convenience the {@link IProcessVariableValueListener}s are only weakly referenced. The
* connector tracks for {@link IProcessVariableValueListener}s that have been garbage collected and
* removes those references from its internal list. This way {@link IProcessVariableValueListener}s
* dont have to be removed from the connector explicitly.
*
* @author Sven Wende, Xihui Chen
*
*/
@SuppressWarnings("unchecked")
public abstract class AbstractConnector implements IConnector, IProcessVariableAdressProvider,
IProcessVariable {
public static final int BLOCKING_TIMEOUT = 3000;
/**
* The latest received value.
*/
private Object _latestValue;
/**
* The latest received severity value.
*/
private Object _latestSeverityValue;
/**
* The latest received status value.
*/
private Object _latestStatusValue;
/**
* The latest received timestamp value.
*/
private Object _latestTimeStampValue;
/**
* The latest received connection state.
*/
private ConnectionState _latestConnectionState = ConnectionState.INITIAL;
/**
* The process variable pointer for the channel this connector is connected to.
*/
private IProcessVariableAddress _processVariableAddress;
/**
* A list of value listeners to which control system events are forwarded.
*/
protected List<ListenerReference> _weakListenerReferences;
/**
* The latest error.
*/
private String _latestError;
/**
* The value type.
*/
private ValueType _valueType;
/**
* Time in milliseconds until which this connector is not disposed.
*/
private long _keepAliveUntil = 0;
/**
* Constructor.
*
* @param pvAddress
* the address of the process variable this connector is for
* @param valueType
* the type of values expected
*/
public AbstractConnector(IProcessVariableAddress pvAddress, ValueType valueType) {
assert pvAddress != null;
assert valueType != null;
_processVariableAddress = pvAddress;
_valueType = valueType;
_weakListenerReferences = new ArrayList<ListenerReference>();
try {
init();
} catch (Exception e) {
CentralLogger.getInstance().error(null, e);
}
}
/**
* {@inheritDoc}
*/
public final int getListenerCount() {
return _weakListenerReferences.size();
}
/**
* {@inheritDoc}
*/
public final ConnectionState getLatestConnectionState() {
return _latestConnectionState;
}
/**
* {@inheritDoc}
*/
public final Object getLatestValue() {
return _latestValue;
}
/**
* {@inheritDoc}
*/
public final String getLatestError() {
return _latestError;
}
/**
* Forwards the specified connection state to all registered listeners.
*
* @param connectionState
* the connection state
*/
protected final void forwardConnectionState(ConnectionState connectionState) {
doForwardConnectionStateChange(connectionState);
}
/**
* Forwards the specified value to all registered listeners.
*
* @param value
* the value
*/
protected final void forwardValue(Object value) {
doForwardValue(value, new Timestamp());
}
/**
* Forwards the specified value to all registered listeners.
*
* @param value
* the value
*/
protected final void forwardError(String error) {
doForwardError(error);
_latestError = error;
}
/**
* Adds a value listener. When a characteristic is provided, the specified listener is only
* informed of changes in that characteristic.
*
* @param listener
* a value listener (has to be !=null)
*
* @param characteristicId
* the id of a characteristic (can be null)
*/
public final void addProcessVariableValueListener(String characteristicId,
IProcessVariableValueListener listener) {
assert listener != null;
synchronized (_weakListenerReferences) {
_weakListenerReferences.add(new ListenerReference(characteristicId, listener));
}
// send initial connection state,
if (_latestConnectionState != null) {
listener.connectionStateChanged(_latestConnectionState);
}
if (characteristicId != null) {
//send initial condition characteristics value
if(characteristicId.equals("severity") && _latestSeverityValue != null) {
listener.valueChanged(_latestSeverityValue, null);
}else if (characteristicId.equals("status") && _latestSeverityValue != null) {
listener.valueChanged(_latestStatusValue, null);
}else if (characteristicId.equals("timestamp") && _latestSeverityValue != null) {
listener.valueChanged(_latestTimeStampValue, null);
}else
getCharacteristicAsynchronously(characteristicId, getValueType(),
listener);
// try {
// Object initial = EpicsUtil.getCharacteristic(characteristic,
// _dalProperty, null);
// listener.valueChanged(initial, new Timestamp());
// } catch (DataExchangeException e) {
// e.printStackTrace();
}
// send initial value
if (_latestValue != null && characteristicId == null) {
listener.valueChanged(_latestValue, null);
}
// send latest error
if (_latestError != null) {
listener.errorOccured(_latestError);
}
}
/**
* Removes the specified value listener. This is optional - a connector does reference its
* listeners weak by design. This way connectors that are no longer referenced outside of the
* connector will get garbage collected anyway.
*
* @param listener
* the value listener to be removed from the connector
*/
public final boolean removeProcessVariableValueListener(IProcessVariableValueListener listener) {
synchronized (_weakListenerReferences) {
ListenerReference toRemove = null;
for (ListenerReference ref : _weakListenerReferences) {
IProcessVariableValueListener lr = ref.getListener();
if (lr != null && listener == lr) {
toRemove = ref;
break;
}
}
if (toRemove != null) {
_weakListenerReferences.remove(toRemove);
return true;
}
}
return false;
}
/**
* Determines, whether this connector can get disposed. This is, when no value listeners for the
* connector live in the JVM anymore.
*
* @return true, if this connector can be disposed, false otherwise
*/
public final synchronized boolean isDisposable() {
// perform a cleanup first
cleanupWeakReferences();
// this connector can be disposed it there are not weak references left
return _weakListenerReferences.isEmpty() && !isBlocked();
}
/**
* {@inheritDoc}
*/
public final IProcessVariableAddress getProcessVariableAddress() {
return _processVariableAddress;
}
/**
* {@inheritDoc}
*/
public final ValueType getValueType() {
return _valueType;
}
/**
* Determines whether it is possible to write values to the underlying process variable.
*
* @return a state that defines whether write access is possible in a yes/no/unknown manner
*/
public final SettableState isSettable() {
SettableState state = null;
try {
state = doIsSettable();
} catch (Exception e) {
CentralLogger.getInstance().error(null, e);
}
return state != null ? state : SettableState.UNKNOWN;
}
/**
* Disposes the connector.
*/
public final void dispose() {
try {
doDispose();
} catch (Exception e) {
CentralLogger.getInstance().error(null, e);
}
}
/**
*{@inheritDoc}
*/
public void forceDispose() {
_weakListenerReferences.clear();
dispose();
}
/**
* Queries the current value using a synchronous call that will block the current thread.
*
* @param <E>
* return type
*
* @return the current value or null
* @throws Exception
*/
public final <E> E getValueSynchronously() throws Exception {
Object value = doGetValueSynchronously();
E result = value != null ? (E) ConverterUtil.convert(value, getValueType()) : null;
return result;
}
/**
* Queries the current value using an asynchronous call. The result will be reported by calling
* the valueChanged() method on the specified listener.
*
* @param <E>
* return type
*/
public final void getValueAsynchronously(final IProcessVariableValueListener listener) {
try {
doGetValueAsynchronously(listener);
} catch (Exception e) {
CentralLogger.getInstance().error(null, e);
}
}
/**
* Queries the specified characteristic using a synchronous call.The result will be reported by
* calling the valueChanged() method on the specified listener.
*
* @param <E>
* return type
* @param characteristicId
* the characteristic id
* @param valueType
* the type of the expected value
*
* @return the current value or null
* @throws Exception
*/
public final <E> E getCharacteristicSynchronously(String characteristicId,
final ValueType valueType) throws Exception {
Object value = doGetCharacteristicSynchronously(characteristicId, valueType);
E result = value != null ? (E) ConverterUtil.convert(value, valueType) : null;
return result;
}
/**
* Queries the specified characteristic using an asynchronous call that will block the current
* thread.
*
* @param <E>
* return type
* @param characteristicId
* the characteristic id
* @param valueType
* the type of the expected value
*
* @return the current value or null
*/
public final void getCharacteristicAsynchronously(final String characteristicId,
final ValueType valueType, final IProcessVariableValueListener listener) {
try {
doGetCharacteristicAsynchronously(characteristicId, valueType, listener);
} catch (Exception e) {
CentralLogger.getInstance().error(null, e);
}
}
/**
* Sets the specified value using an asynchronous call.
*
* @param value
* the value to be set
* @param listener
* an optional call-back listener
*/
public final void setValueAsynchronously(Object value,
final IProcessVariableWriteListener listener) {
try {
doSetValueAsynchronously(value, listener);
} catch (Exception e) {
CentralLogger.getInstance().error(null, e);
}
}
/**
*
* @param value
* @return
*/
public final boolean setValueSynchronously(Object value) throws Exception {
boolean result = false;
result = doSetValueSynchronously(value);
return result;
}
/**
* Template method. Subclasses should determine whether write access to the underlying process
* variable is possible.
*
* @return a state that defines whether write access is possible in a yes/no/unknown manner
* @throws Exception
* an arbitrary exception
*/
protected abstract SettableState doIsSettable() throws Exception;
/**
* Template method. Subclasses should initialize the physical connection here.
*
* @throws Exception
* an arbitrary exception
*
*/
protected abstract void init() throws Exception;
/**
* Template method. Subclasses should shut down all physical connections here.
*
* @throws Exception
* an arbitrary exception
*
*/
protected abstract void doDispose() throws Exception;
/**
* Template method. Subclasses should implement asynchronous access logic for characteristics
* here.
*
* @param characteristicId
* the characteristic id
* @param valueType
* the expected value type
* @param listener
* the listener has to be informed *
* @throws Exception
* an arbitrary exception
*/
protected abstract void doGetCharacteristicAsynchronously(String characteristicId,
ValueType valueType, IProcessVariableValueListener listener) throws Exception;
/**
* Template method. Subclasses should implement synchronous access logic for characteristics
* here.
*
* @param characteristicId
* the characteristic id
* @param valueType
* the expected value type
*
* @return the characteristic value or null
*
* @throws Exception
* an arbitrary exception
*/
protected abstract Object doGetCharacteristicSynchronously(String characteristicId,
ValueType valueType) throws Exception;
/**
* Template method. Subclasses should implement synchronous access logic for the value here.
*
* @return the current value or null
*
* @throws Exception
* an arbitrary exception
*/
protected abstract Object doGetValueSynchronously() throws Exception;
/**
* Template method. Subclasses should implement asynchronous access logic for the value here.
*
* @param listener
* the listener that has to be informed in a call-back style *
* @throws Exception
* an arbitrary exception
*/
protected abstract void doGetValueAsynchronously(final IProcessVariableValueListener listener)
throws Exception;;
/**
* Template method. Subclasses should implement synchronous logic for setting a value here.
*
* @param value
* the value to be set
*
* @return true on success, false otherwise
* @throws Exception
* an arbitrary exception
*/
protected abstract boolean doSetValueSynchronously(Object value) throws Exception;
/**
* Template method. Subclasses should implement asynchronous logic for setting a value here.
*
* @param value
* the value to be set
* @param listener
* an optional call-back listener
*
* @throws Exception
* an arbitrary exception
*/
protected abstract void doSetValueAsynchronously(Object value,
final IProcessVariableWriteListener listener) throws Exception;
/**
* Forward the specified connection event to the value listeners.
*
* @param event
* the DAL connection event
*/
protected final void doForwardConnectionStateChange(final ConnectionState connectionState) {
if (connectionState != null) {
// remember the latest state
_latestConnectionState = connectionState;
execute(new IInternalRunnable() {
public void doRun(IProcessVariableValueListener valueListener,
String characteristicId) {
valueListener.connectionStateChanged(connectionState);
}
public void doRun(IProcessVariableValueListener valueListener) {
valueListener.connectionStateChanged(connectionState);
}
});
}
}
/**
* Forward the current value with its time stamp.
*
* @param value
* the value
* @param timestamp
* the time stamp of the latest event
*/
protected final void doForwardValue(final Object value, final Timestamp timestamp) {
if (value != null) {
execute(new IInternalRunnable() {
public void doRun(IProcessVariableValueListener valueListener,
String characteristicId) {
// nothing to do - this is for "normal" value listeners only
}
public void doRun(IProcessVariableValueListener valueListener) {
try {
valueListener.valueChanged(ConverterUtil.convert(value, _valueType), timestamp);
// memorize the latest value
_latestValue = value;
} catch (NumberFormatException nfe) {
//Do nothing! Is a invalid value format!
CentralLogger.getInstance().warn(this, "Invalid value format. ("+value+") is not set to "+getName()+".");
}
}
});
}
}
/**
* Forwards the specified characteristic value to all listeners registered for that
* characteristic.
*
* @param characteristicValue
* the characteristic value
* @param timestamp
* the timestamp
* @param characteristicId
* the characteristic id
*/
protected final void doForwardCharacteristic(final Object characteristicValue,
final Timestamp timestamp, final String characteristicId) {
if (characteristicValue != null && characteristicId != null) {
// memorize the latest condition value
if(characteristicId.equals("severity"))
_latestSeverityValue = characteristicValue;
if(characteristicId.equals("status"))
_latestStatusValue = characteristicValue;
if(characteristicId.equals("timestamp"))
_latestTimeStampValue = characteristicValue;
execute(new IInternalRunnable() {
public void doRun(IProcessVariableValueListener valueListener, String cId) {
// forward the value only, if the current listener is
// registered for the same characteristic id
if (cId != null && cId.equals(characteristicId)) {
valueListener.valueChanged(characteristicValue, timestamp);
}
}
public void doRun(IProcessVariableValueListener valueListener) {
// do not forward the value because these listeners are not
// registered for a characteristic
}
});
}
}
/**
* Forward the current value.
*
* @param event
* the DAL connection event
*/
protected final void doForwardError(final String error) {
execute(new IInternalRunnable() {
public void doRun(IProcessVariableValueListener valueListener, String characteristicId) {
valueListener.errorOccured(error);
}
public void doRun(IProcessVariableValueListener valueListener) {
valueListener.errorOccured(error);
}
});
}
protected void requestAndForwardInitialValues() {
synchronized (_weakListenerReferences) {
for (ListenerReference ref : _weakListenerReferences) {
IProcessVariableValueListener listener = ref.getListener();
if (listener != null) {
if (ref.getCharacteristicId() != null) {
getCharacteristicAsynchronously(ref.getCharacteristicId(), getValueType(),
listener);
} else {
getValueAsynchronously(listener);
}
}
}
}
}
/**
* Logs a debug message that is prefixed with common connector information (e.g. the name of the
* process variable).
*
* @param message
* the message
*/
protected void printDebugInfo(String message) {
StringBuffer sb = new StringBuffer();
sb.append(getProcessVariableAddress().toString());
sb.append(": ");
sb.append(message);
CentralLogger.getInstance().debug(null, sb.toString());
}
/**
* Executes the specified runnable for all existing value listeners.
*
* Only for valid listeners that still live in the JVM the hook method
* {@link IInternalRunnable#doRun(IProcessVariableValueListener)} is called.
*
* @param runnable
* the runnable
*/
private void execute(IInternalRunnable runnable) {
synchronized (_weakListenerReferences) {
Iterator<ListenerReference> it = _weakListenerReferences.iterator();
while (it.hasNext()) {
ListenerReference wr = it.next();
IProcessVariableValueListener listener = wr.getListener();
if (listener != null) {
// split the calls for listeners that are registered for a
// characteristic and those which are registered for a
// "normal" value
if (wr.getCharacteristicId() != null) {
runnable.doRun(listener, wr.getCharacteristicId());
} else {
runnable.doRun(listener);
}
}
}
}
}
/**
* Removes weak references for value listeners that have been garbage collected.
*/
private void cleanupWeakReferences() {
synchronized (_weakListenerReferences) {
List<ListenerReference> deletionCandidates = new ArrayList<ListenerReference>();
Iterator<ListenerReference> it = _weakListenerReferences.iterator();
while (it.hasNext()) {
ListenerReference ref = it.next();
if (ref.getListener() == null) {
deletionCandidates.add(ref);
}
}
for (ListenerReference wr : deletionCandidates) {
_weakListenerReferences.remove(wr);
}
}
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
return _processVariableAddress.getProperty();
}
/**
* {@inheritDoc}
*/
public List<IProcessVariableAddress> getProcessVariableAdresses() {
return Collections.singletonList(_processVariableAddress);
}
/**
* {@inheritDoc}
*/
public IProcessVariableAddress getPVAdress() {
return _processVariableAddress;
}
/**
* {@inheritDoc}
*/
public String getName() {
return _processVariableAddress.toString();
}
/**
* {@inheritDoc}
*/
public String getTypeId() {
return IProcessVariable.TYPE_ID;
}
public synchronized void block() {
_keepAliveUntil = System.currentTimeMillis() + BLOCKING_TIMEOUT;
}
/**
* {@inheritDoc}
*/
public Object getAdapter(Class adapterType) {
return Platform.getAdapterManager().getAdapter(this, adapterType);
}
private boolean isBlocked() {
long diff = _keepAliveUntil - System.currentTimeMillis();
return diff > 0;
}
/**
* Runnable which is used to forward events to process variable value listeners.
*
* @author Sven Wende
*
*/
interface IInternalRunnable {
/**
* Hook which is called only for valid value listeners, which still live in the JVM and have
* not already been garbage collected AND that is registered for a specific characteristic
* id.
*
* @param valueListener
* a value listener instance (it is ensured, that this is not null)
* @param characteristicId
* the characteristic id (it is ensured, that this is not null)
*/
void doRun(IProcessVariableValueListener valueListener, String characteristicId);
/**
* Hook which is called only for valid value listeners, which still live in the JVM and have
* not already been garbage collected.
*
* @param valueListener
* a value listener instance (we ensure, that this is not null)
*/
void doRun(IProcessVariableValueListener valueListener);
}
/**
* Keeps a weak reference to a listener. Because of its weakness this reference does not prevent
* the listener from getting garbage collected when its not references elsewhere.
*
* A listener could have been registered for a specific characteristic id, which is a special
* case, as several characteristics can be delivered via the same connection and can be reported
* as a reaction to certain system events.
*
* @author Sven Wende
*/
static class ListenerReference {
private WeakReference<IProcessVariableValueListener> _listener;
private String _characteristicId = null;
public ListenerReference(String characteristic, IProcessVariableValueListener<?> listener) {
_characteristicId = characteristic;
_listener = new WeakReference<IProcessVariableValueListener>(listener);
}
public boolean isCharacteristic() {
return _characteristicId != null;
}
public IProcessVariableValueListener<?> getListener() {
return _listener.get();
}
public String getCharacteristicId() {
return _characteristicId;
}
}
}
|
package edu.ucdenver.ccp.datasource.identifiers;
import java.util.HashSet;
import java.util.Set;
import org.apache.log4j.Logger;
import edu.ucdenver.ccp.common.string.StringConstants;
import edu.ucdenver.ccp.common.string.StringUtil;
import edu.ucdenver.ccp.datasource.identifiers.bind.BindInteractionID;
import edu.ucdenver.ccp.datasource.identifiers.dip.DipInteractionID;
import edu.ucdenver.ccp.datasource.identifiers.dip.DipInteractorID;
import edu.ucdenver.ccp.datasource.identifiers.drugbank.DrugBankID;
import edu.ucdenver.ccp.datasource.identifiers.drugbank.DrugCodeDirectoryID;
import edu.ucdenver.ccp.datasource.identifiers.drugbank.DrugsProductDatabaseID;
import edu.ucdenver.ccp.datasource.identifiers.ebi.embl.EmblID;
import edu.ucdenver.ccp.datasource.identifiers.ebi.intact.IntActID;
import edu.ucdenver.ccp.datasource.identifiers.ebi.interpro.InterProID;
import edu.ucdenver.ccp.datasource.identifiers.ebi.interpro.PirID;
import edu.ucdenver.ccp.datasource.identifiers.ebi.interpro.TigrFamsID;
import edu.ucdenver.ccp.datasource.identifiers.ebi.ipi.IpiID;
import edu.ucdenver.ccp.datasource.identifiers.ebi.uniprot.UniProtID;
import edu.ucdenver.ccp.datasource.identifiers.ebi.uniprot.UniProtIsoformID;
import edu.ucdenver.ccp.datasource.identifiers.ensembl.EnsemblGeneID;
import edu.ucdenver.ccp.datasource.identifiers.flybase.FlyBaseID;
import edu.ucdenver.ccp.datasource.identifiers.hgnc.HgncGeneSymbolID;
import edu.ucdenver.ccp.datasource.identifiers.hgnc.HgncID;
import edu.ucdenver.ccp.datasource.identifiers.hprd.HprdID;
import edu.ucdenver.ccp.datasource.identifiers.irefweb.IRefWebInteractionID;
import edu.ucdenver.ccp.datasource.identifiers.irefweb.IRefWebInteractorID;
import edu.ucdenver.ccp.datasource.identifiers.kegg.KeggCompoundID;
import edu.ucdenver.ccp.datasource.identifiers.kegg.KeggDrugID;
import edu.ucdenver.ccp.datasource.identifiers.kegg.KeggGeneID;
import edu.ucdenver.ccp.datasource.identifiers.kegg.KeggPathwayID;
import edu.ucdenver.ccp.datasource.identifiers.mgi.MgiGeneID;
import edu.ucdenver.ccp.datasource.identifiers.mint.MintID;
import edu.ucdenver.ccp.datasource.identifiers.ncbi.GenBankID;
import edu.ucdenver.ccp.datasource.identifiers.ncbi.gene.EntrezGeneID;
import edu.ucdenver.ccp.datasource.identifiers.ncbi.gene.GiNumberID;
import edu.ucdenver.ccp.datasource.identifiers.ncbi.homologene.HomologeneGroupID;
import edu.ucdenver.ccp.datasource.identifiers.ncbi.omim.OmimID;
import edu.ucdenver.ccp.datasource.identifiers.ncbi.refseq.RefSeqID;
import edu.ucdenver.ccp.datasource.identifiers.ncbi.snp.SnpRsId;
import edu.ucdenver.ccp.datasource.identifiers.obo.CellTypeOntologyID;
import edu.ucdenver.ccp.datasource.identifiers.obo.ChebiOntologyID;
import edu.ucdenver.ccp.datasource.identifiers.obo.GeneOntologyID;
import edu.ucdenver.ccp.datasource.identifiers.obo.MammalianPhenotypeID;
import edu.ucdenver.ccp.datasource.identifiers.obo.ProteinOntologyId;
import edu.ucdenver.ccp.datasource.identifiers.obo.SequenceOntologyId;
import edu.ucdenver.ccp.datasource.identifiers.other.AnimalQtlDbID;
import edu.ucdenver.ccp.datasource.identifiers.other.AphidBaseID;
import edu.ucdenver.ccp.datasource.identifiers.other.ApiDbCryptoDbID;
import edu.ucdenver.ccp.datasource.identifiers.other.BeeBaseID;
import edu.ucdenver.ccp.datasource.identifiers.other.BeetleBaseID;
import edu.ucdenver.ccp.datasource.identifiers.other.BioGridID;
import edu.ucdenver.ccp.datasource.identifiers.other.CgncID;
import edu.ucdenver.ccp.datasource.identifiers.other.ClinicalTrialsGovId;
import edu.ucdenver.ccp.datasource.identifiers.other.DbjID;
import edu.ucdenver.ccp.datasource.identifiers.other.DictyBaseID;
import edu.ucdenver.ccp.datasource.identifiers.other.EcoCycID;
import edu.ucdenver.ccp.datasource.identifiers.other.EcoGeneID;
import edu.ucdenver.ccp.datasource.identifiers.other.EmbID;
import edu.ucdenver.ccp.datasource.identifiers.other.GdbId;
import edu.ucdenver.ccp.datasource.identifiers.other.GeoId;
import edu.ucdenver.ccp.datasource.identifiers.other.ImgtID;
import edu.ucdenver.ccp.datasource.identifiers.other.IsrctnId;
import edu.ucdenver.ccp.datasource.identifiers.other.MaizeGdbID;
import edu.ucdenver.ccp.datasource.identifiers.other.MiRBaseID;
import edu.ucdenver.ccp.datasource.identifiers.other.NasoniaBaseID;
import edu.ucdenver.ccp.datasource.identifiers.other.PathemaID;
import edu.ucdenver.ccp.datasource.identifiers.other.PbrID;
import edu.ucdenver.ccp.datasource.identifiers.other.PseudoCapID;
import edu.ucdenver.ccp.datasource.identifiers.other.PubChemBioAssayId;
import edu.ucdenver.ccp.datasource.identifiers.other.PubChemCompoundId;
import edu.ucdenver.ccp.datasource.identifiers.other.PubChemSubstanceId;
import edu.ucdenver.ccp.datasource.identifiers.other.RatMapID;
import edu.ucdenver.ccp.datasource.identifiers.other.TairID;
import edu.ucdenver.ccp.datasource.identifiers.other.UniParcID;
import edu.ucdenver.ccp.datasource.identifiers.other.VbrcID;
import edu.ucdenver.ccp.datasource.identifiers.other.VectorBaseID;
import edu.ucdenver.ccp.datasource.identifiers.other.VegaID;
import edu.ucdenver.ccp.datasource.identifiers.other.XenBaseID;
import edu.ucdenver.ccp.datasource.identifiers.other.ZfinID;
import edu.ucdenver.ccp.datasource.identifiers.pdb.PdbID;
import edu.ucdenver.ccp.datasource.identifiers.pharmgkb.PharmGkbID;
import edu.ucdenver.ccp.datasource.identifiers.psi.PsiModId;
import edu.ucdenver.ccp.datasource.identifiers.reactome.ReactomeReactionID;
import edu.ucdenver.ccp.datasource.identifiers.rgd.RgdID;
import edu.ucdenver.ccp.datasource.identifiers.sgd.SgdID;
import edu.ucdenver.ccp.datasource.identifiers.transfac.TransfacGeneID;
import edu.ucdenver.ccp.datasource.identifiers.wormbase.WormBaseID;
import edu.ucdenver.ccp.identifier.publication.PubMedID;
import edu.ucdenver.ccp.datasource.identifiers.ncbi.taxonomy.NcbiTaxonomyID;
/**
* provides various methods to map from an ID in database or ontology files
* to instances of identifier classes under edu.ucdenver.ccp.datasource.identifiers.
*
* These are basically factory methods. Given some information about where the ID
* came from and an ID string, it creates an instance of an identifier class
* related to the source. This is done for DataSourceIdentifiers,
* PMID identifiers and others.
*
* Three functions named resolveId():
* - a value of the DataSource enum and an ID string.
* - a name of a data source and and ID string.
* - an ID string that is parsed to discover the data source it came from.
**/
public class DataSourceIdResolver {
private static final String IREFWEB_ENTREZGENE_ID_PREFIX = "entrezgene/locuslink:";
private static final Logger logger = Logger.getLogger(DataSourceIdResolver.class);
public static DataSourceIdentifier<?> resolveId(DataSource dataSource, String databaseObjectID) {
switch (dataSource) {
case CLINICAL_TRIALS_GOV:
return new ClinicalTrialsGovId(databaseObjectID);
case DIP:
if (databaseObjectID.matches("DIP-\\d+N"))
return new DipInteractorID(databaseObjectID);
if (databaseObjectID.matches("DIP-\\d+E"))
return new DipInteractionID(databaseObjectID);
throw new IllegalArgumentException(String.format("Invalid DIP Interactor ID detected %s", databaseObjectID));
case EG:
return new EntrezGeneID(databaseObjectID);
case EMBL:
return new EmblID(databaseObjectID);
case ISRCTN:
return new IsrctnId(databaseObjectID);
case GDB:
return new GdbId(databaseObjectID);
case GENBANK:
return new GenBankID(databaseObjectID);
case GEO:
return new GeoId(databaseObjectID);
case MGI:
return new MgiGeneID(databaseObjectID);
case PHARMGKB:
return new PharmGkbID(databaseObjectID);
case PR:
return new ProteinOntologyId(databaseObjectID);
case PUBCHEM_SUBSTANCE:
return new PubChemSubstanceId(databaseObjectID);
case PUBCHEM_COMPOUND:
return new PubChemCompoundId(databaseObjectID);
case PUBCHEM_BIOASSAY:
return new PubChemBioAssayId(databaseObjectID);
case IREFWEB:
return new IRefWebInteractorID(databaseObjectID);
case HPRD:
return new HprdID(databaseObjectID);
case HGNC:
return new HgncGeneSymbolID(databaseObjectID);
case OMIM:
return new OmimID(databaseObjectID);
case PDB:
return new PdbID(databaseObjectID);
case PIR:
return new PirID(databaseObjectID);
case REFSEQ:
return new RefSeqID(databaseObjectID);
case TRANSFAC:
return new TransfacGeneID(databaseObjectID);
case UNIPROT:
if (databaseObjectID.contains(StringConstants.HYPHEN_MINUS))
return new UniProtIsoformID(databaseObjectID);
return new UniProtID(databaseObjectID);
default:
throw new IllegalArgumentException(String.format(
"Resolving the ID's for this DataSource are not yet implemented: %s.", dataSource.name()));
}
}
// TODO: remove this method and replace its use with resolveId(DataSource, String)
public static DataSourceIdentifier<?> resolveId(String databaseName, String databaseObjectID) {
if (databaseName.equalsIgnoreCase("MGI"))
return new MgiGeneID(databaseObjectID);
else if (databaseName.equalsIgnoreCase("UniProtKB"))
return new UniProtID(databaseObjectID);
else if (databaseName.equalsIgnoreCase("chebi"))
return new ChebiOntologyID("CHEBI:" + databaseObjectID);
else if (databaseName.equalsIgnoreCase("DIP"))
return new DipInteractorID(databaseObjectID);
else if (databaseName.equalsIgnoreCase("drugbank"))
return new DrugBankID(databaseObjectID);
else if (databaseName.equalsIgnoreCase("keggdrug"))
return new KeggDrugID(databaseObjectID);
else if (databaseName.equalsIgnoreCase("keggcompound"))
return new KeggCompoundID(databaseObjectID);
else if (databaseName.equalsIgnoreCase("pubchemcompound"))
return new PubChemCompoundId(databaseObjectID);
else if (databaseName.equalsIgnoreCase("pubchemsubstance"))
return new PubChemSubstanceId(databaseObjectID);
else if (databaseName.equalsIgnoreCase("EG"))
return new EntrezGeneID(databaseObjectID);
else if (databaseName.equalsIgnoreCase("Ensembl"))
return new EnsemblGeneID(databaseObjectID);
else if (databaseName.equalsIgnoreCase("EMBL"))
return new EmblID(databaseObjectID);
else if (databaseName.equalsIgnoreCase("RefSeq"))
return new RefSeqID(databaseObjectID);
else if (databaseName.equalsIgnoreCase("VEGA"))
return new VegaID(databaseObjectID);
else if (databaseName.equalsIgnoreCase("NCBI-GI"))
return new GiNumberID(databaseObjectID);
else if (databaseName.equalsIgnoreCase("NCBI-GeneID"))
return new EntrezGeneID(databaseObjectID);
else if (databaseName.equalsIgnoreCase("OMIM"))
return new OmimID(databaseObjectID);
else if (databaseName.equalsIgnoreCase("HGNC"))
return new HgncID(databaseObjectID);
else if (databaseName.equalsIgnoreCase("HPRD"))
return new HprdID(databaseObjectID);
else if (databaseName.equalsIgnoreCase("UniProt"))
return new UniProtID(databaseObjectID);
else if (databaseName.equalsIgnoreCase("PharmGKB"))
return new PharmGkbID(databaseObjectID);
else if (databaseName.equalsIgnoreCase("Drugs Product Database (DPD)") || databaseName.equalsIgnoreCase("DPD"))
return new DrugsProductDatabaseID(databaseObjectID);
else if (databaseName.equalsIgnoreCase("National Drug Code Directory"))
return new DrugCodeDirectoryID(databaseObjectID);
else if (databaseName.equalsIgnoreCase("GenBank") || databaseName.equalsIgnoreCase("GenBank Gene Database")
|| databaseName.equalsIgnoreCase("GenBank Protein Database"))
return new GenBankID(databaseObjectID);
logger.warn("Unable to resolve data source identifier: datasource=" + databaseName + " id=" + databaseObjectID);
return null;
}
/**
* Resolve provided id to an instance of {@link DataSourceIdentifier}.
*
* @param geneIDStr
* @return if can be resolved, id instance; otherwise, null
*/
public static DataSourceIdentifier<?> resolveId(String geneIDStr) {
try {
if (geneIDStr.startsWith("MGI:"))
return new MgiGeneID(geneIDStr);
else if (geneIDStr.startsWith("ncbi-geneid:"))
return new EntrezGeneID(StringUtil.removePrefix(geneIDStr, "ncbi-geneid:"));
else if (geneIDStr.startsWith(IREFWEB_ENTREZGENE_ID_PREFIX))
return new EntrezGeneID(StringUtil.removePrefix(geneIDStr, IREFWEB_ENTREZGENE_ID_PREFIX));
else if (geneIDStr.startsWith("Ensembl:"))
return new EnsemblGeneID(StringUtil.removePrefix(geneIDStr, "Ensembl:"));
else if (geneIDStr.startsWith("refseq:"))
return new RefSeqID(StringUtil.removePrefix(geneIDStr, "refseq:"));
else if (StringUtil.startsWithRegex(geneIDStr.toLowerCase(), "uniprot.*?:")) {
geneIDStr = StringUtil.removePrefixRegex(geneIDStr.toLowerCase(), "uniprot.*?:");
if (geneIDStr.contains(StringConstants.HYPHEN_MINUS))
return new UniProtIsoformID(geneIDStr.toUpperCase());
return new UniProtID(geneIDStr.toUpperCase());
} else if (geneIDStr.startsWith("Swiss-Prot:"))
return new UniProtID(StringUtil.removePrefix(geneIDStr, "Swiss-Prot:"));
else if (geneIDStr.startsWith("TREMBL:"))
return new UniProtID(StringUtil.removePrefix(geneIDStr, "TREMBL:"));
else if (geneIDStr.startsWith("TAIR:"))
return new TairID(StringUtil.removePrefix(geneIDStr, "TAIR:"));
else if (geneIDStr.startsWith("MaizeGDB:"))
return new MaizeGdbID(StringUtil.removePrefix(geneIDStr, "MaizeGDB:"));
else if (geneIDStr.startsWith("WormBase:"))
return new WormBaseID(StringUtil.removePrefix(geneIDStr, "WormBase:"));
else if (geneIDStr.startsWith("BEEBASE:"))
return new BeeBaseID(StringUtil.removePrefix(geneIDStr, "BEEBASE:"));
else if (geneIDStr.startsWith("NASONIABASE:"))
return new NasoniaBaseID(StringUtil.removePrefix(geneIDStr, "NASONIABASE:"));
else if (geneIDStr.startsWith("VectorBase:"))
return new VectorBaseID(StringUtil.removePrefix(geneIDStr, "VectorBase:"));
else if (geneIDStr.startsWith("APHIDBASE:"))
return new AphidBaseID(StringUtil.removePrefix(geneIDStr, "APHIDBASE:"));
else if (geneIDStr.startsWith("BEETLEBASE:"))
return new BeetleBaseID(StringUtil.removePrefix(geneIDStr, "BEETLEBASE:"));
else if (geneIDStr.toUpperCase().startsWith("FLYBASE:"))
return new FlyBaseID(StringUtil.removePrefix(geneIDStr.toUpperCase(), "FLYBASE:"));
else if (geneIDStr.startsWith("ZFIN:"))
return new ZfinID(StringUtil.removePrefix(geneIDStr, "ZFIN:"));
else if (geneIDStr.startsWith("AnimalQTLdb:"))
return new AnimalQtlDbID(StringUtil.removePrefix(geneIDStr, "AnimalQTLdb:"));
else if (geneIDStr.startsWith("RGD:"))
return new RgdID(StringUtil.removePrefix(geneIDStr, "RGD:"));
else if (geneIDStr.startsWith("PBR:"))
return new PbrID(StringUtil.removePrefix(geneIDStr, "PBR:"));
else if (geneIDStr.startsWith("VBRC:"))
return new VbrcID(StringUtil.removePrefix(geneIDStr, "VBRC:"));
else if (geneIDStr.startsWith("Pathema:"))
return new PathemaID(StringUtil.removePrefix(geneIDStr, "Pathema:"));
else if (geneIDStr.startsWith("PseudoCap:"))
return new PseudoCapID(StringUtil.removePrefix(geneIDStr, "PseudoCap:"));
else if (geneIDStr.startsWith("ApiDB_CryptoDB:"))
return new ApiDbCryptoDbID(StringUtil.removePrefix(geneIDStr, "ApiDB_CryptoDB:"));
else if (geneIDStr.startsWith("dictyBase:"))
return new DictyBaseID(StringUtil.removePrefix(geneIDStr, "dictyBase:"));
else if (geneIDStr.startsWith("UniProtKB/Swiss-Prot:"))
return new UniProtID(StringUtil.removePrefix(geneIDStr, "UniProtKB/Swiss-Prot:"));
else if (geneIDStr.startsWith("InterPro:"))
return new InterProID(StringUtil.removePrefix(geneIDStr, "InterPro:"));
else if (geneIDStr.startsWith("EcoGene:"))
return new EcoGeneID(StringUtil.removePrefix(geneIDStr, "EcoGene:"));
else if (geneIDStr.toUpperCase().startsWith("ECOCYC:"))
return new EcoCycID(StringUtil.removePrefix(geneIDStr.toUpperCase(), "ECOCYC:"));
else if (geneIDStr.startsWith("SGD:"))
return new SgdID(StringUtil.removePrefix(geneIDStr, "SGD:"));
else if (geneIDStr.startsWith("RATMAP:"))
return new RatMapID(StringUtil.removePrefix(geneIDStr, "RATMAP:"));
else if (geneIDStr.startsWith("Xenbase:"))
return new XenBaseID(StringUtil.removePrefix(geneIDStr, "Xenbase:"));
else if (geneIDStr.startsWith("CGNC:"))
return new CgncID(StringUtil.removePrefix(geneIDStr, "CGNC:"));
else if (geneIDStr.startsWith("HGNC:"))
return new HgncID(geneIDStr);
else if (geneIDStr.startsWith("MIM:"))
return new OmimID(StringUtil.removePrefix(geneIDStr, "MIM:"));
else if (geneIDStr.startsWith("HPRD:"))
return new HprdID(StringUtil.removePrefix(geneIDStr, "HPRD:"));
else if (geneIDStr.startsWith("IMGT/GENE-DB:"))
return new ImgtID(StringUtil.removePrefix(geneIDStr, "IMGT/GENE-DB:"));
else if (geneIDStr.startsWith("PDB:"))
return new PdbID(StringUtil.removePrefix(geneIDStr, "PDB:"));
else if (geneIDStr.startsWith("irefindex:"))
return new IRefWebInteractorID(StringUtil.removePrefix(geneIDStr, "irefindex:"));
else if (geneIDStr.toLowerCase().startsWith("gb:"))
return new GenBankID(StringUtil.removePrefix(geneIDStr.toLowerCase(), "gb:").toUpperCase());
else if (geneIDStr.startsWith("emb:"))
return new EmbID(StringUtil.removePrefix(geneIDStr, "emb:"));
else if (geneIDStr.startsWith("dbj:"))
return new DbjID(StringUtil.removePrefix(geneIDStr, "dbj:"));
else if (geneIDStr.startsWith("intact:"))
return new IntActID(StringUtil.removePrefix(geneIDStr, "intact:"));
else if (geneIDStr.startsWith("RefSeq:"))
return new RefSeqID(StringUtil.removePrefix(geneIDStr, "RefSeq:"));
else if (geneIDStr.startsWith("uniparc:"))
return new UniParcID(StringUtil.removePrefix(geneIDStr, "uniparc:"));
else if (geneIDStr.startsWith("genbank_protein_gi:"))
return new GiNumberID(StringUtil.removePrefix(geneIDStr, "genbank_protein_gi:"));
else if (geneIDStr.toLowerCase().startsWith("pir:"))
return new PirID(StringUtil.removePrefix(geneIDStr.toLowerCase(), "pir:").toUpperCase());
else if (geneIDStr.startsWith("pubmed:"))
return new PubMedID(StringUtil.removePrefix(geneIDStr, "pubmed:"));
else if (geneIDStr.startsWith("dip:") && geneIDStr.endsWith("N"))
return new DipInteractorID(StringUtil.removePrefix(geneIDStr, "dip:"));
else if (geneIDStr.startsWith("dip:") && geneIDStr.endsWith("E"))
return new DipInteractionID(StringUtil.removePrefix(geneIDStr, "dip:"));
else if (geneIDStr.startsWith("TIGR:"))
return new TigrFamsID(StringUtil.removePrefix(geneIDStr, "TIGR:"));
else if (geneIDStr.startsWith("ipi:"))
return new IpiID(StringUtil.removePrefix(geneIDStr, "ipi:"));
else if (geneIDStr.startsWith("mint:"))
return new MintID(StringUtil.removePrefix(geneIDStr, "mint:"));
else if (geneIDStr.startsWith("Reactome:"))
return new ReactomeReactionID(StringUtil.removePrefix(geneIDStr, "Reactome:"));
else if (geneIDStr.startsWith("miRBase:"))
return new MiRBaseID(StringUtil.removePrefix(geneIDStr, "miRBase:"));
else if (geneIDStr.startsWith("PR:"))
return new ProteinOntologyId(geneIDStr);
else if (geneIDStr.startsWith("SO:"))
return new SequenceOntologyId(geneIDStr);
else if (geneIDStr.startsWith("GO:"))
return new GeneOntologyID(geneIDStr);
else if (geneIDStr.startsWith("CHEBI:"))
return new ChebiOntologyID(geneIDStr);
else if (geneIDStr.startsWith("MP:"))
return new MammalianPhenotypeID(geneIDStr);
else if (geneIDStr.startsWith("MOD:"))
return new PsiModId(geneIDStr);
else if (geneIDStr.startsWith("KEGG_"))
return new KeggGeneID(geneIDStr);
else if (geneIDStr.startsWith("KEGG_PATHWAY"))
return new KeggPathwayID(geneIDStr);
else if (geneIDStr.startsWith("EG_"))
return new EntrezGeneID(StringUtil.removePrefix(geneIDStr, "EG_"));
else if (geneIDStr.startsWith("HOMOLOGENE_GROUP_"))
return new HomologeneGroupID(StringUtil.removePrefix(geneIDStr, "HOMOLOGENE_GROUP_"));
else if (geneIDStr.matches("IPR\\d+"))
return new InterProID(geneIDStr);
else if (geneIDStr.matches("rs\\d+"))
return new SnpRsId(geneIDStr);
else if (geneIDStr.startsWith("CL:"))
return new CellTypeOntologyID(geneIDStr);
else if (geneIDStr.startsWith("NCBITaxon:"))
return new NcbiTaxonomyID(StringUtil.removePrefix(geneIDStr, "NCBITaxon:"));
logger.error(String
.format("Unknown gene ID format: %s. Cannot create DataElementIdentifier<?>.", geneIDStr));
} catch (IllegalArgumentException e) {
logger.warn("Invalid ID detected... ", e);
}
return null;
}
/**
* Resolve interaction id to {@link DataSourceIdentifier}.
*
* @param interactionIDStr
* id to resolve
* @return identifier if argument is resolvable and supported; otherwise, return null.
*/
private static DataSourceIdentifier<?> resolveInteractionID(String interactionIDStr) {
if (interactionIDStr.startsWith("intact:"))
return new IntActID(StringUtil.removePrefix(interactionIDStr, "intact:"));
else if (interactionIDStr.startsWith("irefindex:"))
return new IRefWebInteractionID(StringUtil.removePrefix(interactionIDStr, "irefindex:"));
else if (interactionIDStr.startsWith("bind:"))
return new BindInteractionID(StringUtil.removePrefix(interactionIDStr, "bind:"));
else if (interactionIDStr.startsWith("grid:"))
return new BioGridID(StringUtil.removePrefix(interactionIDStr, "grid:"));
else if (interactionIDStr.startsWith("mint:"))
return new MintID(StringUtil.removePrefix(interactionIDStr, "mint:"));
logger.error(String.format("Unknown interaction ID format: %s. Cannot create DataElementIdentifier<?>.",
interactionIDStr));
return null;
}
/**
* Resolve interaction IDs to list of {@link DataSourceIdentifier}.
*
* @param interactionIDStrs
* ids to resolve
* @return identifier if all members of <code>interactionIDStrs</code> are resolvable and
* supported; otherwise, return null.
*/
public static Set<DataSourceIdentifier<?>> resolveInteractionIDs(Set<String> interactionIDStrs) {
Set<DataSourceIdentifier<?>> interactionIDs = new HashSet<DataSourceIdentifier<?>>();
for (String interactionIDStr : interactionIDStrs) {
DataSourceIdentifier<?> id = resolveInteractionID(interactionIDStr);
if (id == null)
return null;
interactionIDs.add(id);
}
return interactionIDs;
}
/**
* Resolve Pubmed ID from value that starts with prefix 'pubmed:'.
*
* @param pmidStr
* @return id if value following prefix is a positive integer; otherwise, null
*/
public static PubMedID resolvePubMedID(String pmidStr) {
String prefix = "pubmed:";
if (pmidStr.startsWith(prefix)) {
String id = StringUtil.removePrefix(pmidStr, prefix);
if (StringUtil.isIntegerGreaterThanZero(id))
return new PubMedID(id);
}
logger.error(String.format("Unknown PubMed ID format: %s. Cannot create PubMedID.", pmidStr));
return null;
}
public static Set<PubMedID> resolvePubMedIDs(Set<String> pmidStrs) {
Set<PubMedID> pmids = new HashSet<PubMedID>();
for (String pmidStr : pmidStrs) {
PubMedID id = resolvePubMedID(pmidStr);
if (id == null)
return null;
pmids.add(id);
}
return pmids;
}
public static Set<DataSourceIdentifier<?>> resolveIds(Set<String> databaseObjectIDStrs) {
Set<DataSourceIdentifier<?>> databaseObjectIDs = new HashSet<DataSourceIdentifier<?>>();
for (String databaseObjectIDStr : databaseObjectIDStrs) {
DataSourceIdentifier<?> id = resolveId(databaseObjectIDStr);
if (id != null)
databaseObjectIDs.add(id);
}
return databaseObjectIDs;
}
}
|
package jolie.lang.parse;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Vector;
import jolie.Constants;
import jolie.lang.parse.ast.AndConditionNode;
import jolie.lang.parse.ast.AssignStatement;
import jolie.lang.parse.ast.CompareConditionNode;
import jolie.lang.parse.ast.CompensateStatement;
import jolie.lang.parse.ast.ConstantIntegerExpression;
import jolie.lang.parse.ast.ConstantStringExpression;
import jolie.lang.parse.ast.CorrelationSetInfo;
import jolie.lang.parse.ast.DeepCopyStatement;
import jolie.lang.parse.ast.ExecutionInfo;
import jolie.lang.parse.ast.ExitStatement;
import jolie.lang.parse.ast.ExpressionConditionNode;
import jolie.lang.parse.ast.IfStatement;
import jolie.lang.parse.ast.InStatement;
import jolie.lang.parse.ast.InputPortTypeInfo;
import jolie.lang.parse.ast.InstallCompensationStatement;
import jolie.lang.parse.ast.InstallFaultHandlerStatement;
import jolie.lang.parse.ast.LinkInStatement;
import jolie.lang.parse.ast.LinkOutStatement;
import jolie.lang.parse.ast.NDChoiceStatement;
import jolie.lang.parse.ast.NotConditionNode;
import jolie.lang.parse.ast.NotificationOperationDeclaration;
import jolie.lang.parse.ast.NotificationOperationStatement;
import jolie.lang.parse.ast.NullProcessStatement;
import jolie.lang.parse.ast.OLSyntaxNode;
import jolie.lang.parse.ast.OneWayOperationDeclaration;
import jolie.lang.parse.ast.OneWayOperationStatement;
import jolie.lang.parse.ast.OrConditionNode;
import jolie.lang.parse.ast.OutStatement;
import jolie.lang.parse.ast.OutputPortTypeInfo;
import jolie.lang.parse.ast.ParallelStatement;
import jolie.lang.parse.ast.PointerStatement;
import jolie.lang.parse.ast.PortInfo;
import jolie.lang.parse.ast.Procedure;
import jolie.lang.parse.ast.ProcedureCallStatement;
import jolie.lang.parse.ast.ProductExpressionNode;
import jolie.lang.parse.ast.Program;
import jolie.lang.parse.ast.RequestResponseOperationDeclaration;
import jolie.lang.parse.ast.RequestResponseOperationStatement;
import jolie.lang.parse.ast.Scope;
import jolie.lang.parse.ast.SequenceStatement;
import jolie.lang.parse.ast.ServiceInfo;
import jolie.lang.parse.ast.SleepStatement;
import jolie.lang.parse.ast.SolicitResponseOperationDeclaration;
import jolie.lang.parse.ast.SolicitResponseOperationStatement;
import jolie.lang.parse.ast.StateInfo;
import jolie.lang.parse.ast.SumExpressionNode;
import jolie.lang.parse.ast.ThrowStatement;
import jolie.lang.parse.ast.VariableExpressionNode;
import jolie.lang.parse.ast.VariablePath;
import jolie.lang.parse.ast.WhileStatement;
import jolie.util.Pair;
/** Parser for a .ol file.
* @author Fabrizio Montesi
*
*/
public class OLParser extends AbstractParser
{
private Program program = new Program();
private HashMap< String, Scanner.Token > constantsMap =
new HashMap< String, Scanner.Token > ();
public OLParser( Scanner scanner )
{
super( scanner );
}
public Program parse()
throws IOException, ParserException
{
getToken();
Scanner.Token t;
do {
t = token;
parseInclude();
parseConstants();
parseInclude();
parseExecution();
parseInclude();
parseState();
parseInclude();
parseCorrelationSet();
parseInclude();
parsePortTypes();
parseInclude();
parsePorts();
parseInclude();
parseService();
parseInclude();
parseCode();
} while( t != token && t.isNot( Scanner.TokenType.EOF ) );
return program;
}
private void parseCorrelationSet()
throws IOException, ParserException
{
if ( token.is( Scanner.TokenType.CSET ) ) {
getToken();
eat( Scanner.TokenType.LCURLY, "expected {" );
program.addChild( new CorrelationSetInfo( parseIdListN( false ) ) );
eat( Scanner.TokenType.RCURLY, "expected }" );
}
}
private void parseExecution()
throws IOException, ParserException
{
if ( token.is( Scanner.TokenType.EXECUTION ) ) {
Constants.ExecutionMode mode = Constants.ExecutionMode.SEQUENTIAL;
getToken();
eat( Scanner.TokenType.LCURLY, "{ expected" );
if ( token.is( Scanner.TokenType.SEQUENTIAL ) ) {
mode = Constants.ExecutionMode.SEQUENTIAL;
} else if ( token.is( Scanner.TokenType.CONCURRENT ) ) {
mode = Constants.ExecutionMode.CONCURRENT;
} else if ( token.is( Scanner.TokenType.SINGLE ) ) {
mode = Constants.ExecutionMode.SINGLE;
} else
throwException( "Expected execution mode, found " + token.content() );
program.addChild( new ExecutionInfo( mode ) );
getToken();
eat( Scanner.TokenType.RCURLY, "} expected" );
}
}
private void parseState()
throws IOException, ParserException
{
if ( token.is( Scanner.TokenType.STATE ) ) {
Constants.StateMode mode = Constants.StateMode.PERSISTENT;
getToken();
eat( Scanner.TokenType.LCURLY, "{ expected" );
if ( token.is( Scanner.TokenType.PERSISTENT ) ) {
mode = Constants.StateMode.PERSISTENT;
} else if ( token.is( Scanner.TokenType.NOT_PERSISTENT ) ) {
mode = Constants.StateMode.NOT_PERSISTENT;
} else
throwException( "Expected state mode, found " + token.content() );
program.addChild( new StateInfo( mode ) );
getToken();
eat( Scanner.TokenType.RCURLY, "} expected" );
}
}
private void parseConstants()
throws IOException, ParserException
{
if ( token.is( Scanner.TokenType.CONSTANTS ) ) {
getToken();
eat( Scanner.TokenType.LCURLY, "expected {" );
boolean keepRun = true;
while( token.is( Scanner.TokenType.ID ) && keepRun ) {
String cId = token.content();
getToken();
eat( Scanner.TokenType.ASSIGN, "expected =" );
if ( token.isNot( Scanner.TokenType.STRING ) &&
token.isNot( Scanner.TokenType.INT ) &&
token.isNot( Scanner.TokenType.ID ) ) {
throwException( "expected string, integer or identifier constant" );
}
constantsMap.put( cId, token );
getToken();
if ( token.isNot( Scanner.TokenType.COMMA ) )
keepRun = false;
else
getToken();
}
eat( Scanner.TokenType.RCURLY, "expected }" );
}
}
private void parseInclude()
throws IOException, ParserException
{
if ( token.is( Scanner.TokenType.INCLUDE ) ) {
getToken();
Scanner oldScanner = scanner();
tokenAssert( Scanner.TokenType.STRING, "expected filename to include" );
setScanner( new Scanner( new FileInputStream( token.content() ), token.content() ) );
parse();
setScanner( oldScanner );
getToken();
}
}
private boolean checkConstant()
{
if ( token.is( Scanner.TokenType.ID ) ) {
Scanner.Token t = constantsMap.get( token.content() );
if ( t != null ) {
token = t;
return true;
}
}
return false;
}
private void parsePortTypes()
throws IOException, ParserException
{
while ( token.isKeyword( "inputPortType" ) ) {
getToken();
tokenAssert( Scanner.TokenType.ID, "expected input port type identifier" );
InputPortTypeInfo pt = new InputPortTypeInfo( token.content() );
getToken();
eat( Scanner.TokenType.LCURLY, "expected {" );
parseInputOperations( pt );
program.addChild( pt );
eat( Scanner.TokenType.RCURLY, "expected }" );
}
while ( token.isKeyword( "outputPortType" ) ) {
getToken();
tokenAssert( Scanner.TokenType.ID, "expected output port type identifier" );
OutputPortTypeInfo pt = new OutputPortTypeInfo( token.content() );
getToken();
if ( token.is( Scanner.TokenType.COLON ) ) {
getToken();
tokenAssert( Scanner.TokenType.STRING, "expected port type namespace" );
pt.setNamespace( token.content() );
getToken();
}
eat( Scanner.TokenType.LCURLY, "expected {" );
parseOutputOperations( pt );
program.addChild( pt );
eat( Scanner.TokenType.RCURLY, "expected }" );
}
}
private void parsePorts()
throws IOException, ParserException
{
if ( token.isKeyword( "ports" ) ) {
getToken();
eat( Scanner.TokenType.LCURLY, "expected {" );
Constants.ProtocolId protocolId;
String portTypeId, portId;
while( token.is( Scanner.TokenType.ID ) ) {
portTypeId = token.content();
getToken();
tokenAssert( Scanner.TokenType.COLON, ": expected" );
do {
getToken();
tokenAssert( Scanner.TokenType.ID, "port id expected" );
portId = token.content();
getToken();
eat( Scanner.TokenType.LSQUARE, "expected [" );
tokenAssert( Scanner.TokenType.ID, "port protocol expected" );
protocolId = Constants.stringToProtocolId( token.content() );
if ( protocolId == Constants.ProtocolId.UNSUPPORTED )
throwException( "unknown protocol specified in port binding" );
getToken();
eat( Scanner.TokenType.RSQUARE, "expected ]" );
program.addChild( new PortInfo( portId, portTypeId, protocolId ) );
} while( token.is( Scanner.TokenType.COMMA ) );
}
eat( Scanner.TokenType.RCURLY, "expected }" );
}
}
private void parseService()
throws IOException, ParserException
{
if ( token.isKeyword( "service" ) ) {
getToken();
eat( Scanner.TokenType.LCURLY, "{ expected" );
while( token.is( Scanner.TokenType.STRING ) )
parseServiceElement();
eat( Scanner.TokenType.RCURLY, "} expected" );
}
}
private void parseServiceElement()
throws IOException, ParserException
{
URI serviceUri = null;
try {
serviceUri = new URI( token.content() );
} catch( URISyntaxException e ) {
throwException( e );
}
getToken();
eat( Scanner.TokenType.COLON, ": expected" );
Collection< String > ports = parseIdListN( false );
if ( ports.size() < 1 )
throwException( "expected at least one port identifier" );
program.addChild( new ServiceInfo( serviceUri, ports ) );
}
private void parseInputOperations( InputPortTypeInfo pt )
throws IOException, ParserException
{
boolean keepRun = true;
while( keepRun ) {
if ( token.is( Scanner.TokenType.OP_OW ) )
parseOneWayOperations( pt );
else if ( token.is( Scanner.TokenType.OP_RR ) )
parseRequestResponseOperations( pt );
else
keepRun = false;
}
}
private void parseOutputOperations( OutputPortTypeInfo pt )
throws IOException, ParserException
{
boolean keepRun = true;
while( keepRun ) {
if ( token.is( Scanner.TokenType.OP_N ) )
parseNotificationOperations( pt );
else if ( token.is( Scanner.TokenType.OP_SR ) )
parseSolicitResponseOperations( pt );
else
keepRun = false;
}
}
/*private void parseLocations()
throws IOException, ParserException
{
Vector< LocationDefinition > locationDecls = program.locationDeclarations();
// The locations block is optional
if ( token.is( Scanner.TokenType.LOCATIONS ) ) {
getToken();
eat( Scanner.TokenType.LCURLY, "expected {" );
boolean keepRun = true;
String locId;
while( token.isNot( Scanner.TokenType.RCURLY ) && keepRun ) {
tokenAssert( Scanner.TokenType.ID, "expected location identifier" );
locId = token.content();
getToken();
eat( Scanner.TokenType.ASSIGN, "expected =" );
if ( !checkConstant() && token.isNot( Scanner.TokenType.STRING ) )
throwException( "expected string or string constant" );
try {
locationDecls.add(
new LocationDefinition( locId, new URI( token.content() ) )
);
} catch( URISyntaxException e ) {
throwException( "Invalid URI specified for location " + locId );
}
getToken();
if ( token.isNot( Scanner.TokenType.COMMA ) )
keepRun = false;
else
getToken();
}
eat( Scanner.TokenType.RCURLY, "expected }" );
}
//return locationDecls;
}*/
private void parseOneWayOperations( InputPortTypeInfo pt )
throws IOException, ParserException
{
getToken();
eat( Scanner.TokenType.COLON, "expected :" );
boolean keepRun = true;
while( keepRun ) {
checkConstant();
if ( token.is( Scanner.TokenType.ID ) ) {
pt.addOperation( new OneWayOperationDeclaration( token.content() ) );
getToken();
if ( token.is( Scanner.TokenType.COMMA ) )
getToken();
else
keepRun = false;
} else
keepRun = false;
}
}
private void parseRequestResponseOperations( InputPortTypeInfo pt )
throws IOException, ParserException
{
getToken();
eat( Scanner.TokenType.COLON, "expected :" );
boolean keepRun = true;
String opId;
//Collection< Constants.VariableType > inVarTypes, outVarTypes;
while( keepRun ) {
checkConstant();
if ( token.is( Scanner.TokenType.ID ) ) {
opId = token.content();
getToken();
/*inVarTypes = parseVarTypes();
outVarTypes = parseVarTypes();*/
Vector< String > faultNames = new Vector< String >();
if ( token.is( Scanner.TokenType.LSQUARE ) ) { // fault names declaration
getToken();
while( token.is( Scanner.TokenType.ID ) ) {
faultNames.add( token.content() );
getToken();
if ( token.isNot( Scanner.TokenType.COMMA ) )
break;
else getToken();
}
eat( Scanner.TokenType.RSQUARE, "expected ]" );
}
pt.addOperation(
new RequestResponseOperationDeclaration( opId, faultNames )
);
//getToken();
if ( token.is( Scanner.TokenType.COMMA ) )
getToken();
else
keepRun = false;
} else
keepRun = false;
}
}
private void parseNotificationOperations( OutputPortTypeInfo pt )
throws IOException, ParserException
{
getToken();
eat( Scanner.TokenType.COLON, "expected :" );
boolean keepRun = true;
//String opId;
//Collection< VariableType > outVarTypes;
while( keepRun ) {
checkConstant();
if ( token.is( Scanner.TokenType.ID ) ) {
/*opId = token.content();
getToken();*/
//outVarTypes = parseVarTypes();
/*eat( Scanner.TokenType.ASSIGN, "= expected" );
tokenAssert( Scanner.TokenType.ID, "bound input operation name expected" );*/
pt.addOperation(
new NotificationOperationDeclaration( token.content() )
);
getToken();
if ( token.is( Scanner.TokenType.COMMA ) )
getToken();
else
keepRun = false;
} else
keepRun = false;
}
}
private void parseSolicitResponseOperations( OutputPortTypeInfo pt )
throws IOException, ParserException
{
getToken();
eat( Scanner.TokenType.COLON, "expected :" );
boolean keepRun = true;
//String opId;
//Collection< VariableType > outVarTypes, inVarTypes;
while( keepRun ) {
checkConstant();
if ( token.is( Scanner.TokenType.ID ) ) {
//opId = token.content();
//getToken();
/*outVarTypes = parseVarTypes();
inVarTypes = parseVarTypes();*/
/*eat( Scanner.TokenType.ASSIGN, "= expected" );
tokenAssert( Scanner.TokenType.ID, "bound input operation name expected" );*/
pt.addOperation(
new SolicitResponseOperationDeclaration( token.content() )
);
getToken();
if ( token.is( Scanner.TokenType.COMMA ) )
getToken();
else
keepRun = false;
} else
keepRun = false;
}
}
/*private Collection< Constants.VariableType > parseVarTypes()
throws IOException, ParserException
{
eat( Scanner.TokenType.LPAREN, "expected (" );
Vector< VariableType > varTypes = new Vector< VariableType > ();
boolean keepRun = true;
while( keepRun ) {
if ( token.is( Scanner.TokenType.RPAREN ) )
keepRun = false;
else {
if ( token.is( Scanner.TokenType.VAR_TYPE_INT ) )
varTypes.add( Constants.VariableType.INT );
else if ( token.is( Scanner.TokenType.VAR_TYPE_STRING ) )
varTypes.add( Constants.VariableType.STRING );
else if ( token.is( Scanner.TokenType.VAR_TYPE_VARIANT ) )
varTypes.add( Constants.VariableType.VARIANT );
else
throwException( "expected variable type" );
getToken();
if ( token.is( Scanner.TokenType.COMMA ) )
getToken();
else
keepRun = false;
}
}
eat( Scanner.TokenType.RPAREN, "expected )" );
return varTypes;
}*/
/*public void parseLinks()
throws IOException, ParserException
{
Vector< InternalLinkDeclaration > linkDecls = program.linkDeclarations();
// The links block is optional
if ( token.is( Scanner.TokenType.LINKS ) ) {
getToken();
eat( Scanner.TokenType.LCURLY, "expected {" );
boolean keepRun = true;
while( token.isNot( Scanner.TokenType.RCURLY ) && keepRun ) {
tokenAssert( Scanner.TokenType.ID, "expected link identifier" );
linkDecls.add( new InternalLinkDeclaration( token.content() ) );
getToken();
if ( token.is( Scanner.TokenType.COMMA ) )
getToken();
else
keepRun = false;
}
eat( Scanner.TokenType.RCURLY, "} expected" );
}
}*/
/*public Collection< VariableDeclaration > parseVariables()
throws IOException, ParserException
{
Vector< VariableDeclaration > varDecls = new Vector< VariableDeclaration >();
// The links block is optional
if ( token.is( Scanner.TokenType.VARIABLES ) ) {
getToken();
eat( Scanner.TokenType.LCURLY, "expected {" );
boolean keepRun = true;
while( token.isNot( Scanner.TokenType.RCURLY ) && keepRun ) {
tokenAssert( Scanner.TokenType.ID, "expected variable identifier" );
varDecls.add( new VariableDeclaration( token.content() ) );
getToken();
if ( token.is( Scanner.TokenType.COMMA ) )
getToken();
else
keepRun = false;
}
eat( Scanner.TokenType.RCURLY, "} expected" );
}
return varDecls;
}*/
private void parseCode()
throws IOException, ParserException
{
boolean mainDefined = false;
boolean keepRun = true;
do {
if ( token.is( Scanner.TokenType.DEFINE ) )
program.addChild( parseProcedure() );
else if ( token.is( Scanner.TokenType.MAIN ) ) {
if ( mainDefined )
throwException( "you must specify only one main definition" );
program.addChild( parseMain() );
mainDefined = true;
} else
keepRun = false;
} while( keepRun );
}
private Procedure parseMain()
throws IOException, ParserException
{
getToken();
eat( Scanner.TokenType.LCURLY, "expected { after procedure identifier" );
Procedure retVal = new Procedure( "main", parseProcess() );
eat( Scanner.TokenType.RCURLY, "expected } after procedure definition" );
return retVal;
}
private Procedure parseProcedure()
throws IOException, ParserException
{
getToken();
tokenAssert( Scanner.TokenType.ID, "expected procedure identifier" );
String procedureId = token.content();
getToken();
eat( Scanner.TokenType.LCURLY, "expected { after procedure identifier" );
Procedure retVal = new Procedure( procedureId, parseProcess() );
eat( Scanner.TokenType.RCURLY, "expected } after procedure definition" );
return retVal;
}
private OLSyntaxNode parseProcess()
throws IOException, ParserException
{
if( token.is( Scanner.TokenType.LSQUARE ) )
return parseNDChoiceStatement();
return parseParallelStatement();
}
private ParallelStatement parseParallelStatement()
throws IOException, ParserException
{
ParallelStatement stm = new ParallelStatement();
stm.addChild( parseSequenceStatement() );
while( token.is( Scanner.TokenType.PARALLEL ) ) {
getToken();
stm.addChild( parseSequenceStatement() );
}
return stm;
}
private SequenceStatement parseSequenceStatement()
throws IOException, ParserException
{
SequenceStatement stm = new SequenceStatement();
stm.addChild( parseBasicStatement() );
while( token.is( Scanner.TokenType.SEQUENCE ) ) {
getToken();
stm.addChild( parseBasicStatement() );
}
return stm;
}
private OLSyntaxNode parseBasicStatement()
throws IOException, ParserException
{
OLSyntaxNode retVal = null;
if ( token.is( Scanner.TokenType.ID ) ) {
checkConstant();
String id = token.content();
getToken();
if ( token.is( Scanner.TokenType.COLON )
|| token.is( Scanner.TokenType.LSQUARE )
|| token.is( Scanner.TokenType.DOT )
|| token.is( Scanner.TokenType.ASSIGN )
|| token.is( Scanner.TokenType.POINTS_TO )
|| token.is( Scanner.TokenType.DEEP_COPY_LEFT ) ) {
retVal = parseAssignOrDeepCopyOrPointerStatement( id );
} else if ( token.is( Scanner.TokenType.LPAREN ) ) {
retVal = parseInputOperationStatement( id );
} else if ( token.is( Scanner.TokenType.AT ) ) {
getToken();
retVal = parseOutputOperationStatement( id );
} else
retVal = new ProcedureCallStatement( id );
/*} else if ( token.is( Scanner.TokenType.UNDEF ) ) {
getToken();
checkConstant();
tokenAssert( Scanner.TokenType.ID, "expected variable identifier" );
String id = token.content();
getToken();
retVal = new UndefStatement( parseVariablePath( id ) );*/
} else if ( token.is( Scanner.TokenType.OUT ) ) { // out( <Expression> )
getToken();
eat( Scanner.TokenType.LPAREN, "expected (" );
retVal = new OutStatement( parseExpression() );
eat( Scanner.TokenType.RPAREN, "expected )" );
} else if ( token.is( Scanner.TokenType.IN ) ) // in( <id> )
retVal = parseInStatement();
else if ( token.is( Scanner.TokenType.LINKIN ) )
retVal = parseLinkInStatement();
else if ( token.is( Scanner.TokenType.NULL_PROCESS ) ) {
getToken();
retVal = NullProcessStatement.getInstance();
} else if ( token.is( Scanner.TokenType.EXIT ) ) {
getToken();
retVal = ExitStatement.getInstance();
} else if ( token.is( Scanner.TokenType.WHILE ) )
retVal = parseWhileStatement();
else if ( token.is( Scanner.TokenType.SLEEP ) )
retVal = parseSleepStatement();
else if ( token.is( Scanner.TokenType.LINKOUT ) ) {
getToken();
eat( Scanner.TokenType.LPAREN, "expected (" );
tokenAssert( Scanner.TokenType.ID, "expected link identifier" );
retVal = new LinkOutStatement( token.content() );
getToken();
eat( Scanner.TokenType.RPAREN, "expected )" );
} else if ( token.is( Scanner.TokenType.LPAREN ) ) {
getToken();
retVal = parseProcess();
eat( Scanner.TokenType.RPAREN, "expected )" );
} else if ( token.is( Scanner.TokenType.SCOPE ) ) {
getToken();
eat( Scanner.TokenType.LPAREN, "expected (" );
checkConstant();
tokenAssert( Scanner.TokenType.ID, "expected scope identifier" );
String id = token.content();
getToken();
eat( Scanner.TokenType.RPAREN, "expected )" );
eat( Scanner.TokenType.LCURLY, "expected {" );
retVal = new Scope( id, parseProcess() );
eat( Scanner.TokenType.RCURLY, "expected }" );
} else if ( token.is( Scanner.TokenType.COMPENSATE ) ) {
getToken();
eat( Scanner.TokenType.LPAREN, "expected (" );
checkConstant();
tokenAssert( Scanner.TokenType.ID, "expected scope identifier" );
retVal = new CompensateStatement( token.content() );
getToken();
eat( Scanner.TokenType.RPAREN, "expected )" );
} else if ( token.is( Scanner.TokenType.THROW ) ) {
getToken();
eat( Scanner.TokenType.LPAREN, "expected (" );
checkConstant();
tokenAssert( Scanner.TokenType.ID, "expected fault identifier" );
retVal = new ThrowStatement( token.content() );
getToken();
eat( Scanner.TokenType.RPAREN, "expected )" );
} else if ( token.is( Scanner.TokenType.INSTALL_COMPENSATION ) ) {
getToken();
eat( Scanner.TokenType.LPAREN, "expected (" );
retVal = new InstallCompensationStatement( parseProcess() );
eat( Scanner.TokenType.RPAREN, "expected )" );
} else if ( token.is( Scanner.TokenType.INSTALL_FAULT_HANDLER ) ) {
getToken();
eat( Scanner.TokenType.LPAREN, "expected (" );
tokenAssert( Scanner.TokenType.ID, "expected fault identifier" );
String id = token.content();
getToken();
eat( Scanner.TokenType.COMMA, "expected ," );
retVal = new InstallFaultHandlerStatement( id, parseProcess() );
eat( Scanner.TokenType.RPAREN, "expected )" );
} else if ( token.is( Scanner.TokenType.IF ) ) {
IfStatement stm = new IfStatement();
OLSyntaxNode cond;
OLSyntaxNode node;
getToken();
eat( Scanner.TokenType.LPAREN, "expected (" );
cond = parseCondition();
eat( Scanner.TokenType.RPAREN, "expected )" );
eat( Scanner.TokenType.LCURLY, "expected {" );
node = parseProcess();
eat( Scanner.TokenType.RCURLY, "expected }" );
stm.addChild(
new Pair< OLSyntaxNode, OLSyntaxNode >( cond, node )
);
boolean keepRun = true;
while( token.is( Scanner.TokenType.ELSE ) && keepRun ) {
getToken();
if ( token.is( Scanner.TokenType.IF ) ) { // else if branch
getToken();
eat( Scanner.TokenType.LPAREN, "expected (" );
cond = parseCondition();
eat( Scanner.TokenType.RPAREN, "expected )" );
eat( Scanner.TokenType.LCURLY, "expected {" );
node = parseProcess();
eat( Scanner.TokenType.RCURLY, "expected }" );
stm.addChild(
new Pair< OLSyntaxNode, OLSyntaxNode >( cond, node )
);
} else if ( token.is( Scanner.TokenType.LCURLY ) ) { // else branch
keepRun = false;
eat( Scanner.TokenType.LCURLY, "expected {" );
stm.setElseProcess( parseProcess() );
eat( Scanner.TokenType.RCURLY, "expected }" );
} else
throwException( "expected else or else if branch" );
}
retVal = stm;
}
if ( retVal == null )
throwException( "expected basic statement" );
return retVal;
}
private OLSyntaxNode parseAssignOrDeepCopyOrPointerStatement( String varName )
throws IOException, ParserException
{
OLSyntaxNode retVal = null;
VariablePath path = parseVariablePath( varName );
if ( token.is( Scanner.TokenType.ASSIGN ) ) {
getToken();
retVal = new AssignStatement( path, parseExpression() );
} else if ( token.is( Scanner.TokenType.POINTS_TO ) ) {
getToken();
tokenAssert( Scanner.TokenType.ID, "expected variable identifier" );
String id = token.content();
getToken();
retVal = new PointerStatement( path, parseVariablePath( id ) );
} else if ( token.is( Scanner.TokenType.DEEP_COPY_LEFT ) ) {
getToken();
tokenAssert( Scanner.TokenType.ID, "expected variable identifier" );
String id = token.content();
getToken();
retVal = new DeepCopyStatement( path, parseVariablePath( id ) );
} else
throwException( "expected = or -> or <<" );
return retVal;
}
private VariablePath parseVariablePath( String varId )
throws IOException, ParserException
{
OLSyntaxNode expr = null;
if ( token.is( Scanner.TokenType.LSQUARE ) ) {
getToken();
expr = parseExpression();
eat( Scanner.TokenType.RSQUARE, "expected ]" );
}
VariablePath path = new VariablePath( varId, expr );
String node;
while( token.is( Scanner.TokenType.DOT ) ) {
getToken();
tokenAssert( Scanner.TokenType.ID, "expected nested node identifier" );
node = token.content();
getToken();
if ( token.is( Scanner.TokenType.LSQUARE ) ) {
getToken();
expr = parseExpression();
eat( Scanner.TokenType.RSQUARE, "expected ]" );
} else {
expr = null;
}
path.append( new Pair< String, OLSyntaxNode >( node, expr ) );
}
if ( token.is( Scanner.TokenType.COLON ) ) {
getToken();
path.setAttribute( parseExpression() );
}
return path;
}
private InStatement parseInStatement()
throws IOException, ParserException
{
getToken();
eat( Scanner.TokenType.LPAREN, "expected (" );
tokenAssert( Scanner.TokenType.ID, "expected variable identifier" );
String varId = token.content();
getToken();
InStatement stm = new InStatement( parseVariablePath( varId ) );
eat( Scanner.TokenType.RPAREN, "expected )" );
return stm;
}
private NDChoiceStatement parseNDChoiceStatement()
throws IOException, ParserException
{
NDChoiceStatement stm = new NDChoiceStatement();
OLSyntaxNode inputGuard = null;
OLSyntaxNode process;
boolean keepRun = true;
while( keepRun ) {
getToken(); // Eat [
if ( token.is( Scanner.TokenType.LINKIN ) )
inputGuard = parseLinkInStatement();
else if ( token.is( Scanner.TokenType.SLEEP ) )
inputGuard = parseSleepStatement();
else if ( token.is( Scanner.TokenType.LINKIN ) )
inputGuard = parseInStatement();
else if ( token.is( Scanner.TokenType.ID ) ) {
String id = token.content();
getToken();
inputGuard = parseInputOperationStatement( id );
} else
throwException( "expected input guard" );
eat( Scanner.TokenType.RSQUARE, "] expected" );
process = parseProcess();
stm.addChild( new Pair< OLSyntaxNode, OLSyntaxNode >( inputGuard, process ) );
if ( token.is( Scanner.TokenType.CHOICE ) ) {
getToken();
tokenAssert( Scanner.TokenType.LSQUARE, "expected [" );
} else
keepRun = false;
}
return stm;
}
private SleepStatement parseSleepStatement()
throws IOException, ParserException
{
getToken();
eat( Scanner.TokenType.LPAREN, "expected (" );
SleepStatement stm = new SleepStatement( parseExpression() );
eat( Scanner.TokenType.RPAREN, "expected )" );
return stm;
}
private LinkInStatement parseLinkInStatement()
throws IOException, ParserException
{
getToken();
eat( Scanner.TokenType.LPAREN, "expected (" );
tokenAssert( Scanner.TokenType.ID, "expected link identifier" );
LinkInStatement stm = new LinkInStatement( token.content() );
getToken();
eat( Scanner.TokenType.RPAREN, "expected )" );
return stm;
}
private OLSyntaxNode parseInputOperationStatement( String id )
throws IOException, ParserException
{
VariablePath inputVarPath = parseOperationStatementParameter();
OLSyntaxNode stm;
if ( token.is( Scanner.TokenType.LPAREN ) ) { // Request Response operation
VariablePath outputVarPath = parseOperationStatementParameter();
OLSyntaxNode process;
eat( Scanner.TokenType.LCURLY, "expected {" );
process = parseProcess();
eat( Scanner.TokenType.RCURLY, "expected }" );
stm = new RequestResponseOperationStatement(
id, inputVarPath, outputVarPath, process
);
} else // One Way operation
stm = new OneWayOperationStatement( id, inputVarPath );
return stm;
}
/**
* @return The VariablePath parameter of the statement. May be null.
* @throws IOException
* @throws ParserException
*/
private VariablePath parseOperationStatementParameter()
throws IOException, ParserException
{
VariablePath ret = null;
eat( Scanner.TokenType.LPAREN, "expected )" );
if ( token.is( Scanner.TokenType.ID ) ) {
String varId = token.content();
getToken();
ret = parseVariablePath( varId );
}
eat( Scanner.TokenType.RPAREN, "expected )" );
return ret;
}
private OLSyntaxNode parseOutputOperationStatement( String id )
throws IOException, ParserException
{
OLSyntaxNode locExpr = parseExpression();
VariablePath outputVarPath = parseOperationStatementParameter();
OLSyntaxNode stm;
if ( token.is( Scanner.TokenType.LPAREN ) ) { // Solicit Response operation
stm = new SolicitResponseOperationStatement(
id,
locExpr,
outputVarPath,
parseOperationStatementParameter() );
} else // Notification operation
stm = new NotificationOperationStatement( id, locExpr, outputVarPath );
return stm;
}
private OLSyntaxNode parseWhileStatement()
throws IOException, ParserException
{
OLSyntaxNode cond, process;
getToken();
eat( Scanner.TokenType.LPAREN, "expected (" );
cond = parseCondition();
eat( Scanner.TokenType.RPAREN, "expected )" );
eat( Scanner.TokenType.LCURLY, "expected {" );
process = parseProcess();
eat( Scanner.TokenType.RCURLY, "expected }" );
return new WhileStatement( cond, process );
}
private OLSyntaxNode parseCondition()
throws IOException, ParserException
{
OrConditionNode orCond = new OrConditionNode();
orCond.addChild( parseAndCondition() );
while( token.is( Scanner.TokenType.OR ) ) {
getToken();
orCond.addChild( parseAndCondition() );
}
return orCond;
}
private OLSyntaxNode parseAndCondition()
throws IOException, ParserException
{
AndConditionNode andCond = new AndConditionNode();
andCond.addChild( parseBasicCondition() );
while( token.is( Scanner.TokenType.AND ) ) {
getToken();
andCond.addChild( parseBasicCondition() );
}
return andCond;
}
private OLSyntaxNode parseBasicCondition()
throws IOException, ParserException
{
OLSyntaxNode retVal = null;
if ( token.is( Scanner.TokenType.LPAREN ) ) {
getToken();
retVal = parseCondition();
eat( Scanner.TokenType.RPAREN, "expected )" );
} else if ( token.is( Scanner.TokenType.NOT ) ) {
getToken();
eat( Scanner.TokenType.LPAREN, "expected (" );
retVal = new NotConditionNode( parseCondition() );
eat( Scanner.TokenType.RPAREN, "expected )" );
} else {
Scanner.TokenType opType;
OLSyntaxNode expr1;
expr1 = parseExpression();
opType = token.type();
if ( opType != Scanner.TokenType.EQUAL && opType != Scanner.TokenType.LANGLE &&
opType != Scanner.TokenType.RANGLE && opType != Scanner.TokenType.MAJOR_OR_EQUAL &&
opType != Scanner.TokenType.MINOR_OR_EQUAL && opType != Scanner.TokenType.NOT_EQUAL ) {
retVal = new ExpressionConditionNode( expr1 );
} else {
OLSyntaxNode expr2;
getToken();
expr2 = parseExpression();
retVal = new CompareConditionNode( expr1, expr2, opType );
}
}
if ( retVal == null )
throwException( "expected condition" );
return retVal;
}
/**
* @todo Check if negative integer handling is appropriate
*/
private OLSyntaxNode parseExpression()
throws IOException, ParserException
{
boolean keepRun = true;
SumExpressionNode sum = new SumExpressionNode();
sum.add( parseProductExpression() );
while( keepRun ) {
if ( token.is( Scanner.TokenType.PLUS ) ) {
getToken();
sum.add( parseProductExpression() );
} else if ( token.is( Scanner.TokenType.MINUS ) ) {
getToken();
sum.subtract( parseProductExpression() );
} else if ( token.is( Scanner.TokenType.INT ) ) { // e.g. i -1
int value = Integer.parseInt( token.content() );
// We add it, because it's already negative.
if ( value < 0 )
sum.add( parseProductExpression() );
else // e.g. i 1
throwException( "expected expression operator" );
} else
keepRun = false;
}
return sum;
}
private OLSyntaxNode parseFactor()
throws IOException, ParserException
{
OLSyntaxNode retVal = null;
checkConstant();
if ( token.is( Scanner.TokenType.ID ) ) {
String varId = token.content();
getToken();
retVal = new VariableExpressionNode( parseVariablePath( varId ) );
} else if ( token.is( Scanner.TokenType.STRING ) ) {
retVal = new ConstantStringExpression( token.content() );
getToken();
} else if ( token.is( Scanner.TokenType.INT ) ) {
retVal = new ConstantIntegerExpression( Integer.parseInt( token.content() ) );
getToken();
} else if ( token.is( Scanner.TokenType.LPAREN ) ) {
getToken();
retVal = parseExpression();
eat( Scanner.TokenType.RPAREN, "expected )" );
}/* else if ( token.is( Scanner.TokenType.HASH ) ) {
getToken();
tokenAssert( Scanner.TokenType.ID, "expected variable identifier" );
String id = token.content();
getToken();
retVal = VariableSizeExpressionNode( parseVariablePath( id ) );
}*/
if ( retVal == null )
throwException( "expected expression" );
return retVal;
}
private OLSyntaxNode parseProductExpression()
throws IOException, ParserException
{
ProductExpressionNode product = new ProductExpressionNode();
product.multiply( parseFactor() );
boolean keepRun = true;
while( keepRun ) {
if ( token.is( Scanner.TokenType.ASTERISK ) ) {
getToken();
product.multiply( parseFactor() );
} else if ( token.is( Scanner.TokenType.DIVIDE ) ) {
getToken();
product.divide( parseFactor() );
} else
keepRun = false;
}
return product;
}
}
|
package org.cytoscape.ding.internal.charts.util;
import java.awt.Color;
import java.awt.Paint;
import org.cytoscape.ding.internal.util.MathUtil;
import org.jfree.chart.renderer.PaintScale;
public class ColorScale implements PaintScale {
private final double lowerBound;
private final double upperBound;
private final Color lowerColor;
private final Color zeroColor;
private final Color upperColor;
private final Color nanColor;
private static double EPSILON = 1e-30;
public ColorScale(final double lowerBound,
final double upperBound,
final Color lowerColor,
final Color zeroColor,
final Color upperColor,
final Color nanColor) {
this.lowerBound = lowerBound;
this.upperBound = upperBound;
this.lowerColor = lowerColor;
this.zeroColor = zeroColor;
this.upperColor = upperColor;
this.nanColor = nanColor;
}
@Override
public double getLowerBound() {
return lowerBound;
}
@Override
public double getUpperBound() {
return upperBound;
}
public Color getLowerColor() {
return lowerColor;
}
public Color getZeroColor() {
return zeroColor;
}
public Color getUpperColor() {
return upperColor;
}
public Color getNanColor() {
return nanColor;
}
@Override
public Paint getPaint(double value) {
if (Double.isNaN(value))
return nanColor;
return getPaint(value, lowerBound, upperBound, lowerColor, zeroColor, upperColor);
}
public static Paint getPaint(final double value,
final double lowerBound,
final double upperBound,
final Color lowerColor,
final Color zeroColor,
final Color upperColor) {
final boolean hasZero = lowerBound < -EPSILON && upperBound > EPSILON && zeroColor != null;
if (hasZero && value < EPSILON && value > -EPSILON)
return zeroColor;
final Color color = value < 0.0 ? lowerColor : upperColor;
// Linearly interpolate the value
final double f = value < 0.0 ?
MathUtil.invLinearInterp(value, lowerBound, 0) : MathUtil.invLinearInterp(value, 0, upperBound);
float t = (float) (value < 0.0 ? MathUtil.linearInterp(f, 0.0, 1.0) : MathUtil.linearInterp(f, 1.0, 0.0));
// Make sure it's between 0.0-1.0
t = Math.max(0.0f, t);
t = Math.min(1.0f, t);
return org.jdesktop.swingx.color.ColorUtil.interpolate(zeroColor, color, t);
}
}
|
package com.ecyrd.jspwiki;
import java.util.Collection;
import java.util.Properties;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
public class PageRenamerTest extends TestCase
{
TestEngine m_engine;
protected void setUp() throws Exception
{
super.setUp();
Properties props = new Properties();
props.load( TestEngine.findTestProperties() );
props.setProperty( WikiEngine.PROP_MATCHPLURALS, "true" );
TestEngine.emptyWorkDir();
m_engine = new TestEngine(props);
}
protected void tearDown() throws Exception
{
super.tearDown();
TestEngine.deleteTestPage("TestPage");
TestEngine.deleteTestPage("TestPage2");
TestEngine.deleteTestPage("FooTest");
TestEngine.deleteTestPage("Test");
TestEngine.emptyWorkDir();
}
public void testSimpleRename()
throws Exception
{
m_engine.saveText("TestPage", "the big lazy dog thing" );
WikiPage p = m_engine.getPage("TestPage");
WikiContext context = new WikiContext(m_engine, p);
m_engine.renamePage(context, "TestPage", "FooTest", false);
WikiPage newpage = m_engine.getPage("FooTest");
assertNotNull( "no new page", newpage );
assertNull( "old page not gone", m_engine.getPage("TestPage") );
// Refmgr
Collection refs = m_engine.getReferenceManager().findCreated();
assertEquals( "wrong list size", 1, refs.size() );
assertEquals( "wrong item", "FooTest", (String)refs.iterator().next() );
}
public void testReferrerChange()
throws Exception
{
m_engine.saveText("TestPage", "foofoo" );
m_engine.saveText("TestPage2", "[TestPage]");
WikiPage p = m_engine.getPage("TestPage");
WikiContext context = new WikiContext(m_engine, p);
m_engine.renamePage(context, "TestPage", "FooTest", true);
String data = m_engine.getPureText("TestPage2", WikiProvider.LATEST_VERSION);
assertEquals( "no rename", "[FooTest]", data.trim() );
Collection refs = m_engine.getReferenceManager().findReferrers("TestPage");
assertNull( "oldpage", refs );
refs = m_engine.getReferenceManager().findReferrers( "FooTest" );
assertEquals( "new size", 1, refs.size() );
assertEquals( "wrong ref", "TestPage2", (String)refs.iterator().next() );
}
public void testReferrerChangeCC()
throws Exception
{
m_engine.saveText("TestPage", "foofoo" );
m_engine.saveText("TestPage2", "TestPage");
WikiPage p = m_engine.getPage("TestPage");
WikiContext context = new WikiContext(m_engine, p);
m_engine.renamePage(context, "TestPage", "FooTest", true);
String data = m_engine.getPureText("TestPage2", WikiProvider.LATEST_VERSION);
assertEquals( "no rename", "FooTest", data.trim() );
Collection refs = m_engine.getReferenceManager().findReferrers("TestPage");
assertNull( "oldpage", refs );
refs = m_engine.getReferenceManager().findReferrers( "FooTest" );
assertEquals( "new size", 1, refs.size() );
assertEquals( "wrong ref", "TestPage2", (String)refs.iterator().next() );
}
public void testReferrerChangeAnchor()
throws Exception
{
m_engine.saveText("TestPage", "foofoo" );
m_engine.saveText("TestPage2", "[TestPage#heading1]");
WikiPage p = m_engine.getPage("TestPage");
WikiContext context = new WikiContext(m_engine, p);
m_engine.renamePage(context, "TestPage", "FooTest", true);
String data = m_engine.getPureText("TestPage2", WikiProvider.LATEST_VERSION);
assertEquals( "no rename", "[FooTest#heading1]", data.trim() );
Collection refs = m_engine.getReferenceManager().findReferrers("TestPage");
assertNull( "oldpage", refs );
refs = m_engine.getReferenceManager().findReferrers( "FooTest" );
assertEquals( "new size", 1, refs.size() );
assertEquals( "wrong ref", "TestPage2", (String)refs.iterator().next() );
}
public void testReferrerChangeMultilink()
throws Exception
{
m_engine.saveText("TestPage", "foofoo" );
m_engine.saveText("TestPage2", "[TestPage] [TestPage] [linktext|TestPage] TestPage [linktext|TestPage] [TestPage#Anchor] [TestPage] TestPage [TestPage]");
WikiPage p = m_engine.getPage("TestPage");
WikiContext context = new WikiContext(m_engine, p);
m_engine.renamePage(context, "TestPage", "FooTest", true);
String data = m_engine.getPureText("TestPage2", WikiProvider.LATEST_VERSION);
assertEquals( "no rename",
"[FooTest] [FooTest] [linktext|FooTest] FooTest [linktext|FooTest] [FooTest#Anchor] [FooTest] FooTest [FooTest]",
data.trim() );
Collection refs = m_engine.getReferenceManager().findReferrers("TestPage");
assertNull( "oldpage", refs );
refs = m_engine.getReferenceManager().findReferrers( "FooTest" );
assertEquals( "new size", 1, refs.size() );
assertEquals( "wrong ref", "TestPage2", (String)refs.iterator().next() );
}
public void testReferrerNoWikiName()
throws Exception
{
m_engine.saveText("Test","foo");
m_engine.saveText("TestPage2", "[Test] [Test#anchor] test Test [test] [link|test] [link|test]");
WikiPage p = m_engine.getPage("TestPage");
WikiContext context = new WikiContext(m_engine, p);
m_engine.renamePage(context, "Test", "TestPage", true);
String data = m_engine.getPureText("TestPage2", WikiProvider.LATEST_VERSION );
assertEquals( "wrong data", "[TestPage] [TestPage#anchor] test Test [TestPage] [link|TestPage] [link|TestPage]", data.trim() );
}
public static Test suite()
{
return new TestSuite( PageRenamerTest.class );
}
}
|
package com.iosstyle;
import java.nio.charset.Charset;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.ImageSpan;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.EditText;
public class EmojiEditText extends EditText {
private static final String TAG = EmojiEditText.class.getName();
private static final String START_CHAR = "[";
private static final String END_CHAR = "]";
private InputFilter filter;
public EmojiEditText(Context context) {
super(context);
init();
}
public EmojiEditText(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public EmojiEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init() {
filter = new InputFilter() {
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
if (TextUtils.isEmpty(source))
return null;
byte[] bytes = source.toString().getBytes();
String hexStr = convert(bytes);
try {
Resources resources = getContext().getResources();
int id = resources.getIdentifier("emoji_" + hexStr,
"drawable", getContext().getPackageName());
if (id != 0) {
return START_CHAR + hexStr + END_CHAR;
}
} catch (Exception e) {
return null;
}
return null;
}
};
this.setFilters(new InputFilter[] { filter });
this.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i,
int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1,
int i2) {
}
@Override
public void afterTextChanged(Editable editable) {
emotifySpannable(editable);
String rawContent = editable.toString();
SpannableString spannable = new SpannableString(rawContent);
emotifySpannable(spannable);
}
});
}
public static String convert(byte[] bytes) {
try {
String str = new String(bytes, Charset.forName("UTF-8"));
int[] result = toCodePointArray(str);
for (int i = 0; i < result.length; i++) {
String hex_result = Integer.toHexString(result[i]);
}
int codePoint = str.codePointAt(0);
String hex_result = Integer.toHexString(codePoint);
return hex_result;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static int[] toCodePointArray(String str) {
char[] ach = str.toCharArray();
int len = ach.length;
int[] acp = new int[Character.codePointCount(ach, 0, len)];
int j = 0;
for (int i = 0, cp; i < len; i += Character.charCount(cp)) {
cp = Character.codePointAt(ach, i);
acp[j++] = cp;
}
return acp;
}
/**
* Work through the contents of the string, and replace any occurrences of
* [icon] with the imageSpan
*
* @param spannable
*/
private void emotifySpannable(Spannable spannable) {
int length = spannable.length();
int position = 0;
int tagStartPosition = 0;
int tagLength = 0;
StringBuilder buffer = new StringBuilder();
boolean inTag = false;
if (length <= 0)
return;
do {
String c = spannable.subSequence(position, position + 1).toString();
if (!inTag && c.equals(START_CHAR)) {
buffer = new StringBuilder();
tagStartPosition = position;
Log.d(TAG, " Entering tag at " + tagStartPosition);
inTag = true;
tagLength = 0;
}
if (inTag) {
buffer.append(c);
tagLength++;
// Have we reached end of the tag?
if (c.equals(END_CHAR)) {
inTag = false;
String tag = buffer.toString();
int tagEnd = tagStartPosition + tagLength;
Log.d(TAG, "Tag: " + tag + ", started at: "
+ tagStartPosition + ", finished at " + tagEnd
+ ", length: " + tagLength);
String hexStr = tag.substring(1, tag.length() - 1);
try {
int id = getContext().getResources().getIdentifier(
"emoji_" + hexStr, "drawable", getContext().getPackageName());
Drawable emoji = getContext().getResources()
.getDrawable(id);
emoji.setBounds(0, 0, this.getLineHeight(),
this.getLineHeight());
ImageSpan imageSpan = new ImageSpan(emoji,
ImageSpan.ALIGN_BOTTOM);
spannable.setSpan(imageSpan, tagStartPosition, tagEnd,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
} catch (Exception e) {
}
}
}
position++;
} while (position < length);
}
}
|
package com.worth.ifs.application.controller;
import com.worth.ifs.application.constant.ApplicationStatusConstants;
import com.worth.ifs.application.domain.Application;
import com.worth.ifs.application.transactional.ApplicationSummaryService;
import com.worth.ifs.finance.resource.ApplicationFinanceResource;
import com.worth.ifs.finance.transactional.CostService;
import com.worth.ifs.form.domain.FormInputResponse;
import com.worth.ifs.form.repository.FormInputResponseRepository;
import com.worth.ifs.user.domain.ProcessRole;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.NumberFormat;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
import java.util.stream.Collectors;
@RestController
@RequestMapping("/application/download")
public class ApplicationDownloadController {
private static final Log LOG = LogFactory.getLog(ApplicationDownloadController.class);
private static final Long APPLICATION_SUMMARY_FORM_INPUT_ID = 11L;
public static final int PROJECT_SUMMARY_COLUMN_WITH = 50; // the width in amount of letters.
@Autowired
ApplicationSummaryService applicationSummaryService;
@Autowired
CostService costService;
@Autowired
FormInputResponseRepository formInputResponseRepository;
@RequestMapping("/downloadByCompetition/{competitionId}")
public @ResponseBody ResponseEntity<ByteArrayResource> getDownloadByCompetitionId(@PathVariable("competitionId") Long competitionId) throws IOException {
List<Application> applications = applicationSummaryService.getApplicationSummariesByCompetitionIdAndStatus(competitionId, ApplicationStatusConstants.SUBMITTED.getId());
HSSFWorkbook wb = getExcelWorkbook(applications);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
wb.write(baos);
HttpHeaders httpHeaders = new HttpHeaders();
// Prevent caching
httpHeaders.add("Cache-Control", "no-cache, no-store, must-revalidate");
httpHeaders.add("Pragma", "no-cache");
httpHeaders.add("Expires", "0");
return new ResponseEntity<>(new ByteArrayResource(baos.toByteArray()), httpHeaders, HttpStatus.OK);
}
private HSSFWorkbook getExcelWorkbook(List<Application> applications) {
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("Submitted Applications");
int rowCount = 0;
// Set header row
int headerCount = 0;
HSSFRow row = sheet.createRow(rowCount++);
row.createCell(headerCount++).setCellValue("Application ID");
row.createCell(headerCount++).setCellValue("Application Title");
row.createCell(headerCount++).setCellValue("Lead Organisation");
row.createCell(headerCount++).setCellValue("Lead first name");
row.createCell(headerCount++).setCellValue("Lead last name");
row.createCell(headerCount++).setCellValue("Email");
row.createCell(headerCount++).setCellValue("Duration in Months");
row.createCell(headerCount++).setCellValue("Number of partners");
row.createCell(headerCount++).setCellValue("Project Summary");
row.createCell(headerCount++).setCellValue("Total project cost");
row.createCell(headerCount++).setCellValue("Funding sought");
for (Application a : applications) {
Optional<List<ApplicationFinanceResource>> financeTotalsOptional = costService.financeTotals(a.getId()).getOptionalSuccessObject();
List<FormInputResponse> projectSummary = formInputResponseRepository.findByApplicationIdAndFormInputId(a.getId(), APPLICATION_SUMMARY_FORM_INPUT_ID);
String projectSummaryString = "";
if(!projectSummary.isEmpty()){
projectSummaryString = projectSummary.get(0).getValue();
}
BigDecimal total = BigDecimal.ZERO;
BigDecimal fundingSought = BigDecimal.ZERO;
if(financeTotalsOptional.isPresent()){
List<ApplicationFinanceResource> financeTotals;
financeTotals = financeTotalsOptional.get();
total = financeTotals.stream().map(t -> t.getTotal()).reduce(BigDecimal.ZERO, BigDecimal::add);
fundingSought = financeTotals.stream().map(t -> t.getTotalFundingSought()).reduce(BigDecimal.ZERO, BigDecimal::add);
}
String totalFormatted = NumberFormat.getCurrencyInstance(Locale.UK).format(total);
String fundingSoughtFormatted = NumberFormat.getCurrencyInstance(Locale.UK).format(fundingSought);
int cellCount = 0;
row = sheet.createRow(rowCount++);
row.createCell(cellCount++).setCellValue(a.getId());
row.createCell(cellCount++).setCellValue(a.getName());
row.createCell(cellCount++).setCellValue(a.getLeadOrganisation().getName());
row.createCell(cellCount++).setCellValue(a.getLeadApplicant().getFirstName());
row.createCell(cellCount++).setCellValue(a.getLeadApplicant().getLastName());
row.createCell(cellCount++).setCellValue(a.getLeadApplicant().getEmail());
row.createCell(cellCount++).setCellValue(a.getDurationInMonths());
row.createCell(cellCount++).setCellValue(a.getProcessRoles().stream().collect(Collectors.groupingBy(ProcessRole::getOrganisation)).size());
row.createCell(cellCount++).setCellValue(projectSummaryString);
row.createCell(cellCount++).setCellValue(totalFormatted);
row.createCell(cellCount++).setCellValue(fundingSoughtFormatted);
}
for (int i = 0; i < headerCount; i++) {
sheet.autoSizeColumn(i);
}
// This column contains the project summary, so might be very long because of autoSize..
sheet.setColumnWidth(8, PROJECT_SUMMARY_COLUMN_WITH * 256);
return wb;
}
}
|
package com.autonomy.abc.topnavbar.on_prem_options;
import com.autonomy.abc.config.ABCTestBase;
import com.autonomy.abc.config.TestConfig;
import com.autonomy.abc.selenium.config.ApplicationType;
import com.autonomy.abc.selenium.element.Editable;
import com.autonomy.abc.selenium.page.admin.UsersPage;
import com.autonomy.abc.selenium.users.NewUser;
import com.autonomy.abc.selenium.users.Role;
import com.autonomy.abc.selenium.users.User;
import com.autonomy.abc.selenium.users.UserService;
import com.hp.autonomy.frontend.selenium.element.ModalView;
import org.apache.commons.lang.StringUtils;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Platform;
import org.openqa.selenium.UnhandledAlertException;
import java.net.MalformedURLException;
import java.util.List;
import static com.autonomy.abc.framework.ABCAssert.assertThat;
import static com.autonomy.abc.framework.ABCAssert.verifyThat;
import static com.autonomy.abc.matchers.ElementMatchers.*;
import static org.hamcrest.Matchers.*;
import static org.junit.Assume.assumeThat;
import static org.openqa.selenium.lift.Matchers.displayed;
public class UsersPageITCase extends ABCTestBase {
public UsersPageITCase(final TestConfig config, final String browser, final ApplicationType appType, final Platform platform) {
super(config, browser, appType, platform);
}
private final NewUser aNewUser = config.getNewUser("james");
private final NewUser newUser2 = config.getNewUser("john");
private UsersPage usersPage;
private UserService userService;
@Before
public void setUp() throws MalformedURLException, InterruptedException {
userService = getApplication().createUserService(getElementFactory());
usersPage = userService.goToUsers();
usersPage.deleteOtherUsers();
}
private User singleSignUp() {
usersPage.createUserButton().click();
assertThat(usersPage, modalIsDisplayed());
final ModalView newUserModal = ModalView.getVisibleModalView(getDriver());
User user = aNewUser.signUpAs(Role.USER, usersPage);
assertThat(newUserModal, containsText("Done! User " + user.getUsername() + " successfully created"));
usersPage.closeModal();
return user;
}
private void signUpAndLoginAs(NewUser newUser) {
usersPage.createUserButton().click();
assertThat(usersPage, modalIsDisplayed());
User user = newUser.signUpAs(Role.USER, usersPage);
usersPage.closeModal();
logout();
loginAs(user);
assertThat(getDriver().getCurrentUrl(), not(containsString("login")));
}
private void deleteAndVerify(User user) {
usersPage.deleteUser(user.getUsername());
verifyThat(usersPage, containsText("User " + user.getUsername() + " successfully deleted"));
}
@Test
public void testCreateUser() {
// TODO: split into HS/OP?
assumeThat(config.getType(), is(ApplicationType.ON_PREM));
usersPage.createUserButton().click();
assertThat(usersPage, modalIsDisplayed());
final ModalView newUserModal = ModalView.getVisibleModalView(getDriver());
verifyThat(newUserModal, hasTextThat(startsWith("Create New Users")));
usersPage.createButton().click();
verifyThat(newUserModal, containsText("Error! Username must not be blank"));
usersPage.addUsername("Andrew");
usersPage.clearPasswords();
usersPage.createButton().click();
verifyThat(newUserModal, containsText("Error! Password must not be blank"));
usersPage.addAndConfirmPassword("password", "wordpass");
usersPage.createButton().click();
verifyThat(newUserModal, containsText("Error! Password confirmation failed"));
usersPage.createNewUser("Andrew", "qwerty", "Admin");
verifyThat(newUserModal, containsText("Done! User Andrew successfully created"));
usersPage.closeModal();
verifyThat(usersPage, not(containsText("Create New Users")));
}
@Test
public void testWontDeleteSelf() {
assertThat(usersPage.deleteButton(getCurrentUser().getUsername()), disabled());
}
@Test
public void testDeleteAllUsers() {
final int initialNumberOfUsers = usersPage.countNumberOfUsers();
usersPage.createUserButton().click();
assertThat(usersPage, modalIsDisplayed());
User user = aNewUser.signUpAs(Role.USER, usersPage);
User admin = newUser2.signUpAs(Role.ADMIN, usersPage);
usersPage.closeModal();
verifyThat(usersPage.countNumberOfUsers(), is(initialNumberOfUsers + 2));
deleteAndVerify(admin);
verifyThat(usersPage.countNumberOfUsers(), is(initialNumberOfUsers + 1));
deleteAndVerify(user);
verifyThat(usersPage.countNumberOfUsers(), is(initialNumberOfUsers));
usersPage.createUserButton().click();
verifyThat(usersPage.isModalShowing(), is(true));
aNewUser.signUpAs(Role.USER, usersPage);
newUser2.signUpAs(Role.ADMIN, usersPage);
usersPage.closeModal();
verifyThat(usersPage.countNumberOfUsers(), is(initialNumberOfUsers + 2));
usersPage.deleteOtherUsers();
verifyThat("Not all users are deleted", usersPage.countNumberOfUsers(), is(1));
}
@Test
public void testAddDuplicateUser() {
usersPage.createUserButton().click();
assertThat(usersPage, modalIsDisplayed());
User original = aNewUser.signUpAs(Role.USER, usersPage);
final ModalView newUserModal = ModalView.getVisibleModalView(getDriver());
verifyThat(newUserModal, containsText("Done! User " + original.getUsername() + " successfully created"));
aNewUser.signUpAs(Role.USER, usersPage);
verifyThat(newUserModal, containsText("Error! User exists!"));
config.getNewUser("testAddDuplicateUser_james").signUpAs(Role.USER, usersPage);
verifyThat(newUserModal, containsText("Error! User exists!"));
usersPage.closeModal();
verifyThat(usersPage.countNumberOfUsers(), is(2));
}
@Test
public void testUserDetails() {
usersPage.createUserButton().click();
assertThat(usersPage, modalIsDisplayed());
final ModalView newUserModal = ModalView.getVisibleModalView(getDriver());
User admin = aNewUser.signUpAs(Role.ADMIN, usersPage);
assertThat(newUserModal, containsText("Done! User " + admin.getUsername() + " successfully created"));
User user = newUser2.signUpAs(Role.USER, usersPage);
assertThat(newUserModal, containsText("Done! User " + user.getUsername() + " successfully created"));
usersPage.closeModal();
List<String> usernames = usersPage.getUsernames();
assertThat(usernames, hasItem(admin.getUsername()));
assertThat(usersPage.getRoleOf(admin), is(Role.ADMIN));
assertThat(usernames, hasItem(user.getUsername()));
assertThat(usersPage.getRoleOf(user), is(Role.USER));
}
@Test
public void testEditUserPassword() {
// OP/HS split?
assumeThat(config.getType(), is(ApplicationType.ON_PREM));
User user = singleSignUp();
Editable passwordBox = usersPage.passwordBoxFor(user);
passwordBox.setValueAsync("");
assertThat(passwordBox.getElement(), containsText("Password must not be blank"));
assertThat(passwordBox.editButton(), not(displayed()));
passwordBox.setValueAndWait("valid");
assertThat(passwordBox.editButton(), displayed());
}
@Test
public void testEditUserType() {
User user = singleSignUp();
usersPage.roleLinkFor(user).click();
usersPage.setRoleValueFor(user, Role.ADMIN);
usersPage.cancelPendingEditFor(user);
assertThat(usersPage.roleLinkFor(user), displayed());
assertThat(usersPage.getRoleOf(user), is(user.getRole()));
usersPage.changeRole(user, Role.USER);
assertThat(usersPage.roleLinkFor(user), displayed());
assertThat(usersPage.getRoleOf(user), is(Role.USER));
usersPage.changeRole(user, Role.ADMIN);
assertThat(usersPage.roleLinkFor(user), displayed());
assertThat(usersPage.getRoleOf(user), is(Role.ADMIN));
usersPage.changeRole(user, Role.NONE);
assertThat(usersPage.roleLinkFor(user), displayed());
assertThat(usersPage.getRoleOf(user), is(Role.NONE));
}
@Test
public void testAddStupidlyLongUsername() {
assumeThat(config.getType(), is(ApplicationType.ON_PREM));
final String longUsername = StringUtils.repeat("a", 100);
usersPage.createUserButton().click();
assertThat(usersPage, modalIsDisplayed());
usersPage.createNewUser(longUsername, "b", "User");
usersPage.closeModal();
assertThat(usersPage.getTable(), containsText(longUsername));
assertThat(usersPage.deleteButton(longUsername), displayed());
usersPage.deleteUser(longUsername);
assertThat(usersPage.getTable(), not(containsText(longUsername)));
}
@Test
public void testLogOutAndLogInWithNewUser() {
signUpAndLoginAs(aNewUser);
}
@Test
public void testChangeOfPasswordWorksOnLogin() {
User initialUser = singleSignUp();
User updatedUser = usersPage.changeAuth(initialUser, newUser2);
logout();
loginAs(initialUser);
usersPage.loadOrFadeWait();
assertThat("old password does not work", getDriver().getCurrentUrl(), containsString("login"));
loginAs(updatedUser);
usersPage.loadOrFadeWait();
assertThat("new password works", getDriver().getCurrentUrl(), not(containsString("login")));
}
@Test
public void testCreateUserPermissionNoneAndTestLogin() {
User user = singleSignUp();
assertThat(usersPage.roleLinkFor(user), displayed());
assertThat(usersPage.getRoleOf(user), is(user.getRole()));
usersPage.changeRole(user, Role.NONE);
assertThat(usersPage.roleLinkFor(user), displayed());
assertThat(usersPage.getRoleOf(user), is(Role.NONE));
logout();
loginAs(user);
getElementFactory().getLoginPage();
|
package com.ezardlabs.lostsector.objects;
import com.ezardlabs.dethsquare.Animation;
import com.ezardlabs.dethsquare.Animator;
import com.ezardlabs.dethsquare.Camera;
import com.ezardlabs.dethsquare.Collider;
import com.ezardlabs.dethsquare.Collider.Collision;
import com.ezardlabs.dethsquare.Collider.CollisionLocation;
import com.ezardlabs.dethsquare.GameObject;
import com.ezardlabs.dethsquare.Input;
import com.ezardlabs.dethsquare.Input.KeyCode;
import com.ezardlabs.dethsquare.Renderer;
import com.ezardlabs.dethsquare.Screen;
import com.ezardlabs.dethsquare.Script;
import com.ezardlabs.dethsquare.TextureAtlas;
import com.ezardlabs.dethsquare.TextureAtlas.Sprite;
import com.ezardlabs.dethsquare.Touch;
import com.ezardlabs.dethsquare.Vector2;
import com.ezardlabs.dethsquare.animationtypes.OneShotAnimation;
import com.ezardlabs.dethsquare.util.Utils;
import com.ezardlabs.lostsector.objects.warframes.Warframe;
import java.util.Timer;
import java.util.TimerTask;
public class Player extends Script {
public static GameObject player;
public int jumpCount = 0;
private int x = 0;
private float speed = 12.5f;
private Warframe warframe;
public State state = State.IDLE;
public enum State {
IDLE,
RUNNING,
JUMPING,
DOUBLE_JUMPING,
FALLING,
LANDING,
MELEE,
MELEE_WAITING,
SHOOTING,
CASTING
}
@Override
public void start() {
player = gameObject;
warframe = (Warframe) gameObject.getComponentOfType(Warframe.class);
}
@Override
public void update() {
x = getMovement();
if (x < 0) {
gameObject.renderer.hFlipped = true;
} else if (x > 0) {
gameObject.renderer.hFlipped = false;
}
switch (state) {
case IDLE:
if (jumpCheck()) break;
if (fallCheck()) break;
if (meleeCheck()) break;
if (castCheck()) break;
if (x != 0) state = State.RUNNING;
break;
case RUNNING:
if (jumpCheck()) break;
if (fallCheck()) break;
if (meleeCheck()) break;
if (castCheck()) break;
if (x == 0) state = State.IDLE;
break;
case JUMPING:
if (jumpCheck()) break;
if (fallCheck()) break;
break;
case DOUBLE_JUMPING:
if (fallCheck()) break;
break;
case FALLING:
if (jumpCheck()) break;
break;
case LANDING:
break;
case MELEE:
break;
case MELEE_WAITING:
break;
case SHOOTING:
break;
case CASTING:
break;
}
switch (state) {
case IDLE:
gameObject.animator.play("idle");
break;
case RUNNING:
gameObject.animator.play("run");
transform.translate(x * speed, 0);
if (Input.getKeyDown(KeyCode.ALPHA_1)) warframe.ability1();
if (Input.getKeyDown(KeyCode.ALPHA_2)) warframe.ability2();
if (Input.getKeyDown(KeyCode.ALPHA_3)) warframe.ability3();
if (Input.getKeyDown(KeyCode.ALPHA_4)) warframe.ability4();
break;
case JUMPING:
gameObject.animator.play("jump");
transform.translate(x * speed, 0);
if (Input.getKeyDown(KeyCode.ALPHA_1)) warframe.ability1();
break;
case DOUBLE_JUMPING:
gameObject.animator.play("doublejump");
transform.translate(x * speed, 0);
if (Input.getKeyDown(KeyCode.ALPHA_1)) warframe.ability1();
break;
case FALLING:
gameObject.animator.play("fall");
transform.translate(x * speed, 0);
if (Input.getKeyDown(KeyCode.ALPHA_1)) warframe.ability1();
break;
case LANDING:
gameObject.animator.play("land");
break;
case MELEE:
gameObject.animator.play(warframe.meleeWeapon.getNextAnimation(x));
break;
case MELEE_WAITING:
meleeCheck();
break;
case SHOOTING:
break;
case CASTING:
gameObject.animator.play("cast");
break;
}
}
private int getMovement() {
switch (Utils.PLATFORM) {
case ANDROID:
int movement = 0;
if (Input.touches.length == 0) return movement;
for (Touch t : Input.touches) {
if (t.position.x < Screen.width / 6f) {
movement
break;
}
}
for (Touch t : Input.touches) {
if (t.position.x > Screen.width / 6f && t.position.x < Screen.width / 2f) {
movement++;
break;
}
}
return movement;
case DESKTOP:
return (Input.getKey(KeyCode.A) ? -1 : 0) + (Input.getKey(KeyCode.D) ? 1 : 0);
default:
return 0;
}
}
private boolean jumpCheck() {
boolean touchJump = false;
for (Touch t : Input.touches) {
if (t.phase != Touch.TouchPhase.STATIONARY)
if (t.phase == Touch.TouchPhase.ENDED && t.position.x > Screen.width / 2f && t.startPosition.x > Screen.width / 2f && Vector2.distance(t.position, t.startPosition) < 150) {
touchJump = true;
}
}
if ((Input.getKeyDown(KeyCode.SPACE) || Input.getKeyDown(KeyCode.J) || touchJump) && jumpCount++ < 2) {
state = jumpCount == 1 ? State.JUMPING : State.DOUBLE_JUMPING;
gameObject.rigidbody.velocity.y = -25f;
return true;
}
return false;
}
private boolean fallCheck() {
if (gameObject.rigidbody.velocity.y > 0) {
state = State.FALLING;
return true;
}
return false;
}
private boolean meleeCheck() {
if (Input.getKeyDown(KeyCode.RETURN) || Input.getKeyDown(KeyCode.K)) {
state = State.MELEE;
warframe.meleeWeapon.getNextAnimation(x);
return true;
}
return false;
}
private boolean castCheck() {
boolean ability1 = false;
boolean ability2 = false;
boolean ability3 = false;
boolean ability4 = false;
for (Touch t : Input.touches) {
if (t.phase == Touch.TouchPhase.ENDED) {
float x = t.position.x - t.startPosition.x;
float y = t.position.y - t.startPosition.y;
if (x < -150 * Screen.scale) { // left
ability3 = true;
} else if (x > 150 * Screen.scale) { // right
ability1 = true;
} else if (y < -150 * Screen.scale) {
ability4 = true;
} else if (y > 150 * Screen.scale) { // down
ability2 = true;
}
}
}
if (ability1 || Input.getKeyDown(KeyCode.ALPHA_1)) {
if (warframe.hasEnergy(5)) {
warframe.removeEnergy(5);
warframe.ability1();
}
}
if (ability2 || Input.getKeyDown(KeyCode.ALPHA_2)) {
if (warframe.hasEnergy(10)) {
warframe.removeEnergy(10);
warframe.ability2();
}
}
if (ability3 || Input.getKeyDown(KeyCode.ALPHA_3)) {
if (warframe.hasEnergy(25)) {
warframe.removeEnergy(25);
warframe.ability3();
}
}
if ((state == State.IDLE || state == State.RUNNING) && (ability4 || Input.getKeyDown(KeyCode.ALPHA_4))) {
if (warframe.hasEnergy(50)) {
warframe.removeEnergy(50);
warframe.ability4();
state = State.CASTING;
return true;
}
}
return false;
}
@Override
public void onCollision(Collider other, Collision collision) {
if (collision.location == CollisionLocation.BOTTOM) {
jumpCount = 0;
if (collision.speed > 37) {
state = State.LANDING;
// gameObject.renderer.setSize(200, 200);
// gameObject.renderer.setOffsets(0, 0);
// gameObject.animator.play("land");
//noinspection ConstantConditions
Camera.main.gameObject.getComponent(CameraMovement.class).startQuake(100, 0.3f);
TextureAtlas ta = new TextureAtlas("images/effects/dust.png", "images/effects/dust.txt");
GameObject.destroy(GameObject.instantiate(new GameObject("Dust", new Renderer(ta, ta.getSprite("dust0"), 700, 50),
new Animator(new Animation("dust", new Sprite[]{ta.getSprite("dust0"),
ta.getSprite("dust1"),
ta.getSprite("dust2")}, new OneShotAnimation(), 100))),
new Vector2(transform.position.x - 262, transform.position.y + 150)), 300);
new Timer().schedule(new TimerTask() {
@Override
public void run() {
state = State.IDLE;
}
}, 300);
} else {
state = State.IDLE;
}
}
}
}
|
package uk.org.ulcompsoc.ld32.util;
public enum TextureName {
BASIC_TOWER("towers/tower_0.png"),
PADDLE("paddle.png"),
BALL_ANIM("ball.png"),
ENEMY_R("enemies/enemy_0r.png"),
ENEMY_G("enemies/enemy_0g.png"),
ENEMY_B("enemies/enemy_0b.png"),
BALL_R("upgrade_balls/red.png"),
BALL_B("upgrade_balls/blue.png"),
BALL_G("upgrade_balls/green.png"),
ZERO("numbers/0.png"),
ONE("numbers/1.png"),
TWO("numbers/2.png"),
THREE("numbers/3.png"),
FOUR("numbers/4.png"),
FIVE("numbers/5.png"),
SIX("numbers/6.png"),
SEVEN("numbers/7.png"),
EIGHT("numbers/8.png"),
NINE("numbers/9.png"),
FRAME_1("GUI/frame.png"),
AMMO("ammo.png");
public final String assetName;
private TextureName(final String name) {
this.assetName = name;
}
}
|
package com.ezardlabs.lostsector.objects;
import com.ezardlabs.dethsquare.Animation;
import com.ezardlabs.dethsquare.AnimationType;
import com.ezardlabs.dethsquare.Animator;
import com.ezardlabs.dethsquare.Camera;
import com.ezardlabs.dethsquare.Collider;
import com.ezardlabs.dethsquare.Collider.Collision;
import com.ezardlabs.dethsquare.Collider.CollisionLocation;
import com.ezardlabs.dethsquare.GameObject;
import com.ezardlabs.dethsquare.GuiRenderer;
import com.ezardlabs.dethsquare.Input;
import com.ezardlabs.dethsquare.Input.KeyCode;
import com.ezardlabs.dethsquare.Renderer;
import com.ezardlabs.dethsquare.Screen;
import com.ezardlabs.dethsquare.Script;
import com.ezardlabs.dethsquare.TextureAtlas;
import com.ezardlabs.dethsquare.TextureAtlas.Sprite;
import com.ezardlabs.dethsquare.Touch;
import com.ezardlabs.dethsquare.Vector2;
import com.ezardlabs.dethsquare.util.Utils;
import com.ezardlabs.lostsector.objects.warframes.Warframe;
import java.util.Timer;
import java.util.TimerTask;
public class Player extends Script {
public static GameObject player;
public int jumpCount = 0;
private int x = 0;
private float speed = 12.5f;
private Warframe warframe;
private GuiRenderer androidMeleeButton;
public State state = State.IDLE;
public boolean dead = false;
public enum State {
IDLE,
RUNNING,
JUMPING,
DOUBLE_JUMPING,
FALLING,
LANDING,
MELEE,
MELEE_WAITING,
SHOOTING,
CASTING
}
@Override
public void start() {
player = gameObject;
warframe = (Warframe) gameObject.getComponentOfType(Warframe.class);
gameObject.setTag("player");
if (Utils.PLATFORM == Utils.Platform.ANDROID) {
GameObject.instantiate(new GameObject("Melee Button", androidMeleeButton = new GuiRenderer("images/hud/melee.png", 187.5f, 187.5f)), new Vector2((Screen.width - 187.5f * Screen.scale) / Screen.scale, (Screen.height - 187.5f * Screen.scale) / Screen.scale));
}
}
@Override
public void update() {
if (dead) return;
x = getMovement();
if (x < 0) {
gameObject.renderer.hFlipped = true;
} else if (x > 0) {
gameObject.renderer.hFlipped = false;
}
switch (state) {
case IDLE:
if (jumpCheck()) break;
if (fallCheck()) break;
if (meleeCheck()) break;
if (castCheck()) break;
if (x != 0) state = State.RUNNING;
break;
case RUNNING:
if (jumpCheck()) break;
if (fallCheck()) break;
if (meleeCheck()) break;
if (castCheck()) break;
if (x == 0) state = State.IDLE;
break;
case JUMPING:
if (jumpCheck()) break;
if (fallCheck()) break;
break;
case DOUBLE_JUMPING:
if (fallCheck()) break;
break;
case FALLING:
if (jumpCheck()) break;
break;
case LANDING:
break;
case MELEE:
break;
case MELEE_WAITING:
break;
case SHOOTING:
break;
case CASTING:
break;
}
switch (state) {
case IDLE:
gameObject.animator.play("idle");
break;
case RUNNING:
gameObject.animator.play("run");
transform.translate(x * speed, 0);
if (Input.getKeyDown(KeyCode.ALPHA_1)) warframe.ability1();
if (Input.getKeyDown(KeyCode.ALPHA_2)) warframe.ability2();
if (Input.getKeyDown(KeyCode.ALPHA_3)) warframe.ability3();
if (Input.getKeyDown(KeyCode.ALPHA_4)) warframe.ability4();
break;
case JUMPING:
gameObject.animator.play("jump");
transform.translate(x * speed, 0);
if (Input.getKeyDown(KeyCode.ALPHA_1)) warframe.ability1();
break;
case DOUBLE_JUMPING:
gameObject.animator.play("doublejump");
transform.translate(x * speed, 0);
if (Input.getKeyDown(KeyCode.ALPHA_1)) warframe.ability1();
break;
case FALLING:
gameObject.animator.play("fall");
transform.translate(x * speed, 0);
if (Input.getKeyDown(KeyCode.ALPHA_1)) warframe.ability1();
break;
case LANDING:
gameObject.animator.play("land");
break;
case MELEE:
gameObject.animator.play(warframe.meleeWeapon.getNextAnimation(x));
break;
case MELEE_WAITING:
meleeCheck();
break;
case SHOOTING:
break;
case CASTING:
gameObject.animator.play("cast");
break;
}
}
private int getMovement() {
switch (Utils.PLATFORM) {
case ANDROID:
int movement = 0;
if (Input.touches.length == 0) return movement;
for (Touch t : Input.touches) {
if (t.position.x < Screen.width / 6f) {
movement
break;
}
}
for (Touch t : Input.touches) {
if (t.position.x > Screen.width / 6f && t.position.x < Screen.width / 2f) {
movement++;
break;
}
}
return movement;
case DESKTOP:
return (Input.getKey(KeyCode.A) ? -1 : 0) + (Input.getKey(KeyCode.D) ? 1 : 0);
default:
return 0;
}
}
private boolean jumpCheck() {
boolean touchJump = false;
for (Touch t : Input.touches) {
if (t.phase != Touch.TouchPhase.STATIONARY)
if (t.phase == Touch.TouchPhase.ENDED && t.position.x > Screen.width / 2f && t.startPosition.x > Screen.width / 2f && Vector2.distance(t.position, t.startPosition) < 150 && (androidMeleeButton != null && !androidMeleeButton.hitTest(t.position))) {
touchJump = true;
}
}
if ((Input.getKeyDown(KeyCode.SPACE) || Input.getKeyDown(KeyCode.J) || touchJump) && jumpCount++ < 2) {
state = jumpCount == 1 ? State.JUMPING : State.DOUBLE_JUMPING;
gameObject.rigidbody.velocity.y = -25f;
return true;
}
return false;
}
private boolean fallCheck() {
if (gameObject.rigidbody.velocity.y > 0) {
state = State.FALLING;
return true;
}
return false;
}
private boolean meleeCheck() {
boolean touchMelee = false;
if (androidMeleeButton != null) {
for (Touch t : Input.touches) {
if (t.phase == Touch.TouchPhase.BEGAN && androidMeleeButton.hitTest(t.position)) {
touchMelee = true;
break;
}
}
}
if (Input.getKeyDown(KeyCode.RETURN) || Input.getKeyDown(KeyCode.K) || touchMelee) {
state = State.MELEE;
warframe.meleeWeapon.getNextAnimation(x);
return true;
}
return false;
}
private boolean castCheck() {
boolean ability1 = false;
boolean ability2 = false;
boolean ability3 = false;
boolean ability4 = false;
for (Touch t : Input.touches) {
if (t.phase == Touch.TouchPhase.ENDED) {
float x = t.position.x - t.startPosition.x;
float y = t.position.y - t.startPosition.y;
if (x < -150 * Screen.scale) { // left
ability3 = true;
} else if (x > 150 * Screen.scale) { // right
ability1 = true;
} else if (y < -150 * Screen.scale) {
ability4 = true;
} else if (y > 150 * Screen.scale) { // down
ability2 = true;
}
}
}
if (ability1 || Input.getKeyDown(KeyCode.ALPHA_1)) {
if (warframe.hasEnergy(5)) {
warframe.removeEnergy(5);
warframe.ability1();
}
}
if (ability2 || Input.getKeyDown(KeyCode.ALPHA_2)) {
if (warframe.hasEnergy(10)) {
warframe.removeEnergy(10);
warframe.ability2();
}
}
if (ability3 || Input.getKeyDown(KeyCode.ALPHA_3)) {
if (warframe.hasEnergy(25)) {
warframe.removeEnergy(25);
warframe.ability3();
}
}
if ((state == State.IDLE || state == State.RUNNING) && (ability4 || Input.getKeyDown(KeyCode.ALPHA_4))) {
if (warframe.hasEnergy(50)) {
warframe.removeEnergy(50);
warframe.ability4();
state = State.CASTING;
return true;
}
}
return false;
}
@Override
public void onCollision(Collider other, Collision collision) {
if (collision.location == CollisionLocation.BOTTOM) {
jumpCount = 0;
if (collision.speed > 37) {
state = State.LANDING;
// gameObject.renderer.setSize(200, 200);
// gameObject.renderer.setOffsets(0, 0);
// gameObject.animator.play("land");
//noinspection ConstantConditions
Camera.main.gameObject.getComponent(CameraMovement.class).startQuake(100, 0.3f);
TextureAtlas ta = new TextureAtlas("images/effects/dust.png", "images/effects/dust.txt");
GameObject.destroy(GameObject.instantiate(new GameObject("Dust", new Renderer(ta, ta.getSprite("dust0"), 700, 50),
new Animator(new Animation("dust", new Sprite[]{ta.getSprite("dust0"),
ta.getSprite("dust1"),
ta.getSprite("dust2")}, AnimationType.ONE_SHOT, 100))),
new Vector2(transform.position.x - 262, transform.position.y + 150)), 300);
new Timer().schedule(new TimerTask() {
@Override
public void run() {
state = State.IDLE;
}
}, 300);
} else {
state = State.IDLE;
}
}
}
}
|
package com.intellij.codeInspection.visibility;
import com.intellij.codeInsight.daemon.GroupNames;
import com.intellij.codeInsight.daemon.impl.UnusedSymbolUtil;
import com.intellij.codeInspection.AbstractBaseJavaLocalInspectionTool;
import com.intellij.codeInspection.ProblemsHolder;
import com.intellij.codeInspection.deadCode.UnusedDeclarationInspectionBase;
import com.intellij.codeInspection.inheritance.ImplicitSubclassProvider;
import com.intellij.openapi.progress.EmptyProgressIndicator;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Comparing;
import com.intellij.psi.*;
import com.intellij.psi.search.searches.FunctionalExpressionSearch;
import com.intellij.psi.util.ClassUtil;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.util.VisibilityUtil;
import com.intellij.util.containers.ContainerUtil;
import com.siyeh.ig.fixes.ChangeModifierFix;
import com.siyeh.ig.psiutils.MethodUtils;
import gnu.trove.TObjectIntHashMap;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
class AccessCanBeTightenedInspection extends AbstractBaseJavaLocalInspectionTool {
private final VisibilityInspection myVisibilityInspection;
AccessCanBeTightenedInspection(@NotNull VisibilityInspection visibilityInspection) {
myVisibilityInspection = visibilityInspection;
}
@Override
public boolean isEnabledByDefault() {
return true;
}
@Override
@NotNull
public String getGroupDisplayName() {
return GroupNames.VISIBILITY_GROUP_NAME;
}
@Override
@NotNull
public String getDisplayName() {
return "Member access can be tightened";
}
@Override
@NotNull
public String getShortName() {
return VisibilityInspection.SHORT_NAME;
}
@NotNull
@Override
public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, final boolean isOnTheFly) {
return new MyVisitor(holder);
}
private class MyVisitor extends JavaElementVisitor {
private final ProblemsHolder myHolder;
private final UnusedDeclarationInspectionBase myDeadCodeInspection;
public MyVisitor(@NotNull ProblemsHolder holder) {
myHolder = holder;
myDeadCodeInspection = UnusedDeclarationInspectionBase.findUnusedDeclarationInspection(holder.getFile());
}
private final TObjectIntHashMap<PsiClass> maxSuggestedLevelForChildMembers = new TObjectIntHashMap<>();
@Override
public void visitClass(PsiClass aClass) {
checkMember(aClass);
}
@Override
public void visitMethod(PsiMethod method) {
checkMember(method);
}
@Override
public void visitField(PsiField field) {
checkMember(field);
}
private void checkMember(@NotNull final PsiMember member) {
if (!myVisibilityInspection.SUGGEST_FOR_CONSTANTS && isConstantField(member)) {
return;
}
final PsiClass memberClass = member.getContainingClass();
PsiModifierList memberModifierList = member.getModifierList();
if (memberModifierList == null) return;
int currentLevel = PsiUtil.getAccessLevel(memberModifierList);
int suggestedLevel = suggestLevel(member, memberClass, currentLevel);
if (memberClass != null) {
synchronized (maxSuggestedLevelForChildMembers) {
int prevMax = maxSuggestedLevelForChildMembers.get(memberClass);
maxSuggestedLevelForChildMembers.put(memberClass, Math.max(prevMax, suggestedLevel));
}
}
log(member.getName() + ": effective level is '" + PsiUtil.getAccessModifier(suggestedLevel) + "'");
if (suggestedLevel < currentLevel) {
if (member instanceof PsiClass) {
int memberMaxLevel;
synchronized (maxSuggestedLevelForChildMembers) {
memberMaxLevel = maxSuggestedLevelForChildMembers.get((PsiClass)member);
}
if (memberMaxLevel > suggestedLevel) {
// a class can't have visibility less than its members
return;
}
}
PsiElement toHighlight = currentLevel == PsiUtil.ACCESS_LEVEL_PACKAGE_LOCAL ? ((PsiNameIdentifierOwner)member).getNameIdentifier() :
ContainerUtil.find(memberModifierList.getChildren(),
element -> element instanceof PsiKeyword && element.getText().equals(PsiUtil.getAccessModifier(currentLevel)));
// can be null in some strange cases of malbuilt PSI, like in EA-95877
if (toHighlight != null) {
String suggestedModifier = PsiUtil.getAccessModifier(suggestedLevel);
myHolder.registerProblem(toHighlight, "Access can be " + VisibilityUtil.toPresentableText(suggestedModifier), new ChangeModifierFix(suggestedModifier));
}
}
}
@PsiUtil.AccessLevel
private int suggestLevel(@NotNull PsiMember member, PsiClass memberClass, @PsiUtil.AccessLevel int currentLevel) {
if (member.hasModifierProperty(PsiModifier.PRIVATE) || member.hasModifierProperty(PsiModifier.NATIVE)) return currentLevel;
if (member instanceof PsiMethod && member instanceof SyntheticElement || !member.isPhysical()) return currentLevel;
if (member instanceof PsiMethod) {
PsiMethod method = (PsiMethod)member;
if (!method.getHierarchicalMethodSignature().getSuperSignatures().isEmpty()) {
log(member.getName() + " overrides");
return currentLevel; // overrides
}
if (MethodUtils.isOverridden(method)) {
log(member.getName() + " overridden");
return currentLevel;
}
}
if (member instanceof PsiEnumConstant) return currentLevel;
if (member instanceof PsiClass && (member instanceof PsiAnonymousClass ||
member instanceof PsiTypeParameter ||
member instanceof PsiSyntheticClass ||
PsiUtil.isLocalClass((PsiClass)member))) {
return currentLevel;
}
if (memberClass != null && (memberClass.isInterface() || memberClass.isEnum() || memberClass.isAnnotationType() || PsiUtil.isLocalClass(memberClass) && member instanceof PsiClass)) {
return currentLevel;
}
if (memberClass != null && member instanceof PsiMethod) {
// If class will be subclassed by some framework then it could apply some specific requirements for methods visibility
// so we just skip it here (IDEA-182709, IDEA-160602)
for (ImplicitSubclassProvider subclassProvider : ImplicitSubclassProvider.EP_NAME.getExtensions()) {
if (!subclassProvider.isApplicableTo(memberClass)) continue;
ImplicitSubclassProvider.SubclassingInfo info = subclassProvider.getSubclassingInfo(memberClass);
if (info == null) continue;
Map<PsiMethod, ImplicitSubclassProvider.OverridingInfo> methodsInfo = info.getMethodsInfo();
if (methodsInfo == null || methodsInfo.containsKey(member)) {
return currentLevel;
}
}
}
final PsiFile memberFile = member.getContainingFile();
Project project = memberFile.getProject();
int minLevel = PsiUtil.ACCESS_LEVEL_PRIVATE;
boolean entryPoint = myDeadCodeInspection.isEntryPoint(member);
if (entryPoint) {
int level = myVisibilityInspection.getMinVisibilityLevel(member);
if (level <= 0) {
log(member.getName() +" is entry point");
return currentLevel;
}
else {
minLevel = level;
}
}
final PsiPackage memberPackage = getPackage(memberFile);
log(member.getName()+ ": checking effective level for "+member);
AtomicInteger maxLevel = new AtomicInteger(minLevel);
AtomicBoolean foundUsage = new AtomicBoolean();
boolean proceed = UnusedSymbolUtil.processUsages(project, memberFile, member, new EmptyProgressIndicator(), null, info -> {
PsiElement element = info.getElement();
if (element == null) return true;
PsiFile psiFile = info.getFile();
if (psiFile == null) return true;
return handleUsage(member, memberClass, maxLevel, memberPackage, element, psiFile, foundUsage);
});
if (proceed && member instanceof PsiClass && LambdaUtil.isFunctionalClass((PsiClass)member)) {
// there can be lambda implementing this interface implicitly
FunctionalExpressionSearch.search((PsiClass)member).forEach(functionalExpression -> {
PsiFile psiFile = functionalExpression.getContainingFile();
return handleUsage(member, memberClass, maxLevel, memberPackage, functionalExpression, psiFile, foundUsage);
});
}
if (!foundUsage.get() && !entryPoint) {
log(member.getName() + " unused; ignore");
return currentLevel; // do not propose private for unused method
}
@PsiUtil.AccessLevel
int suggestedLevel = maxLevel.get();
if (suggestedLevel == PsiUtil.ACCESS_LEVEL_PRIVATE && memberClass == null) {
suggestedLevel = suggestPackageLocal(member);
}
String suggestedModifier = PsiUtil.getAccessModifier(suggestedLevel);
log(member.getName() + ": effective level is '" + suggestedModifier + "'");
return suggestedLevel;
}
private boolean handleUsage(@NotNull PsiMember member,
@Nullable PsiClass memberClass,
@NotNull AtomicInteger maxLevel,
@Nullable PsiPackage memberPackage,
@NotNull PsiElement element,
@NotNull PsiFile psiFile,
@NotNull AtomicBoolean foundUsage) {
foundUsage.set(true);
if (!(psiFile instanceof PsiJavaFile)) {
log(" refd from " + psiFile.getName() + "; set to public");
maxLevel.set(PsiUtil.ACCESS_LEVEL_PUBLIC);
return false; // referenced from XML, has to be public
}
@PsiUtil.AccessLevel
int level = getEffectiveLevel(element, psiFile, member, memberClass, memberPackage);
log(" ref in file " + psiFile.getName() + "; level = " + PsiUtil.getAccessModifier(level) + "; (" + element + ")");
maxLevel.getAndAccumulate(level, Math::max);
return level != PsiUtil.ACCESS_LEVEL_PUBLIC;
}
@PsiUtil.AccessLevel
private int getEffectiveLevel(@NotNull PsiElement element,
@NotNull PsiFile file,
@NotNull PsiMember member,
PsiClass memberClass,
PsiPackage memberPackage) {
PsiClass innerClass = PsiTreeUtil.getParentOfType(element, PsiClass.class);
boolean isAbstractMember = member.hasModifierProperty(PsiModifier.ABSTRACT);
if (memberClass != null && PsiTreeUtil.isAncestor(innerClass, memberClass, false) ||
innerClass != null && PsiTreeUtil.isAncestor(memberClass, innerClass, false) && !innerClass.hasModifierProperty(PsiModifier.STATIC)) {
// access from the same file can be via private
// except when used in annotation:
// @Ann(value = C.VAL) class C { public static final String VAL = "xx"; }
// or in implements/extends clauses
if (isInReferenceList(innerClass.getModifierList(), member) ||
isInReferenceList(innerClass.getImplementsList(), member) ||
isInReferenceList(innerClass.getExtendsList(), member)) {
return suggestPackageLocal(member);
}
return !isAbstractMember &&
(myVisibilityInspection.SUGGEST_PRIVATE_FOR_INNERS || !isInnerClass(memberClass)) &&
!calledOnInheritor(element, memberClass)
? PsiUtil.ACCESS_LEVEL_PRIVATE : suggestPackageLocal(member);
}
PsiExpression qualifier = getQualifier(element);
PsiElement resolvedQualifier = qualifier instanceof PsiReference ? ((PsiReference)qualifier).resolve() : null;
if (resolvedQualifier instanceof PsiVariable) {
resolvedQualifier = PsiUtil.resolveClassInClassTypeOnly(((PsiVariable)resolvedQualifier).getType());
}
PsiPackage qualifierPackage = resolvedQualifier == null ? null : getPackage(resolvedQualifier);
PsiPackage aPackage = getPackage(file);
if (samePackages(memberPackage, aPackage) && (qualifierPackage == null || samePackages(qualifierPackage, aPackage))) {
return suggestPackageLocal(member);
}
// can't access protected members via "qualifier.protectedMember = 0;"
if (qualifier != null) return PsiUtil.ACCESS_LEVEL_PUBLIC;
if (innerClass != null && memberClass != null && innerClass.isInheritor(memberClass, true)) {
//access from subclass can be via protected, except for constructors
PsiElement resolved = element instanceof PsiReference ? ((PsiReference)element).resolve() : null;
boolean isConstructor = resolved instanceof PsiClass && element.getParent() instanceof PsiNewExpression
|| resolved instanceof PsiMethod && ((PsiMethod)resolved).isConstructor();
if (!isConstructor) {
return PsiUtil.ACCESS_LEVEL_PROTECTED;
}
}
return PsiUtil.ACCESS_LEVEL_PUBLIC;
}
private boolean calledOnInheritor(@NotNull PsiElement element, PsiClass memberClass) {
PsiExpression qualifier = getQualifier(element);
if (qualifier == null) return false;
PsiClass qClass = PsiUtil.resolveClassInClassTypeOnly(qualifier.getType());
return qClass != null && qClass.isInheritor(memberClass, true);
}
}
@Nullable
private static PsiPackage getPackage(@NotNull PsiElement element) {
PsiFile file = element.getContainingFile();
PsiDirectory directory = file == null ? null : file.getContainingDirectory();
return directory == null ? null : JavaDirectoryService.getInstance().getPackage(directory);
}
private static boolean samePackages(PsiPackage package1, PsiPackage package2) {
return package2 == package1 ||
package2 != null && package1 != null && Comparing.strEqual(package2.getQualifiedName(), package1.getQualifiedName());
}
private static PsiExpression getQualifier(@NotNull PsiElement element) {
PsiExpression qualifier = null;
if (element instanceof PsiReferenceExpression) {
qualifier = ((PsiReferenceExpression)element).getQualifierExpression();
}
else if (element instanceof PsiMethodCallExpression) {
qualifier = ((PsiMethodCallExpression)element).getMethodExpression().getQualifierExpression();
}
return qualifier instanceof PsiThisExpression || qualifier instanceof PsiSuperExpression ? null : qualifier;
}
private static boolean isInnerClass(@NotNull PsiClass memberClass) {
return memberClass.getContainingClass() != null || memberClass instanceof PsiAnonymousClass;
}
private static boolean isConstantField(PsiMember member) {
return member instanceof PsiField &&
member.hasModifierProperty(PsiModifier.STATIC) &&
member.hasModifierProperty(PsiModifier.FINAL) &&
((PsiField)member).hasInitializer();
}
private static boolean isInReferenceList(@Nullable PsiElement list, @NotNull final PsiMember member) {
if (list == null) return false;
final PsiManager psiManager = member.getManager();
final boolean[] result = new boolean[1];
list.accept(new JavaRecursiveElementWalkingVisitor() {
@Override
public void visitReferenceElement(PsiJavaCodeReferenceElement reference) {
super.visitReferenceElement(reference);
if (psiManager.areElementsEquivalent(reference.resolve(), member)) {
result[0] = true;
stopWalking();
}
}
});
return result[0];
}
@PsiUtil.AccessLevel
private int suggestPackageLocal(@NotNull PsiMember member) {
boolean suggestPackageLocal = member instanceof PsiClass && ClassUtil.isTopLevelClass((PsiClass)member)
? myVisibilityInspection.SUGGEST_PACKAGE_LOCAL_FOR_TOP_CLASSES
: myVisibilityInspection.SUGGEST_PACKAGE_LOCAL_FOR_MEMBERS;
return suggestPackageLocal ? PsiUtil.ACCESS_LEVEL_PACKAGE_LOCAL : PsiUtil.ACCESS_LEVEL_PUBLIC;
}
private static void log(String s) {
//System.out.println(s);
}
}
|
package ventures.paramount.phonegap.notificationhub;
import android.app.NotificationManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.microsoft.windowsazure.messaging.NativeRegistration;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.lang.String;
import java.util.Iterator;
public class NotificationHubPlugin extends CordovaPlugin {
public static final String VENTURES_PARAMOUNT_PHONEGAP_NOTIFICATIONHUB = "ventures.paramount.phonegap.notificationhub";
public static final String LOG_TAG = "NotificationHubPlugin";
public static final String INITIALIZE = "init";
public static final String UNREGISTER = "unregister";
public static final String EXIT = "exit";
private static CallbackContext pushContext;
private static CordovaWebView gWebView;
private static String gSenderID;
private static Bundle gCachedExtras = null;
private static boolean gForeground = false;
private static String gCallback = null;
/**
* Gets the application context from cordova's main activity.
* @return the application context
*/
private Context getApplicationContext() {
return this.cordova.getActivity().getApplicationContext();
}
@Override
public boolean execute(String action, JSONArray data, CallbackContext callbackContext) {
boolean result = false;
String hubName = null;
String connectionString = null;
Log.v(LOG_TAG, "execute: action=" + action);
// this will initialize the session, registering and listening for notifications
if (INITIALIZE.equals(action)) {
pushContext = callbackContext;
JSONObject jo = null;
Log.v(LOG_TAG, "execute: data=" + data.toString());
try {
jo = data.getJSONObject(0).getJSONObject("android");
hubName = jo.getString("notificationHubPath");
connectionString = jo.getString("connectionString");
Log.v(LOG_TAG, "execute: notificationHubPath=" + hubName.toString());
Log.v(LOG_TAG, "execute: connectionString=" + connectionString.toString());
// get an instance of the messaging cloud
final GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(cordova.getActivity());
// get an instance of the azure hub
final com.microsoft.windowsazure.messaging.NotificationHub hub =
new com.microsoft.windowsazure.messaging.NotificationHub(hubName, connectionString, cordova.getActivity());
gWebView = this.webView;
Log.v(LOG_TAG, "execute: jo=" + jo.toString());
gSenderID = jo.getString("senderID");
Log.v(LOG_TAG, "execute: senderID=" + gSenderID);
// performs the actual registration
//GCMRegistrar.register(getApplicationContext(), gSenderID);
String gcmId = gcm.register(gSenderID);
Log.v(LOG_TAG, "gcmId=" + gcmId);
// register with the hub
NativeRegistration registrationInfo = hub.register(gcmId);
Log.v(LOG_TAG, "gcmId..getRegistrationId()=" + registrationInfo.getRegistrationId());
Log.v(LOG_TAG, "gcmId..getGCMRegistrationId()=" + registrationInfo.getGCMRegistrationId());
result = true;
} catch (JSONException e) {
Log.e(LOG_TAG, "execute: Got JSON Exception " + e.getMessage());
result = false;
callbackContext.error(e.getMessage());
}
if (jo != null) {
SharedPreferences sharedPref = getApplicationContext().getSharedPreferences(VENTURES_PARAMOUNT_PHONEGAP_NOTIFICATIONHUB, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
try {
editor.putString("icon", jo.getString("icon"));
} catch (JSONException e) {
Log.d(LOG_TAG, "no icon option");
}
try {
editor.putString("iconColor", jo.getString("iconColor"));
} catch (JSONException e) {
Log.d(LOG_TAG, "no iconColor option");
}
editor.putBoolean("sound", jo.optBoolean("sound", true));
editor.putBoolean("vibrate", jo.optBoolean("vibrate", true));
editor.putBoolean("clearNotifications", jo.optBoolean("clearNotifications", true));
editor.commit();
}
if (gCachedExtras != null) {
Log.v(LOG_TAG, "sending cached extras");
sendExtras(gCachedExtras);
gCachedExtras = null;
}
} else if (UNREGISTER.equals(action)) {
JSONObject jo = null;
jo = data.getJSONObject(0).getJSONObject("android");
hubName = jo.getString("notificationHubPath");
connectionString = jo.getString("connectionString");
final com.microsoft.windowsazure.messaging.NotificationHub hub =
new com.microsoft.windowsazure.messaging.NotificationHub(hubName, connectionString, cordova.getActivity());
// get an instance of the messaging cloud
//final GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(cordova.getActivity());
//GCMRegistrar.unregister(getApplicationContext());
hub.unregister();
Log.v(LOG_TAG, "UNREGISTER");
result = true;
callbackContext.success();
} else {
result = false;
Log.e(LOG_TAG, "Invalid action : " + action);
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.INVALID_ACTION));
}
return result;
}
public static void sendEvent(JSONObject _json) {
PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, _json);
pluginResult.setKeepCallback(true);
pushContext.sendPluginResult(pluginResult);
}
public static void sendError(String message) {
PluginResult pluginResult = new PluginResult(PluginResult.Status.ERROR, message);
pluginResult.setKeepCallback(true);
pushContext.sendPluginResult(pluginResult);
}
/*
* Sends the pushbundle extras to the client application.
* If the client application isn't currently active, it is cached for later processing.
*/
public static void sendExtras(Bundle extras) {
if (extras != null) {
if (gWebView != null) {
sendEvent(convertBundleToJson(extras));
} else {
Log.v(LOG_TAG, "sendExtras: caching extras to send at a later time.");
gCachedExtras = extras;
}
}
}
@Override
public void initialize(CordovaInterface cordova, CordovaWebView webView) {
super.initialize(cordova, webView);
gForeground = true;
}
@Override
public void onPause(boolean multitasking) {
super.onPause(multitasking);
gForeground = false;
SharedPreferences prefs = getApplicationContext().getSharedPreferences(NotificationHubPlugin.VENTURES_PARAMOUNT_PHONEGAP_NOTIFICATIONHUB, Context.MODE_PRIVATE);
if (prefs.getBoolean("clearNotifications", true)) {
final NotificationManager notificationManager = (NotificationManager) cordova.getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancelAll();
}
}
@Override
public void onResume(boolean multitasking) {
super.onResume(multitasking);
gForeground = true;
}
@Override
public void onDestroy() {
super.onDestroy();
gForeground = false;
gWebView = null;
}
/*
* serializes a bundle to JSON.
*/
private static JSONObject convertBundleToJson(Bundle extras) {
try {
JSONObject json = new JSONObject();
JSONObject additionalData = new JSONObject();
Iterator<String> it = extras.keySet().iterator();
while (it.hasNext()) {
String key = it.next();
Object value = extras.get(key);
Log.d(LOG_TAG, "key = " + key);
// System data from Android
if (key.equals("from") || key.equals("collapse_key")) {
additionalData.put(key, value);
}
else if (key.equals("foreground")) {
additionalData.put(key, extras.getBoolean("foreground"));
}
else if (key.equals("coldstart")){
additionalData.put(key, extras.getBoolean("coldstart"));
} else if (key.equals("message") || key.equals("body") ||
key.equals("gcm.notification.message") ||
key.equals("gcm.notification.body")) {
json.put("message", value);
} else if (key.equals("title") || key.equals("gcm.notification.title")) {
json.put("title", value);
} else if (key.equals("msgcnt") || key.equals("badge") ||
key.equals("gcm.notification.msgcnt") ||
key.equals("gcm.notification.badge")) {
json.put("count", value);
} else if (key.equals("soundname") || key.equals("sound") ||
key.equals("gcm.notification.soundname") ||
key.equals("gcm.notification.sound")) {
json.put("sound", value);
} else if (key.equals("image") || key.equals("gcm.notification.image")) {
json.put("image", value);
} else if (key.equals("callback")) {
json.put("callback", value);
}
else if ( value instanceof String ) {
String strValue = (String)value;
try {
// Try to figure out if the value is another JSON object
if (strValue.startsWith("{")) {
additionalData.put(key, new JSONObject(strValue));
}
// Try to figure out if the value is another JSON array
else if (strValue.startsWith("[")) {
additionalData.put(key, new JSONArray(strValue));
}
else {
additionalData.put(key, value);
}
} catch (Exception e) {
additionalData.put(key, value);
}
}
} // while
json.put("additionalData", additionalData);
Log.v(LOG_TAG, "extrasToJSON: " + json.toString());
return json;
}
catch( JSONException e) {
Log.e(LOG_TAG, "extrasToJSON: JSON exception");
}
return null;
}
public static boolean isInForeground() {
return gForeground;
}
public static boolean isActive() {
return gWebView != null;
}
}
|
package be.kuleuven.cs.distrinet.chameleon.eclipse.view.dependency;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.ScrolledComposite;
import org.eclipse.swt.custom.StackLayout;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IPartListener;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.ViewPart;
import org.eclipse.zest.core.viewers.AbstractZoomableViewer;
import org.eclipse.zest.core.viewers.GraphViewer;
import org.eclipse.zest.core.viewers.IZoomableWorkbenchPart;
import org.eclipse.zest.core.viewers.ZoomContributionViewItem;
import org.eclipse.zest.core.widgets.ZestStyles;
import org.eclipse.zest.layouts.LayoutStyles;
import org.eclipse.zest.layouts.algorithms.SpringLayoutAlgorithm;
import be.kuleuven.cs.distrinet.chameleon.analysis.AnalysisOptions;
import be.kuleuven.cs.distrinet.chameleon.analysis.OptionGroup;
import be.kuleuven.cs.distrinet.chameleon.analysis.dependency.DefaultDependencyOptionsFactory;
import be.kuleuven.cs.distrinet.chameleon.analysis.dependency.DependencyOptionsFactory;
import be.kuleuven.cs.distrinet.chameleon.analysis.dependency.DependencyResult;
import be.kuleuven.cs.distrinet.chameleon.core.language.Language;
import be.kuleuven.cs.distrinet.chameleon.eclipse.util.Workbenches;
import be.kuleuven.cs.distrinet.chameleon.workspace.Project;
public class DependencyView extends ViewPart implements IZoomableWorkbenchPart {
private final class DependencyControlUpdater implements IPartListener {
@Override
public void partOpened(IWorkbenchPart part) {
}
@Override
public void partDeactivated(IWorkbenchPart part) {
}
@Override
public void partClosed(IWorkbenchPart part) {
}
@Override
public void partBroughtToTop(IWorkbenchPart part) {
}
@Override
public void partActivated(IWorkbenchPart part) {
if(part instanceof IEditorPart) {
Project chameleonProject = Workbenches.chameleonProject(part);
if(chameleonProject != null) {
_project = chameleonProject;
Control control = _stackMap.get(chameleonProject);
if(control == null) {
control = createConfigurationControls(_stack, chameleonProject);
_stackMap.put(chameleonProject, control);
}
((StackLayout)_stack.getLayout()).topControl = control;
}
Display.getDefault().syncExec(new Runnable(){
@Override
public void run() {
_stack.layout(true);
DependencyView.this.controlContainer().layout(true);
}
});
}
}
}
private Map<Project,Control> _stackMap = new HashMap<>();
private Map<Project, AnalysisOptions> _optionsMap = new HashMap<>();
private Project _project;
GraphViewer _viewer;
private Composite _controlContainer;
private Composite controlContainer() {
return _controlContainer;
}
@Override
public void createPartControl(Composite parent) {
_controlContainer = parent;
GridLayout gridLayout = new GridLayout(2,false);
parent.setLayout(gridLayout);
addGraphViewer(parent);
initStack(parent);
registerPartListener();
// parent.addControlListener(new ControlListener(){
// @Override
// public void controlResized(ControlEvent e) {
// int width = ((Composite)e.widget).getBounds().width;
// GridData layoutData = (GridData) _stack.getLayoutData();
// if(layoutData != null) {
// layoutData.widthHint = (int) (0.25 * width);
// @Override
// public void controlMoved(ControlEvent e) {
ZoomContributionViewItem toolbarZoomContributionViewItem = new ZoomContributionViewItem(this);
IActionBars bars = getViewSite().getActionBars();
bars.getMenuManager().add(toolbarZoomContributionViewItem);
}
private void initStack(Composite parent) {
_stack = new Composite(parent, SWT.NONE);
StackLayout layout = new StackLayout();
_stack.setLayout(layout);
_stack.setLayoutData(new GridData(SWT.FILL,SWT.FILL,false,true));
}
private Composite _stack;
private Control createConfigurationControls(Composite parent, Project project) {
final Composite right = new Composite(parent, SWT.NONE);
GridData rightData = new GridData(GridData.FILL,GridData.FILL,true,true);
right.setLayoutData(rightData);
GridLayout rightLayout = new GridLayout();
rightLayout.numColumns = 1;
right.setLayout(rightLayout);
createAnalyzeButton(right);
// new SWTWidgetFactory() {
// @Override
// public Composite parent() {
// return right;
// }.createCheckboxList();
TabFolder folder = new TabFolder(right, SWT.BORDER);
GridData tabFolderGridData = new GridData(GridData.FILL,GridData.FILL,true,true);
folder.setLayoutData(tabFolderGridData);
createTabs(folder, project);
return right;
}
private void createTabs(TabFolder folder,Project project) {
Language language = project.views().get(0).language();
DependencyOptionsFactory plugin = language.plugin(DependencyOptionsFactory.class);
if(plugin == null) {
plugin = new DefaultDependencyOptionsFactory();
}
AnalysisOptions<?,?> options = plugin.createConfiguration();
_optionsMap.put(project, options);
for(OptionGroup group: options.optionGroups()) {
createTab(folder, group, project);
}
options.setContext(project);
}
// private void createSourceTab(TabFolder folder,Project project) {
//// Function<DependencyOptions, List<PredicateSelector>, Nothing> selector = new Function<DependencyOptions, List<PredicateSelector>, Nothing>() {
//// @Override
//// public List<PredicateSelector> apply(DependencyOptions argument) throws Nothing {
//// return (List)argument.sourceOptions();
// String name = "Source";
// _sources.put(project,createTab(folder, selector, name,project));
// private Map<Project,SelectorList> _sources = new HashMap<>();
// private Map<Project,SelectorList> _targets= new HashMap<>();
// private Map<Project,SelectorList> _crossReferences= new HashMap<>();
// private Map<Project,SelectorList> _dependencies= new HashMap<>();
// private Map<Project,Function> _mappers= new HashMap<>();
protected SelectorList createTab(TabFolder folder, OptionGroup group, Project project) {
TabItem tab = new TabItem(folder, SWT.NONE);
tab.setText(group.name());
final ScrolledComposite scroll = new ScrolledComposite(folder, SWT.V_SCROLL);
Composite canvas = new Canvas(scroll,SWT.NONE);
scroll.setContent(canvas);
scroll.setExpandVertical(true);
scroll.setExpandHorizontal(true);
GridLayout layout = new GridLayout();
layout.numColumns = 1;
canvas.setLayout(layout);
canvas.setLayoutData(new GridData(SWT.FILL,SWT.FILL,true,true));
tab.setControl(scroll);
SelectorList optionsTab = new SelectorList(canvas, SWT.NONE, group,project);
final GridData layoutData = new GridData(SWT.FILL,SWT.FILL,true,true);
layoutData.widthHint = scroll.getClientArea().width;
optionsTab.setLayoutData(layoutData);
// canvas.addControlListener(new ControlListener(){
// @Override
// public void controlResized(ControlEvent e) {
// layoutData.widthHint = scroll.getClientArea().width;
// @Override
// public void controlMoved(ControlEvent e) {
return optionsTab;
}
// private void createTargetTab(TabFolder folder,Project project) {
// Function<DependencyOptions, List<PredicateSelector>, Nothing> selector = new Function<DependencyOptions, List<PredicateSelector>, Nothing>() {
// @Override
// public List<PredicateSelector> apply(DependencyOptions argument) throws Nothing {
// return (List)argument.targetOptions();
// String name = "Target";
// _targets.put(project,createTab(folder, selector, name,project));
// private void createCrossReferenceTab(TabFolder folder,Project project) {
// Function<DependencyOptions, List<PredicateSelector>, Nothing> selector = new Function<DependencyOptions, List<PredicateSelector>, Nothing>() {
// @Override
// public List<PredicateSelector> apply(DependencyOptions argument) throws Nothing {
// return (List)argument.crossReferenceOptions();
// String name = "Cross-Reference";
// _crossReferences.put(project,createTab(folder, selector, name,project));
// private void createDependenciesTab(TabFolder folder,Project project) {
// Function<DependencyOptions, List<PredicateSelector>, Nothing> selector = new Function<DependencyOptions, List<PredicateSelector>, Nothing>() {
// @Override
// public List<PredicateSelector> apply(DependencyOptions argument) throws Nothing {
// return (List)argument.dependencyOptions();
// String name = "Dependency";
// _dependencies.put(project,createTab(folder, selector, name,project));
private void registerPartListener() {
IWorkbench workbench = PlatformUI.getWorkbench();
IWorkbenchWindow activeWorkbenchWindow = workbench.getActiveWorkbenchWindow();
IWorkbenchPage activePage = activeWorkbenchWindow.getActivePage();
activePage.addPartListener(new DependencyControlUpdater());
}
// UniversalPredicate sourcePredicate() {
// return _sourceTab.predicate();
// private SelectorList _sourceTab;
// Function mapper() {
// return _mapper;
// private Function _mapper;
// UniversalPredicate targetPredicate() {
// return _targetTab.predicate();
// private SelectorList _targetTab;
// UniversalPredicate crossReferencePredicate() {
// return _crossReferenceTab.predicate();
// private SelectorList _crossReferenceTab;
// UniversalPredicate dependencyPredicate() {
// return _dependencyTab.predicate();
// private SelectorList _dependencyTab;
protected void addGraphViewer(Composite parent) {
_viewer = new GraphViewer(parent, SWT.NONE);
_viewer.getGraphControl().setLayoutData( new GridData( SWT.FILL, SWT.FILL, true, true ) );
_viewer.setContentProvider(new DependencyContentProvider());
_viewer.setLabelProvider(new DependencyLabelProvider());
// Start with an empty model.
_viewer.setInput(new DependencyResult());
SpringLayoutAlgorithm algorithm = new SpringLayoutAlgorithm(
LayoutStyles.NO_LAYOUT_NODE_RESIZING +
ZestStyles.NODES_NO_LAYOUT_ANIMATION
+ ZestStyles.NODES_NO_ANIMATION
);
//// int style = LayoutStyles.NONE;
// int style = LayoutStyles.NO_LAYOUT_NODE_RESIZING;
// CompositeLayoutAlgorithm algorithm = new CompositeLayoutAlgorithm(
// new LayoutAlgorithm[]{
// new DirectedGraphLayoutAlgorithm(style),
// new HorizontalShift(style)
_viewer.setLayoutAlgorithm(algorithm,true);
// The following puts all nodes on top of each other. Rubbish layout.
// _viewer.setLayoutAlgorithm(new DirectedGraphLayoutAlgorithm(LayoutStyles.NO_LAYOUT_NODE_RESIZING),true);
// _viewer.setConnectionStyle(ZestStyles.CONNECTIONS_DIRECTED + ZestStyles.CONNECTIONS_SOLID);
_viewer.applyLayout();
}
protected void createAnalyzeButton(Composite right) {
Button analyze = new Button(right, SWT.PUSH);
GridData analyzeData = new GridData();
analyzeData.horizontalAlignment = GridData.CENTER;
analyze.setLayoutData(analyzeData);
analyze.setText("Analyze");
MouseAdapter mouseAdapter = new MouseAdapter() {
@Override
public void mouseDown(MouseEvent e) {
IEditorInput input = input();
new AnalyseDependencies(_optionsMap.get(_project),DependencyView.this,input).run();
}
};
analyze.addMouseListener(mouseAdapter);
}
IEditorInput input() {
IWorkbenchWindow activeWorkbenchWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
IEditorInput editorInput = activeWorkbenchWindow.getActivePage().getActiveEditor().getEditorInput();
return editorInput;
}
IResource extractSelection(ISelection sel) {
if (!(sel instanceof IStructuredSelection))
return null;
IStructuredSelection ss = (IStructuredSelection) sel;
Object element = ss.getFirstElement();
if (element instanceof IResource)
return (IResource) element;
if (!(element instanceof IAdaptable))
return null;
IAdaptable adaptable = (IAdaptable)element;
Object adapter = adaptable.getAdapter(IResource.class);
return (IResource) adapter;
}
@Override
public void setFocus() {
}
@Override
public AbstractZoomableViewer getZoomableViewer() {
return _viewer;
}
}
|
package kmf.broker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.amqp.rabbit.listener.adapter.MessageListenerAdapter;
public class Broker {
public static final String EVENT_QUEUE_PREFIX = "event_";
public static final String CLIENT_QUEUE_PREFIX = "client_";
public static final String CLIENT_REPLY_QUEUE_PREFIX = "client_reply_";
public static final String MEDIA_PIPELINE_QUEUE_PREFIX = "media_pipeline_";
public static final String PIPELINE_CREATION_QUEUE = "pipeline_creation";
private Logger LOG = LoggerFactory.getLogger(Broker.class);
private static final long TIMEOUT = 1000000;
private CachingConnectionFactory cf;
private RabbitAdmin admin;
private String logId;
private RabbitTemplate template;
public interface BrokerMessageReceiverWithResponse {
public String onMessage(String message);
}
public interface BrokerMessageReceiver {
public void onMessage(String message);
}
public Broker() {
this("");
}
public Broker(String logId) {
this.logId = logId;
}
public void init() {
cf = new CachingConnectionFactory();
admin = new RabbitAdmin(cf);
declarePipelineCreationQueue(admin);
}
private void declarePipelineCreationQueue(RabbitAdmin admin) {
Queue queue = new Queue(PIPELINE_CREATION_QUEUE, true, false, false);
admin.declareQueue(queue);
DirectExchange exchange = new DirectExchange(PIPELINE_CREATION_QUEUE,
true, false);
admin.declareExchange(exchange);
admin.declareBinding(BindingBuilder.bind(queue).to(exchange).with(""));
LOG.debug("[" + logId + "] Queue '" + PIPELINE_CREATION_QUEUE
+ "' declared. Exchange '" + PIPELINE_CREATION_QUEUE
+ "' declared.");
}
public Queue declarePipelineQueue() {
return admin.declareQueue();
}
public Queue declareClientQueue() {
return admin.declareQueue();
}
public RabbitTemplate createClientTemplate() {
Queue queue = admin.declareQueue();
RabbitTemplate template = new RabbitTemplate(cf);
template.setReplyTimeout(TIMEOUT);
template.setReplyQueue(queue);
SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(
cf);
container.setMessageListener(template);
container.setQueueNames(queue.getName());
container.start();
return template;
}
public String declareEventsExchange(String pipeline) {
String exchangeName = EVENT_QUEUE_PREFIX + pipeline;
DirectExchange exchange = new DirectExchange(exchangeName, false, true);
admin.declareExchange(exchange);
LOG.debug("[" + logId + "] Events exchange '" + exchangeName
+ "' declared.");
return exchangeName;
}
public void addMessageReceiver(final String queue,
final BrokerMessageReceiver receiver) {
SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(
cf);
MessageListenerAdapter adapter = new MessageListenerAdapter(
new Object() {
@SuppressWarnings("unused")
protected void onMessage(byte[] message) {
String messageJson = new String(message);
LOG.debug("[" + logId + "] <-- Queue:'" + queue + "' "
+ messageJson);
receiver.onMessage(messageJson);
}
}, "onMessage");
container.setMessageListener(adapter);
container.setQueueNames(queue);
container.start();
LOG.debug("[" + logId + "] Registered receiver '"
+ receiver.getClass().getName() + "' for queue '" + queue);
}
public void addMessageReceiverWithResponse(final String queue,
final BrokerMessageReceiverWithResponse receiver) {
SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(
cf);
MessageListenerAdapter adapter = new MessageListenerAdapter(
new Object() {
@SuppressWarnings("unused")
protected String onMessage(byte[] message) {
String messageJson = new String(message);
LOG.debug("[" + logId + "] <-- Queue:'" + queue + "' "
+ messageJson);
String responseJson = receiver.onMessage(messageJson);
LOG.debug("[" + logId + "] <-- " + responseJson);
return responseJson;
}
}, "onMessage");
container.setMessageListener(adapter);
container.setQueueNames(queue);
container.start();
LOG.debug("[" + logId + "] Registered receiver with response '"
+ receiver.getClass().getName() + "' for queue '" + queue);
}
public void send(String exchange, String routingKey, String message) {
RabbitTemplate template = new RabbitTemplate(cf);
LOG.debug("[" + logId + "] --> Exchange:'" + exchange
+ "' RoutingKey:'" + routingKey + "' " + message);
template.send(exchange, routingKey, new Message(message.getBytes(),
new MessageProperties()));
}
public String sendAndReceive(String exchange, String routingKey,
String message) {
return sendAndReceive(exchange, routingKey, message, null);
}
public String sendAndReceive(String exchange, String routingKey,
String message, RabbitTemplate template) {
if (template == null) {
template = new RabbitTemplate(cf);
template.setReplyTimeout(TIMEOUT);
}
LOG.debug("[" + logId + "]--> Exchange:'" + exchange + "' RoutingKey:'"
+ routingKey + "' " + message);
Message response = template.sendAndReceive(exchange, routingKey,
new Message(message.getBytes(), new MessageProperties()));
if (response == null) {
throw new BrokerException("Timeout waiting a reply to message: "
+ message);
}
String responseAsString = new String(response.getBody());
LOG.debug("[" + logId + "] <-- " + responseAsString);
return responseAsString;
}
public void bindExchangeToQueue(String exchangeId, String queueId,
String eventRoutingKey) {
Queue queue = new Queue(queueId, false, true, true);
DirectExchange exchange = new DirectExchange(exchangeId);
admin.declareBinding(BindingBuilder.bind(queue).to(exchange)
.with(eventRoutingKey));
LOG.debug("[" + logId + "] Exchange '" + exchangeId
+ "' bind to queue '" + queueId + "' with routingKey '"
+ eventRoutingKey + "'");
}
public String createRoutingKey(String mediaElementId, String eventType) {
return mediaElementId + "/" + eventType;
}
public void destroy() {
cf.destroy();
}
}
|
package eventdetection.validator.implementations;
import semilar.config.ConfigManager;
import semilar.data.Sentence;
import semilar.sentencemetrics.LexicalOverlapComparer;
import semilar.sentencemetrics.OptimumComparer;
import semilar.tools.preprocessing.SentencePreprocessor;
import semilar.tools.semantic.WordNetSimilarity;
import semilar.sentencemetrics.PairwiseComparer.NormalizeType;
import semilar.sentencemetrics.PairwiseComparer.WordWeightType;
import semilar.wordmetrics.LSAWordMetric;
import semilar.wordmetrics.WNWordMetric;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Set;
import java.text.*;
import edu.sussex.nlp.jws.*;
import java.util.Properties;
import edu.stanford.nlp.pipeline.StanfordCoreNLP;
import edu.stanford.nlp.ling.CoreAnnotations.*;
import edu.stanford.nlp.semgraph.SemanticGraph;
import edu.stanford.nlp.semgraph.SemanticGraphCoreAnnotations.CollapsedCCProcessedDependenciesAnnotation;
import edu.stanford.nlp.ling.*;
import edu.stanford.nlp.pipeline.Annotation;
import edu.stanford.nlp.util.CoreMap;
import eventdetection.common.Article;
import eventdetection.common.POSTagger;
import eventdetection.common.Query;
import eventdetection.common.Source;
import eventdetection.validator.ValidationResult;
import eventdetection.validator.ValidatorController;
import eventdetection.validator.types.OneToOneValidator;
import eventdetection.validator.types.Validator;
import eventdetection.common.ArticleManager;
import eventdetection.common.DBConnection;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import toberumono.json.JSONArray;
import toberumono.json.JSONObject;
import toberumono.json.JSONSystem;
import toberumono.structures.collections.lists.SortedList;
import toberumono.structures.tuples.Pair;
import toberumono.structures.SortingMethods;
public class SEMILARSemanticAnalysisValidator extends OneToOneValidator {
private static int MAX_SENTENCES = 5;
OptimumComparer optimumComparerWNLin;
OptimumComparer optimumComparerLSATasa;
LexicalOverlapComparer lexicalOverlapComparer; // Just see the lexical overlap.
WNWordMetric wnMetricLin;
/**
* Constructs a new instance of the {@link Validator} for the given {@code ID}, {@link Query}, and {@link Article}
*
* @param query
* the {@link Query} to validate
* @param article
* the {@link Article} against which the {@link Query} is to be validated
*/
public SEMILARSemanticAnalysisValidator(Query query, Article article) {
super(query, article);
/* Word to word similarity expanded to sentence to sentence .. so we need word metrics */
boolean wnFirstSenseOnly = false; //applies for WN based methods only.
wnMetricLin = new WNWordMetric(WordNetSimilarity.WNSimMeasure.LIN, wnFirstSenseOnly);
optimumComparerWNLin = new OptimumComparer(wnMetricLin, 0.3f, false, WordWeightType.NONE, NormalizeType.AVERAGE);
//optimumComparerLSATasa = new OptimumComparer(lsaMetricTasa, 0.3f, false, WordWeightType.NONE, NormalizeType.AVERAGE);
//lexicalOverlapComparer = new LexicalOverlapComparer(false); // use base form of words? - No/false.
}
@Override
public ValidationResult[] call() throws IOException {
Sentence querySentence;
Sentence articleSentence;
SentencePreprocessor preprocessor = new SentencePreprocessor(SentencePreprocessor.TokenizerType.STANFORD, SentencePreprocessor.TaggerType.STANFORD, SentencePreprocessor.StemmerType.PORTER, SentencePreprocessor.ParserType.STANFORD);
SortedList<Pair<Double, CoreMap>> topN = new SortedList<>((a, b) -> b.getX().compareTo(a.getX()));
StringBuilder phrase1 = new StringBuilder();
phrase1.append(query.getSubject()).append(" ").append(query.getVerb());
if (query.getDirectObject() != null && query.getDirectObject().length() > 0)
phrase1.append(" ").append(query.getDirectObject());
if (query.getIndirectObject() != null && query.getIndirectObject().length() > 0)
phrase1.append(" ").append(query.getIndirectObject());
if (query.getLocation() != null && query.getLocation().length() > 0)
phrase1.append(" ").append(query.getLocation());
querySentence = preprocessor.preprocessSentence(phrase1.toString());
Double temp;
String title = article.getAnnotatedTitle().toString();
Sentence articleTitle = preprocessor.preprocessSentence(title);
Double tempTitle = (double) optimumComparerWNLin.computeSimilarity(querySentence, articleTitle);
for (Annotation paragraph : article.getAnnotatedText()) {
List<CoreMap> sentences = paragraph.get(SentencesAnnotation.class);
for (CoreMap sentence : sentences) {
String sen = POSTagger.reconstructSentence(sentence);
articleSentence = preprocessor.preprocessSentence(sen);
temp = (double) optimumComparerWNLin.computeSimilarity(querySentence, articleSentence);
if (temp.equals(Double.NaN))
continue;
topN.add(new Pair<>(temp, sentence));
if (topN.size() > MAX_SENTENCES)
topN.remove(topN.size() - 1);
}
}
double average = 0.0;
for (Pair<Double, CoreMap> p : topN){
average += p.getX();
System.out.println(p.getY().toString() + p.getX());
}
average /= (double) topN.size();
double validation = 0.0;
if (average > 0.15 || tempTitle > 0.15) {
validation = postProcess(topN, query,phrase1.toString(), title, tempTitle);
}
System.out.println("Annotated title: "+ article.getAnnotatedTitle());
System.out.println("ARTICLE ID " + article.getID() + " average: "+average + " title: "+tempTitle);
return new ValidationResult[]{new ValidationResult(article.getID(), validation)};
}
public double postProcess(SortedList<Pair<Double, CoreMap>> topN, Query query, String rawQuery, String articleTitle, double titleScore){
// Julia's dependencies experimentation
// Note: for IndexedWord, value = word = ex "asking", lemma = "ask", tag = "VBG"
/*
for (Annotation paragraph : article.getAnnotatedText()) {
List<CoreMap> sentences = paragraph.get(SentencesAnnotation.class);
for (CoreMap sentence : sentences) {
SemanticGraph dependencies = sentence.get(CollapsedCCProcessedDependenciesAnnotation.class);
System.out.println("\"" + sentence + "\"");
// Get 'first' (usually only) root
IndexedWord root = dependencies.getFirstRoot();
// Get a node's children
Set<IndexedWord> children = dependencies.getChildren(root);
System.out.println("Root: " + root + "\nChildren: " + children);
for (IndexedWord child : children) {
// Get a node's parent
IndexedWord parent = dependencies.getParent(child);
System.out.println("Child " + child + "\tParent " + parent);
}
// Prints out the dependency graph for every sentence
System.out.println("Dependency graph:\n" + dependencies);
// Note: Tried getting words' DependentsAnnotation.class but it returns null
// Use POSList to get nsubj. We can do dobj, etc as well
String posList = dependencies.toPOSList();
String nsubjPattern = "nsubj[^\n]*\n";
//String nsubjPattern = "nsubj(\([^)]*\))";
Pattern nsubjRegex = Pattern.compile(nsubjPattern);
Matcher nsubjMatcher = nsubjRegex.matcher(posList);
if (nsubjMatcher.find()) {
System.out.println("FOUND NSUBJ: " + nsubjMatcher.group(0));
}
else {
System.out.println("NO NSUBJ FOUND");
}
}
}
*/
String subject, dirObject, indirObject;
subject = query.getSubject();
dirObject = "";
if (query.getDirectObject() != null && query.getDirectObject().length() > 0)
dirObject = query.getDirectObject();
if (query.getIndirectObject() != null && query.getIndirectObject().length() > 0)
indirObject = query.getIndirectObject();
// if (query.getLocation() != null && query.getLocation().length() > 0)
// phrase1.append(" ").append(query.getLocation());
// if (query.getLocation() != null && query.getLocation().length() > 0)
// query.getLocation();
ArrayList<String> keywordNouns = new ArrayList<>();
//Annotation taggedQuery = POSTagger.annotate(rawQuery);
// Annotation taggedQuery = POSTagger.tag(annotatedQuery);
Annotation taggedQuery = POSTagger.annotate(rawQuery);
for (CoreLabel token: taggedQuery.get(TokensAnnotation.class)){
String pos = token.get(PartOfSpeechAnnotation.class);
System.out.println("Query tag: "+token + pos);
if (pos.length() > 1 && pos.substring(0,2).equals("NN")){
if (subject.contains(token.get(LemmaAnnotation.class))){
keywordNouns.add(token.get(LemmaAnnotation.class));
}
if (dirObject.contains(token.get(LemmaAnnotation.class))){
keywordNouns.add(token.get(LemmaAnnotation.class));
}
//Can add ind Obj later
}
}
int articleMatchScore = 0;
int matchedPerSentence = 0;
for (Pair<Double, CoreMap> p : topN){ //for each sentence
matchedPerSentence= validationScore(p.getY(), keywordNouns);
if (matchedPerSentence > 0){
System.out.println("SEntence matched "+p.getY());
articleMatchScore += 1;
}
}
Annotation annotatedTitle = POSTagger.annotate(articleTitle);
CoreMap taggedTitle = annotatedTitle.get(SentencesAnnotation.class).get(0);
matchedPerSentence = validationScore(taggedTitle, keywordNouns);
// if (matchedPerSentence > 0 || titleScore>0.20){
// articleMatchScore += 2;
System.out.println("MATCH SCORE: " + articleMatchScore);
//add function here
if (articleMatchScore > 2){ // at least (title + 1/5 sentences) or (3 sentences) or both
return 1.0;
}
return 0.0;
}
public int validationScore(CoreMap sentence, ArrayList<String> keywordNouns){
int matchedPerSentence = 0;
for (CoreLabel token: sentence.get(TokensAnnotation.class)){ //each word in sentence
String pos = token.get(PartOfSpeechAnnotation.class);
String lemma = token.get(LemmaAnnotation.class);
// WE NEED Better Lemmatization
if (pos.length() > 1 && pos.substring(0,2).equals("NN")){
System.out.println(article.getID() +"POS tag for word : " + token + " tag: " + pos + " lemma " + lemma);
for (String imptNoun:keywordNouns){
double matched = 0.0;
if (pos.equals("NNP")){
if (lemma.toLowerCase().equals(imptNoun.toLowerCase())){
matched = 1;
}
} else {
matched = wnMetricLin.computeWordSimilarityNoPos(lemma, imptNoun);
System.out.println("2 words that matched: "+lemma+ " matched with query "+imptNoun+" result: "+matched);
}
if (matched>0.65){
matchedPerSentence += 1;
}
// NOUN is matched
//We would want to look at Verb + adj depending on the matched noun and see if any of them match our query
// Check dependecy Graph
}
}
}
return matchedPerSentence;
}
/**
* Hook for loading properties from the Validator's JSON data
*
* @param properties
* a {@link JSONObject} holding the validator's static properties
*/
public static void loadStaticProperties(JSONObject properties) {
MAX_SENTENCES = (Integer) properties.get("max-sentences").value();
System.out.println("MAX SENTENCE " + MAX_SENTENCES);
}
}
|
package org.jgroups.tests;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.jgroups.*;
import org.jgroups.util.Util;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.LinkedList;
import java.util.List;
/**
* Tests the FLUSH protocol, requires flush-udp.xml in ./conf to be present and configured to use FLUSH
* @author Bela Ban
* @version $Id: FlushTest.java,v 1.5 2006/09/28 17:13:26 vlada Exp $
*/
public class FlushTest extends TestCase {
Channel c1, c2;
static final String CONFIG="flush-udp.xml";
public FlushTest(String name) {
super(name);
}
public void tearDown() throws Exception {
super.tearDown();
if(c2 != null) {
c2.close();
Util.sleep(2000);
c2=null;
}
if(c1 != null) {
c1.close();
Util.sleep(2000);
c1=null;
}
}
public void testSingleChannel() throws ChannelException {
c1=createChannel();
MyReceiver receiver=new MyReceiver("c1");
c1.setReceiver(receiver);
c1.connect("bla");
checkSingleMemberJoinSequence(receiver);
c1.close();
Util.sleep(500);
assertEquals(0, receiver.getEvents().size());
}
public void testTwoChannels() throws ChannelException {
c1=createChannel();
MyReceiver receiver=new MyReceiver("c1");
c1.setReceiver(receiver);
c1.connect("bla");
checkSingleMemberJoinSequence(receiver);
c2=createChannel();
MyReceiver receiver2=new MyReceiver("c2");
c2.setReceiver(receiver2);
c2.connect("bla");
View view=c2.getView();
assertEquals(2, view.size());
Util.sleep(500);
checkExistingMemberAfterJoinSequence(receiver);
checkNewMemberAfterJoinSequence(receiver2);
c2.close();
Util.sleep(500);
checkExistingMemberAfterLeaveSequence(receiver);
}
public void testWithStateTransfer() throws ChannelException {
c1=createChannel();
MyReceiver receiver=new MyReceiver("c1");
c1.setReceiver(receiver);
c1.connect("bla");
c2=createChannel();
MyReceiver receiver2=new MyReceiver("c2");
c2.setReceiver(receiver2);
c2.connect("bla");
Util.sleep(2000);
receiver.clear(); receiver2.clear();
System.out.println("=== fetching the state ====");
c2.getState(null, 10000);
Util.sleep(3000);
List events=receiver.getEvents();
checkBlockStateUnBlockSequence(events, "c1");
events=receiver2.getEvents();
checkBlockStateUnBlockSequence(events, "c2");
}
private void checkBlockStateUnBlockSequence(List events, String name) {
assertNotNull(events);
assertEquals("Should have three events [block,get|setstate,unblock] but " + name + " has "
+ events, 3, events.size());
Object obj=events.remove(0);
assertTrue(name, obj instanceof BlockEvent);
obj=events.remove(0);
assertTrue(name, obj instanceof GetStateEvent || obj instanceof SetStateEvent);
obj=events.remove(0);
assertTrue(name, obj instanceof UnblockEvent);
}
private void checkSingleMemberJoinSequence(MyReceiver receiver) {
List events = receiver.getEvents();
assertNotNull(events);
assertEquals("Should have one event [view] but " +receiver.getName()+" has " + events, 1,events.size());
Object obj = events.remove(0);
assertTrue("should be view instance but it is " + obj,obj instanceof View);
receiver.clear();
}
private void checkExistingMemberAfterJoinSequence(MyReceiver receiver) {
List events = receiver.getEvents();
assertNotNull(events);
assertEquals("Should have three events [block,view,unblock] but " + receiver.getName() + " has "
+ events, 3, events.size());
Object obj = events.remove(0);
assertTrue(obj instanceof BlockEvent);
obj = events.remove(0);
assertTrue("should be a View but is " + obj, obj instanceof View);
obj = events.remove(0);
assertTrue(obj instanceof UnblockEvent);
receiver.clear();
}
private void checkExistingMemberAfterLeaveSequence(MyReceiver receiver)
{
checkExistingMemberAfterJoinSequence(receiver);
}
private void checkNewMemberAfterJoinSequence(MyReceiver receiver)
{
List events = receiver.getEvents();
assertNotNull(events);
assertEquals("Should have two events [view,unblock] but " + receiver.getName() + " has "
+ events, 2, events.size());
Object obj=events.remove(0);
assertTrue("should be a View but is " + obj, obj instanceof View);
obj=events.remove(0);
assertTrue(obj instanceof UnblockEvent);
receiver.clear();
}
private Channel createChannel() throws ChannelException {
Channel ret=new JChannel(CONFIG);
ret.setOpt(Channel.BLOCK, Boolean.TRUE);
return ret;
}
public static Test suite() {
return new TestSuite(FlushTest.class);
}
public static void main(String[] args) {
junit.textui.TestRunner.run(FlushTest.suite());
}
private static class MyReceiver extends ExtendedReceiverAdapter {
List events=new LinkedList();
String name;
public MyReceiver(String name) {
this.name=name;
}
public String getName()
{
return name;
}
public void clear() {
events.clear();
}
public List getEvents() {return new LinkedList(events);}
public void block() {
System.out.println("[" + name + "]: BLOCK");
events.add(new BlockEvent());
}
public void unblock() {
System.out.println("[" + name + "]: UNBLOCK");
events.add(new UnblockEvent());
}
public void viewAccepted(View new_view) {
System.out.println("[" + name + "]: " + new_view);
events.add(new_view);
}
public byte[] getState() {
System.out.println("[" + name + "]: GetStateEvent");
events.add(new GetStateEvent(null, null));
return new byte[]{'b', 'e', 'l', 'a'};
}
public void setState(byte[] state) {
System.out.println("[" + name + "]: SetStateEvent");
events.add(new SetStateEvent(null, null));
}
public void getState(OutputStream ostream) {
System.out.println("[" + name + "]: GetStateEvent streamed");
events.add(new GetStateEvent(null, null));
try {
ostream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void setState(InputStream istream) {
System.out.println("[" + name + "]: SetStateEvent streamed");
events.add(new SetStateEvent(null, null));
try {
istream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
|
package mockit.internal;
import java.io.*;
import java.lang.reflect.*;
import java.net.*;
import java.util.*;
import mockit.*;
import mockit.internal.expectations.*;
import mockit.internal.state.*;
import mockit.internal.util.*;
public final class MockingBridge implements InvocationHandler
{
public static final int RECORD_OR_REPLAY = 1;
public static final int CALL_STATIC_MOCK = 3;
public static final int CALL_INSTANCE_MOCK = 4;
public static final int UPDATE_MOCK_STATE = 5;
public static final int EXIT_REENTRANT_MOCK = 6;
private static final Object[] EMPTY_ARGS = {};
@SuppressWarnings({"UnusedDeclaration"})
public static final MockingBridge MB = new MockingBridge();
public Object invoke(Object mocked, Method method, Object[] args) throws Throwable
{
int targetId = (Integer) args[0];
String mockClassDesc = (String) args[2];
if (
mocked == null && "java/lang/System".equals(mockClassDesc) && wasCalledDuringClassLoading() ||
mocked != null && instanceOfClassThatParticipatesInClassLoading(mocked) && wasCalledDuringClassLoading()
) {
return targetId == UPDATE_MOCK_STATE ? false : Void.class;
}
int mockStateIndex = (Integer) args[7];
if (targetId == UPDATE_MOCK_STATE) {
return TestRun.updateMockState(mockClassDesc, mockStateIndex);
}
else if (targetId == EXIT_REENTRANT_MOCK) {
TestRun.exitReentrantMock(mockClassDesc, mockStateIndex);
return null;
}
String mockName = (String) args[3];
String mockDesc = (String) args[4];
int executionMode = (Integer) args[9];
Object[] mockArgs = extractMockArguments(args);
if (targetId != RECORD_OR_REPLAY) {
int mockIndex = (Integer) args[8];
boolean startupMock = executionMode > 0;
return callMock(
mocked, targetId, mockClassDesc, mockName, mockDesc, mockStateIndex, mockIndex, startupMock, mockArgs);
}
if (TestRun.isInsideNoMockingZone()) {
return Void.class;
}
TestRun.enterNoMockingZone();
try {
int mockAccess = (Integer) args[1];
String genericSignature = (String) args[5];
String exceptions = (String) args[6];
return
RecordAndReplayExecution.recordOrReplay(
mocked, mockAccess, mockClassDesc, mockName + mockDesc, genericSignature, exceptions,
executionMode, mockArgs);
}
finally {
TestRun.exitNoMockingZone();
}
}
private static boolean instanceOfClassThatParticipatesInClassLoading(Object mocked)
{
Class<?> mockedClass = mocked.getClass();
return
mockedClass == File.class || mockedClass == URL.class || mockedClass == FileInputStream.class ||
Vector.class.isInstance(mocked) || Hashtable.class.isInstance(mocked);
}
private static boolean wasCalledDuringClassLoading()
{
StackTraceElement[] st = new Throwable().getStackTrace();
for (int i = 3; i < st.length; i++) {
StackTraceElement ste = st[i];
if ("ClassLoader.java".equals(ste.getFileName()) && "loadClass".equals(ste.getMethodName())) {
return true;
}
}
return false;
}
private static Object[] extractMockArguments(Object[] args)
{
int i = 10;
if (args.length > i) {
Object[] mockArgs = new Object[args.length - i];
System.arraycopy(args, i, mockArgs, 0, mockArgs.length);
return mockArgs;
}
return EMPTY_ARGS;
}
private static Object callMock(
Object mocked, int targetId, String mockClassInternalName, String mockName, String mockDesc,
int mockStateIndex, int mockInstanceIndex, boolean startupMock, Object[] mockArgs)
{
Class<?> mockClass;
Object mock;
if (targetId == CALL_STATIC_MOCK) {
mock = mocked;
String mockClassName = getMockClassName(mockClassInternalName);
mockClass = Utilities.loadClass(mockClassName);
}
else {
assert targetId == CALL_INSTANCE_MOCK;
if (mockInstanceIndex < 0) { // call to instance mock method on mock not yet instantiated
String mockClassName = getMockClassName(mockClassInternalName);
mock = Utilities.newInstance(mockClassName);
}
else if (startupMock) {
mock = TestRun.getStartupMock(mockInstanceIndex);
}
else { // call to instance mock method on mock already instantiated
mock = TestRun.getMock(mockInstanceIndex);
}
mockClass = mock.getClass();
setItFieldIfAny(mockClass, mock, mocked);
}
Class<?>[] paramClasses = Utilities.getParameterTypes(mockDesc);
if (paramClasses.length > 0 && paramClasses[0] == Invocation.class) {
Invocation invocation = TestRun.createMockInvocation(mockClassInternalName, mockStateIndex, mocked);
//noinspection AssignmentToMethodParameter
mockArgs = Utilities.argumentsWithExtraFirstValue(mockArgs, invocation);
}
Object result = Utilities.invoke(mockClass, mock, mockName, paramClasses, mockArgs);
return result;
}
private static String getMockClassName(String mockClassInternalName)
{
return mockClassInternalName.replace('/', '.');
}
private static void setItFieldIfAny(Class<?> mockClass, Object mock, Object mocked)
{
try {
Field itField = mockClass.getDeclaredField("it");
Utilities.setFieldValue(itField, mock, mocked);
}
catch (NoSuchFieldException ignore) {}
}
}
|
package org.eclipse.jetty.websocket.generator;
import java.nio.ByteBuffer;
import org.eclipse.jetty.io.ByteBufferPool;
import org.eclipse.jetty.websocket.frames.BaseFrame;
public abstract class FrameGenerator<T extends BaseFrame>
{
private final ByteBufferPool bufferPool;
protected FrameGenerator(ByteBufferPool bufferPool)
{
this.bufferPool = bufferPool;
}
public ByteBuffer generate(T frame)
{
ByteBuffer framing = ByteBuffer.allocate(16);
byte b;
// Setup fin thru opcode
b = 0x00;
b |= (frame.isFin()?0x80:0x00); // 1000_0000
b |= (frame.isRsv1()?0x40:0x00); // 0100_0000
b |= (frame.isRsv2()?0x20:0x00); // 0010_0000 TODO: validate?
b |= (frame.isRsv3()?0x10:0x00); // 0001_0000 TODO: validate?
b |= (frame.getOpCode().getCode() & 0x0F);
framing.put(b);
// is masked
b = 0x00;
b |= (frame.isMasked()?0x80:0x00);
// payload lengths
int payloadLength = frame.getPayloadLength();
if (payloadLength >= 0x7F)
{
// we have a 64 bit length
b |= 0x7F;
framing.put(b);
framing.putInt(payloadLength);
}
else if (payloadLength >= 0x7E)
{
// we have a 16 bit length
b |= 0x7E;
framing.put(b);
framing.putShort((short)(payloadLength & 0xFFFF));
}
else
{
// we have a 7 bit length
b |= (payloadLength & 0x7F);
framing.put(b);
}
// masking key
if (frame.isMasked())
{
// TODO: figure out maskgen
framing.put(frame.getMask());
}
framing.flip(); // to figure out how many bytes are used
// now the payload itself
int buflen = frame.getPayloadLength() + framing.remaining();
ByteBuffer buffer = ByteBuffer.allocate(buflen);
// TODO: figure out how to get this from a bytebuffer pool
buffer.put(framing);
generatePayload(buffer, frame);
return buffer;
}
public abstract void generatePayload(ByteBuffer buffer, T frame);
protected ByteBufferPool getByteBufferPool()
{
return bufferPool;
}
}
|
package org.eclipse.persistence.internal.jpa.metadata;
import java.lang.reflect.Method;
import java.security.AccessController;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.LinkedHashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.persistence.SharedCacheMode;
import javax.persistence.Embeddable;
import javax.persistence.spi.PersistenceUnitInfo;
import org.eclipse.persistence.descriptors.ClassDescriptor;
import org.eclipse.persistence.dynamic.DynamicClassLoader;
import org.eclipse.persistence.dynamic.DynamicType;
import org.eclipse.persistence.exceptions.ValidationException;
import org.eclipse.persistence.internal.helper.DatabaseField;
import org.eclipse.persistence.internal.helper.DatabaseTable;
import org.eclipse.persistence.internal.jpa.deployment.PersistenceUnitProcessor;
import org.eclipse.persistence.internal.jpa.metadata.accessors.classes.ClassAccessor;
import org.eclipse.persistence.internal.jpa.metadata.accessors.classes.EmbeddableAccessor;
import org.eclipse.persistence.internal.jpa.metadata.accessors.classes.EntityAccessor;
import org.eclipse.persistence.internal.jpa.metadata.accessors.classes.InterfaceAccessor;
import org.eclipse.persistence.internal.jpa.metadata.accessors.classes.MappedSuperclassAccessor;
import org.eclipse.persistence.internal.jpa.metadata.accessors.mappings.DirectCollectionAccessor;
import org.eclipse.persistence.internal.jpa.metadata.accessors.mappings.MappingAccessor;
import org.eclipse.persistence.internal.jpa.metadata.accessors.mappings.RelationshipAccessor;
import org.eclipse.persistence.internal.jpa.metadata.accessors.objects.MetadataAnnotation;
import org.eclipse.persistence.internal.jpa.metadata.accessors.objects.MetadataClass;
import org.eclipse.persistence.internal.jpa.metadata.converters.AbstractConverterMetadata;
import org.eclipse.persistence.internal.jpa.metadata.converters.StructConverterMetadata;
import org.eclipse.persistence.internal.jpa.metadata.listeners.EntityListenerMetadata;
import org.eclipse.persistence.internal.jpa.metadata.MetadataLogger;
import org.eclipse.persistence.internal.jpa.metadata.partitioning.AbstractPartitioningMetadata;
import org.eclipse.persistence.internal.jpa.metadata.queries.NamedQueryMetadata;
import org.eclipse.persistence.internal.jpa.metadata.queries.PLSQLComplexTypeMetadata;
import org.eclipse.persistence.internal.jpa.metadata.queries.SQLResultSetMappingMetadata;
import org.eclipse.persistence.internal.jpa.metadata.sequencing.GeneratedValueMetadata;
import org.eclipse.persistence.internal.jpa.metadata.sequencing.TableGeneratorMetadata;
import org.eclipse.persistence.internal.jpa.metadata.sequencing.SequenceGeneratorMetadata;
import org.eclipse.persistence.internal.jpa.metadata.tables.TableMetadata;
import org.eclipse.persistence.internal.jpa.metadata.xml.XMLEntityMappings;
import org.eclipse.persistence.internal.jpa.metadata.xml.XMLPersistenceUnitDefaults;
import org.eclipse.persistence.internal.jpa.metadata.xml.XMLPersistenceUnitMetadata;
import org.eclipse.persistence.internal.security.PrivilegedAccessHelper;
import org.eclipse.persistence.internal.security.PrivilegedGetDeclaredMethod;
import org.eclipse.persistence.internal.security.PrivilegedMethodInvoker;
import org.eclipse.persistence.internal.sessions.AbstractSession;
import org.eclipse.persistence.jpa.dynamic.JPADynamicTypeBuilder;
import org.eclipse.persistence.sequencing.Sequence;
import org.eclipse.persistence.sequencing.TableSequence;
import org.eclipse.persistence.sessions.DatasourceLogin;
import org.eclipse.persistence.sessions.Project;
/**
* INTERNAL:
* A MetadataProject stores metadata and also helps to facilitate the metadata
* processing.
*
* Key notes:
* - Care should be taken when using Sets to hold metadata and checking their
* equality. In most cases you should be able to us a List or Map since most
* additions to those lists should not occur multiple times for the same
* object. Just be aware of what you are gathering and how. For example, for
* ClassAccessors, they can always be stored in a map keyed on
* accessor.getJavaClassName(). List of mapping accessors is ok as well since
* in most cases we check isProcessed() before calling process on them etc.
* - methods should be preserved in alphabetical order.
*
* @author Guy Pelletier
* @since TopLink EJB 3.0 Reference Implementation
*/
public class MetadataProject {
// Sequencing constants.
public static final String DEFAULT_AUTO_GENERATOR = "SEQ_GEN";
public static final String DEFAULT_TABLE_GENERATOR = "SEQ_GEN_TABLE";
public static final String DEFAULT_SEQUENCE_GENERATOR = "SEQ_GEN_SEQUENCE";
public static final String DEFAULT_IDENTITY_GENERATOR = "SEQ_GEN_IDENTITY";
// Boolean to specify if we should weave fetch groups.
private boolean m_isWeavingFetchGroupsEnabled;
// Boolean to specify if the user intends for the related EMF of this
// project to be shared for multitenants.
private boolean m_multitenantSharedEmf;
// Boolean to specify if the user intends for the related EMF cache of this
// project to be shared for multitenants.
private boolean m_multitenantSharedCache;
// Boolean to specify if we should weave eager relationships.
private boolean m_isWeavingEagerEnabled;
// Boolean to specify if we should weave lazy relationships.
private boolean m_isWeavingLazyEnabled;
// Boolean to specify if we should uppercase all field names.
// @see PersistenceUnitProperties.UPPERCASE_COLUMN_NAMES
private boolean m_forceFieldNamesToUpperCase = true;
// Cache the shared cache mode
private SharedCacheMode m_sharedCacheMode;
private boolean m_isSharedCacheModeInitialized;
// A composite PU processor.
private MetadataProcessor m_compositeProcessor;
// Persistence unit info that is represented by this project.
private PersistenceUnitInfo m_persistenceUnitInfo;
// The session we are currently processing for.
private AbstractSession m_session;
// The logger for the project.
private MetadataLogger m_logger;
// Persistence unit metadata for this project.
private XMLPersistenceUnitMetadata m_persistenceUnitMetadata;
// All owning relationship accessors.
private List<RelationshipAccessor> m_owningRelationshipAccessors;
// All non-owning (mappedBy) relationship accessors.
private List<RelationshipAccessor> m_nonOwningRelationshipAccessors;
// Accessors that map to an Embeddable class
private List<MappingAccessor> m_embeddableMappingAccessors;
// All direct collection accessors.
private List<DirectCollectionAccessor> m_directCollectionAccessors;
// Class accessors that have a customizer.
private List<ClassAccessor> m_accessorsWithCustomizer;
// A linked map of all the entity mappings (XML file representation)
private Map<String, XMLEntityMappings> m_entityMappings;
// Map of mapped-superclasses found in XML for this project/persistence unit.
private Map<String, MappedSuperclassAccessor> m_mappedSuperclasseAccessors;
// All the class accessors for this project (Entities and Embeddables).
private Map<String, ClassAccessor> m_allAccessors;
// The entity accessors for this project
private Map<String, EntityAccessor> m_entityAccessors;
// Contains those embeddables and entities that are VIRTUAL (do not exist)
private Map<String, ClassAccessor> m_virtualClasses;
// The embeddable accessors for this project
private Map<String, EmbeddableAccessor> m_embeddableAccessors;
// Root level embeddable accessors. When we pre-process embeddable
// accessors we need to process them from the root down so as to set
// the correct owning descriptor.
private Map<String, EmbeddableAccessor> m_rootEmbeddableAccessors;
// The interface accessors for this project
private Map<String, InterfaceAccessor> m_interfaceAccessors;
// Class accessors that have their id derived from a relationship.
private Map<String, ClassAccessor> m_accessorsWithDerivedId;
// Query metadata.
private Map<String, NamedQueryMetadata> m_queries;
// SQL result set mapping
private Map<String, SQLResultSetMappingMetadata> m_sqlResultSetMappings;
// Sequencing metadata.
private Map<MetadataClass, GeneratedValueMetadata> m_generatedValues;
private Map<String, TableGeneratorMetadata> m_tableGenerators;
private Map<String, SequenceGeneratorMetadata> m_sequenceGenerators;
// Metadata converters, that is, EclipseLink converters.
private Map<String, AbstractConverterMetadata> m_converters;
// Store PLSQL record and table types by name, to allow reuse.
private Map<String, PLSQLComplexTypeMetadata> m_plsqlComplexTypes;
// Store partitioning policies by name, to allow reuse.
private Map<String, AbstractPartitioningMetadata> m_partitioningPolicies;
// All mappedSuperclass accessors, identity is handled by keying on className.
private Map<String, MappedSuperclassAccessor> m_metamodelMappedSuperclasses;
// All id classes (IdClass and EmbeddedId classes) used through-out the
// persistence unit. We need this list to determine derived id accessors.
private Set<String> m_idClasses;
// Contains a list of all interfaces that are implemented by entities in
// this project/pu.
private Set<String> m_interfacesImplementedByEntities;
// Default listeners that need to be applied to each entity in the
// persistence unit (unless they exclude them).
private Set<EntityListenerMetadata> m_defaultListeners;
/**
* INTERNAL:
* Create and return a new MetadataProject with puInfo as its PersistenceUnitInfo,
* session as its Session and weavingEnabled as its global dynamic weaving state.
* @param puInfo - the PersistenceUnitInfo
* @param session - the Session
* @param weavingEnabled - flag for global dynamic weaving state
*/
public MetadataProject(PersistenceUnitInfo puInfo, AbstractSession session, boolean weaveLazy, boolean weaveEager, boolean weaveFetchGroups, boolean multitenantSharedEmf, boolean multitenantSharedCache) {
m_isSharedCacheModeInitialized = false;
m_persistenceUnitInfo = puInfo;
m_session = session;
m_logger = new MetadataLogger(session);
m_isWeavingEagerEnabled = weaveEager;
m_isWeavingLazyEnabled = weaveLazy;
m_isWeavingFetchGroupsEnabled = weaveFetchGroups;
m_multitenantSharedEmf = multitenantSharedEmf;
m_multitenantSharedCache = multitenantSharedCache;
m_owningRelationshipAccessors = new ArrayList<RelationshipAccessor>();
m_nonOwningRelationshipAccessors = new ArrayList<RelationshipAccessor>();
m_embeddableMappingAccessors = new ArrayList<MappingAccessor>();
m_directCollectionAccessors = new ArrayList<DirectCollectionAccessor>();
m_accessorsWithCustomizer = new ArrayList<ClassAccessor>();
// Using linked collections since their ordering needs to be preserved.
m_entityMappings = new LinkedHashMap<String, XMLEntityMappings>();
m_defaultListeners = new LinkedHashSet<EntityListenerMetadata>();
m_queries = new HashMap<String, NamedQueryMetadata>();
m_sqlResultSetMappings = new HashMap<String, SQLResultSetMappingMetadata>();
m_allAccessors = new HashMap<String, ClassAccessor>();
m_entityAccessors = new HashMap<String, EntityAccessor>();
m_embeddableAccessors = new HashMap<String, EmbeddableAccessor>();
m_rootEmbeddableAccessors = new HashMap<String, EmbeddableAccessor>();
m_interfaceAccessors = new HashMap<String, InterfaceAccessor>();
m_mappedSuperclasseAccessors = new HashMap<String, MappedSuperclassAccessor>();
m_generatedValues = new HashMap<MetadataClass, GeneratedValueMetadata>();
m_tableGenerators = new HashMap<String, TableGeneratorMetadata>();
m_sequenceGenerators = new HashMap<String, SequenceGeneratorMetadata>();
m_converters = new HashMap<String, AbstractConverterMetadata>();
m_partitioningPolicies = new HashMap<String, AbstractPartitioningMetadata>();
m_plsqlComplexTypes = new HashMap<String, PLSQLComplexTypeMetadata>();
m_metamodelMappedSuperclasses = new HashMap<String, MappedSuperclassAccessor>();
m_virtualClasses = new HashMap<String, ClassAccessor>();
m_accessorsWithDerivedId = new HashMap<String, ClassAccessor>();
m_idClasses = new HashSet<String>();
m_interfacesImplementedByEntities = new HashSet<String>();
}
/**
* INTERNAL:
* This method will add the descriptor to the actual EclipseLink project,
* if it has not already been added. This method if called for entities
* and embeddable classes (which are both weavable classes).
*/
protected void addAccessor(ClassAccessor accessor) {
MetadataDescriptor descriptor = accessor.getDescriptor();
// Process the persistence unit meta data (if there is any).
processPersistenceUnitMetadata(descriptor);
// Process and set the parent class (if one is available).
accessor.processParentClass();
// Add the descriptor to the actual EclipseLink Project.
m_session.getProject().addDescriptor(descriptor.getClassDescriptor());
// Keep a map of all the accessors that have been added.
m_allAccessors.put(accessor.getJavaClassName(), accessor);
}
/**
* INTERNAL:
*/
public void addAccessorWithCustomizer(ClassAccessor accessor) {
m_accessorsWithCustomizer.add(accessor);
}
/**
* INTERNAL:
*/
public void addAccessorWithDerivedId(ClassAccessor accessor) {
m_accessorsWithDerivedId.put(accessor.getJavaClassName(), accessor);
}
/**
* INTERNAL:
*/
public void addAlias(String alias, MetadataDescriptor descriptor) {
ClassDescriptor existingDescriptor = m_session.getProject().getDescriptorForAlias(alias);
if (existingDescriptor == null) {
descriptor.setAlias(alias);
m_session.getProject().addAlias(alias, descriptor.getClassDescriptor());
} else {
throw ValidationException.nonUniqueEntityName(existingDescriptor.getJavaClassName(), descriptor.getJavaClassName(), alias);
}
}
/**
* INTERNAL:
* Add a abstract converter metadata to the project. The actual processing
* isn't done until an accessor referencing the converter is processed.
*/
public void addConverter(AbstractConverterMetadata converter) {
// Check for another converter with the same name.
if (converter.shouldOverride(m_converters.get(converter.getName()))) {
m_converters.put(converter.getName(), converter);
}
}
/**
* INTERNAL:
*/
public void addDefaultListener(EntityListenerMetadata defaultListener) {
m_defaultListeners.add(defaultListener);
}
/**
* INTERNAL:
* Store basic collection accessors for later processing and quick look up.
*/
public void addDirectCollectionAccessor(MappingAccessor accessor) {
m_directCollectionAccessors.add((DirectCollectionAccessor) accessor);
}
/**
* INTERNAL:
* Add an embeddable accessor to this project. Assumes the embeddable
* needs to be added. That is, does not check if it already exists and
* cause a merge. The caller is responsible for that.
*/
public void addEmbeddableAccessor(EmbeddableAccessor accessor) {
// Add accessor will apply persistence unit defaults.
addAccessor(accessor);
accessor.getDescriptor().setIsEmbeddable();
m_embeddableAccessors.put(accessor.getJavaClassName(), accessor);
}
/**
* INTERNAL:
*/
public void addEmbeddableMappingAccessor(MappingAccessor accessor) {
m_embeddableMappingAccessors.add(accessor);
}
/**
* INTERNAL:
* Add an entity accessor to this project. Assumes the entity needs to be
* added. That is, does not check if it already exists and cause a merge.
* The caller is responsible for that.
*/
public void addEntityAccessor(EntityAccessor accessor) {
// Add accessor will apply persistence unit defaults.
addAccessor(accessor);
// Grab the implemented interfaces (used when defaulting v1-1 mappings)
m_interfacesImplementedByEntities.addAll(accessor.getJavaClass().getInterfaces());
m_entityAccessors.put(accessor.getJavaClassName(), accessor);
}
/**
* INTERNAL:
* The avoid processing the same mapping file twice (e.g. user may
* explicitly specify the orm.xml file) we store the list of entity
* mappings in a map keyed on their URL.
*/
public void addEntityMappings(XMLEntityMappings entityMappings) {
// Add the new entity mappings file to the list.
m_entityMappings.put(entityMappings.getMappingFileOrURL(), entityMappings);
}
/**
* INTERNAL:
*/
public void addGeneratedValue(GeneratedValueMetadata generatedvalue, MetadataClass entityClass) {
m_generatedValues.put(entityClass, generatedvalue);
}
/**
* INTERNAL:
* Add EmbeddedId and IdClass ids to the project
*/
public void addIdClass(String idClassName) {
m_idClasses.add(idClassName);
}
/**
* INTERNAL:
* Add a InterfaceAccessor to this project.
*/
public void addInterfaceAccessor(InterfaceAccessor accessor) {
m_interfaceAccessors.put(accessor.getJavaClassName(), accessor);
// Add it directly and avoid the persistence unit defaults and stuff for now.
m_session.getProject().addDescriptor(accessor.getDescriptor().getClassDescriptor());
}
/**
* INTERNAL:
* Add a mapped superclass accessor to this project. Assumes the mapped
* superclass needs to be added. That is, does not check if it already
* exists and cause a merge. The caller is responsible for that. At runtime,
* this map will contain mapped superclasses from XML only. The canonical
* model processor will populate all mapped superclasses in this map.
*/
public void addMappedSuperclass(MappedSuperclassAccessor mappedSuperclass) {
// Process and set the parent class (if one is available).
mappedSuperclass.processParentClass();
m_mappedSuperclasseAccessors.put(mappedSuperclass.getJavaClassName(), mappedSuperclass);
}
/**
* INTERNAL:
* The metamodel API requires that descriptors exist for mappedSuperclasses
* in order to obtain their mappings.<p>
* In order to accomplish this, this method that is called from EntityAccessor
* will ensure that the descriptors on all mappedSuperclass accessors
* are setup so that they can be specially processed later in
* MetadataProject.processStage2() - where the m_mappedSuperclassAccessors
* Map is required.
* <p>
* We do not use the non-persisting MAPPED_SUPERCLASS_RESERVED_PK_NAME PK field.
* Normally when the MappedSuperclass is part of an inheritance hierarchy of the form MS->MS->E,
* where there is an PK Id on the root Entity E, we need to add the
* MAPPED_SUPERCLASS_RESERVED_PK_NAME PK field solely for metadata processing to complete.
* Why? because even though we treat MappedSuperclass objects as a RelationalDescriptor - we only persist
* RelationalDescriptor objects that relate to concrete Entities.
* <p>
* This method is referenced by EntityAccessor.addPotentialMappedSuperclass()
* during an initial predeploy() and later during a deploy()
* </p>
* @param accessor - The mappedSuperclass accessor for the field on the mappedSuperclass<p>
* @since EclipseLink 1.2 for the JPA 2.0 Reference Implementation
*/
public void addMetamodelMappedSuperclass(MappedSuperclassAccessor accessor, MetadataDescriptor childDescriptor) {
// Check for an existing entry before proceeding. Metamodel mapped
// superclasses need only (and should only) be added once. This code
// will be called from every entity that inherits from it. There is no
// need to check for className == null here as the mapped superclass
// accessor is always created with a class.
if (! m_metamodelMappedSuperclasses.containsKey(accessor.getJavaClassName())) {
MetadataDescriptor metadataDescriptor = accessor.getDescriptor();
// Set a child entity descriptor on the mapped superclass descriptor.
// This descriptor (and its mapping accessors) will help to resolve
// any generic mapping accessors from the mapped superclass.
metadataDescriptor.setMetamodelMappedSuperclassChildDescriptor(childDescriptor);
// Note: set the back pointer from the MetadataDescriptor back to its' accessor manually before we add accessors
metadataDescriptor.setClassAccessor(accessor);
// Make sure you apply the persistence unit metadata and defaults.
processPersistenceUnitMetadata(metadataDescriptor);
// Need to apply the mapping file defaults (if there is one that loaded this mapped superclass).
if (accessor.getEntityMappings() != null) {
accessor.getEntityMappings().processEntityMappingsDefaults(accessor);
}
// After the pu metadata and defaults have been applied, it is safe to process the access type.
accessor.processAccessType();
// Set the referenceClass for Id mappings
// Generics Handler: Check if the referenceType is not set for Collection accessors
accessor.addAccessors();
// Add the accessor to our custom Map keyed on className for separate processing in stage2
m_metamodelMappedSuperclasses.put(accessor.getJavaClassName(), accessor);
// Fake out a database table and primary key for MappedSuperclasses
// We require string names for table processing that does not actually goto the database.
// There will be no conflict with customer values
// The descriptor is assumed never to be null
metadataDescriptor.setPrimaryTable(new DatabaseTable(MetadataConstants.MAPPED_SUPERCLASS_RESERVED_TABLE_NAME));
/*
* We need to add a PK field to the temporary mappedsuperclass table above - in order to continue processing.
* Note: we add this field only if no IdClass or EmbeddedId attributes are set on or above the MappedSuperclass.
* Both the table name and PK name are not used to actual database writes.
* Check accessor collection on the metadataDescriptor (note: getIdAttributeName() and getIdAttributeNames() are not populated yet - so are unavailable
* 300051: The check for at least one IdAccessor or an EmbeddedIdAccessor requires that the map and field respectively
* are set previously in MetadataDescriptor.addAccessor().
* The checks below will also avoid a performance hit on searching the accessor map directly on the descriptor.
*/
if (!metadataDescriptor.hasIdAccessor() && !metadataDescriptor.hasEmbeddedId()) {
DatabaseField pkField = new DatabaseField(MetadataConstants.MAPPED_SUPERCLASS_RESERVED_PK_NAME);
if (this.useDelimitedIdentifier()) {
pkField.setUseDelimiters(true);
} else if (this.getShouldForceFieldNamesToUpperCase()) {
pkField.useUpperCaseForComparisons(true);
}
metadataDescriptor.addPrimaryKeyField(pkField);
}
/*
* We store our descriptor on the core project for later retrieval by MetamodelImpl.
* Why not on MetadataProject? because the Metadata processing is transient.
* We could set the javaClass on the descriptor for the current classLoader
* but we do not need it until metamodel processing time avoiding a _persistence_new call.
* See MetamodelImpl.initialize()
*/
m_session.getProject().addMappedSuperclass(accessor.getJavaClassName(), metadataDescriptor.getClassDescriptor());
}
}
/**
* INTERNAL:
* Add the partitioning policy by name.
*/
public void addPartitioningPolicy(AbstractPartitioningMetadata policy) {
// Check for another policy with the same name.
if (policy.shouldOverride(m_partitioningPolicies.get(policy.getName()))) {
m_partitioningPolicies.put(policy.getName(), policy);
}
}
/**
* INTERNAL:
* Add the named PLSQL type.
*/
public void addPLSQLComplexType(PLSQLComplexTypeMetadata type) {
// Check for another type with the same name.
if (type.shouldOverride(m_plsqlComplexTypes.get(type.getName()))) {
m_plsqlComplexTypes.put(type.getName(), type);
}
}
/**
* INTERNAL:
* Add a query to the project overriding where necessary.
*/
public void addQuery(NamedQueryMetadata query) {
if (query.shouldOverride(m_queries.get(query.getName()))) {
m_queries.put(query.getName(), query);
}
}
/**
* INTERNAL:
*/
public void addRelationshipAccessor(RelationshipAccessor accessor) {
if (accessor.hasMappedBy()) {
m_nonOwningRelationshipAccessors.add(accessor);
} else {
m_owningRelationshipAccessors.add(accessor);
}
}
/**
* INTERNAL:
* Add a root level embeddable accessor.
*/
public void addRootEmbeddableAccessor(EmbeddableAccessor accessor) {
m_rootEmbeddableAccessors.put(accessor.getJavaClassName(), accessor);
}
/**
* INTERNAL:
* Add a sequence generator metadata to the project. The actual processing
* isn't done till processSequencing is called.
*/
public void addSequenceGenerator(SequenceGeneratorMetadata sequenceGenerator, String defaultCatalog, String defaultSchema) {
String name = sequenceGenerator.getName();
// Check if the sequence generator name uses a reserved name.
if (name.equals(DEFAULT_TABLE_GENERATOR)) {
throw ValidationException.sequenceGeneratorUsingAReservedName(DEFAULT_TABLE_GENERATOR, sequenceGenerator.getLocation());
} else if (name.equals(DEFAULT_IDENTITY_GENERATOR)) {
throw ValidationException.sequenceGeneratorUsingAReservedName(DEFAULT_IDENTITY_GENERATOR, sequenceGenerator.getLocation());
}
// Catalog could be "" or null, need to check for an XML default.
sequenceGenerator.setCatalog(MetadataHelper.getName(sequenceGenerator.getCatalog(), defaultCatalog, sequenceGenerator.getCatalogContext(), m_logger, sequenceGenerator.getLocation()));
// Schema could be "" or null, need to check for an XML default.
sequenceGenerator.setSchema(MetadataHelper.getName(sequenceGenerator.getSchema(), defaultSchema, sequenceGenerator.getSchemaContext(), m_logger, sequenceGenerator.getLocation()));
// Check if the name is used with a table generator.
TableGeneratorMetadata tableGenerator = m_tableGenerators.get(name);
if (tableGenerator != null) {
if (sequenceGenerator.shouldOverride(tableGenerator)) {
m_tableGenerators.remove(name);
} else {
throw ValidationException.conflictingSequenceAndTableGeneratorsSpecified(name, sequenceGenerator.getLocation(), tableGenerator.getLocation());
}
}
for (TableGeneratorMetadata otherTableGenerator : m_tableGenerators.values()) {
if ((tableGenerator != otherTableGenerator) && (otherTableGenerator.getPkColumnValue() != null) && otherTableGenerator.getPkColumnValue().equals(sequenceGenerator.getSequenceName())) { // generator name will be used instead of an empty sequence name / pk column name
// generator name will be used instead of an empty sequence name / pk column name
if (otherTableGenerator.getPkColumnValue().length() > 0) {
throw ValidationException.conflictingSequenceNameAndTablePkColumnValueSpecified(sequenceGenerator.getSequenceName(), sequenceGenerator.getLocation(), otherTableGenerator.getLocation());
}
}
}
// Add the sequence generator if there isn't an existing one or if
// we should override an existing one.
if (sequenceGenerator.shouldOverride(m_sequenceGenerators.get(name))) {
m_sequenceGenerators.put(sequenceGenerator.getName(), sequenceGenerator);
}
}
/**
* INTERNAL:
* Add an sql results set mapping to the project overriding where necessary.
*/
public void addSQLResultSetMapping(SQLResultSetMappingMetadata sqlResultSetMapping) {
if (sqlResultSetMapping.shouldOverride(m_sqlResultSetMappings.get(sqlResultSetMapping.getName()))) {
m_sqlResultSetMappings.put(sqlResultSetMapping.getName(), sqlResultSetMapping);
}
}
/**
* INTERNAL:
* Add a discovered metamodel class to the session.
*/
public void addStaticMetamodelClass(MetadataAnnotation annotation, MetadataClass metamodelClass) {
MetadataClass modelClass = metamodelClass.getMetadataClass((String) annotation.getAttributeString("value"));
m_session.addStaticMetamodelClass(modelClass.getName(), metamodelClass.getName());
}
/**
* INTERNAL:
* Add a table generator metadata to the project. The actual processing
* isn't done till processSequencing is called.
*/
public void addTableGenerator(TableGeneratorMetadata tableGenerator, String defaultCatalog, String defaultSchema) {
// Process the default values.
processTable(tableGenerator, "", defaultCatalog, defaultSchema, tableGenerator);
String generatorName = tableGenerator.getGeneratorName();
// Check if the table generator name uses a reserved name.
if (generatorName.equals(DEFAULT_SEQUENCE_GENERATOR)) {
throw ValidationException.tableGeneratorUsingAReservedName(DEFAULT_SEQUENCE_GENERATOR, tableGenerator.getLocation());
} else if (generatorName.equals(DEFAULT_IDENTITY_GENERATOR)) {
throw ValidationException.tableGeneratorUsingAReservedName(DEFAULT_IDENTITY_GENERATOR, tableGenerator.getLocation());
}
// Check if the generator name is used with a sequence generator.
SequenceGeneratorMetadata otherSequenceGenerator = m_sequenceGenerators.get(generatorName);
if (otherSequenceGenerator != null) {
if (tableGenerator.shouldOverride(otherSequenceGenerator)) {
m_sequenceGenerators.remove(generatorName);
} else {
throw ValidationException.conflictingSequenceAndTableGeneratorsSpecified(generatorName, otherSequenceGenerator.getLocation(), tableGenerator.getLocation());
}
}
for (SequenceGeneratorMetadata sequenceGenerator : m_sequenceGenerators.values()) {
if ((otherSequenceGenerator != sequenceGenerator) && (sequenceGenerator.getSequenceName() != null) && sequenceGenerator.getSequenceName().equals(tableGenerator.getPkColumnValue())) {
// generator name will be used instead of an empty sequence name / pk column name
if (sequenceGenerator.getSequenceName().length() > 0) {
throw ValidationException.conflictingSequenceNameAndTablePkColumnValueSpecified(sequenceGenerator.getSequenceName(), sequenceGenerator.getLocation(), tableGenerator.getLocation());
}
}
}
// Add the table generator if there isn't an existing one or if we
// should override an existing one.
if (tableGenerator.shouldOverride(m_tableGenerators.get(generatorName))) {
m_tableGenerators.put(generatorName, tableGenerator);
}
}
/**
* INTERNAL:
* Add virtual class accessor to the project. A virtual class is one that
* has VIRTUAL access and the class does not exist on the classpath.
*/
public void addVirtualClass(ClassAccessor accessor) {
m_virtualClasses.put(accessor.getJavaClassName(), accessor);
}
/**
* INTERNAL:
* Create the dynamic class using JPA metadata processed descriptors. Called
* at deploy time after all metadata processing has completed.
*/
protected void createDynamicClass(MetadataDescriptor descriptor, Map<String, MetadataDescriptor> virtualEntities, DynamicClassLoader dcl) {
// Build the virtual class only if we have not already done so.
if (! virtualEntities.containsKey(descriptor.getJavaClassName())) {
if (descriptor.isInheritanceSubclass()) {
// Get the parent descriptor.
MetadataDescriptor parentDescriptor = descriptor.getInheritanceParentDescriptor();
// Recursively call up the parents.
createDynamicClass(parentDescriptor, virtualEntities, dcl);
// Create and set the virtual class using the parent class.
descriptor.getClassDescriptor().setJavaClass(dcl.createDynamicClass(descriptor.getJavaClassName(), parentDescriptor.getClassDescriptor().getJavaClass()));
} else {
// Create and set the virtual class on the descriptor
descriptor.getClassDescriptor().setJavaClass(dcl.createDynamicClass(descriptor.getJavaClassName()));
}
// Store the descriptor by java class name.
virtualEntities.put(descriptor.getJavaClassName(), descriptor);
}
}
/**
* INTERNAL:
* Create the dynamic class using JPA metadata processed descriptors. Called
* at deploy time after all metadata processing has completed.
*/
public void createDynamicClasses(ClassLoader loader) {
if (! m_virtualClasses.isEmpty()) {
if (DynamicClassLoader.class.isAssignableFrom(loader.getClass())) {
DynamicClassLoader dcl = (DynamicClassLoader) loader;
// Create the dynamic classes.
Map<String, MetadataDescriptor> dynamicClasses = new HashMap<String, MetadataDescriptor>();
for (ClassAccessor accessor : m_virtualClasses.values()) {
createDynamicClass(accessor.getDescriptor(), dynamicClasses, dcl);
}
// Create the dynamic types.
Map<String, DynamicType> dynamicTypes = new HashMap<String, DynamicType>();
for (MetadataDescriptor descriptor : dynamicClasses.values()) {
createDynamicType(descriptor, dynamicTypes, dcl);
}
} else {
// If we have virtual classes that need creation and we do not
// have a dynamic class loader throw an exception.
throw ValidationException.invalidClassLoaderForDynamicPersistence();
}
}
}
/**
* INTERNAL:
* Create the dynamic types using JPA metadata processed descriptors. Called
* at deploy time after all metadata processing has completed.
*/
protected void createDynamicType(MetadataDescriptor descriptor, Map<String, DynamicType> dynamicTypes, DynamicClassLoader dcl) {
// Build the dynamic class only if we have not already done so.
if (! dynamicTypes.containsKey(descriptor.getJavaClassName())) {
JPADynamicTypeBuilder typeBuilder = null;
if (descriptor.isInheritanceSubclass()) {
// Get the parent descriptor
MetadataDescriptor parentDescriptor = descriptor.getInheritanceParentDescriptor();
// Recursively call up the parents.
createDynamicType(parentDescriptor, dynamicTypes, dcl);
// Create the dynamic type using the parent type.
typeBuilder = new JPADynamicTypeBuilder(dcl, descriptor.getClassDescriptor(), dynamicTypes.get(parentDescriptor.getJavaClassName()));
} else {
// Create the dynamic type
typeBuilder = new JPADynamicTypeBuilder(dcl, descriptor.getClassDescriptor(), null);
}
// Store the type builder by java class name.
dynamicTypes.put(descriptor.getJavaClassName(), typeBuilder.getType());
}
}
/**
* INTERNAL:
* Set if the project should use indirection for lazy relationships.
*/
public void disableWeaving() {
m_isWeavingLazyEnabled = false;
m_isWeavingEagerEnabled = false;
m_isWeavingFetchGroupsEnabled = false;
}
/**
* INTERNAL:
* Return true if an exclude-default-mappings setting have been set for this
* persistence unit.
*/
public boolean excludeDefaultMappings() {
if (m_persistenceUnitMetadata != null) {
return m_persistenceUnitMetadata.excludeDefaultMappings();
}
return false;
}
/**
* INTERNAL:
* Return the accessor for the given class. Could be an entity or an
* embeddable. Note: It may return null.
*/
public ClassAccessor getAccessor(String className) {
return m_allAccessors.get(className);
}
/**
* INTERNAL:
*/
public List<ClassAccessor> getAccessorsWithCustomizer() {
return m_accessorsWithCustomizer;
}
/**
* INTERNAL:
*/
public Collection<ClassAccessor> getAllAccessors() {
return m_allAccessors.values();
}
/**
* INTERNAL:
*/
public MetadataProcessor getCompositeProcessor() {
return m_compositeProcessor;
}
/**
* INTERNAL:
*/
public AbstractConverterMetadata getConverter(String name) {
return m_converters.get(name);
}
/**
* INTERNAL:
*/
public Set<EntityListenerMetadata> getDefaultListeners() {
return m_defaultListeners;
}
/**
* INTERNAL:
* This method will attempt to look up the embeddable accessor for the
* reference class provided. If no accessor is found, null is returned.
*/
public EmbeddableAccessor getEmbeddableAccessor(MetadataClass cls) {
return getEmbeddableAccessor(cls, false);
}
/**
* INTERNAL:
* This method will attempt to look up the embeddable accessor for the
* reference class provided. If no accessor is found, null is returned.
*/
public EmbeddableAccessor getEmbeddableAccessor(MetadataClass cls, boolean checkIsIdClass) {
EmbeddableAccessor accessor = m_embeddableAccessors.get(cls.getName());
if (accessor == null) {
// Before we return null we must make a couple final checks:
// 1 - Check for an Embeddable annotation on the class itself. At
// this point we know the class was not tagged as an embeddable in
// a mapping file and was not included in the list of classes for
// this persistence unit. Its inclusion therefore in the persistence
// unit is through the use of an Embedded annotation or an embedded
// element within a known entity.
// 2 - If checkIsIdClass is true, JPA 2.0 introduced support for
// derived id's where a parent entity's id class may be used within
// a dependants embedded id class. We will treat the id class as
// and embeddable accessor at this point.
// Callers to this method will have to handle the null case if they
// so desire.
if (cls.isAnnotationPresent(Embeddable.class) || (checkIsIdClass && isIdClass(cls))) {
accessor = new EmbeddableAccessor(cls.getAnnotation(Embeddable.class), cls, this);
addEmbeddableAccessor(accessor);
}
}
return accessor;
}
/**
* INTERNAL:
* Return the embeddable accessor with the given classname.
*/
public EmbeddableAccessor getEmbeddableAccessor(String className) {
return m_embeddableAccessors.get(className);
}
/**
* INTERNAL:
* Return the embeddable accessor with the given classname.
*/
public Collection<EmbeddableAccessor> getEmbeddableAccessors() {
return m_embeddableAccessors.values();
}
/**
* INTERNAL:
* Return the entity accessor for the given class name.
*/
public EntityAccessor getEntityAccessor(MetadataClass cls) {
return getEntityAccessor(cls.getName());
}
/**
* INTERNAL:
* Return the entity accessor for the given class name.
*/
public EntityAccessor getEntityAccessor(String className) {
return m_entityAccessors.get(className);
}
/**
* INTERNAL:
*/
public Collection<EntityAccessor> getEntityAccessors() {
return m_entityAccessors.values();
}
/**
* INTERNAL:
*/
public Collection<XMLEntityMappings> getEntityMappings() {
return m_entityMappings.values();
}
/**
* INTERNAL:
* Return the entity accessor for the given class.
*/
public InterfaceAccessor getInterfaceAccessor(String className) {
return m_interfaceAccessors.get(className);
}
/**
* INTERNAL:
* Return the logger used by the processor.
*/
public MetadataLogger getLogger() {
return m_logger;
}
/**
* INTERNAL:
*/
public MappedSuperclassAccessor getMappedSuperclassAccessor(MetadataClass cls) {
return getMappedSuperclassAccessor(cls.getName());
}
/**
* INTERNAL:
*/
public MappedSuperclassAccessor getMappedSuperclassAccessor(String className) {
return m_mappedSuperclasseAccessors.get(className);
}
/**
* INTERNAL:
*/
public Collection<MappedSuperclassAccessor> getMappedSuperclasses() {
return m_mappedSuperclasseAccessors.values();
}
/**
* INTERNAL:
* Returns the collection of metamodel MappedSuperclassAccessors. This
* collection is NOT and should NOT be used for any deployment descriptor
* metadata processing. It is used solely with the metamodel.
* @see getMappedSuperclass(MetadataClass)
* @see getMappedSuperclass(String)
* @see getMappedSuperclasses()
* @since EclipseLink 1.2 for the JPA 2.0 Reference Implementation
*/
public Collection<MappedSuperclassAccessor> getMetamodelMappedSuperclasses() {
return m_metamodelMappedSuperclasses.values();
}
/**
* INTERNAL:
* Return the named partitioning policy.
*/
public AbstractPartitioningMetadata getPartitioningPolicy(String name) {
return m_partitioningPolicies.get(name);
}
/**
* INTERNAL:
* Return the persistence unit default catalog.
*/
protected String getPersistenceUnitDefaultCatalog() {
if (m_persistenceUnitMetadata != null) {
return m_persistenceUnitMetadata.getCatalog();
}
return null;
}
/**
* INTERNAL:
* Return the persistence unit default schema.
*/
protected String getPersistenceUnitDefaultSchema() {
if (m_persistenceUnitMetadata != null) {
return m_persistenceUnitMetadata.getSchema();
}
return null;
}
/**
* INTERNAL:
*/
public PersistenceUnitInfo getPersistenceUnitInfo() {
return m_persistenceUnitInfo;
}
/**
* INTERNAL:
*/
public XMLPersistenceUnitMetadata getPersistenceUnitMetadata() {
return m_persistenceUnitMetadata;
}
/**
* INTERNAL:
* Return the named PLSQL type.
*/
public PLSQLComplexTypeMetadata getPLSQLComplexType(String name) {
return m_plsqlComplexTypes.get(name);
}
/**
* INTERNAL:
* Return the core API Project associated with this MetadataProject.
* @return
* @since EclipseLink 1.2 for the JPA 2.0 Reference Implementation
*/
public Project getProject() {
return m_session.getProject();
}
/**
* INTERNAL:
* Add a root level embeddable accessor. Nested embeddables will be
* pre-processed from their roots down.
* @see processStage1()
*/
public Collection<EmbeddableAccessor> getRootEmbeddableAccessors() {
return m_rootEmbeddableAccessors.values();
}
/**
* INTERNAL:
*/
public AbstractSession getSession() {
return m_session;
}
/**
* INTERNAL:
* This method will return the name of the SharedCacheMode if specified in
* the persistence.xml file. Note, this is a JPA 2.0 feature, therefore,
* this method needs to catch any exception as a result of trying to access
* this information from a JPA 1.0 container.
*/
protected String getSharedCacheModeName() {
if (! m_isSharedCacheModeInitialized) {
try {
Method method = null;
if (PrivilegedAccessHelper.shouldUsePrivilegedAccess()) {
method = (Method) AccessController.doPrivileged(new PrivilegedGetDeclaredMethod(PersistenceUnitInfo.class, "getSharedCacheMode", null));
m_sharedCacheMode = (SharedCacheMode) AccessController.doPrivileged(new PrivilegedMethodInvoker(method, m_persistenceUnitInfo));
} else {
method = PrivilegedAccessHelper.getDeclaredMethod(PersistenceUnitInfo.class, "getSharedCacheMode", null);
m_sharedCacheMode = (SharedCacheMode) PrivilegedAccessHelper.invokeMethod(method, m_persistenceUnitInfo, null);
}
} catch (Throwable exception) {
// Swallow any exceptions, shared cache mode will be null.
m_sharedCacheMode = null;
}
// Set the shared cache mode as initialized to avoid the reflective
// calls over and over again.
m_isSharedCacheModeInitialized = true;
}
return (m_sharedCacheMode == null) ? null : m_sharedCacheMode.name();
}
/**
* INTERNAL:
* Used to uppercase default and user defined column field names
*/
public boolean getShouldForceFieldNamesToUpperCase(){
return m_forceFieldNamesToUpperCase;
}
/**
* INTERNAL:
*/
public List<StructConverterMetadata> getStructConverters(){
List<StructConverterMetadata> structConverters = new ArrayList<StructConverterMetadata>();
for (AbstractConverterMetadata converter : m_converters.values()) {
if (converter.isStructConverter()) {
structConverters.add((StructConverterMetadata) converter);
}
}
return structConverters;
}
/**
* INTERNAL:
* Returns all those classes in this project that are available for
* weaving. This list currently includes entity and embeddables classes.
*/
public Collection<String> getWeavableClassNames() {
return Collections.unmodifiableCollection(m_allAccessors.keySet());
}
/**
* INTERNAL:
*/
public boolean hasConverter(String name) {
return m_converters.containsKey(name);
}
/**
* INTERNAL:
*/
public boolean hasEmbeddable(MetadataClass cls) {
return hasEmbeddable(cls.getName());
}
/**
* INTERNAL:
*/
public boolean hasEmbeddable(String className) {
return m_embeddableAccessors.containsKey(className);
}
/**
* INTERNAL:
*/
public boolean hasEntity(MetadataClass cls) {
return hasEntity(cls.getName());
}
/**
* INTERNAL:
*/
public boolean hasEntity(String className) {
return m_entityAccessors.containsKey(className);
}
/**
* INTERNAL:
*/
public boolean hasEntityThatImplementsInterface(String interfaceName) {
return m_interfacesImplementedByEntities.contains(interfaceName);
}
/**
* INTERNAL:
*/
public boolean hasInterface(MetadataClass cls) {
return m_interfaceAccessors.containsKey(cls.getName());
}
/**
* INTERNAL:
*/
public boolean hasMappedSuperclass(MetadataClass cls) {
return hasMappedSuperclass(cls.getName());
}
/**
* INTERNAL:
*/
public boolean hasMappedSuperclass(String className) {
return m_mappedSuperclasseAccessors.containsKey(className);
}
/**
* INTERNAL:
*/
public boolean hasSharedCacheMode() {
return getSharedCacheModeName() != null;
}
/**
* INTERNAL:
*/
public boolean isIdClass(MetadataClass idClass) {
return m_idClasses.contains(idClass.getName());
}
/**
* INTERNAL:
* Return true if the caching has been specified as ALL in the
* persistence.xml.
*/
public boolean isSharedCacheModeAll() {
return hasSharedCacheMode() && getSharedCacheModeName().equals(SharedCacheMode.ALL.name());
}
/**
* INTERNAL:
* Return true if the caching has been specified as DISABLE_SELECTIVE in the
* persistence.xml. DISABLE_SELECTIVE is the default therefore this will
* also return true if no caching setting was set.
*/
public boolean isSharedCacheModeDisableSelective() {
return (! hasSharedCacheMode()) || getSharedCacheModeName().equals(SharedCacheMode.DISABLE_SELECTIVE.name());
}
/**
* INTERNAL:
* Return true if the caching has been specified as ENABLE_SELECTIVE in the
* persistence.xml.
*/
public boolean isSharedCacheModeEnableSelective() {
return hasSharedCacheMode() && getSharedCacheModeName().equals(SharedCacheMode.ENABLE_SELECTIVE.name());
}
/**
* INTERNAL:
* Return true if the caching has been specified as NONE in the
* persistence.xml.
*/
public boolean isSharedCacheModeNone() {
return hasSharedCacheMode() && getSharedCacheModeName().equals(SharedCacheMode.NONE.name());
}
/**
* INTERNAL:
* Return true if the caching has been specified as UNSPECIFIED in the
* persistence.xml.
*/
public boolean isSharedCacheModeUnspecified() {
return hasSharedCacheMode() && getSharedCacheModeName().equals(SharedCacheMode.UNSPECIFIED.name());
}
/**
* INTERNAL:
* Return if the project should use indirection for eager relationships.
*/
public boolean isWeavingEagerEnabled() {
return m_isWeavingEagerEnabled;
}
/**
* INTERNAL:
* Return if the project should process fetch groups.
*/
public boolean isWeavingFetchGroupsEnabled() {
return m_isWeavingFetchGroupsEnabled;
}
/**
* INTERNAL:
* Return if the project should use indirection for lazy relationships.
*/
public boolean isWeavingLazyEnabled() {
return m_isWeavingLazyEnabled;
}
/**
* INTERNAL:
* Return true if an xml-mapping-metadata-complete setting has been set
* for this persistence unit.
*/
public boolean isXMLMappingMetadataComplete() {
if (m_persistenceUnitMetadata != null) {
return m_persistenceUnitMetadata.isXMLMappingMetadataComplete();
}
return false;
}
/**
* INTERNAL:
* Process the embeddable mapping accessors.
*/
protected void processEmbeddableMappingAccessors() {
for (MappingAccessor mappingAccessor : m_embeddableMappingAccessors) {
if (! mappingAccessor.isProcessed()) {
mappingAccessor.process();
}
}
}
/**
* INTERNAL:
* Process descriptors with IDs derived from relationships. This will also
* complete unfinished validation as well as secondary table processing
* on entity accessors. This method will fast track some relationship
* mappings which is ok since simple primary keys will already have been
* discovered and processed whereas any derived id's and their fast tracking
* to be processed will be handled now.
*/
protected void processAccessorsWithDerivedIDs() {
HashSet<ClassAccessor> processed = new HashSet();
HashSet<ClassAccessor> processing = new HashSet();
for (ClassAccessor classAccessor : m_accessorsWithDerivedId.values()) {
classAccessor.processDerivedId(processing, processed);
}
}
/**
* INTERNAL:
* Process any BasicCollection annotation and/or BasicMap annotation that
* were found. They are not processed till after an id has been processed
* since they rely on one to map the collection table.
*/
public void processDirectCollectionAccessors() {
for (DirectCollectionAccessor accessor : m_directCollectionAccessors) {
accessor.process();
}
}
/**
* INTERNAL:
* This method will iterate through all the entities in the PU and check
* if we should add them to a variable one to one mapping that was either
* defined (incompletely) or defaulted.
*/
protected void processInterfaceAccessors() {
for (EntityAccessor accessor : getEntityAccessors()) {
for (String interfaceClass : accessor.getJavaClass().getInterfaces()) {
if (m_interfaceAccessors.containsKey(interfaceClass)) {
m_interfaceAccessors.get(interfaceClass).addEntityAccessor(accessor);
}
}
}
}
/**
* INTERNAL:
* Process the non-owning relationship accessors. All owning relationshuip
* accessors should be processed. Some non-owning relationships may have
* already been fast tracked to from an element collection containing
* an embeddable (with a non-owning relationship).
*/
protected void processNonOwningRelationshipAccessors() {
for (RelationshipAccessor accessor : m_nonOwningRelationshipAccessors) {
if (! accessor.isProcessed()) {
accessor.process();
}
}
}
/**
* INTERNAL:
* Process the owning relationship accessors. Some may have already been
* processed through the processing of derived id's therefore don't process
* them again.
*/
protected void processOwningRelationshipAccessors() {
for (RelationshipAccessor accessor : m_owningRelationshipAccessors) {
if (! accessor.isProcessed()) {
accessor.process();
}
}
}
/**
* INTERNAL:
* Process any and all persistence unit metadata and defaults to the given
* descriptor. This method for will called for every descriptor belonging
* to this project/persistence unit.
*
*/
protected void processPersistenceUnitMetadata(MetadataDescriptor descriptor) {
// Set the persistence unit meta data (if there is any) on the descriptor.
if (m_persistenceUnitMetadata != null) {
// Persistence unit metadata level annotations are not defaults
// and therefore should not be set on the descriptor.
// Set the persistence unit defaults (if there are any) on the descriptor.
XMLPersistenceUnitDefaults persistenceUnitDefaults = m_persistenceUnitMetadata.getPersistenceUnitDefaults();
if (persistenceUnitDefaults != null) {
descriptor.setDefaultAccess(persistenceUnitDefaults.getAccess());
descriptor.setDefaultSchema(persistenceUnitDefaults.getSchema());
descriptor.setDefaultCatalog(persistenceUnitDefaults.getCatalog());
descriptor.setDefaultTenantDiscriminatorColumns(persistenceUnitDefaults.getTenantDiscriminatorColumns());
descriptor.setIsCascadePersist(persistenceUnitDefaults.isCascadePersist());
// Set any default access methods if specified.
if (persistenceUnitDefaults.hasAccessMethods()) {
descriptor.setDefaultAccessMethods(persistenceUnitDefaults.getAccessMethods());
}
}
}
}
/**
* INTERNAL:
* Process the named native queries we found and add them to the given
* session.
*/
public void processQueries(ClassLoader loader) {
// Step 1 - process the sql result set mappings first.
for (SQLResultSetMappingMetadata sqlResultSetMapping : m_sqlResultSetMappings.values()) {
sqlResultSetMapping.process(m_session, loader, this);
}
// Step 2 - process the named queries second, some may need to validate
// a sql result set mapping specification.
for (NamedQueryMetadata query : m_queries.values()) {
query.process(m_session, loader, this);
}
}
/**
* INTERNAL:
* Process the sequencing information. At this point, through validation, it
* is not possible to have:
* 1 - a table generator with the generator name equal to
* DEFAULT_SEQUENCE_GENERATOR or DEFAULT_IDENTITY_GENERATOR
* 2 - a sequence generator with the name eqaul to DEFAULT_TABLE_GENERATOR
* or DEFAULT_IDENTITY_GENERATOR
* 3 - you can't have both a sequence generator and a table generator with
* the same DEFAULT_AUTO_GENERATOR name.
*
* @see addTableGenerator and addSequenceGenerator.
*/
protected void processSequencingAccessors() {
if (! m_generatedValues.isEmpty()) {
// 1 - Build our map of sequences keyed on generator names.
Hashtable<String, Sequence> sequences = new Hashtable<String, Sequence>();
for (SequenceGeneratorMetadata sequenceGenerator : m_sequenceGenerators.values()) {
sequences.put(sequenceGenerator.getName(), sequenceGenerator.process(m_logger));
}
for (TableGeneratorMetadata tableGenerator : m_tableGenerators.values()) {
sequences.put(tableGenerator.getGeneratorName(), tableGenerator.process(m_logger));
}
// 2 - Check if the user defined default generators, otherwise
// create them using the Table and Sequence generator metadata.
if (! sequences.containsKey(DEFAULT_TABLE_GENERATOR)) {
TableGeneratorMetadata tableGenerator = new TableGeneratorMetadata(DEFAULT_TABLE_GENERATOR);
// This will go through the same table defaulting as all other
// tables (table, secondary table, join table etc.) in the PU.
// Here the default table name should come from the platform
// SEQUENCE for Symfoware). We should always try to avoid making
// metadata changes after processing and ensure we always
// process with the correct and necessary metadata.
Sequence seq = m_session.getDatasourcePlatform().getDefaultSequence();
String defaultTableGeneratorName = (seq instanceof TableSequence) ? ((TableSequence) seq).getTableName() : DEFAULT_TABLE_GENERATOR;
// Process the default values.
processTable(tableGenerator, defaultTableGeneratorName, getPersistenceUnitDefaultCatalog(), getPersistenceUnitDefaultSchema(), tableGenerator);
sequences.put(DEFAULT_TABLE_GENERATOR, tableGenerator.process(m_logger));
}
if (! sequences.containsKey(DEFAULT_SEQUENCE_GENERATOR)) {
sequences.put(DEFAULT_SEQUENCE_GENERATOR, new SequenceGeneratorMetadata(DEFAULT_SEQUENCE_GENERATOR, getPersistenceUnitDefaultCatalog(), getPersistenceUnitDefaultSchema()).process(m_logger));
}
if (! sequences.containsKey(DEFAULT_IDENTITY_GENERATOR)) {
sequences.put(DEFAULT_IDENTITY_GENERATOR, new SequenceGeneratorMetadata(DEFAULT_IDENTITY_GENERATOR, 1, getPersistenceUnitDefaultCatalog(), getPersistenceUnitDefaultSchema(), true).process(m_logger));
}
// Use a temporary sequence generator to build a qualifier to set on
// the default generator. Don't use this generator as the default
// auto generator though.
SequenceGeneratorMetadata tempGenerator = new SequenceGeneratorMetadata(DEFAULT_AUTO_GENERATOR, getPersistenceUnitDefaultCatalog(), getPersistenceUnitDefaultSchema());
DatasourceLogin login = m_session.getProject().getLogin();
login.getDefaultSequence().setQualifier(tempGenerator.processQualifier());
// 3 - Loop through generated values and set sequences for each.
for (MetadataClass entityClass : m_generatedValues.keySet()) {
// Skip setting sequences if our accessor is null, must be a mapped superclass
ClassAccessor accessor = m_allAccessors.get(entityClass.getName());
if (accessor != null) {
m_generatedValues.get(entityClass).process(accessor.getDescriptor(), sequences, login);
}
}
}
}
/**
* Process the partitioning metedata and add the PartitioningPolicys to the project.
*/
protected void processPartitioning() {
for (AbstractPartitioningMetadata metadata : m_partitioningPolicies.values()) {
m_session.getProject().addPartitioningPolicy(metadata.buildPolicy());
}
}
/**
* INTERNAL:
* Stage 1 processing is a pre-processing stage that will perform the
* following tasks:
* - gather a list of mapping accessors for all entities and embeddables.
* - discover all global converter specifications.
* - discover mapped superclasses and inheritance parents.
*
* NOTE: This method should only perform any preparatory work like, class
* discovery, flag settings etc. Hard processing will begin in stage 2.
*
* @see processStage2
*/
public void processStage1() {
// 1 - Pre-process the entities first. This will also pre-process
// the mapped superclasses and build/add/complete our list of
// embeddables that will be pre-processed in step 2 below. This is
// necessary so that we may gather our list of id classes which may be
// referenced in embeddable classes as part of a mapped by id accessor.
// This will avoid more complicated processing and ease in building the
// correct accessor at buildAccessor time.
for (EntityAccessor entity : getEntityAccessors()) {
if (! entity.isPreProcessed()) {
entity.preProcess();
}
}
// 2 - Pre-process the embeddables. This will also pre-process any and
// all nested embeddables as well. Embeddables must be processed from
// the root down.
for (EmbeddableAccessor embeddable : getRootEmbeddableAccessors()) {
if (! embeddable.isPreProcessed()) {
embeddable.preProcess();
}
}
}
/**
* INTERNAL:
* Stage 2 processing will perform the following tasks:
* - process all direct mapping accessors from entities, embeddables and
* mapped superclasses.
* - gather a list of relationship accessors and any other special interest
* accessors to be processed in stage 3.
*
* @see processStage3
*/
public void processStage2() {
// 266912: process mappedSuperclasses separately from entity descriptors
for (MappedSuperclassAccessor msAccessor : m_metamodelMappedSuperclasses.values()) {
if (! msAccessor.isProcessed()) {
msAccessor.processMetamodelDescriptor();
}
}
for (EntityAccessor entity : getEntityAccessors()) {
// If the accessor hasn't been processed yet, then process it. An
// EntityAccessor may get fast tracked if it is an inheritance
// parent.
if (! entity.isProcessed()) {
entity.process();
}
}
for (EmbeddableAccessor embeddable : getEmbeddableAccessors()) {
// If the accessor hasn't been processed yet, then process it. An
// EmbeddableAccessor is normally fast tracked if it is a reference.
if (! embeddable.isProcessed()) {
embeddable.process();
}
}
}
/**
* INTERNAL:
* Stage 3 processing does all the extra processing that couldn't be
* completed in the first two stages of processing. The biggest thing
* being that all entities will have processed an id by now and we can
* process those accessors that rely on them. NOTE: The order of invocation
* here is very important here, see the comments.
*/
public void processStage3(PersistenceUnitProcessor.Mode mode) {
if (mode == PersistenceUnitProcessor.Mode.ALL || mode == PersistenceUnitProcessor.Mode.COMPOSITE_MEMBER_MIDDLE) {
// 1 - Process accessors with IDs derived from relationships. This will
// finish up any stage2 processing that relied on the PK processing
// being complete as well. Note: some relationships mappings may be
// processed in this stage. This is ok since it is to determine and
// validate the primary key.
processAccessorsWithDerivedIDs();
// 2 - Process all the direct collection accessors we found. This list
// does not include direct collections to an embeddable class.
processDirectCollectionAccessors();
// 3 - Process the sequencing metadata now that every entity has a
// validated primary key.
processSequencingAccessors();
// 4 - Process the owning relationship accessors now that every entity
// has a validated primary key and we can process join columns.
processOwningRelationshipAccessors();
// 5 - Process the embeddable mapping accessors. These are the
// embedded, embedded id and element collection accessors that map
// to an embeddable class. We must hold off on their processing till
// now to ensure their owning relationship accessors have been processed
// and we can therefore process any association overrides correctly.
processEmbeddableMappingAccessors();
// composite persistence unit case
if (getCompositeProcessor() != null) {
for (EmbeddableAccessor accessor : getEmbeddableAccessors()) {
if (! accessor.isProcessed()) {
accessor.process();
}
}
}
}
if (mode == PersistenceUnitProcessor.Mode.ALL || mode == PersistenceUnitProcessor.Mode.COMPOSITE_MEMBER_FINAL) {
// 6 - Process the non owning relationship accessors now that every
// owning relationship should be fully processed.
processNonOwningRelationshipAccessors();
// 7 - Process the interface accessors which will iterate through all
// the entities in the PU and check if we should add them to a variable
// one to one mapping that was either defined (incompletely) or
// defaulted.
processInterfaceAccessors();
processPartitioning();
}
}
/**
* INTERNAL:
* Common table processing for table, secondary table, join table,
* collection table and table generators
*/
public void processTable(TableMetadata table, String defaultName, String defaultCatalog, String defaultSchema, ORMetadata owner) {
// Name could be "" or null, need to check against the default name.
String name = MetadataHelper.getName(table.getName(), defaultName, table.getNameContext(), m_logger, owner.getAccessibleObject());
// Catalog could be "" or null, need to check for an XML default.
String catalog = MetadataHelper.getName(table.getCatalog(), defaultCatalog, table.getCatalogContext(), m_logger, owner.getAccessibleObject());
// Schema could be "" or null, need to check for an XML default.
String schema = MetadataHelper.getName(table.getSchema(), defaultSchema, table.getSchemaContext(), m_logger, owner.getAccessibleObject());
// Build a fully qualified name and set it on the table.
// schema, attach it if specified
String tableName = new String(name);
if (! schema.equals("")) {
tableName = schema + "." + tableName;
}
// catalog, attach it if specified
if (! catalog.equals("")) {
tableName = catalog + "." + tableName;
}
table.setFullyQualifiedTableName(tableName);
if (useDelimitedIdentifier()){
table.setUseDelimiters(useDelimitedIdentifier());
}
table.getDatabaseTable().setCreationSuffix(table.getCreationSuffix());
// Process the unique constraints.
table.processUniqueConstraints();
}
/**
* INTERNAL:
* Used from the canonical model generator. Specifically when the user
* removes the embeddable designation or changes the embeddable to either
* a mapped superclass or entity.
*/
public void removeEmbeddableAccessor(MetadataClass metadataClass) {
m_allAccessors.remove(metadataClass.getName());
m_embeddableAccessors.remove(metadataClass.getName());
}
/**
* INTERNAL:
* Used from the canonical model generator. Specifically when the user
* removes the entity designation or changes the entity to either
* a mapped superclass or embeddable.
*/
public void removeEntityAccessor(MetadataClass metadataClass) {
m_allAccessors.remove(metadataClass.getName());
m_entityAccessors.remove(metadataClass.getName());
}
/**
* INTERNAL:
* Used from the canonical model generator. Specifically when the user
* removes the mapped superclass designation or changes the mapped
* superclass to either an entity or embeddable.
*/
public void removeMappedSuperclassAccessor(MetadataClass metadataClass) {
m_mappedSuperclasseAccessors.remove(metadataClass.getName());
}
/**
* INTERNAL:
* When at least one entity is found that is multitenant, we turn off
* native SQL queries.
*/
public void setAllowNativeSQLQueries(boolean allowNativeSQLQueries) {
getProject().setAllowNativeSQLQueries(allowNativeSQLQueries);
}
/**
* INTERNAL:
* set compositeProcessor that owns this and pear MetadataProcessors used to create composite persistence unit.
*/
public void setCompositeProcessor(MetadataProcessor compositeProcessor) {
m_compositeProcessor = compositeProcessor;
}
/**
* INTERNAL:
*/
public void setPersistenceUnitMetadata(XMLPersistenceUnitMetadata persistenceUnitMetadata) {
// Set the persistence unit metadata if null otherwise try to merge.
if (m_persistenceUnitMetadata == null) {
m_persistenceUnitMetadata = persistenceUnitMetadata;
} else {
m_persistenceUnitMetadata.merge(persistenceUnitMetadata);
}
}
/**
* INTERNAL:
* Used to uppercase default and user defined column field names
*/
public void setShouldForceFieldNamesToUpperCase(boolean shouldForceFieldNamesToUpperCase){
m_forceFieldNamesToUpperCase = shouldForceFieldNamesToUpperCase;
}
/**
* INTERNAL:
*/
@Override
public String toString() {
return "Project[" + getPersistenceUnitInfo().getPersistenceUnitName() + "]";
}
/**
* INTERNAL:
*/
public boolean useDelimitedIdentifier() {
return m_persistenceUnitMetadata != null && m_persistenceUnitMetadata.isDelimitedIdentifiers();
}
/**
* INTERNAL:
* Return true if the entity manager factory cache for this project is
* intended to be shared amongst multitenants.
*/
public boolean usesMultitenantSharedCache() {
return m_multitenantSharedCache;
}
/**
* INTERNAL:
* Return true if the entity manager factory for this project is intended
* to be shared amongst multitenants.
*/
public boolean usesMultitenantSharedEmf() {
return m_multitenantSharedEmf;
}
}
|
package Common.src;
import java.io.File;
import java.io.FileNotFoundException;
import java.nio.file.Paths;
import java.util.Scanner;
import org.json.JSONException;
import org.json.JSONObject;
public class Configuration {
public String HOST;
public int PORT;
public Configuration() {
String path = Paths.get(".").toAbsolutePath().normalize().toString();
try {
@SuppressWarnings("resource")
String content = new Scanner(new File(path + "/" + "config.json")).useDelimiter("\\Z").next();
JSONObject obj = new JSONObject(content);
HOST = obj.getString("HOST");
PORT = obj.getInt("PORT");
} catch (FileNotFoundException | JSONException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Configuration config = new Configuration();
System.out.println(config.HOST + ":" + config.PORT);
}
}
|
package io.sniffy;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import io.sniffy.configuration.SniffyConfiguration;
import io.sniffy.registry.ConnectionsRegistry;
import io.sniffy.registry.ConnectionsRegistryStorage;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.instrument.Instrumentation;
import java.net.InetSocketAddress;
import static io.sniffy.util.StringUtil.splitByLastSlashAndDecode;
public class SniffyAgent {
public static final String CONNECTION_REGISTRY_URI_PREFIX = "/connectionregistry/";
public static final String SOCKET_REGISTRY_URI_PREFIX = "/connectionregistry/socket/";
public static final String DATASOURCE_REGISTRY_URI_PREFIX = "/connectionregistry/datasource/";
public static final String PERSISTENT_REGISTRY_URI_PREFIX = "/connectionregistry/persistent/";
private static HttpServer server;
public static void main(String[] args) throws Exception {
premain("5555", null);
}
public static void premain(String args, Instrumentation instrumentation) throws Exception {
int port = 5555;
if (args.contains(",") || args.contains("=")) {
String[] parameters = args.split(",");
for (String parameter : parameters) {
String[] kvSplit = parameter.split("=");
if (kvSplit.length == 2) {
if (kvSplit[0].equals("monitorNio")) {
boolean monitorNioEnabled = Boolean.parseBoolean(kvSplit[1]);
SniffyConfiguration.INSTANCE.setMonitorNio(monitorNioEnabled);
} else if (kvSplit[0].equals("sniffyPort")) {
port = Integer.parseInt(kvSplit[1]);
}
}
}
} else {
port = Integer.parseInt(args);
}
SniffyConfiguration.INSTANCE.setMonitorSocket(true);
Sniffy.initialize();
startServer(port);
}
protected static void startServer(int port) throws IOException {
server = HttpServer.create(new InetSocketAddress(port), 0);
server.createContext("/", new MyHandler());
server.setExecutor(null); // creates a default executor
server.start();
}
protected static void stopServer() {
server.stop(1);
}
static class MyHandler implements HttpHandler {
@Override
public void handle(HttpExchange httpExchange) throws IOException {
String path = httpExchange.getRequestURI().toString();
if (path.equals(CONNECTION_REGISTRY_URI_PREFIX)) {
addCorsHeaders(httpExchange);
httpExchange.getResponseHeaders().add("Content-Type", "application/json");
httpExchange.sendResponseHeaders(200, 0);
ConnectionsRegistry.INSTANCE.writeTo(httpExchange.getResponseBody(), "UTF-8");
httpExchange.getResponseBody().close();
} else if (path.startsWith(CONNECTION_REGISTRY_URI_PREFIX)) {
addCorsHeaders(httpExchange);
Integer status = null;
if ("POST".equalsIgnoreCase(httpExchange.getRequestMethod())) {
try {
status = Integer.parseInt(new BufferedReader(new InputStreamReader(httpExchange.getRequestBody())).readLine());
} catch (Exception e) {
status = 0;
}
} else if ("DELETE".equalsIgnoreCase(httpExchange.getRequestMethod())) {
status = -1;
}
if (path.startsWith(SOCKET_REGISTRY_URI_PREFIX)) {
String connectionString = path.substring(SOCKET_REGISTRY_URI_PREFIX.length());
String[] split = splitByLastSlashAndDecode(connectionString);
ConnectionsRegistry.INSTANCE.setSocketAddressStatus(split[0], Integer.parseInt(split[1]), status);
} else if (path.startsWith(DATASOURCE_REGISTRY_URI_PREFIX)) {
String connectionString = path.substring(DATASOURCE_REGISTRY_URI_PREFIX.length());
String[] split = splitByLastSlashAndDecode(connectionString);
ConnectionsRegistry.INSTANCE.setDataSourceStatus(split[0], split[1], status);
} else if (path.startsWith(PERSISTENT_REGISTRY_URI_PREFIX)) {
if (null != status && status >= 0) {
ConnectionsRegistry.INSTANCE.setPersistRegistry(true);
ConnectionsRegistryStorage.INSTANCE.storeConnectionsRegistry(ConnectionsRegistry.INSTANCE);
} else {
ConnectionsRegistry.INSTANCE.setPersistRegistry(false);
}
}
httpExchange.sendResponseHeaders(201, 0);
httpExchange.getResponseBody().close();
} else {
String resourceName =
path.startsWith("/webjars/") ? "/web/META-INF/resources" + path :
"/web" + ("/".equals(path) ? "/index.html" : path);
InputStream inputStream = SniffyAgent.class.getResourceAsStream(resourceName);
if (null != inputStream) {
httpExchange.getResponseHeaders().add("Content-Type", getMimeType(resourceName));
httpExchange.sendResponseHeaders(200, 0);
byte[] buff = new byte[1024];
int read;
while (-1 != (read = inputStream.read(buff))) {
httpExchange.getResponseBody().write(buff, 0, read);
}
httpExchange.getResponseBody().close();
} else {
httpExchange.sendResponseHeaders(404, 0);
httpExchange.getResponseBody().close();
}
}
}
private String getMimeType(String resourceName) {
if (resourceName.endsWith(".html")) {
return "text/html";
} else if (resourceName.endsWith(".ico")) {
return "image/x-icon";
} else if (resourceName.endsWith(".png")) {
return "image/png";
} else if (resourceName.endsWith(".js")) {
return "application/javascript";
} else if (resourceName.endsWith(".css")) {
return "text/css";
} else {
return "application/octet-stream";
}
}
private void addCorsHeaders(HttpExchange httpExchange) {
// TODO: do we need CORS headers (or at least some of them like Sniffy-Inject-Html-Enabled) in agent?
Headers headers = httpExchange.getResponseHeaders();
headers.add("Access-Control-Allow-Origin", "*");
headers.add("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
headers.add("Access-Control-Allow-Headers", "Sniffy-Enabled,Sniffy-Inject-Html-Enabled,X-Requested-With,Content-Type");
headers.add("Access-Control-Max-Age", "86400");
headers.add("Access-Control-Allow-Credentials", "true");
}
}
}
|
package au.com.centrumsystems.hudson.plugin.buildpipeline;
import hudson.EnvVars;
import hudson.model.Item;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.Hudson;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import au.com.centrumsystems.hudson.plugin.util.BuildUtil;
import au.com.centrumsystems.hudson.plugin.util.HudsonResult;
import au.com.centrumsystems.hudson.plugin.util.ProjectUtil;
/**
* @author KevinV
*
*/
public class PipelineBuild {
/** Represents the current build*/
private AbstractBuild<?, ?> currentBuild;
/** Represents the current project*/
private AbstractProject<?, ?> project;
/** Represents the upstream build*/
private AbstractBuild<?, ?> upstreamBuild;
/**
* Contains the upstreamBuild result.
* Can be one of the following:
* - BUILDING
* - SUCCESS
* - FAILURE
* - UNSTABLE
* - NOT_BUILT
* - ABORT
* - PENDING
* - MANUAL
*/
private String upstreamBuildResult;
/**
* Contains the currentBuild result.
* Can be one of the following:
* - BUILDING
* - SUCCESS
* - FAILURE
* - UNSTABLE
* - NOT_BUILT
* - ABORT
* - PENDING
* - MANUAL
*/
private String currentBuildResult;
/** A Logger object is used to log messages */
private static final Logger LOGGER = Logger.getLogger(PipelineBuild.class.getName());
/**
* Default constructor
*/
public PipelineBuild() {
}
/**
* Creates a new PipelineBuild with currentBuild, project and upstreamBuild set.
* @param build - current build
* @param project - current project
* @param previousBuild - upstream build
*/
public PipelineBuild(AbstractBuild<?, ?> build, AbstractProject<?, ?> project, AbstractBuild<?, ?> previousBuild) {
this.currentBuild = build;
this.project = project;
this.upstreamBuild = previousBuild;
this.currentBuildResult = "";
this.upstreamBuildResult = "";
}
public AbstractBuild<?, ?> getCurrentBuild() {
return currentBuild;
}
public void setCurrentBuild(AbstractBuild<?, ?> currentBuild) {
this.currentBuild = currentBuild;
}
public AbstractBuild<?, ?> getUpstreamBuild() {
return upstreamBuild;
}
public void setUpstreamBuild(AbstractBuild<?, ?> upstreamBuild) {
this.upstreamBuild = upstreamBuild;
}
public void setProject(AbstractProject<?, ?> currentProject) {
this.project = currentProject;
}
/**
* Returns the project name. If the current project is null the project name
* is determined using the current build.
* @return - Project name
*/
public AbstractProject<?, ?> getProject() {
final AbstractProject<?, ?> currentProject;
if (this.project == null) {
currentProject = this.currentBuild.getProject();
} else {
currentProject = this.project;
}
return currentProject;
}
/**
* Returns the current build number.
* @return - Current build number or empty String is the current build is null.
*/
private String getCurrentBuildNumber() {
if (this.currentBuild != null) {
return Integer.toString(currentBuild.getNumber());
} else {
return "";
}
}
/**
* Constructs a List of downstream PipelineBuild objects that make up the current pipeline.
* @return - List of downstream PipelineBuild objects that make up the current pipeline.
*/
public List<PipelineBuild> getDownstreamPipeline() {
final List<PipelineBuild> pbList = new ArrayList<PipelineBuild>();
final AbstractProject<?, ?> currentProject;
currentProject = getProject();
final List<AbstractProject<?, ?>> downstreamProjects = ProjectUtil.getDownstreamProjects(currentProject);
for (AbstractProject<?, ?> proj : downstreamProjects) {
AbstractBuild<?, ?> returnedBuild = null;
if (this.currentBuild != null) {
returnedBuild = BuildUtil.getDownstreamBuild(proj, currentBuild);
}
final PipelineBuild newPB = new PipelineBuild(returnedBuild, proj, this.currentBuild);
pbList.add(newPB);
}
return pbList;
}
/**
* Build a URL of the currentBuild
*
* @return URL of the currentBuild
* @throws URISyntaxException If the URI string constructed from the given components violates RFC 2396
*/
public String getBuildResultURL() throws URISyntaxException {
final StringBuffer resultURL = new StringBuffer();
final URI uri;
if (this.currentBuild != null) {
resultURL.append("/job/");
resultURL.append(this.currentBuild.getProject().getName());
resultURL.append('/');
resultURL.append(this.currentBuild.getNumber());
resultURL.append('/');
} else {
resultURL.append(getProjectURL());
}
uri = new URI(null, null, resultURL.toString(), null);
return uri.toASCIIString();
}
/**
* Builds a URL of the current project
*
* @return URL - of the project
* @throws URISyntaxException If the URI string constructed from the given components violates RFC 2396
*/
public String getProjectURL() throws URISyntaxException {
return ProjectUtil.getProjectURL(this.getProject());
}
/**
* Determines the result of the current build.
* @return - String representing the build result
* @see PipelineBuild#getBuildResult(AbstractBuild)
*/
public String getCurrentBuildResult() {
if (this.currentBuildResult.isEmpty()) {
this.currentBuildResult = getBuildResult(this.currentBuild);
}
return this.currentBuildResult;
}
/**
* Determines the result of the upstream build.
* @return - String representing the build result
* @see PipelineBuild#getBuildResult(AbstractBuild)
*/
public String getUpstreamBuildResult() {
if (this.upstreamBuildResult.isEmpty()) {
this.upstreamBuildResult = getBuildResult(this.upstreamBuild);
}
return this.upstreamBuildResult;
}
/**
* Determines the result for a particular build.
* Can be one of the following:
* - BUILDING
* - SUCCESS
* - FAILURE
* - UNSTABLE
* - NOT_BUILT
* - ABORT
* - PENDING
* - MANUAL
*
* @param build - The build for which a result is requested.
* @return - String representing the build result
*/
private String getBuildResult(AbstractBuild<?, ?> build) {
String buildResult;
// If AbstractBuild exists determine its current status
if (build != null) {
if (build.isBuilding()) {
buildResult = HudsonResult.BUILDING.toString();
} else {
buildResult = HudsonResult.values()[build.getResult().ordinal].toString();
}
} else {
// Otherwise determine its pending status
buildResult = getPendingStatus();
}
return buildResult;
}
/**
* Determines the pending currentBuild status of a currentBuild in the pipeline
* that has not been completed. (i.e. the currentBuild is null)
*
* @return - PENDING: Current currentBuild is pending the execution of upstream builds.
* MANUAL: Current currentBuild requires a manual trigger
*/
private String getPendingStatus() {
String pendingStatus = HudsonResult.PENDING.toString();
final PipelineBuild upstreamPB = getUpstreamPipelineBuild();
if (upstreamPB != null) {
if (this.getUpstreamBuild() != null) {
if (getUpstreamBuildResult().equals(HudsonResult.SUCCESS.toString())) {
if (ProjectUtil.isManualTrigger(this.upstreamBuild.getProject(), this.project)) {
pendingStatus = HudsonResult.MANUAL.toString();
}
}
}
}
return pendingStatus;
}
/**
* Returns the upstream PipelineBuild object from the current PipelineBuild object.
* @return - Upstream PipelineBuild object from the current PipelineBuild object
*/
public PipelineBuild getUpstreamPipelineBuild() {
final List<AbstractProject> upstreamProjects = this.project.getUpstreamProjects();
final AbstractProject<?, ?> previousProject;
final PipelineBuild previousPB = new PipelineBuild();
if (upstreamProjects.size() > 0) {
previousProject = upstreamProjects.get(0);
previousPB.setCurrentBuild(this.getUpstreamBuild());
previousPB.setProject(previousProject);
}
return previousPB;
}
/**
* Returns the current build duration.
* @return - Current build duration or an empty String if the current build is null.
*/
public String getBuildDuration() {
if (this.currentBuild != null) {
return this.currentBuild.getDurationString();
} else {
return "";
}
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
return "Project: " + getProject().getName() + " : Build: " + getCurrentBuildNumber();
}
/**
* Returns the current build description.
* @return - Current build description or the project name if the current build is null.
*/
public String getBuildDescription() {
if (this.currentBuild != null) {
return this.currentBuild.toString();
} else {
return "Pending build of project: " + this.getProject().getName();
}
}
/**
* Get the SVN revision no of a particular currentBuild
*
* @return The revision number of the currentBuild or "No Revision"
*/
public String getSVNRevisionNo() {
String revNo = "No Revision";
try {
if (this.currentBuild != null) {
final EnvVars environmentVars = this.currentBuild.getEnvironment(null);
if (environmentVars.get("SVN_REVISION") != null) {
revNo = environmentVars.get("SVN_REVISION");
}
}
} catch (final Exception e) {
LOGGER.info(e.toString());
}
return revNo;
}
public boolean hasBuildPermission() {
boolean buildPermission = false;
// If no security is enabled then allow builds
if (!Hudson.getInstance().isUseSecurity()) {
buildPermission = true;
} else if (this.project != null) {
// If security is enabled check if BUILD is enabled
buildPermission = this.project.hasPermission(Item.BUILD);
}
return buildPermission;
}
}
|
package br.com.dbsoft.ui.component.command;
import javax.el.MethodExpression;
import javax.faces.component.ActionSource2;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.event.FacesEvent;
import javax.faces.event.FacesListener;
import br.com.dbsoft.ui.component.DBSUICommand;
import br.com.dbsoft.ui.core.DBSMessagesFacesContext;
import br.com.dbsoft.ui.core.DBSFaces.FACESCONTEXT_ATTRIBUTE;
public class DBSUICommandAfterActionEvent extends FacesEvent {
private static final long serialVersionUID = 654791198375318147L;
ActionEvent wActionEvent;
public DBSUICommandAfterActionEvent(ActionEvent pEvent) {
super(pEvent.getComponent());
wActionEvent = pEvent;
}
@Override
public boolean isAppropriateListener(FacesListener pListener) {
return true;
}
@Override
public void processListener(FacesListener pListener) {
// System.out.println("DBSUICommandAfterActionEvent processListener");
FacesContext xContext = FacesContext.getCurrentInstance();
if (DBSMessagesFacesContext.getMessage(DBSMessagesFacesContext.ALL) == null){
//Remove ACTION ORIGINAL salvo anteriormente
xContext.getAttributes().put(FACESCONTEXT_ATTRIBUTE.ACTION_SOURCE, null);
return;
}
// System.out.println("DBSUICommandAfterActionEvent processListener TEM MENSAGEM");
xContext.getPartialViewContext().getRenderIds().add(getComponent().getClientId() + DBSUICommand.FACET_MESSAGE);
ActionSource2 xAS = (ActionSource2) wActionEvent.getSource();
MethodExpression xME = xAS.getActionExpression();
if (xME !=null){
// xContext.getApplication().getNavigationHandler().handleNavigation(xContext, xME.getExpressionString(), xContext.getAttributes().get(FACESCONTEXT_ATTRIBUTE.PREVIOUS_VIEW).toString());
xContext.getPartialViewContext().setRenderAll(false);
if (xContext.getAttributes().get(FACESCONTEXT_ATTRIBUTE.ACTION_SOURCE) == null){
//Salva qual ACTION ORIGINAL
xContext.getAttributes().put(FACESCONTEXT_ATTRIBUTE.ACTION_SOURCE, wActionEvent.getComponent());
}
}
}
}
|
package com.bearingpoint.opencms.workflow2.cms.ui;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import org.apache.commons.logging.Log;
import org.opencms.file.CmsProject;
import org.opencms.file.CmsResource;
import org.opencms.file.CmsResourceFilter;
import org.opencms.file.CmsUser;
import org.opencms.jsp.CmsJspActionElement;
import org.opencms.lock.CmsLock;
import org.opencms.main.CmsException;
import org.opencms.main.CmsLog;
import org.opencms.util.CmsUUID;
import org.opencms.workplace.CmsWorkplaceSettings;
import org.opencms.workplace.commons.CmsTouch;
import com.bearingpoint.opencms.workflow2.I_WorkflowController;
import com.bearingpoint.opencms.workflow2.WorkflowController;
import com.bearingpoint.opencms.workflow2.WorkflowException;
import com.bearingpoint.opencms.workflow2.WorkflowPublishNotPermittedException;
import com.bearingpoint.opencms.workflow2.stage.ProjectWrapper;
/**
* Adaptation of the original OpenCms 7 CmsTouch class -
* Copies/Publishes an existing resource of the current project
* to any target project provided by the user interface.
* <p>
*
* Used by following files:
* <ul>
* <li>/ui/movetoproject.jsp
* </ul>
* <p>
*
* @author David Trattnig
*
*/
public class WorkflowMoveToProject extends CmsTouch {
/** Value for the action: copy the resource to current project. */
public static final int ACTION_COPYTOPROJECT = 100;
/** The dialog type. */
public static final String DIALOG_TYPE = "copytoproject";
/** The log object for this class. */
private static final Log LOG = CmsLog.getLog(WorkflowMoveToProject.class);
/** Contains the target project to copy the chosen resource(s) **/
public static final String PARAM_TARGETPROJECT = "project";
private String m_paramTargetProject;
private I_WorkflowController wc;
/**
* Public constructor with JSP action element.<p>
*
* @param jsp an initialized JSP action element
*/
public WorkflowMoveToProject(CmsJspActionElement jsp) {
super(jsp);
try {
wc = new WorkflowController(getCms());
}
catch (WorkflowException e) {
LOG.fatal("fatal error initializing the workflow controller!", e);
throw new RuntimeException (e);
}
}
/**
* Public constructor with JSP variables.<p>
*
* @param context the JSP page context
* @param req the JSP request
* @param res the JSP response
*/
public WorkflowMoveToProject(PageContext context, HttpServletRequest req, HttpServletResponse res) {
this(new CmsJspActionElement(context, req, res));
}
public void actionPublish() throws JspException {
CmsProject targetProject = null;
try {
targetProject = getCms().readProject(new CmsUUID(getParamProject()));
// start workflow
if (targetProject != null) {
CmsResource resource = getCms().readResource(getParamResource());
try {
wc.actionApprove(resource, targetProject);
actionMoveToProject();
} catch (WorkflowPublishNotPermittedException e) {
includeErrorpage(this, e);
}
}
} catch (NumberFormatException e) {
includeErrorpage(this, e);
} catch (CmsException e) {
includeErrorpage(this, e);
} catch (WorkflowException e) {
includeErrorpage(this, e);
}
LOG.info("WF2| started workflow for resource <"+getParamResource()+">");
}
/**
* Performs the copy to project action, will be called by the JSP page.<p>
*
* @throws JspException if problems including sub-elements occur
*/
public void actionMoveToProject() throws JspException {
// save initialized instance of this class in request attribute for included sub-elements
getJsp().getRequest().setAttribute(SESSION_WORKPLACE_CLASS, this);
try {
CmsProject targetProject = getCms().readProject(new CmsUUID(getParamProject()));
LOG.info("WF2| target project uuid: "+targetProject.getUuid().toString());
//backup current project uuid
CmsProject currentProject = getCms().getRequestContext().currentProject();
LOG.info("WF2| current project: "+currentProject.getName());
// switch to target project
getCms().getRequestContext().setCurrentProject(targetProject);
LOG.info("WF2| set current project to target project: "+targetProject.getName());
// copy the resource to the current project
getCms().copyResourceToProject(getParamResource());
setParamNewtimestamp(getCurrentDateTime());
actionTouch();
LOG.info("WF2| copied resource '"+getParamResource()+"' to current project: "+targetProject.getName());
//unlock resource within the target project
unlockResource(getParamResource());
// switch back to previous project
getCms().getRequestContext().setCurrentProject(currentProject);
LOG.info("WF2| reset current project to: "+currentProject.getName());
// close the dialog
actionCloseDialog();
} catch (Throwable e) {
// error copying resource to project, include error page
includeErrorpage(this, e);
}
}
/**
* Returns the value of the target project parameter,
* or null if this parameter was not provided.<p>
*
* The project parameter contains the project to move
* the resource.<p>
*
* @return the value of the target project parameter
*/
public String getParamProject() {
if ((m_paramTargetProject != null) && !"null".equals(m_paramTargetProject)) {
return m_paramTargetProject;
} else {
return null;
}
}
/**
* Set the value of the target project parameter.<p>
*
* The project parameter contains the project to move
* the resource.<p>
*
* @param the value of the target project parameter
*/
public void setParamProject(String targetProject) {
m_paramTargetProject = targetProject;
}
/**
* Returns the HTML containing project information and confirmation question for the JSP.<p>
*
* @return the HTML containing project information and confirmation question for the JSP
*/
public String buildProjectInformation() {
StringBuffer result = new StringBuffer(32);
String resName = getParamResource();
CmsResource res = null;
try {
res = getCms().readResource(getParamResource(), CmsResourceFilter.ALL);
if (res.isFolder() && !resName.endsWith("/")) {
resName += "/";
}
} catch (CmsException e) {
// error reading resource, should not happen
if (LOG.isInfoEnabled()) {
LOG.info(e.getLocalizedMessage());
}
}
try {
CmsUser user = getCms().getRequestContext().currentUser();
List<ProjectWrapper> validTargetProjects = wc.getProjectManager().getValidTargetProjects(user, res);
validTargetProjects.addAll(wc.getProjectManager().getValidRejectProjects(res));
//TODO add localization!
//String[] localizedObject = new String[] {getCms().getRequestContext().currentProject().getName()};
result.append(dialogBlockStart(Messages.get().container(Messages.GUI_WORKFLOW_PUBLISH_TO_PROJECT_BLOCKHEADER_0).key()));
result.append("<select id=\""+PARAM_TARGETPROJECT+"\" name=\""+PARAM_TARGETPROJECT+"\">");
for (ProjectWrapper project : validTargetProjects) {
result.append("<option value=\"");
result.append(project.getId());
result.append("\">");
result.append(project.getName());
result.append("</option>");
}
result.append("</select>");
result.append(dialogBlockEnd());
result.append(dialogSpacer());
} catch (Exception e) {
// error reading project resources, should not happen
if (LOG.isInfoEnabled()) {
LOG.info(e.getLocalizedMessage());
}
}
// show confirmation question
//String[] localizedObject = new String[] {resName, getCms().getRequestContext().currentProject().getName()};
result.append(Messages.get().container(Messages.GUI_WORKFLOW_PUBLISH_TO_PROJECT_CONFIRMATION_2, res.getName(),"").key());
return result.toString();
}
/**
* @see org.opencms.workplace.CmsWorkplace#initWorkplaceRequestValues(org.opencms.workplace.CmsWorkplaceSettings, javax.servlet.http.HttpServletRequest)
*/
protected void initWorkplaceRequestValues(CmsWorkplaceSettings settings, HttpServletRequest request) {
// fill the parameter values in the get/set methods
fillParamValues(request);
// set the dialog type
setParamDialogtype(DIALOG_TYPE);
// set the action for the JSP switch
if (DIALOG_TYPE.equals(getParamAction())) {
setAction(ACTION_COPYTOPROJECT);
} else if (DIALOG_CANCEL.equals(getParamAction())) {
setAction(ACTION_CANCEL);
} else {
setAction(ACTION_DEFAULT);
// build title for copy to project dialog
setParamTitle(Messages.get().container(Messages.GUI_WORKFLOW_PUBLISH_TO_PROJECT_TITLE_0).key());
}
}
/**
* Unlocks the resource within the target project:
* 1. the lock has to be stolen from the previous user (which is the same but from another project ;-)
* 2. the resource has to be unlocked
* <p>
*
* @param resName
* @throws CmsException
*/
protected void unlockResource(String resName) throws CmsException {
//unlock resource if locked and it is locked by the current user:
CmsLock lock = getCms().getLock(resName);
if (!lock.isUnlocked()) {
if (!lock.isNullLock() && lock.isOwnedBy(getCms().getRequestContext().currentUser())) {
getCms().changeLock(resName);
getCms().unlockResource(resName);
}
}
}
}
|
package com.conveyal.r5.analyst.fare;
import com.conveyal.gtfs.model.Fare;
import com.conveyal.r5.profile.McRaptorSuboptimalPathProfileRouter;
import com.conveyal.r5.transit.RouteInfo;
import com.conveyal.r5.transit.TransitLayer;
import gnu.trove.list.TIntList;
import gnu.trove.list.array.TIntArrayList;
import org.apache.commons.math3.random.MersenneTwister;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;
/**
* Fare calculator for systems in which:
* - Each route has a single flat fare
* - At most one agency provides transfer privileges (pay-the-difference when boarding a more expensive route).
* - Unlimited transfers may be allowed allowed between routes with certain fares, between stops with zone_id =
* "station" and sharing the same (non-blank) parent_station
* This calculator is designed for regions with mixed formal and informal transit services such as Bogota, in which the
* formal services issue and accept mutually recognized transfer privileges(e.g. between BRT and cheaper zonal/feeder
* routes) and the semi-formal services (e.g. cash-based private operators) do not.
* This implementation relies on non-standard conventions being used in input GTFS:
* - Every route_id is prefixed with "fare_id"+"--"
* - Stops within the paid area have zone_id = "station"
*/
public class MixedSystemInRoutingFareCalculator extends InRoutingFareCalculator {
/** If true, log a random 1e-6 sample of fares for spot checking */
public static final boolean LOG_FARES = false;
private static final WeakHashMap<TransitLayer, FareSystemWrapper> fareSystemCache = new WeakHashMap<>();
private Map<String, Fare> fares;
// Logging to facilitate debugging
private static final Logger LOG = LoggerFactory.getLogger(MixedSystemInRoutingFareCalculator.class);
private MersenneTwister logRandomizer = LOG_FARES ? new MersenneTwister() : null;
private static int priceToInt(double price) {return (int) (price);} // No conversion for now
// Relies on non-standard convention described in class javadoc
private static String getFareIdFromRouteId(RouteInfo route) {return route.route_id.split("
// fares for routes that serve "paid area" stops, at which unlimited transfers may be available
private static ArrayList<String> faresAvailableInPaidArea = new ArrayList<>(Arrays.asList("T","D"));
private static String STATION = "station";
private class MixedSystemTransferAllowance extends TransferAllowance {
// GTFS-lib does not read fare_attributes.agencyId. We set it explicitly via routes.agencyId, relying on the
// convention described above to map routes.route_id to fare_attributes.fare_id.
private final String agencyId;
private MixedSystemTransferAllowance () {
super();
this.agencyId = null;
}
private MixedSystemTransferAllowance (int value, int number, int expirationTime, String agencyId){
super(value, number, expirationTime);
this.agencyId = agencyId;
}
private MixedSystemTransferAllowance redeemForOneRide(int fareValue) {
int allowanceValue = Math.max(fareValue, value);
return new MixedSystemTransferAllowance(allowanceValue, number - 1, expirationTime, agencyId);
}
}
private static boolean withinPaidArea(int fromStopIndex, int toStopIndex, TransitLayer transitLayer){
String fromFareZone = transitLayer.fareZoneForStop.get(fromStopIndex);
String toFareZone = transitLayer.fareZoneForStop.get(toStopIndex);
if (STATION.equals(fromFareZone) && STATION.equals(toFareZone)){
String fromParentStation = transitLayer.parentStationIdForStop.get(fromStopIndex);
String toParentStation = transitLayer.parentStationIdForStop.get(toStopIndex);
return fromParentStation != null && fromParentStation.equals(toParentStation);
} else {
return false;
}
}
@Override
public FareBounds calculateFare(McRaptorSuboptimalPathProfileRouter.McRaptorState state, int maxClockTime) {
// First, load fare data from GTFS
if (fares == null){
synchronized (this) {
if (fares == null){
synchronized (fareSystemCache) {
FareSystemWrapper fareSystem = fareSystemCache.computeIfAbsent(this.transitLayer,
MixedSystemInRoutingFareCalculator::loadFaresFromGTFS);
this.fares = fareSystem.fares;
}
}
}
}
// Initialize: haven't boarded, paid a fare, or received a transfer allowance
int cumulativeFarePaid = 0;
MixedSystemTransferAllowance transferAllowance = new MixedSystemTransferAllowance();
// Extract relevant data about rides
TIntList patterns = new TIntArrayList();
TIntList boardStops = new TIntArrayList();
TIntList alightStops = new TIntArrayList();
TIntList boardTimes = new TIntArrayList();
List<String> routeNames;
if (LOG_FARES) routeNames = new ArrayList<>();
McRaptorSuboptimalPathProfileRouter.McRaptorState stateForTraversal = state;
while (stateForTraversal != null) {
if (stateForTraversal.pattern == -1) {
stateForTraversal = stateForTraversal.back;
continue; // on the street, not on transit
}
patterns.add(stateForTraversal.pattern);
alightStops.add(stateForTraversal.stop);
boardStops.add(transitLayer.tripPatterns.get(stateForTraversal.pattern).stops[stateForTraversal.boardStopPosition]);
boardTimes.add(stateForTraversal.boardTime);
stateForTraversal = stateForTraversal.back;
}
// reverse data about the rides so we can step forward through them
patterns.reverse();
alightStops.reverse();
boardStops.reverse();
boardTimes.reverse();
// Loop over rides to get to the state in forward-chronological order
for (int ride = 0; ride < patterns.size(); ride ++) {
int pattern = patterns.get(ride);
RouteInfo route = transitLayer.routes.get(transitLayer.tripPatterns.get(pattern).routeIndex);
// used for logging
if (LOG_FARES) routeNames.add(route.route_short_name != null && !route.route_short_name.isEmpty() ?
route.route_short_name : route.route_long_name);
// board stop for this ride
int boardStopIndex = boardStops.get(ride);
int boardClockTime = boardTimes.get(ride);
String fareId = getFareIdFromRouteId(route);
Fare fare = fares.get(fareId);
// Agency of the board route
String receivingAgency = route.agency_id;
// Agency that issued the currently held transfer allowance (possibly several rides ago)
String issuingAgency = transferAllowance.agencyId;
// If this is the second ride or later, check whether the route stays within the paid area
if (ride >= 1) {
int fromStopIndex = alightStops.get(ride - 1);
if (withinPaidArea(fromStopIndex, boardStopIndex, transitLayer)) continue;
}
// We are not staying within the paid area. So...
// Check if enough time has elapsed for our transfer allowance to expire
if (transferAllowance.hasExpiredAt(boardTimes.get(ride))) transferAllowance = new MixedSystemTransferAllowance();
// Then check if we might be able to redeem a transfer
boolean transferValueAvailable =
transferAllowance.value > 0 &&
transferAllowance.number > 0;
int undiscountedPrice = priceToInt(fare.fare_attribute.price);
if (transferValueAvailable) {
// If transfer value is available, attempt to use it.
if (receivingAgency.equals(issuingAgency)) {
// Pay difference and set updated transfer allowance
cumulativeFarePaid += transferAllowance.payDifference(undiscountedPrice);
transferAllowance = transferAllowance.redeemForOneRide(undiscountedPrice);
} else {
// This agency will not accept transfer allowance. Hold onto it, and pay full fare.
cumulativeFarePaid += undiscountedPrice;
}
} else {
// Pay full fare and obtain new transfer allowance
cumulativeFarePaid += undiscountedPrice;
transferAllowance = new MixedSystemTransferAllowance(priceToInt(fare.fare_attribute.price),
fare.fare_attribute.transfers,boardClockTime + fare.fare_attribute.transfer_duration,
receivingAgency);
}
}
// warning: reams of log output
// only log 1/1000000 of the fares
if (LOG_FARES && logRandomizer.nextInt(1000000) == 42) {
LOG.info("Fare for {}: ${}", String.join(" -> ", routeNames), String.format("%.2f", cumulativeFarePaid / 100D));
}
return new FareBounds(cumulativeFarePaid, transferAllowance.tightenExpiration(maxClockTime));
}
@Override
public String getType() {
return "mixed-system";
}
private static class FareSystemWrapper{
public Map<String, Fare> fares;
private FareSystemWrapper(Map<String, Fare> fares) {
this.fares = fares;
}
}
private static FareSystemWrapper loadFaresFromGTFS(TransitLayer transitLayer){
Map<String, Fare> fares = new HashMap<>();
// iterate through fares to record rules
for (Fare fare : transitLayer.fares.values()){
fares.putIfAbsent(fare.fare_id, fare);
}
return new FareSystemWrapper(fares);
}
}
|
package org.ccnx.ccn.io;
import java.io.IOException;
import java.util.ArrayList;
import org.ccnx.ccn.CCNHandle;
import org.ccnx.ccn.config.ConfigurationException;
import org.ccnx.ccn.impl.support.DataUtils;
import org.ccnx.ccn.impl.support.Log;
import org.ccnx.ccn.protocol.ContentName;
import org.ccnx.ccn.protocol.ContentObject;
import org.ccnx.ccn.protocol.Interest;
import org.ccnx.ccn.protocol.PublisherPublicKeyDigest;
/**
* Miscellaneous helper functions to read data. Most clients will
* prefer the higher-level interfaces offered by CCNInputStream and
* its subclasses, or CCNNetworkObject and its subclasses.
*/
public class CCNReader {
protected CCNHandle _handle;
public CCNReader(CCNHandle handle) throws ConfigurationException, IOException {
_handle = handle;
if (null == _handle)
_handle = CCNHandle.open();
}
/**
* Gets a ContentObject matching this name and publisher
* @param name desired name or prefix for data
* @param publisher desired publisher or null for any publisher
* @param timeout milliseconds to wait for data
* @return data matching the name and publisher or null
* @throws IOException
*/
public ContentObject get(ContentName name, PublisherPublicKeyDigest publisher, long timeout) throws IOException {
return _handle.get(name, publisher, timeout);
}
/**
* Gets a ContentObject matching this interest
* @param interest interest for desired object
* @param timeout milliseconds to wait for data
* @return data matching the interest or null
* @throws IOException
*/
public ContentObject get(Interest interest, long timeout) throws IOException {
return _handle.get(interest, timeout);
}
/**
* Helper method to retrieve a set of segmented content blocks and rebuild them
* into a single buffer. Equivalent to CCNWriter's put. Does not do anything about
* versioning.
*/
public byte [] getData(ContentName name, PublisherPublicKeyDigest publisher, int timeout) throws IOException {
CCNInputStream inputStream = new CCNInputStream(name, publisher, _handle);
inputStream.setTimeout(timeout);
byte [] data = DataUtils.getBytesFromStream(inputStream);
return data;
}
/**
* Helper method to retrieve a set of segmented content blocks and rebuild them
* into a single buffer. Equivalent to CCNWriter's put. Does not do anything about
* versioning.
*/
public byte [] getVersionedData(ContentName name, PublisherPublicKeyDigest publisher, int timeout) throws IOException {
CCNInputStream inputStream = new CCNVersionedInputStream(name, publisher, _handle);
inputStream.setTimeout(timeout);
byte [] data = DataUtils.getBytesFromStream(inputStream);
return data;
}
/**
* Return data the specified number of levels below us in the
* hierarchy, with order preference of leftmost.
*
* @param handle handle to use for requests
* @param name of content to get
* @param level number of levels below name in the hierarchy content should sit
* @param publisher the desired publisher of this content, or null for any publisher.
* @param timeout timeout for retrieval
* @return matching content, if found
* @throws IOException
*/
public ContentObject getLower(ContentName name, int level, PublisherPublicKeyDigest publisher, long timeout) throws IOException {
return _handle.get(Interest.lower(name, level, publisher), timeout);
}
/**
* Enumerate matches below query name in the hierarchy, looking
* at raw content. For a higher-level enumeration protocol see the
* name enumeration protocol.
* Note this method is also quite slow because it has to timeout requests at every
* search level
* @param query an Interest defining the highest level of the query
* @param timeout - milliseconds to wait for each individual get of data, default is 5 seconds
* @return a list of the content objects matching this query
* @throws IOException
*/
public ArrayList<ContentObject> enumerate(Interest query, long timeout) throws IOException {
ArrayList<ContentObject> result = new ArrayList<ContentObject>();
// This won't work without a correct order preference
int count = query.name().count();
while (true) {
ContentObject co = null;
co = _handle.get(query, timeout);
if (co == null)
break;
Log.info("enumerate: retrieved " + co.fullName() +
" on query: " + query.name());
result.add(co);
for (int i = co.name().count() - 1; i > count; i
result.addAll(enumerate(new Interest(new ContentName(i, co.name().components())), timeout));
}
query = Interest.next(co.name(), count, null);
}
Log.info("enumerate: retrieved " + result.size() + " objects.");
return result;
}
}
|
package com.creatubbles.ctbmod.common.painting;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.ScaledResolution;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.util.math.RayTraceResult;
import net.minecraft.util.math.RayTraceResult.Type;
import net.minecraft.util.text.TextFormatting;
import net.minecraftforge.client.event.RenderGameOverlayEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import com.creatubbles.api.core.Creation;
import com.creatubbles.api.core.User;
import com.creatubbles.api.response.relationships.RelationshipUser;
import com.creatubbles.ctbmod.CTBMod;
import com.google.common.base.Optional;
public class PaintingHighlightHandler {
@SubscribeEvent
public void renderOverlay(RenderGameOverlayEvent.Pre event) {
if (event.isCanceled() || event.getType() != RenderGameOverlayEvent.ElementType.POTION_ICONS || Minecraft.getMinecraft().thePlayer.isSneaking()) {
return;
}
RayTraceResult res = Minecraft.getMinecraft().objectMouseOver;
if (res != null && res.typeOfHit == Type.BLOCK) {
IBlockState state = Minecraft.getMinecraft().theWorld.getBlockState(res.getBlockPos());
if (state.getBlock() == CTBMod.painting) {
TilePainting painting = BlockPainting.getDataPainting(Minecraft.getMinecraft().theWorld, res.getBlockPos());
if (painting == null) {
return;
}
FontRenderer fr = Minecraft.getMinecraft().fontRendererObj;
ScaledResolution resolution = new ScaledResolution(Minecraft.getMinecraft());
int x = resolution.getScaledWidth() / 2;
int y = resolution.getScaledHeight() / 2;
x += 10;
y -= fr.FONT_HEIGHT / 2 - 1;
fr.drawStringWithShadow("\"" + TextFormatting.ITALIC + painting.getCreation().getName() + TextFormatting.RESET + "\"", x, y, 0xFFFFFFFF);
y += fr.FONT_HEIGHT + 2;
if (painting.getCreation().getRelationships() != null) {
RelationshipUser[] creators = painting.getCreation().getRelationships().getCreators();
for (RelationshipUser r : creators) {
Optional<User> user = CTBMod.cache.getUserForID(r.getId());
y = drawUserString(getUserString(user, painting.getCreation()), x, y);
y += fr.FONT_HEIGHT;
}
}
}
}
}
private static int drawUserString(String[] data, int x, int y) {
FontRenderer fr = Minecraft.getMinecraft().fontRendererObj;
ScaledResolution sr = new ScaledResolution(Minecraft.getMinecraft());
fr.drawStringWithShadow(data[0], x, y, -1);
int ret = y;
if (data.length > 1) {
int len0 = fr.getStringWidth(data[0]);
int len1 = fr.getStringWidth(data[1]);
fr.drawStringWithShadow(data[1], x + len0, y, -1);
if (x + len0 + len1 + fr.getStringWidth(data[2]) > sr.getScaledWidth()) {
y += fr.FONT_HEIGHT;
ret = y + 5;
x += 12;
} else {
x += len0 + len1;
}
fr.drawStringWithShadow(data[2], x, y, -1);
}
return ret;
}
private static String[] getUserString(Optional<User> opt, Creation creation) {
if (opt.isPresent()) {
User user = opt.get();
String gender = user.getGender().equals("male") ? "\u2642" : user.getGender().equals("female") ? "\u2640" : "";
return new String[] { "By: " + user.getDisplayName() + gender, " " + creation.getCreatedAge(user), " \u2295" + user.getCountryName() };
} else {
int dots = (int) ((Minecraft.getMinecraft().theWorld.getTotalWorldTime() / 4) % 4);
String s = "Loading";
for (int i = 0; i < dots; i++) {
s += '.';
}
return new String[] { s };
}
}
}
|
package com.elmakers.mine.bukkit.magic.command;
import com.elmakers.mine.bukkit.api.magic.Mage;
import com.elmakers.mine.bukkit.api.magic.MagicAPI;
import com.elmakers.mine.bukkit.api.spell.SpellTemplate;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class MagicGiveCommandExecutor extends MagicTabExecutor {
public MagicGiveCommandExecutor(MagicAPI api) {
super(api);
}
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (!api.hasPermission(sender, "Magic.commands.mgive"))
{
sendNoPermission(sender);
return true;
}
if (args.length == 0 || args.length > 3)
{
sender.sendMessage("Usage: mgive [player] <item> [count]");
return true;
}
String playerName = null;
String itemName = null;
String countString = null;
if (args.length == 1) {
itemName = args[0];
} else if (args.length == 3) {
playerName = args[0];
itemName = args[1];
countString = args[2];
} else {
playerName = args[0];
Player testPlayer = Bukkit.getPlayer(playerName);
if (testPlayer == null) {
itemName = args[0];
countString = args[1];
} else {
itemName = args[1];
}
}
int count = 1;
if (countString != null) {
try {
count = Integer.parseInt(countString);
} catch (Exception ex) {
sender.sendMessage("Error parsing count: " + countString + ", should be an integer.");
return true;
}
}
Player player = null;
if (playerName != null) {
player = Bukkit.getPlayer(playerName);
}
if (player == null) {
if (!(sender instanceof Player)) {
sender.sendMessage("Console usage: mgive <player> <item> [count]");
return true;
}
player = (Player)sender;
}
if (itemName.equalsIgnoreCase("xp")) {
api.giveExperienceToPlayer(player, count);
sender.sendMessage("Gave " + count + " experience to " + player.getName());
return true;
} else if (itemName.equalsIgnoreCase("sp")) {
Mage mage = api.getMage(player);
mage.addSkillPoints(count);
sender.sendMessage("Gave " + count + " skill points to " + player.getName());
return true;
}else {
Mage mage = api.getMage(player);
ItemStack item = api.createItem(itemName, mage);
if (item == null) {
sender.sendMessage(ChatColor.RED + "Unknown item type " + itemName);
return true;
}
item.setAmount(count);
String displayName = api.describeItem(item);
sender.sendMessage("Gave " + count + " " + displayName + " to " + player.getName());
api.giveItemToPlayer(player, item);
}
return true;
}
@Override
public Collection<String> onTabComplete(CommandSender sender, String commandName, String[] args) {
List<String> options = new ArrayList<String>();
if (!sender.hasPermission("Magic.commands.mgive")) return options;
if (args.length == 1) {
options.addAll(api.getPlayerNames());
}
if (args.length == 1 || args.length == 2) {
Collection<SpellTemplate> spellList = api.getSpellTemplates();
for (SpellTemplate spell : spellList) {
options.add(spell.getKey());
}
Collection<String> allWands = api.getWandKeys();
for (String wandKey : allWands) {
options.add(wandKey);
}
for (Material material : Material.values()) {
options.add(material.name().toLowerCase());
}
options.add("xp");
options.add("sp");
}
return options;
}
}
|
package com.github.anba.es6draft.runtime.objects;
import static com.github.anba.es6draft.runtime.AbstractOperations.*;
import static com.github.anba.es6draft.runtime.internal.Properties.createProperties;
import static com.github.anba.es6draft.runtime.types.Undefined.UNDEFINED;
import static com.github.anba.es6draft.runtime.types.builtins.OrdinaryFunction.AddRestrictedFunctionProperties;
import static com.github.anba.es6draft.runtime.types.builtins.OrdinaryFunction.OrdinaryConstruct;
import com.github.anba.es6draft.runtime.ExecutionContext;
import com.github.anba.es6draft.runtime.Realm;
import com.github.anba.es6draft.runtime.internal.Initialisable;
import com.github.anba.es6draft.runtime.internal.ObjectAllocator;
import com.github.anba.es6draft.runtime.internal.Properties.Attributes;
import com.github.anba.es6draft.runtime.internal.Properties.Function;
import com.github.anba.es6draft.runtime.internal.Properties.Prototype;
import com.github.anba.es6draft.runtime.internal.Properties.Value;
import com.github.anba.es6draft.runtime.types.BuiltinSymbol;
import com.github.anba.es6draft.runtime.types.Intrinsics;
import com.github.anba.es6draft.runtime.types.PropertyDescriptor;
import com.github.anba.es6draft.runtime.types.ScriptObject;
import com.github.anba.es6draft.runtime.types.Type;
import com.github.anba.es6draft.runtime.types.builtins.BuiltinConstructor;
/**
* <h1>19 Fundamental Objects</h1><br>
* <h2>19.5 Error Objects</h2>
* <ul>
* <li>19.5.5 Native Error Types Used in This Standard
* <li>19.5.6 NativeError Object Structure
* <ul>
* <li>19.5.6.1 NativeError Constructors
* <li>19.5.6.2 Properties of the NativeError Constructors
* </ul>
* </ul>
*/
public class NativeErrorConstructor extends BuiltinConstructor implements Initialisable {
/**
* 19.5.5 Native Error Types Used in This Standard
* <ul>
* <li>19.5.5.1 EvalError
* <li>19.5.5.2 RangeError
* <li>19.5.5.3 ReferenceError
* <li>19.5.5.4 SyntaxError
* <li>19.5.5.5 TypeError
* <li>19.5.5.6 URIError
* </ul>
*/
public enum ErrorType {
EvalError, RangeError, ReferenceError, SyntaxError, TypeError, URIError, InternalError;
private Intrinsics prototype() {
switch (this) {
case EvalError:
return Intrinsics.EvalErrorPrototype;
case RangeError:
return Intrinsics.RangeErrorPrototype;
case ReferenceError:
return Intrinsics.ReferenceErrorPrototype;
case SyntaxError:
return Intrinsics.SyntaxErrorPrototype;
case TypeError:
return Intrinsics.TypeErrorPrototype;
case URIError:
return Intrinsics.URIErrorPrototype;
case InternalError:
return Intrinsics.InternalErrorPrototype;
default:
throw new IllegalStateException();
}
}
}
private final ErrorType type;
public NativeErrorConstructor(Realm realm, ErrorType type) {
super(realm);
this.type = type;
}
@Override
public void initialise(ExecutionContext cx) {
switch (type) {
case EvalError:
createProperties(this, cx, EvalErrorConstructorProperties.class);
break;
case RangeError:
createProperties(this, cx, RangeErrorConstructorProperties.class);
break;
case ReferenceError:
createProperties(this, cx, ReferenceErrorConstructorProperties.class);
break;
case SyntaxError:
createProperties(this, cx, SyntaxErrorConstructorProperties.class);
break;
case TypeError:
createProperties(this, cx, TypeErrorConstructorProperties.class);
break;
case URIError:
createProperties(this, cx, URIErrorConstructorProperties.class);
break;
case InternalError:
createProperties(this, cx, InternalErrorConstructorProperties.class);
break;
default:
throw new IllegalStateException();
}
AddRestrictedFunctionProperties(cx, this);
}
/**
* 19.5.6.1.1 NativeError (message)
* <p>
* <strong>Extension</strong>: NativeError (message, fileName, lineNumber, columnNumber)
*/
@Override
public Object call(ExecutionContext callerContext, Object thisValue, Object... args) {
ExecutionContext calleeContext = calleeContext();
Object message = args.length > 0 ? args[0] : UNDEFINED;
/* step 1 (omitted) */
/* steps 2-4 */
ErrorObject obj;
if (!Type.isObject(thisValue) || !(thisValue instanceof ErrorObject)
|| ((ErrorObject) thisValue).isInitialised()) {
obj = OrdinaryCreateFromConstructor(calleeContext, this, type.prototype(),
NativeErrorObjectAllocator.INSTANCE);
} else {
obj = (ErrorObject) thisValue;
}
/* step 5 */
obj.initialise();
/* step 6 */
if (!Type.isUndefined(message)) {
CharSequence msg = ToString(calleeContext, message);
PropertyDescriptor msgDesc = new PropertyDescriptor(msg, true, false, true);
DefinePropertyOrThrow(calleeContext, obj, "message", msgDesc);
}
/* extension: fileName, lineNumber and columnNumber arguments */
if (args.length > 1) {
CharSequence fileName = ToString(calleeContext, args[1]);
CreateDataProperty(calleeContext, obj, "fileName", fileName);
}
if (args.length > 2) {
int lineNumber = ToInt32(calleeContext, args[2]);
CreateDataProperty(calleeContext, obj, "lineNumber", lineNumber);
}
if (args.length > 3) {
int columnNumber = ToInt32(calleeContext, args[3]);
CreateDataProperty(calleeContext, obj, "columnNumber", columnNumber);
}
/* step 7 */
return obj;
}
/**
* 19.5.6.1.2 new NativeError (...argumentsList)
*/
@Override
public ScriptObject construct(ExecutionContext callerContext, Object... args) {
return OrdinaryConstruct(callerContext, this, args);
}
/**
* 19.5.6.2 Properties of the NativeError Constructors
*/
public enum EvalErrorConstructorProperties {
;
@Prototype
public static final Intrinsics __proto__ = Intrinsics.Error;
@Value(name = "length", attributes = @Attributes(writable = false, enumerable = false,
configurable = true))
public static final int length = 1;
@Value(name = "name", attributes = @Attributes(writable = false, enumerable = false,
configurable = true))
public static final String name = "EvalError";
/**
* 19.5.6.2.1 NativeError.prototype
*/
@Value(name = "prototype", attributes = @Attributes(writable = false, enumerable = false,
configurable = false))
public static final Intrinsics prototype = Intrinsics.EvalErrorPrototype;
/**
* 19.5.6.2.2 NativeError [ @@create ] ( )
*/
@Function(name = "[Symbol.create]", symbol = BuiltinSymbol.create, arity = 0,
attributes = @Attributes(writable = false, enumerable = false, configurable = true))
public static Object create(ExecutionContext cx, Object thisValue) {
return OrdinaryCreateFromConstructor(cx, thisValue, Intrinsics.EvalErrorPrototype,
NativeErrorObjectAllocator.INSTANCE);
}
}
/**
* 19.5.6.2 Properties of the NativeError Constructors
*/
public enum RangeErrorConstructorProperties {
;
@Prototype
public static final Intrinsics __proto__ = Intrinsics.Error;
@Value(name = "length", attributes = @Attributes(writable = false, enumerable = false,
configurable = true))
public static final int length = 1;
@Value(name = "name", attributes = @Attributes(writable = false, enumerable = false,
configurable = true))
public static final String name = "RangeError";
/**
* 19.5.6.2.1 NativeError.prototype
*/
@Value(name = "prototype", attributes = @Attributes(writable = false, enumerable = false,
configurable = false))
public static final Intrinsics prototype = Intrinsics.RangeErrorPrototype;
/**
* 19.5.6.2.2 NativeError [ @@create ] ( )
*/
@Function(name = "[Symbol.create]", symbol = BuiltinSymbol.create, arity = 0,
attributes = @Attributes(writable = false, enumerable = false, configurable = true))
public static Object create(ExecutionContext cx, Object thisValue) {
return OrdinaryCreateFromConstructor(cx, thisValue, Intrinsics.RangeErrorPrototype,
NativeErrorObjectAllocator.INSTANCE);
}
}
/**
* 19.5.6.2 Properties of the NativeError Constructors
*/
public enum ReferenceErrorConstructorProperties {
;
@Prototype
public static final Intrinsics __proto__ = Intrinsics.Error;
@Value(name = "length", attributes = @Attributes(writable = false, enumerable = false,
configurable = true))
public static final int length = 1;
@Value(name = "name", attributes = @Attributes(writable = false, enumerable = false,
configurable = true))
public static final String name = "ReferenceError";
/**
* 19.5.6.2.1 NativeError.prototype
*/
@Value(name = "prototype", attributes = @Attributes(writable = false, enumerable = false,
configurable = false))
public static final Intrinsics prototype = Intrinsics.ReferenceErrorPrototype;
/**
* 19.5.6.2.2 NativeError [ @@create ] ( )
*/
@Function(name = "[Symbol.create]", symbol = BuiltinSymbol.create, arity = 0,
attributes = @Attributes(writable = false, enumerable = false, configurable = true))
public static Object create(ExecutionContext cx, Object thisValue) {
return OrdinaryCreateFromConstructor(cx, thisValue, Intrinsics.ReferenceErrorPrototype,
NativeErrorObjectAllocator.INSTANCE);
}
}
/**
* 19.5.6.2 Properties of the NativeError Constructors
*/
public enum SyntaxErrorConstructorProperties {
;
@Prototype
public static final Intrinsics __proto__ = Intrinsics.Error;
@Value(name = "length", attributes = @Attributes(writable = false, enumerable = false,
configurable = true))
public static final int length = 1;
@Value(name = "name", attributes = @Attributes(writable = false, enumerable = false,
configurable = true))
public static final String name = "SyntaxError";
/**
* 19.5.6.2.1 NativeError.prototype
*/
@Value(name = "prototype", attributes = @Attributes(writable = false, enumerable = false,
configurable = false))
public static final Intrinsics prototype = Intrinsics.SyntaxErrorPrototype;
/**
* 19.5.6.2.2 NativeError [ @@create ] ( )
*/
@Function(name = "[Symbol.create]", symbol = BuiltinSymbol.create, arity = 0,
attributes = @Attributes(writable = false, enumerable = false, configurable = true))
public static Object create(ExecutionContext cx, Object thisValue) {
return OrdinaryCreateFromConstructor(cx, thisValue, Intrinsics.SyntaxErrorPrototype,
NativeErrorObjectAllocator.INSTANCE);
}
}
/**
* 19.5.6.2 Properties of the NativeError Constructors
*/
public enum TypeErrorConstructorProperties {
;
@Prototype
public static final Intrinsics __proto__ = Intrinsics.Error;
@Value(name = "length", attributes = @Attributes(writable = false, enumerable = false,
configurable = true))
public static final int length = 1;
@Value(name = "name", attributes = @Attributes(writable = false, enumerable = false,
configurable = true))
public static final String name = "TypeError";
/**
* 19.5.6.2.1 NativeError.prototype
*/
@Value(name = "prototype", attributes = @Attributes(writable = false, enumerable = false,
configurable = false))
public static final Intrinsics prototype = Intrinsics.TypeErrorPrototype;
/**
* 19.5.6.2.2 NativeError [ @@create ] ( )
*/
@Function(name = "[Symbol.create]", symbol = BuiltinSymbol.create, arity = 0,
attributes = @Attributes(writable = false, enumerable = false, configurable = true))
public static Object create(ExecutionContext cx, Object thisValue) {
return OrdinaryCreateFromConstructor(cx, thisValue, Intrinsics.TypeErrorPrototype,
NativeErrorObjectAllocator.INSTANCE);
}
}
/**
* 19.5.6.2 Properties of the NativeError Constructors
*/
public enum URIErrorConstructorProperties {
;
@Prototype
public static final Intrinsics __proto__ = Intrinsics.Error;
@Value(name = "length", attributes = @Attributes(writable = false, enumerable = false,
configurable = true))
public static final int length = 1;
@Value(name = "name", attributes = @Attributes(writable = false, enumerable = false,
configurable = true))
public static final String name = "URIError";
/**
* 19.5.6.2.1 NativeError.prototype
*/
@Value(name = "prototype", attributes = @Attributes(writable = false, enumerable = false,
configurable = false))
public static final Intrinsics prototype = Intrinsics.URIErrorPrototype;
/**
* 19.5.6.2.2 NativeError [ @@create ] ( )
*/
@Function(name = "[Symbol.create]", symbol = BuiltinSymbol.create, arity = 0,
attributes = @Attributes(writable = false, enumerable = false, configurable = true))
public static Object create(ExecutionContext cx, Object thisValue) {
return OrdinaryCreateFromConstructor(cx, thisValue, Intrinsics.URIErrorPrototype,
NativeErrorObjectAllocator.INSTANCE);
}
}
/**
* 19.5.6.2 Properties of the NativeError Constructors
*/
public enum InternalErrorConstructorProperties {
;
@Prototype
public static final Intrinsics __proto__ = Intrinsics.Error;
@Value(name = "length", attributes = @Attributes(writable = false, enumerable = false,
configurable = true))
public static final int length = 1;
@Value(name = "name", attributes = @Attributes(writable = false, enumerable = false,
configurable = true))
public static final String name = "InternalError";
/**
* 19.5.6.2.1 NativeError.prototype
*/
@Value(name = "prototype", attributes = @Attributes(writable = false, enumerable = false,
configurable = false))
public static final Intrinsics prototype = Intrinsics.InternalErrorPrototype;
/**
* 19.5.6.2.2 NativeError [ @@create ] ( )
*/
@Function(name = "[Symbol.create]", symbol = BuiltinSymbol.create, arity = 0,
attributes = @Attributes(writable = false, enumerable = false, configurable = true))
public static Object create(ExecutionContext cx, Object thisValue) {
return OrdinaryCreateFromConstructor(cx, thisValue, Intrinsics.InternalErrorPrototype,
NativeErrorObjectAllocator.INSTANCE);
}
}
private static class NativeErrorObjectAllocator implements ObjectAllocator<ErrorObject> {
static final ObjectAllocator<ErrorObject> INSTANCE = new NativeErrorObjectAllocator();
@Override
public ErrorObject newInstance(Realm realm) {
return new ErrorObject(realm);
}
}
}
|
package com.github.koraktor.steamcondenser.steam.community.tf2;
import java.util.ArrayList;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import com.github.koraktor.steamcondenser.exceptions.SteamCondenserException;
import com.github.koraktor.steamcondenser.exceptions.WebApiException;
import com.github.koraktor.steamcondenser.steam.community.GameStats;
/**
* This class represents the game statistics for a single user in Team Fortress
* 2
*
* @author Sebastian Staudt
*/
public class TF2Stats extends GameStats {
private int accumulatedPoints;
private ArrayList<TF2Class> classStats;
private TF2Inventory inventory;
private int totalPlayTime;
/**
* Creates a new <code>TF2Stats</code> instance by calling the super
* constructor with the game name <code>"tf2"</code>
*
* @param steamId The custom URL or 64bit Steam ID of the user
* @throws SteamCondenserException if an error occurs while fetching the
* stats data
*/
public TF2Stats(Object steamId) throws SteamCondenserException {
this(steamId, false);
}
/**
* Creates a new <code>TF2Stats</code> instance by calling the super
* constructor with the game name <code>"tf2"</code> (or <code>"520"</code>
* for the beta)
*
* @param steamId The custom URL or 64bit Steam ID of the user
* @param beta If <code>true</code>, creates stats for the public TF2 beta
* @throws SteamCondenserException if an error occurs while fetching the
* stats data
*/
public TF2Stats(Object steamId, boolean beta) throws SteamCondenserException {
super(steamId, (beta ? "520" : "tf2"));
if(this.isPublic()) {
Element statsElement = (Element) this.xmlData.getElementsByTagName("stats").item(0);
if(statsElement.getElementsByTagName("accumulatedPoints").getLength() != 0) {
this.accumulatedPoints = Integer.parseInt(statsElement.getElementsByTagName("accumulatedPoints").item(0).getTextContent());
}
if(statsElement.getElementsByTagName("secondsPlayedAllClassesLifetime").getLength() != 0) {
this.totalPlayTime = Integer.parseInt(statsElement.getElementsByTagName("secondsPlayedAllClassesLifetime").item(0).getTextContent());
}
}
}
/**
* Returns the total points this player has achieved in his career
*
* @return This player's accumulated points
*/
public int getAccumulatedPoints() {
return this.accumulatedPoints;
}
/**
* Returns the accumulated number of seconds this player has spent playing as a TF2 class
*
* @return total seconds played as a TF2 class
*/
public int getTotalPlayTime() {
return this.totalPlayTime;
}
/**
* Returns the statistics for all Team Fortress 2 classes for this user
* <p>
* If the classes haven't been parsed already, parsing is done now.
*
* @return An array storing individual stats for each Team Fortress 2 class
*/
public ArrayList<TF2Class> getClassStats() {
if(!this.isPublic()) {
return null;
}
if(this.classStats == null) {
this.classStats = new ArrayList<TF2Class>();
NodeList classes = ((Element) this.xmlData.getElementsByTagName("stats").item(0)).getElementsByTagName("classData");
for(int i = 0; i < classes.getLength(); i++) {
this.classStats.add(TF2ClassFactory.getTF2Class((Element) classes.item(i)));
}
}
return this.classStats;
}
/**
* Returns the current Team Fortress 2 inventory (a.k.a. backpack) of this
* player
*
* @return This player's TF2 backpack
* @throws WebApiException If an error occured while querying Steam's Web
* API
*/
public TF2Inventory getInventory() throws WebApiException {
if(!this.isPublic()) {
return null;
}
if(this.inventory == null) {
if(this.gameFriendlyName.equals("tf2")) {
this.inventory = TF2Inventory.create(this.steamId64);
} else {
this.inventory = TF2BetaInventory.create(this.steamId64);
}
}
return this.inventory;
}
}
|
package tof.cv.mpp;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.Manifest;
import com.astuetz.PagerSlidingTabStrip;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.images.ImageManager;
import com.google.android.gms.games.Games;
import com.google.android.gms.games.Player;
import com.google.android.gms.games.achievement.Achievement;
import com.google.android.gms.games.achievement.Achievements;
import com.google.android.gms.games.leaderboard.LeaderboardScore;
import com.google.android.gms.games.leaderboard.LeaderboardScoreBuffer;
import com.google.android.gms.games.leaderboard.LeaderboardVariant;
import com.google.android.gms.games.leaderboard.Leaderboards;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.koushikdutta.async.future.FutureCallback;
import com.koushikdutta.ion.Ion;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import de.keyboardsurfer.android.widget.crouton.Configuration;
import de.keyboardsurfer.android.widget.crouton.Crouton;
import de.keyboardsurfer.android.widget.crouton.Style;
import tof.cv.mpp.Utils.BaseGameFragment;
import tof.cv.mpp.Utils.MyPagerAdapter;
import tof.cv.mpp.Utils.MyStaggeredGridView;
import tof.cv.mpp.Utils.Utils;
import tof.cv.mpp.adapter.AchievementAdapter;
import tof.cv.mpp.adapter.HighScoreAdapter;
import tof.cv.mpp.bo.Station;
public class GameFragment extends BaseGameFragment implements
GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, ImageManager.OnImageLoadedListener, View.OnClickListener, LocationListener {
private static final Configuration CONFIGURATION_INFINITE = new Configuration.Builder()
.setDuration(Configuration.DURATION_INFINITE)
.build();
boolean top = false;
StationList.StationsList list;
Crouton crouton;
Location me;
long newScore;
//GameHelper mHelper;
boolean init = false;
Handler handler = new Handler();
public final static String LEADER = "CgkI9Y3S0soCEAIQAg";
public final static String CHECKIN = "CgkI9Y3S0soCEAIQBA";
public final static String CHECKDELAY = "CgkI9Y3S0soCEAIQBQ";
public final static String CHECKHUGEDELAY = "CgkI9Y3S0soCEAIQCA";
public final static String VETERAN = "CgkI9Y3S0soCEAIQCg";
MyPagerAdapter mPagerAdapter;
String[] titles;
StationList.Stationinfo closest;
LocationManager locationManager;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_game, null);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
((AppCompatActivity) getActivity()).getSupportActionBar().setSubtitle(null);
//this.getActivity().getActionBar().setIcon(R.drawable.ic_game);
ViewPager pager = (ViewPager) getView().findViewById(R.id.pager);
titles = this.getResources().getStringArray(R.array.titles);
mPagerAdapter = new MyPagerAdapter(titles);
pager.setAdapter(mPagerAdapter);
//mPagerAdapter.notifyDataSetChanged();
PagerSlidingTabStrip tabs = (PagerSlidingTabStrip) getView().findViewById(R.id.tabs);
tabs.setViewPager(pager);
pager.setOffscreenPageLimit(2);
// mHelper = new GameHelper(getActivity(),);
// mHelper.setup(this);
try {
String langue = getActivity().getString(R.string.url_lang);
if (PreferenceManager.getDefaultSharedPreferences(getActivity()).getBoolean(
"prefnl", false))
langue = "nl";
if (langue.contentEquals("en"))
langue = "fr";
InputStream inputStream = getActivity().getAssets().open("stations" + langue + ".json");
Reader r = new InputStreamReader(inputStream);
Gson gson = new Gson();
list = gson.fromJson(r, StationList.StationsList.class);
} catch (IOException e) {
e.printStackTrace();
}
try {
me = Utils.getLastLoc(this.getActivity());
locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
} catch (SecurityException e) {
ActivityCompat.requestPermissions(getActivity(),
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
0);
}
setHasOptionsMenu(true);
GoogleApiClient mGoogleApiClient = new GoogleApiClient.Builder(this.getActivity())
.addApi(Games.API)
.addScope(Games.SCOPE_GAMES)
.build();
if (isSignedIn())
setupOk();
else
beginUserInitiatedSignIn();
}
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED)
switch (requestCode) {
case 0: {
me = Utils.getLastLoc(this.getActivity());
locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
if (isSignedIn())
setupOk();
else
beginUserInitiatedSignIn();
return;
}
}
return;
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
menu.add(Menu.NONE, 0, Menu.NONE, R.string.game_action_map)
.setIcon(android.R.drawable.ic_menu_myplaces)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (closest != null)
switch (item.getItemId()) {
case (0):
String uri = "geo:0,0?q=" + closest.locationY + "," + closest.locationX + " (" + closest.getStation() + ")";
startActivity(new Intent(android.content.Intent.ACTION_VIEW, Uri.parse(uri)));
return true;
default:
return super.onOptionsItemSelected(item);
}
return super.onOptionsItemSelected(item);
}
@Override
public void onPause() {
super.onPause();
Crouton.cancelAllCroutons();
if (locationManager != null)
locationManager.removeUpdates(this);
}
@Override
public void onResume() {
super.onResume();
try {//Some devices have no GPS
if (locationManager != null)
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10 * DateUtils.SECOND_IN_MILLIS, 10, this);
} catch (Exception e) {
e.printStackTrace();
}
if (init && !this.isSignedIn())
this.beginUserInitiatedSignIn();
init = true;
String provider = Settings.Secure.getString(getActivity().getContentResolver(),
Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if (!provider.contains(LocationManager.GPS_PROVIDER)) {
crouton = Crouton.makeText(getActivity(), R.string.game_err_gps, Style.ALERT, R.id.pager).setConfiguration(CONFIGURATION_INFINITE).setOnClickListener(this);
crouton.show();
}
}
@Override
public void onStart() {
super.onStart();
mHelper.onStart(this.getActivity());
}
@Override
public void onStop() {
super.onStop();
mHelper.onStop();
}
@Override
public void onActivityResult(int request, int response, Intent data) {
super.onActivityResult(request, response, data);
setupOk();
}
private void setupOk() {
SharedPreferences sp;
try {
sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
} catch (Exception e) {
e.printStackTrace();
return;
}
int score = sp.getInt("searchGame", 0) + 1;
boolean chat = sp.getBoolean("chatUnlock", false);
Log.e("", "chat " + chat);
try {
Games.Achievements.setSteps(getApiClient(), PlannerFragment.SEARCH, score);
if (chat)
Games.Achievements.unlock(getApiClient(), ChatActivity.ID);
} catch (Exception e) {
e.printStackTrace();
}
Log.e("", "SETUP");
try {
getView().findViewById(R.id.profile).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
getActivity().startActivityForResult(Games.Leaderboards.getLeaderboardIntent(getApiClient(), LEADER), 1);
} catch (Exception e) {
e.printStackTrace();
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
try {//Just to be sure player exists
Games.Leaderboards.submitScore(getApiClient(), LEADER, newScore);
} catch (Exception e) {
e.printStackTrace();
}
try {
Player p = Games.Players.getCurrentPlayer(getApiClient());
try {
((TextView) getView().findViewById(R.id.currentuserName)).setText(p.getDisplayName());
} catch (Exception e) {
e.printStackTrace();
}
//Picasso.with(this.getActivity()).load(p.getIconImageUri().getPath()).into((ImageView)getView().findViewById(R.id.profilePic));
ImageManager im = ImageManager.create(this.getActivity());
im.loadImage(this, p.getHiResImageUri());
id = p.getPlayerId();
refreshScores();
} catch (Exception e) {
e.printStackTrace();
}
try {
int installed = (int) (System.currentTimeMillis() - getActivity()
.getPackageManager()
.getPackageInfo(getActivity().getPackageName(), 0)
.firstInstallTime) / (int) DateUtils.DAY_IN_MILLIS;
if (installed > 0)
Games.Achievements.setSteps(getApiClient(), VETERAN, installed);
Log.e("", "installed" + installed);
Games.Achievements.load(getApiClient(), false).setResultCallback(new ResultCallback<Achievements.LoadAchievementsResult>() {
@Override
public void onResult(Achievements.LoadAchievementsResult loadAchievementsResult) {
Iterator<Achievement> it = loadAchievementsResult.getAchievements().iterator();
AchievementAdapter adapter = new AchievementAdapter(GameFragment.this.getActivity(), R.layout.row_achieve, new ArrayList<Achievement>());
while (it.hasNext()) {
adapter.add(it.next());
}
((MyStaggeredGridView) getView().findViewById(R.id.listAchivement)).setAdapter(adapter);
}
});
} catch (Exception e) {
e.printStackTrace();
}
setupClosest();
startCountDownThread();
}
@Override
public void onConnected(Bundle bundle) {
setupOk();
}
@Override
public void onConnectionSuspended(int i) {
Log.e("", "SUSPENDED");
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.e("", "FAIL");
}
@Override
public void onSignInFailed() {
Log.e("", "SIGNIN NOK");
}
@Override
public void onSignInSucceeded() {
Log.e("", "SIGNIN OK");
setupOk();
}
private String station1;
private String station2;
private String station3;
public void setupClosest() {
Log.e("CVE", "CLOSEST");
try {
for (StationList.Stationinfo aStation : list.station) {
double dDis = Utils.distance(
Double.valueOf(aStation.locationX),
Double.valueOf(aStation.locationY), me.getLongitude(),
me.getLatitude());
aStation.distance = ((int) (dDis * 100)) / 100.0;
}
Collections.sort(list.station);
closest = list.station.get(0);
View l = getView().findViewById(R.id.closest1Layout);
((TextView) l.findViewById(R.id.closestTitle)).setText(closest
.getStation());
((TextView) l.findViewById(R.id.closestDesc))
.setText(closest.getDistance());
station1 = closest.getStation();
setupLayout(closest, R.id.closest1Layout);
StationList.Stationinfo stationinfo = list.station.get(1);
l = getView().findViewById(R.id.closest2Layout);
((TextView) l.findViewById(R.id.closestTitle)).setText(stationinfo
.getStation());
((TextView) l.findViewById(R.id.closestDesc))
.setText(stationinfo.getDistance());
station2 = stationinfo.getStation();
setupLayout(stationinfo, R.id.closest2Layout);
stationinfo = list.station.get(2);
l = getView().findViewById(R.id.closest3Layout);
((TextView) l.findViewById(R.id.closestTitle)).setText(stationinfo
.getStation());
((TextView) l.findViewById(R.id.closestDesc))
.setText(stationinfo.getDistance());
station3 = stationinfo.getStation();
setupLayout(stationinfo, R.id.closest3Layout);
} catch (Exception e) {
e.printStackTrace();
}
}
String id = "";
private void refreshScores() {
top = false;
Games.Leaderboards.loadCurrentPlayerLeaderboardScore(getApiClient(), LEADER, LeaderboardVariant.TIME_SPAN_WEEKLY, LeaderboardVariant.COLLECTION_PUBLIC).setResultCallback(new ResultCallback<Leaderboards.LoadPlayerScoreResult>() {
@Override
public void onResult(Leaderboards.LoadPlayerScoreResult loadPlayerScoreResult) {
if (loadPlayerScoreResult != null && loadPlayerScoreResult.getScore() != null) {
((TextView) getView().findViewById(R.id.currentuserRank)).setText("" + loadPlayerScoreResult.getScore().getDisplayRank());
newScore = loadPlayerScoreResult.getScore().getRawScore();
((TextView) getView().findViewById(R.id.currentuserPoints)).setText("" + loadPlayerScoreResult.getScore().getDisplayScore());
}
}
});
Games.Leaderboards.loadPlayerCenteredScores(getApiClient(), LEADER, LeaderboardVariant.TIME_SPAN_WEEKLY, LeaderboardVariant.COLLECTION_PUBLIC, 25).setResultCallback(new ResultCallback<Leaderboards.LoadScoresResult>() {
@Override
public void onResult(Leaderboards.LoadScoresResult loadScoresResult) {
LeaderboardScoreBuffer leaderboardScores = loadScoresResult.getScores();
try {
Iterator<LeaderboardScore> it = leaderboardScores.iterator();
HighScoreAdapter adapter = new HighScoreAdapter(GameFragment.this.getActivity(), R.layout.row_high, new ArrayList<LeaderboardScore>());
while (it.hasNext()) {
LeaderboardScore temp = it.next();
adapter.add(temp);
}
// leaderboardScores.close();
((GridView) getView().findViewById(R.id.listHighscore)).setAdapter(adapter);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
@Override
public void onClick(View v) {
crouton.cancel();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
@Override
public void onLocationChanged(Location location) {
me = location;
setupClosest();
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onImageLoaded(Uri uri, Drawable drawable, boolean b) {
try {
((ImageView) getView().findViewById(R.id.currentprofilePic)).setImageDrawable(drawable);
} catch (Exception e) {
e.printStackTrace();
}
}
public class StationList {
public class StationsList {
public ArrayList<Stationinfo> station;
}
public class Stationinfo implements Comparable<Object> {
public String name;
public String locationX;
public String locationY;
public double distance;
@Override
public int compareTo(Object toCompare) {
return Double.compare(this.distance,
((Stationinfo) (toCompare)).distance);
}
public CharSequence getDistance() {
if (distance > 1)
return distance + "km";
else
return distance * 1000 + "m";
}
public String getStation() {
return this.name;
}
}
}
private void startCountDownThread() {
final Runnable updater = new Runnable() {
@Override
public void run() {
try {
if ((System.currentTimeMillis() < PreferenceManager
.getDefaultSharedPreferences(GameFragment.this.getActivity())
.getLong("next", 0))) {
long delta = PreferenceManager.getDefaultSharedPreferences(
GameFragment.this.getActivity()).getLong("next", 0)
- System.currentTimeMillis();
int minutes = (int) (delta / DateUtils.MINUTE_IN_MILLIS);
int secondes = (int) ((delta % DateUtils.MINUTE_IN_MILLIS) / DateUtils.SECOND_IN_MILLIS);
GameFragment.this.getActivity().getActionBar().setTitle(
getString(R.string.game_cooling) + minutes + "m" + secondes
+ "s"
);
handler.postDelayed(this, 1000);
} else
GameFragment.this.getActivity().getActionBar().setTitle(getString(R.string.nav_drawer_game));
} catch (Exception e) {
e.printStackTrace();
}
}
};
handler.post(updater);
}
public void setupLayout(final StationList.Stationinfo station, int id) {
/*new DisplayPointsTask(station,)
.execute();*/
final LinearLayout ll = ((LinearLayout) getView().findViewById(id));
String url = "http://api.irail.be/liveboard.php/?station="
+ station.getStation().replace(" ", "%20") + "&format=JSON&fast=true";
Ion.with(getActivity()).load(url).as(new TypeToken<Station>() {
}).setCallback(new FutureCallback<Station>() {
@Override
public void onCompleted(Exception e, Station result) {
Station.StationDepartures stationDepartures = result.getStationDepartures();
int delay = 0;
int num = 1;
if (stationDepartures != null)
try {
for (Station.StationDeparture aDeparture : stationDepartures.getStationDeparture()) {
if (!aDeparture.getDelay().contentEquals("0")) {
delay += Integer.valueOf(aDeparture.getDelay());
num += 1;
}
}
} catch (Exception e1) {
e1.printStackTrace();
}
final int total = num;
final int i = delay < 60 ? 1 : delay / 60;
TextView tv = (TextView) ll.findViewById(R.id.closestTime);
tv.setText(getString(R.string.game_station_score) + num);
ll.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
if (station.distance > 0.5) {
crouton(getString(R.string.game_too_far) + " " + station.getDistance(), Style.ALERT);
return;
}
if ((System.currentTimeMillis() > PreferenceManager
.getDefaultSharedPreferences(GameFragment.this.getActivity())
.getLong("next", 0))) {
SharedPreferences.Editor e = PreferenceManager
.getDefaultSharedPreferences(
GameFragment.this.getActivity()).edit();
Games.Achievements.unlock(getApiClient(), CHECKIN);
if (i >= 50)
Games.Achievements.unlock(getApiClient(), CHECKHUGEDELAY);
else if (i >= 20)
Games.Achievements.unlock(getApiClient(), CHECKDELAY);
newScore += total;
e.putLong(
"next",
(System.currentTimeMillis() + 10 * DateUtils.MINUTE_IN_MILLIS));
e.commit();
Games.Leaderboards.submitScore(getApiClient(), LEADER, newScore);
refreshScores();
startCountDownThread();
} else
croutonWarn(R.string.game_wait);
}
});
}
});
}
private void croutonWarn(int i) {
croutonWarn(getString(i));
}
private void croutonWarn(String string) {
crouton(string, Style.ALERT);
}
public void debug(String s) {
croutonWarn(s);
}
public void crouton(String text, Style style) {
Crouton.makeText(this.getActivity(), text, style, R.id.my_awesome_toolbar).show();
}
}
|
package com.hea3ven.buildingbricks.compat.vanilla.blocks;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import net.minecraft.block.Block;
import net.minecraft.block.BlockGrass;
import net.minecraft.block.properties.IProperty;
import net.minecraft.block.state.BlockState;
import net.minecraft.block.state.IBlockState;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.init.Blocks;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.BlockPos;
import net.minecraft.util.EnumWorldBlockLayer;
import net.minecraft.util.StatCollector;
import net.minecraft.world.ColorizerGrass;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.biome.BiomeColorHelper;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import com.hea3ven.buildingbricks.core.blocks.BlockBuildingBricksSlab;
import com.hea3ven.buildingbricks.core.blocks.base.BlockMaterial;
import com.hea3ven.buildingbricks.core.materials.*;
import com.hea3ven.buildingbricks.core.tileentity.TileMaterial;
public class BlockGrassSlab extends BlockBuildingBricksSlab implements BlockMaterial {
private Material mat;
public BlockGrassSlab() {
super(StructureMaterial.GRASS);
}
@SideOnly(Side.CLIENT)
public int getBlockColor() {
return ColorizerGrass.getGrassColor(0.5D, 1.0D);
}
@SideOnly(Side.CLIENT)
public int getRenderColor(IBlockState state) {
return this.getBlockColor();
}
@SideOnly(Side.CLIENT)
public int colorMultiplier(IBlockAccess worldIn, BlockPos pos, int renderPass) {
return BiomeColorHelper.getGrassColorAtPos(worldIn, pos);
}
@SideOnly(Side.CLIENT)
public EnumWorldBlockLayer getBlockLayer() {
return EnumWorldBlockLayer.CUTOUT_MIPPED;
}
@Override
public List<ItemStack> getDrops(IBlockAccess world, BlockPos pos, IBlockState state, int fortune) {
List<ItemStack> stacks = new ArrayList<>();
BlockDescription slabBlock = MaterialRegistry.get("minecraft:dirt").getBlock(MaterialBlockType.SLAB);
if (slabBlock != null)
stacks.add(slabBlock.getStack().copy());
return stacks;
}
@Override
protected boolean canSilkHarvest() {
return true;
}
@Override
protected BlockState createBlockState() {
Collection<IProperty> props = new ArrayList<>(super.createBlockState().getProperties());
props.add(BlockGrass.SNOWY);
return new BlockState(this, props.toArray(new IProperty[props.size()]));
}
public IBlockState getActualState(IBlockState state, IBlockAccess worldIn, BlockPos pos) {
Block blockN = worldIn.getBlockState(pos.north()).getBlock();
Block blockS = worldIn.getBlockState(pos.south()).getBlock();
Block blockE = worldIn.getBlockState(pos.east()).getBlock();
Block blockW = worldIn.getBlockState(pos.west()).getBlock();
return setSnowy(state,
blockN == Blocks.snow || blockN == Blocks.snow_layer || blockS == Blocks.snow ||
blockS == Blocks.snow_layer || blockE == Blocks.snow || blockE == Blocks.snow_layer ||
blockW == Blocks.snow || blockW == Blocks.snow_layer);
}
public static boolean getSnowy(IBlockState state) {
return state.getValue(BlockGrass.SNOWY);
}
public static IBlockState setSnowy(IBlockState state, boolean snowy) {
return state.withProperty(BlockGrass.SNOWY, snowy);
}
@Override
public String getLocalizedName(Material mat) {
if (StatCollector.canTranslate(getUnlocalizedName() + ".name"))
return super.getLocalizedName();
else
return blockLogic.getLocalizedName(mat);
}
@Override
public Material getMaterial(IBlockAccess world, BlockPos pos) {
return getGrassMaterial();
}
private Material getGrassMaterial() {
if (mat == null)
mat = MaterialRegistry.get("minecraft:grass");
return mat;
}
@Override
public void getSubBlocks(Item itemIn, CreativeTabs tab, List<ItemStack> list) {
if (TileMaterial.blocksInCreative) {
super.getSubBlocks(itemIn, tab, list);
}
}
}
|
package com.skelril.aurora.shards.ShnugglesPrime;
import com.sk89q.craftbook.bukkit.BukkitPlayer;
import com.sk89q.worldedit.BlockVector;
import com.sk89q.worldedit.blocks.BlockID;
import com.sk89q.worldedit.blocks.ItemID;
import com.sk89q.worldedit.bukkit.BukkitUtil;
import com.sk89q.worldedit.regions.CuboidRegion;
import com.sk89q.worldedit.regions.Region;
import com.sk89q.worldedit.world.World;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import com.skelril.OpenBoss.Boss;
import com.skelril.OpenBoss.EntityDetail;
import com.skelril.aurora.bosses.detail.SBossDetail;
import com.skelril.aurora.events.anticheat.ThrowPlayerEvent;
import com.skelril.aurora.exceptions.UnsupportedPrayerException;
import com.skelril.aurora.prayer.PrayerComponent;
import com.skelril.aurora.prayer.PrayerType;
import com.skelril.aurora.shard.ShardInstance;
import com.skelril.aurora.shards.BukkitShardInstance;
import com.skelril.aurora.util.ChanceUtil;
import com.skelril.aurora.util.ChatUtil;
import com.skelril.aurora.util.EntityUtil;
import com.skelril.aurora.util.LocationUtil;
import com.skelril.aurora.util.timer.IntegratedRunnable;
import com.skelril.aurora.util.timer.TimedRunnable;
import com.skelril.aurora.util.timer.TimerUtil;
import org.bukkit.ChatColor;
import org.bukkit.Effect;
import org.bukkit.Location;
import org.bukkit.block.BlockState;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.*;
import org.bukkit.inventory.EntityEquipment;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import org.bukkit.scheduler.BukkitTask;
import org.bukkit.util.Vector;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Random;
import static com.sk89q.commandbook.CommandBook.inst;
import static com.sk89q.commandbook.CommandBook.logger;
import static com.zachsthings.libcomponents.bukkit.BasePlugin.server;
public class ShnugglesPrimeInstance extends BukkitShardInstance<ShnugglesPrimeShard> implements Runnable {
private Giant boss = null;
private long lastAttack = 0;
private int lastAttackNumber = -1;
private long lastDeath = 0;
private boolean damageHeals = false;
private Random random = new Random();
private long lastUltimateAttack = -1;
private boolean flagged = false;
private double toHeal = 0;
private List<Location> spawnPts = new ArrayList<>();
public ShnugglesPrimeInstance(ShnugglesPrimeShard shard, World world, ProtectedRegion region) {
super(shard, world, region);
probeArea();
}
public void probeArea() {
spawnPts.clear();
BlockVector min = getRegion().getParent().getMinimumPoint();
BlockVector max = getRegion().getParent().getMaximumPoint();
int minX = min.getBlockX();
int minZ = min.getBlockZ();
int minY = min.getBlockY();
int maxX = max.getBlockX();
int maxZ = max.getBlockZ();
int maxY = max.getBlockY();
BlockState block;
for (int x = minX; x <= maxX; x++) {
for (int z = minZ; z <= maxZ; z++) {
for (int y = maxY; y >= minY; --y) {
block = getBukkitWorld().getBlockAt(x, y, z).getState();
if (!block.getChunk().isLoaded()) block.getChunk().load();
if (block.getTypeId() == BlockID.GOLD_BLOCK) {
spawnPts.add(block.getLocation().add(0, 2, 0));
}
}
}
}
}
public static ShnugglesPrimeInstance getInst(EntityDetail detail) {
if (detail instanceof SBossDetail) {
ShardInstance<?> inst = ((SBossDetail) detail).getInstance();
if (inst instanceof ShnugglesPrimeInstance) {
return (ShnugglesPrimeInstance) inst;
}
}
return null;
}
@Override
public void teleportTo(com.sk89q.worldedit.entity.Player... players) {
Location target = LocationUtil.getCenter(getBukkitWorld(), region);
for (com.sk89q.worldedit.entity.Player player : players) {
if (player instanceof BukkitPlayer) {
Player bPlayer = ((BukkitPlayer) player).getPlayer();
bPlayer.teleport(target);
}
}
}
@Override
public void run() {
if (!isBossSpawned()) {
if (lastDeath == 0 || System.currentTimeMillis() - lastDeath >= 1000 * 60 * 3) {
removeMobs();
spawnBoss();
}
} else if (!isEmpty()) {
equalize();
runAttack(ChanceUtil.getRandom(OPTION_COUNT));
}
}
public Giant getBoss() {
return boss;
}
public void healBoss(float percentHealth) {
if (isBossSpawned()) {
EntityUtil.heal(boss, boss.getMaxHealth() * percentHealth);
}
}
public void removeMobs() {
getContained(1, Monster.class).forEach(e -> {
for (int i = 0; i < 20; i++) getBukkitWorld().playEffect(e.getLocation(), Effect.SMOKE, 0);
e.remove();
});
}
public void buffBabies() {
for (Zombie zombie : getContained(Zombie.class)) {
zombie.addPotionEffect(new PotionEffect(PotionEffectType.INCREASE_DAMAGE, 20 * 20, 3), true);
}
}
public boolean isBossSpawned() {
if (!isActive()) return true;
boolean found = false;
boolean second = false;
for (Giant e : getContained(Giant.class)) {
if (e.isValid()) {
if (!found) {
boss = e;
found = true;
} else if (e.getHealth() < boss.getHealth()) {
boss = e;
second = true;
} else {
e.remove();
}
}
}
if (second) {
getContained(Giant.class).stream().filter(e -> e.isValid() && !e.equals(boss)).forEach(Entity::remove);
}
return boss != null && boss.isValid();
}
public void spawnBoss() {
BlockVector min = getRegion().getMinimumPoint();
BlockVector max = getRegion().getMaximumPoint();
Region region = new CuboidRegion(min, max);
Location l = BukkitUtil.toLocation(getBukkitWorld(), region.getCenter());
boss = getBukkitWorld().spawn(l, Giant.class);
getMaster().getBossManager().bind(new Boss(boss, new SBossDetail(this)));
}
public void bossDied() {
lastDeath = System.currentTimeMillis();
boss = null;
}
public void equalize() {
flagged = false;
// Equalize Players
for (Player player : getContained(Player.class)) {
try {
getMaster().getAdmin().standardizePlayer(player);
if (player.hasPotionEffect(PotionEffectType.DAMAGE_RESISTANCE)) {
flagged = true;
}
if (player.getVehicle() != null) {
player.getVehicle().eject();
ChatUtil.sendWarning(player, "The boss throws you off!");
}
} catch (Exception e) {
logger().warning("The player: " + player.getName() + " may have an unfair advantage.");
}
}
}
public boolean damageHeals() {
return damageHeals;
}
public boolean canUseUltimate(long time) {
return System.currentTimeMillis() - lastUltimateAttack >= time;
}
public void updateLastUltimate() {
lastUltimateAttack = System.currentTimeMillis();
}
public int getLastAttack() {
return lastAttack <= 13000 ? lastAttackNumber : -1;
}
public void printBossHealth() {
int current = (int) Math.ceil(boss.getHealth());
int max = (int) Math.ceil(boss.getMaxHealth());
String message = "Boss Health: " + current + " / " + max;
ChatUtil.sendNotice(getContained(Player.class), ChatColor.DARK_AQUA, message);
}
private static final ItemStack weapon = new ItemStack(ItemID.BONE);
static {
ItemMeta weaponMeta = weapon.getItemMeta();
weaponMeta.addEnchant(Enchantment.DAMAGE_ALL, 2, true);
weapon.setItemMeta(weaponMeta);
}
public void spawnMinions(LivingEntity target) {
int spawnCount = Math.max(3, getContained(Player.class).size());
for (Location spawnPt : spawnPts) {
if (ChanceUtil.getChance(11)) {
for (int i = spawnCount; i > 0; --i) {
Zombie z = getBukkitWorld().spawn(spawnPt, Zombie.class);
z.setBaby(true);
EntityEquipment equipment = z.getEquipment();
equipment.setArmorContents(null);
equipment.setItemInHand(weapon.clone());
equipment.setItemInHandDropChance(0F);
if (target != null) {
z.setTarget(target);
}
}
}
}
}
public static final int OPTION_COUNT = 9;
public void runAttack(int attackCase) {
int delay = ChanceUtil.getRangedRandom(13000, 17000);
if (lastAttack != 0 && System.currentTimeMillis() - lastAttack <= delay) return;
Collection<Player> containedP = getContained(1, Player.class);
Collection<Player> contained = getContained(Player.class);
if (contained == null || contained.size() <= 0) return;
if (attackCase < 1 || attackCase > OPTION_COUNT) attackCase = ChanceUtil.getRandom(OPTION_COUNT);
// AI system
if ((attackCase == 5 || attackCase == 9) && boss.getHealth() > boss.getMaxHealth() * .9) {
attackCase = ChanceUtil.getChance(2) ? 8 : 2;
}
if (flagged && ChanceUtil.getChance(4)) {
attackCase = ChanceUtil.getChance(2) ? 4 : 7;
}
for (Player player : contained) {
if (player.getHealth() < 4) {
attackCase = 2;
break;
}
}
if (boss.getHealth() < boss.getMaxHealth() * .3 && ChanceUtil.getChance(2)) {
attackCase = 9;
}
if (getContained(Zombie.class).size() > 200) {
attackCase = 7;
}
if ((attackCase == 3 || attackCase == 6) && boss.getHealth() < boss.getMaxHealth() * .6) {
runAttack(ChanceUtil.getRandom(OPTION_COUNT));
return;
}
switch (attackCase) {
case 1:
ChatUtil.sendWarning(containedP, "Taste my wrath!");
for (Player player : contained) {
// Call this event to notify AntiCheat
server().getPluginManager().callEvent(new ThrowPlayerEvent(player));
player.setVelocity(new Vector(
random.nextDouble() * 3 - 1.5,
random.nextDouble() * 1 + 1.3,
random.nextDouble() * 3 - 1.5
));
player.setFireTicks(20 * 3);
}
break;
case 2:
ChatUtil.sendWarning(containedP, "Embrace my corruption!");
for (Player player : contained) {
player.addPotionEffect(new PotionEffect(PotionEffectType.WITHER, 20 * 12, 1));
}
break;
case 3:
ChatUtil.sendWarning(containedP, "Are you BLIND? Mwhahahaha!");
for (Player player : contained) {
player.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, 20 * 4, 0));
}
break;
case 4:
ChatUtil.sendWarning(containedP, ChatColor.DARK_RED + "Tango time!");
server().getScheduler().runTaskLater(inst(), () -> {
if (!isBossSpawned()) return;
for (Player player : getContained(Player.class)) {
if (boss.hasLineOfSight(player)) {
ChatUtil.sendNotice(player, "Come closer...");
player.teleport(boss.getLocation());
player.damage(100, boss);
// Call this event to notify AntiCheat
server().getPluginManager().callEvent(new ThrowPlayerEvent(player));
player.setVelocity(new Vector(
random.nextDouble() * 1.7 - 1.5,
random.nextDouble() * 2,
random.nextDouble() * 1.7 - 1.5
));
} else {
ChatUtil.sendNotice(player, "Fine... No tango this time...");
}
}
ChatUtil.sendNotice(getContained(1, Player.class), "Now wasn't that fun?");
}, 20 * 7);
break;
case 5:
if (!damageHeals) {
ChatUtil.sendWarning(containedP, "I am everlasting!");
damageHeals = true;
server().getScheduler().runTaskLater(inst(), () -> {
if (damageHeals) {
damageHeals = false;
if (!isBossSpawned()) return;
ChatUtil.sendNotice(getContained(1, Player.class), "Thank you for your assistance.");
}
}, 20 * 12);
break;
}
runAttack(ChanceUtil.getRandom(OPTION_COUNT));
return;
case 6:
ChatUtil.sendWarning(containedP, "Fire is your friend...");
for (Player player : contained) {
player.setFireTicks(20 * 30);
}
break;
case 7:
ChatUtil.sendWarning(containedP, ChatColor.DARK_RED + "Bask in my glory!");
server().getScheduler().runTaskLater(inst(), () -> {
if (!isBossSpawned()) return;
// Set defaults
boolean baskInGlory = getContained(Player.class).size() == 0;
damageHeals = true;
// Check Players
for (Player player : getContained(Player.class)) {
if (inst().hasPermission(player, "aurora.prayer.intervention") && ChanceUtil.getChance(3)) {
ChatUtil.sendNotice(player, "A divine wind hides you from the boss.");
continue;
}
if (boss.hasLineOfSight(player)) {
ChatUtil.sendWarning(player, ChatColor.DARK_RED + "You!");
baskInGlory = true;
}
}
//Attack
if (baskInGlory) {
spawnPts.stream().filter(pt -> ChanceUtil.getChance(12)).forEach(pt -> {
getBukkitWorld().createExplosion(pt.getX(), pt.getY(), pt.getZ(), 10, false, false);
});
//Schedule Reset
server().getScheduler().runTaskLater(inst(), () -> damageHeals = false, 10);
return;
}
// Notify if avoided
ChatUtil.sendNotice(getContained(1, Player.class), "Gah... Afraid are you friends?");
}, 20 * 7);
break;
case 8:
ChatUtil.sendWarning(containedP, ChatColor.DARK_RED + "I ask thy lord for aid in this all mighty battle...");
ChatUtil.sendWarning(containedP, ChatColor.DARK_RED + "Heed thy warning, or perish!");
server().getScheduler().runTaskLater(inst(), () -> {
if (!isBossSpawned()) return;
ChatUtil.sendWarning(getContained(1, Player.class), "May those who appose me die a death like no other...");
getContained(Player.class).stream().filter(boss::hasLineOfSight).forEach(player -> {
ChatUtil.sendWarning(getContained(1, Player.class), "Perish " + player.getName() + "!");
try {
getMaster().getPrayers().influencePlayer(
player,
PrayerComponent.constructPrayer(player, PrayerType.DOOM, 120000)
);
} catch (UnsupportedPrayerException e) {
e.printStackTrace();
}
});
}, 20 * 7);
break;
case 9:
ChatUtil.sendNotice(containedP, ChatColor.DARK_RED, "My minions our time is now!");
IntegratedRunnable minionEater = new IntegratedRunnable() {
@Override
public boolean run(int times) {
if (!isBossSpawned()) return true;
for (LivingEntity entity : getContained(LivingEntity.class)) {
if (entity instanceof Giant || !ChanceUtil.getChance(5)) continue;
double realDamage = entity.getHealth();
if (entity instanceof Zombie && ((Zombie) entity).isBaby()) {
entity.setHealth(0);
} else {
entity.damage(realDamage, boss);
}
toHeal += realDamage / 3;
}
if (TimerUtil.matchesFilter(times + 1, -1, 2)) {
ChatUtil.sendNotice(getContained(1, Player.class), ChatColor.DARK_AQUA, "The boss has drawn in: " + (int) toHeal + " health.");
}
return true;
}
@Override
public void end() {
if (!isBossSpawned()) return;
boss.setHealth(Math.min(toHeal + boss.getHealth(), boss.getMaxHealth()));
toHeal = 0;
ChatUtil.sendNotice(getContained(1, Player.class), "Thank you my minions!");
printBossHealth();
}
};
TimedRunnable minonEatingTask = new TimedRunnable(minionEater, 20);
BukkitTask minionEatingTaskExecutor = server().getScheduler().runTaskTimer(inst(), minonEatingTask, 0, 10);
minonEatingTask.setTask(minionEatingTaskExecutor);
break;
}
lastAttack = System.currentTimeMillis();
lastAttackNumber = attackCase;
}
}
|
package com.tealcube.minecraft.bukkit.highnoon.listeners;
import com.tealcube.minecraft.bukkit.facecore.utilities.MessageUtils;
import com.tealcube.minecraft.bukkit.highnoon.HighNoonPlugin;
import com.tealcube.minecraft.bukkit.highnoon.data.Duel;
import com.tealcube.minecraft.bukkit.highnoon.data.Duelist;
import com.tealcube.minecraft.bukkit.highnoon.events.DuelEndEvent;
import com.tealcube.minecraft.bukkit.highnoon.managers.ArenaManager;
import com.tealcube.minecraft.bukkit.highnoon.managers.DuelistManager;
import com.tealcube.minecraft.bukkit.highnoon.tasks.HealPlayerTask;
import com.tealcube.minecraft.bukkit.highnoon.utils.Misc;
import org.bukkit.Bukkit;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile;
import org.bukkit.entity.Tameable;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent;
public class CombatListener implements Listener {
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onEntityDamage(EntityDamageEvent event) {
Entity entity = event.getEntity();
if (!(entity instanceof Player)) {
return;
}
Player player = (Player) entity;
Duelist duelist = DuelistManager.getDuelist(player.getUniqueId());
if (duelist.getTarget() == null) {
return;
}
double playerHealth = player.getHealth();
double damageAmount = event.getFinalDamage();
if ((playerHealth - damageAmount) > 0.05) {
return;
}
Player target = Bukkit.getPlayer(duelist.getTarget());
event.setCancelled(true);
player.setHealth(1);
player.teleport(ArenaManager.getArena(player.getUniqueId()));
DuelEndEvent ev = new DuelEndEvent(new Duel(duelist.getUniqueId(), duelist.getTarget()));
ev.getDuel().setWinner(duelist.getTarget());
ev.getDuel().setLoser(duelist.getUniqueId());
Bukkit.getPluginManager().callEvent(ev);
new HealPlayerTask(player).runTaskLater(HighNoonPlugin.getInstance(), 1);
new HealPlayerTask(target).runTaskLater(HighNoonPlugin.getInstance(), 1);
MessageUtils.sendMessage(player, "<red>You lost your duel!");
MessageUtils.sendMessage(target, "<green>You won your duel!");
Duelist targetDuelist = DuelistManager.getDuelist(duelist.getTarget());
targetDuelist.setTarget(null);
duelist.setTarget(null);
duelist.getTask().cancel();
duelist.setTask(null);
targetDuelist.setTask(null);
duelist.setLastDuelEnded(Misc.currentTimeSeconds());
targetDuelist.setLastDuelEnded(Misc.currentTimeSeconds());
}
@EventHandler(priority = EventPriority.HIGH)
public void onEntityDamageByEntity(EntityDamageByEntityEvent event) {
if (event.getDamage() <= 0) {
return;
}
Entity attacker = event.getDamager();
Entity defender = event.getEntity();
if (attacker instanceof Projectile) {
if (((Projectile) attacker).getShooter() instanceof LivingEntity) {
attacker = (LivingEntity) ((Projectile) attacker).getShooter();
}
} else if (attacker instanceof Tameable) {
if (((Tameable) attacker).getOwner() instanceof LivingEntity) {
attacker = (LivingEntity) ((Tameable) attacker).getOwner();
}
}
if (defender instanceof Player) {
if (!((Player) defender).isOnline() || !defender.isValid()) {
return;
}
if (attacker instanceof Player) {
Duelist attackerDuelist = DuelistManager.getDuelist(attacker.getUniqueId());
Duelist defenderDuelist = DuelistManager.getDuelist(defender.getUniqueId());
if (attackerDuelist.getTarget() == null && defenderDuelist.getTarget() == null) {
return;
}
if (attackerDuelist.getTarget() == null) {
MessageUtils.sendMessage(attacker, "<red>You cannot attack them, they are in a duel.");
event.setCancelled(true);
return;
}
if (defenderDuelist.getTarget() == null) {
MessageUtils.sendMessage(attacker, "<red>You cannot attack them, you are in a duel.");
event.setCancelled(true);
return;
}
if (attackerDuelist.getTarget().equals(defenderDuelist.getUniqueId()) && defenderDuelist.getTarget().equals(attackerDuelist
.getUniqueId())) {
return;
}
MessageUtils.sendMessage(attacker, "<red>You cannot attack them, you're not dueling them.");
event.setCancelled(true);
}
}
}
}
|
package com.zenith.livinghistory.api.zenithlivinghistoryapi.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.zenith.livinghistory.api.zenithlivinghistoryapi.utils.CascadeSave;
import org.joda.time.DateTime;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.DBRef;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
@Document(collection = "Contents")
public class Content implements Serializable {
public Content() {
}
public Content(String contentType, String title, String description, String[] tags, DateTime date, LocationBody location, String creator) {
this.contentType = contentType;
this.title = title;
this.description = description;
this.tags = tags;
this.date = date;
this.location = location;
this.creator = creator;
}
@JsonProperty("@contentType")
private String contentType;
@Id
private String id;
private String title;
@Indexed
private String description;
private String[] tags;
private DateTime date;
private LocationBody location;
private String creator;
@DBRef
@CascadeSave
@Field("annotations")
private List<Annotation> annotations = new ArrayList<>();
public List<Annotation> getAnnotations() {
return annotations;
}
public void setAnnotations(List<Annotation> annotations) {
this.annotations = annotations;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getCreator() {
return creator;
}
public void setCreator(String creator) {
this.creator = creator;
}
public String[] getTags() { return tags; }
public void setTags(String[] tags) { this.tags = tags; }
public DateTime getDate() {
return date;
}
public void setDate(DateTime date) {
this.date = date;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getContentType() {
return contentType;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
public LocationBody getLocation() {
return location;
}
public void setLocation(LocationBody location) {
this.location = location;
}
}
|
package de.braintags.netrelay.controller.impl.persistence;
import java.util.Arrays;
import de.braintags.io.vertx.pojomapper.dataaccess.query.IQuery;
import de.braintags.io.vertx.pojomapper.dataaccess.query.IQueryResult;
import de.braintags.io.vertx.pojomapper.exception.NoSuchRecordException;
import de.braintags.io.vertx.pojomapper.mapping.IMapper;
import de.braintags.netrelay.controller.impl.AbstractCaptureController.CaptureMap;
import io.vertx.core.AsyncResult;
import io.vertx.core.Future;
import io.vertx.core.Handler;
import io.vertx.ext.web.RoutingContext;
/**
*
*
* @author Michael Remme
*
*/
public class DisplayAction extends AbstractAction {
public DisplayAction(PersistenceController persitenceController) {
super(persitenceController);
}
/*
* (non-Javadoc)
*
* @see de.braintags.netrelay.controller.impl.persistence.AbstractAction#handle(io.vertx.ext.web.RoutingContext,
* de.braintags.netrelay.controller.impl.AbstractCaptureController.CaptureMap)
*/
@Override
void handle(String entityName, RoutingContext context, CaptureMap map, Handler<AsyncResult<Void>> handler) {
IMapper mapper = getMapper(entityName);
String id = map.get(PersistenceController.ID_CAPTURE_KEY);
if (id == null) {
handleList(entityName, context, map, mapper, id, handler);
} else {
handleSingleRecord(entityName, context, mapper, id, handler);
}
}
protected void handleList(String entityName, RoutingContext context, CaptureMap map, IMapper mapper, String id,
Handler<AsyncResult<Void>> handler) {
IQuery<?> query = getPersistenceController().getNetRelay().getDatastore().createQuery(mapper.getMapperClass());
try {
if (map.containsKey(PersistenceController.SELECTION_SIZE_CAPTURE_KEY)) {
query.setLimit(Integer.parseInt(map.get(PersistenceController.SELECTION_SIZE_CAPTURE_KEY)));
}
if (map.containsKey(PersistenceController.SELECTION_START_CAPTURE_KEY)) {
query.setStart(Integer.parseInt(map.get(PersistenceController.SELECTION_START_CAPTURE_KEY)));
}
if (map.containsKey(PersistenceController.ORDERBY_CAPTURE_KEY)) {
query.addSort(map.get(PersistenceController.ORDERBY_CAPTURE_KEY));
}
query.execute(result -> {
if (result.failed()) {
handler.handle(Future.failedFuture(result.cause()));
} else {
IQueryResult<?> qr = result.result();
qr.toArray(arr -> {
if (arr.failed()) {
handler.handle(Future.failedFuture(arr.cause()));
} else {
addToContext(context, entityName, Arrays.asList(arr.result()));
handler.handle(Future.succeededFuture());
}
});
}
});
} catch (Exception e) {
handler.handle(Future.failedFuture(e));
}
}
protected void handleSingleRecord(String entityName, RoutingContext context, IMapper mapper, String id,
Handler<AsyncResult<Void>> handler) {
IQuery<?> query = getPersistenceController().getNetRelay().getDatastore().createQuery(mapper.getMapperClass());
query.field(mapper.getIdField().getName()).is(id);
query.execute(result -> {
if (result.failed()) {
handler.handle(Future.failedFuture(result.cause()));
} else {
IQueryResult<?> qr = result.result();
if (qr.isEmpty()) {
handler.handle(Future.failedFuture(new NoSuchRecordException(String.format(ERRORMESSAGE_RECNOTFOUND, id))));
} else {
qr.iterator().next(ir -> {
if (ir.failed()) {
handler.handle(Future.failedFuture(ir.cause()));
} else {
addToContext(context, entityName, ir.result());
handler.handle(Future.succeededFuture());
}
});
}
}
});
}
}
|
package de.craften.plugins.rpgplus.scripting.api.entities;
import de.craften.plugins.rpgplus.RpgPlus;
import de.craften.plugins.rpgplus.components.entitymanager.ManagedVillager;
import de.craften.plugins.rpgplus.components.entitymanager.RpgPlusEntity;
import de.craften.plugins.rpgplus.scripting.api.entities.events.EntityEventManager;
import de.craften.plugins.rpgplus.scripting.util.ScriptUtil;
import de.craften.plugins.rpgplus.scripting.util.luaify.LuaFunction;
import de.craften.plugins.rpgplus.scripting.util.luaify.Luaify;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Villager;
import org.luaj.vm2.LuaTable;
import org.luaj.vm2.LuaValue;
/**
* Lua API for spawning entities.
*/
public class EntitySpawner {
private final EntityEventManager entityEventManager;
public EntitySpawner(EntityEventManager entityEventManager) {
this.entityEventManager = entityEventManager;
}
public void installOn(LuaTable object) {
Luaify.convert(this, object);
}
@LuaFunction("spawn")
public EntityWrapper spawnEntity(LuaValue entityType, LuaValue optionsArg) {
final EntityType type = EntityType.valueOf(entityType.checkjstring().toUpperCase());
LuaTable options = optionsArg.checktable();
RpgPlusEntity entity;
if (type == EntityType.VILLAGER) {
entity = new ManagedVillager(ScriptUtil.getLocation(optionsArg.checktable()));
} else {
entity = new RpgPlusEntity(ScriptUtil.getLocation(optionsArg.checktable())) {
@Override
protected Entity spawnEntity(Location location) {
return location.getWorld().spawn(location, type.getEntityClass());
}
};
}
entity.setName(ChatColor.translateAlternateColorCodes('&', options.get("name").optjstring("")));
entity.setSecondName(ChatColor.translateAlternateColorCodes('&', options.get("secondName").optjstring("")));
entity.setTakingDamage(!options.get("invulnerable").optboolean(false));
entity.setNameVisible(options.get("nameVisible").optboolean(true));
switch (options.get("movementType").optjstring("local")) {
case "normal":
entity.setFrozen(false);
break;
case "frozen":
case "local": //TODO entity should move the head when the movementType is set to local
entity.setFrozen(true);
break;
}
if (entity instanceof ManagedVillager) {
if (!options.get("profession").isnil()) {
((ManagedVillager) entity).setProfession(Villager.Profession.valueOf(options.get("profession").checkjstring().toUpperCase()));
}
}
RpgPlus.getPlugin(RpgPlus.class).getEntityManager().addEntity(entity);
entity.spawn();
return new EntityWrapper(entity, entityEventManager);
}
}
|
package edu.uwi.mona.mobileourvle.app.Activities;
import org.sourceforge.ah.android.utilities.Dialog.DialogManager;
import org.sourceforge.ah.android.utilities.Widgets.Activities.ActivityBase;
import org.sourceforge.ah.android.utilities.Widgets.Fragments.FragmentResponseListerner;
import org.sourceforge.ah.android.utilities.Widgets.Fragments.FragmentResponseManager;
import org.sourceforge.ah.android.utilities.Widgets.Listeners.SimpleViewPagerTabListener;
import android.app.AlertDialog;
import android.app.DownloadManager;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.ViewGroup;
import android.widget.Toast;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import java.io.File;
import edu.uwi.mona.mobileourvle.app.Classes.DataLayer.Moodle.Modules.Forum.DiscussionParent;
import edu.uwi.mona.mobileourvle.app.Classes.DataLayer.Moodle.Modules.Forum.ForumDiscussion;
import edu.uwi.mona.mobileourvle.app.Classes.ParcableWrappers.CourseForumParcel;
import edu.uwi.mona.mobileourvle.app.Classes.ParcableWrappers.DiscussionParentParcel;
import edu.uwi.mona.mobileourvle.app.Classes.ParcableWrappers.ForumDiscussionParcel;
import edu.uwi.mona.mobileourvle.app.Classes.TransportLayer.RemoteAPIRequests.RemoteAPIRequest;
import edu.uwi.mona.mobileourvle.app.Fragments.Forum.ForumDiscussionListFragment;
import edu.uwi.mona.mobileourvle.app.R;
import edu.uwi.mona.mobileourvle.app.Classes.SharedConstants.ParcelKeys;
import edu.uwi.mona.mobileourvle.app.Classes.DataLayer.Authentication.Session.UserSession;
import edu.uwi.mona.mobileourvle.app.Classes.DataLayer.Moodle.Courses.MoodleCourse;
import edu.uwi.mona.mobileourvle.app.Classes.DataLayer.Moodle.Modules.CourseModule;
import edu.uwi.mona.mobileourvle.app.Classes.DataLayer.Moodle.Users.MoodleUser;
import edu.uwi.mona.mobileourvle.app.Classes.ParcableWrappers.CourseModuleParcel;
import edu.uwi.mona.mobileourvle.app.Classes.ParcableWrappers.MoodleCourseParcel;
import edu.uwi.mona.mobileourvle.app.Classes.ParcableWrappers.MoodleUserParcel;
import edu.uwi.mona.mobileourvle.app.Classes.ParcableWrappers.UserSessionParcel;
import edu.uwi.mona.mobileourvle.app.Fragments.Course.CourseContentsFragment;
import edu.uwi.mona.mobileourvle.app.Fragments.Course.CourseOverviewFragment;
import edu.uwi.mona.mobileourvle.app.Fragments.Course.CourseParticipantsFragment;
import edu.uwi.mona.mobileourvle.app.Fragments.Course.Companion.CoursePhotosFragment;
import edu.uwi.mona.mobileourvle.app.Fragments.Course.Companion.CourseVideoesFragment;
import edu.uwi.mona.mobileourvle.app.Fragments.Course.Companion.CourseClasses.CourseClassTimesFragment;
import edu.uwi.mona.mobileourvle.app.Fragments.Course.Companion.Notes.CourseNotesFragment;
import edu.uwi.mona.mobileourvle.app.Fragments.Shared.UnderDevelopementFragment;
/**
* @author Aston Hamilton
*/
public class CourseContentsActivity extends ActivityBase
implements CourseContentsFragment.Listener, CourseParticipantsFragment.Listener {
private UserSession mUserSession;
private MoodleCourse mCourse;
private ViewPager mPager;
private CourseContentsPagerAdapter mPagerAdapter;
private CourseClassTimesFragment mCourseClassTimesProxiedFragment;
private FragmentResponseListerner mOnDiscussionSeclectedReceiver;
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_course_main);
final Bundle extras = getIntent().getExtras();
mUserSession = ((UserSessionParcel) extras.get(ParcelKeys.USER_SESSION)).getWrappedObejct();
mCourse = ((MoodleCourseParcel) extras.get(ParcelKeys.MOODLE_COURSE)).getWrappedObejct();
setTitle(mCourse.getName());
setupViewPager();
addTabNavigation();
}
@Override
protected void onResume() {
if (mOnDiscussionSeclectedReceiver == null)
mOnDiscussionSeclectedReceiver = new FragmentResponseListerner() {
@Override
public void onResponseReceived(final Context context, final Bundle data) {
final ForumDiscussion discussion = ((ForumDiscussionParcel) data
.getParcelable(ForumDiscussionListFragment.ResponseArgs.Discussion))
.getWrappedObejct();
final Intent intent = new Intent(CourseContentsActivity.this,
ForumDiscussionPagerActivity.class);
intent.putExtra(ParcelKeys.USER_SESSION,
new UserSessionParcel(mUserSession));
intent.putExtra(ParcelKeys.FORUM_DISCUSSION_ID,
discussion.getId());
intent.putExtra(ParcelKeys.PARENT,
new CourseForumParcel(mUserSession.getContext()
.getSiteInfo()
.getNewsForum())
);
intent.putExtra(ParcelKeys.PARENT,
new DiscussionParentParcel(
new DiscussionParent(
mUserSession.getContext()
.getSiteInfo()
.getNewsForum()
)
)
);
intent.putExtra(ParcelKeys.FORUM_DISCUSSION_ID,
discussion.getId());
startActivity(intent);
}
};
FragmentResponseManager.registerReceiver(getApplicationContext(),
ForumDiscussionListFragment.Responses.onDiscussionSelected,
mOnDiscussionSeclectedReceiver);
super.onResume();
}
@Override
protected void onPause() {
if (mOnDiscussionSeclectedReceiver != null)
FragmentResponseManager.unregisterReceiver(getApplicationContext(),
mOnDiscussionSeclectedReceiver);
super.onPause();
}
private void setupViewPager() {
mPager = (ViewPager) findViewById(R.id.pager);
mPagerAdapter = new CourseContentsPagerAdapter(getSupportFragmentManager());
mPager.setAdapter(mPagerAdapter);
mPager.setOnPageChangeListener(new OnPageChangeListener() {
@Override
public void onPageScrollStateChanged(final int arg0) {
}
@Override
public void onPageScrolled(final int arg0, final float arg1, final int arg2) {
}
@Override
public void onPageSelected(final int position) {
getActionBar().getTabAt(position).select();
}
});
}
private void addTabNavigation() {
// setup action bar for tabs
final ActionBar actionBar = getActionBar();
// actionBar.setDisplayShowTitleEnabled(false);
Tab tab;
/*
tab = actionBar.newTab().setText("Events").setIcon(R.drawable.event_icon).setTabListener(
new SimpleViewPagerTabListener(mPager));
actionBar.addTab(tab);
*/
tab = actionBar.newTab().setText("Classes").setIcon(R.drawable.ic_time).setTabListener(
new SimpleViewPagerTabListener(mPager));
actionBar.addTab(tab);
tab = actionBar.newTab().setText("Users").setIcon(R.drawable.ic_group).setTabListener(
new SimpleViewPagerTabListener(mPager));
actionBar.addTab(tab);
tab = actionBar.newTab().setText("Resource").setIcon(R.drawable.collection_icon)
.setTabListener(new SimpleViewPagerTabListener(mPager));
actionBar.addTab(tab);
tab = actionBar.newTab().setText("Overview").setIcon(R.drawable.overview_icon)
.setTabListener(new SimpleViewPagerTabListener(mPager));
actionBar.addTab(tab, true);
tab = actionBar.newTab().setText("Notes").setIcon(R.drawable.notes_icon).setTabListener(
new SimpleViewPagerTabListener(mPager));
actionBar.addTab(tab);
/*
tab = actionBar.newTab().setText("Pictures").setIcon(R.drawable.picture_icon)
.setTabListener(new SimpleViewPagerTabListener(mPager));
actionBar.addTab(tab);
tab = actionBar.newTab().setText("Video").setIcon(R.drawable.video_icon).setTabListener(
new SimpleViewPagerTabListener(mPager));
actionBar.addTab(tab);
*/
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
}
@Override
public void onCourseModuleSelected(final CourseModule module) {
if ("forum".equals(module.getName())) {
final Intent intent = new Intent(CourseContentsActivity.this,
ForumDiscussionListActivity.class);
intent.putExtra(ParcelKeys.USER_SESSION, new UserSessionParcel(mUserSession));
intent.putExtra(ParcelKeys.COURSE_FORUM_MODULE, new CourseModuleParcel(module));
startActivity(intent);
} else if ("resource".equalsIgnoreCase(module.getName())) {
String folderLocation = "/OurVLE/courses/"+mCourse.getName().trim()+"-"+mCourse.getId()+"/files/"; // sub-folder definition
File location = new File(Environment.getExternalStorageDirectory(), folderLocation);
if (!location.exists()) {
location.mkdirs(); // makes the subfolder
}
String fileLocation = location+"/"+module.getFileName();
File courseFile = new File(fileLocation);
if(!courseFile.exists()) // checks if the file is not already present
{
Toast.makeText(getApplicationContext(), "Downloading File: " + module.getLabel(),
Toast.LENGTH_LONG).show();
final String url = module.getFileUrl() + "&token=" + mUserSession.getSessionKey();
final DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setDescription("Course file download");
request.setTitle(module.getLabel());
// in order for this if to run, you must use the android 3.2 to compile your app
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
request.allowScanningByMediaScanner();
request.setNotificationVisibility(
DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}
request.setDestinationInExternalPublicDir(folderLocation,
module.getFileName());
// get download service and enqueue file
final DownloadManager manager = (DownloadManager) getSystemService(
Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
}
else // open the file that is already present
{
Uri path = Uri.fromFile(courseFile);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(path);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try
{
startActivity(intent);
}
catch (ActivityNotFoundException e)
{
Toast.makeText(getApplicationContext(), "no application available to view this file",
Toast.LENGTH_LONG).show();
}
}
} else if (module.getFileUrl() != null) {
new AlertDialog.Builder(this)
.setTitle("Not Supported")
.setMessage(
"Access to this type of content is not yet supported by OurVLE Mobile. " +
"\n\nDo you want to open it in a browser?")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
final String url = module.getFileUrl();
final Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(
url));
startActivity(browserIntent);
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
} else //noinspection StatementWithEmptyBody
if ("label".equalsIgnoreCase(module.getName())) {
// do nothing
} else {
Toast.makeText(getApplicationContext(),
"This resource is not yet supported by OurVLE Mobile", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onParticipantSelected(final MoodleUser user) {
final Intent i = new Intent(CourseContentsActivity.this, ViewUserProfileActivity.class);
i.putExtra(ParcelKeys.USER_SESSION, new UserSessionParcel(mUserSession));
i.putExtra(ParcelKeys.MOODLE_USER, new MoodleUserParcel(user));
startActivity(i);
}
private class CourseContentsPagerAdapter extends FragmentStatePagerAdapter {
private Object mPrimaryItem;
public CourseContentsPagerAdapter(final FragmentManager fm) {
super(fm);
}
public Object getPrimaryItem() {
return mPrimaryItem;
}
@Override
public void setPrimaryItem(final ViewGroup container, final int position,
final Object object) {
mPrimaryItem = object;
super.setPrimaryItem(container, position, object);
}
@Override
public int getCount() {
return 5;
}
@Override
public Fragment getItem(final int position) {
Fragment f;
switch (position) {
case 0:
mCourseClassTimesProxiedFragment = CourseClassTimesFragment.newInstance(
mCourse);
f = mCourseClassTimesProxiedFragment;
break;
case 1:
f = CourseParticipantsFragment.newInstance(mUserSession, mCourse);
break;
case 2:
f = CourseContentsFragment.newInstance(mUserSession, mCourse);
break;
case 3:
f = CourseOverviewFragment.newInstance(mUserSession, mCourse);
break;
case 4:
f = CourseNotesFragment.newInstance(mCourse);
break;
case 6:
f = CoursePhotosFragment.newInstance(mCourse);
break;
case 7:
f = CourseVideoesFragment.newInstance(mCourse);
break;
default:
f = UnderDevelopementFragment.newInstance();
}
return f;
}
}
}
|
package mcjty.deepresonance.blocks.crystals;
import mcjty.deepresonance.blocks.ModBlocks;
import mcjty.entity.GenericTileEntity;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;
import java.util.Random;
public class ResonatingCrystalTileEntity extends GenericTileEntity {
// The total maximum RF you can get out of a crystal with the following characteristics:
// * S: Strength (0-100%)
// * P: Purity (0-100%)
// * E: Efficiency (0-100%)
// Is equal to:
// * MaxRF = FullMax * (S/100) * ((P+30)/130)
// The RF/tick you can get out of a crystal with the above characteristics is:
// * RFTick = FullRFTick * (E/100.1) * ((P+2)/102) + 1 (the divide by 100.1 is to make sure we don't go above 20000)
private float strength = 1.0f;
private float power = 1.0f; // Default 1% power
private float efficiency = 1.0f; // Default 1%
private float purity = 1.0f; // Default 1% purity
private float powerPerTick = -1; // Calculated value that contains the power/tick that is drained for this crystal.
private int rfPerTick = -1; // Calculated value that contains the RF/tick for this crystal.
private boolean glowing = false;
@Override
public boolean canUpdate() {
return false;
}
public float getStrength() {
return strength;
}
public float getPower() {
return power;
}
public float getEfficiency() {
return efficiency;
}
public float getPurity() {
return purity;
}
public boolean isGlowing() {
return glowing;
}
public void setStrength(float strength) {
this.strength = strength;
markDirty();
worldObj.markBlockForUpdate(xCoord, yCoord, zCoord);
}
public void setPower(float power) {
this.power = power;
markDirty();
// Don't do block update. We query power on demand from the tooltip of the crystal.
// worldObj.markBlockForUpdate(xCoord, yCoord, zCoord);
}
public void setEfficiency(float efficiency) {
this.efficiency = efficiency;
markDirty();
worldObj.markBlockForUpdate(xCoord, yCoord, zCoord);
}
public void setPurity(float purity) {
this.purity = purity;
markDirty();
worldObj.markBlockForUpdate(xCoord, yCoord, zCoord);
}
public void setGlowing(boolean glowing) {
if (this.glowing == glowing) {
return;
}
this.glowing = glowing;
markDirty();
worldObj.markBlockForUpdate(xCoord, yCoord, zCoord);
}
public float getPowerPerTick() {
if (powerPerTick < 0) {
float totalRF = ResonatingCrystalConfiguration.maximumRF * strength / 100.0f * (purity + 30.0f) / 130.0f;
float numticks = totalRF / getRfPerTick();
powerPerTick = 100.0f / numticks;
}
return powerPerTick;
}
public int getRfPerTick() {
if (rfPerTick == -1) {
rfPerTick = (int) (ResonatingCrystalConfiguration.maximumRFtick * efficiency / 100.1f * (purity + 2.0f) / 102.0f + 1);
}
return rfPerTick;
}
@Override
public void readFromNBT(NBTTagCompound tagCompound) {
super.readFromNBT(tagCompound);
}
@Override
public void readRestorableFromNBT(NBTTagCompound tagCompound) {
super.readRestorableFromNBT(tagCompound);
strength = tagCompound.getFloat("strength");
power = tagCompound.getFloat("power");
efficiency = tagCompound.getFloat("efficiency");
purity = tagCompound.getFloat("purity");
glowing = tagCompound.getBoolean("glowing");
byte version = tagCompound.getByte("version");
if (version < (byte) 2) {
// We have to convert the power.
power *= 20.0f;
}
}
@Override
public void writeToNBT(NBTTagCompound tagCompound) {
super.writeToNBT(tagCompound);
}
@Override
public void writeRestorableToNBT(NBTTagCompound tagCompound) {
super.writeRestorableToNBT(tagCompound);
tagCompound.setFloat("strength", strength);
tagCompound.setFloat("power", power);
tagCompound.setFloat("efficiency", efficiency);
tagCompound.setFloat("purity", purity);
tagCompound.setBoolean("glowing", glowing);
tagCompound.setByte("version", (byte) 2); // Legacy support to support older crystals.
}
// Special == 0, normal
// Special == 1, average random
// Special == 2, best random
// Special == 3, best non-overcharged
public static void spawnRandomCrystal(World world, Random random, int x, int y, int z, int special) {
world.setBlock(x, y, z, ModBlocks.resonatingCrystalBlock, 0, 3);
TileEntity te = world.getTileEntity(x, y, z);
if (te instanceof ResonatingCrystalTileEntity) {
ResonatingCrystalTileEntity resonatingCrystalTileEntity = (ResonatingCrystalTileEntity) te;
if (special == 3) {
resonatingCrystalTileEntity.setStrength(100);
resonatingCrystalTileEntity.setPower(100);
resonatingCrystalTileEntity.setEfficiency(100);
resonatingCrystalTileEntity.setPurity(100);
} else {
resonatingCrystalTileEntity.setStrength(getRandomSpecial(random, special) * 3.0f + 0.01f);
resonatingCrystalTileEntity.setPower(getRandomSpecial(random, special) * 60.0f + 0.2f);
resonatingCrystalTileEntity.setEfficiency(getRandomSpecial(random, special) * 3.0f + 0.1f);
resonatingCrystalTileEntity.setPurity(getRandomSpecial(random, special) * 10.0f + 5.0f);
}
}
}
private static float getRandomSpecial(Random random, int special) {
return special == 0 ? random.nextFloat() :
special == 1 ? .5f : 1.0f;
}
}
|
package net.blay09.mods.cookingforblockheads.client.render;
import net.blay09.mods.cookingforblockheads.blaycommon.RenderUtils;
import net.blay09.mods.cookingforblockheads.block.ModBlocks;
import net.blay09.mods.cookingforblockheads.tile.TileOven;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.*;
import net.minecraft.client.renderer.block.model.IBakedModel;
import net.minecraft.client.renderer.texture.TextureMap;
import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer;
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumBlockRenderType;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import org.lwjgl.opengl.GL11;
public class OvenRenderer extends TileEntitySpecialRenderer<TileOven> {
public static IBakedModel modelDoor;
public static IBakedModel modelDoorActive;
@Override
public void renderTileEntityAt(TileOven tileEntity, double x, double y, double z, float partialTicks, int destroyStage) {
if(!tileEntity.hasWorld()) {
return;
}
World world = tileEntity.getWorld();
BlockPos pos = tileEntity.getPos();
BlockRendererDispatcher dispatcher = Minecraft.getMinecraft().getBlockRendererDispatcher();
RenderItem itemRenderer = Minecraft.getMinecraft().getRenderItem();
Tessellator tessellator = Tessellator.getInstance();
VertexBuffer renderer = tessellator.getBuffer();
EnumFacing facing = tileEntity.getFacing();
if(facing == null) {
return;
}
float blockAngle = RenderUtils.getFacingAngle(facing);
float doorAngle = tileEntity.getDoorAnimator().getRenderAngle(partialTicks);
// Render the oven door
GlStateManager.pushMatrix();
GlStateManager.translate(x + 0.5f, y, z + 0.5f);
GlStateManager.rotate(blockAngle, 0f, 1f, 0f);
GlStateManager.translate(-0.5f, 0f, -0.5f);
GlStateManager.rotate(-(float) Math.toDegrees(doorAngle), 1f, 0f, 0f);
bindTexture(TextureMap.LOCATION_BLOCKS_TEXTURE);
RenderHelper.enableStandardItemLighting();
itemRenderer.renderModel(doorAngle < 0.3f && tileEntity.isBurning() ? modelDoorActive : modelDoor, 0xFFFFFFFF);
GlStateManager.popMatrix();
// Render the oven door (new way) -- DOESN'T WORK RIGHT NOW FOR SOME REASON
// ALSO NEEDS A MODEL FOR EACH DIRECTION (see Kitchen Counter) OTHERWISE LIGHTING WILL BREAK
// GlStateManager.pushMatrix();
// renderer.begin(GL11.GL_QUADS, DefaultVertexFormats.BLOCK);
// GlStateManager.translate(0.5f, 0, 0.5f);
// GlStateManager.rotate(blockAngle, 0f, 1f, 0f);
// GlStateManager.translate(-0.5f, 0f, -0.5f);
// GlStateManager.rotate(-(float) Math.toDegrees(doorAngle), 1f, 0f, 0f);
// bindTexture(TextureMap.LOCATION_BLOCKS_TEXTURE);
// IBakedModel model = doorAngle < 0.3f && tileEntity.isBurning() ? modelDoorActive : modelDoor;
// dispatcher.getBlockModelRenderer().renderModel(world, model, ModBlocks.oven.getDefaultState(), pos, renderer, false);
// tessellator.draw();
// GlStateManager.popMatrix();
// Render the oven tools
GlStateManager.pushMatrix();
GlStateManager.color(1f, 1f, 1f, 1f);
GlStateManager.translate(x + 0.5, y + 1.05, z + 0.5);
GlStateManager.rotate(blockAngle, 0f, 1f, 0f);
GlStateManager.scale(0.4f, 0.4f, 0.4f);
ItemStack itemStack = tileEntity.getToolItem(0);
if (!itemStack.isEmpty()) {
RenderUtils.renderItem(itemRenderer, itemStack, -0.55f, 0f, 0.5f, 45f, 1f, 0f, 0f);
}
itemStack = tileEntity.getToolItem(1);
if (!itemStack.isEmpty()) {
RenderUtils.renderItem(itemRenderer, itemStack, 0.55f, 0f, 0.5f, 45f, 1f, 0f, 0f);
}
itemStack = tileEntity.getToolItem(2);
if (!itemStack.isEmpty()) {
RenderUtils.renderItem(itemRenderer, itemStack, -0.55f, 0f, -0.5f, 45f, 1f, 0f, 0f);
}
itemStack = tileEntity.getToolItem(3);
if (!itemStack.isEmpty()) {
RenderUtils.renderItem(itemRenderer, itemStack, 0.55f, 0f, -0.5f, 45f, 1f, 0f, 0f);
}
GlStateManager.popMatrix();
// Render the oven content when the door is open
if (doorAngle > 0f) {
GlStateManager.pushMatrix();
GlStateManager.translate(x + 0.5, y + 0.4, z + 0.5);
GlStateManager.rotate(blockAngle, 0f, 1f, 0f);
GlStateManager.scale(0.3f, 0.3f, 0.3f);
float offsetX = 0.825f;
float offsetZ = 0.8f;
for (int i = 0; i < 9; i++) {
itemStack = tileEntity.getItemHandler().getStackInSlot(7 + i);
if (!itemStack.isEmpty()) {
RenderUtils.renderItem(itemRenderer, itemStack, offsetX, 0f, offsetZ, 90f, 1f, 0f, 0f);
}
offsetX -= 0.8f;
if (offsetX < -0.8f) {
offsetX = 0.825f;
offsetZ -= 0.8f;
}
}
GlStateManager.popMatrix();
}
}
}
|
package net.earthcomputer.easyeditors.gui.command.slot;
import java.util.List;
import org.lwjgl.opengl.GL11;
import net.earthcomputer.easyeditors.gui.GuiColorPicker;
import net.earthcomputer.easyeditors.gui.IColorPickerCallback;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.Gui;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.WorldRenderer;
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
import net.minecraft.client.resources.I18n;
import net.minecraftforge.fml.client.config.HoverChecker;
/**
* A command slot which can be used to pick a color. This command slot does not
* read from and write from arguments, so if you require this functionality, you
* must create a subclass
*
* @author Earthcomputer
*
*/
public class CommandSlotColor extends GuiCommandSlotImpl implements IColorPickerCallback {
private int color;
private boolean allowAlpha;
private int x;
private int y;
private HoverChecker hoverChecker;
public CommandSlotColor() {
this(true);
}
public CommandSlotColor(boolean allowAlpha) {
super(50, 20);
this.color = allowAlpha ? 0xffffffff : 0xffffff;
this.allowAlpha = allowAlpha;
}
@Override
public int readFromArgs(String[] args, int index) {
return 0;
}
@Override
public void addArgs(List<String> args) {
}
@Override
public void draw(int x, int y, int mouseX, int mouseY, float partialTicks) {
this.x = x;
this.y = y;
int color = getColor();
if ((color & 0xff000000) != 0xff000000) {
GlStateManager.color(1, 1, 1, 1);
Minecraft.getMinecraft().getTextureManager().bindTexture(GuiColorPicker.transparentBackground);
Tessellator tessellator = Tessellator.getInstance();
WorldRenderer worldRenderer = tessellator.getWorldRenderer();
worldRenderer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX);
worldRenderer.pos(x, y + getHeight(), 0).tex(0, (float) getHeight() / 16).endVertex();
worldRenderer.pos(x + getWidth(), y + getHeight(), 0).tex((float) getWidth() / 16, (float) getHeight() / 16)
.endVertex();
worldRenderer.pos(x + getWidth(), y, 0).tex((float) getWidth() / 16, 0).endVertex();
worldRenderer.pos(x, y, 0).tex(0, 0).endVertex();
tessellator.draw();
}
Gui.drawRect(x, y, x + getWidth(), y + getHeight(), color);
drawHorizontalLine(x, x + getWidth(), y, 0xff000000);
drawHorizontalLine(x, x + getWidth(), y + getHeight(), 0xff000000);
drawVerticalLine(x, y, y + getHeight(), 0xff000000);
drawVerticalLine(x + getWidth(), y, y + getHeight(), 0xff000000);
if (hoverChecker == null)
hoverChecker = new HoverChecker(y, y + getHeight(), x, x + getWidth(), 1000);
else
hoverChecker.updateBounds(y, y + getHeight(), x, x + getWidth());
if (hoverChecker.checkHover(mouseX, mouseY))
drawTooltip(mouseX, mouseY, I18n.format("gui.easyeditorsconfig.colortooltip"));
}
@Override
public boolean onMouseClicked(int mouseX, int mouseY, int mouseButton) {
if (mouseButton == 0) {
if (mouseX >= x && mouseX < x + getWidth() && mouseY >= y && mouseY < y + getHeight())
Minecraft.getMinecraft()
.displayGuiScreen(new GuiColorPicker(Minecraft.getMinecraft().currentScreen, this, allowAlpha));
}
return false;
}
@Override
public int getColor() {
return allowAlpha ? color : color | 0xff000000;
}
@Override
public void setColor(int color) {
this.color = allowAlpha ? color : color & 0x00ffffff;
}
}
|
package net.sf.mzmine.project.parameterssetup;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.StringTokenizer;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileNameExtensionFilter;
import net.sf.mzmine.desktop.Desktop;
import net.sf.mzmine.main.MZmineCore;
import net.sf.mzmine.parameters.UserParameter;
import net.sf.mzmine.parameters.parametertypes.ComboParameter;
import net.sf.mzmine.parameters.parametertypes.DoubleParameter;
import net.sf.mzmine.parameters.parametertypes.StringParameter;
/**
* This class imports project parameters and their values from a CSV file to the
* main project parameter setup dialog.
*
*
* Description of input file format:
*
* First column of the comma-separated file must contain file names matching to
* names of raw data files opened in MZmine. Each other column corresponds to
* one project parameter.
*
* First row in the file must contain column headers. Header for the first
* column (filename) is ignored but must exists. Rest of the column headers are
* used as names for project parameters. All column names in the file must be be
* unique. If main dialog already contains a parameter with the same name, a
* warning is shown to the user before overwriting previous parameter.
*
*
* Rules for deciding type of parameter:
*
* 1. If all values in a column (except column header on the first row) are
* numeric, then the parameter type is set to Double.
*
* 2. If there are at least some duplicate strings among values for a parameter,
* then the parameter type is String and possible parameter values are all
* unique strings.
*
* 3. Otherwise it is a free text parameter of type String.
*
*
*/
public class ProjectParametersImporter {
private Logger logger = Logger.getLogger(this.getClass().getName());
private ProjectParametersSetupDialog mainDialog;
private Desktop desktop;
public ProjectParametersImporter(ProjectParametersSetupDialog mainDialog) {
this.mainDialog = mainDialog;
desktop = MZmineCore.getDesktop();
}
public boolean importParameters() {
// Let user choose a CSV file for importing
File parameterFile = chooseFile();
if (parameterFile == null) {
logger.info("Parameter importing cancelled.");
return false;
}
// Read and interpret parameters
UserParameter<?, ?>[] parameters = processParameters(parameterFile);
if (parameters == null)
return false;
// TODO: Show a dialog for selecting which parameters to import and edit
// their types
// Read values of parameters and store them in the project
processParameterValues(parameterFile, parameters);
return true;
}
private File chooseFile() {
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter(
"TXT & CSV files", "txt", "csv");
chooser.setDialogTitle("Please select a file containing project parameter values for files.");
chooser.setFileFilter(filter);
int returnVal = chooser.showOpenDialog(desktop.getMainWindow());
if (returnVal == JFileChooser.CANCEL_OPTION) {
return null;
}
return chooser.getSelectedFile();
}
private UserParameter<?, ?>[] processParameters(File parameterFile) {
ArrayList<UserParameter<?, ?>> parameters = new ArrayList<UserParameter<?, ?>>();
// Open reader
BufferedReader parameterFileReader;
try {
parameterFileReader = new BufferedReader(new FileReader(
parameterFile));
// Read column headers which are used as parameter names
String firstRow = parameterFileReader.readLine();
StringTokenizer st = new StringTokenizer(firstRow, ",");
st.nextToken(); // Assume first column contains file names
ArrayList<String> parameterNames = new ArrayList<String>();
Hashtable<String, ArrayList<String>> parameterValues = new Hashtable<String, ArrayList<String>>();
while (st.hasMoreTokens()) {
String paramName = st.nextToken();
if (parameterValues.containsKey(paramName)) {
logger.severe("Did not import parameters because of a non-unique parameter name: "
+ paramName);
desktop.displayErrorMessage(MZmineCore.getDesktop()
.getMainWindow(), "Could not open file "
+ parameterFile);
parameterFileReader.close();
return null;
}
parameterNames.add(paramName);
parameterValues.put(paramName, new ArrayList<String>());
}
// Read rest of the rows which contain file name in the first column
// and parameter values in the rest of the columns
String nextRow = parameterFileReader.readLine();
int rowNumber = 2;
while (nextRow != null) {
st = new StringTokenizer(nextRow, ",");
// Skip first column (File name)
if (st.hasMoreTokens())
st.nextToken();
Iterator<String> parameterNameIterator = parameterNames
.iterator();
while (st.hasMoreTokens()) {
if (st.hasMoreTokens() ^ parameterNameIterator.hasNext()) {
logger.severe("Incorrect number of parameter values on row "
+ rowNumber);
desktop.displayErrorMessage(MZmineCore.getDesktop()
.getMainWindow(),
"Incorrect number of parameter values on row "
+ rowNumber);
parameterFileReader.close();
return null;
}
parameterValues.get(parameterNameIterator.next()).add(
st.nextToken());
}
nextRow = parameterFileReader.readLine();
rowNumber++;
}
// Decide parameter types (all numeric => Double, all unique string
// => String, at least one duplicate string => Object with possible
// values
Iterator<String> parameterNameIterator = parameterNames.iterator();
while (parameterNameIterator.hasNext()) {
String name = parameterNameIterator.next();
ArrayList<String> vals = parameterValues.get(name);
// Test for all numeric
Iterator<String> valIterator = vals.iterator();
boolean isAllNumeric = true;
while (valIterator.hasNext()) {
try {
Double.valueOf(valIterator.next());
} catch (NumberFormatException ex) {
isAllNumeric = false;
break;
}
}
if (isAllNumeric) {
parameters.add(new DoubleParameter(name, null));
continue;
}
// Test for "set of values"
ArrayList<String> uniqueValues = new ArrayList<String>();
valIterator = vals.iterator();
while (valIterator.hasNext()) {
String val = valIterator.next();
if (!uniqueValues.contains(val))
uniqueValues.add(val);
}
if (uniqueValues.size() < vals.size()) {
parameters.add(new ComboParameter<String>(name, null,
uniqueValues.toArray(new String[0])));
continue;
}
// Otherwise it is a free text parameter
parameters.add(new StringParameter(name, null));
}
// Close reader
parameterFileReader.close();
} catch (IOException ex) {
logger.severe("Could not read file " + parameterFile);
desktop.displayErrorMessage(
MZmineCore.getDesktop().getMainWindow(),
"Could not open file " + parameterFile);
return null;
}
return parameters.toArray(new UserParameter[0]);
}
private boolean processParameterValues(File parameterFile,
UserParameter<?, ?>[] parameters) {
// Warn user if main dialog already contains a parameter with same name
for (UserParameter<?, ?> parameter : parameters) {
UserParameter<?, ?> p = mainDialog
.getParameter(parameter.getName());
if (p != null) {
int res = JOptionPane.showConfirmDialog(mainDialog,
"Overwrite previous parameter(s) with same name?",
"Overwrite?", JOptionPane.OK_CANCEL_OPTION);
if (res == JOptionPane.CANCEL_OPTION)
return false;
else
break;
}
}
// Remove parameters with same name
for (UserParameter<?, ?> parameter : parameters) {
UserParameter<?, ?> p = mainDialog
.getParameter(parameter.getName());
if (p != null) {
mainDialog.removeParameter(p);
}
}
// Add new parameters to the main dialog
for (UserParameter<?, ?> parameter : parameters) {
mainDialog.addParameter(parameter);
}
// Open reader
BufferedReader parameterFileReader;
try {
parameterFileReader = new BufferedReader(new FileReader(
parameterFile));
} catch (FileNotFoundException ex) {
logger.severe("Could not open file " + parameterFile);
desktop.displayErrorMessage(
MZmineCore.getDesktop().getMainWindow(),
"Could not open file " + parameterFile);
return false;
}
try {
// Skip first row
parameterFileReader.readLine();
// Read rest of the rows which contain file name in the first column
// and parameter values in the rest of the columns
String nextRow = parameterFileReader.readLine();
while (nextRow != null) {
StringTokenizer st = new StringTokenizer(nextRow, ",");
nextRow = parameterFileReader.readLine();
if (! st.hasMoreTokens()) continue;
// Get raw data file for this row
String fileName = st.nextToken();
// Set parameter values to project
int parameterIndex = 0;
while (st.hasMoreTokens()) {
String parameterValue = st.nextToken();
UserParameter<?, ?> parameter = parameters[parameterIndex];
if (parameter instanceof DoubleParameter)
mainDialog.setParameterValue(parameter, fileName,
Double.parseDouble(parameterValue));
else
mainDialog.setParameterValue(parameter, fileName,
parameterValue);
parameterIndex++;
}
}
} catch (IOException ex) {
logger.severe("Could not read file " + parameterFile);
desktop.displayErrorMessage(
MZmineCore.getDesktop().getMainWindow(),
"Could not open file " + parameterFile);
return false;
}
// Close reader
try {
parameterFileReader.close();
} catch (IOException ex) {
logger.severe("Could not close file " + parameterFile);
desktop.displayErrorMessage(
MZmineCore.getDesktop().getMainWindow(),
"Could not close file " + parameterFile);
return false;
}
return true;
}
}
|
package org.granitepowered.granite.impl.item.inventory;
import org.apache.commons.lang3.NotImplementedException;
import org.granitepowered.granite.composite.Composite;
import org.granitepowered.granite.mappings.Mappings;
import org.granitepowered.granite.mc.MCBlock;
import org.granitepowered.granite.mc.MCItem;
import org.granitepowered.granite.mc.MCItemStack;
import org.spongepowered.api.block.BlockType;
import org.spongepowered.api.item.Enchantment;
import org.spongepowered.api.item.ItemType;
import org.spongepowered.api.item.inventory.ItemStack;
import java.util.Map;
import static org.granitepowered.granite.utils.MinecraftUtils.unwrap;
import static org.granitepowered.granite.utils.MinecraftUtils.wrap;
public class GraniteItemStack extends Composite<MCItemStack> implements ItemStack {
public GraniteItemStack(MCItemStack obj) {
super(obj);
}
public GraniteItemStack(ItemType type, int amount) {
this((MCItem) unwrap(type), amount);
}
public GraniteItemStack(ItemType type, int amount, int damage) {
this((MCItem) unwrap(type), amount, damage);
}
public GraniteItemStack(BlockType type, int amount) {
this((MCBlock) unwrap(type), amount);
}
public GraniteItemStack(BlockType type, int amount, int damage) {
this((MCBlock) unwrap(type), amount, damage);
}
public GraniteItemStack(MCItem item, int amount) {
this(item, amount, 0);
}
public GraniteItemStack(MCItem item, int amount, int damage) {
super(Mappings.getClass("ItemStack"), new Class[]{Mappings.getClass("Item"), int.class, int.class}, item, amount, damage);
}
public GraniteItemStack(MCBlock block, int amount) {
this(block, amount, 0);
}
public GraniteItemStack(MCBlock block, int amount, int damage) {
super(Mappings.getClass("ItemStack"), new Class[]{Mappings.getClass("Block"), int.class, int.class}, block, amount, damage);
}
@Override
public ItemType getItem() {
return (ItemType) wrap(getMCItem());
}
@Override
public short getDamage() {
return (short) obj.fieldGet$itemDamage();
}
@Override
public void setDamage(short damage) {
obj.fieldSet$itemDamage(damage);
}
@Override
public int getQuantity() {
return obj.fieldGet$stackSize();
}
@Override
public void setQuantity(int quantity) throws IllegalArgumentException {
if (quantity > getMaxStackQuantity()) quantity = getMaxStackQuantity();
obj.fieldSet$stackSize(quantity);
}
@Override
public int getMaxStackQuantity() {
return getMCItem().fieldGet$maxStackSize();
}
@Override
public void setMaxStackQuantity(int quantity) {
// TODO: Decision lies with Sponge on this as is impossible to change the max size of a stack
throw new UnsupportedOperationException("Decision lies with Sponge on this as is impossible to change the max size of a stack");
}
@Override
public Map<Enchantment, Integer> getEnchantments() {
// TODO: Enchantment API
throw new NotImplementedException("");
}
@Override
public boolean isEnchanted() {
// TODO: Enchantment API
throw new NotImplementedException("");
}
@Override
public void setEnchantment(Enchantment enchant, int level) {
// TODO: Enchantment API
throw new NotImplementedException("");
}
@Override
public void removeEnchantment(Enchantment enchant) {
// TODO: Enchantment API
throw new NotImplementedException("");
}
@Override
public int getEnchantment(Enchantment enchant) {
// TODO: Enchantment API
throw new NotImplementedException("");
}
public MCItem getMCItem() {
return obj.fieldGet$item();
}
}
|
package org.jboss.netty.handler.execution;
import java.lang.reflect.Method;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.Semaphore;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelEvent;
import org.jboss.netty.channel.ChannelState;
import org.jboss.netty.channel.ChannelStateEvent;
public class MemoryAwareThreadPoolExecutor extends ThreadPoolExecutor {
private volatile Settings settings = new Settings(0, 0);
// XXX Can be changed in runtime now. Make it mutable in 3.1.
private final ObjectSizeEstimator objectSizeEstimator;
private final ConcurrentMap<Channel, AtomicInteger> channelCounters =
new ConcurrentHashMap<Channel, AtomicInteger>();
private final AtomicInteger totalCounter = new AtomicInteger();
private final Semaphore semaphore = new Semaphore(0);
/**
* Creates a new instance.
*
* @param corePoolSize the maximum number of active threads
* @param maxChannelMemorySize the maximum total size of the queued events per channel.
* Specify {@code 0} to disable.
* @param maxTotalMemorySize the maximum total size of the queued events for this pool
* Specify {@code 0} to disable.
*/
public MemoryAwareThreadPoolExecutor(
int corePoolSize, int maxChannelMemorySize, int maxTotalMemorySize) {
this(corePoolSize, maxChannelMemorySize, maxTotalMemorySize, 30, TimeUnit.SECONDS);
}
/**
* Creates a new instance.
*
* @param corePoolSize the maximum number of active threads
* @param maxChannelMemorySize the maximum total size of the queued events per channel.
* Specify {@code 0} to disable.
* @param maxTotalMemorySize the maximum total size of the queued events for this pool
* Specify {@code 0} to disable.
* @param keepAliveTime the amount of time for an inactive thread to shut itself down
* @param unit the {@link TimeUnit} of {@code keepAliveTime}
*/
public MemoryAwareThreadPoolExecutor(
int corePoolSize, int maxChannelMemorySize, int maxTotalMemorySize, long keepAliveTime, TimeUnit unit) {
this(corePoolSize, maxChannelMemorySize, maxTotalMemorySize, keepAliveTime, unit, Executors.defaultThreadFactory());
}
/**
* Creates a new instance.
*
* @param corePoolSize the maximum number of active threads
* @param maxChannelMemorySize the maximum total size of the queued events per channel.
* Specify {@code 0} to disable.
* @param maxTotalMemorySize the maximum total size of the queued events for this pool
* Specify {@code 0} to disable.
* @param keepAliveTime the amount of time for an inactive thread to shut itself down
* @param unit the {@link TimeUnit} of {@code keepAliveTime}
* @param threadFactory the {@link ThreadFactory} of this pool
*/
public MemoryAwareThreadPoolExecutor(
int corePoolSize, int maxChannelMemorySize, int maxTotalMemorySize, long keepAliveTime, TimeUnit unit, ThreadFactory threadFactory) {
this(corePoolSize, maxChannelMemorySize, maxTotalMemorySize, keepAliveTime, unit, new DefaultObjectSizeEstimator(), threadFactory);
}
/**
* Creates a new instance.
*
* @param corePoolSize the maximum number of active threads
* @param maxChannelMemorySize the maximum total size of the queued events per channel.
* Specify {@code 0} to disable.
* @param maxTotalMemorySize the maximum total size of the queued events for this pool
* Specify {@code 0} to disable.
* @param keepAliveTime the amount of time for an inactive thread to shut itself down
* @param unit the {@link TimeUnit} of {@code keepAliveTime}
* @param threadFactory the {@link ThreadFactory} of this pool
* @param objectSizeEstimator the {@link ObjectSizeEstimator} of this pool
*/
public MemoryAwareThreadPoolExecutor(
int corePoolSize, int maxChannelMemorySize, int maxTotalMemorySize, long keepAliveTime, TimeUnit unit, ObjectSizeEstimator objectSizeEstimator, ThreadFactory threadFactory) {
super(corePoolSize, corePoolSize, keepAliveTime, unit, new LinkedBlockingQueue<Runnable>(), threadFactory);
if (objectSizeEstimator == null) {
throw new NullPointerException("objectSizeEstimator");
}
this.objectSizeEstimator = objectSizeEstimator;
// Call allowCoreThreadTimeOut(true) using reflection
// because it's not supported in Java 5.
try {
Method m = getClass().getMethod("allowCoreThreadTimeOut", new Class[] { boolean.class });
m.invoke(this, Boolean.TRUE);
} catch (Exception e) {
// Java 5
}
setMaxChannelMemorySize(maxChannelMemorySize);
setMaxTotalMemorySize(maxTotalMemorySize);
}
/**
* Returns the {@link ObjectSizeEstimator} of this pool.
*/
public ObjectSizeEstimator getObjectSizeEstimator() {
return objectSizeEstimator;
}
/**
* Returns the maximum total size of the queued events per channel.
*/
public int getMaxChannelMemorySize() {
return settings.maxChannelMemorySize;
}
/**
* Sets the maximum total size of the queued events per channel.
* Specify {@code 0} to disable.
*/
public void setMaxChannelMemorySize(int maxChannelMemorySize) {
if (maxChannelMemorySize < 0) {
throw new IllegalArgumentException(
"maxChannelMemorySize: " + maxChannelMemorySize);
}
settings = new Settings(maxChannelMemorySize, settings.maxTotalMemorySize);
}
/**
* Returns the maximum total size of the queued events for this pool.
*/
public int getMaxTotalMemorySize() {
return settings.maxTotalMemorySize;
}
/**
* Sets the maximum total size of the queued events for this pool.
* Specify {@code 0} to disable.
*/
public void setMaxTotalMemorySize(int maxTotalMemorySize) {
if (maxTotalMemorySize < 0) {
throw new IllegalArgumentException(
"maxTotalMemorySize: " + maxTotalMemorySize);
}
settings = new Settings(settings.maxChannelMemorySize, maxTotalMemorySize);
}
@Override
public void execute(Runnable command) {
boolean pause = increaseCounter(command);
doExecute(command);
if (pause) {
//System.out.println("ACQUIRE");
semaphore.acquireUninterruptibly();
}
}
/**
* Put the actual execution logic here. The default implementation simply
* calls {@link #doUnorderedExecute(Runnable)}.
*/
protected void doExecute(Runnable task) {
doUnorderedExecute(task);
}
/**
* Executes the specified task without maintaining the event order.
*/
protected final void doUnorderedExecute(Runnable task) {
super.execute(task);
}
@Override
public boolean remove(Runnable task) {
boolean removed = super.remove(task);
if (removed) {
decreaseCounter(task);
}
return removed;
}
@Override
protected void beforeExecute(Thread t, Runnable r) {
super.beforeExecute(t, r);
decreaseCounter(r);
}
private boolean increaseCounter(Runnable task) {
if (isInterestOpsEvent(task)) {
return false;
}
Settings settings = this.settings;
int maxTotalMemorySize = settings.maxTotalMemorySize;
int maxChannelMemorySize = settings.maxChannelMemorySize;
int increment = getObjectSizeEstimator().estimateSize(task);
int totalCounter = this.totalCounter.addAndGet(increment);
if (task instanceof ChannelEventRunnable) {
ChannelEventRunnable eventTask = (ChannelEventRunnable) task;
eventTask.estimatedSize = increment;
Channel channel = eventTask.getEvent().getChannel();
int channelCounter = getChannelCounter(channel).addAndGet(increment);
if (maxChannelMemorySize != 0 && channelCounter >= maxChannelMemorySize && channel.isOpen()) {
if (channel.isReadable()) {
channel.setReadable(false);
}
}
}
//System.out.println("I: " + totalCounter + ", " + increment);
return maxTotalMemorySize != 0 && totalCounter >= maxTotalMemorySize;
}
private void decreaseCounter(Runnable task) {
if (isInterestOpsEvent(task)) {
return;
}
Settings settings = this.settings;
int maxTotalMemorySize = settings.maxTotalMemorySize;
int maxChannelMemorySize = settings.maxChannelMemorySize;
int increment;
if (task instanceof ChannelEventRunnable) {
increment = ((ChannelEventRunnable) task).estimatedSize;
} else {
increment = getObjectSizeEstimator().estimateSize(task);
}
int totalCounter = this.totalCounter.addAndGet(-increment);
//System.out.println("D: " + totalCounter + ", " + increment);
if (maxTotalMemorySize != 0 && totalCounter + increment >= maxTotalMemorySize) {
//System.out.println("RELEASE");
semaphore.release();
}
if (task instanceof ChannelEventRunnable) {
Channel channel = ((ChannelEventRunnable) task).getEvent().getChannel();
int channelCounter = getChannelCounter(channel).addAndGet(-increment);
if (maxChannelMemorySize != 0 && channelCounter + increment >= maxChannelMemorySize && channel.isOpen()) {
if (!channel.isReadable()) {
channel.setReadable(true);
}
}
}
}
private AtomicInteger getChannelCounter(Channel channel) {
AtomicInteger counter = channelCounters.get(channel);
if (counter == null) {
counter = new AtomicInteger();
AtomicInteger oldCounter = channelCounters.putIfAbsent(channel, counter);
if (oldCounter != null) {
counter = oldCounter;
}
}
// Remove the entry when the channel closes.
if (!channel.isOpen()) {
channelCounters.remove(channel);
}
return counter;
}
private static boolean isInterestOpsEvent(Runnable task) {
if (task instanceof ChannelEventRunnable) {
ChannelEventRunnable r = (ChannelEventRunnable) task;
if (r.getEvent() instanceof ChannelStateEvent) {
ChannelStateEvent e = (ChannelStateEvent) r.getEvent();
if (e.getState() == ChannelState.INTEREST_OPS) {
return true;
}
}
}
return false;
}
private static class Settings {
final int maxChannelMemorySize;
final int maxTotalMemorySize;
Settings(int maxChannelMemorySize, int maxTotalMemorySize) {
this.maxChannelMemorySize = maxChannelMemorySize;
this.maxTotalMemorySize = maxTotalMemorySize;
}
}
}
|
package org.mockito.internal.creation.bytebuddy;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.ClassFileVersion;
import net.bytebuddy.asm.Advice;
import net.bytebuddy.asm.AsmVisitorWrapper;
import net.bytebuddy.description.field.FieldDescription;
import net.bytebuddy.description.field.FieldList;
import net.bytebuddy.description.method.MethodDescription;
import net.bytebuddy.description.method.MethodList;
import net.bytebuddy.description.method.ParameterDescription;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.dynamic.ClassFileLocator;
import net.bytebuddy.dynamic.scaffold.MethodGraph;
import net.bytebuddy.dynamic.scaffold.TypeValidation;
import net.bytebuddy.implementation.Implementation;
import net.bytebuddy.jar.asm.ClassVisitor;
import net.bytebuddy.jar.asm.MethodVisitor;
import net.bytebuddy.jar.asm.Opcodes;
import net.bytebuddy.matcher.ElementMatchers;
import net.bytebuddy.pool.TypePool;
import net.bytebuddy.utility.OpenedClassReader;
import net.bytebuddy.utility.RandomString;
import org.mockito.exceptions.base.MockitoException;
import org.mockito.internal.util.concurrent.WeakConcurrentMap;
import org.mockito.internal.util.concurrent.WeakConcurrentSet;
import org.mockito.mock.SerializableMode;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.Instrumentation;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.security.ProtectionDomain;
import java.util.*;
import static net.bytebuddy.implementation.MethodDelegation.withDefaultConfiguration;
import static net.bytebuddy.implementation.bind.annotation.TargetMethodAnnotationDrivenBinder.ParameterBinder.ForFixedValue.OfConstant.of;
import static net.bytebuddy.matcher.ElementMatchers.*;
import static org.mockito.internal.util.StringUtil.join;
public class InlineBytecodeGenerator implements BytecodeGenerator, ClassFileTransformer {
private static final String PRELOAD = "org.mockito.inline.preload";
@SuppressWarnings("unchecked")
static final Set<Class<?>> EXCLUDES = new HashSet<Class<?>>(Arrays.asList(Class.class,
Boolean.class,
Byte.class,
Short.class,
Character.class,
Integer.class,
Long.class,
Float.class,
Double.class,
String.class));
private final Instrumentation instrumentation;
private final ByteBuddy byteBuddy;
private final WeakConcurrentSet<Class<?>> mocked;
private final BytecodeGenerator subclassEngine;
private final AsmVisitorWrapper mockTransformer;
private final Method getModule, canRead, redefineModule;
private volatile Throwable lastException;
public InlineBytecodeGenerator(Instrumentation instrumentation, WeakConcurrentMap<Object, MockMethodInterceptor> mocks) {
preload();
this.instrumentation = instrumentation;
byteBuddy = new ByteBuddy()
.with(TypeValidation.DISABLED)
.with(Implementation.Context.Disabled.Factory.INSTANCE)
.with(MethodGraph.Compiler.ForDeclaredMethods.INSTANCE);
mocked = new WeakConcurrentSet<Class<?>>(WeakConcurrentSet.Cleaner.INLINE);
String identifier = RandomString.make();
subclassEngine = new TypeCachingBytecodeGenerator(new SubclassBytecodeGenerator(withDefaultConfiguration()
.withBinders(of(MockMethodAdvice.Identifier.class, identifier))
.to(MockMethodAdvice.ForReadObject.class), isAbstract().or(isNative()).or(isToString())), false);
mockTransformer = new AsmVisitorWrapper.ForDeclaredMethods()
.method(isVirtual()
.and(not(isBridge().or(isHashCode()).or(isEquals()).or(isDefaultFinalizer())))
.and(not(isDeclaredBy(nameStartsWith("java.")).<MethodDescription>and(isPackagePrivate()))),
Advice.withCustomMapping()
.bind(MockMethodAdvice.Identifier.class, identifier)
.to(MockMethodAdvice.class))
.method(isHashCode(),
Advice.withCustomMapping()
.bind(MockMethodAdvice.Identifier.class, identifier)
.to(MockMethodAdvice.ForHashCode.class))
.method(isEquals(),
Advice.withCustomMapping()
.bind(MockMethodAdvice.Identifier.class, identifier)
.to(MockMethodAdvice.ForEquals.class));
Method getModule, canRead, redefineModule;
try {
getModule = Class.class.getMethod("getModule");
canRead = getModule.getReturnType().getMethod("canRead", getModule.getReturnType());
redefineModule = Instrumentation.class.getMethod("redefineModule",
getModule.getReturnType(), Set.class, Map.class, Map.class, Set.class, Map.class);
} catch (Exception ignored) {
getModule = null;
canRead = null;
redefineModule = null;
}
this.getModule = getModule;
this.canRead = canRead;
this.redefineModule = redefineModule;
MockMethodDispatcher.set(identifier, new MockMethodAdvice(mocks, identifier));
instrumentation.addTransformer(this, true);
}
/**
* Mockito allows to mock about any type, including such types that we are relying on ourselves. This can cause a circularity:
* In order to check if an instance is a mock we need to look up if this instance is registered in the {@code mocked} set. But to look
* up this instance, we need to create key instances that rely on weak reference properties. Loading the later classes will happen before
* the key instances are completed what will cause Mockito to check if those key instances are themselves mocks what causes a loop which
* results in a circularity error. This is not normally a problem as we explicitly check if the instance that we investigate is one of
* our instance of which we hold a reference by reference equality what does not cause any code execution. But it seems like the load
* order plays a role here with unloaded types being loaded before we even get to check the mock instance property. To avoid this, we are
* making sure that crucuial JVM types are loaded before we create the first inline mock. Unfortunately, these types dependant on a JVM's
* implementation and we can only maintain types that we know of from well-known JVM implementations such as HotSpot and extend this list
* once we learn of further problematic types for future Java versions. To allow users to whitelist their own types, we do not also offer
* a property that allows running problematic tests before a new Mockito version can be released and that allows us to ask users to
* easily validate that whitelisting actually solves a problem as circularities could also be caused by other problems.
*/
private static void preload() {
String preloads = System.getProperty(PRELOAD);
if (preloads == null) {
preloads = "java.lang.WeakPairMap,java.lang.WeakPairMap$Pair,java.lang.WeakPairMap$Pair$Weak";
}
for (String preload : preloads.split(",")) {
try {
Class.forName(preload, false, null);
} catch (ClassNotFoundException ignored) {
}
}
}
@Override
public <T> Class<? extends T> mockClass(MockFeatures<T> features) {
boolean subclassingRequired = !features.interfaces.isEmpty()
|| features.serializableMode != SerializableMode.NONE
|| Modifier.isAbstract(features.mockedType.getModifiers());
checkSupportedCombination(subclassingRequired, features);
synchronized (this) {
triggerRetransformation(features);
}
return subclassingRequired ?
subclassEngine.mockClass(features) :
features.mockedType;
}
private <T> void triggerRetransformation(MockFeatures<T> features) {
Set<Class<?>> types = new HashSet<Class<?>>();
Class<?> type = features.mockedType;
do {
if (mocked.add(type)) {
types.add(type);
addInterfaces(types, type.getInterfaces());
}
type = type.getSuperclass();
} while (type != null);
if (!types.isEmpty()) {
try {
assureCanReadMockito(types);
instrumentation.retransformClasses(types.toArray(new Class<?>[types.size()]));
Throwable throwable = lastException;
if (throwable != null) {
throw new IllegalStateException(join("Byte Buddy could not instrument all classes within the mock's type hierarchy",
"",
"This problem should never occur for javac-compiled classes. This problem has been observed for classes that are:",
" - Compiled by older versions of scalac",
" - Classes that are part of the Android distribution"), throwable);
}
} catch (Exception exception) {
for (Class<?> failed : types) {
mocked.remove(failed);
}
throw new MockitoException("Could not modify all classes " + types, exception);
} finally {
lastException = null;
}
}
}
private void assureCanReadMockito(Set<Class<?>> types) {
if (redefineModule == null) {
return;
}
Set<Object> modules = new HashSet<Object>();
try {
Object target = getModule.invoke(Class.forName("org.mockito.internal.creation.bytebuddy.MockMethodDispatcher", false, null));
for (Class<?> type : types) {
Object module = getModule.invoke(type);
if (!modules.contains(module) && !(Boolean) canRead.invoke(module, target)) {
modules.add(module);
}
}
for (Object module : modules) {
redefineModule.invoke(instrumentation, module, Collections.singleton(target),
Collections.emptyMap(), Collections.emptyMap(), Collections.emptySet(), Collections.emptyMap());
}
} catch (Exception e) {
throw new IllegalStateException(join("Could not adjust module graph to make the mock instance dispatcher visible to some classes",
"",
"At least one of those modules: " + modules + " is not reading the unnamed module of the bootstrap loader",
"Without such a read edge, the classes that are redefined to become mocks cannot access the mock dispatcher.",
"To circumvent this, Mockito attempted to add a read edge to this module what failed for an unexpected reason"), e);
}
}
private <T> void checkSupportedCombination(boolean subclassingRequired, MockFeatures<T> features) {
if (subclassingRequired
&& !features.mockedType.isArray()
&& !features.mockedType.isPrimitive()
&& Modifier.isFinal(features.mockedType.getModifiers())) {
throw new MockitoException("Unsupported settings with this type '" + features.mockedType.getName() + "'");
}
}
private void addInterfaces(Set<Class<?>> types, Class<?>[] interfaces) {
for (Class<?> type : interfaces) {
if (mocked.add(type)) {
types.add(type);
addInterfaces(types, type.getInterfaces());
}
}
}
@Override
public byte[] transform(ClassLoader loader,
String className,
Class<?> classBeingRedefined,
ProtectionDomain protectionDomain,
byte[] classfileBuffer) {
if (classBeingRedefined == null
|| !mocked.contains(classBeingRedefined)
|| EXCLUDES.contains(classBeingRedefined)) {
return null;
} else {
try {
return byteBuddy.redefine(classBeingRedefined, ClassFileLocator.Simple.of(classBeingRedefined.getName(), classfileBuffer))
// Note: The VM erases parameter meta data from the provided class file (bug). We just add this information manually.
.visit(new ParameterWritingVisitorWrapper(classBeingRedefined))
.visit(mockTransformer)
.make()
.getBytes();
} catch (Throwable throwable) {
lastException = throwable;
return null;
}
}
}
private static class ParameterWritingVisitorWrapper extends AsmVisitorWrapper.AbstractBase {
private final Class<?> type;
private ParameterWritingVisitorWrapper(Class<?> type) {
this.type = type;
}
@Override
public ClassVisitor wrap(TypeDescription instrumentedType,
ClassVisitor classVisitor,
Implementation.Context implementationContext,
TypePool typePool,
FieldList<FieldDescription.InDefinedShape> fields,
MethodList<?> methods,
int writerFlags,
int readerFlags) {
return implementationContext.getClassFileVersion().isAtLeast(ClassFileVersion.JAVA_V8)
? new ParameterAddingClassVisitor(classVisitor, new TypeDescription.ForLoadedType(type))
: classVisitor;
}
private static class ParameterAddingClassVisitor extends ClassVisitor {
private final TypeDescription typeDescription;
private ParameterAddingClassVisitor(ClassVisitor cv, TypeDescription typeDescription) {
super(OpenedClassReader.ASM_API, cv);
this.typeDescription = typeDescription;
}
@Override
public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
MethodVisitor methodVisitor = super.visitMethod(access, name, desc, signature, exceptions);
MethodList<?> methodList = typeDescription.getDeclaredMethods().filter((name.equals(MethodDescription.CONSTRUCTOR_INTERNAL_NAME)
? isConstructor()
: ElementMatchers.<MethodDescription>named(name)).and(hasDescriptor(desc)));
if (methodList.size() == 1 && methodList.getOnly().getParameters().hasExplicitMetaData()) {
for (ParameterDescription parameterDescription : methodList.getOnly().getParameters()) {
methodVisitor.visitParameter(parameterDescription.getName(), parameterDescription.getModifiers());
}
return new MethodParameterStrippingMethodVisitor(methodVisitor);
} else {
return methodVisitor;
}
}
}
private static class MethodParameterStrippingMethodVisitor extends MethodVisitor {
public MethodParameterStrippingMethodVisitor(MethodVisitor mv) {
super(Opcodes.ASM5, mv);
}
@Override
public void visitParameter(String name, int access) {
// suppress to avoid additional writing of the parameter if retained.
}
}
}
}
|
package org.mvnsearch.ali.oss.spring.services.impl;
import com.aliyun.openservices.oss.OSSClient;
import com.aliyun.openservices.oss.model.*;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.http.impl.cookie.DateUtils;
import org.jetbrains.annotations.Nullable;
import org.mvnsearch.ali.oss.spring.services.AliyunOssService;
import org.mvnsearch.ali.oss.spring.services.ConfigService;
import org.mvnsearch.ali.oss.spring.services.OSSUri;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.ConfigurableMimeFileTypeMap;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.List;
/**
* aliyun OSS service implementation
*
* @author linux_china
*/
@Component("aliyunOssService")
public class AliyunOssServiceImpl implements AliyunOssService {
/**
* end point
*/
private String endpoint = "http://storage.aliyun.com";
/**
* config service
*/
private ConfigService configService;
/**
* oss client
*/
private OSSClient oss;
/**
* mime types
*/
private static ConfigurableMimeFileTypeMap mimeTypes = new ConfigurableMimeFileTypeMap();
/**
* inject config service
*
* @param configService config service
*/
@Autowired
public void setConfigService(ConfigService configService) {
this.configService = configService;
}
/**
* refresh token
*/
@PostConstruct
public void refreshToken() {
String accessId = configService.getProperty("ACCESS_ID");
String accessKey = configService.getProperty("ACCESS_KEY");
if (accessId != null) {
oss = new OSSClient(endpoint, accessId, accessKey);
}
}
/**
* get oss client
*
* @return oss client
*/
public OSSClient getOssClient() {
return oss;
}
/**
* create bucket
*
* @param bucket bucket name
* @throws Exception exception
*/
public void createBucket(String bucket) throws Exception {
oss.createBucket(bucket);
}
/**
* drop bucket
*
* @param bucket bucket
* @throws Exception exception
*/
public void dropBucket(String bucket) throws Exception {
oss.deleteBucket(bucket);
}
/**
* delete bucket
*
* @param bucket bucket
* @throws Exception exception
*/
public void deleteBucket(String bucket) throws Exception {
oss.deleteBucket(bucket);
}
/**
* list buckets
*
* @return bucket list
* @throws Exception exception
*/
public List<Bucket> getBuckets() throws Exception {
return oss.listBuckets();
}
/**
* get bucket ACL
*
* @param bucket bucket name
* @return ACL String, such --, RW, R-
* @throws Exception exception
*/
public String getBucketACL(String bucket) throws Exception {
String aclStr = "
AccessControlList acl = oss.getBucketAcl(bucket);
for (Grant grant : acl.getGrants()) {
if (grant.getGrantee() == GroupGrantee.AllUsers) {
if (grant.getPermission() == Permission.Read) {
aclStr = "R-";
}
if (grant.getPermission() == Permission.FullControl) {
aclStr = "RW";
}
}
}
return aclStr;
}
/**
* ACL
*
* @param bucket bucket
* @param acl acl value, such --, R- or RW
* @throws Exception exception
*/
@Override
public void setBucketACL(String bucket, String acl) throws Exception {
if (acl.equals("RW")) {
oss.setBucketAcl(bucket, CannedAccessControlList.PublicReadWrite);
} else if (acl.equals("R-") || acl.equals("R")) {
oss.setBucketAcl(bucket, CannedAccessControlList.PublicRead);
} else {
oss.setBucketAcl(bucket, CannedAccessControlList.Private);
}
}
/**
* list
*
* @param bucketName bucket name
* @param path path
* @return object metadata list
*/
@Override
public ObjectListing list(String bucketName, String path) throws Exception {
if (path == null) {
path = "";
}
path = path.trim();
if (path.endsWith("*")) {
path = path.substring(0, path.length() - 1);
}
ListObjectsRequest request = new ListObjectsRequest();
request.setBucketName(bucketName);
request.setPrefix(path);
request.setMaxKeys(MAX_OBJECTS);
return oss.listObjects(request);
}
/**
* list children only
*
* @param bucketName bucket name
* @param path path
* @return object listing
* @throws Exception exception
*/
public ObjectListing listChildren(String bucketName, String path) throws Exception {
if (path == null || path.equals("/")) {
path = "";
}
if (!path.isEmpty() && !path.endsWith("/")) {
path = path + "/";
}
path = path.trim();
ListObjectsRequest request = new ListObjectsRequest();
request.setBucketName(bucketName);
request.setPrefix(path);
request.setDelimiter("/");
request.setMaxKeys(MAX_OBJECTS);
return oss.listObjects(request);
}
/**
* put local file to OSS
*
* @param sourceFilePath source file path on local disk
* @param destObject dest object
* @return oss file path
*/
public String put(String sourceFilePath, OSSUri destObject) throws Exception {
byte[] content = IOUtils.toByteArray(new FileInputStream(sourceFilePath));
ObjectMetadata objectMetadata = new ObjectMetadata();
objectMetadata.setContentType(mimeTypes.getContentType(sourceFilePath));
objectMetadata.setContentLength(content.length);
oss.putObject(destObject.getBucket(), destObject.getFilePath(), new ByteArrayInputStream(content), objectMetadata);
return destObject.toString();
}
/**
* copy object
*
* @param sourceObjectUri source object uri
* @param destObjectUri dest object uri
* @return new file path
* @throws Exception exception
*/
public String copy(OSSUri sourceObjectUri, OSSUri destObjectUri) throws Exception {
oss.copyObject(sourceObjectUri.getBucket(), sourceObjectUri.getFilePath(), destObjectUri.getBucket(), destObjectUri.getFilePath());
return destObjectUri.toString();
}
/**
* get file and save into local disk
*
* @param objectUri object uri
* @param destFilePath dest file path
* @return local file path
*/
public String get(OSSUri objectUri, String destFilePath) throws Exception {
OSSObject ossObject = oss.getObject(objectUri.getBucket(), objectUri.getFilePath());
if (ossObject != null) {
File destFile = new File(destFilePath);
if (destFile.isDirectory()) {
destFile = new File(destFile, objectUri.getFileName());
}
if (!destFile.getParentFile().exists()) {
FileUtils.forceMkdir(destFile.getParentFile());
}
FileOutputStream fos = new FileOutputStream(destFilePath);
IOUtils.copy(ossObject.getObjectContent(), fos);
fos.close();
}
return destFilePath;
}
/**
* delete object
*
* @param objectUri bucket uri
* @throws Exception exception
*/
public void delete(OSSUri objectUri) throws Exception {
oss.deleteObject(objectUri.getBucket(), objectUri.getFilePath());
}
/**
* get oss object
*
* @param objectUri object uri
* @return oss object
*/
@Nullable
public ObjectMetadata getObjectMetadata(OSSUri objectUri) throws Exception {
return oss.getObjectMetadata(objectUri.getBucket(), objectUri.getFilePath());
}
/**
* get OSS object
*
* @param objectUri object uri
* @return OSS object
* @throws Exception exception
*/
@Nullable
public OSSObject getOssObject(OSSUri objectUri) throws Exception {
return oss.getObject(objectUri.getBucket(), objectUri.getFilePath());
}
/**
* set object meta data
*
* @param objectUri object uri
* @param key key
* @param value value
*/
public void setObjectMetadata(OSSUri objectUri, String key, String value) throws Exception {
ObjectMetadata objectMetadata = oss.getObjectMetadata(objectUri.getBucket(), objectUri.getFilePath());
CopyObjectRequest copyObjectRequest = new CopyObjectRequest(objectUri.getBucket(), objectUri.getFilePath(),
objectUri.getBucket(), objectUri.getFilePath());
if (key.equalsIgnoreCase("Cache-Control")) {
objectMetadata.setCacheControl(value);
} else if (key.equals("Content-Type")) {
objectMetadata.setContentType(value);
} else if (key.equalsIgnoreCase("Expires")) {
objectMetadata.setExpirationTime(DateUtils.parseDate(value, new String[]{"yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss"}));
} else {
if (objectMetadata.getUserMetadata() == null || objectMetadata.getUserMetadata().isEmpty()) {
objectMetadata.setUserMetadata(new HashMap<String, String>());
}
objectMetadata.getUserMetadata().put(key, value);
}
copyObjectRequest.setNewObjectMetadata(objectMetadata);
oss.copyObject(copyObjectRequest);
}
}
|
package org.ndexbio.common.persistence.orientdb;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;
import java.util.concurrent.ExecutionException;
import java.util.logging.Logger;
import org.ndexbio.common.NdexClasses;
import org.ndexbio.common.NetworkSourceFormat;
import org.ndexbio.common.access.NdexDatabase;
import org.ndexbio.common.models.dao.orientdb.NetworkDAO;
import org.ndexbio.common.models.dao.orientdb.UserDAO;
import org.ndexbio.common.models.object.network.RawNamespace;
import org.ndexbio.common.util.NdexUUIDFactory;
import org.ndexbio.model.exceptions.NdexException;
import org.ndexbio.model.object.NdexPropertyValuePair;
import org.ndexbio.model.object.network.BaseTerm;
import org.ndexbio.model.object.network.Citation;
import org.ndexbio.model.object.network.Edge;
import org.ndexbio.model.object.network.FunctionTerm;
import org.ndexbio.model.object.network.Namespace;
import org.ndexbio.model.object.network.Network;
import org.ndexbio.model.object.network.NetworkSummary;
import org.ndexbio.model.object.network.Node;
import org.ndexbio.model.object.network.ReifiedEdgeTerm;
import org.ndexbio.model.object.network.Support;
import org.ndexbio.model.object.network.VisibilityType;
import com.google.common.base.Preconditions;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.tinkerpop.blueprints.impls.orient.OrientVertex;
public class NdexNetworkCloneService extends PersistenceService {
private Network srcNetwork;
// private NetworkSummary networkSummary;
// key is the full URI or other fully qualified baseTerm as a string.
// private LoadingCache<String, BaseTerm> baseTermStrCache;
// private ODocument networkDoc;
// private ODocument ownerDoc;
private String ownerAccount;
// all these mapping are for mapping from source Id to Ids in the newly persisted graph.
private Map<Long, Long> baseTermIdMap;
private Map<Long, Long> reifiedEdgeTermIdMap;
private Map<Long, Long> nodeIdMap;
private Map<Long, Long> functionTermIdMap;
private Map<Long, Long> namespaceIdMap;
private Map<Long, Long> citationIdMap;
private Map<Long, Long> supportIdMap;
private Map<Long, Long> edgeIdMap;
/*
* Currently, the procces flow of this class is:
*
* 1. create object
* 2. Create New network
*/
public NdexNetworkCloneService(NdexDatabase db, Network sourceNetwork, String ownerAccountName) throws NdexException {
super(db);
Preconditions.checkNotNull(sourceNetwork.getName(),"A network title is required");
this.srcNetwork = sourceNetwork;
this.network = new NetworkSummary();
this.ownerAccount = ownerAccountName;
this.baseTermIdMap = new HashMap <>(1000);
this.namespaceIdMap = new HashMap <>(1000);
this.citationIdMap = new HashMap <> (1000);
this.reifiedEdgeTermIdMap = new HashMap<>(1000);
this.nodeIdMap = new HashMap<>(1000);
this.edgeIdMap = new HashMap<> ();
this.supportIdMap = new HashMap<> (1000);
this.functionTermIdMap = new HashMap<>(1000);
// intialize caches.
logger = Logger.getLogger(NdexPersistenceService.class.getName());
}
/**
*
* @return
* @throws NdexException
* @throws ExecutionException
*/
public NetworkSummary updateNetwork() throws NdexException, ExecutionException {
try {
// need to keep this order because of the dependency between objects.
updateNetworkNode ();
cloneNetworkElements();
// addPropertiesToVertex(networkVertex, srcNetwork.getProperties(), srcNetwork.getPresentationProperties());
this.networkDoc.reload();
this.networkDoc.field(NdexClasses.Network_P_isComplete , true);
return this.network;
} finally {
this.localConnection.commit();
}
}
private void updateNetworkNode() throws NdexException, ExecutionException {
if ( this.srcNetwork.getExternalId() == null)
throw new NdexException("Source network doesn't have a UUID. ");
this.networkDoc = networkDAO.getNetworkDocByUUID(this.srcNetwork.getExternalId());
if (networkDoc == null)
throw new NdexException("Network with UUID " + this.srcNetwork.getExternalId()
+ " is not found in this server");
this.network = NetworkDAO.getNetworkSummary(networkDoc);
this.network.setName(srcNetwork.getName());
this.network.setEdgeCount(srcNetwork.getEdges().size());
this.network.setNodeCount(srcNetwork.getNodes().size());
this.network.setDescription(srcNetwork.getDescription());
this.network.setVersion(srcNetwork.getVersion());
// make description is not null so that the Lucene index will index this field.
if ( this.network.getDescription() == null)
this.network.setDescription("");
networkDoc = networkDoc.fields(
NdexClasses.ExternalObj_mTime, Calendar.getInstance().getTime(),
NdexClasses.Network_P_name, srcNetwork.getName(),
NdexClasses.Network_P_edgeCount, network.getEdgeCount(),
NdexClasses.Network_P_nodeCount, network.getNodeCount(),
NdexClasses.Network_P_desc,srcNetwork.getDescription(),
NdexClasses.Network_P_version,srcNetwork.getVersion(),
NdexClasses.Network_P_isLocked, false,
NdexClasses.Network_P_isComplete, false);
NetworkSourceFormat fmt = removeNetworkSourceFormat(srcNetwork);
if ( fmt!=null)
networkDoc.field(NdexClasses.Network_P_source_format, fmt.toString());
networkDoc = networkDoc.save();
this.localConnection.commit();
networkVertex = graph.getVertex(networkDoc);
networkDAO.deleteNetworkProperties(networkDoc);
networkDAO.deleteNetworkElements(network.getExternalId().toString());
networkVertex.getRecord().reload();
addPropertiesToVertex(networkVertex, srcNetwork.getProperties(), srcNetwork.getPresentationProperties());
this.network.getProperties().addAll(srcNetwork.getProperties());
this.network.getPresentationProperties().addAll(srcNetwork.getPresentationProperties());
networkDoc.reload();
networkVertex.getRecord().reload();
logger.info("NDEx network titled: " +srcNetwork.getName() +" has been updated.");
}
private void cloneNetworkElements() throws NdexException, ExecutionException {
try {
// need to keep this order because of the dependency between objects.
cloneNamespaces ();
cloneBaseTerms ();
cloneCitations();
cloneSupports();
cloneReifiedEdgeTermNodes(); // only clone the vertex itself.
cloneFunctionTermVertex();
cloneNodes();
cloneEdges();
// process reifiedEdgeTerm and FunctionTerm
createLinksforRefiedEdgeTerm();
createLinksFunctionTerm();
network.setIsLocked(false);
network.setIsComplete(true);
networkDoc.field(NdexClasses.Network_P_isComplete,true)
.save();
logger.info("Updating network " + network.getName() + " is complete.");
} finally {
this.localConnection.commit();
}
}
public NetworkSummary cloneNetwork() throws NdexException, ExecutionException {
try {
// need to keep this order because of the dependency between objects.
cloneNetworkNode ();
cloneNetworkElements();
this.localConnection.commit();
// find the network owner in the database
UserDAO userdao = new UserDAO(localConnection, graph);
ODocument ownerDoc = userdao.getRecordByAccountName(this.ownerAccount, null) ;
OrientVertex ownerV = graph.getVertex(ownerDoc);
ownerV.addEdge(NdexClasses.E_admin, networkVertex);
this.localConnection.commit();
return this.network;
} finally {
logger.info("Network "+ network.getName() + " with UUID:"+ network.getExternalId() +" has been saved. ");
}
}
private void cloneNetworkNode() throws NdexException, ExecutionException {
this.network.setExternalId( NdexUUIDFactory.INSTANCE.getNDExUUID());
// logger.info("using network prefix: " + NdexDatabase.getURIPrefix() );
// logger.info("Configuration is HostURI=" + Configuration.getInstance().getProperty("HostURI") );
this.network.setURI(NdexDatabase.getURIPrefix() + "/network/"
+ this.network.getExternalId().toString());
this.network.setName(srcNetwork.getName());
this.network.setEdgeCount(srcNetwork.getEdges().size());
this.network.setNodeCount(srcNetwork.getNodes().size());
networkDoc = new ODocument (NdexClasses.Network)
.fields(NdexClasses.Network_P_UUID,this.network.getExternalId().toString(),
NdexClasses.ExternalObj_cTime, network.getCreationTime(),
NdexClasses.ExternalObj_mTime, network.getModificationTime(),
NdexClasses.ExternalObj_isDeleted, false,
NdexClasses.Network_P_name, srcNetwork.getName(),
NdexClasses.Network_P_edgeCount, network.getEdgeCount(),
NdexClasses.Network_P_nodeCount, network.getNodeCount(),
NdexClasses.Network_P_isLocked, false,
NdexClasses.Network_P_isComplete, false,
NdexClasses.Network_P_visibility,
( srcNetwork.getVisibility() == null ?
VisibilityType.PRIVATE.toString() :
srcNetwork.getVisibility().toString()));
if ( srcNetwork.getDescription() != null) {
networkDoc.field(NdexClasses.Network_P_desc,srcNetwork.getDescription());
network.setDescription(srcNetwork.getDescription());
}
if ( srcNetwork.getVersion() != null) {
networkDoc.field(NdexClasses.Network_P_version,srcNetwork.getVersion());
network.setDescription(srcNetwork.getVersion());
}
NetworkSourceFormat fmt = removeNetworkSourceFormat(srcNetwork);
if ( fmt!=null)
networkDoc.field(NdexClasses.Network_P_source_format, fmt.toString());
networkDoc = networkDoc.save();
networkVertex = graph.getVertex(networkDoc);
addPropertiesToVertex(networkVertex, srcNetwork.getProperties(), srcNetwork.getPresentationProperties());
this.network.getProperties().addAll(srcNetwork.getProperties());
this.network.getPresentationProperties().addAll(srcNetwork.getPresentationProperties());
logger.info("A new NDex network titled: " +srcNetwork.getName() +" has been created");
}
private void cloneNamespaces() throws NdexException, ExecutionException {
TreeSet<String> prefixSet = new TreeSet<>();
if ( srcNetwork.getNamespaces() != null) {
for ( Namespace ns : srcNetwork.getNamespaces().values() ) {
if ( ns.getPrefix() !=null && prefixSet.contains(ns.getPrefix()))
throw new NdexException("Duplicated Prefix " + ns.getPrefix() + " found." );
Long nsId = getNamespace( new RawNamespace(ns.getPrefix(), ns.getUri())).getId();
ODocument nsDoc = this.elementIdCache.get(nsId);
OrientVertex nsV = graph.getVertex(nsDoc);
addPropertiesToVertex(nsV, ns.getProperties(), ns.getPresentationProperties());
this.namespaceIdMap.put(ns.getId(), nsId);
}
}
}
private void cloneBaseTerms() throws ExecutionException, NdexException {
if ( srcNetwork.getBaseTerms()!= null) {
for ( BaseTerm term : srcNetwork.getBaseTerms().values() ) {
Long nsId = (long)-1 ;
if ( term.getNamespaceId() >0 ) {
nsId = namespaceIdMap.get(term.getNamespaceId());
if ( nsId == null)
throw new NdexException ("Namespece Id " + term.getNamespaceId() + " is not found in name space list.");
}
Long baseTermId = createBaseTerm(term.getName(), nsId);
this.baseTermIdMap.put(term.getId(), baseTermId);
}
}
}
private void cloneCitations() throws NdexException, ExecutionException {
if ( srcNetwork.getCitations()!= null) {
for ( Citation citation : srcNetwork.getCitations().values() ) {
Long citationId = this.createCitation(citation.getTitle(),
citation.getIdType(), citation.getIdentifier(),
citation.getContributors(), citation.getProperties(), citation.getPresentationProperties());
this.citationIdMap.put(citation.getId(), citationId);
}
}
}
private void cloneSupports() throws NdexException, ExecutionException {
if ( srcNetwork.getSupports()!= null) {
for ( Support support : srcNetwork.getSupports().values() ) {
Long citationId = -1l;
long srcCitationId = support.getCitationId();
if ( srcCitationId != -1)
citationId = citationIdMap.get(srcCitationId);
if ( citationId == null )
throw new NdexException ("Citation Id " + support.getCitationId() + " is not found in citation list.");
Long supportId = createSupport(support.getText(),citationId);
this.supportIdMap.put(support.getId(), supportId);
}
}
}
// we only clone the nodes itself. We added the edges in the second rournd
private void cloneReifiedEdgeTermNodes() {
if ( srcNetwork.getReifiedEdgeTerms()!= null) {
for ( ReifiedEdgeTerm reifiedTerm : srcNetwork.getReifiedEdgeTerms().values() ) {
Long reifiedEdgeTermId = this.database.getNextId();
ODocument eTermdoc = new ODocument (NdexClasses.ReifiedEdgeTerm);
eTermdoc = eTermdoc.field(NdexClasses.Element_ID, reifiedEdgeTermId)
.save();
elementIdCache.put(reifiedEdgeTermId, eTermdoc);
this.reifiedEdgeTermIdMap.put(reifiedTerm.getId(), reifiedEdgeTermId);
}
}
}
private void cloneFunctionTermVertex() {
if ( srcNetwork.getFunctionTerms()!= null) {
for ( FunctionTerm functionTerm : srcNetwork.getFunctionTerms().values() ) {
Long newFunctionTermId = this.database.getNextId();
ODocument eTermdoc = new ODocument (NdexClasses.FunctionTerm)
.field(NdexClasses.Element_ID, newFunctionTermId)
.save();
elementIdCache.put(newFunctionTermId, eTermdoc);
this.functionTermIdMap.put(functionTerm.getId(), newFunctionTermId);
}
}
}
private void cloneNodes() throws NdexException, ExecutionException {
if ( srcNetwork.getNodes()!= null) {
for ( Node node : srcNetwork.getNodes().values() ) {
Long newNodeId = createNode(node);
this.nodeIdMap.put(node.getId(), newNodeId);
}
}
}
private Long createNode (Node node) throws NdexException, ExecutionException {
Long nodeId = database.getNextId();
ODocument nodeDoc = new ODocument(NdexClasses.Node)
.field(NdexClasses.Element_ID, nodeId);
if ( node.getName()!= null) {
nodeDoc = nodeDoc.field(NdexClasses.Node_P_name,node.getName());
}
nodeDoc= nodeDoc.save();
OrientVertex nodeV = graph.getVertex(nodeDoc);
if ( node.getRepresents() != null ) {
Long newRepId = null;
String repType = node.getRepresentsTermType();
if ( repType.equals(NdexClasses.BaseTerm)) {
newRepId = baseTermIdMap.get(node.getRepresents());
} else if (repType.equals(NdexClasses.FunctionTerm)) {
newRepId = functionTermIdMap.get(node.getRepresents());
} else
newRepId = reifiedEdgeTermIdMap.get(node.getRepresents());
if ( newRepId == null)
throw new NdexException ("Term id " + node.getRepresents() + "not found.");
ODocument termDoc = elementIdCache.get(newRepId);
nodeV.addEdge(NdexClasses.Node_E_represents, graph.getVertex(termDoc));
}
if ( node.getAliases() != null) {
for ( Long aliasId : node.getAliases()) {
Long newAliasId = baseTermIdMap.get(aliasId);
if ( newAliasId == null)
throw new NdexException ("Base term id " + aliasId + " not found.");
ODocument termDoc = elementIdCache.get(newAliasId);
nodeV.addEdge(NdexClasses.Node_E_alias, graph.getVertex(termDoc));
}
}
if ( node.getRelatedTerms() != null) {
for ( Long relateToId : node.getRelatedTerms()) {
Long newRelateToId = baseTermIdMap.get(relateToId);
if ( newRelateToId == null)
throw new NdexException ("Base term id " + relateToId + " not found.");
ODocument termDoc = elementIdCache.get(newRelateToId);
nodeV.addEdge(NdexClasses.Node_E_relateTo, graph.getVertex(termDoc));
}
}
if ( node.getCitationIds() != null) {
for ( Long citationId : node.getCitationIds()) {
Long newCitationId = citationIdMap.get(citationId);
if ( newCitationId == null)
throw new NdexException ("Citation id " + citationId + " not found.");
ODocument citationDoc = elementIdCache.get(newCitationId);
nodeV.addEdge(NdexClasses.Node_E_citations, graph.getVertex(citationDoc));
}
}
if ( node.getSupportIds() != null) {
for ( Long supportId : node.getSupportIds()) {
Long newSupportId = supportIdMap.get(supportId);
if ( newSupportId == null)
throw new NdexException ("Support id " + supportId + " not found.");
ODocument supportDoc = elementIdCache.get(newSupportId);
nodeV.addEdge(NdexClasses.Node_E_supports, graph.getVertex(supportDoc));
}
}
networkVertex.addEdge(NdexClasses.Network_E_Nodes,nodeV);
this.addPropertiesToVertex(nodeV, node.getProperties(), node.getPresentationProperties());
elementIdCache.put(nodeId, nodeDoc);
return nodeId;
}
private void cloneEdges() throws NdexException, ExecutionException {
if ( srcNetwork.getEdges() != null) {
for ( Edge edge : srcNetwork.getEdges().values()) {
Long newEdgeId = createEdge(edge);
edgeIdMap.put(edge.getId(), newEdgeId);
}
}
}
private Long createEdge(Edge edge) throws NdexException, ExecutionException {
Long edgeId = database.getNextId();
ODocument edgeDoc = new ODocument(NdexClasses.Edge)
.field(NdexClasses.Element_ID, edgeId)
.save();
OrientVertex edgeV = graph.getVertex(edgeDoc);
{
Long newSubjectId = nodeIdMap.get(edge.getSubjectId());
if ( newSubjectId == null)
throw new NdexException ("Node id " + edge.getSubjectId() + "not found.");
ODocument subjectDoc = elementIdCache.get(newSubjectId);
graph.getVertex(subjectDoc).addEdge(NdexClasses.Edge_E_subject, edgeV);
}
{
Long newObjectId = nodeIdMap.get(edge.getObjectId());
if ( newObjectId == null)
throw new NdexException ("Node id " + edge.getObjectId() + "not found.");
ODocument objectDoc = elementIdCache.get(newObjectId);
edgeV.addEdge(NdexClasses.Edge_E_object, graph.getVertex(objectDoc));
}
Long newPredicateId = baseTermIdMap.get(edge.getPredicateId());
if ( newPredicateId == null)
throw new NdexException ("Base term id " + edge.getPredicateId() + " not found.");
ODocument termDoc = elementIdCache.get(newPredicateId);
edgeV.addEdge(NdexClasses.Edge_E_predicate, graph.getVertex(termDoc));
if ( edge.getCitationIds() != null) {
for ( Long citationId : edge.getCitationIds()) {
Long newCitationId = citationIdMap.get(citationId);
if ( newCitationId == null)
throw new NdexException ("Citation id " + citationId + " not found.");
ODocument citationDoc = elementIdCache.get(newCitationId);
edgeV.addEdge(NdexClasses.Edge_E_citations, graph.getVertex(citationDoc));
}
}
if ( edge.getSupportIds() != null) {
for ( Long supportId : edge.getSupportIds()) {
Long newSupportId = supportIdMap.get(supportId);
if ( newSupportId == null)
throw new NdexException ("Support id " + supportId + " not found.");
ODocument supportDoc = elementIdCache.get(newSupportId);
edgeV.addEdge(NdexClasses.Edge_E_supports, graph.getVertex(supportDoc));
}
}
networkVertex.addEdge(NdexClasses.Network_E_Edges,edgeV);
this.addPropertiesToVertex(edgeV, edge.getProperties(), edge.getPresentationProperties());
elementIdCache.put(edgeId, edgeDoc);
return edgeId;
}
private void createLinksforRefiedEdgeTerm() throws NdexException, ExecutionException {
if ( srcNetwork.getReifiedEdgeTerms()!= null) {
for ( ReifiedEdgeTerm reifiedTerm : srcNetwork.getReifiedEdgeTerms().values() ) {
Long newReifiedEdgeId = this.reifiedEdgeTermIdMap.get(reifiedTerm.getId());
if ( newReifiedEdgeId == null)
throw new NdexException("ReifiedEdgeTerm Id " + reifiedTerm.getId() + " not found.");
Long newEdgeId = edgeIdMap.get(reifiedTerm.getEdgeId());
if ( newEdgeId == null)
throw new NdexException ("Edge Id " + reifiedTerm.getEdgeId() + " not found in the system.");
ODocument edgeDoc = elementIdCache.get(newEdgeId);
ODocument reifiedEdgeTermDoc = elementIdCache.get(newReifiedEdgeId);
graph.getVertex(reifiedEdgeTermDoc).addEdge(
NdexClasses.ReifiedEdge_E_edge, graph.getVertex(edgeDoc));
}
}
}
private void createLinksFunctionTerm() throws NdexException, ExecutionException {
if ( srcNetwork.getFunctionTerms()!= null) {
for ( FunctionTerm functionTerm : srcNetwork.getFunctionTerms().values() ) {
Long newFunctionId = this.functionTermIdMap.get(functionTerm.getId());
if ( newFunctionId == null )
throw new NdexException ("Function term Id " + functionTerm.getId() + " is not found in Term list.");
ODocument functionTermDoc = elementIdCache.get(newFunctionId);
OrientVertex functionTermV = graph.getVertex(functionTermDoc);
Long newFunctionNameId = this.baseTermIdMap.get(functionTerm.getFunctionTermId());
ODocument newFunctionNameDoc = elementIdCache.get(newFunctionNameId);
functionTermV.addEdge(NdexClasses.FunctionTerm_E_baseTerm, graph.getVertex(newFunctionNameDoc));
for ( Long argId : functionTerm.getParameterIds()) {
Long newId = findTermId(argId);
if ( newId == null)
throw new NdexException ("Term Id " + argId + " is not found in any term list.");
ODocument argumentDoc = elementIdCache.get(newId);
functionTermV.addEdge(NdexClasses.FunctionTerm_E_paramter, graph.getVertex(argumentDoc));
}
}
}
}
private static NetworkSourceFormat removeNetworkSourceFormat(NetworkSummary nsummary) {
List<NdexPropertyValuePair> props = nsummary.getProperties();
for ( int i = 0 ; i < props.size(); i++) {
NdexPropertyValuePair p = props.get(i);
if ( p.getPredicateString().equals(NdexClasses.Network_P_source_format)) {
NetworkSourceFormat fmt = NetworkSourceFormat.valueOf(p.getValue());
props.remove(i);
return fmt;
}
}
return null;
}
/**
* Find the matching term ID from an old term Id. This function is only used for cloning function parameters.
* @param oldId original id in the function parameter list.
* @return new id
*/
private Long findTermId (Long oldId) {
Long id = baseTermIdMap.get(oldId);
if ( id != null) return id;
id = functionTermIdMap.get(oldId);
if ( id != null ) return id;
return reifiedEdgeTermIdMap.get(oldId);
}
}
|
package org.spongepowered.api.item.inventory.crafting;
import com.google.common.base.Optional;
import org.spongepowered.api.item.inventory.types.GridInventory;
import org.spongepowered.api.item.recipe.Recipe;
/**
* A CraftingInventory represents the inventory of something that can craft items.
*/
public interface CraftingInventory extends GridInventory {
/**
* Gets the crafting matrix of this CraftingInventory.
*
* @return The crafting matrix
*/
GridInventory getCraftingGrid();
/**
* Gets the result slot of this CraftingInventory.
*
* @return The result slot
*/
CraftingOutput getResult();
/**
* Retrieves the recipe formed by this CraftingInventory, if any.
*
* @return The recipe or {@link Optional#absent()} if no recipe is formed
*/
Optional<Recipe> getRecipe();
/**
* Checks if this is a flowerpot.
*
* @return Whether this is a flowerpot
*/
boolean isFlowerPot();
}
|
package org.spongepowered.mod.mixin.core.world.storage;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.datafix.DataFixer;
import net.minecraft.world.storage.SaveFormatOld;
import net.minecraft.world.storage.SaveHandler;
import net.minecraft.world.storage.WorldInfo;
import net.minecraftforge.fml.common.FMLCommonHandler;
import net.minecraftforge.fml.common.Loader;
import net.minecraftforge.fml.common.ModContainer;
import org.spongepowered.api.Sponge;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.Redirect;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import org.spongepowered.common.SpongeImpl;
import org.spongepowered.common.interfaces.IMixinSaveHandler;
import org.spongepowered.common.plugin.PluginContainerExtension;
import org.spongepowered.mod.SpongeMod;
import java.io.File;
@Mixin(value = SaveHandler.class, priority = 1001)
public abstract class MixinSaveHandler {
@Shadow @Final protected DataFixer dataFixer;
@Shadow @Final private File worldDirectory;
private File modWorldDirectory = null;
@Redirect(method = "saveWorldInfoWithPlayer", at = @At(value = "INVOKE", target = "Lnet/minecraftforge/fml/common/FMLCommonHandler;handleWorldDataSave"
+ "(Lnet/minecraft/world/storage/SaveHandler;Lnet/minecraft/world/storage/WorldInfo;Lnet/minecraft/nbt/NBTTagCompound;)V", remap = false))
public void redirectHandleWorldDataSaveWithPlayer(FMLCommonHandler fml, SaveHandler handler, WorldInfo worldInformation, NBTTagCompound
compound) {
if (fml.getSavesDirectory().equals(this.worldDirectory.getParentFile())) {
fml.handleWorldDataSave(handler, worldInformation, compound);
}
}
@Redirect(method = "loadWorldInfo", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/storage/SaveFormatOld;loadAndFix(Ljava/io/File;Lnet/minecraft/util/datafix/DataFixer;Lnet/minecraft/world/storage/SaveHandler;)Lnet/minecraft/world/storage/WorldInfo;", remap = false))
private WorldInfo onLoadWorldInfo(File file, DataFixer fixer, SaveHandler handler) {
final WorldInfo worldInfo = SaveFormatOld.loadAndFix(file, fixer, handler);
if (worldInfo != null) {
try {
((IMixinSaveHandler) handler).loadSpongeDatData(worldInfo);
} catch (Exception e) {
throw new RuntimeException("derp", e);
}
}
return worldInfo;
}
@Inject(method = "getWorldDirectory", at = @At("HEAD"), cancellable = true)
public void onGetWorldDirectory(CallbackInfoReturnable<File> cir) {
final ModContainer activeContainer = Loader.instance().activeModContainer();
// Since Forge uses a single save handler mods will expect this method to return overworld's world directory
// Fixes mods such as ComputerCraft and FuturePack
if ((activeContainer != null && activeContainer != SpongeMod.instance && !(activeContainer instanceof PluginContainerExtension))) {
if (this.modWorldDirectory != null) {
cir.setReturnValue(this.modWorldDirectory);
} else {
final String defaultWorldName = Sponge.getServer().getDefaultWorldName();
final String defaultWorldPath = Sponge.getPlatform().getType().isClient() ? "saves" + File.separator + defaultWorldName :
defaultWorldName;
this.modWorldDirectory = SpongeImpl.getGameDir().resolve(defaultWorldPath).toFile();
cir.setReturnValue(this.modWorldDirectory);
}
}
}
}
|
package uk.ac.ebi.pride.cluster.ws.modules.psm.controller;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import uk.ac.ebi.pride.cluster.ws.modules.psm.model.PsmList;
import uk.ac.ebi.pride.cluster.ws.modules.psm.model.QualityAwarePsm;
import uk.ac.ebi.pride.cluster.ws.modules.psm.model.QualityAwarePsmList;
import uk.ac.ebi.pride.cluster.ws.modules.psm.util.RepoPsmToWsPsmMapper;
import uk.ac.ebi.pride.spectracluster.repo.dao.cluster.IClusterReadDao;
import uk.ac.ebi.pride.spectracluster.repo.model.ClusterSummary;
import uk.ac.ebi.pride.spectracluster.repo.model.ClusteredPSMDetail;
import java.util.List;
/**
* @author Jose A. Dianes <jdianes@ebi.ac.uk>
*
*/
@Api(value = "psm", description = "retrieve summarised information about PSMs", position = 0)
@Controller
@RequestMapping(value = "/psm")
public class PsmController {
private static final Logger logger = LoggerFactory.getLogger(PsmController.class);
@Autowired
IClusterReadDao clusterReaderDao;
@ApiOperation(value = "returns PSMs for a given Cluster ID", position = 1, notes = "retrieve PSMs for a given Cluster ID")
@RequestMapping(value = "/list/{clusterId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(HttpStatus.OK) // 200
public
@ResponseBody
PsmList getClusterPsms(
@ApiParam(value = "a cluster ID")
@PathVariable("clusterId") long clusterId) {
logger.info("Cluster " + clusterId + " PSMs requested");
List<ClusteredPSMDetail> clusteredPSMDetails = clusterReaderDao.findClusteredPSMSummaryByClusterId(clusterId);
return RepoPsmToWsPsmMapper.asPsmList(clusteredPSMDetails);
}
@ApiOperation(value = "returns the quality of a PSM for a given PRIDE Archive PSM ID", position = 2,
notes = "retrieve PSM with cluster quality annotations")
@RequestMapping(value = "/archive/{archivePsmId:.+}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(HttpStatus.OK) // 200
public
@ResponseBody
QualityAwarePsmList getQualityAwarePsms(
@ApiParam(value = "a PRIDE Archive PSM ID")
@PathVariable("archivePsmId") String archivePsmId) {
logger.info("PRIDE Archive PSM " + archivePsmId + " requested");
QualityAwarePsmList qualityAwarePsmList = new QualityAwarePsmList();
List<ClusteredPSMDetail> clusteredPSMSummaries = clusterReaderDao.findClusteredPSMSummaryByArchiveId(archivePsmId);
if (!clusteredPSMSummaries.isEmpty()) {
for (ClusteredPSMDetail clusteredPSMSummary : clusteredPSMSummaries) {
// get cluster summary first
Long clusterId = clusteredPSMSummary.getClusterId();
ClusterSummary clusterSummary = clusterReaderDao.findClusterSummary(clusterId);
// construct quality aware psm
QualityAwarePsm qualityAwarePsm = RepoPsmToWsPsmMapper.asQualityAwarePsm(clusteredPSMSummary, clusterSummary);
qualityAwarePsmList.addQualityAwarePsm(qualityAwarePsm);
}
}
return qualityAwarePsmList;
}
}
|
package sgdk.rescomp;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import sgdk.rescomp.processor.AlignProcessor;
import sgdk.rescomp.processor.BinProcessor;
import sgdk.rescomp.processor.BitmapProcessor;
import sgdk.rescomp.processor.GroupProcessor;
import sgdk.rescomp.processor.ImageProcessor;
import sgdk.rescomp.processor.PaletteProcessor;
import sgdk.rescomp.processor.SpriteProcessor;
import sgdk.rescomp.processor.TilemapProcessor;
import sgdk.rescomp.processor.TilesetProcessor;
import sgdk.rescomp.processor.WavProcessor;
import sgdk.rescomp.processor.XgmProcessor;
import sgdk.rescomp.resource.Align;
import sgdk.rescomp.resource.Bin;
import sgdk.rescomp.resource.Bitmap;
import sgdk.rescomp.resource.Group;
import sgdk.rescomp.resource.Image;
import sgdk.rescomp.resource.Palette;
import sgdk.rescomp.resource.Sprite;
import sgdk.rescomp.resource.Tilemap;
import sgdk.rescomp.resource.Tileset;
import sgdk.rescomp.resource.internal.Collision;
import sgdk.rescomp.resource.internal.SpriteAnimation;
import sgdk.rescomp.resource.internal.SpriteFrame;
import sgdk.rescomp.resource.internal.SpriteFrameInfo;
import sgdk.rescomp.resource.internal.VDPSprite;
import sgdk.rescomp.type.Basics.Compression;
import sgdk.tool.FileUtil;
import sgdk.tool.StringUtil;
public class Compiler
{
// private final static String REGEX_LETTERS = "[a-zA-Z]";
// private final static String REGEX_ID = "\\b([A-Za-z][A-Za-z0-9_]*)\\b";
private final static List<Processor> resourceProcessors = new ArrayList<>();
static
{
// function processors
resourceProcessors.add(new AlignProcessor());
resourceProcessors.add(new GroupProcessor());
// resource processors
resourceProcessors.add(new BinProcessor());
resourceProcessors.add(new PaletteProcessor());
resourceProcessors.add(new BitmapProcessor());
resourceProcessors.add(new TilesetProcessor());
resourceProcessors.add(new TilemapProcessor());
resourceProcessors.add(new ImageProcessor());
resourceProcessors.add(new SpriteProcessor());
resourceProcessors.add(new WavProcessor());
resourceProcessors.add(new XgmProcessor());
}
// shared directory informations
public static String currentDir;
public static String resDir;
// map storing all resources (same object for key and value as we want fast 'contains' check)
public static Map<Resource, Resource> resources = new HashMap<>();
// list to preserve order
public static List<Resource> resourcesList = new ArrayList<>();
public static boolean compile(String fileName, String fileNameOut, boolean header)
{
// get application directory
// currentDir = new File("").getAbsolutePath();
currentDir = FileUtil.getApplicationDirectory();
// get input file directory
resDir = FileUtil.getDirectory(fileName);
// reset resources lists
resources.clear();
resourcesList.clear();
List<String> lines = null;
try
{
// get all lines from resource file
lines = Files.readAllLines(Paths.get(fileName), Charset.defaultCharset());
}
catch (IOException e)
{
System.err.println("Couldn't open input file " + fileName + ":");
System.err.println(e.getMessage());
return false;
}
int lineCnt = 1;
int align = -1;
boolean group = false;
// process input resource file line by line
for (String l : lines)
{
// cleanup the text
final String line = l.trim().replaceAll("\t", " ").replaceAll(" +", " ");
// count line
lineCnt++;
// ignore empty line
if (StringUtil.isEmpty(line))
continue;
// ignore comment
if (line.startsWith("//") || line.startsWith("
continue;
// execute and get resource
final Resource resource = execute(line);
// can't get resource ? --> error happened, stop here..
if (resource == null)
{
System.err.println(fileName + ": error on line " + lineCnt);
return false;
}
// ALIGN function (not a real resource so handle it specifically)
if (resource instanceof Align)
align = ((Align) resource).align;
// GROUP function (not a real resource so handle it specifically)
else if (resource instanceof Group)
// group resource export by type
group = true;
// just store resource
else
addResource(resource);
}
// define output files
final StringBuilder outS = new StringBuilder(1024);
final StringBuilder outH = new StringBuilder(1024);
try
{
final ByteArrayOutputStream outB = new ByteArrayOutputStream();
// build header name from resource parent folder name
String headerName = FileUtil.getFileName(FileUtil.getDirectory(resDir, false), false);
if (StringUtil.isEmpty(headerName))
headerName = "RES";
headerName += "_" + FileUtil.getFileName(fileNameOut, false);
headerName = headerName.toUpperCase();
outH.append("#ifndef _" + headerName + "_H_\n");
outH.append("#define _" + headerName + "_H_\n\n");
// -- BINARY SECTION --
// get BIN resources
final List<Resource> binResources = getResources(Bin.class);
final List<Resource> binResourcesOfPalette = getBinResourcesOf(Palette.class);
final List<Resource> binResourcesOfTilemap;
final List<Resource> binResourcesOfTileset;
final List<Resource> binResourcesOfBitmap;
// keep raw BIN resources only
binResources.removeAll(binResourcesOfPalette);
if (group)
{
// get BIN resources grouped by type for better compression
binResourcesOfTilemap = getBinResourcesOf(Tilemap.class);
binResourcesOfTileset = getBinResourcesOf(Tileset.class);
binResourcesOfBitmap = getBinResourcesOf(Bitmap.class);
// keep raw BIN resources only
binResources.removeAll(binResourcesOfTilemap);
binResources.removeAll(binResourcesOfTileset);
binResources.removeAll(binResourcesOfBitmap);
}
else
{
binResourcesOfTilemap = new ArrayList<>();
binResourcesOfTileset = new ArrayList<>();
binResourcesOfBitmap = new ArrayList<>();
}
// get "far" BIN resources (palette BIN data are never far)
final List<Resource> farBinResources = getFarBinResourcesOf(binResources);
final List<Resource> farBinResourcesOfTilemap;
final List<Resource> farBinResourcesOfTileset;
final List<Resource> farBinResourcesOfBitmap;
// keep "non far" BIN resources only
binResources.removeAll(farBinResources);
if (group)
{
// get "far" BIN resources grouped by type for better compression
farBinResourcesOfTilemap = getFarBinResourcesOf(binResourcesOfTilemap);
farBinResourcesOfTileset = getFarBinResourcesOf(binResourcesOfTileset);
farBinResourcesOfBitmap = getFarBinResourcesOf(binResourcesOfBitmap);
// keep "non far" BIN resources only
binResourcesOfTilemap.removeAll(farBinResourcesOfTilemap);
binResourcesOfTileset.removeAll(farBinResourcesOfTileset);
binResourcesOfBitmap.removeAll(farBinResourcesOfBitmap);
}
else
{
farBinResourcesOfTilemap = new ArrayList<>();
farBinResourcesOfTileset = new ArrayList<>();
farBinResourcesOfBitmap = new ArrayList<>();
}
// export binary data first !! very important !!
// otherwise metadata structures can't properly get BIN.doneCompression field value
// Read Only Data section
outS.append(".section .rodata\n\n");
// reset binary buffer
outB.reset();
// export simple and safe "metadata" resources which can be compressed (binary data without reference)
exportResources(getResources(VDPSprite.class), outB, outS, outH);
exportResources(getResources(Collision.class), outB, outS, outH);
// BIN Read Only Data section
outS.append(".section .rodata_bin\n\n");
// need to reset binary buffer
outB.reset();
// then export "not far" BIN resources by type for better compression
exportResources(binResourcesOfPalette, outB, outS, outH);
exportResources(binResources, outB, outS, outH);
exportResources(binResourcesOfTilemap, outB, outS, outH);
exportResources(binResourcesOfTileset, outB, outS, outH);
exportResources(binResourcesOfBitmap, outB, outS, outH);
// FAR BIN Read Only Data section
outS.append(".section .rodata_binf\n\n");
// need to reset binary buffer
outB.reset();
// do alignment for FAR BIN data
if (align != -1)
outS.append(" .align " + align + "\n\n");
// then export "far" BIN resources by type for better compression
exportResources(farBinResources, outB, outS, outH);
exportResources(farBinResourcesOfTilemap, outB, outS, outH);
exportResources(farBinResourcesOfTileset, outB, outS, outH);
exportResources(farBinResourcesOfBitmap, outB, outS, outH);
// Read Only Data section
outS.append(".section .rodata\n\n");
// need to reset binary buffer
outB.reset();
// and finally export "metadata" *after* binary data (no compression possible)
exportResources(getResources(Palette.class), outB, outS, outH);
exportResources(getResources(Tileset.class), outB, outS, outH);
exportResources(getResources(Tilemap.class), outB, outS, outH);
exportResources(getResources(SpriteFrameInfo.class), outB, outS, outH);
exportResources(getResources(SpriteFrame.class), outB, outS, outH);
exportResources(getResources(SpriteAnimation.class), outB, outS, outH);
exportResources(getResources(Sprite.class), outB, outS, outH);
exportResources(getResources(Image.class), outB, outS, outH);
exportResources(getResources(Bitmap.class), outB, outS, outH);
outH.append("\n");
outH.append("#endif // _" + headerName + "_H_\n");
int unpackedSize = 0;
int packedRawSize = 0;
int packedSize = 0;
// compute global BIN sizes
for (Resource res : getResources(Bin.class))
{
final Bin bin = (Bin) res;
// compressed ?
if (bin.doneCompression != Compression.NONE)
{
packedRawSize += bin.data.length + (bin.data.length & 1);
packedSize += bin.packedData.data.length + (bin.packedData.data.length & 1);
}
else
unpackedSize += bin.data.length + (bin.data.length & 1);
}
System.out.println(fileName + " summary:");
System.out.println("
System.out.println("Binary data: " + (unpackedSize + packedSize) + " bytes");
if (unpackedSize > 0)
System.out.println(" Unpacked: " + unpackedSize + " bytes");
if (packedSize > 0)
System.out.println(
" Packed: " + packedSize + " bytes (" + Math.round((packedSize * 100f) / packedRawSize)
+ "% - origin size: " + packedRawSize + " bytes)");
int spriteMetaSize = 0;
int miscMetaSize = 0;
// has sprites ?
if (!getResources(Sprite.class).isEmpty())
{
// compute SPRITE structures size
for (Resource res : getResources(VDPSprite.class))
spriteMetaSize += res.shallowSize();
for (Resource res : getResources(Collision.class))
spriteMetaSize += res.shallowSize();
for (Resource res : getResources(SpriteFrameInfo.class))
spriteMetaSize += res.shallowSize();
for (Resource res : getResources(SpriteFrame.class))
spriteMetaSize += res.shallowSize();
for (Resource res : getResources(SpriteAnimation.class))
spriteMetaSize += res.shallowSize();
for (Resource res : getResources(Sprite.class))
spriteMetaSize += res.shallowSize();
System.out.println("Sprite metadata (all but tiles and palette data): " + spriteMetaSize + " bytes");
}
// compute misc structures size
for (Resource res : getResources(Bitmap.class))
miscMetaSize += res.shallowSize();
for (Resource res : getResources(Image.class))
miscMetaSize += res.shallowSize();
for (Resource res : getResources(Tilemap.class))
miscMetaSize += res.shallowSize();
for (Resource res : getResources(Tileset.class))
miscMetaSize += res.shallowSize();
for (Resource res : getResources(Palette.class))
miscMetaSize += res.shallowSize();
if (miscMetaSize > 0)
System.out.println(
"Misc metadata (bitmap, image, tilemap, tileset, palette..): " + miscMetaSize + " bytes");
final int totalSize = unpackedSize + packedSize + spriteMetaSize + miscMetaSize;
System.out.println("Total: " + totalSize + " bytes (" + (totalSize / 1024) + " KB)");
}
catch (Throwable t)
{
System.err.println(t.getMessage());
t.printStackTrace();
return false;
}
BufferedWriter out;
try
{
// save .s file
out = new BufferedWriter(new FileWriter(FileUtil.setExtension(fileNameOut, ".s")));
out.write(outS.toString());
out.close();
// save .h file
out = new BufferedWriter(new FileWriter(FileUtil.setExtension(fileNameOut, ".h")));
out.write(outH.toString());
out.close();
}
catch (IOException e)
{
System.err.println("Couldn't create output file:");
System.err.println(e.getMessage());
return false;
}
// remove unwanted header file if asked
if (!header)
FileUtil.delete(FileUtil.setExtension(fileNameOut, ".h"), false);
return true;
}
private static List<Resource> getFarBinResourcesOf(List<Resource> resourceList)
{
final List<Resource> result = new ArrayList<>();
for (Resource resource : resourceList)
if (resource instanceof Bin)
if (((Bin) resource).far)
result.add(resource);
return result;
}
private static List<Resource> getBinResourcesOf(Class<? extends Resource> resourceType)
{
final List<Resource> result = new ArrayList<>();
final List<Resource> typeResources = getResources(resourceType);
if (resourceType.equals(Palette.class))
{
for (Resource resource : typeResources)
if (!result.contains(resource))
result.add(((Palette) resource).bin);
}
else if (resourceType.equals(Bitmap.class))
{
for (Resource resource : typeResources)
if (!result.contains(resource))
result.add(((Bitmap) resource).bin);
}
else if (resourceType.equals(Tileset.class))
{
for (Resource resource : typeResources)
if (!result.contains(resource))
result.add(((Tileset) resource).bin);
}
else if (resourceType.equals(Tilemap.class))
{
for (Resource resource : typeResources)
if (!result.contains(resource))
result.add(((Tilemap) resource).bin);
}
else
throw new IllegalArgumentException(
"getBinResourcesOf(..) error: " + resourceType.getName() + " class type not expected !");
return result;
}
private static List<Resource> getResources(Class<? extends Resource> resourceType)
{
final List<Resource> result = new ArrayList<>();
for (Resource resource : resourcesList)
if (resourceType.isInstance(resource))
result.add(resource);
return result;
}
private static void exportResources(Collection<Resource> resourceCollection, ByteArrayOutputStream outB,
StringBuilder outS, StringBuilder outH) throws IOException
{
for (Resource res : resourceCollection)
exportResource(res, outB, outS, outH);
}
private static void exportResource(Resource resource, ByteArrayOutputStream outB, StringBuilder outS,
StringBuilder outH) throws IOException
{
resource.out(outB, outS, outH);
}
public static Resource addResource(Resource resource, boolean internal)
{
// internal resource ?
if (internal)
{
// mark as not global
resource.global = false;
// check if we already have this resource
final Resource result = resources.get(resource);
// return it if already exists
if (result != null)
{
// System.out.println("Duplicated resource found: " + resource.id + " = " + result.id);
return result;
}
}
// add resource
resources.put(resource, resource);
resourcesList.add(resource);
return resource;
}
public static Resource addResource(Resource resource)
{
return addResource(resource, false);
}
private static Resource execute(String input)
{
try
{
// regex pattern to properly separate quoted string
final String pattern = " +(?=(([^\"]*\"){2})*[^\"]*$)";
// split on space character and preserve quoted parts
final String[] fields = input.split(pattern);
// remove quotes
for (int f = 0; f < fields.length; f++)
fields[f] = fields[f].replaceAll("\"", "");
// get resource type
final String type = fields[0];
// get resource processor for this type
final Processor processor = getResourceProcessor(type);
// can't find matching processor ? --> invalid resource type
if (processor == null)
{
System.err.println("Error: unknown resource type '" + type + "'");
System.out.println("Accepted resource types are:");
for (Processor rp : resourceProcessors)
System.out.println(" " + rp.getId());
return null;
}
System.out.println();
System.out.println("Resource: " + input);
System.out.println("--> executing plugin " + type + "...");
return processor.execute(fields);
}
catch (IOException e)
{
System.err.println(e.getMessage());
System.err.println("Error: cannot compile resource '" + input + "'");
e.printStackTrace();
return null;
}
catch (IllegalArgumentException e)
{
System.err.println(e.getMessage());
System.err.println("Error: cannot compile resource '" + input + "'");
e.printStackTrace();
return null;
}
}
private static Processor getResourceProcessor(String resourceType)
{
for (Processor rp : resourceProcessors)
if (resourceType.equalsIgnoreCase(rp.getId()))
return rp;
return null;
}
}
|
package sgdk.rescomp.type;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import sgdk.rescomp.resource.Tileset;
import sgdk.rescomp.type.Basics.Compression;
import sgdk.rescomp.type.TSX.TSXTileset;
import sgdk.tool.StringUtil;
import sgdk.tool.XMLUtil;
public class TMX
{
static final String ID_MAP = "map";
static final String ID_TILESET = "tileset";
static final String ID_LAYER = "layer";
static final String ID_DATA = "data";
static final String ID_OBJECTGROUP = "objectgroup";
static final String ID_OBJECT = "object";
static final String ID_TEXT = "text";
static final String ATTR_ID = "id";
static final String ATTR_NAME = "name";
static final String ATTR_VERSION = "version";
static final String ATTR_TILEDVERSION = "tiledversion";
static final String ATTR_ORIENTATION = "orientation";
static final String ATTR_RENDERORDER = "renderorder";
static final String ATTR_WIDTH = "width";
static final String ATTR_HEIGHT = "height";
static final String ATTR_TILEWIDTH = "tilewidth";
static final String ATTR_TILEHEIGHT = "tileheight";
static final String ATTR_INFINITE = "infinite";
static final String ATTR_SOURCE = "source";
static final String ATTR_FIRSTGID = "firstgid";
static final String ATTR_ENCODING = "encoding";
static final String ATTR_VISIBLE = "visible";
static final String ATTR_TYPE = "type";
static final String ATTR_X = "x";
static final String ATTR_Y = "y";
static final String ATTR_VALUE_ORTHOGONAL = "orthogonal";
static final String ATTR_VALUE_RIGHT_DOWN = "right-down";
static final String ATTR_VALUE_CSV = "csv";
static final String ATTR_VALUE_TEXT = "text";
static final String SUFFIX_PRIORITY = " priority";
static final String SUFFIX_LOW_PRIORITY = " low";
static final String SUFFIX_HIGH_PRIORITY = " high";
static final int TMX_HFLIP = (1 << 31);
static final int TMX_VFLIP = (1 << 30);
static final int TMX_AXE_FLIP = (1 << 29);
// <map version="1.8" tiledversion="1.8.4" orientation="orthogonal" renderorder="right-down" width="40" height="14"
// tilewidth="16" tileheight="16" infinite="0" backgroundcolor="#e00080" nextlayerid="15" nextobjectid="6">
// <tileset firstgid="1" source="../tsx/Forest.tsx"/>
// <tileset firstgid="392" source="../tsx/Bathing_Spot.tsx"/>
// <layer id="1" name="B Background" width="40" height="14">
// <data encoding="csv">
// 715,715,715,715,715,715,715,604,604,604,604,604,715,715,715,604,604,604,744,124,125,126,2147483774,2147483773,2147483774,125,126,126,2147483774,2147483773,2147483772,124,125,126,2147483774,2147483773,2147483772,124,125,126
// </data>
// </layer>
// <objectgroup id="7" name="_DEV_Comments" visible="0" locked="1">
// <object id="4" name="Beast" type="Text" x="239.333" y="-172.167" width="147" height="30">
// <text wrap="1">Beasts</text>
// </object>
// </objectgroup>
public static class TMXMap
{
public final String file;
public final String layerName;
public final int tileSize;
public final int w;
public final int h;
public final List<TSXTileset> tsxTilesets;
public final List<TSXTileset> usedTilesets;
public final int[] map;
public TMXMap(String file, String layerName) throws Exception
{
if (!FileUtil.exists(file))
throw new FileNotFoundException("TMX file '" + file + " not found !");
this.file = file;
this.layerName = layerName;
final Document doc = XMLUtil.loadDocument(file);
final Element mapElement = XMLUtil.getRootElement(doc);
// check this is the map node
if (!mapElement.getNodeName().toLowerCase().equals(ID_MAP))
throw new Exception("Expected " + ID_MAP + " root node in TMX file: " + file + ", " + mapElement.getNodeName() + " found.");
checkAttributValue(mapElement, ATTR_ORIENTATION, ATTR_VALUE_ORTHOGONAL, ATTR_VALUE_ORTHOGONAL, file);
checkAttributValue(mapElement, ATTR_RENDERORDER, ATTR_VALUE_RIGHT_DOWN, ATTR_VALUE_RIGHT_DOWN, file);
final int tw = XMLUtil.getAttributeIntValue(mapElement, ATTR_TILEWIDTH, 0);
final int th = XMLUtil.getAttributeIntValue(mapElement, ATTR_TILEHEIGHT, 0);
if (tw != th)
throw new Exception("Non square tile not supported (" + tw + " x " + th + ") in TMX file: " + file);
if ((tw & 7) != 0)
throw new Exception("Unsuported tile size (should be a multiple of 8) in TMX file: " + file);
if ((tw < 8) || (tw > 32))
throw new Exception(tw + " x " + th + " tile size not supported (only 8x8 to 32x32 allowed) in TMX file: " + file);
tileSize = tw;
w = XMLUtil.getAttributeIntValue(mapElement, ATTR_WIDTH, 0);
h = XMLUtil.getAttributeIntValue(mapElement, ATTR_HEIGHT, 0);
if ((w == 0) || (h == 0))
throw new Exception("Null map size in TMX file: " + file);
final List<Element> tilesetElements = XMLUtil.getElements(mapElement, ID_TILESET);
if (tilesetElements.isEmpty())
throw new Exception("No tileset reference(s) found in TMX file: " + file);
// add TSX tilesets
tsxTilesets = new ArrayList<>();
for (Element tilesetElement : tilesetElements)
{
// start ind with dummy blank tile correction
final int startId = XMLUtil.getAttributeIntValue(tilesetElement, ATTR_FIRSTGID, 0);
final String source = XMLUtil.getAttributeValue(tilesetElement, ATTR_SOURCE, "");
// has a source ? --> external TSX
if (!StringUtil.isEmpty(source))
// load from file
tsxTilesets.add(new TSXTileset(Util.getAdjustedPath(source, file), startId));
else
// directly load TSX from node
tsxTilesets.add(new TSXTileset(file, startId, tilesetElement));
}
for (TSXTileset tileset : tsxTilesets)
{
if (tileset.tileSize != tileSize)
throw new Exception("One of the referenced tileset has a different tile size than map tile size in TMX file: " + file);
}
// sort tilesets on startTileIndex
if (tsxTilesets.size() > 1)
Collections.sort(tsxTilesets);
final List<Element> layers = XMLUtil.getElements(mapElement, ID_LAYER);
if (layers.isEmpty())
throw new Exception("No layer found in TMX file: " + file);
final int[] mapData1;
final int[] mapData2;
// single layer definition ?
boolean singleLayer = hasLayer(layers, layerName);
if (singleLayer)
{
final Element mainLayer = getLayer(layers, layerName);
// try to get priority layer
final Element priorityLayer = getLayer(layers, layerName + SUFFIX_PRIORITY);
// get map data in mapData1
mapData1 = getMapData(mainLayer, w, h, file);
// get priority data in mapData2
mapData2 = (priorityLayer != null) ? getMapData(priorityLayer, w, h, file) : new int[mapData1.length];
}
else
{
// use alternate priority definition
final Element lowPriorityLayer = getLayer(layers, layerName + SUFFIX_LOW_PRIORITY);
final Element highPriorityLayer = getLayer(layers, layerName + SUFFIX_HIGH_PRIORITY);
if ((lowPriorityLayer == null) || (highPriorityLayer == null))
throw new Exception("No layer '" + layerName + "' found in TMX file: " + file);
// get low priority map data in mapData1
mapData1 = getMapData(lowPriorityLayer, w, h, file);
// get high priority map data in mapData2
mapData2 = getMapData(lowPriorityLayer, w, h, file);
}
final Set<TSXTileset> usedTilesetsSet = new HashSet<>();
map = new int[mapData1.length];
int ind = 0;
for (int y = 0; y < h; y++)
{
for (int x = 0; x < w; x++)
{
final int v;
final boolean prio;
// single layer for map data
if (singleLayer)
{
// get map data
v = mapData1[ind];
// get prio data
prio = mapData2[ind] != 0;
}
// 2 layers (low and high prio)
else
{
// data in high prio map ? --> use it
if (mapData2[ind] != 0)
{
v = mapData2[ind];
prio = true;
}
// use low prio map data
else
{
v = mapData1[ind];
prio = false;
}
}
// final boolean prio = prioData[ind] != 0;
final boolean hflip = (v & TMX_HFLIP) != 0;
boolean vflip = (v & TMX_VFLIP) != 0;
final boolean axeflip = (v & TMX_AXE_FLIP) != 0;
if (axeflip)
{
// TODO: re-enable warning for non DA game
System.out.println("WARNING: unsupported rotated tile found at [" + x + "," + y + "] in TMX file: " + file);
//vflip = true;
}
// we can guess that tile index is never higher than 2^24
final int tileInd = v & 0xFFFFFF;
// define used TSX tileset
if (tileInd != 0)
{
final TSXTileset tileset = getTSXTilesetFor(tileInd);
if (tileset == null)
throw new Exception(
"Tile [" + x + "," + y + "] is referencing an invalid index (" + tileInd + " is outside available tiles range)");
usedTilesetsSet.add(tileset);
}
// store attributes in upper word
map[ind++] = (Tile.TILE_ATTR_FULL(0, prio, vflip, hflip, 0) << 16) | tileInd;
}
}
// keep trace of tilesets which are really used
usedTilesets = new ArrayList<>(usedTilesetsSet);
// sort on startTileIndex
if (usedTilesets.size() > 1)
Collections.sort(usedTilesets);
// System.out.println("TMX map '" + file + "' is using " + usedTilesetsSet.size() + " tilesets:");
// for (TSXTileset tileset : usedTilesetsSet)
// System.out.println(tileset);
}
private TSXTileset getTSXTilesetFor(int tileInd)
{
for (TSXTileset tileset : tsxTilesets)
if (tileset.containsTile(tileInd))
return tileset;
return null;
}
public List<Tileset> getTilesets(String baseId, Compression compression, boolean temp) throws Exception
{
return TSX.getTilesets(usedTilesets, baseId, compression, temp);
}
// public Tilemap getTilemap(int mapBase) throws Exception
// final int ts = (tileSize / 8);
// final Tilemap result = new Tilemap(w * ts, h * ts);
// final short[] data = new short[result.w * result.h];
// final boolean mapBasePrio = (mapBase & Tile.TILE_PRIORITY_MASK) != 0;
// final int mapBasePal = (mapBase & Tile.TILE_PALETTE_MASK) >> Tile.TILE_PALETTE_SFT;
// final int mapBaseTileInd = mapBase & Tile.TILE_INDEX_MASK;
// // we have a base offset --> we can use system plain tiles
// final boolean useSystemTiles = mapBaseTileInd != 0;
// // need to have a blank tile
// if (!useSystemTiles)
// System.out.println("WARNING: you're using TMX map (file: " + file + ") with a null map base index.");
// System.out.println("See note in rescomp.txt about the required dummy blank tile in the tileset.");
// int ind = 0;
// for (int y = 0; y < h; y++)
// for (int x = 0; x < w; x++)
// final short tileValue = map[ind];
// final short tileAttr = (short) (tileValue & Tile.TILE_ATTR_MASK);
// final short tileInd = (short) (tileValue & Tile.TILE_INDEX_MASK);
// // transparent tile with base tile offset defined ?
// if ((tileInd == 0) && (mapBaseTileInd != 0))
// // convert to 8x8 tile index
// int tmInd = ind * ts * ts;
// // simply use tile 0 (transparent)
// for (int ty = 0; ty < ts; ty++)
// for (int tx = 0; tx < ts; tx++)
// data[tmInd] = tileAttr;
// tmInd++;
// tmInd += result.w - ts;
// else
// final TSXTileset tileset = getTSXTilesetFor(tileInd);
// if (tileset == null)
// throw new Exception("Cannot find tilset for tile #" + tileInd + " in TMX file: " + file);
// final int tileRelativeInd = (tileInd - tileset.startTileIndex);
// final int tileIndX = tileRelativeInd % tileset.imageTileWidth;
// final int tileIndY = tileRelativeInd / tileset.imageTileWidth;
// final int imageSingleTileWidth = tileset.imageTileWidth * (tileSize / 8);
// // convert to 8x8 tile index
// int tmInd = ind * ts * ts;
// int tmTileInd = (tileIndX * ts) + ((tileIndY * ts) * imageSingleTileWidth);
// if (tmTileInd >= 2048)
// throw new Exception("Can't have tile index >= 2048 in TMX file: " + file + ", try to reduce number of unique
// tile.");
// for (int ty = 0; ty < ts; ty++)
// for (int tx = 0; tx < ts; tx++)
// data[tmInd] = (short) Tile.TILE_ATTR_FULL(mapBasePal, mapBasePrio | ((tileAttr & Tile.TILE_PRIORITY_MASK) !=
// (tileAttr & Tile.TILE_VFLIP_MASK) != 0, (tileAttr & Tile.TILE_HFLIP_MASK) != 0,
// mapBaseTileInd + (tmTileInd & Tile.TILE_INDEX_MASK));
// tmInd++;
// tmTileInd++;
// tmInd += result.w - ts;
// tmTileInd += imageSingleTileWidth - ts;
// ind++;
// // set tilemap data
// result.setData(data);
// return result;
// public int getTilesetImageHeight()
// int totalTile = 0;
// for (TSXTileset tileset : usedTilesets)
// totalTile += tileset.numTile;
// final int tilePerRow = 256 / tileSize;
// // calculate image height for 256 pixels wide tileset image
// return ((totalTile + (tilePerRow - 1)) / tilePerRow) * tileSize;
// RAW tileset image (width = 256)
// final int wt = 256 / tileSize;
// final int ht = getTilesetImageHeight() / tileSize;
// if (ht == 0)
// return new byte[0];
// final byte[] fullTilesetImage = new byte[(wt * tileSize) * (ht * tileSize)];
// int tsInd = 0;
// TSXTileset tileset = usedTilesets.get(tsInd++);
// byte[] tilesetImage = tileset.getTilesetImage8bpp(false);
// int tilesetImageW = tileset.imageTileWidth * tileset.tileSize;
// int tilesetImageH = tileset.imageTileHeigt * tileset.tileSize;
// int tileInd = 0;
// int remaining = tileset.numTile;
// for (int yt = 0; yt < ht; yt++)
// for (int xt = 0; xt < wt; xt++)
// final byte[] imageTile = Tile.getImageTile(tilesetImage, tilesetImageW, tilesetImageH, tileInd++, tileSize);
// // copy tile
// Tile.copyTile(fullTilesetImage, 256, imageTile, xt * tileSize, yt * tileSize, tileSize);
// // tileset done ? --> next tileset
// if (--remaining == 0)
// // done --> can return image now
// if (tsInd >= usedTilesets.size())
// return fullTilesetImage;
// tileset = usedTilesets.get(tsInd++);
// tilesetImage = tileset.getTilesetImage8bpp(false);
// tilesetImageW = tileset.imageTileWidth * tileset.tileSize;
// tilesetImageH = (tileset.numTile / tileset.imageTileWidth) * tileset.tileSize;
// tileInd = 0;
// remaining = tileset.numTile;
// return fullTilesetImage;
public byte[] getMapImage() throws Exception
{
final int mapImageW = w * tileSize;
final int mapImageH = h * tileSize;
final byte[] mapImage = new byte[mapImageW * mapImageH];
// build tileset image map
final Map<TSXTileset, byte[]> tilesets = new HashMap<>();
for (TSXTileset tileset : usedTilesets)
tilesets.put(tileset, tileset.getTilesetImage8bpp(true));
// TODO: disable crop palette for DA game dev
// tilesets.put(tileset, tileset.getTilesetImage8bpp(false));
final byte[] baseTile = new byte[tileSize * tileSize];
final byte[] transformedTile = new byte[tileSize * tileSize];
int off = 0;
for (int yt = 0; yt < h; yt++)
{
for (int xt = 0; xt < w; xt++)
{
final int tile = map[off++];
final int tileInd = tile & 0xFFFFFF;
final short tileAttr = (short) ((tile >> 16) & 0xFFFF);
final boolean hflip = (tileAttr & Tile.TILE_HFLIP_MASK) != 0;
final boolean vflip = (tileAttr & Tile.TILE_VFLIP_MASK) != 0;
final boolean prio = (tileAttr & Tile.TILE_PRIORITY_MASK) != 0;
byte[] imageTile;
// special case of blank tile
if (tileInd == 0)
{
Arrays.fill(baseTile, (byte) 0);
imageTile = baseTile;
}
else
{
// find tileset for this tile
final TSXTileset tsxTileset = getTSXTilesetFor(tileInd);
// get tile
imageTile = Tile.getImageTile(tilesets.get(tsxTileset), tsxTileset.imageTileWidth * tileSize, tsxTileset.imageTileHeigt * tileSize,
tileInd - tsxTileset.startTileIndex, tileSize, baseTile);
// need to transform ?
if (hflip || vflip || prio)
imageTile = Tile.transformTile(imageTile, tileSize, hflip, vflip, prio, transformedTile);
}
// then copy tile
Tile.copyTile(mapImage, mapImageW, imageTile, xt * tileSize, yt * tileSize, tileSize);
}
}
return mapImage;
}
@Override
public String toString()
{
return "tileSize=" + tileSize + " - w=" + w + " - h=" + h;
}
}
static String getAttribute(Element element, String attrName, String def)
{
return XMLUtil.getAttributeValue(element, attrName, def).toLowerCase();
}
static Element getLayer(List<Element> layers, String name)
{
for (Element element : layers)
if (StringUtil.equals(getAttribute(element, ATTR_NAME, ""), name.toLowerCase()))
return element;
return null;
}
static boolean hasLayer(List<Element> layers, String name)
{
return getLayer(layers, name) != null;
}
static Element getElement(Node node, String name, String file) throws Exception
{
final Element result = XMLUtil.getElement(node, name);
if (result == null)
throw new Exception("Cannot find " + name + " XML node in TMX file: " + file);
return result;
}
static void checkAttributValue(Element element, String attrName, String value, String def, String file) throws Exception
{
final String attrValue = getAttribute(element, attrName, def);
if (!StringUtil.equals(attrValue, value))
throw new Exception("'" + attrValue + "' " + attrName + " not supported (" + def + " expected) in TMX file: " + file);
}
static int[] getMapData(Element layerElement, int w, int h, String file) throws Exception
{
if (XMLUtil.getAttributeIntValue(layerElement, ATTR_WIDTH, w) != w)
throw new Exception("Layer width do not match map width in TMX file: " + file);
if (XMLUtil.getAttributeIntValue(layerElement, ATTR_HEIGHT, h) != h)
throw new Exception("Layer height do not match map height in TMX file: " + file);
final Element dataElement = getElement(layerElement, ID_DATA, file);
checkAttributValue(dataElement, ATTR_ENCODING, ATTR_VALUE_CSV, "", file);
final String[] values = XMLUtil.getFirstValue(dataElement, "").split(",");
if (values.length != (w * h))
throw new Exception("Data size (" + values.length + ") does not match Layer dimension (" + w + " x " + h + ") in TMX file: " + file);
final int[] result = new int[values.length];
for (int i = 0; i < values.length; i++)
result[i] = (int) Long.parseLong(values[i].trim());
return result;
}
}
|
package drones.handlers.ardrone3;
import akka.util.ByteIterator;
import drones.messages.*;
import drones.models.ardrone3.CommandProcessor;
import drones.models.FlyingState;
import drones.models.ardrone3.Packet;
import drones.util.ardrone3.FrameHelper;
public class PilotingStateHandler extends CommandProcessor {
public PilotingStateHandler(){
super(ArDrone3TypeProcessor.ArDrone3Class.PILOTINGSTATE.getVal());
}
@Override
protected void initHandlers() {
//TODO: use annotations
addHandler((short)0, PilotingStateHandler::flatTrimChanged);
addHandler((short)1, PilotingStateHandler::flyingStateChanged);
addHandler((short)4, PilotingStateHandler::positionChanged);
addHandler((short)5, PilotingStateHandler::speedChanged);
addHandler((short)6, PilotingStateHandler::attitudeChanged);
addHandler((short)8, PilotingStateHandler::altitudeChanged);
}
private static Object flatTrimChanged(Packet p){
return new FlatTrimChangedMessage();
}
private static Object attitudeChanged(Packet p){
ByteIterator it = p.getData().iterator();
float roll = it.getFloat(FrameHelper.BYTE_ORDER);
float pitch = it.getFloat(FrameHelper.BYTE_ORDER);
float yaw = it.getFloat(FrameHelper.BYTE_ORDER);
return new AttitudeChangedMessage(roll, pitch, yaw);
}
private static Object speedChanged(Packet p){
ByteIterator it = p.getData().iterator();
float sx = it.getFloat(FrameHelper.BYTE_ORDER);
float sy = it.getFloat(FrameHelper.BYTE_ORDER);
float sz = it.getFloat(FrameHelper.BYTE_ORDER);
return new SpeedChangedMessage(sx, sy, sz);
}
private static FlyingState getFlyingState(int val){
switch(val){
case 0:
return FlyingState.LANDED;
case 1:
return FlyingState.TAKINGOFF;
case 2:
return FlyingState.HOVERING;
case 3:
return FlyingState.FLYING;
case 4:
return FlyingState.LANDING;
case 5:
return FlyingState.EMERGENCY;
default:
throw new IllegalArgumentException("val");
}
}
private static Object flyingStateChanged(Packet p){
ByteIterator it = p.getData().iterator();
int val = it.getInt(FrameHelper.BYTE_ORDER);
return new FlyingStateChangedMessage(getFlyingState(val));
}
private static Object altitudeChanged(Packet p){
ByteIterator it = p.getData().iterator();
double alt = it.getDouble(FrameHelper.BYTE_ORDER);
return new AltitudeChangedMessage(alt);
}
private static Object positionChanged(Packet p){
ByteIterator it = p.getData().iterator();
double lat = it.getDouble(FrameHelper.BYTE_ORDER);
double longit = it.getDouble(FrameHelper.BYTE_ORDER);
double alt = it.getDouble(FrameHelper.BYTE_ORDER);
if((int)lat == 500) //this uses the exact 500.0d constant, but Sonar mehh
lat = 0d;
if((int)longit == 500)
longit = 0d;
if((int)alt == 500)
alt = 0d;
return new LocationChangedMessage(longit, lat, alt);
}
}
|
package com.firebase.ui.auth.util;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.Result;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.android.gms.tasks.TaskCompletionSource;
import java.net.ConnectException;
import java.util.concurrent.atomic.AtomicInteger;
/**
* A {@link Task} based wrapper to get a connect {@link GoogleApiClient}.
*/
public abstract class GoogleApiHelper implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private static final AtomicInteger SAFE_ID = new AtomicInteger(10);
protected GoogleApiClient mClient;
private TaskCompletionSource<Bundle> mGoogleApiConnectionTask = new TaskCompletionSource<>();
protected GoogleApiHelper(FragmentActivity activity, GoogleApiClient.Builder builder) {
builder.enableAutoManage(activity, getSafeAutoManageId(), this);
builder.addConnectionCallbacks(this);
mClient = builder.build();
}
/**
* @return a safe id for {@link GoogleApiClient.Builder#enableAutoManage(FragmentActivity, int,
* GoogleApiClient.OnConnectionFailedListener)}
*/
public static int getSafeAutoManageId() {
return SAFE_ID.getAndIncrement();
}
public Task<Bundle> getConnectedApiTask() {
return mGoogleApiConnectionTask.getTask();
}
@Override
public void onConnected(@Nullable Bundle bundle) {
// onConnected might be called multiple times, but we don't want to unregister listeners
// because extenders might be relying on each onConnected call. Instead, we just ignore future
// calls to onConnected or onConnectionFailed by using a `trySomething` strategy.
mGoogleApiConnectionTask.trySetResult(bundle);
}
@Override
public void onConnectionSuspended(int i) {
// Just wait
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult result) {
mGoogleApiConnectionTask.trySetException(new ConnectException(result.toString()));
}
protected static final class TaskResultCaptor<R extends Result> implements ResultCallback<R> {
private TaskCompletionSource<R> mSource;
public TaskResultCaptor(TaskCompletionSource<R> source) {
mSource = source;
}
@Override
public void onResult(@NonNull R result) {
mSource.setResult(result);
}
}
protected static class ExceptionForwarder<TResult> implements OnCompleteListener<TResult> {
private TaskCompletionSource mSource;
private OnSuccessListener<TResult> mListener;
public ExceptionForwarder(TaskCompletionSource source,
OnSuccessListener<TResult> listener) {
mSource = source;
mListener = listener;
}
@Override
public void onComplete(@NonNull Task<TResult> task) {
if (task.isSuccessful()) {
mListener.onSuccess(task.getResult());
} else {
mSource.setException(task.getException());
}
}
}
}
|
package org.intermine.bio.web.export;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.biojava.bio.Annotation;
import org.biojava.bio.seq.io.FastaFormat;
import org.biojava.bio.seq.io.SeqIOTools;
import org.biojava.bio.symbol.IllegalSymbolException;
import org.intermine.api.results.ResultElement;
import org.intermine.bio.web.biojava.BioSequence;
import org.intermine.bio.web.biojava.BioSequenceFactory;
import org.intermine.model.InterMineObject;
import org.intermine.model.bio.BioEntity;
import org.intermine.model.bio.LocatedSequenceFeature;
import org.intermine.model.bio.Location;
import org.intermine.model.bio.Protein;
import org.intermine.model.bio.Sequence;
import org.intermine.objectstore.ObjectStore;
import org.intermine.util.IntPresentSet;
import org.intermine.util.StringUtil;
import org.intermine.web.logic.export.ExportException;
import org.intermine.web.logic.export.ExportHelper;
import org.intermine.web.logic.export.Exporter;
/**
* Export data in FASTA format. Select cell in each row that can be exported as
* a sequence and fetch associated sequence.
*
* @author Kim Rutherford
* @author Jakub Kulaviak
**/
public class SequenceExporter implements Exporter
{
private ObjectStore os;
private OutputStream out;
private int featureIndex;
private int writtenResultsCount = 0;
/**
* Constructor.
*
* @param os
* object store used for fetching sequence for exported object
* @param outputStream
* output stream
* @param featureIndex
* index of cell in row that contains object to be exported
*/
public SequenceExporter(ObjectStore os, OutputStream outputStream,
int featureIndex) {
this.os = os;
this.out = outputStream;
this.featureIndex = featureIndex;
}
/**
* {@inheritDoc}
*/
public int getWrittenResultsCount() {
return writtenResultsCount;
}
/**
* {@inheritDoc} Lines are always separated with \n because third party tool
* writeFasta is used for writing sequence.
*/
public void export(Iterator<? extends List<ResultElement>> resultIt) {
// IDs of the features we have successfully output - used to avoid
// duplicates
IntPresentSet exportedIDs = new IntPresentSet();
try {
while (resultIt.hasNext()) {
List<ResultElement> row = resultIt.next();
StringBuffer header = new StringBuffer();
ResultElement resultElement = row.get(featureIndex);
BioSequence bioSequence;
Object object = os.getObjectById(resultElement.getId());
if (!(object instanceof InterMineObject)) {
continue;
}
Integer objectId = ((InterMineObject) object).getId();
if (exportedIDs.contains(objectId)) {
// exported already
continue;
}
if (object instanceof LocatedSequenceFeature) {
bioSequence = createLocatedSequenceFeature(header, object,
row);
} else if (object instanceof Protein) {
bioSequence = createProtein(header, object, row);
} else {
// ignore other objects
continue;
}
if (bioSequence == null) {
// the object doesn't have a sequence
continue;
}
Annotation annotation = bioSequence.getAnnotation();
String headerString = header.toString();
if (headerString.length() > 0) {
annotation.setProperty(
FastaFormat.PROPERTY_DESCRIPTIONLINE, headerString);
} else {
if (object instanceof BioEntity) {
annotation.setProperty(
FastaFormat.PROPERTY_DESCRIPTIONLINE,
((BioEntity) object).getPrimaryIdentifier());
} else {
// last resort
annotation.setProperty(
FastaFormat.PROPERTY_DESCRIPTIONLINE,
"sequence_" + exportedIDs.size());
}
}
SeqIOTools.writeFasta(out, bioSequence);
writtenResultsCount++;
exportedIDs.add(objectId);
}
out.flush();
} catch (Exception e) {
throw new ExportException("Export failed.", e);
}
}
private BioSequence createProtein(StringBuffer header, Object object,
List<ResultElement> row) throws IllegalSymbolException {
BioSequence bioSequence;
Protein protein = (Protein) object;
bioSequence = BioSequenceFactory.make(protein);
String primaryIdentifier = protein.getPrimaryIdentifier();
makeHeader(header, primaryIdentifier, object, row);
return bioSequence;
}
private BioSequence createLocatedSequenceFeature(StringBuffer header,
Object object, List<ResultElement> row)
throws IllegalSymbolException {
BioSequence bioSequence;
LocatedSequenceFeature feature = (LocatedSequenceFeature) object;
bioSequence = BioSequenceFactory.make(feature);
String primaryIdentifier = feature.getPrimaryIdentifier();
makeHeader(header, primaryIdentifier, object, row);
return bioSequence;
}
/**
* Set the header to be the contents of row, separated by spaces.
*/
private void makeHeader(StringBuffer header, String primaryIdentifier,
Object object, List<ResultElement> row) {
List<String> headerBits = new ArrayList<String>();
// add the Object's (Protein or LocatedSequenceFeature)
// primaryIdentifier at the first place
// in the header
headerBits.add(primaryIdentifier);
// two instances
if (object instanceof LocatedSequenceFeature) {
// add the sequence location info at the second place in the header
LocatedSequenceFeature feature = (LocatedSequenceFeature) object;
String chr = feature.getChromosome().getPrimaryIdentifier();
Integer start = feature.getChromosomeLocation().getStart();
Integer end = feature.getChromosomeLocation().getEnd();
String locString = chr + ':' + start + '-' + end;
headerBits.add(locString);
for (ResultElement re : row) {
if (re.getObject().equals(object)) {
Object fieldValue = re.getField();
if (fieldValue == null) {
headerBits.add("-");
} else {
// ignore the primaryIdentifier and Location in
// ResultElement
if (fieldValue.toString().equals(primaryIdentifier)
|| (fieldValue instanceof Location)) {
continue;
} else {
headerBits.add(fieldValue.toString());
}
}
}
}
} else if (object instanceof Protein) {
for (ResultElement re : row) {
if (re.getObject().equals(object)) {
Object fieldValue = re.getField();
if (fieldValue == null) {
headerBits.add("-");
} else {
if (fieldValue.toString().equals(primaryIdentifier)) {
continue;
} else {
headerBits.add(fieldValue.toString());
}
}
}
}
}
header.append(StringUtil.join(headerBits, " "));
}
/**
* {@inheritDoc}
*/
public boolean canExport(List<Class> clazzes) {
return canExportStatic(clazzes);
}
/*
* Method must have different name than canExport because canExport() method
* is inherited from Exporter interface
*/
/**
* @param clazzes
* classes of result
* @return true if this exporter can export result composed of specified
* classes
*/
public static boolean canExportStatic(List<Class> clazzes) {
return (ExportHelper.getClassIndex(clazzes,
LocatedSequenceFeature.class) >= 0
|| ExportHelper.getClassIndex(clazzes, Protein.class) >= 0 || ExportHelper
.getClassIndex(clazzes, Sequence.class) >= 0);
}
}
|
package com.activeandroid;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import dalvik.system.DexFile;
class DatabaseHelper extends SQLiteOpenHelper {
private final static String AA_DB_NAME = "AA_DB_NAME";
private final static String AA_DB_VERSION = "AA_DB_VERSION";
private final static String MIGRATION_PATH = "migrations";
private Context mContext;
// PUBLIC METHODS
public DatabaseHelper(Context context) {
super(context, getDBName(context), null, getDBVersion(context));
mContext = context;
}
@Override
public void onCreate(SQLiteDatabase db) {
ArrayList<Class<? extends ActiveRecordBase<?>>> tables = getEntityClasses(mContext);
if (Params.LOGGING_ENABLED) {
Log.i(Params.LOGGING_TAG, "Creating " + tables.size() + " tables");
}
for (Class<? extends ActiveRecordBase<?>> table : tables) {
createTable(db, table);
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
onCreate(db);
executeMigrations(db, oldVersion, newVersion);
}
// PRIVATE METHODS
private void executeMigrations(SQLiteDatabase db, int oldVersion, int newVersion) {
try {
List<String> files = Arrays.asList(mContext.getAssets().list(MIGRATION_PATH));
Collections.sort(files, new NaturalOrderComparator());
for (String file : files) {
try {
int version = Integer.valueOf(file.replace(".sql", ""));
if (version > oldVersion && version <= newVersion) {
executeSqlScript(db, file);
}
}
catch (NumberFormatException e) {
Log.w(Params.LOGGING_TAG, "Skipping invalidly named file: " + file);
}
}
}
catch (IOException e) {
Log.e(Params.LOGGING_TAG, e.getMessage());
}
}
private void executeSqlScript(SQLiteDatabase db, String file) {
Log.d(Params.LOGGING_TAG, file);
db.execSQL(file);
}
private static void createTable(SQLiteDatabase db, Class<? extends ActiveRecordBase<?>> table) {
ArrayList<Field> fields = ReflectionUtils.getTableFields(table);
ArrayList<String> definitions = new ArrayList<String>();
for (Field field : fields) {
Class<?> fieldType = field.getType();
String fieldName = ReflectionUtils.getColumnName(field);
Integer fieldLength = ReflectionUtils.getColumnLength(field);
String definition = null;
if (ReflectionUtils.typeIsSQLiteFloat(fieldType)) {
definition = fieldName + " FLOAT";
}
else if (ReflectionUtils.typeIsSQLiteInteger(fieldType)) {
definition = fieldName + " INTEGER";
}
else if (ReflectionUtils.typeIsSQLiteString(fieldType)) {
definition = fieldName + " TEXT";
}
if (definition != null) {
if (fieldLength != null && fieldLength > 0) {
definition += "(" + fieldLength + ")";
}
if (fieldName.equals("Id")) {
definition += " PRIMARY KEY AUTOINCREMENT";
}
definitions.add(definition);
}
}
String sql = StringUtils.format("CREATE TABLE IF NOT EXISTS {0} ({1});", ReflectionUtils.getTableName(table),
StringUtils.join(definitions, ", "));
if (Params.LOGGING_ENABLED) {
Log.i(Params.LOGGING_TAG, sql);
}
db.execSQL(sql);
}
@SuppressWarnings("unchecked")
private static ArrayList<Class<? extends ActiveRecordBase<?>>> getEntityClasses(Context context) {
ArrayList<Class<? extends ActiveRecordBase<?>>> entityClasses = new ArrayList<Class<? extends ActiveRecordBase<?>>>();
try {
String path = context.getPackageManager().getApplicationInfo(context.getPackageName(), 0).sourceDir;
DexFile dexfile = new DexFile(path);
Enumeration<String> entries = dexfile.entries();
while (entries.hasMoreElements()) {
String name = entries.nextElement();
Class<?> discoveredClass = null;
Class<?> superClass = null;
try {
discoveredClass = Class.forName(name, true, context.getClass().getClassLoader());
superClass = discoveredClass.getSuperclass();
}
catch (ClassNotFoundException e) {
Log.e(Params.LOGGING_TAG, e.getMessage());
}
if (discoveredClass != null && superClass != null) {
if (discoveredClass.getSuperclass().equals(ActiveRecordBase.class)) {
entityClasses.add((Class<? extends ActiveRecordBase<?>>) discoveredClass);
}
}
}
}
catch (IOException e) {
Log.e(Params.LOGGING_TAG, e.getMessage());
}
catch (NameNotFoundException e) {
Log.e(Params.LOGGING_TAG, e.getMessage());
}
return entityClasses;
}
private static String getDBName(Context context) {
String aaName = getMetaDataString(context, AA_DB_NAME);
if (aaName == null) {
aaName = "Application.db";
}
return aaName;
}
private static int getDBVersion(Context context) {
Integer aaVersion = getMetaDataInteger(context, AA_DB_VERSION);
if (aaVersion == null || aaVersion == 0) {
aaVersion = 1;
}
return aaVersion;
}
private static String getMetaDataString(Context context, String name) {
String value = null;
PackageManager pm;
ApplicationInfo ai;
pm = context.getPackageManager();
try {
ai = pm.getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
value = ai.metaData.getString(name);
}
catch (Exception e) {
Log.w(Params.LOGGING_TAG, "Couldn't find meta data string: " + name);
}
return value;
}
private static Integer getMetaDataInteger(Context context, String name) {
Integer value = null;
PackageManager pm;
ApplicationInfo ai;
pm = context.getPackageManager();
try {
ai = pm.getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
value = ai.metaData.getInt(name);
}
catch (Exception e) {
Log.w(Params.LOGGING_TAG, "Couldn't find meta data string: " + name);
}
return value;
}
}
|
package com.dmdirc.updater;
import com.dmdirc.Main;
import com.dmdirc.Precondition;
import com.dmdirc.config.ConfigManager;
import com.dmdirc.config.IdentityManager;
import com.dmdirc.interfaces.UpdateListener;
import com.dmdirc.interfaces.UpdateCheckerListener;
import com.dmdirc.logger.ErrorLevel;
import com.dmdirc.logger.Logger;
import com.dmdirc.updater.Update.STATUS;
import com.dmdirc.updater.components.ClientComponent;
import com.dmdirc.updater.components.DefaultsComponent;
import com.dmdirc.updater.components.ModeAliasesComponent;
import com.dmdirc.util.Downloader;
import com.dmdirc.util.ListenerList;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Semaphore;
/**
* The update checker contacts the DMDirc website to check to see if there
* are any updates available.
*
* @author chris
*/
public final class UpdateChecker implements Runnable, UpdateListener {
/** The possible states for the checker. */
public static enum STATE {
/** Nothing's happening. */
IDLE,
/** Currently checking for updates. */
CHECKING,
/** New updates are available. */
UPDATES_AVAILABLE
}
/** Semaphore used to prevent multiple invocations. */
private static final Semaphore mutex = new Semaphore(1);
/** A list of components that we're to check. */
private static final List<UpdateComponent> components
= new ArrayList<UpdateComponent>();
/** Our timer. */
private static Timer timer = new Timer("Update Checker Timer");
/** The list of updates that are available. */
private static final List<Update> updates = new ArrayList<Update>();
/** A list of our listeners. */
private static final ListenerList listeners = new ListenerList();
/** Our current state. */
private static STATE status = STATE.IDLE;
static {
components.add(new ClientComponent());
components.add(new ModeAliasesComponent());
components.add(new DefaultsComponent());
}
/**
* Instantiates an Updatechecker.
*/
public UpdateChecker() {
//Ignore
}
/** {@inheritDoc} */
@Override
public void run() {
if (!mutex.tryAcquire()) {
// Duplicate invocation
return;
}
final ConfigManager config = IdentityManager.getGlobalConfig();
if (!config.getOptionBool("updater", "enable", true)) {
init();
return;
}
setStatus(STATE.CHECKING);
updates.clear();
final StringBuilder data = new StringBuilder();
final String updateChannel
= config.getOption("updater", "channel", Main.UPDATE_CHANNEL.toString());
for (UpdateComponent component : components) {
if (config.getOptionBool("updater", "enable-" + component.getName(), true)) {
data.append(component.getName());
data.append(',');
data.append(updateChannel);
data.append(',');
data.append(component.getVersion());
data.append(';');
}
}
if (data.length() > 0) {
try {
final List<String> response
= Downloader.getPage("http://updates.dmdirc.com/", "data=" + data);
updates.clear();
for (String line : response) {
checkLine(line);
}
} catch (MalformedURLException ex) {
Logger.appError(ErrorLevel.LOW, "Error when checking for updates", ex);
} catch (IOException ex) {
Logger.userError(ErrorLevel.LOW,
"I/O error when checking for updates: " + ex.getMessage());
}
}
if (updates.isEmpty()) {
setStatus(STATE.IDLE);
} else {
setStatus(STATE.UPDATES_AVAILABLE);
}
mutex.release();
UpdateChecker.init();
IdentityManager.getConfigIdentity().setOption("updater",
"lastcheck", String.valueOf((int) (new Date().getTime() / 1000)));
}
/**
* Checks the specified line to determine the message from the update server.
*
* @param line The line to be checked
*/
private void checkLine(final String line) {
if (line.startsWith("uptodate")) {
// Do nothing
} else if (line.startsWith("outofdate")) {
doUpdateAvailable(line);
} else if (line.startsWith("error")) {
Logger.userError(ErrorLevel.LOW, "Error when checking for updates: "
+ line.substring(6));
} else {
Logger.userError(ErrorLevel.LOW, "Unknown update line received from server: "
+ line);
}
}
/**
* Informs the user that there's an update available.
*
* @param line The line that was received from the update server
*/
public void doUpdateAvailable(final String line) {
final Update update = new Update(line);
updates.add(update);
update.addUpdateListener(this);
}
/** {@inheritDoc} */
@Override
public void updateStatusChange(final Update update, final STATUS status) {
if (status == Update.STATUS.INSTALLED
|| status == Update.STATUS.ERROR) {
removeUpdate(update);
}
}
/**
* Initialises the update checker. Sets a timer to check based on the
* frequency specified in the config.
*/
public static void init() {
final int last
= IdentityManager.getGlobalConfig().getOptionInt("updater", "lastcheck", 0);
final int freq
= IdentityManager.getGlobalConfig().getOptionInt("updater", "frequency", 86400);
final int timestamp = (int) (new Date().getTime() / 1000);
int time = 0;
if (last + freq > timestamp) {
time = last + freq - timestamp;
}
if (time > freq || time < 0) {
Logger.userError(ErrorLevel.LOW, "Attempted to schedule update check "
+ (time < 0 ? "in the past" : "too far in the future")
+ ", rescheduling.");
time = 1;
}
timer.cancel();
timer = new Timer("Update Checker Timer");
timer.schedule(new TimerTask() {
/** {@inheritDoc} */
@Override
public void run() {
checkNow();
}
}, time * 1000);
}
/**
* Checks for updates now.
*/
public static void checkNow() {
new Thread(new UpdateChecker(), "Update Checker thread").start();
}
/**
* Registers an update component.
*
* @param component The component to be registered
*/
public static void registerComponent(final UpdateComponent component) {
components.add(component);
}
/**
* Finds and returns the component with the specified name.
*
* @param name The name of the component that we're looking for
* @return The corresponding UpdateComponent, or null if it's not found
*/
@Precondition("The specified name is not null")
public static UpdateComponent findComponent(final String name) {
assert(name != null);
for (UpdateComponent component : components) {
if (name.equals(component.getName())) {
return component;
}
}
return null;
}
/**
* Removes the specified update from the list. This should be called when
* the update has finished or has encountered an error.
*
* @param update The update to be removed
*/
private static void removeUpdate(final Update update) {
updates.remove(update);
if (updates.isEmpty()) {
setStatus(STATE.IDLE);
}
}
/**
* Retrieves a list of components registered with the checker.
*
* @return A list of registered components
*/
public static List<UpdateComponent> getComponents() {
return components;
}
/**
* Retrives a list of available updates from the checker.
*
* @return A list of available updates
*/
public static List<Update> getAvailableUpdates() {
return updates;
}
/**
* Adds a new status listener to the update checker.
*
* @param listener The listener to be added
*/
public static void addListener(final UpdateCheckerListener listener) {
listeners.add(UpdateCheckerListener.class, listener);
}
/**
* Removes a status listener from the update checker.
*
* @param listener The listener to be removed
*/
public static void removeListener(final UpdateCheckerListener listener) {
listeners.remove(UpdateCheckerListener.class, listener);
}
/**
* Retrieves the current status of the update checker.
*
* @return The update checker's current status
*/
public static STATE getStatus() {
return status;
}
/**
* Sets the status of the update checker to the specified new status.
*
* @param newStatus The new status of this checker
*/
private static void setStatus(final STATE newStatus) {
status = newStatus;
for (UpdateCheckerListener listener : listeners.get(UpdateCheckerListener.class)) {
listener.statusChanged(newStatus);
}
}
/**
* Checks is a specified component is enabled.
*
* @param component Update component to check state
*
* @return true iif the update component is enabled
*/
public static boolean isEnabled(final UpdateComponent component) {
return IdentityManager.getGlobalConfig().getOptionBool("updater",
component.getName(), true);
}
}
|
package com.ecyrd.jspwiki.rpc;
/**
* A base class for managing RPC calls.
*
* @author jalkanen
* @since 2.5.4
*/
public class RPCManager
{
/**
* Gets an unique RPC ID for a callable object. This is required because a plugin
* does not know how many times it is already been invoked.
* <p>
* The id returned contains only upper and lower ASCII characters and digits, and
* it always starts with an ASCII character. Therefore the id is suitable as a
* programming language construct directly (e.g. object name).
*
* @param c An RPCCallable
* @return An unique id for the callable.
*/
public static String getId( RPCCallable c )
{
return "RPC"+c.hashCode();
}
}
|
/* Eddy: Grab and process the current line
*
* This class contains the logic for extracting the line around the current
* cursor, feeding it to the eddy engine as a token stream, and collecting
* the results as they come in lazily.
*/
package com.eddysystems.eddy.engine;
import com.eddysystems.eddy.EddyPlugin;
import com.eddysystems.eddy.PreferenceData;
import com.eddysystems.eddy.Preferences;
import com.intellij.lang.ASTNode;
import com.intellij.notification.Notification;
import com.intellij.notification.NotificationType;
import com.intellij.notification.Notifications;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.Result;
import com.intellij.openapi.application.RuntimeInterruptedException;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.RangeMarker;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.CodeStyleManager;
import com.intellij.psi.impl.source.tree.*;
import com.intellij.util.SmartList;
import com.siyeh.ipp.base.PsiElementPredicate;
import com.siyeh.ipp.fqnames.ReplaceFullyQualifiedNameWithImportIntention;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import scala.Function2;
import scala.Unit$;
import scala.runtime.AbstractFunction1;
import scala.runtime.AbstractFunction2;
import scala.runtime.BoxedUnit;
import scala.util.Try;
import tarski.Environment.Env;
import tarski.JavaScores;
import tarski.Memory;
import tarski.Scores.Alt;
import tarski.Tarski;
import tarski.Tarski.ShowStmts;
import tarski.Tokens.*;
import utility.Locations.Loc;
import utility.Utility.Unchecked;
import java.util.ArrayList;
import java.util.List;
import static com.eddysystems.eddy.engine.Utility.log;
import static com.eddysystems.eddy.engine.Utility.logError;
import static tarski.JavaScores.ppretty;
import static tarski.Tokens.*;
import static utility.JavaUtils.isDebug;
import static utility.JavaUtils.safeEquals;
import static utility.Utility.unchecked;
public class Eddy {
final private Project project;
final private Memory.Info base;
final private Editor editor;
final private Document document;
public Editor getEditor() { return editor; }
public PsiFile getFile() {
final PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(document);
assert file != null;
return file;
}
public static class Input {
final TextRange range;
final int line;
final List<Loc<Token>> input;
final PsiElement place;
final String before_text;
final boolean atEOL;
Input(final TextRange range, final int line, final List<Loc<Token>> input, final PsiElement place, final String before_text, final boolean atEOL) {
this.range = range;
this.line = line;
this.input = input;
this.place = place;
this.before_text = before_text;
this.atEOL = atEOL;
}
public boolean isAtEOL() { return atEOL; }
public int getLine() { return line; }
public String getText() {
return before_text;
}
public List<Loc<Token>> getInputTokens() { return input; }
}
// The results of the interpretation
public static class Output {
final private Eddy eddy;
final public Input input;
final public List<Alt<ShowStmts>> results;
// Mutable field: which output we've selected. If we haven't explicitly selected something, offset < 0.
private int selected = -1;
Output(final Eddy eddy, final Input input, final List<Alt<ShowStmts>> results) {
this.eddy = eddy;
this.input = input;
this.results = results;
}
@Override public boolean equals(final Object o_) {
if (!(o_ instanceof Output))
return false;
final Output o = (Output) o_;
return eddy==o.eddy && input==o.input && safeEquals(results,o.results);
}
public boolean skipped() {
return results == null;
}
static String format(final ShowStmts ss, final ShowFlags f) {
return f.den() ? ss.den() : f.abbreviate() ? ss.abbrev() : ss.full();
}
public String format(final int i, final ShowFlags f) {
return format(results.get(i).x(),f);
}
public List<String> formats(final ShowFlags f, final boolean probs) {
final List<String> fs = new ArrayList<String>(results.size());
for (final Alt<ShowStmts> a : results)
fs.add(format(a.x(),f));
if (probs) {
for (int i = 0; i < fs.size(); ++i) {
fs.set(i, String.format("%f: %s", results.get(i).p(), fs.get(i)));
}
}
return fs;
}
public String[] getResultSummary() {
return formats(new ShowFlags(false,true,true), true).toArray(new String[results.size()]);
}
public boolean foundSomething() {
return !skipped() && !results.isEmpty();
}
// Did we find useful meanings, and are those meanings different from what's already there?
public boolean shouldShowHint() {
if (!foundSomething())
return false;
for (final Alt<ShowStmts> r : results)
if (r.x().similar(input.input))
return false; // We found what's already there
return !results.isEmpty();
}
// Is there only one realistic option (or did the user explicitly select one)?
public boolean single() {
return results.size() == 1 || selected >= 0;
}
public boolean nextBestResult() {
if (shouldShowHint() && results.size()>1) {
selected = (Math.max(0,selected)+1)%results.size();
return true;
}
return false;
}
public boolean prevBestResult() {
if (shouldShowHint() && results.size()>1) {
selected = (Math.max(0,selected)+results.size()-1)%results.size();
return true;
}
return false;
}
public String bestTextAbbrev() {
assert shouldShowHint();
return format(Math.max(0,selected),abbrevShowFlags());
}
public void applySelected() {
apply(Math.max(0,selected));
}
public int autoApply() {
// Automatically apply the best found result
String code = format(0, fullShowFlags());
int offset = rawApply(eddy.document, code);
Memory.log(Memory.eddyAutoApply(eddy.base, Preferences.noCodeLog(), Memory.now(), input.line, input.input, results, code), Preferences.noLog(), Utility.onError);
return offset;
}
public boolean isConfident() {
// check if we're confident enough to apply the best found result automatically
PreferenceData data = Preferences.getData();
double t = data.getNumericAutoApplyThreshold();
double f = data.getNumericAutoApplyFactor();
if (results.size() >= 1 && results.get(0).p() >= t) {
if (results.size() == 1)
return true;
else
return results.get(0).p()/results.get(1).p() > f;
}
return false;
}
public boolean shouldAutoApply() {
if (!Preferences.getData().isAutoApply())
return false;
return isConfident() && input.isAtEOL();
}
private void removeQualifiers(final @NotNull Document document, final RangeMarker rm) {
// commit
PsiDocumentManager.getInstance(eddy.project).commitDocument(eddy.document);
// find common parent of everything that was inserted
PsiFile file = PsiDocumentManager.getInstance(eddy.project).getPsiFile(eddy.document);
if (file != null) {
PsiElement elem = file.findElementAt(rm.getStartOffset());
final TextRange tr = new TextRange(rm.getStartOffset(), rm.getEndOffset());
while (elem != null && !elem.getTextRange().contains(tr))
elem = elem.getParent();
if (elem != null) {
final ReplaceFullyQualifiedNameWithImportIntention intention = new ReplaceFullyQualifiedNameWithImportIntention();
final PsiElementPredicate pr = intention.getElementPredicate();
// traverse all elements in common parent that overlap the range marker
elem.accept(new JavaRecursiveElementWalkingVisitor() {
@Override
public void visitReferenceElement(PsiJavaCodeReferenceElement reference) {
if (!reference.getTextRange().intersects(tr))
return;
super.visitReferenceElement(reference);
if (pr.satisfiedBy(reference))
// TODO: inline without highlighting
intention.processIntention(reference);
}
});
}
}
}
public int rawApply(final @NotNull Document document, final @NotNull String code) {
document.replaceString(input.range.getStartOffset(), input.range.getEndOffset(), code);
final int afterOffset = input.range.getStartOffset() + code.length();
// remember offset
RangeMarker rm = document.createRangeMarker(input.range.getStartOffset(), afterOffset);
// get rid of qualifiers if imports would do instead
removeQualifiers(document, rm);
// reindent
CodeStyleManager csm = CodeStyleManager.getInstance(eddy.project);
PsiDocumentManager mgr = PsiDocumentManager.getInstance(eddy.project);
final int sline = document.getLineNumber(input.range.getStartOffset());
final int fline = document.getLineNumber(afterOffset);
for (int i = sline; i <= fline; ++i) {
mgr.doPostponedOperationsAndUnblockDocument(document);
csm.adjustLineIndent(document, document.getLineStartOffset(i));
}
PsiDocumentManager.getInstance(eddy.project).commitDocument(eddy.document);
return rm.getEndOffset();
}
public void apply(final int index) {
final String full = format(index,fullShowFlags());
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
final Editor editor = eddy.editor;
new WriteCommandAction(eddy.project, eddy.getFile()) {
@Override
public void run(@NotNull Result result) {
int offset = rawApply(eddy.document, full);
editor.getCaretModel().moveToOffset(offset);
}
}.execute();
}
});
Memory.log(Memory.eddyApply(eddy.base, Preferences.noCodeLog(), Memory.now(),input.line,input.input,results,index), Preferences.noLog(), Utility.onError);
}
public static void logSuggestion(final @NotNull Project project, final @Nullable Output output, final @NotNull String suggestion) {
Memory.Info base = output != null ? output.eddy.base : EddyPlugin.basics(project);
int line = output != null ? output.input.line : -1;
List<Loc<Token>> input = output != null ? output.input.input : null;
List<Alt<ShowStmts>> results = output != null ? output.results : null;
Memory.log(Memory.eddySuggestion(base, false, Memory.now(), line, input, results, suggestion), false, Utility.onError).onComplete(new AbstractFunction1<Try<BoxedUnit>, Void>() {
@Override
public Void apply(Try<BoxedUnit> v) {
final String title, msg;
if (v.isSuccess()) {
title = "Suggestion processed";
msg = "Thank you! Your suggestion will help improve eddy!";
} else {
title = "Suggestion failed to send";
msg = "I'm sorry, your suggestion could not be recorded. Our servers could not be reached.";
}
Notifications.Bus.notify(new Notification("Eddy", title, msg, NotificationType.INFORMATION), project);
return null;
}
}, scala.concurrent.ExecutionContext.Implicits$.MODULE$.global());
}
}
public interface Take {
// Returns a new cutoff probability. To stop entirely, return 1.
double take(Output output);
}
public Eddy(@NotNull final Project project, final Editor editor) {
this.project = project;
this.editor = editor;
this.document = editor.getDocument();
this.base = EddyPlugin.basics(project);
}
// only used here and in tests
protected static class Skip extends Exception {
public Skip(final String s) {
super(s);
}
}
public static class PsiStructureException extends RuntimeException {
public PsiStructureException(final String s) { super(s); }
}
// Find the previous or immediately enclosing element (which may be null if there's no parent)
private static @Nullable PsiElement previous(final PsiElement e) throws Skip {
PsiElement p = e.getPrevSibling();
if (p != null)
return p;
return e.getParent();
}
// Trim a range to not include whitespace
private static TextRange trim(final Document doc, final TextRange r) {
final int lo = r.getStartOffset();
final String s = doc.getText(r);
final String t = s.trim();
final int st = s.indexOf(t);
return new TextRange(lo+st,lo+st+t.length());
}
private static @NotNull PsiCodeBlock codeBlockAbove(PsiElement e) throws Skip {
for (;;) {
if (e == null)
throw new Skip("No enclosing code block found");
if (e instanceof PsiCodeBlock)
return (PsiCodeBlock)e;
e = e.getParent();
}
}
private static @NotNull PsiElement stmtsAbove(PsiElement e) throws Skip {
for (;;) {
if (e == null)
throw new Skip("No enclosing statements found");
if (e instanceof PsiCodeBlock || e instanceof PsiStatement)
return e;
e = e.getParent();
}
}
// Find the smallest consecutive sequence of statements and EOL comments that contains the given range.
// 1. Starting at elem, go up to find the nearest enclosing code block.
// 2. Descend to the smallest child that contains the whole trimmed range.
// 3. Go up to the nearest enclosing statement or code block.
// 4. If we're at a code block, return the list of children intersecting the line.
// 5. Otherwise, return whatever we're at.
private static List<PsiElement> elementsContaining(final Document doc, TextRange range, PsiElement e) throws Skip {
// Trim whitespace off both ends of range
range = trim(doc,range);
// Go up to the nearest enclosing code block
e = codeBlockAbove(e);
// Descend to the smallest child of e that contains the whole (trimmed) range
outer:
for (;;) {
for (final PsiElement kid : e.getChildren())
if (kid.getTextRange().contains(range)) {
e = kid;
continue outer;
}
break;
}
// Go back up to find a statement or code block
e = stmtsAbove(e);
// Go up outside of unblocked ifs so that we don't turn an unblocked body into multiple statements
// For an example, see testBlockYes in the IntelliJ tests.
if (e instanceof PsiStatement)
for (;;) {
final PsiElement p = e.getParent();
if (!(p instanceof PsiIfStatement))
break;
e = p;
}
// Collect results
final List<PsiElement> results = new SmartList<PsiElement>();
if (e instanceof PsiCodeBlock) {
// We're a code block, so return only those children intersecting the line.
// Also ignore the first and last children, which are left and right braces.
final PsiElement[] block = e.getChildren();
int lo = 1, hi = block.length-1;
while (lo < hi && !block[lo ].getTextRange().intersects(range)) lo++;
while (lo < hi && !block[hi-1].getTextRange().intersects(range)) hi
for (int i=lo;i<hi;i++)
results.add(block[i]);
} else {
// Otherwise, return a singleton list
results.add(e);
}
return results;
}
// Should we expand an element or leave it atomic?
private static boolean expand(final TreeElement e, final TextRange range, final int cursor) {
// Never expand leaves
if (e instanceof LeafElement)
return false;
// Otherwise, expand or not based on psi
final @NotNull PsiElement psi = e.getPsi();
final TextRange r = psi.getTextRange();
// Expand blocks if the cursor is strictly inside
if (psi instanceof PsiCodeBlock) {
// Check if we're strictly inside. Note that r.contains(pos) is wrong here.
// |{} - r 0 2, pos 0, not inside
// {|} - r 0 2, pos 1, inside
// {}| - r 0 2, pos 2, not inside
return r.getStartOffset() < cursor && cursor < r.getEndOffset();
}
// Expand statements if they overlap our line
if (psi instanceof PsiStatement)
return r.intersects(range);
// Expand everything else
return true;
}
public Input input() throws Skip {
//log("processing eddy...");
// Determine where we are
final int cursor = editor.getCaretModel().getCurrentCaret().getOffset();
final int line = document.getLineNumber(cursor);
final TextRange range = TextRange.create(document.getLineStartOffset(line), document.getLineEndOffset(line));
//log(" processing line " + line + ": " + document.getText(range));
// Find relevant statements and comments
final PsiElement atCursor = getFile().findElementAt(cursor);
final List<PsiElement> elems = elementsContaining(document, range, atCursor);
if (elems.isEmpty())
throw new Skip("Empty statement list");
final PsiElement place = previous(elems.get(0));
if (place == null)
throw new PsiStructureException("previous(" + elems.get(0) + ") == null");
// Walk all relevant elements, collecting leaves and atomic code blocks.
// We walk on AST instead of Psi to get down to the token level.
final List<Loc<Token>> tokens = new ArrayList<Loc<Token>>();
final TreeElementVisitor V = new TreeElementVisitor() {
public void visitLeaf(LeafElement leaf) {
tokens.add(Tokenizer.psiToTok(leaf));
}
public void visitComposite(CompositeElement e) {
// do we need to expand this further?
if (expand(e,range,cursor)) {
final @NotNull PsiElement psi = e.getPsi();
boolean anon = psi instanceof PsiAnonymousClass;
TreeElement child = e.getFirstChildNode();
while (child != null) {
if (anon && e.getChildRole(child) == ChildRole.LBRACE) {
final ASTNode rb = e.findChildByRole(ChildRole.RBRACE);
assert rb != null;
final int lo = child.getStartOffset();
final int hi = rb.getStartOffset() + rb.getTextLength();
tokens.add(Tokenizer.locTok(lo, hi, new Tokenizer.AtomicAnonBodyTok((PsiAnonymousClass)psi, child)));
break;
}
final TreeElement treeNext = child.getTreeNext();
child.acceptTree(this);
child = treeNext;
}
} else {
// atomic node
tokens.add(Tokenizer.psiToTok(e));
}
}
};
for (final PsiElement elem : elems) {
final ASTNode node = elem.getNode();
assert node instanceof TreeElement : "Bad AST node "+node+" for element "+elem;
((TreeElement)node).acceptTree(V);
}
// Trim whitespace at the ends of the token stream
while (!tokens.isEmpty() && tokens.get(0).x() instanceof WhitespaceTok) tokens.remove(0);
while (!tokens.isEmpty() && tokens.get(tokens.size()-1).x() instanceof WhitespaceTok) tokens.remove(tokens.size()-1);
if (tokens.isEmpty())
throw new Skip("No tokens");
// Skip if we're entirely comments and whitespace
boolean allSpace = true;
for (final Loc<Token> t : tokens)
if (!(t.x() instanceof SpaceTok)) {
allSpace = false;
break;
}
if (allSpace)
throw new Skip("All whitespace and comments");
// Compute range to be replaced. We rely on !tokens.isEmpty
final TextRange trim = Tokenizer.range(tokens.get(0)).union(Tokenizer.range(tokens.get(tokens.size()-1)));
final String before = document.getText(trim);
log("eddy before: " + before.replaceAll("[\n\t ]+", " "));
// find out whether we're functionally at the end of the line (not counting whitespace)
boolean atEOL = editor.getDocument().getText(new TextRange(cursor, range.getEndOffset())).trim().isEmpty();
return new Input(trim, line, tokens, place, before, atEOL);
}
public Env env(final Input input, final int lastEdit) {
return EddyPlugin.getInstance(project).getEnv().getLocalEnvironment(input.place, lastEdit);
}
public void process(final int lastEdit, final Take takeOutput) {
// Use mutable variables so that we log more if an exception is thrown partway through
class Helper {
final double start = Memory.now();
Input input;
List<Alt<ShowStmts>> results;
List<Double> delays = new ArrayList<Double>(4);
Throwable error;
void compute(final Env env) {
if (Thread.currentThread().isInterrupted())
throw new ThreadDeath();
final Function2<String,ShowFlags,String> format = new AbstractFunction2<String,ShowFlags,String>() {
@Override public String apply(final String sh, final ShowFlags f) {
return reformat(input.place,sh);
}
};
final long startTime = System.nanoTime();
final Tarski.Take take = new Tarski.Take() {
@Override public double take(final List<Alt<ShowStmts>> rs) {
final Eddy.Output output = new Output(Eddy.this,input,rs);
if (!rs.isEmpty()) {
results = rs;
final double delay = (System.nanoTime() - startTime)/1e9;
delays.add(delay);
if (isDebug()) {
System.out.println(String.format("output %.3fs: ", delay));
if (JavaScores.trackProbabilities) {
for (int i = 0; i < output.results.size(); ++i) {
Alt<ShowStmts> ss = output.results.get(i);
System.out.println(ppretty(ss.dp()).prefixed(" "));
System.out.println(output.format(i, denotationShowFlags()));
}
} else {
System.out.println(output.formats(denotationShowFlags(),true));
}
}
}
return takeOutput.take(output);
}
};
Tarski.fixTake(input.input,env,format,take);
}
void unsafe() {
try {
input = Eddy.this.input();
compute(env(input,lastEdit));
} catch (Skip s) {
// ignore skipped lines, but let caller know we did nothing
//takeOutput.take(new Output(Eddy.this,input,null));
//log("skipping: " + s.getMessage());
}
}
void safe() {
try {
if (isDebug()) // Run outside try so that we can see inside exceptions
unchecked(new Unchecked<Unit$>() { @Override public Unit$ apply() {
unsafe();
return Unit$.MODULE$;
}});
else try {
unsafe();
} catch (final Throwable e) {
error = e;
if (!(e instanceof ThreadDeath) && !(e instanceof RuntimeInterruptedException))
logError("process()",e); // Log everything except for ThreadDeath and RuntimeInterruptedException, which happens all the time.
if (e instanceof Error && !(e instanceof AssertionError))
throw (Error)e; // Rethrow most kinds of Errors
}
} finally {
Memory.log(Memory.eddyProcess(base,Preferences.noCodeLog(), start,
input==null ? -1 : input.line,
input==null ? null : input.input,
results,
delays).error(error), Preferences.noLog(), Utility.onError);
}
}
}
new Helper().safe();
}
// The string should be a single syntactically valid statement
private String reformat(final PsiElement place, final @NotNull String show) {
return new Formatter(project,place).reformat(show);
}
}
|
package com.fb.droidpad;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.UUID;
import android.app.Fragment;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
public class TrackpadFragment extends Fragment implements ServerSocketListener {
private InputStream mInputStream = null;
private OutputStream mOutputStream = null;
private PrintWriter mPrintWriter = null;
private BluetoothSocket mSocket = null;
private Button mButton1;
private static final String TAG = "Trackpad Fragment";
private String MAC = "";
private BluetoothAdapter mBluetoothAdapter = null;
private static final String NAME = "Droidpad";
private UUID mUUID = UUID.fromString("370a07a0-8557-11e3-9d72-0002a5d5c51b");
private static final int REQUEST_ENABLE_BT = 2;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_trackpad, container,
false);
mButton1 = (Button) v.findViewById(R.id.send);
mButton1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sendMessage();
}
});
return v;
}
@Override
public void onStart() {
super.onStart();
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
// If BT is not on, request that it be enabled.
// setupCommand() will then be called during onActivityResult
if (!mBluetoothAdapter.isEnabled()) {
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
ensureDiscoverable();
}
// otherwise set up the command service
else {
Log.d(TAG, "Starting Asynctask");
new ServerTask(mUUID, NAME, this).execute(mBluetoothAdapter);
// new ClientTask(mUUID, MAC, this).execute(mBluetoothAdapter);
}
}
@Override
public void onServerSocketComplete(BluetoothSocket socket) {
Log.d(TAG, "Completed AsyncTask");
mSocket = socket;
try {
mInputStream = socket.getInputStream();
mOutputStream = socket.getOutputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mPrintWriter = new PrintWriter(mOutputStream);
}
public void sendMessage() {
if (mPrintWriter != null) {
Log.d(TAG, "Sending hello world!");
mPrintWriter.println("Hello world");
mPrintWriter.flush();
}
}
private void ensureDiscoverable() {
Log.d(TAG, "ensure discoverable");
if (mBluetoothAdapter.getScanMode() !=
BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
}
}
}
|
package org.reldb.dbrowser.ui;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Vector;
import org.reldb.rel.client.Connection.ExecuteResult;
import org.reldb.rel.client.Tuple;
import org.reldb.rel.client.Tuples;
import org.reldb.rel.client.Value;
import org.reldb.rel.utilities.StringUtils;
public class RevDatabase {
public static final int EXPECTED_REV_VERSION = 0;
public static final int QUERY_WAIT_MILLISECONDS = 5000;
private DbConnection connection;
public RevDatabase(DbConnection connection) {
this.connection = connection;
}
public Value evaluate(String query) {
return connection.evaluate(query);
}
public int hasRevExtensions() {
return connection.hasRevExtensions();
}
public long getUniqueNumber() {
return connection.evaluate("GET_UNIQUE_NUMBER()").toLong();
}
public ExecuteResult exec(String query) {
return connection.execute(query);
}
private boolean execute(String query) {
ExecuteResult result = connection.execute(query);
if (result.failed()) {
System.out.println("Rev: Error: " + result.getErrorMessage());
System.out.println("Rev: Query: " + query);
return false;
}
return true;
}
private Tuples getTuples(String query) {
return connection.getTuples(query);
}
public boolean installRevExtensions() {
String query =
"var sys.rev.Version real relation {" +
" ver INTEGER" +
"} INIT(relation {tuple {ver " + EXPECTED_REV_VERSION + "}}) key {ver};" +
"var sys.rev.Settings real relation {" +
" Name CHAR, " +
" value CHAR " +
"} key {Name};" +
"var sys.rev.Relvar real relation {" +
" Name CHAR, " +
" relvarName CHAR, " +
" xpos INTEGER, " +
" ypos INTEGER, " +
" model CHAR" +
"} key {Name};" +
"var sys.rev.Query real relation {" +
" Name CHAR, " +
" xpos INTEGER, " +
" ypos INTEGER, " +
" kind CHAR, " +
" connections RELATION {" +
" parameter INTEGER, " +
" Name CHAR" +
" }," +
" model CHAR" +
"} key {Name};" +
"var sys.rev.Script real relation {" +
" Name CHAR, " +
" text CHAR " +
"} key {Name};" +
"var sys.rev.ScriptHistory real relation {" +
" Name CHAR, " +
" text CHAR, " +
" timestamp CHAR " +
"} key {Name, timestamp};" +
"var sys.rev.Operator real relation {" +
" Name CHAR, " +
" Definition CHAR" +
"} key {Name};" +
"var sys.rev.Op_Update real relation {" +
" Name CHAR, " +
" Definition RELATION {" +
" ID INTEGER," +
" attribute CHAR," +
" expression CHAR" +
" }" +
"} key {Name};" +
"var sys.rev.Op_Extend real relation {" +
" Name CHAR, " +
" Definition RELATION {" +
" ID INTEGER," +
" attribute CHAR," +
" expression CHAR" +
" }" +
"} key {Name};" +
"var sys.rev.Op_Summarize real relation {" +
" Name CHAR, " +
" isby BOOLEAN, " +
" byList CHAR, " +
" Definition RELATION {" +
" ID INTEGER, " +
" asAttribute CHAR, " +
" aggregateOp CHAR, " +
" expression1 CHAR, " +
" expression2 CHAR " +
" }" +
"} key {Name};";
return execute(query);
}
public boolean removeRevExtensions() {
String query =
"drop var sys.rev.Operator;" +
"drop var sys.rev.Op_Update;" +
"drop var sys.rev.Op_Extend;" +
"drop var sys.rev.Op_Summarize;" +
"drop var sys.rev.Script;" +
"drop var sys.rev.ScriptHistory;" +
"drop var sys.rev.Query;" +
"drop var sys.rev.Relvar;" +
"drop var sys.rev.Settings;" +
"drop var sys.rev.Version;";
return execute(query);
}
public Tuples getRelvars() {
String query = "sys.Catalog {Name, Owner}";
return getTuples(query);
}
public Tuples getRelvars(String model) {
String query = "sys.rev.Relvar WHERE model = \"" + model + "\"";
return getTuples(query);
}
public Tuples getQueries(String model) {
String query = "sys.rev.Query WHERE model = \"" + model + "\"";
return getTuples(query);
}
// Update relvar position
public void updateRelvarPosition(String name, String relvarName, int x, int y, String model) {
String query =
"DELETE sys.rev.Relvar where Name=\"" + name + "\", " +
"INSERT sys.rev.Relvar relation {tuple {Name \"" + name + "\", relvarName \"" + relvarName + "\", xpos " + x + ", ypos " + y + ", model \"" + model + "\"}};";
execute(query);
}
// Update query operator position
public void updateQueryPosition(String name, int x, int y, String kind, String connections, String model) {
String query =
"DELETE sys.rev.Query where Name=\"" + name + "\", " +
"INSERT sys.rev.Query relation {tuple {" +
"Name \"" + name + "\", " +
"xpos " + x + ", " +
"ypos " + y + ", " +
"kind \"" + kind + "\", " +
"connections " + connections + ", " +
"model \"" + model + "\"" +
"}};";
execute(query);
}
// Preserved States
// Most operators
public Tuples getPreservedStateOperator(String name) {
String query = "sys.rev.Operator WHERE Name = \"" + name + "\"";
return getTuples(query);
}
public void updatePreservedStateOperator(String name, String definition) {
String query = "DELETE sys.rev.Operator WHERE Name = \"" + name + "\", " +
"INSERT sys.rev.Operator RELATION {" +
"TUPLE {Name \"" + name + "\", Definition \"" + definition + "\"}" +
"};";
execute(query);
}
// Update
public Tuples getPreservedStateUpdate(String name) {
String query = "(sys.rev.Op_Update WHERE Name = \"" + name + "\") UNGROUP Definition ORDER(ASC ID)";
return getTuples(query);
}
public void updatePreservedStateUpdate(String name, String definition) {
String query = "DELETE sys.rev.Op_Update WHERE Name = \"" + name + "\", " +
"INSERT sys.rev.Op_Update RELATION {" +
" TUPLE {Name \"" + name + "\", Definition " + definition + "}" +
"};";
execute(query);
}
// Extend
public Tuples getPreservedStateExtend(String name) {
String query = "(sys.rev.Op_Extend WHERE Name = \"" + name + "\") UNGROUP Definition ORDER(ASC ID)";
return getTuples(query);
}
public void updatePreservedStateExtend(String name, String definition) {
String query = "DELETE sys.rev.Op_Extend WHERE Name = \"" + name + "\", " +
"INSERT sys.rev.Op_Extend RELATION {" +
" TUPLE {Name \"" + name + "\", Definition " + definition + "}" +
"};";
execute(query);
}
// Summarize
public Tuples getPreservedStateSummarize(String name) {
String query = "(sys.rev.Op_Summarize WHERE Name = \"" + name + "\") UNGROUP Definition ORDER(ASC ID)";
return getTuples(query);
}
public void updatePreservedStateSummarize(String name, String definition) {
String query = "DELETE sys.rev.Op_Summarize WHERE Name = \"" + name + "\", " +
"INSERT sys.rev.Op_Summarize RELATION {" +
" TUPLE {Name \"" + name + "\", isby false, byList \"\", Definition " + definition + "}" +
"};";
execute(query);
}
public void updatePreservedStateSummarize(String name, String byList, String definition) {
String query = "DELETE sys.rev.Op_Summarize WHERE Name = \"" + name + "\", " +
"INSERT sys.rev.Op_Summarize RELATION {" +
" TUPLE {Name \"" + name + "\", isby true, byList \"" + byList + "\", Definition " + definition + "}" +
"};";
execute(query);
}
public void removeQuery(String name) {
String query = "DELETE sys.rev.Query WHERE Name = \"" + name + "\";";
execute(query);
}
public void removeRelvar(String name) {
String query = "DELETE sys.rev.Relvar WHERE Name = \"" + name + "\";";
execute(query);
}
public void removeOperator(String name) {
String query = "DELETE sys.rev.Operator WHERE Name = \"" + name + "\";";
execute(query);
}
public void removeOperator_Update(String name) {
String query = "DELETE sys.rev.Op_Update WHERE Name = \"" + name + "\";";
execute(query);
}
public void removeOperator_Extend(String name) {
String query = "DELETE sys.rev.Op_Extend WHERE Name = \"" + name + "\";";
execute(query);
}
public void removeOperator_Summarize(String name) {
String query = "DELETE sys.rev.Op_Summarize WHERE Name = \"" + name + "\";";
execute(query);
}
public boolean modelExists(String name) {
String query = "COUNT(((sys.rev.Query {model}) UNION (sys.rev.Relvar {model})) WHERE model = \"" + name + "\") > 0";
return evaluate(query).toBoolean();
}
public void modelRename(String oldName, String newName) {
if (oldName.equals(newName))
return;
String query = "DELETE sys.rev.Query WHERE model = \"" + newName + "\", " +
"DELETE sys.rev.Relvar WHERE model = \"" + newName + "\", " +
"UPDATE sys.rev.Query WHERE model = \"" + oldName + "\": {model := \"" + newName + "\"}, " +
"UPDATE sys.rev.Relvar WHERE model = \"" + oldName + "\": {model := \"" + newName + "\"};";
execute(query);
}
public void modelCopyTo(String oldName, String newName) {
if (oldName.equals(newName))
return;
String query = "DELETE sys.rev.Query WHERE model = \"" + newName + "\", " +
"DELETE sys.rev.Relvar WHERE model = \"" + newName + "\", " +
"INSERT sys.rev.Operator UPDATE sys.rev.Operator JOIN (((sys.rev.Query WHERE model = \"" + oldName + "\") {Name}) UNION ((sys.rev.Relvar WHERE model = \"" + oldName + "\") {Name})): {Name := Name || \"copy\"}, " +
"INSERT sys.rev.Op_Update UPDATE sys.rev.Op_Update JOIN (((sys.rev.Query WHERE model = \"" + oldName + "\") {Name}) UNION ((sys.rev.Relvar WHERE model = \"" + oldName + "\") {Name})): {Name := Name || \"copy\"}, " +
"INSERT sys.rev.Op_Extend UPDATE sys.rev.Op_Extend JOIN (((sys.rev.Query WHERE model = \"" + oldName + "\") {Name}) UNION ((sys.rev.Relvar WHERE model = \"" + oldName + "\") {Name})): {Name := Name || \"copy\"}, " +
"INSERT sys.rev.Op_Summarize UPDATE sys.rev.Op_Summarize JOIN (((sys.rev.Query WHERE model = \"" + oldName + "\") {Name}) UNION ((sys.rev.Relvar WHERE model = \"" + oldName + "\") {Name})): {Name := Name || \"copy\"}, " +
"INSERT sys.rev.Query UPDATE sys.rev.Query WHERE model = \"" + oldName + "\": {model := \"" + newName + "\", Name := Name || \"copy\", connections := UPDATE connections: {Name := Name || \"copy\"}}, " +
"INSERT sys.rev.Relvar UPDATE sys.rev.Relvar WHERE model = \"" + oldName + "\": {model := \"" + newName + "\", Name := Name || \"copy\"};";
execute(query);
}
public boolean modelDelete(String name) {
String query =
"DELETE sys.rev.Operator WHERE TUPLE {Name Name} IN ((sys.rev.Query WHERE model = \"" + name + "\") {Name}) UNION ((sys.rev.Relvar WHERE model = \"" + name + "\") {Name}), " +
"DELETE sys.rev.Op_Update WHERE TUPLE {Name Name} IN ((sys.rev.Query WHERE model = \"" + name + "\") {Name}) UNION ((sys.rev.Relvar WHERE model = \"" + name + "\") {Name}), " +
"DELETE sys.rev.Op_Extend WHERE TUPLE {Name Name} IN ((sys.rev.Query WHERE model = \"" + name + "\") {Name}) UNION ((sys.rev.Relvar WHERE model = \"" + name + "\") {Name}), " +
"DELETE sys.rev.Op_Summarize WHERE TUPLE {Name Name} IN ((sys.rev.Query WHERE model = \"" + name + "\") {Name}) UNION ((sys.rev.Relvar WHERE model = \"" + name + "\") {Name}), " +
"DELETE sys.rev.Query WHERE model = \"" + name + "\", " +
"DELETE sys.rev.Relvar WHERE model = \"" + name + "\";";
return execute(query);
}
public Vector<String> getModels() {
String query = "(sys.rev.Query {model}) UNION (sys.rev.Relvar {model})";
Tuples tuples = (Tuples)evaluate(query);
Vector<String> models = new Vector<String>();
for (Tuple tuple: tuples)
models.add(tuple.get("model").toString());
return models;
}
public boolean relvarExists(String name) {
String query = "COUNT(sys.Catalog WHERE Name = \"" + name + "\") > 0";
Value result = (Value)evaluate(query);
return result.toBoolean();
}
public boolean scriptExists(String name) {
String query = "COUNT(sys.rev.Script WHERE Name = \"" + name + "\") > 0";
Value result = (Value)evaluate(query);
return result.toBoolean();
}
public boolean createScript(String name) {
String query = "INSERT sys.rev.Script RELATION {TUPLE {Name \"" + name + "\", text \"\"}};";
return execute(query);
}
public static class Script {
private String content;
private Vector<String> history;
public Script(String content, Vector<String> history) {
this.content = content;
this.history = history;
}
public Vector<String> getHistory() {
return history;
}
public String getContent() {
return content;
}
}
public Script getScript(String name) {
String query = "sys.rev.Script WHERE Name=\"" + name + "\"";
String content = "";
Tuples tuples = (Tuples)evaluate(query);
for (Tuple tuple: tuples) {
String rawContent = tuple.get("text").toString();
content = rawContent;
}
query = "sys.rev.ScriptHistory WHERE Name=\"" + name + "\" ORDER (ASC timestamp)";
tuples = (Tuples)evaluate(query);
Vector<String> history = new Vector<String>();
for (Tuple tuple: tuples) {
String rawContent = tuple.get("text").toString();
history.add(rawContent);
}
return new Script(content, history);
}
public void setScript(String name, String content) {
String text = StringUtils.quote(content);
String query =
"IF COUNT(sys.rev.Script WHERE Name=\"" + name + "\") = 0 THEN " +
" INSERT sys.rev.Script REL {TUP {Name \"" + name + "\", text \"" + text + "\"}}; " +
"ELSE " +
" UPDATE sys.rev.Script WHERE Name=\"" + name + "\": {text := \"" + text + "\"}; " +
"END IF;";
execute(query);
}
public void addScriptHistory(String name, String historyItem) {
System.out.println("RevDatabase: Add history for: " + name + ": " + StringUtils.quote(historyItem));
String timestamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss.SSS").format(new Date());
String query =
"INSERT sys.rev.ScriptHistory " + "REL {TUP {" +
" Name \"" + name + "\", " +
" text \"" + StringUtils.quote(historyItem) + "\", " +
" timestamp \"" + timestamp + "\"" +
"}};";
execute(query);
}
public boolean scriptDelete(String name) {
String query = "DELETE sys.rev.Script WHERE Name=\"" + name + "\";";
return execute(query);
}
public boolean renameScript(String nameFrom, String nameTo) {
String query =
"UPDATE sys.rev.Script WHERE Name=\"" + nameFrom + "\": {Name := \"" + nameTo + "\"}, " +
"UPDATE sys.rev.ScriptHistory WHERE Name=\"" + nameFrom + "\": {Name := \"" + nameTo + "\"};";
return execute(query);
}
public void setSetting(String name, String value) {
String query =
"IF COUNT(sys.rev.Settings WHERE Name=\"" + name + "\") = 0 THEN " +
" INSERT sys.rev.Settings REL {TUP {Name \"" + name + "\", value \"" + StringUtils.quote(value) + "\"}}; " +
"ELSE " +
" UPDATE sys.rev.Settings WHERE Name=\"" + name + "\": {value := \"" + StringUtils.quote(value) + "\"}; " +
"END IF;";
execute(query);
}
public String getSetting(String name) {
String query = "sys.rev.Settings WHERE Name=\"" + name + "\"";
Tuples tuples = (Tuples)evaluate(query);
for (Tuple tuple: tuples)
return tuple.get("value").toString();
return "";
}
public static class Overview {
private String content;
private boolean revPrompt;
public Overview(String content, boolean revPrompt) {
this.content = content;
this.revPrompt = revPrompt;
}
public String getContent() {
return content;
}
public boolean getRevPrompt() {
return revPrompt;
}
}
public Overview getOverview() {
String query = "pub.Overview";
Tuples tuples = (Tuples)evaluate(query);
try {
for (Tuple tuple: tuples) {
String content = tuple.get("content").toString();
boolean revPrompt = tuple.get("revPrompt").toBoolean();
return new Overview(content, revPrompt);
}
} catch (Exception e) {}
return new Overview("", true);
}
public boolean createOverview() {
String query =
"VAR pub.Overview REAL RELATION {content CHAR, revPrompt BOOLEAN} KEY {}; " +
"INSERT pub.Overview RELATION {TUP {content \"" +
StringUtils.quote(
"Edit the pub.Overview variable to change this text.\n" +
"The \"contents\" attribute value will appear here.\n" +
"Set the \"revPrompt\" attribute to FALSE to only display this overview."
) + "\", revPrompt TRUE}};";
return execute(query);
}
public String[] getKeywords() {
return connection.getKeywords();
}
public String[] getRelvarTypes() {
String query = "UNION {sys.ExternalRelvarTypes {Identifier, Description}, REL {TUP {Identifier \"REAL\", Description \"REAL relation-valued variable.\"}}} ORDER (ASC Identifier)";
Tuples tuples = (Tuples)evaluate(query);
Vector<String> types = new Vector<String>();
try {
for (Tuple tuple: tuples) {
String identifier = tuple.get("Identifier").toString();
String description = tuple.get("Description").toString();
types.add(identifier + ": " + description);
}
} catch (Exception e) {}
return types.toArray(new String[0]);
}
public Tuple getExternalRelvarTypeInfo(String variableType) {
String query = "sys.ExternalRelvarTypes WHERE Identifier=\"" + variableType + "\"";
Tuples tuples = (Tuples)evaluate(query);
for (Tuple tuple: tuples)
return tuple;
return null;
}
}
|
package com.fsck.k9.mail.store;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.PowerManager;
import android.util.Log;
import com.fsck.k9.Account;
import com.fsck.k9.K9;
import com.fsck.k9.controller.MessageRetrievalListener;
import com.fsck.k9.helper.Utility;
import com.fsck.k9.helper.power.TracingPowerManager;
import com.fsck.k9.helper.power.TracingPowerManager.TracingWakeLock;
import com.fsck.k9.mail.*;
import com.fsck.k9.mail.filter.CountingOutputStream;
import com.fsck.k9.mail.filter.EOLConvertingOutputStream;
import com.fsck.k9.mail.filter.FixedLengthInputStream;
import com.fsck.k9.mail.filter.PeekableInputStream;
import com.fsck.k9.mail.internet.*;
import com.fsck.k9.mail.store.ImapResponseParser.ImapList;
import com.fsck.k9.mail.store.ImapResponseParser.ImapResponse;
import com.jcraft.jzlib.JZlib;
import com.jcraft.jzlib.ZInputStream;
import com.jcraft.jzlib.ZOutputStream;
import com.beetstra.jutf7.CharsetProvider;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.TrustManager;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;
import java.io.*;
import java.net.*;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.Security;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
/**
* <pre>
* TODO Need to start keeping track of UIDVALIDITY
* TODO Need a default response handler for things like folder updates
* </pre>
*/
public class ImapStore extends Store
{
public static final int CONNECTION_SECURITY_NONE = 0;
public static final int CONNECTION_SECURITY_TLS_OPTIONAL = 1;
public static final int CONNECTION_SECURITY_TLS_REQUIRED = 2;
public static final int CONNECTION_SECURITY_SSL_REQUIRED = 3;
public static final int CONNECTION_SECURITY_SSL_OPTIONAL = 4;
private enum AuthType { PLAIN, CRAM_MD5 };
private static final int IDLE_READ_TIMEOUT_INCREMENT = 5 * 60 * 1000;
private static final int IDLE_FAILURE_COUNT_LIMIT = 10;
private static int MAX_DELAY_TIME = 5 * 60 * 1000; // 5 minutes
private static int NORMAL_DELAY_TIME = 5000;
private static final Flag[] PERMANENT_FLAGS = { Flag.DELETED, Flag.SEEN };
private static final String CAPABILITY_IDLE = "IDLE";
private static final String COMMAND_IDLE = "IDLE";
private static final String CAPABILITY_NAMESPACE = "NAMESPACE";
private static final String COMMAND_NAMESPACE = "NAMESPACE";
private static final String CAPABILITY_CAPABILITY = "CAPABILITY";
private static final String COMMAND_CAPABILITY = "CAPABILITY";
private static final String CAPABILITY_COMPRESS_DEFLATE = "COMPRESS=DEFLATE";
private static final String COMMAND_COMPRESS_DEFLATE = "COMPRESS DEFLATE";
private String mHost;
private int mPort;
private String mUsername;
private String mPassword;
private int mConnectionSecurity;
private AuthType mAuthType;
private volatile String mPathPrefix;
private volatile String mCombinedPrefix = null;
private volatile String mPathDelimeter = null;
private LinkedList<ImapConnection> mConnections =
new LinkedList<ImapConnection>();
/**
* Charset used for converting folder names to and from UTF-7 as defined by RFC 3501.
*/
private Charset mModifiedUtf7Charset;
/**
* Cache of ImapFolder objects. ImapFolders are attached to a given folder on the server
* and as long as their associated connection remains open they are reusable between
* requests. This cache lets us make sure we always reuse, if possible, for a given
* folder name.
*/
private HashMap<String, ImapFolder> mFolderCache = new HashMap<String, ImapFolder>();
/**
* imap://auth:user:password@server:port CONNECTION_SECURITY_NONE
* imap+tls://auth:user:password@server:port CONNECTION_SECURITY_TLS_OPTIONAL
* imap+tls+://auth:user:password@server:port CONNECTION_SECURITY_TLS_REQUIRED
* imap+ssl+://auth:user:password@server:port CONNECTION_SECURITY_SSL_REQUIRED
* imap+ssl://auth:user:password@server:port CONNECTION_SECURITY_SSL_OPTIONAL
*
* @param _uri
*/
public ImapStore(Account account) throws MessagingException
{
super(account);
URI uri;
try
{
uri = new URI(mAccount.getStoreUri());
}
catch (URISyntaxException use)
{
throw new MessagingException("Invalid ImapStore URI", use);
}
String scheme = uri.getScheme();
if (scheme.equals("imap"))
{
mConnectionSecurity = CONNECTION_SECURITY_NONE;
mPort = 143;
}
else if (scheme.equals("imap+tls"))
{
mConnectionSecurity = CONNECTION_SECURITY_TLS_OPTIONAL;
mPort = 143;
}
else if (scheme.equals("imap+tls+"))
{
mConnectionSecurity = CONNECTION_SECURITY_TLS_REQUIRED;
mPort = 143;
}
else if (scheme.equals("imap+ssl+"))
{
mConnectionSecurity = CONNECTION_SECURITY_SSL_REQUIRED;
mPort = 993;
}
else if (scheme.equals("imap+ssl"))
{
mConnectionSecurity = CONNECTION_SECURITY_SSL_OPTIONAL;
mPort = 993;
}
else
{
throw new MessagingException("Unsupported protocol");
}
mHost = uri.getHost();
if (uri.getPort() != -1)
{
mPort = uri.getPort();
}
if (uri.getUserInfo() != null)
{
try
{
String[] userInfoParts = uri.getUserInfo().split(":");
if (userInfoParts.length == 2)
{
mAuthType = AuthType.PLAIN;
mUsername = URLDecoder.decode(userInfoParts[0], "UTF-8");
mPassword = URLDecoder.decode(userInfoParts[1], "UTF-8");
}
else
{
mAuthType = AuthType.valueOf(userInfoParts[0]);
mUsername = URLDecoder.decode(userInfoParts[1], "UTF-8");
mPassword = URLDecoder.decode(userInfoParts[2], "UTF-8");
}
}
catch (UnsupportedEncodingException enc)
{
// This shouldn't happen since the encoding is hardcoded to UTF-8
Log.e(K9.LOG_TAG, "Couldn't urldecode username or password.", enc);
}
}
if ((uri.getPath() != null) && (uri.getPath().length() > 0))
{
mPathPrefix = uri.getPath().substring(1);
if (mPathPrefix != null && mPathPrefix.trim().length() == 0)
{
mPathPrefix = null;
}
}
mModifiedUtf7Charset = new CharsetProvider().charsetForName("X-RFC-3501");
}
@Override
public Folder getFolder(String name) throws MessagingException
{
ImapFolder folder;
synchronized (mFolderCache)
{
folder = mFolderCache.get(name);
if (folder == null)
{
folder = new ImapFolder(this, name);
mFolderCache.put(name, folder);
}
}
return folder;
}
private String getCombinedPrefix()
{
if (mCombinedPrefix == null)
{
if (mPathPrefix != null)
{
String tmpPrefix = mPathPrefix.trim();
String tmpDelim = (mPathDelimeter != null ? mPathDelimeter.trim() : "");
if (tmpPrefix.endsWith(tmpDelim))
{
mCombinedPrefix = tmpPrefix;
}
else if (tmpPrefix.length() > 0)
{
mCombinedPrefix = tmpPrefix + tmpDelim;
}
else
{
mCombinedPrefix = "";
}
}
else
{
mCombinedPrefix = "";
}
}
return mCombinedPrefix;
}
@Override
public List<? extends Folder> getPersonalNamespaces() throws MessagingException
{
ImapConnection connection = getConnection();
try
{
LinkedList<Folder> folders = new LinkedList<Folder>();
List<ImapResponse> responses =
connection.executeSimpleCommand(String.format("LIST \"\" \"%s*\"",
getCombinedPrefix()));
for (ImapResponse response : responses)
{
if (ImapResponseParser.equalsIgnoreCase(response.get(0), "LIST"))
{
boolean includeFolder = true;
String folder = decodeFolderName(response.getString(3));
if (mPathDelimeter == null)
{
mPathDelimeter = response.getString(2);
mCombinedPrefix = null;
}
if (folder.equalsIgnoreCase(K9.INBOX))
{
continue;
}
else
{
if (getCombinedPrefix().length() > 0)
{
if (folder.length() >= getCombinedPrefix().length())
{
folder = folder.substring(getCombinedPrefix().length());
}
if (!decodeFolderName(response.getString(3)).equalsIgnoreCase(getCombinedPrefix() + folder))
{
includeFolder = false;
}
}
}
ImapList attributes = response.getList(1);
for (int i = 0, count = attributes.size(); i < count; i++)
{
String attribute = attributes.getString(i);
if (attribute.equalsIgnoreCase("\\NoSelect"))
{
includeFolder = false;
}
}
if (includeFolder)
{
folders.add(getFolder(folder));
}
}
}
folders.add(getFolder("INBOX"));
return folders;
}
catch (IOException ioe)
{
connection.close();
throw new MessagingException("Unable to get folder list.", ioe);
}
finally
{
releaseConnection(connection);
}
}
@Override
public void checkSettings() throws MessagingException
{
try
{
ImapConnection connection = new ImapConnection();
connection.open();
connection.close();
}
catch (IOException ioe)
{
throw new MessagingException("Unable to connect.", ioe);
}
}
/**
* Gets a connection if one is available for reuse, or creates a new one if not.
* @return
*/
private ImapConnection getConnection() throws MessagingException
{
synchronized (mConnections)
{
ImapConnection connection = null;
while ((connection = mConnections.poll()) != null)
{
try
{
connection.executeSimpleCommand("NOOP");
break;
}
catch (IOException ioe)
{
connection.close();
}
}
if (connection == null)
{
connection = new ImapConnection();
}
return connection;
}
}
private void releaseConnection(ImapConnection connection)
{
if (connection != null && connection.isOpen())
{
synchronized (mConnections)
{
mConnections.offer(connection);
}
}
}
private String encodeFolderName(String name)
{
try
{
ByteBuffer bb = mModifiedUtf7Charset.encode(name);
byte[] b = new byte[bb.limit()];
bb.get(b);
return new String(b, "US-ASCII");
}
catch (UnsupportedEncodingException uee)
{
/*
* The only thing that can throw this is getBytes("US-ASCII") and if US-ASCII doesn't
* exist we're totally screwed.
*/
throw new RuntimeException("Unable to encode folder name: " + name, uee);
}
}
private String decodeFolderName(String name)
{
/*
* Convert the encoded name to US-ASCII, then pass it through the modified UTF-7
* decoder and return the Unicode String.
*/
try
{
byte[] encoded = name.getBytes("US-ASCII");
CharBuffer cb = mModifiedUtf7Charset.decode(ByteBuffer.wrap(encoded));
return cb.toString();
}
catch (UnsupportedEncodingException uee)
{
/*
* The only thing that can throw this is getBytes("US-ASCII") and if US-ASCII doesn't
* exist we're totally screwed.
*/
throw new RuntimeException("Unable to decode folder name: " + name, uee);
}
}
@Override
public boolean isMoveCapable()
{
return true;
}
@Override
public boolean isCopyCapable()
{
return true;
}
@Override
public boolean isPushCapable()
{
return true;
}
@Override
public boolean isExpungeCapable()
{
return true;
}
class ImapFolder extends Folder
{
private String mName;
protected volatile int mMessageCount = -1;
protected volatile int uidNext = -1;
protected volatile ImapConnection mConnection;
private OpenMode mMode;
private volatile boolean mExists;
private ImapStore store = null;
Map<Integer, String> msgSeqUidMap = new ConcurrentHashMap<Integer, String>();
public ImapFolder(ImapStore nStore, String name)
{
super(nStore.getAccount());
store = nStore;
this.mName = name;
}
public String getPrefixedName() throws MessagingException
{
String prefixedName = "";
if (!K9.INBOX.equalsIgnoreCase(mName))
{
ImapConnection connection = null;
synchronized (this)
{
if (mConnection == null)
{
connection = getConnection();
}
else
{
connection = mConnection;
}
}
try
{
connection.open();
}
catch (IOException ioe)
{
throw new MessagingException("Unable to get IMAP prefix", ioe);
}
finally
{
if (mConnection == null)
{
releaseConnection(connection);
}
}
prefixedName = getCombinedPrefix();
}
prefixedName += mName;
return prefixedName;
}
protected List<ImapResponse> executeSimpleCommand(String command) throws MessagingException, IOException
{
return handleUntaggedResponses(mConnection.executeSimpleCommand(command));
}
protected List<ImapResponse> executeSimpleCommand(String command, boolean sensitve, UntaggedHandler untaggedHandler) throws MessagingException, IOException
{
return handleUntaggedResponses(mConnection.executeSimpleCommand(command, sensitve, untaggedHandler));
}
@Override
public void open(OpenMode mode) throws MessagingException
{
internalOpen(mode);
if (mMessageCount == -1)
{
throw new MessagingException(
"Did not find message count during open");
}
}
public List<ImapResponse> internalOpen(OpenMode mode) throws MessagingException
{
if (isOpen() && mMode == mode)
{
// Make sure the connection is valid. If it's not we'll close it down and continue
// on to get a new one.
try
{
List<ImapResponse> responses = executeSimpleCommand("NOOP");
return responses;
}
catch (IOException ioe)
{
ioExceptionHandler(mConnection, ioe);
}
}
releaseConnection(mConnection);
synchronized (this)
{
mConnection = getConnection();
}
// * FLAGS (\Answered \Flagged \Deleted \Seen \Draft NonJunk
// $MDNSent)
// * OK [PERMANENTFLAGS (\Answered \Flagged \Deleted \Seen \Draft
// NonJunk $MDNSent \*)] Flags permitted.
// * 23 EXISTS
// * 0 RECENT
// * OK [UIDVALIDITY 1125022061] UIDs valid
// * OK [UIDNEXT 57576] Predicted next UID
// 2 OK [READ-WRITE] Select completed.
try
{
msgSeqUidMap.clear();
String command = String.format((mode == OpenMode.READ_WRITE ? "SELECT" : "EXAMINE") + " \"%s\"",
encodeFolderName(getPrefixedName()));
List<ImapResponse> responses = executeSimpleCommand(command);
/*
* If the command succeeds we expect the folder has been opened read-write
* unless we are notified otherwise in the responses.
*/
mMode = mode;
for (ImapResponse response : responses)
{
if (response.mTag != null && response.size() >= 2)
{
Object bracketedObj = response.get(1);
if (bracketedObj instanceof ImapList)
{
ImapList bracketed = (ImapList)bracketedObj;
if (bracketed.size() > 0)
{
Object keyObj = bracketed.get(0);
if (keyObj instanceof String)
{
String key = (String)keyObj;
if ("READ-ONLY".equalsIgnoreCase(key))
{
mMode = OpenMode.READ_ONLY;
}
else if ("READ-WRITE".equalsIgnoreCase(key))
{
mMode = OpenMode.READ_WRITE;
}
}
}
}
}
}
mExists = true;
return responses;
}
catch (IOException ioe)
{
throw ioExceptionHandler(mConnection, ioe);
}
catch (MessagingException me)
{
Log.e(K9.LOG_TAG, "Unable to open connection for " + getLogId(), me);
throw me;
}
}
@Override
public boolean isOpen()
{
return mConnection != null;
}
@Override
public OpenMode getMode() throws MessagingException
{
return mMode;
}
@Override
public void close()
{
if (mMessageCount != -1)
{
mMessageCount = -1;
}
if (!isOpen())
{
return;
}
synchronized (this)
{
releaseConnection(mConnection);
mConnection = null;
}
}
@Override
public String getName()
{
return mName;
}
private boolean exists(String folderName) throws MessagingException
{
try
{
// Since we don't care about RECENT, we'll use that for the check, because we're checking
// a folder other than ourself, and don't want any untagged responses to cause a change
// in our own fields
mConnection.executeSimpleCommand(String.format("STATUS \"%s\" (RECENT)", folderName));
return true;
}
catch (IOException ioe)
{
throw ioExceptionHandler(mConnection, ioe);
}
catch (MessagingException me)
{
return false;
}
}
@Override
public boolean exists() throws MessagingException
{
if (mExists)
{
return true;
}
/*
* This method needs to operate in the unselected mode as well as the selected mode
* so we must get the connection ourselves if it's not there. We are specifically
* not calling checkOpen() since we don't care if the folder is open.
*/
ImapConnection connection = null;
synchronized (this)
{
if (mConnection == null)
{
connection = getConnection();
}
else
{
connection = mConnection;
}
}
try
{
connection.executeSimpleCommand(String.format("STATUS \"%s\" (UIDVALIDITY)",
encodeFolderName(getPrefixedName())));
mExists = true;
return true;
}
catch (MessagingException me)
{
return false;
}
catch (IOException ioe)
{
throw ioExceptionHandler(connection, ioe);
}
finally
{
if (mConnection == null)
{
releaseConnection(connection);
}
}
}
@Override
public boolean create(FolderType type) throws MessagingException
{
/*
* This method needs to operate in the unselected mode as well as the selected mode
* so we must get the connection ourselves if it's not there. We are specifically
* not calling checkOpen() since we don't care if the folder is open.
*/
ImapConnection connection = null;
synchronized (this)
{
if (mConnection == null)
{
connection = getConnection();
}
else
{
connection = mConnection;
}
}
try
{
connection.executeSimpleCommand(String.format("CREATE \"%s\"",
encodeFolderName(getPrefixedName())));
return true;
}
catch (MessagingException me)
{
return false;
}
catch (IOException ioe)
{
throw ioExceptionHandler(mConnection, ioe);
}
finally
{
if (mConnection == null)
{
releaseConnection(connection);
}
}
}
@Override
public void copyMessages(Message[] messages, Folder folder) throws MessagingException
{
if (folder instanceof ImapFolder == false)
{
throw new MessagingException("ImapFolder.copyMessages passed non-ImapFolder");
}
if (messages.length == 0)
return;
ImapFolder iFolder = (ImapFolder)folder;
checkOpen();
String[] uids = new String[messages.length];
for (int i = 0, count = messages.length; i < count; i++)
{
uids[i] = messages[i].getUid();
}
try
{
String remoteDestName = encodeFolderName(iFolder.getPrefixedName());
if (!exists(remoteDestName))
{
/*
* If the remote trash folder doesn't exist we try to create it.
*/
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "IMAPMessage.copyMessages: attempting to create remote '" + remoteDestName + "' folder for " + getLogId());
iFolder.create(FolderType.HOLDS_MESSAGES);
}
if (exists(remoteDestName))
{
executeSimpleCommand(String.format("UID COPY %s \"%s\"",
Utility.combine(uids, ','),
encodeFolderName(iFolder.getPrefixedName())));
}
else
{
throw new MessagingException("IMAPMessage.copyMessages: remote destination folder " + folder.getName()
+ " does not exist and could not be created for " + getLogId()
, true);
}
}
catch (IOException ioe)
{
throw ioExceptionHandler(mConnection, ioe);
}
}
@Override
public void moveMessages(Message[] messages, Folder folder) throws MessagingException
{
if (messages.length == 0)
return;
copyMessages(messages, folder);
setFlags(messages, new Flag[] { Flag.DELETED }, true);
}
@Override
public void delete(Message[] messages, String trashFolderName) throws MessagingException
{
if (messages.length == 0)
return;
if (trashFolderName == null || getName().equalsIgnoreCase(trashFolderName))
{
setFlags(messages, new Flag[] { Flag.DELETED }, true);
}
else
{
ImapFolder remoteTrashFolder = (ImapFolder)getStore().getFolder(trashFolderName);
String remoteTrashName = encodeFolderName(remoteTrashFolder.getPrefixedName());
if (!exists(remoteTrashName))
{
/*
* If the remote trash folder doesn't exist we try to create it.
*/
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "IMAPMessage.delete: attempting to create remote '" + trashFolderName + "' folder for " + getLogId());
remoteTrashFolder.create(FolderType.HOLDS_MESSAGES);
}
if (exists(remoteTrashName))
{
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "IMAPMessage.delete: copying remote " + messages.length + " messages to '" + trashFolderName + "' for " + getLogId());
moveMessages(messages, remoteTrashFolder);
}
else
{
throw new MessagingException("IMAPMessage.delete: remote Trash folder " + trashFolderName + " does not exist and could not be created for " + getLogId()
, true);
}
}
}
@Override
public int getMessageCount()
{
return mMessageCount;
}
@Override
public int getUnreadMessageCount() throws MessagingException
{
checkOpen();
try
{
int count = 0;
int start = mMessageCount - 299;
if (start < 1)
{
start = 1;
}
List<ImapResponse> responses = executeSimpleCommand(String.format("SEARCH %d:* UNSEEN NOT DELETED", start));
for (ImapResponse response : responses)
{
if (ImapResponseParser.equalsIgnoreCase(response.get(0), "SEARCH"))
{
count += response.size() - 1;
}
}
return count;
}
catch (IOException ioe)
{
throw ioExceptionHandler(mConnection, ioe);
}
}
@Override
public int getFlaggedMessageCount() throws MessagingException
{
checkOpen();
try
{
int count = 0;
int start = mMessageCount - 299;
if (start < 1)
{
start = 1;
}
List<ImapResponse> responses = executeSimpleCommand(String.format("SEARCH %d:* FLAGGED NOT DELETED", start));
for (ImapResponse response : responses)
{
if (ImapResponseParser.equalsIgnoreCase(response.get(0), "SEARCH"))
{
count += response.size() - 1;
}
}
return count;
}
catch (IOException ioe)
{
throw ioExceptionHandler(mConnection, ioe);
}
}
protected int getHighestUid()
{
try
{
ImapSearcher searcher = new ImapSearcher()
{
public List<ImapResponse> search() throws IOException, MessagingException
{
return executeSimpleCommand(String.format("UID SEARCH *:* "));
}
};
Message[] messages = search(searcher, null);
if (messages.length > 0)
{
return Integer.parseInt(messages[0].getUid());
}
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Unable to find highest UID in folder " + getName(), e);
}
return -1;
}
@Override
public void delete(boolean recurse) throws MessagingException
{
throw new Error("ImapStore.delete() not yet implemented");
}
@Override
public Message getMessage(String uid) throws MessagingException
{
return new ImapMessage(uid, this);
}
@Override
public Message[] getMessages(int start, int end, MessageRetrievalListener listener)
throws MessagingException
{
return getMessages(start, end, false, listener);
}
protected Message[] getMessages(final int start, final int end, final boolean includeDeleted, final MessageRetrievalListener listener)
throws MessagingException
{
if (start < 1 || end < 1 || end < start)
{
throw new MessagingException(
String.format("Invalid message set %d %d",
start, end));
}
ImapSearcher searcher = new ImapSearcher()
{
public List<ImapResponse> search() throws IOException, MessagingException
{
return executeSimpleCommand(String.format("UID SEARCH %d:%d" + (includeDeleted ? "" : " NOT DELETED"), start, end));
}
};
return search(searcher, listener);
}
protected Message[] getMessages(final List<Integer> mesgSeqs, final boolean includeDeleted, final MessageRetrievalListener listener)
throws MessagingException
{
ImapSearcher searcher = new ImapSearcher()
{
public List<ImapResponse> search() throws IOException, MessagingException
{
return executeSimpleCommand(String.format("UID SEARCH %s" + (includeDeleted ? "" : " NOT DELETED"), Utility.combine(mesgSeqs.toArray(), ',')));
}
};
return search(searcher, listener);
}
protected Message[] getMessagesFromUids(final List<String> mesgUids, final boolean includeDeleted, final MessageRetrievalListener listener)
throws MessagingException
{
ImapSearcher searcher = new ImapSearcher()
{
public List<ImapResponse> search() throws IOException, MessagingException
{
return executeSimpleCommand(String.format("UID SEARCH UID %s" + (includeDeleted ? "" : " NOT DELETED"), Utility.combine(mesgUids.toArray(), ',')));
}
};
return search(searcher, listener);
}
private Message[] search(ImapSearcher searcher, MessageRetrievalListener listener) throws MessagingException
{
checkOpen();
ArrayList<Message> messages = new ArrayList<Message>();
try
{
ArrayList<Integer> uids = new ArrayList<Integer>();
List<ImapResponse> responses = searcher.search();
for (ImapResponse response : responses)
{
if (response.mTag == null)
{
if (ImapResponseParser.equalsIgnoreCase(response.get(0), "SEARCH"))
{
for (int i = 1, count = response.size(); i < count; i++)
{
uids.add(Integer.parseInt(response.getString(i)));
}
}
}
}
// Sort the uids in numerically ascending order
Collections.sort(uids);
for (int i = 0, count = uids.size(); i < count; i++)
{
if (listener != null)
{
listener.messageStarted("" + uids.get(i), i, count);
}
ImapMessage message = new ImapMessage("" + uids.get(i), this);
messages.add(message);
if (listener != null)
{
listener.messageFinished(message, i, count);
}
}
}
catch (IOException ioe)
{
throw ioExceptionHandler(mConnection, ioe);
}
return messages.toArray(new Message[] {});
}
@Override
public Message[] getMessages(MessageRetrievalListener listener) throws MessagingException
{
return getMessages(null, listener);
}
@Override
public Message[] getMessages(String[] uids, MessageRetrievalListener listener)
throws MessagingException
{
checkOpen();
ArrayList<Message> messages = new ArrayList<Message>();
try
{
if (uids == null)
{
List<ImapResponse> responses = executeSimpleCommand("UID SEARCH 1:* NOT DELETED");
ArrayList<String> tempUids = new ArrayList<String>();
for (ImapResponse response : responses)
{
if (ImapResponseParser.equalsIgnoreCase(response.get(0), "SEARCH"))
{
for (int i = 1, count = response.size(); i < count; i++)
{
tempUids.add(response.getString(i));
}
}
}
uids = tempUids.toArray(new String[] {});
}
for (int i = 0, count = uids.length; i < count; i++)
{
if (listener != null)
{
listener.messageStarted(uids[i], i, count);
}
ImapMessage message = new ImapMessage(uids[i], this);
messages.add(message);
if (listener != null)
{
listener.messageFinished(message, i, count);
}
}
}
catch (IOException ioe)
{
throw ioExceptionHandler(mConnection, ioe);
}
return messages.toArray(new Message[] {});
}
@Override
public void fetch(Message[] messages, FetchProfile fp, MessageRetrievalListener listener)
throws MessagingException
{
if (messages == null || messages.length == 0)
{
return;
}
checkOpen();
String[] uids = new String[messages.length];
HashMap<String, Message> messageMap = new HashMap<String, Message>();
for (int i = 0, count = messages.length; i < count; i++)
{
uids[i] = messages[i].getUid();
messageMap.put(uids[i], messages[i]);
}
/*
* Figure out what command we are going to run:
* Flags - UID FETCH (FLAGS)
* Envelope - UID FETCH ([FLAGS] INTERNALDATE UID RFC822.SIZE FLAGS BODY.PEEK[HEADER.FIELDS (date subject from content-type to cc)])
*
*/
LinkedHashSet<String> fetchFields = new LinkedHashSet<String>();
fetchFields.add("UID");
if (fp.contains(FetchProfile.Item.FLAGS))
{
fetchFields.add("FLAGS");
}
if (fp.contains(FetchProfile.Item.ENVELOPE))
{
fetchFields.add("INTERNALDATE");
fetchFields.add("RFC822.SIZE");
fetchFields.add("BODY.PEEK[HEADER.FIELDS (date subject from content-type to cc reply-to "
+ K9.K9MAIL_IDENTITY + ")]");
}
if (fp.contains(FetchProfile.Item.STRUCTURE))
{
fetchFields.add("BODYSTRUCTURE");
}
if (fp.contains(FetchProfile.Item.BODY_SANE))
{
fetchFields.add(String.format("BODY.PEEK[]<0.%d>", FETCH_BODY_SANE_SUGGESTED_SIZE));
}
if (fp.contains(FetchProfile.Item.BODY))
{
fetchFields.add("BODY.PEEK[]");
}
try
{
mConnection.sendCommand(String.format("UID FETCH %s (%s)",
Utility.combine(uids, ','),
Utility.combine(fetchFields.toArray(new String[fetchFields.size()]), ' ')
), false);
ImapResponse response;
int messageNumber = 0;
ImapResponseParser.IImapResponseCallback callback = null;
if (fp.contains(FetchProfile.Item.BODY) || fp.contains(FetchProfile.Item.BODY_SANE) || fp.contains(FetchProfile.Item.ENVELOPE))
{
callback = new FetchBodyCallback(messageMap);
}
do
{
response = mConnection.readResponse(callback);
if (response.mTag == null && ImapResponseParser.equalsIgnoreCase(response.get(1), "FETCH"))
{
ImapList fetchList = (ImapList)response.getKeyedValue("FETCH");
String uid = fetchList.getKeyedString("UID");
int msgSeq = response.getNumber(0);
if (uid != null)
{
try
{
msgSeqUidMap.put(msgSeq, uid);
if (K9.DEBUG)
{
Log.v(K9.LOG_TAG, "Stored uid '" + uid + "' for msgSeq " + msgSeq + " into map " /*+ msgSeqUidMap.toString() */);
}
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Unable to store uid '" + uid + "' for msgSeq " + msgSeq);
}
}
Message message = messageMap.get(uid);
if (message == null)
{
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Do not have message in messageMap for UID " + uid + " for " + getLogId());
handleUntaggedResponse(response);
continue;
}
if (listener != null)
{
listener.messageStarted(uid, messageNumber++, messageMap.size());
}
ImapMessage imapMessage = (ImapMessage) message;
Object literal = handleFetchResponse(imapMessage, fetchList);
if (literal != null)
{
if (literal instanceof String)
{
String bodyString = (String)literal;
InputStream bodyStream = new ByteArrayInputStream(bodyString.getBytes());
imapMessage.parse(bodyStream);
}
else if (literal instanceof Integer)
{
// All the work was done in FetchBodyCallback.foundLiteral()
}
else
{
// This shouldn't happen
throw new MessagingException("Got FETCH response with bogus parameters");
}
}
if (listener != null)
{
listener.messageFinished(message, messageNumber, messageMap.size());
}
}
else
{
handleUntaggedResponse(response);
}
while (response.more());
}
while (response.mTag == null);
}
catch (IOException ioe)
{
throw ioExceptionHandler(mConnection, ioe);
}
}
@Override
public void fetchPart(Message message, Part part, MessageRetrievalListener listener)
throws MessagingException
{
checkOpen();
String[] parts = part.getHeader(MimeHeader.HEADER_ANDROID_ATTACHMENT_STORE_DATA);
if (parts == null)
{
return;
}
String fetch;
String partId = parts[0];
if ("TEXT".equalsIgnoreCase(partId))
{
fetch = String.format("BODY.PEEK[TEXT]<0.%d>", FETCH_BODY_SANE_SUGGESTED_SIZE);
}
else
{
fetch = String.format("BODY.PEEK[%s]", partId);
}
try
{
mConnection.sendCommand(
String.format("UID FETCH %s (UID %s)", message.getUid(), fetch),
false);
ImapResponse response;
int messageNumber = 0;
ImapResponseParser.IImapResponseCallback callback = new FetchPartCallback(part);
do
{
response = mConnection.readResponse(callback);
if ((response.mTag == null) &&
(ImapResponseParser.equalsIgnoreCase(response.get(1), "FETCH")))
{
ImapList fetchList = (ImapList)response.getKeyedValue("FETCH");
String uid = fetchList.getKeyedString("UID");
if (!message.getUid().equals(uid))
{
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Did not ask for UID " + uid + " for " + getLogId());
handleUntaggedResponse(response);
continue;
}
if (listener != null)
{
listener.messageStarted(uid, messageNumber++, 1);
}
ImapMessage imapMessage = (ImapMessage) message;
Object literal = handleFetchResponse(imapMessage, fetchList);
if (literal != null)
{
if (literal instanceof Body)
{
// Most of the work was done in FetchAttchmentCallback.foundLiteral()
part.setBody((Body)literal);
}
else if (literal instanceof String)
{
String bodyString = (String)literal;
InputStream bodyStream = new ByteArrayInputStream(bodyString.getBytes());
String contentTransferEncoding = part.getHeader(
MimeHeader.HEADER_CONTENT_TRANSFER_ENCODING)[0];
part.setBody(MimeUtility.decodeBody(bodyStream, contentTransferEncoding));
}
else
{
// This shouldn't happen
throw new MessagingException("Got FETCH response with bogus parameters");
}
}
if (listener != null)
{
listener.messageFinished(message, messageNumber, 1);
}
}
else
{
handleUntaggedResponse(response);
}
while (response.more());
}
while (response.mTag == null);
}
catch (IOException ioe)
{
throw ioExceptionHandler(mConnection, ioe);
}
}
// Returns value of body field
private Object handleFetchResponse(ImapMessage message, ImapList fetchList) throws MessagingException
{
Object result = null;
if (fetchList.containsKey("FLAGS"))
{
ImapList flags = fetchList.getKeyedList("FLAGS");
if (flags != null)
{
for (int i = 0, count = flags.size(); i < count; i++)
{
String flag = flags.getString(i);
if (flag.equalsIgnoreCase("\\Deleted"))
{
message.setFlagInternal(Flag.DELETED, true);
}
else if (flag.equalsIgnoreCase("\\Answered"))
{
message.setFlagInternal(Flag.ANSWERED, true);
}
else if (flag.equalsIgnoreCase("\\Seen"))
{
message.setFlagInternal(Flag.SEEN, true);
}
else if (flag.equalsIgnoreCase("\\Flagged"))
{
message.setFlagInternal(Flag.FLAGGED, true);
}
}
}
}
if (fetchList.containsKey("INTERNALDATE"))
{
Date internalDate = fetchList.getKeyedDate("INTERNALDATE");
message.setInternalDate(internalDate);
}
if (fetchList.containsKey("RFC822.SIZE"))
{
int size = fetchList.getKeyedNumber("RFC822.SIZE");
message.setSize(size);
}
if (fetchList.containsKey("BODYSTRUCTURE"))
{
ImapList bs = fetchList.getKeyedList("BODYSTRUCTURE");
if (bs != null)
{
try
{
parseBodyStructure(bs, message, "TEXT");
}
catch (MessagingException e)
{
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Error handling message for " + getLogId(), e);
message.setBody(null);
}
}
}
if (fetchList.containsKey("BODY"))
{
int index = fetchList.getKeyIndex("BODY") + 2;
result = fetchList.getObject(index);
// Check if there's an origin octet
if (result instanceof String)
{
String originOctet = (String)result;
if (originOctet.startsWith("<"))
{
result = fetchList.getObject(index + 1);
}
}
}
return result;
}
@Override
public Flag[] getPermanentFlags() throws MessagingException
{
return PERMANENT_FLAGS;
}
/**
* Handle any untagged responses that the caller doesn't care to handle themselves.
* @param responses
*/
protected List<ImapResponse> handleUntaggedResponses(List<ImapResponse> responses)
{
for (ImapResponse response : responses)
{
handleUntaggedResponse(response);
}
return responses;
}
protected void handlePossibleUidNext(ImapResponse response)
{
if (ImapResponseParser.equalsIgnoreCase(response.get(0), "OK") && response.size() > 1)
{
Object bracketedObj = response.get(1);
if (bracketedObj instanceof ImapList)
{
ImapList bracketed = (ImapList)bracketedObj;
if (bracketed.size() > 1)
{
Object keyObj = bracketed.get(0);
if (keyObj instanceof String)
{
String key = (String)keyObj;
if ("UIDNEXT".equalsIgnoreCase(key))
{
uidNext = bracketed.getNumber(1);
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Got UidNext = " + uidNext + " for " + getLogId());
}
}
}
}
}
}
/**
* Handle an untagged response that the caller doesn't care to handle themselves.
* @param response
*/
protected void handleUntaggedResponse(ImapResponse response)
{
if (response.mTag == null && response.size() > 1)
{
if (ImapResponseParser.equalsIgnoreCase(response.get(1), "EXISTS"))
{
mMessageCount = response.getNumber(0);
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Got untagged EXISTS with value " + mMessageCount + " for " + getLogId());
}
handlePossibleUidNext(response);
if (ImapResponseParser.equalsIgnoreCase(response.get(1), "EXPUNGE") && mMessageCount > 0)
{
mMessageCount
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Got untagged EXPUNGE with mMessageCount " + mMessageCount + " for " + getLogId());
}
// if (response.size() > 1) {
// Object bracketedObj = response.get(1);
// if (bracketedObj instanceof ImapList)
// ImapList bracketed = (ImapList)bracketedObj;
// if (bracketed.size() > 0)
// Object keyObj = bracketed.get(0);
// if (keyObj instanceof String)
// String key = (String)keyObj;
// if ("ALERT".equalsIgnoreCase(key))
// StringBuffer sb = new StringBuffer();
// for (int i = 2, count = response.size(); i < count; i++) {
// sb.append(response.get(i).toString());
// sb.append(' ');
// Log.w(K9.LOG_TAG, "ALERT: " + sb.toString() + " for " + getLogId());
}
//Log.i(K9.LOG_TAG, "mMessageCount = " + mMessageCount + " for " + getLogId());
}
private void parseBodyStructure(ImapList bs, Part part, String id)
throws MessagingException
{
if (bs.get(0) instanceof ImapList)
{
* This is a multipart/*
*/
MimeMultipart mp = new MimeMultipart();
for (int i = 0, count = bs.size(); i < count; i++)
{
if (bs.get(i) instanceof ImapList)
{
/*
* For each part in the message we're going to add a new BodyPart and parse
* into it.
*/
ImapBodyPart bp = new ImapBodyPart();
if (id.equalsIgnoreCase("TEXT"))
{
parseBodyStructure(bs.getList(i), bp, Integer.toString(i + 1));
}
else
{
parseBodyStructure(bs.getList(i), bp, id + "." + (i + 1));
}
mp.addBodyPart(bp);
}
else
{
/*
* We've got to the end of the children of the part, so now we can find out
* what type it is and bail out.
*/
String subType = bs.getString(i);
mp.setSubType(subType.toLowerCase());
break;
}
}
part.setBody(mp);
}
else
{
/*
* This is a body. We need to add as much information as we can find out about
* it to the Part.
*/
/*
body type
body subtype
body parameter parenthesized list
body id
body description
body encoding
body size
*/
String type = bs.getString(0);
String subType = bs.getString(1);
String mimeType = (type + "/" + subType).toLowerCase();
ImapList bodyParams = null;
if (bs.get(2) instanceof ImapList)
{
bodyParams = bs.getList(2);
}
String encoding = bs.getString(5);
int size = bs.getNumber(6);
if (MimeUtility.mimeTypeMatches(mimeType, "message/rfc822"))
{
// A body type of type MESSAGE and subtype RFC822
// contains, immediately after the basic fields, the
// envelope structure, body structure, and size in
// text lines of the encapsulated message.
// [MESSAGE, RFC822, [NAME, Fwd: [#HTR-517941]: update plans at 1am Friday - Memory allocation - displayware.eml], NIL, NIL, 7BIT, 5974, NIL, [INLINE, [FILENAME*0, Fwd: [#HTR-517941]: update plans at 1am Friday - Memory all, FILENAME*1, ocation - displayware.eml]], NIL]
/*
* This will be caught by fetch and handled appropriately.
*/
throw new MessagingException("BODYSTRUCTURE message/rfc822 not yet supported.");
}
/*
* Set the content type with as much information as we know right now.
*/
String contentType = String.format("%s", mimeType);
if (bodyParams != null)
{
/*
* If there are body params we might be able to get some more information out
* of them.
*/
for (int i = 0, count = bodyParams.size(); i < count; i += 2)
{
contentType += String.format(";\n %s=\"%s\"",
bodyParams.getString(i),
bodyParams.getString(i + 1));
}
}
part.setHeader(MimeHeader.HEADER_CONTENT_TYPE, contentType);
// Extension items
ImapList bodyDisposition = null;
if (("text".equalsIgnoreCase(type))
&& (bs.size() > 8)
&& (bs.get(9) instanceof ImapList))
{
bodyDisposition = bs.getList(9);
}
else if (!("text".equalsIgnoreCase(type))
&& (bs.size() > 7)
&& (bs.get(8) instanceof ImapList))
{
bodyDisposition = bs.getList(8);
}
String contentDisposition = "";
if (bodyDisposition != null && bodyDisposition.size() > 0)
{
if (!"NIL".equalsIgnoreCase(bodyDisposition.getString(0)))
{
contentDisposition = bodyDisposition.getString(0).toLowerCase();
}
if ((bodyDisposition.size() > 1)
&& (bodyDisposition.get(1) instanceof ImapList))
{
ImapList bodyDispositionParams = bodyDisposition.getList(1);
/*
* If there is body disposition information we can pull some more information
* about the attachment out.
*/
for (int i = 0, count = bodyDispositionParams.size(); i < count; i += 2)
{
contentDisposition += String.format(";\n %s=\"%s\"",
bodyDispositionParams.getString(i).toLowerCase(),
bodyDispositionParams.getString(i + 1));
}
}
}
if (MimeUtility.getHeaderParameter(contentDisposition, "size") == null)
{
contentDisposition += String.format(";\n size=%d", size);
}
/*
* Set the content disposition containing at least the size. Attachment
* handling code will use this down the road.
*/
part.setHeader(MimeHeader.HEADER_CONTENT_DISPOSITION, contentDisposition);
/*
* Set the Content-Transfer-Encoding header. Attachment code will use this
* to parse the body.
*/
part.setHeader(MimeHeader.HEADER_CONTENT_TRANSFER_ENCODING, encoding);
if (part instanceof ImapMessage)
{
((ImapMessage) part).setSize(size);
}
else if (part instanceof ImapBodyPart)
{
((ImapBodyPart) part).setSize(size);
}
else
{
throw new MessagingException("Unknown part type " + part.toString());
}
part.setHeader(MimeHeader.HEADER_ANDROID_ATTACHMENT_STORE_DATA, id);
}
}
/**
* Appends the given messages to the selected folder. This implementation also determines
* the new UID of the given message on the IMAP server and sets the Message's UID to the
* new server UID.
*/
@Override
public void appendMessages(Message[] messages) throws MessagingException
{
checkOpen();
try
{
for (Message message : messages)
{
CountingOutputStream out = new CountingOutputStream();
EOLConvertingOutputStream eolOut = new EOLConvertingOutputStream(out);
message.writeTo(eolOut);
eolOut.flush();
mConnection.sendCommand(
String.format("APPEND \"%s\" (%s) {%d}",
encodeFolderName(getPrefixedName()),
combineFlags(message.getFlags()),
out.getCount()), false);
ImapResponse response;
do
{
response = mConnection.readResponse();
handleUntaggedResponse(response);
if (response.mCommandContinuationRequested)
{
eolOut = new EOLConvertingOutputStream(mConnection.mOut);
message.writeTo(eolOut);
eolOut.write('\r');
eolOut.write('\n');
eolOut.flush();
}
while (response.more());
}
while (response.mTag == null);
String newUid = getUidFromMessageId(message);
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Got UID " + newUid + " for message for " + getLogId());
if (newUid != null)
{
message.setUid(newUid);
}
}
}
catch (IOException ioe)
{
throw ioExceptionHandler(mConnection, ioe);
}
}
@Override
public String getUidFromMessageId(Message message) throws MessagingException
{
try
{
/*
* Try to find the UID of the message we just appended using the
* Message-ID header.
*/
String[] messageIdHeader = message.getHeader("Message-ID");
if (messageIdHeader == null || messageIdHeader.length == 0)
{
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Did not get a message-id in order to search for UID for " + getLogId());
return null;
}
String messageId = messageIdHeader[0];
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Looking for UID for message with message-id " + messageId + " for " + getLogId());
List<ImapResponse> responses =
executeSimpleCommand(
String.format("UID SEARCH HEADER MESSAGE-ID %s", messageId));
for (ImapResponse response1 : responses)
{
if (response1.mTag == null && ImapResponseParser.equalsIgnoreCase(response1.get(0), "SEARCH")
&& response1.size() > 1)
{
return response1.getString(1);
}
}
return null;
}
catch (IOException ioe)
{
throw new MessagingException("Could not find UID for message based on Message-ID", ioe);
}
}
@Override
public void expunge() throws MessagingException
{
checkOpen();
try
{
executeSimpleCommand("EXPUNGE");
}
catch (IOException ioe)
{
throw ioExceptionHandler(mConnection, ioe);
}
}
private String combineFlags(Flag[] flags)
{
ArrayList<String> flagNames = new ArrayList<String>();
for (int i = 0, count = flags.length; i < count; i++)
{
Flag flag = flags[i];
if (flag == Flag.SEEN)
{
flagNames.add("\\Seen");
}
else if (flag == Flag.DELETED)
{
flagNames.add("\\Deleted");
}
else if (flag == Flag.ANSWERED)
{
flagNames.add("\\Answered");
}
else if (flag == Flag.FLAGGED)
{
flagNames.add("\\Flagged");
}
}
return Utility.combine(flagNames.toArray(new String[flagNames.size()]), ' ');
}
@Override
public void setFlags(Flag[] flags, boolean value)
throws MessagingException
{
checkOpen();
try
{
executeSimpleCommand(String.format("UID STORE 1:* %sFLAGS.SILENT (%s)",
value ? "+" : "-", combineFlags(flags)));
}
catch (IOException ioe)
{
throw ioExceptionHandler(mConnection, ioe);
}
}
@Override
public String getNewPushState(String oldPushStateS, Message message)
{
try
{
String messageUidS = message.getUid();
int messageUid = Integer.parseInt(messageUidS);
ImapPushState oldPushState = ImapPushState.parse(oldPushStateS);
if (messageUid >= oldPushState.uidNext)
{
int uidNext = messageUid + 1;
ImapPushState newPushState = new ImapPushState(uidNext);
return newPushState.toString();
}
else
{
return null;
}
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Exception while updated push state for " + getLogId(), e);
return null;
}
}
@Override
public void setFlags(Message[] messages, Flag[] flags, boolean value)
throws MessagingException
{
checkOpen();
String[] uids = new String[messages.length];
for (int i = 0, count = messages.length; i < count; i++)
{
uids[i] = messages[i].getUid();
}
ArrayList<String> flagNames = new ArrayList<String>();
for (int i = 0, count = flags.length; i < count; i++)
{
Flag flag = flags[i];
if (flag == Flag.SEEN)
{
flagNames.add("\\Seen");
}
else if (flag == Flag.DELETED)
{
flagNames.add("\\Deleted");
}
else if (flag == Flag.ANSWERED)
{
flagNames.add("\\Answered");
}
else if (flag == Flag.FLAGGED)
{
flagNames.add("\\Flagged");
}
}
try
{
executeSimpleCommand(String.format("UID STORE %s %sFLAGS.SILENT (%s)",
Utility.combine(uids, ','),
value ? "+" : "-",
Utility.combine(flagNames.toArray(new String[flagNames.size()]), ' ')));
}
catch (IOException ioe)
{
throw ioExceptionHandler(mConnection, ioe);
}
}
private void checkOpen() throws MessagingException
{
if (!isOpen())
{
throw new MessagingException("Folder " + getPrefixedName() + " is not open.");
}
}
private MessagingException ioExceptionHandler(ImapConnection connection, IOException ioe)
throws MessagingException
{
Log.e(K9.LOG_TAG, "IOException for " + getLogId(), ioe);
connection.close();
close();
return new MessagingException("IO Error", ioe);
}
@Override
public boolean equals(Object o)
{
if (o instanceof ImapFolder)
{
return ((ImapFolder)o).getName().equalsIgnoreCase(getName());
}
return super.equals(o);
}
@Override
public int hashCode()
{
return getName().hashCode();
}
protected ImapStore getStore()
{
return store;
}
protected String getLogId()
{
String id = getAccount().getDescription() + ":" + getName() + "/" + Thread.currentThread().getName();
if (mConnection != null)
{
id += "/" + mConnection.getLogId();
}
return id;
}
}
/**
* A cacheable class that stores the details for a single IMAP connection.
*/
class ImapConnection
{
private Socket mSocket;
private PeekableInputStream mIn;
private OutputStream mOut;
private ImapResponseParser mParser;
private int mNextCommandTag;
protected Set<String> capabilities = new HashSet<String>();
private String getLogId()
{
return "conn" + hashCode();
}
private List<ImapResponse> receiveCapabilities(List<ImapResponse> responses)
{
for (ImapResponse response : responses)
{
ImapList capabilityList = null;
if (response.size() > 0 && ImapResponseParser.equalsIgnoreCase(response.get(0), "OK"))
{
for (Object thisPart : response)
{
if (thisPart instanceof ImapList)
{
ImapList thisList = (ImapList)thisPart;
if (ImapResponseParser.equalsIgnoreCase(thisList.get(0), CAPABILITY_CAPABILITY))
{
capabilityList = thisList;
break;
}
}
}
}
else if (response.mTag == null)
{
capabilityList = response;
}
if (capabilityList != null)
{
if (capabilityList.size() > 0 && ImapResponseParser.equalsIgnoreCase(capabilityList.get(0), CAPABILITY_CAPABILITY))
{
if (K9.DEBUG)
{
Log.d(K9.LOG_TAG, "Saving " + capabilityList.size() + " capabilities for " + getLogId());
}
for (Object capability : capabilityList)
{
if (capability instanceof String)
{
// if (K9.DEBUG)
// Log.v(K9.LOG_TAG, "Saving capability '" + capability + "' for " + getLogId());
capabilities.add(((String)capability).toUpperCase());
}
}
}
}
}
return responses;
}
public void open() throws IOException, MessagingException
{
if (isOpen())
{
return;
}
boolean authSuccess = false;
mNextCommandTag = 1;
try
{
Security.setProperty("networkaddress.cache.ttl", "0");
}
catch (Exception e)
{
Log.w(K9.LOG_TAG, "Could not set DNS ttl to 0 for " + getLogId(), e);
}
try
{
SocketAddress socketAddress = new InetSocketAddress(mHost, mPort);
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Connection " + getLogId() + " connecting to " + mHost + " @ IP addr " + socketAddress);
if (mConnectionSecurity == CONNECTION_SECURITY_SSL_REQUIRED ||
mConnectionSecurity == CONNECTION_SECURITY_SSL_OPTIONAL)
{
SSLContext sslContext = SSLContext.getInstance("TLS");
final boolean secure = mConnectionSecurity == CONNECTION_SECURITY_SSL_REQUIRED;
sslContext.init(null, new TrustManager[]
{
TrustManagerFactory.get(mHost, secure)
}, new SecureRandom());
mSocket = sslContext.getSocketFactory().createSocket();
mSocket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT);
}
else
{
mSocket = new Socket();
mSocket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT);
}
setReadTimeout(Store.SOCKET_READ_TIMEOUT);
mIn = new PeekableInputStream(new BufferedInputStream(mSocket.getInputStream(),
1024));
mParser = new ImapResponseParser(mIn);
mOut = mSocket.getOutputStream();
capabilities.clear();
ImapResponse nullResponse = mParser.readResponse();
if (K9.DEBUG)
Log.v(K9.LOG_TAG, getLogId() + "<<<" + nullResponse);
List<ImapResponse> nullResponses = new LinkedList<ImapResponse>();
nullResponses.add(nullResponse);
receiveCapabilities(nullResponses);
if (hasCapability(CAPABILITY_CAPABILITY) == false)
{
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Did not get capabilities in banner, requesting CAPABILITY for " + getLogId());
List<ImapResponse> responses = receiveCapabilities(executeSimpleCommand(COMMAND_CAPABILITY));
if (responses.size() != 2)
{
throw new MessagingException("Invalid CAPABILITY response received");
}
}
if (mConnectionSecurity == CONNECTION_SECURITY_TLS_OPTIONAL
|| mConnectionSecurity == CONNECTION_SECURITY_TLS_REQUIRED)
{
if (hasCapability("STARTTLS"))
{
// STARTTLS
executeSimpleCommand("STARTTLS");
SSLContext sslContext = SSLContext.getInstance("TLS");
boolean secure = mConnectionSecurity == CONNECTION_SECURITY_TLS_REQUIRED;
sslContext.init(null, new TrustManager[]
{
TrustManagerFactory.get(mHost, secure)
}, new SecureRandom());
mSocket = sslContext.getSocketFactory().createSocket(mSocket, mHost, mPort,
true);
mSocket.setSoTimeout(Store.SOCKET_READ_TIMEOUT);
mIn = new PeekableInputStream(new BufferedInputStream(mSocket
.getInputStream(), 1024));
mParser = new ImapResponseParser(mIn);
mOut = mSocket.getOutputStream();
}
else if (mConnectionSecurity == CONNECTION_SECURITY_TLS_REQUIRED)
{
throw new MessagingException("TLS not supported but required");
}
}
mOut = new BufferedOutputStream(mOut, 1024);
try
{
if (mHost.endsWith("yahoo.com"))
{
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "Found Yahoo! account. Sending proprietary commands.");
executeSimpleCommand("ID (\"GUID\" \"1\")");
}
if (mAuthType == AuthType.CRAM_MD5)
{
authCramMD5();
// The authCramMD5 method called on the previous line does not allow for handling updated capabilities
// sent by the server. So, to make sure we update to the post-authentication capability list
// we fetch the capabilities here.
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Updating capabilities after CRAM-MD5 authentication for " + getLogId());
List<ImapResponse> responses = receiveCapabilities(executeSimpleCommand(COMMAND_CAPABILITY));
if (responses.size() != 2)
{
throw new MessagingException("Invalid CAPABILITY response received");
}
}
else if (mAuthType == AuthType.PLAIN)
{
receiveCapabilities(executeSimpleCommand("LOGIN \"" + escapeString(mUsername) + "\" \"" + escapeString(mPassword) + "\"", true));
}
authSuccess = true;
}
catch (ImapException ie)
{
throw new AuthenticationFailedException(ie.getAlertText(), ie);
}
catch (MessagingException me)
{
throw new AuthenticationFailedException(null, me);
}
if (K9.DEBUG)
{
Log.d(K9.LOG_TAG, CAPABILITY_COMPRESS_DEFLATE + " = " + hasCapability(CAPABILITY_COMPRESS_DEFLATE));
}
if (hasCapability(CAPABILITY_COMPRESS_DEFLATE))
{
ConnectivityManager connectivityManager = (ConnectivityManager)K9.app.getSystemService(Context.CONNECTIVITY_SERVICE);
boolean useCompression = true;
NetworkInfo netInfo = connectivityManager.getActiveNetworkInfo();
if (netInfo != null)
{
int type = netInfo.getType();
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "On network type " + type);
useCompression = mAccount.useCompression(type);
}
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "useCompression " + useCompression);
if (useCompression)
{
try
{
executeSimpleCommand(COMMAND_COMPRESS_DEFLATE);
ZInputStream zInputStream = new ZInputStream(mSocket.getInputStream(), true);
zInputStream.setFlushMode(JZlib.Z_PARTIAL_FLUSH);
mIn = new PeekableInputStream(new BufferedInputStream(zInputStream, 1024));
mParser = new ImapResponseParser(mIn);
ZOutputStream zOutputStream = new ZOutputStream(mSocket.getOutputStream(), JZlib.Z_BEST_SPEED, true);
mOut = new BufferedOutputStream(zOutputStream, 1024);
zOutputStream.setFlushMode(JZlib.Z_PARTIAL_FLUSH);
if (K9.DEBUG)
{
Log.i(K9.LOG_TAG, "Compression enabled for " + getLogId());
}
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Unable to negotiate compression", e);
}
}
}
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "NAMESPACE = " + hasCapability(CAPABILITY_NAMESPACE)
+ ", mPathPrefix = " + mPathPrefix);
if (mPathPrefix == null)
{
if (hasCapability(CAPABILITY_NAMESPACE))
{
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "mPathPrefix is unset and server has NAMESPACE capability");
List<ImapResponse> namespaceResponses =
executeSimpleCommand(COMMAND_NAMESPACE);
for (ImapResponse response : namespaceResponses)
{
if (ImapResponseParser.equalsIgnoreCase(response.get(0), COMMAND_NAMESPACE))
{
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Got NAMESPACE response " + response + " on " + getLogId());
Object personalNamespaces = response.get(1);
if (personalNamespaces != null && personalNamespaces instanceof ImapList)
{
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Got personal namespaces: " + personalNamespaces);
ImapList bracketed = (ImapList)personalNamespaces;
Object firstNamespace = bracketed.get(0);
if (firstNamespace != null && firstNamespace instanceof ImapList)
{
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Got first personal namespaces: " + firstNamespace);
bracketed = (ImapList)firstNamespace;
mPathPrefix = bracketed.getString(0);
mPathDelimeter = bracketed.getString(1);
mCombinedPrefix = null;
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Got path '" + mPathPrefix + "' and separator '" + mPathDelimeter + "'");
}
}
}
}
}
else
{
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "mPathPrefix is unset but server does not have NAMESPACE capability");
mPathPrefix = "";
}
}
if (mPathDelimeter == null)
{
try
{
List<ImapResponse> nameResponses =
executeSimpleCommand(String.format("LIST \"\" \"\""));
for (ImapResponse response : nameResponses)
{
if (ImapResponseParser.equalsIgnoreCase(response.get(0), "LIST"))
{
mPathDelimeter = response.getString(2);
mCombinedPrefix = null;
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Got path delimeter '" + mPathDelimeter + "' for " + getLogId());
}
}
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Unable to get path delimeter using LIST", e);
}
}
}
catch (SSLException e)
{
throw new CertificateValidationException(e.getMessage(), e);
}
catch (GeneralSecurityException gse)
{
throw new MessagingException(
"Unable to open connection to IMAP server due to security error.", gse);
}
catch (ConnectException ce)
{
String ceMess = ce.getMessage();
String[] tokens = ceMess.split("-");
if (tokens != null && tokens.length > 1 && tokens[1] != null)
{
Log.e(K9.LOG_TAG, "Stripping host/port from ConnectionException for " + getLogId(), ce);
throw new ConnectException(tokens[1].trim());
}
else
{
throw ce;
}
}
finally
{
if (authSuccess == false)
{
Log.e(K9.LOG_TAG, "Failed to login, closing connection for " + getLogId());
close();
}
}
}
protected void authCramMD5() throws AuthenticationFailedException, MessagingException
{
try
{
String tag = sendCommand("AUTHENTICATE CRAM-MD5", false);
byte[] buf = new byte[ 1024 ];
int b64NonceLen = 0;
for (int i = 0; i < buf.length; i++)
{
buf[ i ] = (byte)mIn.read();
if (buf[i] == 0x0a)
{
b64NonceLen = i;
break;
}
}
if (b64NonceLen == 0)
{
throw new AuthenticationFailedException("Error negotiating CRAM-MD5: nonce too long.");
}
byte[] b64NonceTrim = new byte[ b64NonceLen - 2 ];
System.arraycopy(buf, 1, b64NonceTrim, 0, b64NonceLen - 2);
byte[] nonce = Base64.decodeBase64(b64NonceTrim);
if (K9.DEBUG)
{
Log.d(K9.LOG_TAG, "Got nonce: " + new String(b64NonceTrim, "US-ASCII"));
Log.d(K9.LOG_TAG, "Plaintext nonce: " + new String(nonce, "US-ASCII"));
}
byte[] ipad = new byte[64];
byte[] opad = new byte[64];
byte[] secretBytes = mPassword.getBytes("US-ASCII");
MessageDigest md = MessageDigest.getInstance("MD5");
if (secretBytes.length > 64)
{
secretBytes = md.digest(secretBytes);
}
System.arraycopy(secretBytes, 0, ipad, 0, secretBytes.length);
System.arraycopy(secretBytes, 0, opad, 0, secretBytes.length);
for (int i = 0; i < ipad.length; i++) ipad[i] ^= 0x36;
for (int i = 0; i < opad.length; i++) opad[i] ^= 0x5c;
md.update(ipad);
byte[] firstPass = md.digest(nonce);
md.update(opad);
byte[] result = md.digest(firstPass);
String plainCRAM = mUsername + " " + new String(Hex.encodeHex(result));
byte[] b64CRAM = Base64.encodeBase64(plainCRAM.getBytes("US-ASCII"));
if (K9.DEBUG)
{
Log.d(K9.LOG_TAG, "Username == " + mUsername);
Log.d(K9.LOG_TAG, "plainCRAM: " + plainCRAM);
Log.d(K9.LOG_TAG, "b64CRAM: " + new String(b64CRAM, "US-ASCII"));
}
mOut.write(b64CRAM);
mOut.write(new byte[] { 0x0d, 0x0a });
mOut.flush();
int respLen = 0;
for (int i = 0; i < buf.length; i++)
{
buf[ i ] = (byte)mIn.read();
if (buf[i] == 0x0a)
{
respLen = i;
break;
}
}
String toMatch = tag + " OK";
String respStr = new String(buf, 0, respLen);
if (!respStr.startsWith(toMatch))
{
throw new AuthenticationFailedException("CRAM-MD5 error: " + respStr);
}
}
catch (IOException ioe)
{
throw new AuthenticationFailedException("CRAM-MD5 Auth Failed.");
}
catch (NoSuchAlgorithmException nsae)
{
throw new AuthenticationFailedException("MD5 Not Available.");
}
}
protected void setReadTimeout(int millis) throws SocketException
{
mSocket.setSoTimeout(millis);
}
protected boolean isIdleCapable()
{
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "Connection " + getLogId() + " has " + capabilities.size() + " capabilities");
return capabilities.contains(CAPABILITY_IDLE);
}
protected boolean hasCapability(String capability)
{
return capabilities.contains(capability.toUpperCase());
}
private boolean isOpen()
{
return (mIn != null && mOut != null && mSocket != null && mSocket.isConnected() && !mSocket.isClosed());
}
private void close()
{
// if (isOpen()) {
// try {
// executeSimpleCommand("LOGOUT");
// } catch (Exception e) {
try
{
mIn.close();
}
catch (Exception e)
{
}
try
{
mOut.close();
}
catch (Exception e)
{
}
try
{
mSocket.close();
}
catch (Exception e)
{
}
mIn = null;
mOut = null;
mSocket = null;
}
private ImapResponse readResponse() throws IOException, MessagingException
{
return readResponse(null);
}
private ImapResponse readResponse(ImapResponseParser.IImapResponseCallback callback) throws IOException, MessagingException
{
try
{
ImapResponse response = mParser.readResponse(callback);
if (K9.DEBUG)
Log.v(K9.LOG_TAG, getLogId() + "<<<" + response);
return response;
}
catch (IOException ioe)
{
close();
throw ioe;
}
}
private String escapeString(String in)
{
if (in == null)
{
return null;
}
String out = in.replaceAll("\\\\", "\\\\\\\\");
out = out.replaceAll("\"", "\\\\\"");
return out;
}
private void sendContinuation(String continuation) throws IOException
{
mOut.write(continuation.getBytes());
mOut.write('\r');
mOut.write('\n');
mOut.flush();
if (K9.DEBUG)
Log.v(K9.LOG_TAG, getLogId() + ">>> " + continuation);
}
public String sendCommand(String command, boolean sensitive)
throws MessagingException, IOException
{
try
{
open();
String tag = Integer.toString(mNextCommandTag++);
String commandToSend = tag + " " + command;
mOut.write(commandToSend.getBytes());
mOut.write('\r');
mOut.write('\n');
mOut.flush();
if (K9.DEBUG)
{
if (sensitive && !K9.DEBUG_SENSITIVE)
{
Log.v(K9.LOG_TAG, getLogId() + ">>> "
+ "[Command Hidden, Enable Sensitive Debug Logging To Show]");
}
else
{
Log.v(K9.LOG_TAG, getLogId() + ">>> " + commandToSend);
}
}
return tag;
}
catch (IOException ioe)
{
close();
throw ioe;
}
catch (ImapException ie)
{
close();
throw ie;
}
catch (MessagingException me)
{
close();
throw me;
}
}
public List<ImapResponse> executeSimpleCommand(String command) throws IOException,
ImapException, MessagingException
{
return executeSimpleCommand(command, false);
}
public List<ImapResponse> executeSimpleCommand(String command, boolean sensitive) throws IOException,
ImapException, MessagingException
{
return executeSimpleCommand(command, sensitive, null);
}
private List<ImapResponse> executeSimpleCommand(String command, boolean sensitive, UntaggedHandler untaggedHandler)
throws IOException, ImapException, MessagingException
{
String commandToLog = command;
if (sensitive && !K9.DEBUG_SENSITIVE)
{
commandToLog = "*sensitive*";
}
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "Sending IMAP command " + commandToLog + " on connection " + getLogId());
String tag = sendCommand(command, sensitive);
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "Sent IMAP command " + commandToLog + " with tag " + tag + " for " + getLogId());
ArrayList<ImapResponse> responses = new ArrayList<ImapResponse>();
ImapResponse response;
do
{
response = mParser.readResponse();
if (K9.DEBUG)
Log.v(K9.LOG_TAG, getLogId() + "<<<" + response);
if (response.mTag != null && response.mTag.equalsIgnoreCase(tag) == false)
{
Log.w(K9.LOG_TAG, "After sending tag " + tag + ", got tag response from previous command " + response + " for " + getLogId());
Iterator<ImapResponse> iter = responses.iterator();
while (iter.hasNext())
{
ImapResponse delResponse = iter.next();
if (delResponse.mTag != null || delResponse.size() < 2
|| (ImapResponseParser.equalsIgnoreCase(delResponse.get(1), "EXISTS") == false && ImapResponseParser.equalsIgnoreCase(delResponse.get(1), "EXPUNGE") == false))
{
iter.remove();
}
}
response.mTag = null;
continue;
}
if (untaggedHandler != null)
{
untaggedHandler.handleAsyncUntaggedResponse(response);
}
responses.add(response);
}
while (response.mTag == null);
if (response.size() < 1 || !ImapResponseParser.equalsIgnoreCase(response.get(0), "OK"))
{
throw new ImapException("Command: " + commandToLog + "; response: " + response.toString(), response.getAlertText());
}
return responses;
}
}
class ImapMessage extends MimeMessage
{
ImapMessage(String uid, Folder folder)
{
this.mUid = uid;
this.mFolder = folder;
}
public void setSize(int size)
{
this.mSize = size;
}
@Override
public void parse(InputStream in) throws IOException, MessagingException
{
super.parse(in);
}
public void setFlagInternal(Flag flag, boolean set) throws MessagingException
{
super.setFlag(flag, set);
}
@Override
public void setFlag(Flag flag, boolean set) throws MessagingException
{
super.setFlag(flag, set);
mFolder.setFlags(new Message[] { this }, new Flag[] { flag }, set);
}
@Override
public void delete(String trashFolderName) throws MessagingException
{
getFolder().delete(new Message[] { this }, trashFolderName);
}
}
class ImapBodyPart extends MimeBodyPart
{
public ImapBodyPart() throws MessagingException
{
super();
}
public void setSize(int size)
{
this.mSize = size;
}
}
class ImapException extends MessagingException
{
String mAlertText;
public ImapException(String message, String alertText, Throwable throwable)
{
super(message, throwable);
this.mAlertText = alertText;
}
public ImapException(String message, String alertText)
{
super(message);
this.mAlertText = alertText;
}
public String getAlertText()
{
return mAlertText;
}
public void setAlertText(String alertText)
{
mAlertText = alertText;
}
}
public class ImapFolderPusher extends ImapFolder implements UntaggedHandler
{
final PushReceiver receiver;
Thread listeningThread = null;
final AtomicBoolean stop = new AtomicBoolean(false);
final AtomicBoolean idling = new AtomicBoolean(false);
final AtomicBoolean doneSent = new AtomicBoolean(false);
final AtomicInteger delayTime = new AtomicInteger(NORMAL_DELAY_TIME);
final AtomicInteger idleFailureCount = new AtomicInteger(0);
final AtomicBoolean needsPoll = new AtomicBoolean(false);
List<ImapResponse> storedUntaggedResponses = new ArrayList<ImapResponse>();
TracingWakeLock wakeLock = null;
public ImapFolderPusher(ImapStore store, String name, PushReceiver nReceiver)
{
super(store, name);
receiver = nReceiver;
TracingPowerManager pm = TracingPowerManager.getPowerManager(receiver.getContext());
wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "ImapFolderPusher " + store.getAccount().getDescription() + ":" + getName());
wakeLock.setReferenceCounted(false);
}
public void refresh() throws IOException, MessagingException
{
if (idling.get())
{
wakeLock.acquire(K9.PUSH_WAKE_LOCK_TIMEOUT);
sendDone();
}
}
private void sendDone() throws IOException, MessagingException
{
if (doneSent.compareAndSet(false, true) == true)
{
mConnection.setReadTimeout(Store.SOCKET_READ_TIMEOUT);
sendContinuation("DONE");
}
}
private void sendContinuation(String continuation)
throws MessagingException, IOException
{
if (mConnection != null)
{
mConnection.sendContinuation(continuation);
}
}
public void start()
{
Runnable runner = new Runnable()
{
public void run()
{
wakeLock.acquire(K9.PUSH_WAKE_LOCK_TIMEOUT);
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Pusher starting for " + getLogId());
while (stop.get() != true)
{
try
{
int oldUidNext = -1;
try
{
String pushStateS = receiver.getPushState(getName());
ImapPushState pushState = ImapPushState.parse(pushStateS);
oldUidNext = pushState.uidNext;
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Got oldUidNext " + oldUidNext + " for " + getLogId());
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Unable to get oldUidNext for " + getLogId(), e);
}
ImapConnection oldConnection = mConnection;
internalOpen(OpenMode.READ_ONLY);
if (mConnection == null)
{
receiver.pushError("Could not establish connection for IDLE", null);
throw new MessagingException("Could not establish connection for IDLE");
}
if (mConnection.isIdleCapable() == false)
{
stop.set(true);
receiver.pushError("IMAP server is not IDLE capable: " + mConnection.toString(), null);
throw new MessagingException("IMAP server is not IDLE capable:" + mConnection.toString());
}
if (mAccount.isPushPollOnConnect() && (mConnection != oldConnection || needsPoll.getAndSet(false) == true))
{
List<ImapResponse> untaggedResponses = new ArrayList<ImapResponse>(storedUntaggedResponses);
storedUntaggedResponses.clear();
processUntaggedResponses(untaggedResponses);
receiver.syncFolder(ImapFolderPusher.this);
}
if (stop.get() == true)
{
continue;
}
int startUid = oldUidNext;
int newUidNext = uidNext;
if (newUidNext == -1)
{
if (K9.DEBUG)
{
Log.d(K9.LOG_TAG, "uidNext is -1, using search to find highest UID");
}
int highestUid = getHighestUid();
if (highestUid != -1)
{
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "highest UID = " + highestUid);
newUidNext = highestUid + 1;
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "highest UID = " + highestUid
+ ", set newUidNext to " + newUidNext);
}
}
if (startUid < newUidNext - mAccount.getDisplayCount())
{
startUid = newUidNext - mAccount.getDisplayCount();
}
if (startUid < 1)
{
startUid = 1;
}
if (newUidNext > startUid)
{
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Needs sync from uid " + startUid + " to " + newUidNext + " for " + getLogId());
List<Message> messages = new ArrayList<Message>();
for (int uid = startUid; uid < newUidNext; uid++)
{
ImapMessage message = new ImapMessage("" + uid, ImapFolderPusher.this);
messages.add(message);
}
if (messages.size() > 0)
{
pushMessages(messages, true);
}
}
else
{
List<ImapResponse> untaggedResponses = null;
while (storedUntaggedResponses.size() > 0)
{
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Processing " + storedUntaggedResponses.size() + " untagged responses from previous commands for " + getLogId());
untaggedResponses = new ArrayList<ImapResponse>(storedUntaggedResponses);
storedUntaggedResponses.clear();
processUntaggedResponses(untaggedResponses);
}
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "About to IDLE for " + getLogId());
receiver.setPushActive(getName(), true);
idling.set(true);
doneSent.set(false);
mConnection.setReadTimeout((getAccount().getIdleRefreshMinutes() * 60 * 1000) + IDLE_READ_TIMEOUT_INCREMENT);
untaggedResponses = executeSimpleCommand(COMMAND_IDLE, false, ImapFolderPusher.this);
idling.set(false);
delayTime.set(NORMAL_DELAY_TIME);
idleFailureCount.set(0);
}
}
catch (Exception e)
{
wakeLock.acquire(K9.PUSH_WAKE_LOCK_TIMEOUT);
storedUntaggedResponses.clear();
idling.set(false);
receiver.setPushActive(getName(), false);
try
{
close();
}
catch (Exception me)
{
Log.e(K9.LOG_TAG, "Got exception while closing for exception for " + getLogId(), me);
}
if (stop.get() == true)
{
Log.i(K9.LOG_TAG, "Got exception while idling, but stop is set for " + getLogId());
}
else
{
receiver.pushError("Push error for " + getName(), e);
Log.e(K9.LOG_TAG, "Got exception while idling for " + getLogId(), e);
int delayTimeInt = delayTime.get();
receiver.sleep(wakeLock, delayTimeInt);
delayTimeInt *= 2;
if (delayTimeInt > MAX_DELAY_TIME)
{
delayTimeInt = MAX_DELAY_TIME;
}
delayTime.set(delayTimeInt);
if (idleFailureCount.incrementAndGet() > IDLE_FAILURE_COUNT_LIMIT)
{
Log.e(K9.LOG_TAG, "Disabling pusher for " + getLogId() + " after " + idleFailureCount.get() + " consecutive errors");
receiver.pushError("Push disabled for " + getName() + " after " + idleFailureCount.get() + " consecutive errors", e);
stop.set(true);
}
}
}
}
receiver.setPushActive(getName(), false);
try
{
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Pusher for " + getLogId() + " is exiting");
close();
}
catch (Exception me)
{
Log.e(K9.LOG_TAG, "Got exception while closing for " + getLogId(), me);
}
finally
{
wakeLock.release();
}
}
};
listeningThread = new Thread(runner);
listeningThread.start();
}
@Override
protected void handleUntaggedResponse(ImapResponse response)
{
if (response.mTag == null && response.size() > 1)
{
Object responseType = response.get(1);
if (ImapResponseParser.equalsIgnoreCase(responseType, "FETCH")
|| ImapResponseParser.equalsIgnoreCase(responseType, "EXPUNGE")
|| ImapResponseParser.equalsIgnoreCase(responseType, "EXISTS"))
{
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Storing response " + response + " for later processing");
storedUntaggedResponses.add(response);
}
handlePossibleUidNext(response);
}
}
protected void processUntaggedResponses(List<ImapResponse> responses) throws MessagingException
{
boolean skipSync = false;
int oldMessageCount = mMessageCount;
if (oldMessageCount == -1)
{
skipSync = true;
}
List<Integer> flagSyncMsgSeqs = new ArrayList<Integer>();
List<String> removeMsgUids = new LinkedList<String>();
for (ImapResponse response : responses)
{
oldMessageCount += processUntaggedResponse(oldMessageCount, response, flagSyncMsgSeqs, removeMsgUids);
}
if (skipSync == false)
{
if (oldMessageCount < 0)
{
oldMessageCount = 0;
}
if (mMessageCount > oldMessageCount)
{
syncMessages(mMessageCount, true);
}
}
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "UIDs for messages needing flag sync are " + flagSyncMsgSeqs + " for " + getLogId());
if (flagSyncMsgSeqs.size() > 0)
{
syncMessages(flagSyncMsgSeqs);
}
if (removeMsgUids.size() > 0)
{
removeMessages(removeMsgUids);
}
}
private void syncMessages(int end, boolean newArrivals) throws MessagingException
{
int oldUidNext = -1;
try
{
String pushStateS = receiver.getPushState(getName());
ImapPushState pushState = ImapPushState.parse(pushStateS);
oldUidNext = pushState.uidNext;
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Got oldUidNext " + oldUidNext + " for " + getLogId());
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Unable to get oldUidNext for " + getLogId(), e);
}
Message[] messageArray = getMessages(end, end, true, null);
if (messageArray != null && messageArray.length > 0)
{
int newUid = Integer.parseInt(messageArray[0].getUid());
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Got newUid " + newUid + " for message " + end + " on " + getLogId());
int startUid = oldUidNext;
if (startUid < newUid - 10)
{
startUid = newUid - 10;
}
if (startUid < 1)
{
startUid = 1;
}
if (newUid >= startUid)
{
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Needs sync from uid " + startUid + " to " + newUid + " for " + getLogId());
List<Message> messages = new ArrayList<Message>();
for (int uid = startUid; uid <= newUid; uid++)
{
ImapMessage message = new ImapMessage("" + uid, ImapFolderPusher.this);
messages.add(message);
}
if (messages.size() > 0)
{
pushMessages(messages, true);
}
}
}
}
private void syncMessages(List<Integer> flagSyncMsgSeqs)
{
try
{
Message[] messageArray = null;
messageArray = getMessages(flagSyncMsgSeqs, true, null);
List<Message> messages = new ArrayList<Message>();
for (Message message : messageArray)
{
messages.add(message);
}
pushMessages(messages, false);
}
catch (Exception e)
{
receiver.pushError("Exception while processing Push untagged responses", e);
}
}
private void removeMessages(List<String> removeUids)
{
List<Message> messages = new ArrayList<Message>(removeUids.size());
try
{
Message[] existingMessages = getMessagesFromUids(removeUids, true, null);
for (Message existingMessage : existingMessages)
{
needsPoll.set(true);
msgSeqUidMap.clear();
String existingUid = existingMessage.getUid();
Log.w(K9.LOG_TAG, "Message with UID " + existingUid + " still exists on server, not expunging");
removeUids.remove(existingUid);
}
for (String uid : removeUids)
{
ImapMessage message = new ImapMessage(uid, this);
try
{
message.setFlagInternal(Flag.DELETED, true);
}
catch (MessagingException me)
{
Log.e(K9.LOG_TAG, "Unable to set DELETED flag on message " + message.getUid());
}
messages.add(message);
}
receiver.messagesRemoved(this, messages);
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Cannot remove EXPUNGEd messages", e);
return;
}
}
protected int processUntaggedResponse(int oldMessageCount, ImapResponse response, List<Integer> flagSyncMsgSeqs, List<String> removeMsgUids)
{
super.handleUntaggedResponse(response);
int messageCountDelta = 0;
if (response.mTag == null && response.size() > 1)
{
try
{
Object responseType = response.get(1);
if (ImapResponseParser.equalsIgnoreCase(responseType, "FETCH"))
{
Log.i(K9.LOG_TAG, "Got FETCH " + response);
int msgSeq = response.getNumber(0);
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Got untagged FETCH for msgseq " + msgSeq + " for " + getLogId());
if (flagSyncMsgSeqs.contains(msgSeq) == false)
{
flagSyncMsgSeqs.add(msgSeq);
}
}
if (ImapResponseParser.equalsIgnoreCase(responseType, "EXPUNGE"))
{
int msgSeq = response.getNumber(0);
if (msgSeq <= oldMessageCount)
{
messageCountDelta = -1;
}
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Got untagged EXPUNGE for msgseq " + msgSeq + " for " + getLogId());
List<Integer> newSeqs = new ArrayList<Integer>();
Iterator<Integer> flagIter = flagSyncMsgSeqs.iterator();
while (flagIter.hasNext())
{
Integer flagMsg = flagIter.next();
if (flagMsg >= msgSeq)
{
flagIter.remove();
if (flagMsg > msgSeq)
{
newSeqs.add(flagMsg
}
}
}
flagSyncMsgSeqs.addAll(newSeqs);
List<Integer> msgSeqs = new ArrayList<Integer>(msgSeqUidMap.keySet());
Collections.sort(msgSeqs); // Have to do comparisons in order because of msgSeq reductions
for (Integer msgSeqNumI : msgSeqs)
{
if (K9.DEBUG)
{
Log.v(K9.LOG_TAG, "Comparing EXPUNGEd msgSeq " + msgSeq + " to " + msgSeqNumI);
}
int msgSeqNum = msgSeqNumI;
if (msgSeqNum == msgSeq)
{
String uid = msgSeqUidMap.get(msgSeqNum);
if (K9.DEBUG)
{
Log.d(K9.LOG_TAG, "Scheduling removal of UID " + uid + " because msgSeq " + msgSeqNum + " was expunged");
}
removeMsgUids.add(uid);
msgSeqUidMap.remove(msgSeqNum);
}
else if (msgSeqNum > msgSeq)
{
String uid = msgSeqUidMap.get(msgSeqNum);
if (K9.DEBUG)
{
Log.d(K9.LOG_TAG, "Reducing msgSeq for UID " + uid + " from " + msgSeqNum + " to " + (msgSeqNum - 1));
}
msgSeqUidMap.remove(msgSeqNum);
msgSeqUidMap.put(msgSeqNum-1, uid);
}
}
}
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Could not handle untagged FETCH for " + getLogId(), e);
}
}
return messageCountDelta;
}
private void pushMessages(List<Message> messages, boolean newArrivals)
{
RuntimeException holdException = null;
try
{
if (newArrivals)
{
receiver.messagesArrived(this, messages);
}
else
{
receiver.messagesFlagsChanged(this, messages);
}
}
catch (RuntimeException e)
{
holdException = e;
}
if (holdException != null)
{
throw holdException;
}
}
public void stop()
{
stop.set(true);
if (listeningThread != null)
{
listeningThread.interrupt();
}
if (mConnection != null)
{
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "Closing mConnection to stop pushing for " + getLogId());
mConnection.close();
}
else
{
Log.w(K9.LOG_TAG, "Attempt to interrupt null mConnection to stop pushing on folderPusher for " + getLogId());
}
}
public void handleAsyncUntaggedResponse(ImapResponse response)
{
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "Got async response: " + response);
if (stop.get() == true)
{
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Got async untagged response: " + response + ", but stop is set for " + getLogId());
try
{
sendDone();
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Exception while sending DONE for " + getLogId(), e);
}
}
else
{
if (response.mTag == null)
{
if (response.size() > 1)
{
boolean started = false;
Object responseType = response.get(1);
if (ImapResponseParser.equalsIgnoreCase(responseType, "EXISTS") || ImapResponseParser.equalsIgnoreCase(responseType, "EXPUNGE") ||
ImapResponseParser.equalsIgnoreCase(responseType,"FETCH"))
{
if (started == false)
{
wakeLock.acquire(K9.PUSH_WAKE_LOCK_TIMEOUT);
started = true;
}
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Got useful async untagged response: " + response + " for " + getLogId());
try
{
sendDone();
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Exception while sending DONE for " + getLogId(), e);
}
}
}
else if (response.mCommandContinuationRequested)
{
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Idling " + getLogId());
wakeLock.release();
}
}
}
}
}
@Override
public Pusher getPusher(PushReceiver receiver)
{
return new ImapPusher(this, receiver);
}
public class ImapPusher implements Pusher
{
final ImapStore mStore;
final PushReceiver mReceiver;
private long lastRefresh = -1;
HashMap<String, ImapFolderPusher> folderPushers = new HashMap<String, ImapFolderPusher>();
public ImapPusher(ImapStore store, PushReceiver receiver)
{
mStore = store;
mReceiver = receiver;
}
public void start(List<String> folderNames)
{
stop();
synchronized (folderPushers)
{
setLastRefresh(System.currentTimeMillis());
for (String folderName : folderNames)
{
ImapFolderPusher pusher = folderPushers.get(folderName);
if (pusher == null)
{
pusher = new ImapFolderPusher(mStore, folderName, mReceiver);
folderPushers.put(folderName, pusher);
pusher.start();
}
}
}
}
public void refresh()
{
synchronized (folderPushers)
{
for (ImapFolderPusher folderPusher : folderPushers.values())
{
try
{
folderPusher.refresh();
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Got exception while refreshing for " + folderPusher.getName(), e);
}
}
}
}
public void stop()
{
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Requested stop of IMAP pusher");
synchronized (folderPushers)
{
for (ImapFolderPusher folderPusher : folderPushers.values())
{
try
{
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Requesting stop of IMAP folderPusher " + folderPusher.getName());
folderPusher.stop();
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Got exception while stopping " + folderPusher.getName(), e);
}
}
folderPushers.clear();
}
}
public int getRefreshInterval()
{
return (getAccount().getIdleRefreshMinutes() * 60 * 1000);
}
public long getLastRefresh()
{
return lastRefresh;
}
public void setLastRefresh(long lastRefresh)
{
this.lastRefresh = lastRefresh;
}
}
private interface UntaggedHandler
{
void handleAsyncUntaggedResponse(ImapResponse respose);
}
protected static class ImapPushState
{
protected int uidNext;
protected ImapPushState(int nUidNext)
{
uidNext = nUidNext;
}
protected static ImapPushState parse(String pushState)
{
int newUidNext = -1;
if (pushState != null)
{
StringTokenizer tokenizer = new StringTokenizer(pushState, ";");
while (tokenizer.hasMoreTokens())
{
StringTokenizer thisState = new StringTokenizer(tokenizer.nextToken(), "=");
if (thisState.hasMoreTokens())
{
String key = thisState.nextToken();
if ("uidNext".equalsIgnoreCase(key) && thisState.hasMoreTokens())
{
String value = thisState.nextToken();
try
{
newUidNext = Integer.parseInt(value);
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Unable to part uidNext value " + value, e);
}
}
}
}
}
return new ImapPushState(newUidNext);
}
@Override
public String toString()
{
return "uidNext=" + uidNext;
}
}
private interface ImapSearcher
{
List<ImapResponse> search() throws IOException, MessagingException;
}
private class FetchBodyCallback implements ImapResponseParser.IImapResponseCallback
{
private HashMap<String, Message> mMessageMap;
FetchBodyCallback(HashMap<String, Message> mesageMap)
{
mMessageMap = mesageMap;
}
@Override
public Object foundLiteral(ImapResponse response,
FixedLengthInputStream literal) throws IOException, Exception
{
if (response.mTag == null &&
ImapResponseParser.equalsIgnoreCase(response.get(1), "FETCH"))
{
ImapList fetchList = (ImapList)response.getKeyedValue("FETCH");
String uid = fetchList.getKeyedString("UID");
ImapMessage message = (ImapMessage) mMessageMap.get(uid);
message.parse(literal);
// Return placeholder object
return new Integer(1);
}
return null;
}
}
private class FetchPartCallback implements ImapResponseParser.IImapResponseCallback
{
private Part mPart;
FetchPartCallback(Part part)
{
mPart = part;
}
@Override
public Object foundLiteral(ImapResponse response,
FixedLengthInputStream literal) throws IOException, Exception
{
if (response.mTag == null &&
ImapResponseParser.equalsIgnoreCase(response.get(1), "FETCH"))
{
//TODO: check for correct UID
String contentTransferEncoding = mPart.getHeader(
MimeHeader.HEADER_CONTENT_TRANSFER_ENCODING)[0];
return MimeUtility.decodeBody(literal, contentTransferEncoding);
}
return null;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.