answer
stringlengths
17
10.2M
package org.datavaultplatform.broker.controllers; import com.fasterxml.jackson.databind.ObjectMapper; import org.datavaultplatform.broker.queue.Sender; import org.datavaultplatform.broker.services.*; import org.datavaultplatform.common.event.Event; import org.datavaultplatform.common.model.*; import org.datavaultplatform.common.request.CreateDeposit; import org.datavaultplatform.common.response.DepositInfo; import org.datavaultplatform.common.response.EventInfo; import org.datavaultplatform.common.task.Task; import org.jsondoc.core.annotation.Api; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @RestController @Api(name="Deposits", description = "Interact with DataVault Deposits") public class DepositsController { private VaultsService vaultsService; private DepositsService depositsService; private ArchivesService archivesService; private RetrievesService retrievesService; private MetadataService metadataService; private ExternalMetadataService externalMetadataService; private FilesService filesService; private UsersService usersService; private ArchiveStoreService archiveStoreService; private JobsService jobsService; private Sender sender; private String optionsDir; private String tempDir; private String bucketName; private String region; private String awsAccessKey; private String awsSecretKey; private static final Logger logger = LoggerFactory.getLogger(DepositsController.class); public void setVaultsService(VaultsService vaultsService) { this.vaultsService = vaultsService; } public void setDepositsService(DepositsService depositsService) { this.depositsService = depositsService; } public void setArchivesService(ArchivesService archivesService) { this.archivesService = archivesService; } public void setRetrievesService(RetrievesService retrievesService) { this.retrievesService = retrievesService; } public void setMetadataService(MetadataService metadataService) { this.metadataService = metadataService; } public void setExternalMetadataService(ExternalMetadataService externalMetadataService) { this.externalMetadataService = externalMetadataService; } public void setFilesService(FilesService filesService) { this.filesService = filesService; } public void setArchiveStoreService(ArchiveStoreService archiveStoreService) { this.archiveStoreService = archiveStoreService; } public void setUsersService(UsersService usersService) { this.usersService = usersService; } public void setJobsService(JobsService jobsService) { this.jobsService = jobsService; } public void setSender(Sender sender) { this.sender = sender; } public void setTempDir(String tempDir) { this.tempDir = tempDir; } public void setOptionsDir(String optionsDir) { this.optionsDir = optionsDir; } public void setBucketName(String bucketName) { this.bucketName = bucketName; } public void setRegion(String region) { this.region = region; } public void setAwsAccessKey(String awsAccessKey) { this.awsAccessKey = awsAccessKey; } public void setAwsSecretKey(String awsSecretKey) { this.awsSecretKey = awsSecretKey; } @RequestMapping(value = "/deposits/{depositid}", method = RequestMethod.GET) public DepositInfo getDeposit(@RequestHeader(value = "X-UserID", required = true) String userID, @PathVariable("depositid") String depositID) throws Exception { User user = usersService.getUser(userID); return depositsService.getUserDeposit(user, depositID).convertToResponse(); } @RequestMapping(value = "/deposits", method = RequestMethod.POST) public ResponseEntity<Object> addDeposit(@RequestHeader(value = "X-UserID", required = true) String userID, @RequestBody CreateDeposit createDeposit) throws Exception { Deposit deposit = new Deposit(); User user = usersService.getUser(userID); Vault vault = vaultsService.getUserVault(user, createDeposit.getVaultID()); deposit.setName(createDeposit.getName()); deposit.setDescription(createDeposit.getDescription()); if (createDeposit.getHasPersonalData().toLowerCase().equals("yes")) { deposit.setHasPersonalData(true); } else { deposit.setHasPersonalData(false); } deposit.setPersonalDataStatement(createDeposit.getPersonalDataStatement()); deposit.setDepositPaths(new ArrayList<DepositPath>()); System.out.println("Deposit File Path: "); for (DepositPath dPath : deposit.getDepositPaths()){ System.out.println("\t- " + dPath.getFilePath()); } if (user == null) { throw new Exception("User '" + userID + "' does not exist"); } deposit.setUser(user); // Add the file upload path DepositPath fileUploadPath = new DepositPath(deposit, createDeposit.getFileUploadHandle(), Path.PathType.USER_UPLOAD); deposit.getDepositPaths().add(fileUploadPath); List<ArchiveStore> archiveStores = archiveStoreService.getArchiveStores(); if (archiveStores.size() == 0) { throw new Exception("No configured archive storage"); } archiveStores = this.addArchiveSpecificOptions(archiveStores); // Get metadata content from the external provider (bypass database cache) String externalMetadata = externalMetadataService.getDatasetContent(vault.getDataset().getID()); System.out.println("Deposit File Path: "); for (DepositPath dPath : deposit.getDepositPaths()){ System.out.println("\t- " + dPath.getFilePath()); } // Add the deposit object depositsService.addDeposit(vault, deposit, "", ""); this.runDeposit(deposit, createDeposit.getDepositPaths(), null); // Check the retention policy of the newly created vault vaultsService.checkRetentionPolicy(vault.getID()); return new ResponseEntity<>(deposit.convertToResponse(), HttpStatus.OK); } @RequestMapping(value = "/deposits/{depositid}/manifest", method = RequestMethod.GET) public List<FileFixity> getDepositManifest(@RequestHeader(value = "X-UserID", required = true) String userID, @PathVariable("depositid") String depositID) throws Exception { User user = usersService.getUser(userID); Deposit deposit = depositsService.getUserDeposit(user, depositID); List<FileFixity> manifest = new ArrayList<>(); if (deposit.getStatus() == Deposit.Status.COMPLETE) { manifest = metadataService.getManifest(deposit.getBagId()); } return manifest; } @RequestMapping(value = "/deposits/{depositid}/events", method = RequestMethod.GET) public List<EventInfo> getDepositEvents(@RequestHeader(value = "X-UserID", required = true) String userID, @PathVariable("depositid") String depositID) throws Exception { User user = usersService.getUser(userID); Deposit deposit = depositsService.getUserDeposit(user, depositID); List<EventInfo> events = new ArrayList<>(); for (Event event : deposit.getEvents()) { events.add(event.convertToResponse()); } return events; } @RequestMapping(value = "/deposits/{depositid}/retrieves", method = RequestMethod.GET) public List<Retrieve> getDepositRetrieves(@RequestHeader(value = "X-UserID", required = true) String userID, @PathVariable("depositid") String depositID) throws Exception { User user = usersService.getUser(userID); Deposit deposit = depositsService.getUserDeposit(user, depositID); List<Retrieve> retrieves = deposit.getRetrieves(); return retrieves; } @RequestMapping(value = "/deposits/{depositid}/jobs", method = RequestMethod.GET) public List<Job> getDepositJobs(@RequestHeader(value = "X-UserID", required = true) String userID, @PathVariable("depositid") String depositID) throws Exception { User user = usersService.getUser(userID); Deposit deposit = depositsService.getUserDeposit(user, depositID); List<Job> jobs = deposit.getJobs(); return jobs; } @RequestMapping(value = "/deposits/{depositid}/retrieve", method = RequestMethod.POST) public Boolean retrieveDeposit(@RequestHeader(value = "X-UserID", required = true) String userID, @PathVariable("depositid") String depositID, @RequestBody Retrieve retrieve) throws Exception { User user = usersService.getUser(userID); Deposit deposit = depositsService.getUserDeposit(user, depositID); if (user == null) { throw new Exception("User '" + userID + "' does not exist"); } retrieve.setUser(user); List<Job> jobs = deposit.getJobs(); for (Job job : jobs) { if (job.isError() == false && job.getState() != job.getStates().size() - 1) { // There's an in-progress job for this deposit throw new IllegalArgumentException("Job in-progress for this Deposit"); } } String fullPath = retrieve.getRetrievePath(); String storageID, retrievePath; if (!fullPath.contains("/")) { // A request to retrieve the whole share/device storageID = fullPath; retrievePath = "/"; } else { // A request to retrieve a sub-directory storageID = fullPath.substring(0, fullPath.indexOf("/")); retrievePath = fullPath.replaceFirst(storageID + "/", ""); } // Fetch the ArchiveStore that is flagged for retrieval. We store it in a list as the Task parameters require a list. ArchiveStore archiveStore = archiveStoreService.getForRetrieval(); List<ArchiveStore> archiveStores = new ArrayList<ArchiveStore>(); archiveStores.add(archiveStore); archiveStores = this.addArchiveSpecificOptions(archiveStores); // Find the Archive that matches the ArchiveStore. String archiveID = null; for (Archive archive : deposit.getArchives()) { if (archive.getArchiveStore().getID().equals(archiveStore.getID())) { archiveID = archive.getArchiveId(); } } // Worth checking that we found a matching Archive for the ArchiveStore. if (archiveID == null) { throw new Exception("No valid archive for retrieval"); } FileStore userStore = null; List<FileStore> userStores = user.getFileStores(); for (FileStore store : userStores) { if (store.getID().equals(storageID)) { userStore = store; } } if (userStore == null) { throw new IllegalArgumentException("Storage ID '" + storageID + "' is invalid"); } // Validate the path if (retrievePath == null) { throw new IllegalArgumentException("Path was null"); } // Check the source file path is valid if (!filesService.validPath(retrievePath, userStore)) { throw new IllegalArgumentException("Path '" + retrievePath + "' is invalid"); } // Create a job to track this retrieve Job job = new Job("org.datavaultplatform.worker.tasks.Retrieve"); jobsService.addJob(deposit, job); // Add the retrieve object retrievesService.addRetrieve(retrieve, deposit, retrievePath); // Ask the worker to process the data retrieve try { HashMap<String, String> retrieveProperties = new HashMap<>(); retrieveProperties.put("depositId", deposit.getID()); retrieveProperties.put("retrieveId", retrieve.getID()); retrieveProperties.put("bagId", deposit.getBagId()); retrieveProperties.put("retrievePath", retrievePath); // No longer the absolute path retrieveProperties.put("archiveId", archiveID); retrieveProperties.put("archiveSize", Long.toString(deposit.getArchiveSize())); retrieveProperties.put("userId", user.getID()); retrieveProperties.put("archiveDigest", deposit.getArchiveDigest()); retrieveProperties.put("archiveDigestAlgorithm", deposit.getArchiveDigestAlgorithm()); retrieveProperties.put("numOfChunks", Integer.toString(deposit.getNumOfChunks())); // Add a single entry for the user file storage Map<String, String> userFileStoreClasses = new HashMap<>(); Map<String, Map<String, String>> userFileStoreProperties = new HashMap<>(); userFileStoreClasses.put(storageID, userStore.getStorageClass()); userFileStoreProperties.put(storageID, userStore.getProperties()); // get chunks checksums HashMap<Integer, String> chunksDigest = new HashMap<Integer, String>(); List<DepositChunk> depositChunks = deposit.getDepositChunks(); for (DepositChunk depositChunk : depositChunks) { chunksDigest.put(depositChunk.getChunkNum(), depositChunk.getArchiveDigest()); } // Get encryption IVs byte[] tarIVs = deposit.getEncIV(); HashMap<Integer, byte[]> chunksIVs = new HashMap<Integer, byte[]>(); for( DepositChunk chunks : deposit.getDepositChunks() ) { chunksIVs.put(chunks.getChunkNum(), chunks.getEncIV()); } // Get encrypted digests String encTarDigest = deposit.getEncArchiveDigest(); HashMap<Integer, String> encChunksDigests = new HashMap<Integer, String>(); for( DepositChunk chunks : deposit.getDepositChunks() ) { encChunksDigests.put(chunks.getChunkNum(), chunks.getEcnArchiveDigest()); } Task retrieveTask = new Task( job, retrieveProperties, archiveStores, userFileStoreProperties, userFileStoreClasses, null, null, chunksDigest, tarIVs, chunksIVs, encTarDigest, encChunksDigests, null); ObjectMapper mapper = new ObjectMapper(); String jsonRetrieve = mapper.writeValueAsString(retrieveTask); sender.send(jsonRetrieve); } catch (Exception e) { e.printStackTrace(); } // Check the retention policy of the newly created vault vaultsService.checkRetentionPolicy(deposit.getVault().getID()); return true; } private List<ArchiveStore> addArchiveSpecificOptions(List<ArchiveStore> archiveStores) { if (archiveStores != null && ! archiveStores.isEmpty()) { for (ArchiveStore archiveStore : archiveStores) { if (archiveStore.getStorageClass().equals("org.datavaultplatform.common.storage.impl.TivoliStorageManager")) { HashMap<String, String> asProps = archiveStore.getProperties(); if (this.optionsDir != null && ! this.optionsDir.equals("")) { asProps.put("optionsDir", this.optionsDir); } if (this.tempDir != null && ! this.tempDir.equals("")) { asProps.put("tempDir", this.tempDir); } archiveStore.setProperties(asProps); } if (archiveStore.getStorageClass().equals("org.datavaultplatform.common.storage.impl.S3Cloud")) { HashMap<String, String> asProps = archiveStore.getProperties(); if (this.bucketName != null && ! this.bucketName.equals("")) { asProps.put("s3.bucketName", this.bucketName); } if (this.region != null && ! this.region.equals("")) { asProps.put("s3.region", this.region); } if (this.awsAccessKey != null && ! this.awsAccessKey.equals("")) { asProps.put("s3.awsAccessKey", this.awsAccessKey); } if (this.awsSecretKey != null && ! this.awsSecretKey.equals("")) { asProps.put("s3.awsSecretKey", this.awsSecretKey); } //if (this.authDir != null && ! this.authDir.equals("")) { // asProps.put("authDir", this.authDir); archiveStore.setProperties(asProps); } } } return archiveStores; } @RequestMapping(value = "/deposits/{depositid}/restart", method = RequestMethod.POST) public Deposit restartDeposit(@RequestHeader(value = "X-UserID", required = true) String userID, @PathVariable("depositid") String depositID) throws Exception{ Deposit deposit; User user = usersService.getUser(userID); deposit = depositsService.getUserDeposit(user, depositID); if (user == null) { throw new Exception("User '" + userID + "' does not exist"); } else { if (!user.isAdmin()) { throw new Exception("Only an admin can restart a deposit"); } } if (deposit == null) { throw new Exception("Deposit '" + depositID + "' does not exist"); } List<FileStore> userStores = user.getFileStores(); System.out.println("There is " + userStores.size() + "user stores."); ArrayList<String> paths = new ArrayList<String>(); for(DepositPath dPath : deposit.getDepositPaths()){ if(dPath.getPathType() == Path.PathType.FILESTORE) { paths.add(dPath.getFilePath()); } } System.out.println("There is " + paths.size() + " deposit path"); // Get last Deposit Event Event lastEvent = deposit.getLastNotFailedEvent(); runDeposit(deposit, paths, lastEvent); return deposit; } private Job runDeposit(Deposit deposit, List<String> paths, Event lastEvent){ User user = deposit.getUser(); List<ArchiveStore> archiveStores = archiveStoreService.getArchiveStores(); Vault vault = deposit.getVault(); String externalMetadata = externalMetadataService.getDatasetContent(vault.getDataset().getID()); List<FileStore> userStores = user.getFileStores(); Map<String, String> userFileStoreClasses = new HashMap<>(); Map<String, Map<String, String>> userFileStoreProperties = new HashMap<>(); // Add any server-side filestore paths if (paths != null) { for (String path : paths) { String storageID, storagePath; if (!path.contains("/")) { // A request to archive the whole share/device storageID = path; storagePath = "/"; } else { // A request to archive a sub-directory storageID = path.substring(0, path.indexOf("/")); storagePath = path.replaceFirst(storageID + "/", ""); } if (!userFileStoreClasses.containsKey(storageID)) { try { ObjectMapper mapper = new ObjectMapper(); FileStore userStore = null; for (FileStore store : userStores) { if (store.getID().equals(storageID)) { userStore = store; } } if (userStore == null) { throw new IllegalArgumentException("Storage ID '" + storageID + "' is invalid"); } // Check the source file path is valid if (!filesService.validPath(storagePath, userStore)) { throw new IllegalArgumentException("Path '" + storagePath + "' is invalid"); } userFileStoreClasses.put(storageID, userStore.getStorageClass()); userFileStoreProperties.put(storageID, userStore.getProperties()); } catch (Exception e) { e.printStackTrace(); throw (e); } } System.out.println("Add deposit path: " + path); DepositPath depositPath = new DepositPath(deposit, path, Path.PathType.FILESTORE); deposit.getDepositPaths().add(depositPath); } } // Create a job to track this deposit Job job = new Job("org.datavaultplatform.worker.tasks.Deposit"); jobsService.addJob(deposit, job); // Ask the worker to process the deposit try { ObjectMapper mapper = new ObjectMapper(); HashMap<String, String> depositProperties = new HashMap<>(); depositProperties.put("depositId", deposit.getID()); depositProperties.put("bagId", deposit.getBagId()); depositProperties.put("userId", user.getID()); // Deposit and Vault metadata // TODO: at the moment we're just serialising the objects to JSON. // In future we'll need a more formal schema/representation (e.g. RDF or JSON-LD). depositProperties.put("depositMetadata", mapper.writeValueAsString(deposit)); depositProperties.put("vaultMetadata", mapper.writeValueAsString(vault)); // External metadata is text from an external system - e.g. XML or JSON depositProperties.put("externalMetadata", externalMetadata); ArrayList<String> filestorePaths = new ArrayList<>(); ArrayList<String> userUploadPaths = new ArrayList<>(); for (DepositPath path : deposit.getDepositPaths()) { if (path.getPathType() == Path.PathType.FILESTORE) { filestorePaths.add(path.getFilePath()); } else if (path.getPathType() == Path.PathType.USER_UPLOAD) { userUploadPaths.add(path.getFilePath()); } } Task depositTask = new Task( job, depositProperties, archiveStores, userFileStoreProperties, userFileStoreClasses, filestorePaths, userUploadPaths, null, null, null, null, null, lastEvent); String jsonDeposit = mapper.writeValueAsString(depositTask); sender.send(jsonDeposit); } catch (Exception e) { e.printStackTrace(); } return job; } }
package com.github.dannil.scbjavaclient.test.utility; import java.util.ArrayList; import java.util.List; import info.debatty.java.stringsimilarity.Cosine; import info.debatty.java.stringsimilarity.Jaccard; import info.debatty.java.stringsimilarity.MetricLCS; import info.debatty.java.stringsimilarity.NGram; import info.debatty.java.stringsimilarity.experimental.Sift4; import info.debatty.java.stringsimilarity.interfaces.StringDistance; public class Sorter { public static List<String> sortAccordingTo(List<String> toBeSorted, List<String> accordingTo) { String[] sortedArr = new String[toBeSorted.size()]; for (int i = 0; i < toBeSorted.size(); i++) { String to = toBeSorted.get(i); String toLower = to.toLowerCase(); double mostProbableDistance = Double.MAX_VALUE; int pos = -1; for (int j = 0; j < accordingTo.size(); j++) { String acc = accordingTo.get(j); String accLower = acc.toLowerCase().replaceAll("[^a-zA-Z]", ""); System.out.println("ACCLOWER: " + accLower); // StringDistance dis = new Jaccard(Math.min(to.length(), acc.length())); StringDistance dis = null; double distance = Double.MAX_VALUE; // String toWithoutLast = toLower.substring(0, toLower.length() - 1); // if (accLower.startsWith(toWithoutLast)) { // dis = new MetricLCS(); // System.out.println("Using metricLCS"); // } else { // dis = new Cosine(); // System.out.println("Using cosine"); String toLowerWithoutLast = toLower.substring(0, toLower.length() - 1); if (accLower.startsWith(toLowerWithoutLast)) { // If the method parameter constitutes the beginning of the API // parameter, it's extremely likely this is a match distance = 0.0; // System.out.println("Using metricLCS"); // dis = new MetricLCS(); // int shortest = Math.min(accLower.length(), toLower.length()); // distance = dis.distance(toLower.substring(0, shortest), // accLower.substring(0, shortest)); } else { System.out.println("Using cosine"); dis = new Cosine(); distance = dis.distance(toLower, accLower); } // double distance = dis.distance(toLower, accLower); System.out.println("TO: " + to + ", ACC: " + acc + ", DISTANCE: " + distance); if (distance < mostProbableDistance) { mostProbableDistance = distance; pos = j; } } sortedArr[pos] = to; } List<String> sorted = new ArrayList<>(sortedArr.length); for (int i = 0; i < sortedArr.length; i++) { sorted.add(sortedArr[i]); } return sorted; } }
package io.debezium.connector.oracle; import java.time.Duration; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import org.apache.kafka.common.config.ConfigDef; import org.apache.kafka.common.config.ConfigDef.Importance; import org.apache.kafka.common.config.ConfigDef.Type; import org.apache.kafka.common.config.ConfigDef.Width; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.debezium.DebeziumException; import io.debezium.config.CommonConnectorConfig; import io.debezium.config.ConfigDefinition; import io.debezium.config.Configuration; import io.debezium.config.EnumeratedValue; import io.debezium.config.Field; import io.debezium.config.Field.ValidationOutput; import io.debezium.config.Instantiator; import io.debezium.connector.AbstractSourceInfo; import io.debezium.connector.SourceInfoStructMaker; import io.debezium.connector.oracle.logminer.logwriter.LogWriterFlushStrategy; import io.debezium.connector.oracle.logminer.processor.LogMinerEventProcessor; import io.debezium.connector.oracle.logminer.processor.infinispan.EmbeddedInfinispanLogMinerEventProcessor; import io.debezium.connector.oracle.logminer.processor.infinispan.RemoteInfinispanLogMinerEventProcessor; import io.debezium.connector.oracle.logminer.processor.memory.MemoryLogMinerEventProcessor; import io.debezium.jdbc.JdbcConfiguration; import io.debezium.pipeline.EventDispatcher; import io.debezium.pipeline.source.spi.ChangeEventSource.ChangeEventSourceContext; import io.debezium.relational.ColumnFilterMode; import io.debezium.relational.HistorizedRelationalDatabaseConnectorConfig; import io.debezium.relational.RelationalDatabaseConnectorConfig; import io.debezium.relational.TableId; import io.debezium.relational.Tables.TableFilter; import io.debezium.relational.history.HistoryRecordComparator; import io.debezium.util.Strings; /** * Connector configuration for Oracle. * * @author Gunnar Morling */ public class OracleConnectorConfig extends HistorizedRelationalDatabaseConnectorConfig { protected static final int DEFAULT_PORT = 1528; protected static final int DEFAULT_LOG_FILE_QUERY_MAX_RETRIES = 5; protected static final int DEFAULT_VIEW_FETCH_SIZE = 10_000; protected final static int DEFAULT_BATCH_SIZE = 20_000; protected final static int MIN_BATCH_SIZE = 1_000; protected final static int MAX_BATCH_SIZE = 100_000; protected final static int DEFAULT_SCN_GAP_SIZE = 1_000_000; protected final static int DEFAULT_SCN_GAP_TIME_INTERVAL = 20_000; protected final static Duration MAX_SLEEP_TIME = Duration.ofMillis(3_000); protected final static Duration DEFAULT_SLEEP_TIME = Duration.ofMillis(1_000); protected final static Duration MIN_SLEEP_TIME = Duration.ZERO; protected final static Duration SLEEP_TIME_INCREMENT = Duration.ofMillis(200); protected final static Duration ARCHIVE_LOG_ONLY_POLL_TIME = Duration.ofMillis(10_000); public static final Field PORT = RelationalDatabaseConnectorConfig.PORT .withDefault(DEFAULT_PORT); public static final Field HOSTNAME = RelationalDatabaseConnectorConfig.HOSTNAME .withNoValidation() .withValidation(OracleConnectorConfig::requiredWhenNoUrl); public static final Field PDB_NAME = Field.create(DATABASE_CONFIG_PREFIX + "pdb.name") .withDisplayName("PDB name") .withType(Type.STRING) .withWidth(Width.MEDIUM) .withImportance(Importance.HIGH) .withDescription("Name of the pluggable database when working with a multi-tenant set-up. " + "The CDB name must be given via " + DATABASE_NAME.name() + " in this case."); public static final Field XSTREAM_SERVER_NAME = Field.create(DATABASE_CONFIG_PREFIX + "out.server.name") .withDisplayName("XStream out server name") .withType(Type.STRING) .withWidth(Width.MEDIUM) .withImportance(Importance.HIGH) .withValidation(OracleConnectorConfig::validateOutServerName) .withDescription("Name of the XStream Out server to connect to."); public static final Field INTERVAL_HANDLING_MODE = Field.create("interval.handling.mode") .withDisplayName("Interval Handling") .withEnum(IntervalHandlingMode.class, IntervalHandlingMode.NUMERIC) .withWidth(Width.MEDIUM) .withImportance(Importance.LOW) .withDescription("Specify how INTERVAL columns should be represented in change events, including:" + "'string' represents values as an exact ISO formatted string" + "'numeric' (default) represents values using the inexact conversion into microseconds"); public static final Field SNAPSHOT_MODE = Field.create("snapshot.mode") .withDisplayName("Snapshot mode") .withEnum(SnapshotMode.class, SnapshotMode.INITIAL) .withWidth(Width.SHORT) .withImportance(Importance.LOW) .withDescription("The criteria for running a snapshot upon startup of the connector. " + "Options include: " + "'initial' (the default) to specify the connector should run a snapshot only when no offsets are available for the logical server name; " + "'schema_only' to specify the connector should run a snapshot of the schema when no offsets are available for the logical server name. "); public static final Field SNAPSHOT_LOCKING_MODE = Field.create("snapshot.locking.mode") .withDisplayName("Snapshot locking mode") .withEnum(SnapshotLockingMode.class, SnapshotLockingMode.SHARED) .withWidth(Width.SHORT) .withImportance(Importance.LOW) .withDescription("Controls how the connector holds locks on tables while performing the schema snapshot. The default is 'shared', " + "which means the connector will hold a table lock that prevents exclusive table access for just the initial portion of the snapshot " + "while the database schemas and other metadata are being read. The remaining work in a snapshot involves selecting all rows from " + "each table, and this is done using a flashback query that requires no locks. However, in some cases it may be desirable to avoid " + "locks entirely which can be done by specifying 'none'. This mode is only safe to use if no schema changes are happening while the " + "snapshot is taken."); public static final Field ORACLE_VERSION = Field.createInternal("database.oracle.version") .withDisplayName("Oracle version, 11 or 12+") .withType(Type.STRING) .withImportance(Importance.LOW) .withDescription("Deprecated: For default Oracle 12+, use default pos_version value v2, for Oracle 11, use pos_version value v1."); public static final Field SERVER_NAME = RelationalDatabaseConnectorConfig.SERVER_NAME .withValidation(CommonConnectorConfig::validateServerNameIsDifferentFromHistoryTopicName); public static final Field CONNECTOR_ADAPTER = Field.create(DATABASE_CONFIG_PREFIX + "connection.adapter") .withDisplayName("Connector adapter") .withEnum(ConnectorAdapter.class, ConnectorAdapter.LOG_MINER) .withWidth(Width.MEDIUM) .withImportance(Importance.HIGH) .withDescription("The adapter to use when capturing changes from the database. " + "Options include: " + "'logminer': (the default) to capture changes using native Oracle LogMiner; " + "'xstream' to capture changes using Oracle XStreams"); public static final Field LOG_MINING_STRATEGY = Field.create("log.mining.strategy") .withDisplayName("Log Mining Strategy") .withEnum(LogMiningStrategy.class, LogMiningStrategy.CATALOG_IN_REDO) .withWidth(Width.MEDIUM) .withImportance(Importance.HIGH) .withDescription("There are strategies: Online catalog with faster mining but no captured DDL. Another - with data dictionary loaded into REDO LOG files"); // this option could be true up to Oracle 18c version. Starting from Oracle 19c this option cannot be true todo should we do it? public static final Field CONTINUOUS_MINE = Field.create("log.mining.continuous.mine") .withDisplayName("Should log mining session configured with CONTINUOUS_MINE setting?") .withType(Type.BOOLEAN) .withWidth(Width.SHORT) .withImportance(Importance.LOW) .withDefault(false) .withValidation(Field::isBoolean) .withDescription("If true, CONTINUOUS_MINE option will be added to the log mining session. This will manage log files switches seamlessly."); public static final Field SNAPSHOT_ENHANCEMENT_TOKEN = Field.create("snapshot.enhance.predicate.scn") .withDisplayName("A string to replace on snapshot predicate enhancement") .withType(Type.STRING) .withWidth(Width.MEDIUM) .withImportance(Importance.HIGH) .withDescription("A token to replace on snapshot predicate template"); public static final Field LOG_MINING_TRANSACTION_RETENTION = Field.create("log.mining.transaction.retention.hours") .withDisplayName("Log Mining long running transaction retention") .withType(Type.LONG) .withWidth(Width.SHORT) .withImportance(Importance.MEDIUM) .withDefault(0) .withValidation(Field::isNonNegativeInteger) .withDescription("Hours to keep long running transactions in transaction buffer between log mining sessions. By default, all transactions are retained."); public static final Field RAC_NODES = Field.create("rac.nodes") .withDisplayName("Oracle RAC nodes") .withType(Type.STRING) .withWidth(Width.SHORT) .withImportance(Importance.HIGH) .withValidation(OracleConnectorConfig::validateRacNodes) .withDescription("A comma-separated list of RAC node hostnames or ip addresses"); public static final Field URL = Field.create(DATABASE_CONFIG_PREFIX + "url") .withDisplayName("Complete JDBC URL") .withType(Type.STRING) .withWidth(Width.LONG) .withImportance(Importance.HIGH) .withValidation(OracleConnectorConfig::requiredWhenNoHostname) .withDescription("Complete JDBC URL as an alternative to specifying hostname, port and database provided " + "as a way to support alternative connection scenarios."); public static final Field LOG_MINING_ARCHIVE_LOG_HOURS = Field.create("log.mining.archive.log.hours") .withDisplayName("Log Mining Archive Log Hours") .withType(Type.LONG) .withWidth(Width.SHORT) .withImportance(Importance.LOW) .withDefault(0) .withDescription("The number of hours in the past from SYSDATE to mine archive logs. Using 0 mines all available archive logs"); public static final Field LOG_MINING_BATCH_SIZE_MIN = Field.create("log.mining.batch.size.min") .withDisplayName("Minimum batch size for reading redo/archive logs.") .withType(Type.LONG) .withWidth(Width.SHORT) .withImportance(Importance.LOW) .withDefault(MIN_BATCH_SIZE) .withDescription( "The minimum SCN interval size that this connector will try to read from redo/archive logs. Active batch size will be also increased/decreased by this amount for tuning connector throughput when needed."); public static final Field LOG_MINING_BATCH_SIZE_DEFAULT = Field.create("log.mining.batch.size.default") .withDisplayName("Default batch size for reading redo/archive logs.") .withType(Type.LONG) .withWidth(Width.SHORT) .withImportance(Importance.LOW) .withDefault(DEFAULT_BATCH_SIZE) .withDescription("The starting SCN interval size that the connector will use for reading data from redo/archive logs."); public static final Field LOG_MINING_BATCH_SIZE_MAX = Field.create("log.mining.batch.size.max") .withDisplayName("Maximum batch size for reading redo/archive logs.") .withType(Type.LONG) .withWidth(Width.SHORT) .withImportance(Importance.LOW) .withDefault(MAX_BATCH_SIZE) .withDescription("The maximum SCN interval size that this connector will use when reading from redo/archive logs."); public static final Field LOG_MINING_VIEW_FETCH_SIZE = Field.create("log.mining.view.fetch.size") .withDisplayName("Number of content records that will be fetched.") .withType(Type.LONG) .withWidth(Width.SHORT) .withImportance(Importance.LOW) .withDefault(DEFAULT_VIEW_FETCH_SIZE) .withDescription("The number of content records that will be fetched from the LogMiner content view."); public static final Field LOG_MINING_SLEEP_TIME_MIN_MS = Field.create("log.mining.sleep.time.min.ms") .withDisplayName("Minimum sleep time in milliseconds when reading redo/archive logs.") .withType(Type.LONG) .withWidth(Width.SHORT) .withImportance(Importance.LOW) .withDefault(MIN_SLEEP_TIME.toMillis()) .withDescription( "The minimum amount of time that the connector will sleep after reading data from redo/archive logs and before starting reading data again. Value is in milliseconds."); public static final Field LOG_MINING_SLEEP_TIME_DEFAULT_MS = Field.create("log.mining.sleep.time.default.ms") .withDisplayName("Default sleep time in milliseconds when reading redo/archive logs.") .withType(Type.LONG) .withWidth(Width.SHORT) .withImportance(Importance.LOW) .withDefault(DEFAULT_SLEEP_TIME.toMillis()) .withDescription( "The amount of time that the connector will sleep after reading data from redo/archive logs and before starting reading data again. Value is in milliseconds."); public static final Field LOG_MINING_SLEEP_TIME_MAX_MS = Field.create("log.mining.sleep.time.max.ms") .withDisplayName("Maximum sleep time in milliseconds when reading redo/archive logs.") .withType(Type.LONG) .withWidth(Width.SHORT) .withImportance(Importance.LOW) .withDefault(MAX_SLEEP_TIME.toMillis()) .withDescription( "The maximum amount of time that the connector will sleep after reading data from redo/archive logs and before starting reading data again. Value is in milliseconds."); public static final Field LOG_MINING_SLEEP_TIME_INCREMENT_MS = Field.create("log.mining.sleep.time.increment.ms") .withDisplayName("The increment in sleep time in milliseconds used to tune auto-sleep behavior.") .withType(Type.LONG) .withWidth(Width.SHORT) .withImportance(Importance.LOW) .withDefault(SLEEP_TIME_INCREMENT.toMillis()) .withDescription( "The maximum amount of time that the connector will use to tune the optimal sleep time when reading data from LogMiner. Value is in milliseconds."); public static final Field LOG_MINING_ARCHIVE_LOG_ONLY_MODE = Field.create("log.mining.archive.log.only.mode") .withDisplayName("Specifies whether log mining should only target archive logs or both archive and redo logs") .withType(Type.BOOLEAN) .withWidth(Width.SHORT) .withImportance(Importance.LOW) .withDefault(false) .withDescription("When set to `false`, the default, the connector will mine both archive log and redo logs to emit change events. " + "When set to `true`, the connector will only mine archive logs. There are circumstances where its advantageous to only " + "mine archive logs and accept latency in event emission due to frequent revolving redo logs."); public static final Field LOG_MINING_ARCHIVE_LOG_ONLY_SCN_POLL_INTERVAL_MS = Field.create("log.mining.archive.log.only.scn.poll.interval.ms") .withDisplayName("The interval in milliseconds to wait between polls when SCN is not yet in the archive logs") .withType(Type.LONG) .withWidth(Width.SHORT) .withImportance(Importance.LOW) .withDefault(ARCHIVE_LOG_ONLY_POLL_TIME.toMillis()) .withDescription("The interval in milliseconds to wait between polls checking to see if the SCN is in the archive logs."); public static final Field LOB_ENABLED = Field.create("lob.enabled") .withDisplayName("Specifies whether the connector supports mining LOB fields and operations") .withType(Type.BOOLEAN) .withWidth(Width.SHORT) .withImportance(Importance.LOW) .withDefault(false) .withDescription("When set to `false`, the default, LOB fields will not be captured nor emitted. When set to `true`, the connector " + "will capture LOB fields and emit changes for those fields like any other column type."); public static final Field LOG_MINING_USERNAME_EXCLUDE_LIST = Field.create("log.mining.username.exclude.list") .withDisplayName("List of users to exclude from LogMiner query") .withType(Type.STRING) .withWidth(Width.SHORT) .withImportance(Importance.LOW) .withDescription("Comma separated list of usernames to exclude from LogMiner query."); public static final Field LOG_MINING_ARCHIVE_DESTINATION_NAME = Field.create("log.mining.archive.destination.name") .withDisplayName("Name of the archive log destination to be used for reading archive logs") .withType(Type.STRING) .withWidth(Width.MEDIUM) .withImportance(Importance.LOW) .withDescription("Sets the specific archive log destination as the source for reading archive logs." + "When not set, the connector will automatically select the first LOCAL and VALID destination."); public static final Field LOG_MINING_BUFFER_TYPE = Field.create("log.mining.buffer.type") .withDisplayName("Controls which buffer type implementation to be used") .withEnum(LogMiningBufferType.class, LogMiningBufferType.MEMORY) .withValidation(OracleConnectorConfig::validateLogMiningBufferType) .withImportance(Importance.LOW) .withDescription("The buffer type controls how the connector manages buffering transaction data." + System.lineSeparator() + System.lineSeparator() + "memory - Uses the JVM process' heap to buffer all transaction data." + System.lineSeparator() + System.lineSeparator() + "infinispan_embedded - This option uses an embedded Infinispan cache to buffer transaction data and persist it to disk." + System.lineSeparator() + System.lineSeparator() + "infinispan_remote - This option uses a remote Infinispan cluster to buffer transaction data and persist it to disk."); @Deprecated public static final Field LOG_MINING_BUFFER_LOCATION = Field.create("log.mining.buffer.location") .withDisplayName("Location where Infinispan stores buffer caches") .withType(Type.STRING) .withWidth(Width.MEDIUM) .withImportance(Importance.LOW) .withValidation(OracleConnectorConfig::validateBufferLocation) .withDescription("(Deprecated) Path to location where Infinispan will store buffer caches"); public static final Field LOG_MINING_BUFFER_INFINISPAN_CACHE_TRANSACTIONS = Field.create("log.mining.buffer.infinispan.cache.transactions") .withDisplayName("Infinispan 'transactions' cache configuration") .withType(Type.STRING) .withWidth(Width.LONG) .withImportance(Importance.LOW) .withValidation(OracleConnectorConfig::validateLogMiningInfinispanCacheConfiguration) .withDescription("Specifies the XML configuration for the Infinispan 'transactions' cache"); public static final Field LOG_MINING_BUFFER_INFINISPAN_CACHE_PROCESSED_TRANSACTIONS = Field.create("log.mining.buffer.infinispan.cache.processed_transactions") .withDisplayName("Infinispan 'processed-transactions' cache configuration") .withType(Type.STRING) .withWidth(Width.LONG) .withImportance(Importance.LOW) .withValidation(OracleConnectorConfig::validateLogMiningInfinispanCacheConfiguration) .withDescription("Specifies the XML configuration for the Infinispan 'processed-transactions' cache"); public static final Field LOG_MINING_BUFFER_INFINISPAN_CACHE_EVENTS = Field.create("log.mining.buffer.infinispan.cache.events") .withDisplayName("Infinispan 'events' cache configurations") .withType(Type.STRING) .withWidth(Width.LONG) .withImportance(Importance.LOW) .withValidation(OracleConnectorConfig::validateLogMiningInfinispanCacheConfiguration) .withDescription("Specifies the XML configuration for the Infinispan 'events' cache"); public static final Field LOG_MINING_BUFFER_INFINISPAN_CACHE_SCHEMA_CHANGES = Field.create("log.mining.buffer.infinispan.cache.schema_changes") .withDisplayName("Infinispan 'schema-changes' cache configuration") .withType(Type.STRING) .withWidth(Width.LONG) .withImportance(Importance.LOW) .withValidation(OracleConnectorConfig::validateLogMiningInfinispanCacheConfiguration) .withDescription("Specifies the XML configuration for the Infinispan 'schema-changes' cache"); public static final Field LOG_MINING_BUFFER_DROP_ON_STOP = Field.create("log.mining.buffer.drop.on.stop") .withDisplayName("Controls whether the buffer cache is dropped when connector is stopped") .withType(Type.BOOLEAN) .withDefault(false) .withWidth(Width.SHORT) .withImportance(Importance.LOW) .withDescription("When set to true the underlying buffer cache is not retained when the connector is stopped. " + "When set to false (the default), the buffer cache is retained across restarts."); public static final Field LOG_MINING_SCN_GAP_DETECTION_GAP_SIZE_MIN = Field.create("log.mining.scn.gap.detection.gap.size.min") .withDisplayName("SCN gap size used to detect SCN gap") .withType(Type.LONG) .withWidth(Width.SHORT) .withImportance(Importance.LOW) .withDefault(DEFAULT_SCN_GAP_SIZE) .withDescription("Used for SCN gap detection, if the difference between current SCN and previous end SCN is " + "bigger than this value, and the time difference of current SCN and previous end SCN is smaller than " + "log.mining.scn.gap.detection.time.interval.max.ms, consider it a SCN gap."); public static final Field LOG_MINING_SCN_GAP_DETECTION_TIME_INTERVAL_MAX_MS = Field.create("log.mining.scn.gap.detection.time.interval.max.ms") .withDisplayName("Timer interval used to detect SCN gap") .withType(Type.LONG) .withWidth(Width.SHORT) .withImportance(Importance.LOW) .withDefault(DEFAULT_SCN_GAP_TIME_INTERVAL) .withDescription("Used for SCN gap detection, if the difference between current SCN and previous end SCN is " + "bigger than log.mining.scn.gap.detection.gap.size.min, and the time difference of current SCN and previous end SCN is smaller than " + " this value, consider it a SCN gap."); private static final ConfigDefinition CONFIG_DEFINITION = HistorizedRelationalDatabaseConnectorConfig.CONFIG_DEFINITION.edit() .name("Oracle") .excluding( SCHEMA_WHITELIST, SCHEMA_INCLUDE_LIST, SCHEMA_BLACKLIST, SCHEMA_EXCLUDE_LIST, RelationalDatabaseConnectorConfig.TABLE_IGNORE_BUILTIN, SERVER_NAME) .type( HOSTNAME, PORT, USER, PASSWORD, SERVER_NAME, DATABASE_NAME, PDB_NAME, XSTREAM_SERVER_NAME, SNAPSHOT_MODE, CONNECTOR_ADAPTER, LOG_MINING_STRATEGY, URL, ORACLE_VERSION) .connector( SNAPSHOT_ENHANCEMENT_TOKEN, SNAPSHOT_LOCKING_MODE, RAC_NODES, INTERVAL_HANDLING_MODE, LOG_MINING_ARCHIVE_LOG_HOURS, LOG_MINING_BATCH_SIZE_DEFAULT, LOG_MINING_BATCH_SIZE_MIN, LOG_MINING_BATCH_SIZE_MAX, LOG_MINING_SLEEP_TIME_DEFAULT_MS, LOG_MINING_SLEEP_TIME_MIN_MS, LOG_MINING_SLEEP_TIME_MAX_MS, LOG_MINING_SLEEP_TIME_INCREMENT_MS, LOG_MINING_TRANSACTION_RETENTION, LOG_MINING_ARCHIVE_LOG_ONLY_MODE, LOB_ENABLED, LOG_MINING_USERNAME_EXCLUDE_LIST, LOG_MINING_ARCHIVE_DESTINATION_NAME, LOG_MINING_BUFFER_TYPE, LOG_MINING_BUFFER_LOCATION, LOG_MINING_BUFFER_DROP_ON_STOP, LOG_MINING_BUFFER_INFINISPAN_CACHE_TRANSACTIONS, LOG_MINING_BUFFER_INFINISPAN_CACHE_EVENTS, LOG_MINING_BUFFER_INFINISPAN_CACHE_PROCESSED_TRANSACTIONS, LOG_MINING_BUFFER_INFINISPAN_CACHE_SCHEMA_CHANGES, LOG_MINING_ARCHIVE_LOG_ONLY_SCN_POLL_INTERVAL_MS, LOG_MINING_SCN_GAP_DETECTION_GAP_SIZE_MIN, LOG_MINING_SCN_GAP_DETECTION_TIME_INTERVAL_MAX_MS, UNAVAILABLE_VALUE_PLACEHOLDER, BINARY_HANDLING_MODE) .create(); /** * The set of {@link Field}s defined as part of this configuration. */ public static Field.Set ALL_FIELDS = Field.setOf(CONFIG_DEFINITION.all()); public static ConfigDef configDef() { return CONFIG_DEFINITION.configDef(); } public static final List<String> EXCLUDED_SCHEMAS = Collections.unmodifiableList(Arrays.asList("appqossys", "audsys", "ctxsys", "dvsys", "dbsfwuser", "dbsnmp", "gsmadmin_internal", "lbacsys", "mdsys", "ojvmsys", "olapsys", "orddata", "ordsys", "outln", "sys", "system", "wmsys", "xdb")); private static final Logger LOGGER = LoggerFactory.getLogger(OracleConnectorConfig.class); private final String databaseName; private final String pdbName; private final String xoutServerName; private final IntervalHandlingMode intervalHandlingMode; private final SnapshotMode snapshotMode; private final String oracleVersion; private ConnectorAdapter connectorAdapter; private final StreamingAdapter streamingAdapter; private final String snapshotEnhancementToken; private final SnapshotLockingMode snapshotLockingMode; // LogMiner options private final LogMiningStrategy logMiningStrategy; private final Set<String> racNodes; private final boolean logMiningContinuousMine; private final Duration logMiningArchiveLogRetention; private final int logMiningBatchSizeMin; private final int logMiningBatchSizeMax; private final int logMiningBatchSizeDefault; private final int logMiningViewFetchSize; private final Duration logMiningSleepTimeMin; private final Duration logMiningSleepTimeMax; private final Duration logMiningSleepTimeDefault; private final Duration logMiningSleepTimeIncrement; private final Duration logMiningTransactionRetention; private final boolean archiveLogOnlyMode; private final Duration archiveLogOnlyScnPollTime; private final boolean lobEnabled; private final Set<String> logMiningUsernameExcludes; private final String logMiningArchiveDestinationName; private final LogMiningBufferType logMiningBufferType; private final boolean logMiningBufferDropOnStop; private final int logMiningScnGapDetectionGapSizeMin; private final int logMiningScnGapDetectionTimeIntervalMaxMs; private final int logMiningLogFileQueryMaxRetries; public OracleConnectorConfig(Configuration config) { super(OracleConnector.class, config, config.getString(SERVER_NAME), new SystemTablesPredicate(config), x -> x.schema() + "." + x.table(), true, ColumnFilterMode.SCHEMA); this.databaseName = toUpperCase(config.getString(DATABASE_NAME)); this.pdbName = toUpperCase(config.getString(PDB_NAME)); this.xoutServerName = config.getString(XSTREAM_SERVER_NAME); this.intervalHandlingMode = IntervalHandlingMode.parse(config.getString(INTERVAL_HANDLING_MODE)); this.snapshotMode = SnapshotMode.parse(config.getString(SNAPSHOT_MODE)); this.oracleVersion = config.getString(ORACLE_VERSION); this.snapshotEnhancementToken = config.getString(SNAPSHOT_ENHANCEMENT_TOKEN); this.connectorAdapter = ConnectorAdapter.parse(config.getString(CONNECTOR_ADAPTER)); this.snapshotLockingMode = SnapshotLockingMode.parse(config.getString(SNAPSHOT_LOCKING_MODE), SNAPSHOT_LOCKING_MODE.defaultValueAsString()); this.lobEnabled = config.getBoolean(LOB_ENABLED); this.streamingAdapter = this.connectorAdapter.getInstance(this); if (this.streamingAdapter == null) { throw new DebeziumException("Unable to instantiate the connector adapter implementation"); } // LogMiner this.logMiningStrategy = LogMiningStrategy.parse(config.getString(LOG_MINING_STRATEGY)); this.racNodes = resolveRacNodes(config); this.logMiningContinuousMine = config.getBoolean(CONTINUOUS_MINE); this.logMiningArchiveLogRetention = Duration.ofHours(config.getLong(LOG_MINING_ARCHIVE_LOG_HOURS)); this.logMiningBatchSizeMin = config.getInteger(LOG_MINING_BATCH_SIZE_MIN); this.logMiningBatchSizeMax = config.getInteger(LOG_MINING_BATCH_SIZE_MAX); this.logMiningBatchSizeDefault = config.getInteger(LOG_MINING_BATCH_SIZE_DEFAULT); this.logMiningViewFetchSize = config.getInteger(LOG_MINING_VIEW_FETCH_SIZE); this.logMiningSleepTimeMin = Duration.ofMillis(config.getInteger(LOG_MINING_SLEEP_TIME_MIN_MS)); this.logMiningSleepTimeMax = Duration.ofMillis(config.getInteger(LOG_MINING_SLEEP_TIME_MAX_MS)); this.logMiningSleepTimeDefault = Duration.ofMillis(config.getInteger(LOG_MINING_SLEEP_TIME_DEFAULT_MS)); this.logMiningSleepTimeIncrement = Duration.ofMillis(config.getInteger(LOG_MINING_SLEEP_TIME_INCREMENT_MS)); this.logMiningTransactionRetention = Duration.ofHours(config.getInteger(LOG_MINING_TRANSACTION_RETENTION)); this.archiveLogOnlyMode = config.getBoolean(LOG_MINING_ARCHIVE_LOG_ONLY_MODE); this.logMiningUsernameExcludes = Strings.setOf(config.getString(LOG_MINING_USERNAME_EXCLUDE_LIST), String::new); this.logMiningArchiveDestinationName = config.getString(LOG_MINING_ARCHIVE_DESTINATION_NAME); this.logMiningBufferType = LogMiningBufferType.parse(config.getString(LOG_MINING_BUFFER_TYPE)); this.logMiningBufferDropOnStop = config.getBoolean(LOG_MINING_BUFFER_DROP_ON_STOP); this.archiveLogOnlyScnPollTime = Duration.ofMillis(config.getInteger(LOG_MINING_ARCHIVE_LOG_ONLY_SCN_POLL_INTERVAL_MS)); this.logMiningScnGapDetectionGapSizeMin = config.getInteger(LOG_MINING_SCN_GAP_DETECTION_GAP_SIZE_MIN); this.logMiningScnGapDetectionTimeIntervalMaxMs = config.getInteger(LOG_MINING_SCN_GAP_DETECTION_TIME_INTERVAL_MAX_MS); this.logMiningLogFileQueryMaxRetries = DEFAULT_LOG_FILE_QUERY_MAX_RETRIES; } private static String toUpperCase(String property) { return property == null ? null : property.toUpperCase(); } public String getDatabaseName() { return databaseName; } public String getPdbName() { return pdbName; } public String getCatalogName() { return pdbName != null ? pdbName : databaseName; } public String getXoutServerName() { return xoutServerName; } public IntervalHandlingMode getIntervalHandlingMode() { return intervalHandlingMode; } public SnapshotMode getSnapshotMode() { return snapshotMode; } public SnapshotLockingMode getSnapshotLockingMode() { return snapshotLockingMode; } public String getOracleVersion() { return oracleVersion; } @Override protected HistoryRecordComparator getHistoryRecordComparator() { return getAdapter().getHistoryRecordComparator(); } /** * Defines modes of representation of {@code interval} datatype */ public enum IntervalHandlingMode implements EnumeratedValue { /** * Represents interval as inexact microseconds count */ NUMERIC("numeric"), /** * Represents interval as ISO 8601 time interval */ STRING("string"); private final String value; IntervalHandlingMode(String value) { this.value = value; } @Override public String getValue() { return value; } /** * Convert mode name into the logical value * * @param value the configuration property value ; may not be null * @return the matching option, or null if the match is not found */ public static IntervalHandlingMode parse(String value) { if (value == null) { return null; } value = value.trim(); for (IntervalHandlingMode option : IntervalHandlingMode.values()) { if (option.getValue().equalsIgnoreCase(value)) { return option; } } return null; } /** * Convert mode name into the logical value * * @param value the configuration property value ; may not be null * @param defaultValue the default value ; may be null * @return the matching option or null if the match is not found and non-null default is invalid */ public static IntervalHandlingMode parse(String value, String defaultValue) { IntervalHandlingMode mode = parse(value); if (mode == null && defaultValue != null) { mode = parse(defaultValue); } return mode; } } /** * The set of predefined SnapshotMode options or aliases. */ public enum SnapshotMode implements EnumeratedValue { /** * Perform a snapshot of data and schema upon initial startup of a connector. */ INITIAL("initial", true, true, false), /** * Perform a snapshot of data and schema upon initial startup of a connector and stop after initial consistent snapshot. */ INITIAL_ONLY("initial_only", true, false, false), /** * Perform a snapshot of the schema but no data upon initial startup of a connector. */ SCHEMA_ONLY("schema_only", false, true, false), /** * Perform a snapshot of only the database schemas (without data) and then begin reading the redo log at the current redo log position. * This can be used for recovery only if the connector has existing offsets and the database.history.kafka.topic does not exist (deleted). * This recovery option should be used with care as it assumes there have been no schema changes since the connector last stopped, * otherwise some events during the gap may be processed with an incorrect schema and corrupted. */ SCHEMA_ONLY_RECOVERY("schema_only_recovery", false, true, true); private final String value; private final boolean includeData; private final boolean shouldStream; private final boolean shouldSnapshotOnSchemaError; private SnapshotMode(String value, boolean includeData, boolean shouldStream, boolean shouldSnapshotOnSchemaError) { this.value = value; this.includeData = includeData; this.shouldStream = shouldStream; this.shouldSnapshotOnSchemaError = shouldSnapshotOnSchemaError; } @Override public String getValue() { return value; } /** * Whether this snapshotting mode should include the actual data or just the * schema of captured tables. */ public boolean includeData() { return includeData; } /** * Whether the snapshot mode is followed by streaming. */ public boolean shouldStream() { return shouldStream; } /** * Whether the schema can be recovered if database history is corrupted. */ public boolean shouldSnapshotOnSchemaError() { return shouldSnapshotOnSchemaError; } /** * Determine if the supplied value is one of the predefined options. * * @param value the configuration property value; may not be null * @return the matching option, or null if no match is found */ public static SnapshotMode parse(String value) { if (value == null) { return null; } value = value.trim(); for (SnapshotMode option : SnapshotMode.values()) { if (option.getValue().equalsIgnoreCase(value)) { return option; } } return null; } /** * Determine if the supplied value is one of the predefined options. * * @param value the configuration property value; may not be null * @param defaultValue the default value; may be null * @return the matching option, or null if no match is found and the non-null default is invalid */ public static SnapshotMode parse(String value, String defaultValue) { SnapshotMode mode = parse(value); if (mode == null && defaultValue != null) { mode = parse(defaultValue); } return mode; } } public enum SnapshotLockingMode implements EnumeratedValue { /** * This mode will allow concurrent access to the table during the snapshot but prevents any * session from acquiring any table-level exclusive lock. */ SHARED("shared"), /** * This mode will avoid using ANY table locks during the snapshot process. * This mode should be used carefully only when no schema changes are to occur. */ NONE("none"); private final String value; private SnapshotLockingMode(String value) { this.value = value; } @Override public String getValue() { return value; } public boolean usesLocking() { return !value.equals(NONE.value); } /** * Determine if the supplied value is one of the predefined options. * * @param value the configuration property value; may not be {@code null} * @return the matching option, or null if no match is found */ public static SnapshotLockingMode parse(String value) { if (value == null) { return null; } value = value.trim(); for (SnapshotLockingMode option : SnapshotLockingMode.values()) { if (option.getValue().equalsIgnoreCase(value)) { return option; } } return null; } /** * Determine if the supplied value is one of the predefined options. * * @param value the configuration property value; may not be {@code null} * @param defaultValue the default value; may be {@code null} * @return the matching option, or null if no match is found and the non-null default is invalid */ public static SnapshotLockingMode parse(String value, String defaultValue) { SnapshotLockingMode mode = parse(value); if (mode == null && defaultValue != null) { mode = parse(defaultValue); } return mode; } } public enum ConnectorAdapter implements EnumeratedValue { /** * This is based on XStream API. */ XSTREAM("XStream") { @Override public String getConnectionUrl() { return "jdbc:oracle:oci:@${" + JdbcConfiguration.HOSTNAME + "}:${" + JdbcConfiguration.PORT + "}/${" + JdbcConfiguration.DATABASE + "}"; } @Override public StreamingAdapter getInstance(OracleConnectorConfig connectorConfig) { return Instantiator.getInstanceWithProvidedConstructorType( "io.debezium.connector.oracle.xstream.XStreamAdapter", StreamingAdapter.class::getClassLoader, OracleConnectorConfig.class, connectorConfig); } }, /** * This is based on LogMiner utility. */ LOG_MINER("LogMiner") { @Override public String getConnectionUrl() { return "jdbc:oracle:thin:@${" + JdbcConfiguration.HOSTNAME + "}:${" + JdbcConfiguration.PORT + "}/${" + JdbcConfiguration.DATABASE + "}"; } @Override public StreamingAdapter getInstance(OracleConnectorConfig connectorConfig) { return Instantiator.getInstanceWithProvidedConstructorType( "io.debezium.connector.oracle.logminer.LogMinerAdapter", StreamingAdapter.class::getClassLoader, OracleConnectorConfig.class, connectorConfig); } }; public abstract String getConnectionUrl(); public abstract StreamingAdapter getInstance(OracleConnectorConfig connectorConfig); private final String value; ConnectorAdapter(String value) { this.value = value; } @Override public String getValue() { return value; } /** * Determine if the supplied value is one of the predefined options. * * @param value the configuration property value; may not be null * @return the matching option, or null if no match is found */ public static ConnectorAdapter parse(String value) { if (value == null) { return ConnectorAdapter.LOG_MINER; } value = value.trim(); for (ConnectorAdapter adapter : ConnectorAdapter.values()) { if (adapter.getValue().equalsIgnoreCase(value)) { return adapter; } } return null; } public static ConnectorAdapter parse(String value, String defaultValue) { ConnectorAdapter mode = parse(value); if (mode == null && defaultValue != null) { mode = parse(defaultValue); } return mode; } } public enum LogMiningStrategy implements EnumeratedValue { /** * This strategy uses LogMiner with data dictionary in online catalog. * This option will not capture DDL , but acts fast on REDO LOG switch events * This option does not use CONTINUOUS_MINE option */ ONLINE_CATALOG("online_catalog"), /** * This strategy uses LogMiner with data dictionary in REDO LOG files. * This option will capture DDL, but will develop some lag on REDO LOG switch event and will eventually catch up * This option does not use CONTINUOUS_MINE option * This is default value */ CATALOG_IN_REDO("redo_log_catalog"); private final String value; LogMiningStrategy(String value) { this.value = value; } @Override public String getValue() { return value; } /** * Determine if the supplied value is one of the predefined options. * * @param value the configuration property value; may not be null * @return the matching option, or null if no match is found */ public static LogMiningStrategy parse(String value) { if (value == null) { return null; } value = value.trim(); for (LogMiningStrategy adapter : LogMiningStrategy.values()) { if (adapter.getValue().equalsIgnoreCase(value)) { return adapter; } } return null; } public static LogMiningStrategy parse(String value, String defaultValue) { LogMiningStrategy mode = parse(value); if (mode == null && defaultValue != null) { mode = parse(defaultValue); } return mode; } } public enum LogMiningBufferType implements EnumeratedValue { MEMORY("memory") { @Override public LogMinerEventProcessor createProcessor(ChangeEventSourceContext context, OracleConnectorConfig connectorConfig, OracleConnection connection, EventDispatcher<TableId> dispatcher, OraclePartition partition, OracleOffsetContext offsetContext, OracleDatabaseSchema schema, OracleStreamingChangeEventSourceMetrics metrics) { return new MemoryLogMinerEventProcessor(context, connectorConfig, connection, dispatcher, partition, offsetContext, schema, metrics); } }, /** * @deprecated use either {@link #INFINISPAN_EMBEDDED} or {@link #INFINISPAN_REMOTE}. */ @Deprecated INFINISPAN("infinispan") { @Override public LogMinerEventProcessor createProcessor(ChangeEventSourceContext context, OracleConnectorConfig connectorConfig, OracleConnection connection, EventDispatcher<TableId> dispatcher, OraclePartition partition, OracleOffsetContext offsetContext, OracleDatabaseSchema schema, OracleStreamingChangeEventSourceMetrics metrics) { return new EmbeddedInfinispanLogMinerEventProcessor(context, connectorConfig, connection, dispatcher, partition, offsetContext, schema, metrics); } }, INFINISPAN_EMBEDDED("infinispan_embedded") { @Override public LogMinerEventProcessor createProcessor(ChangeEventSourceContext context, OracleConnectorConfig connectorConfig, OracleConnection connection, EventDispatcher<TableId> dispatcher, OraclePartition partition, OracleOffsetContext offsetContext, OracleDatabaseSchema schema, OracleStreamingChangeEventSourceMetrics metrics) { return new EmbeddedInfinispanLogMinerEventProcessor(context, connectorConfig, connection, dispatcher, partition, offsetContext, schema, metrics); } }, INFINISPAN_REMOTE("infinispan_remote") { @Override public LogMinerEventProcessor createProcessor(ChangeEventSourceContext context, OracleConnectorConfig connectorConfig, OracleConnection connection, EventDispatcher<TableId> dispatcher, OraclePartition partition, OracleOffsetContext offsetContext, OracleDatabaseSchema schema, OracleStreamingChangeEventSourceMetrics metrics) { return new RemoteInfinispanLogMinerEventProcessor(context, connectorConfig, connection, dispatcher, partition, offsetContext, schema, metrics); } }; private final String value; /** * Creates the buffer type's specific processor implementation */ public abstract LogMinerEventProcessor createProcessor(ChangeEventSourceContext context, OracleConnectorConfig connectorConfig, OracleConnection connection, EventDispatcher<TableId> dispatcher, OraclePartition partition, OracleOffsetContext offsetContext, OracleDatabaseSchema schema, OracleStreamingChangeEventSourceMetrics metrics); LogMiningBufferType(String value) { this.value = value; } @Override public String getValue() { return value; } public boolean isInfinispan() { return !MEMORY.equals(this); } public boolean isInfinispanEmbedded() { return isInfinispan() && (INFINISPAN.equals(this) || INFINISPAN_EMBEDDED.equals(this)); } public static LogMiningBufferType parse(String value) { if (value != null) { value = value.trim(); for (LogMiningBufferType option : LogMiningBufferType.values()) { if (option.getValue().equalsIgnoreCase(value)) { return option; } } } return null; } private static LogMiningBufferType parse(String value, String defaultValue) { LogMiningBufferType type = parse(value); if (type == null && defaultValue != null) { type = parse(defaultValue); } return type; } } /** * A {@link TableFilter} that excludes all Oracle system tables. * * @author Gunnar Morling */ private static class SystemTablesPredicate implements TableFilter { private final Configuration config; SystemTablesPredicate(Configuration config) { this.config = config; } @Override public boolean isIncluded(TableId t) { return !isExcludedSchema(t) && !isFlushTable(t); } private boolean isExcludedSchema(TableId id) { return EXCLUDED_SCHEMAS.contains(id.schema().toLowerCase()); } private boolean isFlushTable(TableId id) { return LogWriterFlushStrategy.isFlushTable(id, config.getString(USER)); } } @Override protected SourceInfoStructMaker<? extends AbstractSourceInfo> getSourceInfoStructMaker(Version version) { return new OracleSourceInfoStructMaker(Module.name(), Module.version(), this); } @Override public String getContextName() { return Module.contextName(); } /** * @return the streaming adapter implementation */ public StreamingAdapter getAdapter() { return streamingAdapter; } /** * @return Log Mining strategy */ public LogMiningStrategy getLogMiningStrategy() { return logMiningStrategy; } /** * @return whether Oracle is using RAC */ public Boolean isRacSystem() { return !racNodes.isEmpty(); } /** * @return set of node hosts or ip addresses used in Oracle RAC */ public Set<String> getRacNodes() { return racNodes; } /** * @return String token to replace */ public String getTokenToReplaceInSnapshotPredicate() { return snapshotEnhancementToken; } /** * @return whether continuous log mining is enabled */ public boolean isContinuousMining() { return logMiningContinuousMine; } /** * @return the duration that archive logs are scanned for log mining */ public Duration getLogMiningArchiveLogRetention() { return logMiningArchiveLogRetention; } /** * * @return int The minimum SCN interval used when mining redo/archive logs */ public int getLogMiningBatchSizeMin() { return logMiningBatchSizeMin; } /** * * @return int Number of actual records that will be fetched from the log mining contents view */ public int getLogMiningViewFetchSize() { return logMiningViewFetchSize; } /** * * @return int The maximum SCN interval used when mining redo/archive logs */ public int getLogMiningBatchSizeMax() { return logMiningBatchSizeMax; } /** * * @return int Scn gap size for SCN gap detection */ public int getLogMiningScnGapDetectionGapSizeMin() { return logMiningScnGapDetectionGapSizeMin; } /** * * @return int Time interval for SCN gap detection */ public int getLogMiningScnGapDetectionTimeIntervalMaxMs() { return logMiningScnGapDetectionTimeIntervalMaxMs; } /** * * @return int The minimum sleep time used when mining redo/archive logs */ public Duration getLogMiningSleepTimeMin() { return logMiningSleepTimeMin; } /** * * @return int The maximum sleep time used when mining redo/archive logs */ public Duration getLogMiningSleepTimeMax() { return logMiningSleepTimeMax; } /** * * @return int The default sleep time used when mining redo/archive logs */ public Duration getLogMiningSleepTimeDefault() { return logMiningSleepTimeDefault; } /** * * @return int The increment in sleep time when doing auto-tuning while mining redo/archive logs */ public Duration getLogMiningSleepTimeIncrement() { return logMiningSleepTimeIncrement; } /** * @return the duration for which long running transactions are permitted in the transaction buffer between log switches */ public Duration getLogMiningTransactionRetention() { return logMiningTransactionRetention; } /** * @return true if the connector is to mine archive logs only, false to mine all logs. */ public boolean isArchiveLogOnlyMode() { return archiveLogOnlyMode; } /** * @return the duration that archive log only will use to wait between polling scn availability */ public Duration getArchiveLogOnlyScnPollTime() { return archiveLogOnlyScnPollTime; } /** * @return true if LOB fields are to be captured; false otherwise to not capture LOB fields. */ public boolean isLobEnabled() { return lobEnabled; } /** * @return User names to exclude from the LogMiner query */ public Set<String> getLogMiningUsernameExcludes() { return logMiningUsernameExcludes; } /** * @return name of the archive destination configuration to use */ public String getLogMiningArchiveDestinationName() { return logMiningArchiveDestinationName; } /** * @return the log mining buffer type implementation to be used */ public LogMiningBufferType getLogMiningBufferType() { return logMiningBufferType; } /** * @return whether buffer cache should be dropped on connector stop. */ public boolean isLogMiningBufferDropOnStop() { return logMiningBufferDropOnStop; } /** * * @return int The default SCN interval used when mining redo/archive logs */ public int getLogMiningBatchSizeDefault() { return logMiningBatchSizeDefault; } /** * @return the maximum number of retries that should be used to resolve log filenames for mining */ public int getDefaultLogFileQueryMaxRetries() { return logMiningLogFileQueryMaxRetries; } @Override public String getConnectorName() { return Module.name(); } private Set<String> resolveRacNodes(Configuration config) { final boolean portProvided = config.hasKey(PORT.name()); final Set<String> nodes = Strings.setOf(config.getString(RAC_NODES), String::new); return nodes.stream().map(node -> { if (portProvided && !node.contains(":")) { return node + ":" + config.getInteger(PORT); } else { if (!portProvided && !node.contains(":")) { throw new DebeziumException("RAC node '" + node + "' must specify a port."); } return node; } }).collect(Collectors.toSet()); } public static int validateOutServerName(Configuration config, Field field, ValidationOutput problems) { if (ConnectorAdapter.XSTREAM.equals(ConnectorAdapter.parse(config.getString(CONNECTOR_ADAPTER)))) { return Field.isRequired(config, field, problems); } return 0; } public static int requiredWhenNoUrl(Configuration config, Field field, ValidationOutput problems) { // Validates that the field is required but only when an URL field is not present if (config.getString(URL) == null) { return Field.isRequired(config, field, problems); } return 0; } public static int requiredWhenNoHostname(Configuration config, Field field, ValidationOutput problems) { // Validates that the field is required but only when an URL field is not present if (config.getString(HOSTNAME) == null) { return Field.isRequired(config, field, problems); } return 0; } public static int validateBufferLocation(Configuration config, Field field, ValidationOutput problems) { // Log error if this field is provided in the configuration since its no longer valid and has been removed final LogMiningBufferType bufferType = LogMiningBufferType.parse(config.getString(LOG_MINING_BUFFER_TYPE)); if (bufferType.isInfinispan()) { final String location = config.getString(LOG_MINING_BUFFER_LOCATION); if (!Strings.isNullOrEmpty(location)) { problems.accept(field, location, "Configuration option is no longer valid, please use 'log.mining.buffer.infinispan.cache.*' options"); return 1; } } return 0; } public static int validateRacNodes(Configuration config, Field field, ValidationOutput problems) { int errors = 0; if (ConnectorAdapter.LOG_MINER.equals(ConnectorAdapter.parse(config.getString(CONNECTOR_ADAPTER)))) { // If no "database.port" is specified, guarantee that "rac.nodes" (if not empty) specifies the // port designation for each comma-delimited value. final boolean portProvided = config.hasKey(PORT.name()); if (!portProvided) { final Set<String> racNodes = Strings.setOf(config.getString(RAC_NODES), String::new); for (String racNode : racNodes) { String[] parts = racNode.split(":"); if (parts.length == 1) { problems.accept(field, racNode, "Must be specified as 'ip/hostname:port' since no 'database.port' is provided"); errors++; } } } } return errors; } private static int validateLogMiningBufferType(Configuration config, Field field, ValidationOutput problems) { final LogMiningBufferType bufferType = LogMiningBufferType.parse(config.getString(LOG_MINING_BUFFER_TYPE)); if (LogMiningBufferType.INFINISPAN.equals(bufferType)) { LOGGER.warn("Value '{}' of configuration option '{}' is deprecated and should be replaced with '{}'", LogMiningBufferType.INFINISPAN.getValue(), LOG_MINING_BUFFER_TYPE.name(), LogMiningBufferType.INFINISPAN_EMBEDDED.getValue()); } if (LogMiningBufferType.INFINISPAN_REMOTE.equals(bufferType)) { // Must supply the Hotrod server list property as a minimum when using Infinispan cluster mode final String serverList = config.getString(RemoteInfinispanLogMinerEventProcessor.HOTROD_SERVER_LIST); if (Strings.isNullOrEmpty(serverList)) { LOGGER.error("The option '{}' must be supplied when using the buffer type '{}'", RemoteInfinispanLogMinerEventProcessor.HOTROD_SERVER_LIST, bufferType.name()); return 1; } } return 0; } public static int validateLogMiningInfinispanCacheConfiguration(Configuration config, Field field, ValidationOutput problems) { final LogMiningBufferType bufferType = LogMiningBufferType.parse(config.getString(LOG_MINING_BUFFER_TYPE)); int errors = 0; if (bufferType.isInfinispan()) { errors = Field.isRequired(config, field, problems); } return errors; } }
package com.imcode.imcms.domain.service.api; import com.imcode.imcms.WebAppSpringTestConfig; import com.imcode.imcms.components.datainitializer.LanguageDataInitializer; import com.imcode.imcms.components.datainitializer.MenuDataInitializer; import com.imcode.imcms.components.datainitializer.VersionDataInitializer; import com.imcode.imcms.domain.dto.DocumentDTO; import com.imcode.imcms.domain.dto.MenuDTO; import com.imcode.imcms.domain.dto.MenuItemDTO; import com.imcode.imcms.domain.service.CommonContentService; import com.imcode.imcms.domain.service.DocumentService; import com.imcode.imcms.domain.service.MenuService; import com.imcode.imcms.mapping.jpa.doc.VersionRepository; import com.imcode.imcms.model.CommonContent; import com.imcode.imcms.persistence.entity.Menu; import com.imcode.imcms.persistence.entity.Meta; import com.imcode.imcms.persistence.entity.Version; import com.imcode.imcms.persistence.repository.MenuRepository; import imcode.server.Imcms; import imcode.server.user.UserDomainObject; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; import java.util.List; import java.util.stream.IntStream; import static com.imcode.imcms.persistence.entity.Meta.DisabledLanguageShowMode.DO_NOT_SHOW; import static com.imcode.imcms.persistence.entity.Meta.DisabledLanguageShowMode.SHOW_IN_DEFAULT_LANGUAGE; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; @Transactional public class MenuServiceTest extends WebAppSpringTestConfig { private static final int WORKING_VERSION_NO = 0; private static final int DOC_ID = 1001; @Autowired private MenuService menuService; @Autowired private MenuDataInitializer menuDataInitializer; @Autowired private MenuRepository menuRepository; @Autowired private VersionDataInitializer versionDataInitializer; @Autowired private VersionRepository versionRepository; @Autowired private LanguageDataInitializer languageDataInitializer; @Autowired private DocumentService<DocumentDTO> documentService; @Autowired private CommonContentService commonContentService; @BeforeEach public void setUp() { final UserDomainObject user = new UserDomainObject(1); user.setLanguageIso639_2("eng"); Imcms.setUser(user); } @AfterEach public void cleanUpData() { menuDataInitializer.cleanRepositories(); versionDataInitializer.cleanRepositories(); languageDataInitializer.cleanRepositories(); Imcms.removeUser(); } @Test public void getMenuItemsOf_When_MenuNoAndDocId_Expect_ResultEqualsExpectedMenuItems() { getMenuItemsOf_When_MenuNoAndDocId_Expect_ResultEqualsExpectedMenuItems(true); } @Test public void getMenuItemsOf_When_MenuDoesntExist_Expect_EmptyList() { getMenuItemsOf_When_MenuDoesntExist_Expect_EmptyList(true); } @Test public void saveFrom_When_MenuWithItems_Expect_SameSizeAndResultsEquals() { saveFrom_Expect_SameSizeAndResultsEquals(true); } @Test public void saveFrom_When_MenuDoesntExist_Expect_SameSizeAndResultsEquals() { saveFrom_Expect_SameSizeAndResultsEquals(false); } @Test public void getPublicMenuItemsOf_When_MenuNoAndDocId_Expect_ResultEqualsExpectedMenuItems() { getMenuItemsOf_When_MenuNoAndDocId_Expect_ResultEqualsExpectedMenuItems(false); } @Test public void getPublicMenuItemsOf_When_MenuDoesntExist_Expect_EmptyList() { getMenuItemsOf_When_MenuDoesntExist_Expect_EmptyList(false); } @Test public void saveMenu_When_ExistBefore_Expect_NoDuplicatedDataAndCorrectSave() { menuDataInitializer.cleanRepositories(); versionDataInitializer.createData(WORKING_VERSION_NO, DOC_ID); final MenuDTO menuDTO = menuDataInitializer.createData(true); final List<MenuItemDTO> menuItemBefore = menuDTO.getMenuItems(); MenuDTO savedMenu = menuService.saveFrom(menuDTO); List<MenuItemDTO> menuItemAfter = savedMenu.getMenuItems(); assertEquals(menuItemBefore.size(), menuItemAfter.size()); assertEquals(menuItemBefore, menuItemAfter); final List<MenuItemDTO> menuItems = menuDTO.getMenuItems(); final MenuItemDTO removed = menuItems.remove(0); final int newSize = menuItems.size(); assertNotNull(removed); savedMenu = menuService.saveFrom(menuDTO); menuItemAfter = savedMenu.getMenuItems(); assertEquals(newSize, menuItemAfter.size()); } @Test public void deleteByDocId() { assertTrue(menuRepository.findAll().isEmpty()); final int docId = 1001; IntStream.range(0, 3).forEach((versionIndex) -> { versionDataInitializer.createData(versionIndex, docId); IntStream.range(1, 5).forEach((menuIndex) -> menuDataInitializer.createData(true, menuIndex, versionIndex, docId) ); }); assertFalse(menuRepository.findAll().isEmpty()); menuService.deleteByDocId(docId); assertTrue(menuRepository.findAll().isEmpty()); } @Test public void createVersionedContent() { final boolean withMenuItems = true; final Menu workingVersionMenu = menuDataInitializer.createDataEntity(withMenuItems); final Version workingVersion = versionRepository.findByDocIdAndNo(DOC_ID, WORKING_VERSION_NO); final int latestVersionNo = WORKING_VERSION_NO + 1; final Version latestVersion = versionDataInitializer.createData(latestVersionNo, DOC_ID); menuService.createVersionedContent(workingVersion, latestVersion); final List<Menu> menuByVersion = menuRepository.findByVersion(latestVersion); assertEquals(1, menuByVersion.size()); final Menu menu = menuByVersion.get(0); assertEquals(menu.getNo(), workingVersionMenu.getNo()); assertEquals(menu.getMenuItems().size(), workingVersionMenu.getMenuItems().size()); } @Test public void getMenuItems_MenuNoAndDocIdAndUserLanguage_Expect_MenuItemsIsReturnedWithTitleOfUsersLanguage() { final MenuDTO menu = menuDataInitializer.createData(true); final DocumentDTO documentDTO = documentService.get(menu.getDocId()); documentDTO.setDisabledLanguageShowMode(SHOW_IN_DEFAULT_LANGUAGE); documentService.save(documentDTO); final String language = Imcms.getUser().getLanguage(); final List<MenuItemDTO> menuItems = menuService .getMenuItems(menu.getMenuIndex(), menu.getDocId(), language); assertEquals(menu.getMenuItems().size(), menuItems.size()); } @Test public void getMenuItems_When_UserSetEnLangAndMenuDisableEn_ShowModeSHOW_IN_DEFAULT_LANGUAGE_Expect_CorrectEntities() { final MenuDTO menu = menuDataInitializer.createData(true, 1); final String langUser = Imcms.getUser().getLanguage(); final String enableLanguage = languageDataInitializer.createData().get(1).getCode(); //0 -en setUpMenuItem(menu, SHOW_IN_DEFAULT_LANGUAGE, enableLanguage); assertFalse(menuService.getMenuItems(menu.getMenuIndex(), menu.getDocId(), langUser).isEmpty()); assertEquals(2, menuService.getMenuItems(menu.getMenuIndex(), menu.getDocId(), langUser).size()); } @Test public void getMenuItems_When_UserSetEnLangAndMenuDisableEn_ShowModeDONOTSHOW_Expect_CorrectEntities() { final MenuDTO menu = menuDataInitializer.createData(true, 1); final String langUser = Imcms.getUser().getLanguage(); final String enableLanguage = languageDataInitializer.createData().get(1).getCode(); //0 -en setUpMenuItem(menu, DO_NOT_SHOW, enableLanguage); assertFalse(menuService.getMenuItems(menu.getMenuIndex(), menu.getDocId(), langUser).isEmpty()); assertEquals(2, menuService.getMenuItems(menu.getMenuIndex(), menu.getDocId(), langUser).size()); } @Test public void getMenuItems_When_UserSetSvLangAndMenuDisableEN_ShowModeDO_NOT_SHOW_Expect_CorrectEntitiesSize() { final UserDomainObject user = new UserDomainObject(1); user.setLanguageIso639_2("swe"); Imcms.setUser(user); final MenuDTO menu = menuDataInitializer.createData(true, 1); final String langUser = Imcms.getUser().getLanguage(); final String enableLanguage = languageDataInitializer.createData().get(1).getCode(); //0 -en setUpMenuItem(menu, DO_NOT_SHOW, enableLanguage); assertFalse(menuService.getMenuItems(menu.getMenuIndex(), menu.getDocId(), langUser).isEmpty()); assertEquals(2, menuService.getMenuItems(menu.getMenuIndex(), menu.getDocId(), langUser).size()); } @Test public void getMenuItems_When_UserSetSvLangAndMenuDisableEN_ShowModeSHOW_ON_DEFAULT_Expect_CorrectEntitiesSize() { final UserDomainObject user = new UserDomainObject(1); user.setLanguageIso639_2("swe"); Imcms.setUser(user); final MenuDTO menu = menuDataInitializer.createData(true, 1); final String langUser = Imcms.getUser().getLanguage(); final String enableLanguage = languageDataInitializer.createData().get(1).getCode(); //0 -en setUpMenuItem(menu, SHOW_IN_DEFAULT_LANGUAGE, enableLanguage); assertFalse(menuService.getMenuItems(menu.getMenuIndex(), menu.getDocId(), langUser).isEmpty()); assertEquals(2, menuService.getMenuItems(menu.getMenuIndex(), menu.getDocId(), langUser).size()); } @Test public void getMenu_Expect_CorrectEntities() { menuDataInitializer.createData(true, 1); menuDataInitializer.createData(true, 2); List<Menu> foundMenus = menuService.getAll(); assertNotNull(foundMenus); assertEquals(2, foundMenus.size()); } private void getMenuItemsOf_When_MenuNoAndDocId_Expect_ResultEqualsExpectedMenuItems(boolean isAll) { final MenuDTO menu = menuDataInitializer.createData(true); final DocumentDTO documentDTO = documentService.get(menu.getDocId()); documentDTO.setDisabledLanguageShowMode(SHOW_IN_DEFAULT_LANGUAGE); documentService.save(documentDTO); final String code = languageDataInitializer.createData().get(0).getCode(); final List<MenuItemDTO> menuItemDtosOfMenu = isAll ? menuService.getVisibleMenuItems(menu.getMenuIndex(), menu.getDocId(), code) : menuService.getPublicMenuItems(menu.getMenuIndex(), menu.getDocId(), code); assertEquals(menuDataInitializer.getMenuItemDtoList().size(), menuItemDtosOfMenu.size()); assertEquals(menuDataInitializer.getMenuItemDtoList().get(0).getChildren().size(), menuItemDtosOfMenu.get(0).getChildren().size()); assertEquals(menuDataInitializer.getMenuItemDtoList().get(0).getChildren().get(0).getChildren().size(), menuItemDtosOfMenu.get(0).getChildren().get(0).getChildren().size()); } private void setUpMenuItem(MenuDTO menu, Meta.DisabledLanguageShowMode showMode, String enableLang) { final List<MenuItemDTO> menuItems = menu.getMenuItems(); final DocumentDTO menuItemDoc = documentService.get(menuItems.get(0).getDocumentId()); menuItemDoc.setDisabledLanguageShowMode(showMode); for (CommonContent content : menuItemDoc.getCommonContents()) { content.setEnabled(content.getLanguage().getCode().equals(enableLang)); } commonContentService.save(menuItemDoc.getId(), menuItemDoc.getCommonContents()); } private void getMenuItemsOf_When_MenuDoesntExist_Expect_EmptyList(boolean isAll) { final String code = languageDataInitializer.createData().get(0).getCode(); versionDataInitializer.createData(WORKING_VERSION_NO, DOC_ID); final List<MenuItemDTO> menuItems = isAll ? menuService.getVisibleMenuItems(WORKING_VERSION_NO, DOC_ID, code) : menuService.getPublicMenuItems(WORKING_VERSION_NO, DOC_ID, code); assertTrue(menuItems.isEmpty()); } private void saveFrom_Expect_SameSizeAndResultsEquals(boolean menuExist) { final MenuDTO menuDTO = menuDataInitializer.createData(true); final List<MenuItemDTO> menuItemBefore = menuDTO.getMenuItems(); if (!menuExist) { menuDataInitializer.cleanRepositories(); versionDataInitializer.createData(WORKING_VERSION_NO, DOC_ID); } final MenuDTO savedMenu = menuService.saveFrom(menuDTO); final List<MenuItemDTO> menuItemAfter = savedMenu.getMenuItems(); assertEquals(menuItemBefore.size(), menuItemAfter.size()); assertEquals(menuItemBefore, menuItemAfter); } }
package com.jaeksoft.searchlib.test.rest; import com.jaeksoft.searchlib.test.IntegrationTest; import com.jaeksoft.searchlib.webservice.CommonListResult; import com.jaeksoft.searchlib.webservice.CommonResult; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runners.MethodSorters; import org.xml.sax.SAXException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.xml.parsers.ParserConfigurationException; import javax.xml.xpath.XPathExpressionException; import java.io.IOException; import static org.junit.Assert.*; @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class RestWebCrawlerTest extends CommonRestAPI { public final static String path = "/services/rest/index/{index_name}/crawler/web/sitemap"; public final static String siteMapUrl = "http: @Test public void testA_AddSiteMap() throws IllegalStateException, IOException, XPathExpressionException, SAXException, ParserConfigurationException { Response response = client() .path(path, IntegrationTest.INDEX_NAME) .query("site_map_url", siteMapUrl) .accept(MediaType.APPLICATION_JSON).put(null); checkCommonResult(response, CommonResult.class, 200); } @Test public void testB_testGetSiteMap() throws IllegalStateException, IOException, XPathExpressionException, SAXException, ParserConfigurationException { Response response = client() .path(path, IntegrationTest.INDEX_NAME) .accept(MediaType.APPLICATION_JSON).get(); CommonListResult<String> cmd = checkCommonResult(response, CommonListResult.class, 200); assertNotNull(cmd.items.toArray()); assertEquals(cmd.items.toArray()[0], siteMapUrl); } @Test public void testC_DeleteSiteMap() throws IllegalStateException, IOException, XPathExpressionException, SAXException, ParserConfigurationException { Response response = client() .path(path, IntegrationTest.INDEX_NAME) .query("site_map_url", siteMapUrl) .accept(MediaType.APPLICATION_JSON).delete(); checkCommonResult(response, CommonResult.class, 200); } @Test public void testD_DeleteNoneSiteMap() throws IllegalStateException, IOException, XPathExpressionException, SAXException, ParserConfigurationException { Response response = client() .path(path, IntegrationTest.INDEX_NAME) .query("site_map_url", siteMapUrl) .accept(MediaType.APPLICATION_JSON).delete(); checkCommonResult(response, CommonResult.class, 200); } @Test public void testE_GetSiteMap() throws IllegalStateException, IOException, XPathExpressionException, SAXException, ParserConfigurationException { Response response = client() .path(path, IntegrationTest.INDEX_NAME) .accept(MediaType.APPLICATION_JSON).get(); checkCommonResult(response, CommonListResult.class, 200); } }
package org.pentaho.reporting.designer.core.editor; import java.util.Arrays; import java.util.HashMap; import java.util.Locale; import java.util.Map; import javax.swing.JComponent; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; import javax.swing.UIDefaults; import javax.swing.UIManager; import org.pentaho.reporting.designer.core.ReportDesignerContext; import org.pentaho.reporting.designer.core.actions.global.PasteAction; import org.pentaho.reporting.designer.core.actions.report.AddDataFactoryAction; import org.pentaho.reporting.designer.core.editor.structuretree.ReportFunctionNode; import org.pentaho.reporting.designer.core.editor.structuretree.ReportParametersNode; import org.pentaho.reporting.designer.core.editor.structuretree.ReportQueryNode; import org.pentaho.reporting.designer.core.editor.structuretree.SubReportParametersNode; import org.pentaho.reporting.designer.core.settings.WorkspaceSettings; import org.pentaho.reporting.engine.classic.core.Band; import org.pentaho.reporting.engine.classic.core.CompoundDataFactory; import org.pentaho.reporting.engine.classic.core.CrosstabCellBody; import org.pentaho.reporting.engine.classic.core.CrosstabColumnGroup; import org.pentaho.reporting.engine.classic.core.CrosstabGroup; import org.pentaho.reporting.engine.classic.core.CrosstabOtherGroup; import org.pentaho.reporting.engine.classic.core.CrosstabRowGroup; import org.pentaho.reporting.engine.classic.core.DataFactory; import org.pentaho.reporting.engine.classic.core.Element; import org.pentaho.reporting.engine.classic.core.Group; import org.pentaho.reporting.engine.classic.core.MasterReport; import org.pentaho.reporting.engine.classic.core.RelationalGroup; import org.pentaho.reporting.engine.classic.core.RootLevelBand; import org.pentaho.reporting.engine.classic.core.SubReport; import org.pentaho.reporting.engine.classic.core.function.Expression; import org.pentaho.reporting.engine.classic.core.metadata.DataFactoryMetaData; import org.pentaho.reporting.engine.classic.core.metadata.DataFactoryRegistry; import org.pentaho.reporting.engine.classic.core.metadata.GroupedMetaDataComparator; import org.pentaho.reporting.engine.classic.core.parameters.ParameterDefinitionEntry; import org.pentaho.reporting.engine.classic.core.parameters.ReportParameterDefinition; import org.pentaho.reporting.libraries.base.util.ObjectUtilities; /** * Todo: Document Me * * @author Thomas Morgner */ public class ContextMenuUtility { private ContextMenuUtility() { } public static JPopupMenu getMenu(final ReportDesignerContext designerContext, final Object context) { if (context == null || context instanceof MasterReport) // This check assumes that we've click on a report band see JIRA PRD-1076 { return designerContext.getPopupMenu("popup-ReportDefinition"); // NON-NLS } final ReportRenderContext activeContext = designerContext.getActiveContext(); if (activeContext != null) { if (context == activeContext.getReportDefinition()) { return designerContext.getPopupMenu("popup-ReportDefinition");// NON-NLS } } if (context instanceof SubReport) { return designerContext.getPopupMenu("popup-SubReport");// NON-NLS } if (context instanceof CompoundDataFactory) { return createDataSourcePopup(designerContext); } if (context instanceof DataFactory) { return designerContext.getPopupMenu("popup-DataSource");// NON-NLS } if (context instanceof ReportFunctionNode) { return designerContext.getPopupMenu("popup-Expressions");// NON-NLS } if (context instanceof ReportQueryNode) { final ReportQueryNode rqn = (ReportQueryNode) context; if (rqn.isAllowEdit()) { return designerContext.getPopupMenu("popup-Query");// NON-NLS } return designerContext.getPopupMenu("popup-Inherited-Query");// NON-NLS } if (context instanceof Expression) { return designerContext.getPopupMenu("popup-Expression");// NON-NLS } if (context instanceof RootLevelBand) { return designerContext.getPopupMenu("popup-RootLevelBand");// NON-NLS } if (context instanceof RelationalGroup) { return designerContext.getPopupMenu("popup-RelationalGroup");// NON-NLS } if (context instanceof CrosstabGroup) { return designerContext.getPopupMenu("popup-CrosstabGroup");// NON-NLS } if (context instanceof CrosstabOtherGroup) { return designerContext.getPopupMenu("popup-CrosstabOtherGroup");// NON-NLS } if (context instanceof CrosstabRowGroup) { return designerContext.getPopupMenu("popup-CrosstabRowGroup");// NON-NLS } if (context instanceof CrosstabColumnGroup) { return designerContext.getPopupMenu("popup-CrosstabColumnGroup");// NON-NLS } if (context instanceof CrosstabCellBody) { return designerContext.getPopupMenu("popup-CrosstabCellBody");// NON-NLS } if (context instanceof Group) { return designerContext.getPopupMenu("popup-Group");// NON-NLS } if (context instanceof Band) { return designerContext.getPopupMenu("popup-Band");// NON-NLS } if (context instanceof Element) { final Element element = (Element) context; final JPopupMenu popup = designerContext.getPopupMenu("popup-" + element.getElementTypeName());// NON-NLS if (popup != null) { return popup; } return designerContext.getPopupMenu("popup-Element");// NON-NLS } if (context instanceof ReportParameterDefinition) { return designerContext.getPopupMenu("popup-Parameters");// NON-NLS } if (context instanceof ParameterDefinitionEntry) { return designerContext.getPopupMenu("popup-Parameter");// NON-NLS } if (context instanceof ReportParametersNode) { return designerContext.getPopupMenu("popup-Parameters");// NON-NLS } if (context instanceof SubReportParametersNode) { return designerContext.getPopupMenu("popup-SubReportParameters");// NON-NLS } return null; } public static JPopupMenu createDataSourcePopup(final ReportDesignerContext designerContext) { final JPopupMenu insertDataSourcesMenu = new JPopupMenu(); final PasteAction action = new PasteAction(); action.setReportDesignerContext(designerContext); insertDataSourcesMenu.add(action); insertDataSourcesMenu.addSeparator(); createDataSourceMenu(designerContext, insertDataSourcesMenu); return insertDataSourcesMenu; } public static void createDataSourceMenu(final ReportDesignerContext designerContext, final JComponent insertDataSourcesMenu) { JMenu subMenu = null; UIDefaults uiDefs = UIManager.getDefaults(); uiDefs.put("Tree.leftChildIndent" , new Integer( 0 ) ); final Map<String, Boolean> groupingMap = new HashMap<String, Boolean>(); final DataFactoryMetaData[] datas = DataFactoryRegistry.getInstance().getAll(); for (int i = 0; i < datas.length; i++) { final DataFactoryMetaData data = datas[i]; if (data.isHidden()) { continue; } if (WorkspaceSettings.getInstance().isShowExpertItems() == false && data.isExpert()) { continue; } if (WorkspaceSettings.getInstance().isShowDeprecatedItems() == false && data.isDeprecated()) { continue; } if (WorkspaceSettings.getInstance().isExperimentalFeaturesVisible() == false && data.isExperimental()) { continue; } if (data.isEditorAvailable() == false) { continue; } final String currentGrouping = data.getGrouping(Locale.getDefault()); groupingMap.put(currentGrouping, groupingMap.containsKey(currentGrouping)); } Arrays.sort(datas, new GroupedMetaDataComparator()); Object grouping = null; boolean firstElement = true; for (int i = 0; i < datas.length; i++) { final DataFactoryMetaData data = datas[i]; if (data.isHidden()) { continue; } if (WorkspaceSettings.getInstance().isShowExpertItems() == false && data.isExpert()) { continue; } if (WorkspaceSettings.getInstance().isShowDeprecatedItems() == false && data.isDeprecated()) { continue; } if (WorkspaceSettings.getInstance().isExperimentalFeaturesVisible() == false && data.isExperimental()) { continue; } if (data.isEditorAvailable() == false) { continue; } final String currentGrouping = data.getGrouping(Locale.getDefault()); final boolean isMultiGrouping = groupingMap.get(currentGrouping); if (firstElement == false) { if (ObjectUtilities.equal(currentGrouping, grouping) == false) { grouping = currentGrouping; if (isMultiGrouping) { subMenu = new JMenu(currentGrouping); insertDataSourcesMenu.add(subMenu); } } } else { firstElement = false; grouping = currentGrouping; if (isMultiGrouping) { subMenu = new JMenu(currentGrouping); insertDataSourcesMenu.add(subMenu); } } final AddDataFactoryAction action = new AddDataFactoryAction(data); action.setReportDesignerContext(designerContext); if (isMultiGrouping) { //noinspection ConstantConditions subMenu.add(new JMenuItem(action)); } else { insertDataSourcesMenu.add(new JMenuItem(action)); } } } }
package de.frosner.datagenerator.gui.main; import static org.fest.assertions.Fail.fail; import java.awt.AWTException; import java.awt.Robot; import java.awt.event.ActionEvent; import java.io.File; import javax.swing.JButton; import javax.swing.JTextField; import javax.swing.filechooser.FileFilter; import org.fest.swing.edt.GuiActionRunner; import org.fest.swing.edt.GuiTask; public final class SwingMenuTestUtil { private static final int FILE_CHOOSER_OPEN_DELAY = 500; private static final int ROBOT_DELAY = 75; private SwingMenu _menu; SwingMenuTestUtil(SwingMenu swingMenu) { _menu = swingMenu; GuiActionRunner.execute(new GuiTask() { @Override protected void executeInEDT() { _menu.setVisible(true); _menu.toFront(); } }); } void clickButton(final JButton button) { GuiActionRunner.execute(new GuiTask() { @Override protected void executeInEDT() { _menu.actionPerformed(new ActionEvent(button, 1, "")); } }); } void selectFeature(final int i) { GuiActionRunner.execute(new GuiTask() { @Override protected void executeInEDT() { _menu._featureList.setSelectedIndex(i); } }); } void selectFile(final File file) { GuiActionRunner.execute(new GuiTask() { @Override protected void executeInEDT() { _menu._exportFileDialog.setSelectedFile(file); } }); } void enterText(final JTextField textField, final String text) { GuiActionRunner.execute(new GuiTask() { @Override protected void executeInEDT() { textField.setText(text); } }); } void setExportFileFilter(final FileFilter filter) { GuiActionRunner.execute(new GuiTask() { @Override protected void executeInEDT() { _menu._exportFileDialog.setFileFilter(filter); } }); } void selectFileUsingFileChooserDialog(final File file) { new Thread(new Runnable() { @Override public void run() { Robot robot; try { robot = new Robot(); robot.delay(FILE_CHOOSER_OPEN_DELAY); GuiActionRunner.execute(new GuiTask() { @Override protected void executeInEDT() { _menu._exportFileDialog.setSelectedFile(file); _menu._exportFileDialog.approveSelection(); } }); } catch (AWTException e) { e.printStackTrace(); } } }).start(); clickButton(_menu._exportFileButton); } void addGaussianFeature(String name, String mean, String sigma) { enterText(_menu._gaussianNameField, name); enterText(_menu._gaussianMeanField, mean); enterText(_menu._gaussianSigmaField, sigma); clickButton(_menu._addFeatureButton); } public static void delay(int ms) { try { new Robot().delay(ms); } catch (AWTException e) { fail(); e.printStackTrace(); } } public static void delay() { delay(ROBOT_DELAY); } }
package org.opencds.cqf.cql.engine.fhir.retrieve; import ca.uhn.fhir.context.FhirContext; import org.hl7.fhir.dstu3.model.*; import org.opencds.cqf.cql.engine.fhir.searchparam.SearchParameterMap; import org.opencds.cqf.cql.engine.fhir.searchparam.SearchParameterResolver; import org.opencds.cqf.cql.engine.runtime.Code; import org.opencds.cqf.cql.engine.runtime.Interval; import org.opencds.cqf.cql.engine.terminology.TerminologyProvider; import java.net.URLDecoder; import java.util.ArrayList; import java.util.List; public class Dstu3FhirQueryGenerator extends BaseFhirQueryGenerator { public Dstu3FhirQueryGenerator(SearchParameterResolver searchParameterResolver, TerminologyProvider terminologyProvider) { super(searchParameterResolver, terminologyProvider, FhirContext.forDstu3()); } public List<String> generateFhirQueries(DataRequirement dataRequirement, CapabilityStatement capabilityStatement) { List<String> queries = new ArrayList<>(); String codePath = null; List<Code> codes = null; String valueSet = null; if (dataRequirement.hasCodeFilter()) { for (org.hl7.fhir.dstu3.model.DataRequirement.DataRequirementCodeFilterComponent codeFilterComponent : dataRequirement.getCodeFilter()) { if (!codeFilterComponent.hasPath()) { continue; } codePath = codeFilterComponent.getPath(); // TODO: What to do if/when System is not provided... if (codeFilterComponent.hasValueCode()) { List<org.hl7.fhir.dstu3.model.CodeType> codeFilterValueCode = codeFilterComponent.getValueCode(); for (CodeType codeType : codeFilterValueCode) { Code code = new Code(); code.setCode(codeType.asStringValue()); codes.add(code); } } if (codeFilterComponent.hasValueCoding()) { codes = new ArrayList<Code>(); List<org.hl7.fhir.dstu3.model.Coding> codeFilterValueCodings = codeFilterComponent.getValueCoding(); for (Coding coding : codeFilterValueCodings) { if (coding.hasCode()) { Code code = new Code(); code.setSystem(coding.getSystem()); code.setCode(coding.getCode()); codes.add(code); } } } if (codeFilterComponent.hasValueCodeableConcept()) { List<org.hl7.fhir.dstu3.model.CodeableConcept> codeFilterValueCodeableConcepts = codeFilterComponent.getValueCodeableConcept(); for (CodeableConcept codeableConcept : codeFilterValueCodeableConcepts) { List<org.hl7.fhir.dstu3.model.Coding> codeFilterValueCodeableConceptCodings = codeableConcept.getCoding(); for (Coding coding : codeFilterValueCodeableConceptCodings) { if (coding.hasCode()) { Code code = new Code(); code.setSystem(coding.getSystem()); code.setCode(coding.getCode()); codes.add(code); } } } } if (codeFilterComponent.hasValueSet()) { if (codeFilterComponent.getValueSetReference().getReference() instanceof String) { valueSet = ((Reference)codeFilterComponent.getValueSet()).getReference(); } else if (codeFilterComponent.getValueSetReference() instanceof Reference) { valueSet = codeFilterComponent.getValueSetReference().getReference(); } } } } String datePath = null; String dateLowPath = null; String dateHighPath = null; Interval dateRange = null; // if (dataRequirement.hasDateFilter()) { // for (org.hl7.fhir.dstu3.model.DataRequirement.DataRequirementDateFilterComponent dateFilterComponent : dataRequirement.getDateFilter()) { // if (dateFilterComponent.hasPath() && dateFilterComponent.hasSearchParam()) { // throw new UnsupportedOperationException(String.format("Either a path or a searchParam must be provided, but not both")); // if (dateFilterComponent.hasPath()) { // datePath = dateFilterComponent.getPath(); // } else if (dateFilterComponent.hasSearchParam()) { // datePath = dateFilterComponent.getSearchParam(); // Type dateFilterValue = dateFilterComponent.getValue(); // if (dateFilterValue instanceof DateTimeType) { // } else if (dateFilterValue instanceof Duration) { // } else if (dateFilterValue instanceof Period) { List<SearchParameterMap> maps = new ArrayList<SearchParameterMap>(); maps = setupQueries(null, null, null, dataRequirement.getType(), null, codePath, codes, valueSet, datePath, null, null, null); for (SearchParameterMap map : maps) { String query = null; try { query = URLDecoder.decode(map.toNormalizedQueryString(fhirContext), "UTF-8"); } catch (Exception ex) { query = map.toNormalizedQueryString(fhirContext); } queries.add(dataRequirement.getType() + query); } return queries; } }
package javasnack.ojcp.se8gold.chapter10; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.Test; public class Test10ThreadBasics { static class ThreadA extends Thread { final CountDownLatch done; final int count; ThreadA(CountDownLatch done, final int count) { this.done = done; this.count = count; } @Override public void run() { for (int i = 0; i < count; i++) { System.out.println("thread[" + Thread.currentThread().getName() + "], i=" + i); done.countDown(); } } } @Test public void testThreadByExtendsThread() throws InterruptedException { final CountDownLatch l0 = new CountDownLatch(10); final Thread t1 = new ThreadA(l0, 5); final Thread t2 = new ThreadA(l0, 5); t1.start(); t2.start(); assertThat(l0.await(10, TimeUnit.SECONDS)).isTrue(); assertThatThrownBy(() -> { t1.start(); }).isInstanceOf(IllegalThreadStateException.class); assertThatThrownBy(() -> { t2.start(); }).isInstanceOf(IllegalThreadStateException.class); } static class ThreadB implements Runnable { final CountDownLatch done; final int count; ThreadB(CountDownLatch done, final int count) { this.done = done; this.count = count; } @Override public void run() { for (int i = 0; i < count; i++) { System.out.println("thread[" + Thread.currentThread().getName() + "], i=" + i); done.countDown(); } } } @Test public void testThreadByImplementsRunnable() throws InterruptedException { final CountDownLatch l0 = new CountDownLatch(10); final Thread t1 = new Thread(new ThreadB(l0, 5)); final Thread t2 = new Thread(new ThreadB(l0, 5)); t1.start(); t2.start(); assertThat(l0.await(10, TimeUnit.SECONDS)).isTrue(); assertThatThrownBy(() -> { t1.start(); }).isInstanceOf(IllegalThreadStateException.class); assertThatThrownBy(() -> { t2.start(); }).isInstanceOf(IllegalThreadStateException.class); } @Test public void testThreadByLambdaExpression() throws InterruptedException { final CountDownLatch l0 = new CountDownLatch(10); final Thread t1 = new Thread(new Runnable() { @Override public void run() { for (int i = 0; i < 5; i++) { System.out.println("thread[" + Thread.currentThread().getName() + "], i=" + i); l0.countDown(); } } }); final Thread t2 = new Thread(() -> { for (int i = 0; i < 5; i++) { System.out.println("thread[" + Thread.currentThread().getName() + "], i=" + i); l0.countDown(); } }); t1.start(); t2.start(); assertThat(l0.await(10, TimeUnit.SECONDS)).isTrue(); assertThatThrownBy(() -> { t1.start(); }).isInstanceOf(IllegalThreadStateException.class); assertThatThrownBy(() -> { t2.start(); }).isInstanceOf(IllegalThreadStateException.class); } @Test public void testThreadSleepThenJoin() throws InterruptedException { final CountDownLatch l0 = new CountDownLatch(1); final Thread t1 = new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(3_000); l0.countDown(); } catch (InterruptedException ignore) { } } }); final long started = System.currentTimeMillis(); t1.start(); t1.join(10_000); final long ended = System.currentTimeMillis(); assertThat((ended - started) >= 3_000).isTrue(); assertThat(l0.await(10, TimeUnit.SECONDS)).isTrue(); } @Test public void testThreadSleepThenInterrupt() throws InterruptedException { final CountDownLatch l0 = new CountDownLatch(1); final Thread t1 = new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(3_000); } catch (InterruptedException ignore) { l0.countDown(); } } }); final long started = System.currentTimeMillis(); t1.start(); Thread.sleep(1_500); t1.interrupt(); t1.join(10_000); final long ended = System.currentTimeMillis(); assertThat((ended - started) >= 1_500).isTrue(); assertThat((ended - started) < 3_000).isTrue(); assertThat(l0.await(10, TimeUnit.SECONDS)).isTrue(); } static class BrokenCounter { int c = 0; int getCount() { return c; } void setCount(final int v) { c = v; } } @Test public void testThreadUnsafeCounterDemo1() throws InterruptedException { final BrokenCounter c0 = new BrokenCounter(); final int loops = 10_000; final Thread incrementThread = new Thread(() -> { for (int i = 0; i < loops; i++) { final int x = c0.getCount(); c0.setCount(x + 1); } }); final Thread decrementThread = new Thread(() -> { for (int i = 0; i < loops; i++) { final int x = c0.getCount(); c0.setCount(x - 1); } }); incrementThread.start(); decrementThread.start(); incrementThread.join(10_000); decrementThread.join(10_000); /* increment/decrement * not-equal / equal assertion * -> */ System.out.println("multi-thread broken counter result: " + c0.getCount() + " (expect 0)"); } static class SynchronizedButNotAtomicCounter { int c = 0; synchronized int getCount() { return c; } synchronized void setCount(final int v) { c = v; } } @Test public void testThreadUnsafeCounterDemo2() throws InterruptedException { final SynchronizedButNotAtomicCounter c0 = new SynchronizedButNotAtomicCounter(); final int loops = 10_000; final Thread incrementThread = new Thread(() -> { for (int i = 0; i < loops; i++) { final int x = c0.getCount(); c0.setCount(x + 1); } }); final Thread decrementThread = new Thread(() -> { for (int i = 0; i < loops; i++) { final int x = c0.getCount(); c0.setCount(x - 1); } }); incrementThread.start(); decrementThread.start(); incrementThread.join(10_000); decrementThread.join(10_000); /* increment/decrement * not-equal / equal assertion * -> */ System.out.println("multi-thread synchronized but not atomic counter result: " + c0.getCount() + " (expect 0)"); } static class SynchronizedAndAtomicCounter { int c = 0; synchronized int getCount() { return c; } synchronized void increment() { c++; } synchronized void decrement() { c } } @Test public void testThreadSafeCounterDemo() throws InterruptedException { final SynchronizedAndAtomicCounter c0 = new SynchronizedAndAtomicCounter(); final int loops = 10_000; final Thread incrementThread = new Thread(() -> { for (int i = 0; i < loops; i++) { c0.increment(); } }); final Thread decrementThread = new Thread(() -> { for (int i = 0; i < loops; i++) { c0.decrement(); } }); incrementThread.start(); decrementThread.start(); incrementThread.join(10_000); decrementThread.join(10_000); assertThat(c0.getCount()).isEqualTo(0); } static class WaitAndNotifyDemo { private int a = 0; private String b; synchronized void set() { while (a != 0) { try { wait(); } catch (InterruptedException ignore) { } } notify(); a++; b = "data"; System.out.println("set() a: " + a + " b: " + b); } synchronized void print() { while (b == null) { try { wait(); } catch (InterruptedException ignore) { } } notify(); a b = null; System.out.println("print() a: " + a + " b: " + b); } } @Test public void testWaitAndNotifyDemo() throws InterruptedException { final WaitAndNotifyDemo o1 = new WaitAndNotifyDemo(); final int loops = 10; final Thread t1 = new Thread(() -> { for (int i = 0; i < loops; i++) { o1.set(); } }); final Thread t2 = new Thread(() -> { for (int i = 0; i < loops; i++) { o1.print(); } }); t1.start(); t2.start(); t1.join(10_000); t2.join(10_000); // check console output. } }
package org.echocat.unittest.utils.matchers; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.junit.Test; import javax.annotation.Nonnull; import static org.echocat.unittest.utils.TestUtils.givenDescription; import static org.echocat.unittest.utils.matchers.Strings.*; import static org.echocat.unittest.utils.matchers.Strings.endsWith; import static org.echocat.unittest.utils.matchers.Strings.startsWith; import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.assertThat; public class StringsUnitTest { @Test public void factoryMethodStartsWith() throws Exception { final Matcher<String> instance = startsWith("666"); assertThat(instance, instanceOf(Strings.class)); assertThat(((Strings<?>) instance).comparator(), sameInstance(startsWithComparator())); assertThat(((Strings<?>) instance).comparatorDescription(), equalTo("starts with")); assertThat(((Strings<?>) instance).expected(), equalTo("666")); } @Test public void factoryMethodEndsWith() throws Exception { final Matcher<String> instance = endsWith("666"); assertThat(instance, instanceOf(Strings.class)); assertThat(((Strings<?>) instance).comparator(), sameInstance(endsWithComparator())); assertThat(((Strings<?>) instance).comparatorDescription(), equalTo("ends with")); assertThat(((Strings<?>) instance).expected(), equalTo("666")); } @Test public void factoryMethodContains() throws Exception { final Matcher<String> instance = contains("666"); assertThat(instance, instanceOf(Strings.class)); assertThat(((Strings<?>) instance).comparator(), sameInstance(containsComparator())); assertThat(((Strings<?>) instance).comparatorDescription(), equalTo("contains")); assertThat(((Strings<?>) instance).expected(), equalTo("666")); } @Test public void factoryMethodMatches() throws Exception { final Matcher<String> instance = Strings.matches("666"); assertThat(instance, instanceOf(Strings.class)); assertThat(((Strings<?>) instance).comparator(), sameInstance(matchesComparator())); assertThat(((Strings<?>) instance).comparatorDescription(), equalTo("matches regular expression")); assertThat(((Strings<?>) instance).expected(), equalTo("666")); } @Test public void factoryMethodEqualsIgnoreCase() throws Exception { final Matcher<String> instance = equalsIgnoreCase("666"); assertThat(instance, instanceOf(Strings.class)); assertThat(((Strings<?>) instance).comparator(), sameInstance(equalsIgnoreCaseComparator())); assertThat(((Strings<?>) instance).comparatorDescription(), equalTo("equals ignore case")); assertThat(((Strings<?>) instance).expected(), equalTo("666")); } @Test public void factoryMethodIsEqualsIgnoreCase() throws Exception { final Matcher<String> instance = isEqualIgnoreCase("666"); assertThat(instance, instanceOf(Strings.class)); assertThat(((Strings<?>) instance).comparator(), sameInstance(equalsIgnoreCaseComparator())); assertThat(((Strings<?>) instance).comparatorDescription(), equalTo("equals ignore case")); assertThat(((Strings<?>) instance).expected(), equalTo("666")); } @Test public void factoryMethodIsEqualToIgnoreCase() throws Exception { final Matcher<String> instance = isEqualToIgnoreCase("666"); assertThat(instance, instanceOf(Strings.class)); assertThat(((Strings<?>) instance).comparator(), sameInstance(equalsIgnoreCaseComparator())); assertThat(((Strings<?>) instance).comparatorDescription(), equalTo("equals ignore case")); assertThat(((Strings<?>) instance).expected(), equalTo("666")); } @Test public void factoryMethodEqualsToIgnoreCase() throws Exception { final Matcher<String> instance = equalsToIgnoreCase("666"); assertThat(instance, instanceOf(Strings.class)); assertThat(((Strings<?>) instance).comparator(), sameInstance(equalsIgnoreCaseComparator())); assertThat(((Strings<?>) instance).comparatorDescription(), equalTo("equals ignore case")); assertThat(((Strings<?>) instance).expected(), equalTo("666")); } @Test public void factoryMethodStartsWithComparator() throws Exception { final Comparator instance = startsWithComparator(); assertThat(instance.check("666 hello world", "666"), equalTo(true)); assertThat(instance.check("hello 666 world", "666"), equalTo(false)); assertThat(instance.check("hello world 666", "666"), equalTo(false)); } @Test public void factoryMethodEndsWithComparator() throws Exception { final Comparator instance = endsWithComparator(); assertThat(instance.check("666 hello world", "666"), equalTo(false)); assertThat(instance.check("hello 666 world", "666"), equalTo(false)); assertThat(instance.check("hello world 666", "666"), equalTo(true)); } @Test public void factoryMethodContainsComparator() throws Exception { final Comparator instance = containsComparator(); assertThat(instance.check("66 hello world", "666"), equalTo(false)); assertThat(instance.check("666 hello world", "666"), equalTo(true)); assertThat(instance.check("hello 666 world", "666"), equalTo(true)); assertThat(instance.check("hello world 666", "666"), equalTo(true)); } @Test public void factoryMethodMatchesComparator() throws Exception { final Comparator instance = matchesComparator(); assertThat(instance.check("66 hello world", ".*666.*"), equalTo(false)); assertThat(instance.check("666 hello world", ".*666.*"), equalTo(true)); assertThat(instance.check("hello 666 world", ".*666.*"), equalTo(true)); assertThat(instance.check("hello world 666", ".*666.*"), equalTo(true)); } @Test public void factoryMethodEqualsIgnoreCaseComparator() throws Exception { final Comparator instance = equalsIgnoreCaseComparator(); assertThat(instance.check("hello world", "hello world"), equalTo(true)); assertThat(instance.check("hElLo WoRlD", "hello world"), equalTo(true)); assertThat(instance.check("hElLo WoRlDs", "hello world"), equalTo(false)); } @Test public void constructor() throws Exception { final Strings<String> instance = new Strings<>("test", startsWithComparator(), "666"); assertThat(instance.comparator(), sameInstance(startsWithComparator())); assertThat(instance.comparatorDescription(), equalTo("test")); assertThat(instance.expected(), equalTo("666")); } @Test public void matches() throws Exception { final Matcher<String> instance = givenStartsWith666Instance(); assertThat(instance.matches("666 hello"), equalTo(true)); assertThat(instance.matches("hello 666"), equalTo(false)); assertThat(instance.matches(666), equalTo(false)); } @Test public void describeTo() throws Exception { final Description description = givenDescription(); final Matcher<String> instance = givenStartsWith666Instance(); instance.describeTo(description); assertThat(description.toString(), equalTo("starts with \"666\"")); } @Nonnull protected static Matcher<String> givenStartsWith666Instance() { return new Strings<>("starts with", startsWithComparator(), "666"); } }
package raptor.pref.fields; import org.eclipse.core.runtime.Assert; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.preference.FieldEditor; import org.eclipse.jface.resource.JFaceResources; import org.eclipse.swt.SWT; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.List; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Widget; import raptor.international.L10n; import raptor.swt.InputDialog; /** * A clone of the SWT list editor. This version has a height hint you can set. * Useful to keep lists from growing far to large. */ public abstract class ListEditor extends FieldEditor { /** * The list widget; <code>null</code> if none (before creation or after * disposal). */ private List list; /** * The button box containing the Add, Remove, Up, and Down buttons; * <code>null</code> if none (before creation or after disposal). */ private Composite buttonBox; /** * The Add button. */ private Button addButton; /** * The Remove button. */ private Button removeButton; /** * The Up button. */ private Button upButton; /** * The edit button. */ private Button editButton; /** * The Down button. */ private Button downButton; /** * The selection listener. */ private SelectionListener selectionListener; private int heightHint = SWT.DEFAULT; /** * Creates a new list field editor */ protected ListEditor() { } /** * Creates a list field editor. * * @param name * the name of the preference this field editor works on * @param labelText * the label text of the field editor * @param parent * the parent of the field editor's control */ protected ListEditor(String name, String labelText, Composite parent) { init(name, labelText); createControl(parent); } /** * Creates a list field editor. * * @param name * the name of the preference this field editor works on * @param labelText * the label text of the field editor * @param parent * the parent of the field editor's control */ protected ListEditor(String name, String labelText, Composite parent, int heightHint) { this.heightHint = heightHint; init(name, labelText); createControl(parent); } /** * Creates a selection listener. */ public void createSelectionListener() { selectionListener = new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent event) { Widget widget = event.widget; if (widget == addButton) { addPressed(); } else if (widget == editButton) { editPressed(); } else if (widget == removeButton) { removePressed(); } else if (widget == upButton) { upPressed(); } else if (widget == downButton) { downPressed(); } else if (widget == list) { selectionChanged(); } } }; } /** * Returns this field editor's button box containing the Add, Remove, Up, * and Down button. * * @param parent * the parent control * @return the button box */ public Composite getButtonBoxControl(Composite parent) { if (buttonBox == null) { buttonBox = new Composite(parent, SWT.NULL); GridLayout layout = new GridLayout(); layout.marginWidth = 0; buttonBox.setLayout(layout); createButtons(buttonBox); buttonBox.addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent event) { addButton = null; removeButton = null; editButton = null; upButton = null; downButton = null; buttonBox = null; } }); } else { checkParent(buttonBox, parent); } selectionChanged(); return buttonBox; } public int getHeightHint() { return heightHint; } /** * Returns this field editor's list control. * * @param parent * the parent control * @return the list control */ public List getListControl(Composite parent) { if (list == null) { list = new List(parent, SWT.BORDER | SWT.SINGLE | SWT.V_SCROLL | SWT.H_SCROLL); list.setFont(parent.getFont()); list.addSelectionListener(getSelectionListener()); list.addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent event) { list = null; } }); } else { checkParent(list, parent); } return list; } /* * (non-) Method declared on FieldEditor. */ @Override public int getNumberOfControls() { return 2; } /** * Prompts a user for the answer to a question. The user enters text. The * text the user entered is returned. */ public String promptForText(final String question) { InputDialog dialog = new InputDialog(getShell(), L10n.getInstance().getString("entText"), question,true); return dialog.open(); } /** * Prompts a user for the answer to a question. The user enters text. The * text the user entered is returned. * * @answer the initial text to place in the users answer. */ public String promptForText(final String question, String answer) { InputDialog dialog = new InputDialog(getShell(), L10n.getInstance().getString("entText"), question,true); if (answer != null) { dialog.setInput(answer); } return dialog.open(); } /** * Returns true if the text is valid, false otherwise. * @param text The text to check. * @return True if valid, false otherwise. */ public boolean isTextValid(String text) { return true; } /* * @see FieldEditor.setEnabled(boolean,Composite). */ @Override public void setEnabled(boolean enabled, Composite parent) { super.setEnabled(enabled, parent); getListControl(parent).setEnabled(enabled); addButton.setEnabled(enabled); editButton.setEnabled(enabled); removeButton.setEnabled(enabled); upButton.setEnabled(enabled); downButton.setEnabled(enabled); } /* * (non-) Method declared on FieldEditor. */ @Override public void setFocus() { if (list != null) { list.setFocus(); } } public void setHeightHint(int heightHint) { this.heightHint = heightHint; } /* * (non-) Method declared on FieldEditor. */ @Override protected void adjustForNumColumns(int numColumns) { Control control = getLabelControl(); ((GridData) control.getLayoutData()).horizontalSpan = numColumns; ((GridData) list.getLayoutData()).horizontalSpan = numColumns - 1; } /** * Combines the given list of items into a single string. This method is the * converse of <code>parseString</code>. * <p> * Subclasses must implement this method. * </p> * * @param items * the list of items * @return the combined string * @see #parseString */ protected abstract String createList(String[] items); /* * (non-) Method declared on FieldEditor. */ @Override protected void doFillIntoGrid(Composite parent, int numColumns) { Control control = getLabelControl(parent); GridData gd = new GridData(); gd.horizontalSpan = numColumns; control.setLayoutData(gd); list = getListControl(parent); gd = new GridData(GridData.FILL_HORIZONTAL); gd.heightHint = heightHint; gd.verticalAlignment = GridData.FILL; gd.horizontalSpan = numColumns - 1; gd.grabExcessHorizontalSpace = true; list.setLayoutData(gd); buttonBox = getButtonBoxControl(parent); gd = new GridData(); gd.verticalAlignment = GridData.BEGINNING; buttonBox.setLayoutData(gd); } /* * (non-) Method declared on FieldEditor. */ @Override protected void doLoad() { if (list != null) { String s = getPreferenceStore().getString(getPreferenceName()); String[] array = parseString(s); for (int i = 0; i < array.length; i++) { list.add(array[i]); } } } /* * (non-) Method declared on FieldEditor. */ @Override protected void doLoadDefault() { if (list != null) { list.removeAll(); String s = getPreferenceStore().getDefaultString( getPreferenceName()); String[] array = parseString(s); for (int i = 0; i < array.length; i++) { list.add(array[i]); } } } /* * (non-) Method declared on FieldEditor. */ @Override protected void doStore() { String s = createList(list.getItems()); if (s != null) { getPreferenceStore().setValue(getPreferenceName(), s); } } /** * Creates and returns a new item for the list. * <p> * Subclasses must implement this method. * </p> * * @return a new item */ protected abstract String getNewInputObject(); /** * Returns this field editor's shell. * <p> * This method is internal to the framework; subclassers should not call * this method. * </p> * * @return the shell */ protected Shell getShell() { if (addButton == null) { return null; } return addButton.getShell(); } /** * Splits the given string into a list of strings. This method is the * converse of <code>createList</code>. * <p> * Subclasses must implement this method. * </p> * * @param stringList * the string * @return an array of <code>String</code> * @see #createList */ protected abstract String[] parseString(String stringList); /** * Notifies that the Add button has been pressed. */ private void addPressed() { setPresentsDefaultValue(false); String value = promptForText("Enter new value:"); if (value != null && isTextValid(value)) { int index = list.getSelectionIndex(); if (index >= 0) { list.add(value, index + 1); } else { list.add(value, 0); } selectionChanged(); } else { showErrorMessage("Invalid: " + value); } } /** * Creates the Add, Remove, Up, and Down button in the given button box. * * @param box * the box for the buttons */ private void createButtons(Composite box) { addButton = createPushButton(box, "ListEditor.add", null);//$NON-NLS-1$ editButton = createPushButton(box, null, "Edit"); removeButton = createPushButton(box, "ListEditor.remove", null);//$NON-NLS-1$ upButton = createPushButton(box, "ListEditor.up", null);//$NON-NLS-1$ downButton = createPushButton(box, "ListEditor.down", null);//$NON-NLS-1$ } /** * Helper method to create a push button. * * @param parent * the parent control * @param key * the resource name used to supply the button's label text * @return Button */ private Button createPushButton(Composite parent, String key, String keyOverride) { Button button = new Button(parent, SWT.PUSH); button.setText(key != null ? JFaceResources.getString(key) : keyOverride); button.setFont(parent.getFont()); GridData data = new GridData(GridData.FILL_HORIZONTAL); int widthHint = convertHorizontalDLUsToPixels(button, IDialogConstants.BUTTON_WIDTH); data.widthHint = Math.max(widthHint, button.computeSize(SWT.DEFAULT, SWT.DEFAULT, true).x); button.setLayoutData(data); button.addSelectionListener(getSelectionListener()); return button; } /** * Notifies that the Down button has been pressed. */ private void downPressed() { swap(false); } private void editPressed() { setPresentsDefaultValue(false); String value = list.getItem(list.getSelectionIndex()); value = promptForText("Enter new value:", value); if (value != null && isTextValid(value)) { list.setItem(list.getSelectionIndex(), value); selectionChanged(); } else { showErrorMessage("Invalid: " + value); } } /** * Returns this field editor's selection listener. The listener is created * if nessessary. * * @return the selection listener */ private SelectionListener getSelectionListener() { if (selectionListener == null) { createSelectionListener(); } return selectionListener; } /** * Notifies that the Remove button has been pressed. */ private void removePressed() { setPresentsDefaultValue(false); int index = list.getSelectionIndex(); if (index >= 0) { list.remove(index); selectionChanged(); } } /** * Notifies that the list selection has changed. */ private void selectionChanged() { int index = list.getSelectionIndex(); int size = list.getItemCount(); removeButton.setEnabled(index >= 0); editButton.setEnabled(index >= 0); upButton.setEnabled(size > 1 && index > 0); downButton.setEnabled(size > 1 && index >= 0 && index < size - 1); } /** * Moves the currently selected item up or down. * * @param up * <code>true</code> if the item should move up, and * <code>false</code> if it should move down */ private void swap(boolean up) { setPresentsDefaultValue(false); int index = list.getSelectionIndex(); int target = up ? index - 1 : index + 1; if (index >= 0) { String[] selection = list.getSelection(); Assert.isTrue(selection.length == 1); list.remove(index); list.add(selection[0], target); list.setSelection(target); } selectionChanged(); } /** * Notifies that the Up button has been pressed. */ private void upPressed() { swap(true); } }
package com.tommytony.war; import com.google.common.collect.ImmutableList; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.logging.Level; import org.bukkit.ChatColor; import org.bukkit.GameMode; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.entity.Entity; import org.bukkit.entity.Item; import org.bukkit.entity.Player; import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; import org.getspout.spoutapi.SpoutManager; import org.getspout.spoutapi.player.SpoutPlayer; import com.tommytony.war.config.InventoryBag; import com.tommytony.war.config.TeamConfig; import com.tommytony.war.config.TeamConfigBag; import com.tommytony.war.config.TeamKind; import com.tommytony.war.config.WarzoneConfig; import com.tommytony.war.config.WarzoneConfigBag; import com.tommytony.war.job.InitZoneJob; import com.tommytony.war.job.LoadoutResetJob; import com.tommytony.war.job.ScoreCapReachedJob; import com.tommytony.war.mapper.LoadoutYmlMapper; import com.tommytony.war.spout.SpoutDisplayer; import com.tommytony.war.structure.Bomb; import com.tommytony.war.structure.Cake; import com.tommytony.war.structure.Monument; import com.tommytony.war.structure.HubLobbyMaterials; import com.tommytony.war.structure.WarzoneMaterials; import com.tommytony.war.structure.ZoneLobby; import com.tommytony.war.structure.ZoneWallGuard; import com.tommytony.war.utility.Direction; import com.tommytony.war.utility.Loadout; import com.tommytony.war.utility.LoadoutSelection; import com.tommytony.war.utility.PlayerState; import com.tommytony.war.utility.PotionEffectHelper; import com.tommytony.war.volume.BlockInfo; import com.tommytony.war.volume.Volume; import com.tommytony.war.volume.ZoneVolume; import org.bukkit.inventory.meta.LeatherArmorMeta; /** * * @author tommytony * @package com.tommytony.war */ public class Warzone { private String name; private ZoneVolume volume; private World world; private final List<Team> teams = new ArrayList<Team>(); private final List<Monument> monuments = new ArrayList<Monument>(); private final List<Bomb> bombs = new ArrayList<Bomb>(); private final List<Cake> cakes = new ArrayList<Cake>(); private Location teleport; private ZoneLobby lobby; private Location rallyPoint; private final List<String> authors = new ArrayList<String>(); private final int minSafeDistanceFromWall = 6; private List<ZoneWallGuard> zoneWallGuards = new ArrayList<ZoneWallGuard>(); private HashMap<String, PlayerState> playerStates = new HashMap<String, PlayerState>(); private HashMap<String, Team> flagThieves = new HashMap<String, Team>(); private HashMap<String, Bomb> bombThieves = new HashMap<String, Bomb>(); private HashMap<String, Cake> cakeThieves = new HashMap<String, Cake>(); private HashMap<String, LoadoutSelection> loadoutSelections = new HashMap<String, LoadoutSelection>(); private HashMap<String, PlayerState> deadMenInventories = new HashMap<String, PlayerState>(); private final List<Player> respawn = new ArrayList<Player>(); private final List<String> reallyDeadFighters = new ArrayList<String>(); private final WarzoneConfigBag warzoneConfig; private final TeamConfigBag teamDefaultConfig; private InventoryBag defaultInventories = new InventoryBag(); private HubLobbyMaterials lobbyMaterials = null; private WarzoneMaterials warzoneMaterials = new WarzoneMaterials(49, (byte)0, 85, (byte)0, 89, (byte)0); // default main obsidian, stand ladder, light glowstone private boolean isEndOfGame = false; private boolean isReinitializing = false; //private final Object gameEndLock = new Object(); public Warzone(World world, String name) { this.world = world; this.name = name; this.warzoneConfig = new WarzoneConfigBag(this); this.teamDefaultConfig = new TeamConfigBag(); // don't use ctor with Warzone, as this changes config resolution this.volume = new ZoneVolume(name, this.getWorld(), this); this.lobbyMaterials = new HubLobbyMaterials( War.war.getWarhubMaterials().getFloorId(), War.war.getWarhubMaterials().getFloorData(), War.war.getWarhubMaterials().getOutlineId(), War.war.getWarhubMaterials().getOutlineData(), War.war.getWarhubMaterials().getGateId(), War.war.getWarhubMaterials().getGateData(), War.war.getWarhubMaterials().getLightId(), War.war.getWarhubMaterials().getLightData() ); } public static Warzone getZoneByName(String name) { Warzone bestGuess = null; for (Warzone warzone : War.war.getWarzones()) { if (warzone.getName().toLowerCase().equals(name.toLowerCase())) { // perfect match, return right away return warzone; } else if (warzone.getName().toLowerCase().startsWith(name.toLowerCase())) { // perhaps there's a perfect match in the remaining zones, let's take this one aside bestGuess = warzone; } } return bestGuess; } public static Warzone getZoneByLocation(Location location) { for (Warzone warzone : War.war.getWarzones()) { if (location.getWorld().getName().equals(warzone.getWorld().getName()) && warzone.getVolume() != null && warzone.getVolume().contains(location)) { return warzone; } } return null; } public static Warzone getZoneByLocation(Player player) { return Warzone.getZoneByLocation(player.getLocation()); } public static Warzone getZoneByPlayerName(String playerName) { for (Warzone warzone : War.war.getWarzones()) { Team team = warzone.getPlayerTeam(playerName); if (team != null) { return warzone; } } return null; } public static Warzone getZoneByTeam(Team team) { for (Warzone warzone : War.war.getWarzones()) { for (Team teamToCheck : warzone.getTeams()) { if (teamToCheck.getName().equals(team.getName())) { return warzone; } } } return null; } public boolean ready() { if (this.volume.hasTwoCorners() && !this.volume.tooSmall() && !this.volume.tooBig()) { return true; } return false; } public List<Team> getTeams() { return this.teams; } public Team getPlayerTeam(String playerName) { for (Team team : this.teams) { for (Player player : team.getPlayers()) { if (player.getName().equals(playerName)) { return team; } } } return null; } public String getTeamInformation() { String teamsMessage = "Teams: "; if (this.getTeams().isEmpty()) { teamsMessage += "none."; } else { for (Team team : this.getTeams()) { teamsMessage += team.getName() + " (" + team.getPoints() + " points, " + team.getRemainingLifes() + "/" + team.getTeamConfig().resolveInt(TeamConfig.LIFEPOOL) + " lives left. "; for (Player member : team.getPlayers()) { teamsMessage += member.getName() + " "; } teamsMessage += ") "; } } return teamsMessage; } public String getName() { return this.name; } @Override public String toString() { return this.getName(); } public void setTeleport(Location location) { this.teleport = location; } public Location getTeleport() { return this.teleport; } public int saveState(boolean clearArtifacts) { if (this.ready()) { if (clearArtifacts) { // removed everything to keep save clean for (ZoneWallGuard guard : this.zoneWallGuards) { guard.deactivate(); } this.zoneWallGuards.clear(); for (Team team : this.teams) { team.getSpawnVolume().resetBlocks(); if (team.getTeamFlag() != null) { team.getFlagVolume().resetBlocks(); } } for (Monument monument : this.monuments) { monument.getVolume().resetBlocks(); } if (this.lobby != null) { this.lobby.getVolume().resetBlocks(); } } int saved = this.volume.saveBlocks(); if (clearArtifacts) { this.initializeZone(); // bring back stuff } return saved; } return 0; } /** * Goes back to the saved state of the warzone (resets only block types, not physics). Also teleports all players back to their respective spawns. * * @return */ public void initializeZone() { this.initializeZone(null); } public void initializeZone(Player respawnExempted) { if (this.ready() && this.volume.isSaved()) { // everyone back to team spawn with full health for (Team team : this.teams) { for (Player player : team.getPlayers()) { if (respawnExempted == null || (respawnExempted != null && !player.getName().equals(respawnExempted.getName()))) { this.respawnPlayer(team, player); } } team.setRemainingLives(team.getTeamConfig().resolveInt(TeamConfig.LIFEPOOL)); team.initializeTeamSpawn(); if (team.getTeamFlag() != null) { team.setTeamFlag(team.getTeamFlag()); } } this.initZone(); if (War.war.getWarHub() != null) { War.war.getWarHub().resetZoneSign(this); } } // Don't forget to reset these to false, or we won't be able to score or empty lifepools anymore this.isReinitializing = false; this.isEndOfGame = false; } public void initializeZoneAsJob(Player respawnExempted) { InitZoneJob job = new InitZoneJob(this, respawnExempted); War.war.getServer().getScheduler().scheduleSyncDelayedTask(War.war, job); } public void initializeZoneAsJob() { InitZoneJob job = new InitZoneJob(this); War.war.getServer().getScheduler().scheduleSyncDelayedTask(War.war, job); } private void initZone() { // reset monuments for (Monument monument : this.monuments) { monument.getVolume().resetBlocks(); monument.addMonumentBlocks(); } // reset bombs for (Bomb bomb : this.bombs) { bomb.getVolume().resetBlocks(); bomb.addBombBlocks(); } // reset cakes for (Cake cake : this.cakes) { cake.getVolume().resetBlocks(); cake.addCakeBlocks(); } // reset lobby (here be demons) if (this.lobby != null) { if (this.lobby.getVolume() != null) { this.lobby.getVolume().resetBlocks(); } this.lobby.initialize(); } this.flagThieves.clear(); this.bombThieves.clear(); this.cakeThieves.clear(); this.reallyDeadFighters.clear(); // nom drops for(Entity entity : (this.getWorld().getEntities())) { if (!(entity instanceof Item)) { continue; } // validate position if (!this.getVolume().contains(entity.getLocation())) { continue; } // omnomnomnom entity.remove(); } } public void endRound() { } public void respawnPlayer(Team team, Player player) { this.handleRespawn(team, player); // Teleport the player back to spawn player.teleport(team.getTeamSpawn()); } public void respawnPlayer(PlayerMoveEvent event, Team team, Player player) { this.handleRespawn(team, player); // Teleport the player back to spawn event.setTo(team.getTeamSpawn()); } public boolean isRespawning(Player p) { return respawn.contains(p); } private void handleRespawn(final Team team, final Player player) { // Fill hp player.setRemainingAir(300); player.setHealth(20); player.setFoodLevel(20); player.setSaturation(team.getTeamConfig().resolveInt(TeamConfig.SATURATION)); player.setExhaustion(0); player.setFireTicks(0); //this works fine here, why put it in LoudoutResetJob...? I'll keep it over there though player.getOpenInventory().close(); player.getInventory().clear(); if (player.getGameMode() == GameMode.CREATIVE) { // Players are always in survival mode in warzones player.setGameMode(GameMode.SURVIVAL); } // clear potion effects PotionEffectHelper.clearPotionEffects(player); boolean isFirstRespawn = false; if (!this.getLoadoutSelections().keySet().contains(player.getName())) { isFirstRespawn = true; this.getLoadoutSelections().put(player.getName(), new LoadoutSelection(true, 0)); } else if (this.isReinitializing) { isFirstRespawn = true; this.getLoadoutSelections().get(player.getName()).setStillInSpawn(true); } else { this.getLoadoutSelections().get(player.getName()).setStillInSpawn(true); } // Spout if (War.war.isSpoutServer()) { SpoutManager.getPlayer(player).setTitle(team.getKind().getColor() + player.getName()); } final LoadoutResetJob job = new LoadoutResetJob(this, team, player, isFirstRespawn, false); if (team.getTeamConfig().resolveInt(TeamConfig.RESPAWNTIMER) == 0 || isFirstRespawn) { job.run(); } else { // "Respawn" Timer - player will not be able to leave spawn for a few seconds respawn.add(player); War.war.getServer().getScheduler().scheduleSyncDelayedTask(War.war, new Runnable() { public void run() { respawn.remove(player); War.war.getServer().getScheduler().scheduleSyncDelayedTask(War.war, job); } }, team.getTeamConfig().resolveInt(TeamConfig.RESPAWNTIMER) * 20L); // 20 ticks = 1 second } } public void resetInventory(Team team, Player player, HashMap<Integer, ItemStack> loadout) { // Reset inventory to loadout PlayerInventory playerInv = player.getInventory(); playerInv.clear(); playerInv.clear(playerInv.getSize() + 0); playerInv.clear(playerInv.getSize() + 1); playerInv.clear(playerInv.getSize() + 2); playerInv.clear(playerInv.getSize() + 3); // helmet/blockHead boolean helmetIsInLoadout = false; for (Integer slot : loadout.keySet()) { if (slot == 100) { playerInv.setBoots(War.war.copyStack(loadout.get(slot))); } else if (slot == 101) { playerInv.setLeggings(War.war.copyStack(loadout.get(slot))); } else if (slot == 102) { playerInv.setChestplate(War.war.copyStack(loadout.get(slot))); } else if (slot == 103) { playerInv.setHelmet(War.war.copyStack(loadout.get(slot))); helmetIsInLoadout = true; } else { ItemStack item = loadout.get(slot); if (item != null) { playerInv.addItem(War.war.copyStack(item)); } } } if (this.getWarzoneConfig().getBoolean(WarzoneConfig.BLOCKHEADS)) { playerInv.setHelmet(new ItemStack(team.getKind().getMaterial(), 1, (short) 1, new Byte(team.getKind().getData()))); } else { if (!helmetIsInLoadout) { ItemStack helmet = new ItemStack(Material.LEATHER_HELMET); LeatherArmorMeta meta = (LeatherArmorMeta) helmet.getItemMeta(); meta.setColor(team.getKind().getBukkitColor()); helmet.setItemMeta(meta); playerInv.setHelmet(helmet); } } } public boolean isMonumentCenterBlock(Block block) { for (Monument monument : this.monuments) { int x = monument.getLocation().getBlockX(); int y = monument.getLocation().getBlockY() + 1; int z = monument.getLocation().getBlockZ(); if (x == block.getX() && y == block.getY() && z == block.getZ()) { return true; } } return false; } public Monument getMonumentFromCenterBlock(Block block) { for (Monument monument : this.monuments) { int x = monument.getLocation().getBlockX(); int y = monument.getLocation().getBlockY() + 1; int z = monument.getLocation().getBlockZ(); if (x == block.getX() && y == block.getY() && z == block.getZ()) { return monument; } } return null; } public boolean nearAnyOwnedMonument(Location to, Team team) { for (Monument monument : this.monuments) { if (monument.isNear(to) && monument.isOwner(team)) { return true; } } return false; } public List<Monument> getMonuments() { return this.monuments; } public boolean hasPlayerState(String playerName) { return this.playerStates.containsKey(playerName); } public void keepPlayerState(Player player) { PlayerInventory inventory = player.getInventory(); ItemStack[] contents = inventory.getContents(); String playerTitle = player.getName(); if (War.war.isSpoutServer()) { playerTitle = SpoutManager.getPlayer(player).getTitle(); } this.playerStates.put(player.getName(), new PlayerState(player.getGameMode(), contents, inventory.getHelmet(), inventory.getChestplate(), inventory.getLeggings(), inventory.getBoots(), player.getHealth(), player.getExhaustion(), player.getSaturation(), player.getFoodLevel(), player.getActivePotionEffects(), playerTitle, player.getLevel(), player.getExp())); } public void restorePlayerState(Player player) { PlayerState originalState = this.playerStates.remove(player.getName()); PlayerInventory playerInv = player.getInventory(); if (originalState != null) { player.getOpenInventory().close(); this.playerInvFromInventoryStash(playerInv, originalState); player.setGameMode(originalState.getGamemode()); player.setHealth(originalState.getHealth()); player.setExhaustion(originalState.getExhaustion()); player.setSaturation(originalState.getSaturation()); player.setFoodLevel(originalState.getFoodLevel()); PotionEffectHelper.restorePotionEffects(player, originalState.getPotionEffects()); player.setLevel(originalState.getLevel()); player.setExp(originalState.getExp()); if (War.war.isSpoutServer()) { SpoutManager.getPlayer(player).setTitle(originalState.getPlayerTitle()); } } } private void playerInvFromInventoryStash(PlayerInventory playerInv, PlayerState originalContents) { playerInv.clear(); playerInv.clear(playerInv.getSize() + 0); playerInv.clear(playerInv.getSize() + 1); playerInv.clear(playerInv.getSize() + 2); playerInv.clear(playerInv.getSize() + 3); // helmet/blockHead int invIndex = 0; for (ItemStack item : originalContents.getContents()) { if (item != null && item.getTypeId() != 0) { playerInv.setItem(invIndex, item); } invIndex++; } if (originalContents.getHelmet() != null) { playerInv.setHelmet(originalContents.getHelmet()); } if (originalContents.getChest() != null) { playerInv.setChestplate(originalContents.getChest()); } if (originalContents.getLegs() != null) { playerInv.setLeggings(originalContents.getLegs()); } if (originalContents.getFeet() != null) { playerInv.setBoots(originalContents.getFeet()); } } public boolean hasMonument(String monumentName) { for (Monument monument : this.monuments) { if (monument.getName().startsWith(monumentName)) { return true; } } return false; } public Monument getMonument(String monumentName) { for (Monument monument : this.monuments) { if (monument.getName().startsWith(monumentName)) { return monument; } } return null; } public boolean hasBomb(String bombName) { for (Bomb bomb : this.bombs) { if (bomb.getName().equals(bombName)) { return true; } } return false; } public Bomb getBomb(String bombName) { for (Bomb bomb : this.bombs) { if (bomb.getName().startsWith(bombName)) { return bomb; } } return null; } public boolean hasCake(String cakeName) { for (Cake cake : this.cakes) { if (cake.getName().equals(cakeName)) { return true; } } return false; } public Cake getCake(String cakeName) { for (Cake cake : this.cakes) { if (cake.getName().startsWith(cakeName)) { return cake; } } return null; } public boolean isImportantBlock(Block block) { if (this.ready()) { for (Monument m : this.monuments) { if (m.getVolume().contains(block)) { return true; } } for (Bomb b : this.bombs) { if (b.getVolume().contains(block)) { return true; } } for (Cake c : this.cakes) { if (c.getVolume().contains(block)) { return true; } } for (Team t : this.teams) { if (t.getSpawnVolume().contains(block)) { return true; } else if (t.getFlagVolume() != null && t.getFlagVolume().contains(block)) { return true; } } if (this.volume.isWallBlock(block)) { return true; } } return false; } public World getWorld() { return this.world; } public void setWorld(World world) { this.world = world; } public ZoneVolume getVolume() { return this.volume; } public void setVolume(ZoneVolume zoneVolume) { this.volume = zoneVolume; } public Team getTeamByKind(TeamKind kind) { for (Team t : this.teams) { if (t.getKind() == kind) { return t; } } return null; } public boolean isNearWall(Location latestPlayerLocation) { if (this.volume.hasTwoCorners()) { if (Math.abs(this.volume.getSoutheastZ() - latestPlayerLocation.getBlockZ()) < this.minSafeDistanceFromWall && latestPlayerLocation.getBlockX() <= this.volume.getSoutheastX() && latestPlayerLocation.getBlockX() >= this.volume.getNorthwestX() && latestPlayerLocation.getBlockY() >= this.volume.getMinY() && latestPlayerLocation.getBlockY() <= this.volume.getMaxY()) { return true; // near east wall } else if (Math.abs(this.volume.getSoutheastX() - latestPlayerLocation.getBlockX()) < this.minSafeDistanceFromWall && latestPlayerLocation.getBlockZ() <= this.volume.getNorthwestZ() && latestPlayerLocation.getBlockZ() >= this.volume.getSoutheastZ() && latestPlayerLocation.getBlockY() >= this.volume.getMinY() && latestPlayerLocation.getBlockY() <= this.volume.getMaxY()) { return true; // near south wall } else if (Math.abs(this.volume.getNorthwestX() - latestPlayerLocation.getBlockX()) < this.minSafeDistanceFromWall && latestPlayerLocation.getBlockZ() <= this.volume.getNorthwestZ() && latestPlayerLocation.getBlockZ() >= this.volume.getSoutheastZ() && latestPlayerLocation.getBlockY() >= this.volume.getMinY() && latestPlayerLocation.getBlockY() <= this.volume.getMaxY()) { return true; // near north wall } else if (Math.abs(this.volume.getNorthwestZ() - latestPlayerLocation.getBlockZ()) < this.minSafeDistanceFromWall && latestPlayerLocation.getBlockX() <= this.volume.getSoutheastX() && latestPlayerLocation.getBlockX() >= this.volume.getNorthwestX() && latestPlayerLocation.getBlockY() >= this.volume.getMinY() && latestPlayerLocation.getBlockY() <= this.volume.getMaxY()) { return true; // near west wall } else if (Math.abs(this.volume.getMaxY() - latestPlayerLocation.getBlockY()) < this.minSafeDistanceFromWall && latestPlayerLocation.getBlockX() <= this.volume.getMaxX() && latestPlayerLocation.getBlockX() >= this.volume.getMinX() && latestPlayerLocation.getBlockZ() <= this.volume.getMaxZ() && latestPlayerLocation.getBlockZ() >= this.volume.getMinZ()) { return true; // near up wall } else if (Math.abs(this.volume.getMinY() - latestPlayerLocation.getBlockY()) < this.minSafeDistanceFromWall && latestPlayerLocation.getBlockX() <= this.volume.getMaxX() && latestPlayerLocation.getBlockX() >= this.volume.getMinX() && latestPlayerLocation.getBlockZ() <= this.volume.getMaxZ() && latestPlayerLocation.getBlockZ() >= this.volume.getMinZ()) { return true; // near down wall } } return false; } public List<Block> getNearestWallBlocks(Location latestPlayerLocation) { List<Block> nearestWallBlocks = new ArrayList<Block>(); if (Math.abs(this.volume.getSoutheastZ() - latestPlayerLocation.getBlockZ()) < this.minSafeDistanceFromWall && latestPlayerLocation.getBlockX() <= this.volume.getSoutheastX() && latestPlayerLocation.getBlockX() >= this.volume.getNorthwestX() && latestPlayerLocation.getBlockY() >= this.volume.getMinY() && latestPlayerLocation.getBlockY() <= this.volume.getMaxY()) { // near east wall Block eastWallBlock = this.world.getBlockAt(latestPlayerLocation.getBlockX() + 1, latestPlayerLocation.getBlockY() + 1, this.volume.getSoutheastZ()); nearestWallBlocks.add(eastWallBlock); } if (Math.abs(this.volume.getSoutheastX() - latestPlayerLocation.getBlockX()) < this.minSafeDistanceFromWall && latestPlayerLocation.getBlockZ() <= this.volume.getNorthwestZ() && latestPlayerLocation.getBlockZ() >= this.volume.getSoutheastZ() && latestPlayerLocation.getBlockY() >= this.volume.getMinY() && latestPlayerLocation.getBlockY() <= this.volume.getMaxY()) { // near south wall Block southWallBlock = this.world.getBlockAt(this.volume.getSoutheastX(), latestPlayerLocation.getBlockY() + 1, latestPlayerLocation.getBlockZ()); nearestWallBlocks.add(southWallBlock); } if (Math.abs(this.volume.getNorthwestX() - latestPlayerLocation.getBlockX()) < this.minSafeDistanceFromWall && latestPlayerLocation.getBlockZ() <= this.volume.getNorthwestZ() && latestPlayerLocation.getBlockZ() >= this.volume.getSoutheastZ() && latestPlayerLocation.getBlockY() >= this.volume.getMinY() && latestPlayerLocation.getBlockY() <= this.volume.getMaxY()) { // near north wall Block northWallBlock = this.world.getBlockAt(this.volume.getNorthwestX(), latestPlayerLocation.getBlockY() + 1, latestPlayerLocation.getBlockZ()); nearestWallBlocks.add(northWallBlock); } if (Math.abs(this.volume.getNorthwestZ() - latestPlayerLocation.getBlockZ()) < this.minSafeDistanceFromWall && latestPlayerLocation.getBlockX() <= this.volume.getSoutheastX() && latestPlayerLocation.getBlockX() >= this.volume.getNorthwestX() && latestPlayerLocation.getBlockY() >= this.volume.getMinY() && latestPlayerLocation.getBlockY() <= this.volume.getMaxY()) { // near west wall Block westWallBlock = this.world.getBlockAt(latestPlayerLocation.getBlockX(), latestPlayerLocation.getBlockY() + 1, this.volume.getNorthwestZ()); nearestWallBlocks.add(westWallBlock); } if (Math.abs(this.volume.getMaxY() - latestPlayerLocation.getBlockY()) < this.minSafeDistanceFromWall && latestPlayerLocation.getBlockX() <= this.volume.getMaxX() && latestPlayerLocation.getBlockX() >= this.volume.getMinX() && latestPlayerLocation.getBlockZ() <= this.volume.getMaxZ() && latestPlayerLocation.getBlockZ() >= this.volume.getMinZ()) { // near up wall Block upWallBlock = this.world.getBlockAt(latestPlayerLocation.getBlockX(), this.volume.getMaxY(), latestPlayerLocation.getBlockZ()); nearestWallBlocks.add(upWallBlock); } if (Math.abs(this.volume.getMinY() - latestPlayerLocation.getBlockY()) < this.minSafeDistanceFromWall && latestPlayerLocation.getBlockX() <= this.volume.getMaxX() && latestPlayerLocation.getBlockX() >= this.volume.getMinX() && latestPlayerLocation.getBlockZ() <= this.volume.getMaxZ() && latestPlayerLocation.getBlockZ() >= this.volume.getMinZ()) { // near down wall Block downWallBlock = this.world.getBlockAt(latestPlayerLocation.getBlockX(), this.volume.getMinY(), latestPlayerLocation.getBlockZ()); nearestWallBlocks.add(downWallBlock); } return nearestWallBlocks; // note: y + 1 to line up 3 sided square with player eyes } public List<BlockFace> getNearestWalls(Location latestPlayerLocation) { List<BlockFace> walls = new ArrayList<BlockFace>(); if (Math.abs(this.volume.getSoutheastZ() - latestPlayerLocation.getBlockZ()) < this.minSafeDistanceFromWall && latestPlayerLocation.getBlockX() <= this.volume.getSoutheastX() && latestPlayerLocation.getBlockX() >= this.volume.getNorthwestX() && latestPlayerLocation.getBlockY() >= this.volume.getMinY() && latestPlayerLocation.getBlockY() <= this.volume.getMaxY()) { // near east wall walls.add(Direction.EAST()); } if (Math.abs(this.volume.getSoutheastX() - latestPlayerLocation.getBlockX()) < this.minSafeDistanceFromWall && latestPlayerLocation.getBlockZ() <= this.volume.getNorthwestZ() && latestPlayerLocation.getBlockZ() >= this.volume.getSoutheastZ() && latestPlayerLocation.getBlockY() >= this.volume.getMinY() && latestPlayerLocation.getBlockY() <= this.volume.getMaxY()) { // near south wall walls.add(Direction.SOUTH()); } if (Math.abs(this.volume.getNorthwestX() - latestPlayerLocation.getBlockX()) < this.minSafeDistanceFromWall && latestPlayerLocation.getBlockZ() <= this.volume.getNorthwestZ() && latestPlayerLocation.getBlockZ() >= this.volume.getSoutheastZ() && latestPlayerLocation.getBlockY() >= this.volume.getMinY() && latestPlayerLocation.getBlockY() <= this.volume.getMaxY()) { // near north wall walls.add(Direction.NORTH()); } if (Math.abs(this.volume.getNorthwestZ() - latestPlayerLocation.getBlockZ()) < this.minSafeDistanceFromWall && latestPlayerLocation.getBlockX() <= this.volume.getSoutheastX() && latestPlayerLocation.getBlockX() >= this.volume.getNorthwestX() && latestPlayerLocation.getBlockY() >= this.volume.getMinY() && latestPlayerLocation.getBlockY() <= this.volume.getMaxY()) { // near west wall walls.add(Direction.WEST()); } if (Math.abs(this.volume.getMaxY() - latestPlayerLocation.getBlockY()) < this.minSafeDistanceFromWall && latestPlayerLocation.getBlockX() <= this.volume.getMaxX() && latestPlayerLocation.getBlockX() >= this.volume.getMinX() && latestPlayerLocation.getBlockZ() <= this.volume.getMaxZ() && latestPlayerLocation.getBlockZ() >= this.volume.getMinZ()) { // near up wall walls.add(BlockFace.UP); } if (Math.abs(this.volume.getMinY() - latestPlayerLocation.getBlockY()) < this.minSafeDistanceFromWall && latestPlayerLocation.getBlockX() <= this.volume.getMaxX() && latestPlayerLocation.getBlockX() >= this.volume.getMinX() && latestPlayerLocation.getBlockZ() <= this.volume.getMaxZ() && latestPlayerLocation.getBlockZ() >= this.volume.getMinZ()) { // near down wall walls.add(BlockFace.DOWN); } return walls; } public ZoneWallGuard getPlayerZoneWallGuard(String name, BlockFace wall) { for (ZoneWallGuard guard : this.zoneWallGuards) { if (guard.getPlayer().getName().equals(name) && wall == guard.getWall()) { return guard; } } return null; } public boolean protectZoneWallAgainstPlayer(Player player) { List<BlockFace> nearestWalls = this.getNearestWalls(player.getLocation()); boolean protecting = false; for (BlockFace wall : nearestWalls) { ZoneWallGuard guard = this.getPlayerZoneWallGuard(player.getName(), wall); if (guard != null) { // already protected, need to move the guard guard.updatePlayerPosition(player.getLocation()); } else { // new guard guard = new ZoneWallGuard(player, War.war, this, wall); this.zoneWallGuards.add(guard); } protecting = true; } return protecting; } public void dropZoneWallGuardIfAny(Player player) { List<ZoneWallGuard> playerGuards = new ArrayList<ZoneWallGuard>(); for (ZoneWallGuard guard : this.zoneWallGuards) { if (guard.getPlayer().getName().equals(player.getName())) { playerGuards.add(guard); guard.deactivate(); } } // now remove those zone guards for (ZoneWallGuard playerGuard : playerGuards) { this.zoneWallGuards.remove(playerGuard); } playerGuards.clear(); } public void setLobby(ZoneLobby lobby) { this.lobby = lobby; } public ZoneLobby getLobby() { return this.lobby; } public Team autoAssign(Player player) { Team lowestNoOfPlayers = null; for (Team t : this.teams) { if (lowestNoOfPlayers == null || (lowestNoOfPlayers != null && lowestNoOfPlayers.getPlayers().size() > t.getPlayers().size())) { if (War.war.canPlayWar(player, t)) { lowestNoOfPlayers = t; } } } if (lowestNoOfPlayers != null) { if (player.getWorld() != this.getWorld()) { player.teleport(this.getWorld().getSpawnLocation()); } lowestNoOfPlayers.addPlayer(player); lowestNoOfPlayers.resetSign(); if (!this.hasPlayerState(player.getName())) { this.keepPlayerState(player); } War.war.msg(player, "Your inventory is in storage until you use '/war leave'."); this.respawnPlayer(lowestNoOfPlayers, player); for (Team team : this.teams) { team.teamcast("" + player.getName() + " joined team " + lowestNoOfPlayers.getName() + "."); } } return lowestNoOfPlayers; } public void handleDeath(Player player) { // THIS ISN'T THREAD SAFE // Every death and player movement should ideally occur in sequence because // 1) a death can cause the end of the game by emptying a lifepool causing the max score to be reached // 2) a player movement from one block to the next (getting a flag home or causing a bomb to go off perhaps) could win the game // Concurrent execution of these events could cause the inventory reset of the last players to die to fail as // they get tp'ed back to the lobby, or perhaps kills to bleed into the next round. Team playerTeam = Team.getTeamByPlayerName(player.getName()); // Make sure the player that died is still part of a team, game may have ended while waiting. // Ignore dying players that essentially just got tp'ed to lobby and got their state restored. // Gotta take care of restoring ReallyDeadFighters' game-end state when in onRespawn as well. if (playerTeam != null) { // teleport to team spawn upon fast respawn death, but not for real deaths if (!this.getWarzoneConfig().getBoolean(WarzoneConfig.REALDEATHS)) { this.respawnPlayer(playerTeam, player); } else { // onPlayerRespawn takes care of real deaths //player.setHealth(0); this.getReallyDeadFighters().add(player.getName()); } int remaining = playerTeam.getRemainingLifes(); if (remaining == 0) { // your death caused your team to lose if (this.isReinitializing()) { // Prevent duplicate battle end. You died just after the battle ending death. this.respawnPlayer(playerTeam, player); } else { // Handle team loss List<Team> teams = this.getTeams(); String scores = ""; for (Team t : teams) { if (War.war.isSpoutServer()) { for (Player p : t.getPlayers()) { SpoutPlayer sp = SpoutManager.getPlayer(p); if (sp.isSpoutCraftEnabled()) { sp.sendNotification( SpoutDisplayer.cleanForNotification("Round over! " + playerTeam.getKind().getColor() + playerTeam.getName()), SpoutDisplayer.cleanForNotification("ran out of lives."), playerTeam.getKind().getMaterial(), playerTeam.getKind().getData(), 10000); } } } t.teamcast("The battle is over. Team " + playerTeam.getName() + " lost: " + player.getName() + " died and there were no lives left in their life pool."); if (t.getPlayers().size() != 0 && !t.getTeamConfig().resolveBoolean(TeamConfig.FLAGPOINTSONLY)) { if (!t.getName().equals(playerTeam.getName())) { // all other teams get a point t.addPoint(); t.resetSign(); } scores += t.getName() + "(" + t.getPoints() + "/" + t.getTeamConfig().resolveInt(TeamConfig.MAXSCORE) + ") "; } } if (!scores.equals("")) { for (Team t : teams) { t.teamcast("New scores - " + scores); } } // detect score cap List<Team> scoreCapTeams = new ArrayList<Team>(); for (Team t : teams) { if (t.getPoints() == t.getTeamConfig().resolveInt(TeamConfig.MAXSCORE)) { scoreCapTeams.add(t); } } if (!scoreCapTeams.isEmpty()) { String winnersStr = ""; for (Team winner : scoreCapTeams) { if (winner.getPlayers().size() != 0) { winnersStr += winner.getName() + " "; } } this.handleScoreCapReached(winnersStr); } else { // A new battle starts. Reset the zone but not the teams. for (Team t : teams) { t.teamcast("A new battle begins. Resetting warzone..."); } this.reinitialize(); } } } else { // player died without causing his team's demise if (this.isFlagThief(player.getName())) { // died while carrying flag.. dropped it Team victim = this.getVictimTeamForFlagThief(player.getName()); victim.getFlagVolume().resetBlocks(); victim.initializeTeamFlag(); this.removeFlagThief(player.getName()); if (War.war.isSpoutServer()) { for (Player p : victim.getPlayers()) { SpoutPlayer sp = SpoutManager.getPlayer(p); if (sp.isSpoutCraftEnabled()) { sp.sendNotification( SpoutDisplayer.cleanForNotification(playerTeam.getKind().getColor() + player.getName() + ChatColor.YELLOW + " dropped"), SpoutDisplayer.cleanForNotification(ChatColor.YELLOW + "your flag."), playerTeam.getKind().getMaterial(), playerTeam.getKind().getData(), 5000); } } } for (Team t : this.getTeams()) { t.teamcast(player.getName() + " died and dropped team " + victim.getName() + "'s flag."); } } // Bomb thieves if (this.isBombThief(player.getName())) { // died while carrying bomb.. dropped it Bomb bomb = this.getBombForThief(player.getName()); bomb.getVolume().resetBlocks(); bomb.addBombBlocks(); this.removeBombThief(player.getName()); for (Team t : this.getTeams()) { t.teamcast(player.getName() + " died and dropped bomb " + ChatColor.GREEN + bomb.getName() + ChatColor.WHITE + "."); if (War.war.isSpoutServer()) { for (Player p : t.getPlayers()) { SpoutPlayer sp = SpoutManager.getPlayer(p); if (sp.isSpoutCraftEnabled()) { sp.sendNotification( SpoutDisplayer.cleanForNotification(playerTeam.getKind().getColor() + player.getName() + ChatColor.YELLOW + " dropped"), SpoutDisplayer.cleanForNotification(ChatColor.YELLOW + "bomb " + ChatColor.GREEN + bomb.getName() + ChatColor.YELLOW + "."), Material.TNT, (short)0, 5000); } } } } } if (this.isCakeThief(player.getName())) { // died while carrying cake.. dropped it Cake cake = this.getCakeForThief(player.getName()); cake.getVolume().resetBlocks(); cake.addCakeBlocks(); this.removeCakeThief(player.getName()); for (Team t : this.getTeams()) { t.teamcast(player.getName() + " died and dropped cake " + ChatColor.GREEN + cake.getName() + ChatColor.WHITE + "."); if (War.war.isSpoutServer()) { for (Player p : t.getPlayers()) { SpoutPlayer sp = SpoutManager.getPlayer(p); if (sp.isSpoutCraftEnabled()) { sp.sendNotification( SpoutDisplayer.cleanForNotification(playerTeam.getKind().getColor() + player.getName() + ChatColor.YELLOW + " dropped"), SpoutDisplayer.cleanForNotification(ChatColor.YELLOW + "cake " + ChatColor.GREEN + cake.getName() + ChatColor.YELLOW + "."), Material.CAKE, (short)0, 5000); } } } } } // Decrement lifepool playerTeam.setRemainingLives(remaining - 1); // Lifepool empty warning if (remaining - 1 == 0) { for (Team t : this.getTeams()) { t.teamcast("Team " + playerTeam.getName() + "'s life pool is empty. One more death and they lose the battle!"); } } } playerTeam.resetSign(); } } public void reinitialize() { this.isReinitializing = true; this.getVolume().resetBlocksAsJob(); this.initializeZoneAsJob(); } public void handlePlayerLeave(Player player, Location destination, PlayerMoveEvent event, boolean removeFromTeam) { this.handlePlayerLeave(player, removeFromTeam); event.setTo(destination); } public void handlePlayerLeave(Player player, Location destination, boolean removeFromTeam) { this.handlePlayerLeave(player, removeFromTeam); player.teleport(destination); } private void handlePlayerLeave(Player player, boolean removeFromTeam) { Team playerTeam = Team.getTeamByPlayerName(player.getName()); if (playerTeam != null) { if (removeFromTeam) { playerTeam.removePlayer(player.getName()); } for (Team t : this.getTeams()) { t.teamcast(playerTeam.getKind().getColor() + player.getName() + ChatColor.WHITE + " left the zone."); } playerTeam.resetSign(); if (this.getLobby() != null) { this.getLobby().resetTeamGateSign(playerTeam); } if (this.hasPlayerState(player.getName())) { this.restorePlayerState(player); } if (this.getLoadoutSelections().containsKey(player.getName())) { // clear inventory selection this.getLoadoutSelections().remove(player.getName()); } player.setFireTicks(0); player.setRemainingAir(300); // To hide stats if (War.war.isSpoutServer()) { War.war.getSpoutDisplayer().updateStats(player); } War.war.msg(player, "Your inventory is being restored."); if (War.war.getWarHub() != null) { War.war.getWarHub().resetZoneSign(this); } boolean zoneEmpty = true; for (Team team : this.getTeams()) { if (team.getPlayers().size() > 0) { zoneEmpty = false; break; } } if (zoneEmpty && this.getWarzoneConfig().getBoolean(WarzoneConfig.RESETONEMPTY)) { // reset the zone for a new game when the last player leaves for (Team team : this.getTeams()) { team.resetPoints(); team.setRemainingLives(team.getTeamConfig().resolveInt(TeamConfig.LIFEPOOL)); } this.getVolume().resetBlocksAsJob(); this.initializeZoneAsJob(); War.war.log("Last player left warzone " + this.getName() + ". Warzone blocks resetting automatically...", Level.INFO); } } } public boolean isEnemyTeamFlagBlock(Team playerTeam, Block block) { for (Team team : this.teams) { if (!team.getName().equals(playerTeam.getName()) && team.isTeamFlagBlock(block)) { return true; } } return false; } public boolean isFlagBlock(Block block) { for (Team team : this.teams) { if (team.isTeamFlagBlock(block)) { return true; } } return false; } public Team getTeamForFlagBlock(Block block) { for (Team team : this.teams) { if (team.isTeamFlagBlock(block)) { return team; } } return null; } public boolean isBombBlock(Block block) { for (Bomb bomb : this.bombs) { if (bomb.isBombBlock(block.getLocation())) { return true; } } return false; } public Bomb getBombForBlock(Block block) { for (Bomb bomb : this.bombs) { if (bomb.isBombBlock(block.getLocation())) { return bomb; } } return null; } public boolean isCakeBlock(Block block) { for (Cake cake : this.cakes) { if (cake.isCakeBlock(block.getLocation())) { return true; } } return false; } public Cake getCakeForBlock(Block block) { for (Cake cake : this.cakes) { if (cake.isCakeBlock(block.getLocation())) { return cake; } } return null; } // Flags public void addFlagThief(Team lostFlagTeam, String flagThief) { this.flagThieves.put(flagThief, lostFlagTeam); } public boolean isFlagThief(String suspect) { if (this.flagThieves.containsKey(suspect)) { return true; } return false; } public Team getVictimTeamForFlagThief(String thief) { return this.flagThieves.get(thief); } public void removeFlagThief(String thief) { this.flagThieves.remove(thief); } // Bomb public void addBombThief(Bomb bomb, String bombThief) { this.bombThieves.put(bombThief, bomb); } public boolean isBombThief(String suspect) { if (this.bombThieves.containsKey(suspect)) { return true; } return false; } public Bomb getBombForThief(String thief) { return this.bombThieves.get(thief); } public void removeBombThief(String thief) { this.bombThieves.remove(thief); } // Cake public void addCakeThief(Cake cake, String cakeThief) { this.cakeThieves.put(cakeThief, cake); } public boolean isCakeThief(String suspect) { if (this.cakeThieves.containsKey(suspect)) { return true; } return false; } public Cake getCakeForThief(String thief) { return this.cakeThieves.get(thief); } public void removeCakeThief(String thief) { this.cakeThieves.remove(thief); } public void clearThieves() { this.flagThieves.clear(); this.bombThieves.clear(); this.cakeThieves.clear(); } public boolean isTeamFlagStolen(Team team) { for (String playerKey : this.flagThieves.keySet()) { if (this.flagThieves.get(playerKey).getName().equals(team.getName())) { return true; } } return false; } public void handleScoreCapReached(String winnersStr) { // Score cap reached. Reset everything. this.isEndOfGame = true; new ScoreCapReachedJob(this, winnersStr).run(); // run inventory and teleports immediately to avoid inv reset problems this.reinitialize(); } public boolean isDeadMan(String playerName) { if (this.deadMenInventories.containsKey(playerName)) { return true; } return false; } public void restoreDeadmanInventory(Player player) { if (this.isDeadMan(player.getName())) { this.playerInvFromInventoryStash(player.getInventory(), this.deadMenInventories.get(player.getName())); this.deadMenInventories.remove(player.getName()); } } public void setRallyPoint(Location location) { this.rallyPoint = location; } public Location getRallyPoint() { return this.rallyPoint; } public void unload() { War.war.log("Unloading zone " + this.getName() + "...", Level.INFO); for (Team team : this.getTeams()) { for (Player player : team.getPlayers()) { this.handlePlayerLeave(player, this.getTeleport(), false); } team.getPlayers().clear(); } if (this.getLobby() != null) { this.getLobby().getVolume().resetBlocks(); } if (this.getWarzoneConfig().getBoolean(WarzoneConfig.RESETONUNLOAD)) { this.getVolume().resetBlocks(); } } public boolean isEnoughPlayers() { int teamsWithEnough = 0; for (Team team : teams) { if (team.getPlayers().size() >= this.getWarzoneConfig().getInt(WarzoneConfig.MINPLAYERS)) { teamsWithEnough++; } } if (teamsWithEnough >= this.getWarzoneConfig().getInt(WarzoneConfig.MINTEAMS)) { return true; } return false; } public HashMap<String, LoadoutSelection> getLoadoutSelections() { return loadoutSelections; } public boolean isAuthor(Player player) { // if no authors, all zonemakers can edit the zone return authors.size() == 0 || authors.contains(player.getName()); } public void addAuthor(String playerName) { authors.add(playerName); } public List<String> getAuthors() { return this.authors; } public String getAuthorsString() { String authors = ""; for (String author : this.getAuthors()) { authors += author + ","; } return authors; } public void equipPlayerLoadoutSelection(Player player, Team playerTeam, boolean isFirstRespawn, boolean isToggle) { LoadoutSelection selection = this.getLoadoutSelections().get(player.getName()); if (selection != null && !this.isRespawning(player) && playerTeam.getPlayers().contains(player)) { // Make sure that inventory resets dont occur if player has already tp'ed out (due to game end, or somesuch) // - repawn timer + this method is why inventories were getting wiped as players exited the warzone. List<Loadout> loadouts = playerTeam.getInventories().resolveNewLoadouts(); List<String> sortedNames = LoadoutYmlMapper.sortNames(Loadout.toLegacyFormat(loadouts)); sortedNames.remove("first"); for (Iterator<String> it = sortedNames.iterator(); it.hasNext();) { String loadoutName = it.next(); Loadout ldt = Loadout.getLoadout(loadouts, loadoutName); if (ldt.requiresPermission() && !player.hasPermission(ldt.getPermission())) { it.remove(); } } if (sortedNames.isEmpty()) { // Fix for zones that mistakenly only specify a `first' loadout, but do not add any others. this.handlePlayerLeave(player, this.getTeleport(), true); War.war.badMsg(player, "We couldn't find a loadout for you! Please alert the warzone maker to add a `default' loadout to this warzone."); return; } int currentIndex = selection.getSelectedIndex(); Loadout firstLoadout = Loadout.getLoadout(loadouts, "first"); int i = 0; Iterator<String> it = sortedNames.iterator(); while (it.hasNext()) { String name = (String) it.next(); if (i == currentIndex) { if (playerTeam.getTeamConfig().resolveBoolean(TeamConfig.PLAYERLOADOUTASDEFAULT) && name.equals("default")) { // Use player's own inventory as loadout this.resetInventory(playerTeam, player, this.getPlayerInventoryFromSavedState(player)); } else if (isFirstRespawn && firstLoadout != null && name.equals("default") && (firstLoadout.requiresPermission() ? player.hasPermission(firstLoadout.getPermission()) : true)) { // Get the loadout for the first spawn this.resetInventory(playerTeam, player, Loadout.getLoadout(loadouts, "first").getContents()); } else { // Use the loadout from the list in the settings this.resetInventory(playerTeam, player, Loadout.getLoadout(loadouts, name).getContents()); } if (isFirstRespawn && playerTeam.getInventories().resolveLoadouts().keySet().size() > 1) { War.war.msg(player, "Equipped " + name + " loadout (sneak to switch)."); } else if (isToggle) { War.war.msg(player, "Equipped " + name + " loadout."); } } i++; } } } private HashMap<Integer, ItemStack> getPlayerInventoryFromSavedState(Player player) { HashMap<Integer, ItemStack> playerItems = new HashMap<Integer, ItemStack>(); PlayerState originalState = this.playerStates.get(player.getName()); if (originalState != null) { int invIndex = 0; playerItems = new HashMap<Integer, ItemStack>(); for (ItemStack item : originalState.getContents()) { if (item != null && item.getTypeId() != 0) { playerItems.put(invIndex, item); } invIndex++; } if (originalState.getFeet() != null) { playerItems.put(100, originalState.getFeet()); } if (originalState.getLegs() != null) { playerItems.put(101, originalState.getLegs()); } if (originalState.getChest() != null) { playerItems.put(102, originalState.getChest()); } if (originalState.getHelmet() != null) { playerItems.put(103, originalState.getHelmet()); } if (War.war.isSpoutServer()) { SpoutManager.getPlayer(player).setTitle(originalState.getPlayerTitle()); } } return playerItems; } public WarzoneConfigBag getWarzoneConfig() { return this.warzoneConfig; } public TeamConfigBag getTeamDefaultConfig() { return this.teamDefaultConfig; } public InventoryBag getDefaultInventories() { return this.defaultInventories ; } public List<Bomb> getBombs() { return bombs; } public List<Cake> getCakes() { return cakes; } public List<String> getReallyDeadFighters() { return this.reallyDeadFighters ; } public void gameEndTeleport(Player tp) { if (this.getRallyPoint() != null) { tp.teleport(this.getRallyPoint()); } else { tp.teleport(this.getTeleport()); } tp.setFireTicks(0); tp.setRemainingAir(300); if (this.hasPlayerState(tp.getName())) { this.restorePlayerState(tp); } } public boolean isEndOfGame() { return this.isEndOfGame; } public boolean isReinitializing() { return this.isReinitializing; } // public Object getGameEndLock() { // return gameEndLock; public void setName(String newName) { this.name = newName; this.volume.setName(newName); } public HubLobbyMaterials getLobbyMaterials() { return this.lobbyMaterials; } public void setLobbyMaterials(HubLobbyMaterials lobbyMaterials) { this.lobbyMaterials = lobbyMaterials; } public boolean isOpponentSpawnPeripheryBlock(Team team, Block block) { for (Team maybeOpponent : this.getTeams()) { if (maybeOpponent != team) { Volume periphery = new Volume("periphery", this.getWorld()); periphery.setCornerOne(new BlockInfo(maybeOpponent.getSpawnVolume().getMinX()-1 , maybeOpponent.getSpawnVolume().getMinY()-1, maybeOpponent.getSpawnVolume().getMinZ()-1, 0, (byte)0)); periphery.setCornerTwo(new BlockInfo(maybeOpponent.getSpawnVolume().getMaxX()+1, maybeOpponent.getSpawnVolume().getMaxY()+1, maybeOpponent.getSpawnVolume().getMaxZ()+1, 0, (byte)0)); if (periphery.contains(block)) { return true; } } } return false; } public void setWarzoneMaterials(WarzoneMaterials warzoneMaterials) { this.warzoneMaterials = warzoneMaterials; } public WarzoneMaterials getWarzoneMaterials() { return warzoneMaterials; } }
package com.cloud.vm; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import javax.ejb.Local; import javax.naming.ConfigurationException; import org.apache.log4j.Logger; import com.cloud.agent.AgentManager; import com.cloud.agent.AgentManager.OnError; import com.cloud.agent.api.Answer; import com.cloud.agent.api.CheckVirtualMachineAnswer; import com.cloud.agent.api.CheckVirtualMachineCommand; import com.cloud.agent.api.Command; import com.cloud.agent.api.MigrateAnswer; import com.cloud.agent.api.MigrateCommand; import com.cloud.agent.api.PrepareForMigrationAnswer; import com.cloud.agent.api.PrepareForMigrationCommand; import com.cloud.agent.api.RebootAnswer; import com.cloud.agent.api.RebootCommand; import com.cloud.agent.api.StartAnswer; import com.cloud.agent.api.StartCommand; import com.cloud.agent.api.StopAnswer; import com.cloud.agent.api.StopCommand; import com.cloud.agent.api.to.VirtualMachineTO; import com.cloud.agent.manager.Commands; import com.cloud.alert.AlertManager; import com.cloud.capacity.CapacityManager; import com.cloud.cluster.ClusterManager; import com.cloud.configuration.Config; import com.cloud.configuration.ConfigurationManager; import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.consoleproxy.ConsoleProxyManager; import com.cloud.dc.DataCenter; import com.cloud.dc.HostPodVO; import com.cloud.deploy.DataCenterDeployment; import com.cloud.deploy.DeployDestination; import com.cloud.deploy.DeploymentPlan; import com.cloud.deploy.DeploymentPlanner; import com.cloud.deploy.DeploymentPlanner.ExcludeList; import com.cloud.domain.dao.DomainDao; import com.cloud.event.EventTypes; import com.cloud.event.UsageEventVO; import com.cloud.event.dao.UsageEventDao; import com.cloud.exception.AgentUnavailableException; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.InsufficientServerCapacityException; import com.cloud.exception.OperationTimedoutException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.host.Host; import com.cloud.host.dao.HostDao; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.hypervisor.HypervisorGuru; import com.cloud.network.NetworkManager; import com.cloud.network.NetworkVO; import com.cloud.org.Cluster; import com.cloud.service.ServiceOfferingVO; import com.cloud.service.dao.ServiceOfferingDao; import com.cloud.storage.DiskOfferingVO; import com.cloud.storage.Storage.ImageFormat; import com.cloud.storage.StorageManager; import com.cloud.storage.VMTemplateVO; import com.cloud.storage.Volume; import com.cloud.storage.Volume.VolumeType; import com.cloud.storage.dao.GuestOSCategoryDao; import com.cloud.storage.dao.GuestOSDao; import com.cloud.storage.dao.VMTemplateDao; import com.cloud.storage.dao.VolumeDao; import com.cloud.user.Account; import com.cloud.user.AccountManager; import com.cloud.user.User; import com.cloud.user.dao.AccountDao; import com.cloud.user.dao.UserDao; import com.cloud.utils.Journal; import com.cloud.utils.NumbersUtil; import com.cloud.utils.Pair; import com.cloud.utils.Ternary; import com.cloud.utils.component.Adapters; import com.cloud.utils.component.ComponentLocator; import com.cloud.utils.component.Inject; import com.cloud.utils.concurrency.NamedThreadFactory; import com.cloud.utils.db.DB; import com.cloud.utils.db.Transaction; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.fsm.StateListener; import com.cloud.utils.fsm.StateMachine2; import com.cloud.vm.ItWorkVO.Step; import com.cloud.vm.VirtualMachine.Event; import com.cloud.vm.VirtualMachine.State; import com.cloud.vm.dao.ConsoleProxyDao; import com.cloud.vm.dao.DomainRouterDao; import com.cloud.vm.dao.NicDao; import com.cloud.vm.dao.SecondaryStorageVmDao; import com.cloud.vm.dao.UserVmDao; import com.cloud.vm.dao.VMInstanceDao; @Local(value=VirtualMachineManager.class) public class VirtualMachineManagerImpl implements VirtualMachineManager, StateListener<State, VirtualMachine.Event, VirtualMachine> { private static final Logger s_logger = Logger.getLogger(VirtualMachineManagerImpl.class); String _name; @Inject protected StorageManager _storageMgr; @Inject protected NetworkManager _networkMgr; @Inject protected AgentManager _agentMgr; @Inject protected VMInstanceDao _vmDao; @Inject protected ServiceOfferingDao _offeringDao; @Inject protected VMTemplateDao _templateDao; @Inject protected UserDao _userDao; @Inject protected AccountDao _accountDao; @Inject protected DomainDao _domainDao; @Inject protected ClusterManager _clusterMgr; @Inject protected ItWorkDao _workDao; @Inject protected UserVmDao _userVmDao; @Inject protected DomainRouterDao _routerDao; @Inject protected ConsoleProxyDao _consoleDao; @Inject protected SecondaryStorageVmDao _secondaryDao; @Inject protected UsageEventDao _usageEventDao; @Inject protected NicDao _nicsDao; @Inject protected AccountManager _accountMgr; @Inject protected HostDao _hostDao; @Inject protected AlertManager _alertMgr; @Inject protected GuestOSCategoryDao _guestOsCategoryDao; @Inject protected GuestOSDao _guestOsDao; @Inject protected VolumeDao _volsDao; @Inject protected ConsoleProxyManager _consoleProxyMgr; @Inject protected ConfigurationManager _configMgr; @Inject protected CapacityManager _capacityMgr; @Inject(adapter=DeploymentPlanner.class) protected Adapters<DeploymentPlanner> _planners; Map<VirtualMachine.Type, VirtualMachineGuru<? extends VMInstanceVO>> _vmGurus = new HashMap<VirtualMachine.Type, VirtualMachineGuru<? extends VMInstanceVO>>(); Map<HypervisorType, HypervisorGuru> _hvGurus = new HashMap<HypervisorType, HypervisorGuru>(); protected StateMachine2<State, VirtualMachine.Event, VirtualMachine> _stateMachine; ScheduledExecutorService _executor = null; protected int _retry; protected long _nodeId; protected long _cleanupWait; protected long _cleanupInterval; protected long _cancelWait; protected long _opWaitInterval; protected int _lockStateRetry; @Override public <T extends VMInstanceVO> void registerGuru(VirtualMachine.Type type, VirtualMachineGuru<T> guru) { synchronized(_vmGurus) { _vmGurus.put(type, guru); } } @Override @DB public <T extends VMInstanceVO> T allocate(T vm, VMTemplateVO template, ServiceOfferingVO serviceOffering, Pair<? extends DiskOfferingVO, Long> rootDiskOffering, List<Pair<DiskOfferingVO, Long>> dataDiskOfferings, List<Pair<NetworkVO, NicProfile>> networks, Map<VirtualMachineProfile.Param, Object> params, DeploymentPlan plan, HypervisorType hyperType, Account owner) throws InsufficientCapacityException { if (s_logger.isDebugEnabled()) { s_logger.debug("Allocating entries for VM: " + vm); } VirtualMachineProfileImpl<T> vmProfile = new VirtualMachineProfileImpl<T>(vm, template, serviceOffering, owner, params); vm.setDataCenterId(plan.getDataCenterId()); if (plan.getPodId() != null) { vm.setPodId(plan.getPodId()); } assert (plan.getClusterId() == null && plan.getPoolId() == null) : "We currently don't support cluster and pool preset yet"; @SuppressWarnings("unchecked") VirtualMachineGuru<T> guru = (VirtualMachineGuru<T>)_vmGurus.get(vm.getType()); Transaction txn = Transaction.currentTxn(); txn.start(); vm = guru.persist(vm); if (s_logger.isDebugEnabled()) { s_logger.debug("Allocating nics for " + vm); } try { _networkMgr.allocate(vmProfile, networks); } catch (ConcurrentOperationException e) { throw new CloudRuntimeException("Concurrent operation while trying to allocate resources for the VM", e); } if (dataDiskOfferings == null) { dataDiskOfferings = new ArrayList<Pair<DiskOfferingVO, Long>>(0); } if (s_logger.isDebugEnabled()) { s_logger.debug("Allocaing disks for " + vm); } if (template.getFormat() == ImageFormat.ISO) { _storageMgr.allocateRawVolume(VolumeType.ROOT, "ROOT-" + vm.getId(), rootDiskOffering.first(), rootDiskOffering.second(), vm, owner); } else { _storageMgr.allocateTemplatedVolume(VolumeType.ROOT, "ROOT-" + vm.getId(), rootDiskOffering.first(), template, vm, owner); } for (Pair<DiskOfferingVO, Long> offering : dataDiskOfferings) { _storageMgr.allocateRawVolume(VolumeType.DATADISK, "DATA-" + vm.getId(), offering.first(), offering.second(), vm, owner); } txn.commit(); if (s_logger.isDebugEnabled()) { s_logger.debug("Allocation completed for VM: " + vm); } return vm; } protected void reserveNics(VirtualMachineProfile<? extends VMInstanceVO> vmProfile, DeployDestination dest, ReservationContext context) throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException { // List<NicVO> nics = _nicsDao.listBy(vmProfile.getId()); // for (NicVO nic : nics) { // Pair<NetworkGuru, NetworkVO> implemented = _networkMgr.implementNetwork(nic.getNetworkId(), dest, context); // NetworkGuru concierge = implemented.first(); // NetworkVO network = implemented.second(); // NicProfile profile = null; // if (nic.getReservationStrategy() == ReservationStrategy.Start) { // nic.setState(Resource.State.Reserving); // nic.setReservationId(context.getReservationId()); // _nicsDao.update(nic.getId(), nic); // URI broadcastUri = nic.getBroadcastUri(); // if (broadcastUri == null) { // network.getBroadcastUri(); // URI isolationUri = nic.getIsolationUri(); // profile = new NicProfile(nic, network, broadcastUri, isolationUri); // concierge.reserve(profile, network, vmProfile, dest, context); // nic.setIp4Address(profile.getIp4Address()); // nic.setIp6Address(profile.getIp6Address()); // nic.setMacAddress(profile.getMacAddress()); // nic.setIsolationUri(profile.getIsolationUri()); // nic.setBroadcastUri(profile.getBroadCastUri()); // nic.setReserver(concierge.getName()); // nic.setState(Resource.State.Reserved); // nic.setNetmask(profile.getNetmask()); // nic.setGateway(profile.getGateway()); // nic.setAddressFormat(profile.getFormat()); // _nicsDao.update(nic.getId(), nic); // } else { // profile = new NicProfile(nic, network, nic.getBroadcastUri(), nic.getIsolationUri()); // for (NetworkElement element : _networkElements) { // if (s_logger.isDebugEnabled()) { // s_logger.debug("Asking " + element.getName() + " to prepare for " + nic); // element.prepare(network, profile, vmProfile, dest, context); // vmProfile.addNic(profile); // _networksDao.changeActiveNicsBy(network.getId(), 1); } protected void prepareNics(VirtualMachineProfile<? extends VMInstanceVO> vmProfile, DeployDestination dest, ReservationContext context) { } @Override public <T extends VMInstanceVO> T allocate(T vm, VMTemplateVO template, ServiceOfferingVO serviceOffering, Long rootSize, Pair<DiskOfferingVO, Long> dataDiskOffering, List<Pair<NetworkVO, NicProfile>> networks, DeploymentPlan plan, HypervisorType hyperType, Account owner) throws InsufficientCapacityException { List<Pair<DiskOfferingVO, Long>> diskOfferings = new ArrayList<Pair<DiskOfferingVO, Long>>(1); if (dataDiskOffering != null) { diskOfferings.add(dataDiskOffering); } return allocate(vm, template, serviceOffering, new Pair<DiskOfferingVO, Long>(serviceOffering, rootSize), diskOfferings, networks, null, plan, hyperType, owner); } @Override public <T extends VMInstanceVO> T allocate(T vm, VMTemplateVO template, ServiceOfferingVO serviceOffering, List<Pair<NetworkVO, NicProfile>> networks, DeploymentPlan plan, HypervisorType hyperType, Account owner) throws InsufficientCapacityException { return allocate(vm, template, serviceOffering, new Pair<DiskOfferingVO, Long>(serviceOffering, null), null, networks, null, plan, hyperType, owner); } @SuppressWarnings("unchecked") private <T extends VMInstanceVO> VirtualMachineGuru<T> getVmGuru(T vm) { return (VirtualMachineGuru<T>)_vmGurus.get(vm.getType()); } @Override public <T extends VMInstanceVO> boolean expunge(T vm, User caller, Account account) throws ResourceUnavailableException { try { if (advanceExpunge(vm, caller, account)) { //Mark vms as removed remove(vm, _accountMgr.getSystemUser(), account); return true; } else { s_logger.info("Did not expunge " + vm); return false; } } catch (OperationTimedoutException e) { throw new CloudRuntimeException("Operation timed out", e); } catch (ConcurrentOperationException e) { throw new CloudRuntimeException("Concurrent operation ", e); } } @Override public <T extends VMInstanceVO> boolean advanceExpunge(T vm, User caller, Account account) throws ResourceUnavailableException, OperationTimedoutException, ConcurrentOperationException { if (vm == null || vm.getRemoved() != null) { if (s_logger.isDebugEnabled()) { s_logger.debug("Unable to find vm or vm is destroyed: " + vm); } return true; } if (!this.advanceStop(vm, false, caller, account)) { if (s_logger.isDebugEnabled()) { s_logger.debug("Unable to stop the VM so we can't expunge it."); } } if (!stateTransitTo(vm, VirtualMachine.Event.ExpungeOperation, vm.getHostId())) { s_logger.debug("Unable to destroy the vm because it is not in the correct state: " + vm.toString()); return false; } if (s_logger.isDebugEnabled()) { s_logger.debug("Destroying vm " + vm); } VirtualMachineProfile<T> profile = new VirtualMachineProfileImpl<T>(vm); _networkMgr.cleanupNics(profile); //Clean up volumes based on the vm's instance id _storageMgr.cleanupVolumes(vm.getId()); VirtualMachineGuru<T> guru = (VirtualMachineGuru<T>)_vmGurus.get(vm.getType()); guru.finalizeExpunge(vm); if (s_logger.isDebugEnabled()) { s_logger.debug("Expunged " + vm); } UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_VM_DESTROY, vm.getAccountId(), vm.getDataCenterId(), vm.getId(), vm.getName(), vm.getServiceOfferingId(), vm.getTemplateId(), null); _usageEventDao.persist(usageEvent); return true; } @Override public boolean start() { _executor.scheduleAtFixedRate(new CleanupTask(), _cleanupInterval, _cleanupInterval, TimeUnit.SECONDS); return true; } @Override public boolean stop() { return true; } @Override public boolean configure(String name, Map<String, Object> xmlParams) throws ConfigurationException { _name = name; ComponentLocator locator = ComponentLocator.getCurrentLocator(); ConfigurationDao configDao = locator.getDao(ConfigurationDao.class); Map<String, String> params = configDao.getConfiguration(xmlParams); _retry = NumbersUtil.parseInt(params.get(Config.StartRetry.key()), 10); ReservationContextImpl.setComponents(_userDao, _domainDao, _accountDao); VirtualMachineProfileImpl.setComponents(_offeringDao, _templateDao, _accountDao); Adapters<HypervisorGuru> hvGurus = locator.getAdapters(HypervisorGuru.class); for (HypervisorGuru guru : hvGurus) { _hvGurus.put(guru.getHypervisorType(), guru); } _cancelWait = NumbersUtil.parseLong(params.get(Config.VmOpCancelInterval.key()), 3600); _cleanupWait = NumbersUtil.parseLong(params.get(Config.VmOpCleanupWait.key()), 3600); _cleanupInterval = NumbersUtil.parseLong(params.get(Config.VmOpCleanupInterval.key()), 86400) * 1000; _opWaitInterval = NumbersUtil.parseLong(params.get(Config.VmOpWaitInterval.key()), 120) * 1000; _lockStateRetry = NumbersUtil.parseInt(params.get(Config.VmOpLockStateRetry.key()), 5); _executor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("Vm-Operations-Cleanup")); _nodeId = _clusterMgr.getId(); _stateMachine.registerListener(this); return true; } @Override public String getName() { return _name; } protected VirtualMachineManagerImpl() { setStateMachine(); } @Override public <T extends VMInstanceVO> T start(T vm, Map<VirtualMachineProfile.Param, Object> params, User caller, Account account) throws InsufficientCapacityException, ResourceUnavailableException { try { return advanceStart(vm, params, caller, account); } catch (ConcurrentOperationException e) { throw new CloudRuntimeException("Unable to start a VM due to concurrent operation", e); } } protected boolean checkWorkItems(VMInstanceVO vm, State state) throws ConcurrentOperationException { while (true) { ItWorkVO vo = _workDao.findByOutstandingWork(vm.getId(), state); if (vo == null) { if (s_logger.isDebugEnabled()) { s_logger.debug("Unable to find work for " + vm); } return true; } if (vo.getStep() == Step.Done) { if (s_logger.isDebugEnabled()) { s_logger.debug("Work for " + vm + " is " + vo.getStep()); } return true; } if (vo.getSecondsTaskIsInactive() > _cancelWait) { s_logger.warn("The task item for vm " + vm + " has been inactive for " + vo.getSecondsTaskIsInactive()); return false; } try { Thread.sleep(_opWaitInterval); } catch (InterruptedException e) { s_logger.info("Waiting for " + vm + " but is interrupted"); throw new ConcurrentOperationException("Waiting for " + vm + " but is interrupted"); } s_logger.debug("Waiting some more to make sure there's no activity on " + vm); } } @DB protected <T extends VMInstanceVO> Ternary<T, ReservationContext, ItWorkVO> changeToStartState(VirtualMachineGuru<T> vmGuru, T vm, User caller, Account account) throws ConcurrentOperationException { long vmId = vm.getId(); ItWorkVO work = new ItWorkVO(UUID.randomUUID().toString(), _nodeId, State.Starting, vm.getId()); int retry = _lockStateRetry; while (retry Transaction txn = Transaction.currentTxn(); txn.start(); try { if (stateTransitTo(vm, Event.StartRequested, null, work.getId())) { Journal journal = new Journal.LogJournal("Creating " + vm, s_logger); work = _workDao.persist(work); ReservationContextImpl context = new ReservationContextImpl(work.getId(), journal, caller, account); if (s_logger.isDebugEnabled()) { s_logger.debug("Successfully transitioned to start state for " + vm + " reservation id = " + work.getId()); } return new Ternary<T, ReservationContext, ItWorkVO>(vmGuru.findById(vmId), context, work); } if (s_logger.isDebugEnabled()) { s_logger.debug("Determining why we're unable to update the state to Starting for " + vm); } VMInstanceVO instance = _vmDao.lockRow(vmId, true); if (instance == null) { throw new ConcurrentOperationException("Unable to acquire lock on " + vm); } State state = instance.getState(); if (state == State.Running) { if (s_logger.isDebugEnabled()) { s_logger.debug("VM is already started: " + vm); } return null; } if (state.isTransitional()) { if (!checkWorkItems(vm, state)) { throw new ConcurrentOperationException("There are concurrent operations on the VM " + vm); } else { continue; } } if (state != State.Stopped) { s_logger.debug("VM " + vm + " is not in a state to be started: " + state); return null; } } finally { txn.commit(); } } throw new ConcurrentOperationException("Unable to change the state of " + vm); } @DB protected <T extends VMInstanceVO> boolean changeState(T vm, Event event, Long hostId, ItWorkVO work, Step step) { Transaction txn = Transaction.currentTxn(); txn.start(); if (!stateTransitTo(vm, event, hostId)) { return false; } _workDao.updateStep(work, step); txn.commit(); return true; } @Override public <T extends VMInstanceVO> T advanceStart(T vm, Map<VirtualMachineProfile.Param, Object> params, User caller, Account account) throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException { long vmId = vm.getId(); VirtualMachineGuru<T> vmGuru = getVmGuru(vm); vm = vmGuru.findById(vm.getId()); Ternary<T, ReservationContext, ItWorkVO> start = changeToStartState(vmGuru, vm, caller, account); if (start == null) { return vmGuru.findById(vmId); } vm = start.first(); ReservationContext ctx = start.second(); ItWorkVO work = start.third(); T startedVm = null; ServiceOfferingVO offering = _offeringDao.findById(vm.getServiceOfferingId()); VMTemplateVO template = _templateDao.findById(vm.getTemplateId()); DataCenterDeployment plan = new DataCenterDeployment(vm.getDataCenterId(), vm.getPodId(), null, null); HypervisorGuru hvGuru = _hvGurus.get(vm.getHypervisorType()); try { Journal journal = start.second().getJournal(); ExcludeList avoids = new ExcludeList(); int retry = _retry; while (retry-- != 0) { // It's != so that it can match -1. VirtualMachineProfileImpl<T> vmProfile = new VirtualMachineProfileImpl<T>(vm, template, offering, null, params); DeployDestination dest = null; for (DeploymentPlanner planner : _planners) { dest = planner.plan(vmProfile, plan, avoids); if (dest != null) { avoids.addHost(dest.getHost().getId()); journal.record("Deployment found ", vmProfile, dest); break; } } if (dest == null) { throw new InsufficientServerCapacityException("Unable to create a deployment for " + vmProfile, DataCenter.class, plan.getDataCenterId()); } long destHostId = dest.getHost().getId(); if (!changeState(vm, Event.OperationRetry, destHostId, work, Step.Prepare)) { throw new ConcurrentOperationException("Unable to update the state of the Virtual Machine"); } try { _storageMgr.prepare(vmProfile, dest); _networkMgr.prepare(vmProfile, dest, ctx); vmGuru.finalizeVirtualMachineProfile(vmProfile, dest, ctx); VirtualMachineTO vmTO = hvGuru.implement(vmProfile); Commands cmds = new Commands(OnError.Revert); cmds.addCommand(new StartCommand(vmTO)); vmGuru.finalizeDeployment(cmds, vmProfile, dest, ctx); vm.setPodId(dest.getPod().getId()); work = _workDao.findById(work.getId()); if (work == null || work.getStep() != Step.Prepare) { throw new ConcurrentOperationException("Work steps have been changed: " + work); } _workDao.updateStep(work, Step.Start); _agentMgr.send(destHostId, cmds); _workDao.updateStep(work, Step.Started); Answer startAnswer = cmds.getAnswer(StartAnswer.class); if (startAnswer != null && startAnswer.getResult()) { if (vmGuru.finalizeStart(vmProfile, destHostId, cmds, ctx)) { if (!changeState(vm, Event.OperationSucceeded, destHostId, work, Step.Done)) { throw new ConcurrentOperationException("Unable to transition to a new state."); } startedVm = vm; if (s_logger.isDebugEnabled()) { s_logger.debug("Creation complete for VM " + vm); } return startedVm; } } s_logger.info("Unable to start VM on " + dest.getHost() + " due to " + (startAnswer == null ? " no start answer" : startAnswer.getDetails())); } catch (OperationTimedoutException e) { s_logger.debug("Unable to send the start command to host " + dest.getHost()); if (e.isActive()) { //TODO: This one is different as we're not sure if the VM is actually started. } avoids.addHost(destHostId); continue; } catch (ResourceUnavailableException e) { if (!avoids.add(e)) { if (e.getScope() == Volume.class || e.getScope() == Nic.class) { throw e; } else { throw new CloudRuntimeException("Resource is not available to start the VM.", e); } } s_logger.info("Unable to contact resource.", e); continue; } catch (InsufficientCapacityException e) { if (!avoids.add(e)) { if (e.getScope() == Volume.class || e.getScope() == Nic.class) { throw e; } else { throw new CloudRuntimeException("Insufficient capacity to start the VM.", e); } } s_logger.info("Insufficient capacity ", e); continue; } catch (RuntimeException e) { s_logger.warn("Failed to start instance " + vm, e); throw new CloudRuntimeException("Failed to start " + vm, e); } finally { if (startedVm == null) { _workDao.updateStep(work, Step.Release); cleanup(vmGuru, vmProfile, work, false, caller, account); } } } } finally { if (startedVm == null) { changeState(vm, Event.OperationFailed, null, work, Step.Done); } } return startedVm; } @Override public <T extends VMInstanceVO> boolean stop(T vm, User user, Account account) throws ResourceUnavailableException { try { return advanceStop(vm, false, user, account); } catch (OperationTimedoutException e) { throw new AgentUnavailableException("Unable to stop vm because the operation to stop timed out", vm.getHostId(), e); } catch (ConcurrentOperationException e) { throw new CloudRuntimeException("Unable to stop vm because of a concurrent operation", e); } } protected <T extends VMInstanceVO> boolean sendStop(VirtualMachineGuru<T> guru, VirtualMachineProfile<T> profile, boolean force) { VMInstanceVO vm = profile.getVirtualMachine(); StopCommand stop = new StopCommand(vm, vm.getInstanceName(), null); try { StopAnswer answer = (StopAnswer)_agentMgr.send(vm.getHostId(), stop); if (!answer.getResult()) { s_logger.debug("Unable to stop VM due to " + answer.getDetails()); return false; } guru.finalizeStop(profile, answer); } catch (AgentUnavailableException e) { if (!force) { return false; } } catch (OperationTimedoutException e) { if (!force) { return false; } } return true; } protected <T extends VMInstanceVO> boolean cleanup(VirtualMachineGuru<T> guru, VirtualMachineProfile<T> profile, ItWorkVO work, boolean force, User user, Account account) { T vm = profile.getVirtualMachine(); State state = vm.getState(); s_logger.debug("Cleaning up resources for the vm " + vm + " in " + state + " state"); if (state == State.Starting) { Step step = work.getStep(); if (step == Step.Start && !force) { s_logger.warn("Unable to cleanup vm " + vm + "; work state is incorrect: " + step); return false; } if (step == Step.Started || step == Step.Start) { if (vm.getHostId() != null) { if (!sendStop(guru, profile, force)) { s_logger.warn("Failed to stop vm " + vm + " in " + State.Starting + " state as a part of cleanup process"); return false; } } } if (step != Step.Release && step != Step.Prepare && step != Step.Started && step != Step.Start) { s_logger.debug("Cleanup is not needed for vm " + vm + "; work state is incorrect: " + step); return true; } } else if (state == State.Stopping) { if (vm.getHostId() != null) { if (!sendStop(guru, profile, force)) { s_logger.warn("Failed to stop vm " + vm + " in " + State.Stopping + " state as a part of cleanup process"); return false; } } } else if (state == State.Migrating) { if (vm.getHostId() != null) { if (!sendStop(guru, profile, force)) { s_logger.warn("Failed to stop vm " + vm + " in " + State.Migrating + " state as a part of cleanup process"); return false; } } if (vm.getLastHostId() != null) { if (!sendStop(guru, profile, force)) { s_logger.warn("Failed to stop vm " + vm + " in " + State.Migrating + " state as a part of cleanup process"); return false; } } } else if (state == State.Running) { if (!sendStop(guru, profile, force)) { s_logger.warn("Failed to stop vm " + vm + " in " + State.Running + " state as a part of cleanup process"); return false; } } _networkMgr.release(profile, force); _storageMgr.release(profile); s_logger.debug("Successfully cleanued up resources for the vm " + vm + " in " + state + " state"); return true; } @Override public <T extends VMInstanceVO> boolean advanceStop(T vm, boolean forced, User user, Account account) throws AgentUnavailableException, OperationTimedoutException, ConcurrentOperationException { long vmId = vm.getId(); State state = vm.getState(); if (state == State.Stopped) { if (s_logger.isDebugEnabled()) { s_logger.debug("VM is already stopped: " + vm); } return true; } if (state == State.Destroyed || state == State.Expunging || state == State.Error) { if (s_logger.isDebugEnabled()) { s_logger.debug("Stopped called on " + vm + " but the state is " + state); } return true; } VirtualMachineGuru<T> vmGuru = getVmGuru(vm); if (!stateTransitTo(vm, Event.StopRequested, vm.getHostId())) { if (!forced) { throw new ConcurrentOperationException("VM is being operated on by someone else."); } vm = vmGuru.findById(vmId); if (vm == null) { if (s_logger.isDebugEnabled()) { s_logger.debug("Unable to find VM " + vmId); } return true; } } if ((vm.getState() == State.Starting || vm.getState() == State.Stopping || vm.getState() == State.Migrating) && forced) { ItWorkVO work = _workDao.findByOutstandingWork(vm.getId(), vm.getState()); if (work != null) { if (cleanup(vmGuru, new VirtualMachineProfileImpl<T>(vm), work, forced, user, account)) { return stateTransitTo(vm, Event.AgentReportStopped, null); } } } VirtualMachineProfile<T> profile = new VirtualMachineProfileImpl<T>(vm); if (vm.getHostId() != null) { String routerPrivateIp = null; if(vm.getType() == VirtualMachine.Type.DomainRouter){ routerPrivateIp = vm.getPrivateIpAddress(); } StopCommand stop = new StopCommand(vm, vm.getInstanceName(), null, routerPrivateIp); boolean stopped = false; StopAnswer answer = null; try { answer = (StopAnswer)_agentMgr.send(vm.getHostId(), stop); stopped = answer.getResult(); if (!stopped) { throw new CloudRuntimeException("Unable to stop the virtual machine due to " + answer.getDetails()); } else { if(vm.getType() == VirtualMachine.Type.User){ UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_VM_STOP, vm.getAccountId(), vm.getDataCenterId(), vm.getId(), vm.getName(), vm.getServiceOfferingId(), vm.getTemplateId(), null); _usageEventDao.persist(usageEvent); } } vmGuru.finalizeStop(profile, answer); } catch (AgentUnavailableException e) { } catch (OperationTimedoutException e) { } finally { if (!stopped) { if (!forced) { stateTransitTo(vm, Event.OperationFailed, vm.getHostId()); } else { s_logger.warn("Unable to actually stop " + vm + " but continue with release because it's a force stop"); } } } } if (s_logger.isDebugEnabled()) { s_logger.debug(vm + " is stopped on the host. Proceeding to release resource held."); } try { _networkMgr.release(profile, forced); s_logger.debug("Successfully released network resources for the vm " + vm); } catch (Exception e) { s_logger.warn("Unable to release some network resources.", e); } try { _storageMgr.release(profile); s_logger.debug("Successfully released storage resources for the vm " + vm); } catch (Exception e) { s_logger.warn("Unable to release storage resources.", e); } vm.setReservationId(null); return stateTransitTo(vm, Event.OperationSucceeded, null); } private void setStateMachine() { _stateMachine = VirtualMachine.State.getStateMachine(); } protected boolean stateTransitTo(VMInstanceVO vm, VirtualMachine.Event e, Long hostId, String reservationId) { vm.setReservationId(reservationId); return _stateMachine.transitTo(vm, e, hostId, _vmDao); } @Override public boolean stateTransitTo(VMInstanceVO vm, VirtualMachine.Event e, Long hostId) { return _stateMachine.transitTo(vm, e, hostId, _vmDao); } @Override public <T extends VMInstanceVO> boolean remove(T vm, User user, Account caller) { //expunge the corresponding nics VirtualMachineProfile<T> profile = new VirtualMachineProfileImpl<T>(vm); _networkMgr.expungeNics(profile); s_logger.trace("Nics of the vm " + vm + " are expunged successfully"); return _vmDao.remove(vm.getId()); } @Override public <T extends VMInstanceVO> boolean destroy(T vm, User user, Account caller) throws AgentUnavailableException, OperationTimedoutException, ConcurrentOperationException { if (s_logger.isDebugEnabled()) { s_logger.debug("Destroying vm " + vm.toString()); } if (vm == null || vm.getState() == State.Destroyed || vm.getState() == State.Expunging || vm.getRemoved() != null) { if (s_logger.isDebugEnabled()) { s_logger.debug("Unable to find vm or vm is destroyed: " + vm); } return true; } if (!advanceStop(vm, false, user, caller)) { s_logger.debug("Unable to stop " + vm); return false; } if (!stateTransitTo(vm, VirtualMachine.Event.DestroyRequested, vm.getHostId())) { s_logger.debug("Unable to destroy the vm because it is not in the correct state: " + vm.toString()); return false; } return true; } @Override public <T extends VMInstanceVO> T migrate(T vm, long srcHostId, DeployDestination dest) throws ResourceUnavailableException { s_logger.info("Migrating " + vm + " to " + dest); long dstHostId = dest.getHost().getId(); Host fromHost = _hostDao.findById(srcHostId); if (fromHost == null) { s_logger.info("Unable to find the host to migrate from: " + srcHostId); return null; } VirtualMachineGuru<T> vmGuru = getVmGuru(vm); vm = vmGuru.findById(vm.getId()); if (vm == null || vm.getRemoved() != null) { if (s_logger.isDebugEnabled()) { s_logger.debug("Unable to find the vm " + vm); } return null; } short alertType = AlertManager.ALERT_TYPE_USERVM_MIGRATE; if (VirtualMachine.Type.DomainRouter.equals(vm.getType())) { alertType = AlertManager.ALERT_TYPE_DOMAIN_ROUTER_MIGRATE; } else if (VirtualMachine.Type.ConsoleProxy.equals(vm.getType())) { alertType = AlertManager.ALERT_TYPE_CONSOLE_PROXY_MIGRATE; } VirtualMachineProfile<VMInstanceVO> profile = new VirtualMachineProfileImpl<VMInstanceVO>(vm); _networkMgr.prepareNicForMigration(profile, dest); _storageMgr.prepareForMigration(profile, dest); HypervisorGuru hvGuru = _hvGurus.get(vm.getHypervisorType()); VirtualMachineTO to = hvGuru.implement(profile); PrepareForMigrationCommand pfmc = new PrepareForMigrationCommand(to); PrepareForMigrationAnswer pfma; try { pfma = (PrepareForMigrationAnswer)_agentMgr.send(dstHostId, pfmc); } catch (OperationTimedoutException e1) { throw new AgentUnavailableException("Operation timed out", dstHostId); } if (!pfma.getResult()) { throw new AgentUnavailableException(pfma.getDetails(), dstHostId); } boolean migrated = false; try { vm.setLastHostId(srcHostId); if (vm == null || vm.getRemoved() != null || vm.getHostId() == null || vm.getHostId() != srcHostId || !stateTransitTo(vm, Event.MigrationRequested, dstHostId)) { s_logger.info("Migration cancelled because state has changed: " + vm); return null; } boolean isWindows = _guestOsCategoryDao.findById(_guestOsDao.findById(vm.getGuestOSId()).getCategoryId()).getName().equalsIgnoreCase("Windows"); MigrateCommand mc = new MigrateCommand(vm.getInstanceName(), dest.getHost().getPrivateIpAddress(), isWindows); MigrateAnswer ma = (MigrateAnswer)_agentMgr.send(vm.getLastHostId(), mc); if (!ma.getResult()) { return null; } Commands cmds = new Commands(OnError.Revert); CheckVirtualMachineCommand cvm = new CheckVirtualMachineCommand(vm.getInstanceName()); cmds.addCommand(cvm); _agentMgr.send(dstHostId, cmds); CheckVirtualMachineAnswer answer = cmds.getAnswer(CheckVirtualMachineAnswer.class); if (!answer.getResult()) { s_logger.debug("Unable to complete migration for " + vm.toString()); stateTransitTo(vm, VirtualMachine.Event.AgentReportStopped, null); return null; } State state = answer.getState(); if (state == State.Stopped) { s_logger.warn("Unable to complete migration as we can not detect it on " + dest.getHost()); stateTransitTo(vm, VirtualMachine.Event.AgentReportStopped, null); return null; } stateTransitTo(vm, VirtualMachine.Event.OperationSucceeded, dstHostId); migrated = true; return vm; } catch (final OperationTimedoutException e) { s_logger.debug("operation timed out"); if (e.isActive()) { // FIXME: scheduleRestart(vm, true); } throw new AgentUnavailableException("Operation timed out: ", dstHostId); } finally { if (!migrated) { s_logger.info("Migration was unsuccessful. Cleaning up: " + vm.toString()); _alertMgr.sendAlert(alertType, fromHost.getDataCenterId(), fromHost.getPodId(), "Unable to migrate vm " + vm.getName() + " from host " + fromHost.getName() + " in zone " + dest.getDataCenter().getName() + " and pod " + dest.getPod().getName(), "Migrate Command failed. Please check logs."); stateTransitTo(vm, Event.MigrationFailedOnSource, srcHostId); Command cleanup = vmGuru.cleanup(vm, null); _agentMgr.easySend(dstHostId, cleanup); } } } @Override public boolean migrateAway(VirtualMachine.Type vmType, long vmId, long srcHostId) throws InsufficientServerCapacityException { VirtualMachineGuru<? extends VMInstanceVO> vmGuru = _vmGurus.get(vmType); VMInstanceVO vm = vmGuru.findById(vmId); if (vm == null) { s_logger.debug("Unable to find a VM for " + vmId); return true; } VirtualMachineProfile<VMInstanceVO> profile = new VirtualMachineProfileImpl<VMInstanceVO>(vm); Long hostId = vm.getHostId(); if (hostId == null) { s_logger.debug("Unable to migrate because the VM doesn't have a host id: " + vm); return true; } Host host = _hostDao.findById(hostId); DataCenterDeployment plan = new DataCenterDeployment(host.getDataCenterId(), host.getPodId(), host.getClusterId(), null); ExcludeList excludes = new ExcludeList(); excludes.addHost(hostId); DeployDestination dest = null; while (true) { for (DeploymentPlanner planner : _planners) { dest = planner.plan(profile, plan, excludes); if (dest != null) { if (s_logger.isDebugEnabled()) { s_logger.debug("Planner " + planner + " found " + dest + " for migrating to."); } break; } if (s_logger.isDebugEnabled()) { s_logger.debug("Planner " + planner + " was unable to find anything."); } } if (dest == null) { throw new InsufficientServerCapacityException("Unable to find a server to migrate to.", host.getClusterId()); } excludes.addHost(dest.getHost().getId()); try { vm = migrate(vm, srcHostId, dest); } catch (ResourceUnavailableException e) { s_logger.debug("Unable to migrate to unavailable " + dest); } if (vm != null) { return true; } } } protected class CleanupTask implements Runnable { @Override public void run() { s_logger.trace("VM Operation Thread Running"); try { _workDao.cleanup(_cleanupWait); } catch (Exception e) { s_logger.error("VM Operations failed due to ", e); } } } @Override public <T extends VMInstanceVO> T reboot(T vm, Map<VirtualMachineProfile.Param, Object> params, User caller, Account account) throws InsufficientCapacityException, ResourceUnavailableException { try { return advanceReboot(vm, params, caller, account); } catch (ConcurrentOperationException e) { throw new CloudRuntimeException("Unable to reboot a VM due to concurrent operation", e); } } @Override public <T extends VMInstanceVO> T advanceReboot(T vm, Map<VirtualMachineProfile.Param, Object> params, User caller, Account account) throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException { T rebootedVm = null; DataCenter dc = _configMgr.getZone(vm.getDataCenterId()); HostPodVO pod = _configMgr.getPod(vm.getPodId()); Host host = _hostDao.findById(vm.getHostId()); Cluster cluster = null; if (host != null) { cluster = _configMgr.getCluster(host.getClusterId()); } DeployDestination dest = new DeployDestination(dc, pod, cluster, host); ReservationContext ctx = new ReservationContextImpl(null, null, caller, account); VirtualMachineProfile<VMInstanceVO> vmProfile = new VirtualMachineProfileImpl<VMInstanceVO>(vm); try { //prepare all network elements (start domR/dhcp if needed) _networkMgr.prepare(vmProfile, dest, ctx); Commands cmds = new Commands(OnError.Revert); cmds.addCommand(new RebootCommand(vm.getName())); _agentMgr.send(host.getId(), cmds); Answer rebootAnswer = cmds.getAnswer(RebootAnswer.class); if (rebootAnswer != null && rebootAnswer.getResult()) { rebootedVm = vm; return rebootedVm; } s_logger.info("Unable to reboot VM " + vm + " on " + dest.getHost() + " due to " + (rebootAnswer == null ? " no reboot answer" : rebootAnswer.getDetails())); } catch (OperationTimedoutException e) { s_logger.warn("Unable to send the reboot command to host " + dest.getHost() + " for the vm " + vm + " due to operation timeout", e); throw new CloudRuntimeException("Failed to reboot the vm on host " + dest.getHost()); } return rebootedVm; } @Override public boolean preStateTransitionEvent(State oldState, Event event, State newState, VirtualMachine vm, boolean transitionStatus, Long id) { s_logger.debug("VM state transitted from :" + oldState + " to " + newState + " with event: " + event + "vm's original host id: " + vm.getHostId() + " new host id: " + id); if (!transitionStatus) { return false; } if (oldState == State.Starting) { if (event == Event.OperationSucceeded) { if (vm.getLastHostId() != null && vm.getLastHostId() != id) { /*need to release the reserved capacity on lasthost*/ _capacityMgr.releaseVmCapacity(vm, true, false, vm.getLastHostId()); } vm.setLastHostId(id); } else if (event == Event.OperationFailed) { _capacityMgr.releaseVmCapacity(vm, false, false, vm.getHostId()); } else if (event == Event.OperationRetry) { _capacityMgr.releaseVmCapacity(vm, false, false, vm.getHostId()); } else if (event == Event.AgentReportStopped) { _capacityMgr.releaseVmCapacity(vm, false, true, vm.getHostId()); } } else if (oldState == State.Running) { if (event == Event.AgentReportStopped) { _capacityMgr.releaseVmCapacity(vm, false, true, vm.getHostId()); } } else if (oldState == State.Migrating) { if (event == Event.AgentReportStopped) { /*Release capacity from original host*/ _capacityMgr.releaseVmCapacity(vm, false, true, vm.getHostId()); } else if (event == Event.MigrationFailedOnSource) { /*release capacity from dest host*/ _capacityMgr.releaseVmCapacity(vm, false, false, id); id = vm.getHostId(); } else if (event == Event.MigrationFailedOnDest) { /*release capacify from original host*/ _capacityMgr.releaseVmCapacity(vm, false, false, vm.getHostId()); } else if (event == Event.OperationSucceeded) { _capacityMgr.releaseVmCapacity(vm, false, false, vm.getHostId()); /*set lasthost id to migration destination host id*/ vm.setLastHostId(id); } } else if (oldState == State.Stopping) { if (event == Event.AgentReportStopped || event == Event.OperationSucceeded) { _capacityMgr.releaseVmCapacity(vm, false, true, vm.getHostId()); } } else if (oldState == State.Stopped) { if (event == Event.DestroyRequested) { _capacityMgr.releaseVmCapacity(vm, true, false, vm.getLastHostId()); vm.setLastHostId(null); } } return transitionStatus; } @Override public boolean postStateTransitionEvent(State oldState, Event event, State newState, VirtualMachine vo, boolean status) { return true; } }
package risk; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Collections; public class RiskBoard { private List<Territory> territories; private static List<Colors> players; /** * Colors of game pieces. **/ public static enum Colors{ BLACK, BLUE, GREEN, PINK, RED, YELLOW, NONE; /** * Returns a random color not currently in the players list * * @return A random, unused color */ public static Colors getRandomColor(){ // get the colors not used List<Colors> colors = new ArrayList<Colors>(); for(Colors col: Colors.values()){ if(uniquePlayer(col) && !col.equals(Colors.NONE)) colors.add(col); } // roll a random number corresponding each element int rand = rollDice(colors.size())-1; // return the random element return colors.get(rand); } } // A new board will be blank, with no territories and no connections public RiskBoard(){ territories = new ArrayList<Territory>(); players = new ArrayList<Colors>(); } /** * Will attempt to setup the board based on an input file. Territories * will be added first and then routes will be set up. * <p> * A valid file should contain Regions in the format "Region: Name". * followed by the names of territories. After all the territories * in that region should be a blank line. (You can have as many regions as you like.) * Following all the regions and territories, the routes are set up by starting * a line with "Routes:". This should be followed by a list of each connection * (routes are all bi-directional) in the format "Place-Place2". * * @param fileName the name of a file containing valid board information **/ public void setup(String fileName) { try { BufferedReader br = new BufferedReader(new FileReader(fileName)); while(br.ready()){ String input = br.readLine(); if (input.contains("Region: ")){ // setup regions this.setupRegions(br); }else if(input.contains("Routes:")){ // setup routes this.setupRoutes(br); } else if (input.contains("Players: ")){ // setup number of players this.setupPlayers(br); } } } catch (FileNotFoundException e) { System.out.println("File not found: "); e.printStackTrace(); } catch (IOException e){ System.out.println("File read error: "); e.printStackTrace(); } } /** * Private method takes a BufferedReader and reads in each line, * adds connection to territory objects in the territories list until * it reaches a blank line or end of file. The accepted format is: * "Territory1-Terrotory2"; * * @param br a BufferedReader object of the file with setup information **/ private void setupRoutes(BufferedReader br) throws IOException { while(br.ready()){ String input = br.readLine(); if(input.equals("")) return; else { String[] route = input.split("-"); addConnection(route[0],route[1]); } } } /** * Method to add connections to territories. Note: all connections are 2 way. * Will ignore adds where either territory cannot be found. * * @paramfrom Territory to start in * @param to Territory to end in **/ public void addConnection(String from, String to){ Territory terraFrom = null; Territory terraTo = null; for(Territory terra : territories){ if (terra.getName().equals(from)){ terraFrom = terra; } else if(terra.getName().equals(to)){ terraTo = terra; } } if(terraFrom != null && terraTo != null){ terraFrom.addConnection(terraTo); terraTo.addConnection(terraFrom); } } /** * Looks up a territory and returns that territory's connections list. * * @param territory the territory to look up * @return a list of connections from the given territory */ public List<Territory> getConnections(String territory){ for(Territory terra : territories){ if (terra.getName().equals(territory)){ return terra.getConnections(); } } return null; } /** * Private method takes a BufferedReader and reads in each line, * creates a territory object, and adds it to the territories list until * it reaches a blank line or end of file. * * @param br a BufferedReader object of the file with setup information **/ private void setupRegions(BufferedReader br) throws IOException { while(br.ready()){ String input = br.readLine(); if(input.equals("")) return; else territories.add(new Territory(input)); } } /** * Private method takes a BufferedReader and reads in each line, * adds players and assigns them a random Colors. * * @param br a BufferedReader object of the file with setup information **/ private void setupPlayers(BufferedReader br) throws IOException { while(br.ready()){ String input = br.readLine(); if(input.equals("")) { players = new ArrayList<Colors>(); return; } else { int num = Integer.parseInt(input); addPlayers(num); } } } /** * Method that will add the specified number of players using a random color * from the Colors enum. * * @param num the number of players to add, min: 0, max: 6 **/ private void addPlayers(int num){ // error checking for out of bounds if (num < 0) num = 0; else if (num > 6) num = 6; // assigning a random, unused color for(int i = 0; i<num; i++){ Colors playerColor = Colors.getRandomColor(); while(!uniquePlayer(playerColor)){ playerColor = Colors.getRandomColor(); } players.add(playerColor); } } /** * Helper method to check if a given Colors enum is in the player list. * * @param playerColor Colors enum in question * @return true if no other is present, false otherwise **/ private static boolean uniquePlayer(Colors playerColor){ for(Colors color : players){ if(color.equals(playerColor)) return false; } return true; } /** * Returns the list of players. * * @return the list of players */ public List<Colors> getPlayerList(){ return players; } /** * Get method for territories. * * @return the territories in List<Territory> form. **/ public List<Territory> getTerritories() {return territories;} /** * Method to get the number of troops in a particular territory. * Method will return 0 for calls without a valid name. * * @param territory the name of the territory to get info from * @return returns the number of troops in a territory **/ public int getTroops(String territory) { for(Territory terra : territories){ if (terra.getName().equals(territory)){ return terra.getTroops(); } } return 0; } /** * Method to add (positive number) or subtract (negative number) troops from a given territory. * Any calls without a valid name will be ignored. This method will check to ensure the number * of troops in a territory does not fall below 0. If it does, the number will be set to 0. * * @param territory the name of the territory to add to * @param num the number of troops to add(or subtract) **/ public void changeTroops(String territory, int num) { for(Territory terra : territories){ if (terra.getName().equals(territory)){ int troops = terra.getTroops() + num; if(troops > 0){ terra.setTroops(troops); } else { terra.setTroops(0); } } } } /** * Will return the name of the faction holding the territroy given. * * @param territory the name of the territory to look up * @return a string with the name of the faction in control **/ public Colors getFaction(String territory) { for(Territory terra : territories){ if (terra.getName().equals(territory)){ return terra.getFaction(); } } return Colors.NONE; } /** * Sets the name of the faction for a partuicular territory. * * @param territory the name of the territory * @param faction the name of the faction to change it to **/ public void setFaction(String territory, Colors faction) { for(Territory terra : territories){ if (terra.getName().equals(territory)){ terra.setFaction(faction); } } } /** * Method takes an attacking territory name and a defending * territory name, checks if it is a valid attack and rolls * with the most dice possible (3) if not given. If the defending * territory reaches 0 troops, the attacker invades. * * @param attacker the attacking territory * @param defender the defending territory * @param num the number of troops to attack with (1 - 3) */ public void attack(String attacker, String defender, int num) { int defendTroops = getTroops(defender); int attackTroops = getTroops(attacker); // Error check for same owner if(getFaction(defender).equals(getFaction(attacker))) return; // Error check num is not more than available troops. if (num > 3) num = 3; if (num > attackTroops-1) num = attackTroops-1; // Check for an empty territory, will end method if true. if(defendTroops <= 0) { setFaction(defender, getFaction(attacker)); changeTroops(defender, num); return; } // Find max troops available to defend. int dNum = 1; if (defendTroops > 1) dNum = 2; //dice rolls int[] defendRolls = getRolls(dNum); int[] attackRolls = getRolls(num); // take away troops based on the highest rolls (defender's advantage) if (dNum <= num){ for (int i = 0; i < defendRolls.length; i++){ if(defendRolls[i] >= attackRolls[i]) changeTroops(attacker, -1); else changeTroops(defender, -1); } } else { for (int i = 0; i < attackRolls.length; i++){ if(defendRolls[i] >= attackRolls[i]) changeTroops(attacker, -1); else changeTroops(defender, -1); } } /* Check for 0 troops in defending territory, if so * move # of attacking troops into territory and switch faction */ if(getTroops(defender) <= 0) { setFaction(defender, getFaction(attacker)); changeTroops(defender, num); } } /** * Overflow method to attack with max troops (3). **/ public void attack(String attacker, String defender) { attack(attacker, defender, 3); } /** * Helper method to roll a number of dice in succession. * * @param num the number of times to roll dice * @return an array with the number of dice rolled. **/ private int[] getRolls(int num) { int[] rolls = new int[num]; for(int i = 0; i< num; i++){ rolls[i] = rollDice(6); } Arrays.sort(rolls); return rolls; } /** * Helper method to roll a die. * * @param i the number of sides on the dice. * @return the dice roll **/ private static int rollDice(int i) { return (int) (Math.random()*i) + 1; } /** * Sets up the board with random pieces from each player in the player list. * Will check for minimum players (3) in the player list. **/ public void randomStart() { // Error check for minimum number of players. if (players.size() > 3) return; int count = 0; // randomize territories list Collections.shuffle(territories); // iterate through the territories and assign each player in turn. for (Territory terra : territories) { terra.setFaction(players.get(count)); count++; if(count < players.size()) count = 0; } } }
package nl.dtls.fairdatapoint.domain; import nl.dtls.fairdatapoint.utils.ExampleTurtleFiles; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import org.junit.Test; import org.openrdf.model.Statement; import org.openrdf.repository.Repository; import org.openrdf.repository.RepositoryException; import org.openrdf.repository.RepositoryResult; import org.openrdf.repository.sail.SailRepository; import org.openrdf.sail.Sail; import org.openrdf.sail.memory.MemoryStore; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * StoreManagerImpl class unit tests * * @author Rajaram Kaliyaperumal * @since 2016-01-05 * @version 0.1 */ public class StoreManagerImplTest { private static final Logger LOGGER = LoggerFactory.getLogger(StoreManagerImplTest.class); /** * The triple repository can't be NULL, this test is excepted to throw * NullPointer exception */ @Test(expected = NullPointerException.class) public void exceptionForNullRepository(){ try { Repository repository = new SailRepository(null); new StoreManagerImpl(repository); } catch (RepositoryException ex) { LOGGER.error(ex.getMessage()); fail("The test is not excepted to throw RepositoryException"); } } @Test(expected = IllegalArgumentException.class) public void nullURI() { Sail store = new MemoryStore(); Repository repository = new SailRepository(store); StoreManager testStoreManager; try { testStoreManager = new StoreManagerImpl(repository); if (testStoreManager.retrieveResource(null).hasNext()) { fail("No RDF statements excepted for NULL URI"); } } catch (RepositoryException | StoreManagerException ex) { LOGGER.error(ex.getMessage()); fail("The test is not excepted to throw RepositoryException or " + "StoreManagerException"); } } @Test(expected = IllegalArgumentException.class) public void emptyURI(){ Sail store = new MemoryStore(); String uri = ""; Repository repository = new SailRepository(store); StoreManager testStoreManager; try { testStoreManager = new StoreManagerImpl(repository); if (testStoreManager.retrieveResource(uri).hasNext()) { fail("No RDF statements excepted for NULL URI"); } } catch (RepositoryException | StoreManagerException ex) { LOGGER.error(ex.getMessage()); fail("The test is not excepted to throw RepositoryException or " + "StoreManagerException"); } } /** * The test is excepted to retrieve ZERO statements * * @throws RepositoryException * @throws StoreManagerException * @throws Exception */ @Test public void retrieveNonExitingResource() throws RepositoryException, StoreManagerException, Exception { Sail store = new MemoryStore(); Repository repository = new SailRepository(store); StoreManager testStoreManager = new StoreManagerImpl(repository); ExampleTurtleFiles.storeTurtleFileToTripleStore(repository, ExampleTurtleFiles.FDP_METADATA, null, null); String uri = "http://semlab1.liacs.nl:8080/dummy"; RepositoryResult<Statement> statements = testStoreManager.retrieveResource(uri); int countStatements = 0; while(statements != null && statements.hasNext()){ countStatements = countStatements + 1; break; } testStoreManager.closeRepositoryConnection(); closeRepository(repository); assertTrue(countStatements == 0); } /** * The test is excepted retrieve to retrieve one or more statements * @throws RepositoryException * @throws StoreManagerException * @throws Exception */ @Test public void retrieveExitingResource() throws RepositoryException, StoreManagerException, Exception { Sail store = new MemoryStore(); Repository repository = new SailRepository(store); StoreManager testStoreManager = new StoreManagerImpl(repository); ExampleTurtleFiles.storeTurtleFileToTripleStore(repository, ExampleTurtleFiles.FDP_METADATA, null, null); String uri = "http://semlab1.liacs.nl:8080/fdp"; RepositoryResult<Statement> statements = testStoreManager.retrieveResource(uri); int countStatements = 0; while(statements != null && statements.hasNext()){ countStatements = countStatements + 1; break; } testStoreManager.closeRepositoryConnection(); closeRepository(repository); assertTrue(countStatements > 0); } /** * Null RepositoryConnection connection can't be closed, the test is * excepted to throw exception * * @throws Exception */ @Test(expected = StoreManagerException.class) public void closeNullRepositoryConnection() throws Exception { Sail store = new MemoryStore(); Repository repository = new SailRepository(store); StoreManager testStoreManager = new StoreManagerImpl(repository); testStoreManager.closeRepositoryConnection(); } /** * This test is attempt to close opened repositoryConnection, the test is * excepted to pass * * @throws Exception */ @Test public void closeOpenedRepositoryConnection() throws Exception { Sail store = new MemoryStore(); Repository repository = new SailRepository(store); StoreManager testStoreManager = new StoreManagerImpl(repository); String uri = "http://semlab1.liacs.nl:8080/dummy"; testStoreManager.retrieveResource(uri); testStoreManager.closeRepositoryConnection(); return; } /** * Method to close the repository * * @throws Exception */ private void closeRepository(Repository repository) throws Exception { try { if (repository != null) { repository.shutDown(); } } catch (Exception e) { LOGGER.error("Error closing repository!"); throw (new Exception(e.getMessage())); } } }
package scala.tools.partest.javaagent; import java.lang.instrument.ClassFileTransformer; import java.security.ProtectionDomain; import scala.tools.asm.ClassReader; import scala.tools.asm.ClassWriter; public class ASMTransformer implements ClassFileTransformer { private boolean shouldTransform(String className) { return // do not instrument instrumentation logic (in order to avoid infinite recursion) !className.startsWith("scala/tools/partest/instrumented/") && !className.startsWith("scala/tools/partest/javaagent/") && // we instrument all classes from empty package (!className.contains("/") || // we instrument all classes from scala package className.startsWith("scala/") || // we instrument all classes from `instrumented` package className.startsWith("instrumented/")); } public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) { if (shouldTransform(className)) { ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS); ProfilerVisitor visitor = new ProfilerVisitor(writer); ClassReader reader = new ClassReader(classfileBuffer); reader.accept(visitor, 0); return writer.toByteArray(); } else { return classfileBuffer; } } }
package imgui.examples; import glm_.vec2.Vec2; import glm_.vec2.Vec2i; import glm_.vec4.Vec4; import imgui.Cond; import imgui.ImGui; import imgui.MutableProperty0; import imgui.classes.Context; import imgui.classes.IO; import imgui.classes.InputTextCallbackData; import imgui.impl.gl.ImplGL3; import imgui.impl.glfw.ImplGlfw; import kotlin.jvm.functions.Function1; import org.lwjgl.glfw.GLFW; import org.lwjgl.opengl.GL; import org.lwjgl.system.MemoryStack; import org.lwjgl.system.Platform; import uno.glfw.GlfwWindow; import uno.glfw.VSync; import static gln.GlnKt.glClearColor; import static gln.GlnKt.glViewport; import static imgui.ImguiKt.DEBUG; import static imgui.impl.gl.CommonGLKt.setGlslVersion; import static org.lwjgl.opengl.GL11.GL_COLOR_BUFFER_BIT; import static org.lwjgl.opengl.GL11.glClear; import static uno.glfw.windowHint.Profile.core; public class OpenGL3 { // The window handle private GlfwWindow window; private Context ctx; private uno.glfw.glfw glfw = uno.glfw.glfw.INSTANCE; private uno.glfw.windowHint windowHint = uno.glfw.windowHint.INSTANCE; private ImGui imgui = ImGui.INSTANCE; private IO io; private float[] f = {0f}; private Vec4 clearColor = new Vec4(0.45f, 0.55f, 0.6f, 1f); // Java users can use both a MutableProperty0 or a Boolean Array private MutableProperty0<Boolean> showAnotherWindow = new MutableProperty0<>(false); private boolean[] showDemo = {true}; private int[] counter = {0}; private ImplGlfw implGlfw; private ImplGL3 implGl3; public static void main(String[] args) { new OpenGL3(); } private OpenGL3() { // Setup window GLFW.glfwSetErrorCallback((error, description) -> System.out.println("Glfw Error " + error + ": " + description)); glfw.init(); windowHint.setDebug(DEBUG); // Decide GL+GLSL versions if (Platform.get() == Platform.MACOSX) { // GL 3.2 + GLSL 150 setGlslVersion(150); windowHint.getContext().setVersion("3.2"); windowHint.setProfile(core); // 3.2+ only windowHint.setForwardComp(true); // Required on Mac } else { // GL 3.0 + GLSL 130 setGlslVersion(130); windowHint.getContext().setVersion("3.0"); //profile = core // 3.2+ only //forwardComp = true // 3.0+ only } // Create window with graphics context window = new GlfwWindow(1280, 720, "Dear ImGui GLFW+OpenGL3 OpenGL example", null, new Vec2i(30), true); window.makeContextCurrent(); glfw.setSwapInterval(VSync.ON); // Enable vsync // Initialize OpenGL loader GL.createCapabilities(); // Setup Dear ImGui context ctx = new Context(); //io.configFlags = io.configFlags or ConfigFlag.NavEnableKeyboard // Enable Keyboard Controls //io.configFlags = io.configFlags or ConfigFlag.NavEnableGamepad // Enable Gamepad Controls // Setup Dear ImGui style imgui.styleColorsDark(null); // imgui.styleColorsClassic(null) // Setup Platform/Renderer bindings implGlfw = new ImplGlfw(window, true, null); implGl3 = new ImplGL3(); io = imgui.getIo(); // Load Fonts /* - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use pushFont()/popFont() to select them. - addFontFromFileTTF() will return the Font so you can store it if you need to select the font among multiple. - If the file cannot be loaded, the function will return null. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling FontAtlas.build()/getTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. - Read 'docs/FONTS.txt' for more instructions and details. - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! */ //ImGuiIO& io = ImGui::GetIO(); //io.Fonts->AddFontDefault(); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/ProggyTiny.ttf", 10.0f); // Font font = io.getFonts().addFontFromFileTTF("misc/fonts/ArialUni.ttf", 18f, new FontConfig(), io.getFonts().getGlyphRangesJapanese()); // assert (font != null); /* Main loop This automatically also polls events, swaps buffers and resets the appBuffer Poll and handle events (inputs, window resize, etc.) You can read the io.wantCaptureMouse, io.wantCaptureKeyboard flags to tell if dear imgui wants to use your inputs. - When io.wantCaptureMouse is true, do not dispatch mouse input data to your main application. - When io.wantCaptureKeyboard is true, do not dispatch keyboard input data to your main application. Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. */ window.loop((MemoryStack stack) -> mainLoop()); implGlfw.shutdown(); implGl3.shutdown(); ctx.destroy(); window.destroy(); glfw.terminate(); } private void mainLoop() { // Start the Dear ImGui frame implGl3.newFrame(); implGlfw.newFrame(); imgui.newFrame(); imgui.text("Hello, world!"); // Display some text (you can use a format string too) // TODO // imgui.sliderFloat("float", f, 0, 0f, 1f, "%.3f", 1f); // Edit 1 float using a slider from 0.0f to 1.0f imgui.colorEdit3("clear color", clearColor, 0); // Edit 3 floats representing a color imgui.checkbox("Demo Window", showDemo); // Edit bools storing our windows open/close state imgui.checkbox("Another Window", showAnotherWindow); if (imgui.button("Button", new Vec2())) // Buttons return true when clicked (NB: most widgets return true when edited/activated) counter[0]++; imgui.sameLine(0f, -1f); imgui.text("counter = " + counter[0]); imgui.text("Application average %.3f ms/frame (%.1f FPS)", 1_000f / io.getFramerate(), io.getFramerate()); // 2. Show another simple window. In most cases you will use an explicit begin/end pair to name the window. if (showAnotherWindow.get()) { imgui.begin("Another Window", showAnotherWindow, 0); imgui.text("Hello from another window!"); if (imgui.button("Close Me", new Vec2())) showAnotherWindow.set(false); imgui.end(); } /* 3. Show the ImGui demo window. Most of the sample code is in imgui.showDemoWindow(). Read its code to learn more about Dear ImGui! */ if (showDemo[0]) { /* Normally user code doesn't need/want to call this because positions are saved in .ini file anyway. Here we just want to make the demo initial state a bit more friendly! */ imgui.setNextWindowPos(new Vec2(650, 20), Cond.FirstUseEver, new Vec2()); imgui.showDemoWindow(showDemo); } // Rendering imgui.render(); glViewport(window.getFramebufferSize()); glClearColor(clearColor); glClear(GL_COLOR_BUFFER_BIT); implGl3.renderDrawData(imgui.getDrawData()); } }
package uk.org.cinquin.mutinack.candidate_sequences; import java.io.Serializable; import java.text.NumberFormat; import java.util.Arrays; import java.util.Comparator; import java.util.IntSummaryStatistics; import java.util.Iterator; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.function.Consumer; import java.util.function.ToIntFunction; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.jdo.annotations.PersistenceCapable; import javax.jdo.annotations.Persistent; import org.eclipse.collections.api.bag.Bag; import org.eclipse.collections.api.bag.MutableBag; import org.eclipse.collections.api.list.primitive.MutableIntList; import org.eclipse.collections.api.multimap.set.MutableSetMultimap; import org.eclipse.collections.api.multimap.set.SetMultimap; import org.eclipse.collections.api.set.MutableSet; import org.eclipse.collections.impl.factory.Bags; import org.eclipse.collections.impl.factory.Sets; import org.eclipse.collections.impl.factory.primitive.IntLists; import org.eclipse.collections.impl.multimap.set.UnifiedSetMultimap; import org.eclipse.collections.impl.set.mutable.UnifiedSet; import org.eclipse.jdt.annotation.NonNull; import org.eclipse.jdt.annotation.Nullable; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import contrib.net.sf.samtools.util.StringUtil; import gnu.trove.TByteCollection; import gnu.trove.list.array.TByteArrayList; import gnu.trove.map.TMap; import gnu.trove.map.TObjectIntMap; import gnu.trove.map.hash.TObjectIntHashMap; import gnu.trove.map.hash.TObjectLongHashMap; import uk.org.cinquin.final_annotation.Final; import uk.org.cinquin.mutinack.Duplex; import uk.org.cinquin.mutinack.ExtendedSAMRecord; import uk.org.cinquin.mutinack.Mutation; import uk.org.cinquin.mutinack.MutationType; import uk.org.cinquin.mutinack.Mutinack; import uk.org.cinquin.mutinack.Parameters; import uk.org.cinquin.mutinack.SequenceLocation; import uk.org.cinquin.mutinack.SubAnalyzer; import uk.org.cinquin.mutinack.features.BedComplement; import uk.org.cinquin.mutinack.features.GenomeFeatureTester; import uk.org.cinquin.mutinack.features.GenomeInterval; import uk.org.cinquin.mutinack.misc_util.Assert; import uk.org.cinquin.mutinack.misc_util.ComparablePair; import uk.org.cinquin.mutinack.misc_util.Util; import uk.org.cinquin.mutinack.misc_util.collections.SingletonObjectIntMap; import uk.org.cinquin.mutinack.misc_util.exceptions.AssertionFailedException; import uk.org.cinquin.mutinack.output.LocationExaminationResults; import uk.org.cinquin.mutinack.output.json.ByteArrayStringSerializer; import uk.org.cinquin.mutinack.output.json.ByteStringSerializer; import uk.org.cinquin.mutinack.output.json.TByteArrayListSerializer; import uk.org.cinquin.mutinack.qualities.DetailedDuplexQualities; import uk.org.cinquin.mutinack.qualities.DetailedPositionQualities; import uk.org.cinquin.mutinack.qualities.DetailedQualities; import uk.org.cinquin.mutinack.qualities.Quality; import uk.org.cinquin.mutinack.statistics.Histogram; /** * Equality is computed solely based on the mutation type and sequence, and in particular * not on the list of reads that support the candidate sequence. * Note that many methods in this class are *not* thread-safe. * @author olivier * */ @PersistenceCapable public class CandidateSequence implements CandidateSequenceI, Serializable { private static final long serialVersionUID = 8222086925028013360L; @JsonIgnore private transient @Nullable MutableBag<ComparablePair<String, String>> rawMismatchesQ2, rawDeletionsQ2, rawInsertionsQ2; @Persistent private DetailedQualities<PositionAssay> quality; private transient TObjectLongHashMap<Duplex> issues; private @Nullable StringBuilder supplementalMessage; private transient TObjectIntHashMap<ExtendedSAMRecord> concurringReads; private transient @Nullable MutableSet<@NonNull Duplex> duplexes; private int nGoodDuplexes; private int nGoodDuplexesIgnoringDisag; private int nGoodOrDubiousDuplexes; private int nDuplexes; private int totalGoodDuplexes; private int totalGoodOrDubiousDuplexes; private int totalAllDuplexes; private int totalReadsAtPosition; private int averageMappingQuality = -1; private int minInsertSize = -1; private int maxInsertSize = -1; private int insertSizeAtPos10thP = -1; private int insertSizeAtPos90thP = -1; private int nWrongPairs; private byte singleBasePhredScore = -1; @Persistent @JsonSerialize(using = TByteArrayListSerializer.class) private TByteArrayList phredScores; @Persistent private Serializable preexistingDetection; private byte medianPhredAtPosition; private int minDistanceToLigSite = Integer.MAX_VALUE; private int maxDistanceToLigSite = Integer.MIN_VALUE; private float meanDistanceToLigSite = Float.NaN; private int nDistancesToLigSite = 0; private float probCollision = Float.NaN; private int nDuplexesSisterSamples = -1; private int nMatchingCandidatesOtherSamples = -1; private int smallestConcurringDuplexDistance = -1; private int largestConcurringDuplexDistance = -1; private int nQ1PlusConcurringDuplexes = -1; private float fractionTopStrandReads; private boolean topAndBottomStrandsPresent; private int topStrandDuplexes = -1; private int bottomStrandDuplexes = -1; private int negativeStrandCount = 0, positiveStrandCount = 0; @Final @Persistent private @NonNull MutationType mutationType; @Final @Persistent @JsonSerialize(using = ByteArrayStringSerializer.class) private byte @Nullable[] sequence; @JsonIgnore private transient int hashCode; @JsonSerialize(using = ByteStringSerializer.class) private byte wildtypeSequence; private final transient @NonNull ExtendedSAMRecord initialConcurringRead; @Final private int initialLigationSiteD; @Final @Persistent private @NonNull SequenceLocation location; private final transient SubAnalyzer owningSubAnalyzer; @Final private String sampleName; private boolean hidden = false; private Boolean negativeCodingStrand; private @Persistent boolean goodCandidateForUniqueMutation; @Persistent MutableSetMultimap<String, GenomeInterval> matchingGenomeIntervals; private float frequencyAtPosition; @JsonIgnore private transient Mutation mutation; //For debugging purposes private int insertSize = -1; private int positionInRead = -1; private int readEL = -1; @Nullable private String readName; private int readAlignmentStart = -1; private int mateReadAlignmentStart = -1; private int readAlignmentEnd = -1; private int mateReadAlignmentEnd = -1; private int refPositionOfMateLigationSite = 1; @Override public void reset() { restoreConcurringReads(); if (quality != null) { quality.reset(); } if (issues != null) { issues.clear(); } if (duplexes != null) { duplexes.clear();//Should have no effect } setMinDistanceToLigSite(Integer.MAX_VALUE); setMaxDistanceToLigSite(Integer.MIN_VALUE); setMeanDistanceToLigSite(Float.NaN); setnDuplexesSisterSamples(-1); setnDistancesToLigSite(0); smallestConcurringDuplexDistance = -1; largestConcurringDuplexDistance = -1; nQ1PlusConcurringDuplexes = -1; setGoodCandidateForUniqueMutation(false); matchingGenomeIntervals = null; frequencyAtPosition = -1; } @Override public void acceptLigSiteDistance(int distance) { if (distance < getMinDistanceToLigSite()) { setMinDistanceToLigSite(distance); } if (distance > getMaxDistanceToLigSite()) { setMaxDistanceToLigSite(distance); } if (getnDistancesToLigSite() == 0) { setMeanDistanceToLigSite(distance); } else { setMeanDistanceToLigSite((getMeanDistanceToLigSite() * getnDistancesToLigSite() + distance) / (getnDistancesToLigSite() + 1)); } setnDistancesToLigSite(getnDistancesToLigSite() + 1); } @Override public boolean isHidden() { return hidden; } @Override public void setHidden(boolean hidden) { this.hidden = hidden; } public byte getMedianPhredAtPosition() { return medianPhredAtPosition; } @Override public void setMedianPhredAtPosition(byte medianPhredAtPosition) { this.medianPhredAtPosition = medianPhredAtPosition; } @Override public void setProbCollision(float probCollision) { this.probCollision = probCollision; } public float getProbCollision() { return probCollision; } @SuppressWarnings("null") public CandidateSequence(String sampleName, @NonNull MutationType mutationType, byte @Nullable[] sequence) { Assert.isFalse(mutationType == MutationType.UNKNOWN); this.mutationType = Objects.requireNonNull(mutationType); this.sequence = sequence; this.sampleName = sampleName; this.owningSubAnalyzer = null; this.location = null; this.initialLigationSiteD = -1; this.initialConcurringRead = null; hashCode = computeHashCode(); } @SuppressWarnings("null") public CandidateSequence( @NonNull SubAnalyzer owningSubAnalyzer, @NonNull MutationType mutationType, byte @Nullable[] sequence, @NonNull SequenceLocation location, @NonNull ExtendedSAMRecord initialConcurringRead, int initialLigationSiteD) { this.owningSubAnalyzer = owningSubAnalyzer; this.sampleName = owningSubAnalyzer == null ? null : owningSubAnalyzer.analyzer.name; Assert.isFalse(mutationType == MutationType.UNKNOWN); this.mutationType = Objects.requireNonNull(mutationType); this.sequence = sequence; if (sequence != null) { for (byte b: sequence) { byte up = StringUtil.toUpperCase(b); try { Mutation.checkIsValidUCBase(up); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("Unknown base " + new String(new byte[] {b}) + " at " + location + " from deleted reference sequence or from sequence of read " + initialConcurringRead); } } } this.location = location; this.initialConcurringRead = initialConcurringRead; this.initialLigationSiteD = initialLigationSiteD; hashCode = computeHashCode(); } @Override public String toString() { String result = goodCandidateForUniqueMutation ? "*" : ""; result += getnQ1PlusConcurringDuplexes() + " "; result += getMutationType().toString(); switch(getMutationType()) { case WILDTYPE: break; case DELETION: throw new AssertionFailedException(); case INSERTION: break; case SUBSTITUTION: result += ": " + new String(new byte[] {getWildtypeSequence()}) + "->" + new String(getSequence()); break; default: throw new AssertionFailedException(); } result += " at " + getLocation() + ' ' + matchingGenomeIntervals + " (" + getNonMutableConcurringReads().size() + " concurring reads)"; return result; } @Override public final int hashCode() { if (hashCode == 0) {//Can happen because of serialization hashCode = computeHashCode(); } return hashCode; } private int computeHashCode() { final int prime = 31; int result = 1; result = prime * result + getMutationType().ordinal(); result = prime * result + Arrays.hashCode(getSequence()); return result; } @SuppressWarnings("EqualsWhichDoesntCheckParameterClass") @Override public boolean equals(Object obj) { if (this == obj) { return true; } CandidateSequence other = (CandidateSequence) obj; if (getMutationType() != other.getMutationType()) { return false; } if (!Arrays.equals(getSequence(), other.getSequence())) { return false; } return true; } public static final Comparator<CandidateSequence> reverseFrequencyComparator = (c1, c2) -> { int cmp1 = Float.compare(c2.getFrequencyAtPosition(), c1.getFrequencyAtPosition()); if (cmp1 != 0) { return cmp1; } return c1.getMutation().compareTo(c2.getMutation()); }; @Override public String getChange() { return getMutation().getChange(Boolean.TRUE.equals(getNegativeCodingStrand())); } @Override public int getMaxInsertSize() { return maxInsertSize; } @Override public void setMaxInsertSize(int maxInsertSize) { if (maxInsertSize < 0) { throw new IllegalArgumentException("Negative insert size: " + minInsertSize); } this.maxInsertSize = maxInsertSize; } @Override public int getMinInsertSize() { return minInsertSize; } @Override public void setMinInsertSize(int minInsertSize) { if (minInsertSize < 0) { throw new IllegalArgumentException("Negative insert size: " + minInsertSize); } this.minInsertSize = minInsertSize; } @Override public int getAverageMappingQuality() { return averageMappingQuality; } @Override public void setAverageMappingQuality(int averageMappingQuality) { this.averageMappingQuality = averageMappingQuality; } @Override public Mutinack getOwningAnalyzer() { return getOwningSubAnalyzer().analyzer; } @Override public SubAnalyzer getOwningSubAnalyzer() { return owningSubAnalyzer; } @Override public @NonNull SequenceLocation getLocation() { return location; } @Override public int getTotalReadsAtPosition() { return totalReadsAtPosition; } @Override public void setTotalReadsAtPosition(int totalReadsAtPosition) { this.totalReadsAtPosition = totalReadsAtPosition; } @Override public int getTotalAllDuplexes() { return totalAllDuplexes; } @Override public void setTotalAllDuplexes(int totalAllDuplexes) { this.totalAllDuplexes = totalAllDuplexes; } @Override public int getTotalGoodOrDubiousDuplexes() { return totalGoodOrDubiousDuplexes; } @Override public void setTotalGoodOrDubiousDuplexes(int totalGoodOrDubiousDuplexes) { this.totalGoodOrDubiousDuplexes = totalGoodOrDubiousDuplexes; } @Override public int getTotalGoodDuplexes() { return totalGoodDuplexes; } @Override public void setTotalGoodDuplexes(int totalGoodDuplexes) { this.totalGoodDuplexes = totalGoodDuplexes; } @Override public int getnDuplexes() { return nDuplexes; } @Override public void setnDuplexes(int nDuplexes) { this.nDuplexes = nDuplexes; } @Override public int getnGoodOrDubiousDuplexes() { return nGoodOrDubiousDuplexes; } @Override public void setnGoodOrDubiousDuplexes(int nGoodOrDubiousDuplexes) { this.nGoodOrDubiousDuplexes = nGoodOrDubiousDuplexes; } @Override public int getnGoodDuplexes() { return nGoodDuplexes; } @Override public void setnGoodDuplexes(int nGoodDuplexes) { this.nGoodDuplexes = nGoodDuplexes; } @SuppressWarnings("null") @Override public @NonNull MutableSet<@NonNull Duplex> getDuplexes() { if (duplexes == null) { duplexes = Sets.mutable.empty(); } return duplexes; } @Override public void setDuplexes(@NonNull MutableSet<@NonNull Duplex> duplexes) { this.duplexes = duplexes; } public UnifiedSet<Duplex> computeSupportingDuplexes() { UnifiedSet<Duplex> duplexesSupportingC = new UnifiedSet<>(30); getNonMutableConcurringReads().forEachKey(r -> { Assert.isFalse(r.discarded); Duplex d = r.duplex; if (d != null) { Assert.isFalse(d.invalid); duplexesSupportingC.add(d); } return true; });//Collect *unique* duplexes return duplexesSupportingC; } public static final int NO_ENTRY_VALUE = SingletonObjectIntMap.NO_ENTRY_VALUE; @SuppressWarnings("null") @Override public @NonNull TObjectIntHashMap<ExtendedSAMRecord> getMutableConcurringReads() { if (concurringReads == null) { concurringReads = new TObjectIntHashMap<>(100, 0.5f, NO_ENTRY_VALUE); if (initialConcurringRead != null) { concurringReads.put(initialConcurringRead, initialLigationSiteD); } } return concurringReads; } private transient @Nullable TObjectIntMap<ExtendedSAMRecord> singletonConcurringRead; @SuppressWarnings("null") @Override public @NonNull TObjectIntMap<ExtendedSAMRecord> getNonMutableConcurringReads() { if (concurringReads != null) { return concurringReads; } else { if (singletonConcurringRead == null) { singletonConcurringRead = new SingletonObjectIntMap<>(initialConcurringRead, initialLigationSiteD); } return singletonConcurringRead; } } public void forEachConcurringRead(Consumer<ExtendedSAMRecord> consumer) { getNonMutableConcurringReads().forEachKey(er -> {consumer.accept(er); return true;}); } public IntSummaryStatistics getConcurringReadSummaryStatistics(ToIntFunction<ExtendedSAMRecord> stat) { IntSummaryStatistics stats = new IntSummaryStatistics(); forEachConcurringRead(er -> stats.accept(stat.applyAsInt(er))); return stats; } private transient @Nullable TObjectIntHashMap<ExtendedSAMRecord> originalConcurringReads; @Override public int removeConcurringRead(@NonNull ExtendedSAMRecord er) { if (originalConcurringReads == null) { @NonNull TObjectIntMap<ExtendedSAMRecord> mutable = getMutableConcurringReads(); originalConcurringReads = new TObjectIntHashMap<>(mutable.size(), 0.5f, NO_ENTRY_VALUE); originalConcurringReads.putAll(mutable); } return getMutableConcurringReads().remove(er); } private void restoreConcurringReads() { if (originalConcurringReads != null) { concurringReads = originalConcurringReads; originalConcurringReads = null; } } @SuppressWarnings("unused") private @NonNull TObjectIntMap<ExtendedSAMRecord> getOriginalConcurringReads() { if (originalConcurringReads == null) { return getNonMutableConcurringReads(); } else { return Objects.requireNonNull(originalConcurringReads); } } @Override public @Nullable StringBuilder getSupplementalMessage() { return supplementalMessage; } @Override public void setSupplementalMessage(StringBuilder supplementalMessage) { this.supplementalMessage = supplementalMessage; } @SuppressWarnings("null") @Override public @NonNull DetailedQualities<PositionAssay> getQuality() { if (quality == null) { quality = new DetailedPositionQualities(); } return quality; } @Override public int getMaxDistanceToLigSite() { return maxDistanceToLigSite; } @Override public int getMinDistanceToLigSite() { return minDistanceToLigSite; } @Override public float getMeanDistanceToLigSite() { return meanDistanceToLigSite; } @Override public byte getWildtypeSequence() { return wildtypeSequence; } @Override public void setWildtypeSequence(byte wildtypeSequence) { this.wildtypeSequence = wildtypeSequence; } @Override public byte @Nullable[] getSequence() { return sequence; } @Override public @NonNull MutationType getMutationType() { Assert.isFalse(mutationType == MutationType.UNKNOWN); return mutationType; } @Override public @NonNull String getKind() { return getMutationType().toString(); } @Override public void addBasePhredScore(byte q) { Assert.isFalse(q < 0, "Negative Phred quality score: %s"); if (phredScores == null && singleBasePhredScore == -1) { singleBasePhredScore = q; } else { allocateBasePhredQualityArray(); phredScores.add(q); } } private void allocateBasePhredQualityArray() { if (phredScores != null) { return; } Assert.isFalse(singleBasePhredScore == -2); phredScores = new TByteArrayList(1_000); if (singleBasePhredScore != -1) { phredScores.add(singleBasePhredScore); } singleBasePhredScore = -2; } @SuppressWarnings("null") private @NonNull TByteArrayList getPhredScores() { allocateBasePhredQualityArray(); return phredScores; } @Override public byte getMedianPhredScore() { if (phredScores == null) { if (singleBasePhredScore == -2) { throw new AssertionFailedException(); } else if (singleBasePhredScore == -1) { return -1; } else { return singleBasePhredScore; } } final int nScores = phredScores.size(); if (nScores == 0) { return -1; } phredScores.sort(); return phredScores.get(nScores / 2); } @Override public void addPhredScoresToList(@NonNull TByteCollection ql) { if (phredScores == null) { if (singleBasePhredScore == -1) { return; } else if (singleBasePhredScore < 0) { throw new AssertionFailedException(); } else { ql.add(singleBasePhredScore); } } else { ql.addAll(phredScores); } } @Override public int getnWrongPairs() { return nWrongPairs; } @Override public void setnWrongPairs(int nWrongPairs) { this.nWrongPairs = nWrongPairs; } @Override public int getnGoodDuplexesIgnoringDisag() { return nGoodDuplexesIgnoringDisag; } @Override public void setnGoodDuplexesIgnoringDisag(int nGoodDuplexesIgnoringDisag) { this.nGoodDuplexesIgnoringDisag = nGoodDuplexesIgnoringDisag; } public boolean containsType(Class<? extends CandidateSequence> class1) { return class1.isInstance(this); } @Override public void mergeWith(@NonNull CandidateSequenceI candidate) { Assert.isTrue(this.getClass().isInstance(candidate), "Cannot merge %s to %s %s"/*, this, candidate, candidate.getNonMutableConcurringReads()*/); final Boolean ncs = getNegativeCodingStrand(); final Boolean ncsOther = candidate.getNegativeCodingStrand(); if (ncs != null && ncsOther != null && !ncs.equals(ncsOther)) { throw new IllegalArgumentException("At location " + location + ", candidates " + this + " and " + candidate + "disagree on template strand orientation: " + ncs + " vs " + ncsOther); } if (ncs == null) { setNegativeCodingStrand(ncsOther); } getMutableConcurringReads().putAll(candidate.getNonMutableConcurringReads()); candidate.addPhredScoresToList(getPhredScores()); acceptLigSiteDistance(candidate.getMinDistanceToLigSite()); acceptLigSiteDistance(candidate.getMaxDistanceToLigSite()); incrementNegativeStrandCount(candidate.getNegativeStrandCount()); incrementPositiveStrandCount(candidate.getPositiveStrandCount()); if (!candidate.getRawMismatchesQ2().isEmpty()) { getMutableRawMismatchesQ2().addAllIterable(candidate.getRawMismatchesQ2()); //TODO Is it //worth optimizing this out if not keeping track of raw disagreements? That would //save one list allocation per position } if (!candidate.getRawDeletionsQ2().isEmpty()) { getMutableRawDeletionsQ2().addAllIterable(candidate.getRawDeletionsQ2()); } if (!candidate.getRawInsertionsQ2().isEmpty()) { getMutableRawInsertionsQ2().addAllIterable(candidate.getRawInsertionsQ2()); } } @Override @SuppressWarnings("null") public @NonNull TObjectLongHashMap<Duplex> getIssues() { if (issues == null) { issues = new TObjectLongHashMap<>(); } return issues; } @Override @SuppressWarnings("null") public @NonNull MutableBag<ComparablePair<String, String>> getMutableRawMismatchesQ2() { if (rawMismatchesQ2 == null) { rawMismatchesQ2 = Bags.mutable.empty(); } return rawMismatchesQ2; } @Override @SuppressWarnings("null") public @NonNull Bag<ComparablePair<String, String>> getRawMismatchesQ2() { if (rawMismatchesQ2 == null) { return Bags.immutable.empty(); } return rawMismatchesQ2; } @Override @SuppressWarnings("null") public @NonNull MutableBag<ComparablePair<String, String>> getMutableRawDeletionsQ2() { if (rawDeletionsQ2 == null) { rawDeletionsQ2 = Bags.mutable.empty(); } return rawDeletionsQ2; } @Override @SuppressWarnings("null") public @NonNull Bag<ComparablePair<String, String>> getRawDeletionsQ2() { if (rawDeletionsQ2 == null) { return Bags.immutable.empty(); } return rawDeletionsQ2; } @Override @SuppressWarnings("null") public @NonNull MutableBag<ComparablePair<String, String>> getMutableRawInsertionsQ2() { if (rawInsertionsQ2 == null) { rawInsertionsQ2 = Bags.mutable.empty(); } return rawInsertionsQ2; } @Override @SuppressWarnings("null") public @NonNull Bag<ComparablePair<String, String>> getRawInsertionsQ2() { if (rawInsertionsQ2 == null) { return Bags.immutable.empty(); } return rawInsertionsQ2; } @Override public int getInsertSizeAtPos10thP() { return insertSizeAtPos10thP; } @Override public void setInsertSizeAtPos10thP(int insertSizeAtPos10thP) { this.insertSizeAtPos10thP = insertSizeAtPos10thP; } @Override public int getInsertSizeAtPos90thP() { return insertSizeAtPos90thP; } @Override public void setInsertSizeAtPos90thP(int insertSizeAtPos90thP) { this.insertSizeAtPos90thP = insertSizeAtPos90thP; } @Override public String getSampleName() { return sampleName; } private void initializeGenomeIntervals() { if (matchingGenomeIntervals == null) { matchingGenomeIntervals = new UnifiedSetMultimap<>(); } } public void addMatchingGenomeIntervals(String name, GenomeFeatureTester intervals) { initializeGenomeIntervals(); intervals.apply(location).forEach(gi -> matchingGenomeIntervals.put(name, gi)); } public void recordMatchingGenomeIntervals(TMap<String, GenomeFeatureTester> intervalsMap) { initializeGenomeIntervals(); intervalsMap.forEachEntry((setName, tester) -> { if (tester instanceof BedComplement) { return true; } addMatchingGenomeIntervals(setName, tester); return true; }); } public byte[] getSequenceContext(int windowHalfWidth) { return location.getSequenceContext(windowHalfWidth); } @Override public @NonNull String toOutputString(@Nullable Parameters param, @Nullable LocationExaminationResults examResults) { StringBuilder result = new StringBuilder(); NumberFormat formatter = Util.mediumLengthFloatFormatter.get(); Stream<String> qualityKD = Arrays.stream(getIssues().values()).mapToObj( iss -> DetailedDuplexQualities.fromLong(iss).getQualities(). filter(entry -> entry.getValue().lowerThan(Quality.GOOD)). map(Object::toString). collect(Collectors.joining(",", "{", "}"))); Assert.isTrue(nDuplexesSisterSamples > -1); //TODO The following issues added below to qualityKD should just be retrieved from the //qualities field instead of being recomputed if (param != null && nDuplexesSisterSamples < param.minNumberDuplexesSisterSamples) { qualityKD = Stream.concat(Stream.of(PositionAssay.MIN_DUPLEXES_SISTER_SAMPLE.toString()), qualityKD); } final Quality disagQ = getQuality().getQuality(PositionAssay.AT_LEAST_ONE_DISAG); if (disagQ != null) { qualityKD = Stream.concat(Stream.of(DuplexAssay.DISAGREEMENT + "<=" + disagQ), qualityKD); } if (getQuality().qualitiesContain(PositionAssay.DISAG_THAT_MISSED_Q2)) { qualityKD = Stream.concat(Stream.of(PositionAssay.DISAG_THAT_MISSED_Q2.toString()), qualityKD); } if (getnMatchingCandidatesOtherSamples() > 1) { qualityKD = Stream.concat(Stream.of(PositionAssay.PRESENT_IN_SISTER_SAMPLE.toString()), qualityKD);//TODO This is redundant now } Iterator<CandidateSequence> localCandidates = examResults == null ? null : examResults.analyzedCandidateSequences.iterator(); String qualityKDString = qualityKD.collect(Collectors.joining(",")); /** * Make sure columns stay in sync with Mutinack.outputHeader */ result.append(getnGoodDuplexes() + "\t" + getnGoodOrDubiousDuplexes() + '\t' + getnDuplexes() + '\t' + getNonMutableConcurringReads().size() + '\t' + formatter.format((getnGoodDuplexes() / ((float) getTotalGoodDuplexes()))) + '\t' + formatter.format((getnGoodOrDubiousDuplexes() / ((float) getTotalGoodOrDubiousDuplexes()))) + '\t' + formatter.format((getnDuplexes() / ((float) getTotalAllDuplexes()))) + '\t' + formatter.format((getNonMutableConcurringReads().size() / ((float) getTotalReadsAtPosition()))) + '\t' + (getAverageMappingQuality() == -1 ? "?" : getAverageMappingQuality()) + '\t' + formatter.format(fractionTopStrandReads) + '\t' + topAndBottomStrandsPresent + '\t' + new String(getSequenceContext(5)) + '\t' + nDuplexesSisterSamples + '\t' + getInsertSize() + '\t' + getInsertSizeAtPos10thP() + '\t' + getInsertSizeAtPos90thP() + '\t' + getMinDistanceToLigSite() + '\t' + getMaxDistanceToLigSite() + '\t' + Optional.ofNullable(negativeCodingStrand).map(String::valueOf).orElse("?") + '\t' + formatter.format(getMeanDistanceToLigSite()) + '\t' + formatter.format(getProbCollision()) + '\t' + getPositionInRead() + '\t' + getReadEL() + '\t' + getReadName() + '\t' + getReadAlignmentStart() + '\t' + getMateReadAlignmentStart() + '\t' + getReadAlignmentEnd() + '\t' + getMateReadAlignmentEnd() + '\t' + getRefPositionOfMateLigationSite() + '\t' + ( ( param != null && (param.outputDuplexDetails || param.annotateMutationsInFile != null)) ? qualityKDString : "" /*getIssues()*/) + '\t' + //getIssues() + '\t' + getMedianPhredAtPosition() + '\t' + (getMinInsertSize() == -1 ? "?" : getMinInsertSize()) + '\t' + (getMaxInsertSize() == -1 ? "?" : getMaxInsertSize()) + '\t' + formatter.format(localCandidates == null || !localCandidates.hasNext() ? Float.NaN : localCandidates.next().getFrequencyAtPosition()) + '\t' + formatter.format(localCandidates == null || !localCandidates.hasNext() ? Float.NaN : localCandidates.next().getFrequencyAtPosition()) + '\t' + getSmallestConcurringDuplexDistance() + '\t' + getLargestConcurringDuplexDistance() + '\t' + (getSupplementalMessage() != null ? getSupplementalMessage() : "") + '\t' ); /*result.append(matchingGenomeIntervals.keyMultiValuePairsView(). collect(p -> p.getOne().toString() + ": " + p.getTwo().makeString(", ")). makeString("; "));*/ result.append(matchingGenomeIntervals); return result.toString(); } @Override public int getnMatchingCandidatesOtherSamples() { return nMatchingCandidatesOtherSamples; } @Override public void setnMatchingCandidatesOtherSamples(int nMatchingCandidatesOtherSamples) { this.nMatchingCandidatesOtherSamples = nMatchingCandidatesOtherSamples; } @Override public Serializable getPreexistingDetection() { return preexistingDetection; } @Override public void setPreexistingDetection(Serializable preexistingDetection) { this.preexistingDetection = preexistingDetection; } @Override public int getPositiveStrandCount() { return positiveStrandCount; } @Override public int getNegativeStrandCount() { return negativeStrandCount; } @Override public void incrementPositiveStrandCount(int i) { positiveStrandCount += i; } @Override public void incrementNegativeStrandCount(int i) { negativeStrandCount += i; } @Override public @NonNull Mutation getMutation() { if (mutation == null) { mutation = new Mutation(this); } return Objects.requireNonNull(mutation); } @Override public int getnDuplexesSisterSamples() { if (nDuplexesSisterSamples < 0) { throw new IllegalStateException(); } return nDuplexesSisterSamples; } @Override public void setnDuplexesSisterSamples(int nDuplexesSisterSamples) { this.nDuplexesSisterSamples = nDuplexesSisterSamples; } public void setMinDistanceToLigSite(int minDistanceToLigSite) { this.minDistanceToLigSite = minDistanceToLigSite; } public void setMaxDistanceToLigSite(int maxDistanceToLigSite) { this.maxDistanceToLigSite = maxDistanceToLigSite; } public void setMeanDistanceToLigSite(float meanDistanceToLigSite) { this.meanDistanceToLigSite = meanDistanceToLigSite; } public int getnDistancesToLigSite() { return nDistancesToLigSite; } public void setnDistancesToLigSite(int nDistancesToLigSite) { this.nDistancesToLigSite = nDistancesToLigSite; } public int getInsertSize() { return insertSize; } @Override public void setInsertSize(int insertSize) { this.insertSize = insertSize; } public int getPositionInRead() { return positionInRead; } @Override public void setPositionInRead(int positionInRead) { this.positionInRead = positionInRead; } public int getReadEL() { return readEL; } @Override public void setReadEL(int readEL) { this.readEL = readEL; } public String getReadName() { return readName; } @Override public void setReadName(@NonNull String readName) { this.readName = readName; } public int getReadAlignmentStart() { return readAlignmentStart; } @Override public void setReadAlignmentStart(int readAlignmentStart) { this.readAlignmentStart = readAlignmentStart; } public int getMateReadAlignmentStart() { return mateReadAlignmentStart; } @Override public void setMateReadAlignmentStart(int mateReadAlignmentStart) { this.mateReadAlignmentStart = mateReadAlignmentStart; } public int getReadAlignmentEnd() { return readAlignmentEnd; } @Override public void setReadAlignmentEnd(int readAlignmentEnd) { this.readAlignmentEnd = readAlignmentEnd; } public int getMateReadAlignmentEnd() { return mateReadAlignmentEnd; } @Override public void setMateReadAlignmentEnd(int mateReadAlignmentEnd) { this.mateReadAlignmentEnd = mateReadAlignmentEnd; } public int getRefPositionOfMateLigationSite() { return refPositionOfMateLigationSite; } @Override public void setRefPositionOfMateLigationSite(int refPositionOfMateLigationSite) { this.refPositionOfMateLigationSite = refPositionOfMateLigationSite; } @Override public Boolean getNegativeCodingStrand() { return negativeCodingStrand; } @Override public void setNegativeCodingStrand(@Nullable Boolean negativeCodingStrand) { this.negativeCodingStrand = negativeCodingStrand; } @Override public int getSmallestConcurringDuplexDistance() { return smallestConcurringDuplexDistance; } @Override public int getLargestConcurringDuplexDistance() { return largestConcurringDuplexDistance; } @Override public void setGoodCandidateForUniqueMutation(boolean b) { goodCandidateForUniqueMutation = b; } @Override public boolean isGoodCandidateForUniqueMutation() { return goodCandidateForUniqueMutation; } @SuppressWarnings("static-method") protected Comparator<Duplex> getDuplexQualityComparator() { return duplexQualitycomparator; } private static final Comparator<Duplex> duplexQualitycomparator = Comparator.comparing((Duplex dr) -> CandidateSequence.staticFilterQuality(dr.localAndGlobalQuality)). thenComparing(Comparator.comparing((Duplex dr) -> dr.allRecords.size())). thenComparing(Duplex::getUnclippedAlignmentStart); @SuppressWarnings("ReferenceEquality") public int computeNQ1PlusConcurringDuplexes(Histogram concurringDuplexDistances, Parameters param) { MutableIntList alignmentStarts = IntLists.mutable.empty(); final Duplex bestSupporting = getDuplexes().max(getDuplexQualityComparator()); //Exclude duplexes whose reads all have an unmapped mate from the count //of Q1-Q2 duplexes that agree with the mutation; otherwise failed reads //may cause an overestimate of that number //Also exclude duplexes with clipping greater than maxConcurringDuplexClipping final int nConcurringDuplexes = getDuplexes().count(d -> { //noinspection ObjectEquality if (d == bestSupporting) { return true; } boolean good = d.allRecords.size() >= param.minConcurringDuplexReads * 2 /* double to account for mates */ && d.localAndGlobalQuality.getValueIgnoring(assaysToIgnoreIncludingDuplexNStrands()). atLeast(Quality.GOOD) && d.allRecords.anySatisfy(r -> !r.record.getMateUnmappedFlag()) && d.allRecords.anySatisfy(r -> concurringDuplexReadClippingOK(r, param)) && d.computeMappingQuality() >= param.minMappingQualityQ1; if (good) { final int distance = d.distanceTo(bestSupporting); alignmentStarts.add(distance); if (concurringDuplexDistances != null) { concurringDuplexDistances.insert(distance); } } return good; }); if (!alignmentStarts.isEmpty()) { IntSummaryStatistics stats = alignmentStarts.summaryStatistics(); smallestConcurringDuplexDistance = stats.getMin(); largestConcurringDuplexDistance = stats.getMax(); } nQ1PlusConcurringDuplexes = nConcurringDuplexes; return nConcurringDuplexes; } @Override public int getnQ1PlusConcurringDuplexes() { return nQ1PlusConcurringDuplexes; } @Override public SetMultimap<String, GenomeInterval> getMatchingGenomeIntervals() { return matchingGenomeIntervals; } public static @NonNull Quality staticFilterQuality(DetailedQualities<DuplexAssay> localAndGlobalQuality) { return localAndGlobalQuality.getNonNullValue(); } @SuppressWarnings("static-method") public @NonNull Quality filterQuality(DetailedQualities<DuplexAssay> localAndGlobalQuality) { return staticFilterQuality(localAndGlobalQuality); } @SuppressWarnings("static-method") protected Set<DuplexAssay> assaysToIgnoreIncludingDuplexNStrands() { return SubAnalyzer.ASSAYS_TO_IGNORE_FOR_DUPLEX_NSTRANDS; } @SuppressWarnings("static-method") protected boolean concurringDuplexReadClippingOK(ExtendedSAMRecord r, Parameters param) { return r.getnClipped() < param.maxConcurringDuplexClipping && r.getMate() != null && r.getMate().getnClipped() < param.maxConcurringDuplexClipping; } public void updateQualities(@SuppressWarnings("unused") @NonNull Parameters param) { } public void computeNBottomTopStrandReads() { final long topReads = getDuplexes().sumOfInt(d -> d.topStrandRecords.size()); final float bottomReads = getDuplexes().sumOfInt(d -> d.bottomStrandRecords.size()); setFractionTopStrandReads(topReads / (topReads + bottomReads)); setTopAndBottomStrandsPresent(topReads > 0 && bottomReads > 0); topStrandDuplexes = (int) getDuplexes().sumOfInt(d -> Math.min(1, d.topStrandRecords.size())); bottomStrandDuplexes = (int) getDuplexes().sumOfInt(d -> Math.min(1, d.bottomStrandRecords.size())); } private void setFractionTopStrandReads(float f) { this.fractionTopStrandReads = f; } public float getFractionTopStrandReads() { return fractionTopStrandReads; } public boolean getTopAndBottomStrandsPresent() { return topAndBottomStrandsPresent; } private void setTopAndBottomStrandsPresent(boolean topAndBottomStrandsPresent) { this.topAndBottomStrandsPresent = topAndBottomStrandsPresent; } public int getTopStrandDuplexes() { return topStrandDuplexes; } public int getBottomStrandDuplexes() { return bottomStrandDuplexes; } public float getFrequencyAtPosition() { return frequencyAtPosition; } public void setFrequencyAtPosition(float frequencyAtPosition) { this.frequencyAtPosition = frequencyAtPosition; } }
package gov.usgs.cida.gcmrcservices.mb.endpoint; import gov.usgs.cida.gcmrcservices.mb.dao.DurationCurveDAO; import gov.usgs.cida.gcmrcservices.mb.endpoint.response.ResponseEnvelope; import gov.usgs.cida.gcmrcservices.mb.endpoint.response.SuccessResponse; import gov.usgs.cida.gcmrcservices.mb.model.DurationCurvePoint; import java.util.ArrayList; import java.util.List; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import org.glassfish.jersey.server.JSONP; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author dmsibley, zmoore */ @Path("durationcurve") public class DurationCurveEndpoint { private static final Logger log = LoggerFactory.getLogger(DurationCurveEndpoint.class); private final int MAX_BINS = 2000; @GET @JSONP(queryParam="jsonp_callback") @Produces("application/javascript") public SuccessResponse<DurationCurvePoint> getDurationCurve(@QueryParam("siteId") int siteId, @QueryParam("startTime") String startTime, @QueryParam("endTime") String endTime, @QueryParam("groupId") int groupId, @QueryParam("binCount") int binCount, @QueryParam("binType") String binType) { SuccessResponse<DurationCurvePoint> result = null; List<DurationCurvePoint> durationCurve = new ArrayList<>(); if(binCount > MAX_BINS){ log.error("Too many bins: " + binCount + " (Max: " + MAX_BINS + ")"); throw new WebApplicationException(Response.status(Status.BAD_REQUEST).type("text/plain").entity("Too many bins: " + binCount + " (Max: " + MAX_BINS + ")").build()); } if(binType!= null && binType.equalsIgnoreCase("log")){ binType = "LOG_BINS"; } else if(binType!= null && binType.equalsIgnoreCase("lin")){ binType = "LIN_BINS"; } else { log.error("Invalid bin type: '" + binType + "' (Valid: 'lin' or 'log')"); throw new WebApplicationException(Response.status(Status.BAD_REQUEST).type("text/plain").entity("Invalid bin type: '" + binType + "' (Valid: 'lin' or 'log')").build()); } try { durationCurve = new DurationCurveDAO().getDurationCurve(siteId, startTime, endTime, groupId, binCount, binType); } catch (Exception e) { log.error("Could not get duration curve!", e); throw new WebApplicationException(Response.status(Status.INTERNAL_SERVER_ERROR).type("text/plain").entity("Unable to get duration curve for the specified parameters.\n\nError: " + e.getMessage()).build()); } result = new SuccessResponse<>(new ResponseEnvelope<>(durationCurve)); return result; } }
package store.server.service; import com.google.common.base.Charsets; import java.io.IOException; import java.nio.file.Files; import static java.nio.file.Files.readAllBytes; import static java.nio.file.Files.write; import java.nio.file.Path; import java.util.Map; import static java.util.Objects.requireNonNull; import store.common.MapBuilder; import store.common.hash.Guid; import store.common.value.Value; import static store.common.value.Value.of; import store.common.yaml.YamlReading; import store.common.yaml.YamlWriting; import store.server.exception.InvalidRepositoryPathException; import store.server.exception.WriteException; /** * Manages immutable persisted attributes of a repository, that are currently its name and GUID. */ class AttributesManager { private static final String ATTRIBUTES = "attributes.yml"; private static final String NAME = "name"; private static final String GUID = "guid"; private final String name; private final Guid guid; private AttributesManager(Map<String, Value> attributes) { this.name = requireNonNull(attributes.get(NAME).asString()); this.guid = requireNonNull(attributes.get(GUID).asGuid()); } public static AttributesManager create(Path path) { Map<String, Value> attributes = new MapBuilder() .put(NAME, path.getFileName().toString()) .put(GUID, Guid.random()) .build(); try { write(path.resolve(ATTRIBUTES), YamlWriting.writeValue(of(attributes)).getBytes(Charsets.UTF_8)); } catch (IOException e) { throw new WriteException(e); } return new AttributesManager(attributes); } public static AttributesManager open(Path path) { if (!Files.exists(path.resolve(ATTRIBUTES))) { throw new InvalidRepositoryPathException(); } try { String yaml = new String(readAllBytes(path.resolve(ATTRIBUTES)), Charsets.UTF_8); return new AttributesManager(YamlReading.readValue(yaml).asMap()); } catch (IOException e) { throw new WriteException(e); } } public String getName() { return name; } public Guid getGuid() { return guid; } }
package unluac.decompile; import java.util.Collections; import java.util.LinkedList; import java.util.List; import unluac.decompile.block.AlwaysLoop; import unluac.decompile.block.Block; import unluac.decompile.block.Break; import unluac.decompile.block.ForBlock; import unluac.decompile.block.NewElseEndBlock; import unluac.decompile.block.NewIfThenElseBlock; import unluac.decompile.block.NewIfThenEndBlock; import unluac.decompile.block.NewRepeatBlock; import unluac.decompile.block.NewSetBlock; import unluac.decompile.block.NewWhileBlock; import unluac.decompile.block.OuterBlock; import unluac.decompile.block.TForBlock; import unluac.decompile.condition.AndCondition; import unluac.decompile.condition.BinaryCondition; import unluac.decompile.condition.Condition; import unluac.decompile.condition.OrCondition; import unluac.decompile.condition.RegisterSetCondition; import unluac.decompile.condition.SetCondition; import unluac.decompile.condition.TestCondition; import unluac.parse.LFunction; public class ControlFlowHandler { public static boolean verbose = false; private static class Branch implements Comparable<Branch> { private static enum Type { comparison, //comparisonset, test, testset, finalset, jump; } public Branch previous; public Branch next; public int line; public int target; public Type type; public Condition cond; public int targetFirst; public int targetSecond; public boolean inverseValue; public Branch(int line, Type type, Condition cond, int targetFirst, int targetSecond) { this.line = line; this.type = type; this.cond = cond; this.targetFirst = targetFirst; this.targetSecond = targetSecond; this.inverseValue = false; this.target = -1; } @Override public int compareTo(Branch other) { return this.line - other.line; } } private static class State { public LFunction function; public Registers r; public Code code; public Branch begin_branch; public Branch end_branch; public Branch[] branches; public boolean[] reverse_targets; public List<Block> blocks; } public static List<Block> process(Decompiler d, Registers r) { State state = new State(); state.function = d.function; state.r = r; state.code = d.code; find_reverse_targets(state); find_branches(state); combine_branches(state); initialize_blocks(state); find_fixed_blocks(state); find_while_loops(state); find_repeat_loops(state); find_break_statements(state); unredirect_branches(state); find_blocks(state); // DEBUG: print branches stuff /* Branch b = state.begin_branch; while(b != null) { System.out.println("Branch at " + b.line); System.out.println("\tcondition: " + b.cond); b = b.next; } */ return state.blocks; } private static void find_reverse_targets(State state) { Code code = state.code; boolean[] reverse_targets = state.reverse_targets = new boolean[state.code.length]; for(int line = 1; line <= code.length; line++) { if(code.op(line) == Op.JMP) { int target = code.target(line); if(target <= line) { reverse_targets[target] = true; } } } } private static int find_loadboolblock(State state, int target) { int loadboolblock = -1; if(state.code.op(target) == Op.LOADBOOL) { if(state.code.C(target) != 0) { loadboolblock = target; } else if(target - 1 >= 1 && state.code.op(target - 1) == Op.LOADBOOL && state.code.C(target - 1) != 0) { loadboolblock = target - 1; } } return loadboolblock; } private static void handle_loadboolblock(State state, boolean[] skip, int loadboolblock, Condition c, int line, int target) { int loadboolvalue = state.code.B(target); int final_line = -1; if(loadboolblock - 1 >= 1 && state.code.op(loadboolblock - 1) == Op.JMP && state.code.target(loadboolblock - 1) == loadboolblock + 2) { skip[loadboolblock - 1] = true; final_line = loadboolblock - 2; } boolean inverse = false; if(loadboolvalue == 1) { inverse = true; c = c.inverse(); } Branch b; if(line + 2 == loadboolblock) { b = new Branch(line, Branch.Type.finalset, c, line + 2, loadboolblock + 2); } else { b = new Branch(line, Branch.Type.testset, c, line + 2, loadboolblock + 2); } b.target = state.code.A(loadboolblock); b.inverseValue = inverse; insert_branch(state, b); if(final_line >= line + 2 && state.branches[final_line] == null) { c = new SetCondition(final_line, get_target(state, final_line)); b = new Branch(final_line, Branch.Type.finalset, c, final_line, loadboolblock + 2); b.target = state.code.A(loadboolblock); insert_branch(state, b); } } private static void find_branches(State state) { Code code = state.code; state.branches = new Branch[state.code.length + 1]; boolean[] skip = new boolean[code.length + 1]; for(int line = 1; line <= code.length; line++) { if(!skip[line]) { switch(code.op(line)) { case EQ: case LT: case LE: { BinaryCondition.Operator op = BinaryCondition.Operator.EQ; if(code.op(line) == Op.LT) op = BinaryCondition.Operator.LT; if(code.op(line) == Op.LE) op = BinaryCondition.Operator.LE; int left = code.B(line); int right = code.C(line); int target = code.target(line + 1); Condition c = new BinaryCondition(op, line, left, right); if(code.A(line) == 1) { c = c.inverse(); } int loadboolblock = find_loadboolblock(state, target); if(loadboolblock >= 1) { handle_loadboolblock(state, skip, loadboolblock, c, line, target); } else { Branch b = new Branch(line, Branch.Type.comparison, c, line + 2, target); if(code.A(line) == 1) { b.inverseValue = true; } insert_branch(state, b); } skip[line + 1] = true; break; } case TEST: { Condition c = new TestCondition(line, code.A(line)); if(code.C(line) != 0) c = c.inverse(); int target = code.target(line + 1); int loadboolblock = find_loadboolblock(state, target); if(loadboolblock >= 1) { handle_loadboolblock(state, skip, loadboolblock, c, line, target); } else { Branch b = new Branch(line, Branch.Type.test, c, line + 2, target); b.target = code.A(line); if(code.C(line) != 0) b.inverseValue = true; insert_branch(state, b); } skip[line + 1] = true; break; } case TESTSET: { Condition c = new TestCondition(line, code.B(line)); int target = code.target(line + 1); Branch b = new Branch(line, Branch.Type.testset, c, line + 2, target); b.target = code.A(line); if(code.C(line) != 0) b.inverseValue = true; skip[line + 1] = true; insert_branch(state, b); int final_line = target - 1; if(state.branches[final_line] == null) { int loadboolblock = find_loadboolblock(state, target - 2); if(loadboolblock == -1) { if(line + 2 == target) { c = new RegisterSetCondition(line, get_target(state, line)); //c = new SetCondition(line - 1, get_target(state, line)); final_line = final_line + 1; } else { c = new SetCondition(final_line, get_target(state, final_line)); } b = new Branch(final_line, Branch.Type.finalset, c, target, target); b.target = code.A(line); insert_branch(state, b); } } break; } case JMP: { int target = code.target(line); Branch b = new Branch(line, Branch.Type.jump, null, target, target); insert_branch(state, b); break; } } } } link_branches(state); } private static void combine_branches(State state) { Branch b; b = state.end_branch; while(b != null) { b = combine_left(state, b).previous; } /* b = state.end_branch; while(b != null) { Branch result = combine_right(state, b); if(result != null) { b = result; if(b.next != null) { b = b.next; } } else { b = b.previous; } } */ } private static void unredirect_branches(State state) { // There is more complication here int[] redirect = new int[state.code.length + 1]; Branch b = state.end_branch; while(b != null) { if(b.type == Branch.Type.jump) { if(redirect[b.targetFirst] == 0) { redirect[b.targetFirst] = b.line; } else { int temp = b.targetFirst; b.targetFirst = b.targetSecond = redirect[temp]; redirect[temp] = b.line; } } b = b.previous; } b = state.begin_branch; while(b != null) { if(b.type != Branch.Type.jump) { if(redirect[b.targetSecond] != 0) { // Hack-ish -- redirect can't extend the scope boolean skip = false; if(b.targetSecond > b.line & redirect[b.targetSecond] > b.targetSecond) skip = true; if(!skip) { //System.out.println("Redirected to " + redirct[b.targetSecond] + " from " + b.targetSecond); //if(redirect[b.targetSecond] < b.targetSecond) b.targetSecond = redirect[b.targetSecond]; } } } b = b.next; } } private static void initialize_blocks(State state) { state.blocks = new LinkedList<Block>(); } private static void find_fixed_blocks(State state) { List<Block> blocks = state.blocks; Registers r = state.r; Code code = state.code; Op tforTarget = state.function.header.version.getTForTarget(); blocks.add(new OuterBlock(state.function, state.code.length)); Branch b = state.begin_branch; while(b != null) { if(b.type == Branch.Type.jump) { int line = b.line; int target = b.targetFirst; if(code.op(target) == tforTarget) { int A = code.A(target); int C = code.C(target); if(C == 0) throw new IllegalStateException(); r.setInternalLoopVariable(A, target, line + 1); //TODO: end? r.setInternalLoopVariable(A + 1, target, line + 1); r.setInternalLoopVariable(A + 2, target, line + 1); for(int index = 1; index <= C; index++) { r.setExplicitLoopVariable(A + 2 + index, line, target + 2); //TODO: end? } remove_branch(state, state.branches[line]); remove_branch(state, state.branches[target + 1]); blocks.add(new TForBlock(state.function, line + 1, target + 2, A, C, r)); } break; } b = b.next; } for(int line = 1; line <= code.length; line++) { switch(code.op(line)) { case FORPREP: { int target = code.target(line); blocks.add(new ForBlock(state.function, line + 1, target + 1, code.A(line), r)); r.setInternalLoopVariable(code.A(line), line, target + 1); r.setInternalLoopVariable(code.A(line) + 1, line, target + 1); r.setInternalLoopVariable(code.A(line) + 2, line, target + 1); r.setExplicitLoopVariable(code.A(line) + 3, line, target + 1); break; } } } } private static void unredirect(State state, int begin, int end, int line, int target) { Branch b = state.begin_branch; while(b != null) { if(b.line >= begin && b.line < end && b.targetSecond == target) { b.targetSecond = line; } b = b.next; } } private static void find_while_loops(State state) { List<Block> blocks = state.blocks; Registers r = state.r; Code code = state.code; Branch[] whileEnds = new Branch[code.length + 1]; Branch b = state.begin_branch; while(b != null) { if(b.type == Branch.Type.jump) { if(b.targetFirst < b.line) { whileEnds[b.targetFirst] = b; } } b = b.next; } for(int line = 1; line <= code.length; line++) { Branch j = whileEnds[line]; if(j != null) { int loopback = line; int end = j.line + 1; b = state.begin_branch; while(b != null) { if(is_conditional(b) && b.line >= loopback && b.line < j.line && b.targetSecond == end) { break; } b = b.next; } Block loop; if(b != null) { remove_branch(state, b); loop = new NewWhileBlock(state.function, r, b.cond, b.targetFirst, b.targetSecond); unredirect(state, loopback, end, j.line, loopback); } else { loop = new AlwaysLoop(state.function, loopback, end); unredirect(state, loopback, end, j.line, loopback); } remove_branch(state, j); blocks.add(loop); } } } private static void find_repeat_loops(State state) { List<Block> blocks = state.blocks; Branch b = state.begin_branch; while(b != null) { if(is_conditional(b)) { if(b.targetSecond < b.targetFirst) { Block block = new NewRepeatBlock(state.function, state.r, b.cond, b.targetSecond, b.targetFirst); remove_branch(state, b); blocks.add(block); } } b = b.next; } } private static void unredirect_break(State state, int line, Block enclosing) { Branch b = state.begin_branch; while(b != null) { if(is_conditional(b) && enclosing.contains(b.line) && b.targetFirst <= line && b.targetSecond == enclosing.end) { b.targetSecond = line; } b = b.next; } } private static void find_break_statements(State state) { List<Block> blocks = state.blocks; Branch b = state.begin_branch; while(b != null) { if(b.type == Branch.Type.jump) { int line = b.line; Block enclosing = null; for(Block block : blocks) { if(block.contains(line) && block.breakable()) { if(enclosing == null || enclosing.contains(block)) { enclosing = block; } } } if(enclosing != null && b.targetFirst == enclosing.end) { Block block = new Break(state.function, b.line, b.targetFirst); remove_branch(state, b); unredirect_break(state, line, enclosing); blocks.add(block); } } b = b.next; } //TODO: conditional breaks (Lua 5.2) [conflicts with unredirection] } private static void find_blocks(State state) { List<Block> blocks = state.blocks; Code code = state.code; Branch b = state.begin_branch; while(b != null) { if(is_conditional(b)) { // Conditional branches decompile to if, while, or repeat boolean has_tail = false; int tail_line = b.targetSecond - 1; int tail_target = 0; if(tail_line >= 1 && code.op(tail_line) == Op.JMP) { Branch tail_branch = state.branches[tail_line]; if(tail_branch != null && tail_branch.type == Branch.Type.jump) { has_tail = true; tail_target = tail_branch.targetFirst; } } if(b.targetSecond > b.targetFirst) { if(has_tail) { if(tail_target > tail_line) { // If -- then -- else //System.out.println("If -- then -- else"); //System.out.println("\t" + b.line + "\t" + b.cond.toString()); NewIfThenElseBlock block = new NewIfThenElseBlock(state.function, state.r, b.cond, b.targetFirst, b.targetSecond); NewElseEndBlock block2 = new NewElseEndBlock(state.function, b.targetSecond, tail_target); block.partner = block2; block2.partner = block; //System.out.println("else -- end " + block2.begin + " " + block2.end); remove_branch(state, state.branches[tail_line]); blocks.add(block); blocks.add(block2); } else { if(tail_target <= b.line) { // While //System.out.println("While"); //System.out.println("\t" + b.line + "\t" + b.cond.toString()); Block block = new NewWhileBlock(state.function, state.r, b.cond, b.targetFirst, b.targetSecond); blocks.add(block); } else { // If -- then (tail is from an inner loop) //System.out.println("If -- then"); //System.out.println("\t" + b.line + "\t" + b.cond.toString()); Block block = new NewIfThenEndBlock(state.function, state.r, b.cond, b.targetFirst, b.targetSecond); blocks.add(block); } } } else { // If -- then //System.out.println("If -- then"); //System.out.println("\t" + b.line + "\t" + b.cond.toString() + "\t" + b.targetFirst + "\t" + b.targetSecond); Block block = new NewIfThenEndBlock(state.function, state.r, b.cond, b.targetFirst, b.targetSecond); blocks.add(block); } } else { // Repeat //System.out.println("Repeat " + b.targetSecond + " .. " + b.targetFirst); //System.out.println("\t" + b.line + "\t" + b.cond.toString()); Block block = new NewRepeatBlock(state.function, state.r, b.cond, b.targetSecond, b.targetFirst); blocks.add(block); } } else if(is_assignment(b) || b.type == Branch.Type.finalset) { Block block = new NewSetBlock(state.function, b.cond, b.target, b.line, b.targetFirst, b.targetSecond, false, state.r); blocks.add(block); //System.out.println("Assign block " + b.line); } else if(b.type == Branch.Type.jump) { Block block = new Break(state.function, b.line, b.targetFirst); blocks.add(block); } b = b.next; } Collections.sort(blocks); } private static boolean is_conditional(Branch b) { return b.type == Branch.Type.comparison || b.type == Branch.Type.test; } private static boolean is_conditional(Branch b, int r) { return b.type == Branch.Type.comparison || b.type == Branch.Type.test && b.target != r; } private static boolean is_assignment(Branch b) { return b.type == Branch.Type.testset; } private static boolean is_assignment(Branch b, int r) { return b.type == Branch.Type.testset || b.type == Branch.Type.test && b.target == r; } private static boolean adjacent(State state, Branch branch0, Branch branch1) { if(branch0 == null || branch1 == null) { return false; } else { boolean adjacent = branch0.targetFirst <= branch1.line; if(adjacent) { for(int line = branch0.targetFirst; line < branch1.line; line++) { if(is_statement(state, line)) { if(verbose) System.out.println("Found statement at " + line + " between " + branch0.line + " and " + branch1.line); adjacent = false; break; } } adjacent = adjacent && !state.reverse_targets[branch1.line]; } return adjacent; } } private static Branch combine_left(State state, Branch branch1) { if(is_conditional(branch1)) { return combine_conditional(state, branch1); } else { return combine_assignment(state, branch1); } } private static Branch combine_conditional(State state, Branch branch1) { Branch branch0 = branch1.previous; if(adjacent(state, branch0, branch1) && is_conditional(branch0) && is_conditional(branch1)) { if(branch0.targetSecond == branch1.targetFirst) { // Combination if not branch0 or branch1 then branch0 = combine_conditional(state, branch0); Condition c = new OrCondition(branch0.cond.inverse(), branch1.cond); Branch branchn = new Branch(branch0.line, Branch.Type.comparison, c, branch1.targetFirst, branch1.targetSecond); branchn.inverseValue = branch1.inverseValue; if(verbose) System.err.println("conditional or " + branchn.line); replace_branch(state, branch0, branch1, branchn); return combine_conditional(state, branchn); } else if(branch0.targetSecond == branch1.targetSecond) { // Combination if branch0 and branch1 then branch0 = combine_conditional(state, branch0); Condition c = new AndCondition(branch0.cond, branch1.cond); Branch branchn = new Branch(branch0.line, Branch.Type.comparison, c, branch1.targetFirst, branch1.targetSecond); branchn.inverseValue = branch1.inverseValue; if(verbose) System.err.println("conditional and " + branchn.line); replace_branch(state, branch0, branch1, branchn); return combine_conditional(state, branchn); } } return branch1; } private static Branch combine_assignment(State state, Branch branch1) { Branch branch0 = branch1.previous; if(adjacent(state, branch0, branch1)) { int register = branch1.target; //System.err.println("blah " + branch1.line + " " + branch0.line); if(is_conditional(branch0) && is_assignment(branch1)) { //System.err.println("bridge cand " + branch1.line + " " + branch0.line); if(branch0.targetSecond == branch1.targetFirst) { boolean inverse = branch0.inverseValue; if(verbose) System.err.println("bridge " + (inverse ? "or" : "and") + " " + branch1.line + " " + branch0.line); branch0 = combine_conditional(state, branch0); if(inverse != branch0.inverseValue) throw new IllegalStateException(); Condition c; if(inverse) { //System.err.println("bridge or " + branch0.line + " " + branch0.inverseValue); c = new OrCondition(branch0.cond.inverse(), branch1.cond); } else { //System.err.println("bridge and " + branch0.line + " " + branch0.inverseValue); c = new AndCondition(branch0.cond, branch1.cond); } Branch branchn = new Branch(branch0.line, branch1.type, c, branch1.targetFirst, branch1.targetSecond); branchn.inverseValue = branch1.inverseValue; branchn.target = register; replace_branch(state, branch0, branch1, branchn); return combine_assignment(state, branchn); } else if(branch0.targetSecond == branch1.targetSecond) { /* Condition c = new AndCondition(branch0.cond, branch1.cond); Branch branchn = new Branch(branch0.line, Branch.Type.comparison, c, branch1.targetFirst, branch1.targetSecond); replace_branch(state, branch0, branch1, branchn); return branchn; */ } } if(is_assignment(branch0, register) && is_assignment(branch1) && branch0.inverseValue == branch1.inverseValue) { if(branch0.type == Branch.Type.test && branch0.inverseValue) { branch0.cond = branch0.cond.inverse(); // inverse has been double handled; undo it } if(branch0.targetSecond == branch1.targetSecond) { Condition c; //System.err.println("preassign " + branch1.line + " " + branch0.line + " " + branch0.targetSecond); boolean inverse = branch0.inverseValue; if(verbose) System.err.println("assign " + (inverse ? "or" : "and") + " " + branch1.line + " " + branch0.line); branch0 = combine_assignment(state, branch0); if(inverse != branch0.inverseValue) throw new IllegalStateException(); if(branch0.inverseValue) { //System.err.println("assign and " + branch1.line + " " + branch0.line); c = new OrCondition(branch0.cond, branch1.cond); } else { //System.err.println("assign or " + branch1.line + " " + branch0.line); c = new AndCondition(branch0.cond, branch1.cond); } Branch branchn = new Branch(branch0.line, branch1.type, c, branch1.targetFirst, branch1.targetSecond); branchn.inverseValue = branch1.inverseValue; branchn.target = register; replace_branch(state, branch0, branch1, branchn); return combine_assignment(state, branchn); } } if(is_assignment(branch0, register) && branch1.type == Branch.Type.finalset) { if(branch0.targetSecond == branch1.targetSecond) { if(branch0.type == Branch.Type.test && branch0.inverseValue) { branch0.cond = branch0.cond.inverse(); // inverse has been double handled; undo it } Condition c; //System.err.println("final preassign " + branch1.line + " " + branch0.line); boolean inverse = branch0.inverseValue; if(verbose) System.err.println("final assign " + (inverse ? "or" : "and") + " " + branch1.line + " " + branch0.line); branch0 = combine_assignment(state, branch0); if(inverse != branch0.inverseValue) throw new IllegalStateException(); if(branch0.inverseValue) { //System.err.println("final assign or " + branch1.line + " " + branch0.line); c = new OrCondition(branch0.cond, branch1.cond); } else { //System.err.println("final assign and " + branch1.line + " " + branch0.line); c = new AndCondition(branch0.cond, branch1.cond); } Branch branchn = new Branch(branch0.line, Branch.Type.finalset, c, branch1.targetFirst, branch1.targetSecond); branchn.target = register; replace_branch(state, branch0, branch1, branchn); return combine_assignment(state, branchn); } } } return branch1; } private static void replace_branch(State state, Branch branch0, Branch branch1, Branch branchn) { state.branches[branch0.line] = null; state.branches[branch1.line] = null; branchn.previous = branch0.previous; if(branchn.previous == null) { state.begin_branch = branchn; } else { branchn.previous.next = branchn; } branchn.next = branch1.next; if(branchn.next == null) { state.end_branch = branchn; } else { branchn.next.previous = branchn; } state.branches[branchn.line] = branchn; } private static void remove_branch(State state, Branch b) { state.branches[b.line] = null; Branch prev = b.previous; Branch next = b.next; if(prev != null) { prev.next = next; } else { state.begin_branch = next; } if(next != null) { next.previous = prev; } else { state.end_branch = next; } } private static void insert_branch(State state, Branch b) { state.branches[b.line] = b; } private static void link_branches(State state) { Branch previous = null; for(int index = 0; index < state.branches.length; index++) { Branch b = state.branches[index]; if(b != null) { b.previous = previous; if(previous != null) { previous.next = b; } else { state.begin_branch = b; } previous = b; } } state.end_branch = previous; } /** * Returns the target register of the instruction at the given * line or -1 if the instruction does not have a unique target. * * TODO: this probably needs a more careful pass */ private static int get_target(State state, int line) { Code code = state.code; switch(code.op(line)) { case MOVE: case LOADK: case LOADBOOL: case GETUPVAL: case GETTABUP: case GETGLOBAL: case GETTABLE: case NEWTABLE: case ADD: case SUB: case MUL: case DIV: case MOD: case POW: case UNM: case NOT: case LEN: case CONCAT: case CLOSURE: case TESTSET: return code.A(line); case LOADNIL: if(code.A(line) == code.B(line)) { return code.A(line); } else { return -1; } case SETGLOBAL: case SETUPVAL: case SETTABUP: case SETTABLE: case JMP: case TAILCALL: case RETURN: case FORLOOP: case FORPREP: case TFORCALL: case TFORLOOP: case CLOSE: return -1; case SELF: return -1; case EQ: case LT: case LE: case TEST: case SETLIST: return -1; case CALL: { int a = code.A(line); int c = code.C(line); if(c == 2) { return a; } else { return -1; } } case VARARG: { int a = code.A(line); int b = code.B(line); if(b == 1) { return a; } else { return -1; } } default: throw new IllegalStateException(); } } private static boolean is_statement(State state, int line) { if(state.reverse_targets[line]) return true; Registers r = state.r; int testRegister = -1; Code code = state.code; switch(code.op(line)) { case MOVE: case LOADK: case LOADBOOL: case GETUPVAL: case GETTABUP: case GETGLOBAL: case GETTABLE: case NEWTABLE: case ADD: case SUB: case MUL: case DIV: case MOD: case POW: case UNM: case NOT: case LEN: case CONCAT: case CLOSURE: return r.isLocal(code.A(line), line) || code.A(line) == testRegister; case LOADNIL: for(int register = code.A(line); register <= code.B(line); register++) { if(r.isLocal(register, line)) { return true; } } return false; case SETGLOBAL: case SETUPVAL: case SETTABUP: case SETTABLE: case JMP: case TAILCALL: case RETURN: case FORLOOP: case FORPREP: case TFORCALL: case TFORLOOP: case CLOSE: return true; case SELF: return r.isLocal(code.A(line), line) || r.isLocal(code.A(line) + 1, line); case EQ: case LT: case LE: case TEST: case TESTSET: case SETLIST: return false; case CALL: { int a = code.A(line); int c = code.C(line); if(c == 1) { return true; } if(c == 0) c = r.registers - a + 1; for(int register = a; register < a + c - 1; register++) { if(r.isLocal(register, line)) { return true; } } return (c == 2 && a == testRegister); } case VARARG: { int a = code.A(line); int b = code.B(line); if(b == 0) b = r.registers - a + 1; for(int register = a; register < a + b - 1; register++) { if(r.isLocal(register, line)) { return true; } } return false; } default: throw new IllegalStateException("Illegal opcode: " + code.op(line)); } } // static only private ControlFlowHandler() { } }
package com.oracle.graal.hotspot.test; import static com.oracle.graal.debug.internal.MemUseTrackerImpl.*; import static com.oracle.graal.hotspot.CompileTheWorld.*; import static com.oracle.graal.hotspot.CompileTheWorld.Options.*; import static com.oracle.graal.hotspot.HotSpotGraalRuntime.*; import static com.oracle.graal.nodes.StructuredGraph.*; import com.oracle.graal.api.runtime.*; import com.oracle.graal.compiler.test.*; import com.oracle.graal.debug.*; import com.oracle.graal.debug.internal.*; import com.oracle.graal.hotspot.*; import com.oracle.graal.hotspot.CompileTheWorld.Config; import com.oracle.graal.hotspot.meta.*; import com.oracle.graal.printer.*; /** * Used to benchmark memory usage during Graal compilation. * * To benchmark: * * <pre> * mx vm -XX:-UseGraalClassLoader -cp @com.oracle.graal.hotspot.test com.oracle.graal.hotspot.test.MemoryUsageBenchmark * </pre> * * Memory analysis for a {@link CompileTheWorld} execution can also be performed. For example: * * <pre> * mx --vm server vm -XX:-UseGraalClassLoader -G:CompileTheWorldClasspath=$HOME/SPECjvm2008/SPECjvm2008.jar -cp @com.oracle.graal.hotspot.test com.oracle.graal.hotspot.test.MemoryUsageBenchmark * </pre> */ public class MemoryUsageBenchmark extends GraalCompilerTest { public static int simple(int a, int b) { return a + b; } public static synchronized int complex(CharSequence cs) { if (cs instanceof String) { return cs.hashCode(); } if (cs instanceof StringBuffer) { int[] hash = {0}; cs.chars().forEach(c -> hash[0] += c); return hash[0]; } int res = 0; // Exercise lock elimination synchronized (cs) { res = cs.length(); } synchronized (cs) { res = cs.hashCode() ^ 31; } for (int i = 0; i < cs.length(); i++) { res *= cs.charAt(i); } // A fixed length loop with some canonicalizable arithmetics will // activate loop unrolling and more canonicalization int sum = 0; for (int i = 0; i < 5; i++) { sum += i * 2; } res += sum; // Activates escape-analysis res += new String("asdf").length(); return res; } static class MemoryUsageCloseable implements AutoCloseable { private final long start; private final String name; public MemoryUsageCloseable(String name) { this.name = name; this.start = getCurrentThreadAllocatedBytes(); } @Override public void close() { long end = getCurrentThreadAllocatedBytes(); long allocated = end - start; System.out.println(name + ": " + allocated); } } public static void main(String[] args) { // Ensure a Graal runtime is initialized prior to Debug being initialized as the former // may include processing command line options used by the latter. Graal.getRuntime(); // Ensure a debug configuration for this thread is initialized if (Debug.isEnabled() && DebugScope.getConfig() == null) { DebugEnvironment.initialize(System.out); } new MemoryUsageBenchmark().run(); } private void doCompilation(String methodName, String label) { HotSpotResolvedJavaMethod method = (HotSpotResolvedJavaMethod) getMetaAccess().lookupJavaMethod(getMethod(methodName)); HotSpotBackend backend = runtime().getHostBackend(); // invalidate any existing compiled code method.reprofile(); int id = method.allocateCompileId(INVOCATION_ENTRY_BCI); long ctask = 0L; try (MemoryUsageCloseable c = label == null ? null : new MemoryUsageCloseable(label)) { CompilationTask task = new CompilationTask(backend, method, INVOCATION_ENTRY_BCI, ctask, id); task.runCompilation(); } } private void allocSpyCompilation(String methodName) { if (AllocSpy.isEnabled()) { HotSpotResolvedJavaMethod method = (HotSpotResolvedJavaMethod) getMetaAccess().lookupJavaMethod(getMethod(methodName)); HotSpotBackend backend = runtime().getHostBackend(); // invalidate any existing compiled code method.reprofile(); int id = method.allocateCompileId(INVOCATION_ENTRY_BCI); long ctask = 0L; try (AllocSpy as = AllocSpy.open(methodName)) { CompilationTask task = new CompilationTask(backend, method, INVOCATION_ENTRY_BCI, ctask, id); task.runCompilation(); } } } private static final boolean verbose = Boolean.getBoolean("verbose"); private void compileAndTime(String methodName) { // Parse in eager mode to resolve methods/fields/classes parseEager(methodName); // Warm up and initialize compiler phases used by this compilation for (int i = 0; i < 10; i++) { doCompilation(methodName, verbose ? methodName + "[warmup-" + i + "]" : null); } doCompilation(methodName, methodName); } public void run() { compileAndTime("simple"); compileAndTime("complex"); if (CompileTheWorldClasspath.getValue() != SUN_BOOT_CLASS_PATH) { CompileTheWorld ctw = new CompileTheWorld(CompileTheWorldClasspath.getValue(), new Config(CompileTheWorldConfig.getValue()), CompileTheWorldStartAt.getValue(), CompileTheWorldStopAt.getValue(), CompileTheWorldVerbose.getValue()); try { ctw.compile(); } catch (Throwable e) { e.printStackTrace(); } } allocSpyCompilation("simple"); allocSpyCompilation("complex"); } }
package org.jdesktop.swingx.action; import java.awt.event.ActionEvent; import java.awt.event.ItemEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.Serializable; import java.lang.ref.ReferenceQueue; import java.lang.ref.WeakReference; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JCheckBoxMenuItem; import javax.swing.JMenuItem; import javax.swing.JRadioButton; import javax.swing.JToggleButton; import org.jdesktop.test.PropertyChangeReport; import org.jdesktop.test.SerializableSupport; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @RunWith(JUnit4.class) public class ActionIssues extends ActionTest implements Serializable { /** * Issue #1364-swingx: AbstractActionExt - incorrect parameter type in setActionCommand */ @Test public void testActionCommand() { AbstractActionExt action = new AbstractActionExt("something"){ @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub }}; action.setActionCommand(new Object()); new JButton(action); } /** * core issue: * set selected via putValue leads to inconsistent state. * */ @Test public void testFireSelected() { AbstractActionExt action = new AbstractActionExt("dummy") { public void actionPerformed(ActionEvent e) { // nothing to do } @Override public void itemStateChanged(ItemEvent e) { // nothing to do } }; PropertyChangeListener l = new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { if ("selected".equals(evt.getPropertyName())) { assertEquals(evt.getNewValue(), ((AbstractActionExt) evt.getSource()).isSelected()); } } }; action.addPropertyChangeListener(l); action.putValue("selected", true); } /** * unexpected core behaviour: selected is not a bound property! * PENDING: is it in Mustang? */ @Test public void testToggleButtonPropertyChangeSelected() { JToggleButton button = new JToggleButton(); PropertyChangeReport report = new PropertyChangeReport(); button.addPropertyChangeListener(report); boolean selected = button.isSelected(); button.setSelected(!selected); // sanity... assertEquals(selected, !button.isSelected()); assertEquals("must have one event for selected", 1, report.getEventCount("selected")); } @Test public void testCheckBoxPropertyChangeSelected() { JCheckBox button = new JCheckBox(); PropertyChangeReport report = new PropertyChangeReport(); button.addPropertyChangeListener(report); boolean selected = button.isSelected(); button.setSelected(!selected); // sanity... assertEquals(selected, !button.isSelected()); assertEquals("must have one event for selected", 1, report.getEventCount("selected")); } @Test public void testRadioButtonPropertyChangeSelected() { JRadioButton button = new JRadioButton(); PropertyChangeReport report = new PropertyChangeReport(); button.addPropertyChangeListener(report); boolean selected = button.isSelected(); button.setSelected(!selected); // sanity... assertEquals(selected, !button.isSelected()); assertEquals("must have one event for selected", 1, report.getEventCount("selected")); } @Test public void testCheckBoxMenuItemPropertyChangeSelected() { JMenuItem button = new JCheckBoxMenuItem(); PropertyChangeReport report = new PropertyChangeReport(); button.addPropertyChangeListener(report); boolean selected = button.isSelected(); button.setSelected(!selected); // sanity... assertEquals(selected, !button.isSelected()); assertEquals("must have one event for selected", 1, report.getEventCount("selected")); } /** * Template to try and test memory leaks (from Palantir blog). * TODO apply for listener problems */ @Test public void testMemory() { //create test object Object testObject = new Object(); // create queue and weak reference ReferenceQueue<Object> queue = new ReferenceQueue<Object>(); WeakReference<Object> ref = new WeakReference<Object>(testObject, queue); // set hard reference to null testObject = null; // force garbage collection System.gc(); // soft reference should now be enqueued (no leak) assertTrue(ref.isEnqueued()); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.evolveum.midpoint.schema.processor; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertTrue; import static org.testng.AssertJUnit.assertEquals; import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; import org.testng.annotations.BeforeMethod; import org.testng.AssertJUnit; import com.evolveum.midpoint.schema.exception.SchemaException; import com.evolveum.midpoint.schema.processor.Property; import com.evolveum.midpoint.schema.processor.PropertyContainer; import com.evolveum.midpoint.schema.processor.PropertyContainerDefinition; import com.evolveum.midpoint.schema.processor.PropertyDefinition; import com.evolveum.midpoint.schema.processor.Schema; import com.evolveum.midpoint.schema.util.JAXBUtil; import com.evolveum.midpoint.util.DOMUtil; import java.util.List; import java.util.Set; import javax.xml.bind.JAXBException; import javax.xml.namespace.QName; import org.w3c.dom.Document; import org.w3c.dom.Element; /** * * @author semancik */ public class SchemaProcessorBasicTest { private static final String SCHEMA1_FILENAME = "src/test/resources/processor/schema1.xsd"; private static final String OBJECT1_FILENAME = "src/test/resources/processor/object1.xml"; private static final String SCHEMA2_FILENAME = "src/test/resources/processor/schema2.xsd"; private static final String OBJECT2_FILENAME = "src/test/resources/processor/object2.xml"; private static final String SCHEMA_NAMESPACE = "http://schema.foo.com/bar"; public SchemaProcessorBasicTest() { } @BeforeMethod public void setUp() { } @AfterMethod public void tearDown() { } @Test public void parseSchemaTest() throws SchemaException { System.out.println("===[ parseSchemaTest ]==="); // GIVEN Document schemaDom = DOMUtil.parseFile(SCHEMA1_FILENAME); // WHEN Schema schema = Schema.parse(DOMUtil.getFirstChildElement(schemaDom)); // THEN assertNotNull(schema); System.out.println("Parsed schema from "+SCHEMA1_FILENAME+":"); System.out.println(schema.dump()); PropertyContainerDefinition accDef = schema.findContainerDefinitionByType(new QName(SCHEMA_NAMESPACE,"AccountObjectClass")); assertEquals(new QName(SCHEMA_NAMESPACE,"AccountObjectClass"), accDef.getTypeName()); assertTrue("Expected ResourceObjectDefinition but got "+accDef.getClass().getName(), accDef instanceof ResourceObjectDefinition); assertTrue("Not a default account",((ResourceObjectDefinition)accDef).isDefaultAccountType()); PropertyDefinition loginDef = accDef.findPropertyDefinition(new QName(SCHEMA_NAMESPACE,"login")); assertEquals(new QName(SCHEMA_NAMESPACE,"login"), loginDef.getName()); } @Test public void instantiationTest() throws SchemaException, JAXBException { System.out.println("===[ instantiationTest ]==="); // GIVEN Document schemaDom = DOMUtil.parseFile(SCHEMA1_FILENAME); Schema schema = Schema.parse(DOMUtil.getFirstChildElement(schemaDom)); assertNotNull(schema); System.out.println("Parsed schema:"); System.out.println(schema.dump()); PropertyContainerDefinition accDef = schema.findContainerDefinitionByType(new QName(SCHEMA_NAMESPACE,"AccountObjectClass")); assertEquals(new QName(SCHEMA_NAMESPACE,"AccountObjectClass"), accDef.getTypeName()); PropertyDefinition loginDef = accDef.findPropertyDefinition(new QName(SCHEMA_NAMESPACE,"login")); assertEquals(new QName(SCHEMA_NAMESPACE,"login"), loginDef.getName()); // WHEN // Instantiate PropertyContainer (XSD type) PropertyContainer accInst = accDef.instantiate(new QName(SCHEMA_NAMESPACE,"first")); assertNotNull(accInst); assertNotNull(accInst.getDefinition()); // as the definition is ResourceObjectDefinition, the instance should be of ResoureceObject type assertTrue(accInst instanceof ResourceObject); // Instantiate Property (XSD element) Property loginInst = loginDef.instantiate(); assertNotNull(loginInst); assertNotNull(loginInst.getDefinition()); assertTrue(loginInst instanceof ResourceObjectAttribute); // Set some value loginInst.setValue("FOOBAR"); accInst.getItems().add(loginInst); // Same thing with the prop2 property (type int) PropertyDefinition groupDef = accDef.findPropertyDefinition(new QName(SCHEMA_NAMESPACE,"group")); Property groupInst = groupDef.instantiate(); groupInst.setValue(321); accInst.getItems().add(groupInst); System.out.println("AccountObjectClass INST: "+accInst); // Serialize to DOM Document doc = DOMUtil.getDocument(); accInst.serializeToDom(doc); // TODO: Serialize to XML and check System.out.println("Serialized: "); System.out.println(DOMUtil.serializeDOMToString(doc)); } @Test public void valueParseTest() throws SchemaException, SchemaException { System.out.println("===[ valueParseTest ]==="); // GIVEN Document schemaDom = DOMUtil.parseFile(SCHEMA1_FILENAME); Schema schema = Schema.parse(DOMUtil.getFirstChildElement(schemaDom)); AssertJUnit.assertNotNull(schema); PropertyContainerDefinition type1Def = schema.findContainerDefinitionByType(new QName(SCHEMA_NAMESPACE,"AccountObjectClass")); AssertJUnit.assertEquals(new QName(SCHEMA_NAMESPACE,"AccountObjectClass"), type1Def.getTypeName()); PropertyDefinition prop1Def = type1Def.findPropertyDefinition(new QName(SCHEMA_NAMESPACE,"login")); AssertJUnit.assertEquals(new QName(SCHEMA_NAMESPACE,"login"), prop1Def.getName()); // WHEN Document dataDom = DOMUtil.parseFile(OBJECT1_FILENAME); PropertyContainer container = type1Def.parseItem(DOMUtil.getFirstChildElement(dataDom)); // THEN System.out.println("container: "+container); assertEquals(2,container.getItems().size()); for (Item item : container.getItems()) { ResourceObjectAttribute prop = (ResourceObjectAttribute)item; if (prop.getName().getLocalPart().equals("login")) { AssertJUnit.assertEquals("barbar", prop.getValue(String.class)); } if (prop.getName().getLocalPart().equals("group")) { int val = prop.getValue(int.class); AssertJUnit.assertEquals(123456, val); } } } /** * Take prepared XSD schema, parse it and use it to parse property container instance. */ @Test public void testParsePropertyContainer() throws SchemaException, SchemaException { System.out.println("===[ testParsePropertyContainer ]==="); // GIVEN Document schemaDom = DOMUtil.parseFile(SCHEMA2_FILENAME); Schema schema = Schema.parse(DOMUtil.getFirstChildElement(schemaDom)); assertNotNull(schema); System.out.println(SchemaProcessorBasicTest.class.getSimpleName()+".testParsePropertyContainer parsed schema: "); System.out.println(schema.dump()); PropertyContainerDefinition type1Def = schema.findContainerDefinitionByType(new QName(SCHEMA_NAMESPACE,"PropertyContainerType")); assertEquals(new QName(SCHEMA_NAMESPACE,"PropertyContainerType"), type1Def.getTypeName()); PropertyDefinition prop1Def = type1Def.findPropertyDefinition(new QName(SCHEMA_NAMESPACE,"prop1")); assertEquals(new QName(SCHEMA_NAMESPACE,"prop1"), prop1Def.getName()); // WHEN Document dataDom = DOMUtil.parseFile(OBJECT2_FILENAME); PropertyContainer propertyContainer = schema.parsePropertyContainer(DOMUtil.getFirstChildElement(dataDom)); // THEN assertNotNull(propertyContainer); System.out.println(SchemaProcessorBasicTest.class.getSimpleName()+".testParsePropertyContainer parsed container: "); System.out.println(propertyContainer.dump()); assertEquals(new QName(SCHEMA_NAMESPACE,"propertyContainer"),propertyContainer.getName()); assertEquals(new QName(SCHEMA_NAMESPACE,"propertyContainer"),propertyContainer.getDefinition().getName()); assertEquals(new QName(SCHEMA_NAMESPACE,"PropertyContainerType"),propertyContainer.getDefinition().getTypeName()); } }
package org.bouncycastle.jce.provider.test; import java.io.ByteArrayInputStream; import java.security.Security; import java.security.cert.CertStore; import java.security.cert.CertificateFactory; import java.security.cert.X509CRLSelector; import java.security.cert.X509CertSelector; import java.security.cert.X509Certificate; import java.util.Collection; import java.util.Iterator; import org.bouncycastle.jce.X509LDAPCertStoreParameters; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.util.encoders.Base64; import org.bouncycastle.util.test.SimpleTest; public class X509LDAPCertStoreTest extends SimpleTest { private byte cert1[] = Base64 .decode("MIIDyTCCAzKgAwIBAgIEL64+8zANBgkqhkiG9w0BAQUFADBVMQswCQYDVQQGEwJE" + "RTEcMBoGA1UEChQTRGV1dHNjaGUgVGVsZWtvbSBBRzEoMAwGBwKCBgEKBxQTATEw" + "GAYDVQQDFBFUVEMgVGVzdCBDQSAxMTpQTjAeFw0wMzAzMjUxNDM1MzFaFw0wNjAz" + "MjUxNDM1MzFaMGIxCzAJBgNVBAYTAkRFMRswGQYDVQQKDBJHRlQgU29sdXRpb25z" + "IEdtYkgxEjAQBgNVBAsMCUhZUEFSQ0hJVjEWMBQGA1UEAwwNRGllZ2UsIFNpbW9u" + "ZTEKMAgGA1UEBRMBMTCBoDANBgkqhkiG9w0BAQEFAAOBjgAwgYoCgYEAiEYsFbs4" + "FesQpMjBkzJB92c0p8tJ02nbCNA5l17VVbbrv6/twnQHW4kgA+9lZlXfzI8iunT1" + "KuiwVupWObHgFaGPkelIN/qIbuwbQzh7T+IUKdKETE12Lc+xk9YvQ6mJVgosmwpr" + "nMMjezymh8DjPhe7MC7/H3AotrHVNM3mEJcCBEAAAIGjggGWMIIBkjAfBgNVHSME" + "GDAWgBTQc8wTeltcAM3iTE63fk/wTA+IJTAdBgNVHQ4EFgQUq6ChBvXPiqhMHLS3" + "kiKpSeGWDz4wDgYDVR0PAQH/BAQDAgQwMB8GA1UdEQQYMBaBFHNpbW9uZS5kaWVn" + "ZUBnZnQuY29tMIHoBgNVHR8EgeAwgd0wgdqgaqBohjVsZGFwOi8vcGtzbGRhcC50" + "dHRjLmRlOjM4OS9jPWRlLG89RGV1dHNjaGUgVGVsZWtvbSBBR4YvaHR0cDovL3d3" + "dy50dHRjLmRlL3RlbGVzZWMvc2VydmxldC9kb3dubG9hZF9jcmyibKRqMGgxCzAJ" + "BgNVBAYTAkRFMRwwGgYDVQQKFBNEZXV0c2NoZSBUZWxla29tIEFHMTswDAYHAoIG" + "AQoHFBMBMTArBgNVBAMUJFRlbGVTZWMgRGlyZWN0b3J5IFNlcnZpY2UgU2lnRyAx" + "MDpQTjA0BggrBgEFBQcBAQQoMCYwJAYIKwYBBQUHMAGGGGh0dHA6Ly93d3cudHR0" + "Yy5kZS9vY3NwcjANBgkqhkiG9w0BAQUFAAOBgQBCPudAtrP9Bx7GRhHQgYS6kaoN" + "vYb/yDss86pyn0uiFuwT+mT1popcAfxPo2yxL0jqqlsDNFBC2hJob5rjihsKPmqV" + "rSaW0VJu/zBihsX7hLKOVMf5gvUYMS5ulq/bp8jOj8a+5SmxVY+WWZVFghWjISse" + "T3WABdTS9S3zjnQiyg=="); byte[] directCRL = Base64 .decode("MIIGXTCCBckCAQEwCgYGKyQDAwECBQAwdDELMAkGA1UEBhMCREUxHDAaBgNVBAoU" + "E0RldXRzY2hlIFRlbGVrb20gQUcxFzAVBgNVBAsUDlQtVGVsZVNlYyBUZXN0MS4w" + "DAYHAoIGAQoHFBMBMTAeBgNVBAMUF1QtVGVsZVNlYyBUZXN0IERJUiA4OlBOFw0w" + "NjA4MDQwODQ1MTRaFw0wNjA4MDQxNDQ1MTRaMIIElTAVAgQvrj/pFw0wMzA3MjIw" + "NTQxMjhaMBUCBC+uP+oXDTAzMDcyMjA1NDEyOFowFQIEL64/5xcNMDQwNDA1MTMx" + "ODE3WjAVAgQvrj/oFw0wNDA0MDUxMzE4MTdaMBUCBC+uP+UXDTAzMDExMzExMTgx" + "MVowFQIEL64/5hcNMDMwMTEzMTExODExWjAVAgQvrj/jFw0wMzAxMTMxMTI2NTZa" + "MBUCBC+uP+QXDTAzMDExMzExMjY1NlowFQIEL64/4hcNMDQwNzEzMDc1ODM4WjAV" + "AgQvrj/eFw0wMzAyMTcwNjMzMjVaMBUCBC+uP98XDTAzMDIxNzA2MzMyNVowFQIE" + "L64/0xcNMDMwMjE3MDYzMzI1WjAVAgQvrj/dFw0wMzAxMTMxMTI4MTRaMBUCBC+u" + "P9cXDTAzMDExMzExMjcwN1owFQIEL64/2BcNMDMwMTEzMTEyNzA3WjAVAgQvrj/V" + "Fw0wMzA0MzAxMjI3NTNaMBUCBC+uP9YXDTAzMDQzMDEyMjc1M1owFQIEL64/xhcN" + "MDMwMjEyMTM0NTQwWjAVAgQvrj/FFw0wMzAyMTIxMzQ1NDBaMBUCBC+uP8IXDTAz" + "MDIxMjEzMDkxNlowFQIEL64/wRcNMDMwMjEyMTMwODQwWjAVAgQvrj++Fw0wMzAy" + "MTcwNjM3MjVaMBUCBC+uP70XDTAzMDIxNzA2MzcyNVowFQIEL64/sBcNMDMwMjEy" + "MTMwODU5WjAVAgQvrj+vFw0wMzAyMTcwNjM3MjVaMBUCBC+uP5MXDTAzMDQxMDA1" + "MjYyOFowFQIEL64/khcNMDMwNDEwMDUyNjI4WjAVAgQvrj8/Fw0wMzAyMjYxMTA0" + "NDRaMBUCBC+uPz4XDTAzMDIyNjExMDQ0NFowFQIEL64+zRcNMDMwNTIwMDUyNzM2" + "WjAVAgQvrj7MFw0wMzA1MjAwNTI3MzZaMBUCBC+uPjwXDTAzMDYxNzEwMzQxNlow" + "FQIEL64+OxcNMDMwNjE3MTAzNDE2WjAVAgQvrj46Fw0wMzA2MTcxMDM0MTZaMBUC" + "BC+uPjkXDTAzMDYxNzEzMDEwMFowFQIEL64+OBcNMDMwNjE3MTMwMTAwWjAVAgQv" + "rj43Fw0wMzA2MTcxMzAxMDBaMBUCBC+uPjYXDTAzMDYxNzEzMDEwMFowFQIEL64+" + "MxcNMDMwNjE3MTAzNzQ5WjAVAgQvrj4xFw0wMzA2MTcxMDQyNThaMBUCBC+uPjAX" + "DTAzMDYxNzEwNDI1OFowFQIEL649qRcNMDMxMDIyMTEzMjI0WjAVAgQvrjyyFw0w" + "NTAzMTEwNjQ0MjRaMBUCBC+uPKsXDTA0MDQwMjA3NTQ1M1owFQIEL6466BcNMDUw" + "MTI3MTIwMzI0WjAVAgQvrjq+Fw0wNTAyMTYwNzU3MTZaMBUCBC+uOqcXDTA1MDMx" + "MDA1NTkzNVowFQIEL646PBcNMDUwNTExMTA0OTQ2WjAVAgQvrG3VFw0wNTExMTEx" + "MDAzMjFaMBUCBC+uLmgXDTA2MDEyMzEwMjU1NVowFQIEL64mxxcNMDYwODAxMDk0" + "ODQ0WqCBijCBhzALBgNVHRQEBAICEQwwHwYDVR0jBBgwFoAUA1vI26YMj3njkfCU" + "IXbo244kLjkwVwYDVR0SBFAwToZMbGRhcDovL3Brc2xkYXAudHR0Yy5kZS9vdT1U" + "LVRlbGVTZWMgVGVzdCBESVIgODpQTixvPURldXRzY2hlIFRlbGVrb20gQUcsYz1k" + "ZTAKBgYrJAMDAQIFAAOBgQArj4eMlbAwuA2aS5O4UUUHQMKKdK/dtZi60+LJMiMY" + "ojrMIf4+ZCkgm1Ca0Cd5T15MJxVHhh167Ehn/Hd48pdnAP6Dfz/6LeqkIHGWMHR+" + "z6TXpwWB+P4BdUec1ztz04LypsznrHcLRa91ixg9TZCb1MrOG+InNhleRs1ImXk8" + "MQ=="); private static String ldapURL1 = "ldap://pksldap.tttc.de:389"; private static X509LDAPCertStoreParameters params1 = new X509LDAPCertStoreParameters( ldapURL1, null, "cn", "cn", "cn", "cn", "cn", "cn", "cn", "o", "cn"); private static String ldapURL2 = "ldap://directory.d-trust.de:389"; private static X509LDAPCertStoreParameters params2 = new X509LDAPCertStoreParameters( ldapURL2, null, "cn", "cn", "cn", "cn", "cn", "cn", "cn", "o", "uid"); private byte[] cert2 = Base64 .decode("MIIEADCCAuigAwIBAgIDAJ/QMA0GCSqGSIb3DQEBBQUAMD8xCzAJBgNVBAYTAkRF" + "MRUwEwYDVQQKDAxELVRydXN0IEdtYkgxGTAXBgNVBAMMEEQtVFJVU1QgRGVtbyBD" + "QTEwHhcNMDYwMzAyMTYxNTU3WhcNMDgwMzEyMTYxNTU3WjB+MQswCQYDVQQGEwJE" + "RTEUMBIGA1UECgwLTXVzdGVyIEdtYkgxFzAVBgNVBAMMDk1heCBNdXN0ZXJtYW5u" + "MRMwEQYDVQQEDApNdXN0ZXJtYW5uMQwwCgYDVQQqDANNYXgxHTAbBgNVBAUTFERU" + "UldFMTQxMjk5NDU1MTgwMTIxMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKC" + "AQEAjLDFeviSZDEZgLzTdptU4biPgNV7SvLqsNholfqkyQm2r5WSghGZSjhKYIne" + "qKmZ08W59a51bGqDEsifYR7Tw9JC/AhH19fyK01+1ZAXHalgVthaRtLw31lcoTVJ" + "R7j9fvrnW0sMPVP4m5gePb3P5/pYHVmN1MjdPIm38us5aJOytOO5Li2IwQIG0t4M" + "bEC6/1horBR5TgRl7ACamrdaPHOvO1QVweOqYU7uVxLgDTK4mSV6heyrisFMfkbj" + "7jT/c44kXM7dtgNcmESINudu6bnqaB1CxOFTJ/Jzv81R5lf7pBX2LOG1Bu94Yw2x" + "cHUVROs2UWY8kQrNUozsBHzQ0QIDAKq5o4HFMIHCMBMGA1UdIwQMMAqACEITKrPL" + "WuYiMDMGCCsGAQUFBwEBBCcwJTAjBggrBgEFBQcwAYYXaHR0cDovL29jc3AuZC10" + "cnVzdC5uZXQwEAYDVR0gBAkwBzAFBgMqAwQwEQYDVR0OBAoECEvE8bXFHkFLMA4G" + "A1UdDwEB/wQEAwIGQDAPBgUrJAgDCAQGDARUZXN0MB8GA1UdEQQYMBaBFG0ubXVz" + "dGVybWFubkB0ZXN0LmRlMA8GBSskCAMPBAYMBFRlc3QwDQYJKoZIhvcNAQEFBQAD" + "ggEBADD/X+UZZN30nCBDzJ7MtmgwvMBVDAU6HkPlzfyn9pxIKFrq3uR9wcY2pedM" + "yQQk0NpTDCIhAYIjAHysMue0ViQnW5qq8uUCFn0+fsgMqqTQNRmE4NIqUrnYO40g" + "WjcepCEApkTqGf3RFaDMf9zpRvj9qUx18De+V0GC22uD2vPKpqRcvS2dSw6pHBW2" + "NwEU+RgNhoPXrHt332PEYdwO0zOL7eSLBD9AmkpP2uDjpMQ02Lu9kXG6OOfanwfS" + "jHioCvDXyl5pwSHwrHNWQRb5dLF12Fg41LMapDwR7awAKE9h6qHBonvCMBPMvqrr" + "NktqQcoQkluR9MItONJI5XHADtU="); private static String ldapURL3 = "ldap://dir.signtrust.de:389"; private static X509LDAPCertStoreParameters params3 = new X509LDAPCertStoreParameters( ldapURL3, "c=de", "cn", "cn", "ou", "ou", "o", "cn", "cn", "ou", "serialNumber"); private byte[] cert3 = Base64 .decode("MIICwDCCAimgAwIBAgIBKzANBgkqhkiG9w0BAQUFADA6MRAwDgYDVQQDEwdQQ0Ex" + "OlBOMRkwFwYDVQQKExBEZXV0c2NoZSBQb3N0IEFHMQswCQYDVQQGEwJERTAeFw0w" + "MDA0MTkyMjAwMDBaFw0wMzA0MTkyMjAwMDBaMIGOMRAwDgYDVQQEFAdN5G5jaGVy" + "MQ4wDAYDVQQqEwVLbGF1czEWMBQGA1UEAxQNS2xhdXMgTeRuY2hlcjEVMBMGA1UE" + "CRMMV2llc2Vuc3RyLiAzMQ4wDAYDVQQREwU2MzMyOTESMBAGA1UEBxMJRWdlbHNi" + "YWNoMQswCQYDVQQGEwJERTEKMAgGA1UEBRMBMTCBnzANBgkqhkiG9w0BAQEFAAOB" + "jQAwgYkCgYEAn7z6Ba9wpv/mNBIaricY/d0KpxGpqGAXdqKlvqkk/seJEoBLvmL7" + "wZz88RPELQqzDhc4oXYohS2dh3NHus9FpSPMq0JzKAcE3ArrVDxwtXtlcwN2v7iS" + "TcHurgLOb9C/r8JdsMHNgwHMkkdp96cJk/sioyP5sLPYmgWxg1JH0vMCAwEAAaOB" + "gDB+MAwGA1UdEwEB/wQCMAAwDwYDVR0PAQH/BAUDAwfAADBKBgNVHSMEQzBBoTyk" + "OjEQMA4GA1UEAxMHUENBMTpQTjEZMBcGA1UEChMQRGV1dHNjaGUgUG9zdCBBRzEL" + "MAkGA1UEBhMCREWCAQEwEQYDVR0OBAoECEAeJ6R3USjxMA0GCSqGSIb3DQEBBQUA" + "A4GBADMRtdiQJF2fg7IcedTjnAW+QGl/wNSKy7A4oaBQeahcruo+hzH+ZU+DsiSu" + "TJZaf2X1eUUEPmV+5zZlopGa3HvFfgmIYIXBw9ZO3Qb/HWGsPNgW0yg5eXEGwNEt" + "vV85BTMGuMjiuDw841IuAZaMKqOKnVXHmd2pLJz7Wv0MLJhw"); private byte[] caCert3 = Base64 .decode("MIICUjCCAb6gAwIBAgIDD2ptMAoGBiskAwMBAgUAMG8xCzAJBgNVBAYTAkRFMT0w" + "OwYDVQQKFDRSZWd1bGllcnVuZ3NiZWjIb3JkZSBmyHVyIFRlbGVrb21tdW5pa2F0" + "aW9uIHVuZCBQb3N0MSEwDAYHAoIGAQoHFBMBMTARBgNVBAMUCjRSLUNBIDE6UE4w" + "IhgPMjAwMDA0MTIwODIyMDNaGA8yMDA0MDQxMjA4MjIwM1owWzELMAkGA1UEBhMC" + "REUxGTAXBgNVBAoUEERldXRzY2hlIFBvc3QgQUcxMTAMBgcCggYBCgcUEwExMCEG" + "A1UEAxQaQ0EgREVSIERFVVRTQ0hFTiBQT1NUIDU6UE4wgZ8wDQYJKoZIhvcNAQEB" + "BQADgY0AMIGJAoGBAIH3c+gig1KkY5ceR6n/AMq+xz7hi3f0PMdpwIe2v2w6Hu5k" + "jipe++NvU3r6wakIY2royHl3gKWrExOisBico9aQmn8lMJnWZ7SUbB+WpRn0mAWN" + "ZM9YT+/U5hRCffeeuLWClzrbScaWnAeaaI0G+N/QKnSSjrV/l64jogyADWCTAgMB" + "AAGjEjAQMA4GA1UdDwEB/wQEAwIBBjAKBgYrJAMDAQIFAAOBgQAaV5WClEneXk9s" + "LO8zTQAsf4KvDaLd1BFcFeYM7kLLRHKeWQ0MAd0xkuAMme5NVwWNpNZP74B4HX7Q" + "/Q0h/wo/9LTgQaxw52lLs4Ml0HUyJbSFjoQ+sqgjg2fGNGw7aGkVNY5dQTAy8oSv" + "iG8mxTsQ7Fxaush3cIB0qDDwXar/hg=="); private byte[] crossCert3 = Base64 .decode("MIICVDCCAcCgAwIBAgIDDIOsMAoGBiskAwMBAgUAMG8xCzAJBgNVBAYTAkRFMT0w" + "OwYDVQQKFDRSZWd1bGllcnVuZ3NiZWjIb3JkZSBmyHVyIFRlbGVrb21tdW5pa2F0" + "aW9uIHVuZCBQb3N0MSEwDAYHAoIGAQoHFBMBMTARBgNVBAMUCjRSLUNBIDE6UE4w" + "IhgPMjAwMDAzMjIwOTQzNTBaGA8yMDA0MDEyMTE2MDQ1M1owbzELMAkGA1UEBhMC" + "REUxPTA7BgNVBAoUNFJlZ3VsaWVydW5nc2JlaMhvcmRlIGbIdXIgVGVsZWtvbW11" + "bmlrYXRpb24gdW5kIFBvc3QxITAMBgcCggYBCgcUEwExMBEGA1UEAxQKNVItQ0Eg" + "MTpQTjCBoTANBgkqhkiG9w0BAQEFAAOBjwAwgYsCgYEAih5BUycfBpqKhU8RDsaS" + "vV5AtzWeXQRColL9CH3t0DKnhjKAlJ8iccFtJNv+d3bh8bb9sh0maRSo647xP7hs" + "HTjKgTE4zM5BYNfXvST79OtcMgAzrnDiGjQIIWv8xbfV1MqxxdtZJygrwzRMb9jG" + "CAGoJEymoyzAMNG7tSdBWnUCBQDAAAABMAoGBiskAwMBAgUAA4GBAIBWrl6aEy4d" + "2d6U/924YK8Tv9oChmaKVhklkiTzcKv1N8dhLnLTibq4/stop03CY3rKU4X5aTfu" + "0J77FIV1Poy9jLT5Tm1NBpi71m4uO3AUoSeyhJXGQGsYFjAc3URqkznbTL/nr9re" + "IoBhf6u9cX+idnN6Uy1q+j/LOrcy3zgj"); public void performTest() throws Exception { CertStore cs = CertStore.getInstance("X509LDAP", params1, "BC"); X509CertSelector sl = new X509CertSelector(); CertificateFactory cf = CertificateFactory.getInstance("X.509", "BC"); X509Certificate xcert = (X509Certificate)cf .generateCertificate(new ByteArrayInputStream(cert1)); sl.setCertificate(xcert); Collection coll = cs.getCertificates(sl); if (coll.isEmpty() || !coll.iterator().next().equals(xcert)) { fail("certificate could not be picked from LDAP directory."); } // System.out.println(coll.toArray()[0]); sl.setCertificate(null); sl.setSubject(xcert.getSubjectX500Principal().getEncoded()); coll = cs.getCertificates(sl); if (coll.isEmpty() || !coll.iterator().next().equals(xcert)) { fail("certificate could not be picked from LDAP directory."); } X509CRLSelector sl2 = new X509CRLSelector(); // X509CRL crl = (X509CRL)cf.generateCRL(new // ByteArrayInputStream(directCRL)); // sl2.addIssuer(crl.getIssuerX500Principal()); coll = cs.getCRLs(sl2); if (!coll.iterator().hasNext()) { fail("CRL could not be picked from LDAP directory."); } // //System.out.println(coll.toArray()[0]); cs = CertStore.getInstance("X509LDAP", params2, "BC"); sl = new X509CertSelector(); xcert = (X509Certificate)cf .generateCertificate(new ByteArrayInputStream(cert2)); sl.setCertificate(xcert); coll = cs.getCertificates(sl); if (coll.isEmpty() || !coll.iterator().next().equals(xcert)) { fail("certificate could not be picked from LDAP directory."); } // System.out.println(coll.toArray()[0]); cs = CertStore.getInstance("X509LDAP", params3, "BC"); sl = new X509CertSelector(); xcert = (X509Certificate)cf .generateCertificate(new ByteArrayInputStream(cert3)); sl.setCertificate(xcert); coll = cs.getCertificates(sl); if (coll.isEmpty() || !coll.iterator().next().equals(xcert)) { fail("certificate could not be picked from LDAP directory."); } // System.out.println(coll.toArray()[0]); xcert = (X509Certificate)cf .generateCertificate(new ByteArrayInputStream(caCert3)); sl = new X509CertSelector(); sl.setSubject(xcert.getSubjectX500Principal().getEncoded()); coll = cs.getCertificates(sl); boolean found = false; if (coll.isEmpty()) { fail("certificate could not be picked from LDAP directory."); } for (Iterator it = coll.iterator(); it.hasNext();) { if (it.next().equals(xcert)) { found = true; break; } } if (!found) { fail("certificate could not be picked from LDAP directory."); } // System.out.println(coll.toArray()[0]); sl = new X509CertSelector(); xcert = (X509Certificate)cf .generateCertificate(new ByteArrayInputStream(crossCert3)); sl = new X509CertSelector(); sl.setSubject(xcert.getSubjectX500Principal().getEncoded()); coll = cs.getCertificates(sl); if (coll.isEmpty()) { fail("certificate could not be picked from LDAP directory."); } found = false; for (Iterator it = coll.iterator(); it.hasNext();) { if (it.next().equals(xcert)) { found = true; break; } } if (!found) { fail("certificate could not be picked from LDAP directory."); } // System.out.println(coll.toArray()[0]); } public String getName() { return "LDAPCertStoreTest"; } public static void main(String[] args) { Security.addProvider(new BouncyCastleProvider()); runTest(new X509LDAPCertStoreTest()); } }
package org.pocketcampus.plugin.food; import java.lang.reflect.Type; import java.sql.Connection; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Set; import java.util.Vector; import javax.servlet.http.HttpServletRequest; import org.joda.time.Period; import org.pocketcampus.core.plugin.IPlugin; import org.pocketcampus.core.plugin.PublicMethod; import org.pocketcampus.plugin.food.RssParser.RssFeed; import org.pocketcampus.shared.plugin.food.Meal; import org.pocketcampus.shared.plugin.food.Rating; import org.pocketcampus.shared.plugin.food.Rating.SubmitStatus; import org.pocketcampus.shared.plugin.food.Restaurant; import org.pocketcampus.shared.plugin.food.Sandwich; import com.google.gson.Gson; import com.google.gson.JsonSyntaxException; import com.google.gson.reflect.TypeToken; public class Food implements IPlugin/*, IMapElementsProvider*/ { private List<Meal> campusMeals_; private HashMap<Integer, Rating> campusMealRatings_; private ArrayList<String> deviceIds_; private Date lastImportMenus_; private List<Sandwich> sandwichList_; private Date lastImportDateS_; private FoodDB database_; private boolean noMealsToday_; /** * Parse the menus on startup. */ public Food() { database_ = new FoodDB("PocketCampusDB"); campusMeals_ = new ArrayList<Meal>(); campusMealRatings_ = new HashMap<Integer, Rating>(); sandwichList_ = new ArrayList<Sandwich>(); lastImportDateS_ = new Date(); deviceIds_ = new ArrayList<String>(); importSandwiches(); importMenus(); } /** * Get all menus of the day. * * @param request * @return */ @PublicMethod public List<Meal> getMenus(HttpServletRequest request) { if (!isValid(lastImportMenus_)) { System.out .println("<getMenus>: Date not valid. Reimporting menus."); campusMeals_.clear(); deviceIds_.clear(); campusMealRatings_.clear(); importMenus(); } else { System.out.println("<getMenus>: " + lastImportMenus_ + ", not reimporting menus."); } return campusMeals_; } public List<String> getRestaurants(HttpServletRequest request) { ArrayList<String> restaurantList_ = new ArrayList<String>(); if (campusMeals_ != null) { for (Meal m : campusMeals_) { String r = m.getRestaurant_().getName(); if (!restaurantList_.contains(r)) { restaurantList_.add(r); } } } return restaurantList_; } /** * Get all sandwiches of the day. * * @param request * @return the sandwich list */ @PublicMethod public List<Sandwich> getSandwiches(HttpServletRequest request) { if (!isValid(lastImportDateS_)) { importSandwiches(); System.out.println("Reimporting sandwiches."); } else { System.out.println("Not reimporting sandwiches."); } return sandwichList_; } /** * Checks whether the saved menu is today's. * * @return */ private boolean isValid(Date oldDate) { if (oldDate == null) return false; Calendar now = Calendar.getInstance(); now.setTime(new Date()); Calendar then = Calendar.getInstance(); then.setTime(oldDate); System.out.println("Minutes:"+getMinutes(then.getTime(), now.getTime())); if (now.get(Calendar.DAY_OF_WEEK) != then.get(Calendar.DAY_OF_WEEK)) { return false; } else { if(getMinutes(then.getTime(), now.getTime()) > 60){ return false; } } return true; } private long getMinutes(Date then, Date now){ Period p = new Period(then.getTime(), now.getTime()); long hours = p.getHours(); long minutes = p.getMinutes(); return hours*60 + minutes; } /** * Set rating for a particular meal * * @param meal * the meal for which we want to set the rating * @param rating * the rating we want to put. * @return whether the operation worked. */ @PublicMethod public Rating.SubmitStatus setRating(HttpServletRequest request) { updateMenu(); System.out.println("<setRating>: Rating request."); String deviceId = request.getParameter("deviceId"); String stringMealHashCode = request.getParameter("meal"); String stringRating = request.getParameter("rating"); if (stringMealHashCode == null || stringRating == null || deviceId == null) { return SubmitStatus.Error; } Connection connection = database_.createConnection(); boolean voted = database_.checkVotedDevice(connection, deviceId); if (deviceIds_.contains(deviceId)) { System.out.println("Already in list"); database_.closeConnection(connection); return SubmitStatus.AlreadyVoted; } else if (voted) { System.out.println("Already in database."); database_.closeConnection(connection); return SubmitStatus.AlreadyVoted; } int mealHashCode = Integer.parseInt(stringMealHashCode); double r = Double.parseDouble(stringRating); System.out.println(mealHashCode); for (int i = 0; i < campusMeals_.size(); i++) { Meal currentMeal = campusMeals_.get(i); System.out.println("Dedans " + currentMeal.hashCode()); if (currentMeal.hashCode() == mealHashCode) { // Update rating for meal currentMeal.getRating().addRating(r); // Update rating in the database database_.insertRating(connection, mealHashCode, currentMeal); database_.insertVotedDevice(connection, deviceId); deviceIds_.add(deviceId); // Update rating in the list campusMealRatings_.put(mealHashCode, currentMeal.getRating()); database_.closeConnection(connection); return SubmitStatus.Valid; } } database_.closeConnection(connection); return SubmitStatus.Error; } /** * Upload a picture for a meal * * @param request * @return */ public boolean setPicture(HttpServletRequest request) { System.out.println("<setPicture>: Picture request."); String deviceID = request.getParameter("deviceId"); String pictureString = request.getParameter("pictureArray"); String mealHashCodeString = request.getParameter("meal"); if (deviceID == null || pictureString == null || mealHashCodeString == null) { return false; } int mealHashCode = Integer.parseInt(mealHashCodeString); Gson gson = new Gson(); Type byteArrayType = new TypeToken<byte[]>() { }.getType(); byte[] picture = null; try { picture = gson.fromJson(pictureString, byteArrayType); } catch (JsonSyntaxException e) { System.out.println("Json Syntax exception in retrieving picture."); e.printStackTrace(); return false; } return database_.uploadPicture(deviceID, mealHashCode, picture); } /** * Get the rating for a particular meal * * @param meal * the meal for which we want the rating * @return the corresponding rating. */ @PublicMethod public HashMap<Integer, Rating> getRatings(HttpServletRequest request) { updateMenu(); System.out.println("<getRatings>: rating request."); if (campusMealRatings_ != null) { return campusMealRatings_; } return null; } private void updateMenu() { if (!isValid(lastImportMenus_)) { campusMeals_.clear(); deviceIds_.clear(); campusMealRatings_.clear(); importMenus(); } } /** * Import menus from the Rss feeds */ private void importMenus() { Connection connection = database_.createConnection(); List<Meal> mealsFromDB = database_.getMeals(connection); System.out.println(campusMeals_.size()); if (mealsFromDB != null && !mealsFromDB.isEmpty()) { campusMeals_ = mealsFromDB; for (Meal m : campusMeals_) { campusMealRatings_.put(m.hashCode(), m.getRating()); } lastImportMenus_ = new Date(); System.out.println("<getMenus>: Got from database."); } else { RestaurantListParser rlp = new RestaurantListParser(); HashMap<String, String> restaurantFeeds = rlp.getFeeds(); Set<String> restaurants = restaurantFeeds.keySet(); for (String r : restaurants) { RssParser rp = new RssParser(restaurantFeeds.get(r)); rp.parse(); RssFeed feed = rp.getFeed(); Restaurant newResto = new Restaurant(r); if (feed != null && feed.items != null) { for (int i = 0; i < feed.items.size(); i++) { Rating mealRating = new Rating(); Meal newMeal = new Meal(feed.items.get(i).title, feed.items.get(i).description, newResto, true, mealRating); campusMeals_.add(newMeal); campusMealRatings_.put(newMeal.hashCode(), mealRating); } lastImportMenus_ = new Date(); } else { System.out.println("<importMenus>: empty feed"); } } if(campusMeals_.isEmpty()){ noMealsToday_ = true; lastImportMenus_ = new Date(); } for (Meal m : campusMeals_) { database_.insertMeal(m); System.out.println("<importMenus>: Inserting meal " + m.getName_() + ", " + m.getRestaurant_()); } } } /** * Creates the sandwich list */ private void importSandwiches() { /* Cafeteria INM */ sandwichList_ .add(new Sandwich("Cafeteria INM", "Poulet au Curry", true)); sandwichList_.add(new Sandwich("Cafeteria INM", "Thon", true)); sandwichList_.add(new Sandwich("Cafeteria INM", "Jambon", true)); sandwichList_.add(new Sandwich("Cafeteria INM", "Fromage", true)); sandwichList_.add(new Sandwich("Cafeteria INM", "Tomate Mozzarella", true)); sandwichList_.add(new Sandwich("Cafeteria INM", "Jambon Cru", true)); sandwichList_.add(new Sandwich("Cafeteria INM", "Salami", true)); sandwichList_.add(new Sandwich("Cafeteria INM", "Autres", true)); /* Cafeteria BM */ sandwichList_.addAll(defaultSandwichList("Cafeteria BM")); /* Cafeteria BC */ sandwichList_.addAll(defaultSandwichList("Cafeteria BM")); /* Cafeteria SV */ sandwichList_.addAll(defaultSandwichList("Cafeteria SV")); /* Cafeteria MX */ sandwichList_.addAll(defaultSandwichList("Cafeteria MX")); /* Cafeteria PH */ sandwichList_.addAll(defaultSandwichList("Cafeteria PH")); /* Cafeteria ELA */ sandwichList_.addAll(defaultSandwichList("Cafeteria ELA")); /* Le Giacomettia (Cafeteria SG) */ sandwichList_.add(new Sandwich("Le Giacometti", "Jambon", true)); sandwichList_.add(new Sandwich("Le Giacometti", "Salami", true)); sandwichList_ .add(new Sandwich("Le Giacometti", "Jambon de dinde", true)); sandwichList_.add(new Sandwich("Le Giacometti", "Gruyire", true)); sandwichList_.add(new Sandwich("Le Giacometti", "Viande Sche", true)); sandwichList_.add(new Sandwich("Le Giacometti", "Jambon cru", true)); sandwichList_.add(new Sandwich("Le Giacometti", "Roast-Beef", true)); sandwichList_.add(new Sandwich("Le Giacometti", "Poulet Jijommaise", true)); sandwichList_.add(new Sandwich("Le Giacometti", "Crevettes", true)); sandwichList_.add(new Sandwich("Le Giacometti", "Saumon fum", true)); sandwichList_ .add(new Sandwich("Le Giacometti", "Poulet au Curry", true)); sandwichList_.add(new Sandwich("Le Giacometti", "Autres", true)); /* L'Esplanade */ sandwichList_.add(new Sandwich("L'Esplanade", "Thon", true)); sandwichList_.add(new Sandwich("L'Esplanade", "Poulet au Curry", true)); sandwichList_.add(new Sandwich("L'Esplanade", "Aubergine", true)); sandwichList_.add(new Sandwich("L'Esplanade", "Roast-Beef", true)); sandwichList_.add(new Sandwich("L'Esplanade", "Jambon Cru", true)); sandwichList_.add(new Sandwich("L'Esplanade", "Vuabde Sche", true)); sandwichList_.add(new Sandwich("L'Esplanade", "Saumon Fum", true)); sandwichList_.add(new Sandwich("L'Esplanade", "Autres", true)); /* L'Arcadie */ sandwichList_.addAll(defaultSandwichList("L'Arcadie")); /* Atlantide */ sandwichList_.add(new Sandwich("L'Atlantide", "Sandwich long", true)); sandwichList_ .add(new Sandwich("L'Atlantide", "Sandwich au pavot", true)); sandwichList_ .add(new Sandwich("L'Atlantide", "Sandwich intgral", true)); sandwichList_.add(new Sandwich("L'Atlantide", "Sandwich provenal", true)); sandwichList_.add(new Sandwich("L'Atlantide", "Parisette", true)); sandwichList_.add(new Sandwich("L'Atlantide", "Jambon", true)); sandwichList_.add(new Sandwich("L'Atlantide", "Salami", true)); sandwichList_.add(new Sandwich("L'Atlantide", "Dinde", true)); sandwichList_.add(new Sandwich("L'Atlantide", "Thon", true)); sandwichList_.add(new Sandwich("L'Atlantide", "Mozzarella", true)); sandwichList_.add(new Sandwich("L'Atlantide", "Saumon Fum", true)); sandwichList_.add(new Sandwich("L'Atlantide", "Viande Sche", true)); sandwichList_.add(new Sandwich("L'Atlantide", "Jambon Cru", true)); sandwichList_.add(new Sandwich("L'Atlantide", "Roast-Beef", true)); sandwichList_.add(new Sandwich("L'Atlantide", "Autres", true)); /* Satellite */ sandwichList_.add(new Sandwich("Satellite", "Thon", true)); sandwichList_.add(new Sandwich("Satellite", "Jambon fromage", true)); sandwichList_.add(new Sandwich("Satellite", "Roast-Beef", true)); sandwichList_.add(new Sandwich("Satellite", "Poulet au Curry", true)); sandwichList_.add(new Sandwich("Satellite", "Jambon Cru", true)); sandwichList_.add(new Sandwich("Satellite", "Tomate mozza", true)); sandwichList_.add(new Sandwich("Satellite", "Salami", true)); sandwichList_.add(new Sandwich("Satellite", "Parmesan", true)); sandwichList_.add(new Sandwich("Satellite", "Aubergine grill", true)); sandwichList_.add(new Sandwich("Satellite", "Viande sche", true)); sandwichList_.add(new Sandwich("Satellite", "Autres", true)); /* Negoce */ sandwichList_.add(new Sandwich("Negoce", "Dinde", true)); sandwichList_.add(new Sandwich("Negoce", "Thon", true)); sandwichList_.add(new Sandwich("Negoce", "Gratine Jambon", true)); sandwichList_.add(new Sandwich("Negoce", "Mozza Olives", true)); sandwichList_.add(new Sandwich("Negoce", "Poulet au Curry", true)); sandwichList_.add(new Sandwich("Negoce", "Jambon fromage", true)); sandwichList_.add(new Sandwich("Negoce", "Jambon", true)); sandwichList_.add(new Sandwich("Negoce", "Salami", true)); sandwichList_.add(new Sandwich("Negoce", "RoseBeef", true)); sandwichList_.add(new Sandwich("Negoce", "Mozzarella", true)); sandwichList_.add(new Sandwich("Negoce", "Autres", true)); lastImportDateS_ = new Date(); } private Vector<Sandwich> defaultSandwichList(String name) { Vector<Sandwich> defaultSandwichList = new Vector<Sandwich>(); defaultSandwichList.add(new Sandwich(name, "Thon", true)); defaultSandwichList.add(new Sandwich(name, "Jambon", true)); defaultSandwichList.add(new Sandwich(name, "Fromage", true)); defaultSandwichList.add(new Sandwich(name, "Tomate Mozzarella", true)); defaultSandwichList.add(new Sandwich(name, "Jambon Cru", true)); defaultSandwichList.add(new Sandwich(name, "Salami", true)); defaultSandwichList.add(new Sandwich(name, "Autres", true)); return defaultSandwichList; } // @Override // public List<MapElementBean> getLayerItems(int layerId) { // // TODO Auto-generated method stub // return new ArrayList<MapElementBean>(); // @Override // public List<MapLayerBean> getLayers() { // // TODO Auto-generated method stub // List<MapLayerBean> l = new ArrayList<MapLayerBean>(); // l.add(new MapLayerBean("Restaurants", "", this, 1, -1, true)); // return l; // public void writeToFile() { // lastImportDateM_ = new Date(); // String filename = // "c:/Users/Elodie/workspace/pocketcampus-server/MenusCache"; // File menuFile = new File(filename); // FileOutputStream fos = null; // ObjectOutputStream out = null; // try { // fos = new FileOutputStream(menuFile); // out = new ObjectOutputStream(fos); // out.writeObject(campusMeals_); // out.close(); // } catch (IOException ex) {} // public List<Meal> restoreFromFile() { // String filename = // "c:/Users/Elodie/workspace/pocketcampus-server/MenusCache"; // List<Meal> menu = null; // File toGet = new File(filename); // FileInputStream fis = null; // ObjectInputStream in = null; // try { // fis = new FileInputStream(toGet); // in = new ObjectInputStream(fis); // Object obj = in.readObject(); // if(obj instanceof List<?>){ // menu = (List<Meal>) obj; // in.close(); // } catch (IOException ex) { // } catch (ClassNotFoundException ex) { // } catch (ClassCastException cce) { // return menu; }
package com.jacobkchapman.gameoflife; import com.badlogic.gdx.graphics.glutils.ShapeRenderer; import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType; public class Cell { private int x; private int y; private int width; private int height; private boolean alive; private ShapeRenderer shape; public Cell( int x, int y, int size, ShapeRenderer shape) { this.x = x; this.y = y; width = size; height = size; alive = false; this.shape = shape; } public void draw() { if( alive && shape.getCurrentType() == ShapeType.Line) { shape.set( ShapeType.Filled); } shape.rect( x * width, y * height, width, height); if( shape.getCurrentType() == ShapeType.Filled) { shape.set( ShapeType.Line); } } }
package ccw.repl; import java.net.ConnectException; import java.util.concurrent.atomic.AtomicReference; import org.eclipse.core.resources.ProjectScope; import org.eclipse.core.runtime.CoreException; import org.eclipse.debug.core.ILaunch; import org.eclipse.jface.action.IStatusLineManager; import org.eclipse.jface.commands.ActionHandler; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.resource.JFaceResources; import org.eclipse.jface.text.Document; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.SashForm; import org.eclipse.swt.custom.StyleRange; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.custom.VerifyKeyListener; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.events.FocusEvent; import org.eclipse.swt.events.FocusListener; import org.eclipse.swt.events.KeyAdapter; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.KeyListener; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.VerifyEvent; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Listener; import org.eclipse.ui.IKeyBindingService; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.console.ConsolePlugin; import org.eclipse.ui.console.IConsole; import org.eclipse.ui.contexts.IContextService; import org.eclipse.ui.handlers.IHandlerService; import org.eclipse.ui.part.ViewPart; import ccw.CCWPlugin; import ccw.editors.antlrbased.ClojureSourceViewer; import ccw.editors.antlrbased.ClojureSourceViewerConfiguration; import ccw.editors.antlrbased.IClojureEditorActionDefinitionIds; import ccw.editors.antlrbased.OpenDeclarationAction; import ccw.editors.rulesbased.ClojureDocumentProvider; import ccw.launching.LaunchUtils; import ccw.outline.NamespaceBrowser; import clojure.tools.nrepl.Connection; import clojure.lang.Atom; import clojure.lang.IFn; import clojure.lang.Keyword; import clojure.lang.PersistentTreeMap; import clojure.lang.PersistentVector; import clojure.lang.Symbol; import clojure.lang.Var; import clojure.osgi.ClojureOSGi; public class REPLView extends ViewPart { public static final String VIEW_ID = "ccw.view.repl"; public static final AtomicReference<REPLView> activeREPL = new AtomicReference(); private static Var log; private static Var configureREPLView; static { try { ClojureOSGi.require(CCWPlugin.getDefault().getBundle().getBundleContext(), "ccw.repl.view-helpers"); log = Var.find(Symbol.intern("ccw.repl.view-helpers/log")); configureREPLView = Var.find(Symbol.intern("ccw.repl.view-helpers/configure-repl-view")); } catch (Exception e) { CCWPlugin.logError("Could not initialize view helpers.", e); } } private static final Keyword inputExprLogType = Keyword.intern("in-expr"); // TODO would like to eliminate separate log view, but: // 1. PareditAutoEditStrategy gets all text from a source document, and bails badly if its not well-formed // (and REPL output is guaranteed to not be well-formed) // 2. Even if (1) were fixed/changed, it's not clear to me how to "partition" an IDocument, or compose IDocuments // so that we can have one range that is still *highlighted* for clojure content (and not editable), // and another range that is editable and has full paredit, code completion, etc. StyledText logPanel; private ClojureSourceViewer viewer; public StyledText viewerWidget; // public only to simplify interop with helpers impl'd in Clojure private ClojureSourceViewerConfiguration viewerConfig; private Connection interactive; private Connection toolConnection; private IConsole console; private ILaunch launch; private String currentNamespace = "user"; private final Atom requests = new Atom(PersistentTreeMap.EMPTY); private IFn evalExpression; public REPLView () {} private void copyToLog (StyledText s) { int start = logPanel.getCharCount(); try { log.invoke(logPanel, s.getText(), inputExprLogType); for (StyleRange sr : s.getStyleRanges()) { sr.start += start; logPanel.setStyleRange(sr); } } catch (Exception e) { // should never happen CCWPlugin.logError("Could not copy expression to log", e); } } private void evalExpression () { evalExpression(viewerWidget.getText(), false); copyToLog(viewerWidget); viewerWidget.setText(""); } public void evalExpression (String s) { evalExpression(s, true); } public void evalExpression (String s, boolean copyToLog) { try { if (s.trim().length() > 0) { if (copyToLog) log.invoke(logPanel, s, inputExprLogType); evalExpression.invoke(s); } } catch (Exception e) { e.printStackTrace(); } } public void closeView () throws Exception { IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); page.hideView(this); closeConnections(); } public void closeConnections () throws Exception { if (interactive != null) interactive.close(); if (toolConnection != null) toolConnection.close(); } public void reconnect () throws Exception { closeConnections(); logPanel.append(";; Reconnecting...\n"); configure(interactive.host, interactive.port); } public void setCurrentNamespace (String ns) { // TODO waaaay better to put a dropdown namespace chooser in the view's toolbar, // and this would just change its selection currentNamespace = ns; setPartName(String.format("REPL @ %s:%s (%s)", interactive.host, interactive.port, currentNamespace)); } public String getCurrentNamespace () { return currentNamespace; } private void prepareView () throws Exception { evalExpression = (IFn)configureREPLView.invoke(this, logPanel, interactive.conn, requests); } @SuppressWarnings("unchecked") public boolean configure (String host, int port) throws Exception { try { interactive = new Connection(host, port); toolConnection = new Connection(host, port); setCurrentNamespace(currentNamespace); prepareView(); logPanel.append(";; Clojure " + toolConnection.send("(clojure-version)").values().get(0) + "\n"); return true; } catch (ConnectException e) { closeView(); MessageDialog.openInformation(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), "Could not connect", String.format("Could not connect to REPL @ %s:%s", host, port)); return false; } } public static REPLView connect () throws Exception { IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); ConnectDialog dlg = new ConnectDialog(window.getShell()); REPLView repl = null; if (dlg.open() == ConnectDialog.OK) { // cannot find any way to create a configured/connected REPLView, and install it programmatically String host = dlg.getHost(); int port = dlg.getPort(); if (host == null || host.length() == 0 || port < 0 || port > 65535) { MessageDialog.openInformation(window.getShell(), "Invalid connection info", "You must provide a useful hostname and port number to connect to a REPL."); } else { repl = connect(host, port); } } return repl; } public static REPLView connect (String host, int port) throws Exception { return connect(host, port, null, null); } public static REPLView connect (String host, int port, IConsole console, ILaunch launch) throws Exception { REPLView repl = (REPLView)PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().showView(VIEW_ID, host + "@" + port, IWorkbenchPage.VIEW_ACTIVATE); repl.console = console; repl.launch = launch; return repl.configure(host, port) ? repl : null; } public Connection getConnection () { return interactive; } public Connection getToolingConnection () { return toolConnection; } /** * Returns the console for the launch that this REPL is associated with, or * null if this REPL is using a remote connection. */ public IConsole getConsole () { return console; } public void showConsole () { if (console != null) ConsolePlugin.getDefault().getConsoleManager().showConsoleView(console); } public ILaunch getLaunch() { return launch; } @Override public void createPartControl(Composite parent) { IPreferenceStore prefs = CCWPlugin.getDefault().getCombinedPreferenceStore(); SashForm split = new SashForm(parent, SWT.VERTICAL); logPanel = new StyledText(split, SWT.V_SCROLL | SWT.WRAP); logPanel.setIndent(4); logPanel.setEditable(false); logPanel.setFont(JFaceResources.getFont(JFaceResources.TEXT_FONT)); viewer = new ClojureSourceViewer(split, null, null, false, SWT.V_SCROLL | SWT.H_SCROLL, prefs) { public Connection getCorrespondingREPLConnection () { // we'll be connected by the time this is called return toolConnection; } public void setStatusLineErrorMessage(String msg) { IStatusLineManager slm = (IStatusLineManager) REPLView.super.getSite().getService(IStatusLineManager.class); slm.setErrorMessage(msg); }; public String getDeclaringNamespace() { String inline = super.getDeclaringNamespace(); if (inline != null) { return inline; } else { return currentNamespace; } }; }; viewerConfig = new ClojureSourceViewerConfiguration(prefs, viewer); viewer.configure(viewerConfig); getViewSite().setSelectionProvider(viewer); viewer.setDocument(ClojureDocumentProvider.configure(new Document())); viewerWidget = viewer.getTextWidget(); viewerWidget.setFont(JFaceResources.getFont(JFaceResources.TEXT_FONT)); viewerWidget.addVerifyKeyListener(new REPLInputVerifier()); // push all keyboard input delivered to log panel into input widget logPanel.addListener(SWT.KeyDown, new Listener() { public void handleEvent(Event e) { // this prevents focus switch on cut/copy // no event that would trigger a paste is sent as long as logPanel is uneditable, // so we can't redirect it :-( boolean modifier = (e.keyCode & SWT.MODIFIER_MASK) != 0; if (modifier) return; viewerWidget.notifyListeners(SWT.KeyDown, e); viewerWidget.setFocus(); } }); /* * Need to hook up here to force a re-evaluation of the preferences * for the syntax coloring, after the token scanner has been * initialized. Otherwise the very first Clojure editor will not * have any tokens colored. * TODO this is repeated in AntlrBasedClojureEditor...surely we can make the source viewer self-sufficient here */ viewer.propertyChange(null); viewerWidget.addFocusListener(new NamespaceRefreshFocusListener()); logPanel.addFocusListener(new NamespaceRefreshFocusListener()); parent.addDisposeListener(new DisposeListener () { public void widgetDisposed(DisposeEvent e) { activeREPL.compareAndSet(REPLView.this, null); } }); ((IContextService) getSite().getService(IContextService.class)).activateContext("ccw.ui.clojureEditorScope"); // TODO magic constant IHandlerService handlerService = (IHandlerService) getSite().getService(IHandlerService.class); OpenDeclarationAction action = new OpenDeclarationAction(viewer); action.setActionDefinitionId(IClojureEditorActionDefinitionIds.OPEN_DECLARATION); handlerService.activateHandler("ccw.ui.edit.text.clojure.open.declaration", new ActionHandler(action)); split.setWeights(new int[] {100, 75}); } @Override public void dispose() { super.dispose(); interactive.close(); toolConnection.close(); } public boolean isDisposed () { // TODO we actually want to report whether the viewpart has been closed, not whether or not // the platform has disposed the widget peer return viewerWidget.isDisposed(); } @Override public void setFocus() { viewerWidget.setFocus(); } private final class NamespaceRefreshFocusListener implements FocusListener { public void focusGained(FocusEvent e) { activeREPL.set(REPLView.this); NamespaceBrowser.setREPLConnection(toolConnection); } public void focusLost(FocusEvent e) {} } private class REPLInputVerifier implements VerifyKeyListener { private boolean isEvalEvent (KeyEvent e) { if (e.stateMask == SWT.SHIFT) return false; if (e.keyCode == '\n' || e.keyCode == '\r') { return e.stateMask == SWT.CONTROL || viewerWidget.getSelection().x == viewerWidget.getCharCount(); } return false; } public void verifyKey(VerifyEvent e) { if (isEvalEvent(e)) { evalExpression(); e.doit = false; } } } }
package net.hyperic.sigar; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.util.List; import java.util.Map; import net.hyperic.jni.ArchLoaderException; import net.hyperic.jni.ArchNotSupportedException; /** * The Sigar class provides access to the sigar objects containing * system information. The Sigar object itself maintains internal * state specific to each platform. It also implements the SigarProxy * interface which provides caching at the Java level. */ public class Sigar implements SigarProxy { private static String loadError = null; public static final long FIELD_NOTIMPL = -1; /** * The Sigar version in String form. */ public static final String VERSION_STRING = SigarVersion.VERSION_STRING; /** * The date on which the Sigar binaries were built. */ public static final String BUILD_DATE = SigarVersion.BUILD_DATE; private static SigarLoader loader = new SigarLoader(Sigar.class); private FileSystemMap mounts = null; int sigarWrapper = 0; //holds the sigar_t * long longSigarWrapper = 0; //same, but where sizeof(void*) > sizeof(int) // lastCpu is used to calculate the cpuPerc; private Cpu lastCpu; private Cpu[] lastCpuList; private static SigarProxy instance = null; static { try { loadLibrary(); } catch (SigarException e) { String msg = "Sigar.load: " + e.getMessage(); try { SigarLog.debug(msg, e); } catch (NoClassDefFoundError ne) { //no log4j.jar System.err.println(msg); e.printStackTrace(); } } } public static void load() throws SigarException { if (loadError != null) { throw new SigarException(loadError); } } private static void loadLibrary() throws SigarException { try { if (SigarLoader.IS_WIN32 && System.getProperty("os.version").equals("4.0")) { String lib = loader.findJarPath("pdh.dll") + File.separator + "pdh.dll"; loader.systemLoad(lib); } loader.load(); } catch (ArchNotSupportedException e) { throw new SigarException(e.getMessage()); } catch (ArchLoaderException e) { throw new SigarException(e.getMessage()); } catch (UnsatisfiedLinkError e) { throw new SigarException(e.getMessage()); } } /** * Format size in bytes to a human readable string. * * @param size The size to format. * @return The formatted string. */ public static native String formatSize(long size); /** * Allocate and initialize the native Sigar object. */ public Sigar() { try { open(); } catch (SigarException e) { //XXX log? } catch (UnsatisfiedLinkError e) { //XXX log? } } /** * Convenience method to keep a sigar instance alive. * This instance is safe to share between threads. */ public static synchronized SigarProxy getInstance() { if (instance == null) { instance = new SynchronizedSigar(); } return instance; } protected void finalize() { close(); } private native void open() throws SigarException; /** * Release any native resources associated with this sigar instance. * The sigar object is no longer usable after it has been closed. * If the close method is not called directly, the finalize method will * call it if the Sigar object is garbage collected. */ public void close() { if (this.sigarWrapper != 0) { nativeClose(); } } private native int nativeClose(); /** * Get pid of the current process. * @exception SigarException on failure. */ public native long getPid(); /** * Get pid for the Windows service with the given name. * This method is implemented on Windows only as a helper * for PTQL. */ public native long getServicePid(String name) throws SigarException; /** * Send a signal to a process. * * @param pid The process id. * @param signum The signal number. * @exception SigarException on failure. */ public native void kill(long pid, int signum) throws SigarException; /** * Get system memory info. * @exception SigarException on failure. */ public Mem getMem() throws SigarException { return Mem.fetch(this); } /** * Get system swap info. * @exception SigarException on failure. */ public Swap getSwap() throws SigarException { return Swap.fetch(this); } /** * Get system cpu info. * @exception SigarException on failure. */ public Cpu getCpu() throws SigarException { return (this.lastCpu = Cpu.fetch(this)); } static void pause(int millis) { try { Thread.sleep(millis); } catch(InterruptedException e) { } } static void pause() { pause(500); } /** * Get system CPU info in percentage format. (i.e. fraction of 1) * @exception SigarException on failure. */ public CpuPerc getCpuPerc() throws SigarException { Cpu oldCpu, curCpu; if (this.lastCpu == null){ oldCpu = this.getCpu(); pause(); } else { oldCpu = this.lastCpu; } curCpu = this.getCpu(); return CpuPerc.calculate(oldCpu, curCpu); } /** * Get system per-CPU info in percentage format. (i.e. fraction of 1) * @exception SigarException on failure. */ public CpuPerc[] getCpuPercList() throws SigarException { Cpu[] oldCpuList, curCpuList; if (this.lastCpuList == null){ oldCpuList = getCpuList(); pause(); } else { oldCpuList = this.lastCpuList; } curCpuList = getCpuList(); int curLen = curCpuList.length, oldLen = oldCpuList.length; CpuPerc[] perc = new CpuPerc[curLen < oldLen ? curLen : oldLen]; for (int i=0; i<curCpuList.length; i++) { Cpu curCpu = curCpuList[i], oldCpu; oldCpu = oldCpuList[i]; perc[i] = CpuPerc.calculate(oldCpu, curCpu); } return perc; } /** * Get system uptime info. * @exception SigarException on failure. */ public Uptime getUptime() throws SigarException { return Uptime.fetch(this); } /** * Get system load average. * @exception SigarException on failure. * @return The system load averages for the past 1, 5, and 15 minutes. */ public native double[] getLoadAverage() throws SigarException; /** * Get system process list. * @exception SigarException on failure. * @return Array of process ids. */ public native long[] getProcList() throws SigarException; /** * Get system process stats. * @exception SigarException on failure. */ public ProcStat getProcStat() throws SigarException { return ProcStat.fetch(this); } private long convertPid(String pid) throws SigarException { if (pid.equals("$$")) { return getPid(); } return Long.parseLong(pid); } /** * Get process memory info. * @param pid The process id. * @exception SigarException on failure. */ public ProcMem getProcMem(long pid) throws SigarException { return ProcMem.fetch(this, pid); } public ProcMem getProcMem(String pid) throws SigarException { return getProcMem(convertPid(pid)); } public ProcMem getMultiProcMem(String query) throws SigarException { return MultiProcMem.get(this, query); } /** * Get process state info. * @param pid The process id. * @exception SigarException on failure. */ public ProcState getProcState(long pid) throws SigarException { return ProcState.fetch(this, pid); } public ProcState getProcState(String pid) throws SigarException { return getProcState(convertPid(pid)); } /** * Get process time info. * @param pid The process id. * @exception SigarException on failure. */ public ProcTime getProcTime(long pid) throws SigarException { return ProcTime.fetch(this, pid); } public ProcTime getProcTime(String pid) throws SigarException { return getProcTime(convertPid(pid)); } /** * Get process cpu info. * @param pid The process id. * @exception SigarException on failure. */ public ProcCpu getProcCpu(long pid) throws SigarException { return ProcCpu.get(this, pid); } public ProcCpu getProcCpu(String pid) throws SigarException { return getProcCpu(convertPid(pid)); } public MultiProcCpu getMultiProcCpu(String query) throws SigarException { return MultiProcCpu.get(this, query); } /** * Get process credential info. * @param pid The process id. * @exception SigarException on failure. */ public ProcCred getProcCred(long pid) throws SigarException { return ProcCred.fetch(this, pid); } public ProcCred getProcCred(String pid) throws SigarException { return getProcCred(convertPid(pid)); } /** * Get process credential names. * @param pid The process id. * @exception SigarException on failure. */ public ProcCredName getProcCredName(long pid) throws SigarException { return ProcCredName.fetch(this, pid); } public ProcCredName getProcCredName(String pid) throws SigarException { return getProcCredName(convertPid(pid)); } /** * Get process file descriptor info. * @param pid The process id. * @exception SigarException on failure. */ public ProcFd getProcFd(long pid) throws SigarException { return ProcFd.fetch(this, pid); } public ProcFd getProcFd(String pid) throws SigarException { return getProcFd(convertPid(pid)); } /** * Get process current working directory. * @param pid The process id. * @exception SigarException on failure. */ public ProcExe getProcExe(long pid) throws SigarException { return ProcExe.fetch(this, pid); } public ProcExe getProcExe(String pid) throws SigarException { return getProcExe(convertPid(pid)); } /** * Get process arguments. * @param pid The process id. * @return Array of argument strings. * @exception SigarException on failure. */ public native String[] getProcArgs(long pid) throws SigarException; public String[] getProcArgs(String pid) throws SigarException { return getProcArgs(convertPid(pid)); } /** * Get process environment. * @param pid The process id. * @return Map of environment strings. * @exception SigarException on failure. */ public Map getProcEnv(long pid) throws SigarException { return ProcEnv.getAll(this, pid); } public Map getProcEnv(String pid) throws SigarException { return getProcEnv(convertPid(pid)); } /** * Get process environment variable value. * This method is intended to avoid the overhead * of creating a Map with all variables if only * a single variable is needed. * @param pid The process id. * @param key Environment variable name. * @return Environment variable value. * @exception SigarException on failure. */ public String getProcEnv(long pid, String key) throws SigarException { return ProcEnv.getValue(this, pid, key); } public String getProcEnv(String pid, String key) throws SigarException { return getProcEnv(convertPid(pid), key); } /** * Get process loaded modules.<p> * Supported Platforms: Linux, Solaris and Windows. * @param pid The process id. * @return List of loaded modules. * @exception SigarException on failure. */ private native List getProcModulesNative(long pid) throws SigarException; public List getProcModules(long pid) throws SigarException { return getProcModulesNative(pid); } public List getProcModules(String pid) throws SigarException { return getProcModules(convertPid(pid)); } /** * Find the pid of the process which is listening on the given port.<p> * Supported Platforms: Linux, Windows 2003, Windows XP, AIX. * @param protocol NetFlags.CONN_TCP or NetFlags.CONN_UDP. * @param port The port number. * @return pid of the process. * @exception SigarException on failure. */ public native long getProcPort(int protocol, long port) throws SigarException; /** * @param protocol "tcp" or "udp". * @param port The port number. * @return pid of the process. * @exception SigarException on failure. */ public long getProcPort(String protocol, String port) throws SigarException { return getProcPort(NetFlags.getConnectionProtocol(protocol), Integer.parseInt(port)); } /** * Get the cumulative cpu time for the calling thread. */ public ThreadCpu getThreadCpu() throws SigarException { return ThreadCpu.fetch(this, 0); } private native FileSystem[] getFileSystemListNative() throws SigarException; /** * Get list of file systems. * @exception SigarException on failure. */ public FileSystem[] getFileSystemList() throws SigarException { FileSystem[] fslist = getFileSystemListNative(); if (this.mounts != null) { this.mounts.init(fslist); } return fslist; } /** * Get file system usage. * @param name Name of the directory on which filesystem is mounted. * @exception SigarException on failure. */ public FileSystemUsage getFileSystemUsage(String name) throws SigarException { if (name == null) { throw new SigarException("name cannot be null"); } return FileSystemUsage.fetch(this, name); } /** * Get file system usage of a mounted directory. * This method checks that the given directory is mounted. * Unlike getFileSystemUsage() which only requires that the * directory exists within a mounted file system. * This method will also check that NFS servers are reachable via RPC * before attempting to get the file system stats to prevent application * hang when an NFS server is down. * @param name Name of the directory on which filesystem is mounted. * @exception SigarException If given directory is not mounted. * @exception NfsUnreachableException If NFS server is unreachable. * @see net.hyperic.sigar.Sigar#getFileSystemUsage */ public FileSystemUsage getMountedFileSystemUsage(String name) throws SigarException, NfsUnreachableException { FileSystem fs = getFileSystemMap().getFileSystem(name); if (fs == null) { throw new SigarException(name + " is not a mounted filesystem"); } if (fs instanceof NfsFileSystem) { NfsFileSystem nfs = (NfsFileSystem)fs; if (!nfs.ping()) { throw nfs.getUnreachableException(); } } return FileSystemUsage.fetch(this, name); } public FileSystemMap getFileSystemMap() throws SigarException { if (this.mounts == null) { this.mounts = new FileSystemMap(); } getFileSystemList(); //this.mounts.init() return this.mounts; } public FileInfo getFileInfo(String name) throws SigarException { return FileInfo.fetchFileInfo(this, name); } public FileInfo getLinkInfo(String name) throws SigarException { return FileInfo.fetchLinkInfo(this, name); } public DirStat getDirStat(String name) throws SigarException { return DirStat.fetch(this, name); } /** * Get list of cpu infomation. * @exception SigarException on failure. */ public native CpuInfo[] getCpuInfoList() throws SigarException; private native Cpu[] getCpuListNative() throws SigarException; /** * Get list of per-cpu metrics. * @exception SigarException on failure. */ public Cpu[] getCpuList() throws SigarException { return (this.lastCpuList = getCpuListNative()); } /** * Get list of network routes. * @exception SigarException on failure. */ public native NetRoute[] getNetRouteList() throws SigarException; /** * Get list of network connections. * @exception SigarException on failure. */ public native NetConnection[] getNetConnectionList(int flags) throws SigarException; public NetStat getNetStat() throws SigarException { return new NetStat(this); } public native Who[] getWhoList() throws SigarException; /** * Get network interface configuration info. * @exception SigarException on failure. */ public NetInterfaceConfig getNetInterfaceConfig(String name) throws SigarException { return NetInterfaceConfig.fetch(this, name); } /** * Get network interface stats. * @exception SigarException on failure. */ public NetInterfaceStat getNetInterfaceStat(String name) throws SigarException { return NetInterfaceStat.fetch(this, name); } /** * Get the list of configured network interface names. * @exception SigarException on failure. */ public native String[] getNetInterfaceList() throws SigarException; /** * Prompt for a password, disabling terminal echo * during user input. * @param prompt Text printed before disabling echo * @return Text entered by the user. * @throws IOException If input could not be read. * @throws SigarNotImplementedException If the native method * is not implemented on the current platform. */ native static String getPasswordNative(String prompt) throws IOException, SigarNotImplementedException; /** * Prompt for a password, disabling terminal echo * during user input if possible. * @param prompt Text printed before disabling echo * @return Text entered by the user. * @throws IOException If input could not be read. */ public static String getPassword(String prompt) throws IOException { try { return getPasswordNative(prompt); } catch (IOException e) { throw e; } catch (SigarNotImplementedException e) { //fallthrough } //fallback if native .so was not loaded or not supported System.out.print(prompt); return (new BufferedReader(new InputStreamReader(System.in))). readLine(); } /** * Reliably retrieve the FQDN for a machine * * @return The fully qualified domain name of the machine. * @exception SigarException on failure. */ public native String getFQDN() throws SigarException; /** * Enabling logging in the native Sigar code. * This method will hook log4j into the Sigar * native logging methods. Note that the majority * of logging in the native code is only at the DEBUG * level. */ public void enableLogging(boolean value) { if (value) { SigarLog.enable(this); } else { SigarLog.disable(this); } } }
package aQute.bnd.osgi; import java.io.*; import java.lang.annotation.*; import java.lang.reflect.*; import java.nio.*; import java.util.*; import java.util.regex.*; import aQute.bnd.osgi.Descriptors.Descriptor; import aQute.bnd.osgi.Descriptors.PackageRef; import aQute.bnd.osgi.Descriptors.TypeRef; import aQute.libg.generics.*; public class Clazz { static Pattern METHOD_DESCRIPTOR = Pattern.compile("\\((.*)\\)(.+)"); public class ClassConstant { int cname; public ClassConstant(int class_index) { this.cname = class_index; } public String getName() { return (String) pool[cname]; } } public static enum JAVA { JDK1_1(45, "JRE-1.1"), JDK1_2(46, "J2SE-1.2"), JDK1_3(47, "J2SE-1.3"), JDK1_4(48, "J2SE-1.4"), J2SE5(49, "J2SE-1.5"), J2SE6(50, "JavaSE-1.6"), OpenJDK7(51, "JavaSE-1.7"), UNKNOWN(Integer.MAX_VALUE, "<>") ; final int major; final String ee; JAVA(int major, String ee) { this.major = major; this.ee = ee; } static JAVA format(int n) { for (JAVA e : JAVA.values()) if (e.major == n) return e; return UNKNOWN; } public int getMajor() { return major; } public boolean hasAnnotations() { return major >= J2SE5.major; } public boolean hasGenerics() { return major >= J2SE5.major; } public boolean hasEnums() { return major >= J2SE5.major; } public static JAVA getJava(int major, @SuppressWarnings("unused") int minor) { for (JAVA j : JAVA.values()) { if (j.major == major) return j; } return UNKNOWN; } public String getEE() { return ee; } } public static enum QUERY { IMPLEMENTS, EXTENDS, IMPORTS, NAMED, ANY, VERSION, CONCRETE, ABSTRACT, PUBLIC, ANNOTATED, RUNTIMEANNOTATIONS, CLASSANNOTATIONS; } public final static EnumSet<QUERY> HAS_ARGUMENT = EnumSet.of(QUERY.IMPLEMENTS, QUERY.EXTENDS, QUERY.IMPORTS, QUERY.NAMED, QUERY.VERSION, QUERY.ANNOTATED); /** * <pre> * ACC_PUBLIC 0x0001 Declared public; may be accessed from outside its * package. * ACC_FINAL 0x0010 Declared final; no subclasses allowed. * ACC_SUPER 0x0020 Treat superclass methods specially when invoked by the * invokespecial instruction. * ACC_INTERFACE 0x0200 Is an interface, not a * class. * ACC_ABSTRACT 0x0400 Declared abstract; may not be instantiated. * </pre> * * @param mod */ final static int ACC_PUBLIC = 0x0001; // Declared // public; // may // accessed // from outside its package. final static int ACC_FINAL = 0x0010; // Declared // final; // subclasses // allowed. final static int ACC_SUPER = 0x0020; // Treat // superclass // methods // specially when invoked by the // invokespecial instruction. final static int ACC_INTERFACE = 0x0200; // interface, // not // classs final static int ACC_ABSTRACT = 0x0400; // Declared // a thing not in the source code final static int ACC_SYNTHETIC = 0x1000; final static int ACC_ANNOTATION = 0x2000; final static int ACC_ENUM = 0x4000; static protected class Assoc { Assoc(byte tag, int a, int b) { this.tag = tag; this.a = a; this.b = b; } byte tag; int a; int b; } public abstract class Def { final int access; Set<TypeRef> annotations; public Def(int access) { this.access = access; } public int getAccess() { return access; } public boolean isEnum() { return (access & ACC_ENUM) != 0; } public boolean isPublic() { return Modifier.isPublic(access); } public boolean isAbstract() { return Modifier.isAbstract(access); } public boolean isProtected() { return Modifier.isProtected(access); } public boolean isFinal() { return Modifier.isFinal(access) || Clazz.this.isFinal(); } public boolean isStatic() { return Modifier.isStatic(access); } public boolean isPrivate() { return Modifier.isPrivate(access); } public boolean isNative() { return Modifier.isNative(access); } public boolean isTransient() { return Modifier.isTransient(access); } public boolean isVolatile() { return Modifier.isVolatile(access); } public boolean isInterface() { return Modifier.isInterface(access); } public boolean isSynthetic() { return (access & ACC_SYNTHETIC) != 0; } void addAnnotation(Annotation a) { if (annotations == null) annotations = Create.set(); annotations.add(analyzer.getTypeRef(a.name.getBinary())); } public Collection<TypeRef> getAnnotations() { return annotations; } public TypeRef getOwnerType() { return className; } public abstract String getName(); public abstract TypeRef getType(); public abstract TypeRef[] getPrototype(); public Object getClazz() { return Clazz.this; } } public class FieldDef extends Def { final String name; final Descriptor descriptor; String signature; Object constant; boolean deprecated; public boolean isDeprecated() { return deprecated; } public void setDeprecated(boolean deprecated) { this.deprecated = deprecated; } public FieldDef(int access, String name, String descriptor) { super(access); this.name = name; this.descriptor = analyzer.getDescriptor(descriptor); } public String getName() { return name; } public TypeRef getType() { return descriptor.getType(); } public TypeRef getContainingClass() { return getClassName(); } public Descriptor getDescriptor() { return descriptor; } public void setConstant(Object o) { this.constant = o; } public Object getConstant() { return this.constant; } // TODO change to use proper generics public String getGenericReturnType() { String use = descriptor.toString(); if (signature != null) use = signature; Matcher m = METHOD_DESCRIPTOR.matcher(use); if (!m.matches()) throw new IllegalArgumentException("Not a valid method descriptor: " + descriptor); String returnType = m.group(2); return objectDescriptorToFQN(returnType); } public TypeRef[] getPrototype() { return null; } public String getSignature() { return signature; } public String toString() { return name; } } public class MethodDef extends FieldDef { public MethodDef(int access, String method, String descriptor) { super(access, method, descriptor); } public boolean isConstructor() { return name.equals("<init>") || name.equals("<clinit>"); } public TypeRef[] getPrototype() { return descriptor.getPrototype(); } } public class TypeDef extends Def { TypeRef type; boolean interf; public TypeDef(TypeRef type, boolean interf) { super(Modifier.PUBLIC); this.type = type; this.interf = interf; } public TypeRef getReference() { return type; } public boolean getImplements() { return interf; } public String getName() { if (interf) return "<implements>"; else return "<extends>"; } public TypeRef getType() { return type; } public TypeRef[] getPrototype() { return null; } } final static byte SkipTable[] = { 0, // 0 non existent -1, // 1 CONSTANT_utf8 UTF 8, handled in // method -1, 4, // 3 CONSTANT_Integer 4, // 4 CONSTANT_Float 8, // 5 CONSTANT_Long (index +=2!) 8, // 6 CONSTANT_Double (index +=2!) -1, // 7 CONSTANT_Class 2, // 8 CONSTANT_String 4, // 9 CONSTANT_FieldRef 4, // 10 CONSTANT_MethodRef 4, // 11 CONSTANT_InterfaceMethodRef 4, // 12 CONSTANT_NameAndType -1, // 13 Not defined -1, // 14 Not defined 3, // 15 CONSTANT_MethodHandle 2, // 16 CONSTANT_MethodType -1, // 17 Not defined 4, // 18 CONSTANT_InvokeDynamic }; boolean hasRuntimeAnnotations; boolean hasClassAnnotations; TypeRef className; Object pool[]; int intPool[]; Set<PackageRef> imports = Create.set(); String path; int minor = 0; int major = 0; int innerAccess = -1; int accessx = 0; String sourceFile; Set<TypeRef> xref; Set<TypeRef> annotations; int forName = 0; int class$ = 0; TypeRef[] interfaces; TypeRef zuper; ClassDataCollector cd = null; Resource resource; FieldDef last = null; boolean deprecated; Set<PackageRef> api; final Analyzer analyzer; public Clazz(Analyzer analyzer, String path, Resource resource) { this.path = path; this.resource = resource; this.analyzer = analyzer; } public Set<TypeRef> parseClassFile() throws Exception { return parseClassFileWithCollector(null); } public Set<TypeRef> parseClassFile(InputStream in) throws Exception { return parseClassFile(in, null); } public Set<TypeRef> parseClassFileWithCollector(ClassDataCollector cd) throws Exception { InputStream in = resource.openInputStream(); try { return parseClassFile(in, cd); } finally { in.close(); } } public Set<TypeRef> parseClassFile(InputStream in, ClassDataCollector cd) throws Exception { DataInputStream din = new DataInputStream(in); try { this.cd = cd; return parseClassFile(din); } finally { cd = null; din.close(); } } Set<TypeRef> parseClassFile(DataInputStream in) throws Exception { xref = new HashSet<TypeRef>(); boolean crawl = cd != null; // Crawl the byte code if we have a // collector int magic = in.readInt(); if (magic != 0xCAFEBABE) throw new IOException("Not a valid class file (no CAFEBABE header)"); minor = in.readUnsignedShort(); // minor version major = in.readUnsignedShort(); // major version if (cd != null) cd.version(minor, major); int count = in.readUnsignedShort(); pool = new Object[count]; intPool = new int[count]; process: for (int poolIndex = 1; poolIndex < count; poolIndex++) { byte tag = in.readByte(); switch (tag) { case 0 : break process; case 1 : constantUtf8(in, poolIndex); break; case 3 : constantInteger(in, poolIndex); break; case 4 : constantFloat(in, poolIndex); break; // For some insane optimization reason are // the long and the double two entries in the // constant pool. See 4.4.5 case 5 : constantLong(in, poolIndex); poolIndex++; break; case 6 : constantDouble(in, poolIndex); poolIndex++; break; case 7 : constantClass(in, poolIndex); break; case 8 : constantString(in, poolIndex); break; case 10 : // Method ref case 11 : // Interface Method ref methodRef(in, poolIndex); break; // Name and Type case 12 : nameAndType(in, poolIndex, tag); break; // We get the skip count for each record type // from the SkipTable. This will also automatically // abort when default : if (tag == 2) throw new IOException("Invalid tag " + tag); in.skipBytes(SkipTable[tag]); break; } } pool(pool, intPool); // All name& type and class constant records contain descriptors we must // treat // as references, though not API for (Object o : pool) { if (o == null) continue; if (o instanceof Assoc && ((Assoc) o).tag == 12) { referTo(((Assoc) o).b, 0); // Descriptor } else if (o instanceof ClassConstant) { String binaryClassName = (String) pool[((ClassConstant) o).cname]; TypeRef typeRef = analyzer.getTypeRef(binaryClassName); referTo(typeRef, 0); } } /* * Parse after the constant pool, code thanks to Hans Christian * Falkenberg */ accessx = in.readUnsignedShort(); // access if (Modifier.isPublic(accessx)) api = new HashSet<PackageRef>(); int this_class = in.readUnsignedShort(); className = analyzer.getTypeRef((String) pool[intPool[this_class]]); referTo(className, Modifier.PUBLIC); try { if (cd != null) { if (!cd.classStart(accessx, className)) return null; } int super_class = in.readUnsignedShort(); String superName = (String) pool[intPool[super_class]]; if (superName != null) { zuper = analyzer.getTypeRef(superName); } if (zuper != null) { referTo(zuper, accessx); if (cd != null) cd.extendsClass(zuper); } int interfacesCount = in.readUnsignedShort(); if (interfacesCount > 0) { interfaces = new TypeRef[interfacesCount]; for (int i = 0; i < interfacesCount; i++) { interfaces[i] = analyzer.getTypeRef((String) pool[intPool[in.readUnsignedShort()]]); referTo(interfaces[i], accessx); } if (cd != null) cd.implementsInterfaces(interfaces); } int fieldsCount = in.readUnsignedShort(); for (int i = 0; i < fieldsCount; i++) { int access_flags = in.readUnsignedShort(); // skip access flags int name_index = in.readUnsignedShort(); int descriptor_index = in.readUnsignedShort(); // Java prior to 1.5 used a weird // static variable to hold the com.X.class // result construct. If it did not find it // it would create a variable class$com$X // that would be used to hold the class // object gotten with Class.forName ... // Stupidly, they did not actively use the // class name for the field type, so bnd // would not see a reference. We detect // this case and add an artificial descriptor String name = pool[name_index].toString(); // name_index if (name.startsWith("class$")) { crawl = true; } if (cd != null) cd.field(last = new FieldDef(access_flags, name, pool[descriptor_index].toString())); referTo(descriptor_index, access_flags); doAttributes(in, ElementType.FIELD, false, access_flags); } // Check if we have to crawl the code to find // the ldc(_w) <string constant> invokestatic Class.forName // if so, calculate the method ref index so we // can do this efficiently if (crawl) { forName = findMethodReference("java/lang/Class", "forName", "(Ljava/lang/String;)Ljava/lang/Class;"); class$ = findMethodReference(className.getBinary(), "class$", "(Ljava/lang/String;)Ljava/lang/Class;"); } else if (major == 48) { forName = findMethodReference("java/lang/Class", "forName", "(Ljava/lang/String;)Ljava/lang/Class;"); if (forName > 0) { crawl = true; class$ = findMethodReference(className.getBinary(), "class$", "(Ljava/lang/String;)Ljava/lang/Class;"); } } // There are some serious changes in the // class file format. So we do not do any crawling // it has also become less important if (major >= JAVA.OpenJDK7.major) crawl = false; // Handle the methods int methodCount = in.readUnsignedShort(); for (int i = 0; i < methodCount; i++) { int access_flags = in.readUnsignedShort(); int name_index = in.readUnsignedShort(); int descriptor_index = in.readUnsignedShort(); String name = pool[name_index].toString(); String descriptor = pool[descriptor_index].toString(); if (cd != null) { MethodDef mdef = new MethodDef(access_flags, name, descriptor); last = mdef; cd.method(mdef); } referTo(descriptor_index, access_flags); if ("<init>".equals(name)) { doAttributes(in, ElementType.CONSTRUCTOR, crawl, access_flags); } else { doAttributes(in, ElementType.METHOD, crawl, access_flags); } } if (cd != null) cd.memberEnd(); doAttributes(in, ElementType.TYPE, false, accessx); // Parse all the descriptors we found Set<TypeRef> xref = this.xref; reset(); return xref; } finally { if (cd != null) cd.classEnd(); } } private void constantFloat(DataInputStream in, int poolIndex) throws IOException { if (cd != null) pool[poolIndex] = in.readFloat(); // ALU else in.skipBytes(4); } private void constantInteger(DataInputStream in, int poolIndex) throws IOException { intPool[poolIndex] = in.readInt(); if (cd != null) pool[poolIndex] = intPool[poolIndex]; } protected void pool(@SuppressWarnings("unused") Object[] pool, @SuppressWarnings("unused") int[] intPool) {} /** * @param in * @param poolIndex * @param tag * @throws IOException */ protected void nameAndType(DataInputStream in, int poolIndex, byte tag) throws IOException { int name_index = in.readUnsignedShort(); int descriptor_index = in.readUnsignedShort(); pool[poolIndex] = new Assoc(tag, name_index, descriptor_index); } /** * @param in * @param poolIndex * @param tag * @throws IOException */ private void methodRef(DataInputStream in, int poolIndex) throws IOException { int class_index = in.readUnsignedShort(); int name_and_type_index = in.readUnsignedShort(); pool[poolIndex] = new Assoc((byte) 10, class_index, name_and_type_index); } /** * @param in * @param poolIndex * @throws IOException */ private void constantString(DataInputStream in, int poolIndex) throws IOException { int string_index = in.readUnsignedShort(); intPool[poolIndex] = string_index; } /** * @param in * @param poolIndex * @throws IOException */ protected void constantClass(DataInputStream in, int poolIndex) throws IOException { int class_index = in.readUnsignedShort(); intPool[poolIndex] = class_index; ClassConstant c = new ClassConstant(class_index); pool[poolIndex] = c; } /** * @param in * @throws IOException */ protected void constantDouble(DataInputStream in, int poolIndex) throws IOException { if (cd != null) pool[poolIndex] = in.readDouble(); else in.skipBytes(8); } /** * @param in * @throws IOException */ protected void constantLong(DataInputStream in, int poolIndex) throws IOException { if (cd != null) { pool[poolIndex] = in.readLong(); } else in.skipBytes(8); } /** * @param in * @param poolIndex * @throws IOException */ protected void constantUtf8(DataInputStream in, int poolIndex) throws IOException { // CONSTANT_Utf8 String name = in.readUTF(); pool[poolIndex] = name; } /** * Find a method reference in the pool that points to the given class, * methodname and descriptor. * * @param clazz * @param methodname * @param descriptor * @return index in constant pool */ private int findMethodReference(String clazz, String methodname, String descriptor) { for (int i = 1; i < pool.length; i++) { if (pool[i] instanceof Assoc) { Assoc methodref = (Assoc) pool[i]; if (methodref.tag == 10) { // Method ref int class_index = methodref.a; int class_name_index = intPool[class_index]; if (clazz.equals(pool[class_name_index])) { int name_and_type_index = methodref.b; Assoc name_and_type = (Assoc) pool[name_and_type_index]; if (name_and_type.tag == 12) { // Name and Type int name_index = name_and_type.a; int type_index = name_and_type.b; if (methodname.equals(pool[name_index])) { if (descriptor.equals(pool[type_index])) { return i; } } } } } } } return -1; } /** * Called for each attribute in the class, field, or method. * * @param in * The stream * @param access_flags * @throws Exception */ private void doAttributes(DataInputStream in, ElementType member, boolean crawl, int access_flags) throws Exception { int attributesCount = in.readUnsignedShort(); for (int j = 0; j < attributesCount; j++) { // skip name CONSTANT_Utf8 pointer doAttribute(in, member, crawl, access_flags); } } /** * Process a single attribute, if not recognized, skip it. * * @param in * the data stream * @param access_flags * @throws Exception */ private void doAttribute(DataInputStream in, ElementType member, boolean crawl, int access_flags) throws Exception { int attribute_name_index = in.readUnsignedShort(); String attributeName = (String) pool[attribute_name_index]; long attribute_length = in.readInt(); attribute_length &= 0xFFFFFFFF; if ("Deprecated".equals(attributeName)) { if (cd != null) cd.deprecated(); } else if ("RuntimeVisibleAnnotations".equals(attributeName)) doAnnotations(in, member, RetentionPolicy.RUNTIME, access_flags); else if ("RuntimeVisibleParameterAnnotations".equals(attributeName)) doParameterAnnotations(in, member, RetentionPolicy.RUNTIME, access_flags); else if ("RuntimeInvisibleAnnotations".equals(attributeName)) doAnnotations(in, member, RetentionPolicy.CLASS, access_flags); else if ("RuntimeInvisibleParameterAnnotations".equals(attributeName)) doParameterAnnotations(in, member, RetentionPolicy.CLASS, access_flags); else if ("InnerClasses".equals(attributeName)) doInnerClasses(in); else if ("EnclosingMethod".equals(attributeName)) doEnclosingMethod(in); else if ("SourceFile".equals(attributeName)) doSourceFile(in); else if ("Code".equals(attributeName) && crawl) doCode(in); else if ("Signature".equals(attributeName)) doSignature(in, member, access_flags); else if ("ConstantValue".equals(attributeName)) doConstantValue(in); else { if (attribute_length > 0x7FFFFFFF) { throw new IllegalArgumentException("Attribute > 2Gb"); } in.skipBytes((int) attribute_length); } } /** * <pre> * EnclosingMethod_attribute { * u2 attribute_name_index; * u4 attribute_length; * u2 class_index * u2 method_index; * } * </pre> * * @param in * @throws IOException */ private void doEnclosingMethod(DataInputStream in) throws IOException { int cIndex = in.readShort(); int mIndex = in.readShort(); if (cd != null) { int nameIndex = intPool[cIndex]; TypeRef cName = analyzer.getTypeRef((String) pool[nameIndex]); String mName = null; String mDescriptor = null; if (mIndex != 0) { Assoc nameAndType = (Assoc) pool[mIndex]; mName = (String) pool[nameAndType.a]; mDescriptor = (String) pool[nameAndType.b]; } cd.enclosingMethod(cName, mName, mDescriptor); } } /** * <pre> * InnerClasses_attribute { * u2 attribute_name_index; * u4 attribute_length; * u2 number_of_classes; { * u2 inner_class_info_index; * u2 outer_class_info_index; * u2 inner_name_index; * u2 inner_class_access_flags; * } classes[number_of_classes]; * } * </pre> * * @param in * @throws Exception */ private void doInnerClasses(DataInputStream in) throws Exception { int number_of_classes = in.readShort(); for (int i = 0; i < number_of_classes; i++) { int inner_class_info_index = in.readShort(); int outer_class_info_index = in.readShort(); int inner_name_index = in.readShort(); int inner_class_access_flags = in.readShort() & 0xFFFF; if (cd != null) { TypeRef innerClass = null; TypeRef outerClass = null; String innerName = null; if (inner_class_info_index != 0) { int nameIndex = intPool[inner_class_info_index]; innerClass = analyzer.getTypeRef((String) pool[nameIndex]); } if (outer_class_info_index != 0) { int nameIndex = intPool[outer_class_info_index]; outerClass = analyzer.getTypeRef((String) pool[nameIndex]); } if (inner_name_index != 0) innerName = (String) pool[inner_name_index]; cd.innerClass(innerClass, outerClass, innerName, inner_class_access_flags); } } } /** * Handle a signature * * <pre> * Signature_attribute { * u2 attribute_name_index; * u4 attribute_length; * u2 signature_index; * } * </pre> * * @param member * @param access_flags */ void doSignature(DataInputStream in, ElementType member, int access_flags) throws IOException { int signature_index = in.readUnsignedShort(); String signature = (String) pool[signature_index]; parseDescriptor(signature, access_flags); if (last != null) last.signature = signature; if (cd != null) cd.signature(signature); } /** * Handle a constant value call the data collector with it */ void doConstantValue(DataInputStream in) throws IOException { int constantValue_index = in.readUnsignedShort(); if (cd == null) return; Object object = pool[constantValue_index]; if (object == null) object = pool[intPool[constantValue_index]]; last.constant = object; cd.constant(object); } /** * <pre> * Code_attribute { * u2 attribute_name_index; * u4 attribute_length; * u2 max_stack; * u2 max_locals; * u4 code_length; * u1 code[code_length]; * u2 exception_table_length; * { u2 start_pc; * u2 end_pc; * u2 handler_pc; * u2 catch_type; * } exception_table[exception_table_length]; * u2 attributes_count; * attribute_info attributes[attributes_count]; * } * </pre> * * @param in * @param pool * @throws Exception */ private void doCode(DataInputStream in) throws Exception { /* int max_stack = */in.readUnsignedShort(); /* int max_locals = */in.readUnsignedShort(); int code_length = in.readInt(); byte code[] = new byte[code_length]; in.readFully(code); crawl(code); int exception_table_length = in.readUnsignedShort(); in.skipBytes(exception_table_length * 8); doAttributes(in, ElementType.METHOD, false, 0); } /** * We must find Class.forName references ... * * @param code */ protected void crawl(byte[] code) { ByteBuffer bb = ByteBuffer.wrap(code); bb.order(ByteOrder.BIG_ENDIAN); int lastReference = -1; while (bb.remaining() > 0) { int instruction = 0xFF & bb.get(); switch (instruction) { case OpCodes.ldc : lastReference = 0xFF & bb.get(); break; case OpCodes.ldc_w : lastReference = 0xFFFF & bb.getShort(); break; case OpCodes.invokespecial : { int mref = 0xFFFF & bb.getShort(); if (cd != null) getMethodDef(0, mref); break; } case OpCodes.invokevirtual : { int mref = 0xFFFF & bb.getShort(); if (cd != null) getMethodDef(0, mref); break; } case OpCodes.invokeinterface : { int mref = 0xFFFF & bb.getShort(); if (cd != null) getMethodDef(0, mref); break; } case OpCodes.invokestatic : { int methodref = 0xFFFF & bb.getShort(); if (cd != null) getMethodDef(0, methodref); if ((methodref == forName || methodref == class$) && lastReference != -1 && pool[intPool[lastReference]] instanceof String) { String fqn = (String) pool[intPool[lastReference]]; if (!fqn.equals("class") && fqn.indexOf('.') > 0) { TypeRef clazz = analyzer.getTypeRefFromFQN(fqn); referTo(clazz, 0); } lastReference = -1; } break; } case OpCodes.tableswitch : // Skip to place divisible by 4 while ((bb.position() & 0x3) != 0) bb.get(); /* int deflt = */ bb.getInt(); int low = bb.getInt(); int high = bb.getInt(); try { bb.position(bb.position() + (high - low + 1) * 4); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } lastReference = -1; break; case OpCodes.lookupswitch : // Skip to place divisible by 4 while ((bb.position() & 0x3) != 0) bb.get(); /* deflt = */ bb.getInt(); int npairs = bb.getInt(); bb.position(bb.position() + npairs * 8); lastReference = -1; break; default : lastReference = -1; bb.position(bb.position() + OpCodes.OFFSETS[instruction]); } } } private void doSourceFile(DataInputStream in) throws IOException { int sourcefile_index = in.readUnsignedShort(); this.sourceFile = pool[sourcefile_index].toString(); } private void doParameterAnnotations(DataInputStream in, ElementType member, RetentionPolicy policy, int access_flags) throws IOException { int num_parameters = in.readUnsignedByte(); for (int p = 0; p < num_parameters; p++) { if (cd != null) cd.parameter(p); doAnnotations(in, member, policy, access_flags); } } private void doAnnotations(DataInputStream in, ElementType member, RetentionPolicy policy, int access_flags) throws IOException { int num_annotations = in.readUnsignedShort(); // # of annotations for (int a = 0; a < num_annotations; a++) { if (cd == null) doAnnotation(in, member, policy, false, access_flags); else { Annotation annotion = doAnnotation(in, member, policy, true, access_flags); cd.annotation(annotion); } } } private Annotation doAnnotation(DataInputStream in, ElementType member, RetentionPolicy policy, boolean collect, int access_flags) throws IOException { int type_index = in.readUnsignedShort(); if (annotations == null) annotations = new HashSet<TypeRef>(); TypeRef tr = analyzer.getTypeRef(pool[type_index].toString()); annotations.add(tr); TypeRef name = analyzer.getTypeRef((String) pool[type_index]); if (policy == RetentionPolicy.RUNTIME) { referTo(type_index, 0); hasRuntimeAnnotations = true; if (api != null && (Modifier.isPublic(access_flags) || Modifier.isProtected(access_flags))) api.add(name.getPackageRef()); } else { hasClassAnnotations = true; } int num_element_value_pairs = in.readUnsignedShort(); Map<String,Object> elements = null; for (int v = 0; v < num_element_value_pairs; v++) { int element_name_index = in.readUnsignedShort(); String element = (String) pool[element_name_index]; Object value = doElementValue(in, member, policy, collect, access_flags); if (collect) { if (elements == null) elements = new LinkedHashMap<String,Object>(); elements.put(element, value); } } if (collect) return new Annotation(name, elements, member, policy); return null; } private Object doElementValue(DataInputStream in, ElementType member, RetentionPolicy policy, boolean collect, int access_flags) throws IOException { char tag = (char) in.readUnsignedByte(); switch (tag) { case 'B' : // Byte case 'C' : // Character case 'I' : // Integer case 'S' : // Short int const_value_index = in.readUnsignedShort(); return intPool[const_value_index]; case 'D' : // Double case 'F' : // Float case 's' : // String case 'J' : // Long const_value_index = in.readUnsignedShort(); return pool[const_value_index]; case 'Z' : // Boolean const_value_index = in.readUnsignedShort(); return pool[const_value_index] == null || pool[const_value_index].equals(0) ? false : true; case 'e' : // enum constant int type_name_index = in.readUnsignedShort(); if (policy == RetentionPolicy.RUNTIME) { referTo(type_name_index, 0); if (api != null && (Modifier.isPublic(access_flags) || Modifier.isProtected(access_flags))) { TypeRef name = analyzer.getTypeRef((String) pool[type_name_index]); api.add(name.getPackageRef()); } } int const_name_index = in.readUnsignedShort(); return pool[const_name_index]; case 'c' : // Class int class_info_index = in.readUnsignedShort(); if (policy == RetentionPolicy.RUNTIME) { referTo(class_info_index, 0); if (api != null && (Modifier.isPublic(access_flags) || Modifier.isProtected(access_flags))) { TypeRef name = analyzer.getTypeRef((String) pool[class_info_index]); api.add(name.getPackageRef()); } } return pool[class_info_index]; case '@' : // Annotation type return doAnnotation(in, member, policy, collect, access_flags); case '[' : // Array int num_values = in.readUnsignedShort(); Object[] result = new Object[num_values]; for (int i = 0; i < num_values; i++) { result[i] = doElementValue(in, member, policy, collect, access_flags); } return result; default : throw new IllegalArgumentException("Invalid value for Annotation ElementValue tag " + tag); } } /** * Add a new package reference. * * @param packageRef * A '.' delimited package name */ void referTo(TypeRef typeRef, int modifiers) { if (xref != null) xref.add(typeRef); if (typeRef.isPrimitive()) return; PackageRef packageRef = typeRef.getPackageRef(); if (packageRef.isPrimitivePackage()) return; imports.add(packageRef); if (api != null && (Modifier.isPublic(modifiers) || Modifier.isProtected(modifiers))) api.add(packageRef); if (cd != null) cd.referTo(typeRef, modifiers); } void referTo(int index, int modifiers) { String descriptor = (String) pool[index]; parseDescriptor(descriptor, modifiers); } /** * This method parses a descriptor and adds the package of the descriptor to * the referenced packages. The syntax of the descriptor is: * * <pre> * descriptor ::= ( '(' reference * ')' )? reference * reference ::= 'L' classname ( '&lt;' references '&gt;' )? ';' | 'B' | 'Z' | ... | '+' | '-' | '[' * </pre> * * This methods uses heavy recursion to parse the descriptor and a roving * pointer to limit the creation of string objects. * * @param descriptor * The to be parsed descriptor * @param rover * The pointer to start at */ public void parseDescriptor(String descriptor, int modifiers) { // Some descriptors are weird, they start with a generic // declaration that contains ':', not sure what they mean ... int rover = 0; if (descriptor.charAt(0) == '<') { rover = parseFormalTypeParameters(descriptor, rover, modifiers); } if (descriptor.charAt(rover) == '(') { rover = parseReferences(descriptor, rover + 1, ')', modifiers); rover++; } parseReferences(descriptor, rover, (char) 0, modifiers); } /** * Parse a sequence of references. A sequence ends with a given character or * when the string ends. * * @param descriptor * The whole descriptor. * @param rover * The index in the descriptor * @param delimiter * The end character or 0 * @return the last index processed, one character after the delimeter */ int parseReferences(String descriptor, int rover, char delimiter, int modifiers) { int r = rover; while (r < descriptor.length() && descriptor.charAt(r) != delimiter) { r = parseReference(descriptor, r, modifiers); } return r; } /** * Parse a single reference. This can be a single character or an object * reference when it starts with 'L'. * * @param descriptor * The descriptor * @param rover * The place to start * @return The return index after the reference */ int parseReference(String descriptor, int rover, int modifiers) { int r = rover; char c = descriptor.charAt(r); while (c == '[') c = descriptor.charAt(++r); if (c == '<') { r = parseReferences(descriptor, r + 1, '>', modifiers); } else if (c == 'T') { // Type variable name r++; while (descriptor.charAt(r) != ';') r++; } else if (c == 'L') { StringBuilder sb = new StringBuilder(); r++; while ((c = descriptor.charAt(r)) != ';') { if (c == '<') { r = parseReferences(descriptor, r + 1, '>', modifiers); } else sb.append(c); r++; } TypeRef ref = analyzer.getTypeRef(sb.toString()); if (cd != null) cd.addReference(ref); referTo(ref, modifiers); } else { if ("+-*BCDFIJSZV".indexOf(c) < 0) ;// System.err.println("Should not skip: " + c); } // this skips a lot of characters // [, *, +, -, B, etc. return r + 1; } /** * FormalTypeParameters * * @param descriptor * @param index * @return */ private int parseFormalTypeParameters(String descriptor, int index, int modifiers) { index++; while (descriptor.charAt(index) != '>') { // Skip IDENTIFIER index = descriptor.indexOf(':', index) + 1; if (index == 0) throw new IllegalArgumentException("Expected IDENTIFIER: " + descriptor); // ClassBound? InterfaceBounds char c = descriptor.charAt(index); // Class Bound? if (c == 'L' || c == 'T') { index = parseReference(descriptor, index, modifiers); // class // reference c = descriptor.charAt(index); } // Interface Bounds while (c == ':') { index++; index = parseReference(descriptor, index, modifiers); c = descriptor.charAt(index); } // for each interface } // for each formal parameter return index + 1; // skip > } public Set<PackageRef> getReferred() { return imports; } public String getAbsolutePath() { return path; } public String getSourceFile() { return sourceFile; } /** * .class construct for different compilers sun 1.1 Detect static variable * class$com$acme$MyClass 1.2 " 1.3 " 1.4 " 1.5 ldc_w (class) 1.6 " eclipse * 1.1 class$0, ldc (string), invokestatic Class.forName 1.2 " 1.3 " 1.5 ldc * (class) 1.6 " 1.5 and later is not an issue, sun pre 1.5 is easy to * detect the static variable that decodes the class name. For eclipse, the * class$0 gives away we have a reference encoded in a string. * compilerversions/compilerversions.jar contains test versions of all * versions/compilers. */ public void reset() { pool = null; intPool = null; xref = null; } public boolean is(QUERY query, Instruction instr, Analyzer analyzer) throws Exception { switch (query) { case ANY : return true; case NAMED : if (instr.matches(getClassName().getDottedOnly())) return !instr.isNegated(); return false; case VERSION : String v = major + "." + minor; if (instr.matches(v)) return !instr.isNegated(); return false; case IMPLEMENTS : for (int i = 0; interfaces != null && i < interfaces.length; i++) { if (instr.matches(interfaces[i].getDottedOnly())) return !instr.isNegated(); } break; case EXTENDS : if (zuper == null) return false; if (instr.matches(zuper.getDottedOnly())) return !instr.isNegated(); break; case PUBLIC : return Modifier.isPublic(accessx); case CONCRETE : return !Modifier.isAbstract(accessx); case ANNOTATED : if (annotations == null) return false; for (TypeRef annotation : annotations) { if (instr.matches(annotation.getFQN())) return !instr.isNegated(); } return false; case RUNTIMEANNOTATIONS : return hasRuntimeAnnotations; case CLASSANNOTATIONS : return hasClassAnnotations; case ABSTRACT : return Modifier.isAbstract(accessx); case IMPORTS : for (PackageRef imp : imports) { if (instr.matches(imp.getFQN())) return !instr.isNegated(); } } if (zuper == null) return false; Clazz clazz = analyzer.findClass(zuper); if (clazz == null) return false; return clazz.is(query, instr, analyzer); } public String toString() { return className.getFQN(); } /** * Called when crawling the byte code and a method reference is found */ void getMethodDef(int access, int methodRefPoolIndex) { if (methodRefPoolIndex == 0) return; Object o = pool[methodRefPoolIndex]; if (o != null && o instanceof Assoc) { Assoc assoc = (Assoc) o; if (assoc.tag == 10) { int string_index = intPool[assoc.a]; TypeRef className = analyzer.getTypeRef((String) pool[string_index]); int name_and_type_index = assoc.b; Assoc name_and_type = (Assoc) pool[name_and_type_index]; if (name_and_type.tag == 12) { // Name and Type int name_index = name_and_type.a; int type_index = name_and_type.b; String method = (String) pool[name_index]; String descriptor = (String) pool[type_index]; cd.referenceMethod(access, className, method, descriptor); } else throw new IllegalArgumentException( "Invalid class file (or parsing is wrong), assoc is not type + name (12)"); } else throw new IllegalArgumentException( "Invalid class file (or parsing is wrong), Assoc is not method ref! (10)"); } else throw new IllegalArgumentException("Invalid class file (or parsing is wrong), Not an assoc at a method ref"); } public boolean isPublic() { return Modifier.isPublic(accessx); } public boolean isProtected() { return Modifier.isProtected(accessx); } public boolean isEnum() { return zuper != null && zuper.getBinary().equals("java/lang/Enum"); } public JAVA getFormat() { return JAVA.format(major); } public static String objectDescriptorToFQN(String string) { if (string.startsWith("L") && string.endsWith(";")) return string.substring(1, string.length() - 1).replace('/', '.'); switch (string.charAt(0)) { case 'V' : return "void"; case 'B' : return "byte"; case 'C' : return "char"; case 'I' : return "int"; case 'S' : return "short"; case 'D' : return "double"; case 'F' : return "float"; case 'J' : return "long"; case 'Z' : return "boolean"; case '[' : // Array return objectDescriptorToFQN(string.substring(1)) + "[]"; } throw new IllegalArgumentException("Invalid type character in descriptor " + string); } public static String unCamel(String id) { StringBuilder out = new StringBuilder(); for (int i = 0; i < id.length(); i++) { char c = id.charAt(i); if (c == '_' || c == '$' || c == '.') { if (out.length() > 0 && !Character.isWhitespace(out.charAt(out.length() - 1))) out.append(' '); continue; } int n = i; while (n < id.length() && Character.isUpperCase(id.charAt(n))) { n++; } if (n == i) out.append(id.charAt(i)); else { boolean tolower = (n - i) == 1; if (i > 0 && !Character.isWhitespace(out.charAt(out.length() - 1))) out.append(' '); for (; i < n;) { if (tolower) out.append(Character.toLowerCase(id.charAt(i))); else out.append(id.charAt(i)); i++; } i } } if (id.startsWith(".")) out.append(" *"); out.replace(0, 1, Character.toUpperCase(out.charAt(0)) + ""); return out.toString(); } public boolean isInterface() { return Modifier.isInterface(accessx); } public boolean isAbstract() { return Modifier.isAbstract(accessx); } public int getAccess() { if (innerAccess == -1) return accessx; return innerAccess; } public TypeRef getClassName() { return className; } /** * To provide an enclosing instance * * @param access * @param name * @param descriptor * @return */ public MethodDef getMethodDef(int access, String name, String descriptor) { return new MethodDef(access, name, descriptor); } public TypeRef getSuper() { return zuper; } public String getFQN() { return className.getFQN(); } public TypeRef[] getInterfaces() { return interfaces; } public void setInnerAccess(int access) { innerAccess = access; } public boolean isFinal() { return Modifier.isFinal(accessx); } public void setDeprecated(boolean b) { deprecated = b; } public boolean isDeprecated() { return deprecated; } public boolean isAnnotation() { return (accessx & ACC_ANNOTATION) != 0; } public Set<PackageRef> getAPIUses() { if (api == null) return Collections.emptySet(); return api; } public Clazz.TypeDef getExtends(TypeRef type) { return new TypeDef(type, false); } public Clazz.TypeDef getImplements(TypeRef type) { return new TypeDef(type, true); } }
package aQute.bnd.osgi; import static aQute.bnd.classfile.ConstantPool.CONSTANT_Class; import static aQute.bnd.classfile.ConstantPool.CONSTANT_Fieldref; import static aQute.bnd.classfile.ConstantPool.CONSTANT_InterfaceMethodref; import static aQute.bnd.classfile.ConstantPool.CONSTANT_MethodType; import static aQute.bnd.classfile.ConstantPool.CONSTANT_Methodref; import static aQute.bnd.classfile.ConstantPool.CONSTANT_NameAndType; import static aQute.bnd.classfile.ConstantPool.CONSTANT_String; import static java.util.Collections.emptyList; import static java.util.Collections.emptyMap; import static java.util.Collections.emptySet; import static java.util.Objects.requireNonNull; import static java.util.stream.Collectors.toMap; import java.io.DataInput; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import java.lang.annotation.RetentionPolicy; import java.lang.reflect.Modifier; import java.nio.ByteBuffer; import java.util.ArrayDeque; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Deque; import java.util.EnumSet; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Properties; import java.util.Set; import java.util.Spliterator; import java.util.Spliterators.AbstractSpliterator; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Stream; import java.util.stream.StreamSupport; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import aQute.bnd.classfile.AnnotationDefaultAttribute; import aQute.bnd.classfile.AnnotationInfo; import aQute.bnd.classfile.AnnotationsAttribute; import aQute.bnd.classfile.Attribute; import aQute.bnd.classfile.BootstrapMethodsAttribute; import aQute.bnd.classfile.BootstrapMethodsAttribute.BootstrapMethod; import aQute.bnd.classfile.ClassFile; import aQute.bnd.classfile.CodeAttribute; import aQute.bnd.classfile.CodeAttribute.ExceptionHandler; import aQute.bnd.classfile.ConstantPool; import aQute.bnd.classfile.ConstantPool.AbstractRefInfo; import aQute.bnd.classfile.ConstantPool.MethodTypeInfo; import aQute.bnd.classfile.ConstantPool.NameAndTypeInfo; import aQute.bnd.classfile.ConstantValueAttribute; import aQute.bnd.classfile.DeprecatedAttribute; import aQute.bnd.classfile.ElementValueInfo; import aQute.bnd.classfile.ElementValueInfo.EnumConst; import aQute.bnd.classfile.ElementValueInfo.ResultConst; import aQute.bnd.classfile.EnclosingMethodAttribute; import aQute.bnd.classfile.ExceptionsAttribute; import aQute.bnd.classfile.FieldInfo; import aQute.bnd.classfile.InnerClassesAttribute; import aQute.bnd.classfile.InnerClassesAttribute.InnerClass; import aQute.bnd.classfile.MemberInfo; import aQute.bnd.classfile.MethodInfo; import aQute.bnd.classfile.MethodParametersAttribute; import aQute.bnd.classfile.ParameterAnnotationInfo; import aQute.bnd.classfile.ParameterAnnotationsAttribute; import aQute.bnd.classfile.RuntimeInvisibleAnnotationsAttribute; import aQute.bnd.classfile.RuntimeInvisibleParameterAnnotationsAttribute; import aQute.bnd.classfile.RuntimeInvisibleTypeAnnotationsAttribute; import aQute.bnd.classfile.RuntimeVisibleAnnotationsAttribute; import aQute.bnd.classfile.RuntimeVisibleParameterAnnotationsAttribute; import aQute.bnd.classfile.RuntimeVisibleTypeAnnotationsAttribute; import aQute.bnd.classfile.SignatureAttribute; import aQute.bnd.classfile.SourceFileAttribute; import aQute.bnd.classfile.StackMapTableAttribute; import aQute.bnd.classfile.StackMapTableAttribute.AppendFrame; import aQute.bnd.classfile.StackMapTableAttribute.FullFrame; import aQute.bnd.classfile.StackMapTableAttribute.ObjectVariableInfo; import aQute.bnd.classfile.StackMapTableAttribute.SameLocals1StackItemFrame; import aQute.bnd.classfile.StackMapTableAttribute.SameLocals1StackItemFrameExtended; import aQute.bnd.classfile.StackMapTableAttribute.StackMapFrame; import aQute.bnd.classfile.StackMapTableAttribute.VerificationTypeInfo; import aQute.bnd.classfile.TypeAnnotationInfo; import aQute.bnd.classfile.TypeAnnotationsAttribute; import aQute.bnd.osgi.Annotation.ElementType; import aQute.bnd.osgi.Descriptors.Descriptor; import aQute.bnd.osgi.Descriptors.PackageRef; import aQute.bnd.osgi.Descriptors.TypeRef; import aQute.bnd.signatures.FieldSignature; import aQute.bnd.signatures.MethodSignature; import aQute.bnd.signatures.Signature; import aQute.lib.exceptions.Exceptions; import aQute.lib.io.ByteBufferDataInput; import aQute.lib.utf8properties.UTF8Properties; import aQute.libg.generics.Create; import aQute.libg.glob.Glob; public class Clazz { private final static Logger logger = LoggerFactory.getLogger(Clazz.class); @Deprecated public class ClassConstant { final int cname; public boolean referred; public ClassConstant(int class_index) { this.cname = class_index; } public String getName() { return constantPool.utf8(cname); } @Override public String toString() { return "ClassConstant[" + getName() + "]"; } } public static enum JAVA { JDK1_1(45, "JRE-1.1", "(&(osgi.ee=JavaSE)(version=1.1))"), JDK1_2(46, "J2SE-1.2", "(&(osgi.ee=JavaSE)(version=1.2))"), JDK1_3(47, "J2SE-1.3", "(&(osgi.ee=JavaSE)(version=1.3))"), JDK1_4(48, "J2SE-1.4", "(&(osgi.ee=JavaSE)(version=1.4))"), J2SE5(49, "J2SE-1.5", "(&(osgi.ee=JavaSE)(version=1.5))"), J2SE6(50, "JavaSE-1.6", "(&(osgi.ee=JavaSE)(version=1.6))"), OpenJDK7(51, "JavaSE-1.7", "(&(osgi.ee=JavaSE)(version=1.7))"), OpenJDK8(52, "JavaSE-1.8", "(&(osgi.ee=JavaSE)(version=1.8))") { Map<String, Set<String>> profiles; @Override public Map<String, Set<String>> getProfiles() throws IOException { if (profiles == null) { Properties p = new UTF8Properties(); try (InputStream in = Clazz.class.getResourceAsStream("profiles-" + this + ".properties")) { p.load(in); } profiles = new HashMap<>(); for (Map.Entry<Object, Object> prop : p.entrySet()) { String list = (String) prop.getValue(); Set<String> set = new HashSet<>(); Collections.addAll(set, list.split("\\s*,\\s*")); profiles.put((String) prop.getKey(), set); } } return profiles; } }, OpenJDK9(53, "JavaSE-9", "(&(osgi.ee=JavaSE)(version=9))"), OpenJDK10(54, "JavaSE-10", "(&(osgi.ee=JavaSE)(version=10))"), OpenJDK11(55, "JavaSE-11", "(&(osgi.ee=JavaSE)(version=11))"), UNKNOWN(Integer.MAX_VALUE, "<UNKNOWN>", "(osgi.ee=UNKNOWN)"); final int major; final String ee; final String filter; JAVA(int major, String ee, String filter) { this.major = major; this.ee = ee; this.filter = filter; } static JAVA format(int n) { for (JAVA e : JAVA.values()) if (e.major == n) return e; return UNKNOWN; } public int getMajor() { return major; } public boolean hasAnnotations() { return major >= J2SE5.major; } public boolean hasGenerics() { return major >= J2SE5.major; } public boolean hasEnums() { return major >= J2SE5.major; } public static JAVA getJava(int major, @SuppressWarnings("unused") int minor) { for (JAVA j : JAVA.values()) { if (j.major == major) return j; } return UNKNOWN; } public String getEE() { return ee; } public String getFilter() { return filter; } public Map<String, Set<String>> getProfiles() throws IOException { return null; } } public static enum QUERY { IMPLEMENTS, EXTENDS, IMPORTS, NAMED, ANY, VERSION, CONCRETE, ABSTRACT, PUBLIC, ANNOTATED, INDIRECTLY_ANNOTATED, HIERARCHY_ANNOTATED, HIERARCHY_INDIRECTLY_ANNOTATED, RUNTIMEANNOTATIONS, CLASSANNOTATIONS, DEFAULT_CONSTRUCTOR; } public final static EnumSet<QUERY> HAS_ARGUMENT = EnumSet.of(QUERY.IMPLEMENTS, QUERY.EXTENDS, QUERY.IMPORTS, QUERY.NAMED, QUERY.VERSION, QUERY.ANNOTATED, QUERY.INDIRECTLY_ANNOTATED, QUERY.HIERARCHY_ANNOTATED, QUERY.HIERARCHY_INDIRECTLY_ANNOTATED); final static int ACC_SYNTHETIC = 0x1000; final static int ACC_BRIDGE = 0x0040; final static int ACC_ANNOTATION = 0x2000; final static int ACC_ENUM = 0x4000; final static int ACC_MODULE = 0x8000; @Deprecated static protected class Assoc { private Assoc() {} } public abstract class Def { final int access; public Def(int access) { this.access = access; } public int getAccess() { return access; } public boolean isEnum() { return (access & ACC_ENUM) != 0; } public boolean isPublic() { return Modifier.isPublic(access); } public boolean isAbstract() { return Modifier.isAbstract(access); } public boolean isProtected() { return Modifier.isProtected(access); } public boolean isFinal() { return Modifier.isFinal(access); } public boolean isStatic() { return Modifier.isStatic(access); } public boolean isPrivate() { return Modifier.isPrivate(access); } public boolean isNative() { return Modifier.isNative(access); } public boolean isTransient() { return Modifier.isTransient(access); } public boolean isVolatile() { return Modifier.isVolatile(access); } public boolean isInterface() { return Modifier.isInterface(access); } public boolean isSynthetic() { return (access & ACC_SYNTHETIC) != 0; } public boolean isModule() { return Clazz.isModule(access); } public boolean isAnnotation() { return Clazz.isAnnotation(access); } @Deprecated public Collection<TypeRef> getAnnotations() { return null; } public TypeRef getOwnerType() { return classDef.getType(); } public abstract String getName(); public abstract TypeRef getType(); public abstract TypeRef[] getPrototype(); public Object getClazz() { return Clazz.this; } } abstract class ElementDef extends Def { final Attribute[] attributes; ElementDef(int access, Attribute[] attributes) { super(access); this.attributes = attributes; } public boolean isDeprecated() { return attribute(DeprecatedAttribute.class).isPresent() || annotationInfos(RuntimeVisibleAnnotationsAttribute.class) .anyMatch(a -> a.type.equals("Ljava/lang/Deprecated;")); } public String getSignature() { return attribute(SignatureAttribute.class).map(a -> a.signature) .orElse(null); } <A extends Attribute> Stream<A> attributes(Class<A> attributeType) { @SuppressWarnings("unchecked") Stream<A> stream = (Stream<A>) Arrays.stream(attributes) .filter(attributeType::isInstance); return stream; } <A extends Attribute> Optional<A> attribute(Class<A> attributeType) { return attributes(attributeType).findFirst(); } <A extends AnnotationsAttribute> Stream<AnnotationInfo> annotationInfos(Class<A> attributeType) { return attributes(attributeType).flatMap(a -> Arrays.stream(a.annotations)); } public Stream<Annotation> annotations(String binaryNameFilter) { Predicate<AnnotationInfo> matches = matches(binaryNameFilter); ElementType elementType = elementType(); Stream<Annotation> runtimeAnnotations = annotationInfos(RuntimeVisibleAnnotationsAttribute.class) .filter(matches) .map(a -> newAnnotation(a, elementType, RetentionPolicy.RUNTIME, access)); Stream<Annotation> classAnnotations = annotationInfos(RuntimeInvisibleAnnotationsAttribute.class) .filter(matches) .map(a -> newAnnotation(a, elementType, RetentionPolicy.CLASS, access)); return Stream.concat(runtimeAnnotations, classAnnotations); } Predicate<AnnotationInfo> matches(String binaryNameFilter) { if ((binaryNameFilter == null) || binaryNameFilter.equals("*")) { return annotationInfo -> true; } Glob glob = new Glob("L{" + binaryNameFilter + "};"); return annotationInfo -> glob.matches(annotationInfo.type); } <A extends TypeAnnotationsAttribute> Stream<TypeAnnotationInfo> typeAnnotationInfos(Class<A> attributeType) { return attributes(attributeType).flatMap(a -> Arrays.stream(a.type_annotations)); } public Stream<TypeAnnotation> typeAnnotations(String binaryNameFilter) { Predicate<AnnotationInfo> matches = matches(binaryNameFilter); ElementType elementType = elementType(); Stream<TypeAnnotation> runtimeTypeAnnotations = typeAnnotationInfos( RuntimeVisibleTypeAnnotationsAttribute.class).filter(matches) .map(a -> newTypeAnnotation(a, elementType, RetentionPolicy.RUNTIME, access)); Stream<TypeAnnotation> classTypeAnnotations = typeAnnotationInfos( RuntimeInvisibleTypeAnnotationsAttribute.class).filter(matches) .map(a -> newTypeAnnotation(a, elementType, RetentionPolicy.CLASS, access)); return Stream.concat(runtimeTypeAnnotations, classTypeAnnotations); } @Override public String getName() { return super.toString(); } @Override public TypeRef getType() { return null; } @Override public TypeRef[] getPrototype() { return null; } @Override public String toString() { return getName(); } abstract ElementType elementType(); } class CodeDef extends ElementDef { private final ElementType elementType; CodeDef(CodeAttribute code, ElementType elementType) { super(0, code.attributes); this.elementType = elementType; } @Override ElementType elementType() { return elementType; } @Override public boolean isDeprecated() { return false; } } class ClassDef extends ElementDef { private final TypeRef type; ClassDef(ClassFile classFile) { super(classFile.access, classFile.attributes); type = analyzer.getTypeRef(classFile.this_class); } String getSourceFile() { return attribute(SourceFileAttribute.class).map(a -> a.sourcefile) .orElse(null); } boolean isInnerClass() { String binary = type.getBinary(); return attributes(InnerClassesAttribute.class).flatMap(a -> Arrays.stream(a.classes)) .anyMatch(inner -> !Modifier.isStatic(inner.inner_access) && inner.inner_class.equals(binary)); } @Override public String getName() { return type.getFQN(); } @Override public TypeRef getType() { return type; } @Override ElementType elementType() { if (isAnnotation()) { return ElementType.ANNOTATION_TYPE; } if (isModule()) { return ElementType.MODULE; } return type.getBinary() .endsWith("/package-info") ? ElementType.PACKAGE : ElementType.TYPE; } } public class FieldDef extends ElementDef { final String name; final Descriptor descriptor; @Deprecated public FieldDef(int access, String name, String descriptor) { super(access, new Attribute[0]); this.name = name; this.descriptor = analyzer.getDescriptor(descriptor); } FieldDef(MemberInfo memberInfo) { super(memberInfo.access, memberInfo.attributes); this.name = memberInfo.name; this.descriptor = analyzer.getDescriptor(memberInfo.descriptor); } @Override public boolean isFinal() { return super.isFinal() || Modifier.isFinal(classDef.getAccess()); } @Override public String getName() { return name; } @Override public TypeRef getType() { return descriptor.getType(); } @Deprecated public void setDeprecated(boolean deprecated) {} public TypeRef getContainingClass() { return getClassName(); } public Descriptor getDescriptor() { return descriptor; } @Deprecated public void setConstant(Object o) {} public Object getConstant() { return attribute(ConstantValueAttribute.class).map(a -> a.value) .orElse(null); } public String getGenericReturnType() { String signature = getSignature(); FieldSignature sig = analyzer.getFieldSignature((signature != null) ? signature : descriptor.toString()); return sig.type.toString(); } @Override public TypeRef[] getPrototype() { return null; } @Override ElementType elementType() { return ElementType.FIELD; } } public static class MethodParameter { private final MethodParametersAttribute.MethodParameter methodParameter; MethodParameter(MethodParametersAttribute.MethodParameter methodParameter) { this.methodParameter = methodParameter; } public String getName() { return methodParameter.name; } public int getAccess() { return methodParameter.access_flags; } @Override public String toString() { return getName(); } static MethodParameter[] parameters(MethodParametersAttribute attribute) { int parameters_count = attribute.parameters.length; MethodParameter[] parameters = new MethodParameter[parameters_count]; for (int i = 0; i < parameters_count; i++) { parameters[i] = new MethodParameter(attribute.parameters[i]); } return parameters; } } public class MethodDef extends FieldDef { @Deprecated public MethodDef(int access, String method, String descriptor) { super(access, method, descriptor); } public MethodDef(MethodInfo methodInfo) { super(methodInfo); } public boolean isConstructor() { return name.equals("<init>") || name.equals("<clinit>"); } @Override public TypeRef[] getPrototype() { return descriptor.getPrototype(); } public boolean isBridge() { return (access & ACC_BRIDGE) != 0; } @Override public String getGenericReturnType() { String signature = getSignature(); MethodSignature sig = analyzer.getMethodSignature((signature != null) ? signature : descriptor.toString()); return sig.resultType.toString(); } public MethodParameter[] getParameters() { return attribute(MethodParametersAttribute.class).map(MethodParameter::parameters) .orElseGet(() -> new MethodParameter[0]); } @Override public Object getConstant() { return attribute(AnnotationDefaultAttribute.class).map(a -> annotationDefault(a, access)) .orElse(null); } <A extends ParameterAnnotationsAttribute> Stream<ParameterAnnotationInfo> parameterAnnotationInfos( Class<A> attributeType) { return attributes(attributeType).flatMap(a -> Arrays.stream(a.parameter_annotations)); } public Stream<ParameterAnnotation> parameterAnnotations(String binaryNameFilter) { Predicate<AnnotationInfo> matches = matches(binaryNameFilter); ElementType elementType = elementType(); Stream<ParameterAnnotation> runtimeParameterAnnotations = parameterAnnotationInfos( RuntimeVisibleParameterAnnotationsAttribute.class) .flatMap(a -> parameterAnnotations(a, matches, elementType, RetentionPolicy.RUNTIME)); Stream<ParameterAnnotation> classParameterAnnotations = parameterAnnotationInfos( RuntimeInvisibleParameterAnnotationsAttribute.class) .flatMap(a -> parameterAnnotations(a, matches, elementType, RetentionPolicy.CLASS)); return Stream.concat(runtimeParameterAnnotations, classParameterAnnotations); } private Stream<ParameterAnnotation> parameterAnnotations(ParameterAnnotationInfo parameterAnnotationInfo, Predicate<AnnotationInfo> matches, ElementType elementType, RetentionPolicy policy) { int parameter = parameterAnnotationInfo.parameter; return Arrays.stream(parameterAnnotationInfo.annotations) .filter(matches) .map(a -> newParameterAnnotation(parameter, a, elementType, policy, access)); } /** * We must also look in the method's Code attribute for type * annotations. */ @Override <A extends TypeAnnotationsAttribute> Stream<TypeAnnotationInfo> typeAnnotationInfos(Class<A> attributeType) { ElementType elementType = elementType(); Stream<A> methodAttributes = attributes(attributeType); Stream<A> codeAttributes = attribute(CodeAttribute.class) .map(code -> new CodeDef(code, elementType).attributes(attributeType)) .orElseGet(Stream::empty); return Stream.concat(methodAttributes, codeAttributes) .flatMap(a -> Arrays.stream(a.type_annotations)); } @Override ElementType elementType() { return name.equals("<init>") ? ElementType.CONSTRUCTOR : ElementType.METHOD; } } public class TypeDef extends Def { final TypeRef type; final boolean interf; public TypeDef(TypeRef type, boolean interf) { super(Modifier.PUBLIC); this.type = type; this.interf = interf; } public TypeRef getReference() { return type; } public boolean getImplements() { return interf; } @Override public String getName() { if (interf) return "<implements>"; return "<extends>"; } @Override public TypeRef getType() { return type; } @Override public TypeRef[] getPrototype() { return null; } } public static final Comparator<Clazz> NAME_COMPARATOR = (Clazz a, Clazz b) -> a.classDef.getType() .compareTo(b.classDef.getType()); private boolean hasRuntimeAnnotations; private boolean hasClassAnnotations; private boolean hasDefaultConstructor; private Set<PackageRef> imports = Create.set(); private Set<TypeRef> xref = new HashSet<>(); private Set<TypeRef> annotations; private int forName = 0; private int class$ = 0; private Set<PackageRef> api; private ClassFile classFile = null; private ConstantPool constantPool = null; TypeRef superClass; private TypeRef[] interfaces; ClassDef classDef; private Map<TypeRef, Integer> referred = null; final Analyzer analyzer; final String path; final Resource resource; public static final int TYPEUSE_INDEX_NONE = TypeAnnotationInfo.TYPEUSE_INDEX_NONE; public static final int TYPEUSE_TARGET_INDEX_EXTENDS = TypeAnnotationInfo.TYPEUSE_TARGET_INDEX_EXTENDS; public Clazz(Analyzer analyzer, String path, Resource resource) { this.path = path; this.resource = resource; this.analyzer = analyzer; } public Set<TypeRef> parseClassFile() throws Exception { return parseClassFileWithCollector(null); } public Set<TypeRef> parseClassFile(InputStream in) throws Exception { return parseClassFile(in, null); } public Set<TypeRef> parseClassFileWithCollector(ClassDataCollector cd) throws Exception { ByteBuffer bb = resource.buffer(); if (bb != null) { return parseClassFileData(ByteBufferDataInput.wrap(bb), cd); } return parseClassFile(resource.openInputStream(), cd); } public Set<TypeRef> parseClassFile(InputStream in, ClassDataCollector cd) throws Exception { try (DataInputStream din = new DataInputStream(in)) { return parseClassFileData(din, cd); } } private Set<TypeRef> parseClassFileData(DataInput in, ClassDataCollector cd) throws Exception { Set<TypeRef> xref = parseClassFileData(in); visitClassFile(cd); return xref; } private synchronized Set<TypeRef> parseClassFileData(DataInput in) throws Exception { if (classFile != null) { return xref; } logger.debug("parseClassFile(): path={} resource={}", path, resource); classFile = ClassFile.parseClassFile(in); classDef = new ClassDef(classFile); constantPool = classFile.constant_pool; referred = new HashMap<>(constantPool.size()); if (classDef.isPublic()) { api = new HashSet<>(); } if (!classDef.isModule()) { referTo(classDef.getType(), Modifier.PUBLIC); } String superName = classFile.super_class; if (superName == null) { if (!(classDef.getType() .isObject() || classDef.isModule())) { throw new IOException("Class does not have a super class and is not java.lang.Object or module-info"); } } else { superClass = analyzer.getTypeRef(superName); referTo(superClass, classFile.access); } int interfaces_count = classFile.interfaces.length; if (interfaces_count > 0) { interfaces = new TypeRef[interfaces_count]; for (int i = 0; i < interfaces_count; i++) { interfaces[i] = analyzer.getTypeRef(classFile.interfaces[i]); referTo(interfaces[i], classFile.access); } } // All name&type and class constant records contain descriptors we // must treat as references, though not API int constant_pool_count = constantPool.size(); for (int i = 1; i < constant_pool_count; i++) { switch (constantPool.tag(i)) { case CONSTANT_Fieldref : case CONSTANT_Methodref : case CONSTANT_InterfaceMethodref : { AbstractRefInfo info = constantPool.entry(i); classConstRef(constantPool.className(info.class_index)); break; } case CONSTANT_NameAndType : { NameAndTypeInfo info = constantPool.entry(i); referTo(constantPool.utf8(info.descriptor_index), 0); break; } case CONSTANT_MethodType : { MethodTypeInfo info = constantPool.entry(i); referTo(constantPool.utf8(info.descriptor_index), 0); break; } default : break; } } for (FieldInfo fieldInfo : classFile.fields) { referTo(fieldInfo.descriptor, fieldInfo.access); processAttributes(fieldInfo.attributes, elementType(fieldInfo), fieldInfo.access); } /* * We crawl the code to find the ldc(_w) <string constant> invokestatic * Class.forName if so, calculate the method ref index so we can do this * efficiently */ forName = findMethodReference("java/lang/Class", "forName", "(Ljava/lang/String;)Ljava/lang/Class;"); class$ = findMethodReference(classDef.getType() .getBinary(), "class$", "(Ljava/lang/String;)Ljava/lang/Class;"); for (MethodInfo methodInfo : classFile.methods) { referTo(methodInfo.descriptor, methodInfo.access); ElementType elementType = elementType(methodInfo); if ((elementType == ElementType.CONSTRUCTOR) && Modifier.isPublic(methodInfo.access) && methodInfo.descriptor.equals("()V")) { hasDefaultConstructor = true; } processAttributes(methodInfo.attributes, elementType, methodInfo.access); } processAttributes(classFile.attributes, elementType(classFile), classFile.access); return xref; } private void visitClassFile(ClassDataCollector cd) throws Exception { if (cd == null) { return; } logger.debug("visitClassFile(): path={} resource={}", path, resource); if (!cd.classStart(this)) { return; } try { cd.version(classFile.minor_version, classFile.major_version); if (superClass != null) { cd.extendsClass(superClass); } if (interfaces != null) { cd.implementsInterfaces(interfaces); } referred.forEach((typeRef, access) -> { cd.addReference(typeRef); cd.referTo(typeRef, access.intValue()); }); for (FieldInfo fieldInfo : classFile.fields) { FieldDef fieldDef = new FieldDef(fieldInfo); cd.field(fieldDef); visitAttributes(cd, fieldDef); } for (MethodInfo methodInfo : classFile.methods) { MethodDef methodDef = new MethodDef(methodInfo); cd.method(methodDef); visitAttributes(cd, methodDef); } cd.memberEnd(); visitAttributes(cd, classDef); } finally { cd.classEnd(); } } public Stream<FieldDef> fields() { return Arrays.stream(classFile.fields) .map(FieldDef::new); } public Stream<MethodDef> methods() { return Arrays.stream(classFile.methods) .map(MethodDef::new); } /** * Find a method reference in the pool that points to the given class, * methodname and descriptor. * * @param clazz * @param methodname * @param descriptor * @return index in constant pool */ private int findMethodReference(String clazz, String methodname, String descriptor) { int constant_pool_count = constantPool.size(); for (int i = 1; i < constant_pool_count; i++) { switch (constantPool.tag(i)) { case CONSTANT_Methodref : case CONSTANT_InterfaceMethodref : AbstractRefInfo refInfo = constantPool.entry(i); if (clazz.equals(constantPool.className(refInfo.class_index))) { NameAndTypeInfo nameAndTypeInfo = constantPool.entry(refInfo.name_and_type_index); if (methodname.equals(constantPool.utf8(nameAndTypeInfo.name_index)) && descriptor.equals(constantPool.utf8(nameAndTypeInfo.descriptor_index))) { return i; } } } } return -1; } /** * Called for the attributes in the class, field, method or Code attribute. */ private void processAttributes(Attribute[] attributes, ElementType elementType, int access_flags) { for (Attribute attribute : attributes) { switch (attribute.name()) { case RuntimeVisibleAnnotationsAttribute.NAME : processAnnotations((AnnotationsAttribute) attribute, elementType, RetentionPolicy.RUNTIME, access_flags); break; case RuntimeInvisibleAnnotationsAttribute.NAME : processAnnotations((AnnotationsAttribute) attribute, elementType, RetentionPolicy.CLASS, access_flags); break; case RuntimeVisibleParameterAnnotationsAttribute.NAME : processParameterAnnotations((ParameterAnnotationsAttribute) attribute, ElementType.PARAMETER, RetentionPolicy.RUNTIME, access_flags); break; case RuntimeInvisibleParameterAnnotationsAttribute.NAME : processParameterAnnotations((ParameterAnnotationsAttribute) attribute, ElementType.PARAMETER, RetentionPolicy.CLASS, access_flags); break; case RuntimeVisibleTypeAnnotationsAttribute.NAME : processTypeAnnotations((TypeAnnotationsAttribute) attribute, ElementType.TYPE_USE, RetentionPolicy.RUNTIME, access_flags); break; case RuntimeInvisibleTypeAnnotationsAttribute.NAME : processTypeAnnotations((TypeAnnotationsAttribute) attribute, ElementType.TYPE_USE, RetentionPolicy.CLASS, access_flags); break; case EnclosingMethodAttribute.NAME : processEnclosingMethod((EnclosingMethodAttribute) attribute); break; case CodeAttribute.NAME : processCode((CodeAttribute) attribute, elementType); break; case SignatureAttribute.NAME : processSignature((SignatureAttribute) attribute, elementType, access_flags); break; case AnnotationDefaultAttribute.NAME : processAnnotationDefault((AnnotationDefaultAttribute) attribute, elementType, access_flags); break; case ExceptionsAttribute.NAME : processExceptions((ExceptionsAttribute) attribute, access_flags); break; case BootstrapMethodsAttribute.NAME : processBootstrapMethods((BootstrapMethodsAttribute) attribute); break; case StackMapTableAttribute.NAME : processStackMapTable((StackMapTableAttribute) attribute); break; default : break; } } } /** * Called for the attributes in the class, field, or method. */ private void visitAttributes(ClassDataCollector cd, ElementDef elementDef) throws Exception { int access_flags = elementDef.getAccess(); ElementType elementType = elementDef.elementType(); if (elementDef.isDeprecated()) { cd.deprecated(); } for (Attribute attribute : elementDef.attributes) { switch (attribute.name()) { case RuntimeVisibleAnnotationsAttribute.NAME : visitAnnotations(cd, (AnnotationsAttribute) attribute, elementType, RetentionPolicy.RUNTIME, access_flags); break; case RuntimeInvisibleAnnotationsAttribute.NAME : visitAnnotations(cd, (AnnotationsAttribute) attribute, elementType, RetentionPolicy.CLASS, access_flags); break; case RuntimeVisibleParameterAnnotationsAttribute.NAME : visitParameterAnnotations(cd, (ParameterAnnotationsAttribute) attribute, ElementType.PARAMETER, RetentionPolicy.RUNTIME, access_flags); break; case RuntimeInvisibleParameterAnnotationsAttribute.NAME : visitParameterAnnotations(cd, (ParameterAnnotationsAttribute) attribute, ElementType.PARAMETER, RetentionPolicy.CLASS, access_flags); break; case RuntimeVisibleTypeAnnotationsAttribute.NAME : visitTypeAnnotations(cd, (TypeAnnotationsAttribute) attribute, ElementType.TYPE_USE, RetentionPolicy.RUNTIME, access_flags); break; case RuntimeInvisibleTypeAnnotationsAttribute.NAME : visitTypeAnnotations(cd, (TypeAnnotationsAttribute) attribute, ElementType.TYPE_USE, RetentionPolicy.CLASS, access_flags); break; case InnerClassesAttribute.NAME : visitInnerClasses(cd, (InnerClassesAttribute) attribute); break; case EnclosingMethodAttribute.NAME : visitEnclosingMethod(cd, (EnclosingMethodAttribute) attribute); break; case CodeAttribute.NAME : visitCode(cd, (CodeAttribute) attribute, elementType); break; case SignatureAttribute.NAME : visitSignature(cd, (SignatureAttribute) attribute); break; case ConstantValueAttribute.NAME : visitConstantValue(cd, (ConstantValueAttribute) attribute); break; case AnnotationDefaultAttribute.NAME : visitAnnotationDefault(cd, (AnnotationDefaultAttribute) attribute, elementDef); break; case MethodParametersAttribute.NAME : visitMethodParameters(cd, (MethodParametersAttribute) attribute, elementDef); break; default : break; } } } private void processEnclosingMethod(EnclosingMethodAttribute attribute) { classConstRef(attribute.class_name); } private void visitEnclosingMethod(ClassDataCollector cd, EnclosingMethodAttribute attribute) { TypeRef cName = analyzer.getTypeRef(attribute.class_name); cd.enclosingMethod(cName, attribute.method_name, attribute.method_descriptor); } private void visitInnerClasses(ClassDataCollector cd, InnerClassesAttribute attribute) throws Exception { for (InnerClass innerClassInfo : attribute.classes) { TypeRef innerClass = analyzer.getTypeRef(innerClassInfo.inner_class); TypeRef outerClass; String outerClassName = innerClassInfo.outer_class; if (outerClassName != null) { outerClass = analyzer.getTypeRef(outerClassName); } else { outerClass = null; } cd.innerClass(innerClass, outerClass, innerClassInfo.inner_name, innerClassInfo.inner_access); } } private void processSignature(SignatureAttribute attribute, ElementType elementType, int access_flags) { String signature = attribute.signature; Signature sig; switch (elementType) { case ANNOTATION_TYPE : case TYPE : case PACKAGE : sig = analyzer.getClassSignature(signature); break; case FIELD : sig = analyzer.getFieldSignature(signature); break; case CONSTRUCTOR : case METHOD : sig = analyzer.getMethodSignature(signature); break; default : throw new IllegalArgumentException( "Signature \"" + signature + "\" found for unknown element type: " + elementType); } Set<String> binaryRefs = sig.erasedBinaryReferences(); for (String binary : binaryRefs) { TypeRef ref = analyzer.getTypeRef(binary); referTo(ref, access_flags); } } private void visitSignature(ClassDataCollector cd, SignatureAttribute attribute) { String signature = attribute.signature; cd.signature(signature); } private void processAnnotationDefault(AnnotationDefaultAttribute attribute, ElementType elementType, int access_flags) { Object value = attribute.value; processElementValue(value, elementType, RetentionPolicy.RUNTIME, access_flags); } private void visitAnnotationDefault(ClassDataCollector cd, AnnotationDefaultAttribute attribute, ElementDef elementDef) { MethodDef methodDef = (MethodDef) elementDef; Object value = annotationDefault(attribute, methodDef.getAccess()); cd.annotationDefault(methodDef, value); } static ElementType elementType(FieldInfo fieldInfo) { return ElementType.FIELD; } static ElementType elementType(MethodInfo methodInfo) { return methodInfo.name.equals("<init>") ? ElementType.CONSTRUCTOR : ElementType.METHOD; } static ElementType elementType(ClassFile classFile) { if (isAnnotation(classFile.access)) { return ElementType.ANNOTATION_TYPE; } if (isModule(classFile.access)) { return ElementType.MODULE; } return classFile.this_class.endsWith("/package-info") ? ElementType.PACKAGE : ElementType.TYPE; } Object annotationDefault(AnnotationDefaultAttribute attribute, int access_flags) { try { return newElementValue(attribute.value, ElementType.METHOD, RetentionPolicy.RUNTIME, access_flags); } catch (Exception e) { throw Exceptions.duck(e); } } private void visitConstantValue(ClassDataCollector cd, ConstantValueAttribute attribute) { Object value = attribute.value; cd.constant(value); } private void processExceptions(ExceptionsAttribute attribute, int access_flags) { for (String exception : attribute.exceptions) { TypeRef clazz = analyzer.getTypeRef(exception); referTo(clazz, access_flags); } } private void visitMethodParameters(ClassDataCollector cd, MethodParametersAttribute attribute, ElementDef elementDef) { MethodDef method = (MethodDef) elementDef; cd.methodParameters(method, MethodParameter.parameters(attribute)); } private void processCode(CodeAttribute attribute, ElementType elementType) { ByteBuffer code = attribute.code.duplicate(); code.rewind(); int lastReference = -1; while (code.hasRemaining()) { int instruction = Byte.toUnsignedInt(code.get()); switch (instruction) { case OpCodes.ldc : { lastReference = Byte.toUnsignedInt(code.get()); classConstRef(lastReference); break; } case OpCodes.ldc_w : { lastReference = Short.toUnsignedInt(code.getShort()); classConstRef(lastReference); break; } case OpCodes.anewarray : case OpCodes.checkcast : case OpCodes.instanceof_ : case OpCodes.new_ : { int class_index = Short.toUnsignedInt(code.getShort()); classConstRef(class_index); lastReference = -1; break; } case OpCodes.multianewarray : { int class_index = Short.toUnsignedInt(code.getShort()); classConstRef(class_index); code.get(); lastReference = -1; break; } case OpCodes.invokestatic : { int method_ref_index = Short.toUnsignedInt(code.getShort()); if ((method_ref_index == forName || method_ref_index == class$) && lastReference != -1) { if (constantPool.tag(lastReference) == CONSTANT_String) { String fqn = constantPool.string(lastReference); if (!fqn.equals("class") && fqn.indexOf('.') > 0) { TypeRef typeRef = analyzer.getTypeRefFromFQN(fqn); referTo(typeRef, 0); } } } lastReference = -1; break; } case OpCodes.wide : { int opcode = Byte.toUnsignedInt(code.get()); code.position(code.position() + (opcode == OpCodes.iinc ? 4 : 2)); lastReference = -1; break; } case OpCodes.tableswitch : { // Skip to place divisible by 4 int rem = code.position() % 4; if (rem != 0) { code.position(code.position() + 4 - rem); } int deflt = code.getInt(); int low = code.getInt(); int high = code.getInt(); code.position(code.position() + (high - low + 1) * 4); lastReference = -1; break; } case OpCodes.lookupswitch : { // Skip to place divisible by 4 int rem = code.position() % 4; if (rem != 0) { code.position(code.position() + 4 - rem); } int deflt = code.getInt(); int npairs = code.getInt(); code.position(code.position() + npairs * 8); lastReference = -1; break; } default : { code.position(code.position() + OpCodes.OFFSETS[instruction]); lastReference = -1; break; } } } for (ExceptionHandler exceptionHandler : attribute.exception_table) { classConstRef(exceptionHandler.catch_type); } processAttributes(attribute.attributes, elementType, 0); } private void visitCode(ClassDataCollector cd, CodeAttribute attribute, ElementType elementType) throws Exception { ByteBuffer code = attribute.code.duplicate(); code.rewind(); while (code.hasRemaining()) { int instruction = Byte.toUnsignedInt(code.get()); switch (instruction) { case OpCodes.invokespecial : { int method_ref_index = Short.toUnsignedInt(code.getShort()); visitReferenceMethod(cd, method_ref_index); break; } case OpCodes.invokevirtual : { int method_ref_index = Short.toUnsignedInt(code.getShort()); visitReferenceMethod(cd, method_ref_index); break; } case OpCodes.invokeinterface : { int method_ref_index = Short.toUnsignedInt(code.getShort()); visitReferenceMethod(cd, method_ref_index); code.position(code.position() + 2); break; } case OpCodes.invokestatic : { int method_ref_index = Short.toUnsignedInt(code.getShort()); visitReferenceMethod(cd, method_ref_index); break; } case OpCodes.wide : { int opcode = Byte.toUnsignedInt(code.get()); code.position(code.position() + (opcode == OpCodes.iinc ? 4 : 2)); break; } case OpCodes.tableswitch : { // Skip to place divisible by 4 int rem = code.position() % 4; if (rem != 0) { code.position(code.position() + 4 - rem); } int deflt = code.getInt(); int low = code.getInt(); int high = code.getInt(); code.position(code.position() + (high - low + 1) * 4); break; } case OpCodes.lookupswitch : { // Skip to place divisible by 4 int rem = code.position() % 4; if (rem != 0) { code.position(code.position() + 4 - rem); } int deflt = code.getInt(); int npairs = code.getInt(); code.position(code.position() + npairs * 8); break; } default : { code.position(code.position() + OpCodes.OFFSETS[instruction]); break; } } } CodeDef codeDef = new CodeDef(attribute, elementType); visitAttributes(cd, codeDef); } /** * Called when crawling the byte code and a method reference is found */ private void visitReferenceMethod(ClassDataCollector cd, int method_ref_index) { AbstractRefInfo refInfo = constantPool.entry(method_ref_index); String className = constantPool.className(refInfo.class_index); NameAndTypeInfo nameAndTypeInfo = constantPool.entry(refInfo.name_and_type_index); String method = constantPool.utf8(nameAndTypeInfo.name_index); String descriptor = constantPool.utf8(nameAndTypeInfo.descriptor_index); TypeRef type = analyzer.getTypeRef(className); cd.referenceMethod(0, type, method, descriptor); } private void processParameterAnnotations(ParameterAnnotationsAttribute attribute, ElementType elementType, RetentionPolicy policy, int access_flags) { for (ParameterAnnotationInfo parameterAnnotationInfo : attribute.parameter_annotations) { for (AnnotationInfo annotationInfo : parameterAnnotationInfo.annotations) { processAnnotation(annotationInfo, elementType, policy, access_flags); } } } private void visitParameterAnnotations(ClassDataCollector cd, ParameterAnnotationsAttribute attribute, ElementType elementType, RetentionPolicy policy, int access_flags) throws Exception { for (ParameterAnnotationInfo parameterAnnotationInfo : attribute.parameter_annotations) { if (parameterAnnotationInfo.annotations.length > 0) { cd.parameter(parameterAnnotationInfo.parameter); for (AnnotationInfo annotationInfo : parameterAnnotationInfo.annotations) { Annotation annotation = newAnnotation(annotationInfo, elementType, policy, access_flags); cd.annotation(annotation); } } } } private void processTypeAnnotations(TypeAnnotationsAttribute attribute, ElementType elementType, RetentionPolicy policy, int access_flags) { for (TypeAnnotationInfo typeAnnotationInfo : attribute.type_annotations) { processAnnotation(typeAnnotationInfo, elementType, policy, access_flags); } } private void visitTypeAnnotations(ClassDataCollector cd, TypeAnnotationsAttribute attribute, ElementType elementType, RetentionPolicy policy, int access_flags) throws Exception { for (TypeAnnotationInfo typeAnnotationInfo : attribute.type_annotations) { cd.typeuse(typeAnnotationInfo.target_type, typeAnnotationInfo.target_index, typeAnnotationInfo.target_info, typeAnnotationInfo.type_path); Annotation annotation = newAnnotation(typeAnnotationInfo, elementType, policy, access_flags); cd.annotation(annotation); } } private void processAnnotations(AnnotationsAttribute attribute, ElementType elementType, RetentionPolicy policy, int access_flags) { for (AnnotationInfo annotationInfo : attribute.annotations) { processAnnotation(annotationInfo, elementType, policy, access_flags); } } private void visitAnnotations(ClassDataCollector cd, AnnotationsAttribute attribute, ElementType elementType, RetentionPolicy policy, int access_flags) throws Exception { for (AnnotationInfo annotationInfo : attribute.annotations) { Annotation annotation = newAnnotation(annotationInfo, elementType, policy, access_flags); cd.annotation(annotation); } } private void processAnnotation(AnnotationInfo annotationInfo, ElementType elementType, RetentionPolicy policy, int access_flags) { if (annotations == null) { annotations = new HashSet<>(); } String typeName = annotationInfo.type; TypeRef typeRef = analyzer.getTypeRef(typeName); annotations.add(typeRef); if (policy == RetentionPolicy.RUNTIME) { referTo(typeRef, 0); hasRuntimeAnnotations = true; if (api != null && (Modifier.isPublic(access_flags) || Modifier.isProtected(access_flags))) { api.add(typeRef.getPackageRef()); } } else { hasClassAnnotations = true; } for (ElementValueInfo elementValueInfo : annotationInfo.values) { processElementValue(elementValueInfo.value, elementType, policy, access_flags); } } Annotation newAnnotation(AnnotationInfo annotationInfo, ElementType elementType, RetentionPolicy policy, int access_flags) { String typeName = annotationInfo.type; TypeRef typeRef = analyzer.getTypeRef(typeName); Map<String, Object> elements = annotationValues(annotationInfo.values, elementType, policy, access_flags); return new Annotation(typeRef, elements, elementType, policy); } ParameterAnnotation newParameterAnnotation(int parameter, AnnotationInfo annotationInfo, ElementType elementType, RetentionPolicy policy, int access_flags) { String typeName = annotationInfo.type; TypeRef typeRef = analyzer.getTypeRef(typeName); Map<String, Object> elements = annotationValues(annotationInfo.values, elementType, policy, access_flags); return new ParameterAnnotation(parameter, typeRef, elements, elementType, policy); } TypeAnnotation newTypeAnnotation(TypeAnnotationInfo annotationInfo, ElementType elementType, RetentionPolicy policy, int access_flags) { String typeName = annotationInfo.type; TypeRef typeRef = analyzer.getTypeRef(typeName); Map<String, Object> elements = annotationValues(annotationInfo.values, elementType, policy, access_flags); return new TypeAnnotation(annotationInfo.target_type, annotationInfo.target_info, annotationInfo.target_index, annotationInfo.type_path, typeRef, elements, elementType, policy); } private Map<String, Object> annotationValues(ElementValueInfo[] values, ElementType elementType, RetentionPolicy policy, int access_flags) { Map<String, Object> elements = new LinkedHashMap<>(); for (ElementValueInfo elementValueInfo : values) { String element = elementValueInfo.name; Object value = newElementValue(elementValueInfo.value, elementType, policy, access_flags); elements.put(element, value); } return elements; } private void processElementValue(Object value, ElementType elementType, RetentionPolicy policy, int access_flags) { if (value instanceof EnumConst) { if (policy == RetentionPolicy.RUNTIME) { EnumConst enumConst = (EnumConst) value; TypeRef name = analyzer.getTypeRef(enumConst.type); referTo(name, 0); if (api != null && (Modifier.isPublic(access_flags) || Modifier.isProtected(access_flags))) { api.add(name.getPackageRef()); } } } else if (value instanceof ResultConst) { if (policy == RetentionPolicy.RUNTIME) { ResultConst resultConst = (ResultConst) value; TypeRef name = analyzer.getTypeRef(resultConst.descriptor); if (!name.isPrimitive()) { PackageRef packageRef = name.getPackageRef(); if (!packageRef.isPrimitivePackage()) { referTo(name, 0); if (api != null && (Modifier.isPublic(access_flags) || Modifier.isProtected(access_flags))) { api.add(packageRef); } } } } } else if (value instanceof AnnotationInfo) { processAnnotation((AnnotationInfo) value, elementType, policy, access_flags); } else if (value instanceof Object[]) { Object[] array = (Object[]) value; int num_values = array.length; for (int i = 0; i < num_values; i++) { processElementValue(array[i], elementType, policy, access_flags); } } } private Object newElementValue(Object value, ElementType elementType, RetentionPolicy policy, int access_flags) { if (value instanceof EnumConst) { EnumConst enumConst = (EnumConst) value; return enumConst.name; } else if (value instanceof ResultConst) { ResultConst resultConst = (ResultConst) value; TypeRef name = analyzer.getTypeRef(resultConst.descriptor); return name; } else if (value instanceof AnnotationInfo) { return newAnnotation((AnnotationInfo) value, elementType, policy, access_flags); } else if (value instanceof Object[]) { Object[] array = (Object[]) value; int num_values = array.length; Object[] result = new Object[num_values]; for (int i = 0; i < num_values; i++) { result[i] = newElementValue(array[i], elementType, policy, access_flags); } return result; } else { return value; } } private void processBootstrapMethods(BootstrapMethodsAttribute attribute) { for (BootstrapMethod bootstrapMethod : attribute.bootstrap_methods) { for (int bootstrap_argument : bootstrapMethod.bootstrap_arguments) { classConstRef(bootstrap_argument); } } } private void processStackMapTable(StackMapTableAttribute attribute) { for (StackMapFrame stackMapFrame : attribute.entries) { switch (stackMapFrame.type()) { case StackMapFrame.SAME_LOCALS_1_STACK_ITEM : SameLocals1StackItemFrame sameLocals1StackItemFrame = (SameLocals1StackItemFrame) stackMapFrame; verification_type_info(sameLocals1StackItemFrame.stack); break; case StackMapFrame.SAME_LOCALS_1_STACK_ITEM_EXTENDED : SameLocals1StackItemFrameExtended sameLocals1StackItemFrameExtended = (SameLocals1StackItemFrameExtended) stackMapFrame; verification_type_info(sameLocals1StackItemFrameExtended.stack); break; case StackMapFrame.APPEND : AppendFrame appendFrame = (AppendFrame) stackMapFrame; for (VerificationTypeInfo verificationTypeInfo : appendFrame.locals) { verification_type_info(verificationTypeInfo); } break; case StackMapFrame.FULL_FRAME : FullFrame fullFrame = (FullFrame) stackMapFrame; for (VerificationTypeInfo verificationTypeInfo : fullFrame.locals) { verification_type_info(verificationTypeInfo); } for (VerificationTypeInfo verificationTypeInfo : fullFrame.stack) { verification_type_info(verificationTypeInfo); } break; } } } private void verification_type_info(VerificationTypeInfo verificationTypeInfo) { switch (verificationTypeInfo.tag) { case VerificationTypeInfo.ITEM_Object :// Object_variable_info ObjectVariableInfo objectVariableInfo = (ObjectVariableInfo) verificationTypeInfo; classConstRef(objectVariableInfo.type); break; } } /** * Add a new package reference. * * @param packageRef A '.' delimited package name */ private void referTo(TypeRef typeRef, int modifiers) { xref.add(typeRef); if (typeRef.isPrimitive()) { return; } PackageRef packageRef = typeRef.getPackageRef(); if (packageRef.isPrimitivePackage()) { return; } imports.add(packageRef); if (api != null && (Modifier.isPublic(modifiers) || Modifier.isProtected(modifiers))) { api.add(packageRef); } referred.merge(typeRef, Integer.valueOf(modifiers), (o, n) -> { int old_modifiers = o.intValue(); int new_modifiers = n.intValue(); if ((old_modifiers == new_modifiers) || (new_modifiers == 0)) { return o; } else if (old_modifiers == 0) { return n; } else { return Integer.valueOf(old_modifiers | new_modifiers); } }); } private void referTo(String descriptor, int modifiers) { char c = descriptor.charAt(0); if (c != '(' && c != 'L' && c != '[' && c != '<' && c != 'T') { return; } Signature sig = (c == '(' || c == '<') ? analyzer.getMethodSignature(descriptor) : analyzer.getFieldSignature(descriptor); Set<String> binaryRefs = sig.erasedBinaryReferences(); for (String binary : binaryRefs) { TypeRef ref = analyzer.getTypeRef(binary); referTo(ref, modifiers); } } @Deprecated public void parseDescriptor(String descriptor, int modifiers) { if (referred == null) { referred = new HashMap<>(); } referTo(descriptor, modifiers); } public Set<PackageRef> getReferred() { return imports; } public String getAbsolutePath() { return path; } @Deprecated public void reset() {} private Stream<Clazz> hierarchyStream(Analyzer analyzer) { requireNonNull(analyzer); Spliterator<Clazz> spliterator = new AbstractSpliterator<Clazz>(Long.MAX_VALUE, Spliterator.DISTINCT | Spliterator.ORDERED | Spliterator.NONNULL) { private Clazz clazz = Clazz.this; @Override public boolean tryAdvance(Consumer<? super Clazz> action) { requireNonNull(action); if (clazz == null) { return false; } action.accept(clazz); TypeRef type = clazz.superClass; if (type == null) { clazz = null; } else { try { clazz = analyzer.findClass(type); } catch (Exception e) { throw Exceptions.duck(e); } if (clazz == null) { analyzer.warning("While traversing the type tree for %s cannot find class %s", Clazz.this, type); } } return true; } }; return StreamSupport.stream(spliterator, false); } private Stream<TypeRef> typeStream(Analyzer analyzer, Function<? super Clazz, Collection<? extends TypeRef>> func, Set<TypeRef> visited) { requireNonNull(analyzer); requireNonNull(func); Spliterator<TypeRef> spliterator = new AbstractSpliterator<TypeRef>(Long.MAX_VALUE, Spliterator.DISTINCT | Spliterator.ORDERED | Spliterator.NONNULL) { private final Deque<TypeRef> queue = new ArrayDeque<>(func.apply(Clazz.this)); private final Set<TypeRef> seen = (visited != null) ? visited : new HashSet<>(); @Override public boolean tryAdvance(Consumer<? super TypeRef> action) { requireNonNull(action); TypeRef type; do { type = queue.poll(); if (type == null) { return false; } } while (seen.contains(type)); seen.add(type); action.accept(type); if (visited != null) { Clazz clazz; try { clazz = analyzer.findClass(type); } catch (Exception e) { throw Exceptions.duck(e); } if (clazz == null) { analyzer.warning("While traversing the type tree for %s cannot find class %s", Clazz.this, type); } else { queue.addAll(func.apply(clazz)); } } return true; } }; return StreamSupport.stream(spliterator, false); } public boolean is(QUERY query, Instruction instr, Analyzer analyzer) throws Exception { switch (query) { case ANY : return true; case NAMED : return instr.matches(getClassName().getDottedOnly()) ^ instr.isNegated(); case VERSION : { String v = classFile.major_version + "." + classFile.minor_version; return instr.matches(v) ^ instr.isNegated(); } case IMPLEMENTS : { Set<TypeRef> visited = new HashSet<>(); return hierarchyStream(analyzer).flatMap(c -> c.typeStream(analyzer, Clazz::interfaces, visited)) .map(TypeRef::getDottedOnly) .anyMatch(instr::matches) ^ instr.isNegated(); } case EXTENDS : return hierarchyStream(analyzer).skip(1) // skip this class .map(Clazz::getClassName) .map(TypeRef::getDottedOnly) .anyMatch(instr::matches) ^ instr.isNegated(); case PUBLIC : return isPublic(); case CONCRETE : return !isAbstract(); case ANNOTATED : return typeStream(analyzer, Clazz::annotations, null) .map(TypeRef::getFQN) .anyMatch(instr::matches) ^ instr.isNegated(); case INDIRECTLY_ANNOTATED : return typeStream(analyzer, Clazz::annotations, new HashSet<>()) .map(TypeRef::getFQN) .anyMatch(instr::matches) ^ instr.isNegated(); case HIERARCHY_ANNOTATED : return hierarchyStream(analyzer) .flatMap(c -> c.typeStream(analyzer, Clazz::annotations, null)) .map(TypeRef::getFQN) .anyMatch(instr::matches) ^ instr.isNegated(); case HIERARCHY_INDIRECTLY_ANNOTATED : { Set<TypeRef> visited = new HashSet<>(); return hierarchyStream(analyzer) .flatMap(c -> c.typeStream(analyzer, Clazz::annotations, visited)) .map(TypeRef::getFQN) .anyMatch(instr::matches) ^ instr.isNegated(); } case RUNTIMEANNOTATIONS : return hasRuntimeAnnotations; case CLASSANNOTATIONS : return hasClassAnnotations; case ABSTRACT : return isAbstract(); case IMPORTS : return hierarchyStream(analyzer) .map(Clazz::getReferred) .flatMap(Set::stream) .distinct() .map(PackageRef::getFQN) .anyMatch(instr::matches) ^ instr.isNegated(); case DEFAULT_CONSTRUCTOR : return hasPublicNoArgsConstructor(); } return instr == null ? false : instr.isNegated(); } @Override public String toString() { return (classDef != null) ? classDef.getName() : resource.toString(); } public boolean isPublic() { return classDef.isPublic(); } public boolean isProtected() { return classDef.isProtected(); } public boolean isEnum() { /** * The additional check for superClass name avoids stating that an * anonymous inner class of an enum is an enum class. */ return classDef.isEnum() && superClass.getBinary() .equals("java/lang/Enum"); } public boolean isSynthetic() { return classDef.isSynthetic(); } public boolean isModule() { return classDef.isModule(); } static boolean isModule(int access) { return (access & ACC_MODULE) != 0; } public JAVA getFormat() { return JAVA.format(classFile.major_version); } public static String objectDescriptorToFQN(String string) { if ((string.startsWith("L") || string.startsWith("T")) && string.endsWith(";")) return string.substring(1, string.length() - 1) .replace('/', '.'); switch (string.charAt(0)) { case 'V' : return "void"; case 'B' : return "byte"; case 'C' : return "char"; case 'I' : return "int"; case 'S' : return "short"; case 'D' : return "double"; case 'F' : return "float"; case 'J' : return "long"; case 'Z' : return "boolean"; case '[' : // Array return objectDescriptorToFQN(string.substring(1)) + "[]"; } throw new IllegalArgumentException("Invalid type character in descriptor " + string); } public static String unCamel(String id) { StringBuilder out = new StringBuilder(); for (int i = 0; i < id.length(); i++) { char c = id.charAt(i); if (c == '_' || c == '$' || c == '-' || c == '.') { if (out.length() > 0 && !Character.isWhitespace(out.charAt(out.length() - 1))) out.append(' '); continue; } int n = i; while (n < id.length() && Character.isUpperCase(id.charAt(n))) { n++; } if (n == i) out.append(id.charAt(i)); else { boolean tolower = (n - i) == 1; if (i > 0 && !Character.isWhitespace(out.charAt(out.length() - 1))) out.append(' '); for (; i < n;) { if (tolower) out.append(Character.toLowerCase(id.charAt(i))); else out.append(id.charAt(i)); i++; } i } } if (id.startsWith(".")) out.append(" *"); out.replace(0, 1, Character.toUpperCase(out.charAt(0)) + ""); return out.toString(); } public boolean isInterface() { return classDef.isInterface(); } public boolean isAbstract() { return classDef.isAbstract(); } public boolean hasPublicNoArgsConstructor() { return hasDefaultConstructor; } public int getAccess() { return classDef.getAccess(); } @Deprecated public void setInnerAccess(int access) {} public Stream<Annotation> annotations(String binaryNameFilter) { return classDef.annotations(binaryNameFilter); } public Stream<TypeAnnotation> typeAnnotations(String binaryNameFilter) { return classDef.typeAnnotations(binaryNameFilter); } public TypeRef getClassName() { return classDef.getType(); } public boolean isInnerClass() { return classDef.isInnerClass(); } @Deprecated public MethodDef getMethodDef(int access, String name, String descriptor) { return new MethodDef(access, name, descriptor); } public TypeRef getSuper() { return superClass; } public String getFQN() { return classDef.getName(); } public TypeRef[] getInterfaces() { return interfaces; } public List<TypeRef> interfaces() { return (interfaces != null) ? Arrays.asList(interfaces) : emptyList(); } public Set<TypeRef> annotations() { return (annotations != null) ? annotations : emptySet(); } public boolean isFinal() { return classDef.isFinal(); } @Deprecated public void setDeprecated(boolean b) {} public boolean isDeprecated() { return classDef.isDeprecated(); } public boolean isAnnotation() { return classDef.isAnnotation(); } static boolean isAnnotation(int access) { return (access & ACC_ANNOTATION) != 0; } public Set<PackageRef> getAPIUses() { return (api != null) ? api : emptySet(); } public Clazz.TypeDef getExtends(TypeRef type) { return new TypeDef(type, false); } public Clazz.TypeDef getImplements(TypeRef type) { return new TypeDef(type, true); } private void classConstRef(int index) { if (constantPool.tag(index) == CONSTANT_Class) { String name = constantPool.className(index); classConstRef(name); } } private void classConstRef(String name) { if (name != null) { TypeRef typeRef = analyzer.getTypeRef(name); referTo(typeRef, 0); } } public String getClassSignature() { return classDef.getSignature(); } public String getSourceFile() { return classDef.getSourceFile(); } public Map<String, Object> getDefaults() throws Exception { parseClassFile(); if (!classDef.isAnnotation()) { return emptyMap(); } Map<String, Object> map = methods().filter(m -> m.attribute(AnnotationDefaultAttribute.class) .isPresent()) .collect(toMap(MethodDef::getName, MethodDef::getConstant)); return map; } public Resource getResource() { return resource; } }
package simpledb; import java.util.*; import simpledb.Utility.AvgAgg; import static simpledb.ImputationType.DROP; import static simpledb.ImputationType.MAXIMAL; /** * Adding imputation on top of a plan that already has imputed values along its * tree. We need this to add drop, impute min, impute max to plans that already * include joins. */ public class LogicalComposeImputation extends ImputedPlan { private final DbIterator physicalPlan; private final ImputedPlan subplan; private final Set<QualifiedName> dirtySet; private final double loss; private final double time; private TableStats tableStats; /** * Constructor intended only for internal construction of updated plan * @param tableStats * @param physicalPlan * @param dirtySet * @param loss * @param time */ private LogicalComposeImputation(TableStats tableStats, DbIterator physicalPlan, ImputedPlan subplan, Set<QualifiedName> dirtySet, double loss, double time) { super(); this.physicalPlan = physicalPlan; this.dirtySet = dirtySet; this.loss = loss; this.time = time; this.tableStats = tableStats; this.subplan = subplan; } public TableStats getTableStats() { return this.tableStats; } public static ImputedPlan create(ImputedPlan subplan, ImputationType imp, Set<QualifiedName> impute, Map<String, Integer> tableMap) { assert !Collections.disjoint(subplan.getDirtySet(), impute); // No-op imputations aren't allowed. final Set<QualifiedName> dirtySet = new HashSet<>(subplan.getDirtySet()); // compute new dirty set dirtySet.removeAll(impute); final TupleDesc schema = subplan.getPlan().getTupleDesc(); final Collection<Integer> imputeIndices = schema.fieldNamesToIndices(impute); TableStats subplanTableStats = subplan.getTableStats(); // table stats for subplan switch (imp) { case DROP: { Impute dropOp = new Drop(toNames(impute), subplan); final double loss = dropOp.getEstimatedPenalty(); final double time = dropOp.getEstimatedTime(); final TableStats adjustedTableStats = subplanTableStats.adjustForImpute(DROP, imputeIndices); return new LogicalComposeImputation(adjustedTableStats, dropOp, subplan, dirtySet, loss, time); } case MAXIMAL: case MINIMAL: Impute imputeOp = new ImputeRegressionTree(toNames(impute), subplan); final double loss = imputeOp.getEstimatedPenalty(); final double time = imputeOp.getEstimatedTime(); final TableStats adjustedTableStats = subplanTableStats.adjustForImpute(MAXIMAL, imputeIndices); return new LogicalComposeImputation(adjustedTableStats, imputeOp, subplan, dirtySet, loss, time); case NONE: throw new RuntimeException("NONE is no longer a valid ImputationType."); default: throw new RuntimeException("Unexpected ImputationType."); } } public DbIterator getPlan() { return physicalPlan; } public Set<QualifiedName> getDirtySet() { return dirtySet; } @Override protected AvgAgg loss() { return subplan.loss().add(loss); } @Override protected double time() { return subplan.time() + time; } public double cardinality() { return tableStats.totalTuples(); } private static Set<String> toNames(Set<QualifiedName> attrs) { Set<String> names = new HashSet<>(); for (QualifiedName attr : attrs) { names.add(attr.toString()); } return names; } }
package im.actor.model.modules.notifications; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import im.actor.model.droidkit.engine.SyncKeyValue; import im.actor.model.entity.ContentDescription; import im.actor.model.entity.Notification; import im.actor.model.entity.Peer; import im.actor.model.modules.Modules; import im.actor.model.modules.notifications.entity.PendingNotification; import im.actor.model.modules.notifications.entity.PendingStorage; import im.actor.model.modules.utils.ModuleActor; public class NotificationsActor extends ModuleActor { private static final int MAX_NOTIFICATION_COUNT = 10; private SyncKeyValue storage; private PendingStorage pendingStorage; private Peer visiblePeer; private boolean isAppVisible = false; private boolean isDialogsVisible = false; public NotificationsActor(Modules messenger) { super(messenger); this.storage = messenger.getNotifications().getNotificationsStorage(); } @Override public void preStart() { pendingStorage = new PendingStorage(); byte[] storage = this.storage.get(0); if (storage != null) { try { pendingStorage = PendingStorage.fromBytes(storage); } catch (IOException e) { e.printStackTrace(); } } } private List<PendingNotification> getNotifications() { return pendingStorage.getNotifications(); } public void onNewMessage(Peer peer, int sender, long date, ContentDescription description) { if(date<=modules().getMessagesModule().loadReadState(peer)){ return; } boolean isPeerEnabled = modules().getSettings().isNotificationsEnabled(peer); boolean isEnabled = modules().getSettings().isNotificationsEnabled() && isPeerEnabled; List<PendingNotification> allPending = getNotifications(); allPending.add(new PendingNotification(peer, sender, date, description)); saveStorage(); if (config().getNotificationProvider() != null) { if (isAppVisible) { if (visiblePeer != null && visiblePeer.equals(peer)) { if (modules().getSettings().isConversationTonesEnabled()) { config().getNotificationProvider().onMessageArriveInApp(modules().getMessenger()); } } else if (isDialogsVisible) { if (modules().getSettings().isConversationTonesEnabled()) { config().getNotificationProvider().onMessageArriveInApp(modules().getMessenger()); } } else if (modules().getSettings().isInAppEnabled()) { if (isPeerEnabled) { performNotification(false); } } } else { if (isEnabled) { performNotification(false); } } } } public void onMessagesRead(Peer peer, long fromDate) { boolean isChanged = false; for (PendingNotification p : pendingStorage.getNotifications().toArray(new PendingNotification[0])) { if (p.getPeer().equals(peer) && p.getDate() <= fromDate) { pendingStorage.getNotifications().remove(p); isChanged = true; } } if (isChanged) { saveStorage(); performNotification(true); } } public void onConversationVisible(Peer peer) { this.visiblePeer = peer; //performNotification(true); } public void onConversationHidden(Peer peer) { if (visiblePeer != null && visiblePeer.equals(peer)) { this.visiblePeer = null; } } public void onAppVisible() { isAppVisible = true; hideNotification(); } public void onAppHidden() { isAppVisible = false; } public void onDialogsVisible() { isDialogsVisible = true; hideNotification(); } public void onDialogsHidden() { isDialogsVisible = false; } private void performNotification(boolean isSilentUpdate) { List<PendingNotification> allPending = getNotifications(); List<PendingNotification> destNotifications = new ArrayList<PendingNotification>(); for (int i = 0; i < allPending.size(); i++) { if (destNotifications.size() >= MAX_NOTIFICATION_COUNT) { break; } PendingNotification pendingNotification = allPending.get(allPending.size() - 1 - i); if (visiblePeer != null && visiblePeer.equals(pendingNotification.getPeer())) { continue; } destNotifications.add(pendingNotification); } if (destNotifications.size() == 0) { hideNotification(); return; } List<Notification> res = new ArrayList<Notification>(); for (PendingNotification p : destNotifications) { res.add(new Notification(p.getPeer(), p.getSender(), p.getContent())); } int messagesCount = allPending.size(); HashSet<Peer> peers = new HashSet<Peer>(); for (PendingNotification p : allPending) { peers.add(p.getPeer()); } int chatsCount = peers.size(); config().getNotificationProvider().onNotification(modules().getMessenger(), res, messagesCount, chatsCount, isSilentUpdate, isAppVisible); } private void hideNotification() { config().getNotificationProvider().hideAllNotifications(); } private void saveStorage() { this.storage.put(0, pendingStorage.toByteArray()); } // Messages @Override public void onReceive(Object message) { if (message instanceof NewMessage) { NewMessage newMessage = (NewMessage) message; onNewMessage(newMessage.getPeer(), newMessage.getSender(), newMessage.getSortDate(), newMessage.getContentDescription()); } else if (message instanceof MessagesRead) { MessagesRead read = (MessagesRead) message; onMessagesRead(read.getPeer(), read.getFromDate()); } else if (message instanceof OnConversationVisible) { onConversationVisible(((OnConversationVisible) message).getPeer()); } else if (message instanceof OnConversationHidden) { onConversationHidden(((OnConversationHidden) message).getPeer()); } else if (message instanceof OnAppHidden) { onAppHidden(); } else if (message instanceof OnAppVisible) { onAppVisible(); } else if (message instanceof OnDialogsVisible) { onDialogsVisible(); } else if (message instanceof OnDialogsHidden) { onDialogsHidden(); } else { drop(message); } } public static class NewMessage { private Peer peer; private int sender; private long sortDate; private ContentDescription contentDescription; public NewMessage(Peer peer, int sender, long sortDate, ContentDescription contentDescription) { this.peer = peer; this.sender = sender; this.sortDate = sortDate; this.contentDescription = contentDescription; } public Peer getPeer() { return peer; } public int getSender() { return sender; } public long getSortDate() { return sortDate; } public ContentDescription getContentDescription() { return contentDescription; } } public static class MessagesRead { private Peer peer; private long fromDate; public MessagesRead(Peer peer, long fromDate) { this.peer = peer; this.fromDate = fromDate; } public Peer getPeer() { return peer; } public long getFromDate() { return fromDate; } } public static class OnConversationVisible { private Peer peer; public OnConversationVisible(Peer peer) { this.peer = peer; } public Peer getPeer() { return peer; } } public static class OnConversationHidden { private Peer peer; public OnConversationHidden(Peer peer) { this.peer = peer; } public Peer getPeer() { return peer; } } public static class OnAppVisible { } public static class OnAppHidden { } public static class OnDialogsVisible { } public static class OnDialogsHidden { } }
package org.eclipse.birt.report.model.api; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.eclipse.birt.report.model.api.activity.SemanticException; import org.eclipse.birt.report.model.api.command.CustomMsgException; import org.eclipse.birt.report.model.api.core.AttributeEvent; import org.eclipse.birt.report.model.api.core.DisposeEvent; import org.eclipse.birt.report.model.api.core.IAccessControl; import org.eclipse.birt.report.model.api.core.IAttributeListener; import org.eclipse.birt.report.model.api.core.IDesignElement; import org.eclipse.birt.report.model.api.core.IDisposeListener; import org.eclipse.birt.report.model.api.core.IModuleModel; import org.eclipse.birt.report.model.api.core.IResourceChangeListener; import org.eclipse.birt.report.model.api.core.IStructure; import org.eclipse.birt.report.model.api.css.CssStyleSheetHandle; import org.eclipse.birt.report.model.api.css.StyleSheetException; import org.eclipse.birt.report.model.api.elements.ReportDesignConstants; import org.eclipse.birt.report.model.api.elements.structures.ConfigVariable; import org.eclipse.birt.report.model.api.elements.structures.CustomColor; import org.eclipse.birt.report.model.api.elements.structures.EmbeddedImage; import org.eclipse.birt.report.model.api.elements.structures.IncludeScript; import org.eclipse.birt.report.model.api.elements.structures.ScriptLib; import org.eclipse.birt.report.model.api.olap.CubeHandle; import org.eclipse.birt.report.model.api.olap.DimensionHandle; import org.eclipse.birt.report.model.api.olap.LevelHandle; import org.eclipse.birt.report.model.api.util.PropertyValueValidationUtil; import org.eclipse.birt.report.model.api.util.StringUtil; import org.eclipse.birt.report.model.api.util.URIUtil; import org.eclipse.birt.report.model.api.util.UnicodeUtil; import org.eclipse.birt.report.model.api.validators.IValidationListener; import org.eclipse.birt.report.model.api.validators.ValidationEvent; import org.eclipse.birt.report.model.command.ComplexPropertyCommand; import org.eclipse.birt.report.model.core.DesignElement; import org.eclipse.birt.report.model.core.Module; import org.eclipse.birt.report.model.core.StructureContext; import org.eclipse.birt.report.model.core.StyleElement; import org.eclipse.birt.report.model.elements.CascadingParameterGroup; import org.eclipse.birt.report.model.elements.DataSet; import org.eclipse.birt.report.model.elements.JointDataSet; import org.eclipse.birt.report.model.elements.Library; import org.eclipse.birt.report.model.elements.Parameter; import org.eclipse.birt.report.model.elements.ReportItemTheme; import org.eclipse.birt.report.model.elements.TemplateParameterDefinition; import org.eclipse.birt.report.model.elements.Theme; import org.eclipse.birt.report.model.elements.Translation; import org.eclipse.birt.report.model.elements.olap.Dimension; import org.eclipse.birt.report.model.elements.strategy.DummyCopyPolicy; import org.eclipse.birt.report.model.metadata.ElementPropertyDefn; import org.eclipse.birt.report.model.metadata.MetaDataDictionary; import org.eclipse.birt.report.model.util.LineNumberInfo; import org.eclipse.birt.report.model.util.ModelUtil; import org.eclipse.birt.report.model.util.URIUtilImpl; import com.ibm.icu.util.ULocale; /** * Abstract module handle which provides the common functionalities of report * design and library. * * <table border="1" cellpadding="2" cellspacing="2" style="border-collapse: * collapse" bordercolor="#111111"> * <th width="20%">Content Item</th> * <th width="40%">Description</th> * * <tr> * <td>Code Modules</td> * <td>Global scripts that apply to the report as a whole.</td> * </tr> * * <tr> * <td>Parameters</td> * <td>A list of Parameter elements that describe the data that the user can * enter when running the report.</td> * </tr> * * <tr> * <td>Data Sources</td> * <td>The connections used by the report.</td> * </tr> * * <tr> * <td>Data Sets</td> * <td>Data sets defined in the design.</td> * </tr> * * <tr> * <td>Color Palette</td> * <td>A set of custom color names as part of the design.</td> * </tr> * * <tr> * <td>Styles</td> * <td>User-defined styles used to format elements in the report. Each style * must have a unique name within the set of styles for this report.</td> * </tr> * * <tr> * <td>Page Setup</td> * <td>The layout of the master pages within the report.</td> * </tr> * * <tr> * <td>Components</td> * <td>Reusable report items defined in this design. Report items can extend * these items. Defines a "private library" for this design.</td> * </tr> * * <tr> * <td>Translations</td> * <td>The list of externalized messages specifically for this report.</td> * </tr> * * <tr> * <td>Images</td> * <td>A list of images embedded in this report.</td> * </tr> * * </table> */ public abstract class ModuleHandleImpl extends DesignElementHandle implements IModuleModel { /** * The flag indicates that whether the initialization is finished. */ protected boolean isInitialized = false; /** * Constructs one module handle with the given module element. * * @param module * module */ public ModuleHandleImpl( Module module ) { super( module ); initializeSlotHandles( ); cachePropertyHandles( ); } /** * Adds a new config variable. * * @param configVar * the config variable * @throws SemanticException * if the name is empty or the same name exists. * */ public void addConfigVariable( ConfigVariable configVar ) throws SemanticException { throw new IllegalOperationException( ); } /** * Adds a new embedded image. * * @param image * the image to add * @throws SemanticException * if the name is empty, type is invalid, or the same name * exists. */ public void addImage( EmbeddedImage image ) throws SemanticException { throw new IllegalOperationException( ); } /** * Checks the name of the embedded image in this report. If duplicate, get a * unique name and rename it. * * @param image * the embedded image whose name is need to check */ public final void rename( EmbeddedImage image ) { module.rename( image ); } /** * Adds a new translation to the design. * * @param resourceKey * resource key for the message * @param locale * the string value of a locale for the translation. Locale * should be in java-defined format( en, en-US, zh_CN, etc.) * @param text * translated text for the locale * * @throws CustomMsgException * if the resource key is duplicate or missing, or locale is not * a valid format. * * @see #getTranslation(String, String) */ public void addTranslation( String resourceKey, String locale, String text ) throws CustomMsgException { throw new IllegalOperationException( ); } /** * Adds the validation listener, which implements * <code>IValidationListener</code>. A listener receives notifications each * time an element is validated. * * @param listener * the validation listener. */ public final void addValidationListener( IValidationListener listener ) { module.addValidationListener( listener ); } /** * Checks this whole report. Only one <code>ValidationEvent</code> will be * sent, which contains all error information of this check. */ public final void checkReport( ) { // validate the whole design module.semanticCheck( module ); ValidationEvent event = new ValidationEvent( module, null, getErrorList( ) ); module.broadcastValidationEvent( module, event ); } /** * Closes the design. The report design handle is no longer valid after * closing the design. This method will send notifications instance of * <code>DisposeEvent</code> to all the dispose listeners registered in the * module. */ public final void close( ) { module.close( ); DisposeEvent event = new DisposeEvent( module ); module.broadcastDisposeEvent( event ); } /** * Returns the structures which are defined in report design and all * included valid libraries. This method will filter the structure with * duplicate name with the follow rule. * * <ul> * <li>The structure defined in design file overrides the one with the same * name in library file. * <li>The structure defined in preceding library overrides the one with the * same name in following library file. * <ul> * * @param propName * name of the list property * @param nameMember * name of the name member * @return the filtered structure list with the above rule. */ final List getFilteredStructureList( String propName, String nameMember ) { List list = new ArrayList( ); PropertyHandle propHandle = getPropertyHandle( propName ); if ( propHandle == null ) return Collections.emptyList( ); Set names = new HashSet( ); Iterator iter = propHandle.iterator( ); while ( iter.hasNext( ) ) { StructureHandle s = (StructureHandle) iter.next( ); String nameValue = (String) s.getProperty( nameMember ); if ( !names.contains( nameValue ) ) { list.add( s ); names.add( nameValue ); } } List theLibraries = getLibraries( ); int size = theLibraries.size( ); for ( int i = 0; i < size; i++ ) { LibraryHandle library = (LibraryHandle) theLibraries.get( i ); if ( library.isValid( ) ) { iter = library.getFilteredStructureList( propName, nameMember ) .iterator( ); while ( iter.hasNext( ) ) { StructureHandle s = (StructureHandle) iter.next( ); String nameValue = (String) s.getProperty( nameMember ); if ( !names.contains( nameValue ) ) { list.add( s ); names.add( nameValue ); } } } } return list; } /** * Returns the structures which are defined in the current module and all * included valid libraries. This method will collect all structures from * this module file and each valid library. * * @param propName * name of the list property * @return the structure list, each of which is the instance of <code> * StructureHandle</code> */ final List getStructureList( String propName ) { List list = new ArrayList( ); List tempList = getNativeStructureList( propName ); if ( !tempList.isEmpty( ) ) list.addAll( tempList ); List theLibraries = getLibraries( ); int size = theLibraries.size( ); for ( int i = 0; i < size; i++ ) { LibraryHandle library = (LibraryHandle) theLibraries.get( i ); tempList = library.getStructureList( propName ); if ( !tempList.isEmpty( ) ) list.addAll( tempList ); } return list; } /** * Returns the structures which are defined locally in the current module. * This method will collect all structures from the current module file * locally. * * @param propName * name of the list property * @return the structure list, each of which is the instance of <code> * StructureHandle</code> */ protected final List getNativeStructureList( String propName ) { List list = new ArrayList( ); PropertyHandle propHandle = getPropertyHandle( propName ); if ( propHandle == null ) return Collections.emptyList( ); Iterator iter = propHandle.iterator( ); while ( iter.hasNext( ) ) { StructureHandle s = (StructureHandle) iter.next( ); list.add( s ); } return list; } /** * Returns the iterator over all configuration variables. Each one is the * instance of <code>ConfigVariableHandle</code>. * <p> * Note: The configure variable in library file will be hidden if the one * with the same name appears in design file. * * @return the iterator over all configuration variables. * @see ConfigVariableHandle */ public final Iterator configVariablesIterator( ) { return getFilteredStructureList( CONFIG_VARS_PROP, ConfigVariable.NAME_MEMBER ).iterator( ); } /** * Returns the iterator over all structures of color palette. Each one is * the instance of <code>CustomColorHandle</code> * * @return the iterator over all structures of color palette. * @see CustomColorHandle */ public final Iterator customColorsIterator( ) { return getStructureList( COLOR_PALETTE_PROP ).iterator( ); } /** * Drops a config variable. * * @param name * config variable name * @throws SemanticException * if no config variable is found. * @deprecated */ public void dropConfigVariable( String name ) throws SemanticException { throw new IllegalOperationException( ); } /** * Drops an embedded image handle list from the design. Each one in the list * is the instance of <code>EmbeddedImageHandle</code>. * * @param images * the image handle list to remove * @throws SemanticException * if any image in the list is not found. */ public void dropImage( List images ) throws SemanticException { throw new IllegalOperationException( ); } /** * Drops an embedded image from the design. * * @param name * the image name * @throws SemanticException * if the image is not found. * @deprecated */ public void dropImage( String name ) throws SemanticException { throw new IllegalOperationException( ); } /** * Drops a translation from the design. * * @param resourceKey * resource key of the message in which this translation saves. * @param locale * the string value of the locale for a translation. Locale * should be in java-defined format( en, en-US, zh_CN, etc.) * @throws CustomMsgException * if <code>resourceKey</code> is <code>null</code>. * @see #getTranslation(String, String) */ public void dropTranslation( String resourceKey, String locale ) throws CustomMsgException { throw new IllegalOperationException( ); } /** * Finds a data set by name in this module and the included modules. * * @param name * name of the data set * @return a handle to the data set, or <code>null</code> if the data set is * not found */ public final DataSetHandle findDataSet( String name ) { DesignElement element = module.findDataSet( name ); if ( !( element instanceof DataSet ) ) return null; return (DataSetHandle) element.getHandle( element.getRoot( ) ); } /** * Finds a joint data set by name in this module and the included modules. * * @param name * name of the joint data set * @return a handle to the joint data set, or <code>null</code> if the data * set is not found */ public final JointDataSetHandle findJointDataSet( String name ) { DesignElement element = module.findDataSet( name ); if ( !( element instanceof JointDataSet ) ) return null; return (JointDataSetHandle) element.getHandle( element.getRoot( ) ); } /** * Finds a template data set by name in this module and the included * modules. * * @param name * name of the data set * @return a handle to the template data set, or <code>null</code> if the * data set is not found */ public final TemplateDataSetHandle findTemplateDataSet( String name ) { DesignElement element = module.findDataSet( name ); if ( element == null ) return null; return (TemplateDataSetHandle) element.getHandle( element.getRoot( ) ); } /** * Finds a data source by name in this module and the included modules. * * @param name * name of the data source * @return a handle to the data source, or <code>null</code> if the data * source is not found */ public final DataSourceHandle findDataSource( String name ) { DesignElement element = module.findDataSource( name ); if ( element == null ) return null; return (DataSourceHandle) element.getHandle( element.getRoot( ) ); } /** * Finds a named element in the name space in this module and the included * moduled. * * @param name * the name of the element to find * @return a handle to the element, or <code>null</code> if the element was * not found. */ public final DesignElementHandle findElement( String name ) { DesignElement element = module.findElement( name ); if ( element == null ) return null; return element.getHandle( element.getRoot( ) ); } /** * Finds a cube element by name in this module and the included modules. * * @param name * the element name * @return the cube element handle, if found, otherwise null */ public final CubeHandle findCube( String name ) { DesignElement element = module.findOLAPElement( name ); if ( element == null ) return null; return element.getDefn( ).isKindOf( MetaDataDictionary.getInstance( ).getElement( ReportDesignConstants.CUBE_ELEMENT ) ) ? (CubeHandle) element.getHandle( element.getRoot( ) ) : null; } /** * Finds a cube element by name in this module and the included modules. * * @param name * the element name, name must be Dimension name + "/" + level * name. * @return the cube element handle, if found, otherwise null */ public final LevelHandle findLevel( String name ) { DesignElement element = module.findLevel( name ); if ( element == null ) return null; return (LevelHandle) element.getHandle( element.getRoot( ) ); } /** * Finds a dimension element by name in this module and the included * modules. * * @param name * name of the dimension to find * @return the dimension handle if found, otherwise null */ public final DimensionHandle findDimension( String name ) { Dimension element = module.findDimension( name ); if ( element == null ) return null; return (DimensionHandle) element.getHandle( element.getRoot( ) ); } /** * Finds the image with the given name. * * @param name * the image name * @return embedded image with the given name. Return <code>null</code>, if * not found. */ public final EmbeddedImage findImage( String name ) { return module.findImage( name ); } /** * Finds the config variable with the given name. * * @param name * the variable name * @return the config variable with the given name. Return <code>null</code> * , if not found. */ public final ConfigVariable findConfigVariable( String name ) { return module.findConfigVariabel( name ); } /** * Finds the custom color with the given name. * * @param name * the color name * @return the custom color with the given name. Return <code>null</code> if * it's not found. */ public final CustomColor findColor( String name ) { return module.findColor( name ); } /** * Finds a master page by name in this module and the included modules. * * @param name * the name of the master page * @return a handle to the master page, or <code>null</code> if the page is * not found */ public final MasterPageHandle findMasterPage( String name ) { DesignElement element = module.findPage( name ); if ( element == null ) return null; return (MasterPageHandle) element.getHandle( element.getRoot( ) ); } /** * Finds a parameter by name in this module and the included modules. * * @param name * the name of the parameter * @return a handle to the parameter, or <code>null</code> if the parameter * is not found */ public final ParameterHandle findParameter( String name ) { DesignElement element = module.findParameter( name ); if ( element == null || !( element instanceof Parameter ) ) return null; return (ParameterHandle) element.getHandle( element.getRoot( ) ); } /** * Finds a style by its name in this module. The style with the same name, * which is defined the included module, will never be returned. * * @param name * name of the style * @return a handle to the style, or <code>null</code> if the style is not * found */ public final SharedStyleHandle findNativeStyle( String name ) { StyleElement style = module.findNativeStyle( name ); if ( style == null ) return null; return (SharedStyleHandle) style.getHandle( module ); } /** * Finds a style by its name in this module and the included modules. * * @param name * name of the style * @return a handle to the style, or <code>null</code> if the style is not * found */ public final SharedStyleHandle findStyle( String name ) { StyleElement style = module.findStyle( name ); if ( style == null ) return null; return (SharedStyleHandle) style.getHandle( style.getRoot( ) ); } /** * Finds a theme by its name in this module and the included modules. * * @param name * name of the theme * @return a handle to the theme, or <code>null</code> if the theme is not * found */ public final ThemeHandle findTheme( String name ) { Theme theme = module.findTheme( name ); if ( theme == null ) return null; return (ThemeHandle) theme.getHandle( theme.getRoot( ) ); } /** * Finds a report item theme by its name in this module and its included * libraries. * * @param name * name of the report item theme * @return a handle to the report item theme, or null if not found */ public final ReportItemThemeHandle findReportItemTheme( String name ) { ReportItemTheme theme = module.findReportItemTheme( name ); if ( theme == null ) return null; return (ReportItemThemeHandle) theme.getHandle( theme.getRoot( ) ); } /** * Returns the name of the author of the design report. * * @return the name of the author. */ public final String getAuthor( ) { return getStringProperty( AUTHOR_PROP ); } /** * Gets the subject of the module. * * @return the subject of the module. */ public final String getSubject( ) { return getStringProperty( SUBJECT_PROP ); } /** * Sets the subject of the module. * * @param subject * the subject of the module. * @throws SemanticException */ public final void setSubject( String subject ) throws SemanticException { setStringProperty( SUBJECT_PROP, subject ); } /** * Gets comments property value. * * @return the comments property value. */ public final String getComments( ) { return getStringProperty( COMMENTS_PROP ); } /** * Sets the comments value. * * @param comments * the comments. * @throws SemanticException */ public final void setComments( String comments ) throws SemanticException { setStringProperty( COMMENTS_PROP, comments ); } /** * Returns the command stack that manages undo/redo operations for the * design. * * @return a command stack * * @see CommandStack */ public final CommandStack getCommandStack( ) { return module.getActivityStack( ); } /** * Returns a slot handle to work with the top-level components within the * report. * * @return A handle for working with the components. */ public SlotHandle getComponents( ) { return null; } /** * Returns the name of the tool that created the design. * * @return the name of the tool */ public final String getCreatedBy( ) { return getStringProperty( CREATED_BY_PROP ); } /** * Returns a slot handle to work with the data sets within the report. Note * that the order of the data sets within the slot is unimportant. * * @return A handle for working with the data sets. */ public SlotHandle getDataSets( ) { return null; } /** * Gets the slot handle to work with all cube elements within the report. * * @return cube slot handle */ public abstract SlotHandle getCubes( ); /** * Returns a slot handle to work with the data sources within the report. * Note that the order of the data sources within the slot is unimportant. * * @return A handle for working with the data sources. */ public SlotHandle getDataSources( ) { return null; } /** * Returns the default units for the design. These are the units that are * used for dimensions that don't explicitly specify units. * * @return the default units for the design. * @see org.eclipse.birt.report.model.api.metadata.DimensionValue */ public final String getDefaultUnits( ) { return module.getUnits( ); } /** * Sets the default units for the design. These are the units that are used * for dimensions that don't explicitly specify units. * <p> * * For a report design, it allows the following constants that defined in * <code> * {@link org.eclipse.birt.report.model.api.elements.DesignChoiceConstants} * </code>: * <ul> * <li><code>UNITS_IN</code></li> * <li><code>UNITS_CM</code></li> * <li><code> * UNITS_MM</code></li> * <li><code>UNITS_PT</code></li> * </ul> * * @param units * the default units for the design. * @throws SemanticException * if the input unit is not one of allowed. * * @see org.eclipse.birt.report.model.api.metadata.DimensionValue */ public final void setDefaultUnits( String units ) throws SemanticException { setStringProperty( UNITS_PROP, units ); } /* * (non-Javadoc) * * @see org.eclipse.birt.report.model.api.DesignElementHandle#getElement() */ public final DesignElement getElement( ) { return module; } /** * Finds the handle to an element by a given element ID. Returns <code>null * </code> if the ID is not valid, or if this session does not use IDs. * * @param id * ID of the element to find * @return A handle to the element, or <code>null</code> if the element was * not found or this session does not use IDs. */ public final DesignElementHandle getElementByID( long id ) { DesignElement element = module.getElementByID( id ); if ( element == null ) return null; return element.getHandle( module ); } /** * Returns a list containing errors during parsing the design file. * * @return a list containing parsing errors. Each element in the list is * <code>ErrorDetail</code>. * * @see ErrorDetail */ public final List getErrorList( ) { return module.getErrorList( ); } /** * Returns the file name of the design. This is the name of the file from * which the design was read, or the name to which the design was last * written. * * @return the file name */ public final String getFileName( ) { return module.getFileName( ); } /** * Returns the flatten Parameters/ParameterGroups of the design. This method * put all Parameters and ParameterGroups into a list then return it. The * return list is sorted by on the display name of the parameters. * * @return the sorted, flatten parameters and parameter groups. */ public List getFlattenParameters( ) { return Collections.emptyList( ); } /** * Returns an external file that provides help information for the report. * * @return the name of an external file */ public final String getHelpGuide( ) { return getStringProperty( HELP_GUIDE_PROP ); } /** * Returns the script called when the report starts executing. * * @return the script called when the report starts executing */ public final String getInitialize( ) { return getStringProperty( INITIALIZE_METHOD ); } /** * Returns a slot handle to work with the master pages within the report. * Note that the order of the master pages within the slot is unimportant. * * @return A handle for working with the master pages. */ public SlotHandle getMasterPages( ) { return null; } /** * Finds user-defined messages for the current thread's locale. * * @param resourceKey * Resource key of the user-defined message. * @return the corresponding locale-dependent messages. Return <code>null * </code> if resoueceKey is blank. * @see #getMessage(String, Locale) */ public final String getMessage( String resourceKey ) { return getModule( ).getMessage( resourceKey ); } /** * Finds user-defined messages for the given locale. * <p> * First we look up in the report itself, then look into the referenced * message file. Each search uses a reduced form of Java locale-driven * search algorithm: Language&Country, language, default. * * @param resourceKey * Resource key of the user defined message. * @param locale * locale of message, if the input <code>locale</code> is <code> * null</code> , the locale for the current thread will be used * instead. * @return the corresponding locale-dependent messages. Return <code>null * </code> if resoueceKey is blank. */ public final String getMessage( String resourceKey, Locale locale ) { return getModule( ) .getMessage( resourceKey, ULocale.forLocale( locale ) ); } /** * Finds user-defined messages for the given locale. * <p> * First we look up in the report itself, then look into the referenced * message file. Each search uses a reduced form of Java locale-driven * search algorithm: Language&Country, language, default. * * @param resourceKey * Resource key of the user defined message. * @param locale * locale of message, if the input <code>locale</code> is <code> * null</code> , the locale for the current thread will be used * instead. * @return the corresponding locale-dependent messages. Return <code>null * </code> if resoueceKey is blank. */ public final String getMessage( String resourceKey, ULocale locale ) { return getModule( ).getMessage( resourceKey, locale ); } /** * Return a list of user-defined message keys. The list contained resource * keys defined in the report itself and the keys defined in the referenced * message files for the current thread's locale. The list returned contains * no duplicate keys. * * @return a list of user-defined message keys. */ public final List getMessageKeys( ) { return getModule( ).getMessageKeys( ); } /** * Returns a slot handle to work with the top-level parameters and parameter * groups within the report. The order that the items appear within the slot * determines the order in which they appear in the "requester" UI. * * @return A handle for working with the parameters and parameter groups. */ public SlotHandle getParameters( ) { return null; } /** * Returns a cascading parameter group handle with the given group name * * @param groupName * name of the cascading parameter group. * @return a handle to the cascading parameter group. Returns <code>null * </code> if the cascading group with the given name is not found. */ public final CascadingParameterGroupHandle findCascadingParameterGroup( String groupName ) { DesignElement element = module.findParameter( groupName ); if ( element == null || !( element instanceof CascadingParameterGroup ) ) return null; return (CascadingParameterGroupHandle) element.getHandle( element .getRoot( ) ); } /** * Returns a slot handle to work with the styles within the report. Note * that the order of the styles within the slot is unimportant. * * @return A handle for working with the styles. */ public SlotHandle getStyles( ) { return null; } /** * Gets a handle to deal with a translation. A translation is identified by * its resourceKey and locale. * * @param resourceKey * the resource key * @param locale * the locale information * * @return corresponding <code>TranslationHandle</code>. Or return <code> * null</code> if the translation is not found in the design. * * @see TranslationHandle */ public final TranslationHandle getTranslation( String resourceKey, String locale ) { Translation translation = module.findTranslation( resourceKey, locale ); if ( translation != null ) return translation.handle( getModule( ) ); return null; } /** * Returns a string array containing all the resource keys of user-defined * translations for the report. * * @return a string array containing message resource keys, return <code> * null</code> if there is no messages defined in the design. */ public final String[] getTranslationKeys( ) { return module.getTranslationResourceKeys( ); } /** * Gets a list of translation defined on the report. The content of the list * is the corresponding <code>TranslationHandle</code>. * * @return a list containing TranslationHandles defined on the report or * <code>null</code> if the design has no any translations. * * @see TranslationHandle */ public final List getTranslations( ) { List translations = module.getTranslations( ); if ( translations == null ) return null; List translationHandles = new ArrayList( ); for ( int i = 0; i < translations.size( ); i++ ) { translationHandles.add( ( (Translation) translations.get( i ) ) .handle( getModule( ) ) ); } return translationHandles; } /** * Returns a list containing warnings during parsing the design file. * * @return a list containing parsing warnings. Each element in the list is * <code>ErrorDetail</code>. * * @see ErrorDetail */ public final List getWarningList( ) { return module.getWarningList( ); } /** * Returns the iterator over all embedded images of this module instance. * Each one is the instance of <code>EmbeddedImageHandle</code> * * @return the iterator over all embedded images. * * @see EmbeddedImageHandle */ public Iterator imagesIterator( ) { return Collections.emptyList( ).iterator( ); } /** * Returns the list of embedded images, including the one from libraries. * Each one is the instance of <code>EmbeddedImageHandle</code> * * @return the list of embedded images. * * @see EmbeddedImageHandle */ public final List getAllImages( ) { return getStructureList( IMAGES_PROP ); } /** * Determines if the design has changed since it was last read from, or * written to, the file. The dirty state reflects the action of the command * stack. If the user saves the design and then changes it, the design is * dirty. If the user then undoes the change, the design is no longer dirty. * * @return <code>true</code> if the design has changed since the last load * or save; <code>false</code> if it has not changed. */ public final boolean needsSave( ) { String version = module.getVersionManager( ).getVersion( ); if ( version != null ) { boolean isSupportedUnknownVersion = false; if( module.getOptions( ) != null ) { isSupportedUnknownVersion = module.getOptions( ).isSupportedUnknownVersion( ); } List versionInfos = ModelUtil.checkVersion( version, isSupportedUnknownVersion ); if ( !versionInfos.isEmpty( ) ) return true; } return module.isDirty( ); } /** * Calls to inform a save is successful. Must be called after a successful * completion of a save done using <code>serialize</code>. */ public final void onSave( ) { module.onSave( ); } /** * Removes a given validation listener. If the listener not registered, then * the request is silently ignored. * * @param listener * the listener to de-register * @return <code>true</code> if <code>listener</code> is sucessfully * removed. Otherwise <code>false</code>. */ public final boolean removeValidationListener( IValidationListener listener ) { return getModule( ).removeValidationListener( listener ); } /** * Checks the element name in name space of this report. * * <ul> * <li>If the element name is required and duplicate name is found in name * space, rename the element with a new unique name. * <li>If the element name is not required, clear the name. * </ul> * * @param elementHandle * the element handle whose name is need to check. */ public final void rename( DesignElementHandle elementHandle ) { rename( (DesignElementHandle) null, elementHandle ); } /** * Checks element name is unique in container. * * @param containerHandle * container of element * @param elementHandle * element handle */ public void rename( DesignElementHandle containerHandle, DesignElementHandle elementHandle ) { if ( elementHandle == null ) return; if ( containerHandle == null ) { module.rename( elementHandle.getElement( ) ); return; } // Specially for case rename copied style in theme. if ( elementHandle instanceof StyleHandle ) { if ( containerHandle instanceof ThemeHandle ) { String name = ( (ThemeHandle) containerHandle ) .makeUniqueStyleName( elementHandle.getName( ) ); elementHandle.getElement( ).setName( name ); } else if ( containerHandle instanceof ReportDesignHandle ) module.rename( elementHandle.getElement( ) ); return; } // If both have root, let name helper decide unique name // Now only for rename level name in hierarchy. module.rename( containerHandle.getElement( ), elementHandle.getElement( ) ); } /** * Replaces the old config variable with the new one. * * @param oldVar * the old config variable * @param newVar * the new config variable * @throws SemanticException * if the old config variable is not found or the name of new * one is empty. * */ public void replaceConfigVariable( ConfigVariable oldVar, ConfigVariable newVar ) throws SemanticException { throw new IllegalOperationException( ); } /** * Replaces the old embedded image with the new one. * * @param oldVar * the old embedded image * @param newVar * the new embedded image * @throws SemanticException * if the old image is not found or the name of new one is * empty. */ public void replaceImage( EmbeddedImage oldVar, EmbeddedImage newVar ) throws SemanticException { throw new IllegalOperationException( ); } /** * Saves the module to an existing file name. Call this only when the file * name has been set. * * @throws IOException * if the file cannot be saved on the storage * * @see #saveAs(String) */ public final void save( ) throws IOException { String fileName = getFileName( ); if ( fileName == null ) return; module.prepareToSave( ); String resolvedFileName = URIUtil.getLocalPath( fileName ); if ( resolvedFileName != null ) fileName = resolvedFileName; module.getWriter( ).write( new File( fileName ) ); module.onSave( ); } /** * Saves the design to the file name provided. The file name is saved in the * design, and subsequent calls to <code>save( )</code> will save to this * new name. * * @param newName * the new file name * @throws IOException * if the file cannot be saved * * @see #save() */ public final void saveAs( String newName ) throws IOException { setFileName( newName ); save( ); } /** * Writes the report design to the given output stream. The caller must call * <code>onSave</code> if the save succeeds. * * @param out * the output stream to which the design is written. * @throws IOException * if the file cannot be written to the output stream * successfully. */ public final void serialize( OutputStream out ) throws IOException { assert out != null; module.prepareToSave( ); module.getWriter( ).write( out ); module.onSave( ); } /** * Sets the name of the author of the design report. * * @param author * the name of the author. */ public final void setAuthor( String author ) { try { setStringProperty( AUTHOR_PROP, author ); } catch ( SemanticException e ) { throw new IllegalOperationException( ); } } /** * Returns the name of the tool that created the design. * * @param toolName * the name of the tool */ public final void setCreatedBy( String toolName ) { try { setStringProperty( CREATED_BY_PROP, toolName ); } catch ( SemanticException e ) { throw new IllegalOperationException( ); } } /** * Sets the design file name. This method will send notifications instance * of <code>AttributeEvent</code> to all the attribute listeners registered * in the module. * * @param newName * the new file name. It may contain the relative/absolute path * information. This name must include the file name with the * filename extension. */ public final void setFileName( String newName ) { module.setFileName( newName ); if ( !StringUtil.isBlank( newName ) ) { URL systemId = URIUtilImpl.getDirectory( newName ); if ( systemId != null ) module.setSystemId( systemId ); URL location = URIUtilImpl.getURLPresentation( newName ); module.setLocation( location ); } AttributeEvent event = new AttributeEvent( module, AttributeEvent.FILE_NAME_ATTRIBUTE ); module.broadcastFileNameEvent( event ); } /** * Sets an external file that provides help information for the report. * * @param helpGuide * the name of an external file */ public final void setHelpGuide( String helpGuide ) { try { setStringProperty( HELP_GUIDE_PROP, helpGuide ); } catch ( SemanticException e ) { throw new IllegalOperationException( ); } } /** * Sets the script called when the report starts executing. * * @param value * the script to set. */ public final void setInitialize( String value ) { try { setStringProperty( INITIALIZE_METHOD, value ); } catch ( SemanticException e ) { throw new IllegalOperationException( ); } } /** * Returns all style element handles that this modules and the included * modules contain. * * @return all style element handles that this modules and the included * modules contain. */ public List getAllStyles( ) { return Collections.emptyList( ); } /** * Returns theme handles according the input level. * * @param level * an <code>int</code> value, which should be the one defined in * <code>IVisibleLevelControl</code>. * * @return theme handles according the input level */ public List getVisibleThemes( int level ) { return Collections.emptyList( ); } /** * Returns report item theme handles according the input level. * * @param level * an <code>int</code> value, which should be the one defined in * <code>IVisibleLevelControl</code>. * * @return theme handles according the input level */ public List<ReportItemThemeHandle> getVisibleReportItemThemes( int level, String type ) { return Collections.emptyList( ); } /** * Returns parameters and parameter groups on the module. Those parameters * included in the parameter groups are not included in the return list. * * @return parameters and parameter groups */ public List getParametersAndParameterGroups( ) { return Collections.emptyList( ); } /** * Returns all data source handles that this modules and the included * modules contain. * * @return all data source handles that this modules and the included * modules contain. */ public final List getAllDataSources( ) { List elementList = module.getNameHelper( ).getElements( Module.DATA_SOURCE_NAME_SPACE, IAccessControl.ARBITARY_LEVEL ); return generateHandleList( elementList ); } /** * Returns data source handles that are visible to this modules. * * @return data source handles that are visible to this modules. */ public final List getVisibleDataSources( ) { List elementList = module.getNameHelper( ).getElements( Module.DATA_SOURCE_NAME_SPACE, IAccessControl.NATIVE_LEVEL ); return generateHandleList( sortVisibleElements( elementList, IAccessControl.NATIVE_LEVEL ) ); } /** * Returns all data set handles that this modules and the included modules * contain. * * @return all data set handles that this modules and the included modules * contain. */ public final List getAllDataSets( ) { List elementList = module.getNameHelper( ).getElements( Module.DATA_SET_NAME_SPACE, IAccessControl.ARBITARY_LEVEL ); return generateHandleList( elementList ); } /** * Returns data set handles that are visible to this modules. * * @return data set handles that are visible to this modules. */ public final List getVisibleDataSets( ) { List elementList = module.getNameHelper( ).getElements( Module.DATA_SET_NAME_SPACE, IAccessControl.NATIVE_LEVEL ); return generateHandleList( sortVisibleElements( elementList, IAccessControl.NATIVE_LEVEL ) ); } /** * Returns all cube handles that this modules and the included modules * contain. * * @return all cube handles that this modules and the included modules * contain. */ public final List getAllCubes( ) { List elementList = module.getNameHelper( ).getElements( Module.CUBE_NAME_SPACE, IAccessControl.ARBITARY_LEVEL ); List cubeList = getCubeList( elementList ); return generateHandleList( cubeList ); } /** * Gets all the cube elements from the given element list. * * @param elements * @return all cube elements */ private List getCubeList( List elements ) { if ( elements == null ) return null; List cubes = new ArrayList( ); for ( int i = 0; i < elements.size( ); i++ ) { DesignElement element = (DesignElement) elements.get( i ); if ( element.getDefn( ).isKindOf( MetaDataDictionary.getInstance( ).getElement( ReportDesignConstants.CUBE_ELEMENT ) ) ) cubes.add( element ); } return cubes; } /** * Returns cube handles that are visible to this modules. * * @return cube handles that are visible to this modules. */ public final List getVisibleCubes( ) { List elementList = module.getNameHelper( ).getElements( Module.CUBE_NAME_SPACE, IAccessControl.NATIVE_LEVEL ); List cubeList = getCubeList( elementList ); return generateHandleList( sortVisibleElements( cubeList, IAccessControl.NATIVE_LEVEL ) ); } /** * Returns the embedded images which are defined on the module itself. The * embedded images defined in the included libraries will not be returned by * this method. * * @return the local embedded image list. */ public final List getVisibleImages( ) { List images = getNativeStructureList( IModuleModel.IMAGES_PROP ); return images; } /** * Returns all page handles that this modules and the included modules * contain. * * @return all page handles that this modules and the included modules * contain. */ public List getAllPages( ) { return Collections.emptyList( ); } /** * Returns all parameter handles that this modules. * * @return all parameter handles that this modules. */ public final List getAllParameters( ) { List elementList = module.getNameHelper( ) .getNameSpace( Module.PARAMETER_NAME_SPACE ).getElements( ); return generateHandleList( elementList ); } /** * Returns the libraries this report design includes directly or indirectly. * Each in the returned list is the instance of <code>LibraryHandle</code>. * * @return the libraries this report design includes directly or indirectly. */ public final List getAllLibraries( ) { return getLibraries( IAccessControl.ARBITARY_LEVEL ); } /** * Returns included libaries this report design includes directly or * indirectly within the given depth. * * @param level * the given depth * @return list of libraries. */ protected final List getLibraries( int level ) { List libraries = module.getLibraries( level ); List retLibs = new ArrayList( ); Iterator iter = libraries.iterator( ); while ( iter.hasNext( ) ) { Library library = (Library) iter.next( ); retLibs.add( library.handle( ) ); } return Collections.unmodifiableList( retLibs ); } /** * Returns the libraries this report design includes directly. Each in the * returned list is the instance of <code>LibraryHandle</code>. * * @return the libraries this report design includes directly. */ public final List getLibraries( ) { return getLibraries( IAccessControl.DIRECTLY_INCLUDED_LEVEL ); } /** * Returns the library handle with the given namespace. * * @param namespace * the library namespace * @return the library handle with the given namespace */ public final LibraryHandle getLibrary( String namespace ) { Module library = module.getLibraryWithNamespace( namespace, IAccessControl.DIRECTLY_INCLUDED_LEVEL ); if ( library == null ) return null; return (LibraryHandle) library.getHandle( library ); } /** * Returns the library handle with the given file name. The filename can * include directory information, either relative or absolute directory. And * the file should be on the local disk. * * @param fileName * the library file name. The filename can include directory * information, either relative or absolute directory. And the * file should be on the local disk. * @return the library handle with the given file name */ public final LibraryHandle findLibrary( String fileName ) { URL url = module.findResource( fileName, IResourceLocator.LIBRARY ); if ( url == null ) return null; Module library = module.getLibraryByLocation( url.toString( ) ); if ( library == null ) return null; return (LibraryHandle) library.getHandle( library ); } /** * Shifts the library to new position. This method might affect the style * reference, because the library order is changed. * * @param library * the library to shift * @param toPosn * the new position * @throws SemanticException * if error is encountered when shifting */ public void shiftLibrary( LibraryHandle library, int toPosn ) throws SemanticException { throw new IllegalOperationException( ); } /** * Returns whether this module is read-only. * * @return true, if this module is read-only. Otherwise, return false. */ public final boolean isReadOnly( ) { return module.isReadOnly( ); } /** * Returns the iterator over all included libraries. Each one is the * instance of <code>IncludeLibraryHandle</code> * * @return the iterator over all included libraries. * @see IncludedLibraryHandle */ public Iterator includeLibrariesIterator( ) { return Collections.emptyList( ).iterator( ); } /** * Includes one library with the given library file name. The new library * will be appended to the library list. * * @param libraryFileName * library file name * @param namespace * library namespace * @throws DesignFileException * if the library file is not found, or has fatal error. * @throws SemanticException * if error is encountered when handling <code>IncludeLibrary * </code> structure list. */ public void includeLibrary( String libraryFileName, String namespace ) throws DesignFileException, SemanticException { throw new IllegalOperationException( ); } /** * Drops the given library from the included libraries of this design file. * * @param library * the library to drop * @throws SemanticException * if error is encountered when handling <code>IncludeLibrary * </code> structure list. Or it maybe because that the given * library is not found in the design. Or that the library has * descedents in the current module */ public void dropLibrary( LibraryHandle library ) throws SemanticException { throw new IllegalOperationException( ); } /** * Reloads the library with the given library file path. If the library * already is included directly, reload it. If the library is not included, * exception will be thrown. * <p> * Call this method cautiously ONLY on the condition that the library file * is REALLY changed outside. After reload successfully, the command stack * is cleared. * * @param libraryToReload * the library instance * @throws SemanticException * if error is encountered when handling <code>IncludeLibrary * </code> structure list. Or it maybe because that the given * library is not found in the design. Or that the library has * descedents in the current module * @throws DesignFileException * if the library file is not found, or has fatal error. */ public void reloadLibrary( LibraryHandle libraryToReload ) throws SemanticException, DesignFileException { throw new IllegalOperationException( ); } /** * Reloads all libraries this module included. * <p> * Call this method cautiously ONLY on the condition that the library file * is REALLY changed outside. After reload successfully, the command stack * is cleared. * * {@link #reloadLibrary(LibraryHandle)} * * @throws SemanticException * @throws DesignFileException */ public void reloadLibraries( ) throws SemanticException, DesignFileException { throw new IllegalOperationException( ); } /** * Reloads the library with the given library file path. If the library * already is included directly or indirectly(that is, the reload path could * be the path of grandson of this module), reload it. If the library is not * included, exception will be thrown. * <p> * Call this method cautiously ONLY on the condition that the library file * is REALLY changed outside. After reload successfully, the command stack * is cleared. * * @param reloadPath * this is supposed to be an absolute path, not in url form. * @throws SemanticException * if error is encountered when handling <code>IncludeLibrary * </code> structure list. Or it maybe because that the given * library is not found in the design. Or that the library has * descedents in the current module * @throws DesignFileException * if the library file is not found, or has fatal error. */ public void reloadLibrary( String reloadPath ) throws SemanticException, DesignFileException { throw new IllegalOperationException( ); } /** * Drops the given library from the design and break all the parent/child * relationships. All child element will be localized in the module. * * @param library * the given library to drop * @throws SemanticException * if errors occured when drop the library.It may be because * that the library is not found in the design or that some * elements can not be localized properly. */ public void dropLibraryAndBreakExtends( LibraryHandle library ) throws SemanticException { throw new IllegalOperationException( ); } /** * Adds one attribute listener. The duplicate listener will not be added. * * @param listener * the attribute listener to add */ public final void addAttributeListener( IAttributeListener listener ) { module.addAttributeListener( listener ); } /** * Removes one attribute listener. If the listener not registered, then the * request is silently ignored. * * @param listener * the attribute listener to remove * @return <code>true</code> if <code>listener</code> is successfully * removed. Otherwise <code>false</code>. * */ public final boolean removeAttributeListener( IAttributeListener listener ) { return module.removeAttributeListener( listener ); } /** * Adds one dispose listener. The duplicate listener will not be added. * * @param listener * the dispose listener to add */ public final void addDisposeListener( IDisposeListener listener ) { module.addDisposeListener( listener ); } /** * Adds one resource change listener. The duplicate listener will not be * added. * * @param listener * the resource change listener to add */ public final void addResourceChangeListener( IResourceChangeListener listener ) { module.addResourceChangeListener( listener ); } /** * Removes one dispose listener. If the listener not registered, then the * request is silently ignored. * * @param listener * the dispose listener to remove * @return <code>true</code> if <code>listener</code> is successfully * removed. Otherwise <code>false</code>. * */ public final boolean removeDisposeListener( IDisposeListener listener ) { return module.removeDisposeListener( listener ); } /** * Removes one resource change listener. If the listener not registered, * then the request is silently ignored. * * @param listener * the resource change listener to remove * @return <code>true</code> if <code>listener</code> is successfully * removed. Otherwise <code>false</code>. * */ public final boolean removeResourceChangeListener( IResourceChangeListener listener ) { return module.removeResourceChangeListener( listener ); } /* * (non-Javadoc) * * @see org.eclipse.birt.report.model.api.DesignElementHandle#drop() */ public final void drop( ) throws SemanticException { throw new IllegalOperationException( ); } /* * (non-Javadoc) * * @see org.eclipse.birt.report.model.api.DesignElementHandle#dropAndClear() */ public final void dropAndClear( ) throws SemanticException { throw new IllegalOperationException( ); } /** * Get the base name of the customer-defined resource bundle. * * @return the base name of the customer-defined resource bundle. */ public final String getIncludeResource( ) { return getStringProperty( INCLUDE_RESOURCE_PROP ); } /** * * @return */ public final List<String> getIncludeResources( ) { return getListProperty( INCLUDE_RESOURCE_PROP ); } /** * Set the base name of the customer-defined resource bundle. The name is a * common base name, e.g: "myMessage" without the Language_Country suffix, * then the message file family can be "myMessage_en.properties", * "myMessage_zh_CN.properties" etc. The message file is stored in the same * folder as the design file. * * @param baseName * common base name of the customer-defined resource bundle. */ public final void setIncludeResource( String baseName ) { try { setProperty( INCLUDE_RESOURCE_PROP, baseName ); } catch ( SemanticException e ) { throw new IllegalOperationException( ); } } /** * Set the list of base name of the customer-defined resource bundles. The * name is a common base name, e.g: "myMessage" without the Language_Country * suffix, then the message file family can be "myMessage_en.properties", * "myMessage_zh_CN.properties" etc. The message file is stored in the same * folder as the design file. * * @param baseNameList * list of the base name */ public final void setIncludeResources( List<String> baseNameList ) { try { setProperty( INCLUDE_RESOURCE_PROP, baseNameList ); } catch ( SemanticException e ) { throw new IllegalOperationException( ); } } /** * Returns the <code>URL</code> object if the file with <code>fileName * </code> exists. This method takes the following search steps: * * <ul> * If file type is MESSAGEFILE , * <li>Search file with the file locator ( <code>IResourceLocator</code>) in * session. And Now just deal with relative file name. * * <ul> * If file type is not MESSAGEFILE, * <li>Search file taking <code>fileName * </code> as absolute file name; * <li>Search file taking <code>fileName * </code> as relative file name and basing "base" property of report * design; * <li>Search file with the file locator (<code>IResourceLocator * </code>) in session * </ul> * * @param fileName * file name to search * @param fileType * file type. The value should be one of: * <ul> * <li><code>IResourceLocator.IMAGE</code> <li><code> * IResourceLocator.LIBRARY</code> <li><code> * IResourceLocator.MESSAGEFILE</code> * </ul> * Any invalid value will be treated as <code> * IResourceLocator.IMAGE</code>. * @return the <code>URL</code> object if the file with <code>fileName * </code> is found, or null otherwise. */ public final URL findResource( String fileName, int fileType ) { return module.findResource( fileName, fileType ); } /** * Returns the <code>URL</code> object if the file with <code>fileName * </code> exists. This method takes the following search steps: * * <ul> * If file type is MESSAGEFILE , * <li>Search file with the file locator ( <code>IResourceLocator</code>) in * session. And Now just deal with relative file name. * * <ul> * If file type is not MESSAGEFILE, * <li>Search file taking <code>fileName * </code> as absolute file name; * <li>Search file taking <code>fileName * </code> as relative file name and basing "base" property of report * design; * <li>Search file with the file locator (<code>IResourceLocator * </code>) in session * </ul> * * @param fileName * file name to search * @param fileType * file type. The value should be one of: * <ul> * <li><code>IResourceLocator.IMAGE</code> <li><code> * IResourceLocator.LIBRARY</code> <li><code> * IResourceLocator.MESSAGEFILE</code> * </ul> * Any invalid value will be treated as <code> * IResourceLocator.IMAGE</code>. * @param appContext * The map containing the user's information * @return the <code>URL</code> object if the file with <code>fileName * </code> is found, or null otherwise. */ public final URL findResource( String fileName, int fileType, Map appContext ) { return module.findResource( fileName, fileType, appContext ); } /** * Gets the result style sheet with given file name of an external CSS2 * resource. * * @param fileName * the file name of the external CSS resource * @return the <code>CssStyleSheetHandle</code> if the external resource is * successfully loaded * @throws StyleSheetException * thrown if the resource is not found, or there are syntax * errors in the resource */ public CssStyleSheetHandle openCssStyleSheet( String fileName ) throws StyleSheetException { throw new IllegalOperationException( ); } /** * Gets the result style sheet with given file name of an external CSS2 * resource. * * @param is * the input stream of the resource * @return the <code>CssStyleSheetHandle</code> if the external resource is * successfully loaded * @throws StyleSheetException * thrown if the resource is not found, or there are syntax * errors in the resource */ public CssStyleSheetHandle openCssStyleSheet( InputStream is ) throws StyleSheetException { throw new IllegalOperationException( ); } /** * Imports the selected styles in a <code>CssStyleSheetHandle</code> to the * module. Each in the list is instance of <code>SharedStyleHandle</code> * .If any style selected has a duplicate name with that of one style * already existing in the report design, this method will rename it and * then add it to the design. * * @param stylesheet * the style sheet handle that contains all the selected styles * @param selectedStyles * the selected style list * */ public void importCssStyles( CssStyleSheetHandle stylesheet, List selectedStyles ) { throw new IllegalOperationException( ); } /** * Sets the theme to a report. * * @param themeName * the name of the theme * @throws SemanticException */ public void setThemeName( String themeName ) throws SemanticException { throw new IllegalOperationException( ); } /** * Returns the refresh rate when viewing the report. * * @return the refresh rate */ public final ThemeHandle getTheme( ) { Theme theme = module.getTheme( module ); if ( theme == null ) return null; return (ThemeHandle) theme.getHandle( theme.getRoot( ) ); } /** * Sets the theme to a report. * * @param theme * the theme instance * @throws SemanticException */ public void setTheme( ThemeHandle theme ) throws SemanticException { throw new IllegalOperationException( ); } /** * Gets the location information of the module. * * @return the location information of the module */ final String getLocation( ) { return module.getLocation( ); } /** * Checks whether there is an included library in this module, which has the * same absolute path as that of the given library. * * @param library * the library to check * @return true if there is an included library in this module, which has * the same absolute path as that the given library, otherwise false */ public final boolean isInclude( LibraryHandle library ) { return module.getLibraryByLocation( library.getLocation( ) ) != null; } /** * Finds a template parameter definition by its name in this module and the * included modules. * * @param name * name of the template parameter definition * @return a handle to the template parameter definition, or <code>null * </code> if the template parameter definition is not found */ final TemplateParameterDefinitionHandle findTemplateParameterDefinition( String name ) { TemplateParameterDefinition templateParam = module .findTemplateParameterDefinition( name ); if ( templateParam == null ) return null; return templateParam.handle( templateParam.getRoot( ) ); } /** * Returns all template parameter definition handles that this modules and * the included modules contain. * * @return all template parameter definition handles that this modules and * the included modules contain. */ List getAllTemplateParameterDefinitions( ) { return Collections.emptyList( ); } /** * Returns the static description for the module. * * @return the static description to display */ public final String getDescription( ) { return getStringProperty( IModuleModel.DESCRIPTION_PROP ); } /** * Returns the localized description for the module. If the localized * description for the description resource key is found, it will be * returned. Otherwise, the static description will be returned. * * @return the localized description for the module */ public final String getDisplayDescription( ) { return getExternalizedValue( IModuleModel.DESCRIPTION_ID_PROP, IModuleModel.DESCRIPTION_PROP ); } /** * Sets the description of the module. Sets the static description itself. * If the module is to be externalized, then set the description ID * separately. * * @param description * the new description for the module * @throws SemanticException * if the property is locked. */ public final void setDescription( String description ) throws SemanticException { setStringProperty( IModuleModel.DESCRIPTION_PROP, description ); } /** * Returns the resource key of the static description of the module. * * @return the resource key of the static description */ public final String getDescriptionKey( ) { return getStringProperty( IModuleModel.DESCRIPTION_ID_PROP ); } /** * Sets the resource key of the static description of the module. * * @param resourceKey * the resource key of the static description * * @throws SemanticException * if the resource key property is locked. */ public final void setDescriptionKey( String resourceKey ) throws SemanticException { setStringProperty( IModuleModel.DESCRIPTION_ID_PROP, resourceKey ); } /** * Gets the title property value. * * @return the title property value. */ public final String getTitle( ) { return getStringProperty( IModuleModel.TITLE_PROP ); } /** * Sets the title value. * * @param title * the title. * @throws SemanticException */ public final void setTitle( String title ) throws SemanticException { setStringProperty( IModuleModel.TITLE_PROP, title ); } /** * Gets the title key. * * @return the title key. */ public final String getTitleKey( ) { return getStringProperty( IModuleModel.TITLE_ID_PROP ); } /** * Sets the title key. * * @param titleKey * the title key. * @throws SemanticException */ public final void setTitleKey( String titleKey ) throws SemanticException { setStringProperty( IModuleModel.TITLE_ID_PROP, titleKey ); } /** * Initializes the report design when it is just created. * <p> * Set the value to the properties on repot design element which need the * initialize valuel. * * All initialize operations will not go into the command stack and can not * be undo redo. * * @param properties * the property name value pairs.Those properties in the map are * which need to be initialized. * @throws SemanticException * SemamticException will throw out when the give properties map * contians invlid property name or property value. */ public final void initializeModule( Map properties ) throws SemanticException { // if this report deisgn has been initialized, return. if ( isInitialized ) return; Module root = (Module) getElement( ); // initialize the properties for the reprot design. Iterator itre = properties.entrySet( ).iterator( ); while ( itre.hasNext( ) ) { Entry entry = (Entry) itre.next( ); String name = (String) entry.getKey( ); try { Object value = PropertyValueValidationUtil.validateProperty( this, name, entry.getValue( ) ); root.setProperty( name, value ); } catch ( SemanticException e ) { // Do Nothing } } isInitialized = true; } /** * Returns the encoding of the design/library file. Currently, BIRT only * support UnicodeUtil.SIGNATURE_UTF_8. * * @return the encoding of the file */ public final String getFileEncoding( ) { return UnicodeUtil.SIGNATURE_UTF_8; } /** * Gets symbolic name of this module if defined. This property is needed * when search resources in fragments. Usually it should be the plug-in id * of the host plug-in. * * @return the symbolica name of this module */ public final String getSymbolicName( ) { // This method should be deleted. return null; } /** * Sets symbolic name of this module. This property is needed when search * resources in fragments. Usually it should be the plug-in id of the host * plug-in. * * @param symbolicName * @throws SemanticException */ public final void setSymbolicName( String symbolicName ) throws SemanticException { // This method should be deleted. } /** * Returns the system id of the module. It is the URL path of the module. * * @return the system id of the module */ public final URL getSystemId( ) { return module.getSystemId( ); } /** * Removes special script lib. * * @param scriptLib * script lib * @throws SemanticException */ public final void dropScriptLib( ScriptLib scriptLib ) throws SemanticException { ElementPropertyDefn propDefn = module.getPropertyDefn( SCRIPTLIBS_PROP ); if ( scriptLib == null ) return; ComplexPropertyCommand cmd = new ComplexPropertyCommand( getModule( ), getElement( ) ); cmd.removeItem( new StructureContext( getElement( ), propDefn, null ), scriptLib ); } /** * Removes the given included script. * * @param includeScript * the included script * @throws SemanticException */ public final void dropIncludeScript( IncludeScript includeScript ) throws SemanticException { if ( includeScript == null ) return; ElementPropertyDefn propDefn = module .getPropertyDefn( INCLUDE_SCRIPTS_PROP ); ComplexPropertyCommand cmd = new ComplexPropertyCommand( getModule( ), getElement( ) ); cmd.removeItem( new StructureContext( getElement( ), propDefn, null ), includeScript ); } /** * Removes special script lib handle. * * @param scriptLibHandle * script lib handle * @throws SemanticException */ public final void dropScriptLib( ScriptLibHandle scriptLibHandle ) throws SemanticException { ElementPropertyDefn propDefn = module.getPropertyDefn( SCRIPTLIBS_PROP ); if ( scriptLibHandle == null ) return; ComplexPropertyCommand cmd = new ComplexPropertyCommand( getModule( ), getElement( ) ); cmd.removeItem( new StructureContext( getElement( ), propDefn, null ), scriptLibHandle.getStructure( ) ); } /** * Removes all script libs. * * @throws SemanticException */ public final void dropAllScriptLibs( ) throws SemanticException { List scriptLibs = getFilteredStructureList( SCRIPTLIBS_PROP, ScriptLib.SCRIPTLIB_NAME_MEMBER ); if ( scriptLibs == null ) return; int count = scriptLibs.size( ); for ( int i = count - 1; i >= 0; --i ) { ScriptLibHandle scriptLibHandle = (ScriptLibHandle) scriptLibs .get( i ); dropScriptLib( scriptLibHandle ); } } /** * Returns the iterator over all script libs. Each one is the instance of * <code>ScriptLibHandle</code>. * <p> * * @return the iterator over script libs. * @see ScriptLibHandle */ public final Iterator scriptLibsIterator( ) { return getFilteredStructureList( SCRIPTLIBS_PROP, ScriptLib.SCRIPTLIB_NAME_MEMBER ).iterator( ); } /** * Returns all script libs. * * @return list which structure is <code>ScriptLibHandle</code> */ public final List getAllScriptLibs( ) { return getFilteredStructureList( SCRIPTLIBS_PROP, ScriptLib.SCRIPTLIB_NAME_MEMBER ); } /** * Gets script lib though name * * @param name * name of script lib * @return script lib */ public final ScriptLib findScriptLib( String name ) { List scriptLibs = getListProperty( SCRIPTLIBS_PROP ); if ( scriptLibs == null || scriptLibs.isEmpty( ) ) return null; for ( int i = 0; i < scriptLibs.size( ); ++i ) { ScriptLib scriptLib = (ScriptLib) scriptLibs.get( i ); if ( scriptLib.getName( ).equals( name ) ) { return scriptLib; } } return null; } /** * Shifts jar file from source position to destination position. For * example, if a list has A, B, C scriptLib in order, when move A scriptLib * to <code>newPosn</code> with the value 1, the sequence becomes B, A, C. * * @param sourceIndex * source position. The range is <code>sourceIndex &gt;= 0 && * sourceIndex &lt; list.size()</code> * @param destIndex * destination position.The range is <code> destIndex &gt;= 0 && * destIndex &lt; list.size()</code> * @throws SemanticException */ public final void shiftScriptLibs( int sourceIndex, int destIndex ) throws SemanticException { ElementPropertyDefn propDefn = module.getPropertyDefn( SCRIPTLIBS_PROP ); ComplexPropertyCommand cmd = new ComplexPropertyCommand( getModule( ), getElement( ) ); cmd.moveItem( new StructureContext( getElement( ), propDefn, null ), sourceIndex, destIndex ); } /** * Shifts included script from source position to destination position. For * example, if a list has A, B, C scriptLib in order, when move Am * includeScript to <code>newPosn</code> with the value 1, the sequence * becomes B, A, C. * * @param sourceIndex * source position. The range is <code>sourceIndex &gt;= 0 && * sourceIndex &lt; list.size()</code> * @param destIndex * destination position.The range is <code> destIndex &gt;= 0 && * destIndex &lt; list.size()</code> * @throws SemanticException */ public final void shifIncludeScripts( int sourceIndex, int destIndex ) throws SemanticException { ElementPropertyDefn propDefn = module .getPropertyDefn( INCLUDE_SCRIPTS_PROP ); ComplexPropertyCommand cmd = new ComplexPropertyCommand( getModule( ), getElement( ) ); cmd.moveItem( new StructureContext( getElement( ), propDefn, null ), sourceIndex, destIndex ); } /** * Add script lib * * @param scriptLib * script lib * @throws SemanticException */ public final void addScriptLib( ScriptLib scriptLib ) throws SemanticException { ElementPropertyDefn propDefn = module.getPropertyDefn( SCRIPTLIBS_PROP ); ComplexPropertyCommand cmd = new ComplexPropertyCommand( getModule( ), getElement( ) ); cmd.addItem( new StructureContext( getElement( ), propDefn, null ), scriptLib ); } /** * Adds include script. * * @param includeScript * the include script * @throws SemanticException */ public final void addIncludeScript( IncludeScript includeScript ) throws SemanticException { ElementPropertyDefn propDefn = module .getPropertyDefn( INCLUDE_SCRIPTS_PROP ); ComplexPropertyCommand cmd = new ComplexPropertyCommand( getModule( ), getElement( ) ); cmd.addItem( new StructureContext( getElement( ), propDefn, null ), includeScript ); } /** * Sets the resource folder for this module. * * @param resourceFolder * the folder to set */ public final void setResourceFolder( String resourceFolder ) { module.setResourceFolder( resourceFolder ); } /** * Gets the resource folder set in this module. * * @return the resource folder set in this module */ public final String getResourceFolder( ) { return module.getResourceFolder( ); } /** * Looks up line number of the element in xml source given an element ID. * Returns 1 if no line number of the element exists with the given ID. * * @param id * The id of the element to find. * @return The line number of the element given the element id, or 1 if the * element can't be found or if IDs are not enabled. * @deprecated new method see {@link #getLineNo(Object)} */ public final int getLineNoByID( long id ) { return module.getLineNoByID( id ); } /** * looks up line number of the element\property\structure, in xml source * with given xPaht. Returns 1 if there is no corresponding * element\property\structure. * * @param obj * The xPath of the element\property\structure, it should be * unique in an report file. * @return The line number of the element\property\structure, or 1 if * corresponding item does not exist. */ public final int getLineNo( Object obj ) { if ( obj instanceof StructureHandle ) { IStructure struct = ( (StructureHandle) obj ).getStructure( ); if ( LineNumberInfo.isLineNumberSuppoerted( struct ) ) return module.getLineNo( obj ); } else if ( obj instanceof DesignElementHandle ) { return module .getLineNo( ( (DesignElementHandle) obj ).getElement( ) ); } else if ( obj instanceof PropertyHandle || obj instanceof SlotHandle ) { return module.getLineNo( obj ); } return 1; } /** * Returns the version for the opened design file. If the report/library is * newly created, the version is <code>null</code>. Only the opened/saved * report/library have the version information. * <p> * Whenever the report/library is save, the version becomes <code> * DesignSchemaConstants.REPORT_VERSION</code> . That is, the saved * report/library always have the latest version. * * @return the design file version number */ public final String getVersion( ) { String retVersion = module.getVersionManager( ).getVersion( ); return retVersion; } /** * Returns the iterator over all included scripts. Each one is the instance * of <code>IncludeScriptHandle</code> * * @return the iterator over all included scripts. * @see IncludeScriptHandle */ public final Iterator includeScriptsIterator( ) { PropertyHandle propHandle = getPropertyHandle( INCLUDE_SCRIPTS_PROP ); return propHandle == null ? Collections.emptyList( ).iterator( ) : propHandle.iterator( ); } /** * Gets all included scripts. Includes those defined in the libraries. * * @return the list of included script. Each item is an instance of <code> * IncludeScriptHandle</code> . */ public final List getAllIncludeScripts( ) { return getFilteredStructureList( INCLUDE_SCRIPTS_PROP, IncludeScript.FILE_NAME_MEMBER ); } /* * (non-Javadoc) * * @see org.eclipse.birt.report.model.api.DesignElementHandle#copy() */ public final IDesignElement copy( ) { // for the design/library, should not call copy for paste policy since // don't expect localization for extends-related properties. try { return (IDesignElement) ( (Module) getElement( ) ) .doClone( DummyCopyPolicy.getInstance( ) ); } catch ( CloneNotSupportedException e ) { assert false; } return null; } /** * Sorts visible elements. Check value in design handle and libraries and * sort the sequence as list in slot handle. * * @param nameSpaceList * the list contains elements from name space * @param level * level * * @return the list contains sorted design elements. */ protected final List sortVisibleElements( List nameSpaceList, int level ) { // Sort element in namespace List<ModuleHandleImpl> modules = new ArrayList<ModuleHandleImpl>( ); if ( nameSpaceList.size( ) == 0 ) return modules; // Libraries modules = getVisibleModules( level ); return checkVisibleElements( nameSpaceList, modules ); } /** * Gets the visible modules. * * @param level * @return */ protected List<ModuleHandleImpl> getVisibleModules( int level ) { List<ModuleHandleImpl> modules = new ArrayList<ModuleHandleImpl>( ); modules.add( this ); modules.addAll( getLibraries( level ) ); return modules; } /** * Checks visible elements * * @param nameSpaceList * the list contains elements from name space * @param modules * the list contains design handle and library handle * @param slotID * slot id * @return the list contains sorted design elements. */ private List checkVisibleElements( List nameSpaceList, List modules ) { assert modules != null; List resultList = new ArrayList( ); List<Module> moduleList = new ArrayList<Module>( ); for ( int i = 0; i < modules.size( ); i++ ) { ModuleHandleImpl moduleHandle = (ModuleHandleImpl) modules.get( i ); moduleList.add( moduleHandle.getModule( ) ); } for ( int i = 0; i < nameSpaceList.size( ); ++i ) { DesignElement content = (DesignElement) nameSpaceList.get( i ); if ( moduleList.contains( content.getRoot( ) ) ) { resultList.add( content ); } } return resultList; } /** * Generates a list of element handles according to the given element list. * Each content in the return list is generated use <code>element.getHandle( * Module )</code> * * @param elementList * a list of elements. * @return a list of element handles. */ protected List generateHandleList( List elementList ) { List handleList = new ArrayList( ); Iterator iter = elementList.iterator( ); while ( iter.hasNext( ) ) { DesignElement element = (DesignElement) iter.next( ); Module root = element.getRoot( ); assert root != null; handleList.add( element.getHandle( root ) ); } return handleList; } /** * Gets all the shared dimensions defined or accessed by this module. * * @return */ public List<DimensionHandle> getAllSharedDimensions( ) { return Collections.emptyList( ); } /** * Checks the report if it is set in options. */ public void checkReportIfNecessary( ) { ModuleOption options = module.getOptions( ); if ( options == null || options.useSemanticCheck( ) ) checkReport( ); } /** * Sets options to the module. * * @param options */ public void setOptions( Map options ) { module.setOptions( options ); } /** * Gets the options set in the module. * * @return */ public Map getOptions( ) { ModuleOption options = module.getOptions( ); if ( options == null ) return Collections.EMPTY_MAP; return options.getOptions( ); } }
package org.apache.geronimo.connector.outbound; import java.util.WeakHashMap; import java.util.Iterator; import java.util.Collection; import java.util.LinkedList; import java.util.Map; import java.util.HashMap; import javax.transaction.Transaction; import javax.transaction.TransactionManager; import javax.transaction.SystemException; import javax.transaction.Synchronization; import javax.transaction.RollbackException; import javax.resource.ResourceException; import org.apache.geronimo.connector.TxUtils; /** * TransactionCachingInterceptor.java * * * Created: Mon Sep 29 15:07:07 2003 * * @version 1.0 */ public class TransactionCachingInterceptor implements ConnectionInterceptor { private final ConnectionInterceptor next; private final TransactionManager tm; private final Map txToConnectionList = new HashMap(); public TransactionCachingInterceptor(final ConnectionInterceptor next, final TransactionManager tm) { this.next = next; this.tm = tm; } public void getConnection(ConnectionInfo ci) throws ResourceException { try { Transaction tx = tm.getTransaction(); if (TxUtils.isActive(tx)) { ManagedConnectionInfo mci = ci.getManagedConnectionInfo(); Collection mcis; synchronized (txToConnectionList) { mcis = (Collection)txToConnectionList.get(tx); if (mcis == null) { mcis = new LinkedList(); txToConnectionList.put(tx, mcis); tx.registerSynchronization(new Synch(tx, this, mcis)); } } /*Access to mcis should not need to be synchronized * unless several requests in the same transaction in * different threads are being processed at the same * time. This cannot occur with transactions imported * through jca. I don't know about any other possible * ways this could occur.*/ for (Iterator i = mcis.iterator(); i.hasNext();) { ManagedConnectionInfo oldmci = (ManagedConnectionInfo) i.next(); if (mci.securityMatches(oldmci)) { ci.setManagedConnectionInfo(oldmci); return; } } next.getConnection(ci); //put it in the map mcis.add(ci.getManagedConnectionInfo()); } else { next.getConnection(ci); } } catch (SystemException e) { throw new ResourceException("Could not get transaction from transaction manager", e); } catch (RollbackException e) { throw new ResourceException("Transaction is rolled back, can't enlist synchronization", e); } } public void returnConnection(ConnectionInfo ci, ConnectionReturnAction cra) { try { if (cra == ConnectionReturnAction.DESTROY) { next.returnConnection(ci, cra); } Transaction tx = tm.getTransaction(); if (TxUtils.isActive(tx)) { return; } if (ci.getManagedConnectionInfo().hasConnectionHandles()) { return; } //No transaction, no handles, we return it. next.returnConnection(ci, cra); } catch (SystemException e) { //throw new ResourceException("Could not get transaction from transaction manager", e); } } public void afterCompletion(Transaction tx) { Collection connections = (Collection) txToConnectionList.get(tx); if (connections != null) { for (Iterator iterator = connections.iterator(); iterator.hasNext();) { ManagedConnectionInfo managedConnectionInfo = (ManagedConnectionInfo) iterator.next(); ConnectionInfo connectionInfo = new ConnectionInfo(); connectionInfo.setManagedConnectionInfo(managedConnectionInfo); returnConnection(connectionInfo, ConnectionReturnAction.RETURN_HANDLE); } } } private static class Synch implements Synchronization { private final Transaction transaction; private final TransactionCachingInterceptor returnStack; private final Collection connections; public Synch(Transaction transaction, TransactionCachingInterceptor returnStack, Collection connections) { this.transaction = transaction; this.returnStack = returnStack; this.connections = connections; } public void beforeCompletion() { } public void afterCompletion(int status) { for (Iterator iterator = connections.iterator(); iterator.hasNext();) { ManagedConnectionInfo managedConnectionInfo = (ManagedConnectionInfo) iterator.next(); iterator.remove(); if (!managedConnectionInfo.hasConnectionHandles()) { returnStack.returnConnection(new ConnectionInfo(managedConnectionInfo), ConnectionReturnAction.RETURN_HANDLE); } } } } }
package name.abuchen.portfolio.ui.preferences; import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer; import org.eclipse.jface.preference.IPreferenceStore; import name.abuchen.portfolio.ui.PortfolioPlugin; import name.abuchen.portfolio.ui.UIConstants; public class PreferencesInitializer extends AbstractPreferenceInitializer { @Override public void initializeDefaultPreferences() { IPreferenceStore store = PortfolioPlugin.getDefault().getPreferenceStore(); store.setDefault(UIConstants.Preferences.AUTO_UPDATE, true); store.setDefault(UIConstants.Preferences.UPDATE_SITE, Platform.ARCH_X86.equals(Platform.getOSArch()) ? "https://updates.portfolio-performance.info/portfolio-x86" //$NON-NLS-1$ : "https://updates.portfolio-performance.info/portfolio"); //$NON-NLS-1$ store.setDefault(UIConstants.Preferences.USE_INDIRECT_QUOTATION, true); store.setDefault(UIConstants.Preferences.CREATE_BACKUP_BEFORE_SAVING, true); store.setDefault(UIConstants.Preferences.UPDATE_QUOTES_AFTER_FILE_OPEN, true); store.setDefault(UIConstants.Preferences.AUTO_SAVE_FILE, 0); store.setDefault(UIConstants.Preferences.STORE_SETTINGS_NEXT_TO_FILE, false); store.setDefault(UIConstants.Preferences.ALPHAVANTAGE_CALL_FREQUENCY_LIMIT, 5); store.setDefault(UIConstants.Preferences.CALENDAR, "default"); //$NON-NLS-1$ } }
package net.resheim.eclipse.timekeeper.ui.views; import java.text.MessageFormat; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.time.temporal.ChronoUnit; import java.time.temporal.WeekFields; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Optional; import java.util.Set; import org.apache.commons.lang.time.DurationFormatUtils; import org.eclipse.core.runtime.CoreException; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IMenuListener; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.IToolBarManager; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.jface.layout.GridLayoutFactory; import org.eclipse.jface.viewers.AbstractTreeViewer; import org.eclipse.jface.viewers.ColumnViewerToolTipSupport; import org.eclipse.jface.viewers.DoubleClickEvent; import org.eclipse.jface.viewers.IDoubleClickListener; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.TreeColumnViewerLabelProvider; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.jface.viewers.TreeViewerColumn; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerComparator; import org.eclipse.jface.window.ToolTip; import org.eclipse.mylyn.internal.tasks.core.AbstractTask; import org.eclipse.mylyn.internal.tasks.core.ITaskListChangeListener; import org.eclipse.mylyn.internal.tasks.core.LocalTask; import org.eclipse.mylyn.internal.tasks.core.TaskContainerDelta; import org.eclipse.mylyn.internal.tasks.ui.TasksUiPlugin; import org.eclipse.mylyn.tasks.core.ITask; import org.eclipse.mylyn.tasks.core.ITaskActivationListener; import org.eclipse.mylyn.tasks.core.TaskRepository; import org.eclipse.mylyn.tasks.core.data.TaskAttribute; import org.eclipse.mylyn.tasks.core.data.TaskData; import org.eclipse.mylyn.tasks.ui.TasksUi; import org.eclipse.mylyn.tasks.ui.TasksUiUtil; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ControlAdapter; import org.eclipse.swt.events.ControlEvent; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.DateTime; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.Tree; import org.eclipse.swt.widgets.TreeColumn; import org.eclipse.ui.IActionBars; import org.eclipse.ui.ISharedImages; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.contexts.IContextService; import org.eclipse.ui.part.ViewPart; import net.resheim.eclipse.timekeeper.db.Activity; import net.resheim.eclipse.timekeeper.db.TimekeeperPlugin; import net.resheim.eclipse.timekeeper.db.TrackedTask; import net.resheim.eclipse.timekeeper.ui.TimekeeperUiPlugin; @SuppressWarnings("restriction") public class WorkWeekView extends ViewPart { public static final String VIEW_ID = "net.resheim.eclipse.timekeeper.ui.views.workWeek"; private static final int TIME_COLUMN_WIDTH = 50; /** Update the status field every second */ private static final int UPDATE_INTERVAL = 1_000; private final class ViewerComparatorExtension extends ViewerComparator { @Override public int compare(Viewer viewer, Object e1, Object e2) { if (e1 instanceof ITask && e2 instanceof ITask) { String s1 = ((ITask) e1).getTaskId(); String s2 = ((ITask) e2).getTaskId(); try { int i1 = Integer.parseInt(s1); int i2 = Integer.parseInt(s2); return i1 - i2; } catch (NumberFormatException e) { } return s1.compareTo(s2); } if (e1 instanceof WeeklySummary) { return 1; } if (e1 instanceof Activity && e2 instanceof Activity) { return ((Activity) e1).compareTo((Activity) e2); } return super.compare(viewer, e1, e2); } } private final class TaskListener implements ITaskActivationListener, ITaskListChangeListener { @Override public void containersChanged(Set<TaskContainerDelta> arg0) { updateAll(); } @Override public void preTaskActivated(ITask task) { // Do nothing } @Override public void preTaskDeactivated(ITask task) { // Do nothing } @Override public void taskActivated(ITask task) { updateAll(); } @Override public void taskDeactivated(ITask task) { updateAll(); } private void updateAll() { getSite().getShell().getDisplay().asyncExec(new Runnable() { @Override public void run() { if (!viewer.getControl().isDisposed() && !viewer.isCellEditorActive()) { viewer.setInput(getViewSite()); } } }); } } private void installStatusUpdater() { final Display display = PlatformUI.getWorkbench().getDisplay(); Runnable handler = new Runnable() { public void run() { if (!display.isDisposed() && !PlatformUI.getWorkbench().isClosing() && !statusLabel.isDisposed()) { updateStatus(); display.timerExec(UPDATE_INTERVAL, this); } } }; display.timerExec(UPDATE_INTERVAL, handler); } /** * Returns the number of milliseconds the active task has been active * * @return the active milliseconds or "0" */ public long getActiveTime() { LocalDateTime activeSince = TimekeeperUiPlugin.getDefault().getActiveSince(); if (activeSince != null) { LocalDateTime now = LocalDateTime.now(); return activeSince.until(now, ChronoUnit.MILLIS); } return 0; } private void updateStatus() { ITask activeTask = TasksUi.getTaskActivityManager().getActiveTask(); if (activeTask == null) { statusLabel.setText(""); } else if (TimekeeperUiPlugin.getDefault().isIdle()) { statusLabel.setText("Idle since " + timeFormat.format(TimekeeperUiPlugin.getDefault().getIdleSince())); // do not refresh with an editor active, that would deactivate the // editor and lose focus if (!viewer.isCellEditorActive()) { viewer.refresh(activeTask); viewer.refresh(contentProvider.getParent(activeTask)); viewer.refresh(WeekViewContentProvider.WEEKLY_SUMMARY); } } else if (getActiveTime() > 0) { long activeTime = getActiveTime(); LocalDateTime activeSince = TimekeeperUiPlugin.getDefault().getActiveSince(); statusLabel.setText(MessageFormat.format("Active since {0}, {1} elapsed", timeFormat.format(activeSince), DurationFormatUtils.formatDurationWords(activeTime, true, true))); // do not refresh with an editor active, that would deactivate the // editor and lose focus if (!viewer.isCellEditorActive()) { viewer.refresh(activeTask); viewer.refresh(contentProvider.getParent(activeTask)); viewer.refresh(WeekViewContentProvider.WEEKLY_SUMMARY); } } } private class ContentProvider extends WeekViewContentProvider { @Override public void inputChanged(Viewer v, Object oldInput, Object newInput) { super.inputChanged(v, oldInput, newInput); if (v.getControl().isDisposed() || dateTimeLabel.isDisposed()) { return; } updateWeekLabel(); updateColumHeaders(); filter(); v.refresh(); } private void updateColumHeaders() { TreeColumn[] columns = viewer.getTree().getColumns(); String[] headings = TimekeeperUiPlugin.getDefault().getHeadings(getFirstDayOfWeek()); for (int i = 1; i < columns.length; i++) { LocalDate date = getFirstDayOfWeek().plusDays((long) i - 1); columns[i].setText(headings[i - 1]); columns[i].setToolTipText(getFormattedPeriod(getSum(filtered, date))); } } private void updateWeekLabel() { StringBuilder sb = new StringBuilder(); sb.append("Showing week "); sb.append(getFirstDayOfWeek().format(weekFormat)); sb.append(" starting at"); dateTimeLabel.setText(sb.toString()); dateChooser.setDate(getFirstDayOfWeek().getYear(), getFirstDayOfWeek().getMonthValue() - 1, getFirstDayOfWeek().getDayOfMonth()); } } private static final DateTimeFormatter weekFormat = DateTimeFormatter.ofPattern("w"); private static final DateTimeFormatter timeFormat = DateTimeFormatter.ofPattern("EEEE HH:mm:ss", Locale.ENGLISH); private Action previousWeekAction; private Action currentWeekAction; private Action newActivityAction; private Action nextWeekAction; private Action doubleClickAction; private Action deleteAction; private MenuManager projectFieldMenu; private TaskListener taskListener; private TreeViewer viewer; private Label dateTimeLabel; private DateTime dateChooser; private Action deactivateAction; private Action activateAction; private WeekViewContentProvider contentProvider; private Label statusLabel; /** * The constructor. */ public WorkWeekView() { } private LocalDate calculateFirstDayOfWeek(LocalDate date) { WeekFields weekFields = WeekFields.of(Locale.getDefault()); long day = date.get(weekFields.dayOfWeek()); LocalDate firstDayOfWeek = date.minusDays(day - 1); return firstDayOfWeek; } private void contributeToActionBars() { IActionBars bars = getViewSite().getActionBars(); fillLocalPullDown(bars.getMenuManager()); fillLocalToolBar(bars.getToolBarManager()); } @Override public void createPartControl(Composite parent) { Composite main = new Composite(parent, SWT.NONE); main.setBackgroundMode(SWT.INHERIT_FORCE); GridLayout layout2 = GridLayoutFactory.fillDefaults().numColumns(3).equalWidth(false).create(); main.setLayout(layout2); // text before the date chooser dateTimeLabel = new Label(main, SWT.NONE); GridData gdLabel = new GridData(); gdLabel.verticalIndent = 3; gdLabel.verticalAlignment = SWT.BEGINNING; dateTimeLabel.setLayoutData(gdLabel); dateChooser = new DateTime(main, SWT.DROP_DOWN | SWT.DATE | SWT.LONG); // the DateTime background color is misbehaving, but this is not too bad // although it does not stand out but rather have the same background // color as the labels. dateChooser.setBackgroundMode(SWT.INHERIT_DEFAULT); dateChooser.setFont(dateTimeLabel.getFont()); GridData gdChooser = new GridData(); gdChooser.verticalAlignment = SWT.BEGINNING; dateChooser.setLayoutData(gdChooser); dateChooser.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent event) { // Determine the first date of the week LocalDate date = LocalDate.of(dateChooser.getYear(), dateChooser.getMonth() + 1, dateChooser.getDay()); contentProvider.setFirstDayOfWeek(calculateFirstDayOfWeek(date)); viewer.setInput(this); } }); // text after the date chooser statusLabel = new Label(main, SWT.NONE); GridData gdStatusLabel = new GridData(); gdStatusLabel.grabExcessHorizontalSpace = true; gdStatusLabel.horizontalAlignment = SWT.FILL; gdStatusLabel.verticalIndent = 3; gdStatusLabel.verticalAlignment = SWT.BEGINNING; statusLabel.setLayoutData(gdStatusLabel); viewer = new TreeViewer(main, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION); // Make the tree view provide selections getSite().setSelectionProvider(viewer); contentProvider = new ContentProvider(); TimekeeperPlugin.getDefault().addListener(contentProvider); viewer.setContentProvider(contentProvider); GridData layoutData = GridDataFactory.fillDefaults().grab(true, true).span(3, 1).create(); viewer.getControl().setLayoutData(layoutData); // create the columns createTitleColumn(); for (int i = 0; i < 7; i++) { createTimeColumn(i); } Tree tree = viewer.getTree(); viewer.setComparator(new ViewerComparatorExtension()); viewer.setAutoExpandLevel(AbstractTreeViewer.ALL_LEVELS); ColumnViewerToolTipSupport.enableFor(viewer, ToolTip.NO_RECREATE); tree.setHeaderVisible(true); tree.setLinesVisible(true); // adjust column widths when view is resized main.addControlListener(new ControlAdapter() { int previous; @Override public void controlResized(ControlEvent e) { Rectangle area = main.getBounds(); int width = area.width; if (width != previous) { TreeColumn[] columns = tree.getColumns(); int cwidth = 0; for (int i = 1; i < columns.length; i++) { columns[i].pack(); if (columns[i].getWidth() < TIME_COLUMN_WIDTH) { columns[i].setWidth(TIME_COLUMN_WIDTH); } cwidth += columns[i].getWidth(); } // set the width of the first column columns[0].setWidth(width - cwidth); previous = width; } } }); // Determine the first date of the week LocalDate date = LocalDate.now(); WeekFields weekFields = WeekFields.of(Locale.getDefault()); long day = date.get(weekFields.dayOfWeek()); contentProvider.setFirstDayOfWeek(date.minusDays(day - 1)); makeActions(); hookContextMenu(); hookDoubleClickAction(); contributeToActionBars(); taskListener = new TaskListener(); TasksUiPlugin.getTaskActivityManager().addActivationListener(taskListener); TasksUiPlugin.getTaskList().addChangeListener(taskListener); viewer.setInput(getViewSite()); // Force a redraw so content is visible main.pack(); installStatusUpdater(); } private TreeViewerColumn createTableViewerColumn(String title, int width, final int colNumber) { final TreeViewerColumn viewerColumn = new TreeViewerColumn(viewer, SWT.NONE); TreeColumn column = viewerColumn.getColumn(); column.setText(title); column.setWidth(width); column.setResizable(true); column.setMoveable(false); return viewerColumn; } /** * Creates a table column for the given weekday and installs editing support * * @param weekday * the day of the week, starting from 0 */ private void createTimeColumn(int weekday) { TreeViewerColumn column = createTableViewerColumn("-", TIME_COLUMN_WIDTH, 1 + weekday); column.getColumn().setAlignment(SWT.RIGHT); column.setEditingSupport(new TimeEditingSupport((TreeViewer) column.getViewer(), contentProvider, weekday)); column.setLabelProvider(new TimeColumnLabelProvider(contentProvider) { @Override public String getText(Object element) { // Use modern formatting long seconds = 0; LocalDate date = contentProvider.getFirstDayOfWeek().plusDays(weekday); if (element instanceof String) { seconds = getSum(contentProvider.getFiltered(), date, (String) element); } else if (element instanceof ITask) { AbstractTask task = (AbstractTask) element; TrackedTask trackedTask = TimekeeperPlugin.getDefault().getTask(task); if (trackedTask != null) { seconds = trackedTask.getDuration(contentProvider.getDate(weekday)).getSeconds(); } } else if (element instanceof WeeklySummary) { seconds = getSum(contentProvider.getFiltered(), date); } else if (element instanceof Activity) { seconds = ((Activity) element).getDuration(date).getSeconds(); } if (seconds > 0) { return DurationFormatUtils.formatDuration(seconds * 1000, "H:mm", true); } return ""; } }); } private void createTitleColumn() { TreeViewerColumn column = createTableViewerColumn("Activity", 400, 1); column.setLabelProvider(new TreeColumnViewerLabelProvider(new TitleColumnLabelProvider(contentProvider))); column.setEditingSupport(new ActivitySummaryEditingSupport(viewer)); } @Override public void dispose() { TasksUiPlugin.getTaskActivityManager().removeActivationListener(taskListener); TasksUiPlugin.getTaskList().removeChangeListener(taskListener); super.dispose(); } /** * Populates the view context menu. */ private void fillContextMenu(IMenuManager manager) { manager.add(previousWeekAction); manager.add(nextWeekAction); ISelection selection = viewer.getSelection(); Object obj = ((IStructuredSelection) selection).getFirstElement(); if (obj instanceof ITask) { manager.add(new Separator("task")); if (((ITask) obj).isActive()) { manager.add(deactivateAction); } else { manager.add(activateAction); } manager.add(newActivityAction); manager.add(new Separator()); manager.add(projectFieldMenu); } if (obj instanceof Activity) { Optional<Activity> currentActivity = ((Activity) obj).getTrackedTask().getCurrentActivity(); // do not allow deleting an activity that is currently active if (!(currentActivity.isPresent() && currentActivity.get().equals(obj))) { manager.add(deleteAction); } } } private void fillLocalPullDown(IMenuManager manager) { // manager.add(action1); // manager.add(new Separator()); // manager.add(action2); } private void fillLocalToolBar(IToolBarManager manager) { manager.add(new Separator("additions")); manager.add(new Separator("navigation")); manager.add(previousWeekAction); manager.add(currentWeekAction); manager.add(nextWeekAction); } private String getFormattedPeriod(long seconds) { if (seconds > 0) { return DurationFormatUtils.formatDuration(seconds * 1000, "H:mm", true); } // TODO: Fix dates with no entries "0:00" return ""; } /** * Calculates the total amount of seconds accumulated on specified date. * * @param date * the date to calculate for * @return the total amount of seconds accumulated */ private long getSum(List<ITask> filtered, LocalDate date) { // May not have been initialised when first called. if (filtered == null) { return 0; } return filtered .stream().filter(t -> TimekeeperPlugin.getDefault().getTask(t) != null) .mapToLong(t -> TimekeeperPlugin.getDefault().getTask(t).getDuration(date).getSeconds()) .sum(); } /** * Calculates the total amount of seconds accumulated on the project for the * specified date. * * @param date * the date to calculate for * @param project * the project to calculate for * @return the total amount of seconds accumulated */ private long getSum(List<ITask> filtered, LocalDate date, String project) { return filtered .stream() .filter(t -> TimekeeperPlugin.getDefault().getTask(t) != null) .filter(t -> project.equals(TimekeeperPlugin.getProjectName(t))) .mapToLong(t -> TimekeeperPlugin.getDefault().getTask(t).getDuration(date).getSeconds()) .sum(); } private void hookContextMenu() { MenuManager menuMgr = new MenuManager("#PopupMenu"); menuMgr.setRemoveAllWhenShown(true); menuMgr.addMenuListener(new IMenuListener() { public void menuAboutToShow(IMenuManager manager) { WorkWeekView.this.fillContextMenu(manager); } }); // create a context menu for the view Menu menu = menuMgr.createContextMenu(viewer.getControl()); viewer.getControl().setMenu(menu); getSite().registerContextMenu(menuMgr, viewer); } private void hookDoubleClickAction() { viewer.addDoubleClickListener(new IDoubleClickListener() { public void doubleClick(DoubleClickEvent event) { doubleClickAction.run(); } }); } /** * @return the first day of the week displayed */ public LocalDate getFirstDayOfWeek() { return contentProvider.getFirstDayOfWeek(); } private void makeActions() { // browse to previous week previousWeekAction = new Action() { @Override public void run() { contentProvider.setFirstDayOfWeek(contentProvider.getFirstDayOfWeek().minusDays(7)); viewer.setInput(getViewSite()); } }; previousWeekAction.setText("Previous week"); previousWeekAction.setToolTipText("Show previous week"); previousWeekAction.setImageDescriptor(PlatformUI.getWorkbench().getSharedImages() .getImageDescriptor(ISharedImages.IMG_TOOL_BACK)); // browse to current week currentWeekAction = new Action() { @Override public void run() { contentProvider.setFirstDayOfWeek(calculateFirstDayOfWeek(LocalDate.now())); viewer.setInput(getViewSite()); } }; currentWeekAction.setText("Current week"); currentWeekAction.setToolTipText("Show current week"); currentWeekAction .setImageDescriptor(TimekeeperUiPlugin.getDefault() .getImageRegistry() .getDescriptor(TimekeeperUiPlugin.IMG_TOOL_CURRENT)); // browse to next week nextWeekAction = new Action() { @Override public void run() { contentProvider.setFirstDayOfWeek(contentProvider.getFirstDayOfWeek().plusDays(7)); viewer.setInput(getViewSite()); } }; nextWeekAction.setText("Next week"); nextWeekAction.setToolTipText("Show next week"); nextWeekAction.setImageDescriptor(PlatformUI.getWorkbench().getSharedImages() .getImageDescriptor(ISharedImages.IMG_TOOL_FORWARD)); // double click on task doubleClickAction = new Action() { @Override public void run() { ISelection selection = viewer.getSelection(); Object obj = ((IStructuredSelection) selection).getFirstElement(); if (obj instanceof ITask) { TasksUiUtil.openTask((ITask) obj); } } }; // deactivate task deactivateAction = new Action("Deactivate task") { @Override public void run() { ISelection selection = viewer.getSelection(); Object obj = ((IStructuredSelection) selection).getFirstElement(); if (obj instanceof ITask) { TasksUi.getTaskActivityManager().deactivateTask((ITask) obj); } } }; // activate task activateAction = new Action("Activate task") { @Override public void run() { ISelection selection = viewer.getSelection(); Object obj = ((IStructuredSelection) selection).getFirstElement(); if (obj instanceof ITask) { TasksUi.getTaskActivityManager().activateTask((ITask) obj); } } }; // create a new activity newActivityAction = new Action("New activity") { @Override public void run() { ISelection selection = viewer.getSelection(); Object obj = ((IStructuredSelection) selection).getFirstElement(); if (obj instanceof ITask) { TrackedTask task = TimekeeperPlugin.getDefault().getTask((ITask) obj); task.endActivity(); task.startActivity(); // the user created a new activity on an inactive task, so we assume that we // should not continue to track the time. if (!((ITask) obj).isActive()) { task.endActivity(); } refresh(); } } }; // delete activity deleteAction = new Action("Delete activity") { @Override public void run() { ISelection selection = viewer.getSelection(); Iterator<?> iterator = ((IStructuredSelection) selection).iterator(); while (iterator.hasNext()) { Object i = iterator.next(); if (i instanceof Activity) { ((Activity) i).getTrackedTask().getActivities().remove(i); } } viewer.refresh(); } }; deleteAction.setImageDescriptor( PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(ISharedImages.IMG_TOOL_DELETE)); projectFieldMenu = new MenuManager("Set grouping field", null); projectFieldMenu.setRemoveAllWhenShown(true); projectFieldMenu.addMenuListener(new IMenuListener() { public void menuAboutToShow(IMenuManager manager) { ISelection selection = viewer.getSelection(); if (selection instanceof IStructuredSelection) { Object firstElement = ((IStructuredSelection) selection).getFirstElement(); if (firstElement instanceof AbstractTask) { AbstractTask task = (AbstractTask) firstElement; // No way to change project on local tasks if (task instanceof LocalTask) { return; } String url = task.getRepositoryUrl(); TaskRepository repository = TasksUiPlugin.getRepositoryManager().getRepository(url); try { TaskData taskData = TasksUi.getTaskDataManager().getTaskData(task); List<TaskAttribute> attributesByType = taskData.getAttributeMapper().getAttributesByType( taskData, TaskAttribute.TYPE_SINGLE_SELECT); // customfield_10410 = subproject for (TaskAttribute taskAttribute : attributesByType) { final String label = taskAttribute.getMetaData().getLabel(); if (label != null) { final String id = taskAttribute.getId(); Action a = new Action(label.replaceAll(":", "")) { @Override public void run() { setProjectField(repository, id); } }; manager.add(a); } } manager.add(new Separator()); Action a = new Action("Default") { @Override public void run() { setProjectField(repository, null); } }; manager.add(a); } catch (CoreException e) { e.printStackTrace(); } } // abstract task menu } } }); } /** * Passing the focus request to the viewer's control. */ @Override public void setFocus() { viewer.getControl().setFocus(); IContextService contextService = PlatformUI.getWorkbench().getService(IContextService.class); contextService.activateContext("net.resheim.eclipse.timekeeper.ui.workweek"); } private void setProjectField(TaskRepository repository, String string) { if (null == string) { repository.removeProperty(TimekeeperPlugin.KEY_VALUELIST_ID + ".grouping"); } repository.setProperty(TimekeeperPlugin.KEY_VALUELIST_ID + ".grouping", string); viewer.refresh(); } /** * Used to notify the view that the content have had an massive change. * Typically after importing a number of records. */ public void refresh() { viewer.getContentProvider().inputChanged(viewer, viewer.getInput(), null); viewer.expandAll(); } }
package org.eclipse.mylyn.internal.tasks.ui.editors; import org.eclipse.core.runtime.Platform; import org.eclipse.swt.custom.CTabFolder; import org.eclipse.swt.custom.ScrolledComposite; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Layout; import org.eclipse.swt.widgets.ScrollBar; import org.eclipse.ui.forms.widgets.Section; /** * A layout that uses the width hint or client area of a composite to recommend the width of its children, allowing * children to fill the width and specify their preferred height for a given width. * * Intended for use with a composite that contains a single child that should fill available horizontal space. * * @author David Green */ class FillWidthLayout extends Layout { private final int marginLeft; private final int marginRight; private final int marginTop; private final int marginBottom; private final int widthHintMargin; private Composite layoutAdvisor; private int lastWidthHint; private Point lastComputedSize; /** * create with 0 margins * */ public FillWidthLayout() { this(0, 0, 0, 0); } /** * create while specifying margins * * @param marginLeft * the left margin in pixels, or 0 if there should be none * @param marginRight * the right margin in pixels, or 0 if there should be none * @param marginTop * the top margin in pixels, or 0 if there should be none * @param marginBottom * the bottom margin in pixels, or 0 if there should be none */ public FillWidthLayout(int marginLeft, int marginRight, int marginTop, int marginBottom) { this(null, marginLeft, marginRight, marginTop, marginBottom); } /** * create specifying margins and a {@link #getLayoutAdvisor() layout advisor}. * * @param layoutAdvisor * the composite that is used to advise on layout based on its {@link Composite#getClientArea() client * area}. * @param marginLeft * the left margin in pixels, or 0 if there should be none * @param marginRight * the right margin in pixels, or 0 if there should be none * @param marginTop * the top margin in pixels, or 0 if there should be none * @param marginBottom * the bottom margin in pixels, or 0 if there should be none */ public FillWidthLayout(Composite layoutAdvisor, int marginLeft, int marginRight, int marginTop, int marginBottom) { this.layoutAdvisor = layoutAdvisor; this.marginLeft = marginLeft; this.marginRight = marginRight; this.marginTop = marginTop; this.marginBottom = marginBottom; if (Platform.OS_MACOSX.equals(Platform.getOS())) { this.widthHintMargin = 15; } else { this.widthHintMargin = 20; } } /** * calculate the client area of the given container, accomodating for insets and margins. */ private int calculateWidthHint(Composite container) { return calculateWidthHint(container, layoutAdvisor == null); } /** * calculate the client area of the given container, accomodating for insets and margins. */ private int calculateWidthHint(Composite container, boolean layoutAdvisorHit) { if (container == layoutAdvisor) { layoutAdvisorHit = true; } Rectangle clientArea = container.getClientArea(); int horizontalMargin = 0; if (clientArea.width <= 1 || !layoutAdvisorHit) { // sometimes client area is incorrectly reported as 1 clientArea.width = calculateWidthHint(container.getParent(), layoutAdvisorHit); } Layout bodyLayout = container.getLayout(); if (bodyLayout instanceof GridLayout) { GridLayout gridLayout = (GridLayout) bodyLayout; horizontalMargin = (gridLayout.marginWidth * 2) + gridLayout.marginLeft + gridLayout.marginRight; } else if (bodyLayout instanceof FillLayout) { FillLayout fillLayout = (FillLayout) bodyLayout; horizontalMargin = fillLayout.marginWidth * 2; } else if (container instanceof Section) { horizontalMargin = ((Section) container).marginWidth * 2; } else if (container instanceof CTabFolder) { CTabFolder folder = (CTabFolder) container; horizontalMargin = folder.marginWidth * 2; } if (container instanceof ScrolledComposite) { ScrolledComposite composite = (ScrolledComposite) container; ScrollBar verticalBar = composite.getVerticalBar(); if (verticalBar != null) { int verticalBarWidth = verticalBar.getSize().x; horizontalMargin += Math.max(15, verticalBarWidth); } } return clientArea.width - horizontalMargin; } @Override protected Point computeSize(Composite composite, int widthHint, int heightHint, boolean flushCache) { Control[] children = composite.getChildren(); if (children.length == 0) { return new Point(0, 0); } if (widthHint <= 0) { widthHint = calculateWidthHint(composite); if (widthHint < 300) { widthHint = 300; } else { widthHint -= widthHintMargin; } } if (lastComputedSize == null || widthHint != lastWidthHint) { int horizontalMargin = marginLeft + marginRight; int resultX = 1; int resultY = 1; for (Control control : children) { Point sz = control.computeSize(widthHint - horizontalMargin, -1, flushCache); resultX = Math.max(resultX, sz.x); resultY = Math.max(resultY, sz.y); } lastWidthHint = widthHint; lastComputedSize = new Point(resultX + horizontalMargin, resultY + marginTop + marginBottom); } return new Point(lastComputedSize.x, lastComputedSize.y); } @Override protected void layout(Composite composite, boolean flushCache) { Rectangle area = composite.getClientArea(); if (area.width == 0) { area.width = calculateWidthHint(composite); } // account for margins area.x += marginLeft; area.y += marginTop; area.width -= (marginRight + marginLeft); area.height -= (marginBottom + marginTop); Control[] children = composite.getChildren(); for (Control control : children) { control.setBounds(area); } } /** * the composite that is used to advise on layout based on its {@link Composite#getClientArea() client area}. * * @return the layout advisor, or null if there is none */ public Composite getLayoutAdvisor() { return layoutAdvisor; } /** * the composite that is used to advise on layout based on its {@link Composite#getClientArea() client area}. * * @param layoutAdvisor * the layout advisor, or null if there is none */ public void setLayoutAdvisor(Composite layoutAdvisor) { this.layoutAdvisor = layoutAdvisor; } }
package com.taocoder.ourea.core.loadbalance; import com.taocoder.ourea.core.model.Invocation; import com.taocoder.ourea.core.model.InvokeConn; import java.util.List; import java.util.concurrent.ConcurrentHashMap; public class RoundRobinLoadBalanceStrategy extends AbstractLoadBalanceStrategy { private static final ConcurrentHashMap<String, Integer> current = new ConcurrentHashMap<String, Integer>(); @Override protected InvokeConn doSelect(List<InvokeConn> invokeConns, Invocation invocation) { String key = invocation.getInterfaceName() + invocation.getMethodName(); Integer cur = current.get(key); if (cur == null || cur >= Integer.MAX_VALUE - 1) { cur = 0; } current.putIfAbsent(key, cur + 1); try { return invokeConns.get(cur % invokeConns.size()); }catch (IndexOutOfBoundsException e){ return invokeConns.get(0); } } }
package org.subethamail.smtp.command; import java.io.IOException; import java.io.InputStream; import org.subethamail.common.io.DeferredFileOutputStream; import org.subethamail.smtp.server.BaseCommand; import org.subethamail.smtp.server.CharTerminatedInputStream; import org.subethamail.smtp.server.ConnectionContext; import org.subethamail.smtp.server.DotUnstuffingInputStream; import org.subethamail.smtp.server.Session; import org.subethamail.smtp.server.Session.Delivery; /** * @author Ian McFarland &lt;ian@neo.com&gt; * @author Jon Stevens */ public class DataCommand extends BaseCommand { private final static char[] SMTP_TERMINATOR = { '\r', '\n', '.', '\r', '\n' }; public DataCommand() { super("DATA", "Following text is collected as the message.\n" + "End data with <CR><LF>.<CR><LF>"); } @Override public void execute(String commandString, ConnectionContext context) throws IOException { Session session = context.getSession(); if (session.getSender() == null) { context.sendResponse("503 Error: need MAIL command"); } else if (session.getDeliveries().size() == 0) { context.sendResponse("503 Error: need RCPT command"); } context.sendResponse("354 End data with <CR><LF>.<CR><LF>"); InputStream dotInputStream = new DotUnstuffingInputStream( new CharTerminatedInputStream(context.getConnection().getInput(), SMTP_TERMINATOR)); if (session.getDeliveries().size() == 1) { Delivery delivery = session.getDeliveries().get(0); delivery.getListener().deliver(session.getSender(), delivery.getRecipient(), dotInputStream); } else { // 5 megs DeferredFileOutputStream dfos = new DeferredFileOutputStream(1024*1024*5); try { int value; while ((value = dotInputStream.read()) >= 0) { dfos.write(value); } for (Delivery delivery : session.getDeliveries()) { delivery.getListener().deliver(session.getSender(), delivery.getRecipient(), dfos.getInputStream()); } } finally { dfos.close(); } } context.sendResponse("250 Ok"); } }
package com.intellij.codeInsight; import com.intellij.aspects.psi.PsiPointcutDef; import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer; import com.intellij.codeInsight.lookup.Lookup; import com.intellij.codeInsight.lookup.LookupItem; import com.intellij.codeInsight.lookup.LookupManager; import com.intellij.ide.DataManager; import com.intellij.openapi.actionSystem.DataConstants; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Comparing; import com.intellij.psi.*; import com.intellij.psi.xml.XmlAttribute; import com.intellij.psi.xml.XmlElementDecl; public class TargetElementUtil { public static final int REFERENCED_ELEMENT_ACCEPTED = 0x01; public static final int ELEMENT_NAME_ACCEPTED = 0x02; public static final int NEW_AS_CONSTRUCTOR = 0x04; public static final int LOOKUP_ITEM_ACCEPTED = 0x08; public static final int THIS_ACCEPTED = 0x10; public static final int SUPER_ACCEPTED = 0x20; public static final int TRY_ACCEPTED = 0x40; public static final int CATCH_ACCEPTED = 0x80; public static final int THROW_ACCEPTED = 0x100; public static final int THROWS_ACCEPTED = 0x200; public static final int RETURN_ACCEPTED = 0x400; public static final int THROW_STATEMENT_ACCEPTED = 0x800; public static PsiElement findTargetElement(Editor editor, int flags) { int offset = editor.getCaretModel().getOffset(); return findTargetElement(editor, flags, offset); } public static PsiReference findReference(Editor editor, int offset) { ApplicationManager.getApplication().assertIsDispatchThread(); DataContext dataContext = DataManager.getInstance().getDataContext(editor.getComponent()); Project project = (Project) dataContext.getData(DataConstants.PROJECT); Document document = editor.getDocument(); PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(document); if (file == null) return null; PsiDocumentManager.getInstance(project).commitAllDocuments(); offset = adjustOffset(document, offset); if (file instanceof PsiCompiledElement) { return ((PsiCompiledElement) file).getMirror().findReferenceAt(offset); } return file.findReferenceAt(offset); } public static PsiElement findTargetElement(Editor editor, int flags, int offset) { ApplicationManager.getApplication().assertIsDispatchThread(); DataContext dataContext = DataManager.getInstance().getDataContext(editor.getComponent()); Project project = (Project) dataContext.getData(DataConstants.PROJECT); Lookup activeLookup = LookupManager.getInstance(project).getActiveLookup(); if (activeLookup != null && (flags & LOOKUP_ITEM_ACCEPTED) != 0) { final PsiElement lookupItem = getLookupItem(activeLookup); return lookupItem != null && lookupItem.isValid() ? lookupItem : null; } Document document = editor.getDocument(); PsiDocumentManager.getInstance(project).commitAllDocuments(); PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(document); if (file == null) return null; offset = adjustOffset(document, offset); /* if (file instanceof PsiCompiledElement) { file = (PsiFile)((PsiCompiledElement) file).getMirror(); } */ PsiElement element = file.findElementAt(offset); if (element == null) return null; if ((flags & ELEMENT_NAME_ACCEPTED) != 0) { PsiElement parent = element.getParent(); if (element instanceof PsiIdentifier) { if (parent instanceof PsiClass && element.equals(((PsiClass) parent).getNameIdentifier())) { return parent; } else if (parent instanceof PsiVariable && element.equals(((PsiVariable) parent).getNameIdentifier())) { return parent; } else if (parent instanceof PsiMethod && element.equals(((PsiMethod) parent).getNameIdentifier())) { return parent; } else if (parent instanceof PsiPointcutDef && element.equals(((PsiPointcutDef) parent).getNameIdentifier())) { return parent; } else if (parent instanceof PsiLabeledStatement && element.equals(((PsiLabeledStatement)parent).getLabelIdentifier())) { return parent; } } else if (parent instanceof PsiNamedElement) { // A bit hacky depends on navigation offset correctly overriden if (parent instanceof XmlElementDecl) { return parent; } if (parent.getTextOffset() == element.getTextOffset() && Comparing.equal(((PsiNamedElement)parent).getName(), element.getText()) && !(parent instanceof XmlAttribute) ) { return parent; } } } if (element instanceof PsiKeyword) { if (element.getParent() instanceof PsiThisExpression) { if ((flags & THIS_ACCEPTED) == 0) return null; PsiType type = ((PsiThisExpression) element.getParent()).getType(); if (!(type instanceof PsiClassType)) return null; return ((PsiClassType) type).resolve(); } if (element.getParent() instanceof PsiSuperExpression) { if ((flags & SUPER_ACCEPTED) == 0) return null; PsiType type = ((PsiSuperExpression) element.getParent()).getType(); if (!(type instanceof PsiClassType)) return null; return ((PsiClassType) type).resolve(); } if ("try".equals(element.getText())) { if ((flags & TRY_ACCEPTED) == 0) return null; return element; } if ("catch".equals(element.getText())) { if ((flags & CATCH_ACCEPTED) == 0) return null; return element; } if ("throws".equals(element.getText())) { if ((flags & THROWS_ACCEPTED) == 0) return null; return element; } if ("throw".equals(element.getText())) { if ((flags & THROW_ACCEPTED) != 0) return element; if ((flags & THROW_STATEMENT_ACCEPTED) != 0) { final PsiElement parent = element.getParent(); if (parent instanceof PsiThrowStatement) { return parent; } } return null; } if ("return".equals(element.getText())) { if ((flags & RETURN_ACCEPTED) == 0) return null; return element; } } if ((flags & REFERENCED_ELEMENT_ACCEPTED) != 0) { final PsiElement referenceOrReferencedElement = getReferenceOrReferencedElement(file, editor, flags, offset); if (referenceOrReferencedElement == null) { return getReferenceOrReferencedElement(file, editor, flags, offset); } return referenceOrReferencedElement != null && referenceOrReferencedElement.isValid() ? referenceOrReferencedElement : null; } return null; } private static int adjustOffset(Document document, final int offset) { CharSequence text = document.getCharsSequence(); int correctedOffset = offset; int textLength = document.getTextLength(); if (offset >= textLength) { correctedOffset = textLength - 1; } else { if (!Character.isJavaIdentifierPart(text.charAt(offset))) { correctedOffset } } if (correctedOffset < 0 || !Character.isJavaIdentifierPart(text.charAt(correctedOffset))) return offset; return correctedOffset; } private static PsiElement getReferenceOrReferencedElement(PsiFile file, Editor editor, int flags, int offset) { PsiReference ref = findReference(editor, offset); if (ref == null) { return null; } PsiManager manager = file.getManager(); final PsiElement referenceElement = ref.getElement(); PsiElement refElement; if(ref instanceof PsiJavaReference){ refElement = ((PsiJavaReference)ref).advancedResolve(true).getElement(); } else{ refElement = ref.resolve(); } if (refElement == null) { DaemonCodeAnalyzer.getInstance(manager.getProject()).updateVisibleHighlighters(editor); } else { if ((flags & NEW_AS_CONSTRUCTOR) != 0) { PsiElement parent = referenceElement.getParent(); if (parent instanceof PsiAnonymousClass) { parent = parent.getParent(); } if (parent instanceof PsiNewExpression) { PsiMethod constructor = ((PsiNewExpression) parent).resolveConstructor(); if (constructor != null) { refElement = constructor; } } } if (refElement instanceof PsiClass && refElement.getContainingFile().getVirtualFile() == null) { // in mirror file of compiled class return manager.findClass(((PsiClass) refElement).getQualifiedName(), refElement.getResolveScope()); } return refElement; } return null; } private static PsiElement getLookupItem(Lookup activeLookup) { LookupItem item = activeLookup.getCurrentItem(); if (item == null) return null; Object o = item.getObject(); if (o instanceof PsiClass || o instanceof PsiPackage || o instanceof PsiMethod || o instanceof PsiVariable || o instanceof PsiFile ) { PsiElement element = (PsiElement) o; if (!(element instanceof PsiPackage)) { PsiFile file = element.getContainingFile(); if (file == null) return null; if (file.getOriginalFile() != null) file = file.getOriginalFile(); if (file == null) return null; if (file.getVirtualFile() == null) return null; } return element; } else { return null; } } }
package net.fortuna.ical4j.model.property; import net.fortuna.ical4j.model.ParameterList; import net.fortuna.ical4j.model.Property; import net.fortuna.ical4j.model.ValidationException; import net.fortuna.ical4j.util.CompatibilityHints; /** * $Id$ * * Created: [Apr 6, 2004] * * Defines a CALSCALE iCalendar property. * @author benf */ public class CalScale extends Property { private static final long serialVersionUID = 7446184786984981423L; public static final CalScale GREGORIAN = new ImmutableCalScale("GREGORIAN"); /** * @author Ben Fortuna An immutable instance of CalScale. */ private static final class ImmutableCalScale extends CalScale { private static final long serialVersionUID = 1750949550694413878L; /** * @param value */ private ImmutableCalScale(final String value) { super(new ParameterList(true), value); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.Property#setValue(java.lang.String) */ public void setValue(final String aValue) { throw new UnsupportedOperationException( "Cannot modify constant instances"); } } private String value; /** * Default constructor. */ public CalScale() { super(CALSCALE); } /** * @param aValue a value string for this component */ public CalScale(final String aValue) { super(CALSCALE); this.value = aValue; } /** * @param aList a list of parameters for this component * @param aValue a value string for this component */ public CalScale(final ParameterList aList, final String aValue) { super(CALSCALE, aList); this.value = aValue; } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.Property#setValue(java.lang.String) */ public void setValue(final String aValue) { this.value = aValue; } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.Property#getValue() */ public final String getValue() { return value; } /** * @see net.fortuna.ical4j.model.Property#validate() */ public final void validate() throws ValidationException { if (CompatibilityHints.isHintEnabled(CompatibilityHints.KEY_RELAXED_VALIDATION)) { if (!GREGORIAN.getValue().equalsIgnoreCase(value)) { throw new ValidationException("Invalid value [" + value + "]"); } } else { if (!GREGORIAN.getValue().equals(value)) { throw new ValidationException("Invalid value [" + value + "]"); } } } }
package org.jasig.portal.layout; import org.jasig.portal.IUserLayoutStore; import org.jasig.portal.PortalException; import org.xml.sax.ContentHandler; import java.util.List; import org.apache.xerces.dom.DocumentImpl; /** * An interface for abstracting operations performed on the user layout. * * @author <a href="mailto:pkharchenko@interactivebusiness.com">Peter Kharchenko</a> * @version 1.0 */ public interface IUserLayoutManager { /** * Output user layout (with appropriate markings) into * a <code>ContentHandler</code> * * @param ch a <code>ContentHandler</code> value * @exception PortalException if an error occurs */ public void getUserLayout(ContentHandler ch) throws PortalException ; /** * Output subtree of a user layout (with appropriate markings) defined by a particular node into * a <code>ContentHandler</code> * * @param nodeId a <code>String</code> a node determining a user layout subtree. * @param ch a <code>ContentHandler</code> value * @exception PortalException if an error occurs */ public void getUserLayout(String nodeId, ContentHandler ch) throws PortalException; /** * Set a user layout store implementation. * * @param ls an <code>IUserLayoutStore</code> value */ public void setLayoutStore(IUserLayoutStore ls); /** * Signal manager to load a user layout from a database * * @exception PortalException if an error occurs */ public void loadUserLayout() throws PortalException; /** * Signal manager to persist user layout to a database * * @exception PortalException if an error occurs */ public void saveUserLayout() throws PortalException; /** * Obtain a description of a node (channel or a folder) in a given user layout. * * @param nodeId a <code>String</code> channel subscribe id or folder id. * @return an <code>UserLayoutNodeDescription</code> value * @exception PortalException if an error occurs */ public UserLayoutNodeDescription getNode(String nodeId) throws PortalException; /** * Add a new node to a current user layout. * * @param node an <code>UserLayoutNodeDescription</code> value of a node to be added (Id doesn't have to be set) * @param parentId a <code>String</code> id of a folder to which the new node (channel or folder) should be added. * @param nextSiblingId a <code>String</code> an id of a sibling node (channel or folder) prior to which the new node should be inserted. * @return an <code>UserLayoutNodeDescription</code> value with a newly determined Id. * @exception PortalException if an error occurs */ public UserLayoutNodeDescription addNode(UserLayoutNodeDescription node, String parentId, String nextSiblingId) throws PortalException; /** * Move a node (channel or folder) from one location to another. * * @param nodeId a <code>String</code> value of a node Id. * @param parentId a <code>String</code> id of a folder to which the node should be moved. * @param nextSiblingId a <code>String</code> id of a sibling node (folder or channel) prior to which the node should be placed. (<code>null</code> to append at the end) * @exception PortalException if an error occurs */ public void moveNode(String nodeId, String parentId, String nextSiblingId) throws PortalException; /** * Delete a node (folder or a channel) from a user layout. * * @param nodeId a <code>String</code> id (channel subscribe id or folder id) * @exception PortalException if an error occurs */ public void deleteNode(String nodeId) throws PortalException; /** * Update a given node. * * @param node an <code>UserLayoutNodeDescription</code> value with a valid id. * @exception PortalException if an error occurs */ public void updateNode(UserLayoutNodeDescription node) throws PortalException; /** * Test if a particular node can be added at a given location. * * @param node an <code>UserLayoutNodeDescription</code> value describing the node to be added. * @param parentId a <code>String</code> id of a parent to which the node to be added. * @param nextSiblingId a <code>String</code> id of a sibling prior to which the node to be inserted. (<code>null</code> to append at the end) * @return a <code>boolean</code> value * @exception PortalException if an error occurs */ public boolean canAddNode(UserLayoutNodeDescription node, String parentId, String nextSiblingId) throws PortalException; /** * Test if a particular node can be moved to a given location. * * @param nodeId a <code>String</code> id of a node to be moved. * @param parentId a <code>String</code> id of a parent to which the node to be moved. * @param nextSiblingId a <code>String</code> id of a sibling prior to which the node is to be inserted (<code>null</code> to append at the end) * @return a <code>boolean</code> value * @exception PortalException if an error occurs */ public boolean canMoveNode(String nodeId, String parentId, String nextSiblingId) throws PortalException; /** * Tests if a particular node can be deleted. * * @param nodeId a <code>String</code> node id. * @return a <code>boolean</code> value * @exception PortalException if an error occurs */ public boolean canDeleteNode(String nodeId) throws PortalException; /** * Test if a certain node can be updated. * * @param nodeId a <code>String</code> node id. * @return a <code>boolean</code> value * @exception PortalException if an error occurs */ public boolean canUpdateNode(String nodeId) throws PortalException; /** * Ask manager to output markings at the locations where a given node can be added. * The marks will appear next time {@link getUserLayout} method is called. * * @param node an <code>UserLayoutNodeDescription</code> value or <code>null</code> to stop outputting add markings. */ public void markAddTargets(UserLayoutNodeDescription node); /** * Ask manager to output markings at the locations where a given node can be moved. * The marks will appear next time {@link getUserLayout} method is called. * * @param nodeId a <code>String</code> value or <code>null</code> to stop outputting move markings. * @exception PortalException if an error occurs */ public void markMoveTargets(String nodeId) throws PortalException; /** * Returns an Id of a parent user layout node. * The user layout root node always has ID="root" * * @param nodeId a <code>String</code> value * @return a <code>String</code> value * @exception PortalException if an error occurs */ public String getParentId(String nodeId) throws PortalException; /** * Determine a list of child node Ids for a given node. * * @param nodeId a <code>String</code> value * @return a <code>List</code> of <code>String</code> child node Ids. * @exception PortalException if an error occurs */ public List getChildIds(String nodeId) throws PortalException; /** * Determine an Id of a next sibling node. * * @param nodeId a <code>String</code> value * @return a <code>String</code> Id value of a next sibling node, or <code>null</code> if this is the last sibling. * @exception PortalException if an error occurs */ public String getNextSiblingId(String nodeId) throws PortalException; // temp methods, to be removed (getDOM() might actually stay) // This method should be removed whenever it becomes possible public void setUserLayoutDOM(DocumentImpl doc); // This method should be removed whenever it becomes possible public DocumentImpl getUserLayoutDOM(); }
package org.jfree.chart.annotations; import java.awt.Color; import java.awt.Font; import java.awt.Paint; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import org.jfree.chart.text.TextAnchor; import org.jfree.chart.util.HashUtilities; import org.jfree.chart.util.ObjectUtilities; import org.jfree.chart.util.PaintUtilities; import org.jfree.chart.util.SerialUtilities; /** * A base class for text annotations. This class records the content but not * the location of the annotation. */ public class TextAnnotation implements Serializable { /** For serialization. */ private static final long serialVersionUID = 7008912287533127432L; /** The default font. */ public static final Font DEFAULT_FONT = new Font("SansSerif", Font.PLAIN, 10); /** The default paint. */ public static final Paint DEFAULT_PAINT = Color.black; /** The default text anchor. */ public static final TextAnchor DEFAULT_TEXT_ANCHOR = TextAnchor.CENTER; /** The default rotation anchor. */ public static final TextAnchor DEFAULT_ROTATION_ANCHOR = TextAnchor.CENTER; /** The default rotation angle. */ public static final double DEFAULT_ROTATION_ANGLE = 0.0; /** The text. */ private String text; /** The font. */ private Font font; /** The paint. */ private transient Paint paint; /** The text anchor. */ private TextAnchor textAnchor; /** The rotation anchor. */ private TextAnchor rotationAnchor; /** The rotation angle. */ private double rotationAngle; /** * Creates a text annotation with default settings. * * @param text the text (<code>null</code> not permitted). */ protected TextAnnotation(String text) { if (text == null) { throw new IllegalArgumentException("Null 'text' argument."); } this.text = text; this.font = DEFAULT_FONT; this.paint = DEFAULT_PAINT; this.textAnchor = DEFAULT_TEXT_ANCHOR; this.rotationAnchor = DEFAULT_ROTATION_ANCHOR; this.rotationAngle = DEFAULT_ROTATION_ANGLE; } /** * Returns the text for the annotation. * * @return The text (never <code>null</code>). * * @see #setText(String) */ public String getText() { return this.text; } /** * Sets the text for the annotation. * * @param text the text (<code>null</code> not permitted). * * @see #getText() */ public void setText(String text) { if (text == null) { throw new IllegalArgumentException("Null 'text' argument."); } this.text = text; } /** * Returns the font for the annotation. * * @return The font (never <code>null</code>). * * @see #setFont(Font) */ public Font getFont() { return this.font; } /** * Sets the font for the annotation. * * @param font the font (<code>null</code> not permitted). * * @see #getFont() */ public void setFont(Font font) { if (font == null) { throw new IllegalArgumentException("Null 'font' argument."); } this.font = font; } /** * Returns the paint for the annotation. * * @return The paint (never <code>null</code>). * * @see #setPaint(Paint) */ public Paint getPaint() { return this.paint; } /** * Sets the paint for the annotation. * * @param paint the paint (<code>null</code> not permitted). * * @see #getPaint() */ public void setPaint(Paint paint) { if (paint == null) { throw new IllegalArgumentException("Null 'paint' argument."); } this.paint = paint; } /** * Returns the text anchor. * * @return The text anchor. * * @see #setTextAnchor(TextAnchor) */ public TextAnchor getTextAnchor() { return this.textAnchor; } /** * Sets the text anchor (the point on the text bounding rectangle that is * aligned to the (x, y) coordinate of the annotation). * * @param anchor the anchor point (<code>null</code> not permitted). * * @see #getTextAnchor() */ public void setTextAnchor(TextAnchor anchor) { if (anchor == null) { throw new IllegalArgumentException("Null 'anchor' argument."); } this.textAnchor = anchor; } /** * Returns the rotation anchor. * * @return The rotation anchor point (never <code>null</code>). * * @see #setRotationAnchor(TextAnchor) */ public TextAnchor getRotationAnchor() { return this.rotationAnchor; } /** * Sets the rotation anchor point. * * @param anchor the anchor (<code>null</code> not permitted). * * @see #getRotationAnchor() */ public void setRotationAnchor(TextAnchor anchor) { this.rotationAnchor = anchor; } /** * Returns the rotation angle in radians. * * @return The rotation angle. * * @see #setRotationAngle(double) */ public double getRotationAngle() { return this.rotationAngle; } /** * Sets the rotation angle. The angle is measured clockwise in radians. * * @param angle the angle (in radians). * * @see #getRotationAngle() */ public void setRotationAngle(double angle) { this.rotationAngle = angle; } /** * Tests this object for equality with an arbitrary object. * * @param obj the object (<code>null</code> permitted). * * @return <code>true</code> or <code>false</code>. */ public boolean equals(Object obj) { if (obj == this) { return true; } // now try to reject equality... if (!(obj instanceof TextAnnotation)) { return false; } TextAnnotation that = (TextAnnotation) obj; if (!ObjectUtilities.equal(this.text, that.getText())) { return false; } if (!ObjectUtilities.equal(this.font, that.getFont())) { return false; } if (!PaintUtilities.equal(this.paint, that.getPaint())) { return false; } if (!ObjectUtilities.equal(this.textAnchor, that.getTextAnchor())) { return false; } if (!ObjectUtilities.equal(this.rotationAnchor, that.getRotationAnchor())) { return false; } if (this.rotationAngle != that.getRotationAngle()) { return false; } // seem to be the same... return true; } /** * Returns a hash code for this instance. * * @return A hash code. */ public int hashCode() { int result = 193; result = 37 * result + this.font.hashCode(); result = 37 * result + HashUtilities.hashCodeForPaint(this.paint); result = 37 * result + this.rotationAnchor.hashCode(); long temp = Double.doubleToLongBits(this.rotationAngle); result = 37 * result + (int) (temp ^ (temp >>> 32)); result = 37 * result + this.text.hashCode(); result = 37 * result + this.textAnchor.hashCode(); return result; } /** * Provides serialization support. * * @param stream the output stream. * * @throws IOException if there is an I/O error. */ private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); SerialUtilities.writePaint(this.paint, stream); } /** * Provides serialization support. * * @param stream the input stream. * * @throws IOException if there is an I/O error. * @throws ClassNotFoundException if there is a classpath problem. */ private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); this.paint = SerialUtilities.readPaint(stream); } }
package org.jfree.chart.renderer.xy; import java.awt.BasicStroke; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Polygon; import java.awt.Shape; import java.awt.Stroke; import java.awt.geom.Area; import java.awt.geom.GeneralPath; import java.awt.geom.Line2D; import java.awt.geom.Rectangle2D; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import org.jfree.chart.LegendItem; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.entity.EntityCollection; import org.jfree.chart.event.RendererChangeEvent; import org.jfree.chart.labels.XYSeriesLabelGenerator; import org.jfree.chart.labels.XYToolTipGenerator; import org.jfree.chart.plot.CrosshairState; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.PlotRenderingInfo; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.urls.XYURLGenerator; import org.jfree.chart.util.PublicCloneable; import org.jfree.chart.util.SerialUtilities; import org.jfree.chart.util.ShapeUtilities; import org.jfree.data.xy.XYDataset; public class XYAreaRenderer extends AbstractXYItemRenderer implements XYItemRenderer, PublicCloneable { /** For serialization. */ private static final long serialVersionUID = -4481971353973876747L; /** * A state object used by this renderer. */ static class XYAreaRendererState extends XYItemRendererState { /** Working storage for the area under one series. */ public Polygon area; /** Working line that can be recycled. */ public Line2D line; /** * Creates a new state. * * @param info the plot rendering info. */ public XYAreaRendererState(PlotRenderingInfo info) { super(info); this.area = new Polygon(); this.line = new Line2D.Double(); } } /** Useful constant for specifying the type of rendering (shapes only). */ public static final int SHAPES = 1; /** Useful constant for specifying the type of rendering (lines only). */ public static final int LINES = 2; /** * Useful constant for specifying the type of rendering (shapes and lines). */ public static final int SHAPES_AND_LINES = 3; /** Useful constant for specifying the type of rendering (area only). */ public static final int AREA = 4; /** * Useful constant for specifying the type of rendering (area and shapes). */ public static final int AREA_AND_SHAPES = 5; /** A flag indicating whether or not shapes are drawn at each XY point. */ private boolean plotShapes; /** A flag indicating whether or not lines are drawn between XY points. */ private boolean plotLines; /** A flag indicating whether or not Area are drawn at each XY point. */ private boolean plotArea; /** A flag that controls whether or not the outline is shown. */ private boolean showOutline; /** * The shape used to represent an area in each legend item (this should * never be <code>null</code>). */ private transient Shape legendArea; /** * Constructs a new renderer. */ public XYAreaRenderer() { this(AREA); } /** * Constructs a new renderer. * * @param type the type of the renderer. */ public XYAreaRenderer(int type) { this(type, null, null); } /** * Constructs a new renderer. To specify the type of renderer, use one of * the constants: <code>SHAPES</code>, <code>LINES</code>, * <code>SHAPES_AND_LINES</code>, <code>AREA</code> or * <code>AREA_AND_SHAPES</code>. * * @param type the type of renderer. * @param toolTipGenerator the tool tip generator to use * (<code>null</code> permitted). * @param urlGenerator the URL generator (<code>null</code> permitted). */ public XYAreaRenderer(int type, XYToolTipGenerator toolTipGenerator, XYURLGenerator urlGenerator) { super(); setBaseToolTipGenerator(toolTipGenerator); setBaseURLGenerator(urlGenerator); if (type == SHAPES) { this.plotShapes = true; } if (type == LINES) { this.plotLines = true; } if (type == SHAPES_AND_LINES) { this.plotShapes = true; this.plotLines = true; } if (type == AREA) { this.plotArea = true; } if (type == AREA_AND_SHAPES) { this.plotArea = true; this.plotShapes = true; } this.showOutline = false; GeneralPath area = new GeneralPath(); area.moveTo(0.0f, -4.0f); area.lineTo(3.0f, -2.0f); area.lineTo(4.0f, 4.0f); area.lineTo(-4.0f, 4.0f); area.lineTo(-3.0f, -2.0f); area.closePath(); this.legendArea = area; } /** * Returns true if shapes are being plotted by the renderer. * * @return <code>true</code> if shapes are being plotted by the renderer. */ public boolean getPlotShapes() { return this.plotShapes; } /** * Returns true if lines are being plotted by the renderer. * * @return <code>true</code> if lines are being plotted by the renderer. */ public boolean getPlotLines() { return this.plotLines; } /** * Returns true if Area is being plotted by the renderer. * * @return <code>true</code> if Area is being plotted by the renderer. */ public boolean getPlotArea() { return this.plotArea; } /** * Returns a flag that controls whether or not outlines of the areas are * drawn. * * @return The flag. * * @see #setOutline(boolean) */ public boolean isOutline() { return this.showOutline; } /** * Sets a flag that controls whether or not outlines of the areas are drawn * and sends a {@link RendererChangeEvent} to all registered listeners. * * @param show the flag. * * @see #isOutline() */ public void setOutline(boolean show) { this.showOutline = show; fireChangeEvent(); } /** * Returns the shape used to represent an area in the legend. * * @return The legend area (never <code>null</code>). */ public Shape getLegendArea() { return this.legendArea; } /** * Sets the shape used as an area in each legend item and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param area the area (<code>null</code> not permitted). */ public void setLegendArea(Shape area) { if (area == null) { throw new IllegalArgumentException("Null 'area' argument."); } this.legendArea = area; fireChangeEvent(); } /** * Initialises the renderer and returns a state object that should be * passed to all subsequent calls to the drawItem() method. * * @param g2 the graphics device. * @param dataArea the area inside the axes. * @param plot the plot. * @param data the data. * @param info an optional info collection object to return data back to * the caller. * * @return A state object for use by the renderer. */ public XYItemRendererState initialise(Graphics2D g2, Rectangle2D dataArea, XYPlot plot, XYDataset data, PlotRenderingInfo info) { XYAreaRendererState state = new XYAreaRendererState(info); // in the rendering process, there is special handling for item // zero, so we can't support processing of visible data items only state.setProcessVisibleItemsOnly(false); return state; } /** * Returns a default legend item for the specified series. Subclasses * should override this method to generate customised items. * * @param datasetIndex the dataset index (zero-based). * @param series the series index (zero-based). * * @return A legend item for the series. */ public LegendItem getLegendItem(int datasetIndex, int series) { LegendItem result = null; XYPlot xyplot = getPlot(); if (xyplot != null) { XYDataset dataset = xyplot.getDataset(datasetIndex); if (dataset != null) { XYSeriesLabelGenerator lg = getLegendItemLabelGenerator(); String label = lg.generateLabel(dataset, series); String description = label; String toolTipText = null; if (getLegendItemToolTipGenerator() != null) { toolTipText = getLegendItemToolTipGenerator().generateLabel( dataset, series); } String urlText = null; if (getLegendItemURLGenerator() != null) { urlText = getLegendItemURLGenerator().generateLabel( dataset, series); } Paint paint = lookupSeriesPaint(series); result = new LegendItem(label, description, toolTipText, urlText, this.legendArea, paint); result.setLabelFont(lookupLegendTextFont(series)); Paint labelPaint = lookupLegendTextPaint(series); if (labelPaint != null) { result.setLabelPaint(labelPaint); } result.setDataset(dataset); result.setDatasetIndex(datasetIndex); result.setSeriesKey(dataset.getSeriesKey(series)); result.setSeriesIndex(series); } } return result; } /** * Draws the visual representation of a single data item. * * @param g2 the graphics device. * @param state the renderer state. * @param dataArea the area within which the data is being drawn. * @param info collects information about the drawing. * @param plot the plot (can be used to obtain standard color information * etc). * @param domainAxis the domain axis. * @param rangeAxis the range axis. * @param dataset the dataset. * @param series the series index (zero-based). * @param item the item index (zero-based). * @param crosshairState crosshair information for the plot * (<code>null</code> permitted). * @param pass the pass index. */ public void drawItem(Graphics2D g2, XYItemRendererState state, Rectangle2D dataArea, PlotRenderingInfo info, XYPlot plot, ValueAxis domainAxis, ValueAxis rangeAxis, XYDataset dataset, int series, int item, CrosshairState crosshairState, int pass) { if (!getItemVisible(series, item)) { return; } XYAreaRendererState areaState = (XYAreaRendererState) state; // get the data point... double x1 = dataset.getXValue(series, item); double y1 = dataset.getYValue(series, item); if (Double.isNaN(y1)) { y1 = 0.0; } double transX1 = domainAxis.valueToJava2D(x1, dataArea, plot.getDomainAxisEdge()); double transY1 = rangeAxis.valueToJava2D(y1, dataArea, plot.getRangeAxisEdge()); // get the previous point and the next point so we can calculate a // "hot spot" for the area (used by the chart entity)... int itemCount = dataset.getItemCount(series); double x0 = dataset.getXValue(series, Math.max(item - 1, 0)); double y0 = dataset.getYValue(series, Math.max(item - 1, 0)); if (Double.isNaN(y0)) { y0 = 0.0; } double transX0 = domainAxis.valueToJava2D(x0, dataArea, plot.getDomainAxisEdge()); double transY0 = rangeAxis.valueToJava2D(y0, dataArea, plot.getRangeAxisEdge()); double x2 = dataset.getXValue(series, Math.min(item + 1, itemCount - 1)); double y2 = dataset.getYValue(series, Math.min(item + 1, itemCount - 1)); if (Double.isNaN(y2)) { y2 = 0.0; } double transX2 = domainAxis.valueToJava2D(x2, dataArea, plot.getDomainAxisEdge()); double transY2 = rangeAxis.valueToJava2D(y2, dataArea, plot.getRangeAxisEdge()); double transZero = rangeAxis.valueToJava2D(0.0, dataArea, plot.getRangeAxisEdge()); Polygon hotspot = null; if (plot.getOrientation() == PlotOrientation.HORIZONTAL) { hotspot = new Polygon(); hotspot.addPoint((int) transZero, (int) ((transX0 + transX1) / 2.0)); hotspot.addPoint((int) ((transY0 + transY1) / 2.0), (int) ((transX0 + transX1) / 2.0)); hotspot.addPoint((int) transY1, (int) transX1); hotspot.addPoint((int) ((transY1 + transY2) / 2.0), (int) ((transX1 + transX2) / 2.0)); hotspot.addPoint((int) transZero, (int) ((transX1 + transX2) / 2.0)); } else { // vertical orientation hotspot = new Polygon(); hotspot.addPoint((int) ((transX0 + transX1) / 2.0), (int) transZero); hotspot.addPoint((int) ((transX0 + transX1) / 2.0), (int) ((transY0 + transY1) / 2.0)); hotspot.addPoint((int) transX1, (int) transY1); hotspot.addPoint((int) ((transX1 + transX2) / 2.0), (int) ((transY1 + transY2) / 2.0)); hotspot.addPoint((int) ((transX1 + transX2) / 2.0), (int) transZero); } if (item == 0) { // create a new area polygon for the series areaState.area = new Polygon(); // the first point is (x, 0) double zero = rangeAxis.valueToJava2D(0.0, dataArea, plot.getRangeAxisEdge()); if (plot.getOrientation() == PlotOrientation.VERTICAL) { areaState.area.addPoint((int) transX1, (int) zero); } else if (plot.getOrientation() == PlotOrientation.HORIZONTAL) { areaState.area.addPoint((int) zero, (int) transX1); } } // Add each point to Area (x, y) if (plot.getOrientation() == PlotOrientation.VERTICAL) { areaState.area.addPoint((int) transX1, (int) transY1); } else if (plot.getOrientation() == PlotOrientation.HORIZONTAL) { areaState.area.addPoint((int) transY1, (int) transX1); } PlotOrientation orientation = plot.getOrientation(); Paint paint = getItemPaint(series, item); Stroke stroke = getItemStroke(series, item); g2.setPaint(paint); g2.setStroke(stroke); Shape shape = null; if (getPlotShapes()) { shape = getItemShape(series, item); if (orientation == PlotOrientation.VERTICAL) { shape = ShapeUtilities.createTranslatedShape(shape, transX1, transY1); } else if (orientation == PlotOrientation.HORIZONTAL) { shape = ShapeUtilities.createTranslatedShape(shape, transY1, transX1); } g2.draw(shape); } if (getPlotLines()) { if (item > 0) { if (plot.getOrientation() == PlotOrientation.VERTICAL) { areaState.line.setLine(transX0, transY0, transX1, transY1); } else if (plot.getOrientation() == PlotOrientation.HORIZONTAL) { areaState.line.setLine(transY0, transX0, transY1, transX1); } g2.draw(areaState.line); } } // Check if the item is the last item for the series. // and number of items > 0. We can't draw an area for a single point. if (getPlotArea() && item > 0 && item == (itemCount - 1)) { if (orientation == PlotOrientation.VERTICAL) { // Add the last point (x,0) areaState.area.addPoint((int) transX1, (int) transZero); } else if (orientation == PlotOrientation.HORIZONTAL) { // Add the last point (x,0) areaState.area.addPoint((int) transZero, (int) transX1); } g2.fill(areaState.area); // draw an outline around the Area. if (isOutline()) { Shape area = areaState.area; // Java2D has some issues drawing dashed lines around "large" // geometrical shapes - for example, see bug 6620013 in the // Java bug database. So, we'll check if the outline is // dashed and, if it is, do our own clipping before drawing // the outline... Stroke outlineStroke = lookupSeriesOutlineStroke(series); if (outlineStroke instanceof BasicStroke) { BasicStroke bs = (BasicStroke) outlineStroke; if (bs.getDashArray() != null) { Area poly = new Area(areaState.area); // we make the clip region slightly larger than the // dataArea so that the clipped edges don't show lines // on the chart Area clip = new Area(new Rectangle2D.Double( dataArea.getX() - 5.0, dataArea.getY() - 5.0, dataArea.getWidth() + 10.0, dataArea.getHeight() + 10.0)); poly.intersect(clip); area = poly; } } // end of workaround g2.setStroke(outlineStroke); g2.setPaint(lookupSeriesOutlinePaint(series)); g2.draw(area); } } int domainAxisIndex = plot.getDomainAxisIndex(domainAxis); int rangeAxisIndex = plot.getRangeAxisIndex(rangeAxis); updateCrosshairValues(crosshairState, x1, y1, domainAxisIndex, rangeAxisIndex, transX1, transY1, orientation); // collect entity and tool tip information... EntityCollection entities = state.getEntityCollection(); if (entities != null && hotspot != null) { addEntity(entities, hotspot, dataset, series, item, 0.0, 0.0); } } /** * Returns a clone of the renderer. * * @return A clone. * * @throws CloneNotSupportedException if the renderer cannot be cloned. */ public Object clone() throws CloneNotSupportedException { XYAreaRenderer clone = (XYAreaRenderer) super.clone(); clone.legendArea = ShapeUtilities.clone(this.legendArea); return clone; } /** * Tests this renderer for equality with an arbitrary object. * * @param obj the object (<code>null</code> permitted). * * @return A boolean. */ public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof XYAreaRenderer)) { return false; } XYAreaRenderer that = (XYAreaRenderer) obj; if (this.plotArea != that.plotArea) { return false; } if (this.plotLines != that.plotLines) { return false; } if (this.plotShapes != that.plotShapes) { return false; } if (this.showOutline != that.showOutline) { return false; } if (!ShapeUtilities.equal(this.legendArea, that.legendArea)) { return false; } return true; } /** * Provides serialization support. * * @param stream the input stream. * * @throws IOException if there is an I/O error. * @throws ClassNotFoundException if there is a classpath problem. */ private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); this.legendArea = SerialUtilities.readShape(stream); } /** * Provides serialization support. * * @param stream the output stream. * * @throws IOException if there is an I/O error. */ private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); SerialUtilities.writeShape(this.legendArea, stream); } }
package romanNumeralEvaluator; public class RomanNumeralTester { private static RomanNumeralEvaluator numeralConverter = new RomanNumeralEvaluator(); public static void main(String[] args) { //Generate the Roman Numerals. System.out.println("Hello. Welcome to the Roman Numeral Tester"); System.out.print("66 in Roman Numerals is "); System.out.println(numeralConverter.convertNumberToRomanNumeral(66)); System.out.print("XXII in decimal is "); System.out.println(numeralConverter.convertRomanNumeralToNumber("XXII")); } }
package org.dspace.eperson.test; import junit.framework.*; import org.dspace.core.*; import org.dspace.eperson.*; /** * JUnit test for Group API * * @author Peter Breton * @version $Revision$ */ public class GroupTest extends TestCase { /** * Constructor * * @param name - The name of the TestCase */ public GroupTest (String name) { super(name); } /** * JUnit test method */ public void testGroup() { Context context = null; try { String name = "Test Group created by " + GroupTest.class.getName(); context = new Context(); context.setIgnoreAuthorization(true); EPerson e1 = EPerson.create(context); EPerson e2 = EPerson.create(context); Group g = Group.create(context); g.setName(name); g.addMember(e1); g.addMember(e2); // Deliberately duplicate e2 g.addMember(e2); // The static isMember method will not work until update // has been called g.update(); // Find methods assertEquals("Found group by id", Group.find(context, g.getID()), g); assertEquals("Found group by name", Group.findByName(context, name), g); // Test membership assertTrue("EPerson is member of group", g.isMember(e1)); assertTrue("EPerson is member of group", Group.isMember(context, g.getID(), e1.getID())); assertTrue("EPerson is member of group", g.isMember(e2)); assertTrue("EPerson is member of group", Group.isMember(context, g.getID(), e2.getID())); EPerson[] members = g.getMembers(); assertNotNull("Got group members", members); assertEquals("Group size is 2", members.length, 2); // Test deletion of eperson g.removeMember(e2); g.update(); assertTrue("EPerson deleted from group", ! g.isMember(e2)); assertTrue("EPerson deleted from group", ! Group.isMember(context, g.getID(), e2.getID())); // Test deletion of group g.delete(); assertTrue("EPerson is not a member of deleted group", ! g.isMember(e1)); assertTrue("EPerson is not a member of deleted group", ! Group.isMember(context, g.getID(), e1.getID())); assertNull("Cannot find deleted group by id", Group.find(context, g.getID())); assertNull("Cannot find deleted group by name", Group.findByName(context, name)); } catch (Exception e) { e.printStackTrace(); System.out.println("Got exception: " + e); fail("Exception while running test: " + e); } finally { if (context != null) context.abort(); } } /** * Test suite */ public static Test suite() { return new TestSuite(GroupTest.class); } /** * Embedded test harness * * @param argv - Command-line arguments */ public static void main(String[] argv) { junit.textui.TestRunner.run(suite()); System.exit(0); } }
package de.danielnaber.languagetool.gui; import java.awt.Container; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.Toolkit; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.IOException; import java.io.Reader; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTextArea; import javax.swing.JTextPane; import javax.swing.filechooser.FileFilter; import javax.xml.parsers.ParserConfigurationException; import org.jdesktop.jdic.tray.SystemTray; import org.jdesktop.jdic.tray.TrayIcon; import org.xml.sax.SAXException; import de.danielnaber.languagetool.JLanguageTool; import de.danielnaber.languagetool.Language; import de.danielnaber.languagetool.rules.Rule; import de.danielnaber.languagetool.rules.RuleMatch; import de.danielnaber.languagetool.tools.StringTools; /** * A simple GUI to check texts with. * * @author Daniel Naber */ public class Main implements ActionListener { private static final String HTML_FONT_START = "<font face='Arial,Helvetica'>"; private static final String HTML_FONT_END = "</font>"; private static final Icon SYSTEM_TRAY_ICON = new ImageIcon("resource/TrayIcon.png"); private static final String WINDOW_ICON_URL = "resource/TrayIcon.png"; private static final String CHECK_TEXT_BUTTON = "Check text"; private TrayIcon trayIcon = null; private JFrame frame = null; private JTextArea textArea = null; private JTextPane resultArea = null; private JComboBox langBox = null; private Map<Language, ConfigurationDialog> configDialogs = new HashMap<Language, ConfigurationDialog>(); private Main() { } private void createGUI() { frame = new JFrame("LanguageTool " +JLanguageTool.VERSION+ " Demo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setIconImage(new ImageIcon(WINDOW_ICON_URL).getImage()); frame.setJMenuBar(new MainMenuBar(this)); textArea = new JTextArea("This is a example input to to show you how JLanguageTool works. " + "Note, however, that it does not include a spell checka."); // TODO: wrong line number is displayed for lines that are wrapped automatically: textArea.setLineWrap(true); textArea.setWrapStyleWord(true); resultArea = new JTextPane(); resultArea.setContentType("text/html"); resultArea.setText(HTML_FONT_START + "Results will appear here" + HTML_FONT_END); JLabel label = new JLabel("Please type or paste text to check in the top area"); JButton button = new JButton(CHECK_TEXT_BUTTON); button.setMnemonic('c'); button.addActionListener(this); JPanel panel = new JPanel(); panel.setLayout(new GridBagLayout()); GridBagConstraints buttonCons = new GridBagConstraints(); buttonCons.gridx = 0; buttonCons.gridy = 0; panel.add(button, buttonCons); buttonCons.gridx = 1; buttonCons.gridy = 0; panel.add(new JLabel(" in: "), buttonCons); buttonCons.gridx = 2; buttonCons.gridy = 0; langBox = new JComboBox(); for (Language lang : Language.LANGUAGES) { if (lang != Language.DEMO) { langBox.addItem(lang); } } panel.add(langBox, buttonCons); Container contentPane = frame.getContentPane(); GridBagLayout gridLayout = new GridBagLayout(); contentPane.setLayout(gridLayout); GridBagConstraints cons = new GridBagConstraints(); cons.insets = new Insets(5, 5, 5, 5); cons.fill = GridBagConstraints.BOTH; cons.weightx = 10.0f; cons.weighty = 10.0f; cons.gridx = 0; cons.gridy = 1; cons.weighty = 5.0f; JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, new JScrollPane(textArea), new JScrollPane(resultArea)); splitPane.setDividerLocation(200); contentPane.add(splitPane, cons); cons.fill = GridBagConstraints.NONE; cons.gridx = 0; cons.gridy = 2; cons.weighty = 0.0f; cons.insets = new Insets(3,3,3,3); //cons.fill = GridBagConstraints.NONE; contentPane.add(label, cons); cons.gridy = 3; contentPane.add(panel, cons); frame.pack(); frame.setSize(600, 600); } private void showGUI() { frame.setVisible(true); } public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals(CHECK_TEXT_BUTTON)) { JLanguageTool langTool = getCurrentLanguageTool(); checkTextAndDisplayResults(langTool, getCurrentLanguage().getName()); } else { throw new IllegalArgumentException("Unknown action " + e); } } void loadFile() { JFileChooser jfc = new JFileChooser(); jfc.setFileFilter(new PlainTextFilter()); jfc.showOpenDialog(frame); try { File file = jfc.getSelectedFile(); if (file == null) // user cancelled return; String fileContents = StringTools.readFile(file.getAbsolutePath()); textArea.setText(fileContents); JLanguageTool langTool = getCurrentLanguageTool(); checkTextAndDisplayResults(langTool, getCurrentLanguage().getName()); } catch (IOException e) { JOptionPane.showMessageDialog(null, e.toString()); e.printStackTrace(); } } void hideToTray() { if (trayIcon == null) { trayIcon = new TrayIcon(SYSTEM_TRAY_ICON); SystemTray tray = SystemTray.getDefaultSystemTray(); trayIcon.addActionListener(new TrayActionListener()); tray.addTrayIcon(trayIcon); } frame.setVisible(false); } void showOptions() { JLanguageTool langTool = getCurrentLanguageTool(); List<Rule> rules = langTool.getAllRules(); ConfigurationDialog configDialog = getCurrentConfigDialog(); configDialog.show(rules); } private void restoreFromTray() { // get text from clipboard or selection: Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemSelection(); if (clipboard == null) { // on Windows clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); } String s = null; Transferable data = clipboard.getContents(this); try { DataFlavor df = DataFlavor.getTextPlainUnicodeFlavor(); Reader sr = df.getReaderForText(data); s = StringTools.readerToString(sr); } catch (Exception ex) { ex.printStackTrace(); s = data.toString(); } // show GUI and check the text from clipboard/selection: frame.setVisible(true); textArea.setText(s); JLanguageTool langTool = getCurrentLanguageTool(); checkTextAndDisplayResults(langTool, getCurrentLanguage().getName()); } void quit() { if (trayIcon != null) { SystemTray tray = SystemTray.getDefaultSystemTray(); tray.removeTrayIcon(trayIcon); } frame.setVisible(false); } private Language getCurrentLanguage() { String langName = langBox.getSelectedItem().toString(); return Language.getLanguageforName(langName); } private ConfigurationDialog getCurrentConfigDialog() { Language language = getCurrentLanguage(); ConfigurationDialog configDialog = null; if (configDialogs.containsKey(language)) { configDialog = (ConfigurationDialog)configDialogs.get(language); } else { configDialog = new ConfigurationDialog(false); configDialogs.put(language, configDialog); } return configDialog; } private JLanguageTool getCurrentLanguageTool() { JLanguageTool langTool; try { ConfigurationDialog configDialog = getCurrentConfigDialog(); langTool = new JLanguageTool(getCurrentLanguage(), configDialog.getMotherTongue()); langTool.activateDefaultPatternRules(); langTool.activateDefaultFalseFriendRules(); Set<String> disabledRules = configDialog.getDisabledRuleIds(); if (disabledRules != null) { for (String ruleId : disabledRules) { langTool.disableRule(ruleId); } } } catch (IOException ioe) { throw new RuntimeException(ioe); } catch (ParserConfigurationException ex) { throw new RuntimeException(ex); } catch (SAXException ex) { throw new RuntimeException(ex); } return langTool; } private void checkTextAndDisplayResults(JLanguageTool langTool, String langName) { if (textArea.getText().trim().equals("")) { textArea.setText("Please insert text to check here"); } else { StringBuilder sb = new StringBuilder(); resultArea.setText(HTML_FONT_START + "Starting check in "+langName+"...<br>\n" + HTML_FONT_END); resultArea.repaint(); // FIXME: why doesn't this work? //TODO: resultArea.setCursor(new Cursor(Cursor.WAIT_CURSOR)); sb.append("Starting check in " +langName+ "...<br>\n"); int matches = 0; try { matches = checkText(langTool, textArea.getText(), sb); } catch (Exception ex) { sb.append("<br><br><b><font color=\"red\">" + ex.toString() + "<br>"); StackTraceElement[] elements = ex.getStackTrace(); for (StackTraceElement element : elements) { sb.append(element + "<br>"); } sb.append("</font></b><br>"); ex.printStackTrace(); } sb.append("Check done. " +matches+ " potential problems found<br>\n"); resultArea.setText(HTML_FONT_START + sb.toString() + HTML_FONT_END); resultArea.setCaretPosition(0); } } private int checkText(JLanguageTool langTool, String text, StringBuilder sb) throws IOException { long startTime = System.currentTimeMillis(); List<RuleMatch> ruleMatches = langTool.check(text); long startTimeMatching = System.currentTimeMillis(); int i = 0; for (RuleMatch match : ruleMatches) { sb.append("<br>\n<b>" +(i+1)+ ". Line " + (match.getLine() + 1) + ", column " + match.getColumn() + "</b><br>\n"); String msg = match.getMessage(); msg = msg.replaceAll("<suggestion>", "<b>"); msg = msg.replaceAll("</suggestion>", "</b>"); msg = msg.replaceAll("<old>", "<b>"); msg = msg.replaceAll("</old>", "</b>"); sb.append("<b>Message:</b> " + msg + "<br>\n"); String context = Tools.getContext(match.getFromPos(), match.getToPos(), StringTools.escapeHTML(text)); sb.append("<b>Context:</b> " + context); sb.append("<br>\n"); i++; } long endTime = System.currentTimeMillis(); sb.append("<br>\nTime: " + (endTime - startTime) + "ms (including " + (endTime - startTimeMatching) + "ms for rule matching)<br>\n"); return ruleMatches.size(); } public static void main(String[] args) { final Main prg = new Main(); if (args.length == 1 && (args[0].equals("-t") || args[0].equals("--tray"))) { // dock to systray on startup javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { prg.createGUI(); prg.hideToTray(); } }); } else if (args.length >= 1) { System.out.println("Usage: java de.danielnaber.languagetool.gui.Main [-t|--tray]"); System.out.println(" -t|--tray: dock LanguageTool to tray on startup"); } else { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { prg.createGUI(); prg.showGUI(); } }); } } // The System Tray stuff class TrayActionListener implements ActionListener { public void actionPerformed(@SuppressWarnings("unused") ActionEvent e) { if (frame.isVisible() && frame.isActive()) { frame.setVisible(false); } else if (frame.isVisible() && !frame.isActive()) { frame.toFront(); restoreFromTray(); } else { restoreFromTray(); } } } class PlainTextFilter extends FileFilter { public boolean accept(File f) { if (f.getName().toLowerCase().endsWith(".txt")) return true; return false; } public String getDescription() { return "*.txt"; } } }
package examples.bookTrading; import java.util.Hashtable; import java.util.Random; import jade.core.Agent; import jade.core.behaviours.CyclicBehaviour; import jade.core.behaviours.OneShotBehaviour; import jade.domain.DFService; import jade.domain.FIPAException; import jade.domain.FIPAAgentManagement.DFAgentDescription; import jade.domain.FIPAAgentManagement.ServiceDescription; import jade.lang.acl.ACLMessage; import jade.lang.acl.MessageTemplate; public class BookSellerAgent extends Agent { private static final long serialVersionUID = -8742249310687723764L; private Hashtable<String, Integer> availableBooks = new Hashtable<String, Integer>(); private BookSellerGUI myGUI; private void trace(String p_message) { String agentType = "Seller-agent "; System.out.println(agentType + "(" + getAID().getName() + ") " + p_message); } protected void setup() { initializeData(); initializeGUI(); registerInDirectoryFacilitator(); initializeBehaviour(); trace("is ready"); } protected void takeDown() { deregisterInDirectoryFacilitator(); finalizeGUI(); trace("is terminated"); } private void initializeData() { Random rand = new Random(); registerBook(new String("The-Lord-of-the-rings"), new Integer(rand.nextInt(100))); } private void initializeGUI() { myGUI = new BookSellerGUI(this); myGUI.showGUI(); } private void finalizeGUI() { myGUI.dispose(); } private void registerInDirectoryFacilitator() { DFAgentDescription agentDescription = new DFAgentDescription(); agentDescription.setName(getAID()); ServiceDescription serviceDescription = new ServiceDescription(); serviceDescription.setName("JADE-book-trading"); serviceDescription.setType("book-selling"); agentDescription.addServices(serviceDescription); try { DFService.register(this, agentDescription); } catch(FIPAException exception) { exception.printStackTrace(); } } private void deregisterInDirectoryFacilitator() { try { DFService.deregister(this); } catch(FIPAException exception) { exception.printStackTrace(); } } private void initializeBehaviour() { addBehaviour(new OfferRequestProcessing()); addBehaviour(new PurchaseRequestProcessing()); } public void registerBook(final String p_title, final Integer p_price) { addBehaviour(new RegisterBookInAvailableBooks(p_title, p_price)); } class RegisterBookInAvailableBooks extends OneShotBehaviour { private static final long serialVersionUID = -5766869902626092150L; String title; Integer price; public RegisterBookInAvailableBooks(String p_title, Integer p_price) { title = p_title; price = p_price; } public void action() { availableBooks.put(title, price); System.out.println(title +" inserted into catalogue. Price = " + price); } } class OfferRequestProcessing extends CyclicBehaviour { private static final long serialVersionUID = 1421695410309195595L; public void action() { ACLMessage msg = myAgent.receive(); if(msg != null) { String bookTitle = msg.getContent(); ACLMessage msgReply = msg.createReply(); Integer bookPrice = (Integer) availableBooks.get(bookTitle); if( bookPrice != null) { msgReply.setPerformative(ACLMessage.PROPOSE); msgReply.setContent(String.valueOf(bookPrice.intValue())); } else { msgReply.setPerformative(ACLMessage.REFUSE); msgReply.setContent("not-available"); } myAgent.send(msgReply); } else { block(); } } } class PurchaseRequestProcessing extends CyclicBehaviour { private static final long serialVersionUID = 2627668785596772159L; public void action() { MessageTemplate mt = MessageTemplate.MatchPerformative(ACLMessage.ACCEPT_PROPOSAL); ACLMessage msg = myAgent.receive(mt); if (msg != null) { String title = msg.getContent(); ACLMessage reply = msg.createReply(); Integer price = (Integer) availableBooks.remove(title); if (price != null) { reply.setPerformative(ACLMessage.INFORM); System.out.println(title+" sold to agent " + msg.getSender().getName()); } else { reply.setPerformative(ACLMessage.FAILURE); reply.setContent("not-available"); } myAgent.send(reply); } else { block(); } } } }
package com.db.gui; import java.awt.Dimension; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.JComponent; import javax.swing.JTable; import javax.swing.table.JTableHeader; import javax.swing.table.TableModel; import com.db.event.EventDelegate; import com.db.event.EventObject; /** * Table that allows JComponents to be displayed in its cells and header. * * Sorting is also supported. * * @author Dave Longley */ public class JComponentTable extends JTable { /** * Whether or not this table is editable. */ protected boolean mEditable; /** * An event delegate for firing double click events. */ protected EventDelegate mDoubleClickEventDelegate; /** * Creates a new JComponentTable using the passed JComponentTableModel. * * @param jctm the JComponentTableModel to use. */ public JComponentTable(JComponentTableModel jctm) { super(jctm); // create the double click event delegate mDoubleClickEventDelegate = new EventDelegate(); setEditable(true); setupTableHeader(); // set default editors for JComponents setDefaultEditor(JComponent.class, new JComponentCellEditor()); setDefaultRenderer(JComponent.class, new JComponentCellRenderer()); // set table column header renderers jctm.setTableColumnHeaderRenderers( this, (JComponentTableHeader)getTableHeader()); // set table dimensions jctm.setTableDimensions(this); // add mouse adapter as listener addMouseListener(new JComponentTableMouseAdapter(this)); } /** * Sets up the table header. */ protected void setupTableHeader() { // setup the table header JComponentTableHeader header = new JComponentTableHeader(getColumnModel()); setTableHeader(header); } /** * Fires a double click event. * * @param row the selected row. */ public void fireDoubleClickEvent(int row) { // create event EventObject event = new EventObject("tableDoubleClicked"); event.setData("table", this); event.setDataKeyMessage("table", "The JComponentTable that was double clicked."); event.setData("row", this); event.setDataKeyMessage("row", "The row index (int) of the selected row."); // fire the event getDoubleClickEventDelegate().fireEvent(event); } /** * Sets the data model for this table to <code>newModel</code> and registers * with it for listener notifications from the new data model. * * @param dataModel the new data source for this table. */ public void setModel(TableModel dataModel) { super.setModel(dataModel); JTableHeader header = getTableHeader(); if(header != null) { header.setColumnModel(getColumnModel()); } if(dataModel instanceof JComponentTableModel) { JComponentTableModel jctm = (JComponentTableModel)dataModel; jctm.setScrollResizingOn(this, true); } } /** * Sets whether or not this table is editable. * * @param editable true to make this table editable, false not to. */ public void setEditable(boolean editable) { mEditable = editable; } /** * Returns whether or not this table is editable. * * @return true if this table is editable, false if not. */ public boolean isEditable() { return mEditable; } /** * Returns true if the cell at <code>row</code> and <code>column</code> * is editable. Otherwise, invoking <code>setValueAt</code> on the cell * will have no effect. * <p> * <b>Note</b>: The column is specified in the table view's display * order, and not in the <code>TableModel</code>'s column * order. This is an important distinction because as the * user rearranges the columns in the table, * the column at a given index in the view will change. * Meanwhile the user's actions never affect the model's * column ordering. * * @param row the row whose value is to be queried. * @param column the column whose value is to be queried. * * @return true if the cell is editable. */ public boolean isCellEditable(int row, int column) { boolean rval = false; if(isEditable()) { rval = super.isCellEditable(row, column); } else { rval = false; } return rval; } /** * If the preferredSize has been set to a non-null value just returns it. * If the UI delegate's getPreferredSize method returns a non null value * then return that; otherwise defer to the component's layout manager. * * @return the value of the preferredSize property */ public Dimension getPreferredSize() { // keep preferred height Dimension size = super.getPreferredSize(); // add up preferred width size.width = this.getColumnModel().getTotalColumnWidth(); return size; } /** * Gets the double click event delegate. * * @return the double click event delegate. */ public EventDelegate getDoubleClickEventDelegate() { return mDoubleClickEventDelegate; } /** * A mouse adapter for handling double clicks on the table. * * @author Dave Longley */ public class JComponentTableMouseAdapter extends MouseAdapter { /** * The table this mouse adapter is for. */ protected JComponentTable mTable; /** * Creates a new JComponentTableMouseAdapter. * * @param table the table this mouse adapter is for. */ public JComponentTableMouseAdapter(JComponentTable table) { // store table mTable = table; } /** * Called when the mouse is clicked on the table. * * @param e the mouse event. */ public void mouseClicked(MouseEvent e) { // handle double click if(e.getClickCount() == 2) { // get selected row int row = mTable.getSelectedRow(); // if a row was selected, fire an event if(row != -1) { mTable.fireDoubleClickEvent(row); } } } } }
package verification.platu.main; public class Options { /* * Levels given by an integer number to indicate the amount information to display * while the tool is running */ private static int verbosity = 0; /* * Path in the host where the DOT program is located */ private static String dotPath = Main.workingDirectory; /* * Timing analysis options: */ public static enum timingAnalysisDef { ON, // no timing; zone - use regular zones; ABSTRACTION // merge zones to form convex hull for the same untimed state. } private static String timingAnalysisType = "off"; // Hao's Partial Order reduction options. // /* // * Partial order reduction options // */ // public static enum PorDef { // OFF, // no POR // STATIC, // POR based on dependency relation by static analysis // BEHAVIORAL // POR based on dependency relation by behavioral analysis // private static String POR = "off"; /** * Partial order reduction options for ample set computation (not including ample computation for cycle closing check). * @author Zhen Zhang * */ public static enum PorDef { TB, // POR with trace-back TBOFF, // POR without trace-back BEHAVIORAL, // POR with behavioral analysis OFF // No POR } private static String POR = "off"; /** * Options for dealing with transition rates when partial order reduction is applied. * @author Zhen Zhang */ public static enum tranRatePorDef { FULL, // Fully consider dependency relations in transition rates AVRG, // Add a second criterion for persistent set computation. When more than one persistent sets have the smallest size, // choose one that has higher average transition rates. TOLR, // Only consider transition rate dependency when the rate change exceeds some tolerance NONE, // Ignore entirely the dependency relations in transition rates. } private static String tranRatePorDef = "full"; /* * Cycle closing method for partial order reduction */ public static enum cycleClosingMethdDef{ BEHAVIORAL, // Improved behavioral analysis on cycle closing STATE_SEARCH, // Improved behavioral analysis + state trace-back NO_CYCLECLOSING, // no cycle closing STRONG, // Strong cycle condition: for each cycle, at least one state has to fully expand. } private static String cycleClosingMethd = "behavioral"; /* * Ample computation during cycle closing check. */ public static enum cycleClosingStrongStubbornMethdDef { CCTB, // cycle closing with trace-back CCTBDG, // cycle closing with trace-back using dependency graphs CCTBOFF // cycle closing without trace-back } private static String cycleClosingStrongStubbornMethd = "cctb"; //// /* //// * Flag to use use dependent set queue for POR //// */ // private static boolean useDependentQueue = false; /* * Report disabling error flag */ private static boolean disablingError = true; /* * Output state graph (dot) flag */ private static boolean outputSgFlag = false; /* * Debug mode : options to print intermediate results during POR */ private static boolean debug = false; /* * Option for printing final numbers from search_dfs or search_dfsPOR. */ private static boolean outputLogFlag = false; /* * Name of the LPN under verification. */ private static String lpnName = null; /* * Path for printing global state graph */ private static String prjSgPath = null; /* * Flag indate if there is a user specified memory upper bound */ private static boolean memoryUpperBoundFlag; /* * User specified memory upper bound */ private static long memoryUpperBound; /* * Search algorithm options: */ public static enum searchTypeDef { DFS, // DFS search on the entire state space BFS, // BFS on the entire state space. COMPOSITIONAL // using compositional search/reduction to build the reduce SG. } private static String searchType = "dfs"; /* * Options on how reachable states are stored. */ public static enum StateFormatDef { EXPLICIT, // hash tables in java MDDBUF, // Mutli-Value DD MDD, // Mutli-Value DD BDD, // BDD AIG, // AIG BINARY_TREE, // Binary tree DECOMPOSED, // decompose a global state into a set of triples of global vectors and two local states sharing variables. NATIVE_HASH // hash table in C/C++ } private static String stateFormat = "explicit"; /* * Use multi-threading when set to true. */ private static boolean parallelFlag = false; /* * Memory upper bound for a verification run. The unit is MB. */ public static int MemUpperBound = 1800; /* * Upper bound on the total runtime for a run. The unit is in seconds. */ public static int TimeUpperBound = 1500; /* The timing log file */ public static String _TimingLogFile = null; /* Sets the _TimingLogFile */ public static void set_TimingLogFile(String logFile){ _TimingLogFile = logFile; } /* Gets the _TimingLogFile */ public static String get_TimingLogfile(){ return _TimingLogFile; } /* Flag for range of resets after transitions alone*/ public static boolean _resetOnce = false; /* Sets the _resetOnce flag. */ public static void set_resetOnce(boolean resetOnce){ _resetOnce = resetOnce; } /* Gets the _resetOnce flag. */ public static boolean get_resetOnce(){ return _resetOnce; } /* * Flag for turn on/off the gui response for * verification results */ private static boolean _displayResults = false; /* Sets the _displayResults flag. */ public static void set_displayResults(boolean displayResults){ _displayResults = displayResults; } /* Gets the _displayResults flag. */ public static boolean get_displayResults(){ return _displayResults; } /* * Option for compositional minimization type. * off - no state space reduction * abstraction - transition based abstraction * reduction - state space reduction */ private static String compositionalMinimization = "off"; private static boolean newParser = false; /* * When true, use non-disabling semantics for transition firing. */ private static boolean stickySemantics = false; private static boolean timingAnalysisFlag = false; /** * When true, Markovian analysis can be applied to the LPN model. */ private static boolean markovianModel = false; public static void setCompositionalMinimization(String minimizationType){ if (minimizationType.equals("abstraction")){ compositionalMinimization = minimizationType; } else if (minimizationType.equals("reduction")){ compositionalMinimization = minimizationType; } else if (minimizationType.equals("off")){ } else{ System.out.println("warning: invalid COMPOSITIONAL_MINIMIZATION option - default is \"off\""); } } public static String getCompositionalMinimization(){ return compositionalMinimization; } public static boolean getTimingAnalysisFlag(){ return timingAnalysisFlag; } public static void setStickySemantics(){ stickySemantics = true; } public static boolean getStickySemantics(){ return stickySemantics; } public static void setVerbosity(int v){ verbosity = v; } public static int getVerbosity(){ return verbosity; } public static void setDotPath(String path){ dotPath = path; } public static String getDotPath(){ return dotPath; } public static void setTimingAnalsysisType(String timing){ if (timing.equals("zone")){ timingAnalysisFlag = true; timingAnalysisType = timing; } else if (timing.equals("octagon")){ timingAnalysisFlag = true; timingAnalysisType = timing; } else if (timing.equals("poset")){ timingAnalysisFlag = true; timingAnalysisType = timing; } else if (timing.equals("off")){ // Alteration by Andrew N. Fisher timingAnalysisFlag = false; timingAnalysisType = "off"; } else{ System.out.println("warning: invalid TIMING_ANALYSIS option - default is \"off\""); } } public static String getTimingAnalysisType(){ return timingAnalysisType; } public static void setPOR(String por){ POR = por; } public static String getPOR(){ return POR; } public static void setSearchType(String type){ searchType = type; } public static String getSearchType(){ return searchType; } public static void setStateFormat(String format){ if (format.equals("explicit")){ } else if (format.equals("bdd")){ stateFormat = format; } else if (format.equals("aig")){ stateFormat = format; } else if (format.equals("mdd")){ stateFormat = format; } else if (format.equals("mddbuf")){ stateFormat = format; } else{ System.out.println("warning: invalid STATE_FORMAT option - default is \"explicit\""); } } public static String getStateFormat(){ return stateFormat; } public static void setParallelFlag(){ parallelFlag = true; } public static boolean getParallelFlag(){ return parallelFlag; } public static void setNewParser(){ newParser = true; } public static boolean getNewParser(){ return newParser; } public static void setCycleClosingMthd(String cycleclosing) { cycleClosingMethd = cycleclosing; } public static String getCycleClosingMthd() { return cycleClosingMethd; } public static void setOutputSgFlag(boolean outputSGflag) { outputSgFlag = outputSGflag; } public static boolean getOutputSgFlag() { return outputSgFlag; } public static void setPrjSgPath(String path) { prjSgPath = path; } public static String getPrjSgPath() { return prjSgPath; } public static void setCycleClosingStrongStubbornMethd(String method) { cycleClosingStrongStubbornMethd = method; } public static String getCycleClosingStrongStubbornMethd() { return cycleClosingStrongStubbornMethd; } public static void setDebugMode(boolean debugMode) { debug = debugMode; } public static boolean getDebugMode() { return debug; } public static void setOutputLogFlag(boolean printLog) { outputLogFlag = printLog; } public static boolean getOutputLogFlag() { return outputLogFlag; } public static void setLogName(String lpnFileName) { lpnName = lpnFileName; } public static String getLogName() { return lpnName; } // public static void disablePORdeadlockPreserve() { // porDeadlockPreserve = false; // public static boolean getPORdeadlockPreserve() { // return porDeadlockPreserve; public static void disableDisablingError() { disablingError = false; } public static boolean getReportDisablingError() { return disablingError; } public static void setMemoryUpperBound(long value) { memoryUpperBound = value; } public static float getMemUpperBound() { return memoryUpperBound; } public static void setMemUpperBoundFlag() { memoryUpperBoundFlag = true; } public static boolean getMemUpperBoundFlag() { return memoryUpperBoundFlag; } // public static boolean getUseDependentQueue() { // return useDependentQueue; // public static boolean setUseDependentQueue() { // return useDependentQueue = true; public static void setMarkovianModelFlag() { markovianModel = true; } public static boolean getMarkovianModelFlag() { return markovianModel; } public static String getTranRatePorDef() { return tranRatePorDef; } public static void setTranRatePorDef(String tranRatePorDef) { Options.tranRatePorDef = tranRatePorDef; } }
package imagej.core.commands.display.interactive; import imagej.command.Command; import imagej.data.autoscale.AutoscaleService; import imagej.data.autoscale.DataRange; import imagej.data.command.InteractiveImageCommand; import imagej.data.display.DatasetView; import imagej.data.widget.HistogramBundle; import imagej.menu.MenuConstants; import imagej.module.MutableModuleItem; import imagej.widget.Button; import imagej.widget.ChoiceWidget; import imagej.widget.NumberWidget; import net.imglib2.RandomAccessibleInterval; import net.imglib2.histogram.BinMapper1d; import net.imglib2.histogram.Histogram1d; import net.imglib2.histogram.Real1dBinMapper; import net.imglib2.type.numeric.RealType; import net.imglib2.view.Views; import org.scijava.ItemIO; import org.scijava.plugin.Menu; import org.scijava.plugin.Parameter; import org.scijava.plugin.Plugin; /** * Plugin that sets the minimum and maximum for scaling of display values. Sets * the same min/max for each channel. * * @author Curtis Rueden * @author Grant Harris */ @Plugin(type = Command.class, menu = { @Menu(label = MenuConstants.IMAGE_LABEL, weight = MenuConstants.IMAGE_WEIGHT, mnemonic = MenuConstants.IMAGE_MNEMONIC), @Menu(label = "Adjust"), @Menu(label = "Brightness/Contrast...", accelerator = "control shift C", weight = 0) }, iconPath = "/icons/commands/contrast.png", headless = true, initializer = "initValues") public class BrightnessContrast<T extends RealType<T>> extends InteractiveImageCommand { // -- constants -- private static final int SLIDER_MIN = 0; private static final int SLIDER_MAX = 100; private static final String S_MIN = "" + SLIDER_MIN; private static final String S_MAX = "" + SLIDER_MAX; /** * The exponential power used for computing contrast. The greater this number, * the steeper the slope will be at maximum contrast, and flatter it will be * at minimum contrast. */ private static final int MAX_POWER = 4; private static final String PLANE = "Plane"; private static final String GLOBAL = "Global"; // -- Parameter fields -- @Parameter private AutoscaleService autoscaleService; @Parameter(type = ItemIO.BOTH, callback = "viewChanged") private DatasetView view; @Parameter(label = "Histogram") private HistogramBundle bundle; @Parameter(label = "Minimum", persist = false, callback = "minMaxChanged", style = NumberWidget.SCROLL_BAR_STYLE) private double min = Double.NaN; @Parameter(label = "Maximum", persist = false, callback = "minMaxChanged", style = NumberWidget.SCROLL_BAR_STYLE) private double max = Double.NaN; @Parameter(callback = "brightnessContrastChanged", persist = false, style = NumberWidget.SCROLL_BAR_STYLE, min = S_MIN, max = S_MAX) private int brightness; @Parameter(callback = "brightnessContrastChanged", persist = false, style = NumberWidget.SCROLL_BAR_STYLE, min = S_MIN, max = S_MAX) private int contrast; @Parameter(label = "Default", callback = "setDefault") private Button defaultButton; @Parameter(label = "Range:", style = ChoiceWidget.RADIO_BUTTON_HORIZONTAL_STYLE, choices = { PLANE, GLOBAL }, callback = "viewChanged") String rangeChoice = PLANE; // -- other fields -- /** The minimum and maximum values of the data itself. */ private double dataMin, dataMax; /** The initial minimum and maximum values of the data view. */ private double initialMin, initialMax; // -- constructors -- public BrightnessContrast() { super("view"); } // -- Runnable methods -- @Override public void run() { updateDisplay(); } // -- BrightnessContrast methods -- public DatasetView getView() { return view; } public void setView(final DatasetView view) { this.view = view; } public double getMinimum() { return min; } public void setMinimum(final double min) { this.min = min; } public double getMaximum() { return max; } public void setMaximum(final double max) { this.max = max; } public int getBrightness() { return brightness; } public void setBrightness(final int brightness) { this.brightness = brightness; } public int getContrast() { return contrast; } public void setContrast(final int contrast) { this.contrast = contrast; } // -- Initializers -- protected void initValues() { viewChanged(); } // -- Callback methods -- /** Called when view changes. Updates everything to match. */ protected void viewChanged() { RandomAccessibleInterval<? extends RealType<?>> interval; if (rangeChoice.equals(PLANE)) interval = view.xyPlane(); else interval = view.getData().getImgPlus(); computeDataMinMax(interval); computeInitialMinMax(); if (Double.isNaN(min)) min = initialMin; if (Double.isNaN(max)) max = initialMax; computeBrightnessContrast(); // TEMP : try this to clear up refresh problem // NOPE // updateDisplay(); } /** Called when min or max changes. Updates brightness and contrast. */ protected void minMaxChanged() { computeBrightnessContrast(); } /** Called when brightness or contrast changes. Updates min and max. */ protected void brightnessContrastChanged() { computeMinMax(); } protected void setDefault() { brightness = (SLIDER_MIN + SLIDER_MAX) / 2; contrast = (SLIDER_MIN + SLIDER_MAX) / 2; brightnessContrastChanged(); updateDisplay(); } // -- Helper methods -- // TODO we have a couple refresh problems // 1) right now if you bounce between two displays with this dialog open the // dialog values (like min, max, and hist don't update) // 2) even if you can fix 1) the fact that we don't change to a new // HistogramBundle but rather tweak the existing one might cause refresh() // probs also. Because the update() code checks if the T's are the same. // This means there is a implicit requirement for object reference equality // rather than using something like equals(). Or a isChanged() interface // (since in this case equals() would not work either). private void computeDataMinMax( final RandomAccessibleInterval<? extends RealType<?>> img) { // FIXME: Reconcile this with DefaultDatasetView.autoscale(int). There is // no reason to hardcode the usage of ComputeMinMax twice. Rather, there // should be a single entry point for obtain the channel min/maxes from // the metadata, and if they aren't there, then compute them. Probably // Dataset (not DatasetView) is a good place for it, because it is metadata // independent of the visualization settings. DataRange range = autoscaleService.getDefaultRandomAccessRange(img); dataMin = range.getMin(); dataMax = range.getMax(); final MutableModuleItem<Double> minItem = getInfo().getMutableInput("min", Double.class); minItem.setSoftMinimum(dataMin); minItem.setSoftMaximum(dataMax); final MutableModuleItem<Double> maxItem = getInfo().getMutableInput("max", Double.class); maxItem.setSoftMinimum(dataMin); maxItem.setSoftMaximum(dataMax); // System.out.println("IN HERE!!!!!!"); // System.out.println(" dataMin = " + dataMin); // System.out.println(" dataMax = " + dataMax); @SuppressWarnings({ "unchecked", "rawtypes" }) Iterable<T> iterable = Views .iterable((RandomAccessibleInterval<T>) (RandomAccessibleInterval) img); BinMapper1d<T> mapper = new Real1dBinMapper<T>(dataMin, dataMax, 256, false); Histogram1d<T> histogram = new Histogram1d<T>(iterable, mapper); if (bundle == null) { bundle = new HistogramBundle(histogram); } else { bundle.setHistogram(0, histogram); } bundle.setDataMinMax(dataMin, dataMax); // bundle.setLineSlopeIntercept(1, 0); log().debug( "computeDataMinMax: dataMin=" + dataMin + ", dataMax=" + dataMax); // force a widget refresh to see new Hist (and also fill min and max fields) // NOPE. HistBundle is unchanged. Only internals are. So no // refresh called. Note that I changed InteractiveCommand::update() to // always setValue() and still this did not work. !!!! Huh? // update(getInfo().getMutableInput("bundle", HistogramBundle.class), // bundle); // NOPE // getInfo().getInput("bundle", HistogramBundle.class).setValue(this, // bundle); // NOPE // getInfo().setVisible(false); // getInfo().setVisible(true); // NOPE // getInfo().getMutableInput("bundle",HistogramBundle.class).initialize(this); // NOPE // getInfo().getMutableInput("bundle",HistogramBundle.class).callback(this); } private void computeInitialMinMax() { // use only first channel, for now initialMin = view.getChannelMin(0); initialMax = view.getChannelMax(0); log().debug("computeInitialMinMax: initialMin=" + initialMin + ", initialMax=" + initialMax); } /** Computes min and max from brightness and contrast. */ private void computeMinMax() { // normalize brightness and contrast to [0, 1] final double bUnit = (double) (brightness - SLIDER_MIN) / (SLIDER_MAX - SLIDER_MIN); final double cUnit = (double) (contrast - SLIDER_MIN) / (SLIDER_MAX - SLIDER_MIN); // convert brightness to offset [-1, 1] final double b = 2 * bUnit - 1; // convert contrast to slope [e^-n, e^n] final double m = Math.exp(2 * MAX_POWER * cUnit - MAX_POWER); // y = m*x + b // minUnit is x at y=0 // maxUnit is x at y=1 final double minUnit = -b / m; final double maxUnit = (1 - b) / m; // convert unit min/max to actual min/max min = (dataMax - dataMin) * minUnit + dataMin; max = (dataMax - dataMin) * maxUnit + dataMin; bundle.setTheoreticalMinMax(min, max); // bundle.setLineSlopeIntercept(m, b); log().debug("computeMinMax: bUnit=" + bUnit + ", cUnit=" + cUnit + ", b=" + b + ", m=" + m + ", minUnit=" + minUnit + ", maxUnit=" + maxUnit + ", min=" + min + ", max=" + max); } /** Computes brightness and contrast from min and max. */ private void computeBrightnessContrast() { // normalize min and max to [0, 1] final double minUnit = (min - dataMin) / (dataMax - dataMin); final double maxUnit = (max - dataMin) / (dataMax - dataMin); // y = m*x + b // minUnit is x at y=0 // maxUnit is x at y=1 // b = y - m*x = -m * minUnit = 1 - m * maxUnit // m * maxUnit - m * minUnit = 1 // m = 1 / (maxUnit - minUnit) final double m = 1 / (maxUnit - minUnit); final double b = -m * minUnit; // convert offset to normalized brightness final double bUnit = (b + 1) / 2; // convert slope to normalized contrast final double cUnit = (Math.log(m) + MAX_POWER) / (2 * MAX_POWER); // convert unit brightness/contrast to actual brightness/contrast brightness = (int) ((SLIDER_MAX - SLIDER_MIN) * bUnit + SLIDER_MIN + 0.5); contrast = (int) ((SLIDER_MAX - SLIDER_MIN) * cUnit + SLIDER_MIN + 0.5); bundle.setTheoreticalMinMax(min, max); // bundle.setLineSlopeIntercept(m, b); log().debug("computeBrightnessContrast: minUnit=" + minUnit + ", maxUnit=" + maxUnit + ", m=" + m + ", b=" + b + ", bUnit=" + bUnit + ", cUnit=" + cUnit + ", brightness=" + brightness + ", contrast=" + contrast); } /** Updates the displayed min/max range to match min and max values. */ private void updateDisplay() { view.setChannelRanges(min, max); view.getProjector().map(); view.update(); } }
package org.jkiss.dbeaver.model.impl.data; import org.jkiss.dbeaver.model.data.DBDDataFormatterSample; import java.sql.Timestamp; import java.util.*; public class TimestampFormatSample implements DBDDataFormatterSample { @Override public Map<Object, Object> getDefaultProperties(Locale locale) { // SimpleDateFormat tmp = (SimpleDateFormat)DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM, locale); // String pattern = tmp.toPattern(); return Collections.singletonMap((Object)DateTimeDataFormatter.PROP_PATTERN, (Object)(DateFormatSample.DEFAULT_DATE_PATTERN + " " + TimeFormatSample.DEFAULT_TIME_PATTERN)); } @Override public Object getSampleValue() { Timestamp ts = new Timestamp(System.currentTimeMillis()); ts.setNanos(ts.getNanos() + new Random(System.currentTimeMillis()).nextInt(99999)); return ts; } }
package org.jkiss.dbeaver.ui.controls.resultset; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.IJobChangeEvent; import org.eclipse.core.runtime.jobs.JobChangeAdapter; import org.eclipse.jface.action.*; import org.eclipse.jface.dialogs.ControlEnableState; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.text.IFindReplaceTarget; import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.Viewer; import org.eclipse.osgi.util.NLS; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.SashForm; import org.eclipse.swt.dnd.TextTransfer; import org.eclipse.swt.dnd.Transfer; import org.eclipse.swt.events.*; import org.eclipse.swt.graphics.*; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.*; import org.eclipse.ui.ISaveablePart2; import org.eclipse.ui.IWorkbenchCommandConstants; import org.eclipse.ui.IWorkbenchPartSite; import org.eclipse.ui.commands.ICommandService; import org.eclipse.ui.menus.CommandContributionItem; import org.eclipse.ui.progress.UIJob; import org.eclipse.ui.themes.ITheme; import org.eclipse.ui.themes.IThemeManager; import org.eclipse.ui.views.properties.IPropertySheetPage; import org.eclipse.ui.views.properties.IPropertySource; import org.eclipse.ui.views.properties.IPropertySourceProvider; import org.jkiss.code.NotNull; import org.jkiss.code.Nullable; import org.jkiss.dbeaver.DBException; import org.jkiss.dbeaver.DBeaverPreferences; import org.jkiss.dbeaver.core.CoreMessages; import org.jkiss.dbeaver.core.DBeaverCore; import org.jkiss.dbeaver.core.DBeaverUI; import org.jkiss.dbeaver.ext.IDataSourceProvider; import org.jkiss.dbeaver.ext.ui.IObjectImageProvider; import org.jkiss.dbeaver.model.DBPDataKind; import org.jkiss.dbeaver.model.DBPDataSource; import org.jkiss.dbeaver.model.DBUtils; import org.jkiss.dbeaver.model.data.*; import org.jkiss.dbeaver.model.exec.*; import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor; import org.jkiss.dbeaver.model.runtime.DBRRunnableWithProgress; import org.jkiss.dbeaver.model.struct.DBSAttributeBase; import org.jkiss.dbeaver.model.struct.DBSDataContainer; import org.jkiss.dbeaver.model.struct.DBSEntityAttribute; import org.jkiss.dbeaver.model.struct.DBSTypedObject; import org.jkiss.dbeaver.model.virtual.DBVConstants; import org.jkiss.dbeaver.model.virtual.DBVEntityConstraint; import org.jkiss.dbeaver.runtime.RunnableWithResult; import org.jkiss.dbeaver.runtime.RuntimeUtils; import org.jkiss.dbeaver.runtime.VoidProgressMonitor; import org.jkiss.dbeaver.tools.transfer.IDataTransferProducer; import org.jkiss.dbeaver.tools.transfer.database.DatabaseTransferProducer; import org.jkiss.dbeaver.tools.transfer.wizard.DataTransferWizard; import org.jkiss.dbeaver.ui.*; import org.jkiss.dbeaver.ui.controls.lightgrid.GridCell; import org.jkiss.dbeaver.ui.controls.lightgrid.GridPos; import org.jkiss.dbeaver.ui.controls.lightgrid.IGridContentProvider; import org.jkiss.dbeaver.ui.controls.lightgrid.IGridLabelProvider; import org.jkiss.dbeaver.ui.controls.spreadsheet.ISpreadsheetController; import org.jkiss.dbeaver.ui.controls.spreadsheet.Spreadsheet; import org.jkiss.dbeaver.ui.dialogs.ActiveWizardDialog; import org.jkiss.dbeaver.ui.dialogs.ConfirmationDialog; import org.jkiss.dbeaver.ui.dialogs.EditTextDialog; import org.jkiss.dbeaver.ui.dialogs.sql.ViewSQLDialog; import org.jkiss.dbeaver.ui.dialogs.struct.EditConstraintDialog; import org.jkiss.dbeaver.ui.preferences.PrefPageDatabaseGeneral; import org.jkiss.dbeaver.ui.properties.PropertyCollector; import org.jkiss.dbeaver.ui.properties.tabbed.PropertyPageStandard; import org.jkiss.dbeaver.utils.ContentUtils; import org.jkiss.utils.CommonUtils; import java.lang.reflect.InvocationTargetException; import java.util.*; import java.util.List; /** * ResultSetViewer * * TODO: replace curRowNum and curColNum with elements (mode switcher is broken now) * TODO: calculate column bounds correctly * TODO: select child columns on parent click * TODO: fix content copy * TODO: fix cell editor * TODO: structured rows support */ public class ResultSetViewer extends Viewer implements IDataSourceProvider, ISpreadsheetController, IPropertyChangeListener, ISaveablePart2, IAdaptable { static final Log log = LogFactory.getLog(ResultSetViewer.class); private static final int DEFAULT_ROW_HEADER_WIDTH = 50; private ResultSetValueController panelValueController; private static final String VIEW_PANEL_VISIBLE = "viewPanelVisible"; private static final String VIEW_PANEL_RATIO = "viewPanelRatio"; public enum GridMode { GRID, RECORD } public enum RowPosition { FIRST, PREVIOUS, NEXT, LAST } @NotNull private final IWorkbenchPartSite site; private final Composite viewerPanel; private Composite filtersPanel; private ControlEnableState filtersEnableState; private Combo filtersText; private Text statusLabel; private final SashForm resultsSash; private final Spreadsheet spreadsheet; private final ViewValuePanel previewPane; @NotNull private final ResultSetProvider resultSetProvider; @NotNull private final ResultSetDataReceiver dataReceiver; @NotNull private final IThemeManager themeManager; private ToolBarManager toolBarManager; // Current row/col number private int curRowNum = -1; private int curColNum = -1; // Mode private GridMode gridMode; private final Map<ResultSetValueController, DBDValueEditorStandalone> openEditors = new HashMap<ResultSetValueController, DBDValueEditorStandalone>(); private final List<ResultSetListener> listeners = new ArrayList<ResultSetListener>(); // UI modifiers private final Color colorRed; private Color backgroundAdded; private Color backgroundDeleted; private Color backgroundModified; private Color backgroundOdd; private final Color foregroundNull; private final Font boldFont; private volatile ResultSetDataPumpJob dataPumpJob; private ResultSetFindReplaceTarget findReplaceTarget; private final ResultSetModel model = new ResultSetModel(); private boolean showOddRows = true; private boolean showCelIcons = true; public ResultSetViewer(@NotNull Composite parent, @NotNull IWorkbenchPartSite site, @NotNull ResultSetProvider resultSetProvider) { super(); /* if (!adapterRegistered) { ResultSetAdapterFactory nodesAdapter = new ResultSetAdapterFactory(); IAdapterManager mgr = Platform.getAdapterManager(); mgr.registerAdapters(nodesAdapter, ResultSetProvider.class); mgr.registerAdapters(nodesAdapter, IPageChangeProvider.class); adapterRegistered = true; } */ this.site = site; this.gridMode = GridMode.GRID; this.resultSetProvider = resultSetProvider; this.dataReceiver = new ResultSetDataReceiver(this); this.colorRed = Display.getDefault().getSystemColor(SWT.COLOR_RED); this.foregroundNull = parent.getDisplay().getSystemColor(SWT.COLOR_GRAY); this.boldFont = UIUtils.makeBoldFont(parent.getFont()); this.viewerPanel = UIUtils.createPlaceholder(parent, 1); UIUtils.setHelp(this.viewerPanel, IHelpContextIds.CTX_RESULT_SET_VIEWER); createFiltersPanel(); { resultsSash = new SashForm(viewerPanel, SWT.HORIZONTAL | SWT.SMOOTH); resultsSash.setLayoutData(new GridData(GridData.FILL_BOTH)); resultsSash.setSashWidth(5); //resultsSash.setBackground(resultsSash.getDisplay().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND)); this.spreadsheet = new Spreadsheet( resultsSash, SWT.MULTI | SWT.VIRTUAL | SWT.H_SCROLL | SWT.V_SCROLL, site, this, new ContentProvider(), new GridLabelProvider()); this.spreadsheet.setLayoutData(new GridData(GridData.FILL_BOTH)); this.previewPane = new ViewValuePanel(resultsSash) { @Override protected void hidePanel() { togglePreview(); } }; final IPreferenceStore preferences = getPreferences(); int ratio = preferences.getInt(VIEW_PANEL_RATIO); boolean viewPanelVisible = preferences.getBoolean(VIEW_PANEL_VISIBLE); if (ratio <= 0) { ratio = 750; } resultsSash.setWeights(new int[]{ratio, 1000 - ratio}); if (!viewPanelVisible) { resultsSash.setMaximizedControl(spreadsheet); } previewPane.addListener(SWT.Resize, new Listener() { @Override public void handleEvent(Event event) { DBPDataSource dataSource = getDataSource(); if (dataSource != null) { if (!resultsSash.isDisposed()) { int[] weights = resultsSash.getWeights(); int ratio = weights[0]; preferences.setValue(VIEW_PANEL_RATIO, ratio); } } } }); } createStatusBar(viewerPanel); changeMode(GridMode.GRID); this.themeManager = site.getWorkbenchWindow().getWorkbench().getThemeManager(); this.themeManager.addPropertyChangeListener(this); this.spreadsheet.addDisposeListener(new DisposeListener() { @Override public void widgetDisposed(DisposeEvent e) { dispose(); } }); this.spreadsheet.addCursorChangeListener(new Listener() { @Override public void handleEvent(Event event) { updateGridCursor(event.x, event.y); } }); //this.spreadsheet.setTopLeftRenderer(new TopLeftRenderer(this)); applyThemeSettings(); spreadsheet.addFocusListener(new FocusListener() { @Override public void focusGained(FocusEvent e) { updateToolbar(); } @Override public void focusLost(FocusEvent e) { updateToolbar(); } }); this.spreadsheet.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { fireSelectionChanged(new SelectionChangedEvent(ResultSetViewer.this, new ResultSetSelectionImpl())); } }); } // Filters private void createFiltersPanel() { filtersPanel = new Composite(viewerPanel, SWT.NONE); filtersPanel.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); GridLayout gl = new GridLayout(5, false); gl.marginHeight = 3; gl.marginWidth = 3; filtersPanel.setLayout(gl); Button sourceQueryButton = new Button(filtersPanel, SWT.PUSH | SWT.NO_FOCUS); sourceQueryButton.setImage(DBIcon.SQL_TEXT.getImage()); sourceQueryButton.setText("SQL"); sourceQueryButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { String queryText = model.getStatistics() == null ? null : model.getStatistics().getQueryText(); if (queryText == null || queryText.isEmpty()) { queryText = "<empty>"; } ViewSQLDialog dialog = new ViewSQLDialog(site, getDataSource(), "Query Text", DBIcon.SQL_TEXT.getImage(), queryText); dialog.setEnlargeViewPanel(false); dialog.setWordWrap(true); dialog.open(); } }); Button customizeButton = new Button(filtersPanel, SWT.PUSH | SWT.NO_FOCUS); customizeButton.setImage(DBIcon.FILTER.getImage()); customizeButton.setText("Filters"); customizeButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { new ResultSetFilterDialog(ResultSetViewer.this).open(); } }); //UIUtils.createControlLabel(filtersPanel, " Filter"); this.filtersText = new Combo(filtersPanel, SWT.BORDER | SWT.DROP_DOWN); this.filtersText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); this.filtersText.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { setCustomDataFilter(); } }); { // Register filters text in focus service UIUtils.addFocusTracker(site, UIUtils.INLINE_WIDGET_EDITOR_ID, this.filtersText); this.filtersText.addDisposeListener(new DisposeListener() { @Override public void widgetDisposed(DisposeEvent e) { // Unregister from focus service UIUtils.removeFocusTracker(ResultSetViewer.this.site, filtersText); dispose(); } }); } // Handle all shortcuts by filters editor, not by host editor this.filtersText.addFocusListener(new FocusListener() { private boolean activated = false; @Override public void focusGained(FocusEvent e) { if (!activated) { UIUtils.enableHostEditorKeyBindings(site, false); activated = true; } } @Override public void focusLost(FocusEvent e) { if (activated) { UIUtils.enableHostEditorKeyBindings(site, true); activated = false; } } }); final Button applyButton = new Button(filtersPanel, SWT.PUSH | SWT.NO_FOCUS); applyButton.setText("Apply"); applyButton.setToolTipText("Apply filter criteria"); applyButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { setCustomDataFilter(); } }); applyButton.setEnabled(false); final Button clearButton = new Button(filtersPanel, SWT.PUSH | SWT.NO_FOCUS); clearButton.setText("X"); clearButton.setToolTipText("Remove all filters"); clearButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { resetDataFilter(true); } }); clearButton.setEnabled(false); this.filtersText.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { if (filtersEnableState == null) { String filterText = filtersText.getText(); applyButton.setEnabled(true); clearButton.setEnabled(!CommonUtils.isEmpty(filterText)); } } }); filtersPanel.addTraverseListener(new TraverseListener() { @Override public void keyTraversed(TraverseEvent e) { if (e.detail == SWT.TRAVERSE_RETURN) { setCustomDataFilter(); e.doit = false; e.detail = SWT.TRAVERSE_NONE; } } }); filtersEnableState = ControlEnableState.disable(filtersPanel); } public void resetDataFilter(boolean refresh) { setDataFilter(model.createDataFilter(), refresh); } private void setCustomDataFilter() { DBPDataSource dataSource = getDataSource(); if (dataSource == null) { return; } String condition = filtersText.getText(); StringBuilder currentCondition = new StringBuilder(); model.getDataFilter().appendConditionString(dataSource, currentCondition); if (currentCondition.toString().trim().equals(condition.trim())) { // The same return; } DBDDataFilter newFilter = model.createDataFilter(); newFilter.setWhere(condition); setDataFilter(newFilter, true); spreadsheet.setFocus(); } public void updateFiltersText() { boolean enableFilters = false; DBPDataSource dataSource = getDataSource(); if (dataSource != null) { StringBuilder where = new StringBuilder(); model.getDataFilter().appendConditionString(dataSource, where); String whereCondition = where.toString().trim(); filtersText.setText(whereCondition); if (!whereCondition.isEmpty()) { addFiltersHistory(whereCondition); } if (resultSetProvider.isReadyToRun() && !model.isUpdateInProgress() && (!CommonUtils.isEmpty(whereCondition) || (getModel().getVisibleColumnCount() > 0 && supportsDataFilter()))) { enableFilters = true; } } if (enableFilters) { if (filtersEnableState != null) { filtersEnableState.restore(); filtersEnableState = null; } } else if (filtersEnableState == null) { filtersEnableState = ControlEnableState.disable(filtersPanel); } } private void addFiltersHistory(String whereCondition) { int historyCount = filtersText.getItemCount(); for (int i = 0; i < historyCount; i++) { if (filtersText.getItem(i).equals(whereCondition)) { if (i > 0) { // Move to beginning filtersText.remove(i); break; } else { return; } } } filtersText.add(whereCondition, 0); filtersText.setText(whereCondition); } public void setDataFilter(final DBDDataFilter dataFilter, boolean refreshData) { if (!CommonUtils.equalObjects(model.getDataFilter(), dataFilter)) { if (model.setDataFilter(dataFilter)) { refreshSpreadsheet(true); } if (refreshData) { reorderResultSet(true, new Runnable() { @Override public void run() { if (gridMode == GridMode.GRID) { spreadsheet.refreshData(false); } } }); } } this.updateFiltersText(); } // Misc IPreferenceStore getPreferences() { return DBeaverCore.getGlobalPreferenceStore(); } @Override public DBPDataSource getDataSource() { DBSDataContainer dataContainer = getDataContainer(); return dataContainer == null ? null : dataContainer.getDataSource(); } public IFindReplaceTarget getFindReplaceTarget() { if (findReplaceTarget == null) { findReplaceTarget = new ResultSetFindReplaceTarget(this); } return findReplaceTarget; } @Nullable @Override public Object getAdapter(Class adapter) { if (adapter == IPropertySheetPage.class) { // Show cell properties PropertyPageStandard page = new PropertyPageStandard(); page.setPropertySourceProvider(new IPropertySourceProvider() { @Nullable @Override public IPropertySource getPropertySource(Object object) { if (object instanceof GridCell) { final GridCell cell = translateVisualPos((GridCell) object); final ResultSetValueController valueController = new ResultSetValueController( cell, DBDValueController.EditType.NONE, null); PropertyCollector props = new PropertyCollector(valueController.getAttribute(), false); props.collectProperties(); valueController.getValueHandler().contributeProperties(props, valueController); return props; } return null; } }); return page; } else if (adapter == IFindReplaceTarget.class) { return getFindReplaceTarget(); } return null; } public void addListener(ResultSetListener listener) { synchronized (listeners) { listeners.add(listener); } } public void removeListener(ResultSetListener listener) { synchronized (listeners) { listeners.remove(listener); } } private void updateGridCursor(int col, int row) { boolean changed; if (gridMode == GridMode.GRID) { changed = curRowNum != row || curColNum != col; curRowNum = row; curColNum = col; } else { changed = curColNum != row; curColNum = row; } if (changed) { ResultSetPropertyTester.firePropertyChange(ResultSetPropertyTester.PROP_CAN_MOVE); ResultSetPropertyTester.firePropertyChange(ResultSetPropertyTester.PROP_EDITABLE); updateToolbar(); if (col >= 0 && row >= 0) { previewValue(); } } } private void updateRecordMode() { int oldColNum = this.curColNum; this.initResultSet(); this.curColNum = oldColNum; spreadsheet.setCursor(new GridPos(0, oldColNum), false); } void updateEditControls() { ResultSetPropertyTester.firePropertyChange(ResultSetPropertyTester.PROP_EDITABLE); ResultSetPropertyTester.firePropertyChange(ResultSetPropertyTester.PROP_CHANGED); updateToolbar(); } /** * It is a hack function. Generally all command associated widgets should be updated automatically by framework. * Freaking E4 do not do it. I've spent a couple of days fighting it. Guys, you owe me. * TODO: just remove in future. In fact everything must work without it */ private void updateToolbar() { if (toolBarManager.isEmpty()) { return; } for (IContributionItem item : toolBarManager.getItems()) { item.update(); } } void refreshSpreadsheet(boolean rowsChanged) { if (spreadsheet.isDisposed()) { return; } if (rowsChanged) { if (curRowNum >= model.getRowCount()) { curRowNum = model.getRowCount() - 1; } GridPos curPos = new GridPos(spreadsheet.getCursorPosition()); if (gridMode == GridMode.GRID) { if (curPos.row >= model.getRowCount()) { curPos.row = model.getRowCount() - 1; } } this.spreadsheet.refreshData(true); // Set cursor on new row if (gridMode == GridMode.GRID) { spreadsheet.setCursor(curPos, false); } else { updateRecordMode(); } } else { this.spreadsheet.redrawGrid(); } } private void createStatusBar(Composite parent) { UIUtils.createHorizontalLine(parent); Composite statusBar = new Composite(parent, SWT.NONE); GridData gd = new GridData(GridData.FILL_HORIZONTAL); statusBar.setLayoutData(gd); GridLayout gl = new GridLayout(4, false); gl.marginWidth = 0; gl.marginHeight = 3; //gl.marginBottom = 5; statusBar.setLayout(gl); statusLabel = new Text(statusBar, SWT.READ_ONLY); gd = new GridData(GridData.FILL_HORIZONTAL); statusLabel.setLayoutData(gd); statusLabel.addMouseListener(new MouseAdapter() { @Override public void mouseDoubleClick(MouseEvent e) { EditTextDialog.showText(site.getShell(), CoreMessages.controls_resultset_viewer_dialog_status_title, statusLabel.getText()); } }); /* IAction viewMessageAction = new Action("View status message", DBIcon.TREE_INFO.getImageDescriptor()) { public void run() { } }; */ toolBarManager = new ToolBarManager(SWT.FLAT | SWT.HORIZONTAL); // handle own commands toolBarManager.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_APPLY_CHANGES)); toolBarManager.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_REJECT_CHANGES)); toolBarManager.add(new Separator()); toolBarManager.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_ROW_EDIT)); toolBarManager.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_ROW_ADD)); toolBarManager.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_ROW_COPY)); toolBarManager.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_ROW_DELETE)); toolBarManager.add(new Separator()); toolBarManager.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_ROW_FIRST)); toolBarManager.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_ROW_PREVIOUS)); toolBarManager.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_ROW_NEXT)); toolBarManager.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_ROW_LAST)); toolBarManager.add(new Separator()); // Link to standard Find/Replace action - it has to be handled by owner site toolBarManager.add(ActionUtils.makeCommandContribution(site, IWorkbenchCommandConstants.EDIT_FIND_AND_REPLACE, CommandContributionItem.STYLE_PUSH, DBIcon.FIND_TEXT.getImageDescriptor())); // Use simple action for refresh to avoid ambiguous behaviour of F5 shortcut //toolBarManager.add(ActionUtils.makeCommandContribution(site, IWorkbenchCommandConstants.FILE_REFRESH, "Refresh result set", DBIcon.RS_REFRESH.getImageDescriptor())); Action refreshAction = new Action(CoreMessages.controls_resultset_viewer_action_refresh, DBIcon.RS_REFRESH.getImageDescriptor()) { @Override public void run() { refresh(); } }; toolBarManager.add(refreshAction); toolBarManager.add(new Separator()); toolBarManager.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_TOGGLE_MODE, CommandContributionItem.STYLE_CHECK)); toolBarManager.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_TOGGLE_PREVIEW, CommandContributionItem.STYLE_CHECK)); toolBarManager.add(new ConfigAction()); toolBarManager.createControl(statusBar); //updateEditControls(); } @NotNull public Spreadsheet getSpreadsheet() { return spreadsheet; } public DBSDataContainer getDataContainer() { return resultSetProvider.getDataContainer(); } // Grid/Record mode public GridMode getGridMode() { return gridMode; } public void toggleMode() { changeMode(gridMode == GridMode.GRID ? GridMode.RECORD : GridMode.GRID); // Refresh elements ICommandService commandService = (ICommandService) site.getService(ICommandService.class); if (commandService != null) { commandService.refreshElements(ResultSetCommandHandler.CMD_TOGGLE_MODE, null); } } private void changeMode(GridMode gridMode) { int oldRowNum = this.curRowNum, oldColNum = this.curColNum; int rowCount = model.getRowCount(); if (rowCount > 0) { // Fix row number if needed if (oldRowNum < 0) { oldRowNum = this.curRowNum = 0; } else if (oldRowNum >= rowCount) { oldRowNum = this.curRowNum = rowCount - 1; } } this.gridMode = gridMode; if (this.gridMode == GridMode.GRID) { this.spreadsheet.setRowHeaderWidth(DEFAULT_ROW_HEADER_WIDTH); this.initResultSet(); } else { this.resetRecordHeaderWidth(); this.updateRecordMode(); } if (gridMode == GridMode.GRID) { if (oldRowNum >= 0 && oldRowNum < spreadsheet.getItemCount()) { spreadsheet.setCursor(new GridPos(oldColNum, oldRowNum), false); } } else { if (oldColNum >= 0) { spreadsheet.setCursor(new GridPos(0, oldColNum), false); } } spreadsheet.layout(true, true); previewValue(); } private void resetRecordHeaderWidth() { // Calculate width of spreadsheet panel - use longest column title int defaultWidth = 0; GC gc = new GC(spreadsheet); gc.setFont(spreadsheet.getFont()); for (DBDAttributeBinding column : model.getVisibleColumns()) { Point ext = gc.stringExtent(column.getAttributeName()); if (ext.x > defaultWidth) { defaultWidth = ext.x; } } defaultWidth += DBIcon.EDIT_COLUMN.getImage().getBounds().width + 2; spreadsheet.setRowHeaderWidth(defaultWidth + DEFAULT_ROW_HEADER_WIDTH); } // Value preview public boolean isPreviewVisible() { return resultsSash.getMaximizedControl() == null; } public void togglePreview() { if (resultsSash.getMaximizedControl() == null) { resultsSash.setMaximizedControl(spreadsheet); } else { resultsSash.setMaximizedControl(null); previewValue(); } getPreferences().setValue(VIEW_PANEL_VISIBLE, isPreviewVisible()); // Refresh elements ICommandService commandService = (ICommandService) site.getService(ICommandService.class); if (commandService != null) { commandService.refreshElements(ResultSetCommandHandler.CMD_TOGGLE_PREVIEW, null); } } void previewValue() { GridCell currentPosition = getCurrentPosition(); if (!isPreviewVisible() || currentPosition == null) { return; } GridCell cell = translateVisualPos(currentPosition); if (panelValueController == null || panelValueController.pos.col != cell.col) { panelValueController = new ResultSetValueController( cell, DBDValueController.EditType.PANEL, previewPane.getViewPlaceholder()); } else { panelValueController.setCurRow((RowData) cell.row); } previewPane.viewValue(panelValueController); } // Misc private void dispose() { closeEditors(); clearData(); themeManager.removePropertyChangeListener(ResultSetViewer.this); UIUtils.dispose(this.boldFont); if (toolBarManager != null) { try { toolBarManager.dispose(); } catch (Throwable e) { // ignore log.debug("Error disposing toolbar", e); } } } private void applyThemeSettings() { ITheme currentTheme = themeManager.getCurrentTheme(); Font rsFont = currentTheme.getFontRegistry().get(ThemeConstants.FONT_SQL_RESULT_SET); if (rsFont != null) { this.spreadsheet.setFont(rsFont); } Color previewBack = currentTheme.getColorRegistry().get(ThemeConstants.COLOR_SQL_RESULT_SET_PREVIEW_BACK); if (previewBack != null) { this.previewPane.getViewPlaceholder().setBackground(previewBack); for (Control control : this.previewPane.getViewPlaceholder().getChildren()) { control.setBackground(previewBack); } } this.backgroundAdded = currentTheme.getColorRegistry().get(ThemeConstants.COLOR_SQL_RESULT_CELL_NEW_BACK); this.backgroundDeleted = currentTheme.getColorRegistry().get(ThemeConstants.COLOR_SQL_RESULT_CELL_DELETED_BACK); this.backgroundModified = currentTheme.getColorRegistry().get(ThemeConstants.COLOR_SQL_RESULT_CELL_MODIFIED_BACK); this.backgroundOdd = currentTheme.getColorRegistry().get(ThemeConstants.COLOR_SQL_RESULT_CELL_ODD_BACK); this.spreadsheet.recalculateSizes(); } @Override public void propertyChange(PropertyChangeEvent event) { if (event.getProperty().startsWith(ThemeConstants.RESULTS_PROP_PREFIX)) { applyThemeSettings(); } } void scrollToRow(RowPosition position) { switch (position) { case FIRST: if (gridMode == GridMode.RECORD) { curRowNum = 0; updateRecordMode(); } else { spreadsheet.shiftCursor(0, -spreadsheet.getItemCount(), false); } break; case PREVIOUS: if (gridMode == GridMode.RECORD && curRowNum > 0) { curRowNum updateRecordMode(); } else { spreadsheet.shiftCursor(0, -1, false); } break; case NEXT: if (gridMode == GridMode.RECORD && curRowNum < model.getRowCount() - 1) { curRowNum++; updateRecordMode(); } else { spreadsheet.shiftCursor(0, 1, false); } break; case LAST: if (gridMode == GridMode.RECORD && model.getRowCount() > 0) { curRowNum = model.getRowCount() - 1; updateRecordMode(); } else { spreadsheet.shiftCursor(0, spreadsheet.getItemCount(), false); } break; } } boolean isColumnReadOnly(GridCell pos) { DBDAttributeBinding column; if (gridMode == GridMode.GRID) { column = (DBDAttributeBinding)pos.col; } else { column = (DBDAttributeBinding)pos.row; } return isReadOnly() || model.isColumnReadOnly(column); } boolean isColumnReadOnly(DBDAttributeBinding column) { return isReadOnly() || model.isColumnReadOnly(column); } public int getCurrentRow() { return gridMode == GridMode.GRID ? spreadsheet.getCurrentRow() : curRowNum; } @Nullable public GridCell getCurrentPosition() { return spreadsheet.getCursorCell(); } public void setStatus(String status) { setStatus(status, false); } public void setStatus(String status, boolean error) { if (statusLabel.isDisposed()) { return; } if (error) { statusLabel.setForeground(colorRed); } else { statusLabel.setForeground(null); } if (status == null) { status = "???"; //$NON-NLS-1$ } statusLabel.setText(status); } public void updateStatusMessage() { if (model.getRowCount() == 0) { if (model.getVisibleColumnCount() == 0) { setStatus(CoreMessages.controls_resultset_viewer_status_empty + getExecutionTimeMessage()); } else { setStatus(CoreMessages.controls_resultset_viewer_status_no_data + getExecutionTimeMessage()); } } else { if (gridMode == GridMode.RECORD) { this.resetRecordHeaderWidth(); setStatus(CoreMessages.controls_resultset_viewer_status_row + (curRowNum + 1) + "/" + model.getRowCount() + getExecutionTimeMessage()); } else { setStatus(String.valueOf(model.getRowCount()) + CoreMessages.controls_resultset_viewer_status_rows_fetched + getExecutionTimeMessage()); } } } private String getExecutionTimeMessage() { DBCStatistics statistics = model.getStatistics(); if (statistics == null || statistics.isEmpty()) { return ""; } return " - " + RuntimeUtils.formatExecutionTime(statistics.getTotalTime()); } /** * Sets new metadata of result set * @param columns columns metadata * @return true if new metadata differs from old one, false otherwise */ public boolean setMetaData(DBDAttributeBinding[] columns) { if (model.setMetaData(columns)) { this.panelValueController = null; return true; } return false; } public void setData(List<Object[]> rows, boolean updateMetaData) { if (spreadsheet.isDisposed()) { return; } // Clear previous data this.closeEditors(); model.setData(rows, updateMetaData); if (updateMetaData) { if (getPreferenceStore().getBoolean(DBeaverPreferences.RESULT_SET_AUTO_SWITCH_MODE)) { GridMode newMode = (rows.size() == 1) ? GridMode.RECORD : GridMode.GRID; if (newMode != gridMode) { toggleMode(); // ResultSetPropertyTester.firePropertyChange(ResultSetPropertyTester.PROP_CAN_TOGGLE); } } this.initResultSet(); } else { this.refreshSpreadsheet(true); } updateEditControls(); } public void appendData(List<Object[]> rows) { model.appendData(rows); //refreshSpreadsheet(true); spreadsheet.refreshData(false); setStatus(NLS.bind(CoreMessages.controls_resultset_viewer_status_rows_size, model.getRowCount(), rows.size()) + getExecutionTimeMessage()); updateEditControls(); } private void closeEditors() { List<DBDValueEditorStandalone> editors = new ArrayList<DBDValueEditorStandalone>(openEditors.values()); for (DBDValueEditorStandalone editor : editors) { editor.closeValueEditor(); } if (!openEditors.isEmpty()) { log.warn("Some value editors are still registered at result set: " + openEditors.size()); } openEditors.clear(); } private void initResultSet() { spreadsheet.setRedraw(false); try { spreadsheet.clearGrid(); if (gridMode == GridMode.RECORD) { this.resetRecordHeaderWidth(); } spreadsheet.refreshData(true); } finally { spreadsheet.setRedraw(true); } this.updateFiltersText(); this.updateStatusMessage(); } @Override public int promptToSaveOnClose() { if (!isDirty()) { return ISaveablePart2.YES; } int result = ConfirmationDialog.showConfirmDialog( spreadsheet.getShell(), DBeaverPreferences.CONFIRM_RS_EDIT_CLOSE, ConfirmationDialog.QUESTION_WITH_CANCEL); if (result == IDialogConstants.YES_ID) { return ISaveablePart2.YES; } else if (result == IDialogConstants.NO_ID) { rejectChanges(); return ISaveablePart2.NO; } else { return ISaveablePart2.CANCEL; } } @Override public void doSave(IProgressMonitor monitor) { applyChanges(RuntimeUtils.makeMonitor(monitor)); } @Override public void doSaveAs() { } @Override public boolean isDirty() { return model.isDirty(); } @Override public boolean isSaveAsAllowed() { return false; } @Override public boolean isSaveOnCloseNeeded() { return true; } @Override public boolean hasData() { return model.hasData(); } @Override public boolean isReadOnly() { if (model.isUpdateInProgress()) { return true; } DBSDataContainer dataContainer = getDataContainer(); if (dataContainer == null) { return true; } DBPDataSource dataSource = dataContainer.getDataSource(); return !dataSource.isConnected() || dataSource.getContainer().isConnectionReadOnly() || dataSource.getInfo().isReadOnlyData(); } /** * Translated visual grid position into model cell position. * Check for grid mode (grid/record) and columns reordering/hiding * @param pos visual position * @return model position */ @NotNull GridCell translateVisualPos(@NotNull GridCell pos) { if (gridMode == GridMode.GRID) { return pos; } else { return new GridCell(pos.row, pos.col); } } /** * Checks that current state of result set allows to insert new rows * @return true if new rows insert is allowed */ @Override public boolean isInsertable() { return !isReadOnly() && model.isSingleSource() && model.getVisibleColumnCount() > 0; } @Nullable @Override public Control showCellEditor( final boolean inline) { // The control that will be the editor must be a child of the Table final GridCell focusCell = spreadsheet.getFocusCell(); if (focusCell == null) { return null; } GridCell cell = translateVisualPos(focusCell); if (!inline) { for (ResultSetValueController valueController : openEditors.keySet()) { GridCell cellPos = valueController.getCellPos(); if (cellPos != null && cellPos.equalsTo(cell)) { openEditors.get(valueController).showValueEditor(); return null; } } } DBDAttributeBinding metaColumn = (DBDAttributeBinding) cell.col; final int handlerFeatures = metaColumn.getValueHandler().getFeatures(); if (handlerFeatures == DBDValueHandler.FEATURE_NONE) { return null; } if (inline && (handlerFeatures & DBDValueHandler.FEATURE_INLINE_EDITOR) == 0 && (handlerFeatures & DBDValueHandler.FEATURE_VIEWER) != 0) { // Inline editor isn't supported but panel viewer is // Enable panel if (!isPreviewVisible()) { togglePreview(); } return null; } if (isColumnReadOnly(metaColumn) && inline) { // No inline editors for readonly columns return null; } Composite placeholder = null; if (inline) { if (isReadOnly()) { return null; } spreadsheet.cancelInlineEditor(); placeholder = new Composite(spreadsheet, SWT.NONE); placeholder.setFont(spreadsheet.getFont()); placeholder.setLayout(new FillLayout()); GridData gd = new GridData(GridData.FILL_BOTH); gd.horizontalIndent = 0; gd.verticalIndent = 0; gd.grabExcessHorizontalSpace = true; gd.grabExcessVerticalSpace = true; placeholder.setLayoutData(gd); } ResultSetValueController valueController = new ResultSetValueController( cell, inline ? DBDValueController.EditType.INLINE : DBDValueController.EditType.EDITOR, placeholder); final DBDValueEditor editor; try { editor = metaColumn.getValueHandler().createEditor(valueController); } catch (Exception e) { UIUtils.showErrorDialog(site.getShell(), "Cannot edit value", null, e); return null; } if (editor instanceof DBDValueEditorStandalone) { valueController.registerEditor((DBDValueEditorStandalone)editor); // show dialog in separate job to avoid block new UIJob("Open separate editor") { @Override public IStatus runInUIThread(IProgressMonitor monitor) { ((DBDValueEditorStandalone)editor).showValueEditor(); return Status.OK_STATUS; } }.schedule(); //((DBDValueEditorStandalone)editor).showValueEditor(); } else { // Set editable value if (editor != null) { try { editor.primeEditorValue(valueController.getValue()); } catch (DBException e) { log.error(e); } } } if (inline) { if (editor != null) { spreadsheet.showCellEditor(placeholder); return editor.getControl(); } else { // No editor was created so just drop placeholder placeholder.dispose(); // Probably we can just show preview panel if ((handlerFeatures & DBDValueHandler.FEATURE_VIEWER) != 0) { // Inline editor isn't supported but panel viewer is // Enable panel if (!isPreviewVisible()) { togglePreview(); } return null; } } } return null; } @Override public void resetCellValue(@NotNull GridCell cell, boolean delete) { cell = translateVisualPos(cell); model.resetCellValue(cell, delete); spreadsheet.redrawGrid(); updateEditControls(); previewValue(); } @Override public void fillContextMenu(@NotNull final GridCell curCell, @NotNull IMenuManager manager) { // Custom oldValue items { final GridCell cell = translateVisualPos(curCell); final ResultSetValueController valueController = new ResultSetValueController( cell, DBDValueController.EditType.NONE, null); final Object value = valueController.getValue(); // Standard items manager.add(ActionUtils.makeCommandContribution(site, IWorkbenchCommandConstants.EDIT_CUT)); manager.add(ActionUtils.makeCommandContribution(site, IWorkbenchCommandConstants.EDIT_COPY)); manager.add(ActionUtils.makeCommandContribution(site, ICommandIds.CMD_COPY_SPECIAL)); manager.add(ActionUtils.makeCommandContribution(site, IWorkbenchCommandConstants.EDIT_PASTE)); manager.add(ActionUtils.makeCommandContribution(site, IWorkbenchCommandConstants.EDIT_DELETE)); // Edit items manager.add(new Separator()); manager.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_ROW_EDIT)); manager.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_ROW_EDIT_INLINE)); if (!valueController.isReadOnly() && !DBUtils.isNullValue(value)) { manager.add(new Action(CoreMessages.controls_resultset_viewer_action_set_to_null) { @Override public void run() { valueController.updateValue( DBUtils.makeNullValue(valueController)); } }); } if (((RowData)cell.row).isChanged()) { Action resetValueAction = new Action(CoreMessages.controls_resultset_viewer_action_reset_value) { @Override public void run() { resetCellValue(cell, false); } }; resetValueAction.setAccelerator(SWT.ESC); manager.add(resetValueAction); } // Menus from value handler try { manager.add(new Separator()); ((DBDAttributeBinding)cell.col).getValueHandler().contributeActions(manager, valueController); } catch (Exception e) { log.error(e); } } if (model.getVisibleColumnCount() > 0 && !model.isUpdateInProgress()) { // Export and other utility methods manager.add(new Separator()); MenuManager filtersMenu = new MenuManager( CoreMessages.controls_resultset_viewer_action_order_filter, DBIcon.FILTER.getImageDescriptor(), "filters"); //$NON-NLS-1$ filtersMenu.setRemoveAllWhenShown(true); filtersMenu.addMenuListener(new IMenuListener() { @Override public void menuAboutToShow(IMenuManager manager) { fillFiltersMenu(curCell, manager); } }); manager.add(filtersMenu); manager.add(new Action(CoreMessages.controls_resultset_viewer_action_export, DBIcon.EXPORT.getImageDescriptor()) { @Override public void run() { ActiveWizardDialog dialog = new ActiveWizardDialog( site.getWorkbenchWindow(), new DataTransferWizard( new IDataTransferProducer[] { new DatabaseTransferProducer(getDataContainer(), model.getDataFilter())}, null), getSelection()); dialog.open(); } }); } manager.add(new GroupMarker(ICommandIds.GROUP_TOOLS)); } private void fillFiltersMenu(@NotNull GridCell currentPosition, @NotNull IMenuManager filtersMenu) { DBDAttributeBinding column = (DBDAttributeBinding)(currentPosition.col instanceof DBDAttributeBinding ? currentPosition.col : currentPosition.row); if (supportsDataFilter()) { DBPDataKind dataKind = column.getMetaAttribute().getDataKind(); if (!column.getMetaAttribute().isRequired()) { filtersMenu.add(new FilterByColumnAction("IS NULL", FilterByColumnType.NONE, column)); filtersMenu.add(new FilterByColumnAction("IS NOT NULL", FilterByColumnType.NONE, column)); } for (FilterByColumnType type : FilterByColumnType.values()) { if (type == FilterByColumnType.NONE) { // Value filters are available only if certain cell is selected continue; } filtersMenu.add(new Separator()); if (type.getValue(this, column, true, DBDDisplayFormat.NATIVE) == null) { continue; } if (dataKind == DBPDataKind.BOOLEAN) { filtersMenu.add(new FilterByColumnAction("= ?", type, column)); filtersMenu.add(new FilterByColumnAction("<> ?", type, column)); } else if (dataKind == DBPDataKind.NUMERIC || dataKind == DBPDataKind.DATETIME) { filtersMenu.add(new FilterByColumnAction("= ?", type, column)); filtersMenu.add(new FilterByColumnAction("<> ?", type, column)); filtersMenu.add(new FilterByColumnAction("> ?", type, column)); filtersMenu.add(new FilterByColumnAction("< ?", type, column)); } else if (dataKind == DBPDataKind.STRING) { filtersMenu.add(new FilterByColumnAction("= '?'", type, column)); filtersMenu.add(new FilterByColumnAction("<> '?'", type, column)); filtersMenu.add(new FilterByColumnAction("> '?'", type, column)); filtersMenu.add(new FilterByColumnAction("< '?'", type, column)); filtersMenu.add(new FilterByColumnAction("LIKE '%?%'", type, column)); filtersMenu.add(new FilterByColumnAction("NOT LIKE '%?%'", type, column)); } } filtersMenu.add(new Separator()); if (!CommonUtils.isEmpty(model.getDataFilter().getConstraint(column).getCriteria())) { filtersMenu.add(new FilterResetColumnAction(column)); } } { final List<Object> selectedColumns = getSpreadsheet().getColumnSelection(); if (getGridMode() == GridMode.GRID && !selectedColumns.isEmpty()) { String hideTitle; if (selectedColumns.size() == 1) { DBDAttributeBinding columnToHide = (DBDAttributeBinding) selectedColumns.get(0); hideTitle = "Hide column '" + columnToHide.getAttributeName() + "'"; } else { hideTitle = "Hide selected columns (" + selectedColumns.size() + ")"; } filtersMenu.add(new Action(hideTitle) { @Override public void run() { if (selectedColumns.size() >= getModel().getVisibleColumnCount()) { UIUtils.showMessageBox(getControl().getShell(), "Hide columns", "Can't hide all result columns, at least one column must be visible", SWT.ERROR); } else { int[] columnIndexes = new int[selectedColumns.size()]; for (int i = 0, selectedColumnsSize = selectedColumns.size(); i < selectedColumnsSize; i++) { columnIndexes[i] = model.getVisibleColumnIndex((DBDAttributeBinding) selectedColumns.get(i)); } Arrays.sort(columnIndexes); for (int i = columnIndexes.length; i > 0; i getModel().setColumnVisibility(getModel().getVisibleColumn(columnIndexes[i - 1]), false); } refreshSpreadsheet(true); } } }); } } filtersMenu.add(new Separator()); filtersMenu.add(new ToggleServerSideOrderingAction()); filtersMenu.add(new ShowFiltersAction()); } boolean supportsDataFilter() { return (getDataContainer().getSupportedFeatures() & DBSDataContainer.DATA_FILTER) == DBSDataContainer.DATA_FILTER; } @Override public void changeSorting(@NotNull Object columnElement, final int state) { DBDDataFilter dataFilter = model.getDataFilter(); boolean ctrlPressed = (state & SWT.CTRL) == SWT.CTRL; boolean altPressed = (state & SWT.ALT) == SWT.ALT; if (ctrlPressed) { dataFilter.resetOrderBy(); } DBDAttributeBinding metaColumn = (DBDAttributeBinding)columnElement; DBDAttributeConstraint constraint = dataFilter.getConstraint(metaColumn); //int newSort; if (constraint.getOrderPosition() == 0) { if (isServerSideFiltering() && supportsDataFilter()) { if (!ConfirmationDialog.confirmActionWithParams( spreadsheet.getShell(), DBeaverPreferences.CONFIRM_ORDER_RESULTSET, metaColumn.getAttributeName())) { return; } } constraint.setOrderPosition(dataFilter.getMaxOrderingPosition() + 1); constraint.setOrderDescending(altPressed); } else if (!constraint.isOrderDescending()) { constraint.setOrderDescending(true); } else { for (DBDAttributeConstraint con2 : dataFilter.getConstraints()) { if (con2.getOrderPosition() > constraint.getOrderPosition()) { con2.setOrderPosition(con2.getOrderPosition() - 1); } } constraint.setOrderPosition(0); constraint.setOrderDescending(false); } // Reorder reorderResultSet(false, new Runnable() { @Override public void run() { if (gridMode == GridMode.GRID) { spreadsheet.refreshData(false); } } }); } @Override public Control getControl() { return this.viewerPanel; } @NotNull public IWorkbenchPartSite getSite() { return site; } @NotNull public ResultSetModel getModel() { return model; } @Override public ResultSetModel getInput() { return model; } @Override public void setInput(Object input) { throw new IllegalArgumentException("ResultSet model can't be changed"); } @Override @NotNull public ResultSetSelection getSelection() { return new ResultSetSelectionImpl(); } @Override public void setSelection(ISelection selection, boolean reveal) { if (selection instanceof ResultSetSelectionImpl && ((ResultSetSelectionImpl) selection).getResultSetViewer() == this) { // It may occur on simple focus change so we won't do anything return; } spreadsheet.deselectAllCells(); if (!selection.isEmpty() && selection instanceof IStructuredSelection) { List<GridPos> cellSelection = new ArrayList<GridPos>(); for (Iterator iter = ((IStructuredSelection) selection).iterator(); iter.hasNext(); ) { Object cell = iter.next(); if (cell instanceof GridPos) { cellSelection.add((GridPos) cell); } else { log.warn("Bad selection object: " + cell); } } spreadsheet.selectCells(cellSelection); if (reveal) { spreadsheet.showSelection(); } } fireSelectionChanged(new SelectionChangedEvent(this, selection)); } @NotNull public DBDDataReceiver getDataReceiver() { return dataReceiver; } @Override public void refresh() { // Check if we are dirty if (isDirty()) { switch (promptToSaveOnClose()) { case ISaveablePart2.CANCEL: return; case ISaveablePart2.YES: // Apply changes applyChanges(null, new ResultSetPersister.DataUpdateListener() { @Override public void onUpdate(boolean success) { if (success) { getControl().getDisplay().asyncExec(new Runnable() { @Override public void run() { refresh(); } }); } } }); return; default: // Just ignore previous RS values break; } } // Cache preferences IPreferenceStore preferenceStore = getPreferenceStore(); showOddRows = preferenceStore.getBoolean(DBeaverPreferences.RESULT_SET_SHOW_ODD_ROWS); showCelIcons = preferenceStore.getBoolean(DBeaverPreferences.RESULT_SET_SHOW_CELL_ICONS); // Pump data int oldRowNum = curRowNum; int oldColNum = curColNum; if (resultSetProvider.isReadyToRun() && getDataContainer() != null && dataPumpJob == null) { int segmentSize = getSegmentMaxRows(); if (oldRowNum >= segmentSize && segmentSize > 0) { segmentSize = (oldRowNum / segmentSize + 1) * segmentSize; } runDataPump(0, segmentSize, new GridPos(oldColNum, oldRowNum), new Runnable() { @Override public void run() { if (!supportsDataFilter() && !model.getDataFilter().hasOrdering()) { reorderLocally(); } } }); } } private boolean isServerSideFiltering() { return getPreferenceStore().getBoolean(DBeaverPreferences.RESULT_SET_ORDER_SERVER_SIDE) && (dataReceiver.isHasMoreData() || !CommonUtils.isEmpty(model.getDataFilter().getOrder())); } private void reorderResultSet(boolean force, @Nullable Runnable onSuccess) { if (force || isServerSideFiltering() && supportsDataFilter()) { if (resultSetProvider != null && resultSetProvider.isReadyToRun() && getDataContainer() != null && dataPumpJob == null) { int segmentSize = getSegmentMaxRows(); if (curRowNum >= segmentSize && segmentSize > 0) { segmentSize = (curRowNum / segmentSize + 1) * segmentSize; } runDataPump(0, segmentSize, new GridPos(curColNum, curRowNum), onSuccess); } return; } try { reorderLocally(); } finally { if (onSuccess != null) { onSuccess.run(); } } } private void reorderLocally() { rejectChanges(); model.resetOrdering(); } synchronized void readNextSegment() { if (!dataReceiver.isHasMoreData()) { return; } if (getDataContainer() != null && !model.isUpdateInProgress() && dataPumpJob == null) { dataReceiver.setHasMoreData(false); dataReceiver.setNextSegmentRead(true); runDataPump(model.getRowCount(), getSegmentMaxRows(), null, null); } } int getSegmentMaxRows() { if (getDataContainer() == null) { return 0; } return getPreferenceStore().getInt(DBeaverPreferences.RESULT_SET_MAX_ROWS); } @NotNull public IPreferenceStore getPreferenceStore() { DBPDataSource dataSource = getDataSource(); if (dataSource != null) { return dataSource.getContainer().getPreferenceStore(); } return DBeaverCore.getGlobalPreferenceStore(); } private synchronized void runDataPump( final int offset, final int maxRows, @Nullable final GridPos oldPos, @Nullable final Runnable finalizer) { if (dataPumpJob == null) { dataPumpJob = new ResultSetDataPumpJob(this); dataPumpJob.addJobChangeListener(new JobChangeAdapter() { @Override public void done(IJobChangeEvent event) { ResultSetDataPumpJob job = (ResultSetDataPumpJob)event.getJob(); final Throwable error = job.getError(); if (job.getStatistics() != null) { model.setStatistics(job.getStatistics()); } Display.getDefault().asyncExec(new Runnable() { @Override public void run() { Control control = getControl(); if (control == null || control.isDisposed()) { return; } final Shell shell = control.getShell(); if (error != null) { setStatus(error.getMessage(), true); UIUtils.showErrorDialog( shell, "Error executing query", "Query execution failed", error); } else if (oldPos != null) { // Seems to be refresh // Restore original position ResultSetViewer.this.curRowNum = Math.min(oldPos.row, model.getRowCount() - 1); ResultSetViewer.this.curColNum = Math.min(oldPos.col, model.getVisibleColumnCount() - 1); GridPos newPos; if (gridMode == GridMode.GRID) { newPos = new GridPos(curColNum, curRowNum); } else { if (ResultSetViewer.this.curRowNum < 0 && model.getRowCount() > 0) { ResultSetViewer.this.curRowNum = 0; } newPos = new GridPos(0, curColNum); } spreadsheet.setCursor(newPos, false); updateStatusMessage(); previewValue(); } else { spreadsheet.redraw(); } updateFiltersText(); if (finalizer != null) { finalizer.run(); } dataPumpJob = null; } }); } }); dataPumpJob.setOffset(offset); dataPumpJob.setMaxRows(maxRows); dataPumpJob.schedule(); } } private void clearData() { model.clearData(); this.curRowNum = -1; this.curColNum = -1; } public void applyChanges(@Nullable DBRProgressMonitor monitor) { applyChanges(monitor, null); } /** * Saves changes to database * @param monitor monitor. If null then save will be executed in async job * @param listener finish listener (may be null) */ public void applyChanges(@Nullable DBRProgressMonitor monitor, @Nullable ResultSetPersister.DataUpdateListener listener) { if (!model.isSingleSource()) { UIUtils.showErrorDialog(getControl().getShell(), "Apply changes error", "Can't save data for result set from multiple sources"); return; } try { boolean needPK = false; for (RowData row : model.getAllRows()) { if (row.state == RowData.STATE_REMOVED || (row.state == RowData.STATE_NORMAL && row.isChanged())) { needPK = true; break; } } if (needPK) { // If we have deleted or updated rows then check for unique identifier if (!checkVirtualEntityIdentifier()) { //UIUtils.showErrorDialog(getControl().getShell(), "Can't apply changes", "Can't apply data changes - not unique identifier defined"); return; } } new ResultSetPersister(this).applyChanges(monitor, listener); } catch (DBException e) { UIUtils.showErrorDialog(getControl().getShell(), "Apply changes error", "Error saving changes in database", e); } } public void rejectChanges() { new ResultSetPersister(this).rejectChanges(); } public void copySelectionToClipboard( boolean copyHeader, boolean copyRowNumbers, boolean cut, String delimiter, DBDDisplayFormat format) { if (delimiter == null) { delimiter = "\t"; } String lineSeparator = ContentUtils.getDefaultLineSeparator(); List<Object> selectedColumns = spreadsheet.getColumnSelection(); IGridLabelProvider labelProvider = spreadsheet.getLabelProvider(); StringBuilder tdt = new StringBuilder(); if (copyHeader) { if (copyRowNumbers) { tdt.append(" } for (Object column : selectedColumns) { if (tdt.length() > 0) { tdt.append(delimiter); } tdt.append(labelProvider.getText(column)); } tdt.append(lineSeparator); } List<GridCell> selectedCells = spreadsheet.getCellSelection(); GridCell prevCell = null; for (GridCell cell : selectedCells) { if (prevCell == null || cell.row != prevCell.row) { // Next row if (prevCell != null && prevCell.col != cell.col) { // Fill empty row tail int prevColIndex = selectedColumns.indexOf(prevCell.col); for (int i = prevColIndex; i < selectedColumns.size() - 1; i++) { tdt.append(delimiter); } } if (prevCell != null) { tdt.append(lineSeparator); } if (copyRowNumbers) { tdt.append(labelProvider.getText(cell.row)).append(delimiter); } } if (prevCell != null && prevCell.col != cell.col) { int prevColIndex = selectedColumns.indexOf(prevCell.col); int curColIndex = selectedColumns.indexOf(cell.col); for (int i = prevColIndex; i < curColIndex; i++) { tdt.append(delimiter); } } DBDAttributeBinding column = (DBDAttributeBinding)(getGridMode() == GridMode.GRID ? cell.col : cell.row); RowData row = (RowData) (getGridMode() == GridMode.GRID ? cell.row : cell.col); Object value = row.values[column.getAttributeIndex()]; String cellText = column.getValueHandler().getValueDisplayString( column.getMetaAttribute(), value, format); if (cellText != null) { tdt.append(cellText); } if (cut) { DBDValueController valueController = new ResultSetValueController( cell, DBDValueController.EditType.NONE, null); if (!valueController.isReadOnly()) { valueController.updateValue(DBUtils.makeNullValue(valueController)); } } prevCell = cell; } /* if (copyRowNumbers) { tdt.append(rowLabelProvider.getText(rowNumber++)).append(delimiter); } int prevRow = firstRow; int prevCol = firstCol; for (GridPos pos : selection) { if (pos.row > prevRow) { if (prevCol < lastCol) { for (int i = prevCol; i < lastCol; i++) { if (colsSelected.contains(i)) { tdt.append(delimiter); } } } tdt.append(lineSeparator); if (copyRowNumbers) { tdt.append(rowLabelProvider.getText(rowNumber++)).append(delimiter); } prevRow = pos.row; prevCol = firstCol; } if (pos.col > prevCol) { for (int i = prevCol; i < pos.col; i++) { if (colsSelected.contains(i)) { tdt.append(delimiter); } } prevCol = pos.col; } GridCell cellPos = translateVisualPos(pos); Object[] curRow = model.getRowData(cellPos.row); Object value = curRow[cellPos.col]; DBDAttributeBinding column = model.getColumn(cellPos.col); String cellText = column.getValueHandler().getValueDisplayString( column.getMetaAttribute(), value, format); if (cellText != null) { tdt.append(cellText); } if (cut) { DBDValueController valueController = new ResultSetValueController( cellPos, DBDValueController.EditType.NONE, null); if (!valueController.isReadOnly()) { valueController.updateValue(DBUtils.makeNullValue(valueController)); } } } */ if (tdt.length() > 0) { TextTransfer textTransfer = TextTransfer.getInstance(); getSpreadsheet().getClipboard().setContents( new Object[]{tdt.toString()}, new Transfer[]{textTransfer}); } } public void pasteCellValue() { GridCell cell = getCurrentPosition(); if (cell == null) { return; } cell = translateVisualPos(cell); DBDAttributeBinding metaColumn = (DBDAttributeBinding) cell.col; if (isColumnReadOnly(metaColumn)) { // No inline editors for readonly columns return; } try { Object newValue = getColumnValueFromClipboard(metaColumn); if (newValue == null) { return; } new ResultSetValueController( cell, DBDValueController.EditType.NONE, null).updateValue(newValue); } catch (Exception e) { UIUtils.showErrorDialog(site.getShell(), "Cannot replace cell value", null, e); } } @Nullable private Object getColumnValueFromClipboard(DBDAttributeBinding metaColumn) throws DBCException { DBPDataSource dataSource = getDataSource(); if (dataSource == null) { return null; } DBCSession session = dataSource.openSession(VoidProgressMonitor.INSTANCE, DBCExecutionPurpose.UTIL, "Copy from clipboard"); try { String strValue = (String) getSpreadsheet().getClipboard().getContents(TextTransfer.getInstance()); return metaColumn.getValueHandler().getValueFromObject( session, metaColumn.getMetaAttribute(), strValue, true); } finally { session.close(); } } void addNewRow(final boolean copyCurrent) { GridPos curPos = spreadsheet.getCursorPosition(); int rowNum; if (gridMode == GridMode.RECORD) { rowNum = this.curRowNum; } else { rowNum = curPos.row; } if (rowNum >= getModel().getRowCount()) { rowNum = getModel().getRowCount() - 1; } if (rowNum < 0) { rowNum = 0; } final DBPDataSource dataSource = getDataSource(); if (dataSource == null) { return; } // Add new row final DBDAttributeBinding[] columns = model.getColumns(); final Object[] cells = new Object[columns.length]; final int currentRowNumber = rowNum; // Copy cell values in new context DBCSession session = dataSource.openSession(VoidProgressMonitor.INSTANCE, DBCExecutionPurpose.UTIL, CoreMessages.controls_resultset_viewer_add_new_row_context_name); try { if (copyCurrent && currentRowNumber >= 0 && currentRowNumber < model.getRowCount()) { Object[] origRow = model.getRowData(currentRowNumber); for (int i = 0; i < columns.length; i++) { DBDAttributeBinding metaColumn = columns[i]; DBSAttributeBase attribute = metaColumn.getAttribute(); if (attribute.isAutoGenerated() || attribute.isPseudoAttribute()) { // set pseudo and autoincrement columns to null cells[i] = null; } else { try { cells[i] = metaColumn.getValueHandler().getValueFromObject(session, attribute, origRow[i], true); } catch (DBCException e) { log.warn(e); try { cells[i] = DBUtils.makeNullValue(session, metaColumn.getValueHandler(), attribute); } catch (DBCException e1) { log.warn(e1); } } } } } else { // Initialize new values for (int i = 0; i < columns.length; i++) { DBDAttributeBinding metaColumn = columns[i]; try { cells[i] = DBUtils.makeNullValue(session, metaColumn.getValueHandler(), metaColumn.getAttribute()); } catch (DBCException e) { log.warn(e); } } } } finally { session.close(); } model.addNewRow(rowNum, cells); refreshSpreadsheet(true); updateEditControls(); fireResultSetChange(); } void deleteSelectedRows() { Set<RowData> rowsToDelete = new LinkedHashSet<RowData>(); if (gridMode == GridMode.RECORD) { rowsToDelete.add(model.getRow(curRowNum)); } else { for (GridCell cell : spreadsheet.getCellSelection()) { rowsToDelete.add((RowData) cell.row); } } if (rowsToDelete.isEmpty()) { return; } int rowsRemoved = 0; int lastRowNum = -1; for (RowData row : rowsToDelete) { if (model.deleteRow(row)) { rowsRemoved++; } lastRowNum = row.visualNumber; } // Move one row down (if we are in grid mode) if (gridMode == GridMode.GRID && lastRowNum < spreadsheet.getItemCount() - 1) { GridPos newPos = new GridPos(curColNum, lastRowNum - rowsRemoved + 1); spreadsheet.setCursor(newPos, false); } if (rowsRemoved > 0) { refreshSpreadsheet(true); } else { spreadsheet.redrawGrid(); } updateEditControls(); fireResultSetChange(); } @Nullable static Image getTypeImage(DBSTypedObject column) { if (column instanceof IObjectImageProvider) { return ((IObjectImageProvider)column).getObjectImage(); } else { return DBIcon.TREE_COLUMN.getImage(); } } // Virtual identifier management @Nullable DBCEntityIdentifier getVirtualEntityIdentifier() { if (!model.isSingleSource() || model.getVisibleColumnCount() == 0) { return null; } DBDRowIdentifier rowIdentifier = model.getVisibleColumn(0).getRowIdentifier(); DBCEntityIdentifier identifier = rowIdentifier == null ? null : rowIdentifier.getEntityIdentifier(); if (identifier != null && identifier.getReferrer() instanceof DBVEntityConstraint) { return identifier; } else { return null; } } boolean checkVirtualEntityIdentifier() throws DBException { // Check for value locators // Probably we have only virtual one with empty column set final DBCEntityIdentifier identifier = getVirtualEntityIdentifier(); if (identifier != null) { if (CommonUtils.isEmpty(identifier.getAttributes())) { // Empty identifier. We have to define it RunnableWithResult<Boolean> confirmer = new RunnableWithResult<Boolean>() { @Override public void run() { result = ValidateUniqueKeyUsageDialog.validateUniqueKey(ResultSetViewer.this); } }; UIUtils.runInUI(getControl().getShell(), confirmer); return confirmer.getResult(); } } return true; } boolean editEntityIdentifier(DBRProgressMonitor monitor) throws DBException { DBCEntityIdentifier virtualEntityIdentifier = getVirtualEntityIdentifier(); if (virtualEntityIdentifier == null) { log.warn("No virtual identifier"); return false; } DBVEntityConstraint constraint = (DBVEntityConstraint) virtualEntityIdentifier.getReferrer(); EditConstraintDialog dialog = new EditConstraintDialog( getControl().getShell(), "Define virtual unique identifier", constraint); if (dialog.open() != IDialogConstants.OK_ID) { return false; } Collection<DBSEntityAttribute> uniqueColumns = dialog.getSelectedColumns(); constraint.setAttributes(uniqueColumns); virtualEntityIdentifier = getVirtualEntityIdentifier(); if (virtualEntityIdentifier == null) { log.warn("No virtual identifier defined"); return false; } virtualEntityIdentifier.reloadAttributes(monitor, model.getVisibleColumn(0).getMetaAttribute().getEntity()); DBPDataSource dataSource = getDataSource(); if (dataSource != null) { dataSource.getContainer().persistConfiguration(); } return true; } void clearEntityIdentifier(DBRProgressMonitor monitor) throws DBException { DBDAttributeBinding firstColumn = model.getVisibleColumn(0); DBCEntityIdentifier identifier = firstColumn.getRowIdentifier().getEntityIdentifier(); DBVEntityConstraint virtualKey = (DBVEntityConstraint) identifier.getReferrer(); virtualKey.setAttributes(Collections.<DBSEntityAttribute>emptyList()); identifier.reloadAttributes(monitor, firstColumn.getMetaAttribute().getEntity()); virtualKey.getParentObject().setProperty(DBVConstants.PROPERTY_USE_VIRTUAL_KEY_QUIET, null); DBPDataSource dataSource = getDataSource(); if (dataSource != null) { dataSource.getContainer().persistConfiguration(); } } void fireResultSetChange() { synchronized (listeners) { if (!listeners.isEmpty()) { for (ResultSetListener listener : listeners) { listener.handleResultSetChange(); } } } } // Value controller private class ResultSetValueController implements DBDAttributeController, DBDRowController { private final GridCell pos; private final EditType editType; private final Composite inlinePlaceholder; private RowData curRow; private final DBDAttributeBinding column; private ResultSetValueController(GridCell pos, EditType editType, @Nullable Composite inlinePlaceholder) { this.curRow = (RowData) pos.row; this.column = (DBDAttributeBinding) pos.col; this.pos = new GridCell(pos); this.editType = editType; this.inlinePlaceholder = inlinePlaceholder; } void setCurRow(RowData curRow) { this.curRow = curRow; this.pos.row = curRow; } @Nullable @Override public DBPDataSource getDataSource() { return ResultSetViewer.this.getDataSource(); } @Override public String getValueName() { return getAttribute().getName(); } @Override public DBSTypedObject getValueType() { return getAttribute(); } @Override public DBDRowController getRow() { return this; } @Override public DBCAttributeMetaData getAttribute() { return column.getMetaAttribute(); } @Override public String getColumnId() { DBPDataSource dataSource = getDataSource(); return DBUtils.getSimpleQualifiedName( dataSource == null ? null : dataSource.getContainer().getName(), getAttribute().getEntityName(), getAttribute().getName()); } @Override public Object getValue() { return spreadsheet.getContentProvider().getCellValue(pos, false); } @Override public void updateValue(@Nullable Object value) { if (model.updateCellValue(curRow, column, value)) { // Update controls site.getShell().getDisplay().syncExec(new Runnable() { @Override public void run() { updateEditControls(); spreadsheet.redrawGrid(); previewValue(); } }); } fireResultSetChange(); } @Override public DBDRowIdentifier getValueLocator() { return column.getRowIdentifier(); } @Override public DBDValueHandler getValueHandler() { return column.getValueHandler(); } @Override public EditType getEditType() { return editType; } @Override public boolean isReadOnly() { return isColumnReadOnly(column); } @Override public IWorkbenchPartSite getValueSite() { return site; } @Nullable @Override public Composite getEditPlaceholder() { return inlinePlaceholder; } @Nullable @Override public ToolBar getEditToolBar() { return isPreviewVisible() ? previewPane.getToolBar() : null; } @Override public void closeInlineEditor() { spreadsheet.cancelInlineEditor(); } @Override public void nextInlineEditor(boolean next) { spreadsheet.cancelInlineEditor(); int colOffset = next ? 1 : -1; int rowOffset = 0; //final int rowCount = spreadsheet.getItemCount(); final int colCount = spreadsheet.getColumnCount(); final GridPos curPosition = spreadsheet.getCursorPosition(); if (colOffset > 0 && curPosition.col + colOffset >= colCount) { colOffset = -colCount; rowOffset = 1; } else if (colOffset < 0 && curPosition.col + colOffset < 0) { colOffset = colCount; rowOffset = -1; } spreadsheet.shiftCursor(colOffset, rowOffset, false); showCellEditor(true); } public void registerEditor(DBDValueEditorStandalone editor) { openEditors.put(this, editor); } @Override public void unregisterEditor(DBDValueEditorStandalone editor) { openEditors.remove(this); } @Override public void showMessage(String message, boolean error) { setStatus(message, error); } @Override public Collection<DBCAttributeMetaData> getAttributesMetaData() { List<DBCAttributeMetaData> attributes = new ArrayList<DBCAttributeMetaData>(); for (DBDAttributeBinding column : model.getVisibleColumns()) { attributes.add(column.getMetaAttribute()); } return attributes; } @Nullable @Override public DBCAttributeMetaData getAttributeMetaData(DBCEntityMetaData entity, String columnName) { for (DBDAttributeBinding column : model.getVisibleColumns()) { if (column.getMetaAttribute().getEntity() == entity && column.getAttributeName().equals(columnName)) { return column.getMetaAttribute(); } } return null; } @Nullable @Override public Object getAttributeValue(DBCAttributeMetaData attribute) { DBDAttributeBinding[] columns = model.getColumns(); for (int i = 0; i < columns.length; i++) { DBDAttributeBinding metaColumn = columns[i]; if (metaColumn.getMetaAttribute() == attribute) { return curRow.values[i]; } } log.warn("Unknown column value requested: " + attribute); return null; } @Nullable private GridCell getCellPos() { return pos; } } private class ContentProvider implements IGridContentProvider { @NotNull @Override public Object[] getElements(boolean horizontal) { if (horizontal) { // columns if (gridMode == GridMode.GRID) { return model.getVisibleColumns().toArray(); } else { return new Object[] {model.getRow(curRowNum)}; } } else { // rows if (gridMode == GridMode.GRID) { return model.getAllRows().toArray(); } else { return model.getVisibleColumns().toArray(); } } } @Nullable @Override public Object[] getChildren(Object element) { if (element instanceof DBDAttributeBinding) { DBDAttributeBinding binding = (DBDAttributeBinding) element; if (binding.getNestedBindings() != null) { return binding.getNestedBindings().toArray(); } final DBSAttributeBase attribute = binding.getAttribute(); if (attribute.getDataKind() == DBPDataKind.ARRAY && getGridMode() == GridMode.RECORD) { } } return null; } @Override public int getSortOrder(@NotNull Object column) { if (column instanceof DBDAttributeBinding) { DBDAttributeBinding binding = (DBDAttributeBinding) column; if (!binding.hasNestedBindings()) { DBDAttributeConstraint co = model.getDataFilter().getConstraint(binding); if (co != null && co.getOrderPosition() > 0) { return co.isOrderDescending() ? SWT.UP : SWT.DOWN; } return SWT.DEFAULT; } } return SWT.NONE; } @Override public ElementState getDefaultState(@NotNull Object element) { return ElementState.NONE; } @Override public void dispose() { } @Override public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { } @Nullable @Override public Object getCellValue(@NotNull GridCell cell, boolean formatString) { DBDAttributeBinding column = (DBDAttributeBinding)(cell.col instanceof DBDAttributeBinding ? cell.col : cell.row); RowData row = (RowData)(cell.col instanceof RowData ? cell.col : cell.row); int rowNum = row.visualNumber; Object value = extractColumnValue(row, column); if (rowNum > 0 && rowNum == model.getRowCount() - 1 && (gridMode == GridMode.RECORD || spreadsheet.isRowVisible(rowNum)) && dataReceiver.isHasMoreData()) { readNextSegment(); } if (formatString) { return column.getValueHandler().getValueDisplayString( column.getMetaAttribute(), value, DBDDisplayFormat.UI); } else { return value; } } @Nullable private Object extractColumnValue(@NotNull RowData row, @NotNull DBDAttributeBinding column) { int depth = column.getDepth(); if (depth == 1) { return row.values[column.getAttributeIndex()]; } DBDAttributeBinding[] path = new DBDAttributeBinding[depth]; for (int i = depth - 1; i >= 0; i path[i] = column; column = column.getParent(); } Object curValue = row.values[path[0].getAttributeIndex()]; for (int i = 1; i < depth; i++) { if (curValue == null) { break; } if (curValue instanceof DBDStructure) { try { curValue = ((DBDStructure) curValue).getAttributeValue(path[i].getAttribute()); } catch (DBCException e) { log.warn("Error getting field [" + path[i].getAttributeName() + "] value", e); curValue = null; break; } } else { log.debug("No struct value handler while trying to read nested attribute [" + path[i].getAttributeName() + "]"); curValue = null; break; } } return curValue; } @Nullable @Override public Image getCellImage(@NotNull GridCell cell) { if (!showCelIcons) { return null; } DBDAttributeBinding attr; if (gridMode == GridMode.RECORD) { attr = (DBDAttributeBinding) cell.row; } else { attr = (DBDAttributeBinding) cell.col; } if ((attr.getValueHandler().getFeatures() & DBDValueHandler.FEATURE_SHOW_ICON) != 0) { return getTypeImage(attr.getMetaAttribute()); } else { return null; } } @NotNull @Override public String getCellText(@NotNull GridCell cell) { return String.valueOf(getCellValue(cell, true)); } @Nullable @Override public Color getCellForeground(@NotNull GridCell cell) { Object value = getCellValue(cell, false); if (DBUtils.isNullValue(value)) { return foregroundNull; } else { return null; } } @Nullable @Override public Color getCellBackground(@NotNull GridCell cell) { RowData row = (RowData) (getGridMode() == GridMode.GRID ? cell.row : cell.col); boolean odd = row.visualNumber % 2 == 0; if (row.state == RowData.STATE_ADDED) { return backgroundAdded; } if (row.state == RowData.STATE_REMOVED) { return backgroundDeleted; } if (row.changedValues != null) { DBDAttributeBinding column = (DBDAttributeBinding)(getGridMode() == GridMode.GRID ? cell.col : cell.row); if (row.changedValues[column.getAttributeIndex()]) { return backgroundModified; } } if (odd && showOddRows) { return backgroundOdd; } return null; } } private class GridLabelProvider implements IGridLabelProvider { @Nullable @Override public Image getImage(Object element) { if (element instanceof DBDAttributeBinding) { return getTypeImage(((DBDAttributeBinding)element).getMetaAttribute()); } return null; } @Nullable @Override public Color getForeground(Object element) { return null; } @Nullable @Override public Color getBackground(Object element) { return null; } @Nullable @Override public String getText(Object element) { if (element instanceof DBDAttributeBinding) { DBDAttributeBinding attributeBinding = (DBDAttributeBinding) element; DBCAttributeMetaData attribute = attributeBinding.getMetaAttribute(); if (CommonUtils.isEmpty(attribute.getLabel())) { return attributeBinding.getAttributeName(); } else { return attribute.getLabel(); } } else { if (getGridMode() == GridMode.GRID) { return String.valueOf(((RowData)element).visualNumber + 1); } else { return CoreMessages.controls_resultset_viewer_value; } } } @Nullable @Override public Font getFont(Object element) { if (element instanceof DBDAttributeBinding) { DBDAttributeBinding attributeBinding = (DBDAttributeBinding) element; DBDAttributeConstraint constraint = model.getDataFilter().getConstraint(attributeBinding); if (constraint != null && constraint.hasFilter()) { return boldFont; } } return null; } @Nullable @Override public String getTooltip(Object element) { if (element instanceof DBDAttributeBinding) { DBDAttributeBinding attributeBinding = (DBDAttributeBinding) element; String name = attributeBinding.getAttributeName(); String typeName = DBUtils.getFullTypeName(attributeBinding.getMetaAttribute()); return name + ": " + typeName; } return null; } } private class ConfigAction extends Action implements IMenuCreator { public ConfigAction() { super(CoreMessages.controls_resultset_viewer_action_options, IAction.AS_DROP_DOWN_MENU); setImageDescriptor(DBIcon.CONFIGURATION.getImageDescriptor()); } @Override public IMenuCreator getMenuCreator() { return this; } @Override public void runWithEvent(Event event) { Menu menu = getMenu(getSpreadsheet()); if (menu != null && event.widget instanceof ToolItem) { Rectangle bounds = ((ToolItem) event.widget).getBounds(); Point point = ((ToolItem) event.widget).getParent().toDisplay(bounds.x, bounds.y + bounds.height); menu.setLocation(point.x, point.y); menu.setVisible(true); } } @Override public void dispose() { } @Override public Menu getMenu(Control parent) { MenuManager menuManager = new MenuManager(); menuManager.add(new ShowFiltersAction()); menuManager.add(new Separator()); menuManager.add(new VirtualKeyEditAction(true)); menuManager.add(new VirtualKeyEditAction(false)); menuManager.add(new DictionaryEditAction()); menuManager.add(new Separator()); menuManager.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_TOGGLE_MODE, CommandContributionItem.STYLE_CHECK)); menuManager.add(ActionUtils.makeCommandContribution(site, ResultSetCommandHandler.CMD_TOGGLE_PREVIEW, CommandContributionItem.STYLE_CHECK)); menuManager.add(new Separator()); menuManager.add(new Action("Preferences") { @Override public void run() { UIUtils.showPreferencesFor( getControl().getShell(), ResultSetViewer.this, PrefPageDatabaseGeneral.PAGE_ID); } }); return menuManager.createContextMenu(parent); } @Nullable @Override public Menu getMenu(Menu parent) { return null; } } private class ShowFiltersAction extends Action { public ShowFiltersAction() { super(CoreMessages.controls_resultset_viewer_action_order_filter, DBIcon.FILTER.getImageDescriptor()); } @Override public void run() { new ResultSetFilterDialog(ResultSetViewer.this).open(); } } private class ToggleServerSideOrderingAction extends Action { public ToggleServerSideOrderingAction() { super(CoreMessages.pref_page_database_resultsets_label_server_side_order); } @Override public int getStyle() { return AS_CHECK_BOX; } @Override public boolean isChecked() { return getPreferenceStore().getBoolean(DBeaverPreferences.RESULT_SET_ORDER_SERVER_SIDE); } @Override public void run() { IPreferenceStore preferenceStore = getPreferenceStore(); preferenceStore.setValue( DBeaverPreferences.RESULT_SET_ORDER_SERVER_SIDE, !preferenceStore.getBoolean(DBeaverPreferences.RESULT_SET_ORDER_SERVER_SIDE)); } } private enum FilterByColumnType { VALUE(DBIcon.FILTER_VALUE.getImageDescriptor()) { @Override String getValue(ResultSetViewer viewer, DBDAttributeBinding column, boolean useDefault, DBDDisplayFormat format) { GridCell focusCell = viewer.getSpreadsheet().getFocusCell(); return focusCell == null ? "" : viewer.getSpreadsheet().getContentProvider().getCellText(focusCell); } }, INPUT(DBIcon.FILTER_INPUT.getImageDescriptor()) { @Override String getValue(ResultSetViewer viewer, DBDAttributeBinding column, boolean useDefault, DBDDisplayFormat format) { if (useDefault) { return ".."; } else { return EditTextDialog.editText( viewer.getControl().getShell(), "Enter value", ""); } } }, CLIPBOARD(DBIcon.FILTER_CLIPBOARD.getImageDescriptor()) { @Override String getValue(ResultSetViewer viewer, DBDAttributeBinding column, boolean useDefault, DBDDisplayFormat format) { try { return column.getValueHandler().getValueDisplayString( column.getMetaAttribute(), viewer.getColumnValueFromClipboard(column), format); } catch (DBCException e) { log.debug("Error copying from clipboard", e); return null; } } }, NONE(DBIcon.FILTER_VALUE.getImageDescriptor()) { @Override String getValue(ResultSetViewer viewer, DBDAttributeBinding column, boolean useDefault, DBDDisplayFormat format) { return ""; } }; final ImageDescriptor icon; private FilterByColumnType(ImageDescriptor icon) { this.icon = icon; } @Nullable abstract String getValue(ResultSetViewer viewer, DBDAttributeBinding column, boolean useDefault, DBDDisplayFormat format); } private String translateFilterPattern(String pattern, FilterByColumnType type, DBDAttributeBinding column) { String value = CommonUtils.truncateString( CommonUtils.toString( type.getValue(this, column, true, DBDDisplayFormat.UI)), 30); return pattern.replace("?", value); } private class FilterByColumnAction extends Action { private final String pattern; private final FilterByColumnType type; private final DBDAttributeBinding column; public FilterByColumnAction(String pattern, FilterByColumnType type, DBDAttributeBinding column) { super(column.getAttributeName() + " " + translateFilterPattern(pattern, type, column), type.icon); this.pattern = pattern; this.type = type; this.column = column; } @Override public void run() { String value = type.getValue(ResultSetViewer.this, column, false, DBDDisplayFormat.NATIVE); if (value == null) { return; } String stringValue = pattern.replace("?", value); DBDDataFilter filter = model.getDataFilter(); filter.getConstraint(column).setCriteria(stringValue); updateFiltersText(); refresh(); } } private class FilterResetColumnAction extends Action { private final DBDAttributeBinding column; public FilterResetColumnAction(DBDAttributeBinding column) { super("Remove filter for '" + column.getAttributeName() + "'", DBIcon.REVERT.getImageDescriptor()); this.column = column; } @Override public void run() { model.getDataFilter().getConstraint(column).setCriteria(null); updateFiltersText(); refresh(); } } private class VirtualKeyEditAction extends Action { private boolean define; public VirtualKeyEditAction(boolean define) { super(define ? "Define virtual unique key" : "Clear virtual unique key"); this.define = define; } @Override public boolean isEnabled() { DBCEntityIdentifier identifier = getVirtualEntityIdentifier(); return identifier != null && (define || !CommonUtils.isEmpty(identifier.getAttributes())); } @Override public void run() { DBeaverUI.runUIJob("Edit virtual key", new DBRRunnableWithProgress() { @Override public void run(DBRProgressMonitor monitor) throws InvocationTargetException, InterruptedException { try { if (define) { editEntityIdentifier(monitor); } else { clearEntityIdentifier(monitor); } } catch (DBException e) { throw new InvocationTargetException(e); } } }); } } private class DictionaryEditAction extends Action { public DictionaryEditAction() { super("Define dictionary"); } @Override public void run() { } @Override public boolean isEnabled() { return false; } } private class ResultSetSelectionImpl implements ResultSetSelection { @Nullable @Override public GridPos getFirstElement() { Collection<GridPos> ssSelection = spreadsheet.getSelection(); if (ssSelection.isEmpty()) { return null; } return ssSelection.iterator().next(); } @Override public Iterator iterator() { return spreadsheet.getSelection().iterator(); } @Override public int size() { return spreadsheet.getSelection().size(); } @Override public Object[] toArray() { return spreadsheet.getSelection().toArray(); } @Override public List toList() { return new ArrayList<GridPos>(spreadsheet.getSelection()); } @Override public boolean isEmpty() { return spreadsheet.getSelection().isEmpty(); } @Override public ResultSetViewer getResultSetViewer() { return ResultSetViewer.this; } @Override public Collection<RowData> getSelectedRows() { List<RowData> rows = new ArrayList<RowData>(); if (gridMode == GridMode.RECORD) { if (curRowNum < 0 || curRowNum >= model.getRowCount()) { return Collections.emptyList(); } rows.add(model.getRow(curRowNum)); } else { Collection<Integer> rowSelection = spreadsheet.getRowSelection(); for (Integer row : rowSelection) { rows.add(model.getRow(row)); } } return rows; } @Override public boolean equals(Object obj) { return obj instanceof ResultSetSelectionImpl && super.equals(obj); } } }
package com.opengamma.integration.regression; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.Collections; import java.util.List; import java.util.Map; import org.fudgemsg.FudgeContext; import org.fudgemsg.FudgeMsg; import org.fudgemsg.mapping.FudgeDeserializer; import org.fudgemsg.wire.FudgeMsgReader; import org.fudgemsg.wire.xml.FudgeXMLStreamReader; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.opengamma.OpenGammaRuntimeException; import com.opengamma.core.config.impl.ConfigItem; import com.opengamma.core.marketdatasnapshot.impl.ManageableMarketDataSnapshot; import com.opengamma.engine.view.ViewCalculationConfiguration; import com.opengamma.engine.view.ViewDefinition; import com.opengamma.id.ObjectId; import com.opengamma.id.UniqueId; import com.opengamma.integration.server.RemoteServer; import com.opengamma.master.config.ConfigDocument; import com.opengamma.master.config.ConfigMaster; import com.opengamma.master.exchange.ExchangeDocument; import com.opengamma.master.exchange.ExchangeMaster; import com.opengamma.master.exchange.ManageableExchange; import com.opengamma.master.historicaltimeseries.HistoricalTimeSeriesInfoDocument; import com.opengamma.master.historicaltimeseries.HistoricalTimeSeriesMaster; import com.opengamma.master.historicaltimeseries.ManageableHistoricalTimeSeries; import com.opengamma.master.historicaltimeseries.ManageableHistoricalTimeSeriesInfo; import com.opengamma.master.holiday.HolidayDocument; import com.opengamma.master.holiday.HolidayMaster; import com.opengamma.master.holiday.ManageableHoliday; import com.opengamma.master.marketdatasnapshot.MarketDataSnapshotDocument; import com.opengamma.master.marketdatasnapshot.MarketDataSnapshotMaster; import com.opengamma.master.orgs.ManageableOrganization; import com.opengamma.master.orgs.OrganizationDocument; import com.opengamma.master.orgs.OrganizationMaster; import com.opengamma.master.portfolio.ManageablePortfolio; import com.opengamma.master.portfolio.ManageablePortfolioNode; import com.opengamma.master.portfolio.PortfolioDocument; import com.opengamma.master.portfolio.PortfolioMaster; import com.opengamma.master.position.ManageablePosition; import com.opengamma.master.position.ManageableTrade; import com.opengamma.master.position.PositionDocument; import com.opengamma.master.position.PositionMaster; import com.opengamma.master.security.ManageableSecurity; import com.opengamma.master.security.SecurityDocument; import com.opengamma.master.security.SecurityMaster; import com.opengamma.util.ArgumentChecker; import com.opengamma.util.fudgemsg.OpenGammaFudgeContext; /** * Loads the data required to run views from Fudge XML files into an empty database. * TODO split this up to allow a subset of data to be dumped and restored? */ /* package */ class DatabaseRestore { /** Attribute name holding a position's original unique ID from the source database. */ public static final String REGRESSION_ID = "regressionId"; private static final Logger s_logger = LoggerFactory.getLogger(DatabaseRestore.class); private final File _dataDir; private final SecurityMaster _securityMaster; private final PositionMaster _positionMaster; private final PortfolioMaster _portfolioMaster; private final ConfigMaster _configMaster; private final HistoricalTimeSeriesMaster _timeSeriesMaster; private final HolidayMaster _holidayMaster; private final ExchangeMaster _exchangeMaster; private final MarketDataSnapshotMaster _snapshotMaster; private final OrganizationMaster _organizationMaster; private final FudgeContext _ctx = new FudgeContext(OpenGammaFudgeContext.getInstance()); private final FudgeDeserializer _deserializer = new FudgeDeserializer(OpenGammaFudgeContext.getInstance()); public DatabaseRestore(String dataDir, SecurityMaster securityMaster, PositionMaster positionMaster, PortfolioMaster portfolioMaster, ConfigMaster configMaster, HistoricalTimeSeriesMaster timeSeriesMaster, HolidayMaster holidayMaster, ExchangeMaster exchangeMaster, MarketDataSnapshotMaster snapshotMaster, OrganizationMaster organizationMaster) { ArgumentChecker.notEmpty(dataDir, "dataDir"); ArgumentChecker.notNull(securityMaster, "securityMaster"); ArgumentChecker.notNull(positionMaster, "positionMaster"); ArgumentChecker.notNull(portfolioMaster, "portfolioMaster"); ArgumentChecker.notNull(configMaster, "configMaster"); ArgumentChecker.notNull(timeSeriesMaster, "timeSeriesMaster"); ArgumentChecker.notNull(holidayMaster, "holidayMaster"); ArgumentChecker.notNull(exchangeMaster, "exchangeMaster"); ArgumentChecker.notNull(snapshotMaster, "snapshotMaster"); ArgumentChecker.notNull(organizationMaster, "organizationMaster"); _securityMaster = securityMaster; _positionMaster = positionMaster; _portfolioMaster = portfolioMaster; _configMaster = configMaster; _timeSeriesMaster = timeSeriesMaster; _holidayMaster = holidayMaster; _exchangeMaster = exchangeMaster; _snapshotMaster = snapshotMaster; _organizationMaster = organizationMaster; _dataDir = new File(dataDir); // TODO check data dir is an existing directory } public static void main(String[] args) throws IOException { if (args.length < 2) { System.err.println("arguments: dataDirectory serverUrl"); System.exit(1); } String dataDir = args[0]; String serverUrl = args[1]; try (RemoteServer server = RemoteServer.create(serverUrl)) { DatabaseRestore databaseRestore = new DatabaseRestore(dataDir, server.getSecurityMaster(), server.getPositionMaster(), server.getPortfolioMaster(), server.getConfigMaster(), server.getHistoricalTimeSeriesMaster(), server.getHolidayMaster(), server.getExchangeMaster(), server.getMarketDataSnapshotMaster(), server.getOrganizationMaster()); databaseRestore.restoreDatabase(); } } public void restoreDatabase() { try { File idMappingsFile = new File(_dataDir, RegressionUtils.ID_MAPPINGS_FILE); if (idMappingsFile.exists()) { IdMappings idMappings = (IdMappings) readFromFudge(idMappingsFile); ConfigItem<IdMappings> mappingsItem = RegressionUtils.loadIdMappings(_configMaster); if (mappingsItem == null) { _configMaster.add(new ConfigDocument(ConfigItem.of(idMappings, RegressionUtils.ID_MAPPINGS))); } else { ConfigItem<IdMappings> configItem = ConfigItem.of(idMappings, RegressionUtils.ID_MAPPINGS); configItem.setUniqueId(mappingsItem.getUniqueId()); _configMaster.update(new ConfigDocument(configItem)); } } Map<ObjectId, ObjectId> securityIdMappings = loadSecurities(); Map<ObjectId, ObjectId> positionIdMappings = loadPositions(securityIdMappings); Map<ObjectId, ObjectId> portfolioIdMappings = loadPortfolios(positionIdMappings); loadConfigs(portfolioIdMappings); loadTimeSeries(); loadHolidays(); loadExchanges(); loadSnapshots(); loadOrganizations(); s_logger.info("Successfully restored database"); } catch (IOException e) { throw new OpenGammaRuntimeException("Failed to restore database", e); } } private Map<ObjectId, ObjectId> loadSecurities() throws IOException { List<?> securities = readFromDirectory("securities"); Map<ObjectId, ObjectId> ids = Maps.newHashMapWithExpectedSize(securities.size()); for (Object o : securities) { ManageableSecurity security = (ManageableSecurity) o; ObjectId oldId = security.getUniqueId().getObjectId(); security.setUniqueId(null); SecurityDocument doc = _securityMaster.add(new SecurityDocument(security)); ids.put(oldId, doc.getUniqueId().getObjectId()); } return ids; } private Map<ObjectId, ObjectId> loadPositions(Map<ObjectId, ObjectId> securityIdMappings) throws IOException { List<?> positions = readFromDirectory("positions"); Map<ObjectId, ObjectId> ids = Maps.newHashMapWithExpectedSize(positions.size()); for (Object o : positions) { ManageablePosition position = (ManageablePosition) o; ObjectId oldId = position.getUniqueId().getObjectId(); position.setUniqueId(null); ObjectId securityObjectId = position.getSecurityLink().getObjectId(); if (securityObjectId != null) { ObjectId newObjectId = securityIdMappings.get(securityObjectId); position.getSecurityLink().setObjectId(newObjectId); if (newObjectId == null) { s_logger.warn("No security found with ID {} for position {}", securityObjectId, position); } } for (ManageableTrade trade : position.getTrades()) { trade.addAttribute(REGRESSION_ID, trade.getUniqueId().getObjectId().toString()); trade.setUniqueId(null); trade.setParentPositionId(null); } // put the old ID on as an attribute. this allows different instances of a position or trade to be identified // when they're saved in different databases and therefore have different unique IDs position.addAttribute(REGRESSION_ID, oldId.toString()); PositionDocument doc = _positionMaster.add(new PositionDocument(position)); ObjectId newId = doc.getUniqueId().getObjectId(); ids.put(oldId, newId); } return ids; } private Map<ObjectId, ObjectId> loadPortfolios(Map<ObjectId, ObjectId> positionIdMappings) throws IOException { List<?> portfolios = readFromDirectory("portfolios"); Map<ObjectId, ObjectId> idMappings = Maps.newHashMapWithExpectedSize(portfolios.size()); for (Object o : portfolios) { ManageablePortfolio portfolio = (ManageablePortfolio) o; UniqueId oldId = portfolio.getUniqueId(); portfolio.setUniqueId(null); replacePositionIds(portfolio.getRootNode(), positionIdMappings); UniqueId newId = _portfolioMaster.add(new PortfolioDocument(portfolio)).getUniqueId(); s_logger.debug("Saved portfolio {} with ID {}, old ID {}", portfolio.getName(), newId, oldId); idMappings.put(oldId.getObjectId(), newId.getObjectId()); } return idMappings; } private void loadConfigs(Map<ObjectId, ObjectId> portfolioIdMappings) throws IOException { List<?> configs = readFromDirectory("configs"); List<ViewDefinition> viewDefs = Lists.newArrayList(); // view definitions refer to other config items by unique ID Map<ObjectId, ObjectId> idMappings = Maps.newHashMap(); for (Object o : configs) { ConfigItem<?> config = (ConfigItem<?>) o; Object configValue = config.getValue(); if (configValue instanceof ViewDefinition) { viewDefs.add((ViewDefinition) configValue); } else { UniqueId oldId = config.getUniqueId(); config.setUniqueId(null); UniqueId newId = _configMaster.add(new ConfigDocument(config)).getUniqueId(); s_logger.debug("Saved config of type {} with ID {}", configValue.getClass().getSimpleName(), newId); idMappings.put(oldId.getObjectId(), newId.getObjectId()); } } // TODO maybe this should be pluggable to handle new config types that need post processing for (ViewDefinition viewDef : viewDefs) { ObjectId oldPortfolioId = viewDef.getPortfolioId().getObjectId(); UniqueId newPortfolioId; if (oldPortfolioId != null) { if (portfolioIdMappings.containsKey(oldPortfolioId)) { newPortfolioId = portfolioIdMappings.get(oldPortfolioId).atLatestVersion(); } else { newPortfolioId = null; s_logger.warn("No mapping found for view def portfolio ID {}", oldPortfolioId); } } else { newPortfolioId = null; } ViewDefinition newViewDef = viewDef.copyWith(viewDef.getName(), newPortfolioId, viewDef.getMarketDataUser()); for (ViewCalculationConfiguration calcConfig : newViewDef.getAllCalculationConfigurations()) { calcConfig.setScenarioId(getNewId(calcConfig.getScenarioId(), idMappings)); calcConfig.setScenarioParametersId(getNewId(calcConfig.getScenarioParametersId(), idMappings)); } UniqueId newId = _configMaster.add(new ConfigDocument(ConfigItem.of(newViewDef))).getUniqueId(); s_logger.debug("Saved view definition with ID {}", newId); } } private static UniqueId getNewId(UniqueId oldId, Map<ObjectId, ObjectId> idMappings) { if (oldId == null) { return null; } ObjectId newObjectId = idMappings.get(oldId.getObjectId()); if (newObjectId == null) { return null; } else { return newObjectId.atLatestVersion(); } } private void loadTimeSeries() throws IOException { List<?> objects = readFromDirectory("timeseries"); for (Object o : objects) { TimeSeriesWithInfo timeSeriesWithInfo = (TimeSeriesWithInfo) o; ManageableHistoricalTimeSeriesInfo info = timeSeriesWithInfo.getInfo(); ManageableHistoricalTimeSeries timeSeries = timeSeriesWithInfo.getTimeSeries(); info.setUniqueId(null); HistoricalTimeSeriesMaster timeSeriesMaster = _timeSeriesMaster; HistoricalTimeSeriesInfoDocument infoDoc = timeSeriesMaster.add(new HistoricalTimeSeriesInfoDocument(info)); timeSeriesMaster.updateTimeSeriesDataPoints(infoDoc.getInfo().getTimeSeriesObjectId(), timeSeries.getTimeSeries()); } } private void loadHolidays() throws IOException { List<?> holidays = readFromDirectory("holidays"); for (Object o : holidays) { ManageableHoliday holiday = (ManageableHoliday) o; holiday.setUniqueId(null); _holidayMaster.add(new HolidayDocument(holiday)); } } private void loadExchanges() throws IOException { List<?> exchanges = readFromDirectory("exchanges"); for (Object o : exchanges) { ManageableExchange exchange = (ManageableExchange) o; exchange.setUniqueId(null); _exchangeMaster.add(new ExchangeDocument(exchange)); } } private void loadSnapshots() throws IOException { List<?> snapshots = readFromDirectory("snapshots"); for (Object o : snapshots) { ManageableMarketDataSnapshot snapshot = (ManageableMarketDataSnapshot) o; snapshot.setUniqueId(null); _snapshotMaster.add(new MarketDataSnapshotDocument(snapshot)); } } private void loadOrganizations() throws IOException { List<?> organizations = readFromDirectory("organizations"); for (Object o : organizations) { ManageableOrganization organization = (ManageableOrganization) o; organization.setUniqueId(null); _organizationMaster.add(new OrganizationDocument(organization)); } } private void replacePositionIds(ManageablePortfolioNode node, Map<ObjectId, ObjectId> positionIdMappings) { node.setUniqueId(null); node.setParentNodeId(null); node.setPortfolioId(null); List<ObjectId> oldPositionIds = node.getPositionIds(); List<ObjectId> positionsIds = Lists.newArrayListWithCapacity(oldPositionIds.size()); for (ObjectId oldPositionId : oldPositionIds) { ObjectId newPositionId = positionIdMappings.get(oldPositionId); if (newPositionId != null) { positionsIds.add(newPositionId); } else { s_logger.warn("No position ID mapping for {}", oldPositionId); } } node.setPositionIds(positionsIds); for (ManageablePortfolioNode childNode : node.getChildNodes()) { replacePositionIds(childNode, positionIdMappings); } } private List<?> readFromDirectory(String subDirName) throws IOException { File subDir = new File(_dataDir, subDirName); if (!subDir.exists()) { s_logger.info("Directory {} doesn't exist", subDir); return Collections.emptyList(); } s_logger.info("Reading from {}", subDir.getAbsolutePath()); List<Object> objects = Lists.newArrayList(); File[] files = subDir.listFiles(); if (files == null) { throw new OpenGammaRuntimeException("No files found in " + subDir); } for (File file : files) { objects.add(readFromFudge(file)); } s_logger.info("Read {} objects from {}", objects.size(), subDir.getAbsolutePath()); return objects; } private Object readFromFudge(File file) throws IOException { Object object; try (BufferedReader reader = new BufferedReader(new FileReader(file))) { FudgeXMLStreamReader streamReader = new FudgeXMLStreamReader(_ctx, reader); FudgeMsgReader fudgeMsgReader = new FudgeMsgReader(streamReader); FudgeMsg msg = fudgeMsgReader.nextMessage(); object = _deserializer.fudgeMsgToObject(msg); s_logger.debug("Read object {}", object); } return object; } }
package querqy.rewrite.commonrules.model; import org.junit.Test; import querqy.model.EmptySearchEngineRequestAdapter; import querqy.model.ExpandedQuery; import querqy.model.Query; import querqy.rewrite.commonrules.AbstractCommonRulesTest; import querqy.rewrite.commonrules.CommonRulesRewriter; import static org.hamcrest.MatcherAssert.assertThat; import static querqy.QuerqyMatchers.bq; import static querqy.QuerqyMatchers.dmq; import static querqy.QuerqyMatchers.must; import static querqy.QuerqyMatchers.term; import static querqy.rewrite.commonrules.select.SelectionStrategyFactory.DEFAULT_SELECTION_STRATEGY; public class SynonymAndDeleteInteractionTest extends AbstractCommonRulesTest { @Test public void testSynonymBeforeDelete() { RulesCollectionBuilder builder = new TrieMapRulesCollectionBuilder(false); addRule(builder, input("a"), synonym("c") ); addRule(builder, input("a", "b"), delete("a") ); CommonRulesRewriter rewriter = new CommonRulesRewriter(builder.build(), DEFAULT_SELECTION_STRATEGY); ExpandedQuery query = makeQuery("a b"); Query rewritten = (Query) rewriter.rewrite(query, new EmptySearchEngineRequestAdapter()).getUserQuery(); assertThat(rewritten, bq( dmq( term("c", true) ), dmq( term("b", false) ) )); } @Test public void testSynonymAfterDelete() { RulesCollectionBuilder builder = new TrieMapRulesCollectionBuilder(false); addRule(builder, input("a", "b"), delete("a") ); addRule(builder, input("a"), synonym("c") ); CommonRulesRewriter rewriter = new CommonRulesRewriter(builder.build(), DEFAULT_SELECTION_STRATEGY); ExpandedQuery query = makeQuery("a b"); Query rewritten = (Query) rewriter.rewrite(query, new EmptySearchEngineRequestAdapter()).getUserQuery(); assertThat(rewritten, bq( dmq( term("b", false) ) )); } @Test public void testExpandBySynonymAndDeleteBothInputTermsBySeparateInstructions() { RulesCollectionBuilder builder = new TrieMapRulesCollectionBuilder(false); addRule(builder, input("a", "b"), synonym("s1"), delete("a"), delete("b") ); CommonRulesRewriter rewriter = new CommonRulesRewriter(builder.build(), DEFAULT_SELECTION_STRATEGY); ExpandedQuery query = makeQuery("a b"); Query rewritten = (Query) rewriter.rewrite(query, new EmptySearchEngineRequestAdapter()).getUserQuery(); assertThat(rewritten, bq( dmq( term("s1", true) ), dmq( term("s1", true) ) )); } @Test public void testExpandBySynonymAndDeleteBothInputTermsBySingleInstruction() { RulesCollectionBuilder builder = new TrieMapRulesCollectionBuilder(false); addRule(builder, input("a", "b"), synonym("s1"), delete("a", "b") ); CommonRulesRewriter rewriter = new CommonRulesRewriter(builder.build(), DEFAULT_SELECTION_STRATEGY); ExpandedQuery query = makeQuery("a b"); Query rewritten = (Query) rewriter.rewrite(query, new EmptySearchEngineRequestAdapter()).getUserQuery(); assertThat(rewritten, bq( dmq( term("a", false), term("s1", true) ), dmq( term("b", false), term("s1", true) ) )); } @Test public void testExpandBySynonymAndDeleteTwoOfThreeInputTermsBySingleInstruction() { RulesCollectionBuilder builder = new TrieMapRulesCollectionBuilder(false); addRule(builder, input("a", "b", "c"), synonym("s1"), delete("a", "b") ); CommonRulesRewriter rewriter = new CommonRulesRewriter(builder.build(), DEFAULT_SELECTION_STRATEGY); ExpandedQuery query = makeQuery("a b c"); Query rewritten = (Query) rewriter.rewrite(query, new EmptySearchEngineRequestAdapter()).getUserQuery(); assertThat(rewritten, bq( dmq( term("s1", true) ), dmq( term("s1", true) ), dmq( term("c", false), term("s1", true) ) )); } @Test public void testSynonymsForTermsToBeDeleted() { RulesCollectionBuilder builder = new TrieMapRulesCollectionBuilder(false); addRule(builder, input("a", "b"), synonym("s1"), delete("a"), delete("b") ); addRule(builder, input("a"), synonym("s2") ); addRule(builder, input("b"), synonym("s3") ); CommonRulesRewriter rewriter = new CommonRulesRewriter(builder.build(), DEFAULT_SELECTION_STRATEGY); ExpandedQuery query = makeQuery("a b"); Query rewritten = (Query) rewriter.rewrite(query, new EmptySearchEngineRequestAdapter()).getUserQuery(); assertThat(rewritten, bq( dmq( term("s1", true), term("s2", true) ), dmq( term("s1", true), term("s3", true) ) )); } @Test public void testExpandQueryByTwoSynonymTermsAndDeleteBothInputTerms() { RulesCollectionBuilder builder = new TrieMapRulesCollectionBuilder(false); addRule(builder, input("a", "b"), synonym("s1_1", "s1_2"), delete("a"), delete("b") ); CommonRulesRewriter rewriter = new CommonRulesRewriter(builder.build(), DEFAULT_SELECTION_STRATEGY); ExpandedQuery query = makeQuery("a b"); Query rewritten = (Query) rewriter.rewrite(query, new EmptySearchEngineRequestAdapter()).getUserQuery(); assertThat(rewritten, bq( dmq( bq( dmq(must(), term("s1_1", true)), dmq(must(), term("s1_2", true)) ) ), dmq( bq( dmq(must(), term("s1_1", true)), dmq(must(), term("s1_2", true)) ) ) )); } }
package info.bitrich.xchangestream.service.netty; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import io.netty.util.concurrent.Future; import io.reactivex.CompletableEmitter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import info.bitrich.xchangestream.service.exception.NotConnectedException; import io.netty.bootstrap.Bootstrap; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.ChannelPipeline; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.handler.codec.http.DefaultHttpHeaders; import io.netty.handler.codec.http.HttpClientCodec; import io.netty.handler.codec.http.HttpObjectAggregator; import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame; import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; import io.netty.handler.codec.http.websocketx.WebSocketClientHandshaker; import io.netty.handler.codec.http.websocketx.WebSocketClientHandshakerFactory; import io.netty.handler.codec.http.websocketx.WebSocketFrame; import io.netty.handler.codec.http.websocketx.WebSocketVersion; import io.netty.handler.codec.http.websocketx.extensions.WebSocketClientExtensionHandler; import io.netty.handler.codec.http.websocketx.extensions.compression.WebSocketClientCompressionHandler; import io.netty.handler.ssl.SslContext; import io.netty.handler.ssl.SslContextBuilder; import io.reactivex.Completable; import io.reactivex.Observable; import io.reactivex.ObservableEmitter; public abstract class NettyStreamingService<T> { private final Logger LOG = LoggerFactory.getLogger(this.getClass()); private static final Duration DEFAULT_CONNECTION_TIMEOUT = Duration.ofSeconds(10); private static final Duration DEFAULT_RETRY_DURATION = Duration.ofSeconds(15); private class Subscription { final ObservableEmitter<T> emitter; final String channelName; final Object[] args; public Subscription(ObservableEmitter<T> emitter, String channelName, Object[] args) { this.emitter = emitter; this.channelName = channelName; this.args = args; } } protected final int maxFramePayloadLength; protected final URI uri; private boolean isManualDisconnect = false; protected Channel webSocketChannel; private Duration retryDuration; protected Duration connectionTimeout; protected final NioEventLoopGroup eventLoopGroup; protected Map<String, Subscription> channels = new ConcurrentHashMap<>(); public NettyStreamingService(String apiUrl) { this(apiUrl, 65536); } public NettyStreamingService(String apiUrl, int maxFramePayloadLength) { this(apiUrl, maxFramePayloadLength, DEFAULT_CONNECTION_TIMEOUT, DEFAULT_RETRY_DURATION); } public NettyStreamingService(String apiUrl, int maxFramePayloadLength, Duration connectionTimeout, Duration retryDuration) { try { this.maxFramePayloadLength = maxFramePayloadLength; this.retryDuration = retryDuration; this.connectionTimeout = connectionTimeout; this.uri = new URI(apiUrl); this.eventLoopGroup = new NioEventLoopGroup(2); } catch (URISyntaxException e) { throw new IllegalArgumentException("Error parsing URI " + apiUrl, e); } } public Completable connect() { return Completable.create(completable -> { try { LOG.info("Connecting to {}://{}:{}{}", uri.getScheme(), uri.getHost(), uri.getPort(), uri.getPath()); String scheme = uri.getScheme() == null ? "ws" : uri.getScheme(); String host = uri.getHost(); if (host == null) { throw new IllegalArgumentException("Host cannot be null."); } final int port; if (uri.getPort() == -1) { if ("ws".equalsIgnoreCase(scheme)) { port = 80; } else if ("wss".equalsIgnoreCase(scheme)) { port = 443; } else { port = -1; } } else { port = uri.getPort(); } if (!"ws".equalsIgnoreCase(scheme) && !"wss".equalsIgnoreCase(scheme)) { throw new IllegalArgumentException("Only WS(S) is supported."); } final boolean ssl = "wss".equalsIgnoreCase(scheme); final SslContext sslCtx; if (ssl) { sslCtx = SslContextBuilder.forClient().build(); } else { sslCtx = null; } final WebSocketClientHandler handler = getWebSocketClientHandler( WebSocketClientHandshakerFactory.newHandshaker(uri, WebSocketVersion.V13, null, true, new DefaultHttpHeaders(), maxFramePayloadLength), this::messageHandler); Bootstrap b = new Bootstrap(); b.group(eventLoopGroup) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, java.lang.Math.toIntExact(connectionTimeout.toMillis())) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) { ChannelPipeline p = ch.pipeline(); if (sslCtx != null) { p.addLast(sslCtx.newHandler(ch.alloc(), host, port)); } WebSocketClientExtensionHandler clientExtensionHandler = getWebSocketClientExtensionHandler(); List<ChannelHandler> handlers = new ArrayList<>(4); handlers.add(new HttpClientCodec()); handlers.add(new HttpObjectAggregator(8192)); if (clientExtensionHandler != null) { handlers.add(clientExtensionHandler); } handlers.add(handler); p.addLast(handlers.toArray(new ChannelHandler[handlers.size()])); } }); b.connect(uri.getHost(), port).addListener((ChannelFuture future) -> { webSocketChannel = future.channel(); if (future.isSuccess()) { handler.handshakeFuture().addListener(f -> { if (f.isSuccess()) { completable.onComplete(); } else { handleError(completable, f.cause()); } }); } else { handleError(completable, future.cause()); } }); } catch (Exception throwable) { handleError(completable, throwable); } }); } protected void handleError(CompletableEmitter completable, Throwable t) { isManualDisconnect = true; ChannelFuture disconnect = webSocketChannel.disconnect(); disconnect.addListener(f -> { if(f.isSuccess()) { isManualDisconnect = false; } }); completable.onError(t); } public Completable disconnect() { isManualDisconnect = true; return Completable.create(completable -> { if (webSocketChannel.isOpen()) { CloseWebSocketFrame closeFrame = new CloseWebSocketFrame(); webSocketChannel.writeAndFlush(closeFrame).addListener(future -> { channels = new ConcurrentHashMap<>(); completable.onComplete(); }); } }); } protected abstract String getChannelNameFromMessage(T message) throws IOException; public abstract String getSubscribeMessage(String channelName, Object... args) throws IOException; public abstract String getUnsubscribeMessage(String channelName) throws IOException; public String getSubscriptionUniqueId(String channelName, Object... args) { return channelName; } /** * Handler that receives incoming messages. * * @param message Content of the message from the server. */ public abstract void messageHandler(String message); public void sendMessage(String message) { LOG.debug("Sending message: {}", message); if (webSocketChannel == null || !webSocketChannel.isOpen()) { LOG.warn("WebSocket is not open! Call connect first."); return; } if (!webSocketChannel.isWritable()) { LOG.warn("Cannot send data to WebSocket as it is not writable."); return; } if (message != null) { WebSocketFrame frame = new TextWebSocketFrame(message); webSocketChannel.writeAndFlush(frame); } } public Observable<T> subscribeChannel(String channelName, Object... args) { final String channelId = getSubscriptionUniqueId(channelName, args); LOG.info("Subscribing to channel {}", channelId); return Observable.<T> create(e -> { if (webSocketChannel == null || !webSocketChannel.isOpen()) { e.onError(new NotConnectedException()); } if (!channels.containsKey(channelId)) { Subscription newSubscription = new Subscription(e, channelName, args); channels.put(channelId, newSubscription); try { sendMessage(getSubscribeMessage(channelName, args)); } catch (IOException throwable) { e.onError(throwable); } } }).doOnDispose(() -> { if (channels.containsKey(channelId)) { sendMessage(getUnsubscribeMessage(channelId)); channels.remove(channelId); } }).share(); } public void resubscribeChannels() { for (String channelId : channels.keySet()) { try { Subscription subscription = channels.get(channelId); sendMessage(getSubscribeMessage(subscription.channelName, subscription.args)); } catch (IOException e) { LOG.error("Failed to reconnect channel: {}", channelId); } } } protected String getChannel(T message) { String channel; try { channel = getChannelNameFromMessage(message); } catch (IOException e) { LOG.error("Cannot parse channel from message: {}", message); return ""; } return channel; } protected void handleMessage(T message) { String channel = getChannel(message); handleChannelMessage(channel, message); } protected void handleError(T message, Throwable t) { String channel = getChannel(message); handleChannelError(channel, t); } protected void handleChannelMessage(String channel, T message) { ObservableEmitter<T> emitter = channels.get(channel).emitter; if (emitter == null) { LOG.debug("No subscriber for channel {}.", channel); return; } emitter.onNext(message); } protected void handleChannelError(String channel, Throwable t) { ObservableEmitter<T> emitter = channels.get(channel).emitter; if (emitter == null) { LOG.debug("No subscriber for channel {}.", channel); return; } emitter.onError(t); } protected WebSocketClientExtensionHandler getWebSocketClientExtensionHandler() { return WebSocketClientCompressionHandler.INSTANCE; } protected WebSocketClientHandler getWebSocketClientHandler(WebSocketClientHandshaker handshaker, WebSocketClientHandler.WebSocketMessageHandler handler) { return new NettyWebSocketClientHandler(handshaker, handler); } protected class NettyWebSocketClientHandler extends WebSocketClientHandler { protected NettyWebSocketClientHandler(WebSocketClientHandshaker handshaker, WebSocketMessageHandler handler) { super(handshaker, handler); } @Override public void channelInactive(ChannelHandlerContext ctx) { if (isManualDisconnect) { isManualDisconnect = false; } else { super.channelInactive(ctx); LOG.info("Reopening websocket because it was closed by the host"); final Completable c = connect().doOnError(t -> LOG.warn("Problem with reconnect", t)).retryWhen(new RetryWithDelay(retryDuration.toMillis())).doOnComplete(() -> { LOG.info("Resubscribing channels"); resubscribeChannels(); }); c.subscribe(); } } } public boolean isSocketOpen() { return webSocketChannel.isOpen(); } }
package com.intellij.openapi.roots.ui.configuration.projectRoot; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectBundle; import com.intellij.openapi.projectRoots.ProjectJdk; import com.intellij.openapi.roots.*; import com.intellij.openapi.roots.impl.libraries.LibraryEx; import com.intellij.openapi.roots.impl.libraries.LibraryImpl; import com.intellij.openapi.roots.libraries.Library; import com.intellij.openapi.roots.libraries.LibraryTable; import com.intellij.openapi.roots.libraries.LibraryTablePresentation; import com.intellij.openapi.roots.libraries.LibraryTablesRegistrar; import com.intellij.openapi.roots.ui.configuration.LibraryTableModifiableModelProvider; import com.intellij.openapi.roots.ui.configuration.ModuleEditor; import com.intellij.openapi.roots.ui.configuration.ModulesConfigurator; import com.intellij.openapi.ui.MasterDetailsComponent; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.Condition; import com.intellij.util.Alarm; import com.intellij.util.NotNullFunction; import com.intellij.util.containers.ContainerUtil; import gnu.trove.THashMap; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.util.*; public class StructureConfigrableContext implements Disposable { private static final Logger LOG = Logger.getInstance("#" + StructureConfigrableContext.class.getName()); @NonNls public static final String DELETED_LIBRARIES = "lib"; public static final String NO_JDK = ProjectBundle.message("project.roots.module.jdk.problem.message"); public final Map<Library, Set<String>> myLibraryDependencyCache = new HashMap<Library, Set<String>>(); public final Map<ProjectJdk, Set<String>> myJdkDependencyCache = new HashMap<ProjectJdk, Set<String>>(); public final Map<Module, Map<String, Set<String>>> myValidityCache = new HashMap<Module, Map<String, Set<String>>>(); public final Map<Library, Boolean> myLibraryPathValidityCache = new HashMap<Library, Boolean>(); //can be invalidated on startup only public final Map<Module, Set<String>> myModulesDependencyCache = new HashMap<Module, Set<String>>(); private ModuleManager myModuleManager; public final ModulesConfigurator myModulesConfigurator; private boolean myDisposed; public final Alarm myUpdateDependenciesAlarm = new Alarm(Alarm.ThreadToUse.SHARED_THREAD); public final Alarm myReloadProjectAlarm = new Alarm(); public final Map<String, LibrariesModifiableModel> myLevel2Providers = new THashMap<String, LibrariesModifiableModel>(); private Project myProject; public StructureConfigrableContext(Project project, final ModuleManager moduleManager, final ModulesConfigurator modulesConfigurator) { myProject = project; myModuleManager = moduleManager; myModulesConfigurator = modulesConfigurator; } @Nullable public Set<String> getCachedDependencies(final Object selectedObject, final MasterDetailsComponent.MyNode selectedNode, boolean force) { if (selectedObject instanceof Library){ final Library library = (Library)selectedObject; if (myLibraryDependencyCache.containsKey(library)){ return myLibraryDependencyCache.get(library); } } else if (selectedObject instanceof ProjectJdk){ final ProjectJdk projectJdk = (ProjectJdk)selectedObject; if (myJdkDependencyCache.containsKey(projectJdk)){ return myJdkDependencyCache.get(projectJdk); } } else if (selectedObject instanceof Module) { final Module module = (Module)selectedObject; if (myModulesDependencyCache.containsKey(module)) { return myModulesDependencyCache.get(module); } } if (force){ LOG.assertTrue(ApplicationManager.getApplication().isDispatchThread()); final Set<String> dep = getDependencies(selectedObject, selectedNode); updateCache(selectedObject, dep); return dep; } else { myUpdateDependenciesAlarm.addRequest(new Runnable(){ public void run() { final Set<String> dep = getDependencies(selectedObject, selectedNode); SwingUtilities.invokeLater(new Runnable() { public void run() { if (!myDisposed) { updateCache(selectedObject, dep); fireOnCacheChanged(); } } }); } }, 100); return null; } } private void updateCache(final Object selectedObject, final Set<String> dep) { if (selectedObject instanceof Library) { myLibraryDependencyCache.put((Library)selectedObject, dep); } else if (selectedObject instanceof ProjectJdk) { myJdkDependencyCache.put((ProjectJdk)selectedObject, dep); } else if (selectedObject instanceof Module) { myModulesDependencyCache.put((Module)selectedObject, dep); } } private Set<String> getDependencies(final Condition<OrderEntry> condition) { final Set<String> result = new TreeSet<String>(); ApplicationManager.getApplication().runReadAction(new Runnable() { public void run() { final Module[] modules = myModulesConfigurator.getModules(); for (final Module module : modules) { final ModuleEditor moduleEditor = myModulesConfigurator.getModuleEditor(module); if (moduleEditor != null) { final OrderEntry[] entries = moduleEditor.getModifiableRootModel().getOrderEntries(); for (OrderEntry entry : entries) { if (myDisposed) return; if (condition.value(entry)) { result.add(module.getName()); break; } } } } } }); return result; } @Nullable private Set<String> getDependencies(final Object selectedObject, final MasterDetailsComponent.MyNode node) { if (selectedObject instanceof Module) { return getDependencies(new Condition<OrderEntry>() { public boolean value(final OrderEntry orderEntry) { return orderEntry instanceof ModuleOrderEntry && Comparing.equal(((ModuleOrderEntry)orderEntry).getModule(), selectedObject); } }); } else if (selectedObject instanceof Library) { if (((Library)selectedObject).getTable() == null) { //module library navigation final Set<String> set = new HashSet<String>(); set.add(((MasterDetailsComponent.MyNode)node.getParent()).getDisplayName()); return set; } return getDependencies(new Condition<OrderEntry>() { @SuppressWarnings({"SimplifiableIfStatement"}) public boolean value(final OrderEntry orderEntry) { if (orderEntry instanceof LibraryOrderEntry){ final LibraryImpl library = (LibraryImpl)((LibraryOrderEntry)orderEntry).getLibrary(); if (Comparing.equal(library, selectedObject)) return true; return library != null && Comparing.equal(library.getSource(), selectedObject); } return false; } }); } else if (selectedObject instanceof ProjectJdk) { return getDependencies(new Condition<OrderEntry>() { public boolean value(final OrderEntry orderEntry) { return orderEntry instanceof JdkOrderEntry && Comparing.equal(((JdkOrderEntry)orderEntry).getJdk(), selectedObject); } }); } return null; } public void dispose() { myJdkDependencyCache.clear(); myLibraryDependencyCache.clear(); myValidityCache.clear(); myLibraryPathValidityCache.clear(); myModulesDependencyCache.clear(); myDisposed = true; } public void invalidateModules(final Set<String> modules) { SwingUtilities.invokeLater(new Runnable() { public void run() { if (modules != null) { for (String module : modules) { myValidityCache.remove(myModuleManager.findModuleByName(module)); } } } }); } public void clearCaches(final Module module, final List<Library> chosen) { LOG.assertTrue(ApplicationManager.getApplication().isDispatchThread()); for (Library library : chosen) { myLibraryDependencyCache.remove(library); } myValidityCache.remove(module); fireOnCacheChanged(); } public void clearCaches(final Module module, final ProjectJdk oldJdk, final ProjectJdk selectedModuleJdk) { LOG.assertTrue(ApplicationManager.getApplication().isDispatchThread()); myJdkDependencyCache.remove(oldJdk); myJdkDependencyCache.remove(selectedModuleJdk); myValidityCache.remove(module); fireOnCacheChanged(); } public void clearCaches(final OrderEntry entry) { LOG.assertTrue(ApplicationManager.getApplication().isDispatchThread()); if (entry instanceof ModuleOrderEntry) { final Module module = ((ModuleOrderEntry)entry).getModule(); myValidityCache.remove(module); myModulesDependencyCache.remove(module); } else if (entry instanceof JdkOrderEntry) { invalidateModules(myJdkDependencyCache.remove(((JdkOrderEntry)entry).getJdk())); } else if (entry instanceof LibraryOrderEntry) { invalidateModules(myLibraryDependencyCache.remove(((LibraryOrderEntry)entry).getLibrary())); } fireOnCacheChanged(); } public boolean isInvalid(final Object object) { if (object instanceof Module){ final Module module = (Module)object; if (myValidityCache.containsKey(module)) return myValidityCache.get(module) != null; myUpdateDependenciesAlarm.addRequest(new Runnable(){ public void run() { ApplicationManager.getApplication().runReadAction(new Runnable() { public void run() { updateModuleValidityCache(module); } }); } }, 100); } else if (object instanceof LibraryEx) { final LibraryEx library = (LibraryEx)object; if (myLibraryPathValidityCache.containsKey(library)) return myLibraryPathValidityCache.get(library).booleanValue(); myUpdateDependenciesAlarm.addRequest(new Runnable(){ public void run() { ApplicationManager.getApplication().runReadAction(new Runnable() { public void run() { updateLibraryValidityCache(library); } }); } }, 100); } return false; } private void updateLibraryValidityCache(final LibraryEx library) { if (myLibraryPathValidityCache.containsKey(library)) return; //do not check twice final boolean valid = library.allPathsValid(OrderRootType.CLASSES) && library.allPathsValid(OrderRootType.JAVADOC) && library.allPathsValid(OrderRootType.SOURCES); SwingUtilities.invokeLater(new Runnable(){ public void run() { if (!myDisposed){ myLibraryPathValidityCache.put(library, valid ? Boolean.FALSE : Boolean.TRUE); fireOnCacheChanged(); } } }); } private void updateModuleValidityCache(final Module module) { if (myValidityCache.containsKey(module)) return; //do not check twice final OrderEntry[] entries = myModulesConfigurator.getRootModel(module).getOrderEntries(); Map<String, Set<String>> problems = null; for (OrderEntry entry : entries) { if (myDisposed) return; if (!entry.isValid()){ if (problems == null) { problems = new HashMap<String, Set<String>>(); } if (entry instanceof JdkOrderEntry && ((JdkOrderEntry)entry).getJdkName() == null) { problems.put(NO_JDK, null); } else { Set<String> deletedLibraries = problems.get(DELETED_LIBRARIES); if (deletedLibraries == null){ deletedLibraries = new HashSet<String>(); problems.put(DELETED_LIBRARIES, deletedLibraries); } deletedLibraries.add(entry.getPresentableName()); } } } final Map<String, Set<String>> finalProblems = problems; SwingUtilities.invokeLater(new Runnable() { public void run() { if (!myDisposed) { myValidityCache.put(module, finalProblems); fireOnCacheChanged(); } } }); } public boolean isUnused(final Object object, MasterDetailsComponent.MyNode node) { if (object == null) return false; if (object instanceof Module){ getCachedDependencies(object, node, false); return false; } if (object instanceof ProjectJdk) { return false; } if (object instanceof Library) { final LibraryTable libraryTable = ((Library)object).getTable(); if (libraryTable == null || libraryTable.getTableLevel() != LibraryTablesRegistrar.PROJECT_LEVEL) { return false; } } final Set<String> dependencies = getCachedDependencies(object, node, false); return dependencies != null && dependencies.isEmpty(); } private void fireOnCacheChanged() { //myTree.repaint(); } public void addReloadProjectRequest(final Runnable runnable) { myReloadProjectAlarm.cancelAllRequests(); myReloadProjectAlarm.addRequest(runnable, 300, ModalityState.NON_MODAL); } public void resetLibraries() { final LibraryTablesRegistrar tablesRegistrar = LibraryTablesRegistrar.getInstance(); myLevel2Providers.clear(); myLevel2Providers.put(LibraryTablesRegistrar.APPLICATION_LEVEL, new LibrariesModifiableModel(tablesRegistrar.getLibraryTable())); myLevel2Providers.put(LibraryTablesRegistrar.PROJECT_LEVEL, new LibrariesModifiableModel(tablesRegistrar.getLibraryTable(myProject))); for (final LibraryTable table : tablesRegistrar.getCustomLibraryTables()) { myLevel2Providers.put(table.getTableLevel(), new LibrariesModifiableModel(table)); } } public LibraryTableModifiableModelProvider getGlobalLibrariesProvider(final boolean tableEditable) { return createModifiableModelProvider(LibraryTablesRegistrar.APPLICATION_LEVEL, tableEditable); } public LibraryTableModifiableModelProvider createModifiableModelProvider(final String level, final boolean isTableEditable) { final LibraryTable table = LibraryTablesRegistrar.getInstance().getLibraryTableByLevel(level, myProject); return new LibraryTableModifiableModelProvider() { public LibraryTable.ModifiableModel getModifiableModel() { return myLevel2Providers.get(level); } public String getTableLevel() { return table.getTableLevel(); } public LibraryTablePresentation getLibraryTablePresentation() { return table.getPresentation(); } public boolean isLibraryTableEditable() { return isTableEditable && table.isEditable(); } }; } public LibraryTableModifiableModelProvider getProjectLibrariesProvider(final boolean tableEditable) { return createModifiableModelProvider(LibraryTablesRegistrar.PROJECT_LEVEL, tableEditable); } public List<LibraryTableModifiableModelProvider> getCustomLibrariesProviders(final boolean tableEditable) { return ContainerUtil.map2List(LibraryTablesRegistrar.getInstance().getCustomLibraryTables(), new NotNullFunction<LibraryTable, LibraryTableModifiableModelProvider>() { @NotNull public LibraryTableModifiableModelProvider fun(final LibraryTable libraryTable) { return createModifiableModelProvider(libraryTable.getTableLevel(), tableEditable); } }); } @Nullable public Library getLibrary(final String libraryName, final String libraryLevel) { /* the null check is added only to prevent NPE when called from getLibrary */ final LibrariesModifiableModel model = myLevel2Providers.get(libraryLevel); return model == null ? null : findLibraryModel(libraryName, model); } @Nullable private static Library findLibraryModel(final String libraryName, @NotNull LibrariesModifiableModel model) { final Library library = model.getLibraryByName(libraryName); return findLibraryModel(library, model); } @Nullable private static Library findLibraryModel(final Library library, LibrariesModifiableModel tableModel) { if (tableModel == null) return library; if (tableModel.wasLibraryRemoved(library)) return null; return tableModel.hasLibraryEditor(library) ? (Library)tableModel.getLibraryEditor(library).getModel() : library; } public void reset() { myDisposed = false; resetLibraries(); myModulesConfigurator.resetModuleEditors(); } }
package javax.validation; import java.lang.annotation.ElementType; /** * Contract determining if a property can be accessed by the Bean Validation provider * This contract is called for each property either validated or traversed. * * A traversable resolver implementation must me thread-safe. * * @author Emmanuel Bernard */ public interface TraversableResolver { /** * Determine if a property can be traversed by Bean Validation. * * @param traversableObject object hosting <code>traversableProperty</code>. * @param traversableProperty name of the traversable property. * @param rootBeanType type of the root object passed to the Validator. * @param pathToTraversableObject path from the root object to the <code>traversableProperty</code> * (using the path specification defined by Bean Validator). * @param elementType either <code>FIELD</code> or <code>METHOD</code>. * * @return <code>true</code> if the property is traversable by Bean Validation, <code>false</code> otherwise. */ boolean isTraversable(Object traversableObject, String traversableProperty, Class<?> rootBeanType, String pathToTraversableObject, ElementType elementType); }
package io.vivarium.visualizer; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import com.badlogic.gdx.ApplicationAdapter; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.InputProcessor; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.ui.Label; import com.badlogic.gdx.scenes.scene2d.ui.SelectBox; import com.badlogic.gdx.scenes.scene2d.ui.Skin; import com.badlogic.gdx.scenes.scene2d.ui.Table; import com.badlogic.gdx.scenes.scene2d.ui.TextField; import com.badlogic.gdx.scenes.scene2d.ui.TextField.TextFieldListener; import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener; import com.badlogic.gdx.utils.Align; import com.badlogic.gdx.utils.viewport.ScreenViewport; import com.google.common.collect.Lists; import io.vivarium.core.Action; import io.vivarium.core.Creature; import io.vivarium.core.CreatureBlueprint; import io.vivarium.core.ItemType; import io.vivarium.core.TerrainType; import io.vivarium.core.World; import io.vivarium.core.WorldBlueprint; public class Vivarium extends ApplicationAdapter implements InputProcessor { private static final int SIZE = 30; private static final int BLOCK_SIZE = 32; // Simulation information private WorldBlueprint _blueprint; private World _world; // Simulation + Animation private int framesSinceTick = 0; private boolean _enableInterpolation = false; private Map<Integer, CreatureDelegate> _animationCreatureDelegates = new HashMap<>(); private int _selectedCreature = 42; // Low Level Graphics information private SpriteBatch _batch; private Texture _img; // Graphical settings private CreatureRenderMode _creatureRenderMode = CreatureRenderMode.GENDER; private enum CreatureRenderMode { GENDER, HEALTH, HUNGER, AGE, MEMORY, SIGN } private int _ticks = 1; private int _overFrames = 1; private MouseClickMode _mouseClickMode = MouseClickMode.SELECT_CREATURE; private enum MouseClickMode { SELECT_CREATURE(false), ADD_FLAMETHROWER(true), ADD_FOODGENERATOR(true), ADD_WALL(true), ADD_WALL_BRUTALLY(true), REMOVE_TERRAIN(true), REMOVE_ANYTHING(true); private final boolean _isPaintbrushMode; MouseClickMode(boolean isPaintbrushMode) { _isPaintbrushMode = isPaintbrushMode; } public boolean isPaintbrushMode() { return _isPaintbrushMode; } } // High Level Graphics information private Stage stage; private Skin skin; private Label fpsLabel; private Label populationLabel; private Label generationLabel; private Label foodSupplyLabel; private Label mouseLabel; // Input tracking private int _xDownWorld = -1; private int _yDownWorld = -1; public Vivarium() { } @Override public void create() { // Create simulation _blueprint = WorldBlueprint.makeDefault(); CreatureBlueprint creatureBlueprint = CreatureBlueprint.makeDefault(3, 0, 3); _blueprint.setCreatureBlueprints(Lists.newArrayList(creatureBlueprint)); _blueprint.setSignEnabled(true); _blueprint.setSize(SIZE); _world = new World(_blueprint); // Setup Input Listeners Gdx.input.setInputProcessor(this); // Low level grahpics _batch = new SpriteBatch(); _img = new Texture("sprites.png"); buildSidebarUI(); } private void buildSidebarUI() { skin = new Skin(Gdx.files.internal("data/uiskin.json")); // stage = new Stage(Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), false, new PolygonSpriteBatch()); stage = new Stage(new ScreenViewport()); // Gdx.input.setInputProcessor(stage); // Simulation Speed final Label ticksLabel = new Label("Ticks", skin); TextField framesPerTickTextInput = new TextField("", skin); framesPerTickTextInput.setMessageText("1"); framesPerTickTextInput.setAlignment(Align.center); final Label perLabel = new Label("per", skin); final Label framesLabel = new Label("Frames", skin); TextField perFramesTextInput = new TextField("", skin); perFramesTextInput.setMessageText("1"); perFramesTextInput.setAlignment(Align.center); // Food Spawn Rate final Label foodSpawnLabel = new Label("Food Spawn", skin); TextField foodSpawnTextInput = new TextField("", skin); foodSpawnTextInput.setMessageText("" + _blueprint.getFoodGenerationProbability()); foodSpawnTextInput.setAlignment(Align.center); // Click Mode final Label clickModeLabel = new Label("Click Mode: ", skin); final SelectBox<String> clickModeSelectBox = new SelectBox<>(skin); clickModeSelectBox.addListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { _mouseClickMode = MouseClickMode.valueOf(clickModeSelectBox.getSelected()); _xDownWorld = -1; _yDownWorld = -1; } }); String[] clickModeStrings = new String[MouseClickMode.values().length]; for (int i = 0; i < MouseClickMode.values().length; i++) { clickModeStrings[i] = MouseClickMode.values()[i].toString(); } clickModeSelectBox.setItems(clickModeStrings); clickModeSelectBox.setSelected(_mouseClickMode.toString()); // Render Mode final Label renderModeLabel = new Label("Render Mode: ", skin); final SelectBox<String> renderModeSelectBox = new SelectBox<>(skin); renderModeSelectBox.addListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { _creatureRenderMode = CreatureRenderMode.valueOf(renderModeSelectBox.getSelected()); } }); String[] creatureRenderModeStrings = new String[CreatureRenderMode.values().length]; for (int i = 0; i < CreatureRenderMode.values().length; i++) { creatureRenderModeStrings[i] = CreatureRenderMode.values()[i].toString(); } renderModeSelectBox.setItems(creatureRenderModeStrings); renderModeSelectBox.setSelected(_creatureRenderMode.toString()); // FPS Display fpsLabel = new Label("fps:", skin); populationLabel = new Label("population:", skin); generationLabel = new Label("generation:", skin); foodSupplyLabel = new Label("food:", skin); mouseLabel = new Label("mouse:", skin); // Layout Table table = new Table(); table.setPosition(200, getHeight() - 150); table.add(renderModeLabel).colspan(2); table.add(renderModeSelectBox).maxWidth(100); table.row(); table.add(clickModeLabel).colspan(2); table.add(clickModeSelectBox).maxWidth(100); table.row(); table.add(); table.add(framesPerTickTextInput); table.add(ticksLabel); table.row(); table.add(perLabel); table.add(perFramesTextInput); table.add(framesLabel); table.row(); table.add(foodSpawnLabel); table.add(foodSpawnTextInput); table.row(); table.add(fpsLabel).colspan(4); table.row(); table.add(populationLabel).colspan(4); table.row(); table.add(generationLabel).colspan(4); table.row(); table.add(foodSupplyLabel).colspan(4); table.row(); table.add(mouseLabel).colspan(4); stage.addActor(table); framesPerTickTextInput.setTextFieldListener(new TextFieldListener() { @Override public void keyTyped(TextField textField, char key) { if (key == '\n') { textField.getOnscreenKeyboard().show(false); } try { _ticks = Integer.parseInt(textField.getText().trim()); } catch (Exception e) { _ticks = 1; } _ticks = Math.max(_ticks, 1); _ticks = Math.min(_ticks, 1_000); _enableInterpolation = _ticks == 1 && _overFrames > 1; } }); perFramesTextInput.setTextFieldListener(new TextFieldListener() { @Override public void keyTyped(TextField textField, char key) { if (key == '\n') { textField.getOnscreenKeyboard().show(false); } try { _overFrames = Integer.parseInt(textField.getText().trim()); } catch (Exception e) { _overFrames = 1; } _overFrames = Math.max(_overFrames, 1); _overFrames = Math.min(_overFrames, 600); _enableInterpolation = _ticks == 1 && _overFrames > 1; } }); foodSpawnTextInput.setTextFieldListener(new TextFieldListener() { @Override public void keyTyped(TextField textField, char key) { if (key == '\n') { textField.getOnscreenKeyboard().show(false); } try { _world.getBlueprint().setFoodGenerationProbability(Double.parseDouble(textField.getText().trim())); } catch (Exception e) { } } }); } @Override public void render() { Gdx.gl.glClearColor(0, 0, 0, 1); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); _batch.begin(); _batch.setColor(Color.WHITE); float interpolationFraction = _enableInterpolation ? (float) framesSinceTick / _overFrames : 1; drawTerrain(interpolationFraction); drawFood(); drawCreatures(interpolationFraction); _batch.end(); setLabels(); stage.act(Gdx.graphics.getDeltaTime()); stage.draw(); framesSinceTick++; if (framesSinceTick >= _overFrames) { for (int i = 0; i < _ticks; i++) { _world.tick(); updateCreatureDelegates(); } framesSinceTick = 0; } mouseBrush(); } private void mouseBrush() { if (this._xDownWorld > -1 && this._yDownWorld > -1) { if (this._mouseClickMode.isPaintbrushMode()) { applyMouseBrush(_xDownWorld, _yDownWorld); } } } private void removeTerrain(int r, int c) { _world.setTerrain(null, r, c); } private void applyMouseBrush(int x, int y) { Creature creature; // Check bounds, don't let the user change terrain near the edge of the world if (x < 1 || x >= _world.getWidth() - 1 || y < 1 || y >= _world.getHeight() - 1) { return; } // Apply brush modes switch (this._mouseClickMode) { case ADD_WALL: if (_world.squareIsEmpty(y, x)) { _world.setTerrain(TerrainType.WALL, y, x); } break; case ADD_WALL_BRUTALLY: creature = _world.getCreature(y, x); if (creature != null) { this._animationCreatureDelegates.remove(creature.getID()); _world.removeCreature(y, x); } _world.removeFood(y, x); _world.setTerrain(TerrainType.WALL, y, x); break; case REMOVE_TERRAIN: removeTerrain(y, x); break; case REMOVE_ANYTHING: creature = _world.getCreature(y, x); if (creature != null) { this._animationCreatureDelegates.remove(creature.getID()); _world.removeCreature(y, x); } _world.removeFood(y, x); _world.setTerrain(null, y, x); break; case ADD_FLAMETHROWER: if (_world.squareIsEmpty(y, x)) { _world.setTerrain(TerrainType.FLAMETHROWER, y, x); } break; case ADD_FOODGENERATOR: if (_world.squareIsEmpty(y, x)) { _world.setTerrain(TerrainType.FOOD_GENERATOR, y, x); } break; case SELECT_CREATURE: throw new IllegalStateException("" + MouseClickMode.SELECT_CREATURE + " is not a brush mode"); } } private void setLabels() { fpsLabel.setText("fps: " + Gdx.graphics.getFramesPerSecond()); populationLabel.setText("population: " + _world.getCreatureCount()); LinkedList<Creature> creatures = _world.getCreatures(); double generation = 0; for (Creature creature : creatures) { generation += creature.getGeneration(); } generation /= creatures.size(); generationLabel.setText("generation: " + ((int) (generation * 100) / 100.0)); foodSupplyLabel.setText("food: " + _world.getItemCount()); } private void drawSprite(VivariumSprite sprite, float xPos, float yPos, float angle) { drawSprite(sprite, xPos, yPos, angle, 1); } private void drawSprite(VivariumSprite sprite, float xPos, float yPos, float angle, float scale) { float x = SIZE / 2 * BLOCK_SIZE + xPos * BLOCK_SIZE; float y = getHeight() - yPos * BLOCK_SIZE - BLOCK_SIZE; float originX = BLOCK_SIZE / 2; float originY = BLOCK_SIZE / 2; float width = BLOCK_SIZE; float height = BLOCK_SIZE; float rotation = angle; // In degrees int srcX = sprite.x * BLOCK_SIZE; int srcY = sprite.y * BLOCK_SIZE; int srcW = BLOCK_SIZE; int srcH = BLOCK_SIZE; boolean flipX = false; boolean flipY = false; _batch.draw(_img, x, y, originX, originY, width, height, scale, scale, rotation, srcX, srcY, srcW, srcH, flipX, flipY); } private void drawTerrain(float interpolationFraction) { for (int c = 0; c < _world.getWorldWidth(); c++) { for (int r = 0; r < _world.getWorldHeight(); r++) { if (_world.getTerrain(r, c) == TerrainType.WALL) { drawSprite(VivariumSprite.WALL, c, r, 0); } if (_world.getTerrain(r, c) == TerrainType.FOOD_GENERATOR) { drawSprite(VivariumSprite.FOOD_GENERATOR_ACTIVE, c, r, 0); } if (_world.getTerrain(r, c) == TerrainType.FLAMETHROWER) { drawSprite(VivariumSprite.FLAMETHROWER_ACTIVE, c, r, 0); } if (_world.getTerrain(r, c) == TerrainType.FLAME) { if (interpolationFraction < 1f / 3f) { drawSprite(VivariumSprite.FLAME_1, c, r, 0); } else if (interpolationFraction < 2f / 3f) { drawSprite(VivariumSprite.FLAME_2, c, r, 0); } else { drawSprite(VivariumSprite.FLAME_3, c, r, 0); } } } } } private void drawFood() { for (int c = 0; c < _world.getWorldWidth(); c++) { for (int r = 0; r < _world.getWorldHeight(); r++) { if (_world.getItem(r, c) == ItemType.FOOD) { drawSprite(VivariumSprite.FOOD, c, r, 0); } } } } private void drawCreatures(float interpolationFraction) { for (CreatureDelegate delegate : _animationCreatureDelegates.values()) { drawCreature(delegate, interpolationFraction); } } private void drawCreature(CreatureDelegate delegate, float interpolationFraction) { Creature creature = delegate.getCreature(); switch (_creatureRenderMode) { case GENDER: setColorOnGenderAndPregnancy(delegate, interpolationFraction); break; case HEALTH: setColorOnHealth(creature); break; case AGE: setColorOnAge(creature); break; case HUNGER: setColorOnFood(creature); break; case MEMORY: setColorOnMemory(creature); break; case SIGN: setColorOnSignLanguage(creature); break; } float scale = delegate.getScale(interpolationFraction); VivariumSprite creatureSprite = getCreatureSpriteFrame(interpolationFraction, creature); drawSprite(creatureSprite, delegate.getC(interpolationFraction), delegate.getR(interpolationFraction), delegate.getRotation(interpolationFraction), scale); if (creature.getID() == this._selectedCreature) { _batch.setColor(Color.WHITE); VivariumSprite creatureHaloSprite = getCreatureHaloSpriteFrame(interpolationFraction, creature); drawSprite(creatureHaloSprite, delegate.getC(interpolationFraction), delegate.getR(interpolationFraction), delegate.getRotation(interpolationFraction), scale); } } private void updateCreatureDelegates() { // Find creatures that are dying and mark them as such. These creatures will no longer // be present in the world, but it's expensive to check this. Fortunately, a creature // will use the die action as its last act in the world. Any existing delegate // with a creature that has used dye either needs to animate its death, or has // already done so. Set<Integer> creatureIDsToRemove = new HashSet<>(); for (Entry<Integer, CreatureDelegate> delegatePair : _animationCreatureDelegates.entrySet()) { if (delegatePair.getValue().isDying()) { creatureIDsToRemove.add(delegatePair.getKey()); } else if (delegatePair.getValue().getCreature().getAction() == Action.DIE) { delegatePair.getValue().die(); } } // Remove creatures that have finished dying from the animation delegates. for (Integer creatureID : creatureIDsToRemove) { _animationCreatureDelegates.remove(creatureID); } // For all other creatures, update their animation delegate, or add a new one if they // don't have an animation delegate yet. for (int c = 0; c < _world.getWorldWidth(); c++) { for (int r = 0; r < _world.getWorldHeight(); r++) { Creature creature = _world.getCreature(r, c); if (creature != null) { if (_animationCreatureDelegates.containsKey(creature.getID())) { _animationCreatureDelegates.get(creature.getID()).updateSnapshot(r, c); } else { _animationCreatureDelegates.put(creature.getID(), new CreatureDelegate(creature, r, c)); } } } } } public void setColorOnGenderAndPregnancy(CreatureDelegate delegate, float interpolationFraction) { if (delegate.getCreature().getIsFemale()) { float pregnancyFraction = delegate.getPregnancy(interpolationFraction); float red = (0.4f - 0) * pregnancyFraction + 0.0f; float green = (0 - 0.8f) * pregnancyFraction + 0.8f; float blue = (0.4f - 0.8f) * pregnancyFraction + 0.8f; _batch.setColor(new Color(red, green, blue, 1)); } else { _batch.setColor(new Color(0.8f, 0, 0, 1)); } } public void setColorOnFood(Creature creature) { float food = ((float) creature.getFood()) / creature.getBlueprint().getMaximumFood(); _batch.setColor(new Color(1, food, food, 1)); } public void setColorOnHealth(Creature creature) { float health = ((float) creature.getHealth()) / creature.getBlueprint().getMaximumHealth(); _batch.setColor(new Color(1, health, health, 1)); } public void setColorOnAge(Creature creature) { float age = ((float) creature.getAge()) / creature.getBlueprint().getMaximumAge(); _batch.setColor(new Color(age, 1, age, 1)); } public void setColorOnMemory(Creature creature) { double[] memories = creature.getMemoryUnits(); float[] displayMemories = { 1, 1, 1 }; for (int i = 0; i < memories.length && i < displayMemories.length; i++) { displayMemories[i] = (float) memories[i]; } _batch.setColor(new Color(displayMemories[0], displayMemories[1], displayMemories[2], 1)); } public void setColorOnSignLanguage(Creature creature) { double[] signs = creature.getSignOutputs(); float[] displaySigns = { 1, 1, 1 }; for (int i = 0; i < signs.length && i < displaySigns.length; i++) { displaySigns[i] = (float) signs[i]; } _batch.setColor(new Color(displaySigns[0], displaySigns[1], displaySigns[2], 1)); } private VivariumSprite getCreatureSpriteFrame(float cycle, Creature creature) { int offset = (int) (cycle * 100 + creature.getRandomSeed() * 100) % 100; if (offset < 25) { return VivariumSprite.CREATURE_1; } else if (offset < 50) { return VivariumSprite.CREATURE_2; } else if (offset < 75) { return VivariumSprite.CREATURE_3; } else { return VivariumSprite.CREATURE_2; } } private VivariumSprite getCreatureHaloSpriteFrame(float cycle, Creature creature) { int offset = (int) (cycle * 100 + creature.getRandomSeed() * 100) % 100; if (offset < 25) { return VivariumSprite.HALO_CREATURE_1; } else if (offset < 50) { return VivariumSprite.HALO_CREATURE_2; } else if (offset < 75) { return VivariumSprite.HALO_CREATURE_3; } else { return VivariumSprite.HALO_CREATURE_2; } } public static int getHeight() { return SIZE * BLOCK_SIZE; } public static int getWidth() { return SIZE * BLOCK_SIZE; } @Override public boolean keyDown(int keycode) { stage.keyDown(keycode); return false; } @Override public boolean keyUp(int keycode) { stage.keyUp(keycode); return false; } @Override public boolean keyTyped(char character) { stage.keyTyped(character); return false; } @Override public boolean touchDown(int screenX, int screenY, int pointer, int button) { stage.touchDown(screenX, screenY, pointer, button); if (screenX > SIZE / 2 * BLOCK_SIZE) { this._xDownWorld = (screenX - SIZE / 2 * BLOCK_SIZE) / BLOCK_SIZE; this._yDownWorld = screenY / BLOCK_SIZE; } else { this._xDownWorld = -1; this._yDownWorld = -1; } return true; } @Override public boolean touchUp(int screenX, int screenY, int pointer, int button) { stage.touchUp(screenX, screenY, pointer, button); if (screenX > SIZE / 2 * BLOCK_SIZE) { int xUpWorld = (screenX - SIZE / 2 * BLOCK_SIZE) / BLOCK_SIZE; int yUpWorld = screenY / BLOCK_SIZE; if (_xDownWorld == xUpWorld && _yDownWorld == yUpWorld) { if (_mouseClickMode == MouseClickMode.SELECT_CREATURE) { if (_world.getCreature(yUpWorld, xUpWorld) != null) { this._selectedCreature = _world.getCreature(yUpWorld, xUpWorld).getID(); } this._xDownWorld = -1; this._yDownWorld = -1; } } } return true; } @Override public boolean touchDragged(int screenX, int screenY, int pointer) { stage.touchDragged(screenX, screenY, pointer); if (screenX > SIZE / 2 * BLOCK_SIZE) { int xDragWorld = (screenX - SIZE / 2 * BLOCK_SIZE) / BLOCK_SIZE; int yDragWorld = screenY / BLOCK_SIZE; if (this._mouseClickMode.isPaintbrushMode()) { applyMouseBrush(xDragWorld, yDragWorld); } } return false; } @Override public boolean mouseMoved(int screenX, int screenY) { stage.mouseMoved(screenX, screenY); return false; } @Override public boolean scrolled(int amount) { stage.scrolled(amount); return false; } }
package com.intellij.psi.impl.source.tree; import com.intellij.lang.ASTNode; import com.intellij.lexer.JavaLexer; import com.intellij.lexer.Lexer; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Document; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.pom.java.LanguageLevel; import com.intellij.psi.*; import com.intellij.psi.impl.PsiDocumentManagerImpl; import com.intellij.psi.impl.PsiManagerImpl; import com.intellij.psi.impl.PsiTreeChangeEventImpl; import com.intellij.psi.impl.cache.RepositoryManager; import com.intellij.psi.impl.light.LightTypeElement; import com.intellij.psi.impl.source.*; import com.intellij.psi.impl.source.codeStyle.CodeEditUtil; import com.intellij.psi.impl.source.codeStyle.CodeStyleManagerEx; import com.intellij.psi.impl.source.parsing.*; import com.intellij.psi.xml.XmlTag; import com.intellij.psi.xml.XmlTagValue; import com.intellij.util.CharTable; import com.intellij.util.IncorrectOperationException; public class ChangeUtil implements Constants { private static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.source.tree.ChangeUtil"); private ChangeUtil() { } public static void addChild(final CompositeElement parent, final TreeElement child, TreeElement anchorBefore) { LOG.assertTrue(anchorBefore == null || anchorBefore.getTreeParent() == parent); int offset = anchorBefore != null ? anchorBefore.getStartOffset() : parent.getStartOffset() + parent.getTextLength(); PsiTreeChangeEventImpl event = null; PsiElement parentPsiElement = SourceTreeToPsiMap.treeElementToPsi(parent); PsiFile file = parentPsiElement.getContainingFile(); checkConsistency(file); boolean physical = parentPsiElement.isPhysical(); if (physical) { PsiManagerImpl manager = (PsiManagerImpl)parent.getManager(); if (file != null) { manager.invalidateFile(file); } event = new PsiTreeChangeEventImpl(manager); event.setParent(parentPsiElement); event.setFile(file); event.setOffset(offset); event.setOldLength(0); manager.beforeChildAddition(event); RepositoryManager repositoryManager = manager.getRepositoryManager(); if (repositoryManager != null) { repositoryManager.beforeChildAddedOrRemoved(file, parent, child); } } final CharTable newCharTab = SharedImplUtil.findCharTableByTree(parent); final CharTable oldCharTab = SharedImplUtil.findCharTableByTree(child); TreeUtil.remove(child); if (newCharTab != oldCharTab) { registerLeafsInCharTab(newCharTab, child, oldCharTab); } if (anchorBefore != null) { TreeUtil.insertBefore(anchorBefore, child); } else { TreeUtil.addChildren(parent, child); } //updateCachedLengths(parent, childLength); PsiManagerImpl manager = (PsiManagerImpl)parent.getManager(); parent.subtreeChanged(); if (physical) { event.setChild(SourceTreeToPsiMap.treeElementToPsi(child)); manager.childAdded(event); } else if (manager != null) { manager.nonPhysicalChange(); } checkConsistency(file); } private static void checkConsistency(PsiFile file) { if (LOG.isDebugEnabled() && file != null) { Document document = PsiDocumentManager.getInstance(file.getProject()).getDocument(file); if (document != null) { PsiDocumentManagerImpl.checkConsistency(file, document); } checkTextRanges(file); } } private static void registerLeafsInCharTab(CharTable newCharTab, ASTNode child, CharTable oldCharTab) { if (newCharTab == oldCharTab) return; while (child != null) { CharTable charTable = child.getUserData(CharTable.CHAR_TABLE_KEY); if (child instanceof LeafElement) { ((LeafElement)child).registerInCharTable(newCharTab, oldCharTab); } else { registerLeafsInCharTab(newCharTab, child.getFirstChildNode(), charTable != null ? charTable : oldCharTab); } if (charTable != null) { child.putUserData(CharTable.CHAR_TABLE_KEY, null); } child = child.getTreeNext(); } } public static void removeChild(final CompositeElement parent, final TreeElement child) { LOG.assertTrue(child.getTreeParent() == parent); int offset = child.getStartOffset(); int childLength = child.getTextLength(); PsiTreeChangeEventImpl event = null; PsiElement parentPsiElement = SourceTreeToPsiMap.treeElementToPsi(parent); PsiFile file = parentPsiElement.getContainingFile(); boolean physical = parentPsiElement.isPhysical(); if (physical) { PsiManagerImpl manager = (PsiManagerImpl)parent.getManager(); if (file != null) { manager.invalidateFile(file); } event = new PsiTreeChangeEventImpl(manager); event.setParent(parentPsiElement); event.setChild(SourceTreeToPsiMap.treeElementToPsi(child)); event.setFile(file); event.setOffset(offset); event.setOldLength(childLength); manager.beforeChildRemoval(event); RepositoryManager repositoryManager = manager.getRepositoryManager(); if (repositoryManager != null) { repositoryManager.beforeChildAddedOrRemoved(file, parent, child); } } child.putUserData(CharTable.CHAR_TABLE_KEY, SharedImplUtil.findCharTableByTree(child)); TreeUtil.remove(child); parent.subtreeChanged(); //updateCachedLengths(parent, -childLength); PsiManagerImpl manager = (PsiManagerImpl)parent.getManager(); if (physical) { manager.childRemoved(event); } else if (manager != null) { manager.nonPhysicalChange(); } checkConsistency(file); } public static void replaceChild(final CompositeElement parent, final TreeElement oldChild, final TreeElement newChild) { LOG.assertTrue(oldChild.getTreeParent() == parent); int offset = oldChild.getStartOffset(); int oldLength = oldChild.getTextLength(); final CharTable newCharTable = SharedImplUtil.findCharTableByTree(parent); final CharTable oldCharTable = SharedImplUtil.findCharTableByTree(newChild); PsiTreeChangeEventImpl event = null; PsiElement parentPsiElement = SourceTreeToPsiMap.treeElementToPsi(parent); PsiFile file = parentPsiElement.getContainingFile(); boolean physical = parentPsiElement.isPhysical(); if (physical) { PsiManagerImpl manager = (PsiManagerImpl)parent.getManager(); if (file != null) { manager.invalidateFile(file); } event = new PsiTreeChangeEventImpl(manager); event.setParent(parentPsiElement); event.setOldChild(SourceTreeToPsiMap.treeElementToPsi(oldChild)); event.setFile(file); event.setOffset(offset); event.setOldLength(oldLength); manager.beforeChildReplacement(event); RepositoryManager repositoryManager = manager.getRepositoryManager(); if (repositoryManager != null) { repositoryManager.beforeChildAddedOrRemoved(file, parent, oldChild); repositoryManager.beforeChildAddedOrRemoved(file, parent, newChild); } } TreeUtil.remove(newChild); if (oldCharTable != newCharTable) { registerLeafsInCharTab(newCharTable, newChild, oldCharTable); } oldChild.putUserData(CharTable.CHAR_TABLE_KEY, newCharTable); if (oldChild != newChild) { TreeUtil.replaceWithList(oldChild, newChild); SharedImplUtil.invalidate(oldChild); } parent.subtreeChanged(); PsiManagerImpl manager = (PsiManagerImpl)parent.getManager(); if (physical) { event.setNewChild(SourceTreeToPsiMap.treeElementToPsi(newChild)); manager.childReplaced(event); } else if (manager != null) { manager.nonPhysicalChange(); } checkConsistency(file); } public static void replaceAllChildren(final CompositeElement parent, final ASTNode newChildrenParent) { int offset = parent.getStartOffset(); int oldLength = parent.getTextLength(); int newLength = newChildrenParent.getTextLength(); PsiTreeChangeEventImpl event = null; PsiElement parentPsiElement = SourceTreeToPsiMap.treeElementToPsi(parent); boolean physical = parentPsiElement.isPhysical(); PsiFile file = parentPsiElement.getContainingFile(); ChameleonTransforming.transformChildren(newChildrenParent); final ASTNode firstChild = newChildrenParent.getFirstChildNode(); if (physical) { PsiManagerImpl manager = (PsiManagerImpl)parent.getManager(); manager.invalidateFile(file); event = new PsiTreeChangeEventImpl(manager); event.setParent(parentPsiElement); event.setFile(file); event.setOffset(offset); event.setOldLength(oldLength); manager.beforeChildrenChange(event); VirtualFile vFile = file.getVirtualFile(); if (vFile != null) { RepositoryManager repositoryManager = manager.getRepositoryManager(); if (repositoryManager != null) { ChameleonTransforming.transformChildren(parent); for (ASTNode child = parent.getFirstChildNode(); child != null; child = child.getTreeNext()) { repositoryManager.beforeChildAddedOrRemoved(file, parent, child); } for (ASTNode child = firstChild; child != null; child = child.getTreeNext()) { repositoryManager.beforeChildAddedOrRemoved(file, parent, child); } } } } final CharTable newCharTab = SharedImplUtil.findCharTableByTree(parent); ASTNode oldChild = parent.getFirstChildNode(); while (oldChild != null) { oldChild.putUserData(CharTable.CHAR_TABLE_KEY, newCharTab); oldChild = oldChild.getTreeNext(); } TreeUtil.removeRange((TreeElement)parent.getFirstChildNode(), null); if (firstChild != null) { final CharTable oldCharTab = SharedImplUtil.findCharTableByTree(newChildrenParent); registerLeafsInCharTab(newCharTab, firstChild, oldCharTab); TreeUtil.addChildren(parent, (TreeElement)firstChild); } parent.setCachedLength(newLength); parent.subtreeChanged(); //if (parent.getTreeParent() != null){ // updateCachedLengths(parent.getTreeParent(), newLength - oldLength); PsiManagerImpl manager = (PsiManagerImpl)parent.getManager(); if (physical) { manager.childrenChanged(event); } else if (manager != null) { manager.nonPhysicalChange(); } checkConsistency(file); } public static void encodeInformation(TreeElement element) { encodeInformation(element, element); } private static void encodeInformation(TreeElement element, ASTNode original) { boolean encodeRefTargets = true; if (original.getTreeParent() instanceof DummyHolderElement) { DummyHolder dummyHolder = (DummyHolder)SourceTreeToPsiMap.treeElementToPsi(original.getTreeParent()); if (dummyHolder.getContext() == null && !dummyHolder.hasImports()) { // optimization encodeRefTargets = false; } } _encodeInformation(element, original, encodeRefTargets); } private static void _encodeInformation(TreeElement element, ASTNode original, boolean encodeRefTargets) { if (original instanceof CompositeElement) { if (original.getElementType() == ElementType.JAVA_CODE_REFERENCE || original.getElementType() == ElementType.REFERENCE_EXPRESSION) { if (encodeRefTargets) { encodeInformationInRef(element, original); } } else if (original.getElementType() == ElementType.MODIFIER_LIST) { if ((original.getTreeParent().getElementType() == ElementType.FIELD || original.getTreeParent().getElementType() == ElementType.METHOD) && original.getTreeParent().getTreeParent().getElementType() == ElementType.CLASS && ((PsiClass)SourceTreeToPsiMap.treeElementToPsi(original.getTreeParent().getTreeParent())).isInterface()) { element.putUserData(INTERFACE_MODIFIERS_FLAG_KEY, Boolean.TRUE); } } ChameleonTransforming.transformChildren(element); ChameleonTransforming.transformChildren(original); TreeElement child = (TreeElement)element.getFirstChildNode(); ASTNode child1 = original.getFirstChildNode(); while (child != null) { _encodeInformation(child, child1, encodeRefTargets); child = child.getTreeNext(); child1 = child1.getTreeNext(); } } } private static void encodeInformationInRef(TreeElement ref, ASTNode original) { if (original.getElementType() == REFERENCE_EXPRESSION) { if (original.getTreeParent().getElementType() != REFERENCE_EXPRESSION) return; // cannot refer to class (optimization) PsiElement target = ((PsiJavaCodeReferenceElement)SourceTreeToPsiMap.treeElementToPsi(original)).resolve(); if (target instanceof PsiClass) { ref.putCopyableUserData(REFERENCED_CLASS_KEY, (PsiClass)target); } } else if (original.getElementType() == JAVA_CODE_REFERENCE) { switch (((PsiJavaCodeReferenceElementImpl)original).getKind()) { case PsiJavaCodeReferenceElementImpl.CLASS_NAME_KIND: case PsiJavaCodeReferenceElementImpl.CLASS_OR_PACKAGE_NAME_KIND: case PsiJavaCodeReferenceElementImpl.CLASS_IN_QUALIFIED_NEW_KIND: { final PsiElement target = ((PsiJavaCodeReferenceElement)SourceTreeToPsiMap.treeElementToPsi(original)).resolve(); if (target instanceof PsiClass) { ref.putCopyableUserData(REFERENCED_CLASS_KEY, (PsiClass)target); } } break; case PsiJavaCodeReferenceElementImpl.PACKAGE_NAME_KIND: case PsiJavaCodeReferenceElementImpl.CLASS_FQ_NAME_KIND: case PsiJavaCodeReferenceElementImpl.CLASS_FQ_OR_PACKAGE_NAME_KIND: break; default: LOG.assertTrue(false); } } else { LOG.assertTrue(false, "Wrong element type: " + original.getElementType()); return; } } public static TreeElement decodeInformation(TreeElement element) { if (element instanceof CompositeElement) { ChameleonTransforming.transformChildren(element); TreeElement child = (TreeElement)element.getFirstChildNode(); while (child != null) { child = decodeInformation(child); child = child.getTreeNext(); } if (element.getElementType() == ElementType.JAVA_CODE_REFERENCE || element.getElementType() == ElementType.REFERENCE_EXPRESSION) { PsiJavaCodeReferenceElement ref = (PsiJavaCodeReferenceElement)SourceTreeToPsiMap.treeElementToPsi(element); final PsiClass refClass = element.getCopyableUserData(REFERENCED_CLASS_KEY); if (refClass != null) { element.putCopyableUserData(REFERENCED_CLASS_KEY, null); if (refClass.isPhysical() || !ref.isPhysical()) { PsiManager manager = refClass.getManager(); CodeStyleManagerEx codeStyleManager = (CodeStyleManagerEx)manager.getCodeStyleManager(); PsiElement refElement1 = ref.resolve(); try { if (refClass != refElement1 && !manager.areElementsEquivalent(refClass, refElement1)) { if (((CompositeElement)element).findChildByRole(ChildRole.QUALIFIER) == null) { // can restore only if short (otherwise qualifier should be already restored) ref = (PsiJavaCodeReferenceElement)ref.bindToElement(refClass); } } else { // shorten references to the same package and to inner classes that can be accessed by short name ref = (PsiJavaCodeReferenceElement)codeStyleManager.shortenClassReferences(ref, CodeStyleManagerEx.DO_NOT_ADD_IMPORTS); } element = (TreeElement)SourceTreeToPsiMap.psiElementToTree(ref); } catch (IncorrectOperationException e) { codeStyleManager.addImport(ref.getContainingFile(), refClass); // it may fail for local class, let's try for DummyHolder } } } } else if (element.getElementType() == ElementType.MODIFIER_LIST) { if (element.getUserData(INTERFACE_MODIFIERS_FLAG_KEY) != null) { element.putUserData(INTERFACE_MODIFIERS_FLAG_KEY, null); try { PsiModifierList modifierList = (PsiModifierList)SourceTreeToPsiMap.treeElementToPsi(element); if (element.getTreeParent().getElementType() == ElementType.FIELD) { modifierList.setModifierProperty(PsiModifier.PUBLIC, true); modifierList.setModifierProperty(PsiModifier.STATIC, true); modifierList.setModifierProperty(PsiModifier.FINAL, true); } else if (element.getTreeParent().getElementType() == ElementType.METHOD) { modifierList.setModifierProperty(PsiModifier.PUBLIC, true); modifierList.setModifierProperty(PsiModifier.ABSTRACT, true); } } catch (IncorrectOperationException e) { LOG.error(e); } } } } return element; } public static TreeElement copyElement(TreeElement original, CharTable table) { final TreeElement element = (TreeElement)original.clone(); final PsiManager manager = original.getManager(); final CharTable charTableByTree = SharedImplUtil.findCharTableByTree(original); registerLeafsInCharTab(table, element, charTableByTree); new DummyHolder(manager, element, null, table).getTreeElement(); encodeInformation(element, original); // CodeEditUtil.normalizeCloneIndent(element, original, table); CodeEditUtil.unindentSubtree(element, original, table); return element; } public static TreeElement copyToElement(PsiElement original) { final DummyHolder holder = new DummyHolder(original.getManager(), null); final FileElement holderElement = holder.getTreeElement(); final TreeElement treeElement = _copyToElement(original, holderElement.getCharTable()); // TreeElement treePrev = treeElement.getTreePrev(); // This is hack to support bug used in formater TreeUtil.addChildren(holderElement, treeElement); // treeElement.setTreePrev(treePrev); return treeElement; } private static TreeElement _copyToElement(PsiElement original, CharTable table) { LOG.assertTrue(original.isValid()); if (SourceTreeToPsiMap.hasTreeElement(original)) { return copyElement((TreeElement)SourceTreeToPsiMap.psiElementToTree(original), table); } else if (original instanceof PsiIdentifier) { final String text = original.getText(); return Factory.createLeafElement(IDENTIFIER, text.toCharArray(), 0, text.length(), -1, table); } else if (original instanceof PsiKeyword) { final String text = original.getText(); return Factory.createLeafElement(((PsiKeyword)original).getTokenType(), text.toCharArray(), 0, text.length(), -1, table); } else if (original instanceof PsiReferenceExpression) { TreeElement element = createReferenceExpression(original.getManager(), original.getText(), table); PsiElement refElement = ((PsiJavaCodeReferenceElement)original).resolve(); if (refElement instanceof PsiClass) { element.putCopyableUserData(REFERENCED_CLASS_KEY, (PsiClass)refElement); } return element; } else if (original instanceof PsiJavaCodeReferenceElement) { PsiElement refElement = ((PsiJavaCodeReferenceElement)original).resolve(); if (refElement instanceof PsiClass) { if (refElement instanceof PsiAnonymousClass) { PsiJavaCodeReferenceElement ref = ((PsiAnonymousClass)refElement).getBaseClassReference(); original = ref; refElement = ref.resolve(); } boolean isFQ = false; if (original instanceof PsiJavaCodeReferenceElementImpl) { int kind = ((PsiJavaCodeReferenceElementImpl)original).getKind(); switch (kind) { case PsiJavaCodeReferenceElementImpl.CLASS_OR_PACKAGE_NAME_KIND: case PsiJavaCodeReferenceElementImpl.CLASS_NAME_KIND: case PsiJavaCodeReferenceElementImpl.CLASS_IN_QUALIFIED_NEW_KIND: isFQ = false; break; case PsiJavaCodeReferenceElementImpl.CLASS_FQ_NAME_KIND: case PsiJavaCodeReferenceElementImpl.CLASS_FQ_OR_PACKAGE_NAME_KIND: isFQ = true; break; default: LOG.assertTrue(false); } } String text = isFQ ? ((PsiClass)refElement).getQualifiedName() : original.getText(); TreeElement element = createReference(original.getManager(), text, table); element.putCopyableUserData(REFERENCED_CLASS_KEY, (PsiClass)refElement); return element; } else if (refElement instanceof PsiPackage) { return createReference(original.getManager(), original.getText(), table); } else { return createReference(original.getManager(), original.getText(), table); } } else if (original instanceof PsiCompiledElement) { PsiElement sourceVersion = original.getNavigationElement(); if (sourceVersion != original) { return _copyToElement(sourceVersion, table); } ASTNode mirror = SourceTreeToPsiMap.psiElementToTree(((PsiCompiledElement)original).getMirror()); return _copyToElement(SourceTreeToPsiMap.treeElementToPsi(mirror), table); } else if (original instanceof PsiTypeElement) { PsiTypeElement typeElement = (PsiTypeElement)original; PsiType type = typeElement.getType(); if (type instanceof PsiEllipsisType) { TreeElement componentTypeCopy = _copyToElement( new LightTypeElement(original.getManager(), ((PsiEllipsisType)type).getComponentType()), table ); if (componentTypeCopy == null) return null; CompositeElement element = Factory.createCompositeElement(TYPE); TreeUtil.addChildren(element, componentTypeCopy); TreeUtil.addChildren(element, Factory.createLeafElement(ELLIPSIS, new char[]{'.', '.', '.'}, 0, 3, -1, table)); return element; } else if (type instanceof PsiArrayType) { TreeElement componentTypeCopy = _copyToElement( new LightTypeElement(original.getManager(), ((PsiArrayType)type).getComponentType()), table ); if (componentTypeCopy == null) return null; CompositeElement element = Factory.createCompositeElement(TYPE); TreeUtil.addChildren(element, componentTypeCopy); TreeUtil.addChildren(element, Factory.createLeafElement(LBRACKET, new char[]{'['}, 0, 1, -1, table)); TreeUtil.addChildren(element, Factory.createLeafElement(RBRACKET, new char[]{']'}, 0, 1, -1, table)); return element; } else if (type instanceof PsiPrimitiveType) { String text = typeElement.getText(); if (text.equals("null")) return null; Lexer lexer = new JavaLexer(LanguageLevel.JDK_1_3); lexer.start(text.toCharArray()); TreeElement keyword = ParseUtil.createTokenElement(lexer, table); CompositeElement element = Factory.createCompositeElement(TYPE); TreeUtil.addChildren(element, keyword); return element; } else if (type instanceof PsiWildcardType) { char[] buffer = original.getText().toCharArray(); return DeclarationParsing.parseTypeText(original.getManager(), buffer, 0, buffer.length, table); } else { PsiClassType classType = (PsiClassType)type; final PsiJavaCodeReferenceElement ref; if (classType instanceof PsiClassReferenceType) { ref = ((PsiClassReferenceType)type).getReference(); } else { final CompositeElement reference = createReference(original.getManager(), classType.getPresentableText(), table); final CompositeElement immediateTypeElement = Factory.createCompositeElement(TYPE); TreeUtil.addChildren(immediateTypeElement, reference); encodeInfoInTypeElement(immediateTypeElement, classType); return immediateTypeElement; } CompositeElement element = Factory.createCompositeElement(TYPE); TreeUtil.addChildren(element, _copyToElement(ref, table)); return element; } } else { LOG.error("ChangeUtil.copyToElement() unknown element " + original); return null; } } private static CompositeElement createReference(PsiManager manager, String text, CharTable table) { return Parsing.parseJavaCodeReferenceText(manager, text.toCharArray(), table); } private static TreeElement createReferenceExpression(PsiManager manager, String text, CharTable table) { return ExpressionParsing.parseExpressionText(manager, text.toCharArray(), 0, text.toCharArray().length, table); } private static void encodeInfoInTypeElement(ASTNode typeElement, PsiType type) { if (type instanceof PsiPrimitiveType) return; LOG.assertTrue(typeElement.getElementType() == TYPE); if (type instanceof PsiArrayType) { final ASTNode firstChild = typeElement.getFirstChildNode(); LOG.assertTrue(firstChild.getElementType() == TYPE); encodeInfoInTypeElement(firstChild, ((PsiArrayType)type).getComponentType()); return; } else if (type instanceof PsiWildcardType) { final PsiType bound = ((PsiWildcardType)type).getBound(); if (bound == null) return; final ASTNode lastChild = typeElement.getLastChildNode(); if (lastChild.getElementType() != TYPE) return; encodeInfoInTypeElement(lastChild, bound); } else if (type instanceof PsiCapturedWildcardType) { final PsiType bound = ((PsiCapturedWildcardType)type).getWildcard().getBound(); if (bound == null) return; final ASTNode lastChild = typeElement.getLastChildNode(); if (lastChild.getElementType() != TYPE) return; encodeInfoInTypeElement(lastChild, bound); } else if (type instanceof PsiIntersectionType) { encodeInfoInTypeElement(typeElement, ((PsiIntersectionType)type).getRepresentative()); return; } else { LOG.assertTrue(type instanceof PsiClassType); final PsiClassType classType = (PsiClassType)type; final PsiClassType.ClassResolveResult resolveResult = classType.resolveGenerics(); PsiClass referencedClass = resolveResult.getElement(); if (referencedClass == null) return; if (referencedClass instanceof PsiAnonymousClass) { encodeInfoInTypeElement(typeElement, ((PsiAnonymousClass)referencedClass).getBaseClassType()); } else { final ASTNode reference = typeElement.getFirstChildNode(); LOG.assertTrue(reference.getElementType() == JAVA_CODE_REFERENCE); encodeClassTypeInfoInReference((CompositeElement)reference, resolveResult.getElement(), resolveResult.getSubstitutor()); } } } private static void encodeClassTypeInfoInReference(CompositeElement reference, PsiClass referencedClass, PsiSubstitutor substitutor) { LOG.assertTrue(referencedClass != null); reference.putCopyableUserData(REFERENCED_CLASS_KEY, referencedClass); final PsiTypeParameterList typeParameterList = referencedClass.getTypeParameterList(); if (typeParameterList == null) return; final PsiTypeParameter[] typeParameters = typeParameterList.getTypeParameters(); if (typeParameters.length == 0) return; final ASTNode referenceParameterList = reference.findChildByRole(ChildRole.REFERENCE_PARAMETER_LIST); int index = 0; for (ASTNode child = referenceParameterList.getFirstChildNode(); child != null; child = child.getTreeNext()) { if (child.getElementType() == TYPE) { final PsiType substitutedType = substitutor.substitute(typeParameters[index]); if (substitutedType != null) { encodeInfoInTypeElement(child, substitutedType); } index++; } } final ASTNode qualifier = reference.findChildByRole(ChildRole.QUALIFIER); if (qualifier != null) { if (referencedClass.hasModifierProperty(PsiModifier.STATIC)) return; final PsiClass outerClass = referencedClass.getContainingClass(); if (outerClass != null) { encodeClassTypeInfoInReference((CompositeElement)qualifier, outerClass, substitutor); } } } private static final Key<PsiClass> REFERENCED_CLASS_KEY = Key.create("REFERENCED_CLASS_KEY"); private static final Key<Boolean> INTERFACE_MODIFIERS_FLAG_KEY = Key.create("INTERFACE_MODIFIERS_FLAG_KEY"); public static void addChildren(final ASTNode parent, ASTNode firstChild, final ASTNode lastChild, final ASTNode anchorBefore) { while (firstChild != lastChild) { final ASTNode next = firstChild.getTreeNext(); parent.addChild(firstChild, anchorBefore); firstChild = next; } } public static void replaceAll(LeafElement[] leafElements, LeafElement merged) { if (leafElements.length == 0) return; final CompositeElement parent = leafElements[0].getTreeParent(); if (LOG.isDebugEnabled()) { for (int i = 0; i < leafElements.length; i++) { final ASTNode leafElement = leafElements[i]; LOG.assertTrue(leafElement.getTreeParent() == parent); } } final PsiElement psiParent = SourceTreeToPsiMap.treeElementToPsi(parent); final PsiFile containingFile = psiParent.getContainingFile(); final PsiManagerImpl manager = (PsiManagerImpl)containingFile.getManager(); final PsiTreeChangeEventImpl event = new PsiTreeChangeEventImpl(manager); if (containingFile.isPhysical()) { event.setParent(psiParent); event.setFile(containingFile); event.setOffset(parent.getStartOffset()); event.setOldLength(parent.getTextLength()); manager.beforeChildrenChange(event); } TreeUtil.insertAfter(leafElements[0], merged); for (int i = 0; i < leafElements.length; i++) TreeUtil.remove(leafElements[i]); parent.subtreeChanged(); if (containingFile.isPhysical()) manager.childrenChanged(event); checkConsistency(containingFile); } public static int checkTextRanges(PsiElement root) { if (true) return 0; TextRange range = root.getTextRange(); int off = range.getStartOffset(); PsiElement[] children = root.getChildren(); if (children.length != 0) { for (int i = 0; i < children.length; i++) { PsiElement child = children[i]; off += checkTextRanges(child); } } else { off += root.getTextLength(); } LOG.assertTrue(off == range.getEndOffset()); String fileText = root.getContainingFile().getText(); LOG.assertTrue(root.getText().equals(fileText.substring(range.getStartOffset(), range.getEndOffset()))); if (root instanceof XmlTag) { XmlTagValue value = ((XmlTag)root).getValue(); TextRange textRange = value.getTextRange(); LOG.assertTrue(value.getText().equals(fileText.substring(textRange.getStartOffset(), textRange.getEndOffset()))); } return range.getLength(); } }
package controllers; import com.fasterxml.jackson.core.type.TypeReference; import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Injector; import io.sphere.sdk.categories.Category; import io.sphere.sdk.categories.CategoryTree; import io.sphere.sdk.client.PlayJavaClient; import io.sphere.sdk.client.PlayJavaClientImpl; import io.sphere.sdk.client.SphereRequestExecutor; import io.sphere.sdk.client.SphereRequestExecutorTestDouble; import io.sphere.sdk.queries.PagedQueryResult; import io.sphere.sdk.utils.JsonUtils; import play.Application; import play.Configuration; import plugins.Global; import play.test.FakeApplication; import play.test.WithApplication; import static play.test.Helpers.fakeApplication; public abstract class WithSunriseApplication extends WithApplication { @Override protected FakeApplication provideFakeApplication() { return fakeApplication(new Global() { @Override protected Injector createInjector(final Application app) { return Guice.createInjector(new AbstractModule() { @Override protected void configure() { bind(PlayJavaClient.class).toInstance(injectedClientInstance(app)); bind(CategoryTree.class).toInstance(injectedCategoryTree()); } }); } }); } private CategoryTree injectedCategoryTree() { final TypeReference<PagedQueryResult<Category>> typeReference = new TypeReference<PagedQueryResult<Category>>() { }; final PagedQueryResult<Category> categoryPagedQueryResult = JsonUtils.readObjectFromResource("categories.json", typeReference); return CategoryTree.of(categoryPagedQueryResult.getResults()); } protected PlayJavaClient injectedClientInstance(final Application app){ return new PlayJavaClientImpl(getConfiguration(app), getSphereRequestExecutor()); } protected SphereRequestExecutor getSphereRequestExecutor() { return new SphereRequestExecutorTestDouble() { }; } /** * Override this to add additional settings * @param app the application used * @return a configuration containing the {@code app} configuration values and overridden values */ protected Configuration getConfiguration(Application app) { return app.configuration(); } }
import org.simpleflatmapper.converter.ContextualConverterFactoryProducer; module org.simpleflatmapper.datastax { requires transitive org.simpleflatmapper.map; requires transitive org.simpleflatmapper.tuple; requires cassandra.driver.core; requires guava; exports org.simpleflatmapper.datastax; provides org.simpleflatmapper.reflect.meta.AliasProviderProducer with org.simpleflatmapper.datastax.impl.mapping.DatastaxAliasProviderFactory; provides ContextualConverterFactoryProducer with org.simpleflatmapper.datastax.impl.converter.DatastaxConverterFactoryProducer; }
package de.tsystems.mms.apm.performancesignature.dynatrace.rest; import de.tsystems.mms.apm.performancesignature.util.PerfSigUtils; import org.apache.commons.lang.StringUtils; import java.net.MalformedURLException; import java.net.URL; public class ManagementURLBuilder { private String serverAddress; private String parameters; public String getPostParameters() { return this.parameters; } public void setServerAddress(final String serverAddress) { this.serverAddress = serverAddress; } public URL serverVersionURL() { try { final String s = String.format("%1$s/rest/management/version", this.serverAddress); return new URL(s); } catch (MalformedURLException e) { e.printStackTrace(); } return null; } public URL reanalyzeSessionURL(final String sessionName) { try { return new URL(String.format("%1$s/rest/management/sessions/%2$s/reanalyze", this.serverAddress, PerfSigUtils.encodeString(sessionName))); } catch (MalformedURLException e) { e.printStackTrace(); } return null; } public URL reanalyzeSessionStatusURL(final String sessionName) { try { return new URL(String.format("%1$s/rest/management/sessions/%2$s/reanalyze/finished", this.serverAddress, PerfSigUtils.encodeString(sessionName))); } catch (MalformedURLException e) { e.printStackTrace(); } return null; } public URL storePurePathsURL(final String profileName, final String sessionName, final String timeframeStart, final String timeframeEnd, String recordingOption, final boolean sessionLocked, final boolean appendTimestamp) { if (StringUtils.isBlank(recordingOption)) { recordingOption = "all"; } try { return new URL(String.format("%1$s/rest/management/profiles/%2$s/storepurepaths?storedSessionName=%3$s&timeframeStart=%4$s&timeframeEnd=%5$s&" + "recordingOption=%6$s&isSessionLocked=%7$s&appendTimestamp=%8$s", this.serverAddress, PerfSigUtils.encodeString(profileName), PerfSigUtils.encodeString(sessionName), timeframeStart, timeframeEnd, recordingOption, sessionLocked, appendTimestamp)); } catch (MalformedURLException e) { e.printStackTrace(); } return null; } public URL startRecordingURL(final String profileName, final String sessionName, final String description, String recordingOption, final boolean sessionLocked, final boolean isNoTimestamp) { if (StringUtils.isBlank(recordingOption)) { recordingOption = "all"; } try { this.parameters = String.format("recordingOption=%1$s&isSessionLocked=%2$s&isTimeStampAllowed=%3$s&description=%4$s&presentableName=%5$s", recordingOption, sessionLocked, isNoTimestamp, StringUtils.isBlank(description) ? "" : PerfSigUtils.encodeString(description), StringUtils.isBlank(sessionName) ? PerfSigUtils.encodeString(profileName) : PerfSigUtils.encodeString(sessionName)); final String url = String.format("%1$s/rest/management/profiles/%2$s/startrecording", this.serverAddress, PerfSigUtils.encodeString(profileName)); return new URL(url); } catch (MalformedURLException e) { e.printStackTrace(); } return null; } public URL stopRecordingURL(final String profileName) { try { final String s = String.format("%1$s/rest/management/profiles/%2$s/stoprecording", this.serverAddress, PerfSigUtils.encodeString(profileName)); return new URL(s); } catch (MalformedURLException e) { e.printStackTrace(); } return null; } public URL listProfilesURL() { try { final String s = String.format("%1$s/rest/management/profiles/", this.serverAddress); return new URL(s); } catch (MalformedURLException e) { e.printStackTrace(); } return null; } public URL listConfigurationsURL(final String profileName) { try { final String s = String.format("%1$s/rest/management/profiles/%2$s/configurations", this.serverAddress, PerfSigUtils.encodeString(profileName)); return new URL(s); } catch (MalformedURLException e) { e.printStackTrace(); } return null; } public URL activateConfigurationURL(final String profileName, final String configuration) { try { final String s = String.format("%1$s/rest/management/profiles/%2$s/configurations/%3$s/activate", this.serverAddress, PerfSigUtils.encodeString(profileName), PerfSigUtils.encodeString(configuration)); return new URL(s); } catch (MalformedURLException e) { e.printStackTrace(); } return null; } public URL listAgentsURL() { try { final String s = String.format("%1$s/rest/management/agents", this.serverAddress); return new URL(s); } catch (MalformedURLException e) { e.printStackTrace(); } return null; } public URL hotSensorPlacementURL(final int agentId) { try { final String s = String.format("%1$s/rest/management/agents/%2$s/hotsensorplacement", this.serverAddress, PerfSigUtils.encodeString(String.valueOf(agentId))); return new URL(s); } catch (MalformedURLException e) { e.printStackTrace(); } return null; } public URL listSessionsURL() { try { final String s = String.format("%1$s/rest/management/sessions?type=purepath", this.serverAddress); return new URL(s); } catch (MalformedURLException e) { e.printStackTrace(); } return null; } public URL listDashboardsURL() { try { final String s = String.format("%1$s/rest/management/dashboards", this.serverAddress); return new URL(s); } catch (MalformedURLException e) { e.printStackTrace(); } return null; } public URL downloadSessionURL(final String sessionName) { try { final String s = String.format("%1$s/rest/management/sessions/%2$s/export", this.serverAddress, PerfSigUtils.encodeString(sessionName)); return new URL(s); } catch (MalformedURLException e) { e.printStackTrace(); } return null; } public StringBuilder resourceDumpURL(final String agentName, final String hostName, final int processId, final boolean sessionLocked) { StringBuilder builder = new StringBuilder(); builder.append(String.format("agentName=%1$s&isSessionLocked=%2$s&hostName=%3$s&processId=%4$s", agentName, sessionLocked ? "true" : "false", hostName, String.valueOf(processId))); return builder; } public URL memoryDumpStatusURL(final String profileName, final String memoryDumpName) { try { return new URL(String.format("%1$s/rest/management/profiles/%2$s/memorydumpcreated/%3$s", this.serverAddress, PerfSigUtils.encodeString(profileName), PerfSigUtils.encodeString(memoryDumpName))); } catch (MalformedURLException e) { e.printStackTrace(); } return null; } public URL memoryDumpURL(final String profileName, final String agentName, final String hostName, final int processId, String dumpType, final boolean sessionLocked, final boolean captureStrings, final boolean capturePrimitives, final boolean autoPostProcess, final boolean dogc) { if (StringUtils.isBlank(dumpType)) { dumpType = "simple"; } try { StringBuilder builder = resourceDumpURL(agentName, hostName, processId, sessionLocked); builder.append("&type=").append(dumpType); builder.append(captureStrings ? "&capturestrings=true" : ""); builder.append(capturePrimitives ? "&captureprimitives=true" : ""); builder.append(autoPostProcess ? "&autopostprocess=true" : ""); builder.append(dogc ? "&dogc=true" : ""); this.parameters = builder.toString(); return new URL(String.format("%1$s/rest/management/profiles/%2$s/memorydump", this.serverAddress, PerfSigUtils.encodeString(profileName))); } catch (MalformedURLException e) { e.printStackTrace(); } return null; } public URL threadDumpStatusURL(final String profileName, final String threadDumpName) { try { return new URL(String.format("%1$s/rest/management/profiles/%2$s/threaddumpcreated/%3$s", this.serverAddress, PerfSigUtils.encodeString(profileName), PerfSigUtils.encodeString(threadDumpName))); } catch (MalformedURLException e) { e.printStackTrace(); } return null; } public URL threadDumpURL(final String profileName, final String agentName, final String hostName, final int processId, final boolean sessionLocked) { try { this.parameters = String.format("agentName=%1$s&isSessionLocked=%2$s&hostName=%3$s&processId=%4$s", agentName, sessionLocked, hostName, processId); return new URL(String.format("%1$s/rest/management/profiles/%2$s/threaddump", this.serverAddress, PerfSigUtils.encodeString(profileName))); } catch (MalformedURLException e) { e.printStackTrace(); } return null; } public URL registerTestRunURL(final String profileName) { try { return new URL(String.format("%1$s/rest/management/profiles/%2$s/testruns", this.serverAddress, PerfSigUtils.encodeString(profileName))); } catch (MalformedURLException e) { e.printStackTrace(); } return null; } public URL testRunDetailsURL(final String profileName, final String testRunID) { try { return new URL(String.format("%1$s/rest/management/profiles/%2$s/testruns/%3$s.xml", this.serverAddress, PerfSigUtils.encodeString(profileName), testRunID)); } catch (MalformedURLException e) { e.printStackTrace(); } return null; } }
package io.github.kkysen.quicktrip.apis.google.geocoding.exists; import io.github.kkysen.quicktrip.apis.QueryField; import io.github.kkysen.quicktrip.apis.google.geocoding.exists.response.AddressExistsOnly; import io.github.kkysen.quicktrip.apis.google.maps.GoogleMapsApiRequest; import java.io.IOException; import java.nio.file.Path; import lombok.RequiredArgsConstructor; /** * * * @author Khyber Sen */ @RequiredArgsConstructor public class AddressExistsRequest extends GoogleMapsApiRequest<AddressExistsOnly> { private final @QueryField String address; private final @QueryField String fields = "status"; @Override protected String getRequestType() { return "geocode"; } @Override protected Class<? extends AddressExistsOnly> getResponseClass() { return AddressExistsOnly.class; } @Override protected Path getRelativeCachePath() { return super.getRelativeCachePath().resolve("geocoding").resolve("exists"); } public static boolean exists(final String address) throws IOException { if (address.isEmpty()) { return false; } return new AddressExistsRequest(address).getResponse().exists(); } }
package org.asciidoc.intellij.editor.notification; import com.intellij.ide.util.PropertiesComponent; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.editor.ex.EditorSettingsExternalizable; import com.intellij.openapi.fileEditor.FileEditor; import com.intellij.openapi.project.DumbAware; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Key; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.ui.EditorNotificationPanel; import com.intellij.ui.EditorNotifications; import com.intellij.util.PatternUtil; import org.asciidoc.intellij.file.AsciiDocFileType; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import static com.intellij.ide.actions.ShowSettingsUtilImpl.showSettingsDialog; /** * Notify user that permanent softwrap is available. */ public class EnableSoftWrapNotificationProvider extends EditorNotifications.Provider<EditorNotificationPanel> implements DumbAware { private static final Key<EditorNotificationPanel> KEY = Key.create("Enable Softwrap for Asciidoctor"); private static final String SOFTWRAP_AVAILABLE = "asciidoc.softwrap.enable"; @NotNull @Override public Key<EditorNotificationPanel> getKey() { return KEY; } @Nullable @Override public EditorNotificationPanel createNotificationPanel(@NotNull VirtualFile file, @NotNull final FileEditor fileEditor, @NotNull Project project) { // only in AsciiDoc files if (file.getFileType() != AsciiDocFileType.INSTANCE) { return null; } // only if not previously disabled if (PropertiesComponent.getInstance().getBoolean(SOFTWRAP_AVAILABLE)) { return null; } // don't show if soft wrap is already enabled by default for this file if (isSoftWrapEnabledByDefaultForFile(file)) { return null; } final EditorNotificationPanel panel = new EditorNotificationPanel(); panel.setText("Writing AsciiDoc works best with soft-wrap enabled. Do you want to enable it by default?"); panel.createActionLabel("Yes, take me to the Soft Wrap settings!", () -> ApplicationManager.getApplication().invokeLater(() -> { if (!project.isDisposed()) { showSettingsDialog(project, "preferences.editor", "soft wraps"); } })); panel.createActionLabel("Do not show again", () -> { PropertiesComponent.getInstance().setValue(SOFTWRAP_AVAILABLE, true); EditorNotifications.updateAll(); }); return panel; } /** * Check if the file given as parameter would open as soft-wrapped by default. * Logic is inspired by {@link com.intellij.openapi.editor.impl.SettingsImpl#isUseSoftWraps()}. */ private boolean isSoftWrapEnabledByDefaultForFile(VirtualFile file) { boolean softWrapsEnabled = EditorSettingsExternalizable.getInstance().isUseSoftWraps(); if (!softWrapsEnabled) { return softWrapsEnabled; } String masks = EditorSettingsExternalizable.getInstance().getSoftWrapFileMasks(); if (masks.trim().equals("*")) { return true; } return file != null && fileNameMatches(file.getName(), masks); } private static boolean fileNameMatches(@NotNull String fileName, @NotNull String globPatterns) { for (String p : globPatterns.split(";", -1)) { String pTrimmed = p.trim(); if (!pTrimmed.isEmpty() && PatternUtil.fromMask(pTrimmed).matcher(fileName).matches()) { return true; } } return false; } }
package org.synyx.sybil.bricklet.output.ledstrip.api; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.hateoas.Link; import org.springframework.hateoas.Resources; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ExceptionHandler; 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.ResponseBody; import org.springframework.web.bind.annotation.RestController; import org.synyx.sybil.api.PatchResource; import org.synyx.sybil.api.SinglePatchResource; import org.synyx.sybil.bricklet.output.ledstrip.Color; import org.synyx.sybil.bricklet.output.ledstrip.LEDStrip; import org.synyx.sybil.bricklet.output.ledstrip.LEDStripService; import org.synyx.sybil.bricklet.output.ledstrip.Sprite1D; import org.synyx.sybil.bricklet.output.ledstrip.database.LEDStripDomain; import java.util.ArrayList; import java.util.List; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn; //TODO: Add 404 for non-existing LED Strips! /** * ConfigurationLEDStripsController. * * @author Tobias Theuer - theuer@synyx.de */ @RestController @RequestMapping("/configuration/ledstrips") public class ConfigurationLEDStripController { private LEDStripService ledStripService; @Autowired public ConfigurationLEDStripController(LEDStripService ledStripService) { this.ledStripService = ledStripService; } @ResponseBody @RequestMapping(method = RequestMethod.GET, produces = { "application/hal+json" }) public Resources<LEDStripResource> ledstrips() { List<LEDStripDomain> ledStrips = ledStripService.getAllDomains(); List<LEDStripResource> resources = new ArrayList<>(); List<Link> links = new ArrayList<>(); Link self = linkTo(ConfigurationLEDStripController.class).withSelfRel(); links.add(self); for (LEDStripDomain ledStripDomain : ledStrips) { self = linkTo(methodOn(ConfigurationLEDStripController.class).ledStrip(ledStripDomain.getName())) .withSelfRel(); LEDStripResource resource = new LEDStripResource(ledStripDomain, self); resources.add(resource); } return new Resources<>(resources, links); } @ResponseBody @RequestMapping(value = "/{name}", method = RequestMethod.GET, produces = { "application/hal+json" }) public LEDStripResource ledStrip(@PathVariable String name) { LEDStripDomain ledStripDomain = ledStripService.getDomain(name); List<Link> links = new ArrayList<>(); links.add(linkTo(methodOn(ConfigurationLEDStripController.class).ledStrip(ledStripDomain.getName())) .withSelfRel()); links.add(linkTo(methodOn(ConfigurationLEDStripController.class).getDisplay(ledStripDomain.getName())).withRel( "display")); return new LEDStripResource(ledStripDomain, links); } @ResponseBody @RequestMapping(value = "/{name}/display", method = RequestMethod.GET, produces = { "application/hal+json" }) public DisplayResource getDisplay(@PathVariable String name) { LEDStripDomain ledStripDomain = ledStripService.getDomain(name); LEDStrip ledStrip = ledStripService.getLEDStrip(ledStripDomain); Link self = linkTo(methodOn(ConfigurationLEDStripController.class).getDisplay(ledStripDomain.getName())) .withSelfRel(); DisplayResource display = new DisplayResource(); display.add(self); display.setPixels(ledStrip.getPixelBuffer()); display.setBrightness(ledStrip.getBrightness()); return display; } @ResponseBody @RequestMapping(value = "/{name}/display", method = RequestMethod.PUT, produces = { "application/hal+json" }) public DisplayResource setDisplay(@PathVariable String name, @RequestBody DisplayResource display) { LEDStripDomain ledStripDomain = ledStripService.getDomain(name); LEDStrip ledStrip = ledStripService.getLEDStrip(ledStripDomain); if (display.getPixels() != null && display.getPixels().size() > 0) { Sprite1D pixels = new Sprite1D(display.getPixels().size(), "setDisplay", display.getPixels()); ledStrip.drawSprite(pixels, 0); } display.setPixels(ledStrip.getPixelBuffer()); if (display.getBrightness() != null) { ledStrip.setBrightness(display.getBrightness()); } else { display.setBrightness(1.0); } ledStrip.updateDisplay(); Link self = linkTo(methodOn(ConfigurationLEDStripController.class).getDisplay(ledStripDomain.getName())) .withSelfRel(); display.add(self); return display; } @ResponseBody @RequestMapping(value = "/{name}/display", method = RequestMethod.PATCH, produces = { "application/hal+json" }) public DisplayResource updateDisplay(@PathVariable String name, @RequestBody PatchResource input) throws Exception { LEDStripDomain ledStripDomain = ledStripService.getDomain(name); LEDStrip ledStrip = ledStripService.getLEDStrip(ledStripDomain); for (SinglePatchResource patch : input.getPatches()) { switch (patch.getAction()) { case "set": switch (patch.getTarget()) { case "brightness": ledStrip.setBrightness(Double.parseDouble(patch.getValues().get(0))); break; case "fill": { List<String> values = patch.getValues(); int red = Integer.parseInt(values.get(0)); int green = Integer.parseInt(values.get(1)); int blue = Integer.parseInt(values.get(2)); Color color = new Color(red, green, blue); ledStrip.setFill(color); break; } case "pixel": { int index = Integer.parseInt(patch.getValues().get(0)); int red = Integer.parseInt(patch.getValues().get(1)); int green = Integer.parseInt(patch.getValues().get(2)); int blue = Integer.parseInt(patch.getValues().get(3)); Color color = new Color(red, green, blue); ledStrip.setPixel(index, color); break; } default: throw new Exception("Unknown target for action set"); } break; case "update": switch (patch.getTarget()) { case "display": ledStrip.updateDisplay(); break; default: throw new Exception("Unknown target for action update"); } break; case "move": switch (patch.getTarget()) { case "pixels": { Sprite1D pixelbuffer = new Sprite1D(ledStrip.getLength(), "pixelbuffer", ledStrip.getPixelBuffer()); int offset = Integer.parseInt(patch.getValues().get(0)); if (offset < 0) { offset = ledStrip.getLength() + offset; } if (offset > ledStrip.getLength()) { offset = offset - ledStrip.getLength(); } ledStrip.drawSprite(pixelbuffer, offset, true); } } break; default: throw new Exception("Unknown action"); } } Link self = linkTo(methodOn(ConfigurationLEDStripController.class).getDisplay(ledStripDomain.getName())) .withSelfRel(); DisplayResource display = new DisplayResource(); display.add(self); display.setPixels(ledStrip.getPixelBuffer()); display.setBrightness(ledStrip.getBrightness()); return display; } // TODO: Non-existing LED strips give a NullPointerException. Should be 404! @ResponseBody @ExceptionHandler(Exception.class) public ResponseEntity<String> errorHandler(Exception e) { String error = "Error parsing input: " + e.toString(); return new ResponseEntity<>(error, HttpStatus.BAD_REQUEST); } }
package org.mtransit.parser.ca_whistler_transit_system_bus; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang3.StringUtils; import org.mtransit.commons.StrategicMappingCommons; import org.mtransit.parser.CleanUtils; import org.mtransit.parser.DefaultAgencyTools; import org.mtransit.parser.Pair; import org.mtransit.parser.SplitUtils; import org.mtransit.parser.SplitUtils.RouteTripSpec; import org.mtransit.parser.Utils; import org.mtransit.parser.gtfs.data.GCalendar; import org.mtransit.parser.gtfs.data.GCalendarDate; import org.mtransit.parser.gtfs.data.GRoute; import org.mtransit.parser.gtfs.data.GSpec; import org.mtransit.parser.gtfs.data.GStop; import org.mtransit.parser.gtfs.data.GTrip; import org.mtransit.parser.gtfs.data.GTripStop; import org.mtransit.parser.mt.data.MAgency; import org.mtransit.parser.mt.data.MRoute; import org.mtransit.parser.mt.data.MTrip; import org.mtransit.parser.mt.data.MTripStop; // https://bctransit.com/*/footer/open-data public class WhistlerTransitSystemBusAgencyTools extends DefaultAgencyTools { public static void main(String[] args) { if (args == null || args.length == 0) { args = new String[3]; args[0] = "input/gtfs.zip"; args[1] = "../../mtransitapps/ca-whistler-transit-system-bus-android/res/raw/"; args[2] = ""; // files-prefix } new WhistlerTransitSystemBusAgencyTools().start(args); } private HashSet<String> serviceIds; @Override public void start(String[] args) { System.out.printf("\nGenerating Whistler Transit System bus data..."); long start = System.currentTimeMillis(); this.serviceIds = extractUsefulServiceIds(args, this, true); super.start(args); System.out.printf("\nGenerating Whistler Transit System bus data... DONE in %s.\n", Utils.getPrettyDuration(System.currentTimeMillis() - start)); } @Override public boolean excludingAll() { return this.serviceIds != null && this.serviceIds.isEmpty(); } @Override public boolean excludeCalendar(GCalendar gCalendar) { if (this.serviceIds != null) { return excludeUselessCalendar(gCalendar, this.serviceIds); } return super.excludeCalendar(gCalendar); } @Override public boolean excludeCalendarDate(GCalendarDate gCalendarDates) { if (this.serviceIds != null) { return excludeUselessCalendarDate(gCalendarDates, this.serviceIds); } return super.excludeCalendarDate(gCalendarDates); } private static final String INCLUDE_AGENCY_ID = "1"; // Whistler Transit System only @Override public boolean excludeRoute(GRoute gRoute) { if (!INCLUDE_AGENCY_ID.equals(gRoute.getAgencyId())) { return true; } return super.excludeRoute(gRoute); } @Override public boolean excludeTrip(GTrip gTrip) { if (this.serviceIds != null) { return excludeUselessTrip(gTrip, this.serviceIds); } return super.excludeTrip(gTrip); } @Override public Integer getAgencyRouteType() { return MAgency.ROUTE_TYPE_BUS; } private static final Pattern DIGITS = Pattern.compile("[\\d]+"); private static final long RID_ENDS_WITH_W = 23_000_000L; private static final long RID_ENDS_WITH_X = 24_000_000L; @Override public long getRouteId(GRoute gRoute) { if (!Utils.isDigitsOnly(gRoute.getRouteShortName())) { Matcher matcher = DIGITS.matcher(gRoute.getRouteShortName()); if (matcher.find()) { int digits = Integer.parseInt(matcher.group()); String rsn = gRoute.getRouteShortName().toLowerCase(Locale.ENGLISH); if (rsn.endsWith("w")) { return digits + RID_ENDS_WITH_W; } else if (rsn.endsWith("x")) { return digits + RID_ENDS_WITH_X; } System.out.printf("\nUnexptected route ID for %s!\n", gRoute); System.exit(-1); return -1l; } } return Long.parseLong(gRoute.getRouteShortName()); // use route short name as route ID } @Override public String getRouteLongName(GRoute gRoute) { String routeLongName = gRoute.getRouteLongName(); if (StringUtils.isEmpty(routeLongName)) { routeLongName = gRoute.getRouteDesc(); } routeLongName = CleanUtils.cleanSlashes(routeLongName); routeLongName = CleanUtils.cleanNumbers(routeLongName); routeLongName = CleanUtils.cleanStreetTypes(routeLongName); return CleanUtils.cleanLabel(routeLongName); } private static final String AGENCY_COLOR_GREEN = "34B233";// GREEN (from PDF Corporate Graphic Standards) private static final String AGENCY_COLOR_BLUE = "002C77"; // BLUE (from PDF Corporate Graphic Standards) private static final String AGENCY_COLOR = AGENCY_COLOR_GREEN; @Override public String getAgencyColor() { return AGENCY_COLOR; } @Override public String getRouteColor(GRoute gRoute) { String routeColor = gRoute.getRouteColor(); if ("000000".equals(routeColor)) { routeColor = null; // ignore black } if (StringUtils.isEmpty(routeColor)) { if (!Utils.isDigitsOnly(gRoute.getRouteShortName())) { if ("20X".equalsIgnoreCase(gRoute.getRouteShortName())) { return "004B8D"; } else if ("25X".equalsIgnoreCase(gRoute.getRouteShortName())) { return "EC1A8D"; } } int rsn = Integer.parseInt(gRoute.getRouteShortName()); switch (rsn) { // @formatter:off case 4: return "00A84F"; case 5: return "8D0B3A"; case 6: return "FFC10E"; case 7: return "B2A97E"; case 8: return "F399C0"; case 10: return AGENCY_COLOR_BLUE; // TODO case 20: return "004B8D"; case 21: return "F7921E"; case 25: return "EC1A8D"; case 30: return "00ADEE"; case 31: return "A54499"; case 32: return "8BC53F"; case 99: return "5D86A0"; // @formatter:on default: System.out.printf("\nUnexpected route color %s!\n", gRoute); System.exit(-1); return null; } } return super.getRouteColor(gRoute); } private static HashMap<Long, RouteTripSpec> ALL_ROUTE_TRIPS2; static { HashMap<Long, RouteTripSpec> map2 = new HashMap<Long, RouteTripSpec>(); map2.put(31L, new RouteTripSpec(31L, StrategicMappingCommons.NORTH, MTrip.HEADSIGN_TYPE_STRING, "Alpine", StrategicMappingCommons.SOUTH, MTrip.HEADSIGN_TYPE_STRING, "Village") .addTripSort(StrategicMappingCommons.NORTH, Arrays.asList(new String[] { Stops.ALL_STOPS.get("102714"), Stops2.ALL_STOPS2.get("102714"), // Gondola Exchange Bay 3 Stops.ALL_STOPS.get("102622"), Stops2.ALL_STOPS2.get("102622"), // Alpine at Rainbow (WB) })) .addTripSort(StrategicMappingCommons.SOUTH, Arrays.asList(new String[] { Stops.ALL_STOPS.get("102622"), Stops2.ALL_STOPS2.get("102622"), // Alpine at Rainbow (WB) Stops.ALL_STOPS.get("102714"), Stops2.ALL_STOPS2.get("102714"), // Gondola Exchange Bay 3 })) .compileBothTripSort()); ALL_ROUTE_TRIPS2 = map2; } @Override public int compareEarly(long routeId, List<MTripStop> list1, List<MTripStop> list2, MTripStop ts1, MTripStop ts2, GStop ts1GStop, GStop ts2GStop) { if (ALL_ROUTE_TRIPS2.containsKey(routeId)) { return ALL_ROUTE_TRIPS2.get(routeId).compare(routeId, list1, list2, ts1, ts2, ts1GStop, ts2GStop, this); } return super.compareEarly(routeId, list1, list2, ts1, ts2, ts1GStop, ts2GStop); } @Override public ArrayList<MTrip> splitTrip(MRoute mRoute, GTrip gTrip, GSpec gtfs) { if (ALL_ROUTE_TRIPS2.containsKey(mRoute.getId())) { return ALL_ROUTE_TRIPS2.get(mRoute.getId()).getAllTrips(); } return super.splitTrip(mRoute, gTrip, gtfs); } @Override public Pair<Long[], Integer[]> splitTripStop(MRoute mRoute, GTrip gTrip, GTripStop gTripStop, ArrayList<MTrip> splitTrips, GSpec routeGTFS) { if (ALL_ROUTE_TRIPS2.containsKey(mRoute.getId())) { return SplitUtils.splitTripStop(mRoute, gTrip, gTripStop, routeGTFS, ALL_ROUTE_TRIPS2.get(mRoute.getId()), this); } return super.splitTripStop(mRoute, gTrip, gTripStop, splitTrips, routeGTFS); } @Override public void setTripHeadsign(MRoute mRoute, MTrip mTrip, GTrip gTrip, GSpec gtfs) { if (ALL_ROUTE_TRIPS2.containsKey(mRoute.getId())) { return; // split } if (mRoute.getId() == 4L) { if (gTrip.getDirectionId() == 1) { // Marketplace - Free Shuttle - COUNTERCLOCKWISE if ("Marketplace - Free Shuttle".equalsIgnoreCase(gTrip.getTripHeadsign())) { mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.COUNTERCLOCKWISE); return; } } } else if (mRoute.getId() == 5L) { if (gTrip.getDirectionId() == 0) { // Upper Vlg - Benchlands - CLOCKWISE if ("Upper Vlg - Benchlands - Free Shuttle".equalsIgnoreCase(gTrip.getTripHeadsign())) { mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.CLOCKWISE); return; } } } else if (mRoute.getId() == 6L) { if (gTrip.getDirectionId() == 1) { // Tapley''s-Blueberry - COUNTERCLOCKWISE if ("Tapley's-Blueberry".equalsIgnoreCase(gTrip.getTripHeadsign())) { mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.COUNTERCLOCKWISE); return; } } } else if (mRoute.getId() == 7L) { if (gTrip.getDirectionId() == 0) { // Staff Housing - CLOCKWISE if ("Staff Housing".equalsIgnoreCase(gTrip.getTripHeadsign())) { mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.CLOCKWISE); return; } } } else if (mRoute.getId() == 8L) { if (isGoodEnoughAccepted()) { if (gTrip.getDirectionId() == 1) { // ??? - CLOCKWISE if ("Lost Lake Shuttle - Free Service".equalsIgnoreCase(gTrip.getTripHeadsign())) { mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.CLOCKWISE); return; } } } } else if (mRoute.getId() == 10L) { if (gTrip.getDirectionId() == 0) { // Emerald - NORTH if (Arrays.asList( "Valley Express to Emerald", "Emerald Via Function Jct-Valley Exp" ).contains(gTrip.getTripHeadsign())) { mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.NORTH); return; } } else if (gTrip.getDirectionId() == 1) { // Cheakamus - SOUTH if (Arrays.asList( "Valley Express to Cheakamus", "Cheakamus Via Function Jct-Valley Exp" ).contains(gTrip.getTripHeadsign())) { mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.SOUTH); return; } } } else if (mRoute.getId() == 20L) { if (gTrip.getDirectionId() == 0) { // Village - NORTH if ("To Village".equalsIgnoreCase(gTrip.getTripHeadsign()) || "To Village-Via Function Jct".equalsIgnoreCase(gTrip.getTripHeadsign())) { mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.NORTH); return; } } else if (gTrip.getDirectionId() == 1) { // Cheakamus - SOUTH if ("Cheakamus".equalsIgnoreCase(gTrip.getTripHeadsign()) || "Cheakamus- Via Function Jct".equalsIgnoreCase(gTrip.getTripHeadsign())) { mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.SOUTH); return; } } } else if (mRoute.getId() == 20L + RID_ENDS_WITH_X) { // 20X if (gTrip.getDirectionId() == 0) { // Village - NORTH if ("Village Exp".equalsIgnoreCase(gTrip.getTripHeadsign()) || "Village Exp- Via Function Jct".equalsIgnoreCase(gTrip.getTripHeadsign())) { mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.NORTH); return; } } else if (gTrip.getDirectionId() == 1) { // Cheakamus - SOUTH if ("Cheakamus Exp".equalsIgnoreCase(gTrip.getTripHeadsign()) || "Cheakamus Exp- Via Function Jct".equalsIgnoreCase(gTrip.getTripHeadsign())) { mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.SOUTH); return; } } } else if (mRoute.getId() == 21L) { if (gTrip.getDirectionId() == 0) { // Village - NORTH if ("To Village".equalsIgnoreCase(gTrip.getTripHeadsign())) { mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.NORTH); return; } } else if (gTrip.getDirectionId() == 1) { // Spring Creek - SOUTH if ("Spring Creek".equalsIgnoreCase(gTrip.getTripHeadsign())) { mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.SOUTH); return; } } } else if (mRoute.getId() == 25L) { if (gTrip.getDirectionId() == 0) { // Village - NORTH if ("To Village".equalsIgnoreCase(gTrip.getTripHeadsign())) { mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.NORTH); return; } } else if (gTrip.getDirectionId() == 1) { // Whistler Creek - SOUTH if ("Whistler Creek".equalsIgnoreCase(gTrip.getTripHeadsign())) { mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.SOUTH); return; } } } else if (mRoute.getId() == 30L) { if (gTrip.getDirectionId() == 0) { // Alpine/Emerald - NORTH if ("Alpine/Emerald- Via Nesters".equalsIgnoreCase(gTrip.getTripHeadsign()) || "Emerald- Via Nesters".equalsIgnoreCase(gTrip.getTripHeadsign())) { mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.NORTH); return; } } else if (gTrip.getDirectionId() == 1) { // Village - SOUTH if ("To Village".equalsIgnoreCase(gTrip.getTripHeadsign()) || "To Village- Via Alpine".equalsIgnoreCase(gTrip.getTripHeadsign())) { mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.SOUTH); return; } } } else if (mRoute.getId() == 32L) { if (gTrip.getDirectionId() == 0) { // Emerald - NORTH if ("Emerald- Via Spruve Grv".equalsIgnoreCase(gTrip.getTripHeadsign())) { mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.NORTH); return; } } else if (gTrip.getDirectionId() == 1) { // Village - SOUTH if ("To Village".equalsIgnoreCase(gTrip.getTripHeadsign())) { mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.SOUTH); return; } } } else if (mRoute.getId() == 99L) { if (gTrip.getDirectionId() == 0) { // Pemberton - NORTH if ("Commuter- To Pemberton".equalsIgnoreCase(gTrip.getTripHeadsign())) { mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.NORTH); return; } } else if (gTrip.getDirectionId() == 1) { // Whistler - SOUTH if ("Commuter- to Whistler".equalsIgnoreCase(gTrip.getTripHeadsign())) { mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.SOUTH); return; } } } System.out.printf("\n%s: Unexpected trips headsign for %s!\n", mTrip.getRouteId(), gTrip); System.exit(-1); return; } @Override public boolean mergeHeadsign(MTrip mTrip, MTrip mTripToMerge) { if (MTrip.mergeEmpty(mTrip, mTripToMerge)) { return true; } List<String> headsignsValues = Arrays.asList(mTrip.getHeadsignValue(), mTripToMerge.getHeadsignValue()); if (mTrip.getRouteId() == 1L) { if (Arrays.asList( "Alpine", "Emerald", "Vlg" ).containsAll(headsignsValues)) { mTrip.setHeadsignString("Emerald", mTrip.getHeadsignId()); return true; } else if (Arrays.asList( "Cheakamus", "Spg Crk", "Vlg", "Whistler Crk" ).containsAll(headsignsValues)) { mTrip.setHeadsignString("Cheakamus", mTrip.getHeadsignId()); return true; } } else if (mTrip.getRouteId() == 2L) { if (Arrays.asList( "Cheakamus", "Function / Cheakamus" ).containsAll(headsignsValues)) { mTrip.setHeadsignString("Cheakamus", mTrip.getHeadsignId()); return true; } } else if (mTrip.getRouteId() == 20L) { if (Arrays.asList( "Vlg", "Vlg" + "-Via Function Jct", "Via Function Jct" ).containsAll(headsignsValues)) { mTrip.setHeadsignString("Vlg", mTrip.getHeadsignId()); return true; } else if (Arrays.asList( "Cheakamus", "Cheakamus" + "- Via Function Jct", "Via Function Jct" ).containsAll(headsignsValues)) { mTrip.setHeadsignString("Cheakamus", mTrip.getHeadsignId()); return true; } } else if (mTrip.getRouteId() == 20L + RID_ENDS_WITH_X) { // 20X if (Arrays.asList( "Vlg Exp", "Vlg Exp" + "- Via Function Jct", "Via Function Jct" ).containsAll(headsignsValues)) { mTrip.setHeadsignString("Vlg Exp", mTrip.getHeadsignId()); return true; } else if (Arrays.asList( "Cheakamus Exp", "Cheakamus Exp" + "- Via Function Jct", "Via Function Jct" ).containsAll(headsignsValues)) { mTrip.setHeadsignString("Cheakamus Exp", mTrip.getHeadsignId()); return true; } } else if (mTrip.getRouteId() == 30L) { if (Arrays.asList( "Alpine / Emerald", "Alpine / Emerald" + "- Via Nesters", "Emerald", "Emerald" + "- Via Nesters" ).containsAll(headsignsValues)) { mTrip.setHeadsignString("Emerald", mTrip.getHeadsignId()); return true; } else if (Arrays.asList( "Vlg", "Vlg" + "- Via Alpine", "Via Alpine" ).containsAll(headsignsValues)) { mTrip.setHeadsignString("Vlg", mTrip.getHeadsignId()); return true; } } System.out.printf("\nUnexpected trips to merge %s & %s.\n", mTrip, mTripToMerge); System.exit(-1); return false; } private static final String EXCH = "Exch"; private static final Pattern EXCHANGE = Pattern.compile("((^|\\W){1}(exchange)(\\W|$){1})", Pattern.CASE_INSENSITIVE); private static final String EXCHANGE_REPLACEMENT = "$2" + EXCH + "$4"; private static final Pattern ENDS_WITH_VIA = Pattern.compile("([\\s]?[\\-]?[\\s]?via .*$)", Pattern.CASE_INSENSITIVE); private static final Pattern STARTS_WITH_TO = Pattern.compile("(^(.* to|to) )", Pattern.CASE_INSENSITIVE); private static final Pattern FREE_SHUTTLE_SERVICE = Pattern.compile("((^|\\W){1}(free (service|shuttle))(\\W|$){1})", Pattern.CASE_INSENSITIVE); private static final String FREE_SHUTTLE_SERVICE_REPLACEMENT = "$2" + StringUtils.EMPTY + "$5"; private static final Pattern EXPRESS_ = Pattern.compile("((^|\\W){1}(express|exp)(\\W|$){1})", Pattern.CASE_INSENSITIVE); private static final String EXPRESS_REPLACEMENT = "$2" + StringUtils.EMPTY + "$4"; private static final Pattern ENDS_WITH_DASH = Pattern.compile("([\\s]*[\\-]+[\\s]*$)", Pattern.CASE_INSENSITIVE); @Override public String cleanTripHeadsign(String tripHeadsign) { if (Utils.isUppercaseOnly(tripHeadsign, true, true)) { tripHeadsign = tripHeadsign.toLowerCase(Locale.ENGLISH); } tripHeadsign = EXCHANGE.matcher(tripHeadsign).replaceAll(EXCHANGE_REPLACEMENT); tripHeadsign = FREE_SHUTTLE_SERVICE.matcher(tripHeadsign).replaceAll(FREE_SHUTTLE_SERVICE_REPLACEMENT); tripHeadsign = EXPRESS_.matcher(tripHeadsign).replaceAll(EXPRESS_REPLACEMENT); tripHeadsign = ENDS_WITH_VIA.matcher(tripHeadsign).replaceAll(StringUtils.EMPTY); tripHeadsign = STARTS_WITH_TO.matcher(tripHeadsign).replaceAll(StringUtils.EMPTY); tripHeadsign = ENDS_WITH_DASH.matcher(tripHeadsign).replaceAll(StringUtils.EMPTY); tripHeadsign = CleanUtils.CLEAN_AND.matcher(tripHeadsign).replaceAll(CleanUtils.CLEAN_AND_REPLACEMENT); tripHeadsign = CleanUtils.CLEAN_PARENTHESE1.matcher(tripHeadsign).replaceAll(CleanUtils.CLEAN_PARENTHESE1_REPLACEMENT); tripHeadsign = CleanUtils.CLEAN_PARENTHESE2.matcher(tripHeadsign).replaceAll(CleanUtils.CLEAN_PARENTHESE2_REPLACEMENT); tripHeadsign = CleanUtils.cleanSlashes(tripHeadsign); tripHeadsign = CleanUtils.cleanStreetTypes(tripHeadsign); tripHeadsign = CleanUtils.cleanNumbers(tripHeadsign); return CleanUtils.cleanLabel(tripHeadsign); } private static final Pattern STARTS_WITH_IMPL = Pattern.compile("(^(\\(\\-IMPL\\-\\)))", Pattern.CASE_INSENSITIVE); private static final Pattern STARTS_WITH_BOUND = Pattern.compile("(^(east|west|north|south)bound)", Pattern.CASE_INSENSITIVE); private static final Pattern AT = Pattern.compile("((^|\\W){1}(at)(\\W|$){1})", Pattern.CASE_INSENSITIVE); private static final String AT_REPLACEMENT = "$2/$4"; @Override public String cleanStopName(String gStopName) { gStopName = STARTS_WITH_IMPL.matcher(gStopName).replaceAll(StringUtils.EMPTY); gStopName = STARTS_WITH_BOUND.matcher(gStopName).replaceAll(StringUtils.EMPTY); gStopName = AT.matcher(gStopName).replaceAll(AT_REPLACEMENT); gStopName = EXCHANGE.matcher(gStopName).replaceAll(EXCHANGE_REPLACEMENT); gStopName = CleanUtils.cleanStreetTypes(gStopName); gStopName = CleanUtils.cleanNumbers(gStopName); return CleanUtils.cleanLabel(gStopName); } @Override public int getStopId(GStop gStop) { return Integer.parseInt(gStop.getStopCode()); // use stop code as stop ID } }
package org.mtransit.parser.ca_whistler_transit_system_bus; import java.util.HashSet; import java.util.regex.Pattern; import org.apache.commons.lang3.StringUtils; import org.mtransit.parser.DefaultAgencyTools; import org.mtransit.parser.Utils; import org.mtransit.parser.gtfs.data.GCalendar; import org.mtransit.parser.gtfs.data.GCalendarDate; import org.mtransit.parser.gtfs.data.GRoute; import org.mtransit.parser.gtfs.data.GSpec; import org.mtransit.parser.gtfs.data.GTrip; import org.mtransit.parser.mt.data.MAgency; import org.mtransit.parser.mt.data.MDirectionType; import org.mtransit.parser.mt.data.MRoute; import org.mtransit.parser.CleanUtils; import org.mtransit.parser.mt.data.MTrip; // http://bctransit.com/*/footer/open-data public class WhistlerTransitSystemBusAgencyTools extends DefaultAgencyTools { public static void main(String[] args) { if (args == null || args.length == 0) { args = new String[3]; args[0] = "input/gtfs.zip"; args[1] = "../../mtransitapps/ca-whistler-transit-system-bus-android/res/raw/"; args[2] = ""; // files-prefix } new WhistlerTransitSystemBusAgencyTools().start(args); } private HashSet<String> serviceIds; @Override public void start(String[] args) { System.out.printf("\nGenerating Whistler Transit System bus data..."); long start = System.currentTimeMillis(); this.serviceIds = extractUsefulServiceIds(args, this, true); super.start(args); System.out.printf("\nGenerating Whistler Transit System bus data... DONE in %s.\n", Utils.getPrettyDuration(System.currentTimeMillis() - start)); } private static final String INCLUDE_ONLY_SERVICE_ID_CONTAINS = null; private static final String INCLUDE_ONLY_SERVICE_ID_CONTAINS2 = null; private static final String INCLUDE_ONLY_SERVICE_ID_CONTAINS3 = null; @Override public boolean excludeCalendar(GCalendar gCalendar) { if (INCLUDE_ONLY_SERVICE_ID_CONTAINS != null && !gCalendar.getServiceId().contains(INCLUDE_ONLY_SERVICE_ID_CONTAINS) && INCLUDE_ONLY_SERVICE_ID_CONTAINS2 != null && !gCalendar.getServiceId().contains(INCLUDE_ONLY_SERVICE_ID_CONTAINS2) && INCLUDE_ONLY_SERVICE_ID_CONTAINS3 != null && !gCalendar.getServiceId().contains(INCLUDE_ONLY_SERVICE_ID_CONTAINS3)) { return true; } if (this.serviceIds != null) { return excludeUselessCalendar(gCalendar, this.serviceIds); } return super.excludeCalendar(gCalendar); } @Override public boolean excludeCalendarDate(GCalendarDate gCalendarDates) { if (INCLUDE_ONLY_SERVICE_ID_CONTAINS != null && !gCalendarDates.getServiceId().contains(INCLUDE_ONLY_SERVICE_ID_CONTAINS) && INCLUDE_ONLY_SERVICE_ID_CONTAINS2 != null && !gCalendarDates.getServiceId().contains(INCLUDE_ONLY_SERVICE_ID_CONTAINS2) && INCLUDE_ONLY_SERVICE_ID_CONTAINS3 != null && !gCalendarDates.getServiceId().contains(INCLUDE_ONLY_SERVICE_ID_CONTAINS3)) { return true; } if (this.serviceIds != null) { return excludeUselessCalendarDate(gCalendarDates, this.serviceIds); } return super.excludeCalendarDate(gCalendarDates); } private static final String INCLUDE_AGENCY_ID = "3"; // Whistler Transit System only @Override public boolean excludeRoute(GRoute gRoute) { if (!INCLUDE_AGENCY_ID.equals(gRoute.getAgencyId())) { return true; } return super.excludeRoute(gRoute); } @Override public boolean excludeTrip(GTrip gTrip) { if (INCLUDE_ONLY_SERVICE_ID_CONTAINS != null && !gTrip.getServiceId().contains(INCLUDE_ONLY_SERVICE_ID_CONTAINS) && INCLUDE_ONLY_SERVICE_ID_CONTAINS2 != null && !gTrip.getServiceId().contains(INCLUDE_ONLY_SERVICE_ID_CONTAINS2) && INCLUDE_ONLY_SERVICE_ID_CONTAINS3 != null && !gTrip.getServiceId().contains(INCLUDE_ONLY_SERVICE_ID_CONTAINS3)) { return true; } if (this.serviceIds != null) { return excludeUselessTrip(gTrip, this.serviceIds); } return super.excludeTrip(gTrip); } @Override public Integer getAgencyRouteType() { return MAgency.ROUTE_TYPE_BUS; } @Override public long getRouteId(GRoute gRoute) { return Long.parseLong(gRoute.getRouteShortName()); // use route short name as route ID } @Override public String getRouteLongName(GRoute gRoute) { String routeLongName = gRoute.getRouteLongName(); routeLongName = CleanUtils.cleanSlashes(routeLongName); routeLongName = CleanUtils.cleanNumbers(routeLongName); routeLongName = CleanUtils.cleanStreetTypes(routeLongName); return CleanUtils.cleanLabel(routeLongName); } private static final String AGENCY_COLOR_GREEN = "34B233";// GREEN (from PDF Corporate Graphic Standards) private static final String AGENCY_COLOR_BLUE = "002C77"; // BLUE (from PDF Corporate Graphic Standards) private static final String AGENCY_COLOR = AGENCY_COLOR_GREEN; @Override public String getAgencyColor() { return AGENCY_COLOR; } private static final String COLOR_F78B1F = "F78B1F"; private static final String COLOR_004B8D = "004B8D"; private static final String COLOR_8CC63F = "8CC63F"; private static final String COLOR_4F6F19 = "4F6F19"; private static final String COLOR_8D0B3A = "8D0B3A"; private static final String COLOR_FFC20E = "FFC20E"; private static final String COLOR_B2A97E = "B2A97E"; private static final String COLOR_77AD98 = "77AD98"; private static final String COLOR_5D86BF = "5D86BF"; @Override public String getRouteColor(GRoute gRoute) { if (StringUtils.isEmpty(gRoute.getRouteColor())) { int rsn = Integer.parseInt(gRoute.getRouteShortName()); switch (rsn) { // @formatter:off case 1: return COLOR_F78B1F; case 2: return COLOR_004B8D; case 3: return COLOR_8CC63F; case 4: return COLOR_4F6F19; case 5: return COLOR_8D0B3A; case 6: return COLOR_FFC20E; case 7: return COLOR_B2A97E; case 8: return COLOR_77AD98; case 99: return COLOR_5D86BF; // @formatter:on default: return AGENCY_COLOR_BLUE; } } return super.getRouteColor(gRoute); } @Override public void setTripHeadsign(MRoute mRoute, MTrip mTrip, GTrip gTrip, GSpec gtfs) { if (mRoute.getId() == 1l) { if (gTrip.getDirectionId() == 0) { mTrip.setHeadsignDirection(MDirectionType.NORTH); return; } else if (gTrip.getDirectionId() == 1) { mTrip.setHeadsignDirection(MDirectionType.SOUTH); return; } } else if (mRoute.getId() == 2l) { if (gTrip.getDirectionId() == 0) { mTrip.setHeadsignDirection(MDirectionType.NORTH); return; } else if (gTrip.getDirectionId() == 1) { mTrip.setHeadsignDirection(MDirectionType.SOUTH); return; } } mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), gTrip.getDirectionId()); } private static final String EXCH = "Exch"; private static final Pattern EXCHANGE = Pattern.compile("((^|\\W){1}(exchange)(\\W|$){1})", Pattern.CASE_INSENSITIVE); private static final String EXCHANGE_REPLACEMENT = "$2" + EXCH + "$4"; private static final Pattern ENDS_WITH_VIA = Pattern.compile("( via .*$)", Pattern.CASE_INSENSITIVE); private static final Pattern STARTS_WITH_TO = Pattern.compile("(^.* to )", Pattern.CASE_INSENSITIVE); private static final Pattern AND = Pattern.compile("( and )", Pattern.CASE_INSENSITIVE); private static final String AND_REPLACEMENT = " & "; private static final Pattern CLEAN_P1 = Pattern.compile("[\\s]*\\([\\s]*"); private static final String CLEAN_P1_REPLACEMENT = " ("; private static final Pattern CLEAN_P2 = Pattern.compile("[\\s]*\\)[\\s]*"); private static final String CLEAN_P2_REPLACEMENT = ") "; @Override public String cleanTripHeadsign(String tripHeadsign) { tripHeadsign = EXCHANGE.matcher(tripHeadsign).replaceAll(EXCHANGE_REPLACEMENT); tripHeadsign = ENDS_WITH_VIA.matcher(tripHeadsign).replaceAll(StringUtils.EMPTY); tripHeadsign = STARTS_WITH_TO.matcher(tripHeadsign).replaceAll(StringUtils.EMPTY); tripHeadsign = AND.matcher(tripHeadsign).replaceAll(AND_REPLACEMENT); tripHeadsign = CLEAN_P1.matcher(tripHeadsign).replaceAll(CLEAN_P1_REPLACEMENT); tripHeadsign = CLEAN_P2.matcher(tripHeadsign).replaceAll(CLEAN_P2_REPLACEMENT); tripHeadsign = CleanUtils.cleanStreetTypes(tripHeadsign); tripHeadsign = CleanUtils.cleanNumbers(tripHeadsign); return CleanUtils.cleanLabel(tripHeadsign); } private static final Pattern STARTS_WITH_BOUND = Pattern.compile("(^(east|west|north|south)bound)", Pattern.CASE_INSENSITIVE); private static final Pattern AT = Pattern.compile("((^|\\W){1}(at)(\\W|$){1})", Pattern.CASE_INSENSITIVE); private static final String AT_REPLACEMENT = "$2/$4"; @Override public String cleanStopName(String gStopName) { gStopName = STARTS_WITH_BOUND.matcher(gStopName).replaceAll(StringUtils.EMPTY); gStopName = AT.matcher(gStopName).replaceAll(AT_REPLACEMENT); gStopName = EXCHANGE.matcher(gStopName).replaceAll(EXCHANGE_REPLACEMENT); gStopName = CleanUtils.cleanStreetTypes(gStopName); gStopName = CleanUtils.cleanNumbers(gStopName); return CleanUtils.cleanLabel(gStopName); } }
package net.fortuna.ical4j.model.component; import java.io.IOException; import java.util.Iterator; import net.fortuna.ical4j.model.Component; import net.fortuna.ical4j.model.ComponentList; import net.fortuna.ical4j.model.DateTime; import net.fortuna.ical4j.model.Dur; import net.fortuna.ical4j.model.Period; import net.fortuna.ical4j.model.PeriodList; import net.fortuna.ical4j.model.Property; import net.fortuna.ical4j.model.PropertyList; import net.fortuna.ical4j.model.ValidationException; import net.fortuna.ical4j.model.parameter.FbType; import net.fortuna.ical4j.model.property.Contact; import net.fortuna.ical4j.model.property.DtEnd; import net.fortuna.ical4j.model.property.DtStamp; import net.fortuna.ical4j.model.property.DtStart; import net.fortuna.ical4j.model.property.Duration; import net.fortuna.ical4j.model.property.FreeBusy; import net.fortuna.ical4j.model.property.Organizer; import net.fortuna.ical4j.model.property.Uid; import net.fortuna.ical4j.model.property.Url; import net.fortuna.ical4j.util.CompatibilityHints; import net.fortuna.ical4j.util.PropertyValidator; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class VFreeBusy extends CalendarComponent { private static final long serialVersionUID = 1046534053331139832L; private transient Log log = LogFactory.getLog(VFreeBusy.class); /** * Default constructor. */ public VFreeBusy() { super(VFREEBUSY); getProperties().add(new DtStamp()); } /** * Constructor. * @param properties a list of properties */ public VFreeBusy(final PropertyList properties) { super(VFREEBUSY, properties); } /** * Constructs a new VFreeBusy instance with the specified start and end boundaries. This constructor should be used * for requesting Free/Busy time for a specified period. * @param startDate the starting boundary for the VFreeBusy * @param endDate the ending boundary for the VFreeBusy */ public VFreeBusy(final DateTime start, final DateTime end) { this(); // dtstart MUST be specified in UTC.. getProperties().add(new DtStart(start, true)); // dtend MUST be specified in UTC.. getProperties().add(new DtEnd(end, true)); } /** * Constructs a new VFreeBusy instance with the specified start and end boundaries. This constructor should be used * for requesting Free/Busy time for a specified duration in given period defined by the start date and end date. * @param startDate the starting boundary for the VFreeBusy * @param endDate the ending boundary for the VFreeBusy * @param duration the length of the period being requested */ public VFreeBusy(final DateTime start, final DateTime end, final Dur duration) { this(); // dtstart MUST be specified in UTC.. getProperties().add(new DtStart(start, true)); // dtend MUST be specified in UTC.. getProperties().add(new DtEnd(end, true)); getProperties().add(new Duration(duration)); } /** * Constructs a new VFreeBusy instance representing a reply to the specified VFREEBUSY request according to the * specified list of components. * If the request argument has its duration set, then the result * represents a list of <em>free</em> times (that is, parameter FBTYPE * is set to FbType.FREE). * If the request argument does not have its duration set, then the result * represents a list of <em>busy</em> times. * @param request a VFREEBUSY request * @param components a component list used to initialise busy time */ public VFreeBusy(final VFreeBusy request, final ComponentList components) { this(); DtStart start = (DtStart) request.getProperty(Property.DTSTART); DtEnd end = (DtEnd) request.getProperty(Property.DTEND); Duration duration = (Duration) request.getProperty(Property.DURATION); // dtstart MUST be specified in UTC.. getProperties().add(new DtStart(start.getDate(), true)); // dtend MUST be specified in UTC.. getProperties().add(new DtEnd(end.getDate(), true)); if (duration != null) { getProperties().add(new Duration(duration.getDuration())); // Initialise with all free time of at least the specified // duration.. DateTime freeStart = new DateTime(start.getDate()); DateTime freeEnd = new DateTime(end.getDate()); FreeBusy fb = createFreeTime(freeStart, freeEnd, duration .getDuration(), components); if (fb != null && !fb.getPeriods().isEmpty()) { getProperties().add(fb); } } else { // initialise with all busy time for the specified period.. DateTime busyStart = new DateTime(start.getDate()); DateTime busyEnd = new DateTime(end.getDate()); FreeBusy fb = createBusyTime(busyStart, busyEnd, components); if (fb != null && !fb.getPeriods().isEmpty()) { getProperties().add(fb); } } } /** * Create a FREEBUSY property representing the busy time for the specified component list. If the component is not * applicable to FREEBUSY time, or if the component is outside the bounds of the start and end dates, null is * returned. If no valid busy periods are identified in the component an empty FREEBUSY property is returned (i.e. * empty period list). * @param component a component to base the FREEBUSY property on * @return a FreeBusy instance or null if the component is not applicable */ private FreeBusy createBusyTime(final DateTime start, final DateTime end, final ComponentList components) { PeriodList periods = getConsumedTime(components, start, end); // periods must be in UTC time for freebusy.. periods.setUtc(true); for (Iterator i = periods.iterator(); i.hasNext();) { Period period = (Period) i.next(); // check if period outside bounds.. if (period.getStart().after(end) || period.getEnd().before(start)) { periods.remove(period); } } return new FreeBusy(periods); } /** * Create a FREEBUSY property representing the free time available of the specified duration for the given list of * components. component. If the component is not applicable to FREEBUSY time, or if the component is outside the * bounds of the start and end dates, null is returned. If no valid busy periods are identified in the component an * empty FREEBUSY property is returned (i.e. empty period list). * @param start * @param end * @param duration * @param components * @return */ private FreeBusy createFreeTime(final DateTime start, final DateTime end, final Dur duration, final ComponentList components) { FreeBusy fb = new FreeBusy(); fb.getParameters().add(FbType.FREE); PeriodList periods = getConsumedTime(components, start, end); // debugging.. if (log.isDebugEnabled()) { log.debug("Busy periods: " + periods); } DateTime lastPeriodEnd = null; // where no time is consumed set the last period end as the range start.. if (periods.isEmpty()) { lastPeriodEnd = new DateTime(start); } for (Iterator i = periods.iterator(); i.hasNext();) { Period period = (Period) i.next(); // check if period outside bounds.. if (period.getStart().after(end) || period.getEnd().before(start)) { continue; } // create a dummy last period end if first period starts after the start date // (i.e. there is a free time gap between the start and the first period). if (lastPeriodEnd == null && period.getStart().after(start)) { lastPeriodEnd = new DateTime(start); } // calculate duration between this period start and last period end.. if (lastPeriodEnd != null) { Duration freeDuration = new Duration(lastPeriodEnd, period .getStart()); if (freeDuration.getDuration().compareTo(duration) >= 0) { fb.getPeriods().add( new Period(lastPeriodEnd, freeDuration .getDuration())); } } lastPeriodEnd = period.getEnd(); } // calculate duration between last period end and end .. if (lastPeriodEnd != null) { Duration freeDuration = new Duration(lastPeriodEnd, end); if (freeDuration.getDuration().compareTo(duration) >= 0) { fb.getPeriods().add( new Period(lastPeriodEnd, freeDuration.getDuration())); } } return fb; } /** * Creates a list of periods representing the time consumed by the specified list of components. * @param components * @return */ private PeriodList getConsumedTime(final ComponentList components, final DateTime rangeStart, final DateTime rangeEnd) { PeriodList periods = new PeriodList(); for (Iterator i = components.iterator(); i.hasNext();) { Component component = (Component) i.next(); // only events consume time.. if (component instanceof VEvent) { periods.addAll(((VEvent) component).getConsumedTime(rangeStart, rangeEnd)); } } return periods.normalise(); } /* * (non-Javadoc) * @see net.fortuna.ical4j.model.Component#validate(boolean) */ public final void validate(final boolean recurse) throws ValidationException { if (!CompatibilityHints .isHintEnabled(CompatibilityHints.KEY_RELAXED_VALIDATION)) { // From "4.8.4.7 Unique Identifier": // Conformance: The property MUST be specified in the "VEVENT", "VTODO", // "VJOURNAL" or "VFREEBUSY" calendar components. PropertyValidator.getInstance().assertOne(Property.UID, getProperties()); // From "4.8.7.2 Date/Time Stamp": // Conformance: This property MUST be included in the "VEVENT", "VTODO", // "VJOURNAL" or "VFREEBUSY" calendar components. PropertyValidator.getInstance().assertOne(Property.DTSTAMP, getProperties()); } PropertyValidator validator = PropertyValidator.getInstance(); /* * ; the following are optional, ; but MUST NOT occur more than once contact / dtstart / dtend / duration / * dtstamp / organizer / uid / url / */ validator.assertOneOrLess(Property.CONTACT, getProperties()); validator.assertOneOrLess(Property.DTSTART, getProperties()); validator.assertOneOrLess(Property.DTEND, getProperties()); validator.assertOneOrLess(Property.DURATION, getProperties()); validator.assertOneOrLess(Property.DTSTAMP, getProperties()); validator.assertOneOrLess(Property.ORGANIZER, getProperties()); validator.assertOneOrLess(Property.UID, getProperties()); validator.assertOneOrLess(Property.URL, getProperties()); /* * ; the following are optional, ; and MAY occur more than once attendee / comment / freebusy / rstatus / x-prop */ /* * The recurrence properties ("RRULE", "EXRULE", "RDATE", "EXDATE") are not permitted within a "VFREEBUSY" * calendar component. Any recurring events are resolved into their individual busy time periods using the * "FREEBUSY" property. */ validator.assertNone(Property.RRULE, getProperties()); validator.assertNone(Property.EXRULE, getProperties()); validator.assertNone(Property.RDATE, getProperties()); validator.assertNone(Property.EXDATE, getProperties()); // DtEnd value must be later in time that DtStart.. DtStart dtStart = (DtStart) getProperty(Property.DTSTART); DtEnd dtEnd = (DtEnd) getProperty(Property.DTEND); if (dtStart != null && dtEnd != null && !dtStart.getDate().before(dtEnd.getDate())) { throw new ValidationException("Property [" + Property.DTEND + "] must be later in time than [" + Property.DTSTART + "]"); } if (recurse) { validateProperties(); } } /** * @return */ public final Contact getContact() { return (Contact) getProperty(Property.CONTACT); } /** * @return */ public final DtStart getStartDate() { return (DtStart) getProperty(Property.DTSTART); } /** * @return */ public final DtEnd getEndDate() { return (DtEnd) getProperty(Property.DTEND); } /** * @return */ public final Duration getDuration() { return (Duration) getProperty(Property.DURATION); } /** * @return */ public final DtStamp getDateStamp() { return (DtStamp) getProperty(Property.DTSTAMP); } /** * @return */ public final Organizer getOrganizer() { return (Organizer) getProperty(Property.ORGANIZER); } /** * @return */ public final Url getUrl() { return (Url) getProperty(Property.URL); } /** * Returns the UID property of this component if available. * @return a Uid instance, or null if no UID property exists */ public final Uid getUid() { return (Uid) getProperty(Property.UID); } /** * @param stream * @throws IOException * @throws ClassNotFoundException */ private void readObject(java.io.ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); log = LogFactory.getLog(VFreeBusy.class); } }
package protocolsupport.protocol.transformer.middlepacket.clientbound.play; import java.io.IOException; import java.util.ArrayList; import protocolsupport.protocol.PacketDataSerializer; import protocolsupport.protocol.storage.LocalStorage; import protocolsupport.protocol.transformer.middlepacket.ClientBoundMiddlePacket; public abstract class MiddleWorldParticle<T> extends ClientBoundMiddlePacket<T> { protected int type; protected boolean longdist; protected float x; protected float y; protected float z; protected float offX; protected float offY; protected float offZ; protected float speed; protected int count; protected ArrayList<Integer> adddata = new ArrayList<Integer>(); @Override public void readFromServerData(PacketDataSerializer serializer) throws IOException { type = serializer.readInt(); longdist = serializer.readBoolean(); x = serializer.readFloat(); y = serializer.readFloat(); z = serializer.readFloat(); offX = serializer.readFloat(); offY = serializer.readFloat(); offZ = serializer.readFloat(); speed = serializer.readFloat(); count = serializer.readInt(); while (serializer.isReadable()) { adddata.add(serializer.readVarInt()); } } @Override public void handle(LocalStorage storage) { } }
package net.fortuna.ical4j.model.component; import java.util.Date; import java.util.Iterator; import net.fortuna.ical4j.model.Component; import net.fortuna.ical4j.model.ComponentList; import net.fortuna.ical4j.model.Period; import net.fortuna.ical4j.model.PeriodList; import net.fortuna.ical4j.model.Property; import net.fortuna.ical4j.model.PropertyList; import net.fortuna.ical4j.model.ValidationException; import net.fortuna.ical4j.model.parameter.FbType; import net.fortuna.ical4j.model.property.DtEnd; import net.fortuna.ical4j.model.property.DtStamp; import net.fortuna.ical4j.model.property.DtStart; import net.fortuna.ical4j.model.property.Duration; import net.fortuna.ical4j.model.property.FreeBusy; import net.fortuna.ical4j.util.PropertyValidator; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Defines an iCalendar VFREEBUSY component. * * <pre> * 4.6.4 Free/Busy Component * * Component Name: VFREEBUSY * * Purpose: Provide a grouping of component properties that describe * either a request for free/busy time, describe a response to a request * for free/busy time or describe a published set of busy time. * * Formal Definition: A &quot;VFREEBUSY&quot; calendar component is defined by the * following notation: * * freebusyc = &quot;BEGIN&quot; &quot;:&quot; &quot;VFREEBUSY&quot; CRLF * fbprop * &quot;END&quot; &quot;:&quot; &quot;VFREEBUSY&quot; CRLF * * fbprop = *( * * ; the following are optional, * ; but MUST NOT occur more than once * * contact / dtstart / dtend / duration / dtstamp / * organizer / uid / url / * * ; the following are optional, * ; and MAY occur more than once * * attendee / comment / freebusy / rstatus / x-prop * * ) * </pre> * * Example 1 - Requesting all busy time slots for a given period: * * <pre><code> * // request all busy time between today and 1 week from now.. * java.util.Calendar cal = java.util.Calendar.getInstance(); * Date start = cal.getTime(); * cal.add(java.util.Calendar.WEEK_OF_YEAR, 1); * Date end = cal.getTime(); * * VFreeBusy request = new VFreeBusy(start, end); * </code></pre> * * Example 2 - Publishing all busy time slots for the period requested: * * <pre><code> * VFreeBusy reply = new VFreeBusy(request, calendar.getComponents()); * </code></pre> * * Example 3 - Requesting all free time slots for a given period of at least the * specified duration: * * <pre><code> * // request all free time between today and 1 week from now of * // duration 2 hours or more.. * java.util.Calendar cal = java.util.Calendar.getInstance(); * Date start = cal.getTime(); * cal.add(java.util.Calendar.WEEK_OF_YEAR, 1); * Date end = cal.getTime(); * * VFreeBusy request = new VFreeBusy(start, end, 2 * 60 * 60 * 1000); * </code></pre> * * @author Ben Fortuna */ public class VFreeBusy extends Component { private static Log log = LogFactory.getLog(VFreeBusy.class); /** * Default constructor. */ public VFreeBusy() { super(VFREEBUSY); } /** * Constructor. * * @param properties * a list of properties */ public VFreeBusy(final PropertyList properties) { super(VFREEBUSY, properties); } /** * Constructs a new VFreeBusy instance with the specified start and end * boundaries. This constructor should be used for requesting Free/Busy time * for a specified period. * * @param startDate * the starting boundary for the VFreeBusy * @param endDate * the ending boundary for the VFreeBusy */ public VFreeBusy(final Date startDate, final Date endDate) { this(); // dtstart MUST be specified in UTC.. getProperties().add(new DtStart(startDate, true)); // dtend MUST be specified in UTC.. getProperties().add(new DtEnd(endDate, true)); getProperties().add(new DtStamp(new Date())); } /** * Constructs a new VFreeBusy instance with the specified start and end * boundaries. This constructor should be used for requesting Free/Busy time * for a specified duration in given period defined by the start date and * end date. * * @param startDate * the starting boundary for the VFreeBusy * @param endDate * the ending boundary for the VFreeBusy * @param duration * the length of the period being requested */ public VFreeBusy(final Date startDate, final Date endDate, final long duration) { this(); // dtstart MUST be specified in UTC.. getProperties().add(new DtStart(startDate, true)); // dtend MUST be specified in UTC.. getProperties().add(new DtEnd(endDate, true)); getProperties().add(new Duration(duration)); getProperties().add(new DtStamp(new Date())); } /** * Constructs a new VFreeBusy instance represeting a reply to the specified * VFREEBUSY request according to the specified list of components. * * @param request * a VFREEBUSY request * @param components * a component list used to initialise busy time */ public VFreeBusy(final VFreeBusy request, final ComponentList components) { this(); DtStart start = (DtStart) request.getProperties().getProperty(Property.DTSTART); DtEnd end = (DtEnd) request.getProperties().getProperty(Property.DTEND); Duration duration = (Duration) request.getProperties().getProperty(Property.DURATION); // dtstart MUST be specified in UTC.. getProperties().add(new DtStart(start.getTime(), true)); // dtend MUST be specified in UTC.. getProperties().add(new DtEnd(end.getTime(), true)); getProperties().add(new DtStamp(new Date())); if (duration != null) { getProperties().add(new Duration(duration.getDuration())); // Initialise with all free time of at least the specified // duration.. FreeBusy fb = createFreeTime(start.getTime(), end.getTime(), duration.getDuration(), components); if (fb != null && !fb.getPeriods().isEmpty()) { getProperties().add(fb); } } else { // initialise with all busy time for the specified period.. FreeBusy fb = createBusyTime(start.getTime(), end.getTime(), components); if (fb != null && !fb.getPeriods().isEmpty()) { getProperties().add(fb); } } } /** * Create a FREEBUSY property representing the busy time for the specified * component list. If the component is not applicable to FREEBUSY time, or if the * component is outside the bounds of the start and end dates, null is * returned. If no valid busy periods are identified in the component an * empty FREEBUSY property is returned (i.e. empty period list). * * @param component * a component to base the FREEBUSY property on * @return a FreeBusy instance or null if the component is not applicable */ private FreeBusy createBusyTime(final Date startDate, final Date endDate, final ComponentList components) { PeriodList periods = getConsumedTime(components, startDate, endDate); for (Iterator i = periods.iterator(); i.hasNext();) { Period period = (Period) i.next(); // check if period outside bounds.. if (period.getStart().after(endDate) || period.getEnd().before(startDate)) { periods.remove(period); } } return new FreeBusy(periods); } /** * Create a FREEBUSY property representing the free time available of the specified * duration for the given list of components. * component. If the component is not applicable to FREEBUSY time, or if the * component is outside the bounds of the start and end dates, null is * returned. If no valid busy periods are identified in the component an * empty FREEBUSY property is returned (i.e. empty period list). * @param start * @param end * @param duration * @param components * @return */ private FreeBusy createFreeTime(final Date start, final Date end, final long duration, final ComponentList components) { FreeBusy fb = new FreeBusy(); fb.getParameters().add(FbType.FREE); PeriodList periods = getConsumedTime(components, start, end); // debugging.. if (log.isDebugEnabled()) { log.debug("Busy periods: " + periods); } Date lastPeriodEnd = null; for (Iterator i = periods.iterator(); i.hasNext();) { Period period = (Period) i.next(); // check if period outside bounds.. if (period.getStart().after(end) || period.getEnd().before(start)) { continue; } // create a dummy last period end if first period starts after the start date // (i.e. there is a free time gap between the start and the first period). if (lastPeriodEnd == null && period.getStart().after(start)) { lastPeriodEnd = start; } // calculate duration between this period start and last period end.. if (lastPeriodEnd != null) { Duration freeDuration = new Duration(lastPeriodEnd, period.getStart()); if (freeDuration.getDuration() >= duration) { fb.getPeriods().add(new Period(lastPeriodEnd, freeDuration.getDuration())); } } lastPeriodEnd = period.getEnd(); } return fb; } /** * Creates a list of periods representing the time consumed by the specified * list of components. * @param components * @return */ private PeriodList getConsumedTime(final ComponentList components, final Date rangeStart, final Date rangeEnd) { PeriodList periods = new PeriodList(); for (Iterator i = components.iterator(); i.hasNext();) { Component component = (Component) i.next(); // only events consume time.. if (component instanceof VEvent) { periods.addAll(((VEvent) component).getConsumedTime(rangeStart, rangeEnd)); } } return periods.normalise(); } /* * (non-Javadoc) * * @see net.fortuna.ical4j.model.Component#validate(boolean) */ public final void validate(final boolean recurse) throws ValidationException { PropertyValidator validator = PropertyValidator.getInstance(); /* * ; the following are optional, ; but MUST NOT occur more than once * * contact / dtstart / dtend / duration / dtstamp / organizer / uid / * url / */ validator.validateOneOrLess(Property.CONTACT, getProperties()); validator.validateOneOrLess(Property.DTSTART, getProperties()); validator.validateOneOrLess(Property.DTEND, getProperties()); validator.validateOneOrLess(Property.DURATION, getProperties()); validator.validateOneOrLess(Property.DTSTAMP, getProperties()); validator.validateOneOrLess(Property.ORGANIZER, getProperties()); validator.validateOneOrLess(Property.UID, getProperties()); validator.validateOneOrLess(Property.URL, getProperties()); /* * ; the following are optional, ; and MAY occur more than once * * attendee / comment / freebusy / rstatus / x-prop */ /* * The recurrence properties ("RRULE", "EXRULE", "RDATE", "EXDATE") are * not permitted within a "VFREEBUSY" calendar component. Any recurring * events are resolved into their individual busy time periods using the * "FREEBUSY" property. */ validator.validateNone(Property.RRULE, getProperties()); validator.validateNone(Property.EXRULE, getProperties()); validator.validateNone(Property.RDATE, getProperties()); validator.validateNone(Property.EXDATE, getProperties()); // DtEnd value must be later in time that DtStart.. DtStart dtStart = (DtStart) getProperties().getProperty(Property.DTSTART); DtEnd dtEnd = (DtEnd) getProperties().getProperty(Property.DTEND); if (dtStart != null && dtEnd != null && !dtStart.getTime().before(dtEnd.getTime())) { throw new ValidationException("Property [" + Property.DTEND + "] must be later in time than [" + Property.DTSTART + "]"); } if (recurse) { validateProperties(); } } }
package org.jasig.portal.layout.al; public interface IFragmentRegistry { /** * Obtain a layout fragment * @param fragmentId fragment id * @return fragment */ public IFragment getFragment(IFragmentId fragmentId); /** * Delete a fragment * * @param fragmentId */ public void deleteFragment(IFragmentId fragmentId); /** * Create a new, empty fragment * * @return */ public IFragment createNewFragment(); /** * Obtain a set of fragments that should be pushed to a user * * @return an array of fragment ids */ public IFragmentId[] getPushedFragments(); /** * Obtain id of the user's main fragment (containing root node) * @return id of the user's main fragment */ public IFragmentId getUserFragmentId(); }
package org.jfree.chart.renderer.category; import java.awt.Graphics2D; import java.awt.geom.RectangularShape; import org.jfree.chart.util.RectangleEdge; /** * The interface for plugin painter for the {@link BarRenderer} class. When * developing a class that implements this interface, bear in mind the * following: * <ul> * <li>the <code>equals(Object)</code> method should be overridden;</li> * <li>instances of the class should be immutable OR implement the * <code>PublicCloneable</code> interface, so that a renderer using the * painter can be cloned reliably; * <li>the class should be <code>Serializable</code>, otherwise chart * serialization will not be supported.</li> * </ul> * * @since 1.0.11 */ public interface BarPainter { /** * Paints a single bar on behalf of a renderer. * * @param g2 the graphics target. * @param renderer the renderer. * @param row the row index for the item. * @param column the column index for the item. * @param bar the bounds for the bar. * @param base the base of the bar. */ public void paintBar(Graphics2D g2, BarRenderer renderer, int row, int column, RectangularShape bar, RectangleEdge base); /** * Paints the shadow for a single bar on behalf of a renderer. * * @param g2 the graphics target. * @param renderer the renderer. * @param row the row index for the item. * @param column the column index for the item. * @param bar the bounds for the bar. * @param base the base of the bar. * @param pegShadow peg the shadow to the base of the bar? */ public void paintBarShadow(Graphics2D g2, BarRenderer renderer, int row, int column, RectangularShape bar, RectangleEdge base, boolean pegShadow); }
package be.ibridge.kettle.job.entry.sftp; import java.io.File; import java.net.InetAddress; import java.util.ArrayList; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.eclipse.swt.widgets.Shell; import org.w3c.dom.Node; import be.ibridge.kettle.core.Const; import be.ibridge.kettle.core.LogWriter; import be.ibridge.kettle.core.Result; import be.ibridge.kettle.core.ResultFile; import be.ibridge.kettle.core.XMLHandler; import be.ibridge.kettle.core.exception.KettleDatabaseException; import be.ibridge.kettle.core.exception.KettleException; import be.ibridge.kettle.core.exception.KettleXMLException; import be.ibridge.kettle.core.util.StringUtil; import be.ibridge.kettle.job.Job; import be.ibridge.kettle.job.JobMeta; import be.ibridge.kettle.job.entry.JobEntryBase; import be.ibridge.kettle.job.entry.JobEntryDialogInterface; import be.ibridge.kettle.job.entry.JobEntryInterface; import be.ibridge.kettle.repository.Repository; /** * This defines an FTP job entry. * * @author Matt * @since 05-11-2003 * */ public class JobEntrySFTP extends JobEntryBase implements Cloneable, JobEntryInterface { private String serverName; private String serverPort; private String userName; private String password; private String sftpDirectory; private String targetDirectory; private String wildcard; private boolean remove; public JobEntrySFTP(String n) { super(n, ""); serverName=null; serverPort="22"; setID(-1L); setType(JobEntryInterface.TYPE_JOBENTRY_SFTP); } public JobEntrySFTP() { this(""); } public JobEntrySFTP(JobEntryBase jeb) { super(jeb); } public Object clone() { JobEntrySFTP je = (JobEntrySFTP) super.clone(); return je; } public String getXML() { StringBuffer retval = new StringBuffer(200); retval.append(super.getXML()); retval.append(" ").append(XMLHandler.addTagValue("servername", serverName)); retval.append(" ").append(XMLHandler.addTagValue("serverport", serverPort)); retval.append(" ").append(XMLHandler.addTagValue("username", userName)); retval.append(" ").append(XMLHandler.addTagValue("password", password)); retval.append(" ").append(XMLHandler.addTagValue("sftpdirectory", sftpDirectory)); retval.append(" ").append(XMLHandler.addTagValue("targetdirectory", targetDirectory)); retval.append(" ").append(XMLHandler.addTagValue("wildcard", wildcard)); retval.append(" ").append(XMLHandler.addTagValue("remove", remove)); return retval.toString(); } public void loadXML(Node entrynode, ArrayList databases, Repository rep) throws KettleXMLException { try { super.loadXML(entrynode, databases); serverName = XMLHandler.getTagValue(entrynode, "servername"); serverPort = XMLHandler.getTagValue(entrynode, "serverport"); userName = XMLHandler.getTagValue(entrynode, "username"); password = XMLHandler.getTagValue(entrynode, "password"); sftpDirectory = XMLHandler.getTagValue(entrynode, "sftpdirectory"); targetDirectory = XMLHandler.getTagValue(entrynode, "targetdirectory"); wildcard = XMLHandler.getTagValue(entrynode, "wildcard"); remove = "Y".equalsIgnoreCase( XMLHandler.getTagValue(entrynode, "remove") ); } catch(KettleXMLException xe) { throw new KettleXMLException("Unable to load job entry of type 'SFTP' from XML node", xe); } } public void loadRep(Repository rep, long id_jobentry, ArrayList databases) throws KettleException { try { super.loadRep(rep, id_jobentry, databases); serverName = rep.getJobEntryAttributeString(id_jobentry, "servername"); int intServerPort = (int)rep.getJobEntryAttributeInteger(id_jobentry, "serverport"); serverPort = rep.getJobEntryAttributeString(id_jobentry, "serverport"); // backward compatible. if (intServerPort>0 && Const.isEmpty(serverPort)) serverPort = Integer.toString(intServerPort); userName = rep.getJobEntryAttributeString(id_jobentry, "username"); password = rep.getJobEntryAttributeString(id_jobentry, "password"); sftpDirectory = rep.getJobEntryAttributeString(id_jobentry, "sftpdirectory"); targetDirectory = rep.getJobEntryAttributeString(id_jobentry, "targetdirectory"); wildcard = rep.getJobEntryAttributeString(id_jobentry, "wildcard"); remove = rep.getJobEntryAttributeBoolean(id_jobentry, "remove"); } catch(KettleException dbe) { throw new KettleException("Unable to load job entry of type 'SFTP' from the repository for id_jobentry="+id_jobentry, dbe); } } public void saveRep(Repository rep, long id_job) throws KettleException { try { super.saveRep(rep, id_job); rep.saveJobEntryAttribute(id_job, getID(), "servername", serverName); rep.saveJobEntryAttribute(id_job, getID(), "serverport", serverPort); rep.saveJobEntryAttribute(id_job, getID(), "username", userName); rep.saveJobEntryAttribute(id_job, getID(), "password", password); rep.saveJobEntryAttribute(id_job, getID(), "sftpdirectory", sftpDirectory); rep.saveJobEntryAttribute(id_job, getID(), "targetdirectory", targetDirectory); rep.saveJobEntryAttribute(id_job, getID(), "wildcard", wildcard); rep.saveJobEntryAttribute(id_job, getID(), "remove", remove); } catch(KettleDatabaseException dbe) { throw new KettleException("Unable to save job entry of type 'SFTP' to the repository for id_job="+id_job, dbe); } } /** * @return Returns the directory. */ public String getScpDirectory() { return sftpDirectory; } /** * @param directory The directory to set. */ public void setScpDirectory(String directory) { this.sftpDirectory = directory; } /** * @return Returns the password. */ public String getPassword() { return password; } /** * @param password The password to set. */ public void setPassword(String password) { this.password = password; } /** * @return Returns the serverName. */ public String getServerName() { return serverName; } /** * @param serverName The serverName to set. */ public void setServerName(String serverName) { this.serverName = serverName; } /** * @return Returns the userName. */ public String getUserName() { return userName; } /** * @param userName The userName to set. */ public void setUserName(String userName) { this.userName = userName; } /** * @return Returns the wildcard. */ public String getWildcard() { return wildcard; } /** * @param wildcard The wildcard to set. */ public void setWildcard(String wildcard) { this.wildcard = wildcard; } /** * @return Returns the targetDirectory. */ public String getTargetDirectory() { return targetDirectory; } /** * @param targetDirectory The targetDirectory to set. */ public void setTargetDirectory(String targetDirectory) { this.targetDirectory = targetDirectory; } /** * @param remove The remove to set. */ public void setRemove(boolean remove) { this.remove = remove; } /** * @return Returns the remove. */ public boolean getRemove() { return remove; } public String getServerPort() { return serverPort; } public void setServerPort(String serverPort) { this.serverPort = serverPort; } public Result execute(Result prev_result, int nr, Repository rep, Job parentJob) { LogWriter log = LogWriter.getInstance(); Result result = new Result(nr); result.setResult( false ); long filesRetrieved = 0; log.logDetailed(toString(), "Start of SFTP job entry"); SFTPClient sftpclient = null; // String substitution.. String realServerName = StringUtil.environmentSubstitute(serverName); String realServerPort = StringUtil.environmentSubstitute(serverPort); String realUsername = StringUtil.environmentSubstitute(userName); String realPassword = StringUtil.environmentSubstitute(password); String realSftpDirString = StringUtil.environmentSubstitute(sftpDirectory); String realWildcard = StringUtil.environmentSubstitute(wildcard); String realTargetDirectory = StringUtil.environmentSubstitute(targetDirectory); try { // Create sftp client to host ... sftpclient = new SFTPClient(InetAddress.getByName(realServerName), Const.toInt(realServerPort, 22), realUsername); log.logDetailed(toString(), "Opened SFTP connection to server ["+realServerName+"] on port ["+realServerPort+"] with username ["+realUsername+"]"); // login to ftp host ... sftpclient.login(realPassword); // Passwords should not appear in log files. //log.logDetailed(toString(), "logged in using password "+realPassword); // Logging this seems a bad idea! Oh well. // move to spool dir ... if (!Const.isEmpty(realSftpDirString)) { sftpclient.chdir(realSftpDirString); log.logDetailed(toString(), "Changed to directory ["+realSftpDirString+"]"); } // Get all the files in the current directory... String[] filelist = sftpclient.dir(); log.logDetailed(toString(), "Found "+filelist.length+" files in the remote directory"); Pattern pattern = null; if (!Const.isEmpty(realWildcard)) { pattern = Pattern.compile(realWildcard); } // Get the files in the list... for (int i=0;i<filelist.length && !parentJob.isStopped();i++) { boolean getIt = true; // First see if the file matches the regular expression! if (pattern!=null) { Matcher matcher = pattern.matcher(filelist[i]); getIt = matcher.matches(); } if (getIt) { log.logDebug(toString(), "Getting file ["+filelist[i]+"] to directory ["+realTargetDirectory+"]"); String targetFilename = realTargetDirectory+Const.FILE_SEPARATOR+filelist[i]; sftpclient.get(targetFilename, filelist[i]); filesRetrieved++; // Add to the result files... ResultFile resultFile = new ResultFile(ResultFile.FILE_TYPE_GENERAL, new File(targetFilename), parentJob.getJobname(), toString()); result.getResultFiles().put(resultFile.getFile().toString(), resultFile); log.logDetailed(toString(), "Transferred file ["+filelist[i]+"]"); // Delete the file if this is needed! if (remove) { sftpclient.delete(filelist[i]); log.logDetailed(toString(), "Deleted file ["+filelist[i]+"]"); } } } result.setResult( true ); result.setNrFilesRetrieved(filesRetrieved); } catch(Exception e) { result.setNrErrors(1); e.printStackTrace(); log.logError(toString(), "Error getting files from SFTP : "+e.getMessage()); } finally { // close connection, if possible try { if(sftpclient != null) sftpclient.disconnect(); } catch (Exception e) { // just ignore this, makes no big difference } } return result; } public boolean evaluates() { return true; } public JobEntryDialogInterface getDialog(Shell shell,JobEntryInterface jei,JobMeta jobMeta,String jobName,Repository rep) { return new JobEntrySFTPDialog(shell,this,jobMeta); } }
package org.stagemonitor; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.stagemonitor.configuration.ConfigurationOption; import org.stagemonitor.configuration.ConfigurationRegistry; import org.stagemonitor.core.StagemonitorPlugin; import org.stagemonitor.util.StringUtils; import java.io.IOException; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.TreeSet; public class ConfigurationOptionsMarkdownExporter { private ConfigurationOptionsMarkdownExporter() { } public static void main(String[] args) throws IOException { final ConfigurationRegistry configurationRegistry = new ConfigurationRegistry(StagemonitorPlugin.class); System.out.println(getMarkdown(configurationRegistry)); } private static String getMarkdown(ConfigurationRegistry configurationRegistry) { StringBuilder markdown = new StringBuilder(); final Map<String, List<ConfigurationOption<?>>> configurationOptionsByPlugin = new TreeMap<>(configurationRegistry.getConfigurationOptionsByCategory()); MultiValueMap<String, ConfigurationOption<?>> configurationOptionsByTags = new LinkedMultiValueMap<>(); configurationOptionsByPlugin.values() .stream() .flatMap(Collection::stream) .filter(opt -> !opt.getTags().isEmpty()) .forEach(opt -> opt.getTags() .forEach(tag -> configurationOptionsByTags.add(tag, opt))); markdown.append("# Overview\n"); markdown.append("## All Plugins\n"); for (String plugin : new TreeSet<>(configurationOptionsByPlugin.keySet())) { markdown.append("* ").append(linkToHeadline(plugin)).append('\n'); } markdown.append("\n"); markdown.append("## Available Tags\n"); for (String tag : new TreeSet<>(configurationOptionsByTags.keySet())) { markdown.append("`").append(tag).append("` "); } markdown.append("\n"); markdown.append("# Options by Plugin\n"); for (Map.Entry<String, List<ConfigurationOption<?>>> entry : configurationOptionsByPlugin.entrySet()) { final String pluginName = entry.getKey(); markdown.append("* ").append(linkToHeadline(pluginName)).append('\n'); for (ConfigurationOption<?> option : entry.getValue()) { markdown.append(" * ").append(linkToHeadline(option.getLabel())).append('\n'); } } markdown.append("\n"); markdown.append("# Options by Tag\n"); markdown.append("\n"); for (Map.Entry<String, List<ConfigurationOption<?>>> entry : configurationOptionsByTags.entrySet()) { markdown.append("* `").append(entry.getKey()).append("` \n"); for (ConfigurationOption<?> option : entry.getValue()) { markdown.append(" * ").append(linkToHeadline(option.getLabel())).append('\n'); }} markdown.append("\n"); for (Map.Entry<String, List<ConfigurationOption<?>>> entry : configurationOptionsByPlugin.entrySet()) { markdown.append("# ").append(entry.getKey()).append("\n\n"); for (ConfigurationOption<?> configurationOption : entry.getValue()) { markdown.append("## ").append(configurationOption.getLabel()).append("\n\n"); if (configurationOption.getDescription() != null) { markdown.append(configurationOption.getDescription()).append("\n\n"); } markdown.append("Key: `").append(configurationOption.getKey()).append("`\n\n"); markdown.append("Default Value: "); final String defaultValue = configurationOption.getDefaultValueAsString(); if (defaultValue == null) { markdown.append("`null`\n\n"); } else if (!defaultValue.contains("\n")) { markdown.append('`').append(defaultValue).append("`\n\n"); } else { markdown.append("\n\n```\n").append(defaultValue).append("\n```\n\n"); } if (!configurationOption.getTags().isEmpty()) { markdown.append("Tags: "); for (String tag : configurationOption.getTags()) { markdown.append('`').append(tag).append("` "); } markdown.append("\n\n"); } } markdown.append("***\n\n"); } return markdown.toString(); } private static String linkToHeadline(String headline) { return "[" + headline + "](#" + StringUtils.slugify(headline) + ')'; } }
package org.pentaho.di.core.plugins; import java.io.File; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.net.URLDecoder; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.vfs.FileObject; import org.pentaho.di.core.Const; import org.pentaho.di.core.exception.KettlePluginException; import org.pentaho.di.core.logging.LogChannel; import org.pentaho.di.core.row.RowBuffer; import org.pentaho.di.core.row.RowMeta; import org.pentaho.di.core.row.RowMetaInterface; import org.pentaho.di.core.row.ValueMeta; import org.pentaho.di.core.row.ValueMetaInterface; import org.pentaho.di.i18n.BaseMessages; import org.scannotation.AnnotationDB; /** * This singleton provides access to all the plugins in the Kettle universe.<br> * It allows you to register types and plugins, query plugin lists per category, list plugins per type, etc.<br> * * @author matt * */ public class PluginRegistry { private static Class<?> PKG = PluginRegistry.class; // for i18n purposes, needed by Translator2!! $NON-NLS-1$ private static PluginRegistry pluginRegistry; private Map<Class<? extends PluginTypeInterface>, List<PluginInterface>> pluginMap; private Map<String, URLClassLoader> folderBasedClassLoaderMap = new HashMap<String, URLClassLoader>(); private Map<Class<? extends PluginTypeInterface>, Map<PluginInterface, URLClassLoader>> classLoaderMap; private Map<Class<? extends PluginTypeInterface>, List<String>> categoryMap; private static AnnotationDB annotationDB; private static ClassPathFinder classPathFinder; private static List<PluginTypeInterface> pluginTypes = new ArrayList<PluginTypeInterface>(); /** * Initialize the registry, keep private to keep this a singleton */ private PluginRegistry() { pluginMap = new HashMap<Class<? extends PluginTypeInterface>, List<PluginInterface>>(); classLoaderMap = new HashMap<Class<? extends PluginTypeInterface>, Map<PluginInterface,URLClassLoader>>(); categoryMap = new HashMap<Class<? extends PluginTypeInterface>, List<String>>(); } /** * @return The one and only PluginRegistry instance */ public static PluginRegistry getInstance() { if (pluginRegistry==null) { pluginRegistry=new PluginRegistry(); } return pluginRegistry; } /** * @return The annotation database of all the classes in the plugins/ folders ONLY! */ public static AnnotationDB getAnnotationDB() { return annotationDB; } public void registerPluginType(Class<? extends PluginTypeInterface> pluginType) { pluginMap.put(pluginType, new ArrayList<PluginInterface>()); // Keep track of the categories separately for performance reasons... if (categoryMap.get(pluginType)==null) { List<String> categories = new ArrayList<String>(); categoryMap.put(pluginType, categories); } } public void registerPlugin(Class<? extends PluginTypeInterface> pluginType, PluginInterface plugin) throws KettlePluginException { if (plugin.getIds()[0]==null) { throw new KettlePluginException("Not a valid id specified in plugin :"+plugin); } if (plugin.getName().startsWith("i18n:")) { System.out.println("i18n untranslated key detected: "+plugin.getName()); } if (plugin.getName().startsWith("!") && plugin.getName().endsWith("!")) { System.out.println("i18n untranslated key detected: "+plugin.getName()); } List<PluginInterface> list = pluginMap.get(pluginType); if (list==null) { list = new ArrayList<PluginInterface>(); pluginMap.put(pluginType, list); // classLoaderMap.put(pluginType, new HashMap<PluginInterface, URLClassLoader>()); } int index = list.indexOf(plugin); if (index<0) { list.add(plugin); } else { list.set(index, plugin); // replace with the new one } // Keep the list of plugins sorted by name... Collections.sort(list, new Comparator<PluginInterface>() { public int compare(PluginInterface p1, PluginInterface p2) { return p1.getName().compareToIgnoreCase(p2.getName()); } }); if (!Const.isEmpty(plugin.getCategory())) { List<String> categories = categoryMap.get(pluginType); if (!categories.contains(plugin.getCategory())) { categories.add(plugin.getCategory()); // Keep it sorted in the natural order here too! // Sort the categories in the correct order. String[] naturalOrder = null; PluginTypeCategoriesOrder naturalOrderAnnotation = pluginType.getAnnotation(PluginTypeCategoriesOrder.class); if(naturalOrderAnnotation != null){ String[] naturalOrderKeys = naturalOrderAnnotation.getNaturalCategoriesOrder(); Class<?> i18nClass = naturalOrderAnnotation.i18nPackageClass(); naturalOrder = new String[naturalOrderKeys.length]; for(int i=0; i< naturalOrderKeys.length; i++){ naturalOrder[i] = BaseMessages.getString(i18nClass, naturalOrderKeys[i]); } } if (naturalOrder!=null) { final String[] fNaturalOrder = naturalOrder; Collections.sort(categories, new Comparator<String>() { public int compare(String one, String two) { int idx1 = Const.indexOfString(one, fNaturalOrder); int idx2 = Const.indexOfString(two, fNaturalOrder); return idx1 - idx2; } }); } } } } /** * @return An unmodifiable list of plugin types */ public List<Class<? extends PluginTypeInterface>> getPluginTypes() { return Collections.unmodifiableList(new ArrayList<Class<? extends PluginTypeInterface>>(pluginMap.keySet())); } /** * @param type The plugin type to query * @return The list of plugins */ @SuppressWarnings("unchecked") public <T extends PluginInterface, K extends PluginTypeInterface> List<T> getPlugins(Class<K> type) { List<T> list = new ArrayList<T>(); List<PluginInterface> mapList = pluginMap.get(type); if(mapList != null){ for(PluginInterface p : mapList){ list.add((T) p); } } return list; // return pluginMap.get(type); } /** * Get a plugin from the registry * * @param stepplugintype The type of plugin to look for * @param id The ID to scan for * * @return the plugin or null if nothing was found. */ public PluginInterface getPlugin(Class<? extends PluginTypeInterface> pluginType, String id) { List<PluginInterface> plugins = getPlugins(pluginType); if (plugins==null) { return null; } for (PluginInterface plugin : plugins) { if (plugin.matches(id)) { return plugin; } } return null; } /** * Retrieve a list of plugins per category. * * @param pluginType The type of plugins to search * @param pluginCategory The category to look in * * @return An unmodifiable list of plugins that belong to the specified type and category. */ public <T extends PluginTypeInterface> List<PluginInterface> getPluginsByCategory(Class<T> pluginType, String pluginCategory) { List<PluginInterface> plugins = new ArrayList<PluginInterface>(); for (PluginInterface verify : getPlugins(pluginType)) { if (verify.getCategory()!=null && verify.getCategory().equals(pluginCategory)) { plugins.add(verify); } } // Also sort return Collections.unmodifiableList(plugins); } /** * Retrieve a list of all categories for a certain plugin type. * @param pluginType The plugin type to search categories for. * @return The list of categories for this plugin type. The list can be modified (sorted etc) but will not impact the registry in any way. */ public List<String> getCategories(Class<? extends PluginTypeInterface> pluginType) { List<String> categories = categoryMap.get(pluginType); return categories; } /** * Load and instantiate the main class of the plugin specified. * * @param plugin The plugin to load the main class for. * @return The instantiated class * @throws KettlePluginException In case there was a loading problem. */ public Object loadClass(PluginInterface plugin) throws KettlePluginException { return loadClass(plugin, plugin.getMainType()); } /** * Load the class of the type specified for the plugin that owns the class of the specified object. * * @param pluginType the type of plugin * @param object The object for which we want to search the class to find the plugin * @param classType The type of class to load * @return the instantiated class. * @throws KettlePluginException */ public <T> T loadClass(Class<? extends PluginTypeInterface> pluginType, Object object, Class<T> classType) throws KettlePluginException { PluginInterface plugin = getPlugin(pluginType, object); if (plugin==null) return null; return loadClass(plugin, classType); } /** * Load the class of the type specified for the plugin with the ID specified. * * @param pluginType the type of plugin * @param plugiId The plugin id to use * @param classType The type of class to load * @return the instantiated class. * @throws KettlePluginException */ public <T> T loadClass(Class<? extends PluginTypeInterface> pluginType, String pluginId, Class<T> classType) throws KettlePluginException { PluginInterface plugin = getPlugin(pluginType, pluginId); if (plugin==null) return null; return loadClass(plugin, classType); } /** * Load and instantiate the plugin class specified * @param plugin the plugin to load * @param pluginClass the class to be loaded * @return The instantiated class * * @throws KettlePluginException In case there was a class loading problem somehow */ @SuppressWarnings("unchecked") public <T> T loadClass(PluginInterface plugin, Class<T> pluginClass) throws KettlePluginException { if (plugin == null) { throw new KettlePluginException(BaseMessages.getString(PKG, "PluginRegistry.RuntimeError.NoValidStepOrPlugin.PLUGINREGISTRY001")); //$NON-NLS-1$ } String className = plugin.getClassMap().get(pluginClass); if (className==null) { throw new KettlePluginException(BaseMessages.getString(PKG, "PluginRegistry.RuntimeError.NoValidClassRequested.PLUGINREGISTRY002", pluginClass.getName())); //$NON-NLS-1$ } try { Class<? extends T> cl = null; if (plugin.isNativePlugin()) { cl = (Class<? extends T>) Class.forName(className); } else { List<String> jarfiles = plugin.getLibraries(); URL urls[] = new URL[jarfiles.size()]; for (int i = 0; i < jarfiles.size(); i++) { File jarfile = new File(jarfiles.get(i)); urls[i] = new URL(URLDecoder.decode(jarfile.toURI().toURL().toString(), "UTF-8")); } // Load the class!! // First get the class loader: get the one that's the webstart classloader, not the thread classloader ClassLoader classLoader = getClass().getClassLoader(); URLClassLoader ucl = null; // If the plugin needs to have a separate class loader for each instance of the plugin. // This is not the default. By default we cache the class loader for each plugin ID. if (plugin.isSeparateClassLoaderNeeded()) { // Create a new one each time ucl = new KettleURLClassLoader(urls, classLoader, plugin.getDescription()); } else { // See if we can find a class loader to re-use. Map<PluginInterface, URLClassLoader> classLoaders = classLoaderMap.get(plugin.getPluginType()); if (classLoaders==null) { classLoaders=new HashMap<PluginInterface, URLClassLoader>(); classLoaderMap.put(plugin.getPluginType(), classLoaders); } else { ucl = classLoaders.get(plugin); } if (ucl==null) { if(plugin.getPluginDirectory() != null){ ucl = folderBasedClassLoaderMap.get(plugin.getPluginDirectory().toString()); if(ucl == null){ ucl = new KettleURLClassLoader(urls, classLoader, plugin.getDescription()); classLoaders.put(plugin, ucl); // save for later use... folderBasedClassLoaderMap.put(plugin.getPluginDirectory().toString(), ucl); } } else { ucl = classLoaders.get(plugin); if (ucl==null) { ucl = new KettleURLClassLoader(urls, classLoader, plugin.getDescription()); classLoaders.put(plugin, ucl); // save for later use... } } } } // Load the class. cl = (Class<? extends T>) ucl.loadClass(className); } return cl.newInstance(); } catch (ClassNotFoundException e) { throw new KettlePluginException(BaseMessages.getString(PKG, "PluginRegistry.RuntimeError.ClassNotFound.PLUGINREGISTRY003"), e); //$NON-NLS-1$ } catch (InstantiationException e) { throw new KettlePluginException(BaseMessages.getString(PKG, "PluginRegistry.RuntimeError.UnableToInstantiateClass.PLUGINREGISTRY004"), e); //$NON-NLS-1$ } catch (IllegalAccessException e) { throw new KettlePluginException(BaseMessages.getString(PKG, "PluginRegistry.RuntimeError.IllegalAccessToClass.PLUGINREGISTRY005"), e); //$NON-NLS-1$ } catch (MalformedURLException e) { throw new KettlePluginException(BaseMessages.getString(PKG, "PluginRegistry.RuntimeError.MalformedURL.PLUGINREGISTRY006"), e); //$NON-NLS-1$ } catch (Throwable e) { e.printStackTrace(); throw new KettlePluginException(BaseMessages.getString(PKG, "PluginRegistry.RuntimeError.UnExpectedErrorLoadingClass.PLUGINREGISTRY007"), e); //$NON-NLS-1$ } } /** * Add a PluginType to be managed by the registry * @param type */ public static void addPluginType(PluginTypeInterface type){ pluginTypes.add(type); } /** * This method registers plugin types and loads their respective plugins * * @throws KettlePluginException */ public static void init() throws KettlePluginException { PluginRegistry registry = getInstance(); try { annotationDB = new AnnotationDB(); List<URL> urlList = new ArrayList<URL>(); List<PluginFolderInterface> folders = PluginFolder.populateFolders(null); for (PluginFolderInterface pluginFolder : folders) { try { FileObject[] fileObjects = pluginFolder.findJarFiles(); if (fileObjects!=null) { for (FileObject fileObject : fileObjects) { String uri = fileObject.getName().getURI(); urlList.add(new URL(URLDecoder.decode(uri, "UTF-8"))); } } } catch(Exception e) { LogChannel.GENERAL.logError("Error searching for jar files in plugin folder '"+pluginFolder+"'", e); } } LogChannel.GENERAL.logDetailed("Found "+urlList.size()+" objects to scan for annotated plugins."); long startScan = System.currentTimeMillis(); URL[] urls = urlList.toArray(new URL[urlList.size()]); annotationDB.scanArchives(urls); LogChannel.GENERAL.logDetailed("Finished annotation scan in "+(System.currentTimeMillis()-startScan)+"ms."); classPathFinder = new ClassPathFinder(urls); } catch(Exception e) { throw new KettlePluginException("Unable to scan for annotations in the classpath", e); } for (PluginTypeInterface pluginType : pluginTypes) { // Register the plugin type registry.registerPluginType(pluginType.getClass()); // Search plugins for this type... long startScan = System.currentTimeMillis(); pluginType.searchPlugins(); LogChannel.GENERAL.logDetailed("Registered "+registry.getPlugins(pluginType.getClass()).size()+" plugins of type '"+pluginType.getName()+"' in "+(System.currentTimeMillis()-startScan)+"ms."); } } /** * Find the plugin ID based on the class * @param pluginClass * @return The ID of the plugin to which this class belongs (checks the plugin class maps) */ public String getPluginId(Object pluginClass) { for (Class<? extends PluginTypeInterface> pluginType : getPluginTypes()) { String id = getPluginId(pluginType, pluginClass); if (id!=null) { return id; } } return null; } /** * Find the plugin ID based on the class * * @param pluginType the type of plugin * @param pluginClass The class to look for * @return The ID of the plugin to which this class belongs (checks the plugin class maps) or null if nothing was found. */ public String getPluginId(Class<? extends PluginTypeInterface> pluginType, Object pluginClass) { String className = pluginClass.getClass().getName(); for (PluginInterface plugin : getPlugins(pluginType)) { for (String check : plugin.getClassMap().values()) { if (check != null && check.equals(className)) { return plugin.getIds()[0]; } } } return null; } /** * Retrieve the Plugin for a given class * @param pluginType The type of plugin to search for * @param pluginClass The class of this object is used to look around * @return the plugin or null if nothing could be found */ public PluginInterface getPlugin(Class<? extends PluginTypeInterface> pluginType, Object pluginClass) { String pluginId = getPluginId(pluginType, pluginClass); if (pluginId==null) { return null; } return getPlugin(pluginType, pluginId); } /** * Find the plugin ID based on the name of the plugin * * @param pluginType the type of plugin * @param pluginName The name to look for * @return The plugin with the specified name or null if nothing was found. */ public PluginInterface findPluginWithName(Class<? extends PluginTypeInterface> pluginType, String pluginName) { for (PluginInterface plugin : getPlugins(pluginType)) { if (plugin.getName().equals(pluginName)) { return plugin; } } return null; } /** * Find the plugin ID based on the description of the plugin * * @param pluginType the type of plugin * @param pluginDescription The description to look for * @return The plugin with the specified description or null if nothing was found. */ public PluginInterface findPluginWithDescription(Class<? extends PluginTypeInterface> pluginType, String pluginDescription) { for (PluginInterface plugin : getPlugins(pluginType)) { if (plugin.getDescription().equals(pluginDescription)) { return plugin; } } return null; } /** * Find the plugin ID based on the name of the plugin * * @param pluginType the type of plugin * @param pluginName The name to look for * @return The plugin with the specified name or null if nothing was found. */ public PluginInterface findPluginWithId(Class<? extends PluginTypeInterface> pluginType, String pluginId) { for (PluginInterface plugin : getPlugins(pluginType)) { if (plugin.matches(pluginId)) { return plugin; } } return null; } /** * @return a unique list of all the step plugin package names */ public List<String> getPluginPackages(Class<? extends PluginTypeInterface> pluginType) { List<String> list = new ArrayList<String>(); for (PluginInterface plugin : getPlugins(pluginType)) { for (String className : plugin.getClassMap().values()) { if (className==null) { System.out.println("SNAFU!!!"); } int lastIndex = className.lastIndexOf("."); String packageName = className.substring(0, lastIndex); if (!list.contains(packageName)) list.add(packageName); } } Collections.sort(list); return list; } private RowMetaInterface getPluginInformationRowMeta() { RowMetaInterface row = new RowMeta(); row.addValueMeta(new ValueMeta(BaseMessages.getString(PKG, "PluginRegistry.Information.Type.Label"), ValueMetaInterface.TYPE_STRING)); row.addValueMeta(new ValueMeta(BaseMessages.getString(PKG, "PluginRegistry.Information.ID.Label"), ValueMetaInterface.TYPE_STRING)); row.addValueMeta(new ValueMeta(BaseMessages.getString(PKG, "PluginRegistry.Information.Name.Label"), ValueMetaInterface.TYPE_STRING)); row.addValueMeta(new ValueMeta(BaseMessages.getString(PKG, "PluginRegistry.Information.Description.Label"), ValueMetaInterface.TYPE_STRING)); row.addValueMeta(new ValueMeta(BaseMessages.getString(PKG, "PluginRegistry.Information.Libraries.Label"), ValueMetaInterface.TYPE_STRING)); row.addValueMeta(new ValueMeta(BaseMessages.getString(PKG, "PluginRegistry.Information.ImageFile.Label"), ValueMetaInterface.TYPE_STRING)); row.addValueMeta(new ValueMeta(BaseMessages.getString(PKG, "PluginRegistry.Information.ClassName.Label"), ValueMetaInterface.TYPE_STRING)); row.addValueMeta(new ValueMeta(BaseMessages.getString(PKG, "PluginRegistry.Information.Category.Label"), ValueMetaInterface.TYPE_STRING)); return row; } /** * @param the type of plugin to get information for * @return a row buffer containing plugin information for the given plugin type */ public RowBuffer getPluginInformation(Class<? extends PluginTypeInterface> pluginType) { RowBuffer rowBuffer = new RowBuffer(getPluginInformationRowMeta()); for (PluginInterface plugin : getPlugins(pluginType)) { Object[] row = new Object[getPluginInformationRowMeta().size()]; int rowIndex=0; row[rowIndex++] = plugin.getPluginType().getName(); row[rowIndex++] = plugin.getIds()[0]; row[rowIndex++] = plugin.getName(); row[rowIndex++] = plugin.getDescription(); row[rowIndex++] = plugin.getLibraries().toString(); row[rowIndex++] = plugin.getImageFile(); row[rowIndex++] = plugin.getClassMap().values().toString(); row[rowIndex++] = plugin.getCategory(); rowBuffer.getBuffer().add(row); } return rowBuffer; } /** * Load the class with a certain name using the class loader of certain plugin. * * @param plugin The plugin for which we want to use the class loader * @param className The name of the class to load * @return the name of the class * @throws KettlePluginException In case there is something wrong */ @SuppressWarnings("unchecked") public <T> T getClass(PluginInterface plugin, String className) throws KettlePluginException { try { if (plugin.isNativePlugin()) { return (T) Class.forName(className); } else { URLClassLoader ucl = null; Map<PluginInterface, URLClassLoader> classLoaders = classLoaderMap.get(plugin.getPluginType()); if (classLoaders==null) { classLoaders=new HashMap<PluginInterface, URLClassLoader>(); classLoaderMap.put(plugin.getPluginType(), classLoaders); } else { ucl = classLoaders.get(plugin); } if (ucl==null) { if(plugin.getPluginDirectory() != null){ ucl = folderBasedClassLoaderMap.get(plugin.getPluginDirectory().toString()); classLoaders.put(plugin, ucl); // save for later use... } } if (ucl==null) { throw new KettlePluginException("Unable to find class loader for plugin: "+plugin); } return (T) ucl.loadClass(className); } } catch (Exception e) { throw new KettlePluginException("Unexpected error loading class with name: "+className, e); } } /** * Load the class with a certain name using the class loader of certain plugin. * * @param plugin The plugin for which we want to use the class loader * @param classType The type of class to load * @return the name of the class * @throws KettlePluginException In case there is something wrong */ @SuppressWarnings("unchecked") public <T> T getClass(PluginInterface plugin, T classType) throws KettlePluginException { String className = plugin.getClassMap().get(classType); return (T) getClass(plugin, className); } /** * @return the classPathFinder */ public static ClassPathFinder getClassPathFinder() { return classPathFinder; } }
public class StringUtil { public static String padleft(String s, int largura, char pad) { char[] chars = s.toCharArray(); if (chars.length < largura) { int faltam = largura - chars.length; char[] stringComPad = new char[largura]; for (int i = 0; i < largura; i++) { if (i < faltam) stringComPad[i] = pad; else stringComPad[i] = chars[i - faltam]; } return new String(stringComPad); } else { return s; } } public static String padright(String s, int largura, char pad) { char[] chars = s.toCharArray(); char[] stringComPad = new char[largura]; for (int i = 0; i < largura; i++) { if (i < chars.length) stringComPad[i] = chars[i]; else stringComPad[i] = pad; } return new String(stringComPad); } public static String padcenter(String s, int largura, char pad) { char[] chars = s.toCharArray(); int pads = largura - chars.length; // 10 - 5 = 5 char[] stringComPad = new char[largura]; for (int i = 0; i < largura; i++) { if (i < pads / 2) stringComPad[i] = pad; else if (i >= pads / 2 + chars.length) stringComPad[i] = pad; else stringComPad[i] = chars[i - pads / 2]; } return new String(stringComPad); } }
package org.commcare.util.screen; import org.commcare.modern.session.SessionWrapper; import org.commcare.modern.util.Pair; import org.commcare.session.CommCareSession; import org.commcare.session.RemoteQuerySessionManager; import org.commcare.suite.model.DisplayUnit; import org.javarosa.core.model.instance.ExternalDataInstance; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import java.net.URL; import java.util.Hashtable; import java.util.Map; import okhttp3.Credentials; import okhttp3.HttpUrl; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; /** * Screen that displays user configurable entry texts and makes * a case query to the server with these fields. * * @author wspride */ public class QueryScreen extends Screen { private RemoteQuerySessionManager remoteQuerySessionManager; private Hashtable<String, DisplayUnit> userInputDisplays; private SessionWrapper sessionWrapper; private String[] fields; private String mTitle; private String currentMessage; private String domainedUsername; private String password; private PrintStream out; public QueryScreen(String domainedUsername, String password, PrintStream out) { this.domainedUsername = domainedUsername; this.password = password; this.out = out; } @Override public void init(SessionWrapper sessionWrapper) throws CommCareSessionException { this.sessionWrapper = sessionWrapper; remoteQuerySessionManager = RemoteQuerySessionManager.buildQuerySessionManager(sessionWrapper, sessionWrapper.getEvaluationContext()); if (remoteQuerySessionManager == null) { throw new CommCareSessionException(String.format("QueryManager for case " + "claim screen with id %s cannot be null.", sessionWrapper.getNeededData())); } userInputDisplays = remoteQuerySessionManager.getNeededUserInputDisplays(); int count = 0; fields = new String[userInputDisplays.keySet().size()]; for (Map.Entry<String, DisplayUnit> displayEntry : userInputDisplays.entrySet()) { fields[count] = displayEntry.getValue().getText().evaluate(sessionWrapper.getEvaluationContext()); } mTitle = "Case Claim"; } private static String buildUrl(String baseUrl, Hashtable<String, String> queryParams) { HttpUrl.Builder urlBuilder = HttpUrl.parse(baseUrl).newBuilder(); for (String key: queryParams.keySet()) { urlBuilder.addQueryParameter(key, queryParams.get(key)); } return urlBuilder.build().toString(); } private InputStream makeQueryRequestReturnStream() { String url = buildUrl(getBaseUrl().toString(), getQueryParams()); String credential = Credentials.basic(domainedUsername, password); Request request = new Request.Builder() .url(url) .header("Authorization", credential) .build(); try { Response response = new OkHttpClient().newCall(request).execute(); return response.body().byteStream(); } catch (IOException e) { e.printStackTrace(); return null; } } public boolean processResponse(InputStream responseData) { if (responseData == null) { currentMessage = "Query result null."; return false; } Pair<ExternalDataInstance, String> instanceOrError = remoteQuerySessionManager.buildExternalDataInstance(responseData); if (instanceOrError.first == null) { currentMessage = "Query response format error: " + instanceOrError.second; return false; } else if (isResponseEmpty(instanceOrError.first)) { currentMessage = "Query successful but returned no results."; return false; } else { sessionWrapper.setQueryDatum(instanceOrError.first); return true; } } private boolean isResponseEmpty(ExternalDataInstance instance) { return !instance.getRoot().hasChildren(); } public void answerPrompts(Hashtable<String, String> answers) { for(String key: answers.keySet()){ remoteQuerySessionManager.answerUserPrompt(key, answers.get(key)); } } protected URL getBaseUrl(){ return remoteQuerySessionManager.getBaseUrl(); } protected Hashtable<String, String> getQueryParams(){ return remoteQuerySessionManager.getRawQueryParams(); } public String getScreenTitle() { return mTitle; } @Override public void prompt(PrintStream out) { out.println("Enter the search fields as a space separated list."); for (int i=0; i< fields.length; i++) { out.println(i + ") " + fields[i]); } } @Override public String[] getOptions() { return fields; } @Override public boolean handleInputAndUpdateSession(CommCareSession session, String input) { String[] answers = input.split(","); Hashtable<String, String> userAnswers = new Hashtable<>(); int count = 0; for (Map.Entry<String, DisplayUnit> displayEntry : userInputDisplays.entrySet()) { userAnswers.put(displayEntry.getKey(), answers[count]); count ++; } answerPrompts(userAnswers); InputStream response = makeQueryRequestReturnStream(); boolean refresh = processResponse(response); if (currentMessage != null) { out.println(currentMessage); } return refresh; } public Hashtable<String, DisplayUnit> getUserInputDisplays(){ return userInputDisplays; } public String getCurrentMessage(){ return currentMessage; } }
package org.wisdom.engine.server; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.EventLoopGroup; import io.netty.channel.group.ChannelGroup; import io.netty.channel.group.DefaultChannelGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.util.concurrent.GlobalEventExecutor; import org.wisdom.api.configuration.ApplicationConfiguration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.InetAddress; /** * The Wisdom Server. */ public class WisdomServer { private static final String KEY_HTTP_ADDRESS = "http.address"; private static final Logger LOGGER = LoggerFactory.getLogger("wisdom-engine"); private final ServiceAccessor accessor; private EventLoopGroup bossGroup; private EventLoopGroup workerGroup; private ChannelGroup group; private int httpPort; private int httpsPort; private InetAddress address; public WisdomServer(ServiceAccessor accessor) { this.accessor = accessor; } public void start() throws InterruptedException { LOGGER.info("Starting Wisdom server"); httpPort = accessor.getConfiguration().getIntegerWithDefault(ApplicationConfiguration.HTTP_PORT, 9000); httpsPort = accessor.getConfiguration().getIntegerWithDefault(ApplicationConfiguration.HTTPS_PORT, -1); address = null; if (System.getProperties().containsKey(ApplicationConfiguration.HTTP_PORT)) { httpPort = Integer.parseInt(System.getProperty(ApplicationConfiguration.HTTP_PORT)); } if (System.getProperties().containsKey(ApplicationConfiguration.HTTPS_PORT)) { httpsPort = Integer.parseInt(System.getProperty(ApplicationConfiguration.HTTPS_PORT)); } try { if (accessor.getConfiguration().get(KEY_HTTP_ADDRESS) != null) { address = InetAddress.getByName(accessor.getConfiguration().get(KEY_HTTP_ADDRESS)); } if (System.getProperties().containsKey(KEY_HTTP_ADDRESS)) { address = InetAddress.getByName(System.getProperty(KEY_HTTP_ADDRESS)); } } catch (Exception e) { LOGGER.error("Could not understand http.address", e); onError(); } group = new DefaultChannelGroup("wisdom-channels", GlobalEventExecutor.INSTANCE); // Configure the server. bossGroup = new NioEventLoopGroup(); workerGroup = new NioEventLoopGroup(); try { //HTTP if (httpPort != -1) { LOGGER.info("Wisdom is going to serve HTTP requests on port " + httpPort); ServerBootstrap http = new ServerBootstrap(); http.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .childHandler(new WisdomServerInitializer(accessor, false)); group.add(http.bind(address, httpPort).sync().channel()); } //HTTPS if (httpsPort != -1) { LOGGER.info("Wisdom is going to serve HTTPS requests on port " + httpsPort); ServerBootstrap https = new ServerBootstrap(); https.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .childHandler(new WisdomServerInitializer(accessor, true)); group.add(https.bind(address, httpsPort).sync().channel()); } } catch (Exception e) { LOGGER.error("Cannot initialize Wisdom", e); group.close().sync(); bossGroup.shutdownGracefully().sync(); workerGroup.shutdownGracefully().sync(); onError(); } } private void onError() { System.exit(-1); //NOSONAR } public void stop() { try { group.close().sync(); bossGroup.shutdownGracefully().sync(); workerGroup.shutdownGracefully().sync(); LOGGER.info("Wisdom server has been stopped gracefully"); } catch (InterruptedException e) { LOGGER.warn("Cannot stop the Wisdom server gracefully", e); } } public String hostname() { if (address == null) { return "localhost"; } else { return address.getHostName(); } } public int httpPort() { return httpPort; } public int httpsPort() { return httpsPort; } }
package org.openlmis.functional; import org.openlmis.UiUtils.TestCaseHelper; import org.openlmis.pageobjects.*; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.io.FileNotFoundException; import java.io.IOException; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; import static com.thoughtworks.selenium.SeleneseTestBase.assertFalse; import static com.thoughtworks.selenium.SeleneseTestBase.assertTrue; import static org.testng.AssertJUnit.assertEquals; public class ManageSupervisoryNodes extends TestCaseHelper { LoginPage loginPage; public static final String USER = "user"; public static final String ADMIN = "admin"; public static final String PASSWORD = "password"; public Map<String, String> testData = new HashMap<String, String>() {{ put(USER, "fieldCoordinator"); put(PASSWORD, "Admin123"); put(ADMIN, "Admin123"); }}; @BeforeMethod(groups = {"admin"}) public void setUp() throws InterruptedException, SQLException, IOException { super.setup(); dbWrapper.insertFacilities("F10", "F11"); loginPage = PageObjectFactory.getLoginPage(testWebDriver, baseUrlGlobal); } @Test(groups = {"admin"}) public void testRightsNotPresent() throws SQLException { dbWrapper.insertSupervisoryNode("F10", "N1", "Node1", null); dbWrapper.insertSupervisoryNode("F11", "N2", "Node2", null); dbWrapper.insertSupervisoryNode("F10", "N3", "Node3", "N2"); HomePage homePage = loginPage.loginAs(testData.get(ADMIN), testData.get(PASSWORD)); homePage.navigateToUser(); homePage.verifyAdminTabs(); assertFalse(homePage.isSupervisoryNodeTabDisplayed()); homePage.logout(); dbWrapper.assignRight("Admin", "MANAGE_SUPERVISORY_NODE"); loginPage.loginAs(testData.get(ADMIN), testData.get(PASSWORD)); homePage.navigateToUser(); assertTrue(homePage.isSupervisoryNodeTabDisplayed()); SupervisoryNodesPage supervisoryNodesPage = homePage.navigateToSupervisoryNodes(); assertEquals("Search supervisory node", supervisoryNodesPage.getSearchSupervisoryNodeLabel()); assertTrue(supervisoryNodesPage.isAddNewButtonDisplayed()); assertEquals("Supervisory node", supervisoryNodesPage.getSelectedSearchOption()); assertTrue(supervisoryNodesPage.isSearchIconDisplayed()); } @Test(groups = {"admin"}) public void testSupervisoryNodeSearchSortAndPagination() throws SQLException, FileNotFoundException { dbWrapper.assignRight("Admin", "MANAGE_SUPERVISORY_NODE"); dbWrapper.insertSupervisoryNode("F10", "N1", "Node1", null); dbWrapper.insertSupervisoryNode("F11", "N2", "Node2", null); dbWrapper.insertSupervisoryNode("F10", "N3", "Node3", "N2"); HomePage homePage = loginPage.loginAs(testData.get(ADMIN), testData.get(PASSWORD)); SupervisoryNodesPage supervisoryNodesPage = homePage.navigateToSupervisoryNodes(); homePage.verifyAdminTabs(); assertTrue(homePage.isSupervisoryNodeTabDisplayed()); assertEquals("Search supervisory node", supervisoryNodesPage.getSearchSupervisoryNodeLabel()); assertTrue(supervisoryNodesPage.isAddNewButtonDisplayed()); assertEquals("Supervisory node", supervisoryNodesPage.getSelectedSearchOption()); //assertFalse(supervisoryNodesPage.isNoResultMessageDisplayed()); //assertFalse(supervisoryNodesPage.isNResultsMessageDisplayed()); //assertFalse(supervisoryNodesPage.isOneResultMessageDisplayed()); //assertFalse(supervisoryNodesPage.isSupervisoryNodeHeaderPresent()); searchNode("nod"); assertEquals("3 matches found for 'nod'", supervisoryNodesPage.getNResultsMessage()); assertEquals("Supervisory Node Name", supervisoryNodesPage.getSupervisoryNodeHeader()); assertEquals("Code", supervisoryNodesPage.getCodeHeader()); assertEquals("Facility", supervisoryNodesPage.getFacilityHeader()); assertEquals("Parent", supervisoryNodesPage.getParentHeader()); assertEquals("Node3", supervisoryNodesPage.getSupervisoryNodeName(1)); assertEquals("N3", supervisoryNodesPage.getSupervisoryNodeCode(1)); assertEquals("Village Dispensary", supervisoryNodesPage.getFacility(1)); assertEquals("Node2", supervisoryNodesPage.getParent(1)); UploadPage uploadPage = homePage.navigateUploads(); uploadPage.uploadSupervisoryNodes("QA_supervisoryNodes21.csv"); uploadPage.verifySuccessMessageOnUploadScreen(); homePage.navigateToSupervisoryNodes(); assertEquals("Search supervisory node", supervisoryNodesPage.getSearchSupervisoryNodeLabel()); searchNode("Approval Point"); assertEquals("19 matches found for 'Approval Point'", supervisoryNodesPage.getNResultsMessage()); searchNode("Ap"); assertEquals("21 matches found for 'Ap'", supervisoryNodesPage.getNResultsMessage()); verifyNumberOFPageLinksDisplayed(21, 10); verifyPageNumberLinksDisplayed(); verifyPageNumberSelected(1); verifyNextAndLastPageLinksEnabled(); verifyPreviousAndFirstPageLinksDisabled(); verifyNumberOfLineItemsVisibleOnPage(10); verifyParentNameOrderOnPage(new String[]{"Approval Point 10", "Approval Point 3", "Approval Point 3", "approval Point 4", "approval Point 4", "Approval Point 5", "Approval Point 5", "Approval Point 5", "Approval Point 6", "approval Point 7"}); verifySupervisoryNodeNameOrderOnPage(new String[]{"Approval Point 13", "Approval Point 12", "Approval Point 21", "Approval Point 13", "Approval Point 5", "Approval Point 15", "Approval Point 20", "Approval Point 6", "Approval Point 8", "Approval Point 9"}); navigateToPage(2); verifyPageNumberSelected(2); verifyNextAndLastPageLinksEnabled(); verifyPreviousAndFirstPageLinksEnabled(); verifyNumberOfLineItemsVisibleOnPage(10); verifyParentNameOrderOnPage(new String[]{"Approval Point 8", "Approval Point 8", "Approval Point 9", "Node1", "Node1", "Node1", "Node1", "Node1", "Node1", "Node3"}); verifySupervisoryNodeNameOrderOnPage(new String[]{"Approval Point 11", "Approval Point 13", "Approval Point 13", "Approval Point 10", "Approval Point 13", "Approval Point 3", "approval Point 7", "Aproval Point 3", "Aproval Point 4", "Approval Point 13"}); navigateToNextPage(); verifyPageNumberSelected(3); verifyNextAndLastPageLinksDisabled(); verifyPreviousAndFirstPageLinksEnabled(); verifyNumberOfLineItemsVisibleOnPage(1); verifyParentNameOrderOnPage(new String[]{"Node3"}); verifySupervisoryNodeNameOrderOnPage(new String[]{"Approval Point 13"}); navigateToFirstPage(); verifyPageNumberSelected(1); verifyNextAndLastPageLinksEnabled(); verifyPreviousAndFirstPageLinksDisabled(); verifyNumberOfLineItemsVisibleOnPage(10); verifyParentNameOrderOnPage(new String[]{"Approval Point 10", "Approval Point 3", "Approval Point 3", "approval Point 4", "approval Point 4", "Approval Point 5", "Approval Point 5", "Approval Point 5", "Approval Point 6", "approval Point 7"}); verifySupervisoryNodeNameOrderOnPage(new String[]{"Approval Point 13", "Approval Point 12", "Approval Point 21", "Approval Point 13", "Approval Point 5", "Approval Point 15", "Approval Point 20", "Approval Point 6", "Approval Point 8", "Approval Point 9"}); navigateToLastPage(); verifyPageNumberSelected(3); verifyNextAndLastPageLinksDisabled(); verifyPreviousAndFirstPageLinksEnabled(); verifyNumberOfLineItemsVisibleOnPage(1); navigateToPreviousPage(); verifyPageNumberSelected(2); verifyNextAndLastPageLinksEnabled(); verifyPreviousAndFirstPageLinksEnabled(); verifyNumberOfLineItemsVisibleOnPage(10); supervisoryNodesPage.closeSearchResults(); assertFalse(supervisoryNodesPage.isSupervisoryNodeHeaderPresent()); } @Test(groups = {"admin"}) public void testSupervisoryNodeParentSearchSortAndPagination() throws SQLException, FileNotFoundException { dbWrapper.assignRight("Admin", "MANAGE_SUPERVISORY_NODE"); dbWrapper.insertSupervisoryNode("F10", "N1", "Node1", null); dbWrapper.insertSupervisoryNode("F11", "N2", "Node2", null); dbWrapper.insertSupervisoryNode("F10", "N3", "Node3", "N2"); HomePage homePage = loginPage.loginAs(testData.get(ADMIN), testData.get(PASSWORD)); UploadPage uploadPage = homePage.navigateUploads(); uploadPage.uploadSupervisoryNodes("QA_supervisoryNodes21.csv"); uploadPage.verifySuccessMessageOnUploadScreen(); SupervisoryNodesPage supervisoryNodesPage = homePage.navigateToSupervisoryNodes(); assertEquals("Supervisory node", supervisoryNodesPage.getSelectedSearchOption()); supervisoryNodesPage.clickSearchOptionButton(); supervisoryNodesPage.selectSupervisoryNodeParentAsSearchOption(); assertEquals("Supervisory node parent", supervisoryNodesPage.getSelectedSearchOption()); searchNode("Approval Point"); assertEquals("14 matches found for 'Approval Point'", supervisoryNodesPage.getNResultsMessage()); searchNode("Ap"); assertEquals("14 matches found for 'Ap'", supervisoryNodesPage.getNResultsMessage()); verifyNumberOFPageLinksDisplayed(16, 10); verifyPageNumberLinksDisplayed(); verifyPageNumberSelected(1); verifyNextAndLastPageLinksEnabled(); verifyPreviousAndFirstPageLinksDisabled(); verifyNumberOfLineItemsVisibleOnPage(10); verifyParentNameOrderOnPage(new String[]{"Approval Point 10", "Approval Point 3", "Approval Point 3", "Approval Point 3", "approval Point 4", "approval Point 4", "Approval Point 5", "Approval Point 5", "Approval Point 5", "Approval Point 6"}); verifySupervisoryNodeNameOrderOnPage(new String[]{"Approval Point 13", "Approval Point 12", "Approval Point 21", "Node3", "Approval Point 13", "Approval Point 5", "Approval Point 15", "Approval Point 20", "Approval Point 6", "Approval Point 8"}); navigateToPage(2); verifyPageNumberSelected(2); verifyNextAndLastPageLinksDisabled(); verifyPreviousAndFirstPageLinksEnabled(); verifyNumberOfLineItemsVisibleOnPage(4); verifyParentNameOrderOnPage(new String[]{"approval Point 7", "Approval Point 8", "Approval Point 8", "Approval Point 9"}); verifySupervisoryNodeNameOrderOnPage(new String[]{"Approval Point 9", "Approval Point 11", "Approval Point 13", "Approval Point 13"}); navigateToFirstPage(); verifyPageNumberSelected(1); verifyNextAndLastPageLinksEnabled(); verifyPreviousAndFirstPageLinksDisabled(); verifyNumberOfLineItemsVisibleOnPage(10); verifyParentNameOrderOnPage(new String[]{"Approval Point 10", "Approval Point 3", "Approval Point 3", "Approval Point 3", "approval Point 4", "approval Point 4", "Approval Point 5", "Approval Point 5", "Approval Point 5", "Approval Point 6"}); verifySupervisoryNodeNameOrderOnPage(new String[]{"Approval Point 13", "Approval Point 12", "Approval Point 21", "Node3", "Approval Point 13", "Approval Point 5", "Approval Point 15", "Approval Point 20", "Approval Point 6", "Approval Point 8"}); navigateToLastPage(); verifyPageNumberSelected(2); verifyNextAndLastPageLinksDisabled(); verifyPreviousAndFirstPageLinksEnabled(); verifyNumberOfLineItemsVisibleOnPage(4); navigateToPreviousPage(); verifyPageNumberSelected(1); verifyNextAndLastPageLinksEnabled(); verifyPreviousAndFirstPageLinksDisabled(); verifyNumberOfLineItemsVisibleOnPage(10); } @Test(groups = {"admin"}) public void testSupervisoryNodeParentSearchWhenNoResults() throws SQLException { dbWrapper.assignRight("Admin", "MANAGE_SUPERVISORY_NODE"); dbWrapper.insertSupervisoryNode("F10", "N1", "Super1", null); HomePage homePage = loginPage.loginAs(testData.get(ADMIN), testData.get(PASSWORD)); SupervisoryNodesPage supervisoryNodesPage = homePage.navigateToSupervisoryNodes(); assertEquals("Supervisory node", supervisoryNodesPage.getSelectedSearchOption()); supervisoryNodesPage.clickSearchOptionButton(); supervisoryNodesPage.selectSupervisoryNodeParentAsSearchOption(); assertEquals("Supervisory node parent", supervisoryNodesPage.getSelectedSearchOption()); searchNode("nod"); assertTrue(supervisoryNodesPage.isNoResultMessageDisplayed()); supervisoryNodesPage.clickSearchOptionButton(); supervisoryNodesPage.selectSupervisoryNodeAsSearchOption(); assertTrue(supervisoryNodesPage.isNoResultMessageDisplayed()); dbWrapper.insertSupervisoryNode("F10", "N2", "Node2", null); testWebDriver.refresh(); searchNode("nod"); assertTrue(supervisoryNodesPage.isOneResultMessageDisplayed()); assertEquals("Node2", supervisoryNodesPage.getSupervisoryNodeName(1)); assertEquals("N2", supervisoryNodesPage.getSupervisoryNodeCode(1)); assertEquals("Village Dispensary", supervisoryNodesPage.getFacility(1)); assertEquals("", supervisoryNodesPage.getParent(1)); supervisoryNodesPage.clickSearchOptionButton(); supervisoryNodesPage.selectSupervisoryNodeParentAsSearchOption(); supervisoryNodesPage.clickSearchIcon(); testWebDriver.waitForAjax(); assertTrue(supervisoryNodesPage.isNoResultMessageDisplayed()); } //@Test(groups = {"admin"}) public void testAddNewSupervisoryNode() throws SQLException { dbWrapper.assignRight("Admin", "MANAGE_SUPERVISORY_NODE"); HomePage homePage = loginPage.loginAs(testData.get(ADMIN), testData.get(PASSWORD)); SupervisoryNodesPage supervisoryNodesPage = homePage.navigateToSupervisoryNodes(); supervisoryNodesPage.clickAddNewButton(); //add a valid supervisoryNode //click save searchNode(""); //enter the one added //verify it supervisoryNodesPage.clickAddNewButton(); //add same node //verify error message //add new with parent as previous one //click save searchNode(""); //new added //verify supervisoryNodesPage.clickSearchOptionButton(); supervisoryNodesPage.selectSupervisoryNodeParentAsSearchOption(); searchNode(""); //previously added //verify supervisoryNodesPage.clickAddNewButton(); //add same node //verify error message //add new with parent as previous one //click cancel supervisoryNodesPage.clickSearchOptionButton(); supervisoryNodesPage.selectSupervisoryNodeAsSearchOption(); searchNode(""); //new added //verify no result } //@Test(groups = {"admin"}) public void testUpdateSupervisoryNode() throws SQLException { dbWrapper.assignRight("Admin", "MANAGE_SUPERVISORY_NODE"); dbWrapper.insertSupervisoryNode("F10", "N1", "Super1", null); dbWrapper.insertSupervisoryNode("F11", "N2", "Super2", null); HomePage homePage = loginPage.loginAs(testData.get(ADMIN), testData.get(PASSWORD)); SupervisoryNodesPage supervisoryNodesPage = homePage.navigateToSupervisoryNodes(); searchNode("sup"); //click the resultant Super1 //update the code and parent //click save searchNode("sup"); assertFalse(supervisoryNodesPage.isOneResultMessageDisplayed()); assertTrue(supervisoryNodesPage.isNoResultMessageDisplayed()); searchNode(""); //new code assertTrue(supervisoryNodesPage.isOneResultMessageDisplayed()); searchNode("sup"); //click the resultant //update the code as the last updated code and parent //click save //verify error msg //update code //enter invalid parent //verify error message //enter parent as the new code above //verify error msg //enter valid parent //click save searchNode(""); //new code assertTrue(supervisoryNodesPage.isOneResultMessageDisplayed()); //click the resultant //update code //click cancel searchNode(""); //new code assertTrue(supervisoryNodesPage.isNoResultMessageDisplayed()); } public void searchNode(String searchParameter) { SupervisoryNodesPage supervisoryNodesPage = PageObjectFactory.getSupervisoryNodesPage(testWebDriver); supervisoryNodesPage.enterSearchParameter(searchParameter); supervisoryNodesPage.clickSearchIcon(); testWebDriver.waitForAjax(); } private void verifySupervisoryNodeNameOrderOnPage(String[] nodeNames) { SupervisoryNodesPage supervisoryNodesPage = PageObjectFactory.getSupervisoryNodesPage(testWebDriver); for (int i = 1; i < nodeNames.length; i++) { assertEquals(nodeNames[i - 1], supervisoryNodesPage.getSupervisoryNodeName(i)); } } private void verifyParentNameOrderOnPage(String[] parentNames) { SupervisoryNodesPage supervisoryNodesPage = PageObjectFactory.getSupervisoryNodesPage(testWebDriver); for (int i = 1; i < parentNames.length; i++) { assertEquals(parentNames[i - 1], supervisoryNodesPage.getParent(i)); } } private void verifyNumberOfLineItemsVisibleOnPage(int numberOfLineItems) { assertEquals(numberOfLineItems, testWebDriver.getElementsSizeByXpath("//table[@id='supervisoryNodesTable']/tbody/tr")); } @AfterMethod(groups = {"admin"}) public void tearDown() throws SQLException { HomePage homePage = PageObjectFactory.getHomePage(testWebDriver); homePage.logout(baseUrlGlobal); dbWrapper.deleteData(); dbWrapper.closeConnection(); } }
package org.kuali.kfs.module.ar.document; import java.sql.Date; import java.sql.Timestamp; import java.util.Calendar; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang.StringUtils; import org.kuali.kfs.coa.businessobject.Account; import org.kuali.kfs.coa.businessobject.Chart; import org.kuali.kfs.coa.businessobject.ObjectCode; import org.kuali.kfs.coa.businessobject.Organization; import org.kuali.kfs.coa.businessobject.ProjectCode; import org.kuali.kfs.coa.businessobject.SubAccount; import org.kuali.kfs.coa.businessobject.SubObjectCode; import org.kuali.kfs.module.ar.ArConstants; import org.kuali.kfs.module.ar.businessobject.AccountsReceivableDocumentHeader; import org.kuali.kfs.module.ar.businessobject.Customer; import org.kuali.kfs.module.ar.businessobject.CustomerAddress; import org.kuali.kfs.module.ar.businessobject.CustomerInvoiceDetail; import org.kuali.kfs.module.ar.businessobject.CustomerInvoiceRecurrenceDetails; import org.kuali.kfs.module.ar.businessobject.CustomerProcessingType; import org.kuali.kfs.module.ar.businessobject.InvoiceRecurrence; import org.kuali.kfs.module.ar.businessobject.PrintInvoiceOptions; import org.kuali.kfs.module.ar.businessobject.ReceivableCustomerInvoiceDetail; import org.kuali.kfs.module.ar.businessobject.SalesTaxCustomerInvoiceDetail; import org.kuali.kfs.module.ar.document.service.AccountsReceivableTaxService; import org.kuali.kfs.module.ar.document.service.CustomerAddressService; import org.kuali.kfs.module.ar.document.service.CustomerInvoiceDetailService; import org.kuali.kfs.module.ar.document.service.CustomerInvoiceDocumentService; import org.kuali.kfs.module.ar.document.service.CustomerInvoiceGLPEService; import org.kuali.kfs.module.ar.document.service.InvoicePaidAppliedService; import org.kuali.kfs.sys.businessobject.GeneralLedgerPendingEntrySequenceHelper; import org.kuali.kfs.sys.businessobject.GeneralLedgerPendingEntrySourceDetail; import org.kuali.kfs.sys.businessobject.TaxDetail; import org.kuali.kfs.sys.context.SpringContext; import org.kuali.kfs.sys.document.AccountingDocumentBase; import org.kuali.kfs.sys.document.AmountTotaling; import org.kuali.kfs.sys.document.Correctable; import org.kuali.kfs.sys.service.GeneralLedgerPendingEntryService; import org.kuali.kfs.sys.service.TaxService; import org.kuali.rice.kew.exception.WorkflowException; import org.kuali.rice.kns.UserSession; import org.kuali.rice.kns.document.Copyable; import org.kuali.rice.kns.document.MaintenanceDocument; import org.kuali.rice.kns.service.BusinessObjectService; import org.kuali.rice.kns.service.DateTimeService; import org.kuali.rice.kns.service.DocumentService; import org.kuali.rice.kns.service.ParameterService; import org.kuali.rice.kns.util.DateUtils; import org.kuali.rice.kns.util.GlobalVariables; import org.kuali.rice.kns.util.KualiDecimal; import org.kuali.rice.kns.util.ObjectUtils; import org.kuali.rice.kns.util.TypedArrayList; /** * @author Kuali Nervous System Team (kualidev@oncourse.iu.edu) */ public class CustomerInvoiceDocument extends AccountingDocumentBase implements AmountTotaling, Copyable, Correctable, Comparable<CustomerInvoiceDocument> { private static final String HAS_RECCURENCE_NODE = "HasReccurence"; private String invoiceHeaderText; private String invoiceAttentionLineText; private Date invoiceDueDate; private Date billingDate; private Date closedDate; private Date billingDateForDisplay; private String invoiceTermsText; private String organizationInvoiceNumber; private String customerPurchaseOrderNumber; private String printInvoiceIndicator; private Date customerPurchaseOrderDate; private String billByChartOfAccountCode; private String billedByOrganizationCode; private Integer customerShipToAddressIdentifier; private Integer customerBillToAddressIdentifier; private String customerSpecialProcessingCode; private boolean customerRecordAttachmentIndicator; private boolean openInvoiceIndicator; private String paymentChartOfAccountsCode; private String paymentAccountNumber; private String paymentSubAccountNumber; private String paymentFinancialObjectCode; private String paymentFinancialSubObjectCode; private String paymentProjectCode; private String paymentOrganizationReferenceIdentifier; private Date printDate; private Integer age; private String customerName; private String billingAddressName; private String billingCityName; private String billingStateCode; private String billingZipCode; private String billingCountryCode; private String billingAddressInternationalProvinceName; private String billingInternationalMailCode; private String billingEmailAddress; private String billingAddressTypeCode; private String billingLine1StreetAddress; private String billingLine2StreetAddress; private String shippingLine1StreetAddress; private String shippingLine2StreetAddress; private String shippingAddressName; private String shippingCityName; private String shippingStateCode; private String shippingZipCode; private String shippingCountryCode; private String shippingAddressInternationalProvinceName; private String shippingInternationalMailCode; private String shippingEmailAddress; private String shippingAddressTypeCode; private boolean recurredInvoiceIndicator; private AccountsReceivableDocumentHeader accountsReceivableDocumentHeader; private Chart billByChartOfAccount; private Organization billedByOrganization; private CustomerProcessingType customerSpecialProcessing; private Account paymentAccount; private Chart paymentChartOfAccounts; private SubAccount paymentSubAccount; private ObjectCode paymentFinancialObject; private SubObjectCode paymentFinancialSubObject; private ProjectCode paymentProject; private PrintInvoiceOptions printInvoiceOption; private CustomerAddress customerShipToAddress; private CustomerAddress customerBillToAddress; private CustomerInvoiceRecurrenceDetails customerInvoiceRecurrenceDetails; // added for quick apply check control private boolean quickApply; /** * Default constructor. */ public CustomerInvoiceDocument() { super(); } /** * This method calculates the outstanding balance on an invoice. * * @return the outstanding balance on this invoice */ public KualiDecimal getOpenAmount() { return SpringContext.getBean(CustomerInvoiceDocumentService.class).getOpenAmountForCustomerInvoiceDocument(this); } public void setOpenAmount(KualiDecimal openAmount) { // do nothing } public void setBalance(KualiDecimal balance) { // do nothing } public void setSourceTotal(KualiDecimal sourceTotal) { // do nothing } /** * Gets the documentNumber attribute. * * @return Returns the documentNumber */ public String getDocumentNumber() { return documentNumber; } /** * Sets the documentNumber attribute. * * @param documentNumber The documentNumber to set. */ public void setDocumentNumber(String documentNumber) { this.documentNumber = documentNumber; } /** * Gets the invoiceHeaderText attribute. * * @return Returns the invoiceHeaderText */ public String getInvoiceHeaderText() { return invoiceHeaderText; } /** * Sets the invoiceHeaderText attribute. * * @param invoiceHeaderText The invoiceHeaderText to set. */ public void setInvoiceHeaderText(String invoiceHeaderText) { this.invoiceHeaderText = invoiceHeaderText; } /** * Gets the invoiceAttentionLineText attribute. * * @return Returns the invoiceAttentionLineText */ public String getInvoiceAttentionLineText() { return invoiceAttentionLineText; } /** * Sets the invoiceAttentionLineText attribute. * * @param invoiceAttentionLineText The invoiceAttentionLineText to set. */ public void setInvoiceAttentionLineText(String invoiceAttentionLineText) { this.invoiceAttentionLineText = invoiceAttentionLineText; } /** * Gets the invoiceDueDate attribute. * * @return Returns the invoiceDueDate */ public Date getInvoiceDueDate() { return invoiceDueDate; } /** * Sets the invoiceDueDate attribute. * * @param invoiceDueDate The invoiceDueDate to set. */ public void setInvoiceDueDate(Date invoiceDueDate) { this.invoiceDueDate = invoiceDueDate; } /** * Gets the billingDate attribute. * * @return Returns the billingDate */ public Date getBillingDate() { return billingDate; } /** * This method returns the age of an invoice (i.e. current date - billing date) * * @return */ public Integer getAge() { if (ObjectUtils.isNotNull(billingDate)) { return (int) DateUtils.getDifferenceInDays(new Timestamp(billingDate.getTime()), SpringContext.getBean(DateTimeService.class).getCurrentTimestamp()); } // TODO should I be throwing an exception or throwing a null? return null; } public void setAge(Integer age) { this.age = age; } /** * Sets the billingDate attribute. * * @param billingDate The billingDate to set. */ public void setBillingDate(Date billingDate) { this.billingDate = billingDate; } /** * Gets the invoiceTermsText attribute. * * @return Returns the invoiceTermsText */ public String getInvoiceTermsText() { return invoiceTermsText; } /** * Sets the invoiceTermsText attribute. * * @param invoiceTermsText The invoiceTermsText to set. */ public void setInvoiceTermsText(String invoiceTermsText) { this.invoiceTermsText = invoiceTermsText; } /** * Gets the organizationInvoiceNumber attribute. * * @return Returns the organizationInvoiceNumber */ public String getOrganizationInvoiceNumber() { return organizationInvoiceNumber; } /** * Sets the organizationInvoiceNumber attribute. * * @param organizationInvoiceNumber The organizationInvoiceNumber to set. */ public void setOrganizationInvoiceNumber(String organizationInvoiceNumber) { this.organizationInvoiceNumber = organizationInvoiceNumber; } /** * Gets the customerPurchaseOrderNumber attribute. * * @return Returns the customerPurchaseOrderNumber */ public String getCustomerPurchaseOrderNumber() { return customerPurchaseOrderNumber; } /** * Sets the customerPurchaseOrderNumber attribute. * * @param customerPurchaseOrderNumber The customerPurchaseOrderNumber to set. */ public void setCustomerPurchaseOrderNumber(String customerPurchaseOrderNumber) { this.customerPurchaseOrderNumber = customerPurchaseOrderNumber; } /** * Gets the printInvoiceIndicator attribute. * * @return Returns the printInvoiceIndicator. */ public String getPrintInvoiceIndicator() { return printInvoiceIndicator; } /** * Sets the printInvoiceIndicator attribute value. * * @param printInvoiceIndicator The printInvoiceIndicator to set. */ public void setPrintInvoiceIndicator(String printInvoiceIndicator) { this.printInvoiceIndicator = printInvoiceIndicator; } /** * Gets the customerPurchaseOrderDate attribute. * * @return Returns the customerPurchaseOrderDate */ public Date getCustomerPurchaseOrderDate() { return customerPurchaseOrderDate; } /** * Sets the customerPurchaseOrderDate attribute. * * @param customerPurchaseOrderDate The customerPurchaseOrderDate to set. */ public void setCustomerPurchaseOrderDate(Date customerPurchaseOrderDate) { this.customerPurchaseOrderDate = customerPurchaseOrderDate; } /** * Gets the billByChartOfAccountCode attribute. * * @return Returns the billByChartOfAccountCode */ public String getBillByChartOfAccountCode() { return billByChartOfAccountCode; } /** * Sets the billByChartOfAccountCode attribute. * * @param billByChartOfAccountCode The billByChartOfAccountCode to set. */ public void setBillByChartOfAccountCode(String billByChartOfAccountCode) { this.billByChartOfAccountCode = billByChartOfAccountCode; } /** * Gets the billedByOrganizationCode attribute. * * @return Returns the billedByOrganizationCode */ public String getBilledByOrganizationCode() { return billedByOrganizationCode; } /** * Sets the billedByOrganizationCode attribute. * * @param billedByOrganizationCode The billedByOrganizationCode to set. */ public void setBilledByOrganizationCode(String billedByOrganizationCode) { this.billedByOrganizationCode = billedByOrganizationCode; } /** * Gets the customerShipToAddressIdentifier attribute. * * @return Returns the customerShipToAddressIdentifier */ public Integer getCustomerShipToAddressIdentifier() { return customerShipToAddressIdentifier; } /** * Sets the customerShipToAddressIdentifier attribute. * * @param customerShipToAddressIdentifier The customerShipToAddressIdentifier to set. */ public void setCustomerShipToAddressIdentifier(Integer customerShipToAddressIdentifier) { this.customerShipToAddressIdentifier = customerShipToAddressIdentifier; } /** * Gets the customerBillToAddressIdentifier attribute. * * @return Returns the customerBillToAddressIdentifier */ public Integer getCustomerBillToAddressIdentifier() { return customerBillToAddressIdentifier; } /** * Sets the customerBillToAddressIdentifier attribute. * * @param customerBillToAddressIdentifier The customerBillToAddressIdentifier to set. */ public void setCustomerBillToAddressIdentifier(Integer customerBillToAddressIdentifier) { this.customerBillToAddressIdentifier = customerBillToAddressIdentifier; } /** * Gets the customerSpecialProcessingCode attribute. * * @return Returns the customerSpecialProcessingCode */ public String getCustomerSpecialProcessingCode() { return customerSpecialProcessingCode; } /** * Sets the customerSpecialProcessingCode attribute. * * @param customerSpecialProcessingCode The customerSpecialProcessingCode to set. */ public void setCustomerSpecialProcessingCode(String customerSpecialProcessingCode) { this.customerSpecialProcessingCode = customerSpecialProcessingCode; } /** * Gets the customerRecordAttachmentIndicator attribute. * * @return Returns the customerRecordAttachmentIndicator */ public boolean isCustomerRecordAttachmentIndicator() { return customerRecordAttachmentIndicator; } /** * Sets the customerRecordAttachmentIndicator attribute. * * @param customerRecordAttachmentIndicator The customerRecordAttachmentIndicator to set. */ public void setCustomerRecordAttachmentIndicator(boolean customerRecordAttachmentIndicator) { this.customerRecordAttachmentIndicator = customerRecordAttachmentIndicator; } /** * Gets the openInvoiceIndicator attribute. * * @return Returns the openInvoiceIndicator */ public boolean isOpenInvoiceIndicator() { return openInvoiceIndicator; } /** * Sets the openInvoiceIndicator attribute. * * @param openInvoiceIndicator The openInvoiceIndicator to set. */ public void setOpenInvoiceIndicator(boolean openInvoiceIndicator) { this.openInvoiceIndicator = openInvoiceIndicator; } /** * Gets the paymentAccountNumber attribute. * * @return Returns the paymentAccountNumber. */ public String getPaymentAccountNumber() { return paymentAccountNumber; } /** * Sets the paymentAccountNumber attribute value. * * @param paymentAccountNumber The paymentAccountNumber to set. */ public void setPaymentAccountNumber(String paymentAccountNumber) { this.paymentAccountNumber = paymentAccountNumber; } /** * Gets the paymentChartOfAccountsCode attribute. * * @return Returns the paymentChartOfAccountsCode. */ public String getPaymentChartOfAccountsCode() { return paymentChartOfAccountsCode; } /** * Sets the paymentChartOfAccountsCode attribute value. * * @param paymentChartOfAccountsCode The paymentChartOfAccountsCode to set. */ public void setPaymentChartOfAccountsCode(String paymentChartOfAccountsCode) { this.paymentChartOfAccountsCode = paymentChartOfAccountsCode; } /** * Gets the paymentFinancialObjectCode attribute. * * @return Returns the paymentFinancialObjectCode. */ public String getPaymentFinancialObjectCode() { return paymentFinancialObjectCode; } /** * Sets the paymentFinancialObjectCode attribute value. * * @param paymentFinancialObjectCode The paymentFinancialObjectCode to set. */ public void setPaymentFinancialObjectCode(String paymentFinancialObjectCode) { this.paymentFinancialObjectCode = paymentFinancialObjectCode; } /** * Gets the paymentFinancialSubObjectCode attribute. * * @return Returns the paymentFinancialSubObjectCode. */ public String getPaymentFinancialSubObjectCode() { return paymentFinancialSubObjectCode; } /** * Sets the paymentFinancialSubObjectCode attribute value. * * @param paymentFinancialSubObjectCode The paymentFinancialSubObjectCode to set. */ public void setPaymentFinancialSubObjectCode(String paymentFinancialSubObjectCode) { this.paymentFinancialSubObjectCode = paymentFinancialSubObjectCode; } /** * Gets the paymentOrganizationReferenceIdentifier attribute. * * @return Returns the paymentOrganizationReferenceIdentifier. */ public String getPaymentOrganizationReferenceIdentifier() { return paymentOrganizationReferenceIdentifier; } /** * Sets the paymentOrganizationReferenceIdentifier attribute value. * * @param paymentOrganizationReferenceIdentifier The paymentOrganizationReferenceIdentifier to set. */ public void setPaymentOrganizationReferenceIdentifier(String paymentOrganizationReferenceIdentifier) { this.paymentOrganizationReferenceIdentifier = paymentOrganizationReferenceIdentifier; } /** * Gets the paymentProjectCode attribute. * * @return Returns the paymentProjectCode. */ public String getPaymentProjectCode() { return paymentProjectCode; } /** * Sets the paymentProjectCode attribute value. * * @param paymentProjectCode The paymentProjectCode to set. */ public void setPaymentProjectCode(String paymentProjectCode) { this.paymentProjectCode = paymentProjectCode; } /** * Gets the paymentSubAccountNumber attribute. * * @return Returns the paymentSubAccountNumber. */ public String getPaymentSubAccountNumber() { return paymentSubAccountNumber; } /** * Sets the paymentSubAccountNumber attribute value. * * @param paymentSubAccountNumber The paymentSubAccountNumber to set. */ public void setPaymentSubAccountNumber(String paymentSubAccountNumber) { this.paymentSubAccountNumber = paymentSubAccountNumber; } /** * Gets the printDate attribute. * * @return Returns the printDate */ public Date getPrintDate() { return printDate; } /** * Sets the printDate attribute. * * @param printDate The printDate to set. */ public void setPrintDate(Date printDate) { this.printDate = printDate; } /** * Gets the accountsReceivableDocumentHeader attribute. * * @return Returns the accountsReceivableDocumentHeader */ public AccountsReceivableDocumentHeader getAccountsReceivableDocumentHeader() { return accountsReceivableDocumentHeader; } /** * Sets the accountsReceivableDocumentHeader attribute. * * @param accountsReceivableDocumentHeader The accountsReceivableDocumentHeader to set. */ public void setAccountsReceivableDocumentHeader(AccountsReceivableDocumentHeader accountsReceivableDocumentHeader) { this.accountsReceivableDocumentHeader = accountsReceivableDocumentHeader; } /** * Gets the billByChartOfAccount attribute. * * @return Returns the billByChartOfAccount */ public Chart getBillByChartOfAccount() { return billByChartOfAccount; } /** * Sets the billByChartOfAccount attribute. * * @param billByChartOfAccount The billByChartOfAccount to set. * @deprecated */ public void setBillByChartOfAccount(Chart billByChartOfAccount) { this.billByChartOfAccount = billByChartOfAccount; } /** * Gets the billedByOrganization attribute. * * @return Returns the billedByOrganization */ public Organization getBilledByOrganization() { return billedByOrganization; } /** * Sets the billedByOrganization attribute. * * @param billedByOrganization The billedByOrganization to set. * @deprecated */ public void setBilledByOrganization(Organization billedByOrganization) { this.billedByOrganization = billedByOrganization; } /** * Gets the customerSpecialProcessing attribute. * * @return Returns the customerSpecialProcessing */ public CustomerProcessingType getCustomerSpecialProcessing() { return customerSpecialProcessing; } /** * Sets the customerSpecialProcessing attribute. * * @param customerSpecialProcessing The customerSpecialProcessing to set. * @deprecated */ public void setCustomerSpecialProcessing(CustomerProcessingType customerSpecialProcessing) { this.customerSpecialProcessing = customerSpecialProcessing; } /** * Gets the paymentAccount attribute. * * @return Returns the paymentAccount. */ public Account getPaymentAccount() { return paymentAccount; } /** * Sets the paymentAccount attribute value. * * @param paymentAccount The paymentAccount to set. * @deprecated */ public void setPaymentAccount(Account paymentAccount) { this.paymentAccount = paymentAccount; } /** * Gets the paymentChartOfAccounts attribute. * * @return Returns the paymentChartOfAccounts. */ public Chart getPaymentChartOfAccounts() { return paymentChartOfAccounts; } /** * Sets the paymentChartOfAccounts attribute value. * * @param paymentChartOfAccounts The paymentChartOfAccounts to set. * @deprecated */ public void setPaymentChartOfAccounts(Chart paymentChartOfAccounts) { this.paymentChartOfAccounts = paymentChartOfAccounts; } /** * Gets the paymentFinancialObject attribute. * * @return Returns the paymentFinancialObject. */ public ObjectCode getPaymentFinancialObject() { return paymentFinancialObject; } /** * Sets the paymentFinancialObject attribute value. * * @param paymentFinancialObject The paymentFinancialObject to set. * @deprecated */ public void setPaymentFinancialObject(ObjectCode paymentFinancialObject) { this.paymentFinancialObject = paymentFinancialObject; } /** * Gets the paymentFinancialSubObject attribute. * * @return Returns the paymentFinancialSubObject. */ public SubObjectCode getPaymentFinancialSubObject() { return paymentFinancialSubObject; } /** * Sets the paymentFinancialSubObject attribute value. * * @param paymentFinancialSubObject The paymentFinancialSubObject to set. * @deprecated */ public void setPaymentFinancialSubObject(SubObjectCode paymentFinancialSubObject) { this.paymentFinancialSubObject = paymentFinancialSubObject; } /** * Gets the paymentProject attribute. * * @return Returns the paymentProject. */ public ProjectCode getPaymentProject() { return paymentProject; } /** * Sets the paymentProject attribute value. * * @param paymentProject The paymentProject to set. * @deprecated */ public void setPaymentProject(ProjectCode paymentProject) { this.paymentProject = paymentProject; } /** * Gets the paymentSubAccount attribute. * * @return Returns the paymentSubAccount. */ public SubAccount getPaymentSubAccount() { return paymentSubAccount; } /** * Sets the paymentSubAccount attribute value. * * @param paymentSubAccount The paymentSubAccount to set. * @deprecated */ public void setPaymentSubAccount(SubAccount paymentSubAccount) { this.paymentSubAccount = paymentSubAccount; } /** * This method returns the billing date for display. If billing date hasn't been set yet, just display current date * * @return */ public Date getBillingDateForDisplay() { if (ObjectUtils.isNotNull(getBillingDate())) { return getBillingDate(); } else { return SpringContext.getBean(DateTimeService.class).getCurrentSqlDate(); } } /** * This method... * * @param date */ public void setBillingDateForDisplay(Date date) { // do nothing } public Date getClosedDate() { return closedDate; } public void setClosedDate(Date closedDate) { this.closedDate = closedDate; } /** * @see org.kuali.rice.kns.bo.BusinessObjectBase#toStringMapper() */ @SuppressWarnings("unchecked") protected LinkedHashMap toStringMapper() { LinkedHashMap m = new LinkedHashMap(); m.put("documentNumber", this.documentNumber); return m; } /** * This method returns true if this document is a reversal for another document * * @return */ public boolean isInvoiceReversal() { return ObjectUtils.isNotNull(getDocumentHeader().getFinancialDocumentInErrorNumber()); } /** * @see org.kuali.kfs.sys.document.AccountingDocumentBase#isDebit(org.kuali.kfs.sys.businessobject.GeneralLedgerPendingEntrySourceDetail) */ @Override public boolean isDebit(GeneralLedgerPendingEntrySourceDetail postable) { return ((CustomerInvoiceDetail) postable).isDebit(); } /** * @see org.kuali.kfs.sys.document.AccountingDocumentBase#getSourceAccountingLineClass() */ @Override public Class<CustomerInvoiceDetail> getSourceAccountingLineClass() { return CustomerInvoiceDetail.class; } /** * Ensures that all the accounts receivable object codes are correctly updated */ public void updateAccountReceivableObjectCodes() { for (Iterator e = getSourceAccountingLines().iterator(); e.hasNext();) { SpringContext.getBean(CustomerInvoiceDetailService.class).updateAccountsReceivableObjectCode(((CustomerInvoiceDetail) e.next())); } } /** * This method creates the following GLPE's for the invoice 1. Debit to receivable for total line amount ( including sales tax * if it exists ). 2. Credit to income based on item price * quantity. 3. Credit to state sales tax account/object code if state * sales tax exists. 4. Credit to district sales tax account/object code if district sales tax exists. * * @see org.kuali.kfs.service.impl.GenericGeneralLedgerPendingEntryGenerationProcessImpl#processGenerateGeneralLedgerPendingEntries(org.kuali.kfs.sys.document.GeneralLedgerPendingEntrySource, * org.kuali.kfs.sys.businessobject.GeneralLedgerPendingEntrySourceDetail, * org.kuali.kfs.sys.businessobject.GeneralLedgerPendingEntrySequenceHelper) */ @Override public boolean generateGeneralLedgerPendingEntries(GeneralLedgerPendingEntrySourceDetail glpeSourceDetail, GeneralLedgerPendingEntrySequenceHelper sequenceHelper) { String receivableOffsetOption = SpringContext.getBean(ParameterService.class).getParameterValue(CustomerInvoiceDocument.class, ArConstants.GLPE_RECEIVABLE_OFFSET_GENERATION_METHOD); boolean hasClaimOnCashOffset = ArConstants.GLPE_RECEIVABLE_OFFSET_GENERATION_METHOD_FAU.equals(receivableOffsetOption); addReceivableGLPEs(sequenceHelper, glpeSourceDetail, hasClaimOnCashOffset); sequenceHelper.increment(); addIncomeGLPEs(sequenceHelper, glpeSourceDetail, hasClaimOnCashOffset); // if sales tax is enabled generate GLPEs if (SpringContext.getBean(AccountsReceivableTaxService.class).isCustomerInvoiceDetailTaxable(this, (CustomerInvoiceDetail) glpeSourceDetail)) { addSalesTaxGLPEs(sequenceHelper, glpeSourceDetail, hasClaimOnCashOffset); } return true; } /** * This method creates the receivable GLPEs for each invoice detail line. * * @param poster * @param sequenceHelper * @param postable * @param explicitEntry */ protected void addReceivableGLPEs(GeneralLedgerPendingEntrySequenceHelper sequenceHelper, GeneralLedgerPendingEntrySourceDetail glpeSourceDetail, boolean hasClaimOnCashOffset) { CustomerInvoiceDetail customerInvoiceDetail = (CustomerInvoiceDetail) glpeSourceDetail; ReceivableCustomerInvoiceDetail receivableCustomerInvoiceDetail = new ReceivableCustomerInvoiceDetail(customerInvoiceDetail, this); boolean isDebit = (!isInvoiceReversal() && !customerInvoiceDetail.isDiscountLine()) || (isInvoiceReversal() && customerInvoiceDetail.isDiscountLine()); CustomerInvoiceGLPEService service = SpringContext.getBean(CustomerInvoiceGLPEService.class); service.createAndAddGenericInvoiceRelatedGLPEs(this, receivableCustomerInvoiceDetail, sequenceHelper, isDebit, hasClaimOnCashOffset, customerInvoiceDetail.getInvoiceItemPreTaxAmount()); } /** * This method adds pending entry with transaction ledger entry amount set to item price * quantity * * @param poster * @param sequenceHelper * @param postable * @param explicitEntry */ protected void addIncomeGLPEs(GeneralLedgerPendingEntrySequenceHelper sequenceHelper, GeneralLedgerPendingEntrySourceDetail glpeSourceDetail, boolean hasClaimOnCashOffset) { CustomerInvoiceDetail customerInvoiceDetail = (CustomerInvoiceDetail) glpeSourceDetail; boolean isDebit = (!isInvoiceReversal() && customerInvoiceDetail.isDiscountLine()) || (isInvoiceReversal() && !customerInvoiceDetail.isDiscountLine()); CustomerInvoiceGLPEService service = SpringContext.getBean(CustomerInvoiceGLPEService.class); service.createAndAddGenericInvoiceRelatedGLPEs(this, customerInvoiceDetail, sequenceHelper, isDebit, hasClaimOnCashOffset, customerInvoiceDetail.getInvoiceItemPreTaxAmount()); } /** * This method add pending entries for every tax detail that exists for a particular postal code * * @param sequenceHelper * @param glpeSourceDetail * @param hasClaimOnCashOffset */ protected void addSalesTaxGLPEs(GeneralLedgerPendingEntrySequenceHelper sequenceHelper, GeneralLedgerPendingEntrySourceDetail glpeSourceDetail, boolean hasClaimOnCashOffset) { CustomerInvoiceDetail customerInvoiceDetail = (CustomerInvoiceDetail) glpeSourceDetail; boolean isDebit = (!isInvoiceReversal() && customerInvoiceDetail.isDiscountLine()) || (isInvoiceReversal() && !customerInvoiceDetail.isDiscountLine()); String postalCode = SpringContext.getBean(AccountsReceivableTaxService.class).getPostalCodeForTaxation(this); Date dateOfTransaction = SpringContext.getBean(DateTimeService.class).getCurrentSqlDate(); List<TaxDetail> salesTaxDetails = SpringContext.getBean(TaxService.class).getSalesTaxDetails(dateOfTransaction, postalCode, customerInvoiceDetail.getInvoiceItemPreTaxAmount()); CustomerInvoiceGLPEService service = SpringContext.getBean(CustomerInvoiceGLPEService.class); SalesTaxCustomerInvoiceDetail salesTaxCustomerInvoiceDetail; ReceivableCustomerInvoiceDetail receivableCustomerInvoiceDetail; for (TaxDetail salesTaxDetail : salesTaxDetails) { salesTaxCustomerInvoiceDetail = new SalesTaxCustomerInvoiceDetail(salesTaxDetail, customerInvoiceDetail); receivableCustomerInvoiceDetail = new ReceivableCustomerInvoiceDetail(salesTaxCustomerInvoiceDetail, this); sequenceHelper.increment(); service.createAndAddGenericInvoiceRelatedGLPEs(this, receivableCustomerInvoiceDetail, sequenceHelper, !isDebit, hasClaimOnCashOffset, salesTaxDetail.getTaxAmount()); sequenceHelper.increment(); service.createAndAddGenericInvoiceRelatedGLPEs(this, salesTaxCustomerInvoiceDetail, sequenceHelper, isDebit, hasClaimOnCashOffset, salesTaxDetail.getTaxAmount()); } } /** * Returns an implementation of the GeneralLedgerPendingEntryService * * @return an implementation of the GeneralLedgerPendingEntryService */ public GeneralLedgerPendingEntryService getGeneralLedgerPendingEntryService() { return SpringContext.getBean(GeneralLedgerPendingEntryService.class); } /** * Returns a map with the primitive field names as the key and the primitive values as the map value. * * @return Map */ @SuppressWarnings("unchecked") public Map getValuesMap() { Map valuesMap = new HashMap(); valuesMap.put("postingYear", getPostingYear()); valuesMap.put("paymentChartOfAccountsCode", getPaymentChartOfAccountsCode()); valuesMap.put("paymentAccountNumber", getPaymentAccountNumber()); valuesMap.put("paymentFinancialObjectCode", getPaymentFinancialObjectCode()); valuesMap.put("paymentSubAccountNumber", getPaymentSubAccountNumber()); valuesMap.put("paymentFinancialSubObjectCode", getPaymentFinancialSubObjectCode()); valuesMap.put("paymentProjectCode", getPaymentProjectCode()); return valuesMap; } /** * When document is processed do the following: 1) Set the billingDate to today's date if not already set 2) If there are * discounts, create corresponding invoice paid applied rows 3) If the document is a reversal, in addition to reversing paid * applied rows, update the open paid applied indicator * * @see org.kuali.kfs.sys.document.GeneralLedgerPostingDocumentBase#handleRouteStatusChange() */ @Override public void handleRouteStatusChange() { super.handleRouteStatusChange(); // fast-exit if status != P if (!getDocumentHeader().getWorkflowDocument().stateIsProcessed()) { return; } // wire up the billing date if (ObjectUtils.isNull(getBillingDate())) { setBillingDate(SpringContext.getBean(DateTimeService.class).getCurrentSqlDateMidnight()); } // apply amounts InvoicePaidAppliedService paidAppliedService = SpringContext.getBean(InvoicePaidAppliedService.class); List<CustomerInvoiceDetail> discounts = this.getDiscounts(); paidAppliedService.saveInvoicePaidApplieds(discounts, documentNumber); // handle a Correction/Reversal document if (this.isInvoiceReversal()) { try { CustomerInvoiceDocument correctedCustomerInvoiceDocument = (CustomerInvoiceDocument) SpringContext.getBean(DocumentService.class).getByDocumentHeaderId(this.getDocumentHeader().getFinancialDocumentInErrorNumber()); // if reversal, close both this reversal invoice and the original invoice SpringContext.getBean(CustomerInvoiceDocumentService.class).closeCustomerInvoiceDocument(correctedCustomerInvoiceDocument); SpringContext.getBean(CustomerInvoiceDocumentService.class).closeCustomerInvoiceDocument(this); } catch (WorkflowException e) { throw new RuntimeException("Cannot find customer invoice document with id " + this.getDocumentHeader().getFinancialDocumentInErrorNumber()); } } // handle Recurrence if (ObjectUtils.isNull(this.getCustomerInvoiceRecurrenceDetails()) || (ObjectUtils.isNull(this.getCustomerInvoiceRecurrenceDetails().getDocumentRecurrenceBeginDate()) && ObjectUtils.isNull(this.getCustomerInvoiceRecurrenceDetails().getDocumentRecurrenceEndDate()) && ObjectUtils.isNull(this.getCustomerInvoiceRecurrenceDetails().getDocumentRecurrenceIntervalCode()) && ObjectUtils.isNull(this.getCustomerInvoiceRecurrenceDetails().getDocumentTotalRecurrenceNumber()) && ObjectUtils.isNull(this.getCustomerInvoiceRecurrenceDetails().getDocumentInitiatorUserIdentifier()))) { } else { try { // set new user session to recurrence initiator String initiator = this.getCustomerInvoiceRecurrenceDetails().getDocumentInitiatorUserPersonUserIdentifier(); GlobalVariables.setUserSession(new UserSession(initiator)); // populate InvoiceRecurrence business object InvoiceRecurrence newInvoiceRecurrence = new InvoiceRecurrence(); newInvoiceRecurrence.setInvoiceNumber(this.getCustomerInvoiceRecurrenceDetails().getInvoiceNumber()); newInvoiceRecurrence.setCustomerNumber(this.getCustomerInvoiceRecurrenceDetails().getCustomerNumber()); newInvoiceRecurrence.setDocumentRecurrenceBeginDate(this.getCustomerInvoiceRecurrenceDetails().getDocumentRecurrenceBeginDate()); newInvoiceRecurrence.setDocumentRecurrenceEndDate(this.getCustomerInvoiceRecurrenceDetails().getDocumentRecurrenceEndDate()); newInvoiceRecurrence.setDocumentRecurrenceIntervalCode(this.getCustomerInvoiceRecurrenceDetails().getDocumentRecurrenceIntervalCode()); newInvoiceRecurrence.setDocumentTotalRecurrenceNumber(this.getCustomerInvoiceRecurrenceDetails().getDocumentTotalRecurrenceNumber()); newInvoiceRecurrence.setDocumentInitiatorUserIdentifier(this.getCustomerInvoiceRecurrenceDetails().getDocumentInitiatorUserIdentifier()); newInvoiceRecurrence.setActive(this.getCustomerInvoiceRecurrenceDetails().isActive()); // create a new InvoiceRecurrenceMaintenanceDocument MaintenanceDocument invoiceRecurrenceMaintDoc = (MaintenanceDocument) SpringContext.getBean(DocumentService.class).getNewDocument(getInvoiceRecurrenceMaintenanceDocumentTypeName()); invoiceRecurrenceMaintDoc.getDocumentHeader().setDocumentDescription("Automatically created from Invoice"); invoiceRecurrenceMaintDoc.getNewMaintainableObject().setBusinessObject(newInvoiceRecurrence); // route InvoiceRecurrenceMaintenanceDocument SpringContext.getBean(DocumentService.class).routeDocument(invoiceRecurrenceMaintDoc, null, null); } catch (WorkflowException e) { throw new RuntimeException("Cannot find Invoice Recurrence Maintenance Document with id " + this.getDocumentHeader().getFinancialDocumentInErrorNumber()); } } } private String getInvoiceRecurrenceMaintenanceDocumentTypeName() { return "INVR"; } /** * If this invoice is a reversal, set the open indicator to false * * @see org.kuali.kfs.sys.document.FinancialSystemTransactionalDocumentBase#prepareForSave() */ @Override public void prepareForSave() { if (this.isInvoiceReversal()) { setOpenInvoiceIndicator(false); } // invoice recurrence stuff, if there is a recurrence object if (ObjectUtils.isNotNull(this.getCustomerInvoiceRecurrenceDetails())) { // wire up the recurrence customer number if one exists if (ObjectUtils.isNull(this.getCustomerInvoiceRecurrenceDetails().getCustomerNumber())) { this.getCustomerInvoiceRecurrenceDetails().setCustomerNumber(this.getAccountsReceivableDocumentHeader().getCustomerNumber()); } // calc recurrence number if only end-date specified if (ObjectUtils.isNull(this.getCustomerInvoiceRecurrenceDetails().getDocumentTotalRecurrenceNumber()) && ObjectUtils.isNotNull(this.getCustomerInvoiceRecurrenceDetails().getDocumentRecurrenceEndDate())) { Calendar beginCalendar = Calendar.getInstance(); beginCalendar.setTime(this.getCustomerInvoiceRecurrenceDetails().getDocumentRecurrenceBeginDate()); Date beginDate = this.getCustomerInvoiceRecurrenceDetails().getDocumentRecurrenceBeginDate(); Calendar endCalendar = Calendar.getInstance(); endCalendar.setTime(this.getCustomerInvoiceRecurrenceDetails().getDocumentRecurrenceEndDate()); Date endDate = this.getCustomerInvoiceRecurrenceDetails().getDocumentRecurrenceEndDate(); Calendar nextCalendar = Calendar.getInstance(); Date nextDate = beginDate; int totalRecurrences = 0; int addCounter = 0; String intervalCode = this.getCustomerInvoiceRecurrenceDetails().getDocumentRecurrenceIntervalCode(); if (intervalCode.equals("M")) { addCounter = 1; } if (intervalCode.equals("Q")) { addCounter = 3; } /* perform this loop while begin_date is less than or equal to end_date */ while (!(beginDate.after(endDate))) { beginCalendar.setTime(beginDate); beginCalendar.add(Calendar.MONTH, addCounter); beginDate = DateUtils.convertToSqlDate(beginCalendar.getTime()); totalRecurrences++; nextDate = beginDate; nextCalendar.setTime(nextDate); nextCalendar.add(Calendar.MONTH, addCounter); nextDate = DateUtils.convertToSqlDate(nextCalendar.getTime()); if (endDate.after(beginDate) && endDate.before(nextDate)) { totalRecurrences++; break; } } if (totalRecurrences > 0) { this.getCustomerInvoiceRecurrenceDetails().setDocumentTotalRecurrenceNumber(totalRecurrences); } } // calc end-date if only recurrence-number is specified if (ObjectUtils.isNotNull(this.getCustomerInvoiceRecurrenceDetails().getDocumentTotalRecurrenceNumber()) && ObjectUtils.isNull(this.getCustomerInvoiceRecurrenceDetails().getDocumentRecurrenceEndDate())) { Calendar beginCalendar = Calendar.getInstance(); beginCalendar.setTime(new Timestamp(this.getCustomerInvoiceRecurrenceDetails().getDocumentRecurrenceBeginDate().getTime())); Calendar endCalendar = Calendar.getInstance(); endCalendar = beginCalendar; int addCounter = 0; Integer documentTotalRecurrenceNumber = this.getCustomerInvoiceRecurrenceDetails().getDocumentTotalRecurrenceNumber(); String intervalCode = this.getCustomerInvoiceRecurrenceDetails().getDocumentRecurrenceIntervalCode(); if (intervalCode.equals("M")) { addCounter = -1; addCounter += documentTotalRecurrenceNumber * 1; } if (intervalCode.equals("Q")) { addCounter = -3; addCounter += documentTotalRecurrenceNumber * 3; } endCalendar.add(Calendar.MONTH, addCounter); this.getCustomerInvoiceRecurrenceDetails().setDocumentRecurrenceEndDate(DateUtils.convertToSqlDate(endCalendar.getTime())); } } // Force upper case setBilledByOrganizationCode(getBilledByOrganizationCode().toUpperCase()); if (ObjectUtils.isNull(getCustomerShipToAddressIdentifier())) { setCustomerShipToAddress(null); setCustomerShipToAddressOnInvoice(null); } // get rid of the child object if there's not enough information there to make a recurrence if (ObjectUtils.isNotNull(this.getCustomerInvoiceRecurrenceDetails())) { boolean removeRecurrence = false; CustomerInvoiceRecurrenceDetails rec = this.getCustomerInvoiceRecurrenceDetails(); removeRecurrence |= (null == rec.getDocumentRecurrenceBeginDate()); removeRecurrence |= (null == rec.getCustomerNumber()); removeRecurrence |= (null == rec.getDocumentInitiatorUserIdentifier()); removeRecurrence |= (null == rec.getDocumentRecurrenceIntervalCode()); removeRecurrence |= (!rec.isActive()); if (removeRecurrence) { deleteChildRecurrenceObject(); this.setCustomerInvoiceRecurrenceDetails(null); } else { // need to make sure the fk/pk for the recurrence is wired up, this is // necessary if the person repeatedly adds a recurrence, saves, deletes a // recurrence, saves, and then adds one again. if (ObjectUtils.isNotNull(customerInvoiceRecurrenceDetails)) { customerInvoiceRecurrenceDetails.setInvoiceNumber(getDocumentNumber()); } } } } // since the fk for this child object is also the pk of the parent object, we cant do the normal way of doing this, // and just clear the fk primitive field on the parent object, and we have to get all explicit about it. private void deleteChildRecurrenceObject() { BusinessObjectService boService = SpringContext.getBean(BusinessObjectService.class); Map<String,String> pks = new HashMap<String,String>(); pks.put("invoiceNumber", getDocumentNumber()); CustomerInvoiceRecurrenceDetails dbRecurrence = (CustomerInvoiceRecurrenceDetails) boService.findByPrimaryKey(CustomerInvoiceRecurrenceDetails.class, pks); if (dbRecurrence != null) { boService.delete(dbRecurrence); } } /** * @see org.kuali.kfs.sys.document.AccountingDocumentBase#toCopy() */ @Override public void toCopy() throws WorkflowException { super.toCopy(); SpringContext.getBean(CustomerInvoiceDocumentService.class).setupDefaultValuesForCopiedCustomerInvoiceDocument(this); } /** * @see org.kuali.kfs.sys.document.GeneralLedgerPostingDocumentBase#toErrorCorrection() */ @Override public void toErrorCorrection() throws WorkflowException { super.toErrorCorrection(); negateCustomerInvoiceDetailUnitPrices(); this.setOpenInvoiceIndicator(false); // if we dont force this on the error correction, the recurrence will // have the old doc number, and will revert the main doc due to OJB fun, // which will cause PK unique index failure. if (ObjectUtils.isNotNull(customerInvoiceRecurrenceDetails)) { customerInvoiceRecurrenceDetails.setInvoiceNumber(this.documentNumber); } } /** * This method... */ @SuppressWarnings("unchecked") public void negateCustomerInvoiceDetailUnitPrices() { CustomerInvoiceDetail customerInvoiceDetail; for (Iterator i = getSourceAccountingLines().iterator(); i.hasNext();) { customerInvoiceDetail = (CustomerInvoiceDetail) i.next(); customerInvoiceDetail.setInvoiceItemUnitPrice(customerInvoiceDetail.getInvoiceItemUnitPrice().negate()); } } /** * This method returns true if invoice document has at least one discount line * * @return */ @SuppressWarnings("unchecked") public boolean hasAtLeastOneDiscount() { CustomerInvoiceDetail customerInvoiceDetail; for (Iterator i = getSourceAccountingLines().iterator(); i.hasNext();) { customerInvoiceDetail = (CustomerInvoiceDetail) i.next(); if (customerInvoiceDetail.isDiscountLineParent()) { return true; } } return false; } /** * This method returns true if line number is discount line number based on sequence number * * @param sequenceNumber * @return */ @SuppressWarnings("unchecked") public boolean isDiscountLineBasedOnSequenceNumber(Integer sequenceNumber) { if (ObjectUtils.isNull(sequenceNumber)) { return false; } CustomerInvoiceDetail customerInvoiceDetail; for (Iterator i = getSourceAccountingLines().iterator(); i.hasNext();) { customerInvoiceDetail = (CustomerInvoiceDetail) i.next(); Integer discLineNum = customerInvoiceDetail.getInvoiceItemDiscountLineNumber(); // check if sequence number is referenced as a discount line for another customer invoice detail (i.e. the parent line) if (ObjectUtils.isNotNull(discLineNum) && sequenceNumber.equals(customerInvoiceDetail.getInvoiceItemDiscountLineNumber())) { return true; } } return false; } /** * This method returns parent customer invoice detail based on child discount sequence number * * @param sequenceNumber * @return */ @SuppressWarnings("unchecked") public CustomerInvoiceDetail getParentLineBasedOnDiscountSequenceNumber(Integer discountSequenceNumber) { if (ObjectUtils.isNull(discountSequenceNumber)) { return null; } CustomerInvoiceDetail customerInvoiceDetail; for (Iterator i = getSourceAccountingLines().iterator(); i.hasNext();) { customerInvoiceDetail = (CustomerInvoiceDetail) i.next(); Integer discLineNum = customerInvoiceDetail.getInvoiceItemDiscountLineNumber(); if (ObjectUtils.isNotNull(discLineNum) && discountSequenceNumber.equals(customerInvoiceDetail.getInvoiceItemDiscountLineNumber())) { return customerInvoiceDetail; } } return null; } /** * This method is called on CustomerInvoiceDocumentAction.execute() to set isDiscount to true if it truly is a discount line */ @SuppressWarnings("unchecked") public void updateDiscountAndParentLineReferences() { CustomerInvoiceDetail discount; for (Iterator i = getSourceAccountingLines().iterator(); i.hasNext();) { discount = (CustomerInvoiceDetail) i.next(); // get sequence number and check if theres a corresponding parent line for that discount line CustomerInvoiceDetail parent = getParentLineBasedOnDiscountSequenceNumber(discount.getSequenceNumber()); if (ObjectUtils.isNotNull(parent)) { discount.setParentDiscountCustomerInvoiceDetail(parent); parent.setDiscountCustomerInvoiceDetail(discount); } else { discount.setParentDiscountCustomerInvoiceDetail(null); } } } /** * This method removes the corresponding discount line based on the index of the parent line index. This assumes that the * discount line is ALWAYS after the index of the parent line. * * @param deleteIndex */ public void removeDiscountLineBasedOnParentLineIndex(int parentLineIndex) { // get parent line line CustomerInvoiceDetail parentLine = (CustomerInvoiceDetail) getSourceAccountingLines().get(parentLineIndex); // get index for discount line int discountLineIndex = -1; // this should ALWAYS get set for (int i = 0; i < getSourceAccountingLines().size(); i++) { if (parentLine.getInvoiceItemDiscountLineNumber().equals(((CustomerInvoiceDetail) getSourceAccountingLines().get(i)).getSequenceNumber())) { discountLineIndex = i; } } // remove discount line getSourceAccountingLines().remove(discountLineIndex); } public CustomerInvoiceRecurrenceDetails getCustomerInvoiceRecurrenceDetails() { return customerInvoiceRecurrenceDetails; } public void setCustomerInvoiceRecurrenceDetails(CustomerInvoiceRecurrenceDetails customerInvoiceRecurrenceDetails) { this.customerInvoiceRecurrenceDetails = customerInvoiceRecurrenceDetails; } public CustomerAddress getCustomerShipToAddress() { return customerShipToAddress; } public void setCustomerShipToAddress(CustomerAddress customerShipToAddress) { this.customerShipToAddress = customerShipToAddress; } public CustomerAddress getCustomerBillToAddress() { return customerBillToAddress; } public void setCustomerBillToAddress(CustomerAddress customerBillToAddress) { this.customerBillToAddress = customerBillToAddress; } public PrintInvoiceOptions getPrintInvoiceOption() { if (ObjectUtils.isNull(printInvoiceOption) && StringUtils.isNotEmpty(printInvoiceIndicator)){ refreshReferenceObject("printInvoiceOption"); } return printInvoiceOption; } public void setPrintInvoiceOption(PrintInvoiceOptions printInvoiceOption) { this.printInvoiceOption = printInvoiceOption; } /** * This method returns the total of all pre tax amounts for all customer invoice detail lines * * @return */ public KualiDecimal getInvoiceItemPreTaxAmountTotal() { KualiDecimal invoiceItemPreTaxAmountTotal = new KualiDecimal(0); for (Iterator i = getSourceAccountingLines().iterator(); i.hasNext();) { invoiceItemPreTaxAmountTotal = invoiceItemPreTaxAmountTotal.add(((CustomerInvoiceDetail) i.next()).getInvoiceItemPreTaxAmount()); } return invoiceItemPreTaxAmountTotal; } /** * This method returns the total of all tax amounts for all customer invoice detail lines * * @return */ public KualiDecimal getInvoiceItemTaxAmountTotal() { KualiDecimal invoiceItemTaxAmountTotal = new KualiDecimal(0); for (Iterator i = getSourceAccountingLines().iterator(); i.hasNext();) { invoiceItemTaxAmountTotal = invoiceItemTaxAmountTotal.add(((CustomerInvoiceDetail) i.next()).getInvoiceItemTaxAmount()); } return invoiceItemTaxAmountTotal; } /** * This method returns the primary customer address for the customer number provided. * * @return */ public CustomerAddress getPrimaryAddressForCustomerNumber() { if (ObjectUtils.isNotNull(accountsReceivableDocumentHeader) && StringUtils.isNotEmpty(accountsReceivableDocumentHeader.getCustomerNumber())) { return SpringContext.getBean(CustomerAddressService.class).getPrimaryAddress(accountsReceivableDocumentHeader.getCustomerNumber()); } return null; } /** * This method returns the customer object for the invoice * * @return */ public Customer getCustomer() { if (ObjectUtils.isNotNull(accountsReceivableDocumentHeader)) { return accountsReceivableDocumentHeader.getCustomer(); } return null; } /** * This method will return all the customer invoice details excluding discount invoice detail lines. * * @return */ public List<CustomerInvoiceDetail> getCustomerInvoiceDetailsWithoutDiscounts() { List<CustomerInvoiceDetail> customerInvoiceDetailsWithoutDiscounts = new TypedArrayList(CustomerInvoiceDetail.class); updateDiscountAndParentLineReferences(); List<CustomerInvoiceDetail> customerInvoiceDetailsWithDiscounts = getSourceAccountingLines(); for (CustomerInvoiceDetail customerInvoiceDetail : customerInvoiceDetailsWithDiscounts) { if (!customerInvoiceDetail.isDiscountLine()) { customerInvoiceDetail.setDocumentNumber(getDocumentNumber()); customerInvoiceDetailsWithoutDiscounts.add(customerInvoiceDetail); } } return customerInvoiceDetailsWithoutDiscounts; } /** * This method could be a bit dangerous. It's meant to be used only on the payment application document, where the modified * invoice is never saved. * * @param customerInvoiceDetails */ public void setCustomerInvoiceDetailsWithoutDiscounts(List<CustomerInvoiceDetail> customerInvoiceDetails) { List<CustomerInvoiceDetail> customerInvoiceDetailsWithoutDiscounts = getSourceAccountingLines(); int sequenceCounter = 0; for (CustomerInvoiceDetail customerInvoiceDetail : customerInvoiceDetailsWithoutDiscounts) { for (CustomerInvoiceDetail revisedCustomerInvoiceDetail : customerInvoiceDetails) { if (!customerInvoiceDetail.isDiscountLine() && customerInvoiceDetail.getSequenceNumber().equals(revisedCustomerInvoiceDetail.getSequenceNumber())) { customerInvoiceDetailsWithoutDiscounts.remove(sequenceCounter); customerInvoiceDetailsWithoutDiscounts.add(sequenceCounter, revisedCustomerInvoiceDetail); } } sequenceCounter += 1; } setSourceAccountingLines(customerInvoiceDetailsWithoutDiscounts); } /** * This method will return all the customer invoice details that are discounts * * @return */ public List<CustomerInvoiceDetail> getDiscounts() { List<CustomerInvoiceDetail> discounts = new TypedArrayList(CustomerInvoiceDetail.class); updateDiscountAndParentLineReferences(); List<CustomerInvoiceDetail> customerInvoiceDetailsWithDiscounts = getSourceAccountingLines(); for (CustomerInvoiceDetail customerInvoiceDetail : customerInvoiceDetailsWithDiscounts) { if (customerInvoiceDetail.isDiscountLine()) { customerInvoiceDetail.setDocumentNumber(getDocumentNumber()); discounts.add(customerInvoiceDetail); } } return discounts; } public int compareTo(CustomerInvoiceDocument customerInvoiceDocument) { if (this.getBillByChartOfAccountCode().equals(customerInvoiceDocument.getBillByChartOfAccountCode())) if (this.getBilledByOrganizationCode().equals(customerInvoiceDocument.getBilledByOrganizationCode())) return 0; return -1; } /** * * Returns whether or not the Invoice would be paid off by applying the additional amount, passed in * by the parameter. * * @param additionalAmountToApply The additional applied amount to test against. * @return True if applying the additionalAmountToApply parameter amount would bring the OpenAmount to zero. */ public boolean wouldPayOff(KualiDecimal additionalAmountToApply) { KualiDecimal openAmount = getOpenAmount(); return KualiDecimal.ZERO.isGreaterEqual(openAmount.subtract(additionalAmountToApply)); } @Override public KualiDecimal getTotalDollarAmount() { return getSourceTotal(); } public String getBillingAddressInternationalProvinceName() { return billingAddressInternationalProvinceName; } public void setBillingAddressInternationalProvinceName(String billingAddressInternationalProvinceName) { this.billingAddressInternationalProvinceName = billingAddressInternationalProvinceName; } public String getBillingAddressName() { return billingAddressName; } public void setBillingAddressName(String billingAddressName) { this.billingAddressName = billingAddressName; } public String getBillingAddressTypeCode() { return billingAddressTypeCode; } public void setBillingAddressTypeCode(String billingAddressTypeCode) { this.billingAddressTypeCode = billingAddressTypeCode; } public String getBillingCityName() { return billingCityName; } public void setBillingCityName(String billingCityName) { this.billingCityName = billingCityName; } public String getBillingCountryCode() { return billingCountryCode; } public void setBillingCountryCode(String billingCountryCode) { this.billingCountryCode = billingCountryCode; } public String getBillingEmailAddress() { return billingEmailAddress; } public void setBillingEmailAddress(String billingEmailAddress) { this.billingEmailAddress = billingEmailAddress; } public String getBillingInternationalMailCode() { return billingInternationalMailCode; } public void setBillingInternationalMailCode(String billingInternationalMailCode) { this.billingInternationalMailCode = billingInternationalMailCode; } public String getBillingStateCode() { return billingStateCode; } public void setBillingStateCode(String billingStateCode) { this.billingStateCode = billingStateCode; } public String getBillingZipCode() { return billingZipCode; } public void setBillingZipCode(String billingZipCode) { this.billingZipCode = billingZipCode; } public String getCustomerName() { return customerName; } public void setCustomerName(String customerName) { this.customerName = customerName; } public String getShippingAddressInternationalProvinceName() { return shippingAddressInternationalProvinceName; } public void setShippingAddressInternationalProvinceName(String shippingAddressInternationalProvinceName) { this.shippingAddressInternationalProvinceName = shippingAddressInternationalProvinceName; } public String getShippingAddressName() { return shippingAddressName; } public void setShippingAddressName(String shippingAddressName) { this.shippingAddressName = shippingAddressName; } public String getShippingAddressTypeCode() { return shippingAddressTypeCode; } public void setShippingAddressTypeCode(String shippingAddressTypeCode) { this.shippingAddressTypeCode = shippingAddressTypeCode; } public String getShippingCityName() { return shippingCityName; } public void setShippingCityName(String shippingCityName) { this.shippingCityName = shippingCityName; } public String getShippingCountryCode() { return shippingCountryCode; } public void setShippingCountryCode(String shippingCountryCode) { this.shippingCountryCode = shippingCountryCode; } public String getShippingEmailAddress() { return shippingEmailAddress; } public void setShippingEmailAddress(String shippingEmailAddress) { this.shippingEmailAddress = shippingEmailAddress; } public String getShippingInternationalMailCode() { return shippingInternationalMailCode; } public void setShippingInternationalMailCode(String shippingInternationalMailCode) { this.shippingInternationalMailCode = shippingInternationalMailCode; } public String getShippingStateCode() { return shippingStateCode; } public void setShippingStateCode(String shippingStateCode) { this.shippingStateCode = shippingStateCode; } public String getShippingZipCode() { return shippingZipCode; } public void setShippingZipCode(String shippingZipCode) { this.shippingZipCode = shippingZipCode; } public String getBillingLine1StreetAddress() { return billingLine1StreetAddress; } public void setBillingLine1StreetAddress(String billingLine1StreetAddress) { this.billingLine1StreetAddress = billingLine1StreetAddress; } public String getBillingLine2StreetAddress() { return billingLine2StreetAddress; } public void setBillingLine2StreetAddress(String billingLine2StreetAddress) { this.billingLine2StreetAddress = billingLine2StreetAddress; } public String getShippingLine1StreetAddress() { return shippingLine1StreetAddress; } public void setShippingLine1StreetAddress(String shippingLine1StreetAddress) { this.shippingLine1StreetAddress = shippingLine1StreetAddress; } public String getShippingLine2StreetAddress() { return shippingLine2StreetAddress; } public void setShippingLine2StreetAddress(String shippingLine2StreetAddress) { this.shippingLine2StreetAddress = shippingLine2StreetAddress; } public boolean getRecurredInvoiceIndicator() { return recurredInvoiceIndicator; } public void setRecurredInvoiceIndicator(boolean recurredInvoiceIndicator) { this.recurredInvoiceIndicator = recurredInvoiceIndicator; } /** * Get a string representation for billing chart/organization * * @return */ public String getBilledByChartOfAccCodeAndOrgCode() { String returnVal = getBillByChartOfAccountCode() + "/" + getBilledByOrganizationCode(); return returnVal; } /** * Populate Customer Billing Address fields on Customer Invoice. * * @return */ public void setCustomerBillToAddressOnInvoice(CustomerAddress customerBillToAddress) { accountsReceivableDocumentHeader.refreshReferenceObject("customer"); this.setCustomerName(accountsReceivableDocumentHeader.getCustomer().getCustomerName()); this.setBillingAddressTypeCode(customerBillToAddress.getCustomerAddressTypeCode()); this.setBillingAddressName(customerBillToAddress.getCustomerAddressName()); this.setBillingLine1StreetAddress(customerBillToAddress.getCustomerLine1StreetAddress()); this.setBillingLine2StreetAddress(customerBillToAddress.getCustomerLine2StreetAddress()); this.setBillingCityName(customerBillToAddress.getCustomerCityName()); this.setBillingStateCode(customerBillToAddress.getCustomerStateCode()); this.setBillingZipCode(customerBillToAddress.getCustomerZipCode()); this.setBillingCountryCode(customerBillToAddress.getCustomerCountryCode()); this.setBillingAddressInternationalProvinceName(customerBillToAddress.getCustomerAddressInternationalProvinceName()); this.setBillingInternationalMailCode(customerBillToAddress.getCustomerInternationalMailCode()); this.setBillingEmailAddress(customerBillToAddress.getCustomerEmailAddress()); } /** * Populate Customer Shipping Address fields on Customer Invoice. * * @return */ public void setCustomerShipToAddressOnInvoice(CustomerAddress customerShipToAddress) { accountsReceivableDocumentHeader.refreshReferenceObject("customer"); Customer customer = accountsReceivableDocumentHeader.getCustomer(); if (ObjectUtils.isNotNull(customer)) this.setCustomerName(customer.getCustomerName()); if (ObjectUtils.isNotNull(customerShipToAddress)) { this.setShippingAddressTypeCode(customerShipToAddress.getCustomerAddressTypeCode()); this.setShippingAddressName(customerShipToAddress.getCustomerAddressName()); this.setShippingLine1StreetAddress(customerShipToAddress.getCustomerLine1StreetAddress()); this.setShippingLine2StreetAddress(customerShipToAddress.getCustomerLine2StreetAddress()); this.setShippingCityName(customerShipToAddress.getCustomerCityName()); this.setShippingStateCode(customerShipToAddress.getCustomerStateCode()); this.setShippingZipCode(customerShipToAddress.getCustomerZipCode()); this.setShippingCountryCode(customerShipToAddress.getCustomerCountryCode()); this.setShippingAddressInternationalProvinceName(customerShipToAddress.getCustomerAddressInternationalProvinceName()); this.setShippingInternationalMailCode(customerShipToAddress.getCustomerInternationalMailCode()); this.setShippingEmailAddress(customerShipToAddress.getCustomerEmailAddress()); } else { this.setShippingAddressTypeCode(null); this.setShippingAddressName(null); this.setShippingLine1StreetAddress(null); this.setShippingLine2StreetAddress(null); this.setShippingCityName(null); this.setShippingStateCode(null); this.setShippingZipCode(null); this.setShippingCountryCode(null); this.setShippingAddressInternationalProvinceName(null); this.setShippingInternationalMailCode(null); this.setShippingEmailAddress(null); } } /** * Gets the quickApply attribute. * * @return Returns the quickApply. */ public boolean isQuickApply() { return quickApply; } public boolean getQuickApply() { return isQuickApply(); } /** * Sets the quickApply attribute value. * * @param quickApply The quickApply to set. */ public void setQuickApply(boolean quickApply) { this.quickApply = quickApply; } /** * Answers true when invoice recurrence details are provided by the user * * @see org.kuali.kfs.sys.document.FinancialSystemTransactionalDocumentBase#answerSplitNodeQuestion(java.lang.String) */ @Override public boolean answerSplitNodeQuestion(String nodeName) throws UnsupportedOperationException { if (HAS_RECCURENCE_NODE.equals(nodeName)) { return hasRecurrence(); } throw new UnsupportedOperationException("answerSplitNode('" + nodeName + "') was called but no handler for nodeName specified."); } private boolean hasRecurrence() { return (ObjectUtils.isNotNull(getCustomerInvoiceRecurrenceDetails()) && getCustomerInvoiceRecurrenceDetails().isActive()); } }
package org.apache.batik.apps.regsvggen; import java.io.*; //import java.io.BufferedInputStream; //import java.io.BufferedOutputStream; //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.io.PrintStream; //import java.io.FileWriter; //import java.io.PrintWriter; //import java.util.Calendar; import java.util.*; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics2D; import java.awt.GraphicsEnvironment; import java.awt.RenderingHints; import java.awt.Shape; import java.awt.Rectangle; import java.awt.geom.GeneralPath; import java.awt.image.BufferedImage; import java.awt.image.Raster; import java.awt.image.SampleModel; import java.awt.image.SinglePixelPackedSampleModel; import java.awt.image.DataBuffer; import java.awt.image.DataBufferInt; import java.net.MalformedURLException; import org.apache.batik.transcoder.TranscoderInput; import org.apache.batik.transcoder.TranscoderOutput; import org.apache.batik.transcoder.image.ImageTranscoder; import org.apache.batik.transcoder.image.PNGTranscoder; import org.apache.batik.dom.GenericDOMImplementation; import org.apache.batik.dom.util.SAXDocumentFactory; import org.apache.batik.ext.awt.image.ImageLoader; import org.apache.batik.ext.awt.image.GraphicsUtil; import org.apache.batik.svggen.*; import org.apache.batik.css.CSSDocumentHandler; import org.apache.batik.dom.svg.SVGDOMImplementation; import org.xml.sax.InputSource; import org.w3c.dom.*; /** * A regression checking tool for SVG generator test cases. * * @author <a href="mailto:spei@cs.uiowa.edu">Sheng Pei</a> * @version $Id$ */ public class Main { // The following section defines the Directory names /** The regsvggen root directory name. */ static final String REGSVGGEN_DIRECTORY_NAME = "regsvggen"; /** This directory contains images transcoded from SVG files * that're from SVG Generator */ static final String REGSVGGEN_REF_DIRECTORY_NAME = "ref"; /** This directory contains images encoded directly from * the BufferedImage */ static final String REGSVGGEN_NEW_DIRECTORY_NAME = "new"; /** This directory contains the svg files that're generated * dynamically by the Classes which use Java codes embedded * in the XML test cases */ static final String REGSVGGEN_SVG_DIRECTORY_NAME = "svg"; /** This directory contains the xml test cases */ static final String REGSVGGEN_XML_DIRECTORY_NAME = "xml"; /** This sub directory contains the difference images. */ static final String REGSVGGEN_DIFF_DIRECTORY_NAME = "diff"; /** This sub directory contains the temp class files. */ static final String REGSVGGEN_CLASSES_DIRECTORY_NAME = "classes"; // The following section defines the Report file /** The regsvggen report file name */ static final String REGSVGGEN_REPORT_FILE_NAME = "report"; /** The regsvggen report file extension */ static final String REGSVGGEN_REPORT_FILE_EXT = "html"; /** The regsvggen report head string */ static final String REGSVGGEN_REPORT_HEAD_STRING = "<!doctype html public " + "\"" + "-//w3c//dtd html 4.0 transitional//en" + "\"" + "> <html> <body> <center>Batik Regression Guard Tool(Regsvggen) Report</center>"; /** The regsvggen report end string */ static final String REGSVGGEN_REPORT_END_STRING = "</body> </html>"; /** The regsvggen report no-regression string */ static final String REGSVGGEN_REPORT_NO_REGRESSION_STRING ="<p>There's no file that has regression.<br>"; static final String CLASSPATH_SEPARATOR = System.getProperty("path.separator", ";"); static final String FILE_SEPARATOR = System.getProperty("file.separator", "/"); // The following section defines the Class constants and variables private static final String EOL = "\n"; private static final String IMPORT = "import"; private static final String ATTR_TEXT_AS_SHAPES = "textAsShapes"; private static final String TEST_PACKAGE = "usecases"; private static final String testPackage = "package " + TEST_PACKAGE + ";\n\n"; private static final String testImports = "import java.awt.*; \n import java.awt.image.*; \n import org.apache.batik.apps.regsvggen.Painter; \n import java.awt.geom.*; \n import java.awt.font.*; \n"; private static final String testClassDec = " implements Painter {\n\n\tstatic final String IMAGE_DIR=\"/work/doc/svg/src/usecases/html/images/\";\n\n\tpublic void paint(Graphics2D g){"; private static final String testFinish = "\tpublic Dimension getSize(){ \n\t\treturn new Dimension(300, 400); \n\t} \n\n}"; private static final String testOutName = "CompileOut"; private static final String classDir = "." + FILE_SEPARATOR + "regsvggen" + FILE_SEPARATOR + "classes"; /** * The CSS parser class name key. */ public final static String CSS_PARSER_CLASS_NAME = "org.apache.batik.css.parser.Parser"; /** * MAIN */ public static void main(String [] args) { // Setting the Fonts GraphicsEnvironment env; env = GraphicsEnvironment.getLocalGraphicsEnvironment(); String fontNames[] = env.getAvailableFontFamilyNames(); int nFonts = fontNames != null ? fontNames.length : 0; for(int i=0; i<nFonts; i++){ System.out.print("."); // display("Initializing the fonts..."); //fonts.put(fontNames[i], fontNames[i]); } System.out.println(); if (args.length != 1) { usage(System.err); exit(1); } if (args[0].equals("-help")) { usage(System.out); exit(0); } else if (args[0].equals("-init")) { init(); } else if (args[0].equals("-reset")) { reset(); } else if (args[0].equals("-go")) { setUp(); generateGraphics(); generateRefImages(); diffImage(); cleanUp(); } else { usage(System.err); exit(1); } } /** * INITILIZATION * * Creates the regsvggen directory and its sub directories. */ public static void init() { File f = new File(REGSVGGEN_DIRECTORY_NAME); if (!f.exists()) { display("Creating "+f.getAbsolutePath()); f.mkdir(); File ff = new File(f, REGSVGGEN_XML_DIRECTORY_NAME); ff.mkdir(); display("Creating "+ff.getAbsolutePath()); ff = new File(f, REGSVGGEN_SVG_DIRECTORY_NAME); ff.mkdir(); display("Creating "+ff.getAbsolutePath()); ff = new File(f, REGSVGGEN_DIFF_DIRECTORY_NAME); ff.mkdir(); display("Creating "+ff.getAbsolutePath()); ff = new File(f, REGSVGGEN_NEW_DIRECTORY_NAME); ff.mkdir(); display("Creating temp directory: "+ff.getAbsolutePath()); exit(0); } else { error(f.getAbsolutePath()+" already exists"); exit(2); } } /** * GO * * The main processing unit, devided into four parts: * 1. setUp() -- generate temp directories: ref and new * 2. generateGraphics() -- load XML file, create Classes, generate * PNG image in "new" and SVG file in "svg" * 3. generateRefImages() -- generate PNG image from SVG files into "ref" * 4. diffImage() -- compare the images between "ref" and "new", * generate reports * 5. cleanUp() -- delete temp files and directories */ public static void setUp(){ File f = new File(REGSVGGEN_DIRECTORY_NAME); if(!f.exists()){ display("The regsvggen hasn't been initilized. Use -init"); exit(2); } else { File ff = new File(f, REGSVGGEN_REF_DIRECTORY_NAME); ff.mkdir(); display("Creating temp directory: "+ff.getAbsolutePath()); ff = new File(f, REGSVGGEN_CLASSES_DIRECTORY_NAME); ff.mkdir(); display("Creating temp directory:"+ff.getAbsolutePath()); } } public static void generateGraphics(){ File xmlDir = new File(getXmlDirectory()); File [] xmlFiles = xmlDir.listFiles(); if (xmlFiles == null){ error("No XML files has been found in "+ xmlDir.getAbsolutePath()); exit(2); } File xmlFile; File nowImage; String testFileName; String testName; String testImageName; String dClassName; for (int i=0; i<xmlFiles.length; i++){ xmlFile = xmlFiles[i]; testFileName = xmlFile.getAbsolutePath(); testName = getImageName(xmlFile.getName()); if (!testFileName.endsWith(".xml")){continue;} try { dClassName = compileTestClass(testFileName); nowImage = new File(getNewDirectory(), testName); testImageName = nowImage.getAbsolutePath(); createBufImage(dClassName, testImageName); nowImage = new File(getSvgDirectory(), testName); testImageName = nowImage.getAbsolutePath().substring(0, testImageName.length() - 4) + ".svg"; createSvgFile(dClassName, testImageName); } catch (Exception e){ display("Error when loading classes: " + e.toString()); } } } /** * The gui resources file name */ public final static String RESOURCES = "org.apache.batik.apps.regsvggen.resources.Messages"; /** * The resource bundle */ protected static ResourceBundle bundle; static { bundle = ResourceBundle.getBundle(RESOURCES, Locale.getDefault()); } /** * This method will do the following: * 1. Load the test case XML file specified by testFileName * 2. Extract the Java code in the XML file and merge a Java source file * 3. Compile the temparory Java source file and get the Class name */ public static String compileTestClass(String testFileName) throws Exception{ // Load xml test file SAXDocumentFactory df = new SAXDocumentFactory (GenericDOMImplementation.getDOMImplementation(), bundle.getString("org.xml.sax.driver")); Document testDoc = null; try { testDoc = df.createDocument(null, "text", new File(testFileName).toURL().toString()); } catch (Exception e){ e.printStackTrace(); display("Error: " + e.toString()); throw e; } // Get Test Title Element root = testDoc.getDocumentElement(); // Get text convertion strategy. Defaults to false. String textAsShapesAttr = root.getAttribute(ATTR_TEXT_AS_SHAPES); if(textAsShapesAttr == null) textAsShapesAttr = "false"; // Get Test Description /* NodeList testDescriptions = root.getElementsByTagName(DESCRIPTION); String descriptions[] = new String[testDescriptions.getLength()]; for(int i=0; i<descriptions.length; i++) descriptions[i] = testDescriptions.item(i).getFirstChild().getNodeValue(); */ // Get node that contains the Java Code to be compiled NodeList codeNodes = testDoc.getElementsByTagName("javaCode"); StringBuffer javaCode = new StringBuffer(); int nCodeNodes = codeNodes.getLength(); int nCD = 0; for(int i=0; i<nCodeNodes; i++){ Element codeNode = (Element)codeNodes.item(i); NodeList codeDefs = codeNode.getChildNodes(); int nCodeDefs = codeDefs.getLength(); for(int j=0; j<nCodeDefs; j++){ Node codeDef = codeDefs.item(j); // display("Child of type: " + codeDef.getNodeType()); javaCode.append(codeDef.getNodeValue()); javaCode.append("\n"); } } // display("Found : " + nCodeNodes + " javaCode elements and " + nCD + " CDATA sections"); // Get additional imports NodeList importNodes = testDoc.getElementsByTagName(IMPORT); StringBuffer imports = new StringBuffer(); int nImports = importNodes.getLength(); for(int i=0; i<nImports; i++){ Element importNode = (Element)importNodes.item(i); imports.append(importNode.getFirstChild().getNodeValue()); imports.append("\n"); } // display("Imports: " + imports.toString()); // Create a temporary file for compiling the test File tmpSourceFile = File.createTempFile("SVGGeneratorTest", ".java"); String className = tmpSourceFile.getName().substring(0, tmpSourceFile.getName().length() - 5); // Write source in temporary file Writer ow = new OutputStreamWriter(new FileOutputStream(tmpSourceFile)); ow.write(testPackage); ow.write(testImports); ow.write(imports.toString()); ow.write("public class " + className + testClassDec); ow.write(javaCode.toString()); ow.write("\n\t}\n\n\tpublic boolean isTextAsShapes(){ return " + textAsShapesAttr.equalsIgnoreCase("true") + "; }\n\n"); ow.write(testFinish); ow.flush(); ow.close(); // Compile test now String command = "javac -classpath "; command += System.getProperty("java.class.path") + CLASSPATH_SEPARATOR + tmpSourceFile.getParent(); command += " -d " + classDir + " " + tmpSourceFile.getAbsolutePath(); // display(command); display("compiling test..."); final Process process = Runtime.getRuntime().exec(command); // In a separate thread, read the compilation output final StringWriter compileOutput = new StringWriter(); Thread traceProcessTh = new Thread(){ public void run(){ InputStream pis = process.getErrorStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(pis)); try{ String line = null; while((line = reader.readLine()) != null){ compileOutput.write(testOutName); compileOutput.write(" : "); compileOutput.write(line); compileOutput.write(EOL); } /* The following will generate a file for compilation output compileOutput.write(testOutName + " compilation finished" + EOL); File f = new File(REGSVGGEN_DIRECTORY_NAME); File compileout = new File(f,"compile"); PrintWriter writer = new PrintWriter(new FileWriter(compileout)); writer.print(compileOutput.toString()); writer.close(); */ }catch(IOException ioe){ compileOutput.write(testOutName + " compilation finished" + EOL); } } }; traceProcessTh.start(); process.waitFor(); // Clean up source file tmpSourceFile.delete(); // Return back the qualified class name String qualifiedClassName = TEST_PACKAGE + "." + className; return qualifiedClassName; } /** * This method will generate PNG file directly * from the BufferedImage, the image files will * be stored in the "new" directory */ public static void createBufImage(String className, String testImageName) throws Exception{ Class cl = Class.forName(className); display("Loading compiled test..."); Painter painter = null; try{ painter = (Painter)cl.newInstance(); }catch(Exception e){ exit(1); } // Begin encoding to PNG image file ImageTranscoder transcoder = getTranscoder(); Dimension size = painter.getSize(); BufferedImage buf = transcoder.createImage(size.width, size.height); Graphics2D g = GraphicsUtil.createGraphics(buf); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON); Shape clip = new Rectangle(0, 0, 300, 400); clip = new GeneralPath(clip); g.setClip(clip); painter.paint(g); g.dispose(); try{ transcoder.writeImage(buf, new TranscoderOutput(new FileOutputStream(testImageName))); } catch(Exception e){ } } /** * This method will generate SVG files using the * SVGGraphics2D, SVG files will be in "svg" directory */ public static void createSvgFile(String className, String testImageName) throws Exception{ Class cl = Class.forName(className); display("Loading compiled test to convert to SVG ..."); Painter painter = null; try{ painter = (Painter)cl.newInstance(); }catch(Exception e){ exit(1); } // First, create an instance of org.w3c.dom.Document CSSDocumentHandler.setParserClassName(CSS_PARSER_CLASS_NAME); DOMImplementation impl = SVGDOMImplementation.getDOMImplementation(); String namespaceURI = SVGDOMImplementation.SVG_NAMESPACE_URI; Document domFactory = impl.createDocument(namespaceURI, "svg", null); // Second, create an instance of the generator and paint to it ExtensionHandler extensionHandler = new DefaultExtensionHandler(); SVGGraphics2D svggen = new SVGGraphics2D(domFactory); Dimension size = painter.getSize(); svggen.setSVGCanvasSize(size); painter.paint(svggen); // Third, find out whether to use XML attributes or CSS properties // and write the SVG content to the output file boolean useCss = false; svggen.stream(testImageName, useCss); } /** * This method will generate PNG files from corresponding * SVG files under "svg" directory, the image files will * be in "ref" directory */ public static void generateRefImages() { File f = new File(REGSVGGEN_DIRECTORY_NAME); if (!f.exists()) { error("regsvggen is not initialized. use -init first"); } File ff = new File(f, REGSVGGEN_REF_DIRECTORY_NAME); if (ff.list().length != 0) { error("The reference directory "+ff.getAbsolutePath()+ " is not empty. Use -reset first."); exit(3); } generateImages(getRefDirectory(), "images from SVG files"); } static void generateImages(String outputDirectory, String desc) { File destDir = new File(outputDirectory); File svgDir = new File(getSvgDirectory()); ImageTranscoder transcoder = getTranscoder(); File [] samples = svgDir.listFiles(); if (samples == null) { error("No SVG files has been found in "+ svgDir.getAbsolutePath()); exit(2); } for (int i=0; i < samples.length; ++i) { File src = samples[i]; if (!src.getName().endsWith(".svg")){continue;} File dest = new File(destDir, getImageName(src.getName())); display("Generating "+desc+" "+src.getName()); try { writeImage(transcoder, src.toURL().toString(), dest.getAbsolutePath()); } catch (MalformedURLException ex) { error("Bad URL for "+src.getAbsolutePath()+" or "+ dest.getAbsolutePath()); } catch(Exception e){ e.printStackTrace(); } } } public static void diffImage() { File f = new File(REGSVGGEN_DIRECTORY_NAME); if (!f.exists()) { error("regsvggen is not initialized. use -init first"); } File refDir = new File(getRefDirectory()); File newDir = new File(getNewDirectory()); File [] refImages = refDir.listFiles(); int [] badIndex = new int [refImages.length]; int badFiles = 0; for (int i=0; i < refImages.length; ++i) { File refImg = refImages[i]; File newImg = new File(newDir, refImg.getName()); boolean ok = diffImage(refImg.getAbsolutePath(), newImg.getAbsolutePath()); if (ok) { display("Diff: "+refImg.getName()+" ok"); } else { badIndex[badFiles] = i; display("Diff: "+refImg.getName()+" has regression"); badFiles++; } } display("Total: "+badFiles+"/"+refImages.length+" corrupted"); // When there's regression, we'll produce the diff directory and // diff image files if(badFiles>0) { generateReport(refImages, badIndex, badFiles); } else{ generateReport(); } } public static void generateReport(){ String time = computeTimeStamp(); String reportFileName = REGSVGGEN_REPORT_FILE_NAME + "_" + time + "." + REGSVGGEN_REPORT_FILE_EXT; File f = new File(REGSVGGEN_DIRECTORY_NAME); File reportFile = new File(f, reportFileName); display("Creating report... " + reportFileName); try { PrintWriter writer = new PrintWriter(new FileWriter(reportFile)); String content = new String(); content += REGSVGGEN_REPORT_HEAD_STRING; content += REGSVGGEN_REPORT_NO_REGRESSION_STRING; content += "<p>Reported On:"; content += time; content += REGSVGGEN_REPORT_END_STRING; writer.print(content); writer.close(); display("Report finished"); } catch(IOException e){ } } public static void generateReport(File [] refImages, int [] badIndex, int bi){ // create report file and the difference directory File f = new File(REGSVGGEN_DIRECTORY_NAME); String time = computeTimeStamp(); String reportFileName = REGSVGGEN_REPORT_FILE_NAME + "_" + time + "." + REGSVGGEN_REPORT_FILE_EXT; File reportFile = new File(f, reportFileName); File diffDir = new File(f, REGSVGGEN_DIFF_DIRECTORY_NAME); diffDir.mkdir(); display("Creating "+diffDir.getAbsolutePath()); // get the new directory reference File newDir = new File(getNewDirectory()); // begin to prepare the report and difference image files display("Creating report..."); String content = new String(); content += REGSVGGEN_REPORT_HEAD_STRING; content += "<p>There're "; content += String.valueOf(bi); content += " file(s) that has/have regression:<p>"; for(int i=0; i<bi; i++){ File refImg = refImages[badIndex[i]]; File newImg = new File(newDir, refImg.getName()); File diffImg = new File(diffDir, refImg.getName()); BufferedImage bfRef = ImageLoader.loadImage(refImg, BufferedImage.TYPE_INT_ARGB); BufferedImage bfNew = null; if(newImg != null){ bfNew = ImageLoader.loadImage(newImg, BufferedImage.TYPE_INT_ARGB); } if (bfNew == null || bfRef == null || (bfRef.getWidth() != bfNew.getWidth()) || (bfRef.getHeight() != bfNew.getHeight())){ display("Error: image size changed!"); String s = "<br>" + String.valueOf(i+1) + ". " + refImg.getName() + ": image size changed!"; content += s; continue; } ImageTranscoder transcoder = getTranscoder(); BufferedImage bfDiff = transcoder.createImage(3*bfRef.getWidth(), bfRef.getHeight()); diffBufferedImage(bfRef.getRaster(), bfNew.getRaster(), bfDiff.getRaster()); try{ transcoder.writeImage(bfDiff, new TranscoderOutput(new FileOutputStream(diffImg))); } catch(Exception e){ } display(String.valueOf(i+1) + ". " + "Creating the difference image file of " + refImg.getName()); try{ String s = diffImg.toURL().toString(); content += "<br>" + String.valueOf(i+1) + ". " + "<a href=" + "\"" + s + "\"" +">" + "<img src=" + "\"" + s + "\"" + " height=40 width=90" + " />" + "</a>"; } catch(MalformedURLException e){ } } content += "<p>Reported On: "; content += time; content += REGSVGGEN_REPORT_END_STRING; try{ PrintWriter writer = new PrintWriter(new FileWriter(reportFile)); writer.print(content); writer.close(); } catch (IOException e){} display("Report finished"); } public static void reset(){ File dir = new File(getSvgDirectory()); File [] images = dir.listFiles(); for (int i=0; i < images.length; ++i) { display("Deleting svg files "+images[i].getName()); images[i].delete(); } dir = new File(getDiffDirectory()); images = dir.listFiles(); for (int i=0; i < images.length; ++i) { display("Deleting diff files "+images[i].getName()); images[i].delete(); } dir = new File(getRefDirectory()); images = dir.listFiles(); if(images != null){ for (int i=0; i < images.length; ++i) { display("Deleting diff files "+images[i].getName()); images[i].delete(); } } } public static void cleanUp(){ File dir = new File(getRefDirectory()); File [] images = dir.listFiles(); for (int i=0; i < images.length; ++i) { //display("Deleting svg image files "+images[i].getName()); images[i].delete(); } dir.delete(); /*dir = new File(getNewDirectory()); images = dir.listFiles(); for (int i=0; i < images.length; ++i) { //display("Deleting bufferedimage files "+images[i].getName()); images[i].delete(); } dir.delete();*/ dir = new File(getClassesDirectory()); images = dir.listFiles(); for (int i=0; i < images.length; ++i) { images[i].delete(); } dir.delete(); exit(0); } // Convenient methods static String getImageName(String uri) { if (uri.endsWith(".svg")) { uri = uri.substring(0, uri.lastIndexOf(".svg")); uri += ".png"; } else if (uri.endsWith(".xml")) { uri = uri.substring(0, uri.lastIndexOf(".xml")); uri += ".png"; } return uri; } /** * Writes an image. * @param transcoder the transcoder to use to generate the image * @param inputURI the URI of the SVG file * @param outputURI the URI of the image to generate */ public static void writeImage(ImageTranscoder transcoder, String inputURI, String output) { try { OutputStream ostream = new BufferedOutputStream(new FileOutputStream(output)); transcoder.transcode(new TranscoderInput(inputURI), new TranscoderOutput(ostream)); ostream.flush(); ostream.close(); } catch(IOException ex) { error("while writing "+inputURI+" to "+output+"\n"+ex.getMessage()); } catch(Exception ex) { error("while writing "+inputURI+" to "+output+"\n"+ex.getMessage()); } } /** * Returns true if the specified images are the same, false otherwise. * @param refInputURI the reference image * @param newInputURI the new produced image */ public static boolean diffImage(String refInputURI, String newInputURI) { try { InputStream refStream = new BufferedInputStream(new FileInputStream(refInputURI)); InputStream newStream = new BufferedInputStream(new FileInputStream(newInputURI)); int b, nb; do { b = refStream.read(); nb = newStream.read(); } while (b != -1 && nb != -1 && b == nb); refStream.close(); newStream.close(); return (b == nb); } catch(IOException ex) { System.out.println("Error while diffing "+refInputURI+ " and "+newInputURI); return false; } } /** * This is the core method to calculate the difference of the two * input images and save the comparison into the output image * @param ref the reference image in BufferedImage * @param new the new image in BufferedImage * @param diff the difference image in BufferedImage */ public static void diffBufferedImage(Raster ref, Raster cmp, Raster diff){ final int w = ref.getWidth(); final int h = ref.getHeight(); // Access the integer buffer for each image. DataBufferInt refDB = (DataBufferInt)ref.getDataBuffer(); DataBufferInt cmpDB = (DataBufferInt)cmp.getDataBuffer(); DataBufferInt diffDB = (DataBufferInt)diff.getDataBuffer(); // Offset defines where in the stack the real data begin final int refOff = refDB.getOffset(); final int cmpOff = cmpDB.getOffset(); final int diffOff = diffDB.getOffset(); // Stride is the distance between two consecutive column elements, // in the one-dimention dataBuffer final int refScanStride = ((SinglePixelPackedSampleModel) ref.getSampleModel()).getScanlineStride(); final int cmpScanStride = ((SinglePixelPackedSampleModel) cmp.getSampleModel()).getScanlineStride(); final int diffScanStride = ((SinglePixelPackedSampleModel) diff.getSampleModel()).getScanlineStride(); // Access the pixel value array final int refPixels[] = refDB.getBankData()[0]; final int cmpPixels[] = cmpDB.getBankData()[0]; final int diffPixels[] = diffDB.getBankData()[0]; // source pointers pointing to pixels in Ref and Cmp int rp, np; // destination pointers pointing to three areas in the Diff int dp0, dp1, dp2; // pixel values int refPixel; int cmpPixel; int diffPixel; for (int i=0; i<h; i++){ rp = refOff + i*refScanStride; np = cmpOff + i*cmpScanStride; dp0 = diffOff + i*diffScanStride; dp1 = diffOff + i*diffScanStride + w; dp2 = diffOff + i*diffScanStride + 2*w; for (int j=0; j<w; j++){ refPixel = refPixels[rp]; cmpPixel = cmpPixels[np]; diffPixel = cmpPixel - refPixel; diffPixels[dp0] = refPixel; diffPixels[dp1] = cmpPixel; if(diffPixel != 0){ diffPixel = 0xff000000; } diffPixels[dp2] = diffPixel; rp++; np++; dp0++; dp1++; dp2++; } } } public static String computeTimeStamp(){ String time = ""; Calendar rightNow = Calendar.getInstance(); time += String.valueOf(rightNow.get(Calendar.HOUR)); time += "_"; time += String.valueOf(rightNow.get(Calendar.MINUTE)); time += "_"; time += String.valueOf(rightNow.get(Calendar.MONTH)); time += "_"; time += String.valueOf(rightNow.get(Calendar.DATE)); time += "_"; time += String.valueOf(rightNow.get(Calendar.YEAR)); return time; } /** * Returns the transcoder to use. */ public static ImageTranscoder getTranscoder() { ImageTranscoder t = new PNGTranscoder(); t.addTranscodingHint(PNGTranscoder.KEY_XML_PARSER_CLASSNAME, "org.apache.crimson.parser.XMLReaderImpl"); return t; } /** * Display the specified error message. * @param msg the error message to display */ public static void error(String msg) { System.err.println("ERROR: "+msg); } /** * Display the specified message. * @param msg the message to display */ public static void display(String msg) { System.out.println(msg); } /** * Shows the usage message. * @param out the stream where to write the usage message */ public static void usage(PrintStream out) { out.println("usage: regsvggen [-help|-init|-reset|-go]"); out.println("-help Display this message"); out.println("-init Initialize regsvggen"); out.println("-reset Remove the reference and new images"); out.println("-go Process the test cases and produce report"); } /** * Exits the application with the specified code. * @param code the exit code */ public static void exit(int code) { System.exit(code); } /** * Returns the directory where the XML test cases are stored. */ public static String getXmlDirectory() { File f = new File(REGSVGGEN_DIRECTORY_NAME); return new File(f, REGSVGGEN_XML_DIRECTORY_NAME).getAbsolutePath(); } /** * Returns the directory where the reference images are stored. */ public static String getRefDirectory() { File f = new File(REGSVGGEN_DIRECTORY_NAME); return new File(f, REGSVGGEN_REF_DIRECTORY_NAME).getAbsolutePath(); } /** * Returns the directory where the new images are stored. */ public static String getNewDirectory() { File f = new File(REGSVGGEN_DIRECTORY_NAME); return new File(f, REGSVGGEN_NEW_DIRECTORY_NAME).getAbsolutePath(); } /** * Returns the directory where temporary classes are stored. */ public static String getClassesDirectory() { File f = new File(REGSVGGEN_DIRECTORY_NAME); return new File(f, REGSVGGEN_CLASSES_DIRECTORY_NAME).getAbsolutePath(); } /** * Returns the directory where the difference images are stored. */ public static String getDiffDirectory() { File f = new File(REGSVGGEN_DIRECTORY_NAME); return new File(f, REGSVGGEN_DIFF_DIRECTORY_NAME).getAbsolutePath(); } /** * Returns the directory where the svg files are stored. */ public static String getSvgDirectory() { File f = new File(REGSVGGEN_DIRECTORY_NAME); return new File(f, REGSVGGEN_SVG_DIRECTORY_NAME).getAbsolutePath(); } }
package org.yamcs.parameterarchive; import java.lang.reflect.Array; import java.nio.BufferOverflowException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import me.lemire.integercompression.FastPFOR128; import me.lemire.integercompression.IntWrapper; import org.yamcs.utils.DecodingException; import org.yamcs.utils.IntArray; import org.yamcs.utils.VarIntUtil; /** * Segment for all non primitive types. * * Each element is encoded to a binary that is not compressed. The compression of the segment (if any) is realized by not repeating elements. * * Finds best encoding among: * - raw - list of values stored verbatim, each preceded by its size varint32 encoded * - enum - the list of unique values are stored at the beginning of the segment - each value has an implicit id (the order in the list) * - the rest of the segment is the list of ids and can be encoded in one of the following formats * - VB: varint32 of each id * - FPROF: coded with the FPROF codec + varint32 of remaining * - RLE: run length encoded * * * @author nm * */ public class ObjectSegment<E> extends BaseSegment { final static byte SUBFORMAT_ID_RAW = 0; final static byte SUBFORMAT_ID_ENUM_RLE = 1; final static byte SUBFORMAT_ID_ENUM_VB = 2; final static byte SUBFORMAT_ID_ENUM_FPROF = 3; //this is set only during deserialisation. boolean runLengthEncoded = false; //one of the lists below is used depending whether runLengthEncoded is true or false List<E> objectList; List<E> rleObjectList; IntArray rleCounts; int size = 0; final ObjectSerializer<E> objSerializer; //temporary fields used during the construction before serialisation - could be probably refactored into some builder which returns another object in the consolidate method List<HashableByteArray> serializedObjectList; Map<HashableByteArray, Integer> valuemap; IntArray rleValues; IntArray enumValues; List<HashableByteArray> unique; int rawSize; int enumRawSize; int enumRleSize; boolean consolidated = false; /** * b * @param objSerializer * @param buildForSerialisation - is set to true at the construction and false at deserialisation */ ObjectSegment(ObjectSerializer<E> objSerializer, boolean buildForSerialisation) { super(objSerializer.getFormatId()); this.objSerializer = objSerializer; if(buildForSerialisation) { objectList = new ArrayList<E>(); serializedObjectList = new ArrayList<HashableByteArray>(); unique = new ArrayList<HashableByteArray>(); valuemap = new HashMap<>(); enumValues = new IntArray(); } //else in the parseFrom will construct the necessary fields } /** * add element to the end of the segment * * @param e */ public void add(E e) { byte[] b = objSerializer.serialize(e); HashableByteArray se = new HashableByteArray(b); int valueId; if(valuemap.containsKey(se)) { valueId = valuemap.get(se); se = unique.get(valueId); //release the old se object to garbage } else { valueId = unique.size(); valuemap.put(se, valueId); unique.add(se); } enumValues.add(valueId); serializedObjectList.add(se); objectList.add(e); size++; } public void add(int pos, E e) { if(pos==size) { add(e); return; } byte[] b = objSerializer.serialize(e); HashableByteArray se = new HashableByteArray(b); int valueId; if(valuemap.containsKey(se)) { valueId = valuemap.get(se); se = unique.get(valueId); //release the old se object to garbage } else { valueId = unique.size(); valuemap.put(se, valueId); unique.add(se); } enumValues.add(pos, valueId); serializedObjectList.add(pos, se); objectList.add(pos, e); size++; } @Override public void writeTo(ByteBuffer bb) { if(!consolidated) { throw new IllegalStateException("The segment has to be consolidated before serialization can take place"); } boolean encoded = false; int position = bb.position(); try { //first try to encode them as Rle or EnuFprof if(enumRleSize<=enumRawSize && enumRleSize<=rawSize) { encoded = writeEnumRle(bb); } else if(enumRawSize<enumRleSize && enumRawSize<=rawSize) { encoded = writeEnumFprof(bb); } } catch (IndexOutOfBoundsException|BufferOverflowException e) { encoded = false; } //if the resulted size is bigger than raw encoding, then encode it raw if(!encoded) { bb.position(position); writeRaw(bb); } } public void writeRaw(ByteBuffer bb) { bb.put(SUBFORMAT_ID_RAW); //write the size VarIntUtil.writeVarInt32(bb, objectList.size()); //then write the values for(int i=0; i<size; i++) { byte[] b = serializedObjectList.get(i).b; VarIntUtil.writeVarInt32(bb, b.length); bb.put(b); } } boolean writeEnumFprof(ByteBuffer bb) { int position = bb.position(); bb.put(SUBFORMAT_ID_ENUM_FPROF); //first write the enum values VarIntUtil.writeVarInt32(bb, unique.size()); for(int i=0; i<unique.size(); i++) { byte[] b = unique.get(i).b; VarIntUtil.writeVarInt32(bb, b.length); bb.put(b); } //then writes the enum ids VarIntUtil.writeVarInt32(bb, size); FastPFOR128 fastpfor = FastPFORFactory.get(); IntWrapper inputoffset = new IntWrapper(0); IntWrapper outputoffset = new IntWrapper(0); int[] out = new int[size]; int[] in = enumValues.array(); fastpfor.compress(in, inputoffset, size, out, outputoffset); if (outputoffset.get() == 0) { //fastpfor didn't compress anything, probably there were too few datapoints bb.put(position, SUBFORMAT_ID_ENUM_VB); } else { //write the fastpfor output for(int i=0; i<outputoffset.get(); i++) { bb.putInt(out[i]); } } //write the remaining bytes varint compressed for(int i = inputoffset.get(); i<size; i++) { VarIntUtil.writeVarInt32(bb, in[i]); } return true; } boolean writeEnumRle(ByteBuffer bb) { bb.put(SUBFORMAT_ID_ENUM_RLE); //first write the enum values VarIntUtil.writeVarInt32(bb, unique.size()); for(int i=0; i<unique.size(); i++) { byte[] b = unique.get(i).b; VarIntUtil.writeVarInt32(bb, b.length); bb.put(b); } //then write the rleCounts VarIntUtil.writeVarInt32(bb, rleCounts.size()); for(int i=0; i< rleCounts.size(); i++) { VarIntUtil.writeVarInt32(bb, rleCounts.get(i)); } //and write the rleValues for(int i=0; i< rleCounts.size(); i++) { VarIntUtil.writeVarInt32(bb, rleValues.get(i)); } return true; } protected void parse(ByteBuffer bb) throws DecodingException { byte formatId = bb.get(); try { switch(formatId) { case SUBFORMAT_ID_RAW: parseRaw(bb); break; case SUBFORMAT_ID_ENUM_VB: //intentional fall trough case SUBFORMAT_ID_ENUM_FPROF://intentional fall trough case SUBFORMAT_ID_ENUM_RLE: parseEnum(formatId, bb); break; default: throw new DecodingException("Unknown subformatid: "+formatId); } } catch (DecodingException e) { throw e; } catch (Exception e) { throw new DecodingException("Cannot decode object segment subformatId "+formatId, e); } } private void parseRaw(ByteBuffer bb) throws DecodingException { size = VarIntUtil.readVarInt32(bb); objectList = new ArrayList<E>(size); for(int i = 0; i<size; i++) { int l = VarIntUtil.readVarInt32(bb); byte[] b = new byte[l]; bb.get(b); E e = objSerializer.deserialize(b); objectList.add(e); } } void parseEnum(int formatId, ByteBuffer bb) throws DecodingException { int n = VarIntUtil.readVarInt32(bb); List<E> uniqueValues = new ArrayList<E>(); for(int i = 0;i<n; i++) { int l = VarIntUtil.readVarInt32(bb); byte[] b = new byte[l]; bb.get(b); E e = objSerializer.deserialize(b); uniqueValues.add(e); } if(formatId == SUBFORMAT_ID_ENUM_RLE) { parseEnumRle(uniqueValues, bb); } else { parseEnumNonRle(formatId, uniqueValues, bb); } } private void parseEnumNonRle(int formatId, List<E> uniqueValues, ByteBuffer bb) throws DecodingException { size = VarIntUtil.readVarInt32(bb); int position = bb.position(); int[] enumValues = new int[size]; IntWrapper outputoffset = new IntWrapper(0); if(formatId==SUBFORMAT_ID_ENUM_FPROF) { int[] x = new int[(bb.limit()-position)/4]; for(int i=0; i<x.length;i++) { x[i] = bb.getInt(); } IntWrapper inputoffset = new IntWrapper(0); FastPFOR128 fastpfor = FastPFORFactory.get(); fastpfor.uncompress(x, inputoffset, x.length, enumValues, outputoffset); bb.position(position+inputoffset.get()*4); } for(int i = outputoffset.get(); i<size;i++) { enumValues[i] = VarIntUtil.readVarInt32(bb); } objectList = new ArrayList<E>(size); for(int i =0 ; i<size; i++) { objectList.add(uniqueValues.get(enumValues[i])); } } private void parseEnumRle(List<E> uniqueValues, ByteBuffer bb ) throws DecodingException{ int countNum = VarIntUtil.readVarInt32(bb); rleCounts = new IntArray(countNum); size = 0; for(int i=0; i<countNum; i++) { int c = VarIntUtil.readVarInt32(bb); rleCounts.add(c); size+=c; } rleObjectList = new ArrayList<>(countNum); for(int i=0; i<countNum; i++) { int c = VarIntUtil.readVarInt32(bb); rleObjectList.add(uniqueValues.get(c)); } runLengthEncoded = true; } @Override public int getMaxSerializedSize() { return rawSize; } @Override public E[] getRange(int posStart, int posStop, boolean ascending) { if(posStart>=posStop) throw new IllegalArgumentException("posStart has to be smaller than posStop"); if(runLengthEncoded) { if(ascending) { return getRleRangeAscending(posStart, posStop); } else { return getRleRangeDescending(posStart, posStop); } } else { return getNonRleRange(posStart, posStop, ascending); } } E[] getNonRleRange(int posStart, int posStop, boolean ascending) { @SuppressWarnings("unchecked") E[] r = (E[]) Array.newInstance(objectList.get(0).getClass(), posStop-posStart); if(ascending) { for(int i = posStart; i<posStop; i++) { r[i-posStart] = objectList.get(i); } } else { for(int i = posStop; i>posStart; i r[posStop-i] = objectList.get(i); } } return r; } E[] getRleRangeAscending(int posStart, int posStop) { int n = posStop-posStart; @SuppressWarnings("unchecked") E[] r = (E[]) Array.newInstance(rleObjectList.get(0).getClass(), n); int k = posStart; int i = 0; while(k>=rleCounts.get(i)) { k-=rleCounts.get(i++); } int pos = 0; while(pos<n) { r[pos++] = rleObjectList.get(i); k++; if(k>=rleCounts.get(i)) { i++; k=0; } } return r; } public E[] getRleRangeDescending(int posStart, int posStop) { if(posStop>=size) throw new IndexOutOfBoundsException("Index: "+posStop+" size: "+size); int n = posStop-posStart; @SuppressWarnings("unchecked") E[] r = (E[]) Array.newInstance(rleObjectList.get(0).getClass(), n); int k = size - posStop; int i = rleCounts.size()-1; while(k > rleCounts.get(i)) { k-=rleCounts.get(i } k=rleCounts.get(i)-k; int pos = 0; while(true) { r[pos++] = rleObjectList.get(i); if(pos==n) break; k if(k<0) { i k = rleCounts.get(i)-1; } } return r; } public E get(int index) { if(runLengthEncoded) { int k = 0; int i = 0; while(k<=index) { k += rleCounts.get(i); i++; } return rleObjectList.get(i-1); } else { return objectList.get(index); } } /** * the number of elements in this segment (not taking into account any compression due to run-length encoding) * @return */ @Override public int size() { return size; } ObjectSegment<E> consolidate() { rleCounts = new IntArray(); rleValues = new IntArray(); rawSize = enumRawSize = enumRleSize = 1; //subFormatId byte rawSize += VarIntUtil.getEncodedSize(size); enumRawSize += VarIntUtil.getEncodedSize(size)+VarIntUtil.getEncodedSize(unique.size()); enumRleSize += VarIntUtil.getEncodedSize(unique.size()); for(int i=0; i<size; i++) { HashableByteArray se = serializedObjectList.get(i); byte[] b = se.b; int valueId = enumValues.get(i); rawSize+= VarIntUtil.getEncodedSize(b.length)+b.length; enumRawSize+=VarIntUtil.getEncodedSize(valueId); boolean rleAdded = false; int rleId = rleValues.size()-1; if(rleId>=0) { int lastValueId = rleValues.get(rleId); if(valueId == lastValueId) { rleCounts.set(rleId, rleCounts.get(rleId)+1); rleAdded = true; } } if(!rleAdded) { rleCounts.add(1); rleValues.add(valueId); } } for(int i = 0; i<unique.size(); i++) { HashableByteArray se = unique.get(i); byte[] b = se.b; int s = VarIntUtil.getEncodedSize(b.length)+b.length; enumRawSize+=s; enumRleSize+=s; } enumRleSize += VarIntUtil.getEncodedSize(rleCounts.size()); for(int i =0 ;i<rleCounts.size();i++) { enumRleSize += VarIntUtil.getEncodedSize(rleCounts.get(i))+VarIntUtil.getEncodedSize(rleValues.get(i)); } consolidated = true; return this; } @SuppressWarnings("rawtypes") @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ObjectSegment other = (ObjectSegment) obj; if (serializedObjectList == null) { if (other.serializedObjectList != null) return false; } else if (!serializedObjectList.equals(other.serializedObjectList)) return false; return true; } } /** * wrapper around byte[] to allow it to be used in HashMaps */ class HashableByteArray { private int hash =0 ; final byte[] b; public HashableByteArray(byte[] b) { this.b = b ; } @Override public int hashCode() { if (hash == 0) { hash = Arrays.hashCode(b); } return hash; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; HashableByteArray other = (HashableByteArray) obj; if(hashCode()!=other.hashCode()) return false; if (!Arrays.equals(b, other.b)) return false; return true; } } interface ObjectSerializer<E> { byte getFormatId(); E deserialize(byte[] b) throws DecodingException; byte[] serialize(E e); }
package org.zanata.rest.service; import java.util.List; import javax.ws.rs.core.Response.Status; import org.dbunit.operation.DatabaseOperation; import org.hamcrest.CoreMatchers; import org.jboss.resteasy.client.ClientResponse; import org.jboss.seam.security.Identity; import org.junit.Assert; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import org.zanata.ZanataRestTest; import org.zanata.common.LocaleId; import org.zanata.rest.client.IGlossaryResource; import org.zanata.rest.dto.Glossary; import org.zanata.rest.dto.GlossaryEntry; import org.zanata.rest.dto.GlossaryTerm; import org.zanata.seam.SeamAutowire; import org.zanata.security.ZanataIdentity; import org.zanata.service.impl.GlossaryFileServiceImpl; import org.zanata.service.impl.LocaleServiceImpl; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.verify; public class GlossaryRestTest extends ZanataRestTest { @Mock private ZanataIdentity mockIdentity; private IGlossaryResource glossaryService; private SeamAutowire seam = SeamAutowire.instance(); @BeforeClass void beforeClass() { Identity.setSecurityEnabled(false); } @BeforeMethod(dependsOnMethods = "prepareRestEasyFramework") public void createClient() { MockitoAnnotations.initMocks(this); this.glossaryService = getClientRequestFactory().createProxy(IGlossaryResource.class, createBaseURI("/glossary")); } @Override protected void prepareDBUnitOperations() { beforeTestOperations.add(new DataSetOperation("org/zanata/test/model/LocalesData.dbunit.xml", DatabaseOperation.CLEAN_INSERT)); beforeTestOperations.add(new DataSetOperation("org/zanata/test/model/GlossaryData.dbunit.xml", DatabaseOperation.CLEAN_INSERT)); beforeTestOperations.add(new DataSetOperation("org/zanata/test/model/AccountData.dbunit.xml", DatabaseOperation.CLEAN_INSERT)); } @Override protected void prepareResources() { seam.reset(); // @formatter:off seam.ignoreNonResolvable() .use("session", getSession()) .use("identity", mockIdentity) .useImpl(LocaleServiceImpl.class) .useImpl(GlossaryFileServiceImpl.class); // @formatter:on GlossaryService glossaryService = seam.autowire(GlossaryService.class); resources.add(glossaryService); } @Test public void retrieveAllGlossaryTerm() { ClientResponse<Glossary> response = glossaryService.getEntries(); assertThat(response.getStatus(), is(200)); List<GlossaryEntry> glossaryEntries = response.getEntity().getGlossaryEntries(); assertThat(glossaryEntries.size(), is(1)); List<GlossaryTerm> glossaryTerms = glossaryEntries.get(0).getGlossaryTerms(); assertThat(glossaryTerms.size(), is(3)); } @Test public void retrieveGlossaryTermWithLocale() { ClientResponse<Glossary> response = glossaryService.get(LocaleId.EN_US); assertThat(response.getStatus(), is(200)); List<GlossaryEntry> glossaryEntries = response.getEntity().getGlossaryEntries(); assertThat(glossaryEntries.size(), is(1)); List<GlossaryTerm> glossaryTerms = glossaryEntries.get(0).getGlossaryTerms(); assertThat(glossaryTerms.size(), is(1)); Assert.assertNotNull(glossaryEntries.get(0).getSrcLang()); assertThat(glossaryEntries.get(0).getSrcLang(), is(LocaleId.EN_US)); } @Test public void retrieveNonExistingGlossaryTermLocale() { ClientResponse<Glossary> response = glossaryService.get(LocaleId.FR); List<GlossaryEntry> glossaryEntries = response.getEntity().getGlossaryEntries(); assertThat(glossaryEntries.size(), is(0)); } @Test public void putGlossary() { Glossary glossary = new Glossary(); GlossaryEntry glossaryEntry1 = new GlossaryEntry(); glossaryEntry1.setSrcLang(LocaleId.EN_US); glossaryEntry1.setSourcereference("TEST SOURCE REF DATA"); GlossaryTerm glossaryTerm1 = new GlossaryTerm(); glossaryTerm1.setLocale(LocaleId.EN_US); glossaryTerm1.setContent("TEST DATA 1 EN_US"); glossaryTerm1.getComments().add("COMMENT 1"); GlossaryTerm glossaryTerm2 = new GlossaryTerm(); glossaryTerm2.setLocale(LocaleId.DE); glossaryTerm2.setContent("TEST DATA 2 DE"); glossaryTerm2.getComments().add("COMMENT 2"); glossaryEntry1.getGlossaryTerms().add(glossaryTerm1); glossaryEntry1.getGlossaryTerms().add(glossaryTerm2); GlossaryEntry glossaryEntry2 = new GlossaryEntry(); glossaryEntry2.setSrcLang(LocaleId.EN_US); glossaryEntry2.setSourcereference("TEST SOURCE REF DATA2"); GlossaryTerm glossaryTerm3 = new GlossaryTerm(); glossaryTerm3.setLocale(LocaleId.EN_US); glossaryTerm3.setContent("TEST DATA 3 EN_US"); glossaryTerm3.getComments().add("COMMENT 3"); GlossaryTerm glossaryTerm4 = new GlossaryTerm(); glossaryTerm4.setLocale(LocaleId.DE); glossaryTerm4.setContent("TEST DATA 4 DE"); glossaryTerm4.getComments().add("COMMENT 4"); glossaryEntry2.getGlossaryTerms().add(glossaryTerm3); glossaryEntry2.getGlossaryTerms().add(glossaryTerm4); glossary.getGlossaryEntries().add(glossaryEntry1); glossary.getGlossaryEntries().add(glossaryEntry2); ClientResponse<String> response = glossaryService.put(glossary); assertThat(response.getStatus(), is(Status.CREATED.getStatusCode())); // TODO SeamAutowire needs to handle @Restrict. See org.jboss.seam.security.SecurityInterceptor.Restriction.check(Object[]) } @Test public void deleteAllGlossaries() { ClientResponse<String> response = glossaryService.deleteGlossaries(); assertThat(response.getStatus(), is(200)); ClientResponse<Glossary> response1 = glossaryService.getEntries(); List<GlossaryEntry> glossaryEntries = response1.getEntity().getGlossaryEntries(); assertThat(glossaryEntries.size(), is(0)); // TODO SeamAutowire needs to handle @Restrict. See org.jboss.seam.security.SecurityInterceptor.Restriction.check(Object[]) } @Test public void deleteGlossaryTermWithLocale() { ClientResponse<String> response = glossaryService.deleteGlossary(LocaleId.ES); assertThat(response.getStatus(), is(200)); ClientResponse<Glossary> response1 = glossaryService.getEntries(); List<GlossaryEntry> glossaryEntries = response1.getEntity().getGlossaryEntries(); assertThat(glossaryEntries.get(0).getGlossaryTerms().size(), is(2)); // TODO SeamAutowire needs to handle @Restrict. See org.jboss.seam.security.SecurityInterceptor.Restriction.check(Object[]) } @Test public void testPutGlossaries() { Glossary glossary = new Glossary(); GlossaryEntry glossaryEntry1 = new GlossaryEntry(); glossaryEntry1.setSrcLang(LocaleId.EN_US); glossaryEntry1.setSourcereference("TEST SOURCE REF DATA"); GlossaryTerm glossaryTerm1 = new GlossaryTerm(); glossaryTerm1.setLocale(LocaleId.EN_US); glossaryTerm1.setContent("test data content 1 (source lang)"); glossaryTerm1.getComments().add("COMMENT 1"); glossaryEntry1.getGlossaryTerms().add(glossaryTerm1); glossary.getGlossaryEntries().add(glossaryEntry1); ClientResponse<String> response = glossaryService.put(glossary); ClientResponse<Glossary> response1 = glossaryService.getEntries(); assertThat(response1.getEntity().getGlossaryEntries().size(), CoreMatchers.is(1)); // TODO SeamAutowire needs to handle @Restrict. See org.jboss.seam.security.SecurityInterceptor.Restriction.check(Object[]) } }
package org.usfirst.frc.team2339.Barracuda; import org.usfirst.frc.team2339.Barracuda.RobotMap.SwerveMap; //import com.sun.squawk.util.MathUtils; import java.lang.Math; import edu.wpi.first.wpilibj.DoubleSolenoid; import edu.wpi.first.wpilibj.Encoder; import edu.wpi.first.wpilibj.PIDController; import edu.wpi.first.wpilibj.PIDOutput; import edu.wpi.first.wpilibj.PIDSource; import edu.wpi.first.wpilibj.RobotDrive; import edu.wpi.first.wpilibj.SpeedController; import edu.wpi.first.wpilibj.Talon; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; public class SwerveDrive extends RobotDrive { //declare the steering pods and shifter valve public static final int frontLeft = MotorType.kFrontLeft.value; public static final int frontRight = MotorType.kFrontRight.value; public static final int rearLeft = MotorType.kRearLeft.value; public static final int rearRight = MotorType.kRearRight.value; protected SpeedController speedControllers[] = new SpeedController[kMaxNumberOfMotors]; protected Pod wheelPods[] = new Pod[kMaxNumberOfMotors]; private DoubleSolenoid shift; public class WheelData { public double wheelSpeeds[] = new double[kMaxNumberOfMotors]; public double wheelAngles[] = new double[kMaxNumberOfMotors]; public WheelData() { // Initialize data for (int iiWheel = 0; iiWheel < kMaxNumberOfMotors; iiWheel++) { wheelSpeeds[iiWheel] = 0; wheelAngles[iiWheel] = 0; } } /** * Set speed and angle values when joystick in dead band */ public void setDeadBandValues() { for (int iiWheel = 0; iiWheel < kMaxNumberOfMotors; iiWheel++) { wheelSpeeds[iiWheel] = 0; wheelAngles[iiWheel] = 45; } wheelAngles[frontRight] = -45; wheelAngles[rearLeft] = -45; } } public SwerveDrive() { super(SwerveMap.PWM.DRIVE_FRONT_LEFT, SwerveMap.PWM.DRIVE_REAR_LEFT, SwerveMap.PWM.DRIVE_FRONT_RIGHT, SwerveMap.PWM.DRIVE_REAR_RIGHT); speedControllers[frontLeft] = new Talon(SwerveMap.PWM.DRIVE_FRONT_LEFT_STEERING); speedControllers[frontRight] = new Talon(SwerveMap.PWM.DRIVE_FRONT_RIGHT_STEERING); speedControllers[rearLeft] = new Talon(SwerveMap.PWM.DRIVE_REAR_LEFT_STEERING); speedControllers[rearRight] = new Talon(SwerveMap.PWM.DRIVE_REAR_RIGHT_STEERING); //set up the steering pods with the correct sensors and controllers shift = new DoubleSolenoid(SwerveMap.Solenoid.DRIVE_SHIFT_HIGH, SwerveMap.Solenoid.DRIVE_SHIFT_LOW); wheelPods[frontLeft] = new Pod(m_frontLeftMotor, speedControllers[frontLeft], SwerveMap.DIO.DRIVE_FRONT_LEFT_ENC_A, SwerveMap.DIO.DRIVE_FRONT_LEFT_ENC_B, 1); wheelPods[frontRight] = new Pod(m_frontRightMotor, speedControllers[frontRight], SwerveMap.DIO.DRIVE_FRONT_RIGHT_ENC_A, SwerveMap.DIO.DRIVE_FRONT_RIGHT_ENC_B, 2); wheelPods[rearLeft] = new Pod(m_rearLeftMotor, speedControllers[rearLeft], SwerveMap.DIO.DRIVE_REAR_LEFT_ENC_A, SwerveMap.DIO.DRIVE_REAR_LEFT_ENC_B, 3); wheelPods[rearRight] = new Pod(m_rearRightMotor, speedControllers[rearRight], SwerveMap.DIO.DRIVE_REAR_RIGHT_ENC_A, SwerveMap.DIO.DRIVE_REAR_RIGHT_ENC_B, 4); } /** * Calculate raw speeds and angles for swerve drive. * Wheel speeds are normalized to the range [0, 1.0]. Angles are normalized to the range [-180, 180). * Calculated values are raw in that they have no consideration for current state of drive. * Most swerve code assumes the pivot point for rotation is the center of the wheels (i.e. center of rectangle with wheels as corners) * This calculation is generalized based on pivot being offset from rectangle center. * @param x strafe (sideways) speed between -1.0 and 1.0 * @param y forward speed between -1.0 and 1.0 * @param rotate rotation speed between -1.0 and 1.0 * @param xPivotOffset Amount pivot is offset sideways from center. (Positive toward right, negative toward left) * @param yPivotOffset Amount pivot is offset forward from center. (Positive toward front, negative toward back) * @return raw wheel speeds and angles */ public WheelData calculateRawWheelDataGeneral(double x, double y, double rotate, double xPivotOffset, double yPivotOffset) { WheelData rawWheelData = new WheelData(); double L = SwerveMap.Constants.WHEEL_BASE_LENGTH; double W = SwerveMap.Constants.WHEEL_BASE_WIDTH; double frontDist = L/2 - xPivotOffset; double rearDist = L/2 + xPivotOffset; double rightDist = W/2 - yPivotOffset; double leftDist = W/2 + yPivotOffset; double xDist = 0; double yDist = 0; double rWheel = 0; double xWheel = 0; double yWheel = 0; xDist = rightDist; yDist = frontDist; rWheel = Math.hypot(xDist, yDist); xWheel = x + rotate * yDist / rWheel; yWheel = y - rotate * xDist / rWheel; rawWheelData.wheelSpeeds[frontRight] = Math.hypot(xWheel, yWheel); rawWheelData.wheelAngles[frontRight] = Math.toDegrees(Math.atan2(xWheel, yWheel)); xDist = leftDist; yDist = frontDist; rWheel = Math.hypot(xDist, yDist); xWheel = x + rotate * yDist / rWheel; yWheel = y + rotate * xDist / rWheel; rawWheelData.wheelSpeeds[frontLeft] = Math.hypot(xWheel, yWheel); rawWheelData.wheelAngles[frontLeft] = Math.toDegrees(Math.atan2(xWheel, yWheel)); xDist = leftDist; yDist = rearDist; rWheel = Math.hypot(xDist, yDist); xWheel = x - rotate * yDist / rWheel; yWheel = y + rotate * xDist / rWheel; rawWheelData.wheelSpeeds[rearLeft] = Math.hypot(xWheel, yWheel); rawWheelData.wheelAngles[rearLeft] = Math.toDegrees(Math.atan2(xWheel, yWheel)); xDist = rightDist; yDist = rearDist; rWheel = Math.hypot(xDist, yDist); xWheel = x - rotate * yDist / rWheel; yWheel = y - rotate * xDist / rWheel; rawWheelData.wheelSpeeds[rearRight] = Math.hypot(xWheel, yWheel); rawWheelData.wheelAngles[rearRight] = Math.toDegrees(Math.atan2(xWheel, yWheel)); normalize(rawWheelData.wheelSpeeds); return rawWheelData; } /** * NOTE: This should give same result as standard method below. * Calculate raw speeds and angles for swerve drive. * Wheel speeds are normalized to the range [0, 1.0]. Angles are normalized to the range [-180, 180). * Calculated values are raw in that they have no consideration for current state of drive. * @param x strafe (sideways) speed between -1.0 and 1.0 * @param y forward speed between -1.0 and 1.0 * @param rotate rotation speed between -1.0 and 1.0 * @return raw wheel speeds and angles */ public WheelData calculateRawWheelData1(double x, double y, double rotate) { return calculateRawWheelDataGeneral(x, y, rotate, 0.0, 0.0); } /** * Calculate raw speeds and angles for swerve drive. * Wheel speeds are normalized to the range [0, 1.0]. Angles are normalized to the range [-180, 180). * Calculated values are raw in that they have no consideration for current state of drive. * @param x strafe (sideways) speed between -1.0 and 1.0 * @param y forward speed between -1.0 and 1.0 * @param rotate rotation speed between -1.0 and 1.0 * @return raw wheel speeds and angles */ public WheelData calculateRawWheelData(double x, double y, double rotate) { WheelData rawWheelData = new WheelData(); //calculate angle/speed setpoints using wheel dimensions from SwerveMap double L = SwerveMap.Constants.WHEEL_BASE_LENGTH; double W = SwerveMap.Constants.WHEEL_BASE_WIDTH;; double R = Math.hypot(L, W); double A = x - rotate * (L / R); double B = x + rotate * (L / R); double C = y - rotate * (W / R); double D = y + rotate * (W / R); // Find wheel speeds rawWheelData.wheelSpeeds[frontLeft] = Math.hypot(B, D); rawWheelData.wheelSpeeds[frontRight] = Math.hypot(B, C); rawWheelData.wheelSpeeds[rearLeft] = Math.hypot(A, D); rawWheelData.wheelSpeeds[rearRight] = Math.hypot(A, C); normalize(rawWheelData.wheelSpeeds); // Find steering angles rawWheelData.wheelAngles[frontLeft] = Math.toDegrees(Math.atan2(B, D)); rawWheelData.wheelAngles[frontRight] = Math.toDegrees(Math.atan2(B, C)); rawWheelData.wheelAngles[rearLeft] = Math.toDegrees(Math.atan2(A, D)); rawWheelData.wheelAngles[rearRight] = Math.toDegrees(Math.atan2(A, C)); return rawWheelData; } /** * Calculate wheel data change (delta) based on current data. * @param rawWheelData Raw wheel change data * @return wheel change data (delta) based on current wheel values */ public WheelData calculateDeltaWheelData(WheelData rawWheelData) { WheelData deltaWheelData = new WheelData(); for (int iiWheel = 0; iiWheel < kMaxNumberOfMotors; iiWheel++) { // Compute turn angle from encoder value (pidGet) and raw target value AngleFlip turnAngle = computeTurnAngle(wheelPods[iiWheel].pidGet(), rawWheelData.wheelAngles[iiWheel]); deltaWheelData.wheelAngles[iiWheel] = turnAngle.getAngle(); deltaWheelData.wheelSpeeds[iiWheel] = driveScale(turnAngle) * rawWheelData.wheelSpeeds[iiWheel]; } return deltaWheelData; } public void setPods(WheelData wheelData) { for (int iiWheel = 0; iiWheel < kMaxNumberOfMotors; iiWheel++) { wheelPods[iiWheel].setSteeringAngle(wheelData.wheelAngles[iiWheel]); wheelPods[iiWheel].setWheelSpeed(wheelData.wheelSpeeds[iiWheel]); } } /** * Drive in swerve mode with a given speed, rotation, and shift values. * Driving parameters are assumed to be relative to the current robot angle. * @param x strafe (sideways) speed between -1.0 and 1.0 * @param y forward speed between -1.0 and 1.0 * @param rotate rotation speed between -1.0 and 1.0 * @param isLowGear true if need to shift to low * @param isHighGear true if need to shift to high */ public void swerveDriveRobot(double x, double y, double rotate, boolean isLowGear, boolean isHighGear) { WheelData deltaWheelData = null; if (x > SwerveMap.Control.DRIVE_STICK_DEAD_BAND || y > SwerveMap.Control.DRIVE_STICK_DEAD_BAND || rotate > SwerveMap.Control.DRIVE_STICK_DEAD_BAND) { // Compute new values WheelData rawWheelData = calculateRawWheelData(x, y, rotate); deltaWheelData = calculateDeltaWheelData(rawWheelData); } else { // Joystick in dead band, set neutral values deltaWheelData = new WheelData(); deltaWheelData.setDeadBandValues(); } // Set shifter if(isLowGear){ shift.set(DoubleSolenoid.Value.kForward); } if(isHighGear){ shift.set(DoubleSolenoid.Value.kReverse); } // Set pods setPods(deltaWheelData); } /** * Drive in swerve mode with a given speed, rotation, and shift values. * Driving parameters are assumed to be absolute based on a fixed angle, e.g. the field. * @param robotAngle Angle (in degrees) of robot relative to fixed angle. This is probably taken from the gyro. * @param x strafe (sideways) speed between -1.0 and 1.0 * @param y forward speed between -1.0 and 1.0 * @param rotate rotation speed between -1.0 and 1.0 * @param isLowGear true if need to shift to low * @param isHighGear true if need to shift to high */ public void swerveDriveAbsolute(double robotAngle, double x, double y, double rotate, boolean isLowGear, boolean isHighGear) { double robotAngleRad = Math.toRadians(robotAngle); double xRobot = -x * Math.sin(robotAngleRad) + y * Math.cos(robotAngleRad); double yRobot = x * Math.cos(robotAngleRad) + y * Math.sin(robotAngleRad); this.swerveDriveRobot(xRobot, yRobot, rotate, isLowGear, isHighGear); } /** * Control robot relative to itself */ public void swerveDriveTeleop() { double x, y, rotate; boolean isLowGear, isHighGear; x = SwerveMap.Control.DRIVE_STICK.getRawAxis(SwerveMap.Control.DRIVE_AXIS_FORWARD_BACK); y = -SwerveMap.Control.DRIVE_STICK.getRawAxis(SwerveMap.Control.DRIVE_AXIS_SIDEWAYS); rotate = SwerveMap.Control.DRIVE_STICK.getRawAxis(SwerveMap.Control.DRIVE_AXIS_ROTATE); isLowGear = SwerveMap.Control.DRIVE_STICK.getRawButton(SwerveMap.Control.DRIVE_CONTROLLER_SHIFT_LOW); isHighGear = SwerveMap.Control.DRIVE_STICK.getRawButton(SwerveMap.Control.DRIVE_CONTROLLER_SHIFT_HIGH); swerveDriveRobot(x, y, rotate, isLowGear, isHighGear); } /** * Control robot relative to a fixed angle using gyro */ public void swerveDriveTeleopGyro() { double x, y, rotate; boolean isLowGear, isHighGear; x = SwerveMap.Control.DRIVE_STICK.getRawAxis(SwerveMap.Control.DRIVE_AXIS_FORWARD_BACK); y = -SwerveMap.Control.DRIVE_STICK.getRawAxis(SwerveMap.Control.DRIVE_AXIS_SIDEWAYS); rotate = SwerveMap.Control.DRIVE_STICK.getRawAxis(SwerveMap.Control.DRIVE_AXIS_ROTATE); isLowGear = SwerveMap.Control.DRIVE_STICK.getRawButton(SwerveMap.Control.DRIVE_CONTROLLER_SHIFT_LOW); isHighGear = SwerveMap.Control.DRIVE_STICK.getRawButton(SwerveMap.Control.DRIVE_CONTROLLER_SHIFT_HIGH); double robotAngle = SwerveMap.Control.GYRO.getAngle(); swerveDriveAbsolute(robotAngle, x, y, rotate, isLowGear, isHighGear); } /** * Class to store angle and flip together * @author emiller * */ public class AngleFlip { private double angle; private boolean flip; public AngleFlip() { setAngle(0); setFlip(false); } public AngleFlip(double angle) { this.setAngle(angle); setFlip(false); } public AngleFlip(double angle, boolean flip) { this.setAngle(angle); flip = false; } /** * @return the angle */ public double getAngle() { return angle; } /** * @param angle the angle to set */ public void setAngle(double angle) { this.angle = angle; } /** * @return the flip */ public boolean isFlip() { return flip; } /** * @param flip the flip to set */ public void setFlip(boolean flip) { this.flip = flip; } }; /** * Normalizes an angle in degrees to (-180, 180]. * @param theta Angle to normalize * @return Normalized angle */ public double normalizeAngle(double theta) { while (theta > 180) { theta -= 360; } while (theta < -180) { theta += 360; } return theta; } /** * Compute angle needed to turn and whether or not flip is needed * @param currentAngle * @param targetAngle * @return new angle with flip */ public AngleFlip computeTurnAngle(double currentAngle, double targetAngle) { AngleFlip turnAngle = new AngleFlip(targetAngle - currentAngle, false); if (Math.abs(turnAngle.getAngle()) > 90) { turnAngle.setAngle(normalizeAngle(turnAngle.getAngle() + 180)); turnAngle.setFlip(true); } return turnAngle; } /** * Compute change angle to get from current to target angle. * @param currentAngle Current angle * @param targetAngle New angle to change to * @return change angle */ public double computeChangeAngle(double currentAngle, double targetAngle) { return computeTurnAngle(currentAngle, targetAngle).getAngle(); } /** * Scale drive speed based on how far wheel needs to turn * @param turnAngle Angle wheel needs to turn (with flip value) * @return speed scale factor in range [0, 1] */ public double driveScale(AngleFlip turnAngle) { double scale = 0; if (Math.abs(turnAngle.getAngle()) < 45) { /* * Eric comment: I don't like the discontinuous nature of this scaling. * Possible improvements: * 1) Use cosine(2 * turnAngle) * 2) Scale any angle < 90. */ scale = Math.cos(Math.toRadians(turnAngle.getAngle())); } else { scale = 0; } if (turnAngle.isFlip()) { scale = -scale; } return scale; } private class Pod implements PIDOutput, PIDSource { private Encoder steeringEnc; private SpeedController drive; private SpeedController steer; private PIDController pid; public Pod(SpeedController driveController, SpeedController steeringController, int steeringEncA, int steeringEncB, int podNumber) { steeringEnc = new Encoder(steeringEncA, steeringEncB); steeringEnc.setDistancePerPulse(SwerveMap.Constants.STEERING_ENC_PULSES_PER_REVOLUTION); drive = driveController; steer = steeringController; pid = new PIDController(SwerveMap.Constants.STEERING_PID_P, SwerveMap.Constants.STEERING_PID_I, SwerveMap.Constants.STEERING_PID_D, this, this); SmartDashboard.putData("Steering Pod " + podNumber, pid); pid.setInputRange(-180, 180); pid.setContinuous(true); pid.enable(); } public void pidWrite(double output) { steer.set(output); } public double pidGet() { return steeringEnc.getDistance(); } public void setSteeringAngle(double angle) { pid.setSetpoint(angle); } public void setWheelSpeed(double speed) { drive.set(speed); } } public void initDefaultCommand() { } }
package org.freeflow.core; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.freeflow.layouts.AbstractLayout; import org.freeflow.layouts.animations.DefaultLayoutAnimator; import org.freeflow.layouts.animations.LayoutAnimator; import android.animation.ValueAnimator; import android.animation.ValueAnimator.AnimatorUpdateListener; import android.content.Context; import android.graphics.Rect; import android.util.AttributeSet; import android.util.Log; import android.util.Pair; import android.view.MotionEvent; import android.view.VelocityTracker; import android.view.View; import android.view.ViewConfiguration; public class Container extends AbsLayoutContainer { private static final String TAG = "Container"; // ViewPool class protected ViewPool viewpool; // Not used yet, but we'll probably need to // prevent layout in <code>layout()</code> method private boolean preventLayout = false; protected BaseSectionedAdapter itemAdapter; protected AbstractLayout layout; public int viewPortX = 0; public int viewPortY = 0; protected View headerView = null; private VelocityTracker mVelocityTracker = null; private float deltaX = -1f; private float deltaY = -1f; private int maxFlingVelocity; private int touchSlop; private LayoutParams params = new LayoutParams(0, 0); private LayoutAnimator layoutAnimator = new DefaultLayoutAnimator(); private ItemProxy beginTouchAt; private boolean markLayoutDirty = false; private boolean markAdapterDirty = false; private AbstractLayout oldLayout; public Container(Context context) { super(context); } public Container(Context context, AttributeSet attrs) { super(context, attrs); } public Container(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override protected void init(Context context) { // usedViews = new HashMap<Object, ItemProxy>(); // usedHeaderViews = new HashMap<Object, ItemProxy>(); viewpool = new ViewPool(); frames = new HashMap<Object, ItemProxy>(); maxFlingVelocity = ViewConfiguration.get(context).getScaledMaximumFlingVelocity(); touchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int beforeWidth = getWidth(); int beforeHeight = getHeight(); super.onMeasure(widthMeasureSpec, heightMeasureSpec); int afterWidth = MeasureSpec.getSize(widthMeasureSpec); int afterHeight = MeasureSpec.getSize(heightMeasureSpec); if (beforeWidth != afterWidth || beforeHeight != afterHeight || markLayoutDirty) { computeLayout(afterWidth, afterHeight); } } public void computeLayout(int w, int h) { Log.d(TAG, "=== Computing layout ==== "); if (layout != null) { layout.setDimensions(w, h); if (this.itemAdapter != null) layout.setItems(itemAdapter); computeViewPort(layout); HashMap<? extends Object, ItemProxy> oldFrames = frames; if (markLayoutDirty) { markLayoutDirty = false; } // Create a copy of the incoming values because the source // Layout // may change the map inside its own class frames = new HashMap<Object, ItemProxy>(layout.getItemProxies(viewPortX, viewPortY)); dispatchLayoutComputed(); animateChanges(getViewChanges(oldFrames, frames)); // for (ItemProxy frameDesc : changeSet.added) { // addAndMeasureViewIfNeeded(frameDesc); } } private void addAndMeasureViewIfNeeded(ItemProxy frameDesc) { View view; if (frameDesc.view == null) { View convertView = viewpool.getViewFromPool(itemAdapter.getViewType(frameDesc)); if (frameDesc.isHeader) { view = itemAdapter.getHeaderViewForSection(frameDesc.itemSection, convertView, this); } else { view = itemAdapter.getViewForSection(frameDesc.itemSection, frameDesc.itemIndex, convertView, this); } if (view instanceof Container) throw new IllegalStateException("A container cannot be a direct child view to a container"); frameDesc.view = view; prepareViewForAddition(view); addView(view, getChildCount(), params); } view = frameDesc.view; int widthSpec = MeasureSpec.makeMeasureSpec(frameDesc.frame.width(), MeasureSpec.EXACTLY); int heightSpec = MeasureSpec.makeMeasureSpec(frameDesc.frame.height(), MeasureSpec.EXACTLY); view.measure(widthSpec, heightSpec); if (view instanceof StateListener) ((StateListener) view).ReportCurrentState(frameDesc.state); } private void prepareViewForAddition(View view) { // view.setOnTouchListener(this); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { Log.d(TAG, "== onLayout =="); // if (layout == null || frames == null) { // return; // animateChanges(); dispatchLayoutComplete(); } private void doLayout(ItemProxy proxy) { View view = proxy.view; Rect frame = proxy.frame; view.layout(frame.left - viewPortX, frame.top - viewPortY, frame.left + frame.width() - viewPortX, frame.top + frame.height() - viewPortY); if (view instanceof StateListener) ((StateListener) view).ReportCurrentState(proxy.state); } public void setLayout(AbstractLayout lc) { if (lc == layout) { return; } oldLayout = layout; layout = lc; dispatchLayoutChanging(oldLayout, lc); dispatchDataChanged(); markLayoutDirty = true; Log.d(TAG, "=== setting layout ==="); requestLayout(); } public AbstractLayout getLayout() { return layout; } private void computeViewPort(AbstractLayout newLayout) { if (layout == null || frames == null || frames.size() == 0) { viewPortX = 0; viewPortY = 0; return; } Object data = null; int lowestSection = 99999; int lowestPosition = 99999; for (ItemProxy fd : frames.values()) { if (fd.itemSection < lowestSection || (fd.itemSection == lowestSection && fd.itemIndex < lowestPosition)) { data = fd.data; lowestSection = fd.itemSection; lowestPosition = fd.itemIndex; } } ItemProxy proxy = newLayout.getItemProxyForItem(data); if (proxy == null) { viewPortX = 0; viewPortY = 0; return; } Rect vpFrame = proxy.frame; viewPortX = vpFrame.left; viewPortY = vpFrame.top; if (viewPortX > newLayout.getContentWidth()) viewPortX = newLayout.getContentWidth(); if (viewPortY > newLayout.getContentHeight()) viewPortY = newLayout.getContentHeight(); } /** * Returns the actual frame for a view as its on stage. The ItemProxy's * frame object always represents the position it wants to be in but actual * frame may be different based on animation etc. * * @param proxy * The proxy to get the <code>Frame</code> for * @return The Frame for the proxy or null if that view doesn't exist */ public Rect getActualFrame(final ItemProxy proxy) { View v = proxy.view; if (v == null) { return null; } Rect of = new Rect(); of.left = (int) (v.getLeft() + v.getTranslationX()); of.top = (int) (v.getTop() + v.getTranslationY()); of.right = of.left + v.getWidth(); of.bottom = of.bottom + v.getHeight(); return of; } /** * TODO:::: This should be renamed to layoutInvalidated, since the layout * isn't changed */ public void layoutChanged() { Log.d(TAG, "== layoutChanged"); markLayoutDirty = true; dispatchDataChanged(); requestLayout(); } protected boolean isAnimatingChanges = false; private void animateChanges(LayoutChangeSet changeSet) { if (changeSet.added.size() == 0 && changeSet.removed.size() == 0 && changeSet.moved.size() == 0) { return; } if (isAnimatingChanges) { layoutAnimator.cancel(); } isAnimatingChanges = true; for (ItemProxy proxy : changeSet.getAdded()) { addAndMeasureViewIfNeeded(proxy); doLayout(proxy); } Log.d(TAG, "== animating changes: " + changeSet.toString()); dispatchAnimationsStarted(); layoutAnimator.animateChanges(changeSet, this); // for (Pair<ItemProxy, Rect> item : changeSet.getMoved()) { // ItemProxy proxy = ItemProxy.clone(item.first); // View v = proxy.view; // proxy.view.layout(proxy.frame.left, proxy.frame.top, proxy.frame.right, proxy.frame.bottom); // for (ItemProxy proxy : changeSet.getRemoved()) { // View v = proxy.view; // removeView(v); // returnItemToPoolIfNeeded(proxy); // requestLayout(); } public void onLayoutChangeAnimationsCompleted(LayoutAnimator anim) { // preventLayout = false; isAnimatingChanges = false; Log.d(TAG, "=== layout changes complete"); for (ItemProxy proxy : anim.getChangeSet().getRemoved()) { View v = proxy.view; removeView(v); returnItemToPoolIfNeeded(proxy); } dispatchAnimationsComplete(); // changeSet = null; } public LayoutChangeSet getViewChanges(HashMap<? extends Object, ItemProxy> oldFrames, HashMap<? extends Object, ItemProxy> newFrames) { return getViewChanges(oldFrames, newFrames, false); } public LayoutChangeSet getViewChanges(HashMap<? extends Object, ItemProxy> oldFrames, HashMap<? extends Object, ItemProxy> newFrames, boolean moveEvenIfSame) { // cleanupViews(); LayoutChangeSet change = new LayoutChangeSet(); if (oldFrames == null) { markAdapterDirty = false; Log.d(TAG, "old frames is null"); for (ItemProxy proxy : newFrames.values()) { change.addToAdded(proxy); } return change; } if (markAdapterDirty) { Log.d(TAG, "old frames is null"); markAdapterDirty = false; for (ItemProxy proxy : newFrames.values()) { change.addToAdded(proxy); } for (ItemProxy proxy : oldFrames.values()) { change.addToDeleted(proxy); } return change; } Iterator<?> it = newFrames.entrySet().iterator(); while (it.hasNext()) { Map.Entry m = (Map.Entry) it.next(); ItemProxy proxy = (ItemProxy) m.getValue(); if (oldFrames.get(m.getKey()) != null) { ItemProxy old = oldFrames.remove(m.getKey()); proxy.view = old.view; //if (moveEvenIfSame || !old.compareRect(((ItemProxy) m.getValue()).frame)) { if (moveEvenIfSame || !old.frame.equals(((ItemProxy) m.getValue()).frame)) { change.addToMoved(proxy, getActualFrame(proxy)); } } else { change.addToAdded(proxy); } } for (ItemProxy proxy : oldFrames.values()) { change.addToDeleted(proxy); } frames = newFrames; return change; } @Override public void requestLayout() { if (!preventLayout) { Log.d(TAG, "== requesting layout ==="); super.requestLayout(); } } /** * Sets the adapter for the this CollectionView.All view pools will be * cleared at this point and all views on the stage will be cleared * * @param adapter * The {@link BaseSectionedAdapter} that will populate this * Collection */ public void setAdapter(BaseSectionedAdapter adapter) { Log.d(TAG, "setting adapter"); markLayoutDirty = true; markAdapterDirty = true; this.itemAdapter = adapter; if (adapter != null) viewpool.initializeViewPool(adapter.getViewTypes()); requestLayout(); } public AbstractLayout getLayoutController() { return layout; } /** * Indicates that we are not in the middle of a touch gesture */ static final int TOUCH_MODE_REST = -1; /** * Indicates we just received the touch event and we are waiting to see if * the it is a tap or a scroll gesture. */ static final int TOUCH_MODE_DOWN = 0; /** * Indicates the touch has been recognized as a tap and we are now waiting * to see if the touch is a longpress */ static final int TOUCH_MODE_TAP = 1; /** * Indicates we have waited for everything we can wait for, but the user's * finger is still down */ static final int TOUCH_MODE_DONE_WAITING = 2; /** * Indicates the touch gesture is a scroll */ static final int TOUCH_MODE_SCROLL = 3; /** * Indicates the view is in the process of being flung */ static final int TOUCH_MODE_FLING = 4; /** * Indicates the touch gesture is an overscroll - a scroll beyond the * beginning or end. */ static final int TOUCH_MODE_OVERSCROLL = 5; /** * Indicates the view is being flung outside of normal content bounds and * will spring back. */ static final int TOUCH_MODE_OVERFLING = 6; /** * One of TOUCH_MODE_REST, TOUCH_MODE_DOWN, TOUCH_MODE_TAP, * TOUCH_MODE_SCROLL, or TOUCH_MODE_DONE_WAITING */ int mTouchMode = TOUCH_MODE_REST; @Override public boolean onTouchEvent(MotionEvent event) { super.onTouchEvent(event); if (layout == null) return false; boolean canScroll = false; if(layout.horizontalDragEnabled() && this.layout.getContentWidth() > getWidth()){ canScroll = true; } if(layout.verticalDragEnabled() && layout.getContentHeight() > getHeight()){ canScroll = true; } if (mVelocityTracker == null && canScroll){ mVelocityTracker = VelocityTracker.obtain(); mVelocityTracker.addMovement(event); } if (event.getAction() == MotionEvent.ACTION_DOWN) { beginTouchAt = layout.getItemAt(viewPortX + event.getX(), viewPortY + event.getY()); if(canScroll){ deltaX = event.getX(); deltaY = event.getY(); } mTouchMode = TOUCH_MODE_DOWN; return true; } else if (event.getAction() == MotionEvent.ACTION_MOVE) { if(canScroll){ float xDiff = event.getX() - deltaX; float yDiff = event.getY() - deltaY; double distance = Math.sqrt(xDiff * xDiff + yDiff * yDiff); if (mTouchMode == TOUCH_MODE_DOWN && distance > touchSlop) { mTouchMode = TOUCH_MODE_SCROLL; } if (mTouchMode == TOUCH_MODE_SCROLL) { moveScreen(event.getX() - deltaX, event.getY() - deltaY); deltaX = event.getX(); deltaY = event.getY(); } } return true; } else if (event.getAction() == MotionEvent.ACTION_CANCEL) { mTouchMode = TOUCH_MODE_REST; if(canScroll){ mVelocityTracker.recycle(); mVelocityTracker = null; } // requestLayout(); return true; } else if (event.getAction() == MotionEvent.ACTION_UP) { Log.d(TAG, "Action Up"); if (mTouchMode == TOUCH_MODE_SCROLL) { Log.d(TAG, "Scroll...."); mVelocityTracker.computeCurrentVelocity(maxFlingVelocity); // frames = layoutController.getFrameDescriptors(viewPortX, // viewPortY); if (Math.abs(mVelocityTracker.getXVelocity()) > 100) { final float velocityX = mVelocityTracker.getXVelocity(); final float velocityY = mVelocityTracker.getYVelocity(); ValueAnimator animator = ValueAnimator.ofFloat(1, 0); animator.addUpdateListener(new AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { int translateX = (int) ((1 - animation.getAnimatedFraction()) * velocityX / 350); int translateY = (int) ((1 - animation.getAnimatedFraction()) * velocityY / 350); moveScreen(translateX, translateY); } }); animator.setDuration(500); animator.start(); } mTouchMode = TOUCH_MODE_REST; Log.d(TAG, "Setting to rest"); } else { Log.d(TAG, "Select"); selectedItemProxy = beginTouchAt; if (mOnItemSelectedListener != null) { mOnItemSelectedListener.onItemSelected(this, selectedItemProxy); } mTouchMode = TOUCH_MODE_REST; } return true; } return false; } private void moveScreen(float movementX, float movementY) { if (layout.horizontalDragEnabled()) { viewPortX = (int) (viewPortX - movementX); } else { movementX = 0; } if (layout.verticalDragEnabled()) { viewPortY = (int) (viewPortY - movementY); } else { movementY = 0; } if (viewPortX < 0) viewPortX = 0; else if (viewPortX > layout.getContentWidth()) viewPortX = layout.getContentWidth(); if (viewPortY < 0) viewPortY = 0; else if (viewPortY > layout.getContentHeight()) viewPortY = layout.getContentHeight(); Log.d("blah", "vpx = " + viewPortX + ", vpy = " + viewPortY); HashMap<? extends Object, ItemProxy> oldFrames = frames; frames = new HashMap<Object, ItemProxy>(layout.getItemProxies(viewPortX, viewPortY)); LayoutChangeSet changeSet = getViewChanges(oldFrames, frames, true); Log.d("blah", "added = " + changeSet.added.size() + ", moved = " + changeSet.moved.size()); for (ItemProxy proxy : changeSet.added) { addAndMeasureViewIfNeeded(proxy); doLayout(proxy); } for (Pair<ItemProxy, Rect> proxyPair : changeSet.moved) { doLayout(proxyPair.first); } for (ItemProxy proxy : changeSet.removed) { proxy.view.setAlpha(0.3f); removeViewInLayout(proxy.view); returnItemToPoolIfNeeded(proxy); } } protected void returnItemToPoolIfNeeded(ItemProxy proxy) { View v = proxy.view; v.setTranslationX(0); v.setTranslationY(0); v.setRotation(0); v.setScaleX(1f); v.setScaleY(1f); v.setAlpha(1); viewpool.returnViewToPool(v); } public BaseSectionedAdapter getAdapter() { return itemAdapter; } public void setLayoutAnimator(LayoutAnimator anim) { layoutAnimator = anim; } public LayoutAnimator getLayoutAnimator() { return layoutAnimator; } public HashMap<? extends Object, ItemProxy> getFrames() { return frames; } public void clearFrames() { removeAllViews(); frames = null; } }
package com.dmdirc.ui.swing.dialogs.wizard; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.Insets; import java.awt.LayoutManager2; import java.io.Serializable; import java.util.ArrayList; import java.util.List; /** * Adjusted Card layout. */ public class StepLayout implements LayoutManager2, Serializable { /** * A version number for this class. It should be changed whenever the class * structure is changed (or anything else that would prevent serialized * objects being unserialized with the new class). */ private static final long serialVersionUID = 2; /** Parent container. */ private Container parent; /** Cards vector. */ private final List<Step> steps; /** Current step. */ private int currentStep; /** Vertical gap. */ private int vGap; /** Horiontal gap. */ private int hGap; /** * Instantiates a new step layout. */ public StepLayout() { this(0, 0); } /** * Instantiates a new step layout. * * @param parent Parent component */ public StepLayout(final Container parent) { this(0, 0, parent); } /** * Instantiates a new step layout with the specified gaps. * * @param hGap Horizontal gap * @param vGap Vertical gap */ public StepLayout(final int hGap, final int vGap) { steps = new ArrayList<Step>(); currentStep = -1; this.hGap = hGap; this.vGap = vGap; } /** * Instantiates a new step layout with the specified gaps. * * @param hGap Horizontal gap * @param vGap Vertical gap * @param parent Parent component */ public StepLayout(final int hGap, final int vGap, final Container parent) { steps = new ArrayList<Step>(); currentStep = -1; this.hGap = hGap; this.vGap = vGap; this.parent = parent; } /** * Returns the number of steps in the layout. * * @return number of steps >= 0 */ public int size() { return steps.size(); } /** * Checks if the layout is empty * * @return true iif the layout has no steps */ public boolean isEmpty() { return steps.isEmpty(); } /** * Returns the specified step from the layout. * * @param index Step to retrieve * * @return Step */ public Step getStep(final int index) { return steps.get(index); } /** * Returns the step list. * * @return List of steps */ public List getSteps() { return steps; } /** * Show the first step. * * @param parent Parent container */ public void first(final Container parent) { show(0, parent); } /** * Show the last step. * * @param parent Parent container */ public void last(final Container parent) { show(parent.getComponentCount() - 1, parent); } /** * Show the next step. * * @param parent Parent container */ public void next(final Container parent) { show(currentStep + 1, parent); } /** * Show the previous step. * * @param parent Parent container */ public void previous(final Container parent) { show(currentStep - 1, parent); } /** * Show the specified step. * * @param step Step to show * @param parent Parent container */ public void show(final Step step, final Container parent) { show(steps.indexOf(step), parent); } /** * Show the step at the specified index. * * @param step Step to show * @param parent Parent container */ public void show(final int step, final Container parent) { int stepNumber = step; if (stepNumber == -1) { if (stepNumber >= steps.size()) { stepNumber = steps.size() - 1; } else { stepNumber = 0; } } synchronized (parent.getTreeLock()) { int componentCount = parent.getComponentCount(); for (int i = 0; i < componentCount; i++) { Component comp = parent.getComponent(i); if (comp.isVisible()) { comp.setVisible(false); break; } } if (componentCount > 0) { currentStep = stepNumber; parent.getComponent(currentStep).setVisible(true); parent.validate(); } } } /** {@inheritDoc} */ @Override public void addLayoutComponent(final Component comp, final Object constraints) { if (!(comp instanceof Step)) { throw new IllegalArgumentException("Component must be an instance of Step"); } addLayoutComponent((Step) comp); } /** * {@inheritDoc} * * @deprecated Use addLayoutComponent(Component, Object) or * addLayoutComponent(Component) * * @see addLayoutComponent(Component) * @see addLayoutComponent(Component, Object) */ @Override @Deprecated public void addLayoutComponent(final String name, final Component comp) { if (!(comp instanceof Step)) { throw new IllegalArgumentException("Component must be an instance of Step"); } addLayoutComponent((Step) comp); } /** * Adds a component to the layout. * * @param step Component to add */ public void addLayoutComponent(final Step step) { synchronized (step.getTreeLock()) { if (!steps.isEmpty()) { step.setVisible(false); } steps.add(step); } } /** {@inheritDoc} */ @Override public void removeLayoutComponent(final Component comp) { synchronized (comp.getTreeLock()) { if (comp.isVisible()) { comp.setVisible(false); } next(comp.getParent()); steps.remove(comp); } } /** * {@inheritDoc} * * @return Returns the preferred size of the container */ @Override public Dimension preferredLayoutSize(final Container parent) { synchronized (parent.getTreeLock()) { Insets insets = parent.getInsets(); int componentCount = parent.getComponentCount(); int width = 0; int height = 0; for (int i = 0; i < componentCount; i++) { Component comp = parent.getComponent(i); Dimension preferredDimension = comp.getPreferredSize(); if (preferredDimension.width > width) { width = preferredDimension.width; } if (preferredDimension.height > height) { height = preferredDimension.height; } } return new Dimension(insets.left + insets.right + width + hGap * 2, insets.top + insets.bottom + height + vGap * 2); } } /** * {@inheritDoc} * * @return Returns the minimum size of the container */ @Override public Dimension minimumLayoutSize(final Container parent) { synchronized (parent.getTreeLock()) { Insets insets = parent.getInsets(); int componentCount = parent.getComponentCount(); int width = 0; int height = 0; for (int i = 0; i < componentCount; i++) { Component comp = parent.getComponent(i); Dimension minimumDimension = comp.getMinimumSize(); if (minimumDimension.width > width) { width = minimumDimension.width; } if (minimumDimension.height > height) { height = minimumDimension.height; } } return new Dimension(insets.left + insets.right + width + hGap * 2, insets.top + insets.bottom + height + vGap * 2); } } /** * {@inheritDoc} * * @param parent Container to get the size for * * @return Returns the maximum size of the container */ @Override public Dimension maximumLayoutSize(final Container parent) { return new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE); } /** * {@inheritDoc} * * @param target Container to get the alignment from * * @return Alignment */ @Override public float getLayoutAlignmentX(final Container target) { return 0.5f; } /** * {@inheritDoc} * * @param target Container to get the alignment from * * @return Alignment */ @Override public float getLayoutAlignmentY(final Container target) { return 0.5f; } /** * {@inheritDoc} * * @param target Container to invalidate */ @Override public void invalidateLayout(final Container target) { //Ignore } /** {@inheritDoc} */ @Override public void layoutContainer(final Container parent) { synchronized (parent.getTreeLock()) { Insets insets = parent.getInsets(); int componentCount = parent.getComponentCount(); Component comp = null; boolean currentFound = false; for (int i = 0; i < componentCount; i++) { comp = parent.getComponent(i); comp.setBounds(hGap + insets.left, vGap + insets.top, parent.getWidth() - (hGap * 2 + insets.left + insets.right), parent.getHeight() - (vGap * 2 + insets.top + insets.bottom)); if (comp.isVisible()) { currentFound = true; } } if (!currentFound && componentCount > 0) { parent.getComponent(0).setVisible(true); } } } }
package org.motechproject.nms.testing.it.api; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; import javax.inject.Inject; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.io.IOUtils; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.util.EntityUtils; import org.codehaus.jackson.map.ObjectMapper; import org.json.JSONObject; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.motechproject.mtraining.service.BookmarkService; import org.motechproject.nms.api.web.BaseController; import org.motechproject.nms.api.web.contract.BadRequest; import org.motechproject.nms.api.web.contract.mobileAcademy.CourseResponse; import org.motechproject.nms.api.web.contract.mobileAcademy.SaveBookmarkRequest; import org.motechproject.nms.api.web.contract.mobileAcademy.SmsStatusRequest; import org.motechproject.nms.api.web.contract.mobileAcademy.sms.RequestData; import org.motechproject.nms.mobileacademy.domain.NmsCourse; import org.motechproject.nms.mobileacademy.dto.MaCourse; import org.motechproject.nms.mobileacademy.repository.NmsCourseDataService; import org.motechproject.nms.mobileacademy.service.MobileAcademyService; import org.motechproject.nms.testing.it.api.utils.RequestBuilder; import org.motechproject.nms.testing.service.TestingService; import org.motechproject.testing.osgi.BasePaxIT; import org.motechproject.testing.osgi.container.MotechNativeTestContainerFactory; import org.motechproject.testing.osgi.http.SimpleHttpClient; import org.motechproject.testing.utils.TestContext; import org.ops4j.pax.exam.ExamFactory; import org.ops4j.pax.exam.junit.PaxExam; import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy; import org.ops4j.pax.exam.spi.reactors.PerSuite; /** * Integration tests for mobile academy controller */ @RunWith(PaxExam.class) @ExamReactorStrategy(PerSuite.class) @ExamFactory(MotechNativeTestContainerFactory.class) public class MobileAcademyControllerBundleIT extends BasePaxIT { @Inject MobileAcademyService mobileAcademyService; @Inject TestingService testingService; @Inject private BookmarkService bookmarkService; @Inject private NmsCourseDataService nmsCourseDataService; private static final String COURSE_NAME = "MobileAcademyCourse"; @Before public void setupTestData() { testingService.clearDatabase(); nmsCourseDataService.deleteAll(); } @Test public void testBookmarkBadCallingNumber() throws IOException, InterruptedException { String endpoint = String.format("http://localhost:%d/api/mobileacademy/bookmarkWithScore", TestContext.getJettyPort()); HttpPost request = RequestBuilder.createPostRequest(endpoint, new SaveBookmarkRequest()); assertTrue(SimpleHttpClient.execHttpRequest(request, HttpStatus.SC_BAD_REQUEST, RequestBuilder.ADMIN_USERNAME, RequestBuilder.ADMIN_PASSWORD)); } @Test public void testBookmarkBadCallId() throws IOException, InterruptedException { String endpoint = String.format("http://localhost:%d/api/mobileacademy/bookmarkWithScore", TestContext.getJettyPort()); SaveBookmarkRequest bookmarkRequest = new SaveBookmarkRequest(); bookmarkRequest.setCallId(BaseController.SMALLEST_15_DIGIT_NUMBER - 1); HttpPost request = RequestBuilder.createPostRequest(endpoint, bookmarkRequest); assertTrue(SimpleHttpClient.execHttpRequest(request, HttpStatus.SC_BAD_REQUEST, RequestBuilder.ADMIN_USERNAME, RequestBuilder.ADMIN_PASSWORD)); } @Test public void testBookmarkNullCallId() throws IOException, InterruptedException { String endpoint = String.format("http://localhost:%d/api/mobileacademy/bookmarkWithScore", TestContext.getJettyPort()); SaveBookmarkRequest bookmark = new SaveBookmarkRequest(); bookmark.setCallingNumber(BaseController.SMALLEST_10_DIGIT_NUMBER); HttpPost request = RequestBuilder.createPostRequest(endpoint, bookmark); assertTrue(SimpleHttpClient.execHttpRequest(request, HttpStatus.SC_BAD_REQUEST, RequestBuilder.ADMIN_USERNAME, RequestBuilder.ADMIN_PASSWORD)); } @Test public void testSetValidBookmark() throws IOException, InterruptedException { String endpoint = String.format("http://localhost:%d/api/mobileacademy/bookmarkWithScore", TestContext.getJettyPort()); SaveBookmarkRequest bookmark = new SaveBookmarkRequest(); bookmark.setCallingNumber(BaseController.SMALLEST_10_DIGIT_NUMBER); bookmark.setCallId(BaseController.SMALLEST_15_DIGIT_NUMBER); HttpPost request = RequestBuilder.createPostRequest(endpoint, bookmark); assertTrue(SimpleHttpClient.execHttpRequest(request, HttpStatus.SC_OK, RequestBuilder.ADMIN_USERNAME, RequestBuilder.ADMIN_PASSWORD)); } @Test public void testTriggerNotification() throws IOException, InterruptedException { String endpoint = String.format("http://localhost:%d/api/mobileacademy/bookmarkWithScore", TestContext.getJettyPort()); SaveBookmarkRequest bookmark = new SaveBookmarkRequest(); bookmark.setCallingNumber(BaseController.SMALLEST_10_DIGIT_NUMBER); bookmark.setCallId(BaseController.SMALLEST_15_DIGIT_NUMBER); Map<String, Integer> scores = new HashMap<>(); for (int i = 1; i < 12; i++) { scores.put(String.valueOf(i), 4); } bookmark.setScoresByChapter(scores); bookmark.setBookmark("Chapter11_Quiz"); HttpPost request = RequestBuilder.createPostRequest(endpoint, bookmark); assertTrue(SimpleHttpClient.execHttpRequest(request, HttpStatus.SC_OK, RequestBuilder.ADMIN_USERNAME, RequestBuilder.ADMIN_PASSWORD)); long callingNumber = BaseController.SMALLEST_10_DIGIT_NUMBER; endpoint = String.format("http://localhost:%d/api/mobileacademy/notify", TestContext.getJettyPort()); request = RequestBuilder.createPostRequest(endpoint, callingNumber); assertTrue(SimpleHttpClient.execHttpRequest(request, HttpStatus.SC_OK, RequestBuilder.ADMIN_USERNAME, RequestBuilder.ADMIN_PASSWORD)); // removed the negative testing since there's not reliable way to clean the data for it to fail // after the first time. Debugged and verified that the negative works too and we have negative ITs // at the service layer. } @Test public void testSetValidExistingBookmark() throws IOException, InterruptedException { String endpoint = String.format("http://localhost:%d/api/mobileacademy/bookmarkWithScore", TestContext.getJettyPort()); SaveBookmarkRequest bookmark = new SaveBookmarkRequest(); bookmark.setCallingNumber(BaseController.SMALLEST_10_DIGIT_NUMBER); bookmark.setCallId(BaseController.SMALLEST_15_DIGIT_NUMBER); HttpPost request = RequestBuilder.createPostRequest(endpoint, bookmark); assertTrue(SimpleHttpClient.execHttpRequest(request, HttpStatus.SC_OK, RequestBuilder.ADMIN_USERNAME, RequestBuilder.ADMIN_PASSWORD)); // Now, update the previous bookmark successfully bookmark.setBookmark("Chapter3_Lesson2"); request = RequestBuilder.createPostRequest(endpoint, bookmark); assertTrue(SimpleHttpClient.execHttpRequest(request, HttpStatus.SC_OK, RequestBuilder.ADMIN_USERNAME, RequestBuilder.ADMIN_PASSWORD)); } @Test public void testGetCourseValid() throws IOException, InterruptedException { setupMaCourse(); String endpoint = String.format("http://localhost:%d/api/mobileacademy/course", TestContext.getJettyPort()); HttpGet request = RequestBuilder.createGetRequest(endpoint); HttpResponse httpResponse = SimpleHttpClient.httpRequestAndResponse(request, RequestBuilder.ADMIN_USERNAME, RequestBuilder.ADMIN_PASSWORD); assertEquals(200, httpResponse.getStatusLine().getStatusCode()); String body = IOUtils.toString(httpResponse.getEntity().getContent()); assertNotNull(body); //TODO: figure out a way to automate the body comparison from the course json resource file } @Test @Ignore public void testSmsStatusInvalidFormat() throws IOException, InterruptedException { String endpoint = String.format("http://localhost:%d/api/mobileacademy/smsdeliverystatus", TestContext.getJettyPort()); SmsStatusRequest smsStatusRequest = new SmsStatusRequest(); smsStatusRequest.setRequestData(new RequestData()); HttpPost request = RequestBuilder.createPostRequest(endpoint, smsStatusRequest); assertTrue(SimpleHttpClient.execHttpRequest(request, HttpStatus.SC_BAD_REQUEST, RequestBuilder.ADMIN_USERNAME, RequestBuilder.ADMIN_PASSWORD)); } /** * setup MA course structure from nmsCourse.json file. */ private JSONObject setupMaCourse() throws IOException { MaCourse course = new MaCourse(); String jsonText = IOUtils .toString(getFileInputStream("nmsCourse.json")); JSONObject jo = new JSONObject(jsonText); course.setName(jo.get("name").toString()); course.setContent(jo.get("chapters").toString()); nmsCourseDataService.create(new NmsCourse(course.getName(), course .getContent())); return jo; } private InputStream getFileInputStream(String fileName) { try { return new FileInputStream(new File(Thread.currentThread() .getContextClassLoader().getResource(fileName).getPath())); } catch (IOException io) { return null; } } /** * To verify Get MA Course Version API is not returning course version when * MA course structure doesn't exist. */ @Test public void verifyFT400() throws IOException, InterruptedException { String endpoint = String.format( "http://localhost:%d/api/mobileacademy/courseVersion", TestContext.getJettyPort()); HttpGet request = RequestBuilder.createGetRequest(endpoint); HttpResponse httpResponse = SimpleHttpClient.httpRequestAndResponse( request, RequestBuilder.ADMIN_USERNAME, RequestBuilder.ADMIN_PASSWORD); assertEquals(HttpStatus.SC_INTERNAL_SERVER_ERROR, httpResponse .getStatusLine().getStatusCode()); } /** * To verify Get MA Course Version API is returning correct course version * when MA course structure exist . */ @Test public void verifyFT401() throws IOException, InterruptedException { setupMaCourse(); String endpoint = String.format( "http://localhost:%d/api/mobileacademy/courseVersion", TestContext.getJettyPort()); HttpGet request = RequestBuilder.createGetRequest(endpoint); HttpResponse httpResponse = SimpleHttpClient.httpRequestAndResponse( request, RequestBuilder.ADMIN_USERNAME, RequestBuilder.ADMIN_PASSWORD); NmsCourse course = nmsCourseDataService.getCourseByName(COURSE_NAME); String expectedJsonResponse = "{\"courseVersion\":" + course.getModificationDate().getMillis() + "}"; assertEquals(HttpStatus.SC_OK, httpResponse.getStatusLine() .getStatusCode()); assertEquals(expectedJsonResponse, EntityUtils.toString(httpResponse.getEntity())); } /** * To verify Get MA Course API is not returning course structure when MA * course structure doesn't exist. */ @Test public void verifyFT402() throws IOException, InterruptedException { String endpoint = String.format( "http://localhost:%d/api/mobileacademy/course", TestContext.getJettyPort()); HttpGet request = RequestBuilder.createGetRequest(endpoint); HttpResponse httpResponse = SimpleHttpClient.httpRequestAndResponse( request, RequestBuilder.ADMIN_USERNAME, RequestBuilder.ADMIN_PASSWORD); assertEquals(HttpStatus.SC_INTERNAL_SERVER_ERROR, httpResponse .getStatusLine().getStatusCode()); } /** * To verify Get MA Course API is returning correct course structure when MA * course structure exist. */ @Test public void verifyFT403() throws IOException, InterruptedException { JSONObject jo = setupMaCourse(); String endpoint = String.format( "http://localhost:%d/api/mobileacademy/course", TestContext.getJettyPort()); HttpGet request = RequestBuilder.createGetRequest(endpoint); HttpResponse httpResponse = SimpleHttpClient.httpRequestAndResponse( request, RequestBuilder.ADMIN_USERNAME, RequestBuilder.ADMIN_PASSWORD); NmsCourse course = nmsCourseDataService.getCourseByName(COURSE_NAME); CourseResponse courseResponseDTO = new CourseResponse(); courseResponseDTO.setName(jo.get("name").toString()); courseResponseDTO.setCourseVersion(course.getModificationDate() .getMillis()); courseResponseDTO.setChapters(jo.get("chapters").toString()); ObjectMapper mapper = new ObjectMapper(); String expectedJsonResponse = mapper .writeValueAsString(courseResponseDTO); assertEquals(HttpStatus.SC_OK, httpResponse.getStatusLine() .getStatusCode()); assertEquals(expectedJsonResponse, EntityUtils.toString(httpResponse.getEntity())); } HttpGet createHttpGetBookmarkWithScore(String callingNo, String callId) { StringBuilder sb = new StringBuilder(); sb.append(String.format( "http://localhost:%d/api/mobileacademy/bookmarkWithScore", TestContext.getJettyPort())); String seperator = "?"; if (callingNo != null) { sb.append(seperator); sb.append("callingNumber="); sb.append(callingNo); seperator = ""; } if (callId != null) { if (seperator.equals("")) { sb.append("&"); } else { sb.append(seperator); } sb.append("callId="); sb.append(callId); } // System.out.println("Request url:" + sb.toString()); return RequestBuilder.createGetRequest(sb.toString()); } private String createFailureResponseJson(String failureReason) throws IOException { BadRequest badRequest = new BadRequest(failureReason); ObjectMapper mapper = new ObjectMapper(); return mapper.writeValueAsString(badRequest); } /** * To verify Get Bookmark with Score API is returning correct bookmark and * score details. */ @Ignore @Test public void verifyFT404() throws IOException, InterruptedException { bookmarkService.deleteAllBookmarksForUser("1234567890"); // Blank bookmark should come as request response, As there is no any // bookmark in the system for the user HttpGet getRequest = createHttpGetBookmarkWithScore("1234567890", "123456789012345"); getRequest.setHeader("Content-type", "application/json"); HttpResponse response = SimpleHttpClient.httpRequestAndResponse( getRequest, RequestBuilder.ADMIN_USERNAME, RequestBuilder.ADMIN_PASSWORD); assertEquals(HttpStatus.SC_OK, response.getStatusLine() .getStatusCode()); assertTrue("{}".equals(EntityUtils.toString(response.getEntity()))); } /** * To verify Get Bookmark with Score API is returning correct bookmark and * score details. */ @Ignore @Test public void verifyFT532() throws IOException, InterruptedException { // create bookmark for the user String endpoint = String.format( "http://localhost:%d/api/mobileacademy/bookmarkWithScore", TestContext.getJettyPort()); SaveBookmarkRequest bookmarkRequest = new SaveBookmarkRequest(); bookmarkRequest.setCallId(123456789012345l); bookmarkRequest.setCallingNumber(1234567890l); bookmarkRequest.setBookmark("Chapter01_Lesson01"); Map<String, Integer> scoreMap = new HashMap<String, Integer>(); scoreMap.put("1", 2); bookmarkRequest.setScoresByChapter(scoreMap); HttpPost postRequest = RequestBuilder.createPostRequest(endpoint, bookmarkRequest); SimpleHttpClient.httpRequestAndResponse(postRequest, RequestBuilder.ADMIN_USERNAME, RequestBuilder.ADMIN_PASSWORD); // fetch bookmark for the same user HttpGet getRequest = createHttpGetBookmarkWithScore("1234567890", "123456789012345"); HttpResponse response = SimpleHttpClient.httpRequestAndResponse( getRequest, RequestBuilder.ADMIN_USERNAME, RequestBuilder.ADMIN_PASSWORD); assertEquals(HttpStatus.SC_OK, response.getStatusLine() .getStatusCode()); assertTrue("{\"bookmark\":\"Chapter01_Lesson01\",\"scoresByChapter\":{\"1\":2}}" .equals(EntityUtils.toString(response .getEntity()))); } /** * To verify that bookmark with score are saved correctly using Save * bookmark with score API. */ @Test public void verifyFT409() throws IOException, InterruptedException { String endpoint = String.format( "http://localhost:%d/api/mobileacademy/bookmarkWithScore", TestContext.getJettyPort()); SaveBookmarkRequest bookmarkRequest = new SaveBookmarkRequest(); bookmarkRequest.setCallId(123456789012345l); bookmarkRequest.setCallingNumber(1234567890l); bookmarkRequest.setBookmark("Chapter01_Lesson01"); Map<String, Integer> scoreMap = new HashMap<String, Integer>(); scoreMap.put("1", 2); scoreMap.put("2", 0); scoreMap.put("3", 3); bookmarkRequest.setScoresByChapter(scoreMap); HttpPost request = RequestBuilder.createPostRequest(endpoint, bookmarkRequest); assertTrue(SimpleHttpClient.execHttpRequest(request, HttpStatus.SC_OK, RequestBuilder.ADMIN_USERNAME, RequestBuilder.ADMIN_PASSWORD)); } /** * To verify that bookmark with score are saved correctly using Save * bookmark with score API when optional parameter are missing. */ @Test public void verifyFT410() throws IOException, InterruptedException { // Request without callingNumber and Bookmark String endpoint = String.format( "http://localhost:%d/api/mobileacademy/bookmarkWithScore", TestContext.getJettyPort()); SaveBookmarkRequest bookmarkRequest = new SaveBookmarkRequest(); bookmarkRequest.setCallId(123456789012345l); bookmarkRequest.setCallingNumber(1234567890l); HttpPost request = RequestBuilder.createPostRequest(endpoint, bookmarkRequest); assertTrue(SimpleHttpClient.execHttpRequest(request, HttpStatus.SC_OK, RequestBuilder.ADMIN_USERNAME, RequestBuilder.ADMIN_PASSWORD)); } /** * To verify Save bookmark with score API is rejected when mandatory * parameter "callingNumber" is missing. */ @Test @Ignore public void verifyFT411() throws IOException, InterruptedException { // callingNumber missing in the request body String endpoint = String.format( "http://localhost:%d/api/mobileacademy/bookmarkWithScore", TestContext.getJettyPort()); SaveBookmarkRequest bookmarkRequest = new SaveBookmarkRequest(); bookmarkRequest.setCallId(123456789012345l); bookmarkRequest.setBookmark("Chapter01_Lesson01"); Map<String, Integer> scoreMap = new HashMap<String, Integer>(); scoreMap.put("1", 2); scoreMap.put("2", 0); scoreMap.put("3", 3); bookmarkRequest.setScoresByChapter(scoreMap); HttpPost request = RequestBuilder.createPostRequest(endpoint, bookmarkRequest); HttpResponse response = SimpleHttpClient.httpRequestAndResponse( request, RequestBuilder.ADMIN_USERNAME, RequestBuilder.ADMIN_PASSWORD); assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusLine() .getStatusCode()); String expectedJsonResponse = createFailureResponseJson("<callingNumber: Not Present>"); assertTrue(expectedJsonResponse.equals(EntityUtils.toString(response .getEntity()))); } /** * To verify Save bookmark with score API is rejected when mandatory * parameter "callId" is missing. */ @Test @Ignore public void verifyFT412() throws IOException, InterruptedException { // callId missing in the request body String endpoint = String.format( "http://localhost:%d/api/mobileacademy/bookmarkWithScore", TestContext.getJettyPort()); SaveBookmarkRequest bookmarkRequest = new SaveBookmarkRequest(); bookmarkRequest.setCallingNumber(1234567890l); bookmarkRequest.setBookmark("Chapter01_Lesson01"); Map<String, Integer> scoreMap = new HashMap<String, Integer>(); scoreMap.put("1", 2); scoreMap.put("2", 0); scoreMap.put("3", 3); bookmarkRequest.setScoresByChapter(scoreMap); HttpPost request = RequestBuilder.createPostRequest(endpoint, bookmarkRequest); HttpResponse response = SimpleHttpClient.httpRequestAndResponse( request, RequestBuilder.ADMIN_USERNAME, RequestBuilder.ADMIN_PASSWORD); assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusLine() .getStatusCode()); String expectedJsonResponse = createFailureResponseJson("<callId: Not Present>"); assertTrue(expectedJsonResponse.equals(EntityUtils.toString(response .getEntity()))); } /** * To verify Save bookmark with score API is rejected when mandatory * parameter "callId" is having invalid value. */ @Test @Ignore public void verifyFT413() throws IOException, InterruptedException { // callId more than 15 digit String endpoint = String.format( "http://localhost:%d/api/mobileacademy/bookmarkWithScore", TestContext.getJettyPort()); SaveBookmarkRequest bookmarkRequest = new SaveBookmarkRequest(); bookmarkRequest.setCallId(1234567890123456l); bookmarkRequest.setCallingNumber(1234567890l); bookmarkRequest.setBookmark("Chapter01_Lesson01"); Map<String, Integer> scoreMap = new HashMap<String, Integer>(); scoreMap.put("1", 2); scoreMap.put("2", 0); scoreMap.put("3", 3); bookmarkRequest.setScoresByChapter(scoreMap); HttpPost request = RequestBuilder.createPostRequest(endpoint, bookmarkRequest); HttpResponse response = SimpleHttpClient.httpRequestAndResponse( request, RequestBuilder.ADMIN_USERNAME, RequestBuilder.ADMIN_PASSWORD); assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusLine() .getStatusCode()); String expectedJsonResponse = createFailureResponseJson("<callId: Invalid>"); assertTrue(expectedJsonResponse.equals(EntityUtils.toString(response .getEntity()))); } /** * To verify Save bookmark with score API is rejected when mandatory * parameter "callingNumber" is having invalid value. */ @Test public void verifyFT414() throws IOException, InterruptedException { // callingNumber less than 10 digit String endpoint = String.format( "http://localhost:%d/api/mobileacademy/bookmarkWithScore", TestContext.getJettyPort()); SaveBookmarkRequest bookmarkRequest = new SaveBookmarkRequest(); bookmarkRequest.setCallingNumber(123456789l); bookmarkRequest.setCallId(123456789012345l); bookmarkRequest.setBookmark("Chapter01_Lesson01"); Map<String, Integer> scoreMap = new HashMap<String, Integer>(); scoreMap.put("1", 2); scoreMap.put("2", 0); scoreMap.put("3", 3); bookmarkRequest.setScoresByChapter(scoreMap); HttpPost request = RequestBuilder.createPostRequest(endpoint, bookmarkRequest); HttpResponse response = SimpleHttpClient.httpRequestAndResponse( request, RequestBuilder.ADMIN_USERNAME, RequestBuilder.ADMIN_PASSWORD); assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusLine() .getStatusCode()); String expectedJsonResponse = createFailureResponseJson("<callingNumber: Invalid>"); assertTrue(expectedJsonResponse.equals(EntityUtils.toString(response .getEntity()))); // callingNumber more than 10 digit bookmarkRequest.setCallingNumber(12345678901l); request = RequestBuilder.createPostRequest(endpoint, bookmarkRequest); response = SimpleHttpClient.httpRequestAndResponse(request, RequestBuilder.ADMIN_USERNAME, RequestBuilder.ADMIN_PASSWORD); assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusLine() .getStatusCode()); assertTrue(expectedJsonResponse.equals(EntityUtils.toString(response .getEntity()))); } /** * To verify Save bookmark with score API is rejected when parameter * scoresByChapter is having value greater than 4. */ @Test @Ignore public void verifyFT415() throws IOException, InterruptedException { // Invalid scores should not be accepted String endpoint = String.format( "http://localhost:%d/api/mobileacademy/bookmarkWithScore", TestContext.getJettyPort()); SaveBookmarkRequest bookmarkRequest = new SaveBookmarkRequest(); bookmarkRequest.setCallingNumber(123456789l); bookmarkRequest.setCallId(123456789012345l); bookmarkRequest.setBookmark("Chapter01_Lesson01"); Map<String, Integer> scoreMap = new HashMap<String, Integer>(); scoreMap.put("1", 2); scoreMap.put("2", 6); // Invalid score greater than 4 scoreMap.put("3", 3); bookmarkRequest.setScoresByChapter(scoreMap); HttpPost request = RequestBuilder.createPostRequest(endpoint, bookmarkRequest); HttpResponse response = SimpleHttpClient.httpRequestAndResponse( request, RequestBuilder.ADMIN_USERNAME, RequestBuilder.ADMIN_PASSWORD); assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusLine() .getStatusCode()); String expectedJsonResponse = createFailureResponseJson("<scoresByChapter: Invalid>"); assertTrue(expectedJsonResponse.equals(EntityUtils.toString(response .getEntity()))); } /** * To verify Save bookmark with score API is rejected when parameter * "bookmark" is having invalid value. */ @Test @Ignore public void verifyFT416() throws IOException, InterruptedException { // Requets with invalid bookmark value String endpoint = String.format( "http://localhost:%d/api/mobileacademy/bookmarkWithScore", TestContext.getJettyPort()); SaveBookmarkRequest bookmarkRequest = new SaveBookmarkRequest(); bookmarkRequest.setCallingNumber(123456789l); bookmarkRequest.setCallId(123456789012345l); bookmarkRequest.setBookmark("Abc_Abc"); // Invalid bookmark Map<String, Integer> scoreMap = new HashMap<String, Integer>(); scoreMap.put("1", 2); scoreMap.put("2", 3); scoreMap.put("3", 3); bookmarkRequest.setScoresByChapter(scoreMap); HttpPost request = RequestBuilder.createPostRequest(endpoint, bookmarkRequest); HttpResponse response = SimpleHttpClient.httpRequestAndResponse( request, RequestBuilder.ADMIN_USERNAME, RequestBuilder.ADMIN_PASSWORD); assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusLine() .getStatusCode()); String expectedJsonResponse = createFailureResponseJson("<bookmark: Invalid>"); assertTrue(expectedJsonResponse.equals(EntityUtils.toString(response .getEntity()))); } }
package com.haxademic.sketch.particle; import java.util.ArrayList; import com.haxademic.core.app.P; import com.haxademic.core.app.PAppletHax; import com.haxademic.core.constants.AppSettings; import com.haxademic.core.draw.context.DrawUtil; import com.haxademic.core.draw.context.OpenGLUtil; import com.haxademic.core.draw.filters.pshader.VignetteAltFilter; import com.haxademic.core.math.easing.EasingFloat; import processing.core.PVector; public class VectorFieldTest extends PAppletHax { public static void main(String args[]) { PAppletHax.main(Thread.currentThread().getStackTrace()[1].getClassName()); } protected ArrayList<PVector> _vectorField; protected ArrayList<FieldParticle> _particles; protected int frames = 130; float FIELD_SPACING = 40f; float NUM_PARTICLES = 700f; float ATTENTION_RADIUS = 100; int DRAWS_PER_FRAME = 1; int OVERDRAW_FADE = 20; boolean DEBUG_VECTORS = false; protected void overridePropsFile() { p.appConfig.setProperty( AppSettings.WIDTH, 1280 ); p.appConfig.setProperty( AppSettings.HEIGHT, 720 ); p.appConfig.setProperty( AppSettings.WIDTH, 640 ); p.appConfig.setProperty( AppSettings.HEIGHT, 640 ); p.appConfig.setProperty( AppSettings.FULLSCREEN, false ); // p.appConfig.setProperty( AppSettings.DISPLAY, 2 ); p.appConfig.setProperty( AppSettings.FILLS_SCREEN, false ); p.appConfig.setProperty( AppSettings.RETINA, false ); p.appConfig.setProperty( AppSettings.RENDERING_MOVIE, false); p.appConfig.setProperty( AppSettings.RENDERING_MOVIE_STOP_FRAME, frames); } public void setup() { super.setup(); _vectorField = new ArrayList<PVector>(); for( int x = 0; x <= p.width; x += FIELD_SPACING ) { for( int y = 0; y <= p.height; y += FIELD_SPACING ) { _vectorField.add( new PVector(x, y, 0) ); } } _particles = new ArrayList<FieldParticle>(); for( int i = 0; i < NUM_PARTICLES; i++ ) { _particles.add( new FieldParticle() ); } } public void drawApp() { if( p.frameCount == 1 ) p.background(0); // OpenGLUtil.setBlending(p.g, true); // OpenGLUtil.setBlendMode(p.g, OpenGLUtil.Blend.ADDITIVE); // feedback(4, 0.2f); // fade out background DrawUtil.setDrawCorner(p); p.noStroke(); p.fill(0, OVERDRAW_FADE); p.rect(0,0,p.width, p.height); // draw field DrawUtil.setDrawCenter(p); p.fill(0); for (PVector vector : _vectorField) { float noise = p.noise( vector.x/11f + p.noise(p.frameCount/50f), vector.y/20f + p.noise(p.frameCount/50f) ); float targetRotation = noise * 4f * P.TWO_PI; vector.set(vector.x, vector.y, P.lerp(vector.z, targetRotation, 0.2f)); // draw attractors p.pushMatrix(); p.translate(vector.x, vector.y); p.rotate( vector.z ); // use z for rotation! // p.rect(0, 0, 1, 10); p.popMatrix(); } updateVectors(); for (int j = 0; j < DRAWS_PER_FRAME; j++) { // draw particles p.strokeWeight(2f); DrawUtil.setDrawCenter(p); for( int i = 0; i < _particles.size(); i++ ) { // p.fill((i % 150 + 55 / 10), i % 155 + 100, i % 100 + 100); // blue/green p.stroke(180 + (i % 75), 200 + (i % 55), 210 + (i % 45)); _particles.get(i).update( _vectorField, i ); } } // postProcessForRendering(); } public void feedback(float amp, float darkness) { DrawUtil.setDrawCorner(p); p.g.copy( p.g, 0, 0, p.width, p.height, P.round(-amp/2f), P.round(-amp/2f), P.round(p.width + amp), P.round(p.height + amp) ); p.fill(0, darkness * 255f); p.noStroke(); p.rect(0, 0, p.width, p.height); } protected void updateVectors() { // override this if we want } protected void postProcessForRendering() { // overlay int transitionIn = 50; int transition = 40; DrawUtil.setDrawCorner(p); if(p.frameCount <= transitionIn) { VignetteAltFilter.instance(p).setDarkness(P.map(p.frameCount, 1f, transitionIn, -7f, -1.75f)); VignetteAltFilter.instance(p).setSpread(P.map(p.frameCount, 1f, transitionIn, -3f, -1.25f)); VignetteAltFilter.instance(p).applyTo(p); p.fill(255, P.map(p.frameCount, 1f, transition, 255f, 0)); p.rect(0,0,p.width, p.height); } else if(p.frameCount >= frames - transition) { VignetteAltFilter.instance(p).setDarkness(P.map(p.frameCount, frames - transition, frames, -1.75f, -7f)); VignetteAltFilter.instance(p).setSpread(P.map(p.frameCount, frames - transition, frames, -1.25f, -3f)); VignetteAltFilter.instance(p).applyTo(p); p.fill(255, P.map(p.frameCount, frames - transition, frames, 0, 255f)); p.rect(0,0,p.width, p.height); } else { VignetteAltFilter.instance(p).setDarkness(-1.75f); VignetteAltFilter.instance(p).setSpread(-1.25f); VignetteAltFilter.instance(p).applyTo(p); } } public class FieldParticle { public PVector lastPosition; public PVector position; public EasingFloat radians; public float speed; public FieldParticle() { speed = p.random(2,6); radians = new EasingFloat(0, p.random(6,20) ); position = new PVector( p.random(0, p.width), p.random(0, p.height) ); lastPosition = new PVector(); lastPosition.set(position); } public void update( ArrayList<PVector> vectorField, int index ) { // adjust to surrounding vectors int closeVectors = 0; float averageDirection = 0; for (PVector vector : _vectorField) { if( vector.dist( position ) < ATTENTION_RADIUS ) { averageDirection += vector.z; closeVectors++; } } if( closeVectors > 0 ) { if( p.frameCount == 1 ) { radians.setCurrent( -averageDirection / closeVectors ); } else { radians.setTarget( -averageDirection / closeVectors ); } } radians.update(); // update position lastPosition.set(position); float curSpeed = speed * p.audioFreq(index); position.set( position.x + P.sin(radians.value()) * curSpeed * P.map(p.mouseX, 0, p.width, 0, 2f), position.y + P.cos(radians.value()) * curSpeed * P.map(p.mouseX, 0, p.width, 0, 2f) ); if( position.x < 0 ) position.set( p.width, position.y ); if( position.x > p.width ) position.set( 0, position.y ); if( position.y < 0 ) position.set( position.x, p.height ); if( position.y > p.height ) position.set( position.x, 0 ); // draw if(position.dist(lastPosition) < curSpeed * 2f) { p.line(position.x, position.y, lastPosition.x, lastPosition.y); } } } }
package dynamake; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Cursor; import java.awt.Dimension; import java.awt.Font; import java.awt.Point; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.util.ArrayList; import java.util.Date; import java.util.Hashtable; import java.util.List; import java.util.Map; import javax.swing.BorderFactory; import javax.swing.ButtonGroup; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JLayeredPane; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JSeparator; import javax.swing.JToggleButton; import javax.swing.SwingUtilities; import javax.swing.border.BevelBorder; import javax.swing.event.PopupMenuEvent; import javax.swing.event.PopupMenuListener; public class LiveModel extends Model { private static final long serialVersionUID = 1L; public static class SelectionChanged { } public static class OutputChanged { } public static class StateChanged { } public static class ButtonToolBindingChanged { public final int button; public final int tool; public ButtonToolBindingChanged(int button, int tool) { this.button = button; this.tool = tool; } } public static final int STATE_USE = 0; public static final int STATE_EDIT = 1; public static final int STATE_PLOT = 2; public static final int STATE_BIND = 3; public static final int STATE_DRAG = 4; public static final int STATE_CONS = 5; private int tool; private Model content; private Model selection; private Model output; private Hashtable<Integer, Integer> buttonToToolMap = new Hashtable<Integer, Integer>(); // private Hashtable<Integer, Integer> toolToButtonMap = new Hashtable<Integer, Integer>(); public LiveModel(Model content) { this.content = content; } @Override public Model modelCloneIsolated() { LiveModel clone = new LiveModel(content.cloneIsolated()); clone.tool = tool; clone.selection = this.selection.cloneIsolated(); return clone; } public void setSelection(Model selection, PropogationContext propCtx, int propDistance, PrevaylerServiceBranch<Model> branch) { this.selection = selection; sendChanged(new SelectionChanged(), propCtx, propDistance, 0, branch); } public void setOutput(Model output, PropogationContext propCtx, int propDistance, PrevaylerServiceBranch<Model> branch) { this.output = output; sendChanged(new OutputChanged(), propCtx, propDistance, 0, branch); } public int getTool() { return tool; } public void setTool(int tool, PropogationContext propCtx, int propDistance, PrevaylerServiceBranch<Model> branch) { this.tool = tool; sendChanged(new StateChanged(), propCtx, propDistance, 0, branch); } public int getToolForButton(int button) { Integer tool = buttonToToolMap.get(button); return tool != null ? tool : -1; } public int getButtonForTool(int tool) { for(Map.Entry<Integer, Integer> entry: buttonToToolMap.entrySet()) { if(entry.getValue() == tool) return entry.getKey(); } return -1; // Integer button = toolToButtonMap.get(tool); // return button != null ? button : -1; } // public int[] getButtonsForTool(int tool) { // ArrayList<Integer> toolButtons = toolToButtonsMap.get(tool); // if(toolButtons == null) // return new int[0]; // int[] toolButtonsArray = new int[toolButtons.size()]; // for(int i = 0; i < toolButtons.size(); i++) // toolButtonsArray[i] = toolButtons.get(i); // return toolButtonsArray; public void removeButtonToToolBinding(int button, int tool, PropogationContext propCtx, int propDistance, PrevaylerServiceBranch<Model> branch) { buttonToToolMap.remove(button); System.out.println("Removed binding from button " + button + " and tool " + tool); System.out.println("buttonToToolMap: " + buttonToToolMap); sendChanged(new ButtonToolBindingChanged(-1, tool), propCtx, propDistance, 0, branch); } public void bindButtonToTool(int button, int tool, PropogationContext propCtx, int propDistance, PrevaylerServiceBranch<Model> branch) { // ArrayList<Integer> toolButtons = toolToButtonsMap.get(button); // if(toolButtons == null) { // toolButtons = new ArrayList<Integer>(); // toolButtons.add(button); // Integer currentToolForButton = buttonToToolMap.get(button); // if(currentToolForButton != null) { // ArrayList<Integer> currentToolButtons = toolToButtonsMap.get(tool); // currentToolButtons.remove((Integer)button); buttonToToolMap.put(button, tool); System.out.println("Bound button " + button + " to tool " + tool); System.out.println("buttonToToolMap: " + buttonToToolMap); // toolToButtonMap.put(tool, button); sendChanged(new ButtonToolBindingChanged(button, tool), propCtx, propDistance, 0, branch); } public static class BindButtonToToolCommand implements Command<Model> { private static final long serialVersionUID = 1L; private Location modelLocation; private int button; private int tool; public BindButtonToToolCommand(Location modelLocation, int button, int tool) { this.modelLocation = modelLocation; this.button = button; this.tool = tool; } @Override public void executeOn(PropogationContext propCtx, Model prevalentSystem, Date executionTime, PrevaylerServiceBranch<Model> branch) { LiveModel liveModel = (LiveModel)modelLocation.getChild(prevalentSystem); liveModel.bindButtonToTool(button, tool, propCtx, 0, branch); } } public static class RemoveButtonToToolBindingCommand implements Command<Model> { private static final long serialVersionUID = 1L; private Location modelLocation; private int button; private int tool; public RemoveButtonToToolBindingCommand(Location modelLocation, int button, int tool) { this.modelLocation = modelLocation; this.button = button; this.tool = tool; } @Override public void executeOn(PropogationContext propCtx, Model prevalentSystem, Date executionTime, PrevaylerServiceBranch<Model> branch) { LiveModel liveModel = (LiveModel)modelLocation.getChild(prevalentSystem); liveModel.removeButtonToToolBinding(button, tool, propCtx, 0, branch); } } public static class SetSelection implements Command<Model> { private static final long serialVersionUID = 1L; private Location liveModelLocation; private Location modelLocation; public SetSelection(Location liveModelLocation, Location modelLocation) { this.liveModelLocation = liveModelLocation; this.modelLocation = modelLocation; } @Override public void executeOn(PropogationContext propCtx, Model prevalentSystem, Date executionTime, PrevaylerServiceBranch<Model> branch) { // System.out.println("SetSelection"); LiveModel liveModel = (LiveModel)liveModelLocation.getChild(prevalentSystem); if(modelLocation != null) { Model selection = (Model)modelLocation.getChild(prevalentSystem); liveModel.setSelection(selection, new PropogationContext(), 0, branch); } else { liveModel.setSelection(null, new PropogationContext(), 0, branch); } } } public static class SetOutput implements Command<Model> { private static final long serialVersionUID = 1L; private Location liveModelLocation; private Location modelLocation; public SetOutput(Location liveModelLocation, Location modelLocation) { this.liveModelLocation = liveModelLocation; this.modelLocation = modelLocation; } @Override public void executeOn(PropogationContext propCtx, Model prevalentSystem, Date executionTime, PrevaylerServiceBranch<Model> branch) { LiveModel liveModel = (LiveModel)liveModelLocation.getChild(prevalentSystem); if(modelLocation != null) { Model selection = (Model)modelLocation.getChild(prevalentSystem); liveModel.setOutput(selection, new PropogationContext(), 0, branch); } else { liveModel.setOutput(null, new PropogationContext(), 0, branch); } } public static DualCommand<Model> createDual(LiveModel.LivePanel livePanel, Location outputLocation) { Location currentOutputLocation = null; if(livePanel.productionPanel.editPanelMouseAdapter.output != null) currentOutputLocation = livePanel.productionPanel.editPanelMouseAdapter.output.getTransactionFactory().getModelLocation(); return new DualCommandPair<Model>( new SetOutput(livePanel.getTransactionFactory().getModelLocation(), outputLocation), new SetOutput(livePanel.getTransactionFactory().getModelLocation(), currentOutputLocation) ); } } public static class SetTool implements Command<Model> { private static final long serialVersionUID = 1L; private Location modelLocation; private int tool; public SetTool(Location modelLocation, int tool) { this.modelLocation = modelLocation; this.tool = tool; } @Override public void executeOn(PropogationContext propCtx, Model prevalentSystem, Date executionTime, PrevaylerServiceBranch<Model> branch) { LiveModel model = (LiveModel)modelLocation.getChild(prevalentSystem); model.setTool(tool, propCtx, 0, branch); } } public static class ContentLocator implements dynamake.ModelLocator { @Override public ModelLocation locate() { return new FieldContentLocation(); } } private static class FieldContentLocation implements ModelLocation { private static final long serialVersionUID = 1L; @Override public Object getChild(Object holder) { return ((LiveModel)holder).content; } @Override public void setChild(Object holder, Object child) { ((LiveModel)holder).content = (Model)child; } @Override public Location getModelComponentLocation() { // TODO Auto-generated method stub return new ViewFieldContentLocation(); } } private static class ViewFieldContentLocation implements Location { @Override public Object getChild(Object holder) { return ((LivePanel)holder).contentView.getBindingTarget(); } @Override public void setChild(Object holder, Object child) { // TODO Auto-generated method stub } } private static final int BUTTON_FONT_SIZE = 13; private static final Color TOP_BACKGROUND_COLOR = Color.GRAY; private static final Color TOP_FOREGROUND_COLOR = Color.WHITE; public static final int TAG_CAUSED_BY_UNDO = 0; public static final int TAG_CAUSED_BY_REDO = 1; public static final int TAG_CAUSED_BY_TOGGLE_BUTTON = 2; public static final int TAG_CAUSED_BY_ROLLBACK = 3; public static final int TAG_CAUSED_BY_COMMIT = 4; private static class ToolButton extends JPanel { private static final long serialVersionUID = 1L; private int tool; private int button; private String text; private LiveModel liveModel; private TransactionFactory transactionFactory; private JLabel labelToolName; private JLabel labelButton; public ToolButton(int tool, int button, String text, LiveModel liveModel, TransactionFactory transactionFactory) { this.tool = tool; this.button = button; this.text = text; this.liveModel = liveModel; this.transactionFactory = transactionFactory; /* buttonTool.setBackground(TOP_BACKGROUND_COLOR); buttonTool.setForeground(TOP_FOREGROUND_COLOR); */ setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 5)); setLayout(new BorderLayout()); setBackground(TOP_BACKGROUND_COLOR); labelToolName = new JLabel(); labelToolName.setAlignmentY(JLabel.CENTER_ALIGNMENT); labelToolName.setForeground(TOP_FOREGROUND_COLOR); labelToolName.setFont(new Font(labelToolName.getFont().getFontName(), Font.BOLD, BUTTON_FONT_SIZE)); add(labelToolName, BorderLayout.CENTER); labelButton = new JLabel(); add(labelButton, BorderLayout.EAST); labelButton.setFont(new Font(labelButton.getFont().getFontName(), Font.ITALIC | Font.BOLD, 18)); labelButton.setAlignmentY(JLabel.CENTER_ALIGNMENT); this.setPreferredSize(new Dimension(60, 25)); update(); this.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { // System.out.println("Mouse button:" + e.getButton()); final int newButton = e.getButton(); PropogationContext propCtx = new PropogationContext(TAG_CAUSED_BY_TOGGLE_BUTTON); PrevaylerServiceBranch<Model> branch = ToolButton.this.transactionFactory.createBranch(); branch.execute(propCtx, new DualCommandFactory<Model>() { @Override public void createDualCommands(List<DualCommand<Model>> dualCommands) { setBackground(TOP_BACKGROUND_COLOR.brighter()); int currentButton = ToolButton.this.button; Location modelLocation = ToolButton.this.transactionFactory.getModelLocation(); int previousToolForNewButton = ToolButton.this.liveModel.getToolForButton(newButton); if(previousToolForNewButton != -1) { // If the new button is associated to another tool, then remove that binding dualCommands.add(new DualCommandPair<Model>( new RemoveButtonToToolBindingCommand(modelLocation, newButton, previousToolForNewButton), new BindButtonToToolCommand(modelLocation, newButton, previousToolForNewButton)) ); } if(currentButton != -1) { // If this tool is associated to button, then remove that binding before dualCommands.add(new DualCommandPair<Model>( new RemoveButtonToToolBindingCommand(modelLocation, currentButton, ToolButton.this.tool), new BindButtonToToolCommand(modelLocation, currentButton, ToolButton.this.tool)) ); // adding the replacement binding dualCommands.add(new DualCommandPair<Model>( new BindButtonToToolCommand(modelLocation, newButton, ToolButton.this.tool), new RemoveButtonToToolBindingCommand(modelLocation, newButton, ToolButton.this.tool)) ); } else { dualCommands.add(new DualCommandPair<Model>( new BindButtonToToolCommand(modelLocation, newButton, ToolButton.this.tool), new RemoveButtonToToolBindingCommand(modelLocation, newButton, ToolButton.this.tool) )); } } }); branch.close(); } @Override public void mouseReleased(MouseEvent e) { setBackground(TOP_BACKGROUND_COLOR); } }); } private static final Color[] BUTTON_COLORS = new Color[] { new Color(220, 10, 10),//Color.RED, new Color(10, 220, 10), //Color.GREEN, new Color(10, 10, 220), //Color.BLUE, new Color(10, 220, 220), //Color.CYAN, new Color(220, 220, 10), //Color.ORANGE new Color(220, 10, 220), }; public Color getColorForButton(int button) { return BUTTON_COLORS[button - 1]; } private void update() { labelToolName.setText(text); if(button != -1) { labelButton.setText("" + button); // label.setText(text + "(" + button + ")"); labelButton.setForeground(getColorForButton(button)); } else { labelButton.setText(""); labelButton.setForeground(null); } } public void setButton(int button) { this.button = button; update(); } } private static JComponent createToolButton(final LiveModel model, final TransactionFactory transactionFactory, ButtonGroup group, int button, int currentTool, final int tool, final String text) { final ToolButton buttonTool = new ToolButton(tool, button, text, model, transactionFactory); // buttonTool.setBackground(TOP_BACKGROUND_COLOR); // buttonTool.setForeground(TOP_FOREGROUND_COLOR); // buttonTool.setBorderPainted(false); /* Somehow, when clicking on a button, the mouse button which was used to click on the button should be associated to the particular tool the clicked button represent. This means that, then a mouse button is used to click on the production panel, then tool, associated to the button, should be looked up and used. If the button is already associated to a tool, this associated is removed. */ // buttonTool.addMouseListener(new MouseAdapter() { // @Override // public void mouseClicked(MouseEvent e) { // System.out.println("Mouse button:" + e.getButton()); // buttonTool.addMouseListener(new MouseAdapter() { // @Override // public void mousePressed(MouseEvent e) { //// System.out.println("Mouse button:" + e.getButton()); // final int newButton = e.getButton(); // PropogationContext propCtx = new PropogationContext(TAG_CAUSED_BY_TOGGLE_BUTTON); // PrevaylerServiceBranch<Model> branch = transactionFactory.createBranch(); // branch.execute(propCtx, new DualCommandFactory<Model>() { // @Override // public void createDualCommands(List<DualCommand<Model>> dualCommands) { // int currentButton = buttonTool.button; // Location modelLocation = transactionFactory.getModelLocation(); // int previousToolForNewButton = model.getToolForButton(newButton); // if(previousToolForNewButton != -1) { // // If the new button is associated to another tool, then remove that binding // dualCommands.add(new DualCommandPair<Model>( // new RemoveButtonToToolBindingCommand(modelLocation, newButton, previousToolForNewButton), // new BindButtonToToolCommand(modelLocation, newButton, previousToolForNewButton)) // if(currentButton != -1) { // // If this tool is associated to button, then remove that binding before // dualCommands.add(new DualCommandPair<Model>( // new RemoveButtonToToolBindingCommand(modelLocation, currentButton, tool), // new BindButtonToToolCommand(modelLocation, currentButton, tool)) // // adding the replacement binding // dualCommands.add(new DualCommandPair<Model>( // new BindButtonToToolCommand(modelLocation, newButton, tool), // new RemoveButtonToToolBindingCommand(modelLocation, newButton, tool)) // } else { // dualCommands.add(new DualCommandPair<Model>( // new BindButtonToToolCommand(modelLocation, newButton, tool), // new RemoveButtonToToolBindingCommand(modelLocation, newButton, tool) // branch.close(); // buttonTool.addActionListener(new ActionListener() { // @Override // public void actionPerformed(ActionEvent arg0) { // System.out.println("Change tool to " + text); // // Indicate this is an radio button toggle context // PropogationContext propCtx = new PropogationContext(TAG_CAUSED_BY_TOGGLE_BUTTON); // PrevaylerServiceBranch<Model> branch = transactionFactory.createBranch(); // branch.execute(propCtx, new DualCommandFactory<Model>() { // @Override // public void createDualCommands(List<DualCommand<Model>> dualCommands) { // Location modelLocation = transactionFactory.getModelLocation(); // int previousTool = model.getTool(); // dualCommands.add( // new DualCommandPair<Model>(new SetTool(modelLocation, tool), new SetTool(modelLocation, previousTool)) // branch.close(); buttonTool.setFocusable(false); // group.add(buttonTool); // if(currentTool == tool) { // buttonTool.setSelected(true); return buttonTool; } private static void updateToolButton(JComponent toolButton, int button) { ((ToolButton)toolButton).setButton(button); } public static class ProductionPanel extends JPanel { private static final long serialVersionUID = 1L; // Temporary frames private JPanel effectFrame; public JPanel targetFrame; // Persistent frames public JPanel selectionFrame; public JPanel outputFrame; public Binding<Component> selectionBoundsBinding; public static final Color TARGET_OVER_COLOR = new Color(35, 89, 184); public static final Color BIND_COLOR = new Color(25, 209, 89); public static final Color UNBIND_COLOR = new Color(240, 34, 54); public static final Color SELECTION_COLOR = Color.GRAY; public static final Color OUTPUT_COLOR = new Color(54, 240, 17); public static class EditPanelMouseAdapter extends MouseAdapter { public ProductionPanel productionPanel; public ModelComponent selection; public Point selectionMouseDown; public Rectangle initialEffectBounds; public Dimension selectionFrameSize; public int selectionFrameHorizontalPosition; public int selectionFrameVerticalPosition; public ModelComponent targetOver; public ModelComponent output; protected int buttonPressed; public static final int HORIZONTAL_REGION_WEST = 0; public static final int HORIZONTAL_REGION_CENTER = 1; public static final int HORIZONTAL_REGION_EAST = 2; public static final int VERTICAL_REGION_NORTH = 0; public static final int VERTICAL_REGION_CENTER = 1; public static final int VERTICAL_REGION_SOUTH = 2; public EditPanelMouseAdapter(ProductionPanel productionPanel) { this.productionPanel = productionPanel; } private Tool getTool(int button) { int toolForButton = productionPanel.livePanel.model.getToolForButton(button); if(toolForButton != -1) { // return productionPanel.livePanel.viewManager.getTools()[productionPanel.livePanel.model.tool - 1]; return productionPanel.livePanel.viewManager.getTools()[toolForButton - 1]; } else { return new Tool() { @Override public void mouseReleased(ProductionPanel productionPanel, MouseEvent e) { } @Override public void mousePressed(ProductionPanel productionPanel, MouseEvent e) { } @Override public void mouseMoved(ProductionPanel productionPanel, MouseEvent e) { } @Override public void mouseExited(ProductionPanel productionPanel, MouseEvent e) { } @Override public void mouseDragged(ProductionPanel productionPanel, MouseEvent e) { } @Override public String getName() { return null; } }; } } public void createEffectFrame(Rectangle creationBounds, Point initialMouseDown) { if(productionPanel.effectFrame == null) { final JPanel localEffectFrame = new JPanel(); localEffectFrame.setBackground(new Color(0, 0, 0, 0)); localEffectFrame.setBounds(creationBounds); localEffectFrame.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createDashedBorder(Color.BLACK, 2.0f, 2.0f, 1.5f, false), BorderFactory.createDashedBorder(Color.WHITE, 2.0f, 2.0f, 1.5f, false) )); productionPanel.effectFrame = localEffectFrame; selectionMouseDown = initialMouseDown; initialEffectBounds = creationBounds; // Ensure effect frame is shown in front of selection frame if(productionPanel.selectionFrame != null) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { productionPanel.remove(productionPanel.selectionFrame); productionPanel.add(localEffectFrame); productionPanel.add(productionPanel.selectionFrame); } }); } else { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { productionPanel.add(localEffectFrame); } }); } } else { System.out.println("Attempted to created an effect frame when it has already been created."); } } public void changeEffectFrame(final Rectangle newBounds) { if(productionPanel.effectFrame != null) { final JPanel localEffectFrame = productionPanel.effectFrame; SwingUtilities.invokeLater(new Runnable() { @Override public void run() { localEffectFrame.setBounds(newBounds); } }); } else { System.out.println("Attempted to change effect frame when it hasn't been created."); } } public void clearEffectFrame() { if(productionPanel.effectFrame != null) { final JPanel localEffectFrame = productionPanel.effectFrame; productionPanel.effectFrame = null; selectionMouseDown = null; initialEffectBounds = null; SwingUtilities.invokeLater(new Runnable() { @Override public void run() { productionPanel.remove(localEffectFrame); } }); } else { System.out.println("Attempted to clear effect frame when it hasn't been created."); } } public int getEffectFrameX() { return productionPanel.effectFrame.getX(); } public int getEffectFrameY() { return productionPanel.effectFrame.getY(); } public int getEffectFrameWidth() { return productionPanel.effectFrame.getWidth(); } public int getEffectFrameHeight() { return productionPanel.effectFrame.getHeight(); } public Rectangle getEffectFrameBounds() { return productionPanel.effectFrame.getBounds(); } public void setEffectFrameCursor(final Cursor cursor) { final JPanel localEffectFrame = productionPanel.effectFrame; SwingUtilities.invokeLater(new Runnable() { @Override public void run() { localEffectFrame.setCursor(cursor); } }); } public void updateRelativeCursorPosition(Point point, Dimension size) { int resizeWidth = 5; int leftPositionEnd = resizeWidth; int rightPositionStart = size.width - resizeWidth; int topPositionEnd = resizeWidth; int bottomPositionStart = size.height - resizeWidth; selectionFrameHorizontalPosition = 1; selectionFrameVerticalPosition = 1; if(point.x <= leftPositionEnd) selectionFrameHorizontalPosition = HORIZONTAL_REGION_WEST; else if(point.x < rightPositionStart) selectionFrameHorizontalPosition = HORIZONTAL_REGION_CENTER; else selectionFrameHorizontalPosition = HORIZONTAL_REGION_EAST; if(point.y <= topPositionEnd) selectionFrameVerticalPosition = VERTICAL_REGION_NORTH; else if(point.y < bottomPositionStart) selectionFrameVerticalPosition = VERTICAL_REGION_CENTER; else selectionFrameVerticalPosition = VERTICAL_REGION_SOUTH; } public Cursor getCursorFromRelativePosition() { return getCursorFromRelativePosition(selectionFrameHorizontalPosition, selectionFrameVerticalPosition); } public static Cursor getCursorFromRelativePosition(int horizontalPosition, int verticalPosition) { final Cursor cursor; switch(horizontalPosition) { case ProductionPanel.EditPanelMouseAdapter.HORIZONTAL_REGION_WEST: switch(verticalPosition) { case ProductionPanel.EditPanelMouseAdapter.VERTICAL_REGION_NORTH: cursor = Cursor.getPredefinedCursor(Cursor.NW_RESIZE_CURSOR); break; case ProductionPanel.EditPanelMouseAdapter.VERTICAL_REGION_CENTER: cursor = Cursor.getPredefinedCursor(Cursor.W_RESIZE_CURSOR); break; case ProductionPanel.EditPanelMouseAdapter.VERTICAL_REGION_SOUTH: cursor = Cursor.getPredefinedCursor(Cursor.SW_RESIZE_CURSOR); break; default: cursor = null; break; } break; case ProductionPanel.EditPanelMouseAdapter.HORIZONTAL_REGION_CENTER: switch(verticalPosition) { case ProductionPanel.EditPanelMouseAdapter.VERTICAL_REGION_NORTH: cursor = Cursor.getPredefinedCursor(Cursor.N_RESIZE_CURSOR); break; case ProductionPanel.EditPanelMouseAdapter.VERTICAL_REGION_SOUTH: cursor = Cursor.getPredefinedCursor(Cursor.S_RESIZE_CURSOR); break; default: cursor = null; break; } break; case ProductionPanel.EditPanelMouseAdapter.HORIZONTAL_REGION_EAST: switch(verticalPosition) { case ProductionPanel.EditPanelMouseAdapter.VERTICAL_REGION_NORTH: cursor = Cursor.getPredefinedCursor(Cursor.NE_RESIZE_CURSOR); break; case ProductionPanel.EditPanelMouseAdapter.VERTICAL_REGION_CENTER: cursor = Cursor.getPredefinedCursor(Cursor.E_RESIZE_CURSOR); break; case ProductionPanel.EditPanelMouseAdapter.VERTICAL_REGION_SOUTH: cursor = Cursor.getPredefinedCursor(Cursor.SE_RESIZE_CURSOR); break; default: cursor = null; break; } break; default: cursor = null; break; } return cursor; } public void selectFromView(final ModelComponent view, final Point initialMouseDown, PrevaylerServiceBranch<Model> branch) { Rectangle effectBounds = SwingUtilities.convertRectangle(((JComponent)view).getParent(), ((JComponent)view).getBounds(), productionPanel); requestSelect(view, effectBounds, branch); createEffectFrame(effectBounds, initialMouseDown); } public void selectFromDefault(final ModelComponent view, final Point initialMouseDown, PrevaylerServiceBranch<Model> branch) { Dimension sourceBoundsSize = new Dimension(125, 33); Point sourceBoundsLocation = new Point(initialMouseDown.x - sourceBoundsSize.width / 2, initialMouseDown.y - sourceBoundsSize.height / 2); Rectangle sourceBounds = new Rectangle(sourceBoundsLocation, sourceBoundsSize); Rectangle selectionBounds = SwingUtilities.convertRectangle((JComponent)view, sourceBounds, productionPanel); requestSelect(view, selectionBounds, branch); createEffectFrame(selectionBounds, initialMouseDown); } public void selectFromEmpty(final ModelComponent view, final Point initialMouseDown, PrevaylerServiceBranch<Model> branch) { requestSelect(view, new Rectangle(0, 0, 0, 0), branch); createEffectFrame(new Rectangle(0, 0, 0, 0), initialMouseDown); } private void requestSelect(final ModelComponent view, final Rectangle effectBounds, PrevaylerServiceBranch<Model> branch) { // Notice: executes a transaction PropogationContext propCtx = new PropogationContext(); branch.execute(propCtx, new DualCommandFactory<Model>() { @Override public void createDualCommands(List<DualCommand<Model>> dualCommands) { createSelectCommands(view, dualCommands); } }); } public void createSelectCommands(final ModelComponent view, List<DualCommand<Model>> dualCommands) { Location selectionLocation = view != null ? view.getTransactionFactory().getModelLocation() : null; createSelectCommandsFromLocation(selectionLocation, dualCommands); } public void createSelectCommandsFromLocation(final Location selectionLocation, List<DualCommand<Model>> dualCommands) { final Location liveModelLocation = productionPanel.livePanel.getTransactionFactory().getModelLocation(); Location currentSelectionLocation = EditPanelMouseAdapter.this.selection != null ? EditPanelMouseAdapter.this.selection.getTransactionFactory().getModelLocation() : null; dualCommands.add(new DualCommandPair<Model>( new SetSelection(liveModelLocation, selectionLocation), new SetSelection(liveModelLocation, currentSelectionLocation) )); } private void select(final ModelComponent view) { // System.out.println("in select method"); // <Don't remove> // Whether the following check is necessary or not has not been decided yet, so don't remove the code // if(this.selection == view) // return; // </Don't remove> this.selection = view; if(productionPanel.selectionBoundsBinding != null) productionPanel.selectionBoundsBinding.releaseBinding(); if(this.selection != null) { if(productionPanel.selectionFrame == null) { productionPanel.selectionFrame = new JPanel(); productionPanel.selectionFrame.setBackground(new Color(0, 0, 0, 0)); productionPanel.selectionFrame.setBorder( BorderFactory.createCompoundBorder( BorderFactory.createLineBorder(Color.BLACK, 1), BorderFactory.createCompoundBorder( BorderFactory.createLineBorder(SELECTION_COLOR, 3), BorderFactory.createLineBorder(Color.BLACK, 1) ) ) ); MouseAdapter mouseAdapter = new MouseAdapter() { @Override public void mouseMoved(MouseEvent e) { // The tool associated to button 1 it used here getTool(1).mouseMoved(productionPanel, e); } public void mouseExited(MouseEvent e) { // The tool associated to button 1 it used here getTool(1).mouseExited(productionPanel, e); } @Override public void mousePressed(MouseEvent e) { productionPanel.editPanelMouseAdapter.buttonPressed = e.getButton(); getTool(productionPanel.editPanelMouseAdapter.buttonPressed).mousePressed(productionPanel, e); } @Override public void mouseDragged(MouseEvent e) { getTool(productionPanel.editPanelMouseAdapter.buttonPressed).mouseDragged(productionPanel, e); } @Override public void mouseReleased(MouseEvent e) { getTool(productionPanel.editPanelMouseAdapter.buttonPressed).mouseReleased(productionPanel, e); productionPanel.editPanelMouseAdapter.buttonPressed = -1; } }; productionPanel.selectionFrame.addMouseListener(mouseAdapter); productionPanel.selectionFrame.addMouseMotionListener(mouseAdapter); final JPanel selectionFrame = productionPanel.selectionFrame; if(productionPanel.effectFrame != null) System.out.println("Effect frame was there before selection was added"); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { productionPanel.add(selectionFrame); } }); } selectionFrameSize = ((JComponent)view).getSize(); final Rectangle selectionBounds = SwingUtilities.convertRectangle(((JComponent)view).getParent(), ((JComponent)view).getBounds(), productionPanel); final JPanel selectionFrame = productionPanel.selectionFrame; SwingUtilities.invokeLater(new Runnable() { @Override public void run() { selectionFrame.setBounds(selectionBounds); } }); productionPanel.selectionBoundsBinding = new Binding<Component>() { private Component component; private ComponentListener listener; { component = (JComponent)selection; listener = new ComponentListener() { @Override public void componentShown(ComponentEvent arg0) { } @Override public void componentResized(ComponentEvent arg0) { Rectangle selectionBounds = SwingUtilities.convertRectangle(((JComponent)view).getParent(), ((JComponent)view).getBounds(), productionPanel); productionPanel.selectionFrame.setBounds(selectionBounds); productionPanel.livePanel.repaint(); } @Override public void componentMoved(ComponentEvent arg0) { Rectangle selectionBounds = SwingUtilities.convertRectangle(((JComponent)view).getParent(), ((JComponent)view).getBounds(), productionPanel); productionPanel.selectionFrame.setBounds(selectionBounds); productionPanel.livePanel.repaint(); } @Override public void componentHidden(ComponentEvent arg0) { } }; ((JComponent)selection).addComponentListener(listener); } @Override public void releaseBinding() { component.removeComponentListener(listener); } @Override public Component getBindingTarget() { return component; } }; } else { if(productionPanel.selectionFrame != null) productionPanel.clearFocus(); } } public void showPopupForSelectionObject(final JComponent popupMenuInvoker, final Point pointOnInvoker, final ModelComponent targetOver, PrevaylerServiceBranch<Model> branch) { showPopupForSelection(popupMenuInvoker, pointOnInvoker, targetOver, new DragDragDropPopupBuilder(branch)); } public void showPopupForSelectionCons(final JComponent popupMenuInvoker, final Point pointOnInvoker, final ModelComponent targetOver, PrevaylerServiceBranch<Model> branch) { showPopupForSelection(popupMenuInvoker, pointOnInvoker, targetOver, new ConsDragDropPopupBuilder(branch)); } public void showPopupForSelectionTell(final JComponent popupMenuInvoker, final Point pointOnInvoker, final ModelComponent targetOver, PrevaylerServiceBranch<Model> branch) { showPopupForSelection(popupMenuInvoker, pointOnInvoker, targetOver, new TellDragDropPopupBuilder(branch)); } public void showPopupForSelectionView(final JComponent popupMenuInvoker, final Point pointOnInvoker, final ModelComponent targetOver, PrevaylerServiceBranch<Model> branch) { showPopupForSelection(popupMenuInvoker, pointOnInvoker, targetOver, new ViewDragDropPopupBuilder(branch)); } private void showPopupForSelection(final JComponent popupMenuInvoker, final Point pointOnInvoker, final ModelComponent targetOver, final DragDropPopupBuilder popupBuilder) { if(selection != null) { JPopupMenu transactionsPopupMenu = new JPopupMenu() { private static final long serialVersionUID = 1L; private boolean ignoreNextPaint; public void paint(java.awt.Graphics g) { super.paint(g); if(!ignoreNextPaint) { productionPanel.livePanel.repaint(); ignoreNextPaint = true; } else { ignoreNextPaint = false; } } }; Point pointOnTargetOver = SwingUtilities.convertPoint(popupMenuInvoker, pointOnInvoker, (JComponent)targetOver); Rectangle droppedBounds = SwingUtilities.convertRectangle(productionPanel, productionPanel.effectFrame.getBounds(), (JComponent)targetOver); popupBuilder.buildFromSelectionAndTarget(productionPanel.livePanel, transactionsPopupMenu, selection, targetOver, pointOnTargetOver, droppedBounds); transactionsPopupMenu.show(popupMenuInvoker, pointOnInvoker.x, pointOnInvoker.y); productionPanel.livePanel.repaint(); transactionsPopupMenu.addPopupMenuListener(new PopupMenuListener() { @Override public void popupMenuWillBecomeVisible(PopupMenuEvent arg0) { } @Override public void popupMenuWillBecomeInvisible(PopupMenuEvent arg0) { clearTarget(); productionPanel.livePanel.repaint(); } @Override public void popupMenuCanceled(PopupMenuEvent arg0) { popupBuilder.cancelPopup(productionPanel.livePanel); } }); } } public void clearTarget() { if(productionPanel.targetFrame != null) { final JPanel targetFrame = productionPanel.targetFrame; SwingUtilities.invokeLater(new Runnable() { @Override public void run() { productionPanel.remove(targetFrame); } }); productionPanel.targetFrame = null; } } public ModelComponent closestModelComponent(Component component) { while(component != null && !(component instanceof ModelComponent)) component = component.getParent(); return (ModelComponent)component; } public Rectangle getPlotBounds(Point firstPoint, Point secondPoint) { int left = Math.min(firstPoint.x, secondPoint.x); int right = Math.max(firstPoint.x, secondPoint.x); int top = Math.min(firstPoint.y, secondPoint.y); int bottom = Math.max(firstPoint.y, secondPoint.y); return new Rectangle(left, top, right - left, bottom - top); } public void mousePressed(final MouseEvent e) { /* For further implementations of tools, when branches are used in all tools: Create a branch here, through which executions are scheduled and flushed immediately, such that it is ensured that selections have been made before drag and release events. This branch is then provided to the respective tool. NOTICE: This requires that each tool must ensure selecting a model during each press event. - NOTICE FURTHER: In some cases, this guarantee may not make sense. */ final int button = e.getButton(); productionPanel.livePanel.getTransactionFactory().executeTransient(new Runnable() { @Override public void run() { productionPanel.editPanelMouseAdapter.buttonPressed = button; getTool(button).mousePressed(productionPanel, e); } }); } public void mouseDragged(final MouseEvent e) { productionPanel.livePanel.getTransactionFactory().executeTransient(new Runnable() { @Override public void run() { e.translatePoint(-productionPanel.selectionFrame.getX(), -productionPanel.selectionFrame.getY()); e.setSource(productionPanel.selectionFrame); for(MouseMotionListener l: productionPanel.selectionFrame.getMouseMotionListeners()) { l.mouseDragged(e); } } }); } public void mouseReleased(MouseEvent e) { if(productionPanel.selectionFrame != null) { e.translatePoint(-productionPanel.selectionFrame.getX(), -productionPanel.selectionFrame.getY()); e.setSource(productionPanel.selectionFrame); for(MouseListener l: productionPanel.selectionFrame.getMouseListeners()) { l.mouseReleased(e); } } } @Override public void mouseMoved(MouseEvent e) { // getTool().mouseMoved(productionPanel, e); } public void setOutput(ModelComponent view) { this.output = view; if(view != null) { if(productionPanel.outputFrame == null) { productionPanel.outputFrame = new JPanel(); productionPanel.outputFrame.setBackground(new Color(0, 0, 0, 0)); productionPanel.outputFrame.setBorder( BorderFactory.createBevelBorder( BevelBorder.RAISED, OUTPUT_COLOR.darker().darker(), OUTPUT_COLOR.darker(), OUTPUT_COLOR.darker().darker().darker(), OUTPUT_COLOR.darker().darker()) ); final JPanel outputFrame = productionPanel.outputFrame; SwingUtilities.invokeLater(new Runnable() { @Override public void run() { productionPanel.add(outputFrame); } }); } final Rectangle outputBounds = SwingUtilities.convertRectangle(((JComponent)view).getParent(), ((JComponent)view).getBounds(), productionPanel); final JPanel outputFrame = productionPanel.outputFrame; SwingUtilities.invokeLater(new Runnable() { @Override public void run() { outputFrame.setBounds(outputBounds); } }); } else { if(productionPanel.outputFrame != null) { final JPanel outputFrame = productionPanel.outputFrame; SwingUtilities.invokeLater(new Runnable() { @Override public void run() { productionPanel.remove(outputFrame); } }); productionPanel.outputFrame = null; } } } } public LivePanel livePanel; public Binding<ModelComponent> contentView; public EditPanelMouseAdapter editPanelMouseAdapter; public ProductionPanel(final LivePanel livePanel, final Binding<ModelComponent> contentView) { this.setLayout(null); this.livePanel = livePanel; this.contentView = contentView; // TODO: Consider the following: // For a selected frame, it should be possible to scroll upwards to select its immediate parent // - and scroll downwards to select its root parents editPanelMouseAdapter = new EditPanelMouseAdapter(this); this.addMouseListener(editPanelMouseAdapter); this.addMouseMotionListener(editPanelMouseAdapter); this.setOpaque(true); this.setBackground(new Color(0, 0, 0, 0)); } public void clearFocus() { if(selectionFrame != null) { if(selectionBoundsBinding != null) selectionBoundsBinding.releaseBinding(); this.remove(selectionFrame); selectionFrame = null; } } } public static class LivePanel extends JPanel implements ModelComponent { private static final long serialVersionUID = 1L; public LiveModel model; private JPanel topPanel; private JLayeredPane contentPane; private RemovableListener removableListener; public ProductionPanel productionPanel; public ViewManager viewManager; private TransactionFactory transactionFactory; private JComponent[] buttonTools; private final Binding<ModelComponent> contentView; private ModelComponent rootView; public LivePanel(final ModelComponent rootView, LiveModel model, TransactionFactory transactionFactory, final ViewManager viewManager) { this.rootView = rootView; this.setLayout(new BorderLayout()); this.model = model; this.viewManager = viewManager; this.transactionFactory = transactionFactory; ViewManager newViewManager = new ViewManager() { @Override public void setFocus(JComponent component) { } @Override public void unFocus(PropogationContext propCtx, ModelComponent view, PrevaylerServiceBranch<Model> branch) { if(productionPanel.editPanelMouseAdapter.selection == view) { productionPanel.editPanelMouseAdapter.requestSelect(null, null, branch); } } @Override public void selectAndActive(ModelComponent view, int x, int y) { } @Override public int getState() { return LivePanel.this.model.getTool(); } @Override public Factory[] getFactories() { return viewManager.getFactories(); } @Override public void clearFocus(PropogationContext propCtx) { productionPanel.clearFocus(); } @Override public void repaint(JComponent view) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { LivePanel.this.repaint(); } }); } @Override public void refresh(ModelComponent view) { LivePanel.this.repaint(); } @Override public void wasCreated(ModelComponent view) { } @Override public void becameVisible(ModelComponent view) { } @Override public void becameInvisible(PropogationContext propCtx, ModelComponent view) { } @Override public Tool[] getTools() { return null; } }; contentView = model.getContent().createView(rootView, newViewManager, transactionFactory.extend(new ContentLocator())); productionPanel = new ProductionPanel(this, contentView); topPanel = new JPanel(); topPanel.setBackground(TOP_BACKGROUND_COLOR); JButton undo = new JButton("Undo"); undo.setFont(new Font(undo.getFont().getFontName(), Font.BOLD, BUTTON_FONT_SIZE)); undo.setBackground(TOP_FOREGROUND_COLOR); undo.setForeground(TOP_BACKGROUND_COLOR); undo.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { PropogationContext propCtx = new PropogationContext(TAG_CAUSED_BY_UNDO); // Indicate this is an undo context getTransactionFactory().undo(propCtx); } }); undo.setFocusable(false); topPanel.add(undo); JButton redo = new JButton("Redo"); redo.setFont(new Font(redo.getFont().getFontName(), Font.BOLD, BUTTON_FONT_SIZE)); redo.setBackground(TOP_FOREGROUND_COLOR); redo.setForeground(TOP_BACKGROUND_COLOR); redo.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { PropogationContext propCtx = new PropogationContext(TAG_CAUSED_BY_REDO); // Indicate this is an redo context getTransactionFactory().redo(propCtx); } }); redo.setFocusable(false); topPanel.add(redo); topPanel.add(new JSeparator(JSeparator.VERTICAL)); topPanel.add(new JSeparator(JSeparator.VERTICAL)); // Tool[] tools = viewManager.getTools(); // buttonTools = new JComponent[1 + tools.length]; // ButtonGroup group = new ButtonGroup(); // buttonTools[0] = createToolButton(model, transactionFactory, group, -1, this.model.getTool(), STATE_USE, "Use"); // for(int i = 0; i < tools.length; i++) { // Tool tool = tools[i]; // int button = model.getButtonForTool(i); // buttonTools[i + 1] = createToolButton(model, transactionFactory, group, button, this.model.getTool(), i + 1, tool.getName()); // for(JComponent buttonTool: buttonTools) { // JPanel buttonToolWrapper = new JPanel(); // buttonToolWrapper.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY)); // buttonToolWrapper.setLayout(new BorderLayout()); // buttonToolWrapper.add(buttonTool, BorderLayout.CENTER); // topPanel.add(buttonToolWrapper); topPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK)); contentPane = new JLayeredPane(); productionPanel.setSize(contentPane.getSize().width, contentPane.getSize().height - 1); contentPane.addComponentListener(new ComponentListener() { @Override public void componentShown(ComponentEvent e) { } @Override public void componentResized(ComponentEvent e) { ((JComponent)contentView.getBindingTarget()).setSize(((JComponent)e.getSource()).getSize()); if(productionPanel != null) { productionPanel.setSize(((JComponent)e.getSource()).getSize().width, ((JComponent)e.getSource()).getSize().height - 1); } } @Override public void componentMoved(ComponentEvent e) { } @Override public void componentHidden(ComponentEvent e) { } }); contentPane.add((JComponent)contentView.getBindingTarget(), JLayeredPane.DEFAULT_LAYER); this.add(topPanel, BorderLayout.NORTH); this.add(contentPane, BorderLayout.CENTER); removableListener = Model.RemovableListener.addObserver(model, new ObserverAdapter() { int previousState; { initializeObserverAdapter(); } private void initializeObserverAdapter() { int state = LivePanel.this.model.getTool(); if(state != LiveModel.STATE_USE) { contentPane.add(productionPanel, JLayeredPane.MODAL_LAYER); contentPane.revalidate(); contentPane.repaint(); } previousState = state; } @Override public void changed(Model sender, Object change, final PropogationContext propCtx, int propDistance, int changeDistance, PrevaylerServiceBranch<Model> branch) { if(change instanceof LiveModel.ButtonToolBindingChanged) { LiveModel.ButtonToolBindingChanged bindButtonChanged = (LiveModel.ButtonToolBindingChanged)change; // if(!propCtx.isTagged(TAG_CAUSED_BY_TOGGLE_BUTTON)) { // JComponent buttonNewTool = buttonTools[bindButtonChanged.tool]; // updateToolButton(buttonNewTool, bindButtonChanged.button); //// buttonNewTool.setSelected(true); if(bindButtonChanged.tool != -1) { JComponent buttonNewTool = buttonTools[bindButtonChanged.tool]; updateToolButton(buttonNewTool, bindButtonChanged.button); } // if(previousState == LiveModel.STATE_USE && LivePanel.this.model.getTool() != LiveModel.STATE_USE) { // SwingUtilities.invokeLater(new Runnable() { // @Override // public void run() { // contentPane.add(productionPanel, JLayeredPane.MODAL_LAYER); // contentPane.revalidate(); // contentPane.repaint(); // } else if(previousState != LiveModel.STATE_USE && LivePanel.this.model.getTool() == LiveModel.STATE_USE) { // SwingUtilities.invokeLater(new Runnable() { // @Override // public void run() { // contentPane.remove(productionPanel); // contentPane.revalidate(); // contentPane.repaint(); // previousState = LivePanel.this.model.getTool(); } /*if(change instanceof LiveModel.StateChanged) { if(!propCtx.isTagged(TAG_CAUSED_BY_TOGGLE_BUTTON)) { JComponent buttonNewTool = buttonTools[LivePanel.this.model.getTool()]; // buttonNewTool.setSelected(true); } if(previousState == LiveModel.STATE_USE && LivePanel.this.model.getTool() != LiveModel.STATE_USE) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { contentPane.add(productionPanel, JLayeredPane.MODAL_LAYER); contentPane.revalidate(); contentPane.repaint(); } }); } else if(previousState != LiveModel.STATE_USE && LivePanel.this.model.getTool() == LiveModel.STATE_USE) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { contentPane.remove(productionPanel); contentPane.revalidate(); contentPane.repaint(); } }); } previousState = LivePanel.this.model.getTool(); }*/ else if(change instanceof LiveModel.OutputChanged) { if(LivePanel.this.model.output == null) { productionPanel.editPanelMouseAdapter.setOutput(null); } else { ModelLocator locator = LivePanel.this.model.output.getLocator(); ModelLocation modelLocation = locator.locate(); Location modelComponentLocation = modelLocation.getModelComponentLocation(); ModelComponent view = (ModelComponent)modelComponentLocation.getChild(rootView); productionPanel.editPanelMouseAdapter.setOutput(view); } SwingUtilities.invokeLater(new Runnable() { @Override public void run() { productionPanel.livePanel.repaint(); } }); } else if(change instanceof LiveModel.SelectionChanged) { if(LivePanel.this.model.selection != null) { // TODO: Consider whether this is a safe manner in which location of selection if derived. ModelLocator locator = LivePanel.this.model.selection.getLocator(); ModelLocation modelLocation = locator.locate(); Location modelComponentLocation = modelLocation.getModelComponentLocation(); final ModelComponent view = (ModelComponent)modelComponentLocation.getChild(rootView); productionPanel.editPanelMouseAdapter.select(view); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { productionPanel.livePanel.repaint(); } }); } else { productionPanel.editPanelMouseAdapter.select(null); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { productionPanel.livePanel.repaint(); } }); } } } }); contentPane.add(productionPanel, JLayeredPane.MODAL_LAYER); } @Override public void initialize() { Tool[] tools = viewManager.getTools(); buttonTools = new JComponent[1 + tools.length]; ButtonGroup group = new ButtonGroup(); buttonTools[0] = createToolButton(model, transactionFactory, group, -1, this.model.getTool(), STATE_USE, "Use"); for(int i = 0; i < tools.length; i++) { Tool tool = tools[i]; int button = model.getButtonForTool(i + 1); buttonTools[i + 1] = createToolButton(model, transactionFactory, group, button, this.model.getTool(), i + 1, tool.getName()); } for(JComponent buttonTool: buttonTools) { JPanel buttonToolWrapper = new JPanel(); buttonToolWrapper.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY)); buttonToolWrapper.setLayout(new BorderLayout()); buttonToolWrapper.add(buttonTool, BorderLayout.CENTER); topPanel.add(buttonToolWrapper); } if(LivePanel.this.model.selection != null) { ModelComponent selectionView = (ModelComponent)LivePanel.this.model.selection.getLocator().locate().getModelComponentLocation().getChild(rootView); LivePanel.this.productionPanel.editPanelMouseAdapter.select(selectionView); } if(LivePanel.this.model.output != null) { ModelComponent outputView = (ModelComponent)LivePanel.this.model.output.getLocator().locate().getModelComponentLocation().getChild(rootView); LivePanel.this.productionPanel.editPanelMouseAdapter.setOutput(outputView); } } public Factory[] getFactories() { return viewManager.getFactories(); } @Override public Model getModelBehind() { return model; } @Override public void appendContainerTransactions( LivePanel livePanel, TransactionMapBuilder transactions, ModelComponent child, PrevaylerServiceBranch<Model> branch) { // TODO Auto-generated method stub } @Override public void appendTransactions(ModelComponent livePanel, TransactionMapBuilder transactions, PrevaylerServiceBranch<Model> branch) { // TODO Auto-generated method stub } @Override public void appendDroppedTransactions(ModelComponent livePanel, ModelComponent target, Rectangle droppedBounds, TransactionMapBuilder transactions, PrevaylerServiceBranch<Model> branch) { Model.appendGeneralDroppedTransactions(livePanel, this, target, droppedBounds, transactions, branch); } @Override public void appendDropTargetTransactions(ModelComponent livePanel, ModelComponent dropped, Rectangle droppedBounds, Point dropPoint, TransactionMapBuilder transactions, PrevaylerServiceBranch<Model> branch) { // TODO Auto-generated method stub } @Override public TransactionFactory getTransactionFactory() { return transactionFactory; } public void releaseBinding() { removableListener.releaseBinding(); } @Override public DualCommandFactory<Model> getImplicitDropAction(ModelComponent target) { // TODO Auto-generated method stub return null; } @Override public void visitTree(Action1<ModelComponent> visitAction) { visitAction.run(this); } } @Override public Binding<ModelComponent> createView(ModelComponent rootView, ViewManager viewManager, TransactionFactory transactionFactory) { this.setLocation(transactionFactory.getModelLocator()); final LivePanel view = new LivePanel(rootView, this, transactionFactory, viewManager); viewManager.wasCreated(view); return new Binding<ModelComponent>() { @Override public void releaseBinding() { view.releaseBinding(); } @Override public ModelComponent getBindingTarget() { return view; } }; } public Model getContent() { return content; } public Model getOutput() { return output; } }
package com.humblepotato2.packagesigner; import java.awt.EventQueue; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import javax.swing.GroupLayout; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JProgressBar; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JToolBar; import javax.swing.KeyStroke; import javax.swing.LayoutStyle; import javax.swing.SwingConstants; import javax.swing.SwingWorker; import javax.swing.WindowConstants; import javax.swing.filechooser.FileNameExtensionFilter; import net.iharder.dnd.FileDrop; import org.apache.commons.io.FilenameUtils; public class PackageSigner extends JFrame { /** * Initialize variables. */ private DragAndDrop fileDrop; private GroupLayout layoutA, layoutMain; private ImageIcon icon; private JButton jButton1, jButton2, jButton3, jButton4, jButton5; private JFileChooser jFileChooser1, jFileChooser2; private JMenu jMenu1, jMenu2; private JMenuBar jMenuBar; private JMenuItem jMenuItem1, jMenuItem2, jMenuItem3, jMenuItem4, jMenuItem5, jMenuItem6; private JPanel jPanel; private JPopupMenu.Separator jSeparator; private JProgressBar jProgressBar; private JScrollPane jScrollPane; private JTextArea jTextArea; private JToolBar jToolBar; private KeyStroke keyStroke; private OutputSelection outputSelection; private PackageSelection packageSelection; private SignPackage signPackages; private String date, message; /** * Class constructor */ public PackageSigner() { initUI(); // #Initialize User Interface } /** * #Initialize User Interface */ private void initUI() { this.setTitle("Package Signer 2.2"); this.setResizable(false); this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); initComponents(); // #Initialize components this.setJMenuBar(jMenuBar); this.getContentPane().setLayout(layoutMain); this.pack(); } /** * #Initialize components */ private void initComponents() { initObjects(); // #Initialize objects configureSwingMenus(); // #Swing menus configuration configureToolbarActions(); // #Toolbar actions configuration configureTextBox(); // #Text box configuration assembleLayout(); // #Layout configuration } /** * #Initialize objects */ private void initObjects() { date = new SimpleDateFormat(" MM/dd/yyyy - ").format(new Date()); fileDrop = new DragAndDrop(); jButton1 = new JButton(); jButton2 = new JButton(); jButton3 = new JButton(); jButton4 = new JButton(); jButton5 = new JButton(); jFileChooser1 = new JFileChooser(); jFileChooser2 = new JFileChooser(); jMenu1 = new JMenu(); jMenu2 = new JMenu(); jMenuBar = new JMenuBar(); jMenuItem1 = new JMenuItem(); jMenuItem2 = new JMenuItem(); jMenuItem3 = new JMenuItem(); jMenuItem4 = new JMenuItem(); jMenuItem5 = new JMenuItem(); jMenuItem6 = new JMenuItem(); jPanel = new JPanel(); jProgressBar = new JProgressBar(); jScrollPane = new JScrollPane(); jSeparator = new JPopupMenu.Separator(); jTextArea = new JTextArea(); jToolBar = new JToolBar(); outputSelection = new OutputSelection(); packageSelection = new PackageSelection(); } /** * #Swing menus configuration */ private void configureSwingMenus() { /* JMenuItems */ // Package selection (jMenuItem1) jMenuItem1.setIcon(new ImageIcon(getClass().getResource("/drawable/ic_archive_18.png"))); jMenuItem1.setMnemonic('P'); jMenuItem1.setText("Package "); jMenuItem1.setToolTipText("Browse for new package(s)"); jMenuItem1.setAccelerator(keyStroke.getKeyStroke('P', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); jMenuItem1.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { packageSelection.choosePackages(); } }); // Output directory selection (jMenuItem2) jMenuItem2.setEnabled(false); jMenuItem2.setIcon(new ImageIcon(getClass().getResource("/drawable/ic_folder_18.png"))); jMenuItem2.setMnemonic('O'); jMenuItem2.setText("Output"); jMenuItem2.setToolTipText("Browse for an output directory"); jMenuItem2.setAccelerator(keyStroke.getKeyStroke('O', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); jMenuItem2.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { outputSelection.assignOutput(); } }); // Signing package (jMenuItem3) jMenuItem3.setEnabled(false); jMenuItem3.setIcon(new ImageIcon(getClass().getResource("/drawable/ic_sign_18.png"))); jMenuItem3.setMnemonic('S'); jMenuItem3.setText("Sign"); jMenuItem3.setToolTipText("Sign the package(s)"); jMenuItem3.setAccelerator(keyStroke.getKeyStroke('S', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); jMenuItem3.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JMenuItem source = (JMenuItem) e.getSource(); if (source == jMenuItem3) { jMenuItem3.setEnabled(false); jButton3.setEnabled(false); jButton4.setEnabled(true); } signPackages = new SignPackage(); signPackages.execute(); jProgressBar.setIndeterminate(true); } }); // Exit program (jMenuItem4) jMenuItem4.setMnemonic('X'); jMenuItem4.setText("Exit"); jMenuItem4.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.exit(0); } }); // Instructions dialog (jMenuItem5) jMenuItem5.setIcon(new ImageIcon(getClass().getResource("/drawable/ic_help_18.png"))); jMenuItem5.setMnemonic('I'); jMenuItem5.setText("?"); jMenuItem5.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { message = "Instructions\n"+ "1. Specify the Package(s) you want to sign.\n"+ "2. Choose an Output directory where to save it.\n"+ "3. Hit the Sign button to start signing it.\n\n"+ "Shortcut keys\n"+ "- Package selection > ⌘ or CTRL + P (for Windows/Linux/Mac)\n"+ "- Output selection > ⌘ or CTRL + O (for Windows/Linux/Mac)\n"+ "- Signing package > ⌘ or CTRL + S (for Windows/Linux/Mac)\n\n"+ "Drag & Drop\n"+ "Supports dragging and dropping of package(s) into the text box. \n\n"; icon = new ImageIcon(getClass().getResource("/drawable/ic_help_36.png")); JOptionPane.showMessageDialog(rootPane, message, "Help", JOptionPane.QUESTION_MESSAGE, icon); } }); // About dialog (jMenuItem6) jMenuItem6.setIcon(new ImageIcon(getClass().getResource("/drawable/ic_info_18.png"))); jMenuItem6.setMnemonic('A'); jMenuItem6.setText("About "); jMenuItem6.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { message = "Package Signer 2.2\n"+ "Created by Humble Potato II"; icon = new ImageIcon(getClass().getResource("/drawable/ic_info_36.png")); JOptionPane.showMessageDialog(rootPane, message, "About", JOptionPane.INFORMATION_MESSAGE, icon); } }); /* Add JMenuItems to JMenus */ // File (jMenu1) jMenu1.setText("File"); jMenu1.add(jMenuItem1); // - Package jMenu1.add(jMenuItem2); // - Output jMenu1.add(jMenuItem3); // - Sign jMenu1.add(jSeparator); jMenu1.add(jMenuItem4); // - Exit // Help (jMenu2) jMenu2.setText("Help"); jMenu2.add(jMenuItem5); // - Instructions jMenu2.add(jMenuItem6); // - About /* Add JMenus to JMenuBar */ // JMenuBar (jMenu1 + jMenu2) jMenuBar.add(jMenu1); // File jMenuBar.add(jMenu2); // Help } /** * #Toolbar actions configuration */ private void configureToolbarActions() { /* JButtons */ // Package selection (jButton1) jButton1.setIcon(new ImageIcon(getClass().getResource("/drawable/ic_archive_36.png"))); jButton1.setToolTipText("Browse for new package(s)"); jButton1.setFocusable(false); jButton1.setHorizontalTextPosition(SwingConstants.CENTER); jButton1.setVerticalTextPosition(SwingConstants.BOTTOM); jButton1.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { packageSelection.choosePackages(); } }); // Output directory selection (jButton2) jButton2.setEnabled(false); jButton2.setIcon(new ImageIcon(getClass().getResource("/drawable/ic_folder_36.png"))); jButton2.setToolTipText("Browse for an output directory"); jButton2.setFocusable(false); jButton2.setHorizontalTextPosition(SwingConstants.CENTER); jButton2.setVerticalTextPosition(SwingConstants.BOTTOM); jButton2.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { outputSelection.assignOutput(); } }); // Signing package (jButton3) jButton3.setEnabled(false); jButton3.setIcon(new ImageIcon(getClass().getResource("/drawable/ic_sign_36.png"))); jButton3.setToolTipText("Sign the package(s)"); jButton3.setFocusable(false); jButton3.setHorizontalTextPosition(SwingConstants.CENTER); jButton3.setVerticalTextPosition(SwingConstants.BOTTOM); jButton3.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JButton source = (JButton) e.getSource(); if (source == jButton3) { jMenuItem3.setEnabled(false); jButton3.setEnabled(false); jButton4.setEnabled(true); } signPackages = new SignPackage(); signPackages.execute(); jProgressBar.setIndeterminate(true); } }); // Cancel sign process (jButton4) jButton4.setEnabled(false); jButton4.setIcon(new ImageIcon(getClass().getResource("/drawable/ic_cancel_36.png"))); jButton4.setToolTipText("Cancel signing process"); jButton4.setFocusable(false); jButton4.setHorizontalTextPosition(SwingConstants.CENTER); jButton4.setVerticalTextPosition(SwingConstants.BOTTOM); jButton4.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { signPackages.cancel(true); signPackages.done(); } }); // Clear log message (jButton5) jButton5.setIcon(new ImageIcon(getClass().getResource("/drawable/ic_clear_36.png"))); jButton5.setToolTipText("Clear log message"); jButton5.setFocusable(false); jButton5.setHorizontalTextPosition(SwingConstants.CENTER); jButton5.setVerticalTextPosition(SwingConstants.BOTTOM); jButton5.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { jTextArea.setText(null); } }); /* Add JButtons to JToolBar */ jToolBar.setFloatable(false); jToolBar.setRollover(true); jToolBar.add(jButton1); // Package selection jToolBar.add(jButton2); // Output directory selection jToolBar.add(jButton3); // Signing package jToolBar.add(jButton4); // Cancel sign process jToolBar.add(jButton5); // Clear log message } /** * #Text box configuration */ private void configureTextBox() { /* JTextArea & JScrollPane */ jTextArea.setEditable(false); jTextArea.setText(date + "Package Signer version 2.2 \n"); jScrollPane.setViewportView(jTextArea); fileDrop.dropPackages(); // Drag and drop packages into text box. } /** * #Layout configuration */ private void assembleLayout() { /* Group JProgressBar and JScrollPane to layoutA */ layoutA = new GroupLayout(jPanel); layoutA.setHorizontalGroup( layoutA.createParallelGroup(GroupLayout.Alignment.LEADING) .addComponent(jProgressBar, GroupLayout.DEFAULT_SIZE, 475, Short.MAX_VALUE) .addComponent(jScrollPane, GroupLayout.Alignment.TRAILING) ); layoutA.setVerticalGroup( layoutA.createParallelGroup(GroupLayout.Alignment.LEADING) .addGroup(layoutA.createSequentialGroup() .addComponent(jScrollPane, GroupLayout.PREFERRED_SIZE, 300, GroupLayout.PREFERRED_SIZE) .addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jProgressBar, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel.setLayout(layoutA); // Set layoutA as jPanel's layout. /* Group JToolBar and JPanel to layoutMain */ layoutMain = new GroupLayout(this.getContentPane()); layoutMain.setHorizontalGroup( layoutMain.createParallelGroup(GroupLayout.Alignment.LEADING) .addComponent(jToolBar, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layoutMain.createSequentialGroup() .addContainerGap() .addComponent(jPanel, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); layoutMain.setVerticalGroup( layoutMain.createParallelGroup(GroupLayout.Alignment.LEADING) .addGroup(layoutMain.createSequentialGroup() .addComponent(jToolBar, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jPanel, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)) ); } /** * Main method */ public static void main(String[] args) { /* Create and display the program */ EventQueue.invokeLater(new Runnable() { @Override public void run() { new PackageSigner().setVisible(true); } }); } /** * FileDrop (A library used to support drag and drop function) * * Since the Package selection uses only the jFileChooser1 * to store the selected files, then we need to pass or set * the dropped packages to jFileChooser1. */ private class DragAndDrop { protected void dropPackages() { new FileDrop(null, jTextArea, new FileDrop.Listener() { @Override public void filesDropped(File[] packages) { jFileChooser1.setSelectedFiles(packages); for (int i = 0; i < packages.length; i++) { message = date + "Dropped package included (" + packages[i].getName() + ") \n"; jTextArea.append(message); } jMenuItem2.setEnabled(true); jButton2.setEnabled(true); } }); } } /** * Package selection */ private class PackageSelection { private FileNameExtensionFilter filter; protected void choosePackages() { filter = new FileNameExtensionFilter("(*.apk, *.zip)", "apk", "zip"); jFileChooser1.setCurrentDirectory(new File(System.getProperty("user.dir"))); jFileChooser1.setAcceptAllFileFilterUsed(false); // Disable All Files filter. jFileChooser1.setMultiSelectionEnabled(true); // Support for multiple selection. jFileChooser1.setFileFilter(filter); // Sets File extension filter to APK and ZIP only. int response = jFileChooser1.showOpenDialog(rootPane); if (response == JFileChooser.APPROVE_OPTION) { File[] chosenPackages = jFileChooser1.getSelectedFiles(); for (int i = 0; i < chosenPackages.length; i++) { String name = chosenPackages[i].getName(); message = date + "Selected package included (" + name + ") \n"; jTextArea.append(message); } jMenuItem2.setEnabled(true); jButton2.setEnabled(true); } } } /** * Output directory selection */ private class OutputSelection { protected void assignOutput() { jFileChooser2.setCurrentDirectory(new File(System.getProperty("user.dir"))); jFileChooser2.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); // Show directories only. int response = jFileChooser2.showOpenDialog(rootPane); if (response == JFileChooser.APPROVE_OPTION) { String path = jFileChooser2.getSelectedFile().getAbsolutePath(); message = date + "Selected output assigned (" + path + ") \n"; jTextArea.append(message); jMenuItem3.setEnabled(true); jButton3.setEnabled(true); } } } /** * Signing package * * Using SwingWorker.doInBackground for the signing process. */ private class SignPackage extends SwingWorker<Integer, String> { private Process process; private int status; @Override protected Integer doInBackground() throws Exception { /* Get the package(s) and output directory paths. */ File[] includedPackages = jFileChooser1.getSelectedFiles(); String folder = jFileChooser2.getSelectedFile().getAbsolutePath(); // Get the specified output directory path. String path = System.getProperty("user.dir"); // Get current running JAR path. String separator = System.getProperty("file.separator"); // Use the system default path separator. /* The FOR loop statement will handle the process for multiple packages. */ for (int i = 0; i < includedPackages.length; i++) { String packages = includedPackages[i].getAbsolutePath(); // Get the current package's absolute path. // Using Commons IO FilenameUtils to separate // the base name and the package's extension. String name = FilenameUtils.getBaseName(includedPackages[i].getName()); String extension = FilenameUtils.getExtension(includedPackages[i].getName()); // This is basically, the system command that // will sign the package(s). So to access the // signapk.jar and the testkeys, get the current // "user.dir" path (this will return the path // where the current JAR is running), then use // the system default path separator (cause it // varies according to Operating Systems). String[] command = {"java", "-Xmx1024m", "-jar", "" + path + separator + "assets" + separator + "signapk.jar", "-w", "" + path + separator + "assets" + separator + "testkey.x509.pem", "" + path + separator + "assets" + separator + "testkey.pk8", "" + packages + "", "" + folder + separator + name + "-signed." + extension +""}; try { // Using ProcessBuilder to execute the command. Which needs to be in array form. ProcessBuilder processBuilder = new ProcessBuilder(command); process = processBuilder.start(); if (!isCancelled()) { message = date + "Processing package (" + name + "." + extension + ") \n"; jTextArea.append(message); status = process.waitFor(); if (status == 0) { message = date + "Signing package succeed (" + name + "-signed." + extension + ") \n"; jTextArea.append(message); Thread.sleep(1000); } else { message = "Known issues\n"+ "- The package specified is not valid.\n"+ "- The package specified may be damaged.\n"+ "- The package specified may be renamed or removed.\n"+ "- The output directory may be renamed or removed.\n"+ "- The assets' folder may be renamed or removed.\n"+ "- The assets' file(s) may be modified or removed.\n"+ "- The libraries' folder may be renamed or removed.\n"+ "- The libraries' file(s) may be renamed or removed. \n\n"; icon = new ImageIcon(getClass().getResource("/drawable/ic_error_36.png")); JOptionPane.showMessageDialog(rootPane, message, "Error", JOptionPane.ERROR_MESSAGE, icon); message = date + "Signing package failed (an error occured) \n"; jTextArea.append(message); process.destroy(); return status; } } else { message = date + "Signing package stopped (process was cancelled) \n"; jTextArea.append(message); process.destroy(); return status; } process.destroy(); } catch (IOException | InterruptedException ex) { if( process != null ) process.destroy(); } } return status; } @Override protected void done() { // When the process ws completed, failed or cancelled, // set all selections and actions to their default state. jMenuItem2.setEnabled(false); jMenuItem3.setEnabled(false); jButton2.setEnabled(false); jButton3.setEnabled(false); jButton4.setEnabled(false); jProgressBar.setIndeterminate(false); jFileChooser1.setSelectedFiles(null); jFileChooser2.setSelectedFile(null); } } }
package hr.fer.zemris.vhdllab.applets.schema2.gui.canvas; import hr.fer.zemris.vhdllab.applets.editor.schema2.constants.Constants; import hr.fer.zemris.vhdllab.applets.editor.schema2.enums.ECanvasState; import hr.fer.zemris.vhdllab.applets.editor.schema2.enums.EPropertyChange; import hr.fer.zemris.vhdllab.applets.editor.schema2.exceptions.UnknownComponentPrototypeException; import hr.fer.zemris.vhdllab.applets.editor.schema2.interfaces.ICommand; import hr.fer.zemris.vhdllab.applets.editor.schema2.interfaces.ICommandResponse; import hr.fer.zemris.vhdllab.applets.editor.schema2.interfaces.ILocalGuiController; import hr.fer.zemris.vhdllab.applets.editor.schema2.interfaces.IQuery; import hr.fer.zemris.vhdllab.applets.editor.schema2.interfaces.IQueryResult; import hr.fer.zemris.vhdllab.applets.editor.schema2.interfaces.ISchemaComponent; import hr.fer.zemris.vhdllab.applets.editor.schema2.interfaces.ISchemaComponentCollection; import hr.fer.zemris.vhdllab.applets.editor.schema2.interfaces.ISchemaController; import hr.fer.zemris.vhdllab.applets.editor.schema2.interfaces.ISchemaCore; import hr.fer.zemris.vhdllab.applets.editor.schema2.interfaces.ISchemaWire; import hr.fer.zemris.vhdllab.applets.editor.schema2.interfaces.ISchemaWireCollection; import hr.fer.zemris.vhdllab.applets.editor.schema2.misc.Caseless; import hr.fer.zemris.vhdllab.applets.editor.schema2.misc.DrawingProperties; import hr.fer.zemris.vhdllab.applets.editor.schema2.misc.Rect2d; import hr.fer.zemris.vhdllab.applets.editor.schema2.misc.SMath; import hr.fer.zemris.vhdllab.applets.editor.schema2.misc.SchemaPort; import hr.fer.zemris.vhdllab.applets.editor.schema2.misc.WireSegment; import hr.fer.zemris.vhdllab.applets.editor.schema2.misc.XYLocation; import hr.fer.zemris.vhdllab.applets.editor.schema2.model.SimpleSchemaComponentCollection; import hr.fer.zemris.vhdllab.applets.editor.schema2.model.SimpleSchemaWireCollection; import hr.fer.zemris.vhdllab.applets.editor.schema2.model.commands.DeleteSegmentAndDivideCommand; import hr.fer.zemris.vhdllab.applets.editor.schema2.model.commands.DeleteWireCommand; import hr.fer.zemris.vhdllab.applets.editor.schema2.model.commands.InstantiateComponentCommand; import hr.fer.zemris.vhdllab.applets.editor.schema2.model.commands.MoveComponentCommand; import hr.fer.zemris.vhdllab.applets.editor.schema2.model.queries.FindConnectedPins; import java.awt.Color; import java.awt.Component; import java.awt.Cursor; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Insets; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.image.BufferedImage; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.swing.BorderFactory; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.Timer; public class SchemaCanvas extends JPanel implements PropertyChangeListener, ISchemaCanvas { /** * Generated serial ID */ private static final long serialVersionUID = -179843489371055255L; private static final int MIN_COMPONENT_DISTANCE = 10; /** * Image used to create double-buffer effect. */ protected BufferedImage img = new BufferedImage(1, 1, BufferedImage.TYPE_3BYTE_BGR); /** * Collection containing all components in design. */ protected ISchemaComponentCollection components = new SimpleSchemaComponentCollection(); /** * Collection containing all wires in design. */ protected ISchemaWireCollection wires = new SimpleSchemaWireCollection(); /** * controller na razini schema-editora */ protected ISchemaController controller; /** * controller na razini GUI-a */ protected ILocalGuiController localController; /** * Stanje u kojem se canvas nalazi. */ protected ECanvasState state; /** * komponenta koja se iscrtava kao komponenta za dodati */ protected ISchemaComponent addComponentComponent = null; /** * Lokacija komponente za dodati */ protected int addComponentX = 0, addComponentY = 0; /** * Sadrani svi podatci o zici za dodati... */ protected IWirePreLocator preLoc = null; /** * trenutni critical point nad kojim je mis */ private CriticalPoint point = null; /** * akcija za animaciju critical point-a */ private Decrementer decrementer = null; /** * critical point sa kojeg je zica krenula */ protected CriticalPoint wireBeginning = null; /** * critical point gdije je zica zavrsila */ protected CriticalPoint wireEnding = null; private DrawingProperties drawProperties = null; private Timer timer = null; protected Caseless componentToMove = null; private boolean isGridOn =true; //constrictors public SchemaCanvas(ISchemaCore core) { this(); components = core.getSchemaInfo().getComponents(); wires = core.getSchemaInfo().getWires(); repaint(); } /** * Dummy constructor za testiranje panela * */ public SchemaCanvas(ISchemaComponentCollection comp, ISchemaWireCollection wir) { this(); components = comp; wires = wir; repaint(); } public SchemaCanvas() { state = ECanvasState.MOVE_STATE; //init state decrementer = new Decrementer(20, this); timer = new Timer(70,decrementer); drawProperties = new DrawingProperties(); this.addMouseListener(new Mouse1()); this.addMouseMotionListener(new Mose2()); this.setOpaque(true); this.setBorder(BorderFactory.createLineBorder(Color.BLACK, 3)); } // // /** * Overriden method for painting the canvas. */ @Override protected void paintComponent(Graphics g) { Insets in = this.getInsets(); if(img == null) { img=new BufferedImage(this.getWidth()-in.left-in.right,this.getHeight()-in.top-in.bottom , BufferedImage.TYPE_3BYTE_BGR); drawComponents(); } else { if (img.getHeight()!=this.getHeight()-in.top-in.bottom || img.getWidth()!=this.getWidth()-in.left-in.right){ img=new BufferedImage(this.getWidth()-in.left-in.right,this.getHeight()-in.top-in.bottom , BufferedImage.TYPE_3BYTE_BGR); } drawComponents(); g.drawImage(img, in.left, in.right, img.getWidth(), img.getHeight(), null); } } // /** * Private method responsible for drawing all components and wires contained in components * and wires collections. * */ private void drawComponents() { Graphics2D g = (Graphics2D)img.getGraphics(); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); components = controller.getSchemaInfo().getComponents(); wires = controller.getSchemaInfo().getWires(); g.setColor(CanvasColorProvider.CANVAS_BACKGROUND); g.fillRect(0,0,img.getWidth(),img.getHeight()); int dist = Constants.GRID_SIZE; g.setColor(CanvasColorProvider.GRID_DOT); for(int i = 0; i<=img.getWidth()/dist;i++) for(int j=0;j<=img.getHeight()/dist;j++){ g.fillOval(i*dist, j*dist, 1, 1); } Set<Caseless> names = components.getComponentNames(); int sizeX = 0; int sizeY = 0; Caseless sel = localController.getSelectedComponent(); int type = localController.getSelectedType(); for(Caseless name: names){ ISchemaComponent comp = components.fetchComponent(name); XYLocation componentLocation = components.getComponentLocation(name); Color cl = g.getColor(); g.setColor(type == CanvasToolbarLocalGUIController.TYPE_COMPONENT && name.equals(sel)? CanvasColorProvider.COMPONENT_SELECTED: CanvasColorProvider.COMPONENT); g.translate(componentLocation.x, componentLocation.y); comp.getDrawer().draw(g, drawProperties); g.translate(-componentLocation.x, -componentLocation.y); // String text = name.toString(); Rectangle rect = components.getComponentBounds(name); // FontMetrics fm = g.getFontMetrics(); // int tx=rect.x+rect.width/2-fm.stringWidth(text)/2; // int ty=rect.y; // g.drawString(text,tx,ty); if(rect.x + rect.width + 10 > sizeX)sizeX =rect.x + rect.width + 10; if(rect.y + rect.height + 10 > sizeY)sizeY =rect.y + rect.height + 10; g.setColor(cl); } names=wires.getWireNames(); for(Caseless name: names){ Color cl = g.getColor(); g.setColor(type == CanvasToolbarLocalGUIController.TYPE_WIRE && name.equals(sel)? CanvasColorProvider.SIGNAL_LINE_SELECTED: CanvasColorProvider.SIGNAL_LINE); wires.fetchWire(name).getDrawer().draw(g, drawProperties); Rect2d rect = wires.getBounds(name); if(rect.left + rect.width + 10 > sizeX)sizeX =rect.left + rect.width + 10; if(rect.top + rect.height + 10 > sizeY)sizeY =rect.top + rect.height + 10; g.setColor(cl); } if(addComponentComponent!= null){ Color temp = g.getColor(); g.setColor(CanvasColorProvider.COMPONENT_TO_ADD); g.translate(addComponentX, addComponentY); addComponentComponent.getDrawer().draw(g, drawProperties); g.translate(-addComponentX, -addComponentY); g.setColor(temp); } if(preLoc != null){ Color temp = g.getColor(); g.setColor(preLoc.isWireInstantiable()? CanvasColorProvider.SIGNAL_LINE_TO_ADD: CanvasColorProvider.SIGNAL_LINE_ERROR); preLoc.draw(g); g.setColor(temp); } if(point!=null){ point.draw(g, decrementer.getIznos()); } if(type == CanvasToolbarLocalGUIController.TYPE_WIRE && !Caseless.isNullOrEmpty(sel)){ drawConnectedPins(g,sel); } if(type == CanvasToolbarLocalGUIController.TYPE_COMPONENT && !Caseless.isNullOrEmpty(sel)){ ISchemaComponent comp = components.fetchComponent(sel); if (comp != null) { Color cl = g.getColor(); g.setColor(CanvasColorProvider.SIGNAL_LINE_SELECTED_ONCOMP); for (SchemaPort sp : comp.getSchemaPorts()) { Caseless mappedto = sp.getMapping(); if (Caseless.isNullOrEmpty(mappedto)) continue; wires.fetchWire(mappedto).getDrawer().draw(g, drawProperties); drawConnectedPins(g, mappedto); } g.setColor(cl); } } setCanvasSize(sizeX,sizeY); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); } @SuppressWarnings("unchecked") private void drawConnectedPins(Graphics2D g, Caseless sel) { IQuery q = new FindConnectedPins(sel); IQueryResult r = controller.send(q); List<XYLocation> locList = (List<XYLocation>) r.get(FindConnectedPins.KEY_PIN_LOCATIONS); Color cl = g.getColor(); g.setColor(CanvasColorProvider.SIGNAL_LINE_SELECTED_PORT); for(XYLocation xy:locList){ g.fillOval(xy.x-4, xy.y-4, 8, 8); } g.setColor(cl); } private void setCanvasSize(int sizeX, int sizeY) { Insets in = this.getInsets(); this.setPreferredSize(new Dimension(sizeX+in.left+in.right, sizeY+in.top+in.bottom)); this.revalidate(); } // /* (non-Javadoc) * @see hr.fer.zemris.vhdllab.applets.schema2.gui.canvas.ISchemaCanvas#setDummyStuff(hr.fer.zemris.vhdllab.applets.schema2.interfaces.ISchemaComponentCollection, hr.fer.zemris.vhdllab.applets.schema2.interfaces.ISchemaWireCollection) */ public void setDummyStuff(ISchemaComponentCollection components, ISchemaWireCollection wires) { this.components = components; this.wires = wires; repaint(); } public void propertyChange(PropertyChangeEvent evt) { // System.out.println("Canvas registered:"+evt.getPropertyName()); if(evt.getPropertyName().equals(EPropertyChange.CANVAS_CHANGE.toString())){ drawComponents(); }else if(evt.getPropertyName().equalsIgnoreCase("GRID")){ isGridOn = localController.isGridON(); }else if(evt.getPropertyName().equalsIgnoreCase(CanvasToolbarLocalGUIController.PROPERTY_CHANGE_SELECTION)){ // System.out.println("Canvas registered: localControler.PROPERTY_CHANGE_SELECTION"); }else if(evt.getPropertyName().equalsIgnoreCase(CanvasToolbarLocalGUIController.PROPERTY_CHANGE_STATE) ||evt.getPropertyName().equalsIgnoreCase(CanvasToolbarLocalGUIController.PROPERTY_CHANGE_COMPONENT_TO_ADD)){ this.setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); modifyTimerStatus(); localController.setSelectedComponent(new Caseless(""), CanvasToolbarLocalGUIController.TYPE_NOTHING_SELECTED); addComponentComponent = null; preLoc = null; point = null; addComponentX = 0; addComponentY = 0; ILocalGuiController tempCont = (CanvasToolbarLocalGUIController) evt.getSource(); state = tempCont.getState(); if(state.equals(ECanvasState.ADD_COMPONENT_STATE)){ this.setCursor(new Cursor(Cursor.HAND_CURSOR)); try { addComponentComponent = controller.getSchemaInfo().getPrototyper().clonePrototype(tempCont.getComponentToAdd(), new HashSet<Caseless>()); } catch (UnknownComponentPrototypeException e) { System.out.println("Canvas Property change | illegal action on component initialization."); e.printStackTrace(); } } // System.out.println("Canvas registered:" + tempCont); } repaint(); } /* (non-Javadoc) * @see hr.fer.zemris.vhdllab.applets.schema2.gui.canvas.ISchemaCanvas#setConteroler(hr.fer.zemris.vhdllab.applets.schema2.interfaces.ISchemaController) */ public void registerSchemaController(ISchemaController controller) { this.controller=controller; } /* (non-Javadoc) * @see hr.fer.zemris.vhdllab.applets.schema2.gui.canvas.ISchemaCanvas#registerLocalController(hr.fer.zemris.vhdllab.applets.schema2.interfaces.ILocalGuiController) */ public void registerLocalController(ILocalGuiController cont){ localController = cont; } // protected class Mouse1 implements MouseListener{ public void mouseClicked(MouseEvent e) { if(e.getButton()==MouseEvent.BUTTON1){ if(state.equals(ECanvasState.ADD_COMPONENT_STATE)){ Caseless comp = localController.getComponentToAdd(); ICommand instantiate = new InstantiateComponentCommand(comp, alignToGrid(addComponentX), alignToGrid(addComponentY)); ICommandResponse response = controller.send(instantiate); System.out.println ("canvas report| component instantiate succesful: "+response.isSuccessful()); } else if(state.equals(ECanvasState.DELETE_STATE)){ ISchemaComponent comp = components.fetchComponent(e.getX(), e.getY(), MIN_COMPONENT_DISTANCE); int distToComp = -1; if(comp != null){ //+5 je zbog crtanja komponenti distToComp = 5 + Math.abs(components.distanceTo(comp.getName(), e.getX(), e.getY())); } ISchemaWire wire = wires.fetchWire(e.getX(), e.getY(), 10); int distToWire = -1; if(wire != null){ distToWire = Math.abs(wires.distanceTo(wire.getName(), e.getX(), e.getY())); } // System.err.println(" if(distToComp != -1){ if(distToWire != -1){ if(distToComp<distToWire){ // ICommand instantiate = new DeleteComponentCommand(comp.getName()); // controller.send(instantiate); }else{ int segNo = SMath.calcClosestSegment(new XYLocation(e.getX(), e.getY()), 10, wire.getSegments()); WireSegment seg = wire.getSegments().get(segNo); ICommand deleteSegment = new DeleteSegmentAndDivideCommand(wire.getName(),seg); controller.send(deleteSegment); } }else{ // ICommand instantiate = new DeleteComponentCommand(comp.getName()); // controller.send(instantiate); } }else{ if(distToWire != -1){ int segNo = SMath.calcClosestSegment(new XYLocation(e.getX(), e.getY()), 10, wire.getSegments()); WireSegment seg = wire.getSegments().get(segNo); ICommand deleteSegment = new DeleteSegmentAndDivideCommand(wire.getName(),seg); controller.send(deleteSegment); } } // if(comp != null){ // ICommand instantiate = new DeleteComponentCommand(comp.getName()); // ICommandResponse response = controller.send(instantiate); // System.out.println ("canvas report| component delete succesful: "+response.isSuccessful()); // }else{ // ISchemaWire wire = wires.fetchWire(e.getX(), e.getY(), 10); // if(wire != null){ // int segNo = SMath.calcClosestSegment(new XYLocation(e.getX(), e.getY()), 10, wire.getSegments()); // WireSegment seg = wire.getSegments().get(segNo); // ICommand deleteSegment = new DeleteSegmentAndDivideCommand(wire.getName(),seg); // ICommandResponse response = controller.send(deleteSegment); // System.out.println ("canvas report| component delete succesful: "+response.isSuccessful()); } else if(state.equals(ECanvasState.MOVE_STATE)){ ISchemaComponent comp = components.fetchComponent(e.getX(), e.getY(), MIN_COMPONENT_DISTANCE); int distToComp = -1; if(comp != null){ //+5 je zbog crtanja komponenti... distToComp = 5 + Math.abs(components.distanceTo(comp.getName(), e.getX(), e.getY())); } ISchemaWire wire = wires.fetchWire(e.getX(), e.getY(), 10); int distToWire = -1; if(wire != null){ distToWire = Math.abs(wires.distanceTo(wire.getName(), e.getX(), e.getY())); } //System.err.println(" if(distToComp != -1){ if(distToWire != -1){ if(distToComp<distToWire){ localController.setSelectedComponent(comp.getName(),CanvasToolbarLocalGUIController.TYPE_COMPONENT); }else{ localController.setSelectedComponent(wire.getName(), CanvasToolbarLocalGUIController.TYPE_WIRE); } }else{ localController.setSelectedComponent(comp.getName(),CanvasToolbarLocalGUIController.TYPE_COMPONENT); } }else{ if(distToWire != -1){ localController.setSelectedComponent(wire.getName(), CanvasToolbarLocalGUIController.TYPE_WIRE); } } // ISchemaComponent comp = components.fetchComponent(e.getX(), e.getY(), MIN_COMPONENT_DISTANCE); // if(comp != null){ // localController.setSelectedComponent(comp.getName(),CanvasToolbarLocalGUIController.TYPE_COMPONENT); // }else{ // ISchemaWire wir = wires.fetchWire(e.getX(), e.getY(),10); // if(wir!=null) // localController.setSelectedComponent(wir.getName(), CanvasToolbarLocalGUIController.TYPE_WIRE); } }else if(e.getButton()==MouseEvent.BUTTON3){ if(state.equals(ECanvasState.MOVE_STATE)){ localController.setSelectedComponent(new Caseless(""), CanvasToolbarLocalGUIController.TYPE_NOTHING_SELECTED); }else if(state.equals(ECanvasState.ADD_WIRE_STATE)){ preLoc = null; wireBeginning = null; wireEnding = null; repaint(); }else if(state.equals(ECanvasState.DELETE_STATE)){ ISchemaWire wire = wires.fetchWire(e.getX(), e.getY(), 10); if(wire != null){ if(doDeleteWire(SchemaCanvas.this)){ ICommand delete = new DeleteWireCommand(wire.getName()); ICommandResponse response = controller.send(delete); System.out.println ("canvas report| component delete succesful: "+response.isSuccessful()); } } } } } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) {} public void mousePressed(MouseEvent e) { if(e.getButton() == MouseEvent.BUTTON1){ if(state.equals(ECanvasState.ADD_WIRE_STATE)){ wireBeginning = getCriticalPoint(e.getX(),e.getY()); int x = alignToGrid(e.getX()); int y = alignToGrid(e.getY()); if(wireBeginning!=null){ x=wireBeginning.getX(); y=wireBeginning.getY(); } if(localController.isSmartConectON()){ preLoc = new AdvancedWirePreLocator(new ArrayList<WireSegment>(),controller); preLoc.setX1(x); preLoc.setY1(y); }else{ preLoc = new WirePreLocator(x,y,x,y); } }else if(state.equals(ECanvasState.MOVE_STATE)){ ISchemaComponent comp = components.fetchComponent(e.getX(), e.getY(), MIN_COMPONENT_DISTANCE); if(comp!=null){ componentToMove = comp.getName(); localController.setSelectedComponent(comp.getName(),CanvasToolbarLocalGUIController.TYPE_COMPONENT); } } } } public void mouseReleased(MouseEvent e) { if(e.getButton()==MouseEvent.BUTTON1){ if(state.equals(ECanvasState.ADD_WIRE_STATE)&&preLoc!=null){ wireEnding = getCriticalPoint(e.getX(),e.getY()); int x = alignToGrid(e.getX()); int y = alignToGrid(e.getY()); if(wireEnding!=null){ x=wireEnding.getX(); y=wireEnding.getY(); } preLoc.setX2(x); preLoc.setY2(y); preLoc.revalidateWire(); preLoc.setWireInstantiable(wireBeginning,wireEnding); if(preLoc.isWireInstance()){ preLoc.instantiateWire(controller, wireBeginning, wireEnding); } preLoc = null; wireBeginning = null; wireEnding = null; repaint(); }else if(state.equals(ECanvasState.MOVE_STATE)){ componentToMove = null; } } } } protected class Mose2 implements MouseMotionListener{ public void mouseDragged(MouseEvent e) { if(state.equals(ECanvasState.ADD_WIRE_STATE)&&preLoc!=null){ preLoc.setX2(alignToGrid(e.getX())); preLoc.setY2(alignToGrid(e.getY())); point = getCriticalPoint(e.getX(), e.getY()); preLoc.setWireInstantiable(wireBeginning,point); preLoc.revalidateWire(); modifyTimerStatus(); repaint(); }else if(state.equals(ECanvasState.MOVE_STATE)&&componentToMove!=null){ ISchemaComponent comp = components.fetchComponent(componentToMove); if(e.getX()>comp.getWidth()/2&&e.getY()>comp.getHeight()/2){ ICommand move = new MoveComponentCommand( componentToMove,new XYLocation( alignToGrid(e.getX()-comp.getWidth()/2),alignToGrid(e.getY()-comp.getHeight()/2) ) ); controller.send(move); //System.out.println ("canvas report| component delete succesful: "+response.isSuccessful()); } } } public void mouseMoved(MouseEvent e) { if(state.equals(ECanvasState.ADD_COMPONENT_STATE)){ int x = e.getX(); int y = e.getY(); if(x > addComponentComponent.getWidth()/2 && y > addComponentComponent.getHeight()/2 && x < img.getWidth() && y < img.getHeight()) { addComponentX = alignToGrid(x-addComponentComponent.getWidth()/2); addComponentY = alignToGrid(y-addComponentComponent.getHeight()/2); repaint(); } } if(state.equals(ECanvasState.ADD_WIRE_STATE)){ point = getCriticalPoint(e.getX(), e.getY()); modifyTimerStatus(); repaint(); } } } public static boolean doDeleteWire(Component comp) { String[] options={"Yes", "No" }; JLabel name=new JLabel("Delete entire wire?"); JOptionPane optionPane=new JOptionPane(name,JOptionPane.QUESTION_MESSAGE,JOptionPane.OK_CANCEL_OPTION,null,options,options[0]); JDialog dialog=optionPane.createDialog(comp,"VHDLLAB"); dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE); dialog.setVisible(true); Object selected=optionPane.getValue(); return selected.equals(options[0]); } public void modifyTimerStatus() { if(point==null)timer.stop(); else{ decrementer.reset(); timer.start(); } } public CriticalPoint getCriticalPoint(int x, int y) { CriticalPoint point = null; ISchemaComponent comp = components.fetchComponent(x,y, MIN_COMPONENT_DISTANCE); if(comp!=null){ Rectangle rect = components.getComponentBounds(comp.getName()); SchemaPort port = comp.getSchemaPort(x-rect.x, y-rect.y, MIN_COMPONENT_DISTANCE); if(port != null){ if(port.getMapping()==null||port.getMapping().equals(new Caseless(""))){ point = new CriticalPoint(port.getOffset().getX()+rect.x,port.getOffset().getY()+rect.y, CriticalPoint.ON_COMPONENT_PLUG,comp.getName(),port.getName()); decrementer.reset(); }else{ // Caseless c = port.getMapping();//TODO pitaj aleksa za ovaj getMapping!! // point = new CriticalPoint(wires.fetchWire(port.getMapping()), alignToGrid(x), alignToGrid(y)); } } } if(point == null){ ISchemaWire wire = wires.fetchWire(x, y, Constants.GRID_SIZE/2-1); if(wire != null){ point = new CriticalPoint(wire, alignToGrid(x), alignToGrid(y)); } } return point; } protected int alignToGrid(int x){ if(isGridOn) return Math.round((float)x/Constants.GRID_SIZE)*Constants.GRID_SIZE; return x; } }
package com.db.xml; import com.db.crypto.Cryptor; import com.db.crypto.KeyManager; import com.db.logging.Logger; import com.db.logging.LoggerManager; import com.db.util.Base64Coder; import java.security.PrivateKey; import org.w3c.dom.Element; /** * A SignableXMLEnvelope is a transferrable container that allows * any object that implements the IXmlSerializer interface to be * transported in a secure, signed vessel. * * This envelope may be used in either "signed" or "unsigned" form to * transport information. * * Whenever this envelope is signed, its content becomes locked. If * the content of this envelope is changed after it has been signed, then * it will fail verification. The envelope must be signed again if the * contents are changed in order to pass verification. * * In other words, once sign() is called on this envelope, if you want * to modify its contents and pass verification, you must call sign() * again after the modification. * * This ensures the integrity of the signature generated when sign() was * called such that the text contents of this envelope will match that * signature regardless of any changes to the xml serializer contents of * this envelope. If you want to see the changes reflected, then you must * re-sign the envelope. * * If an envelope is never signed, then it will remain in an "unsigned" state * and any changes to the xml serializer contents of that envelope will be * instantly reflected. * * So: * * By default, an envelope is in an unsigned state. Calling sign() will * permanently change the envelopes state to signed. * * When an envelope is in an unsigned state any changes made to its xml * serializer contents will be immediately reflected when converting the * envelope to xml. * * When an envelope is in a signed state any changes made to its xml * serializer contents will only be reflected upon calling sign(). * * @author Dave Longley */ public class SignableXmlEnvelope extends VersionedXmlSerializer { /** * The xml serializer interface that produces the xml that will * be signed. This is the content for this envelope. */ protected IXmlSerializer mContent; /** * The text to sign/that was signed. */ protected String mSignText; /** * The identity of the signer. */ protected String mSigner; /** * The status of this signable xml entity. The status can be * "unsigned", "signed", or "invalid". */ protected String mStatus; /** * The algorithm used to produce the signature. */ protected String mAlgorithm; /** * The signature produced when signing. */ protected String mSignature; /** * Constructs a SignableXmlEnvelope with no yet set xml serializer content. */ public SignableXmlEnvelope() { this(null); } /** * Constructs a SignableXmlEnvelope that envelopes the passed xml * serializer. * * @param xmlSerializer the xml serializer to envelope. * @param xml the xml to convert from. */ public SignableXmlEnvelope(IXmlSerializer xmlSerializer, String xml) { this(xmlSerializer); // convert from xml convertFromXml(xml); } /** * Constructs a signable xml envelope that envelopes the * xml text produced by the passed IXMLSerializer. * * @param xmlSerializer the xml serializer interface to envelope. */ public SignableXmlEnvelope(IXmlSerializer xmlSerializer) { super("2.0"); mContent = xmlSerializer; mSignText = ""; mSigner = "0"; mStatus = "unsigned"; mAlgorithm = ""; mSignature = ""; } /** * Updates the text to sign. */ protected synchronized void updateSignText() { mSignText = ""; if(getContent() != null) { mSignText = getContent().convertToXml(1); } } /** * Sets the status of this envelope. * * @param status the status to set the envelope to. */ protected void setStatus(String status) { mStatus = status; } /** * Contructs a signature with the passed signer and * the private key. * * When this method is called, the text contents of the envelope * are locked until this method is called again. Therefore, any changes * made to the xml serializer contents of this envelope will not be * reflected until this method is called again. This ensures the * integrity of the signature. * * When converting this envelope to xml, the signed text will be used * as the contents of this envelope, the xml serializers convert method * will not be called again until sign() is called again. * * @param signer the signer of the signature. * @param privateKey the privateKey to sign with. * * @return true if successfully signed, false if not. */ public boolean sign(long signer, PrivateKey privateKey) { return sign("" + signer, privateKey); } /** * Contructs a signature with the passed signer and * the private key. * * When this method is called, the text contents of the envelope * are locked until this method is called again. Therefore, any changes * made to the xml serializer contents of this envelope will not be * reflected until this method is called again. This ensures the * integrity of the signature. * * When converting this envelope to xml, the signed text will be used * as the contents of this envelope, the xml serializers convert method * will not be called again until sign() is called again. * * @param signer the signer of the signature. * @param key the Base64-PKCS8 privateKey to sign with. * * @return true if successfully signed, false if not. */ public boolean sign(long signer, String key) { return sign("" + signer, key); } /** * Contructs a signature with the passed signer and * the private key. * * When this method is called, the text contents of the envelope * are locked until this method is called again. Therefore, any changes * made to the xml serializer contents of this envelope will not be * reflected until this method is called again. This ensures the * integrity of the signature. * * When converting this envelope to xml, the signed text will be used * as the contents of this envelope, the xml serializers convert method * will not be called again until sign() is called again. * * @param signer the signer of the signature. * @param key the Base64-PKCS8 privateKey to sign with. * * @return true if successfully signed, false if not. */ public boolean sign(String signer, String key) { PrivateKey privateKey = KeyManager.decodePrivateKey(key); return sign(signer, privateKey); } /** * Contructs a signature with the passed signer and * the private key. * * When this method is called, the text contents of the envelope * are locked until this method is called again. Therefore, any changes * made to the xml serializer contents of this envelope will not be * reflected until this method is called again. This ensures the * integrity of the signature. * * When converting this envelope to xml, the signed text will be used * as the contents of this envelope, the xml serializers convert method * will not be called again until sign() is called again. * * @param signer the signer of the signature. * @param privateKey the privateKey to sign with. * * @return true if successfully signed, false if not. */ public synchronized boolean sign(String signer, PrivateKey privateKey) { boolean rval = false; // set status to signed, regardless of whether or not signature is // successful -- a sign() was attempted setStatus("signed"); // set the signer mSigner = signer; // update the text to sign updateSignText(); // make sure there is a key to sign it with if(privateKey != null) { try { // get the signature algorithm -- use SHA1 if(privateKey.getAlgorithm().equals("DSA")) { mAlgorithm = "SHAwithDSA"; } else if(privateKey.getAlgorithm().equals("RSA")) { mAlgorithm = "SHA1withRSA"; } else { mAlgorithm = ""; } // sign the text byte[] sig = Cryptor.sign(mSignText, privateKey); // base64 encode the signature for xml transport Base64Coder encoder = new Base64Coder(); mSignature = encoder.encode(sig); getLogger().detail(getClass(), "BEGIN SIGN TEXT:" + mSignText + ":END SIGN TEXT\n" + "SIGNATURE: '" + mSignature + "'"); if(mSignature != null) { rval = true; } else { mSignature = ""; } } catch(Exception e) { getLogger().debug(getClass(), Logger.getStackTrace(e)); } } return rval; } /** * Attempts to verify that this object was digitally * signed. The passed public key should be a Base64-encoded * string that represents the X.509 encoded public key. * * @param publicKey the public key to verify the signature. * * @return true if verified, false if not. */ public synchronized boolean verify(String publicKey) { boolean rval = false; // make sure the status is valid if(isValid()) { // make sure there is a signature if(!mSignature.equals("")) { // make sure there is a public key if(publicKey != null) { try { if(!mAlgorithm.startsWith("SHA")) { getLogger().debug(getClass(), "unknown signature algorithm!," + "algorithm=" + mAlgorithm); } // base64 decode the signature Base64Coder decoder = new Base64Coder(); byte[] sig = decoder.decode(mSignature); getLogger().detail(getClass(), "BEGIN VERIFY TEXT:" + mSignText + ":END VERIFY TEXT\n" + "SIGNATURE: '" + mSignature + "'"); // verify the signature rval = Cryptor.verify(sig, mSignText, publicKey); } catch(Exception e) { getLogger().debug(getClass(), Logger.getStackTrace(e)); } } } } if(!rval) { setStatus("invalid"); } return rval; } /** * Gets the last signer of this envelope as a long. * * @return the signer's id as a long. */ public long getSignerLong() { long rval = 0; try { rval = Long.parseLong(getSigner()); } catch(Throwable t) { getLogger().debug(getClass(), Logger.getStackTrace(t)); } return rval; } /** * Gets the last signer of this envelope. * * @return the signer's id. */ public String getSigner() { return mSigner; } /** * Gets the status of this envelope. * * @return the status of this envelope. */ public String getStatus() { return mStatus; } /** * Returns true if this envelope's status is valid, false if not. * Whenever verify() fails on an envelope its status is set to * "invalid". Otherwise this envelope is valid whether its status is * "signed" or "unsigned." * * @return returns true if this envelope's status is valid, false if not. */ public boolean isValid() { return !getStatus().equals("invalid"); } /** * Gets the algorithm used to create the signature for the envelope. * * @return the algorithm used to create the signature for the envelope, * or a blank string if the envelope is not signed. */ public String getAlgorithm() { return mAlgorithm; } /** * Sets the content of this envelope, that is, the object that implements * an xml serializer interface that produces the xml text to envelope. * * @param xmlSerializer the xml serializer interface. */ public synchronized void setContent(IXmlSerializer xmlSerializer) { mContent = xmlSerializer; mSignText = ""; } /** * Gets the content of this envelope, that is, the object that implements * an xml serializer interface that produces the text to envelope. * * @return the xml serializer interface. */ public IXmlSerializer getContent() { return mContent; } /** * Returns the root tag name for this serializer. * * @return the root tag name for this serializer. */ public String getRootTag() { return "envelope"; } /** * This method takes the object representation and creates an * XML-based representation of the object. * * @param indentLevel the number of spaces to place before the text * after each new line. * * @return the xml-based representation of the object. */ public String convertToXml(int indentLevel) { StringBuffer xml = new StringBuffer(); StringBuffer indent = new StringBuffer("\n"); for(int i = 0; i < indentLevel; i++) { indent.append(' '); } if(indentLevel == 0) { xml.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); //xml.append("<!DOCTYPE transaction SYSTEM \"bitmunk.dtd\">\n"); } // start tag xml.append(indent); xml.append('<'); xml.append(getRootTag()); xml.append(" version=\""); xml.append(XmlCoder.encode(getVersion())); xml.append("\" signer=\""); xml.append(XmlCoder.encode(getSigner())); xml.append("\" status=\""); xml.append(XmlCoder.encode(getStatus())); xml.append("\">"); // signature tag xml.append(indent); xml.append(" <signature algorithm=\""); xml.append(XmlCoder.encode(getAlgorithm())); xml.append("\">"); xml.append(XmlCoder.encode(mSignature)); xml.append("</signature>"); // start content tag xml.append(indent); xml.append(" <content>"); if(getStatus().equals("signed")) { // since the envelope is signed, use the sign text xml.append(XmlCoder.encode(mSignText)); } else if(getContent() != null) { // the envelope is not signed, so just convert xml.append(XmlCoder.encode(getContent().convertToXml(1))); } // end content tag xml.append("</content>"); // end tag xml.append(indent); xml.append("</"); xml.append(getRootTag()); xml.append('>'); return xml.toString(); } /** * This method takes a parsed DOM XML element and converts it * back into this object's representation. * * @param element the parsed element that contains this objects information. * * @return true if successful, false otherwise. */ public boolean convertFromXml(Element element) { boolean rval = false; ElementReader er = new ElementReader(element); if(er != null) { // get version, signer, status setVersion(XmlCoder.decode(er.getStringAttribute("version"))); mSigner = XmlCoder.decode(er.getStringAttribute("signer")); mStatus = XmlCoder.decode(er.getStringAttribute("status")); // get signature information ElementReader sigReader = er.getFirstElementReader("signature"); mAlgorithm = XmlCoder.decode( sigReader.getStringAttribute("algorithm")); mSignature = XmlCoder.decode( sigReader.getStringValue()); rval = true; // if this envelope has content, get the content reader if(getContent() != null) { // get an element reader for the content ElementReader contentReader = er.getFirstElementReader("content"); if(contentReader != null) { // store the content xml as the sign text mSignText = contentReader.getStringValue(); // convert the xml content rval = getContent().convertFromXml(mSignText.trim()); } else { // blank out sign text mSignText = ""; } } } return rval; } /** * Gets the logger for this xml serializer. * * @return the logger for this xml serializer. */ public Logger getLogger() { return LoggerManager.getLogger("dbxml"); } }
package com.legit2.Demigods.Listeners; import java.sql.SQLException; import java.util.ArrayList; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.entity.Player; import org.bukkit.event.EventException; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.inventory.CraftItemEvent; import org.bukkit.event.inventory.InventoryType; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerLoginEvent; import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.inventory.ItemStack; import com.legit2.Demigods.DConfig; import com.legit2.Demigods.DDatabase; import com.legit2.Demigods.DSave; import com.legit2.Demigods.DSouls; import com.legit2.Demigods.DUtil; import com.legit2.Demigods.Demigods; public class DPlayerListener implements Listener { static Demigods plugin; public DPlayerListener(Demigods instance) { plugin = instance; } @EventHandler(priority = EventPriority.LOWEST) public void onPlayerLogin(PlayerLoginEvent event) { String username = event.getPlayer().getName(); try { DDatabase.addPlayer(username); } catch(SQLException e) { e.printStackTrace(); } } @EventHandler public void onPlayerJoin(PlayerJoinEvent event) throws EventException { // Define Variables Player player = event.getPlayer(); DUtil.setPlayerData(player.getName(), "lastlogintime", System.currentTimeMillis()); // if(!DConfig.getEnabledWorlds().contains(player.getWorld())) return; if(DConfig.getSettingBoolean("motd")) { player.sendMessage(ChatColor.GRAY + "This server is running Demigods version: " + ChatColor.YELLOW + DUtil.getPlugin().getDescription().getVersion()); player.sendMessage(ChatColor.GRAY + "Type "+ChatColor.GREEN + "/dg" + ChatColor.GRAY + " for more information."); } } @EventHandler(priority = EventPriority.HIGHEST) public void onPlayerCraft(CraftItemEvent event) { // Define variables Player player = (Player) event.getWhoClicked(); InventoryType invType = event.getInventory().getType(); ArrayList<ItemStack> allSouls = DSouls.returnAllSouls(); if(invType.equals(InventoryType.CRAFTING) || invType.equals(InventoryType.WORKBENCH)) { ItemStack[] invItems = event.getInventory().getContents(); for(ItemStack soul : allSouls) { for(ItemStack invItem : invItems) { if(invItem.isSimilar(soul)) { event.setCancelled(true); player.sendMessage(ChatColor.RED + "You cannot craft with souls!"); } } } } } @EventHandler(priority = EventPriority.HIGHEST) public void onPlayerMove(PlayerMoveEvent event) { // PREVENT LINE JUMPING int pvp_area_delay = (int)(DConfig.getSettingDouble("pvp_area_delay_seconds")*20); final Player player = (Player) event.getPlayer(); final String username = player.getName(); final Location from = event.getFrom(); final Location to = event.getTo(); if(DSave.hasPlayerData(username, "pvp_area_cooldown_temp")) { player.teleport((Location) DSave.getPlayerData(username, "pvp_area_cooldown_temp")); return; } if(DUtil.canPVP(to) != DUtil.canPVP(from)) { if(DUtil.hasPermission(player, "demigods.bypass.pvpareacooldown")) return; // Find the PVP Zone Location PVP; if(DUtil.canPVP(to)) PVP = to; else PVP = from; // Set data to prevent this from triggering more than once DSave.savePlayerData(username, "pvp_area_cooldown_temp", PVP); player.sendMessage(ChatColor.YELLOW + "Please wait while you cooldown..."); player.teleport(PVP); DUtil.getPlugin().getServer().getScheduler().scheduleSyncDelayedTask(DUtil.getPlugin(), new Runnable() { @Override public void run() { player.teleport(to); DSave.removePlayerData(username, "pvp_area_cooldown_temp"); player.sendMessage(ChatColor.YELLOW + "Cooldown complete!"); } }, pvp_area_delay); } } }
package soot.coffi; import soot.options.*; import java.lang.*; import java.util.*; import soot.*; import soot.jimple.*; import soot.baf.*; import soot.util.*; import soot.tagkit.*; /** A Control Flow Graph. * @author Clark Verbrugge */ public class CFG { /** Method for which this is a control flow graph. * @see method_info */ private method_info method; /** Ordered list of BasicBlocks comprising the code of this CFG. */ BasicBlock cfg; Chain units; JimpleBody listBody; Map instructionToFirstStmt; Map instructionToLastStmt; SootMethod jmethod; Scene cm; Instruction firstInstruction; Instruction lastInstruction; private short wide; // convert indices when parsing jimple private Instruction sentinel; private Hashtable h2bb, t2bb; private int bbcount; // statistics, number of BBs processed /** Constructs a new control flow graph for the given method. * @param m the method in question. * @see method_info */ public CFG(method_info m) { this.method = m; this.sentinel = new Instruction_Nop(); this.sentinel.next = m.instructions; m.instructions.prev = this.sentinel; // printInstructions(); // printExceptionTable(); eliminateJsrRets(); // printInstructions(); // printExceptionTable(); buildBBCFG(); // printBBs(); // printBBCFGSucc(); cfg.beginCode = true; m.cfg = this; if(cfg != null) firstInstruction = cfg.head; else firstInstruction = null; /* if (m.code_attr != null) { for (int i=0; i<m.code_attr.attributes.length; i++) { if (m.code_attr.attributes[i] instanceof LineNumberTable_attribute) { G.v().out.print(m.code_attr.attributes[i]); } } } */ } private void printBBCFGSucc() { BasicBlock b = this.cfg; while ( b!= null ) { G.v().out.print(b.id +" -> "); for (int i=0; i<b.succ.size(); i++) { BasicBlock bs = (BasicBlock)b.succ.elementAt(i); G.v().out.print(bs.id+" "); } G.v().out.println(); b = b.next; } } private void printBBCFGPred() { BasicBlock b = this.cfg; while ( b!= null ) { G.v().out.print(b.id +" <- "); for (int i=0; i<b.pred.size(); i++) { BasicBlock bs = (BasicBlock)b.pred.elementAt(i); G.v().out.print(bs.id+" "); } G.v().out.println(); b = b.next; } } private void printOneBasicBlock(BasicBlock b) { G.v().out.println("Block "+b.id); Instruction insn = b.head; G.v().out.println(insn); while (insn != b.tail && insn != null) { insn = insn.next; G.v().out.println(insn); } G.v().out.println(); } private void printBBHeadTail(BasicBlock fb) { BasicBlock b = fb; while (b != null) { G.v().out.println(b.head); G.v().out.println(b.tail+"\n"); b = b.next; } } private void printBBs() { BasicBlock bb = this.cfg; while (bb != null) { printOneBasicBlock(bb); bb = bb.next; } } private void printInstructions() { Instruction insn = method.instructions; while (insn != null) { G.v().out.println(insn); insn = insn.next; } } private void printExceptionTable() { Code_attribute ca = this.method.locate_code_attribute(); G.v().out.println("\nException table :"); G.v().out.println("start\tend\thandler"); for (int i=0; i<ca.exception_table.length; i++) { exception_table_entry ete = ca.exception_table[i]; G.v().out.println((ete.start_inst == null ? "null" : Integer.toString(ete.start_inst.label)) + " \t " + (ete.end_inst == null ? "null" : Integer.toString(ete.end_inst.label)) + " \t " + ete.handler_inst.label); } } // Constructs the actual control flow graph. Assumes the hash table // currently associates leaders with BasicBlocks, this function // builds the next[] and prev[] pointer arrays. private void buildBBCFG() { Object branches[], nextinsn; Code_attribute ca = method.locate_code_attribute(); { h2bb = new Hashtable(100,25); t2bb = new Hashtable(100,25); Instruction insn = this.sentinel.next; BasicBlock blast = null; if (insn != null) { Instruction tail = buildBasicBlock(insn); cfg = new BasicBlock(insn, tail); h2bb.put(insn, cfg); t2bb.put(tail, cfg); insn = tail.next; blast = cfg; } while (insn != null) { Instruction tail = buildBasicBlock(insn); BasicBlock block = new BasicBlock(insn, tail); blast.next = block; blast = block; h2bb.put(insn, block); t2bb.put(tail, block); insn = tail.next; } } BasicBlock block = cfg; while (block != null) { Instruction insn = block.tail; if (insn.branches) { if (insn instanceof Instruction_Athrow) { // see how many targets it can reach. Note that this is a // subset of the exception_table. HashSet ethandlers = new HashSet(); // exits this method, so start icount at 1 for (int i=0; i<ca.exception_table_length; i++) { exception_table_entry etentry = ca.exception_table[i]; if (insn.label >= etentry.start_inst.label && (etentry.end_inst==null || insn.label < etentry.end_inst.label)) { ethandlers.add(etentry.handler_inst); } } branches = ethandlers.toArray(); } else { branches = insn.branchpoints(insn.next); } if (branches != null) { block.succ.ensureCapacity(block.succ.size()+branches.length); for (int i=0; i<branches.length; i++) { if ( branches[i]!=null ) { BasicBlock bb = (BasicBlock)h2bb.get(branches[i]); if (bb == null) { G.v().out.println("Warning: " +"target of a branch is null"); G.v().out.println ( insn ); } else { block.succ.addElement(bb); bb.pred.addElement(block); } } } } } else if (block.next!=null) { // BB ended not with a branch, so just go to next block.succ.addElement(block.next); block.next.pred.addElement(block); } block = block.next; } // One final step, run through exception handlers and mark which // basic blocks begin their code for (int i=0; i<ca.exception_table_length; i++) { BasicBlock bb = (BasicBlock)h2bb.get( ca.exception_table[i].handler_inst); if ( bb == null ) { G.v().out.println("Warning: No basic block found for" + " start of exception handler code."); } else { bb.beginException = true; ca.exception_table[i].b = bb; } } } /* given the list of instructions head, this pulls off the front * basic block, terminates it with a null, and returns the next * instruction after. */ private static Instruction buildBasicBlock(Instruction head) { Instruction insn, next; insn = head; next = insn.next; if (next == null) return insn; do { if (insn.branches || next.labelled) break; else { insn = next; next = insn.next; } } while (next != null); return insn; } /* get a set of reachable instructions from an astore to matching ret. * it does not consider the exception handler as reachable now. */ private Set getReachableInsns(Instruction from, Instruction to) { Code_attribute codeAttribute = method.locate_code_attribute(); /* find all reachable blocks. */ Set reachableinsns = new HashSet(); LinkedList tovisit = new LinkedList(); reachableinsns.add(from); tovisit.add(from); while (!tovisit.isEmpty()) { Instruction insn = (Instruction)tovisit.removeFirst(); if (insn == to) continue; Instruction[] bps = null; if (insn.branches) { bps = insn.branchpoints(insn.next); } else { bps = new Instruction[1]; bps[0] = insn.next; } if (bps != null) { for (int i=0; i<bps.length; i++) { Instruction bp = bps[i]; if (bp != null && !reachableinsns.contains(bp)) { reachableinsns.add(bp); tovisit.add(bp); } } } } return reachableinsns; } /* We only handle simple cases. */ Map jsr2astore = new HashMap(); Map astore2ret = new HashMap(); LinkedList jsrorder = new LinkedList(); /* Eliminate subroutines ( JSR/RET instructions ) by inlining the routine bodies. */ private boolean eliminateJsrRets() { Instruction insn = this.sentinel; // find the last instruction, for copying blocks. while (insn.next != null) { insn = insn.next; } this.lastInstruction = insn; HashMap todoBlocks = new HashMap(); todoBlocks.put(this.sentinel.next, this.lastInstruction); LinkedList todoList = new LinkedList(); todoList.add(this.sentinel.next); while (!todoList.isEmpty()) { Instruction firstInsn = (Instruction)todoList.removeFirst(); Instruction lastInsn = (Instruction)todoBlocks.get(firstInsn); jsrorder.clear(); jsr2astore.clear(); astore2ret.clear(); if (findOutmostJsrs(firstInsn, lastInsn)) { HashMap newblocks = inliningJsrTargets(); todoBlocks.putAll(newblocks); todoList.addAll(newblocks.keySet()); } } /* patch exception table and others.*/ { method.instructions = this.sentinel.next; adjustExceptionTable(); adjustLineNumberTable(); adjustBranchTargets(); } // we should prune the code and exception table here. // remove any exception handler whose region is in a jsr/ret block. // pruneExceptionTable(); return true; } // find outmost jsr/ret pairs in a code area, all information is // saved in jsr2astore, and astore2ret // start : start instruction, inclusively. // end : the last instruction, inclusively. // return the last instruction encounted ( before end ) // the caller cleans jsr2astore, astore2ret private boolean findOutmostJsrs(Instruction start, Instruction end) { // use to put innerJsrs. HashSet innerJsrs = new HashSet(); boolean unusual = false; Instruction insn = start; do { if (insn instanceof Instruction_Jsr || insn instanceof Instruction_Jsr_w) { if (innerJsrs.contains(insn)) { // skip it insn = insn.next; continue; } Instruction astore = ((Instruction_branch)insn).target; if (! (astore instanceof Interface_Astore)) { unusual = true; break; } Instruction ret = findMatchingRet(astore, insn, innerJsrs); /* if (ret == null) { unusual = true; break; } */ jsrorder.addLast(insn); jsr2astore.put(insn, astore); astore2ret.put(astore, ret); } insn = insn.next; } while (insn != end.next); if (unusual) { G.v().out.println("Sorry, I cannot handle this method."); return false; } return true; } private Instruction findMatchingRet(Instruction astore, Instruction jsr, HashSet innerJsrs) { int astorenum = ((Interface_Astore)astore).getLocalNumber(); Instruction insn = astore.next; while (insn != null) { if (insn instanceof Instruction_Ret || insn instanceof Instruction_Ret_w) { int retnum = ((Interface_OneIntArg)insn).getIntArg(); if (astorenum == retnum) return insn; } else /* adjust the jsr inlining order. */ if (insn instanceof Instruction_Jsr || insn instanceof Instruction_Jsr_w) { innerJsrs.add(insn); } insn = insn.next; } return null; } // make copies of jsr/ret blocks // return new blocks private HashMap inliningJsrTargets() { /* for (int i=0, n=jsrorder.size(); i<n; i++) { Instruction jsr = (Instruction)jsrorder.get(i); Instruction astore = (Instruction)jsr2astore.get(jsr); Instruction ret = (Instruction)astore2ret.get(astore); G.v().out.println("jsr"+jsr.label+"\t" +"as"+astore.label+"\t" +"ret"+ret.label); } */ HashMap newblocks = new HashMap(); while (!jsrorder.isEmpty()) { Instruction jsr = (Instruction)jsrorder.removeFirst(); Instruction astore = (Instruction)jsr2astore.get(jsr); Instruction ret = (Instruction)astore2ret.get(astore); // make a copy of the code, append to the last instruction. Instruction newhead = makeCopyOf(astore, ret, jsr.next); // jsr is replaced by goto newhead // astore has been removed // ret is replaced by goto jsr.next Instruction_Goto togo = new Instruction_Goto(); togo.target = newhead; newhead.labelled = true; togo.label = jsr.label; togo.labelled = jsr.labelled; togo.prev = jsr.prev; togo.next = jsr.next; togo.prev.next = togo; togo.next.prev = togo; replacedInsns.put(jsr, togo); // just quick hack if (ret != null) { newblocks.put(newhead, this.lastInstruction); } } return newblocks; } /* make a copy of code between from and to exclusively, * fixup targets of branch instructions in the code. */ private Instruction makeCopyOf(Instruction astore, Instruction ret, Instruction target) { // do a quick hacker for ret == null if (ret == null) { return astore.next; } Instruction last = this.lastInstruction; Instruction headbefore = last; int curlabel = this.lastInstruction.label; // mapping from original instructions to new instructions. HashMap insnmap = new HashMap(); Instruction insn = astore.next; while (insn != ret && insn != null) { try { Instruction newone = (Instruction)insn.clone(); newone.label = ++curlabel; newone.prev = last; last.next = newone; last = newone; insnmap.put(insn, newone); } catch (CloneNotSupportedException e) { G.v().out.println("Error !"); } insn = insn.next; } // replace ret by a goto Instruction_Goto togo = new Instruction_Goto(); togo.target = target; target.labelled = true; togo.label = ++curlabel; last.next = togo; togo.prev = last; last = togo; this.lastInstruction = last; // The ret instruction is removed, insnmap.put(astore, headbefore.next); insnmap.put(ret, togo); // fixup targets in new instruction (only in the scope of // new instructions). // do not forget set target labelled as TRUE insn = headbefore.next; while (insn != last) { if (insn instanceof Instruction_branch) { Instruction oldtgt = ((Instruction_branch)insn).target; Instruction newtgt = (Instruction)insnmap.get(oldtgt); if (newtgt != null) { ((Instruction_branch)insn).target = newtgt; newtgt.labelled = true; } } else if (insn instanceof Instruction_Lookupswitch) { Instruction_Lookupswitch switchinsn = (Instruction_Lookupswitch)insn; Instruction newdefault = (Instruction)insnmap.get(switchinsn.default_inst); if (newdefault != null) { switchinsn.default_inst = newdefault; newdefault.labelled = true; } for (int i=0; i<switchinsn.match_insts.length; i++) { Instruction newtgt = (Instruction)insnmap.get(switchinsn.match_insts[i]); if (newtgt != null) { switchinsn.match_insts[i] = newtgt; newtgt.labelled = true; } } } else if (insn instanceof Instruction_Tableswitch) { Instruction_Tableswitch switchinsn = (Instruction_Tableswitch)insn; Instruction newdefault = (Instruction)insnmap.get(switchinsn.default_inst); if (newdefault != null) { switchinsn.default_inst = newdefault; newdefault.labelled = true; } for (int i=0; i<switchinsn.jump_insts.length; i++) { Instruction newtgt = (Instruction)insnmap.get(switchinsn.jump_insts[i]); if (newtgt != null) { switchinsn.jump_insts[i] = newtgt; newtgt.labelled = true; } } } insn = insn.next; } // do we need to copy a new exception table entry? // new exception table has new exception range, // and the new exception handler. { Code_attribute ca = method.locate_code_attribute(); LinkedList newentries = new LinkedList(); int orig_start_of_subr = headbefore.next.originalIndex; // inclusive int orig_end_of_subr = ret.originalIndex; // again, inclusive for (int i=0; i<ca.exception_table_length; i++) { exception_table_entry etentry = ca.exception_table[i]; int orig_start_of_trap = etentry.start_pc; // inclusive int orig_end_of_trap = etentry.end_pc; // exclusive if ( orig_start_of_trap < orig_end_of_subr && orig_end_of_trap > orig_start_of_subr) { // At least a portion of the cloned subroutine is trapped. exception_table_entry newone = new exception_table_entry(); if (orig_start_of_trap <= orig_start_of_subr) { newone.start_inst = headbefore.next; } else { newone.start_inst = (Instruction)insnmap.get(etentry.start_inst); } if (orig_end_of_trap > orig_end_of_subr) { newone.end_inst = null; // Representing the insn after // the last instruction in the // subr; we need to fix it if // we inline another subr. } else { newone.end_inst = (Instruction)insnmap.get(etentry.end_inst); } newone.handler_inst = (Instruction)insnmap.get(etentry.handler_inst); if (newone.handler_inst == null) newone.handler_inst = etentry.handler_inst; // We can leave newone.start_pc == 0 and newone.end_pc == 0. // since that cannot overlap the range of any other // subroutines that get inlined later. newentries.add(newone); } // Finally, fix up the old entry if its protected area // ran to the end of the method we have just lengthened: // patch its end marker to be the first // instruction in the subroutine we've just inlined. if (etentry.end_inst == null) { etentry.end_inst = headbefore.next; } } if (newentries.size() > 0) { ca.exception_table_length += newentries.size(); exception_table_entry[] newtable = new exception_table_entry[ca.exception_table_length]; System.arraycopy(ca.exception_table, 0, newtable, 0, ca.exception_table.length); for (int i=0, j=ca.exception_table.length; i<newentries.size(); i++, j++) { newtable[j] = (exception_table_entry)newentries.get(i); } ca.exception_table = newtable; } } return headbefore.next; } private void pruneExceptionTable() { HashSet invalidInsns = new HashSet(); Instruction insn = this.sentinel.next; do { if (insn instanceof Instruction_Jsr || insn instanceof Instruction_Jsr_w) { Instruction astore = ((Instruction_branch)insn).target; int astorenum = ((Interface_Astore)astore).getLocalNumber(); Instruction ret = astore.next; do { invalidInsns.add(ret); if (ret instanceof Instruction_Ret || ret instanceof Instruction_Ret_w) { int retnum = ((Interface_OneIntArg)ret).getIntArg(); if (astorenum == retnum) { insn = ret; break; } } ret = ret.next; } while (true); } insn = insn.next; } while (insn != null); Iterator it = invalidInsns.iterator(); while (it.hasNext()) { G.v().out.println(it.next()); } // pruning exception table LinkedList validEntries = new LinkedList(); Code_attribute codeAttribute = method.locate_code_attribute(); for(int i = 0; i < codeAttribute.exception_table_length; i++) { exception_table_entry entry = codeAttribute.exception_table[i]; if (!invalidInsns.contains(entry.start_inst)) { validEntries.add(entry); } } if (validEntries.size() != codeAttribute.exception_table_length) { exception_table_entry newtable[] = new exception_table_entry[validEntries.size()]; for (int i=0; i<newtable.length; i++) { newtable[i] = (exception_table_entry)validEntries.get(i); } codeAttribute.exception_table = newtable; codeAttribute.exception_table_length = newtable.length; } } /* if a jsr/astore/ret is replaced by some other instruction, it will be put on this table. */ private Hashtable replacedInsns = new Hashtable(); private void dumpReplacedInsns() { G.v().out.println("replaced table:"); Set keys = replacedInsns.keySet(); Iterator keyIt = keys.iterator(); while (keyIt.hasNext()) { Object key = keyIt.next(); Object value = replacedInsns.get(key); G.v().out.println(key + " ==> "+ value); } } /* do not forget set the target labelled as TRUE.*/ private void adjustBranchTargets() { Instruction insn = this.sentinel.next; while (insn != null) { if (insn instanceof Instruction_branch) { Instruction_branch binsn = (Instruction_branch)insn; Instruction newtgt = (Instruction)replacedInsns.get(binsn.target); if (newtgt != null) { binsn.target = newtgt; newtgt.labelled = true; } } else if (insn instanceof Instruction_Lookupswitch) { Instruction_Lookupswitch switchinsn = (Instruction_Lookupswitch)insn; Instruction newdefault = (Instruction)replacedInsns.get(switchinsn.default_inst); if (newdefault != null) { switchinsn.default_inst = newdefault; newdefault.labelled = true; } for (int i=0; i<switchinsn.npairs; i++) { Instruction newtgt = (Instruction)replacedInsns.get(switchinsn.match_insts[i]); if (newtgt != null) { switchinsn.match_insts[i] = newtgt; newtgt.labelled = true; } } } else if (insn instanceof Instruction_Tableswitch) { Instruction_Tableswitch switchinsn = (Instruction_Tableswitch)insn; Instruction newdefault = (Instruction)replacedInsns.get(switchinsn.default_inst); if (newdefault != null) { switchinsn.default_inst = newdefault; newdefault.labelled = true; } for (int i=0; i<switchinsn.high-switchinsn.low; i++) { Instruction newtgt = (Instruction)replacedInsns.get(switchinsn.jump_insts[i]); if (newtgt != null) { switchinsn.jump_insts[i] = newtgt; newtgt.labelled = true; } } } insn = insn.next; } } private void adjustExceptionTable() { Code_attribute codeAttribute = method.locate_code_attribute(); for(int i = 0; i < codeAttribute.exception_table_length; i++) { exception_table_entry entry = codeAttribute.exception_table[i]; Instruction oldinsn = entry.start_inst; Instruction newinsn = (Instruction)replacedInsns.get(oldinsn); if (newinsn != null) entry.start_inst = newinsn; oldinsn = entry.end_inst; if (entry.end_inst != null) { newinsn = (Instruction)replacedInsns.get(oldinsn); if (newinsn != null) entry.end_inst = newinsn; } oldinsn = entry.handler_inst; newinsn = (Instruction)replacedInsns.get(oldinsn); if (newinsn != null) entry.handler_inst = newinsn; } } private void adjustLineNumberTable() { if (!Options.v().keep_line_number()) return; if (method.code_attr == null) return; attribute_info[] attributes = method.code_attr.attributes; for (int i=0; i<attributes.length; i++) { if (attributes[i] instanceof LineNumberTable_attribute) { LineNumberTable_attribute lntattr = (LineNumberTable_attribute)attributes[i]; for (int j=0; j<lntattr.line_number_table.length; j++) { Instruction oldinst = lntattr.line_number_table[j].start_inst; Instruction newinst = (Instruction)replacedInsns.get(oldinst); if (newinst != null) lntattr.line_number_table[j].start_inst = newinst; } } } } /** Reconstructs the instruction stream by appending the Instruction * lists associated with each basic block. * <p> * Note that this joins up the basic block Instruction lists, and so * they will no longer end with <i>null</i> after this. * @return the head of the list of instructions. */ public Instruction reconstructInstructions() { if (cfg != null) return cfg.head; else return null; } /** Main.v() entry point for converting list of Instructions to Jimple statements; * performs flow analysis, constructs Jimple statements, and fixes jumps. * @param constant_pool constant pool of ClassFile. * @param this_class constant pool index of the CONSTANT_Class_info object for * this' class. * @return <i>true</i> if all ok, <i>false</i> if there was an error. * @see Stmt */ public boolean jimplify(cp_info constant_pool[],int this_class, JimpleBody listBody) { Util.v().setClassNameToAbbreviation(new HashMap()); Chain units = listBody.getUnits(); this.listBody = listBody; this.units = units; instructionToFirstStmt = new HashMap(); instructionToLastStmt = new HashMap(); jmethod = listBody.getMethod(); cm = Scene.v(); Util.v().setActiveClassManager(cm); //TypeArray.setClassManager(cm); //TypeStack.setClassManager(cm); Set initialLocals = new ArraySet(); List parameterTypes = jmethod.getParameterTypes(); // Initialize nameToLocal which is an index*Type->Local map, which is used // to determine local in bytecode references. { Code_attribute ca = method.locate_code_attribute(); LocalVariableTable_attribute la = ca.findLocalVariableTable(); Util.v().activeVariableTable = la; Util.v().activeConstantPool = constant_pool; Type thisType = RefType.v(jmethod.getDeclaringClass().getName()); boolean isStatic = Modifier.isStatic(jmethod.getModifiers()); int currentLocalIndex = 0; // Initialize the 'this' variable { if(!isStatic) { String name; if(!Util.v().useFaithfulNaming || la == null) name = "l0"; else { name = la.getLocalVariableName(constant_pool, currentLocalIndex); if (!Util.v().isValidJimpleName(name)) name = "l0"; } Local local = Jimple.v().newLocal(name, UnknownType.v()); listBody.getLocals().add(local); currentLocalIndex++; units.add(Jimple.v().newIdentityStmt(local, Jimple.v().newThisRef(jmethod.getDeclaringClass().getType()))); } } // Initialize parameters { Iterator typeIt = parameterTypes.iterator(); int argCount = 0; while(typeIt.hasNext()) { String name; Type type = (Type) typeIt.next(); if(!Util.v().useFaithfulNaming || la == null) name = "l" + currentLocalIndex; else { name = la.getLocalVariableName(constant_pool, currentLocalIndex); if (!Util.v().isValidJimpleName(name)) name = "l" + currentLocalIndex; } Local local = Jimple.v().newLocal(name, UnknownType.v()); initialLocals.add(local); listBody.getLocals().add(local); units.add(Jimple.v().newIdentityStmt(local, Jimple.v().newParameterRef(type, argCount))); if(type.equals(DoubleType.v()) || type.equals(LongType.v())) { currentLocalIndex += 2; } else { currentLocalIndex += 1; } argCount++; } } Util.v().resetEasyNames(); } jimplify(constant_pool,this_class); return true; } private void buildInsnCFGfromBBCFG() { BasicBlock block = cfg; while(block != null) { Instruction insn = block.head; while (insn != block.tail) { Instruction[] succs = new Instruction[1]; succs[0] = insn.next; insn.succs = succs; insn = insn.next; } { // The successors are the ones from the basic block. Vector bsucc = block.succ; int size = bsucc.size(); Instruction[] succs = new Instruction[size]; for(int i = 0; i<size; i++) succs[i] = ((BasicBlock)bsucc.elementAt(i)).head; insn.succs = succs; } block = block.next; } } private void printInsnCFG() { Instruction insn = cfg.head; while (insn != null) { G.v().out.println(insn + " --> " + makeString(insn.succs)); insn = insn.next; } } private String makeString(Object[] objs) { String buf = ""; for (int i=0; i<objs.length; i++) buf += " , "+objs[i]; return buf; } /** Main.v() entry point for converting list of Instructions to Jimple statements; * performs flow analysis, constructs Jimple statements, and fixes jumps. * @param constant_pool constant pool of ClassFile. * @param this_class constant pool index of the CONSTANT_Class_info object for * this' class. * @param clearStacks if <i>true</i> semantic stacks will be deleted after * the process is complete. * @return <i>true</i> if all ok, <i>false</i> if there was an error. * @see CFG#jimplify(cp_info[], int) * @see Stmt */ void jimplify(cp_info constant_pool[],int this_class) { Code_attribute codeAttribute = method.locate_code_attribute(); Set handlerInstructions = new ArraySet(); Map handlerInstructionToException = new HashMap(); Map instructionToTypeStack; Map instructionToPostTypeStack; { // build graph in buildInsnCFGfromBBCFG(); // Put in successors due to exception handlers { for(int i = 0; i < codeAttribute.exception_table_length; i++) { Instruction startIns = codeAttribute.exception_table[i].start_inst; Instruction endIns = codeAttribute.exception_table[i].end_inst; Instruction handlerIns = codeAttribute.exception_table[i].handler_inst; handlerInstructions.add(handlerIns); // Determine exception to catch { int catchType = codeAttribute.exception_table[i].catch_type; SootClass exception; if(catchType != 0) { CONSTANT_Class_info classinfo = (CONSTANT_Class_info) constant_pool[catchType]; String name = ((CONSTANT_Utf8_info) (constant_pool[classinfo.name_index])). convert(); name = name.replace('/', '.'); exception = cm.getSootClass(name); } else exception = cm.getSootClass("java.lang.Throwable"); handlerInstructionToException.put(handlerIns, exception); } if(startIns == endIns) throw new RuntimeException("Empty catch range for exception handler"); Instruction ins = startIns; for(;;) { Instruction[] succs = ins.succs; Instruction[] newsuccs = new Instruction[succs.length+1]; System.arraycopy(succs, 0, newsuccs, 0, succs.length); newsuccs[succs.length] = handlerIns; ins.succs = newsuccs; ins = ins.next; if (ins == endIns || ins == null) break; } } } } Set reachableInstructions = new HashSet(); // Mark all the reachable instructions { LinkedList instructionsToVisit = new LinkedList(); reachableInstructions.add(firstInstruction); instructionsToVisit.addLast(firstInstruction); while( !instructionsToVisit.isEmpty()) { Instruction ins = (Instruction) instructionsToVisit.removeFirst(); Instruction[] succs = ins.succs; for (int i=0; i<succs.length; i++) { Instruction succ = succs[i]; if(!reachableInstructions.contains(succ)) { reachableInstructions.add(succ); instructionsToVisit.addLast(succ); } } } } /* // Check to see if any instruction is unmarked. { BasicBlock b = cfg; while(b != null) { Instruction ins = b.head; while(ins != null) { if(!reachableInstructions.contains(ins)) throw new RuntimeException("Method to jimplify contains unreachable code! (not handled for now)"); ins = ins.next; } b = b.next; } } */ // Perform the flow analysis, and build up instructionToTypeStack and instructionToLocalArray { instructionToTypeStack = new HashMap(); instructionToPostTypeStack = new HashMap(); Set visitedInstructions = new HashSet(); List changedInstructions = new ArrayList(); TypeStack initialTypeStack; // Build up initial type stack and initial local array (for the first instruction) { initialTypeStack = TypeStack.v(); // the empty stack with nothing on it. } // Get the loop cranked up. { instructionToTypeStack.put(firstInstruction, initialTypeStack); visitedInstructions.add(firstInstruction); changedInstructions.add(firstInstruction); } { while(!changedInstructions.isEmpty()) { Instruction ins = (Instruction) changedInstructions.get(0); changedInstructions.remove(0); OutFlow ret = processFlow(ins, (TypeStack) instructionToTypeStack.get(ins), constant_pool); instructionToPostTypeStack.put(ins, ret.typeStack); Instruction[] successors = ins.succs; for(int i = 0; i < successors.length; i++) { Instruction s = successors[i]; if(!visitedInstructions.contains(s)) { // Special case for the first time visiting. if(handlerInstructions.contains(s)) { TypeStack exceptionTypeStack = (TypeStack.v()).push(RefType.v( ((SootClass) handlerInstructionToException.get(s)).getName())); instructionToTypeStack.put(s, exceptionTypeStack); } else { instructionToTypeStack.put(s, ret.typeStack); } visitedInstructions.add(s); changedInstructions.add(s); // G.v().out.println("adding successor: " + s); } else { // G.v().out.println("considering successor: " + s); TypeStack newTypeStack, oldTypeStack = (TypeStack) instructionToTypeStack.get(s); if(handlerInstructions.contains(s)) { // The type stack for an instruction handler should always be that of // single object on the stack. TypeStack exceptionTypeStack = (TypeStack.v()).push(RefType.v( ((SootClass) handlerInstructionToException.get(s)).getName())); newTypeStack = exceptionTypeStack; } else { try { newTypeStack = ret.typeStack.merge(oldTypeStack); } catch (RuntimeException re) { G.v().out.println("Considering "+s); throw re; } } if(!newTypeStack.equals(oldTypeStack)) { changedInstructions.add(s); // G.v().out.println("requires a revisit: " + s); } instructionToTypeStack.put(s, newTypeStack); } } } } } // Print out instructions + their localArray + typeStack { Instruction ins = firstInstruction; // G.v().out.println(); while(ins != null) { TypeStack typeStack = (TypeStack) instructionToTypeStack.get(ins); // TypeArray typeArray = (TypeArray) instructionToLocalArray.get(ins); /* G.v().out.println("[TypeArray]"); typeArray.print(G.v().out); G.v().out.println(); G.v().out.println("[TypeStack]"); typeStack.print(G.v().out); G.v().out.println(); G.v().out.println(ins.toString()); */ ins = ins.next; /* G.v().out.println(); G.v().out.println(); */ } } // G.v().out.println("Producing Jimple code..."); // Jimplify each statement { BasicBlock b = cfg; while(b != null) { Instruction ins = b.head; b.statements = new ArrayList(); List blockStatements = b.statements; for (;;) { List statementsForIns = new ArrayList(); if(reachableInstructions.contains(ins)) generateJimple(ins, (TypeStack) instructionToTypeStack.get(ins), (TypeStack) instructionToPostTypeStack.get(ins), constant_pool, statementsForIns, b); else statementsForIns.add(Jimple.v().newNopStmt()); if(!statementsForIns.isEmpty()) { for(int i = 0; i < statementsForIns.size(); i++) { units.add(statementsForIns.get(i)); blockStatements.add(statementsForIns.get(i)); } instructionToFirstStmt.put(ins, statementsForIns.get(0)); instructionToLastStmt.put(ins, statementsForIns.get(statementsForIns.size() - 1)); } if (ins == b.tail) break; ins = ins.next; } b = b.next; } } jimpleTargetFixup(); // fix up jump targets /* // Print out basic blocks { BasicBlock b = cfg; G.v().out.println("Basic blocks for: " + jmethod.getName()); while(b != null) { Instruction ins = b.head; G.v().out.println(); while(ins != null) { G.v().out.println(ins.toString()); ins = ins.next; } b = b.next; } } */ // Insert beginCatch/endCatch statements for exception handling { Map targetToHandler = new HashMap(); for(int i = 0; i < codeAttribute.exception_table_length; i++) { Instruction startIns = codeAttribute.exception_table[i].start_inst; Instruction endIns = codeAttribute.exception_table[i].end_inst; Instruction targetIns = codeAttribute.exception_table[i].handler_inst; if(!instructionToFirstStmt.containsKey(startIns) || (endIns != null && (!instructionToLastStmt.containsKey(endIns)))) { throw new RuntimeException("Exception range does not coincide with jimple instructions"); } if(!instructionToFirstStmt.containsKey(targetIns)) { throw new RuntimeException ("Exception handler does not coincide with jimple instruction"); } SootClass exception; // Determine exception to catch { int catchType = codeAttribute.exception_table[i].catch_type; if(catchType != 0) { CONSTANT_Class_info classinfo = (CONSTANT_Class_info) constant_pool[catchType]; String name = ((CONSTANT_Utf8_info) (constant_pool[classinfo.name_index])).convert(); name = name.replace('/', '.'); exception = cm.getSootClass(name); } else exception = cm.getSootClass("java.lang.Throwable"); } Stmt newTarget; // Insert assignment of exception { Stmt firstTargetStmt = (Stmt) instructionToFirstStmt.get(targetIns); if(targetToHandler.containsKey(firstTargetStmt)) newTarget = (Stmt) targetToHandler.get(firstTargetStmt); else { Local local = Util.v().getLocalCreatingIfNecessary(listBody, "$stack0",UnknownType.v()); newTarget = Jimple.v().newIdentityStmt(local, Jimple.v().newCaughtExceptionRef()); units.insertBefore(newTarget, firstTargetStmt); targetToHandler.put(firstTargetStmt, newTarget); } } // Insert trap { Stmt firstStmt = (Stmt)instructionToFirstStmt.get(startIns); Stmt afterEndStmt; if (endIns == null) { // A kludge which isn't really correct, but // gets us closer to correctness (until we // clean up the rest of Soot to properly // represent Traps which extend to the end // of a method): if the protected code extends // to the end of the method, use the last Stmt // as the endUnit of the Trap, even though // that will leave the last unit outside // the protected area. afterEndStmt = (Stmt) units.getLast(); } else { afterEndStmt = (Stmt) instructionToLastStmt.get(endIns); IdentityStmt catchStart = (IdentityStmt) targetToHandler.get(afterEndStmt); // (Cast to IdentityStmt as an assertion check.) if (catchStart != null) { // The protected region extends to the beginning of an // exception handler, so we need to reset afterEndStmt // to the identity statement which we have inserted // before the old afterEndStmt. if (catchStart != units.getPredOf(afterEndStmt)) { throw new IllegalStateException("Assertion failure: catchStart != pred of afterEndStmt"); } afterEndStmt = catchStart; } } Trap trap = Jimple.v().newTrap(exception, firstStmt, afterEndStmt, newTarget); listBody.getTraps().add(trap); } } } /* convert line number table to tags attached to statements */ if (Options.v().keep_line_number()) { HashMap stmtstags = new HashMap(); LinkedList startstmts = new LinkedList(); attribute_info[] attrs = codeAttribute.attributes; for (int i=0; i<attrs.length; i++) { if (attrs[i] instanceof LineNumberTable_attribute) { LineNumberTable_attribute lntattr = (LineNumberTable_attribute)attrs[i]; for (int j=0; j<lntattr.line_number_table.length; j++) { Stmt start_stmt = (Stmt)instructionToFirstStmt.get( lntattr.line_number_table[j].start_inst); if (start_stmt != null) { LineNumberTag lntag= new LineNumberTag( lntattr.line_number_table[j].line_number); stmtstags.put(start_stmt, lntag); startstmts.add(start_stmt); } } } } /* attach line number tag to each statement. */ for (int i=0; i<startstmts.size(); i++) { Stmt stmt = (Stmt)startstmts.get(i); Tag tag = (Tag)stmtstags.get(stmt); stmt.addTag(tag); stmt = (Stmt)units.getSuccOf(stmt); while (stmt != null && !stmtstags.containsKey(stmt)) { stmt.addTag(tag); stmt = (Stmt)units.getSuccOf(stmt); } } } } private Type byteCodeTypeOf(Type type) { if(type.equals(ShortType.v()) || type.equals(CharType.v()) || type.equals(ByteType.v()) || type.equals(BooleanType.v())) { return IntType.v(); } else return type; } OutFlow processFlow(Instruction ins, TypeStack typeStack, cp_info[] constant_pool) { int x; x = ((int)(ins.code))&0xff; switch(x) { case ByteCode.BIPUSH: typeStack = typeStack.push(IntType.v()); break; case ByteCode.SIPUSH: typeStack = typeStack.push(IntType.v()); break; case ByteCode.LDC1: return processCPEntry(constant_pool, ((Instruction_Ldc1)ins).arg_b, typeStack, jmethod); case ByteCode.LDC2: case ByteCode.LDC2W: return processCPEntry(constant_pool, ((Instruction_intindex)ins).arg_i, typeStack, jmethod); case ByteCode.ACONST_NULL: typeStack = typeStack.push(RefType.v("java.lang.Object")); break; case ByteCode.ICONST_M1: case ByteCode.ICONST_0: case ByteCode.ICONST_1: case ByteCode.ICONST_2: case ByteCode.ICONST_3: case ByteCode.ICONST_4: case ByteCode.ICONST_5: typeStack = typeStack.push(IntType.v()); break; case ByteCode.LCONST_0: case ByteCode.LCONST_1: typeStack = typeStack.push(LongType.v()); typeStack = typeStack.push(Long2ndHalfType.v()); break; case ByteCode.FCONST_0: case ByteCode.FCONST_1: case ByteCode.FCONST_2: typeStack = typeStack.push(FloatType.v()); break; case ByteCode.DCONST_0: case ByteCode.DCONST_1: typeStack = typeStack.push(DoubleType.v()); typeStack = typeStack.push(Double2ndHalfType.v()); break; case ByteCode.ILOAD: typeStack = typeStack.push(IntType.v()); break; case ByteCode.FLOAD: typeStack = typeStack.push(FloatType.v()); break; case ByteCode.ALOAD: typeStack = typeStack.push(RefType.v("java.lang.Object")); // this is highly imprecise break; case ByteCode.DLOAD: typeStack = typeStack.push(DoubleType.v()); typeStack = typeStack.push(Double2ndHalfType.v()); break; case ByteCode.LLOAD: typeStack = typeStack.push(LongType.v()); typeStack = typeStack.push(Long2ndHalfType.v()); break; case ByteCode.ILOAD_0: case ByteCode.ILOAD_1: case ByteCode.ILOAD_2: case ByteCode.ILOAD_3: typeStack = typeStack.push(IntType.v()); break; case ByteCode.FLOAD_0: case ByteCode.FLOAD_1: case ByteCode.FLOAD_2: case ByteCode.FLOAD_3: typeStack = typeStack.push(FloatType.v()); break; case ByteCode.ALOAD_0: case ByteCode.ALOAD_1: case ByteCode.ALOAD_2: case ByteCode.ALOAD_3: typeStack = typeStack.push(RefType.v("java.lang.Object")); // this is highly imprecise break; case ByteCode.LLOAD_0: case ByteCode.LLOAD_1: case ByteCode.LLOAD_2: case ByteCode.LLOAD_3: typeStack = typeStack.push(LongType.v()); typeStack = typeStack.push(Long2ndHalfType.v()); break; case ByteCode.DLOAD_0: case ByteCode.DLOAD_1: case ByteCode.DLOAD_2: case ByteCode.DLOAD_3: typeStack = typeStack.push(DoubleType.v()); typeStack = typeStack.push(Double2ndHalfType.v()); break; case ByteCode.ISTORE: typeStack = popSafe(typeStack, IntType.v()); break; case ByteCode.FSTORE: typeStack = popSafe(typeStack, FloatType.v()); break; case ByteCode.ASTORE: typeStack = typeStack.pop(); break; case ByteCode.LSTORE: typeStack = popSafe(typeStack, Long2ndHalfType.v()); typeStack = popSafe(typeStack, LongType.v()); break; case ByteCode.DSTORE: typeStack = popSafe(typeStack, Double2ndHalfType.v()); typeStack = popSafe(typeStack, DoubleType.v()); break; case ByteCode.ISTORE_0: case ByteCode.ISTORE_1: case ByteCode.ISTORE_2: case ByteCode.ISTORE_3: typeStack = popSafe(typeStack, IntType.v()); break; case ByteCode.FSTORE_0: case ByteCode.FSTORE_1: case ByteCode.FSTORE_2: case ByteCode.FSTORE_3: typeStack = popSafe(typeStack, FloatType.v()); break; case ByteCode.ASTORE_0: case ByteCode.ASTORE_1: case ByteCode.ASTORE_2: case ByteCode.ASTORE_3: if(!(typeStack.top() instanceof StmtAddressType) && !(typeStack.top() instanceof RefType) && !(typeStack.top() instanceof ArrayType)) { throw new RuntimeException("Astore failed, invalid stack type: " + typeStack.top()); } typeStack = typeStack.pop(); break; case ByteCode.LSTORE_0: case ByteCode.LSTORE_1: case ByteCode.LSTORE_2: case ByteCode.LSTORE_3: typeStack = popSafe(typeStack, Long2ndHalfType.v()); typeStack = popSafe(typeStack, LongType.v()); break; case ByteCode.DSTORE_0: case ByteCode.DSTORE_1: case ByteCode.DSTORE_2: case ByteCode.DSTORE_3: typeStack = popSafe(typeStack, Double2ndHalfType.v()); typeStack = popSafe(typeStack, DoubleType.v()); break; case ByteCode.IINC: break; case ByteCode.WIDE: throw new RuntimeException("Wide instruction should not be encountered"); // break; case ByteCode.NEWARRAY: { typeStack = popSafe(typeStack, IntType.v()); Type baseType = (Type) jimpleTypeOfAtype(((Instruction_Newarray)ins).atype); typeStack = typeStack.push(ArrayType.v(baseType, 1)); break; } case ByteCode.ANEWARRAY: { CONSTANT_Class_info c = (CONSTANT_Class_info) constant_pool[ ((Instruction_Anewarray)ins).arg_i]; String name = ((CONSTANT_Utf8_info) (constant_pool[c.name_index])).convert(); name = name.replace('/', '.'); typeStack = popSafe(typeStack, IntType.v()); typeStack = typeStack.push(ArrayType.v( RefType.v(name), 1)); break; } case ByteCode.MULTIANEWARRAY: { int bdims = (int)(((Instruction_Multianewarray)ins).dims); CONSTANT_Class_info c = (CONSTANT_Class_info) constant_pool[ ((Instruction_Multianewarray)ins).arg_i]; String arrayDescriptor = ((CONSTANT_Utf8_info) (constant_pool[c.name_index])).convert(); ArrayType arrayType = (ArrayType) Util.v().jimpleTypeOfFieldDescriptor(cm, arrayDescriptor); for (int j=0;j<bdims;j++) typeStack = popSafe(typeStack, IntType.v()); typeStack = typeStack.push(arrayType); break; } case ByteCode.ARRAYLENGTH: typeStack = popSafeRefType(typeStack); typeStack = typeStack.push(IntType.v()); break; case ByteCode.IALOAD: case ByteCode.BALOAD: case ByteCode.CALOAD: case ByteCode.SALOAD: typeStack = popSafe(typeStack, IntType.v()); typeStack = popSafeRefType(typeStack); typeStack = typeStack.push(IntType.v()); break; case ByteCode.FALOAD: typeStack = popSafe(typeStack, FloatType.v()); typeStack = popSafeRefType(typeStack); typeStack = typeStack.push(FloatType.v()); break; case ByteCode.AALOAD: { typeStack = popSafe(typeStack, IntType.v()); if(typeStack.top() instanceof ArrayType) { ArrayType arrayType = (ArrayType) typeStack.top(); typeStack = popSafeRefType(typeStack); if(arrayType.numDimensions == 1) typeStack = typeStack.push(arrayType.baseType); else typeStack = typeStack.push(ArrayType.v(arrayType.baseType, arrayType.numDimensions - 1)); } else { // it's a null object typeStack = popSafeRefType(typeStack); typeStack = typeStack.push(RefType.v("java.lang.Object")); } break; } case ByteCode.LALOAD: typeStack = popSafe(typeStack, IntType.v()); typeStack = popSafeRefType(typeStack); typeStack = typeStack.push(LongType.v()); typeStack = typeStack.push(Long2ndHalfType.v()); break; case ByteCode.DALOAD: typeStack = popSafe(typeStack, IntType.v()); typeStack = popSafeRefType(typeStack); typeStack = typeStack.push(DoubleType.v()); typeStack = typeStack.push(Double2ndHalfType.v()); break; case ByteCode.IASTORE: case ByteCode.BASTORE: case ByteCode.CASTORE: case ByteCode.SASTORE: typeStack = popSafe(typeStack, IntType.v()); typeStack = popSafe(typeStack, IntType.v()); typeStack = popSafeRefType(typeStack); break; case ByteCode.AASTORE: typeStack = popSafeRefType(typeStack); typeStack = popSafe(typeStack, IntType.v()); typeStack = popSafeRefType(typeStack); break; case ByteCode.FASTORE: typeStack = popSafe(typeStack, FloatType.v()); typeStack = popSafe(typeStack, IntType.v()); typeStack = popSafeRefType(typeStack); break; case ByteCode.LASTORE: typeStack = popSafe(typeStack, Long2ndHalfType.v()); typeStack = popSafe(typeStack, LongType.v()); typeStack = popSafe(typeStack, IntType.v()); typeStack = popSafeRefType(typeStack); break; case ByteCode.DASTORE: typeStack = popSafe(typeStack, Double2ndHalfType.v()); typeStack = popSafe(typeStack, DoubleType.v()); typeStack = popSafe(typeStack, IntType.v()); typeStack = popSafeRefType(typeStack); break; case ByteCode.NOP: break; case ByteCode.POP: typeStack = typeStack.pop(); break; case ByteCode.POP2: typeStack = typeStack.pop(); typeStack = typeStack.pop(); break; case ByteCode.DUP: typeStack = typeStack.push(typeStack.top()); break; case ByteCode.DUP2: { Type topType = typeStack.get(typeStack.topIndex()), secondType = typeStack.get(typeStack.topIndex()-1); typeStack = (typeStack.push(secondType)).push(topType); break; } case ByteCode.DUP_X1: { Type topType = typeStack.get(typeStack.topIndex()), secondType = typeStack.get(typeStack.topIndex()-1); typeStack = typeStack.pop().pop(); typeStack = typeStack.push(topType).push(secondType).push(topType); break; } case ByteCode.DUP_X2: { Type topType = typeStack.get(typeStack.topIndex()), secondType = typeStack.get(typeStack.topIndex()-1), thirdType = typeStack.get(typeStack.topIndex()-2); typeStack = typeStack.pop().pop().pop(); typeStack = typeStack.push(topType).push(thirdType).push(secondType).push(topType); break; } case ByteCode.DUP2_X1: { Type topType = typeStack.get(typeStack.topIndex()), secondType = typeStack.get(typeStack.topIndex()-1), thirdType = typeStack.get(typeStack.topIndex()-2); typeStack = typeStack.pop().pop().pop(); typeStack = typeStack.push(secondType).push(topType). push(thirdType).push(secondType).push(topType); break; } case ByteCode.DUP2_X2: { Type topType = typeStack.get(typeStack.topIndex()), secondType = typeStack.get(typeStack.topIndex()-1), thirdType = typeStack.get(typeStack.topIndex()-2), fourthType = typeStack.get(typeStack.topIndex()-3); typeStack = typeStack.pop().pop().pop().pop(); typeStack = typeStack.push(secondType).push(topType). push(fourthType).push(thirdType).push(secondType).push(topType); break; } case ByteCode.SWAP: { Type topType = typeStack.top(); typeStack = typeStack.pop(); Type secondType = typeStack.top(); typeStack = typeStack.pop(); typeStack = typeStack.push(topType); typeStack = typeStack.push(secondType); break; } case ByteCode.IADD: case ByteCode.ISUB: case ByteCode.IMUL: case ByteCode.IDIV: case ByteCode.IREM: case ByteCode.ISHL: case ByteCode.ISHR: case ByteCode.IUSHR: case ByteCode.IAND: case ByteCode.IOR: case ByteCode.IXOR: typeStack = popSafe(typeStack, IntType.v()); typeStack = popSafe(typeStack, IntType.v()); typeStack = typeStack.push(IntType.v()); break; case ByteCode.LUSHR: case ByteCode.LSHR: case ByteCode.LSHL: typeStack = popSafe(typeStack, IntType.v()); typeStack = popSafe(typeStack, Long2ndHalfType.v()); typeStack = popSafe(typeStack, LongType.v()); typeStack = typeStack.push(LongType.v()); typeStack = typeStack.push(Long2ndHalfType.v()); break; case ByteCode.LREM: case ByteCode.LDIV: case ByteCode.LMUL: case ByteCode.LSUB: case ByteCode.LADD: case ByteCode.LAND: case ByteCode.LOR: case ByteCode.LXOR: typeStack = popSafe(typeStack, Long2ndHalfType.v()); typeStack = popSafe(typeStack, LongType.v()); typeStack = popSafe(typeStack, Long2ndHalfType.v()); typeStack = popSafe(typeStack, LongType.v()); typeStack = typeStack.push(LongType.v()); typeStack = typeStack.push(Long2ndHalfType.v()); break; case ByteCode.FREM: case ByteCode.FDIV: case ByteCode.FMUL: case ByteCode.FSUB: case ByteCode.FADD: typeStack = popSafe(typeStack, FloatType.v()); typeStack = popSafe(typeStack, FloatType.v()); typeStack = typeStack.push(FloatType.v()); break; case ByteCode.DREM: case ByteCode.DDIV: case ByteCode.DMUL: case ByteCode.DSUB: case ByteCode.DADD: typeStack = popSafe(typeStack, Double2ndHalfType.v()); typeStack = popSafe(typeStack, DoubleType.v()); typeStack = popSafe(typeStack, Double2ndHalfType.v()); typeStack = popSafe(typeStack, DoubleType.v()); typeStack = typeStack.push(DoubleType.v()); typeStack = typeStack.push(Double2ndHalfType.v()); break; case ByteCode.INEG: case ByteCode.LNEG: case ByteCode.FNEG: case ByteCode.DNEG: // Doesn't check to see if the required types are on the stack, but it should // if it wanted to be safe. break; case ByteCode.I2L: typeStack = popSafe(typeStack, IntType.v()); typeStack = typeStack.push(LongType.v()); typeStack = typeStack.push(Long2ndHalfType.v()); break; case ByteCode.I2F: typeStack = popSafe(typeStack, IntType.v()); typeStack = typeStack.push(FloatType.v()); break; case ByteCode.I2D: typeStack = popSafe(typeStack, IntType.v()); typeStack = typeStack.push(DoubleType.v()); typeStack = typeStack.push(Double2ndHalfType.v()); break; case ByteCode.L2I: typeStack = popSafe(typeStack, Long2ndHalfType.v()); typeStack = popSafe(typeStack, LongType.v()); typeStack = typeStack.push(IntType.v()); break; case ByteCode.L2F: typeStack = popSafe(typeStack, Long2ndHalfType.v()); typeStack = popSafe(typeStack, LongType.v()); typeStack = typeStack.push(FloatType.v()); break; case ByteCode.L2D: typeStack = popSafe(typeStack, Long2ndHalfType.v()); typeStack = popSafe(typeStack, LongType.v()); typeStack = typeStack.push(DoubleType.v()); typeStack = typeStack.push(Double2ndHalfType.v()); break; case ByteCode.F2I: typeStack = popSafe(typeStack, FloatType.v()); typeStack = typeStack.push(IntType.v()); break; case ByteCode.F2L: typeStack = popSafe(typeStack, FloatType.v()); typeStack = typeStack.push(LongType.v()); typeStack = typeStack.push(Long2ndHalfType.v()); break; case ByteCode.F2D: typeStack = popSafe(typeStack, FloatType.v()); typeStack = typeStack.push(DoubleType.v()); typeStack = typeStack.push(Double2ndHalfType.v()); break; case ByteCode.D2I: typeStack = popSafe(typeStack, Double2ndHalfType.v()); typeStack = popSafe(typeStack, DoubleType.v()); typeStack = typeStack.push(IntType.v()); break; case ByteCode.D2L: typeStack = popSafe(typeStack, Double2ndHalfType.v()); typeStack = popSafe(typeStack, DoubleType.v()); typeStack = typeStack.push(LongType.v()); typeStack = typeStack.push(Long2ndHalfType.v()); break; case ByteCode.D2F: typeStack = popSafe(typeStack, Double2ndHalfType.v()); typeStack = popSafe(typeStack, DoubleType.v()); typeStack = typeStack.push(FloatType.v()); break; case ByteCode.INT2BYTE: break; case ByteCode.INT2CHAR: break; case ByteCode.INT2SHORT: break; case ByteCode.IFEQ: case ByteCode.IFGT: case ByteCode.IFLT: case ByteCode.IFLE: case ByteCode.IFNE: case ByteCode.IFGE: typeStack = popSafe(typeStack, IntType.v()); break; case ByteCode.IFNULL: case ByteCode.IFNONNULL: typeStack = popSafeRefType(typeStack); break; case ByteCode.IF_ICMPEQ: case ByteCode.IF_ICMPLT: case ByteCode.IF_ICMPLE: case ByteCode.IF_ICMPNE: case ByteCode.IF_ICMPGT: case ByteCode.IF_ICMPGE: typeStack = popSafe(typeStack, IntType.v()); typeStack = popSafe(typeStack, IntType.v()); break; case ByteCode.LCMP: typeStack = popSafe(typeStack, Long2ndHalfType.v()); typeStack = popSafe(typeStack, LongType.v()); typeStack = popSafe(typeStack, Long2ndHalfType.v()); typeStack = popSafe(typeStack, LongType.v()); typeStack = typeStack.push(IntType.v()); break; case ByteCode.FCMPL: case ByteCode.FCMPG: typeStack = popSafe(typeStack, FloatType.v()); typeStack = popSafe(typeStack, FloatType.v()); typeStack = typeStack.push(IntType.v()); break; case ByteCode.DCMPL: case ByteCode.DCMPG: typeStack = popSafe(typeStack, Double2ndHalfType.v()); typeStack = popSafe(typeStack, DoubleType.v()); typeStack = popSafe(typeStack, Double2ndHalfType.v()); typeStack = popSafe(typeStack, DoubleType.v()); typeStack = typeStack.push(IntType.v()); break; case ByteCode.IF_ACMPEQ: case ByteCode.IF_ACMPNE: typeStack = popSafeRefType(typeStack); typeStack = popSafeRefType(typeStack); break; case ByteCode.GOTO: case ByteCode.GOTO_W: break; case ByteCode.JSR: case ByteCode.JSR_W: typeStack = typeStack.push(StmtAddressType.v()); break; case ByteCode.RET: break; case ByteCode.RET_W: break; case ByteCode.RETURN: break; case ByteCode.IRETURN: typeStack = popSafe(typeStack, IntType.v()); break; case ByteCode.FRETURN: typeStack = popSafe(typeStack, FloatType.v()); break; case ByteCode.ARETURN: typeStack = popSafeRefType(typeStack); break; case ByteCode.DRETURN: typeStack = popSafe(typeStack, Double2ndHalfType.v()); typeStack = popSafe(typeStack, DoubleType.v()); break; case ByteCode.LRETURN: typeStack = popSafe(typeStack, Long2ndHalfType.v()); typeStack = popSafe(typeStack, LongType.v()); break; case ByteCode.BREAKPOINT: break; case ByteCode.TABLESWITCH: typeStack = popSafe(typeStack, IntType.v()); break; case ByteCode.LOOKUPSWITCH: typeStack = popSafe(typeStack, IntType.v()); break; case ByteCode.PUTFIELD: { Type type = byteCodeTypeOf(jimpleTypeOfFieldInFieldRef(cm, constant_pool, ((Instruction_Putfield)ins).arg_i)); if(type.equals(DoubleType.v())) { typeStack = popSafe(typeStack, Double2ndHalfType.v()); typeStack = popSafe(typeStack, DoubleType.v()); } else if(type.equals(LongType.v())) { typeStack = popSafe(typeStack, Long2ndHalfType.v()); typeStack = popSafe(typeStack, LongType.v()); } else if(type instanceof RefType) typeStack = popSafeRefType(typeStack); else typeStack = popSafe(typeStack, type); typeStack = popSafeRefType(typeStack); break; } case ByteCode.GETFIELD: { Type type = byteCodeTypeOf(jimpleTypeOfFieldInFieldRef(cm, constant_pool, ((Instruction_Getfield)ins).arg_i)); typeStack = popSafeRefType(typeStack); if (type.equals(DoubleType.v())) { typeStack = typeStack.push(DoubleType.v()); typeStack = typeStack.push(Double2ndHalfType.v()); } else if(type.equals(LongType.v())) { typeStack = typeStack.push(LongType.v()); typeStack = typeStack.push(Long2ndHalfType.v()); } else typeStack = typeStack.push(type); break; } case ByteCode.PUTSTATIC: { Type type = byteCodeTypeOf(jimpleTypeOfFieldInFieldRef(cm, constant_pool, ((Instruction_Putstatic)ins).arg_i)); if(type.equals(DoubleType.v())) { typeStack = popSafe(typeStack, Double2ndHalfType.v()); typeStack = popSafe(typeStack, DoubleType.v()); } else if(type.equals(LongType.v())) { typeStack = popSafe(typeStack, Long2ndHalfType.v()); typeStack = popSafe(typeStack, LongType.v()); } else if(type instanceof RefType) typeStack = popSafeRefType(typeStack); else typeStack = popSafe(typeStack, type); break; } case ByteCode.GETSTATIC: { Type type = byteCodeTypeOf(jimpleTypeOfFieldInFieldRef(cm, constant_pool, ((Instruction_Getstatic)ins).arg_i)); if (type.equals(DoubleType.v())) { typeStack = typeStack.push(DoubleType.v()); typeStack = typeStack.push(Double2ndHalfType.v()); } else if(type.equals(LongType.v())) { typeStack = typeStack.push(LongType.v()); typeStack = typeStack.push(Long2ndHalfType.v()); } else typeStack = typeStack.push(type); break; } case ByteCode.INVOKEVIRTUAL: { Instruction_Invokevirtual iv = (Instruction_Invokevirtual)ins; int args = cp_info.countParams(constant_pool,iv.arg_i); Type returnType = byteCodeTypeOf(jimpleReturnTypeOfMethodRef(cm, constant_pool, iv.arg_i)); // pop off parameters. for (int j=args-1;j>=0;j { if(typeStack.top().equals(Long2ndHalfType.v())) { typeStack = popSafe(typeStack, Long2ndHalfType.v()); typeStack = popSafe(typeStack, LongType.v()); } else if(typeStack.top().equals(Double2ndHalfType.v())) { typeStack = popSafe(typeStack, Double2ndHalfType.v()); typeStack = popSafe(typeStack, DoubleType.v()); } else typeStack = popSafe(typeStack, typeStack.top()); } typeStack = popSafeRefType(typeStack); if(!returnType.equals(VoidType.v())) typeStack = smartPush(typeStack, returnType); break; } case ByteCode.INVOKENONVIRTUAL: { Instruction_Invokenonvirtual iv = (Instruction_Invokenonvirtual)ins; int args = cp_info.countParams(constant_pool,iv.arg_i); Type returnType = byteCodeTypeOf(jimpleReturnTypeOfMethodRef(cm, constant_pool, iv.arg_i)); // pop off parameters. for (int j=args-1;j>=0;j { if(typeStack.top().equals(Long2ndHalfType.v())) { typeStack = popSafe(typeStack, Long2ndHalfType.v()); typeStack = popSafe(typeStack, LongType.v()); } else if(typeStack.top().equals(Double2ndHalfType.v())) { typeStack = popSafe(typeStack, Double2ndHalfType.v()); typeStack = popSafe(typeStack, DoubleType.v()); } else typeStack = popSafe(typeStack, typeStack.top()); } typeStack = popSafeRefType(typeStack); if(!returnType.equals(VoidType.v())) typeStack = smartPush(typeStack, returnType); break; } case ByteCode.INVOKESTATIC: { Instruction_Invokestatic iv = (Instruction_Invokestatic)ins; int args = cp_info.countParams(constant_pool,iv.arg_i); Type returnType = byteCodeTypeOf(jimpleReturnTypeOfMethodRef(cm, constant_pool, iv.arg_i)); // pop off parameters. for (int j=args-1;j>=0;j { if(typeStack.top().equals(Long2ndHalfType.v())) { typeStack = popSafe(typeStack, Long2ndHalfType.v()); typeStack = popSafe(typeStack, LongType.v()); } else if(typeStack.top().equals(Double2ndHalfType.v())) { typeStack = popSafe(typeStack, Double2ndHalfType.v()); typeStack = popSafe(typeStack, DoubleType.v()); } else typeStack = popSafe(typeStack, typeStack.top()); } if(!returnType.equals(VoidType.v())) typeStack = smartPush(typeStack, returnType); break; } case ByteCode.INVOKEINTERFACE: { Instruction_Invokeinterface iv = (Instruction_Invokeinterface) ins; int args = cp_info.countParams(constant_pool,iv.arg_i); Type returnType = byteCodeTypeOf(jimpleReturnTypeOfInterfaceMethodRef(cm, constant_pool, iv.arg_i)); // pop off parameters. for (int j=args-1;j>=0;j { if(typeStack.top().equals(Long2ndHalfType.v())) { typeStack = popSafe(typeStack, Long2ndHalfType.v()); typeStack = popSafe(typeStack, LongType.v()); } else if(typeStack.top().equals(Double2ndHalfType.v())) { typeStack = popSafe(typeStack, Double2ndHalfType.v()); typeStack = popSafe(typeStack, DoubleType.v()); } else typeStack = popSafe(typeStack, typeStack.top()); } typeStack = popSafeRefType(typeStack); if(!returnType.equals(VoidType.v())) typeStack = smartPush(typeStack, returnType); break; } case ByteCode.ATHROW: // technically athrow leaves the stack in an undefined // state. In fact, the top value is the one we actually // throw, but it should stay on the stack since the exception // handler expects to start that way, at least in the real JVM. break; case ByteCode.NEW: { Type type = RefType.v(getClassName(constant_pool, ((Instruction_New)ins).arg_i)); typeStack = typeStack.push(type); break; } case ByteCode.CHECKCAST: { String className = getClassName(constant_pool, ((Instruction_Checkcast)ins).arg_i); Type castType; if(className.startsWith("[")) castType = Util.v().jimpleTypeOfFieldDescriptor(cm, getClassName(constant_pool, ((Instruction_Checkcast)ins).arg_i)); else castType = RefType.v(className); typeStack = popSafeRefType(typeStack); typeStack = typeStack.push(castType); break; } case ByteCode.INSTANCEOF: { typeStack = popSafeRefType(typeStack); typeStack = typeStack.push(IntType.v()); break; } case ByteCode.MONITORENTER: typeStack = popSafeRefType(typeStack); break; case ByteCode.MONITOREXIT: typeStack = popSafeRefType(typeStack); break; default: throw new RuntimeException("processFlow failed: Unknown bytecode instruction: " + x); } return new OutFlow(typeStack); } private Type jimpleTypeOfFieldInFieldRef(Scene cm, cp_info[] constant_pool, int index) { CONSTANT_Fieldref_info fr = (CONSTANT_Fieldref_info) (constant_pool[index]); CONSTANT_NameAndType_info nat = (CONSTANT_NameAndType_info) (constant_pool[fr.name_and_type_index]); String fieldDescriptor = ((CONSTANT_Utf8_info) (constant_pool[nat.descriptor_index])).convert(); return Util.v().jimpleTypeOfFieldDescriptor(cm, fieldDescriptor); } private Type jimpleReturnTypeOfMethodRef(Scene cm, cp_info[] constant_pool, int index) { CONSTANT_Methodref_info mr = (CONSTANT_Methodref_info) (constant_pool[index]); CONSTANT_NameAndType_info nat = (CONSTANT_NameAndType_info) (constant_pool[mr.name_and_type_index]); String methodDescriptor = ((CONSTANT_Utf8_info) (constant_pool[nat.descriptor_index])).convert(); return Util.v().jimpleReturnTypeOfMethodDescriptor(cm, methodDescriptor); } private Type jimpleReturnTypeOfInterfaceMethodRef(Scene cm, cp_info[] constant_pool, int index) { CONSTANT_InterfaceMethodref_info mr = (CONSTANT_InterfaceMethodref_info) (constant_pool[index]); CONSTANT_NameAndType_info nat = (CONSTANT_NameAndType_info) (constant_pool[mr.name_and_type_index]); String methodDescriptor = ((CONSTANT_Utf8_info) (constant_pool[nat.descriptor_index])).convert(); return Util.v().jimpleReturnTypeOfMethodDescriptor(cm, methodDescriptor); } private OutFlow processCPEntry(cp_info constant_pool[],int i, TypeStack typeStack, SootMethod jmethod) { cp_info c = constant_pool[i]; if (c instanceof CONSTANT_Integer_info) typeStack = typeStack.push(IntType.v()); else if (c instanceof CONSTANT_Float_info) typeStack = typeStack.push(FloatType.v()); else if (c instanceof CONSTANT_Long_info) { typeStack = typeStack.push(LongType.v()); typeStack = typeStack.push(Long2ndHalfType.v()); } else if (c instanceof CONSTANT_Double_info) { typeStack = typeStack.push(DoubleType.v()); typeStack = typeStack.push(Double2ndHalfType.v()); } else if (c instanceof CONSTANT_String_info) typeStack = typeStack.push(RefType.v("java.lang.String")); else if (c instanceof CONSTANT_Utf8_info) typeStack = typeStack.push(RefType.v("java.lang.String")); else throw new RuntimeException("Attempting to push a non-constant cp entry"); return new OutFlow(typeStack); } TypeStack smartPush(TypeStack typeStack, Type type) { if(type.equals(LongType.v())) { typeStack = typeStack.push(LongType.v()); typeStack = typeStack.push(Long2ndHalfType.v()); } else if(type.equals(DoubleType.v())) { typeStack = typeStack.push(DoubleType.v()); typeStack = typeStack.push(Double2ndHalfType.v()); } else typeStack = typeStack.push(type); return typeStack; } TypeStack popSafeRefType(TypeStack typeStack) { /* if(!(typeStack.top() instanceof RefType) && !(typeStack.top() instanceof ArrayType)) { throw new RuntimeException("popSafe failed; top: " + typeStack.top() + " required: RefType"); } */ return typeStack.pop(); } TypeStack popSafeArrayType(TypeStack typeStack) { /* if(!(typeStack.top() instanceof ArrayType) && !(RefType.v("null").equals(typeStack.top()))) { throw new RuntimeException("popSafe failed; top: " + typeStack.top() + " required: ArrayType"); } */ return typeStack.pop(); } TypeStack popSafe(TypeStack typeStack, Type requiredType) { /* if(!typeStack.top().equals(requiredType)) throw new RuntimeException("popSafe failed; top: " + typeStack.top() + " required: " + requiredType); */ return typeStack.pop(); } void confirmType(Type actualType, Type requiredType) { /* if(!actualType.equals(requiredType)) throw new RuntimeException("confirmType failed; actualType: " + actualType + " required: " + requiredType);*/ } String getClassName(cp_info[] constant_pool, int index) { CONSTANT_Class_info c = (CONSTANT_Class_info) constant_pool[index]; String name = ((CONSTANT_Utf8_info) (constant_pool[c.name_index])).convert(); return name.replace('/', '.'); } void confirmRefType(Type actualType) { /* if(!(actualType instanceof RefType) && !(actualType instanceof ArrayType)) throw new RuntimeException("confirmRefType failed; actualType: " + actualType);*/ } /** Runs through the given bbq contents performing the target fix-up pass; * Requires all reachable blocks to have their done flags set to true, and * this resets them all back to false; * @param bbq queue of BasicBlocks to process. * @see jimpleTargetFixup */ private void processTargetFixup(BBQ bbq) { BasicBlock b,p; Stmt s; while (!bbq.isEmpty()) { try { b = bbq.pull(); } catch(NoSuchElementException e) { break; } s = b.getTailJStmt(); if (s instanceof GotoStmt) { if (b.succ.size() == 1) { // Regular goto ((GotoStmt)s).setTarget(((BasicBlock) b.succ.firstElement()).getHeadJStmt()); } else { // Goto derived from a jsr bytecode /* if((BasicBlock)(b.succ.firstElement())==b.next) ((GotoStmt)s).setTarget(((BasicBlock) b.succ.elementAt(1)).getHeadJStmt()); else ((GotoStmt)s).setTarget(((BasicBlock) b.succ.firstElement()).getHeadJStmt()); */ G.v().out.println("Error :"); for (int i=0; i<b.statements.size(); i++) G.v().out.println(b.statements.get(i)); throw new RuntimeException(b +" has "+b.succ.size()+" successors."); } } else if (s instanceof IfStmt) { if (b.succ.size()!=2) G.v().out.println("How can an if not have 2 successors?"); if((BasicBlock)(b.succ.firstElement())==b.next) { ((IfStmt)s).setTarget(((BasicBlock) b.succ.elementAt(1)).getHeadJStmt()); } else { ((IfStmt)s).setTarget(((BasicBlock) b.succ.firstElement()).getHeadJStmt()); } } else if (s instanceof TableSwitchStmt) { int count=0; TableSwitchStmt sts = (TableSwitchStmt)s; // Successors of the basic block ending with a switch statement // are listed in the successor vector in order, with the // default as the very first (0-th entry) for (Enumeration e = b.succ.elements();e.hasMoreElements();) { p = (BasicBlock)(e.nextElement()); if (count==0) { sts.setDefaultTarget(p.getHeadJStmt()); } else { sts.setTarget(count-1, p.getHeadJStmt()); } count++; } } else if (s instanceof LookupSwitchStmt) { int count=0; LookupSwitchStmt sls = (LookupSwitchStmt)s; // Successors of the basic block ending with a switch statement // are listed in the successor vector in order, with the // default as the very first (0-th entry) for (Enumeration e = b.succ.elements();e.hasMoreElements();) { p = (BasicBlock)(e.nextElement()); if (count==0) { sls.setDefaultTarget(p.getHeadJStmt()); } else { sls.setTarget(count-1, p.getHeadJStmt()); } count++; } } b.done = false; for (Enumeration e = b.succ.elements();e.hasMoreElements();) { p = (BasicBlock)(e.nextElement()); if (p.done) bbq.push(p); } } } /** After the initial jimple construction, a second pass is made to fix up * missing Stmt targets for <tt>goto</tt>s, <tt>if</tt>'s etc. * @param c code attribute of this method. * @see CFG#jimplify */ void jimpleTargetFixup() { BasicBlock b; BBQ bbq = new BBQ(); Code_attribute c = method.locate_code_attribute(); if (c==null) return; // Reset all the dones to true { BasicBlock bb = cfg; while(bb != null) { bb.done = true; bb = bb.next; } } // first process the main code bbq.push(cfg); processTargetFixup(bbq); // then the exceptions if (bbq.isEmpty()) { int i; for (i=0;i<c.exception_table_length;i++) { b = c.exception_table[i].b; // if block hasn't yet been processed... if (b!=null && b.done) { bbq.push(b); processTargetFixup(bbq); if (!bbq.isEmpty()) { G.v().out.println("Error 2nd processing exception block."); break; } } } } } private void generateJimpleForCPEntry(cp_info constant_pool[], int i, TypeStack typeStack, TypeStack postTypeStack, SootMethod jmethod, List statements) { Expr e; Stmt stmt; Value rvalue; cp_info c = constant_pool[i]; if (c instanceof CONSTANT_Integer_info) { CONSTANT_Integer_info ci = (CONSTANT_Integer_info)c; rvalue = IntConstant.v((int) ci.bytes); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex()), rvalue); } else if (c instanceof CONSTANT_Float_info) { CONSTANT_Float_info cf = (CONSTANT_Float_info)c; rvalue = FloatConstant.v(cf.convert()); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex()), rvalue); } else if (c instanceof CONSTANT_Long_info) { CONSTANT_Long_info cl = (CONSTANT_Long_info)c; rvalue = LongConstant.v(cl.convert()); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex()), rvalue); } else if (c instanceof CONSTANT_Double_info) { CONSTANT_Double_info cd = (CONSTANT_Double_info)c; rvalue = DoubleConstant.v(cd.convert()); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex()), rvalue); } else if (c instanceof CONSTANT_String_info) { CONSTANT_String_info cs = (CONSTANT_String_info)c; String constant = cs.toString(constant_pool); if(constant.startsWith("\"") && constant.endsWith("\"")) constant = constant.substring(1, constant.length() - 1); rvalue = StringConstant.v(constant); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex()), rvalue); } else if (c instanceof CONSTANT_Utf8_info) { CONSTANT_Utf8_info cu = (CONSTANT_Utf8_info)c; String constant = cu.convert(); if(constant.startsWith("\"") && constant.endsWith("\"")) constant = constant.substring(1, constant.length() - 1); rvalue = StringConstant.v(constant); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex()), rvalue); } else { throw new RuntimeException("Attempting to push a non-constant cp entry"); } statements.add(stmt); } void generateJimple(Instruction ins, TypeStack typeStack, TypeStack postTypeStack, cp_info constant_pool[], List statements, BasicBlock basicBlock) { Value[] params; Value v1=null,v2=null,v3=null,v4=null; Local l1 = null, l2 = null, l3 = null, l4 = null; Expr e=null,rhs=null; BinopExpr b=null; ConditionExpr co = null; ArrayRef a=null; int args; Value rvalue; // int localIndex; Stmt stmt = null; int x = ((int)(ins.code))&0xff; Util.v().activeOriginalIndex = ins.originalIndex; Util.v().isLocalStore = false; Util.v().isWideLocalStore = false; switch(x) { case ByteCode.BIPUSH: rvalue = IntConstant.v(((Instruction_Bipush)ins).arg_b); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex()), rvalue); break; case ByteCode.SIPUSH: rvalue = IntConstant.v(((Instruction_Sipush)ins).arg_i); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex()), rvalue); break; case ByteCode.LDC1: generateJimpleForCPEntry(constant_pool,((Instruction_Ldc1)ins).arg_b, typeStack, postTypeStack, jmethod, statements); break; case ByteCode.LDC2: case ByteCode.LDC2W: generateJimpleForCPEntry(constant_pool, ((Instruction_intindex)ins).arg_i, typeStack, postTypeStack, jmethod, statements); break; case ByteCode.ACONST_NULL: rvalue = NullConstant.v(); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex()), rvalue); break; case ByteCode.ICONST_M1: case ByteCode.ICONST_0: case ByteCode.ICONST_1: case ByteCode.ICONST_2: case ByteCode.ICONST_3: case ByteCode.ICONST_4: case ByteCode.ICONST_5: rvalue = IntConstant.v(x-ByteCode.ICONST_0); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex()), rvalue); break; case ByteCode.LCONST_0: case ByteCode.LCONST_1: rvalue = LongConstant.v(x-ByteCode.LCONST_0); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex()), rvalue); break; case ByteCode.FCONST_0: case ByteCode.FCONST_1: case ByteCode.FCONST_2: rvalue = FloatConstant.v((float)(x - ByteCode.FCONST_0)); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex()), rvalue); break; case ByteCode.DCONST_0: case ByteCode.DCONST_1: rvalue = DoubleConstant.v((double)(x-ByteCode.DCONST_0)); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex()), rvalue); break; case ByteCode.ILOAD: { Local local = (Local) Util.v().getLocalForIndex(listBody, ((Instruction_bytevar) ins).arg_b); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex()), local); break; } case ByteCode.FLOAD: { Local local = (Local) Util.v().getLocalForIndex(listBody, ((Instruction_bytevar)ins).arg_b); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex()), local); break; } case ByteCode.ALOAD: { Local local = Util.v().getLocalForIndex(listBody, ((Instruction_bytevar)ins).arg_b); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex()), local); break; } case ByteCode.DLOAD: { Local local = Util.v().getLocalForIndex(listBody, ((Instruction_bytevar)ins).arg_b); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex()), local); break; } case ByteCode.LLOAD: { Local local = Util.v().getLocalForIndex(listBody, ((Instruction_bytevar)ins).arg_b); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex()), local); break; } case ByteCode.ILOAD_0: case ByteCode.ILOAD_1: case ByteCode.ILOAD_2: case ByteCode.ILOAD_3: { Local local = Util.v().getLocalForIndex(listBody, (x - ByteCode.ILOAD_0)); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex()), local); break; } case ByteCode.FLOAD_0: case ByteCode.FLOAD_1: case ByteCode.FLOAD_2: case ByteCode.FLOAD_3: { Local local = Util.v().getLocalForIndex(listBody, (x - ByteCode.FLOAD_0)); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex()), local); break; } case ByteCode.ALOAD_0: case ByteCode.ALOAD_1: case ByteCode.ALOAD_2: case ByteCode.ALOAD_3: { Local local = Util.v().getLocalForIndex(listBody, (x - ByteCode.ALOAD_0)); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex()), local); break; } case ByteCode.LLOAD_0: case ByteCode.LLOAD_1: case ByteCode.LLOAD_2: case ByteCode.LLOAD_3: { Local local = Util.v().getLocalForIndex(listBody, (x - ByteCode.LLOAD_0)); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex()), local); break; } case ByteCode.DLOAD_0: case ByteCode.DLOAD_1: case ByteCode.DLOAD_2: case ByteCode.DLOAD_3: { Local local = Util.v().getLocalForIndex(listBody, (x - ByteCode.DLOAD_0)); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex()), local); break; } case ByteCode.ISTORE: { Util.v().isLocalStore = true; Util.v().isWideLocalStore = true; Local local = Util.v().getLocalForIndex(listBody, ((Instruction_bytevar)ins).arg_b); stmt = Jimple.v().newAssignStmt(local, Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex())); break; } case ByteCode.FSTORE: { Util.v().isLocalStore = true; Util.v().isWideLocalStore = true; Local local = Util.v().getLocalForIndex(listBody, ((Instruction_bytevar)ins).arg_b); stmt = Jimple.v().newAssignStmt(local, Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex())); break; } case ByteCode.ASTORE: { Util.v().isLocalStore = true; Util.v().isWideLocalStore = true; Local local = Util.v().getLocalForIndex(listBody, ((Instruction_bytevar)ins).arg_b); stmt = Jimple.v().newAssignStmt(local, Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex())); break; } case ByteCode.LSTORE: { Util.v().isLocalStore = true; Util.v().isWideLocalStore = true; Local local = Util.v().getLocalForIndex(listBody, ((Instruction_bytevar)ins).arg_b); stmt = Jimple.v().newAssignStmt(local, Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex())); break; } case ByteCode.DSTORE: { Util.v().isLocalStore = true; Util.v().isWideLocalStore = true; Local local = Util.v().getLocalForIndex(listBody, ((Instruction_bytevar)ins).arg_b); stmt = Jimple.v().newAssignStmt(local, Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex())); break; } case ByteCode.ISTORE_0: case ByteCode.ISTORE_1: case ByteCode.ISTORE_2: case ByteCode.ISTORE_3: { Util.v().isLocalStore = true; Local local = Util.v().getLocalForIndex(listBody, (x - ByteCode.ISTORE_0)); stmt = Jimple.v().newAssignStmt(local, Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex())); break; } case ByteCode.FSTORE_0: case ByteCode.FSTORE_1: case ByteCode.FSTORE_2: case ByteCode.FSTORE_3: { Util.v().isLocalStore = true; Local local = (Local) Util.v().getLocalForIndex(listBody, (x - ByteCode.FSTORE_0)); stmt = Jimple.v().newAssignStmt(local, Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex())); break; } case ByteCode.ASTORE_0: case ByteCode.ASTORE_1: case ByteCode.ASTORE_2: case ByteCode.ASTORE_3: { Util.v().isLocalStore = true; Local local = Util.v().getLocalForIndex(listBody, (x - ByteCode.ASTORE_0)); stmt = Jimple.v().newAssignStmt(local, Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex())); break; } case ByteCode.LSTORE_0: case ByteCode.LSTORE_1: case ByteCode.LSTORE_2: case ByteCode.LSTORE_3: { Util.v().isLocalStore = true; Local local = Util.v().getLocalForIndex(listBody, (x - ByteCode.LSTORE_0)); stmt = Jimple.v().newAssignStmt(local, Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex())); break; } case ByteCode.DSTORE_0: case ByteCode.DSTORE_1: case ByteCode.DSTORE_2: case ByteCode.DSTORE_3: { Util.v().isLocalStore = true; Local local = Util.v().getLocalForIndex(listBody, (x - ByteCode.DSTORE_0)); stmt = Jimple.v().newAssignStmt(local, Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex())); break; } case ByteCode.IINC: { Local local = Util.v().getLocalForIndex(listBody, ((Instruction_Iinc)ins).arg_b); int amt = (((Instruction_Iinc)ins).arg_c); rhs = Jimple.v().newAddExpr(local, IntConstant.v(amt)); stmt = Jimple.v().newAssignStmt(local,rhs); break; } case ByteCode.WIDE: throw new RuntimeException("WIDE instruction should not be encountered anymore"); // break; case ByteCode.NEWARRAY: { Type baseType = (Type) jimpleTypeOfAtype(((Instruction_Newarray)ins).atype); rhs = Jimple.v().newNewArrayExpr(baseType, Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex())); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex()), rhs); break; } case ByteCode.ANEWARRAY: { String baseName = getClassName(constant_pool, ((Instruction_Anewarray)ins).arg_i); Type baseType; if(baseName.startsWith("[")) baseType = Util.v().jimpleTypeOfFieldDescriptor(cm, getClassName(constant_pool, ((Instruction_Anewarray)ins).arg_i)); else baseType = RefType.v(baseName); rhs = Jimple.v().newNewArrayExpr(baseType, Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex())); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex()),rhs); break; } case ByteCode.MULTIANEWARRAY: { int bdims = (int)(((Instruction_Multianewarray)ins).dims); List dims = new ArrayList(); for (int j=0; j < bdims; j++) dims.add(Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex() - bdims + j + 1)); String mstype = constant_pool[((Instruction_Multianewarray)ins).arg_i]. toString(constant_pool); ArrayType jimpleType = (ArrayType) Util.v().jimpleTypeOfFieldDescriptor(cm, mstype); rhs = Jimple.v().newNewMultiArrayExpr(jimpleType, dims); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex()),rhs); break; } case ByteCode.ARRAYLENGTH: rhs = Jimple.v().newLengthExpr( Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex())); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex()),rhs); break; case ByteCode.IALOAD: case ByteCode.BALOAD: case ByteCode.CALOAD: case ByteCode.SALOAD: case ByteCode.FALOAD: case ByteCode.LALOAD: case ByteCode.DALOAD: case ByteCode.AALOAD: a = Jimple.v().newArrayRef(Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex() - 1), Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex())); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex()), a); break; case ByteCode.IASTORE: case ByteCode.FASTORE: case ByteCode.AASTORE: case ByteCode.BASTORE: case ByteCode.CASTORE: case ByteCode.SASTORE: a = Jimple.v().newArrayRef(Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex() - 2), Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex() - 1)); stmt = Jimple.v().newAssignStmt(a, Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex())); break; case ByteCode.LASTORE: case ByteCode.DASTORE: a = Jimple.v().newArrayRef(Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex() - 3), Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex() - 2)); stmt = Jimple.v().newAssignStmt(a, Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex())); break; case ByteCode.NOP: stmt = Jimple.v().newNopStmt(); break; case ByteCode.POP: case ByteCode.POP2: stmt = Jimple.v().newNopStmt(); break; case ByteCode.DUP: stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex()), Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex())); break; case ByteCode.DUP2: if(typeSize(typeStack.top()) == 2) { stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex() - 1), Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex() - 1)); } else { stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex() - 1), Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex() - 1)); statements.add(stmt); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex()), Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex())); statements.add(stmt); stmt = null; } break; case ByteCode.DUP_X1: l1 = Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()); l2 = Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()-1); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex()), l1); statements.add(stmt); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex() - 1), l2); statements.add(stmt); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex() - 2), Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex())); statements.add(stmt); stmt = null; break; case ByteCode.DUP_X2: if(typeSize(typeStack.get(typeStack.topIndex() - 2)) == 2) { l3 = Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex() - 2); l1 = Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex() - 2), l3); statements.add(stmt); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex() - 3), l1); statements.add(stmt); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex()), l1); statements.add(stmt); stmt = null; } else { l3 = Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex() - 2); l2 = Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex() - 1); l1 = Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex()), l1); statements.add(stmt); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex() - 1), l2); statements.add(stmt); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex() - 2), l3); statements.add(stmt); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex() - 3), Util.v().getLocalForStackOp( listBody, postTypeStack, postTypeStack.topIndex())); statements.add(stmt); stmt = null; } break; case ByteCode.DUP2_X1: if(typeSize(typeStack.get(typeStack.topIndex() - 1)) == 2) { l2 = Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex() - 1); l3 = Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex() - 2); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex() -1), l2); statements.add(stmt); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex() - 2), l3); statements.add(stmt); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex() - 4), Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex() - 1)); statements.add(stmt); stmt = null; } else { l3 = Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex() - 2); l2 = Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex() - 1); l1 = Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex()), l1); statements.add(stmt); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex() - 1), l2); statements.add(stmt); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex() - 2), l3); statements.add(stmt); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex() - 3), Util.v().getLocalForStackOp( listBody, postTypeStack, postTypeStack.topIndex())); statements.add(stmt); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex() - 4), Util.v().getLocalForStackOp( listBody, postTypeStack, postTypeStack.topIndex() - 1)); statements.add(stmt); stmt = null; } break; case ByteCode.DUP2_X2: if(typeSize(typeStack.get(typeStack.topIndex() - 1)) == 2) { l2 = Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex() - 1); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex() - 1), l2); statements.add(stmt); } else { l1 = Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()); l2 = Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex() - 1); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex() - 1), l2); statements.add(stmt); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex()), l1); statements.add(stmt); } if(typeSize(typeStack.get(typeStack.topIndex() - 3)) == 2) { l4 = Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex() - 3); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex() - 3), l4); statements.add(stmt); } else { l4 = Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex() - 3); l3 = Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex() - 2); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex() - 3), l4); statements.add(stmt); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex() - 2), l3); statements.add(stmt); } if(typeSize(typeStack.get(typeStack.topIndex() - 1)) == 2) { stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex() - 5), Util.v().getLocalForStackOp( listBody, postTypeStack, postTypeStack.topIndex() - 1)); statements.add(stmt); } else { stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex() - 5), Util.v().getLocalForStackOp( listBody, postTypeStack, postTypeStack.topIndex() - 1)); statements.add(stmt); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex() - 4), Util.v().getLocalForStackOp( listBody, postTypeStack, postTypeStack.topIndex())); statements.add(stmt); } stmt = null; break; case ByteCode.SWAP: { Local first; typeStack = typeStack.push(typeStack.top()); first = Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()); typeStack = typeStack.pop(); // generation of a free temporary Local second = Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex()); Local third = Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex() - 1); stmt = Jimple.v().newAssignStmt(first, second); statements.add(stmt); stmt = Jimple.v().newAssignStmt(second, third); statements.add(stmt); stmt = Jimple.v().newAssignStmt(third, first); statements.add(stmt); stmt = null; break; } case ByteCode.FADD: case ByteCode.IADD: rhs = Jimple.v().newAddExpr(Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex() - 1), Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex())); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex()), rhs); break; case ByteCode.DADD: case ByteCode.LADD: rhs = Jimple.v().newAddExpr(Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex() - 3), Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex() - 1)); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex()), rhs); break; case ByteCode.FSUB: case ByteCode.ISUB: rhs = Jimple.v().newSubExpr(Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex() - 1), Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex())); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex()), rhs); break; case ByteCode.DSUB: case ByteCode.LSUB: rhs = Jimple.v().newSubExpr(Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex() - 3), Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex() - 1)); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex()), rhs); break; case ByteCode.FMUL: case ByteCode.IMUL: rhs = Jimple.v().newMulExpr(Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex() - 1), Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex())); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex()), rhs); break; case ByteCode.DMUL: case ByteCode.LMUL: rhs = Jimple.v().newMulExpr(Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex() - 3), Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex() - 1)); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex()), rhs); break; case ByteCode.FDIV: case ByteCode.IDIV: rhs = Jimple.v().newDivExpr(Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex() - 1), Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex())); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex()), rhs); break; case ByteCode.DDIV: case ByteCode.LDIV: rhs = Jimple.v().newDivExpr(Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex() - 3), Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex() - 1)); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex()), rhs); break; case ByteCode.FREM: case ByteCode.IREM: rhs = Jimple.v().newRemExpr(Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex() - 1), Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex())); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex()), rhs); break; case ByteCode.DREM: case ByteCode.LREM: rhs = Jimple.v().newRemExpr(Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex() - 3), Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex() - 1)); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex()), rhs); break; case ByteCode.INEG: case ByteCode.LNEG: case ByteCode.FNEG: case ByteCode.DNEG: rhs = Jimple.v().newNegExpr(Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex())); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex()),rhs); break; case ByteCode.ISHL: rhs = Jimple.v().newShlExpr(Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex() - 1), Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex())); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex()), rhs); break; case ByteCode.ISHR: rhs = Jimple.v().newShrExpr(Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex() - 1), Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex())); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex()), rhs); break; case ByteCode.IUSHR: rhs = Jimple.v().newUshrExpr(Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex() - 1), Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex())); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex()), rhs); break; case ByteCode.LSHL: rhs = Jimple.v().newShlExpr(Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex() - 2), Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex())); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex()), rhs); break; case ByteCode.LSHR: rhs = Jimple.v().newShrExpr(Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex() - 2), Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex())); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex()), rhs); break; case ByteCode.LUSHR: rhs = Jimple.v().newUshrExpr(Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex() - 2), Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex())); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex()), rhs); break; case ByteCode.IAND: rhs = Jimple.v().newAndExpr(Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex() - 1), Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex())); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex()), rhs); break; case ByteCode.LAND: rhs = Jimple.v().newAndExpr(Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex() - 3), Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex() - 1)); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex()), rhs); break; case ByteCode.IOR: rhs = Jimple.v().newOrExpr(Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex() - 1), Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex())); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex()), rhs); break; case ByteCode.LOR: rhs = Jimple.v().newOrExpr(Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex() - 3), Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex() - 1)); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex()), rhs); break; case ByteCode.IXOR: rhs = Jimple.v().newXorExpr(Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex() - 1), Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex())); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex()), rhs); break; case ByteCode.LXOR: rhs = Jimple.v().newXorExpr(Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex() - 3), Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex() - 1)); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex()), rhs); break; case ByteCode.D2L: case ByteCode.F2L: case ByteCode.I2L: rhs = Jimple.v().newCastExpr(Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()), LongType.v()); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex()), rhs); break; case ByteCode.D2F: case ByteCode.L2F: case ByteCode.I2F: rhs = Jimple.v().newCastExpr(Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()), FloatType.v()); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex()), rhs); break; case ByteCode.I2D: case ByteCode.L2D: case ByteCode.F2D: rhs = Jimple.v().newCastExpr(Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()), DoubleType.v()); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex()), rhs); break; case ByteCode.L2I: case ByteCode.F2I: case ByteCode.D2I: rhs = Jimple.v().newCastExpr(Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()), IntType.v()); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex()), rhs); break; case ByteCode.INT2BYTE: rhs = Jimple.v().newCastExpr(Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()), ByteType.v()); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex()), rhs); break; case ByteCode.INT2CHAR: rhs = Jimple.v().newCastExpr(Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()), CharType.v()); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex()), rhs); break; case ByteCode.INT2SHORT: rhs = Jimple.v().newCastExpr(Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()), ShortType.v()); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex()), rhs); break; case ByteCode.IFEQ: co = Jimple.v().newEqExpr(Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()), IntConstant.v(0)); stmt = Jimple.v().newIfStmt(co, new FutureStmt()); break; case ByteCode.IFNULL: co = Jimple.v().newEqExpr(Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()), NullConstant.v()); stmt = Jimple.v().newIfStmt(co, new FutureStmt()); break; case ByteCode.IFLT: co = Jimple.v().newLtExpr(Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()), IntConstant.v(0)); stmt = Jimple.v().newIfStmt(co, new FutureStmt()); break; case ByteCode.IFLE: co = Jimple.v().newLeExpr(Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()), IntConstant.v(0)); stmt = Jimple.v().newIfStmt(co, new FutureStmt()); break; case ByteCode.IFNE: co = Jimple.v().newNeExpr(Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()), IntConstant.v(0)); stmt = Jimple.v().newIfStmt(co, new FutureStmt()); break; case ByteCode.IFNONNULL: co = Jimple.v().newNeExpr(Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()), NullConstant.v()); stmt = Jimple.v().newIfStmt(co, new FutureStmt()); break; case ByteCode.IFGT: co = Jimple.v().newGtExpr(Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()), IntConstant.v(0)); stmt = Jimple.v().newIfStmt(co, new FutureStmt()); break; case ByteCode.IFGE: co = Jimple.v().newGeExpr(Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()), IntConstant.v(0)); stmt = Jimple.v().newIfStmt(co, new FutureStmt()); break; case ByteCode.IF_ICMPEQ: co = Jimple.v().newEqExpr( Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()-1), Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex())); stmt = Jimple.v().newIfStmt(co, new FutureStmt()); break; case ByteCode.IF_ICMPLT: co = Jimple.v().newLtExpr( Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()-1), Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex())); stmt = Jimple.v().newIfStmt(co, new FutureStmt()); break; case ByteCode.IF_ICMPLE: co = Jimple.v().newLeExpr( Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()-1), Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex())); stmt = Jimple.v().newIfStmt(co, new FutureStmt()); break; case ByteCode.IF_ICMPNE: co = Jimple.v().newNeExpr( Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()-1), Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex())); stmt = Jimple.v().newIfStmt(co, new FutureStmt()); break; case ByteCode.IF_ICMPGT: co = Jimple.v().newGtExpr( Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()-1), Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex())); stmt = Jimple.v().newIfStmt(co, new FutureStmt()); break; case ByteCode.IF_ICMPGE: co = Jimple.v().newGeExpr( Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()-1), Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex())); stmt = Jimple.v().newIfStmt(co, new FutureStmt()); break; case ByteCode.LCMP: rhs = Jimple.v().newCmpExpr( Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()-3), Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()-1)); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex()), rhs); break; case ByteCode.FCMPL: rhs = Jimple.v().newCmplExpr( Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()-1), Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex())); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex()),rhs); break; case ByteCode.FCMPG: rhs = Jimple.v().newCmpgExpr( Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()-1), Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex())); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex()),rhs); break; case ByteCode.DCMPL: rhs = Jimple.v().newCmplExpr( Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()-3), Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()-1)); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex()),rhs); break; case ByteCode.DCMPG: rhs = Jimple.v().newCmpgExpr( Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()-3), Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()-1)); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex()),rhs); break; case ByteCode.IF_ACMPEQ: co = Jimple.v().newEqExpr( Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()-1), Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex())); stmt = Jimple.v().newIfStmt(co, new FutureStmt()); break; case ByteCode.IF_ACMPNE: co = Jimple.v().newNeExpr( Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()-1), Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex())); stmt = Jimple.v().newIfStmt(co, new FutureStmt()); break; case ByteCode.GOTO: stmt = Jimple.v().newGotoStmt(new FutureStmt()); break; case ByteCode.GOTO_W: stmt = Jimple.v().newGotoStmt(new FutureStmt()); break; /* case ByteCode.JSR: case ByteCode.JSR_W: { stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex()), Jimple.v().newNextNextStmtRef()); statements.add(stmt); stmt = Jimple.v().newGotoStmt(new FutureStmt()); statements.add(stmt); stmt = null; break; } */ case ByteCode.RET: { Local local = Util.v().getLocalForIndex(listBody, ((Instruction_Ret)ins).arg_b); stmt = Jimple.v().newRetStmt(local); break; } case ByteCode.RET_W: { Local local = Util.v().getLocalForIndex(listBody, ((Instruction_Ret_w)ins).arg_i); stmt = Jimple.v().newRetStmt(local); break; } case ByteCode.RETURN: stmt = Jimple.v().newReturnVoidStmt(); break; case ByteCode.LRETURN: case ByteCode.DRETURN: case ByteCode.IRETURN: case ByteCode.FRETURN: case ByteCode.ARETURN: stmt = Jimple.v().newReturnStmt(Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex())); break; case ByteCode.BREAKPOINT: stmt = Jimple.v().newBreakpointStmt(); break; case ByteCode.TABLESWITCH: { int lowIndex = ((Instruction_Tableswitch)ins).low, highIndex = ((Instruction_Tableswitch)ins).high; stmt = Jimple.v().newTableSwitchStmt( Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()), lowIndex, highIndex, Arrays.asList(new FutureStmt[highIndex - lowIndex + 1]), new FutureStmt()); break; } case ByteCode.LOOKUPSWITCH: { List matches = new ArrayList(); int npairs = ((Instruction_Lookupswitch)ins).npairs; for (int j = 0; j < npairs; j++) matches.add(IntConstant.v( ((Instruction_Lookupswitch)ins).match_offsets[j*2])); stmt = Jimple.v().newLookupSwitchStmt( Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()), matches, Arrays.asList(new FutureStmt[npairs]), new FutureStmt()); break; } case ByteCode.PUTFIELD: { CONSTANT_Fieldref_info fieldInfo = (CONSTANT_Fieldref_info) constant_pool[((Instruction_Putfield)ins).arg_i]; CONSTANT_Class_info c = (CONSTANT_Class_info) constant_pool[fieldInfo.class_index]; String className = ((CONSTANT_Utf8_info) (constant_pool[c.name_index])).convert(); className = className.replace('/', '.'); CONSTANT_NameAndType_info i = (CONSTANT_NameAndType_info) constant_pool[fieldInfo.name_and_type_index]; String fieldName = ((CONSTANT_Utf8_info) (constant_pool[i.name_index])).convert(); String fieldDescriptor = ((CONSTANT_Utf8_info) (constant_pool[i.descriptor_index])). convert(); Type fieldType = Util.v().jimpleTypeOfFieldDescriptor(cm, fieldDescriptor); SootClass bclass = cm.getSootClass(className); SootField field = bclass.getField(fieldName, fieldType); InstanceFieldRef fr = Jimple.v().newInstanceFieldRef(Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex() - typeSize(typeStack.top())), field); rvalue = Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()); stmt = Jimple.v().newAssignStmt(fr,rvalue); break; } case ByteCode.GETFIELD: { InstanceFieldRef fr = null; CONSTANT_Fieldref_info fieldInfo = (CONSTANT_Fieldref_info) constant_pool[((Instruction_Getfield)ins).arg_i]; CONSTANT_Class_info c = (CONSTANT_Class_info) constant_pool[fieldInfo.class_index]; String className = ((CONSTANT_Utf8_info) (constant_pool[c.name_index])).convert(); className = className.replace('/', '.'); CONSTANT_NameAndType_info i = (CONSTANT_NameAndType_info) constant_pool[fieldInfo.name_and_type_index]; String fieldName = ((CONSTANT_Utf8_info) (constant_pool[i.name_index])).convert(); String fieldDescriptor = ((CONSTANT_Utf8_info) (constant_pool[i.descriptor_index])). convert(); SootClass bclass = cm.getSootClass(className); Type fieldType = Util.v().jimpleTypeOfFieldDescriptor(cm, fieldDescriptor); SootField field = bclass.getField(fieldName, fieldType); fr = Jimple.v().newInstanceFieldRef(Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()), field); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex()), fr); break; } case ByteCode.PUTSTATIC: { StaticFieldRef fr = null; CONSTANT_Fieldref_info fieldInfo = (CONSTANT_Fieldref_info) constant_pool[((Instruction_Putstatic)ins).arg_i]; CONSTANT_Class_info c = (CONSTANT_Class_info) constant_pool[fieldInfo.class_index]; String className = ((CONSTANT_Utf8_info) (constant_pool[c.name_index])).convert(); className = className.replace('/', '.'); CONSTANT_NameAndType_info i = (CONSTANT_NameAndType_info) constant_pool[fieldInfo.name_and_type_index]; String fieldName = ((CONSTANT_Utf8_info) (constant_pool[i.name_index])).convert(); String fieldDescriptor = ((CONSTANT_Utf8_info) (constant_pool[i.descriptor_index])). convert(); Type fieldType = Util.v().jimpleTypeOfFieldDescriptor(cm, fieldDescriptor); SootClass bclass = cm.getSootClass(className); SootField field = bclass.getField(fieldName, fieldType); fr = Jimple.v().newStaticFieldRef(field); stmt = Jimple.v().newAssignStmt(fr, Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex())); break; } case ByteCode.GETSTATIC: { StaticFieldRef fr = null; CONSTANT_Fieldref_info fieldInfo = (CONSTANT_Fieldref_info) constant_pool[((Instruction_Getstatic)ins).arg_i]; CONSTANT_Class_info c = (CONSTANT_Class_info) constant_pool[fieldInfo.class_index]; String className = ((CONSTANT_Utf8_info) (constant_pool[c.name_index])).convert(); className = className.replace('/', '.'); CONSTANT_NameAndType_info i = (CONSTANT_NameAndType_info) constant_pool[fieldInfo.name_and_type_index]; String fieldName = ((CONSTANT_Utf8_info) (constant_pool[i.name_index])).convert(); String fieldDescriptor = ((CONSTANT_Utf8_info) (constant_pool[i.descriptor_index])). convert(); Type fieldType = Util.v().jimpleTypeOfFieldDescriptor(cm, fieldDescriptor); SootClass bclass = cm.getSootClass(className); SootField field = bclass.getField(fieldName, fieldType); fr = Jimple.v().newStaticFieldRef(field); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex()), fr); break; } case ByteCode.INVOKEVIRTUAL: { Instruction_Invokevirtual iv = (Instruction_Invokevirtual)ins; args = cp_info.countParams(constant_pool,iv.arg_i); SootMethod method = null; CONSTANT_Methodref_info methodInfo = (CONSTANT_Methodref_info) constant_pool[iv.arg_i]; CONSTANT_Class_info c = (CONSTANT_Class_info) constant_pool[methodInfo.class_index]; String className = ((CONSTANT_Utf8_info) (constant_pool[c.name_index])).convert(); className = className.replace('/', '.'); CONSTANT_NameAndType_info i = (CONSTANT_NameAndType_info) constant_pool[methodInfo.name_and_type_index]; String methodName = ((CONSTANT_Utf8_info) (constant_pool[i.name_index])).convert(); String methodDescriptor = ((CONSTANT_Utf8_info) (constant_pool[i.descriptor_index])). convert(); SootClass bclass = cm.getSootClass(className); Local[] parameters; List parameterTypes; Type returnType; // Generate parameters & returnType & parameterTypes { Type[] types = Util.v().jimpleTypesOfFieldOrMethodDescriptor(cm, methodDescriptor); parameterTypes = new ArrayList(); for(int k = 0; k < types.length - 1; k++) { parameterTypes.add(types[k]); } returnType = types[types.length - 1]; } method = bclass.getMethod(methodName, parameterTypes, returnType); // build array of parameters params = new Value[args]; for (int j=args-1;j>=0;j { params[j] = Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()); if(typeSize(typeStack.top()) == 2) { typeStack = typeStack.pop(); typeStack = typeStack.pop(); } else typeStack = typeStack.pop(); } rvalue = Jimple.v().newVirtualInvokeExpr(Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()), method, Arrays.asList(params)); if(!returnType.equals(VoidType.v())) { stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex()),rvalue); } else stmt = Jimple.v().newInvokeStmt((InvokeExpr) rvalue); break; } case ByteCode.INVOKENONVIRTUAL: { Instruction_Invokenonvirtual iv = (Instruction_Invokenonvirtual)ins; args = cp_info.countParams(constant_pool,iv.arg_i); SootMethod method = null; CONSTANT_Methodref_info methodInfo = (CONSTANT_Methodref_info) constant_pool[iv.arg_i]; CONSTANT_Class_info c = (CONSTANT_Class_info) constant_pool[methodInfo.class_index]; String className = ((CONSTANT_Utf8_info) (constant_pool[c.name_index])).convert(); className = className.replace('/', '.'); CONSTANT_NameAndType_info i = (CONSTANT_NameAndType_info) constant_pool[methodInfo.name_and_type_index]; String methodName = ((CONSTANT_Utf8_info) (constant_pool[i.name_index])).convert(); String methodDescriptor = ((CONSTANT_Utf8_info) (constant_pool[i.descriptor_index])). convert(); SootClass bclass = cm.getSootClass(className); Local[] parameters; List parameterTypes; Type returnType; // Generate parameters & returnType & parameterTypes { Type[] types = Util.v().jimpleTypesOfFieldOrMethodDescriptor(cm, methodDescriptor); parameterTypes = new ArrayList(); for(int k = 0; k < types.length - 1; k++) { parameterTypes.add(types[k]); } returnType = types[types.length - 1]; } method = bclass.getMethod(methodName, parameterTypes, returnType); // build array of parameters params = new Value[args]; for (int j=args-1;j>=0;j { params[j] = Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()); if(typeSize(typeStack.top()) == 2) { typeStack = typeStack.pop(); typeStack = typeStack.pop(); } else typeStack = typeStack.pop(); } rvalue = Jimple.v().newSpecialInvokeExpr(Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()), method, Arrays.asList(params)); if(!returnType.equals(VoidType.v())) { stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex()), rvalue); } else stmt = Jimple.v().newInvokeStmt((InvokeExpr) rvalue); break; } case ByteCode.INVOKESTATIC: { Instruction_Invokestatic is = (Instruction_Invokestatic)ins; args = cp_info.countParams(constant_pool,is.arg_i); SootMethod method = null; CONSTANT_Methodref_info methodInfo = (CONSTANT_Methodref_info) constant_pool[is.arg_i]; CONSTANT_Class_info c = (CONSTANT_Class_info) constant_pool[methodInfo.class_index]; String className = ((CONSTANT_Utf8_info) (constant_pool[c.name_index])).convert(); className = className.replace('/', '.'); CONSTANT_NameAndType_info i = (CONSTANT_NameAndType_info) constant_pool[methodInfo.name_and_type_index]; String methodName = ((CONSTANT_Utf8_info) (constant_pool[i.name_index])).convert(); String methodDescriptor = ((CONSTANT_Utf8_info) (constant_pool[i.descriptor_index])). convert(); SootClass bclass = cm.getSootClass(className); Local[] parameters; List parameterTypes; Type returnType; // Generate parameters & returnType & parameterTypes { Type[] types = Util.v().jimpleTypesOfFieldOrMethodDescriptor(cm, methodDescriptor); parameterTypes = new ArrayList(); for(int k = 0; k < types.length - 1; k++) { parameterTypes.add(types[k]); } returnType = types[types.length - 1]; } method = bclass.getMethod(methodName, parameterTypes, returnType); // build Vector of parameters params = new Value[args]; for (int j=args-1;j>=0;j { /* G.v().out.println("BeforeTypeStack"); typeStack.print(G.v().out); G.v().out.println("AfterTypeStack"); postTypeStack.print(G.v().out); */ params[j] = Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()); if(typeSize(typeStack.top()) == 2) { typeStack = typeStack.pop(); typeStack = typeStack.pop(); } else typeStack = typeStack.pop(); } rvalue = Jimple.v().newStaticInvokeExpr(method, Arrays.asList(params)); if(!returnType.equals(VoidType.v())) { stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex()),rvalue); } else stmt = Jimple.v().newInvokeStmt((InvokeExpr) rvalue); break; } case ByteCode.INVOKEINTERFACE: { Instruction_Invokeinterface ii = (Instruction_Invokeinterface)ins; args = cp_info.countParams(constant_pool,ii.arg_i); SootMethod method = null; CONSTANT_InterfaceMethodref_info methodInfo = (CONSTANT_InterfaceMethodref_info) constant_pool[ii.arg_i]; CONSTANT_Class_info c = (CONSTANT_Class_info) constant_pool[methodInfo.class_index]; String className = ((CONSTANT_Utf8_info) (constant_pool[c.name_index])).convert(); className = className.replace('/', '.'); CONSTANT_NameAndType_info i = (CONSTANT_NameAndType_info) constant_pool[methodInfo.name_and_type_index]; String methodName = ((CONSTANT_Utf8_info) (constant_pool[i.name_index])).convert(); String methodDescriptor = ((CONSTANT_Utf8_info) (constant_pool[i.descriptor_index])). convert(); SootClass bclass = cm.getSootClass(className); Local[] parameters; List parameterTypes; Type returnType; // Generate parameters & returnType & parameterTypes { Type[] types = Util.v().jimpleTypesOfFieldOrMethodDescriptor(cm, methodDescriptor); parameterTypes = new ArrayList(); for(int k = 0; k < types.length - 1; k++) { parameterTypes.add(types[k]); } returnType = types[types.length - 1]; } method = bclass.getMethod(methodName, parameterTypes, returnType); // build Vector of parameters params = new Value[args]; for (int j=args-1;j>=0;j { params[j] = Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()); if(typeSize(typeStack.top()) == 2) { typeStack = typeStack.pop(); typeStack = typeStack.pop(); } else typeStack = typeStack.pop(); } rvalue = Jimple.v().newInterfaceInvokeExpr(Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()), method, Arrays.asList(params)); if(!returnType.equals(VoidType.v())) { stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex()), rvalue); } else stmt = Jimple.v().newInvokeStmt((InvokeExpr) rvalue); break; } case ByteCode.ATHROW: stmt = Jimple.v().newThrowStmt(Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex())); break; case ByteCode.NEW: { SootClass bclass = cm.getSootClass(getClassName(constant_pool, ((Instruction_New)ins).arg_i)); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex()), Jimple.v().newNewExpr(RefType.v(bclass.getName()))); break; } case ByteCode.CHECKCAST: { String className = getClassName(constant_pool, ((Instruction_Checkcast)ins).arg_i); Type castType; if(className.startsWith("[")) castType = Util.v().jimpleTypeOfFieldDescriptor(cm, getClassName(constant_pool, ((Instruction_Checkcast)ins).arg_i)); else castType = RefType.v(className); rhs = Jimple.v().newCastExpr(Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()), castType); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex()),rhs); break; } case ByteCode.INSTANCEOF: { Type checkType; String className = getClassName(constant_pool, ((Instruction_Instanceof)ins).arg_i); if(className.startsWith("[")) checkType = Util.v().jimpleTypeOfFieldDescriptor(cm, getClassName(constant_pool, ((Instruction_Instanceof)ins).arg_i)); else checkType = RefType.v(className); rhs = Jimple.v().newInstanceOfExpr(Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex()), checkType); stmt = Jimple.v().newAssignStmt(Util.v().getLocalForStackOp(listBody, postTypeStack, postTypeStack.topIndex()),rhs); break; } case ByteCode.MONITORENTER: stmt = Jimple.v().newEnterMonitorStmt(Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex())); break; case ByteCode.MONITOREXIT: stmt = Jimple.v().newExitMonitorStmt(Util.v().getLocalForStackOp(listBody, typeStack, typeStack.topIndex())); break; default: throw new RuntimeException("Unrecognized bytecode instruction: " + x); } if(stmt != null) { if (Options.v().keep_offset()) { stmt.addTag(new BytecodeOffsetTag(ins.label)); } statements.add(stmt); } } Type jimpleTypeOfAtype(int atype) { switch(atype) { case 4: return BooleanType.v(); case 5: return CharType.v(); case 6: return FloatType.v(); case 7: return DoubleType.v(); case 8: return ByteType.v(); case 9: return ShortType.v(); case 10: return IntType.v(); case 11: return LongType.v(); default: throw new RuntimeException("Undefined 'atype' in NEWARRAY byte instruction"); } } int typeSize(Type type) { if (type.equals(LongType.v()) || type.equals(DoubleType.v()) || type.equals(Long2ndHalfType.v()) || type.equals(Double2ndHalfType.v())) { return 2; } else return 1; } } class OutFlow { TypeStack typeStack; OutFlow(TypeStack typeStack) { this.typeStack = typeStack; } }
package com.matabii.dev.scaleimageview; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Matrix; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.util.FloatMath; import android.view.GestureDetector; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.widget.ImageView; public class ScaleImageView extends ImageView implements OnTouchListener { private float MAX_SCALE = 2f; private Matrix mMatrix; private final float[] mMatrixValues = new float[9]; // display width height. private int mWidth; private int mHeight; private int mIntrinsicWidth; private int mIntrinsicHeight; private float mScale; private float mMinScale; private float mPrevDistance; private boolean isScaling; private int mPrevMoveX; private int mPrevMoveY; private GestureDetector mDetector; String TAG = "ScaleImageView"; public ScaleImageView(Context context, AttributeSet attr) { super(context, attr); initialize(); } public ScaleImageView(Context context) { super(context); initialize(); } @Override public void setImageBitmap(Bitmap bm) { super.setImageBitmap(bm); this.initialize(); } private void initialize() { this.setScaleType(ScaleType.MATRIX); this.mMatrix = new Matrix(); Drawable d = getDrawable(); if (d != null) { mIntrinsicWidth = d.getIntrinsicWidth(); mIntrinsicHeight = d.getIntrinsicHeight(); setOnTouchListener(this); } mDetector = new GestureDetector(new GestureDetector.SimpleOnGestureListener() { @Override public boolean onDoubleTap(MotionEvent e) { maxZoomTo((int) e.getX(), (int) e.getY()); cutting(); return super.onDoubleTap(e); } }); } @Override protected boolean setFrame(int l, int t, int r, int b) { mWidth = r - l; mHeight = b - t; mMatrix.reset(); mScale = (float) r / (float) mIntrinsicWidth; int paddingHeight = 0; int paddingWidth = 0; // scaling vertical if (mScale * mIntrinsicHeight > mHeight) { mScale = (float) mHeight / (float) mIntrinsicHeight; mMatrix.postScale(mScale, mScale); paddingWidth = (r - mWidth) / 2; paddingHeight = 0; // scaling horizontal } else { mMatrix.postScale(mScale, mScale); paddingHeight = (b - mHeight) / 2; paddingWidth = 0; } mMatrix.postTranslate(paddingWidth, paddingHeight); setImageMatrix(mMatrix); mMinScale = mScale; zoomTo(mScale, mWidth / 2, mHeight / 2); cutting(); return super.setFrame(l, t, r, b); } protected float getValue(Matrix matrix, int whichValue) { matrix.getValues(mMatrixValues); return mMatrixValues[whichValue]; } protected float getScale() { return getValue(mMatrix, Matrix.MSCALE_X); } public float getTranslateX() { return getValue(mMatrix, Matrix.MTRANS_X); } protected float getTranslateY() { return getValue(mMatrix, Matrix.MTRANS_Y); } protected void maxZoomTo(int x, int y) { if (mMinScale != getScale() && (getScale() - mMinScale) > 0.1f) { // threshold 0.1f float scale = mMinScale / getScale(); zoomTo(scale, x, y); } else { float scale = MAX_SCALE / getScale(); zoomTo(scale, x, y); } } public void zoomTo(float scale, int x, int y) { if (getScale() * scale < mMinScale) { return; } if (scale >= 1 && getScale() * scale > MAX_SCALE) { return; } mMatrix.postScale(scale, scale); // move to center mMatrix.postTranslate(-(mWidth * scale - mWidth) / 2, -(mHeight * scale - mHeight) / 2); // move x and y distance mMatrix.postTranslate(-(x - (mWidth / 2)) * scale, 0); mMatrix.postTranslate(0, -(y - (mHeight / 2)) * scale); setImageMatrix(mMatrix); } public void cutting() { int width = (int) (mIntrinsicWidth * getScale()); int height = (int) (mIntrinsicHeight * getScale()); if (getTranslateX() < -(width - mWidth)) { mMatrix.postTranslate(-(getTranslateX() + width - mWidth), 0); } if (getTranslateX() > 0) { mMatrix.postTranslate(-getTranslateX(), 0); } if (getTranslateY() < -(height - mHeight)) { mMatrix.postTranslate(0, -(getTranslateY() + height - mHeight)); } if (getTranslateY() > 0) { mMatrix.postTranslate(0, -getTranslateY()); } if (width < mWidth) { mMatrix.postTranslate((mWidth - width) / 2, 0); } if (height < mHeight) { mMatrix.postTranslate(0, (mHeight - height) / 2); } setImageMatrix(mMatrix); } private float distance(float x0, float x1, float y0, float y1) { float x = x0 - x1; float y = y0 - y1; return FloatMath.sqrt(x * x + y * y); } private float dispDistance() { return FloatMath.sqrt(mWidth * mWidth + mHeight * mHeight); } @Override public boolean onTouchEvent(MotionEvent event) { if (mDetector.onTouchEvent(event)) { return true; } int touchCount = event.getPointerCount(); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_POINTER_1_DOWN: case MotionEvent.ACTION_POINTER_2_DOWN: if (touchCount >= 2) { float distance = distance(event.getX(0), event.getX(1), event.getY(0), event.getY(1)); mPrevDistance = distance; isScaling = true; } else { mPrevMoveX = (int) event.getX(); mPrevMoveY = (int) event.getY(); } case MotionEvent.ACTION_MOVE: if (touchCount >= 2 && isScaling) { float dist = distance(event.getX(0), event.getX(1), event.getY(0), event.getY(1)); float scale = (dist - mPrevDistance) / dispDistance(); mPrevDistance = dist; scale += 1; scale = scale * scale; zoomTo(scale, mWidth / 2, mHeight / 2); cutting(); } else if (!isScaling) { int distanceX = mPrevMoveX - (int) event.getX(); int distanceY = mPrevMoveY - (int) event.getY(); mPrevMoveX = (int) event.getX(); mPrevMoveY = (int) event.getY(); mMatrix.postTranslate(-distanceX, -distanceY); cutting(); } break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_POINTER_UP: case MotionEvent.ACTION_POINTER_2_UP: if (event.getPointerCount() <= 1) { isScaling = false; } break; } return true; } @Override public boolean onTouch(View v, MotionEvent event) { return super.onTouchEvent(event); } }
package com.mebigfatguy.fbcontrib.detect; import java.util.HashMap; import java.util.Map; import java.util.Objects; import org.apache.bcel.classfile.AnnotationEntry; import org.apache.bcel.classfile.Field; import org.apache.bcel.classfile.JavaClass; import com.mebigfatguy.fbcontrib.utils.BugType; import com.mebigfatguy.fbcontrib.utils.ToString; import com.mebigfatguy.fbcontrib.utils.Values; import edu.umd.cs.findbugs.BugInstance; import edu.umd.cs.findbugs.BugReporter; import edu.umd.cs.findbugs.Detector; import edu.umd.cs.findbugs.FieldAnnotation; import edu.umd.cs.findbugs.ba.ClassContext; import edu.umd.cs.findbugs.visitclass.PreorderVisitor; public class WiringIssues extends PreorderVisitor implements Detector { private static final String SPRING_AUTOWIRED = "Lorg/springframework/beans/factory/annotation/Autowired;"; private static final String SPRING_QUALIFIER = "Lorg/springframework/beans/factory/annotation/Qualifier;"; private BugReporter bugReporter; public WiringIssues(BugReporter bugReporter) { this.bugReporter = bugReporter; } @edu.umd.cs.findbugs.annotations.SuppressFBWarnings(value = "SF_SWITCH_NO_DEFAULT", justification = "Only a few cases need special handling") @Override public void visitClassContext(ClassContext classContext) { try { JavaClass cls = classContext.getJavaClass(); Field[] fields = cls.getFields(); if (fields.length > 0) { Map<WiringType, FieldAnnotation> wiredFields = new HashMap<>(); boolean loadedParents = false; for (Field field : fields) { boolean hasAutowired = false; String qualifier = ""; for (AnnotationEntry entry : field.getAnnotationEntries()) { switch (entry.getAnnotationType()) { case SPRING_AUTOWIRED: if (!loadedParents) { loadParentAutowireds(cls.getSuperClass(), wiredFields); loadedParents = true; } hasAutowired = true; break; case SPRING_QUALIFIER: qualifier = entry.getElementValuePairs()[0].getValue().stringifyValue(); break; } } if (hasAutowired) { WiringType wt = new WiringType(field.getSignature(), field.getGenericSignature(), qualifier); FieldAnnotation existingAnnotation = wiredFields.get(wt); if (existingAnnotation != null) { bugReporter.reportBug(new BugInstance(this, BugType.WI_DUPLICATE_WIRED_TYPES.name(), NORMAL_PRIORITY).addClass(cls) .addField(existingAnnotation).addField(FieldAnnotation.fromBCELField(cls, field))); wiredFields.remove(wt); } else { wiredFields.put(wt, FieldAnnotation.fromBCELField(cls.getClassName(), field)); } } } } } catch (ClassNotFoundException e) { bugReporter.reportMissingClass(e); } } @Override public void report() { // required by the interface, but not used } @edu.umd.cs.findbugs.annotations.SuppressFBWarnings(value = "SF_SWITCH_NO_DEFAULT", justification = "Only a few cases need special handling") private void loadParentAutowireds(JavaClass cls, Map<WiringType, FieldAnnotation> wiredFields) throws ClassNotFoundException { if (Values.DOTTED_JAVA_LANG_OBJECT.equals(cls.getClassName())) { return; } loadParentAutowireds(cls.getSuperClass(), wiredFields); Field[] fields = cls.getFields(); if (fields.length > 0) { for (Field field : fields) { boolean hasAutowired = false; String qualifier = ""; for (AnnotationEntry entry : field.getAnnotationEntries()) { switch (entry.getAnnotationType()) { case SPRING_AUTOWIRED: hasAutowired = true; break; case SPRING_QUALIFIER: qualifier = entry.getElementValuePairs()[0].getValue().stringifyValue(); break; } } if (hasAutowired) { WiringType wt = new WiringType(field.getSignature(), field.getGenericSignature(), qualifier); wiredFields.put(wt, FieldAnnotation.fromBCELField(cls.getClassName(), field)); } } } } static class WiringType { String signature; String genericSignature; String qualifier; public WiringType(String fieldSignature, String genSignature, String qualifierName) { signature = fieldSignature; genericSignature = genSignature; qualifier = qualifierName; } @Override public boolean equals(Object o) { if (!(o instanceof WiringType)) { return false; } WiringType that = (WiringType) o; return signature.equals(that.signature) && Objects.equals(genericSignature, that.genericSignature) && qualifier.equals(that.qualifier); } @Override public int hashCode() { return signature.hashCode() ^ qualifier.hashCode() ^ ((genericSignature != null) ? genericSignature.hashCode() : 0); } @Override public String toString() { return ToString.build(this); } } }
package org.xcordion.ide.intellij.story; import com.intellij.compiler.CompilerWorkspaceConfiguration; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.compiler.CompileContext; import com.intellij.openapi.compiler.CompileScope; import com.intellij.openapi.compiler.CompileStatusNotification; import com.intellij.openapi.compiler.CompilerManager; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.actionSystem.EditorActionHandler; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.progress.PerformInBackgroundOption; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.progress.Task; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.ModuleRootManager; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiJavaFile; import org.hiro.psi.PsiHelper; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; public class StoryRunnerActionHandler extends EditorActionHandler { private static final int YES_RESPONSE = 0; private PsiHelper psiHelper; private boolean runInMemory; private Editor editor; public void execute(Editor editor, DataContext dataContext) { this.editor = editor; this.psiHelper = new PsiHelper(dataContext); determineRunningTestsInMemory(); make(); } private void determineRunningTestsInMemory() { runInMemory = YES_RESPONSE == Messages.showYesNoDialog("Wanna run test in memory?", "", Messages.getQuestionIcon()); } private void make() { compileAndRunTests(getTestsToRun()); } private List<TestToRun> getTestsToRun() { PsiFile storyPage = psiHelper.getCurrentFile(); List<String> htmlFileNames = getConcordionTestFileNames(storyPage, editor); List<TestToRun> testFiles = new ArrayList<TestToRun>(); for (String htmlFileName : htmlFileNames) { VirtualFile testHtmlFile = storyPage.getVirtualFile().getParent().findFileByRelativePath(htmlFileName); TestToRun testToRun = new TestToRun(htmlFileName); if (testHtmlFile != null) { setupTestToRun(testHtmlFile, testToRun); } testFiles.add(testToRun); } return testFiles; } private void compileAndRunTests(final List<TestToRun> testsToRun) { final Project project = psiHelper.getProject(); final boolean autoShowErrorsInEditor = CompilerWorkspaceConfiguration.getInstance(project).AUTO_SHOW_ERRORS_IN_EDITOR; final boolean compileInBackground = CompilerWorkspaceConfiguration.getInstance(project).COMPILE_IN_BACKGROUND; CompilerWorkspaceConfiguration.getInstance(project).COMPILE_IN_BACKGROUND = false; Set<VirtualFile> testFiles = new HashSet<VirtualFile>(); for (TestToRun testToRun : testsToRun) { if (testToRun.hasJavaFile()) { testFiles.add(testToRun.getHtmlVirtualFile()); testFiles.add(testToRun.getJavaVirtualFile()); } } CompileScope compileScope = CompilerManager.getInstance(project).createFilesCompileScope(testFiles.toArray(new VirtualFile[testFiles.size()])); CompilerManager.getInstance(project).compile(compileScope, new CompileStatusNotification() { public void finished(boolean aborted, int errors, int warnings, CompileContext compileContext) { if (!aborted && errors == YES_RESPONSE) { runTests(testsToRun, runInMemory); } } }, true); CompilerWorkspaceConfiguration.getInstance(project).AUTO_SHOW_ERRORS_IN_EDITOR = autoShowErrorsInEditor; CompilerWorkspaceConfiguration.getInstance(project).COMPILE_IN_BACKGROUND = compileInBackground; } private void runTests(final List<TestToRun> testsToRun, final boolean runInMemory) { PerformInBackgroundOption backgroundOption = new PerformInBackgroundOption() { public boolean shouldStartInBackground() { return false; } public void processSentToBackground() { } }; ProgressManager.getInstance().run(new Task.Backgroundable(psiHelper.getProject(), "Story Runner", true, backgroundOption) { public void run(@NotNull ProgressIndicator progressIndicator) { JavaTestRunner testRunner = new JavaTestRunner(testsToRun, runInMemory); List<TestResultLogger> results = testRunner.getTestResults(); PsiFile storyPage = psiHelper.getCurrentFile(); new StoryPageResults(storyPage.getName(), storyPage.getText(), results).save(); } }); } private List<String> getConcordionTestFileNames(PsiFile storyPage, Editor editor) { List<String> testHtmlNames = new ArrayList<String>(); String selectedContent; if(editor.getSelectionModel().hasSelection()) { selectedContent = editor.getSelectionModel().getSelectedText(); } else { selectedContent = storyPage.getText(); } Matcher matcher = Pattern.compile("<a.*?href=\"([../]+.*.html)\"").matcher(selectedContent); while (matcher.find()) { testHtmlNames.add(matcher.group(1)); } return testHtmlNames; } private Module getModule(Project project, VirtualFile testJavaFile) { Module testModule = null; Module[] modules = ModuleManager.getInstance(project).getModules(); for (Module module : modules) { ModuleRootManager moduleRootManager = ModuleRootManager.getInstance(module); if (moduleRootManager.getFileIndex().isInSourceContent(testJavaFile)) { testModule = module; break; } } return testModule; } private String toFullyQualifyJavaClassName(VirtualFile testJavaFile, PsiHelper psiHelper) { PsiFile psiFile = psiHelper.getPsiManager().findFile(testJavaFile); PsiJavaFile psiJavaFile = (PsiJavaFile) psiFile; return psiJavaFile.getPackageName() + '.' + testJavaFile.getNameWithoutExtension(); } private void setupTestToRun(VirtualFile testHtmlFile, TestToRun testToRun) { VirtualFile testJavaFile = testHtmlFile.getParent().findFileByRelativePath(testHtmlFile.getNameWithoutExtension() + "Test.java"); if (testJavaFile != null) { Module testModule = getModule(psiHelper.getProject(), testJavaFile); testToRun.setModule(testModule); testToRun.setHtmlVirtualFile(testHtmlFile); testToRun.setJavaVirtualFile(testJavaFile); testToRun.setFullyQualifiedClassName(toFullyQualifyJavaClassName(testJavaFile, psiHelper)); } } }
package com.thoughtworks.xstream.converters.reflection; import com.thoughtworks.xstream.converters.ConversionException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Map; import java.util.HashMap; import java.util.Collections; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; /** * Convenience wrapper to invoke special serialization methods on objects (and perform reflection caching). * * @author Joe Walnes */ public class SerializationMethodInvoker { private Map cache = Collections.synchronizedMap(new HashMap()); private static final Object NO_METHOD = new Object(); /** * Resolves an object as native serialization does by calling readResolve(), if available. */ public Object callReadResolve(Object result) { if (result == null) { return null; } else { Method readResolveMethod = getMethod(result.getClass(), "readResolve", null); if (readResolveMethod != null) { try { return readResolveMethod.invoke(result, null); } catch (IllegalAccessException e) { throw new ObjectAccessException("Could not call " + result.getClass().getName() + ".readResolve()", e); } catch (InvocationTargetException e) { throw new ObjectAccessException("Could not call " + result.getClass().getName() + ".readResolve()", e); } } else { return result; } } } public boolean supportsReadObject(Class type) { return getMethod(type, "readObject", new Class[]{ObjectInputStream.class}) != null; } public void callReadObject(Object object, ObjectInputStream stream) { try { Method readObjectMethod = getMethod(object.getClass(), "readObject", new Class[]{ObjectInputStream.class}); readObjectMethod.invoke(object, new Object[]{stream}); } catch (IllegalAccessException e) { throw new ConversionException("Could not call " + object.getClass().getName() + ".readObject()", e); } catch (InvocationTargetException e) { throw new ConversionException("Could not call " + object.getClass().getName() + ".readObject()", e); } } public boolean supportsWriteObject(Class type) { return getMethod(type, "writeObject", new Class[]{ObjectOutputStream.class}) != null; } public void callWriteObject(Object object, ObjectOutputStream stream) { try { Method readObjectMethod = getMethod(object.getClass(), "writeObject", new Class[]{ObjectOutputStream.class}); readObjectMethod.invoke(object, new Object[]{stream}); } catch (IllegalAccessException e) { throw new ConversionException("Could not call " + object.getClass().getName() + ".readObject()", e); } catch (InvocationTargetException e) { throw new ConversionException("Could not call " + object.getClass().getName() + ".readObject()", e); } } private Method getMethod(Class type, String name, Class[] parameterTypes) { Object key = type.getName() + "." + name; if (cache.containsKey(key)) { Object result = cache.get(key); return (Method) (result == NO_METHOD ? null : result); } while (type != null) { try { Method result = type.getDeclaredMethod(name, parameterTypes); result.setAccessible(true); cache.put(key, result); return result; } catch (NoSuchMethodException e) { type = type.getSuperclass(); } } cache.put(key, NO_METHOD); return null; } }