answer
stringlengths 17
10.2M
|
|---|
package cc.catalysts.boot.report.pdf.config;
import org.apache.fontbox.ttf.NamingTable;
import org.apache.pdfbox.pdmodel.font.PDCIDFontType2;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDType0Font;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.springframework.util.Assert;
import java.awt.*;
import java.util.HashMap;
import java.util.Map;
public class PdfTextStyle {
static Map<String, PDFont> fonts = new HashMap<>();
public static void registerFont(PDType0Font font) {
if(font.getDescendantFont() instanceof PDCIDFontType2) {
PDCIDFontType2 tmpFont = (PDCIDFontType2) font.getDescendantFont();
NamingTable ttfNamingTable = (NamingTable) tmpFont.getTrueTypeFont().getTableMap().get("name");
String fontBaseName = ttfNamingTable.getFontFamily();
String fontStyle = ttfNamingTable.getFontSubFamily();
}
fonts.put(font.getName(), font);
}
/**
* NOTE: this is kind of a hack, but since PdfBox doesn't expose the constructor
* org.apache.pdfbox.pdmodel.font.PDType1Font#PDType1Font(java.lang.String), it is necessary.
*
* @param fontName One of the standard 14 font names defined by PostScript or of a font registered with registerFont(PDFont)
* @return The appropriate PDFont
*/
public static PDFont getFont(String fontName) {
switch(fontName) {
case "Times-Roman": return PDType1Font.TIMES_ROMAN;
case "Times-Bold": return PDType1Font.TIMES_BOLD;
case "Times-Italic": return PDType1Font.TIMES_ITALIC;
case "Times-BoldItalic": return PDType1Font.TIMES_BOLD_ITALIC;
case "Helvetica": return PDType1Font.HELVETICA;
case "Helvetica-Bold": return PDType1Font.HELVETICA_BOLD;
case "Helvetica-Oblique": return PDType1Font.HELVETICA_OBLIQUE;
case "Helvetica-BoldOblique": return PDType1Font.HELVETICA_BOLD_OBLIQUE;
case "Courier": return PDType1Font.COURIER;
case "Courier-Bold": return PDType1Font.COURIER_BOLD;
case "Courier-Oblique": return PDType1Font.COURIER_OBLIQUE;
case "Courier-BoldOblique": return PDType1Font.COURIER_BOLD_OBLIQUE;
case "Symbol": return PDType1Font.SYMBOL;
case "ZapfDingbats": return PDType1Font.ZAPF_DINGBATS;
}
if(fonts.containsKey(fontName)) {
return fonts.get(fontName);
}
throw new IllegalArgumentException("Could not find font " + fontName);
}
private int fontSize;
private PDFont font;
private Color color;
public PdfTextStyle(int fontSize, PDFont defaultFont, Color color) {
this.fontSize = fontSize;
this.font = defaultFont;
this.color = color;
}
public PdfTextStyle(int fontSize, PDType1Font defaultFont, Color color) {
this.fontSize = fontSize;
this.font = defaultFont;
this.color = color;
}
/**
* This constructor is used by spring when creating a font from properties.
*
* @param config e.g. 10,Times-Roman,#000000
*/
public PdfTextStyle(String config) {
Assert.hasText(config);
String[] split = config.split(",");
Assert.isTrue(split.length == 3, "config must look like: 10,Times-Roman,#000000");
fontSize = Integer.parseInt(split[0]);
font = getFont(split[1]);
color = new Color(Integer.valueOf(split[2].substring(1), 16));
}
public int getFontSize() {
return fontSize;
}
public PDFont getFont() {
return font;
}
public Color getColor() {
return color;
}
}
|
package org.gbif.checklistbank.ws.resources;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import com.google.inject.Inject;
import org.gbif.api.model.Constants;
import org.gbif.api.model.checklistbank.*;
import org.gbif.api.model.checklistbank.search.*;
import org.gbif.api.model.common.Identifier;
import org.gbif.api.model.common.paging.Pageable;
import org.gbif.api.model.common.paging.PagingResponse;
import org.gbif.api.model.common.search.SearchResponse;
import org.gbif.api.service.checklistbank.*;
import org.gbif.api.vocabulary.Kingdom;
import org.gbif.api.vocabulary.NameType;
import org.gbif.api.vocabulary.Rank;
import org.gbif.api.vocabulary.ThreatStatus;
import org.gbif.checklistbank.model.IucnRedListCategory;
import org.gbif.checklistbank.model.NubMapping;
import org.gbif.checklistbank.model.TreeContainer;
import org.gbif.checklistbank.model.UsageCount;
import org.gbif.checklistbank.service.mybatis.mapper.DistributionMapper;
import org.gbif.checklistbank.service.mybatis.mapper.NubRelMapper;
import org.gbif.checklistbank.service.mybatis.mapper.UsageCountMapper;
import org.gbif.ws.server.interceptor.NullToNotFound;
import org.gbif.ws.util.ExtraMediaTypes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.util.*;
/**
* Species resource.
*/
@Path("/species")
@Produces({MediaType.APPLICATION_JSON, ExtraMediaTypes.APPLICATION_JAVASCRIPT})
public class SpeciesResource {
private static final Logger LOG = LoggerFactory.getLogger(SpeciesResource.class);
private static final String DATASET_KEY = "datasetKey";
private static final int DEEP_PAGING_OFFSET_LIMIT = 100000;
private static final Set<Integer> iucnKingdoms = Sets.newHashSet(
Kingdom.ANIMALIA.nubUsageKey(),
Kingdom.PLANTAE.nubUsageKey(),
Kingdom.FUNGI.nubUsageKey()
);
private final NameUsageService nameUsageService;
private final VernacularNameService vernacularNameService;
private final TypeSpecimenService typeSpecimenService;
private final SpeciesProfileService speciesProfileService;
private final ReferenceService referenceService;
private final MultimediaService imageService;
private final DescriptionService descriptionService;
private final DistributionService distributionService;
private final IdentifierService identifierService;
private final NameUsageSearchService searchService;
private final UsageCountMapper usageCountMapper;
//Used instead of DistributionService to avoid upgrading GBIF API.
private final DistributionMapper distributionMapper;
private final NubRelMapper nubRelMapper;
@Inject
public SpeciesResource(
NameUsageService nameUsageService, VernacularNameService vernacularNameService,
TypeSpecimenService typeSpecimenService, SpeciesProfileService speciesProfileService,
ReferenceService referenceService, MultimediaService imageService, DescriptionService descriptionService,
DistributionService distributionService, IdentifierService identifierService, NameUsageSearchService searchService,
UsageCountMapper usageCountMapper,
DistributionMapper distributionMapper, NubRelMapper nubRelMapper) {
this.nameUsageService = nameUsageService;
this.vernacularNameService = vernacularNameService;
this.typeSpecimenService = typeSpecimenService;
this.speciesProfileService = speciesProfileService;
this.referenceService = referenceService;
this.imageService = imageService;
this.descriptionService = descriptionService;
this.distributionService = distributionService;
this.identifierService = identifierService;
this.searchService = searchService;
this.usageCountMapper = usageCountMapper;
this.distributionMapper = distributionMapper;
this.nubRelMapper = nubRelMapper;
}
/**
* This retrieves a list of all NameUsage from ChecklistBank.
*
* @param locale identifier for a region
* @param datasetKeys the optional checklist keys to limit paging to
* @param page the limit, offset paging information
* @return requested list of NameUsage or an empty list if none could be found
*/
@GET
public PagingResponse<NameUsage> list(@Context Locale locale, @QueryParam(DATASET_KEY) Set<UUID> datasetKeys,
@QueryParam("sourceId") String sourceId, @QueryParam("name") String canonicalName, @Context Pageable page) {
// limit the maximum allowed offset
checkDeepPaging(page);
if (datasetKeys == null) {
datasetKeys = ImmutableSet.of();
}
if (Strings.isNullOrEmpty(canonicalName)) {
if (datasetKeys.size() > 1) {
throw new IllegalArgumentException("Multiple datasetKey parameters are not allowed");
}
return nameUsageService.list(locale,
datasetKeys.isEmpty() ? null : datasetKeys.iterator().next(), sourceId, page);
} else {
return nameUsageService.listByCanonicalName(locale, canonicalName, page,
datasetKeys.isEmpty() ? null : datasetKeys.toArray(new UUID[datasetKeys.size()]));
}
}
@GET
@Path("mapping")
public List<NubMapping> mappings(@QueryParam(DATASET_KEY) UUID datasetKey) {
if (datasetKey == null) {
throw new IllegalArgumentException("DatasetKey is a required parameter");
}
List<NubMapping> result = new ArrayList<>();
nubRelMapper.process(datasetKey).forEach(result::add);
return result;
}
/**
* This retrieves a NameUsage by its key from ChecklistBank.
*
* @param usageKey NameUsage key
* @param locale identifier for a region
* @return requested NameUsage or null if none could be found. List of NameUsage in case of a search.
* @see NameUsageService#get(int, Locale)
*/
@GET
@Path("{id}")
@NullToNotFound
public NameUsage get(@PathParam("id") int usageKey, @Context Locale locale) {
return nameUsageService.get(usageKey, locale);
}
@GET
@Path("{id}/metrics")
@NullToNotFound
public NameUsageMetrics getMetrics(@PathParam("id") int usageKey) {
return nameUsageService.getMetrics(usageKey);
}
@GET
@Path("{id}/name")
@NullToNotFound
public ParsedName getParsedName(@PathParam("id") int usageKey) {
return nameUsageService.getParsedName(usageKey);
}
@GET
@Path("{id}/verbatim")
@NullToNotFound
public VerbatimNameUsage getVerbatim(@PathParam("id") int usageKey) {
return nameUsageService.getVerbatim(usageKey);
}
/**
* This retrieves a list of children NameUsage for a parent NameUsage from ChecklistBank.
*
* @param parentKey parent NameUsage key
* @param locale identifier for a region
* @param page the limit, offset paging information
* @return requested list of NameUsage or an empty list if none could be found
* @see NameUsageService#listChildren(int, Locale, Pageable)
*/
@GET
@Path("{id}/children")
public PagingResponse<NameUsage> listChildren(@PathParam("id") int parentKey, @Context Locale locale, @Context Pageable page) {
return nameUsageService.listChildren(parentKey, locale, page);
}
@GET
@Path("{id}/childrenAll")
public List<UsageCount> listAllChildren(@PathParam("id") int parentKey) {
return usageCountMapper.children(parentKey);
}
/**
* This retrieves a list of synonym NameUsage for a NameUsage from ChecklistBank.
*
* @param usageKey parent NameUsage key
* @param locale identifier for a region
* @param page the limit, offset, and count paging information
* @return requested list of NameUsage or an empty list if none could be found
* @see NameUsageService#listChildren(int, Locale, Pageable)
*/
@GET
@Path("{id}/synonyms")
public PagingResponse<NameUsage> listSynonyms(@PathParam("id") int usageKey, @Context Locale locale, @Context Pageable page) {
return nameUsageService.listSynonyms(usageKey, locale, page);
}
/**
* This retrieves all VernacularNames for a NameUsage from ChecklistBank.
*
* @param usageKey NameUsage key
* @param page The page and offset and count information
* @return a list of all VernacularNames
* @see VernacularNameService#listByUsage(int, Pageable)
*/
@GET
@Path("{id}/vernacularNames")
public PagingResponse<VernacularName> listVernacularNamesByNameUsage(@PathParam("id") int usageKey, @Context Pageable page) {
return vernacularNameService.listByUsage(usageKey, page);
}
/**
* This retrieves all TypeSpecimens for a NameUsage from ChecklistBank.
*
* @param usageKey NameUsage key
* @param page The page and offset and count information
* @return a list of all TypeSpecimens
* @see TypeSpecimenService#listByUsage(int, Pageable)
*/
@GET
@Path("{id}/typeSpecimens")
public PagingResponse<TypeSpecimen> listTypeSpecimensByNameUsage(@PathParam("id") int usageKey, @Context Pageable page) {
return typeSpecimenService.listByUsage(usageKey, page);
}
/**
* This retrieves all SpeciesProfiles for a NameUsage from ChecklistBank.
*
* @param usageKey NameUsage key
* @param page The page and offset and count information
* @return a list of all SpeciesProfiles
* @see SpeciesProfileService#listByUsage(int, Pageable)
*/
@GET
@Path("{id}/speciesProfiles")
public PagingResponse<SpeciesProfile> listSpeciesProfilesByNameUsage(@PathParam("id") int usageKey, @Context Pageable page) {
return speciesProfileService.listByUsage(usageKey, page);
}
/**
* This retrieves all References for a NameUsage from ChecklistBank.
*
* @param usageKey NameUsage key
* @param page The page and offset and count information
* @return a list of all References
* @see ReferenceService#listByUsage(int, Pageable)
*/
@GET
@Path("{id}/references")
public PagingResponse<Reference> listReferencesByNameUsage(@PathParam("id") int usageKey, @Context Pageable page) {
return referenceService.listByUsage(usageKey, page);
}
/**
* This retrieves all multimedia objects for a NameUsage from ChecklistBank.
*
* @param usageKey NameUsage key
* @param page The page and offset and count information
* @return a list of all Media objects
*/
@GET
@Path("{id}/media")
public PagingResponse<NameUsageMediaObject> listImagesByNameUsage(@PathParam("id") int usageKey, @Context Pageable page) {
return imageService.listByUsage(usageKey, page);
}
/**
* This retrieves all Descriptions for a NameUsage from ChecklistBank.
*
* @param usageKey NameUsage key
* @param page The page and offset and count information
* @return a list of all Descriptions
* @see DescriptionService#listByUsage(int, Pageable)
*/
@GET
@Path("{id}/descriptions")
public PagingResponse<Description> listDescriptionsByNameUsage(@PathParam("id") int usageKey, @Context Pageable page) {
return descriptionService.listByUsage(usageKey, page);
}
/**
* This retrieves a table of contents for all descriptions of a name usage from ChecklistBank.
*/
@GET
@Path("{id}/toc")
@NullToNotFound
public TableOfContents get(@PathParam("id") Integer key) {
return descriptionService.getToc(key);
}
/**
* This retrieves all Distributions for a NameUsage from ChecklistBank.
*
* @param usageKey NameUsage key
* @param page The page and offset and count information
* @return a list of all Distributions
* @see DistributionService#listByUsage(int, Pageable)
*/
@GET
@Path("{id}/distributions")
public PagingResponse<Distribution> listDistributionsByNameUsage(@PathParam("id") int usageKey, @Context Pageable page) {
return distributionService.listByUsage(usageKey, page);
}
/**
* This retrieves all Identifier for a NameUsage from ChecklistBank.
*
* @param usageKey NameUsage key
* @param page The page and offset and count information
* @return a list of all Identifier
*/
@GET
@Path("{id}/identifier")
public PagingResponse<Identifier> listIdentifierByNameUsage(@PathParam("id") int usageKey, @Context Pageable page) {
return identifierService.listByUsage(usageKey, page);
}
/**
* This retrieves all related Usages for a NameUsage from ChecklistBank.
*
* @param usageKey NameUsage key
* @param datasetKeys The optional list of dataset keys to filter related usages
* @return a list of all Related usages
*/
@GET
@Path("{id}/related")
public PagingResponse<NameUsage> listRelatedByNameUsage(@PathParam("id") int usageKey, @Context Locale locale, @Context Pageable page,
@QueryParam(DATASET_KEY) Set<UUID> datasetKeys) {
return nameUsageService.listRelated(usageKey, locale, page, datasetKeys.toArray(new UUID[datasetKeys.size()]));
}
@GET
@Path("{id}/combinations")
public List<NameUsage> listCombinations(@PathParam("id") int basionymKey, @Context Locale locale) {
return nameUsageService.listCombinations(basionymKey, locale);
}
/**
* This retrieves all Parents for a NameUsage from ChecklistBank.
*
* @param usageKey NameUsage key
* @param page The page and offset and count information
* @return a list of all Parents
* @see NameUsageService#listParents(int, Locale)
*/
@GET
@Path("{id}/parents")
public List<NameUsage> listParentsByNameUsage(@PathParam("id") int usageKey, @Context Locale locale, @Context Pageable page) {
return nameUsageService.listParents(usageKey, locale);
}
/**
* This retrieves the IUCN Redlist Category for a nub usage key.
* If the matching IUCN usage does not contain a category not evaluated (NE) is returned.
*
* @param usageKey backbone NameUsage key
* @return IUCN usage with a category, a nub usage with NotEvaluated or null if its not an animal, plant or fungi
*/
@GET
@Path("{id}/iucnRedListCategory")
public IucnRedListCategory getIucnRedListCategory(@PathParam("id") int usageKey) {
IucnRedListCategory iucn = distributionMapper.getIucnRedListCategory(usageKey);
if (iucn != null) {
if (iucn.getCategory() == null) {
iucn.setCategory(ThreatStatus.NOT_EVALUATED);
}
return iucn;
}
// all nub usages that have no matching IUCN usage should become NE if they are animals, plants or fungi
NameUsage nub = nameUsageService.get(usageKey, Locale.US);
if (nub != null && nub.getKingdomKey() != null
&& iucnKingdoms.contains(nub.getKingdomKey())
&& nub.getNameType() == NameType.SCIENTIFIC) {
iucn = new IucnRedListCategory();
iucn.setCategory(ThreatStatus.NOT_EVALUATED);
iucn.setScientificName(nub.getScientificName());
iucn.setTaxonomicStatus(nub.getTaxonomicStatus());
iucn.setAcceptedName(nub.getAccepted());
return iucn;
}
return null;
}
/**
* This retrieves a list of root NameUsage for a Checklist from ChecklistBank.
*
* @param datasetKey UUID or case insensitive shortname of the Checklist to retrieve
* @param locale identifier for a region
* @param page the limit, offset, and count paging information
* @return requested list of NameUsage or an empty list if none could be found
* @see NameUsageService#listRoot(UUID, Locale, Pageable)
*/
@GET
@Path("root/{datasetKey}")
public PagingResponse<NameUsage> listRootUsages(@PathParam(DATASET_KEY) UUID datasetKey, @Context Locale locale, @Context Pageable page) {
return nameUsageService.listRoot(datasetKey, locale, page);
}
@GET
@Path("rootAll/{datasetKey}")
public List<UsageCount> root(@PathParam("datasetKey") UUID datasetKey) {
return usageCountMapper.root(datasetKey);
}
@GET
@Path("rootNub")
public TreeContainer<UsageCount, Integer> rootNub() {
TreeContainer<UsageCount, Integer> tree = new TreeContainer<>();
// kingdoms
tree.setRoot(usageCountMapper.root(Constants.NUB_DATASET_KEY));
for (UsageCount k : tree.getRoot()) {
// phyla ~140, classes ~350, orders ~1400, families are over 22.000 skip
addChildrenRecursively(tree, k.getKey(), 0, Rank.PHYLUM, Rank.CLASS, Rank.ORDER);
}
return tree;
}
private void addChildrenRecursively(TreeContainer<UsageCount, Integer> tree, int parent, int rankIdx, Rank... ranks) {
List<UsageCount> children = usageCountMapper.childrenUntilRank(parent, ranks[rankIdx]);
if (!children.isEmpty()) {
tree.getChildren().put(parent, children);
if (++rankIdx < ranks.length) {
for (UsageCount c : children) {
addChildrenRecursively(tree, c.getKey(), rankIdx, ranks);
}
}
}
}
@GET
@Path("search")
public SearchResponse<NameUsageSearchResult, NameUsageSearchParameter> search(@Context NameUsageSearchRequest searchRequest) {
// POR-2801
// protect SOLR against deep paging requests which blow heap
checkDeepPaging(searchRequest);
return searchService.search(searchRequest);
}
@Path("suggest")
@GET
public List<NameUsageSuggestResult> suggest(@Context NameUsageSuggestRequest searchSuggestRequest) {
// POR-2801
// protect SOLR against deep paging requests which blow heap
checkDeepPaging(searchSuggestRequest);
return searchService.suggest(searchSuggestRequest);
}
private static void checkDeepPaging(Pageable page) {
if (page.getOffset() > DEEP_PAGING_OFFSET_LIMIT) {
throw new IllegalArgumentException("Offset is limited for this operation to " + DEEP_PAGING_OFFSET_LIMIT);
}
}
}
|
package org.chromium;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaArgs;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.PluginManager;
import org.apache.cordova.PluginResult;
import org.apache.cordova.PluginResult.Status;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class ChromeSocketsTcpServer extends CordovaPlugin {
private static final String LOG_TAG = "ChromeSocketsTcpServer";
private Map<Integer, TcpServerSocket> sockets = new ConcurrentHashMap<Integer, TcpServerSocket>();
private BlockingQueue<SelectorMessage> selectorMessages =
new LinkedBlockingQueue<SelectorMessage>();
private int nextSocket = 0;
private CallbackContext acceptContext;
private Selector selector;
private SelectorThread selectorThread;
private PluginManager getPluginManager() {
PluginManager pm = null;
try {
Method gpm = webView.getClass().getMethod("getPluginManager");
pm = (PluginManager) gpm.invoke(webView);
} catch (Exception e) {
try {
Field pmf = webView.getClass().getField("pluginManager");
pm = (PluginManager)pmf.get(webView);
} catch (Exception e2) {}
}
return pm;
}
@Override
public boolean execute(String action, CordovaArgs args, final CallbackContext callbackContext)
throws JSONException {
if ("create".equals(action)) {
create(args, callbackContext);
} else if ("update".equals(action)) {
update(args, callbackContext);
} else if ("setPaused".equals(action)) {
setPaused(args, callbackContext);
} else if ("listen".equals(action)) {
listen(args, callbackContext);
} else if ("disconnect".equals(action)) {
disconnect(args, callbackContext);
} else if ("close".equals(action)) {
close(args, callbackContext);
} else if ("getInfo".equals(action)) {
getInfo(args, callbackContext);
} else if ("getSockets".equals(action)) {
getSockets(args, callbackContext);
} else if ("registerAcceptEvents".equals(action)) {
registerAcceptEvents(args, callbackContext);
} else {
return false;
}
return true;
}
@Override
public void onDestroy() {
super.onDestroy();
closeAllSockets();
stopSelectorThread();
}
@Override
public void onReset() {
super.onReset();
closeAllSockets();
stopSelectorThread();
}
private JSONObject buildErrorInfo(int code, String message) {
JSONObject error = new JSONObject();
try {
error.put("message", message);
error.put("resultCode", code);
} catch (JSONException e) {
}
return error;
}
private void create(CordovaArgs args, final CallbackContext callbackContext)
throws JSONException {
JSONObject properties = args.getJSONObject(0);
try {
TcpServerSocket socket = new TcpServerSocket(nextSocket++, properties);
sockets.put(Integer.valueOf(socket.getSocketId()), socket);
callbackContext.success(socket.getSocketId());
} catch (IOException e) {
}
}
private void update(CordovaArgs args, final CallbackContext callbackContext)
throws JSONException {
int socketId = args.getInt(0);
JSONObject properties = args.getJSONObject(1);
TcpServerSocket socket = sockets.get(Integer.valueOf(socketId));
if (socket == null) {
Log.e(LOG_TAG, "No socket with socketId " + socketId);
return;
}
try {
socket.setProperties(properties);
callbackContext.success();
} catch (SocketException e) {
}
}
private void setPaused(CordovaArgs args, final CallbackContext callbackContext)
throws JSONException {
int socketId = args.getInt(0);
boolean paused = args.getBoolean(1);
TcpServerSocket socket = sockets.get(Integer.valueOf(socketId));
if (socket == null) {
Log.e(LOG_TAG, "No socket with socketId " + socketId);
return;
}
socket.setPaused(paused);
if (paused) {
// Accept interest will be removed when socket is acceptable on selector thread.
callbackContext.success();
} else {
// All interests need to be modified in selector thread.
addSelectorMessage(socket, SelectorMessageType.SO_ADD_ACCEPT_INTEREST, callbackContext);
}
}
private void listen(CordovaArgs args, final CallbackContext callbackContext)
throws JSONException {
int socketId = args.getInt(0);
String address = args.getString(1);
int port = args.getInt(2);
TcpServerSocket socket = sockets.get(Integer.valueOf(socketId));
if (socket == null) {
Log.e(LOG_TAG, "No socket with socketId " + socketId);
callbackContext.error(buildErrorInfo(-4, "Invalid Argument"));
return;
}
try {
if (args.isNull(3)) {
socket.listen(address, port);
} else {
int backlog = args.getInt(3);
socket.listen(address, port, backlog);
}
addSelectorMessage(socket, SelectorMessageType.SO_LISTEN, null);
callbackContext.success();
} catch (IOException e) {
callbackContext.error(buildErrorInfo(-2, e.getMessage()));
}
}
private void disconnect(CordovaArgs args, final CallbackContext callbackContext)
throws JSONException {
int socketId = args.getInt(0);
TcpServerSocket socket = sockets.get(Integer.valueOf(socketId));
if (socket == null) {
Log.e(LOG_TAG, "No socket with socketId " + socketId);
return;
}
addSelectorMessage(socket, SelectorMessageType.SO_DISCONNECTED, callbackContext);
}
private void closeAllSockets() {
for(TcpServerSocket socket: sockets.values()) {
addSelectorMessage(socket, SelectorMessageType.SO_CLOSE, null);
}
}
private void close(CordovaArgs args, final CallbackContext callbackContext)
throws JSONException {
int socketId = args.getInt(0);
TcpServerSocket socket = sockets.get(Integer.valueOf(socketId));
if (socket == null) {
Log.e(LOG_TAG, "No socket with socketId " + socketId);
return;
}
addSelectorMessage(socket, SelectorMessageType.SO_CLOSE, callbackContext);
}
private void getInfo(CordovaArgs args, final CallbackContext callbackContext)
throws JSONException {
int socketId = args.getInt(0);
TcpServerSocket socket = sockets.get(Integer.valueOf(socketId));
if (socket == null) {
Log.e(LOG_TAG, "No socket with socketId " + socketId);
return;
}
callbackContext.success(socket.getInfo());
}
private void getSockets(CordovaArgs args, final CallbackContext callbackContext)
throws JSONException {
JSONArray results = new JSONArray();
for (TcpServerSocket socket: sockets.values()) {
results.put(socket.getInfo());
}
callbackContext.success(results);
}
private void registerAcceptEvents(CordovaArgs args, final CallbackContext callbackContext) {
acceptContext = callbackContext;
startSelectorThread();
}
private void startSelectorThread() {
if (selectorThread != null) return;
selectorThread = new SelectorThread(selectorMessages, sockets);
selectorThread.start();
}
private void stopSelectorThread() {
if (selectorThread == null) return;
addSelectorMessage(null, SelectorMessageType.T_STOP, null);
try {
selectorThread.join();
selectorThread = null;
} catch (InterruptedException e) {
}
}
private void addSelectorMessage(
TcpServerSocket socket, SelectorMessageType type, CallbackContext callbackContext) {
try {
selectorMessages.put(new SelectorMessage(
socket, type, callbackContext));
if (selector != null)
selector.wakeup();
} catch (InterruptedException e) {
}
}
private enum SelectorMessageType {
SO_LISTEN,
SO_DISCONNECTED,
SO_CLOSE,
SO_ADD_ACCEPT_INTEREST,
T_STOP;
}
private class SelectorMessage {
final TcpServerSocket socket;
final SelectorMessageType type;
final CallbackContext callbackContext;
SelectorMessage(
TcpServerSocket socket, SelectorMessageType type, CallbackContext callbackContext) {
this.socket = socket;
this.type = type;
this.callbackContext = callbackContext;
}
}
private class SelectorThread extends Thread {
private BlockingQueue<SelectorMessage> selectorMessages;
private Map<Integer, TcpServerSocket> sockets;
private boolean running = true;
SelectorThread(
BlockingQueue<SelectorMessage> selectorMessages,
Map<Integer, TcpServerSocket> sockets) {
this.selectorMessages = selectorMessages;
this.sockets = sockets;
}
private void processPendingMessages() {
while (selectorMessages.peek() != null) {
SelectorMessage msg = null;
try {
msg = selectorMessages.take();
switch (msg.type) {
case SO_LISTEN:
msg.socket.register(selector, SelectionKey.OP_ACCEPT);
break;
case SO_DISCONNECTED:
msg.socket.disconnect();
break;
case SO_CLOSE:
msg.socket.disconnect();
sockets.remove(Integer.valueOf(msg.socket.getSocketId()));
break;
case SO_ADD_ACCEPT_INTEREST:
msg.socket.addInterestSet(SelectionKey.OP_ACCEPT);
break;
case T_STOP:
running = false;
break;
}
if (msg.callbackContext != null)
msg.callbackContext.success();
} catch (InterruptedException e) {
} catch (IOException e) {
if (msg.callbackContext != null)
msg.callbackContext.error(buildErrorInfo(-2, e.getMessage()));
}
}
}
public void run() {
try {
selector = Selector.open();
} catch (IOException e) {
throw new RuntimeException(e);
}
// process possible messages that send during openning the selector
// before select.
processPendingMessages();
Iterator<SelectionKey> it;
while (running) {
try {
selector.select();
} catch (IOException e) {
continue;
}
it = selector.selectedKeys().iterator();
while (it.hasNext()) {
SelectionKey key = it.next();
it.remove();
if (!key.isValid()) {
continue;
}
TcpServerSocket socket = (TcpServerSocket)key.attachment();
try {
if (key.isAcceptable()) {
socket.accept();
}
} catch (JSONException e) {
}
}
processPendingMessages();
}
}
}
private class TcpServerSocket {
private final int socketId;
private ServerSocketChannel channel;
private SelectionKey key;
private boolean paused;
private boolean persistent;
private String name;
TcpServerSocket(int socketId, JSONObject properties)
throws JSONException, IOException {
this.socketId = socketId;
channel = ServerSocketChannel.open();
channel.configureBlocking(false);
// set socket default options
paused = false;
persistent = false;
name = "";
setProperties(properties);
}
// Only call this method on selector thread
void addInterestSet(int interestSet) {
if (key != null && key.isValid()) {
key.interestOps(key.interestOps() | interestSet);
key.selector().wakeup();
}
}
// Only call this method on selector thread
void removeInterestSet(int interestSet) {
if (key != null && key.isValid()) {
key.interestOps(key.interestOps() & ~interestSet);
key.selector().wakeup();
}
}
int getSocketId() {
return socketId;
}
void register(Selector selector, int interestSets) throws IOException {
key = channel.register(selector, interestSets, this);
}
void setProperties(JSONObject properties) throws JSONException, SocketException {
if (!properties.isNull("persistent"))
persistent = properties.getBoolean("persistent");
if (!properties.isNull("name"))
name = properties.getString("name");
}
void setPaused(boolean paused) {
this.paused = paused;
}
void setUpListen() throws IOException {
if (!channel.isOpen()) {
channel = ServerSocketChannel.open();
channel.configureBlocking(false);
}
}
void listen(String address, int port) throws IOException {
setUpListen();
channel.socket().bind(new InetSocketAddress(port));
}
void listen(String address, int port, int backlog) throws IOException {
setUpListen();
channel.socket().bind(new InetSocketAddress(port), backlog);
}
void disconnect() throws IOException {
if (key != null && channel.isRegistered())
key.cancel();
channel.close();
}
JSONObject getInfo() throws JSONException {
JSONObject info = new JSONObject();
info.put("socketId", socketId);
info.put("persistent", persistent);
info.put("name", name);
info.put("paused", paused);
if (channel.socket().getInetAddress() != null) {
info.put("localAddress", channel.socket().getInetAddress().getHostAddress());
info.put("localPort", channel.socket().getLocalPort());
}
return info;
}
// This method can be only called by selector thread.
void accept() throws JSONException {
if (paused) {
// Remove accept interests to avoid seletor wakeup when acceptable.
removeInterestSet(SelectionKey.OP_ACCEPT);
return;
}
try {
SocketChannel acceptedSocket = channel.accept();
ChromeSocketsTcp tcpPlugin =
(ChromeSocketsTcp) getPluginManager().getPlugin("ChromeSocketsTcp");
int clientSocketId = tcpPlugin.registerAcceptedSocketChannel(acceptedSocket);
JSONObject info = new JSONObject();
info.put("socketId", socketId);
info.put("clientSocketId", clientSocketId);
PluginResult acceptedResult = new PluginResult(Status.OK, info);
acceptedResult.setKeepCallback(true);
acceptContext.sendPluginResult(acceptedResult);
} catch (IOException e) {
JSONObject info = buildErrorInfo(-2, e.getMessage());
info.put("socketId", socketId);
PluginResult errResult = new PluginResult(Status.ERROR, info);
errResult.setKeepCallback(true);
acceptContext.sendPluginResult(errResult);
}
}
}
}
|
package edu.duke.cabig.c3pr.web.study;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.validation.Errors;
import org.springframework.web.servlet.ModelAndView;
import edu.duke.cabig.c3pr.domain.RandomizationType;
import edu.duke.cabig.c3pr.domain.Study;
import edu.duke.cabig.c3pr.web.ajax.BookRandomizationAjaxFacade;
public class StudyRandomizationTab extends StudyTab {
private BookRandomizationAjaxFacade bookRandomizationAjaxFacade;
String []bookRandomizationEntries;
public StudyRandomizationTab() {
super("Study Book Randomizations", "Randomization", "study/study_randomizations");
bookRandomizationEntries = new String[10];
}
@Override
public void postProcess(HttpServletRequest req, Study study, Errors errors) {
if(study.getRandomizationType() != null && study.getRandomizationType().equals(RandomizationType.BOOK)){
parseFile(req, study, errors);
}
}
public ModelAndView parseFile(HttpServletRequest request, Object commandObj, Errors error){
//save it to session
if(getFlow().getName().equals("Create Study")){
request.getSession().setAttribute("edu.duke.cabig.c3pr.web.study.CreateStudyController.FORM.command" ,commandObj);
} else if (getFlow().getName().equals("Edit Study")){
request.getSession().setAttribute("edu.duke.cabig.c3pr.web.study.EditStudyController.FORM.command" ,commandObj);
}
Map map=new HashMap();
try {
String index = request.getParameter("index").toString();
Study study = (Study)(commandObj);
Object viewData = bookRandomizationAjaxFacade.getTable(new HashMap<String, List>(), study.getFile(), index, request);
bookRandomizationEntries[Integer.parseInt(index)] = viewData.toString();
request.setAttribute("bookRandomizationEntries", bookRandomizationEntries);
map.put(getFreeTextModelName(), viewData.toString());
} catch(Exception e ){
log.error(e.getMessage());
}
return new ModelAndView("",map);
}
public BookRandomizationAjaxFacade getBookRandomizationAjaxFacade() {
return bookRandomizationAjaxFacade;
}
public void setBookRandomizationAjaxFacade(
BookRandomizationAjaxFacade bookRandomizationAjaxFacade) {
this.bookRandomizationAjaxFacade = bookRandomizationAjaxFacade;
}
/* if(study.getRandomizationType().equals(RandomizationType.CALL_OUT) ||
study.getRandomizationType().equals(RandomizationType.PHONE_CALL)){
return;
}
if(study.getRandomizationType().equals(RandomizationType.BOOK)){
ArrayList <String>reqParamArr = new ArrayList<String>();
Enumeration e = req.getParameterNames();
String temp;
while(e.hasMoreElements()){
temp = e.nextElement().toString();
if(temp.startsWith("bookRandomizations")){
reqParamArr.add(temp);
}
}
String epochIndex, bookRandomizations;
int selectedEpoch;
for(String param : reqParamArr){
bookRandomizations = StringUtils.getBlankIfNull(req.getParameter(param));
if(!StringUtils.isEmpty(bookRandomizations)){
epochIndex = param.substring(param.indexOf("-")+1);
selectedEpoch = StringUtils.getBlankIfNull(epochIndex).equals("")?-1:Integer.parseInt(epochIndex);
TreatmentEpoch tEpoch = study.getTreatmentEpochs().get(selectedEpoch);
if(study.getRandomizationType().getName().equals("BOOK")){
parseBookRandomization(bookRandomizations, tEpoch);
}
}
}
}
}*/
}
|
package com.itti7.itimeu;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.itti7.itimeu.data.ItemContract;
import com.itti7.itimeu.data.ItemDbHelper;
/**
* A simple {@link Fragment} subclass.
*/
public class TimerFragment extends Fragment {
/*Setting UI*/
public static final String WORKTIME = "worktime";
public static final String BREAKTIME = "breaktime";
public static final String LONGBREAKTIME = "longbreaktime";
public static final String SESSION = "session";
private TextView mTimeText;
private TextView mItemNameText;
private ProgressBar mProgressBar;
private Button mStateBttn;
/*timer Service Component*/
private TimerService mTimerService;
boolean mServiceBound = false;
private TimerHandler Timerhandler;
private int progressBarValue = 0;
public int runTime; // minute
/*timer calc*/
private Intent intent;
//private ServiceConnection conn;
private Thread mReadThread;
/*store time count*/
private int mCountTimer;
// Item info come from ListView
private int mId, mStatus, mUnit, mTotalUnit;
private String mName;
// For access ITimeU database
ItemDbHelper dbHelper;
SQLiteDatabase db;
String query;
public TimerFragment() {
// Required empty public constructor
}
BroadcastReceiver mReceiver;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View timerView = inflater.inflate(R.layout.fragment_timer, container, false);
// get Timer tag and set to TimerTag
String timerTag = getTag();
((MainActivity) getActivity()).setTimerTag(timerTag);
//get ItemDbHelper to get SQLITEDB.getWritableDB()
dbHelper = new ItemDbHelper(getActivity());
mItemNameText = timerView.findViewById(R.id.job_name_txt);
/*progressBar button init*/
mProgressBar = (ProgressBar) timerView.findViewById(R.id.progressBar);
mStateBttn = (Button) timerView.findViewById(R.id.state_bttn_view);
mStateBttn.setOnClickListener(stateChecker);
mStateBttn.setEnabled(false);
/*Time Text Initialize */
mTimeText = (TextView) timerView.findViewById(R.id.time_txt_view);
/*progressBar button init*/
mProgressBar = (ProgressBar) timerView.findViewById(R.id.progressBar);
mProgressBar.bringToFront(); // bring the progressbar to the top
mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
onUnitFinish();
}
};
/*init timer count */
mCountTimer = 1;
/*init shared prefernce*/
PrefUtil.save(getContext(), "COUNT", mCountTimer);
db = dbHelper.getWritableDatabase();
query = "UPDATE " + ItemContract.ItemEntry.TABLE_NAME + " SET unit = '" + mUnit + "', status = '";
// if all the units are completed
if (mUnit == mTotalUnit) {
//UPDATE DB mStatus = 2
query = query + ItemContract.ItemEntry.STATUS_DONE + "' WHERE _ID = '" + mId + "';";
// if the last break of the list just end go back to the listFragment
if (mCountTimer == mUnit * 2) {
//if finished, set the button disable
mStateBttn.setEnabled(false);
// Change Fragment TimerFragment -> ListItemFragment ->
MainActivity mainActivity = (MainActivity) getActivity();
(mainActivity).getViewPager().setCurrentItem(0);
}
} else {
//UPDATE DB mStatus = 0
query = query + ItemContract.ItemEntry.STATUS_TODO + "' WHERE _ID = '" + mId + "';";
}
db.execSQL(query);
db.close();
/*List Item unit count update*/
MainActivity mainActivity = (MainActivity) getActivity();
String listTag = mainActivity.getListTag();
ListItemFragment listItemFragment = (ListItemFragment) mainActivity.getSupportFragmentManager().findFragmentByTag(listTag);
listItemFragment.listUiUpdateFromDb();
return timerView;
}
public void onUnitFinish() {
// UPDATE mCountTimner range 1..8
// if Long Break Time has just finished, change to 1
mCountTimer++;
int sessionNum = PrefUtil.get(getContext(), SESSION, 4) * 2;
if (mCountTimer == sessionNum + 1)
mCountTimer = 1;
PrefUtil.save(getContext(), "COUNT", mCountTimer);
//change the button text to 'start'
mStateBttn.setText("start");
//set the ListItemText for the next session
if (mCountTimer % 2 == 1)
mItemNameText.setText(mName);
else {
mUnit++; //if the last session WAS work ,increase mUnit
if (mCountTimer % sessionNum == 0)
mItemNameText.setText("Long Break Time");
else
mItemNameText.setText("Break Time");
}
//store mUnit and mStatus
query = "UPDATE " + ItemContract.ItemEntry.TABLE_NAME + " SET unit = '" + mUnit + "', status = '";
// if all the units are completed
if (mUnit == mTotalUnit) {
//UPDATE DB mStatus = 2
query = query + ItemContract.ItemEntry.STATUS_DONE + "' WHERE _ID = '" + mId + "';";
// if the last break of the list just end go back to the listFragment
if (mCountTimer % 2 == 1) {
//if finished, set the button disable
mStateBttn.setEnabled(false);
// Change Fragment TimerFragment -> ListItemFragment ->
MainActivity mainActivity = (MainActivity) getActivity();
(mainActivity).getViewPager().setCurrentItem(0);
}
} else {
//UPDATE DB mStatus = 0
query = query + ItemContract.ItemEntry.STATUS_TODO + "' WHERE _ID = '" + mId + "';";
}
dbUpdate(query);
//after the unit values has been updated
//turn the value to false;
TimerService.mTimerServiceFinished = false;
}
public void updateListFragment() {
/*List Item unit count update*/
MainActivity mainActivity = (MainActivity) getActivity();
String listTag = mainActivity.getListTag();
ListItemFragment listItemFragment = (ListItemFragment) mainActivity.getSupportFragmentManager().findFragmentByTag(listTag);
listItemFragment.listUiUpdateFromDb();
}
@Override
public void onStart() {
super.onStart();
intent = new Intent(getActivity(), TimerService.class);
if (TimerService.mTimerServiceFinished == true) {
onUnitFinish();
}
/*TimerService Intent Listener*/
getActivity().bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
/**
* Defines callbacks for service binding, passed to bindService()
*/
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className, IBinder service) {
// We've bound to LocalService, cast the IBinder and get LocalService instance
mTimerService = ((TimerService.MyBinder) service).getService();
mServiceBound = true;
}
@Override
public void onServiceDisconnected(ComponentName arg0) {
mTimerService = null;
//mTimerService.stopCountNotification();
mProgressBar.setProgress(0);
Timerhandler.removeMessages(0);
mItemNameText.setText("");
mStateBttn.setEnabled(false);
mServiceBound = false;
}
};
@Override
public void onResume() {
super.onResume();
getActivity().registerReceiver(mReceiver, new IntentFilter(mTimerService.strReceiver));
}
public void dbUpdate(String query) {
db = dbHelper.getWritableDatabase();
db.execSQL(query);
db.close();
/*List Item unit count update*/
updateListFragment();
}
public void setStatusToDo(){
/*set mStatus to TO DO(0)*/
if (mStateBttn.getText().toString().equals("stop")) {
query = "UPDATE " + ItemContract.ItemEntry.TABLE_NAME + " SET status = '" + ItemContract.ItemEntry.STATUS_TODO + "' WHERE _ID = '" + mId + "';";
dbUpdate(query);
}
}
Button.OnClickListener stateChecker = new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mStateBttn.getText().toString().equals("start")) { // checked
//mUnit will be intialize when list item is clicked
if (mServiceBound) {
/* set mStatus DB to DO(1)*/
query = "UPDATE " + ItemContract.ItemEntry.TABLE_NAME + " SET status = '" + ItemContract.ItemEntry.STATUS_DO + "' WHERE _ID = '" + mId + "';";
dbUpdate(query);
mCountTimer = PrefUtil.get(getContext(), "COUNT", 1);
Log.i("TimerFragment","Session : "+(PrefUtil.get(getContext(), SESSION, 4) * 2));
if (mCountTimer % ((PrefUtil.get(getContext(), SESSION, 4) * 2)) == 0) // assign time by work,short & long break
runTime = PrefUtil.get(getContext(), LONGBREAKTIME, 20);
else if (mCountTimer % 2 == 1)
runTime = PrefUtil.get(getContext(), WORKTIME, 25);
else
runTime = PrefUtil.get(getContext(), BREAKTIME, 5);
mProgressBar.setMax(runTime * 60 + 2); // setMax by sec
Timerhandler = new TimerHandler();
updateLeftTime();
mTimerService.setRunTimeTaskName(runTime, mItemNameText.getText().toString());
mStateBttn.setText(R.string.stop);
Timerhandler.sendEmptyMessage(0);
}
} else {
getActivity().stopService(intent); //stop service
mReadThread.interrupt();
mTimerService.stopCountNotification();
mProgressBar.setProgress(0);
Timerhandler.removeMessages(0);
progressBarValue = 0; //must be set 0
mStateBttn.setText(R.string.start);
/*set mStatus to TO DO(0)*/
query = "UPDATE " + ItemContract.ItemEntry.TABLE_NAME + " SET status = '" + ItemContract.ItemEntry.STATUS_TODO + "' WHERE _ID = '" + mId + "';";
dbUpdate(query);
}
}
};
public void updateLeftTime() {
mReadThread = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
//check out if it is still available
if (getActivity() == null)
return;
try {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
mTimeText.setText(mTimerService.getTime());
}
});
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace(); //back to list
}
}
}
});
mReadThread.start();
}
public class TimerHandler extends Handler {
TimerHandler() {
super();
}
@Override
public void handleMessage(android.os.Message msg) {
if (mTimerService.getRun()) {
progressBarValue++;
mProgressBar.bringToFront();
mProgressBar.setProgress(progressBarValue);
Timerhandler.sendEmptyMessageDelayed(0, 1000); //increase by sec
} else { // Timer must be finished
mProgressBar.setProgress(0);
progressBarValue = 0;
}
}
}
@Override
public void onStop(){
super.onStop();
setStatusToDo();
}
@Override
public void onDestroy() {
super.onDestroy();
if (mServiceBound) {
mTimerService.stopService(intent);
getActivity().unbindService(mConnection);
mServiceBound = false;
}
}
/**
* This function set TimerFragment once listItem was clicked
*/
public void setTimerFragment(int mId, int mStatus, int mUnit, int mTotalUnit, String mName) {
this.mId = mId;
this.mStatus = mStatus;
this.mUnit = mUnit;
this.mTotalUnit = mTotalUnit;
this.mName = mName;
this.mStateBttn.setEnabled(true);
if (mCountTimer % 2 == 1) {
//should keep setting when the breakTimer hasn't run yet
mItemNameText.setText(mName);
}
}
public void setDeleteItemDisable(int dId) {
//once the Item became deleted
if (dId == mId) {
/*set the button disable*/
mStateBttn.setEnabled(false);
mItemNameText.setText("Deleted");
}
}
}
|
package com.dubture.twig.core.index;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.dltk.ast.ASTNode;
import org.eclipse.dltk.ast.declarations.MethodDeclaration;
import org.eclipse.dltk.ast.declarations.ModuleDeclaration;
import org.eclipse.dltk.ast.declarations.TypeDeclaration;
import org.eclipse.dltk.ast.expressions.CallArgumentsList;
import org.eclipse.dltk.ast.expressions.Expression;
import org.eclipse.dltk.ast.references.SimpleReference;
import org.eclipse.dltk.ast.references.VariableReference;
import org.eclipse.dltk.ast.statements.Statement;
import org.eclipse.dltk.core.ISourceModule;
import org.eclipse.dltk.core.index2.IIndexingRequestor.ReferenceInfo;
import org.eclipse.php.core.index.PhpIndexingVisitorExtension;
import org.eclipse.php.internal.core.compiler.ast.nodes.ArrayCreation;
import org.eclipse.php.internal.core.compiler.ast.nodes.ArrayElement;
import org.eclipse.php.internal.core.compiler.ast.nodes.ClassDeclaration;
import org.eclipse.php.internal.core.compiler.ast.nodes.ClassInstanceCreation;
import org.eclipse.php.internal.core.compiler.ast.nodes.ExpressionStatement;
import org.eclipse.php.internal.core.compiler.ast.nodes.PHPCallExpression;
import org.eclipse.php.internal.core.compiler.ast.nodes.PHPDocBlock;
import org.eclipse.php.internal.core.compiler.ast.nodes.PHPMethodDeclaration;
import org.eclipse.php.internal.core.compiler.ast.nodes.ReturnStatement;
import org.eclipse.php.internal.core.compiler.ast.nodes.Scalar;
import org.eclipse.php.internal.core.compiler.ast.visitor.PHPASTVisitor;
import org.json.simple.JSONObject;
import com.dubture.twig.core.TwigCoreConstants;
import com.dubture.twig.core.log.Logger;
import com.dubture.twig.core.model.Filter;
import com.dubture.twig.core.model.Function;
import com.dubture.twig.core.model.ITwigModelElement;
import com.dubture.twig.core.model.Tag;
import com.dubture.twig.core.model.Test;
import com.dubture.twig.core.model.TwigType;
import com.dubture.twig.core.util.TwigModelUtils;
/**
*
* {@link TwigIndexingVisitorExtension} indexes:
*
* - Filters - Functions - TokenParsers (used to detect start/end tags like
* if/endif, block/endblock etc
*
*
* @author Robert Gruendler <r.gruendler@gmail.com>
*
*/
@SuppressWarnings("restriction")
public class TwigIndexingVisitorExtension extends PhpIndexingVisitorExtension
{
protected boolean inTwigExtension;
protected boolean inTokenParser;
protected boolean inTagParseMethod;
protected ClassDeclaration currentClass;
protected Tag tag;
protected List<MethodDeclaration> methods = new ArrayList<MethodDeclaration>();
protected List<Function> functions = new ArrayList<Function>();
protected List<Filter> filters = new ArrayList<Filter>();
protected List<Test> tests = new ArrayList<Test>();
protected TwigIndexingVisitor visitor;
public TwigIndexingVisitorExtension()
{
}
@Override
public void setSourceModule(ISourceModule module)
{
super.setSourceModule(module);
visitor = new TwigIndexingVisitor(requestor, sourceModule);
}
@Override
@SuppressWarnings("unchecked")
public boolean visit(MethodDeclaration s) throws Exception
{
if (!methods.contains(s))
methods.add(s);
if (s instanceof PHPMethodDeclaration) {
PHPMethodDeclaration phpMethod = (PHPMethodDeclaration) s;
if (inTwigExtension&& phpMethod.getName().equals(TwigCoreConstants.GET_FILTERS)) {
phpMethod.traverse(new PHPASTVisitor()
{
@Override
public boolean visit(ArrayElement s) throws Exception
{
Expression key = s.getKey();
Expression value = s.getValue();
if (key == null | value == null) {
return false;
}
if (key.getClass() == Scalar.class && value.getClass() == ClassInstanceCreation.class) {
Scalar name = (Scalar) key;
ClassInstanceCreation filterClass = (ClassInstanceCreation) value;
CallArgumentsList ctorParams = filterClass.getCtorParams();
Object child = ctorParams.getChilds().get(0);
if (child instanceof VariableReference && ((VariableReference)child).getName().equals("$this") &&
filterClass.getClassName().toString().equals((TwigCoreConstants.TWIG_FILTER_METHOD))) {
if (ctorParams.getChilds().size() > 2 && ctorParams.getChilds().get(1) instanceof Scalar) {
Scalar internal = (Scalar) ctorParams.getChilds().get(1);
String elemName = name.getValue().replaceAll("['\"]", "");
Filter filter = new Filter(elemName);
filter.setInternalFunction(internal.getValue().replaceAll("['\"]", ""));
filter.setPhpClass(currentClass.getName());
filters.add(filter);
}
}
if (!(child instanceof Scalar)) {
return true;
}
Scalar internal = (Scalar) child;
if (filterClass.getClassName().toString().equals(TwigCoreConstants.TWIG_FILTER_FUNCTION)) {
String elemName = name.getValue().replaceAll("['\"]", "");
Filter filter = new Filter(elemName);
filter.setInternalFunction(internal.getValue()
.replaceAll("['\"]", ""));
filter.setPhpClass(currentClass.getName());
filters.add(filter);
}
}
return true;
}
});
} else if (inTwigExtension && TwigCoreConstants.GET_TESTS.equals(s.getName())) {
phpMethod.traverse(new PHPASTVisitor()
{
@Override
public boolean visit(ArrayElement s) throws Exception
{
Expression key = s.getKey();
Expression value = s.getValue();
if (key == null || value == null)
return false;
if (key.getClass() == Scalar.class && value.getClass() == ClassInstanceCreation.class) {
Scalar name = (Scalar) key;
ClassInstanceCreation functionClass = (ClassInstanceCreation) value;
CallArgumentsList args = functionClass.getCtorParams();
if (!(args.getChilds().get(0) instanceof Scalar)) {
return true;
}
Scalar internalFunction = (Scalar) args.getChilds().get(0);
if (functionClass.getClassName().toString().equals(TwigCoreConstants.TWIG_TEST_FUNCTION)) {
String elemName = name.getValue().replaceAll("['\"]", "");
JSONObject metadata = new JSONObject();
metadata.put(TwigType.PHPCLASS,currentClass.getName());
Test test = new Test(elemName);
test.setPhpClass(currentClass.getName());
test.setInternalFunction(internalFunction.getValue().replaceAll("['\"]", ""));
tests.add(test);
}
}
return true;
}
});
} else if (inTwigExtension&& TwigCoreConstants.GET_FUNCTIONS.equals(s.getName())) {
phpMethod.traverse(new PHPASTVisitor()
{
@Override
public boolean visit(ArrayElement s) throws Exception
{
Expression key = s.getKey();
Expression value = s.getValue();
if (key == null || value == null) {
return false;
}
if (key.getClass() == Scalar.class && value.getClass() == ClassInstanceCreation.class) {
Scalar name = (Scalar) key;
ClassInstanceCreation functionClass = (ClassInstanceCreation) value;
CallArgumentsList args = functionClass.getCtorParams();
String functionClassName = functionClass.getClassName().toString();
int index = -1;
if (functionClassName.equals(TwigCoreConstants.TWIG_FUNCTION_FUNCTION)) {
index = 0;
} else if (functionClassName.equals(TwigCoreConstants.TWIG_FUNCTION_METHOD)) {
index = 1;
}
if (index > -1 && args.getChilds().get(index) instanceof Scalar) {
Scalar internalFunction = (Scalar) args.getChilds().get(index);
if (internalFunction == null) {
return true;
}
String elemName = name.getValue().replaceAll("['\"]", "");
JSONObject metadata = new JSONObject();
metadata.put(TwigType.PHPCLASS, currentClass.getName());
Function function = new Function(elemName);
function.setPhpClass(currentClass.getName());
function.setInternalFunction(internalFunction.getValue().replaceAll("['\"]", ""));
functions.add(function);
}
}
return true;
}
});
} else if (inTokenParser && TwigCoreConstants.PARSE_TOKEN_METHOD.equals(s.getName())) {
inTagParseMethod = true;
} else if (inTokenParser && TwigCoreConstants.PARSE_GET_TAG_METHOD.equals(s.getName())) {
phpMethod.traverse(new PHPASTVisitor()
{
@Override
public boolean visit(ReturnStatement s) throws Exception
{
if (s.getExpr().getClass() == Scalar.class) {
Scalar scalar = (Scalar) s.getExpr();
tag.setStartTag(scalar.getValue().replaceAll("['\"]", ""));
}
return false;
}
});
}
}
return false;
}
@Override
public boolean endvisit(MethodDeclaration s) throws Exception
{
inTagParseMethod = false;
return true;
}
@Override
public boolean visit(TypeDeclaration s) throws Exception
{
if (s instanceof ClassDeclaration) {
inTwigExtension = false;
currentClass = (ClassDeclaration) s;
for (String superclass : currentClass.getSuperClassNames()) {
if (superclass.equals(TwigCoreConstants.TWIG_EXTENSION)) {
inTwigExtension = true;
} else if (superclass.equals(TwigCoreConstants.TWIG_TOKEN_PARSER)) {
tag = new Tag();
inTokenParser = true;
}
}
return true;
}
return false;
}
@SuppressWarnings("unchecked")
@Override
public boolean endvisit(TypeDeclaration s) throws Exception
{
if (s instanceof ClassDeclaration) {
if (tag != null) {
if (tag.getStartTag() != null) {
int length = currentClass.sourceEnd() - currentClass.sourceStart();
PHPDocBlock block = currentClass.getPHPDoc();
String desc = "";
if (block != null) {
String shortDesc = block.getShortDescription() != null
? block.getShortDescription()
: "";
String longDesc = block.getLongDescription() != null
? block.getLongDescription()
: "";
desc = shortDesc + longDesc;
}
String endTag = tag.getEndTag();
JSONObject metadata = new JSONObject();
metadata.put(TwigType.PHPCLASS, currentClass.getName());
metadata.put(TwigType.DOC, desc);
metadata.put(TwigType.IS_OPEN_CLOSE, endTag != null);
Logger.debugMSG("indexing twig tag: " + tag.getStartTag()
+ " : " + tag.getEndTag() + " with metadata: "
+ metadata.toString());
ReferenceInfo info = new ReferenceInfo(
ITwigModelElement.START_TAG,
currentClass.sourceStart(), length,
tag.getStartTag(), metadata.toString(), null);
addReferenceInfo(info);
if (endTag != null) {
ReferenceInfo endIinfo = new ReferenceInfo(
ITwigModelElement.END_TAG,
currentClass.sourceStart(), length,
tag.getEndTag(), metadata.toString(), null);
addReferenceInfo(endIinfo);
}
}
tag = null;
}
inTwigExtension = false;
inTokenParser = false;
currentClass = null;
}
return false;
}
@Override
public boolean visit(Statement s) throws Exception
{
if (!inTagParseMethod)
return false;
s.traverse(new PHPASTVisitor()
{
@Override
public boolean visit(PHPCallExpression callExpr) throws Exception
{
SimpleReference ref = callExpr.getCallName();
if (ref != null
&& TwigCoreConstants.PARSE_SUB.equals(ref.getName())) {
callExpr.traverse(new PHPASTVisitor()
{
@Override
public boolean visit(ArrayCreation array)
throws Exception
{
for (ArrayElement elem : array.getElements()) {
Expression value = elem.getValue();
if (value == null)
continue;
if (value.getClass() == Scalar.class) {
Scalar scalar = (Scalar) value;
String subParseMethod = scalar.getValue().replaceAll("['\"]", "");
for (MethodDeclaration method : currentClass.getMethods()) {
if (subParseMethod.equals(method.getName())) {
String[] endStatements = TwigModelUtils.getEndStatements((PHPMethodDeclaration) method);
for (String stmt : endStatements) {
if (stmt.startsWith("end")) {
tag.setEndTag(stmt);
return false;
}
}
}
}
}
}
return true;
}
});
}
return true;
}
});
return true;
}
@Override
public boolean endvisit(Statement s) throws Exception
{
if (s instanceof ExpressionStatement) {
ExpressionStatement stmt = (ExpressionStatement) s;
if (stmt.getExpr() instanceof PHPCallExpression) {
return true;
}
}
return false;
}
@Override
public boolean endvisit(ModuleDeclaration s) throws Exception
{
for (Test test : tests) {
for (MethodDeclaration method : methods) {
if (method.getName().equals(test.getInternalFunction())) {
PHPMethodDeclaration phpMethod = (PHPMethodDeclaration) method;
PHPDocBlock doc = phpMethod.getPHPDoc();
if (doc != null) {
test.addDoc(doc);
}
Logger.debugMSG("indexing test tag: "
+ test.getElementName() + " with metadata: "
+ test.getMetadata());
ReferenceInfo info = new ReferenceInfo(
ITwigModelElement.TEST, 0, 0,
test.getElementName(), test.getMetadata(), null);
addReferenceInfo(info);
}
}
}
for (Function function : functions) {
for (MethodDeclaration method : methods) {
if (method.getName().equals(function.getInternalFunction())) {
PHPMethodDeclaration phpMethod = (PHPMethodDeclaration) method;
PHPDocBlock doc = phpMethod.getPHPDoc();
if (doc != null) {
function.addDoc(doc);
}
function.addArgs(method.getArguments());
Logger.debugMSG("indexing function: "
+ function.getElementName() + " with metadata: "
+ function.getMetadata());
ReferenceInfo info = new ReferenceInfo(
ITwigModelElement.FUNCTION, 0, 0,
function.getElementName(), function.getMetadata(),
null);
addReferenceInfo(info);
}
}
}
for (Filter filter : filters) {
for (MethodDeclaration method : methods) {
if (method.getName().equals(filter.getInternalFunction())) {
PHPMethodDeclaration phpMethod = (PHPMethodDeclaration) method;
PHPDocBlock doc = phpMethod.getPHPDoc();
if (doc != null) {
filter.addDoc(doc);
}
filter.addArgs(method.getArguments());
Logger.debugMSG("indexing filter: "
+ filter.getElementName() + " with metadata: "
+ filter.getMetadata());
ReferenceInfo info = new ReferenceInfo(
ITwigModelElement.FILTER, 0, 0,
filter.getElementName(), filter.getMetadata(), null);
addReferenceInfo(info);
}
}
}
return true;
}
protected void addReferenceInfo(ReferenceInfo info)
{
try {
requestor.addReference(info);
} catch (Exception e) {
Logger.logException(e);
}
}
@Override
public boolean visitGeneral(ASTNode node) throws Exception
{
if (node instanceof org.eclipse.dltk.ast.statements.Block) {
node.traverse(new TwigIndexingVisitor(requestor, sourceModule));
}
return super.visitGeneral(node);
}
}
|
package de.equalit.liv;
import com.codename1.ui.Display;
import com.codename1.ui.Form;
import com.codename1.ui.Button;
import com.codename1.ui.Dialog;
import com.codename1.ui.Label;
import com.codename1.ui.plaf.UIManager;
import com.codename1.ui.util.Resources;
import com.codename1.io.Log;
import com.codename1.ui.Toolbar;
import java.io.IOException;
public class liv {
private Form current;
private Resources theme;
public void init(Object context) {
theme = UIManager.initFirstTheme("/theme");
// Enable Toolbar on all Forms by default
Toolbar.setGlobalToolbar(true);
// Pro only feature, uncomment if you have a pro subscription
// Log.bindCrashProtection(true);
}
public void start() {
if (current != null) {
current.show();
return;
}
Form home = new Form("LIV");
Button b = new Button("About LIV");
home.add(b);
b.addActionListener((e) -> Dialog.show("Lebensmittelinhaltverifizierer",
"Eine Smartphone-App, die Menschen mit Lebensmittelunvertrglichkeiten unerwnschte Inhaltsstoffe von Lebensmitteln auf einen Blick erfassen lsst.",
"OK", null));
Button c = new Button("Impressum");
home.add(c);
c.addActionListener((e) -> Dialog.show("Impressum", "equal-IT email: team@equal-it.de", "OK", null));
home.show();
}
public void stop() {
current = Display.getInstance().getCurrent();
if (current instanceof Dialog) {
((Dialog) current).dispose();
current = Display.getInstance().getCurrent();
}
}
public void destroy() {
}
}
|
package com.jetbrains.python.psi;
import com.intellij.codeInsight.CodeInsightUtilBase;
import com.intellij.codeInsight.completion.PrioritizedLookupElement;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.LookupElementBuilder;
import com.intellij.lang.ASTNode;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ModuleRootManager;
import com.intellij.openapi.ui.MessageType;
import com.intellij.openapi.ui.popup.Balloon;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.wm.WindowManager;
import com.intellij.psi.*;
import com.intellij.psi.tree.TokenSet;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.ui.awt.RelativePoint;
import com.intellij.util.ArrayUtil;
import com.intellij.util.Icons;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.SmartList;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.HashSet;
import com.jetbrains.python.PyNames;
import com.jetbrains.python.PyTokenTypes;
import com.jetbrains.python.psi.impl.PyBuiltinCache;
import com.jetbrains.python.psi.types.PyClassType;
import com.jetbrains.python.psi.types.PyType;
import com.jetbrains.python.psi.types.TypeEvalContext;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
import java.util.Set;
import static com.jetbrains.python.psi.PyFunction.Flag.*;
import static com.jetbrains.python.psi.impl.PyCallExpressionHelper.interpretAsStaticmethodOrClassmethodWrappingCall;
public class PyUtil {
private PyUtil() {
}
public static ASTNode getNextNonWhitespace(ASTNode after) {
ASTNode node = after;
do {
node = node.getTreeNext();
}
while (isWhitespace(node));
return node;
}
private static boolean isWhitespace(ASTNode node) {
return node != null && node.getElementType().equals(TokenType.WHITE_SPACE);
}
@NotNull
public static Set<PsiElement> getComments(PsiElement start) {
final Set<PsiElement> comments = new HashSet<PsiElement>();
PsiElement seeker = start.getPrevSibling();
if (seeker == null) seeker = start.getParent().getPrevSibling();
while (seeker instanceof PsiWhiteSpace || seeker instanceof PsiComment) {
if (seeker instanceof PsiComment) {
comments.add(seeker);
}
seeker = seeker.getPrevSibling();
}
return comments;
}
@Nullable
public static PsiElement getFirstNonCommentAfter(PsiElement start) {
PsiElement seeker = start;
while (seeker instanceof PsiWhiteSpace || seeker instanceof PsiComment) seeker = seeker.getNextSibling();
return seeker;
}
@Nullable
public static PsiElement getFirstNonCommentBefore(PsiElement start) {
PsiElement seeker = start;
while (seeker instanceof PsiWhiteSpace || seeker instanceof PsiComment) {
seeker = seeker.getPrevSibling();
}
return seeker;
}
@NotNull
public static <T extends PyElement> T[] getAllChildrenOfType(@NotNull PsiElement element, @NotNull Class<T> aClass) {
List<T> result = new SmartList<T>();
for (PsiElement child : element.getChildren()) {
if (instanceOf(child, aClass)) {
result.add((T)child);
}
else {
ContainerUtil.addAll(result, getAllChildrenOfType(child, aClass));
}
}
return ArrayUtil.toObjectArray(result, aClass);
}
public static PyExpression flattenParens(PyExpression expr) {
while (expr instanceof PyParenthesizedExpression) {
expr = ((PyParenthesizedExpression) expr).getContainedExpression();
}
return expr;
}
/**
* @see PyUtil#flattenedParensAndTuples
*/
protected static List<PyExpression> _unfoldParenExprs(PyExpression[] targets, List<PyExpression> receiver,
boolean unfoldListLiterals, boolean unfoldStarExpressions) {
// NOTE: this proliferation of instanceofs is not very beautiful. Maybe rewrite using a visitor.
for (PyExpression exp : targets) {
if (exp instanceof PyParenthesizedExpression) {
final PyParenthesizedExpression parex = (PyParenthesizedExpression)exp;
_unfoldParenExprs(new PyExpression[] { parex.getContainedExpression() }, receiver, unfoldListLiterals, unfoldStarExpressions);
}
else if (exp instanceof PyTupleExpression) {
final PyTupleExpression tupex = (PyTupleExpression)exp;
_unfoldParenExprs(tupex.getElements(), receiver, unfoldListLiterals, unfoldStarExpressions);
}
else if (exp instanceof PyListLiteralExpression && unfoldListLiterals) {
final PyListLiteralExpression listLiteral = (PyListLiteralExpression) exp;
_unfoldParenExprs(listLiteral.getElements(), receiver, unfoldListLiterals, unfoldStarExpressions);
}
else if (exp instanceof PyStarExpression && unfoldStarExpressions) {
_unfoldParenExprs(new PyExpression[] { ((PyStarExpression) exp).getExpression() }, receiver, unfoldListLiterals, unfoldStarExpressions);
}
else {
receiver.add(exp);
}
}
return receiver;
}
// Poor man's catamorhpism :)
/**
* Flattens the representation of every element in targets, and puts all results together.
* Elements of every tuple nested in target item are brought to the top level: (a, (b, (c, d))) -> (a, b, c, d)
* Typical usage: <code>flattenedParensAndTuples(some_tuple.getExpressions())</code>.
*
* @param targets target elements.
* @return the list of flattened expressions.
*/
@NotNull
public static List<PyExpression> flattenedParensAndTuples(PyExpression... targets) {
return _unfoldParenExprs(targets, new ArrayList<PyExpression>(targets.length), false, false);
}
@NotNull
public static List<PyExpression> flattenedParensAndLists(PyExpression... targets) {
return _unfoldParenExprs(targets, new ArrayList<PyExpression>(targets.length), true, true);
}
@NotNull
public static List<PyExpression> flattenedParensAndStars(PyExpression... targets) {
return _unfoldParenExprs(targets, new ArrayList<PyExpression>(targets.length), false, true);
}
// Poor man's filter
// TODO: move to a saner place
public static boolean instanceOf(Object obj, Class... possibleClasses) {
for (Class cls : possibleClasses) {
if (cls.isInstance(obj)) return true;
}
return false;
}
/**
* Produce a reasonable representation of a PSI element, good for debugging.
*
* @param elt element to represent; nulls and invalid nodes are ok.
* @param cutAtEOL if true, representation stops at nearest EOL inside the element.
* @return the representation.
*/
@NotNull
@NonNls
public static String getReadableRepr(PsiElement elt, final boolean cutAtEOL) {
if (elt == null) return "null!";
ASTNode node = elt.getNode();
if (node == null) {
return "null";
}
else {
String s = node.getText();
int cut_pos;
if (cutAtEOL) {
cut_pos = s.indexOf('\n');
}
else {
cut_pos = -1;
}
if (cut_pos < 0) cut_pos = s.length();
return s.substring(0, Math.min(cut_pos, s.length()));
}
}
@Nullable
public static PyClass getContainingClassOrSelf(final PsiElement element) {
PsiElement current = element;
while (current != null && !(current instanceof PyClass)) {
current = current.getParent();
}
return (PyClass)current;
}
/**
* @param element for which to obtain the file
* @return PyFile, or null, if there's no containing file, or it is not a PyFile.
*/
@Nullable
public static PyFile getContainingPyFile(PyElement element) {
final PsiFile containingFile = element.getContainingFile();
return containingFile instanceof PyFile ? (PyFile)containingFile : null;
}
/**
* Shows an information balloon in a reasonable place at the top right of the window.
*
* @param project our project
* @param message the text, HTML markup allowed
* @param messageType message type, changes the icon and the background.
*/
// TODO: move to a better place
public static void showBalloon(Project project, String message, MessageType messageType) {
// ripped from com.intellij.openapi.vcs.changes.ui.ChangesViewBalloonProblemNotifier
final JFrame frame = WindowManager.getInstance().getFrame(project.isDefault() ? null : project);
if (frame == null) return;
final JComponent component = frame.getRootPane();
if (component == null) return;
final Rectangle rect = component.getVisibleRect();
final Point p = new Point(rect.x + rect.width - 10, rect.y + 10);
final RelativePoint point = new RelativePoint(component, p);
JBPopupFactory.getInstance().createHtmlTextBalloonBuilder(message, messageType.getDefaultIcon(), messageType.getPopupBackground(), null)
.setShowCallout(false).setCloseButtonEnabled(true)
.createBalloon().show(point, Balloon.Position.atLeft);
}
@NonNls
/**
* Returns a quoted string representation, or "null".
*/
public static String nvl(Object s) {
if (s != null) {
return "'" + s.toString() + "'";
}
else {
return "null";
}
}
/**
* Adds an item into a comma-separated list in a PSI tree. E.g. can turn "foo, bar" into "foo, bar, baz", adding commas as needed.
*
* @param parent the element to represent the list; we're adding a child to it.
* @param newItem the element we're inserting (the "baz" in the example).
* @param beforeThis node to mark the insertion point inside the list; must belong to a child of target. Set to null to add first element.
* @param isFirst true if we don't need a comma before the element we're adding.
* @param isLast true if we don't need a comma after the element we're adding.
*/
public static void addListNode(PsiElement parent, PsiElement newItem, ASTNode beforeThis, boolean isFirst, boolean isLast) {
if (!CodeInsightUtilBase.preparePsiElementForWrite(parent)) {
return;
}
ASTNode node = parent.getNode();
assert node != null;
ASTNode itemNode = newItem.getNode();
assert itemNode != null;
Project project = parent.getProject();
PyElementGenerator gen = PyElementGenerator.getInstance(project);
if (!isFirst) node.addChild(gen.createComma(), beforeThis);
node.addChild(itemNode, beforeThis);
if (!isLast) node.addChild(gen.createComma(), beforeThis);
}
/**
* Removes an element from a a comma-separated list in a PSI tree. E.g. can turn "foo, bar, baz" into "foo, baz",
* removing commas as needed. It removes a trailing comma if it results from deletion.
*
* @param item what to remove. Its parent is considered the list, and commas must be its peers.
*/
public static void removeListNode(PsiElement item) {
PsiElement parent = item.getParent();
if (!CodeInsightUtilBase.preparePsiElementForWrite(parent)) {
return;
}
// remove comma after the item
ASTNode binder = parent.getNode();
assert binder != null : "parent node is null, ensureWritable() lied";
boolean got_comma_after = eraseWhitespaceAndComma(binder, item, false);
if (!got_comma_after) {
// there was not a comma after the item; remove a comma before the item
eraseWhitespaceAndComma(binder, item, true);
}
// finally
item.delete();
}
/**
* Removes whitespace and comma(s) that are siblings of the item, up to the first non-whitespace and non-comma.
*
* @param parent_node node of the parent of item.
* @param item starting point; we erase left or right of it, but not it.
* @param backwards true to erase prev siblings, false to erase next siblings.
* @return true if a comma was found and removed.
*/
private static boolean eraseWhitespaceAndComma(ASTNode parent_node, PsiElement item, boolean backwards) {
// we operate on AST, PSI won't let us delete whitespace easily.
boolean is_comma;
boolean got_comma = false;
ASTNode current = item.getNode();
ASTNode candidate;
boolean have_skipped_the_item = false;
while (current != null) {
candidate = current;
current = backwards ? current.getTreePrev() : current.getTreeNext();
if (have_skipped_the_item) {
is_comma = ",".equals(candidate.getText());
got_comma |= is_comma;
if (is_comma || candidate.getElementType() == TokenType.WHITE_SPACE) {
parent_node.removeChild(candidate);
}
else {
break;
}
}
else {
have_skipped_the_item = true;
}
}
return got_comma;
}
/**
* Collects superclasses of a class all the way up the inheritance chain. The order is <i>not</i> necessarily the MRO.
*/
@NotNull
public static List<PyClass> getAllSuperClasses(@NotNull PyClass pyClass) {
List<PyClass> superClasses = new ArrayList<PyClass>();
for (PyClass ancestor : pyClass.iterateAncestorClasses()) superClasses.add(ancestor);
return superClasses;
}
/**
* Finds the first identifier AST node under target element, and returns its text.
*
* @param target
* @return identifier text, or null.
*/
public static
@Nullable
String getIdentifier(PsiElement target) {
ASTNode node = target.getNode();
if (node != null) {
ASTNode ident_node = node.findChildByType(PyTokenTypes.IDENTIFIER);
if (ident_node != null) return ident_node.getText();
}
return null;
}
// TODO: move to a more proper place?
/**
* Determine the type of a special attribute. Currently supported: {@code __class__} and {@code __dict__}.
*
* @param ref reference to a possible attribute; only qualified references make sense.
* @return type, or null (if type cannot be determined, reference is not to a known attribute, etc.)
*/
@Nullable
public static PyType getSpecialAttributeType(@Nullable PyReferenceExpression ref, TypeEvalContext context) {
if (ref != null) {
PyExpression qualifier = ref.getQualifier();
if (qualifier != null) {
String attr_name = getIdentifier(ref);
if ("__class__".equals(attr_name)) {
PyType qual_type = context.getType(qualifier);
if (qual_type instanceof PyClassType) {
return new PyClassType(((PyClassType)qual_type).getPyClass(), true); // always as class, never instance
}
}
else if ("__dict__".equals(attr_name)) {
PyType qual_type = context.getType(qualifier);
if (qual_type instanceof PyClassType && ((PyClassType)qual_type).isDefinition()) {
return PyBuiltinCache.getInstance(ref).getDictType();
}
}
}
}
return null;
}
/**
* Makes sure that 'thing' is not null; else throws an {@link IncorrectOperationException}.
*
* @param thing what we check.
* @return thing, if not null.
*/
@NotNull
public static <T> T sure(T thing) {
if (thing == null) throw new IncorrectOperationException();
return thing;
}
/**
* Makes sure that the 'thing' is true; else throws an {@link IncorrectOperationException}.
*
* @param thing what we check.
*/
public static void sure(boolean thing) {
if (!thing) throw new IncorrectOperationException();
}
/**
* When a function is decorated many decorators, finds the deepest builtin decorator:
* <pre>
* @foo
* @classmethod <b># <-- that's it</b>
* @bar
* def moo(cls):
* pass
* </pre>
* @param node the allegedly decorated function
* @return name of the built-in decorator, or null (even if there are non-built-in decorators).
*/
@Nullable
public static String getClassOrStaticMethodDecorator(@NotNull final PyFunction node) {
PyDecoratorList decolist = node.getDecoratorList();
if (decolist != null) {
PyDecorator[] decos = decolist.getDecorators();
if (decos.length > 0) {
for (int i = decos.length - 1; i >= 0; i -= 1) {
PyDecorator deco = decos[i];
String deconame = deco.getName();
if (PyNames.CLASSMETHOD.equals(deconame) || PyNames.STATICMETHOD.equals(deconame)) {
return deconame;
}
for(PyKnownDecoratorProvider provider: KnownDecoratorProviderHolder.KNOWN_DECORATOR_PROVIDERS) {
String name = provider.toKnownDecorator(deconame);
if (name != null) {
return name;
}
}
}
}
}
return null;
}
public static class KnownDecoratorProviderHolder {
public static PyKnownDecoratorProvider[] KNOWN_DECORATOR_PROVIDERS = Extensions.getExtensions(PyKnownDecoratorProvider.EP_NAME);
private KnownDecoratorProviderHolder() {
}
}
/**
* Looks for two standard decorators to a function, or a wrapping assignment that closely follows it.
*
* @param function what to analyze
* @return a set of flags describing what was detected.
*/
@NotNull
public static Set<PyFunction.Flag> detectDecorationsAndWrappersOf(PyFunction function) {
Set<PyFunction.Flag> flags = EnumSet.noneOf(PyFunction.Flag.class);
String deconame = getClassOrStaticMethodDecorator(function);
if (PyNames.CLASSMETHOD.equals(deconame)) {
flags.add(CLASSMETHOD);
}
else if (PyNames.STATICMETHOD.equals(deconame)) flags.add(STATICMETHOD);
// implicit staticmethod __new__
PyClass cls = function.getContainingClass();
if (cls != null && PyNames.NEW.equals(function.getName()) && cls.isNewStyleClass()) flags.add(STATICMETHOD);
if (!flags.contains(CLASSMETHOD) && !flags.contains(STATICMETHOD)) { // not set by decos, look for reassignment
String func_name = function.getName();
if (func_name != null) {
PyAssignmentStatement assignment = PsiTreeUtil.getNextSiblingOfType(function, PyAssignmentStatement.class);
if (assignment != null) {
for (Pair<PyExpression, PyExpression> pair : assignment.getTargetsToValuesMapping()) {
PyExpression value = pair.getSecond();
if (value instanceof PyCallExpression) {
PyExpression target = pair.getFirst();
if (target instanceof PyTargetExpression && func_name.equals(target.getName())) {
Pair<String, PyFunction> interpreted = interpretAsStaticmethodOrClassmethodWrappingCall((PyCallExpression)value, function);
if (interpreted != null) {
PyFunction original = interpreted.getSecond();
if (original == function) {
String wrapper_name = interpreted.getFirst();
if (PyNames.CLASSMETHOD.equals(wrapper_name)) {
flags.add(CLASSMETHOD);
}
else if (PyNames.STATICMETHOD.equals(wrapper_name)) flags.add(STATICMETHOD);
flags.add(WRAPPED);
}
}
}
}
}
}
}
}
return flags;
}
/**
* Returns child element in the psi tree
*
* @param filter Types of expected child
* @param number number
* @param element tree parent node
* @return PsiElement - child psiElement
*/
@Nullable
public static PsiElement getChildByFilter(@NotNull final PsiElement element, final @NotNull TokenSet filter, final int number) {
final ASTNode node = element.getNode();
if (node != null) {
final ASTNode[] children = node.getChildren(filter);
return (0 <= number && number < children.length) ? children[number].getPsi() : null;
}
return null;
}
/**
* If argument is a PsiDirectory, turn it into a PsiFile that points to __init__.py in that directory.
* If there's no __init__.py there, null is returned, there's no point to resolve to a dir which is not a package.
* Alas, resolve() and multiResolve() can't return anything but a PyFile or PsiFileImpl.isPsiUpToDate() would fail.
* This is because isPsiUpToDate() relies on identity of objects returned by FileViewProvider.getPsi().
* If we ever need to exactly tell a dir from __init__.py, that logic has to change.
*
* @param target a resolve candidate.
* @return a PsiFile if target was a PsiDirectory, or null, or target unchanged.
*/
@Nullable
public static PsiElement turnDirIntoInit(PsiElement target) {
if (target instanceof PsiDirectory) {
final PsiDirectory dir = (PsiDirectory)target;
final PsiFile file = dir.findFile(PyNames.INIT_DOT_PY);
if (file != null) {
return file; // ResolveImportUtil will extract directory part as needed, everyone else are better off with a file.
}
else {
return null;
} // dir without __init__.py does not resolve
}
else {
return target;
} // don't touch non-dirs
}
/**
* Counts initial underscores of an identifier.
*
* @param name identifier
* @return 0 if no initial underscores found, 1 if there's only one underscore, 2 if there's two or more initial underscores.
*/
public static int getInitialUnderscores(String name) {
int underscores = 0;
if (name.startsWith("__")) {
underscores = 2;
}
else if (name.startsWith("_")) underscores = 1;
return underscores;
}
/**
* Tries to find nearest parent that conceals names defined inside it. Such elements are 'class' and 'def':
* anything defined within it does not seep to the namespace below them, but is concealed within.
*
* @param elt starting point of search.
* @return 'class' or 'def' element, or null if not found.
*/
@Nullable
public static PsiElement getConcealingParent(PsiElement elt) {
if (elt == null || elt instanceof PsiFile) {
return null;
}
PsiElement parent = PsiTreeUtil.getStubOrPsiParent(elt);
boolean jump_over = false;
while (parent != null) {
if (parent instanceof PyClass || parent instanceof Callable) {
if (jump_over) jump_over = false;
else return parent;
}
else if (parent instanceof PyDecoratorList) {
// decorators PSI is inside decorated things but their namespace is outside
jump_over = true;
}
else if (parent instanceof PsiFileSystemItem) {
break;
}
parent = PsiTreeUtil.getStubOrPsiParent(parent);
}
return null;
}
/**
* @param name
* @return true iff the name looks like a class-private one, starting with two underscores but not ending with two underscores.
*/
public static boolean isClassPrivateName(String name) {
return name.startsWith("__") && !name.endsWith("__");
}
public static boolean isPythonIdentifier(String name) {
return PyNames.isIdentifier(name);
}
public static LookupElement createNamedParameterLookup(String name) {
LookupElementBuilder lookupElementBuilder = LookupElementBuilder.create(name + "=").setIcon(Icons.PARAMETER_ICON);
return PrioritizedLookupElement.withGrouping(lookupElementBuilder, 1);
}
/**
* Peels argument expression of parentheses and of keyword argument wrapper
* @param expr an item of getArguments() array
* @return expression actually passed as argument
*/
@Nullable
public static PyExpression peelArgument(PyExpression expr) {
while (expr instanceof PyParenthesizedExpression) expr = ((PyParenthesizedExpression)expr).getContainedExpression();
if (expr instanceof PyKeywordArgument) expr = ((PyKeywordArgument)expr).getValueExpression();
return expr;
}
public static String getFirstParameterName(PyFunction container) {
String selfName = PyNames.CANONICAL_SELF;
if (container != null) {
final PyParameter[] params = container.getParameterList().getParameters();
if (params.length > 0) {
final PyNamedParameter named = params[0].getAsNamed();
if (named != null) {
selfName = named.getName();
}
}
}
return selfName;
}
@Nullable
public static VirtualFile findInRoots(Module module, String path) {
final ModuleRootManager moduleRootManager = ModuleRootManager.getInstance(module);
VirtualFile result = findInRoots(moduleRootManager.getContentRoots(), path);
if (result == null) {
result = findInRoots(moduleRootManager.getSourceRoots(), path);
}
return result;
}
@Nullable
public static VirtualFile findInRoots(VirtualFile[] roots, String path) {
for (VirtualFile root : roots) {
VirtualFile settingsFile = root.findFileByRelativePath(path);
if (settingsFile != null) {
return settingsFile;
}
}
return null;
}
@Nullable
public static List<String> getStringListFromTargetExpression(PyTargetExpression attr) {
PyExpression value = attr.findAssignedValue();
while (value instanceof PyParenthesizedExpression) {
value = ((PyParenthesizedExpression) value).getContainedExpression();
}
if (value instanceof PySequenceExpression) {
final PyExpression[] elements = ((PySequenceExpression)value).getElements();
List<String> result = new ArrayList<String>(elements.length);
for (PyExpression element : elements) {
if (!(element instanceof PyStringLiteralExpression)) {
return null;
}
result.add(((PyStringLiteralExpression) element).getStringValue());
}
return result;
}
return null;
}
@Nullable
public static String strValue(@Nullable PyExpression expression) {
return expression instanceof PyStringLiteralExpression ? ((PyStringLiteralExpression) expression).getStringValue() : null;
}
/**
* @param what thing to search for
* @param variants things to search among
* @return true iff what.equals() one of the variants.
*/
public static <T> boolean among(@NotNull T what, T... variants) {
for (T s : variants) {
if (what.equals(s)) return true;
}
return false;
}
public static class UnderscoreFilter implements Condition<String> {
private int myAllowed; // how many starting underscores is allowed: 0 is none, 1 is only one, 2 is two and more.
public UnderscoreFilter(int allowed) {
myAllowed = allowed;
}
public boolean value(String name) {
if (name == null) return false;
if (name.length() < 1) return false; // empty strings make no sense
int have_underscores = 0;
if (name.charAt(0) == '_') have_underscores = 1;
if (have_underscores != 0 && name.length() > 1 && name.charAt(1) == '_') have_underscores = 2;
return myAllowed >= have_underscores;
}
}
@Nullable
public static PyExpression getKeywordArgument(PyCallExpression expr, String keyword) {
for (PyExpression arg : expr.getArguments()) {
if (arg instanceof PyKeywordArgument) {
PyKeywordArgument kwarg = (PyKeywordArgument)arg;
if (keyword.equals(kwarg.getKeyword())) {
return kwarg.getValueExpression();
}
}
}
return null;
}
@Nullable
public static String getKeywordArgumentString(PyCallExpression expr, String keyword) {
return strValue(getKeywordArgument(expr, keyword));
}
public static boolean isExceptionClass(PyClass pyClass) {
return pyClass.isSubclass("BaseException");
}
public static class MethodFlags {
private boolean myIsStaticMethod;
private boolean myIsMetaclassMethod;
private boolean myIsSpecialMetaclassMethod;
private boolean myIsClassMethod;
/**
* @return true iff the method belongs to a metaclass (an ancestor of 'type').
*/
public boolean isMetaclassMethod() {
return myIsMetaclassMethod;
}
/**
* @return iff isMetaclassMethod and the method is either __init__ or __call__.
*/
public boolean isSpecialMetaclassMethod() {
return myIsSpecialMetaclassMethod;
}
public boolean isStaticMethod() {
return myIsStaticMethod;
}
public boolean isClassMethod() {
return myIsClassMethod;
}
private MethodFlags(boolean isClassMethod, boolean isStaticMethod, boolean isMetaclassMethod, boolean isSpecialMetaclassMethod) {
myIsClassMethod = isClassMethod;
myIsStaticMethod = isStaticMethod;
myIsMetaclassMethod = isMetaclassMethod;
myIsSpecialMetaclassMethod = isSpecialMetaclassMethod;
}
/**
* @param node a function
* @return a new flags object, or null if the function is not a method
*/
@Nullable
public static MethodFlags of(@NotNull PyFunction node) {
PyClass cls = node.getContainingClass();
if (cls != null) {
Set<PyFunction.Flag> flags = detectDecorationsAndWrappersOf(node);
boolean isMetaclassMethod = false;
PyClass type_cls = PyBuiltinCache.getInstance(node).getClass("type");
for (PyClass ancestor_cls : cls.iterateAncestorClasses()) {
if (ancestor_cls == type_cls) {
isMetaclassMethod = true;
break;
}
}
final String method_name = node.getName();
boolean isSpecialMetaclassMethod = isMetaclassMethod && method_name != null && among(method_name, PyNames.INIT, "__call__");
return new MethodFlags(flags.contains(CLASSMETHOD), flags.contains(STATICMETHOD), isMetaclassMethod, isSpecialMetaclassMethod);
}
return null;
}
}
}
|
package org.koreader.test.eink;
import java.util.Locale;
import android.content.Intent;
import android.graphics.Point;
import android.view.Display;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import org.koreader.launcher.device.freescale.NTXEPDController;
import org.koreader.launcher.device.rockchip.RK30xxEPDController;
import org.koreader.launcher.device.rockchip.RK33xxEPDController;
public class MainActivity extends android.app.Activity {
// tests
private static final int RK30xx = 1;
private static final int RK33xx = 2;
private static final int NTX_NEW= 3;
// device id.
private static final String MANUFACTURER = android.os.Build.MANUFACTURER;
private static final String BRAND = android.os.Build.BRAND;
private static final String MODEL = android.os.Build.MODEL;
private static final String PRODUCT = android.os.Build.PRODUCT;
private static final String HARDWARE = android.os.Build.HARDWARE;
// text view with device info
private TextView info;
@Override
public void onCreate(android.os.Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
info = findViewById(R.id.info);
TextView readmeReport = findViewById(R.id.readmeReport);
TextView rk30xx_description = findViewById(R.id.rk30xxText);
TextView rk33xx_description = findViewById(R.id.rk33xxText);
TextView ntx_new_description = findViewById(R.id.ntxNewText);
Button rk30xx_button = findViewById(R.id.rk30xxButton);
Button rk33xx_button = findViewById(R.id.rk33xxButton);
Button ntx_new_button = findViewById(R.id.ntxNewButton);
Button share_button = findViewById(R.id.shareButton);
/* current device info */
info.append("Manufacturer: " + MANUFACTURER + "\n");
info.append("Brand: " + BRAND + "\n");
info.append("Model: " + MODEL + "\n");
info.append("Product: " + PRODUCT + "\n");
info.append("Hardware: " + HARDWARE + "\n");
/* add platform if available */
String platform = "unknown";
try {
platform = (String) Class.forName("android.os.SystemProperties").getMethod(
"get", String.class).invoke(null, "ro.board.platform");
if (platform.length() < 2) {
platform = "unknown";
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (platform != null) {
info.append("Platform: " + platform + "\n");
}
}
readmeReport.setText("Did you see a flashing black to white eink update? Cool\n\n");
readmeReport.append("Go to github.com/koreader/koreader/issues/4551 ");
readmeReport.append("and share the following information with us");
/* rockchip rk30xx */
rk30xx_description.setText("This button should invoke a full refresh of Boyue T61/T62 clones.");
rk30xx_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
runEinkTest(RK30xx);
}
});
/* rockchip rk33xx */
rk33xx_description.setText("This button should work on boyue rk3368 clones.");
rk33xx_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
runEinkTest(RK33xx);
}
});
/* freescale/ntx - Newer Tolino/Nook devices */
ntx_new_description.setText("This button should work on modern Tolinos/Nooks and other ntx boards");
ntx_new_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
runEinkTest(NTX_NEW);
}
});
/* share button */
share_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
shareText(info.getText().toString());
}
});
}
private void runEinkTest(int test) {
boolean success = false;
info.append(String.format(Locale.US,"run test #%d -> ", test));
try {
View v = getWindow().getDecorView().findViewById(android.R.id.content);
if (test == RK30xx) {
info.append("rk30xx: ");
// force a flashing black->white update
if (RK30xxEPDController.requestEpdMode(v, "EPD_FULL", true))
success = true;
} else if (test == RK33xx) {
info.append("rk33xx: ");
if (RK33xxEPDController.requestEpdMode("EPD_FULL"))
success = true;
} else if (test == NTX_NEW) {
// get screen width and height
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
info.append("tolino: ");
if (NTXEPDController.requestEpdMode(v,
34, 50, 0, 0, width, height))
success = true;
}
} catch (Exception e) {
e.printStackTrace();
}
if (success)
info.append("pass\n");
else
info.append("fail\n");
}
private void shareText(String text) {
Intent i = new Intent(Intent.ACTION_SEND);
i.putExtra(Intent.EXTRA_TEXT, text);
i.setType("text/plain");
startActivity(Intent.createChooser(i, "e-ink test results"));
}
}
|
package cgeo.geocaching.files;
import cgeo.geocaching.Intents;
import com.robotium.solo.Solo;
import android.annotation.TargetApi;
import android.content.Intent;
import android.os.Build;
import android.test.ActivityInstrumentationTestCase2;
import android.test.suitebuilder.annotation.Suppress;
import android.widget.CheckBox;
import java.util.ArrayList;
@TargetApi(Build.VERSION_CODES.FROYO)
@Suppress
public class SimpleDirChooserUITest extends ActivityInstrumentationTestCase2<SimpleDirChooser> {
private Solo solo;
public SimpleDirChooserUITest() {
super(SimpleDirChooser.class);
}
@Override
public void setUp() throws Exception {
super.setUp();
setActivityIntent(new Intent().putExtra(Intents.EXTRA_START_DIR, "").putExtra(SimpleDirChooser.EXTRA_CHOOSE_FOR_WRITING, false));
solo = new Solo(getInstrumentation(), getActivity());
}
public ArrayList<CheckBox> getCurrentCheckBoxes() {
return solo.getCurrentViews(CheckBox.class);
}
public void testSingleSelection() throws InterruptedException {
// normally our activity should be ready, but we already had Jenkins report no checkboxes right here at the beginning
solo.waitForActivity(solo.getCurrentActivity().getClass().getSimpleName(), 2000);
assertChecked("Newly opened activity", 0);
solo.scrollToBottom();
pause();
// according to the documentation, automatic pauses only happen in the clickXYZ() methods.
// Therefore lets introduce a manual pause after the scrolling methods.
final int lastIndex = getCurrentCheckBoxes().size() - 1;
solo.clickOnCheckBox(lastIndex);
assertTrue(solo.isCheckBoxChecked(lastIndex));
assertFalse(solo.isCheckBoxChecked(0));
assertChecked("Clicked last checkbox", 1);
solo.scrollUp();
pause();
solo.scrollToBottom();
pause();
assertChecked("Refreshing last checkbox", 1);
solo.scrollToTop();
pause();
solo.clickOnCheckBox(0);
assertChecked("Clicked first checkbox", 1);
assertTrue(solo.isCheckBoxChecked(0));
solo.clickOnCheckBox(1);
assertChecked("Clicked second checkbox", 1);
assertTrue(solo.isCheckBoxChecked(1));
}
private static void pause() throws InterruptedException {
Thread.sleep(100);
}
private void assertChecked(String message, int expectedChecked) {
final ArrayList<CheckBox> boxes = getCurrentCheckBoxes();
assertNotNull("Could not get checkboxes", boxes);
assertTrue("There are no checkboxes", boxes.size() > 1);
int checked = 0;
for (int i = 0; i < boxes.size(); i++) {
if (solo.isCheckBoxChecked(i)) {
checked++;
}
}
assertEquals(message, expectedChecked, checked);
}
@Override
public void tearDown() throws Exception {
solo.finishOpenedActivities();
super.tearDown();
}
}
|
package com.yahoo.vespa.config.server.session;
import com.google.common.collect.HashMultiset;
import com.google.common.collect.Multiset;
import com.yahoo.cloud.config.ConfigserverConfig;
import com.yahoo.concurrent.DaemonThreadFactory;
import com.yahoo.concurrent.StripedExecutor;
import com.yahoo.config.FileReference;
import com.yahoo.config.application.api.ApplicationPackage;
import com.yahoo.config.application.api.DeployLogger;
import com.yahoo.config.model.api.ConfigDefinitionRepo;
import com.yahoo.config.model.application.provider.DeployData;
import com.yahoo.config.model.application.provider.FilesApplicationPackage;
import com.yahoo.config.provision.AllocatedHosts;
import com.yahoo.config.provision.ApplicationId;
import com.yahoo.config.provision.TenantName;
import com.yahoo.config.provision.Zone;
import com.yahoo.container.jdisc.secretstore.SecretStore;
import com.yahoo.io.IOUtils;
import com.yahoo.lang.SettableOptional;
import com.yahoo.path.Path;
import com.yahoo.transaction.AbstractTransaction;
import com.yahoo.transaction.NestedTransaction;
import com.yahoo.transaction.Transaction;
import com.yahoo.vespa.config.server.ConfigServerDB;
import com.yahoo.vespa.config.server.TimeoutBudget;
import com.yahoo.vespa.config.server.application.ApplicationSet;
import com.yahoo.vespa.config.server.application.PermanentApplicationPackage;
import com.yahoo.vespa.config.server.application.TenantApplications;
import com.yahoo.vespa.config.server.configchange.ConfigChangeActions;
import com.yahoo.vespa.config.server.deploy.TenantFileSystemDirs;
import com.yahoo.vespa.config.server.filedistribution.FileDirectory;
import com.yahoo.vespa.config.server.filedistribution.FileDistributionFactory;
import com.yahoo.vespa.config.server.http.UnknownVespaVersionException;
import com.yahoo.vespa.config.server.modelfactory.ActivatedModelsBuilder;
import com.yahoo.vespa.config.server.modelfactory.ModelFactoryRegistry;
import com.yahoo.vespa.config.server.monitoring.MetricUpdater;
import com.yahoo.vespa.config.server.monitoring.Metrics;
import com.yahoo.vespa.config.server.provision.HostProvisionerProvider;
import com.yahoo.vespa.config.server.tenant.TenantRepository;
import com.yahoo.vespa.config.server.zookeeper.SessionCounter;
import com.yahoo.vespa.config.server.zookeeper.ZKApplication;
import com.yahoo.vespa.curator.Curator;
import com.yahoo.vespa.defaults.Defaults;
import com.yahoo.vespa.flags.FlagSource;
import com.yahoo.yolean.Exceptions;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.ChildData;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
import org.apache.zookeeper.KeeperException;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import static com.yahoo.vespa.curator.Curator.CompletionWaiter;
/**
*
* Session repository for a tenant. Stores session state in zookeeper and file system. There are two
* different session types (RemoteSession and LocalSession).
*
* @author Ulf Lilleengen
* @author hmusum
*
*/
public class SessionRepository {
private static final Logger log = Logger.getLogger(SessionRepository.class.getName());
private static final FilenameFilter sessionApplicationsFilter = (dir, name) -> name.matches("\\d+");
private static final long nonExistingActiveSessionId = 0;
private final Object monitor = new Object();
private final Map<Long, LocalSession> localSessionCache = Collections.synchronizedMap(new HashMap<>());
private final Map<Long, RemoteSession> remoteSessionCache = Collections.synchronizedMap(new HashMap<>());
private final Map<Long, SessionStateWatcher> sessionStateWatchers = Collections.synchronizedMap(new HashMap<>());
private final Duration sessionLifetime;
private final Clock clock;
private final Curator curator;
private final Executor zkWatcherExecutor;
private final FileDistributionFactory fileDistributionFactory;
private final PermanentApplicationPackage permanentApplicationPackage;
private final FlagSource flagSource;
private final TenantFileSystemDirs tenantFileSystemDirs;
private final Metrics metrics;
private final MetricUpdater metricUpdater;
private final Curator.DirectoryCache directoryCache;
private final TenantApplications applicationRepo;
private final SessionPreparer sessionPreparer;
private final Path sessionsPath;
private final TenantName tenantName;
private final SessionCounter sessionCounter;
private final SecretStore secretStore;
private final HostProvisionerProvider hostProvisionerProvider;
private final ConfigserverConfig configserverConfig;
private final ConfigServerDB configServerDB;
private final Zone zone;
private final ModelFactoryRegistry modelFactoryRegistry;
private final ConfigDefinitionRepo configDefinitionRepo;
private final int maxNodeSize;
public SessionRepository(TenantName tenantName,
TenantApplications applicationRepo,
SessionPreparer sessionPreparer,
Curator curator,
Metrics metrics,
StripedExecutor<TenantName> zkWatcherExecutor,
FileDistributionFactory fileDistributionFactory,
PermanentApplicationPackage permanentApplicationPackage,
FlagSource flagSource,
ExecutorService zkCacheExecutor,
SecretStore secretStore,
HostProvisionerProvider hostProvisionerProvider,
ConfigserverConfig configserverConfig,
ConfigServerDB configServerDB,
Zone zone,
Clock clock,
ModelFactoryRegistry modelFactoryRegistry,
ConfigDefinitionRepo configDefinitionRepo,
int maxNodeSize) {
this.tenantName = tenantName;
sessionCounter = new SessionCounter(curator, tenantName);
this.sessionsPath = TenantRepository.getSessionsPath(tenantName);
this.clock = clock;
this.curator = curator;
this.sessionLifetime = Duration.ofSeconds(configserverConfig.sessionLifetime());
this.zkWatcherExecutor = command -> zkWatcherExecutor.execute(tenantName, command);
this.fileDistributionFactory = fileDistributionFactory;
this.permanentApplicationPackage = permanentApplicationPackage;
this.flagSource = flagSource;
this.tenantFileSystemDirs = new TenantFileSystemDirs(configServerDB, tenantName);
this.applicationRepo = applicationRepo;
this.sessionPreparer = sessionPreparer;
this.metrics = metrics;
this.metricUpdater = metrics.getOrCreateMetricUpdater(Metrics.createDimensions(tenantName));
this.secretStore = secretStore;
this.hostProvisionerProvider = hostProvisionerProvider;
this.configserverConfig = configserverConfig;
this.configServerDB = configServerDB;
this.zone = zone;
this.modelFactoryRegistry = modelFactoryRegistry;
this.configDefinitionRepo = configDefinitionRepo;
this.maxNodeSize = maxNodeSize;
loadSessions(); // Needs to be done before creating cache below
this.directoryCache = curator.createDirectoryCache(sessionsPath.getAbsolute(), false, false, zkCacheExecutor);
this.directoryCache.addListener(this::childEvent);
this.directoryCache.start();
}
private void loadSessions() {
ExecutorService executor = Executors.newFixedThreadPool(Math.max(8, Runtime.getRuntime().availableProcessors()),
new DaemonThreadFactory("load-sessions-"));
loadSessions(executor);
}
// For testing
void loadSessions(ExecutorService executor) {
loadRemoteSessions(executor);
try {
executor.shutdown();
if ( ! executor.awaitTermination(1, TimeUnit.MINUTES))
log.log(Level.INFO, "Executor did not terminate");
} catch (InterruptedException e) {
log.log(Level.WARNING, "Shutdown of executor for loading sessions failed: " + Exceptions.toMessageString(e));
}
}
public void addLocalSession(LocalSession session) {
long sessionId = session.getSessionId();
localSessionCache.put(sessionId, session);
if (remoteSessionCache.get(sessionId) == null)
createRemoteSession(sessionId);
}
public LocalSession getLocalSession(long sessionId) {
return localSessionCache.get(sessionId);
}
/** Returns a copy of local sessions */
public Collection<LocalSession> getLocalSessions() {
return List.copyOf(localSessionCache.values());
}
public Set<LocalSession> getLocalSessionsFromFileSystem() {
File[] sessions = tenantFileSystemDirs.sessionsPath().listFiles(sessionApplicationsFilter);
if (sessions == null) return Set.of();
Set<LocalSession> sessionIds = new HashSet<>();
for (File session : sessions) {
long sessionId = Long.parseLong(session.getName());
SessionZooKeeperClient sessionZKClient = createSessionZooKeeperClient(sessionId);
File sessionDir = getAndValidateExistingSessionAppDir(sessionId);
ApplicationPackage applicationPackage = FilesApplicationPackage.fromFile(sessionDir);
LocalSession localSession = new LocalSession(tenantName, sessionId, applicationPackage, sessionZKClient);
sessionIds.add(localSession);
}
return sessionIds;
}
public ConfigChangeActions prepareLocalSession(Session session, DeployLogger logger, PrepareParams params, Instant now) {
params.vespaVersion().ifPresent(version -> {
if ( ! params.isBootstrap() && ! modelFactoryRegistry.allVersions().contains(version))
throw new UnknownVespaVersionException("Vespa version '" + version + "' not known by this configserver");
});
applicationRepo.createApplication(params.getApplicationId()); // TODO jvenstad: This is wrong, but it has to be done now, since preparation can change the application ID of a session :(
logger.log(Level.FINE, "Created application " + params.getApplicationId());
long sessionId = session.getSessionId();
SessionZooKeeperClient sessionZooKeeperClient = createSessionZooKeeperClient(sessionId);
Optional<CompletionWaiter> waiter = params.isDryRun()
? Optional.empty()
: Optional.of(sessionZooKeeperClient.createPrepareWaiter());
Optional<ApplicationSet> activeApplicationSet = getActiveApplicationSet(params.getApplicationId());
ConfigChangeActions actions = sessionPreparer.prepare(applicationRepo.getHostValidator(), logger, params,
activeApplicationSet, now, getSessionAppDir(sessionId),
session.getApplicationPackage(), sessionZooKeeperClient)
.getConfigChangeActions();
setPrepared(session);
waiter.ifPresent(w -> w.awaitCompletion(params.getTimeoutBudget().timeLeft()));
return actions;
}
public LocalSession createSessionFromExisting(Session existingSession,
boolean internalRedeploy,
TimeoutBudget timeoutBudget) {
ApplicationId existingApplicationId = existingSession.getApplicationId();
File existingApp = getSessionAppDir(existingSession.getSessionId());
LocalSession session = createSessionFromApplication(existingApp, existingApplicationId, internalRedeploy, timeoutBudget);
// Note: Setters below need to be kept in sync with calls in SessionPreparer.writeStateToZooKeeper()
session.setApplicationId(existingApplicationId);
session.setApplicationPackageReference(existingSession.getApplicationPackageReference());
session.setVespaVersion(existingSession.getVespaVersion());
session.setDockerImageRepository(existingSession.getDockerImageRepository());
session.setAthenzDomain(existingSession.getAthenzDomain());
session.setTenantSecretStores(existingSession.getTenantSecretStores());
session.setOperatorCertificates(existingSession.getOperatorCertificates());
return session;
}
/**
* Creates a new deployment session from an application package.
*
* @param applicationDirectory a File pointing to an application.
* @param applicationId application id for this new session.
* @param timeoutBudget Timeout for creating session and waiting for other servers.
* @return a new session
*/
public LocalSession createSessionFromApplicationPackage(File applicationDirectory, ApplicationId applicationId, TimeoutBudget timeoutBudget) {
applicationRepo.createApplication(applicationId);
return createSessionFromApplication(applicationDirectory, applicationId, false, timeoutBudget);
}
private void createLocalSession(File applicationFile, ApplicationId applicationId, long sessionId) {
try {
ApplicationPackage applicationPackage = createApplicationPackage(applicationFile, applicationId, sessionId, false);
createLocalSession(sessionId, applicationPackage);
} catch (Exception e) {
throw new RuntimeException("Error creating session " + sessionId, e);
}
}
// Will delete session data in ZooKeeper and file system
public void deleteLocalSession(LocalSession session) {
long sessionId = session.getSessionId();
log.log(Level.FINE, () -> "Deleting local session " + sessionId);
SessionStateWatcher watcher = sessionStateWatchers.remove(sessionId);
if (watcher != null) watcher.close();
localSessionCache.remove(sessionId);
NestedTransaction transaction = new NestedTransaction();
transaction.add(FileTransaction.from(FileOperations.delete(getSessionAppDir(sessionId).getAbsolutePath())));
transaction.commit();
}
private void deleteAllSessions() {
for (LocalSession session : getLocalSessions()) {
deleteLocalSession(session);
}
}
public RemoteSession getRemoteSession(long sessionId) {
return remoteSessionCache.get(sessionId);
}
/** Returns a copy of remote sessions */
public Collection<RemoteSession> getRemoteSessions() {
return List.copyOf(remoteSessionCache.values());
}
public List<Long> getRemoteSessionsFromZooKeeper() {
return getSessionList(curator.getChildren(sessionsPath));
}
public RemoteSession createRemoteSession(long sessionId) {
SessionZooKeeperClient sessionZKClient = createSessionZooKeeperClient(sessionId);
RemoteSession session = new RemoteSession(tenantName, sessionId, sessionZKClient);
RemoteSession newSession = loadSessionIfActive(session).orElse(session);
remoteSessionCache.put(sessionId, newSession);
updateSessionStateWatcher(sessionId, newSession);
return newSession;
}
public int deleteExpiredRemoteSessions(Clock clock, Duration expiryTime) {
int deleted = 0;
for (long sessionId : getRemoteSessionsFromZooKeeper()) {
Session session = remoteSessionCache.get(sessionId);
if (session == null) continue; // Internal sessions not in sync with zk, continue
if (session.getStatus() == Session.Status.ACTIVATE) continue;
if (sessionHasExpired(session.getCreateTime(), expiryTime, clock)) {
log.log(Level.FINE, () -> "Remote session " + sessionId + " for " + tenantName + " has expired, deleting it");
deleteRemoteSessionFromZooKeeper(session);
deleted++;
}
}
return deleted;
}
public void deactivateAndUpdateCache(RemoteSession remoteSession) {
RemoteSession session = remoteSession.deactivated();
remoteSessionCache.put(session.getSessionId(), session);
}
public void deleteRemoteSessionFromZooKeeper(Session session) {
SessionZooKeeperClient sessionZooKeeperClient = createSessionZooKeeperClient(session.getSessionId());
Transaction transaction = sessionZooKeeperClient.deleteTransaction();
transaction.commit();
transaction.close();
}
private boolean sessionHasExpired(Instant created, Duration expiryTime, Clock clock) {
return (created.plus(expiryTime).isBefore(clock.instant()));
}
private List<Long> getSessionListFromDirectoryCache(List<ChildData> children) {
return getSessionList(children.stream()
.map(child -> Path.fromString(child.getPath()).getName())
.collect(Collectors.toList()));
}
private List<Long> getSessionList(List<String> children) {
return children.stream().map(Long::parseLong).collect(Collectors.toList());
}
private void loadRemoteSessions(ExecutorService executor) throws NumberFormatException {
Map<Long, Future<?>> futures = new HashMap<>();
for (long sessionId : getRemoteSessionsFromZooKeeper()) {
futures.put(sessionId, executor.submit(() -> sessionAdded(sessionId)));
}
futures.forEach((sessionId, future) -> {
try {
future.get();
log.log(Level.FINE, () -> "Remote session " + sessionId + " loaded");
} catch (ExecutionException | InterruptedException e) {
throw new RuntimeException("Could not load remote session " + sessionId, e);
}
});
}
/**
* A session for which we don't have a watcher, i.e. hitherto unknown to us.
*
* @param sessionId session id for the new session
*/
public void sessionAdded(long sessionId) {
if (hasStatusDeleted(sessionId)) return;
log.log(Level.FINE, () -> "Adding remote session " + sessionId);
Session session = createRemoteSession(sessionId);
if (session.getStatus() == Session.Status.NEW) {
log.log(Level.FINE, () -> session.logPre() + "Confirming upload for session " + sessionId);
confirmUpload(session);
}
createLocalSessionFromDistributedApplicationPackage(sessionId);
}
private boolean hasStatusDeleted(long sessionId) {
SessionZooKeeperClient sessionZKClient = createSessionZooKeeperClient(sessionId);
RemoteSession session = new RemoteSession(tenantName, sessionId, sessionZKClient);
return session.getStatus() == Session.Status.DELETE;
}
void activate(RemoteSession session) {
long sessionId = session.getSessionId();
CompletionWaiter waiter = createSessionZooKeeperClient(sessionId).getActiveWaiter();
log.log(Level.FINE, () -> session.logPre() + "Activating " + sessionId);
applicationRepo.activateApplication(ensureApplicationLoaded(session), sessionId);
log.log(Level.FINE, () -> session.logPre() + "Notifying " + waiter);
notifyCompletion(waiter);
log.log(Level.INFO, session.logPre() + "Session activated: " + sessionId);
}
private Optional<RemoteSession> loadSessionIfActive(RemoteSession session) {
for (ApplicationId applicationId : applicationRepo.activeApplications()) {
if (applicationRepo.requireActiveSessionOf(applicationId) == session.getSessionId()) {
log.log(Level.FINE, () -> "Found active application for session " + session.getSessionId() + " , loading it");
applicationRepo.activateApplication(ensureApplicationLoaded(session), session.getSessionId());
log.log(Level.INFO, session.logPre() + "Application activated successfully: " + applicationId + " (generation " + session.getSessionId() + ")");
return Optional.ofNullable(remoteSessionCache.get(session.getSessionId()));
}
}
return Optional.empty();
}
void prepareRemoteSession(RemoteSession session) {
SessionZooKeeperClient sessionZooKeeperClient = createSessionZooKeeperClient(session.getSessionId());
CompletionWaiter waiter = sessionZooKeeperClient.getPrepareWaiter();
ensureApplicationLoaded(session);
notifyCompletion(waiter);
}
public ApplicationSet ensureApplicationLoaded(RemoteSession session) {
if (session.applicationSet().isPresent()) {
return session.applicationSet().get();
}
Optional<Long> activeSessionId = getActiveSessionId(session.getApplicationId());
Optional<ApplicationSet> previousApplicationSet = activeSessionId.filter(session::isNewerThan)
.flatMap(this::getApplicationSet);
ApplicationSet applicationSet = loadApplication(session, previousApplicationSet);
RemoteSession activated = session.activated(applicationSet);
long sessionId = activated.getSessionId();
remoteSessionCache.put(sessionId, activated);
updateSessionStateWatcher(sessionId, activated);
return applicationSet;
}
void confirmUpload(Session session) {
CompletionWaiter waiter = session.getSessionZooKeeperClient().getUploadWaiter();
long sessionId = session.getSessionId();
log.log(Level.FINE, () -> "Notifying upload waiter for session " + sessionId);
notifyCompletion(waiter);
log.log(Level.FINE, () -> "Done notifying upload for session " + sessionId);
}
void notifyCompletion(CompletionWaiter completionWaiter) {
try {
completionWaiter.notifyCompletion();
} catch (RuntimeException e) {
// Throw only if we get something else than NoNodeException or NodeExistsException.
// NoNodeException might happen when the session is no longer in use (e.g. the app using this session
// has been deleted) and this method has not been called yet for the previous session operation on a
// minority of the config servers.
// NodeExistsException might happen if an event for this node is delivered more than once, in that case
// this is a no-op
Set<Class<? extends KeeperException>> acceptedExceptions = Set.of(KeeperException.NoNodeException.class,
KeeperException.NodeExistsException.class);
Class<? extends Throwable> exceptionClass = e.getCause().getClass();
if (acceptedExceptions.contains(exceptionClass))
log.log(Level.FINE, () -> "Not able to notify completion for session (" + completionWaiter + ")," +
" node " + (exceptionClass.equals(KeeperException.NoNodeException.class)
? "has been deleted"
: "already exists"));
else
throw e;
}
}
private ApplicationSet loadApplication(Session session, Optional<ApplicationSet> previousApplicationSet) {
log.log(Level.FINE, () -> "Loading application for " + session);
SessionZooKeeperClient sessionZooKeeperClient = createSessionZooKeeperClient(session.getSessionId());
ApplicationPackage applicationPackage = sessionZooKeeperClient.loadApplicationPackage();
ActivatedModelsBuilder builder = new ActivatedModelsBuilder(session.getTenantName(),
session.getSessionId(),
sessionZooKeeperClient,
previousApplicationSet,
sessionPreparer.getExecutor(),
curator,
metrics,
permanentApplicationPackage,
flagSource,
secretStore,
hostProvisionerProvider,
configserverConfig,
zone,
modelFactoryRegistry,
configDefinitionRepo);
// Read hosts allocated on the config server instance which created this
SettableOptional<AllocatedHosts> allocatedHosts = new SettableOptional<>(applicationPackage.getAllocatedHosts());
return ApplicationSet.fromList(builder.buildModels(session.getApplicationId(),
sessionZooKeeperClient.readDockerImageRepository(),
sessionZooKeeperClient.readVespaVersion(),
applicationPackage,
allocatedHosts,
clock.instant()));
}
private void nodeChanged() {
zkWatcherExecutor.execute(() -> {
Multiset<Session.Status> sessionMetrics = HashMultiset.create();
getRemoteSessions().forEach(session -> sessionMetrics.add(session.getStatus()));
metricUpdater.setNewSessions(sessionMetrics.count(Session.Status.NEW));
metricUpdater.setPreparedSessions(sessionMetrics.count(Session.Status.PREPARE));
metricUpdater.setActivatedSessions(sessionMetrics.count(Session.Status.ACTIVATE));
metricUpdater.setDeactivatedSessions(sessionMetrics.count(Session.Status.DEACTIVATE));
});
}
@SuppressWarnings("unused")
private void childEvent(CuratorFramework ignored, PathChildrenCacheEvent event) {
zkWatcherExecutor.execute(() -> {
log.log(Level.FINE, () -> "Got child event: " + event);
switch (event.getType()) {
case CHILD_ADDED:
case CHILD_REMOVED:
case CONNECTION_RECONNECTED:
sessionsChanged();
break;
default:
break;
}
});
}
public void deleteExpiredSessions(Map<ApplicationId, Long> activeSessions) {
log.log(Level.FINE, () -> "Purging old sessions for tenant '" + tenantName + "'");
Set<LocalSession> toDelete = new HashSet<>();
try {
for (LocalSession candidate : getLocalSessionsFromFileSystem()) {
Instant createTime = candidate.getCreateTime();
log.log(Level.FINE, () -> "Candidate session for deletion: " + candidate.getSessionId() + ", created: " + createTime);
if (hasExpired(candidate) && canBeDeleted(candidate)) {
toDelete.add(candidate);
} else if (createTime.plus(Duration.ofDays(1)).isBefore(clock.instant())) {
// Sessions with state ACTIVATE, but which are not actually active
Optional<ApplicationId> applicationId = candidate.getOptionalApplicationId();
if (applicationId.isEmpty()) continue;
Long activeSession = activeSessions.get(applicationId.get());
if (activeSession == null || activeSession != candidate.getSessionId()) {
toDelete.add(candidate);
log.log(Level.INFO, "Deleted inactive session " + candidate.getSessionId() + " created " +
createTime + " for '" + applicationId + "'");
}
}
}
toDelete.forEach(this::deleteLocalSession);
// Make sure to catch here, to avoid executor just dying in case of issues ...
} catch (Throwable e) {
log.log(Level.WARNING, "Error when purging old sessions ", e);
}
log.log(Level.FINE, () -> "Done purging old sessions");
}
private boolean hasExpired(LocalSession candidate) {
return candidate.getCreateTime().plus(sessionLifetime).isBefore(clock.instant());
}
// Sessions with state other than UNKNOWN or ACTIVATE
private boolean canBeDeleted(LocalSession candidate) {
return ! List.of(Session.Status.UNKNOWN, Session.Status.ACTIVATE).contains(candidate.getStatus());
}
private void ensureSessionPathDoesNotExist(long sessionId) {
Path sessionPath = getSessionPath(sessionId);
if (curator.exists(sessionPath)) {
throw new IllegalArgumentException("Path " + sessionPath.getAbsolute() + " already exists in ZooKeeper");
}
}
private ApplicationPackage createApplication(File userDir,
File configApplicationDir,
ApplicationId applicationId,
long sessionId,
Optional<Long> currentlyActiveSessionId,
boolean internalRedeploy) {
long deployTimestamp = System.currentTimeMillis();
String user = System.getenv("USER");
if (user == null) {
user = "unknown";
}
DeployData deployData = new DeployData(user, userDir.getAbsolutePath(), applicationId, deployTimestamp,
internalRedeploy, sessionId, currentlyActiveSessionId.orElse(nonExistingActiveSessionId));
return FilesApplicationPackage.fromFileWithDeployData(configApplicationDir, deployData);
}
private LocalSession createSessionFromApplication(File applicationFile,
ApplicationId applicationId,
boolean internalRedeploy,
TimeoutBudget timeoutBudget) {
long sessionId = getNextSessionId();
try {
ensureSessionPathDoesNotExist(sessionId);
ApplicationPackage app = createApplicationPackage(applicationFile, applicationId, sessionId, internalRedeploy);
log.log(Level.FINE, () -> TenantRepository.logPre(tenantName) + "Creating session " + sessionId + " in ZooKeeper");
SessionZooKeeperClient sessionZKClient = createSessionZooKeeperClient(sessionId);
sessionZKClient.createNewSession(clock.instant());
CompletionWaiter waiter = sessionZKClient.getUploadWaiter();
LocalSession session = new LocalSession(tenantName, sessionId, app, sessionZKClient);
waiter.awaitCompletion(Duration.ofSeconds(Math.min(120, timeoutBudget.timeLeft().getSeconds())));
addLocalSession(session);
return session;
} catch (Exception e) {
throw new RuntimeException("Error creating session " + sessionId, e);
}
}
private ApplicationPackage createApplicationPackage(File applicationFile,
ApplicationId applicationId,
long sessionId,
boolean internalRedeploy) throws IOException {
// Synchronize to avoid threads trying to create an application package concurrently
// (e.g. a maintainer and an external deployment)
synchronized (monitor) {
Optional<Long> activeSessionId = getActiveSessionId(applicationId);
File userApplicationDir = getSessionAppDir(sessionId);
copyApp(applicationFile, userApplicationDir);
ApplicationPackage applicationPackage = createApplication(applicationFile,
userApplicationDir,
applicationId,
sessionId,
activeSessionId,
internalRedeploy);
applicationPackage.writeMetaData();
return applicationPackage;
}
}
public Optional<ApplicationSet> getActiveApplicationSet(ApplicationId appId) {
return applicationRepo.activeSessionOf(appId).flatMap(this::getApplicationSet);
}
private Optional<ApplicationSet> getApplicationSet(long sessionId) {
Optional<ApplicationSet> applicationSet = Optional.empty();
try {
applicationSet = Optional.ofNullable(getRemoteSession(sessionId)).map(this::ensureApplicationLoaded);
} catch (IllegalArgumentException e) {
// Do nothing if we have no currently active session
}
return applicationSet;
}
private void copyApp(File sourceDir, File destinationDir) throws IOException {
if (destinationDir.exists()) {
log.log(Level.INFO, "Destination dir " + destinationDir + " already exists, app has already been copied");
return;
}
if (! sourceDir.isDirectory())
throw new IllegalArgumentException(sourceDir.getAbsolutePath() + " is not a directory");
// Copy app atomically: Copy to a temp dir and move to destination
java.nio.file.Path tempDestinationDir = null;
try {
tempDestinationDir = Files.createTempDirectory(destinationDir.getParentFile().toPath(), "app-package");
log.log(Level.FINE, "Copying dir " + sourceDir.getAbsolutePath() + " to " + tempDestinationDir.toFile().getAbsolutePath());
IOUtils.copyDirectory(sourceDir, tempDestinationDir.toFile());
moveSearchDefinitionsToSchemasDir(tempDestinationDir);
log.log(Level.FINE, "Moving " + tempDestinationDir + " to " + destinationDir.getAbsolutePath());
Files.move(tempDestinationDir, destinationDir.toPath(), StandardCopyOption.ATOMIC_MOVE);
} finally {
// In case some of the operations above fail
if (tempDestinationDir != null)
IOUtils.recursiveDeleteDir(tempDestinationDir.toFile());
}
}
// TODO: Remove in Vespa 8 (when we don't allow files in SEARCH_DEFINITIONS_DIR)
// Copies schemas from searchdefinitions/ to schemas/ if searchdefinitions/ exists
private void moveSearchDefinitionsToSchemasDir(java.nio.file.Path applicationDir) throws IOException {
File schemasDir = applicationDir.resolve(ApplicationPackage.SCHEMAS_DIR.getRelative()).toFile();
File sdDir = applicationDir.resolve(ApplicationPackage.SEARCH_DEFINITIONS_DIR.getRelative()).toFile();
if (sdDir.exists() && sdDir.isDirectory()) {
File[] sdFiles = sdDir.listFiles();
if (sdFiles != null) {
Files.createDirectories(schemasDir.toPath());
Arrays.asList(sdFiles).forEach(file -> Exceptions.uncheck(
() -> Files.move(file.toPath(),
schemasDir.toPath().resolve(file.toPath().getFileName()),
StandardCopyOption.REPLACE_EXISTING)));
}
Files.delete(sdDir.toPath());
}
}
/**
* Returns a new session instance for the given session id.
*/
void createSessionFromId(long sessionId) {
File sessionDir = getAndValidateExistingSessionAppDir(sessionId);
ApplicationPackage applicationPackage = FilesApplicationPackage.fromFile(sessionDir);
createLocalSession(sessionId, applicationPackage);
}
void createLocalSession(long sessionId, ApplicationPackage applicationPackage) {
SessionZooKeeperClient sessionZKClient = createSessionZooKeeperClient(sessionId);
LocalSession session = new LocalSession(tenantName, sessionId, applicationPackage, sessionZKClient);
addLocalSession(session);
}
/**
* Returns a new local session for the given session id if it does not already exist.
* Will also add the session to the local session cache if necessary
*/
public void createLocalSessionFromDistributedApplicationPackage(long sessionId) {
if (applicationRepo.sessionExistsInFileSystem(sessionId)) {
log.log(Level.FINE, () -> "Local session for session id " + sessionId + " already exists");
createSessionFromId(sessionId);
return;
}
SessionZooKeeperClient sessionZKClient = createSessionZooKeeperClient(sessionId);
FileReference fileReference = sessionZKClient.readApplicationPackageReference();
log.log(Level.FINE, () -> "File reference for session id " + sessionId + ": " + fileReference);
if (fileReference != null) {
File rootDir = new File(Defaults.getDefaults().underVespaHome(configserverConfig.fileReferencesDir()));
File sessionDir;
FileDirectory fileDirectory = new FileDirectory(rootDir);
try {
sessionDir = fileDirectory.getFile(fileReference);
} catch (IllegalArgumentException e) {
// We cannot be guaranteed that the file reference exists (it could be that it has not
// been downloaded yet), and e.g when bootstrapping we cannot throw an exception in that case
log.log(Level.FINE, () -> "File reference for session id " + sessionId + ": " + fileReference + " not found in " + fileDirectory);
return;
}
ApplicationId applicationId = sessionZKClient.readApplicationId()
.orElseThrow(() -> new RuntimeException("Could not find application id for session " + sessionId));
log.log(Level.FINE, () -> "Creating local session for tenant '" + tenantName + "' with session id " + sessionId);
createLocalSession(sessionDir, applicationId, sessionId);
}
}
private Optional<Long> getActiveSessionId(ApplicationId applicationId) {
List<ApplicationId> applicationIds = applicationRepo.activeApplications();
return applicationIds.contains(applicationId)
? Optional.of(applicationRepo.requireActiveSessionOf(applicationId))
: Optional.empty();
}
private long getNextSessionId() {
return sessionCounter.nextSessionId();
}
public Path getSessionPath(long sessionId) {
return sessionsPath.append(String.valueOf(sessionId));
}
Path getSessionStatePath(long sessionId) {
return getSessionPath(sessionId).append(ZKApplication.SESSIONSTATE_ZK_SUBPATH);
}
private SessionZooKeeperClient createSessionZooKeeperClient(long sessionId) {
return new SessionZooKeeperClient(curator,
tenantName,
sessionId,
configserverConfig.serverId(),
fileDistributionFactory.createFileManager(getSessionAppDir(sessionId)),
maxNodeSize);
}
private File getAndValidateExistingSessionAppDir(long sessionId) {
File appDir = getSessionAppDir(sessionId);
if (!appDir.exists() || !appDir.isDirectory()) {
throw new IllegalArgumentException("Unable to find correct application directory for session " + sessionId);
}
return appDir;
}
private File getSessionAppDir(long sessionId) {
return new TenantFileSystemDirs(configServerDB, tenantName).getUserApplicationDir(sessionId);
}
private void updateSessionStateWatcher(long sessionId, RemoteSession remoteSession) {
SessionStateWatcher sessionStateWatcher = sessionStateWatchers.get(sessionId);
if (sessionStateWatcher == null) {
Curator.FileCache fileCache = curator.createFileCache(getSessionStatePath(sessionId).getAbsolute(), false);
fileCache.addListener(this::nodeChanged);
sessionStateWatchers.put(sessionId, new SessionStateWatcher(fileCache, remoteSession, metricUpdater, zkWatcherExecutor, this));
} else {
sessionStateWatcher.updateRemoteSession(remoteSession);
}
}
@Override
public String toString() {
return getLocalSessions().toString();
}
public Clock clock() { return clock; }
public void close() {
deleteAllSessions();
tenantFileSystemDirs.delete();
try {
if (directoryCache != null) {
directoryCache.close();
}
} catch (Exception e) {
log.log(Level.WARNING, "Exception when closing path cache", e);
} finally {
checkForRemovedSessions(new ArrayList<>());
}
}
private void sessionsChanged() throws NumberFormatException {
List<Long> sessions = getSessionListFromDirectoryCache(directoryCache.getCurrentData());
checkForRemovedSessions(sessions);
checkForAddedSessions(sessions);
}
private void checkForRemovedSessions(List<Long> existingSessions) {
for (Iterator<RemoteSession> it = remoteSessionCache.values().iterator(); it.hasNext(); ) {
long sessionId = it.next().sessionId;
if (existingSessions.contains(sessionId)) continue;
SessionStateWatcher watcher = sessionStateWatchers.remove(sessionId);
if (watcher != null) watcher.close();
it.remove();
metricUpdater.incRemovedSessions();
}
}
private void checkForAddedSessions(List<Long> sessions) {
for (Long sessionId : sessions)
if (remoteSessionCache.get(sessionId) == null)
sessionAdded(sessionId);
}
public Transaction createActivateTransaction(Session session) {
Transaction transaction = createSetStatusTransaction(session, Session.Status.ACTIVATE);
transaction.add(applicationRepo.createPutTransaction(session.getApplicationId(), session.getSessionId()).operations());
return transaction;
}
public Transaction createSetStatusTransaction(Session session, Session.Status status) {
return session.sessionZooKeeperClient.createWriteStatusTransaction(status);
}
void setPrepared(Session session) {
session.setStatus(Session.Status.PREPARE);
}
private static class FileTransaction extends AbstractTransaction {
public static FileTransaction from(FileOperation operation) {
FileTransaction transaction = new FileTransaction();
transaction.add(operation);
return transaction;
}
@Override
public void prepare() { }
@Override
public void commit() {
for (Operation operation : operations())
((FileOperation)operation).commit();
}
}
/** Factory for file operations */
private static class FileOperations {
/** Creates an operation which recursively deletes the given path */
public static DeleteOperation delete(String pathToDelete) {
return new DeleteOperation(pathToDelete);
}
}
private interface FileOperation extends Transaction.Operation {
void commit();
}
/**
* Recursively deletes this path and everything below.
* Succeeds with no action if the path does not exist.
*/
private static class DeleteOperation implements FileOperation {
private final String pathToDelete;
DeleteOperation(String pathToDelete) {
this.pathToDelete = pathToDelete;
}
@Override
public void commit() {
// TODO: Check delete access in prepare()
IOUtils.recursiveDeleteDir(new File(pathToDelete));
}
}
}
|
package com.yahoo.vespa.config.server.session;
import com.google.common.collect.HashMultiset;
import com.google.common.collect.Multiset;
import com.yahoo.cloud.config.ConfigserverConfig;
import com.yahoo.concurrent.DaemonThreadFactory;
import com.yahoo.concurrent.StripedExecutor;
import com.yahoo.config.FileReference;
import com.yahoo.config.application.api.ApplicationPackage;
import com.yahoo.config.application.api.DeployLogger;
import com.yahoo.config.model.api.ConfigDefinitionRepo;
import com.yahoo.config.model.application.provider.DeployData;
import com.yahoo.config.model.application.provider.FilesApplicationPackage;
import com.yahoo.config.provision.AllocatedHosts;
import com.yahoo.config.provision.ApplicationId;
import com.yahoo.config.provision.TenantName;
import com.yahoo.config.provision.Zone;
import com.yahoo.container.jdisc.secretstore.SecretStore;
import com.yahoo.io.IOUtils;
import com.yahoo.lang.SettableOptional;
import com.yahoo.path.Path;
import com.yahoo.transaction.AbstractTransaction;
import com.yahoo.transaction.NestedTransaction;
import com.yahoo.transaction.Transaction;
import com.yahoo.vespa.config.server.ConfigServerDB;
import com.yahoo.vespa.config.server.TimeoutBudget;
import com.yahoo.vespa.config.server.application.ApplicationSet;
import com.yahoo.vespa.config.server.application.PermanentApplicationPackage;
import com.yahoo.vespa.config.server.application.TenantApplications;
import com.yahoo.vespa.config.server.configchange.ConfigChangeActions;
import com.yahoo.vespa.config.server.deploy.TenantFileSystemDirs;
import com.yahoo.vespa.config.server.filedistribution.FileDirectory;
import com.yahoo.vespa.config.server.modelfactory.ActivatedModelsBuilder;
import com.yahoo.vespa.config.server.modelfactory.ModelFactoryRegistry;
import com.yahoo.vespa.config.server.monitoring.MetricUpdater;
import com.yahoo.vespa.config.server.monitoring.Metrics;
import com.yahoo.vespa.config.server.provision.HostProvisionerProvider;
import com.yahoo.vespa.config.server.tenant.TenantListener;
import com.yahoo.vespa.config.server.tenant.TenantRepository;
import com.yahoo.vespa.config.server.zookeeper.ConfigCurator;
import com.yahoo.vespa.config.server.zookeeper.SessionCounter;
import com.yahoo.vespa.curator.Curator;
import com.yahoo.vespa.defaults.Defaults;
import com.yahoo.vespa.flags.FlagSource;
import com.yahoo.yolean.Exceptions;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.ChildData;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
import org.apache.zookeeper.KeeperException;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
/**
*
* Session repository for a tenant. Stores session state in zookeeper and file system. There are two
* different session types (RemoteSession and LocalSession).
*
* @author Ulf Lilleengen
* @author hmusum
*
*/
public class SessionRepository {
private static final Logger log = Logger.getLogger(SessionRepository.class.getName());
private static final FilenameFilter sessionApplicationsFilter = (dir, name) -> name.matches("\\d+");
private static final long nonExistingActiveSessionId = 0;
private final Object monitor = new Object();
private final Map<Long, LocalSession> localSessionCache = Collections.synchronizedMap(new HashMap<>());
private final Map<Long, RemoteSession> remoteSessionCache = Collections.synchronizedMap(new HashMap<>());
private final Map<Long, SessionStateWatcher> sessionStateWatchers = Collections.synchronizedMap(new HashMap<>());
private final Duration sessionLifetime;
private final Clock clock;
private final Curator curator;
private final Executor zkWatcherExecutor;
private final PermanentApplicationPackage permanentApplicationPackage;
private final FlagSource flagSource;
private final TenantFileSystemDirs tenantFileSystemDirs;
private final Metrics metrics;
private final MetricUpdater metricUpdater;
private final Curator.DirectoryCache directoryCache;
private final TenantApplications applicationRepo;
private final SessionPreparer sessionPreparer;
private final Path sessionsPath;
private final TenantName tenantName;
private final ConfigCurator configCurator;
private final SessionCounter sessionCounter;
private final SecretStore secretStore;
private final HostProvisionerProvider hostProvisionerProvider;
private final ConfigserverConfig configserverConfig;
private final ConfigServerDB configServerDB;
private final Zone zone;
private final ModelFactoryRegistry modelFactoryRegistry;
private final ConfigDefinitionRepo configDefinitionRepo;
private final TenantListener tenantListener;
public SessionRepository(TenantName tenantName,
TenantApplications applicationRepo,
SessionPreparer sessionPreparer,
ConfigCurator configCurator,
Metrics metrics,
StripedExecutor<TenantName> zkWatcherExecutor,
PermanentApplicationPackage permanentApplicationPackage,
FlagSource flagSource,
ExecutorService zkCacheExecutor,
SecretStore secretStore,
HostProvisionerProvider hostProvisionerProvider,
ConfigserverConfig configserverConfig,
ConfigServerDB configServerDB,
Zone zone,
Clock clock,
ModelFactoryRegistry modelFactoryRegistry,
ConfigDefinitionRepo configDefinitionRepo,
TenantListener tenantListener) {
this.tenantName = tenantName;
this.configCurator = configCurator;
sessionCounter = new SessionCounter(configCurator, tenantName);
this.sessionsPath = TenantRepository.getSessionsPath(tenantName);
this.clock = clock;
this.curator = configCurator.curator();
this.sessionLifetime = Duration.ofSeconds(configserverConfig.sessionLifetime());
this.zkWatcherExecutor = command -> zkWatcherExecutor.execute(tenantName, command);
this.permanentApplicationPackage = permanentApplicationPackage;
this.flagSource = flagSource;
this.tenantFileSystemDirs = new TenantFileSystemDirs(configServerDB, tenantName);
this.applicationRepo = applicationRepo;
this.sessionPreparer = sessionPreparer;
this.metrics = metrics;
this.metricUpdater = metrics.getOrCreateMetricUpdater(Metrics.createDimensions(tenantName));
this.secretStore = secretStore;
this.hostProvisionerProvider = hostProvisionerProvider;
this.configserverConfig = configserverConfig;
this.configServerDB = configServerDB;
this.zone = zone;
this.modelFactoryRegistry = modelFactoryRegistry;
this.configDefinitionRepo = configDefinitionRepo;
this.tenantListener = tenantListener;
loadSessions(); // Needs to be done before creating cache below
this.directoryCache = curator.createDirectoryCache(sessionsPath.getAbsolute(), false, false, zkCacheExecutor);
this.directoryCache.addListener(this::childEvent);
this.directoryCache.start();
}
private void loadSessions() {
ExecutorService executor = Executors.newFixedThreadPool(Math.max(8, Runtime.getRuntime().availableProcessors()),
new DaemonThreadFactory("load-sessions-"));
loadLocalSessions(executor);
loadRemoteSessions(executor);
try {
executor.shutdown();
if ( ! executor.awaitTermination(1, TimeUnit.MINUTES))
log.log(Level.INFO, "Executor did not terminate");
} catch (InterruptedException e) {
log.log(Level.WARNING, "Shutdown of executor for loading sessions failed: " + Exceptions.toMessageString(e));
}
}
public void addLocalSession(LocalSession session) {
long sessionId = session.getSessionId();
localSessionCache.put(sessionId, session);
if (remoteSessionCache.get(sessionId) == null)
createRemoteSession(sessionId);
}
public LocalSession getLocalSession(long sessionId) {
return localSessionCache.get(sessionId);
}
/** Returns a copy of local sessions */
public Collection<LocalSession> getLocalSessions() {
return List.copyOf(localSessionCache.values());
}
private void loadLocalSessions(ExecutorService executor) {
File[] sessions = tenantFileSystemDirs.sessionsPath().listFiles(sessionApplicationsFilter);
if (sessions == null) return;
Map<Long, Future<?>> futures = new HashMap<>();
for (File session : sessions) {
long sessionId = Long.parseLong(session.getName());
futures.put(sessionId, executor.submit(() -> createSessionFromId(sessionId)));
}
futures.forEach((sessionId, future) -> {
try {
future.get();
log.log(Level.FINE, () -> "Local session " + sessionId + " loaded");
} catch (ExecutionException | InterruptedException e) {
log.log(Level.WARNING, "Could not load session " + sessionId, e);
}
});
}
public ConfigChangeActions prepareLocalSession(Session session, DeployLogger logger, PrepareParams params, Instant now) {
applicationRepo.createApplication(params.getApplicationId()); // TODO jvenstad: This is wrong, but it has to be done now, since preparation can change the application ID of a session :(
logger.log(Level.FINE, "Created application " + params.getApplicationId());
long sessionId = session.getSessionId();
SessionZooKeeperClient sessionZooKeeperClient = createSessionZooKeeperClient(sessionId);
Curator.CompletionWaiter waiter = sessionZooKeeperClient.createPrepareWaiter();
Optional<ApplicationSet> activeApplicationSet = getActiveApplicationSet(params.getApplicationId());
ConfigChangeActions actions = sessionPreparer.prepare(applicationRepo.getHostValidator(), logger, params,
activeApplicationSet, now, getSessionAppDir(sessionId),
session.getApplicationPackage(), sessionZooKeeperClient)
.getConfigChangeActions();
setPrepared(session);
waiter.awaitCompletion(params.getTimeoutBudget().timeLeft());
return actions;
}
public LocalSession createSessionFromExisting(Session existingSession,
boolean internalRedeploy,
TimeoutBudget timeoutBudget) {
ApplicationId existingApplicationId = existingSession.getApplicationId();
File existingApp = getSessionAppDir(existingSession.getSessionId());
LocalSession session = createSessionFromApplication(existingApp, existingApplicationId, internalRedeploy, timeoutBudget);
// Note: Setters below need to be kept in sync with calls in SessionPreparer.writeStateToZooKeeper()
session.setApplicationId(existingApplicationId);
session.setApplicationPackageReference(existingSession.getApplicationPackageReference());
session.setVespaVersion(existingSession.getVespaVersion());
session.setDockerImageRepository(existingSession.getDockerImageRepository());
session.setAthenzDomain(existingSession.getAthenzDomain());
session.setTenantSecretStores(existingSession.getTenantSecretStores());
if (existingSession.getDedicatedClusterControllerCluster())
session.setDedicatedClusterControllerCluster();
return session;
}
/**
* Creates a new deployment session from an application package.
*
* @param applicationDirectory a File pointing to an application.
* @param applicationId application id for this new session.
* @param timeoutBudget Timeout for creating session and waiting for other servers.
* @return a new session
*/
public LocalSession createSessionFromApplicationPackage(File applicationDirectory, ApplicationId applicationId, TimeoutBudget timeoutBudget) {
applicationRepo.createApplication(applicationId);
return createSessionFromApplication(applicationDirectory, applicationId, false, timeoutBudget);
}
private void createLocalSession(File applicationFile, ApplicationId applicationId, long sessionId) {
try {
ApplicationPackage applicationPackage = createApplicationPackage(applicationFile, applicationId, sessionId, false);
createLocalSession(sessionId, applicationPackage);
} catch (Exception e) {
throw new RuntimeException("Error creating session " + sessionId, e);
}
}
// Will delete session data in ZooKeeper and file system
public void deleteLocalSession(LocalSession session) {
long sessionId = session.getSessionId();
log.log(Level.FINE, () -> "Deleting local session " + sessionId);
SessionStateWatcher watcher = sessionStateWatchers.remove(sessionId);
if (watcher != null) watcher.close();
localSessionCache.remove(sessionId);
NestedTransaction transaction = new NestedTransaction();
transaction.add(FileTransaction.from(FileOperations.delete(getSessionAppDir(sessionId).getAbsolutePath())));
transaction.commit();
}
private void deleteAllSessions() {
for (LocalSession session : getLocalSessions()) {
deleteLocalSession(session);
}
}
public RemoteSession getRemoteSession(long sessionId) {
return remoteSessionCache.get(sessionId);
}
/** Returns a copy of remote sessions */
public Collection<RemoteSession> getRemoteSessions() {
return List.copyOf(remoteSessionCache.values());
}
public List<Long> getRemoteSessionsFromZooKeeper() {
return getSessionList(curator.getChildren(sessionsPath));
}
public RemoteSession createRemoteSession(long sessionId) {
SessionZooKeeperClient sessionZKClient = createSessionZooKeeperClient(sessionId);
RemoteSession session = new RemoteSession(tenantName, sessionId, sessionZKClient);
RemoteSession newSession = loadSessionIfActive(session).orElse(session);
remoteSessionCache.put(sessionId, newSession);
updateSessionStateWatcher(sessionId, newSession);
return newSession;
}
public int deleteExpiredRemoteSessions(Clock clock, Duration expiryTime) {
int deleted = 0;
for (long sessionId : getRemoteSessionsFromZooKeeper()) {
Session session = remoteSessionCache.get(sessionId);
if (session == null) continue; // Internal sessions not in sync with zk, continue
if (session.getStatus() == Session.Status.ACTIVATE) continue;
if (sessionHasExpired(session.getCreateTime(), expiryTime, clock)) {
log.log(Level.FINE, () -> "Remote session " + sessionId + " for " + tenantName + " has expired, deleting it");
deleteRemoteSessionFromZooKeeper(session);
deleted++;
}
}
return deleted;
}
public void deactivateAndUpdateCache(RemoteSession remoteSession) {
RemoteSession session = remoteSession.deactivated();
remoteSessionCache.put(session.getSessionId(), session);
}
public void deleteRemoteSessionFromZooKeeper(Session session) {
SessionZooKeeperClient sessionZooKeeperClient = createSessionZooKeeperClient(session.getSessionId());
Transaction transaction = sessionZooKeeperClient.deleteTransaction();
transaction.commit();
transaction.close();
}
private boolean sessionHasExpired(Instant created, Duration expiryTime, Clock clock) {
return (created.plus(expiryTime).isBefore(clock.instant()));
}
private List<Long> getSessionListFromDirectoryCache(List<ChildData> children) {
return getSessionList(children.stream()
.map(child -> Path.fromString(child.getPath()).getName())
.collect(Collectors.toList()));
}
private List<Long> getSessionList(List<String> children) {
return children.stream().map(Long::parseLong).collect(Collectors.toList());
}
private void loadRemoteSessions(ExecutorService executor) throws NumberFormatException {
Map<Long, Future<?>> futures = new HashMap<>();
for (long sessionId : getRemoteSessionsFromZooKeeper()) {
futures.put(sessionId, executor.submit(() -> sessionAdded(sessionId)));
}
futures.forEach((sessionId, future) -> {
try {
future.get();
log.log(Level.FINE, () -> "Remote session " + sessionId + " loaded");
} catch (ExecutionException | InterruptedException e) {
log.log(Level.WARNING, "Could not load session " + sessionId, e);
}
});
}
/**
* A session for which we don't have a watcher, i.e. hitherto unknown to us.
*
* @param sessionId session id for the new session
*/
public void sessionAdded(long sessionId) {
if (hasStatusDeleted(sessionId)) return;
log.log(Level.FINE, () -> "Adding remote session " + sessionId);
Session session = createRemoteSession(sessionId);
if (session.getStatus() == Session.Status.NEW) {
log.log(Level.FINE, () -> session.logPre() + "Confirming upload for session " + sessionId);
confirmUpload(session);
}
createLocalSessionFromDistributedApplicationPackage(sessionId);
}
private boolean hasStatusDeleted(long sessionId) {
SessionZooKeeperClient sessionZKClient = createSessionZooKeeperClient(sessionId);
RemoteSession session = new RemoteSession(tenantName, sessionId, sessionZKClient);
return session.getStatus() == Session.Status.DELETE;
}
void activate(RemoteSession session) {
long sessionId = session.getSessionId();
Curator.CompletionWaiter waiter = createSessionZooKeeperClient(sessionId).getActiveWaiter();
log.log(Level.FINE, () -> session.logPre() + "Activating " + sessionId);
applicationRepo.activateApplication(ensureApplicationLoaded(session), sessionId);
log.log(Level.FINE, () -> session.logPre() + "Notifying " + waiter);
notifyCompletion(waiter, session);
log.log(Level.INFO, session.logPre() + "Session activated: " + sessionId);
}
public void delete(Session remoteSession) {
long sessionId = remoteSession.getSessionId();
log.log(Level.FINE, () -> remoteSession.logPre() + "Deactivating and deleting remote session " + sessionId);
createSetStatusTransaction(remoteSession, Session.Status.DELETE).commit();
deleteRemoteSessionFromZooKeeper(remoteSession);
remoteSessionCache.remove(sessionId);
LocalSession localSession = getLocalSession(sessionId);
if (localSession != null) {
log.log(Level.FINE, () -> localSession.logPre() + "Deleting local session " + sessionId);
deleteLocalSession(localSession);
}
}
private Optional<RemoteSession> loadSessionIfActive(RemoteSession session) {
for (ApplicationId applicationId : applicationRepo.activeApplications()) {
if (applicationRepo.requireActiveSessionOf(applicationId) == session.getSessionId()) {
log.log(Level.FINE, () -> "Found active application for session " + session.getSessionId() + " , loading it");
applicationRepo.activateApplication(ensureApplicationLoaded(session), session.getSessionId());
log.log(Level.INFO, session.logPre() + "Application activated successfully: " + applicationId + " (generation " + session.getSessionId() + ")");
return Optional.ofNullable(remoteSessionCache.get(session.getSessionId()));
}
}
return Optional.empty();
}
void prepareRemoteSession(RemoteSession session) {
SessionZooKeeperClient sessionZooKeeperClient = createSessionZooKeeperClient(session.getSessionId());
Curator.CompletionWaiter waiter = sessionZooKeeperClient.getPrepareWaiter();
ensureApplicationLoaded(session);
notifyCompletion(waiter, session);
}
public ApplicationSet ensureApplicationLoaded(RemoteSession session) {
if (session.applicationSet().isPresent()) {
return session.applicationSet().get();
}
Optional<Long> activeSessionId = getActiveSessionId(session.getApplicationId());
Optional<ApplicationSet> previousApplicationSet = activeSessionId.filter(session::isNewerThan)
.flatMap(this::getApplicationSet);
ApplicationSet applicationSet = loadApplication(session, previousApplicationSet);
RemoteSession activated = session.activated(applicationSet);
long sessionId = activated.getSessionId();
remoteSessionCache.put(sessionId, activated);
updateSessionStateWatcher(sessionId, activated);
return applicationSet;
}
void confirmUpload(Session session) {
Curator.CompletionWaiter waiter = session.getSessionZooKeeperClient().getUploadWaiter();
long sessionId = session.getSessionId();
log.log(Level.FINE, "Notifying upload waiter for session " + sessionId);
notifyCompletion(waiter, session);
log.log(Level.FINE, "Done notifying upload for session " + sessionId);
}
void notifyCompletion(Curator.CompletionWaiter completionWaiter, Session session) {
try {
completionWaiter.notifyCompletion();
} catch (RuntimeException e) {
// Throw only if we get something else than NoNodeException or NodeExistsException.
// NoNodeException might happen when the session is no longer in use (e.g. the app using this session
// has been deleted) and this method has not been called yet for the previous session operation on a
// minority of the config servers.
// NodeExistsException might happen if an event for this node is delivered more than once, in that case
// this is a no-op
Set<Class<? extends KeeperException>> acceptedExceptions = Set.of(KeeperException.NoNodeException.class,
KeeperException.NodeExistsException.class);
Class<? extends Throwable> exceptionClass = e.getCause().getClass();
if (acceptedExceptions.contains(exceptionClass))
log.log(Level.FINE, "Not able to notify completion for session " + session.getSessionId() +
" (" + completionWaiter + ")," +
" node " + (exceptionClass.equals(KeeperException.NoNodeException.class)
? "has been deleted"
: "already exists"));
else
throw e;
}
}
private ApplicationSet loadApplication(Session session, Optional<ApplicationSet> previousApplicationSet) {
log.log(Level.FINE, () -> "Loading application for " + session);
SessionZooKeeperClient sessionZooKeeperClient = createSessionZooKeeperClient(session.getSessionId());
ApplicationPackage applicationPackage = sessionZooKeeperClient.loadApplicationPackage();
ActivatedModelsBuilder builder = new ActivatedModelsBuilder(session.getTenantName(),
session.getSessionId(),
sessionZooKeeperClient,
previousApplicationSet,
curator,
metrics,
permanentApplicationPackage,
flagSource,
secretStore,
hostProvisionerProvider,
configserverConfig,
zone,
modelFactoryRegistry,
configDefinitionRepo,
tenantListener);
// Read hosts allocated on the config server instance which created this
SettableOptional<AllocatedHosts> allocatedHosts = new SettableOptional<>(applicationPackage.getAllocatedHosts());
return ApplicationSet.fromList(builder.buildModels(session.getApplicationId(),
sessionZooKeeperClient.readDockerImageRepository(),
sessionZooKeeperClient.readVespaVersion(),
applicationPackage,
allocatedHosts,
clock.instant()));
}
private void nodeChanged() {
zkWatcherExecutor.execute(() -> {
Multiset<Session.Status> sessionMetrics = HashMultiset.create();
getRemoteSessions().forEach(session -> sessionMetrics.add(session.getStatus()));
metricUpdater.setNewSessions(sessionMetrics.count(Session.Status.NEW));
metricUpdater.setPreparedSessions(sessionMetrics.count(Session.Status.PREPARE));
metricUpdater.setActivatedSessions(sessionMetrics.count(Session.Status.ACTIVATE));
metricUpdater.setDeactivatedSessions(sessionMetrics.count(Session.Status.DEACTIVATE));
});
}
@SuppressWarnings("unused")
private void childEvent(CuratorFramework ignored, PathChildrenCacheEvent event) {
zkWatcherExecutor.execute(() -> {
log.log(Level.FINE, () -> "Got child event: " + event);
switch (event.getType()) {
case CHILD_ADDED:
case CHILD_REMOVED:
case CONNECTION_RECONNECTED:
sessionsChanged();
break;
default:
break;
}
});
}
public void deleteExpiredSessions(Map<ApplicationId, Long> activeSessions) {
log.log(Level.FINE, () -> "Purging old sessions for tenant '" + tenantName + "'");
Set<LocalSession> toDelete = new HashSet<>();
try {
for (LocalSession candidate : getLocalSessions()) {
Instant createTime = candidate.getCreateTime();
log.log(Level.FINE, () -> "Candidate session for deletion: " + candidate.getSessionId() + ", created: " + createTime);
// Sessions with state other than ACTIVATE
if (hasExpired(candidate) && !isActiveSession(candidate)) {
toDelete.add(candidate);
} else if (createTime.plus(Duration.ofDays(1)).isBefore(clock.instant())) {
// Sessions with state ACTIVATE, but which are not actually active
Optional<ApplicationId> applicationId = candidate.getOptionalApplicationId();
if (applicationId.isEmpty()) continue;
Long activeSession = activeSessions.get(applicationId.get());
if (activeSession == null || activeSession != candidate.getSessionId()) {
toDelete.add(candidate);
log.log(Level.INFO, "Deleted inactive session " + candidate.getSessionId() + " created " +
createTime + " for '" + applicationId + "'");
}
}
}
toDelete.forEach(this::deleteLocalSession);
// Make sure to catch here, to avoid executor just dying in case of issues ...
} catch (Throwable e) {
log.log(Level.WARNING, "Error when purging old sessions ", e);
}
log.log(Level.FINE, () -> "Done purging old sessions");
}
private boolean hasExpired(LocalSession candidate) {
return candidate.getCreateTime().plus(sessionLifetime).isBefore(clock.instant());
}
private boolean isActiveSession(LocalSession candidate) {
return candidate.getStatus() == Session.Status.ACTIVATE;
}
private void ensureSessionPathDoesNotExist(long sessionId) {
Path sessionPath = getSessionPath(sessionId);
if (configCurator.exists(sessionPath.getAbsolute())) {
throw new IllegalArgumentException("Path " + sessionPath.getAbsolute() + " already exists in ZooKeeper");
}
}
private ApplicationPackage createApplication(File userDir,
File configApplicationDir,
ApplicationId applicationId,
long sessionId,
Optional<Long> currentlyActiveSessionId,
boolean internalRedeploy) {
long deployTimestamp = System.currentTimeMillis();
String user = System.getenv("USER");
if (user == null) {
user = "unknown";
}
DeployData deployData = new DeployData(user, userDir.getAbsolutePath(), applicationId, deployTimestamp,
internalRedeploy, sessionId, currentlyActiveSessionId.orElse(nonExistingActiveSessionId));
return FilesApplicationPackage.fromFileWithDeployData(configApplicationDir, deployData);
}
private LocalSession createSessionFromApplication(File applicationFile,
ApplicationId applicationId,
boolean internalRedeploy,
TimeoutBudget timeoutBudget) {
long sessionId = getNextSessionId();
try {
ensureSessionPathDoesNotExist(sessionId);
ApplicationPackage app = createApplicationPackage(applicationFile, applicationId, sessionId, internalRedeploy);
log.log(Level.FINE, () -> TenantRepository.logPre(tenantName) + "Creating session " + sessionId + " in ZooKeeper");
SessionZooKeeperClient sessionZKClient = createSessionZooKeeperClient(sessionId);
sessionZKClient.createNewSession(clock.instant());
Curator.CompletionWaiter waiter = sessionZKClient.getUploadWaiter();
LocalSession session = new LocalSession(tenantName, sessionId, app, sessionZKClient);
waiter.awaitCompletion(Duration.ofSeconds(Math.min(60, timeoutBudget.timeLeft().getSeconds())));
addLocalSession(session);
return session;
} catch (Exception e) {
throw new RuntimeException("Error creating session " + sessionId, e);
}
}
private ApplicationPackage createApplicationPackage(File applicationFile,
ApplicationId applicationId,
long sessionId,
boolean internalRedeploy) throws IOException {
// Synchronize to avoid threads trying to create an application package concurrently
// (e.g. a maintainer and an external deployment)
synchronized (monitor) {
Optional<Long> activeSessionId = getActiveSessionId(applicationId);
File userApplicationDir = getSessionAppDir(sessionId);
copyApp(applicationFile, userApplicationDir);
ApplicationPackage applicationPackage = createApplication(applicationFile,
userApplicationDir,
applicationId,
sessionId,
activeSessionId,
internalRedeploy);
applicationPackage.writeMetaData();
return applicationPackage;
}
}
public Optional<ApplicationSet> getActiveApplicationSet(ApplicationId appId) {
return applicationRepo.activeSessionOf(appId).flatMap(this::getApplicationSet);
}
private Optional<ApplicationSet> getApplicationSet(long sessionId) {
Optional<ApplicationSet> applicationSet = Optional.empty();
try {
RemoteSession session = getRemoteSession(sessionId);
applicationSet = Optional.ofNullable(ensureApplicationLoaded(session));
} catch (IllegalArgumentException e) {
// Do nothing if we have no currently active session
}
return applicationSet;
}
private void copyApp(File sourceDir, File destinationDir) throws IOException {
if (destinationDir.exists()) {
log.log(Level.INFO, "Destination dir " + destinationDir + " already exists, app has already been copied");
return;
}
if (! sourceDir.isDirectory())
throw new IllegalArgumentException(sourceDir.getAbsolutePath() + " is not a directory");
// Copy app atomically: Copy to a temp dir and move to destination
java.nio.file.Path tempDestinationDir = null;
try {
tempDestinationDir = Files.createTempDirectory(destinationDir.getParentFile().toPath(), "app-package");
log.log(Level.FINE, "Copying dir " + sourceDir.getAbsolutePath() + " to " + tempDestinationDir.toFile().getAbsolutePath());
IOUtils.copyDirectory(sourceDir, tempDestinationDir.toFile());
log.log(Level.FINE, "Moving " + tempDestinationDir + " to " + destinationDir.getAbsolutePath());
Files.move(tempDestinationDir, destinationDir.toPath(), StandardCopyOption.ATOMIC_MOVE);
} finally {
// In case some of the operations above fail
if (tempDestinationDir != null)
IOUtils.recursiveDeleteDir(tempDestinationDir.toFile());
}
}
/**
* Returns a new session instance for the given session id.
*/
void createSessionFromId(long sessionId) {
File sessionDir = getAndValidateExistingSessionAppDir(sessionId);
ApplicationPackage applicationPackage = FilesApplicationPackage.fromFile(sessionDir);
createLocalSession(sessionId, applicationPackage);
}
void createLocalSession(long sessionId, ApplicationPackage applicationPackage) {
SessionZooKeeperClient sessionZKClient = createSessionZooKeeperClient(sessionId);
LocalSession session = new LocalSession(tenantName, sessionId, applicationPackage, sessionZKClient);
addLocalSession(session);
}
/**
* Returns a new local session for the given session id if it does not already exist.
* Will also add the session to the local session cache if necessary
*/
public void createLocalSessionFromDistributedApplicationPackage(long sessionId) {
if (applicationRepo.sessionExistsInFileSystem(sessionId)) {
log.log(Level.FINE, () -> "Local session for session id " + sessionId + " already exists");
createSessionFromId(sessionId);
return;
}
SessionZooKeeperClient sessionZKClient = createSessionZooKeeperClient(sessionId);
FileReference fileReference = sessionZKClient.readApplicationPackageReference();
log.log(Level.FINE, () -> "File reference for session id " + sessionId + ": " + fileReference);
if (fileReference != null) {
File rootDir = new File(Defaults.getDefaults().underVespaHome(configserverConfig.fileReferencesDir()));
File sessionDir;
FileDirectory fileDirectory = new FileDirectory(rootDir);
try {
sessionDir = fileDirectory.getFile(fileReference);
} catch (IllegalArgumentException e) {
// We cannot be guaranteed that the file reference exists (it could be that it has not
// been downloaded yet), and e.g when bootstrapping we cannot throw an exception in that case
log.log(Level.FINE, "File reference for session id " + sessionId + ": " + fileReference + " not found in " + fileDirectory);
return;
}
ApplicationId applicationId = sessionZKClient.readApplicationId()
.orElseThrow(() -> new RuntimeException("Could not find application id for session " + sessionId));
log.log(Level.FINE, () -> "Creating local session for tenant '" + tenantName + "' with session id " + sessionId);
createLocalSession(sessionDir, applicationId, sessionId);
}
}
private Optional<Long> getActiveSessionId(ApplicationId applicationId) {
List<ApplicationId> applicationIds = applicationRepo.activeApplications();
return applicationIds.contains(applicationId)
? Optional.of(applicationRepo.requireActiveSessionOf(applicationId))
: Optional.empty();
}
private long getNextSessionId() {
return sessionCounter.nextSessionId();
}
public Path getSessionPath(long sessionId) {
return sessionsPath.append(String.valueOf(sessionId));
}
Path getSessionStatePath(long sessionId) {
return getSessionPath(sessionId).append(ConfigCurator.SESSIONSTATE_ZK_SUBPATH);
}
private SessionZooKeeperClient createSessionZooKeeperClient(long sessionId) {
String serverId = configserverConfig.serverId();
return new SessionZooKeeperClient(curator, configCurator, tenantName, sessionId, serverId);
}
private File getAndValidateExistingSessionAppDir(long sessionId) {
File appDir = getSessionAppDir(sessionId);
if (!appDir.exists() || !appDir.isDirectory()) {
throw new IllegalArgumentException("Unable to find correct application directory for session " + sessionId);
}
return appDir;
}
private File getSessionAppDir(long sessionId) {
return new TenantFileSystemDirs(configServerDB, tenantName).getUserApplicationDir(sessionId);
}
private void updateSessionStateWatcher(long sessionId, RemoteSession remoteSession) {
SessionStateWatcher sessionStateWatcher = sessionStateWatchers.get(sessionId);
if (sessionStateWatcher == null) {
Curator.FileCache fileCache = curator.createFileCache(getSessionStatePath(sessionId).getAbsolute(), false);
fileCache.addListener(this::nodeChanged);
sessionStateWatchers.put(sessionId, new SessionStateWatcher(fileCache, remoteSession, metricUpdater, zkWatcherExecutor, this));
} else {
sessionStateWatcher.updateRemoteSession(remoteSession);
}
}
@Override
public String toString() {
return getLocalSessions().toString();
}
public Clock clock() { return clock; }
public void close() {
deleteAllSessions();
tenantFileSystemDirs.delete();
try {
if (directoryCache != null) {
directoryCache.close();
}
} catch (Exception e) {
log.log(Level.WARNING, "Exception when closing path cache", e);
} finally {
checkForRemovedSessions(new ArrayList<>());
}
}
private void sessionsChanged() throws NumberFormatException {
List<Long> sessions = getSessionListFromDirectoryCache(directoryCache.getCurrentData());
checkForRemovedSessions(sessions);
checkForAddedSessions(sessions);
}
private void checkForRemovedSessions(List<Long> existingSessions) {
for (Iterator<RemoteSession> it = remoteSessionCache.values().iterator(); it.hasNext(); ) {
long sessionId = it.next().sessionId;
if (existingSessions.contains(sessionId)) continue;
SessionStateWatcher watcher = sessionStateWatchers.remove(sessionId);
if (watcher != null) watcher.close();
it.remove();
metricUpdater.incRemovedSessions();
}
}
private void checkForAddedSessions(List<Long> sessions) {
for (Long sessionId : sessions)
if (remoteSessionCache.get(sessionId) == null)
sessionAdded(sessionId);
}
public Transaction createActivateTransaction(Session session) {
Transaction transaction = createSetStatusTransaction(session, Session.Status.ACTIVATE);
transaction.add(applicationRepo.createPutTransaction(session.getApplicationId(), session.getSessionId()).operations());
return transaction;
}
public Transaction createSetStatusTransaction(Session session, Session.Status status) {
return session.sessionZooKeeperClient.createWriteStatusTransaction(status);
}
void setPrepared(Session session) {
session.setStatus(Session.Status.PREPARE);
}
private static class FileTransaction extends AbstractTransaction {
public static FileTransaction from(FileOperation operation) {
FileTransaction transaction = new FileTransaction();
transaction.add(operation);
return transaction;
}
@Override
public void prepare() { }
@Override
public void commit() {
for (Operation operation : operations())
((FileOperation)operation).commit();
}
}
/** Factory for file operations */
private static class FileOperations {
/** Creates an operation which recursively deletes the given path */
public static DeleteOperation delete(String pathToDelete) {
return new DeleteOperation(pathToDelete);
}
}
private interface FileOperation extends Transaction.Operation {
void commit();
}
/**
* Recursively deletes this path and everything below.
* Succeeds with no action if the path does not exist.
*/
private static class DeleteOperation implements FileOperation {
private final String pathToDelete;
DeleteOperation(String pathToDelete) {
this.pathToDelete = pathToDelete;
}
@Override
public void commit() {
// TODO: Check delete access in prepare()
IOUtils.recursiveDeleteDir(new File(pathToDelete));
}
}
}
|
package io.quarkus.deployment.pkg.steps;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.jboss.logging.Logger;
import io.quarkus.bootstrap.util.IoUtils;
import io.quarkus.deployment.annotations.BuildStep;
import io.quarkus.deployment.builditem.nativeimage.NativeImageSystemPropertyBuildItem;
import io.quarkus.deployment.pkg.NativeConfig;
import io.quarkus.deployment.pkg.PackageConfig;
import io.quarkus.deployment.pkg.builditem.ArtifactResultBuildItem;
import io.quarkus.deployment.pkg.builditem.NativeImageBuildItem;
import io.quarkus.deployment.pkg.builditem.NativeImageSourceJarBuildItem;
import io.quarkus.deployment.pkg.builditem.OutputTargetBuildItem;
import io.quarkus.deployment.util.FileUtil;
public class NativeImageBuildStep {
private static final Logger log = Logger.getLogger(NativeImageBuildStep.class);
private static final String DEBUG_BUILD_PROCESS_PORT = "5005";
private static final String GRAALVM_HOME = "GRAALVM_HOME";
/**
* Name of the <em>system</em> property to retrieve JAVA_HOME
*/
private static final String JAVA_HOME_SYS = "java.home";
/**
* Name of the <em>environment</em> variable to retrieve JAVA_HOME
*/
private static final String JAVA_HOME_ENV = "JAVA_HOME";
private static final boolean IS_LINUX = System.getProperty("os.name").toLowerCase(Locale.ROOT).contains("linux");
private static final boolean IS_WINDOWS = System.getProperty("os.name").toLowerCase(Locale.ROOT).contains("windows");
/**
* The name of the environment variable containing the system path.
*/
private static final String PATH = "PATH";
@BuildStep(onlyIf = NativeBuild.class)
ArtifactResultBuildItem result(NativeImageBuildItem image) {
return new ArtifactResultBuildItem(image.getPath(), PackageConfig.NATIVE, Collections.emptyMap());
}
@BuildStep
public NativeImageBuildItem build(NativeConfig nativeConfig, NativeImageSourceJarBuildItem nativeImageSourceJarBuildItem,
OutputTargetBuildItem outputTargetBuildItem,
PackageConfig packageConfig,
List<NativeImageSystemPropertyBuildItem> nativeImageProperties) {
Path runnerJar = nativeImageSourceJarBuildItem.getPath();
log.info("Building native image from " + runnerJar);
Path outputDir = nativeImageSourceJarBuildItem.getPath().getParent();
final String runnerJarName = runnerJar.getFileName().toString();
HashMap<String, String> env = new HashMap<>(System.getenv());
List<String> nativeImage;
String noPIE = "";
if (nativeConfig.containerRuntime.isPresent() || nativeConfig.containerBuild) {
String containerRuntime = nativeConfig.containerRuntime.orElse("docker");
// E.g. "/usr/bin/docker run -v {{PROJECT_DIR}}:/project --rm quarkus/graalvm-native-image"
nativeImage = new ArrayList<>();
String outputPath = outputDir.toAbsolutePath().toString();
if (IS_WINDOWS) {
outputPath = FileUtil.translateToVolumePath(outputPath);
}
Collections.addAll(nativeImage, containerRuntime, "run", "-v", outputPath + ":/project:z");
if (IS_LINUX) {
if ("docker".equals(containerRuntime)) {
String uid = getLinuxID("-ur");
String gid = getLinuxID("-gr");
if (uid != null && gid != null && !"".equals(uid) && !"".equals(gid)) {
Collections.addAll(nativeImage, "--user", uid + ":" + gid);
}
} else if ("podman".equals(containerRuntime)) {
// Needed to avoid AccessDeniedExceptions
nativeImage.add("--userns=keep-id");
}
}
nativeConfig.containerRuntimeOptions.ifPresent(nativeImage::addAll);
if (nativeConfig.debugBuildProcess && nativeConfig.publishDebugBuildProcessPort) {
// publish the debug port onto the host if asked for
nativeImage.add("--publish=" + DEBUG_BUILD_PROCESS_PORT + ":" + DEBUG_BUILD_PROCESS_PORT);
}
Collections.addAll(nativeImage, "--rm", nativeConfig.builderImage);
} else {
if (IS_LINUX) {
noPIE = detectNoPIE();
}
Optional<String> graal = nativeConfig.graalvmHome;
File java = nativeConfig.javaHome;
if (graal.isPresent()) {
env.put(GRAALVM_HOME, graal.get());
}
if (java == null) {
// try system property first - it will be the JAVA_HOME used by the current JVM
String home = System.getProperty(JAVA_HOME_SYS);
if (home == null) {
// No luck, somewhat a odd JVM not enforcing this property
// try with the JAVA_HOME environment variable
home = env.get(JAVA_HOME_ENV);
}
if (home != null) {
java = new File(home);
}
}
nativeImage = Collections.singletonList(getNativeImageExecutable(graal, java, env).getAbsolutePath());
}
final Optional<String> graalVMVersion;
try {
List<String> versionCommand = new ArrayList<>(nativeImage);
versionCommand.add("--version");
Process versionProcess = new ProcessBuilder(versionCommand.toArray(new String[0]))
.redirectErrorStream(true)
.start();
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(versionProcess.getInputStream(), StandardCharsets.UTF_8))) {
graalVMVersion = reader.lines().filter((l) -> l.startsWith("GraalVM Version")).findFirst();
}
} catch (Exception e) {
throw new RuntimeException("Failed to get GraalVM version", e);
}
if (graalVMVersion.isPresent()) {
checkGraalVMVersion(graalVMVersion.get());
} else {
log.error("Unable to get GraalVM version from the native-image binary.");
}
try {
List<String> command = new ArrayList<>(nativeImage);
if (nativeConfig.cleanupServer) {
List<String> cleanup = new ArrayList<>(nativeImage);
cleanup.add("--server-shutdown");
ProcessBuilder pb = new ProcessBuilder(cleanup.toArray(new String[0]));
pb.directory(outputDir.toFile());
pb.redirectInput(ProcessBuilder.Redirect.INHERIT);
pb.redirectOutput(ProcessBuilder.Redirect.INHERIT);
pb.redirectError(ProcessBuilder.Redirect.INHERIT);
Process process = pb.start();
process.waitFor();
}
Boolean enableSslNative = false;
boolean enableAllTimeZones = false;
for (NativeImageSystemPropertyBuildItem prop : nativeImageProperties) {
//todo: this should be specific build items
if (prop.getKey().equals("quarkus.ssl.native") && prop.getValue() != null) {
enableSslNative = Boolean.parseBoolean(prop.getValue());
} else if (prop.getKey().equals("quarkus.jni.enable") && prop.getValue() != null) {
nativeConfig.enableJni |= Boolean.parseBoolean(prop.getValue());
} else if (prop.getKey().equals("quarkus.native.enable-all-security-services") && prop.getValue() != null) {
nativeConfig.enableAllSecurityServices |= Boolean.parseBoolean(prop.getValue());
} else if (prop.getKey().equals("quarkus.native.enable-all-charsets") && prop.getValue() != null) {
nativeConfig.addAllCharsets |= Boolean.parseBoolean(prop.getValue());
} else if (prop.getKey().equals("quarkus.native.enable-all-timezones") && prop.getValue() != null) {
enableAllTimeZones = Boolean.parseBoolean(prop.getValue());
} else {
// todo maybe just -D is better than -J-D in this case
if (prop.getValue() == null) {
command.add("-J-D" + prop.getKey());
} else {
command.add("-J-D" + prop.getKey() + "=" + prop.getValue());
}
}
}
if (enableSslNative) {
nativeConfig.enableHttpsUrlHandler = true;
nativeConfig.enableJni = true;
nativeConfig.enableAllSecurityServices = true;
}
nativeConfig.additionalBuildArgs.ifPresent(l -> l.stream().map(String::trim).forEach(command::add));
command.add("--initialize-at-build-time=");
command.add("-H:InitialCollectionPolicy=com.oracle.svm.core.genscavenge.CollectionPolicy$BySpaceAndTime"); //the default collection policy results in full GC's 50% of the time
command.add("-jar");
command.add(runnerJarName);
if (nativeConfig.enableFallbackImages) {
command.add("-H:FallbackThreshold=5");
} else {
//Default: be strict as those fallback images aren't very useful
//and tend to cover up real problems.
command.add("-H:FallbackThreshold=0");
}
if (nativeConfig.reportErrorsAtRuntime) {
command.add("-H:+ReportUnsupportedElementsAtRuntime");
}
if (nativeConfig.reportExceptionStackTraces) {
command.add("-H:+ReportExceptionStackTraces");
}
if (nativeConfig.debugSymbols) {
command.add("-g");
}
if (nativeConfig.debugBuildProcess) {
command.add("-J-Xrunjdwp:transport=dt_socket,address=" + DEBUG_BUILD_PROCESS_PORT + ",server=y,suspend=y");
}
if (nativeConfig.enableReports) {
command.add("-H:+PrintAnalysisCallTree");
}
if (nativeConfig.dumpProxies) {
command.add("-Dsun.misc.ProxyGenerator.saveGeneratedFiles=true");
if (nativeConfig.enableServer) {
log.warn(
"Options dumpProxies and enableServer are both enabled: this will get the proxies dumped in an unknown external working directory");
}
}
if (nativeConfig.nativeImageXmx.isPresent()) {
command.add("-J-Xmx" + nativeConfig.nativeImageXmx.get());
}
List<String> protocols = new ArrayList<>(2);
if (nativeConfig.enableHttpUrlHandler) {
protocols.add("http");
}
if (nativeConfig.enableHttpsUrlHandler) {
protocols.add("https");
}
if (nativeConfig.addAllCharsets) {
command.add("-H:+AddAllCharsets");
} else {
command.add("-H:-AddAllCharsets");
}
if (enableAllTimeZones) {
command.add("-H:+IncludeAllTimeZones");
}
if (!protocols.isEmpty()) {
command.add("-H:EnableURLProtocols=" + String.join(",", protocols));
}
if (nativeConfig.enableAllSecurityServices) {
command.add("--enable-all-security-services");
}
if (!noPIE.isEmpty()) {
command.add("-H:NativeLinkerOption=" + noPIE);
}
if (!nativeConfig.enableIsolates) {
command.add("-H:-SpawnIsolates");
}
if (nativeConfig.enableJni || (graalVMVersion.isPresent() && !graalVMVersion.get().contains(" 19.2."))) {
command.add("-H:+JNI");
} else {
command.add("-H:-JNI");
}
if (!nativeConfig.enableServer && !IS_WINDOWS) {
command.add("--no-server");
}
if (nativeConfig.enableVmInspection) {
command.add("-H:+AllowVMInspection");
}
if (nativeConfig.autoServiceLoaderRegistration) {
command.add("-H:+UseServiceLoaderFeature");
//When enabling, at least print what exactly is being added:
command.add("-H:+TraceServiceLoaderFeature");
} else {
command.add("-H:-UseServiceLoaderFeature");
}
if (nativeConfig.fullStackTraces) {
command.add("-H:+StackTrace");
} else {
command.add("-H:-StackTrace");
}
String executableName = outputTargetBuildItem.getBaseName() + packageConfig.runnerSuffix;
command.add(executableName);
log.info(String.join(" ", command));
CountDownLatch errorReportLatch = new CountDownLatch(1);
Process process = new ProcessBuilder(command)
.directory(outputDir.toFile())
.inheritIO()
.start();
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.submit(new ErrorReplacingProcessReader(process.getErrorStream(), outputDir.resolve("reports").toFile(),
errorReportLatch));
executor.shutdown();
errorReportLatch.await();
if (process.waitFor() != 0) {
throw new RuntimeException("Image generation failed. Exit code: " + process.exitValue());
}
Path generatedImage = outputDir.resolve(executableName);
IoUtils.copy(generatedImage,
outputTargetBuildItem.getOutputDirectory().resolve(executableName));
Files.delete(generatedImage);
String finalPath = outputTargetBuildItem.getBaseName();
System.setProperty("native.image.path", finalPath);
return new NativeImageBuildItem(Paths.get(finalPath));
} catch (Exception e) {
throw new RuntimeException("Failed to build native image", e);
}
}
private void checkGraalVMVersion(String version) {
log.info("Running Quarkus native-image plugin on " + version);
final List<String> obsoleteGraalVmVersions = Arrays.asList("1.0.0", "19.0.", "19.1.", "19.2.0");
final boolean vmVersionIsObsolete = version.contains(" 19.3.0 ")
|| obsoleteGraalVmVersions.stream().anyMatch(v -> version.contains(" " + v));
if (vmVersionIsObsolete) {
throw new IllegalStateException("Unsupported version of GraalVM detected: " + version + "."
+ " Quarkus currently offers a stable support of GraalVM 19.2.1 and a preview support of GraalVM 19.3.1."
+ " Please upgrade GraalVM to one of these versions.");
}
}
private static File getNativeImageExecutable(Optional<String> graalVmHome, File javaHome, Map<String, String> env) {
String imageName = IS_WINDOWS ? "native-image.cmd" : "native-image";
if (graalVmHome.isPresent()) {
File file = Paths.get(graalVmHome.get(), "bin", imageName).toFile();
if (file.exists()) {
return file;
}
}
if (javaHome != null) {
File file = new File(javaHome, "bin/" + imageName);
if (file.exists()) {
return file;
}
}
// System path
String systemPath = env.get(PATH);
if (systemPath != null) {
String[] pathDirs = systemPath.split(File.pathSeparator);
for (String pathDir : pathDirs) {
File dir = new File(pathDir);
if (dir.isDirectory()) {
File file = new File(dir, imageName);
if (file.exists()) {
return file;
}
}
}
}
throw new RuntimeException("Cannot find the `" + imageName + "` in the GRAALVM_HOME, JAVA_HOME and System " +
"PATH. Install it using `gu install native-image`");
}
private static String getLinuxID(String option) {
Process process;
try {
StringBuilder responseBuilder = new StringBuilder();
String line;
ProcessBuilder idPB = new ProcessBuilder().command("id", option);
idPB.redirectError(new File("/dev/null"));
idPB.redirectInput(new File("/dev/null"));
process = idPB.start();
try (InputStream inputStream = process.getInputStream()) {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {
while ((line = reader.readLine()) != null) {
responseBuilder.append(line);
}
safeWaitFor(process);
return responseBuilder.toString();
}
} catch (Throwable t) {
safeWaitFor(process);
throw t;
}
} catch (IOException e) { //from process.start()
//swallow and return null id
return null;
}
}
static void safeWaitFor(Process process) {
boolean intr = false;
try {
for (;;)
try {
process.waitFor();
return;
} catch (InterruptedException ex) {
intr = true;
}
} finally {
if (intr)
Thread.currentThread().interrupt();
}
}
private static String detectNoPIE() {
String argument = testGCCArgument("-no-pie");
return argument.length() == 0 ? testGCCArgument("-nopie") : argument;
}
private static String testGCCArgument(String argument) {
try {
Process gcc = new ProcessBuilder("cc", "-v", "-E", argument, "-").start();
gcc.getOutputStream().close();
if (gcc.waitFor() == 0) {
return argument;
}
} catch (IOException | InterruptedException e) {
// eat
}
return "";
}
}
|
package io.cloudslang.content.maps.services;
import io.cloudslang.content.maps.entities.ModifyMapElementsInput;
import io.cloudslang.content.maps.exceptions.ValidationException;
import io.cloudslang.content.maps.utils.MapSerializer;
import io.cloudslang.content.maps.utils.StringMethods;
import io.cloudslang.content.maps.validators.ModifyMapElementsInputValidator;
import io.cloudslang.content.utils.OutputUtilities;
import org.jetbrains.annotations.NotNull;
import java.util.Map;
import java.util.stream.Collectors;
public class ModifyMapElementsService {
private final ModifyMapElementsInputValidator validator = new ModifyMapElementsInputValidator();
public @NotNull Map<String, String> execute(@NotNull ModifyMapElementsInput input) throws Exception {
ValidationException validationEx = validator.validate(input);
if (validationEx != null) {
throw validationEx;
}
MapSerializer serializer = new MapSerializer(
input.getPairDelimiter(), input.getEntryDelimiter(),
input.getMapStart(), input.getMapEnd(),
input.getElementWrapper(), input.isStripWhitespaces(), false);
Map<String, String> map = serializer.deserialize(input.getMap());
Map<String, String> newMap;
switch (input.getElements().toLowerCase()) {
case "keys":
newMap = map.keySet().parallelStream()
.collect(Collectors.toMap(key -> StringMethods.execute(key, input.getMethod(), input.getValue()), map::get));
break;
case "values":
newMap = map.keySet().parallelStream()
.collect(Collectors.toMap(key -> key, key -> StringMethods.execute(map.get(key), input.getMethod(), input.getValue())));
break;
default:
newMap = map.keySet().parallelStream()
.collect(Collectors.toMap(key -> StringMethods.execute(key, input.getMethod(), input.getValue()),
key -> StringMethods.execute(map.get(key), input.getMethod(), input.getValue())));
break;
}
String returnResult = serializer.serialize(newMap);
return OutputUtilities.getSuccessResultsMap(returnResult);
}
}
|
//$Header: /deegreerepository/deegree/src/org/deegree/io/datastore/Datastore.java,v 1.28 2007/01/16 13:58:34 mschneider Exp $
package org.deegree.metadata.persistence;
/**
* Indicates an exception that occured in the metadata persistence layer.
*
* @author <a href="mailto:thomas@lat-lon.de">Steffen Thomas</a>
* @author <a href="mailto:schneider@lat-lon.de">Markus Schneider</a>
* @author last edited by: $Author$
*
* @version $Revision$, $Date$
*/
public class MetadataStoreException extends Exception {
private static final long serialVersionUID = -8171919093492328054L;
/**
* Creates a new {@link MetadataStoreException} without detail message.
*/
public MetadataStoreException() {
super();
}
/**
* Creates a new {@link MetadataStoreException} with detail message.
*
* @param message
* detail message
*/
public MetadataStoreException( String message ) {
super( message );
}
/**
* Creates a new {@link MetadataStoreException} which wraps the causing exception.
*
* @param cause
*/
public MetadataStoreException( Throwable cause ) {
super( cause );
}
/**
* Creates a new {@link MetadataStoreException} which wraps the causing exception and provides a detail message.
*
* @param message
* @param cause
*/
public MetadataStoreException( String message, Throwable cause ) {
super( message, cause );
}
}
|
//$HeadURL: svn+ssh://developername@svn.wald.intevation.org/deegree/base/trunk/resources/eclipse/files_template.xml $
package org.deegree.tools.jdbc;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.util.Date;
import java.util.Locale;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamReader;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.deegree.commons.utils.time.DateUtils;
import org.deegree.geometry.Envelope;
import org.deegree.geometry.GeometryException;
import org.deegree.gml.GMLInputFactory;
import org.deegree.gml.GMLStreamReader;
import org.deegree.gml.GMLVersion;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import com.vividsolutions.jts.io.ParseException;
public class MappingUtils {
private static final DecimalFormatSymbols dfs = new DecimalFormatSymbols( Locale.ENGLISH );
private static final NumberFormat nf = new DecimalFormat( "
/**
*
* @param node
* @return maximum x coordinate
* @throws ParseException
* @throws GeometryException
*/
public static String getXMax( Node node ) {
if ( node == null ) {
return "";
}
return nf.format( getAsEnvelope( node ).getMax().get0() );
}
/**
*
* @param node
* @return minimum x coordinate
* @throws ParseException
* @throws GeometryException
*/
public static String getXMin( Node node ) {
if ( node == null ) {
return "";
}
return nf.format( getAsEnvelope( node ).getMin().get0() );
}
/**
*
* @param node
* @return maximum y coordinate
* @throws ParseException
* @throws GeometryException
*/
public static String getYMax( Node node )
throws ParseException {
if ( node == null ) {
return "";
}
return nf.format( getAsEnvelope( node ).getMax().get1() );
}
/**
*
* @param node
* @return minimum y coordinate
* @throws GeometryException
*/
public static String getYMin( Node node )
throws ParseException {
if ( node == null ) {
return "";
}
return nf.format( getAsEnvelope( node ).getMin().get1() );
}
private static Envelope getAsEnvelope( Node node ) {
try {
// TODO: this is a really dirty hack!!!!
Transformer t = TransformerFactory.newInstance().newTransformer();
t.setOutputProperty( OutputKeys.OMIT_XML_DECLARATION, "yes" );
StringWriter sw = new StringWriter();
t.transform( new DOMSource( node ), new StreamResult( sw ) );
String nodeAsString = sw.toString();
// where is the namespace binding???
nodeAsString = nodeAsString.replaceFirst( " ", " xmlns:gml=\"http:
InputStream in = new ByteArrayInputStream( nodeAsString.getBytes() );
XMLStreamReader stream = XMLInputFactory.newInstance().createXMLStreamReader( in );
GMLStreamReader gmlReader = GMLInputFactory.createGMLStreamReader( GMLVersion.GML_32, stream );
org.deegree.geometry.Geometry geometry = gmlReader.readGeometry();
return geometry.getEnvelope();
// Source source = new DOMSource( node );
// XMLStreamReader stream = XMLInputFactory.newInstance().createXMLStreamReader( source );
// System.out.println(StAXParsingHelper.getEventTypeString( stream.getEventType() ));
// if(stream.getEventType() == XMLStreamConstants.START_DOCUMENT)
// stream.nextTag();
// System.out.println(StAXParsingHelper.getEventTypeString( stream.getEventType() ));
// GMLStreamReader gmlReader = GMLInputFactory.createGMLStreamReader( GMLVersion.GML_32, stream );
// org.deegree.geometry.Geometry geometry = gmlReader.readGeometry();
// return geometry.getEnvelope();
} catch ( Exception e ) {
throw new IllegalArgumentException( "could not read as GMLGeometry: " + node.getNodeName(), e );
}
}
/**
*
* @param date
* ISO 8601 formated date
* @param offset
* days; could be a positive or a negative value
* @return date plus/minus offset
* @throws java.text.ParseException
*/
public static String addDateOffeset( Node date, int offset )
throws java.text.ParseException {
long off = ( (long) offset ) * 24 * 60 * 60 * 1000;
long t = createDate( getStringValue( date ) ).getTime();
return DateUtils.formatISO8601DateWOMS( new Date( t + off ) );
}
/**
* Returns the text contained in the specified element.
*
* @param node
* current element
* @return the textual contents of the element
*/
private static String getStringValue( Node node ) {
NodeList children = node.getChildNodes();
if ( children != null ) {
StringBuffer sb = new StringBuffer( children.getLength() * 500 );
if ( node.getNodeValue() != null ) {
sb.append( node.getNodeValue().trim() );
}
if ( node.getNodeType() != Node.ATTRIBUTE_NODE ) {
for ( int i = 0; i < children.getLength(); i++ ) {
if ( children.item( i ).getNodeType() == Node.TEXT_NODE
|| children.item( i ).getNodeType() == Node.CDATA_SECTION_NODE ) {
sb.append( children.item( i ).getNodeValue() );
}
}
}
return sb.toString();
} else {
return "";
}
}
public static Date createDate( String isoDate )
throws java.text.ParseException {
return DateUtils.parseISO8601Date( isoDate );
}
}
|
package org.psem2m.composer.demo.impl;
import java.util.HashMap;
import java.util.Map;
import org.apache.felix.ipojo.annotations.Component;
import org.apache.felix.ipojo.annotations.Property;
import org.apache.felix.ipojo.annotations.Provides;
import org.apache.felix.ipojo.annotations.Requires;
import org.osgi.framework.BundleException;
import org.psem2m.composer.demo.DemoComponentsConstants;
import org.psem2m.composer.demo.IErpData;
import org.psem2m.composer.test.api.IComponent;
import org.psem2m.isolates.base.IIsolateLoggerSvc;
import org.psem2m.isolates.base.activators.CPojoBase;
/**
* Exported data server service
*
* @author Thomas Calmant
*/
@Component(name = DemoComponentsConstants.COMPONENT_SERVER_EXPORTED)
@Provides(specifications = IErpData.class)
public class ServerExported extends CPojoBase implements IErpData {
/** applyCart treatment chain */
@Requires(id = "applyCart")
private IComponent pChainApplyCart;
/** getItem treatment chain */
@Requires(id = "getItem")
private IComponent pChainGetItem;
/** getItems treatment chain */
@Requires(id = "getItems")
private IComponent pChainGetItems;
/** getItemsStock treatment chain */
@Requires(id = "getItemsStock")
private IComponent pChainGetItemsStock;
/** The instance name */
@Property(name = DemoComponentsConstants.PROPERTY_INSTANCE_NAME)
private String pInstanceName;
/** The logger */
@Requires
private IIsolateLoggerSvc pLogger;
/*
* (non-Javadoc)
*
* @see org.psem2m.composer.demo.IErpData#applyCart(java.util.Map)
*/
@Override
public Map<String, Object> applyCart(final Map<String, Object> aCart) {
try {
// Prepare the treatment map
final Map<String, Object> treatmentMap = new HashMap<String, Object>();
treatmentMap.put(IComponent.KEY_REQUEST, aCart);
return pChainApplyCart.computeResult(treatmentMap);
} catch (final Exception ex) {
// Log the error
pLogger.logSevere(this, "applyCart",
"Error treating an applyCart request.", ex);
// Return an error map
return makeErrorMap(ex);
}
}
/*
* (non-Javadoc)
*
* @see org.psem2m.composer.demo.IErpData#getItem(java.lang.String)
*/
@Override
public Map<String, Object> getItem(final String aItemId) {
try {
// Prepare the treatment map
final Map<String, Object> treatmentMap = new HashMap<String, Object>();
final Map<String, Object> requestMap = new HashMap<String, Object>();
requestMap.put("itemId", aItemId);
treatmentMap.put(IComponent.KEY_REQUEST, requestMap);
return pChainGetItem.computeResult(treatmentMap);
} catch (final Exception ex) {
// Log the error
pLogger.logSevere(this, "getItem",
"Error treating an getItem request.", ex);
// Return an error map
return makeErrorMap(ex);
}
}
/*
* (non-Javadoc)
*
* @see org.psem2m.composer.demo.IErpData#getItems(java.lang.String, int,
* boolean, java.lang.String)
*/
@Override
public Map<String, Object> getItems(final String aCategory,
final int aItemsCount, final boolean aRandomize,
final String aBaseId) {
try {
// Prepare the treatment map
final Map<String, Object> treatmentMap = new HashMap<String, Object>();
final Map<String, Object> requestMap = new HashMap<String, Object>();
requestMap.put("category", aCategory);
requestMap.put("itemsCount", aItemsCount);
requestMap.put("randomize", aRandomize);
requestMap.put("baseId", aBaseId);
treatmentMap.put(IComponent.KEY_REQUEST, requestMap);
return pChainGetItems.computeResult(treatmentMap);
} catch (final Exception ex) {
// Log the error
pLogger.logSevere(this, "getItems",
"Error treating an getItems request.", ex);
// Return an error map
return makeErrorMap(ex);
}
}
/*
* (non-Javadoc)
*
* @see org.psem2m.composer.demo.IErpData#getItemsStock(java.lang.String[])
*/
@Override
public Map<String, Object> getItemsStock(final String[] aItemIds) {
try {
// Prepare the treatment map
final Map<String, Object> treatmentMap = new HashMap<String, Object>();
final Map<String, Object> requestMap = new HashMap<String, Object>();
requestMap.put("itemIds", aItemIds);
treatmentMap.put(IComponent.KEY_REQUEST, requestMap);
return pChainGetItemsStock.computeResult(treatmentMap);
} catch (final Exception ex) {
// Log the error
pLogger.logSevere(this, "getItemsStock",
"Error treating an getItemsStock request.", ex);
// Return an error map
return makeErrorMap(ex);
}
}
/*
* (non-Javadoc)
*
* @see org.psem2m.isolates.base.activators.CPojoBase#invalidatePojo()
*/
@Override
public void invalidatePojo() throws BundleException {
pLogger.logInfo(this, "invalidatePojo", "Component", pInstanceName,
"Gone");
}
/**
* Creates a map containing the given throwable
*
* @param aThrowable
* A throwable
* @return A map containing the given throwable
*/
protected Map<String, Object> makeErrorMap(final Throwable aThrowable) {
final Map<String, Object> resultMap = new HashMap<String, Object>();
if (aThrowable != null) {
resultMap.put(IComponent.KEY_ERROR, aThrowable);
} else {
resultMap.put(IComponent.KEY_ERROR, "No error given.");
}
return resultMap;
}
/*
* (non-Javadoc)
*
* @see org.psem2m.isolates.base.activators.CPojoBase#validatePojo()
*/
@Override
public void validatePojo() throws BundleException {
pLogger.logInfo(this, "validatePojo", "Component", pInstanceName,
"Ready");
}
}
|
package org.hisp.dhis.metadataimport;
import com.google.gson.JsonObject;
import org.apache.commons.lang3.RandomStringUtils;
import org.hamcrest.Matchers;
import org.hisp.dhis.ApiTest;
import org.hisp.dhis.actions.LoginActions;
import org.hisp.dhis.actions.RestApiActions;
import org.hisp.dhis.actions.SchemasActions;
import org.hisp.dhis.actions.system.SystemActions;
import org.hisp.dhis.dto.ApiResponse;
import org.hisp.dhis.dto.ObjectReport;
import org.hisp.dhis.dto.TypeReport;
import org.hisp.dhis.helpers.file.FileReaderUtils;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.junit.jupiter.api.Assertions.*;
/**
* @author Gintare Vilkelyte <vilkelyte.gintare@gmail.com>
*/
public class MetadataImportTest
extends ApiTest
{
private RestApiActions metadataActions;
private SchemasActions schemasActions;
private SystemActions systemActions;
@BeforeEach
public void before()
{
schemasActions = new SchemasActions();
metadataActions = new RestApiActions( "/metadata" );
systemActions = new SystemActions();
new LoginActions().loginAsSuperUser();
}
@ParameterizedTest( name = "withImportStrategy[{0}]" )
@CsvSource( { "CREATE, ignored", "CREATE_AND_UPDATE, updated" } )
public void shouldUpdateExistingMetadata( String importStrategy, String expected )
{
// arrange
JsonObject exported = metadataActions.get().getBody();
String params = "?async=false" +
"&importReportMode=FULL" +
"&importStrategy=" + importStrategy;
// act
ApiResponse response = metadataActions.post( params, exported );
// assert
response.validate()
.statusCode( 200 )
.body( "stats.total", greaterThan( 0 ) )
.body( "stats.created", Matchers.equalTo( 0 ) )
.body( "stats.deleted", Matchers.equalTo( 0 ) )
.body( "stats.total", equalTo( response.extract( "stats." + expected ) ) );
List<HashMap> typeReports = response.extractList( "typeReports.stats" );
typeReports.forEach( x -> {
assertEquals( x.get( expected ), x.get( "total" ) );
} );
}
@Test
public void shouldImportUniqueMetadataAndReturnObjectReports()
throws Exception
{
// arrange
String params = "?async=false" +
"&importReportMode=DEBUG" +
"&importStrategy=CREATE";
JsonObject object = new FileReaderUtils()
.readJsonAndGenerateData( new File( "src/test/resources/metadata/uniqueMetadata.json" ) );
// act
ApiResponse response = metadataActions.post( params, object );
// assert
response.validate()
.statusCode( 200 )
.body( "stats.total", greaterThan( 0 ) )
.body( "typeReports", Matchers.notNullValue() )
.body( "typeReports.stats", Matchers.notNullValue() )
.body( "typeReports.objectReports", Matchers.notNullValue() );
List<HashMap> stats = response.extractList( "typeReports.stats" );
stats.forEach( x -> {
assertEquals( x.get( "total" ), x.get( "created" ) );
} );
List<ObjectReport> objectReports = getObjectReports( response.getTypeReports() );
assertNotNull( objectReports );
validateCreatedEntities( objectReports );
}
@Test
public void shouldReturnObjectReportsWhenSomeMetadataWasIgnoredAndAtomicModeFalse()
throws Exception
{
// arrange
String params = "?async=false" +
"&importReportMode=DEBUG" +
"&importStrategy=CREATE" +
"&atomicMode=NONE";
JsonObject object = new FileReaderUtils()
.readJsonAndGenerateData( new File( "src/test/resources/metadata/uniqueMetadata.json" ) );
// act
ApiResponse response = metadataActions.post( params, object );
response.validate().statusCode( 200 );
JsonObject newObj = new FileReaderUtils()
.readJsonAndGenerateData( new File( "src/test/resources/metadata/uniqueMetadata.json" ) );
// add one of the orgunits from already imported metadata to get it ignored
newObj.get( "organisationUnits" )
.getAsJsonArray()
.add( object.get( "organisationUnits" ).getAsJsonArray().get( 0 ) );
response = metadataActions.post( params, newObj );
// assert
response.validate()
.statusCode( 200 )
.body( "stats.total", greaterThan( 1 ) )
.body( "stats.ignored", equalTo( 1 ) );
assertEquals( response.extract( "stats.created" ), (Integer) response.extract( "stats.total" ) - 1 );
int total = (int) response.extract( "stats.total" );
List<ObjectReport> objectReports = getObjectReports( response.getTypeReports() );
assertNotNull( objectReports );
validateCreatedEntities( objectReports );
assertThat( objectReports, Matchers.hasItems( hasProperty( "errorReports", notNullValue() ) ) );
assertEquals( total, objectReports.size(), "Not all imported entities had object reports" );
}
@Test
public void shouldReturnImportSummariesWhenImportingInvalidMetadataAsync()
throws Exception
{
// arrange
String params = "?async=true" +
"&importReportMode=DEBUG" +
"&importStrategy=CREATE_AND_UPDATE" +
"&atomicMode=NONE";
JsonObject metadata = new FileReaderUtils()
.readJsonAndGenerateData( new File( "src/test/resources/metadata/uniqueMetadata.json" ) );
metadata.getAsJsonArray( "organisationUnits" ).get( 0 ).getAsJsonObject()
.addProperty( "shortName", RandomStringUtils.random( 51 ) );
// act
ApiResponse response = metadataActions.post( params, metadata );
response.validate()
.statusCode( 200 )
.body( not( equalTo( "null" ) ) )
.body( "response.name", equalTo( "metadataImport" ) )
.body( "response.jobType", equalTo( "METADATA_IMPORT" ) );
String taskId = response.extractString( "response.id" );
// Validate that job was successful
response = systemActions.waitUntilTaskCompleted( "METADATA_IMPORT", taskId );
assertThat( response.extractList( "message" ), hasItem( containsString( "Import:Start" ) ) );
assertThat( response.extractList( "message" ), hasItem( containsString( "Import:Done" ) ) );
// validate task summaries were created
response = systemActions.getTaskSummariesResponse( "METADATA_IMPORT", taskId );
response.validate().statusCode( 200 )
.body( not( equalTo( "null" ) ) )
.body( "status", equalTo( "WARNING" ) )
.body( "typeReports", notNullValue() )
.rootPath( "typeReports" )
.body( "stats.total", everyItem( greaterThan( 0 ) ) )
.body( "stats.ignored", hasSize( greaterThanOrEqualTo( 1 ) ) )
.body( "objectReports", notNullValue() )
.body( "objectReports", hasSize( greaterThanOrEqualTo( 1 ) ) )
.body( "objectReports.errorReports", notNullValue() );
}
@Test
public void shouldImportMetadataAsync()
throws Exception
{
JsonObject object = new FileReaderUtils()
.readJsonAndGenerateData( new File( "src/test/resources/metadata/uniqueMetadata.json" ) );
// arrange
String params = "?async=false" +
"&importReportMode=DEBUG" +
"&importStrategy=CREATE_AND_UPDATE" +
"&atomicMode=NONE";
// import metadata so that we have references and can clean up
ApiResponse response = metadataActions.post( params, object );
params = params.replace( "async=false", "async=true" );
// act
response = metadataActions.post( params, object );
response.validate()
.statusCode( 200 )
.body( not( equalTo( "null" ) ) )
.body( "response.name", equalTo( "metadataImport" ) )
.body( "response.jobType", equalTo( "METADATA_IMPORT" ) );
String taskId = response.extractString( "response.id" );
// Validate that job was successful
response = systemActions.waitUntilTaskCompleted( "METADATA_IMPORT", taskId );
assertThat( response.extractList( "message" ), hasItem( containsString( "Import:Start" ) ) );
assertThat( response.extractList( "message" ), hasItem( containsString( "Import:Done" ) ) );
// validate task summaries were created
response = systemActions.getTaskSummariesResponse( "METADATA_IMPORT", taskId );
response.validate().statusCode( 200 )
.body( not( equalTo( "null" ) ) )
.body( "status", equalTo( "OK" ) )
.body( "typeReports", notNullValue() )
.body( "typeReports.stats.total", everyItem( greaterThan( 0 ) ) )
.body( "typeReports.objectReports", hasSize( greaterThan( 0 ) ) );
}
private List<ObjectReport> getObjectReports( List<TypeReport> typeReports )
{
List<ObjectReport> objectReports = new ArrayList<>();
typeReports.stream().forEach( typeReport -> {
objectReports.addAll( typeReport.getObjectReports() );
} );
return objectReports;
}
private void validateCreatedEntities( List<ObjectReport> objectReports )
{
objectReports.forEach(
report -> {
assertNotEquals( "", report.getUid() );
assertNotEquals( "", report.getKlass() );
assertNotEquals( "", report.getIndex() );
assertNotEquals( "", report.getDisplayName() );
}
);
}
}
|
package com.orientechnologies.orient.core.db;
import static com.orientechnologies.orient.core.config.OGlobalConfiguration.FILE_DELETE_DELAY;
import static com.orientechnologies.orient.core.config.OGlobalConfiguration.FILE_DELETE_RETRY;
import com.orientechnologies.common.concur.OOfflineNodeException;
import com.orientechnologies.common.concur.lock.OModificationOperationProhibitedException;
import com.orientechnologies.common.exception.OException;
import com.orientechnologies.common.log.OLogManager;
import com.orientechnologies.orient.core.Orient;
import com.orientechnologies.orient.core.config.OContextConfiguration;
import com.orientechnologies.orient.core.db.document.ODatabaseDocumentEmbedded;
import com.orientechnologies.orient.core.exception.ODatabaseException;
import com.orientechnologies.orient.core.storage.OStorage;
import com.orientechnologies.orient.core.storage.disk.OLocalPaginatedStorage;
import com.orientechnologies.orient.core.storage.impl.local.OAbstractPaginatedStorage;
import com.orientechnologies.orient.enterprise.channel.binary.OChannelBinary;
import com.orientechnologies.orient.server.OClientConnection;
import com.orientechnologies.orient.server.OServer;
import com.orientechnologies.orient.server.OServerAware;
import com.orientechnologies.orient.server.distributed.ODistributedServerManager;
import com.orientechnologies.orient.server.distributed.impl.ODatabaseDocumentDistributed;
import com.orientechnologies.orient.server.distributed.impl.ODatabaseDocumentDistributedPooled;
import com.orientechnologies.orient.server.distributed.impl.ODistributedDatabaseImpl;
import com.orientechnologies.orient.server.distributed.impl.ODistributedPlugin;
import com.orientechnologies.orient.server.distributed.impl.metadata.OSharedContextDistributed;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
public class OrientDBDistributed extends OrientDBEmbedded implements OServerAware {
private volatile OServer server;
private volatile ODistributedPlugin plugin;
public OrientDBDistributed(String directoryPath, OrientDBConfig config, Orient instance) {
super(directoryPath, config, instance);
// This now si simple but should be replaced by a factory depending to the protocol version
}
@Override
public void init(OServer server) {
// Cannot get the plugin from here, is too early, doing it lazy
this.server = server;
}
public synchronized ODistributedPlugin getPlugin() {
if (plugin == null) {
if (server != null && server.isActive()) plugin = server.getPlugin("cluster");
}
return plugin;
}
protected OSharedContext createSharedContext(OAbstractPaginatedStorage storage) {
if (OSystemDatabase.SYSTEM_DB_NAME.equals(storage.getName())
|| plugin == null
|| !plugin.isEnabled()) {
return new OSharedContextEmbedded(storage, this);
}
return new OSharedContextDistributed(storage, this);
}
protected ODatabaseDocumentEmbedded newSessionInstance(OAbstractPaginatedStorage storage) {
if (OSystemDatabase.SYSTEM_DB_NAME.equals(storage.getName())
|| plugin == null
|| !plugin.isEnabled()) {
return new ODatabaseDocumentEmbedded(storage);
}
plugin.registerNewDatabaseIfNeeded(storage.getName());
return new ODatabaseDocumentDistributed(storage, plugin);
}
protected ODatabaseDocumentEmbedded newPooledSessionInstance(
ODatabasePoolInternal pool, OAbstractPaginatedStorage storage) {
if (OSystemDatabase.SYSTEM_DB_NAME.equals(storage.getName())
|| plugin == null
|| !plugin.isEnabled()) {
return new ODatabaseDocumentEmbeddedPooled(pool, storage);
}
plugin.registerNewDatabaseIfNeeded(storage.getName());
return new ODatabaseDocumentDistributedPooled(pool, storage, plugin);
}
public void setPlugin(ODistributedPlugin plugin) {
this.plugin = plugin;
}
public OStorage fullSync(String dbName, InputStream backupStream, OrientDBConfig config) {
OAbstractPaginatedStorage storage = null;
ODatabaseDocumentEmbedded embedded;
synchronized (this) {
try {
storage = storages.get(dbName);
if (storage != null) {
// The underlying storage instance will be closed so no need to closed it
ODatabaseDocumentEmbedded deleteInstance = newSessionInstance(storage);
deleteInstance.init(config, getOrCreateSharedContext(storage));
dropStorageFiles((OLocalPaginatedStorage) storage);
OSharedContext context = sharedContexts.remove(dbName);
context.close();
storage.delete();
storages.remove(dbName);
ODatabaseRecordThreadLocal.instance().remove();
}
storage =
(OAbstractPaginatedStorage)
disk.createStorage(
buildName(dbName),
new HashMap<>(),
maxWALSegmentSize,
doubleWriteLogMaxSegSize,
generateStorageId());
embedded = internalCreate(config, storage);
storages.put(dbName, storage);
} catch (OModificationOperationProhibitedException e) {
throw e;
} catch (Exception e) {
if (storage != null) {
storage.delete();
}
throw OException.wrapException(
new ODatabaseException("Cannot restore database '" + dbName + "'"), e);
}
}
try {
storage.restoreFullIncrementalBackup(backupStream);
} catch (RuntimeException e) {
try {
if (storage != null) {
storage.delete();
}
} catch (Exception e1) {
OLogManager.instance()
.warn(this, "Error doing cleanups, should be safe do progress anyway", e1);
}
synchronized (this) {
sharedContexts.remove(dbName);
storages.remove(dbName);
}
OContextConfiguration configs = getConfigurations().getConfigurations();
OLocalPaginatedStorage.deleteFilesFromDisc(
dbName,
configs.getValueAsInteger(FILE_DELETE_RETRY),
configs.getValueAsInteger(FILE_DELETE_DELAY),
buildName(dbName));
throw e;
}
embedded.getSharedContext().reInit(storage, embedded);
ODatabaseRecordThreadLocal.instance().remove();
return storage;
}
@Override
public ODatabaseDocumentInternal poolOpen(
String name, String user, String password, ODatabasePoolInternal pool) {
ODatabaseDocumentInternal session = super.poolOpen(name, user, password, pool);
return session;
}
@Override
public void internalDrop(String name) {
synchronized (this) {
checkOpen();
// This is a temporary fix for distributed drop that avoid scheduled view update to re-open
// the distributed database while is dropped
OSharedContext sharedContext = sharedContexts.get(name);
if (sharedContext != null) {
sharedContext.getViewManager().close();
}
}
ODatabaseDocumentInternal current = ODatabaseRecordThreadLocal.instance().getIfDefined();
try {
ODatabaseDocumentInternal db = openNoAuthenticate(name, null);
for (Iterator<ODatabaseLifecycleListener> it = orient.getDbLifecycleListeners();
it.hasNext(); ) {
it.next().onDrop(db);
}
db.close();
} finally {
ODatabaseRecordThreadLocal.instance().set(current);
}
synchronized (this) {
if (exists(name, null, null)) {
OAbstractPaginatedStorage storage = getOrInitStorage(name);
OSharedContext sharedContext = sharedContexts.get(name);
if (sharedContext != null) {
sharedContext.close();
}
if (storage instanceof OLocalPaginatedStorage) {
dropStorageFiles((OLocalPaginatedStorage) storage);
}
storage.delete();
storages.remove(name);
sharedContexts.remove(name);
}
}
}
@Override
public void drop(String name, String user, String password) {
if (getPlugin() != null && getPlugin().isEnabled()) {
plugin.executeInDistributedDatabaseLock(
name,
20000,
null,
(cfg) -> {
plugin.dropOnAllServers(name);
return null;
});
plugin.dropConfig(name);
} else {
super.drop(name, user, password);
}
}
private boolean checkDbAvailable(String name) {
if (getPlugin() == null || !getPlugin().isEnabled()) {
return true;
}
if (OSystemDatabase.SYSTEM_DB_NAME.equals(name)) return true;
ODistributedServerManager.DB_STATUS dbStatus =
plugin.getDatabaseStatus(plugin.getLocalNodeName(), name);
return dbStatus == ODistributedServerManager.DB_STATUS.ONLINE
|| dbStatus == ODistributedServerManager.DB_STATUS.BACKUP;
}
@Override
public ODatabaseDocumentInternal open(String name, String user, String password) {
if (checkDbAvailable(name)) {
return super.open(name, user, password);
} else {
if (exists(name, user, password)) {
super.open(name, user, password);
}
throw new OOfflineNodeException(
"database " + name + " not online on " + plugin.getLocalNodeName());
}
}
@Override
public ODatabaseDocumentInternal open(
String name, String user, String password, OrientDBConfig config) {
if (checkDbAvailable(name)) {
return super.open(name, user, password, config);
} else {
if (exists(name, user, password)) {
super.open(name, user, password, config);
}
throw new OOfflineNodeException(
"database " + name + " not online on " + plugin.getLocalNodeName());
}
}
@Override
public void coordinatedRequest(
OClientConnection connection, int requestType, int clientTxId, OChannelBinary channel)
throws IOException {
throw new UnsupportedOperationException("old implementation do not support new flow");
}
public static void dropStorageFiles(OLocalPaginatedStorage storage) {
// REMOVE distributed-config.json and distributed-sync.json files to allow removal of directory
final File dCfg =
new File(
storage.getStoragePath() + "/" + ODistributedServerManager.FILE_DISTRIBUTED_DB_CONFIG);
try {
if (dCfg.exists()) {
for (int i = 0; i < 10; ++i) {
if (dCfg.delete()) break;
Thread.sleep(100);
}
}
final File dCfg2 =
new File(
storage.getStoragePath()
+ "/"
+ ODistributedDatabaseImpl.DISTRIBUTED_SYNC_JSON_FILENAME);
if (dCfg2.exists()) {
for (int i = 0; i < 10; ++i) {
if (dCfg2.delete()) break;
Thread.sleep(100);
}
}
} catch (InterruptedException e) {
// IGNORE IT
}
}
@Override
public ODistributedServerManager getDistributedManager() {
return this.plugin;
}
}
|
package org.k3.language.ui.wizards;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspaceRunnable;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.INewWizard;
import org.eclipse.ui.IWorkbench;
import org.k3.language.ui.Activator;
import org.k3.language.ui.tools.Context;
import org.k3.language.ui.tools.FileUtils;
import org.k3.language.ui.tools.GenerateGenModelCode;
import org.k3.language.ui.tools.ProjectDescriptor;
import org.k3.language.ui.tools.classpath.ManageClasspath;
import org.k3.language.ui.tools.classpath.ManageClasspathMaven;
import org.k3.language.ui.tools.classpath.ManageClasspathPlugin;
import org.k3.language.ui.tools.classpath.ManageClasspathStandAlone;
import org.k3.language.ui.wizards.pages.WizardPageCustomNewProjectK3Plugin;
import org.k3.language.ui.wizards.pages.WizardPageNewProjectK3Plugin;
public class WizardNewProjectK3Plugin extends Wizard implements INewWizard {
protected Context context = new Context();
WizardPageNewProjectK3Plugin projectPage = new WizardPageNewProjectK3Plugin(this.context);
WizardPageCustomNewProjectK3Plugin projectPageCustom = new WizardPageCustomNewProjectK3Plugin(this.context);
public WizardNewProjectK3Plugin() {
}
@Override
public void addPages() {
addPage(projectPage);
addPage(projectPageCustom);
}
@Override
public void init(IWorkbench workbench, IStructuredSelection selection) {
// TODO Auto-generated method stub
}
@Override
public boolean performFinish() {
try {
final IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(this.context.nameProject);
IWorkspaceRunnable operation = new IWorkspaceRunnable() {
public void run(IProgressMonitor monitor) throws CoreException {
project.create(monitor);
project.open(monitor);
addKermetaNatureToProject(project);
IFile ecoreFile = context.ecoreIFile;
if(ecoreFile != null){
createProjectWithEcore(monitor);
} else {
createFolder("src/" + getContextNamePackage(), project, monitor);
createDefaultKmt(project, monitor);
}
FileUtils.unZip(project, new ProjectDescriptor("fr.inria.diverse.k3.eclipse.language.ui","zips/resources.zip"));
configureProject(project, monitor);
//setClassPath(project, monitor);
project.refreshLocal(IResource.DEPTH_INFINITE, monitor);
}
};
ResourcesPlugin.getWorkspace().run(operation, null);
} catch (Exception exception) {
Activator.logErrorMessage(exception.getMessage(), exception);
return false;
}
return true;
}
@Override
public boolean isHelpAvailable() {
return true;
}
public void addKermetaNatureToProject(IProject project) {
IProjectDescription description;
try {
description = project.getDescription();
if (!description.hasNature("org.eclipse.jdt.core.javanature")){
addNature(description, "org.eclipse.jdt.core.javanature");
}
if(!description.hasNature("org.eclipse.xtext.ui.shared.xtextNature")){
addNature(description, "org.eclipse.xtext.ui.shared.xtextNature");
}
if((this.context.kindsOfProject == Context.KindsOfProject.PLUGIN) && (!description.hasNature("org.eclipse.pde.PluginNature"))){
addNature(description, "org.eclipse.pde.PluginNature");
}
if((this.context.kindsOfProject == Context.KindsOfProject.MAVEN) && (!description.hasNature("org.eclipse.m2e.core.maven2Nature"))){
addNature(description, "org.eclipse.m2e.core.maven2Nature");
}
project.setDescription(description, null);
} catch (CoreException e) {
Activator.logErrorMessage(e.getMessage(), e);
}
}
public void configureProject(IProject project, IProgressMonitor monitor) {
try {
ManageClasspath classpath;
IProjectDescription description;
description = project.getDescription();
addNature(description, "org.eclipse.jdt.core.javanature");
addNature(description, "org.eclipse.xtext.ui.shared.xtextNature");
switch (this.context.kindsOfProject)
{
case STANDALONE :
classpath = new ManageClasspathStandAlone();
classpath.setClasspath(project, monitor);
break;
case PLUGIN :
classpath = new ManageClasspathPlugin();
addNature(description, "org.eclipse.pde.PluginNature");
configurePlugIn(project, monitor);
classpath.setClasspath(project, monitor);
break;
case MAVEN :
classpath = new ManageClasspathMaven();
addNature(description, "org.eclipse.m2e.core.maven2Nature");
createMavenFile(project, monitor, false);
classpath.setClasspath(project, monitor);
break;
}
project.setDescription(description, monitor);
} catch (Exception e) {
Activator.logErrorMessage(e.getMessage(), e);
}
}
private void configurePlugIn (IProject project, IProgressMonitor monitor) {
try {
createManifestFile(project, monitor);
createPlugInFile(project, monitor);
createBuildProperties(project, monitor);
} catch (Exception e) {
Activator.logErrorMessage(e.getMessage(), e);
}
}
public static void addNature(IProjectDescription description, String nature) {
String[] natures = description.getNatureIds();
String[] newNatures = new String[natures.length + 1];
System.arraycopy(natures, 0, newNatures, 0, natures.length);
newNatures[natures.length] = nature;
description.setNatureIds(newNatures);
}
private void createFolder(String path, IProject project, IProgressMonitor monitor) throws CoreException {
String[] strings = path.split("/");
IContainer currentContainer = project;
for ( String s : strings ) {
IFolder folder = currentContainer.getFolder( new Path(s) );
folder.create(true, true, monitor);
currentContainer = folder;
}
}
private void createManifestFile(IProject project, IProgressMonitor monitor) throws Exception {
IFolder metaInf = project.getFolder("META-INF");
metaInf.create(false, true, monitor);
String path = "META-INF/MANIFEST.MF";
IContainer currentContainer = project;
IFile file = currentContainer.getFile(new Path(path));
String contents = FileUtils.manifestMFPlugin(this.context.nameProject, new ArrayList<String>(), new ArrayList<String>());
InputStream stream = new ByteArrayInputStream(contents.getBytes());
if (file.exists()) {
file.setContents(stream, true, true, monitor);
} else {
file.create(stream, true, monitor);
}
stream.close();
}
private void createBuildProperties(IProject project, IProgressMonitor monitor) throws Exception {
String path = "build.properties";
IContainer currentContainer = project;
IFile file = currentContainer.getFile(new Path(path));
String contents = FileUtils.buildProperties();
InputStream stream = new ByteArrayInputStream(contents.getBytes());
if (file.exists()) {
file.setContents(stream, true, true, monitor);
} else {
file.create(stream, true, monitor);
}
stream.close();
}
private void createPlugInFile(IProject project,IProgressMonitor monitor) throws Exception {
String path = "/plugin.xml";
IContainer currentContainer = project;
IFile file = currentContainer.getFile(new Path(path));
String contents = FileUtils.pluginbasisXML();
InputStream stream = new ByteArrayInputStream(contents.getBytes());
if (file.exists()) {
file.setContents(stream, true, true, monitor);
} else {
file.create(stream, true, monitor);
}
stream.close();
}
private void createMavenFile(IProject project,IProgressMonitor monitor, Boolean bEcoreProject) throws Exception {
String path = "/pom.xml";
IContainer currentContainer = project;
IFile file = currentContainer.getFile(new Path(path));
String contents = "";
if(!bEcoreProject) {
if(this.context.ecoreProject) {
contents = FileUtils.pomXmlK3Ecore(this.context.nameProject, "GroupID", "ArtifactID", "0.0.1-SNAPSHOT", this.context.ecoreIFile.getName() + ".metamodel", this.context.ecoreIFile.getName() + ".metamodel", "0.0.1-SNAPSHOT");
}else {
contents = FileUtils.pomXmlK3(this.context.nameProject, "GroupID", "ArtifactID", "0.0.1-SNAPSHOT");
}
} else {
contents = FileUtils.pomXmlMetamodel(this.context.ecoreIFile.getName() + ".metamodel", this.context.ecoreIFile.getName() + ".metamodel", this.context.ecoreIFile.getName() + ".metamodel", "0.0.1-SNAPSHOT");
}
InputStream stream = new ByteArrayInputStream(contents.getBytes());
if (file.exists()) {
file.setContents(stream, true, true, monitor);
} else {
file.create(stream, true, monitor);
}
stream.close();
}
private void createDefaultKmt(IProject project,IProgressMonitor monitor) throws CoreException{
String path = "src/" + this.context.namePackage + "/HelloWorld.xtend";
IContainer currentContainer = project;
IFile file = currentContainer.getFile(new Path(path));
String contents = FileUtils.getFileTypeK3(this.context.namePackage);
try {
InputStream stream = new ByteArrayInputStream(contents.getBytes());
if (file.exists()) {
file.setContents(stream, true, true, monitor);
} else {
file.create(stream, true, monitor);
}
stream.close();
} catch (IOException e) {
Activator.logErrorMessage(e.getMessage(), e);
}
}
public Context getContext() {
return context;
}
public boolean createProjectWithEcore(IProgressMonitor monitor) {
boolean returnVal = true;
try {
final IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(this.context.ecoreIFile.getName() +".metamodel");
project.create(monitor);
project.open(monitor);
Boolean tabNature[] = {true,false,true,true};
addNatureToProject(project, tabNature);
createFolder("src/", project, monitor);
createFolder("model/", project, monitor);
createEcoreFile(project, monitor);
new GenerateGenModelCode().createGenModel(this.context.ecoreIFile.getLocation().toString(), this.context.ecoreIFile.getName() +".metamodel");
configurePlugIn(project, null);
try {
createMavenFile(project, monitor, true);
} catch (Exception e) {
Activator.logErrorMessage(e.getMessage(), e);
}
//setClassPath(project, monitor);
project.refreshLocal(IResource.DEPTH_INFINITE, monitor);
} catch (Exception exception) {
Activator.logErrorMessage(exception.getMessage(), exception);
returnVal = false;
}
if (this.context.indexTransfomation != 0) {
k3.language.aspectgenerator.AspectGenerator.aspectGenerate (
"File:///"+this.context.locationProject,
this.context.nameProject,
this.context.operationName,
"File:///"+this.context.ecoreIFile.getLocation().toOSString(),
this.context.listNewClass,
this.context.operationParams);
}
return returnVal;
}
public void addNatureToProject(IProject project, Boolean tabNature[]) {
IProjectDescription description;
try {
description = project.getDescription();
if (!tabNature[0] && !description.hasNature("org.eclipse.jdt.core.javanature")){
addNature(description, "org.eclipse.jdt.core.javanature");
}
if(!tabNature[1] && !description.hasNature("org.eclipse.xtext.ui.shared.xtextNature")){
addNature(description, "org.eclipse.xtext.ui.shared.xtextNature");
}
if(!tabNature[2] && (!description.hasNature("org.eclipse.pde.PluginNature"))){
addNature(description, "org.eclipse.pde.PluginNature");
}
if(!tabNature[3] && (!description.hasNature("org.eclipse.m2e.core.maven2Nature"))){
addNature(description, "org.eclipse.m2e.core.maven2Nature");
}
project.setDescription(description, null);
} catch (CoreException e) {
Activator.logErrorMessage(e.getMessage(), e);
}
}
private void createEcoreFile(IProject project,IProgressMonitor monitor) throws Exception {
String path = "model/"+ this.context.ecoreIFile.getName();
IContainer currentContainer = project;
IFile file = currentContainer.getFile(new Path(path));
String contents = "";
InputStream stream = new ByteArrayInputStream(contents.getBytes());
if (file.exists()) {
file.setContents(stream, true, true, monitor);
} else {
file.create(stream, true, monitor);
}
stream.close();
FileUtils.copyFile (new File(this.context.ecoreIFile.getLocationURI()), new File(file.getLocationURI()));
}
private String getContextNamePackage() {
return this.context.namePackage;
}
public WizardPageNewProjectK3Plugin getPageProject() {
return this.projectPage;
}
}
|
package com.thaiopensource.relaxng.output.rnc;
import com.thaiopensource.relaxng.edit.*;
import com.thaiopensource.relaxng.output.OutputDirectory;
import com.thaiopensource.relaxng.output.common.ErrorReporter;
import com.thaiopensource.relaxng.parse.SchemaBuilder;
import com.thaiopensource.xml.util.WellKnownNamespaces;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.HashSet;
import java.util.Vector;
import java.util.Collections;
import java.util.Map;
import java.util.HashMap;
/*
Annotations and comments (in progress)
Use \x{} escapes for characters not in repertoire of selected encoding
Avoid lines with excessive complexity
Make use of ##
Make long literals pretty
Take advantage of
default namespace x = "..."
*/
class Output {
private final Prettyprinter pp;
private final String sourceUri;
private final OutputDirectory od;
private final ErrorReporter er;
private final NamespaceManager.NamespaceBindings nsb;
private final Map datatypeLibraryMap = new HashMap();
private final NameClassVisitor nameClassOutput = new NameClassOutput(true);
private final NameClassVisitor noParenNameClassOutput = new NameClassOutput(false);
private final PatternVisitor noParenPatternOutput = new PatternOutput(false);
private final PatternVisitor patternOutput = new PatternOutput(true);
private final ComponentVisitor componentOutput = new ComponentOutput();
private final AnnotationChildVisitor annotationChildOutput = new AnnotationChildOutput();
private final AnnotationChildVisitor followingAnnotationChildOutput = new FollowingAnnotationChildOutput();
private boolean isAttributeNameClass;
static private final String indent = " ";
static private final String[] keywords = {
"attribute", "default", "datatypes", "div", "element", "empty", "external",
"grammar", "include", "inherit", "list", "mixed", "namespace", "notAllowed",
"parent", "start", "string", "text", "token"
};
static private final Set keywordSet = new HashSet();
static {
for (int i = 0; i < keywords.length; i++)
keywordSet.add(keywords[i]);
}
static void output(Pattern p, String sourceUri, OutputDirectory od, ErrorReporter er) throws IOException {
try {
new Output(sourceUri, od, er, NamespaceVisitor.createBindings(p)).topLevel(p);
}
catch (Prettyprinter.WrappedException e) {
throw e.getIOException();
}
}
private Output(String sourceUri, OutputDirectory od, ErrorReporter er,
NamespaceManager.NamespaceBindings nsb) throws IOException {
this.sourceUri = sourceUri;
this.od = od;
this.er = er;
this.pp = new StreamingPrettyprinter(od.getLineLength(), od.getLineSeparator(), od.open(sourceUri));
this.nsb = nsb;
}
private void topLevel(Pattern p) {
outputNamespaceDeclarations();
outputDatatypeLibraryDeclarations(p);
// XXX deal with annotations
if (p instanceof GrammarPattern)
innerBody(((GrammarPattern)p).getComponents());
else
p.accept(patternOutput);
pp.hardNewline();
pp.close();
}
private void outputNamespaceDeclarations() {
List prefixes = new Vector();
prefixes.addAll(nsb.getPrefixes());
Collections.sort(prefixes);
boolean needNewline = false;
for (Iterator iter = prefixes.iterator(); iter.hasNext();) {
String prefix = (String)iter.next();
String ns = nsb.getNamespaceUri(prefix);
if (prefix.length() == 0) {
if (!ns.equals(SchemaBuilder.INHERIT_NS)) {
pp.text("default namespace = ");
literal(ns);
pp.hardNewline();
needNewline = true;
}
}
else if (!prefix.equals("xml")) {
pp.text("namespace ");
pp.text(prefix);
pp.text(" = ");
if (ns.equals(SchemaBuilder.INHERIT_NS))
pp.text("inherit");
else
literal(ns);
pp.hardNewline();
needNewline = true;
}
}
if (needNewline)
pp.hardNewline();
}
private void outputDatatypeLibraryDeclarations(Pattern p) {
datatypeLibraryMap.put(WellKnownNamespaces.XML_SCHEMA_DATATYPES, "xsd");
List datatypeLibraries = new Vector();
datatypeLibraries.addAll(DatatypeLibraryVisitor.findDatatypeLibraries(p));
if (datatypeLibraries.isEmpty())
return;
Collections.sort(datatypeLibraries);
for (int i = 0, len = datatypeLibraries.size(); i < len; i++) {
String prefix = "d";
if (len > 1)
prefix += Integer.toString(i + 1);
String uri = (String)datatypeLibraries.get(i);
datatypeLibraryMap.put(uri, prefix);
pp.text("datatypes ");
pp.text(prefix);
pp.text(" = ");
literal(uri);
pp.hardNewline();
}
pp.hardNewline();
}
static class DatatypeLibraryVisitor extends NullVisitor {
private Set datatypeLibraries = new HashSet();
public void nullVisitValue(ValuePattern p) {
noteDatatypeLibrary(p.getDatatypeLibrary());
super.nullVisitValue(p);
}
public void nullVisitData(DataPattern p) {
noteDatatypeLibrary(p.getDatatypeLibrary());
super.nullVisitData(p);
}
private void noteDatatypeLibrary(String uri) {
if (!uri.equals("") && !uri.equals(WellKnownNamespaces.XML_SCHEMA_DATATYPES))
datatypeLibraries.add(uri);
}
static Set findDatatypeLibraries(Pattern p) {
DatatypeLibraryVisitor dlv = new DatatypeLibraryVisitor();
p.accept(dlv);
return dlv.datatypeLibraries;
}
}
static class NamespaceVisitor extends NullVisitor {
private NamespaceManager nsm = new NamespaceManager();
private boolean isAttribute;
public void nullVisitInclude(IncludeComponent c) {
super.nullVisitInclude(c);
nsm.requireNamespace(c.getNs(), true);
}
public void nullVisitExternalRef(ExternalRefPattern p) {
super.nullVisitExternalRef(p);
nsm.requireNamespace(p.getNs(), true);
}
public void nullVisitElement(ElementPattern p) {
isAttribute = false;
super.nullVisitElement(p);
}
public void nullVisitAttribute(AttributePattern p) {
isAttribute = true;
super.nullVisitAttribute(p);
}
public void nullVisitName(NameNameClass nc) {
super.nullVisitName(nc);
if (!isAttribute || nc.getNamespaceUri().length() != 0)
nsm.requireNamespace(nc.getNamespaceUri(), !isAttribute);
if (nc.getPrefix() == null) {
if (!isAttribute)
nsm.preferBinding("", nc.getNamespaceUri());
}
else
nsm.preferBinding(nc.getPrefix(), nc.getNamespaceUri());
}
public void nullVisitNsName(NsNameNameClass nc) {
super.nullVisitNsName(nc);
nsm.requireNamespace(nc.getNs(), false);
}
public void nullVisitValue(ValuePattern p) {
super.nullVisitValue(p);
for (Iterator iter = p.getPrefixMap().entrySet().iterator(); iter.hasNext();) {
Map.Entry entry = (Map.Entry)iter.next();
nsm.requireBinding((String)entry.getKey(), (String)entry.getValue());
}
}
public void nullVisitElement(ElementAnnotation ea) {
super.nullVisitElement(ea);
noteAnnotationBinding(ea.getPrefix(), ea.getNamespaceUri());
}
public void nullVisitAttribute(AttributeAnnotation a) {
super.nullVisitAttribute(a);
noteAnnotationBinding(a.getPrefix(), a.getNamespaceUri());
}
private void noteAnnotationBinding(String prefix, String ns) {
if (ns.length() != 0)
nsm.requireNamespace(ns, false);
if (prefix != null)
nsm.preferBinding(prefix, ns);
}
static NamespaceManager.NamespaceBindings createBindings(Pattern p) {
NamespaceVisitor nsv = new NamespaceVisitor();
p.accept(nsv);
return nsv.nsm.createBindings();
}
}
class ComponentOutput implements ComponentVisitor {
// XXX output annotations
public Object visitDefine(DefineComponent c) {
pp.startGroup();
String name = c.getName();
if (name == DefineComponent.START)
pp.text("start");
else
identifier(name);
Combine combine = c.getCombine();
String op;
if (combine == null)
op = " =";
else if (combine == Combine.CHOICE)
op = " |=";
else
op = " &=";
pp.text(op);
pp.startNest(indent);
pp.softNewline(" ");
c.getBody().accept(noParenPatternOutput);
pp.endNest();
pp.endGroup();
return null;
}
public Object visitDiv(DivComponent c) {
pp.text("div");
body(c);
return null;
}
public Object visitInclude(IncludeComponent c) {
pp.text("include ");
literal(od.reference(sourceUri, c.getHref()));
inherit(c.getNs());
List components = c.getComponents();
if (!components.isEmpty())
body(components);
return null;
}
}
class PatternOutput implements PatternVisitor {
private final boolean alwaysUseParens;
PatternOutput(boolean alwaysUseParens) {
this.alwaysUseParens = alwaysUseParens;
}
public Object visitGrammar(GrammarPattern p) {
startAnnotations(p);
pp.text("grammar");
body(p);
endAnnotations(p);
return null;
}
public Object visitElement(ElementPattern p) {
isAttributeNameClass = false;
nameClassed(p, "element ");
return null;
}
public Object visitAttribute(AttributePattern p) {
isAttributeNameClass = true;
nameClassed(p, "attribute ");
return null;
}
private void nameClassed(NameClassedPattern p, String key) {
startAnnotations(p);
pp.text(key);
pp.startNest(key);
p.getNameClass().accept(noParenNameClassOutput);
pp.endNest();
pp.startGroup();
pp.text(" {");
pp.startNest(indent);
pp.softNewline(" ");
p.getChild().accept(noParenPatternOutput);
pp.endNest();
pp.softNewline(" ");
pp.text("}");
pp.endGroup();
endAnnotations(p);
}
public Object visitOneOrMore(OneOrMorePattern p) {
postfix(p, "+");
return null;
}
public Object visitZeroOrMore(ZeroOrMorePattern p) {
postfix(p, "*");
return null;
}
public Object visitOptional(OptionalPattern p) {
postfix(p, "?");
return null;
}
private void postfix(UnaryPattern p, String op) {
if (!startAnnotations(p)) {
p.getChild().accept(patternOutput);
pp.text(op);
}
else {
pp.text("(");
pp.startNest("(");
p.getChild().accept(patternOutput);
pp.endNest();
pp.text(")");
pp.text(op);
}
endAnnotations(p);
}
public Object visitRef(RefPattern p) {
startAnnotations(p);
identifier(p.getName());
endAnnotations(p);
return null;
}
public Object visitParentRef(ParentRefPattern p) {
startAnnotations(p);
pp.text("parent ");
identifier(p.getName());
endAnnotations(p);
return null;
}
public Object visitExternalRef(ExternalRefPattern p) {
startAnnotations(p);
pp.text("external ");
literal(od.reference(sourceUri, p.getHref()));
inherit(p.getNs());
endAnnotations(p);
return null;
}
public Object visitText(TextPattern p) {
startAnnotations(p);
pp.text("text");
endAnnotations(p);
return null;
}
public Object visitEmpty(EmptyPattern p) {
startAnnotations(p);
pp.text("empty");
endAnnotations(p);
return null;
}
public Object visitNotAllowed(NotAllowedPattern p) {
startAnnotations(p);
pp.text("notAllowed");
endAnnotations(p);
return null;
}
public Object visitList(ListPattern p) {
prefix(p, "list");
return null;
}
public Object visitMixed(MixedPattern p) {
prefix(p, "mixed");
return null;
}
private void prefix(UnaryPattern p, String key) {
startAnnotations(p);
pp.text(key);
pp.text(" {");
pp.startNest(indent);
pp.softNewline(" ");
p.getChild().accept(noParenPatternOutput);
pp.endNest();
pp.softNewline(" ");
pp.text("}");
endAnnotations(p);
}
public Object visitChoice(ChoicePattern p) {
composite(p, "| ", false);
return null;
}
public Object visitInterleave(InterleavePattern p) {
composite(p, "& ", false);
return null;
}
public Object visitGroup(GroupPattern p) {
composite(p, ",", true);
return null;
}
void composite(CompositePattern p, String sep, boolean sepBeforeNewline) {
boolean useParens = alwaysUseParens;
if (startAnnotations(p))
useParens = true;
pp.startGroup();
if (useParens) {
pp.text("(");
pp.startNest("(");
}
boolean first = true;
for (Iterator iter = p.getChildren().iterator(); iter.hasNext();) {
if (!first) {
if (sepBeforeNewline)
pp.text(sep);
pp.softNewline(" ");
if (!sepBeforeNewline) {
pp.text(sep);
pp.startNest(sep);
}
}
((Pattern)iter.next()).accept(patternOutput);
if (first)
first = false;
else if (!sepBeforeNewline)
pp.endNest();
}
if (useParens) {
pp.endNest();
pp.text(")");
}
pp.endGroup();
endAnnotations(p);
}
public Object visitData(DataPattern p) {
startAnnotations(p);
String lib = p.getDatatypeLibrary();
String qn;
if (!lib.equals(""))
qn = (String)datatypeLibraryMap.get(lib) + ":" + p.getType();
else
qn = p.getType();
pp.text(qn);
List params = p.getParams();
if (params.size() > 0) {
pp.startGroup();
pp.text(" {");
pp.startNest(indent);
for (Iterator iter = params.iterator(); iter.hasNext();) {
pp.softNewline(" ");
Param param = (Param)iter.next();
startAnnotations(param);
pp.text(param.getName());
pp.text(" = ");
literal(param.getValue());
endAnnotations(param);
}
pp.endNest();
pp.softNewline(" ");
pp.text("}");
pp.endGroup();
}
Pattern e = p.getExcept();
if (e != null) {
if (params.size() == 0) {
pp.text(" - ");
pp.startNest(qn + " - ");
e.accept(patternOutput);
pp.endNest();
}
else {
pp.startGroup();
pp.softNewline(" ");
pp.text("- ");
pp.startNest("- ");
// XXX think we need parentheses if e has following annotations
e.accept(patternOutput);
pp.endNest();
pp.endGroup();
}
}
endAnnotations(p);
return null;
}
public Object visitValue(ValuePattern p) {
startAnnotations(p);
String lib = p.getDatatypeLibrary();
if (lib.equals("")) {
if (!p.getType().equals("token"))
pp.text(p.getType() + " ");
}
else
pp.text((String)datatypeLibraryMap.get(lib) + ":" + p.getType() + " ");
literal(p.getValue());
endAnnotations(p);
return null;
}
}
class NameClassOutput implements NameClassVisitor {
private final boolean alwaysUseParens;
NameClassOutput(boolean alwaysUseParens) {
this.alwaysUseParens = alwaysUseParens;
}
public Object visitAnyName(AnyNameNameClass nc) {
NameClass e = nc.getExcept();
if (e == null) {
startAnnotations(nc);
pp.text("*");
}
else {
boolean useParens = startAnnotations(nc) || alwaysUseParens;
String s = useParens ? "(* - " : "* - ";
pp.text(s);
pp.startNest(s);
e.accept(nameClassOutput);
if (useParens)
pp.text(")");
pp.endNest();
}
endAnnotations(nc);
return null;
}
public Object visitNsName(NsNameNameClass nc) {
NameClass e = nc.getExcept();
String prefix = nsb.getNonEmptyPrefix(nc.getNs());
if (e == null) {
startAnnotations(nc);
pp.text(prefix);
pp.text(":*");
}
else {
boolean useParens = startAnnotations(nc) || alwaysUseParens;
String s = useParens ? "(" : "";
s += prefix;
s += ":* - ";
pp.text(s);
pp.startNest(s);
e.accept(nameClassOutput);
pp.endNest();
if (useParens)
pp.text(")");
}
endAnnotations(nc);
return null;
}
public Object visitName(NameNameClass nc) {
startAnnotations(nc);
pp.text(qualifyName(nc.getNamespaceUri(), nc.getPrefix(), nc.getLocalName(), isAttributeNameClass));
endAnnotations(nc);
return null;
}
public Object visitChoice(ChoiceNameClass nc) {
boolean useParens = alwaysUseParens;
if (startAnnotations(nc))
useParens = true;
else if (nc.getChildren().size() == 1)
useParens = false;
if (useParens) {
pp.text("(");
pp.startNest("(");
}
pp.startGroup();
boolean first = true;
for (Iterator iter = nc.getChildren().iterator(); iter.hasNext();) {
if (first)
first = false;
else {
pp.softNewline(" ");
pp.text("| ");
}
((NameClass)iter.next()).accept(nameClassOutput);
}
pp.endGroup();
if (useParens) {
pp.endNest();
pp.text(")");
}
endAnnotations(nc);
return null;
}
}
class AnnotationChildOutput implements AnnotationChildVisitor {
public Object visitText(TextAnnotation ta) {
literal(ta.getValue());
return null;
}
public Object visitComment(Comment c) {
pp.text("
// XXX output the comment
pp.hardNewline();
return null;
}
public Object visitElement(ElementAnnotation elem) {
pp.text(qualifyName(elem.getNamespaceUri(), elem.getPrefix(), elem.getLocalName(),
// unqualified annotation element names have "" namespace
true));
pp.text(" ");
annotationBody(elem.getAttributes(), elem.getChildren());
return null;
}
}
class FollowingAnnotationChildOutput extends AnnotationChildOutput {
public Object visitElement(ElementAnnotation elem) {
pp.text(">> ");
pp.startNest(">> ");
super.visitElement(elem);
pp.endNest();
return null;
}
}
private static boolean hasAnnotations(Annotated annotated) {
return (!annotated.getChildElementAnnotations().isEmpty()
|| !annotated.getAttributeAnnotations().isEmpty()
|| !annotated.getFollowingElementAnnotations().isEmpty());
}
private boolean startAnnotations(Annotated annotated) {
if (!annotated.getLeadingComments().isEmpty()) {
// XXX output the comments
if (!hasAnnotations(annotated))
return false;
}
else if (!hasAnnotations(annotated))
return false;
pp.startGroup();
List before = (annotated.mayContainText()
? annotated.getFollowingElementAnnotations()
: annotated.getChildElementAnnotations());
if (!annotated.getAttributeAnnotations().isEmpty()
|| !before.isEmpty()) {
annotationBody(annotated.getAttributeAnnotations(), before);
pp.softNewline(" ");
}
return true;
}
private void endAnnotations(Annotated annotated) {
if (!annotated.mayContainText()) {
for (Iterator iter = annotated.getFollowingElementAnnotations().iterator(); iter.hasNext();) {
pp.softNewline(" ");
((AnnotationChild)iter.next()).accept(followingAnnotationChildOutput);
}
}
if (hasAnnotations(annotated))
pp.endGroup();
}
private void annotationBody(List attributes, List children) {
pp.startGroup();
pp.text("[");
pp.startNest(indent);
for (Iterator iter = attributes.iterator(); iter.hasNext();) {
AttributeAnnotation att = (AttributeAnnotation)iter.next();
pp.softNewline(" ");
pp.text(qualifyName(att.getNamespaceUri(), att.getPrefix(), att.getLocalName(), true));
pp.text(" = ");
literal(att.getValue());
}
for (Iterator iter = children.iterator(); iter.hasNext();) {
pp.softNewline(" ");
((AnnotationChild)iter.next()).accept(annotationChildOutput);
}
pp.endNest();
pp.softNewline(" ");
pp.text("]");
pp.endGroup();
}
private void body(Container container) {
body(container.getComponents());
}
private void body(List components) {
if (components.size() == 0)
pp.text(" { }");
else {
pp.text(" {");
pp.startNest(indent);
pp.hardNewline();
innerBody(components);
pp.endNest();
pp.hardNewline();
pp.text("}");
}
}
private void innerBody(List components) {
boolean first = true;
for (Iterator iter = components.iterator(); iter.hasNext();) {
if (first)
first = false;
else
pp.hardNewline();
((Component)iter.next()).accept(componentOutput);
}
}
private void inherit(String ns) {
if (ns.equals(nsb.getNamespaceUri("")))
return;
pp.text(" inherit = ");
pp.text(nsb.getNonEmptyPrefix(ns));
}
private void identifier(String name) {
if (keywordSet.contains(name))
pp.text("\\");
pp.text(name);
}
|
package org.apache.james.smtpserver;
import org.apache.avalon.cornerstone.services.connection.ConnectionHandler;
import org.apache.avalon.cornerstone.services.scheduler.PeriodicTimeTrigger;
import org.apache.avalon.cornerstone.services.scheduler.Target;
import org.apache.avalon.cornerstone.services.scheduler.TimeScheduler;
import org.apache.avalon.framework.component.ComponentException;
import org.apache.avalon.framework.component.ComponentManager;
import org.apache.avalon.framework.component.Composable;
import org.apache.avalon.framework.configuration.Configurable;
import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.ConfigurationException;
import org.apache.james.BaseConnectionHandler;
import org.apache.james.Constants;
import org.apache.james.core.MailHeaders;
import org.apache.james.core.MailImpl;
import org.apache.james.services.MailServer;
import org.apache.james.services.UsersRepository;
import org.apache.james.services.UsersStore;
import org.apache.james.util.*;
import org.apache.mailet.MailAddress;
import javax.mail.MessagingException;
import java.io.*;
import java.net.Socket;
import java.net.SocketException;
import java.util.*;
/**
* Provides SMTP functionality by carrying out the server side of the SMTP
* interaction.
*
* @author Serge Knystautas <sergek@lokitech.com>
* @author Federico Barbieri <scoobie@systemy.it>
* @author Jason Borden <jborden@javasense.com>
* @author Matthew Pangaro <mattp@lokitech.com>
* @author Danny Angus <danny@thought.co.uk>
* @author Peter M. Goldstein <farsight@alum.mit.edu>
*
* @version This is $Revision: 1.27 $
*/
public class SMTPHandler
extends BaseConnectionHandler
implements ConnectionHandler, Composable, Configurable, Target {
/**
* SMTP Server identification string used in SMTP headers
*/
private final static String SOFTWARE_TYPE = "JAMES SMTP Server "
+ Constants.SOFTWARE_VERSION;
// Keys used to store/lookup data in the internal state hash map
private final static String SERVER_NAME = "SERVER_NAME"; // Local server name
private final static String SERVER_TYPE = "SERVER_TYPE"; // SMTP Software Type
private final static String REMOTE_NAME = "REMOTE_NAME"; // Remote host name
private final static String REMOTE_IP = "REMOTE_IP"; // Remote IP address
private final static String NAME_GIVEN = "NAME_GIVEN"; // Remote host name provided by
// client
private final static String CURRENT_HELO_MODE = "CURRENT_HELO_MODE"; // HELO or EHLO
private final static String SENDER = "SENDER_ADDRESS"; // Sender's email address
private final static String MESG_FAILED = "MESG_FAILED"; // Message failed flag
private final static String MESG_SIZE = "MESG_SIZE"; // The size of the message
private final static String RCPT_VECTOR = "RCPT_VECTOR"; // The message recipients
private final static String SMTP_ID = "SMTP_ID"; // The SMTP ID associated with
// the connection
private final static String AUTH = "AUTHENTICATED"; // The authenticated user id
/**
* The character array that indicates termination of an SMTP connection
*/
private final static char[] SMTPTerminator = { '\r', '\n', '.', '\r', '\n' };
/**
* Static Random instance used to generate SMTP ids
*/
private final static Random random = new Random();
/**
* Static RFC822DateFormat used to generate date headers
*/
private final static RFC822DateFormat rfc822DateFormat = new RFC822DateFormat();
private Socket socket; // The TCP/IP socket over which the SMTP
// dialogue is occurring
private InputStream in; // The incoming stream of bytes coming from the socket.
private PrintWriter out; // The writer to which outgoing messages are written.
/**
* A Reader wrapper for the incoming stream of bytes coming from the socket.
*/
private BufferedReader inReader;
private String remoteHost; // The remote host name obtained by lookup on the socket.
private String remoteIP; // The remote IP address of the socket.
private String smtpID; // The id associated with this particular SMTP interaction.
private boolean authRequired = false; // Whether authentication is required to use
// this SMTP server.
private boolean verifyIdentity = false; // Whether the server verifies that the user
// actually sending an email matches the
// authentication credentials attached to the
// SMTP interaction.
private long maxmessagesize = 0; // The maximum message size allowed by this
// SMTP server. The default value, 0, means
// no limit.
private int lengthReset = 20000; // The number of bytes to read before resetting
// the connection timeout timer. Defaults to
// 20 seconds.
private TimeScheduler scheduler; // The scheduler used to handle timeouts for the SMTP
// interaction
private UsersRepository users; // The user repository for this server - used to authenticate
// users.
private MailServer mailServer; // The internal mail server service
private HashMap state = new HashMap(); // The hash map that holds variables for the SMTP
// session in progress.
/**
* Pass the <code>ComponentManager</code> to the <code>composer</code>.
* The instance uses the specified <code>ComponentManager</code> to
* acquire the components it needs for execution.
*
* @param componentManager The <code>ComponentManager</code> which this
* <code>Composable</code> uses.
* @throws ComponentException if an error occurs
*/
public void compose(final ComponentManager componentManager) throws ComponentException {
mailServer = (MailServer) componentManager.lookup("org.apache.james.services.MailServer");
scheduler =
(TimeScheduler) componentManager.lookup(
"org.apache.avalon.cornerstone.services.scheduler.TimeScheduler");
UsersStore usersStore =
(UsersStore) componentManager.lookup("org.apache.james.services.UsersStore");
users = usersStore.getRepository("LocalUsers");
}
/**
* Pass the <code>Configuration</code> to the instance.
*
* @param configuration the class configurations.
* @throws ConfigurationException if an error occurs
*/
public void configure(Configuration configuration) throws ConfigurationException {
super.configure(configuration);
authRequired = configuration.getChild("authRequired").getValueAsBoolean(false);
verifyIdentity = configuration.getChild("verifyIdentity").getValueAsBoolean(false);
// get the message size limit from the conf file and multiply
// by 1024, to put it in bytes
maxmessagesize = configuration.getChild( "maxmessagesize" ).getValueAsLong( 0 ) * 1024;
if (getLogger().isDebugEnabled()) {
getLogger().debug("Max message size is: " + maxmessagesize);
}
//how many bytes to read before updating the timer that data is being transfered
lengthReset = configuration.getChild("lengthReset").getValueAsInteger(20000);
}
/**
* Handle a connection.
* This handler is responsible for processing connections as they occur.
*
* @param connection the connection
* @throws IOException if an error reading from socket occurs
* @throws ProtocolException if an error handling connection occurs
*/
public void handleConnection(Socket connection) throws IOException {
try {
this.socket = connection;
in = new BufferedInputStream(socket.getInputStream(), 1024);
// An ASCII encoding can be used because all transmissions other
// that those in the DATA command are guaranteed
// to be ASCII
inReader = new BufferedReader(new InputStreamReader(in, "ASCII"));
out = new InternetPrintWriter(socket.getOutputStream(), true);
remoteHost = socket.getInetAddress().getHostName();
remoteIP = socket.getInetAddress().getHostAddress();
smtpID = random.nextInt(1024) + "";
resetState();
} catch (Exception e) {
StringBuffer exceptionBuffer =
new StringBuffer(256)
.append("Cannot open connection from ")
.append(remoteHost)
.append(" (")
.append(remoteIP)
.append("): ")
.append(e.getMessage());
String exceptionString = exceptionBuffer.toString();
getLogger().error(exceptionString, e );
throw new RuntimeException(exceptionString);
}
if (getLogger().isInfoEnabled()) {
StringBuffer infoBuffer =
new StringBuffer(128)
.append("Connection from ")
.append(remoteHost)
.append(" (")
.append(remoteIP)
.append(")");
getLogger().info(infoBuffer.toString());
}
try {
// Initially greet the connector
// Format is: Sat, 24 Jan 1998 13:16:09 -0500
final PeriodicTimeTrigger trigger = new PeriodicTimeTrigger( timeout, -1 );
scheduler.addTrigger( this.toString(), trigger, this );
StringBuffer responseBuffer =
new StringBuffer(192)
.append("220 ")
.append(this.helloName)
.append(" SMTP Server (")
.append(SOFTWARE_TYPE)
.append(") ready ")
.append(rfc822DateFormat.format(new Date()));
String responseString = responseBuffer.toString();
out.println(responseString);
out.flush();
logResponseString(responseString);
while (parseCommand(inReader.readLine())) {
scheduler.resetTrigger(this.toString());
}
getLogger().debug("Closing socket.");
scheduler.removeTrigger(this.toString());
} catch (SocketException se) {
if (getLogger().isDebugEnabled()) {
StringBuffer errorBuffer =
new StringBuffer(64)
.append("Socket to ")
.append(remoteHost)
.append(" closed remotely.");
getLogger().debug(errorBuffer.toString(), se );
}
} catch ( InterruptedIOException iioe ) {
if (getLogger().isDebugEnabled()) {
StringBuffer errorBuffer =
new StringBuffer(64)
.append("Socket to ")
.append(remoteHost)
.append(" timeout.");
getLogger().debug( errorBuffer.toString(), iioe );
}
} catch ( IOException ioe ) {
if (getLogger().isDebugEnabled()) {
StringBuffer errorBuffer =
new StringBuffer(256)
.append("Exception handling socket to ")
.append(remoteHost)
.append(":")
.append(ioe.getMessage());
getLogger().debug( errorBuffer.toString(), ioe );
}
} catch (Exception e) {
if (getLogger().isDebugEnabled()) {
getLogger().debug( "Exception opening socket: "
+ e.getMessage(), e );
}
} finally {
try {
socket.close();
} catch (IOException e) {
if (getLogger().isErrorEnabled()) {
getLogger().error("Exception closing socket: "
+ e.getMessage());
}
}
}
}
/**
* Callback method called when the the PeriodicTimeTrigger in
* handleConnection is triggered. In this case the trigger is
* being used as a timeout, so the method simply closes the connection.
*
* @param triggerName the name of the trigger
*/
public void targetTriggered(final String triggerName) {
getLogger().error("Connection timeout on socket");
try {
out.println("Connection timeout. Closing connection");
socket.close();
} catch (IOException e) {
}
}
/**
* Resets message-specific, but not authenticated user, state.
*
*/
private void resetState() {
String user = (String) state.get(AUTH);
state.clear();
state.put(SERVER_NAME, this.helloName);
state.put(SERVER_TYPE, SOFTWARE_TYPE);
state.put(REMOTE_NAME, remoteHost);
state.put(REMOTE_IP, remoteIP);
state.put(SMTP_ID, smtpID);
// seems that after authenticating an smtp client sends
// a RSET, so we need to remember that they are authenticated
if (user != null) {
state.put(AUTH, user);
}
}
/**
* This method parses SMTP commands read off the wire in handleConnection.
* Actual processing of the command (possibly including additional back and
* forth communication with the client) is delegated to one of a number of
* command specific handler methods. The primary purpose of this method is
* to parse the raw command string to determine exactly which handler should
* be called. It returns true if expecting additional commands, false otherwise.
*
* @param commandRaw the raw command string passed in over the socket
*
* @return whether additional commands are expected.
*/
private boolean parseCommand(String command) throws Exception {
String argument = null;
String argument1 = null;
boolean returnValue = true;
if (command == null) {
return false;
}
if ((state.get(MESG_FAILED) == null) && (getLogger().isDebugEnabled())) {
getLogger().debug("Command received: " + command);
}
command = command.trim();
if (command.indexOf(" ") > 0) {
argument = command.substring(command.indexOf(" ") + 1);
command = command.substring(0, command.indexOf(" "));
if (argument.indexOf(":") > 0) {
argument1 = argument.substring(argument.indexOf(":") + 1);
argument = argument.substring(0, argument.indexOf(":"));
}
}
command = command.toUpperCase(Locale.US);
if (command.equals("HELO")) {
doHELO(command, argument, argument1);
} else if (command.equals("EHLO")) {
doEHLO(command, argument, argument1);
} else if (command.equals("AUTH")) {
doAUTH(command, argument, argument1);
} else if (command.equals("MAIL")) {
doMAIL(command, argument, argument1);
} else if (command.equals("RCPT")) {
doRCPT(command, argument, argument1);
} else if (command.equals("NOOP")) {
doNOOP(command, argument, argument1);
} else if (command.equals("RSET")) {
doRSET(command, argument, argument1);
} else if (command.equals("DATA")) {
doDATA(command, argument, argument1);
} else if (command.equals("QUIT")) {
doQUIT(command, argument, argument1);
returnValue = false;
} else {
doUnknownCmd(command, argument, argument1);
}
return returnValue;
}
/**
* Handler method called upon receipt of a HELO command.
* Responds with a greeting and informs the client whether
* client authentication is required.
*
* @param command the command parsed by the parseCommand method
* @argument the first argument parsed by the parseCommand method
* @argument1 the second argument parsed by the parseCommand method
*/
private void doHELO(String command, String argument, String argument1) {
String responseString = null;
if (state.containsKey(CURRENT_HELO_MODE)) {
StringBuffer responseBuffer =
new StringBuffer(96)
.append("250 ")
.append(state.get(SERVER_NAME))
.append(" Duplicate HELO");
responseString = responseBuffer.toString();
out.println(responseString);
} else if (argument == null) {
responseString = "501 domain address required: " + command;
out.println(responseString);
} else {
state.put(CURRENT_HELO_MODE, command);
state.put(NAME_GIVEN, argument);
StringBuffer responseBuffer = new StringBuffer(256);
if (authRequired) {
//This is necessary because we're going to do a multiline response
responseBuffer.append("250-");
} else {
responseBuffer.append("250 ");
}
responseBuffer.append(state.get(SERVER_NAME))
.append(" Hello ")
.append(argument)
.append(" (")
.append(state.get(REMOTE_NAME))
.append(" [")
.append(state.get(REMOTE_IP))
.append("])");
responseString = responseBuffer.toString();
out.println(responseString);
if (authRequired) {
logResponseString(responseString);
responseString = "250 AUTH LOGIN PLAIN";
out.println(responseString);
}
}
out.flush();
logResponseString(responseString);
}
/**
* Handler method called upon receipt of a EHLO command.
* Responds with a greeting and informs the client whether
* client authentication is required.
*
* @param command the command parsed by the parseCommand method
* @argument the first argument parsed by the parseCommand method
* @argument1 the second argument parsed by the parseCommand method
*/
private void doEHLO(String command, String argument, String argument1) {
String responseString = null;
if (state.containsKey(CURRENT_HELO_MODE)) {
StringBuffer responseBuffer =
new StringBuffer(96)
.append("250 ")
.append(state.get(SERVER_NAME))
.append(" Duplicate EHLO");
responseString = responseBuffer.toString();
out.println(responseString);
} else if (argument == null) {
responseString = "501 domain address required: " + command;
out.println(responseString);
} else {
state.put(CURRENT_HELO_MODE, command);
state.put(NAME_GIVEN, argument);
// Extension defined in RFC 1870
if (maxmessagesize > 0) {
responseString = "250-SIZE " + maxmessagesize;
out.println(responseString);
logResponseString(responseString);
}
StringBuffer responseBuffer = new StringBuffer(256);
if (authRequired) {
//This is necessary because we're going to do a multiline response
responseBuffer.append("250-");
} else {
responseBuffer.append("250 ");
}
responseBuffer.append(state.get(SERVER_NAME))
.append(" Hello ")
.append(argument)
.append(" (")
.append(state.get(REMOTE_NAME))
.append(" [")
.append(state.get(REMOTE_IP))
.append("])");
responseString = responseBuffer.toString();
out.println(responseString);
if (authRequired) {
logResponseString(responseString);
responseString = "250 AUTH LOGIN PLAIN";
out.println(responseString);
}
}
out.flush();
logResponseString(responseString);
}
/**
* Handler method called upon receipt of a AUTH command.
* Handles client authentication to the SMTP server.
*
* @param command the command parsed by the parseCommand method
* @argument the first argument parsed by the parseCommand method
* @argument1 the second argument parsed by the parseCommand method
*/
private void doAUTH(String command, String argument, String argument1)
throws Exception {
String responseString = null;
if (state.containsKey(AUTH)) {
responseString = "503 User has previously authenticated. "
+ " Further authentication is not required!";
out.println(responseString);
} else if (argument == null) {
responseString = "501 Usage: AUTH (authentication type) <challenge>";
out.println(responseString);
} else {
if ((argument1 == null) && (argument.indexOf(" ") > 0)) {
argument1 = argument.substring(argument.indexOf(" ")+1);
argument = argument.substring(0,argument.indexOf(" "));
}
argument = argument.toUpperCase(Locale.US);
if (argument.equals("PLAIN")) {
String userpass = null, user = null, pass = null;
StringTokenizer authTokenizer;
if (argument1 == null) {
responseString = "334 OK. Continue authentication";
out.println(responseString);
out.flush();
logResponseString(responseString);
userpass = inReader.readLine().trim();
} else {
userpass = argument1.trim();
}
try {
if (userpass != null) {
userpass = Base64.decodeAsString(userpass);
}
if (userpass != null) {
authTokenizer = new StringTokenizer(userpass, "\0");
user = authTokenizer.nextToken();
pass = authTokenizer.nextToken();
}
}
catch (Exception e) {
// Ignored - this exception in parsing will be dealt
// with in the if clause below
}
// Authenticate user
if ((user == null) || (pass == null)) {
responseString = "501 Could not decode parameters for AUTH PLAIN";
out.println(responseString);
out.flush();
} else if (users.test(user, pass)) {
state.put(AUTH, user);
responseString = "235 Authentication Successful";
out.println(responseString);
getLogger().info("AUTH method PLAIN succeeded");
} else {
responseString = "535 Authentication Failed";
out.println(responseString);
getLogger().error("AUTH method PLAIN failed");
}
logResponseString(responseString);
return;
} else if (argument.equals("LOGIN")) {
String user = null, pass = null;
if (argument1 == null) {
responseString = "334 VXNlcm5hbWU6"; // base64 encoded "Username:"
out.println(responseString);
out.flush();
logResponseString(responseString);
user = inReader.readLine().trim();
} else {
user = argument1.trim();
}
if (user != null) {
try {
user = Base64.decodeAsString(user);
} catch (Exception e) {
// Ignored - this parse error will be
// addressed in the if clause below
user = null;
}
}
responseString = "334 UGFzc3dvcmQ6"; // base64 encoded "Password:"
out.println(responseString);
out.flush();
logResponseString(responseString);
pass = inReader.readLine().trim();
if (pass != null) {
try {
pass = Base64.decodeAsString(pass);
} catch (Exception e) {
// Ignored - this parse error will be
// addressed in the if clause below
pass = null;
}
}
// Authenticate user
if ((user == null) || (pass == null)) {
responseString = "501 Could not decode parameters for AUTH LOGIN";
out.println(responseString);
} else if (users.test(user, pass)) {
state.put(AUTH, user);
responseString = "235 Authentication Successful";
out.println(responseString);
getLogger().info("AUTH method LOGIN succeeded");
} else {
responseString = "535 Authentication Failed";
out.println(responseString);
getLogger().error("AUTH method LOGIN failed");
}
out.flush();
logResponseString(responseString);
return;
} else {
responseString = "504 Unrecognized Authentication Type";
out.println(responseString);
logResponseString(responseString);
if (getLogger().isErrorEnabled()) {
StringBuffer errorBuffer =
new StringBuffer(128)
.append("AUTH method ")
.append(argument)
.append(" is an unrecognized authentication type");
getLogger().error(errorBuffer.toString());
}
return;
}
}
out.flush();
logResponseString(responseString);
}
/**
* Handler method called upon receipt of a MAIL command.
* Sets up handler to deliver mail as the stated sender.
*
* @param command the command parsed by the parseCommand method
* @argument the first argument parsed by the parseCommand method
* @argument1 the second argument parsed by the parseCommand method
*/
private void doMAIL(String command, String argument, String argument1) {
String responseString = null;
if (state.containsKey(SENDER)) {
responseString = "503 Sender already specified";
out.println(responseString);
} else if (argument == null || !argument.toUpperCase(Locale.US).equals("FROM")
|| argument1 == null) {
responseString = "501 Usage: MAIL FROM:<sender>";
out.println(responseString);
} else {
String sender = argument1.trim();
int lastChar = sender.lastIndexOf('>');
// Check to see if any options are present and, if so, whether they are correctly formatted
// (separated from the closing angle bracket by a ' ').
if ((lastChar > 0) && (sender.length() > lastChar + 2) && (sender.charAt(lastChar + 1) == ' ')) {
String mailOptionString = sender.substring(lastChar + 2);
// Remove the options from the sender
sender = sender.substring(0, lastChar + 1);
StringTokenizer optionTokenizer = new StringTokenizer(mailOptionString, " ");
while (optionTokenizer.hasMoreElements()) {
String mailOption = optionTokenizer.nextToken();
int equalIndex = mailOptionString.indexOf('=');
String mailOptionName = mailOption;
String mailOptionValue = "";
if (equalIndex > 0) {
mailOptionName = mailOption.substring(0, equalIndex).toUpperCase(Locale.US);
mailOptionValue = mailOption.substring(equalIndex + 1);
}
// Handle the SIZE extension keyword
// TODO: Encapsulate option logic in a method
if (mailOptionName.startsWith("SIZE")) {
int size = 0;
try {
size = Integer.parseInt(mailOptionValue);
} catch (NumberFormatException pe) {
// This is a malformed option value. We ignore it
// and proceed to the next option.
continue;
}
if (getLogger().isDebugEnabled()) {
StringBuffer debugBuffer =
new StringBuffer(128)
.append("MAIL command option SIZE received with value ")
.append(size)
.append(".");
getLogger().debug(debugBuffer.toString());
}
if ((maxmessagesize > 0) && (size > maxmessagesize)) {
// Let the client know that the size limit has been hit.
responseString = "552 Message size exceeds fixed maximum message size";
out.println(responseString);
out.flush();
logResponseString(responseString);
getLogger().error(responseString);
return;
} else {
// put the message size in the message state so it can be used
// later to restrict messages for user quotas, etc.
state.put(MESG_SIZE, new Integer(size));
}
} else {
// Unexpected option attached to the Mail command
if (getLogger().isDebugEnabled()) {
StringBuffer debugBuffer =
new StringBuffer(128)
.append("MAIL command had unrecognized/unexpected option ")
.append(mailOptionName)
.append(" with value ")
.append(mailOptionValue);
getLogger().debug(debugBuffer.toString());
}
}
}
}
if (!sender.startsWith("<") || !sender.endsWith(">")) {
responseString = "501 Syntax error in parameters or arguments";
out.println(responseString);
logResponseString(responseString);
if (getLogger().isErrorEnabled()) {
StringBuffer errorBuffer =
new StringBuffer(128)
.append("Error parsing sender address: ")
.append(sender)
.append(": did not start and end with < >");
getLogger().error(errorBuffer.toString());
}
return;
}
MailAddress senderAddress = null;
//Remove < and >
sender = sender.substring(1, sender.length() - 1);
if (sender.length() == 0) {
//This is the <> case. Let senderAddress == null
} else {
if (sender.indexOf("@") < 0) {
sender = sender + "@localhost";
}
try {
senderAddress = new MailAddress(sender);
} catch (Exception pe) {
responseString = "501 Syntax error in parameters or arguments";
out.println(responseString);
logResponseString(responseString);
if (getLogger().isErrorEnabled()) {
StringBuffer errorBuffer =
new StringBuffer(256)
.append("Error parsing sender address: ")
.append(sender)
.append(": ")
.append(pe.getMessage());
getLogger().error(errorBuffer.toString());
}
return;
}
}
state.put(SENDER, senderAddress);
StringBuffer responseBuffer =
new StringBuffer(128)
.append("250 Sender <")
.append(sender)
.append("> OK");
responseString = responseBuffer.toString();
out.println(responseString);
}
out.flush();
logResponseString(responseString);
}
/**
* Handler method called upon receipt of a RCPT command.
* Reads recipient. Does some connection validation.
*
* @param command the command parsed by the parseCommand method
* @argument the first argument parsed by the parseCommand method
* @argument1 the second argument parsed by the parseCommand method
*/
private void doRCPT(String command, String argument, String argument1) {
String responseString = null;
if (!state.containsKey(SENDER)) {
responseString = "503 Need MAIL before RCPT";
out.println(responseString);
} else if (argument == null || !argument.toUpperCase(Locale.US).equals("TO")
|| argument1 == null) {
responseString = "501 Usage: RCPT TO:<recipient>";
out.println(responseString);
} else {
Collection rcptColl = (Collection) state.get(RCPT_VECTOR);
if (rcptColl == null) {
rcptColl = new Vector();
}
String recipient = argument1.trim();
int lastChar = recipient.lastIndexOf('>');
// Check to see if any options are present and, if so, whether they are correctly formatted
// (separated from the closing angle bracket by a ' ').
if ((lastChar > 0) && (recipient.length() > lastChar + 2) && (recipient.charAt(lastChar + 1) == ' ')) {
String rcptOptionString = recipient.substring(lastChar + 2);
// Remove the options from the recipient
recipient = recipient.substring(0, lastChar + 1);
StringTokenizer optionTokenizer = new StringTokenizer(rcptOptionString, " ");
while (optionTokenizer.hasMoreElements()) {
String rcptOption = optionTokenizer.nextToken();
int equalIndex = rcptOptionString.indexOf('=');
String rcptOptionName = rcptOption;
String rcptOptionValue = "";
if (equalIndex > 0) {
rcptOptionName = rcptOption.substring(0, equalIndex).toUpperCase(Locale.US);
rcptOptionValue = rcptOption.substring(equalIndex + 1);
}
// Unexpected option attached to the RCPT command
if (getLogger().isDebugEnabled()) {
StringBuffer debugBuffer =
new StringBuffer(128)
.append("RCPT command had unrecognized/unexpected option ")
.append(rcptOptionName)
.append(" with value ")
.append(rcptOptionValue);
getLogger().debug(debugBuffer.toString());
}
}
}
if (!recipient.startsWith("<") || !recipient.endsWith(">")) {
responseString = "501 Syntax error in parameters or arguments";
out.println(responseString);
out.flush();
logResponseString(responseString);
if (getLogger().isErrorEnabled()) {
StringBuffer errorBuffer =
new StringBuffer(192)
.append("Error parsing recipient address: ")
.append(recipient)
.append(": did not start and end with < >");
getLogger().error(errorBuffer.toString());
}
return;
}
MailAddress recipientAddress = null;
//Remove < and >
recipient = recipient.substring(1, recipient.length() - 1);
if (recipient.indexOf("@") < 0) {
recipient = recipient + "@localhost";
}
try {
recipientAddress = new MailAddress(recipient);
} catch (Exception pe) {
responseString = "501 Syntax error in parameters or arguments";
out.println(responseString);
logResponseString(responseString);
if (getLogger().isErrorEnabled()) {
StringBuffer errorBuffer =
new StringBuffer(192)
.append("Error parsing recipient address: ")
.append(recipient)
.append(": ")
.append(pe.getMessage());
getLogger().error(errorBuffer.toString());
}
return;
}
if (authRequired) {
// Make sure the mail is being sent locally if not
// authenticated else reject.
if (!state.containsKey(AUTH)) {
String toDomain = recipientAddress.getHost();
if (!mailServer.isLocalServer(toDomain)) {
responseString = "530 Authentication Required";
out.println(responseString);
logResponseString(responseString);
getLogger().error("Authentication is required for mail request");
return;
}
} else {
// Identity verification checking
if (verifyIdentity) {
String authUser = ((String) state.get(AUTH)).toLowerCase(Locale.US);
MailAddress senderAddress = (MailAddress) state.get(SENDER);
boolean domainExists = false;
if (!authUser.equals(senderAddress.getUser())) {
responseString = "503 Incorrect Authentication for Specified Email Address";
out.println(responseString);
logResponseString(responseString);
if (getLogger().isErrorEnabled()) {
StringBuffer errorBuffer =
new StringBuffer(128)
.append("User ")
.append(authUser)
.append(" authenticated, however tried sending email as ")
.append(senderAddress);
getLogger().error(errorBuffer.toString());
}
return;
}
if (!mailServer.isLocalServer(
senderAddress.getHost())) {
responseString = "503 Incorrect Authentication for Specified Email Address";
out.println(responseString);
logResponseString(responseString);
if (getLogger().isErrorEnabled()) {
StringBuffer errorBuffer =
new StringBuffer(128)
.append("User ")
.append(authUser)
.append(" authenticated, however tried sending email as ")
.append(senderAddress);
getLogger().error(errorBuffer.toString());
}
return;
}
}
}
}
rcptColl.add(recipientAddress);
state.put(RCPT_VECTOR, rcptColl);
StringBuffer responseBuffer =
new StringBuffer(96)
.append("250 Recipient <")
.append(recipient)
.append("> OK");
responseString = responseBuffer.toString();
out.println(responseString);
}
out.flush();
logResponseString(responseString);
}
/**
* Handler method called upon receipt of a NOOP command.
* Just sends back an OK and logs the command.
*
* @param command the command parsed by the parseCommand method
* @argument the first argument parsed by the parseCommand method
* @argument1 the second argument parsed by the parseCommand method
*/
private void doNOOP(String command, String argument, String argument1) {
String responseString = "250 OK";
out.println(responseString);
logResponseString(responseString);
}
/**
* Handler method called upon receipt of a RSET command.
* Resets message-specific, but not authenticated user, state.
*
* @param command the command parsed by the parseCommand method
* @argument the first argument parsed by the parseCommand method
* @argument1 the second argument parsed by the parseCommand method
*/
private void doRSET(String command, String argument, String argument1) {
resetState();
String responseString = "250 OK";
out.println(responseString);
out.flush();
logResponseString(responseString);
}
/**
* Handler method called upon receipt of a DATA command.
* Reads in message data, creates header, and delivers to
* mail server service for delivery.
*
* @param command the command parsed by the parseCommand method
* @argument the first argument parsed by the parseCommand method
* @argument1 the second argument parsed by the parseCommand method
*/
private void doDATA(String command, String argument, String argument1) {
String responseString = null;
if (!state.containsKey(SENDER)) {
responseString = "503 No sender specified";
out.println(responseString);
} else if (!state.containsKey(RCPT_VECTOR)) {
responseString = "503 No recipients specified";
out.println(responseString);
} else {
responseString = "354 Ok Send data ending with <CRLF>.<CRLF>";
out.println(responseString);
out.flush();
logResponseString(responseString);
try {
// Setup the input stream to notify the scheduler periodically
InputStream msgIn =
new SchedulerNotifyInputStream(in, scheduler, this.toString(), 20000);
// Look for data termination
msgIn = new CharTerminatedInputStream(msgIn, SMTPTerminator);
// if the message size limit has been set, we'll
// wrap msgIn with a SizeLimitedInputStream
if (maxmessagesize > 0) {
if (getLogger().isDebugEnabled()) {
StringBuffer logBuffer =
new StringBuffer(128)
.append("Using SizeLimitedInputStream ")
.append(" with max message size: ")
.append(maxmessagesize);
getLogger().debug(logBuffer.toString());
}
msgIn = new SizeLimitedInputStream(msgIn, maxmessagesize);
}
//Removes the dot stuffing
msgIn = new SMTPInputStream(msgIn);
//Parse out the message headers
MailHeaders headers = new MailHeaders(msgIn);
// if headers do not contains minimum REQUIRED headers fields,
// add them
if (!headers.isSet(RFC2822Headers.DATE)) {
headers.setHeader(RFC2822Headers.DATE, rfc822DateFormat.format(new Date()));
}
if (!headers.isSet(RFC2822Headers.FROM) && state.get(SENDER) != null) {
headers.setHeader(RFC2822Headers.FROM, state.get(SENDER).toString());
}
//Determine the Return-Path
String returnPath = headers.getHeader(RFC2822Headers.RETURN_PATH, "\r\n");
headers.removeHeader(RFC2822Headers.RETURN_PATH);
if (returnPath == null) {
if (state.get(SENDER) == null) {
returnPath = "<>";
} else {
StringBuffer returnPathBuffer =
new StringBuffer(64)
.append("<")
.append(state.get(SENDER))
.append(">");
returnPath = returnPathBuffer.toString();
}
}
//We will rebuild the header object to put Return-Path and our
// Received message at the top
Enumeration headerLines = headers.getAllHeaderLines();
headers = new MailHeaders();
//Put the Return-Path first
headers.addHeaderLine(RFC2822Headers.RETURN_PATH + ": " + returnPath);
//Put our Received header next
StringBuffer headerLineBuffer =
new StringBuffer(128)
.append(RFC2822Headers.RECEIVED + ": from ")
.append(state.get(REMOTE_NAME))
.append(" ([")
.append(state.get(REMOTE_IP))
.append("])");
headers.addHeaderLine(headerLineBuffer.toString());
headerLineBuffer =
new StringBuffer(256)
.append(" by ")
.append(this.helloName)
.append(" (")
.append(SOFTWARE_TYPE)
.append(") with SMTP ID ")
.append(state.get(SMTP_ID));
if (((Collection) state.get(RCPT_VECTOR)).size() == 1) {
//Only indicate a recipient if they're the only recipient
//(prevents email address harvesting and large headers in
// bulk email)
headers.addHeaderLine(headerLineBuffer.toString());
headerLineBuffer =
new StringBuffer(256)
.append(" for <")
.append(((Vector) state.get(RCPT_VECTOR)).get(0).toString())
.append(">;");
headers.addHeaderLine(headerLineBuffer.toString());
} else {
//Put the ; on the end of the 'by' line
headerLineBuffer.append(";");
headers.addHeaderLine(headerLineBuffer.toString());
}
headers.addHeaderLine(" " + rfc822DateFormat.format(new Date()));
//Add all the original message headers back in next
while (headerLines.hasMoreElements()) {
headers.addHeaderLine((String) headerLines.nextElement());
}
ByteArrayInputStream headersIn = new ByteArrayInputStream(headers.toByteArray());
MailImpl mail =
new MailImpl(
mailServer.getId(),
(MailAddress) state.get(SENDER),
(Vector) state.get(RCPT_VECTOR),
new SequenceInputStream(headersIn, msgIn));
// if the message size limit has been set, we'll
// call mail.getSize() to force the message to be
// loaded. Need to do this to enforce the size limit
if (maxmessagesize > 0) {
mail.getMessageSize();
}
mail.setRemoteHost((String) state.get(REMOTE_NAME));
mail.setRemoteAddr((String) state.get(REMOTE_IP));
mailServer.sendMail(mail);
} catch (MessagingException me) {
//Grab any exception attached to this one.
Exception e = me.getNextException();
//If there was an attached exception, and it's a
//MessageSizeException
if (e != null && e instanceof MessageSizeException) {
// Add an item to the state to suppress
// logging of extra lines of data
// that are sent after the size limit has
// been hit.
state.put(MESG_FAILED, Boolean.TRUE);
//then let the client know that the size
//limit has been hit.
responseString = "552 Error processing message: "
+ e.getMessage();
} else {
responseString = "451 Error processing message: "
+ me.getMessage();
}
out.println(responseString);
out.flush();
logResponseString(responseString);
getLogger().error(responseString);
return;
}
getLogger().info("Mail sent to Mail Server");
resetState();
responseString = "250 Message received";
out.println(responseString);
}
out.flush();
logResponseString(responseString);
}
/**
* Handler method called upon receipt of a QUIT command.
* This method informs the client that the connection is
* closing.
*
* @param command the command parsed by the parseCommand method
* @argument the first argument parsed by the parseCommand method
* @argument1 the second argument parsed by the parseCommand method
*/
private void doQUIT(String command, String argument, String argument1) {
StringBuffer responseBuffer =
new StringBuffer(128)
.append("221 ")
.append(state.get(SERVER_NAME))
.append(" Service closing transmission channel");
String responseString = responseBuffer.toString();
out.println(responseString);
out.flush();
logResponseString(responseString);
}
/**
* Handler method called upon receipt of an unrecognized command.
* Returns an error response and logs the command.
*
* @param command the command parsed by the parseCommand method
* @argument the first argument parsed by the parseCommand method
* @argument1 the second argument parsed by the parseCommand method
*/
private void doUnknownCmd(String command, String argument, String argument1) {
if (state.get(MESG_FAILED) == null) {
StringBuffer responseBuffer =
new StringBuffer(128)
.append("500 ")
.append(state.get(SERVER_NAME))
.append(" Syntax error, command unrecognized: ")
.append(command);
String responseString = responseBuffer.toString();
out.println(responseString);
out.flush();
logResponseString(responseString);
}
}
/**
* This method logs at a "DEBUG" level the response string that
* was sent to the SMTP client. The method is provided largely
* as syntactic sugar to neaten up the code base. It is declared
* private and final to encourage compiler inlining.
*
* @param responseString the response string sent to the client
*/
private final void logResponseString(String responseString) {
if (getLogger().isDebugEnabled()) {
getLogger().debug("Sent: " + responseString);
}
}
}
|
package outland.feature.server.features;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.document.DynamoDB;
import com.amazonaws.services.dynamodbv2.document.Item;
import com.amazonaws.services.dynamodbv2.document.ItemCollection;
import com.amazonaws.services.dynamodbv2.document.Page;
import com.amazonaws.services.dynamodbv2.document.PutItemOutcome;
import com.amazonaws.services.dynamodbv2.document.QueryOutcome;
import com.amazonaws.services.dynamodbv2.document.Table;
import com.amazonaws.services.dynamodbv2.document.spec.QuerySpec;
import com.amazonaws.services.dynamodbv2.document.utils.ValueMap;
import com.codahale.metrics.MetricRegistry;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import javax.inject.Inject;
import javax.inject.Named;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import outland.feature.proto.Feature;
import outland.feature.server.hystrix.HystrixConfiguration;
import outland.feature.server.protobuf.Protobuf3Support;
import static outland.feature.server.StructLog.kvp;
public class DefaultFeatureStorage implements FeatureStorage {
private static final Logger logger = LoggerFactory.getLogger(DefaultFeatureStorage.class);
static Map<String, Feature> features = Maps.newHashMap();
private final DynamoDB dynamoDB;
private final String featureTableName;
private final HystrixConfiguration hystrixWriteConfiguration;
private final HystrixConfiguration hystrixReadConfiguration;
private final MetricRegistry metrics;
@Inject
public DefaultFeatureStorage(
AmazonDynamoDB amazonDynamoDB,
FeatureTableConfiguration featureTableConfiguration,
@Named("dynamodbFeatureWriteHystrix") HystrixConfiguration hystrixWriteConfiguration,
@Named("dynamodbFeatureReadHystrix") HystrixConfiguration hystrixReadConfiguration,
MetricRegistry metrics
) {
this.dynamoDB = new DynamoDB(amazonDynamoDB);
this.featureTableName = featureTableConfiguration.outlandFeaturesTable;
this.hystrixWriteConfiguration = hystrixWriteConfiguration;
this.hystrixReadConfiguration = hystrixReadConfiguration;
this.metrics = metrics;
}
@Override public Void saveFeature(Feature feature) {
String key = feature.getKey();
String id = feature.getId();
String appId = feature.getAppId();
String json = Protobuf3Support.toJsonString(feature);
Map<String, String> owner = Maps.newHashMap();
if (!Strings.isNullOrEmpty(feature.getOwner().getName())) {
owner.put("name", feature.getOwner().getName());
}
owner.put("email", feature.getOwner().getEmail());
Item item = new Item()
.withString("app_id", appId)
.withString("feature_key", key)
.withString("id", id)
.withString("state", feature.getState().name())
.withString("json", json)
.withString("v", "1")
.withString("created", feature.getCreated())
.withString("updated", feature.getUpdated())
.withMap("owner", owner);
if (!Strings.isNullOrEmpty(feature.getDescription())) {
item.withString("desc", feature.getDescription());
}
Table table = dynamoDB.getTable(featureTableName);
DynamoDbCommand<PutItemOutcome> cmd = new DynamoDbCommand<>("saveFeature",
() -> table.putItem(item),
() -> {
throw new RuntimeException("saveFeature");
},
hystrixWriteConfiguration,
metrics);
PutItemOutcome outcome = cmd.execute();
logger.info("{} /dynamodb_put_item_result=[{}]",
kvp("op", "saveFeature", "app_id", appId, "feature_key", key, "result", "ok"),
outcome.getPutItemResult().toString());
return null;
}
@Override public Void updateFeature(Feature feature) {
logger.info("{}",
kvp("op", "updateFeature", "app_id", feature.getAppId(), "feature_key", feature.getKey()));
saveFeature(feature);
return null;
}
@Override public Optional<Feature> loadFeatureByKey(String appId, String key) {
logger.info("{}", kvp("op", "loadFeatureByKey", "app_id", appId, "feature_key", key));
Table table = dynamoDB.getTable(featureTableName);
DynamoDbCommand<Item> cmd = new DynamoDbCommand<>("loadFeatureByKey",
() -> getItem(appId, key, table),
() -> {
throw new RuntimeException("loadFeatureById");
},
hystrixReadConfiguration,
metrics);
Item item = cmd.execute();
if (item == null) {
return Optional.empty();
}
return Optional.of(FeatureSupport.toFeature(item.getString("json")));
}
private Item getItem(String appId, String key, Table table) {
return table.getItem("app_id", appId, "feature_key",key);
}
@Override public List<Feature> loadFeatures(String appId) {
logger.info("{}", kvp("op", "loadFeatures", "app_id", appId));
List<Feature> features = Lists.newArrayList();
Table table = dynamoDB.getTable(featureTableName);
QuerySpec querySpec = new QuerySpec()
.withKeyConditionExpression("app_id = :k_app_id")
.withValueMap(new ValueMap().withString(":k_app_id", appId))
.withConsistentRead(true);
DynamoDbCommand<ItemCollection<QueryOutcome>> cmd = new DynamoDbCommand<>("loadFeatures",
() -> queryTable(table, querySpec),
() -> {
throw new RuntimeException("loadFeatureById");
},
hystrixReadConfiguration,
metrics);
ItemCollection<QueryOutcome> items = cmd.execute();
for (Page<Item, QueryOutcome> page : items.pages()) {
page.forEach(item -> features.add(FeatureSupport.toFeature(item.getString("json"))));
}
return features;
}
private ItemCollection<QueryOutcome> queryTable(Table table, QuerySpec querySpec) {
return table.query(querySpec);
}
}
|
package com.angcyo.uiview.widget;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Region;
import android.support.v4.view.MotionEventCompat;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import com.angcyo.uiview.R;
import com.angcyo.uiview.skin.SkinHelper;
import java.util.HashSet;
import java.util.Set;
public class RSeekBar extends View {
public static final int THUMB_CIRCLE = 1;
public static final int THUMB_DEFAULT = 0;
int mTrackBgColor;
int mTrackColor;
int mTrackHeight;
int mTrackRadius;
int mThumbColor;
int mThumbHeight;
int mThumbWidth;
//thumbType==THUMB_CIRCLE
int mThumbRadius;
int mThumbRoundSize;
Paint mPaint;
/**
* (0-100)
*/
int curProgress = 0;
int secondProgress = 0;
int secondProgressColor;
int maxProgress = 100;
boolean isTouchDown = false;
Rect clipBounds = new Rect();
Set<OnProgressChangeListener> mOnProgressChangeListeners = new HashSet<>();
private float mDensity;
private RectF mProgressRectF = new RectF();
private RectF mTrackRectF = new RectF();
private int thumbType = THUMB_DEFAULT;
public RSeekBar(Context context) {
this(context, null);
}
public RSeekBar(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public RSeekBar(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
// if (isInEditMode()) {
// return;
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.RSeekBar);
mDensity = getResources().getDisplayMetrics().density;
mTrackBgColor = Color.parseColor("#cccccc");
mTrackColor = Color.parseColor("#fdc775");
mTrackHeight = (int) (2 * mDensity);
mThumbColor = mTrackColor;
mThumbHeight = (int) (10 * mDensity);
mThumbWidth = (int) (20 * mDensity);
mThumbRoundSize = (int) (10 * mDensity);
mTrackBgColor = typedArray.getColor(R.styleable.RSeekBar_r_track_bg_color, mTrackBgColor);
mTrackColor = typedArray.getColor(R.styleable.RSeekBar_r_track_color, mTrackColor);
secondProgressColor = SkinHelper.getTranColor(mTrackColor, 0x80);
secondProgressColor = typedArray.getColor(R.styleable.RSeekBar_r_second_progress_color, secondProgressColor);
mThumbColor = typedArray.getColor(R.styleable.RSeekBar_r_thumb_color, mThumbColor);
mTrackHeight = typedArray.getDimensionPixelOffset(R.styleable.RSeekBar_r_track_height, mTrackHeight);
mThumbHeight = typedArray.getDimensionPixelOffset(R.styleable.RSeekBar_r_thumb_height, mThumbHeight);
mThumbWidth = typedArray.getDimensionPixelOffset(R.styleable.RSeekBar_r_thumb_width, mThumbWidth);
mThumbRoundSize = typedArray.getDimensionPixelOffset(R.styleable.RSeekBar_r_thumb_round_size, mThumbRoundSize);
mTrackRadius = typedArray.getDimensionPixelOffset(R.styleable.RSeekBar_r_track_round_size, 0);
curProgress = typedArray.getInteger(R.styleable.RSeekBar_r_cur_progress, curProgress);
secondProgress = typedArray.getInteger(R.styleable.RSeekBar_r_second_progress, secondProgress);
thumbType = typedArray.getInt(R.styleable.RSeekBar_r_thumb_type, THUMB_DEFAULT);
curProgress = ensureProgress(curProgress);
typedArray.recycle();
if (thumbType == THUMB_CIRCLE) {
mThumbRadius = Math.min(mThumbWidth, mThumbHeight);
mThumbWidth = mThumbHeight = mThumbRadius;
}
initView();
}
private void initView() {
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
if (curProgress != 0) {
notifyListenerProgress(false);
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
if (widthMode == MeasureSpec.AT_MOST || widthMode == MeasureSpec.UNSPECIFIED) {
widthSize = (int) (100 * mDensity + mThumbWidth) + getPaddingLeft() + getPaddingRight();
}
if (heightMode == MeasureSpec.AT_MOST || heightMode == MeasureSpec.UNSPECIFIED) {
heightSize = Math.max(mThumbHeight, mTrackHeight) + getPaddingBottom() + getPaddingTop();
}
setMeasuredDimension(widthSize, heightSize);
}
@Override
protected void onDraw(Canvas canvas) {
// if (isInEditMode()) {
// canvas.drawColor(Color.BLACK);
// return;
canvas.save();
mPaint.setColor(mTrackBgColor);
int trackLeft = getPaddingLeft();
int trackTop = (getMeasuredHeight() - mTrackHeight) / 2;
int trackRight = getMeasuredWidth() - getPaddingRight();
int trackBottom = getMeasuredHeight() / 2 + mTrackHeight / 2;
mTrackRectF.set(trackLeft, trackTop, trackRight, trackBottom);
canvas.drawRoundRect(mTrackRectF, mTrackRadius, mTrackRadius, mPaint);
canvas.restore();
if (secondProgress > 0) {
canvas.save();
mPaint.setColor(secondProgressColor);
if (thumbType == THUMB_DEFAULT) {
mTrackRectF.set(trackLeft, trackTop, trackLeft + secondProgress / getMaxProgress() * getMaxProgressLength(), trackBottom);
} else if (thumbType == THUMB_CIRCLE) {
mTrackRectF.set(trackLeft, trackTop, trackLeft + secondProgress / getMaxProgress() * getMaxProgressLength(), trackBottom);
}
canvas.drawRoundRect(mTrackRectF, mTrackRadius, mTrackRadius, mPaint);
canvas.restore();
}
canvas.save();
mPaint.setColor(mTrackColor);
if (thumbType == THUMB_DEFAULT) {
mTrackRectF.set(trackLeft, trackTop, trackLeft + curProgress / getMaxProgress() * getMaxLength() + mThumbWidth / 2, trackBottom);
} else if (thumbType == THUMB_CIRCLE) {
mTrackRectF.set(trackLeft, trackTop, trackLeft + curProgress / getMaxProgress() * getMaxLength() + mThumbRadius / 2, trackBottom);
}
canvas.drawRoundRect(mTrackRectF, mTrackRadius, mTrackRadius, mPaint);
canvas.restore();
updateProgress();
//, touch
if (isTouchDown && thumbType == THUMB_CIRCLE) {
canvas.save();
canvas.getClipBounds(clipBounds);
clipBounds.inset(-mThumbRoundSize * 2, -mThumbRoundSize * 2);
canvas.clipRect(clipBounds, Region.Op.REPLACE);
mPaint.setColor(secondProgressColor);
canvas.drawCircle(mProgressRectF.centerX(), mProgressRectF.centerY(),
mThumbRoundSize + mThumbRoundSize / 2, mPaint);
canvas.restore();
}
canvas.save();
mPaint.setColor(mThumbColor);
if (thumbType == THUMB_DEFAULT) {
canvas.drawRoundRect(mProgressRectF, mThumbRoundSize, mThumbRoundSize, mPaint);
} else if (thumbType == THUMB_CIRCLE) {
canvas.drawCircle(mProgressRectF.centerX(), mProgressRectF.centerY(), mThumbHeight / 2, mPaint);
}
canvas.restore();
}
private int getMaxLength() {
return getMeasuredWidth() - getPaddingLeft() - getPaddingRight() - mThumbWidth;
}
private int getMaxProgressLength() {
return getMeasuredWidth() - getPaddingLeft() - getPaddingRight();
}
private void updateProgress() {
int left = (int) (getPaddingLeft() + curProgress / getMaxProgress() * getMaxLength());
mProgressRectF.set(left, (getMeasuredHeight() - mThumbHeight) / 2,
left + mThumbWidth, getMeasuredHeight() / 2 + mThumbHeight / 2);
}
public float getMaxProgress() {
return maxProgress * 1f;
}
public void setMaxProgress(int maxProgress) {
this.maxProgress = maxProgress;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (!isEnabled()) {
return super.onTouchEvent(event);
}
int action = MotionEventCompat.getActionMasked(event);
float eventX = event.getX();
//L.e("call: onTouchEvent([event])-> " + action + " x:" + eventX);
switch (action) {
case MotionEvent.ACTION_DOWN:
//L.e("call: onTouchEvent([event])-> DOWN:" + " x:" + eventX);
isTouchDown = true;
notifyListenerStartTouch();
calcProgress(eventX);
getParent().requestDisallowInterceptTouchEvent(true);
break;
case MotionEvent.ACTION_MOVE:
calcProgress(eventX);
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
isTouchDown = false;
notifyListenerStopTouch();
getParent().requestDisallowInterceptTouchEvent(false);
break;
}
return true;
}
/**
* touch,
*/
private void calcProgress(float touchX) {
float x = touchX - getPaddingLeft() - mThumbWidth / 2;
int old = this.curProgress;
this.curProgress = ensureProgress((int) (x / getMaxLength() * maxProgress));
if (old != curProgress) {
notifyListenerProgress(true);
}
postInvalidate();
}
private void notifyListenerProgress(boolean fromTouch) {
for (OnProgressChangeListener listener : mOnProgressChangeListeners) {
listener.onProgress(curProgress, fromTouch);
}
}
private void notifyListenerStartTouch() {
for (OnProgressChangeListener listener : mOnProgressChangeListeners) {
listener.onStartTouch();
}
}
private void notifyListenerStopTouch() {
for (OnProgressChangeListener listener : mOnProgressChangeListeners) {
listener.onStopTouch();
}
}
private int ensureProgress(int progress) {
return Math.max(0, Math.min(maxProgress, progress));
}
public void addOnProgressChangeListener(OnProgressChangeListener listener) {
mOnProgressChangeListeners.add(listener);
}
public void removeOnProgressChangeListener(OnProgressChangeListener listener) {
mOnProgressChangeListeners.remove(listener);
}
public int getCurProgress() {
return curProgress;
}
public void setCurProgress(int curProgress) {
this.curProgress = Math.min(curProgress, maxProgress);
postInvalidate();
notifyListenerProgress(false);
}
public void setSecondProgress(int secondProgress) {
this.secondProgress = Math.min(secondProgress, maxProgress);
postInvalidate();
}
public void setTrackBgColor(int trackBgColor) {
mTrackBgColor = trackBgColor;
}
public void setTrackColor(int trackColor) {
mTrackColor = trackColor;
}
public void setThumbColor(int thumbColor) {
mThumbColor = thumbColor;
}
public void setSecondProgressColor(int secondProgressColor) {
this.secondProgressColor = secondProgressColor;
}
public interface OnProgressChangeListener {
void onProgress(int progress, boolean fromTouch);
void onStartTouch();
void onStopTouch();
}
}
|
/*
* @author max
*/
package com.intellij.openapi.vfs.impl.jar;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.application.PathManager;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vfs.JarFileSystem;
import com.intellij.openapi.vfs.VfsBundle;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.newvfs.FileSystemInterface;
import com.intellij.openapi.vfs.newvfs.NewVirtualFile;
import gnu.trove.THashMap;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.*;
import java.lang.ref.SoftReference;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class JarHandler implements FileSystemInterface {
@NonNls private static final String JARS_FOLDER = "jars";
private final Lock lock = new ReentrantLock();
private SoftReference<ZipFile> myZipFile = new SoftReference<ZipFile>(null);
private final JarFileSystemImpl myFileSystem;
private final String myBasePath;
private SoftReference<Map<String, EntryInfo>> myRelPathsToEntries = new SoftReference<Map<String, EntryInfo>>(null);
private static class EntryInfo {
public EntryInfo(final String shortName, final EntryInfo parent, final boolean directory) {
this.shortName = new String(shortName);
this.parent = parent;
isDirectory = directory;
}
final boolean isDirectory;
private final String shortName;
final EntryInfo parent;
}
public JarHandler(final JarFileSystemImpl fileSystem, String path) {
myFileSystem = fileSystem;
myBasePath = path;
}
public void dispose() {
}
public void markDirty() {
lock.lock();
try {
myRelPathsToEntries.clear();
myZipFile = new SoftReference<ZipFile>(null);
NewVirtualFile root = (NewVirtualFile)
JarFileSystem.getInstance().findFileByPath(myBasePath + JarFileSystem.JAR_SEPARATOR);
if (root != null) {
root.markDirtyReqursively();
/*RefreshQueue.getInstance().refresh(true, true, null, root);*/
}
}
finally {
lock.unlock();
}
}
@NotNull
private Map<String, EntryInfo> initEntries() {
lock.lock();
try {
Map<String, EntryInfo> map = myRelPathsToEntries.get();
if (map == null) {
final ZipFile zip = getZip();
map = new THashMap<String, EntryInfo>();
if (zip == null) return map;
map.put("", new EntryInfo("", null, true));
final Enumeration<? extends ZipEntry> entries = zip.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
final String name = entry.getName();
final boolean isDirectory = name.endsWith("/");
getOrCreate(isDirectory ? name.substring(0, name.length() - 1) : name, isDirectory, map);
}
myRelPathsToEntries = new SoftReference<Map<String, EntryInfo>>(map);
}
return map;
}
finally {
lock.unlock();
}
}
private static EntryInfo getOrCreate(String entryName, boolean isDirectory, Map<String, EntryInfo> map) {
EntryInfo info = map.get(entryName);
if (info == null) {
int idx = entryName.lastIndexOf('/');
final String parentEntryName = idx > 0 ? entryName.substring(0, idx) : "";
String shortName = idx > 0 ? entryName.substring(idx + 1) : entryName;
info = new EntryInfo(shortName, getOrCreate(parentEntryName, true, map), isDirectory);
map.put(entryName, info);
}
return info;
}
public String[] list(final VirtualFile file) {
lock.lock();
try {
EntryInfo parentEntry = getEntryInfo(file);
Set<String> names = new HashSet<String>();
for (EntryInfo info : getEntriesMap().values()) {
if (info.parent == parentEntry) {
names.add(info.shortName);
}
}
return names.toArray(new String[names.size()]);
}
finally {
lock.unlock();
}
}
private EntryInfo getEntryInfo(final VirtualFile file) {
String parentPath = getRelativePath(file);
return getEntriesMap().get(parentPath);
}
private String getRelativePath(final VirtualFile file) {
final String path = file.getPath().substring(myBasePath.length() + 1);
return path.startsWith("/") ? path.substring(1) : path;
}
public File getMirrorFile(File originalFile) {
if (!myFileSystem.isMakeCopyOfJar(originalFile) || !originalFile.exists()) return originalFile;
String folderPath = PathManager.getSystemPath() + File.separatorChar + JARS_FOLDER;
if (!new File(folderPath).exists()) {
if (!new File(folderPath).mkdirs()) {
return originalFile;
}
}
String fileName = originalFile.getName() + "." + Integer.toHexString(originalFile.getPath().hashCode());
final File mirror = new File(folderPath, fileName);
if (!mirror.exists() || Math.abs(originalFile.lastModified() - mirror.lastModified()) > 2000) {
return copyToMirror(originalFile, mirror);
}
return mirror;
}
private File copyToMirror(final File original, final File mirror) {
ProgressManager progressManager = ProgressManager.getInstance();
ProgressIndicator progress = progressManager.getProgressIndicator();
if (progress != null){
progress.pushState();
progress.setText(VfsBundle.message("jar.copy.progress", original.getPath()));
progress.setFraction(0);
}
try{
FileUtil.copy(original, mirror);
}
catch(final IOException e){
final String path1 = original.getPath();
final String path2 = mirror.getPath();
ApplicationManager.getApplication().invokeLater(new Runnable() {
public void run() {
Messages.showMessageDialog(VfsBundle.message("jar.copy.error.message", path1, path2, e.getMessage()), VfsBundle.message("jar.copy.error.title"),
Messages.getErrorIcon());
}
}, ModalityState.NON_MODAL);
myFileSystem.setNoCopyJarForPath(path1);
return original;
}
if (progress != null){
progress.popState();
}
return mirror;
}
@Nullable
public ZipFile getZip() {
ZipFile zip = myZipFile.get();
if (zip == null) {
try {
zip = new ZipFile(getMirrorFile(getOriginalFile()));
myZipFile = new SoftReference<ZipFile>(zip);
}
catch (IOException e) {
return null;
}
}
return zip;
}
private File getOriginalFile() {
return new File(myBasePath);
}
@Nullable
private ZipEntry convertToEntry(VirtualFile file) {
String path = getRelativePath(file);
final ZipFile zip = getZip();
return zip != null ? zip.getEntry(path) : null;
}
public long getCRC(final VirtualFile file) {
if (file.getParent() == null) return -1L; // Optimization
lock.lock();
try {
final ZipEntry entry = convertToEntry(file);
return entry != null ? entry.getCrc() : -1L;
}
finally {
lock.unlock();
}
}
public long getLength(final VirtualFile file) {
lock.lock();
try {
final ZipEntry entry = convertToEntry(file);
return entry != null ? entry.getSize() : 0;
}
finally {
lock.unlock();
}
}
public InputStream getInputStream(final VirtualFile file) throws IOException {
lock.lock();
try {
final ZipEntry entry = convertToEntry(file);
if (entry == null) {
lock.unlock();
return new ByteArrayInputStream(new byte[0]);
}
final ZipFile zip = getZip();
assert zip != null;
return new BufferedInputStream(zip.getInputStream(entry)) {
public void close() throws IOException {
super.close();
lock.unlock();
}
};
}
catch (Throwable e) {
lock.unlock();
throw new RuntimeException(e);
}
}
public long getTimeStamp(final VirtualFile file) {
if (file.getParent() == null) return -1L; // Optimization
lock.lock();
try {
final ZipEntry entry = convertToEntry(file);
return entry != null ? entry.getTime() : -1L;
}
finally {
lock.unlock();
}
}
public boolean isDirectory(final VirtualFile file) {
if (file.getParent() == null) return true; // Optimization
lock.lock();
try {
String path = getRelativePath(file);
final EntryInfo info = getEntriesMap().get(path);
return info == null || info.isDirectory;
}
finally {
lock.unlock();
}
}
private Map<String, EntryInfo> getEntriesMap() {
return initEntries();
}
public boolean isWritable(final VirtualFile file) {
return false;
}
public boolean exists(final VirtualFile fileOrDirectory) {
if (fileOrDirectory.getParent() == null) {
// Optimization. Do not build entries if asked for jar root existence.
return myZipFile.get() != null || getOriginalFile().exists();
}
return getEntryInfo(fileOrDirectory) != null;
}
private static void throwReadOnly() throws IOException {
throw new IOException("Jar file system is read-only");
}
@SuppressWarnings({"ConstantConditions"})
public OutputStream getOutputStream(final VirtualFile file, final Object requestor, final long modStamp, final long timeStamp) throws IOException {
throwReadOnly();
return null; // Unreachable
}
@SuppressWarnings({"ConstantConditions"})
public VirtualFile copyFile(final Object requestor, final VirtualFile file, final VirtualFile newParent, final String copyName) throws IOException {
throwReadOnly();
return null;
}
public void moveFile(final Object requestor, final VirtualFile file, final VirtualFile newParent) throws IOException {
throwReadOnly();
}
public void renameFile(final Object requestor, final VirtualFile file, final String newName) throws IOException {
throwReadOnly();
}
public void setTimeStamp(final VirtualFile file, final long modstamp) throws IOException {
throwReadOnly();
}
public void setWritable(final VirtualFile file, final boolean writableFlag) throws IOException {
throwReadOnly();
}
@SuppressWarnings({"ConstantConditions"})
public VirtualFile createChildDirectory(final Object requestor, final VirtualFile parent, final String dir) throws IOException {
throwReadOnly();
return null;
}
@SuppressWarnings({"ConstantConditions"})
public VirtualFile createChildFile(final Object requestor, final VirtualFile parent, final String file) throws IOException {
throwReadOnly();
return null;
}
public void deleteFile(final Object requestor, final VirtualFile file) throws IOException {
throwReadOnly();
}
}
|
package com.psddev.dari.util;
import java.io.IOException;
import java.lang.reflect.Array;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.UUID;
import javax.servlet.Servlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.jsp.PageContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.joda.time.DateTime;
/** Utility methods for working with a web page. */
public class WebPageContext {
private final Object page;
private final ServletContext servletContext;
private final HttpServletRequest request;
private final HttpServletResponse response;
private HtmlWriter writer;
private Converter converter;
/**
* Creates an instance based on the given {@code pageContext}.
*
* @param pageContext Can't be {@code null}.
*/
public WebPageContext(PageContext pageContext) {
ErrorUtils.errorIfNull(pageContext, "pageContext");
this.page = pageContext.getPage();
this.servletContext = pageContext.getServletContext();
this.request = (HttpServletRequest) pageContext.getRequest();
this.response = (HttpServletResponse) pageContext.getResponse();
this.writer = new HtmlWriter(pageContext.getOut());
}
/**
* Creates an instance based on the given {@code servlet},
* {@code request}, {@code response}.
*
* @param servlet Can't be {@code null}.
*/
public WebPageContext(
Servlet servlet,
HttpServletRequest request,
HttpServletResponse response) {
ErrorUtils.errorIfNull(servlet, "servlet");
this.page = servlet;
this.servletContext = servlet.getServletConfig().getServletContext();
this.request = request;
this.response = response;
this.writer = null;
}
/**
* Creates an instance based on the given {@code servletContext},
* {@code request}, and {@code response}.
*/
public WebPageContext(
ServletContext servletContext,
HttpServletRequest request,
HttpServletResponse response) {
this.page = null;
this.servletContext = servletContext;
this.request = request;
this.response = response;
this.writer = null;
}
/**
* Returns the original servlet context.
*
* @return Never {@code null}.
*/
public ServletContext getServletContext() {
return servletContext;
}
/**
* Returns the original request.
*
* @return Never {@code null}.
*/
public HttpServletRequest getRequest() {
return request;
}
/**
* Returns the original response.
*
* @return Never {@code null}.
*/
public HttpServletResponse getResponse() {
return response;
}
/**
* Returns the original output writer.
*
* @return Never {@code null}.
*/
public HtmlWriter getWriter() throws IOException {
if (writer == null) {
writer = new HtmlWriter(getResponse().getWriter());
}
return writer;
}
/**
* Returns the converter.
*
* @return Never {@code null}.
*/
public Converter getConverter() {
if (converter == null) {
converter = new Converter();
converter.putAllStandardFunctions();
}
return converter;
}
/**
* Sets the converter.
*
* @param converter If {@code null}, restores the default converter.
*/
public void setConverter(Converter converter) {
this.converter = converter;
}
/**
* Stringifies and writes all given {@code objects} to output writer.
*
* @param objects May be {@code null}.
*/
public void write(Object... objects) throws IOException {
if (objects != null) {
for (Object object : objects) {
getWriter().write(String.valueOf(object));
}
}
}
/**
* Escapes the given {@code input}, or if it's {@code null} the given
* {@code defaultValue}, so that it's safe to use in an HTML page.
*
* @param input Can be {@code null}.
* @param defaultValue Can be {@code null}.
*/
public String h(Object input, Object defaultValue) {
return StringUtils.escapeHtml(input != null ?
input.toString() :
String.valueOf(defaultValue));
}
/**
* Escapes the given {@code input} so that it's safe to use in
* an HTML page.
*
* @param input Can be {@code null}.
* @return Empty string if the given {@code input} is {@code null}.
*/
public String h(Object input) {
return h(input, "");
}
/**
* Escapes the given {@code input} so that it's safe to use in
* JavaScript code.
*
* @param input Can be {@code null}.
* @return Empty string if the given {@code input} is {@code null}.
*/
public String js(Object input) {
return input == null ? "" : StringUtils.escapeJavaScript(input.toString());
}
/**
* Returns all request parameter names.
*
* @return Never {@code null}. Mutable.
*/
public List<String> paramNamesList() {
List<String> names = new ArrayList<String>();
@SuppressWarnings("unchecked")
Enumeration<String> namesEnumeration = getRequest().getParameterNames();
if (namesEnumeration != null) {
while (namesEnumeration.hasMoreElements()) {
Object value = namesEnumeration.nextElement();
names.add(value != null ? value.toString() : null);
}
}
return names;
}
/**
* Returns the parameter associated with the given {@code name}
* as an instance of the given {@code returnType}, or if not found or
* is blank, the given {@code defaultValue}.
*
* @param returnType Can't be {@code null}.
* @param name Can be {@code null}.
* @param defaultValue Can be {@code null}.
* @return May be {@code null}.
*/
public Object paramOrDefault(Type returnType, String name, Object defaultValue) {
Converter converter = getConverter();
String value = getRequest().getParameter(name);
if (!ObjectUtils.isBlank(value)) {
Object convertedValue = converter.convert(returnType, value);
if (convertedValue != null) {
return convertedValue;
}
}
return converter.convert(returnType, defaultValue);
}
/**
* Returns the parameter associated with the given {@code name}
* as an instance of the given {@code returnClass}, or if not found or
* is blank, the given {@code defaultValue}.
*
* @param returnClass Can't be {@code null}.
* @param name Can be {@code null}.
* @param defaultValue Can be {@code null}.
* @return May be {@code null}.
*/
@SuppressWarnings("unchecked")
public <T> T paramOrDefault(Class<T> returnClass, String name, T defaultValue) {
return (T) paramOrDefault((Type) returnClass, name, defaultValue);
}
/**
* Returns the parameter associated with the given {@code name}
* as an instance of the type referenced by the given
* {@code returnTypeReference}, or if not found or is blank,
* the given {@code defaultValue}.
*
* @param returnTypeReference Can't be {@code null}.
* @param name Can be {@code null}.
* @param defaultValue Can be {@code null}.
* @return May be {@code null}.
*/
@SuppressWarnings("unchecked")
public <T> T paramOrDefault(TypeReference<T> returnTypeReference, String name, T defaultValue) {
return (T) paramOrDefault(returnTypeReference.getType(), name, defaultValue);
}
/**
* Returns the parameter associated with the given {@code name}
* as an instance of the given {@code returnType}, or if not found or
* is blank, {@code null}.
*
* @param returnType Can't be {@code null}.
* @param name Can be {@code null}.
* @return May be {@code null}.
*/
public Object param(Type returnType, String name) {
return paramOrDefault(returnType, name, null);
}
/**
* Returns the parameter associated with the given {@code name}
* as an instance of the given {@code returnClass}, or if not found or
* is blank, {@code null}.
*
* @param returnClass Can't be {@code null}.
* @param name Can be {@code null}.
* @return May be {@code null}.
*/
public <T> T param(Class<T> returnClass, String name) {
return paramOrDefault(returnClass, name, null);
}
/**
* Returns the parameter associated with the given {@code name}
* as an instance of the type referenced by the given
* {@code returnTypeReference}, or if not found or is blank,
* {@code null}.
*
* @param returnTypeReference Can't be {@code null}.
* @param name Can be {@code null}.
* @return May be {@code null}.
*/
public <T> T param(TypeReference<T> returnTypeReference, String name) {
return paramOrDefault(returnTypeReference, name, null);
}
/**
* Returns the parameters associated with the given {@code name}
* as instances of the given {@code itemType}.
*
* @param itemType Can't be {@code null}.
* @param name Can be {@code null}.
* @return Never {@code null}. Mutable. Empty list if the parameter
* with the given {@code name} doesn't exist.
*/
public List<Object> params(Type itemType, String name) {
List<Object> convertedValues;
String[] values = getRequest().getParameterValues(name);
if (values == null) {
convertedValues = new ArrayList<Object>(1);
} else {
Converter converter = getConverter();
int length = values.length;
convertedValues = new ArrayList<Object>(length);
for (int i = 0; i < length; ++ i) {
convertedValues.add(converter.convert(itemType, values[i]));
}
}
return convertedValues;
}
/**
* Returns the parameters associated with the given {@code name}
* as instances of the given {@code itemClass}.
*
* @param itemClass Can't be {@code null}.
* @param name Can be {@code null}.
* @return Never {@code null}. Mutable. Empty list if the parameter
* with the given {@code name} doesn't exist.
*/
@SuppressWarnings("unchecked")
public <T> List<T> params(Class<T> itemClass, String name) {
return (List<T>) params((Type) itemClass, name);
}
/**
* Returns the parameters associated with the given {@code name}
* as instances of the type referenced by the given
* {@code itemTypeReference}.
*
* @param itemTypeReference Can't be {@code null}.
* @param name Can be {@code null}.
* @return Never {@code null}. Mutable. Empty list if the parameter
* with the given {@code name} doesn't exist.
*/
@SuppressWarnings("unchecked")
public <T> List<T> params(TypeReference<T> itemTypeReference, String name) {
return (List<T>) params(itemTypeReference.getType(), name);
}
/** @see JspUtils#createId */
public String createId() {
return JspUtils.createId(getRequest());
}
/** @see JspUtils#finish */
public void finish() {
JspUtils.finish(getRequest());
}
/** @see JspUtils#forward */
public void forward(String path, Object... parameters) throws IOException, ServletException {
JspUtils.forward(getRequest(), getResponse(), path, parameters);
}
/** @see JspUtils#getAbsolutePath */
public String absoluteUrl(Object path, Object... parameters) {
String pathString = path == null ? null : path.toString();
return JspUtils.getAbsolutePath(getRequest(), pathString, parameters);
}
/** @see JspUtils#getCookie */
public Cookie getCookie(String name) {
return JspUtils.getCookie(getRequest(), name);
}
/** @see JspUtils#getEmbeddedAbsolutePath */
public String url(Object path, Object... parameters) {
String pathString = path == null ? null : path.toString();
return JspUtils.getEmbeddedAbsolutePath(getServletContext(), getRequest(), pathString, parameters);
}
/** @see JspUtils#getId */
public String getId() {
return JspUtils.getId(getRequest());
}
/** @see JspUtils#getOriginalContextPath */
public String getOriginalContextPath() {
return JspUtils.getOriginalContextPath(getRequest());
}
/** @see JspUtils#getOriginalServletPath */
public String getOriginalServletPath() {
return JspUtils.getOriginalServletPath(getRequest());
}
/** @see JspUtils#getOriginalPathInfo */
public String getOriginalPathInfo() {
return JspUtils.getOriginalPathInfo(getRequest());
}
/** @see JspUtils#getOriginalQueryString */
public String getOriginalQueryString() {
return JspUtils.getOriginalQueryString(getRequest());
}
/** @see JspUtils#includeEmbedded */
public boolean include(String path, Object... attributes) throws IOException, ServletException {
return JspUtils.includeEmbedded(
getServletContext(),
getRequest(),
getResponse(),
getWriter(),
path,
attributes);
}
/** @see JspUtils#isAjaxRequest */
public boolean isAjaxRequest() {
return JspUtils.isAjaxRequest(getRequest());
}
/** @see JspUtils#isFinished */
public boolean isFinished() {
return JspUtils.isFinished(getRequest(), getResponse());
}
/** @see JspUtils#isFormPost */
public boolean isFormPost() {
return JspUtils.isFormPost(getRequest());
}
/** @see JspUtils#isForwarded */
public boolean isForwarded() {
return JspUtils.isForwarded(getRequest());
}
/** @see JspUtils#isIncluded */
public boolean isIncluded() {
return JspUtils.isIncluded(getRequest());
}
/** @see JspUtils#proxy */
public void proxy(Object url, Object... parameters) throws IOException {
JspUtils.proxy(getRequest(), getResponse(), getWriter(), url, parameters);
}
/** @see JspUtils#redirectEmbedded */
public void redirect(Object path, Object... parameters) throws IOException {
JspUtils.redirectEmbedded(getServletContext(), getRequest(), getResponse(), path, parameters);
}
/**
* Returns the original page object (instance of {@link Servlet}
* in a servlet environment).
*
* @return May be {@code null}.
* @deprecated No replacement.
*/
@Deprecated
public Object getPage() {
return this.page;
}
/** @deprecated Use {@link DateUtils#toString} instead. */
@Deprecated
public String dt(Date date, String format) {
return new DateTime(date).toString(format);
}
/** @deprecated No replacement. */
@Deprecated
public String hb(Object input, Object defaultValue) {
return input != null ?
StringUtils.escapeHtmlAndBreak(input.toString()) :
defaultValue.toString();
}
/** @deprecated No replacement. */
@Deprecated
public String hb(Object input) {
return hb(input, "");
}
/** @deprecated Use {@link #paramNamesList} instead. */
@Deprecated
public String[] paramNames(String prefix) {
List<String> names = new ArrayList<String>();
for (
@SuppressWarnings("unchecked")
Enumeration<String> e = getRequest().getParameterNames();
e.hasMoreElements(); ) {
String name = e.nextElement();
if (prefix == null || name.startsWith(prefix)) {
names.add(name);
}
}
return names.toArray(new String[names.size()]);
}
/** @deprecated Use {@link #paramNamesList} instead. */
@Deprecated
public String[] paramNames() {
return paramNames(null);
}
/** @deprecated Use {@link #param} instead. */
@Deprecated
public boolean boolParam(String name) {
return Boolean.parseBoolean(getRequest().getParameter(name));
}
/** @deprecated Use {@link #params} instead. */
@Deprecated
public boolean[] boolParams(String name) {
String[] stringValues = getRequest().getParameterValues(name);
if (stringValues != null) {
int len = stringValues.length;
if (len > 0) {
boolean[] values = new boolean[len];
for (int i = 0; i < len; i ++) {
values[i] = Boolean.parseBoolean(stringValues[i]);
}
return values;
}
}
return new boolean[0];
}
/** @deprecated Use {@link #paramOrDefault} instead. */
@Deprecated
public Date dateParam(String name, Date defaultValue) {
Date value = ObjectUtils.to(Date.class, getRequest().getParameter(name));
return value != null ? value : defaultValue;
}
/** @deprecated Use {@link #param} instead. */
@Deprecated
public Date dateParam(String name) {
return dateParam(name, null);
}
/** @deprecated Use {@link #params} instead. */
@Deprecated
public Date[] dateParams(String name, Date defaultValue) {
String[] stringValues = getRequest().getParameterValues(name);
if (stringValues != null) {
int len = stringValues.length;
if (len > 0) {
Date[] values = new Date[len];
for (int i = 0; i < len; i ++) {
Date value = ObjectUtils.to(Date.class, stringValues[i]);
values[i] = value != null ? value : defaultValue;
}
return values;
}
}
return new Date[0];
}
/** @deprecated Use {@link #params} instead. */
@Deprecated
public Date[] dateParams(String name) {
return dateParams(name, null);
}
/** @deprecated Use {@link #paramOrDefault} instead. */
@Deprecated
public <T extends Enum<T>> T enumParam(Class<T> type, String name, T defaultValue) {
T value = ObjectUtils.to(type, getRequest().getParameter(name));
return value != null ? value : defaultValue;
}
/** @deprecated Use {@link #params} instead. */
@Deprecated
public <T extends Enum<T>> T[] enumParams(Class<T> type, String name, T defaultValue) {
String[] stringValues = getRequest().getParameterValues(name);
int len = stringValues != null ? stringValues.length : 0;
@SuppressWarnings("unchecked")
T[] values = (T[]) Array.newInstance(type, len);
for (int i = 0; i < len; i ++) {
T value = ObjectUtils.to(type, stringValues[i]);
values[i] = value != null ? value : defaultValue;
}
return values;
}
/** @deprecated Use {@link #paramOrDefault} instead. */
@Deprecated
public Double doubleParam(String name, Double defaultValue) {
Double value = ObjectUtils.to(Double.class, getRequest().getParameter(name));
return value != null ? value : defaultValue;
}
/** @deprecated Use {@link #param} instead. */
@Deprecated
public Double doubleParam(String name) {
return doubleParam(name, 0.0);
}
/** @deprecated Use {@link #params} instead. */
@Deprecated
public Double[] doubleParams(String name, Double defaultValue) {
String[] stringValues = getRequest().getParameterValues(name);
if (stringValues != null) {
int len = stringValues.length;
if (len > 0) {
Double[] values = new Double[len];
for (int i = 0; i < len; i ++) {
Double value = ObjectUtils.to(Double.class, stringValues[i]);
values[i] = value != null ? value : defaultValue;
}
return values;
}
}
return new Double[0];
}
/** @deprecated Use {@link #params} instead. */
@Deprecated
public Double[] doubleParams(String name) {
return doubleParams(name, 0.0);
}
/** @deprecated Use {@link #paramOrDefault} instead. */
@Deprecated
public Float floatParam(String name, Float defaultValue) {
Float value = ObjectUtils.to(Float.class, getRequest().getParameter(name));
return value != null ? value : defaultValue;
}
/** @deprecated Use {@link #param} instead. */
@Deprecated
public Float floatParam(String name) {
return floatParam(name, 0.0f);
}
/** @deprecated Use {@link #params} instead. */
@Deprecated
public Float[] floatParams(String name, Float defaultValue) {
String[] stringValues = getRequest().getParameterValues(name);
if (stringValues != null) {
int len = stringValues.length;
if (len > 0) {
Float[] values = new Float[len];
for (int i = 0; i < len; i ++) {
Float value = ObjectUtils.to(Float.class, stringValues[i]);
values[i] = value != null ? value : defaultValue;
}
return values;
}
}
return new Float[0];
}
/** @deprecated Use {@link #params} instead. */
@Deprecated
public Float[] floatParams(String name) {
return floatParams(name, 0.0f);
}
/** @deprecated Use {@link #paramOrDefault} instead. */
@Deprecated
public Integer intParam(String name, Integer defaultValue) {
Integer value = ObjectUtils.to(Integer.class, getRequest().getParameter(name));
return value != null ? value : defaultValue;
}
/** @deprecated Use {@link #param} instead. */
@Deprecated
public Integer intParam(String name) {
return intParam(name, 0);
}
/** @deprecated Use {@link #params} instead. */
@Deprecated
public Integer[] intParams(String name, Integer defaultValue) {
String[] stringValues = getRequest().getParameterValues(name);
if (stringValues != null) {
int len = stringValues.length;
if (len > 0) {
Integer[] values = new Integer[len];
for (int i = 0; i < len; i ++) {
Integer value = ObjectUtils.to(Integer.class, stringValues[i]);
values[i] = value != null ? value : defaultValue;
}
return values;
}
}
return new Integer[0];
}
/** @deprecated Use {@link #params} instead. */
@Deprecated
public Integer[] intParams(String name) {
return intParams(name, 0);
}
/** @deprecated Use {@link #paramOrDefault} instead. */
@Deprecated
public Long longParam(String name, Long defaultValue) {
Long value = ObjectUtils.to(Long.class, getRequest().getParameter(name));
return value != null ? value : defaultValue;
}
/** @deprecated Use {@link #param} instead. */
@Deprecated
public Long longParam(String name) {
return longParam(name, 0L);
}
/** @deprecated Use {@link #params} instead. */
@Deprecated
public Long[] longParams(String name, Long defaultValue) {
String[] stringValues = getRequest().getParameterValues(name);
if (stringValues != null) {
int len = stringValues.length;
if (len > 0) {
Long[] values = new Long[len];
for (int i = 0; i < len; i ++) {
Long value = ObjectUtils.to(Long.class, stringValues[i]);
values[i] = value != null ? value : defaultValue;
}
return values;
}
}
return new Long[0];
}
/** @deprecated Use {@link #params} instead. */
@Deprecated
public Long[] longParams(String name) {
return longParams(name, 0L);
}
/** @deprecated Use {@link #paramOrDefault} instead. */
@Deprecated
public String param(String name, String defaultValue) {
String value = getRequest().getParameter(name);
return value == null || value.length() == 0 ? defaultValue : value;
}
/** @deprecated Use {@link #param} instead. */
@Deprecated
public String param(String name) {
return param(name, null);
}
/** @deprecated Use {@link #params} instead. */
@Deprecated
public String[] params(String name, String defaultValue) {
String[] values = getRequest().getParameterValues(name);
if (values != null) {
int len = values.length;
if (len > 0) {
for (int i = 0; i < len; i ++) {
String value = values[i];
values[i] = value == null
|| value.length() == 0 ? defaultValue : value;
}
return values;
}
}
return new String[0];
}
/** @deprecated Use {@link #params} instead. */
@Deprecated
public String[] params(String name) {
return params(name, null);
}
/** @deprecated Use {@link #paramOrDefault} instead. */
@Deprecated
public UUID uuidParam(String name, UUID defaultValue) {
UUID uuid = ObjectUtils.to(UUID.class, getRequest().getParameter(name));
return uuid != null ? uuid : defaultValue;
}
/** @deprecated Use {@link #param} instead. */
@Deprecated
public UUID uuidParam(String name) {
return uuidParam(name, null);
}
/** @deprecated Use {@link #params} instead. */
@Deprecated
public UUID[] uuidParams(String name, UUID defaultValue) {
String[] stringValues = getRequest().getParameterValues(name);
if (stringValues != null) {
int len = stringValues.length;
if (len > 0) {
UUID[] values = new UUID[len];
for (int i = 0; i < len; i ++) {
UUID value = ObjectUtils.to(UUID.class, stringValues[i]);
values[i] = value != null ? value : defaultValue;
}
return values;
}
}
return new UUID[0];
}
/** @deprecated Use {@link #params} instead. */
@Deprecated
public UUID[] uuidParams(String name) {
return uuidParams(name, null);
}
}
|
package VASSAL.chat;
import java.awt.Component;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.IOException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.UnknownHostException;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;
import javax.swing.AbstractAction;
import javax.swing.DefaultListCellRenderer;
import javax.swing.DefaultListModel;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import net.miginfocom.swing.MigLayout;
import VASSAL.build.GameModule;
import VASSAL.chat.jabber.JabberClient;
import VASSAL.chat.jabber.JabberClientFactory;
import VASSAL.chat.node.NodeClientFactory;
import VASSAL.chat.peer2peer.P2PClientFactory;
import VASSAL.configure.StringConfigurer;
import VASSAL.i18n.Resources;
import VASSAL.preferences.Prefs;
import VASSAL.tools.PropertiesEncoder;
import VASSAL.tools.SequenceEncoder;
import VASSAL.tools.icon.IconFactory;
import VASSAL.tools.icon.IconFamily;
import VASSAL.tools.swing.Dialogs;
import VASSAL.tools.swing.SwingUtils;
public class ServerAddressBook {
public static final String CURRENT_SERVER = "currentServer"; //$NON-NLS-1$
protected static final String ADDRESS_PREF = "ServerAddressBook"; //$NON-NLS-1$
protected static final String LEGACY_TYPE = NodeClientFactory.NODE_TYPE;
protected static final String DYNAMIC_TYPE = DynamicClientFactory.DYNAMIC_TYPE;
protected static final String JABBER_TYPE = JabberClientFactory.JABBER_SERVER_TYPE;
protected static final String P2P_TYPE = P2PClientFactory.P2P_TYPE;
protected static final String P2P_MODE_KEY = P2PClientFactory.P2P_MODE_KEY;
protected static final String P2P_SERVER_MODE = P2PClientFactory.P2P_SERVER_MODE;
@Deprecated(since = "2020-08-16", forRemoval = true)
protected static final String P2P_CLIENT_MODE = P2PClientFactory.P2P_CLIENT_MODE;
// protected static final String PRIVATE_TYPE = PrivateClientFactory.PRIVATE_TYPE;
protected static final String TYPE_KEY = ChatServerFactory.TYPE_KEY;
protected static final String DESCRIPTION_KEY = "description"; //$NON-NLS-1$
protected final int LEAF_ICON_SIZE = IconFamily.SMALL;
protected final int CONTROLS_ICON_SIZE = IconFamily.XSMALL;
private boolean frozen;
private JComponent controls;
private StringConfigurer addressConfig;
private JList<AddressBookEntry> myList;
private DefaultListModel<AddressBookEntry> addressBook;
private AddressBookEntry currentEntry;
private boolean enabled = true;
private PropertyChangeSupport changeSupport = new PropertyChangeSupport(this);
private static ServerAddressBook instance;
private static String localIPAddress;
private static String externalIPAddress;
private JButton addButton;
private JButton removeButton;
private JButton editButton;
private JButton setButton;
public static ServerAddressBook getInstance() {
return instance;
}
public static void editCurrentServer(boolean connected) {
instance.editCurrent(connected);
}
public static void changeServerPopup(JComponent source) {
instance.showPopup(source);
}
public static String getLocalAddress() {
if (localIPAddress == null) {
try {
localIPAddress = getLocalHostLANAddress().getHostAddress();
}
catch (UnknownHostException e) {
localIPAddress = "?"; //$NON-NLS-1$
}
}
return localIPAddress;
}
public static String getExternalAddress() {
return getExternalAddress("?"); //$NON-NLS-1$
}
public static String getExternalAddress(String dflt) {
if (externalIPAddress == null) {
externalIPAddress = dflt;
try {
externalIPAddress = discoverMyIpAddressFromRemote();
}
catch (IOException e) {
externalIPAddress = "?"; //$NON-NLS-1$
}
}
return externalIPAddress;
}
private static String discoverMyIpAddressFromRemote() throws IOException {
String theIp = null;
HttpRequestWrapper r = new HttpRequestWrapper("http:
List<String> l = r.doGet(null);
if (!l.isEmpty()) {
theIp = l.get(0);
}
else {
throw new IOException(Resources.getString("Server.empty_response")); //$NON-NLS-1$
}
return theIp;
}
private static InetAddress getLocalHostLANAddress() throws UnknownHostException {
try {
InetAddress candidateAddress = null;
// Iterate all NICs (network interface cards)...
for (Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces(); ifaces.hasMoreElements();) {
NetworkInterface iface = ifaces.nextElement();
// Iterate all IP addresses assigned to each card...
for (Enumeration<InetAddress> inetAddrs = iface.getInetAddresses(); inetAddrs.hasMoreElements();) {
InetAddress inetAddr = inetAddrs.nextElement();
if (!inetAddr.isLoopbackAddress()) {
if (inetAddr.isSiteLocalAddress()) {
// Found non-loopback site-local address. Return it immediately...
return inetAddr;
}
else if (candidateAddress == null) {
// Found non-loopback address, but not necessarily site-local.
// Store it as a candidate to be returned if site-local address is not subsequently found...
candidateAddress = inetAddr;
// Note that we don't repeatedly assign non-loopback non-site-local addresses as candidates,
// only the first. For subsequent iterations, candidate will be non-null.
}
}
}
}
if (candidateAddress != null) {
// We did not find a site-local address, but we found some other non-loopback address.
// Server might have a non-site-local address assigned to its NIC (or it might be running
// IPv6 which deprecates the "site-local" concept).
// Return this non-loopback candidate address...
return candidateAddress;
}
// At this point, we did not find a non-loopback address.
// Fall back to returning whatever InetAddress.getLocalHost() returns...
InetAddress jdkSuppliedAddress = InetAddress.getLocalHost();
if (jdkSuppliedAddress == null) {
throw new UnknownHostException("The JDK InetAddress.getLocalHost() method unexpectedly returned null.");
}
return jdkSuppliedAddress;
}
catch (Exception e) {
UnknownHostException unknownHostException = new UnknownHostException("Failed to determine LAN address: " + e);
unknownHostException.initCause(e);
throw unknownHostException;
}
}
public ServerAddressBook() {
instance = this;
}
public JComponent getControls() {
if (controls == null) {
controls = new JPanel(new MigLayout());
addressConfig = new StringConfigurer(ADDRESS_PREF, null, ""); //$NON-NLS-1$
Prefs.getGlobalPrefs().addOption(null, addressConfig);
addressBook = new DefaultListModel<AddressBookEntry>();
loadAddressBook();
myList = new JList<>(addressBook);
myList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
myList.setCellRenderer(new MyRenderer());
myList.addListSelectionListener(e -> updateButtonVisibility());
myList.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (editButton.isEnabled() && e.getClickCount() == 2
&& SwingUtils.isMainMouseButtonDown(e)) {
int index = myList.locationToIndex(e.getPoint());
editServer(index);
}
}
});
final JScrollPane scroll = new JScrollPane(myList);
myList.repaint();
controls.add(scroll, "grow, push, w 500, h 400, wrap, span 4"); //$NON-NLS-1$
setButton = new JButton(Resources.getString("ServerAddressBook.set_current")); //$NON-NLS-1$
setButton.setToolTipText(Resources.getString("ServerAddressBook.set_selected_server")); //$NON-NLS-1$
setButton.addActionListener(e -> setCurrentServer(myList.getSelectedIndex()));
addButton = new JButton(Resources.getString(Resources.ADD));
addButton.setToolTipText(Resources.getString("ServerAddressBook.add_jabber_server")); //$NON-NLS-1$
addButton.addActionListener(e -> addServer());
removeButton = new JButton(Resources.getString(Resources.REMOVE));
removeButton.setToolTipText(Resources.getString("ServerAddressBook.remove_selected_server")); //$NON-NLS-1$
removeButton.addActionListener(e -> removeServer(myList.getSelectedIndex()));
editButton = new JButton(Resources.getString(Resources.EDIT));
editButton.setToolTipText(Resources.getString("ServerAddressBook.edit_server")); //$NON-NLS-1$
editButton.addActionListener(e -> editServer(myList.getSelectedIndex()));
controls.add(addButton, "grow, push"); //$NON-NLS-1$
controls.add(editButton, "grow, push"); //$NON-NLS-1$
controls.add(removeButton, "grow, push"); //$NON-NLS-1$
controls.add(setButton, "grow, push"); //$NON-NLS-1$
updateButtonVisibility();
}
return controls;
}
public void setEnabled(boolean b) {
enabled = b;
updateButtonVisibility();
}
public boolean isEnabled() {
return enabled;
}
public void setFrozen(boolean b) {
frozen = b;
}
private void updateButtonVisibility() {
final int index = myList.getSelectedIndex();
if (index >= 0) {
final AddressBookEntry e = addressBook.get(index);
editButton.setEnabled(e.isEditable() && (isEnabled() || !e.isCurrent()));
removeButton.setEnabled(e.isRemovable() && !e.isCurrent());
setButton.setEnabled(isEnabled() && !e.isCurrent());
}
else {
editButton.setEnabled(false);
removeButton.setEnabled(false);
setButton.setEnabled(false);
}
}
public void setCurrentServer(Properties p) {
// Check for Basic Types, regardless of other properties
int index = 0;
final String type = p.getProperty(TYPE_KEY);
final String dtype = p.getProperty(DYNAMIC_TYPE);
final String ctype = p.getProperty(P2P_MODE_KEY);
for (Enumeration<AddressBookEntry> e = addressBook.elements(); e.hasMoreElements();) {
final AddressBookEntry entry = e.nextElement();
final Properties ep = entry.getProperties();
if (ep.equals(p)) {
setCurrentServer(index);
return;
}
else if (DYNAMIC_TYPE.equals(type) && DYNAMIC_TYPE.equals(ep.getProperty(TYPE_KEY))
&& ep.getProperty(DYNAMIC_TYPE).equals(dtype)) {
setCurrentServer(index);
return;
}
else if (P2P_TYPE.equals(type) && P2P_TYPE.equals(ep.getProperty(TYPE_KEY))
&& ep.getProperty(P2P_MODE_KEY).equals(ctype)) {
setCurrentServer(index);
}
index++;
}
// Some Server we don't know about, add a server entry
final AddressBookEntry newEntry = buildEntry(p);
if (newEntry != null) {
addressBook.addElement(newEntry);
setCurrentServer(addressBook.indexOf(newEntry));
}
saveAddressBook();
}
private void setCurrentServer(AddressBookEntry e) {
setCurrentServer(addressBook.indexOf(e));
}
private void setCurrentServer(int index) {
final AddressBookEntry e = addressBook.get(index);
if (currentEntry != null) {
currentEntry.setCurrent(false);
}
final Properties oldProps = currentEntry == null ? null : currentEntry.getProperties();
currentEntry = e;
currentEntry.setCurrent(true);
if (!frozen) {
changeSupport.firePropertyChange(CURRENT_SERVER, oldProps, e.getProperties());
}
updateButtonVisibility();
myList.repaint();
}
protected Properties getCurrentServerProperties() {
return currentEntry.getProperties();
}
public void showPopup(JComponent source) {
final JPopupMenu popup = new JPopupMenu();
for (Enumeration<AddressBookEntry> e = addressBook.elements(); e.hasMoreElements();) {
final AddressBookEntry entry = e.nextElement();
final JMenuItem item = new JMenuItem(entry.toString());
final AbstractAction action = new MenuAction(entry);
item.setAction(action);
item.setIcon(entry.getIcon(IconFamily.SMALL));
popup.add(item);
}
popup.show(source, 0, 0);
}
private class MenuAction extends AbstractAction {
private static final long serialVersionUID = 1L;
private AddressBookEntry entry;
public MenuAction (AddressBookEntry e) {
super(e.toString());
entry = e;
}
@Override
public void actionPerformed(ActionEvent e) {
ServerAddressBook.getInstance().setCurrentServer(entry);
}
}
public void addPropertyChangeListener(PropertyChangeListener l) {
changeSupport.addPropertyChangeListener(l);
}
public void removePropertyChangeListener(PropertyChangeListener l) {
changeSupport.removePropertyChangeListener(l);
}
public Icon getCurrentIcon() {
return currentEntry.getIcon(CONTROLS_ICON_SIZE);
}
public String getCurrentDescription() {
return currentEntry.toString();
}
private void editCurrent(boolean connected) {
if (currentEntry != null) {
editServer(addressBook.indexOf(currentEntry), connected);
}
}
private void editServer(int index) {
editServer(index, true);
}
private void editServer(int index, boolean enabled) {
final AddressBookEntry e = addressBook.get(index);
final boolean current = e.equals(currentEntry);
final Properties oldProps = e.getProperties();
if (e.edit(enabled) && current) {
changeSupport.firePropertyChange(CURRENT_SERVER, oldProps, e.getProperties());
}
}
private void removeServer(int index) {
final AddressBookEntry e = addressBook.get(index);
final int i = JOptionPane.showConfirmDialog(
GameModule.getGameModule().getPlayerWindow(),
Resources.getString("ServerAddressBook.remove_server", e.getDescription()) //$NON-NLS-1$
);
if (i == 0) {
addressBook.remove(index);
myList.setSelectedIndex(-1);
myList.repaint();
updateButtonVisibility();
saveAddressBook();
}
}
private void addServer() {
final JPopupMenu popup = new JPopupMenu();
final JMenuItem p2pItem = new JMenuItem(Resources.getString("ServerAddressBook.peer_server"));
p2pItem.addActionListener(e -> addEntry(new PeerServerEntry()));
final JMenuItem jabItem = new JMenuItem(Resources.getString("ServerAddressBook.jabber_server"));
jabItem.addActionListener(e -> addEntry(new JabberEntry()));
// final JMenuItem privateItem = new JMenuItem(Resources.getString("ServerAddressBook.private_server"));
// privateItem.addActionListener(new ActionListener() {
// public void actionPerformed(ActionEvent arg0) {
// addEntry(new PrivateEntry());
popup.add(p2pItem);
// popup.add(privateItem);
popup.add(jabItem);
popup.show(addButton, 0, 0);
}
private void addEntry(AddressBookEntry e) {
if (e.edit()) {
addressBook.addElement(e);
saveAddressBook();
}
}
/**
* Set up the default server
* @return
*/
public Properties getDefaultServerProperties() {
// return (new VassalJabberEntry()).getProperties();
return (new LegacyEntry()).getProperties();
}
private void loadAddressBook() {
decodeAddressBook(addressConfig.getValueString());
final DefaultListModel<AddressBookEntry> newAddressBook = new DefaultListModel<>();
for (Enumeration<AddressBookEntry> e = addressBook.elements(); e.hasMoreElements();) {
final AddressBookEntry entry = e.nextElement();
if (entry instanceof LegacyEntry) {
newAddressBook.add(0, entry);
}
else {
newAddressBook.addElement(entry);
}
}
addressBook = newAddressBook;
// Ensure that the Address Book has the basic
// servers in it.
boolean legacy = false;
boolean jabber = false;
boolean peerServer = false;
boolean updated = false;
for (Enumeration<AddressBookEntry> e = addressBook.elements(); e.hasMoreElements();) {
final AddressBookEntry entry = e.nextElement();
if (entry instanceof LegacyEntry) {
legacy = true;
}
else if (entry instanceof VassalJabberEntry) {
jabber = true;
}
else if (entry instanceof PeerServerEntry) {
peerServer = true;
}
}
if (!jabber) {
final AddressBookEntry entry = new VassalJabberEntry();
entry.setCurrent(true);
currentEntry = entry;
addressBook.addElement(entry);
updated = true;
}
if (!legacy) {
addressBook.addElement(new LegacyEntry());
updated = true;
}
if (!peerServer) {
addressBook.addElement(new PeerServerEntry());
updated = true;
}
if (updated) {
saveAddressBook();
}
}
private void saveAddressBook() {
addressConfig.setValue(encodeAddressBook());
if (myList != null) {
myList.repaint();
}
}
private String encodeAddressBook() {
SequenceEncoder se = new SequenceEncoder(',');
for (Enumeration<AddressBookEntry> e = addressBook.elements(); e.hasMoreElements();) {
final AddressBookEntry entry = e.nextElement();
if (entry != null) {
se.append(entry.encode());
}
}
return se.getValue();
}
private void decodeAddressBook(String s) {
addressBook.clear();
for (SequenceEncoder.Decoder sd = new SequenceEncoder.Decoder(s, ','); sd.hasMoreTokens();) {
final String token = sd.nextToken(""); //$NON-NLS-1$
if (token.length() > 0) {
final AddressBookEntry entry = buildEntry(token);
if (entry != null) {
addressBook.addElement(buildEntry(token));
}
}
}
}
/**
* Return an appropriately typed Entry, depending on the Server Properties
* passed
*
* @param s
* Encoded Server Properties
* @return Entry
*/
private AddressBookEntry buildEntry(String s) {
Properties newProperties = new Properties();
try {
newProperties = new PropertiesEncoder(s).getProperties();
}
catch (IOException e) {
// FIXME: Error Message?
}
return buildEntry(newProperties);
}
private AddressBookEntry buildEntry(Properties newProperties) {
final String type = newProperties.getProperty(TYPE_KEY);
if (JABBER_TYPE.equals(type)) {
return new JabberEntry(newProperties);
}
else if (DYNAMIC_TYPE.equals(type)) {
final String dtype = newProperties.getProperty(DYNAMIC_TYPE);
if (JABBER_TYPE.equals(dtype)) {
return new VassalJabberEntry(newProperties);
}
else if (LEGACY_TYPE.equals(dtype)) {
return new LegacyEntry(newProperties);
}
}
else if (P2P_TYPE.equals(type)) {
final String ctype = newProperties.getProperty(P2P_MODE_KEY);
if (P2P_SERVER_MODE.equals(ctype)) {
return new PeerServerEntry(newProperties);
}
}
return null;
}
/**
* Base class for an Address Book Entry
*
*/
private abstract class AddressBookEntry implements Comparable<AddressBookEntry> {
protected Properties properties = new Properties();
protected boolean current;
protected AddressBookEntry() {
this(new Properties());
}
protected AddressBookEntry(Properties props) {
properties = props;
}
protected String getDescription() {
return getProperty(DESCRIPTION_KEY);
}
protected void setDescription(String desc) {
properties.setProperty(DESCRIPTION_KEY, desc);
}
public String getProperty(String key) {
return properties.getProperty(key);
}
public void setProperty(String key, String value) {
properties.setProperty(key, value);
}
protected boolean isRemovable() {
return true;
}
protected boolean isEditable() {
return true;
}
protected abstract String getIconName();
protected Icon getIcon(int size) {
return IconFactory.getIcon(getIconName(), size);
}
public String getType() {
return properties.getProperty(TYPE_KEY);
}
public void setType(String t) {
properties.setProperty(TYPE_KEY, t);
}
public Properties getProperties() {
return properties;
}
public void setProperties(Properties p) {
properties = p;
}
public String encode() {
return new PropertiesEncoder(properties).getStringValue();
}
@Override
public int compareTo(AddressBookEntry target) {
if (getType().equals(target.getType())) {
return getDescription().compareTo(target.getDescription());
}
return getType().compareTo(target.getType());
}
public boolean isCurrent() {
return current;
}
public void setCurrent(boolean b) {
current = b;
}
protected boolean isDescriptionEditable() {
return true;
}
public boolean edit() {
return edit(true);
}
public boolean edit(boolean enabled) {
if (isEditable()) {
final ServerConfig config = getEditor(getProperties(), enabled);
final Integer result = (Integer) Dialogs.showDialog(null,
Resources.getString("ServerAddressBook.edit_server_configuration"), //$NON-NLS-1$
config.getControls(), JOptionPane.PLAIN_MESSAGE, null, JOptionPane.OK_CANCEL_OPTION,
null, null, null, null);
if (result != null && result == 0) {
if (enabled) {
setProperties(config.getProperties());
saveAddressBook();
}
return true;
}
}
return false;
}
protected abstract void setAdditionalProperties(Properties props);
protected abstract void getAdditionalProperties(Properties props);
protected abstract void addAdditionalControls(JComponent c, boolean enabled);
public ServerConfig getEditor(Properties p, boolean enabled) {
return new ServerConfig(p, this, enabled);
}
class ServerConfig {
protected JComponent configControls;
protected JTextField description = new JTextField();
protected AddressBookEntry entry;
boolean enabled;
public ServerConfig() {
}
public ServerConfig(Properties props, AddressBookEntry entry, boolean enabled) {
this();
this.entry = entry;
this.enabled = enabled;
description.setText(props.getProperty(DESCRIPTION_KEY));
setAdditionalProperties(props);
}
protected boolean isEnabled() {
return enabled;
}
public JComponent getControls() {
if (configControls == null) {
configControls = new JPanel();
configControls.setLayout(new MigLayout("", "[align right]rel[]", "")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
configControls.add(
new JLabel(IconFactory.getIcon(entry.getIconName(), IconFamily.LARGE)),
"span 2, align center, wrap"); //$NON-NLS-1$
configControls.add(new JLabel(Resources.getString("Editor.description_label"))); //$NON-NLS-1$
configControls.add(description, "wrap, grow, push"); //$NON-NLS-1$
entry.addAdditionalControls(configControls, enabled);
description.setEditable(isDescriptionEditable() && isEnabled());
}
return configControls;
}
public Properties getProperties() {
final Properties props = new Properties();
props.setProperty(DESCRIPTION_KEY, description.getText());
getAdditionalProperties(props);
return props;
}
}
}
/**
* Address Book entry for a user defined Jabber Server
*
*/
private class JabberEntry extends AddressBookEntry {
private JTextField jabberHost = new JTextField();
private JTextField jabberPort = new JTextField();
private JTextField jabberUser = new JTextField();
private JTextField jabberPw = new JTextField();
private JButton testButton;
public JabberEntry() {
this(new Properties());
setType(JABBER_TYPE);
setDescription(""); //$NON-NLS-1$
setProperty(JabberClientFactory.JABBER_PORT, "5222"); //$NON-NLS-1$
}
public JabberEntry(Properties props) {
super(props);
}
public String toString() {
return Resources.getString("ServerAddressBook.jabber_server") + " " + getDescription() + " [" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ getProperty(JabberClientFactory.JABBER_HOST) + ":" //$NON-NLS-1$
+ getProperty(JabberClientFactory.JABBER_PORT) + " " //$NON-NLS-1$
+ getProperty(JabberClientFactory.JABBER_LOGIN) + "/" //$NON-NLS-1$
+ getProperty(JabberClientFactory.JABBER_PWD) + "]"; //$NON-NLS-1$
}
@Override
protected String getIconName() {
return "jabber"; //$NON-NLS-1$
}
@Override
protected boolean isDescriptionEditable() {
return true;
}
@Override
protected void setAdditionalProperties(Properties props) {
jabberHost.setText(props.getProperty(JabberClientFactory.JABBER_HOST));
jabberPort.setText(props.getProperty(JabberClientFactory.JABBER_PORT));
jabberUser.setText(props.getProperty(JabberClientFactory.JABBER_LOGIN));
jabberPw.setText(props.getProperty(JabberClientFactory.JABBER_PWD));
}
@Override
protected void getAdditionalProperties(Properties props) {
props.setProperty(JabberClientFactory.JABBER_HOST, jabberHost.getText());
props.setProperty(JabberClientFactory.JABBER_PORT, jabberPort.getText());
props.setProperty(JabberClientFactory.JABBER_LOGIN, jabberUser.getText());
props.setProperty(JabberClientFactory.JABBER_PWD, jabberPw.getText());
props.setProperty(TYPE_KEY, JabberClientFactory.JABBER_SERVER_TYPE);
}
@Override
protected void addAdditionalControls(JComponent c, boolean enabled) {
jabberHost.setEditable(enabled);
jabberPort.setEditable(enabled);
jabberUser.setEditable(enabled);
jabberPw.setEditable(enabled);
c.add(new JLabel(Resources.getString("ServerAddressBook.jabber_host"))); //$NON-NLS-1$
c.add(jabberHost, "wrap, grow, push"); //$NON-NLS-1$
c.add(new JLabel(Resources.getString("ServerAddressBook.port"))); //$NON-NLS-1$
c.add(jabberPort, "wrap, grow, push"); //$NON-NLS-1$
c.add(new JLabel(Resources.getString("ServerAddressBook.user_name"))); //$NON-NLS-1$
c.add(jabberUser, "wrap, grow, push"); //$NON-NLS-1$
c.add(new JLabel(Resources.getString("ServerAddressBook.password"))); //$NON-NLS-1$
c.add(jabberPw, "wrap, grow, push"); //$NON-NLS-1$
testButton = new JButton(Resources.getString("ServerAddressBook.test_connection")); //$NON-NLS-1$
testButton.addActionListener(e -> test());
c.add(testButton, "span 2, align center, wrap"); //$NON-NLS-1$
}
protected void test() {
final JTextArea result = new JTextArea(10, 30);
result.setText(JabberClient.testConnection(jabberHost.getText(), jabberPort.getText(),
jabberUser.getText(), jabberPw.getText()));
try {
Dialogs.showDialog(null,
Resources.getString("ServerAddressBook.connection_test"), //$NON-NLS-1$
result, JOptionPane.INFORMATION_MESSAGE, null, JOptionPane.OK_CANCEL_OPTION, null, null,
null, null);
}
catch (IllegalStateException ex) {
ex.printStackTrace();
}
}
}
/**
* Address Book entry for the VASSAL Jabber server
*
*/
private class VassalJabberEntry extends AddressBookEntry {
protected JTextField jabberUser = new JTextField();
protected JTextField jabberPw = new JTextField();
public VassalJabberEntry() {
this(new Properties());
setDescription("VASSAL" + Resources.getString("ServerAddressBook.jabber_server")); //$NON-NLS-1$ //$NON-NLS-2$
setType(DYNAMIC_TYPE);
setProperty(DYNAMIC_TYPE, JabberClientFactory.JABBER_SERVER_TYPE);
setProperty(JabberClientFactory.JABBER_LOGIN, ""); //$NON-NLS-1$
setProperty(JabberClientFactory.JABBER_PWD, ""); //$NON-NLS-1$
}
public VassalJabberEntry(Properties props) {
super(props);
}
public String toString() {
String details;
final String login = getProperty(JabberClientFactory.JABBER_LOGIN);
final String pw = getProperty(JabberClientFactory.JABBER_PWD);
if (login == null || login.isEmpty() || pw == null || pw.isEmpty()) {
details = Resources.getString("ServerAddressBook.login_details_required"); //$NON-NLS-1$
}
else {
details = getProperty(JabberClientFactory.JABBER_LOGIN) + "/" //$NON-NLS-1$
+ getProperty(JabberClientFactory.JABBER_PWD);
}
return getDescription() + " [" + details + "]"; //$NON-NLS-1$ //$NON-NLS-2$
}
@Override
protected boolean isRemovable() {
return false;
}
@Override
protected boolean isDescriptionEditable() {
return false;
}
@Override
protected String getIconName() {
return "VASSAL-jabber"; //$NON-NLS-1$
}
@Override
protected void setAdditionalProperties(Properties props) {
jabberUser.setText(props.getProperty(JabberClientFactory.JABBER_LOGIN));
jabberPw.setText(props.getProperty(JabberClientFactory.JABBER_PWD));
setType(DYNAMIC_TYPE);
setProperty(DYNAMIC_TYPE, JABBER_TYPE);
}
@Override
protected void getAdditionalProperties(Properties props) {
props.setProperty(JabberClientFactory.JABBER_LOGIN, jabberUser.getText());
props.setProperty(JabberClientFactory.JABBER_PWD, jabberPw.getText());
props.setProperty(TYPE_KEY, DYNAMIC_TYPE);
props.setProperty(DYNAMIC_TYPE, JABBER_TYPE);
}
@Override
protected void addAdditionalControls(JComponent c, boolean enabled) {
jabberUser.setEditable(enabled);
jabberPw.setEditable(enabled);
c.add(new JLabel(Resources.getString("ServerAddressBook.user_name"))); //$NON-NLS-1$
c.add(jabberUser, "wrap, grow, push"); //$NON-NLS-1$
c.add(new JLabel(Resources.getString("ServerAddressBook.password"))); //$NON-NLS-1$
c.add(jabberPw, "wrap, grow, push"); //$NON-NLS-1$
}
}
/**
* Address Book entry for the VASSAL legacy server
*
*/
private class LegacyEntry extends AddressBookEntry {
public LegacyEntry() {
this(new Properties());
setDescription(Resources.getString("ServerAddressBook.legacy_server")); //$NON-NLS-1$
setType(DYNAMIC_TYPE);
setProperty(DynamicClientFactory.DYNAMIC_TYPE, NodeClientFactory.NODE_TYPE);
}
public LegacyEntry(Properties props) {
super(props);
}
public String toString() {
return getDescription();
}
@Override
protected String getIconName() {
return "VASSAL"; //$NON-NLS-1$
}
@Override
protected boolean isRemovable() {
return false;
}
@Override
protected boolean isEditable() {
return false;
}
@Override
protected boolean isDescriptionEditable() {
return false;
}
@Override
protected void addAdditionalControls(JComponent c, boolean enabled) {
}
@Override
protected void getAdditionalProperties(Properties props) {
}
@Override
protected void setAdditionalProperties(Properties props) {
}
}
/**
* Address Book entry for a Private VASSAL server
*/
/**
* Address Book Entry for a Peer to Peer connection
*
*/
private class PeerServerEntry extends AddressBookEntry {
private JTextField listenPort = new JTextField();
private JTextField serverPw = new JTextField();
public PeerServerEntry() {
super();
setDescription(Resources.getString("ServerAddressBook.peer_server")); //$NON-NLS-1$
setType(P2P_TYPE);
setProperty(P2P_MODE_KEY, P2P_SERVER_MODE);
setProperty(P2PClientFactory.P2P_LISTEN_PORT, "5050"); //$NON-NLS-1$
setProperty(P2PClientFactory.P2P_SERVER_PW, "xyzzy"); //$NON-NLS-1$
}
public PeerServerEntry(Properties props) {
super(props);
}
public String toString() {
return Resources.getString("ServerAddressBook.peer_server") + " [" + getProperty(DESCRIPTION_KEY) + "]";
}
@Override
public boolean isRemovable() {
return true;
}
@Override
protected boolean isDescriptionEditable() {
return true;
}
@Override
protected String getIconName() {
return "network-server"; //$NON-NLS-1$
}
@Override
protected void setAdditionalProperties(Properties p) {
setType(P2P_TYPE);
setProperty(P2P_MODE_KEY, P2P_SERVER_MODE);
listenPort.setText(p.getProperty(P2PClientFactory.P2P_LISTEN_PORT));
serverPw.setText(p.getProperty(P2PClientFactory.P2P_SERVER_PW));
}
@Override
protected void getAdditionalProperties(Properties props) {
props.setProperty(TYPE_KEY, P2P_TYPE);
props.setProperty(P2P_MODE_KEY, P2P_SERVER_MODE);
props.setProperty(P2PClientFactory.P2P_LISTEN_PORT, listenPort.getText());
props.setProperty(P2PClientFactory.P2P_SERVER_PW, serverPw.getText());
}
@Override
protected void addAdditionalControls(JComponent c, boolean enabled) {
listenPort.setEditable(enabled);
c.add(new JLabel(Resources.getString("ServerAddressBook.listen_port"))); //$NON-NLS-1$
c.add(listenPort, "wrap, growx, push"); //$NON-NLS-1$
serverPw.setEditable(enabled);
c.add(new JLabel(Resources.getString("ServerAddressBook.server_password"))); //$NON-NLS-1$
c.add(serverPw, "wrap, growx, push"); //$NON-NLS-1$
c.add(new JLabel(Resources.getString("Peer2Peer.internet_address"))); //$NON-NLS-1$
final JTextField externalIP = new JTextField(getExternalAddress());
externalIP.setEditable(false);
c.add(externalIP, "wrap, growx, push"); //$NON-NLS-1$
if (!getLocalAddress().equals(getExternalAddress())) {
c.add(new JLabel(Resources.getString("Peer2Peer.local_address"))); //$NON-NLS-1$
final JTextField localIP = new JTextField(getLocalAddress());
localIP.setEditable(false);
c.add(localIP, "wrap, growx, push"); //$NON-NLS-1$
}
}
}
/**
* Customised List Cell Renderer for the JList display: - Display the Icon
* appropriate to the Server Entry - Highlight the currently selected server
*
*/
private class MyRenderer extends DefaultListCellRenderer {
private static final long serialVersionUID = 1L;
private Font standardFont;
private Font highlightFont;
@Override
public Component getListCellRendererComponent(JList list, Object value, int index,
boolean isSelected, boolean cellHasFocus) {
super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
if (standardFont == null) {
standardFont = getFont();
highlightFont = new Font(
standardFont.getFamily(),
Font.BOLD | Font.ITALIC,
standardFont.getSize()
);
}
if (value instanceof AddressBookEntry) {
final AddressBookEntry e = (AddressBookEntry) value;
setIcon(e.getIcon(LEAF_ICON_SIZE));
if (e.isCurrent()) {
setFont(highlightFont);
setText(e + Resources.getString("ServerAddressBook.current")); //$NON-NLS-1$
}
else {
setFont(standardFont);
}
}
return this;
}
}
}
|
package org.jasig.portal.layout.al;
import org.jasig.portal.PortalException;
import org.jasig.portal.layout.AggregatedLayout;
import org.jasig.portal.layout.IUserLayout;
import org.jasig.portal.layout.al.common.node.INodeId;
import org.jasig.portal.layout.al.common.node.ILayoutNode;
import org.jasig.portal.layout.al.common.node.INodeDescription;
import org.jasig.portal.layout.restrictions.IRestrictionManager;
/**
* Aggregated user layout manager implementation
*
* @author Michael Ivanov <a href="mailto:">mvi@immagic.com</a>
* @author Peter Kharchenko: pkharchenko at unicon.net
* @version $Revision$
*/
public class LayoutManagerImpl implements ILayoutManager {
private ILayoutCommandManager layoutCommandManager;
private IRestrictionManager restrictionManager;
// internal representation of an assembled layout
AggregatedLayout currentLayout;
// fragment manager
IFragmentManager fragmentManager;
// assemble user layout from scratch
public void loadUserLayout() {
// obtain user fragment, set it to be root
// should lost folder (i.e. loose nodes be obtained separately?)
// obtain list of all pushed fragments
// obtain list of operations
// perform operations, recording which pushed fragments
// has been successfully attached
}
/* (non-Javadoc)
* @see org.jasig.portal.layout.al.ILayoutManager#addNodes(org.jasig.portal.layout.al.common.node.ILayoutNode, org.jasig.portal.layout.al.common.node.INodeId, org.jasig.portal.layout.al.common.node.INodeId)
*/
public ILayoutNode addNodes(ILayoutNode node, INodeId parentId, INodeId nextId) {
// attach newly constructed copy to the active layout, checking restrictions first
// if fragmentId of the nodes being attached is not the same as the
// fragmentId of the attachment point, place the subtree under the "lost folder" for that fragment
// and record appropriate "move" operation.
return null;
}
/* (non-Javadoc)
* @see org.jasig.portal.layout.al.ILayoutManager#deleteNode(org.jasig.portal.layout.node.INodeId)
*/
public boolean deleteNode(INodeId nodeId) {
// check restrictions
// if central modifications
// if fragment root, delete fragment ?
// otherwise: perform node deletion
// else (local modifications)
// record "delete" operation
return false;
}
/* (non-Javadoc)
* @see org.jasig.portal.layout.al.ILayoutManager#moveNode(org.jasig.portal.layout.node.INodeId, org.jasig.portal.layout.node.INodeId, org.jasig.portal.layout.node.INodeId)
*/
public boolean moveNode(INodeId nodeId, INodeId parentId, INodeId nextId) {
// check restrictions
// edit-oriented logic:
// if cm(d) {
// if(cm(s)) {
// remove node from s, add to d fragments
// } else {
// perform local delete on s
// add node to d
// } else {
// if(cm(s)) {
// remove node from s, add to user fragment
// record attachment node operation on d
// } else {
// record move operation from s to d
// // simplified central mod logic:
// if(cm(d) && cm(s)) {
// remove node from s, add to d
// } else {
// record move operation from d to s
return false;
}
/* (non-Javadoc)
* @see org.jasig.portal.layout.al.ILayoutManager#updateNode(org.jasig.portal.layout.node.INodeDescription)
*/
public INodeDescription updateNode(INodeDescription nodeDesc) {
// check restrictions
// if central modification {
// change fragment node
// } else {
// record local update command
return null;
}
/**
* Import a subtree by constructing a local copy with
* assigned ids.
* @param node
* @return a local aggregated layout node copy with assigned ids
*/
protected IALNode importNodes(ILayoutNode node) {
// construct subtree copy, assigning layout ids.
// if the layout node implements IALNode, make use of the available
// restriction information, otherwise assign default restrictions (none?)
return null;
}
/* (non-Javadoc)
* @see org.jasig.portal.layout.al.ILayoutManager#attachNode(org.jasig.portal.layout.node.INodeId, org.jasig.portal.layout.node.INodeId, org.jasig.portal.layout.node.INodeId)
*/
public boolean attachNode(INodeId nodeId, INodeId parentId, INodeId nextId) {
// TODO Auto-generated method stub
return false;
}
/* (non-Javadoc)
* @see org.jasig.portal.layout.al.ILayoutManager#addNode(org.jasig.portal.layout.node.INodeDescription, org.jasig.portal.layout.node.INodeId, org.jasig.portal.layout.node.INodeId)
*/
public ILayoutNode addNode(INodeDescription nodeDesc, INodeId parentId, INodeId nextId) {
return null;
}
/* (non-Javadoc)
* @see org.jasig.portal.layout.al.ILayoutManager#canDeleteNode(org.jasig.portal.layout.node.INodeId)
*/
public boolean canDeleteNode(INodeId nodeId) throws PortalException {
// TODO Auto-generated method stub
return false;
}
/* (non-Javadoc)
* @see org.jasig.portal.layout.al.ILayoutManager#canMoveNode(org.jasig.portal.layout.node.INodeId, org.jasig.portal.layout.node.INodeId, org.jasig.portal.layout.node.INodeId)
*/
public boolean canMoveNode(INodeId nodeId, INodeId parentId,
INodeId nextSiblingId) throws PortalException {
// TODO Auto-generated method stub
return false;
}
/* (non-Javadoc)
* @see org.jasig.portal.layout.al.ILayoutManager#canUpdateNode(org.jasig.portal.layout.node.INodeDescription)
*/
public boolean canUpdateNode(INodeDescription node)
throws PortalException {
// TODO Auto-generated method stub
return false;
}
/* (non-Javadoc)
* @see org.jasig.portal.layout.al.ILayoutManager#getUserLayout()
*/
public IUserLayout getUserLayout() throws PortalException {
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see org.jasig.portal.layout.al.ILayoutManager#setUserLayout(org.jasig.portal.layout.IUserLayout)
*/
public void setUserLayout(IUserLayout userLayout) throws PortalException {
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
public int hashCode() {
// TODO Auto-generated method stub
return super.hashCode();
}
/* (non-Javadoc)
* @see java.lang.Object#finalize()
*/
protected void finalize() throws Throwable {
// TODO Auto-generated method stub
super.finalize();
}
/* (non-Javadoc)
* @see java.lang.Object#clone()
*/
protected Object clone() throws CloneNotSupportedException {
// TODO Auto-generated method stub
return super.clone();
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
public boolean equals(Object obj) {
// TODO Auto-generated method stub
return super.equals(obj);
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
public String toString() {
// TODO Auto-generated method stub
return super.toString();
}
/*private ILayoutNode addNode ( INodeDescription nodeDesc, IFragmentNodeId parentId, INodeId nextId ) {
}
private ILayoutNode addNode ( INodeDescription nodeDesc, ILayoutNodeId parentId, INodeId nextId ) {
}
private boolean moveNode ( ILayoutNodeId nodeId, ILayoutNodeId parentId, INodeId nextId ) {
}
private boolean moveNode ( ILayoutNodeId nodeId, IFragmentNodeId parentId, INodeId nextId ) {
}
private boolean moveNode ( IFragmentNodeId nodeId, ILayoutNodeId parentId, INodeId nextId ) {
}
private boolean moveNode ( IFragmentNodeId nodeId, IFragmentNodeId parentId, INodeId nextId ) {
}
private boolean deleteNode ( IFragmentNodeId nodeId ) {
}*/
/**
* @return Returns the layoutCommandManager.
*/
public ILayoutCommandManager getLayoutCommandManager() {
return layoutCommandManager;
}
/**
* Secify layout command manager to be used
* @param layoutCommandManager The layoutCommandManager to set.
*/
public void setLayoutCommandManager(ILayoutCommandManager layoutCommandManager) {
this.layoutCommandManager = layoutCommandManager;
}
/**
* @return Returns the restrictionManager.
*/
public IRestrictionManager getRestrictionManager() {
return restrictionManager;
}
/**
* @param restrictionManager The restrictionManager to set.
*/
public void setRestrictionManager(IRestrictionManager restrictionManager) {
this.restrictionManager = restrictionManager;
}
}
|
package org.caleydo.view.info.dataset;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import org.caleydo.core.data.collection.table.NumericalTable;
import org.caleydo.core.data.datadomain.ATableBasedDataDomain;
import org.caleydo.core.data.datadomain.DataDomainManager;
import org.caleydo.core.data.datadomain.IDataDomain;
import org.caleydo.core.data.perspective.table.TablePerspective;
import org.caleydo.core.event.EventListenerManager;
import org.caleydo.core.event.EventListenerManager.ListenTo;
import org.caleydo.core.event.EventListenerManagers;
import org.caleydo.core.event.data.DataSetSelectedEvent;
import org.caleydo.core.io.MetaDataElement;
import org.caleydo.core.io.MetaDataElement.AttributeType;
import org.caleydo.core.io.NumericalProperties;
import org.caleydo.core.manager.GeneralManager;
import org.caleydo.core.serialize.ASerializedSingleTablePerspectiveBasedView;
import org.caleydo.core.serialize.ProjectMetaData;
import org.caleydo.core.util.collection.Pair;
import org.caleydo.core.util.function.DoubleStatistics;
import org.caleydo.core.util.system.BrowserUtils;
import org.caleydo.core.view.CaleydoRCPViewPart;
import org.caleydo.core.view.IDataDomainBasedView;
import org.caleydo.view.histogram.GLHistogram;
import org.caleydo.view.histogram.RcpGLColorMapperHistogramView;
import org.caleydo.view.histogram.SerializedHistogramView;
import org.eclipse.jface.viewers.ColumnViewerToolTipSupport;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.StyledCellLabelProvider;
import org.eclipse.jface.viewers.StyledString;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerCell;
import org.eclipse.jface.window.ToolTip;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.ExpandBar;
import org.eclipse.swt.widgets.ExpandItem;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Link;
import org.eclipse.swt.widgets.TreeItem;
/**
* Data meta view showing details about a data table.
*
* @author Marc Streit
* @author Alexander Lex
*/
public class RcpDatasetInfoView extends CaleydoRCPViewPart implements IDataDomainBasedView<IDataDomain> {
public static final String VIEW_TYPE = "org.caleydo.view.info.dataset";
private IDataDomain dataDomain;
private TablePerspective tablePerspective;
private ExpandItem metaDataItem;
private ExpandItem dataSetItem;
private ExpandItem processingItem;
private ExpandItem statsItem;
private ExpandItem tablePerspectiveItem;
private Label recordPerspectiveLabel;
private Label recordPerspectiveCount;
// private Label unmappedRecordElements;
private Label dimensionPerspectiveLabel;
private Label dimensionPerspectiveCount;
// private Label unmappedDimensionElements;
private Label recordLabel;
private Label recordCount;
private Label dimensionLabel;
private Label dimensionCount;
private StyledText processingInfo;
private StyledText stats;
private TreeViewer metaDataTree;
// private StyledText metaDataInfo;
private ExpandItem histogramItem;
private RcpGLColorMapperHistogramView histogramView;
private final EventListenerManager listeners = EventListenerManagers.createSWTDirect();
/**
* Constructor.
*/
public RcpDatasetInfoView() {
super(SerializedDatasetInfoView.class);
listeners.register(this);
}
@Override
public void dispose() {
listeners.unregisterAll();
super.dispose();
}
@Override
public boolean isSupportView() {
return true;
}
@Override
public void createPartControl(Composite parent) {
ExpandBar expandBar = new ExpandBar(parent, SWT.V_SCROLL | SWT.NO_BACKGROUND);
expandBar.setSpacing(1);
expandBar.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, true));
parentComposite = expandBar;
createProjectInfos(expandBar);
createDataSetInfos(expandBar);
createProcessingInfo(expandBar);
createStatsInfo(expandBar);
createMetaDataInfo(expandBar);
createTablePerspectiveInfos(expandBar);
createHistogramInfos(expandBar);
if (dataDomain == null) {
setDataDomain(DataDomainManager.get().getDataDomainByID(
((ASerializedSingleTablePerspectiveBasedView) serializedView).getDataDomainID()));
}
parent.layout();
}
private void createDataSetInfos(ExpandBar expandBar) {
this.dataSetItem = new ExpandItem(expandBar, SWT.WRAP);
dataSetItem.setText("Data Set: <no selection>");
Composite c = new Composite(expandBar, SWT.NONE);
c.setLayout(new GridLayout(2, false));
recordLabel = new Label(c, SWT.NONE);
recordLabel.setText("");
recordLabel.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false));
recordCount = new Label(c, SWT.NONE);
recordCount.setText("");
recordCount.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, false));
dimensionLabel = new Label(c, SWT.NONE);
dimensionLabel.setText("");
dimensionLabel.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false));
dimensionCount = new Label(c, SWT.NONE);
dimensionCount.setText("");
dimensionCount.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, false));
dataSetItem.setControl(c);
dataSetItem.setHeight(c.computeSize(SWT.DEFAULT, SWT.DEFAULT).y);
dataSetItem.setExpanded(false);
}
private void createStatsInfo(ExpandBar expandBar) {
this.statsItem = new ExpandItem(expandBar, SWT.WRAP);
statsItem.setText("Dataset Stats");
Composite c = new Composite(expandBar, SWT.NONE);
c.setLayout(new GridLayout(1, false));
stats = new StyledText(c, SWT.H_SCROLL | SWT.V_SCROLL | SWT.MULTI | SWT.BORDER | SWT.WRAP);
stats.setBackgroundMode(SWT.INHERIT_FORCE);
stats.setText("No processing");
GridData gd = new GridData(SWT.FILL, SWT.FILL, true, false);
gd.heightHint = 60;
stats.setLayoutData(gd);
stats.setEditable(false);
stats.setWordWrap(true);
// transformationLabel.set
// transformationLabel.();
statsItem.setControl(c);
statsItem.setHeight(c.computeSize(SWT.DEFAULT, SWT.DEFAULT).y);
}
private void createProcessingInfo(ExpandBar expandBar) {
this.processingItem = new ExpandItem(expandBar, SWT.WRAP);
processingItem.setText("Processing Info");
Composite c = new Composite(expandBar, SWT.NONE);
c.setLayout(new GridLayout(1, false));
processingInfo = new StyledText(c, SWT.H_SCROLL | SWT.V_SCROLL | SWT.MULTI | SWT.BORDER | SWT.WRAP);
processingInfo.setBackgroundMode(SWT.INHERIT_FORCE);
processingInfo.setText("No processing");
GridData gd = new GridData(SWT.FILL, SWT.FILL, true, false);
gd.heightHint = 60;
processingInfo.setLayoutData(gd);
processingInfo.setEditable(false);
processingInfo.setWordWrap(true);
// transformationLabel.set
// transformationLabel.();
processingItem.setControl(c);
processingItem.setHeight(c.computeSize(SWT.DEFAULT, SWT.DEFAULT).y);
}
private void createMetaDataInfo(ExpandBar expandBar) {
this.metaDataItem = new ExpandItem(expandBar, SWT.WRAP);
metaDataItem.setText("Meta Data");
Composite c = new Composite(expandBar, SWT.NONE);
c.setLayout(new GridLayout(1, false));
metaDataTree = new TreeViewer(c, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
metaDataTree.setContentProvider(new MetaDataContentProvider());
metaDataTree.setLabelProvider(new MetaDataLabelProvider());
GridData gridData = new GridData(GridData.FILL_HORIZONTAL);
gridData.grabExcessVerticalSpace = true;
gridData.minimumHeight = 150;
metaDataTree.getTree().setLayoutData(gridData);
ColumnViewerToolTipSupport.enableFor(metaDataTree, ToolTip.NO_RECREATE);
metaDataTree.getTree().addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
super.widgetSelected(e);
TreeItem item = (TreeItem) e.item;
Object element = item.getData();
if (!(element instanceof MetaDataElement)) {
@SuppressWarnings("unchecked")
Entry<String, Pair<String, AttributeType>> attribute = (Entry<String, Pair<String, AttributeType>>) element;
if (attribute.getValue().getSecond() == AttributeType.URL) {
BrowserUtils.openURL(attribute.getValue().getFirst());
}
}
}
});
// metaDataInfo = new StyledText(c, SWT.H_SCROLL | SWT.V_SCROLL | SWT.MULTI | SWT.BORDER | SWT.WRAP);
// metaDataInfo.setBackgroundMode(SWT.INHERIT_FORCE);
// metaDataInfo.setText("No meta data");
// GridData gd = new GridData(SWT.FILL, SWT.FILL, true, false);
// gd.heightHint = 160;
// metaDataInfo.setLayoutData(gd);
// metaDataInfo.setEditable(false);
// metaDataInfo.setWordWrap(true);
// transformationLabel.set
// transformationLabel.();
metaDataItem.setControl(c);
metaDataItem.setHeight(c.computeSize(SWT.DEFAULT, SWT.DEFAULT).y);
}
private void createTablePerspectiveInfos(ExpandBar expandBar) {
this.tablePerspectiveItem = new ExpandItem(expandBar, SWT.WRAP);
tablePerspectiveItem.setText("Perspective: <no selection>");
Composite c = new Composite(expandBar, SWT.NONE);
c.setLayout(new GridLayout(2, false));
recordPerspectiveLabel = new Label(c, SWT.NONE);
recordPerspectiveLabel.setText("");
recordPerspectiveLabel.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false));
recordPerspectiveCount = new Label(c, SWT.NONE);
recordPerspectiveCount.setText("");
recordPerspectiveCount.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, false));
// unmappedRecordElements = new Label(c, SWT.NONE);
// unmappedRecordElements.setText("");
// unmappedRecordElements.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 2, 0));
dimensionPerspectiveLabel = new Label(c, SWT.NONE);
dimensionPerspectiveLabel.setText("");
dimensionPerspectiveLabel.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false));
dimensionPerspectiveCount = new Label(c, SWT.NONE);
dimensionPerspectiveCount.setText("");
dimensionPerspectiveCount.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, false));
// unmappedDimensionElements = new Label(c, SWT.NONE);
// unmappedDimensionElements.setText("");
// unmappedDimensionElements.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 2, 0));
tablePerspectiveItem.setControl(c);
tablePerspectiveItem.setHeight(c.computeSize(SWT.DEFAULT, SWT.DEFAULT).y);
tablePerspectiveItem.setExpanded(false);
}
private void createProjectInfos(ExpandBar expandBar) {
ProjectMetaData metaData = GeneralManager.get().getMetaData();
if (metaData.keys().isEmpty())
return;
ExpandItem expandItem = new ExpandItem(expandBar, SWT.NONE);
expandItem.setText("Project: " + metaData.getName());
Composite g = new Composite(expandBar, SWT.NONE);
g.setLayout(new GridLayout(2, false));
createLine(
g,
"Creation Date",
DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, Locale.ENGLISH).format(
metaData.getCreationDate()));
for (String key : metaData.keys()) {
createLine(g, key, metaData.get(key));
}
expandItem.setControl(g);
expandItem.setHeight(g.computeSize(SWT.DEFAULT, SWT.DEFAULT).y);
expandItem.setExpanded(false);
}
private void createHistogramInfos(ExpandBar expandBar) {
histogramItem = new ExpandItem(expandBar, SWT.NONE);
histogramItem.setText("Histogram");
histogramItem.setHeight(200);
Composite wrapper = new Composite(expandBar, SWT.NONE);
wrapper.setLayout(new FillLayout());
histogramItem.setControl(wrapper);
histogramItem.setExpanded(false);
histogramItem.getControl().setEnabled(false);
}
private void createLine(Composite parent, String label, String value) {
if (label == null || label.trim().isEmpty() || value == null || value.trim().isEmpty())
return;
Label l = new Label(parent, SWT.NO_BACKGROUND);
l.setText(label + ":");
l.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false));
try {
final URL url = new URL(value);
Link v = new Link(parent, SWT.NO_BACKGROUND);
value = url.toExternalForm();
if (value.length() > 20)
value = value.substring(0, 20 - 3) + "...";
v.setText("<a href=\"" + url.toExternalForm() + "\">" + value + "</a>");
v.setToolTipText(url.toExternalForm());
v.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, false));
v.addSelectionListener(BrowserUtils.LINK_LISTENER);
} catch (MalformedURLException e) {
Label v = new Label(parent, SWT.NO_BACKGROUND);
v.setText(value);
v.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, false));
}
}
@Override
public void setDataDomain(IDataDomain dataDomain) {
// Do nothing if new datadomain is the same as the current one, or if dd
// is null
if (dataDomain == this.dataDomain || dataDomain == null)
return;
this.dataDomain = dataDomain;
updateDataSetInfo();
}
private void updateDataSetInfo() {
short stringLength = 28;
String dsLabel = "Dataset: " + dataDomain.getLabel();
if (dsLabel.length() > stringLength)
dsLabel = dsLabel.substring(0, stringLength - 3) + "...";
// dataSetItem.setText("Data Set: " + dataDomain.getLabel().substring(0, 15));
dataSetItem.setText(dsLabel);
if (dataDomain instanceof ATableBasedDataDomain) {
ATableBasedDataDomain tableBasedDD = (ATableBasedDataDomain) dataDomain;
dataSetItem.setExpanded(true);
int nrRecords = tableBasedDD.getTable().depth();
int nrDimensions = tableBasedDD.getTable().size();
String recordName = tableBasedDD.getRecordDenomination(true, true);
recordLabel.setText(recordName + ":");
recordCount.setText("" + nrRecords);
String dimensionName = tableBasedDD.getDimensionDenomination(true, true);
dimensionLabel.setText(dimensionName + ":");
dimensionCount.setText("" + nrDimensions);
((Composite) dataSetItem.getControl()).layout();
recordPerspectiveLabel.setText(recordName + ":");
dimensionPerspectiveLabel.setText(dimensionName + ":");
if (((ATableBasedDataDomain) dataDomain).getTable() instanceof NumericalTable) {
NumericalProperties numProp = dataDomain.getDataSetDescription().getDataDescription()
.getNumericalProperties();
String processingMessage = "";
if (numProp.getzScoreNormalization() != null) {
if (numProp.getzScoreNormalization().equals(NumericalProperties.ZSCORE_COLUMNS)) {
processingMessage += "Z-standardised on "
+ ((ATableBasedDataDomain) dataDomain).getColumnIDCategory() + "\n" + "";
} else if (numProp.getzScoreNormalization().equals(NumericalProperties.ZSCORE_ROWS)) {
processingMessage += "Z-standardised on "
+ ((ATableBasedDataDomain) dataDomain).getRowIDCategory() + System.lineSeparator();
}
}
if (numProp.getDataTransformation() != null) {
processingMessage += "Scale: " + numProp.getDataTransformation() + System.lineSeparator();
}
if (numProp.getClipToStdDevFactor() != null) {
processingMessage += "Clipped to " + numProp.getClipToStdDevFactor() + " std devs"
+ System.lineSeparator();
} else if (numProp.getMax() != null || numProp.getMin() != null) {
processingMessage += "Clipped to max: " + numProp.getMax() + ", min:" + numProp.getMin()
+ System.lineSeparator();
}
NumericalTable table = (NumericalTable) ((ATableBasedDataDomain) dataDomain).getTable();
if (table.getDataCenter() != null) {
processingMessage += "Centered at " + table.getDataCenter() + System.lineSeparator();
}
processingInfo.setText(processingMessage);
String n = System.lineSeparator();
DoubleStatistics dsStats = table.getDatasetStatistics();
String statsMessage = "";
statsMessage += "Mean: " + dsStats.getMean() + n;
statsMessage += "Std. Dev.: " + dsStats.getSd() + n;
statsMessage += "Max: " + dsStats.getMax() + n;
statsMessage += "Min: " + dsStats.getMin() + n;
statsMessage += "Skewness: " + dsStats.getSkewness() + n;
statsMessage += "Kurtosis: " + dsStats.getKurtosis() + n;
stats.setText(statsMessage);
} else {
statsItem.setExpanded(false);
stats.setText("");
processingItem.setExpanded(false);
processingInfo.setText("");
}
if (tablePerspective != null) {
String tpLabel = "Persp.: " + tablePerspective.getLabel();
if (tpLabel.length() > stringLength)
tpLabel = tpLabel.substring(0, stringLength - 3) + "...";
tablePerspectiveItem.setText(tpLabel);
tablePerspectiveItem.setExpanded(true);
recordPerspectiveCount.setText("" + tablePerspective.getNrRecords() + " ("
+ String.format("%.2f", tablePerspective.getNrRecords() * 100f / nrRecords) + "%)");
if (tablePerspective.getRecordPerspective().getUnmappedElements() > 0) {
recordPerspectiveCount.setToolTipText("Unmapped: "
+ tablePerspective.getRecordPerspective().getUnmappedElements() + " - The number of "
+ recordName
+ " that are in the original stratification but can't be mapped to this dataset");
} else {
recordPerspectiveCount.setToolTipText("");
}
dimensionPerspectiveCount.setText("" + tablePerspective.getNrDimensions() + " ("
+ String.format("%.2f", tablePerspective.getNrDimensions() * 100f / nrDimensions) + "%)");
if (tablePerspective.getDimensionPerspective().getUnmappedElements() > 1) {
dimensionPerspectiveCount.setToolTipText("Unmapped: "
+ tablePerspective.getDimensionPerspective().getUnmappedElements() + " - The number of "
+ dimensionName
+ " that are in the original stratification but can't be mapped to this dataset");
} else {
dimensionPerspectiveCount.setToolTipText("");
}
((Composite) tablePerspectiveItem.getControl()).layout();
} else {
tablePerspectiveItem.setText("Perspective: <no selection>");
tablePerspectiveItem.setExpanded(false);
recordPerspectiveCount.setText("<no selection>");
recordPerspectiveCount.setToolTipText("");
dimensionPerspectiveCount.setText("<no selection>");
dimensionPerspectiveCount.setToolTipText("");
}
updateMetaDataInfo();
if (!tableBasedDD.getTable().isDataHomogeneous() && tablePerspective == null) {
histogramItem.getControl().setEnabled(false);
histogramItem.setExpanded(false);
return;
}
histogramItem.getControl().setEnabled(true);
histogramItem.setExpanded(true);
if (histogramView == null) {
histogramView = new RcpGLColorMapperHistogramView();
histogramView.setDataDomain(tableBasedDD);
if (tablePerspective != null)
histogramView.setTablePerspective(tablePerspective);
SerializedHistogramView serializedHistogramView = new SerializedHistogramView();
serializedHistogramView.setDataDomainID(dataDomain.getDataDomainID());
serializedHistogramView
.setTablePerspectiveKey(((ASerializedSingleTablePerspectiveBasedView) serializedView)
.getTablePerspectiveKey());
histogramView.setExternalSerializedView(serializedHistogramView);
histogramView.createPartControl((Composite) histogramItem.getControl());
// Usually the canvas is registered to the GL2 animator in the
// PartListener. Because the GL2 histogram is no usual RCP view
// have to do it on our own
GeneralManager.get().getViewManager().registerGLCanvasToAnimator(histogramView.getGLCanvas());
((Composite) histogramItem.getControl()).layout();
}
// If the default table perspective does not exist yet, we
// create it and set it to private so that it does not show up
// in the DVI
if (!tableBasedDD.hasTablePerspective(tableBasedDD.getTable().getDefaultRecordPerspective(false)
.getPerspectiveID(), tableBasedDD.getTable().getDefaultDimensionPerspective(false)
.getPerspectiveID())) {
tableBasedDD.getDefaultTablePerspective().setPrivate(true);
}
histogramView.setDataDomain(tableBasedDD);
((GLHistogram) histogramView.getGLView()).setDataDomain(tableBasedDD);
histogramView.setTablePerspective(tablePerspective);
((GLHistogram) histogramView.getGLView()).setTablePerspective(tablePerspective);
((GLHistogram) histogramView.getGLView()).setDisplayListDirty();
} else {
dataSetItem.setExpanded(true);
histogramItem.setExpanded(false);
histogramItem.getControl().setEnabled(false);
}
}
private void updateMetaDataInfo() {
MetaDataElement metaData = dataDomain.getDataSetDescription().getMetaData();
if (metaData != null) {
// String text = new PlainTextFormatter().format(metaData);
metaDataTree.setContentProvider(new MetaDataContentProvider(metaData));
metaDataTree.setInput(metaData);
// metaDataInfo.setText(text);
}
}
@Override
public IDataDomain getDataDomain() {
return dataDomain;
}
@Override
public void createDefaultSerializedView() {
serializedView = new SerializedDatasetInfoView();
determineDataConfiguration(serializedView, false);
}
@ListenTo
private void onDataDomainUpdate(DataSetSelectedEvent event) {
IDataDomain dd = event.getDataDomain();
TablePerspective tp = event.getTablePerspective();
// Do nothing if new datadomain is the same as the current one, or if dd
// is null
if (dd == null || (dd == this.dataDomain && tp == this.tablePerspective))
return;
this.dataDomain = dd;
this.tablePerspective = tp;
updateDataSetInfo();
setDataDomain(event.getDataDomain());
}
private class MetaDataContentProvider implements ITreeContentProvider {
private MetaDataElement root;
public MetaDataContentProvider() {
// TODO Auto-generated constructor stub
}
public MetaDataContentProvider(MetaDataElement root) {
this.root = root;
}
@Override
public void dispose() {
}
@Override
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
}
@Override
public Object[] getElements(Object inputElement) {
if (inputElement instanceof MetaDataElement) {
return getChildren((MetaDataElement) inputElement);
}
return null;
}
@Override
public Object[] getChildren(Object parentElement) {
if (parentElement instanceof MetaDataElement) {
return getChildren((MetaDataElement) parentElement);
}
return null;
}
@SuppressWarnings("unchecked")
@Override
public Object getParent(Object element) {
if (element instanceof MetaDataElement) {
if (element == root)
return null;
return getParent((MetaDataElement) element, root);
} else {
return getParent((Entry<String, Pair<String, AttributeType>>) element, root);
}
}
private MetaDataElement getParent(MetaDataElement element, MetaDataElement parent) {
List<MetaDataElement> elements = parent.getElements();
if (elements != null && !elements.isEmpty()) {
if (elements.contains(element))
return parent;
for (MetaDataElement child : elements) {
MetaDataElement p = getParent(element, child);
if (p != null)
return p;
}
}
return null;
}
private MetaDataElement getParent(Entry<String, Pair<String, AttributeType>> attribute, MetaDataElement parent) {
Map<String, Pair<String, AttributeType>> attributes = parent.getAttributes();
if (attributes != null && !attributes.isEmpty()) {
if (attributes.entrySet().contains(attribute))
return parent;
List<MetaDataElement> elements = parent.getElements();
if (elements != null && !elements.isEmpty()) {
for (MetaDataElement child : elements) {
MetaDataElement p = getParent(attribute, child);
if (p != null)
return p;
}
}
}
return null;
}
@Override
public boolean hasChildren(Object element) {
if (element instanceof MetaDataElement) {
MetaDataElement e = (MetaDataElement) element;
Map<String, Pair<String, AttributeType>> attributes = e.getAttributes();
if (attributes != null && !attributes.isEmpty()) {
return true;
}
List<MetaDataElement> elements = e.getElements();
if (elements != null && !elements.isEmpty()) {
return true;
}
}
return false;
}
private Object[] getChildren(MetaDataElement element) {
Map<String, Pair<String, AttributeType>> attributes = element.getAttributes();
List<Object> children = new ArrayList<>();
if (attributes != null && !attributes.isEmpty()) {
children.addAll(attributes.entrySet());
}
List<MetaDataElement> elements = element.getElements();
if (elements != null && !elements.isEmpty()) {
children.addAll(elements);
}
return children.toArray();
}
/**
* @param root
* setter, see {@link root}
*/
public void setRoot(MetaDataElement root) {
this.root = root;
}
}
private class MetaDataLabelProvider extends StyledCellLabelProvider {
@Override
public void update(ViewerCell cell) {
Object element = cell.getElement();
StyledString text = new StyledString();
if (element instanceof MetaDataElement) {
MetaDataElement e = (MetaDataElement) element;
String name = e.getName();
if (name != null)
text.append(name);
} else {
@SuppressWarnings("unchecked")
Entry<String, Pair<String, AttributeType>> attribute = (Entry<String, Pair<String, AttributeType>>) element;
if (attribute.getValue().getSecond() == AttributeType.URL) {
text.append(attribute.getKey() + ": ");
String url = attribute.getValue().getFirst();
if (url.length() > 17) {
int index = url.lastIndexOf("/") + 1;
url = url.substring(index, url.length());
}
text.append(url, StyledString.COUNTER_STYLER);
} else {
text.append(attribute.getKey() + ": " + attribute.getValue().getFirst());
}
}
cell.setText(text.toString());
cell.setStyleRanges(text.getStyleRanges());
super.update(cell);
}
@Override
public String getToolTipText(Object element) {
if (!(element instanceof MetaDataElement)) {
@SuppressWarnings("unchecked")
Entry<String, Pair<String, AttributeType>> attribute = (Entry<String, Pair<String, AttributeType>>) element;
if (attribute.getValue().getSecond() == AttributeType.URL) {
return attribute.getValue().getFirst();
}
}
return super.getToolTipText(element);
}
}
}
|
package nl.idgis.publisher.database;
import java.util.Arrays;
import java.util.List;
import com.infradna.tool.bridge_method_injector.WithBridgeMethods;
import com.mysema.query.JoinFlag;
import com.mysema.query.QueryFlag;
import com.mysema.query.QueryFlag.Position;
import com.mysema.query.QueryMetadata;
import com.mysema.query.QueryModifiers;
import com.mysema.query.sql.ForeignKey;
import com.mysema.query.sql.RelationalFunctionCall;
import com.mysema.query.sql.RelationalPath;
import com.mysema.query.sql.SQLCommonQuery;
import com.mysema.query.sql.SQLOps;
import com.mysema.query.sql.SQLTemplates;
import com.mysema.query.sql.WithBuilder;
import com.mysema.query.support.Expressions;
import com.mysema.query.support.QueryMixin;
import com.mysema.query.types.CollectionExpression;
import com.mysema.query.types.EntityPath;
import com.mysema.query.types.Expression;
import com.mysema.query.types.ExpressionUtils;
import com.mysema.query.types.OperationImpl;
import com.mysema.query.types.Operator;
import com.mysema.query.types.OrderSpecifier;
import com.mysema.query.types.ParamExpression;
import com.mysema.query.types.Path;
import com.mysema.query.types.Predicate;
import com.mysema.query.types.SubQueryExpression;
import com.mysema.query.types.TemplateExpressionImpl;
import com.mysema.query.types.expr.CollectionExpressionBase;
import com.mysema.query.types.expr.CollectionOperation;
import com.mysema.query.types.query.ListSubQuery;
public abstract class AbstractAsyncSQLQuery<Q extends AbstractAsyncSQLQuery<Q>> implements SQLCommonQuery<Q> {
protected final QueryMixin<Q> queryMixin;
@SuppressWarnings("unchecked")
public AbstractAsyncSQLQuery(QueryMetadata metadata) {
queryMixin = new QueryMixin<Q>((Q)this, metadata);
}
@Override
@WithBridgeMethods(value=AbstractAsyncSQLQuery.class, castRequired=true)
public Q addFlag(Position position, String prefix, Expression<?> expr) {
Expression<?> flag = TemplateExpressionImpl.create(expr.getType(), prefix + "{0}", expr);
return queryMixin.addFlag(new QueryFlag(position, flag));
}
@Override
@WithBridgeMethods(value=AbstractAsyncSQLQuery.class, castRequired=true)
public Q addFlag(Position position, String flag) {
return queryMixin.addFlag(new QueryFlag(position, flag));
}
@Override
@WithBridgeMethods(value=AbstractAsyncSQLQuery.class, castRequired=true)
public Q addFlag(Position position, Expression<?> flag) {
return queryMixin.addFlag(new QueryFlag(position, flag));
}
@Override
@WithBridgeMethods(value=AbstractAsyncSQLQuery.class, castRequired=true)
public Q addJoinFlag(String flag) {
return addJoinFlag(flag, JoinFlag.Position.BEFORE_TARGET);
}
@Override
@WithBridgeMethods(value=AbstractAsyncSQLQuery.class, castRequired=true)
@SuppressWarnings("unchecked")
public Q addJoinFlag(String flag, JoinFlag.Position position) {
queryMixin.addJoinFlag(new JoinFlag(flag, position));
return (Q)this;
}
@WithBridgeMethods(value=AbstractAsyncSQLQuery.class, castRequired=true)
public Q from(Expression<?> arg) {
return queryMixin.from(arg);
}
@Override
@WithBridgeMethods(value=AbstractAsyncSQLQuery.class, castRequired=true)
public Q from(Expression<?>... args) {
return queryMixin.from(args);
}
@Override
@WithBridgeMethods(value=AbstractAsyncSQLQuery.class, castRequired=true)
@SuppressWarnings({ "unchecked", "rawtypes" })
public Q from(SubQueryExpression<?> subQuery, Path<?> alias) {
queryMixin.from(ExpressionUtils.as((Expression)subQuery, alias));
return (Q)this;
}
@Override
@WithBridgeMethods(value=AbstractAsyncSQLQuery.class, castRequired=true)
public Q fullJoin(EntityPath<?> target) {
return queryMixin.fullJoin(target);
}
@Override
@WithBridgeMethods(value=AbstractAsyncSQLQuery.class, castRequired=true)
public <E> Q fullJoin(RelationalFunctionCall<E> target, Path<E> alias) {
return queryMixin.fullJoin(target, alias);
}
@Override
@WithBridgeMethods(value=AbstractAsyncSQLQuery.class, castRequired=true)
public <E> Q fullJoin(ForeignKey<E> key, RelationalPath<E> entity) {
return queryMixin.fullJoin(entity).on(key.on(entity));
}
@Override
@WithBridgeMethods(value=AbstractAsyncSQLQuery.class, castRequired=true)
public Q fullJoin(SubQueryExpression<?> target, Path<?> alias) {
return queryMixin.fullJoin(target, alias);
}
@Override
@WithBridgeMethods(value=AbstractAsyncSQLQuery.class, castRequired=true)
public Q innerJoin(EntityPath<?> target) {
return queryMixin.innerJoin(target);
}
@Override
@WithBridgeMethods(value=AbstractAsyncSQLQuery.class, castRequired=true)
public <E> Q innerJoin(RelationalFunctionCall<E> target, Path<E> alias) {
return queryMixin.innerJoin(target, alias);
}
@Override
@WithBridgeMethods(value=AbstractAsyncSQLQuery.class, castRequired=true)
public <E> Q innerJoin(ForeignKey<E> key, RelationalPath<E> entity) {
return queryMixin.innerJoin(entity).on(key.on(entity));
}
@Override
@WithBridgeMethods(value=AbstractAsyncSQLQuery.class, castRequired=true)
public Q innerJoin(SubQueryExpression<?> target, Path<?> alias) {
return queryMixin.innerJoin(target, alias);
}
@Override
@WithBridgeMethods(value=AbstractAsyncSQLQuery.class, castRequired=true)
public Q join(EntityPath<?> target) {
return queryMixin.join(target);
}
@Override
@WithBridgeMethods(value=AbstractAsyncSQLQuery.class, castRequired=true)
public <E> Q join(RelationalFunctionCall<E> target, Path<E> alias) {
return queryMixin.join(target, alias);
}
@Override
@WithBridgeMethods(value=AbstractAsyncSQLQuery.class, castRequired=true)
public <E> Q join(ForeignKey<E> key, RelationalPath<E> entity) {
return queryMixin.join(entity).on(key.on(entity));
}
@Override
@WithBridgeMethods(value=AbstractAsyncSQLQuery.class, castRequired=true)
public Q join(SubQueryExpression<?> target, Path<?> alias) {
return queryMixin.join(target, alias);
}
@Override
@WithBridgeMethods(value=AbstractAsyncSQLQuery.class, castRequired=true)
public Q leftJoin(EntityPath<?> target) {
return queryMixin.leftJoin(target);
}
@Override
@WithBridgeMethods(value=AbstractAsyncSQLQuery.class, castRequired=true)
public <E> Q leftJoin(RelationalFunctionCall<E> target, Path<E> alias) {
return queryMixin.leftJoin(target, alias);
}
@Override
@WithBridgeMethods(value=AbstractAsyncSQLQuery.class, castRequired=true)
public <E> Q leftJoin(ForeignKey<E> key, RelationalPath<E> entity) {
return queryMixin.leftJoin(entity).on(key.on(entity));
}
@Override
@WithBridgeMethods(value=AbstractAsyncSQLQuery.class, castRequired=true)
public Q leftJoin(SubQueryExpression<?> target, Path<?> alias) {
return queryMixin.leftJoin(target, alias);
}
@WithBridgeMethods(value=AbstractAsyncSQLQuery.class, castRequired=true)
public Q on(Predicate condition) {
return queryMixin.on(condition);
}
@Override
@WithBridgeMethods(value=AbstractAsyncSQLQuery.class, castRequired=true)
public Q on(Predicate... conditions) {
return queryMixin.on(conditions);
}
@Override
@WithBridgeMethods(value=AbstractAsyncSQLQuery.class, castRequired=true)
public Q rightJoin(EntityPath<?> target) {
return queryMixin.rightJoin(target);
}
@Override
@WithBridgeMethods(value=AbstractAsyncSQLQuery.class, castRequired=true)
public <E> Q rightJoin(RelationalFunctionCall<E> target, Path<E> alias) {
return queryMixin.fullJoin(target, alias);
}
@Override
@WithBridgeMethods(value=AbstractAsyncSQLQuery.class, castRequired=true)
public <E> Q rightJoin(ForeignKey<E> key, RelationalPath<E> entity) {
return queryMixin.rightJoin(entity).on(key.on(entity));
}
@Override
@WithBridgeMethods(value=AbstractAsyncSQLQuery.class, castRequired=true)
public Q rightJoin(SubQueryExpression<?> target, Path<?> alias) {
return queryMixin.rightJoin(target, alias);
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private <T> CollectionExpressionBase<?,T> union(Operator<Object> op, List<? extends SubQueryExpression<?>> sq) {
Expression<?> rv = sq.get(0);
if (sq.size() == 1 && !CollectionExpression.class.isInstance(rv)) {
return new ListSubQuery(rv.getType(), sq.get(0).getMetadata());
} else {
Class<?> elementType = sq.get(0).getType();
if (rv instanceof CollectionExpression) {
elementType = ((CollectionExpression)rv).getParameter(0);
}
for (int i = 1; i < sq.size(); i++) {
rv = CollectionOperation.create(op, (Class)elementType, rv, sq.get(i));
}
return (CollectionExpressionBase<?,T>)rv;
}
}
public <T> CollectionExpressionBase<?,T> union(List<? extends SubQueryExpression<T>> sq) {
return union(SQLOps.UNION, sq);
}
@SuppressWarnings("unchecked")
public <T> CollectionExpressionBase<?,T> union(ListSubQuery<T>... sq) {
return union(SQLOps.UNION, Arrays.asList(sq));
}
@SuppressWarnings("unchecked")
public <T> CollectionExpressionBase<?,T> union(SubQueryExpression<T>... sq) {
return union(SQLOps.UNION, Arrays.asList(sq));
}
public <T> CollectionExpressionBase<?,T> unionAll(List<? extends SubQueryExpression<T>> sq) {
return union(SQLOps.UNION_ALL, sq);
}
@SuppressWarnings("unchecked")
public <T> CollectionExpressionBase<?,T> unionAll(ListSubQuery<T>... sq) {
return union(SQLOps.UNION_ALL, Arrays.asList(sq));
}
@SuppressWarnings("unchecked")
public <T> CollectionExpressionBase<?,T> unionAll(SubQueryExpression<T>... sq) {
return union(SQLOps.UNION_ALL, Arrays.asList(sq));
}
@Override
@WithBridgeMethods(value=AbstractAsyncSQLQuery.class, castRequired=true)
public Q withRecursive(Path<?> alias, SubQueryExpression<?> query) {
queryMixin.addFlag(new QueryFlag(QueryFlag.Position.WITH, SQLTemplates.RECURSIVE));
return with(alias, query);
}
@Override
@WithBridgeMethods(value=AbstractAsyncSQLQuery.class, castRequired=true)
public Q withRecursive(Path<?> alias, Expression<?> query) {
queryMixin.addFlag(new QueryFlag(QueryFlag.Position.WITH, SQLTemplates.RECURSIVE));
return with(alias, query);
}
@Override
@WithBridgeMethods(value=AbstractAsyncSQLQuery.class, castRequired=true)
public WithBuilder<Q> withRecursive(Path<?> alias, Path<?>... columns) {
queryMixin.addFlag(new QueryFlag(QueryFlag.Position.WITH, SQLTemplates.RECURSIVE));
return with(alias, columns);
}
@Override
@WithBridgeMethods(value=AbstractAsyncSQLQuery.class, castRequired=true)
public Q with(Path<?> alias, SubQueryExpression<?> target) {
Expression<?> expr = OperationImpl.create(alias.getType(), SQLOps.WITH_ALIAS, alias, target);
return queryMixin.addFlag(new QueryFlag(QueryFlag.Position.WITH, expr));
}
@Override
@WithBridgeMethods(value=AbstractAsyncSQLQuery.class, castRequired=true)
public Q with(Path<?> alias, Expression<?> query) {
Expression<?> expr = OperationImpl.create(alias.getType(), SQLOps.WITH_ALIAS, alias, query);
return queryMixin.addFlag(new QueryFlag(QueryFlag.Position.WITH, expr));
}
@Override
public WithBuilder<Q> with(Path<?> alias, Path<?>... columns) {
Expression<?> columnsCombined = ExpressionUtils.list(Object.class, columns);
Expression<?> aliasCombined = Expressions.operation(alias.getType(), SQLOps.WITH_COLUMNS, alias, columnsCombined);
return new WithBuilder<Q>(queryMixin, aliasCombined);
}
public QueryMetadata getMetadata() {
return queryMixin.getMetadata();
}
@Override
public abstract Q clone();
@Override
public Q groupBy(Expression<?>... o) {
return queryMixin.groupBy(o);
}
@Override
public Q having(Predicate... o) {
return queryMixin.having(o);
}
@Override
public Q limit(long limit) {
return queryMixin.limit(limit);
}
@Override
public Q offset(long offset) {
return queryMixin.offset(offset);
}
@Override
public Q restrict(QueryModifiers modifiers) {
return queryMixin.restrict(modifiers);
}
@Override
public Q orderBy(OrderSpecifier<?>... o) {
return queryMixin.orderBy(o);
}
@Override
public <T> Q set(ParamExpression<T> param, T value) {
return queryMixin.set(param, value);
}
@Override
public Q distinct() {
return queryMixin.distinct();
}
@Override
public Q where(Predicate... o) {
return queryMixin.where(o);
}
}
|
package org.kivy.android;
import java.io.File;
import android.util.Log;
import java.util.ArrayList;
import java.io.FilenameFilter;
import java.util.regex.Pattern;
public class PythonUtil {
private static final String TAG = "pythonutil";
protected static void addLibraryIfExists(ArrayList<String> libsList, String pattern, File libsDir) {
// pattern should be the name of the lib file, without the
// preceding "lib" or suffix ".so", for instance "ssl.*" will
// match files of the form "libssl.*.so".
File [] files = libsDir.listFiles();
pattern = "lib" + pattern + "\\.so";
Pattern p = Pattern.compile(pattern);
for (int i = 0; i < files.length; ++i) {
File file = files[i];
String name = file.getName();
Log.v(TAG, "Checking pattern " + pattern + " against " + name);
if (p.matcher(name).matches()) {
Log.v(TAG, "Pattern " + pattern + " matched file " + name);
libsList.add(name.substring(3, name.length() - 3));
}
}
}
protected static ArrayList<String> getLibraries(File libsDir) {
ArrayList<String> libsList = new ArrayList<String>();
addLibraryIfExists(libsList, "crystax", libsDir);
addLibraryIfExists(libsList, "sqlite3", libsDir);
addLibraryIfExists(libsList, "ffi", libsDir);
addLibraryIfExists(libsList, "ssl.*", libsDir);
addLibraryIfExists(libsList, "crypto.*", libsDir);
libsList.add("python2.7");
libsList.add("python3.5m");
libsList.add("python3.6m");
libsList.add("python3.7m");
libsList.add("main");
return libsList;
}
public static void loadLibraries(File filesDir, File libsDir) {
String filesDirPath = filesDir.getAbsolutePath();
boolean foundPython = false;
for (String lib : getLibraries(libsDir)) {
Log.v(TAG, "Loading library: " + lib);
try {
System.loadLibrary(lib);
if (lib.startsWith("python")) {
foundPython = true;
}
} catch(UnsatisfiedLinkError e) {
// If this is the last possible libpython
// load, and it has failed, give a more
// general error
Log.v(TAG, "Library loading error: " + e.getMessage());
if (lib.startsWith("python3.7") && !foundPython) {
throw new java.lang.RuntimeException("Could not load any libpythonXXX.so");
} else if (lib.startsWith("python")) {
continue;
} else {
Log.v(TAG, "An UnsatisfiedLinkError occurred loading " + lib);
throw e;
}
}
}
Log.v(TAG, "Loaded everything!");
}
}
|
package br.beholder.memelang.model.visitor;
import br.beholder.memelang.model.analisador.AssemblyName;
import br.beholder.memelang.model.analisador.Escopo;
import br.beholder.memelang.model.analisador.Identificador;
import br.beholder.memelang.model.language.MemelangParser;
import br.beholder.memelang.model.language.MemelangParser.ExpressaoContext;
import br.beholder.memelang.model.language.MemelangParser.Op_bitwiseContext;
import br.beholder.memelang.model.language.MemelangParser.ParametroContext;
import br.beholder.memelang.model.language.MemelangParser.Val_finalContext;
import java.util.ArrayList;
import java.util.List;
import org.antlr.v4.runtime.misc.ParseCancellationException;
/**
*
* @author 5663296
*/
public class BipGeneratorVisitor extends MemeVisitor{
private final StringBuilder header = new StringBuilder();
private final StringBuilder codigo = new StringBuilder();
private final List<AssemblyName> anlist;
private int maiorNumTemporariosNecessarios = 0;
private int numTemporariosNecessarios = 0;
private int numRotuloAtual = 0;
private int contEscopo = 1;
public BipGeneratorVisitor(List<Identificador> tabelaSimbolos) {
super(tabelaSimbolos);
this.anlist = AssemblyName.getMatrix(tabelaSimbolos);
this.codigo.append(".text\n");
this.geradorData();
}
public String getCodigo() {
String lines[] = this.codigo.toString().split("\n");
int lastReturn = -2;
StringBuilder finalCode = new StringBuilder();
finalCode.append(this.header);
for (int i = 1; i <= this.maiorNumTemporariosNecessarios; i++) {
finalCode.append("\t");
finalCode.append("temp");
finalCode.append(i);
finalCode.append(" : 0\n");
}
for (int i = 0; i < lines.length; i++) {
if(i - 1 == lastReturn && lines[i].contains("RETURN")){
lines[i] = "";
}
if(lines[i].contains("RETURN")){
lastReturn = i;
}
finalCode.append(lines[i]+"\n");
}
// finalCode.append(this.codigo);
return finalCode.toString();
}
private int getOneTemp() {
this.numTemporariosNecessarios++;
if (this.maiorNumTemporariosNecessarios < this.numTemporariosNecessarios) {
this.maiorNumTemporariosNecessarios = this.numTemporariosNecessarios;
}
return this.numTemporariosNecessarios;
}
private int releaseTheTemp() {
this.numTemporariosNecessarios
return this.numTemporariosNecessarios;
}
private String getOneRot() {
this.numRotuloAtual++;
String rot = "rot" + this.numRotuloAtual;
return rot;
}
private void geradorData() {
this.header.append(".data\n");
for (Identificador identificador : tabelaSimbolos) {
if (!identificador.isFuncao()) {
if (identificador.getTipo() != Identificador.Tipo.INTEIRO) {
throw new ParseCancellationException(identificador.getTipo() + " NOT SUPPORTED BY BIPIDE");
}
this.header.append("\t");
this.header.append(AssemblyName.findAN(this.anlist, identificador));
this.header.append(" : ");
for (int i = 0; i < identificador.getQtdArmazenada(); i++) {
if (i == identificador.getQtdArmazenada() - 1) {
this.header.append("0\n");
} else {
this.header.append("0 , ");
}
}
}
}
}
@Override
public Object visitTipoComVoid(MemelangParser.TipoComVoidContext ctx) {
return super.visitTipoComVoid(ctx); //To change body of generated methods, choose Tools | Templates.
}
@Override
public Object visitExpressao(MemelangParser.ExpressaoContext ctx) {
// System.out.println("Expr: " + ctx.getText());
this.primeiraOperacao(ctx);
int tempNum;
MemelangParser.Op_relContext rel = null;
for (int i = 1; i < ctx.val_final().size(); i++) {
if (ctx.operations(i - 1).op_rel() != null) {
tempNum = this.getOneTemp();
this.comando("STO", "temp" + tempNum);
rel = ctx.operations(i - 1).op_rel();
this.comando("LDI", ctx.val_final(i).getText());
}
resolveValFinalEOperando(ctx.operations(i - 1), ctx.val_final(i));
}
if (rel != null) {
tempNum = getOneTemp();
comando("STO", "temp" + tempNum);
comando("LD", "temp" + (tempNum - 1));
comando("SUB", "temp" + tempNum);
releaseTheTemp();
releaseTheTemp();
}
return null; //To change body of generated methods, choose Tools | Templates.
}
private void resolveSalto(MemelangParser.Op_relContext rel, boolean anti_form, String rot) {
if (rel.DIFERENTE() != null) {
if (anti_form) {
comando("BEQ", rot);
} else {
comando("BNE", rot);
}
}
if (rel.IDENTICO() != null) {
if (anti_form) {
comando("BNE", rot);
} else {
comando("BEQ", rot);
}
}
if (rel.MAIOROUIGUAL() != null) {
if (anti_form) {
comando("BLT", rot);
} else {
comando("BGE", rot);
}
}
if (rel.MAIORQUE() != null) {
if (anti_form) {
comando("BLE", rot);
} else {
comando("BGT", rot);
}
}
if (rel.MENOROUIGUAL() != null) {
if (anti_form) {
comando("BGT", rot);
} else {
comando("BLE", rot);
}
}
if (rel.MENORQUE() != null) {
if (anti_form) {
comando("BGE", rot);
} else {
comando("BLT", rot);
}
}
}
private void primeiraOperacao(MemelangParser.ExpressaoContext ctx) {
// System.out.println("FirstOp: " + ctx.getText());
MemelangParser.Val_finalContext valctx = ctx.val_final(0);
//Carregar valor inteiro imediato
if (valctx.CONSTINTEIRO() != null) {
comando("LDI", valctx.CONSTINTEIRO().getSymbol().getText());
}
//Carrega valor de um ID
if (valctx.ID() != null) {
if (valctx.multidimensional() != null) {
//Carregar valor de vetor
for(ExpressaoContext exp : valctx.multidimensional().expressao()){
visitExpressao(exp);
}
comando("STO", "$indr");
comando("LDV", findAN(valctx.ID().getSymbol().getText()).toString());
} else {
//Carregar valor de variavel
String varName = findAN(valctx.ID().getText()).toString();
comando("LD", varName);
}
}
if (valctx.chamadaFuncao() != null) {
visitChamadaFuncao(valctx.chamadaFuncao());
}
if (valctx.expressao() != null) {
// System.out.println("exp");
visitExpressao(valctx.expressao());
}
if (ctx.op_neg() != null) {
if(ctx.op_neg().BITNOT() != null){
comando("NOT", "0");
} else if (ctx.op_neg().MENOS() != null) {
reverteSinalAcc();
}
}
// System.out.println("Caiu fora");
}
private void resolveValFinalEOperando(MemelangParser.OperationsContext opctx, MemelangParser.Val_finalContext valctx) {
// System.out.println("Entrou resolve");
if (opctx.op_arit_baixa() != null) {
if (opctx.op_arit_baixa().MAIS() != null) {
resolveOpAritmeticaMaisOuNegacaoMenos(valctx, true);
}
}
if (opctx.op_bitwise() != null){
resolveOpBitwise(opctx.op_bitwise(), valctx);
}
if (opctx.op_neg() != null) {
if (opctx.op_neg().MENOS() != null) {
resolveOpAritmeticaMaisOuNegacaoMenos(valctx, false);
}
}
}
private void resolveOpBitwise(Op_bitwiseContext opBit, Val_finalContext valctx){
// System.out.println("Entrou " + valctx.getText());
if (valctx.CONSTINTEIRO() != null) {
if (opBit.BITAND() != null) {
comando("ANDI", valctx.CONSTINTEIRO().getSymbol().getText());
} else if (opBit.BITOR() != null) {
comando("ORI", valctx.CONSTINTEIRO().getSymbol().getText());
} else if (opBit.BITXOR() != null){
comando("XORI", valctx.CONSTINTEIRO().getSymbol().getText());
} else if (opBit.BITSHIFTLEFT() != null){
comando("SLL", valctx.CONSTINTEIRO().getSymbol().getText());
} else if (opBit.BITSHIFTRIGHT() != null){
comando("SRL", valctx.CONSTINTEIRO().getSymbol().getText());
} else if (opBit.BITNOT() != null){
comando("NOT", "0");
}
return;
}
//Carrega valor de um ID
if (valctx.ID() != null) {
if (valctx.multidimensional() != null) {
//Carregar valor de vetor
int tempNum = getOneTemp();
comando("STO", "temp" + tempNum);
for(ExpressaoContext exp : valctx.multidimensional().expressao()){
visitExpressao(exp);
}
comando("STO", "$indr");
comando("LDV", findAN(valctx.ID().getSymbol().getText()).toString());
tempNum = getOneTemp();
comando("STO", "temp" + tempNum);
comando("LD", "temp" + (tempNum - 1));
if(opBit.BITAND() != null){
comando("AND", "temp" + tempNum);
}else if (opBit.BITNOT() != null){
comando("NOT", "0");
}else if (opBit.BITOR() != null ){
comando("OR", "temp" + tempNum);
}else if (opBit.BITSHIFTLEFT() != null){
comando("SLL", "temp" + tempNum);
}else if (opBit.BITSHIFTRIGHT() != null){
comando("SRL", "temp" + tempNum);
}else if(opBit.BITXOR() != null){
comando("XOR", "temp" + tempNum);
}
releaseTheTemp();
releaseTheTemp();
return;
} else {
//Carregar valor de variavel
String varName = findAN(valctx.ID().getText()).toString();
if(opBit.BITAND() != null){
comando("AND", varName);
}else if (opBit.BITNOT() != null){
comando("NOT", "0");
}else if (opBit.BITOR() != null ){
comando("OR", varName);
}else if (opBit.BITSHIFTLEFT() != null){
comando("SLL", varName);
}else if (opBit.BITSHIFTRIGHT() != null){
comando("SRL", varName);
}else if(opBit.BITXOR() != null){
comando("XOR", varName);
}
return;
}
}
if (valctx.chamadaFuncao() != null) {
int tempNum = getOneTemp();
comando("STO", "temp" + tempNum);
visitChamadaFuncao(valctx.chamadaFuncao());
tempNum = getOneTemp();
comando("STO", "temp" + tempNum);
comando("LD", "temp" + (tempNum - 1));
if(opBit.BITAND() != null){
comando("AND", "temp" + tempNum);
}else if (opBit.BITNOT() != null){
comando("NOT", "0");
}else if (opBit.BITOR() != null ){
comando("OR", "temp" + tempNum);
}else if (opBit.BITSHIFTLEFT() != null){
comando("SLL", "temp" + tempNum);
}else if (opBit.BITSHIFTRIGHT() != null){
comando("SRL", "temp" + tempNum);
}else if(opBit.BITXOR() != null){
comando("XOR", "temp" + tempNum);
}
releaseTheTemp();
releaseTheTemp();
return;
}
if (valctx.expressao() != null) {
int tempNum = getOneTemp();
comando("STO", "temp" + tempNum);
visitExpressao(valctx.expressao());
tempNum = getOneTemp();
comando("STO", "temp" + tempNum);
comando("LD", "temp" + (tempNum - 1));
if(opBit.BITAND() != null){
comando("AND", "temp" + tempNum);
}else if (opBit.BITNOT() != null){
comando("NOT", "0");
}else if (opBit.BITOR() != null ){
comando("OR", "temp" + tempNum);
}else if (opBit.BITSHIFTLEFT() != null){
comando("SLL", "temp" + tempNum);
}else if (opBit.BITSHIFTRIGHT() != null){
comando("SRL", "temp" + tempNum);
}else if(opBit.BITXOR() != null){
comando("XOR", "temp" + tempNum);
}
releaseTheTemp();
releaseTheTemp();
return;
}
throw new ParseCancellationException("Outras operações não identificadas" + valctx.getText());
}
private void resolveOpAritmeticaMaisOuNegacaoMenos(MemelangParser.Val_finalContext valctx, boolean operacaoMais) {
//ADD ou SUB valor inteiro imediato
// System.out.println("Exp " + valctx.getText());
if (valctx.CONSTINTEIRO() != null) {
if (operacaoMais) {
comando("ADDI", valctx.CONSTINTEIRO().getSymbol().getText());
} else {
comando("SUBI", valctx.CONSTINTEIRO().getSymbol().getText());
}
return;
}
//Carrega valor de um ID
if (valctx.ID() != null) {
if (valctx.multidimensional() != null) {
//Carregar valor de vetor
int tempNum = getOneTemp();
comando("STO", "temp" + tempNum);
for(ExpressaoContext exp : valctx.multidimensional().expressao()){
visitExpressao(exp);
}
comando("STO", "$indr");
comando("LDV", findAN(valctx.ID().getSymbol().getText()).toString());
tempNum = getOneTemp();
comando("STO", "temp" + tempNum);
comando("LD", "temp" + (tempNum - 1));
if (operacaoMais) {
comando("ADD", "temp" + tempNum);
} else {
comando("SUB", "temp" + tempNum);
}
releaseTheTemp();
releaseTheTemp();
return;
} else {
//Carregar valor de variavel
String varName = findAN(valctx.ID().getText()).toString();
if (operacaoMais) {
comando("ADD", varName);
} else {
comando("SUB", varName);
}
return;
}
}
if (valctx.chamadaFuncao() != null) {
int tempNum = getOneTemp();
comando("STO", "temp" + tempNum);
visitChamadaFuncao(valctx.chamadaFuncao());
tempNum = getOneTemp();
comando("STO", "temp" + tempNum);
comando("LD", "temp" + (tempNum - 1));
if (operacaoMais) {
comando("ADD", "temp" + tempNum);
} else {
comando("SUB", "temp" + tempNum);
}
releaseTheTemp();
releaseTheTemp();
return;
}
if (valctx.expressao() != null) {
int tempNum = getOneTemp();
comando("STO", "temp" + tempNum);
visitExpressao(valctx.expressao());
tempNum = getOneTemp();
comando("STO", "temp" + tempNum);
comando("LD", "temp" + (tempNum - 1));
if (operacaoMais) {
comando("ADD", "temp" + tempNum);
} else {
comando("SUB", "temp" + tempNum);
}
releaseTheTemp();
releaseTheTemp();
return;
}
throw new ParseCancellationException("Outras operações não identificadas" + valctx.getText());
}
private void comando(String comando, String operador) {
if(!comando.contains(":")){
this.codigo.append("\t");
}
this.codigo.append(comando);
this.codigo.append(" ");
this.codigo.append(operador);
this.codigo.append("\n");
}
@Override
public Object visitVal_final(MemelangParser.Val_finalContext ctx) {
if (ctx.CONSTINTEIRO() != null) {
}
return super.visitVal_final(ctx); //To change body of generated methods, choose Tools | Templates.
}
@Override
public Object visitOp_logica(MemelangParser.Op_logicaContext ctx) {
return super.visitOp_logica(ctx); //To change body of generated methods, choose Tools | Templates.
}
@Override
public Object visitOp_bitwise(MemelangParser.Op_bitwiseContext ctx) {
return super.visitOp_bitwise(ctx); //To change body of generated methods, choose Tools | Templates.
}
@Override
public Object visitOperations(MemelangParser.OperationsContext ctx) {
return super.visitOperations(ctx); //To change body of generated methods, choose Tools | Templates.
}
private void reverteSinalAcc() {
int tempNum = getOneTemp();
comando("STO", "temp" + tempNum);
comando("LDI", "0");
comando("SUB", "temp" + tempNum);
releaseTheTemp();
}
@Override
public Object visitParametrosChamada(MemelangParser.ParametrosChamadaContext ctx) {
for (ExpressaoContext expressao : ctx.expressao()) {
visitExpressao(expressao);
int tempNum = getOneTemp();
comando("STO", "temp" + tempNum);
}
for (ExpressaoContext expressao : ctx.expressao()) {
releaseTheTemp();
}
return null;
// return super.visitParametrosChamada(ctx); //To change body of generated methods, choose Tools | Templates.
}
@Override
public Object visitTipo(MemelangParser.TipoContext ctx) {
return super.visitTipo(ctx); //To change body of generated methods, choose Tools | Templates.
}
@Override
public Object visitSwitchCase(MemelangParser.SwitchCaseContext ctx) {
return super.visitSwitchCase(ctx); //To change body of generated methods, choose Tools | Templates.
}
@Override
public Object visitOp_arit_baixa(MemelangParser.Op_arit_baixaContext ctx) {
return super.visitOp_arit_baixa(ctx); //To change body of generated methods, choose Tools | Templates.
}
@Override
public Object visitParametros(MemelangParser.ParametrosContext ctx) {
return super.visitParametros(ctx); //To change body of generated methods, choose Tools | Templates.
}
@Override
public Object visitSwitchdes(MemelangParser.SwitchdesContext ctx) {
return super.visitSwitchdes(ctx); //To change body of generated methods, choose Tools | Templates.
}
@Override
public Object visitFuncao(MemelangParser.FuncaoContext ctx) {
if (ctx.ID() == null) {
return null;
}
AssemblyName an = findAN(ctx.ID().getText());
escopoAtual = vaiEscopoFilho(an.getId().getNome());
this.codigo.append(an.toString());
this.codigo.append(" : \n");
for (ParametroContext par : ctx.parametros().parametro()) {
AssemblyName variavel = findAN(par.ID().getText());
int tempNum = getOneTemp();
comando("LD", "temp" + tempNum);
comando("STO", variavel.toString());
}
for (ParametroContext par : ctx.parametros().parametro()) {
releaseTheTemp();
}
visitBloco(ctx.bloco()); //To change body of generated methods, choose Tools | Templates.
if (an.toString().equals("divideByZero")) {
this.codigo.append("\tHLT\n");
} else {
this.codigo.append("\tRETURN\n");
}
retornaEscopoPai();
// visitFuncoes(ctx.funcoes());
return null;
}
@Override
public Object visitIfdeselse(MemelangParser.IfdeselseContext ctx) {
escopoAtual = Escopo.criaEVaiEscopoNovo("else_" + contEscopo++, escopoAtual);
return super.visitIfdeselse(ctx); //To change body of generated methods, choose Tools | Templates.
}
@Override
public Object visitIfdes(MemelangParser.IfdesContext ctx) {
escopoAtual = Escopo.criaEVaiEscopoNovo("if_" + contEscopo++, escopoAtual);
String rot = getOneRot();
String rot2 = null;
visitExpressao(ctx.expressao());
List<MemelangParser.OperationsContext> operacoes = ctx.expressao().operations();
for (MemelangParser.OperationsContext operacao : operacoes) {
if (operacao.op_rel() != null) {
resolveSalto(operacao.op_rel(), true, rot);
}
}
visitBloco(ctx.bloco());
if (ctx.ifdeselse() != null || ctx.ifdeselseif() != null) {
rot2 = getOneRot();
comando("JMP", rot2);
}
comando(rot + " : ", "");
if (ctx.ifdeselse() != null) {
visitIfdeselse(ctx.ifdeselse());
comando(rot2 + " : ", "");
}
if (ctx.ifdeselseif() != null) {
visitIfdeselseif(ctx.ifdeselseif());
comando(rot2 + " : ", "");
}
retornaEscopoPai();
return null;
}
@Override
public Object visitCondicionais(MemelangParser.CondicionaisContext ctx) {
return super.visitCondicionais(ctx); //To change body of generated methods, choose Tools | Templates.
}
@Override
public Object visitMultidimensional(MemelangParser.MultidimensionalContext ctx) {
return super.visitMultidimensional(ctx); //To change body of generated methods, choose Tools | Templates.
}
@Override
public Object visitDeclaracoesArray(MemelangParser.DeclaracoesArrayContext ctx) {
return super.visitDeclaracoesArray(ctx); //To change body of generated methods, choose Tools | Templates.
}
@Override
public Object visitSubArrayDeclaracoes(MemelangParser.SubArrayDeclaracoesContext ctx) {
return super.visitSubArrayDeclaracoes(ctx); //To change body of generated methods, choose Tools | Templates.
}
@Override
public Object visitAtribuicoes(MemelangParser.AtribuicoesContext ctx) {
AssemblyName variavel = findAN(ctx.ID().getText());
if(variavel == null){
System.out.println("Null aqui " + ctx.ID().getText());
}
if(ctx.atribuicoesIncEDec()!= null){
if(ctx.atribuicoesIncEDec().MAIS().size()>0)
{
comando("LD", variavel.toString());
comando("ADDI", ""+1);
comando("STO", variavel.toString());
}
else if(ctx.atribuicoesIncEDec().MENOS().size()>0)
{
comando("LD", variavel.toString());
comando("SUBI", ""+1);
comando("STO", variavel.toString());
}
}
else if (variavel.getId().getDimensoes() == 0) {
visitExpressao(ctx.expressao());
comando("STO", variavel.toString());
} else {
visitExpressao(ctx.expressao());
int tempNum = getOneTemp();
comando("STO", "temp" + tempNum);
for(ExpressaoContext exp : ctx.multidimensional().expressao()){
visitExpressao(exp);
}
//tempNum = getOneTemp();
//comando("LDI", "temp"+tempNum);
comando("STO", "$indr");
comando("LD", "temp" + tempNum);
releaseTheTemp();
comando("STOV", variavel.toString());
}
return null; //To change body of generated methods, choose Tools | Templates.
}
@Override
public Object visitComandos(MemelangParser.ComandosContext ctx) {
return super.visitComandos(ctx); //To change body of generated methods, choose Tools | Templates.
}
@Override
public Object visitFordes(MemelangParser.FordesContext ctx) {
escopoAtual = Escopo.criaEVaiEscopoNovo("for_" + contEscopo++, escopoAtual);
if(ctx.declaracoes() != null){
visitDeclaracoes(ctx.declaracoes());
}else{
visitAtribuicoes(ctx.atribuicoes(0));
}
String rotRest = getOneRot();
String rotQuit = getOneRot();
comando(rotRest+" : ", "");
visitExpressao(ctx.expressao());
List<MemelangParser.OperationsContext> operacoes = ctx.expressao().operations();
for (MemelangParser.OperationsContext operacao : operacoes) {
if (operacao.op_rel() != null) {
resolveSalto(operacao.op_rel(), true, rotQuit);
}
}
visitBloco(ctx.bloco());
visitAtribuicoes(ctx.atribuicoes(ctx.atribuicoes().size() - 1));
// List<MemelangParser.AtribuicoesContext> atris = ctx.atribuicoes();
// for (MemelangParser.AtribuicoesContext atri : atris) {
// visitAtribuicoes(atri);
comando("JMP", rotRest);
comando(rotQuit+" : ", "");
retornaEscopoPai();
return null;
}
@Override
public Object visitWhiledes(MemelangParser.WhiledesContext ctx) {
escopoAtual = Escopo.criaEVaiEscopoNovo("while_" + contEscopo++, escopoAtual);
String rotRest = getOneRot();
String rotQuit = getOneRot();
comando(rotRest+" : ", "");
visitExpressao(ctx.expressao());
List<MemelangParser.OperationsContext> operacoes = ctx.expressao().operations();
for (MemelangParser.OperationsContext operacao : operacoes) {
if (operacao.op_rel() != null) {
resolveSalto(operacao.op_rel(), true, rotQuit);
}
}
visitBloco(ctx.bloco());
comando("JMP", rotRest);
comando(rotQuit+" : ", "");
retornaEscopoPai();
return null;
}
private AssemblyName findAN(String name) {
System.out.println(escopoAtual);
return AssemblyName.findAN(this.anlist, Identificador.getId(name, tabelaSimbolos, escopoAtual));
}
@Override
public Object visitDeclaracoes(MemelangParser.DeclaracoesContext ctx) {
visitTipo(ctx.tipo());
for (MemelangParser.DeclaracaoContext declaracaoContext : ctx.declaracao()) {
if(declaracaoContext.IGUAL() != null){
AssemblyName variavel = findAN(declaracaoContext.ID().getText());
if (declaracaoContext.multidimensional() == null) {
visitExpressao(declaracaoContext.expressao());
comando("STO", variavel.toString());
} else {
int iMax = Integer.parseInt(declaracaoContext.multidimensional().expressao(0).getText());
for (int i = 0; i < iMax; i++) {
visitExpressao(declaracaoContext.declaracoesArray().subArrayDeclaracoes(0).expressao(i));
int tempNum = getOneTemp();
comando("STO", "temp" + tempNum);
comando("LDI", String.valueOf(i));
comando("STO", "$indr");
comando("LD", "temp" + tempNum);
comando("STOV", variavel.toString());
releaseTheTemp();
}
}
}
}
return null; //To change body of generated methods, choose Tools | Templates.
}
@Override
public Object visitDodes(MemelangParser.DodesContext ctx) {
escopoAtual = Escopo.criaEVaiEscopoNovo("doWhile_" + contEscopo++, escopoAtual);
String rotRest = getOneRot();
String rotQuit = getOneRot();
comando(rotRest+" : ", "");
visitBloco(ctx.bloco());
visitExpressao(ctx.expressao());
List<MemelangParser.OperationsContext> operacoes = ctx.expressao().operations();
for (MemelangParser.OperationsContext operacao : operacoes) {
if (operacao.op_rel() != null) {
resolveSalto(operacao.op_rel(), true, rotQuit);
}
}
comando("JMP", rotRest);
comando(rotQuit+" : ", "");
retornaEscopoPai();
return null;
}
@Override
public Object visitOp_rel(MemelangParser.Op_relContext ctx) {
return super.visitOp_rel(ctx); //To change body of generated methods, choose Tools | Templates.
}
@Override
public Object visitBloco(MemelangParser.BlocoContext ctx) {
visitComandos(ctx.comandos());
return null; //To change body of generated methods, choose Tools | Templates.
}
@Override
public Object visitAtribuicoesIncEDec(MemelangParser.AtribuicoesIncEDecContext ctx) {
return super.visitAtribuicoesIncEDec(ctx); //To change body of generated methods, choose Tools | Templates.
}
@Override
public Object visitProg(MemelangParser.ProgContext ctx) {
escopoAtual = Identificador.getUNSAFEId("divideByZero", tabelaSimbolos).getEscopo();
this.codigo.append("\tCALL divideByZero\n");
//JUMP TO MAIN
return super.visitProg(ctx); //To change body of generated methods, choose Tools | Templates.
}
@Override
public Object visitEntradaesaida(MemelangParser.EntradaesaidaContext ctx) {
ExpressaoContext expGeralAtual;
for (int i = 0; i < ctx.parametrosChamada().expressao().size(); i++) {
expGeralAtual = ctx.parametrosChamada().expressao().get(i);
// System.out.println("TEST " + expGeralAtual.val_final(0).getText());
if (ctx.DEFREAD() != null) {
if(expGeralAtual.val_final(0).multidimensional() != null){
for(ExpressaoContext exp : expGeralAtual.val_final(0).multidimensional().expressao() ){
visitExpressao(exp);
}
comando("STO", "$indr");
comando("LD", "$in_port");
comando("STOV", findAN(expGeralAtual.val_final(0).ID().getText()).toString());
}else{
comando("LD", "$in_port");
comando("STO", findAN(expGeralAtual.getText()).toString());
}
} else if (ctx.DEFWRITE() != null) {
int tempNum = getOneTemp();
if(expGeralAtual.val_final(0).multidimensional() != null){
for(ExpressaoContext exp : expGeralAtual.val_final(0).multidimensional().expressao() ){
visitExpressao(exp);
}
comando("STO", "$indr");
comando("LDV", findAN(expGeralAtual.val_final(0).ID().getText()).toString());
}else{
visitExpressao(expGeralAtual);
}
comando("STO", "$out_port");
releaseTheTemp();
}
}
return null; //To change body of generated methods, choose Tools | Templates.
}
@Override
public Object visitChamadaFuncao(MemelangParser.ChamadaFuncaoContext ctx) {
visitParametrosChamada(ctx.parametrosChamada());
if(ctx.ID() == null){
System.out.println("Satan " + ctx.getText());
}else{
System.out.println("782785");
String funName = findAN(ctx.ID().getText()).toString();
comando("CALL", funName);
}
return null; //To change body of generated methods, choose Tools | Templates.
}
@Override
public Object visitIfdeselseif(MemelangParser.IfdeselseifContext ctx) {
escopoAtual = Escopo.criaEVaiEscopoNovo("else_if_" + contEscopo++, escopoAtual);
return super.visitIfdeselseif(ctx); //To change body of generated methods, choose Tools | Templates.
}
@Override
public Object visitRetorno(MemelangParser.RetornoContext ctx) {
visitExpressao(ctx.expressao());
this.codigo.append("\tRETURN\n");
return null; //To change body of generated methods, choose Tools | Templates.
}
@Override
public Object visitDefaultdes(MemelangParser.DefaultdesContext ctx) {
return super.visitDefaultdes(ctx); //To change body of generated methods, choose Tools | Templates.
}
@Override
public Object visitOp_neg(MemelangParser.Op_negContext ctx) {
return super.visitOp_neg(ctx); //To change body of generated methods, choose Tools | Templates.
}
}
|
package ch.idsia.benchmark.mario.environments;
import ch.idsia.agents.Agent;
import ch.idsia.benchmark.mario.engine.*;
import ch.idsia.benchmark.mario.engine.sprites.Mario;
import ch.idsia.benchmark.mario.engine.sprites.Sprite;
import ch.idsia.tools.EvaluationInfo;
import ch.idsia.tools.MarioAIOptions;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public final class MarioEnvironment implements Environment
{
private int[] marioEgoPos = new int[2];
private int receptiveFieldHeight = -1; // to be setup via MarioAIOptions
private int receptiveFieldWidth = -1; // to be setup via MarioAIOptions
private int prevRFH = -1;
private int prevRFW = -1;
private byte[][] levelSceneZ; // memory is allocated in reset
private byte[][] enemiesZ; // memory is allocated in reset
private byte[][] mergedZZ; // memory is allocated in reset
final public List<Sprite> sprites = new ArrayList<Sprite>();
private int[] serializedLevelScene; // memory is allocated in reset
private int[] serializedEnemies; // memory is allocated in reset
private int[] serializedMergedObservation; // memory is allocated in reset
private final LevelScene levelScene;
// private int frame = 0;
private MarioVisualComponent marioVisualComponent;
private Agent agent;
private static final MarioEnvironment ourInstance = new MarioEnvironment();
private static final EvaluationInfo evaluationInfo = new EvaluationInfo();
private static String marioTraceFile;
private Recorder recorder;
private float intermediateReward = -1;
public static MarioEnvironment getInstance()
{
return ourInstance;
}
private MarioEnvironment()
{
// System.out.println("System.getProperty(\"java.awt.headless\") = " + System.getProperty("java.awt.headless"));
// System.out.println("System.getProperty(\"verbose\") = " + System.getProperty("-verbose"));
// System.out.println("Java: JA ZDES'!!");
// System.out.flush();
System.out.println(GlobalOptions.getBenchmarkName());
levelScene = new LevelScene();
}
public void resetDefault()
{
levelScene.resetDefault();
}
public void reset(String args)
{
MarioAIOptions marioAIOptions = MarioAIOptions.getOptionsByString(args);
this.reset(marioAIOptions);
// MarioAIOptions opts = new MarioAIOptions(setUpOptions);
// int[] intOpts = opts.toIntArray();
// this.reset(intOpts);
}
public void reset(MarioAIOptions setUpOptions)
{
/*System.out.println("\nsetUpOptions = " + setUpOptions);
for (int i = 0; i < setUpOptions.length; ++i)
{
System.out.print(" op[" + i +"] = " + setUpOptions[i]);
}
System.out.println("");
System.out.flush();*/
// if (!setUpOptions.getReplayOptions().equals(""))
this.setAgent(setUpOptions.getAgent());
receptiveFieldWidth = setUpOptions.getReceptiveFieldWidth();
receptiveFieldHeight = setUpOptions.getReceptiveFieldHeight();
if (receptiveFieldHeight != this.prevRFH || receptiveFieldWidth != this.prevRFW)
{
serializedLevelScene = new int[receptiveFieldHeight * receptiveFieldWidth];
serializedEnemies = new int[receptiveFieldHeight * receptiveFieldWidth];
serializedMergedObservation = new int[receptiveFieldHeight * receptiveFieldWidth];
levelSceneZ = new byte[receptiveFieldHeight][receptiveFieldWidth];
enemiesZ = new byte[receptiveFieldHeight][receptiveFieldWidth];
mergedZZ = new byte[receptiveFieldHeight][receptiveFieldWidth];
this.prevRFH = this.receptiveFieldHeight;
this.prevRFW = this.receptiveFieldWidth;
}
marioEgoPos[0] = setUpOptions.getMarioEgoPosRow();
marioEgoPos[1] = setUpOptions.getMarioEgoPosCol();
if (marioEgoPos[0] == 9 && getReceptiveFieldWidth() != 19)
marioEgoPos[0] = getReceptiveFieldWidth() / 2;
if (marioEgoPos[1] == 9 && getReceptiveFieldHeight() != 19)
marioEgoPos[1] = getReceptiveFieldHeight() / 2;
marioTraceFile = setUpOptions.getTraceFileName();
if (setUpOptions.isVisualization())
{
if (marioVisualComponent == null)
marioVisualComponent = MarioVisualComponent.getInstance(setUpOptions, this);
levelScene.reset(setUpOptions);
marioVisualComponent.reset();
marioVisualComponent.postInitGraphicsAndLevel();
marioVisualComponent.setAgent(agent);
marioVisualComponent.setLocation(setUpOptions.getViewLocation());
marioVisualComponent.setAlwaysOnTop(setUpOptions.isViewAlwaysOnTop());
if (setUpOptions.isScale2X())
GlobalOptions.changeScale2x();
} else
levelScene.reset(setUpOptions);
//create recorder
String recordingFileName = setUpOptions.getRecordingFileName();
if (!recordingFileName.equals("off"))
{
if (recordingFileName.equals("on"))
recordingFileName = GlobalOptions.getTimeStamp() + ".zip";
try
{
recorder = new Recorder(recordingFileName);
recorder.createFile("level.lvl");
recorder.writeObject(levelScene.level);
recorder.closeFile();
recorder.createFile("options");
recorder.writeObject(setUpOptions.asString());
recorder.closeFile();
recorder.createFile("actions.act");
} catch (FileNotFoundException e)
{
System.err.println("[Mario AI EXCEPTION] : Some of the recording components were not created. Recording failed");
} catch (IOException e)
{
System.err.println("[Mario AI EXCEPTION] : Some of the recording components were not created. Recording failed");
e.printStackTrace();
}
}
}
public void tick()
{
levelScene.tick();
if (GlobalOptions.isVisualization)
marioVisualComponent.tick();
}
public float[] getMarioFloatPos()
{
return levelScene.getMarioFloatPos();
}
public int getMarioMode()
{
return levelScene.getMarioMode();
}
public byte[][] getLevelSceneObservationZ(int ZLevel)
{
for (int y = levelScene.mario.mapY - receptiveFieldHeight / 2, obsX = 0; y <= levelScene.mario.mapY + receptiveFieldHeight / 2; y++, obsX++)
{
for (int x = levelScene.mario.mapX - receptiveFieldWidth / 2, obsY = 0; x <= levelScene.mario.mapX + receptiveFieldWidth / 2; x++, obsY++)
{
if (x >= 0 && x < levelScene.level.xExit && y >= 0 && y < levelScene.level.height)
{
levelSceneZ[obsX][obsY] = GeneralizerLevelScene.ZLevelGeneralization(levelScene.level.map[x][y], ZLevel);
} else
{
levelSceneZ[obsX][obsY] = 0;
}
}
}
return levelSceneZ;
}
public byte[][] getEnemiesObservationZ(int ZLevel)
{
for (int w = 0; w < enemiesZ.length; w++)
for (int h = 0; h < enemiesZ[0].length; h++)
enemiesZ[w][h] = 0;
for (Sprite sprite : sprites)
{
if (sprite.kind == levelScene.mario.kind)
continue;
if (sprite.mapX >= 0 &&
sprite.mapX >= levelScene.mario.mapX - receptiveFieldWidth / 2 &&
sprite.mapX <= levelScene.mario.mapX + receptiveFieldWidth / 2 &&
sprite.mapY >= 0 &&
sprite.mapY >= levelScene.mario.mapY - receptiveFieldHeight / 2 &&
sprite.mapY <= levelScene.mario.mapY + receptiveFieldHeight / 2)
{
int obsX = sprite.mapY - levelScene.mario.mapY + receptiveFieldHeight / 2;
int obsY = sprite.mapX - levelScene.mario.mapX + receptiveFieldWidth / 2;
enemiesZ[obsX][obsY] = GeneralizerEnemies.ZLevelGeneralization(sprite.kind, ZLevel);
}
}
return enemiesZ;
}
public byte[][] getMergedObservationZZ(int ZLevelScene, int ZLevelEnemies)
{
// int MarioXInMap = (int) mario.x / cellSize;
// int MarioYInMap = (int) mario.y / cellSize;
// if (MarioXInMap != (int) mario.x / cellSize ||MarioYInMap != (int) mario.y / cellSize )
// throw new Error("WRONG mario x or y pos");
for (int y = levelScene.mario.mapY - receptiveFieldHeight / 2, obsX = 0; y <= levelScene.mario.mapY + receptiveFieldHeight / 2; y++, obsX++)
{
for (int x = levelScene.mario.mapX - receptiveFieldWidth / 2, obsY = 0; x <= levelScene.mario.mapX + receptiveFieldWidth / 2; x++, obsY++)
{
if (x >= 0 && x < levelScene.level.xExit && y >= 0 && y < levelScene.level.height)
{
mergedZZ[obsX][obsY] = GeneralizerLevelScene.ZLevelGeneralization(levelScene.level.map[x][y], ZLevelScene);
} else
mergedZZ[obsX][obsY] = 0;
// if (x == MarioXInMap && y == MarioYInMap)
// mergedZZ[obsX][obsY] = mario.kind;
}
}
// for (int w = 0; w < mergedZZ.length; w++)
// for (int h = 0; h < mergedZZ[0].length; h++)
// mergedZZ[w][h] = -1;
for (Sprite sprite : sprites)
{
if (sprite.kind == levelScene.mario.kind)
continue;
if (sprite.mapX >= 0 &&
sprite.mapX > levelScene.mario.mapX - receptiveFieldWidth / 2 &&
sprite.mapX < levelScene.mario.mapX + receptiveFieldWidth / 2 &&
sprite.mapY >= 0 &&
sprite.mapY > levelScene.mario.mapY - receptiveFieldHeight / 2 &&
sprite.mapY < levelScene.mario.mapY + receptiveFieldHeight / 2)
{
int obsX = sprite.mapY - levelScene.mario.mapY + receptiveFieldHeight / 2;
int obsY = sprite.mapX - levelScene.mario.mapX + receptiveFieldWidth / 2;
// quick fix TODO: handle this in more general way.
// TODO: substitue '14' by explicit statement
if (mergedZZ[obsX][obsY] != 14)
{
byte tmp = GeneralizerEnemies.ZLevelGeneralization(sprite.kind, ZLevelEnemies);
if (tmp != Sprite.KIND_NONE)
mergedZZ[obsX][obsY] = tmp;
}
}
}
return mergedZZ;
}
public List<String> getObservationStrings(boolean Enemies, boolean LevelMap,
boolean mergedObservationFlag,
int ZLevelScene, int ZLevelEnemies)
{
List<String> ret = new ArrayList<String>();
if (levelScene.level != null && levelScene.mario != null)
{
ret.add("Total levelScene length = " + levelScene.level.length);
ret.add("Total levelScene height = " + levelScene.level.height);
ret.add("Physical Mario Position (x,y): (" + levelScene.mario.x + "," + levelScene.mario.y + ")");
ret.add("Mario Observation (Receptive Field) Width: " + receptiveFieldWidth + " Height: " + receptiveFieldHeight);
ret.add("X Exit Position: " + levelScene.level.xExit);
int MarioXInMap = (int) levelScene.mario.x / levelScene.cellSize;
int MarioYInMap = (int) levelScene.mario.y / levelScene.cellSize;
ret.add("Calibrated Mario Position (x,y): (" + MarioXInMap + "," + MarioYInMap + ")\n");
byte[][] levelScene = getLevelSceneObservationZ(ZLevelScene);
if (LevelMap)
{
ret.add("~ZLevel: Z" + ZLevelScene + " map:\n");
for (int x = 0; x < levelScene.length; ++x)
{
String tmpData = "";
for (int y = 0; y < levelScene[0].length; ++y)
tmpData += mapElToStr(levelScene[x][y]);
ret.add(tmpData);
}
}
byte[][] enemiesObservation = null;
if (Enemies || mergedObservationFlag)
enemiesObservation = getEnemiesObservationZ(ZLevelEnemies);
if (Enemies)
{
ret.add("~ZLevel: Z" + ZLevelScene + " Enemies Observation:\n");
for (int x = 0; x < enemiesObservation.length; x++)
{
String tmpData = "";
for (int y = 0; y < enemiesObservation[0].length; y++)
{
// if (x >=0 && x <= level.xExit)
tmpData += enemyToStr(enemiesObservation[x][y]);
}
ret.add(tmpData);
}
}
if (mergedObservationFlag)
{
byte[][] mergedObs = getMergedObservationZZ(ZLevelScene, ZLevelEnemies);
ret.add("~ZLevelScene: Z" + ZLevelScene + " ZLevelEnemies: Z" + ZLevelEnemies + " ; Merged observation /* Mario ~> #M.# */");
for (int x = 0; x < levelScene.length; ++x)
{
String tmpData = "";
for (int y = 0; y < levelScene[0].length; ++y)
tmpData += mapElToStr(mergedObs[x][y]);
ret.add(tmpData);
}
}
} else
ret.add("~[MarioAI ERROR] level : " + levelScene.level + " mario : " + levelScene.mario);
return ret;
}
private String mapElToStr(int el)
{
String s = "";
if (el == 0 || el == 1)
s = "
s += (el == levelScene.mario.kind) ? "#M.#" : el;
while (s.length() < 4)
s += "
return s + " ";
}
private String enemyToStr(int el)
{
String s = "";
if (el == 0)
s = "";
s += (el == levelScene.mario.kind) ? "-m" : el;
while (s.length() < 2)
s += "
return s + " ";
}
public float[] getEnemiesFloatPos()
{
return levelScene.getEnemiesFloatPos();
}
public boolean isMarioOnGround()
{
return levelScene.isMarioOnGround();
}
public boolean isMarioAbleToJump()
{
return levelScene.isMarioAbleToJump();
}
public boolean isMarioCarrying()
{
return levelScene.isMarioCarrying();
}
public boolean isMarioAbleToShoot()
{
return levelScene.isMarioAbleToShoot();
}
public int getReceptiveFieldWidth()
{
return receptiveFieldWidth;
}
public int getReceptiveFieldHeight()
{
return receptiveFieldHeight;
}
public int getKillsTotal()
{
return levelScene.getKillsTotal();
}
public int getKillsByFire()
{
return levelScene.getKillsByFire();
}
public int getKillsByStomp()
{
return levelScene.getKillsByStomp();
}
public int getKillsByShell()
{
return levelScene.getKillsByShell();
}
public int getMarioStatus()
{
return levelScene.getMarioStatus();
}
public float[] getSerializedFullObservationZZ(int ZLevelScene, int ZLevelEnemies)
{
// TODO:TASK:[M], serialize all data to a sole double[]
assert false;
return new float[0];
}
public int[] getSerializedLevelSceneObservationZ(int ZLevelScene)
{
// serialization into arrays of primitive types to speed up the data transfer.
byte[][] levelScene = this.getLevelSceneObservationZ(ZLevelScene);
for (int i = 0; i < serializedLevelScene.length; ++i)
{
final int i1 = i / receptiveFieldWidth;
final int i2 = i % receptiveFieldWidth;
serializedLevelScene[i] = (int) levelScene[i1][i2];
}
return serializedLevelScene;
}
public int[] getSerializedEnemiesObservationZ(int ZLevelEnemies)
{
// serialization into arrays of primitive types to speed up the data transfer.
byte[][] enemies = this.getEnemiesObservationZ(ZLevelEnemies);
for (int i = 0; i < serializedEnemies.length; ++i)
serializedEnemies[i] = (int) enemies[i / receptiveFieldWidth][i % receptiveFieldWidth];
return serializedEnemies;
}
public int[] getSerializedMergedObservationZZ(int ZLevelScene, int ZLevelEnemies)
{
// serialization into arrays of primitive types to speed up the data transfer.
byte[][] merged = this.getMergedObservationZZ(ZLevelScene, ZLevelEnemies);
for (int i = 0; i < serializedMergedObservation.length; ++i)
serializedMergedObservation[i] = (int) merged[i / receptiveFieldWidth][i % receptiveFieldWidth];
return serializedMergedObservation;
}
public float[] getCreaturesFloatPos()
{
return levelScene.getCreaturesFloatPos();
}
public int[] getMarioState()
{
return levelScene.getMarioState();
}
public void performAction(boolean[] action)
{
try
{
if (recorder != null && action != null)
{
recorder.writeAction(action);
recorder.changeRecordingState(GlobalOptions.isRecording, getTimeSpent());
}
} catch (IOException e)
{
e.printStackTrace();
}
levelScene.performAction(action);
}
public boolean isLevelFinished()
{
return levelScene.isLevelFinished();
}
public int[] getEvaluationInfoAsInts()
{
return this.getEvaluationInfo().toIntArray();
}
public String getEvaluationInfoAsString()
{
return this.getEvaluationInfo().toString();
}
public EvaluationInfo getEvaluationInfo()
{
computeEvaluationInfo();
return evaluationInfo;
}
private void computeEvaluationInfo()
{
if (recorder != null)
closeRecorder();
// evaluationInfo.agentType = agent.getClass().getSimpleName();
// evaluationInfo.agentName = agent.getName();
evaluationInfo.marioStatus = levelScene.getMarioStatus();
evaluationInfo.flowersDevoured = Mario.flowersDevoured;
evaluationInfo.distancePassedPhys = (int) levelScene.mario.x;
evaluationInfo.distancePassedCells = levelScene.mario.mapX;
// evaluationInfo.totalLengthOfLevelCells = levelScene.level.getWidthCells();
// evaluationInfo.totalLengthOfLevelPhys = levelScene.level.getWidthPhys();
evaluationInfo.timeSpent = levelScene.getTimeSpent();
evaluationInfo.timeLeft = levelScene.getTimeLeft();
evaluationInfo.coinsGained = Mario.coins;
evaluationInfo.totalNumberOfCoins = levelScene.level.counters.coinsCount;
evaluationInfo.totalNumberOfHiddenBlocks = levelScene.level.counters.hiddenBlocksCount;
evaluationInfo.totalNumberOfFlowers = levelScene.level.counters.flowers;
evaluationInfo.totalNumberOfMushrooms = levelScene.level.counters.mushrooms;
evaluationInfo.totalNumberOfCreatures = levelScene.level.counters.creatures;
evaluationInfo.marioMode = levelScene.getMarioMode();
evaluationInfo.mushroomsDevoured = Mario.mushroomsDevoured;
evaluationInfo.killsTotal = levelScene.getKillsTotal();
evaluationInfo.killsByStomp = levelScene.getKillsByStomp();
evaluationInfo.killsByFire = levelScene.getKillsByFire();
evaluationInfo.killsByShell = levelScene.getKillsByShell();
evaluationInfo.hiddenBlocksFound = Mario.hiddenBlocksFound;
evaluationInfo.collisionsWithCreatures = Mario.collisionsWithCreatures;
evaluationInfo.Memo = levelScene.memo;
evaluationInfo.levelLength = levelScene.level.length;
evaluationInfo.marioTraceFileName = marioTraceFile;
evaluationInfo.marioTrace = levelScene.level.marioTrace;
}
public void setAgent(Agent agent)
{
this.agent = agent;
}
public float getIntermediateReward()
{
// TODO: reward for coins, killed creatures, cleared dead-ends, bypassed gaps, hidden blocks found
return intermediateReward;
}
public int[] getMarioEgoPos()
{
return marioEgoPos;
}
public void closeRecorder()
{
if (recorder != null)
{
try
{
// recorder.closeFile();
recorder.closeRecorder(false, getTimeSpent());
recorder = null;
} catch (IOException e)
{
e.printStackTrace();
}
}
}
public int getTimeSpent()
{
return levelScene.getTimeSpent();
}
public void setReplayer(Replayer replayer)
{
levelScene.setReplayer(replayer);
}
//public void setRecording(boolean isRecording)
// this.isRecording = isRecording;
}
|
package com.sunzn.utils.library;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.ParcelFileDescriptor;
import android.provider.MediaStore;
import android.util.Log;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import static android.content.ContentValues.TAG;
public class FileUtils {
private FileUtils() {
throw new RuntimeException("Stub!");
}
/**
*
*
*
* file
*
* String
*
*/
public static String getExtensionName(File file) {
if (file != null && file.exists()) {
String fileName = file.getName();
return fileName.substring(fileName.lastIndexOf(".") + 1);
} else {
return StringUtils.NULL;
}
}
/**
*
*
*
* context
* drawable
*
* String
*
*/
public static String saveImageToGallery(Context context, String child, Drawable drawable) {
if (drawable instanceof BitmapDrawable) {
return saveImageToGallery(context, child, ((BitmapDrawable) drawable).getBitmap());
} else {
return null;
}
}
/**
*
*
*
* context
* child
* bmp
*
* void
*
*/
public static String saveImageToGallery(Context context, String child, Bitmap bmp) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
String fileName = System.currentTimeMillis() + ".jpg";
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.DISPLAY_NAME, fileName);
values.put(MediaStore.Images.Media.DESCRIPTION, "");
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
values.put(MediaStore.Images.Media.IS_PENDING, 1);
values.put(MediaStore.Images.Media.RELATIVE_PATH, "DCIM/" + child + "/");
Uri url = null;
String stringUrl = null; /* value to be returned */
ContentResolver resolver = context.getContentResolver();
try {
Uri uri = MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY);
url = resolver.insert(uri, values);
if (url == null) {
return null;
}
ParcelFileDescriptor parcelFileDescriptor = resolver.openFileDescriptor(url, "w");
FileOutputStream fileOutputStream = new FileOutputStream(parcelFileDescriptor.getFileDescriptor());
bmp.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
values.clear();
values.put(MediaStore.Images.Media.IS_PENDING, 0);
resolver.update(url, values, null, null);
ToastUtils.success(context, "");
} catch (Exception e) {
Log.e(TAG, "Failed to insert media file", e);
if (url != null) {
resolver.delete(url, null, null);
url = null;
}
ToastUtils.failure(context, "");
}
if (url != null) {
stringUrl = url.toString();
}
return stringUrl;
} else {
File appDir = new File(Environment.getExternalStorageDirectory(), child);
if (!appDir.exists()) {
appDir.mkdir();
}
String fileName = System.currentTimeMillis() + ".jpg";
File file = new File(appDir, fileName);
try {
FileOutputStream fos = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getAbsolutePath(), fileName, null);
ToastUtils.success(context, "");
} catch (FileNotFoundException e) {
ToastUtils.failure(context, "");
e.printStackTrace();
}
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File(appDir.getPath()))));
return file.getAbsolutePath();
}
}
/**
*
*
*
* srcFile
* destFile
*
* boolean true false
*
*/
public static boolean copyFile(File srcFile, File destFile) {
boolean result;
try {
try (InputStream in = new FileInputStream(srcFile)) {
result = saveToFile(in, destFile);
}
} catch (IOException e) {
result = false;
}
return result;
}
/**
*
*
*
* inputStream
* destFile
*
* boolean true false
*
*/
public static boolean saveToFile(InputStream inputStream, File destFile) {
try {
if (destFile.exists()) {
destFile.delete();
}
FileOutputStream out = new FileOutputStream(destFile);
try {
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) >= 0) {
out.write(buffer, 0, bytesRead);
}
} finally {
out.flush();
try {
out.getFD().sync();
} catch (IOException e) {
e.printStackTrace();
}
out.close();
}
return true;
} catch (IOException e) {
return false;
}
}
}
|
package de.volzo.miscreen;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Matrix;
import android.os.Handler;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.os.Bundle;
import android.util.Log;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import de.volzo.miscreen.Message;
import org.artoolkit.ar.base.ARActivity;
import org.artoolkit.ar.base.ARToolKit;
import org.artoolkit.ar.base.rendering.ARRenderer;
import org.ejml.data.DenseMatrix64F;
import org.ejml.simple.SimpleMatrix;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
public class Positioner extends ARActivity {
public static int MARKER_SIZE = 80;
private static final int MY_PERMISSIONS_REQUEST_READ_CONTACTS = 55;
//private int markerID = -1;
private SimpleRenderer arRenderer;
private TextView spRole;
private int counter = 0;
private final Map<String, List<SimpleMatrix>> DISPLAY_CORNERS = new HashMap<>();
public Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
displayPosition();
}
};
private Timer timer;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_positioner);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.CAMERA},
MY_PERMISSIONS_REQUEST_READ_CONTACTS);
}
Client.getInstance().manuallyInjectPositioner(this);
Log.d(TAG, "Setting Camera preferences:");
this.timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
try {
sendTransMatrices();
} catch (Exception e) {
Log.d(TAG, "Sending transformation matrices failed: " + e.toString());
//e.printStackTrace();
}
}
}, 0, 10 * 1000);
drawImage(null);
}
private void drawImage(Matrix matrix) {
ImageView imageView = (ImageView) findViewById(R.id.imageView);
imageView.setImageResource(R.drawable.flunder_lowres);
imageView.setScaleType(ImageView.ScaleType.MATRIX); //required
if (matrix == null) {
matrix = new Matrix();
matrix.postRotate(45, 1280, 720);
matrix.postTranslate(200, 200);
matrix.postScale(0.5f, 0.5f);
}
imageView.setImageMatrix(matrix);
float[] matrixValues = new float[9];
matrix.getValues(matrixValues);
String desc = "Translate X: " + (int) matrixValues[Matrix.MTRANS_X] + "mm\n" +
"Translate Y: " + (int) matrixValues[Matrix.MTRANS_Y] + "mm\n" +
"Scale: " + matrixValues[Matrix.MSCALE_X];
TextView tvMatrixInternals = (TextView) findViewById(R.id.tvMatrixInternals);
tvMatrixInternals.setText(desc);
}
public void sendTransMatrices() throws Exception {
List<SimpleMatrix> matrices = getDeviceCornersTransformationsFromMarker();
Message msg = new Message();
for (SimpleMatrix m : matrices) {
double[] array = Message.convertSimpleMatrixToArray(m);
msg.transformationMatrix3D.add(array);
}
JSONObject json = msg.toJson();
Client.getInstance().send(json);
}
public void receivedResponseFromHost(Message msg) {
// msg should carry one 2D transformation matrix
double[] transM = msg.transformationMatrix2D.get(0);
SimpleMatrix transMM = new SimpleMatrix(3,3, true, transM);
String printM = transMM.toString();
SimpleMatrix imageT = new SimpleMatrix(3,3, true, msg.transformationMatrixImage.get(0));
SimpleMatrix combinedT = imageT.mult(transMM);
// Context context = getApplicationContext();
// int duration = Toast.LENGTH_LONG;
// Toast toast = Toast.makeText(context, printM, duration);
// toast.show();
float[] matrixData = Host.doubleArray2floatArray(combinedT.getMatrix().getData());
Matrix graphicsMatrix = new Matrix();
graphicsMatrix.setValues(matrixData);
drawImage(graphicsMatrix);
}
public List<SimpleMatrix> getDeviceCornersTransformationsFromMarker() throws Exception {
float[] fMarkerToCameraFloat = getTranformationMatrixMarkerToCamera();
SimpleMatrix fMarkerToCamera = new SimpleMatrix(4, 4, false, Host.floatArray2doubleArray(fMarkerToCameraFloat));
List<SimpleMatrix> fCameraToCorners = getDeviceCornersTransformationsFromCamera();
List<SimpleMatrix> fMarkerToCorners = new ArrayList<>();
for (int i = 0; i < fCameraToCorners.size(); ++i) {
SimpleMatrix fCameraToOneCorner = fCameraToCorners.get(i);
SimpleMatrix fMarkerToOneCorner = fCameraToOneCorner.mult(fMarkerToCamera);
fMarkerToCorners.add(fMarkerToOneCorner);
}
return fMarkerToCorners;
}
private List<SimpleMatrix> getDeviceCornersTransformationsFromCamera() {
return Support.getInstance().getDeviceCornersTransformations();
}
// ARToolkit
@Override
protected ARRenderer supplyRenderer() {
this.arRenderer = new SimpleRenderer(mHandler, MARKER_SIZE);
return arRenderer;
}
@Override
protected FrameLayout supplyFrameLayout() {
//this.findViewById(R.id.frameLayoutPositioner).setVisibility(View.INVISIBLE);
return (FrameLayout) this.findViewById(R.id.frameLayoutPositioner);
}
public float[] getTranformationMatrixMarkerToCamera() throws Exception {
int markerID = arRenderer.getMarkerID();
if (markerID == -1) {
throw new Exception("Marker not defined yet");
}
float[] t = ARToolKit.getInstance().queryMarkerTransformation(markerID);
if (t == null || t.length == 0) {
throw new Exception("Marker not visible in camera image");
}
return t;
}
public void displayPosition() {
if (arRenderer != null) {
int markerID = arRenderer.getMarkerID();
if (markerID > -1) {
float[] t = ARToolKit.getInstance().queryMarkerTransformation(markerID);
if (t != null) {
if (counter > 0) {
float offsetX = t[12];
float offsetY = t[13];
float offsetZ = t[14];
double dist = Math.sqrt(offsetX * offsetX + offsetY * offsetY + offsetZ * offsetZ);
String text = "Distance: " + Double.toString(dist);
spRole.setText(text);
Log.d(TAG, Arrays.toString(t));
Log.d(TAG, text + "(X:" + offsetX + " Y:" + offsetY + " Z:" + offsetZ + ")");
counter = 0;
} else {
counter++;
}
}
}
}
}
protected void onDestroy () {
super.onDestroy();
this.timer.cancel();
}
}
|
package lpn.parser;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
public class Transition {
private String name;
private boolean fail = false;
private boolean persistent = false;
private String enabling;
private ExprTree enablingTree;
private String delay;
private ExprTree delayTree;
private String priority;
private ExprTree priorityTree;
private ArrayList<Place> preset;
private ArrayList<Place> postset;
private HashMap<String, String> boolAssignments;
private HashMap<String, ExprTree> boolAssignTrees;
private HashMap<String, String> intAssignments;
private HashMap<String, ExprTree> intAssignTrees;
private HashMap<String, String> contAssignments;
private HashMap<String, ExprTree> contAssignTrees;
private HashMap<String, String> rateAssignments;
private HashMap<String, ExprTree> rateAssignTrees;
private LhpnFile lhpn;
private int index;
//private boolean local;
private List<LhpnFile> dstLpnList = new ArrayList<LhpnFile>();
// public Transition(String name, ArrayList<Variable> variables, LhpnFile lhpn) {
// this.name = name;
// this.lhpn = lhpn;
// preset = new ArrayList<Place>();
// postset = new ArrayList<Place>();
// boolAssignments = new HashMap<String, String>();
// boolAssignTrees = new HashMap<String, ExprTree>();
// intAssignments = new HashMap<String, String>();
// intAssignTrees = new HashMap<String, ExprTree>();
// contAssignments = new HashMap<String, String>();
// contAssignTrees = new HashMap<String, ExprTree>();
// rateAssignments = new HashMap<String, String>();
// rateAssignTrees = new HashMap<String, ExprTree>();
public Transition(String name, int index, LhpnFile lhpn) {
this.name = name;
this.lhpn = lhpn;
this.index = index;
//this.local = local;
preset = new ArrayList<Place>();
postset = new ArrayList<Place>();
boolAssignments = new HashMap<String, String>();
boolAssignTrees = new HashMap<String, ExprTree>();
intAssignments = new HashMap<String, String>();
intAssignTrees = new HashMap<String, ExprTree>();
contAssignments = new HashMap<String, String>();
contAssignTrees = new HashMap<String, ExprTree>();
rateAssignments = new HashMap<String, String>();
rateAssignTrees = new HashMap<String, ExprTree>();
}
public Transition() {
preset = new ArrayList<Place>();
postset = new ArrayList<Place>();
boolAssignments = new HashMap<String, String>();
boolAssignTrees = new HashMap<String, ExprTree>();
intAssignments = new HashMap<String, String>();
intAssignTrees = new HashMap<String, ExprTree>();
contAssignments = new HashMap<String, String>();
contAssignTrees = new HashMap<String, ExprTree>();
rateAssignments = new HashMap<String, String>();
rateAssignTrees = new HashMap<String, ExprTree>();
}
public void addPostset(Place place) {
if (postset != null)
postset.add(place);
else {
postset = new ArrayList<Place>();
postset.add(place);
}
}
public void addPreset(Place place) {
if (preset != null)
preset.add(place);
else {
preset = new ArrayList<Place>();
preset.add(place);
}
}
public boolean addEnabling(String newEnab) {
boolean retVal = false;
if (newEnab == null) {
return false;
}
if (newEnab.equals("")) {
enabling = "";
enablingTree = new ExprTree();
retVal = true;
}
ExprTree expr = new ExprTree(lhpn);
if (newEnab != null && !newEnab.equals("")) {
expr.token = expr.intexpr_gettok(newEnab);
retVal = expr.intexpr_L(newEnab);
if (retVal) {
enablingTree = expr;
enabling = newEnab;
}
}
return retVal;
}
public void addEnablingWithoutLPN(ExprTree newEnab) {
if (newEnab != null)
enablingTree = newEnab;
enabling = newEnab.toString();
}
public boolean addIntAssign(String variable, String assignment) {
boolean retVal;
ExprTree expr = new ExprTree(lhpn);
expr.token = expr.intexpr_gettok(assignment);
retVal = expr.intexpr_L(assignment);
if (retVal) {
intAssignTrees.put(variable, expr);
intAssignments.put(variable, assignment);
}
return retVal;
}
public void addIntAssign(String variable, ExprTree assignment) {
if (intAssignTrees == null && intAssignments == null) {
intAssignTrees = new HashMap<String, ExprTree>();
intAssignments = new HashMap<String, String>();
intAssignTrees.put(variable, assignment);
intAssignments.put(variable, assignment.toString());
}
else if (intAssignTrees == null && intAssignments != null){
intAssignTrees = new HashMap<String, ExprTree>();
intAssignTrees.put(variable, assignment);
intAssignments.put(variable, assignment.toString());
}
else if (intAssignments == null && intAssignTrees != null) {
intAssignments = new HashMap<String, String>();
intAssignTrees.put(variable, assignment);
intAssignments.put(variable, assignment.toString());
}
else {
intAssignTrees.put(variable, assignment);
intAssignments.put(variable, assignment.toString());
}
}
public boolean addContAssign(String variable, String assignment) {
boolean retVal;
ExprTree expr = new ExprTree(lhpn);
expr.token = expr.intexpr_gettok(assignment);
retVal = expr.intexpr_L(assignment);
if (retVal) {
contAssignTrees.put(variable, expr);
contAssignments.put(variable, assignment);
}
return retVal;
}
public boolean addRateAssign(String variable, String assignment) {
boolean retVal;
ExprTree expr = new ExprTree(lhpn);
expr.token = expr.intexpr_gettok(assignment);
retVal = expr.intexpr_L(assignment);
if (retVal) {
rateAssignTrees.put(variable, expr);
rateAssignments.put(variable, assignment);
}
return retVal;
}
public boolean addDelay(String delay) {
if (delay.equals("")) {
this.delay = null;
delayTree = null;
return true;
}
boolean retVal;
if (delay.matches("\\d+?,\\d+?")) {
delay = "uniform(" + delay + ")";
}
ExprTree expr = new ExprTree(lhpn);
expr.token = expr.intexpr_gettok(delay);
retVal = expr.intexpr_L(delay);
if (retVal) {
delayTree = expr;
this.delay = delay;
}
return retVal;
}
public boolean addPriority(String priority) {
if (priority.equals("")) {
this.priority = null;
priorityTree = null;
return true;
}
boolean retVal;
ExprTree expr = new ExprTree(lhpn);
expr.token = expr.intexpr_gettok(priority);
retVal = expr.intexpr_L(priority);
if (retVal) {
priorityTree = expr;
this.priority = priority;
}
return retVal;
}
public boolean addBoolAssign(String variable, String assignment) {
boolean retVal;
ExprTree expr = new ExprTree(lhpn);
expr.token = expr.intexpr_gettok(assignment);
retVal = expr.intexpr_L(assignment);
if (retVal) {
boolAssignTrees.put(variable, expr);
boolAssignments.put(variable, assignment);
}
return retVal;
}
public void setName(String newName) {
this.name = newName;
}
public void setFail(boolean fail) {
this.fail = fail;
}
public void setIndex(int idx) {
this.index = idx;
}
public void setPersistent(boolean persistent) {
this.persistent = persistent;
}
public boolean isFail() {
return fail;
}
public boolean isPersistent() {
return persistent;
}
public boolean isConnected() {
return (preset.size() > 0 || postset.size() > 0);
}
public boolean isInteresting(ArrayList<Transition> visited) {
visited.add(this);
if (boolAssignments.size() > 0 || intAssignments.size() > 0
|| contAssignments.size() > 0 || rateAssignments.size() > 0
|| fail) {
return true;
}
for (Place p : postset) {
for (Transition t : p.getPostset()) {
if (visited.contains(t)) {
continue;
}
if (t.isInteresting(visited)) {
return true;
}
}
}
return false;
}
public boolean hasConflictSet() {
for (Place p : getPreset()) {
for (Transition t : p.getPostset()) {
if (!this.toString().equals(t.toString())) {
return true;
}
}
}
return false;
}
public int getIndex() {
return this.index;
}
public String getName() {
return name;
}
public String getDelay() {
return delay;
}
public String getPriority() {
return priority;
}
public ExprTree getDelayTree() {
return delayTree;
}
public ExprTree getPriorityTree() {
return priorityTree;
}
public String getTransitionRate() {
if (delayTree != null) {
if (delayTree.op.equals("exponential")) {
return delayTree.r1.toString();
}
}
return null;
}
public ExprTree getTransitionRateTree() {
if (delayTree.op.equals("exponential")) {
return delayTree.r1;
}
return null;
}
public Place[] getPreset() {
Place[] array = new Place[preset.size()];
int i = 0;
for (Place p : preset) {
array[i++] = p;
}
return array;
}
public Place[] getPostset() {
Place[] array = new Place[postset.size()];
int i = 0;
for (Place p : postset) {
array[i++] = p;
}
return array;
}
public Transition[] getConflictSet() {
ArrayList<Transition> conflictSet = new ArrayList<Transition>();
for (Place p : getPreset()) {
for (Transition t : p.getPostset()) {
if (!this.toString().equals(t.toString())) {
conflictSet.add(t);
}
}
}
Transition[] returnSet = new Transition[conflictSet.size()];
int i = 0;
for (Transition t : conflictSet) {
returnSet[i] = t;
i++;
}
return returnSet;
}
public Set<String> getConflictSetTransNames() {
Set<String> conflictSet = new HashSet<String>();
for (Place p : getPreset()) {
for (Transition t : p.getPostset()) {
if (!this.toString().equals(t.toString())) {
conflictSet.add(t.getName());
}
}
}
return conflictSet;
}
public Set<Integer> getConflictSetTransIndices() {
Set<Integer> conflictSet = new HashSet<Integer>();
for (Place p : getPreset()) {
for (Transition t : p.getPostset()) {
if (!this.toString().equals(t.toString())) {
conflictSet.add(t.getIndex());
}
}
}
return conflictSet;
}
public String getEnabling() {
return enabling;
}
public ExprTree getEnablingTree() {
return enablingTree;
}
public HashMap<String, String> getAssignments() {
HashMap<String, String> assignments = new HashMap<String, String>();
assignments.putAll(boolAssignments);
assignments.putAll(intAssignments);
assignments.putAll(contAssignments);
for (String var : rateAssignments.keySet()) {
if (assignments.containsKey(var)) {
assignments.put(var + "_rate", rateAssignments.get(var));
} else {
assignments.put(var, rateAssignments.get(var));
}
}
return assignments;
}
public HashMap<String, ExprTree> getAssignTrees() {
HashMap<String, ExprTree> assignments = new HashMap<String, ExprTree>();
assignments.putAll(boolAssignTrees);
assignments.putAll(intAssignTrees);
assignments.putAll(contAssignTrees);
for (String var : rateAssignments.keySet()) {
if (assignments.containsKey(var)) {
assignments.put(var + "_rate", rateAssignTrees.get(var));
} else {
assignments.put(var, rateAssignTrees.get(var));
}
}
return assignments;
}
public ExprTree getAssignTree(String var) {
if (boolAssignTrees.containsKey(var)) {
return getBoolAssignTree(var);
}
if (intAssignTrees.containsKey(var)) {
return getIntAssignTree(var);
}
if (contAssignTrees.containsKey(var)) {
return getContAssignTree(var);
}
if (rateAssignTrees.containsKey(var)) {
return getRateAssignTree(var);
}
if (var.split("\\s").length > 1) {
return getRateAssignTree(var.split("\\s")[0]);
}
return null;
}
public HashMap<String, String> getContAssignments() {
return contAssignments;
}
public HashMap<String, ExprTree> getContAssignTrees() {
return contAssignTrees;
}
public String getContAssignment(String variable) {
return contAssignments.get(variable);
}
public ExprTree getContAssignTree(String variable) {
return contAssignTrees.get(variable);
}
public HashMap<String, String> getIntAssignments() {
return intAssignments;
}
public HashMap<String, ExprTree> getIntAssignTrees() {
return intAssignTrees;
}
public String getIntAssignment(String variable) {
return intAssignments.get(variable);
}
public ExprTree getIntAssignTree(String variable) {
return intAssignTrees.get(variable);
}
public HashMap<String, String> getRateAssignments() {
return rateAssignments;
}
public HashMap<String, ExprTree> getRateAssignTrees() {
return rateAssignTrees;
}
public String getRateAssignment(String variable) {
return rateAssignments.get(variable);
}
public ExprTree getRateAssignTree(String variable) {
return rateAssignTrees.get(variable);
}
public HashMap<String, String> getBoolAssignments() {
return boolAssignments;
}
public HashMap<String, ExprTree> getBoolAssignTrees() {
return boolAssignTrees;
}
public String getBoolAssignment(String variable) {
return boolAssignments.get(variable);
}
public ExprTree getBoolAssignTree(String variable) {
return boolAssignTrees.get(variable);
}
public void renamePlace(Place oldPlace, Place newPlace) {
if (preset.contains(oldPlace)) {
preset.add(newPlace);
preset.remove(oldPlace);
}
if (postset.contains(oldPlace)) {
postset.add(newPlace);
postset.remove(oldPlace);
}
}
public void removeEnabling() {
enabling = null;
enablingTree = null;
}
public void removePreset(Place place) {
preset.remove(place);
}
public void removePostset(Place place) {
postset.remove(place);
}
public void removeAllAssign() {
boolAssignments.clear();
contAssignments.clear();
rateAssignments.clear();
intAssignments.clear();
}
public void removeAssignment(String variable) {
if (contAssignments.containsKey(variable)) {
removeContAssign(variable);
}
if (rateAssignments.containsKey(variable)) {
removeRateAssign(variable);
}
if (intAssignments.containsKey(variable)) {
removeIntAssign(variable);
}
if (boolAssignments.containsKey(variable)) {
removeBoolAssign(variable);
}
if (variable.split("\\s").length > 1) {
removeRateAssign(variable.split("\\s")[0]);
}
}
public void removeBoolAssign(String variable) {
boolAssignments.remove(variable);
boolAssignTrees.remove(variable);
}
public void removeContAssign(String variable) {
contAssignments.remove(variable);
contAssignTrees.remove(variable);
}
public void removeRateAssign(String variable) {
rateAssignments.remove(variable);
rateAssignTrees.remove(variable);
}
public void removeIntAssign(String variable) {
intAssignments.remove(variable);
intAssignTrees.remove(variable);
}
public boolean containsDelay() {
return ((delay != null) && !delay.equals(""));
}
public boolean containsEnabling() {
return ((enabling != null) && !enabling.equals(""));
}
public boolean containsPriority() {
return ((priority != null) && !priority.equals(""));
}
public boolean containsPreset(String name) {
return preset.contains(name);
}
public boolean containsPostset(String name) {
return postset.contains(name);
}
public boolean containsAssignment() {
return (boolAssignments.size() > 0 || intAssignments.size() > 0
|| contAssignments.size() > 0 || rateAssignments.size() > 0);
}
public boolean containsBooleanAssignment() {
return boolAssignments.size() > 0;
}
public boolean containsIntegerAssignment() {
return intAssignments.size() > 0;
}
public boolean containsContinuousAssignment() {
return contAssignments.size() > 0;
}
public boolean containsRateAssignment() {
return rateAssignments.size() > 0;
}
public boolean containsAssignment(String var) {
if (boolAssignments.containsKey(var)) {
return true;
}
if (intAssignments.containsKey(var)) {
return true;
}
if (contAssignments.containsKey(var)) {
return true;
}
if (rateAssignments.containsKey(var)) {
return true;
}
return false;
}
public boolean simplifyExpr(boolean change) {
if (enablingTree != null) {
if (!enabling.equals(enablingTree.toString("LHPN"))) {
change = true;
}
String newEnab = enablingTree.toString("LHPN");
addEnabling(newEnab);
}
if (delayTree != null) {
if (!delay.equals(delayTree.toString("LHPN"))) {
change = true;
}
String newDelay = delayTree.toString("LHPN");
addDelay(newDelay);
}
for (String var : boolAssignTrees.keySet()) {
if (!boolAssignments.get(var).equals(
boolAssignTrees.get(var).toString("boolean", "LHPN"))) {
change = true;
}
boolAssignments.put(var, boolAssignTrees.get(var).toString(
"boolean", "LHPN"));
}
for (String var : intAssignTrees.keySet()) {
if (!intAssignments.get(var).equals(
intAssignTrees.get(var).toString("integer", "LHPN"))) {
change = true;
}
intAssignments.put(var, intAssignTrees.get(var).toString("integer",
"LHPN"));
}
for (String var : contAssignTrees.keySet()) {
if (!contAssignments.get(var).equals(
contAssignTrees.get(var).toString("continuous", "LHPN"))) {
change = true;
}
contAssignments.put(var, contAssignTrees.get(var).toString(
"continuous", "LHPN"));
}
for (String var : rateAssignTrees.keySet()) {
if (!rateAssignments.get(var).equals(
rateAssignTrees.get(var).toString("continuous", "LHPN"))) {
change = true;
}
rateAssignments.put(var, rateAssignTrees.get(var).toString(
"continuous", "LHPN"));
}
return change;
}
public boolean minimizeUniforms(boolean change) {
if (enablingTree != null) {
if (!enabling.equals(enablingTree.minimizeUniforms().toString(
"LHPN"))) {
change = true;
}
enabling = enablingTree.minimizeUniforms().toString("LHPN");
}
if (delayTree != null) {
if (!delay.equals(delayTree.minimizeUniforms().toString("LHPN"))) {
change = true;
}
delay = delayTree.minimizeUniforms().toString("LHPN");
}
for (String var : boolAssignTrees.keySet()) {
if (!boolAssignments.get(var).equals(
boolAssignTrees.get(var).minimizeUniforms().toString(
"boolean", "LHPN"))) {
change = true;
}
boolAssignments.put(var, boolAssignTrees.get(var)
.minimizeUniforms().toString("boolean", "LHPN"));
}
for (String var : intAssignTrees.keySet()) {
if (!intAssignments.get(var).equals(
intAssignTrees.get(var).minimizeUniforms().toString(
"integer", "LHPN"))) {
change = true;
}
intAssignments.put(var, intAssignTrees.get(var).minimizeUniforms()
.toString("integer", "LHPN"));
}
for (String var : contAssignTrees.keySet()) {
if (!contAssignments.get(var).equals(
contAssignTrees.get(var).minimizeUniforms().toString(
"continuous", "LHPN"))) {
change = true;
}
contAssignments.put(var, contAssignTrees.get(var)
.minimizeUniforms().toString("continuous", "LHPN"));
}
for (String var : rateAssignTrees.keySet()) {
if (!rateAssignments.get(var).equals(
rateAssignTrees.get(var).minimizeUniforms().toString(
"continuous", "LHPN"))) {
change = true;
}
rateAssignments.put(var, rateAssignTrees.get(var)
.minimizeUniforms().toString("continuous", "LHPN"));
}
return change;
}
@Override
public String toString() {
return name;
}
public void changeName(String newName) {
name = newName;
}
/**
* @return LPN object containing this LPN transition.
*/
public LhpnFile getLpn() {
return lhpn;
}
/**
* @param lpn - Associated LPN containing this LPN transition.
*/
public void setLpn(LhpnFile lpn) {
this.lhpn = lpn;
}
public boolean isLocal() {
// Returns true if LPNTran only modifies non-output variables.
boolean isLocal = true;
for (String assignVar : this.getAssignments().keySet()) {
if (!this.getLpn().getAllInternals().keySet().contains(assignVar)) {
isLocal = false;
break;
}
}
return isLocal;
}
// public void setLocal(boolean local) {
// this.local = local;
public List<LhpnFile> getDstLpnList(){
return this.dstLpnList;
}
// public void addDstLpn(LhpnFile lpn){
// this.dstLpnList.add(lpn);
public String getFullLabel() {
return this.lhpn.getLabel() + ":" + this.name;
}
/**
* Check if firing 'fired_transition' causes a disabling error.
* @param current_enabled_transitions
* @param next_enabled_transitions
* @return
*/
public Transition disablingError(final LinkedList<Transition> current_enabled_transitions,
LinkedList<Transition> next_enabled_transitions) {
if (current_enabled_transitions == null || current_enabled_transitions.size()==0)
return null;
for(Transition curTran : current_enabled_transitions) {
if (curTran == this)
continue;
boolean disabled = true;
if (next_enabled_transitions != null && next_enabled_transitions.size()!=0) {
for(Transition nextTran : next_enabled_transitions) {
if(curTran == nextTran) {
disabled = false;
break;
}
}
}
if (disabled == true) {
Place[] preset1 = this.getPreset();
Place[] preset2 = curTran.getPreset();
Boolean share=false;
for (int i=0; i < preset1.length && !share; i++) {
for (int j=0; j < preset2.length && !share; j++) {
if (preset1[i].getName().equals(preset2[j].getName())) share=true;
}
}
if (!share) return curTran;
// if(this.sharePreSet(curTran) == false)
// return curTran;
/*
for (Iterator<String> confIter = this.getConflictSetTransNames().iterator(); confIter.hasNext();) {
String tran = confIter.next();
if (curTran.getConflictSetTransNames().contains(tran))
return curTran;
}
*/
}
}
return null;
}
public void setDstLpnList(LhpnFile curLPN) {
String[] allVars = curLPN.getVariables();
boolean foundLPN = false;
if (this.getAssignments() != null) {
Set<String> assignedVars = this.getAssignments().keySet();
for (Iterator<String> assignedVarsIter = assignedVars.iterator(); assignedVarsIter.hasNext();) {
String curVar = assignedVarsIter.next();
for (int i=0; i<allVars.length; i++) {
if (curVar.equals(allVars[i]) && !this.dstLpnList.contains(curLPN)) {
this.dstLpnList.add(curLPN);
foundLPN = true;
break;
}
}
if (foundLPN)
break;
}
}
}
public boolean isSticky() {
// TODO Auto-generated method stub
return false;
}
public void setSticky(boolean b) {
// TODO Auto-generated method stub
}
/* Maybe copy method below is not needed.
public Transition copy(HashMap<String, VarNode> variables){
return new Transition(this.name, this.index, this.preset, this.postset, this.enablingGuard.copy(variables),
this.assignments.copy(variables), this.delayLB, this.delayUB, this.local);
}
*/
}
|
package org.wzj.memcached.node;
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.channel.ChannelFactory;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
import org.wzj.memcached.MemcachedChannelPipelineFactory;
/**
*
* @author Wen
*
*/
public class Connection {
private static final Connection INSTANCE = new Connection();
private ChannelFactory channelFactory;
private ClientBootstrap boostrap;
private boolean init = false ;
private Connection() {
}
public ChannelFuture connect(InetSocketAddress remoteAdd) {
if(init == false ){
throw new RuntimeException(" Not initialized ") ;
}
return boostrap.connect(remoteAdd);
}
public static Connection getInstance() {
return INSTANCE;
}
public void shutdown(){
boostrap.releaseExternalResources();
init = false ;
}
public void init(String[] servers) {
if(init) return ;
channelFactory = new NioClientSocketChannelFactory(
Executors.newCachedThreadPool(),
Executors.newCachedThreadPool(), servers.length );
boostrap = new ClientBootstrap(channelFactory);
boostrap.setPipelineFactory(new MemcachedChannelPipelineFactory());
init = true ;
}
}
|
package it.playfellas.superapp.conveyors;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.utils.Array;
import java.util.Iterator;
import it.playfellas.superapp.CompositeBgSprite;
import it.playfellas.superapp.SimpleSprite;
import it.playfellas.superapp.TileRepr;
import it.playfellas.superapp.TutorialSprite;
import it.playfellas.superapp.listeners.BaseListener;
import it.playfellas.superapp.tiles.Tile;
import it.playfellas.superapp.tiles.TutorialTile;
public class MovingConveyor extends Conveyor {
public static final int RIGHT = 1;
public static final int LEFT = -1;
private float rtt = 5;
private int direction;
private int pixelSpeed;
private boolean running = false;
private float bgFragmentWidth = 1f;
private Texture bgFragmentTexture;
private Texture tileRightTexture;
private Texture tileWrongTexture;
private CompositeBgSprite bgCompositeSprite;
public MovingConveyor(BaseListener listener, float rtt, int direction) {
super(listener);
this.rtt = rtt;
this.direction = direction;
changeRTT(rtt);
}
@Override
public void init(float h, float w, final float relativeY) {
super.init(h, w, relativeY);
updatePixelSpeed();
Gdx.app.postRunnable(new Runnable() {
@Override
public void run() {
// Loading tutorial textures
tileRightTexture = new Texture("_tutorial_right.png");
tileWrongTexture = new Texture("_tutorial_wrong.png");
// Preparing the background
bgFragmentTexture = new Texture("_conveyor_bg_fragment.png");
bgFragmentTexture.setFilter(Texture.TextureFilter.Nearest, Texture.TextureFilter.Linear);
bgFragmentWidth = bgFragmentTexture.getWidth() / 1f;
bgCompositeSprite = new CompositeBgSprite();
float noFloatFragment = width / bgFragmentWidth;
// Rounding
int noFragment = (int) (noFloatFragment) + ((noFloatFragment % 1) == 0 ? 0 : 1);
for (int i = -1; i < noFragment + 1; i++) {
SimpleSprite fragmentSprite = new SimpleSprite(bgFragmentTexture);
fragmentSprite.setBounds(i * bgFragmentWidth, relativeY, bgFragmentWidth, height);
bgCompositeSprite.addSprite(fragmentSprite);
}
setBgSprite(bgCompositeSprite);
}
});
}
@Override
public void update() {
// Moving tiles
if (running) {
lighten();
// Update background
updateBackground();
} else {
darken();
}
// Update tiles
updateTiles();
}
private void updateTiles() {
Iterator<TileRepr> it = new Array.ArrayIterator<TileRepr>(tileReprs, true); //to allow remove pass true
while (it.hasNext()) {
TileRepr tileRepr = it.next();
SimpleSprite tileSprite = tileRepr.getSprite();
if (tileSprite.isLeaving()) {
tileSprite.decreaseSize();
}
if (direction == LEFT) {
tileSprite.incrementX(-pixelSpeed * Gdx.graphics.getDeltaTime());
} else {
tileSprite.incrementX(pixelSpeed * Gdx.graphics.getDeltaTime());
}
if (tileSprite.getX() > width || tileSprite.getX() < -tileSprite.getWidth() || tileSprite.isDead()) {
it.remove();
}
}
}
private void updateBackground() {
Array<SimpleSprite> bgSprites = bgCompositeSprite.getSprites();
boolean shift = false;
if (direction == LEFT) {
if (bgSprites.get(bgSprites.size - 1).getX() < width) {
shift = true;
}
} else {
if (bgSprites.get(0).getX() > 0) {
shift = true;
}
}
for (SimpleSprite sprite : bgSprites) {
if (direction == LEFT) {
if (shift) sprite.setX(sprite.getX() + bgFragmentWidth);
sprite.incrementX(-pixelSpeed * Gdx.graphics.getDeltaTime());
} else {
if (shift) sprite.setX(sprite.getX() - bgFragmentWidth);
sprite.incrementX(pixelSpeed * Gdx.graphics.getDeltaTime());
}
}
}
private void lighten() {
setAlpha(1f);
}
private void darken() {
setAlpha(0f);
// TODO add X image
// new TileRepr(new SimpleSprite(new Texture("x")), null);
}
private void setAlpha(float alpha) {
Array<SimpleSprite> bgSprites = bgCompositeSprite.getSprites();
for (SimpleSprite s : bgSprites) {
s.setAlpha(alpha);
}
}
/* API */
/**
* Starts moving all the tiles on the conveyor.
*/
@Override
public void start() {
running = true;
}
/**
* Stops moving all the tiles on the conveyor.
*/
@Override
public void stop() {
running = false;
}
/**
* Handles a touche event
*/
@Override
public void touch(Vector3 touchPos) {
Iterator<TileRepr> it = new Array.ArrayIterator<TileRepr>(tileReprs);
while (it.hasNext()) {
TileRepr tileRepr = it.next();
Rectangle tileRect = tileRepr.getSprite().getBoundingRectangle();
// enlarge rectangle if the repr is too small
float wh = height * tileHeightMult;
float oldWidth = tileRect.getWidth();
float oldX = tileRect.getX();
float oldY = tileRect.getY();
if (oldWidth < wh) {
tileRect = new Rectangle(
oldX - ((wh - oldWidth) / 2f),
oldY - ((wh - oldWidth) / 2f),
wh, wh // a square
);
}
if (tileRect.contains(touchPos.x, touchPos.y) && !tileRepr.getSprite().isLeaving()) {
listener.onTileClicked(tileRepr.getTile());
tileRepr.getSprite().setLeaving(true);
}
}
}
/**
* @return a boolean that indicates if the conveyor is running.
*/
public boolean isRunning() {
return running;
}
/**
* Change the rtt (Round Trip Time) that is the time a tile spend to go through the conveyor.
*
* @param rtt the new round trip time.
*/
public void changeRTT(float rtt) {
this.rtt = rtt;
updatePixelSpeed();
}
/**
* Change the direction of movement of the conveyor.
*
* @param direction int representing the direction. (LEFT or RIGHT)
*/
public void changeDirection(int direction) {
if (direction != LEFT && direction != RIGHT) {
throw new IllegalArgumentException(
"direction must be 1 or -1. See Conveyor.LEFT and Conveyor.RIGHT");
}
this.direction = direction;
}
/**
* Adds a new tile to the conveyor.
*
* @param tile the tile to be drawn
*/
public void addTile(final Tile tile) {
if (!running) {
return;
}
// Adding the new tile on the libgdx thread. Otherwise the libgdx context wouldn't be available.
Gdx.app.postRunnable(new Runnable() {
@Override
public void run() {
SimpleSprite tileSprite = makeSprite(tile);
tileSprite.setPosition(calculateSpriteX(tileSprite), calculateSpriteY(tileSprite));
TileRepr tileRepr = new TileRepr(tileSprite, tile);
tileReprs.add(tileRepr);
}
});
}
/**
* Adds a new TutorialTile to the conveyor.
*
* @param tutorialTile the TutorialTile to be drawn
*/
@Override
public void addTile(final TutorialTile tutorialTile) {
Gdx.app.postRunnable(new Runnable() {
@Override
public void run() {
SimpleSprite tileSprite = makeSprite(tutorialTile.getTile());
SimpleSprite tileBgSprite;
if (tutorialTile.isRw()) {
tileBgSprite = new SimpleSprite(tileRightTexture);
} else {
tileBgSprite = new SimpleSprite(tileWrongTexture);
}
tileBgSprite.setSize(height, height);
TutorialSprite tutorialSprite = new TutorialSprite(tileBgSprite, tileSprite);
tutorialSprite.setPosition(calculateSpriteX(tutorialSprite), calculateSpriteY(tutorialSprite));
tutorialSprite.setPulse(tutorialTile.isRw());
TileRepr tileRepr = new TileRepr(tutorialSprite, tutorialTile.getTile());
tileReprs.add(tileRepr);
}
});
}
@Override
public void clear() {
for (TileRepr tileRepr : tileReprs) {
tileRepr.getSprite().setLeaving(true);
}
}
private void updatePixelSpeed() {
pixelSpeed = (int) (width / rtt);
}
private float calculateSpriteX(SimpleSprite sprite) {
float tileSize = sprite.getWidth();
float x;
if (direction == LEFT) {
x = (int) width;
} else {
x = 0 - tileSize;
}
return x;
}
}
|
package org.opencb.cellbase.mongodb.db;
import org.opencb.cellbase.core.CellBaseConfiguration;
import org.opencb.cellbase.core.lib.DBAdaptorFactory;
import org.opencb.cellbase.core.lib.api.CpGIslandDBAdaptor;
import org.opencb.cellbase.core.lib.api.CytobandDBAdaptor;
import org.opencb.cellbase.core.lib.api.core.*;
import org.opencb.cellbase.core.lib.api.regulatory.MirnaDBAdaptor;
import org.opencb.cellbase.core.lib.api.regulatory.RegulatoryRegionDBAdaptor;
import org.opencb.cellbase.core.lib.api.regulatory.TfbsDBAdaptor;
import org.opencb.cellbase.core.lib.api.systems.PathwayDBAdaptor;
import org.opencb.cellbase.core.lib.api.systems.ProteinProteinInteractionDBAdaptor;
import org.opencb.cellbase.core.lib.api.variation.*;
import org.opencb.cellbase.mongodb.db.network.PathwayMongoDBAdaptor;
import org.opencb.cellbase.mongodb.db.network.ProteinProteinInteractionMongoDBAdaptor;
import org.opencb.cellbase.mongodb.db.regulatory.RegulatoryRegionMongoDBAdaptor;
import org.opencb.cellbase.mongodb.db.regulatory.TfbsMongoDBAdaptor;
import org.opencb.datastore.core.config.DataStoreServerAddress;
import org.opencb.datastore.mongodb.MongoDBConfiguration;
import org.opencb.datastore.mongodb.MongoDataStore;
import org.opencb.datastore.mongodb.MongoDataStoreManager;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
public class MongoDBAdaptorFactory extends DBAdaptorFactory {
/**
* MongoDataStoreManager acts as singleton by keeping a reference to all databases connections created.
*/
private MongoDataStoreManager mongoDataStoreManager;
// private static Map<String, MongoDataStore> mongoDatastoreFactory;
public MongoDBAdaptorFactory(CellBaseConfiguration cellBaseConfiguration){
super(cellBaseConfiguration);
init();
}
private void init() {
if(mongoDataStoreManager == null) {
String[] hosts = cellBaseConfiguration.getDatabase().getHost().split(",");
List<DataStoreServerAddress> dataStoreServerAddresses = new ArrayList<>(hosts.length);
for (String host : hosts) {
String[] hostPort = host.split(":");
if(hostPort.length == 1) {
dataStoreServerAddresses.add(new DataStoreServerAddress(hostPort[0], 27017));
} else {
dataStoreServerAddresses.add(new DataStoreServerAddress(hostPort[0], Integer.parseInt(hostPort[1])));
}
}
mongoDataStoreManager = new MongoDataStoreManager(dataStoreServerAddresses);
logger.info("MongoDBAdaptorFactory constructor, this should be only be printed once");
}
// logger = LoggerFactory.getLogger(this.getClass());
}
private MongoDataStore createMongoDBDatastore(String species, String assembly) {
/**
Database name has the following pattern in lower case and with no '.' in the name:
cellbase_speciesId_assembly_cellbaseVersion
Example:
cellbase_hsapiens_grch37_v3
**/
// We need to look for the species object in the configuration
CellBaseConfiguration.SpeciesProperties.Species speciesObject = getSpecies(species);
if(speciesObject != null) {
species = speciesObject.getId();
assembly = getAssembly(speciesObject, assembly).toLowerCase();
if (species != null && !species.isEmpty() && assembly != null && !assembly.isEmpty()) {
// Database name is built following the above pattern
String database = "cellbase" + "_" + species + "_" + assembly.replaceAll("\\.", "_") + "_" + cellBaseConfiguration.getVersion();
logger.debug("Database for the species is '{}'", database);
MongoDBConfiguration mongoDBConfiguration;
// For authenticated databases
if(!cellBaseConfiguration.getDatabase().getUser().isEmpty()
&& !cellBaseConfiguration.getDatabase().getPassword().isEmpty()) {
// MongoDB could authenticate against different databases
if(cellBaseConfiguration.getDatabase().getOptions().containsKey("authenticationDatabase")) {
mongoDBConfiguration = MongoDBConfiguration.builder()
.add("username", cellBaseConfiguration.getDatabase().getUser())
.add("password", cellBaseConfiguration.getDatabase().getPassword())
.add("readPreference", cellBaseConfiguration.getDatabase().getOptions().get("readPreference"))
.add("authenticationDatabase", cellBaseConfiguration.getDatabase().getOptions().get("authenticationDatabase"))
.build();
} else {
mongoDBConfiguration = MongoDBConfiguration.builder()
.add("username", cellBaseConfiguration.getDatabase().getUser())
.add("password", cellBaseConfiguration.getDatabase().getPassword())
.add("readPreference", cellBaseConfiguration.getDatabase().getOptions().get("readPreference"))
.build();
}
} else {
mongoDBConfiguration = MongoDBConfiguration.builder().init().build();
}
// A MongoDataStore to this host and database is returned
MongoDataStore mongoDatastore = mongoDataStoreManager.get(database, mongoDBConfiguration);
// we return the MongoDataStore object
return mongoDatastore;
} else {
logger.error("Species name or assembly are not valid, species '{}', assembly '{}'", species, assembly);
return null;
}
} else {
logger.error("Species name is not valid: '{}'", species);
return null;
}
}
@Override
public void setConfiguration(CellBaseConfiguration cellBaseConfiguration) {
if (cellBaseConfiguration != null) {
this.cellBaseConfiguration = cellBaseConfiguration;
}
}
@Override
public void open(String species, String assembly) {
}
@Override
public void close() {
}
@Override
public GenomeSequenceDBAdaptor getGenomeSequenceDBAdaptor(String species) {
return getGenomeSequenceDBAdaptor(species, null);
}
@Override
public GenomeSequenceDBAdaptor getGenomeSequenceDBAdaptor(String species, String assembly) {
MongoDataStore mongoDataStore = createMongoDBDatastore(species, assembly);
return new GenomeSequenceMongoDBAdaptor(species, assembly, mongoDataStore);
}
@Override
public ChromosomeDBAdaptor getChromosomeDBAdaptor(String species) {
return getChromosomeDBAdaptor(species, null);
}
@Override
public ChromosomeDBAdaptor getChromosomeDBAdaptor(String species, String assembly) {
MongoDataStore mongoDatastore = createMongoDBDatastore(species, assembly);
return new ChromosomeMongoDBAdaptor(species, assembly, mongoDatastore);
}
@Override
public ConservedRegionDBAdaptor getConservedRegionDBAdaptor(String species) {
return getConservedRegionDBAdaptor(species, null);
}
@Override
public ConservedRegionDBAdaptor getConservedRegionDBAdaptor(String species, String assembly) {
MongoDataStore mongoDatastore = createMongoDBDatastore(species, assembly);
return new ConservationMongoDBAdaptor(species, assembly, mongoDatastore);
}
@Override
public ExonDBAdaptor getExonDBAdaptor(String species) {
return getExonDBAdaptor(species, null);
}
@Override
public ExonDBAdaptor getExonDBAdaptor(String species, String assembly) {
MongoDataStore mongoDatastore = createMongoDBDatastore(species, assembly);
return new ExonMongoDBAdaptor(species, assembly, mongoDatastore);
}
@Override
public TranscriptDBAdaptor getTranscriptDBAdaptor(String species) {
return getTranscriptDBAdaptor(species, null);
}
@Override
public TranscriptDBAdaptor getTranscriptDBAdaptor(String species, String assembly) {
MongoDataStore mongoDatastore = createMongoDBDatastore(species, assembly);
return new TranscriptMongoDBAdaptor(species, assembly, mongoDatastore);
}
@Override
public GeneDBAdaptor getGeneDBAdaptor(String species) {
return getGeneDBAdaptor(species, null);
}
@Override
public GeneDBAdaptor getGeneDBAdaptor(String species, String assembly) {
MongoDataStore mongoDatastore = createMongoDBDatastore(species, assembly);
return new GeneMongoDBAdaptor(species, assembly, mongoDatastore);
}
@Override
public XRefsDBAdaptor getXRefDBAdaptor(String species) {
return getXRefDBAdaptor(species, null);
}
@Override
public XRefsDBAdaptor getXRefDBAdaptor(String species, String assembly) {
MongoDataStore mongoDatastore = createMongoDBDatastore(species, assembly);
return new XRefsMongoDBAdaptor(species, assembly, mongoDatastore);
}
@Override
public VariationDBAdaptor getVariationDBAdaptor(String species) {
return getVariationDBAdaptor(species, null);
}
@Override
public VariationDBAdaptor getVariationDBAdaptor(String species, String assembly) {
MongoDataStore mongoDatastore = createMongoDBDatastore(species, assembly);
return new VariationMongoDBAdaptor(species, assembly, mongoDatastore);
}
@Override
public VariantAnnotationDBAdaptor getVariantAnnotationDBAdaptor(String species) {
return getVariantAnnotationDBAdaptor(species, null);
}
@Override
public VariantAnnotationDBAdaptor getVariantAnnotationDBAdaptor(String species, String assembly) {
MongoDataStore mongoDatastore = createMongoDBDatastore(species, assembly);
VariantAnnotationDBAdaptor variantAnnotationDBAdaptor = new VariantAnnotationMongoDBAdaptor(species, assembly,
mongoDatastore);
variantAnnotationDBAdaptor.setGeneDBAdaptor(getGeneDBAdaptor(species, assembly));
variantAnnotationDBAdaptor.setRegulatoryRegionDBAdaptor(getRegulatoryRegionDBAdaptor(species, assembly));
variantAnnotationDBAdaptor.setVariationDBAdaptor(getVariationDBAdaptor(species, assembly));
variantAnnotationDBAdaptor.setVariantClinicalDBAdaptor(getClinicalDBAdaptor(species, assembly));
variantAnnotationDBAdaptor.setProteinFunctionPredictorDBAdaptor(getProteinFunctionPredictorDBAdaptor(species, assembly));
variantAnnotationDBAdaptor.setConservedRegionDBAdaptor(getConservedRegionDBAdaptor(species, assembly));
return variantAnnotationDBAdaptor;
}
@Override
public ClinicalDBAdaptor getClinicalDBAdaptor(String species) {
return getClinicalDBAdaptor(species, null);
}
@Override
public ClinicalDBAdaptor getClinicalDBAdaptor(String species, String assembly) {
MongoDataStore mongoDatastore = createMongoDBDatastore(species, assembly);
return new ClinicalMongoDBAdaptor(species, assembly, mongoDatastore);
}
@Override
public ProteinDBAdaptor getProteinDBAdaptor(String species) {
return getProteinDBAdaptor(species, null);
}
@Override
public ProteinDBAdaptor getProteinDBAdaptor(String species, String assembly) {
MongoDataStore mongoDatastore = createMongoDBDatastore(species, assembly);
return new ProteinMongoDBAdaptor(species, assembly, mongoDatastore);
}
@Override
public ProteinFunctionPredictorDBAdaptor getProteinFunctionPredictorDBAdaptor(String species) {
return getProteinFunctionPredictorDBAdaptor(species, null);
}
@Override
public ProteinFunctionPredictorDBAdaptor getProteinFunctionPredictorDBAdaptor(String species, String assembly) {
MongoDataStore mongoDatastore = createMongoDBDatastore(species, assembly);
return new ProteinFunctionPredictorMongoDBAdaptor(species, assembly, mongoDatastore);
}
@Override
public ProteinProteinInteractionDBAdaptor getProteinProteinInteractionDBAdaptor(String species) {
return getProteinProteinInteractionDBAdaptor(species, null);
}
@Override
public ProteinProteinInteractionDBAdaptor getProteinProteinInteractionDBAdaptor(String species, String assembly) {
MongoDataStore mongoDatastore = createMongoDBDatastore(species, assembly);
return new ProteinProteinInteractionMongoDBAdaptor(species, assembly, mongoDatastore);
}
@Override
public RegulatoryRegionDBAdaptor getRegulatoryRegionDBAdaptor(String species) {
return getRegulatoryRegionDBAdaptor(species, null);
}
@Override
public RegulatoryRegionDBAdaptor getRegulatoryRegionDBAdaptor(String species, String assembly) {
MongoDataStore mongoDatastore = createMongoDBDatastore(species, assembly);
return new RegulatoryRegionMongoDBAdaptor(species, assembly, mongoDatastore);
}
@Override
public TfbsDBAdaptor getTfbsDBAdaptor(String species) {
return getTfbsDBAdaptor(species, null);
}
@Override
public TfbsDBAdaptor getTfbsDBAdaptor(String species, String assembly) {
MongoDataStore mongoDatastore = createMongoDBDatastore(species, assembly);
return new TfbsMongoDBAdaptor(species, assembly, mongoDatastore);
}
@Override
public PathwayDBAdaptor getPathwayDBAdaptor(String species) {
return getPathwayDBAdaptor(species, null);
}
@Override
public PathwayDBAdaptor getPathwayDBAdaptor(String species, String assembly) {
MongoDataStore mongoDatastore = createMongoDBDatastore(species, assembly);
return new PathwayMongoDBAdaptor(species, assembly, mongoDatastore);
}
@Override
public VariationPhenotypeAnnotationDBAdaptor getVariationPhenotypeAnnotationDBAdaptor(String species) {
return getVariationPhenotypeAnnotationDBAdaptor(species, null);
}
@Override
public VariationPhenotypeAnnotationDBAdaptor getVariationPhenotypeAnnotationDBAdaptor(String species, String assembly) {
MongoDataStore mongoDatastore = createMongoDBDatastore(species, assembly);
return (VariationPhenotypeAnnotationDBAdaptor) new VariationPhenotypeAnnotationMongoDBAdaptor(species, assembly, mongoDatastore);
}
@Override
public CpGIslandDBAdaptor getCpGIslandDBAdaptor(String species) {
// TODO Auto-generated method stub
return null;
}
@Override
public CpGIslandDBAdaptor getCpGIslandDBAdaptor(String species, String assembly) {
// TODO Auto-generated method stub
return null;
}
@Override
public StructuralVariationDBAdaptor getStructuralVariationDBAdaptor(String species) {
// TODO Auto-generated method stub
return null;
}
@Override
public StructuralVariationDBAdaptor getStructuralVariationDBAdaptor(String species, String assembly) {
// TODO Auto-generated method stub
return null;
}
@Override
public SnpDBAdaptor getSnpDBAdaptor(String species) {
// TODO Auto-generated method stub
return null;
}
@Override
public SnpDBAdaptor getSnpDBAdaptor(String species, String assembly) {
// TODO Auto-generated method stub
return null;
}
@Override
public CytobandDBAdaptor getCytobandDBAdaptor(String species) {
// TODO Auto-generated method stub
return null;
}
@Override
public MirnaDBAdaptor getMirnaDBAdaptor(String species) {
// TODO Auto-generated method stub
return null;
}
@Override
public MirnaDBAdaptor getMirnaDBAdaptor(String species, String assembly) {
// TODO Auto-generated method stub
return null;
}
@Deprecated
@Override
public VariantEffectDBAdaptor getGenomicVariantEffectDBAdaptor(String species) {
return getGenomicVariantEffectDBAdaptor(species, null);
}
@Deprecated
@Override
public VariantEffectDBAdaptor getGenomicVariantEffectDBAdaptor(String species, String assembly) {
MongoDataStore mongoDatastore = createMongoDBDatastore(species, assembly);
return new VariantEffectMongoDBAdaptor(species, assembly, mongoDatastore);
}
@Override
public MutationDBAdaptor getMutationDBAdaptor(String species) {
return getMutationDBAdaptor(species, null);
}
@Deprecated
@Override
public MutationDBAdaptor getMutationDBAdaptor(String species, String assembly) {
MongoDataStore mongoDatastore = createMongoDBDatastore(species, assembly);
return (MutationDBAdaptor) new MutationMongoDBAdaptor(species, assembly, mongoDatastore);
}
@Override
public ClinVarDBAdaptor getClinVarDBAdaptor(String species) {
return getClinVarDBAdaptor(species, null);
}
@Override
public ClinVarDBAdaptor getClinVarDBAdaptor(String species, String assembly) {
MongoDataStore mongoDatastore = createMongoDBDatastore(species, assembly);
return (ClinVarDBAdaptor) new ClinVarMongoDBAdaptor(species, assembly, mongoDatastore);
}
@Override
public CytobandDBAdaptor getCytobandDBAdaptor(String species, String assembly) {
// TODO Auto-generated method stub
return null;
}
}
|
package com.mikepenz.fastadapter;
import android.os.Bundle;
import android.support.v4.util.ArrayMap;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.util.SparseIntArray;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import com.mikepenz.fastadapter.utils.AdapterUtil;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
public class FastAdapter<Item extends IItem> extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
protected static final String BUNDLE_SELECTIONS = "bundle_selections";
protected static final String BUNDLE_EXPANDED = "bundle_expanded";
// we remember all adapters
private ArrayMap<Integer, IAdapter<Item>> mAdapters = new ArrayMap<>();
// we remember all possible types so we can create a new view efficiently
private ArrayMap<Integer, Item> mTypeInstances = new ArrayMap<>();
// if enabled we will select the item via a notifyItemChanged -> will animate with the Animator
// you can also use this if you have any custom logic for selections, and do not depend on the "selected" state of the view
// note if enabled it will feel a bit slower because it will animate the selection
private boolean mSelectWithItemUpdate = false;
// if we want multiSelect enabled
private boolean mMultiSelect = false;
// if we want the multiSelect only on longClick
private boolean mMultiSelectOnLongClick = true;
// if a user can deselect a selection via click. required if there is always one selected item!
private boolean mAllowDeselection = true;
// we need to remember all selections to recreate them after orientation change
private SortedSet<Integer> mSelections = new TreeSet<>();
// we need to remember all expanded items to recreate them after orientation change
private SparseIntArray mExpanded = new SparseIntArray();
// the listeners which can be hooked on an item
private OnClickListener<Item> mOnClickListener;
private OnClickListener<Item> mOnPostClickListener;
private OnLongClickListener<Item> mOnLongClickListener;
private OnLongClickListener<Item> mOnPostLongClickListener;
private OnTouchListener<Item> mOnTouchListener;
//the listeners for onCreateViewHolder or onBindViewHolder
private OnCreateViewHolderListener mOnCreateViewHolderListener = new OnCreateViewHolderListenerImpl();
private OnBindViewHolderListener mOnBindViewHolderListener = new OnBindViewHolderListenerImpl();
/**
* default CTOR
*/
public FastAdapter() {
setHasStableIds(true);
}
/**
* Define the OnClickListener which will be used for a single item
*
* @param onClickListener the OnClickListener which will be used for a single item
* @return this
*/
public FastAdapter<Item> withOnClickListener(OnClickListener<Item> onClickListener) {
this.mOnClickListener = onClickListener;
return this;
}
/**
* Define the OnPostClickListener which will be used for a single item and is called after all internal methods are done
*
* @param onPostClickListener the OnPostClickListener which will be called after a single item was clicked and all internal methods are done
* @return this
*/
public FastAdapter<Item> withOnPostClickListener(OnClickListener<Item> onPostClickListener) {
this.mOnPostClickListener = onPostClickListener;
return this;
}
/**
* Define the OnLongClickListener which will be used for a single item
*
* @param onLongClickListener the OnLongClickListener which will be used for a single item
* @return this
*/
public FastAdapter<Item> withOnLongClickListener(OnLongClickListener<Item> onLongClickListener) {
this.mOnLongClickListener = onLongClickListener;
return this;
}
/**
* Define the OnLongClickListener which will be used for a single item and is called after all internal methods are done
*
* @param onPostLongClickListener the OnLongClickListener which will be called after a single item was clicked and all internal methods are done
* @return this
*/
public FastAdapter<Item> withOnPostLongClickListener(OnLongClickListener<Item> onPostLongClickListener) {
this.mOnPostLongClickListener = onPostLongClickListener;
return this;
}
/**
* Define the TouchListener which will be used for a single item
*
* @param onTouchListener the TouchListener which will be used for a single item
* @return this
*/
public FastAdapter<Item> withOnTouchListener(OnTouchListener<Item> onTouchListener) {
this.mOnTouchListener = onTouchListener;
return this;
}
/**
* select between the different selection behaviors.
* there are now 2 different variants of selection. you can toggle this via `withSelectWithItemUpdate(boolean)` (where false == default - variant 1)
* 1.) direct selection via the view "selected" state, we also make sure we do not animate here so no notifyItemChanged is called if we repeatly press the same item
* 2.) we select the items via a notifyItemChanged. this will allow custom selected logics within your views (isSelected() - do something...) and it will also animate the change via the provided itemAnimator. because of the animation of the itemAnimator the selection will have a small delay (time of animating)
*
* @param selectWithItemUpdate true if notifyItemChanged should be called upon select
* @return this
*/
public FastAdapter<Item> withSelectWithItemUpdate(boolean selectWithItemUpdate) {
this.mSelectWithItemUpdate = selectWithItemUpdate;
return this;
}
/**
* Enable this if you want multiSelection possible in the list
*
* @param multiSelect true to enable multiSelect
* @return this
*/
public FastAdapter<Item> withMultiSelect(boolean multiSelect) {
mMultiSelect = multiSelect;
return this;
}
/**
* Disable this if you want the multiSelection on a single tap (note you have to enable multiSelect for this to make a difference)
*
* @param multiSelectOnLongClick false to do multiSelect via single click
* @return this
*/
public FastAdapter<Item> withMultiSelectOnLongClick(boolean multiSelectOnLongClick) {
mMultiSelectOnLongClick = multiSelectOnLongClick;
return this;
}
/**
* If false, a user can't deselect an item via click (you can still do this programmatically)
*
* @param allowDeselection true if a user can deselect an already selected item via click
* @return this
*/
public FastAdapter<Item> withAllowDeselection(boolean allowDeselection) {
this.mAllowDeselection = allowDeselection;
return this;
}
/**
* re-selects all elements stored in the savedInstanceState
* IMPORTANT! Call this method only after all items where added to the adapters again. Otherwise it may select wrong items!
*
* @param savedInstanceState If the activity is being re-initialized after
* previously being shut down then this Bundle contains the data it most
* recently supplied in Note: Otherwise it is null.
* @return this
*/
public FastAdapter<Item> withSavedInstanceState(Bundle savedInstanceState) {
return withSavedInstanceState(savedInstanceState, "");
}
/**
* re-selects all elements stored in the savedInstanceState
* IMPORTANT! Call this method only after all items where added to the adapters again. Otherwise it may select wrong items!
*
* @param savedInstanceState If the activity is being re-initialized after
* previously being shut down then this Bundle contains the data it most
* recently supplied in Note: Otherwise it is null.
* @param prefix a prefix added to the savedInstance key so we can store multiple states
* @return this
*/
public FastAdapter<Item> withSavedInstanceState(Bundle savedInstanceState, String prefix) {
if (savedInstanceState != null) {
//make sure already done selections are removed
deselect();
//first restore opened collasable items, as otherwise may not all selections could be restored
int[] expandedItems = savedInstanceState.getIntArray(BUNDLE_EXPANDED + prefix);
if (expandedItems != null) {
for (Integer expandedItem : expandedItems) {
expand(expandedItem);
}
}
//restore the selections
int[] selections = savedInstanceState.getIntArray(BUNDLE_SELECTIONS + prefix);
if (selections != null) {
for (Integer selection : selections) {
select(selection);
}
}
}
return this;
}
/**
* registers an AbstractAdapter which will be hooked into the adapter chain
*
* @param adapter an adapter which extends the AbstractAdapter
*/
public <A extends AbstractAdapter<Item>> void registerAdapter(A adapter) {
if (!mAdapters.containsKey(adapter.getOrder())) {
mAdapters.put(adapter.getOrder(), adapter);
}
}
/**
* register a new type into the TypeInstances to be able to efficiently create thew ViewHolders
*
* @param item an IItem which will be shown in the list
*/
public void registerTypeInstance(Item item) {
if (!mTypeInstances.containsKey(item.getType())) {
mTypeInstances.put(item.getType(), item);
}
}
/**
* @return all typeInstances remembered within the FastAdapter
*/
public Map<Integer, Item> getTypeInstances() {
return mTypeInstances;
}
/**
* Creates the ViewHolder by the viewType
*
* @param parent the parent view (the RecyclerView)
* @param viewType the current viewType which is bound
* @return the ViewHolder with the bound data
*/
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
final RecyclerView.ViewHolder holder = mOnCreateViewHolderListener.onPreCreateViewHolder(parent, viewType);
//handle click behavior
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int pos = holder.getAdapterPosition();
if (pos != RecyclerView.NO_POSITION) {
boolean consumed = false;
RelativeInfo<Item> relativeInfo = getRelativeInfo(pos);
if (relativeInfo.item != null && relativeInfo.item.isEnabled()) {
if (mOnClickListener != null) {
consumed = mOnClickListener.onClick(v, relativeInfo.adapter, relativeInfo.item, pos);
}
if (!consumed && (!(mMultiSelect && mMultiSelectOnLongClick) || !mMultiSelect)) {
handleSelection(v, relativeInfo.item, pos);
}
if (mOnPostClickListener != null) {
mOnPostClickListener.onClick(v, relativeInfo.adapter, relativeInfo.item, pos);
}
}
}
}
});
//handle long click behavior
holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
int pos = holder.getAdapterPosition();
if (pos != RecyclerView.NO_POSITION) {
boolean consumed = false;
RelativeInfo<Item> relativeInfo = getRelativeInfo(pos);
if (relativeInfo.item != null && relativeInfo.item.isEnabled()) {
if (mOnLongClickListener != null) {
consumed = mOnLongClickListener.onLongClick(v, relativeInfo.adapter, relativeInfo.item, pos);
}
if (!consumed && (mMultiSelect && mMultiSelectOnLongClick)) {
handleSelection(v, relativeInfo.item, pos);
}
if (mOnPostLongClickListener != null) {
consumed = mOnPostLongClickListener.onLongClick(v, relativeInfo.adapter, relativeInfo.item, pos);
}
}
return consumed;
}
return false;
}
});
//handle touch behavior
holder.itemView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (mOnTouchListener != null) {
int pos = holder.getAdapterPosition();
if (pos != RecyclerView.NO_POSITION) {
RelativeInfo<Item> relativeInfo = getRelativeInfo(pos);
return mOnTouchListener.onTouch(v, event, relativeInfo.adapter, relativeInfo.item, pos);
}
}
return false;
}
});
return mOnCreateViewHolderListener.onPostCreateViewHolder(holder);
}
/**
* Binds the data to the created ViewHolder and sets the listeners to the holder.itemView
*
* @param holder the viewHolder we bind the data on
* @param position the global position
*/
@Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
mOnBindViewHolderListener.onBindViewHolder(holder, position);
}
/**
* Searches for the given item and calculates it's global position
*
* @param item the item which is searched for
* @return the global position, or -1 if not found
*/
public int getPosition(Item item) {
if (item.getIdentifier() == -1) {
Log.e("FastAdapter", "You have to define an identifier for your item to retrieve the position via this method");
return -1;
}
int position = 0;
int length = mAdapters.size();
for (int i = 0; i < length; i++) {
IAdapter<Item> adapter = mAdapters.valueAt(i);
if (adapter.getOrder() < 0) {
continue;
}
int relativePosition = adapter.getAdapterPosition(item);
if (relativePosition != -1) {
return position + relativePosition;
}
position = adapter.getAdapterItemCount();
}
return -1;
}
/**
* gets the IItem by a position, from all registered adapters
*
* @param position the global position
* @return the found IItem or null
*/
public Item getItem(int position) {
return getRelativeInfo(position).item;
}
/**
* Internal method to get the Item as ItemHolder which comes with the relative position within it's adapter
* Finds the responsible adapter for the given position
*
* @param position the global position
* @return the adapter which is responsible for this position
*/
public RelativeInfo<Item> getRelativeInfo(int position) {
if (position < 0) {
return new RelativeInfo<>();
}
RelativeInfo<Item> relativeInfo = new RelativeInfo<>();
IAdapter<Item> adapter = getAdapter(position);
if (adapter != null) {
relativeInfo.item = adapter.getAdapterItem(position - getItemCount(adapter.getOrder()));
relativeInfo.adapter = adapter;
}
return relativeInfo;
}
/**
* Gets the adapter for the given position
*
* @param position the global position
* @return the adapter responsible for this global position
*/
public IAdapter<Item> getAdapter(int position) {
int currentCount = 0;
int length = mAdapters.size();
for (int i = 0; i < length; i++) {
IAdapter<Item> adapter = mAdapters.valueAt(i);
if (adapter.getOrder() < 0) {
continue;
}
if (currentCount <= position && currentCount + adapter.getAdapterItemCount() > position) {
return adapter;
}
currentCount = currentCount + adapter.getAdapterItemCount();
}
return null;
}
/**
* finds the int ItemViewType from the IItem which exists at the given position
*
* @param position the global position
* @return the viewType for this position
*/
@Override
public int getItemViewType(int position) {
return getItem(position).getType();
}
/**
* finds the int ItemId from the IItem which exists at the given position
*
* @param position the global position
* @return the itemId for this position
*/
@Override
public long getItemId(int position) {
return getItem(position).getIdentifier();
}
/**
* calculates the total ItemCount over all registered adapters
*
* @return the global count
*/
@Override
public int getItemCount() {
//we go over all adapters and fetch all item sizes
int size = 0;
int length = mAdapters.size();
for (int i = 0; i < length; i++) {
IAdapter adapter = mAdapters.valueAt(i);
if (adapter.getOrder() < 0) {
continue;
}
size = size + adapter.getAdapterItemCount();
}
return size;
}
/**
* calculates the item count up to a given (excluding this) order number
*
* @param order the number up to which the items are counted
* @return the total count of items up to the adapter order
*/
public int getItemCount(int order) {
//we go over all adapters and fetch all item sizes
int size = 0;
int length = mAdapters.size();
for (int i = 0; i < length; i++) {
IAdapter adapter = mAdapters.valueAt(i);
if (adapter.getOrder() < 0) {
continue;
}
if (adapter.getOrder() < order) {
size = adapter.getAdapterItemCount();
} else {
return size;
}
}
return size;
}
/**
* add the values to the bundle for saveInstanceState
*
* @param savedInstanceState If the activity is being re-initialized after
* previously being shut down then this Bundle contains the data it most
* recently supplied in Note: Otherwise it is null.
* @return the passed bundle with the newly added data
*/
public Bundle saveInstanceState(Bundle savedInstanceState) {
return saveInstanceState(savedInstanceState, "");
}
/**
* add the values to the bundle for saveInstanceState
*
* @param savedInstanceState If the activity is being re-initialized after
* previously being shut down then this Bundle contains the data it most
* recently supplied in Note: Otherwise it is null.
* @param prefix a prefix added to the savedInstance key so we can store multiple states
* @return the passed bundle with the newly added data
*/
public Bundle saveInstanceState(Bundle savedInstanceState, String prefix) {
if (savedInstanceState != null) {
//remember the selections
int[] selections = new int[mSelections.size()];
int index = 0;
for (Integer selection : mSelections) {
selections[index] = selection;
index++;
}
savedInstanceState.putIntArray(BUNDLE_SELECTIONS + prefix, selections);
//remember the collapsed states
savedInstanceState.putIntArray(BUNDLE_EXPANDED + prefix, getExpandedItems());
}
return savedInstanceState;
}
//Selection stuff
/**
* @return a set with the global positions of all selected items
*/
public Set<Integer> getSelections() {
return mSelections;
}
/**
* @return a set with the items which are currently selected
*/
public Set<Item> getSelectedItems() {
Set<Item> items = new HashSet<>();
for (Integer position : getSelections()) {
items.add(getItem(position));
}
return items;
}
/**
* toggles the selection of the item at the given position
*
* @param position the global position
*/
public void toggleSelection(int position) {
if (mSelections.contains(position)) {
deselect(position);
} else {
select(position);
}
}
/**
* handles the selection and deselects item if multiSelect is disabled
*
* @param position the global position
*/
private void handleSelection(View view, Item item, int position) {
//if this item is not selectable don't continue
if (!item.isSelectable()) {
return;
}
//if we have disabled deselection via click don't continue
if (item.isSelected() && !mAllowDeselection) {
return;
}
boolean selected = mSelections.contains(position);
if (mSelectWithItemUpdate || view == null) {
if (!mMultiSelect) {
deselect();
}
if (selected) {
deselect(position);
} else {
select(position);
}
} else {
if (!mMultiSelect) {
//we have to separately handle deselection here because if we toggle the current item we do not want to deselect this first!
Iterator<Integer> entries = mSelections.iterator();
while (entries.hasNext()) {
//deselect all but the current one! this is important!
Integer pos = entries.next();
if (pos != position) {
deselect(pos, entries);
}
}
}
//we toggle the state of the view
item.withSetSelected(!selected);
view.setSelected(!selected);
//now we make sure we remember the selection!
if (selected) {
if (mSelections.contains(position)) {
mSelections.remove(position);
}
} else {
mSelections.add(position);
}
}
}
/**
* selects all items at the positions in the iteratable
*
* @param positions the global positions to select
*/
public void select(Iterable<Integer> positions) {
for (Integer position : positions) {
select(position);
}
}
/**
* selects an item and remembers it's position in the selections list
*
* @param position the global position
*/
public void select(int position) {
select(position, false);
}
/**
* selects an item and remembers it's position in the selections list
*
* @param position the global position
* @param fireEvent true if the onClick listener should be called
*/
public void select(int position, boolean fireEvent) {
Item item = getItem(position);
if (item != null) {
item.withSetSelected(true);
mSelections.add(position);
}
notifyItemChanged(position);
if (mOnClickListener != null && fireEvent) {
mOnClickListener.onClick(null, getAdapter(position), item, position);
}
}
/**
* deselects all selections
*/
public void deselect() {
deselect(mSelections);
}
/**
* deselects all items at the positions in the iteratable
*
* @param positions the global positions to deselect
*/
public void deselect(Iterable<Integer> positions) {
Iterator<Integer> entries = positions.iterator();
while (entries.hasNext()) {
deselect(entries.next(), entries);
}
}
/**
* deselects an item and removes it's position in the selections list
*
* @param position the global position
*/
public void deselect(int position) {
deselect(position, null);
}
/**
* deselects an item and removes it's position in the selections list
* also takes an iterator to remove items from the map
*
* @param position the global position
* @param entries the iterator which is used to deselect all
*/
private void deselect(int position, Iterator<Integer> entries) {
Item item = getItem(position);
if (item != null) {
item.withSetSelected(false);
}
if (entries == null) {
if (mSelections.contains(position)) {
mSelections.remove(position);
}
} else {
entries.remove();
}
notifyItemChanged(position);
}
/**
* deletes all current selected items
*
* @return a list of the IItem elements which were deleted
*/
public List<Item> deleteAllSelectedItems() {
List<Item> deletedItems = new LinkedList<>();
//we have to refetch the selections array again and again as the position will change after one item is deleted
Set<Integer> selections = getSelections();
while (selections.size() > 0) {
Iterator<Integer> iterator = selections.iterator();
int position = iterator.next();
IAdapter adapter = getAdapter(position);
if (adapter != null && adapter instanceof IItemAdapter) {
deletedItems.add(getItem(position));
((IItemAdapter) adapter).remove(position);
} else {
iterator.remove();
}
selections = getSelections();
}
return deletedItems;
}
//Expandable stuff
/**
* @return a set with the global positions of all expanded items
*/
public int[] getExpandedItems() {
int[] expandedItems = new int[mExpanded.size()];
int length = mExpanded.size();
for (int i = 0; i < length; i++) {
expandedItems[i] = mExpanded.keyAt(i);
}
return expandedItems;
}
/**
* toggles the expanded state of the given expandable item at the given position
*
* @param position the global position
*/
public void toggleExpandable(int position) {
if (mExpanded.indexOfKey(position) >= 0) {
collapse(position);
} else {
expand(position);
}
}
/**
* collapses (closes) the given collapsible item at the given position
*
* @param position the global position
*/
public void collapse(int position) {
Item item = getItem(position);
if (item != null && item instanceof IExpandable) {
IExpandable expandable = (IExpandable) item;
//as we now know the item we will collapse we can collapse all subitems
//if this item is not already callapsed and has sub items we go on
if (expandable.isExpanded() && expandable.getSubItems() != null && expandable.getSubItems().size() > 0) {
//first we find out how many items were added in total
int totalAddedItems = expandable.getSubItems().size();
int length = mExpanded.size();
for (int i = 0; i < length; i++) {
if (mExpanded.keyAt(i) > position && mExpanded.keyAt(i) <= position + totalAddedItems) {
totalAddedItems = totalAddedItems + mExpanded.get(mExpanded.keyAt(i));
}
}
//we will deselect starting with the lowest one
for (Integer value : mSelections) {
if (value > position && value <= position + totalAddedItems) {
deselect(value);
}
}
//now we start to collapse them
for (int i = length - 1; i >= 0; i
if (mExpanded.keyAt(i) > position && mExpanded.keyAt(i) <= position + totalAddedItems) {
//we collapsed those items now we remove update the added items
totalAddedItems = totalAddedItems - mExpanded.get(mExpanded.keyAt(i));
//we collapse the item
internalCollapse(mExpanded.keyAt(i));
}
}
//we collapse our root element
internalCollapse(expandable, position);
}
}
}
private void internalCollapse(int position) {
Item item = getItem(position);
if (item != null && item instanceof IExpandable) {
IExpandable expandable = (IExpandable) item;
//if this item is not already callapsed and has sub items we go on
if (expandable.isExpanded() && expandable.getSubItems() != null && expandable.getSubItems().size() > 0) {
internalCollapse(expandable, position);
}
}
}
private void internalCollapse(IExpandable expandable, int position) {
IAdapter adapter = getAdapter(position);
if (adapter != null && adapter instanceof IItemAdapter) {
((IItemAdapter) adapter).removeItemRange(position + 1, expandable.getSubItems().size());
}
//remember that this item is now collapsed again
expandable.withIsExpanded(false);
//remove the information that this item was opened
int indexOfKey = mExpanded.indexOfKey(position);
if (indexOfKey >= 0) {
mExpanded.removeAt(indexOfKey);
}
}
/**
* opens the expandable item at the given position
*
* @param position the global position
*/
public void expand(int position) {
Item item = getItem(position);
if (item != null && item instanceof IExpandable) {
IExpandable<?, Item> expandable = (IExpandable<?, Item>) item;
//if this item is not already callapsed and has sub items we go on
if (!expandable.isExpanded() && expandable.getSubItems() != null && expandable.getSubItems().size() > 0) {
IAdapter<Item> adapter = getAdapter(position);
if (adapter != null && adapter instanceof IItemAdapter) {
((IItemAdapter<Item>) adapter).add(position + 1, expandable.getSubItems());
}
//remember that this item is now opened (not collapsed)
expandable.withIsExpanded(true);
//store it in the list of opened expandable items
mExpanded.put(position, expandable.getSubItems() != null ? expandable.getSubItems().size() : 0);
}
}
}
//wrap the notify* methods so we can have our required selection adjustment code
/**
* wraps notifyItemInserted
*
* @param position the global position
*/
public void notifyAdapterItemInserted(int position) {
//we have to update all current stored selection and expandable states in our map
mSelections = AdapterUtil.adjustPosition(mSelections, position, Integer.MAX_VALUE, 1);
mExpanded = AdapterUtil.adjustPosition(mExpanded, position, Integer.MAX_VALUE, 1);
notifyItemInserted(position);
}
/**
* wraps notifyItemRangeInserted
*
* @param position the global position
* @param itemCount the count of items inserted
*/
public void notifyAdapterItemRangeInserted(int position, int itemCount) {
//we have to update all current stored selection and expandable states in our map
mSelections = AdapterUtil.adjustPosition(mSelections, position, Integer.MAX_VALUE, itemCount);
mExpanded = AdapterUtil.adjustPosition(mExpanded, position, Integer.MAX_VALUE, itemCount);
notifyItemRangeInserted(position, itemCount);
}
/**
* wraps notifyItemRemoved
*
* @param position the global position
*/
public void notifyAdapterItemRemoved(int position) {
//we have to update all current stored selection and expandable states in our map
mSelections = AdapterUtil.adjustPosition(mSelections, position, Integer.MAX_VALUE, -1);
mExpanded = AdapterUtil.adjustPosition(mExpanded, position, Integer.MAX_VALUE, -1);
notifyItemRemoved(position);
}
/**
* wraps notifyItemRangeRemoved
*
* @param position the global position
* @param itemCount the count of items removed
*/
public void notifyAdapterItemRangeRemoved(int position, int itemCount) {
//we have to update all current stored selection and expandable states in our map
mSelections = AdapterUtil.adjustPosition(mSelections, position, Integer.MAX_VALUE, itemCount * (-1));
mExpanded = AdapterUtil.adjustPosition(mExpanded, position, Integer.MAX_VALUE, itemCount * (-1));
notifyItemRangeRemoved(position, itemCount);
}
/**
* wraps notifyItemMoved
*
* @param fromPosition the global fromPosition
* @param toPosition the global toPosition
*/
public void notifyAdapterItemMoved(int fromPosition, int toPosition) {
//collapse items we move. just in case :D
collapse(fromPosition);
collapse(toPosition);
if (!mSelections.contains(fromPosition) && mSelections.contains(toPosition)) {
mSelections.remove(toPosition);
mSelections.add(fromPosition);
} else if (mSelections.contains(fromPosition) && !mSelections.contains(toPosition)) {
mSelections.remove(fromPosition);
mSelections.add(toPosition);
}
notifyItemMoved(fromPosition, toPosition);
}
/**
* wraps notifyItemChanged
*
* @param position the global position
*/
public void notifyAdapterItemChanged(int position) {
notifyAdapterItemChanged(position, null);
}
/**
* wraps notifyItemChanged
*
* @param position the global position
* @param payload additional payload
*/
public void notifyAdapterItemChanged(int position, Object payload) {
Item updateItem = getItem(position);
if (updateItem.isSelected()) {
mSelections.add(position);
} else if (mSelections.contains(position)) {
mSelections.remove(position);
}
if (payload == null) {
notifyItemChanged(position);
} else {
notifyItemChanged(position, payload);
}
}
/**
* wraps notifyItemRangeChanged
*
* @param position the global position
* @param itemCount the count of items changed
*/
public void notifyAdapterItemRangeChanged(int position, int itemCount) {
notifyAdapterItemRangeChanged(position, itemCount, null);
}
/**
* wraps notifyItemRangeChanged
*
* @param position the global position
* @param itemCount the count of items changed
* @param payload an additional payload
*/
public void notifyAdapterItemRangeChanged(int position, int itemCount, Object payload) {
for (int i = position; i < position + itemCount; i++) {
Item updateItem = getItem(position);
if (updateItem.isSelected()) {
mSelections.add(position);
} else if (mSelections.contains(position)) {
mSelections.remove(position);
}
}
if (payload == null) {
notifyItemRangeChanged(position, itemCount);
} else {
notifyItemRangeChanged(position, itemCount, payload);
}
}
//listeners
public interface OnTouchListener<Item extends IItem> {
/**
* the onTouch event of a specific item inside the RecyclerView
*
* @param v the view we clicked
* @param event the touch event
* @param adapter the adapter which is responsible for the given item
* @param item the IItem which was clicked
* @param position the global position
* @return return true if the event was consumed, otherwise false
*/
boolean onTouch(View v, MotionEvent event, IAdapter<Item> adapter, Item item, int position);
}
public interface OnClickListener<Item extends IItem> {
/**
* the onClick event of a specific item inside the RecyclerView
*
* @param v the view we clicked
* @param adapter the adapter which is responsible for the given item
* @param item the IItem which was clicked
* @param position the global position
* @return return true if the event was consumed, otherwise false
*/
boolean onClick(View v, IAdapter<Item> adapter, Item item, int position);
}
public interface OnLongClickListener<Item extends IItem> {
/**
* the onLongClick event of a specific item inside the RecyclerView
*
* @param v the view we clicked
* @param adapter the adapter which is responsible for the given item
* @param item the IItem which was clicked
* @param position the global position
* @return return true if the event was consumed, otherwise false
*/
boolean onLongClick(View v, IAdapter<Item> adapter, Item item, int position);
}
public interface OnCreateViewHolderListener {
/**
* is called inside the onCreateViewHolder method and creates the viewHolder based on the provided viewTyp
*
* @param parent the parent which will host the View
* @param viewType the type of the ViewHolder we want to create
* @return the generated ViewHolder based on the given viewType
*/
RecyclerView.ViewHolder onPreCreateViewHolder(ViewGroup parent, int viewType);
/**
* is called after the viewHolder was created and the default listeners were added
*
* @param viewHolder the created viewHolder after all listeners were set
* @return the viewHolder given as param
*/
RecyclerView.ViewHolder onPostCreateViewHolder(RecyclerView.ViewHolder viewHolder);
}
/**
* default implementation of the OnCreateViewHolderListener
*/
public class OnCreateViewHolderListenerImpl implements OnCreateViewHolderListener {
/**
* is called inside the onCreateViewHolder method and creates the viewHolder based on the provided viewTyp
*
* @param parent the parent which will host the View
* @param viewType the type of the ViewHolder we want to create
* @return the generated ViewHolder based on the given viewType
*/
@Override
public RecyclerView.ViewHolder onPreCreateViewHolder(ViewGroup parent, int viewType) {
return mTypeInstances.get(viewType).getViewHolder(parent);
}
/**
* is called after the viewHolder was created and the default listeners were added
*
* @param viewHolder the created viewHolder after all listeners were set
* @return the viewHolder given as param
*/
@Override
public RecyclerView.ViewHolder onPostCreateViewHolder(RecyclerView.ViewHolder viewHolder) {
return viewHolder;
}
}
public interface OnBindViewHolderListener {
/**
* is called in onBindViewHolder to bind the data on the ViewHolder
*
* @param viewHolder the viewHolder for the type at this position
* @param position the position of thsi viewHolder
*/
void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position);
}
public class OnBindViewHolderListenerImpl implements OnBindViewHolderListener {
/**
* is called in onBindViewHolder to bind the data on the ViewHolder
*
* @param viewHolder the viewHolder for the type at this position
* @param position the position of thsi viewHolder
*/
@Override
public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
getItem(position).bindView(viewHolder);
}
}
/**
* an internal class to return the IItem and relativePosition and it's adapter at once. used to save one iteration inside the getInternalItem method
*/
public static class RelativeInfo<Item extends IItem> {
public IAdapter<Item> adapter = null;
public Item item = null;
}
}
|
package org.csstudio.ui.util.widgets;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StyledCellLabelProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerCell;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.wb.swt.ResourceManager;
import org.eclipse.wb.swt.SWTResourceManager;
/**
* A widget to display a set of Images
*
* @author shroffk
*
*/
public class ImageStackWidget extends Composite {
private boolean editable;
private String selectedImageName;
private boolean scrollBarVisble;
protected final PropertyChangeSupport changeSupport = new PropertyChangeSupport(
this);
private ImagePreview imagePreview;
private Table table;
private TableViewer tableViewer;
private Map<String, byte[]> imageInputStreamsMap = new HashMap<String, byte[]>();
private Button buttonRemove;
private TableViewerColumn tableViewerColumn;
private TableColumn tblclmnImage;
/**
* Adds a listener, notified a porperty has been changed.
*
* @param listener
* a new listener
*/
public void addPropertyChangeListener(PropertyChangeListener listener) {
changeSupport.addPropertyChangeListener(listener);
}
/**
* Removes a listener.
*
* @param listener
* listener to be removed
*/
public void removePropertyChangeListener(PropertyChangeListener listener) {
changeSupport.removePropertyChangeListener(listener);
}
public ImageStackWidget(final Composite parent, int style) {
super(parent, SWT.NONE);
setLayout(new FormLayout());
Label label = new Label(this, SWT.SEPARATOR | SWT.VERTICAL);
FormData fd_label = new FormData();
fd_label.bottom = new FormAttachment(100, 5);
fd_label.top = new FormAttachment(0, 5);
fd_label.right = new FormAttachment(100, 100, -125);
label.setLayoutData(fd_label);
Label lblImages = new Label(this, SWT.NONE);
FormData fd_lblImages = new FormData();
fd_lblImages.left = new FormAttachment(label, 5);
fd_lblImages.top = new FormAttachment(0, 5);
lblImages.setLayoutData(fd_lblImages);
lblImages.setText("Images:");
tableViewer = new TableViewer(this, SWT.DOUBLE_BUFFERED | SWT.NO_SCROLL
| SWT.V_SCROLL);
table = tableViewer.getTable();
FormData fd_table = new FormData();
fd_table.left = new FormAttachment(label, 5);
fd_table.right = new FormAttachment(100, -5);
fd_table.bottom = new FormAttachment(100, -5);
fd_table.top = new FormAttachment(0, 30);
table.setLayoutData(fd_table);
table.setBackground(SWTResourceManager
.getColor(SWT.COLOR_WIDGET_LIGHT_SHADOW));
tableViewerColumn = new TableViewerColumn(tableViewer, SWT.NONE);
tableViewerColumn.setLabelProvider(new StyledCellLabelProvider() {
@Override
public void update(ViewerCell cell) {
// TODO does not center
// TODO does not preserve aspect ratio
// use the OwnerDrawLabelProvider
String imageName = cell.getElement() == null ? "" : cell
.getElement().toString();
ImageData imageData = new ImageData(new ByteArrayInputStream(
imageInputStreamsMap.get(imageName)));
int width = scrollBarVisble ? 90 : 100;
cell.setImage(new Image(getDisplay(), imageData.scaledTo(width,
width)));
}
});
table.addPaintListener(new PaintListener() {
public void paintControl(PaintEvent e) {
Rectangle rect = table.getClientArea();
int itemHeight = table.getItemHeight();
int headerHeight = table.getHeaderHeight();
int visibleCount = (rect.height - headerHeight + itemHeight - 1)
/ itemHeight;
setScrollBarVisble(table.getItemCount() >= visibleCount);
}
});
tblclmnImage = tableViewerColumn.getColumn();
tblclmnImage.setResizable(false);
tblclmnImage.setWidth(104);
tableViewer.setContentProvider(new IStructuredContentProvider() {
@Override
public void inputChanged(Viewer viewer, Object oldInput,
Object newInput) {
}
@Override
public void dispose() {
}
@Override
public Object[] getElements(Object inputElement) {
return (Object[]) inputElement;
}
});
tableViewer
.addSelectionChangedListener(new ISelectionChangedListener() {
@Override
public void selectionChanged(SelectionChangedEvent event) {
ISelection selection = event.getSelection();
if (selection != null
&& selection instanceof IStructuredSelection) {
IStructuredSelection sel = (IStructuredSelection) selection;
if (sel.size() == 1) {
setSelectedImageName((String) sel.iterator()
.next());
}
}
}
});
buttonRemove = new Button(this, SWT.NONE);
buttonRemove.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
try {
removeImage(getSelectedImageName());
} catch (IOException e1) {
}
}
});
buttonRemove.setImage(ResourceManager.getPluginImage(
"org.csstudio.ui.util", "icons/remove-16.gif"));
FormData fd_lblNewLabel = new FormData();
fd_lblNewLabel.right = new FormAttachment(label, -5);
fd_lblNewLabel.top = new FormAttachment(0, 5);
buttonRemove.setLayoutData(fd_lblNewLabel);
buttonRemove.setText("Remove");
buttonRemove.setVisible(false);
imagePreview = new ImagePreview(this);
FormData fd_imagePreview = new FormData();
fd_imagePreview.right = new FormAttachment(label, -5);
fd_imagePreview.bottom = new FormAttachment(100, -5);
fd_imagePreview.top = new FormAttachment(0, 5);
fd_imagePreview.left = new FormAttachment(0, 5);
imagePreview.setLayoutData(fd_imagePreview);
this.addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
switch (evt.getPropertyName()) {
case "editable":
break;
case "imageInputStreamsMap":
if (imageInputStreamsMap != null
&& !imageInputStreamsMap.isEmpty()) {
// Populate the list on the side
tableViewer.setInput(imageInputStreamsMap.keySet()
.toArray(
new String[imageInputStreamsMap
.keySet().size()]));
if (imageInputStreamsMap.keySet().contains(
selectedImageName)) {
imagePreview
.setImage(new ByteArrayInputStream(
imageInputStreamsMap
.get(selectedImageName)));
} else {
Entry<String, byte[]> next = imageInputStreamsMap
.entrySet().iterator().next();
imagePreview.setImage(new ByteArrayInputStream(next
.getValue()));
selectedImageName = next.getKey();
buttonRemove.setVisible(true);
}
} else {
tableViewer.setInput(null);
imagePreview.setImage((InputStream) null);
}
tableViewer.refresh();
imagePreview.redraw();
break;
case "selectedImageName":
imagePreview.setImage(new ByteArrayInputStream(
imageInputStreamsMap.get(selectedImageName)));
buttonRemove.setVisible(true);
imagePreview.redraw();
break;
case "scrollBarVisible":
tblclmnImage.setWidth(scrollBarVisble? 94 : 104);
tableViewer.getTable().layout();
tableViewer.refresh();
default:
break;
}
}
});
}
public boolean isEditable() {
return editable;
}
public void setEditable(boolean editable) {
boolean oldValue = this.editable;
this.editable = editable;
changeSupport.firePropertyChange("editable", oldValue, this.editable);
}
/**
* Set multiple Images to the widget, this will remove all existing images.
* In the imageInputStreamMap - the key defines the imageName and the value
* is an inputStream to the Image
*
* @param imageInputStreamsMap
* - a map of image names and image input streams
* @throws IOException
*/
public void setImageInputStreamsMap(
Map<String, InputStream> imageInputStreamsMap) throws IOException {
Map<String, byte[]> oldValue = this.imageInputStreamsMap;
this.imageInputStreamsMap = new HashMap<String, byte[]>();
for (Entry<String, InputStream> test : imageInputStreamsMap.entrySet()) {
this.imageInputStreamsMap.put(test.getKey(),
read2byteArray(test.getValue()));
}
changeSupport.firePropertyChange("imageInputStreamsMap", oldValue,
this.imageInputStreamsMap);
}
/**
* Add a single Image to the stack
*
* @param name
* - the name to Identify the Image.
* @param imageInputStream
* - an inputStream for the Image to be added.
* @throws IOException
*/
public void addImage(String name, InputStream imageInputStream)
throws IOException {
Map<String, byte[]> oldValue = new HashMap<String, byte[]>(
this.imageInputStreamsMap);
this.imageInputStreamsMap.put(name, read2byteArray(imageInputStream));
changeSupport.firePropertyChange("imageInputStreamsMap", oldValue,
this.imageInputStreamsMap);
}
public void removeImage(String name) throws IOException {
if (imageInputStreamsMap.containsKey(name)) {
Map<String, byte[]> oldValue = new HashMap<String, byte[]>(
this.imageInputStreamsMap);
this.imageInputStreamsMap.remove(name);
changeSupport.firePropertyChange("imageInputStreamsMap", oldValue,
this.imageInputStreamsMap);
}
}
/**
* @param scrollBarVisble
* the scrollBarVisble to set
*/
private void setScrollBarVisble(boolean scrollBarVisble) {
boolean oldValue = this.scrollBarVisble;
this.scrollBarVisble = scrollBarVisble;
changeSupport.firePropertyChange("scrollBarVisible", oldValue,
this.scrollBarVisble);
}
/**
* Return an InputStream for the Image identified by name
*
* @param name
* - name of the Image
* @return InputStream - to the Image identified by name
*/
public InputStream getImage(String name) {
return new ByteArrayInputStream(imageInputStreamsMap.get(name));
}
/**
* get a set of all the image Names associated with the Images being
* displayed by this widget
*
* @return Set of strings containing the names of all Images
*/
public Set<String> getImageNames() {
return imageInputStreamsMap.keySet();
}
/**
* get the name of the current Image in focus
*
* @return String imageName of the Image in focus
*/
public String getSelectedImageName() {
return selectedImageName;
}
/**
* set the Image to be brought into focus using its imageName
*
* @param selectedImageName
*/
public void setSelectedImageName(String selectedImageName) {
String oldValue = this.selectedImageName;
this.selectedImageName = selectedImageName;
changeSupport.firePropertyChange("selectedImageName", oldValue,
this.selectedImageName);
}
private static byte[] read2byteArray(InputStream input) throws IOException {
byte[] buffer = new byte[8192];
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();
while ((bytesRead = input.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
return output.toByteArray();
}
}
|
package com.novoda.downloadmanager.lib;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import java.util.ArrayList;
import java.util.List;
/**
* This class may be used to filter download manager queries.
*/
public class Query {
/**
* Constant for use with {@link #orderBy}
*/
static final int ORDER_ASCENDING = 1;
/**
* Constant for use with {@link #orderBy}
*/
static final int ORDER_DESCENDING = 2;
private long[] mIds = null;
private Integer mStatusFlags = null;
private String mOrderByColumn = Downloads.Impl.COLUMN_LAST_MODIFICATION;
private int mOrderDirection = ORDER_DESCENDING;
private boolean mOnlyIncludeVisibleInDownloadsUi = false;
private String[] filterExtras;
/**
* Include only the downloads with the given IDs.
*
* @return this object
*/
public Query setFilterById(long... ids) {
mIds = ids;
return this;
}
/**
* Include only the downloads with the given extras.
*
* @return this object
*/
public Query setFilterByExtras(String... extras) {
filterExtras = extras;
return this;
}
/**
* Include only downloads with status matching any the given status flags.
*
* @param flags any combination of the STATUS_* bit flags
* @return this object
*/
public Query setFilterByStatus(int flags) {
mStatusFlags = flags;
return this;
}
/**
* Controls whether this query includes downloads not visible in the system's Downloads UI.
*
* @param value if true, this query will only include downloads that should be displayed in
* the system's Downloads UI; if false (the default), this query will include
* both visible and invisible downloads.
* @return this object
*/
public Query setOnlyIncludeVisibleInDownloadsUi(boolean value) {
mOnlyIncludeVisibleInDownloadsUi = value;
return this;
}
/**
* Change the sort order of the returned Cursor.
*
* @param column one of the COLUMN_* constants; currently, only
* {DownloadManager.COLUMN_LAST_MODIFIED_TIMESTAMP} and {DownloadManager.COLUMN_TOTAL_SIZE_BYTES} are
* supported.
* @param direction either {@link #ORDER_ASCENDING} or {@link #ORDER_DESCENDING}
* @return this object
*/
Query orderBy(String column, int direction) {
if (direction != ORDER_ASCENDING && direction != ORDER_DESCENDING) {
throw new IllegalArgumentException("Invalid direction: " + direction);
}
if (column.equals(DownloadManager.COLUMN_LAST_MODIFIED_TIMESTAMP)) {
mOrderByColumn = Downloads.Impl.COLUMN_LAST_MODIFICATION;
} else if (column.equals(DownloadManager.COLUMN_TOTAL_SIZE_BYTES)) {
mOrderByColumn = Downloads.Impl.COLUMN_TOTAL_BYTES;
} else {
throw new IllegalArgumentException("Cannot order by " + column);
}
mOrderDirection = direction;
return this;
}
/**
* Run this query using the given ContentResolver.
*
* @param projection the projection to pass to ContentResolver.query()
* @return the Cursor returned by ContentResolver.query()
*/
Cursor runQuery(ContentResolver resolver, String[] projection, Uri baseUri) {
List<String> selectionParts = new ArrayList<String>();
String[] selectionArgs = getSelectionArgsFromIds();
filterByIds(selectionParts);
filterByExtras(selectionParts);
filterByStatus(selectionParts);
if (mOnlyIncludeVisibleInDownloadsUi) {
selectionParts.add(Downloads.Impl.COLUMN_IS_VISIBLE_IN_DOWNLOADS_UI + " != '0'");
}
// only return rows which are not marked 'deleted = 1'
selectionParts.add(Downloads.Impl.COLUMN_DELETED + " != '1'");
String selection = joinStrings(" AND ", selectionParts);
String orderDirection = (mOrderDirection == ORDER_ASCENDING ? "ASC" : "DESC");
String orderBy = mOrderByColumn + " " + orderDirection;
return resolver.query(baseUri, projection, selection, selectionArgs, orderBy);
}
private String[] getSelectionArgsFromIds() {
if (mIds == null) {
return null;
}
return DownloadManager.getWhereArgsForIds(mIds);
}
private void filterByIds(List<String> selectionParts) {
if (mIds == null) {
return;
}
selectionParts.add(DownloadManager.getWhereClauseForIds(mIds));
}
private void filterByExtras(List<String> selectionParts) {
if (filterExtras == null) {
return;
}
List<String> parts = new ArrayList<String>();
for (String filterExtra : filterExtras) {
parts.add(extrasClause(filterExtra));
}
selectionParts.add(joinStrings(" OR ", parts));
}
private void filterByStatus(List<String> selectionParts) {
if (mStatusFlags == null) {
return;
}
List<String> parts = new ArrayList<String>();
if ((mStatusFlags & DownloadManager.STATUS_PENDING) != 0) {
parts.add(statusClause("=", Downloads.Impl.STATUS_PENDING));
}
if ((mStatusFlags & DownloadManager.STATUS_RUNNING) != 0) {
parts.add(statusClause("=", Downloads.Impl.STATUS_RUNNING));
}
if ((mStatusFlags & DownloadManager.STATUS_PAUSED) != 0) {
parts.add(statusClause("=", Downloads.Impl.STATUS_PAUSED_BY_APP));
parts.add(statusClause("=", Downloads.Impl.STATUS_WAITING_TO_RETRY));
parts.add(statusClause("=", Downloads.Impl.STATUS_WAITING_FOR_NETWORK));
parts.add(statusClause("=", Downloads.Impl.STATUS_QUEUED_FOR_WIFI));
}
if ((mStatusFlags & DownloadManager.STATUS_SUCCESSFUL) != 0) {
parts.add(statusClause("=", Downloads.Impl.STATUS_SUCCESS));
}
if ((mStatusFlags & DownloadManager.STATUS_FAILED) != 0) {
parts.add("(" + statusClause(">=", 400) + " AND " + statusClause("<", 600) + ")");
}
selectionParts.add(joinStrings(" OR ", parts));
}
private String joinStrings(String joiner, Iterable<String> parts) {
StringBuilder builder = new StringBuilder();
boolean first = true;
for (String part : parts) {
if (!first) {
builder.append(joiner);
}
builder.append(part);
first = false;
}
return builder.toString();
}
private String extrasClause(String extra) {
return Downloads.Impl.COLUMN_NOTIFICATION_EXTRAS + " = '" + extra + "'";
}
private String statusClause(String operator, int value) {
return Downloads.Impl.COLUMN_STATUS + operator + "'" + value + "'";
}
}
|
package com.ianhanniballake.contractiontimer.ui;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import org.acra.ACRA;
import org.json.JSONException;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.Toast;
import com.android.vending.billing.IInAppBillingService;
import com.google.analytics.tracking.android.EasyTracker;
import com.google.analytics.tracking.android.Item;
import com.google.analytics.tracking.android.Transaction;
import com.ianhanniballake.contractiontimer.BuildConfig;
import com.ianhanniballake.contractiontimer.R;
import com.ianhanniballake.contractiontimer.actionbar.ActionBarFragmentActivity;
import com.ianhanniballake.contractiontimer.inappbilling.IabException;
import com.ianhanniballake.contractiontimer.inappbilling.Inventory;
import com.ianhanniballake.contractiontimer.inappbilling.Purchase;
import com.ianhanniballake.contractiontimer.inappbilling.Security;
import com.ianhanniballake.contractiontimer.inappbilling.SkuDetails;
/**
* Activity controlling donations, including Paypal and In-App Billing
*/
public class DonateActivity extends ActionBarFragmentActivity
{
private class ConsumeAsyncTask extends AsyncTask<Purchase, Void, List<Purchase>>
{
private final boolean finishActivity;
private final WeakReference<IInAppBillingService> mBillingService;
ConsumeAsyncTask(final IInAppBillingService service, final boolean finishActivity)
{
mBillingService = new WeakReference<IInAppBillingService>(service);
this.finishActivity = finishActivity;
}
@Override
protected List<Purchase> doInBackground(final Purchase... purchases)
{
if (BuildConfig.DEBUG)
Log.d(DonateActivity.class.getSimpleName(), "Starting Consume of " + Arrays.toString(purchases));
final List<Purchase> consumedPurchases = new ArrayList<Purchase>();
for (final Purchase purchase : purchases)
try
{
final String token = purchase.getToken();
if (TextUtils.isEmpty(token))
{
Log.e(DonateActivity.class.getSimpleName(), "Invalid consume token " + token);
EasyTracker.getTracker().trackEvent("Donate", "Invalid consume token", purchase.getSku(), -1L);
break;
}
final IInAppBillingService service = mBillingService.get();
if (service == null)
{
Log.w(DonateActivity.class.getSimpleName(), "Billing service is null");
break;
}
final int response = service.consumePurchase(3, getPackageName(), token);
if (response == 0)
consumedPurchases.add(purchase);
else
{
Log.e(DonateActivity.class.getSimpleName(), "Bad consume response " + response);
EasyTracker.getTracker().trackEvent("Donate", "Bad consume response", purchase.getSku(), -1L);
}
} catch (final RemoteException e)
{
Log.e(DonateActivity.class.getSimpleName(), "Error consuming " + purchase.getSku(), e);
EasyTracker.getTracker().trackEvent("Donate", "Remote Exception consume", purchase.getSku(), -1L);
}
return consumedPurchases;
}
@Override
protected void onPostExecute(final List<Purchase> result)
{
if (result == null || result.isEmpty())
{
Log.w(DonateActivity.class.getSimpleName(), "No purchases consumed");
return;
}
for (final Purchase purchase : result)
{
final String sku = purchase.getSku();
if (BuildConfig.DEBUG)
Log.d(DonateActivity.class.getSimpleName(), "Consume completed successfully " + sku);
EasyTracker.getTracker().trackEvent("Donate", "Purchased", sku, 0L);
final long purchasedPriceMicro = skuPrices.containsKey(sku) ? skuPrices.get(sku).longValue() : 0;
final String purchasedName = skuNames.containsKey(sku) ? skuNames.get(sku) : sku;
final Transaction transaction = new Transaction.Builder(purchase.getOrderId(), purchasedPriceMicro)
.setAffiliation("Google Play").build();
transaction.addItem(new Item.Builder(sku, purchasedName, purchasedPriceMicro, 1L).setProductCategory(
"Donation").build());
EasyTracker.getTracker().trackTransaction(transaction);
}
Toast.makeText(DonateActivity.this, R.string.donate_thank_you, Toast.LENGTH_LONG).show();
if (finishActivity)
{
if (BuildConfig.DEBUG)
Log.d(DonateActivity.class.getSimpleName(), "Finishing Donate Activity");
finish();
}
}
}
private class InventoryQueryAsyncTask extends AsyncTask<String, Void, Inventory>
{
private final WeakReference<IInAppBillingService> mBillingService;
public InventoryQueryAsyncTask(final IInAppBillingService service)
{
mBillingService = new WeakReference<IInAppBillingService>(service);
}
@Override
protected Inventory doInBackground(final String... moreSkus)
{
try
{
final Inventory inv = new Inventory();
if (BuildConfig.DEBUG)
Log.d(DonateActivity.class.getSimpleName(), "Starting query inventory");
int r = queryPurchases(inv);
if (r != 0)
throw new IabException(r, "Error refreshing inventory (querying owned items).");
if (BuildConfig.DEBUG)
Log.d(DonateActivity.class.getSimpleName(), "Starting sku details query");
r = querySkuDetails(inv, moreSkus);
if (r != 0)
throw new IabException(r, "Error refreshing inventory (querying prices of items).");
return inv;
} catch (final RemoteException e)
{
Log.e(DonateActivity.class.getSimpleName(), "Error loading inventory", e);
EasyTracker.getTracker().trackEvent("Donate", "Remote Exception inventory", "", -1L);
} catch (final JSONException e)
{
Log.e(DonateActivity.class.getSimpleName(), "Error parsing inventory", e);
EasyTracker.getTracker().trackEvent("Donate", "Bad inventory response", "", -1L);
} catch (final IabException e)
{
Log.e(DonateActivity.class.getSimpleName(), "Error parsing inventory", e);
EasyTracker.getTracker().trackEvent("Donate", "Error loading inventory", "", -1L);
}
return null;
}
@Override
protected void onPostExecute(final Inventory inv)
{
if (BuildConfig.DEBUG)
Log.d(getClass().getSimpleName(), "Inventory Returned: " + inv);
// If we failed to get the inventory, then leave the in-app billing UI hidden
if (inv == null)
return;
// Make sure we've consumed any previous purchases
final List<Purchase> purchases = inv.getAllPurchases();
if (!purchases.isEmpty())
{
final IInAppBillingService service = mBillingService.get();
if (service != null)
new ConsumeAsyncTask(service, false).execute(purchases.toArray(new Purchase[0]));
else
Log.w(DonateActivity.class.getSimpleName(), "Billing service is null");
}
final String[] inAppName = new String[skus.length];
for (int h = 0; h < skus.length; h++)
{
final String currentSku = skus[h];
final SkuDetails sku = inv.getSkuDetails(currentSku);
skuNames.put(currentSku, sku.getTitle());
inAppName[h] = sku.getDescription() + " (" + sku.getPrice() + ")";
}
final Spinner inAppSpinner = (Spinner) findViewById(R.id.donate_in_app_spinner);
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(DonateActivity.this,
android.R.layout.simple_spinner_item, inAppName);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
inAppSpinner.setAdapter(adapter);
// And finally show the In-App Billing UI
final RelativeLayout inAppLayout = (RelativeLayout) findViewById(R.id.in_app_layout);
inAppLayout.setVisibility(View.VISIBLE);
}
int queryPurchases(final Inventory inv) throws JSONException, RemoteException
{
// Query purchases
boolean verificationFailed = false;
String continueToken = null;
do
{
final IInAppBillingService service = mBillingService.get();
if (service == null)
{
Log.w(DonateActivity.class.getSimpleName(), "Billing service is null");
return -1;
}
final Bundle ownedItems = service.getPurchases(3, getPackageName(), ITEM_TYPE_INAPP, continueToken);
final int response = getResponseCodeFromBundle(ownedItems);
if (response != 0)
{
Log.e(getClass().getSimpleName(), "Bad purchases response " + response);
EasyTracker.getTracker().trackEvent("Donate", "Bad purchases response", "", -1L);
return response;
}
if (!ownedItems.containsKey(RESPONSE_INAPP_ITEM_LIST)
|| !ownedItems.containsKey(RESPONSE_INAPP_PURCHASE_DATA_LIST)
|| !ownedItems.containsKey(RESPONSE_INAPP_SIGNATURE_LIST))
{
Log.e(getClass().getSimpleName(), "Bad purchases response: invalid data");
EasyTracker.getTracker().trackEvent("Donate", "Bad purchases response", "", -1L);
return -1;
}
final ArrayList<String> ownedSkus = ownedItems.getStringArrayList(RESPONSE_INAPP_ITEM_LIST);
final ArrayList<String> purchaseDataList = ownedItems
.getStringArrayList(RESPONSE_INAPP_PURCHASE_DATA_LIST);
final ArrayList<String> signatureList = ownedItems.getStringArrayList(RESPONSE_INAPP_SIGNATURE_LIST);
for (int i = 0; i < purchaseDataList.size(); ++i)
{
final String purchaseData = purchaseDataList.get(i);
final String signature = signatureList.get(i);
ownedSkus.get(i);
if (Security.verifyPurchase(publicKey, purchaseData, signature))
{
final Purchase purchase = new Purchase(ITEM_TYPE_INAPP, purchaseData, signature);
// Record ownership and token
inv.addPurchase(purchase);
}
else
verificationFailed = true;
}
continueToken = ownedItems.getString("INAPP_CONTINUATION_TOKEN");
} while (!TextUtils.isEmpty(continueToken));
return verificationFailed ? -1 : 0;
}
int querySkuDetails(final Inventory inv, final String[] moreSkus) throws RemoteException, JSONException
{
final ArrayList<String> skuList = new ArrayList<String>();
skuList.addAll(inv.getAllOwnedSkus(ITEM_TYPE_INAPP));
if (moreSkus != null)
skuList.addAll(Arrays.asList(moreSkus));
if (skuList.size() == 0)
return 0;
final Bundle querySkus = new Bundle();
querySkus.putStringArrayList("ITEM_ID_LIST", skuList);
final IInAppBillingService service = mBillingService.get();
if (service == null)
{
Log.w(DonateActivity.class.getSimpleName(), "Billing service is null");
return -1;
}
final Bundle skuDetails = service.getSkuDetails(3, getPackageName(), ITEM_TYPE_INAPP, querySkus);
if (!skuDetails.containsKey(RESPONSE_GET_SKU_DETAILS_LIST))
{
final int response = getResponseCodeFromBundle(skuDetails);
if (response != 0)
{
Log.e(getClass().getSimpleName(), "Bad sku details response " + response);
EasyTracker.getTracker().trackEvent("Donate", "Bad sku details response", "", -1L);
return response;
}
return -1;
}
final ArrayList<String> responseList = skuDetails.getStringArrayList(RESPONSE_GET_SKU_DETAILS_LIST);
for (final String thisResponse : responseList)
{
final SkuDetails d = new SkuDetails(ITEM_TYPE_INAPP, thisResponse);
inv.addSkuDetails(d);
}
return 0;
}
}
private final static String ITEM_TYPE_INAPP = "inapp";
private final static String publicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEApmwDry4kZ8n3DulD1UxcJ89+TRI/DGSvFbhtjNkO1yWki16Q3MzOHwZ4Opyykn3cfiuexMNQYWZfQBqrvkdWWXf+iwBmG6PlOPzgYHV/0ohQhADCUb71SPihmf2WX2zejyNt71sMMUuIklB9HgXukO2uspdWYjKy8CkaMSHK+pQZdG2reACtLjgLMIm1tOlU2C7kGbsL+xodGyh29bO/6cn1/IPrnLZVgAfMm3UDGrqrK2PlgRlLZsoVQKvdi2vbQ8e4LH90rYlXrqEHHgRQw4ozXsj0QmaUx2b2EzRu4q17yvKvhmlFzZSShCkAJgPCOLds0A2SBbOAAX15lB8RmQIDAQAB";
private final static String PURCHASED_SKU = "com.ianhanniballake.contractiontimer.PURCHASED_SKU";
private final static int RC_REQUEST = 1;
private static final String RESPONSE_CODE = "RESPONSE_CODE";
private static final String RESPONSE_GET_SKU_DETAILS_LIST = "DETAILS_LIST";
private static final String RESPONSE_INAPP_ITEM_LIST = "INAPP_PURCHASE_ITEM_LIST";
private static final String RESPONSE_INAPP_PURCHASE_DATA_LIST = "INAPP_PURCHASE_DATA_LIST";
private static final String RESPONSE_INAPP_SIGNATURE_LIST = "INAPP_DATA_SIGNATURE_LIST";
// Workaround to bug where sometimes response codes come as Long instead of Integer
static int getResponseCodeFromBundle(final Bundle b)
{
final Object o = b.get(RESPONSE_CODE);
if (o == null)
return 0;
else if (o instanceof Integer)
return ((Integer) o).intValue();
else if (o instanceof Long)
return (int) ((Long) o).longValue();
else
throw new RuntimeException("Unexpected type for bundle response code: " + o.getClass().getName());
}
// Workaround to bug where sometimes response codes come as Long instead of Integer
static int getResponseCodeFromIntent(final Intent i)
{
final Object o = i.getExtras().get(RESPONSE_CODE);
if (o == null)
return 0;
else if (o instanceof Integer)
return ((Integer) o).intValue();
else if (o instanceof Long)
return (int) ((Long) o).longValue();
else
throw new RuntimeException("Unexpected type for intent response code: " + o.getClass().getName());
}
IInAppBillingService mService;
private ServiceConnection mServiceConn;
/**
* Recently purchased SKU, if any. Should be saved in the instance state
*/
String purchasedSku = "";
/**
* SKU Product Names
*/
HashMap<String, String> skuNames = new HashMap<String, String>();
/**
* US Prices for SKUs in micro-currency
*/
HashMap<String, Long> skuPrices = new HashMap<String, Long>();
/**
* List of valid SKUs
*/
String[] skus = new String[0];
@Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data)
{
if (BuildConfig.DEBUG)
Log.d(getClass().getSimpleName(), "onActivityResult(" + requestCode + "," + resultCode + "," + data + ")");
if (requestCode != RC_REQUEST)
{
super.onActivityResult(requestCode, resultCode, data);
return;
}
if (data == null)
{
Log.e(getClass().getSimpleName(), "Bad purchase response: null Intent");
EasyTracker.getTracker().trackEvent("Donate", "Bad purchase response", purchasedSku, -1L);
return;
}
final int responseCode = getResponseCodeFromIntent(data);
final String purchaseData = data.getStringExtra("INAPP_PURCHASE_DATA");
final String dataSignature = data.getStringExtra("INAPP_DATA_SIGNATURE");
if (resultCode == Activity.RESULT_OK && responseCode == 0)
{
if (purchaseData == null || dataSignature == null)
{
Log.e(getClass().getSimpleName(), "Invalid purchase response: null data fields");
EasyTracker.getTracker().trackEvent("Donate", "Invalid purchase response", purchasedSku, -1L);
return;
}
Purchase purchase = null;
try
{
purchase = new Purchase(ITEM_TYPE_INAPP, purchaseData, dataSignature);
final String sku = purchase.getSku();
// Verify signature
if (!Security.verifyPurchase(publicKey, purchaseData, dataSignature))
{
Log.e(getClass().getSimpleName(), "Signature verification failed " + sku);
EasyTracker.getTracker().trackEvent("Donate", "Signature verification failed", sku, -1L);
return;
}
} catch (final JSONException e)
{
Log.e(getClass().getSimpleName(), "Bad purchase response", e);
EasyTracker.getTracker().trackEvent("Donate", "Bad purchase response", purchasedSku, -1L);
return;
}
new ConsumeAsyncTask(mService, true).execute(purchase);
}
else if (resultCode == Activity.RESULT_OK)
{
Log.e(getClass().getSimpleName(), "Purchase error " + responseCode);
EasyTracker.getTracker().trackEvent("Donate", "Purchase error " + responseCode, purchasedSku, -1L);
}
else if (resultCode == Activity.RESULT_CANCELED)
{
if (BuildConfig.DEBUG)
Log.d(getClass().getSimpleName(), "Purchase canceled");
EasyTracker.getTracker().trackEvent("Donate", "Canceled", purchasedSku, 0L);
}
else
{
Log.w(getClass().getSimpleName(), "Unknown purchase response");
EasyTracker.getTracker().trackEvent("Donate", "Unknown purchase response", purchasedSku, -1L);
}
}
@Override
protected void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Set up SKUs
final ArrayList<String> allSkus = new ArrayList<String>();
if (BuildConfig.DEBUG)
{
allSkus.add("android.test.purchased");
allSkus.add("android.test.canceled");
allSkus.add("android.test.refunded");
allSkus.add("android.test.item_unavailable");
}
final String[] skuArray = getResources().getStringArray(R.array.donate_in_app_sku_array);
allSkus.addAll(Arrays.asList(skuArray));
skus = allSkus.toArray(new String[allSkus.size()]);
final int[] skuPriceArray = getResources().getIntArray(R.array.donate_in_app_price_array);
for (int h = 0; h < skuPriceArray.length; h++)
skuPrices.put(skuArray[h], (long) skuPriceArray[h]);
// Set up the UI
setContentView(R.layout.activity_donate);
final Button paypal_button = (Button) findViewById(R.id.paypal_button);
paypal_button.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(final View v)
{
if (BuildConfig.DEBUG)
Log.d(DonateActivity.this.getClass().getSimpleName(), "Clicked Paypal");
EasyTracker.getTracker().trackEvent("Donate", "Paypal", "", 0L);
final Uri.Builder uriBuilder = new Uri.Builder();
uriBuilder.scheme("https").authority("www.paypal.com").path("cgi-bin/webscr");
uriBuilder.appendQueryParameter("cmd", "_donations");
uriBuilder.appendQueryParameter("business", "ian.hannibal.lake@gmail.com");
uriBuilder.appendQueryParameter("lc", "US");
uriBuilder.appendQueryParameter("item_name", "Contraction Timer Donation");
uriBuilder.appendQueryParameter("no_note", "1");
uriBuilder.appendQueryParameter("no_shipping", "1");
uriBuilder.appendQueryParameter("currency_code", "USD");
final Uri payPalUri = uriBuilder.build();
// Start your favorite browser
final Intent viewIntent = new Intent(Intent.ACTION_VIEW, payPalUri);
startActivity(viewIntent);
// Close this activity
finish();
}
});
final Button inAppButton = (Button) findViewById(R.id.donate__in_app_button);
inAppButton.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(final View v)
{
final Spinner inAppSpinner = (Spinner) findViewById(R.id.donate_in_app_spinner);
final int selectedInAppAmount = inAppSpinner.getSelectedItemPosition();
purchasedSku = skus[selectedInAppAmount];
if (BuildConfig.DEBUG)
Log.d(DonateActivity.class.getSimpleName(), "Clicked " + purchasedSku);
EasyTracker.getTracker().trackEvent("Donate", "Click", purchasedSku, 0L);
try
{
final Bundle buyIntentBundle = mService.getBuyIntent(3, getPackageName(), purchasedSku,
ITEM_TYPE_INAPP, "");
final int response = getResponseCodeFromBundle(buyIntentBundle);
if (response != 0)
{
Log.e(getClass().getSimpleName(), "Purchase error " + response);
EasyTracker.getTracker().trackEvent("Donate", "Purchase error " + response, purchasedSku, -1L);
return;
}
final PendingIntent pendingIntent = buyIntentBundle.getParcelable("BUY_INTENT");
startIntentSenderForResult(pendingIntent.getIntentSender(), RC_REQUEST, new Intent(),
Integer.valueOf(0), Integer.valueOf(0), Integer.valueOf(0));
} catch (final SendIntentException e)
{
Log.e(DonateActivity.class.getSimpleName(), "Failed to send intent", e);
EasyTracker.getTracker().trackEvent("Donate", "Failed to send intent", purchasedSku, -1L);
} catch (final RemoteException e)
{
Log.e(DonateActivity.class.getSimpleName(), "Failed to send intent", e);
EasyTracker.getTracker()
.trackEvent("Donate", "Remote Exception during purchase", purchasedSku, -1L);
}
}
});
// Start the In-App Billing process, only if on Froyo or higher
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO)
{
mServiceConn = new ServiceConnection()
{
@Override
public void onServiceConnected(final ComponentName name, final IBinder service)
{
mService = IInAppBillingService.Stub.asInterface(service);
final String packageName = getPackageName();
try
{
// check for in-app billing v3 support
final int response = mService.isBillingSupported(3, packageName, ITEM_TYPE_INAPP);
if (response == 0)
new InventoryQueryAsyncTask(mService).execute(skus);
else
{
Log.w(getClass().getSimpleName(), "In app not supported");
EasyTracker.getTracker().trackEvent("Donate", "In app not supported", "", -1L);
}
} catch (final RemoteException e)
{
Log.e(getClass().getSimpleName(), "Error during initialization", e);
EasyTracker.getTracker()
.trackEvent("Donate", "Remote exception during initialization", "", -1L);
return;
}
}
@Override
public void onServiceDisconnected(final ComponentName name)
{
mService = null;
}
};
final Intent serviceIntent = new Intent("com.android.vending.billing.InAppBillingService.BIND");
if (!getPackageManager().queryIntentServices(serviceIntent, 0).isEmpty())
// service available to handle that Intent
bindService(serviceIntent, mServiceConn, Context.BIND_AUTO_CREATE);
else
{
// no service available to handle that Intent
Log.w(getClass().getSimpleName(), "Billing unavailable");
EasyTracker.getTracker().trackEvent("Donate", "Billing Unavailable", "", -1L);
}
}
}
@Override
protected void onDestroy()
{
super.onDestroy();
if (mServiceConn != null)
{
try
{
unbindService(mServiceConn);
} catch (final IllegalArgumentException e)
{
// Assume the service has already been unbinded, so only log that it happened
Log.e(getClass().getSimpleName(), "Error unbinding service", e);
EasyTracker.getTracker().trackException(Thread.currentThread().getName(), e, false);
if (!BuildConfig.DEBUG)
ACRA.getErrorReporter().handleSilentException(e);
}
mServiceConn = null;
mService = null;
}
}
@Override
protected void onRestoreInstanceState(final Bundle savedInstanceState)
{
super.onRestoreInstanceState(savedInstanceState);
purchasedSku = savedInstanceState.containsKey(PURCHASED_SKU) ? savedInstanceState.getString(PURCHASED_SKU) : "";
}
@Override
protected void onResume()
{
super.onResume();
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
final boolean isLockPortrait = preferences.getBoolean(Preferences.LOCK_PORTRAIT_PREFERENCE_KEY, getResources()
.getBoolean(R.bool.pref_settings_lock_portrait_default));
if (BuildConfig.DEBUG)
Log.d(getClass().getSimpleName(), "Lock Portrait: " + isLockPortrait);
if (isLockPortrait)
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
else
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
}
@Override
protected void onSaveInstanceState(final Bundle outState)
{
super.onSaveInstanceState(outState);
outState.putString(PURCHASED_SKU, purchasedSku);
}
@Override
protected void onStart()
{
super.onStart();
getActionBarHelper().setDisplayHomeAsUpEnabled(true);
EasyTracker.getInstance().activityStart(this);
EasyTracker.getTracker().trackView("Donate");
}
@Override
protected void onStop()
{
super.onStop();
EasyTracker.getInstance().activityStop(this);
}
}
|
package com.matthewtamlin.spyglass.library.use_adapters;
import com.matthewtamlin.spyglass.library.use_annotations.UseInt;
import static com.matthewtamlin.java_utilities.checkers.NullChecker.checkNotNull;
public class UseIntAdapter implements UseAdapter<Integer, UseInt> {
@Override
public Integer getValue(final UseInt annotation) {
checkNotNull(annotation, "Argument 'annotation' cannot be null.");
return annotation.value();
}
}
|
package com.redhat.ceylon.compiler.typechecker.util;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import com.redhat.ceylon.common.Backend;
import com.redhat.ceylon.compiler.typechecker.tree.Tree;
import com.redhat.ceylon.model.typechecker.model.ClassOrInterface;
import com.redhat.ceylon.model.typechecker.model.Declaration;
import com.redhat.ceylon.model.typechecker.model.FunctionOrValue;
import com.redhat.ceylon.model.typechecker.model.ModelUtil;
/** Certain convenience methods related to native types.
*
* @author Enrique Zamudio
*/
public class NativeUtil {
public static List<Tree.Statement> mergeStatements(Tree.Body body, Tree.Declaration header) {
// And if the header exists we go through the declarations in
// its body and add them to our list of statements as if they
// were part of the native implementation when a) it has a
// default implementation and b) we can't find a matching
// declaration in our (original) list of statements
List<Tree.Statement> hdrstmts;
if (header instanceof Tree.ClassDefinition) {
hdrstmts = ((Tree.ClassDefinition)header).getClassBody().getStatements();
} else if (header instanceof Tree.ObjectDefinition) {
hdrstmts = ((Tree.ObjectDefinition)header).getClassBody().getStatements();
} else {
hdrstmts = null;
}
List<Tree.Statement> stmts = body.getStatements();
if (hdrstmts != null && !hdrstmts.isEmpty()) {
Set<String> names = getDeclarationNames(stmts);
LinkedList<Tree.Statement> newstmts = new LinkedList<Tree.Statement>(stmts);
for (Tree.Statement stmt : hdrstmts) {
if (stmt instanceof Tree.Declaration) {
Tree.Declaration decl = (Tree.Declaration)stmt;
if (isImplemented(decl)
&& !names.contains(decl.getDeclarationModel().getName())) {
newstmts.addFirst(decl);
}
} else {
newstmts.addFirst(stmt);
}
}
stmts = newstmts;
}
return stmts;
}
public static Set<String> getDeclarationNames(java.util.List<Tree.Statement> stmts) {
java.util.HashSet<String> names = new java.util.HashSet<String>();
for (Tree.Statement stmt : stmts) {
if (stmt instanceof Tree.Declaration) {
Tree.Declaration decl = (Tree.Declaration)stmt;
String declName = decl.getDeclarationModel().getName();
names.add(declName);
}
}
return names;
}
public static boolean isImplemented(Tree.Declaration decl) {
return isImplemented(decl.getDeclarationModel());
}
public static boolean isImplemented(Declaration decl) {
if (decl instanceof FunctionOrValue) {
return ((FunctionOrValue)decl).isImplemented();
} else if (decl instanceof ClassOrInterface) {
return !decl.isNative();
} else {
return false;
}
}
public static boolean isNative(Tree.Declaration decl) {
return isNative(decl.getDeclarationModel());
}
public static boolean isNative(Declaration decl) {
return decl.isNative();
}
public static boolean isNativeHeader(Tree.Declaration decl) {
return isNativeHeader(decl.getDeclarationModel());
}
public static boolean isNativeHeader(Declaration decl) {
return decl.isNativeHeader();
}
public static String getNative(Tree.Declaration decl) {
return getNative(decl.getDeclarationModel());
}
public static String getNative(Declaration decl) {
return decl.getNativeBackend();
}
/**
* Checks that the declaration is marked "native" and has a Ceylon implementation
* meant for the specified backend
*/
public static boolean isForBackend(Tree.Declaration decl, Backend backend) {
return isForBackend(decl.getDeclarationModel(), backend);
}
/**
* Checks that the declaration is marked "native" and has a Ceylon implementation
* meant for the specified backend
*/
public static boolean isForBackend(Declaration decl, Backend backend) {
String be = getNative(decl);
return be == null || be.equals(backend.nativeAnnotation);
}
public static boolean isHeaderWithoutBackend(Tree.Declaration decl, Backend backend) {
return isHeaderWithoutBackend(decl.getDeclarationModel(), backend);
}
public static boolean isHeaderWithoutBackend(Declaration decl, Backend backend) {
return decl.isNativeHeader()
&& (ModelUtil.getNativeDeclaration(decl, backend) == null);
}
}
|
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// all copies or substantial portions of the Software.
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package com.uber.m3.tally.m3.thrift;
import org.apache.http.annotation.GuardedBy;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketAddress;
import java.net.SocketException;
import java.nio.ByteBuffer;
/**
* Abstract class that supports Thrift UDP functionality.
*/
public abstract class TUdpTransport extends TTransport implements AutoCloseable {
// NOTE: This is the maximum size of a single UDP packet's payload in IPv4
// which is set at 65,535, we reserve 512 byte of buffering for various
// network configurations therefore setting payload size to be no more than:
// 65535 - 512 = 65023 bytes
public static final int PACKET_DATA_PAYLOAD_MAX_SIZE = 65023;
protected final Logger logger = LoggerFactory.getLogger(getClass());
protected final Object sendLock = new Object();
protected final SocketAddress socketAddress;
protected final DatagramSocket socket;
// NOTE: We're using dedicated boolean flag to avoid invoking {@link DatagramSocket#isOpen} directly
// on the hot-path which is checking the state of the socket under lock.
protected volatile boolean open;
@GuardedBy("sendLock")
protected ByteBuffer writeBuffer;
private final Object receiveLock = new Object();
@GuardedBy("receiveLock")
private ByteBuffer receiveBuffer;
// NOTE: This is used in tests
TUdpTransport(SocketAddress socketAddress, DatagramSocket socket) {
this.socketAddress = socketAddress;
this.socket = socket;
this.writeBuffer = ByteBuffer.allocate(PACKET_DATA_PAYLOAD_MAX_SIZE);
this.receiveBuffer = ByteBuffer.allocate(PACKET_DATA_PAYLOAD_MAX_SIZE);
// Resets receiving buffer to 0, to make sure it isn't readable
// until it would be first written
this.receiveBuffer.limit(0);
this.open = false;
}
protected TUdpTransport(SocketAddress socketAddress) throws SocketException {
this(socketAddress, new DatagramSocket(null));
}
@Override
public boolean isOpen() {
return open;
}
@Override
public abstract void open() throws TTransportException;
@Override
public void close() {
socket.close();
open = false;
logger.info("UDP socket has been closed");
}
@Override
public int read(byte[] bytes, int offset, int length) throws TTransportException {
if (!isOpen()) {
throw new TTransportException(TTransportException.NOT_OPEN);
}
synchronized (receiveLock) {
if (!receiveBuffer.hasRemaining()) {
// Use ByteBuffer's backing array and manually set the position and limit to
// avoid having to re-copy contents to a new array via `get`
DatagramPacket packet = new DatagramPacket(receiveBuffer.array(), PACKET_DATA_PAYLOAD_MAX_SIZE);
try {
socket.receive(packet);
} catch (IOException e) {
throw new TTransportException("Error from underlying socket", e);
}
receiveBuffer.position(0);
receiveBuffer.limit(packet.getLength());
}
length = Math.min(length, receiveBuffer.remaining());
receiveBuffer.get(bytes, offset, length);
return length;
}
}
@Override
public void write(byte[] bytes, int offset, int length) throws TTransportException {
if (!isOpen()) {
throw new TTransportException(TTransportException.NOT_OPEN);
}
synchronized (sendLock) {
if (writeBuffer.position() + length > PACKET_DATA_PAYLOAD_MAX_SIZE) {
throw new TTransportException(
String.format("Message size too large: %d is greater than available size %d",
length,
PACKET_DATA_PAYLOAD_MAX_SIZE - writeBuffer.position()
)
);
}
writeBuffer.put(bytes, offset, length);
}
}
@Override
public abstract void flush() throws TTransportException;
@Override
public int getBytesRemainingInBuffer() {
synchronized (receiveLock) {
return receiveBuffer.remaining();
}
}
@Override
public byte[] getBuffer() {
synchronized (receiveLock) {
return receiveBuffer.array();
}
}
@Override
public int getBufferPosition() {
synchronized (receiveLock) {
return receiveBuffer.position();
}
}
@Override
public void consumeBuffer(int length) {
synchronized (receiveLock) {
receiveBuffer.position(receiveBuffer.position() + length);
}
}
}
|
package com.mapswithme.maps.location;
import android.annotation.SuppressLint;
import android.net.SSLCertificateSocketFactory;
import android.os.SystemClock;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.mapswithme.maps.BuildConfig;
import com.mapswithme.util.log.DebugLogger;
import com.mapswithme.util.log.Logger;
import javax.net.SocketFactory;
import javax.net.ssl.SSLSocketFactory;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.SocketException;
import java.net.SocketTimeoutException;
/**
* Implements interface that will be used by the core for
* sending/receiving the raw data trough platform socket interface.
* <p>
* The instance of this class is supposed to be created in JNI layer
* and supposed to be used in the thread safe environment, i.e. thread safety
* should be provided externally (by the client of this class).
* <p>
* <b>All public methods are blocking and shouldn't be called from the main thread.</b>
*/
class PlatformSocket
{
private final static Logger sLogger = new DebugLogger(PlatformSocket.class.getSimpleName());
private final static int DEFAULT_TIMEOUT = 30 * 1000;
@Nullable
private Socket mSocket;
@Nullable
private String mHost;
private int mPort;
private int mTimeout = DEFAULT_TIMEOUT;
public boolean open(@NonNull String host, int port)
{
if (mSocket != null)
{
sLogger.e("Socket is already opened. Seems that it wasn't closed.");
return false;
}
if (!isPortAllowed(port))
{
sLogger.e("A wrong port number, it must be within (0-65535) range", port);
return false;
}
mHost = host;
mPort = port;
Socket socket = createSocket(host, port, true);
if (socket != null && socket.isConnected())
{
setReadSocketTimeout(socket, mTimeout);
mSocket = socket;
}
return mSocket != null;
}
private static boolean isPortAllowed(int port)
{
return port >= 0 && port <= 65535;
}
@Nullable
private static Socket createSocket(@NonNull String host, int port, boolean ssl)
{
if (ssl)
{
try
{
SocketFactory sf = getSocketFactory();
return sf.createSocket(host, port);
} catch (IOException e)
{
sLogger.e("Failed to create the ssl socket, mHost = ", host, " mPort = ", port, e);
}
} else
{
try
{
return new Socket(host, port);
} catch (IOException e)
{
sLogger.e("Failed to create the socket, mHost = ", host, " mPort = ", port, e);
}
}
return null;
}
@SuppressLint("SSLCertificateSocketFactoryGetInsecure")
@NonNull
private static SocketFactory getSocketFactory()
{
// Trusting to any ssl certificate factory that will be used in
// debug mode, for testing purposes only.
if (BuildConfig.DEBUG)
//TODO: implement the custom KeyStore to make the self-signed certificates work
return SSLCertificateSocketFactory.getInsecure(0, null);
return SSLSocketFactory.getDefault();
}
public void close()
{
if (mSocket == null)
{
sLogger.d("Socket is already closed or it wasn't opened yet");
return;
}
try
{
mSocket.close();
sLogger.d("Socket has been closed: ", this);
} catch (IOException e)
{
sLogger.e("Failed to close socket: ", this, e);
} finally
{
mSocket = null;
}
}
public boolean read(@NonNull byte[] data, int count)
{
if (!checkSocketAndArguments(data, count))
return false;
sLogger.d("Reading has started, data.length = " + data.length, ", count = " + count);
long startTime = SystemClock.elapsedRealtime();
int readBytes = 0;
try
{
if (mSocket == null)
throw new AssertionError("mSocket cannot be null");
InputStream in = mSocket.getInputStream();
while (readBytes != count && (SystemClock.elapsedRealtime() - startTime) < mTimeout)
{
try
{
sLogger.d("Attempting to read ", count, " bytes from offset = ", readBytes);
int read = in.read(data, readBytes, count - readBytes);
if (read == -1)
{
sLogger.d("All data have been read from the stream, read bytes count = ", readBytes);
break;
}
if (read == 0)
{
sLogger.e("0 bytes have been obtained. It's considered as error");
break;
}
sLogger.d("Read bytes count = ", read);
readBytes += read;
} catch (SocketTimeoutException e)
{
long readingTime = SystemClock.elapsedRealtime() - startTime;
sLogger.e(e, "Socked timeout has occurred after ", readingTime, " (ms) ");
if (readingTime > mTimeout)
{
sLogger.e("Socket wrapper timeout has occurred, requested count = ",
count - readBytes, ", " + "readBytes = ", readBytes);
break;
}
}
}
} catch (IOException e)
{
sLogger.e(e, "Failed to read data from socket: ", this);
}
return count == readBytes;
}
public boolean write(@NonNull byte[] data, int count)
{
if (!checkSocketAndArguments(data, count))
return false;
sLogger.d("Writing method has started, data.length = " + data.length, ", count = " + count);
long startTime = SystemClock.elapsedRealtime();
try
{
if (mSocket == null)
throw new AssertionError("mSocket cannot be null");
OutputStream out = mSocket.getOutputStream();
out.write(data, 0, count);
sLogger.d(count + " bytes have been written");
return true;
} catch (SocketTimeoutException e)
{
long writingTime = SystemClock.elapsedRealtime() - startTime;
sLogger.e(e, "Socked timeout has occurred after ", writingTime, " (ms) ");
} catch (IOException e)
{
sLogger.e(e, "Failed to write data to socket: ", this);
}
return false;
}
private boolean checkSocketAndArguments(@NonNull byte[] data, int count)
{
if (mSocket == null)
{
sLogger.e("Socket must be opened before reading/writing");
return false;
}
if (data.length < 0 || count < 0 || count > data.length)
{
sLogger.e("Illegal arguments, data.length = ", data.length, ", count = " + count);
return false;
}
return true;
}
public void setTimeout(int millis)
{
mTimeout = millis;
sLogger.d("Setting the socket wrapper timeout = ", millis, " ms");
}
private void setReadSocketTimeout(@NonNull Socket socket, int millis)
{
try
{
socket.setSoTimeout(millis);
} catch (SocketException e)
{
sLogger.e("Failed to set system socket timeout: ", millis, "ms, ", this, e);
}
}
@Override
public String toString()
{
return "PlatformSocket{" +
"mSocket=" + mSocket +
", mHost='" + mHost + '\'' +
", mPort=" + mPort +
'}';
}
}
|
package urteam.user;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.fasterxml.jackson.annotation.JsonView;
import urteam.community.Community;
import urteam.event.Event;
@RestController
@RequestMapping("/api/users")
public class UserRestController {
public interface MinimalUser extends User.MinimalUser{}
public interface BasicUser extends User.MinimalUser,User.BasicUser {}
public interface CompleteUser extends User.MinimalUser, User.CompleteUser, User.BasicUser, Event.BasicEvent, Community.BasicCommunity {}
public interface FriendUser extends User.MinimalUser, User.CompleteUser {}
@Autowired
private UserService userService;
@Autowired
private UserComponent userComponent;
@JsonView(MinimalUser.class)
@RequestMapping(value = "/", method = RequestMethod.GET)
@ResponseStatus(HttpStatus.OK)
public ResponseEntity<List<User>> getUsers() {
List<User> users = userService.getUsers();
if (users != null) {
return new ResponseEntity<>(users, HttpStatus.OK);
} else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
@JsonView(CompleteUser.class)
@RequestMapping(value = "/{nickname}", method = RequestMethod.GET)
@ResponseStatus(HttpStatus.OK)
public ResponseEntity<User> getUser(@PathVariable String nickname) {
User user = userService.getUser(nickname);
if (user != null) {
return new ResponseEntity<>(user, HttpStatus.OK);
} else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
@JsonView(BasicUser.class)
@RequestMapping(value = "/{nickname}", method = RequestMethod.PUT)
public ResponseEntity<User> updateUserInfo(@PathVariable String nickname, @RequestBody User user) {
User updatedUser = userService.getUser(nickname);
User userLogged = userService.findOne(userComponent.getLoggedUser().getId());
if(updatedUser == userLogged){
if (updatedUser != null) {
updatedUser = userService.updateUserInfo(nickname, user);
return new ResponseEntity<>(updatedUser, HttpStatus.OK);
} else {
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
}else{
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
}
@JsonView(BasicUser.class)
@RequestMapping(value = "/{nickname}/avatar", method = RequestMethod.PUT)
public ResponseEntity<User> updateUserAvatar(@PathVariable String nickname, @RequestBody MultipartFile file) {
User updatedUserAvatar = userService.getUser(nickname);
if (userService.findOne(userComponent.getLoggedUser().getId()) != null ){
User userLogged = userService.findOne(userComponent.getLoggedUser().getId());
if(updatedUserAvatar == userLogged){
if (updatedUserAvatar != null) {
updatedUserAvatar = userService.updateUserAvatar(nickname, file);
return new ResponseEntity<>(updatedUserAvatar, HttpStatus.OK);
} else {
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
}
}
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
@JsonView(BasicUser.class)
@RequestMapping(value = "/", method = RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED)
public ResponseEntity<User> createUser(@RequestBody User user) {
User newUser = userService.createNewUser(user);
if (newUser != null) {
return new ResponseEntity<>(newUser, HttpStatus.OK);
} else {
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
}
@JsonView(MinimalUser.class)
@RequestMapping(value = "/{nickname}/friends", method = RequestMethod.PUT)
public ResponseEntity<List<User>> followUnfollowUser(@PathVariable String nickname) {
if (userService.findOne(userComponent.getLoggedUser().getId()) != null ){
User userToFollow = userService.getUser(nickname);
User userLogged = userService.findOne(userComponent.getLoggedUser().getId());
if(userLogged != userToFollow){
List<User> friends = userService.getFriends(nickname);
if (friends != null) {
friends = userService.followUnfollow( userLogged, nickname);
return new ResponseEntity<>(friends, HttpStatus.OK);
} else {
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
}
}
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
@JsonView(FriendUser.class)
@RequestMapping(value = "/{nickname}/friends", method = RequestMethod.GET)
public ResponseEntity<List<User>> getFriends(@PathVariable String nickname) {
List<User> friends = userService.getFriends(nickname);
if (friends != null) {
return new ResponseEntity<>(friends, HttpStatus.OK);
} else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
@JsonView(FriendUser.class)
@RequestMapping(value = "/{nickname}/followers", method = RequestMethod.GET)
public ResponseEntity<List<User>> getFollowers(@PathVariable String nickname) {
List<User> followers = userService.getFollowers(nickname);
if (followers != null) {
return new ResponseEntity<>(followers, HttpStatus.OK);
} else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
}
|
package cgeo.geocaching.connector.opencaching;
import cgeo.geocaching.Parameters;
import cgeo.geocaching.cgBase;
import cgeo.geocaching.cgCache;
import cgeo.geocaching.cgImage;
import cgeo.geocaching.cgLog;
import cgeo.geocaching.connector.ConnectorFactory;
import cgeo.geocaching.connector.IConnector;
import cgeo.geocaching.enumerations.CacheSize;
import cgeo.geocaching.enumerations.CacheType;
import cgeo.geocaching.geopoint.GeopointParser;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.net.Uri;
import android.text.Html;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
final public class OkapiClient {
private static final String CACHE_VOTES = "rating_votes";
private static final String CACHE_NOTFOUNDS = "notfounds";
private static final String CACHE_FOUNDS = "founds";
private static final String CACHE_HIDDEN = "date_hidden";
private static final String CACHE_LATEST_LOGS = "latest_logs";
private static final String CACHE_IMAGE_URL = "url";
private static final String CACHE_IMAGE_CAPTION = "caption";
private static final String CACHE_IMAGE_IS_SPOILER = "is_spoiler";
private static final String CACHE_IMAGES = "images";
private static final String CACHE_HINT = "hint";
private static final String CACHE_DESCRIPTION = "description";
private static final String CACHE_RECOMMENDATIONS = "recommendations";
private static final String CACHE_RATING = "rating";
private static final String CACHE_TERRAIN = "terrain";
private static final String CACHE_DIFFICULTY = "difficulty";
private static final String CACHE_OWNER = "owner";
private static final String CACHE_STATUS = "status";
private static final String CACHE_TYPE = "type";
private static final String CACHE_LOCATION = "location";
private static final String CACHE_NAME = "name";
private static final String CACHE_CODE = "code";
private static final String LOG_TYPE = "type";
private static final String LOG_COMMENT = "comment";
private static final String LOG_DATE = "date";
private static final String LOG_USER = "user";
private static final String USER_USERNAME = "username";
private static final String SERVICE_CACHE = "/okapi/services/caches/geocache";
private static final String SERVICE_CACHE_FIELDS = "code|name|location|type|status|owner|founds|notfounds|size|difficulty|terrain|rating|rating_votes|recommendations|description|hint|images|latest_logs|date_hidden";
public static cgCache getCache(final String geoCode) {
final Parameters params = new Parameters("cache_code", geoCode, "fields", SERVICE_CACHE_FIELDS);
final JSONObject data = request(geoCode, SERVICE_CACHE, params);
if (data == null) {
return null;
}
final cgCache cache = parseCache(data);
cache.setUpdated(new Date().getTime());
cache.setDetailedUpdate(new Date().getTime());
return cache;
}
private static cgCache parseCache(final JSONObject response) {
final cgCache cache = new cgCache();
try {
cache.setGeocode(response.getString(CACHE_CODE));
cache.setName(response.getString(CACHE_NAME));
// not used: names
setLocation(cache, response.getString(CACHE_LOCATION));
cache.setCacheType(getCacheType(response.getString(CACHE_TYPE)));
final String status = response.getString(CACHE_STATUS);
cache.setDisabled(status.equalsIgnoreCase("Temporarily unavailable"));
cache.setArchived(status.equalsIgnoreCase("Archived"));
// not used: url
final JSONObject owner = response.getJSONObject(CACHE_OWNER);
cache.setOwner(parseUser(owner));
cache.getLogCounts().put(cgBase.LOG_FOUND_IT, response.getInt(CACHE_FOUNDS));
cache.getLogCounts().put(cgBase.LOG_DIDNT_FIND_IT, response.getInt(CACHE_NOTFOUNDS));
cache.setSize(getCacheSize(response));
cache.setDifficulty((float) response.getDouble(CACHE_DIFFICULTY));
cache.setTerrain((float) response.getDouble(CACHE_TERRAIN));
if (response.has(CACHE_RATING) && !isNull(response.getString(CACHE_RATING))) {
cache.setRating((float) response.getDouble(CACHE_RATING));
}
cache.setVotes(response.getInt(CACHE_VOTES));
cache.setFavouriteCnt(response.getInt(CACHE_RECOMMENDATIONS));
// not used: req_password
cache.setDescription(response.getString(CACHE_DESCRIPTION));
cache.setHint(Html.fromHtml(response.getString(CACHE_HINT)).toString());
// not used: hints
final JSONArray images = response.getJSONArray(CACHE_IMAGES);
if (images != null) {
JSONObject imageResponse;
cgImage image;
for (int i = 0; i < images.length(); i++) {
imageResponse = images.getJSONObject(i);
if (imageResponse.getBoolean(CACHE_IMAGE_IS_SPOILER)) {
image = new cgImage();
image.title = imageResponse.getString(CACHE_IMAGE_CAPTION);
image.url = absoluteUrl(imageResponse.getString(CACHE_IMAGE_URL), cache.getGeocode());
if (cache.getSpoilers() == null) {
cache.setSpoilers(new ArrayList<cgImage>());
}
cache.getSpoilers().add(image);
}
}
}
// not used: attrnames
cache.setLogs(parseLogs(response.getJSONArray(CACHE_LATEST_LOGS)));
cache.setHidden(parseDate(response.getString(CACHE_HIDDEN)));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return cache;
}
private static String absoluteUrl(String url, String geocode) {
final Uri uri = Uri.parse(url);
if (!uri.isAbsolute()) {
final IConnector connector = ConnectorFactory.getConnector(geocode);
final String host = connector.getHost();
if (StringUtils.isNotBlank(host)) {
return "http://" + host + "/" + url;
}
}
return url;
}
private static boolean isNull(String string) {
return string.equalsIgnoreCase("null");
}
private static String parseUser(JSONObject user) throws JSONException {
return user.getString(USER_USERNAME);
}
private static List<cgLog> parseLogs(JSONArray logsJSON) {
List<cgLog> result = null;
for (int i = 0; i < logsJSON.length(); i++) {
try {
JSONObject logResponse = logsJSON.getJSONObject(i);
cgLog log = new cgLog();
log.date = parseDate(logResponse.getString(LOG_DATE)).getTime();
log.log = logResponse.getString(LOG_COMMENT).trim();
log.type = parseLogType(logResponse.getString(LOG_TYPE));
log.author = parseUser(logResponse.getJSONObject(LOG_USER));
if (result == null) {
result = new ArrayList<cgLog>();
}
result.add(log);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return result;
}
private static int parseLogType(String logType) {
if ("Found it".equalsIgnoreCase(logType)) {
return cgBase.LOG_FOUND_IT;
}
else if ("Didn't find it".equalsIgnoreCase(logType)) {
return cgBase.LOG_DIDNT_FIND_IT;
}
return cgBase.LOG_NOTE;
}
private static Date parseDate(final String date) {
final SimpleDateFormat ISO8601DATEFORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.getDefault());
final String strippedDate = date.replaceAll("\\+0([0-9]){1}\\:00", "+0$100");
try {
return ISO8601DATEFORMAT.parse(strippedDate);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
private static void setLocation(final cgCache cache, final String location) {
final String latitude = StringUtils.substringBefore(location, "|");
final String longitude = StringUtils.substringAfter(location, "|");
// FIXME: the next line should be a setter at cgCache
cache.setCoords(GeopointParser.parse(latitude, longitude));
}
private static CacheSize getCacheSize(final JSONObject response) {
double size = 0;
try {
size = response.getDouble("size");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
switch ((int) Math.round(size)) {
case 1:
return CacheSize.MICRO;
case 2:
return CacheSize.SMALL;
case 3:
return CacheSize.REGULAR;
case 4:
return CacheSize.LARGE;
case 5:
return CacheSize.LARGE;
default:
break;
}
return CacheSize.NOT_CHOSEN;
}
private static CacheType getCacheType(final String type) {
if (type.equalsIgnoreCase("Traditional")) {
return CacheType.TRADITIONAL;
} else if (type.equalsIgnoreCase("Multi")) {
return CacheType.MULTI;
} else if (type.equalsIgnoreCase("Quiz")) {
return CacheType.MYSTERY;
} else if (type.equalsIgnoreCase("Virtual")) {
return CacheType.VIRTUAL;
}
return CacheType.UNKNOWN;
}
private static JSONObject request(final String geoCode, final String service, final Parameters params) {
final IConnector connector = ConnectorFactory.getConnector(geoCode);
if (connector == null) {
return null;
}
if (!(connector instanceof ApiOpenCachingConnector)) {
return null;
}
final String host = connector.getHost();
if (StringUtils.isBlank(host)) {
return null;
}
final String uri = "http://" + host + service;
((ApiOpenCachingConnector) connector).addAuthentication(params);
return cgBase.requestJSON(uri, params);
}
}
|
package annotator.find;
import annotator.Main;
import java.io.*;
import java.util.*;
import javax.tools.*;
import com.sun.source.tree.*;
import com.sun.source.util.*;
import com.sun.source.util.TreeScanner;
import com.sun.tools.javac.tree.*;
import com.sun.tools.javac.tree.JCTree.*;
import com.google.common.collect.*;
/**
* A {@code TreeScanner} that is able to locate program elements in an
* AST based on {@code Criteria}. It is used to scan a tree and return a
* mapping of source positions (as character offsets) to insertion text.
*/
public class TreeFinder extends TreeScanner<Void, List<Insertion>> {
static public boolean debug = false;
private static void debug(String message) {
if (debug)
System.out.println(message);
}
/**
* Used to determine the insertion position for various elements. For
* instance, variable annotations should be placed before the variable's
* <i>type</i> rather than its name.
*/
private static class TypePositionFinder extends TreeScanner<Integer, Void> {
private CompilationUnitTree tree;
public TypePositionFinder(CompilationUnitTree tree) {
super();
this.tree = tree;
}
/** et should be an expression for a type */
private JCTree leftmostIdentifier(JCTree t) {
while (true) {
switch (t.getKind()) {
case IDENTIFIER:
case PRIMITIVE_TYPE:
return t;
case MEMBER_SELECT:
t = ((JCFieldAccess) t).getExpression();
break;
case ARRAY_TYPE:
t = ((JCArrayTypeTree) t).elemtype;
break;
default:
throw new RuntimeException(String.format("Unrecognized type (kind=%s, class=%s): %s", t.getKind(), t.getClass(), t));
}
}
}
@Override
public Integer visitVariable(VariableTree node, Void p) {
JCTree jt = ((JCVariableDecl) node).getType();
if (jt instanceof JCTypeApply) {
JCTypeApply vt = (JCTypeApply) jt;
return vt.clazz.pos;
}
JCExpression type = (JCExpression) (((JCVariableDecl)node).getType());
return leftmostIdentifier(type).pos;
}
// When a method is visited, it is visited for the receiver, not the return value.
@Override
public Integer visitMethod(MethodTree node, Void p) {
super.visitMethod(node, p);
// System.out.println("node: " + node);
// System.out.println("return: " + node.getReturnType());
// location for the receiver annotation
int receiverLoc;
JCMethodDecl jcnode = (JCMethodDecl) node;
List<JCExpression> throwsExpressions = jcnode.thrown;
JCBlock body = jcnode.getBody();
List<JCTypeAnnotation> receiverAnnotations = jcnode.receiverAnnotations;
if (! throwsExpressions.isEmpty()) {
// has a throws expression
IdentifierTree it = (IdentifierTree) leftmostIdentifier(throwsExpressions.get(0));
receiverLoc = this.visitIdentifier(it, p);
receiverLoc -= 7; // for the 'throws' clause
// Search backwards for the close paren. Hope for no problems with
// comments.
JavaFileObject jfo = tree.getSourceFile();
try {
String s = String.valueOf(jfo.getCharContent(true));
for (int i = receiverLoc; i >= 0; i
if (s.charAt(i) == ')') {
receiverLoc = i + 1;
break;
}
}
} catch(IOException e) {
throw new RuntimeException(e);
}
} else if (body != null) {
// has a body
receiverLoc = body.pos;
} else if (! receiverAnnotations.isEmpty()) {
// has receiver annotations. After them would be better, but for
// now put the new one at the front.
receiverLoc = receiverAnnotations.get(0).pos;
} else {
// try the last parameter, or failing that the return value
List<? extends VariableTree> params = jcnode.getParameters();
if (! params.isEmpty()) {
VariableTree lastParam = params.get(params.size()-1);
receiverLoc = ((JCVariableDecl) lastParam).pos;
} else {
receiverLoc = jcnode.restype.pos;
}
// Search forwards for the close paren. Hope for no problems with
// comments.
JavaFileObject jfo = tree.getSourceFile();
try {
String s = String.valueOf(jfo.getCharContent(true));
for (int i = receiverLoc; i < s.length(); i++) {
if (s.charAt(i) == ')') {
receiverLoc = i + 1;
break;
}
}
} catch(IOException e) {
throw new RuntimeException(e);
}
}
// TODO:
//debugging: System.out.println("result: " + receiverLoc);
return receiverLoc;
// // old implementations scans characters in the source (which is error-prone).
// if (i.getCriteria().isOnReceiver()) {
// CharSequence s = null;
// try {
// s = path.getCompilationUnit().getSourceFile().getCharContent(true);
// } catch(Exception e) {
// throw new RuntimeException("problem with receiver: " + e.getMessage(), e);
// // For a receiver, the match is on the method name.
// // Therefore, scan forward until after the first ')' encountered
// for (int j = pos; j < s.length(); j++) {
// if (s.charAt(j) == ')') {
// pos = j + 1;
// break;
// return ((JCMethodDecl)node).getReturnType().pos;
}
private int getFirstBracketAfter(int i) {
try {
CharSequence s = tree.getSourceFile().getCharContent(true);
// return first [, plus 1
for (int j=i; j < s.length(); j++) {
if (s.charAt(j) == '[') {
return j;
}
}
} catch(Exception e) {
throw new RuntimeException(e);
}
return i;
}
@Override
public Integer visitIdentifier(IdentifierTree node, Void p) {
// for arrays, need to indent inside array, not right before type
TreePath path = TreePath.getPath(tree, node);
Tree parent = path.getParentPath().getLeaf();
Integer i = null;
if (parent instanceof ArrayTypeTree) {
debug("TypePositionFinder.visitIdentifier: recognized array");
ArrayTypeTree att = (ArrayTypeTree) parent;
JCIdent jcid = (JCIdent) node;
i = jcid.pos;
} else {
i = ((JCIdent) node).pos;
}
debug("visitId: " + i);
return i;
}
@Override
public Integer visitPrimitiveType(PrimitiveTypeTree node, Void p) {
// want exact same logistics as with visitIdentifier
TreePath path = TreePath.getPath(tree, node);
Tree parent = path.getParentPath().getLeaf();
Integer i = null;
if (parent instanceof ArrayTypeTree) {
ArrayTypeTree att = (ArrayTypeTree) parent;
JCTree jcid = (JCTree) node;
i = jcid.pos;
} else {
i = ((JCTree) node).pos;
}
// JCPrimitiveTypeTree pt = (JCPrimitiveTypeTree) node;
JCTree jt = (JCTree) node;
return i;
}
@Override
public Integer visitParameterizedType(ParameterizedTypeTree node, Void p) {
TreePath path = TreePath.getPath(tree, node);
Tree parent = path.getParentPath().getLeaf();
Integer i = null;
if (parent instanceof ArrayTypeTree) {
// want to annotate the first level of this array
ArrayTypeTree att = (ArrayTypeTree) parent;
Tree baseType = att.getType();
i = leftmostIdentifier(((JCTypeApply) node).getType()).pos;
debug("BASE TYPE: " + baseType.toString());
} else {
i = leftmostIdentifier(((JCTypeApply)node).getType()).pos;
}
return i;
}
// @Override
// public Integer visitBlock(BlockTree node, Void p) {
// //debugging: System.out.println("visitBlock");
// int rightBeforeBlock = ((JCBlock) node).pos;
// // Will be adjusted if a throws statement exists.
// int afterParamList = -1;
// TreePath path = TreePath.getPath(tree, node);
// Tree methodTree = path.getParentPath().getLeaf();
// if (!(methodTree.getKind() == Tree.Kind.METHOD)) {
// throw new RuntimeException("BlockTree has non-method parent");
// MethodTree mt = (MethodTree) methodTree;
// // TODO: figure out how to better place reciever annotation!!!
// // List<? extends VariableTree> vars = mt.getParameters();
// // VariableTree vt = vars.get(0);
// // vt.getName().length();
// List<? extends ExpressionTree> throwsExpressions = mt.getThrows();
// if (throwsExpressions.isEmpty()) {
// afterParamList = rightBeforeBlock;
// } else {
// ExpressionTree et = throwsExpressions.get(0);
// while (afterParamList == -1) {
// switch (et.getKind()) {
// case IDENTIFIER:
// afterParamList = this.visitIdentifier((IdentifierTree) et, p);
// afterParamList -= 7; // for the 'throws' clause
// JavaFileObject jfo = tree.getSourceFile();
// try {
// String s = String.valueOf(jfo.getCharContent(true));
// for (int i = afterParamList; i >= 0; i--) {
// if (s.charAt(i) == ')') {
// afterParamList = i + 1;
// break;
// } catch(IOException e) {
// throw new RuntimeException(e);
// break;
// case MEMBER_SELECT:
// et = ((MemberSelectTree) et).getExpression();
// break;
// default:
// throw new RuntimeException("Unrecognized throws (kind=" + et.getKind() + "): " + et);
// // TODO:
// //debugging: System.out.println("result: " + afterParamList);
// return afterParamList;
@Override
public Integer visitArrayType(ArrayTypeTree node, Void p) {
JCArrayTypeTree att = (JCArrayTypeTree) node;
return att.getPreferredPosition();
}
@Override
public Integer visitCompilationUnit(CompilationUnitTree node, Void p) {
JCCompilationUnit cu = (JCCompilationUnit) node;
JCTree.JCExpression pid = cu.pid;
while (pid instanceof JCTree.JCFieldAccess) {
pid = ((JCTree.JCFieldAccess) pid).selected;
}
JCTree.JCIdent firstComponent = (JCTree.JCIdent) pid;
int result = firstComponent.getPreferredPosition();
// Now back up over the word "package" and the preceding newline
JavaFileObject jfo = tree.getSourceFile();
String fileContent;
try {
fileContent = String.valueOf(jfo.getCharContent(true));
} catch(IOException e) {
throw new RuntimeException(e);
}
while (java.lang.Character.isWhitespace(fileContent.charAt(result-1))) {
result
}
result -= 7;
String packageString = fileContent.substring(result, result+7);
assert "package".equals(packageString) : "expected 'package', got: " + packageString;
assert result == 0 || java.lang.Character.isWhitespace(fileContent.charAt(result-1));
return result;
}
@Override
public Integer visitClass(ClassTree node, Void p) {
JCClassDecl cd = (JCClassDecl) node;
if (cd.mods != null) {
return cd.mods.getPreferredPosition();
} else {
return cd.getPreferredPosition();
}
}
}
/**
* A comparator for sorting integers in reverse
*/
public static class ReverseIntegerComparator implements Comparator<Integer> {
public int compare(Integer o1, Integer o2) {
return o1.compareTo(o2) * -1;
}
}
private Map<Tree, TreePath> paths;
private TypePositionFinder tpf;
private CompilationUnitTree tree;
private SetMultimap<Integer, String> positions;
// Set of insertions that got added; any insertion not in this set could
// not be added.
private Set<Insertion> satisfied;
/**
* Creates a {@code TreeFinder} from a source tree.
*
* @param tree the source tree to search
*/
public TreeFinder(CompilationUnitTree tree) {
this.tree = tree;
this.positions = LinkedHashMultimap.create();
this.tpf = new TypePositionFinder(tree);
this.paths = new HashMap<Tree, TreePath>();
this.satisfied = new HashSet<Insertion>();
}
boolean handled(Tree node) {
return (node instanceof CompilationUnitTree
|| node instanceof ClassTree
|| node instanceof MethodTree
|| node instanceof VariableTree
|| node instanceof IdentifierTree
|| node instanceof ParameterizedTypeTree
|| node instanceof BlockTree
|| node instanceof ArrayTypeTree
|| node instanceof PrimitiveTypeTree);
}
/**
* Scans this tree, using the list of insertions to generate the source
* position to insertion text mapping.
*/
@Override
public Void scan(Tree node, List<Insertion> p) {
if (node == null) {
return null;
}
if (! handled(node)) {
// nothing to do
return super.scan(node, p);
}
TreePath path;
if (paths.containsKey(tree))
path = paths.get(tree);
else
path = TreePath.getPath(tree, node);
assert path == null || path.getLeaf() == node :
String.format("Mismatch: '%s' '%s' '%s' '%s'%n", path, tree, paths.containsKey(tree), node);
// To avoid annotating existing annotations right before
// the element you wish to annotate, skip anything inside of
// an annotation.
if (path != null) {
for (Tree t : path) {
if (t.getKind() == Tree.Kind.ANNOTATION) {
return super.scan(node, p);
}
}
}
for (Insertion i : p) {
if (satisfied.contains(i))
continue;
if (debug) {
debug("Considering insertion at tree:");
debug(" " + i);
debug(" " + Main.firstLine(node.toString()));
}
if (!i.getCriteria().isSatisfiedBy(path, node)) {
debug(" ... not satisfied");
continue;
} else {
debug(" ... satisfied!");
}
// Question: is this particular annotation already present at this location?
// If so, we don't want to insert a duplicate.
ModifiersTree mt = null;
for (Tree n : path) {
if (n instanceof ClassTree) {
mt = ((ClassTree) n).getModifiers();
break;
} else if (n instanceof MethodTree) {
mt = ((MethodTree) n).getModifiers();
break;
} else if (n instanceof VariableTree) {
mt = ((VariableTree) n).getModifiers();
break;
}
}
// System.out.printf("mt = %s for %s%n", mt, node.getKind());
// printPath(path);
if (mt != null) {
for (AnnotationTree at : mt.getAnnotations()) {
String ann = at.toString();
if (ann.equals(i.getText())
|| ann.equals(i.getText() + "()")) {
satisfied.add(i);
return super.scan(node, p);
}
}
}
// If this is a method, then it might have been selected because of
// the receiver, or because of the return value. Distinguish those.
// One way would be to set a global variable here. Another would be
// to look for a particular different node. I will do the latter.
Integer pos;
if ((node instanceof MethodTree) && ! i.getCriteria().isOnReceiver()) {
// we must be looking for the return type
pos = tpf.scan(((MethodTree)node).getReturnType(), null);
assert handled(node);
// System.out.println("return type node: " + ((JCMethodDecl)node).getReturnType().getClass());
} else {
pos = tpf.scan(node, null);
assert pos != null;
}
assert pos >= 0 : pos;
debug(" ... satisfied! at " + pos + " for node of type " + node.getClass() + ": " + Main.treeToString(node));
if (pos != null) {
positions.put(pos, i.getText());
}
satisfied.add(i);
}
return super.scan(node, p);
}
/**
* Scans the given tree with the given insertion list and returns the
* source position to insertion text mapping. The positions are sorted
* in decreasing order of index, so that inserting one doesn't throw
* off the index for a subsequent one.
*
* <p>
* <i>N.B.:</i> This method calls {@code scan()} internally.
* </p>
*
* @param node the tree to scan
* @param p the list of insertion criteria
* @return the source position to insertion text mapping
*/
public SetMultimap<Integer, String> getPositions(Tree node, List<Insertion> p) {
this.scan(node, p);
// This needs to be optional, because there may be many extra
// annotations in a .jaif file.
if (debug) {
// Output every insertion that was not given a position:
for (Insertion i : p) {
if (!satisfied.contains(i) ) { // TODO: && options.hasOption("x")) {
System.err.println("Unable to insert: " + i);
}
}
}
return Multimaps.unmodifiableSetMultimap(positions);
}
private static void printPath(TreePath path) {
System.out.printf("
if (path != null) {
for (Tree t : path) {
System.out.printf("%s %s%n", t.getKind(), t);
}
}
System.out.printf("
}
}
|
package me.nallar.tickthreading.minecraft;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.event.FMLServerStartingEvent;
import cpw.mods.fml.common.network.NetworkMod;
import me.nallar.tickthreading.Log;
import me.nallar.tickthreading.minecraft.commands.TPSCommand;
import me.nallar.tickthreading.minecraft.commands.TicksCommand;
import me.nallar.tickthreading.minecraft.entitylist.EntityList;
import me.nallar.tickthreading.minecraft.entitylist.LoadedEntityList;
import me.nallar.tickthreading.minecraft.entitylist.LoadedTileEntityList;
import me.nallar.tickthreading.patcher.PatchManager;
import me.nallar.tickthreading.util.FieldUtil;
import me.nallar.tickthreading.util.LocationUtil;
import me.nallar.tickthreading.util.PatchUtil;
import net.minecraft.command.ServerCommandManager;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;
import net.minecraftforge.common.Configuration;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.common.Property;
import net.minecraftforge.event.ForgeSubscribe;
import net.minecraftforge.event.world.WorldEvent;
@SuppressWarnings ("WeakerAccess")
@Mod (modid = "TickThreading", name = "TickThreading", version = "1.0")
@NetworkMod (clientSideRequired = false, serverSideRequired = false)
public class TickThreading {
private final int loadedTileEntityFieldIndex = 2;
private final int loadedEntityFieldIndex = 0;
public final boolean enabled;
private int minimumTickThreads = 0;
private int maximumTickThreads = 0;
private boolean enableEntityTickThreading = true;
private boolean enableTileEntityTickThreading = true;
private int regionSize = 16;
private boolean variableTickRate = true;
private boolean requirePatched = true;
final Map<World, TickManager> managers = new HashMap<World, TickManager>();
private static TickThreading instance;
public TickThreading() {
if (requirePatched && PatchManager.shouldPatch(LocationUtil.getJarLocations())) {
enabled = false;
try {
PatchUtil.writePatchRunners();
} catch (IOException e) {
Log.severe("Failed to write patch runners", e);
}
} else {
enabled = true;
}
}
@Mod.Init
public void init(FMLInitializationEvent event) {
if (enabled) {
MinecraftForge.EVENT_BUS.register(this);
}
instance = this;
}
@Mod.PreInit
public void preInit(FMLPreInitializationEvent event) {
Configuration config = new Configuration(event.getSuggestedConfigurationFile());
config.load();
Property minimumTickThreadsProperty = config.get(Configuration.CATEGORY_GENERAL, "minimumTickThreads", minimumTickThreads);
minimumTickThreadsProperty.comment = "minimum number of threads to use to tick. 0 = automatic";
Property maximumTickThreadsProperty = config.get(Configuration.CATEGORY_GENERAL, "maximumTickThreads", maximumTickThreads);
maximumTickThreadsProperty.comment = "maximum number of threads to use to tick. 0 = automatic";
Property enableEntityTickThreadingProperty = config.get(Configuration.CATEGORY_GENERAL, "enableEntityTickThreading", enableEntityTickThreading);
enableEntityTickThreadingProperty.comment = "Whether entity ticks should be threaded";
Property enableTileEntityTickThreadingProperty = config.get(Configuration.CATEGORY_GENERAL, "enableTileEntityTickThreading", enableTileEntityTickThreading);
enableTileEntityTickThreadingProperty.comment = "Whether tile entity ticks should be threaded";
Property regionSizeProperty = config.get(Configuration.CATEGORY_GENERAL, "regionSize", regionSize);
regionSizeProperty.comment = "width/length of tick regions, specified in blocks.";
Property variableTickRateProperty = config.get(Configuration.CATEGORY_GENERAL, "variableRegionTickRate", variableTickRate);
variableTickRateProperty.comment = "Allows tick rate to vary per region so that each region uses at most 50ms on average per tick.";
Property ticksCommandName = config.get(Configuration.CATEGORY_GENERAL, "ticksCommandName", TicksCommand.name);
ticksCommandName.comment = "Name of the command to be used for performance stats. Defaults to ticks.";
Property tpsCommandName = config.get(Configuration.CATEGORY_GENERAL, "tpsCommandName", TPSCommand.name);
tpsCommandName.comment = "Name of the command to be used for TPS reports.";
Property requirePatchedProperty = config.get(Configuration.CATEGORY_GENERAL, "requirePatched", requirePatched);
requirePatchedProperty.comment = "If the server must be patched to run with TickThreading";
config.save();
minimumTickThreads = minimumTickThreadsProperty.getInt(minimumTickThreads);
maximumTickThreads = maximumTickThreadsProperty.getInt(maximumTickThreads);
enableEntityTickThreading = enableEntityTickThreadingProperty.getBoolean(enableEntityTickThreading);
enableTileEntityTickThreading = enableTileEntityTickThreadingProperty.getBoolean(enableTileEntityTickThreading);
regionSize = regionSizeProperty.getInt(regionSize);
variableTickRate = variableTickRateProperty.getBoolean(variableTickRate);
TicksCommand.name = ticksCommandName.value;
TPSCommand.name = tpsCommandName.value;
requirePatched = requirePatchedProperty.getBoolean(requirePatched);
}
@Mod.ServerStarting
public void serverStarting(FMLServerStartingEvent event) {
if (enabled) {
ServerCommandManager serverCommandManager = (ServerCommandManager) event.getServer().getCommandManager();
serverCommandManager.registerCommand(new TicksCommand());
serverCommandManager.registerCommand(new TPSCommand());
} else {
Log.severe("TickThreading is disabled, because your server has not been patched!" +
"\nTo patch your server, simply run the PATCHME.bat/sh file in your server directory" +
"\nAlternatively, you can try to run without patching, just edit the config. Probably won't end well.");
}
}
@ForgeSubscribe
public void onWorldLoad(WorldEvent.Load event) {
TickManager manager = new TickManager(event.world, regionSize, minimumTickThreads, maximumTickThreads);
manager.setVariableTickRate(variableTickRate);
try {
if (enableTileEntityTickThreading) {
Field loadedTileEntityField = FieldUtil.getFields(World.class, List.class)[loadedTileEntityFieldIndex];
new LoadedTileEntityList<TileEntity>(event.world, loadedTileEntityField, manager);
}
if (enableEntityTickThreading) {
Field loadedEntityField = FieldUtil.getFields(World.class, List.class)[loadedEntityFieldIndex];
new LoadedEntityList<TileEntity>(event.world, loadedEntityField, manager);
}
Log.info("Threading initialised for world " + Log.name(event.world));
managers.put(event.world, manager);
} catch (Exception e) {
Log.severe("Failed to initialise threading for world " + Log.name(event.world), e);
}
}
@ForgeSubscribe
public void onWorldUnload(WorldEvent.Unload event) {
managers.remove(event.world);
try {
if (enableTileEntityTickThreading) {
Field loadedTileEntityField = FieldUtil.getFields(World.class, List.class)[loadedTileEntityFieldIndex];
Object loadedTileEntityList = loadedTileEntityField.get(event.world);
if (loadedTileEntityList instanceof EntityList) {
((EntityList) loadedTileEntityList).unload();
} else {
Log.severe("Looks like another mod broke TickThreading in world: " + Log.name(event.world));
}
}
if (enableEntityTickThreading) {
Field loadedEntityField = FieldUtil.getFields(World.class, List.class)[loadedEntityFieldIndex];
Object loadedEntityList = loadedEntityField.get(event.world);
if (loadedEntityList instanceof EntityList) {
((EntityList) loadedEntityList).unload();
} else {
Log.severe("Looks like another mod broke TickThreading in world: " + Log.name(event.world));
}
}
} catch (Exception e) {
Log.severe("Probable memory leak, failed to unload threading for world " + Log.name(event.world), e);
}
}
public TickManager getManager(World world) {
return managers.get(world);
}
public List<TickManager> getManagers() {
return new ArrayList<TickManager>(managers.values());
}
public static TickThreading instance() {
return instance;
}
}
|
package org.navalplanner.web.resources.worker;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang.Validate;
import org.hibernate.validator.ClassValidator;
import org.hibernate.validator.InvalidValue;
import org.navalplanner.business.common.exceptions.InstanceNotFoundException;
import org.navalplanner.business.common.exceptions.ValidationException;
import org.navalplanner.business.resources.entities.Criterion;
import org.navalplanner.business.resources.entities.CriterionSatisfaction;
import org.navalplanner.business.resources.entities.CriterionWithItsType;
import org.navalplanner.business.resources.entities.ICriterionType;
import org.navalplanner.business.resources.entities.Interval;
import org.navalplanner.business.resources.entities.PredefinedCriterionTypes;
import org.navalplanner.business.resources.entities.Resource;
import org.navalplanner.business.resources.entities.Worker;
import org.navalplanner.business.resources.services.CriterionService;
import org.navalplanner.business.resources.services.ResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
@Component
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class WorkerModel implements IWorkerModel {
private final ResourceService resourceService;
private final ICriterionType<?>[] laboralRelatedTypes = {
PredefinedCriterionTypes.LEAVE,
PredefinedCriterionTypes.WORK_RELATIONSHIP };
private Worker worker;
private ClassValidator<Worker> workerValidator;
private final CriterionService criterionService;
private IMultipleCriterionActiveAssigner localizationsAssigner;
@Autowired
public WorkerModel(ResourceService resourceService,
CriterionService criterionService) {
Validate.notNull(resourceService);
Validate.notNull(criterionService);
this.resourceService = resourceService;
this.workerValidator = new ClassValidator<Worker>(Worker.class);
this.criterionService = criterionService;
}
@Override
@Transactional
public void save() throws ValidationException {
InvalidValue[] invalidValues = workerValidator
.getInvalidValues(getWorker());
if (invalidValues.length > 0) {
throw new ValidationException(invalidValues);
}
getLocalizationsAssigner().applyChanges();
resourceService.saveResource(worker);
worker = null;
localizationsAssigner = null;
}
@Override
@Transactional(readOnly = true)
public List<Worker> getWorkers() {
return resourceService.getWorkers();
}
@Override
public Worker getWorker() {
return worker;
}
@Override
@Transactional(readOnly = true)
public void prepareForCreate() {
worker = new Worker();
localizationsAssigner = new MultipleCriterionActiveAssigner(
criterionService, worker,
PredefinedCriterionTypes.LOCATION_GROUP);
}
@Override
@Transactional(readOnly = true)
public void prepareEditFor(Worker worker) {
Validate.notNull(worker, "worker must be not null");
try {
this.worker = (Worker) resourceService.findResource(worker.getId());
this.worker.forceLoadSatisfactions();
localizationsAssigner = new MultipleCriterionActiveAssigner(
criterionService, this.worker,
PredefinedCriterionTypes.LOCATION_GROUP);
} catch (InstanceNotFoundException e) {
throw new RuntimeException(e);
}
}
@Override
@Transactional(readOnly = true)
public AddingSatisfactionResult addSatisfaction(ICriterionType<?> type,
CriterionSatisfaction original, CriterionSatisfaction edited) {
/* Check worker's version. */
Worker worker = getWorker();
resourceService.checkVersion(worker);
/* Add criterion satisfaction. */
edited.setResource(worker);
boolean previouslyContained = false;
if (previouslyContained = worker.contains(original)) {
worker.removeCriterionSatisfaction(original);
}
boolean canAdd = false;
try {
canAdd = worker.canAddSatisfaction(type, edited);
} catch (IllegalArgumentException e) {
if (previouslyContained) {
worker.addSatisfaction(type, original);
}
return AddingSatisfactionResult.SATISFACTION_WRONG;
}
if (!canAdd) {
if (previouslyContained) {
worker.addSatisfaction(type, original);
}
return AddingSatisfactionResult.DONT_COMPLY_OVERLAPPING_RESTRICTIONS;
}
worker.addSatisfaction(type, edited);
return AddingSatisfactionResult.OK;
}
@Override
@Transactional(readOnly = true)
public void removeSatisfaction(CriterionSatisfaction satisfaction) {
/* Check worker's version. */
Worker worker = getWorker();
resourceService.checkVersion(worker);
/* Remove criterion satisfaction. */
worker.removeCriterionSatisfaction(satisfaction);
}
@Override
@Transactional(readOnly = true)
public void assignCriteria(Collection<? extends Criterion> criteria) {
/* Check worker's version. */
Worker worker = getWorker();
resourceService.checkVersion(worker);
/* Assign criteria. */
getLocalizationsAssigner().assign(criteria);
}
@Override
@Transactional(readOnly = true)
public void unassignSatisfactions(
Collection<? extends CriterionSatisfaction> satisfactions) {
/* Check worker's version. */
Worker worker = getWorker();
resourceService.checkVersion(worker);
/* Unassign criterion satisfactions. */
getLocalizationsAssigner().unassign(satisfactions);
}
private static class NullAssigner implements
IMultipleCriterionActiveAssigner {
private List<CriterionSatisfaction> empty = Arrays.asList();
private List<Criterion> emptyCriterions = Arrays.asList();
@Override
public void assign(Collection<? extends Criterion> criterions) {
}
@Override
public List<CriterionSatisfaction> getActiveSatisfactions() {
return empty;
}
@Override
public List<Criterion> getCriterionsNotAssigned() {
return emptyCriterions;
}
@Override
public List<CriterionSatisfaction> getHistoric() {
return empty;
}
@Override
public void unassign(
Collection<? extends CriterionSatisfaction> satisfactions) {
}
@Override
public void applyChanges() {
}
}
private static class MultipleCriterionActiveAssigner implements
IMultipleCriterionActiveAssigner {
private final Resource resource;
private final ICriterionType<?> type;
private final CriterionService criterionService;
private List<CriterionSatisfaction> history;
private List<Criterion> initialCriterionsNotAssigned;
private Set<CriterionSatisfaction> initialActive;
private Map<Criterion, CriterionSatisfaction> unassigned = new HashMap<Criterion, CriterionSatisfaction>();
private Set<CriterionSatisfaction> added = new HashSet<CriterionSatisfaction>();
public MultipleCriterionActiveAssigner(
CriterionService criterionService, Resource resource,
ICriterionType<?> type) {
Validate
.isTrue(
type.allowSimultaneousCriterionsPerResource(),
"must allow multiple active criterions for this type to use this assignment strategy");
this.criterionService = criterionService;
this.resource = resource;
this.type = type;
this.resource.forceLoadSatisfactions();
this.history = calculateInitialHistory();
this.initialCriterionsNotAssigned = calculateInitialCriterionsNotAssigned();
for (Criterion criterion : initialCriterionsNotAssigned) {
unassigned.put(criterion, createSatisfactionFor(criterion));
}
this.initialActive = calculateInitialActive();
}
public List<CriterionSatisfaction> getHistoric() {
return history;
}
private List<CriterionSatisfaction> calculateInitialHistory() {
Collection<CriterionSatisfaction> allSatisfactions = resource
.getSatisfactionsFor(type);
ArrayList<CriterionSatisfaction> result = new ArrayList<CriterionSatisfaction>();
for (CriterionSatisfaction criterionSatisfaction : allSatisfactions) {
if (criterionSatisfaction.isFinished()) {
result.add(criterionSatisfaction);
}
}
return result;
}
private HashSet<CriterionSatisfaction> calculateInitialActive() {
return new HashSet<CriterionSatisfaction>(resource
.getCurrentSatisfactionsFor(type));
}
private List<Criterion> calculateInitialCriterionsNotAssigned() {
Map<Long, Criterion> allCriterions = byId(criterionService
.getCriterionsFor(type));
for (Long activeId : asIds(resource.getCurrentCriterionsFor(type))) {
allCriterions.remove(activeId);
}
return new ArrayList<Criterion>(allCriterions.values());
}
public List<CriterionSatisfaction> getActiveSatisfactions() {
Set<CriterionSatisfaction> result = new HashSet<CriterionSatisfaction>(
added);
for (CriterionSatisfaction criterionSatisfaction : initialActive) {
if (!unassigned.containsKey(criterionSatisfaction
.getCriterion())) {
result.add(criterionSatisfaction);
}
}
return new ArrayList<CriterionSatisfaction>(result);
}
public List<Criterion> getCriterionsNotAssigned() {
return new ArrayList<Criterion>(unassigned.keySet());
}
public void unassign(
Collection<? extends CriterionSatisfaction> satisfactions) {
for (CriterionSatisfaction criterionSatisfaction : satisfactions) {
unassigned.put(criterionSatisfaction.getCriterion(),
criterionSatisfaction);
added.remove(criterionSatisfaction);
}
}
public void assign(Collection<? extends Criterion> criterions) {
for (Criterion criterion : criterions) {
CriterionSatisfaction removed = unassigned.remove(criterion);
if (!initialActive.contains(removed)) {
added.add(removed);
}
}
}
private CriterionSatisfaction createSatisfactionFor(Criterion criterion) {
return new CriterionSatisfaction(new Date(), criterion, resource);
}
@Override
public void applyChanges() {
for (CriterionSatisfaction criterionSatisfaction : added) {
resource.addSatisfaction(new CriterionWithItsType(type,
criterionSatisfaction.getCriterion()), Interval
.from(criterionSatisfaction.getStartDate()));
}
for (Criterion criterion : unassigned.keySet()) {
resource.finish(new CriterionWithItsType(type, criterion));
}
}
}
@Override
public IMultipleCriterionActiveAssigner getLocalizationsAssigner() {
return localizationsAssigner != null ? localizationsAssigner
: new NullAssigner();
}
private static List<Long> asIds(Collection<? extends Criterion> criterions) {
List<Long> result = new ArrayList<Long>();
for (Criterion criterion : criterions) {
result.add(criterion.getId());
}
return result;
}
private static Map<Long, Criterion> byId(
Collection<? extends Criterion> criterions) {
Map<Long, Criterion> result = new HashMap<Long, Criterion>();
for (Criterion criterion : criterions) {
result.put(criterion.getId(), criterion);
}
return result;
}
@Override
public boolean isCreating() {
return worker != null && worker.getId() == null;
}
@Override
@Transactional(readOnly = true)
public Map<ICriterionType<?>, Collection<Criterion>> getLaboralRelatedCriterions() {
Map<ICriterionType<?>, Collection<Criterion>> result = new HashMap<ICriterionType<?>, Collection<Criterion>>();
for (ICriterionType<?> type : laboralRelatedTypes) {
result.put(type, criterionService.getCriterionsFor(type));
}
return result;
}
@Override
public List<CriterionSatisfaction>
getLaboralRelatedCriterionSatisfactions() {
return worker.query().oneOf(laboralRelatedTypes).sortByStartDate()
.result();
}
}
|
package dyvil.tools.compiler.ast.expression;
import dyvil.collection.iterator.ArrayIterator;
import dyvil.reflect.Opcodes;
import dyvil.tools.compiler.ast.annotation.IAnnotation;
import dyvil.tools.compiler.ast.classes.IClass;
import dyvil.tools.compiler.ast.context.IContext;
import dyvil.tools.compiler.ast.generic.ITypeContext;
import dyvil.tools.compiler.ast.parameter.ArgumentList;
import dyvil.tools.compiler.ast.structure.IClassCompilableList;
import dyvil.tools.compiler.ast.structure.Package;
import dyvil.tools.compiler.ast.type.IType;
import dyvil.tools.compiler.ast.type.Mutability;
import dyvil.tools.compiler.ast.type.builtin.Types;
import dyvil.tools.compiler.ast.type.compound.ArrayType;
import dyvil.tools.compiler.backend.MethodWriter;
import dyvil.tools.compiler.backend.exception.BytecodeException;
import dyvil.tools.compiler.config.Formatting;
import dyvil.tools.compiler.transform.TypeChecker;
import dyvil.tools.compiler.util.Util;
import dyvil.tools.parsing.ast.IASTNode;
import dyvil.tools.parsing.marker.MarkerList;
import dyvil.tools.parsing.position.ICodePosition;
import java.util.Iterator;
public final class ArrayExpr implements IValue, IValueList
{
public static final class LazyFields
{
public static final IClass ARRAY_CONVERTIBLE = Package.dyvilLangLiteral.resolveClass("ArrayConvertible");
private static final TypeChecker.MarkerSupplier ELEMENT_MARKER_SUPPLIER = TypeChecker.markerSupplier(
"array.element.type.incompatible", "array.element.type.expected", "array.element.type.actual");
private LazyFields()
{
// no instances
}
}
protected ICodePosition position;
protected IValue[] values;
protected int valueCount;
// Metadata
protected IType arrayType;
protected IType elementType;
public ArrayExpr()
{
this.values = new IValue[4];
}
public ArrayExpr(IValue[] values, int valueCount)
{
this.values = values;
this.valueCount = valueCount;
}
public ArrayExpr(ICodePosition position)
{
this.position = position;
this.values = new IValue[3];
}
public ArrayExpr(ICodePosition position, int capacity)
{
this.position = position;
this.values = new IValue[capacity];
}
public ArrayExpr(ICodePosition position, IValue[] values, int valueCount)
{
this.position = position;
this.values = values;
this.valueCount = valueCount;
}
@Override
public ICodePosition getPosition()
{
return this.position;
}
@Override
public void setPosition(ICodePosition position)
{
this.position = position;
}
@Override
public int valueTag()
{
return ARRAY;
}
@Override
public boolean isAnnotationConstant()
{
for (int i = 0; i < this.valueCount; i++)
{
if (!this.values[i].isAnnotationConstant())
{
return false;
}
}
return true;
}
@Override
public boolean isPrimitive()
{
return false;
}
public IType getElementType()
{
if (this.elementType != null)
{
return this.elementType;
}
return this.elementType = getCommonType(this.values, this.valueCount);
}
public static IType getCommonType(IValue[] values, int valueCount)
{
if (valueCount == 0)
{
return Types.ANY;
}
IType type = values[0].getType();
for (int i = 1; i < valueCount; i++)
{
final IType valueType = values[i].getType();
type = Types.combine(type, valueType);
if (type == null)
{
return Types.ANY;
}
}
return type;
}
@Override
public boolean isResolved()
{
if (this.arrayType != null)
{
return this.arrayType.isResolved();
}
return this.elementType != null && this.elementType.isResolved();
}
@Override
public IType getType()
{
if (this.arrayType != null)
{
return this.arrayType;
}
return this.arrayType = new ArrayType(this.getElementType(), Mutability.IMMUTABLE);
}
@Override
public void setType(IType type)
{
this.arrayType = type;
this.elementType = type.getElementType();
}
@Override
public IValue toAnnotationConstant(MarkerList markers, IContext context, int depth)
{
for (int i = 0; i < this.valueCount; i++)
{
final IValue value = this.values[i];
final IValue constant = value.toAnnotationConstant(markers, context, depth);
if (constant == null)
{
return null;
}
else
{
this.values[i] = constant;
}
}
return this;
}
@Override
public IValue withType(IType arrayType, ITypeContext typeContext, MarkerList markers, IContext context)
{
IType elementType;
if (!arrayType.isArrayType())
{
final IAnnotation annotation;
if ((annotation = arrayType.getAnnotation(LazyFields.ARRAY_CONVERTIBLE)) != null)
{
return new LiteralConversion(this, annotation, new ArgumentList(this.values, this.valueCount))
.withType(arrayType, typeContext, markers, context);
}
if (arrayType.getTheClass() != Types.OBJECT_CLASS)
{
return null;
}
elementType = this.getType().getElementType();
}
else
{
// If the type is an array type, get it's element type
this.elementType = elementType = arrayType.getElementType();
this.arrayType = arrayType;
}
for (int i = 0; i < this.valueCount; i++)
{
this.values[i] = TypeChecker.convertValue(this.values[i], elementType, typeContext, markers, context,
LazyFields.ELEMENT_MARKER_SUPPLIER);
}
return this;
}
private boolean isConvertibleFrom(IType type)
{
return type.getTheClass() == Types.OBJECT_CLASS || type.getAnnotation(LazyFields.ARRAY_CONVERTIBLE) != null;
}
@Override
public boolean isType(IType type)
{
if (!type.isArrayType())
{
return this.isConvertibleFrom(type);
}
// Skip getting the element type if this is an empty array
if (this.valueCount == 0)
{
return true;
}
// If the type is an array type, get it's element type
final IType elementType = type.getElementType();
// Check for every value if it is the element type
for (int i = 0; i < this.valueCount; i++)
{
if (!this.values[i].isType(elementType))
{
// If not, this is not the type
return false;
}
}
return true;
}
@Override
public int getTypeMatch(IType type)
{
if (!type.isArrayType())
{
// isConvertibleFrom also returns true for Object, but the
// CONVERSION_MATCH return value here is intentional.
return this.isConvertibleFrom(type) ? CONVERSION_MATCH : 0;
}
// Skip getting the element type if this is an empty array
if (this.valueCount == 0)
{
return 1;
}
// If the type is an array type, get it's element type
final IType elementType = type.getElementType();
int total = 0;
// Get the type match for every value in the array
for (int i = 0; i < this.valueCount; i++)
{
final int match = this.values[i].getTypeMatch(elementType);
if (match <= 0)
{
// If the type match for one value is zero, return 0
return 0;
}
total += match;
}
// Divide by the count
return 1 + total / this.valueCount;
}
@Override
public Iterator<IValue> iterator()
{
return new ArrayIterator<>(this.values, this.valueCount);
}
@Override
public int valueCount()
{
return this.valueCount;
}
@Override
public boolean isEmpty()
{
return this.valueCount == 0;
}
@Override
public void setValue(int index, IValue value)
{
this.values[index] = value;
}
@Override
public void addValue(IValue value)
{
int index = this.valueCount++;
if (index >= this.values.length)
{
IValue[] temp = new IValue[this.valueCount];
System.arraycopy(this.values, 0, temp, 0, index);
this.values = temp;
}
this.values[index] = value;
}
@Override
public void addValue(int index, IValue value)
{
IValue[] temp = new IValue[++this.valueCount];
System.arraycopy(this.values, 0, temp, 0, index);
temp[index] = value;
System.arraycopy(this.values, index, temp, index + 1, this.valueCount - index - 1);
this.values = temp;
}
@Override
public IValue getValue(int index)
{
return this.values[index];
}
@Override
public void resolveTypes(MarkerList markers, IContext context)
{
for (int i = 0; i < this.valueCount; i++)
{
this.values[i].resolveTypes(markers, context);
}
}
@Override
public IValue resolve(MarkerList markers, IContext context)
{
for (int i = 0; i < this.valueCount; i++)
{
this.values[i] = this.values[i].resolve(markers, context);
}
return this;
}
@Override
public void checkTypes(MarkerList markers, IContext context)
{
for (int i = 0; i < this.valueCount; i++)
{
this.values[i].checkTypes(markers, context);
}
}
@Override
public void check(MarkerList markers, IContext context)
{
for (int i = 0; i < this.valueCount; i++)
{
this.values[i].check(markers, context);
}
}
@Override
public IValue foldConstants()
{
for (int i = 0; i < this.valueCount; i++)
{
this.values[i] = this.values[i].foldConstants();
}
return this;
}
@Override
public IValue cleanup(IContext context, IClassCompilableList compilableList)
{
for (int i = 0; i < this.valueCount; i++)
{
this.values[i] = this.values[i].cleanup(context, compilableList);
}
return this;
}
@Override
public void writeExpression(MethodWriter writer, IType type) throws BytecodeException
{
final IType elementType = this.getElementType();
final int arrayStoreOpcode = elementType.getArrayStoreOpcode();
writer.visitLdcInsn(this.valueCount);
writer.visitMultiANewArrayInsn(this.getType(), 1);
for (int i = 0; i < this.valueCount; i++)
{
writer.visitInsn(Opcodes.DUP);
writer.visitLdcInsn(i);
this.values[i].writeExpression(writer, elementType);
writer.visitInsn(arrayStoreOpcode);
}
}
@Override
public String toString()
{
return IASTNode.toString(this);
}
@Override
public void toString(String prefix, StringBuilder buffer)
{
if (this.valueCount == 0)
{
if (Formatting.getBoolean("array.empty.space_between"))
{
buffer.append("[ ]");
}
else
{
buffer.append("[]");
}
return;
}
buffer.append('[');
if (Formatting.getBoolean("array.open_bracket.space_after"))
{
buffer.append(' ');
}
Util.astToString(prefix, this.values, this.valueCount, Formatting.getSeparator("array.separator", ','), buffer);
if (Formatting.getBoolean("array.close_bracket.space_before"))
{
buffer.append(' ');
}
buffer.append(']');
}
}
|
package org.umlg.sqlg.util;
import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.collect.LinkedListMultimap;
import com.google.common.collect.Multimap;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.tinkerpop.gremlin.process.traversal.Contains;
import org.apache.tinkerpop.gremlin.process.traversal.step.util.HasContainer;
import org.apache.tinkerpop.gremlin.structure.T;
import org.umlg.sqlg.sql.dialect.SqlDialect;
import org.umlg.sqlg.sql.parse.SchemaTableTree;
import org.umlg.sqlg.sql.parse.WhereClause;
import org.umlg.sqlg.strategy.Emit;
import org.umlg.sqlg.strategy.TopologyStrategy;
import org.umlg.sqlg.structure.*;
import java.lang.reflect.Array;
import java.sql.*;
import java.sql.Date;
import java.time.*;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.BiPredicate;
import java.util.stream.Collectors;
import static org.apache.tinkerpop.gremlin.structure.T.label;
public class SqlgUtil {
//This is the default count to indicate whether to use in statement or join onto a temp table.
//As it happens postgres join to temp is always faster except for count = 1 when in is not used but '='
private final static int BULK_WITHIN_COUNT = 1;
public static final String PROPERTY_ARRAY_VALUE_ELEMENTS_MAY_NOT_BE_NULL = "Property array value elements may not be null.";
private SqlgUtil() {
}
/**
* @param sqlgGraph
* @param resultSetMetaData
* @param resultSet
* @param rootSchemaTableTree
* @param subQueryStacks
* @param first
* @param lastElementIdCountMap
* @return A list of @{@link Emit}s that represent a single @{@link org.apache.tinkerpop.gremlin.process.traversal.Path}
* @throws SQLException
*/
public static List<Emit<SqlgElement>> loadResultSetIntoResultIterator(
SqlgGraph sqlgGraph,
ResultSetMetaData resultSetMetaData,
ResultSet resultSet,
SchemaTableTree rootSchemaTableTree,
List<LinkedList<SchemaTableTree>> subQueryStacks,
boolean first,
Map<String, Integer> lastElementIdCountMap
) throws SQLException {
List<Emit<SqlgElement>> result = new ArrayList<>();
if (resultSet.next()) {
if (first) {
for (LinkedList<SchemaTableTree> subQueryStack : subQueryStacks) {
for (SchemaTableTree schemaTableTree : subQueryStack) {
schemaTableTree.clearColumnNamePropertNameMap();
}
}
populateIdCountMap(resultSetMetaData, rootSchemaTableTree, lastElementIdCountMap);
}
int subQueryDepth = 0;
for (LinkedList<SchemaTableTree> subQueryStack : subQueryStacks) {
List<Emit<SqlgElement>> labeledElements = SqlgUtil.loadLabeledElements(
sqlgGraph, resultSet, subQueryStack, lastElementIdCountMap
);
result.addAll(labeledElements);
if (subQueryDepth == subQueryStacks.size() - 1) {
SchemaTableTree lastSchemaTableTree = subQueryStack.getLast();
if (labeledElements.isEmpty()) {
SqlgElement e = SqlgUtil.loadElement(
sqlgGraph, lastElementIdCountMap, resultSet, lastSchemaTableTree
);
Emit<SqlgElement> emit = new Emit<>(e, Collections.emptySet());
if (lastSchemaTableTree.isLocalStep() && lastSchemaTableTree.isOptionalLeftJoin()) {
emit.setIncomingOnlyLocalOptionalStep(true);
}
result.add(emit);
}
if (lastSchemaTableTree.getReplacedStepDepth() == lastSchemaTableTree.getStepDepth() &&
lastSchemaTableTree.isEmit() &&
lastSchemaTableTree.isUntilFirst()) {
Emit<SqlgElement> repeatEmit = labeledElements.get(labeledElements.size() - 1);
repeatEmit.setRepeat(true);
}
}
subQueryDepth++;
}
}
return result;
}
private static void populateIdCountMap(ResultSetMetaData resultSetMetaData, SchemaTableTree rootSchemaTableTree, Map<String, Integer> lastElementIdCountMap) throws SQLException {
lastElementIdCountMap.clear();
//First load all labeled entries from the resultSet
//Translate the columns back from alias to meaningful column headings
for (int columnCount = 1; columnCount <= resultSetMetaData.getColumnCount(); columnCount++) {
String columnLabel = resultSetMetaData.getColumnLabel(columnCount);
String unAliased = rootSchemaTableTree.getThreadLocalAliasColumnNameMap().get(columnLabel);
String mapKey = unAliased != null ? unAliased : columnLabel;
if (mapKey.endsWith(SchemaTableTree.ALIAS_SEPARATOR + SchemaManager.ID)) {
lastElementIdCountMap.put(mapKey, columnCount);
}
}
}
/**
* Loads all labeled or emitted elements.
*
* @param sqlgGraph
* @param resultSet
* @param subQueryStack
* @return
* @throws SQLException
*/
private static <E extends SqlgElement> List<Emit<E>> loadLabeledElements(
SqlgGraph sqlgGraph,
final ResultSet resultSet,
LinkedList<SchemaTableTree> subQueryStack,
Map<String, Integer> lastElementIdCountMap) throws SQLException {
List<Emit<E>> result = new ArrayList<>();
for (SchemaTableTree schemaTableTree : subQueryStack) {
if (!schemaTableTree.getLabels().isEmpty()) {
String idProperty = schemaTableTree.labeledAliasId();
Integer columnCount = lastElementIdCountMap.get(idProperty);
Long id = resultSet.getLong(columnCount);
if (!resultSet.wasNull()) {
SqlgElement sqlgElement;
if (schemaTableTree.getSchemaTable().isVertexTable()) {
String rawLabel = schemaTableTree.getSchemaTable().getTable().substring(SchemaManager.VERTEX_PREFIX.length());
sqlgElement = SqlgVertex.of(sqlgGraph, id, schemaTableTree.getSchemaTable().getSchema(), rawLabel);
} else {
String rawLabel = schemaTableTree.getSchemaTable().getTable().substring(SchemaManager.EDGE_PREFIX.length());
sqlgElement = new SqlgEdge(sqlgGraph, id, schemaTableTree.getSchemaTable().getSchema(), rawLabel);
}
schemaTableTree.loadProperty(resultSet, sqlgElement);
result.add(new Emit<>((E) sqlgElement, schemaTableTree.getRealLabels()));
}
}
}
return result;
}
private static <E> E loadElement(
SqlgGraph sqlgGraph,
Map<String, Integer> columnMap,
ResultSet resultSet,
SchemaTableTree leafSchemaTableTree) throws SQLException {
SchemaTable schemaTable = leafSchemaTableTree.getSchemaTable();
String idProperty = leafSchemaTableTree.idProperty();
Integer columnCount = columnMap.get(idProperty);
Long id = resultSet.getLong(columnCount);
SqlgElement sqlgElement;
if (schemaTable.isVertexTable()) {
String rawLabel = schemaTable.getTable().substring(SchemaManager.VERTEX_PREFIX.length());
sqlgElement = SqlgVertex.of(sqlgGraph, id, schemaTable.getSchema(), rawLabel);
} else {
String rawLabel = schemaTable.getTable().substring(SchemaManager.EDGE_PREFIX.length());
sqlgElement = new SqlgEdge(sqlgGraph, id, schemaTable.getSchema(), rawLabel);
}
leafSchemaTableTree.loadProperty(resultSet, sqlgElement);
return (E) sqlgElement;
}
public static boolean isBulkWithinAndOut(SqlgGraph sqlgGraph, HasContainer hasContainer) {
BiPredicate p = hasContainer.getPredicate().getBiPredicate();
return (p == Contains.within || p == Contains.without) && ((Collection) hasContainer.getPredicate().getValue()).size() > sqlgGraph.configuration().getInt("bulk.within.count", BULK_WITHIN_COUNT);
}
public static boolean isBulkWithin(SqlgGraph sqlgGraph, HasContainer hasContainer) {
BiPredicate p = hasContainer.getPredicate().getBiPredicate();
return p == Contains.within && ((Collection) hasContainer.getPredicate().getValue()).size() > sqlgGraph.configuration().getInt("bulk.within.count", BULK_WITHIN_COUNT);
}
public static void setParametersOnStatement(SqlgGraph sqlgGraph, LinkedList<SchemaTableTree> schemaTableTreeStack, Connection conn, PreparedStatement preparedStatement, int parameterIndex) throws SQLException {
Multimap<String, Object> keyValueMap = LinkedListMultimap.create();
for (SchemaTableTree schemaTableTree : schemaTableTreeStack) {
for (HasContainer hasContainer : schemaTableTree.getHasContainers()) {
if (!sqlgGraph.getSqlDialect().supportsBulkWithinOut() || !isBulkWithinAndOut(sqlgGraph, hasContainer)) {
WhereClause whereClause = WhereClause.from(hasContainer.getPredicate());
whereClause.putKeyValueMap(hasContainer, keyValueMap);
}
}
}
List<ImmutablePair<PropertyType, Object>> typeAndValues = SqlgUtil.transformToTypeAndValue(keyValueMap);
//This is for selects
setKeyValuesAsParameter(sqlgGraph, false, parameterIndex, conn, preparedStatement, typeAndValues);
}
//This is called for inserts
public static int setKeyValuesAsParameter(SqlgGraph sqlgGraph, int i, Connection conn, PreparedStatement preparedStatement, Map<String, Object> keyValues) throws SQLException {
List<ImmutablePair<PropertyType, Object>> typeAndValues = SqlgUtil.transformToTypeAndValue(keyValues);
i = setKeyValuesAsParameter(sqlgGraph, true, i, conn, preparedStatement, typeAndValues);
return i;
}
public static int setKeyValuesAsParameter(SqlgGraph sqlgGraph, boolean mod, int parameterStartIndex, Connection conn, PreparedStatement preparedStatement, List<ImmutablePair<PropertyType, Object>> typeAndValues) throws SQLException {
for (ImmutablePair<PropertyType, Object> pair : typeAndValues) {
switch (pair.left) {
case BOOLEAN:
preparedStatement.setBoolean(parameterStartIndex++, (Boolean) pair.right);
break;
case BYTE:
preparedStatement.setByte(parameterStartIndex++, (Byte) pair.right);
break;
case SHORT:
preparedStatement.setShort(parameterStartIndex++, (Short) pair.right);
break;
case INTEGER:
preparedStatement.setInt(parameterStartIndex++, (Integer) pair.right);
break;
case LONG:
preparedStatement.setLong(parameterStartIndex++, (Long) pair.right);
break;
case FLOAT:
preparedStatement.setFloat(parameterStartIndex++, (Float) pair.right);
break;
case DOUBLE:
preparedStatement.setDouble(parameterStartIndex++, (Double) pair.right);
break;
case STRING:
preparedStatement.setString(parameterStartIndex++, (String) pair.right);
break;
case LOCALDATE:
preparedStatement.setTimestamp(parameterStartIndex++, Timestamp.valueOf(((LocalDate) pair.right).atStartOfDay()));
break;
case LOCALDATETIME:
preparedStatement.setTimestamp(parameterStartIndex++, Timestamp.valueOf(((LocalDateTime) pair.right)));
break;
case ZONEDDATETIME:
if (sqlgGraph.getSqlDialect().needsTimeZone()) {
//This is for postgresql that adjust the timestamp to the server's timezone
preparedStatement.setTimestamp(
parameterStartIndex++,
Timestamp.valueOf(((ZonedDateTime) pair.right).toLocalDateTime()),
Calendar.getInstance(TimeZone.getTimeZone(((ZonedDateTime) pair.right).getZone().getId()))
);
} else {
preparedStatement.setTimestamp(
parameterStartIndex++,
Timestamp.valueOf(((ZonedDateTime) pair.right).toLocalDateTime())
);
}
if (mod)
preparedStatement.setString(parameterStartIndex++, ((ZonedDateTime) pair.right).getZone().getId());
break;
case LOCALTIME:
//looses nano seconds
preparedStatement.setTime(parameterStartIndex++, Time.valueOf((LocalTime) pair.right));
break;
case PERIOD:
preparedStatement.setInt(parameterStartIndex++, ((Period) pair.right).getYears());
preparedStatement.setInt(parameterStartIndex++, ((Period) pair.right).getMonths());
preparedStatement.setInt(parameterStartIndex++, ((Period) pair.right).getDays());
break;
case DURATION:
preparedStatement.setLong(parameterStartIndex++, ((Duration) pair.right).getSeconds());
preparedStatement.setInt(parameterStartIndex++, ((Duration) pair.right).getNano());
break;
case JSON:
sqlgGraph.getSqlDialect().setJson(preparedStatement, parameterStartIndex, (JsonNode) pair.getRight());
parameterStartIndex++;
break;
case POINT:
sqlgGraph.getSqlDialect().setPoint(preparedStatement, parameterStartIndex, pair.getRight());
parameterStartIndex++;
break;
case LINESTRING:
sqlgGraph.getSqlDialect().setLineString(preparedStatement, parameterStartIndex, pair.getRight());
parameterStartIndex++;
break;
case POLYGON:
sqlgGraph.getSqlDialect().setPolygon(preparedStatement, parameterStartIndex, pair.getRight());
parameterStartIndex++;
break;
case GEOGRAPHY_POINT:
sqlgGraph.getSqlDialect().setPoint(preparedStatement, parameterStartIndex, pair.getRight());
parameterStartIndex++;
break;
case GEOGRAPHY_POLYGON:
sqlgGraph.getSqlDialect().setPolygon(preparedStatement, parameterStartIndex, pair.getRight());
parameterStartIndex++;
break;
case BOOLEAN_ARRAY:
java.sql.Array booleanArray = conn.createArrayOf(sqlgGraph.getSqlDialect().getArrayDriverType(PropertyType.BOOLEAN_ARRAY), SqlgUtil.transformArrayToInsertValue(pair.left, pair.right));
preparedStatement.setArray(parameterStartIndex++, booleanArray);
break;
case boolean_ARRAY:
booleanArray = conn.createArrayOf(sqlgGraph.getSqlDialect().getArrayDriverType(PropertyType.boolean_ARRAY), SqlgUtil.transformArrayToInsertValue(pair.left, pair.right));
preparedStatement.setArray(parameterStartIndex++, booleanArray);
break;
case BYTE_ARRAY:
byte[] byteArray = SqlgUtil.convertObjectArrayToBytePrimitiveArray((Object[]) pair.getRight());
preparedStatement.setBytes(parameterStartIndex++, byteArray);
break;
case byte_ARRAY:
preparedStatement.setBytes(parameterStartIndex++, (byte[]) pair.right);
break;
case SHORT_ARRAY:
java.sql.Array shortArray = conn.createArrayOf(sqlgGraph.getSqlDialect().getArrayDriverType(PropertyType.SHORT_ARRAY), SqlgUtil.transformArrayToInsertValue(pair.left, pair.right));
preparedStatement.setArray(parameterStartIndex++, shortArray);
break;
case short_ARRAY:
shortArray = conn.createArrayOf(sqlgGraph.getSqlDialect().getArrayDriverType(PropertyType.short_ARRAY), SqlgUtil.transformArrayToInsertValue(pair.left, pair.right));
preparedStatement.setArray(parameterStartIndex++, shortArray);
break;
case INTEGER_ARRAY:
java.sql.Array intArray = conn.createArrayOf(sqlgGraph.getSqlDialect().getArrayDriverType(PropertyType.INTEGER_ARRAY), SqlgUtil.transformArrayToInsertValue(pair.left, pair.right));
preparedStatement.setArray(parameterStartIndex++, intArray);
break;
case int_ARRAY:
intArray = conn.createArrayOf(sqlgGraph.getSqlDialect().getArrayDriverType(PropertyType.int_ARRAY), SqlgUtil.transformArrayToInsertValue(pair.left, pair.right));
preparedStatement.setArray(parameterStartIndex++, intArray);
break;
case LONG_ARRAY:
java.sql.Array longArray = conn.createArrayOf(sqlgGraph.getSqlDialect().getArrayDriverType(PropertyType.LONG_ARRAY), SqlgUtil.transformArrayToInsertValue(pair.left, pair.right));
preparedStatement.setArray(parameterStartIndex++, longArray);
break;
case long_ARRAY:
longArray = conn.createArrayOf(sqlgGraph.getSqlDialect().getArrayDriverType(PropertyType.long_ARRAY), SqlgUtil.transformArrayToInsertValue(pair.left, pair.right));
preparedStatement.setArray(parameterStartIndex++, longArray);
break;
case FLOAT_ARRAY:
java.sql.Array floatArray = conn.createArrayOf(sqlgGraph.getSqlDialect().getArrayDriverType(PropertyType.FLOAT_ARRAY), SqlgUtil.transformArrayToInsertValue(pair.left, pair.right));
preparedStatement.setArray(parameterStartIndex++, floatArray);
break;
case float_ARRAY:
floatArray = conn.createArrayOf(sqlgGraph.getSqlDialect().getArrayDriverType(PropertyType.float_ARRAY), SqlgUtil.transformArrayToInsertValue(pair.left, pair.right));
preparedStatement.setArray(parameterStartIndex++, floatArray);
break;
case DOUBLE_ARRAY:
java.sql.Array doubleArray = conn.createArrayOf(sqlgGraph.getSqlDialect().getArrayDriverType(PropertyType.DOUBLE_ARRAY), SqlgUtil.transformArrayToInsertValue(pair.left, pair.right));
preparedStatement.setArray(parameterStartIndex++, doubleArray);
break;
case double_ARRAY:
doubleArray = conn.createArrayOf(sqlgGraph.getSqlDialect().getArrayDriverType(PropertyType.double_ARRAY), SqlgUtil.transformArrayToInsertValue(pair.left, pair.right));
preparedStatement.setArray(parameterStartIndex++, doubleArray);
break;
case STRING_ARRAY:
java.sql.Array stringArray = conn.createArrayOf(sqlgGraph.getSqlDialect().getArrayDriverType(PropertyType.STRING_ARRAY), SqlgUtil.transformArrayToInsertValue(pair.left, pair.right));
preparedStatement.setArray(parameterStartIndex++, stringArray);
break;
case LOCALDATETIME_ARRAY:
java.sql.Array localDateTimeArray = sqlgGraph.getSqlDialect().createArrayOf(conn, PropertyType.LOCALDATETIME_ARRAY, SqlgUtil.transformArrayToInsertValue(pair.left, pair.right));
preparedStatement.setArray(parameterStartIndex++, localDateTimeArray);
break;
case LOCALDATE_ARRAY:
java.sql.Array localDateArray = sqlgGraph.getSqlDialect().createArrayOf(conn, PropertyType.LOCALDATE_ARRAY, SqlgUtil.transformArrayToInsertValue(pair.left, pair.right));
preparedStatement.setArray(parameterStartIndex++, localDateArray);
break;
case LOCALTIME_ARRAY:
java.sql.Array localTimeArray = sqlgGraph.getSqlDialect().createArrayOf(conn, PropertyType.LOCALTIME_ARRAY, SqlgUtil.transformArrayToInsertValue(pair.left, pair.right));
preparedStatement.setArray(parameterStartIndex++, localTimeArray);
break;
case ZONEDDATETIME_ARRAY:
java.sql.Array zonedDateTimeArray = sqlgGraph.getSqlDialect().createArrayOf(conn, PropertyType.ZONEDDATETIME_ARRAY, SqlgUtil.transformArrayToInsertValue(pair.left, pair.right));
preparedStatement.setArray(parameterStartIndex++, zonedDateTimeArray);
if (mod) {
List<String> zones = (Arrays.asList((ZonedDateTime[]) pair.right)).stream().map(z -> z.getZone().getId()).collect(Collectors.toList());
java.sql.Array zonedArray = sqlgGraph.getSqlDialect().createArrayOf(conn, PropertyType.STRING_ARRAY, SqlgUtil.transformArrayToInsertValue(PropertyType.STRING_ARRAY, zones.toArray()));
preparedStatement.setArray(parameterStartIndex++, zonedArray);
}
break;
case DURATION_ARRAY:
Duration[] durations = (Duration[]) pair.getRight();
List<Long> seconds = Arrays.stream(durations).map(d -> d.getSeconds()).collect(Collectors.toList());
List<Integer> nanos = Arrays.stream(durations).map(d -> d.getNano()).collect(Collectors.toList());
java.sql.Array secondsArray = sqlgGraph.getSqlDialect().createArrayOf(conn, PropertyType.long_ARRAY, SqlgUtil.transformArrayToInsertValue(pair.left, seconds.toArray()));
preparedStatement.setArray(parameterStartIndex++, secondsArray);
java.sql.Array nanoArray = sqlgGraph.getSqlDialect().createArrayOf(conn, PropertyType.int_ARRAY, SqlgUtil.transformArrayToInsertValue(pair.left, nanos.toArray()));
preparedStatement.setArray(parameterStartIndex++, nanoArray);
break;
case PERIOD_ARRAY:
Period[] periods = (Period[]) pair.getRight();
List<Integer> years = Arrays.stream(periods).map(d -> d.getYears()).collect(Collectors.toList());
List<Integer> months = Arrays.stream(periods).map(d -> d.getMonths()).collect(Collectors.toList());
List<Integer> days = Arrays.stream(periods).map(d -> d.getDays()).collect(Collectors.toList());
java.sql.Array yearsArray = sqlgGraph.getSqlDialect().createArrayOf(conn, PropertyType.int_ARRAY, SqlgUtil.transformArrayToInsertValue(pair.left, years.toArray()));
preparedStatement.setArray(parameterStartIndex++, yearsArray);
java.sql.Array monthsArray = sqlgGraph.getSqlDialect().createArrayOf(conn, PropertyType.int_ARRAY, SqlgUtil.transformArrayToInsertValue(pair.left, months.toArray()));
preparedStatement.setArray(parameterStartIndex++, monthsArray);
java.sql.Array daysArray = sqlgGraph.getSqlDialect().createArrayOf(conn, PropertyType.int_ARRAY, SqlgUtil.transformArrayToInsertValue(pair.left, days.toArray()));
preparedStatement.setArray(parameterStartIndex++, daysArray);
break;
case JSON_ARRAY:
JsonNode[] objectNodes = (JsonNode[]) pair.getRight();
java.sql.Array objectNodeArray = sqlgGraph.getSqlDialect().createArrayOf(conn, PropertyType.JSON_ARRAY, SqlgUtil.transformArrayToInsertValue(pair.left, objectNodes));
preparedStatement.setArray(parameterStartIndex++, objectNodeArray);
break;
default:
throw new IllegalStateException("Unhandled type " + pair.left.name());
}
}
return parameterStartIndex;
}
public static SchemaTable parseLabel(final String label) {
Objects.requireNonNull(label, "label may not be null!");
String[] schemaLabel = label.split("\\.");
if (schemaLabel.length != 2) {
throw new IllegalStateException(String.format("label must be if the format 'schema.table', %s", new Object[]{label}));
}
return SchemaTable.of(schemaLabel[0], schemaLabel[1]);
}
public static SchemaTable parseLabelMaybeNoSchema(SqlgGraph sqlgGraph, final String label) {
Objects.requireNonNull(label, "label may not be null!");
String[] schemaLabel = label.split("\\.");
if (schemaLabel.length == 2) {
return SchemaTable.of(schemaLabel[0], schemaLabel[1]);
} else if (schemaLabel.length == 1) {
return SchemaTable.of(sqlgGraph.getSqlDialect().getPublicSchema(), schemaLabel[0]);
} else {
throw new IllegalStateException("label must be if the format 'schema.table' or just 'table'");
}
}
public static Object[] mapTokeyValues(Map<Object, Object> keyValues) {
Object[] result = new Object[keyValues.size() * 2];
int i = 0;
for (Map.Entry<Object, Object> entry : keyValues.entrySet()) {
result[i++] = entry.getKey();
result[i++] = entry.getValue();
}
return result;
}
public static Object[] mapToStringKeyValues(Map<String, Object> keyValues) {
Object[] result = new Object[keyValues.size() * 2];
int i = 0;
for (Map.Entry<String, Object> entry : keyValues.entrySet()) {
result[i++] = entry.getKey();
result[i++] = entry.getValue();
}
return result;
}
public static ConcurrentHashMap<String, PropertyType> transformToColumnDefinitionMap(Object... keyValues) {
//This is to ensure the keys are unique
Set<String> keys = new HashSet<>();
ConcurrentHashMap<String, PropertyType> result = new ConcurrentHashMap<>();
int i = 1;
Object key = null;
for (Object keyValue : keyValues) {
if (i++ % 2 != 0) {
//key
key = keyValue;
} else {
//value
//key
//skip the label as that is not a property but the table
if (key.equals(label) || keys.contains(key)) {
continue;
}
keys.add((String) key);
result.put((String) key, PropertyType.from(keyValue));
}
}
return result;
}
public static Map<String, Object> transformToInsertValues(Object... keyValues) {
Map<String, Object> result = new LinkedHashMap<>();
int i = 1;
Object key = null;
for (Object keyValue : keyValues) {
if (i++ % 2 != 0) {
//key
key = keyValue;
} else {
//value
//skip the label as that is not a property but the table
if (key.equals(label) || key.equals(T.id)) {
continue;
}
result.put((String) key, keyValue);
}
}
return result;
}
public static List<ImmutablePair<PropertyType, Object>> transformToTypeAndValue(Multimap<String, Object> keyValues) {
List<ImmutablePair<PropertyType, Object>> result = new ArrayList<>();
for (Map.Entry<String, Object> entry : keyValues.entries()) {
Object value = entry.getValue();
String key = entry.getKey();
//value
//skip the label as that is not a property but the table
if (key.equals(label.getAccessor())) {
continue;
}
if (key.equals(T.id.getAccessor())) {
RecordId id;
if (!(value instanceof RecordId)) {
id = RecordId.from(value);
} else {
id = (RecordId) value;
}
result.add(ImmutablePair.of(PropertyType.LONG, id.getId()));
} else {
result.add(ImmutablePair.of(PropertyType.from(value), value));
}
}
return result;
}
public static List<ImmutablePair<PropertyType, Object>> transformToTypeAndValue(Map<String, Object> keyValues) {
List<ImmutablePair<PropertyType, Object>> result = new ArrayList<>();
for (Map.Entry<String, Object> entry : keyValues.entrySet()) {
Object value = entry.getValue();
//value
//skip the label as that is not a property but the table
if (entry.getKey().equals(label)) {
continue;
}
result.add(ImmutablePair.of(PropertyType.from(value), value));
}
return result;
}
/**
* This only gets called for array properties
*
* @param propertyType
* @param value
* @return
*/
public static Object[] transformArrayToInsertValue(PropertyType propertyType, Object value) {
return getArray(propertyType, value);
}
private static Object[] getArray(PropertyType propertyType, Object val) {
int arrlength = Array.getLength(val);
Object[] outputArray = new Object[arrlength];
for (int i = 0; i < arrlength; ++i) {
switch (propertyType) {
case LOCALDATETIME_ARRAY:
outputArray[i] = Timestamp.valueOf((LocalDateTime) Array.get(val, i));
break;
case LOCALDATE_ARRAY:
outputArray[i] = Timestamp.valueOf(((LocalDate) Array.get(val, i)).atStartOfDay());
break;
case LOCALTIME_ARRAY:
outputArray[i] = Time.valueOf(((LocalTime) Array.get(val, i)));
break;
case ZONEDDATETIME_ARRAY:
ZonedDateTime zonedDateTime = (ZonedDateTime) Array.get(val, i);
outputArray[i] = Timestamp.valueOf(zonedDateTime.toLocalDateTime());
break;
case BYTE_ARRAY:
Byte aByte = (Byte) Array.get(val, i);
outputArray[i] = aByte.byteValue();
break;
default:
outputArray[i] = Array.get(val, i);
}
}
return outputArray;
}
public static String removeTrailingInId(String foreignKey) {
if (foreignKey.endsWith(SchemaManager.IN_VERTEX_COLUMN_END)) {
return foreignKey.substring(0, foreignKey.length() - SchemaManager.IN_VERTEX_COLUMN_END.length());
} else {
return foreignKey;
}
}
public static String removeTrailingOutId(String foreignKey) {
if (foreignKey.endsWith(SchemaManager.OUT_VERTEX_COLUMN_END)) {
return foreignKey.substring(0, foreignKey.length() - SchemaManager.OUT_VERTEX_COLUMN_END.length());
} else {
return foreignKey;
}
}
public static Map<String, Map<String, PropertyType>> filterHasContainers(SchemaManager schemaManager, List<HasContainer> hasContainers) {
HasContainer fromHasContainer = null;
HasContainer withoutHasContainer = null;
for (HasContainer hasContainer : hasContainers) {
if (hasContainer.getKey().equals(TopologyStrategy.TOPOLOGY_SELECTION_FROM)) {
fromHasContainer = hasContainer;
break;
} else if (hasContainer.getKey().equals(TopologyStrategy.TOPOLOGY_SELECTION_WITHOUT)) {
withoutHasContainer = hasContainer;
break;
}
}
//from and without are mutually exclusive, only one will ever be set.
Map<String, Map<String, PropertyType>> filteredAllTables;
if (fromHasContainer != null) {
filteredAllTables = schemaManager.getAllTablesFrom((List<String>) fromHasContainer.getPredicate().getValue());
} else if (withoutHasContainer != null) {
filteredAllTables = schemaManager.getAllTablesWithout((List<String>) withoutHasContainer.getPredicate().getValue());
} else {
filteredAllTables = schemaManager.getAllTables();
}
return filteredAllTables;
}
public static void removeTopologyStrategyHasContainer(List<HasContainer> hasContainers) {
//remove the TopologyStrategy hasContainer
Optional<HasContainer> fromHascontainer = hasContainers.stream().filter(h -> h.getKey().equals(TopologyStrategy.TOPOLOGY_SELECTION_FROM)).findAny();
Optional<HasContainer> withoutHascontainer = hasContainers.stream().filter(h -> h.getKey().equals(TopologyStrategy.TOPOLOGY_SELECTION_WITHOUT)).findAny();
if (fromHascontainer.isPresent()) {
hasContainers.remove(fromHascontainer.get());
}
if (withoutHascontainer.isPresent()) {
hasContainers.remove(withoutHascontainer.get());
}
}
public static void dropDb(SqlgGraph sqlgGraph) {
try {
SqlDialect sqlDialect = sqlgGraph.getSqlDialect();
Connection conn = sqlgGraph.tx().getConnection();
DatabaseMetaData metadata = conn.getMetaData();
if (sqlDialect.supportsCascade()) {
String catalog = null;
String schemaPattern = null;
String tableNamePattern = "%";
String[] types = {"TABLE"};
ResultSet result = metadata.getTables(catalog, schemaPattern, tableNamePattern, types);
while (result.next()) {
String schema = result.getString(2);
String table = result.getString(3);
if (sqlDialect.getGisSchemas().contains(schema) || sqlDialect.getSpacialRefTable().contains(table)) {
continue;
}
StringBuilder sql = new StringBuilder("DROP TABLE ");
sql.append(sqlDialect.maybeWrapInQoutes(schema));
sql.append(".");
sql.append(sqlDialect.maybeWrapInQoutes(table));
sql.append(" CASCADE");
if (sqlDialect.needsSemicolon()) {
sql.append(";");
}
try (PreparedStatement preparedStatement = conn.prepareStatement(sql.toString())) {
preparedStatement.executeUpdate();
}
}
catalog = null;
schemaPattern = null;
result = metadata.getSchemas(catalog, schemaPattern);
while (result.next()) {
String schema = result.getString(1);
if (!sqlDialect.getDefaultSchemas().contains(schema)) {
StringBuilder sql = new StringBuilder("DROP SCHEMA ");
sql.append(sqlDialect.maybeWrapInQoutes(schema));
sql.append(" CASCADE");
if (sqlDialect.needsSemicolon()) {
sql.append(";");
}
try (PreparedStatement preparedStatement = conn.prepareStatement(sql.toString())) {
preparedStatement.executeUpdate();
}
}
}
} else if (!sqlDialect.supportSchemas()) {
ResultSet result = metadata.getCatalogs();
while (result.next()) {
StringBuilder sql = new StringBuilder("DROP DATABASE ");
String database = result.getString(1);
if (!sqlDialect.getDefaultSchemas().contains(database)) {
sql.append(sqlDialect.maybeWrapInQoutes(database));
if (sqlDialect.needsSemicolon()) {
sql.append(";");
}
try (PreparedStatement preparedStatement = conn.prepareStatement(sql.toString())) {
preparedStatement.executeUpdate();
}
}
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static Byte[] convertPrimitiveByteArrayToByteArray(byte[] value) {
Byte[] target = new Byte[value.length];
for (int i = 0; i < value.length; i++) {
Array.set(target, i, value[i]);
}
return target;
}
public static Object convertByteArrayToPrimitiveArray(Byte[] value) {
byte[] target = new byte[value.length];
for (int i = 0; i < value.length; i++) {
if (value[i] == null) {
throw new IllegalArgumentException(PROPERTY_ARRAY_VALUE_ELEMENTS_MAY_NOT_BE_NULL);
}
Array.set(target, i, value[i].byteValue());
}
return target;
}
public static byte[] convertObjectArrayToBytePrimitiveArray(Object[] byteArray) {
byte[] target = new byte[byteArray.length];
for (int i = 0; i < byteArray.length; i++) {
Array.set(target, i, byteArray[i]);
}
return target;
}
public static Boolean[] convertObjectArrayToBooleanArray(Object[] booleanArray) {
Boolean[] target = new Boolean[booleanArray.length];
for (int i = 0; i < booleanArray.length; i++) {
Array.set(target, i, booleanArray[i]);
}
return target;
}
public static boolean[] convertObjectArrayToBooleanPrimitiveArray(Object[] booleanArray) {
boolean[] target = new boolean[booleanArray.length];
for (int i = 0; i < booleanArray.length; i++) {
Array.set(target, i, booleanArray[i]);
}
return target;
}
public static Short[] convertObjectOfIntegersArrayToShortArray(Object[] shortArray) {
Short[] target = new Short[shortArray.length];
for (int i = 0; i < shortArray.length; i++) {
Array.set(target, i, Short.valueOf(((Integer) shortArray[i]).shortValue()));
}
return target;
}
public static short[] convertObjectOfIntegersArrayToShortPrimitiveArray(Object[] shortArray) {
short[] target = new short[shortArray.length];
for (int i = 0; i < shortArray.length; i++) {
Array.set(target, i, ((Integer) shortArray[i]).shortValue());
}
return target;
}
public static Integer[] convertObjectOfIntegersArrayToIntegerArray(Object[] integerArray) {
Integer[] target = new Integer[integerArray.length];
for (int i = 0; i < integerArray.length; i++) {
Array.set(target, i, integerArray[i]);
}
return target;
}
public static int[] convertObjectOfIntegersArrayToIntegerPrimitiveArray(Object[] integerArray) {
int[] target = new int[integerArray.length];
for (int i = 0; i < integerArray.length; i++) {
Array.set(target, i, integerArray[i]);
}
return target;
}
public static long[] convertObjectOfLongsArrayToLongPrimitiveArray(Object[] longArray) {
long[] target = new long[longArray.length];
for (int i = 0; i < longArray.length; i++) {
Array.set(target, i, longArray[i]);
}
return target;
}
public static double[] convertObjectOfDoublesArrayToDoublePrimitiveArray(Object[] doubleArray) {
double[] target = new double[doubleArray.length];
for (int i = 0; i < doubleArray.length; i++) {
Array.set(target, i, doubleArray[i]);
}
return target;
}
public static Long[] convertObjectOfLongsArrayToLongArray(Object[] longArray) {
Long[] target = new Long[longArray.length];
for (int i = 0; i < longArray.length; i++) {
Array.set(target, i, longArray[i]);
}
return target;
}
public static Double[] convertObjectOfDoublesArrayToDoubleArray(Object[] doubleArray) {
Double[] target = new Double[doubleArray.length];
for (int i = 0; i < doubleArray.length; i++) {
Array.set(target, i, doubleArray[i]);
}
return target;
}
public static String[] convertObjectOfStringsArrayToStringArray(Object[] stringArray) {
String[] target = new String[stringArray.length];
for (int i = 0; i < stringArray.length; i++) {
Array.set(target, i, stringArray[i]);
}
return target;
}
public static float[] convertFloatArrayToPrimitiveFloat(Float[] floatArray) {
float[] target = new float[floatArray.length];
for (int i = 0; i < floatArray.length; i++) {
Array.set(target, i, floatArray[i].floatValue());
}
return target;
}
public static <T> T copyToLocalDateTime(Timestamp[] value, T target) {
for (int i = 0; i < value.length; i++) {
if (value[i] == null) {
throw new IllegalArgumentException(PROPERTY_ARRAY_VALUE_ELEMENTS_MAY_NOT_BE_NULL);
}
Array.set(target, i, value[i].toLocalDateTime());
}
return target;
}
public static <T> T copyObjectArrayOfTimestampToLocalDateTime(Object[] value, T target) {
for (int i = 0; i < value.length; i++) {
if (value[i] == null) {
throw new IllegalArgumentException(PROPERTY_ARRAY_VALUE_ELEMENTS_MAY_NOT_BE_NULL);
}
Array.set(target, i, ((Timestamp) value[i]).toLocalDateTime());
}
return target;
}
public static <T> T copyToLocalDate(Date[] value, T target) {
for (int i = 0; i < value.length; i++) {
if (value[i] == null) {
throw new IllegalArgumentException(PROPERTY_ARRAY_VALUE_ELEMENTS_MAY_NOT_BE_NULL);
}
Array.set(target, i, value[i].toLocalDate());
}
return target;
}
public static <T> T copyObjectArrayOfDateToLocalDate(Object[] value, T target) {
for (int i = 0; i < value.length; i++) {
if (value[i] == null) {
throw new IllegalArgumentException(PROPERTY_ARRAY_VALUE_ELEMENTS_MAY_NOT_BE_NULL);
}
Array.set(target, i, ((Date) value[i]).toLocalDate());
}
return target;
}
private static <T> T copyToLocalDate(Object[] value, T target) {
for (int i = 0; i < value.length; i++) {
if (value[i] == null) {
throw new IllegalArgumentException(PROPERTY_ARRAY_VALUE_ELEMENTS_MAY_NOT_BE_NULL);
}
Array.set(target, i, ((Date) value[i]).toLocalDate());
}
return target;
}
public static <T> T copyToLocalTime(Time[] value, T target) {
for (int i = 0; i < value.length; i++) {
if (value[i] == null) {
throw new IllegalArgumentException(PROPERTY_ARRAY_VALUE_ELEMENTS_MAY_NOT_BE_NULL);
}
Array.set(target, i, (value[i]).toLocalTime());
}
return target;
}
public static <T> T copyObjectArrayOfTimeToLocalTime(Object[] value, T target) {
for (int i = 0; i < value.length; i++) {
if (value[i] == null) {
throw new IllegalArgumentException(PROPERTY_ARRAY_VALUE_ELEMENTS_MAY_NOT_BE_NULL);
}
Array.set(target, i, ((Time) value[i]).toLocalTime());
}
return target;
}
}
|
package eu.stratuslab.storage.disk.main;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;
import org.restlet.data.Status;
import org.restlet.resource.ResourceException;
import eu.stratuslab.storage.disk.utils.FileUtils;
import eu.stratuslab.storage.disk.utils.ProcessUtils;
public class ServiceConfiguration {
private static final ServiceConfiguration instance = new ServiceConfiguration();
public enum DiskType {
LVM, FILE;
public static DiskType valueOfIgnoreCase(String value) {
try {
return valueOf(value.toUpperCase());
} catch (IllegalArgumentException e) {
throw new ResourceException(Status.SERVER_ERROR_INTERNAL,
"illegal value for disk.store.iscsi.type: " + value);
}
}
}
public enum ShareType {
ISCSI, NFS;
public static ShareType valueOfIgnoreCase(String value) {
try {
return valueOf(value.toUpperCase());
} catch (IllegalArgumentException e) {
throw new ResourceException(Status.SERVER_ERROR_INTERNAL,
"illegal value for disk.store.share: " + value);
}
}
}
// Configuration file
public static final String SYSTEM_PROPERTY_CONFIG_FILENAME = "pdisk.config.filename";
public static final String DEFAULT_CFG_FILENAME = "/etc/stratuslab/pdisk.cfg";
public static final String DEFAULT_ISCSI_CONFIG_FILENAME = "/etc/stratuslab/iscsi.conf";
public static final String ISCSI_CONFIG_FILENAME_SYS_PARAM_NAME = "iscsi.config.filename";
// Disk size limits (in GiBs)
public static final int DISK_SIZE_MIN = 1;
public static final int DISK_SIZE_MAX = 1024;
public static final int CACHE_EXPIRATION_DURATION = 2000;
public final Properties CONFIGURATION;
public final ShareType SHARE_TYPE;
public final DiskType ISCSI_DISK_TYPE;
public final File ISCSI_CONFIG;
public final String ISCSI_ADMIN;
public final String LVM_GROUP_PATH;
public final String VGDISPLAY_CMD;
public final String LVCREATE_CMD;
public final String LVREMOVE_CMD;
public final String LVCHANGE_CMD;
public final String DMSETUP_CMD;
public final File STORAGE_LOCATION;
public final int USERS_PER_DISK;
public final String CLOUD_NODE_SSH_KEY;
public final String CLOUD_NODE_ADMIN;
public final String CLOUD_NODE_VM_DIR;
public final String CLOUD_SERVICE_USER;
public final String CACHE_LOCATION;
public final String GZIP_CMD;
public final String GUNZIP_CMD;
public final int UPLOAD_COMPRESSED_IMAGE_MAX_BYTES;
private ServiceConfiguration() {
CONFIGURATION = readConfigFile();
SHARE_TYPE = getShareType();
ISCSI_DISK_TYPE = getDiskType();
ISCSI_CONFIG = getISCSIConfig();
ISCSI_ADMIN = getCommand("disk.store.iscsi.admin");
VGDISPLAY_CMD = getLVMCommand("disk.store.lvm.vgdisplay");
LVCREATE_CMD = getLVMCommand("disk.store.lvm.create");
LVREMOVE_CMD = getLVMCommand("disk.store.lvm.remove");
LVM_GROUP_PATH = getLVMGroup();
LVCHANGE_CMD = getLVMCommand("disk.store.lvm.lvchange");
DMSETUP_CMD = getLVMCommand("disk.store.lvm.dmsetup");
STORAGE_LOCATION = getDiskLocation();
USERS_PER_DISK = getUsersPerDisks();
CLOUD_NODE_SSH_KEY = getConfigValue("disk.store.cloud.node.ssh_keyfile");
CLOUD_NODE_ADMIN = getConfigValue("disk.store.cloud.node.admin");
CLOUD_NODE_VM_DIR = getConfigValue("disk.store.cloud.node.vm_dir");
CLOUD_SERVICE_USER = getConfigValue("disk.store.cloud.service.user");
CACHE_LOCATION = getCacheLocation();
GZIP_CMD = getCommand("disk.store.utils.gzip");
GUNZIP_CMD = getCommand("disk.store.utils.gunzip");
UPLOAD_COMPRESSED_IMAGE_MAX_BYTES = 10240000;
}
public static ServiceConfiguration getInstance() {
return instance;
}
private static Properties readConfigFile() {
File cfgFile = new File(System.getProperty(SYSTEM_PROPERTY_CONFIG_FILENAME, DEFAULT_CFG_FILENAME));
Properties properties = new Properties();
if (!cfgFile.exists()) {
throw new ResourceException(Status.SERVER_ERROR_INTERNAL,
"Configuration file does not exists.");
}
FileReader reader = null;
try {
reader = new FileReader(cfgFile);
properties.load(reader);
} catch (IOException consumed) {
throw new ResourceException(Status.SERVER_ERROR_INTERNAL,
"An error occured while reading configuration file");
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException consumed) {
throw new ResourceException(Status.SERVER_ERROR_INTERNAL,
"An error occured while reading configuration file");
}
}
}
return properties;
}
private ShareType getShareType() {
String type = getConfigValue("disk.store.share");
return ShareType.valueOfIgnoreCase(type);
}
private DiskType getDiskType() {
String value = getConfigValue("disk.store.iscsi.type");
return DiskType.valueOfIgnoreCase(value);
}
private File getISCSIConfig() {
String iscsiConf = getConfigValue("disk.store.iscsi.conf");
File confHandler = new File(iscsiConf);
File stratusConf = new File(System.getProperty(
ISCSI_CONFIG_FILENAME_SYS_PARAM_NAME,
DEFAULT_ISCSI_CONFIG_FILENAME));
String includeConfig = "\ninclude " + stratusConf.getAbsolutePath()
+ "\n";
if (!confHandler.isFile()) {
throw new ResourceException(Status.SERVER_ERROR_INTERNAL,
"Unable to find ISCSI configuration file " + confHandler.getAbsolutePath());
}
if (!isPdiskIscsiConfigInGlobalIscsiConfig(confHandler, includeConfig)) {
FileUtils.appendToFile(confHandler, includeConfig);
}
return stratusConf;
}
private Boolean isPdiskIscsiConfigInGlobalIscsiConfig(File confHandler,
String includeConfig) {
return FileUtils
.fileHasLine(confHandler, includeConfig.replace("\n", ""));
}
private String getConfigValue(String key) {
if (!CONFIGURATION.containsKey(key)) {
throw new ResourceException(Status.SERVER_ERROR_INTERNAL,
"Unable to retrieve configuration key: " + key);
}
return CONFIGURATION.getProperty(key);
}
private File getDiskLocation() {
String diskStoreDir;
if (SHARE_TYPE == ShareType.ISCSI) {
diskStoreDir = getConfigValue("disk.store.iscsi.file.location");
} else {
diskStoreDir = getConfigValue("disk.store.nfs.location");
}
File diskStoreHandler = new File(diskStoreDir);
// Don't check if we use LVM
if (SHARE_TYPE == ShareType.ISCSI && ISCSI_DISK_TYPE == DiskType.LVM) {
return diskStoreHandler;
}
if (!diskStoreHandler.isDirectory() || !diskStoreHandler.canWrite()
|| !diskStoreHandler.canRead()) {
throw new ResourceException(Status.SERVER_ERROR_INTERNAL,
"Disk store must be readable and writable");
}
return diskStoreHandler;
}
private String getCacheLocation() {
String cache = getConfigValue("disk.store.cache.location");
File cacheDir = new File(cache);
if (cacheDir.exists()) {
if (!cacheDir.isDirectory()) {
throw new ResourceException(Status.SERVER_ERROR_INTERNAL,
"Cache location " + cacheDir.getAbsolutePath()
+ " already in use");
} else if (!cacheDir.canWrite()) {
throw new ResourceException(Status.SERVER_ERROR_INTERNAL,
"Cannot write cache location "
+ cacheDir.getAbsolutePath());
}
} else {
if (!cacheDir.mkdirs()) {
throw new ResourceException(Status.SERVER_ERROR_INTERNAL,
"Unable to create cache location "
+ cacheDir.getAbsolutePath());
}
}
return cache;
}
private String getCommand(String configName) {
String configValue = getConfigValue(configName);
File exec = new File(configValue);
if (!FileUtils.isExecutable(exec)) {
throw new ResourceException(Status.SERVER_ERROR_INTERNAL,
configValue
+ " command does not exist or is not executable");
}
return configValue;
}
private String getLVMCommand(String configName) {
// Require command only if used
if (SHARE_TYPE == ShareType.ISCSI && ISCSI_DISK_TYPE == DiskType.LVM) {
return getCommand(configName);
} else {
return "/bin/echo";
}
}
private String getLVMGroup() {
String lvmGroup = getConfigValue("disk.store.lvm.device");
// Check group only if necessary
if (SHARE_TYPE == ShareType.ISCSI && ISCSI_DISK_TYPE == DiskType.LVM) {
checkLVMGroupExists(lvmGroup);
}
return lvmGroup;
}
private int getUsersPerDisks() {
String users = getConfigValue("disk.store.user_per_disk");
int userNo = 0;
try {
userNo = Integer.parseInt(users);
} catch (NumberFormatException e) {
throw new ResourceException(Status.SERVER_ERROR_INTERNAL,
"Unable to get user per disk value");
}
return userNo;
}
private void checkLVMGroupExists(String lvmGroup) {
ProcessBuilder pb = new ProcessBuilder(VGDISPLAY_CMD, lvmGroup);
ProcessUtils
.execute(pb,
"LVM Group does not exist. Please create it and restart pdisk service");
}
}
|
package org.sana.net.http.handler;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ResponseHandler;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class FileHandler implements ResponseHandler<File> {
public static final String TAG = FileHandler.class.getSimpleName();
final String path;
final File file;
public FileHandler(String path){
this.path = path;
file = new File(path);
}
public FileHandler(File file){
this.file = file;
path = file.getPath();
}
@Override
public File handleResponse(HttpResponse response){
if(file.exists()) file.delete();
HttpEntity entity = response.getEntity();
if (entity != null) {
try {
FileOutputStream os = new FileOutputStream(file);
InputStream is = entity.getContent();
int inByte;
while((inByte = is.read()) != -1) os.write(inByte);
is.close();
os.close();
} catch(IOException ioe){
ioe.printStackTrace();
}
}
return file;
}
}
|
package org.openmrs.maven.plugins;
import org.apache.commons.lang.StringUtils;
import org.apache.maven.model.Model;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.eclipse.egit.github.core.RepositoryId;
import org.eclipse.egit.github.core.client.GitHubClient;
import org.eclipse.egit.github.core.service.RepositoryService;
import org.eclipse.jgit.api.Git;
import org.openmrs.maven.plugins.model.Artifact;
import org.openmrs.maven.plugins.utility.Project;
import org.openmrs.maven.plugins.utility.SDKConstants;
import org.twdata.maven.mojoexecutor.MojoExecutor;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import static org.twdata.maven.mojoexecutor.MojoExecutor.*;
/**
* @goal clone
* @requiresProject false
*/
public class Clone extends AbstractTask {
public static final String GITHUB_COM = "github.com";
public static final String GITHUB_HTTP_SUFFIX = "https://github.com/";
/**
* @parameter expression="${groupId}"
*/
private String groupId;
/**
* @parameter expression="${artifactId}"
*/
private String artifactId;
/**
* @parameter expression="${githubUsername}"
*/
private String githubUsername;
/**
* @parameter expression="${githubPassword}"
*/
private String githubPassword;
@Override
public void executeTask() throws MojoExecutionException, MojoFailureException {
groupId = wizard.promptForValueIfMissingWithDefault(null, groupId, "groupId", "org.openmrs.module");
artifactId = wizard.promptForValueIfMissing(artifactId, "artifactId");
String version = versionsHelper.getLatestReleasedVersion(new Artifact(artifactId, "0", groupId));
String repoUrl;
try {
repoUrl = extractGitHubHttpKeyFromModulePom(artifactId, version, groupId);
} catch (IOException e) {
throw new IllegalStateException("Failed to fetch scm url from maven repository", e);
}
githubUsername = wizard.promptForValueIfMissing(githubUsername, "your GitHub username");
githubPassword = wizard.promptForPasswordIfMissing(githubPassword, "your GitHub password");
cloneRepo(repoUrl);
}
private String extractGitHubHttpKeyFromModulePom(String artifactId, String version, String groupId) throws MojoExecutionException, IOException {
downloadModulePom(new Artifact(artifactId, version, groupId, "pom"));
String pomFileName = this.artifactId+"-"+version+".pom";
File pomDir = new File("pom/");
File pom = new File("pom/", pomFileName);
Model pomProperties = Project.loadProject(pomDir, pomFileName).getModel();
String url = pomProperties.getScm().getUrl();
pom.delete();
pomDir.delete();
return extractUniversalRepoUrl(url);
}
private String extractUniversalRepoUrl(String repoUrl) {
String result;
result = repoUrl.substring(repoUrl.indexOf(GITHUB_COM) + GITHUB_COM.length() + 1);
result = StringUtils.removeEnd(result,"/");
if (!repoUrl.endsWith(".git")) {
return result + ".git";
}
else {
return result;
}
}
private void downloadModulePom(Artifact artifact) throws MojoExecutionException {
MojoExecutor.Element[] artifactItems = new MojoExecutor.Element[1];
artifactItems[0] = artifact.toElement("pom/");
List<Element> configuration = new ArrayList<Element>();
configuration.add(element("artifactItems", artifactItems));
executeMojo(
plugin(
groupId(SDKConstants.PLUGIN_DEPENDENCIES_GROUP_ID),
artifactId(SDKConstants.PLUGIN_DEPENDENCIES_ARTIFACT_ID),
version(SDKConstants.PLUGIN_DEPENDENCIES_VERSION)
),
goal("copy"),
configuration(configuration.toArray(new Element[0])),
executionEnvironment(mavenProject, mavenSession, pluginManager)
);
}
private void forkRepo(String repoName, String repoOwner) {
wizard.showMessage("Forking " + repoName + " from " + repoOwner);
GitHubClient client = new GitHubClient();
client.setCredentials(githubUsername, githubPassword);
RepositoryService service = new RepositoryService();
service.getClient().setCredentials(githubUsername, githubPassword);
RepositoryId toBeForked = new RepositoryId(repoOwner, repoName);
try {
service.forkRepository(toBeForked);
} catch (IOException e) {
throw new IllegalStateException("Failed to fork repository", e);
}
}
private void cloneRepo(String repoUrl) {
String repoOwner = repoUrl.substring(0, repoUrl.indexOf("/"));
String originUrl = StringUtils.replaceOnce(repoUrl, repoOwner, githubUsername);
String repoName = repoUrl.substring(repoOwner.length() + 1, repoUrl.lastIndexOf(".git"));
if ("false".equals(testMode)) {
forkRepo(repoName, repoOwner);
}
File localPath = new File(repoName);
wizard.showMessage("Cloning from " + originUrl + " into " + localPath.getAbsolutePath());
if (localPath.exists()) {
throw new IllegalStateException("Destination path \"" + localPath.getAbsolutePath() + "\" already exists.");
}
try {
Git.cloneRepository()
.setURI(GITHUB_HTTP_SUFFIX + originUrl)
.setDirectory(localPath)
.call();
Git git = new Git(gitHelper.getLocalRepository(localPath.getAbsolutePath()));
gitHelper.addRemoteUpstream(git, localPath.getAbsolutePath());
} catch (Exception e) {
throw new IllegalStateException("Failed to clone repository", e);
}
}
}
|
package dr.evomodel.coalescent;
//import com.sun.xml.internal.messaging.saaj.packaging.mime.internet.ParameterList;
import dr.evolution.coalescent.IntervalType;
import dr.evolution.coalescent.TreeIntervals;
import dr.evolution.tree.Tree;
import dr.evomodel.tree.TreeModel;
import dr.evomodelxml.coalescent.GMRFSkyrideLikelihoodParser;
import dr.inference.hmc.GradientWrtParameterProvider;
import dr.inference.model.Likelihood;
import dr.inference.model.MatrixParameter;
import dr.inference.model.Model;
import dr.inference.model.Parameter;
import dr.util.Author;
import dr.util.Citable;
import dr.util.Citation;
import no.uib.cipr.matrix.DenseVector;
import no.uib.cipr.matrix.SymmTridiagMatrix;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* @author Mandev Gill
* @author Marc A. Suchard
*/
public class GMRFMultilocusSkyrideLikelihood extends GMRFSkyrideLikelihood
implements GradientWrtParameterProvider, MultiLociTreeSet, CoalescentIntervalProvider, Citable {
public static final boolean DEBUG = false;
private double cutOff;
private int numGridPoints;
protected int oldFieldLength;
// number of coalescent events which occur in an interval with constant population size
protected double[] numCoalEvents;
protected double[] storedNumCoalEvents;
protected double[] gridPoints;
protected double theLastTime;
protected double diagonalValue;
// sortedPoints[i][0] is the time of the i-th grid point or sampling or coalescent event
// sortedPoints[i][1] is 0 if the i-th point is a grid point, 1 if it's a sampling point, and 2 if it's a coalescent point
// sortedPoints[i][2] is the number of lineages present in the interval starting at time sortedPoints[i][0]
protected Parameter phiParameter;
protected Parameter ploidyFactors;
protected double[] ploidySums;
protected double[] storedPloidySums;
protected SymmTridiagMatrix precMatrix;
protected SymmTridiagMatrix storedPrecMatrix;
private SkygridHelper skygridHelper;
protected List<Parameter> missingCov;
protected List<MatrixParameter> covariates;
protected List<Parameter> beta;
protected List<Parameter> covPrecParametersRecent;
protected List<Parameter> covPrecParametersDistant;
protected List<SymmTridiagMatrix> weightMatricesForMissingCovRecent;
protected List<SymmTridiagMatrix> weightMatricesForMissingCovDistant;
protected int[] firstObservedIndex;
protected int[] lastObservedIndex;
protected int[] recIndices;
protected int[] distIndices;
private double[] coalescentEventStatisticValues;
public GMRFMultilocusSkyrideLikelihood(List<Tree> treeList,
Parameter popParameter,
Parameter groupParameter,
Parameter precParameter,
Parameter lambda,
Parameter beta,
MatrixParameter dMatrix,
boolean timeAwareSmoothing,
double cutOff,
int numGridPoints,
Parameter phi,
Parameter ploidyFactorsParameter) {
super(GMRFSkyrideLikelihoodParser.SKYLINE_LIKELIHOOD);
// adding the key word to the the model means the keyword will be logged in the
// header of the logfile.
this.addKeyword("skygrid");
if (treeList.size() > 1) {
this.addKeyword("multilocus");
}
this.popSizeParameter = popParameter;
this.groupSizeParameter = groupParameter;
this.precisionParameter = precParameter;
this.lambdaParameter = lambda;
this.betaParameter = beta;
this.dMatrix = dMatrix;
if (dMatrix != null) {
addVariable(dMatrix);
}
this.timeAwareSmoothing = timeAwareSmoothing;
this.cutOff = cutOff;
this.numGridPoints = numGridPoints;
this.phiParameter = phi;
this.ploidyFactors = ploidyFactorsParameter;
setupGridPoints();
addVariable(popSizeParameter);
addVariable(precisionParameter);
addVariable(lambdaParameter);
if (betaParameter != null) {
addVariable(betaParameter);
skygridHelper = new SkygridCovariateHelper();
} else {
skygridHelper = new SkygridHelper();
}
if (phiParameter != null) {
addVariable(phiParameter);
}
addVariable(ploidyFactors);
setTree(treeList);
int correctFieldLength = getCorrectFieldLength();
if (popSizeParameter.getDimension() <= 1) {
// popSize dimension hasn't been set yet, set it here:
popSizeParameter.setDimension(correctFieldLength);
}
fieldLength = popSizeParameter.getDimension();
if (correctFieldLength != fieldLength) {
throw new IllegalArgumentException("Population size parameter should have length " + correctFieldLength);
}
oldFieldLength = getCorrectOldFieldLength();
if (ploidyFactors.getDimension() != treeList.size()) {
throw new IllegalArgumentException("Ploidy factors parameter should have length " + treeList.size());
}
// Field length must be set by this point
wrapSetupIntervals();
coalescentIntervals = new double[oldFieldLength];
storedCoalescentIntervals = new double[oldFieldLength];
sufficientStatistics = new double[fieldLength];
storedSufficientStatistics = new double[fieldLength];
numCoalEvents = new double[fieldLength];
storedNumCoalEvents = new double[fieldLength];
ploidySums = new double[fieldLength];
storedPloidySums = new double[fieldLength];
setupGMRFWeights();
setupSufficientStatistics();
addStatistic(new DeltaStatistic());
initializationReport();
/* Force all entries in groupSizeParameter = 1 for compatibility with Tracer */
if (groupSizeParameter != null) {
for (int i = 0; i < groupSizeParameter.getDimension(); i++)
groupSizeParameter.setParameterValue(i, 1.0);
}
this.coalescentEventStatisticValues = new double[getNumberOfCoalescentEvents()];
}
//rewrite this constructor without duplicating so much code
public GMRFMultilocusSkyrideLikelihood(List<Tree> treeList,
Parameter popParameter,
Parameter groupParameter,
Parameter precParameter,
Parameter lambda,
Parameter betaParameter,
MatrixParameter dMatrix,
boolean timeAwareSmoothing,
Parameter specGridPoints,
List<MatrixParameter> covariates,
Parameter ploidyFactorsParameter,
List<Parameter> firstObservedIndexParameter,
List<Parameter> lastObservedIndexParameter,
List<Parameter> covPrecParametersRecent,
List<Parameter> covPrecParametersDistant,
Parameter recentIndices,
Parameter distantIndices,
List<Parameter> betaList) {
super(GMRFSkyrideLikelihoodParser.SKYLINE_LIKELIHOOD);
// adding the key word to the the model means the keyword will be logged in the
// header of the logfile.
this.addKeyword("skygrid");
if (treeList.size() > 1) {
this.addKeyword("multilocus");
}
this.gridPoints = specGridPoints.getParameterValues();
this.numGridPoints = gridPoints.length;
this.cutOff = gridPoints[numGridPoints - 1];
if (firstObservedIndexParameter != null) {
this.firstObservedIndex = new int[firstObservedIndexParameter.size()];
for (int i = 0; i < firstObservedIndexParameter.size(); i++) {
this.firstObservedIndex[i] = (int) firstObservedIndexParameter.get(i).getParameterValue(0);
}
if(recentIndices != null){
// indices specify which covariates require default unobserved covariate data prior
this.recIndices = new int [firstObservedIndexParameter.size()];
for (int i = 0; i < firstObservedIndexParameter.size(); i++){
this.recIndices[i] = (int) recentIndices.getParameterValue(i);
}
}else{
// If specific covariates not specified by indices, need default unobserved covariate data prior for all covariates
this.recIndices = new int [firstObservedIndexParameter.size()];
for (int i = 0; i < firstObservedIndexParameter.size(); i++){
this.recIndices[i] = i+1;
}
}
}
if (lastObservedIndexParameter != null) {
this.lastObservedIndex = new int[lastObservedIndexParameter.size()];
for (int i = 0; i < lastObservedIndexParameter.size(); i++) {
this.lastObservedIndex[i] = (int) lastObservedIndexParameter.get(i).getParameterValue(0);
}
if(distantIndices != null){
// indices specify which covariates require default unobserved covariate data prior
this.distIndices = new int [lastObservedIndexParameter.size()];
for (int i = 0; i < lastObservedIndexParameter.size(); i++){
this.distIndices[i] = (int) distantIndices.getParameterValue(i);
}
}else{
// If specific covariates not specified by indices, need default unobserved covariate data prior for all covariates
this.distIndices = new int [lastObservedIndexParameter.size()];
for (int i = 0; i < lastObservedIndexParameter.size(); i++){
this.distIndices[i] = i+1;
}
}
}
/*else{
for(int i=0; i < beta.getDimension(); i++) {
this.lastObservedIndex[i] = popParameter.getDimension();
}
}*/
this.betaParameter = betaParameter;
if (betaParameter != null) {
addVariable(betaParameter);
}
this.popSizeParameter = popParameter;
this.groupSizeParameter = groupParameter;
this.precisionParameter = precParameter;
this.lambdaParameter = lambda;
this.beta = betaList;
this.dMatrix = dMatrix;
if (dMatrix != null) {
addVariable(dMatrix);
}
this.timeAwareSmoothing = timeAwareSmoothing;
this.ploidyFactors = ploidyFactorsParameter;
this.covariates = covariates;
if (covariates != null) {
for (MatrixParameter cov : covariates) {
addVariable(cov);
}
}
this.covPrecParametersRecent = covPrecParametersRecent;
if (covPrecParametersRecent != null) {
for (Parameter covPrecRecent : covPrecParametersRecent) {
addVariable(covPrecRecent);
}
}
this.covPrecParametersDistant = covPrecParametersDistant;
if (covPrecParametersDistant != null){
for(Parameter covPrecDistant : covPrecParametersDistant){
addVariable(covPrecDistant);
}
}
addVariable(popSizeParameter);
addVariable(precisionParameter);
addVariable(lambdaParameter);
addVariable(ploidyFactors);
setTree(treeList);
int correctFieldLength = getCorrectFieldLength();
if (popSizeParameter.getDimension() <= 1) {
// popSize dimension hasn't been set yet, set it here:
popSizeParameter.setDimension(correctFieldLength);
}
fieldLength = popSizeParameter.getDimension();
if (correctFieldLength != fieldLength) {
throw new IllegalArgumentException("Population size parameter should have length " + correctFieldLength);
}
oldFieldLength = getCorrectOldFieldLength();
if (ploidyFactors.getDimension() != treeList.size()) {
throw new IllegalArgumentException("Ploidy factor parameter should have length " + treeList.size());
}
// Field length must be set by this point
if (betaList != null || betaParameter != null) {
if (betaList != null) {
for (Parameter betaParam : betaList) {
addVariable(betaParam);
}
}
if (lastObservedIndexParameter != null || firstObservedIndexParameter != null) {
setupGMRFWeightsForMissingCov();
skygridHelper = new SkygridMissingCovariateHelper();
} else {
skygridHelper = new SkygridCovariateHelper();
}
} else {
skygridHelper = new SkygridHelper();
}
wrapSetupIntervals();
coalescentIntervals = new double[oldFieldLength];
storedCoalescentIntervals = new double[oldFieldLength];
sufficientStatistics = new double[fieldLength];
storedSufficientStatistics = new double[fieldLength];
numCoalEvents = new double[fieldLength];
storedNumCoalEvents = new double[fieldLength];
ploidySums = new double[fieldLength];
storedPloidySums = new double[fieldLength];
setupGMRFWeights();
addStatistic(new DeltaStatistic());
initializationReport();
}
protected void setTree(List<Tree> treeList) {
treesSet = this;
this.treeList = treeList;
makeTreeIntervalList(treeList, true);
numTrees = treeList.size();
}
private void makeTreeIntervalList(List<Tree> treeList, boolean add) {
if (intervalsList == null) {
intervalsList = new ArrayList<TreeIntervals>();
} else {
intervalsList.clear();
}
for (Tree tree : treeList) {
intervalsList.add(new TreeIntervals(tree));
if (add && tree instanceof TreeModel) {
addModel((TreeModel) tree);
}
}
}
protected int getCorrectFieldLength() {
return numGridPoints + 1;
}
protected int getCorrectOldFieldLength() {
int tips = 0;
for (Tree tree : treeList) {
tips += tree.getExternalNodeCount();
}
return tips - treeList.size();
}
protected void handleModelChangedEvent(Model model, Object object, int index) {
if (model instanceof TreeModel) {
TreeModel treeModel = (TreeModel) model;
int tn = treeList.indexOf(treeModel);
if (tn >= 0) {
// intervalsList.get(tn).setIntervalsUnknown(); // TODO Why is this slower (?) than remaking whole list?
makeTreeIntervalList(treeList, false);
intervalsKnown = false;
likelihoodKnown = false;
} else {
throw new RuntimeException("Unknown tree modified in GMRFMultilocusSkyrideLikelihood");
}
} else {
throw new RuntimeException("Unknown object modified in GMRFMultilocusSkyrideLikelihood");
}
}
public void initializationReport() {
System.out.println("Creating a GMRF smoothed skyride model for multiple loci (SkyGrid)");
System.out.println("\tPopulation sizes: " + popSizeParameter.getDimension());
}
public void wrapSetupIntervals() {
// Do nothing
}
int numTrees;
protected void setupGridPoints() {
if (gridPoints == null) {
gridPoints = new double[numGridPoints];
} else {
Arrays.fill(gridPoints, 0);
}
for (int pt = 0; pt < numGridPoints; pt++) {
gridPoints[pt] = (pt + 1) * (cutOff / numGridPoints);
}
}
protected void setupSufficientStatistics() {
//numCoalEvents = new double[fieldLength];
//sufficientStatistics = new double[fieldLength];
Arrays.fill(numCoalEvents, 0);
Arrays.fill(sufficientStatistics, 0);
Arrays.fill(ploidySums, 0);
//index of smallest grid point greater than at least one sampling/coalescent time in current tree
int minGridIndex;
//index of greatest grid point less than at least one sampling/coalescent time in current tree
int maxGridIndex;
int numLineages;
int currentGridIndex;
int currentTimeIndex;
double currentTime;
double nextTime;
double ploidyFactor;
//time of last coalescent event in tree
double lastCoalescentTime;
for (int i = 0; i < numTrees; i++) {
ploidyFactor = 1 / getPopulationFactor(i);
currentTimeIndex = 0;
currentTime = intervalsList.get(i).getIntervalTime(currentTimeIndex);
nextTime = intervalsList.get(i).getIntervalTime(currentTimeIndex + 1);
while (nextTime <= currentTime) {
currentTimeIndex++;
currentTime = intervalsList.get(i).getIntervalTime(currentTimeIndex);
nextTime = intervalsList.get(i).getIntervalTime(currentTimeIndex + 1);
}
numLineages = intervalsList.get(i).getLineageCount(currentTimeIndex + 1);
minGridIndex = 0;
while (minGridIndex < numGridPoints - 1 && gridPoints[minGridIndex] <= currentTime) { // MAS: Unclear about need for -1
minGridIndex++;
}
currentGridIndex = minGridIndex;
lastCoalescentTime = currentTime + intervalsList.get(i).getTotalDuration();
theLastTime = lastCoalescentTime;
maxGridIndex = numGridPoints - 1;
while ((maxGridIndex >= 0) && (gridPoints[maxGridIndex] >= lastCoalescentTime)) {
maxGridIndex = maxGridIndex - 1;
}
if (maxGridIndex >= 0 && minGridIndex < numGridPoints) {
//from likelihood of interval between first sampling time and gridPoints[minGridIndex]
while (nextTime < gridPoints[currentGridIndex]) {
//check to see if interval ends with coalescent event
if (intervalsList.get(i).getCoalescentEvents(currentTimeIndex + 1) > 0) {
numCoalEvents[currentGridIndex]++;
}
sufficientStatistics[currentGridIndex] = sufficientStatistics[currentGridIndex] + (nextTime - currentTime) * numLineages * (numLineages - 1) * 0.5 * ploidyFactor;
currentTime = nextTime;
currentTimeIndex++;
nextTime = intervalsList.get(i).getIntervalTime(currentTimeIndex + 1);
while (nextTime <= currentTime) {
currentTimeIndex++;
currentTime = intervalsList.get(i).getIntervalTime(currentTimeIndex);
nextTime = intervalsList.get(i).getIntervalTime(currentTimeIndex + 1);
}
numLineages = intervalsList.get(i).getLineageCount(currentTimeIndex + 1);
}
sufficientStatistics[currentGridIndex] = sufficientStatistics[currentGridIndex] + (gridPoints[currentGridIndex] - currentTime) * numLineages * (numLineages - 1) * 0.5 * ploidyFactor;
ploidySums[currentGridIndex] = ploidySums[currentGridIndex] + Math.log(ploidyFactor) * numCoalEvents[currentGridIndex];
currentGridIndex++;
//from likelihood of intervals between gridPoints[minGridIndex] and gridPoints[maxGridIndex]
while (currentGridIndex <= maxGridIndex) {
if (nextTime >= gridPoints[currentGridIndex]) {
sufficientStatistics[currentGridIndex] = sufficientStatistics[currentGridIndex] + (gridPoints[currentGridIndex] - gridPoints[currentGridIndex - 1]) * numLineages * (numLineages - 1) * 0.5 * ploidyFactor;
ploidySums[currentGridIndex] = ploidySums[currentGridIndex] + Math.log(ploidyFactor) * numCoalEvents[currentGridIndex];
currentGridIndex++;
} else {
sufficientStatistics[currentGridIndex] = sufficientStatistics[currentGridIndex] + (nextTime - gridPoints[currentGridIndex - 1]) * numLineages * (numLineages - 1) * 0.5 * ploidyFactor;
//check to see if interval ends with coalescent event
if (intervalsList.get(i).getCoalescentEvents(currentTimeIndex + 1) > 0) {
numCoalEvents[currentGridIndex]++;
}
currentTime = nextTime;
currentTimeIndex++;
nextTime = intervalsList.get(i).getIntervalTime(currentTimeIndex + 1);
while (nextTime <= currentTime) {
currentTimeIndex++;
currentTime = intervalsList.get(i).getIntervalTime(currentTimeIndex);
nextTime = intervalsList.get(i).getIntervalTime(currentTimeIndex + 1);
}
numLineages = intervalsList.get(i).getLineageCount(currentTimeIndex + 1);
while (nextTime < gridPoints[currentGridIndex]) {
//check to see if interval is coalescent interval or sampling interval
if (intervalsList.get(i).getCoalescentEvents(currentTimeIndex + 1) > 0) {
numCoalEvents[currentGridIndex]++;
}
sufficientStatistics[currentGridIndex] = sufficientStatistics[currentGridIndex] + (nextTime - currentTime) * numLineages * (numLineages - 1) * 0.5 * ploidyFactor;
currentTime = nextTime;
currentTimeIndex++;
nextTime = intervalsList.get(i).getIntervalTime(currentTimeIndex + 1);
while (nextTime <= currentTime) {
currentTimeIndex++;
currentTime = intervalsList.get(i).getIntervalTime(currentTimeIndex);
nextTime = intervalsList.get(i).getIntervalTime(currentTimeIndex + 1);
}
numLineages = intervalsList.get(i).getLineageCount(currentTimeIndex + 1);
}
sufficientStatistics[currentGridIndex] = sufficientStatistics[currentGridIndex] + (gridPoints[currentGridIndex] - currentTime) * numLineages * (numLineages - 1) * 0.5 * ploidyFactor;
ploidySums[currentGridIndex] = ploidySums[currentGridIndex] + Math.log(ploidyFactor) * numCoalEvents[currentGridIndex];
currentGridIndex++;
}
}
//from likelihood of interval between gridPoints[maxGridIndex] and lastCoalescentTime
sufficientStatistics[currentGridIndex] = sufficientStatistics[currentGridIndex] + (nextTime - gridPoints[currentGridIndex - 1]) * numLineages * (numLineages - 1) * 0.5 * ploidyFactor;
//check to see if interval ends with coalescent event
if (intervalsList.get(i).getCoalescentEvents(currentTimeIndex + 1) > 0) {
numCoalEvents[currentGridIndex]++;
}
currentTime = nextTime;
currentTimeIndex++;
while ((currentTimeIndex + 1) < intervalsList.get(i).getIntervalCount()) {
// currentTime = nextTime;
// currentTimeIndex++;
nextTime = intervalsList.get(i).getIntervalTime(currentTimeIndex + 1);
while (nextTime <= currentTime) {
currentTimeIndex++;
currentTime = intervalsList.get(i).getIntervalTime(currentTimeIndex);
nextTime = intervalsList.get(i).getIntervalTime(currentTimeIndex + 1);
}
numLineages = intervalsList.get(i).getLineageCount(currentTimeIndex + 1);
//check to see if interval is coalescent interval or sampling interval
if (intervalsList.get(i).getCoalescentEvents(currentTimeIndex + 1) > 0) {
numCoalEvents[currentGridIndex]++;
}
sufficientStatistics[currentGridIndex] = sufficientStatistics[currentGridIndex] + (nextTime - currentTime) * numLineages * (numLineages - 1) * 0.5 * ploidyFactor;
currentTime = nextTime;
currentTimeIndex++;
}
// if tree does not overlap with any gridpoints/change-points, in which case logpopsize is constant
} else {
while ((currentTimeIndex + 1) < intervalsList.get(i).getIntervalCount()) {
//check to see if interval is coalescent interval or sampling interval
if (intervalsList.get(i).getCoalescentEvents(currentTimeIndex + 1) > 0) {
numCoalEvents[currentGridIndex]++;
}
sufficientStatistics[currentGridIndex] = sufficientStatistics[currentGridIndex] + (nextTime - currentTime) * numLineages * (numLineages - 1) * 0.5 * ploidyFactor;
currentTime = nextTime;
currentTimeIndex++;
if ((currentTimeIndex + 1) < intervalsList.get(i).getIntervalCount()) {
nextTime = intervalsList.get(i).getIntervalTime(currentTimeIndex + 1);
while (nextTime <= currentTime) {
currentTimeIndex++;
currentTime = intervalsList.get(i).getIntervalTime(currentTimeIndex);
nextTime = intervalsList.get(i).getIntervalTime(currentTimeIndex + 1);
}
numLineages = intervalsList.get(i).getLineageCount(currentTimeIndex + 1);
}
}
ploidySums[currentGridIndex] = ploidySums[currentGridIndex] + Math.log(ploidyFactor) * numCoalEvents[currentGridIndex];
}
}
}
public double[] getNumCoalEvents() {
return numCoalEvents;
}
public int getNumberOfCoalescentEvents() {
return getCorrectOldFieldLength();
}
public double getCoalescentEventsStatisticValue(int i) {
if (i == 0) {
if (DEBUG) {
System.err.println("numTrees: " + numTrees);
System.err.println("getCoalescentIntervalDimension(): " + super.getCoalescentIntervalDimension());
System.err.println("getNumberOfCoalescentEvents(): " + getNumberOfCoalescentEvents());
System.err.println("getIntervalCount(): " + getIntervalCount());
System.err.println("intervalsList.size(): " + intervalsList.size());
System.err.println("intervalsList.get(0).getIntervalCount(): " + intervalsList.get(0).getIntervalCount());
}
if (numTrees > 1) {
throw new RuntimeException("Generalized stepping-stone sampling for the Skygrid not implemented for #trees > 1");
}
for (int j = 0; j < coalescentEventStatisticValues.length; j++) {
coalescentEventStatisticValues[j] = 0.0;
}
int counter = 0;
for (int j = 0; j < intervalsList.get(0).getIntervalCount(); j++) {
if (intervalsList.get(0).getIntervalType(j) == IntervalType.COALESCENT) {
//this.coalescentEventStatisticValues[counter] += getCoalescentInterval(j) * (getLineageCount(j) * (getLineageCount(j) - 1.0)) / 2.0;
this.coalescentEventStatisticValues[counter] += intervalsList.get(0).getInterval(j) * (intervalsList.get(0).getLineageCount(j) * (intervalsList.get(0).getLineageCount(j) - 1.0)) / 2.0;
counter++;
} else {
//this.coalescentEventStatisticValues[counter] += getCoalescentInterval(j) * (getLineageCount(j) * (getLineageCount(j) - 1.0)) / 2.0;
this.coalescentEventStatisticValues[counter] += intervalsList.get(0).getInterval(j) * (intervalsList.get(0).getLineageCount(j) * (intervalsList.get(0).getLineageCount(j) - 1.0)) / 2.0;
}
}
}
return coalescentEventStatisticValues[i];
//throw new RuntimeException("getCoalescentEventsStatisticValue(int i) not implemented for Bayesian Skygrid");
//return sufficientStatistics[i];
}
protected double calculateLogCoalescentLikelihood() {
if (!intervalsKnown) {
// intervalsKnown -> false when handleModelChanged event occurs in super.
wrapSetupIntervals();
setupSufficientStatistics();
intervalsKnown = true;
}
// Matrix operations taken from block update sampler to calculate data likelihood and field prior
double currentLike = 0;
double[] currentGamma = popSizeParameter.getParameterValues();
for (int i = 0; i < fieldLength; i++) {
currentLike += -numCoalEvents[i] * currentGamma[i] + ploidySums[i] - sufficientStatistics[i] * Math.exp(-currentGamma[i]);
}
return currentLike;
}
public double getLogLikelihood() {
if (!likelihoodKnown) {
logLikelihood = calculateLogCoalescentLikelihood();
logFieldLikelihood = skygridHelper.getLogFieldLikelihood();
likelihoodKnown = true;
}
return logLikelihood + logFieldLikelihood;
}
protected void setupGMRFWeights() {
//setupSufficientStatistics();
//Set up the weight Matrix
double[] offdiag = new double[fieldLength - 1];
double[] diag = new double[fieldLength];
diagonalValue = 2;
//First set up the offdiagonal entries;
for (int i = 0; i < fieldLength - 1; i++) {
offdiag[i] = -1;
}
//Then set up the diagonal entries;
for (int i = 1; i < fieldLength - 1; i++) {
// diag[i] = -(offdiag[i] + offdiag[i - 1]);
diag[i] = diagonalValue;
}
//Take care of the endpoints
//diag[0] = -offdiag[0];
//diag[fieldLength - 1] = -offdiag[fieldLength - 2];
diag[0] = diagonalValue - 1.0;
diag[fieldLength - 1] = diagonalValue - 1.0;
weightMatrix = new SymmTridiagMatrix(diag, offdiag);
}
protected double getFieldScalar() {
return 1.0;
}
protected void setupGMRFWeightsForMissingCov() {
if(firstObservedIndex != null){
weightMatricesForMissingCovRecent = new ArrayList<SymmTridiagMatrix>();
for (int i = 0; i < covPrecParametersRecent.size(); i++) {
double[] offdiagRec = new double[firstObservedIndex[i] - 2];
double[] diagRec = new double[firstObservedIndex[i] - 1];
for (int k = 0; k < firstObservedIndex[i] - 2; k++) {
offdiagRec[k] = -1;
}
for (int k = 1; k < firstObservedIndex[i] - 1; k++) {
diagRec[k] = 2.0;
}
diagRec[0] = 1.0;
weightMatricesForMissingCovRecent.add(i, new SymmTridiagMatrix(diagRec, offdiagRec));
}
}
if(lastObservedIndex != null) {
weightMatricesForMissingCovDistant = new ArrayList<SymmTridiagMatrix>();
for (int i = 0; i < covPrecParametersDistant.size(); i++) {
double[] offdiag = new double[fieldLength - lastObservedIndex[i] - 1];
double[] diag = new double[fieldLength - lastObservedIndex[i]];
//First set up the offdiagonal entries;
for (int k = 0; k < fieldLength - lastObservedIndex[i] - 1; k++) {
offdiag[k] = -1;
}
//Then set up the diagonal entries;
for (int k = 0; k < fieldLength - lastObservedIndex[i] - 1; k++) {
// diag[i] = -(offdiag[i] + offdiag[i - 1]);
diag[k] = 2.0;
}
//Take care of the endpoint
diag[fieldLength - lastObservedIndex[i] - 1] = 1.0;
weightMatricesForMissingCovDistant.add(i, new SymmTridiagMatrix(diag, offdiag));
}
}
}
public SymmTridiagMatrix getScaledWeightMatrixForMissingCovRecent(double precision, int covIndex, int firstObs) {
SymmTridiagMatrix a = weightMatricesForMissingCovRecent.get(covIndex).copy();
for (int i = 0; i < a.numRows() - 1; i++) {
a.set(i, i, a.get(i, i) * precision);
a.set(i + 1, i, a.get(i + 1, i) * precision);
}
a.set(firstObs - 2, firstObs - 2,
a.get(firstObs - 2, firstObs - 2) * precision);
return a;
}
public SymmTridiagMatrix getScaledWeightMatrixForMissingCovDistant(double precision, int covIndex, int lastObs) {
SymmTridiagMatrix a = weightMatricesForMissingCovDistant.get(covIndex).copy();
for (int i = 0; i < a.numRows() - 1; i++) {
a.set(i, i, a.get(i, i) * precision);
a.set(i + 1, i, a.get(i + 1, i) * precision);
}
a.set(fieldLength - lastObs - 1, fieldLength - lastObs - 1,
a.get(fieldLength - lastObs - 1, fieldLength - lastObs - 1) * precision);
return a;
}
private List<Tree> treeList;
private List<TreeIntervals> intervalsList;
public int nLoci() {
return treeList.size();
}
public Tree getTree(int nt) {
return treeList.get(nt);
}
public TreeIntervals getTreeIntervals(int nt) {
return intervalsList.get(nt);
}
public double getPopulationFactor(int nt) {
return ploidyFactors.getParameterValue(nt);
}
public List<Parameter> getBetaListParameter() {
return beta;
}
public List<MatrixParameter> getCovariates() {
return covariates;
}
public void storeTheState() {
for (TreeIntervals intervals : intervalsList) {
intervals.storeState();
}
}
public void restoreTheState() {
for (TreeIntervals intervals : intervalsList) {
intervals.restoreState();
}
}
protected void storeState() {
// System.arraycopy(numCoalEvents, 0, storedNumCoalEvents, 0, numCoalEvents.length);
super.storeState();
System.arraycopy(numCoalEvents, 0, storedNumCoalEvents, 0, numCoalEvents.length);
// storedPrecMatrix = precMatrix.copy();
System.arraycopy(ploidySums, 0, storedPloidySums, 0, ploidySums.length);
}
protected void restoreState() {
super.restoreState();
// Swap pointers
double[] tmp = numCoalEvents;
numCoalEvents = storedNumCoalEvents;
storedNumCoalEvents = tmp;
double[] tmp2 = ploidySums;
ploidySums = storedPloidySums;
storedPloidySums = tmp2;
}
// Implementation of GradientWrtParameterProvider
// Need to update to include beta and log-transformed precision parameter
public Parameter getParameter() {
return popSizeParameter;
}
public int getDimension() {
return popSizeParameter.getDimension();
}
public Likelihood getLikelihood() {
return this;
}
public double[] getGradientLogDensity() {
double [] gradLogDens = new double [popSizeParameter.getSize()];
double[] currentGamma = popSizeParameter.getParameterValues();
int popSizeDim = popSizeParameter.getSize();
// handle covariate case later
gradLogDens[0] = precisionParameter.getParameterValue(0)*(currentGamma[0]-currentGamma[1])
+ numCoalEvents[0] - sufficientStatistics[0]*Math.exp(-currentGamma[0]);
gradLogDens[popSizeDim-1] = precisionParameter.getParameterValue(0)*(currentGamma[popSizeDim-1]-currentGamma[popSizeDim-2])
+ numCoalEvents[popSizeDim-1] - sufficientStatistics[popSizeDim-1]*Math.exp(-currentGamma[popSizeDim-1]);
if(beta != null) {
for (int k = 0; k < beta.size(); k++) {
Parameter b = beta.get(k);
MatrixParameter covariate = covariates.get(k);
gradLogDens[0] = gradLogDens[0] - precisionParameter.getParameterValue(0) * covariate.getParameterValue(0, 0) * b.getParameterValue(0)
+ precisionParameter.getParameterValue(0) * covariate.getParameterValue(0, 1) * b.getParameterValue(0);
gradLogDens[popSizeDim - 1] = gradLogDens[popSizeDim - 1] - precisionParameter.getParameterValue(0) * covariate.getParameterValue(0, popSizeDim - 1) * b.getParameterValue(0)
+ precisionParameter.getParameterValue(0) * covariate.getParameterValue(0, popSizeDim - 2) * b.getParameterValue(0);
}
}
for(int i = 1; i<(popSizeDim-1); i++){
gradLogDens[i] = precisionParameter.getParameterValue(0)*(-currentGamma[i-1] + 2*currentGamma[i] - currentGamma[i+1])
+ numCoalEvents[i] - sufficientStatistics[i]*Math.exp(-currentGamma[i]);
if(beta != null) {
for (int k = 0; k < beta.size(); k++) {
Parameter bk = beta.get(k);
MatrixParameter covk = covariates.get(k);
gradLogDens[i] = gradLogDens[i] + precisionParameter.getParameterValue(0) * covk.getParameterValue(0, i - 1) * bk.getParameterValue(0)
- 2 * precisionParameter.getParameterValue(0) * covk.getParameterValue(0, i) * bk.getParameterValue(0)
+ precisionParameter.getParameterValue(0) * covk.getParameterValue(0, i + 1) * bk.getParameterValue(0);
}
}
}
return gradLogDens;
}
/*public int getCoalescentIntervalLineageCount(int i) {
return 0;
}
public IntervalType getCoalescentIntervalType(int i) {
return null;
}*/
class SkygridHelper {
public SkygridHelper() {
}
protected void updateGammaWithCovariates(DenseVector currentGamma) {
// Do nothing
}
protected double handleMissingValues() {
return 0.0;
}
public double getLogFieldLikelihood() {
if (!intervalsKnown) {
//intervalsKnown -> false when handleModelChanged event occurs in super.
wrapSetupIntervals();
setupSufficientStatistics();
intervalsKnown = true;
}
DenseVector diagonal1 = new DenseVector(fieldLength);
DenseVector currentGamma = new DenseVector(popSizeParameter.getParameterValues());
updateGammaWithCovariates(currentGamma);
double currentLike = handleMissingValues();
SymmTridiagMatrix currentQ = getScaledWeightMatrix(precisionParameter.getParameterValue(0), lambdaParameter.getParameterValue(0));
currentQ.mult(currentGamma, diagonal1);
currentLike += 0.5 * (fieldLength - 1) * Math.log(precisionParameter.getParameterValue(0)) - 0.5 * currentGamma.dot(diagonal1);
if (lambdaParameter.getParameterValue(0) == 1) {
currentLike -= (fieldLength - 1) / 2.0 * LOG_TWO_TIMES_PI;
} else {
currentLike -= fieldLength / 2.0 * LOG_TWO_TIMES_PI;
}
return currentLike;
}
}
class SkygridCovariateHelper extends SkygridHelper {
public SkygridCovariateHelper() {
}
@Override
protected void updateGammaWithCovariates(DenseVector currentGamma) {
// Handle betaParameter / designMatrix
if (NEW_APPROACH) {
final int N = currentGamma.size();
double[] update = new double[N];
if (dMatrix != null) {
final int K = dMatrix.getColumnDimension();
if (N != dMatrix.getRowDimension()) {
throw new RuntimeException("Incorrect covariate dimensions (" + N + " != "
+ dMatrix.getRowDimension() + ")");
}
for (int i = 0; i < N; ++i) {
for (int j = 0; j < K; ++j) {
update[i] += dMatrix.getParameterValue(i, j) * betaParameter.getParameterValue(j);
}
}
}
if (covariates != null) {
if (beta.size() != covariates.size()) {
throw new RuntimeException("beta.size(" + beta.size() + ") != covariates.size(" + covariates.size() + ")");
}
for (int k = 0; k < beta.size(); ++k) {
Parameter b = beta.get(k);
final int J = b.getDimension();
MatrixParameter covariate = covariates.get(k);
if ((J != covariate.getRowDimension()) ||
(N != covariate.getColumnDimension())) { // Note: XML current has covariates transposed
throw new RuntimeException("Incorrect dimensions in " + covariate.getId() + " (r=" + covariate.getRowDimension() +
",c=" + covariate.getColumnDimension()+ ")");
}
for (int i = 0; i < N; ++i) {
for (int j = 0; j < J; ++j) {
update[i] += covariate.getParameterValue(j, i) * b.getParameterValue(j);
}
}
}
}
for (int i = 0; i < N; ++i) {
currentGamma.set(i, currentGamma.get(i) - update[i]);
}
} else {
DenseVector currentBeta = new DenseVector(beta.size());
for (int i = 0; i < beta.size(); i++) {
currentBeta.set(i, beta.get(i).getParameterValue(0));
}
//int numMissing = fieldLength - lastObservedIndex;
//DenseVector tempVectCov = new DenseVector(numMissing);
//System.err.println("covariates.size(): " + covariates.size());
//System.err.println("covariates.get(0).getColumnDimension: " + covariates.get(0).getColumnDimension());
//System.err.println("covariates.get(0).getRowDimension: " + covariates.get(0).getRowDimension());
for (int i = 0; i < covariates.size(); i++) {
for (int j = 0; j < covariates.get(i).getColumnDimension(); j++) {
// System.err.println("j: " + j);
// System.err.println("covariates.get(i).getParameterValue(0,j): " + covariates.get(i).getParameterValue(0,j));
currentGamma.set(j, currentGamma.get(j) - covariates.get(i).getParameterValue(0, j) * currentBeta.get(i));
}
}
}
}
}
private static final boolean NEW_APPROACH = true;
class SkygridMissingCovariateHelper extends SkygridCovariateHelper {
public SkygridMissingCovariateHelper() {
}
@Override
protected double handleMissingValues() {
int numMissing;
DenseVector tempVectMissingCov;
SymmTridiagMatrix missingCovQ;
DenseVector tempVectMissingCov2;
int numMissingRecent;
double currentLike = 0.0;
if(lastObservedIndex != null) {
for (int i = 0; i < covPrecParametersDistant.size(); i++) {
numMissing = fieldLength - lastObservedIndex[i];
tempVectMissingCov = new DenseVector(numMissing);
tempVectMissingCov2 = new DenseVector(numMissing);
missingCovQ = getScaledWeightMatrixForMissingCovDistant(covPrecParametersDistant.get(i).getParameterValue(0), i,
lastObservedIndex[i]);
for (int j = 0; j < numMissing; j++) {
tempVectMissingCov.set(j, covariates.get(distIndices[i] - 1).getParameterValue(0, lastObservedIndex[i] + j) -
covariates.get(distIndices[i] - 1).getParameterValue(0, lastObservedIndex[i] - 1));
}
missingCovQ.mult(tempVectMissingCov, tempVectMissingCov2);
currentLike += 0.5 * (numMissing) * Math.log(covPrecParametersDistant.get(i).getParameterValue(0))
- 0.5 * tempVectMissingCov.dot(tempVectMissingCov2);
}
}
if(firstObservedIndex != null){
for (int i = 0; i < covPrecParametersRecent.size(); i++) {
numMissingRecent = firstObservedIndex[i]-1;
tempVectMissingCov = new DenseVector(numMissingRecent);
tempVectMissingCov2 = new DenseVector(numMissingRecent);
missingCovQ = getScaledWeightMatrixForMissingCovRecent(covPrecParametersRecent.get(i).getParameterValue(0), i,
firstObservedIndex[i]);
for (int j = 0; j < numMissingRecent; j++) {
tempVectMissingCov.set(j, covariates.get(recIndices[i] - 1).getParameterValue(0, j) -
covariates.get(recIndices[i] - 1).getParameterValue(0, firstObservedIndex[i]-1));
}
missingCovQ.mult(tempVectMissingCov, tempVectMissingCov2);
currentLike += 0.5 * (numMissingRecent) * Math.log(covPrecParametersRecent.get(i).getParameterValue(0))
- 0.5 * tempVectMissingCov.dot(tempVectMissingCov2);
}
}
return currentLike;
}
}
@Override
public Citation.Category getCategory() {
return Citation.Category.TREE_PRIORS;
}
@Override
public String getDescription() {
return "Skyride coalescent";
}
@Override
public List<Citation> getCitations() {
return Arrays.asList(new Citation(
new Author[]{
new Author("MS", "Gill"),
new Author("P", "Lemey"),
new Author("NR", "Faria"),
new Author("A", "Rambaut"),
new Author("B", "Shapiro"),
new Author("MA", "Suchard")
},
"Improving Bayesian population dynamics inference: a coalescent-based model for multiple loci",
2013,
"Mol Biol Evol",
30, 713, 724
),
new Citation(
new Author[]{
new Author("VN", "Minin"),
new Author("EW", "Bloomquist"),
new Author("MA", "Suchard")
},
"Smooth skyride through a rough skyline: Bayesian coalescent-based inference of population dynamics",
2008,
"Mol Biol Evol",
25, 1459, 1471,
"10.1093/molbev/msn090"
)
);
}
}
|
package dr.evomodel.coalescent;
import com.sun.xml.internal.messaging.saaj.packaging.mime.internet.ParameterList;
import dr.evolution.coalescent.IntervalType;
import dr.evolution.coalescent.TreeIntervals;
import dr.evolution.tree.Tree;
import dr.evomodel.tree.TreeModel;
import dr.evomodelxml.coalescent.GMRFSkyrideLikelihoodParser;
import dr.inference.model.MatrixParameter;
import dr.inference.model.Model;
import dr.inference.model.Parameter;
import no.uib.cipr.matrix.DenseVector;
import no.uib.cipr.matrix.SymmTridiagMatrix;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* @author Mandev Gill
* @author Marc A. Suchard
*/
public class GMRFMultilocusSkyrideLikelihood extends GMRFSkyrideLikelihood implements MultiLociTreeSet {
private double cutOff;
private int numGridPoints;
protected int oldFieldLength;
// number of coalescent events which occur in an interval with constant population size
protected double[] numCoalEvents;
protected double[] storedNumCoalEvents;
protected double[] gridPoints;
protected double theLastTime;
protected double diagonalValue;
// sortedPoints[i][0] is the time of the i-th grid point or sampling or coalescent event
// sortedPoints[i][1] is 0 if the i-th point is a grid point, 1 if it's a sampling point, and 2 if it's a coalescent point
// sortedPoints[i][2] is the number of lineages present in the interval starting at time sortedPoints[i][0]
protected Parameter phiParameter;
protected Parameter ploidyFactors;
protected double[] ploidySums;
protected double[] storedPloidySums;
protected SymmTridiagMatrix precMatrix;
protected SymmTridiagMatrix storedPrecMatrix;
private SkygridHelper skygridHelper;
protected List<Parameter> missingCov;
protected List<MatrixParameter> covariates;
protected List<Parameter> beta;
protected List<Parameter> covPrecParameters;
protected List<SymmTridiagMatrix> weightMatricesForMissingCov;
protected int[] lastObservedIndex;
public GMRFMultilocusSkyrideLikelihood(List<Tree> treeList,
Parameter popParameter,
Parameter groupParameter,
Parameter precParameter,
Parameter lambda,
Parameter beta,
MatrixParameter dMatrix,
boolean timeAwareSmoothing,
double cutOff,
int numGridPoints,
Parameter phi,
Parameter ploidyFactorsParameter) {
super(GMRFSkyrideLikelihoodParser.SKYLINE_LIKELIHOOD);
this.popSizeParameter = popParameter;
this.groupSizeParameter = groupParameter;
this.precisionParameter = precParameter;
this.lambdaParameter = lambda;
this.betaParameter = beta;
this.dMatrix = dMatrix;
this.timeAwareSmoothing = timeAwareSmoothing;
this.cutOff = cutOff;
this.numGridPoints = numGridPoints;
this.phiParameter = phi;
this.ploidyFactors = ploidyFactorsParameter;
setupGridPoints();
addVariable(popSizeParameter);
addVariable(precisionParameter);
addVariable(lambdaParameter);
if (betaParameter != null) {
addVariable(betaParameter);
skygridHelper = new SkygridCovariateHelper();
}else{
skygridHelper = new SkygridHelper();
}
if (phiParameter != null) {
addVariable(phiParameter);
}
addVariable(ploidyFactors);
setTree(treeList);
int correctFieldLength = getCorrectFieldLength();
if (popSizeParameter.getDimension() <= 1) {
// popSize dimension hasn't been set yet, set it here:
popSizeParameter.setDimension(correctFieldLength);
}
fieldLength = popSizeParameter.getDimension();
if (correctFieldLength != fieldLength) {
throw new IllegalArgumentException("Population size parameter should have length " + correctFieldLength);
}
oldFieldLength = getCorrectOldFieldLength();
if (ploidyFactors.getDimension() != treeList.size()) {
throw new IllegalArgumentException("Ploidy factors parameter should have length " + treeList.size());
}
// Field length must be set by this point
wrapSetupIntervals();
coalescentIntervals = new double[oldFieldLength];
storedCoalescentIntervals = new double[oldFieldLength];
sufficientStatistics = new double[fieldLength];
storedSufficientStatistics = new double[fieldLength];
numCoalEvents = new double[fieldLength];
storedNumCoalEvents = new double[fieldLength];
ploidySums = new double[fieldLength];
storedPloidySums = new double[fieldLength];
setupGMRFWeights();
setupSufficientStatistics();
addStatistic(new DeltaStatistic());
initializationReport();
/* Force all entries in groupSizeParameter = 1 for compatibility with Tracer */
if (groupSizeParameter != null) {
for (int i = 0; i < groupSizeParameter.getDimension(); i++)
groupSizeParameter.setParameterValue(i, 1.0);
}
}
//rewrite this constructor without duplicating so much code
public GMRFMultilocusSkyrideLikelihood(List<Tree> treeList,
Parameter popParameter,
Parameter groupParameter,
Parameter precParameter,
Parameter lambda,
// List<Parameter> beta,
MatrixParameter dMatrix,
boolean timeAwareSmoothing,
Parameter specGridPoints,
List<MatrixParameter> covariates,
Parameter ploidyFactorsParameter,
List<Parameter> lastObservedIndexParameter,
List<Parameter> covPrecParameters,
List<Parameter> beta) {
super(GMRFSkyrideLikelihoodParser.SKYLINE_LIKELIHOOD);
this.gridPoints = specGridPoints.getParameterValues();
this.numGridPoints = gridPoints.length;
this.cutOff = gridPoints[numGridPoints - 1];
if(lastObservedIndexParameter != null){
lastObservedIndex = new int[lastObservedIndexParameter.size()];
for(int i=0; i < lastObservedIndexParameter.size(); i++) {
this.lastObservedIndex[i] = (int) lastObservedIndexParameter.get(i).getParameterValue(0);
}
}
/*else{
for(int i=0; i < beta.getDimension(); i++) {
this.lastObservedIndex[i] = popParameter.getDimension();
}
}*/
this.popSizeParameter = popParameter;
this.groupSizeParameter = groupParameter;
this.precisionParameter = precParameter;
this.lambdaParameter = lambda;
this.beta = beta;
this.dMatrix = dMatrix;
this.timeAwareSmoothing = timeAwareSmoothing;
this.ploidyFactors = ploidyFactorsParameter;
this.covariates = covariates;
if (covariates != null) {
for (MatrixParameter cov : covariates){
addVariable(cov);
}
}
this.covPrecParameters = covPrecParameters;
if (covPrecParameters != null) {
for (Parameter covPrec : covPrecParameters){
addVariable(covPrec);
}
}
addVariable(popSizeParameter);
addVariable(precisionParameter);
addVariable(lambdaParameter);
addVariable(ploidyFactors);
setTree(treeList);
int correctFieldLength = getCorrectFieldLength();
if (popSizeParameter.getDimension() <= 1) {
// popSize dimension hasn't been set yet, set it here:
popSizeParameter.setDimension(correctFieldLength);
}
fieldLength = popSizeParameter.getDimension();
if (correctFieldLength != fieldLength) {
throw new IllegalArgumentException("Population size parameter should have length " + correctFieldLength);
}
oldFieldLength = getCorrectOldFieldLength();
if (ploidyFactors.getDimension() != treeList.size()) {
throw new IllegalArgumentException("Ploidy factor parameter should have length " + treeList.size());
}
// Field length must be set by this point
if (beta != null) {
for (Parameter betaParam : beta) {
addVariable(betaParam);
}
if(lastObservedIndexParameter != null){
setupGMRFWeightsForMissingCov();
skygridHelper = new SkygridMissingCovariateHelper();
}else {
skygridHelper = new SkygridCovariateHelper();
}
}else{
skygridHelper = new SkygridHelper();
}
wrapSetupIntervals();
coalescentIntervals = new double[oldFieldLength];
storedCoalescentIntervals = new double[oldFieldLength];
sufficientStatistics = new double[fieldLength];
storedSufficientStatistics = new double[fieldLength];
numCoalEvents = new double[fieldLength];
storedNumCoalEvents = new double[fieldLength];
ploidySums = new double[fieldLength];
storedPloidySums = new double[fieldLength];
setupGMRFWeights();
addStatistic(new DeltaStatistic());
initializationReport();
}
protected void setTree(List<Tree> treeList) {
treesSet = this;
this.treeList = treeList;
makeTreeIntervalList(treeList, true);
numTrees = treeList.size();
}
private void makeTreeIntervalList(List<Tree> treeList, boolean add) {
if (intervalsList == null) {
intervalsList = new ArrayList<TreeIntervals>();
} else {
intervalsList.clear();
}
for (Tree tree : treeList) {
intervalsList.add(new TreeIntervals(tree));
if (add && tree instanceof TreeModel) {
addModel((TreeModel) tree);
}
}
}
protected int getCorrectFieldLength() {
return numGridPoints + 1;
}
protected int getCorrectOldFieldLength() {
int tips = 0;
for (Tree tree : treeList) {
tips += tree.getExternalNodeCount();
}
return tips - treeList.size();
}
protected void handleModelChangedEvent(Model model, Object object, int index) {
if (model instanceof TreeModel) {
TreeModel treeModel = (TreeModel) model;
int tn = treeList.indexOf(treeModel);
if (tn >= 0) {
// intervalsList.get(tn).setIntervalsUnknown(); // TODO Why is this slower (?) than remaking whole list?
makeTreeIntervalList(treeList, false);
intervalsKnown = false;
likelihoodKnown = false;
} else {
throw new RuntimeException("Unknown tree modified in GMRFMultilocusSkyrideLikelihood");
}
} else {
throw new RuntimeException("Unknown object modified in GMRFMultilocusSkyrideLikelihood");
}
}
public void initializationReport() {
System.out.println("Creating a GMRF smoothed skyride model for multiple loci:");
System.out.println("\tPopulation sizes: " + popSizeParameter.getDimension());
System.out.println("\tIf you publish results using this model, please reference: ");
System.out.println("\t\tMinin, Bloomquist and Suchard (2008) Molecular Biology and Evolution, 25, 1459-1471, and");
System.out.println("\t\tGill, Lemey, Faria, Rambaut, Shapiro and Suchard (2013) Molecular Biology and Evolution, 30, 713-724.");
}
public void wrapSetupIntervals() {
// Do nothing
}
int numTrees;
protected void setupGridPoints() {
if (gridPoints == null) {
gridPoints = new double[numGridPoints];
} else {
Arrays.fill(gridPoints, 0);
}
for (int pt = 0; pt < numGridPoints; pt++) {
gridPoints[pt] = (pt + 1) * (cutOff / numGridPoints);
}
}
protected void setupSufficientStatistics() {
//numCoalEvents = new double[fieldLength];
//sufficientStatistics = new double[fieldLength];
Arrays.fill(numCoalEvents, 0);
Arrays.fill(sufficientStatistics, 0);
Arrays.fill(ploidySums, 0);
//index of smallest grid point greater than at least one sampling/coalescent time in current tree
int minGridIndex;
//index of greatest grid point less than at least one sampling/coalescent time in current tree
int maxGridIndex;
int numLineages;
int currentGridIndex;
int currentTimeIndex;
double currentTime;
double nextTime;
double ploidyFactor;
//time of last coalescent event in tree
double lastCoalescentTime;
for (int i = 0; i < numTrees; i++) {
ploidyFactor = 1 / getPopulationFactor(i);
currentTimeIndex = 0;
currentTime = intervalsList.get(i).getIntervalTime(currentTimeIndex);
nextTime = intervalsList.get(i).getIntervalTime(currentTimeIndex + 1);
while (nextTime <= currentTime) {
currentTimeIndex++;
currentTime = intervalsList.get(i).getIntervalTime(currentTimeIndex);
nextTime = intervalsList.get(i).getIntervalTime(currentTimeIndex + 1);
}
numLineages = intervalsList.get(i).getLineageCount(currentTimeIndex + 1);
minGridIndex = 0;
while (minGridIndex < numGridPoints && gridPoints[minGridIndex] <= currentTime) {
//while (gridPoints[minGridIndex] <= currentTime) {
minGridIndex++;
}
currentGridIndex = minGridIndex;
lastCoalescentTime = currentTime + intervalsList.get(i).getTotalDuration();
theLastTime = lastCoalescentTime;
maxGridIndex = numGridPoints - 1;
while ((maxGridIndex >= 0) && (gridPoints[maxGridIndex] >= lastCoalescentTime)) {
maxGridIndex = maxGridIndex - 1;
}
if (maxGridIndex >= 0 && minGridIndex < numGridPoints) {
//if (maxGridIndex >= 0) {
//from likelihood of interval between first sampling time and gridPoints[minGridIndex]
while (nextTime < gridPoints[currentGridIndex]) {
//check to see if interval ends with coalescent event
if (intervalsList.get(i).getCoalescentEvents(currentTimeIndex + 1) > 0) {
numCoalEvents[currentGridIndex]++;
}
sufficientStatistics[currentGridIndex] = sufficientStatistics[currentGridIndex] + (nextTime - currentTime) * numLineages * (numLineages - 1) * 0.5 * ploidyFactor;
currentTime = nextTime;
currentTimeIndex++;
nextTime = intervalsList.get(i).getIntervalTime(currentTimeIndex + 1);
while (nextTime <= currentTime) {
currentTimeIndex++;
currentTime = intervalsList.get(i).getIntervalTime(currentTimeIndex);
nextTime = intervalsList.get(i).getIntervalTime(currentTimeIndex + 1);
}
numLineages = intervalsList.get(i).getLineageCount(currentTimeIndex + 1);
}
sufficientStatistics[currentGridIndex] = sufficientStatistics[currentGridIndex] + (gridPoints[currentGridIndex] - currentTime) * numLineages * (numLineages - 1) * 0.5 * ploidyFactor;
ploidySums[currentGridIndex] = ploidySums[currentGridIndex] + Math.log(ploidyFactor) * numCoalEvents[currentGridIndex];
currentGridIndex++;
//from likelihood of intervals between gridPoints[minGridIndex] and gridPoints[maxGridIndex]
while (currentGridIndex <= maxGridIndex) {
if (nextTime >= gridPoints[currentGridIndex]) {
sufficientStatistics[currentGridIndex] = sufficientStatistics[currentGridIndex] + (gridPoints[currentGridIndex] - gridPoints[currentGridIndex - 1]) * numLineages * (numLineages - 1) * 0.5 * ploidyFactor;
ploidySums[currentGridIndex] = ploidySums[currentGridIndex] + Math.log(ploidyFactor) * numCoalEvents[currentGridIndex];
currentGridIndex++;
} else {
sufficientStatistics[currentGridIndex] = sufficientStatistics[currentGridIndex] + (nextTime - gridPoints[currentGridIndex - 1]) * numLineages * (numLineages - 1) * 0.5 * ploidyFactor;
//check to see if interval ends with coalescent event
if (intervalsList.get(i).getCoalescentEvents(currentTimeIndex + 1) > 0) {
numCoalEvents[currentGridIndex]++;
}
currentTime = nextTime;
currentTimeIndex++;
nextTime = intervalsList.get(i).getIntervalTime(currentTimeIndex + 1);
while (nextTime <= currentTime) {
currentTimeIndex++;
currentTime = intervalsList.get(i).getIntervalTime(currentTimeIndex);
nextTime = intervalsList.get(i).getIntervalTime(currentTimeIndex + 1);
}
numLineages = intervalsList.get(i).getLineageCount(currentTimeIndex + 1);
while (nextTime < gridPoints[currentGridIndex]) {
//check to see if interval is coalescent interval or sampling interval
if (intervalsList.get(i).getCoalescentEvents(currentTimeIndex + 1) > 0) {
numCoalEvents[currentGridIndex]++;
}
sufficientStatistics[currentGridIndex] = sufficientStatistics[currentGridIndex] + (nextTime - currentTime) * numLineages * (numLineages - 1) * 0.5 * ploidyFactor;
currentTime = nextTime;
currentTimeIndex++;
nextTime = intervalsList.get(i).getIntervalTime(currentTimeIndex + 1);
while (nextTime <= currentTime) {
currentTimeIndex++;
currentTime = intervalsList.get(i).getIntervalTime(currentTimeIndex);
nextTime = intervalsList.get(i).getIntervalTime(currentTimeIndex + 1);
}
numLineages = intervalsList.get(i).getLineageCount(currentTimeIndex + 1);
}
sufficientStatistics[currentGridIndex] = sufficientStatistics[currentGridIndex] + (gridPoints[currentGridIndex] - currentTime) * numLineages * (numLineages - 1) * 0.5 * ploidyFactor;
ploidySums[currentGridIndex] = ploidySums[currentGridIndex] + Math.log(ploidyFactor) * numCoalEvents[currentGridIndex];
currentGridIndex++;
}
}
//from likelihood of interval between gridPoints[maxGridIndex] and lastCoalescentTime
sufficientStatistics[currentGridIndex] = sufficientStatistics[currentGridIndex] + (nextTime - gridPoints[currentGridIndex - 1]) * numLineages * (numLineages - 1) * 0.5 * ploidyFactor;
//check to see if interval ends with coalescent event
if (intervalsList.get(i).getCoalescentEvents(currentTimeIndex + 1) > 0) {
numCoalEvents[currentGridIndex]++;
}
currentTime = nextTime;
currentTimeIndex++;
while ((currentTimeIndex + 1) < intervalsList.get(i).getIntervalCount()) {
// currentTime = nextTime;
// currentTimeIndex++;
nextTime = intervalsList.get(i).getIntervalTime(currentTimeIndex + 1);
while (nextTime <= currentTime) {
currentTimeIndex++;
currentTime = intervalsList.get(i).getIntervalTime(currentTimeIndex);
nextTime = intervalsList.get(i).getIntervalTime(currentTimeIndex + 1);
}
numLineages = intervalsList.get(i).getLineageCount(currentTimeIndex + 1);
//check to see if interval is coalescent interval or sampling interval
if (intervalsList.get(i).getCoalescentEvents(currentTimeIndex + 1) > 0) {
numCoalEvents[currentGridIndex]++;
}
sufficientStatistics[currentGridIndex] = sufficientStatistics[currentGridIndex] + (nextTime - currentTime) * numLineages * (numLineages - 1) * 0.5 * ploidyFactor;
currentTime = nextTime;
currentTimeIndex++;
}
// if tree does not overlap with any gridpoints/change-points, in which case logpopsize is constant
} else {
while ((currentTimeIndex + 1) < intervalsList.get(i).getIntervalCount()) {
//check to see if interval is coalescent interval or sampling interval
if (intervalsList.get(i).getCoalescentEvents(currentTimeIndex + 1) > 0) {
numCoalEvents[currentGridIndex]++;
}
sufficientStatistics[currentGridIndex] = sufficientStatistics[currentGridIndex] + (nextTime - currentTime) * numLineages * (numLineages - 1) * 0.5 * ploidyFactor;
currentTime = nextTime;
currentTimeIndex++;
if ((currentTimeIndex + 1) < intervalsList.get(i).getIntervalCount()) {
nextTime = intervalsList.get(i).getIntervalTime(currentTimeIndex + 1);
while (nextTime <= currentTime) {
currentTimeIndex++;
currentTime = intervalsList.get(i).getIntervalTime(currentTimeIndex);
nextTime = intervalsList.get(i).getIntervalTime(currentTimeIndex + 1);
}
numLineages = intervalsList.get(i).getLineageCount(currentTimeIndex + 1);
}
}
ploidySums[currentGridIndex] = ploidySums[currentGridIndex] + Math.log(ploidyFactor) * numCoalEvents[currentGridIndex];
}
}
}
public double[] getNumCoalEvents() {
return numCoalEvents;
}
protected double calculateLogCoalescentLikelihood() {
if (!intervalsKnown) {
// intervalsKnown -> false when handleModelChanged event occurs in super.
wrapSetupIntervals();
setupSufficientStatistics();
intervalsKnown = true;
}
// Matrix operations taken from block update sampler to calculate data likelihood and field prior
double currentLike = 0;
double[] currentGamma = popSizeParameter.getParameterValues();
for (int i = 0; i < fieldLength; i++) {
currentLike += -numCoalEvents[i] * currentGamma[i] + ploidySums[i] - sufficientStatistics[i] * Math.exp(-currentGamma[i]);
}
return currentLike;
}
protected double calculateLogFieldLikelihood() {
if (!intervalsKnown) {
//intervalsKnown -> false when handleModelChanged event occurs in super.
wrapSetupIntervals();
setupSufficientStatistics();
intervalsKnown = true;
}
double currentLike = 0;
DenseVector diagonal1 = new DenseVector(fieldLength);
DenseVector currentGamma = new DenseVector(popSizeParameter.getParameterValues());
SymmTridiagMatrix currentQ = getScaledWeightMatrix(precisionParameter.getParameterValue(0), lambdaParameter.getParameterValue(0));
currentQ.mult(currentGamma, diagonal1);
// currentLike += 0.5 * logGeneralizedDeterminant(currentQ) - 0.5 * currentGamma.dot(diagonal1);
currentLike += 0.5 * (fieldLength - 1) * Math.log(precisionParameter.getParameterValue(0)) - 0.5 * currentGamma.dot(diagonal1);
if (lambdaParameter.getParameterValue(0) == 1) {
currentLike -= (fieldLength - 1) / 2.0 * LOG_TWO_TIMES_PI;
} else {
currentLike -= fieldLength / 2.0 * LOG_TWO_TIMES_PI;
}
return currentLike;
}
public double getLogLikelihood() {
if (!likelihoodKnown) {
logLikelihood = calculateLogCoalescentLikelihood();
//logFieldLikelihood = calculateLogFieldLikelihood();
logFieldLikelihood = skygridHelper.getLogFieldLikelihood();
likelihoodKnown = true;
}
return logLikelihood + logFieldLikelihood;
}
protected void setupGMRFWeights() {
//setupSufficientStatistics();
//Set up the weight Matrix
double[] offdiag = new double[fieldLength - 1];
double[] diag = new double[fieldLength];
diagonalValue = 2;
//First set up the offdiagonal entries;
for (int i = 0; i < fieldLength - 1; i++) {
offdiag[i] = -1;
}
//Then set up the diagonal entries;
for (int i = 1; i < fieldLength - 1; i++) {
// diag[i] = -(offdiag[i] + offdiag[i - 1]);
diag[i] = diagonalValue;
}
//Take care of the endpoints
//diag[0] = -offdiag[0];
//diag[fieldLength - 1] = -offdiag[fieldLength - 2];
diag[0] = diagonalValue - 1.0;
diag[fieldLength - 1] = diagonalValue - 1.0;
weightMatrix = new SymmTridiagMatrix(diag, offdiag);
}
protected double getFieldScalar() {
return 1.0;
}
protected void setupGMRFWeightsForMissingCov() {
//System.err.println("fieldLength: " + fieldLength);
// System.err.println("lastObservedIndex: " + lastObservedIndex);
//Set up the weight Matrix
weightMatricesForMissingCov = new ArrayList<SymmTridiagMatrix>();
for (int i = 0; i < covPrecParameters.size(); i++){
double[] offdiag = new double[fieldLength - lastObservedIndex[i] - 1];
double[] diag = new double[fieldLength - lastObservedIndex[i]];
//First set up the offdiagonal entries;
for (int k = 0; k < fieldLength - lastObservedIndex[i] - 1; k++) {
offdiag[k] = -1;
}
//Then set up the diagonal entries;
for (int k = 0; k < fieldLength - lastObservedIndex[i] - 1; k++) {
// diag[i] = -(offdiag[i] + offdiag[i - 1]);
diag[k] = 2.0;
}
//Take care of the endpoint
diag[fieldLength - lastObservedIndex[i] - 1] = 1.0;
weightMatricesForMissingCov.add(i, new SymmTridiagMatrix(diag, offdiag));
}
}
public SymmTridiagMatrix getScaledWeightMatrixForMissingCov(double precision, int covIndex, int lastObs) {
SymmTridiagMatrix a = weightMatricesForMissingCov.get(covIndex).copy();
for (int i = 0; i < a.numRows() - 1; i++) {
a.set(i, i, a.get(i, i) * precision);
a.set(i + 1, i, a.get(i + 1, i) * precision);
}
a.set(fieldLength -lastObs - 1, fieldLength - lastObs - 1,
a.get(fieldLength - lastObs - 1, fieldLength - lastObs - 1) * precision);
return a;
}
private List<Tree> treeList;
private List<TreeIntervals> intervalsList;
public int nLoci() {
return treeList.size();
}
public Tree getTree(int nt) {
return treeList.get(nt);
}
public TreeIntervals getTreeIntervals(int nt) {
return intervalsList.get(nt);
}
public double getPopulationFactor(int nt) {
return ploidyFactors.getParameterValue(nt);
}
public List<Parameter> getBetaListParameter() {
return beta;
}
public List<MatrixParameter> getCovariates() {
return covariates;
}
public void storeTheState() {
for (TreeIntervals intervals : intervalsList) {
intervals.storeState();
}
}
public void restoreTheState() {
for (TreeIntervals intervals : intervalsList) {
intervals.restoreState();
}
}
protected void storeState() {
// System.arraycopy(numCoalEvents, 0, storedNumCoalEvents, 0, numCoalEvents.length);
super.storeState();
System.arraycopy(numCoalEvents, 0, storedNumCoalEvents, 0, numCoalEvents.length);
// storedPrecMatrix = precMatrix.copy();
System.arraycopy(ploidySums, 0, storedPloidySums, 0, ploidySums.length);
}
protected void restoreState() {
super.restoreState();
// Swap pointers
double[] tmp = numCoalEvents;
numCoalEvents = storedNumCoalEvents;
storedNumCoalEvents = tmp;
double[] tmp2 = ploidySums;
ploidySums = storedPloidySums;
storedPloidySums = tmp2;
}
public int getCoalescentIntervalLineageCount(int i) {
return 0; //To change body of implemented methods use File | Settings | File Templates.
}
public IntervalType getCoalescentIntervalType(int i) {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
class SkygridHelper{
public SkygridHelper(){}
public double getLogFieldLikelihood(){
if (!intervalsKnown) {
//intervalsKnown -> false when handleModelChanged event occurs in super.
wrapSetupIntervals();
setupSufficientStatistics();
intervalsKnown = true;
}
double currentLike = 0;
DenseVector diagonal1 = new DenseVector(fieldLength);
DenseVector currentGamma = new DenseVector(popSizeParameter.getParameterValues());
SymmTridiagMatrix currentQ = getScaledWeightMatrix(precisionParameter.getParameterValue(0), lambdaParameter.getParameterValue(0));
currentQ.mult(currentGamma, diagonal1);
// currentLike += 0.5 * logGeneralizedDeterminant(currentQ) - 0.5 * currentGamma.dot(diagonal1);
currentLike += 0.5 * (fieldLength - 1) * Math.log(precisionParameter.getParameterValue(0)) - 0.5 * currentGamma.dot(diagonal1);
if (lambdaParameter.getParameterValue(0) == 1) {
currentLike -= (fieldLength - 1) / 2.0 * LOG_TWO_TIMES_PI;
} else {
currentLike -= fieldLength / 2.0 * LOG_TWO_TIMES_PI;
}
return currentLike;
}
}
class SkygridCovariateHelper extends SkygridHelper {
public SkygridCovariateHelper(){}
public double getLogFieldLikelihood(){
if (!intervalsKnown) {
//intervalsKnown -> false when handleModelChanged event occurs in super.
wrapSetupIntervals();
setupSufficientStatistics();
intervalsKnown = true;
}
double currentLike = 0;
DenseVector tempVect = new DenseVector(popSizeParameter.getParameterValues());
DenseVector diagonal1 = new DenseVector(fieldLength);
DenseVector currentGamma = new DenseVector(popSizeParameter.getParameterValues());
DenseVector currentBeta = new DenseVector(beta.size());
for(int i =0; i < beta.size(); i++){
currentBeta.set(i, beta.get(i).getParameterValue(0));
}
//int numMissing = fieldLength - lastObservedIndex;
//DenseVector tempVectCov = new DenseVector(numMissing);
//System.err.println("covariates.size(): " + covariates.size());
//System.err.println("covariates.get(0).getColumnDimension: " + covariates.get(0).getColumnDimension());
//System.err.println("covariates.get(0).getRowDimension: " + covariates.get(0).getRowDimension());
for(int i = 0; i < covariates.size(); i++){
for(int j = 0; j < covariates.get(i).getColumnDimension(); j++){
// System.err.println("j: " + j);
// System.err.println("covariates.get(i).getParameterValue(0,j): " + covariates.get(i).getParameterValue(0,j));
tempVect.set(j, tempVect.get(j) - covariates.get(i).getParameterValue(0,j)*currentBeta.get(i));
}
}
SymmTridiagMatrix currentQ = getScaledWeightMatrix(precisionParameter.getParameterValue(0), lambdaParameter.getParameterValue(0));
// currentQ.mult(currentGamma, diagonal1);
currentQ.mult(tempVect, diagonal1);
// currentLike += 0.5 * logGeneralizedDeterminant(currentQ) - 0.5 * currentGamma.dot(diagonal1);
//currentLike += 0.5 * (fieldLength - 1) * Math.log(precisionParameter.getParameterValue(0)) - 0.5 * currentGamma.dot(diagonal1);
currentLike += 0.5 * (fieldLength - 1) * Math.log(precisionParameter.getParameterValue(0)) - 0.5 * tempVect.dot(diagonal1);
if (lambdaParameter.getParameterValue(0) == 1) {
currentLike -= (fieldLength - 1) / 2.0 * LOG_TWO_TIMES_PI;
} else {
currentLike -= fieldLength / 2.0 * LOG_TWO_TIMES_PI;
}
return currentLike;
}
}
class SkygridMissingCovariateHelper extends SkygridHelper {
public SkygridMissingCovariateHelper(){}
public double getLogFieldLikelihood(){
if (!intervalsKnown) {
//intervalsKnown -> false when handleModelChanged event occurs in super.
wrapSetupIntervals();
setupSufficientStatistics();
intervalsKnown = true;
}
double currentLike = 0;
DenseVector tempVect = new DenseVector(popSizeParameter.getParameterValues());
DenseVector diagonal1 = new DenseVector(fieldLength);
DenseVector currentGamma = new DenseVector(popSizeParameter.getParameterValues());
// DenseVector currentBeta = new DenseVector(betaParameter.getParameterValues());
DenseVector currentBeta = new DenseVector(beta.size());
for(int i =0; i < beta.size(); i++){
currentBeta.set(i, beta.get(i).getParameterValue(0));
}
int numMissing;
DenseVector tempVectMissingCov;
SymmTridiagMatrix missingCovQ;
DenseVector tempVectMissingCov2;
//System.err.println("covariates.size(): " + covariates.size());
//System.err.println("covariates.get(0).getColumnDimension: " + covariates.get(0).getColumnDimension());
//System.err.println("covariates.get(0).getRowDimension: " + covariates.get(0).getRowDimension());
for(int i = 0; i < covariates.size(); i++){
for(int j = 0; j < covariates.get(i).getColumnDimension(); j++){
// System.err.println("j: " + j);
// System.err.println("covariates.get(i).getParameterValue(0,j): " + covariates.get(i).getParameterValue(0,j));
tempVect.set(j, tempVect.get(j) - covariates.get(i).getParameterValue(0,j)*currentBeta.get(i));
}
}
for(int i = 0; i < covPrecParameters.size(); i++){
numMissing = fieldLength - lastObservedIndex[i];
tempVectMissingCov = new DenseVector(numMissing);
tempVectMissingCov2 = new DenseVector(numMissing);
missingCovQ = getScaledWeightMatrixForMissingCov(covPrecParameters.get(i).getParameterValue(0), i,
lastObservedIndex[i]);
for(int j = 0; j < numMissing; j++) {
// System.err.println("covariate.get(i).getSize(): " + covariates.get(i).getSize());
// System.err.println("lastObservedIndex: " + lastObservedIndex);
// System.err.println("j: " + j);
// System.err.println("getParameterValue(0, lastObservedIndex-1): " + covariates.get(i).getParameterValue(0,lastObservedIndex-1));
tempVectMissingCov.set(j, covariates.get(i).getParameterValue(0, lastObservedIndex[i] + j) -
covariates.get(i).getParameterValue(0, lastObservedIndex[i]-1));
}
missingCovQ.mult(tempVectMissingCov, tempVectMissingCov2);
// System.err.println("missingCovQ: " + missingCovQ.get(0,0));
currentLike += 0.5*(numMissing)*Math.log(covPrecParameters.get(i).getParameterValue(0))
-0.5*tempVectMissingCov.dot(tempVectMissingCov2);
}
SymmTridiagMatrix currentQ = getScaledWeightMatrix(precisionParameter.getParameterValue(0), lambdaParameter.getParameterValue(0));
// currentQ.mult(currentGamma, diagonal1);
currentQ.mult(tempVect, diagonal1);
// currentLike += 0.5 * logGeneralizedDeterminant(currentQ) - 0.5 * currentGamma.dot(diagonal1);
//currentLike += 0.5 * (fieldLength - 1) * Math.log(precisionParameter.getParameterValue(0)) - 0.5 * currentGamma.dot(diagonal1);
currentLike += 0.5 * (fieldLength - 1) * Math.log(precisionParameter.getParameterValue(0)) - 0.5 * tempVect.dot(diagonal1);
if (lambdaParameter.getParameterValue(0) == 1) {
currentLike -= (fieldLength - 1) / 2.0 * LOG_TWO_TIMES_PI;
} else {
currentLike -= fieldLength / 2.0 * LOG_TWO_TIMES_PI;
}
return currentLike;
}
}
}
|
package net.sandius.rembulan.compiler.gen.block;
import net.sandius.rembulan.compiler.gen.PrototypeContext;
import net.sandius.rembulan.compiler.gen.SlotState;
import net.sandius.rembulan.core.ControlThrowable;
import net.sandius.rembulan.core.Dispatch;
import net.sandius.rembulan.core.LuaState;
import net.sandius.rembulan.core.ObjectSink;
import net.sandius.rembulan.core.Resumable;
import net.sandius.rembulan.core.ResumeInfo;
import net.sandius.rembulan.core.Table;
import net.sandius.rembulan.core.Upvalue;
import net.sandius.rembulan.util.Check;
import net.sandius.rembulan.util.asm.ASMUtils;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.FieldInsnNode;
import org.objectweb.asm.tree.FrameNode;
import org.objectweb.asm.tree.InsnList;
import org.objectweb.asm.tree.InsnNode;
import org.objectweb.asm.tree.JumpInsnNode;
import org.objectweb.asm.tree.LabelNode;
import org.objectweb.asm.tree.LdcInsnNode;
import org.objectweb.asm.tree.LineNumberNode;
import org.objectweb.asm.tree.LocalVariableNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
import org.objectweb.asm.tree.TableSwitchInsnNode;
import org.objectweb.asm.tree.TryCatchBlockNode;
import org.objectweb.asm.tree.TypeInsnNode;
import org.objectweb.asm.tree.VarInsnNode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.objectweb.asm.Opcodes.*;
public class CodeEmitter {
public final int REGISTER_OFFSET = 4;
public final int LV_STATE = 1;
public final int LV_OBJECTSINK = 2;
public final int LV_RESUME = 3;
private final ClassEmitter parent;
private final PrototypeContext context;
private final MethodNode methodNode;
private final MethodNode resumeMethodNode;
private MethodNode saveStateNode;
private final Map<Object, LabelNode> labels;
private final ArrayList<LabelNode> resumptionPoints;
private final InsnList resumeSwitch;
private final InsnList code;
private final InsnList errorState;
private final InsnList resumeHandler;
public CodeEmitter(ClassEmitter parent, PrototypeContext context) {
this.parent = Check.notNull(parent);
this.context = Check.notNull(context);
this.labels = new HashMap<>();
this.resumptionPoints = new ArrayList<>();
this.methodNode = new MethodNode(
ACC_PRIVATE,
methodName(),
methodType().getDescriptor(),
null,
exceptions());
this.resumeMethodNode = new MethodNode(
ACC_PUBLIC,
"resume",
Type.getMethodType(
Type.VOID_TYPE,
Type.getType(LuaState.class),
Type.getType(ObjectSink.class),
Type.getType(Object.class)).getDescriptor(),
null,
exceptions());
this.saveStateNode = null;
resumeSwitch = new InsnList();
code = new InsnList();
errorState = new InsnList();
resumeHandler = new InsnList();
}
public MethodNode node() {
return methodNode;
}
public MethodNode resumeNode() {
return resumeMethodNode;
}
public MethodNode saveNode() {
return saveStateNode;
}
private String methodName() {
return "run";
}
private Type methodType() {
Type[] args = new Type[3 + numOfRegisters()];
args[0] = Type.getType(LuaState.class);
args[1] = Type.getType(ObjectSink.class);
args[2] = Type.INT_TYPE;
for (int i = 3; i < args.length; i++) {
args[i] = Type.getType(Object.class);
}
return Type.getMethodType(Type.VOID_TYPE, args);
}
private String[] exceptions() {
return new String[] { Type.getInternalName(ControlThrowable.class) };
}
protected LabelNode _l(Object key) {
LabelNode l = labels.get(key);
if (l != null) {
return l;
}
else {
LabelNode nl = new LabelNode();
labels.put(key, nl);
return nl;
}
}
public void _note(String text) {
System.out.println("// " + text);
}
public void _dup() {
code.add(new InsnNode(DUP));
}
public void _swap() {
code.add(new InsnNode(SWAP));
}
public void _push_this() {
code.add(new VarInsnNode(ALOAD, 0));
}
public void _push_null() {
code.add(new InsnNode(ACONST_NULL));
}
public void _load_k(int idx, Class castTo) {
Object k = context.getConst(idx);
if (k == null) {
_push_null();
}
else if (k instanceof Boolean) {
code.add(ASMUtils.loadInt((Boolean) k ? 1 : 0));
code.add(ASMUtils.box(Type.BOOLEAN_TYPE, Type.getType(Boolean.class)));
}
else if (k instanceof Double || k instanceof Float) {
code.add(ASMUtils.loadDouble(((Number) k).doubleValue()));
code.add(ASMUtils.box(Type.DOUBLE_TYPE, Type.getType(Double.class)));
}
else if (k instanceof Number) {
code.add(ASMUtils.loadLong(((Number) k).longValue()));
code.add(ASMUtils.box(Type.LONG_TYPE, Type.getType(Long.class)));
}
else if (k instanceof String) {
code.add(new LdcInsnNode((String) k));
}
else {
throw new UnsupportedOperationException("Illegal const type: " + k.getClass());
}
if (castTo != null) {
if (!castTo.isAssignableFrom(k.getClass())) {
_checkCast(castTo);
}
}
}
public void _load_k(int idx) {
_load_k(idx, null);
}
public void _load_reg_value(int idx) {
code.add(new VarInsnNode(ALOAD, REGISTER_OFFSET + idx));
}
public void _load_reg_value(int idx, Class clazz) {
_load_reg_value(idx);
_checkCast(clazz);
}
public void _load_reg(int idx, SlotState slots, Class castTo) {
Check.notNull(slots);
Check.nonNegative(idx);
if (slots.isCaptured(idx)) {
_get_downvalue(idx);
_get_upvalue_value();
}
else {
_load_reg_value(idx);
}
Class clazz = Object.class;
if (castTo != null) {
if (!castTo.isAssignableFrom(clazz)) {
_checkCast(castTo);
}
}
}
public void _load_reg(int idx, SlotState slots) {
_load_reg(idx, slots, null);
}
public void _load_regs(int firstIdx, SlotState slots, int num) {
for (int i = 0; i < num; i++) {
_load_reg(firstIdx + i, slots);
}
}
public void _get_downvalue(int idx) {
code.add(new VarInsnNode(ALOAD, REGISTER_OFFSET + idx));
_checkCast(Upvalue.class);
}
public void _load_reg_or_const(int rk, SlotState slots, Class castTo) {
Check.notNull(slots);
if (rk < 0) {
// it's a constant
_load_k(-rk - 1, castTo);
}
else {
_load_reg(rk, slots, castTo);
}
}
public void _load_reg_or_const(int rk, SlotState slots) {
_load_reg_or_const(rk, slots, null);
}
private void _store_reg_value(int r) {
code.add(new VarInsnNode(ASTORE, REGISTER_OFFSET + r));
}
public void _store(int r, SlotState slots) {
Check.notNull(slots);
if (slots.isCaptured(r)) {
_get_downvalue(r);
_swap();
_set_upvalue_value();
}
else {
_store_reg_value(r);
}
}
public void _invokeStatic(Class clazz, String methodName, Type methodSignature) {
code.add(new MethodInsnNode(
INVOKESTATIC,
Type.getInternalName(clazz),
methodName,
methodSignature.getDescriptor(),
false
));
}
public void _invokeVirtual(Class clazz, String methodName, Type methodSignature) {
code.add(new MethodInsnNode(
INVOKEVIRTUAL,
Type.getInternalName(clazz),
methodName,
methodSignature.getDescriptor(),
false
));
}
public void _invokeInterface(Class clazz, String methodName, Type methodSignature) {
code.add(new MethodInsnNode(
INVOKEINTERFACE,
Type.getInternalName(clazz),
methodName,
methodSignature.getDescriptor(),
true
));
}
public void _invokeSpecial(String className, String methodName, Type methodSignature) {
code.add(new MethodInsnNode(
INVOKESPECIAL,
ASMUtils.typeForClassName(className).getInternalName(),
methodName,
methodSignature.getDescriptor(),
false
));
}
public void _dispatch_binop(String name, Class clazz) {
Type t = Type.getType(clazz);
_invokeStatic(Dispatch.class, name, Type.getMethodType(t, t, t));
}
public void _dispatch_generic_mt_2(String name) {
_invokeStatic(
Dispatch.class,
name,
Type.getMethodType(
Type.VOID_TYPE,
Type.getType(LuaState.class),
Type.getType(ObjectSink.class),
Type.getType(Object.class),
Type.getType(Object.class)
)
);
}
public void _dispatch_index() {
_dispatch_generic_mt_2("index");
}
public void _checkCast(Class clazz) {
code.add(new TypeInsnNode(CHECKCAST, Type.getInternalName(clazz)));
}
public void _loadState() {
withLuaState(code)
.push();
}
public void _loadObjectSink() {
withObjectSink(code)
.push();
}
public void _retrieve_1() {
withObjectSink(code)
.push()
.call_get(1);
}
public void _save_pc(Object o) {
LabelNode rl = _l(o);
int idx = resumptionPoints.size();
resumptionPoints.add(rl);
code.add(ASMUtils.loadInt(idx));
code.add(new VarInsnNode(ISTORE, LV_RESUME));
}
public void _resumptionPoint(Object label) {
_label_here(label);
}
private LabelNode l_insns_begin;
private LabelNode l_body_begin;
private LabelNode l_error_state;
private LabelNode l_handler_begin;
public void begin() {
l_insns_begin = new LabelNode();
methodNode.instructions.add(l_insns_begin);
l_body_begin = new LabelNode();
l_error_state = new LabelNode();
l_handler_begin = new LabelNode();
resumptionPoints.add(l_body_begin);
code.add(l_body_begin);
_frame_same(code);
}
public void end() {
if (isResumable()) {
_error_state();
}
_dispatch_table();
if (isResumable()) {
_resumption_handler();
}
// local variable declaration
LabelNode l_insns_end = new LabelNode();
List<LocalVariableNode> locals = methodNode.localVariables;
locals.add(new LocalVariableNode("this", parent.thisClassType().getDescriptor(), null, l_insns_begin, l_insns_end, 0));
locals.add(new LocalVariableNode("state", Type.getDescriptor(LuaState.class), null, l_insns_begin, l_insns_end, LV_STATE));
locals.add(new LocalVariableNode("sink", Type.getDescriptor(ObjectSink.class), null, l_insns_begin, l_insns_end, LV_OBJECTSINK));
locals.add(new LocalVariableNode("rp", Type.INT_TYPE.getDescriptor(), null, l_insns_begin, l_insns_end, LV_RESUME));
for (int i = 0; i < numOfRegisters(); i++) {
locals.add(new LocalVariableNode("r_" + i, Type.getDescriptor(Object.class), null, l_insns_begin, l_insns_end, REGISTER_OFFSET + i));
}
// if (isResumable()) {
// locals.add(new LocalVariableNode("ct", Type.getDescriptor(ControlThrowable.class), null, l_handler_begin, l_handler_end, REGISTER_OFFSET + numOfRegisters()));
// TODO: check these
// methodNode.maxLocals = numOfRegisters() + 4;
// methodNode.maxStack = numOfRegisters() + 5;
methodNode.maxLocals = locals.size();
methodNode.maxStack = 4 + numOfRegisters() + 5;
methodNode.instructions.add(resumeSwitch);
methodNode.instructions.add(code);
methodNode.instructions.add(errorState);
methodNode.instructions.add(resumeHandler);
methodNode.instructions.add(l_insns_end);
emitResumeNode();
MethodNode save = saveStateNode();
if (save != null) {
parent.node().methods.add(save);
}
}
private void emitResumeNode() {
if (isResumable()) {
InsnList il = resumeMethodNode.instructions;
List<LocalVariableNode> locals = resumeMethodNode.localVariables;
LabelNode begin = new LabelNode();
LabelNode vars = new LabelNode();
LabelNode end = new LabelNode();
il.add(begin);
il.add(new VarInsnNode(ALOAD, 3));
il.add(new TypeInsnNode(CHECKCAST, Type.getInternalName(ResumeInfo.SavedState.class)));
il.add(vars);
il.add(new VarInsnNode(ASTORE, 4));
il.add(new VarInsnNode(ALOAD, 0)); // this
il.add(new VarInsnNode(ALOAD, 1)); // state
il.add(new VarInsnNode(ALOAD, 2)); // sink
il.add(new VarInsnNode(ALOAD, 4)); // saved state
il.add(new FieldInsnNode(
GETFIELD,
Type.getInternalName(ResumeInfo.SavedState.class),
"resumptionPoint",
Type.INT_TYPE.getDescriptor()
)); // resumption point
// registers
if (numOfRegisters() > 0) {
il.add(new VarInsnNode(ALOAD, 4));
il.add(new FieldInsnNode(
GETFIELD,
Type.getInternalName(ResumeInfo.SavedState.class),
"registers",
ASMUtils.arrayTypeFor(Object.class).getDescriptor()
));
for (int i = 0; i < numOfRegisters(); i++) {
// Note: it might be more elegant to use a local variable
// to store the array instead of having to perform SWAPs
if (i + 1 < numOfRegisters()) {
il.add(new InsnNode(DUP));
}
il.add(ASMUtils.loadInt(i));
il.add(new InsnNode(AALOAD));
if (i + 1 < numOfRegisters()) {
il.add(new InsnNode(SWAP));
}
}
}
// call run(...)
il.add(new MethodInsnNode(
INVOKESPECIAL,
parent.thisClassType().getInternalName(),
methodName(),
methodType().getDescriptor(),
false
));
il.add(new InsnNode(RETURN));
il.add(end);
locals.add(new LocalVariableNode("this", parent.thisClassType().getDescriptor(), null, begin, end, 0));
locals.add(new LocalVariableNode("state", Type.getDescriptor(LuaState.class), null, begin, end, 1));
locals.add(new LocalVariableNode("sink", Type.getDescriptor(ObjectSink.class), null, begin, end, 2));
locals.add(new LocalVariableNode("suspendedState", Type.getDescriptor(Object.class), null, begin, end, 3));
locals.add(new LocalVariableNode("ss", Type.getDescriptor(ResumeInfo.SavedState.class), null, vars, end, 4));
resumeMethodNode.maxStack = 4 + (numOfRegisters() > 0 ? 3: 0);
resumeMethodNode.maxLocals = 5;
}
else
{
InsnList il = resumeMethodNode.instructions;
List<LocalVariableNode> locals = resumeMethodNode.localVariables;
LabelNode begin = new LabelNode();
LabelNode end = new LabelNode();
il.add(begin);
il.add(new TypeInsnNode(NEW, Type.getInternalName(UnsupportedOperationException.class)));
il.add(new InsnNode(DUP));
il.add(ASMUtils.ctor(UnsupportedOperationException.class));
il.add(new InsnNode(ATHROW));
il.add(end);
locals.add(new LocalVariableNode("this", parent.thisClassType().getDescriptor(), null, begin, end, 0));
locals.add(new LocalVariableNode("state", Type.getDescriptor(LuaState.class), null, begin, end, 1));
locals.add(new LocalVariableNode("sink", Type.getDescriptor(ObjectSink.class), null, begin, end, 2));
locals.add(new LocalVariableNode("suspendedState", Type.getDescriptor(Object.class), null, begin, end, 3));
resumeMethodNode.maxStack = 2;
resumeMethodNode.maxLocals = 4;
}
}
protected void _error_state() {
errorState.add(l_error_state);
errorState.add(new TypeInsnNode(NEW, Type.getInternalName(IllegalStateException.class)));
errorState.add(new InsnNode(DUP));
errorState.add(ASMUtils.ctor(IllegalStateException.class));
errorState.add(new InsnNode(ATHROW));
}
protected boolean isResumable() {
return resumptionPoints.size() > 1;
}
protected void _dispatch_table() {
if (isResumable()) {
LabelNode[] labels = resumptionPoints.toArray(new LabelNode[0]);
resumeSwitch.add(new VarInsnNode(ILOAD, LV_RESUME));
resumeSwitch.add(new TableSwitchInsnNode(0, resumptionPoints.size() - 1, l_error_state, labels));
}
}
protected int numOfRegisters() {
return context.prototype().getMaximumStackSize();
}
private Type saveStateType() {
Type[] args = new Type[1 + numOfRegisters()];
args[0] = Type.INT_TYPE;
for (int i = 1; i < args.length; i++) {
args[i] = Type.getType(Object.class);
}
return Type.getMethodType(Type.getType(ResumeInfo.class), args);
}
private String saveStateName() {
return "resumeInfo";
}
private MethodNode saveStateNode() {
if (isResumable()) {
MethodNode saveNode = new MethodNode(
ACC_PRIVATE,
saveStateName(),
saveStateType().getDescriptor(),
null,
null);
InsnList il = saveNode.instructions;
LabelNode begin = new LabelNode();
LabelNode end = new LabelNode();
il.add(begin);
il.add(new TypeInsnNode(NEW, Type.getInternalName(ResumeInfo.class)));
il.add(new InsnNode(DUP));
il.add(new VarInsnNode(ALOAD, 0));
il.add(new TypeInsnNode(NEW, Type.getInternalName(ResumeInfo.SavedState.class)));
il.add(new InsnNode(DUP));
// resumption point
il.add(new VarInsnNode(ILOAD, 1));
// registers
int numRegs = numOfRegisters();
il.add(ASMUtils.loadInt(numRegs));
il.add(new TypeInsnNode(ANEWARRAY, Type.getInternalName(Object.class)));
for (int i = 0; i < numRegs; i++) {
il.add(new InsnNode(DUP));
il.add(ASMUtils.loadInt(i));
il.add(new VarInsnNode(ALOAD, 2 + i));
il.add(new InsnNode(AASTORE));
}
// TODO: varargs
il.add(ASMUtils.ctor(
Type.getType(ResumeInfo.SavedState.class),
Type.INT_TYPE,
ASMUtils.arrayTypeFor(Object.class)));
il.add(ASMUtils.ctor(
Type.getType(ResumeInfo.class),
Type.getType(Resumable.class),
Type.getType(Object.class)));
il.add(new InsnNode(ARETURN));
il.add(end);
List<LocalVariableNode> locals = saveNode.localVariables;
locals.add(new LocalVariableNode("this", parent.thisClassType().getDescriptor(), null, begin, end, 0));
locals.add(new LocalVariableNode("rp", Type.INT_TYPE.getDescriptor(), null, begin, end, 1));
for (int i = 0; i < numOfRegisters(); i++) {
locals.add(new LocalVariableNode("r_" + i, Type.getDescriptor(Object.class), null, begin, end, 2 + i));
}
saveNode.maxLocals = 2 + numOfRegisters();
saveNode.maxStack = 7 + 3; // 7 to get register array at top, +3 to add element to it
return saveNode;
}
else {
return null;
}
}
protected void _resumption_handler() {
resumeHandler.add(l_handler_begin);
resumeHandler.add(new FrameNode(F_SAME1, 0, null, 1, new Object[] { Type.getInternalName(ControlThrowable.class) }));
resumeHandler.add(new InsnNode(DUP));
resumeHandler.add(new VarInsnNode(ALOAD, 0));
resumeHandler.add(new VarInsnNode(ILOAD, LV_RESUME));
for (int i = 0; i < numOfRegisters(); i++) {
resumeHandler.add(new VarInsnNode(ALOAD, REGISTER_OFFSET + i));
}
resumeHandler.add(new MethodInsnNode(
INVOKESPECIAL,
parent.thisClassType().getInternalName(),
saveStateName(),
saveStateType().getDescriptor(),
false));
resumeHandler.add(new MethodInsnNode(
INVOKEVIRTUAL,
Type.getInternalName(ControlThrowable.class),
"push",
Type.getMethodType(
Type.VOID_TYPE,
Type.getType(ResumeInfo.class)).getDescriptor(),
false));
// rethrow
resumeHandler.add(new InsnNode(ATHROW));
methodNode.tryCatchBlocks.add(new TryCatchBlockNode(l_insns_begin, l_handler_begin, l_handler_begin, Type.getInternalName(ControlThrowable.class)));
}
public void _get_upvalue_ref(int idx) {
code.add(new VarInsnNode(ALOAD, 0));
code.add(new FieldInsnNode(
GETFIELD,
parent.thisClassType().getInternalName(),
parent.getUpvalueFieldName(idx),
Type.getDescriptor(Upvalue.class)));
}
public void _get_upvalue_value() {
_invokeVirtual(Upvalue.class, "get", Type.getMethodType(Type.getType(Object.class)));
}
public void _set_upvalue_value() {
_invokeVirtual(Upvalue.class, "set", Type.getMethodType(Type.VOID_TYPE, Type.getType(Object.class)));
}
public void _return() {
code.add(new InsnNode(RETURN));
}
public void _new(String className) {
code.add(new TypeInsnNode(NEW, ASMUtils.typeForClassName(className).getInternalName()));
}
public void _new(Class clazz) {
_new(clazz.getName());
}
public void _closure_ctor(String className, int numUpvalues) {
Type[] argTypes = new Type[numUpvalues];
Arrays.fill(argTypes, Type.getType(Upvalue.class));
code.add(ASMUtils.ctor(ASMUtils.typeForClassName(className), argTypes));
}
public void _capture(int idx) {
LuaState_prx state = withLuaState(code);
state.push();
_load_reg_value(idx);
state.call_newUpvalue();
_store_reg_value(idx);
}
public void _uncapture(int idx) {
_load_reg_value(idx);
_get_upvalue_value();
_store_reg_value(idx);
}
private void _frame_same(InsnList il) {
il.add(new FrameNode(F_SAME, 0, null, 0, null));
}
public void _label_here(Object identity) {
LabelNode l = _l(identity);
code.add(l);
_frame_same(code);
}
public void _goto(Object l) {
code.add(new JumpInsnNode(GOTO, _l(l)));
}
public void _next_insn(Target t) {
_goto(t);
// if (t.inSize() < 2) {
// // can be inlined, TODO: check this again
// _note("goto ignored: " + t.toString());
// else {
// _goto(t);
}
public void _new_table(int array, int hash) {
withLuaState(code)
.push()
.do_newTable(array, hash);
}
public void _if_null(Object target) {
code.add(new JumpInsnNode(IFNULL, _l(target)));
}
public void _if_nonnull(Object target) {
code.add(new JumpInsnNode(IFNONNULL, _l(target)));
}
public void _tailcall(int numArgs) {
withObjectSink(code)
.call_tailCall(numArgs);
}
public void _setret(int num) {
withObjectSink(code)
.call_setTo(num);
}
public void _line_here(int line) {
LabelNode l = _l(new Object());
code.add(l);
code.add(new LineNumberNode(line, l));
}
private LuaState_prx withLuaState(InsnList il) {
return new LuaState_prx(LV_STATE, il);
}
private ObjectSink_prx withObjectSink(InsnList il) {
return new ObjectSink_prx(LV_OBJECTSINK, il);
}
private static class LuaState_prx {
private final int selfIndex;
private final InsnList il;
public LuaState_prx(int selfIndex, InsnList il) {
this.selfIndex = selfIndex;
this.il = il;
}
private Type selfTpe() {
return Type.getType(LuaState.class);
}
public LuaState_prx push() {
il.add(new VarInsnNode(ALOAD, selfIndex));
return this;
}
public LuaState_prx do_newTable(int array, int hash) {
push();
il.add(ASMUtils.loadInt(array));
il.add(ASMUtils.loadInt(hash));
il.add(new MethodInsnNode(
INVOKEVIRTUAL,
selfTpe().getInternalName(),
"newTable",
Type.getMethodType(
Type.getType(Table.class),
Type.INT_TYPE,
Type.INT_TYPE).getDescriptor(),
false));
return this;
}
public LuaState_prx call_newUpvalue() {
il.add(new MethodInsnNode(
INVOKEVIRTUAL,
selfTpe().getInternalName(),
"newUpvalue",
Type.getMethodType(
Type.getType(Upvalue.class),
Type.getType(Object.class)).getDescriptor(),
false));
return this;
}
}
private static class ObjectSink_prx {
private final int selfIndex;
private final InsnList il;
public ObjectSink_prx(int selfIndex, InsnList il) {
this.selfIndex = selfIndex;
this.il = il;
}
private Type selfTpe() {
return Type.getType(ObjectSink.class);
}
public ObjectSink_prx push() {
il.add(new VarInsnNode(ALOAD, selfIndex));
return this;
}
public ObjectSink_prx call_get(int index) {
Check.nonNegative(index);
if (index <= 4) {
String methodName = "_" + index;
il.add(new MethodInsnNode(
INVOKEVIRTUAL,
selfTpe().getInternalName(),
methodName,
Type.getMethodType(
Type.getType(Object.class)).getDescriptor(),
true));
}
else {
il.add(ASMUtils.loadInt(index));
il.add(new MethodInsnNode(
INVOKEVIRTUAL,
selfTpe().getInternalName(),
"get",
Type.getMethodType(
Type.getType(Object.class),
Type.INT_TYPE).getDescriptor(),
true));
}
return this;
}
public ObjectSink_prx call_setTo(int numValues) {
Check.nonNegative(numValues);
if (numValues == 0) {
il.add(new MethodInsnNode(
INVOKEVIRTUAL,
selfTpe().getInternalName(),
"reset",
Type.getMethodType(
Type.VOID_TYPE).getDescriptor(),
true));
}
else {
// TODO: determine this by reading the ObjectSink interface?
if (numValues <= 5) {
Type[] argTypes = new Type[numValues];
Arrays.fill(argTypes, Type.getType(Object.class));
il.add(new MethodInsnNode(
INVOKEVIRTUAL,
selfTpe().getInternalName(),
"setTo",
Type.getMethodType(
Type.VOID_TYPE,
argTypes).getDescriptor(),
true));
}
else {
// TODO: iterate and push
throw new UnsupportedOperationException("Return " + numValues + " values");
}
}
return this;
}
public ObjectSink_prx call_tailCall(int numCallArgs) {
Check.nonNegative(numCallArgs);
// TODO: determine this by reading the ObjectSink interface?
if (numCallArgs <= 4) {
Type[] callArgTypes = new Type[numCallArgs + 1]; // don't forget the call target
Arrays.fill(callArgTypes, Type.getType(Object.class));
il.add(new MethodInsnNode(
INVOKEVIRTUAL,
selfTpe().getInternalName(),
"tailCall",
Type.getMethodType(
Type.VOID_TYPE,
callArgTypes).getDescriptor(),
true));
}
else {
// TODO: iterate and push
throw new UnsupportedOperationException("Tail call with " + numCallArgs + " arguments");
}
return this;
}
}
}
|
package edu.psu.rcy5017.publicspeakingassistant;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
/**
* A helper class that is responsible for creating and updating the app database,
* and for creating all the tables in the database.
* @author ryosua
*
*/
public final class DatabaseHelper extends SQLiteOpenHelper {
private static final String TAG = "DatabaseHelper";
public static final int DATABASE_VERSION = 2;
public static final String DATABASE_NAME = "PublicSpeakingAssistantDatabase";
public static final String COLUMN_ID = "_id";
public static final String SPEECH_ID = "SpeechID";
// Speech Table
public static final String SPEECH_TABLE_NAME = "Speech";
public static final String SPEECH_TITLE = "Title";
// NoteCard Table
public static final String NOTECARD_TABLE_NAME = "Notecard";
public static final String NOTECARD_TITLE = "Title";
// Note Table
public static final String NOTE_TABLE_NAME = "Note";
public static final String NOTE_TEXT = "Text";
// SpeechRecording Table
public static final String SPEECH_RECORDING_TABLE_NAME = "SpeechRecording";
public static final String SPEECH_RECORDING_TITLE = "Title";
public static final String SPEECH_RECORDING_FILE = "File";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
createSpeechTable(db);
createNoteCardTable(db);
//createSpeechRecording(db);
//createBulletPointTable(db);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Do nothing.
}
@Override
public void onConfigure(SQLiteDatabase db) {
super.onConfigure(db);
db.setForeignKeyConstraintsEnabled(true);
}
private void createSpeechTable(SQLiteDatabase db) {
final String createStatement =
"CREATE TABLE " + SPEECH_TABLE_NAME + " (" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
SPEECH_TITLE + " TEXT NOT NULL" +
");";
db.execSQL(createStatement);
}
private void createNoteCardTable(SQLiteDatabase db) {
final String createStatement =
"CREATE TABLE " + NOTECARD_TABLE_NAME + " (" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
NOTECARD_TITLE + " TEXT NOT NULL," +
SPEECH_ID + " INTEGER NOT NULL," +
"FOREIGN KEY("+ SPEECH_ID +") REFERENCES " + SPEECH_TABLE_NAME + "("+ COLUMN_ID +") ON DELETE CASCADE" +
");";
Log.d(TAG, createStatement);
db.execSQL(createStatement);
}
}
|
package dr.evomodel.treedatalikelihood.discrete;
import dr.evolution.tree.NodeRef;
import dr.evomodel.branchratemodel.BranchRateModel;
import dr.evomodel.tree.TreeModel;
import dr.evomodel.treedatalikelihood.DataLikelihoodDelegate;
import dr.evomodel.treedatalikelihood.ProcessOnTreeDelegate;
import dr.inference.model.Bounds;
import dr.inference.model.CompoundParameter;
import dr.inference.model.Parameter;
import java.util.List;
/**
* @author Marc A. Suchard
* @author Xiang Ji
*/
public class NodeHeightToRatiosFullTransformDelegate extends NodeHeightToRatiosTransformDelegate {
private final double maxTipHeight;
private final Parameter heightParameter;
private CompoundParameter rootHeightAndRatios;
public NodeHeightToRatiosFullTransformDelegate(TreeModel treeModel,
Parameter nodeHeights,
Parameter ratios,
BranchRateModel branchRateModel) {
super(treeModel, nodeHeights, ratios, branchRateModel);
if (treeModel.getInternalNodeCount() != nodeHeights.getDimension()) {
throw new RuntimeException("Use all internal node (including root) for this transform.");
}
double tmpMaxTipHeight = 0.0;
for (int i = 0; i < tree.getExternalNodeCount(); i++) {
double tipHeight = tree.getNodeHeight(tree.getNode(i));
if (tipHeight > tmpMaxTipHeight) {
tmpMaxTipHeight = tipHeight;
}
}
this.maxTipHeight = tmpMaxTipHeight;
this.heightParameter = new HeightParameter(tree,
new Parameter.DefaultBounds(Double.POSITIVE_INFINITY, 0.0, 1));
this.rootHeightAndRatios = new CompoundParameter("rootHeightAndRatios",
new Parameter[]{heightParameter, ratios});
}
private class HeightParameter extends Parameter.Proxy {
private final TreeModel tree;
private Bounds<Double> bounds = null;
private HeightParameter(TreeModel tree, Bounds<Double> boundary) {
super("LocationShiftedRootHeightParameter", 1);
this.tree = tree;
addBounds(boundary);
}
@Override
public void addBounds(Bounds<Double> boundary) {
this.bounds = boundary;
}
@Override
public Bounds<Double> getBounds() {
return bounds;
}
@Override
public double getParameterValue(int dim) {
return tree.getNodeHeight(tree.getRoot()) - maxTipHeight;
}
@Override
public void setParameterValue(int dim, double value) {
tree.setNodeHeight(tree.getRoot(), getRootHeight(value));
}
@Override
public void setParameterValueQuietly(int dim, double value) {
tree.setNodeHeight(tree.getRoot(), getRootHeight(value));
}
@Override
public void setParameterValueNotifyChangedAll(int dim, double value) {
tree.setNodeHeight(tree.getRoot(), getRootHeight(value));
}
}
private double getRootHeight(double heightValue) {
return heightValue + maxTipHeight;
}
@Override
public double[] transform(double[] values) {
setNodeHeights(values);
updateRatios();
return setCombinedValues();
}
@Override
public double[] updateGradientLogDensity(double[] gradient, double[] value) {
double[] gradientLogDensityWrtRatios = super.updateGradientLogDensity(gradient, value);
double[] updatedGradient = new double[ratios.getDimension() + 1];
System.arraycopy(gradientLogDensityWrtRatios, 0, updatedGradient, 1, ratios.getDimension());
double[] logTime = getLogTimeArray();
updatedGradient[0] = updateHeightParameterGradientUnweightedLogDensity(gradient) - updateHeightParameterGradientUnweightedLogDensity(logTime);
return updatedGradient;
}
@Override
public double[] updateGradientUnWeightedLogDensity(double[] gradient, double[] value, int from, int to) {
double[] gradientUnWeightedLogDensityWrtRatios = super.updateGradientUnWeightedLogDensity(gradient, value, from, to);
double[] updatedGradient = new double[ratios.getDimension() + 1];
updatedGradient[0] = updateHeightParameterGradientUnweightedLogDensity(gradient);
System.arraycopy(gradientUnWeightedLogDensityWrtRatios, 0, updatedGradient, 1, ratios.getDimension());
return updatedGradient;
}
private double[] setCombinedValues() {
double[] rootHeightAndRatioArray = new double[ratios.getDimension() + 1];
System.arraycopy(ratios.getParameterValues(), 0, rootHeightAndRatioArray, 1,
ratios.getDimension());
rootHeightAndRatioArray[0] = this.rootHeightAndRatios.getParameterValue(0);
return rootHeightAndRatioArray;
}
@Override
public double[] inverse(double[] values) {
this.heightParameter.setParameterValue(0, values[0]);
double[] ratioValues = separateRatios(values);
return super.inverse(ratioValues);
}
private double[] separateRatios(double[] combinedValues) {
double[] ratioValues = new double[ratios.getDimension()];
System.arraycopy(combinedValues, 1, ratioValues, 0, ratioValues.length);
return ratioValues;
}
@Override
public Parameter getParameter() {
return rootHeightAndRatios;
}
private double updateHeightParameterGradientUnweightedLogDensity(double[] gradient) {
preOrderTraversal.updateAllNodes();
preOrderTraversal.dispatchTreeTraversalCollectBranchAndNodeOperations();
double[] multiplierArray = new double[tree.getInternalNodeCount()];
final List<DataLikelihoodDelegate.NodeOperation> nodeOperations = preOrderTraversal.getNodeOperations();
multiplierArray[getNodeHeightGradientIndex(tree.getRoot())] = 1.0;
for (ProcessOnTreeDelegate.NodeOperation op : nodeOperations) {
NodeRef node = tree.getNode(op.getLeftChild());
if (!tree.isRoot(node) && ! tree.isExternal(node)) {
final double ratio = ratios.getParameterValue(getRatiosIndex(node));
multiplierArray[getNodeHeightGradientIndex(node)] =
ratio * multiplierArray[getNodeHeightGradientIndex(tree.getParent(node))];
}
}
double sum = 0.0;
for (int i = 0; i < gradient.length; i++) {
sum += gradient[i] * multiplierArray[i];
}
return sum;
}
}
|
package com.grandmaapp.services;
import java.util.ArrayList;
import com.grandmaapp.activities.GrandmaActivity;
import com.grandmaapp.model.Eat;
import com.grandmaapp.model.Medicine;
import com.grandmaapp.model.Grandma.Requests;
import com.grandmaapp.notification.Notifications;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.text.format.Time;
import android.util.Log;
public class WishesService extends Service {
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Wuensche generieren, Benutzer informieren usw
//zeiten der wnsche abfragen/speichern
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
Time now = new Time();
now.setToNow();
//time as integer from 0 to 2359 (hour and minutes)
int time = Integer.parseInt(now.format2445().substring(9, 13));
Log.d("test", String.valueOf(time));
Editor editor = preferences.edit();
// editor.putInt(r.kind().toString(), calcExpireTime(r.getTimeMS()));
// if(r.kind() == Requests.EAT){
// Eat eat = (Eat) r;
// editor.putString("FoodWish", eat.getFoodWish().toString());
// if(r.kind() == Requests.MEDICINE){
// Medicine meds = (Medicine) r;
// editor.putString("MedWish", meds.getDaytime().toString());
boolean noFood = false;
// Time based requests
if( time == 800 )
{
createSuitUpRequest( time, editor );
}
else if( time == 830 )
{
createMorningMedicineRequest( time, editor );
}
else if( time == 900 )
{
createBreakfastRequest( time, editor );
}
else if ( time == 1000 || time == 1300 || time == 1800 )
{
createDrinkRequest( preferences, time, editor );
}
else if( time == 1200 )
{
noFood = createLunchRequest( preferences, time, editor );
}
else if( time == 1100 || time == 1400 || time == 1900 )
{
createWashDishesRequest( time, editor );
}
else if( time == 1650 )
{
createEveningMedicineRequest( time, editor );
}
else if( time == 1700 )
{
createSupperRequest( time, editor );
}
else if( time == 2000 )
{
createSleepRequest( time, editor );
}
// Storeroom supplies based request
if( preferences.getInt( "StoreClothes", -1 ) <= 0 )
{
createWashClothesRequest( time, editor );
}
else if( noFood || preferences.getInt( "StoreWater", -1 ) <= 0 )
{
createShoppingRequest( time, editor );
}
editor.commit();
return Service.START_NOT_STICKY;
}
public void createShoppingRequest( int time, Editor editor )
{
editor.putInt( "SHOPPING", time + 100 );
}
public void createWashClothesRequest( int time, Editor editor )
{
editor.putInt( "WASHCLOTHES", time + 1200 );
}
public void createSleepRequest( int time, Editor editor )
{
editor.putInt( "SLEEP", time + 100 );
notifyUser( "Brunhilde mchte schlafen!" );
}
public void createSupperRequest( int time, Editor editor )
{
editor.putInt( "EAT", time + 100 );
editor.putString( "FoodWish", "SUPPER" );
notifyUser( "Brunhilde mchte zu Abend essen!" );
}
public void createEveningMedicineRequest( int time, Editor editor )
{
editor.putInt( "MEDICINE", time + 100 );
editor.putString( "MedWish", "EVENING" );
}
public void createWashDishesRequest( int time, Editor editor )
{
editor.putInt( "WASHDISHES", time + 100 );
notifyUser( "Brunhilde hat schmutziges Geschirr!" );
}
public boolean createLunchRequest( SharedPreferences preferences, int time, Editor editor )
{
String foodwish = "";
ArrayList< String > availableFood = new ArrayList< String >( );
if( preferences.getInt( "StoreSchnitzel", -1 ) > 0 )
{
availableFood.add( "SCHNITZEL" );
}
if( preferences.getInt( "StoreNoodles", -1 ) > 0 )
{
availableFood.add( "NOODLES" );
}
if( preferences.getInt( "StoreDoener", -1 ) > 0 )
{
availableFood.add( "DOENER" );
}
if( preferences.getInt( "StorePizza", -1 ) > 0 )
{
availableFood.add( "PIZZA" );
}
// If nothing is available a wish for shopping food is generated
if( availableFood.size( ) != 0 )
{
int choice = (int) Math.random( ) * availableFood.size( );
foodwish = availableFood.get( choice );
if( foodwish.equals( "SCHNITZEL" ) || foodwish.equals( "PIZZA" ) )
{
editor.putInt( "MEDICINE", time + 100 );
editor.putString( "MedWish", "NOON" );
notifyUser( "Brunhilde braucht ihre Medizin!" );
}
editor.putInt( "EAT", time + 100 );
editor.putString( "FoodWish", foodwish );
notifyUser( "Brunhilde mchte essen!" );
}
else
{
return true;
}
return false;
}
public void createDrinkRequest( SharedPreferences preferences, int time, Editor editor )
{
if( preferences.getInt( "StoreWater", -1 ) > 0 )
{
editor.putInt( "DRINK", time + 30 );
notifyUser( "Brunhilde mchte trinken!" );
}
else
{
notifyUser( "Kein Wasser mehr vorrtig!" );
}
}
public void createBreakfastRequest( int time, Editor editor )
{
editor.putInt( "EAT", time + 100 );
editor.putString( "FoodWish", "BREAKFAST" );
notifyUser( "Brunhilde mchte Frhstck essen!" );
}
public void createMorningMedicineRequest( int time, Editor editor )
{
editor.putInt( "MEDICINE", time + 100 );
editor.putString( "MedWish", "MORNING" );
notifyUser( "Brunhilde muss ihre Morgen-Medizin nehmen!" );
}
public void createSuitUpRequest( int time, Editor editor )
{
editor.putInt( "SUITUP", time + 30 );
notifyUser( "Brunhilde mchte angezogen werden!" );
}
public void notifyUser( String message )
{
Notifications.newNotification( message, this );
}
@Override
public IBinder onBind(Intent arg0) {
// TODO for communication return IBinder implementation
return null;
}
}
|
package experimentalcode.erich.pca;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import de.lmu.ifi.dbs.elki.data.RealVector;
import de.lmu.ifi.dbs.elki.database.Database;
import de.lmu.ifi.dbs.elki.database.DistanceResultPair;
import de.lmu.ifi.dbs.elki.distance.NumberDistance;
import de.lmu.ifi.dbs.elki.math.linearalgebra.EigenPair;
import de.lmu.ifi.dbs.elki.math.linearalgebra.EigenvalueDecomposition;
import de.lmu.ifi.dbs.elki.math.linearalgebra.Matrix;
import de.lmu.ifi.dbs.elki.math.linearalgebra.SortedEigenPairs;
import de.lmu.ifi.dbs.elki.math.linearalgebra.pca.FilteredEigenPairs;
import de.lmu.ifi.dbs.elki.math.linearalgebra.pca.PCAFilteredResult;
import de.lmu.ifi.dbs.elki.math.linearalgebra.pca.PCAFilteredRunner;
/**
* Performs a self-tuning local PCA based on the covariance matrices of given
* objects. At most the closest 'k' points are used in the calculation and a
* weight function is applied.
*
* The number of points actually used depends on when the strong eigenvectors
* exhibit the clearest correlation.
*
* @author Erich Schubert
* @param <V> vector type
*/
public class PCAFilteredAutotuningRunner<V extends RealVector<V, ?>, D extends NumberDistance<D,?>> extends PCAFilteredRunner<V,D> {
/**
* Default constructor
*/
public PCAFilteredAutotuningRunner() {
super();
}
/**
* Run PCA on a collection of database IDs
*
* @param ids a collection of ids
* @param database the database used
* @return PCA result
*/
@Override
public PCAFilteredResult processIds(Collection<Integer> ids, Database<V> database) {
// FIXME: We're only supporting QueryResults for now, add compatibility
// wrapper?
return null;
}
/**
* Run PCA on a QueryResult Collection
*
* @param results a collection of QueryResults
* @param database the database used
* @return PCA result
*/
@Override
public PCAFilteredResult processQueryResult(Collection<DistanceResultPair<D>> results, Database<V> database) {
assertSortedByDistance(results);
int dim = database.dimensionality();
List<Matrix> best = new LinkedList<Matrix>();
for(int i = 0; i < dim; i++)
best.add(null);
double[] beststrength = new double[dim];
for(int i = 0; i < dim; i++)
beststrength[i] = -1;
int[] bestk = new int[dim];
// 'history'
LinkedList<Matrix> prevM = new LinkedList<Matrix>();
LinkedList<Double> prevS = new LinkedList<Double>();
LinkedList<Integer> prevD = new LinkedList<Integer>();
// TODO: starting parameter shouldn't be hardcoded...
int smooth = 3;
int startk = 4;
if(startk > results.size() - 1)
startk = results.size() - 1;
// TODO: add smoothing options, handle border cases better.
for(int k = startk; k < results.size(); k++) {
// sorted eigenpairs, eigenvectors, eigenvalues
Matrix covMat = covarianceMatrixBuilder.processQueryResults(results, database);
EigenvalueDecomposition evd = covMat.eig();
SortedEigenPairs eigenPairs = new SortedEigenPairs(evd, false);
FilteredEigenPairs filteredEigenPairs = getEigenPairFilter().filter(eigenPairs);
// correlationDimension = #strong EV
int thisdim = filteredEigenPairs.countStrongEigenPairs();
// FIXME: handle the case of no strong EVs.
assert ((thisdim > 0) && (thisdim <= dim));
double thisexplain = computeExplainedVariance(filteredEigenPairs);
prevM.add(covMat);
prevS.add(thisexplain);
prevD.add(thisdim);
assert (prevS.size() == prevM.size());
assert (prevS.size() == prevD.size());
if(prevS.size() >= 2 * smooth + 1) {
// all the same dimension?
boolean samedim = true;
for(Iterator<Integer> it = prevD.iterator(); it.hasNext();)
if(it.next().intValue() != thisdim)
samedim = false;
if(samedim) {
// average their explain values
double avgexplain = 0.0;
for(Iterator<Double> it = prevS.iterator(); it.hasNext();)
avgexplain += it.next().doubleValue();
avgexplain /= prevS.size();
if(avgexplain > beststrength[thisdim - 1]) {
beststrength[thisdim - 1] = avgexplain;
best.set(thisdim - 1, prevM.get(smooth));
bestk[thisdim - 1] = k - smooth;
}
}
prevM.removeFirst();
prevS.removeFirst();
prevD.removeFirst();
assert (prevS.size() == prevM.size());
assert (prevS.size() == prevD.size());
}
}
// Try all dimensions, lowest first.
for(int i = 0; i < dim; i++)
if(beststrength[i] > 0.0) {
// If the best was the lowest or the biggest k, skip it!
if(bestk[i] == startk + smooth)
continue;
if(bestk[i] == results.size() - smooth - 1)
continue;
Matrix covMat = best.get(i);
// We stop at the lowest dimension that did the job for us.
// System.err.println("Auto-k: "+bestk[i]+" dim: "+(i+1));
return processCovarMatrix(covMat);
}
// NOTE: if we didn't get a 'maximum' anywhere, we end up with the data from
// the last
// run of the loop above. I.e. PCA on the full data set. That is intended.
return processCovarMatrix(covarianceMatrixBuilder.processQueryResults(results, database));
}
/**
* Compute the explained variance for a FilteredEigenPairs
* @param filteredEigenPairs
* @return explained variance by the strong eigenvectors.
*/
private double computeExplainedVariance(FilteredEigenPairs filteredEigenPairs) {
double strongsum = 0.0;
double weaksum = 0.0;
for (EigenPair ep : filteredEigenPairs.getStrongEigenPairs())
strongsum += ep.getEigenvalue();
for (EigenPair ep : filteredEigenPairs.getWeakEigenPairs())
weaksum += ep.getEigenvalue();
return strongsum / (strongsum / weaksum);
}
/**
* Ensure that the results are sorted by distance.
*
* @param results
*/
private void assertSortedByDistance(Collection<DistanceResultPair<D>> results) {
// TODO: sort results instead?
double dist = -1.0;
for(Iterator<DistanceResultPair<D>> it = results.iterator(); it.hasNext();) {
DistanceResultPair<D> qr = it.next();
if(qr.getDistance().getValue().doubleValue() < dist) {
System.err.println("WARNING: results not sorted by distance!");
}
dist = qr.getDistance().getValue().doubleValue();
}
}
}
|
package com.season.scut;
import android.content.Context;
import android.content.Intent;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
public class Case implements Parcelable{
public long id;
public long starttime;
public long endtime;
public long alarmtime;
public long modifiedtime;
public String title;
public String matters;
public int status;
public static HashMap<Long ,Case> caseMap=new HashMap<>();
public Case() {
this.modifiedtime=0l;
this.status=1;
}
protected Case(Parcel in) {
id = in.readLong();
starttime = in.readLong();
endtime = in.readLong();
alarmtime = in.readLong();
modifiedtime = in.readLong();
title = in.readString();
matters = in.readString();
status =in.readInt();
}
public static final Creator<Case> CREATOR = new Creator<Case>() {
@Override
public Case createFromParcel(Parcel in) {
return new Case(in);
}
@Override
public Case[] newArray(int size) {
return new Case[size];
}
};
public long getEndtime() {
return endtime;
}
public String getMatters() {
return matters;
}
public long getStarttime() {
return starttime;
}
public String getTitle() {
return title;
}
public long getAlarmtime() {
return alarmtime;
}
public long getId() {
return id;
}
public long getModifiedtime() {
return modifiedtime;
}
public String getStringStartTime() {
StringBuilder builder =new StringBuilder();
Date startdate =new Date(getStarttime());
builder.append(startdate.getYear());
builder.append(".");
builder.append(startdate.getMonth()+1);
builder.append(".");
builder.append(startdate.getDay());
builder.append(" ");
builder.append(startdate.getHours());
builder.append(":");
builder.append(startdate.getMinutes());
return builder.toString();
}
public String getStringEndTime() {
StringBuilder builder =new StringBuilder();
Date startdate =new Date(getEndtime());
builder.append(startdate.getYear());
builder.append(".");
builder.append(startdate.getMonth()+1);
builder.append(".");
builder.append(startdate.getDay());
builder.append(" ");
builder.append(startdate.getHours());
builder.append(":");
builder.append(startdate.getMinutes());
return builder.toString();
}
public String getStrTime(){
StringBuilder builder =new StringBuilder();
Date startdate =new Date(getStarttime());
Date enddate=new Date(getEndtime());
builder.append(startdate.getMonth()+1);
builder.append("");
builder.append(startdate.getDay());
builder.append("");
if (startdate.getDay()==enddate.getDay()&&startdate.getMonth()==enddate.getMonth()){
if (startdate.getHours()==enddate.getHours()){
builder.append(startdate.getHours());
builder.append("");
builder.append(" ");
builder.append(startdate.getMinutes());
builder.append("");
builder.append(" ");
builder.append(enddate.getMinutes());
builder.append("");
}else{
builder.append(" ");
builder.append(startdate.getHours());
builder.append("");
builder.append(" ");
builder.append(enddate.getHours());
builder.append("");
}
}else{
builder.append(" ");
enddate=new Date(getEndtime());
builder.append(enddate.getMonth()+1);
builder.append("");
builder.append(enddate.getDay());
builder.append("");
}
return builder.toString();
}
public static Case insertOrUpdate(Context context,JSONObject object){
Case mCase=null;
try {
long id =object.getLong("id");
if (caseMap.containsKey(id)){
long modifiedtime=object.getLong("modified_time");
mCase= caseMap.get(id);
if (mCase.modifiedtime>modifiedtime){
LocalBroadcastManager manager =LocalBroadcastManager.getInstance(context);
Intent intent =new Intent();
intent.setAction(MApplication.ACTION_MODIFY);
intent.putExtra("data",mCase);
manager.sendBroadcast(intent);
return mCase;
}
if (object.has("status")){
mCase.status=object.getInt("status");
}
mCase.starttime=object.getLong("time");
mCase.endtime=object.getLong("end_time");
mCase.modifiedtime=modifiedtime;
mCase.alarmtime =object.getLong("alarm_time");
mCase.matters=object.getString("content");
mCase.title=object.getString("title");
}else{
mCase =new Case();
mCase.id=id;
mCase.starttime=object.getLong("time");
if (object.has("status")){
mCase.status=object.getInt("status");
}
mCase.endtime=object.getLong("end_time");
mCase.modifiedtime=object.getLong("modified_time");
mCase.alarmtime =object.getLong("alarm_time");
mCase.matters=object.getString("content");
mCase.title=object.getString("title");
caseMap.put(id,mCase);
}
if (mCase.alarmtime>System.currentTimeMillis()){
MApplication.getInstance().addNotification(mCase.alarmtime,mCase.id);
}
return mCase;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
public static List<Case> insertOrUpdate(Context context,JSONArray array){
try {
for (int i=0;i<array.length();i++){
JSONObject data =array.getJSONObject(i);
insertOrUpdate(context,data);
}
} catch (JSONException e) {
e.printStackTrace();
}
return getListData();
}
/**case*/
public static List<Case> getListData(){
List<Case> caseList = new ArrayList<>();
Iterator<Long> iterator =caseMap.keySet().iterator();
Case mCase ;
while(iterator.hasNext()){
mCase=caseMap.get(iterator.next());
if (mCase.status==1){
caseList.add(mCase);
}
}
for (int i=caseList.size()-1;i>=0;i
for (int j=0;j<i;j++){
if (caseList.get(j).starttime>caseList.get(j+1).starttime){
caseList.get(j).starttime=caseList.get(j).starttime+caseList.get(j+1).starttime;
caseList.get(j+1).starttime=caseList.get(j).starttime-caseList.get(j+1).starttime;
caseList.get(j).starttime=caseList.get(j).starttime-caseList.get(j+1).starttime;
}
}
}
//list
return caseList;
}
public static Case getCaseById(long id){
return caseMap.get(id);
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeLong(id);
dest.writeLong(starttime);
dest.writeLong(endtime);
dest.writeLong(alarmtime);
dest.writeLong(modifiedtime);
dest.writeString(title);
dest.writeString(matters);
}
public static void deletebyid(long id) {
caseMap.remove(id);
}
}
|
package hudson.remoting;
import java.io.IOException;
import java.io.Serializable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Request/response pattern over {@link Channel}, the layer-1 service.
*
* <p>
* This assumes that the receiving side has all the class definitions
* available to de-serialize {@link Request}, just like {@link Command}.
*
* @author Kohsuke Kawaguchi
* @see Response
*/
abstract class Request<RSP extends Serializable,EXC extends Throwable> extends Command {
/**
* Executed on a remote system to perform the task.
*
* @param channel
* The local channel. From the view point of the JVM that
* {@link #call(Channel) made the call}, this channel is
* the remote channel.
* @return
* the return value will be sent back to the calling process.
* @throws EXC
* The exception will be forwarded to the calling process.
* If no checked exception is supposed to be thrown, use {@link RuntimeException}.
*/
protected abstract RSP perform(Channel channel) throws EXC;
/**
* Uniquely identifies this request.
* Used for correlation between request and response.
*/
private final int id;
private volatile Response<RSP,EXC> response;
protected Request() {
synchronized(Request.class) {
id = nextId++;
}
}
/**
* Sends this request to a remote system, and blocks until we receives a response.
*
* @param channel
* The channel from which the request will be sent.
* @throws InterruptedException
* If the thread is interrupted while it's waiting for the call to complete.
* @throws IOException
* If there's an error during the communication.
* @throws RequestAbortedException
* If the channel is terminated while the call is in progress.
* @throws EXC
* If the {@link #perform(Channel)} throws an exception.
*/
public synchronized final RSP call(Channel channel) throws EXC, InterruptedException, IOException {
response=null;
channel.pendingCalls.put(id,this);
channel.send(this);
while(response==null)
wait(); // wait until the response arrives
EXC exc = response.exception;
if(exc !=null)
throw exc; // some versions of JDK fails to compile this line. If so, upgrade your JDK.
return response.returnValue;
}
/**
* Makes an invocation but immediately returns without waiting for the completion
* (AKA aysnchronous invocation.)
*
* @param channel
* The channel from which the request will be sent.
* @return
* The {@link Future} object that can be used to wait for the completion.
* @throws IOException
* If there's an error during the communication.
*/
public final Future<RSP> callAsync(Channel channel) throws IOException {
response=null;
channel.pendingCalls.put(id,this);
channel.send(this);
return new Future<RSP>() {
/**
* The task cannot be cancelled.
*/
public boolean cancel(boolean mayInterruptIfRunning) {
return false;
}
public boolean isCancelled() {
return false;
}
public boolean isDone() {
return response!=null;
}
public RSP get() throws InterruptedException, ExecutionException {
synchronized(Request.this) {
while(response==null)
Request.this.wait(); // wait until the response arrives
if(response.exception!=null)
throw new ExecutionException(response.exception);
return response.returnValue;
}
}
public RSP get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
synchronized(Request.this) {
if(response==null)
Request.this.wait(unit.toMillis(timeout)); // wait until the response arrives
if(response==null)
throw new TimeoutException();
if(response.exception!=null)
throw new ExecutionException(response.exception);
return response.returnValue;
}
}
};
}
/**
* Called by the {@link Response} when we received it.
*/
/*package*/ synchronized void onCompleted(Response<RSP,EXC> response) {
this.response = response;
notify();
}
/**
* Aborts the processing. The calling thread will receive an exception.
*/
/*package*/ void abort(IOException e) {
onCompleted(new Response(id,new RequestAbortedException(e)));
}
/**
* Schedules the execution of this request.
*/
protected final void execute(final Channel channel) {
channel.executor.execute(new Runnable() {
public void run() {
try {
RSP rsp;
try {
rsp = Request.this.perform(channel);
} catch (Throwable t) {
// error return
channel.send(new Response<RSP,Throwable>(id,t));
return;
}
// normal completion
channel.send(new Response<RSP,EXC>(id,rsp));
} catch (IOException e) {
// communication error.
// this means the caller will block forever
logger.log(Level.SEVERE, "Failed to send back a reply",e);
}
}
});
}
/**
* Next request ID.
*/
private static int nextId=0;
private static final long serialVersionUID = 1L;
private static final Logger logger = Logger.getLogger(Request.class.getName());
}
|
package gov.nih.nci.calab.service.search;
import gov.nih.nci.calab.db.DataAccessProxy;
import gov.nih.nci.calab.db.IDataAccess;
import gov.nih.nci.calab.domain.LabFile;
import gov.nih.nci.calab.domain.Protocol;
import gov.nih.nci.calab.domain.ProtocolFile;
import gov.nih.nci.calab.dto.common.LabFileBean;
import gov.nih.nci.calab.dto.common.ProtocolBean;
import gov.nih.nci.calab.dto.common.ProtocolFileBean;
import gov.nih.nci.calab.dto.common.UserBean;
import gov.nih.nci.calab.service.security.UserService;
import gov.nih.nci.calab.service.util.CaNanoLabConstants;
import gov.nih.nci.calab.service.util.StringUtils;
import org.hibernate.collection.PersistentSet;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Iterator;
import java.util.HashMap;
import java.util.Map;
import org.apache.log4j.Logger;
/**
* This class includes methods invovled in searching reports.
*
* @author pansu
*
*/
public class SearchProtocolService {
private static Logger logger = Logger
.getLogger(SearchReportService.class);
private UserService userService;
public SearchProtocolService() throws Exception{
userService = new UserService(
CaNanoLabConstants.CSM_APP_NAME);
}
public ProtocolFileBean getProtocolFileBean(String fileBeanId) throws Exception {
ProtocolFileBean fileBean = null;
IDataAccess ida = (new DataAccessProxy())
.getInstance(IDataAccess.HIBERNATE);
try {
ida.open();
List results = ida
.search("select protocolFile.title, protocolFile.description, protocolFile.filename, " +
"protocolFile.version from ProtocolFile protocolFile " +
"where protocolFile.id='" + fileBeanId + "'");
for (Object obj : results) {
String title = (String)(((Object[]) obj)[0]);
String description = (String) (((Object[]) obj)[1]);
String fileName = (String) (((Object[]) obj)[2]);
String version = (String) (((Object[]) obj)[3]);
fileBean = new ProtocolFileBean();
fileBean.setId(fileBeanId);
fileBean.setDescription(description);
fileBean.setTitle(title);
fileBean.setName(fileName);
fileBean.setVersion(version);
}
} catch (Exception e) {
logger.error("Problem finding protocol file info for protocol file Id: " + fileBeanId);
throw e;
} finally {
ida.close();
}
// get visibilities
UserService userService = new UserService(
CaNanoLabConstants.CSM_APP_NAME);
List<String> accessibleGroups = userService.getAccessibleGroups(
fileBean.getId(), CaNanoLabConstants.CSM_READ_ROLE);
String[] visibilityGroups = accessibleGroups.toArray(new String[0]);
fileBean.setVisibilityGroups(visibilityGroups);
return fileBean;
}
public ProtocolFileBean getWholeProtocolFileBean(String fileId
) throws Exception {
ProtocolFileBean pfb = new ProtocolFileBean();
IDataAccess ida = (new DataAccessProxy())
.getInstance(IDataAccess.HIBERNATE);
try {
ida.open();
String hqlString = "select protocolFile from ProtocolFile protocolFile left join fetch " +
"protocolFile.protocol where protocolFile.id='" + fileId + "'";
List results = ida.search(hqlString);
for (Object obj : results) {
ProtocolFile pf = (ProtocolFile)obj;
pfb.setId(pf.getId().toString());
pfb.setVersion(pf.getVersion());
pfb.setTitle(pf.getTitle());
pfb.setName(pf.getFilename());
pfb.setDescription(pf.getDescription());
ProtocolBean pb = new ProtocolBean();
Protocol p = pf.getProtocol();
pb.setId(p.getId().toString());
pb.setName(p.getName());
pb.setType(p.getType());
pfb.setProtocolBean(pb);
}
} catch (Exception e) {
logger.error("Problem finding protocol info.");
throw e;
} finally {
ida.close();
}
UserService userService = new UserService(
CaNanoLabConstants.CSM_APP_NAME);
List<String> accessibleGroups = userService.getAccessibleGroups(
pfb.getId(), CaNanoLabConstants.CSM_READ_ROLE);
String[] visibilityGroups = accessibleGroups.toArray(new String[0]);
pfb.setVisibilityGroups(visibilityGroups);
return pfb;
}
public List<ProtocolFileBean> searchProtocols(String fileTitle,
String protocolType, String protocolName,
UserBean user) throws Exception {
List<ProtocolFileBean> protocols = new ArrayList<ProtocolFileBean>();
List<LabFileBean> protocolFiles = new ArrayList<LabFileBean>();
IDataAccess ida = (new DataAccessProxy())
.getInstance(IDataAccess.HIBERNATE);
try {
ida.open();
List<Object> paramList = new ArrayList<Object>();
List<String> whereList = new ArrayList<String>();
String where = "";
if (fileTitle.length() > 0) {
where = "where ";
if (fileTitle.indexOf("*") != -1) {
fileTitle = fileTitle.replace('*', '%');
whereList.add("protocolFile.title like ?");
} else {
whereList.add("protocolFile.title=? ");
}
paramList.add(fileTitle.toUpperCase());
}
if (protocolType.length() > 0) {
paramList.add(protocolType);
where = "where ";
whereList.add("p.type=? ");
}
if (protocolName.length() > 0) {
where = "where ";
if (protocolName.indexOf("*") != -1) {
protocolName = protocolName.replace('*', '%');
whereList.add("p.name like ?");
} else {
whereList.add("p.name=? ");
}
paramList.add(protocolName);
}
String whereStr = StringUtils.join(whereList, " and ");
String hqlString = "select protocolFile from ProtocolFile protocolFile join fetch " +
"protocolFile.protocol p ";
hqlString = hqlString + where + whereStr + " order by protocolFile.protocol.name, protocolFile.version ";
List results = ida.searchByParam(hqlString, paramList);
for (Object obj : results) {
ProtocolFile pf = (ProtocolFile)obj;
LabFileBean pfb = new ProtocolFileBean();
pfb.setId(pf.getId().toString());
pfb.setVersion(pf.getVersion());
pfb.setTitle(pf.getTitle());
pfb.setDescription(pf.getDescription());
ProtocolBean pb = new ProtocolBean();
Protocol p = pf.getProtocol();
pb.setId(p.getId().toString());
pb.setName(p.getName());
pb.setType(p.getType());
((ProtocolFileBean)pfb).setProtocolBean(pb);
protocolFiles.add(pfb);
}
} catch (Exception e) {
logger.error("Problem finding protocol info.");
throw e;
} finally {
ida.close();
}
if (protocolFiles.isEmpty())
return protocols;
List<LabFileBean> filteredProtocols = userService.getFilteredFiles(
user, protocolFiles);
if (!filteredProtocols.isEmpty()){
for (LabFileBean fb : filteredProtocols){
protocols.add((ProtocolFileBean)fb);
}
}
//return returnProtocols;
return protocols;
}
}
|
package com.exedio.cope;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import com.exedio.cope.function.LengthView;
import com.exedio.cope.function.UppercaseView;
import com.exedio.cope.testmodel.StringItem;
public class StringTest extends TestmodelTest
{
boolean supports;
String emptyString;
StringItem item, item2;
int numberOfItems;
@Override
public void setUp() throws Exception
{
super.setUp();
supports = model.supportsEmptyStrings();
emptyString = supports ? "" : null;
deleteOnTearDown(item = new StringItem("StringTest"));
deleteOnTearDown(item2 = new StringItem("StringTest2"));
numberOfItems = 2;
}
public void testStrings()
{
// test model
assertEquals(item.TYPE, item.any.getType());
assertEquals("any", item.any.getName());
assertEquals(false, item.any.isMandatory());
assertEqualsUnmodifiable(list(), item.any.getPatterns());
assertEquals(0, item.any.getMinimumLength());
assertEquals(StringAttribute.DEFAULT_LENGTH, item.any.getMaximumLength());
assertEquals(item.TYPE, item.mandatory.getType());
assertEquals("mandatory", item.mandatory.getName());
assertEquals(true, item.mandatory.isMandatory());
assertEquals(4, item.min4.getMinimumLength());
assertEquals(StringAttribute.DEFAULT_LENGTH, item.min4.getMaximumLength());
assertEquals(0, item.max4.getMinimumLength());
assertEquals(4, item.max4.getMaximumLength());
assertEquals(4, item.min4Max8.getMinimumLength());
assertEquals(8, item.min4Max8.getMaximumLength());
assertEquals(6, item.exact6.getMinimumLength());
assertEquals(6, item.exact6.getMaximumLength());
assertEquals(item.TYPE, item.min4Upper.getType());
assertEquals("min4Upper", item.min4Upper.getName());
{
final StringAttribute orig = new StringAttribute(Item.OPTIONAL);
assertEquals(false, orig.isFinal());
assertEquals(false, orig.isMandatory());
assertEquals(0, orig.getMinimumLength());
assertEquals(StringAttribute.DEFAULT_LENGTH, orig.getMaximumLength());
final StringAttribute copy = orig.copyFunctionAttribute();
assertEquals(false, copy.isFinal());
assertEquals(false, copy.isMandatory());
assertEquals(0, copy.getMinimumLength());
assertEquals(StringAttribute.DEFAULT_LENGTH, copy.getMaximumLength());
}
{
final StringAttribute orig = new StringAttribute(Item.FINAL_OPTIONAL).lengthMin(10);
assertEquals(true, orig.isFinal());
assertEquals(false, orig.isMandatory());
assertNull(orig.getImplicitUniqueConstraint());
assertEquals(10, orig.getMinimumLength());
assertEquals(StringAttribute.DEFAULT_LENGTH, orig.getMaximumLength());
final StringAttribute copy = orig.copyFunctionAttribute();
assertEquals(true, copy.isFinal());
assertEquals(false, copy.isMandatory());
assertNull(copy.getImplicitUniqueConstraint());
assertEquals(10, copy.getMinimumLength());
assertEquals(StringAttribute.DEFAULT_LENGTH, copy.getMaximumLength());
}
{
final StringAttribute orig = new StringAttribute(Item.FINAL_UNIQUE_OPTIONAL).lengthMin(20);
assertEquals(true, orig.isFinal());
assertEquals(false, orig.isMandatory());
assertNotNull(orig.getImplicitUniqueConstraint());
assertEquals(20, orig.getMinimumLength());
assertEquals(StringAttribute.DEFAULT_LENGTH, orig.getMaximumLength());
final StringAttribute copy = orig.copyFunctionAttribute();
assertEquals(true, copy.isFinal());
assertEquals(false, copy.isMandatory());
assertNotNull(copy.getImplicitUniqueConstraint());
assertEquals(20, copy.getMinimumLength());
assertEquals(StringAttribute.DEFAULT_LENGTH, copy.getMaximumLength());
}
{
final StringAttribute orig = new StringAttribute(Item.MANDATORY).lengthRange(10, 20);
assertEquals(false, orig.isFinal());
assertEquals(true, orig.isMandatory());
assertEquals(10, orig.getMinimumLength());
assertEquals(20, orig.getMaximumLength());
final StringAttribute copy = orig.copyFunctionAttribute();
assertEquals(false, copy.isFinal());
assertEquals(true, copy.isMandatory());
assertEquals(10, copy.getMinimumLength());
assertEquals(20, copy.getMaximumLength());
}
assertWrongLength(-1, 20, "mimimum length must be positive, but was -1.");
assertWrongLength( 0, 0, "maximum length must be greater zero, but was 0.");
assertWrongLength(20, 10, "maximum length must be greater or equal mimimum length, but was 10 and 20.");
// test conditions
assertEquals(item.any.equal("hallo"), item.any.equal("hallo"));
assertNotEquals(item.any.equal("hallo"), item.any.equal("bello"));
assertNotEquals(item.any.equal("hallo"), item.any.equal((String)null));
assertNotEquals(item.any.equal("hallo"), item.any.like("hallo"));
assertEquals(item.any.equal(item.mandatory), item.any.equal(item.mandatory));
assertNotEquals(item.any.equal(item.mandatory), item.any.equal(item.any));
// test convenience for conditions
assertEquals(item.any.startsWith("hallo"), item.any.like("hallo%"));
assertEquals(item.any.endsWith("hallo"), item.any.like("%hallo"));
assertEquals(item.any.contains("hallo"), item.any.like("%hallo%"));
assertEquals(item.any.equalIgnoreCase("hallo"), item.any.toUpperCase().equal("HALLO"));
assertEquals(item.any.likeIgnoreCase("hallo%"), item.any.toUpperCase().like("HALLO%"));
assertEquals(item.any.startsWithIgnoreCase("hallo"), item.any.toUpperCase().like("HALLO%"));
assertEquals(item.any.endsWithIgnoreCase("hallo"), item.any.toUpperCase().like("%HALLO"));
assertEquals(item.any.containsIgnoreCase("hallo"), item.any.toUpperCase().like("%HALLO%"));
// any
item.setAny("1234");
assertEquals("1234", item.getAny());
item.setAny("123");
assertEquals("123", item.getAny());
// standard tests
item.setAny(null);
assertString(item, item2, item.any);
assertString(item, item2, item.long1K);
assertString(item, item2, item.long1M);
{
final StringItem itemEmptyInit = new StringItem("", false);
deleteOnTearDown(itemEmptyInit);
numberOfItems++;
assertEquals(emptyString, itemEmptyInit.getAny());
restartTransaction();
assertEquals(emptyString, itemEmptyInit.getAny());
}
// mandatory
assertEquals("StringTest", item.getMandatory());
item.setMandatory("someOtherString");
assertEquals("someOtherString", item.getMandatory());
try
{
item.setMandatory(null);
fail();
}
catch(MandatoryViolationException e)
{
assertEquals(item, e.getItem());
assertEquals(item.mandatory, e.getMandatoryAttribute());
assertEquals(item.mandatory, e.getFeature());
assertEquals("mandatory violation on " + item + " for " + item.mandatory, e.getMessage());
}
assertEquals("someOtherString", item.getMandatory());
assertEquals(numberOfItems, item.TYPE.search(null).size());
try
{
new StringItem((String)null);
fail();
}
catch(MandatoryViolationException e)
{
assertEquals(null, e.getItem());
assertEquals(item.mandatory, e.getMandatoryAttribute());
assertEquals(item.mandatory, e.getFeature());
assertEquals("mandatory violation on a newly created item for " + item.mandatory, e.getMessage());
}
assertEquals(numberOfItems, item.TYPE.search(null).size());
assertEquals(numberOfItems, item.TYPE.search(null).size());
try
{
new StringItem(new SetValue[]{});
fail();
}
catch(MandatoryViolationException e)
{
assertEquals(null, e.getItem());
assertEquals(item.mandatory, e.getMandatoryAttribute());
assertEquals(item.mandatory, e.getFeature());
assertEquals("mandatory violation on a newly created item for " + item.mandatory, e.getMessage());
}
assertEquals(numberOfItems, item.TYPE.search(null).size());
// mandatory and empty string
try
{
item.setMandatory("");
if(supports)
assertEquals("", item.getMandatory());
else
fail();
}
catch(MandatoryViolationException e)
{
assertTrue(!supports);
assertEquals(item.mandatory, e.getMandatoryAttribute());
assertEquals(item.mandatory, e.getFeature());
assertEquals(item, e.getItem());
assertEquals("mandatory violation on " + item + " for " + item.mandatory, e.getMessage());
assertEquals("someOtherString", item.getMandatory());
}
StringItem item3 = null;
assertEquals(numberOfItems, item.TYPE.search(null).size());
try
{
item3 = new StringItem("", 0.0);
deleteOnTearDown(item3);
numberOfItems++;
if(supports)
assertEquals("", item3.getMandatory());
else
fail();
}
catch(MandatoryViolationException e)
{
assertTrue(!supports);
assertEquals(item3.mandatory, e.getMandatoryAttribute());
assertEquals(item3.mandatory, e.getFeature());
assertEquals(item3, e.getItem());
assertEquals("mandatory violation on a newly created item for " + item.mandatory, e.getMessage());
}
assertEquals(numberOfItems, item.TYPE.search(null).size());
// min4
try
{
item.setMin4("123");
fail("should have thrown LengthViolationException");
}
catch(LengthViolationException e)
{
assertEquals(item, e.getItem());
assertEquals(item.min4, e.getStringAttribute());
assertEquals(item.min4, e.getFeature());
assertEquals("123", e.getValue());
assertEquals(true, e.isTooShort());
assertEquals(
"length violation on " + item + ", " +
"'123' is too short for " + item.min4 + ", " +
"must be at least 4 characters.",
e.getMessage());
}
assertEquals(null, item.getMin4());
restartTransaction();
assertEquals(null, item.getMin4());
item.setMin4("1234");
assertEquals("1234", item.getMin4());
// max4
item.setMax4("1234");
assertEquals("1234", item.getMax4());
try
{
item.setMax4("12345");
fail("should have thrown LengthViolationException");
}
catch(LengthViolationException e)
{
assertEquals(item, e.getItem());
assertEquals(item.max4, e.getStringAttribute());
assertEquals(item.max4, e.getFeature());
assertEquals("12345", e.getValue());
assertEquals(false, e.isTooShort());
assertEquals(
"length violation on " + item + ", " +
"'12345' is too long for " + item.max4 + ", " +
"must be at most 4 characters.",
e.getMessage());
}
assertEquals("1234", item.getMax4());
restartTransaction();
assertEquals("1234", item.getMax4());
assertEquals(numberOfItems, item.TYPE.search(null).size());
try
{
new StringItem("12345", (Date)null);
fail();
}
catch(LengthViolationException e)
{
assertEquals(null, e.getItem());
assertEquals(item.max4, e.getStringAttribute());
assertEquals(item.max4, e.getFeature());
assertEquals("12345", e.getValue());
assertEquals(
"length violation on a newly created item, " +
"'12345' is too long for " + item.max4 + ", " +
"must be at most 4 characters.",
e.getMessage());
}
assertEquals(numberOfItems, item.TYPE.search(null).size());
try
{
StringItem.TYPE.newItem(new SetValue[]{
item.mandatory.map("defaultByMax4"),
item.max4.map("12345")
});
fail();
}
catch(LengthViolationException e)
{
assertEquals(null, e.getItem());
assertEquals(item.max4, e.getStringAttribute());
assertEquals(item.max4, e.getFeature());
assertEquals("12345", e.getValue());
assertEquals(
"length violation on a newly created item, " +
"'12345' is too long for " + item.max4 + ", " +
"must be at most 4 characters.",
e.getMessage());
}
assertEquals(numberOfItems, item.TYPE.search(null).size());
// min4max8
try
{
item.setMin4Max8("123");
fail("should have thrown LengthViolationException");
}
catch(LengthViolationException e)
{
assertEquals(item, e.getItem());
assertEquals(item.min4Max8, e.getStringAttribute());
assertEquals(item.min4Max8, e.getFeature());
assertEquals("123", e.getValue());
assertEquals(true, e.isTooShort());
assertEquals(
"length violation on " + item + ", " +
"'123' is too short for " + item.min4Max8 + ", " +
"must be at least 4 characters.",
e.getMessage());
}
assertEquals(null, item.getMin4Max8());
restartTransaction();
assertEquals(null, item.getMin4Max8());
item.setMin4Max8("1234");
assertEquals("1234", item.getMin4Max8());
item.setMin4Max8("12345678");
assertEquals("12345678", item.getMin4Max8());
restartTransaction();
assertEquals("12345678", item.getMin4Max8());
try
{
item.setMin4Max8("123456789");
fail("should have thrown LengthViolationException");
}
catch(LengthViolationException e)
{
assertEquals(item, e.getItem());
assertEquals(item.min4Max8, e.getStringAttribute());
assertEquals(item.min4Max8, e.getFeature());
assertEquals("123456789", e.getValue());
assertEquals(false, e.isTooShort());
assertEquals(
"length violation on " + item + ", " +
"'123456789' is too long for " + item.min4Max8 + ", " +
"must be at most 8 characters.",
e.getMessage());
}
assertEquals("12345678", item.getMin4Max8());
restartTransaction();
assertEquals("12345678", item.getMin4Max8());
// exact6
try
{
item.setExact6("12345");
fail("should have thrown LengthViolationException");
}
catch(LengthViolationException e)
{
assertEquals(item, e.getItem());
assertEquals(item.exact6, e.getStringAttribute());
assertEquals(item.exact6, e.getFeature());
assertEquals("12345", e.getValue());
assertEquals(true, e.isTooShort());
assertEquals(
"length violation on " + item + ", " +
"'12345' is too short for " + item.exact6 + ", " +
"must be at least 6 characters.",
e.getMessage());
}
assertEquals(null, item.getExact6());
restartTransaction();
assertEquals(null, item.getExact6());
item.setExact6("123456");
assertEquals("123456", item.getExact6());
restartTransaction();
assertEquals("123456", item.getExact6());
try
{
item.setExact6("1234567");
fail("should have thrown LengthViolationException");
}
catch(LengthViolationException e)
{
assertEquals(item, e.getItem());
assertEquals(item.exact6, e.getStringAttribute());
assertEquals(item.exact6, e.getFeature());
assertEquals("1234567", e.getValue());
assertEquals(false, e.isTooShort());
assertEquals(
"length violation on " + item + ", " +
"'1234567' is too long for " + item.exact6 + ", " +
"must be at most 6 characters.",
e.getMessage());
}
assertEquals("123456", item.getExact6());
restartTransaction();
assertEquals("123456", item.getExact6());
assertEquals(numberOfItems, item.TYPE.search(null).size());
try
{
new StringItem("1234567", 40);
fail();
}
catch(LengthViolationException e)
{
assertEquals(null, e.getItem());
assertEquals(item.exact6, e.getStringAttribute());
assertEquals(item.exact6, e.getFeature());
assertEquals("1234567", e.getValue());
assertEquals(false, e.isTooShort());
assertEquals(
"length violation on a newly created item, " +
"'1234567' is too long for " + item.exact6 + ", " +
"must be at most 6 characters.",
e.getMessage());
}
assertEquals(numberOfItems, item.TYPE.search(null).size());
try
{
StringItem.TYPE.newItem(new SetValue[]{
item.mandatory.map("defaultByExact6"),
item.exact6.map("1234567")
});
fail();
}
catch(LengthViolationException e)
{
assertEquals(null, e.getItem());
assertEquals(item.exact6, e.getStringAttribute());
assertEquals(item.exact6, e.getFeature());
assertEquals("1234567", e.getValue());
assertEquals(false, e.isTooShort());
assertEquals(
"length violation on a newly created item, " +
"'1234567' is too long for " + item.exact6 + ", " +
"must be at most 6 characters.",
e.getMessage());
}
assertEquals(numberOfItems, item.TYPE.search(null).size());
model.checkUnsupportedConstraints();
}
@SuppressWarnings("unchecked") // OK: test bad API usage
public void testUnchecked()
{
try
{
item.set((FunctionAttribute)item.any, Integer.valueOf(10));
fail();
}
catch(ClassCastException e)
{
assertEquals("expected a " + String.class.getName() + ", " + "but was a " + Integer.class.getName(), e.getMessage());
}
}
void assertWrongLength(final int minimumLength, final int maximumLength, final String message)
{
try
{
new StringAttribute(Item.OPTIONAL).lengthRange(minimumLength, maximumLength);
fail();
}
catch(RuntimeException e)
{
assertEquals(message, e.getMessage());
}
}
static final String makeString(final int length)
{
final int segmentLength = length/20 + 1;
final char[] buf = new char[length];
char val = 'A';
for(int i = 0; i<length; i+=segmentLength)
Arrays.fill(buf, i, Math.min(i+segmentLength, length), val++);
final String lengthString = String.valueOf(length) + ':';
System.arraycopy(lengthString.toCharArray(), 0, buf, 0, Math.min(lengthString.length(), length));
final String result = new String(buf);
return result;
}
void assertString(final Item item, final Item item2, final StringAttribute sa)
{
final Type<? extends Item> type = item.getCopeType();
assertEquals(type, item2.getCopeType());
final String VALUE = "someString";
final String VALUE2 = VALUE+"2";
final String VALUE_UPPER = "SOMESTRING";
final String VALUE2_UPPER = "SOMESTRING2";
final UppercaseView saup = sa.toUpperCase();
final LengthView saln = sa.length();
assertEquals(null, sa.get(item));
assertEquals(null, saup.get(item));
assertEquals(null, saln.get(item));
assertEquals(null, sa.get(item2));
assertEquals(null, saup.get(item2));
assertEquals(null, saln.get(item2));
assertContains(item, item2, type.search(sa.isNull()));
sa.set(item, VALUE);
assertEquals(VALUE, sa.get(item));
assertEquals(VALUE_UPPER, saup.get(item));
assertEquals(Integer.valueOf(VALUE.length()), saln.get(item));
sa.set(item2, VALUE2);
assertEquals(VALUE2, sa.get(item2));
assertEquals(VALUE2_UPPER, saup.get(item2));
assertEquals(Integer.valueOf(VALUE2.length()), saln.get(item2));
if(!oracle||sa.getMaximumLength()<4000)
{
assertContains(item, type.search(sa.equal(VALUE)));
assertContains(item2, type.search(sa.notEqual(VALUE)));
assertContains(type.search(sa.equal(VALUE_UPPER)));
assertContains(item, type.search(sa.like(VALUE)));
assertContains(item, item2, type.search(sa.like(VALUE+"%")));
assertContains(item2, type.search(sa.like(VALUE2+"%")));
assertContains(item, type.search(saup.equal(VALUE_UPPER)));
assertContains(item2, type.search(saup.notEqual(VALUE_UPPER)));
assertContains(type.search(saup.equal(VALUE)));
assertContains(item, type.search(saup.like(VALUE_UPPER)));
assertContains(item, item2, type.search(saup.like(VALUE_UPPER+"%")));
assertContains(item2, type.search(saup.like(VALUE2_UPPER+"%")));
assertContains(item, type.search(saln.equal(VALUE.length())));
assertContains(item2, type.search(saln.notEqual(VALUE.length())));
assertContains(type.search(saln.equal(VALUE.length()+2)));
assertContains(VALUE, VALUE2, search(sa));
assertContains(VALUE, search(sa, sa.equal(VALUE)));
// TODO allow functions for select
//assertContains(VALUE_UPPER, search(saup, sa.equal(VALUE)));
}
restartTransaction();
assertEquals(VALUE, sa.get(item));
assertEquals(VALUE_UPPER, saup.get(item));
assertEquals(Integer.valueOf(VALUE.length()), saln.get(item));
{
sa.set(item, "");
assertEquals(emptyString, sa.get(item));
restartTransaction();
assertEquals(emptyString, sa.get(item));
assertEquals(list(item), type.search(sa.equal(emptyString)));
if(!oracle||sa.getMaximumLength()<4000)
{
assertEquals(list(), type.search(sa.equal("x")));
assertEquals(supports ? list(item) : list(), type.search(sa.equal("")));
}
}
assertStringSet(item, sa,
"Auml \u00c4; "
+ "Ouml \u00d6; "
+ "Uuml \u00dc; "
+ "auml \u00e4; "
+ "ouml \u00f6; "
+ "uuml \u00fc; "
+ "szlig \u00df; "
+ "paragraph \u00a7; "
+ "kringel \u00b0; "
//+ "abreve \u0102; "
//+ "hebrew \u05d8 "
+ "euro \u20ac");
// byte C5 in several encodings
assertStringSet(item, sa,
"Aringabove \u00c5;" // ISO-8859-1/4/9/10 (Latin1/4/5/6)
+ "Lacute \u0139;" // ISO-8859-2 (Latin2)
+ "Cdotabove \u010a;" // ISO-8859-3 (Latin3)
+ "ha \u0425;" // ISO-8859-5 (Cyrillic)
+ "AlefHamzaBelow \u0625;" // ISO-8859-6 (Arabic)
+ "Epsilon \u0395;" // ISO-8859-7 (Greek)
);
// test SQL injection
// if SQL injection is not prevented properly,
// the following lines will throw a SQLException
// due to column "hijackedColumn" not found
assertStringSet(item, sa, "value',hijackedColumn='otherValue");
// TODO use streams for oracle
assertStringSet(item, sa, makeString(Math.min(sa.getMaximumLength(), oracle ? (1300/*32766-1*/) : (4 * 1000 * 1000))));
sa.set(item, null);
assertEquals(null, sa.get(item));
assertEquals(null, saup.get(item));
assertEquals(null, saln.get(item));
assertContains(item, type.search(sa.isNull()));
sa.set(item2, null);
assertEquals(null, sa.get(item2));
assertEquals(null, saup.get(item2));
assertEquals(null, saln.get(item2));
assertContains(item, item2, type.search(sa.isNull()));
}
private void assertStringSet(final Item item, final StringAttribute sa, final String value)
{
final Type type = item.getCopeType();
sa.set(item, value);
assertEquals(value, sa.get(item));
restartTransaction();
assertEquals(value, sa.get(item));
if(!oracle||sa.getMaximumLength()<4000) // TODO should work without condition
{
assertEquals(list(item), type.search(sa.equal(value)));
assertEquals(list(), type.search(sa.equal(value+"x")));
}
}
protected static List<? extends Object> search(final FunctionAttribute<? extends Object> selectAttribute)
{
return search(selectAttribute, null);
}
protected static List<? extends Object> search(final FunctionAttribute<? extends Object> selectAttribute, final Condition condition)
{
return new Query<Object>(selectAttribute, condition).search();
}
}
|
package gov.nih.nci.calab.service.search;
import gov.nih.nci.calab.db.DataAccessProxy;
import gov.nih.nci.calab.db.IDataAccess;
import gov.nih.nci.calab.domain.InputFile;
import gov.nih.nci.calab.domain.OutputFile;
import gov.nih.nci.calab.dto.search.WorkflowResultBean;
import gov.nih.nci.calab.service.util.CalabConstants;
import gov.nih.nci.calab.service.util.StringUtils;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;
import org.apache.log4j.Logger;
/**
* This class implements middle-tier methods for the search workflow page
*
* @author pansu
*
*/
/* CVS $Id: SearchWorkflowService.java,v 1.12 2006-04-18 15:51:50 pansu Exp $ */
public class SearchWorkflowService {
private static Logger logger = Logger
.getLogger(SearchWorkflowService.class);
/**
*
* @return all file submitters
*/
public List<String> getAllFileSubmitters() {
SortedSet<String> submitters = new TreeSet<String>();
try {
IDataAccess ida = (new DataAccessProxy())
.getInstance(IDataAccess.TOOLKITAPI);
ida.open();
String hqlString1 = "select distinct createdBy from InputFile order by createdBy";
List results1 = ida.query(hqlString1, InputFile.class.getName());
for (Object obj : results1) {
submitters.add((String) obj);
}
String hqlString2 = "select distinct createdBy from OutputFile order by createdBy";
List results2 = ida.query(hqlString2, OutputFile.class.getName());
for (Object obj : results2) {
submitters.add((String) obj);
}
ida.close();
} catch (Exception e) {
logger.error("Error in retrieving all file submitters", e);
throw new RuntimeException(
"Error in retrieving all file submitters");
}
return new ArrayList<String>(submitters);
}
public List<WorkflowResultBean> searchWorkflows(String assayName,
String assayType, Date assayRunDateBegin, Date assayRunDateEnd,
String aliquotName, boolean includeMaskedAliquots, String fileName,
boolean isFileIn, boolean isFileOut, Date fileSubmissionDateBegin,
Date fileSubmissionDateEnd, String fileSubmitter,
boolean includeMaskedFiles, String criteriaJoin) {
List<WorkflowResultBean> workflows = null;
// construct where clause and parameter list
Object[] whereParams = null;
if (criteriaJoin.equals("and")) {
whereParams = constructWhereParams(assayName, assayType,
assayRunDateBegin, assayRunDateEnd, aliquotName,
includeMaskedAliquots, fileName, fileSubmissionDateBegin,
fileSubmissionDateEnd, fileSubmitter, includeMaskedFiles,
"and");
} else {
whereParams = constructWhereParams(assayName, assayType,
assayRunDateBegin, assayRunDateEnd, aliquotName,
includeMaskedAliquots, fileName, fileSubmissionDateBegin,
fileSubmissionDateEnd, fileSubmitter, includeMaskedFiles,
"or");
}
String hqlString = "select distinct file.path, assay.assayType, assay.name, run.createdDate, aliquot.name, file.createdDate, file.createdBy, fileStatus.status ";
// search either input file or output file, not both
if (!(isFileIn && isFileOut)) {
boolean isInputFile = (isFileIn == true) ? true : false;
{
// if select an item, need to include in join
if (isInputFile) {
hqlString += "from Aliquot aliquot left join aliquot.dataStatus aliquotStatus join aliquot.runSampleContainerCollection.run run left join run.inputFileCollection file join run.assay assay left join file.dataStatus fileStatus ";
} else {
hqlString += "from Aliquot aliquot left join aliquot.dataStatus aliquotStatus join aliquot.runSampleContainerCollection.run run left join run.outputFileCollection file join run.assay assay left join file.dataStatus fileStatus ";
}
hqlString += whereParams[0];
workflows = getWorkflows(hqlString, (List) whereParams[1]);
}
}
else {
//get inputFile workflows first
workflows=new ArrayList<WorkflowResultBean>();
String inHqlString =hqlString+ "from Aliquot aliquot left join aliquot.dataStatus aliquotStatus join aliquot.runSampleContainerCollection.run run left join run.inputFileCollection file join run.assay assay left join file.dataStatus fileStatus ";
inHqlString += whereParams[0];
List<WorkflowResultBean> inWorkflows = getWorkflows(inHqlString, (List) whereParams[1]);
workflows.addAll(inWorkflows);
//get outputFile workflows next
String outHqlString =hqlString+ "from Aliquot aliquot left join aliquot.dataStatus aliquotStatus join aliquot.runSampleContainerCollection.run run left join run.outputFileCollection file join run.assay assay left join file.dataStatus fileStatus ";
outHqlString += whereParams[0];
List<WorkflowResultBean> outWorkflows = getWorkflows(outHqlString, (List) whereParams[1]);
workflows.addAll(outWorkflows);
}
return workflows;
}
private Object[] constructWhereParams(String assayName, String assayType,
Date assayRunDateBegin, Date assayRunDateEnd, String aliquotName,
boolean includeMaskedAliquots, String fileName,
Date fileSubmissionDateBegin, Date fileSubmissionDateEnd,
String fileSubmitter, boolean includeMaskedFiles, String join) {
List<Object> paramList = new ArrayList<Object>();
List<String> whereList = new ArrayList<String>();
String where = "";
if (assayName.length() > 0) {
if (assayName.indexOf("*") != -1) {
assayName = assayName.replace('*', '%');
whereList.add("assay.name like ?");
} else {
whereList.add("assay.name=?");
}
paramList.add(assayName);
where = "where ";
}
if (assayType.length() > 0) {
if (assayType.indexOf("*") != -1) {
assayType = assayType.replace('*', '%');
whereList.add("assay.assayType like ?");
} else {
whereList.add("assay.assayType =?");
}
paramList.add(assayType);
where = "where ";
}
if (assayRunDateBegin != null && assayRunDateEnd != null) {
paramList.add(assayRunDateBegin);
paramList.add(assayRunDateEnd);
whereList.add("run.runDate>=? and run.runDate<=?");
where = "where ";
} else if (assayRunDateEnd != null) {
paramList.add(assayRunDateEnd);
whereList.add("run.runDate<=?");
where = "where ";
} else if (assayRunDateBegin != null) {
paramList.add(assayRunDateBegin);
whereList.add("run.runDate>=?");
where = "where ";
}
if (aliquotName.length() > 0) {
if (aliquotName.indexOf("*") != -1) {
aliquotName = aliquotName.replace('*', '%');
whereList.add("aliquot.name like ?");
} else {
whereList.add("aliquot.name=?");
}
paramList.add(aliquotName);
where = "where ";
}
if (!includeMaskedAliquots) {
whereList.add("aliquotStatus.status is null");
where = "where ";
}
if (fileName.length() > 0) {
if (fileName.indexOf("*") != -1) {
fileName = fileName.replace('*', '%');
whereList.add("file.path like ?");
} else {
whereList.add("file.path=?");
}
paramList.add(fileName);
where = "where ";
}
if (fileSubmissionDateBegin != null) {
paramList.add(fileSubmissionDateBegin);
whereList.add("file.createdDate>=?");
where = "where ";
}
if (fileSubmissionDateEnd != null) {
paramList.add(fileSubmissionDateEnd);
whereList.add("file.createdDate<=?");
where = "where ";
}
if (fileSubmitter.length() > 0) {
paramList.add(fileSubmitter);
whereList.add("file.createdBy=?");
where = "where ";
}
if (!includeMaskedFiles) {
whereList.add("fileStatus.status is null");
where = "where ";
}
String whereStr = "";
if (join.equals("and")) {
whereStr = StringUtils.join(whereList, " and ");
} else {
whereStr = StringUtils.join(whereList, " or ");
}
where = where + whereStr;
Object[] objs = new Object[] { where, paramList };
return objs;
}
private List<WorkflowResultBean> getWorkflows(String hqlString,
List paramList) {
List<WorkflowResultBean> workflows = new ArrayList<WorkflowResultBean>();
try {
IDataAccess ida = (new DataAccessProxy())
.getInstance(IDataAccess.HIBERNATE);
ida.open();
List results = ida.searchByParam(hqlString, paramList);
for (Object obj : results) {
Object[] items = (Object[]) obj;
String theFilePath = (String) items[0];
String theAssayType = (String) items[1];
String theAssayName = (String) items[2];
String theAssayRunDate = StringUtils.convertDateToString(
(Date) items[3], CalabConstants.DATE_FORMAT);
String theAliquotName = (String) items[4];
String theFileSubmissionDate = StringUtils.convertDateToString(
(Date) items[5], CalabConstants.DATE_FORMAT);
String theFileSubmitter = (String) items[6];
String theFileStatus = (String) items[7];
workflows
.add(new WorkflowResultBean(theFilePath, theAssayType,
theAssayName, theAssayRunDate, theAliquotName,
theFileSubmissionDate, theFileSubmitter,
theFileStatus));
}
ida.close();
} catch (Exception e) {
logger.error("Error in searching aliquots by the given parameters",
e);
throw new RuntimeException(
"Error in searching aliquots by the given parameters");
}
return workflows;
}
}
|
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import javax.xml.bind.JAXBException;
import org.springframework.util.StopWatch;
import net.leanix.api.BusinessCapabilitiesApi;
import net.leanix.api.BusinessObjectsApi;
import net.leanix.api.ConsumersApi;
import net.leanix.api.IfacesApi;
import net.leanix.api.ProcessesApi;
import net.leanix.api.ProjectsApi;
import net.leanix.api.ResourcesApi;
import net.leanix.api.ServicesApi;
import net.leanix.api.common.ApiClient;
import net.leanix.api.models.BusinessCapability;
import net.leanix.api.models.BusinessObject;
import net.leanix.api.models.Consumer;
import net.leanix.api.models.DataObject;
import net.leanix.api.models.FactSheetHasIfaceProvider;
import net.leanix.api.models.Iface;
import net.leanix.api.models.IfaceHasBusinessObject;
import net.leanix.api.models.Process;
import net.leanix.api.models.Project;
import net.leanix.api.models.Resource;
import net.leanix.api.models.Service;
import net.leanix.api.models.ServiceHasBusinessCapability;
import net.leanix.api.models.ServiceHasConsumer;
import net.leanix.api.models.ServiceHasInterface;
import net.leanix.api.models.ServiceHasProcess;
import net.leanix.api.models.ServiceHasProject;
import net.leanix.api.models.ServiceHasResource;
import net.leanix.benchmark.ApiClientFactory;
import net.leanix.benchmark.ConfigurationProvider;
import net.leanix.benchmark.Helper;
import net.leanix.benchmark.performance.ReportBuilder;
import net.leanix.benchmark.performance.TestSuite;
/**
* Creates a list of services (SERVICE_COUNT) with a list of linked resources (RESOURCE_PER_SERVICE_COUNT)
*
* @author andre
*/
public class BenchmarkC extends BaseBenchmarkTests {
int numServices = ConfigurationProvider.getServicesCount();
int numResourcesPerService = ConfigurationProvider.getNumResourcesPerService();
final StopWatch stopWatch;
public static void main(String[] args) throws Exception {
BenchmarkC instance = new BenchmarkC();
instance.run(instance.stopWatch);
}
public BenchmarkC() {
super();
stopWatch = new StopWatch(
String.format("%s creates %s services withc %s resources/service", getClass().getSimpleName(), numServices,
numResourcesPerService));
}
@Override
public void runBenchmarkOnWorkspace(StopWatch stopWatch) throws JAXBException {
try {
ApiClient apiClient = ApiClientFactory.getApiClient(wsName);
apiClient.addDefaultHeader("X-Api-Update-Relations", "true");
// allow asynchronous job run
apiClient.addDefaultHeader("X-Api-Synchronous", "false");
ServicesApi servicesApi = new ServicesApi(apiClient);
ResourcesApi resourcesApi = new ResourcesApi(apiClient);
ConsumersApi consumersApi = new ConsumersApi(apiClient);
BusinessCapabilitiesApi businessCapabilitiesApi = new BusinessCapabilitiesApi(apiClient);
ProcessesApi processApi = new ProcessesApi(apiClient);
ProjectsApi projectApi = new ProjectsApi(apiClient);
BusinessObjectsApi businessObjectApi = new BusinessObjectsApi(apiClient);
IfacesApi ifacesApi = new IfacesApi(apiClient);
// Add consumers (User Group)
Helper h = new Helper(configurationProvider.getRandomSeed());
List<Consumer> consumers = new ArrayList<>();
stopWatch.start("adding Consumers " + Helper.getProperty("consumers.count", "20"));
for (int i = 0; i < Integer.parseInt(Helper.getProperty("consumers.count", "20")); i++) {
Consumer c = new Consumer();
c.setName(h.getUniqueString());
c.setDescription(h.getUniqueText(10));
c = consumersApi.createConsumer(c);
System.out.println(String.format("Create USER GROUP %d, name = %s, id = %s", i, c.getName(), c.getID()));
consumers.add(c);
}
stopWatch.stop();
// Add business capability
List<BusinessCapability> bcs = new ArrayList<>();
stopWatch.start("adding BusinessCapabilities " + Helper.getProperty("businessCapabilities.count", "8"));
for (int i = 0; i < Integer.parseInt(Helper.getProperty("businessCapabilities.count", "8")); i++) {
BusinessCapability bc = new BusinessCapability();
bc.setName(h.getUniqueString());
bc.setDescription(h.getUniqueText(10));
bc = businessCapabilitiesApi.createBusinessCapability(bc);
System.out.println(String.format("Create BUS. CAPABILITY %d, name = %s, id = %s", i, bc.getName(), bc.getID()));
bcs.add(bc);
}
stopWatch.stop();
// Add Processes
List<Process> processes = new ArrayList<>();
stopWatch.start("adding Processes " + Helper.getProperty("processes.count", "8"));
for (int i = 0; i < Integer.parseInt(Helper.getProperty("processes.count", "8")); i++) {
Process process = new Process();
process.setName(h.getUniqueString());
process.setDescription(h.getUniqueText(10));
process = processApi.createProcess(process);
System.out.println(String.format("Create PROCESS %d, name = %s, id = %s", i, process.getName(), process.getID()));
processes.add(process);
}
stopWatch.stop();
// Add Projects
List<Project> projects = new ArrayList<>();
stopWatch.start("adding Projects " + Helper.getProperty("projects.count", "8"));
for (int i = 0; i < Integer.parseInt(Helper.getProperty("projects.count", "8")); i++) {
Project project = new Project();
project.setName(h.getUniqueString());
project.setDescription(h.getUniqueText(10));
project = projectApi.createProject(project);
System.out.println(String.format("Create PROJECT %d, name = %s, id = %s", i, project.getName(), project.getID()));
projects.add(project);
}
stopWatch.stop();
// Add Business Objects (Data Objects)
List<BusinessObject> businessObjects = new ArrayList<>();
stopWatch.start("adding Data Objects " + Helper.getProperty("businessobjects.count", "6"));
for (int i = 0; i < Integer.parseInt(Helper.getProperty("businessobjects.count", "6")); i++) {
BusinessObject businessObject = new BusinessObject();
businessObject.setName("Data Object " + h.getUniqueString());
businessObject.setDescription(h.getUniqueText(40));
businessObject = businessObjectApi.createBusinessObject(businessObject);
System.out.println(String.format("Create DATA OBJECT %d, name = %s, id = %s", i, businessObject.getName(),
businessObject.getID()));
businessObjects.add(businessObject);
}
stopWatch.stop();
// Add Interfaces assigned with business objects
List<Iface> interfaces = new ArrayList<>();
stopWatch.start("adding Interfaces " + Helper.getProperty("iface.count", "8"));
for (int i = 0; i < Integer.parseInt(Helper.getProperty("iface.count", "8")); i++) {
Iface iface = new Iface();
iface.setName("IFace " + h.getUniqueString());
iface.setDescription(h.getUniqueText(40));
IfaceHasBusinessObject ifaceHasBusinessObject = new IfaceHasBusinessObject();
ifaceHasBusinessObject.setBusinessObjectID(
businessObjects.get(ThreadLocalRandom.current().nextInt(0, businessObjects.size() - 1)).getID());
iface.setIfaceHasBusinessObjects(Arrays.asList(ifaceHasBusinessObject));
iface.setInterfaceDirectionID("1");
iface = ifacesApi.createIface(iface);
System.out.println(String.format("Create INTERFACE %d, name = %s, id = %s", i, iface.getName(), iface.getID()));
interfaces.add(iface);
}
stopWatch.stop();
// Create services
for (int i = 0; i < numServices; i++) {
stopWatch.start("Service " + i);
Service s = new Service();
s.setName(h.getUniqueString());
s.setDescription(h.getUniqueText(10));
s.setFactSheetHasLifecycles(h.getRandomLifecycle("2010-01-10", "2020-01-01"));
if (consumers.size() > 0) {
Consumer cur = consumers.get(ThreadLocalRandom.current().nextInt(0, consumers.size() - 1));
ServiceHasConsumer shc = new ServiceHasConsumer();
shc.setUsageTypeID("1");
shc.setConsumerID(cur.getID());
List<ServiceHasConsumer> shcList = new ArrayList<>();
shcList.add(shc);
s.setServiceHasConsumers(shcList);
}
if (bcs.size() > 0) {
BusinessCapability cur = bcs.get(ThreadLocalRandom.current().nextInt(0, bcs.size() - 1));
ServiceHasBusinessCapability shb = new ServiceHasBusinessCapability();
shb.setSupportTypeID("1");
shb.setBusinessCapabilityID(cur.getID());
List<ServiceHasBusinessCapability> shbList = new ArrayList<>();
shbList.add(shb);
s.setServiceHasBusinessCapabilities(shbList);
}
if (processes.size() > 0) {
Process process = processes.get(ThreadLocalRandom.current().nextInt(0, processes.size() - 1));
ServiceHasProcess shp = new ServiceHasProcess();
shp.setProcessID(process.getID());
s.setServiceHasProcesses(Arrays.asList(shp));
}
if (projects.size() > 0) {
Project project = projects.get(ThreadLocalRandom.current().nextInt(0, projects.size() - 1));
ServiceHasProject shp = new ServiceHasProject();
shp.setProjectID(project.getID());
s.setServiceHasProjects(Arrays.asList(shp));
}
if (interfaces.size() > 0) {
Iface iface = interfaces.get(ThreadLocalRandom.current().nextInt(0, interfaces.size() - 1));
FactSheetHasIfaceProvider factSheetHasIfaceProvider = new FactSheetHasIfaceProvider();
factSheetHasIfaceProvider.setIfaceID(iface.getID());
s.setFactSheetHasIfaceProviders(Arrays.asList(factSheetHasIfaceProvider));
}
s = servicesApi.createService(s);
System.out.println("Create SERVICE " + i + ", name = " + s.getName() + ", id = " + s.getID());
// Create resources (IT Components)
for (int x = 0; x < numResourcesPerService; x++) {
Resource r = new Resource();
r.setName(h.getUniqueString());
r.setDescription(h.getUniqueText(10));
r.setFactSheetHasLifecycles(h.getRandomLifecycle("2012-01-10", "2020-01-01"));
ServiceHasResource shr = new ServiceHasResource();
shr.setServiceID(s.getID());
shr.setComment("Created by SDK");
List<ServiceHasResource> shrList = new ArrayList<>();
shrList.add(shr);
r.setServiceHasResources(shrList);
r = resourcesApi.createResource(r);
System.out.println("Create RESOURCE " + i + ", name = " + r.getName() + ", id = " + r.getID());
}
stopWatch.stop();
}
} catch (Exception ex) {
System.out.println("Exception: " + ex.getMessage());
ReportBuilder reportBuilder = new ReportBuilder().forTestClass(getClass());
TestSuite testSuite = reportBuilder.addErrorTestResult("runBenchmarkOnWorkspace", 0, ex).build();
writeBenchmarkJUnitResultFile(getClass(), testSuite);
return;
}
// do some output to stdout
System.out.println(stopWatch.prettyPrint());
double totalTimeSeconds = stopWatch.getTotalTimeSeconds();
System.out.println(String.format("Complete Time of Run (+WS Setup) : %.2f s (%d:%02d)", totalTimeSeconds,
(int) totalTimeSeconds / 60, (int) totalTimeSeconds % 60));
double timeTestCase = getSumOfLastTasksInSeconds(stopWatch, stopWatch.getTaskCount() - 1);
System.out.println(String.format("Complete Job processing time : %.2f s (%d:%02d)", timeTestCase,
(int) timeTestCase / 60, (int) timeTestCase % 60));
System.out.println(String.format("Average Time of test for / %d FS : %.3f s", numServices, timeTestCase / numServices));
// write junit result file used in jenkin's performance plugin
// TestSuite testSuite = createTestSuiteObjectBasedOnTaskInfo(getClass(),
// getLastTasks(stopWatch, stopWatch.getTaskCount() - 1));
ReportBuilder reportBuilder = new ReportBuilder().forTestClass(getClass());
TestSuite testSuite = reportBuilder
.addSuccessfulTestResult(String.format("Average time for %d FS", numServices), timeTestCase / numServices)
.build();
writeBenchmarkJUnitResultFile(getClass(), testSuite);
}
}
|
/**
*
* $Id: NomenclatureManagerImpl.java,v 1.6 2008-01-24 16:13:29 pandyas Exp $
*
* $Log: not supported by cvs2svn $
* Revision 1.5 2007/09/12 19:36:03 pandyas
* modified debug statements for build to stage tier
*
* Revision 1.4 2007/02/22 21:03:00 pandyas
* Added get method to manager for save bug fix
*
* Revision 1.3 2007/02/21 00:55:08 pandyas
* Fixed Nomenclature save
*
* Revision 1.2 2007/02/01 19:07:06 pandyas
* Fixed Genotype bug - working on saving Nomenclature
*
* Revision 1.1 2006/10/17 16:13:46 pandyas
* modified during development of caMOD 2.2 - various
*
*
*/
package gov.nih.nci.camod.service.impl;
import gov.nih.nci.camod.domain.Nomenclature;
import gov.nih.nci.camod.service.NomenclatureManager;
import gov.nih.nci.common.persistence.Search;
import gov.nih.nci.common.persistence.exception.PersistenceException;
import gov.nih.nci.common.persistence.hibernate.eqbe.Evaluation;
import gov.nih.nci.common.persistence.hibernate.eqbe.Evaluator;
import java.util.List;
/**
* @author pandyas
*
* Impl class for the NomenclatureManager
*/
public class NomenclatureManagerImpl extends BaseManager implements NomenclatureManager {
/**
* Get a specific Nomenclature by id
*
* @param id
* the unique id for a Nomenclature
*
* @return the matching Nomenclature object, or null if not found.
*
* @exception Exception
* when anything goes wrong.
*/
public Nomenclature get(String id) throws Exception {
log.debug("In NomenclatureManagerImpl.get");
return (Nomenclature) super.get(id, Nomenclature.class);
}
public List getAll() throws Exception {
log.trace("In NomenclatureManagerImpl.getAll");
return super.getAll(Nomenclature.class);
}
/**
* Get the Nomenclature by it's name
*
* @param inName
* the name of the Nomenclature
*
* @return the Nomenclature that matches the name
*/
public Nomenclature getByName(String inName) throws Exception {
Nomenclature theNomenclature = null;
if (inName != null && inName.length() > 0) {
try {
// The following two objects are needed for eQBE.
Nomenclature theQueryObj = new Nomenclature();
theQueryObj.setName(inName);
// Apply evaluators to object properties
Evaluation theEvaluation = new Evaluation();
theEvaluation.addEvaluator("Nomenclature.inName",
Evaluator.EQUAL);
List theList = Search.query(theQueryObj, theEvaluation);
if (theList != null && theList.size() > 0) {
theNomenclature = (Nomenclature) theList.get(0);
}
} catch (PersistenceException pe) {
log.error("PersistenceException in getByName", pe);
throw pe;
} catch (Exception e) {
log.error("Exception in getByName", e);
throw e;
}
}
return theNomenclature;
}
public Nomenclature getOrCreate(String inName) throws Exception {
log.debug("<NomenclatureManagerImpl> Entering getOrCreate(String)");
Nomenclature theQBENomenclature = new Nomenclature();
theQBENomenclature.setName(inName);
Nomenclature theNomenclature = null;
try
{
List theList = Search.query(theQBENomenclature);
// Does exist - get object
if (theList != null && theList.size() > 0)
{
theNomenclature = (Nomenclature) theList.get(0);
}
// Doesn't exist. Create object with name
else
{
log.debug("<NomenclatureManagerImpl> No matching Nomenclature. Create new one");
theNomenclature = theQBENomenclature;
if (inName != null)
{
theQBENomenclature.setName(inName);
}
}
}
catch (Exception e)
{
log.error("Error querying for matching Nomenclature object. Creating new one.", e);
theNomenclature = theQBENomenclature;
}
log.debug("<NomenclatureManagerImpl> theNomenclature: " + theNomenclature.toString());
return theNomenclature;
}
}
|
package com.battlelancer.seriesguide.util;
import com.battlelancer.seriesguide.Constants;
import com.battlelancer.seriesguide.R;
import com.battlelancer.seriesguide.provider.SeriesContract.Shows;
import com.battlelancer.seriesguide.ui.SeriesGuidePreferences;
import com.battlelancer.thetvdbapi.ImageCache;
import com.jakewharton.trakt.ServiceManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.text.format.DateFormat;
import android.text.format.DateUtils;
import android.widget.ImageView;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.channels.FileChannel;
import java.text.DateFormatSymbols;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
public class Utils {
private static final int DEFAULT_BUFFER_SIZE = 8192;
private static ServiceManager sServiceManagerWithAuthInstance;
private static ServiceManager sServiceManagerInstance;
/**
* Returns the Calendar constant (e.g. <code>Calendar.SUNDAY</code>) for a
* given weekday string of the US locale. If no match is found
* <code>Calendar.SUNDAY</code> will be returned.
*
* @param day
* @return
*/
private static int getDayOfWeek(String day) {
DateFormatSymbols dfs = new DateFormatSymbols(Locale.US);
String[] weekdays = dfs.getWeekdays();
for (int i = 1; i < weekdays.length; i++) {
if (day.equalsIgnoreCase(weekdays[i])) {
return i;
}
}
return Calendar.SUNDAY;
}
public static String getDayShortcode(String day) {
return getDayShortcode(getDayOfWeek(day));
}
/**
* Returns the short version of the date symbol for the given weekday (e.g.
* <code>Calendar.SUNDAY</code>) in the user default locale.
*
* @param day
* @return
*/
public static String getDayShortcode(int day) {
DateFormatSymbols dfs = new DateFormatSymbols();
String[] weekdays = dfs.getShortWeekdays();
return weekdays[day];
}
/**
* Parses a TVDB date string and airtime in milliseconds to a relative
* timestring and day shortcode. An string is returned which holds the
* timestring and the day shortcode (in this order).
*
* @param tvdbDateString
* @param airtime
* @param ctx
* @return String array holding timestring and shortcode.
*/
public static String parseDateToLocalRelative(String tvdbDateString, long airtime, Context ctx) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ctx);
boolean useUserTimeZone = prefs.getBoolean(SeriesGuidePreferences.KEY_USE_MY_TIMEZONE,
false);
try {
Calendar cal = getLocalCalendar(tvdbDateString, airtime, useUserTimeZone, ctx);
Calendar now = Calendar.getInstance();
String day = "";
// Use midnight to compare if not airing today
if (!DateUtils.isToday(cal.getTimeInMillis())) {
int dayofweek = cal.get(Calendar.DAY_OF_WEEK);
DateFormatSymbols dfs = new DateFormatSymbols();
day = " (" + dfs.getShortWeekdays()[dayofweek] + ")";
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
now.set(Calendar.HOUR_OF_DAY, 0);
now.set(Calendar.MINUTE, 0);
now.set(Calendar.SECOND, 0);
now.set(Calendar.MILLISECOND, 0);
}
return DateUtils.getRelativeTimeSpanString(cal.getTimeInMillis(),
now.getTimeInMillis(), DateUtils.MINUTE_IN_MILLIS, DateUtils.FORMAT_ABBREV_ALL)
.toString()
+ day;
} catch (ParseException e) {
// shouldn't happen, if so there are errors in theTVDB
e.printStackTrace();
}
return "";
}
public static String parseDateToLocal(String tvdbDateString, long airtime, Context ctx) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ctx);
try {
Calendar local = getLocalCalendar(tvdbDateString, airtime,
prefs.getBoolean(SeriesGuidePreferences.KEY_USE_MY_TIMEZONE, false), ctx);
String timezone = local.getTimeZone().getDisplayName(true, TimeZone.SHORT);
String today = "";
if (DateUtils.isToday(local.getTimeInMillis())) {
today = ctx.getString(R.string.today) + ", ";
}
return today + DateFormat.getDateFormat(ctx).format(local.getTime()) + " " + timezone;
} catch (ParseException e) {
// shouldn't happen, if so there are errors in theTVDB
e.printStackTrace();
}
return "";
}
/**
* Returns a local calendar with the air time and date set. If
* useUserTimeZone is true time and date are converted from Pacific Time to
* the users time zone.
*
* @param tvdbDateString
* @param airtime
* @param useUserTimeZone
* @param context
* @return
* @throws ParseException
*/
public static Calendar getLocalCalendar(String tvdbDateString, long airtime,
boolean useUserTimeZone, Context context) throws ParseException {
Calendar cal;
if (useUserTimeZone) {
cal = Calendar.getInstance(TimeZone.getTimeZone("America/Los_Angeles"));
} else {
// use local calendar, e.g. for US based users where airtime is the
// same across time zones
cal = Calendar.getInstance();
}
// set airday
Date date = Constants.theTVDBDateFormat.parse(tvdbDateString);
cal.set(Calendar.DATE, date.getDate());
cal.set(Calendar.MONTH, date.getMonth());
cal.set(Calendar.YEAR, date.getYear() + 1900);
// set airtime
Calendar time = Calendar.getInstance(TimeZone.getTimeZone("America/Los_Angeles"));
time.setTimeInMillis(airtime);
cal.set(Calendar.HOUR_OF_DAY, time.get(Calendar.HOUR_OF_DAY));
cal.set(Calendar.MINUTE, time.get(Calendar.MINUTE));
cal.set(Calendar.SECOND, 0);
// add user-set hour offset
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
int offset = Integer.valueOf(prefs.getString(SeriesGuidePreferences.KEY_OFFSET, "0"));
cal.add(Calendar.HOUR_OF_DAY, offset);
// check for US Central and automagically subtract one hour
if (TimeZone.getDefault().getRawOffset() == TimeZone.getTimeZone("US/Central")
.getRawOffset()) {
cal.add(Calendar.HOUR_OF_DAY, -1);
}
if (useUserTimeZone) {
// convert to local timezone
Calendar local = Calendar.getInstance(TimeZone.getDefault(), Locale.getDefault());
local.setTime(cal.getTime());
return local;
} else {
return cal;
}
}
public static final SimpleDateFormat thetvdbTimeFormatAMPM = new SimpleDateFormat("h:mm aa",
Locale.US);
public static final SimpleDateFormat thetvdbTimeFormatAMPMalt = new SimpleDateFormat("h:mmaa",
Locale.US);
public static final SimpleDateFormat thetvdbTimeFormatAMPMshort = new SimpleDateFormat("h aa",
Locale.US);
public static final SimpleDateFormat thetvdbTimeFormatNormal = new SimpleDateFormat("H:mm",
Locale.US);
public static long parseTimeToMilliseconds(String tvdbTimeString) {
Date time = null;
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("America/Los_Angeles"));
// try parsing with three different formats, most of the time the first
// should match
if (tvdbTimeString.length() != 0) {
try {
time = thetvdbTimeFormatAMPM.parse(tvdbTimeString);
} catch (ParseException e) {
try {
time = thetvdbTimeFormatAMPMalt.parse(tvdbTimeString);
} catch (ParseException e1) {
try {
time = thetvdbTimeFormatAMPMshort.parse(tvdbTimeString);
} catch (ParseException e2) {
try {
time = thetvdbTimeFormatNormal.parse(tvdbTimeString);
} catch (ParseException e3) {
// string may be wrongly formatted
time = null;
}
}
}
}
}
if (time != null) {
cal.set(Calendar.HOUR_OF_DAY, time.getHours());
cal.set(Calendar.MINUTE, time.getMinutes());
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTimeInMillis();
} else {
return -1;
}
}
public static String[] parseMillisecondsToTime(long milliseconds, String dayofweek,
Context context) {
// return empty strings if time is missing
if (context == null || milliseconds == -1) {
return new String[] {
"", ""
};
}
final TimeZone pacificTimeZone = TimeZone.getTimeZone("America/Los_Angeles");
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
final boolean useUserTimeZone = prefs.getBoolean(
SeriesGuidePreferences.KEY_USE_MY_TIMEZONE, false);
// set calendar time and day on Pacific cal
final Calendar cal = Calendar.getInstance(pacificTimeZone);
cal.setTimeInMillis(milliseconds);
boolean isDaily = false;
if (dayofweek != null) {
if (dayofweek.equals("Daily")) {
isDaily = true;
} else {
cal.set(Calendar.DAY_OF_WEEK, getDayOfWeek(dayofweek));
}
}
setOffsets(prefs, cal);
// create time string
final java.text.DateFormat timeFormat = DateFormat.getTimeFormat(context);
final SimpleDateFormat dayFormat = new SimpleDateFormat("E");
final Date date = cal.getTime();
if (useUserTimeZone) {
timeFormat.setTimeZone(TimeZone.getDefault());
dayFormat.setTimeZone(TimeZone.getDefault());
} else {
// assume we are US Pacific based
timeFormat.setTimeZone(pacificTimeZone);
dayFormat.setTimeZone(pacificTimeZone);
}
String day = "";
if (isDaily) {
day = context.getString(R.string.daily);
} else if (dayofweek != null) {
day = dayFormat.format(date);
}
return new String[] {
timeFormat.format(date), day
};
}
/**
* Return an array with absolute time [0], day [1] and relative time [2] of
* the given millisecond time. Respects user offsets and 'Use my time zone'
* setting.
*
* @param airtime
* @param context
* @return
*/
public static String[] formatToTimeAndDay(long airtime, Context context) {
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
Calendar cal = getAirtimeCalendar(airtime, prefs);
// TODO introduce flags to exclude some values (speedier?)
final java.text.DateFormat timeFormat = DateFormat.getTimeFormat(context);
final SimpleDateFormat dayFormat = new SimpleDateFormat("E");
Date airDate = cal.getTime();
String day = dayFormat.format(airDate);
String absoluteTime = timeFormat.format(airDate);
String relativeTime = DateUtils
.getRelativeTimeSpanString(cal.getTimeInMillis(), System.currentTimeMillis(),
DateUtils.MINUTE_IN_MILLIS, DateUtils.FORMAT_ABBREV_ALL).toString();
return new String[] {
absoluteTime, day, relativeTime
};
}
/**
* Return date string of the given time, prefixed with 'today, ' if
* applicable.
*
* @param airtime
* @param context
* @return
*/
public static String formatToDate(long airtime, Context context) {
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
Calendar cal = getAirtimeCalendar(airtime, prefs);
TimeZone localTimeZone = cal.getTimeZone();
Date date = cal.getTime();
String timezone = localTimeZone.getDisplayName(localTimeZone.inDaylightTime(date),
TimeZone.SHORT);
String dateString = DateFormat.getDateFormat(context).format(date) + " " + timezone;
// add today prefix if applicable
if (DateUtils.isToday(cal.getTimeInMillis())) {
dateString = context.getString(R.string.today) + ", " + dateString;
}
return dateString;
}
/**
* Create a calendar set to the given airtime, time is adjusted according to
* 'Use my time zone', 'Time Offset' settings and user time zone.
*
* @param airtime
* @param prefs
* @return
*/
public static Calendar getAirtimeCalendar(long airtime, final SharedPreferences prefs) {
final boolean useUserTimeZone = prefs.getBoolean(
SeriesGuidePreferences.KEY_USE_MY_TIMEZONE, false);
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(airtime);
if (!useUserTimeZone) {
// assume we are US located
Calendar real = Calendar.getInstance(TimeZone.getTimeZone("America/Los_Angeles"));
real.setTimeInMillis(airtime);
// and airtime is not in LA but local time
cal.set(real.get(Calendar.YEAR), real.get(Calendar.MONTH),
real.get(Calendar.DAY_OF_MONTH), real.get(Calendar.HOUR_OF_DAY),
real.get(Calendar.MINUTE), real.get(Calendar.SECOND));
cal.set(Calendar.MILLISECOND, real.get(Calendar.MILLISECOND));
}
setOffsets(prefs, cal);
return cal;
}
/**
* Add user set manual offset and/or auto-offset if we are in US Central
* time zone.
*
* @param prefs
* @param cal
*/
private static void setOffsets(final SharedPreferences prefs, Calendar cal) {
// add user-set hour offset
int offset = Integer.valueOf(prefs.getString(SeriesGuidePreferences.KEY_OFFSET, "0"));
if (offset != 0) {
cal.add(Calendar.HOUR_OF_DAY, offset);
}
// check for US Central and automagically subtract one hour
if (TimeZone.getDefault().getRawOffset() == TimeZone.getTimeZone("US/Central")
.getRawOffset()) {
cal.add(Calendar.HOUR_OF_DAY, -1);
}
}
public static long buildEpisodeAirtime(String tvdbDateString, long airtime) {
TimeZone pacific = TimeZone.getTimeZone("America/Los_Angeles");
SimpleDateFormat tvdbDateFormat = Constants.theTVDBDateFormat;
tvdbDateFormat.setTimeZone(pacific);
try {
Date day = tvdbDateFormat.parse(tvdbDateString);
Calendar dayCal = Calendar.getInstance(pacific);
dayCal.setTime(day);
// set an airtime if we have one (may not be the case for ended
// shows)
if (airtime != -1) {
Calendar timeCal = Calendar.getInstance(pacific);
timeCal.setTimeInMillis(airtime);
dayCal.set(Calendar.HOUR_OF_DAY, timeCal.get(Calendar.HOUR_OF_DAY));
dayCal.set(Calendar.MINUTE, timeCal.get(Calendar.MINUTE));
dayCal.set(Calendar.SECOND, 0);
dayCal.set(Calendar.MILLISECOND, 0);
}
long episodeAirtime = dayCal.getTimeInMillis();
return episodeAirtime;
} catch (ParseException e) {
e.printStackTrace();
}
return -1;
}
/**
* Returns a string in format "1x01 title" or "S1E01 title" dependent on a
* user preference.
*/
public static String getNextEpisodeString(SharedPreferences prefs, String season,
String episode, String title) {
season = getEpisodeNumber(prefs, season, episode);
season += " " + title;
return season;
}
/**
* Returns the episode number formatted according to the users preference
* (e.g. '1x01', 'S01E01', ...).
*/
public static String getEpisodeNumber(SharedPreferences prefs, String season, String episode) {
String format = prefs.getString(SeriesGuidePreferences.KEY_NUMBERFORMAT,
SeriesGuidePreferences.NUMBERFORMAT_DEFAULT);
if (format.equals(SeriesGuidePreferences.NUMBERFORMAT_DEFAULT)) {
// 1x01 format
season += "x";
} else {
// S01E01 format
// make season number always two chars long
if (season.length() == 1) {
season = "0" + season;
}
if (format.equals(SeriesGuidePreferences.NUMBERFORMAT_ENGLISHLOWER))
season = "s" + season + "e";
else
season = "S" + season + "E";
}
// make episode number always two chars long
if (episode.length() == 1) {
season += "0";
}
season += episode;
return season;
}
/**
* Splits the string and reassembles it, separating the items with commas.
* The given object is returned with the new string.
*
* @param tvdbstring
* @return
*/
public static String splitAndKitTVDBStrings(String tvdbstring) {
String[] splitted = tvdbstring.split("\\|");
tvdbstring = "";
for (String item : splitted) {
if (tvdbstring.length() != 0) {
tvdbstring += ", ";
}
tvdbstring += item;
}
return tvdbstring;
}
/**
* Get the currently set episode sorting from settings.
*
* @param context
* @return a EpisodeSorting enum set to the current sorting
*/
public static Constants.EpisodeSorting getEpisodeSorting(Context context) {
String[] epsortingData = context.getResources().getStringArray(R.array.epsortingData);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context
.getApplicationContext());
String currentPref = prefs.getString("episodeSorting", epsortingData[1]);
Constants.EpisodeSorting sorting;
if (currentPref.equals(epsortingData[0])) {
sorting = Constants.EpisodeSorting.LATEST_FIRST;
} else if (currentPref.equals(epsortingData[1])) {
sorting = Constants.EpisodeSorting.OLDEST_FIRST;
} else if (currentPref.equals(epsortingData[2])) {
sorting = Constants.EpisodeSorting.UNWATCHED_FIRST;
} else if (currentPref.equals(epsortingData[3])) {
sorting = Constants.EpisodeSorting.ALPHABETICAL_ASC;
} else if (currentPref.equals(epsortingData[4])) {
sorting = Constants.EpisodeSorting.ALPHABETICAL_DESC;
} else if (currentPref.equals(epsortingData[5])) {
sorting = Constants.EpisodeSorting.DVDLATEST_FIRST;
} else {
sorting = Constants.EpisodeSorting.DVDOLDEST_FIRST;
}
return sorting;
}
public static boolean isHoneycombOrHigher() {
// Can use static final constants like HONEYCOMB, declared in later
// versions
// of the OS since they are inlined at compile time. This is guaranteed
// behavior.
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB;
}
public static boolean isFroyoOrHigher() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO;
}
public static boolean isExtStorageAvailable() {
return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
}
public static boolean isNetworkConnected(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
if (activeNetworkInfo != null) {
return activeNetworkInfo.isConnected();
}
return false;
}
public static boolean isWifiConnected(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo wifiNetworkInfo = connectivityManager
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (wifiNetworkInfo != null) {
return wifiNetworkInfo.isConnected();
}
return false;
}
public static void copyFile(File src, File dst) throws IOException {
FileChannel inChannel = new FileInputStream(src).getChannel();
FileChannel outChannel = new FileOutputStream(dst).getChannel();
try {
inChannel.transferTo(0, inChannel.size(), outChannel);
} finally {
if (inChannel != null) {
inChannel.close();
}
if (outChannel != null) {
outChannel.close();
}
}
}
public static int copy(InputStream input, OutputStream output) throws IOException {
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int count = 0;
int n = 0;
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
count += n;
}
return count;
}
/**
* Update the latest episode fields for all existing shows.
*/
public static void updateLatestEpisodes(Context context) {
Thread t = new UpdateLatestEpisodeThread(context);
t.start();
}
/**
* Update the latest episode field for a specific show.
*/
public static void updateLatestEpisode(Context context, String showId) {
Thread t = new UpdateLatestEpisodeThread(context, showId);
t.start();
}
public static class UpdateLatestEpisodeThread extends Thread {
private Context mContext;
private String mShowId;
public UpdateLatestEpisodeThread(Context context) {
mContext = context;
this.setName("UpdateLatestEpisode");
}
public UpdateLatestEpisodeThread(Context context, String showId) {
this(context);
mShowId = showId;
}
public void run() {
if (mShowId != null) {
// update single show
DBUtils.updateLatestEpisode(mContext, mShowId);
} else {
// update all shows
final Cursor shows = mContext.getContentResolver().query(Shows.CONTENT_URI,
new String[] {
Shows._ID
}, null, null, null);
while (shows.moveToNext()) {
String id = shows.getString(0);
DBUtils.updateLatestEpisode(mContext, id);
}
shows.close();
}
// Adapter gets notified by ContentProvider
}
}
/**
* Get the trakt-java ServiceManger with user credentials and our API key
* set.
*
* @param context
* @param refreshCredentials Set this flag to refresh the user credentials.
* @return
* @throws Exception When decrypting the password failed.
*/
public static synchronized ServiceManager getServiceManagerWithAuth(Context context,
boolean refreshCredentials) throws Exception {
if (sServiceManagerWithAuthInstance == null) {
sServiceManagerWithAuthInstance = new ServiceManager();
sServiceManagerWithAuthInstance.setApiKey(Constants.TRAKT_API_KEY);
// this made some problems, so sadly disabled for now
// manager.setUseSsl(true);
refreshCredentials = true;
}
if (refreshCredentials) {
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context
.getApplicationContext());
final String username = prefs.getString(SeriesGuidePreferences.KEY_TRAKTUSER, "");
String password = prefs.getString(SeriesGuidePreferences.KEY_TRAKTPWD, "");
password = SimpleCrypto.decrypt(password, context);
sServiceManagerWithAuthInstance.setAuthentication(username, password);
}
return sServiceManagerWithAuthInstance;
}
/**
* Get a trakt-java ServiceManager with just our API key set. NO user auth
* data.
*
* @return
*/
public static synchronized ServiceManager getServiceManager() {
if (sServiceManagerInstance == null) {
sServiceManagerInstance = new ServiceManager();
sServiceManagerInstance.setApiKey(Constants.TRAKT_API_KEY);
// this made some problems, so sadly disabled for now
// manager.setUseSsl(true);
}
return sServiceManagerInstance;
}
public static String getTraktUsername(Context context) {
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context
.getApplicationContext());
return prefs.getString(SeriesGuidePreferences.KEY_TRAKTUSER, "");
}
public static String getVersion(Context context) {
String version;
try {
version = context.getPackageManager().getPackageInfo(context.getPackageName(),
PackageManager.GET_META_DATA).versionName;
} catch (NameNotFoundException e) {
version = "UnknownVersion";
}
return version;
}
/**
* Put the TVDb season string in, get a full 'Season X' or 'Special
* Episodes' string out.
*
* @param context
* @param season
* @return
*/
public static String getSeasonString(Context context, String season) {
if (season.equals("0") || season.length() == 0) {
season = context.getString(R.string.specialseason);
} else {
season = context.getString(R.string.season) + " " + season;
}
return season;
}
/**
* If {@code isBusy} is {@code true}, then the image is only loaded if it is
* in memory. In every other case a place-holder is shown.
*
* @param poster
* @param path
* @param isBusy
* @param context TODO
*/
public static void setPosterBitmap(ImageView poster, String path, boolean isBusy,
Context context) {
Bitmap bitmap = null;
if (path.length() != 0) {
bitmap = ImageCache.getInstance(context).getThumb(path, isBusy);
}
if (bitmap != null) {
poster.setImageBitmap(bitmap);
poster.setTag(null);
} else {
// set placeholder
poster.setImageResource(R.drawable.show_generic);
// Non-null tag means the view still needs to load it's data
poster.setTag(path);
}
}
}
|
package list;
class Node<E> {
Node next;
E data;
Node() {
// TODO
}
Node(E data) {
// TODO
}
Node(Node next) {
// TODO
}
Node(E data, Node next) {
// TODO
}
Node getNext() {
// TODO
return null;
}
void setNext(Node newNext) {
// TODO
}
void setData(E newData) {
// TODO
}
E getData() {
// TODO
return null;
}
}
|
package gov.nih.nci.ncicb.cadsr.loader.event;
import gov.nih.nci.ncicb.cadsr.domain.*;
import gov.nih.nci.ncicb.cadsr.loader.ElementsLists;
import gov.nih.nci.ncicb.cadsr.loader.ReviewTracker;
import org.apache.log4j.Logger;
import java.util.*;
import gov.nih.nci.ncicb.cadsr.loader.persister.OCRRoleNameBuilder;
import gov.nih.nci.ncicb.cadsr.loader.util.*;
import gov.nih.nci.ncicb.cadsr.loader.defaults.*;
import gov.nih.nci.ncicb.cadsr.loader.ext.*;
import gov.nih.nci.ncicb.cadsr.loader.ChangeTracker;
import gov.nih.nci.ncicb.cadsr.loader.ReviewTrackerType;
import gov.nih.nci.ncicb.cadsr.loader.UserSelections;
import gov.nih.nci.ncicb.cadsr.loader.validator.ValidationError;
import gov.nih.nci.ncicb.cadsr.loader.validator.ValidationItems;
/**
* This class implements UMLHandler specifically to handle UML events and
* convert them into caDSR objects.<br/> The handler's responsibility is to
* transform events received into cadsr domain objects, and store those objects
* in the Elements List.
*
* @author <a href="mailto:ludetc@mail.nih.gov">Christophe Ludet</a>
*/
public class UMLDefaultHandler
implements UMLHandler, CadsrModuleListener, RunModeListener {
private ElementsLists elements;
private Logger logger = Logger.getLogger(UMLDefaultHandler.class.getName());
private List packageList = new ArrayList();
private ReviewTracker reviewTracker;
private CadsrModule cadsrModule;
// keeps track of the mapping between an oc and the DE that set it's public id
// key = oc Id / version
// Value = the DE that set oc id / version
private Map<String, DataElement> ocMapping = new HashMap<String, DataElement>();
private InheritedAttributeList inheritedAttributes = InheritedAttributeList.getInstance();
public UMLDefaultHandler() {
this.elements = ElementsLists.getInstance();
}
public void setRunMode(RunMode runMode) {
if(runMode.equals(RunMode.Curator)) {
reviewTracker = reviewTracker.getInstance(ReviewTrackerType.Curator);
} else {
reviewTracker = reviewTracker.getInstance(ReviewTrackerType.Owner);
}
}
public void newPackage(NewPackageEvent event) {
logger.info("Package: " + event.getName());
}
public void newOperation(NewOperationEvent event) {
logger.debug("Operation: " + event.getClassName() + "." +
event.getName());
}
public void newValueDomain(NewValueDomainEvent event) {
logger.info("Value Domain: " + event.getName());
List<Concept> concepts = createConcepts(event);
ValueDomain vd = DomainObjectFactory.newValueDomain();
vd.setLongName(event.getName());
vd.setPreferredDefinition(event.getDescription());
vd.setVdType(event.getType());
vd.setDataType(event.getDatatype());
ConceptualDomain cd = DomainObjectFactory.newConceptualDomain();
cd.setPublicId(event.getCdId());
cd.setVersion(event.getCdVersion());
// un comment the following to lookup CD.
// Map<String, Object> queryFields =
// new HashMap<String, Object>();
// queryFields.put(CadsrModule.PUBLIC_ID, event.getPersistenceId());
// queryFields.put(CadsrModule.VERSION, event.getPersistenceVersion());
// List<ConceptualDomain> result = null;
// try {
// result = new ArrayList<ConceptualDomain>(cadsrModule.findConceptualDomain(queryFields));
// } catch (Exception e){
// logger.error("Could not query cadsr module ", e);
// } // end of try-catch
// if(result.size() > 0) {
// cd = result.get(0);
vd.setConceptualDomain(cd);
// create CSI for package (since 3.2)
ClassificationSchemeItem csi = DomainObjectFactory.newClassificationSchemeItem();
String pName = event.getPackageName();
csi.setName(pName);
if (!packageList.contains(pName)) {
elements.addElement(csi);
packageList.add(pName);
}
AdminComponentClassSchemeClassSchemeItem acCsCsi = DomainObjectFactory.newAdminComponentClassSchemeClassSchemeItem();
ClassSchemeClassSchemeItem csCsi = DomainObjectFactory.newClassSchemeClassSchemeItem();
csCsi.setCsi(csi);
acCsCsi.setCsCsi(csCsi);
List l = new ArrayList();
l.add(acCsCsi);
vd.setAcCsCsis(l);
// if(concepts.size() > 0)
vd.setConceptDerivationRule(ConceptUtil.createConceptDerivationRule(concepts, true));
elements.addElement(vd);
reviewTracker.put(event.getName(), event.isReviewed());
}
public void newValueMeaning(NewValueMeaningEvent event) {
logger.info("Value Meaning: " + event.getName());
List<Concept> concepts = createConcepts(event);
// // is the NO_CONCEPT in there? if so, forget concepts for this.
// boolean noConcept = false;
// for(Concept con : concepts) {
// if(con.getPreferredName().equals(NO_CONCEPT_CODE))
// noConcept = true;
ValueDomain vd = LookupUtil.lookupValueDomain(event.getValueDomainName());
ValueMeaning vm = DomainObjectFactory.newValueMeaning();
vm.setLongName(event.getName());
vm.setLifecycle(UMLDefaults.getInstance().getLifecycle());
Concept[] vmConcepts = new Concept[concepts.size()];
concepts.toArray(vmConcepts);
// Definition vmAltDef = DomainObjectFactory.newDefinition();
// vmAltDef.setType(Definition.TYPE_UML_VM);
// if(!StringUtil.isEmpty(event.getDescription())) {
// vmAltDef.setDefinition(event.getDescription());
// } else {
// // vmAltDef.setDefinition(ValueMeaning.DEFAULT_DEFINITION);
// if this VM has concepts, then use evs definition
// if VM has no concept, then use user defined definition
if(concepts != null && concepts.size() > 0) {
vm.setPreferredDefinition(ConceptUtil
.preferredDefinitionFromConcepts(vmConcepts));
// if(!StringUtil.isEmpty(event.getDescription()))
// vm.addDefinition(vmAltDef);
} else {
if(!StringUtil.isEmpty(event.getDescription())) {
vm.setPreferredDefinition(event.getDescription());
} else
vm.setPreferredDefinition(ValueMeaning.DEFAULT_DEFINITION);
// if(!StringUtil.isEmpty(event.getDescription()))
// vm.addDefinition(vmAltDef);
}
// if(noConcept) {
// vm.setConceptDerivationRule(createConceptDerivationRule(new ArrayList<Concepts>()));
// } else {
vm.setConceptDerivationRule(ConceptUtil.createConceptDerivationRule(concepts, true));
PermissibleValue pv = DomainObjectFactory.newPermissibleValue();
pv.setValueMeaning(vm);
pv.setValue(event.getName());
vd.addPermissibleValue(pv);
AlternateName vmAltName = DomainObjectFactory.newAlternateName();
vmAltName.setType(AlternateName.TYPE_UML_VM);
vmAltName.setName(event.getName());
vm.addAlternateName(vmAltName);
if(!StringUtil.isEmpty(event.getDescription())) {
Definition vmAltDef = DomainObjectFactory.newDefinition();
vmAltDef.setType(Definition.TYPE_UML_VM);
vmAltDef.setDefinition(event.getDescription());
vm.addDefinition(vmAltDef);
}
elements.addElement(vm);
reviewTracker.put("ValueDomains." + event.getValueDomainName() + "." + event.getName(), event.isReviewed());
}
public void newClass(NewClassEvent event) {
logger.info("Class: " + event.getName());
List<Concept> concepts = createConcepts(event);
ObjectClass oc = DomainObjectFactory.newObjectClass();
// store concept codes in preferredName
oc.setPreferredName(ConceptUtil.preferredNameFromConcepts(concepts));
oc.setLongName(event.getName());
if(event.getDescription() != null && event.getDescription().length() > 0)
oc.setPreferredDefinition(event.getDescription());
else
oc.setPreferredDefinition("");
elements.addElement(oc);
reviewTracker.put(event.getName(), event.isReviewed());
ClassificationSchemeItem csi = DomainObjectFactory.newClassificationSchemeItem();
String pName = event.getPackageName();
csi.setName(pName);
if (!packageList.contains(pName)) {
elements.addElement(csi);
packageList.add(pName);
}
// Store package names
AdminComponentClassSchemeClassSchemeItem acCsCsi = DomainObjectFactory.newAdminComponentClassSchemeClassSchemeItem();
ClassSchemeClassSchemeItem csCsi = DomainObjectFactory.newClassSchemeClassSchemeItem();
csCsi.setCsi(csi);
acCsCsi.setCsCsi(csCsi);
List l = new ArrayList();
l.add(acCsCsi);
oc.setAcCsCsis(l);
AlternateName fullName = DomainObjectFactory.newAlternateName();
fullName.setType(AlternateName.TYPE_CLASS_FULL_NAME);
fullName.setName(event.getName());
AlternateName className = DomainObjectFactory.newAlternateName();
className.setType(AlternateName.TYPE_UML_CLASS);
className.setName(event.getName().substring(event.getName().lastIndexOf(".") + 1));
oc.addAlternateName(fullName);
oc.addAlternateName(className);
}
public void newAttribute(NewAttributeEvent event) {
logger.info("Attribute: " + event.getClassName() + "." +
event.getName());
DataElement de = DomainObjectFactory.newDataElement();
// populate if there is valid existing mapping
DataElement existingDe = null;
if(event.getPersistenceId() != null) {
Map<String, Object> queryFields =
new HashMap<String, Object>();
queryFields.put(CadsrModule.PUBLIC_ID, event.getPersistenceId());
queryFields.put(CadsrModule.VERSION, event.getPersistenceVersion());
List<DataElement> result = null;
try {
result = new ArrayList<DataElement>(cadsrModule.findDataElement(queryFields));
} catch (Exception e){
logger.error("Could not query cadsr module ", e);
} // end of try-catch
if(result.size() == 0) {
ChangeTracker changeTracker = ChangeTracker.getInstance();
// ValidationItems.getInstance()
// .addItem(new ValidationError(PropertyAccessor.getProperty("de.doesnt.exist", new String[]
// {event.getClassName() + "." + event.getName(),
// ConventionUtil.publicIdVersion(de)}), de));
ValidationItems.getInstance()
.addItem(new ValidationError(PropertyAccessor.getProperty("de.doesnt.exist", event.getClassName() + "." + event.getName(),
event.getPersistenceId() + "v" + event.getPersistenceVersion()), de));
de.setPublicId(null);
de.setVersion(null);
changeTracker.put
(event.getClassName() + "." + event.getName(),
true);
} else {
existingDe = result.get(0);
}
}
List concepts = createConcepts(event);
Property prop = DomainObjectFactory.newProperty();
// store concept codes in preferredName
prop.setPreferredName(ConceptUtil.preferredNameFromConcepts(concepts));
// prop.setPreferredName(event.getName());
prop.setLongName(event.getName());
String propName = event.getName();
String s = event.getClassName();
int ind = s.lastIndexOf(".");
String className = s.substring(ind + 1);
String packageName = s.substring(0, ind);
DataElementConcept dec = DomainObjectFactory.newDataElementConcept();
dec.setLongName(className + ":" + propName);
dec.setProperty(prop);
logger.debug("DEC LONG_NAME: " + dec.getLongName());
ObjectClass oc = DomainObjectFactory.newObjectClass();
List<ObjectClass> ocs = elements.getElements(oc);
for (ObjectClass o : ocs) {
String fullClassName = null;
for(AlternateName an : o.getAlternateNames()) {
if(an.getType().equals(AlternateName.TYPE_CLASS_FULL_NAME))
fullClassName = an.getName();
}
if (fullClassName.equals(event.getClassName())) {
oc = o;
}
}
if(existingDe != null) {
if(oc.getPublicId() != null) {
// Verify conflicts
if(!existingDe.getDataElementConcept().getObjectClass().getPublicId().equals(oc.getPublicId()) || !existingDe.getDataElementConcept().getObjectClass().getVersion().equals(oc.getVersion())) {
// Oc was already mapped by an existing DE. This DE conflicts with the previous mapping.
ValidationItems.getInstance()
.addItem(new ValidationError(PropertyAccessor.getProperty("de.conflict", new String[]
{event.getClassName() + "." + event.getName(),
ocMapping.get(ConventionUtil.publicIdVersion(oc)).getLongName()}), de));
}
} else {
oc.setPublicId(existingDe.getDataElementConcept().getObjectClass().getPublicId());
oc.setVersion(existingDe.getDataElementConcept().getObjectClass().getVersion());
// Keep track so if there's conflict, we know both ends of the conflict
ocMapping.put(ConventionUtil.publicIdVersion(oc), de);
oc.setLongName(existingDe.getDataElementConcept().getObjectClass().getLongName());
oc.setPreferredName("");
ChangeTracker changeTracker = ChangeTracker.getInstance();
changeTracker.put
(event.getClassName(),
true);
}
prop.setPublicId(existingDe.getDataElementConcept().getProperty().getPublicId());
prop.setVersion(existingDe.getDataElementConcept().getProperty().getVersion());
}
dec.setObjectClass(oc);
if(existingDe != null) {
de.setLongName(existingDe.getLongName());
de.setContext(existingDe.getContext());
de.setPublicId(existingDe.getPublicId());
de.setVersion(existingDe.getVersion());
de.setLatestVersionIndicator(existingDe.getLatestVersionIndicator());
de.setValueDomain(existingDe.getValueDomain());
} else {
de.setLongName(dec.getLongName() + " " + event.getType());
// de.setPreferredDefinition(event.getDescription());
String datatype = event.getType().trim();
if(DatatypeMapping.getKeys().contains(datatype.toLowerCase()))
datatype = DatatypeMapping.getMapping().get(datatype.toLowerCase());
ValueDomain vd = DomainObjectFactory.newValueDomain();
vd.setLongName(datatype);
ValueDomain existingVd = null;
if(event.getTypeId() != null) {
Map<String, Object> queryFields =
new HashMap<String, Object>();
queryFields.put(CadsrModule.PUBLIC_ID, event.getTypeId());
queryFields.put(CadsrModule.VERSION, event.getTypeVersion());
List<ValueDomain> result = null;
try {
result = new ArrayList<ValueDomain>(cadsrModule.findValueDomain(queryFields));
} catch (Exception e){
logger.error("Could not query cadsr module ", e);
} // end of try-catch
if(result.size() == 0) {
ChangeTracker changeTracker = ChangeTracker.getInstance();
// ValidationItems.getInstance()
// .addItem(new ValidationError(PropertyAccessor.getProperty("de.doesnt.exist", new String[]
// {event.getClassName() + "." + event.getName(),
// ConventionUtil.publicIdVersion(de)}), de));
ValidationItems.getInstance()
.addItem(new ValidationError(PropertyAccessor.getProperty("vd.doesnt.exist", event.getClassName() + "." + event.getName(),
event.getTypeId() + "v" + event.getTypeVersion()), de));
vd.setPublicId(null);
vd.setVersion(null);
changeTracker.put
(event.getClassName() + "." + event.getName(),
true);
} else {
existingVd = result.get(0);
vd.setLongName(existingVd.getLongName());
vd.setPublicId(existingVd.getPublicId());
vd.setVersion(existingVd.getVersion());
vd.setContext(existingVd.getContext());
vd.setDataType(existingVd.getDataType());
}
}
de.setValueDomain(vd);
}
logger.debug("DE LONG_NAME: " + de.getLongName());
de.setDataElementConcept(dec);
// Store alt Name for DE:
// packageName.ClassName.PropertyName
AlternateName fullName = DomainObjectFactory.newAlternateName();
fullName.setType(AlternateName.TYPE_FULL_NAME);
fullName.setName(packageName + "." + className + "." + propName);
de.addAlternateName(fullName);
// Store alt Name for DE:
// ClassName:PropertyName
fullName = DomainObjectFactory.newAlternateName();
fullName.setType(AlternateName.TYPE_UML_DE);
fullName.setName(className + ":" + propName);
de.addAlternateName(fullName);
if(!StringUtil.isEmpty(event.getDescription())) {
Definition altDef = DomainObjectFactory.newDefinition();
altDef.setType(Definition.TYPE_UML_DE);
altDef.setDefinition(event.getDescription());
de.addDefinition(altDef);
altDef = DomainObjectFactory.newDefinition();
altDef.setType(Definition.TYPE_UML_DEC);
altDef.setDefinition(event.getDescription());
dec.addDefinition(altDef);
}
// Add packages to Prop, DE and DEC.
prop.setAcCsCsis(oc.getAcCsCsis());
de.setAcCsCsis(oc.getAcCsCsis());
dec.setAcCsCsis(oc.getAcCsCsis());
reviewTracker.put(event.getClassName() + "." + event.getName(), event.isReviewed());
elements.addElement(de);
elements.addElement(dec);
elements.addElement(prop);
}
public void newInterface(NewInterfaceEvent event) {
logger.debug("Interface: " + event.getName());
}
public void newStereotype(NewStereotypeEvent event) {
logger.debug("Stereotype: " + event.getName());
}
public void newDataType(NewDataTypeEvent event) {
logger.debug("DataType: " + event.getName());
}
public void newAssociation(NewAssociationEvent event) {
ObjectClassRelationship ocr = DomainObjectFactory.newObjectClassRelationship();
ObjectClass oc = DomainObjectFactory.newObjectClass();
NewAssociationEndEvent aEvent = event.getAEvent();
NewAssociationEndEvent bEvent = event.getBEvent();
NewAssociationEndEvent sEvent = null;
NewAssociationEndEvent tEvent = null;
List<ObjectClass> ocs = elements.getElements(oc);
boolean aDone = false,
bDone = false;
for(ObjectClass o : ocs) {
String classFullName = null;
for(AlternateName an : o.getAlternateNames()) {
if(an.getType().equals(AlternateName.TYPE_CLASS_FULL_NAME))
classFullName = an.getName();
}
if (classFullName == null) {
System.err.println("No full class name found for "+o.getLongName());
continue;
}
if (!aDone && (classFullName.equals(aEvent.getClassName()))) {
if (event.getDirection().equals("B")) {
sEvent = aEvent;
ocr.setSource(o);
ocr.setSourceRole(aEvent.getRoleName());
ocr.setSourceLowCardinality(aEvent.getLowCardinality());
ocr.setSourceHighCardinality(aEvent.getHighCardinality());
} else {
tEvent = aEvent;
ocr.setTarget(o);
ocr.setTargetRole(aEvent.getRoleName());
ocr.setTargetLowCardinality(aEvent.getLowCardinality());
ocr.setTargetHighCardinality(aEvent.getHighCardinality());
}
aDone = true;
}
if (!bDone && (classFullName.equals(bEvent.getClassName()))) {
if (event.getDirection().equals("B")) {
tEvent = bEvent;
ocr.setTarget(o);
ocr.setTargetRole(bEvent.getRoleName());
ocr.setTargetLowCardinality(bEvent.getLowCardinality());
ocr.setTargetHighCardinality(bEvent.getHighCardinality());
} else {
sEvent = bEvent;
ocr.setSource(o);
ocr.setSourceRole(bEvent.getRoleName());
ocr.setSourceLowCardinality(bEvent.getLowCardinality());
ocr.setSourceHighCardinality(bEvent.getHighCardinality());
}
bDone = true;
}
}
if (event.getDirection().equals("AB")) {
ocr.setDirection(ObjectClassRelationship.DIRECTION_BOTH);
} else {
ocr.setDirection(ObjectClassRelationship.DIRECTION_SINGLE);
}
ocr.setLongName(event.getRoleName());
ocr.setType(ObjectClassRelationship.TYPE_HAS);
if(event.getConcepts() != null && event.getConcepts().size() > 0)
ocr.setConceptDerivationRule(
ConceptUtil.createConceptDerivationRule(createConcepts(event), true));
if(sEvent.getConcepts() != null && sEvent.getConcepts().size() > 0)
ocr.setSourceRoleConceptDerivationRule(
ConceptUtil.createConceptDerivationRule(createConcepts(sEvent), true));
if(tEvent.getConcepts() != null && tEvent.getConcepts().size() > 0)
ocr.setTargetRoleConceptDerivationRule(
ConceptUtil.createConceptDerivationRule(createConcepts(tEvent), true));
if(!aDone)
logger.debug("!aDone: " + aEvent.getClassName() + " -- " + bEvent.getClassName());
if(!bDone)
logger.debug("!bDone: " + aEvent.getClassName() + " -- " + bEvent.getClassName());
elements.addElement(ocr);
OCRRoleNameBuilder nameBuilder = new OCRRoleNameBuilder();
String fullName = nameBuilder.buildRoleName(ocr);
reviewTracker.put(fullName, event.isReviewed());
reviewTracker.put(fullName+" Source", sEvent.isReviewed());
reviewTracker.put(fullName+" Target", tEvent.isReviewed());
}
public void newGeneralization(NewGeneralizationEvent event) {
ObjectClassRelationship ocr = DomainObjectFactory.newObjectClassRelationship();
ObjectClass oc = DomainObjectFactory.newObjectClass();
AlternateName an = DomainObjectFactory.newAlternateName();
an.setName(event.getParentClassName());
an.setType(AlternateName.TYPE_CLASS_FULL_NAME);
ocr.setTarget(LookupUtil.lookupObjectClass(an));
an.setName(event.getChildClassName());
ocr.setSource(LookupUtil.lookupObjectClass(an));
ocr.setType(ObjectClassRelationship.TYPE_IS);
// Inherit all attributes
// Find all DECs:
ObjectClass parentOc = ocr.getTarget(),
childOc = ocr.getSource();
List newElts = new ArrayList();
List<DataElement> des = elements.getElements(DomainObjectFactory.newDataElement());
if(des != null)
for(DataElement de : des) {
DataElementConcept dec = de.getDataElementConcept();
if(dec.getObjectClass() == parentOc) {
// We found property belonging to parent
// Duplicate it for child.
// Property newProp = DomainObjectFactory.newProperty();
// newProp.setLongName(dec.getProperty().getLongName());
// newProp.setPreferredName(dec.getProperty().getPreferredName());
DataElementConcept newDec = DomainObjectFactory.newDataElementConcept();
newDec.setProperty(dec.getProperty());
newDec.setObjectClass(childOc);
// for(Definition def : dec.getDefinitions()) {
// newDec.addDefinition(def);
String propName = newDec.getProperty().getLongName();
String s = event.getChildClassName();
int ind = s.lastIndexOf(".");
String className = s.substring(ind + 1);
String packageName = s.substring(0, ind);
newDec.setLongName(className + ":" + propName);
DataElement newDe = DomainObjectFactory.newDataElement();
newDe.setDataElementConcept(newDec);
newDe.setValueDomain(de.getValueDomain());
newDe.setLongName(newDec.getLongName() + " " + de.getValueDomain().getLongName());
for(Definition def : de.getDefinitions()) {
if(def.getType().equals(Definition.TYPE_UML_DE)) {
Definition newDef = DomainObjectFactory.newDefinition();
newDef.setType(Definition.TYPE_UML_DE);
newDef.setDefinition(childOc.getPreferredDefinition() + " " + def.getDefinition());
newDe.addDefinition(newDef);
}
}
AlternateName fullName = DomainObjectFactory.newAlternateName();
fullName.setType(AlternateName.TYPE_FULL_NAME);
fullName.setName(packageName + "." + className + "." + propName);
newDe.addAlternateName(fullName);
// Store alt Name for DE:
// ClassName:PropertyName
fullName = DomainObjectFactory.newAlternateName();
fullName.setType(AlternateName.TYPE_UML_DE);
fullName.setName(className + ":" + propName);
newDe.addAlternateName(fullName);
// for(Iterator it2 = de.getAlternateNames().iterator(); it2.hasNext();) {
// AlternateName an = (AlternateName)it2.next();
// newDe.addAlternateName(an);
newDe.setAcCsCsis(childOc.getAcCsCsis());
newDec.setAcCsCsis(childOc.getAcCsCsis());
Property oldProp = de.getDataElementConcept().getProperty();
List oldAcCsCsis = oldProp.getAcCsCsis();
List newAcCsCsis = new ArrayList(childOc.getAcCsCsis());
newAcCsCsis.addAll(oldAcCsCsis);
oldProp.setAcCsCsis(newAcCsCsis);
// newElts.add(newProp);
newElts.add(newDe);
newElts.add(newDec);
inheritedAttributes.add(newDe);
}
}
for(Iterator it = newElts.iterator(); it.hasNext();
elements.addElement(it.next()));
elements.addElement(ocr);
logger.debug("Generalization: ");
logger.debug("Source:");
logger.debug("-- " + ocr.getSource().getLongName());
logger.debug("Target: ");
if(ocr.getTarget() != null)
logger.debug("-- " + ocr.getTarget().getLongName());
else {
logger.error("Target does not exist: ");
logger.error("Parent: " + event.getParentClassName());
}
}
private Concept newConcept(NewConceptEvent event) {
Concept concept = DomainObjectFactory.newConcept();
concept.setPreferredName(event.getConceptCode());
concept.setPreferredDefinition(event.getConceptDefinition());
concept.setDefinitionSource(event.getConceptDefinitionSource());
concept.setLongName(event.getConceptPreferredName());
elements.addElement(concept);
return concept;
}
private List<Concept> createConcepts(NewConceptualEvent event) {
List<Concept> concepts = new ArrayList<Concept>();
List<NewConceptEvent> conEvs = event.getConcepts();
for(NewConceptEvent conEv : conEvs) {
concepts.add(newConcept(conEv));
}
return concepts;
}
private void verifyConcepts(AdminComponent cause, List concepts) {
for(Iterator it = concepts.iterator(); it.hasNext(); ) {
Concept concept = (Concept)it.next();
if(StringUtil.isEmpty(concept.getPreferredName())) {
ValidationItems.getInstance()
.addItem(new ValidationError(
PropertyAccessor.getProperty("validation.concept.missing.for", cause.getLongName()),
cause));
// elements.addElement(new ConceptError(
// ConceptError.SEVERITY_ERROR,
// PropertyAccessor.getProperty("validation.concept.missing.for", eltName)));
}
}
}
public void setCadsrModule(CadsrModule module) {
this.cadsrModule = module;
}
public void beginParsing() {}
public void endParsing() {}
public void addProgressListener(ProgressListener listener) {}
}
|
package com.astoev.cave.survey.activity.main;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseArray;
import android.util.SparseIntArray;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import com.astoev.cave.survey.Constants;
import com.astoev.cave.survey.R;
import com.astoev.cave.survey.activity.MainMenuActivity;
import com.astoev.cave.survey.activity.UIUtilities;
import com.astoev.cave.survey.activity.home.HomeActivity;
import com.astoev.cave.survey.activity.map.MapActivity;
import com.astoev.cave.survey.activity.map.MapUtilities;
import com.astoev.cave.survey.activity.map.opengl.Map3DActivity;
import com.astoev.cave.survey.model.Gallery;
import com.astoev.cave.survey.model.Leg;
import com.astoev.cave.survey.model.Note;
import com.astoev.cave.survey.model.Photo;
import com.astoev.cave.survey.model.Point;
import com.astoev.cave.survey.model.Project;
import com.astoev.cave.survey.model.Sketch;
import com.astoev.cave.survey.util.DaoUtil;
import com.astoev.cave.survey.util.PointUtil;
import com.astoev.cave.survey.util.StringUtils;
import com.j256.ormlite.misc.TransactionManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
public class MainActivity extends MainMenuActivity {
private static final int[] ADD_ITEM_LABELS = {R.string.main_add_leg,
R.string.main_add_branch,
// R.string.main_add_middlepoint
};
private SparseIntArray mGalleryColors;
private SparseArray<String> mGalleryNames;
private static boolean isDebug = false;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
private void drawTable() {
try {
Leg activeLeg = getWorkspace().getActiveLeg();
if (activeLeg == null) {
activeLeg = getWorkspace().getLastLeg();
getWorkspace().setActiveLeg(activeLeg);
}
Integer currGalleryId = getWorkspace().getActiveGalleryId();
if (currGalleryId == null) {
getWorkspace().setActiveGalleryId(activeLeg.getGalleryId());
}
mGalleryColors = new SparseIntArray();
mGalleryNames = new SparseArray<String>();
// prepare labels
TextView activeLegName = (TextView) findViewById(R.id.mainActiveLeg);
activeLegName.setText(activeLeg.buildLegDescription());
TableLayout table = (TableLayout) findViewById(R.id.mainTable);
Log.i(Constants.LOG_TAG_UI, "Found " + table);
// prepare grid
table.removeAllViews();
List<Leg> legs = DaoUtil.getCurrProjectLegs();
boolean currentLeg;
Integer lastGalleryId = null, prevGalleryId;
for (final Leg l : legs) {
TableRow row = new TableRow(this);
LayoutParams params = new TableLayout.LayoutParams(0, LayoutParams.WRAP_CONTENT, 1);
row.setLayoutParams(params);
row.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View aView) {
Intent intent = new Intent(MainActivity.this, PointActivity.class);
intent.putExtra(Constants.LEG_SELECTED, l.getId());
getWorkspace().setActiveLegId(l.getId());
getWorkspace().setActiveGalleryId(l.getGalleryId());
startActivity(intent);
}
});
currentLeg = getWorkspace().getActiveLegId().equals(l.getId());
if (currentLeg) {
row.setBackgroundColor(Color.GRAY);
}
if (mGalleryColors.get(l.getGalleryId(), Constants.NOT_FOUND) == Constants.NOT_FOUND) {
Gallery gallery = DaoUtil.getGallery(l.getGalleryId());
mGalleryColors.put(l.getGalleryId(), MapUtilities.getNextGalleryColor(mGalleryColors.size()));
mGalleryNames.put(l.getGalleryId(), gallery.getName());
}
Point fromPoint = l.getFromPoint();
DaoUtil.refreshPoint(fromPoint);
String fromPointString = fromPoint.getName();
if (lastGalleryId == null) {
lastGalleryId = l.getGalleryId();
}
if (l.getGalleryId().equals(lastGalleryId)) {
fromPointString = mGalleryNames.get(l.getGalleryId()) + fromPointString;
prevGalleryId = l.getGalleryId();
} else {
prevGalleryId = DaoUtil.getLegByToPoint(l.getFromPoint()).getGalleryId();
fromPointString = mGalleryNames.get(prevGalleryId) + fromPointString;
}
Point toPoint = l.getToPoint();
DaoUtil.refreshPoint(toPoint);
String toPointString = mGalleryNames.get(l.getGalleryId()) + toPoint.getName();
lastGalleryId = l.getGalleryId();
if (isDebug){
fromPointString = fromPointString +"(" + fromPoint.getId() + ")";
toPointString = toPointString + "("+toPoint.getId()+")";
}
row.addView(createTextView(fromPointString, currentLeg, false, mGalleryColors.get(prevGalleryId)));
row.addView(createTextView(toPointString, currentLeg, false, mGalleryColors.get(l.getGalleryId())));
row.addView(createTextView(l.getDistance(), currentLeg, true));
row.addView(createTextView(l.getAzimuth(), currentLeg, true));
row.addView(createTextView(l.getSlope(), currentLeg, true));
//TODO build SNP string
StringBuilder moreText = new StringBuilder();
//TODO Debug
if (isDebug){
moreText.append(l.getGalleryId()).append(" ");
}
Sketch sketch = DaoUtil.getScetchByLeg(l);
if (sketch != null){
moreText.append(getString(R.string.table_sketch_prefix));
}
Note note = DaoUtil.getActiveLegNote(l);
if (note != null){
moreText.append(getString(R.string.table_note_prefix));
}
Photo photo = DaoUtil.getPhotoByLeg(l);
if (photo != null) {
moreText.append(getString(R.string.table_photo_prefix));
}
//TODO add sketch and photo here
row.addView(createTextView(moreText.toString(), currentLeg, true));
table.addView(row, params);
}
table.invalidate();
} catch (Exception e) {
Log.e(Constants.LOG_TAG_UI, "Failed to render main activity", e);
UIUtilities.showNotification(R.string.error);
}
}
private TextView createTextView(Float aMeasure, boolean isCurrentLeg, boolean allowEditing) {
return createTextView(StringUtils.floatToLabel(aMeasure), isCurrentLeg, allowEditing);
}
private TextView createTextView(String aText, boolean isCurrentLeg, boolean allowEditing) {
TextView edit = new TextView(this);
edit.setLines(1);
if (aText != null) {
edit.setText(aText);
}
edit.setGravity(Gravity.CENTER);
if (!isCurrentLeg || !allowEditing) {
edit.setEnabled(false);
}
return edit;
}
private TextView createTextView(String aText, boolean isCurrentLeg, boolean allowEditing, int aColor) {
TextView edit = createTextView(aText, isCurrentLeg, allowEditing);
edit.setTextColor(aColor);
return edit;
}
public void addButtonClick() {
Log.i(Constants.LOG_TAG_UI, "Adding");
final String[] labels = new String[ADD_ITEM_LABELS.length];
for (int i = 0; i < ADD_ITEM_LABELS.length; i++) {
labels[i] = getString(ADD_ITEM_LABELS[i]);
}
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.main_add_title);
builder.setSingleChoiceItems(labels, -1, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
try {
if (0 == item) {
addLeg(false);
} else if (1 == item) {
addLeg(true);
} else if (2 == item) {
// requestLengthAndAddMiddle();
UIUtilities.showNotification(R.string.todo);
}
} catch (Exception e) {
Log.e(Constants.LOG_TAG_UI, "Error adding", e);
UIUtilities.showNotification(R.string.error);
}
}
});
AlertDialog alert = builder.create();
alert.show();
}
private void requestLengthAndAddMiddle() throws SQLException {
LayoutInflater li = LayoutInflater.from(this);
View promptsView = li.inflate(R.layout.number_popup, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setView(promptsView);
final EditText userInput = (EditText) promptsView.findViewById(R.id.popup_distance);
final Leg currLeg = getWorkspace().getActiveOrFirstLeg();
// set dialog message
alertDialogBuilder
.setCancelable(true)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Float distance = StringUtils.getFromEditTextNotNull(userInput);
if (null == distance) {
UIUtilities.showNotification(R.string.popup_bad_input);
dialog.cancel();
return;
}
if (currLeg.getDistance() != null && currLeg.getDistance().floatValue() <= distance.floatValue()) {
UIUtilities.showNotification(R.string.popup_bad_input);
dialog.cancel();
return;
}
try {
addMiddle(distance.floatValue());
} catch (SQLException e) {
Log.e(Constants.LOG_TAG_UI, "Error adding", e);
UIUtilities.showNotification(R.string.error);
}
dialog.cancel();
}
})
.setNegativeButton("Back",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
private void addMiddle(final float atDistance) throws SQLException {
Log.i(Constants.LOG_TAG_UI, "Creating middle point");
Integer newLegId = TransactionManager.callInTransaction(getWorkspace().getDBHelper().getConnectionSource(),
new Callable<Integer>() {
public Integer call() throws Exception {
try {
Leg activeLeg = getWorkspace().getActiveLeg();
float activeLegOrigDistance = activeLeg.getDistance();
// another leg, starting from the current leg and in new gallery
Point newFrom = activeLeg.getFromPoint();
Point oldToPoint = activeLeg.getToPoint();
DaoUtil.refreshPoint(newFrom);
DaoUtil.refreshPoint(oldToPoint);
// create new point
Point newMiddlePoint = PointUtil.generateMiddlePoint(newFrom);
getWorkspace().getDBHelper().getPointDao().create(newMiddlePoint);
// split the old leg - update the existing and add new one
activeLeg.setToPoint(newMiddlePoint);
activeLeg.setDistance(atDistance);
getWorkspace().getDBHelper().getLegDao().update(activeLeg);
Leg newLeg = new Leg(newMiddlePoint, oldToPoint, activeLeg.getProject(), activeLeg.getGalleryId());
// copy measurements to the new leg
newLeg.setAzimuth(activeLeg.getAzimuth());
newLeg.setDistance(activeLegOrigDistance - atDistance);
newLeg.setLeft(activeLeg.getLeft());
newLeg.setRight(activeLeg.getRight());
newLeg.setTop(activeLeg.getTop());
newLeg.setDown(activeLeg.getDown());
getWorkspace().getDBHelper().getLegDao().create(newLeg);
return newLeg.getId();
} catch (Exception e) {
Log.e(Constants.LOG_TAG_DB, "Failed to add middle point", e);
throw e;
}
}
}
);
if (newLegId != null)
{
getWorkspace().setActiveLegId(newLegId);
Intent intent = new Intent(MainActivity.this, PointActivity.class);
intent.putExtra(Constants.LEG_SELECTED, newLegId);
startActivity(intent);
} else
{
UIUtilities.showNotification(R.string.error);
}
}
private void addLeg(final boolean isDeviation) throws SQLException {
Log.i(Constants.LOG_TAG_UI, "Creating leg");
/* Integer newLegId = TransactionManager.callInTransaction(getWorkspace().getDBHelper().getConnectionSource(),
new Callable<Integer>() {
public Integer call() throws Exception {
try {
Leg activeLeg = (Leg) getWorkspace().getDBHelper().getLegDao().queryForId(getWorkspace().getActiveLegId());
if (isDeviation) {
// another leg, starting from the current leg and in new gallery
Point newFrom = activeLeg.getFromPoint();
getWorkspace().getDBHelper().getPointDao().refresh(newFrom);
Point newTo = PointUtil.generateDeviationPoint(newFrom);
getWorkspace().getDBHelper().getPointDao().create(newTo);
Gallery newGallery = new Gallery();
// TODO read name ?
newGallery.setName(newFrom.getName());
getWorkspace().getDBHelper().getGalleryDao().create(newGallery);
Leg nextLeg = new Leg(newFrom, newTo, getWorkspace().getActiveProject(), newGallery.getId());
getWorkspace().getDBHelper().getLegDao().create(nextLeg);
return nextLeg.getId();
} else {
// another leg, starting from the latest in the gallery
Point newFrom = (Point) getWorkspace().getLastGalleryPoint(activeLeg.getGalleryId());
Point newTo = PointUtil.generateNextPoint(activeLeg.getGalleryId());
getWorkspace().getDBHelper().getPointDao().create(newTo);
Leg nextLeg = new Leg(newFrom, newTo, getWorkspace().getActiveProject(), activeLeg.getGalleryId());
getWorkspace().getDBHelper().getLegDao().create(nextLeg);
return nextLeg.getId();
}
} catch (Exception e) {
Log.e(Constants.LOG_TAG_DB, "Failed to add leg", e);
throw e;
}
}
});*/
// if (newLegId != null) {
// getWorkspace().setActiveLegId(newLegId);
Intent intent = new Intent(MainActivity.this, PointActivity.class);
intent.putExtra(Constants.GALLERY_NEW, isDeviation);
startActivity(intent);
// } else {
// UIUtilities.showNotification(this, R.string.error);
}
@Override
public void onResume() { // After a pause OR at startup
super.onResume();
//Refresh your stuff here
drawTable();
}
public void plotButton() {
Intent intent = new Intent(this, MapActivity.class);
startActivity(intent);
}
public void plot3dButton() {
Intent intent = new Intent(this, Map3DActivity.class);
startActivity(intent);
}
public void infoButton() {
Intent intent = new Intent(this, InfoActivity.class);
startActivity(intent);
}
public void changeButton() {
Log.i(Constants.LOG_TAG_UI, "Change active leg");
try {
final List<Leg> legs = DaoUtil.getCurrProjectLegs();
List<String> itemsList = new ArrayList<String>();
int selectedItem = -1;
int counter = 0;
for (Leg l : legs) {
itemsList.add(l.buildLegDescription());
if (l.getId().equals(getWorkspace().getActiveLegId())) {
selectedItem = counter;
} else {
counter++;
}
}
final CharSequence[] items = itemsList.toArray(new CharSequence[itemsList.size()]);
Log.d(Constants.LOG_TAG_UI, "Display " + items.length + " legs");
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.main_button_change_title);
builder.setSingleChoiceItems(items, selectedItem, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
Log.i(Constants.LOG_TAG_UI, "Selected leg " + legs.get(item));
getWorkspace().setActiveLegId(legs.get(item).getId());
getWorkspace().setActiveGalleryId(legs.get(item).getGalleryId());
Intent intent = new Intent(MainActivity.this, MainActivity.class);
startActivity(intent);
}
});
AlertDialog alert = builder.create();
alert.show();
} catch (Exception e) {
Log.e(Constants.LOG_TAG_DB, "Failed to select leg", e);
UIUtilities.showNotification(R.string.error);
}
}
@Override
public void onBackPressed() {
Intent setIntent = new Intent(this, HomeActivity.class);
startActivity(setIntent);
}
/**
* @see com.astoev.cave.survey.activity.MainMenuActivity#getChildsOptionsMenu()
*/
@Override
protected int getChildsOptionsMenu() {
return R.menu.mainmenu;
}
/**
* @see com.astoev.cave.survey.activity.MainMenuActivity#onOptionsItemSelected(android.view.MenuItem)
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Log.i(Constants.LOG_TAG_UI, "Main activity's menu selected - " + item.toString());
switch (item.getItemId()) {
case R.id.main_action_add:{
addButtonClick();
return true;
}
case R.id.main_action_select : {
changeButton();
return true;
}
case R.id.main_action_map :{
plotButton();
return true;
}
case R.id.main_action_info : {
infoButton();
return true;
}
default:
return super.onOptionsItemSelected(item);
}
}
/**
* Add project's name as a title
*
* @see com.astoev.cave.survey.activity.BaseActivity#getScreenTitle()
*/
@Override
protected String getScreenTitle() {
// set the name of the chosen project as title in the action bar
Project activeProject = getWorkspace().getActiveProject();
if (activeProject != null){
return activeProject.getName();
}
return null;
}
}
|
package com.dreamwing.serverville.scripting;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Semaphore;
import javax.script.ScriptException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.dreamwing.serverville.util.FileUtil;
public class ScriptManager
{
public static final int MAX_ENGINES=4;
private static final Logger l = LogManager.getLogger(ScriptManager.class);
public static String EngineBaseSource;
private static Semaphore EngineLock;
private static ScriptEngineContext[] Engines;
private static volatile int ScriptVersion=0;
private static Map<String,Boolean> ClientHandlers;
private static Set<String> AgentHandlers;
public static void init() throws Exception
{
ClassLoader loader = ScriptManager.class.getClassLoader();
EngineBaseSource = FileUtil.readStreamToString(loader.getResourceAsStream("javascript/engine.js"), StandardCharsets.UTF_8);
Engines = new ScriptEngineContext[MAX_ENGINES];
EngineLock = new Semaphore(MAX_ENGINES, true);
updateHandlerSets();
try
{
getEngine().invokeFunction("globalInit");
} catch (NoSuchMethodException e) {
// No function, no problem
} catch (Exception e) {
l.error("Error executing script globalInit: ", e);
}
}
public static ScriptEngineContext getEngine() throws InterruptedException
{
ScriptEngineContext engine = getEngineContext();
try {
engine.init(ScriptVersion);
} catch (Exception e) {
l.error("Error creating new engine", e);
EngineLock.release();
return null;
}
return engine;
}
private static ScriptEngineContext getEngineContext() throws InterruptedException
{
EngineLock.acquire();
synchronized(ScriptManager.class)
{
for(int i = 0; i<MAX_ENGINES; i++)
{
ScriptEngineContext info = Engines[i];
if(info == null)
{
info = new ScriptEngineContext();
Engines[i] = info;
}
else if(info.InUse)
{
continue;
}
info.InUse = true;
return info;
}
}
EngineLock.release();
l.error("No engine available, something is out of sync");
return null;
}
public static void returnEngine(ScriptEngineContext engineInfo)
{
if(engineInfo == null)
return;
engineInfo.InUse = false;
EngineLock.release();
}
public static void scriptsUpdated() throws InterruptedException, ScriptException
{
ScriptVersion++;
ScriptEngineContext eng = null;
try
{
eng = getEngine();
eng.invokeFunction("globalInit");
} catch (NoSuchMethodException e) {
// No function, no problem
}
finally
{
returnEngine(eng);
}
updateHandlerSets();
}
private static void updateHandlerSets()
{
ScriptEngineContext ctx = new ScriptEngineContext();
try {
ctx.init(ScriptVersion);
} catch (Exception e) {
l.error("Couldn't update script handler sets due exception", e);
return;
}
Map<String,Boolean> clientHandlers = new HashMap<String,Boolean>();
String[] clientHandlerList = ctx.getClientHandlerList();
if(clientHandlerList != null)
{
for(String handlerName : clientHandlerList)
{
Object handler = ctx.getClientHandler(handlerName);
if(handler == null)
{
// Nulled out API, so it can't be called by clients
clientHandlers.put(handlerName, false);
}
else
{
clientHandlers.put(handlerName, true);
}
}
}
ClientHandlers = clientHandlers;
Set<String> agentHandlers = new HashSet<String>();
String[] agentHandlerList = ctx.getAgentHandlerList();
if(agentHandlerList != null)
{
for(String handlerName : agentHandlerList)
{
agentHandlers.add(handlerName);
}
}
AgentHandlers = agentHandlers;
}
public static Boolean hasClientHandler(String apiType)
{
return ClientHandlers.get(apiType);
}
public static boolean hasAgentHandler(String apiType)
{
return AgentHandlers.contains(apiType);
}
}
|
// Narya library - tools for developing networked games
// This library is free software; you can redistribute it and/or modify it
// (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// You should have received a copy of the GNU Lesser General Public
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.crowd.peer.server;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.google.inject.Inject;
import com.samskivert.util.Comparators;
import com.samskivert.util.Interval;
import com.samskivert.util.Lifecycle;
import com.samskivert.util.ResultListener;
import com.threerings.util.Name;
import com.threerings.presents.client.InvocationService;
import com.threerings.presents.data.ClientObject;
import com.threerings.presents.peer.data.ClientInfo;
import com.threerings.presents.peer.data.NodeObject;
import com.threerings.presents.peer.server.PeerManager;
import com.threerings.presents.peer.server.PeerNode;
import com.threerings.presents.server.InvocationException;
import com.threerings.presents.server.InvocationManager;
import com.threerings.presents.server.PresentsSession;
import com.threerings.crowd.chat.client.ChatService;
import com.threerings.crowd.chat.data.UserMessage;
import com.threerings.crowd.chat.server.ChatProvider;
import com.threerings.crowd.chat.server.SpeakUtil;
import com.threerings.crowd.chat.server.SpeakUtil.ChatHistoryEntry;
import com.threerings.crowd.data.BodyObject;
import com.threerings.crowd.peer.data.CrowdClientInfo;
import com.threerings.crowd.peer.data.CrowdNodeObject;
import static com.threerings.crowd.Log.log;
/**
* Extends the standard peer manager and bridges certain Crowd services.
*/
public abstract class CrowdPeerManager extends PeerManager
implements CrowdPeerProvider, ChatProvider.ChatForwarder
{
/**
* Value asynchronously returned by {@link #collectChatHistory} after polling all peer nodes.
*/
public static class ChatHistoryResult
{
/** The set of nodes that either did not reply within the timeout, or had a failure. */
public Set<String> failedNodes;
/** The things in the user's chat history, aggregated from all nodes and sorted by
* timestamp. */
public List<ChatHistoryEntry> history;
}
/**
* Creates an uninitialized peer manager.
*/
@Inject public CrowdPeerManager (Lifecycle cycle)
{
super(cycle);
}
// from interface CrowdPeerProvider
public void deliverTell (ClientObject caller, UserMessage message,
Name target, ChatService.TellListener listener)
throws InvocationException
{
// we just forward the message as if it originated on this server
_chatprov.deliverTell(message, target, listener);
}
// from interface CrowdPeerProvider
public void deliverBroadcast (
ClientObject caller, Name from, byte levelOrMode, String bundle, String msg)
{
// deliver the broadcast locally on this server
_chatprov.broadcast(from, levelOrMode, bundle, msg, false);
}
// from interface CrowdPeerProvider
public void getChatHistory (
ClientObject caller, Name user, InvocationService.ResultListener lner)
throws InvocationException
{
lner.requestProcessed(Lists.newArrayList(Iterables.filter(
SpeakUtil.getChatHistory(user), IS_USER_MESSAGE)));
}
// from interface ChatProvider.ChatForwarder
public boolean forwardTell (UserMessage message, Name target,
ChatService.TellListener listener)
{
// look up their auth username from their visible name
Name username = authFromViz(target);
if (username == null) {
return false; // sorry kid, don't know ya
}
// look through our peers to see if the target user is online on one of them
for (PeerNode peer : _peers.values()) {
CrowdNodeObject cnobj = (CrowdNodeObject)peer.nodeobj;
if (cnobj == null) {
continue;
}
// we have to use auth username to look up their ClientInfo
CrowdClientInfo cinfo = (CrowdClientInfo)cnobj.clients.get(username);
if (cinfo != null) {
cnobj.crowdPeerService.deliverTell(peer.getClient(), message, target, listener);
return true;
}
}
return false;
}
// from interface ChatProvider.ChatForwarder
public void forwardBroadcast (Name from, byte levelOrMode, String bundle, String msg)
{
for (PeerNode peer : _peers.values()) {
if (peer.nodeobj != null) {
((CrowdNodeObject)peer.nodeobj).crowdPeerService.deliverBroadcast(
peer.getClient(), from, levelOrMode, bundle, msg);
}
}
}
/**
* Collects all chat messages heard by the given user on all peers. Must be called on the
* dobj event thread.
*/
public void collectChatHistory (Name user, ResultListener<ChatHistoryResult> lner)
{
_omgr.requireEventThread();
new ChatHistoryCollector(user, lner).collect();
}
@Override // from PeerManager
public void shutdown ()
{
super.shutdown();
// unregister our invocation service
if (_nodeobj != null) {
_invmgr.clearDispatcher(((CrowdNodeObject)_nodeobj).crowdPeerService);
}
// clear our chat forwarder registration
_chatprov.setChatForwarder(null);
}
@Override // from PeerManager
protected NodeObject createNodeObject ()
{
return new CrowdNodeObject();
}
@Override // from PeerManager
protected ClientInfo createClientInfo ()
{
return new CrowdClientInfo();
}
@Override // from PeerManager
protected void initClientInfo (PresentsSession client, ClientInfo info)
{
super.initClientInfo(client, info);
((CrowdClientInfo)info).visibleName =
((BodyObject)client.getClientObject()).getVisibleName();
}
@Override // from PeerManager
protected void didInit ()
{
super.didInit();
// register and initialize our invocation service
CrowdNodeObject cnobj = (CrowdNodeObject)_nodeobj;
cnobj.setCrowdPeerService(_invmgr.registerDispatcher(new CrowdPeerDispatcher(this)));
// register ourselves as a chat forwarder
_chatprov.setChatForwarder(this);
}
/**
* Converts a visible name to an authentication name. If this method returns null, the chat
* system will act as if the vizname in question is not online.
*/
protected abstract Name authFromViz (Name vizname);
/**
* Asynchronously collects the chat history from all nodes for a given user.
* TODO: refactor node parts into base class similar to PeerManager.NodeAction
*/
protected class ChatHistoryCollector
{
public ChatHistoryCollector (Name user, ResultListener<ChatHistoryResult> listener)
{
_user = user;
_listener = listener;
_result = new ChatHistoryResult();
_result.failedNodes = Sets.newHashSet();
_waiting = Sets.newHashSet();
}
public void collect ()
{
_result.history = Lists.newArrayList(
Iterables.filter(SpeakUtil.getChatHistory(_user), IS_USER_MESSAGE));
for (PeerNode peer : _peers.values()) {
final PeerNode fpeer = peer;
((CrowdNodeObject)peer.nodeobj).crowdPeerService.getChatHistory(
peer.getClient(), _user, new InvocationService.ResultListener() {
public void requestProcessed (Object result) {
processed(fpeer, result);
}
public void requestFailed (String cause) {
failed(fpeer, cause);
}
});
_waiting.add(peer.getNodeName());
}
// timeout in 5 seconds if we haven't heard back from all nodes
final long TIMEOUT = 5 * 1000;
if (!maybeComplete()) {
new Interval(_omgr) {
@Override public void expired () {
checkTimeout();
}
}.schedule(TIMEOUT);
}
}
protected void processed (PeerNode node, Object result)
{
String name = node.getNodeName();
if (!_waiting.remove(name)) {
log.warning("Double chat history response from node", "name", name);
return;
}
@SuppressWarnings("unchecked")
List<ChatHistoryEntry> nodeMessages = (List<ChatHistoryEntry>)result;
_result.history.addAll(nodeMessages);
maybeComplete();
}
protected void failed (PeerNode node, String cause)
{
String name = node.getNodeName();
_result.failedNodes.add(name);
if (_waiting.remove(name)) {
maybeComplete();
} else {
log.warning("Double chat history response from node", "name", name);
}
}
protected boolean maybeComplete ()
{
if (!_waiting.isEmpty()) {
return false;
}
Collections.sort(_result.history, SORT_BY_TIMESTAMP);
_listener.requestCompleted(_result);
return true;
}
protected void checkTimeout ()
{
if (!_waiting.isEmpty()) {
_result.failedNodes.addAll(_waiting);
_waiting.clear();
maybeComplete();
}
}
protected Name _user;
protected ResultListener<ChatHistoryResult> _listener;
protected ChatHistoryResult _result;
protected Set<String> _waiting;
}
@Inject protected InvocationManager _invmgr;
@Inject protected ChatProvider _chatprov;
protected static final Predicate<ChatHistoryEntry> IS_USER_MESSAGE =
new Predicate<ChatHistoryEntry>() {
public boolean apply (ChatHistoryEntry entry) {
return entry.message instanceof UserMessage;
}
};
protected static final Comparator<ChatHistoryEntry> SORT_BY_TIMESTAMP =
new Comparator<ChatHistoryEntry>() {
public int compare (ChatHistoryEntry e1, ChatHistoryEntry e2) {
return Comparators.compare(e1.message.timestamp, e2.message.timestamp);
}
};
}
|
package edu.yu.einstein.wasp.controller;
/**
* this controller just forwards to the view
*
*
*
*
*
*
*/
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.transaction.annotation.*;
import javax.servlet.http.HttpServletRequest;
@Controller
public class DefaultController extends WaspController {
@RequestMapping("*")
public String def(HttpServletRequest req, ModelMap m) {
String c = req.getContextPath();
String s = req.getRequestURI();
String p = req.getServletPath();
// strips context, lead slash ("/"), spring mapping
String d = s.replaceFirst(c + "/", "").replaceFirst("\\.do.*$", "");
m.addAttribute("c", c);
m.addAttribute("s", s);
m.addAttribute("p", p);
m.addAttribute("d", d);
m.addAttribute("roles", getRoles());
return d;
}
}
|
package org.antlr.intellij.plugin;
import com.intellij.execution.filters.TextConsoleBuilder;
import com.intellij.execution.filters.TextConsoleBuilderFactory;
import com.intellij.execution.ui.ConsoleView;
import com.intellij.ide.plugins.IdeaPluginDescriptor;
import com.intellij.ide.plugins.PluginManager;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.ProjectComponent;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.EditorFactory;
import com.intellij.openapi.editor.event.EditorFactoryAdapter;
import com.intellij.openapi.editor.event.EditorFactoryEvent;
import com.intellij.openapi.editor.event.EditorMouseAdapter;
import com.intellij.openapi.editor.event.EditorMouseEvent;
import com.intellij.openapi.extensions.PluginId;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.fileEditor.FileEditorManagerAdapter;
import com.intellij.openapi.fileEditor.FileEditorManagerEvent;
import com.intellij.openapi.fileEditor.FileEditorManagerListener;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileAdapter;
import com.intellij.openapi.vfs.VirtualFileEvent;
import com.intellij.openapi.vfs.VirtualFileManager;
import com.intellij.openapi.wm.ToolWindow;
import com.intellij.openapi.wm.ToolWindowAnchor;
import com.intellij.openapi.wm.ToolWindowManager;
import com.intellij.ui.content.Content;
import com.intellij.ui.content.ContentFactory;
import com.intellij.util.messages.MessageBusConnection;
import org.antlr.intellij.adaptor.parser.SyntaxErrorListener;
import org.antlr.intellij.plugin.parsing.ParsingResult;
import org.antlr.intellij.plugin.parsing.ParsingUtils;
import org.antlr.intellij.plugin.parsing.RunANTLROnGrammarFile;
import org.antlr.intellij.plugin.preview.PreviewPanel;
import org.antlr.intellij.plugin.preview.PreviewState;
import org.antlr.intellij.plugin.profiler.ProfilerPanel;
import org.antlr.v4.parse.ANTLRParser;
import org.antlr.v4.tool.Grammar;
import org.antlr.v4.tool.LexerGrammar;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/** This object is the controller for the ANTLR plug-in. It receives
* events and can send them on to its contained components. For example,
* saving the grammar editor or flipping to a new grammar sends an event
* to this object, which forwards on update events to the preview tool window.
*
* The main components are related to the console tool window forever output and
* the main panel of the preview tool window.
*
* This controller also manages the cache of grammar/editor combinations
* needed for the preview window. Updates must be made atomically so that
* the grammars and editors are consistently associated with the same window.
*/
public class ANTLRv4PluginController implements ProjectComponent {
public static final String PLUGIN_ID = "org.antlr.intellij.plugin";
public static final Key<GrammarEditorMouseAdapter> EDITOR_MOUSE_LISTENER_KEY = Key.create("EDITOR_MOUSE_LISTENER_KEY");
public static final Logger LOG = Logger.getInstance("ANTLRv4PluginController");
public static final String PREVIEW_WINDOW_ID = "ANTLR Preview";
public static final String CONSOLE_WINDOW_ID = "Tool Output";
public boolean projectIsClosed = false;
public Project project;
public ConsoleView console;
public ToolWindow consoleWindow;
public Map<String, PreviewState> grammarToPreviewState =
Collections.synchronizedMap(new HashMap<String, PreviewState>());
public ToolWindow previewWindow; // same for all grammar editor
public PreviewPanel previewPanel; // same for all grammar editor
public MyVirtualFileAdapter myVirtualFileAdapter = new MyVirtualFileAdapter();
public MyFileEditorManagerAdapter myFileEditorManagerAdapter = new MyFileEditorManagerAdapter();
public ANTLRv4PluginController(Project project) {
this.project = project;
}
public static ANTLRv4PluginController getInstance(Project project) {
if ( project==null ) {
LOG.error("getInstance: project is null");
return null;
}
ANTLRv4PluginController pc = project.getComponent(ANTLRv4PluginController.class);
if ( pc==null ) {
LOG.error("getInstance: getComponent() for "+project.getName()+" returns null");
}
return pc;
}
@Override
public void initComponent() {
}
@Override
public void projectOpened() {
IdeaPluginDescriptor plugin = PluginManager.getPlugin(PluginId.getId(PLUGIN_ID));
String version = "unknown";
if ( plugin!=null ) {
version = plugin.getVersion();
}
LOG.info("ANTLR 4 Plugin version "+version+", Java version "+ SystemInfo.JAVA_VERSION);
// make sure the tool windows are created early
createToolWindows();
installListeners();
}
public void createToolWindows() {
LOG.info("createToolWindows "+project.getName());
ToolWindowManager toolWindowManager = ToolWindowManager.getInstance(project);
previewPanel = new PreviewPanel(project);
ContentFactory contentFactory = ContentFactory.SERVICE.getInstance();
Content content = contentFactory.createContent(previewPanel, "", false);
previewWindow = toolWindowManager.registerToolWindow(PREVIEW_WINDOW_ID, true, ToolWindowAnchor.BOTTOM);
previewWindow.getContentManager().addContent(content);
previewWindow.setIcon(Icons.FILE);
TextConsoleBuilderFactory factory = TextConsoleBuilderFactory.getInstance();
TextConsoleBuilder consoleBuilder = factory.createBuilder(project);
this.console = consoleBuilder.getConsole();
JComponent consoleComponent = console.getComponent();
content = contentFactory.createContent(consoleComponent, "", false);
consoleWindow = toolWindowManager.registerToolWindow(CONSOLE_WINDOW_ID, true, ToolWindowAnchor.BOTTOM);
consoleWindow.getContentManager().addContent(content);
consoleWindow.setIcon(Icons.FILE);
}
@Override
public void projectClosed() {
LOG.info("projectClosed " + project.getName());
//synchronized ( shutdownLock ) { // They should be called from EDT only so no lock
projectIsClosed = true;
uninstallListeners();
console.dispose();
for (PreviewState it : grammarToPreviewState.values()) {
previewPanel.inputPanel.releaseEditor(it);
}
previewPanel = null;
previewWindow = null;
consoleWindow = null;
project = null;
grammarToPreviewState = null;
}
// seems that intellij can kill and reload a project w/o user knowing.
// a ptr was left around that pointed at a disposed project. led to
// problem in switchGrammar. Probably was a listener still attached and trigger
// editor listeners released in editorReleased() events.
public void uninstallListeners() {
VirtualFileManager.getInstance().removeVirtualFileListener(myVirtualFileAdapter);
MessageBusConnection msgBus = project.getMessageBus().connect(project);
msgBus.disconnect();
}
@Override
public void disposeComponent() {
}
@NotNull
@Override
public String getComponentName() {
return "antlr.ProjectComponent";
}
public void installListeners() {
LOG.info("installListeners "+project.getName());
// Listen for .g4 file saves
VirtualFileManager.getInstance().addVirtualFileListener(myVirtualFileAdapter);
// Listen for editor window changes
MessageBusConnection msgBus = project.getMessageBus().connect(project);
msgBus.subscribe(
FileEditorManagerListener.FILE_EDITOR_MANAGER,
myFileEditorManagerAdapter
);
EditorFactory factory = EditorFactory.getInstance();
factory.addEditorFactoryListener(
new EditorFactoryAdapter() {
@Override
public void editorCreated(@NotNull EditorFactoryEvent event) {
final Editor editor = event.getEditor();
final Document doc = editor.getDocument();
VirtualFile vfile = FileDocumentManager.getInstance().getFile(doc);
if ( vfile!=null && vfile.getName().endsWith(".g4") ) {
GrammarEditorMouseAdapter listener = new GrammarEditorMouseAdapter();
editor.putUserData(EDITOR_MOUSE_LISTENER_KEY, listener);
editor.addEditorMouseListener(listener);
}
}
@Override
public void editorReleased(@NotNull EditorFactoryEvent event) {
Editor editor = event.getEditor();
if (editor.getProject() != null && editor.getProject() != project) {
return;
}
GrammarEditorMouseAdapter listener = editor.getUserData(EDITOR_MOUSE_LISTENER_KEY);
if (listener != null) {
editor.removeEditorMouseListener(listener);
editor.putUserData(EDITOR_MOUSE_LISTENER_KEY, null);
}
}
}
);
}
/** The test ANTLR rule action triggers this event. This can occur
* only occur when the current editor the showing a grammar, because
* that is the only time that the action is enabled. We will see
* a file changed event when the project loads the first grammar file.
*/
public void setStartRuleNameEvent(VirtualFile grammarFile, String startRuleName) {
LOG.info("setStartRuleNameEvent " + startRuleName+" "+project.getName());
PreviewState previewState = getPreviewState(grammarFile);
previewState.startRuleName = startRuleName;
if ( previewPanel!=null ) {
previewPanel.getInputPanel().setStartRuleName(grammarFile, startRuleName); // notify the view
previewPanel.updateParseTreeFromDoc(grammarFile);
}
else {
LOG.error("setStartRuleNameEvent called before preview panel created");
}
}
public void grammarFileSavedEvent(VirtualFile grammarFile) {
LOG.info("grammarFileSavedEvent "+grammarFile.getPath()+" "+project.getName());
updateGrammarObjectsFromFile(grammarFile); // force reload
if ( previewPanel!=null ) {
previewPanel.grammarFileSaved(grammarFile);
}
else {
LOG.error("grammarFileSavedEvent called before preview panel created");
}
runANTLRTool(grammarFile);
}
public void currentEditorFileChangedEvent(VirtualFile oldFile, VirtualFile newFile) {
LOG.info("currentEditorFileChangedEvent "+(oldFile!=null?oldFile.getPath():"none")+
" -> "+(newFile!=null?newFile.getPath():"none")+" "+project.getName());
if ( newFile==null ) { // all files must be closed I guess
return;
}
if ( newFile.getName().endsWith(".g") ) {
LOG.info("currentEditorFileChangedEvent ANTLR 4 cannot handle .g files, only .g4");
previewWindow.hide(null);
return;
}
if ( !newFile.getName().endsWith(".g4") ) {
previewWindow.hide(null);
return;
}
PreviewState previewState = getPreviewState(newFile);
if ( previewState.g==null && previewState.lg==null ) { // only load grammars if none is there
updateGrammarObjectsFromFile(newFile);
}
if ( previewPanel!=null ) {
previewPanel.grammarFileChanged(oldFile, newFile);
}
}
public void mouseEnteredGrammarEditorEvent(VirtualFile vfile, EditorMouseEvent e) {
if ( previewPanel!=null ) {
ProfilerPanel profilerPanel = previewPanel.getProfilerPanel();
if ( profilerPanel!=null ) {
profilerPanel.mouseEnteredGrammarEditorEvent(vfile, e);
}
}
}
public void editorFileClosedEvent(VirtualFile vfile) {
// hopefully called only from swing EDT
String grammarFileName = vfile.getPath();
LOG.info("editorFileClosedEvent "+ grammarFileName+" "+project.getName());
if ( !vfile.getName().endsWith(".g4") ) {
previewWindow.hide(null);
return;
}
// Dispose of state, editor, and such for this file
PreviewState previewState = grammarToPreviewState.get(grammarFileName);
if ( previewState==null ) { // project closing must have done already
return;
}
previewState.g = null; // wack old ref to the Grammar for text in editor
previewState.lg = null;
previewPanel.closeGrammar(vfile);
grammarToPreviewState.remove(grammarFileName);
// close tool window
previewWindow.hide(null);
}
/** Make sure to run after updating grammars in previewState */
public void runANTLRTool(final VirtualFile grammarFile) {
String title = "ANTLR Code Generation";
boolean canBeCancelled = true;
boolean forceGeneration = false;
Task gen =
new RunANTLROnGrammarFile(grammarFile,
project,
title,
canBeCancelled,
forceGeneration);
ProgressManager.getInstance().run(gen);
}
/** Look for state information concerning this grammar file and update
* the Grammar objects. This does not necessarily update the grammar file
* in the current editor window. Either we are already looking at
* this grammar or we will have seen a grammar file changed event.
* (I hope!)
*/
public void updateGrammarObjectsFromFile(VirtualFile grammarFile) {
updateGrammarObjectsFromFile_(grammarFile);
// if grammarFileName is a separate lexer, we need to look for
// its matching parser, if any, that is loaded in an editor
// (don't go looking on disk).
PreviewState s = getAssociatedParserIfLexer(grammarFile.getPath());
if ( s!=null ) {
// try to load lexer again and associate with this parser grammar.
// must update parser too as tokens have changed
updateGrammarObjectsFromFile_(s.grammarFile);
}
}
public String updateGrammarObjectsFromFile_(VirtualFile grammarFile) {
String grammarFileName = grammarFile.getPath();
PreviewState previewState = getPreviewState(grammarFile);
Grammar[] grammars = ParsingUtils.loadGrammars(grammarFileName, project);
if (grammars != null) {
synchronized (previewState) { // build atomically
previewState.lg = (LexerGrammar)grammars[0];
previewState.g = grammars[1];
}
}
return grammarFileName;
}
public PreviewState getAssociatedParserIfLexer(String grammarFileName) {
for (PreviewState s : grammarToPreviewState.values()) {
if ( s!=null && s.lg!=null &&
(grammarFileName.equals(s.lg.fileName)||s.lg==ParsingUtils.BAD_LEXER_GRAMMAR) )
{
// s has a lexer with same filename, see if there is a parser grammar
// (not a combined grammar)
if ( s.g!=null && s.g.getType()==ANTLRParser.PARSER ) {
System.out.println(s.lg.fileName+" vs "+grammarFileName+", g="+s.g.name+", type="+s.g.getTypeString());
return s;
}
}
}
return null;
}
public ParsingResult parseText(final VirtualFile grammarFile, String inputText) throws IOException {
String grammarFileName = grammarFile.getPath();
if (!new File(grammarFileName).exists()) {
LOG.error("parseText grammar doesn't exit " + grammarFileName);
return null;
}
// Wipes out the console and also any error annotations
previewPanel.inputPanel.clearParseErrors();
final PreviewState previewState = getPreviewState(grammarFile);
long start = System.nanoTime();
previewState.parsingResult =
ParsingUtils.parseText(previewState.g, previewState.lg,
previewState.startRuleName,
grammarFile, inputText);
if ( previewState.parsingResult==null ) {
return null;
}
long stop = System.nanoTime();
previewPanel.profilerPanel.setProfilerData(previewState, stop-start);
SyntaxErrorListener syntaxErrorListener = previewState.parsingResult.syntaxErrorListener;
previewPanel.inputPanel.showParseErrors(syntaxErrorListener.getSyntaxErrors());
return previewState.parsingResult;
}
public PreviewPanel getPreviewPanel() {
return previewPanel;
}
public ConsoleView getConsole() {
return console;
}
public ToolWindow getConsoleWindow() {
return consoleWindow;
}
public static void showConsoleWindow(final Project project) {
ApplicationManager.getApplication().invokeLater(
new Runnable() {
@Override
public void run() {
ANTLRv4PluginController.getInstance(project).getConsoleWindow().show(null);
}
}
);
}
public ToolWindow getPreviewWindow() {
return previewWindow;
}
public @NotNull PreviewState getPreviewState(VirtualFile grammarFile) {
// make sure only one thread tries to add a preview state object for a given file
String grammarFileName = grammarFile.getPath();
// Have we seen this grammar before?
PreviewState stateForCurrentGrammar = grammarToPreviewState.get(grammarFileName);
if ( stateForCurrentGrammar!=null ) {
return stateForCurrentGrammar; // seen this before
}
// not seen, must create state
stateForCurrentGrammar = new PreviewState(project, grammarFile);
grammarToPreviewState.put(grammarFileName, stateForCurrentGrammar);
return stateForCurrentGrammar;
}
public Editor getEditor(VirtualFile vfile) {
final FileDocumentManager fdm = FileDocumentManager.getInstance();
final Document doc = fdm.getDocument(vfile);
if (doc == null) return null;
EditorFactory factory = EditorFactory.getInstance();
final Editor[] editors = factory.getEditors(doc, previewPanel.project);
if ( editors.length==0 ) {
// no editor found for this file. likely an out-of-sequence issue
// where Intellij is opening a project and doesn't fire events
// in order we'd expect.
return null;
}
return editors[0]; // hope just one
}
/** Get the state information associated with the grammar in the current
* editor window. If there is no grammar in the editor window, return null.
* If there is a grammar, return any existing preview state else
* create a new one in store in the map.
*
* Too dangerous; turning off but might be useful later.
public @org.jetbrains.annotations.Nullable PreviewState getPreviewState() {
VirtualFile currentGrammarFile = getCurrentGrammarFile();
if ( currentGrammarFile==null ) {
return null;
}
String currentGrammarFileName = currentGrammarFile.getPath();
if ( currentGrammarFileName==null ) {
return null; // we are not looking at a grammar file
}
return getPreviewState(currentGrammarFile);
}
*/
// These "get current editor file" routines should only be used
// when you are sure the user is in control and is viewing the
// right file (i.e., don't use these during project loading etc...)
public static VirtualFile getCurrentEditorFile(Project project) {
FileEditorManager fmgr = FileEditorManager.getInstance(project);
// "If more than one file is selected (split), the file with most recent focused editor is returned first." from IDE doc on method
VirtualFile files[] = fmgr.getSelectedFiles();
if ( files.length == 0 ) {
return null;
}
return files[0];
}
// public Editor getCurrentGrammarEditor() {
// FileEditorManager edMgr = FileEditorManager.getInstance(project);
// return edMgr.getSelectedTextEditor();
public VirtualFile getCurrentGrammarFile() {
return getCurrentGrammarFile(project);
}
public static VirtualFile getCurrentGrammarFile(Project project) {
VirtualFile f = getCurrentEditorFile(project);
if ( f==null ) {
return null;
}
if ( f.getName().endsWith(".g4") ) return f;
return null;
}
private class GrammarEditorMouseAdapter extends EditorMouseAdapter {
@Override
public void mouseClicked(EditorMouseEvent e) {
Document doc = e.getEditor().getDocument();
VirtualFile vfile = FileDocumentManager.getInstance().getFile(doc);
if ( vfile!=null && vfile.getName().endsWith(".g4") ) {
mouseEnteredGrammarEditorEvent(vfile, e);
}
}
}
private class MyVirtualFileAdapter extends VirtualFileAdapter {
@Override
public void contentsChanged(VirtualFileEvent event) {
final VirtualFile vfile = event.getFile();
if ( !vfile.getName().endsWith(".g4") ) return;
if ( !projectIsClosed ) grammarFileSavedEvent(vfile);
}
}
private class MyFileEditorManagerAdapter extends FileEditorManagerAdapter {
@Override
public void selectionChanged(FileEditorManagerEvent event) {
if ( !projectIsClosed ) currentEditorFileChangedEvent(event.getOldFile(), event.getNewFile());
}
@Override
public void fileClosed(FileEditorManager source, VirtualFile file) {
if ( !projectIsClosed ) editorFileClosedEvent(file);
}
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.bearsoft.rowset;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.bearsoft.rowset.beans.PropertyChangeEvent;
import com.bearsoft.rowset.beans.PropertyChangeListener;
import com.bearsoft.rowset.beans.PropertyChangeSupport;
import com.bearsoft.rowset.beans.VetoableChangeListener;
import com.bearsoft.rowset.changes.Change;
import com.bearsoft.rowset.changes.Delete;
import com.bearsoft.rowset.changes.Insert;
import com.bearsoft.rowset.changes.Update;
import com.bearsoft.rowset.dataflow.FlowProvider;
import com.bearsoft.rowset.events.RowsetChangeSupport;
import com.bearsoft.rowset.events.RowsetListener;
import com.bearsoft.rowset.exceptions.FlowProviderFailedException;
import com.bearsoft.rowset.exceptions.InvalidColIndexException;
import com.bearsoft.rowset.exceptions.InvalidCursorPositionException;
import com.bearsoft.rowset.exceptions.InvalidFieldsExceptionException;
import com.bearsoft.rowset.exceptions.MissingFlowProviderException;
import com.bearsoft.rowset.exceptions.RowsetException;
import com.bearsoft.rowset.filters.Filter;
import com.bearsoft.rowset.locators.Locator;
import com.bearsoft.rowset.locators.ParentLocator;
import com.bearsoft.rowset.metadata.Field;
import com.bearsoft.rowset.metadata.Fields;
import com.bearsoft.rowset.metadata.Parameters;
import com.bearsoft.rowset.ordering.DefaultOrderersFactory;
import com.bearsoft.rowset.ordering.HashOrderer;
import com.bearsoft.rowset.ordering.OrderersFactory;
import com.bearsoft.rowset.utils.KeySet;
import com.bearsoft.rowset.utils.RowsetUtils;
import com.google.gwt.core.client.Callback;
/**
* Rowset serves as original and updated rows vectors holder. There are three
* developing themes: - rowset's life, with it's data processing (sorting,
* locating and filtering). - rowset's saving and restoring to and from variety
* of sources (database, files and others). - applying and rolling back changes,
* maded to it's data.
*
* @author mg
*/
public class Rowset implements PropertyChangeListener, VetoableChangeListener {
public static final String BAD_FLOW_PROVIDER_RESULT_MSG = "Flow Provider must return at least an empty rowset";
// multi-tier transactions support
protected String sessionId;
// support for data flows.
protected FlowProvider flow;
// rowset's metadata
protected Fields fields;
// rowset's data
protected List<Row> original = new ArrayList<>();
protected List<Row> current = new ArrayList<>();
// data view capabilities
protected int currentRowPos; // before first position
protected boolean showOriginal;
// data processing
protected Set<Filter> filters = new HashSet<>(); // filters
protected Set<Locator> locators = new HashSet<>(); // locators
protected Filter activeFilter;
protected Row insertingRow;
// client code interaction
protected PropertyChangeSupport propertyChangeSupport;
protected RowsetChangeSupport rowsetChangeSupport;
protected OrderersFactory orderersFactory;
protected boolean immediateFilter = true;
protected boolean modified;
/**
* Simple constructor.
*/
public Rowset() {
super();
propertyChangeSupport = new PropertyChangeSupport(this);
rowsetChangeSupport = new RowsetChangeSupport(this);
orderersFactory = new DefaultOrderersFactory(this);
}
/**
* Rowset's metadata constructor.
*
* @param aFields
* Columns definition new rowset have to work with.
*/
public Rowset(Fields aFields) {
this();
fields = aFields;
}
/**
* Rowset's data flow constructor. Gets a converter from flow provider
* passed in if flow provider is JdbcFlowProvider.
*
* @param aProvider
* Data flow provider new rowset have to work with.
* @see DatabaseFlowProvider
*/
public Rowset(FlowProvider aProvider) {
this();
flow = aProvider;
}
/**
* Returns the flow provider instance, used by this rowset to support data
* flow process.
*
* @return Current flow provider.
*/
public FlowProvider getFlowProvider() {
return flow;
}
/**
* Sets the provider to be used in data flow process.
*
* @param aFlowProvider
* Flow provider to set.
*/
public void setFlowProvider(FlowProvider aFlowProvider) {
flow = aFlowProvider;
}
// changes management support
public void commited() throws Exception {
final Set<RowsetListener> lrowsetListeners = rowsetChangeSupport.getRowsetListeners();
rowsetChangeSupport.setRowsetListeners(null);
try {
currentToOriginal();
} finally {
rowsetChangeSupport.setRowsetListeners(lrowsetListeners);
}
rowsetChangeSupport.fireSavedEvent();
}
public void rolledback() throws Exception {
final Set<RowsetListener> lrowsetListeners = rowsetChangeSupport.getRowsetListeners();
rowsetChangeSupport.setRowsetListeners(null);
try {
originalToCurrent();
if (currentRowPos > current.size() + 1) {
currentRowPos = current.size() + 1;
} else if (currentRowPos < 0) {
currentRowPos = 0;
}
if (current.isEmpty()) {
currentRowPos = 0;
}
} finally {
rowsetChangeSupport.setRowsetListeners(lrowsetListeners);
}
rowsetChangeSupport.fireRolledbackEvent();
}
/**
* Registers <code>PropertyChangeListener</code> on this rowset.
*
* @param aListener
* <code>PropertyChangeListener</code> to be registered.
*/
public void addPropertyChangeListener(PropertyChangeListener aListener) {
propertyChangeSupport.addPropertyChangeListener(aListener);
}
/**
* Removes <code>PropertyChangeListener</code> from this rowset.
*
* @param aListener
* <code>PropertyChangeListener</code> to be removed.
*/
public void removePropertyChangeListener(PropertyChangeListener aListener) {
propertyChangeSupport.removePropertyChangeListener(aListener);
}
/**
* Registers <code>RowsetListener</code> on this rowset.
*
* @param aListener
* <code>RowsetListener</code> to be registered.
*/
public void addRowsetListener(RowsetListener aListener) {
rowsetChangeSupport.addRowsetListener(aListener);
}
/**
* Removes <code>RowsetListener</code> from this rowset.
*
* @param aListener
* <code>RowsetListener</code> to be removed.
*/
public void removeRowsetListener(RowsetListener aListener) {
rowsetChangeSupport.removeRowsetListener(aListener);
}
/**
* Inner utility method for filters and some others.
*
* @return <code>RowsetChangeSupport</code> instance from this rowset.
*/
public RowsetChangeSupport getRowsetChangeSupport() {
return rowsetChangeSupport;
}
/**
* Returns current <code>OrderersFactory</code> object, installed on this
* rowset.
*
* @return Currently installed <code>OrderersFactory</code> object
*/
public OrderersFactory getOrderersFactory() {
return orderersFactory;
}
/**
* Installed <code>OrderersFactory</code> object on this rowset.
*
* @param orderersFactory
* Factory object to install.
*/
public void setOrderersFactory(OrderersFactory orderersFactory) {
this.orderersFactory = orderersFactory;
}
/**
* Columns definition getter.
*
* @return Columns definition of this rowset.
*/
public Fields getFields() {
return fields;
}
/**
* Columns definition setter.
*
* @param aFields
* Columns definition.
*/
public void setFields(Fields aFields) throws InvalidFieldsExceptionException {
if (!current.isEmpty()) {
Row row = current.get(0);
assert row != null;
if (row.getColumnCount() != aFields.getFieldsCount()) {
throw new InvalidFieldsExceptionException("column count is wrong, expected: " + row.getColumnCount() + ", but " + aFields.getFieldsCount() + " is got");
}
} else if (!original.isEmpty()) {
Row row = original.get(0);
assert row != null;
if (row.getColumnCount() != aFields.getFieldsCount()) {
throw new InvalidFieldsExceptionException("column count is wrong, expected: " + row.getColumnCount() + ", but " + aFields.getFieldsCount() + " is got");
}
}
fields = aFields;
}
/**
* Returns active (current) filter of this rowset. May be null.
*
* @return Active (current) filter of this rowset. May be null.
*/
public Filter getActiveFilter() {
return activeFilter;
}
/**
* Sets active (current) filter of this rowset. For internal use only.
*
* @param aValue
* Filter to be setted as active (current) filter of this rowset.
* May be null.
*/
public void setActiveFilter(Filter aValue) {
activeFilter = aValue;
}
/**
* Retruns this rowset's modified status.
*
* @return True if this rowses have changes since last currentToOriginal()
* and originalToCurrent() method calls
* @see #currentToOriginal()
* @see #originalToCurrent()
*/
public boolean isModified() {
return modified;
}
/**
* Sets the modified flag for this rowset. It's not recomended to use this
* method, but in some cases it may be useful.
*
* @param aValue
*/
public void setModified(boolean aValue) {
modified = aValue;
}
/**
* Returns whether installed filter have to immediately re-filter this
* rowset after updating a field which is filtering criteria.
*
* @return True is filter have to re-filter this rowset immediately after
* updating a field which is filtering criteria.
*/
public boolean isImmediateFilter() {
return immediateFilter;
}
/**
* Sets immediateFilter flag for this rowset.
*
* @param aValue
* @see #isImmediateFilter()
*/
public void setImmediateFilter(boolean aValue) {
if (immediateFilter != aValue) {
boolean oldValue = immediateFilter;
immediateFilter = aValue;
propertyChangeSupport.firePropertyChange("immediateFilter", oldValue, immediateFilter);
}
}
public Cancellable refresh(final Callback<Rowset, String> aCallback) throws Exception {
return refresh(new Parameters(), aCallback);
}
public Cancellable refresh(Parameters aParams, final Callback<Rowset, String> aCallback) throws Exception {
if (flow != null) {
if (rowsetChangeSupport.fireWillRequeryEvent()) {
rowsetChangeSupport.fireBeforeRequery();
return flow.refresh(aParams, new CallbackAdapter<Rowset, String>() {
@Override
protected void doWork(Rowset aRowset) throws Exception {
if (aRowset != null) {
if (activeFilter != null && activeFilter.isApplied()) {
activeFilter.deactivate(); // No implicit calls
// to setCurrent and
// etc.
activeFilter = null;
}
if (fields == null) {
setFields(aRowset.getFields());
}
List<Row> rows = aRowset.getCurrent();
aRowset.setCurrent(new ArrayList<Row>());
aRowset.currentToOriginal();
setCurrent(rows);
currentToOriginal();
invalidateFilters();
// silent first
if (!current.isEmpty()) {
currentRowPos = 1;
}
rowsetChangeSupport.fireRequeriedEvent();
if (aCallback != null) {
aCallback.onSuccess(Rowset.this);
}
} else {
throw new FlowProviderFailedException(BAD_FLOW_PROVIDER_RESULT_MSG);
}
}
@Override
public void onFailure(String reason) {
if (reason == null)
reason = "Unknown network error. May be cancelled.";
rowsetChangeSupport.fireNetErrorEvent(reason);
if (aCallback != null) {
aCallback.onFailure(reason);
}
}
});
}
return null;
} else {
throw new MissingFlowProviderException();
}
}
public void silentFirst() throws InvalidCursorPositionException {
Set<RowsetListener> l = rowsetChangeSupport.getRowsetListeners();
rowsetChangeSupport.setRowsetListeners(null);
try {
first();
} finally {
rowsetChangeSupport.setRowsetListeners(l);
}
}
/**
* Returns current rows vector. Used with filtering classes.
*
* @return Current rows vector.
* @see HashOrderer
*/
public List<Row> getCurrent() {
return current;
}
/**
* Returns original rows vector.
*
* @return Original rows vector.
*/
public List<Row> getOriginal() {
return original;
}
/**
* Sets current rows vector. Unsubscribes from old rows events and sub
* subscribes on new rows events.
*
* @param aCurrent
* Current rows list.
* @see HashOrderer
* @see Filter
* @see Locator
*/
public void setCurrent(List<Row> aCurrent) {
assert fields != null;
unsubscribeFromRows(current);
current = aCurrent;
subscribeOnRows(current);
currentRowPos = 0;
invalidateLocators();
// WARNING: Invalidating of filters MUST NOT go here, because filtering
// calls this setCurrent(List<Row> aCurrent) method.
// Current set of rowset's rows is changed and so, we need to invalidate
// locators, but NOT FILTERS!
}
/**
* Method similar to setCurrent, except it doesn't unsubscribe from old rows
* events and doesn't subscribe on new rows events. Used with filtering
* classes. The idea is that new rows list is a subset of this rowset's
* native rows and so, we don't need to riddle theese rows's events
* subscribers.
*
* @param aCurrent
* Rows list to be setted as current rowset's content.
* @see HashOrderer
* @see Filter
* @see Locator
*/
public void setSubsetAsCurrent(List<Row> aCurrent) {
assert fields != null;
current = aCurrent;
currentRowPos = 0;
invalidateLocators();
// WARNING: Invalidating of filters MUST NOT go here, because filtering
// calls this setCurrent(List<Row> aCurrent) method.
// Current set of rowset's rows is changed and so, we need to invalidate
// locators, but NOT FILTERS!
}
private void unsubscribeFromRows(List<Row> aRows) {
for (Row row : aRows) {
row.removePropertyChangeListener(this);
row.removeVetoableChangeListener(this);
}
}
/**
* Subscribes this rowset on rows events and sets this rowset's fields to
* the rows.
*
* @param aRows
*/
private void subscribeOnRows(List<Row> aRows) {
for (Row row : aRows) {
row.addPropertyChangeListener(this);
row.addVetoableChangeListener(this);
// hack. We extremely need a way to set row's fields without related
// processing
row.fields = fields;
}
}
/**
* Moves cursor on pre first position. Cusor position becomes 0.
*
* @see #absolute(int aCursorPos)
* @see #getCursorPos()
* @see #size()
* @see #first()
* @see #isBeforeFirst()
* @see #previous()
* @see #next()
* @see #last()
* @see #afterLast()
* @see #isAfterLast()
*/
public boolean beforeFirst() throws InvalidCursorPositionException {
if (!isBeforeFirst()) {
if (rowsetChangeSupport.fireWillScrollEvent(0)) {
int oldCurrentRowPos = currentRowPos;
currentRowPos = 0;
rowsetChangeSupport.fireScrolledEvent(oldCurrentRowPos);
return true;
} else {
return false;
}
} else {
return true;
}
}
/**
* Returns if cursor is before the first row. Takes into account
* <code>showOriginal</code> flag
*
* @return True if the cursor is on before first position.
* @see #absolute(int aCursorPos)
* @see #getCursorPos()
* @see #size()
* @see #beforeFirst()
* @see #first()
* @see #previous()
* @see #next()
* @see #last()
* @see #afterLast()
* @see #isAfterLast()
*/
public boolean isBeforeFirst() {
assert currentRowPos >= 0;
return isEmpty() || currentRowPos == 0;
}
/**
* Moves cursor to the first position in the rowset. It won't to position
* the rowset if it is empty. After that, position becomes 1 if this method
* returns true. If this method returns false, than position remains
* unchnaged. Takes into account <code>showOriginal</code> flag
*
* @return True if rowset is on the first position, and false if it is not.
* @see #absolute(int aCursorPos)
* @see #getCursorPos()
* @see #size()
* @see #beforeFirst()
* @see #isBeforeFirst()
* @see #previous()
* @see #next()
* @see #last()
* @see #afterLast()
* @see #isAfterLast()
*/
public boolean first() throws InvalidCursorPositionException {
if (!isEmpty()) {
if (currentRowPos != 1) {
if (rowsetChangeSupport.fireWillScrollEvent(1)) {
int oldCurrentRowPos = currentRowPos;
currentRowPos = 1;
rowsetChangeSupport.fireScrolledEvent(oldCurrentRowPos);
return true;
} else {
return false;
}
} else {
return true;
}
}
return false;
}
/**
* Moves cursor to the last position in the rowset. It won't to position the
* rowset if it is empty. After that, position equals to rows count if this
* method returns true. If this method returns false, than position remains
* unchnaged. Takes into account <code>showOriginal</code> flag
*
* @return True if rowset is on the last position, and false if it is not.
* @see #absolute(int aCursorPos)
* @see #getCursorPos()
* @see #size()
* @see #beforeFirst()
* @see #first()
* @see #isBeforeFirst()
* @see #previous()
* @see #next()
* @see #afterLast()
* @see #isAfterLast()
*/
public boolean last() throws InvalidCursorPositionException {
if (!isEmpty()) {
if (currentRowPos != size()) {
if (rowsetChangeSupport.fireWillScrollEvent(size())) {
int oldCurrentRowPos = currentRowPos;
currentRowPos = size();
rowsetChangeSupport.fireScrolledEvent(oldCurrentRowPos);
return true;
} else {
return false;
}
} else {
return true;
}
}
return false;
}
/**
* Moves cursor to the after last position in the rowset. It won't to
* position the rowset if it is empty. After positioning, position equals to
* rows count+1 if this method returns true. If this method returns false,
* than position remains 0. Takes into account <code>showOriginal</code>
* flag
*
* @return True if has been positioned, and false if it hasn't.
* @see #absolute(int aCursorPos)
* @see #getCursorPos()
* @see #size()
* @see #beforeFirst()
* @see #first()
* @see #isBeforeFirst()
* @see #previous()
* @see #next()
* @see #last()
* @see #isAfterLast()
*/
public boolean afterLast() throws InvalidCursorPositionException {
if (!isAfterLast()) {
if (rowsetChangeSupport.fireWillScrollEvent(size() + 1)) {
int oldCurrentRowPos = currentRowPos;
currentRowPos = size() + 1;
rowsetChangeSupport.fireScrolledEvent(oldCurrentRowPos);
return true;
} else {
return false;
}
} else {
return true;
}
}
/**
* Returns if cursor is after last row. Takes into account
* <code>showOriginal</code> flag
*
* @return True if the cursor is on after last position.
* @see #absolute(int aCursorPos)
* @see #getCursorPos()
* @see #size()
* @see #beforeFirst()
* @see #first()
* @see #isBeforeFirst()
* @see #previous()
* @see #next()
* @see #last()
* @see #afterLast()
*/
public boolean isAfterLast() {
return isEmpty() || currentRowPos > size();
}
/**
* Moves the cursor one position forward. Takes into account
* <code>showOriginal</code> flag
*
* @return True if new position is on the next row. False if the rowset is
* empty or cursor becomes after last position. In this case cusor
* is moved, but method returns false.
* @see #absolute(int aCursorPos)
* @see #getCursorPos()
* @see #size()
* @see #beforeFirst()
* @see #first()
* @see #isBeforeFirst()
* @see #previous()
* @see #last()
* @see #afterLast()
* @see #isAfterLast()
*/
public boolean next() throws InvalidCursorPositionException {
if (!isEmpty()) {
if (currentRowPos < size() + 1) {
if (currentRowPos < size()) {
if (rowsetChangeSupport.fireWillScrollEvent(currentRowPos + 1)) {
int oldCurrentRowPos = currentRowPos;
currentRowPos++;
rowsetChangeSupport.fireScrolledEvent(oldCurrentRowPos);
return true;
} else {
return false;
}
} else {
if (rowsetChangeSupport.fireWillScrollEvent(currentRowPos + 1)) {
int oldCurrentRowPos = currentRowPos;
currentRowPos++;
rowsetChangeSupport.fireScrolledEvent(oldCurrentRowPos);
}
return false;
}
}
} else {
assert currentRowPos == 0;
}
return false;
}
/**
* Moves the cursor one position backward. Takes into account
* <code>showOriginal</code> flag
*
* @return True if new position is on the previous row. False if the rowset
* is empty or cursor becomes before first position. In this case
* cusor is moved, but method returns false.
* @see #absolute(int aCursorPos)
* @see #getCursorPos()
* @see #size()
* @see #beforeFirst()
* @see #first()
* @see #isBeforeFirst()
* @see #next()
* @see #last()
* @see #afterLast()
* @see #isAfterLast()
*/
public boolean previous() throws InvalidCursorPositionException {
if (!isEmpty()) {
if (currentRowPos > 0) {
if (currentRowPos > 1) {
if (rowsetChangeSupport.fireWillScrollEvent(currentRowPos - 1)) {
int oldCurrentRowPos = currentRowPos;
currentRowPos
rowsetChangeSupport.fireScrolledEvent(oldCurrentRowPos);
return true;
} else {
return false;
}
} else {
if (rowsetChangeSupport.fireWillScrollEvent(currentRowPos - 1)) {
int oldCurrentRowPos = currentRowPos;
currentRowPos
rowsetChangeSupport.fireScrolledEvent(oldCurrentRowPos);
}
return false;
}
} else {
return false;
}
} else {
assert currentRowPos == 0;
}
return false;
}
/**
* Returns rows count in this rowset. Takes into account
* <code>showOriginal</code> flag
*
* @return Rows count in this rowset.
* @see #absolute(int aCursorPos)
* @see #getCursorPos()
* @see #beforeFirst()
* @see #first()
* @see #isBeforeFirst()
* @see #previous()
* @see #next()
* @see #last()
* @see #afterLast()
* @see #isAfterLast()
*/
public int size() {
if (showOriginal) {
return original.size();
} else {
return current.size();
}
}
/**
* Checks whether cusor is in the valid position. If not than the
* <code>InvalidCursorPositionException</code> is thrown.
*
* @throws InvalidCursorPositionException
*/
protected void checkCursor() throws InvalidCursorPositionException {
if (!isInserting()) {
if (currentRowPos < 1) {
throw new InvalidCursorPositionException("currentRowPos < 1");
}
if (currentRowPos > size()) {
throw new InvalidCursorPositionException("currentRowPos > current.size()");
}
}
}
/**
* Checks whether cusor is in the valid position, including before first and
* after last position. If not than the
* <code>InvalidCursorPositionException</code> is thrown.
*
* @throws InvalidCursorPositionException
*/
public void wideCheckCursor() throws InvalidCursorPositionException {
if (currentRowPos < 0) {
throw new InvalidCursorPositionException("currentRowPos < 0. Before before first posotion is illegal");
}
if (currentRowPos > size() + 1) {
throw new InvalidCursorPositionException("currentRowPos > current.size()+1. After after last position is illegal");
}
}
/**
* Checks whether index of column is valid for this rowset's
* <code>Fields</code>
*
* @param aColIndex
* Index of particular column.
* @throws InvalidColIndexException
*/
protected void checkColIndex(int aColIndex) throws InvalidColIndexException {
assert fields != null;
Field field = fields.get(aColIndex);
if (field == null) {
throw new InvalidColIndexException(aColIndex + " have been passed as aColIndex parameter. But it had to be >= 1 and <= " + fields.getFieldsCount());
}
}
/**
* Returns current cursor position in this rowset.
*
* @return Current cursor position in this rowset.
* @see #absolute(int aCursorPos)
* @see #size()
* @see #beforeFirst()
* @see #first()
* @see #isBeforeFirst()
* @see #previous()
* @see #next()
* @see #last()
* @see #afterLast()
* @see #isAfterLast()
*/
public int getCursorPos() {
return currentRowPos;
}
/**
* Positions rowset on specified row number. Row number is 1-based.
*
* @param aCursorPos
* Cursor position you whant to be setted in this rowset.
* @return True if cursor position in rowset equals to aCursorPos.
* @throws InvalidCursorPositionException
* @see #getCursorPos()
* @see #size()
* @see #beforeFirst()
* @see #first()
* @see #isBeforeFirst()
* @see #previous()
* @see #next()
* @see #last()
* @see #afterLast()
* @see #isAfterLast()
*/
public boolean absolute(int aCursorPos) throws InvalidCursorPositionException {
if (!isEmpty()) {
if (aCursorPos >= 1 && aCursorPos <= size()) {
if (aCursorPos != currentRowPos) {
if (rowsetChangeSupport.fireWillScrollEvent(aCursorPos)) {
int oldCurrentRowPos = currentRowPos;
currentRowPos = aCursorPos;
rowsetChangeSupport.fireScrolledEvent(oldCurrentRowPos);
return true;
} else {
return false;
}
} else {
return true;
}
} else {
return false;
}
} else {
return false;
}
}
/**
* Returns a row by ordinal number. Row number is 1-based.
*
* @param aRowNumber
* Row number you whant to be used to locate the row.
* @return Row if speciified row number is valid, null otherwise.
* @see #getCursorPos()
* @see #size()
* @see #beforeFirst()
* @see #first()
* @see #isBeforeFirst()
* @see #previous()
* @see #next()
* @see #last()
* @see #afterLast()
* @see #isAfterLast()
*/
public Row getRow(int aRowNumber) {
if (!isEmpty()) {
if (aRowNumber >= 1 && aRowNumber <= size()) {
if (showOriginal) {
return original.get(aRowNumber - 1);
} else {
return current.get(aRowNumber - 1);
}
} else {
return null;
}
} else {
return null;
}
}
/**
* Returns whether this rowset is empty.
*
* @return Whether this rowset is empty.
*/
public boolean isEmpty() {
if (showOriginal) {
return original.isEmpty();
} else {
return current.isEmpty();
}
}
/**
* Simple insert method. Inserts a new <code>Row</code> in this rowset in
* both original and current rows vectors. Initialization with current
* filter values is performed.
*/
public void insert() throws RowsetException {
insert(new Object[] {});
}
/**
* Simple insert method. Inserts a new <code>Row</code> in this rowset in
* both original and current rows arrays. First, filter's values are used
* for initialization, than <code>initingValues</code> specified is used.
* Takes into account <code>showOriginal</code> flag. If
* <code>showOriginal</code> flag is setted, than no action is performed.
*
* @param initingValues
* Values inserting row to be initialized with.
* @throws RowsetException
*/
public Row insert(Object... initingValues) throws RowsetException {
if (!showOriginal) {
assert fields != null;
Row row = new Row();
row.setFields(fields);
insert(row, false, initingValues);
return row;
} else {
return null;
}
}
/**
* Simple insert method. Inserts a new <code>Row</code> in this rowset in
* both original and current rows arrays. First, filter's values are used
* for initialization, than <code>initingValues</code> specified is used.
* Takes into account <code>showOriginal</code> flag. If
* <code>showOriginal</code> flag is setted, than no action is performed.
*
* @param insertAt
* Index new row wull be placed at. 1-Based.
* @param initingValues
* Values inserting row to be initialized with.
* @throws RowsetException
*/
public Row insertAt(int insertAt, Object... initingValues) throws RowsetException {
if (!showOriginal) {
assert fields != null;
Row row = new Row();
row.setFields(fields);
insertAt(row, false, insertAt, initingValues);
return row;
} else {
return null;
}
}
/**
* Collections - like insert method. Inserts a passed <code>Row</code> in
* this rowset in both original and current rows vectors. Initialization
* with current filter values is performed.
*
* @param toInsert
* A row to insertt in the rowset.
* @throws RowsetException
*/
public void insert(Row toInsert, boolean aAjusting) throws RowsetException {
insert(toInsert, aAjusting, new Object[] {});
}
/**
* Row insert method. Inserts a passed <code>Row</code> in this rowset in
* both original and current rows arrays. First, filter's values are used
* for initialization, than <code>initingValues</code> specified is used.
* Takes into account <code>showOriginal</code> flag. If
* <code>showOriginal</code> flag is setted, than no action is performed.
*
* @param toInsert
* A row to insert in the rowset.
* @param aAjusting
* Flag, indicating that inserting is within a batch operation
* @param initingValues
* Values inserting row to be initialized with.
* @throws RowsetException
*/
public void insert(Row toInsert, boolean aAjusting, Object... initingValues) throws RowsetException {
int insertAtPosition;
if (isBeforeFirst()) {
insertAtPosition = 1;
} else if (isAfterLast()) {
insertAtPosition = currentRowPos;
} else {
insertAtPosition = currentRowPos + 1;
}
insertAt(toInsert, aAjusting, insertAtPosition, initingValues);
}
/**
* Row insert method. Inserts a passed <code>Row</code> in this rowset in
* both original and current rows arrays. First, filter's values are used
* for initialization, than <code>initingValues</code> specified is used.
* Takes into account <code>showOriginal</code> flag. If
* <code>showOriginal</code> flag is setted, than no action is performed.
*
* @param toInsert
* A row to insert in the rowset.
* @param aAjusting
* Flag, indicating that inserting is within a batch operation
* @param insertAt
* Index the new row to be added at. 1-Based.
* @param initingValues
* Values inserting row to be initialized with.
* @throws RowsetException
*/
public void insertAt(Row toInsert, boolean aAjusting, int insertAt, Object... initingValues) throws RowsetException {
if (!showOriginal) {
assert fields != null;
if (toInsert == null) {
throw new RowsetException("Bad inserting row. It must be non null value.");
}
if (toInsert.getColumnCount() != fields.getFieldsCount()) {
throw new RowsetException("Bad column count. While inserting, columns count in a row must same with fields count in rowset fields.");
}
insertingRow = toInsert;
try {
if (rowsetChangeSupport.fireWillInsertEvent(insertingRow, aAjusting)) {
initColumns(insertingRow, initingValues);
insertingRow.setInserted();
// work on current rows list, probably filtered
List<Row> lcurrent = current;
lcurrent.add(insertAt - 1, insertingRow);
currentRowPos = insertAt;
if (activeFilter != null) {
// work on rowset's original rows vector, hided by
// active
// filter
lcurrent = activeFilter.getOriginalRows();
int lcurrentRowPos = activeFilter.getOriginalPos();
if (lcurrentRowPos == 0) { // before first
lcurrent.add(0, insertingRow);
lcurrentRowPos = 1;
} else if (lcurrentRowPos > lcurrent.size()) {
lcurrent.add(insertingRow);
// lcurrent.size() has been incremented by add()
// method.
lcurrentRowPos = lcurrent.size();
} else {
lcurrent.add(lcurrentRowPos, insertingRow);
lcurrentRowPos++;
}
activeFilter.setOriginalPos(lcurrentRowPos);
}
original.add(insertingRow);
addRow2Filters(insertingRow, -1);
invalidateLocators();
Row insertedRow = insertingRow;
modified = true;
insertedRow.addVetoableChangeListener(this);
insertedRow.addPropertyChangeListener(this);
generateInsert(insertedRow);
rowsetChangeSupport.fireRowInsertedEvent(insertedRow, aAjusting);
}
} finally {
insertingRow = null;
}
}
}
/**
* Returns whether rowset is in inserting a new row state.
*
* @return Whether rowset is inserting a row.
*/
public boolean isInserting() {
return insertingRow != null;
}
/**
* Initializes new row with supplied initialization values. Than initializes
* it with active filter values.
*
* @param aRow
* A <code>Row</code> to initialize.
* @param values
* Values the specified <code>Row</code> to initialize with.
*/
protected void initColumns(Row aRow, Object... values) throws RowsetException {
if (aRow != null) {
// key fields generation
for (int i = 1; i <= fields.getFieldsCount(); i++) {
Field field = fields.get(i);
if (field.isPk() && aRow.getColumnObject(i) == null) {
Object pkValue = RowsetUtils.generatePkValueByType(field.getTypeInfo().getType());
pkValue = Converter.convert2RowsetCompatible(pkValue, field.getTypeInfo());
aRow.setColumnObject(i, pkValue);
}
}
// user supplied fields, including values for primary keys
if (values != null && values.length > 0 && values.length % 2 == 0) {
for (int i = 0; i < values.length - 1; i += 2) {
if (values[i] != null && (values[i] instanceof Integer || values[i] instanceof Double || values[i] instanceof String || values[i] instanceof Field)) {
Field field = null;
int colIndex = 0;
if (values[i] instanceof String) {
colIndex = fields.find((String) values[i]);
field = fields.get(colIndex);
} else if (values[i] instanceof Field) {
field = (Field) values[i];
colIndex = fields.find(field.getName());
} else {
colIndex = values[i] instanceof Integer ? (Integer) values[i] : (int) Math.round((Double) values[i]);
field = fields.get(colIndex);
}
if (field != null && colIndex != 0) {
Object fieldValue = values[i + 1];
fieldValue = Converter.convert2RowsetCompatible(fieldValue, field.getTypeInfo());
aRow.setColumnObject(colIndex, fieldValue);
}
}
}
}
// filtered values to corresponding fields, excluding key fields
// This initing is also needed in aAjusting case, because otherwise
// row will
// disapear.
if (activeFilter != null) {
List<Integer> filterCriteriaFields = activeFilter.getFields();
KeySet ks = activeFilter.getKeysetApplied();
assert filterCriteriaFields != null;
assert ks != null;
assert filterCriteriaFields.size() == ks.size();
for (int i = 0; i < filterCriteriaFields.size(); i++) {
int colIndex = filterCriteriaFields.get(i);
Field field = fields.get(colIndex);
// do not touch key fields!
if (!field.isPk()) {
Object fieldValue = ks.get(i);
if (fieldValue == RowsetUtils.UNDEFINED_SQL_VALUE) {
fieldValue = null;
}
fieldValue = Converter.convert2RowsetCompatible(fieldValue, field.getTypeInfo());
aRow.setColumnObject(colIndex, fieldValue);
}
}
}
}
}
protected boolean isFilteringCriteria(int aFieldIndex) {
if (activeFilter != null) {
List<Integer> fIdxes = activeFilter.getFields();
if (fIdxes != null && fIdxes.contains(aFieldIndex)) {
return true;
}
}
return false;
}
/**
* Removes a row from all filters as aFieldIndex == -1, and from some
* filters if aFieldIndex != -1.
*
* @param aRow
* - A row to operate with
* @param aFieldIndex
* - A field index to detemine if it is filtering criteria. It
* may be -1 to force removing a row from filters
* @return True if aRow was removed from one of the filters, False
* otherwise.
* @throws RowsetException
*/
public boolean removeRowFromFilters(Row aRow, int aFieldIndex) throws RowsetException {
boolean removed = false;
if (filters != null) {
for (Filter hf : filters) {
assert hf != null;
if (aFieldIndex == -1 || hf.isFilteringCriteria(aFieldIndex)) {
boolean lRemoved = hf.remove(aRow);
if (lRemoved) {
removed = true;
}
}
}
}
return removed;
}
/**
* Adds a row to all filters as aFieldIndex == -1, and to some filters if
* aFieldIndex != -1.
*
* @param aRow
* - A row to operate with
* @param aFieldIndex
* - A field index to detemine if it is filtering criteria. It
* may be -1 to force adding a row to filters
* @return True if aRow was added to one of the filters, False otherwise.
* @throws RowsetException
*/
public boolean addRow2Filters(Row aRow, int aFieldIndex) throws RowsetException {
boolean added = false;
if (filters != null) {
for (Filter hf : filters) {
assert hf != null;
if (aFieldIndex == -1 || hf.isFilteringCriteria(aFieldIndex)) {
boolean lAdded = hf.add(aRow);
if (lAdded) {
added = true;
}
}
}
}
return added;
}
/**
* Returns if <code>showOriginal</code> flag is set.
*
* @return True if showOriginal flag is set.
*/
public boolean isShowOriginal() {
return showOriginal;
}
/**
* Sets <code>showOriginal</code> flag to this rowset.
*
* @param aShowOriginal
* Flag, indicating this rowset show original rows vector.
*/
public void setShowOriginal(boolean aShowOriginal) {
showOriginal = aShowOriginal;
if (currentRowPos < 0) {
currentRowPos = 0;
}
if (currentRowPos > size() + 1) {
currentRowPos = size() + 1;
}
}
/**
* Deletes current row. It means current row is marked as deleted and
* removed from cuurent rows vector. If cursor is not on the valid position
* no action is performed. Takes into account <code>showOriginal</code>
* flag. If <code>showOriginal</code> flag is setted, than no action is
* performed. If <code>showOriginal</code> flag setted, than no action is
* performed.
*
* @see #delete(java.util.Set)
* @see #deleteAll()
* @throws RowsetException
*/
public void delete() throws RowsetException {
if (!showOriginal) {
checkCursor();
Row row = getCurrentRow();
assert row != null;
if (rowsetChangeSupport.fireWillDeleteEvent(row)) {
row.setDeleted();
row.removePropertyChangeListener(this);
row.removeVetoableChangeListener(this);
generateDelete(row);
current.remove(currentRowPos - 1);
if (!isEmpty()) {
if (isBeforeFirst()) {
currentRowPos = 1;
}
if (isAfterLast()) {
currentRowPos = current.size();
}
} else {
currentRowPos = 0;
}
invalidateLocators();
removeRowFromFilters(row, -1);
modified = true;
rowsetChangeSupport.fireRowDeletedEvent(row);
}
}
}
/**
* Deletes all rows in the rowset. Rows are marked as deleted and removed
* from cuurent rows vector. After deleting, cursor position becomes invalid
* and both <code>isBeforeFirst()</code> and <code>isAfterLast()</code> must
* return true. Subsequent calls to this method perform no action. Takes
* into account <code>showOriginal</code> flag. If <code>showOriginal</code>
* flag setted, than no action is performed.
*
* @see #isBeforeFirst()
* @see #isAfterLast()
* @see #delete()
* @see #delete(java.util.Set)
* @throws RowsetException
*/
public void deleteAll() throws RowsetException {
if (!showOriginal) {
/**
* The following approach is very harmful! If any events listener
* whould like to veto the deletion, than the cycle never ends.
* while(!isEmpty()) delete();
*/
boolean wasBeforeFirst = isBeforeFirst();
boolean wasAfterLast = isAfterLast();
for (int i = current.size() - 1; i >= 0; i
Row row = current.get(i);
assert row != null;
if (rowsetChangeSupport.fireWillDeleteEvent(row, i != 0)) { // last
// iteration
// will
// fire
// non-ajusting
// event
invalidateLocators();
row.setDeleted();
row.removePropertyChangeListener(this);
row.removeVetoableChangeListener(this);
generateDelete(row);
current.remove(i);
removeRowFromFilters(row, -1);
modified = true;
currentRowPos = i + 1;
rowsetChangeSupport.fireRowDeletedEvent(row, i != 0); // last
// iteration
// will
// fire
// non-ajusting
// event
currentRowPos = Math.min(currentRowPos, current.size());
}
}
if (current.isEmpty()) {
currentRowPos = 0;
} else {
if (wasBeforeFirst) {
currentRowPos = 0;
}
if (wasAfterLast) {
currentRowPos = size() + 1;
}
if (!wasBeforeFirst && !wasAfterLast && currentRowPos > size()) {
currentRowPos = size();
}
}
wideCheckCursor();
}
}
public void deleteRow(Row aRow) throws RowsetException {
delete(Collections.singleton(aRow));
}
/**
* Deletes specified rows from the rowset. Rows are marked as deleted and
* removed from cuurent rows vector. After deleting, cursor position becomes
* invalid and rowset may be repositioned.
*
* @param rows2Delete
* Set of rows to be deleted from the rowset
* @see #isBeforeFirst()
* @see #isAfterLast()
* @see #delete()
* @see #deleteAll()
* @throws RowsetException
*/
public void delete(Collection<Row> aRows2Delete) throws RowsetException {
if (!showOriginal) {
Set<Row> rows2Delete = new HashSet<>();
rows2Delete.addAll(aRows2Delete);
boolean wasBeforeFirst = isBeforeFirst();
boolean wasAfterLast = isAfterLast();
for (int i = current.size() - 1; i >= 0; i
Row row = current.get(i);
assert row != null;
if (rows2Delete.contains(row)) {
rows2Delete.remove(row);
if (rowsetChangeSupport.fireWillDeleteEvent(row, !rows2Delete.isEmpty())) { // last
// iteration
// will
// fire
// non-ajusting
// event
invalidateLocators();
row.setDeleted();
row.removePropertyChangeListener(this);
row.removeVetoableChangeListener(this);
generateDelete(row);
current.remove(i);
removeRowFromFilters(row, -1);
modified = true;
currentRowPos = i + 1;
rowsetChangeSupport.fireRowDeletedEvent(row, !rows2Delete.isEmpty()); // last
// iteration
// will
// fire
// non-ajusting
// event
currentRowPos = Math.min(currentRowPos, current.size());
}
}
}
if (current.isEmpty()) {
currentRowPos = 0;
} else {
if (wasBeforeFirst) {
currentRowPos = 0;
}
if (wasAfterLast) {
currentRowPos = size() + 1;
}
if (!wasBeforeFirst && !wasAfterLast && currentRowPos > size()) {
currentRowPos = size();
}
}
wideCheckCursor();
}
}
/**
* Deletes specified row from the rowset by index. Row is marked as deleted
* and removed from cuurent rows vector. After deleting, cursor position
* becomes invalid and rowset may be repositioned.
*
* @param aRowIndex
* Index of row to be deleted from the rowset. aRowIndex is
* 1-based.
* @see #isBeforeFirst()
* @see #isAfterLast()
* @see #delete()
* @see #deleteAll()
* @throws RowsetException
*/
public void deleteAt(int aRowIndex) throws RowsetException {
if (!showOriginal) {
boolean wasBeforeFirst = isBeforeFirst();
boolean wasAfterLast = isAfterLast();
if (aRowIndex >= 1 && aRowIndex <= size()) {
Row row = current.get(aRowIndex - 1);
assert row != null;
if (rowsetChangeSupport.fireWillDeleteEvent(row, false)) {
// last iteration will fire non-ajusting event
invalidateLocators();
row.setDeleted();
row.removePropertyChangeListener(this);
row.removeVetoableChangeListener(this);
generateDelete(row);
current.remove(aRowIndex - 1);
removeRowFromFilters(row, -1);
modified = true;
currentRowPos = aRowIndex;
rowsetChangeSupport.fireRowDeletedEvent(row, false);
// last iteration will fire non-ajusting event
currentRowPos = Math.min(currentRowPos, current.size());
}
if (current.isEmpty()) {
currentRowPos = 0;
} else {
if (wasBeforeFirst) {
currentRowPos = 0;
}
if (wasAfterLast) {
currentRowPos = size() + 1;
}
if (!wasBeforeFirst && !wasAfterLast && currentRowPos > size()) {
currentRowPos = size();
}
}
wideCheckCursor();
} else
throw new InvalidCursorPositionException("Cursor position pointing to deleted row must be in range [1, size()]");
}
}
public Object getJsObject(String aFieldName) throws Exception {
try {
return Utils.toJs(getObject(fields.find(aFieldName)));
} catch (Exception ex) {
if (isEmpty())
throw new Exception("Attempt to read data field: " + aFieldName + " under cursor from empty dataset");
else
throw ex;
}
}
/**
* Returns value of particular field of current row by index of column.
*
* @param colIndex
* Index of particular field.
* @return Value of perticular field of current row by index of column.
* @throws InvalidColIndexException
* @throws InvalidCursorPositionException
* @see #updateObject(int colIndex, Object aValue)
*/
public Object getObject(int colIndex) throws InvalidColIndexException, InvalidCursorPositionException {
checkCursor();
checkColIndex(colIndex);
Row row = getCurrentRow();
assert row != null;
if (showOriginal) {
return row.getOriginalColumnObject(colIndex);
} else {
return row.getColumnObject(colIndex);
}
}
/**
* Returns value of particular field of current row by index of column as
* string.
*
* @param colIndex
* Index of particular field.
* @return Value of perticular field of current row by index of column as
* string.
* @throws InvalidColIndexException
* @throws InvalidCursorPositionException
* @see #updateObject(int colIndex, Object aValue)
* @see #getObject(int colIndex)
*/
public String getString(int colIndex) throws InvalidColIndexException, InvalidCursorPositionException {
return (String) getObject(colIndex);
}
/**
* Returns value of particular field of current row by index of column as
* integer number.
*
* @param colIndex
* Index of particular field.
* @return Value of perticular field of current row by index of column as
* integer number.
* @throws InvalidColIndexException
* @throws InvalidCursorPositionException
* @see #updateObject(int colIndex, Object aValue)
* @see #getObject(int colIndex)
*/
public Integer getInt(int colIndex) throws InvalidColIndexException, InvalidCursorPositionException {
Object value = getObject(colIndex);
if (value instanceof Integer) {
return (Integer) getObject(colIndex);
} else if (value instanceof Number) {
return ((Number) value).intValue();
} else {
return null;
}
}
/**
* Returns value of particular field of current row by index of column as
* date.
*
* @param colIndex
* Index of particular field.
* @return Value of perticular field of current row by index of column as
* date.
* @throws InvalidColIndexException
* @throws InvalidCursorPositionException
* @see #updateObject(int colIndex, Object aValue)
* @see #getObject(int colIndex)
*/
public Date getDate(int colIndex) throws InvalidColIndexException, InvalidCursorPositionException {
return (Date) getObject(colIndex);
}
/**
* Returns value of particular field of current row by index of column as
* double number.
*
* @param colIndex
* Index of particular field.
* @return Value of perticular field of current row by index of column as
* double number.
* @throws InvalidColIndexException
* @throws InvalidCursorPositionException
* @see #updateObject(int colIndex, Object aValue)
* @see #getObject(int colIndex)
*/
public Double getDouble(int colIndex) throws InvalidColIndexException, InvalidCursorPositionException {
Object value = getObject(colIndex);
if (value instanceof Double) {
return (Double) getObject(colIndex);
} else if (value instanceof Number) {
return ((Number) value).doubleValue();
} else {
return null;
}
}
/**
* Returns value of particular field of current row by index of column as
* float number.
*
* @param colIndex
* Index of particular field.
* @return Value of perticular field of current row by index of column as
* float number.
* @throws InvalidColIndexException
* @throws InvalidCursorPositionException
* @see #updateObject(int colIndex, Object aValue)
* @see #getObject(int colIndex)
*/
public Float getFloat(int colIndex) throws InvalidColIndexException, InvalidCursorPositionException {
Object value = getObject(colIndex);
if (value instanceof Float) {
return (Float) getObject(colIndex);
} else if (value instanceof Number) {
return ((Number) value).floatValue();
} else {
return null;
}
}
/**
* Returns value of particular field of current row by index of column as
* boolean value.
*
* @param colIndex
* Index of particular field.
* @return Value of perticular field of current row by index of column as
* boolean value.
* @throws InvalidColIndexException
* @throws InvalidCursorPositionException
* @see #updateObject(int colIndex, Object aValue)
* @see #getObject(int colIndex)
*/
public Boolean getBoolean(int colIndex) throws InvalidColIndexException, InvalidCursorPositionException {
return (Boolean) getObject(colIndex);
}
/**
* Returns value of particular field of current row by index of column as
* short number.
*
* @param colIndex
* Index of particular field.
* @return Value of perticular field of current row by index of column as
* short number.
* @throws InvalidColIndexException
* @throws InvalidCursorPositionException
* @see #updateObject(int colIndex, Object aValue)
* @see #getObject(int colIndex)
*/
public Short getShort(int colIndex) throws InvalidColIndexException, InvalidCursorPositionException {
Object value = getObject(colIndex);
if (value instanceof Short) {
return (Short) getObject(colIndex);
} else if (value instanceof Number) {
return ((Number) value).shortValue();
} else {
return null;
}
}
/**
* Returns value of particular field of current row by index of column as
* long number.
*
* @param colIndex
* Index of particular field.
* @return Value of perticular field of current row by index of column as
* long number.
* @throws InvalidColIndexException
* @throws InvalidCursorPositionException
* @see #updateObject(int colIndex, Object aValue)
* @see #getObject(int colIndex)
*/
public Long getLong(int colIndex) throws InvalidColIndexException, InvalidCursorPositionException {
Object value = getObject(colIndex);
if (value instanceof Long) {
return (Long) getObject(colIndex);
} else if (value instanceof Number) {
return ((Number) value).longValue();
} else {
return null;
}
}
public void updateJsObject(String aFieldName, Object aValue) throws Exception {
updateObject(fields.find(aFieldName), Utils.toJava(aValue));
}
/**
* Updates particular field of the current record.
*
* @param colIndex
* Index of particular field. 1-Based.
* @param aValue
* Value you whant to be setted to field.
* @throws RowsetException
*/
public void updateObject(int colIndex, Object aValue) throws RowsetException {
checkCursor();
checkColIndex(colIndex);
Row row = getCurrentRow();
assert row != null;
row.setColumnObject(colIndex, aValue);
}
private int extractColIndex(PropertyChangeEvent evt) {
int colIndex = 0;
if (evt.getPropagationId() != null && evt.getPropagationId() instanceof Integer) {
colIndex = (Integer) evt.getPropagationId();
} else {
colIndex = fields.find(evt.getPropertyName());
}
return colIndex;
}
@Override
public void vetoableChange(PropertyChangeEvent evt) throws Exception {
int colIndex = extractColIndex(evt);
assert colIndex != 0;
assert evt.getSource() instanceof Row;
if (!rowsetChangeSupport.fireWillChangeEvent((Row) evt.getSource(), colIndex, evt.getOldValue(), evt.getNewValue())) {
throw new Exception("One of rowset's change listeners have prohibited a column change");
}
}
@Override
public void propertyChange(PropertyChangeEvent evt) {
try {
int colIndex = extractColIndex(evt);
assert colIndex != 0;
assert evt.getSource() instanceof Row;
Row row = (Row) evt.getSource();
invalidateLocatorsByColIndex(colIndex);
row.getInternalCurrentValues().set(colIndex - 1, evt.getOldValue());
removeRowFromFilters(row, colIndex);
row.getInternalCurrentValues().set(colIndex - 1, evt.getNewValue());
addRow2Filters(row, colIndex);
modified = true;
generateUpdate(colIndex, row, evt.getOldValue(), evt.getNewValue());
rowsetChangeSupport.fireRowChangedEvent(row, colIndex, evt.getOldValue(), evt.getNewValue());
if (activeFilter != null && immediateFilter && activeFilter.isFilteringCriteria(colIndex)) {
activeFilter.refilterRowset();
}
} catch (RowsetException ex) {
Logger.getLogger(Rowset.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Returns <code>Row</code> at current cursor position. Doesn't perform
* current position check, so it has to be called internally.
*
* @return <code>Row</code> at current cursor position.
*/
public Row getCurrentRow() {
if (insertingRow != null) {
return insertingRow;
} else if (!isEmpty() && !isBeforeFirst() && !isAfterLast()) {
if (showOriginal) {
return original.get(currentRowPos - 1);
} else {
return current.get(currentRowPos - 1);
}
} else {
return null;
}
}
/**
* Applies modifications maded to this rowset. After that no difference
* between original and current rows vectors and row's data have place.
*/
public void currentToOriginal() {
original.clear();
List<Row> lcurrent = null;
if (activeFilter != null && activeFilter.isApplied()) {
lcurrent = activeFilter.getOriginalRows();
} else {
lcurrent = current;
}
original.addAll(lcurrent);
for (int i = original.size() - 1; i >= 0; i
Row row = original.get(i);
assert row != null;
row.currentToOriginal();
row.clearInserted();
if (row.isDeleted()) {// Should never happen. Added for code
// strength in case of mark and sweep row
// deletion.
original.remove(i);
lcurrent.remove(i);
}
}
modified = false;
}
/**
* Cancels modifications maded to this rowset. After that no difference
* between original and current rows vectors and row's data have place.
*/
public void originalToCurrent() throws RowsetException {
Filter wasFilter = activeFilter;
boolean wasApplied = false;
if (wasFilter != null) {
wasApplied = wasFilter.isApplied();
wasFilter.cancelFilter();
}
try {
current.clear();
current.addAll(original);
for (int i = current.size() - 1; i >= 0; i
Row row = current.get(i);
assert row != null;
row.originalToCurrent();
if (row.isInserted()) {
row.removePropertyChangeListener(this);
row.removeVetoableChangeListener(this);
current.remove(i);
original.remove(i);
}
row.clearDeleted();
}
modified = false;
invalidateLocators();
invalidateFilters();
} finally {
if (wasFilter != null && wasApplied) {
wasFilter.refilterRowset();// implicit setCurrent() call.
}
}
}
protected void generateInsert(Row aRow) {
if (flow != null && flow.getChangeLog() != null) {
List<Change> changesLog = flow.getChangeLog();
Insert insert = new Insert(flow.getEntityId());
List<Change.Value> data = new ArrayList<>();
for (int i = 0; i < aRow.getCurrentValues().length; i++) {
Field field = aRow.getFields().get(i + 1);
Object value = aRow.getCurrentValues()[i];
if (value != null || field.isStrong4Insert()) {
data.add(new Change.Value(field.getName(), value, field.getTypeInfo()));
}
}
insert.data = data.toArray(new Change.Value[] {});
changesLog.add(insert);
aRow.setInserted(insert);
}
}
private Change.Value[] generateChangeLogKeys(int colIndex, Row aRow, Object oldValue) {
if (fields != null) {
List<Change.Value> keys = new ArrayList<>();
for (int i = 1; i <= fields.getFieldsCount(); i++) {
Field field = fields.get(i);
// Some tricky processing of primary key modification case ...
if (field.isPk()) {
Object value = aRow.getInternalCurrentValues().get(i - 1);
if (i == colIndex) {
value = oldValue;
}
keys.add(new Change.Value(field.getName(), value, field.getTypeInfo()));
}
}
return keys.toArray(new Change.Value[] {});
} else {
return null;
}
}
protected void generateUpdate(int colIndex, Row aRow, Object oldValue, Object newValue) {
if (fields != null && flow != null && flow.getChangeLog() != null) {
List<Change> changesLog = flow.getChangeLog();
Field field = fields.get(colIndex);
boolean insertComplemented = tryToComplementInsert(aRow, field, newValue);
if (!insertComplemented) {
Update update = new Update(flow.getEntityId());
update.data = new Change.Value[] { new Change.Value(field.getName(), newValue, field.getTypeInfo()) };
update.keys = generateChangeLogKeys(colIndex, aRow, oldValue);
changesLog.add(update);
}
}
}
protected void generateDelete(Row aRow) {
if (flow != null && flow.getChangeLog() != null) {
List<Change> changesLog = flow.getChangeLog();
Delete delete = new Delete(flow.getEntityId());
delete.keys = generateChangeLogKeys(-1, aRow, null);
changesLog.add(delete);
}
}
/**
* Creates and returns new filter based on this rowset.
*
* @return New filter based on this rowset.
*/
public Filter createFilter() {
Filter hf = orderersFactory.createFilter();
filters.add(hf);
return hf;
}
/**
* Creates and returns new locator based on this rowset.
*
* @return New locator based on this rowset.
*/
public Locator createLocator() {
Locator hl = orderersFactory.createLocator();
locators.add(hl);
return hl;
}
/**
* Creates locator, that doesn't distinguish the null key and key that is
* not found in the rowset by <code>aParentColIndex</code> with
* <code>aByPkLocator</code>
*
* @param aParentColIndex
* Index of column that is used to achive key values to locate
* "parent" rows.
* @param aByPkLocator
* A <code>Locator</code> that is used to locate "parent" rows.
* @return New locator.
*/
public Locator createParentLocator(int aParentColIndex, Locator aByPkLocator) {
Locator hl = new ParentLocator(this, aParentColIndex, aByPkLocator);
locators.add(hl);
return hl;
}
/**
* Removes specified filter from this rowset.
*
* @param aFilter
* Locator object to be removed.
* @throws RowsetException
*/
public void removeFilter(Filter aFilter) throws RowsetException {
if (aFilter == activeFilter) {
activeFilter.cancelFilter();
}
filters.remove(aFilter);
aFilter.die();
}
/**
* Removes specified locator from this rowset.
*
* @param aLocator
* Locator object to be removed.
*/
public void removeLocator(Locator aLocator) {
locators.remove(aLocator);
}
/**
* Service method to sort current vector of rows.
*
* @param aComparator
* Comparator to use while sorting rows.
* @throws InvalidCursorPositionException
*/
public void sort(Comparator<Row> aComparator) throws InvalidCursorPositionException {
if (aComparator != null) {
if (rowsetChangeSupport.fireWillSortEvent()) {
Collections.sort(current, aComparator);
invalidateLocators();
rowsetChangeSupport.fireSortedEvent();
}
}
}
public void reverse() throws InvalidCursorPositionException {
if (rowsetChangeSupport.fireWillSortEvent()) {
Collections.reverse(current);
invalidateLocators();
rowsetChangeSupport.fireSortedEvent();
}
}
/*
* Invlidates all installed locators
*/
public void invalidateLocators() {
if (locators != null) {
for (Locator loc : locators) {
assert loc != null;
loc.invalidate();
}
}
}
/*
* Invlidates all installed filters and deactivates them. Also it cancels
* any active filter.
*/
protected void invalidateFilters() {
activeFilter = null;
if (filters != null) {
for (Filter filter : filters) {
assert filter != null;
filter.deactivate();
filter.invalidate();
}
}
}
/**
* Invlidates all installed locators with constrainting set including
* <code>aColIndex</code>.
*
* @param aColIndex
* Column index to examine constraints with.
*/
public void invalidateLocatorsByColIndex(int aColIndex) {
if (locators != null) {
for (Locator loc : locators) {
assert loc != null;
if (loc.getFields().contains(aColIndex)) {
loc.invalidate();
}
}
}
}
/**
* Returns array of locators installed on this rowset.
*
* @return Array of locators installed on this rowset.
*/
public Locator[] getLocators() {
Locator[] res = new Locator[locators.size()];
return locators.toArray(res);
}
/**
* Returns array of filters installed on this rowset.
*
* @return Array of filters installed on this rowset.
*/
public Filter[] getFilters() {
Filter[] res = new Filter[filters.size()];
return filters.toArray(res);
}
private boolean tryToComplementInsert(Row aRow, Field field, Object newValue) {
boolean insertComplemented = false;
Insert insertChange = aRow.getInsertChange();
if (insertChange != null && !field.isNullable()) {
boolean met = false;
for (Change.Value value : insertChange.data) {
if (value.name.equalsIgnoreCase(field.getName())) {
met = true;
break;
}
}
if (!met) {
Change.Value[] newdata = new Change.Value[insertChange.data.length + 1];
newdata[newdata.length - 1] = new Change.Value(field.getName(), newValue, field.getTypeInfo());
for (int i = 0; i < insertChange.data.length; i++) {
newdata[i] = insertChange.data[i];
}
insertChange.data = newdata;
insertComplemented = true;
}
}
return insertComplemented;
}
}
|
package org.apache.commons.vfs.provider.ftp;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.ArrayList;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.vfs.FileName;
import org.apache.commons.vfs.FileSystemException;
import org.apache.commons.vfs.FileType;
import org.apache.commons.vfs.FileObject;
import org.apache.commons.vfs.provider.AbstractFileObject;
import org.apache.commons.vfs.util.MonitorInputStream;
import org.apache.commons.vfs.util.MonitorOutputStream;
final class FtpFileObject
extends AbstractFileObject
{
private static final FTPFile[] EMPTY_FTP_FILE_ARRAY = {};
private final FtpFileSystem ftpFs;
private final String relPath;
// Cached info
private FTPFile fileInfo;
private FTPFile[] children;
public FtpFileObject( final FileName name,
final FtpFileSystem fileSystem,
final FileName rootName )
throws FileSystemException
{
super( name, fileSystem );
ftpFs = fileSystem;
relPath = rootName.getRelativeName( name );
}
/**
* Called by child file objects, to locate their ftp file info.
*/
private FTPFile getChildFile( final String name, final boolean flush )
throws IOException
{
if ( flush )
{
children = null;
}
// List the children of this file
doGetChildren();
// Look for the requested child
// TODO - use hash table
for ( int i = 0; i < children.length; i++ )
{
final FTPFile child = children[ i ];
if ( child.getName().equals( name ) )
{
// TODO - should be using something else to compare names
return child;
}
}
return null;
}
/**
* Fetches the children of this file, if not already cached.
*/
private void doGetChildren() throws IOException
{
if ( children != null )
{
return;
}
final FTPClient client = ftpFs.getClient();
try
{
final FTPFile[] tmpChildren = client.listFiles( relPath );
if ( tmpChildren == null || tmpChildren.length == 0 )
{
children = EMPTY_FTP_FILE_ARRAY;
}
else
{
// Remove '.' and '..' elements
final ArrayList childList = new ArrayList();
for ( int i = 0; i < tmpChildren.length; i++ )
{
final FTPFile child = tmpChildren[ i ];
if ( ! child.getName().equals( "." )
&& !child.getName().equals( ".." ) )
{
childList.add( child );
}
}
children = (FTPFile[])childList.toArray( new FTPFile[ childList.size() ] );
}
}
finally
{
ftpFs.putClient( client );
}
}
/**
* Attaches this file object to its file resource.
*/
protected void doAttach()
throws IOException
{
// Get the parent folder to find the info for this file
getInfo( false );
}
/** Fetches the info for this file. */
private void getInfo( boolean flush ) throws IOException
{
final FtpFileObject parent = (FtpFileObject)getParent();
if ( parent != null )
{
fileInfo = parent.getChildFile( getName().getBaseName(), flush );
}
else
{
// Assume the root is a directory and exists
fileInfo = new FTPFile();
fileInfo.setType( FTPFile.DIRECTORY_TYPE );
}
}
/**
* Detaches this file object from its file resource.
*/
protected void doDetach()
{
fileInfo = null;
children = null;
}
/**
* Called when the children of this file change.
*/
protected void onChildrenChanged()
{
children = null;
}
/**
* Called when the type or content of this file changes.
*/
protected void onChange() throws IOException
{
children = null;
getInfo( true );
}
/**
* Determines the type of the file, returns null if the file does not
* exist.
*/
protected FileType doGetType()
throws Exception
{
if ( fileInfo == null )
{
return FileType.IMAGINARY;
}
else if ( fileInfo.isDirectory() )
{
return FileType.FOLDER;
}
else if ( fileInfo.isFile() )
{
return FileType.FILE;
}
else if ( fileInfo.isSymbolicLink() )
{
// TODO - add generic support for links
final String path = fileInfo.getLink();
final FileObject target = getParent().resolveFile( path );
return target.getType();
}
throw new FileSystemException( "vfs.provider.ftp/get-type.error", getName() );
}
/**
* Lists the children of the file.
*/
protected String[] doListChildren()
throws Exception
{
// List the children of this file
doGetChildren();
final String[] childNames = new String[ children.length ];
for ( int i = 0; i < children.length; i++ )
{
final FTPFile child = children[ i ];
childNames[ i ] = child.getName();
}
return childNames;
}
/**
* Deletes the file.
*/
protected void doDelete() throws Exception
{
final boolean ok;
final FTPClient ftpClient = ftpFs.getClient();
try
{
if ( fileInfo.isDirectory() )
{
ok = ftpClient.removeDirectory( relPath );
}
else
{
ok = ftpClient.deleteFile( relPath );
}
}
finally
{
ftpFs.putClient( ftpClient );
}
if ( !ok )
{
throw new FileSystemException( "vfs.provider.ftp/delete-file.error", getName() );
}
fileInfo = null;
children = EMPTY_FTP_FILE_ARRAY;
}
/**
* Creates this file as a folder.
*/
protected void doCreateFolder()
throws Exception
{
final boolean ok;
final FTPClient client = ftpFs.getClient();
try
{
ok = client.makeDirectory( relPath );
}
finally
{
ftpFs.putClient( client );
}
if ( !ok )
{
throw new FileSystemException( "vfs.provider.ftp/create-folder.error", getName() );
}
}
/**
* Returns the size of the file content (in bytes).
*/
protected long doGetContentSize() throws Exception
{
return fileInfo.getSize();
}
/**
* get the last modified time on an ftp file
* @see org.apache.commons.vfs.provider.AbstractFileObject#doGetLastModifiedTime()
*/
protected long doGetLastModifiedTime() throws Exception
{
return ( fileInfo.getTimestamp().getTime().getTime() );
}
/**
* get the last modified time on an ftp file
* @param modtime the time to set on the ftp file
* @see org.apache.commons.vfs.provider.AbstractFileObject#doSetLastModifiedTime(long)
*/
protected void doSetLastModifiedTime( final long modtime ) throws Exception
{
final Date d = new Date( modtime );
final Calendar c = new GregorianCalendar();
c.setTime( d );
fileInfo.setTimestamp( c );
}
/**
* Creates an input stream to read the file content from.
*/
protected InputStream doGetInputStream() throws Exception
{
final FTPClient client = ftpFs.getClient();
final InputStream instr = client.retrieveFileStream( relPath );
return new FtpInputStream( client, instr );
}
/**
* Creates an output stream to write the file content to.
*/
protected OutputStream doGetOutputStream()
throws Exception
{
final FTPClient client = ftpFs.getClient();
return new FtpOutputStream( client, client.storeFileStream( relPath ) );
}
/**
* An InputStream that monitors for end-of-file.
*/
private class FtpInputStream
extends MonitorInputStream
{
private final FTPClient client;
public FtpInputStream( final FTPClient client, final InputStream in )
{
super( in );
this.client = client;
}
/**
* Called after the stream has been closed.
*/
protected void onClose() throws IOException
{
final boolean ok;
try
{
ok = client.completePendingCommand();
}
finally
{
ftpFs.putClient( client );
}
if ( !ok )
{
throw new FileSystemException( "vfs.provider.ftp/finish-get.error", getName() );
}
}
}
/**
* An OutputStream that monitors for end-of-file.
*/
private class FtpOutputStream
extends MonitorOutputStream
{
private final FTPClient client;
public FtpOutputStream( final FTPClient client, final OutputStream outstr )
{
super( outstr );
this.client = client;
}
/**
* Called after this stream is closed.
*/
protected void onClose() throws IOException
{
final boolean ok;
try
{
ok = client.completePendingCommand();
}
finally
{
ftpFs.putClient( client );
}
if ( !ok )
{
throw new FileSystemException( "vfs.provider.ftp/finish-put.error", getName() );
}
}
}
}
|
/* Generated By:JJTree: Do not edit this line. ASTMethod.java */
package org.apache.velocity.runtime.parser.node;
import java.lang.reflect.Method;
import org.apache.velocity.Context;
import org.apache.velocity.runtime.parser.*;
import org.apache.velocity.util.introspection.Introspector;
public class ASTMethod extends SimpleNode
{
private String methodName;
private int paramCount;
private Method method;
private Object[] params;
public ASTMethod(int id)
{
super(id);
}
public ASTMethod(Parser p, int id)
{
super(p, id);
}
/** Accept the visitor. **/
public Object jjtAccept(ParserVisitor visitor, Object data)
{
return visitor.visit(this, data);
}
public Object init(Context context, Object data)
throws Exception
{
methodName = getFirstToken().image;
paramCount = jjtGetNumChildren() - 1;
params = new Object[paramCount];
// Now the parameters have to be processed, there
// may be references contained within that need
// to be introspected.
for (int i = 0; i < paramCount; i++)
jjtGetChild(i + 1).init(context, null);
for (int j = 0; j < paramCount; j++)
params[j] = jjtGetChild(j + 1).value(context);
//method = Introspector.getMethod((Class) data, methodName, paramCount);
method = Introspector.getMethod((Class) data, methodName, params);
return method.getReturnType();
}
public Object execute(Object o, Context context)
{
// I need to pass in the arguments to the
// method.
for (int j = 0; j < paramCount; j++)
params[j] = jjtGetChild(j + 1).value(context);
try
{
return method.invoke(o, params);
}
catch (Exception e)
{
return null;
}
}
}
|
package org.jdesktop.swingx.action;
import java.awt.Insets;
import java.beans.PropertyChangeListener;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.swing.AbstractButton;
import javax.swing.Action;
import javax.swing.ActionMap;
import javax.swing.ButtonGroup;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JComponent;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.JToggleButton;
import javax.swing.JToolBar;
/**
* Creates user interface elements based on action ids and lists of action ids.
* All action ids must represent actions managed by the ActionManager.
* <p>
* <h3>Action Lists</h3>
* Use the createXXX(List) methods to construct containers of actions like menu
* bars, menus, popups and toolbars from actions represented as action ids in a
* <i>java.util.List</i>. Each element in the action-list can be one of 3 types:
* <ul>
* <li>action id: corresponds to an action managed by the ActionManager
* <li>null: indicates a separator should be inserted.
* <li>java.util.List: represents a submenu. See the note below which describes
* the configuration of menus.
* </li>
* The order of elements in an action-list determines the arrangement of the ui
* components which are contructed from the action-list.
* <p>
* For a menu or submenu, the first element in the action-list represents a menu
* and subsequent elements represent menu items or separators (if null).
* <p>
* This class can be used as a general component factory which will construct
* components from Actions if the <code>create<comp>(Action,...)</code>
* methods are used.
*
* @see ActionManager
*/
public class ActionContainerFactory {
/**
* Standard margin for toolbar buttons to improve their look
*/
private static Insets TOOLBAR_BUTTON_MARGIN = new Insets(1, 1, 1, 1);
private ActionMap manager;
// Map between group id + component and the ButtonGroup
private Map<Integer, ButtonGroup> groupMap;
/**
* Constructs an container factory which uses the default
* ActionManager.
*
*/
public ActionContainerFactory() {
}
/**
* Constructs an container factory which uses managed actions.
*
* @param manager use the actions managed with this manager for
* constructing ui componenents.
*/
public ActionContainerFactory(ActionMap manager) {
setActionManager(manager);
}
/**
* Gets the ActionManager instance. If the ActionManager has not been explicitly
* set then the default ActionManager instance will be used.
*
* @return the ActionManager used by the ActionContainerFactory.
* @see #setActionManager
*/
public ActionMap getActionManager() {
if (manager == null) {
manager = ActionManager.getInstance();
}
return manager;
}
/**
* Sets the ActionManager instance that will be used by this
* ActionContainerFactory
*/
public void setActionManager(ActionMap manager) {
this.manager = manager;
}
/**
* Constructs a toolbar from an action-list id. By convention,
* the identifier of the main toolbar should be "main-toolbar"
*
* @param list a list of action ids used to construct the toolbar.
* @return the toolbar or null
*/
public JToolBar createToolBar(Object[] list) {
return createToolBar(Arrays.asList(list));
}
/**
* Constructs a toolbar from an action-list id. By convention,
* the identifier of the main toolbar should be "main-toolbar"
*
* @param list a list of action ids used to construct the toolbar.
* @return the toolbar or null
*/
public JToolBar createToolBar(List<? extends Object> list) {
JToolBar toolbar = new JToolBar();
Iterator<? extends Object> iter = list.iterator();
while(iter.hasNext()) {
Object element = iter.next();
if (element == null) {
toolbar.addSeparator();
} else {
AbstractButton button = createButton(element, toolbar);
// toolbar buttons shouldn't steal focus
button.setFocusable(false);
/*
* TODO
* The next two lines improve the default look of the buttons.
* This code should be changed to retrieve the default look
* from some UIDefaults object.
*/
button.setMargin(TOOLBAR_BUTTON_MARGIN);
button.setBorderPainted(false);
toolbar.add(button);
}
}
return toolbar;
}
/**
* Constructs a popup menu from an array of action ids.
*
* @param list an array of action ids used to construct the popup.
* @return the popup or null
*/
public JPopupMenu createPopup(Object[] list) {
return createPopup(Arrays.asList(list));
}
/**
* Constructs a popup menu from a list of action ids.
*
* @param list a list of action ids used to construct the popup.
* @return the popup or null
*/
public JPopupMenu createPopup(List<? extends Object> list) {
JPopupMenu popup = new JPopupMenu();
Iterator<? extends Object> iter = list.iterator();
while(iter.hasNext()) {
Object element = iter.next();
if (element == null) {
popup.addSeparator();
} else if (element instanceof List) {
JMenu newMenu= createMenu((List)element);
if (newMenu!= null) {
popup.add(newMenu);
}
} else {
popup.add(createMenuItem(element, popup));
}
}
return popup;
}
/**
* Constructs a menu tree from a list of actions or lists of lists or actions.
*
* TODO This method is broken. It <em>should</em> expect either that every
* entry is a List (thus, the sub menus off the main MenuBar), or it should
* handle normal actions properly. By submitting a List of all Actions, nothing
* is created....
* <p>
* For example, If my list is [action, action, action], then nothing is added
* to the menu bar. However, if my list is [list[action], action, action, action] then
* I get a menu and under it the tree actions. This should not be, because if I
* wanted those actions to be on the sub menu, then they should have been
* listed within the sub list!
*
* @param actionIds an array which represents the root item.
* @return a menu bar which represents the menu bar tree
*/
public JMenuBar createMenuBar(Object[] actionIds) {
return createMenuBar(Arrays.asList(actionIds));
}
/**
* Constructs a menu tree from a list of actions or lists of lists or actions.
* TODO This method is broken. It <em>should</em> expect either that every
* entry is a List (thus, the sub menus off the main MenuBar), or it should
* handle normal actions properly. By submitting a List of all Actions, nothing
* is created....
* <p>
* For example, If my list is [action, action, action], then nothing is added
* to the menu bar. However, if my list is [list[action], action, action, action] then
* I get a menu and under it the tree actions. This should not be, because if I
* wanted those actions to be on the sub menu, then they should have been
* listed within the sub list!
*
* @param list a list which represents the root item.
* @return a menu bar which represents the menu bar tree
*/
public JMenuBar createMenuBar(List<? extends Object> list) {
JMenuBar menubar = new JMenuBar();
JMenu menu = null;
Iterator<? extends Object> iter = list.iterator();
while(iter.hasNext()) {
Object element = iter.next();
if (element == null) {
if (menu != null) {
menu.addSeparator();
}
} else if (element instanceof List) {
menu = createMenu((List)element);
if (menu != null) {
menubar.add(menu);
}
} else {
if (menu != null) {
menu.add(createMenuItem(element, menu));
}
}
}
return menubar;
}
/**
* Creates and returns a menu from a List which represents actions, separators
* and sub-menus. The menu
* constructed will have the attributes from the first action in the List.
* Subsequent actions in the list represent menu items.
*
* @param actionIds an array of action ids used to construct the menu and menu items.
* the first element represents the action used for the menu,
* @return the constructed JMenu or null
*/
public JMenu createMenu(Object[] actionIds) {
return createMenu(Arrays.asList(actionIds));
}
/**
* Creates and returns a menu from a List which represents actions, separators
* and sub-menus. The menu
* constructed will have the attributes from the first action in the List.
* Subsequent actions in the list represent menu items.
*
* @param list a list of action ids used to construct the menu and menu items.
* the first element represents the action used for the menu,
* @return the constructed JMenu or null
*/
public JMenu createMenu(List<? extends Object> list) {
// The first item will be the action for the JMenu
Action action = getAction(list.get(0));
if (action == null) {
return null;
}
JMenu menu = new JMenu(action);
// The rest of the items represent the menu items.
Iterator<? extends Object> iter = list.listIterator(1);
while(iter.hasNext()) {
Object element = iter.next();
if (element == null) {
menu.addSeparator();
} else if (element instanceof List) {
JMenu newMenu = createMenu((List)element);
if (newMenu != null) {
menu.add(newMenu);
}
} else {
menu.add(createMenuItem(element, menu));
}
}
return menu;
}
/**
* Convenience method to get the action from an ActionManager.
*/
private Action getAction(Object id) {
return getActionManager().get(id);
}
/**
* Returns the button group corresponding to the groupid
*
* @param groupid the value of the groupid attribute for the action element
* @param container a container which will further identify the ButtonGroup
*/
private ButtonGroup getGroup(String groupid, JComponent container) {
if (groupMap == null) {
groupMap = new HashMap<Integer, ButtonGroup>();
}
int intCode = groupid.hashCode();
if (container != null) {
intCode ^= container.hashCode();
}
Integer hashCode = new Integer(intCode);
ButtonGroup group = groupMap.get(hashCode);
if (group == null) {
group = new ButtonGroup();
groupMap.put(hashCode, group);
}
return group;
}
/**
* Creates a menu item based on the attributes of the action element.
* Will return a JMenuItem, JRadioButtonMenuItem or a JCheckBoxMenuItem
* depending on the context of the Action.
*
* @return a JMenuItem or subclass depending on type.
*/
private JMenuItem createMenuItem(Object id, JComponent container) {
return createMenuItem(getAction(id), container);
}
/**
* Creates a menu item based on the attributes of the action element.
* Will return a JMenuItem, JRadioButtonMenuItem or a JCheckBoxMenuItem
* depending on the context of the Action.
*
* @param action a mangaged Action
* @param container the parent container may be null for non-group actions.
* @return a JMenuItem or subclass depending on type.
*/
public JMenuItem createMenuItem(Action action, JComponent container) {
JMenuItem menuItem = null;
if (action instanceof AbstractActionExt) {
AbstractActionExt ta = (AbstractActionExt)action;
if (ta.isStateAction()) {
String groupid = (String)ta.getGroup();
if (groupid != null) {
// If this action has a groupid attribute then it's a
// GroupAction
menuItem = createRadioButtonMenuItem(getGroup(groupid, container),
(AbstractActionExt)action);
} else {
menuItem = createCheckBoxMenuItem((AbstractActionExt)action);
}
}
}
if (menuItem == null) {
menuItem= new JMenuItem(action);
configureMenuItemFromExtActionProperties(menuItem, action);
}
return menuItem;
}
/**
* Creates a menu item based on the attributes of the action.
* Will return a JMenuItem, JRadioButtonMenuItem or a JCheckBoxMenuItem
* depending on the context of the Action.
*
* @param action an action used to create the menu item
* @return a JMenuItem or subclass depending on type.
*/
public JMenuItem createMenuItem(Action action) {
return createMenuItem(action, null);
}
/**
* Creates, configures and returns an AbstractButton.
*
* The attributes of the action element
* registered with the ActionManger by the given id.
* Will return a JButton or a JToggleButton.
*
* @param id the identifer
* @param container the JComponent which parents the group, if any.
* @return an AbstractButton based on the
*/
public AbstractButton createButton(Object id, JComponent container) {
return createButton(getAction(id), container);
}
/**
* Creates a button based on the attributes of the action. If the container
* parameter is non-null then it will be used to uniquely identify
* the returned component within a ButtonGroup. If the action doesn't
* represent a grouped component then this value can be null.
*
* @param action an action used to create the button
* @param container the parent container to uniquely identify
* grouped components or null
* @return will return a JButton or a JToggleButton.
*/
public AbstractButton createButton(Action action, JComponent container) {
if (action == null) {
return null;
}
AbstractButton button = null;
if (action instanceof AbstractActionExt) {
// Check to see if we should create a toggle button
AbstractActionExt ta = (AbstractActionExt)action;
if (ta.isStateAction()) {
// If this action has a groupid attribute then it's a
// GroupAction
String groupid = (String)ta.getGroup();
if (groupid == null) {
button = createToggleButton(ta);
} else {
button = createToggleButton(ta, getGroup(groupid, container));
}
}
}
if (button == null) {
// Create a regular button
button = new JButton(action);
configureButtonFromExtActionProperties(button, action);
}
return button;
}
/**
* Creates a button based on the attributes of the action.
*
* @param action an action used to create the button
* @return will return a JButton or a JToggleButton.
*/
public AbstractButton createButton(Action action) {
return createButton(action, null);
}
/**
* Adds and configures a toggle button.
* @param a an abstraction of a toggle action.
*/
private JToggleButton createToggleButton(AbstractActionExt a) {
return createToggleButton(a, null);
}
/**
* Adds and configures a toggle button.
* @param a an abstraction of a toggle action.
* @param group the group to add the toggle button or null
*/
private JToggleButton createToggleButton(AbstractActionExt a, ButtonGroup group) {
JToggleButton button = new JToggleButton();
configureButton(button, a, group);
return button;
}
/**
*
* @param button
* @param a
* @param group
*/
public void configureButton(JToggleButton button, AbstractActionExt a, ButtonGroup group) {
configureSelectableButton(button, a, group);
configureButtonFromExtActionProperties(button, a);
}
public void configureSelectableButton(AbstractButton button, AbstractActionExt a, ButtonGroup group){
if ((a != null) && !a.isStateAction()) throw
new IllegalArgumentException("the Action must be a stateAction");
// we assume that all button configuration is done exclusively through this method!!
if (button.getAction() == a) return;
// unconfigure if the old Action is a state AbstractActionExt
// PENDING JW: automate unconfigure via a PCL that is listening to
// the button's action property? Think about memory leak implications!
Action oldAction = button.getAction();
if (oldAction instanceof AbstractActionExt) {
AbstractActionExt actionExt = (AbstractActionExt) oldAction;
// remove as itemListener
button.removeItemListener(actionExt);
// remove the button related PCL from the old actionExt
PropertyChangeListener[] l = actionExt.getPropertyChangeListeners();
for (int i = l.length - 1; i >= 0; i
if (l[i] instanceof ToggleActionPropertyChangeListener) {
ToggleActionPropertyChangeListener togglePCL = (ToggleActionPropertyChangeListener) l[i];
if (togglePCL.isToggling(button)) {
actionExt.removePropertyChangeListener(togglePCL);
}
}
}
}
button.setAction(a);
if (group != null) {
group.add(button);
}
if (a != null) {
button.addItemListener(a);
// JW: move the initial config into the PCL??
button.setSelected(a.isSelected());
new ToggleActionPropertyChangeListener(a, button);
// new ToggleActionPCL(button, a);
}
}
/**
* This method will be called after buttons created from an action. Override
* for custom configuration.
*
* @param button the button to be configured
* @param action the action used to construct the menu item.
*/
protected void configureButtonFromExtActionProperties(AbstractButton button, Action action) {
if (action.getValue(Action.SHORT_DESCRIPTION) == null) {
button.setToolTipText((String)action.getValue(Action.NAME));
}
// Use the large icon for toolbar buttons.
if (action.getValue(AbstractActionExt.LARGE_ICON) != null) {
button.setIcon((Icon)action.getValue(AbstractActionExt.LARGE_ICON));
}
// Don't show the text under the toolbar buttons if they have an icon
if (button.getIcon() != null) {
button.setText("");
}
}
/**
* This method will be called after menu items are created.
* Override for custom configuration.
*
* @param menuItem the menu item to be configured
* @param action the action used to construct the menu item.
*/
protected void configureMenuItemFromExtActionProperties(JMenuItem menuItem, Action action) {
}
/**
* Helper method to add a checkbox menu item.
*/
private JCheckBoxMenuItem createCheckBoxMenuItem(AbstractActionExt a) {
JCheckBoxMenuItem mi = new JCheckBoxMenuItem();
configureSelectableButton(mi, a, null);
configureMenuItemFromExtActionProperties(mi, a);
return mi;
}
/**
* Helper method to add a radio button menu item.
*/
private JRadioButtonMenuItem createRadioButtonMenuItem(ButtonGroup group,
AbstractActionExt a) {
JRadioButtonMenuItem mi = new JRadioButtonMenuItem();
configureSelectableButton(mi, a, group);
configureMenuItemFromExtActionProperties(mi, a);
return mi;
}
}
|
package org.jdesktop.swingx.plaf.basic;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Image;
import java.awt.Insets;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.UIManager;
import javax.swing.plaf.UIResource;
import org.jdesktop.swingx.JXPanel;
import org.jdesktop.swingx.JXTitledPanel;
import org.jdesktop.swingx.painter.Painter;
import org.jdesktop.swingx.plaf.TitledPanelUI;
/**
* All TitledPanels contain a title section and a content section. The default
* implementation for the title section relies on a Gradient background. All
* title sections can have components embedded to the "left" or
* "right" of the Title.
*
* @author Richard Bair
* @author Jeanette Winzenburg
*
*/
public abstract class BasicTitledPanelUI extends TitledPanelUI {
private static final Logger LOG = Logger.getLogger(BasicTitledPanelUI.class
.getName());
/**
* JLabel used for the title in the Title section of the JTitledPanel.
*/
private JLabel caption;
/**
* The Title section panel.
*/
private JXPanel topPanel;
/**
* Listens to changes in the title of the JXTitledPanel component
*/
private PropertyChangeListener titleChangeListener;
/**
* The JXTitledPanel peered with this UI
*/
protected JXTitledPanel titledPanel;
private JComponent left;
private JComponent right;
/** Creates a new instance of BasicTitledPanelUI */
public BasicTitledPanelUI() {
}
/**
* Configures the specified component appropriate for the look and feel.
* This method is invoked when the <code>ComponentUI</code> instance is being installed
* as the UI delegate on the specified component. This method should
* completely configure the component for the look and feel,
* including the following:
* <ol>
* <li>Install any default property values for color, fonts, borders,
* icons, opacity, etc. on the component. Whenever possible,
* property values initialized by the client program should <i>not</i>
* be overridden.
* <li>Install a <code>LayoutManager</code> on the component if necessary.
* <li>Create/add any required sub-components to the component.
* <li>Create/install event listeners on the component.
* <li>Create/install a <code>PropertyChangeListener</code> on the component in order
* to detect and respond to component property changes appropriately.
* <li>Install keyboard UI (mnemonics, traversal, etc.) on the component.
* <li>Initialize any appropriate instance data.
* </ol>
* @param c the component where this UI delegate is being installed
*
* @see #uninstallUI
* @see javax.swing.JComponent#setUI
* @see javax.swing.JComponent#updateUI
*/
public void installUI(JComponent c) {
assert c instanceof JXTitledPanel;
titledPanel = (JXTitledPanel)c;
installProperty(titledPanel, "titlePainter", (Painter)UIManager.get("JXTitledPanel.title.painter"));
installProperty(titledPanel, "titleForeground", UIManager.getColor("JXTitledPanel.title.foreground"));
installProperty(titledPanel, "titleFont", UIManager.getFont("JXTitledPanel.title.font"));
caption = createAndConfigureCaption(titledPanel);
topPanel = createAndConfigureTopPanel(titledPanel);
fillTopPanel();
titledPanel.setLayout(new BorderLayout());
titledPanel.add(topPanel, BorderLayout.NORTH);
titledPanel.setBorder(BorderFactory.createRaisedBevelBorder());
titledPanel.setOpaque(false);
installListeners();
}
private void fillTopPanel() {
topPanel.add(caption, new GridBagConstraints(1, 0, 1, 1, 1.0, 1.0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(4, 12, 4, 12), 0, 0));
if (titledPanel.getClientProperty(JXTitledPanel.RIGHT_DECORATION) instanceof JComponent) {
setRightDecoration((JComponent) titledPanel.getClientProperty(JXTitledPanel.RIGHT_DECORATION));
}
if (titledPanel.getClientProperty(JXTitledPanel.LEFT_DECORATION) instanceof JComponent) {
setLeftDecoration((JComponent) titledPanel.getClientProperty(JXTitledPanel.LEFT_DECORATION));
}
}
private JXPanel createAndConfigureTopPanel(JXTitledPanel titledPanel) {
JXPanel topPanel = new JXPanel();
topPanel.setBackgroundPainter(titledPanel.getTitlePainter());
topPanel.setBorder(BorderFactory.createEmptyBorder());
topPanel.setLayout(new GridBagLayout());
return topPanel;
}
private JLabel createAndConfigureCaption(JXTitledPanel titledPanel) {
JLabel caption = new JLabel(titledPanel.getTitle());
caption.setFont(titledPanel.getTitleFont());
caption.setForeground(titledPanel.getTitleForeground());
return caption;
}
/**
* Reverses configuration which was done on the specified component during
* <code>installUI</code>. This method is invoked when this
* <code>UIComponent</code> instance is being removed as the UI delegate
* for the specified component. This method should undo the
* configuration performed in <code>installUI</code>, being careful to
* leave the <code>JComponent</code> instance in a clean state (no
* extraneous listeners, look-and-feel-specific property objects, etc.).
* This should include the following:
* <ol>
* <li>Remove any UI-set borders from the component.
* <li>Remove any UI-set layout managers on the component.
* <li>Remove any UI-added sub-components from the component.
* <li>Remove any UI-added event/property listeners from the component.
* <li>Remove any UI-installed keyboard UI from the component.
* <li>Nullify any allocated instance data objects to allow for GC.
* </ol>
* @param c the component from which this UI delegate is being removed;
* this argument is often ignored,
* but might be used if the UI object is stateless
* and shared by multiple components
*
* @see #installUI
* @see javax.swing.JComponent#updateUI
*/
public void uninstallUI(JComponent c) {
assert c instanceof JXTitledPanel;
uninstallListeners(titledPanel);
// JW: this is needed to make the gradient paint work correctly...
// LF changes will remove the left/right components...
topPanel.removeAll();
titledPanel.remove(topPanel);
titledPanel.putClientProperty(JXTitledPanel.LEFT_DECORATION, left);
titledPanel.putClientProperty(JXTitledPanel.RIGHT_DECORATION, right);
caption = null;
topPanel = null;
titledPanel = null;
left = null;
right = null;
}
protected void installListeners() {
titleChangeListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getPropertyName().equals("title")) {
caption.setText((String)evt.getNewValue());
} else if (evt.getPropertyName().equals("titleForeground")) {
caption.setForeground((Color)evt.getNewValue());
} else if (evt.getPropertyName().equals("titleFont")) {
caption.setFont((Font)evt.getNewValue());
} else if ("titlePainter".equals(evt.getPropertyName())) {
topPanel.setBackgroundPainter(titledPanel.getTitlePainter());
topPanel.repaint();
}
}
};
titledPanel.addPropertyChangeListener(titleChangeListener);
}
protected void uninstallListeners(JXTitledPanel panel) {
titledPanel.removePropertyChangeListener(titleChangeListener);
}
protected void installProperty(JComponent c, String propName, Object value) {
try {
BeanInfo bi = Introspector.getBeanInfo(c.getClass());
for (PropertyDescriptor pd : bi.getPropertyDescriptors()) {
if (pd.getName().equals(propName)) {
Method m = pd.getReadMethod();
Object oldVal = m.invoke(c);
if (oldVal == null || oldVal instanceof UIResource) {
m = pd.getWriteMethod();
m.invoke(c, value);
}
}
}
} catch (Exception e) {
LOG.log(Level.FINE, "Failed to install property " + propName, e);
}
}
/**
* Paints the specified component appropriate for the look and feel.
* This method is invoked from the <code>ComponentUI.update</code> method when
* the specified component is being painted. Subclasses should override
* this method and use the specified <code>Graphics</code> object to
* render the content of the component.
*
* @param g the <code>Graphics</code> context in which to paint
* @param c the component being painted;
* this argument is often ignored,
* but might be used if the UI object is stateless
* and shared by multiple components
*
* @see #update
*/
public void paint(Graphics g, JComponent c) {
super.paint(g, c);
}
/**
* Adds the given JComponent as a decoration on the right of the title
* @param decoration
*/
public void setRightDecoration(JComponent decoration) {
if (right != null) topPanel.remove(right);
right = decoration;
if (right != null) {
topPanel.add(decoration, new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(1, 1, 1, 1), 0, 0));
}
}
public JComponent getRightDecoration() {
return right;
}
/**
* Adds the given JComponent as a decoration on the left of the title
* @param decoration
*/
public void setLeftDecoration(JComponent decoration) {
if (left != null) topPanel.remove(left);
left = decoration;
if (left != null) {
topPanel.add(left, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(1, 1, 1, 1), 0, 0));
}
}
public JComponent getLeftDecoration() {
return left;
}
/**
* @return the Container acting as the title bar for this component
*/
public Container getTitleBar() {
return topPanel;
}
}
|
package org.jdesktop.swingx.plaf.basic;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Image;
import java.awt.Insets;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.UIManager;
import javax.swing.plaf.UIResource;
import org.jdesktop.swingx.JXPanel;
import org.jdesktop.swingx.JXTitledPanel;
import org.jdesktop.swingx.plaf.TitledPanelUI;
/**
* All TitledPanels contain a title section and a content section. The default
* implementation for the title section relies on a Gradient background. All
* title sections can have components embedded to the "left" or
* "right" of the Title.
*
* @author Richard Bair
* @author Jeanette Winzenburg
*
*/
public abstract class BasicTitledPanelUI extends TitledPanelUI {
private static final Logger LOG = Logger.getLogger(BasicTitledPanelUI.class
.getName());
/**
* JLabel used for the title in the Title section of the JTitledPanel.
*/
private JLabel caption;
/**
* The Title section panel.
*/
private JGradientPanel topPanel;
/**
* Listens to changes in the title of the JXTitledPanel component
*/
private PropertyChangeListener titleChangeListener;
/**
* The JXTitledPanel peered with this UI
*/
protected JXTitledPanel titledPanel;
private JComponent left;
private JComponent right;
/** Creates a new instance of BasicTitledPanelUI */
public BasicTitledPanelUI() {
}
/**
* Configures the specified component appropriate for the look and feel.
* This method is invoked when the <code>ComponentUI</code> instance is being installed
* as the UI delegate on the specified component. This method should
* completely configure the component for the look and feel,
* including the following:
* <ol>
* <li>Install any default property values for color, fonts, borders,
* icons, opacity, etc. on the component. Whenever possible,
* property values initialized by the client program should <i>not</i>
* be overridden.
* <li>Install a <code>LayoutManager</code> on the component if necessary.
* <li>Create/add any required sub-components to the component.
* <li>Create/install event listeners on the component.
* <li>Create/install a <code>PropertyChangeListener</code> on the component in order
* to detect and respond to component property changes appropriately.
* <li>Install keyboard UI (mnemonics, traversal, etc.) on the component.
* <li>Initialize any appropriate instance data.
* </ol>
* @param c the component where this UI delegate is being installed
*
* @see #uninstallUI
* @see javax.swing.JComponent#setUI
* @see javax.swing.JComponent#updateUI
*/
public void installUI(JComponent c) {
assert c instanceof JXTitledPanel;
titledPanel = (JXTitledPanel)c;
installProperty(titledPanel, "titleForeground", UIManager.getColor("JXTitledPanel.title.foreground"));
installProperty(titledPanel, "titleDarkBackground", UIManager.getColor("JXTitledPanel.title.darkBackground"));
installProperty(titledPanel, "titleLightBackground", UIManager.getColor("JXTitledPanel.title.lightBackground"));
installProperty(titledPanel, "titleFont", UIManager.getFont("JXTitledPanel.title.font"));
caption = createAndConfigureCaption(titledPanel);
topPanel = createAndConfigureTopPanel(titledPanel);
fillTopPanel();
titledPanel.setLayout(new BorderLayout());
titledPanel.add(topPanel, BorderLayout.NORTH);
titledPanel.setBorder(BorderFactory.createRaisedBevelBorder());
titledPanel.setOpaque(false);
installListeners();
}
private void fillTopPanel() {
topPanel.add(caption, new GridBagConstraints(1, 0, 1, 1, 1.0, 1.0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(4, 12, 4, 12), 0, 0));
if (titledPanel.getClientProperty(JXTitledPanel.RIGHT_DECORATION) instanceof JComponent) {
addRightDecoration((JComponent) titledPanel.getClientProperty(JXTitledPanel.RIGHT_DECORATION));
}
if (titledPanel.getClientProperty(JXTitledPanel.LEFT_DECORATION) instanceof JComponent) {
addLeftDecoration((JComponent) titledPanel.getClientProperty(JXTitledPanel.LEFT_DECORATION));
}
}
private JGradientPanel createAndConfigureTopPanel(JXTitledPanel titledPanel) {
JGradientPanel topPanel = createTopPanel(titledPanel);
topPanel.setBorder(BorderFactory.createEmptyBorder());
topPanel.setLayout(new GridBagLayout());
return topPanel;
}
private JLabel createAndConfigureCaption(JXTitledPanel titledPanel) {
JLabel caption = new JLabel(titledPanel.getTitle());
caption.setFont(titledPanel.getTitleFont());
caption.setForeground(titledPanel.getTitleForeground());
return caption;
}
/**
* Reverses configuration which was done on the specified component during
* <code>installUI</code>. This method is invoked when this
* <code>UIComponent</code> instance is being removed as the UI delegate
* for the specified component. This method should undo the
* configuration performed in <code>installUI</code>, being careful to
* leave the <code>JComponent</code> instance in a clean state (no
* extraneous listeners, look-and-feel-specific property objects, etc.).
* This should include the following:
* <ol>
* <li>Remove any UI-set borders from the component.
* <li>Remove any UI-set layout managers on the component.
* <li>Remove any UI-added sub-components from the component.
* <li>Remove any UI-added event/property listeners from the component.
* <li>Remove any UI-installed keyboard UI from the component.
* <li>Nullify any allocated instance data objects to allow for GC.
* </ol>
* @param c the component from which this UI delegate is being removed;
* this argument is often ignored,
* but might be used if the UI object is stateless
* and shared by multiple components
*
* @see #installUI
* @see javax.swing.JComponent#updateUI
*/
public void uninstallUI(JComponent c) {
assert c instanceof JXTitledPanel;
uninstallListeners(titledPanel);
// JW: this is needed to make the gradient paint work correctly...
// LF changes will remove the left/right components...
topPanel.removeAll();
titledPanel.remove(topPanel);
titledPanel.putClientProperty(JXTitledPanel.LEFT_DECORATION, left);
titledPanel.putClientProperty(JXTitledPanel.RIGHT_DECORATION, right);
caption = null;
topPanel = null;
titledPanel = null;
left = null;
right = null;
}
protected void installListeners() {
titleChangeListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getPropertyName().equals("title")) {
caption.setText((String)evt.getNewValue());
} else if (evt.getPropertyName().equals("titleForeground")) {
caption.setForeground((Color)evt.getNewValue());
} else if (evt.getPropertyName().equals("titleFont")) {
caption.setFont((Font)evt.getNewValue());
} else if ("titleDarkBackground".equals(evt.getPropertyName())) {
topPanel.revalidateGradient();
} else if ("titleLightBackground".equals(evt.getPropertyName())) {
topPanel.revalidateGradient();
}
}
};
titledPanel.addPropertyChangeListener(titleChangeListener);
}
protected void uninstallListeners(JXTitledPanel panel) {
titledPanel.removePropertyChangeListener(titleChangeListener);
}
protected void installProperty(JComponent c, String propName, Object value) {
try {
BeanInfo bi = Introspector.getBeanInfo(c.getClass());
for (PropertyDescriptor pd : bi.getPropertyDescriptors()) {
if (pd.getName().equals(propName)) {
Method m = pd.getReadMethod();
Object oldVal = m.invoke(c);
if (oldVal == null || oldVal instanceof UIResource) {
m = pd.getWriteMethod();
m.invoke(c, value);
}
}
}
} catch (Exception e) {
LOG.log(Level.FINE, "Failed to install property " + propName, e);
}
}
/**
* Paints the specified component appropriate for the look and feel.
* This method is invoked from the <code>ComponentUI.update</code> method when
* the specified component is being painted. Subclasses should override
* this method and use the specified <code>Graphics</code> object to
* render the content of the component.
*
* @param g the <code>Graphics</code> context in which to paint
* @param c the component being painted;
* this argument is often ignored,
* but might be used if the UI object is stateless
* and shared by multiple components
*
* @see #update
*/
public void paint(Graphics g, JComponent c) {
super.paint(g, c);
}
/**
* Adds the given JComponent as a decoration on the right of the title
* @param decoration
*/
public void addRightDecoration(JComponent decoration) {
if (right != null) topPanel.remove(right);
right = decoration;
if (right != null) {
topPanel.add(decoration, new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
}
}
/**
* Adds the given JComponent as a decoration on the left of the title
* @param decoration
*/
public void addLeftDecoration(JComponent decoration) {
if (left != null) topPanel.remove(left);
left = decoration;
if (left != null) {
topPanel.add(left, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
}
}
/**
* @return the Container acting as the title bar for this component
*/
public Container getTitleBar() {
return topPanel;
}
protected JGradientPanel createTopPanel(JXTitledPanel panel) {
return new JGradientPanel(panel);
}
protected static
class JGradientPanel extends JXPanel {
private GradientPaint gp;
private double oldWidth = -1;
private double oldHeight = -1;
private ImageIcon helper = new ImageIcon();
private JXTitledPanel titledPanel;
public JGradientPanel(JXTitledPanel panel) {
this.titledPanel = panel;
}
public void invalidateGradient() {
gp = null;
}
public void revalidateGradient() {
invalidateGradient();
repaint();
}
//override the background color to provide for a gradient
/* (non-Javadoc)
* @see javax.swing.JComponent#paintComponent(java.awt.Graphics)
*
* There is some special optimization code in here that is kind of...er..shall we say, tricky.
* First off, the gradient panels are taking forever to draw. Therefore, I have resorted to caching the
* gradient'ed paint job so that I don't have to repaint it all the time.
*/
protected void paintComponent(Graphics g) {
//draw the gradient background
if (gp == null || oldWidth != getWidth() || oldHeight != getHeight()) {
gp = createGradientPaint();
Image savedImg = createImage(getWidth(), getHeight());
Graphics2D imgg = (Graphics2D)savedImg.getGraphics();
imgg.setPaint(gp);
imgg.fillRect(0, 0, getWidth(), getHeight());
oldWidth = getWidth();
oldHeight = getHeight();
helper.setImage(savedImg);
}
// draw the image
g.drawImage(helper.getImage(), 0, 0, getWidth(), getHeight(), helper.getImageObserver());
}
protected GradientPaint createGradientPaint() {
return new GradientPaint(0,
0,
titledPanel.getTitleDarkBackground(),
getWidth(),
0,
titledPanel.getTitleLightBackground());
}
}
}
|
package org.helioviewer.gl3d.view;
import java.awt.Color;
import java.io.File;
import java.io.IOException;
import javax.media.opengl.GL2;
import javax.media.opengl.GLAutoDrawable;
import javax.media.opengl.GLCapabilities;
import javax.media.opengl.GLEventListener;
import javax.media.opengl.GLProfile;
import javax.media.opengl.awt.GLCanvas;
import org.helioviewer.base.logging.Log;
import org.helioviewer.base.math.Vector2dInt;
import org.helioviewer.gl3d.scenegraph.GL3DState;
import org.helioviewer.jhv.display.DisplayListener;
import org.helioviewer.jhv.display.Displayer;
import org.helioviewer.jhv.display.GL3DComponentFakeInterface;
import org.helioviewer.viewmodel.changeevent.ChangeEvent;
import org.helioviewer.viewmodel.changeevent.LayerChangedReason;
import org.helioviewer.viewmodel.changeevent.LayerChangedReason.LayerChangeType;
import org.helioviewer.viewmodel.changeevent.TimestampChangedReason;
import org.helioviewer.viewmodel.changeevent.ViewChainChangedReason;
import org.helioviewer.viewmodel.renderer.screen.GLScreenRenderGraphics;
import org.helioviewer.viewmodel.renderer.screen.ScreenRenderer;
import org.helioviewer.viewmodel.view.AbstractComponentView;
import org.helioviewer.viewmodel.view.ComponentView;
import org.helioviewer.viewmodel.view.LinkedMovieManager;
import org.helioviewer.viewmodel.view.TimedMovieView;
import org.helioviewer.viewmodel.view.View;
import org.helioviewer.viewmodel.view.ViewportView;
import org.helioviewer.viewmodel.view.opengl.GLTextureHelper;
import org.helioviewer.viewmodel.view.opengl.GLView;
import org.helioviewer.viewmodel.view.opengl.shader.GLFragmentShaderView;
import org.helioviewer.viewmodel.view.opengl.shader.GLMinimalFragmentShaderProgram;
import org.helioviewer.viewmodel.view.opengl.shader.GLMinimalVertexShaderProgram;
import org.helioviewer.viewmodel.view.opengl.shader.GLShaderBuilder;
import org.helioviewer.viewmodel.view.opengl.shader.GLShaderHelper;
import org.helioviewer.viewmodel.view.opengl.shader.GLVertexShaderView;
import org.helioviewer.viewmodel.viewport.StaticViewport;
import org.helioviewer.viewmodel.viewport.Viewport;
/**
* The top-most View in the 3D View Chain. Let's the viewchain render to its
* {@link GLCanvas}.
*
*
* @author Simon Spoerri (simon.spoerri@fhnw.ch)
*
*/
public class GL3DComponentView extends AbstractComponentView implements GLEventListener, ComponentView, DisplayListener, GL3DComponentFakeInterface {
private GLCanvas canvas;
private Color backgroundColor = Color.BLACK;
private boolean backGroundColorHasChanged = false;
private boolean rebuildShadersRequest = false;
private final GLTextureHelper textureHelper = new GLTextureHelper();
private final GLShaderHelper shaderHelper = new GLShaderHelper();
// private GL3DOrthoView orthoView;
private ViewportView viewportView;
private Vector2dInt viewportSize;
public GL3DComponentView() {
GLCapabilities caps = new GLCapabilities(GLProfile.getDefault());
GLCanvas glCanvas = new GLCanvas(caps);
this.setCanvas(glCanvas);
this.getCanvas().setMinimumSize(new java.awt.Dimension(100, 100));
Displayer.getSingletonInstance().register(this);
Displayer.getSingletonInstance().addListener(this);
this.getCanvas().addGLEventListener(this);
}
@Override
public void deactivate() {
}
@Override
public void activate() {
}
@Override
public GLCanvas getComponent() {
return this.getCanvas();
}
public void displayChanged(GLAutoDrawable arg0, boolean arg1, boolean arg2) {
Log.debug("GL3DComponentView.DisplayChanged");
}
@Override
public void init(GLAutoDrawable glAD) {
Log.debug("GL3DComponentView.Init");
//GLSharedContext.setSharedContext(glAD.getContext());
GL2 gl = (GL2) glAD.getGL();
GL3DState.create(gl);
// GLTextureCoordinate.init(gl);
textureHelper.delAllTextures(gl);
GLTextureHelper.initHelper(gl);
shaderHelper.delAllShaderIDs(gl);
// gl.glEnable(GL2.GL_LINE_SMOOTH);
gl.glHint(GL2.GL_LINE_SMOOTH_HINT, GL2.GL_NICEST);
// gl.glShadeModel(GL2.GL_FLAT);
gl.glShadeModel(GL2.GL_SMOOTH);
gl.glClear(GL2.GL_COLOR_BUFFER_BIT | GL2.GL_DEPTH_BUFFER_BIT);
gl.glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
//gl.glTexEnvi(GL2.GL_TEXTURE_ENV, GL2.GL_TEXTURE_ENV_MODE, GL2.GL_BLEND);
// gl.glTexEnvi(GL2.GL_TEXTURE_ENV, GL2.GL_TEXTURE_ENV_MODE,
// GL2.GL_REPLACE);
gl.glEnable(GL2.GL_BLEND);
gl.glEnable(GL2.GL_POINT_SMOOTH);
gl.glEnable(GL2.GL_COLOR_MATERIAL);
gl.glEnable(GL2.GL_LIGHTING);
gl.glEnable(GL2.GL_NORMALIZE);
// gl.glEnable(GL2.GL_CULL_FACE);
gl.glCullFace(GL2.GL_BACK);
gl.glFrontFace(GL2.GL_CCW);
gl.glEnable(GL2.GL_DEPTH_TEST);
// gl.glDepthFunc(GL2.GL_LESS);
gl.glDepthFunc(GL2.GL_LEQUAL);
gl.glEnable(GL2.GL_LIGHT0);
viewportSize = new Vector2dInt(0, 0);
this.rebuildShadersRequest = true;
// gl.glColor3f(1.0f, 1.0f, 0.0f);
}
@Override
public void reshape(GLAutoDrawable glAD, int x, int y, int width, int height) {
viewportSize = new Vector2dInt(width, height);
GL2 gl = (GL2) glAD.getGL();
gl.setSwapInterval(1);
}
@Override
public synchronized void display(GLAutoDrawable glAD) {
GL2 gl = (GL2) glAD.getGL();
int width = this.viewportSize.getX();
int height = this.viewportSize.getY();
GL3DState.getUpdated(gl, width, height);
if (backGroundColorHasChanged) {
gl.glClearColor(backgroundColor.getRed() / 255.0f, backgroundColor.getGreen() / 255.0f, backgroundColor.getBlue() / 255.0f, backgroundColor.getAlpha() / 255.0f);
backGroundColorHasChanged = false;
}
// Rebuild all shaders, if necessary
if (rebuildShadersRequest) {
rebuildShaders(gl);
}
// Viewport viewport =
// view.getAdapter(ViewportView.class).getViewport();
// int width = viewport.getWidth();
// int height = viewport.getHeight();
gl.glClear(GL2.GL_COLOR_BUFFER_BIT | GL2.GL_DEPTH_BUFFER_BIT);
gl.glColor4f(1, 1, 1, 1);
gl.glEnable(GL2.GL_LIGHTING);
gl.glEnable(GL2.GL_DEPTH_TEST);
// gl.glLoadIdentity();
gl.glPushMatrix();
if (this.getView() instanceof GLView) {
((GLView) this.getView()).renderGL(gl, true);
}
gl.glPopMatrix();
gl.glPushMatrix();
if (!this.postRenderers.isEmpty()) {
gl.glMatrixMode(GL2.GL_PROJECTION);
gl.glLoadIdentity();
gl.glOrtho(0, width, 0, height, -1, 10000);
gl.glMatrixMode(GL2.GL_MODELVIEW);
gl.glLoadIdentity();
gl.glTranslatef(0.0f, height, 0.0f);
gl.glScalef(1.0f, -1.0f, 1.0f);
gl.glDisable(GL2.GL_LIGHTING);
gl.glColor4f(1, 1, 1, 0);
gl.glDisable(GL2.GL_DEPTH_TEST);
gl.glEnable(GL2.GL_TEXTURE_2D);
GLScreenRenderGraphics glRenderer = new GLScreenRenderGraphics(gl);
synchronized (postRenderers) {
for (ScreenRenderer r : postRenderers) {
r.render(glRenderer);
}
}
gl.glDisable(GL2.GL_TEXTURE_2D);
}
gl.glPopMatrix();
GL3DState.get().checkGLErrors();
}
@Override
public void saveScreenshot(String imageFormat, File outputFile) throws IOException {
throw new UnsupportedOperationException("Cannot Save screenshots in 3D mode yet!");
}
@Override
public void setBackgroundColor(Color background) {
backgroundColor = background;
backGroundColorHasChanged = true;
}
@Override
public void setOffset(Vector2dInt offset) {
// if(this.orthoView!=null) {
// orthoView.setOffset(offset);
}
@Override
public void updateMainImagePanelSize(Vector2dInt size) {
super.updateMainImagePanelSize(size);
this.viewportSize = size;
// if(this.orthoView!=null) {
// this.orthoView.updateMainImagePanelSize(size);
if (this.viewportView != null) {
Viewport viewport = StaticViewport.createAdaptedViewport(Math.max(1, size.getX()), Math.max(1, size.getY()));
this.viewportView.setViewport(viewport, null);
}
}
@Override
protected void setViewSpecificImplementation(View newView, ChangeEvent changeEvent) {
// this.orthoView = getAdapter(GL3DOrthoView.class);
this.viewportView = getAdapter(ViewportView.class);
}
@Override
public void display() {
try {
this.canvas.display();
} catch (Exception e) {
Log.warn("Display of GL3DComponentView canvas failed", e);
}
}
@Override
public void viewChanged(View sender, ChangeEvent aEvent) {
if (aEvent.reasonOccurred(ViewChainChangedReason.class) || (aEvent.reasonOccurred(LayerChangedReason.class) && aEvent.getLastChangedReasonByType(LayerChangedReason.class).getLayerChangeType() == LayerChangeType.LAYER_ADDED)) {
rebuildShadersRequest = true;
this.viewportView = getAdapter(ViewportView.class);
}
TimestampChangedReason timestampReason = aEvent.getLastChangedReasonByType(TimestampChangedReason.class);
if ((timestampReason != null) && (timestampReason.getView() instanceof TimedMovieView) && LinkedMovieManager.getActiveInstance().isMaster((TimedMovieView) timestampReason.getView())) {
try {
// this.display();
Displayer.getSingletonInstance().display();
} catch (Exception e) {
}
}
notifyViewListeners(aEvent);
}
private void rebuildShaders(GL2 gl) {
rebuildShadersRequest = false;
shaderHelper.delAllShaderIDs(gl);
GLFragmentShaderView fragmentView = view.getAdapter(GLFragmentShaderView.class);
if (fragmentView != null) {
// create new shader builder
GLShaderBuilder newShaderBuilder = new GLShaderBuilder(gl, GL2.GL_FRAGMENT_PROGRAM_ARB);
// fill with standard values
GLMinimalFragmentShaderProgram minimalProgram = new GLMinimalFragmentShaderProgram();
minimalProgram.build(newShaderBuilder);
// fill with other filters and compile
fragmentView.buildFragmentShader(newShaderBuilder).compile();
}
GLVertexShaderView vertexView = view.getAdapter(GLVertexShaderView.class);
if (vertexView != null) {
// create new shader builder
GLShaderBuilder newShaderBuilder = new GLShaderBuilder(gl, GL2.GL_VERTEX_PROGRAM_ARB);
// fill with standard values
GLMinimalVertexShaderProgram minimalProgram = new GLMinimalVertexShaderProgram();
minimalProgram.build(newShaderBuilder);
// fill with other filters and compile
vertexView.buildVertexShader(newShaderBuilder).compile();
}
}
public GLCanvas getCanvas() {
return canvas;
}
public void setCanvas(GLCanvas canvas) {
this.canvas = canvas;
}
@Override
public void dispose(GLAutoDrawable arg0) {
}
}
|
package samples.typed;
import com.sun.xml.analysis.types.SchemaProcessor;
import com.sun.xml.analysis.types.XSDataType;
import com.sun.xml.fastinfoset.algorithm.BuiltInEncodingAlgorithmFactory;
import com.sun.xml.fastinfoset.sax.SAXDocumentParser;
import com.sun.xml.fastinfoset.sax.SAXDocumentSerializer;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.Map;
import java.util.Set;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import org.jvnet.fastinfoset.EncodingAlgorithmIndexes;
import org.jvnet.fastinfoset.FastInfosetSource;
import org.jvnet.fastinfoset.sax.PrimitiveTypeContentHandler;
import org.jvnet.fastinfoset.sax.helpers.EncodingAlgorithmAttributesImpl;
import org.jvnet.fastinfoset.sax.helpers.FastInfosetDefaultHandler;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLFilterImpl;
/**
*
* @author Paul.Sandoz@Sun.Com
*/
public class ConvertLexicalValues {
static class LexicalFilter extends XMLFilterImpl {
private Map<String, Set<XSDataType>> _elements;
private Map<String, Set<XSDataType>> _attributes;
private Set<XSDataType> _textContent;
public LexicalFilter(Map<String, Set<XSDataType>> elements,
Map<String, Set<XSDataType>> attributes) {
_elements = elements;
_attributes = attributes;
}
private void replaceAttributeValue(Set<XSDataType> attributeTypes,
int index, EncodingAlgorithmAttributesImpl atts) {
if (attributeTypes == null) return;
char[] ch = atts.getValue(index).toCharArray();
for (XSDataType dt : attributeTypes) {
try {
switch(dt) {
case BASE64BINARY:
byte[] b = (byte[])BuiltInEncodingAlgorithmFactory.
base64EncodingAlgorithm.
convertFromCharacters(ch, 0, ch.length);
atts.replaceAttributeAlgorithmData(index,
null, EncodingAlgorithmIndexes.BASE64, b);
return;
case FLOAT:
float[] f = (float[])BuiltInEncodingAlgorithmFactory.
floatEncodingAlgorithm.
convertFromCharacters(ch, 0, ch.length);
atts.replaceAttributeAlgorithmData(index,
null, EncodingAlgorithmIndexes.FLOAT, f);
return;
default:
}
} catch (Exception e) {
}
}
}
public void startElement(String uri, String localName, String qName,
Attributes atts) throws SAXException {
_textContent = _elements.get(localName);
for (int i = 0; i < atts.getLength(); i++) {
if (_attributes.containsKey(atts.getLocalName(i))) {
// Copy attributes
final EncodingAlgorithmAttributesImpl eatts = new EncodingAlgorithmAttributesImpl(atts);
for (i = 0; i < atts.getLength(); i++) {
replaceAttributeValue(_attributes.get(atts.getLocalName(i)),
i, eatts);
}
atts = eatts;
break;
}
}
super.startElement(uri, localName, qName, atts);
}
public void characters (char ch[], int start, int length)
throws SAXException {
if (_textContent == null) {
super.characters(ch, start, length);
return;
}
for (XSDataType dt : _textContent) {
try {
switch(dt) {
case BASE64BINARY:
byte[] b = (byte[])BuiltInEncodingAlgorithmFactory.
base64EncodingAlgorithm.
convertFromCharacters(ch, start, length);
((PrimitiveTypeContentHandler)getContentHandler()).
bytes(b, 0, b.length);
_textContent = null;
return;
case FLOAT:
float[] f = (float[])BuiltInEncodingAlgorithmFactory.
floatEncodingAlgorithm.
convertFromCharacters(ch, start, length);
((PrimitiveTypeContentHandler)getContentHandler()).
floats(f, 0, f.length);
_textContent = null;
return;
default:
super.characters(ch, start, length);
_textContent = null;
return;
}
} catch (Exception e) {
}
}
}
}
public static void main(String[] args) throws Exception {
SchemaProcessor sp = new SchemaProcessor(new File(args[0]).toURL());
sp.process();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
SAXDocumentSerializer s = new SAXDocumentSerializer();
s.setOutputStream(baos);
LexicalFilter lf = new LexicalFilter(sp.getElementToXSDataTypeMap(),
sp.getAttributeToXSDataTypeMap());
lf.setContentHandler(s);
lf.setParent(getXMLReader());
lf.parse(new InputSource(new FileInputStream(args[1])));
FastInfosetSource source = new FastInfosetSource(
new ByteArrayInputStream(baos.toByteArray()));
StreamResult result = new StreamResult(System.out);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer t = tf.newTransformer();
t.transform(source, result);
System.out.println();
SAXDocumentParser p = new SAXDocumentParser();
FastInfosetDefaultHandler h = new FastInfosetDefaultHandler() {
public void bytes(byte[] b, int start, int length)
throws SAXException {
System.out.println("Byte: " + b[start]);
}
public void floats(float[] f, int start, int length)
throws SAXException {
System.out.println("Float: " + f[start]);
}
};
p.setContentHandler(h);
p.setPrimitiveTypeContentHandler(h);
p.parse(new ByteArrayInputStream(baos.toByteArray()));
}
public static XMLReader getXMLReader() throws Exception {
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setNamespaceAware(true);
return spf.newSAXParser().getXMLReader();
}
}
|
package laas.openrobots.ontology.modules.events;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import laas.openrobots.ontology.PartialStatement;
import laas.openrobots.ontology.backends.IOntologyBackend;
import laas.openrobots.ontology.exceptions.EventNotFoundException;
import laas.openrobots.ontology.exceptions.EventRegistrationException;
import laas.openrobots.ontology.exceptions.IllegalStatementException;
import laas.openrobots.ontology.exceptions.OntologyServerException;
import laas.openrobots.ontology.helpers.Helpers;
import laas.openrobots.ontology.helpers.Logger;
import laas.openrobots.ontology.helpers.Namespaces;
import laas.openrobots.ontology.helpers.VerboseLevel;
import laas.openrobots.ontology.modules.events.IWatcher.EventType;
import com.hp.hpl.jena.ontology.OntClass;
import com.hp.hpl.jena.query.Query;
import com.hp.hpl.jena.query.QueryExecException;
import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.QueryFactory;
import com.hp.hpl.jena.query.QueryParseException;
import com.hp.hpl.jena.query.QuerySolution;
import com.hp.hpl.jena.query.ResultSet;
import com.hp.hpl.jena.query.Syntax;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.shared.Lock;
public class EventProcessor {
private Set<EventType> supportedEventTypes;
IOntologyBackend onto;
/**
* The WatcherHolder class is a pre-compiled version of an {@link IWatcher}
* plus some caching mechanisms.
* @author slemaign
*
*/
//TODO: rewrite (with subclasses?) this class to be more generic regarding type of events.
private class WatcherHolder {
public final IWatcher watcher;
public Query cachedQuery;
public OntClass referenceClass;
public String varName;
public boolean lastStatus;
public Set<Resource> lastMatchedResources;
public WatcherHolder(IWatcher watcher) throws EventRegistrationException {
super();
this.watcher = watcher;
lastStatus = false;
compilePattern();
}
public IWatcher getWatcher() {
return watcher;
}
private void compilePattern() throws EventRegistrationException {
switch(watcher.getPatternType()) {
case FACT_CHECKING:
{
String statement = "";
try {
for (String s : watcher.getWatchPattern())
if (PartialStatement.isPartialStatement(s))
statement += onto.createPartialStatement(s).asSparqlRow();
else statement += Helpers.asSparqlRow(onto.createStatement(s));
} catch (IllegalStatementException e) {
Logger.log("Error while parsing a new watch pattern! ("+
e.getLocalizedMessage() +").\nCheck the syntax of " +
"your statement.\n", VerboseLevel.ERROR);
throw new EventRegistrationException("Error while parsing a " +
"new watch pattern! ("+ e.getLocalizedMessage() +").\n" +
"Check the syntax of your statement.\n");
}
String resultQuery = "ASK { " + statement + " }";
Logger.log("SPARQL query: " + resultQuery + "\n", VerboseLevel.DEBUG);
try {
cachedQuery = QueryFactory.create(resultQuery, Syntax.syntaxSPARQL);
}
catch (QueryParseException e) {
Logger.log("Internal error during query parsing while trying" +
" to add an event hook! ("+ e.getLocalizedMessage() +
").\nCheck the syntax of your statement.\n", VerboseLevel.ERROR);
throw new EventRegistrationException("Internal error during " +
"query parsing while trying to add an event hook! ("+
e.getLocalizedMessage() +").\nCheck the syntax of " +
"your statement.\n");
}
Logger.log("New FACT_CHECKING event registered:" +
"\n\tPattern: " + watcher.getWatchPattern() +
"\n\tTriggering type: " + watcher.getTriggeringType() +
"\n\tID: " + watcher.getId() + "\n");
break;
}
case NEW_CLASS_INSTANCE:
{
//No query to compile: we use directly the IOntologyBackend.getInstancesOf() method
if (watcher.getWatchPattern().size() != 1) {
Logger.log("Wrong pattern for a NEW_INSTANCE type of event." +
" Only one class name was expected.\n", VerboseLevel.ERROR);
throw new EventRegistrationException("Wrong pattern for a " +
"NEW_INSTANCE type of event. Only one class name was " +
"expected.");
}
//must use a "for" loop because getWatchPattern is a set, but it
//contains actually only one element.
for (String s : watcher.getWatchPattern()) {
Logger.logConcurrency(Logger.LockType.ACQUIRE_READ);
onto.getModel().enterCriticalSection(Lock.READ);
referenceClass = onto.getModel().getOntClass(Namespaces.format(s));
onto.getModel().leaveCriticalSection();
Logger.logConcurrency(Logger.LockType.RELEASE_READ);
if (referenceClass == null) {
Logger.log("The class " + s + " does not exists in the " +
"ontology. Cannot register the NEW_INSTANCE " +
"event!\n", VerboseLevel.ERROR);
throw new EventRegistrationException("The class " + s +
" does not exists in the ontology. Cannot " +
"register the NEW_INSTANCE event!");
}
}
//Initialize the list of matching instance from the current
//state on the ontology.
lastMatchedResources = new HashSet<Resource>(onto.getInstancesOf(referenceClass, false));
Logger.log("Initial matching instances: " + lastMatchedResources +
" (they won't be reported).\n", VerboseLevel.DEBUG);
Logger.log("New NEW_CLASS_INSTANCE event registered." +
"\n\tClass: " + Namespaces.toLightString(referenceClass) +
"\n\tID: " + watcher.getId() + "\n");
break;
}
case NEW_INSTANCE:
{
Logger.log("Compiling new NEW_INSTANCE event.\n", VerboseLevel.VERBOSE);
List<String> pattern = new ArrayList<String>(watcher.getWatchPattern());
//TODO: Implement filters for NEW_INSTANCE events
Set<String> filters = null;
varName = pattern.remove(0);
if (varName.length() > 0 && varName.charAt(0) == '?') varName = varName.substring(1);
String query = "SELECT ?" + varName + "\n" +
"WHERE {\n";
try {
for (String s : pattern)
query += onto.createPartialStatement(s).asSparqlRow();
} catch (IllegalStatementException e) {
Logger.log("Error while parsing partial statement ("+
e.getLocalizedMessage() +").\n", VerboseLevel.ERROR);
throw new EventRegistrationException("Error while parsing a " +
"new watch pattern! ("+ e.getLocalizedMessage() +").\n" +
"Check the syntax of your partial statements.\n");
}
if (!(filters == null || filters.isEmpty()))
{
Iterator<String> filtersItr = filters.iterator();
while (filtersItr.hasNext())
{
query += "FILTER (" + filtersItr.next() + ") .\n";
}
}
query += "}";
Logger.log("SPARQL query:\n" + query + "\n", VerboseLevel.DEBUG);
try {
cachedQuery = QueryFactory.create(query, Syntax.syntaxSPARQL);
}
catch (QueryParseException e) {
Logger.log("Internal error during query parsing while trying " +
"to add an event hook! ("+ e.getLocalizedMessage() +").\n" +
"Check the syntax of your statement.\n", VerboseLevel.ERROR);
throw new EventRegistrationException("Internal error during " +
"query parsing while trying to add an event hook! ("+
e.getLocalizedMessage() +").\nCheck the syntax of " +
"your statement.\n");
}
//Initialize the list of matching instance from the current state on the ontology.
lastMatchedResources = new HashSet<Resource>();
ResultSet rawResult = QueryExecutionFactory.create(cachedQuery, onto.getModel()).execSelect();
if (rawResult != null) {
while (rawResult.hasNext())
{
QuerySolution row = rawResult.nextSolution();
lastMatchedResources.add(row.getResource(varName));
}
}
Logger.log("Initial matching instances: " + lastMatchedResources +
" (they won't be reported).\n", VerboseLevel.DEBUG);
Logger.log("New NEW_INSTANCE event registered " +
"\n\tPattern: " + watcher.getWatchPattern() +
"\n\tTriggering type: " + watcher.getTriggeringType() +
"\n\tID: " + watcher.getId() + "\n");
}
}
}
}
/**
* the watchersCache holds as keys the literal watch pattern and as value a
* pair of pre-processed query built from the watch pattern and a boolean
* holding the last known result of the query.
*/
private Set<WatcherHolder> watchers;
public EventProcessor(IOntologyBackend onto) {
this.onto = onto;
this.watchers = new HashSet<WatcherHolder>();
this.supportedEventTypes = new HashSet<EventType>();
supportedEventTypes.add(EventType.FACT_CHECKING);
supportedEventTypes.add(EventType.NEW_CLASS_INSTANCE);
supportedEventTypes.add(EventType.NEW_INSTANCE);
}
public void process() {
Set<WatcherHolder> watchersToBeRemoved = new HashSet<WatcherHolder>();
//iterate over the various registered watchers and notify the subscribers
//when needed.
synchronized (watchers) {
for (WatcherHolder holder : watchers) {
switch (holder.getWatcher().getPatternType()) {
case FACT_CHECKING:
processFactChecking(holder, watchersToBeRemoved);
break;
case NEW_CLASS_INSTANCE:
processNewClassInstance(holder, watchersToBeRemoved);
break;
case NEW_INSTANCE:
processNewInstance(holder, watchersToBeRemoved);
break;
}
}
watchers.removeAll(watchersToBeRemoved);
}
}
private void processFactChecking(WatcherHolder holder, Set<WatcherHolder> watchersToBeRemoved) throws QueryExecException {
boolean isAsserted = false;
Logger.logConcurrency(Logger.LockType.ACQUIRE_READ);
onto.getModel().enterCriticalSection(Lock.READ);
try {
isAsserted = QueryExecutionFactory.create(holder.cachedQuery, onto.getModel()).execAsk();
}
catch (QueryExecException e) {
Logger.log("Internal error during query execution while " +
"verifiying conditions for event handlers! " +
"("+ e.getLocalizedMessage() +").\nPlease contact the " +
"maintainer :-)\n", VerboseLevel.SERIOUS_ERROR);
throw e;
}
finally {
onto.getModel().leaveCriticalSection();
Logger.logConcurrency(Logger.LockType.RELEASE_READ);
}
if (isAsserted) {
OroEvent e = new OroEventImpl();
switch(holder.watcher.getTriggeringType()){
case ON_TRUE:
case ON_TOGGLE:
//if the last status for this query is NOT true, then, trigger the event.
if (!holder.lastStatus) {
Logger.log("Event triggered for pattern " + holder.watcher.getWatchPattern() + "\n");
holder.watcher.notifySubscribers(e);
}
break;
case ON_TRUE_ONE_SHOT:
Logger.log("Event triggered for pattern " + holder.watcher.getWatchPattern() + "\n");
holder.watcher.notifySubscribers(e);
watchersToBeRemoved.add(holder);
break;
}
} else {
OroEvent e = new OroEventImpl();
switch(holder.watcher.getTriggeringType()){
case ON_FALSE:
case ON_TOGGLE:
//if the last statut for this query is NOT false, then, trigger the event.
if (holder.lastStatus) {
Logger.log("Event triggered for pattern " + holder.watcher.getWatchPattern() + "\n");
holder.watcher.notifySubscribers(e);
}
break;
case ON_FALSE_ONE_SHOT:
Logger.log("Event triggered for pattern " + holder.watcher.getWatchPattern() + "\n");
holder.watcher.notifySubscribers(e);
watchersToBeRemoved.add(holder);
break;
}
}
holder.lastStatus = isAsserted;
}
private void processNewClassInstance(WatcherHolder holder, Set<WatcherHolder> watchersToBeRemoved) throws QueryExecException {
Set<Resource> instances = new HashSet<Resource>(onto.getInstancesOf(holder.referenceClass, false));
Set<Resource> futureResources = new HashSet<Resource>(instances);
instances.removeAll(holder.lastMatchedResources);
//Nothing changed
if (instances.isEmpty() && futureResources.size() == holder.lastMatchedResources.size())
return;
//Instances have been removed
if (instances.isEmpty() && futureResources.size() < holder.lastMatchedResources.size()) {
holder.lastMatchedResources = futureResources;
return;
}
assert (!(instances.isEmpty() && futureResources.size() > holder.lastMatchedResources.size()));
//New instances have been added
OroEvent e = new OroEventNewInstances(instances);
switch (holder.watcher.getTriggeringType()) {
case ON_TRUE:
holder.watcher.notifySubscribers(e);
break;
case ON_TRUE_ONE_SHOT:
holder.watcher.notifySubscribers(e);
watchersToBeRemoved.add(holder);
break;
}
holder.lastMatchedResources = futureResources;
}
private void processNewInstance(WatcherHolder holder, Set<WatcherHolder> watchersToBeRemoved) throws QueryExecException {
Set<Resource> instances = new HashSet<Resource>();
ResultSet rawResult = null;
Logger.logConcurrency(Logger.LockType.ACQUIRE_READ);
onto.getModel().enterCriticalSection(Lock.READ);
try {
rawResult = QueryExecutionFactory.create(holder.cachedQuery, onto.getModel()).execSelect();
}
catch (QueryExecException e) {
Logger.log("Internal error during query execution while " +
"verifiying conditions for event handlers! " +
"("+ e.getLocalizedMessage() +").\nPlease contact the " +
"maintainer :-)\n", VerboseLevel.SERIOUS_ERROR);
throw e;
}
finally {
onto.getModel().leaveCriticalSection();
Logger.logConcurrency(Logger.LockType.RELEASE_READ);
}
if (rawResult != null) {
while (rawResult.hasNext())
{
QuerySolution row = rawResult.nextSolution();
instances.add(row.getResource(holder.varName));
}
}
Set<Resource> addedResources = new HashSet<Resource>(instances);
addedResources.removeAll(holder.lastMatchedResources);
Set<Resource> removedResources = new HashSet<Resource>(holder.lastMatchedResources);
removedResources.removeAll(instances);
//Instances have been removed
if (!removedResources.isEmpty()) {
OroEvent e = new OroEventNewInstances(removedResources);
switch (holder.watcher.getTriggeringType()) {
case ON_FALSE:
case ON_TOGGLE:
holder.watcher.notifySubscribers(e);
break;
case ON_FALSE_ONE_SHOT:
holder.watcher.notifySubscribers(e);
watchersToBeRemoved.add(holder);
break;
}
}
//New instances have been added
if (!addedResources.isEmpty()) {
OroEvent e = new OroEventNewInstances(addedResources);
switch (holder.watcher.getTriggeringType()) {
case ON_TRUE:
case ON_TOGGLE:
holder.watcher.notifySubscribers(e);
break;
case ON_TRUE_ONE_SHOT:
holder.watcher.notifySubscribers(e);
watchersToBeRemoved.add(holder);
break;
}
}
holder.lastMatchedResources = instances;
}
public Set<EventType> getSupportedEvents() {
return supportedEventTypes;
}
public void add(IWatcher w) throws EventRegistrationException {
if (!supportedEventTypes.contains(w.getPatternType())) {
Logger.log("An unsupported type of event (" +
w.getPatternType() + ") has reached the compilation stage. It" +
"shouldn't happen. Discarding it for now.\n", VerboseLevel.SERIOUS_ERROR);
}
else {
synchronized (watchers) {
watchers.add(new WatcherHolder(w));
}
}
}
public void clear() {
synchronized (watchers) {
watchers.clear();
}
}
public void remove(IWatcher w) throws OntologyServerException {
WatcherHolder wh = null;
synchronized (watchers) {
for (WatcherHolder e : watchers) {
if (e.watcher.equals(w)) wh = e;
}
if (wh == null) throw new OntologyServerException("Internal error! Event " +
w.getId().toString() + " is absent from the EventProcessor watchers. Please " +
"report this bug to openrobots@laas.fr.");
watchers.remove(wh);
}
}
}
|
package at.ac.tuwien.kr.alpha.grounder;
import at.ac.tuwien.kr.alpha.common.*;
import at.ac.tuwien.kr.alpha.common.NoGood.Type;
import at.ac.tuwien.kr.alpha.common.atoms.*;
import at.ac.tuwien.kr.alpha.common.terms.VariableTerm;
import at.ac.tuwien.kr.alpha.grounder.atoms.ChoiceAtom;
import at.ac.tuwien.kr.alpha.grounder.atoms.EnumerationAtom;
import at.ac.tuwien.kr.alpha.grounder.atoms.IntervalLiteral;
import at.ac.tuwien.kr.alpha.grounder.atoms.RuleAtom;
import at.ac.tuwien.kr.alpha.grounder.bridges.Bridge;
import at.ac.tuwien.kr.alpha.grounder.heuristics.GrounderHeuristicsConfiguration;
import at.ac.tuwien.kr.alpha.grounder.structure.AnalyzeUnjustified;
import at.ac.tuwien.kr.alpha.grounder.structure.ProgramAnalysis;
import at.ac.tuwien.kr.alpha.grounder.transformation.*;
import at.ac.tuwien.kr.alpha.solver.ThriceTruth;
import org.apache.commons.lang3.tuple.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import static at.ac.tuwien.kr.alpha.Util.oops;
import static at.ac.tuwien.kr.alpha.common.Literals.atomOf;
import static java.util.Collections.singletonList;
public class NaiveGrounder extends BridgedGrounder implements ProgramAnalyzingGrounder {
private static final Logger LOGGER = LoggerFactory.getLogger(NaiveGrounder.class);
private final WorkingMemory workingMemory = new WorkingMemory();
private final AtomStore atomStore;
private final NogoodRegistry registry = new NogoodRegistry();
final NoGoodGenerator noGoodGenerator;
private final ChoiceRecorder choiceRecorder;
private final ProgramAnalysis programAnalysis;
private final AnalyzeUnjustified analyzeUnjustified;
private final Map<Predicate, LinkedHashSet<Instance>> factsFromProgram = new LinkedHashMap<>();
private final Map<IndexedInstanceStorage, ArrayList<FirstBindingAtom>> rulesUsingPredicateWorkingMemory = new HashMap<>();
private final Map<NonGroundRule, HashSet<Substitution>> knownGroundingSubstitutions = new HashMap<>();
private final Map<Integer, NonGroundRule> knownNonGroundRules = new HashMap<>();
private ArrayList<NonGroundRule> fixedRules = new ArrayList<>();
private LinkedHashSet<Atom> removeAfterObtainingNewNoGoods = new LinkedHashSet<>();
private boolean disableInstanceRemoval;
private final boolean useCountingGridNormalization;
private final boolean debugInternalChecks;
private final GrounderHeuristicsConfiguration heuristicsConfiguration;
public NaiveGrounder(Program program, AtomStore atomStore, boolean debugInternalChecks, Bridge... bridges) {
this(program, atomStore, new GrounderHeuristicsConfiguration(), debugInternalChecks, bridges);
}
private NaiveGrounder(Program program, AtomStore atomStore, GrounderHeuristicsConfiguration heuristicsConfiguration, boolean debugInternalChecks, Bridge... bridges) {
this(program, atomStore, p -> true, heuristicsConfiguration, false, debugInternalChecks, bridges);
}
NaiveGrounder(Program program, AtomStore atomStore, java.util.function.Predicate<Predicate> filter, GrounderHeuristicsConfiguration heuristicsConfiguration, boolean useCountingGrid, boolean debugInternalChecks, Bridge... bridges) {
super(filter, bridges);
this.atomStore = atomStore;
this.heuristicsConfiguration = heuristicsConfiguration;
LOGGER.debug("Grounder configuration: " + heuristicsConfiguration);
programAnalysis = new ProgramAnalysis(program);
analyzeUnjustified = new AnalyzeUnjustified(programAnalysis, atomStore, factsFromProgram);
// Apply program transformations/rewritings.
useCountingGridNormalization = useCountingGrid;
applyProgramTransformations(program);
LOGGER.debug("Transformed input program is:\n" + program);
initializeFactsAndRules(program);
final Set<NonGroundRule> uniqueGroundRulePerGroundHead = getRulesWithUniqueHead();
choiceRecorder = new ChoiceRecorder(atomStore);
noGoodGenerator = new NoGoodGenerator(atomStore, choiceRecorder, factsFromProgram, programAnalysis, uniqueGroundRulePerGroundHead);
this.debugInternalChecks = debugInternalChecks;
}
private void initializeFactsAndRules(Program program) {
// initialize all facts
for (Atom fact : program.getFacts()) {
final Predicate predicate = fact.getPredicate();
// Record predicate
workingMemory.initialize(predicate);
// Construct fact instance(s).
List<Instance> instances = FactIntervalEvaluator.constructFactInstances(fact);
// Add instances to corresponding list of facts.
factsFromProgram.putIfAbsent(predicate, new LinkedHashSet<>());
HashSet<Instance> internalPredicateInstances = factsFromProgram.get(predicate);
internalPredicateInstances.addAll(instances);
}
// Register internal atoms.
workingMemory.initialize(RuleAtom.PREDICATE);
workingMemory.initialize(ChoiceAtom.OFF);
workingMemory.initialize(ChoiceAtom.ON);
// Initialize rules and constraints.
for (Rule rule : program.getRules()) {
// Record the rule for later use
NonGroundRule nonGroundRule = NonGroundRule.constructNonGroundRule(rule);
knownNonGroundRules.put(nonGroundRule.getRuleId(), nonGroundRule);
LOGGER.debug("NonGroundRule #" + nonGroundRule.getRuleId() + ": " + nonGroundRule);
// Record defining rules for each predicate.
Atom headAtom = nonGroundRule.getHeadAtom();
if (headAtom != null) {
Predicate headPredicate = headAtom.getPredicate();
programAnalysis.recordDefiningRule(headPredicate, nonGroundRule);
}
// Create working memories for all predicates occurring in the rule
for (Predicate predicate : nonGroundRule.getOccurringPredicates()) {
// FIXME: this also contains interval/builtin predicates that are not needed.
workingMemory.initialize(predicate);
}
// If the rule has fixed ground instantiations, it is not registered but grounded once like facts.
if (nonGroundRule.groundingOrder.fixedInstantiation()) {
fixedRules.add(nonGroundRule);
continue;
}
// Register each starting literal at the corresponding working memory.
for (Literal literal : nonGroundRule.groundingOrder.getStartingLiterals()) {
registerLiteralAtWorkingMemory(literal, nonGroundRule);
}
}
}
private Set<NonGroundRule> getRulesWithUniqueHead() {
// FIXME: below optimisation (adding support nogoods if there is only one rule instantiation per unique atom over the interpretation) could be done as a transformation (adding a non-ground constraint corresponding to the nogood that is generated by the grounder).
// Record all unique rule heads.
final Set<NonGroundRule> uniqueGroundRulePerGroundHead = new HashSet<>();
for (Map.Entry<Predicate, HashSet<NonGroundRule>> headDefiningRules : programAnalysis.getPredicateDefiningRules().entrySet()) {
if (headDefiningRules.getValue().size() != 1) {
continue;
}
NonGroundRule nonGroundRule = headDefiningRules.getValue().iterator().next();
// Check that all variables of the body also occur in the head (otherwise grounding is not unique).
Atom headAtom = nonGroundRule.getHeadAtom();
// Rule is not guaranteed unique if there are facts for it.
HashSet<Instance> potentialFacts = factsFromProgram.get(headAtom.getPredicate());
if (potentialFacts != null && !potentialFacts.isEmpty()) {
continue;
}
// Collect head and body variables.
HashSet<VariableTerm> occurringVariablesHead = new HashSet<>(headAtom.toLiteral().getBindingVariables());
HashSet<VariableTerm> occurringVariablesBody = new HashSet<>();
for (Atom atom : nonGroundRule.getBodyAtomsPositive()) {
occurringVariablesBody.addAll(atom.toLiteral().getBindingVariables());
}
occurringVariablesBody.removeAll(occurringVariablesHead);
// Check if ever body variables occurs in the head.
if (occurringVariablesBody.isEmpty()) {
uniqueGroundRulePerGroundHead.add(nonGroundRule);
}
}
return uniqueGroundRulePerGroundHead;
}
private void applyProgramTransformations(Program program) {
// Transform choice rules.
new ChoiceHeadToNormal().transform(program);
// Transform cardinality aggregates.
new CardinalityNormalization(!useCountingGridNormalization).transform(program);
// Transform sum aggregates.
new SumNormalization().transform(program);
// Transform intervals.
new IntervalTermToIntervalAtom().transform(program);
// Remove variable equalities.
new VariableEqualityRemoval().transform(program);
// Transform enumeration atoms.
new EnumerationRewriting().transform(program);
EnumerationAtom.resetEnumerations();
}
/**
* Registers a starting literal of a NonGroundRule at its corresponding working memory.
* @param nonGroundRule the rule in which the literal occurs.
*/
private void registerLiteralAtWorkingMemory(Literal literal, NonGroundRule nonGroundRule) {
if (literal.isNegated()) {
throw new RuntimeException("Literal to register is negated. Should not happen.");
}
IndexedInstanceStorage workingMemory = this.workingMemory.get(literal.getPredicate(), true);
rulesUsingPredicateWorkingMemory.putIfAbsent(workingMemory, new ArrayList<>());
rulesUsingPredicateWorkingMemory.get(workingMemory).add(new FirstBindingAtom(nonGroundRule, literal));
}
@Override
public AnswerSet assignmentToAnswerSet(Iterable<Integer> trueAtoms) {
Map<Predicate, SortedSet<Atom>> predicateInstances = new LinkedHashMap<>();
SortedSet<Predicate> knownPredicates = new TreeSet<>();
// Iterate over all true atomIds, computeNextAnswerSet instances from atomStore and add them if not filtered.
for (int trueAtom : trueAtoms) {
final Atom atom = atomStore.get(trueAtom);
Predicate predicate = atom.getPredicate();
// Skip atoms over internal predicates.
if (predicate.isInternal()) {
continue;
}
// Skip filtered predicates.
if (!filter.test(predicate)) {
continue;
}
knownPredicates.add(predicate);
predicateInstances.putIfAbsent(predicate, new TreeSet<>());
Set<Atom> instances = predicateInstances.get(predicate);
instances.add(atom);
}
// Add true atoms from facts.
for (Map.Entry<Predicate, LinkedHashSet<Instance>> facts : factsFromProgram.entrySet()) {
Predicate factPredicate = facts.getKey();
// Skip atoms over internal predicates.
if (factPredicate.isInternal()) {
continue;
}
// Skip filtered predicates.
if (!filter.test(factPredicate)) {
continue;
}
// Skip predicates without any instances.
if (facts.getValue().isEmpty()) {
continue;
}
knownPredicates.add(factPredicate);
predicateInstances.putIfAbsent(factPredicate, new TreeSet<>());
for (Instance factInstance : facts.getValue()) {
SortedSet<Atom> instances = predicateInstances.get(factPredicate);
instances.add(new BasicAtom(factPredicate, factInstance.terms));
}
}
if (knownPredicates.isEmpty()) {
return BasicAnswerSet.EMPTY;
}
return new BasicAnswerSet(knownPredicates, predicateInstances);
}
/**
* Prepares facts of the input program for joining and derives all NoGoods representing ground rules. May only be called once.
* @return
*/
private HashMap<Integer, NoGood> bootstrap() {
final HashMap<Integer, NoGood> groundNogoods = new LinkedHashMap<>();
for (Predicate predicate : factsFromProgram.keySet()) {
// Instead of generating NoGoods, add instance to working memories directly.
workingMemory.addInstances(predicate, true, factsFromProgram.get(predicate));
}
for (NonGroundRule nonGroundRule : fixedRules) {
// Generate NoGoods for all rules that have a fixed grounding.
RuleGroundingOrder groundingOrder = nonGroundRule.groundingOrder.getFixedGroundingOrder();
BindingResult bindingResult = bindNextAtomInRule(nonGroundRule, groundingOrder, new Substitution(), null);
groundAndRegister(nonGroundRule, bindingResult.generatedSubstitutions, groundNogoods);
}
fixedRules = null;
return groundNogoods;
}
@Override
public Map<Integer, NoGood> getNoGoods(Assignment currentAssignment) {
// In first call, prepare facts and ground rules.
final Map<Integer, NoGood> newNoGoods = fixedRules != null ? bootstrap() : new LinkedHashMap<>();
// Compute new ground rule (evaluate joins with newly changed atoms)
for (IndexedInstanceStorage modifiedWorkingMemory : workingMemory.modified()) {
// Skip predicates solely used in the solver which do not occur in rules.
Predicate workingMemoryPredicate = modifiedWorkingMemory.getPredicate();
if (workingMemoryPredicate.isSolverInternal()) {
continue;
}
// Iterate over all rules whose body contains the interpretation corresponding to the current workingMemory.
final ArrayList<FirstBindingAtom> firstBindingAtoms = rulesUsingPredicateWorkingMemory.get(modifiedWorkingMemory);
// Skip working memories that are not used by any rule.
if (firstBindingAtoms == null) {
continue;
}
for (FirstBindingAtom firstBindingAtom : firstBindingAtoms) {
// Use the recently added instances from the modified working memory to construct an initial substitution
NonGroundRule nonGroundRule = firstBindingAtom.rule;
// Generate substitutions from each recent instance.
for (Instance instance : modifiedWorkingMemory.getRecentlyAddedInstances()) {
// Check instance if it matches with the atom.
final Substitution unifier = Substitution.unify(firstBindingAtom.startingLiteral, instance, new Substitution());
if (unifier == null) {
continue;
}
final BindingResult bindingResult = bindNextAtomInRule(
nonGroundRule,
nonGroundRule.groundingOrder.orderStartingFrom(firstBindingAtom.startingLiteral),
unifier,
currentAssignment
);
groundAndRegister(nonGroundRule, bindingResult.generatedSubstitutions, newNoGoods);
}
}
// Mark instances added by updateAssignment as done
modifiedWorkingMemory.markRecentlyAddedInstancesDone();
}
workingMemory.reset();
for (Atom removeAtom : removeAfterObtainingNewNoGoods) {
final IndexedInstanceStorage storage = this.workingMemory.get(removeAtom, true);
Instance instance = new Instance(removeAtom.getTerms());
if (storage.containsInstance(instance)) {
// lax grounder heuristics may attempt to remove instances that are not yet in the working memory
storage.removeInstance(instance);
}
}
removeAfterObtainingNewNoGoods = new LinkedHashSet<>();
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Grounded NoGoods are:");
for (Map.Entry<Integer, NoGood> noGoodEntry : newNoGoods.entrySet()) {
LOGGER.debug("{} == {}", noGoodEntry.getValue(), atomStore.noGoodToString(noGoodEntry.getValue()));
}
LOGGER.debug("{}", choiceRecorder);
}
if (debugInternalChecks) {
checkTypesOfNoGoods(newNoGoods.values());
}
return newNoGoods;
}
/**
* Grounds the given {@code nonGroundRule} by applying the given {@code substitutions} and registers the nogoods generated during that process.
*
* @param nonGroundRule
* the rule to be grounded
* @param substitutions
* the substitutions to be applied
* @param newNoGoods
* a set of nogoods to which newly generated nogoods will be added
*/
private void groundAndRegister(final NonGroundRule nonGroundRule, final List<Substitution> substitutions, final Map<Integer, NoGood> newNoGoods) {
for (Substitution substitution : substitutions) {
List<NoGood> generatedNoGoods = noGoodGenerator.generateNoGoodsFromGroundSubstitution(nonGroundRule, substitution);
registry.register(generatedNoGoods, newNoGoods);
}
}
@Override
public int register(NoGood noGood) {
return registry.register(noGood);
}
private BindingResult bindNextAtomInRule(NonGroundRule rule, RuleGroundingOrder groundingOrder, Substitution partialSubstitution, Assignment currentAssignment) {
int tolerance = heuristicsConfiguration.getTolerance(rule.isConstraint());
if (tolerance < 0) {
tolerance = Integer.MAX_VALUE;
}
BindingResult bindingResult = bindNextAtomInRule(groundingOrder, 0, tolerance, tolerance, partialSubstitution, currentAssignment);
if (LOGGER.isDebugEnabled()) {
for (int i = 0; i < bindingResult.size(); i++) {
Integer numberOfUnassignedPositiveBodyAtoms = bindingResult.numbersOfUnassignedPositiveBodyAtoms.get(i);
if (numberOfUnassignedPositiveBodyAtoms > 0) {
LOGGER.debug("Grounded rule in which " + numberOfUnassignedPositiveBodyAtoms + " positive atoms are still unassigned: " + rule + " (substitution: " + bindingResult.generatedSubstitutions.get(i) + ")");
}
}
}
return bindingResult;
}
private BindingResult advanceAndBindNextAtomInRule(RuleGroundingOrder groundingOrder, int orderPosition, int originalTolerance, int remainingTolerance, Substitution partialSubstitution, Assignment currentAssignment) {
groundingOrder.considerUntilCurrentEnd();
return bindNextAtomInRule(groundingOrder, orderPosition + 1, originalTolerance, remainingTolerance, partialSubstitution, currentAssignment);
}
private BindingResult pushBackAndBindNextAtomInRule(RuleGroundingOrder groundingOrder, int orderPosition, int originalTolerance, int remainingTolerance, Substitution partialSubstitution, Assignment currentAssignment) {
RuleGroundingOrder modifiedGroundingOrder = groundingOrder.pushBack(orderPosition);
if (modifiedGroundingOrder == null) {
return BindingResult.empty();
}
return bindNextAtomInRule(modifiedGroundingOrder, orderPosition + 1, originalTolerance, remainingTolerance, partialSubstitution, currentAssignment);
}
private BindingResult bindNextAtomInRule(RuleGroundingOrder groundingOrder, int orderPosition, int originalTolerance, int remainingTolerance, Substitution partialSubstitution, Assignment currentAssignment) {
boolean laxGrounderHeuristic = originalTolerance > 0;
Literal currentLiteral = groundingOrder.getLiteralAtOrderPosition(orderPosition);
if (currentLiteral == null) {
return BindingResult.singleton(partialSubstitution, originalTolerance - remainingTolerance);
}
Atom currentAtom = currentLiteral.getAtom();
if (currentLiteral instanceof FixedInterpretationLiteral) {
// Generate all substitutions for the builtin/external/interval atom.
FixedInterpretationLiteral substitutedLiteral = (FixedInterpretationLiteral)currentLiteral.substitute(partialSubstitution);
// TODO: this has to be improved before merging into master:
if (!substitutedLiteral.isGround() &&
!(substitutedLiteral instanceof ComparisonLiteral && ((ComparisonLiteral)substitutedLiteral).isLeftOrRightAssigning()) &&
!(substitutedLiteral instanceof IntervalLiteral && substitutedLiteral.getTerms().get(0).isGround()) &&
!(substitutedLiteral instanceof ExternalLiteral)
) {
return pushBackAndBindNextAtomInRule(groundingOrder, orderPosition, originalTolerance, remainingTolerance, partialSubstitution, currentAssignment);
}
final List<Substitution> substitutions = substitutedLiteral.getSubstitutions(partialSubstitution);
if (substitutions.isEmpty()) {
// if FixedInterpretationLiteral cannot be satisfied now, it will never be
return BindingResult.empty();
}
final BindingResult bindingResult = new BindingResult();
for (Substitution substitution : substitutions) {
// Continue grounding with each of the generated values.
bindingResult.add(advanceAndBindNextAtomInRule(groundingOrder, orderPosition, originalTolerance, remainingTolerance, substitution, currentAssignment));
}
return bindingResult;
}
if (currentAtom instanceof EnumerationAtom) {
// Get the enumeration value and add it to the current partialSubstitution.
((EnumerationAtom) currentAtom).addEnumerationToSubstitution(partialSubstitution);
return advanceAndBindNextAtomInRule(groundingOrder, orderPosition, originalTolerance, remainingTolerance, partialSubstitution, currentAssignment);
}
Collection<Instance> instances = null;
// check if partialVariableSubstitution already yields a ground atom
final Atom substitute = currentAtom.substitute(partialSubstitution);
if (substitute.isGround()) {
// Substituted atom is ground, in case it is positive, only ground if it also holds true
if (currentLiteral.isNegated()) {
// Atom occurs negated in the rule: continue grounding
return advanceAndBindNextAtomInRule(groundingOrder, orderPosition, originalTolerance, remainingTolerance, partialSubstitution, currentAssignment);
}
if (!groundingOrder.isGround() && remainingTolerance <= 0
&& !workingMemory.get(currentAtom.getPredicate(), true).containsInstance(new Instance(substitute.getTerms()))) {
// Generate no variable substitution.
return BindingResult.empty();
}
// Check if atom is also assigned true.
final LinkedHashSet<Instance> factInstances = factsFromProgram.get(substitute.getPredicate());
if (factInstances != null && factInstances.contains(new Instance(substitute.getTerms()))) {
// Ground literal holds, continue finding a variable substitution.
return advanceAndBindNextAtomInRule(groundingOrder, orderPosition, originalTolerance, remainingTolerance, partialSubstitution, currentAssignment);
}
// Atom is not a fact already.
instances = singletonList(new Instance(substitute.getTerms()));
}
// substituted atom contains variables
if (currentLiteral.isNegated()) {
if (laxGrounderHeuristic) {
return pushBackAndBindNextAtomInRule(groundingOrder, orderPosition, originalTolerance, remainingTolerance, partialSubstitution, currentAssignment);
} else {
throw oops("Current atom should be positive at this point but is not");
}
}
if (instances == null) {
IndexedInstanceStorage storage = workingMemory.get(currentAtom.getPredicate(), true);
if (partialSubstitution.isEmpty()) {
// No variables are bound, but first atom in the body became recently true, consider all instances now.
instances = storage.getAllInstances();
} else {
instances = storage.getInstancesFromPartiallyGroundAtom(substitute);
}
}
if (laxGrounderHeuristic && instances.isEmpty()) {
// we have reached a point where we have to terminate binding,
// but it might be possible that a different grounding order would allow us to continue binding
// under the presence of a lax grounder heuristic
return pushBackAndBindNextAtomInRule(groundingOrder, orderPosition, originalTolerance, remainingTolerance, partialSubstitution, currentAssignment);
}
BindingResult bindingResult = new BindingResult();
for (Instance instance : instances) {
// Check each instance if it matches with the atom.
Substitution unified = Substitution.unify(substitute, instance, new Substitution(partialSubstitution));
if (unified == null) {
continue;
}
// Check if atom is also assigned true.
Atom substituteClone = new BasicAtom(substitute.getPredicate(), substitute.getTerms());
Atom substitutedAtom = substituteClone.substitute(unified);
if (!substitutedAtom.isGround()) {
throw oops("Grounded atom should be ground but is not");
}
AtomicInteger atomicRemainingTolerance = new AtomicInteger(remainingTolerance); // TODO: done this way for call-by-reference, should be refactored
if (factsFromProgram.get(substitutedAtom.getPredicate()) == null || !factsFromProgram.get(substitutedAtom.getPredicate()).contains(new Instance(substitutedAtom.getTerms()))) {
if (storeAtomAndTerminateIfAtomDoesNotHold(substitutedAtom, currentAssignment, atomicRemainingTolerance)) {
continue;
}
}
bindingResult.add(advanceAndBindNextAtomInRule(groundingOrder, orderPosition, originalTolerance, atomicRemainingTolerance.get(), unified, currentAssignment));
}
return bindingResult;
}
private boolean storeAtomAndTerminateIfAtomDoesNotHold(final Atom substitute, Assignment currentAssignment, AtomicInteger remainingTolerance) {
final int atomId = atomStore.putIfAbsent(substitute);
if (currentAssignment != null) {
ThriceTruth truth = currentAssignment.isAssigned(atomId) ? currentAssignment.getTruth(atomId) : null;
if (truth == null || !truth.toBoolean()) {
// Atom currently does not hold
if (!disableInstanceRemoval) {
removeAfterObtainingNewNoGoods.add(substitute);
}
if (truth == null && remainingTolerance.decrementAndGet() < 0) {
// terminate if more positive atoms are unsatisfied as tolerated by the heuristic
return true;
}
// terminate if positive body atom is assigned false
return truth != null && !truth.toBoolean();
}
}
return false;
}
@Override
public Pair<Map<Integer, Integer>, Map<Integer, Integer>> getChoiceAtoms() {
return choiceRecorder.getAndResetChoices();
}
@Override
public Map<Integer, Set<Integer>> getHeadsToBodies() {
return choiceRecorder.getAndResetHeadsToBodies();
}
@Override
public void updateAssignment(Iterator<Integer> it) {
while (it.hasNext()) {
workingMemory.addInstance(atomStore.get(it.next()), true);
}
}
@Override
public void forgetAssignment(int[] atomIds) {
throw new UnsupportedOperationException("Forgetting assignments is not implemented");
}
public static String groundAndPrintRule(NonGroundRule rule, Substitution substitution) {
StringBuilder ret = new StringBuilder();
if (!rule.isConstraint()) {
Atom groundHead = rule.getHeadAtom().substitute(substitution);
ret.append(groundHead.toString());
}
ret.append(" :- ");
boolean isFirst = true;
for (Atom bodyAtom : rule.getBodyAtomsPositive()) {
ret.append(groundLiteralToString(bodyAtom.toLiteral(), substitution, isFirst));
isFirst = false;
}
for (Atom bodyAtom : rule.getBodyAtomsNegative()) {
ret.append(groundLiteralToString(bodyAtom.toLiteral(false), substitution, isFirst));
isFirst = false;
}
ret.append(".");
return ret.toString();
}
static String groundLiteralToString(Literal literal, Substitution substitution, boolean isFirst) {
Literal groundLiteral = literal.substitute(substitution);
return (isFirst ? "" : ", ") + groundLiteral.toString();
}
@Override
public NonGroundRule getNonGroundRule(Integer ruleId) {
return knownNonGroundRules.get(ruleId);
}
@Override
public boolean isFact(Atom atom) {
LinkedHashSet<Instance> instances = factsFromProgram.get(atom.getPredicate());
if (instances == null) {
return false;
}
return instances.contains(new Instance(atom.getTerms()));
}
@Override
public Set<Literal> justifyAtom(int atomToJustify, Assignment currentAssignment) {
Set<Literal> literals = analyzeUnjustified.analyze(atomToJustify, currentAssignment);
// Remove facts from justification before handing it over to the solver.
for (Iterator<Literal> iterator = literals.iterator(); iterator.hasNext();) {
Literal literal = iterator.next();
if (literal.isNegated()) {
continue;
}
LinkedHashSet<Instance> factsOverPredicate = factsFromProgram.get(literal.getPredicate());
if (factsOverPredicate != null && factsOverPredicate.contains(new Instance(literal.getAtom().getTerms()))) {
iterator.remove();
}
}
return literals;
}
/**
* Checks that every nogood not marked as {@link NoGood.Type#INTERNAL} contains only
* atoms which are not {@link Predicate#isSolverInternal()} (except {@link RuleAtom}s, which are allowed).
* @param newNoGoods
*/
private void checkTypesOfNoGoods(Collection<NoGood> newNoGoods) {
for (NoGood noGood : newNoGoods) {
if (noGood.getType() != Type.INTERNAL) {
for (int literal : noGood) {
Atom atom = atomStore.get(atomOf(literal));
if (atom.getPredicate().isSolverInternal() && !(atom instanceof RuleAtom)) {
throw oops("NoGood containing atom of internal predicate " + atom + " is " + noGood.getType() + " instead of INTERNAL");
}
}
}
}
}
private static class FirstBindingAtom {
final NonGroundRule rule;
final Literal startingLiteral;
FirstBindingAtom(NonGroundRule rule, Literal startingLiteral) {
this.rule = rule;
this.startingLiteral = startingLiteral;
}
}
private static class BindingResult {
final List<Substitution> generatedSubstitutions = new ArrayList<>();
final List<Integer> numbersOfUnassignedPositiveBodyAtoms = new ArrayList<>();
void add(Substitution generatedSubstitution, int numberOfUnassignedPositiveBodyAtoms) {
this.generatedSubstitutions.add(generatedSubstitution);
this.numbersOfUnassignedPositiveBodyAtoms.add(numberOfUnassignedPositiveBodyAtoms);
}
void add(BindingResult otherBindingResult) {
this.generatedSubstitutions.addAll(otherBindingResult.generatedSubstitutions);
this.numbersOfUnassignedPositiveBodyAtoms.addAll(otherBindingResult.numbersOfUnassignedPositiveBodyAtoms);
}
int size() {
return generatedSubstitutions.size();
}
static BindingResult empty() {
return new BindingResult();
}
static BindingResult singleton(Substitution generatedSubstitution, int numberOfUnassignedPositiveBodyAtoms) {
BindingResult bindingResult = new BindingResult();
bindingResult.add(generatedSubstitution, numberOfUnassignedPositiveBodyAtoms);
return bindingResult;
}
}
}
|
package com.censoredsoftware.censoredlib.util;
import com.censoredsoftware.censoredlib.data.Cache;
import com.censoredsoftware.censoredlib.language.Symbol;
import com.censoredsoftware.censoredlib.schematic.BlockData;
import com.censoredsoftware.censoredlib.schematic.Schematic;
import com.censoredsoftware.censoredlib.schematic.Selection;
import com.google.common.collect.ImmutableBiMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.bukkit.*;
import org.bukkit.entity.Player;
import org.bukkit.map.MapCanvas;
import org.bukkit.map.MapPalette;
import org.bukkit.map.MapRenderer;
import org.bukkit.map.MapView;
import javax.imageio.ImageIO;
import java.awt.Color;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.util.Map;
public class Images
{
private static final ImmutableBiMap<ChatColor, Color> CHAT_COLOR_COLOR;
static
{
Map<ChatColor, Color> chatColorColor = Maps.newHashMap();
chatColorColor.put(ChatColor.BLACK, Color.decode("#000000"));
chatColorColor.put(ChatColor.DARK_BLUE, Color.decode("#0000AA"));
chatColorColor.put(ChatColor.DARK_GREEN, Color.decode("#00AA00"));
chatColorColor.put(ChatColor.DARK_AQUA, Color.decode("#00AAAA"));
chatColorColor.put(ChatColor.DARK_RED, Color.decode("#AA0000"));
chatColorColor.put(ChatColor.DARK_PURPLE, Color.decode("#AA00AA"));
chatColorColor.put(ChatColor.GOLD, Color.decode("#FFAA00"));
chatColorColor.put(ChatColor.GRAY, Color.decode("#AAAAAA"));
chatColorColor.put(ChatColor.DARK_GRAY, Color.decode("#555555"));
chatColorColor.put(ChatColor.BLUE, Color.decode("#5555FF"));
chatColorColor.put(ChatColor.GREEN, Color.decode("#55FF55"));
chatColorColor.put(ChatColor.AQUA, Color.decode("#55FFFF"));
chatColorColor.put(ChatColor.RED, Color.decode("#FF5555"));
chatColorColor.put(ChatColor.LIGHT_PURPLE, Color.decode("#FF55FF"));
chatColorColor.put(ChatColor.YELLOW, Color.decode("#FFFF55"));
chatColorColor.put(ChatColor.WHITE, Color.decode("#FFFFFF"));
CHAT_COLOR_COLOR = ImmutableBiMap.copyOf(chatColorColor);
}
private static ImmutableBiMap<DyeColor, Color> DYE_COLOR_COLOR;
static
{
Map<DyeColor, Color> dyeColorColor = Maps.newHashMap();
dyeColorColor.put(DyeColor.BLACK, Color.decode("#191919"));
dyeColorColor.put(DyeColor.BLUE, Color.decode("#334CB2"));
dyeColorColor.put(DyeColor.BROWN, Color.decode("#664C33"));
dyeColorColor.put(DyeColor.CYAN, Color.decode("#4C7F99"));
dyeColorColor.put(DyeColor.GRAY, Color.decode("#4C4C4C"));
dyeColorColor.put(DyeColor.GREEN, Color.decode("#667F33"));
dyeColorColor.put(DyeColor.LIGHT_BLUE, Color.decode("#6699D8"));
dyeColorColor.put(DyeColor.LIME, Color.decode("#7FCC19"));
dyeColorColor.put(DyeColor.MAGENTA, Color.decode("#B24CD8"));
dyeColorColor.put(DyeColor.ORANGE, Color.decode("#D87F33"));
dyeColorColor.put(DyeColor.PINK, Color.decode("#F27FA5"));
dyeColorColor.put(DyeColor.PURPLE, Color.decode("#7F3FB2"));
dyeColorColor.put(DyeColor.RED, Color.decode("#993333"));
dyeColorColor.put(DyeColor.SILVER, Color.decode("#999999"));
dyeColorColor.put(DyeColor.WHITE, Color.decode("#FFFFFF"));
dyeColorColor.put(DyeColor.YELLOW, Color.decode("#E5E533"));
DYE_COLOR_COLOR = ImmutableBiMap.copyOf(dyeColorColor);
}
/**
* @deprecated
*/
public static ChatColor fromColor(Color color)
{
return getChatColor(color);
}
public static double getColorDistance(Color color1, Color color2)
{
long rmean = ((long) color1.getRed() + (long) color2.getRed()) / 2;
long r = (long) color1.getRed() - (long) color2.getRed();
long g = (long) color1.getGreen() - (long) color2.getGreen();
long b = (long) color1.getBlue() - (long) color2.getBlue();
return Math.sqrt((((512 + rmean) * r * r) >> 8) + 4 * g * g + (((767 - rmean) * b * b) >> 8));
}
public static ChatColor getChatColor(final Color color)
{
Color nearestColor = Color.decode("#FFFFFF");
double nearestDistance = -1.0;
for(Color chatColor : CHAT_COLOR_COLOR.values())
{
double distance = getColorDistance(chatColor, color);
if(nearestDistance == -1.0 || distance < nearestDistance)
{
nearestColor = color;
nearestDistance = distance;
}
}
return CHAT_COLOR_COLOR.inverse().get(nearestColor);
}
public static DyeColor getDyeColor(final Color color)
{
Color nearestColor = Color.decode("#FFFFFF");
double nearestDistance = -1.0;
for(Color chatColor : DYE_COLOR_COLOR.values())
{
double distance = getColorDistance(chatColor, color);
if(nearestDistance == -1.0 || distance < nearestDistance)
{
nearestColor = color;
nearestDistance = distance;
}
}
return DYE_COLOR_COLOR.inverse().get(nearestColor);
}
public static java.util.List<String> convertImage(BufferedImage image, Symbol symbol)
{
// Working list.
java.util.List<String> convertedImage = Lists.newArrayList();
// Get the image's height and width.
int width = image.getWidth();
int height = image.getHeight();
// Iterate through the image, pixel by pixel.
for(int i = 0; i < height; i++)
{
StringBuilder line = new StringBuilder();
for(int j = 0; j < width; j++)
{
// Get the color for each pixel.
ChatColor color = getChatColor(new Color(image.getRGB(j, i)));
// Append to the line.
line.append(color.toString()).append(symbol);
}
// Add to working list.
convertedImage.add(line.toString());
}
// Return finalized list.
return convertedImage;
}
public static Schematic convertImageToSchematic(BufferedImage image)
{
// Working list.
Schematic schematic = new Schematic("", "", 0);
// Get the image's height and width.
int width = image.getWidth();
int height = image.getHeight();
// Iterate through the image, pixel by pixel.
for(int i = 0; i < height; i++)
{
for(int j = 0; j < width; j++)
{
// Get the color for each pixel.
DyeColor color = getDyeColor(new Color(image.getRGB(j, i)));
// Make new selection.
schematic.add(new Selection(j, width - i, 0, new BlockData(Material.WOOL, color.getWoolData())));
}
}
// Return finalized list.
return schematic;
}
public static MapView sendMapImage(Player player, BufferedImage image)
{
MapView map = Bukkit.createMap(player.getWorld());
map = ImageRenderer.applyToMap(map, image);
player.sendMap(map);
return map;
}
public static class ImageRenderer extends MapRenderer
{
private BufferedImage image;
public ImageRenderer(BufferedImage image)
{
this.image = MapPalette.resizeImage(image);
}
@Override
public void render(MapView mapView, MapCanvas mapCanvas, Player player)
{
mapCanvas.drawImage(0, 0, image);
}
public static MapView applyToMap(MapView map, BufferedImage image)
{
for(MapRenderer renderer : map.getRenderers())
map.removeRenderer(renderer);
map.addRenderer(new ImageRenderer(image));
return map;
}
}
public static BufferedImage getPlayerHead(String playerName) throws NullPointerException
{
try
{
// Get the image from Mojang.
URL url = new URL("http://s3.amazonaws.com/MinecraftSkins/" + playerName + ".png");
BufferedImage image = ImageIO.read(url);
// Get data from the skin.
Image head = image.getSubimage(8, 8, 8, 8);
Image overlay = image.getSubimage(40, 8, 8, 8);
// Render just the (front of the) head of the skin.
BufferedImage finalImage = new BufferedImage(64, 64, Image.SCALE_SMOOTH);
finalImage.getGraphics().drawImage(head, 0, 0, 64, 64, null);
finalImage.getGraphics().drawImage(overlay, 0, 0, 64, 64, null);
return finalImage;
}
catch(Throwable errored)
{
errored.printStackTrace();
Bukkit.getServer().getLogger().warning("[CensoredLib] " + "Something went wrong during an image conversion process.");
}
return null;
}
public static java.util.List<String> getPlayerHead(OfflinePlayer player) throws NullPointerException
{
// Get the player's name.
String playerName = player.getName();
// Check if we already have this player's head.
if(Cache.hasTimed(playerName, ""))
{
Object data = Cache.getTimedValue(playerName, "playerHead");
if(data != null && data instanceof java.util.List) return (java.util.List<String>) data;
else Cache.remove(playerName, "playerHead");
}
try
{
BufferedImage image = getPlayerHead(playerName);
// Convert.
java.util.List<String> convertedImage = convertImage(image, Symbol.FULL_BLOCK);
// Put the player's head in the cache.
Cache.saveTimedDay(playerName, "playerHead", convertedImage);
// Return the converted head.
return convertedImage;
}
catch(Throwable errored)
{
errored.printStackTrace();
Bukkit.getServer().getLogger().warning("[CensoredLib] " + "Something went wrong during an image conversion process.");
}
// Something went wrong.
return null;
}
public static BufferedImage getScaledImage(BufferedImage image, int width, int height) throws IOException
{
int imageWidth = image.getWidth();
int imageHeight = image.getHeight();
double scaleX = (double) width / imageWidth;
double scaleY = (double) height / imageHeight;
AffineTransform scaleTransform = AffineTransform.getScaleInstance(scaleX, scaleY);
AffineTransformOp bilinearScaleOp = new AffineTransformOp(scaleTransform, AffineTransformOp.TYPE_BILINEAR);
return bilinearScaleOp.filter(image, new BufferedImage(width, height, image.getType()));
}
public static BufferedImage getGrayscaleImage(BufferedImage image)
{
BufferedImage gray = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_BYTE_GRAY);
Graphics g = image.getGraphics();
g.drawImage(image, 0, 0, null);
g.dispose();
return gray;
}
}
|
package com.commafeed.backend.dao;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.ejb.Stateless;
import javax.persistence.NoResultException;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import org.apache.commons.lang.StringUtils;
import com.commafeed.backend.model.Feed;
import com.commafeed.backend.model.FeedCategory;
import com.commafeed.backend.model.FeedEntry;
import com.commafeed.backend.model.FeedEntryContent;
import com.commafeed.backend.model.FeedEntryContent_;
import com.commafeed.backend.model.FeedEntryStatus;
import com.commafeed.backend.model.FeedEntryStatus_;
import com.commafeed.backend.model.FeedEntry_;
import com.commafeed.backend.model.FeedSubscription;
import com.commafeed.backend.model.FeedSubscription_;
import com.commafeed.backend.model.User;
import com.commafeed.backend.model.UserSettings.ReadingOrder;
import com.google.api.client.util.Lists;
import com.google.api.client.util.Maps;
import com.uaihebert.model.EasyCriteria;
@Stateless
public class FeedEntryStatusDAO extends GenericDAO<FeedEntryStatus> {
public FeedEntryStatus findById(User user, Long id) {
EasyCriteria<FeedEntryStatus> criteria = createCriteria();
criteria.andEquals(FeedEntryStatus_.id.getName(), id);
criteria.innerJoinFetch(FeedEntryStatus_.subscription.getName());
criteria.andJoinEquals(FeedEntryStatus_.subscription.getName(),
FeedSubscription_.user.getName(), user);
FeedEntryStatus status = null;
try {
status = criteria.getSingleResult();
} catch (NoResultException e) {
status = null;
}
return status;
}
@SuppressWarnings("unchecked")
public List<FeedEntryStatus> findByKeywords(User user, String keywords,
int offset, int limit) {
String joinedKeywords = StringUtils.join(
keywords.toLowerCase().split(" "), "%");
joinedKeywords = "%" + joinedKeywords + "%";
CriteriaQuery<FeedEntryStatus> query = builder.createQuery(getType());
Root<FeedEntryStatus> root = query.from(getType());
List<Predicate> predicates = Lists.newArrayList();
Join<FeedEntryStatus, FeedEntry> entryJoin = (Join<FeedEntryStatus, FeedEntry>) root
.fetch(FeedEntryStatus_.entry);
Join<FeedEntryStatus, FeedSubscription> subJoin = (Join<FeedEntryStatus, FeedSubscription>) root
.fetch(FeedEntryStatus_.subscription);
subJoin.fetch(FeedSubscription_.feed);
Join<FeedEntry, FeedEntryContent> contentJoin = (Join<FeedEntry, FeedEntryContent>) entryJoin
.fetch(FeedEntry_.content);
predicates
.add(builder.equal(subJoin.get(FeedSubscription_.user), user));
Predicate content = builder.like(
builder.lower(contentJoin.get(FeedEntryContent_.content)),
joinedKeywords);
Predicate title = builder.like(
builder.lower(contentJoin.get(FeedEntryContent_.title)),
joinedKeywords);
predicates.add(builder.or(content, title));
query.where(predicates.toArray(new Predicate[0]));
orderBy(query, entryJoin, ReadingOrder.desc);
TypedQuery<FeedEntryStatus> q = em.createQuery(query);
limit(q, offset, limit);
return q.getResultList();
}
@SuppressWarnings("unchecked")
public List<FeedEntryStatus> findStarred(User user, int offset, int limit,
ReadingOrder order, boolean includeContent) {
CriteriaQuery<FeedEntryStatus> query = builder.createQuery(getType());
Root<FeedEntryStatus> root = query.from(getType());
List<Predicate> predicates = Lists.newArrayList();
Join<FeedEntryStatus, FeedEntry> entryJoin = (Join<FeedEntryStatus, FeedEntry>) root
.fetch(FeedEntryStatus_.entry);
Join<FeedEntryStatus, FeedSubscription> subJoin = (Join<FeedEntryStatus, FeedSubscription>) root
.fetch(FeedEntryStatus_.subscription);
subJoin.fetch(FeedSubscription_.feed);
predicates
.add(builder.equal(subJoin.get(FeedSubscription_.user), user));
predicates.add(builder.equal(root.get(FeedEntryStatus_.starred), true));
query.where(predicates.toArray(new Predicate[0]));
if (includeContent) {
entryJoin.fetch(FeedEntry_.content);
}
orderBy(query, entryJoin, order);
TypedQuery<FeedEntryStatus> q = em.createQuery(query);
limit(q, offset, limit);
return q.getResultList();
}
public List<FeedEntryStatus> findAll(User user, boolean unreadOnly,
ReadingOrder order, boolean includeContent) {
return findAll(user, unreadOnly, -1, -1, order, includeContent);
}
@SuppressWarnings("unchecked")
public List<FeedEntryStatus> findAll(User user, boolean unreadOnly,
int offset, int limit, ReadingOrder order, boolean includeContent) {
CriteriaQuery<FeedEntryStatus> query = builder.createQuery(getType());
Root<FeedEntryStatus> root = query.from(getType());
List<Predicate> predicates = Lists.newArrayList();
Join<FeedEntryStatus, FeedEntry> entryJoin = (Join<FeedEntryStatus, FeedEntry>) root
.fetch(FeedEntryStatus_.entry);
Join<FeedEntryStatus, FeedSubscription> subJoin = (Join<FeedEntryStatus, FeedSubscription>) root
.fetch(FeedEntryStatus_.subscription);
subJoin.fetch(FeedSubscription_.feed);
predicates
.add(builder.equal(subJoin.get(FeedSubscription_.user), user));
if (unreadOnly) {
predicates.add(builder.isFalse(root.get(FeedEntryStatus_.read)));
}
if (includeContent) {
entryJoin.fetch(FeedEntry_.content);
}
query.where(predicates.toArray(new Predicate[0]));
orderBy(query, entryJoin, order);
TypedQuery<FeedEntryStatus> q = em.createQuery(query);
limit(q, offset, limit);
return q.getResultList();
}
/**
* Map between subscriptionId and unread count
*/
@SuppressWarnings("rawtypes")
public Map<Long, Long> getUnreadCount(User user) {
Map<Long, Long> map = Maps.newHashMap();
Query query = em.createNamedQuery("EntryStatus.unreadCounts");
query.setParameter("user", user);
List resultList = query.getResultList();
for (Object o : resultList) {
Object[] array = (Object[]) o;
map.put((Long) array[0], (Long) array[1]);
}
return map;
}
public List<FeedEntryStatus> findByFeed(Feed feed, User user,
boolean unreadOnly, ReadingOrder order, boolean includeContent) {
return findByFeed(feed, user, unreadOnly, -1, -1, order, includeContent);
}
@SuppressWarnings("unchecked")
public List<FeedEntryStatus> findByFeed(Feed feed, User user,
boolean unreadOnly, int offset, int limit, ReadingOrder order,
boolean includeContent) {
CriteriaQuery<FeedEntryStatus> query = builder.createQuery(getType());
Root<FeedEntryStatus> root = query.from(getType());
List<Predicate> predicates = Lists.newArrayList();
Join<FeedEntryStatus, FeedEntry> entryJoin = (Join<FeedEntryStatus, FeedEntry>) root
.fetch(FeedEntryStatus_.entry);
Join<FeedEntryStatus, FeedSubscription> subJoin = (Join<FeedEntryStatus, FeedSubscription>) root
.fetch(FeedEntryStatus_.subscription);
subJoin.fetch(FeedSubscription_.feed);
predicates
.add(builder.equal(subJoin.get(FeedSubscription_.user), user));
predicates
.add(builder.equal(subJoin.get(FeedSubscription_.feed), feed));
if (unreadOnly) {
predicates.add(builder.isFalse(root.get(FeedEntryStatus_.read)));
}
if (includeContent) {
entryJoin.fetch(FeedEntry_.content);
}
query.where(predicates.toArray(new Predicate[0]));
orderBy(query, entryJoin, order);
TypedQuery<FeedEntryStatus> q = em.createQuery(query);
limit(q, offset, limit);
return q.getResultList();
}
public List<FeedEntryStatus> findByCategories(
List<FeedCategory> categories, User user, boolean unreadOnly,
ReadingOrder order, boolean includeContent) {
return findByCategories(categories, user, unreadOnly, -1, -1, order,
includeContent);
}
@SuppressWarnings("unchecked")
public List<FeedEntryStatus> findByCategories(
List<FeedCategory> categories, User user, boolean unreadOnly,
int offset, int limit, ReadingOrder order, boolean includeContent) {
CriteriaQuery<FeedEntryStatus> query = builder.createQuery(getType());
Root<FeedEntryStatus> root = query.from(getType());
List<Predicate> predicates = Lists.newArrayList();
Join<FeedEntryStatus, FeedEntry> entryJoin = (Join<FeedEntryStatus, FeedEntry>) root
.fetch(FeedEntryStatus_.entry);
Join<FeedEntryStatus, FeedSubscription> subJoin = (Join<FeedEntryStatus, FeedSubscription>) root
.fetch(FeedEntryStatus_.subscription);
subJoin.fetch(FeedSubscription_.feed);
predicates
.add(builder.equal(subJoin.get(FeedSubscription_.user), user));
predicates.add(subJoin.get(FeedSubscription_.category).in(categories));
if (unreadOnly) {
predicates.add(builder.isFalse(root.get(FeedEntryStatus_.read)));
}
if (includeContent) {
entryJoin.fetch(FeedEntry_.content);
}
query.where(predicates.toArray(new Predicate[0]));
orderBy(query, entryJoin, order);
TypedQuery<FeedEntryStatus> q = em.createQuery(query);
limit(q, offset, limit);
return q.getResultList();
}
private void orderBy(CriteriaQuery<FeedEntryStatus> query,
Join<FeedEntryStatus, FeedEntry> entryJoin, ReadingOrder order) {
Path<Date> orderPath = entryJoin.get(FeedEntry_.updated);
if (order == ReadingOrder.asc) {
query.orderBy(builder.asc(orderPath));
} else {
query.orderBy(builder.desc(orderPath));
}
}
public void markFeedEntries(User user, Feed feed, Date olderThan) {
List<FeedEntryStatus> statuses = findByFeed(feed, user, true,
ReadingOrder.desc, false);
update(markList(statuses, olderThan));
}
public void markCategoryEntries(User user, List<FeedCategory> categories,
Date olderThan) {
List<FeedEntryStatus> statuses = findByCategories(categories, user,
true, ReadingOrder.desc, false);
update(markList(statuses, olderThan));
}
public void markAllEntries(User user, Date olderThan) {
List<FeedEntryStatus> statuses = findAll(user, true, ReadingOrder.desc,
false);
update(markList(statuses, olderThan));
}
private List<FeedEntryStatus> markList(List<FeedEntryStatus> statuses,
Date olderThan) {
List<FeedEntryStatus> list = Lists.newArrayList();
for (FeedEntryStatus status : statuses) {
if (!status.isRead()) {
Date inserted = status.getEntry().getInserted();
if (olderThan == null || inserted == null
|| olderThan.after(inserted)) {
status.setRead(true);
list.add(status);
}
}
}
return list;
}
}
|
package x2x.translator.pragma;
import exc.object.Xobject;
import java.util.regex.*;
public enum CLAWpragma {
//directive
LOOP_FUSION,
LOOP_INTERCHANGE,
LOOP_TO,
// loop-fusion
FUSION_GROUP,
// loop-interchange
NEW_ORDER,
;
private static final String CLAW_DIRECTIVE = "claw";
private static final String LOOP_FUSION_DIRECTIVE = "loop-fusion";
private static final String LOOP_INTERCHANGE_DIRECTIVE = "loop-interchange";
private static final String LOOP_TO_DIRECTIVE = "loop-vector";
private static final String OPTION_FUSION_GROUP = "group";
private static final String MULTIPLE_SPACES = " *";
private static final String INNER_OPTION = "\\(([^)]+)\\)";
private String name = null;
public String getName() {
if (name == null) name = toString().toLowerCase();
return name;
}
public static CLAWpragma getDirective(String pragma){
// TODO error handling
String[] parts = pragma.split(" ");
String directive = parts[1];
switch(directive){
case LOOP_FUSION_DIRECTIVE:
return CLAWpragma.LOOP_FUSION;
case LOOP_INTERCHANGE_DIRECTIVE:
return CLAWpragma.LOOP_INTERCHANGE;
default:
return null;
}
}
public static String getGroupOptionValue(String pragma){
if(getDirective(pragma) != CLAWpragma.LOOP_FUSION){
return null;
}
Matcher matchFullDirective = Pattern.compile(CLAW_DIRECTIVE +
MULTIPLE_SPACES + LOOP_FUSION_DIRECTIVE + MULTIPLE_SPACES +
OPTION_FUSION_GROUP + INNER_OPTION).matcher(pragma);
if(!matchFullDirective.matches()){
return null;
}
Matcher matchOption = Pattern.compile(INNER_OPTION).matcher(pragma);
while(matchOption.find()) {
return matchOption.group(1);
}
return null;
}
public static String getNewOrderOptionValue(String pragma){
if(getDirective(pragma) != CLAWpragma.LOOP_INTERCHANGE){
return null;
}
Matcher matchFullDirective = Pattern.compile(CLAW_DIRECTIVE +
MULTIPLE_SPACES + LOOP_INTERCHANGE_DIRECTIVE + MULTIPLE_SPACES
+ INNER_OPTION).matcher(pragma);
if(!matchFullDirective.matches()){
return null;
}
Matcher matchOption = Pattern.compile(INNER_OPTION).matcher(pragma);
while(matchOption.find()) {
return matchOption.group(1);
}
return null;
}
public static boolean startsWithClaw(String pragma){
if(pragma.startsWith(CLAW_DIRECTIVE)){
return true;
}
return false;
}
// Check the correctness of a claw directive
// TODO correct error message
public static boolean isValid(String pragma){
String[] parts = pragma.split(" ");
if(parts.length < 2){
return false;
}
String claw = parts[0];
String directive = parts[1];
if(!claw.equals(CLAW_DIRECTIVE)){
return false;
}
switch(directive){
case LOOP_FUSION_DIRECTIVE:
return isValidOption(CLAWpragma.LOOP_FUSION, null);
case LOOP_INTERCHANGE_DIRECTIVE:
return isValidOption(CLAWpragma.LOOP_INTERCHANGE, null);
case LOOP_TO_DIRECTIVE:
return isValidOption(CLAWpragma.LOOP_TO, null);
default:
return false;
}
}
// TODO check option according to the directive
private static boolean isValidOption(CLAWpragma directive, String[] options){
return true;
}
public static CLAWpragma valueOf(Xobject x) {
return valueOf(x.getString());
}
public boolean isDirective(){
switch(this){
case LOOP_FUSION:
case LOOP_INTERCHANGE:
case LOOP_TO:
return true;
default:
return false;
}
}
public boolean isLoop(){
switch(this){
case LOOP_FUSION:
case LOOP_INTERCHANGE:
case LOOP_TO:
return true;
default:
return false;
}
}
}
|
package com.couchbase.lite.replicator;
import com.couchbase.lite.BlobKey;
import com.couchbase.lite.BlobStore;
import com.couchbase.lite.ChangesOptions;
import com.couchbase.lite.CouchbaseLiteException;
import com.couchbase.lite.Database;
import com.couchbase.lite.DocumentChange;
import com.couchbase.lite.Manager;
import com.couchbase.lite.ReplicationFilter;
import com.couchbase.lite.RevisionList;
import com.couchbase.lite.Status;
import com.couchbase.lite.internal.InterfaceAudience;
import com.couchbase.lite.internal.RevisionInternal;
import com.couchbase.lite.support.CustomFuture;
import com.couchbase.lite.support.HttpClientFactory;
import com.couchbase.lite.support.RemoteRequest;
import com.couchbase.lite.support.RemoteRequestCompletionBlock;
import com.couchbase.lite.support.RevisionUtils;
import com.couchbase.lite.util.JSONUtils;
import com.couchbase.lite.util.Log;
import com.couchbase.lite.util.Utils;
import com.couchbase.org.apache.http.entity.mime.MultipartEntity;
import com.couchbase.org.apache.http.entity.mime.content.FileBody;
import com.couchbase.org.apache.http.entity.mime.content.StringBody;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpResponseException;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
/**
* @exclude
*/
@InterfaceAudience.Private
public class PusherInternal extends ReplicationInternal implements Database.ChangeListener {
// Max in-memory size of buffered bulk_docs dictionary
private static long kMaxBulkDocsObjectSize = 5*1000*1000;
public static final int MAX_PENDING_DOCS = 200;
private boolean createTarget;
private boolean creatingTarget;
private boolean observing;
private ReplicationFilter filter;
private boolean dontSendMultipart = false;
SortedSet<Long> pendingSequences;
Long maxPendingSequence;
private boolean paused = false;
private Object pausedObj = new Object();
/**
* Constructor
*
* @exclude
*/
@InterfaceAudience.Private
public PusherInternal(Database db, URL remote,
HttpClientFactory clientFactory,
ScheduledExecutorService workExecutor,
Replication.Lifecycle lifecycle,
Replication parentReplication) {
super(db, remote, clientFactory, workExecutor, lifecycle, parentReplication);
}
@Override
@InterfaceAudience.Public
public boolean isPull() {
return false;
}
@Override
public boolean shouldCreateTarget() {
return createTarget;
}
@Override
public void setCreateTarget(boolean createTarget) {
this.createTarget = createTarget;
}
@Override
protected void stop() {
if (stateMachine.isInState(ReplicationState.STOPPED))
return;
Log.d(Log.TAG_SYNC, "%s STOPPING...", toString());
stopObserving();
super.stop();
// this has to be on a different thread than the replicator thread, or else it's a deadlock
// because it might be waiting for jobs that have been scheduled, and not
// yet executed (and which will never execute because this will block processing).
new Thread(new Runnable() {
@Override
public void run() {
try {
// wait for all tasks completed
waitForPendingFutures();
} catch (Exception e) {
Log.e(Log.TAG_SYNC, "stop.run() had exception: %s", e);
} finally {
triggerStopImmediate();
Log.d(Log.TAG_SYNC, "PusherInternal stop.run() finished");
}
}
}).start();
}
protected boolean waitingForPendingFutures = false;
protected Object lockWaitForPendingFutures = new Object();
public void waitForPendingFutures() {
if (waitingForPendingFutures) {
return;
}
synchronized (lockWaitForPendingFutures) {
waitingForPendingFutures = true;
Log.d(Log.TAG_SYNC, "[waitForPendingFutures()] STARTED - thread id: " +
Thread.currentThread().getId());
try {
// wait for batcher's pending futures
if (batcher != null) {
Log.d(Log.TAG_SYNC, "batcher.waitForPendingFutures()");
// TODO: should we call batcher.flushAll(); here?
batcher.waitForPendingFutures();
Log.d(Log.TAG_SYNC, "/batcher.waitForPendingFutures()");
}
while (!pendingFutures.isEmpty()) {
Future future = pendingFutures.take();
try {
Log.d(Log.TAG_SYNC, "calling future.get() on %s", future);
future.get();
Log.d(Log.TAG_SYNC, "done calling future.get() on %s", future);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
// since it's possible that in the process of waiting for pendingFutures,
// new items were added to the batcher, let's wait for the batcher to
// drain again.
if (batcher != null) {
Log.d(Log.TAG_SYNC, "batcher.waitForPendingFutures()");
batcher.waitForPendingFutures();
Log.d(Log.TAG_SYNC, "/batcher.waitForPendingFutures()");
}
// If pendingFutures queue is empty and state is RUNNING, fireTrigger to IDLE
// NOTE: in case of many documents sync, new Future tasks could be added into the queue.
// This is reason to check if queue is empty.
if (pendingFutures.isEmpty()) {
Log.v(Log.TAG_SYNC, "[waitForPendingFutures()] state=" + stateMachine.getState());
if (isContinuous()) {
// Make state IDLE
Log.v(Log.TAG_SYNC, "[waitForPendingFutures()] fireTrigger(ReplicationTrigger.WAITING_FOR_CHANGES);");
fireTrigger(ReplicationTrigger.WAITING_FOR_CHANGES);
} else {
// Make state STOPPING
triggerStopGraceful();
}
}
} catch (Exception e) {
Log.e(Log.TAG_SYNC, "Exception waiting for pending futures: %s", e);
} finally {
Log.d(Log.TAG_SYNC, "[waitForPendingFutures()] END - thread id: " + Thread.currentThread().getId());
waitingForPendingFutures = false;
}
}
}
/**
* - (void) maybeCreateRemoteDB in CBL_Replicator.m
*/
@Override
@InterfaceAudience.Private
protected void maybeCreateRemoteDB() {
if (!createTarget) {
return;
}
creatingTarget = true;
Log.v(Log.TAG_SYNC, "Remote db might not exist; creating it...");
Future future = sendAsyncRequest("PUT", "", null, new RemoteRequestCompletionBlock() {
@Override
public void onCompletion(HttpResponse httpResponse, Object result, Throwable e) {
creatingTarget = false;
if (e != null && e instanceof HttpResponseException &&
((HttpResponseException) e).getStatusCode() != 412) {
Log.e(Log.TAG_SYNC, this + ": Failed to create remote db", e);
setError(e);
triggerStopGraceful(); // this is fatal: no db to push to!
} else {
Log.v(Log.TAG_SYNC, "%s: Created remote db", this);
createTarget = false;
beginReplicating();
}
}
});
pendingFutures.add(future);
}
/**
* - (void) beginReplicating in CBL_Replicator.m
*/
@Override
@InterfaceAudience.Private
public void beginReplicating() {
// If we're still waiting to create the remote db, do nothing now. (This method will be
// re-invoked after that request finishes; see -maybeCreateRemoteDB above.)
Log.d(Log.TAG_SYNC, "%s: beginReplicating() called", this);
// If we're still waiting to create the remote db, do nothing now. (This method will be
// re-invoked after that request finishes; see maybeCreateRemoteDB() above.)
if (creatingTarget) {
Log.d(Log.TAG_SYNC, "%s: creatingTarget == true, doing nothing", this);
return;
}
pendingSequences = Collections.synchronizedSortedSet(new TreeSet<Long>());
try {
maxPendingSequence = Long.parseLong(lastSequence);
} catch (NumberFormatException e) {
Log.w(Log.TAG_SYNC, "Error converting lastSequence: %s to long. Using 0", lastSequence);
maxPendingSequence = new Long(0);
}
filter = compilePushReplicationFilter();
if (filterName != null && filter == null) {
Log.w(Log.TAG_SYNC, "%s: No ReplicationFilter registered for filter '%s'; ignoring",
this, filterName);
}
// Process existing changes since the last push:
long lastSequenceLong = 0;
if (lastSequence != null) {
lastSequenceLong = Long.parseLong(lastSequence);
}
ChangesOptions options = new ChangesOptions();
options.setIncludeConflicts(true);
Log.d(Log.TAG_SYNC, "%s: Getting changes since %s", this, lastSequence);
RevisionList changes = db.changesSince(lastSequenceLong, options, filter, filterParams);
if (changes.size() > 0) {
Log.d(Log.TAG_SYNC, "%s: Queuing %d changes since %s", this, changes.size(), lastSequence);
int remaining = changes.size();
int size = batcher.getCapacity();
int start = 0;
while(remaining > 0){
if(size > remaining)
size = remaining;
RevisionList subChanges = new RevisionList(changes.subList(start, start+size));
batcher.queueObjects(subChanges);
start += size;
remaining -= size;
pauseOrResume();
waitIfPaused();
}
} else {
Log.d(Log.TAG_SYNC, "%s: No changes since %s", this, lastSequence);
}
// Now listen for future changes (in continuous mode):
if (isContinuous()) {
observing = true;
db.addChangeListener(this);
}
}
/**
* - (void) stopObserving in CBL_Replicator.m
*/
@InterfaceAudience.Private
private void stopObserving() {
if (observing) {
observing = false;
db.removeChangeListener(this);
}
}
/**
* - (BOOL) goOnline in CBL_Replicator.m
*/
@Override
protected void goOnline() {
super.goOnline();
Log.d(Log.TAG_SYNC, "%s: goOnline() called, calling checkSession()", this);
// Note: checkSession() -> fetchRemoteCheckpointDoc() -> beginReplicating()
// => start observing database
checkSession();
}
/**
* - (BOOL) goOffline in CBL_Pusher.m
*/
@Override
protected void goOffline() {
super.goOffline();
stopObserving();
}
/**
* Adds a local revision to the "pending" set that are awaiting upload:
* - (void) addPending: (CBL_Revision*)rev in CBLRestPusher.m
*/
@InterfaceAudience.Private
private void addPending(RevisionInternal revisionInternal) {
long seq = revisionInternal.getSequence();
pendingSequences.add(seq);
if (seq > maxPendingSequence) {
maxPendingSequence = seq;
}
}
/**
* Removes a revision from the "pending" set after it's been uploaded. Advances checkpoint.
* - (void) removePending: (CBL_Revision*)rev in CBLRestPusher.m
*/
@InterfaceAudience.Private
private void removePending(RevisionInternal revisionInternal) {
long seq = revisionInternal.getSequence();
if (pendingSequences == null || pendingSequences.isEmpty()) {
Log.w(Log.TAG_SYNC, "%s: removePending() called w/ rev: %s, but pendingSequences empty",
this, revisionInternal);
if(revisionInternal.getBody()!=null)
revisionInternal.getBody().release();
pauseOrResume();
return;
}
boolean wasFirst = (seq == pendingSequences.first());
if (!pendingSequences.contains(seq)) {
Log.w(Log.TAG_SYNC, "%s: removePending: sequence %s not in set, for rev %s",
this, seq, revisionInternal);
}
pendingSequences.remove(seq);
if (wasFirst) {
// If I removed the first pending sequence, can advance the checkpoint:
long maxCompleted;
if (pendingSequences.size() == 0) {
maxCompleted = maxPendingSequence;
} else {
maxCompleted = pendingSequences.first();
--maxCompleted;
}
setLastSequence(Long.toString(maxCompleted));
}
if(revisionInternal.getBody()!=null)
revisionInternal.getBody().release();
pauseOrResume();
}
/**
* - (void) dbChanged: (NSNotification*)n in CBLRestPusher.m
*/
@Override
@InterfaceAudience.Private
public void changed(Database.ChangeEvent event) {
List<DocumentChange> changes = event.getChanges();
for (DocumentChange change : changes) {
// Skip revisions that originally came from the database I'm syncing to:
URL source = change.getSource();
if (source != null && source.equals(remote)) {
return;
}
RevisionInternal rev = change.getAddedRevision();
if (getLocalDatabase().runFilter(filter, filterParams, rev)) {
pauseOrResume();
waitIfPaused();
RevisionInternal nuRev = rev.copy();
nuRev.setBody(null); //save memory
addToInbox(nuRev);
}
}
}
/**
* - (void) processInbox: (CBL_RevisionList*)changes in CBLRestPusher.m
*/
@Override
@InterfaceAudience.Private
protected void processInbox(final RevisionList changes) {
Log.v(Log.TAG_SYNC, "processInbox() changes="+changes.size());
// Generate a set of doc/rev IDs in the JSON format that _revs_diff wants:
Map<String, List<String>> diffs = new HashMap<String, List<String>>();
for (RevisionInternal rev : changes) {
String docID = rev.getDocID();
List<String> revs = diffs.get(docID);
if (revs == null) {
revs = new ArrayList<String>();
diffs.put(docID, revs);
}
revs.add(rev.getRevID());
addPending(rev);
}
// Call _revs_diff on the target db:
Log.v(Log.TAG_SYNC, "%s: posting to /_revs_diff", this);
CustomFuture future = sendAsyncRequest("POST", "/_revs_diff", diffs, new RemoteRequestCompletionBlock() {
@Override
public void onCompletion(HttpResponse httpResponse, Object response, Throwable e) {
Log.v(Log.TAG_SYNC, "%s: got /_revs_diff response", this);
Map<String, Object> results = (Map<String, Object>) response;
if (e != null) {
setError(e);
} else {
if (results.size() != 0) {
// Go through the list of local changes again, selecting the ones the destination server
// said were missing and mapping them to a JSON dictionary in the form _bulk_docs wants:
List<Object> docsToSend = new ArrayList<Object>();
RevisionList revsToSend = new RevisionList();
long bufferedSize = 0;
for (RevisionInternal rev : changes) {
// Is this revision in the server's 'missing' list?
Map<String, Object> properties = null;
Map<String, Object> revResults = (Map<String, Object>) results.get(rev.getDocID());
if (revResults == null) {
removePending(rev);
continue;
}
List<String> revs = (List<String>) revResults.get("missing");
if (revs == null || !revs.contains(rev.getRevID())) {
removePending(rev);
continue;
}
// NOTE: force to load body by Database.loadRevisionBody()
// In SQLiteStore.loadRevisionBody() does not load data from database
// if sequence != 0 && body != null
rev.setSequence(0);
rev.setBody(null);
RevisionInternal loadedRev;
try {
loadedRev = db.loadRevisionBody(rev);
} catch (CouchbaseLiteException e1) {
Log.w(Log.TAG_SYNC, "%s Couldn't get local contents of %s", rev, PusherInternal.this);
continue;
}
RevisionInternal populatedRev = transformRevision(loadedRev);
loadedRev = null;
List<String> possibleAncestors = (List<String>) revResults.get("possible_ancestors");
properties = new HashMap<String, Object>(populatedRev.getProperties());
Map<String, Object> revisions = db.getRevisionHistoryDictStartingFromAnyAncestor(populatedRev, possibleAncestors);
properties.put("_revisions", revisions);
populatedRev.setProperties(properties);
// Strip any attachments already known to the target db:
if (properties.containsKey("_attachments")) {
// Look for the latest common ancestor and stub out older attachments:
int minRevPos = findCommonAncestor(populatedRev, possibleAncestors);
Status status = new Status(Status.OK);
if (!db.expandAttachments(populatedRev, minRevPos + 1, !dontSendMultipart, false, status)) {
Log.w(Log.TAG_SYNC, "%s: Couldn't expand attachments of %s", this, populatedRev);
continue;
}
properties = populatedRev.getProperties();
if (!dontSendMultipart && uploadMultipartRevision(populatedRev)) {
continue;
}
}
if (properties == null || !properties.containsKey("_id")) {
throw new IllegalStateException("properties must contain a document _id");
}
revsToSend.add(rev);
docsToSend.add(properties);
bufferedSize += JSONUtils.estimate(properties);
if (bufferedSize > kMaxBulkDocsObjectSize) {
uploadBulkDocs(docsToSend, revsToSend);
docsToSend = new ArrayList<Object>();
revsToSend = new RevisionList();
bufferedSize = 0;
}
}
// Post the revisions to the destination:
uploadBulkDocs(docsToSend, revsToSend);
} else {
// None of the revisions are new to the remote
for (RevisionInternal revisionInternal : changes) {
removePending(revisionInternal);
}
}
}
}
});
future.setQueue(pendingFutures);
pendingFutures.add(future);
pauseOrResume();
}
/**
* Post the revisions to the destination. "new_edits":false means that the server should
* use the given _rev IDs instead of making up new ones.
*
* - (void) uploadBulkDocs: (NSArray*)docsToSend changes: (CBL_RevisionList*)changes
* in CBLRestPusher.m
*/
@InterfaceAudience.Private
protected void uploadBulkDocs(List<Object> docsToSend, final RevisionList changes) {
final int numDocsToSend = docsToSend.size();
if (numDocsToSend == 0) {
return;
}
Log.v(Log.TAG_SYNC, "%s: POSTing " + numDocsToSend + " revisions to _bulk_docs: %s", PusherInternal.this, docsToSend);
addToChangesCount(numDocsToSend);
Map<String, Object> bulkDocsBody = new HashMap<String, Object>();
bulkDocsBody.put("docs", docsToSend);
bulkDocsBody.put("new_edits", false);
CustomFuture future = sendAsyncRequest("POST", "/_bulk_docs", bulkDocsBody, new RemoteRequestCompletionBlock() {
@Override
public void onCompletion(HttpResponse httpResponse, Object result, Throwable e) {
if (e == null) {
Set<String> failedIDs = new HashSet<String>();
// _bulk_docs response is really an array, not a dictionary!
List<Map<String, Object>> items = (List) result;
for (Map<String, Object> item : items) {
Status status = statusFromBulkDocsResponseItem(item);
if (status.isError()) {
// One of the docs failed to save.
Log.w(Log.TAG_SYNC, "%s: _bulk_docs got an error: %s", item, this);
// 403/Forbidden means validation failed; don't treat it as an error
// because I did my job in sending the revision. Other statuses are
// actual replication errors.
if (status.getCode() != Status.FORBIDDEN) {
String docID = (String) item.get("id");
failedIDs.add(docID);
// TODO - port from iOS
// NSURL* url = docID ? [_remote URLByAppendingPathComponent: docID] : nil;
// error = CBLStatusToNSError(status, url);
}
}
}
// Remove from the pending list all the revs that didn't fail:
for (RevisionInternal revisionInternal : changes) {
if (!failedIDs.contains(revisionInternal.getDocID())) {
removePending(revisionInternal);
}
}
}
if (e != null) {
setError(e);
} else {
Log.v(Log.TAG_SYNC, "%s: POSTed to _bulk_docs", PusherInternal.this);
}
addToCompletedChangesCount(numDocsToSend);
}
});
future.setQueue(pendingFutures);
pendingFutures.add(future);
}
/**
* in CBL_Pusher.m
* - (CBLMultipartWriter*)multipartWriterForRevision: (CBL_Revision*)rev
*/
@InterfaceAudience.Private
private boolean uploadMultipartRevision(final RevisionInternal revision) {
MultipartEntity multiPart = null;
Map<String, Object> revProps = revision.getProperties();
Map<String, Object> attachments = (Map<String, Object>) revProps.get("_attachments");
for (String attachmentKey : attachments.keySet()) {
Map<String, Object> attachment = (Map<String, Object>) attachments.get(attachmentKey);
if (attachment.containsKey("follows")) {
if (multiPart == null) {
multiPart = new MultipartEntity();
try {
String json = Manager.getObjectMapper().writeValueAsString(revProps);
Charset utf8charset = Charset.forName("UTF-8");
byte[] uncompressed = json.getBytes(utf8charset);
byte[] compressed = null;
byte[] data = uncompressed;
String contentEncoding = null;
if (uncompressed.length > RemoteRequest.MIN_JSON_LENGTH_TO_COMPRESS && canSendCompressedRequests()) {
compressed = Utils.compressByGzip(uncompressed);
if (compressed.length < uncompressed.length) {
data = compressed;
contentEncoding = "gzip";
}
}
// NOTE: StringBody.contentEncoding default value is null. Setting null value to contentEncoding does not cause any impact.
multiPart.addPart("param1", new StringBody(data, "application/json", utf8charset, contentEncoding));
} catch (IOException e) {
throw new IllegalArgumentException(e);
}
}
BlobStore blobStore = this.db.getAttachmentStore();
String base64Digest = (String) attachment.get("digest");
BlobKey blobKey = new BlobKey(base64Digest);
String path = blobStore.getRawPathForKey(blobKey);
File file = new File(path);
if (!file.exists()) {
Log.w(Log.TAG_SYNC, "Unable to find blob file for blobKey: %s - Skipping upload of multipart revision.", blobKey);
return false;
} else {
String contentType = null;
if (attachment.containsKey("content_type")) {
contentType = (String) attachment.get("content_type");
} else if (attachment.containsKey("type")) {
contentType = (String) attachment.get("type");
} else if (attachment.containsKey("content-type")) {
Log.w(Log.TAG_SYNC, "Found attachment that uses content-type" +
" field name instead of content_type (see couchbase-lite-android" +
" issue #80): %s", attachment);
}
// contentType = null causes Exception from FileBody of apache.
if(contentType == null)
contentType = "application/octet-stream"; // default
// NOTE: Content-Encoding might not be necessary to set. Apache FileBody does not set Content-Encoding.
// FileBody always return null for getContentEncoding(), and Content-Encoding header is not set in multipart
// CBL iOS: https://github.com/couchbase/couchbase-lite-ios/blob/feb7ff5eda1e80bd00e5eb19f1d46c793f7a1951/Source/CBL_Pusher.m#L449-L452
String contentEncoding = null;
if (attachment.containsKey("encoding")) {
contentEncoding = (String) attachment.get("encoding");
}
FileBody fileBody = new CustomFileBody(file, attachmentKey, contentType, contentEncoding);
multiPart.addPart(attachmentKey, fileBody);
}
}
}
if (multiPart == null) {
return false;
}
final String path = String.format("/%s?new_edits=false", encodeDocumentId(revision.getDocID()));
Log.d(Log.TAG_SYNC, "Uploading multipart request. Revision: %s", revision);
addToChangesCount(1);
CustomFuture future = sendAsyncMultipartRequest("PUT", path, multiPart, new RemoteRequestCompletionBlock() {
@Override
public void onCompletion(HttpResponse httpResponse, Object result, Throwable e) {
try {
if (e != null) {
if (e instanceof HttpResponseException) {
// Server doesn't like multipart, eh? Fall back to JSON.
if (((HttpResponseException) e).getStatusCode() == 415) {
//status 415 = "bad_content_type"
dontSendMultipart = true;
uploadJsonRevision(revision);
}
} else {
Log.e(Log.TAG_SYNC, "Exception uploading multipart request", e);
setError(e);
}
} else {
Log.v(Log.TAG_SYNC, "Uploaded multipart request. Revision: %s", revision);
removePending(revision);
}
} finally {
addToCompletedChangesCount(1);
}
}
});
future.setQueue(pendingFutures);
pendingFutures.add(future);
return true;
}
/**
* Fallback to upload a revision if uploadMultipartRevision failed due to the server's rejecting
* multipart format.
* - (void) uploadJSONRevision: (CBL_Revision*)originalRev in CBLRestPusher.m
*/
private void uploadJsonRevision(final RevisionInternal rev) {
// Get the revision's properties:
if (!db.inlineFollowingAttachmentsIn(rev)) {
setError(new CouchbaseLiteException(Status.BAD_ATTACHMENT));
return;
}
final String path = String.format("/%s?new_edits=false", encodeDocumentId(rev.getDocID()));
CustomFuture future = sendAsyncRequest("PUT",
path,
rev.getProperties(),
new RemoteRequestCompletionBlock() {
public void onCompletion(HttpResponse httpResponse, Object result, Throwable e) {
if (e != null) {
setError(e);
} else {
Log.v(Log.TAG_SYNC, "%s: Sent %s (JSON), response=%s", this, rev, result);
removePending(rev);
}
}
});
future.setQueue(pendingFutures);
pendingFutures.add(future);
}
/**
* Given a revision and an array of revIDs, finds the latest common ancestor revID
* and returns its generation #. If there is none, returns 0.
*
* int CBLFindCommonAncestor(CBL_Revision* rev, NSArray* possibleRevIDs) in CBLRestPusher.m
*/
private static int findCommonAncestor(RevisionInternal rev, List<String> possibleRevIDs) {
if (possibleRevIDs == null || possibleRevIDs.size() == 0) {
return 0;
}
List<String> history = Database.parseCouchDBRevisionHistory(rev.getProperties());
//rev is missing _revisions property
assert (history != null);
boolean changed = history.retainAll(possibleRevIDs);
String ancestorID = history.size() == 0 ? null : history.get(0);
if (ancestorID == null) {
return 0;
}
int generation = RevisionUtils.parseRevIDNumber(ancestorID);
return generation;
}
// CustomFileBody to support contentEncoding. FileBody returns always null for getContentEncoding()
private static class CustomFileBody extends FileBody {
private String contentEncoding = null;
public CustomFileBody(File file, String filename, String mimeType, String contentEncoding) {
super(file, filename, mimeType, null);
this.contentEncoding = contentEncoding;
}
@Override
public String getContentEncoding() {
return contentEncoding;
}
}
private void pauseOrResume() {
int pending = batcher.count() + pendingSequences.size();
setPaused(pending >= MAX_PENDING_DOCS);
}
private void setPaused(boolean paused) {
Log.v(Log.TAG, "setPaused: " + paused);
synchronized (pausedObj) {
if(this.paused != paused) {
this.paused = paused;
pausedObj.notifyAll();
}
}
}
private void waitIfPaused(){
synchronized (pausedObj) {
while (paused) {
Log.v(Log.TAG, "Waiting: " + paused);
try {
pausedObj.wait();
} catch (InterruptedException e) {
}
}
}
}
}
|
package com.devicehive.service;
import com.devicehive.configuration.Constants;
import com.devicehive.dao.DeviceDAO;
import com.devicehive.model.Device;
import com.devicehive.model.DeviceClass;
import com.devicehive.utils.LogExecutionTime;
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.IMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.PostConstruct;
import javax.ejb.*;
import javax.websocket.Session;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
@Singleton
@Startup
@ConcurrencyManagement(ConcurrencyManagementType.BEAN)
@EJB(beanInterface = DeviceActivityService.class, name = "DeviceActivityService")
@LogExecutionTime
public class DeviceActivityService {
private static final Logger logger = LoggerFactory.getLogger(DeviceActivityService.class);
@EJB
private HazelcastService hazelcastService;
@EJB
private DeviceDAO deviceDAO;
private HazelcastInstance hazelcast;
private IMap<Long,Long> deviceTimestampMap;
@PostConstruct
public void postConstruct() {
hazelcast = hazelcastService.getHazelcast();
deviceTimestampMap = hazelcast.getMap(Constants.DEVICE_ACTIVITY_MAP);
}
public void update(long deviceId) {
deviceTimestampMap.putAsync(deviceId, hazelcast.getCluster().getClusterTime());
}
@Schedule(hour = "*", minute = "*/1")
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public void processOfflineDevices() {
logger.debug("Checking lost offline devices");
long now = hazelcast.getCluster().getClusterTime();
for (Iterator<Long> iter = deviceTimestampMap.localKeySet().iterator(); iter.hasNext();) {
Long deviceId = iter.next();
Device device = deviceDAO.findById(deviceId);
logger.debug("Checking device {} ", device.getGuid());
DeviceClass deviceClass = device.getDeviceClass();
if (deviceClass.getOfflineTimeout() != null) {
if (now - deviceTimestampMap.get(deviceId) > deviceClass.getOfflineTimeout() * 1000) {
deviceDAO.setOffline(deviceId);
iter.remove();
logger.warn("Device {} is now offline", device.getGuid());
}
}
}
logger.debug("Checking lost offline devices complete");
}
}
|
package com.elmakers.mine.bukkit.block;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.elmakers.mine.bukkit.api.block.BrushMode;
import com.elmakers.mine.bukkit.api.magic.MageController;
import com.elmakers.mine.bukkit.api.magic.Messages;
import com.elmakers.mine.bukkit.utility.InventoryUtils;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.DyeColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Hanging;
import org.bukkit.entity.Item;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.map.MapRenderer;
import org.bukkit.map.MapView;
import org.bukkit.util.Vector;
import com.elmakers.mine.bukkit.api.block.Schematic;
import com.elmakers.mine.bukkit.api.magic.Mage;
import com.elmakers.mine.bukkit.entity.EntityData;
import com.elmakers.mine.bukkit.maps.BufferedMapCanvas;
import com.elmakers.mine.bukkit.utility.ConfigurationUtils;
public class MaterialBrush extends MaterialAndData implements com.elmakers.mine.bukkit.api.block.MaterialBrush {
public static final String ERASE_MATERIAL_KEY = "erase";
public static final String COPY_MATERIAL_KEY = "copy";
public static final String CLONE_MATERIAL_KEY = "clone";
public static final String REPLICATE_MATERIAL_KEY = "replicate";
public static final String MAP_MATERIAL_KEY = "map";
public static final String SCHEMATIC_MATERIAL_KEY = "schematic";
public static final int DEFAULT_MAP_SIZE = 16;
// This does not include schematics
public static final String[] SPECIAL_MATERIAL_KEYS = {ERASE_MATERIAL_KEY, COPY_MATERIAL_KEY,
CLONE_MATERIAL_KEY, REPLICATE_MATERIAL_KEY, MAP_MATERIAL_KEY};
public static Material EraseMaterial = Material.SULPHUR;
public static Material CopyMaterial = Material.SUGAR;
public static Material CloneMaterial = Material.NETHER_STALK;
public static Material ReplicateMaterial = Material.PUMPKIN_SEEDS;
public static Material MapMaterial = Material.MAP;
public static Material SchematicMaterial = Material.PAPER;
public static Material DefaultBrushMaterial = Material.SULPHUR;
public static String EraseCustomIcon;
public static String CopyCustomIcon;
public static String CloneCustomIcon;
public static String ReplicateCustomIcon;
public static String MapCustomIcon;
public static String SchematicCustomIcon;
public static String DefaultBrushCustomIcon;
public static final Material DEFAULT_MATERIAL = Material.DIRT;
private static final Map<MaterialAndData, MaterialAndData> replacements = new HashMap<MaterialAndData, MaterialAndData>();
private BrushMode mode = BrushMode.MATERIAL;
private Location cloneSource = null;
private Location cloneTarget = null;
private Location materialTarget = null;
private Vector targetOffset = null;
private String targetWorldName = null;
private final Mage mage;
private short mapId = -1;
private BufferedMapCanvas mapCanvas = null;
private Material mapMaterialBase = Material.STAINED_CLAY;
private Schematic schematic;
private String schematicName = "";
private boolean fillWithAir = true;
private Vector orientVector = null;
private double scale = 1;
public MaterialBrush(final Mage mage, final Material material, final byte data) {
super(material, data);
this.mage = mage;
}
public MaterialBrush(final Mage mage, final Location location, final String materialKey) {
super(DEFAULT_MATERIAL, (byte)0);
this.mage = mage;
update(materialKey);
activate(location, materialKey);
}
public MaterialBrush(final Mage mage, final Block block) {
super(block);
this.mage = mage;
}
public MaterialBrush(final String materialKey) {
super(DEFAULT_MATERIAL, (byte)0);
this.mage = null;
update(materialKey);
}
public String getKey() {
String materialKey = null;
if (mode == BrushMode.ERASE) {
materialKey = ERASE_MATERIAL_KEY;
} else if (mode == BrushMode.COPY) {
materialKey = COPY_MATERIAL_KEY;
} else if (mode == BrushMode.CLONE) {
materialKey = CLONE_MATERIAL_KEY;
} else if (mode == BrushMode.MAP) {
materialKey = MAP_MATERIAL_KEY;
int mapSize = (int)((float)128 / scale);
if (mapSize != DEFAULT_MAP_SIZE)
{
materialKey = materialKey + ":" + mapSize;
}
} else if (mode == BrushMode.REPLICATE) {
materialKey = REPLICATE_MATERIAL_KEY;
} else if (mode == BrushMode.SCHEMATIC) {
// This would be kinda broken.. might want to revisit all this.
// This method is only called by addMaterial at this point,
// which should only be called with real materials anyway.
materialKey = SCHEMATIC_MATERIAL_KEY + ":" + schematicName;
} else {
materialKey = super.getKey();
}
return materialKey;
}
public static boolean isSpecialMaterialKey(String materialKey) {
if (materialKey == null || materialKey.length() == 0) return false;
materialKey = splitMaterialKey(materialKey)[0];
return COPY_MATERIAL_KEY.equals(materialKey) || ERASE_MATERIAL_KEY.equals(materialKey) ||
REPLICATE_MATERIAL_KEY.equals(materialKey) || CLONE_MATERIAL_KEY.equals(materialKey) ||
MAP_MATERIAL_KEY.equals(materialKey) || SCHEMATIC_MATERIAL_KEY.equals(materialKey);
}
public static boolean isSchematic(String materialKey) {
if (materialKey == null || materialKey.length() == 0) return false;
materialKey = splitMaterialKey(materialKey)[0];
return SCHEMATIC_MATERIAL_KEY.equals(materialKey);
}
public static String getMaterialName(Messages messages, String materialKey) {
MaterialBrush brush = new MaterialBrush(materialKey);
return brush.getName(messages);
}
public String getName() {
Messages messages = mage != null ? mage.getController().getMessages() : null;
return getName(messages);
}
public String getName(Messages messages) {
String brushKey;
switch (mode) {
case ERASE:
brushKey = ERASE_MATERIAL_KEY;
if (messages != null) {
brushKey = messages.get("wand.erase_material_name");
}
break;
case CLONE:
brushKey = CLONE_MATERIAL_KEY;
if (messages != null) {
brushKey = messages.get("wand.clone_material_name");
}
break;
case REPLICATE:
brushKey = REPLICATE_MATERIAL_KEY;
if (messages != null) {
brushKey = messages.get("wand.replicate_material_name");
}
break;
case COPY:
brushKey = COPY_MATERIAL_KEY;
if (messages != null) {
brushKey = messages.get("wand.copy_material_name");
}
break;
case MAP:
brushKey = MAP_MATERIAL_KEY;
int mapSize = (int)((float)128 / scale);
if (mapSize != DEFAULT_MAP_SIZE)
{
if (messages != null) {
brushKey = messages.get("wand.map_material_name_scaled");
brushKey = brushKey.replace("$size", Integer.toString(mapSize));
} else {
brushKey = brushKey + " " + mapSize + "x" + mapSize;
}
} else if (messages != null) {
brushKey = messages.get("wand.map_material_name");
}
break;
case SCHEMATIC:
brushKey = schematicName;
brushKey = brushKey.toLowerCase().replace('_', ' ');
break;
default:
brushKey = super.getName(messages);
}
return brushKey;
}
public static MaterialBrush parseMaterialKey(String materialKey) {
return parseMaterialKey(materialKey, false);
}
public static MaterialBrush parseMaterialKey(String materialKey, boolean allowItems) {
if (materialKey == null || materialKey.length() == 0) return null;
MaterialBrush brush = new MaterialBrush(materialKey);
return brush.isValid(allowItems) ? brush : null;
}
public static boolean isValidMaterial(String materialKey, boolean allowItems) {
MaterialBrush brush = new MaterialBrush(materialKey);
return brush.isValid(allowItems);
}
public boolean isValid(boolean allowItems) {
if (!isValid()) return false;
if (mode != BrushMode.MATERIAL) return true;
return allowItems || material.isBlock();
}
@Override
public void setMaterial(Material material, Short data) {
if (material != null && material.isBlock() && (mage == null || !mage.isRestricted(material))) {
super.setMaterial(material, data);
isValid = true;
} else {
isValid = false;
}
fillWithAir = true;
}
public void enableCloning() {
if (this.mode != BrushMode.CLONE) {
fillWithAir = this.mode == BrushMode.ERASE;
this.mode = BrushMode.CLONE;
}
}
public void enableErase() {
if (this.mode != BrushMode.ERASE) {
this.setMaterial(Material.AIR);
this.mode = BrushMode.ERASE;
fillWithAir = true;
}
}
public void enableMap(int size) {
fillWithAir = false;
if (size <= 0) {
size = DEFAULT_MAP_SIZE;
}
this.scale = (float)128 / size;
this.mode = BrushMode.MAP;
if (this.material == Material.WOOL || this.material == Material.STAINED_CLAY
|| this.material == Material.STAINED_GLASS || this.material == Material.STAINED_GLASS_PANE
|| this.material == Material.CARPET) {
this.mapMaterialBase = this.material;
}
}
public void enableSchematic(String name) {
if (this.mode != BrushMode.SCHEMATIC) {
fillWithAir = this.mode == BrushMode.ERASE;
this.mode = BrushMode.SCHEMATIC;
}
this.schematicName = name;
schematic = null;
}
public void clearSchematic() {
schematic = null;
}
public void enableReplication() {
if (this.mode != BrushMode.REPLICATE) {
fillWithAir = this.mode == BrushMode.ERASE;
this.mode = BrushMode.REPLICATE;
}
}
public void setMapId(short mapId) {
this.mapCanvas = null;
this.mapId = mapId;
}
public void setCloneLocation(Location cloneFrom) {
cloneSource = cloneFrom;
materialTarget = cloneFrom;
cloneTarget = null;
}
public void clearCloneLocation() {
cloneSource = null;
materialTarget = null;
}
public void clearCloneTarget() {
cloneTarget = null;
targetOffset = null;
targetWorldName = null;
}
public void setTargetOffset(Vector offset, String worldName) {
targetOffset = offset.clone();
targetWorldName = worldName;
}
public boolean hasCloneTarget() {
return cloneSource != null && cloneTarget != null;
}
public void enableCopying() {
mode = BrushMode.COPY;
}
public boolean isReady() {
if ((mode == BrushMode.CLONE || mode == BrushMode.REPLICATE) && materialTarget != null) {
Block block = materialTarget.getBlock();
return (block.getChunk().isLoaded());
} else if (mode == BrushMode.SCHEMATIC) {
return checkSchematic();
}
return true;
}
public Location toTargetLocation(Location target) {
if (cloneSource == null || cloneTarget == null) return null;
Location translated = cloneSource.clone();
translated.subtract(cloneTarget.toVector());
translated.add(target.toVector());
return translated;
}
public Location fromTargetLocation(World targetWorld, Location target) {
if (cloneSource == null || cloneTarget == null) return null;
Location translated = target.clone();
translated.setX(translated.getBlockX());
translated.setY(translated.getBlockY());
translated.setZ(translated.getBlockZ());
Vector cloneVector = new Vector(cloneSource.getBlockX(), cloneSource.getBlockY(), cloneSource.getBlockZ());
translated.subtract(cloneVector);
Vector cloneTargetVector = new Vector(cloneTarget.getBlockX(), cloneTarget.getBlockY(), cloneTarget.getBlockZ());
translated.add(cloneTargetVector);
translated.setWorld(targetWorld);
return translated;
}
@SuppressWarnings("deprecation")
public boolean update(final Mage fromMage, final Location target) {
if (mode == BrushMode.CLONE || mode == BrushMode.REPLICATE) {
if (cloneSource == null) {
isValid = false;
return true;
}
if (cloneTarget == null) cloneTarget = target;
materialTarget = toTargetLocation(target);
if (materialTarget.getY() < 0 || materialTarget.getWorld() == null || materialTarget.getY() > materialTarget.getWorld().getMaxHeight()) {
isValid = false;
} else {
Block block = materialTarget.getBlock();
if (!block.getChunk().isLoaded()) return false;
updateFrom(block, fromMage.getRestrictedMaterials());
isValid = fillWithAir || material != Material.AIR;
}
}
if (mode == BrushMode.SCHEMATIC) {
if (!checkSchematic()) {
return true;
}
if (cloneTarget == null) {
isValid = false;
return true;
}
Vector diff = target.toVector().subtract(cloneTarget.toVector());
com.elmakers.mine.bukkit.api.block.MaterialAndData newMaterial = schematic.getBlock(diff);
if (newMaterial == null) {
isValid = false;
} else {
updateFrom(newMaterial);
isValid = fillWithAir || newMaterial.getMaterial() != Material.AIR;
}
}
if (mode == BrushMode.MAP && mapId >= 0) {
if (mapCanvas == null && fromMage != null) {
try {
MapView mapView = Bukkit.getMap(mapId);
if (mapView != null) {
Player player = fromMage.getPlayer();
List<MapRenderer> renderers = mapView.getRenderers();
if (renderers.size() > 0 && player != null) {
mapCanvas = new BufferedMapCanvas();
MapRenderer renderer = renderers.get(0);
// This is mainly here as a hack for my own urlmaps that do their own caching
// Bukkit *seems* to want to do caching at the MapView level, but looking at the code-
// they cache but never use the cache?
// Anyway render gets called constantly so I'm not re-rendering on each render... but then
// how to force a render to a canvas? So we re-initialize.
renderer.initialize(mapView);
renderer.render(mapView, mapCanvas, player);
}
}
} catch (Exception ex) {
}
}
isValid = false;
if (mapCanvas != null && cloneTarget != null) {
Vector diff = target.toVector().subtract(cloneTarget.toVector());
// TODO : Different orientations, centering, scaling, etc
// We default to 1/8 scaling for now to make the portraits work well.
DyeColor mapColor = DyeColor.WHITE;
if (orientVector.getBlockY() > orientVector.getBlockZ() || orientVector.getBlockY() > orientVector.getBlockX()) {
if (orientVector.getBlockX() > orientVector.getBlockZ()) {
mapColor = mapCanvas.getDyeColor(
Math.abs((int)(diff.getBlockX() * scale + BufferedMapCanvas.CANVAS_WIDTH / 2) % BufferedMapCanvas.CANVAS_WIDTH),
Math.abs((int)(-diff.getBlockY() * scale + BufferedMapCanvas.CANVAS_HEIGHT / 2) % BufferedMapCanvas.CANVAS_HEIGHT));
} else {
mapColor = mapCanvas.getDyeColor(
Math.abs((int)(diff.getBlockZ() * scale + BufferedMapCanvas.CANVAS_WIDTH / 2) % BufferedMapCanvas.CANVAS_WIDTH),
Math.abs((int)(-diff.getBlockY() * scale + BufferedMapCanvas.CANVAS_HEIGHT / 2) % BufferedMapCanvas.CANVAS_HEIGHT));
}
} else {
mapColor = mapCanvas.getDyeColor((int)(
Math.abs((int)(diff.getBlockX() * scale + BufferedMapCanvas.CANVAS_WIDTH / 2) % BufferedMapCanvas.CANVAS_WIDTH)),
Math.abs((int)(diff.getBlockZ() * scale + BufferedMapCanvas.CANVAS_HEIGHT / 2) % BufferedMapCanvas.CANVAS_HEIGHT));
}
if (mapColor != null) {
this.material = mapMaterialBase;
this.data = (short)mapColor.getData();
isValid = true;
}
}
}
return true;
}
protected boolean checkSchematic() {
if (schematic == null && mage != null) {
if (schematicName.length() == 0) {
isValid = false;
return false;
}
schematic = mage.getController().loadSchematic(schematicName);
if (schematic == null) {
schematicName = "";
isValid = false;
return false;
}
}
return schematic != null && schematic.isLoaded();
}
public void prepare() {
if (cloneSource != null) {
Block block = cloneTarget.getBlock();
if (!block.getChunk().isLoaded()) {
block.getChunk().load(true);
}
}
}
public void load(ConfigurationSection node)
{
try {
cloneSource = ConfigurationUtils.getLocation(node, "clone_location");
cloneTarget = ConfigurationUtils.getLocation(node, "clone_target");
materialTarget = ConfigurationUtils.getLocation(node, "material_target");
schematicName = node.getString("schematic", schematicName);
mapId = (short)node.getInt("map_id", mapId);
material = ConfigurationUtils.getMaterial(node, "material", material);
data = (short)node.getInt("data", data);
customName = node.getString("extra_data", customName);
scale = node.getDouble("scale", scale);
fillWithAir = node.getBoolean("erase", fillWithAir);
} catch (Exception ex) {
ex.printStackTrace();
if (mage != null) {
mage.getController().getLogger().warning("Failed to load brush data: " + ex.getMessage());
}
}
}
public void save(ConfigurationSection node)
{
try {
if (cloneSource != null) {
node.set("clone_location", ConfigurationUtils.fromLocation(cloneSource));
}
if (cloneTarget != null) {
node.set("clone_target", ConfigurationUtils.fromLocation(cloneTarget));
}
if (materialTarget != null) {
node.set("material_target", ConfigurationUtils.fromLocation(materialTarget));
}
node.set("map_id", (int)mapId);
node.set("material", ConfigurationUtils.fromMaterial(material));
node.set("data", data);
node.set("extra_data", customName);
node.set("schematic", schematicName);
node.set("scale", scale);
node.set("erase", fillWithAir);
} catch (Exception ex) {
ex.printStackTrace();
if (mage != null) {
mage.getController().getLogger().warning("Failed to save brush data: " + ex.getMessage());
}
}
}
@Override
public boolean hasEntities()
{
return mode == BrushMode.CLONE || mode == BrushMode.REPLICATE || mode == BrushMode.SCHEMATIC;
}
@Override
public Collection<Entity> getTargetEntities()
{
if (cloneTarget == null || mage == null) return null;
if (mode == BrushMode.CLONE || mode == BrushMode.REPLICATE || mode == BrushMode.SCHEMATIC)
{
List<Entity> targetData = new ArrayList<Entity>();
World targetWorld = cloneTarget.getWorld();
List<Entity> targetEntities = targetWorld.getEntities();
for (Entity entity : targetEntities) {
// Schematics currently only deal with Hanging entities
if (mode == BrushMode.SCHEMATIC && !(entity instanceof Hanging)) continue;
// Note that we ignore players and NPCs
if (!(entity instanceof Player) && !mage.getController().isNPC(entity)) {
targetData.add(entity);
}
}
return targetData;
}
return null;
}
@Override
public Collection<com.elmakers.mine.bukkit.api.entity.EntityData> getEntities()
{
if (cloneTarget == null) return null;
if ((mode == BrushMode.CLONE || mode == BrushMode.REPLICATE) && cloneSource != null)
{
List<com.elmakers.mine.bukkit.api.entity.EntityData> copyEntities = new ArrayList<com.elmakers.mine.bukkit.api.entity.EntityData>();
World sourceWorld = cloneSource.getWorld();
List<Entity> entities = sourceWorld.getEntities();
for (Entity entity : entities) {
if (!(entity instanceof Player || entity instanceof Item)) {
Location entityLocation = entity.getLocation();
Location translated = fromTargetLocation(cloneTarget.getWorld(), entityLocation);
EntityData entityData = new EntityData(translated, entity);
copyEntities.add(entityData);
}
}
return copyEntities;
}
else if (mode == BrushMode.SCHEMATIC)
{
if (schematic != null)
{
return schematic.getEntities(cloneTarget);
}
}
return null;
}
@Override
public void activate(final Location location, final String material) {
String materialKey = splitMaterialKey(material)[0];
if (materialKey.equals(CLONE_MATERIAL_KEY) || materialKey.equals(REPLICATE_MATERIAL_KEY) && location != null) {
Location cloneFrom = location.clone();
cloneFrom.setY(cloneFrom.getY() - 1);
setCloneLocation(cloneFrom);
} else if (materialKey.equals(MAP_MATERIAL_KEY) || materialKey.equals(SCHEMATIC_MATERIAL_KEY)) {
clearCloneTarget();
}
}
@Override
public void update(String activeMaterial) {
String pieces[] = splitMaterialKey(activeMaterial);
isValid = true;
if (activeMaterial.equals(COPY_MATERIAL_KEY)) {
enableCopying();
} else if (activeMaterial.equals(CLONE_MATERIAL_KEY)) {
enableCloning();
} else if (activeMaterial.equals(REPLICATE_MATERIAL_KEY)) {
enableReplication();
} else if (pieces[0].equals(MAP_MATERIAL_KEY)) {
int size = DEFAULT_MAP_SIZE;
if (pieces.length > 1) {
try {
size = Integer.parseInt(pieces[1]);
} catch (Exception ex) {
}
}
enableMap(size);
} else if (activeMaterial.equals(ERASE_MATERIAL_KEY)) {
enableErase();
} else if (pieces.length > 1 && pieces[0].equals(SCHEMATIC_MATERIAL_KEY)) {
enableSchematic(pieces[1]);
} else {
mode = BrushMode.MATERIAL;
super.update(activeMaterial);
}
}
@Override
public void setTarget(Location target) {
setTarget(target, target);
}
@Override
public void setTarget(Location target, Location center) {
if (target == null || center == null || mage == null) return;
orientVector = target.toVector().subtract(center.toVector());
orientVector.setX(Math.abs(orientVector.getX()));
orientVector.setY(Math.abs(orientVector.getY()));
orientVector.setZ(Math.abs(orientVector.getZ()));
if (mode == BrushMode.REPLICATE || mode == BrushMode.CLONE || mode == BrushMode.MAP || mode == BrushMode.SCHEMATIC) {
if (cloneTarget == null || mode == BrushMode.CLONE ||
!center.getWorld().getName().equals(cloneTarget.getWorld().getName())) {
cloneTarget = center;
if (targetOffset != null) {
cloneTarget = cloneTarget.add(targetOffset);
}
} else if (mode == BrushMode.SCHEMATIC) {
if (schematic == null && schematicName != null) {
schematic = mage.getController().loadSchematic(schematicName);
}
boolean recenter = true;
if (schematic != null && schematic.isLoaded()) {
Vector diff = target.toVector().subtract(cloneTarget.toVector());
recenter = (!schematic.contains(diff));
}
if (recenter) {
cloneTarget = center;
if (targetOffset != null) {
cloneTarget = cloneTarget.add(targetOffset);
}
}
}
cloneTarget.setX(cloneTarget.getBlockX());
cloneTarget.setY(cloneTarget.getBlockY());
cloneTarget.setZ(cloneTarget.getBlockZ());
if (cloneSource == null) {
cloneSource = cloneTarget.clone();
if (targetWorldName != null && targetWorldName.length() > 0) {
World sourceWorld = cloneSource.getWorld();
cloneSource.setWorld(ConfigurationUtils.overrideWorld(targetWorldName, sourceWorld, mage.getController().canCreateWorlds()));
}
}
if (materialTarget == null) {
materialTarget = cloneTarget;
}
}
if (mode == BrushMode.COPY) {
Block block = target.getBlock();
if (targetOffset != null) {
Location targetLocation = block.getLocation();
targetLocation = targetLocation.add(targetOffset);
block = targetLocation.getBlock();
}
updateFrom(block, mage.getRestrictedMaterials());
}
}
@Override
public Vector getSize() {
if (mode != BrushMode.SCHEMATIC) {
return new Vector(0, 0, 0);
}
if (!checkSchematic()) {
return new Vector(0, 0, 0);
}
return schematic.getSize();
}
@Override
public BrushMode getMode()
{
return mode;
}
@Override
public boolean isEraseModifierActive()
{
return fillWithAir;
}
@Override
public boolean isErase()
{
return mode == BrushMode.ERASE || material == Material.AIR;
}
public ItemStack getItem(MageController controller, boolean isItem) {
Messages messages = controller.getMessages();
MaterialAndData icon = new MaterialAndData(this.getMaterial(), this.getData());
String extraLore = null;
String customName = getName(messages);
ItemStack itemStack = null;
if (mode == BrushMode.ERASE) {
icon.setMaterial(MaterialBrush.EraseMaterial);
if (EraseCustomIcon != null && !EraseCustomIcon.isEmpty() && controller.isUrlIconsEnabled()) {
itemStack = InventoryUtils.getURLSkull(EraseCustomIcon);
}
extraLore = messages.get("wand.erase_material_description");
} else if (mode == BrushMode.COPY) {
icon.setMaterial(MaterialBrush.CopyMaterial);
if (CopyCustomIcon != null && !CopyCustomIcon.isEmpty() && controller.isUrlIconsEnabled()) {
itemStack = InventoryUtils.getURLSkull(CopyCustomIcon);
}
extraLore = messages.get("wand.copy_material_description");
} else if (mode == BrushMode.CLONE) {
icon.setMaterial(MaterialBrush.CloneMaterial);
if (CloneCustomIcon != null && !CloneCustomIcon.isEmpty() && controller.isUrlIconsEnabled()) {
itemStack = InventoryUtils.getURLSkull(CloneCustomIcon);
}
extraLore = messages.get("wand.clone_material_description");
} else if (mode == BrushMode.REPLICATE) {
icon.setMaterial(MaterialBrush.ReplicateMaterial);
if (ReplicateCustomIcon != null && !ReplicateCustomIcon.isEmpty() && controller.isUrlIconsEnabled()) {
itemStack = InventoryUtils.getURLSkull(ReplicateCustomIcon);
}
extraLore = messages.get("wand.replicate_material_description");
} else if (mode == BrushMode.MAP) {
icon.setMaterial(MaterialBrush.MapMaterial);
if (MapCustomIcon != null && !MapCustomIcon.isEmpty() && controller.isUrlIconsEnabled()) {
itemStack = InventoryUtils.getURLSkull(MapCustomIcon);
}
extraLore = messages.get("wand.map_material_description");
} else if (mode == BrushMode.SCHEMATIC) {
icon.setMaterial(MaterialBrush.SchematicMaterial);
if (SchematicCustomIcon != null && !SchematicCustomIcon.isEmpty() && controller.isUrlIconsEnabled()) {
itemStack = InventoryUtils.getURLSkull(SchematicCustomIcon);
}
extraLore = messages.get("wand.schematic_material_description").replace("$schematic", schematicName);
} else {
MaterialAndData replacementMaterial = replacements.get(icon);
if (replacementMaterial != null) {
icon = replacementMaterial;
}
extraLore = messages.get("wand.building_material_description").replace("$material", customName);
}
if (itemStack == null) {
itemStack = icon.getItemStack(1);
itemStack = InventoryUtils.makeReal(itemStack);
if (itemStack == null) {
if (DefaultBrushCustomIcon != null && !DefaultBrushCustomIcon.isEmpty() && controller.isUrlIconsEnabled()) {
itemStack = InventoryUtils.getURLSkull(DefaultBrushCustomIcon);
}
if (itemStack == null) {
itemStack = new ItemStack(DefaultBrushMaterial, 1);
itemStack = InventoryUtils.makeReal(itemStack);
if (itemStack == null) {
return itemStack;
}
}
}
}
ItemMeta meta = itemStack.getItemMeta();
List<String> lore = new ArrayList<String>();
if (extraLore != null) {
lore.add(ChatColor.LIGHT_PURPLE + extraLore);
}
if (isItem) {
lore.add(ChatColor.YELLOW + messages.get("wand.brush_item_description"));
}
meta.setLore(lore);
if (customName != null) {
meta.setDisplayName(customName);
}
itemStack.setItemMeta(meta);
return itemStack;
}
public static void configureReplacements(ConfigurationSection replacementConfig) {
replacements.clear();
if (replacementConfig == null) return;
Set<String> keys = replacementConfig.getKeys(false);
for (String key : keys) {
MaterialAndData toMaterial = ConfigurationUtils.getMaterialAndData(replacementConfig, key);
MaterialAndData fromMaterial = ConfigurationUtils.toMaterialAndData(key);
replacements.put(fromMaterial, toMaterial);
}
}
@Override
public String toString() {
return mode + ": " + super.toString();
}
}
|
package com.ezardlabs.lostsector.missions;
import com.ezardlabs.dethsquare.GameObject;
import com.ezardlabs.dethsquare.Level;
import com.ezardlabs.dethsquare.LevelManager;
import com.ezardlabs.dethsquare.Script;
import com.ezardlabs.dethsquare.Vector2;
import com.ezardlabs.dethsquare.prefabs.PrefabManager;
import com.ezardlabs.lostsector.levels.MissionLevel;
import java.util.LinkedHashMap;
import java.util.Map.Entry;
import java.util.concurrent.ThreadLocalRandom;
public class SpawnPoint extends Script {
private static SpawnMode mode = SpawnMode.SINGLE;
private static int maxEnemies = 0;
private static int numEnemies = 0;
private static long minInterval = 0;
private static long maxInterval = 0;
private static LinkedHashMap<String, Float> spawnProbabilities;
private long nextSpawn = 0;
private Mission mission;
private enum SpawnMode {
SINGLE,
CONTINUOUS,
WAVE
}
@Override
public void start() {
Level level = LevelManager.getCurrentLevel();
if (level instanceof MissionLevel) {
mission = ((MissionLevel) level).getMission();
}
}
@Override
public void update() {
if (System.currentTimeMillis() > nextSpawn) {
switch (mode) {
case SINGLE:
if (numEnemies < maxEnemies) {
spawnEnemy(transform.position);
numEnemies++;
}
break;
case CONTINUOUS:
if (mission == null || mission.numEnemies < maxEnemies) {
spawnEnemy(transform.position);
}
break;
case WAVE:
if (numEnemies < maxEnemies) {
spawnEnemy(transform.position);
numEnemies++;
}
break;
default:
break;
}
nextSpawn = System.currentTimeMillis() + ThreadLocalRandom.current().nextLong(minInterval, maxInterval + 1);
}
}
private static void spawnEnemy(Vector2 position) {
String enemyPrefab = getSpawn();
if (enemyPrefab != null) {
GameObject.instantiate(PrefabManager.loadPrefab(getSpawn()), position);
}
}
private static String getSpawn() {
double rand = Math.random();
float total = 0;
for (Entry<String, Float> entry : spawnProbabilities.entrySet()) {
if (rand < entry.getValue() + total) {
return entry.getKey();
} else {
total += entry.getValue();
}
}
return null;
}
public static void setSingleSpawnMode(int numEnemies, long minInterval, long maxInterval,
LinkedHashMap<String, Float> spawnProbabilities) {
SpawnPoint.mode = SpawnMode.SINGLE;
SpawnPoint.maxEnemies = numEnemies;
SpawnPoint.numEnemies = 0;
SpawnPoint.minInterval = minInterval;
SpawnPoint.maxInterval = maxInterval;
SpawnPoint.spawnProbabilities = spawnProbabilities;
}
public static void setContinuousSpawnMode(int maxEnemies, long minInterval, long maxInterval,
LinkedHashMap<String, Float> spawnProbabilities) {
SpawnPoint.mode = SpawnMode.CONTINUOUS;
SpawnPoint.maxEnemies = maxEnemies;
SpawnPoint.numEnemies = 0;
SpawnPoint.minInterval = minInterval;
SpawnPoint.maxInterval = maxInterval;
SpawnPoint.spawnProbabilities = spawnProbabilities;
}
public static void setWaveSpawnMode(long minInterval, long maxInterval) {
SpawnPoint.mode = SpawnMode.WAVE;
SpawnPoint.minInterval = minInterval;
SpawnPoint.maxInterval = maxInterval;
}
public static void spawnWave(int numEnemies, LinkedHashMap<String, Float> spawnProbabilities) {
SpawnPoint.maxEnemies = numEnemies;
SpawnPoint.numEnemies = 0;
SpawnPoint.spawnProbabilities = spawnProbabilities;
}
}
|
package com.github.onsdigital.json.markdown;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import com.github.onsdigital.generator.Folder;
import com.github.onsdigital.json.ContentType;
import com.github.onsdigital.json.collection.CollectionItem;
import com.github.onsdigital.json.partial.Email;
import com.github.onsdigital.json.taxonomy.TaxonomyHome;
public class Bulletin extends CollectionItem {
// Top section
public String nextRelease = "21 November 2014";
public Email contact = new Email();
// Exec summary
public String lede = "Producer Price Inflation (PPI) measures the price changes of goods bought and sold by UK manufacturers this month compared to the same month a year ago. PPI provides a key measure of inflation alongside other indicators such as the Consumer Prices Index (CPI) and Services Producer Price Index (SPPI)."
+ "PPI is split into two components: output price inflation and input price inflation. The input price indices capture changes in the cost of the material and fuel inputs that producers face whereas the output price indices capture the changing prices of goods sold by producers."
+ "This article looks at the trends in both producer price indices since 2000 and which components contribute most towards changes in each price index in recent years.";
public String more = "Annual output and input price changes follow similar trends, but with the latter tending to have higher price growth1. In Figure 1, trends in producer price inflation can be split into three distinct periods: 2000 to 2005, 2005 to 2012 and 2012 to June 2014. Both indices experience greater variability within the second period of 2005 to 2012 than compared with the first and third period. From 2005 to 2012 the average growth rate was 2.9% for output price inflation and 8.1% for input price inflation. The largest peaks and troughs experienced for both indices throughout the time series shown below occurred in the second period of 2005 to 2012. Output price inflation rose to 8.9% in July 2008 while input price inflation rose to 34.8% in June 2008 and both fell to their lowest rates in July 2009: output price inflation falling by 1.6% and input price inflation falling by 14.8%.";
// Table of contents
public List<Section> sections = new ArrayList<Section>();
public List<Section> accordion = new ArrayList<Section>();
public URI uri;
public String headline1 = "Duis ut laoreet felis";
public String headline2 = "Morbi sed sem at magna";
public String headline3 = "Auctor gravida sed non enim";
public String summary = "Summary section";
// Used to help place bulletins in the taxonomy
public transient String theme;
public transient String level2;
public transient String level3;
/**
* Sets up some basic content.
*/
public Bulletin() {
type = ContentType.bulletin;
title = "Consumer Price Inflation, August 2014";
releaseDate = "19 August 2014";
}
public void setBreadcrumb(TaxonomyHome t3) {
breadcrumb = new ArrayList<>(t3.breadcrumb);
Folder folder = new Folder();
folder.name = t3.name;
TaxonomyHome extra = new TaxonomyHome(folder);
breadcrumb.add(extra);
}
}
|
package com.github.rschmitt.dynamicobject;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.WildcardType;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import static java.lang.String.format;
import static java.util.stream.Collectors.toList;
class Validation {
static <T extends DynamicObject<T>> void validateInstance(
Class<T> type,
Function<Method, Object> getter,
Function<Method, Object> rawGetter
) {
MethodObject<T> methodObject = new MethodObject<>();
methodObject.validate(type, getter, rawGetter);
Collection<Method> missingFields = methodObject.missingFields;
Map<Method, Class<?>> mismatchedFields = methodObject.mismatchedFields;
if (!missingFields.isEmpty() || !mismatchedFields.isEmpty())
throw new IllegalStateException(methodObject.getValidationErrorMessage());
}
static class MethodObject<T extends DynamicObject<T>> {
private final Collection<Method> missingFields = new LinkedHashSet<>();
private final Map<Method, Class<?>> mismatchedFields = new HashMap<>();
private Function<Method, Object> getter;
void validate(
Class<T> type,
Function<Method, Object> getter,
Function<Method, Object> rawGetter
) {
Collection<Method> fields = Reflection.fieldGetters(type);
this.getter = getter;
for (Method field : fields) {
try {
validateField(field);
} catch (ClassCastException | AssertionError cce) {
mismatchedFields.put(field, rawGetter.apply(field).getClass());
}
}
}
private void validateField(Method field) {
Object val = getter.apply(field);
if (Reflection.isRequired(field) && val == null)
missingFields.add(field);
if (val != null) {
Type genericReturnType = field.getGenericReturnType();
if (val instanceof Optional && ((Optional) val).isPresent()) {
genericReturnType = Reflection.getTypeArgument(genericReturnType, 0);
val = ((Optional) val).get();
}
Class<?> expectedType = Primitives.box(Reflection.getRawType(genericReturnType));
Class<?> actualType = val.getClass();
if (!expectedType.isAssignableFrom(actualType))
mismatchedFields.put(field, actualType);
if (val instanceof DynamicObject)
((DynamicObject) val).validate();
else if (val instanceof List || val instanceof Set)
validateCollection((Collection<?>) val, genericReturnType);
else if (val instanceof Map)
validateMap((Map<?, ?>) val, genericReturnType);
}
}
@SuppressWarnings("unchecked")
private void validateCollection(Collection<?> val, Type genericReturnType) {
if (val == null) return;
Class<?> baseCollectionType = Reflection.getRawType(genericReturnType);
if (!baseCollectionType.isAssignableFrom(val.getClass()))
throw new IllegalStateException(format("Wrong collection type: expected %s, got %s",
baseCollectionType.getSimpleName(), val.getClass().getSimpleName()));
if (genericReturnType instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType) genericReturnType;
List<Type> typeArgs = Arrays.asList(parameterizedType.getActualTypeArguments());
assert typeArgs.size() == 1;
Type typeArg = typeArgs.get(0);
checkTypeVariable(typeArg);
val.forEach(element -> checkElement(typeArg, element));
}
}
private void checkTypeVariable(Type typeArg) {
if (typeArg instanceof WildcardType)
throw new UnsupportedOperationException("Wildcard return types are not supported");
else if (typeArg instanceof ParameterizedType)
return;
else if (typeArg instanceof Class)
return;
else
throw new UnsupportedOperationException("Unknown generic type argument type: " + typeArg.getClass().getCanonicalName());
}
private void checkElement(Type elementType, Object element) {
if (elementType instanceof Class)
checkAtomicElement((Class<?>) elementType, element);
else
checkNestedElement(elementType, element);
}
private void checkAtomicElement(Class<?> expectedType, Object element) {
if (element != null) {
Class<?> actualType = element.getClass();
if (!expectedType.isAssignableFrom(actualType))
throw new IllegalStateException(format("Expected collection element of type %s, got %s",
expectedType.getCanonicalName(),
actualType.getCanonicalName()));
if (element instanceof DynamicObject)
((DynamicObject) element).validate();
}
}
private void checkNestedElement(Type elementType, Object element) {
Class<?> rawType = Reflection.getRawType(elementType);
if (List.class.isAssignableFrom(rawType) || Set.class.isAssignableFrom(rawType))
validateCollection((Collection<?>) element, elementType);
else if (Map.class.isAssignableFrom(rawType))
validateMap((Map<?, ?>) element, elementType);
else
throw new UnsupportedOperationException("Unsupported base type " + rawType.getCanonicalName());
}
private void validateMap(Map<?, ?> map, Type genericReturnType) {
if (map == null) return;
if (genericReturnType instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType) genericReturnType;
List<Type> typeArgs = Arrays.asList(parameterizedType.getActualTypeArguments());
assert typeArgs.size() == 2;
typeArgs.forEach(this::checkTypeVariable);
Type keyType = typeArgs.get(0);
Type valType = typeArgs.get(1);
map.keySet().forEach(k -> checkElement(keyType, k));
map.values().forEach(v -> checkElement(valType, v));
}
}
String getValidationErrorMessage() {
StringBuilder ret = new StringBuilder();
if (!missingFields.isEmpty()) {
ret.append("The following @Required fields were missing: ");
List<String> fieldNames = missingFields.stream().map(Method::getName).collect(toList());
for (int i = 0; i < fieldNames.size(); i++) {
ret.append(fieldNames.get(i));
if (i != fieldNames.size() - 1)
ret.append(", ");
}
ret.append("\n");
}
if (!mismatchedFields.isEmpty()) {
ret.append("The following fields had the wrong type:\n");
for (Map.Entry<Method, Class<?>> methodClassEntry : mismatchedFields.entrySet()) {
Method method = methodClassEntry.getKey();
String name = method.getName();
String expected = method.getReturnType().getSimpleName();
String actual = methodClassEntry.getValue().getSimpleName();
ret.append(format("\t%s (expected %s, got %s)%n", name, expected, actual));
}
}
return ret.toString();
}
}
}
|
package com.github.slidekb.front;
import java.awt.AWTException;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import com.github.slidekb.api.SlideBarPlugin;
import com.github.slidekb.back.MainBack;
import com.github.slidekb.back.settings.GlobalSettings;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import javax.swing.JScrollPane;
import javax.swing.JEditorPane;
import javax.swing.JList;
import javax.swing.JLabel;
import java.awt.Font;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.Toolkit;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import javax.swing.JCheckBox;
import javax.swing.JButton;
public class PluginConfiguration {
private static JFrame frame;
private static JPanel contentPane;
private static GlobalSettings settings;
private static ArrayList<String> arrayProcess = new ArrayList<String>();
private static JList<String> processList = new JList<>();
/**
* Create the frame.
*/
public static void createAndShowGUI() {
if (frame == null) {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(100, 100, 839, 546);
frame.setPreferredSize(new Dimension(839, 546));
frame.setMinimumSize(new Dimension(839, 546));
frame.setMaximumSize(new Dimension(839, 546));
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
frame.setContentPane(contentPane);
contentPane.setLayout(null);
ArrayList<String> arrayPlugins = new ArrayList<String>();
for (SlideBarPlugin p : MainBack.PM.getProci()) {
arrayPlugins.add(p.getLabelName());
}
String plugins[] = arrayPlugins.toArray(new String[arrayPlugins.size()]);
JList<String> pluginList = new JList<>(plugins);
MouseListener mouseListener = new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 1) {
int selected[] = pluginList.getSelectedIndices();
System.out.println("Selected Elements: ");
for (int i = 0; i < selected.length; i++) {
String element = (String) pluginList.getModel().getElementAt(selected[i]);
ArrayList<SlideBarPlugin> temp = MainBack.PM.getProci();
arrayProcess.clear();
for (SlideBarPlugin p : temp) {
if (p.getLabelName().contentEquals(element)) {
System.out.println(p.getLabelName());
System.out.println(p.getClass().getCanonicalName());
try {
for (String processName : settings.getPlugins().get(p.getClass().getCanonicalName()).getProcesses()) {
arrayProcess.add(processName);
}
} catch (Exception e1) {
System.out.println("somthing went wrong");
}
String proci[] = arrayProcess.toArray(new String[arrayProcess.size()]);
processList.setListData(proci);
frame.revalidate();
frame.repaint();
}
}
}
}
}
};
pluginList.addMouseListener(mouseListener);
pluginList.setBounds(10, 44, 313, 452);
contentPane.add(pluginList);
JLabel lblPluginsLoaded = new JLabel("Plugins Loaded");
lblPluginsLoaded.setFont(new Font("Tahoma", Font.PLAIN, 18));
lblPluginsLoaded.setBounds(10, 11, 130, 22);
contentPane.add(lblPluginsLoaded);
JLabel lblProcesses = new JLabel("Processes");
lblProcesses.setFont(new Font("Tahoma", Font.PLAIN, 18));
lblProcesses.setBounds(333, 11, 130, 22);
contentPane.add(lblProcesses);
JLabel lblHotkeys = new JLabel("Hotkeys");
lblHotkeys.setFont(new Font("Tahoma", Font.PLAIN, 18));
lblHotkeys.setBounds(333, 223, 130, 22);
contentPane.add(lblHotkeys);
JCheckBox chckbxAlwaysRun = new JCheckBox("Always Run");
chckbxAlwaysRun.setBounds(329, 425, 97, 23);
contentPane.add(chckbxAlwaysRun);
processList.setBounds(333, 44, 425, 162);
contentPane.add(processList);
JList<String> hotkeyList = new JList<>();
hotkeyList.setBounds(333, 256, 425, 162);
contentPane.add(hotkeyList);
JButton processAddButton = new JButton("+");
processAddButton.setBounds(768, 44, 45, 22);
contentPane.add(processAddButton);
JButton processMinusButton = new JButton("-");
processMinusButton.setBounds(768, 77, 45, 22);
contentPane.add(processMinusButton);
JButton hotkeyMinusButton = new JButton("-");
hotkeyMinusButton.setBounds(768, 289, 45, 22);
contentPane.add(hotkeyMinusButton);
JButton hotkeyAddButton = new JButton("+");
hotkeyAddButton.setBounds(768, 256, 45, 22);
contentPane.add(hotkeyAddButton);
}
// Display the window.
frame.pack();
bringToFront();
}
private static void bringToFront() {
getInstance().setVisible(true);
getInstance().setExtendedState(JFrame.NORMAL);
getInstance().toFront();
getInstance().repaint();
}
private static JFrame getInstance() {
return frame;
}
/**
* Popup Menu
*
* @return
*/
protected static PopupMenu createPopupMenu() {
final PopupMenu popup = new PopupMenu();
MenuItem aboutItem = new MenuItem("Open Configuration");
aboutItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
createAndShowGUI();
}
});
MenuItem about = new MenuItem("About");
MenuItem website = new MenuItem("Website");
MenuItem reload = new MenuItem("Reload");
MenuItem exitItem = new MenuItem("Exit");
exitItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
// Add components to pop-up menu
popup.add(aboutItem);
popup.addSeparator();
popup.add(about);
popup.add(website);
popup.add(reload);
popup.addSeparator();
popup.add(exitItem);
return popup;
}
private static void setupTray() {
try {
// Check the SystemTray is supported
if (!SystemTray.isSupported()) {
System.out.println("SystemTray is not supported");
return;
}
final TrayIcon trayIcon = new TrayIcon(Toolkit.getDefaultToolkit().getImage(new URL("http://home.comcast.net/~supportcd/Icons/Java_Required.jpg")), "Library Drop");
final SystemTray tray = SystemTray.getSystemTray();
// Create a pop-up menu components
final PopupMenu popup = createPopupMenu();
trayIcon.setPopupMenu(popup);
trayIcon.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON1) {
createAndShowGUI();
}
}
});
tray.add(trayIcon);
} catch (AWTException e) {
System.out.println("TrayIcon could not be added.");
} catch (MalformedURLException e) {
System.out.println("Malformed Exception");
}
}
public static void main(String[] args) throws InterruptedException {
Thread back = new Thread(new MainBack());
back.start();
MainBack.PM.waitUntilProcessesLoaded();
settings = MainBack.getSettings();
createAndShowGUI();
setupTray();
}
static class SlideListener implements ChangeListener {
SlideListener() {
}
public synchronized void stateChanged(ChangeEvent e) {
}
}
}
|
package com.gh4a.fragment;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import com.gh4a.BaseActivity;
import com.gh4a.R;
import com.gh4a.utils.RxUtils;
import com.gh4a.utils.UiUtils;
import com.gh4a.widget.SwipeRefreshLayout;
import com.philosophicalhacker.lib.RxLoader;
import fr.castorflex.android.smoothprogressbar.SmoothProgressBar;
import io.reactivex.SingleTransformer;
public abstract class LoadingFragmentBase extends Fragment implements
BaseActivity.RefreshableChild, SwipeRefreshLayout.ChildScrollDelegate {
private ViewGroup mContentContainer;
private View mContentView;
private SmoothProgressBar mProgress;
private final int[] mProgressColors = new int[2];
private boolean mContentShown = true;
private RxLoader mRxLoader;
public LoadingFragmentBase() {
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
mRxLoader = new RxLoader(context, getLoaderManager());
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.loading_fragment, container, false);
mContentContainer = view.findViewById(R.id.content_container);
mContentView = onCreateContentView(inflater, mContentContainer);
mContentContainer.addView(mContentView);
return view;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mProgress = view.findViewById(R.id.progress);
mProgressColors[0] = UiUtils.resolveColor(mProgress.getContext(), R.attr.colorPrimary);
mProgressColors[1] = UiUtils.resolveColor(mProgress.getContext(), R.attr.colorPrimaryDark);
mProgress.setSmoothProgressDrawableColors(mProgressColors);
updateContentVisibility();
}
@Override
public void onDestroyView() {
super.onDestroyView();
mContentContainer = null;
mProgress = null;
mProgress = null;
}
@Override
public boolean canChildScrollUp() {
return UiUtils.canViewScrollUp(mContentView);
}
protected BaseActivity getBaseActivity() {
return (BaseActivity) getActivity();
}
protected <T> SingleTransformer<T, T> makeLoaderSingle(int id, boolean force) {
return upstream -> upstream
.compose(RxUtils::doInBackground)
.doOnError(error -> getBaseActivity().handleLoadFailure(error))
.compose(mRxLoader.makeSingleTransformer(id, force));
}
protected void setHighlightColors(int colorAttrId, int statusBarColorAttrId) {
mProgressColors[0] = UiUtils.resolveColor(getActivity(), colorAttrId);
mProgressColors[1] = UiUtils.resolveColor(getActivity(), statusBarColorAttrId);
if (mProgress != null) {
mProgress.invalidate();
}
}
protected int getHighlightColor() {
return mProgressColors[0];
}
protected boolean isContentShown() {
return mContentShown;
}
protected void setContentShown(boolean shown) {
if (mContentShown != shown) {
mContentShown = shown;
if (mContentContainer != null) {
updateContentVisibility();
}
}
}
private void updateContentVisibility() {
View out = mContentShown ? mProgress : mContentContainer;
View in = mContentShown ? mContentContainer : mProgress;
if (isResumed()) {
out.startAnimation(AnimationUtils.loadAnimation(getActivity(), android.R.anim.fade_out));
in.startAnimation(AnimationUtils.loadAnimation(getActivity(), android.R.anim.fade_in));
} else {
in.clearAnimation();
out.clearAnimation();
}
out.setVisibility(View.GONE);
in.setVisibility(View.VISIBLE);
}
protected abstract View onCreateContentView(LayoutInflater inflater, ViewGroup parent);
public boolean onBackPressed() {
return false;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.