diff
stringlengths
164
2.11M
is_single_chunk
bool
2 classes
is_single_function
bool
2 classes
buggy_function
stringlengths
0
335k
fixed_function
stringlengths
23
335k
diff --git a/activemq-core/src/main/java/org/apache/activemq/store/kahadb/MessageDatabase.java b/activemq-core/src/main/java/org/apache/activemq/store/kahadb/MessageDatabase.java index 65d491a03..c3a69cb1b 100644 --- a/activemq-core/src/main/java/org/apache/activemq/store/kahadb/MessageDatabase.java +++ b/activemq-core/src/main/java/org/apache/activemq/store/kahadb/MessageDatabase.java @@ -1,2451 +1,2454 @@ /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activemq.store.kahadb; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.*; import java.util.*; import java.util.Map.Entry; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.locks.ReentrantReadWriteLock; import org.apache.activemq.ActiveMQMessageAuditNoSync; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.BrokerServiceAware; import org.apache.activemq.command.ActiveMQDestination; import org.apache.activemq.command.ConnectionId; import org.apache.activemq.command.LocalTransactionId; import org.apache.activemq.command.MessageAck; import org.apache.activemq.command.MessageId; import org.apache.activemq.command.SubscriptionInfo; import org.apache.activemq.command.TransactionId; import org.apache.activemq.command.XATransactionId; import org.apache.activemq.protobuf.Buffer; import org.apache.activemq.store.kahadb.data.*; import org.apache.activemq.util.Callback; import org.apache.activemq.util.IOHelper; import org.apache.activemq.util.ServiceStopper; import org.apache.activemq.util.ServiceSupport; import org.apache.kahadb.index.BTreeIndex; import org.apache.kahadb.index.BTreeVisitor; import org.apache.kahadb.journal.DataFile; import org.apache.kahadb.journal.Journal; import org.apache.kahadb.journal.Location; import org.apache.kahadb.page.Page; import org.apache.kahadb.page.PageFile; import org.apache.kahadb.page.Transaction; import org.apache.kahadb.util.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class MessageDatabase extends ServiceSupport implements BrokerServiceAware { protected BrokerService brokerService; public static final String PROPERTY_LOG_SLOW_ACCESS_TIME = "org.apache.activemq.store.kahadb.LOG_SLOW_ACCESS_TIME"; public static final int LOG_SLOW_ACCESS_TIME = Integer.parseInt(System.getProperty(PROPERTY_LOG_SLOW_ACCESS_TIME, "0")); protected static final Buffer UNMATCHED; static { UNMATCHED = new Buffer(new byte[]{}); } private static final Logger LOG = LoggerFactory.getLogger(MessageDatabase.class); private static final int DEFAULT_DATABASE_LOCKED_WAIT_DELAY = 10 * 1000; static final int CLOSED_STATE = 1; static final int OPEN_STATE = 2; static final long NOT_ACKED = -1; static final long UNMATCHED_SEQ = -2; static final int VERSION = 3; protected class Metadata { protected Page<Metadata> page; protected int state; protected BTreeIndex<String, StoredDestination> destinations; protected Location lastUpdate; protected Location firstInProgressTransactionLocation; protected Location producerSequenceIdTrackerLocation = null; protected transient ActiveMQMessageAuditNoSync producerSequenceIdTracker = new ActiveMQMessageAuditNoSync(); protected int version = VERSION; public void read(DataInput is) throws IOException { state = is.readInt(); destinations = new BTreeIndex<String, StoredDestination>(pageFile, is.readLong()); if (is.readBoolean()) { lastUpdate = LocationMarshaller.INSTANCE.readPayload(is); } else { lastUpdate = null; } if (is.readBoolean()) { firstInProgressTransactionLocation = LocationMarshaller.INSTANCE.readPayload(is); } else { firstInProgressTransactionLocation = null; } try { if (is.readBoolean()) { producerSequenceIdTrackerLocation = LocationMarshaller.INSTANCE.readPayload(is); } else { producerSequenceIdTrackerLocation = null; } } catch (EOFException expectedOnUpgrade) { } try { version = is.readInt(); } catch (EOFException expectedOnUpgrade) { version = 1; } LOG.info("KahaDB is version " + version); } public void write(DataOutput os) throws IOException { os.writeInt(state); os.writeLong(destinations.getPageId()); if (lastUpdate != null) { os.writeBoolean(true); LocationMarshaller.INSTANCE.writePayload(lastUpdate, os); } else { os.writeBoolean(false); } if (firstInProgressTransactionLocation != null) { os.writeBoolean(true); LocationMarshaller.INSTANCE.writePayload(firstInProgressTransactionLocation, os); } else { os.writeBoolean(false); } if (producerSequenceIdTrackerLocation != null) { os.writeBoolean(true); LocationMarshaller.INSTANCE.writePayload(producerSequenceIdTrackerLocation, os); } else { os.writeBoolean(false); } os.writeInt(VERSION); } } class MetadataMarshaller extends VariableMarshaller<Metadata> { public Metadata readPayload(DataInput dataIn) throws IOException { Metadata rc = new Metadata(); rc.read(dataIn); return rc; } public void writePayload(Metadata object, DataOutput dataOut) throws IOException { object.write(dataOut); } } protected PageFile pageFile; protected JournalManager journalManager; protected Metadata metadata = new Metadata(); protected MetadataMarshaller metadataMarshaller = new MetadataMarshaller(); protected boolean failIfDatabaseIsLocked; protected boolean deleteAllMessages; protected File directory = new File("KahaDB"); protected Thread checkpointThread; protected boolean enableJournalDiskSyncs = true; protected boolean archiveDataLogs; protected File directoryArchive; protected AtomicLong storeSize = new AtomicLong(0); long checkpointInterval = 5 * 1000; long cleanupInterval = 30 * 1000; int journalMaxFileLength = Journal.DEFAULT_MAX_FILE_LENGTH; int journalMaxWriteBatchSize = Journal.DEFAULT_MAX_WRITE_BATCH_SIZE; boolean enableIndexWriteAsync = false; int setIndexWriteBatchSize = PageFile.DEFAULT_WRITE_BATCH_SIZE; protected AtomicBoolean opened = new AtomicBoolean(); private LockFile lockFile; private boolean ignoreMissingJournalfiles = false; private int indexCacheSize = 10000; private boolean checkForCorruptJournalFiles = false; private boolean checksumJournalFiles = false; private int databaseLockedWaitDelay = DEFAULT_DATABASE_LOCKED_WAIT_DELAY; protected boolean forceRecoverIndex = false; private final Object checkpointThreadLock = new Object(); private boolean journalPerDestination = false; public MessageDatabase() { } @Override public void doStart() throws Exception { load(); } @Override public void doStop(ServiceStopper stopper) throws Exception { unload(); } private void loadPageFile() throws IOException { this.indexLock.writeLock().lock(); try { final PageFile pageFile = getPageFile(); pageFile.load(); pageFile.tx().execute(new Transaction.Closure<IOException>() { public void execute(Transaction tx) throws IOException { if (pageFile.getPageCount() == 0) { // First time this is created.. Initialize the metadata Page<Metadata> page = tx.allocate(); assert page.getPageId() == 0; page.set(metadata); metadata.page = page; metadata.state = CLOSED_STATE; metadata.destinations = new BTreeIndex<String, StoredDestination>(pageFile, tx.allocate().getPageId()); tx.store(metadata.page, metadataMarshaller, true); } else { Page<Metadata> page = tx.load(0, metadataMarshaller); metadata = page.get(); metadata.page = page; } metadata.destinations.setKeyMarshaller(StringMarshaller.INSTANCE); metadata.destinations.setValueMarshaller(new StoredDestinationMarshaller()); metadata.destinations.load(tx); } }); // Load up all the destinations since we need to scan all the indexes to figure out which journal files can be deleted. // Perhaps we should just keep an index of file storedDestinations.clear(); pageFile.tx().execute(new Transaction.Closure<IOException>() { public void execute(Transaction tx) throws IOException { for (Iterator<Entry<String, StoredDestination>> iterator = metadata.destinations.iterator(tx); iterator.hasNext(); ) { Entry<String, StoredDestination> entry = iterator.next(); StoredDestination sd = loadStoredDestination(tx, entry.getKey(), entry.getValue().subscriptions != null); storedDestinations.put(entry.getKey(), sd); } } }); pageFile.flush(); } finally { this.indexLock.writeLock().unlock(); } } private void startCheckpoint() { synchronized (checkpointThreadLock) { boolean start = false; if (checkpointThread == null) { start = true; } else if (!checkpointThread.isAlive()) { start = true; LOG.info("KahaDB: Recovering checkpoint thread after death"); } if (start) { checkpointThread = new Thread("ActiveMQ Journal Checkpoint Worker") { @Override public void run() { try { long lastCleanup = System.currentTimeMillis(); long lastCheckpoint = System.currentTimeMillis(); // Sleep for a short time so we can periodically check // to see if we need to exit this thread. long sleepTime = Math.min(checkpointInterval, 500); while (opened.get()) { Thread.sleep(sleepTime); long now = System.currentTimeMillis(); if (now - lastCleanup >= cleanupInterval) { checkpointCleanup(true); lastCleanup = now; lastCheckpoint = now; } else if (now - lastCheckpoint >= checkpointInterval) { checkpointCleanup(false); lastCheckpoint = now; } } } catch (InterruptedException e) { // Looks like someone really wants us to exit this thread... } catch (IOException ioe) { LOG.error("Checkpoint failed", ioe); brokerService.handleIOException(ioe); } } }; checkpointThread.setDaemon(true); checkpointThread.start(); } } } public void open() throws IOException { if (opened.compareAndSet(false, true)) { getJournalManager().start(); loadPageFile(); startCheckpoint(); recover(); } } private void lock() throws IOException { if (lockFile == null) { File lockFileName = new File(directory, "lock"); lockFile = new LockFile(lockFileName, true); if (failIfDatabaseIsLocked) { lockFile.lock(); } else { boolean locked = false; while ((!isStopped()) && (!isStopping())) { try { lockFile.lock(); locked = true; break; } catch (IOException e) { LOG.info("Database " + lockFileName + " is locked... waiting " + (getDatabaseLockedWaitDelay() / 1000) + " seconds for the database to be unlocked. Reason: " + e); try { Thread.sleep(getDatabaseLockedWaitDelay()); } catch (InterruptedException e1) { } } } if (!locked) { throw new IOException("attempt to obtain lock aborted due to shutdown"); } } } } // for testing public LockFile getLockFile() { return lockFile; } public void load() throws IOException { this.indexLock.writeLock().lock(); try { lock(); if (deleteAllMessages) { getJournalManager().start(); getJournalManager().delete(); getJournalManager().close(); journalManager = null; getPageFile().delete(); LOG.info("Persistence store purged."); deleteAllMessages = false; } open(); for (Journal journal : getJournalManager().getJournals()) { store(journal, new KahaTraceCommand().setMessage("LOADED " + new Date())); } } finally { this.indexLock.writeLock().unlock(); } } public void close() throws IOException, InterruptedException { if (opened.compareAndSet(true, false)) { this.indexLock.writeLock().lock(); try { pageFile.tx().execute(new Transaction.Closure<IOException>() { public void execute(Transaction tx) throws IOException { for (Journal journal : getJournalManager().getJournals()) { checkpointUpdate(tx, journal, true); } } }); pageFile.unload(); metadata = new Metadata(); } finally { this.indexLock.writeLock().unlock(); } journalManager.close(); synchronized (checkpointThreadLock) { checkpointThread.join(); } lockFile.unlock(); lockFile = null; } } public void unload() throws IOException, InterruptedException { this.indexLock.writeLock().lock(); try { if (pageFile != null && pageFile.isLoaded()) { metadata.state = CLOSED_STATE; metadata.firstInProgressTransactionLocation = getFirstInProgressTxLocation(); pageFile.tx().execute(new Transaction.Closure<IOException>() { public void execute(Transaction tx) throws IOException { tx.store(metadata.page, metadataMarshaller, true); } }); } } finally { this.indexLock.writeLock().unlock(); } close(); } // public for testing public Location getFirstInProgressTxLocation() { Location l = null; synchronized (inflightTransactions) { if (!inflightTransactions.isEmpty()) { l = inflightTransactions.values().iterator().next().get(0).getLocation(); } if (!preparedTransactions.isEmpty()) { Location t = preparedTransactions.values().iterator().next().get(0).getLocation(); if (l == null || t.compareTo(l) <= 0) { l = t; } } } return l; } /** * Move all the messages that were in the journal into long term storage. We * just replay and do a checkpoint. */ private void recover() throws IllegalStateException, IOException { this.indexLock.writeLock().lock(); try { for (Journal journal : getJournalManager().getJournals()) { recover(journal); } } finally { this.indexLock.writeLock().unlock(); } } private void recover(final Journal journal) throws IllegalStateException, IOException { long start = System.currentTimeMillis(); Location producerAuditPosition = recoverProducerAudit(journal); Location lastIndoubtPosition = getRecoveryPosition(journal); Location recoveryPosition = minimum(producerAuditPosition, lastIndoubtPosition); if (recoveryPosition != null) { int redoCounter = 0; LOG.info("Recovering from the journal ..."); while (recoveryPosition != null) { JournalCommand<?> message = load(journal, recoveryPosition); metadata.lastUpdate = recoveryPosition; process(message, recoveryPosition, lastIndoubtPosition); redoCounter++; recoveryPosition = journal.getNextLocation(recoveryPosition); } long end = System.currentTimeMillis(); LOG.info("Recovery replayed " + redoCounter + " operations from the journal in " + ((end - start) / 1000.0f) + " seconds."); } // We may have to undo some index updates. pageFile.tx().execute(new Transaction.Closure<IOException>() { public void execute(Transaction tx) throws IOException { recoverIndex(tx, journal); } }); // rollback any recovered inflight local transactions Set<TransactionId> toRollback = new HashSet<TransactionId>(); synchronized (inflightTransactions) { for (Iterator<TransactionId> it = inflightTransactions.keySet().iterator(); it.hasNext(); ) { TransactionId id = it.next(); if (id.isLocalTransaction()) { toRollback.add(id); } } for (TransactionId tx : toRollback) { LOG.debug("rolling back recovered indoubt local transaction " + tx); store(journal, new KahaRollbackCommand().setTransactionInfo(createTransactionInfo(tx)), false, null, null); } } } private Location minimum(Location producerAuditPosition, Location lastIndoubtPosition) { Location min = null; if (producerAuditPosition != null) { min = producerAuditPosition; if (lastIndoubtPosition != null && lastIndoubtPosition.compareTo(producerAuditPosition) < 0) { min = lastIndoubtPosition; } } else { min = lastIndoubtPosition; } return min; } private Location recoverProducerAudit(Journal journal) throws IOException { if (metadata.producerSequenceIdTrackerLocation != null) { KahaProducerAuditCommand audit = (KahaProducerAuditCommand) load(journal, metadata.producerSequenceIdTrackerLocation); try { ObjectInputStream objectIn = new ObjectInputStream(audit.getAudit().newInput()); metadata.producerSequenceIdTracker = (ActiveMQMessageAuditNoSync) objectIn.readObject(); return journal.getNextLocation(metadata.producerSequenceIdTrackerLocation); } catch (Exception e) { LOG.warn("Cannot recover message audit", e); return journal.getNextLocation(null); } } else { // got no audit stored so got to recreate via replay from start of the journal return journal.getNextLocation(null); } } protected void recoverIndex(Transaction tx, Journal journal) throws IOException { long start = System.currentTimeMillis(); // It is possible index updates got applied before the journal updates.. // in that case we need to removed references to messages that are not in the journal final Location lastAppendLocation = journal.getLastAppendLocation(); long undoCounter = 0; // Go through all the destinations to see if they have messages past the lastAppendLocation for (StoredDestination sd : storedDestinations.values()) { final ArrayList<Long> matches = new ArrayList<Long>(); // Find all the Locations that are >= than the last Append Location. sd.locationIndex.visit(tx, new BTreeVisitor.GTEVisitor<Location, Long>(lastAppendLocation) { @Override protected void matched(Location key, Long value) { matches.add(value); } }); for (Long sequenceId : matches) { MessageKeys keys = sd.orderIndex.remove(tx, sequenceId); sd.locationIndex.remove(tx, keys.location); sd.messageIdIndex.remove(tx, keys.messageId); metadata.producerSequenceIdTracker.rollback(keys.messageId); undoCounter++; // TODO: do we need to modify the ack positions for the pub sub case? } } long end = System.currentTimeMillis(); if (undoCounter > 0) { // The rolledback operations are basically in flight journal writes. To avoid getting these the end user // should do sync writes to the journal. LOG.info("Rolled back " + undoCounter + " messages from the index in " + ((end - start) / 1000.0f) + " seconds."); } undoCounter = 0; start = System.currentTimeMillis(); // Lets be extra paranoid here and verify that all the datafiles being referenced // by the indexes still exists. final SequenceSet ss = new SequenceSet(); for (StoredDestination sd : storedDestinations.values()) { // Use a visitor to cut down the number of pages that we load sd.locationIndex.visit(tx, new BTreeVisitor<Location, Long>() { int last = -1; public boolean isInterestedInKeysBetween(Location first, Location second) { if (first == null) { return !ss.contains(0, second.getDataFileId()); } else if (second == null) { return true; } else { return !ss.contains(first.getDataFileId(), second.getDataFileId()); } } public void visit(List<Location> keys, List<Long> values) { for (Location l : keys) { int fileId = l.getDataFileId(); if (last != fileId) { ss.add(fileId); last = fileId; } } } }); } HashSet<Integer> missingJournalFiles = new HashSet<Integer>(); while (!ss.isEmpty()) { missingJournalFiles.add((int) ss.removeFirst()); } missingJournalFiles.removeAll(journal.getFileMap().keySet()); if (!missingJournalFiles.isEmpty()) { LOG.info("Some journal files are missing: " + missingJournalFiles); } ArrayList<BTreeVisitor.Predicate<Location>> missingPredicates = new ArrayList<BTreeVisitor.Predicate<Location>>(); for (Integer missing : missingJournalFiles) { missingPredicates.add(new BTreeVisitor.BetweenVisitor<Location, Long>(new Location(missing, 0), new Location(missing + 1, 0))); } if (checkForCorruptJournalFiles) { Collection<DataFile> dataFiles = journal.getFileMap().values(); for (DataFile dataFile : dataFiles) { int id = dataFile.getDataFileId(); missingPredicates.add(new BTreeVisitor.BetweenVisitor<Location, Long>(new Location(id, dataFile.getLength()), new Location(id + 1, 0))); Sequence seq = dataFile.getCorruptedBlocks().getHead(); while (seq != null) { missingPredicates.add(new BTreeVisitor.BetweenVisitor<Location, Long>(new Location(id, (int) seq.getFirst()), new Location(id, (int) seq.getLast() + 1))); seq = seq.getNext(); } } } if (!missingPredicates.isEmpty()) { for (StoredDestination sd : storedDestinations.values()) { final ArrayList<Long> matches = new ArrayList<Long>(); sd.locationIndex.visit(tx, new BTreeVisitor.OrVisitor<Location, Long>(missingPredicates) { @Override protected void matched(Location key, Long value) { matches.add(value); } }); // If somes message references are affected by the missing data files... if (!matches.isEmpty()) { // We either 'gracefully' recover dropping the missing messages or // we error out. if (ignoreMissingJournalfiles) { // Update the index to remove the references to the missing data for (Long sequenceId : matches) { MessageKeys keys = sd.orderIndex.remove(tx, sequenceId); sd.locationIndex.remove(tx, keys.location); sd.messageIdIndex.remove(tx, keys.messageId); undoCounter++; // TODO: do we need to modify the ack positions for the pub sub case? } } else { throw new IOException("Detected missing/corrupt journal files. " + matches.size() + " messages affected."); } } } } end = System.currentTimeMillis(); if (undoCounter > 0) { // The rolledback operations are basically in flight journal writes. To avoid getting these the end user // should do sync writes to the journal. LOG.info("Detected missing/corrupt journal files. Dropped " + undoCounter + " messages from the index in " + ((end - start) / 1000.0f) + " seconds."); } } private Location nextRecoveryPosition; private Location lastRecoveryPosition; public void incrementalRecover(Journal journal) throws IOException { this.indexLock.writeLock().lock(); try { if (nextRecoveryPosition == null) { if (lastRecoveryPosition == null) { nextRecoveryPosition = getRecoveryPosition(journal); } else { nextRecoveryPosition = journal.getNextLocation(lastRecoveryPosition); } } while (nextRecoveryPosition != null) { lastRecoveryPosition = nextRecoveryPosition; metadata.lastUpdate = lastRecoveryPosition; JournalCommand<?> message = load(journal, lastRecoveryPosition); process(message, lastRecoveryPosition); nextRecoveryPosition = journal.getNextLocation(lastRecoveryPosition); } } finally { this.indexLock.writeLock().unlock(); } } public Location getLastUpdatePosition() throws IOException { return metadata.lastUpdate; } private Location getRecoveryPosition(Journal journal) throws IOException { if (!this.forceRecoverIndex) { // If we need to recover the transactions.. if (metadata.firstInProgressTransactionLocation != null) { return metadata.firstInProgressTransactionLocation; } // Perhaps there were no transactions... if (metadata.lastUpdate != null) { // Start replay at the record after the last one recorded in the index file. return journal.getNextLocation(metadata.lastUpdate); } } // This loads the first position. return journal.getNextLocation(null); } protected void checkpointCleanup(final boolean cleanup) throws IOException { for (Journal journal : getJournalManager().getJournals()) { checkpointCleanup(journal, cleanup); } } protected void checkpointCleanup(final Journal journal, final boolean cleanup) throws IOException { long start; this.indexLock.writeLock().lock(); try { start = System.currentTimeMillis(); if (!opened.get()) { return; } pageFile.tx().execute(new Transaction.Closure<IOException>() { public void execute(Transaction tx) throws IOException { checkpointUpdate(tx, journal, cleanup); } }); } finally { this.indexLock.writeLock().unlock(); } long end = System.currentTimeMillis(); if (LOG_SLOW_ACCESS_TIME > 0 && end - start > LOG_SLOW_ACCESS_TIME) { LOG.info("Slow KahaDB access: cleanup took " + (end - start)); } } public void checkpoint(final Journal journal, Callback closure) throws Exception { this.indexLock.writeLock().lock(); try { pageFile.tx().execute(new Transaction.Closure<IOException>() { public void execute(Transaction tx) throws IOException { checkpointUpdate(tx, journal, false); } }); closure.execute(); } finally { this.indexLock.writeLock().unlock(); } } // ///////////////////////////////////////////////////////////////// // Methods call by the broker to update and query the store. // ///////////////////////////////////////////////////////////////// public Location store(Journal journal, JournalCommand<?> data) throws IOException { return store(journal, data, false, null, null); } /** * All updated are are funneled through this method. The updates are converted * to a JournalMessage which is logged to the journal and then the data from * the JournalMessage is used to update the index just like it would be done * during a recovery process. */ public Location store(final Journal journal, JournalCommand<?> data, boolean sync, Runnable before, Runnable after) throws IOException { if (before != null) { before.run(); } try { int size = data.serializedSizeFramed(); DataByteArrayOutputStream os = new DataByteArrayOutputStream(size + 1); os.writeByte(data.type().getNumber()); data.writeFramed(os); long start = System.currentTimeMillis(); Location location = journal.write(os.toByteSequence(), sync); long start2 = System.currentTimeMillis(); process(data, location); long end = System.currentTimeMillis(); if (LOG_SLOW_ACCESS_TIME > 0 && end - start > LOG_SLOW_ACCESS_TIME) { LOG.info("Slow KahaDB access: Journal append took: " + (start2 - start) + " ms, Index update took " + (end - start2) + " ms"); } this.indexLock.writeLock().lock(); try { metadata.lastUpdate = location; } finally { this.indexLock.writeLock().unlock(); } if (!checkpointThread.isAlive()) { startCheckpoint(); } if (after != null) { after.run(); } return location; } catch (IOException ioe) { LOG.error("KahaDB failed to store to Journal", ioe); brokerService.handleIOException(ioe); throw ioe; } } /** * Loads a previously stored JournalMessage */ public JournalCommand<?> load(Journal journal, Location location) throws IOException { long start = System.currentTimeMillis(); ByteSequence data = journal.read(location); long end = System.currentTimeMillis(); if (LOG_SLOW_ACCESS_TIME > 0 && end - start > LOG_SLOW_ACCESS_TIME) { LOG.info("Slow KahaDB access: Journal read took: " + (end - start) + " ms"); } DataByteArrayInputStream is = new DataByteArrayInputStream(data); byte readByte = is.readByte(); KahaEntryType type = KahaEntryType.valueOf(readByte); if (type == null) { throw new IOException("Could not load journal record. Invalid location: " + location); } JournalCommand<?> message = (JournalCommand<?>) type.createMessage(); message.mergeFramed(is); return message; } /** * do minimal recovery till we reach the last inDoubtLocation */ void process(JournalCommand<?> data, final Location location, final Location inDoubtlocation) throws IOException { if (inDoubtlocation != null && location.compareTo(inDoubtlocation) >= 0) { process(data, location); } else { // just recover producer audit data.visit(new Visitor() { public void visit(KahaAddMessageCommand command) throws IOException { metadata.producerSequenceIdTracker.isDuplicate(command.getMessageId()); } }); } } // ///////////////////////////////////////////////////////////////// // Journaled record processing methods. Once the record is journaled, // these methods handle applying the index updates. These may be called // from the recovery method too so they need to be idempotent // ///////////////////////////////////////////////////////////////// void process(JournalCommand<?> data, final Location location) throws IOException { data.visit(new Visitor() { @Override public void visit(KahaAddMessageCommand command) throws IOException { process(command, location); } @Override public void visit(KahaRemoveMessageCommand command) throws IOException { process(command, location); } @Override public void visit(KahaPrepareCommand command) throws IOException { process(command, location); } @Override public void visit(KahaCommitCommand command) throws IOException { process(command, location); } @Override public void visit(KahaRollbackCommand command) throws IOException { process(command, location); } @Override public void visit(KahaRemoveDestinationCommand command) throws IOException { process(command, location); } @Override public void visit(KahaSubscriptionCommand command) throws IOException { process(command, location); } }); } protected void process(final KahaAddMessageCommand command, final Location location) throws IOException { if (command.hasTransactionInfo()) { List<Operation> inflightTx = getInflightTx(command.getTransactionInfo(), location); inflightTx.add(new AddOpperation(command, location)); } else { this.indexLock.writeLock().lock(); try { pageFile.tx().execute(new Transaction.Closure<IOException>() { public void execute(Transaction tx) throws IOException { upadateIndex(tx, command, location); } }); } finally { this.indexLock.writeLock().unlock(); } } } protected void process(final KahaRemoveMessageCommand command, final Location location) throws IOException { if (command.hasTransactionInfo()) { List<Operation> inflightTx = getInflightTx(command.getTransactionInfo(), location); inflightTx.add(new RemoveOpperation(command, location)); } else { this.indexLock.writeLock().lock(); try { pageFile.tx().execute(new Transaction.Closure<IOException>() { public void execute(Transaction tx) throws IOException { updateIndex(tx, command, location); } }); } finally { this.indexLock.writeLock().unlock(); } } } protected void process(final KahaRemoveDestinationCommand command, final Location location) throws IOException { this.indexLock.writeLock().lock(); try { pageFile.tx().execute(new Transaction.Closure<IOException>() { public void execute(Transaction tx) throws IOException { updateIndex(tx, command, location); } }); } finally { this.indexLock.writeLock().unlock(); } } protected void process(final KahaSubscriptionCommand command, final Location location) throws IOException { this.indexLock.writeLock().lock(); try { pageFile.tx().execute(new Transaction.Closure<IOException>() { public void execute(Transaction tx) throws IOException { updateIndex(tx, command, location); } }); } finally { this.indexLock.writeLock().unlock(); } } protected void process(KahaCommitCommand command, Location location) throws IOException { TransactionId key = key(command.getTransactionInfo()); List<Operation> inflightTx; synchronized (inflightTransactions) { inflightTx = inflightTransactions.remove(key); if (inflightTx == null) { inflightTx = preparedTransactions.remove(key); } } if (inflightTx == null) { return; } final List<Operation> messagingTx = inflightTx; this.indexLock.writeLock().lock(); try { pageFile.tx().execute(new Transaction.Closure<IOException>() { public void execute(Transaction tx) throws IOException { for (Operation op : messagingTx) { op.execute(tx); } } }); } finally { this.indexLock.writeLock().unlock(); } } protected void process(KahaPrepareCommand command, Location location) { TransactionId key = key(command.getTransactionInfo()); synchronized (inflightTransactions) { List<Operation> tx = inflightTransactions.remove(key); if (tx != null) { preparedTransactions.put(key, tx); } } } protected void process(KahaRollbackCommand command, Location location) { TransactionId key = key(command.getTransactionInfo()); synchronized (inflightTransactions) { List<Operation> tx = inflightTransactions.remove(key); if (tx == null) { preparedTransactions.remove(key); } } } // ///////////////////////////////////////////////////////////////// // These methods do the actual index updates. // ///////////////////////////////////////////////////////////////// protected final ReentrantReadWriteLock indexLock = new ReentrantReadWriteLock(); private final HashSet<Integer> journalFilesBeingReplicated = new HashSet<Integer>(); void upadateIndex(Transaction tx, KahaAddMessageCommand command, Location location) throws IOException { StoredDestination sd = getStoredDestination(command.getDestination(), tx); // Skip adding the message to the index if this is a topic and there are // no subscriptions. if (sd.subscriptions != null && sd.subscriptions.isEmpty(tx)) { return; } // Add the message. int priority = command.getPrioritySupported() ? command.getPriority() : javax.jms.Message.DEFAULT_PRIORITY; long id = sd.orderIndex.getNextMessageId(priority); Long previous = sd.locationIndex.put(tx, location, id); if (previous == null) { previous = sd.messageIdIndex.put(tx, command.getMessageId(), id); if (previous == null) { sd.orderIndex.put(tx, priority, id, new MessageKeys(command.getMessageId(), location)); if (sd.subscriptions != null && !sd.subscriptions.isEmpty(tx)) { addAckLocationForNewMessage(tx, sd, id); } } else { // If the message ID as indexed, then the broker asked us to // store a DUP // message. Bad BOY! Don't do it, and log a warning. LOG.warn("Duplicate message add attempt rejected. Destination: " + command.getDestination().getName() + ", Message id: " + command.getMessageId()); // TODO: consider just rolling back the tx. sd.messageIdIndex.put(tx, command.getMessageId(), previous); sd.locationIndex.remove(tx, location); } } else { // restore the previous value.. Looks like this was a redo of a // previously // added message. We don't want to assign it a new id as the other // indexes would // be wrong.. // // TODO: consider just rolling back the tx. sd.locationIndex.put(tx, location, previous); } // record this id in any event, initial send or recovery metadata.producerSequenceIdTracker.isDuplicate(command.getMessageId()); } void updateIndex(Transaction tx, KahaRemoveMessageCommand command, Location ackLocation) throws IOException { StoredDestination sd = getStoredDestination(command.getDestination(), tx); if (!command.hasSubscriptionKey()) { // In the queue case we just remove the message from the index.. Long sequenceId = sd.messageIdIndex.remove(tx, command.getMessageId()); if (sequenceId != null) { MessageKeys keys = sd.orderIndex.remove(tx, sequenceId); if (keys != null) { sd.locationIndex.remove(tx, keys.location); recordAckMessageReferenceLocation(ackLocation, keys.location); } } } else { // In the topic case we need remove the message once it's been acked // by all the subs Long sequence = sd.messageIdIndex.get(tx, command.getMessageId()); // Make sure it's a valid message id... if (sequence != null) { String subscriptionKey = command.getSubscriptionKey(); if (command.getAck() != UNMATCHED) { sd.orderIndex.get(tx, sequence); byte priority = sd.orderIndex.lastGetPriority(); sd.subscriptionAcks.put(tx, subscriptionKey, new LastAck(sequence, priority)); } // The following method handles deleting un-referenced messages. removeAckLocation(tx, sd, subscriptionKey, sequence); } } } Map<Integer, Set<Integer>> ackMessageFileMap = new HashMap<Integer, Set<Integer>>(); private void recordAckMessageReferenceLocation(Location ackLocation, Location messageLocation) { Set<Integer> referenceFileIds = ackMessageFileMap.get(Integer.valueOf(ackLocation.getDataFileId())); if (referenceFileIds == null) { referenceFileIds = new HashSet<Integer>(); referenceFileIds.add(messageLocation.getDataFileId()); ackMessageFileMap.put(ackLocation.getDataFileId(), referenceFileIds); } else { Integer id = Integer.valueOf(messageLocation.getDataFileId()); if (!referenceFileIds.contains(id)) { referenceFileIds.add(id); } } } void updateIndex(Transaction tx, KahaRemoveDestinationCommand command, Location location) throws IOException { StoredDestination sd = getStoredDestination(command.getDestination(), tx); sd.orderIndex.remove(tx); sd.locationIndex.clear(tx); sd.locationIndex.unload(tx); tx.free(sd.locationIndex.getPageId()); sd.messageIdIndex.clear(tx); sd.messageIdIndex.unload(tx); tx.free(sd.messageIdIndex.getPageId()); if (sd.subscriptions != null) { sd.subscriptions.clear(tx); sd.subscriptions.unload(tx); tx.free(sd.subscriptions.getPageId()); sd.subscriptionAcks.clear(tx); sd.subscriptionAcks.unload(tx); tx.free(sd.subscriptionAcks.getPageId()); sd.ackPositions.clear(tx); sd.ackPositions.unload(tx); tx.free(sd.ackPositions.getPageId()); } String key = key(command.getDestination()); storedDestinations.remove(key); metadata.destinations.remove(tx, key); } void updateIndex(Transaction tx, KahaSubscriptionCommand command, Location location) throws IOException { StoredDestination sd = getStoredDestination(command.getDestination(), tx); final String subscriptionKey = command.getSubscriptionKey(); // If set then we are creating it.. otherwise we are destroying the sub if (command.hasSubscriptionInfo()) { sd.subscriptions.put(tx, subscriptionKey, command); long ackLocation = NOT_ACKED; if (!command.getRetroactive()) { ackLocation = sd.orderIndex.nextMessageId - 1; } else { addAckLocationForRetroactiveSub(tx, sd, ackLocation, subscriptionKey); } sd.subscriptionAcks.put(tx, subscriptionKey, new LastAck(ackLocation)); } else { // delete the sub... sd.subscriptions.remove(tx, subscriptionKey); sd.subscriptionAcks.remove(tx, subscriptionKey); removeAckLocationsForSub(tx, sd, subscriptionKey); } } /** * @param tx * @throws IOException */ void checkpointUpdate(Transaction tx, Journal journal, boolean cleanup) throws IOException { LOG.debug("Checkpoint started."); // reflect last update exclusive of current checkpoint Location firstTxLocation = metadata.lastUpdate; metadata.state = OPEN_STATE; metadata.producerSequenceIdTrackerLocation = checkpointProducerAudit(journal); metadata.firstInProgressTransactionLocation = getFirstInProgressTxLocation(); tx.store(metadata.page, metadataMarshaller, true); pageFile.flush(); if (cleanup) { final TreeSet<Integer> completeFileSet = new TreeSet<Integer>(journal.getFileMap().keySet()); final TreeSet<Integer> gcCandidateSet = new TreeSet<Integer>(completeFileSet); LOG.trace("Last update: " + firstTxLocation + ", full gc candidates set: " + gcCandidateSet); // Don't GC files under replication if (journalFilesBeingReplicated != null) { gcCandidateSet.removeAll(journalFilesBeingReplicated); } + if (metadata.producerSequenceIdTrackerLocation != null) { + gcCandidateSet.remove(metadata.producerSequenceIdTrackerLocation.getDataFileId()); + } + // Don't GC files after the first in progress tx if (metadata.firstInProgressTransactionLocation != null) { if (metadata.firstInProgressTransactionLocation.getDataFileId() < firstTxLocation.getDataFileId()) { firstTxLocation = metadata.firstInProgressTransactionLocation; } - ; } if (firstTxLocation != null) { while (!gcCandidateSet.isEmpty()) { Integer last = gcCandidateSet.last(); if (last >= firstTxLocation.getDataFileId()) { gcCandidateSet.remove(last); } else { break; } } LOG.trace("gc candidates after first tx:" + firstTxLocation + ", " + gcCandidateSet); } // Go through all the destinations to see if any of them can remove GC candidates. for (Entry<String, StoredDestination> entry : storedDestinations.entrySet()) { if (gcCandidateSet.isEmpty()) { break; } // Use a visitor to cut down the number of pages that we load entry.getValue().locationIndex.visit(tx, new BTreeVisitor<Location, Long>() { int last = -1; public boolean isInterestedInKeysBetween(Location first, Location second) { if (first == null) { SortedSet<Integer> subset = gcCandidateSet.headSet(second.getDataFileId() + 1); if (!subset.isEmpty() && subset.last() == second.getDataFileId()) { subset.remove(second.getDataFileId()); } return !subset.isEmpty(); } else if (second == null) { SortedSet<Integer> subset = gcCandidateSet.tailSet(first.getDataFileId()); if (!subset.isEmpty() && subset.first() == first.getDataFileId()) { subset.remove(first.getDataFileId()); } return !subset.isEmpty(); } else { SortedSet<Integer> subset = gcCandidateSet.subSet(first.getDataFileId(), second.getDataFileId() + 1); if (!subset.isEmpty() && subset.first() == first.getDataFileId()) { subset.remove(first.getDataFileId()); } if (!subset.isEmpty() && subset.last() == second.getDataFileId()) { subset.remove(second.getDataFileId()); } return !subset.isEmpty(); } } public void visit(List<Location> keys, List<Long> values) { for (Location l : keys) { int fileId = l.getDataFileId(); if (last != fileId) { gcCandidateSet.remove(fileId); last = fileId; } } } }); LOG.trace("gc candidates after dest:" + entry.getKey() + ", " + gcCandidateSet); } // check we are not deleting file with ack for in-use journal files LOG.trace("gc candidates: " + gcCandidateSet); final TreeSet<Integer> gcCandidates = new TreeSet<Integer>(gcCandidateSet); Iterator<Integer> candidates = gcCandidateSet.iterator(); while (candidates.hasNext()) { Integer candidate = candidates.next(); Set<Integer> referencedFileIds = ackMessageFileMap.get(candidate); if (referencedFileIds != null) { for (Integer referencedFileId : referencedFileIds) { if (completeFileSet.contains(referencedFileId) && !gcCandidates.contains(referencedFileId)) { // active file that is not targeted for deletion is referenced so don't delete candidates.remove(); break; } } if (gcCandidateSet.contains(candidate)) { ackMessageFileMap.remove(candidate); } else { LOG.trace("not removing data file: " + candidate + " as contained ack(s) refer to referenced file: " + referencedFileIds); } } } if (!gcCandidateSet.isEmpty()) { LOG.debug("Cleanup removing the data files: " + gcCandidateSet); journal.removeDataFiles(gcCandidateSet); } } LOG.debug("Checkpoint done."); } private Location checkpointProducerAudit(Journal journal) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oout = new ObjectOutputStream(baos); oout.writeObject(metadata.producerSequenceIdTracker); oout.flush(); oout.close(); return store(journal, new KahaProducerAuditCommand().setAudit(new Buffer(baos.toByteArray())), true, null, null); } public HashSet<Integer> getJournalFilesBeingReplicated() { return journalFilesBeingReplicated; } // ///////////////////////////////////////////////////////////////// // StoredDestination related implementation methods. // ///////////////////////////////////////////////////////////////// private final HashMap<String, StoredDestination> storedDestinations = new HashMap<String, StoredDestination>(); class StoredSubscription { SubscriptionInfo subscriptionInfo; String lastAckId; Location lastAckLocation; Location cursor; } static class MessageKeys { final String messageId; final Location location; public MessageKeys(String messageId, Location location) { this.messageId = messageId; this.location = location; } @Override public String toString() { return "[" + messageId + "," + location + "]"; } } static protected class MessageKeysMarshaller extends VariableMarshaller<MessageKeys> { static final MessageKeysMarshaller INSTANCE = new MessageKeysMarshaller(); public MessageKeys readPayload(DataInput dataIn) throws IOException { return new MessageKeys(dataIn.readUTF(), LocationMarshaller.INSTANCE.readPayload(dataIn)); } public void writePayload(MessageKeys object, DataOutput dataOut) throws IOException { dataOut.writeUTF(object.messageId); LocationMarshaller.INSTANCE.writePayload(object.location, dataOut); } } class LastAck { long lastAckedSequence; byte priority; public LastAck(LastAck source) { this.lastAckedSequence = source.lastAckedSequence; this.priority = source.priority; } public LastAck() { this.priority = MessageOrderIndex.HI; } public LastAck(long ackLocation) { this.lastAckedSequence = ackLocation; this.priority = MessageOrderIndex.LO; } public LastAck(long ackLocation, byte priority) { this.lastAckedSequence = ackLocation; this.priority = priority; } public String toString() { return "[" + lastAckedSequence + ":" + priority + "]"; } } protected class LastAckMarshaller implements Marshaller<LastAck> { public void writePayload(LastAck object, DataOutput dataOut) throws IOException { dataOut.writeLong(object.lastAckedSequence); dataOut.writeByte(object.priority); } public LastAck readPayload(DataInput dataIn) throws IOException { LastAck lastAcked = new LastAck(); lastAcked.lastAckedSequence = dataIn.readLong(); if (metadata.version >= 3) { lastAcked.priority = dataIn.readByte(); } return lastAcked; } public int getFixedSize() { return 9; } public LastAck deepCopy(LastAck source) { return new LastAck(source); } public boolean isDeepCopySupported() { return true; } } class StoredDestination { MessageOrderIndex orderIndex = new MessageOrderIndex(); BTreeIndex<Location, Long> locationIndex; BTreeIndex<String, Long> messageIdIndex; // These bits are only set for Topics BTreeIndex<String, KahaSubscriptionCommand> subscriptions; BTreeIndex<String, LastAck> subscriptionAcks; HashMap<String, MessageOrderCursor> subscriptionCursors; BTreeIndex<Long, HashSet<String>> ackPositions; } protected class StoredDestinationMarshaller extends VariableMarshaller<StoredDestination> { public StoredDestination readPayload(DataInput dataIn) throws IOException { final StoredDestination value = new StoredDestination(); value.orderIndex.defaultPriorityIndex = new BTreeIndex<Long, MessageKeys>(pageFile, dataIn.readLong()); value.locationIndex = new BTreeIndex<Location, Long>(pageFile, dataIn.readLong()); value.messageIdIndex = new BTreeIndex<String, Long>(pageFile, dataIn.readLong()); if (dataIn.readBoolean()) { value.subscriptions = new BTreeIndex<String, KahaSubscriptionCommand>(pageFile, dataIn.readLong()); value.subscriptionAcks = new BTreeIndex<String, LastAck>(pageFile, dataIn.readLong()); if (metadata.version >= 3) { value.ackPositions = new BTreeIndex<Long, HashSet<String>>(pageFile, dataIn.readLong()); } else { // upgrade pageFile.tx().execute(new Transaction.Closure<IOException>() { public void execute(Transaction tx) throws IOException { value.ackPositions = new BTreeIndex<Long, HashSet<String>>(pageFile, tx.allocate()); value.ackPositions.setKeyMarshaller(LongMarshaller.INSTANCE); value.ackPositions.setValueMarshaller(HashSetStringMarshaller.INSTANCE); value.ackPositions.load(tx); } }); } } if (metadata.version >= 2) { value.orderIndex.lowPriorityIndex = new BTreeIndex<Long, MessageKeys>(pageFile, dataIn.readLong()); value.orderIndex.highPriorityIndex = new BTreeIndex<Long, MessageKeys>(pageFile, dataIn.readLong()); } else { // upgrade pageFile.tx().execute(new Transaction.Closure<IOException>() { public void execute(Transaction tx) throws IOException { value.orderIndex.lowPriorityIndex = new BTreeIndex<Long, MessageKeys>(pageFile, tx.allocate()); value.orderIndex.lowPriorityIndex.setKeyMarshaller(LongMarshaller.INSTANCE); value.orderIndex.lowPriorityIndex.setValueMarshaller(MessageKeysMarshaller.INSTANCE); value.orderIndex.lowPriorityIndex.load(tx); value.orderIndex.highPriorityIndex = new BTreeIndex<Long, MessageKeys>(pageFile, tx.allocate()); value.orderIndex.highPriorityIndex.setKeyMarshaller(LongMarshaller.INSTANCE); value.orderIndex.highPriorityIndex.setValueMarshaller(MessageKeysMarshaller.INSTANCE); value.orderIndex.highPriorityIndex.load(tx); } }); } return value; } public void writePayload(StoredDestination value, DataOutput dataOut) throws IOException { dataOut.writeLong(value.orderIndex.defaultPriorityIndex.getPageId()); dataOut.writeLong(value.locationIndex.getPageId()); dataOut.writeLong(value.messageIdIndex.getPageId()); if (value.subscriptions != null) { dataOut.writeBoolean(true); dataOut.writeLong(value.subscriptions.getPageId()); dataOut.writeLong(value.subscriptionAcks.getPageId()); dataOut.writeLong(value.ackPositions.getPageId()); } else { dataOut.writeBoolean(false); } dataOut.writeLong(value.orderIndex.lowPriorityIndex.getPageId()); dataOut.writeLong(value.orderIndex.highPriorityIndex.getPageId()); } } static class KahaSubscriptionCommandMarshaller extends VariableMarshaller<KahaSubscriptionCommand> { final static KahaSubscriptionCommandMarshaller INSTANCE = new KahaSubscriptionCommandMarshaller(); public KahaSubscriptionCommand readPayload(DataInput dataIn) throws IOException { KahaSubscriptionCommand rc = new KahaSubscriptionCommand(); rc.mergeFramed((InputStream) dataIn); return rc; } public void writePayload(KahaSubscriptionCommand object, DataOutput dataOut) throws IOException { object.writeFramed((OutputStream) dataOut); } } protected StoredDestination getStoredDestination(KahaDestination destination, Transaction tx) throws IOException { String key = key(destination); StoredDestination rc = storedDestinations.get(key); if (rc == null) { boolean topic = destination.getType() == KahaDestination.DestinationType.TOPIC || destination.getType() == KahaDestination.DestinationType.TEMP_TOPIC; rc = loadStoredDestination(tx, key, topic); // Cache it. We may want to remove/unload destinations from the // cache that are not used for a while // to reduce memory usage. storedDestinations.put(key, rc); } return rc; } protected StoredDestination getExistingStoredDestination(KahaDestination destination, Transaction tx) throws IOException { String key = key(destination); StoredDestination rc = storedDestinations.get(key); if (rc == null && metadata.destinations.containsKey(tx, key)) { rc = getStoredDestination(destination, tx); } return rc; } /** * @param tx * @param key * @param topic * @return * @throws IOException */ private StoredDestination loadStoredDestination(Transaction tx, String key, boolean topic) throws IOException { // Try to load the existing indexes.. StoredDestination rc = metadata.destinations.get(tx, key); if (rc == null) { // Brand new destination.. allocate indexes for it. rc = new StoredDestination(); rc.orderIndex.allocate(tx); rc.locationIndex = new BTreeIndex<Location, Long>(pageFile, tx.allocate()); rc.messageIdIndex = new BTreeIndex<String, Long>(pageFile, tx.allocate()); if (topic) { rc.subscriptions = new BTreeIndex<String, KahaSubscriptionCommand>(pageFile, tx.allocate()); rc.subscriptionAcks = new BTreeIndex<String, LastAck>(pageFile, tx.allocate()); rc.ackPositions = new BTreeIndex<Long, HashSet<String>>(pageFile, tx.allocate()); } metadata.destinations.put(tx, key, rc); } // Configure the marshalers and load. rc.orderIndex.load(tx); // Figure out the next key using the last entry in the destination. rc.orderIndex.configureLast(tx); rc.locationIndex.setKeyMarshaller(org.apache.kahadb.util.LocationMarshaller.INSTANCE); rc.locationIndex.setValueMarshaller(LongMarshaller.INSTANCE); rc.locationIndex.load(tx); rc.messageIdIndex.setKeyMarshaller(StringMarshaller.INSTANCE); rc.messageIdIndex.setValueMarshaller(LongMarshaller.INSTANCE); rc.messageIdIndex.load(tx); // If it was a topic... if (topic) { rc.subscriptions.setKeyMarshaller(StringMarshaller.INSTANCE); rc.subscriptions.setValueMarshaller(KahaSubscriptionCommandMarshaller.INSTANCE); rc.subscriptions.load(tx); rc.subscriptionAcks.setKeyMarshaller(StringMarshaller.INSTANCE); rc.subscriptionAcks.setValueMarshaller(new LastAckMarshaller()); rc.subscriptionAcks.load(tx); rc.ackPositions.setKeyMarshaller(LongMarshaller.INSTANCE); rc.ackPositions.setValueMarshaller(HashSetStringMarshaller.INSTANCE); rc.ackPositions.load(tx); rc.subscriptionCursors = new HashMap<String, MessageOrderCursor>(); if (metadata.version < 3) { // on upgrade need to fill ackLocation with available messages past last ack for (Iterator<Entry<String, LastAck>> iterator = rc.subscriptionAcks.iterator(tx); iterator.hasNext(); ) { Entry<String, LastAck> entry = iterator.next(); for (Iterator<Entry<Long, MessageKeys>> orderIterator = rc.orderIndex.iterator(tx, new MessageOrderCursor(entry.getValue().lastAckedSequence)); orderIterator.hasNext(); ) { Long sequence = orderIterator.next().getKey(); addAckLocation(tx, rc, sequence, entry.getKey()); } // modify so it is upgraded rc.subscriptionAcks.put(tx, entry.getKey(), entry.getValue()); } } if (rc.orderIndex.nextMessageId == 0) { // check for existing durable sub all acked out - pull next seq from acks as messages are gone if (!rc.subscriptionAcks.isEmpty(tx)) { for (Iterator<Entry<String, LastAck>> iterator = rc.subscriptionAcks.iterator(tx); iterator.hasNext(); ) { Entry<String, LastAck> entry = iterator.next(); rc.orderIndex.nextMessageId = Math.max(rc.orderIndex.nextMessageId, entry.getValue().lastAckedSequence + 1); } } } else { // update based on ackPositions for unmatched, last entry is always the next if (!rc.ackPositions.isEmpty(tx)) { Entry<Long, HashSet<String>> last = rc.ackPositions.getLast(tx); rc.orderIndex.nextMessageId = Math.max(rc.orderIndex.nextMessageId, last.getKey()); } } } if (metadata.version < 3) { // store again after upgrade metadata.destinations.put(tx, key, rc); } return rc; } private void addAckLocation(Transaction tx, StoredDestination sd, Long messageSequence, String subscriptionKey) throws IOException { HashSet<String> hs = sd.ackPositions.get(tx, messageSequence); if (hs == null) { hs = new HashSet<String>(); } hs.add(subscriptionKey); // every ack location addition needs to be a btree modification to get it stored sd.ackPositions.put(tx, messageSequence, hs); } // new sub is interested in potentially all existing messages private void addAckLocationForRetroactiveSub(Transaction tx, StoredDestination sd, Long messageSequence, String subscriptionKey) throws IOException { for (Iterator<Entry<Long, HashSet<String>>> iterator = sd.ackPositions.iterator(tx, messageSequence); iterator.hasNext(); ) { Entry<Long, HashSet<String>> entry = iterator.next(); entry.getValue().add(subscriptionKey); sd.ackPositions.put(tx, entry.getKey(), entry.getValue()); } } final HashSet nextMessageIdMarker = new HashSet<String>(); // on a new message add, all existing subs are interested in this message private void addAckLocationForNewMessage(Transaction tx, StoredDestination sd, Long messageSequence) throws IOException { HashSet hs = new HashSet<String>(); for (Iterator<Entry<String, LastAck>> iterator = sd.subscriptionAcks.iterator(tx); iterator.hasNext(); ) { Entry<String, LastAck> entry = iterator.next(); hs.add(entry.getKey()); } sd.ackPositions.put(tx, messageSequence, hs); // add empty next to keep track of nextMessage sd.ackPositions.put(tx, messageSequence + 1, nextMessageIdMarker); } private void removeAckLocationsForSub(Transaction tx, StoredDestination sd, String subscriptionKey) throws IOException { if (!sd.ackPositions.isEmpty(tx)) { Long end = sd.ackPositions.getLast(tx).getKey(); for (Long sequence = sd.ackPositions.getFirst(tx).getKey(); sequence <= end; sequence++) { removeAckLocation(tx, sd, subscriptionKey, sequence); } } } /** * @param tx * @param sd * @param subscriptionKey * @param sequenceId * @throws IOException */ private void removeAckLocation(Transaction tx, StoredDestination sd, String subscriptionKey, Long sequenceId) throws IOException { // Remove the sub from the previous location set.. if (sequenceId != null) { HashSet<String> hs = sd.ackPositions.get(tx, sequenceId); if (hs != null) { hs.remove(subscriptionKey); if (hs.isEmpty()) { HashSet<String> firstSet = sd.ackPositions.getFirst(tx).getValue(); sd.ackPositions.remove(tx, sequenceId); // Find all the entries that need to get deleted. ArrayList<Entry<Long, MessageKeys>> deletes = new ArrayList<Entry<Long, MessageKeys>>(); sd.orderIndex.getDeleteList(tx, deletes, sequenceId); // Do the actual deletes. for (Entry<Long, MessageKeys> entry : deletes) { sd.locationIndex.remove(tx, entry.getValue().location); sd.messageIdIndex.remove(tx, entry.getValue().messageId); sd.orderIndex.remove(tx, entry.getKey()); } } else { // update sd.ackPositions.put(tx, sequenceId, hs); } } } } private String key(KahaDestination destination) { return destination.getType().getNumber() + ":" + destination.getName(); } // ///////////////////////////////////////////////////////////////// // Transaction related implementation methods. // ///////////////////////////////////////////////////////////////// protected final LinkedHashMap<TransactionId, List<Operation>> inflightTransactions = new LinkedHashMap<TransactionId, List<Operation>>(); protected final LinkedHashMap<TransactionId, List<Operation>> preparedTransactions = new LinkedHashMap<TransactionId, List<Operation>>(); protected final Set<String> ackedAndPrepared = new HashSet<String>(); // messages that have prepared (pending) acks cannot be redispatched unless the outcome is rollback, // till then they are skipped by the store. // 'at most once' XA guarantee public void trackRecoveredAcks(ArrayList<MessageAck> acks) { this.indexLock.writeLock().lock(); try { for (MessageAck ack : acks) { ackedAndPrepared.add(ack.getLastMessageId().toString()); } } finally { this.indexLock.writeLock().unlock(); } } public void forgetRecoveredAcks(ArrayList<MessageAck> acks) throws IOException { if (acks != null) { this.indexLock.writeLock().lock(); try { for (MessageAck ack : acks) { ackedAndPrepared.remove(ack.getLastMessageId().toString()); } } finally { this.indexLock.writeLock().unlock(); } } } private List<Operation> getInflightTx(KahaTransactionInfo info, Location location) { TransactionId key = key(info); List<Operation> tx; synchronized (inflightTransactions) { tx = inflightTransactions.get(key); if (tx == null) { tx = Collections.synchronizedList(new ArrayList<Operation>()); inflightTransactions.put(key, tx); } } return tx; } private TransactionId key(KahaTransactionInfo transactionInfo) { if (transactionInfo.hasLocalTransacitonId()) { KahaLocalTransactionId tx = transactionInfo.getLocalTransacitonId(); LocalTransactionId rc = new LocalTransactionId(); rc.setConnectionId(new ConnectionId(tx.getConnectionId())); rc.setValue(tx.getTransacitonId()); return rc; } else { KahaXATransactionId tx = transactionInfo.getXaTransacitonId(); XATransactionId rc = new XATransactionId(); rc.setBranchQualifier(tx.getBranchQualifier().toByteArray()); rc.setGlobalTransactionId(tx.getGlobalTransactionId().toByteArray()); rc.setFormatId(tx.getFormatId()); return rc; } } abstract class Operation { final Location location; public Operation(Location location) { this.location = location; } public Location getLocation() { return location; } abstract public void execute(Transaction tx) throws IOException; } class AddOpperation extends Operation { final KahaAddMessageCommand command; public AddOpperation(KahaAddMessageCommand command, Location location) { super(location); this.command = command; } @Override public void execute(Transaction tx) throws IOException { upadateIndex(tx, command, location); } public KahaAddMessageCommand getCommand() { return command; } } class RemoveOpperation extends Operation { final KahaRemoveMessageCommand command; public RemoveOpperation(KahaRemoveMessageCommand command, Location location) { super(location); this.command = command; } @Override public void execute(Transaction tx) throws IOException { updateIndex(tx, command, location); } public KahaRemoveMessageCommand getCommand() { return command; } } // ///////////////////////////////////////////////////////////////// // Initialization related implementation methods. // ///////////////////////////////////////////////////////////////// private PageFile createPageFile() { PageFile index = new PageFile(directory, "db"); index.setEnableWriteThread(isEnableIndexWriteAsync()); index.setWriteBatchSize(getIndexWriteBatchSize()); index.setPageCacheSize(indexCacheSize); return index; } private JournalManager createJournalManager() throws IOException { JournalManager manager = isJournalPerDestination() ? new DestinationJournalManager() : new DefaultJournalManager(); manager.setDirectory(directory); manager.setMaxFileLength(getJournalMaxFileLength()); manager.setCheckForCorruptionOnStartup(checkForCorruptJournalFiles); manager.setChecksum(checksumJournalFiles || checkForCorruptJournalFiles); manager.setWriteBatchSize(getJournalMaxWriteBatchSize()); manager.setArchiveDataLogs(isArchiveDataLogs()); manager.setStoreSize(storeSize); if (getDirectoryArchive() != null) { IOHelper.mkdirs(getDirectoryArchive()); manager.setDirectoryArchive(getDirectoryArchive()); } return manager; } public int getJournalMaxWriteBatchSize() { return journalMaxWriteBatchSize; } public void setJournalMaxWriteBatchSize(int journalMaxWriteBatchSize) { this.journalMaxWriteBatchSize = journalMaxWriteBatchSize; } public File getDirectory() { return directory; } public void setDirectory(File directory) { this.directory = directory; } public boolean isDeleteAllMessages() { return deleteAllMessages; } public void setDeleteAllMessages(boolean deleteAllMessages) { this.deleteAllMessages = deleteAllMessages; } public void setIndexWriteBatchSize(int setIndexWriteBatchSize) { this.setIndexWriteBatchSize = setIndexWriteBatchSize; } public int getIndexWriteBatchSize() { return setIndexWriteBatchSize; } public void setEnableIndexWriteAsync(boolean enableIndexWriteAsync) { this.enableIndexWriteAsync = enableIndexWriteAsync; } boolean isEnableIndexWriteAsync() { return enableIndexWriteAsync; } public boolean isEnableJournalDiskSyncs() { return enableJournalDiskSyncs; } public void setEnableJournalDiskSyncs(boolean syncWrites) { this.enableJournalDiskSyncs = syncWrites; } public long getCheckpointInterval() { return checkpointInterval; } public void setCheckpointInterval(long checkpointInterval) { this.checkpointInterval = checkpointInterval; } public long getCleanupInterval() { return cleanupInterval; } public void setCleanupInterval(long cleanupInterval) { this.cleanupInterval = cleanupInterval; } public void setJournalMaxFileLength(int journalMaxFileLength) { this.journalMaxFileLength = journalMaxFileLength; } public int getJournalMaxFileLength() { return journalMaxFileLength; } public void setMaxFailoverProducersToTrack(int maxFailoverProducersToTrack) { this.metadata.producerSequenceIdTracker.setMaximumNumberOfProducersToTrack(maxFailoverProducersToTrack); } public int getMaxFailoverProducersToTrack() { return this.metadata.producerSequenceIdTracker.getMaximumNumberOfProducersToTrack(); } public void setFailoverProducersAuditDepth(int failoverProducersAuditDepth) { this.metadata.producerSequenceIdTracker.setAuditDepth(failoverProducersAuditDepth); } public int getFailoverProducersAuditDepth() { return this.metadata.producerSequenceIdTracker.getAuditDepth(); } public PageFile getPageFile() { if (pageFile == null) { pageFile = createPageFile(); } return pageFile; } public JournalManager getJournalManager() throws IOException { if (journalManager == null) { journalManager = createJournalManager(); } return journalManager; } public Journal getJournal(ActiveMQDestination destination) throws IOException { return getJournalManager().getJournal(destination); } public boolean isFailIfDatabaseIsLocked() { return failIfDatabaseIsLocked; } public void setFailIfDatabaseIsLocked(boolean failIfDatabaseIsLocked) { this.failIfDatabaseIsLocked = failIfDatabaseIsLocked; } public boolean isIgnoreMissingJournalfiles() { return ignoreMissingJournalfiles; } public void setIgnoreMissingJournalfiles(boolean ignoreMissingJournalfiles) { this.ignoreMissingJournalfiles = ignoreMissingJournalfiles; } public int getIndexCacheSize() { return indexCacheSize; } public void setIndexCacheSize(int indexCacheSize) { this.indexCacheSize = indexCacheSize; } public boolean isCheckForCorruptJournalFiles() { return checkForCorruptJournalFiles; } public void setCheckForCorruptJournalFiles(boolean checkForCorruptJournalFiles) { this.checkForCorruptJournalFiles = checkForCorruptJournalFiles; } public boolean isChecksumJournalFiles() { return checksumJournalFiles; } public void setChecksumJournalFiles(boolean checksumJournalFiles) { this.checksumJournalFiles = checksumJournalFiles; } public void setBrokerService(BrokerService brokerService) { this.brokerService = brokerService; } /** * @return the archiveDataLogs */ public boolean isArchiveDataLogs() { return this.archiveDataLogs; } /** * @param archiveDataLogs the archiveDataLogs to set */ public void setArchiveDataLogs(boolean archiveDataLogs) { this.archiveDataLogs = archiveDataLogs; } /** * @return the directoryArchive */ public File getDirectoryArchive() { return this.directoryArchive; } /** * @param directoryArchive the directoryArchive to set */ public void setDirectoryArchive(File directoryArchive) { this.directoryArchive = directoryArchive; } /** * @return the databaseLockedWaitDelay */ public int getDatabaseLockedWaitDelay() { return this.databaseLockedWaitDelay; } /** * @param databaseLockedWaitDelay the databaseLockedWaitDelay to set */ public void setDatabaseLockedWaitDelay(int databaseLockedWaitDelay) { this.databaseLockedWaitDelay = databaseLockedWaitDelay; } public boolean isJournalPerDestination() { return journalPerDestination; } public void setJournalPerDestination(boolean journalPerDestination) { this.journalPerDestination = journalPerDestination; } // ///////////////////////////////////////////////////////////////// // Internal conversion methods. // ///////////////////////////////////////////////////////////////// KahaTransactionInfo createTransactionInfo(TransactionId txid) { if (txid == null) { return null; } KahaTransactionInfo rc = new KahaTransactionInfo(); if (txid.isLocalTransaction()) { LocalTransactionId t = (LocalTransactionId) txid; KahaLocalTransactionId kahaTxId = new KahaLocalTransactionId(); kahaTxId.setConnectionId(t.getConnectionId().getValue()); kahaTxId.setTransacitonId(t.getValue()); rc.setLocalTransacitonId(kahaTxId); } else { XATransactionId t = (XATransactionId) txid; KahaXATransactionId kahaTxId = new KahaXATransactionId(); kahaTxId.setBranchQualifier(new Buffer(t.getBranchQualifier())); kahaTxId.setGlobalTransactionId(new Buffer(t.getGlobalTransactionId())); kahaTxId.setFormatId(t.getFormatId()); rc.setXaTransacitonId(kahaTxId); } return rc; } class MessageOrderCursor { long defaultCursorPosition; long lowPriorityCursorPosition; long highPriorityCursorPosition; MessageOrderCursor() { } MessageOrderCursor(long position) { this.defaultCursorPosition = position; this.lowPriorityCursorPosition = position; this.highPriorityCursorPosition = position; } MessageOrderCursor(MessageOrderCursor other) { this.defaultCursorPosition = other.defaultCursorPosition; this.lowPriorityCursorPosition = other.lowPriorityCursorPosition; this.highPriorityCursorPosition = other.highPriorityCursorPosition; } MessageOrderCursor copy() { return new MessageOrderCursor(this); } void reset() { this.defaultCursorPosition = 0; this.highPriorityCursorPosition = 0; this.lowPriorityCursorPosition = 0; } void increment() { if (defaultCursorPosition != 0) { defaultCursorPosition++; } if (highPriorityCursorPosition != 0) { highPriorityCursorPosition++; } if (lowPriorityCursorPosition != 0) { lowPriorityCursorPosition++; } } public String toString() { return "MessageOrderCursor:[def:" + defaultCursorPosition + ", low:" + lowPriorityCursorPosition + ", high:" + highPriorityCursorPosition + "]"; } public void sync(MessageOrderCursor other) { this.defaultCursorPosition = other.defaultCursorPosition; this.lowPriorityCursorPosition = other.lowPriorityCursorPosition; this.highPriorityCursorPosition = other.highPriorityCursorPosition; } } class MessageOrderIndex { static final byte HI = 9; static final byte LO = 0; static final byte DEF = 4; long nextMessageId; BTreeIndex<Long, MessageKeys> defaultPriorityIndex; BTreeIndex<Long, MessageKeys> lowPriorityIndex; BTreeIndex<Long, MessageKeys> highPriorityIndex; MessageOrderCursor cursor = new MessageOrderCursor(); Long lastDefaultKey; Long lastHighKey; Long lastLowKey; byte lastGetPriority; MessageKeys remove(Transaction tx, Long key) throws IOException { MessageKeys result = defaultPriorityIndex.remove(tx, key); if (result == null && highPriorityIndex != null) { result = highPriorityIndex.remove(tx, key); if (result == null && lowPriorityIndex != null) { result = lowPriorityIndex.remove(tx, key); } } return result; } void load(Transaction tx) throws IOException { defaultPriorityIndex.setKeyMarshaller(LongMarshaller.INSTANCE); defaultPriorityIndex.setValueMarshaller(MessageKeysMarshaller.INSTANCE); defaultPriorityIndex.load(tx); lowPriorityIndex.setKeyMarshaller(LongMarshaller.INSTANCE); lowPriorityIndex.setValueMarshaller(MessageKeysMarshaller.INSTANCE); lowPriorityIndex.load(tx); highPriorityIndex.setKeyMarshaller(LongMarshaller.INSTANCE); highPriorityIndex.setValueMarshaller(MessageKeysMarshaller.INSTANCE); highPriorityIndex.load(tx); } void allocate(Transaction tx) throws IOException { defaultPriorityIndex = new BTreeIndex<Long, MessageKeys>(pageFile, tx.allocate()); if (metadata.version >= 2) { lowPriorityIndex = new BTreeIndex<Long, MessageKeys>(pageFile, tx.allocate()); highPriorityIndex = new BTreeIndex<Long, MessageKeys>(pageFile, tx.allocate()); } } void configureLast(Transaction tx) throws IOException { // Figure out the next key using the last entry in the destination. if (highPriorityIndex != null) { Entry<Long, MessageKeys> lastEntry = highPriorityIndex.getLast(tx); if (lastEntry != null) { nextMessageId = lastEntry.getKey() + 1; } else { lastEntry = defaultPriorityIndex.getLast(tx); if (lastEntry != null) { nextMessageId = lastEntry.getKey() + 1; } else { lastEntry = lowPriorityIndex.getLast(tx); if (lastEntry != null) { nextMessageId = lastEntry.getKey() + 1; } } } } else { Entry<Long, MessageKeys> lastEntry = defaultPriorityIndex.getLast(tx); if (lastEntry != null) { nextMessageId = lastEntry.getKey() + 1; } } } void remove(Transaction tx) throws IOException { defaultPriorityIndex.clear(tx); defaultPriorityIndex.unload(tx); tx.free(defaultPriorityIndex.getPageId()); if (lowPriorityIndex != null) { lowPriorityIndex.clear(tx); lowPriorityIndex.unload(tx); tx.free(lowPriorityIndex.getPageId()); } if (highPriorityIndex != null) { highPriorityIndex.clear(tx); highPriorityIndex.unload(tx); tx.free(highPriorityIndex.getPageId()); } } void resetCursorPosition() { this.cursor.reset(); lastDefaultKey = null; lastHighKey = null; lastLowKey = null; } void setBatch(Transaction tx, Long sequence) throws IOException { if (sequence != null) { Long nextPosition = new Long(sequence.longValue() + 1); if (defaultPriorityIndex.containsKey(tx, sequence)) { lastDefaultKey = sequence; cursor.defaultCursorPosition = nextPosition.longValue(); } else if (highPriorityIndex != null) { if (highPriorityIndex.containsKey(tx, sequence)) { lastHighKey = sequence; cursor.highPriorityCursorPosition = nextPosition.longValue(); } else if (lowPriorityIndex.containsKey(tx, sequence)) { lastLowKey = sequence; cursor.lowPriorityCursorPosition = nextPosition.longValue(); } } else { lastDefaultKey = sequence; cursor.defaultCursorPosition = nextPosition.longValue(); } } } void setBatch(Transaction tx, LastAck last) throws IOException { setBatch(tx, last.lastAckedSequence); if (cursor.defaultCursorPosition == 0 && cursor.highPriorityCursorPosition == 0 && cursor.lowPriorityCursorPosition == 0) { long next = last.lastAckedSequence + 1; switch (last.priority) { case DEF: cursor.defaultCursorPosition = next; cursor.highPriorityCursorPosition = next; break; case HI: cursor.highPriorityCursorPosition = next; break; case LO: cursor.lowPriorityCursorPosition = next; cursor.defaultCursorPosition = next; cursor.highPriorityCursorPosition = next; break; } } } void stoppedIterating() { if (lastDefaultKey != null) { cursor.defaultCursorPosition = lastDefaultKey.longValue() + 1; } if (lastHighKey != null) { cursor.highPriorityCursorPosition = lastHighKey.longValue() + 1; } if (lastLowKey != null) { cursor.lowPriorityCursorPosition = lastLowKey.longValue() + 1; } lastDefaultKey = null; lastHighKey = null; lastLowKey = null; } void getDeleteList(Transaction tx, ArrayList<Entry<Long, MessageKeys>> deletes, Long sequenceId) throws IOException { if (defaultPriorityIndex.containsKey(tx, sequenceId)) { getDeleteList(tx, deletes, defaultPriorityIndex, sequenceId); } else if (highPriorityIndex != null && highPriorityIndex.containsKey(tx, sequenceId)) { getDeleteList(tx, deletes, highPriorityIndex, sequenceId); } else if (lowPriorityIndex != null && lowPriorityIndex.containsKey(tx, sequenceId)) { getDeleteList(tx, deletes, lowPriorityIndex, sequenceId); } } void getDeleteList(Transaction tx, ArrayList<Entry<Long, MessageKeys>> deletes, BTreeIndex<Long, MessageKeys> index, Long sequenceId) throws IOException { Iterator<Entry<Long, MessageKeys>> iterator = index.iterator(tx, sequenceId); deletes.add(iterator.next()); } long getNextMessageId(int priority) { return nextMessageId++; } MessageKeys get(Transaction tx, Long key) throws IOException { MessageKeys result = defaultPriorityIndex.get(tx, key); if (result == null) { result = highPriorityIndex.get(tx, key); if (result == null) { result = lowPriorityIndex.get(tx, key); lastGetPriority = LO; } else { lastGetPriority = HI; } } else { lastGetPriority = DEF; } return result; } MessageKeys put(Transaction tx, int priority, Long key, MessageKeys value) throws IOException { if (priority == javax.jms.Message.DEFAULT_PRIORITY) { return defaultPriorityIndex.put(tx, key, value); } else if (priority > javax.jms.Message.DEFAULT_PRIORITY) { return highPriorityIndex.put(tx, key, value); } else { return lowPriorityIndex.put(tx, key, value); } } Iterator<Entry<Long, MessageKeys>> iterator(Transaction tx) throws IOException { return new MessageOrderIterator(tx, cursor); } Iterator<Entry<Long, MessageKeys>> iterator(Transaction tx, MessageOrderCursor m) throws IOException { return new MessageOrderIterator(tx, m); } public byte lastGetPriority() { return lastGetPriority; } class MessageOrderIterator implements Iterator<Entry<Long, MessageKeys>> { Iterator<Entry<Long, MessageKeys>> currentIterator; final Iterator<Entry<Long, MessageKeys>> highIterator; final Iterator<Entry<Long, MessageKeys>> defaultIterator; final Iterator<Entry<Long, MessageKeys>> lowIterator; MessageOrderIterator(Transaction tx, MessageOrderCursor m) throws IOException { this.defaultIterator = defaultPriorityIndex.iterator(tx, m.defaultCursorPosition); if (highPriorityIndex != null) { this.highIterator = highPriorityIndex.iterator(tx, m.highPriorityCursorPosition); } else { this.highIterator = null; } if (lowPriorityIndex != null) { this.lowIterator = lowPriorityIndex.iterator(tx, m.lowPriorityCursorPosition); } else { this.lowIterator = null; } } public boolean hasNext() { if (currentIterator == null) { if (highIterator != null) { if (highIterator.hasNext()) { currentIterator = highIterator; return currentIterator.hasNext(); } if (defaultIterator.hasNext()) { currentIterator = defaultIterator; return currentIterator.hasNext(); } if (lowIterator.hasNext()) { currentIterator = lowIterator; return currentIterator.hasNext(); } return false; } else { currentIterator = defaultIterator; return currentIterator.hasNext(); } } if (highIterator != null) { if (currentIterator.hasNext()) { return true; } if (currentIterator == highIterator) { if (defaultIterator.hasNext()) { currentIterator = defaultIterator; return currentIterator.hasNext(); } if (lowIterator.hasNext()) { currentIterator = lowIterator; return currentIterator.hasNext(); } return false; } if (currentIterator == defaultIterator) { if (lowIterator.hasNext()) { currentIterator = lowIterator; return currentIterator.hasNext(); } return false; } } return currentIterator.hasNext(); } public Entry<Long, MessageKeys> next() { Entry<Long, MessageKeys> result = currentIterator.next(); if (result != null) { Long key = result.getKey(); if (highIterator != null) { if (currentIterator == defaultIterator) { lastDefaultKey = key; } else if (currentIterator == highIterator) { lastHighKey = key; } else { lastLowKey = key; } } else { lastDefaultKey = key; } } return result; } public void remove() { throw new UnsupportedOperationException(); } } } private static class HashSetStringMarshaller extends VariableMarshaller<HashSet<String>> { final static HashSetStringMarshaller INSTANCE = new HashSetStringMarshaller(); public void writePayload(HashSet<String> object, DataOutput dataOut) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oout = new ObjectOutputStream(baos); oout.writeObject(object); oout.flush(); oout.close(); byte[] data = baos.toByteArray(); dataOut.writeInt(data.length); dataOut.write(data); } public HashSet<String> readPayload(DataInput dataIn) throws IOException { int dataLen = dataIn.readInt(); byte[] data = new byte[dataLen]; dataIn.readFully(data); ByteArrayInputStream bais = new ByteArrayInputStream(data); ObjectInputStream oin = new ObjectInputStream(bais); try { return (HashSet<String>) oin.readObject(); } catch (ClassNotFoundException cfe) { IOException ioe = new IOException("Failed to read HashSet<String>: " + cfe); ioe.initCause(cfe); throw ioe; } } } }
false
false
null
null
diff --git a/client/net/minecraft/src/buildcraft/logisticspipes/ItemModule.java b/client/net/minecraft/src/buildcraft/logisticspipes/ItemModule.java index 5b1e1a6b..17b44e4e 100644 --- a/client/net/minecraft/src/buildcraft/logisticspipes/ItemModule.java +++ b/client/net/minecraft/src/buildcraft/logisticspipes/ItemModule.java @@ -1,193 +1,193 @@ package net.minecraft.src.buildcraft.logisticspipes; import java.util.ArrayList; import net.minecraft.src.ItemStack; import net.minecraft.src.buildcraft.krapht.LogisticsItem; import net.minecraft.src.buildcraft.logisticspipes.modules.ILogisticsModule; import net.minecraft.src.buildcraft.logisticspipes.modules.ISendRoutedItem; import net.minecraft.src.buildcraft.logisticspipes.modules.ModuleAdvancedExtractor; import net.minecraft.src.buildcraft.logisticspipes.modules.ModuleAdvancedExtractorMK2; import net.minecraft.src.buildcraft.logisticspipes.modules.ModuleAdvancedExtractorMK3; import net.minecraft.src.buildcraft.logisticspipes.modules.ModuleExtractorMk2; import net.minecraft.src.buildcraft.logisticspipes.modules.ModuleExtractorMk3; import net.minecraft.src.buildcraft.logisticspipes.modules.ModulePolymorphicItemSink; import net.minecraft.src.buildcraft.logisticspipes.modules.ModuleExtractor; import net.minecraft.src.buildcraft.logisticspipes.modules.ModuleItemSink; import net.minecraft.src.buildcraft.logisticspipes.modules.ModulePassiveSupplier; import net.minecraft.src.buildcraft.logisticspipes.modules.ModuleProvider; import net.minecraft.src.buildcraft.logisticspipes.modules.ModuleQuickSort; import net.minecraft.src.buildcraft.logisticspipes.modules.ModuleTerminus; public class ItemModule extends LogisticsItem{ //PASSIVE MODULES public static final int BLANK = 0; public static final int ITEMSINK = 1; public static final int PASSIVE_SUPPLIER = 2; public static final int EXTRACTOR = 3; public static final int POLYMORPHIC_ITEMSINK = 4; public static final int QUICKSORT = 5; public static final int TERMINUS = 6; public static final int ADVANCED_EXTRACTOR = 7; //PASSIVE MK 2 public static final int EXTRACTOR_MK2 = 100 + EXTRACTOR; public static final int ADVANCED_EXTRACTOR_MK2 = 100 + ADVANCED_EXTRACTOR; - //PASSIVE MK 2 + //PASSIVE MK 3 public static final int EXTRACTOR_MK3 = 200 + EXTRACTOR; public static final int ADVANCED_EXTRACTOR_MK3 = 200 + ADVANCED_EXTRACTOR; //ACTIVE MODULES public static final int PROVIDER = 500; public ItemModule(int i) { super(i); this.hasSubtypes = true; } @Override public int getIconFromDamage(int i) { if (i >= 500){ return 5 * 16 + (i - 500); } if (i >= 200){ return 4 * 16 + (i - 200); } if (i >= 100){ return 3 * 16 + (i - 100); } return 2 * 16 + i; } @Override public String getItemDisplayName(ItemStack itemstack) { switch(itemstack.getItemDamage()){ case BLANK: return "Blank module"; //PASSIVE case ITEMSINK: return "ItemSink module"; case PASSIVE_SUPPLIER: return "Passive Supplier module"; case EXTRACTOR: return "Extractor module"; case POLYMORPHIC_ITEMSINK: return "Polymorphic ItemSink module"; case QUICKSORT: return "QuickSort module"; case TERMINUS: return "Terminus module"; case ADVANCED_EXTRACTOR: return "Advanced Extractor module"; //PASSIVE MK2 case EXTRACTOR_MK2: return "Extractor MK2 module"; case ADVANCED_EXTRACTOR_MK2: return "Advanced Extractor MK2"; //PASSIVE MK3 case EXTRACTOR_MK3: return "Extractor MK3 module"; case ADVANCED_EXTRACTOR_MK3: return "Advanced Extractor MK3"; //ACTIVE case PROVIDER: return "Provider module"; default: return ""; } } @SuppressWarnings({ "unchecked", "rawtypes" }) @Override public void addCreativeItems(ArrayList itemList) { for (int i = 0; i <= 7; i++){ itemList.add(new ItemStack(this, 1, i)); } itemList.add(new ItemStack(this, 1, 103)); itemList.add(new ItemStack(this, 1, 107)); itemList.add(new ItemStack(this, 1, 203)); itemList.add(new ItemStack(this, 1, 207)); for (int i = 500; i <= 500; i++){ itemList.add(new ItemStack(this, 1, i)); } } public ILogisticsModule getModuleForItem(ItemStack itemStack, ILogisticsModule currentModule, IInventoryProvider invProvider, ISendRoutedItem itemSender){ if (itemStack == null) return null; if (itemStack.itemID != this.shiftedIndex) return null; switch (itemStack.getItemDamage()){ //PASSIVE case ITEMSINK: if (currentModule instanceof ModuleItemSink) return currentModule; return new ModuleItemSink(); case PASSIVE_SUPPLIER: if (currentModule instanceof ModulePassiveSupplier) return currentModule; return new ModulePassiveSupplier(invProvider); case EXTRACTOR: if (currentModule != null && currentModule.getClass().equals(ModuleExtractor.class)) return currentModule; return new ModuleExtractor(invProvider, itemSender); case POLYMORPHIC_ITEMSINK: if (currentModule instanceof ModulePolymorphicItemSink) return currentModule; return new ModulePolymorphicItemSink(invProvider); case QUICKSORT: if (currentModule instanceof ModuleQuickSort) return currentModule; return new ModuleQuickSort(invProvider, itemSender); case TERMINUS: if (currentModule instanceof ModuleTerminus) return currentModule; return new ModuleTerminus(); case ADVANCED_EXTRACTOR: if (currentModule != null && currentModule.getClass().equals(ModuleAdvancedExtractor.class)) return currentModule; return new ModuleAdvancedExtractor(invProvider, itemSender); //PASSIVE MK2 case EXTRACTOR_MK2: if (currentModule != null && currentModule.getClass().equals(ModuleExtractorMk2.class)) return currentModule; return new ModuleExtractorMk2(invProvider, itemSender); case ADVANCED_EXTRACTOR_MK2: if (currentModule != null && currentModule.getClass().equals(ModuleAdvancedExtractorMK2.class)) return currentModule; return new ModuleAdvancedExtractorMK2(invProvider, itemSender); //PASSIVE MK2 case EXTRACTOR_MK3: if (currentModule != null && currentModule.getClass().equals(ModuleExtractorMk3.class)) return currentModule; return new ModuleExtractorMk3(invProvider, itemSender); case ADVANCED_EXTRACTOR_MK3: if (currentModule != null && currentModule.getClass().equals(ModuleAdvancedExtractorMK3.class)) return currentModule; return new ModuleAdvancedExtractorMK3(invProvider, itemSender); //ACTIVE case PROVIDER: if (currentModule instanceof ModuleProvider) return currentModule; return new ModuleProvider(invProvider, itemSender); default: return null; } } }
true
false
null
null
diff --git a/impl/src/main/java/org/jboss/jsr299/tck/tests/context/dependent/DependentContextTest.java b/impl/src/main/java/org/jboss/jsr299/tck/tests/context/dependent/DependentContextTest.java index 51d24f542..81b858356 100644 --- a/impl/src/main/java/org/jboss/jsr299/tck/tests/context/dependent/DependentContextTest.java +++ b/impl/src/main/java/org/jboss/jsr299/tck/tests/context/dependent/DependentContextTest.java @@ -1,420 +1,420 @@ package org.jboss.jsr299.tck.tests.context.dependent; import java.lang.annotation.Annotation; import java.util.Set; import javax.enterprise.context.Dependent; import javax.enterprise.context.spi.Context; import javax.enterprise.context.spi.CreationalContext; import javax.enterprise.inject.AnnotationLiteral; import javax.enterprise.inject.spi.Bean; import org.jboss.jsr299.tck.AbstractJSR299Test; import org.jboss.jsr299.tck.impl.MockCreationalContext; import org.jboss.test.audit.annotations.SpecAssertion; import org.jboss.test.audit.annotations.SpecAssertions; import org.jboss.test.audit.annotations.SpecVersion; import org.jboss.testharness.impl.packaging.Artifact; import org.jboss.testharness.impl.packaging.jsr299.BeansXml; import org.testng.annotations.Test; @Artifact @BeansXml("beans.xml") @SpecVersion(spec="cdi", version="PFD2") public class DependentContextTest extends AbstractJSR299Test { private static final Annotation TAME_LITERAL = new AnnotationLiteral<Tame> () {}; private static final Annotation PET_LITERAL = new AnnotationLiteral<Pet> () {}; @Test(groups = { "contexts", "injection" }) @SpecAssertions({ @SpecAssertion(section = "6.4", id = "a"), @SpecAssertion(section = "6.4.1", id = "ga") }) public void testInstanceNotSharedBetweenInjectionPoints() { Set<Bean<Fox>> foxBeans = getBeans(Fox.class); assert foxBeans.size() == 1; Set<Bean<FoxRun>> foxRunBeans = getBeans(FoxRun.class); assert foxRunBeans.size() == 1; Bean<FoxRun> foxRunBean = foxRunBeans.iterator().next(); CreationalContext<FoxRun> creationalContext = getCurrentManager().createCreationalContext(foxRunBean); FoxRun foxRun = foxRunBean.create(creationalContext); assert !foxRun.fox.equals(foxRun.anotherFox); } @Test(groups = { "contexts", "injection" }) @SpecAssertions({ @SpecAssertion(section = "6.4.1", id = "ga"), @SpecAssertion(section = "6.4.1", id = "gb"), @SpecAssertion(section = "6.4.1", id = "gc") }) public void testDependentBeanIsDependentObjectOfBeanInjectedInto() { FoxFarm foxFarm = getInstanceByType(FoxFarm.class); FoxHole foxHole = getInstanceByType(FoxHole.class); assert !foxFarm.fox.equals(foxHole.fox); assert !foxFarm.fox.equals(foxFarm.constructorFox); assert !foxFarm.constructorFox.equals(foxHole.initializerFox); assert !foxHole.fox.equals(foxHole.initializerFox); } @Test(groups = { "contexts", "el" }) @SpecAssertion(section = "6.4", id = "ca") public void testInstanceUsedForElEvaluationNotShared() throws Exception { Set<Bean<Fox>> foxBeans = getBeans(Fox.class); assert foxBeans.size() == 1; Fox fox1 = getCurrentConfiguration().getEl().evaluateValueExpression("#{fox}", Fox.class); Fox fox2 = getCurrentConfiguration().getEl().evaluateValueExpression("#{fox}", Fox.class); assert !fox1.equals(fox2); } @Test(groups = { "contexts", "producerMethod" }) @SpecAssertion(section = "6.4", id = "da") public void testInstanceUsedForProducerMethodNotShared() throws Exception { Bean<Tarantula> tarantulaBean = getBeans(Tarantula.class, PET_LITERAL).iterator().next(); CreationalContext<Tarantula> creationalContext = getCurrentManager().createCreationalContext(tarantulaBean); Tarantula tarantula = tarantulaBean.create(creationalContext); Tarantula tarantula2 = tarantulaBean.create(creationalContext); assert tarantula != null; assert tarantula2 != null; assert tarantula != tarantula2; } @Test(groups = { "contexts", "producerMethod" }) @SpecAssertion(section = "6.4", id = "db") public void testInstanceUsedForProducerFieldNotShared() throws Exception { Bean<Tarantula> tarantulaBean = getBeans(Tarantula.class, TAME_LITERAL).iterator().next(); CreationalContext<Tarantula> creationalContext = getCurrentManager().createCreationalContext(tarantulaBean); Tarantula tarantula = tarantulaBean.create(creationalContext); Tarantula tarantula2 = tarantulaBean.create(creationalContext); assert tarantula != null; assert tarantula2 != null; assert tarantula != tarantula2; } @Test(groups = { "contexts", "disposalMethod" }) @SpecAssertion(section = "6.4", id = "dc") public void testInstanceUsedForDisposalMethodNotShared() { SpiderProducer spiderProducer = getInstanceByType(SpiderProducer.class); - Bean<Tarantula> tarantulaBean = getBeans(Tarantula.class).iterator().next(); + Bean<Tarantula> tarantulaBean = getUniqueBean(Tarantula.class, PET_LITERAL); CreationalContext<Tarantula> creationalContext = getCurrentManager().createCreationalContext(tarantulaBean); Tarantula tarantula = tarantulaBean.create(creationalContext); assert tarantula != null; tarantulaBean.destroy(tarantula, creationalContext); assert SpiderProducer.getInstanceUsedForDisposal() != null; assert SpiderProducer.getInstanceUsedForDisposal() != spiderProducer; } @Test(groups = { "contexts", "observerMethod" }) @SpecAssertion(section = "6.4", id = "dd") public void testInstanceUsedForObserverMethodNotShared() { HorseStable firstStableInstance = getInstanceByType(HorseStable.class); getCurrentManager().fireEvent(new HorseInStableEvent()); assert HorseStable.getInstanceThatObservedEvent() != null; assert HorseStable.getInstanceThatObservedEvent() != firstStableInstance; } @Test(groups = "contexts") @SpecAssertion(section = "6.4", id = "e") public void testContextGetWithCreationalContextReturnsNewInstance() { Set<Bean<Fox>> foxBeans = getBeans(Fox.class); assert foxBeans.size() == 1; Bean<Fox> foxBean = foxBeans.iterator().next(); Context context = getCurrentManager().getContext(Dependent.class); assert context.get(foxBean, new MockCreationalContext<Fox>()) != null; assert context.get(foxBean, new MockCreationalContext<Fox>()) instanceof Fox; } @Test(groups = "contexts") @SpecAssertion(section = "6.4", id = "f") public void testContextGetWithCreateFalseReturnsNull() { Set<Bean<Fox>> foxBeans = getBeans(Fox.class); assert foxBeans.size() == 1; Bean<Fox> foxBean = foxBeans.iterator().next(); Context context = getCurrentManager().getContext(Dependent.class); assert context.get(foxBean, null) == null; } @Test(groups = { "contexts" }) @SpecAssertion(section = "6.2", id = "ab") public void testContextScopeType() { assert getCurrentManager().getContext(Dependent.class).getScope().equals(Dependent.class); } @Test(groups = { "contexts" }) @SpecAssertions({ @SpecAssertion(section = "6.2", id = "ha"), @SpecAssertion(section = "6.4", id = "g") }) public void testContextIsActive() { assert getCurrentManager().getContext(Dependent.class).isActive(); } @Test(groups = { "contexts", "producerMethod" }) @SpecAssertions({ @SpecAssertion(section = "6.2", id = "ha"), @SpecAssertion(section = "6.4", id = "g") // Dependent context is now always active }) public void testContextIsActiveWhenInvokingProducerMethod() { Bean<Tarantula> tarantulaBean = getBeans(Tarantula.class).iterator().next(); CreationalContext<Tarantula> creationalContext = getCurrentManager().createCreationalContext(tarantulaBean); Tarantula tarantula = tarantulaBean.create(creationalContext); assert tarantula != null; assert SpiderProducer.isDependentContextActive(); } @Test(groups = { "contexts", "producerField"}) @SpecAssertion(section = "6.4", id = "g") // Dependent context is now always active public void testContextIsActiveWhenInvokingProducerField() { // Reset test class Tarantula.reset(); getInstanceByType(Tarantula.class,TAME_LITERAL); assert Tarantula.isDependentContextActive(); } @Test(groups = { "contexts", "disposalMethod" }) @SpecAssertions({ @SpecAssertion(section = "6.4", id = "g"), @SpecAssertion(section = "11.1", id = "aa") }) public void testContextIsActiveWhenInvokingDisposalMethod() { Bean<Tarantula> tarantulaBean = getBeans(Tarantula.class, PET_LITERAL).iterator().next(); CreationalContext<Tarantula> creationalContext = getCurrentManager().createCreationalContext(tarantulaBean); Tarantula tarantula = tarantulaBean.create(creationalContext); assert tarantula != null; SpiderProducer.reset(); tarantulaBean.destroy(tarantula, creationalContext); assert SpiderProducer.isDependentContextActive(); } @Test(groups = { "contexts", "observerMethod" }) @SpecAssertion(section = "6.4", id = "g") // Dependent context is now always active public void testContextIsActiveWhenCreatingObserverMethodInstance() { getCurrentManager().fireEvent(new HorseInStableEvent()); assert HorseStable.isDependentContextActive(); } @Test(groups = { "contexts", "el" }) @SpecAssertion(section = "6.4", id = "g") // Dependent context is now always active public void testContextIsActiveWhenEvaluatingElExpression() { SensitiveFox.setManager(getCurrentManager()); String foxName = getCurrentConfiguration().getEl().evaluateMethodExpression("#{sensitiveFox.getName}", String.class, new Class[0], new Object[0]); assert foxName != null; assert SensitiveFox.isDependentContextActiveDuringEval(); } @Test(groups = { "contexts", "beanLifecycle" }) @SpecAssertion(section = "6.4", id = "g") // Dependent context is now always active public void testContextIsActiveDuringBeanCreation() { SensitiveFox.setManager(getCurrentManager()); SensitiveFox fox1 = getInstanceByType(SensitiveFox.class); assert fox1 != null; assert fox1.isDependentContextActiveDuringCreate(); } @Test(groups = { "contexts", "injection" }) @SpecAssertion(section = "6.4", id = "g") // Dependent context is now always active public void testContextIsActiveDuringInjection() { Bean<FoxRun> foxRunBean = getBeans(FoxRun.class).iterator().next(); FoxRun foxRun = foxRunBean.create(new MockCreationalContext<FoxRun>()); assert foxRun.fox != null; } @Test(groups = { "contexts", "beanDestruction"}) @SpecAssertions({ @SpecAssertion(section = "6.4.2", id = "aaaa"), @SpecAssertion(section = "6.4", id = "b") }) public void testDestroyingSimpleParentDestroysDependents() { assert getBeans(Farm.class).size() == 1; Bean<Farm> farmBean = getBeans(Farm.class).iterator().next(); CreationalContext<Farm> creationalContext = getCurrentManager().createCreationalContext(farmBean); Farm farm = farmBean.create(creationalContext); farm.open(); Stable.destroyed = false; Horse.destroyed = false; farmBean.destroy(farm, creationalContext); assert Stable.destroyed; assert Horse.destroyed; } @Test(groups = { "contexts", "beanDestruction"}) @SpecAssertions({ @SpecAssertion(section = "6.1.1", id = "e") }) public void testCallingCreationalContextReleaseDestroysDependents() { assert getBeans(Farm.class).size() == 1; Bean<Farm> farmBean = getBeans(Farm.class).iterator().next(); CreationalContext<Farm> creationalContext = getCurrentManager().createCreationalContext(farmBean); Farm farm = farmBean.create(creationalContext); farm.open(); Stable.destroyed = false; Horse.destroyed = false; creationalContext.release(); assert Stable.destroyed; assert Horse.destroyed; } @Test(groups = { "contexts", "beanDestruction"}) @SpecAssertions({ @SpecAssertion(section = "6.4.2", id = "aaaa"), @SpecAssertion(section = "6.4", id = "b") }) public void testDestroyingManagedParentDestroysDependentsOfSameBean() { // Reset test class Fox.reset(); assert getCurrentManager().getBeans(FoxRun.class).size() == 1; Bean<FoxRun> bean = getBeans(FoxRun.class).iterator().next(); CreationalContext<FoxRun> creationalContext = getCurrentManager().createCreationalContext(bean); FoxRun instance = bean.create(creationalContext); assert instance.fox != instance.anotherFox; bean.destroy(instance, creationalContext); assert Fox.isDestroyed(); assert Fox.getDestroyCount() == 2; } @Test(groups = { "contexts", "el"}) @SpecAssertion(section = "6.4.2", id = "eee") public void testDependentsDestroyedWhenElEvaluationCompletes() throws Exception { // Reset test class Fox.reset(); FoxRun.setDestroyed(false); getCurrentConfiguration().getEl().evaluateValueExpression("#{foxRun}", FoxRun.class); assert FoxRun.isDestroyed(); assert Fox.isDestroyed(); } @Test(groups = { "contexts", "producerMethod" }) @SpecAssertions({ @SpecAssertion(section = "6.4.2", id = "ddd"), @SpecAssertion(section = "6.4.1", id="h") }) public void testDependentsDestroyedWhenProducerMethodCompletes() { // Reset the test class SpiderProducer.reset(); Tarantula.reset(); Tarantula spiderInstance = getInstanceByType(Tarantula.class, PET_LITERAL); spiderInstance.ping(); assert SpiderProducer.isDestroyed(); assert Tarantula.isDestroyed(); } @Test(groups = { "contexts", "producerField" }) @SpecAssertion(section = "6.4.2", id = "dde") public void testDependentsDestroyedWhenProducerFieldCompletes() { // Reset the test class OtherSpiderProducer.setDestroyed(false); Tarantula spiderInstance = getInstanceByType(Tarantula.class,TAME_LITERAL); assert spiderInstance != null; assert OtherSpiderProducer.isDestroyed(); } @Test(groups = { "contexts", "disposalMethod" }) @SpecAssertions({ @SpecAssertion(section = "6.4.2", id = "ddf"), @SpecAssertion(section = "6.4.2", id ="ccc") }) public void testDependentsDestroyedWhenDisposerMethodCompletes() { Bean<Tarantula> tarantulaBean = getBeans(Tarantula.class, PET_LITERAL).iterator().next(); CreationalContext<Tarantula> creationalContext = getCurrentManager().createCreationalContext(tarantulaBean); Tarantula tarantula = tarantulaBean.create(creationalContext); assert tarantula != null; // Reset test class state SpiderProducer.reset(); Fox.reset(); tarantulaBean.destroy(tarantula, creationalContext); assert SpiderProducer.isDestroyed(); assert Fox.isDestroyed(); } @Test(groups = { "contexts", "observerMethod" }) @SpecAssertions({ @SpecAssertion(section = "6.4.2", id = "ddg"), @SpecAssertion(section = "6.4.2", id = "ccd") }) public void testDependentsDestroyedWhenObserverMethodEvaluationCompletes() { // Reset test class state... HorseStable.reset(); Fox.reset(); getCurrentManager().fireEvent(new HorseInStableEvent()); assert HorseStable.getInstanceThatObservedEvent() != null; assert HorseStable.isDestroyed(); assert Fox.isDestroyed(); } @Test(groups = { "contexts" }) @SpecAssertion(section = "6.4.1", id = "ab") public void testDependentScopedDecoratorsAreDependentObjectsOfBean() { Bean<Interior> roomBean = getBeans(Interior.class, new RoomBinding()).iterator().next(); CreationalContext<Interior> roomCreationalContext = getCurrentManager().createCreationalContext(roomBean); Interior room = roomBean.create(roomCreationalContext); InteriorDecorator.reset(); room.foo(); assert InteriorDecorator.getInstances().size() == 1; roomBean.destroy(room, roomCreationalContext); assert InteriorDecorator.isDestroyed(); } @Test @SpecAssertion(section = "6.4.1", id = "aa") public void testDependentScopedInterceptorsAreDependentObjectsOfBean() { TransactionalInterceptor.destroyed = false; TransactionalInterceptor.intercepted = false; Bean<AccountTransaction> bean = getBeans(AccountTransaction.class).iterator().next(); CreationalContext<AccountTransaction> ctx = getCurrentManager().createCreationalContext(bean); AccountTransaction trans = bean.create(ctx); trans.execute(); assert TransactionalInterceptor.intercepted; bean.destroy(trans, ctx); assert TransactionalInterceptor.destroyed; } }
true
false
null
null
diff --git a/src/com/dmdirc/Query.java b/src/com/dmdirc/Query.java index 0e940e21f..ac1bb0ccf 100644 --- a/src/com/dmdirc/Query.java +++ b/src/com/dmdirc/Query.java @@ -1,348 +1,349 @@ /* * Copyright (c) 2006-2007 Chris Smith, Shane Mc Cormack, Gregory Holmes * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.dmdirc; import com.dmdirc.actions.ActionManager; import com.dmdirc.actions.CoreActionType; import com.dmdirc.commandparser.CommandManager; import com.dmdirc.logger.ErrorLevel; import com.dmdirc.logger.Logger; import com.dmdirc.parser.ClientInfo; import com.dmdirc.parser.IRCParser; import com.dmdirc.parser.callbacks.CallbackManager; import com.dmdirc.parser.callbacks.CallbackNotFound; import com.dmdirc.parser.callbacks.interfaces.INickChanged; import com.dmdirc.parser.callbacks.interfaces.IPrivateAction; import com.dmdirc.parser.callbacks.interfaces.IPrivateMessage; import com.dmdirc.parser.callbacks.interfaces.IQuit; import com.dmdirc.ui.input.TabCompleter; import com.dmdirc.ui.interfaces.InputWindow; import com.dmdirc.ui.interfaces.QueryWindow; import java.io.Serializable; /** * The Query class represents the client's view of a query with another user. * It handles callbacks for query events from the parser, maintains the * corresponding QueryWindow, and handles user input for the query. * @author chris */ public final class Query extends MessageTarget implements IPrivateAction, IPrivateMessage, INickChanged, IQuit, 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 = 1; /** The Server this Query is on. */ private Server server; /** The QueryWindow used for this Query. */ private QueryWindow window; /** The full host of the client associated with this Query. */ private String host; /** The tab completer for the query window. */ private final TabCompleter tabCompleter; /** * Creates a new instance of Query. * * @param newHost host of the remove client * @param newServer The server object that this Query belongs to */ public Query(final Server newServer, final String newHost) { super(); this.server = newServer; this.host = newHost; icon = IconManager.getIconManager().getIcon("query"); window = Main.getUI().getQuery(this); ActionManager.processEvent(CoreActionType.QUERY_OPENED, null, this); window.setFrameIcon(icon); if (!Config.getOptionBool("general", "hidequeries")) { window.open(); } tabCompleter = new TabCompleter(server.getTabCompleter()); tabCompleter.addEntries(CommandManager.getQueryCommandNames()); tabCompleter.addEntries(CommandManager.getChatCommandNames()); window.getInputHandler().setTabCompleter(tabCompleter); reregister(); updateTitle(); } /** * Shows this query's window. */ public void show() { window.open(); } /** {@inheritDoc} */ public InputWindow getFrame() { return window; } /** * Returns the tab completer for this query. * * @return This query's tab completer */ public TabCompleter getTabCompleter() { return tabCompleter; } /** {@inheritDoc} */ public void sendLine(final String line) { final ClientInfo client = server.getParser().getMyself(); if (line.length() <= getMaxLineLength()) { server.getParser().sendMessage(ClientInfo.parseHost(host), window.getTranscoder().encode(line)); final StringBuffer buff = new StringBuffer("querySelfMessage"); ActionManager.processEvent(CoreActionType.QUERY_SELF_MESSAGE, buff, this, line); window.addLine(buff, client.getNickname(), client.getIdent(), client.getHost(), window.getTranscoder().encode(line)); } else { sendLine(line.substring(0, getMaxLineLength())); sendLine(line.substring(getMaxLineLength())); } } /** {@inheritDoc} */ public int getMaxLineLength() { return server.getParser().getMaxLength("PRIVMSG", host); } /** * Sends a private action to the remote user. * * @param action action text to send */ public void sendAction(final String action) { final ClientInfo client = server.getParser().getMyself(); final int maxLineLength = server.getParser().getMaxLength("PRIVMSG", host); if (maxLineLength >= action.length() + 2) { server.getParser().sendAction(ClientInfo.parseHost(host), window.getTranscoder().encode(action)); final StringBuffer buff = new StringBuffer("querySelfAction"); ActionManager.processEvent(CoreActionType.QUERY_SELF_ACTION, buff, this, action); window.addLine(buff, client.getNickname(), client.getIdent(), client.getHost(), window.getTranscoder().encode(action)); } else { window.addLine("actionTooLong", action.length()); } } /** * Handles a private message event from the parser. * * @param parser Parser receiving the event * @param message message received * @param remoteHost remote user host */ public void onPrivateMessage(final IRCParser parser, final String message, final String remoteHost) { final String[] parts = ClientInfo.parseHostFull(remoteHost); final StringBuffer buff = new StringBuffer("queryMessage"); ActionManager.processEvent(CoreActionType.QUERY_MESSAGE, buff, this, message); window.addLine(buff, parts[0], parts[1], parts[2], message); } /** * Handles a private action event from the parser. * * @param parser Parser receiving the event * @param message message received * @param remoteHost remote host */ public void onPrivateAction(final IRCParser parser, final String message, final String remoteHost) { final String[] parts = ClientInfo.parseHostFull(host); final StringBuffer buff = new StringBuffer("queryAction"); ActionManager.processEvent(CoreActionType.QUERY_ACTION, buff, this, message); window.addLine(buff, parts[0], parts[1], parts[2], message); } /** * Updates the QueryWindow's title. */ private void updateTitle() { final String title = ClientInfo.parseHost(host); window.setTitle(title); if (window.isMaximum() && window.equals(Main.getUI().getMainWindow().getActiveFrame())) { Main.getUI().getMainWindow().setTitle(Main.getUI().getMainWindow().getTitlePrefix() + " - " + title); } } /** * Reregisters query callbacks. Called when reconnecting to the server. */ public void reregister() { final CallbackManager callbackManager = server.getParser().getCallbackManager(); try { callbackManager.addCallback("onPrivateAction", this, ClientInfo.parseHost(host)); callbackManager.addCallback("onPrivateMessage", this, ClientInfo.parseHost(host)); callbackManager.addCallback("onQuit", this); callbackManager.addCallback("onNickChanged", this); } catch (CallbackNotFound ex) { Logger.appError(ErrorLevel.HIGH, "Unable to get query events", ex); } } /** {@inheritDoc} */ public void onNickChanged(final IRCParser tParser, final ClientInfo cClient, final String sOldNick) { if (sOldNick.equals(ClientInfo.parseHost(host))) { final CallbackManager callbackManager = server.getParser().getCallbackManager(); callbackManager.delCallback("onPrivateAction", this); callbackManager.delCallback("onPrivateMessage", this); try { callbackManager.addCallback("onPrivateAction", this, cClient.getNickname()); callbackManager.addCallback("onPrivateMessage", this, cClient.getNickname()); } catch (CallbackNotFound ex) { Logger.appError(ErrorLevel.HIGH, "Unable to get query events", ex); } final StringBuffer format = new StringBuffer("queryNickChanged"); ActionManager.processEvent(CoreActionType.QUERY_NICKCHANGE, format, this, sOldNick); window.addLine(format, sOldNick, cClient.getIdent(), cClient.getHost(), cClient.getNickname()); host = cClient.getNickname() + "!" + cClient.getIdent() + "@" + cClient.getHost(); updateTitle(); } } /** {@inheritDoc} */ public void onQuit(final IRCParser tParser, final ClientInfo cClient, final String sReason) { if (cClient.getNickname().equals(ClientInfo.parseHost(host))) { final StringBuffer format = new StringBuffer(sReason.isEmpty() ? "queryQuit" : "queryQuitReason"); ActionManager.processEvent(CoreActionType.QUERY_QUIT, format, this, sReason); window.addLine(format, cClient.getNickname(), cClient.getIdent(), cClient.getHost(), sReason); } } /** * Returns the Server assocaited with this query. * * @return asscoaited Server */ public Server getServer() { return server; } /** * Closes the query and associated window. */ public void close() { close(true); } /** * Closes the query and associated window. * * @param shouldRemove Whether or not we should remove the window from the server. */ public void close(final boolean shouldRemove) { server.getParser().getCallbackManager().delCallback("onPrivateAction", this); server.getParser().getCallbackManager().delCallback("onPrivateMessage", this); server.getParser().getCallbackManager().delCallback("onNickChanged", this); server.getParser().getCallbackManager().delCallback("onQuit", this); ActionManager.processEvent(CoreActionType.QUERY_CLOSED, null, this); window.setVisible(false); - server.delQuery(host); if (shouldRemove) { - Main.getUI().getMainWindow().delChild(window); + server.delQuery(host); } + Main.getUI().getMainWindow().delChild(window); + window = null; server = null; } /** * Returns this query's name. * * @return A string representation of this query (i.e., the user's name) */ public String toString() { return ClientInfo.parseHost(host); } /** * Returns the host that this query is with. * * @return The full host that this query is with */ public String getHost() { return host; } /** {@inheritDoc} */ @Override public void activateFrame() { if (!window.isVisible()) { show(); } Main.getUI().getMainWindow().setActiveFrame(window); } }
false
false
null
null
diff --git a/programs/slammer/gui/SelectRecordsPanel.java b/programs/slammer/gui/SelectRecordsPanel.java index efc9bf6e..e400f365 100644 --- a/programs/slammer/gui/SelectRecordsPanel.java +++ b/programs/slammer/gui/SelectRecordsPanel.java @@ -1,597 +1,597 @@ /* This file is in the public domain. */ package slammer.gui; import javax.swing.*; import javax.swing.event.*; import java.awt.*; import java.awt.event.*; import javax.swing.border.*; import java.util.ArrayList; import slammer.*; class SelectRecordsPanel extends JPanel implements ActionListener,TableModelListener { SlammerTabbedPane parent; String[][] searchList = SlammerTable.getSearchList(); JTextField[][] textFields = new JTextField[searchList.length][2]; JButton searchButton = new JButton("Search for records"); JButton clearButton = new JButton("Clear all search fields"); JLabel searchTA = new JLabel(); JComboBox eqList = new JComboBox(); JComboBox recordList = new JComboBox(); JButton selectRecord = new JButton("Select record(s)"); JCheckBox FocMechAll = new JCheckBox("All", true); JCheckBox FocMechStrikeSlip = new JCheckBox(SlammerTable.FocMechArray[SlammerTable.FMStrikeSlip]); JCheckBox FocMechReverse = new JCheckBox(SlammerTable.FocMechArray[SlammerTable.FMReverse]); JCheckBox FocMechNormal = new JCheckBox(SlammerTable.FocMechArray[SlammerTable.FMNormal]); JCheckBox FocMechObliqueReverse = new JCheckBox(SlammerTable.FMObliqueReverseLong); JCheckBox FocMechObliqueNormal = new JCheckBox(SlammerTable.FMObliqueNormalLong); JCheckBox SiteClassAll = new JCheckBox("All", true); JCheckBox SiteClassA = new JCheckBox(SlammerTable.SiteClassArray[SlammerTable.SCA]); JCheckBox SiteClassB = new JCheckBox(SlammerTable.SiteClassArray[SlammerTable.SCB]); JCheckBox SiteClassC = new JCheckBox(SlammerTable.SiteClassArray[SlammerTable.SCC]); JCheckBox SiteClassD = new JCheckBox(SlammerTable.SiteClassArray[SlammerTable.SCD]); JCheckBox SiteClassE = new JCheckBox(SlammerTable.SiteClassArray[SlammerTable.SCE]); JButton selectNone = new JButton("Deselect all for analysis"); JButton selectAll = new JButton("Select all for analysis"); JButton emptyTable = new JButton("Clear table"); JButton deleteSelected = new JButton("Clear highlighted record(s)"); JButton groupManage = new JButton("Manage groups..."); GroupFrame groupFrame; SlammerTable table; JButton next = new JButton("Go to Step 2: Select Analyses"); JLabel selectLabel = new JLabel(); boolean isSlammer; public SelectRecordsPanel(SlammerTabbedPane parent, boolean isSlammer) throws Exception { this.parent = parent; this.isSlammer = isSlammer; searchButton.setActionCommand("search"); searchButton.addActionListener(this); clearButton.setActionCommand("clear"); clearButton.addActionListener(this); FocMechAll.setActionCommand("focMechAll"); FocMechStrikeSlip.setActionCommand("focMechOther"); FocMechReverse.setActionCommand("focMechOther"); FocMechNormal.setActionCommand("focMechOther"); FocMechObliqueReverse.setActionCommand("focMechOther"); FocMechObliqueNormal.setActionCommand("focMechOther"); SiteClassAll.setActionCommand("SiteClassAll"); SiteClassA.setActionCommand("siteClassOther"); SiteClassB.setActionCommand("siteClassOther"); SiteClassC.setActionCommand("siteClassOther"); SiteClassD.setActionCommand("siteClassOther"); SiteClassE.setActionCommand("siteClassOther"); FocMechAll.addActionListener(this); FocMechStrikeSlip.addActionListener(this); FocMechReverse.addActionListener(this); FocMechNormal.addActionListener(this); FocMechObliqueReverse.addActionListener(this); FocMechObliqueNormal.addActionListener(this); SiteClassAll.addActionListener(this); SiteClassA.addActionListener(this); SiteClassB.addActionListener(this); SiteClassC.addActionListener(this); SiteClassD.addActionListener(this); SiteClassE.addActionListener(this); Utils.addEQList(eqList); Utils.updateRecordList(recordList, eqList); eqList.setActionCommand("eqListChange"); eqList.addActionListener(this); selectRecord.setActionCommand("addRecord"); selectRecord.addActionListener(this); selectNone.setActionCommand("none"); selectNone.addActionListener(this); selectAll.setActionCommand("all"); selectAll.addActionListener(this); emptyTable.setActionCommand("empty"); emptyTable.addActionListener(this); deleteSelected.setActionCommand("deleteSelected"); deleteSelected.addActionListener(this); next.setActionCommand("next"); next.addActionListener(this); groupManage.setActionCommand("groupmanage"); groupManage.addActionListener(this); updateSelectLabel(); JPanel selectPanel = new JPanel(new BorderLayout()); selectPanel.add(BorderLayout.NORTH, createTabbedPanel()); selectPanel.add(BorderLayout.CENTER, createSlammerTablePanel()); selectPanel.add(BorderLayout.SOUTH, selectLabel); setLayout(new BorderLayout()); add(BorderLayout.CENTER, selectPanel); table.getModel().addTableModelListener(this); groupFrame = new GroupFrame(table.getModel(), this); } private JTabbedPane createTabbedPanel() { JTabbedPane pane = new JTabbedPane(); pane.addTab("Search records by properties", createSearchPanel()); pane.addTab("Select individual records", createSelectIndivPanel()); return pane; } private JPanel createSearchPanel() { JPanel selectHeaderArrayList = new JPanel(new BorderLayout()); selectHeaderArrayList.add(BorderLayout.WEST, createParmsPanel()); ArrayList checkBoxesArrayList = new ArrayList(2); checkBoxesArrayList.add(createSiteClassPanel()); JPanel ret = new JPanel(new BorderLayout()); ret.add(BorderLayout.NORTH, selectHeaderArrayList); ret.add(BorderLayout.WEST, GUIUtils.makeRecursiveLayoutDown(checkBoxesArrayList)); ret.add(BorderLayout.SOUTH, createFocMechPanel()); return ret; } private JPanel createFocMechPanel() { ArrayList list = new ArrayList(); list.add(new JLabel(SlammerTable.fieldArray[SlammerTable.rowFocMech][SlammerTable.colFieldName].toString() + ": ")); list.add(FocMechAll); list.add(FocMechStrikeSlip); list.add(FocMechNormal); list.add(FocMechReverse); list.add(FocMechObliqueNormal); list.add(FocMechObliqueReverse); return GUIUtils.makeRecursiveLayoutRight(list); } private JPanel createSiteClassPanel() { ArrayList list = new ArrayList(); list.add(new JLabel(SlammerTable.fieldArray[SlammerTable.rowSiteClass][SlammerTable.colFieldName].toString() + ": ")); list.add(SiteClassAll); list.add(SiteClassA); list.add(SiteClassB); list.add(SiteClassC); list.add(SiteClassD); list.add(SiteClassE); return GUIUtils.makeRecursiveLayoutRight(list); } private JPanel createParmsPanel() { JPanel searchPanel = new JPanel(new BorderLayout()); GridBagLayout gridbag = new GridBagLayout(); GridBagConstraints c = new GridBagConstraints(); JPanel searchFields = new JPanel(); searchFields.setLayout(gridbag); Component comp; int x = 1; int y = 0; c.gridx = x++; c.gridy = y++; c.anchor = GridBagConstraints.NORTHWEST; c.fill = GridBagConstraints.HORIZONTAL; c.weightx = 1; c.insets = new Insets(0, 0, 0, 8); comp = new JLabel("Greater than or equal to:"); gridbag.setConstraints(comp, c); searchFields.add(comp); c.gridx = x++; comp = new JLabel("Less than or equal to:"); gridbag.setConstraints(comp, c); searchFields.add(comp); c.insets = new Insets(0, 0, 0, 0); for(int i = 0; i < textFields.length; i++) { textFields[i][0] = new JTextField(5); textFields[i][1] = new JTextField(5); x = 0; c.gridx = x++; c.gridy = y++; c.weightx = 0; comp = new JLabel(searchList[i][0]); gridbag.setConstraints(comp, c); searchFields.add(comp); c.gridx = x++; c.weightx = 1; comp = textFields[i][0]; gridbag.setConstraints(comp, c); searchFields.add(comp); c.gridx = x++; comp = textFields[i][1]; gridbag.setConstraints(comp, c); searchFields.add(comp); switch(i) { case 0: comp = searchButton; break; case 2: comp = clearButton; break; case 4: comp = searchTA; break; default: comp = null; break; } if(comp != null) { c.gridx = x++; c.weightx = 1; c.gridheight = 2; c.fill = GridBagConstraints.NONE; gridbag.setConstraints(comp, c); searchFields.add(comp); c.gridheight = 1; c.fill = GridBagConstraints.HORIZONTAL; } } searchPanel.add(BorderLayout.WEST, searchFields); return searchPanel; } private JPanel createSelectIndivPanel() { JPanel panel = new JPanel(); GridLayout gl = new GridLayout(0, 3); gl.setHgap(10); panel.setLayout(gl); panel.add(new JLabel("Earthquake")); panel.add(new JLabel("Record name")); panel.add(new JLabel()); panel.add(eqList); panel.add(recordList); panel.add(selectRecord); /* This is to make it not take up the entire space */ ArrayList list = new ArrayList(); list.add(panel); panel = GUIUtils.makeRecursiveLayoutDown(list); list = new ArrayList(); list.add(panel); panel = GUIUtils.makeRecursiveLayoutRight(list); return panel; } private JPanel createSlammerTablePanel() throws Exception { JPanel searchTablePanel = new JPanel(new BorderLayout()); JPanel header = new JPanel(new BorderLayout()); if(isSlammer) { JPanel headerEast = new JPanel(new GridLayout(1, 0)); headerEast.add(selectAll); headerEast.add(selectNone); header.add(BorderLayout.EAST, headerEast); } JLabel label = new JLabel("Records selected (units as indicated above):"); label.setFont(GUIUtils.headerFont); header.add(BorderLayout.WEST, label); header.setBorder(GUIUtils.makeCompoundBorder(3, 0, 0, 0)); table = new SlammerTable(true, isSlammer); JPanel footer = new JPanel(new BorderLayout()); Box footerEast = new Box(BoxLayout.X_AXIS); footerEast.add(emptyTable); footerEast.add(deleteSelected); if(isSlammer) footerEast.add(next); footer.add(BorderLayout.EAST, footerEast); footer.add(BorderLayout.WEST, groupManage); searchTablePanel.add(BorderLayout.NORTH, header); searchTablePanel.add(BorderLayout.CENTER, table); searchTablePanel.add(BorderLayout.SOUTH, footer); return searchTablePanel; } public void actionPerformed(java.awt.event.ActionEvent e) { try { String command = e.getActionCommand(); if(command.equals("addRecord")) { if(eqList.getItemCount() == 0) return; String eq = eqList.getSelectedItem().toString(); String record = recordList.getSelectedItem().toString(); if(eq != null && record != null) { if(record == "Select all records") { Utils.getDB().runUpdate("update data set select2=1, analyze=1 where eq='" + eq + "' and select2=0"); table.setModel(SlammerTable.REFRESH); } else table.addRecord(eq, record, true); } updateSelectLabel(); } else if(command.equals("all")) { Utils.getDB().runUpdate("update data set analyze=1 where select2=1 and analyze=0"); table.setModel(SlammerTable.REFRESH); updateSelectLabel(); } else if(command.equals("clear")) { searchTA.setText(""); for(int i1 = textFields.length - 1; i1 >= 0; i1--) { for(int i2 = textFields[i1].length - 1; i2 >= 0; i2--) { textFields[i1][i2].setText(""); } } FocMechAll.setSelected(true); FocMechStrikeSlip.setSelected(false); FocMechReverse.setSelected(false); FocMechNormal.setSelected(false); FocMechObliqueReverse.setSelected(false); FocMechObliqueNormal.setSelected(false); SiteClassAll.setSelected(true); SiteClassA.setSelected(false); SiteClassB.setSelected(false); SiteClassC.setSelected(false); SiteClassD.setSelected(false); SiteClassE.setSelected(false); } else if(command.equals("deleteSelected")) { table.deleteSelected(); updateSelectLabel(); } else if(command.equals("empty")) { table.empty(); updateSelectLabel(); } else if(command.equals("eqListChange")) { if(Utils.locked()) return; Utils.updateRecordList(recordList, eqList.getSelectedItem().toString()); } else if(command.equals("focMechAll")) { if(FocMechAll.isSelected()) { FocMechStrikeSlip.setSelected(false); FocMechReverse.setSelected(false); FocMechNormal.setSelected(false); FocMechObliqueReverse.setSelected(false); FocMechObliqueNormal.setSelected(false); } } else if(command.equals("focMechOther")) { FocMechAll.setSelected(false); } else if(command.equals("groupmanage")) { groupFrame.setVisible(true); } else if(command.equals("next")) { parent.selectParameters(); } else if(command.equals("none")) { Utils.getDB().runUpdate("update data set analyze=0 where select2=1 and analyze=1"); table.setModel(SlammerTable.REFRESH); updateSelectLabel(); } else if(command.equals("search")) { String where = ""; String lefts, rights; Double left = null,right = null; for(int i = 0; i < textFields.length; i++) { left = null; right = null; lefts = textFields[i][0].getText().trim(); if(!lefts.equals("")) { - left = (Double)Utils.checkNum(lefts, searchList[i][0] + " greater than side", null, false, null, new Double(0), true, null, false); + left = (Double)Utils.checkNum(lefts, searchList[i][2] + " greater than side", null, false, null, new Double(0), true, null, false); if(left == null) return; } rights = textFields[i][1].getText().trim(); if(!rights.equals("")) { - right = (Double)Utils.checkNum(rights, searchList[i][0] + " less than side", null, false, null, new Double(0), false, null, false); + right = (Double)Utils.checkNum(rights, searchList[i][2] + " less than side", null, false, null, new Double(0), false, null, false); if(right == null) return; } if(left != null && right != null) { - if(Utils.checkNum(lefts, searchList[i][0] + " greater than side", right, true, "less than side", null, false, null, false) == null) return; + if(Utils.checkNum(lefts, searchList[i][2] + " greater than side", right, true, "less than side", null, false, null, false) == null) return; } if(left != null) where += "and " + searchList[i][1] + ">=" + lefts + " "; if(right != null) where += "and " + searchList[i][1] + "<=" + rights + " "; } String FocMechWhere = ""; String dbname = SlammerTable.fieldArray[SlammerTable.rowFocMech][SlammerTable.colDBName].toString(); FocMechWhere += makeCheckBoxString(FocMechWhere, dbname, Integer.toString(SlammerTable.FMStrikeSlip), FocMechStrikeSlip); FocMechWhere += makeCheckBoxString(FocMechWhere, dbname, Integer.toString(SlammerTable.FMReverse), FocMechReverse); FocMechWhere += makeCheckBoxString(FocMechWhere, dbname, Integer.toString(SlammerTable.FMNormal), FocMechNormal); FocMechWhere += makeCheckBoxString(FocMechWhere, dbname, Integer.toString(SlammerTable.FMObliqueReverse), FocMechObliqueReverse); FocMechWhere += makeCheckBoxString(FocMechWhere, dbname, Integer.toString(SlammerTable.FMObliqueNormal), FocMechObliqueNormal); if(FocMechWhere.equals("")) FocMechAll.setSelected(true); if(FocMechAll.isSelected()) FocMechWhere = ""; String SiteClassWhere = ""; dbname = SlammerTable.fieldArray[SlammerTable.rowSiteClass][SlammerTable.colDBName].toString(); SiteClassWhere += makeCheckBoxString(SiteClassWhere, dbname, Integer.toString(SlammerTable.SCA), SiteClassA); SiteClassWhere += makeCheckBoxString(SiteClassWhere, dbname, Integer.toString(SlammerTable.SCB), SiteClassB); SiteClassWhere += makeCheckBoxString(SiteClassWhere, dbname, Integer.toString(SlammerTable.SCC), SiteClassC); SiteClassWhere += makeCheckBoxString(SiteClassWhere, dbname, Integer.toString(SlammerTable.SCD), SiteClassD); SiteClassWhere += makeCheckBoxString(SiteClassWhere, dbname, Integer.toString(SlammerTable.SCE), SiteClassE); if(SiteClassWhere.equals("")) SiteClassAll.setSelected(true); if(SiteClassAll.isSelected()) SiteClassWhere = ""; where += fixCheckBoxWhere(FocMechWhere, SiteClassWhere); if(!where.equals("")) { where = "where " + where.substring(4); try { int result = Utils.getDB().runUpdate("update data set select2=1, analyze=1 " + where); if(result == 0) { searchTA.setText("Search complete. No records found."); return; } else { searchTA.setText("Search complete. " + result + " records found."); table.setModel(SlammerTable.REFRESH); updateSelectLabel(); } } catch(Exception ex) { Utils.catchException(ex); } } else { searchTA.setText("No search parameters defined: nothing to search for."); } } else if(command.equals("SiteClassAll")) { if(SiteClassAll.isSelected()) { SiteClassA.setSelected(false); SiteClassB.setSelected(false); SiteClassC.setSelected(false); SiteClassD.setSelected(false); SiteClassE.setSelected(false); } } else if(command.equals("siteClassOther")) { SiteClassAll.setSelected(false); } } catch (Exception ex) { Utils.catchException(ex); } } public void tableChanged(TableModelEvent e) { int row = e.getFirstRow(); int column = e.getColumn(); SlammerTableModel model = table.getModel(); if(model.isCellEditable(row, column) == false) return; try { Utils.getDB().set( model.getValueAt(row, 0).toString(), model.getValueAt(row, 1).toString(), ("analyze=" + (model.getValueAt(row, column).toString().equals("true") ? "1" : "0")) ); updateSelectLabel(); } catch(Exception ex) { Utils.catchException(ex); } } private String makeCheckBoxString(String append, String colName, String value, JCheckBox box) { String ret = ""; if(box.isSelected() == true) { if(append.equals("") == false) ret = "or "; ret += colName + "=" + value + " "; } return ret; } private String fixCheckBoxWhere(String one, String two) { boolean oneb = (one.equals("") ? true : false); boolean twob = (two.equals("") ? true : false); if(oneb && twob) return ""; if(oneb) return ("and ( " + two + ") "); if(twob) return ("and ( " + one + ") "); return ("and ( " + one + ") and ( " + two + ") "); } public void updateSelectLabel() throws Exception { Object[][] ret1 = Utils.getDB().runQuery("select count(*) from data where select2=1 and analyze=1"); Object[][] ret2 = Utils.getDB().runQuery("select count(*) from data where select2=1"); if(ret1 == null) ret1 = new Object[][]{{null, "0"}}; if(ret2 == null) ret2 = new Object[][]{{null, "0"}}; String selectText; if(isSlammer) selectText = ret1[1][0].toString() + " of " + ret2[1][0].toString() + " records selected for analysis"; else selectText = ret2[1][0].toString() + " records"; selectLabel.setText(selectText); } } diff --git a/programs/slammer/gui/SlammerTable.java b/programs/slammer/gui/SlammerTable.java index eed5b8c9..8d584cff 100644 --- a/programs/slammer/gui/SlammerTable.java +++ b/programs/slammer/gui/SlammerTable.java @@ -1,251 +1,252 @@ /* This file is in the public domain. */ package slammer.gui; import java.sql.*; import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.util.ArrayList; import slammer.*; class SlammerTable extends JPanel implements ActionListener, SlammerTableInterface { SlammerTableModel model; JTable table; boolean selectTable; String selectStr; String[] sortList; JComboBox primarySort; JComboBox secondarySort; JComboBox order = new JComboBox(); JRadioButton recordButton = new JRadioButton("Records", true); JRadioButton stationButton = new JRadioButton("Stations"); ButtonGroup displayGroup = new ButtonGroup(); /* selectTable determines if this is the table from the select records page, or * from the records manager page. If selectTable is false, the records manager * page is used. */ public SlammerTable(boolean selectTable, boolean isSlammer) throws Exception { sortList = getSortList(); primarySort = new JComboBox(sortList); secondarySort = new JComboBox(sortList); secondarySort.setSelectedIndex(1); // station this.selectTable = selectTable; selectStr = "select" + (selectTable ? 2 : 1); primarySort.setActionCommand("sort"); primarySort.addActionListener(this); secondarySort.setActionCommand("sort"); secondarySort.addActionListener(this); order.addItem("A/A"); order.addItem("A/D"); order.addItem("D/A"); order.addItem("D/D"); order.setActionCommand("sort"); order.addActionListener(this); model = new SlammerTableModel(selectTable, isSlammer, primarySort, secondarySort, order); table = new JTable(model); recordButton.setActionCommand("record"); recordButton.addActionListener(this); stationButton.setActionCommand("station"); stationButton.addActionListener(this); displayGroup.add(recordButton); displayGroup.add(stationButton); setLayout(new BorderLayout()); add(BorderLayout.CENTER, new JScrollPane(table)); JPanel north = new JPanel(new BorderLayout()); ArrayList west = new ArrayList(); west.add(new JLabel("Sort by ")); west.add(primarySort); west.add(new JLabel(" then ")); west.add(secondarySort); west.add(order); north.add(BorderLayout.WEST, GUIUtils.makeRecursiveLayoutRight(west)); ArrayList east = new ArrayList(); east.add(new JLabel("Display properties of: ")); east.add(recordButton); east.add(stationButton); north.add(BorderLayout.EAST, GUIUtils.makeRecursiveLayoutRight(east)); add(BorderLayout.NORTH, north); } private String[] getSortList() { ArrayList list = new ArrayList(fieldArray.length); for(int i = 0; i < fieldArray.length; i++) if(fieldArray[i][colSortField] == Boolean.TRUE) list.add(fieldArray[i][colDispName]); String[] slist = new String[list.size()]; for(int i = 0; i < list.size(); i++) slist[i] = list.get(i).toString(); return slist; } public void setModel(int modelint) throws Exception { model.setModel(modelint); } public void deleteSelected() throws Exception { deleteSelected(false); } public void deleteSelected(boolean fromDB) throws Exception { int[] rows = table.getSelectedRows(); Object[][] res; String eq, record; for(int i = rows.length - 1; i >= 0; i--) { eq = model.getValueAt(rows[i], 0).toString(); record = model.getValueAt(rows[i], 1).toString(); res = Utils.getDB().runQuery("select change from data where eq='" + eq + "' and record='" + record + "'"); if(fromDB && (res == null || res.length <= 1)) continue; set(rows[i], selectStr + "=0"); if(fromDB) Utils.getDB().runUpdate("delete from data where eq='" + eq + "' and record='" + record + "'"); } model.setModel(REFRESH); if(fromDB) Utils.updateEQLists(); } public void empty() throws Exception { Utils.getDB().runUpdate("update data set " + selectStr + "=0 where " + selectStr + "=1"); model.setModel(REFRESH); } private void set(int row, String value) throws Exception { Utils.getDB().set( model.getValueAt(row, 0).toString(), model.getValueAt(row, 1).toString(), value ); } public void addRecord(String eq, String record, boolean setAnalyze) throws Exception { String set = selectStr + "=1"; if(setAnalyze) set += ", analyze=1"; Utils.getDB().set(eq, record, set); model.setModel(REFRESH); } public void addRecord(String eq, String record) throws Exception { addRecord(eq, record, false); } public void actionPerformed(java.awt.event.ActionEvent e) { try { String command = e.getActionCommand(); if(command.equals("record")) { model.setModel(RECORD); } else if(command.equals("sort")) { model.setModel(REFRESH); } else if(command.equals("station")) { model.setModel(STATION); } } catch(Exception ex) { Utils.catchException(ex); } } public static String[][] getSearchList() { ArrayList rows = new ArrayList(); for(int i = 0; i < fieldArray.length; i++) if(fieldArray[i][colSearchable] == Boolean.TRUE) rows.add(new Integer(i)); - String[][] list = new String[rows.size()][2]; + String[][] list = new String[rows.size()][3]; int num; for(int i = 0; rows.size() != 0; i++) { num = ((Integer)rows.remove(0)).intValue(); if(fieldArray[num][colSearchable] == Boolean.TRUE) { list[i][0] = makeUnitName(num); list[i][1] = fieldArray[num][colDBName].toString(); + list[i][2] = fieldArray[num][colDispName].toString(); } } return list; } public static String makeUnitName(int row) { String ret = "<html>" + fieldArray[row][colFieldName].toString(); if(fieldArray[row][colUnits].equals("") == false) ret += " (" + fieldArray[row][colUnits].toString() + ")"; ret += "</html>"; return ret; } public SlammerTableModel getModel() { return model; } public static String getColValue(int from, int to, String value) { for(int i = 0; i < fieldArray.length; i++) if(fieldArray[i][from].toString().equals(value)) return fieldArray[i][to].toString(); return null; } public static Object[] getColumnList(int col, int compareCol, int contain) { ArrayList v = new ArrayList(); for(int i = 0; i < fieldArray.length; i++) { if((contain & ((Integer)(fieldArray[i][compareCol])).intValue()) != 0) { v.add(fieldArray[i][col]); } } return v.toArray(); } public ListSelectionModel getSelectionModel() { return table.getSelectionModel(); } public int getSelectedRow() { return table.getSelectedRow(); } }
false
false
null
null
diff --git a/spring-social-facebook/src/main/java/org/springframework/social/facebook/api/MediaOperations.java b/spring-social-facebook/src/main/java/org/springframework/social/facebook/api/MediaOperations.java index c4c574ca..e531ca47 100644 --- a/spring-social-facebook/src/main/java/org/springframework/social/facebook/api/MediaOperations.java +++ b/spring-social-facebook/src/main/java/org/springframework/social/facebook/api/MediaOperations.java @@ -1,409 +1,399 @@ /* * Copyright 2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.social.facebook.api; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.Resource; import org.springframework.social.ApiException; import org.springframework.social.InsufficientPermissionException; import org.springframework.social.MissingAuthorizationException; /** * Defines operations for working with albums, photos, and videos. * @author Craig Walls */ public interface MediaOperations { /** * Retrieves a list of albums belonging to the authenticated user. * Requires "user_photos" or "friends_photos" permission. * @return a list {@link Album}s for the user, or an empty list if not available. * @throws ApiException if there is an error while communicating with Facebook. * @throws InsufficientPermissionException if the user has not granted "user_photos" or "friends_photos" permission. * @throws MissingAuthorizationException if FacebookTemplate was not created with an access token. */ PagedList<Album> getAlbums(); /** * Retrieves a list of albums belonging to the authenticated user. * Requires "user_photos" or "friends_photos" permission. * @param offset the offset into the list of albums * @param limit the maximum number of albums to return * @return a list {@link Album}s for the user, or an empty list if not available. * @throws ApiException if there is an error while communicating with Facebook. * @throws InsufficientPermissionException if the user has not granted "user_photos" or "friends_photos" permission. * @throws MissingAuthorizationException if FacebookTemplate was not created with an access token. * @deprecated Use {@link #getAlbums(PagingParameters)} instead. */ @Deprecated PagedList<Album> getAlbums(int offset, int limit); /** * Retrieves a list of albums belonging to the authenticated user. * Requires "user_photos" or "friends_photos" permission. * @param pagedListParameters the parameters defining the bounds of the list to return. * @return a list {@link Album}s for the user, or an empty list if not available. * @throws ApiException if there is an error while communicating with Facebook. * @throws InsufficientPermissionException if the user has not granted "user_photos" or "friends_photos" permission. * @throws MissingAuthorizationException if FacebookTemplate was not created with an access token. */ PagedList<Album> getAlbums(PagingParameters pagedListParameters); /** * Retrieves a list of albums belonging to a specific owner (user, page, etc). * Requires "user_photos" or "friends_photos" permission. * @param ownerId the album owner's ID * @return a list {@link Album}s for the user, or an empty list if not available. * @throws ApiException if there is an error while communicating with Facebook. * @throws InsufficientPermissionException if the user has not granted "user_photos" or "friends_photos" permission. - * @throws MissingAuthorizationException if FacebookTemplate was not created with an access token. */ PagedList<Album> getAlbums(String ownerId); /** * Retrieves a list of albums belonging to a specific owner (user, page, etc). * Requires "user_photos" or "friends_photos" permission. * @param ownerId the album owner's ID * @param offset the offset into the list of albums * @param limit the maximum number of albums to return * @return a list {@link Album}s for the user, or an empty list if not available. * @throws ApiException if there is an error while communicating with Facebook. * @throws InsufficientPermissionException if the user has not granted "user_photos" or "friends_photos" permission. - * @throws MissingAuthorizationException if FacebookTemplate was not created with an access token. * @deprecated Use {@link #getAlbums(String, PagingParameters)} instead */ @Deprecated PagedList<Album> getAlbums(String ownerId, int offset, int limit); /** * Retrieves a list of albums belonging to a specific owner (user, page, etc). * Requires "user_photos" or "friends_photos" permission. * @param ownerId the album owner's ID * @param pagedListParameters the parameters defining the bounds of the list to return. * @return a list {@link Album}s for the user, or an empty list if not available. * @throws ApiException if there is an error while communicating with Facebook. * @throws InsufficientPermissionException if the user has not granted "user_photos" or "friends_photos" permission. - * @throws MissingAuthorizationException if FacebookTemplate was not created with an access token. */ PagedList<Album> getAlbums(String ownerId, PagingParameters pagedListParameters); /** * Retrieves data for a specific album. * Requires "user_photos" or "friends_photos" permission if the album is not public. * @param albumId the album ID * @return the requested {@link Album} object. * @throws ApiException if there is an error while communicating with Facebook. * @throws InsufficientPermissionException if the album is not public and if the user has not granted "user_photos" or "friends_photos" permission. - * @throws MissingAuthorizationException if FacebookTemplate was not created with an access token. */ Album getAlbum(String albumId); /** * Creates a new photo album. * Requires "publish_stream" permission. * @param name the name of the album. * @param description the album's description. * @return the ID of the newly created album. * @throws ApiException if there is an error while communicating with Facebook. * @throws InsufficientPermissionException if the user has not granted "publish_stream" permission. * @throws MissingAuthorizationException if FacebookTemplate was not created with an access token. */ String createAlbum(String name, String description); /** * Retrieves an album's image as an array of bytes. Returns the image in Facebook's "normal" type. * Requires "user_photos" or "friends_photos" permission if the album is not public. * @param albumId the album ID * @return an array of bytes containing the album's image. * @throws ApiException if there is an error while communicating with Facebook. * @throws InsufficientPermissionException if the album is not public and if the user has not granted "user_photos" or "friends_photos" permission. */ byte[] getAlbumImage(String albumId); /** * Retrieves an album's image as an array of bytes. * Requires "user_photos" or "friends_photos" permission if the album is not public. * @param albumId the album ID * @param imageType the image type (eg., small, normal, large. square) * @return an array of bytes containing the album's image. * @throws ApiException if there is an error while communicating with Facebook. * @throws InsufficientPermissionException if the album is not public and if the user has not granted "user_photos" or "friends_photos" permission. * @throws MissingAuthorizationException if FacebookTemplate was not created with an access token. */ byte[] getAlbumImage(String albumId, ImageType imageType); /** * Retrieves data for up to 25 photos from a specific album or that a user is tagged in. * If the objectId parameter is the ID of an album, the photos returned are the photos from that album. * If the objectId parameter is the ID of a user, the photos returned are the photos that the user is tagged in. * Requires "user_photos" or "friends_photos" permission if the album is not public. * @param objectId either an album ID or a user ID * @return a list of {@link Photo}s in the specified album. * @throws ApiException if there is an error while communicating with Facebook. * @throws InsufficientPermissionException if the album is not public and if the user has not granted "user_photos" or "friends_photos" permission. - * @throws MissingAuthorizationException if FacebookTemplate was not created with an access token. */ PagedList<Photo> getPhotos(String objectId); /** * Retrieves photo data from a specific album or that a user is tagged in. * If the objectId parameter is the ID of an album, the photos returned are the photos from that album. * If the objectId parameter is the ID of a user, the photos returned are the photos that the user is tagged in. * Requires "user_photos" or "friends_photos" permission if the album is not public. * @param objectId either an album ID or a user ID * @param offset the offset into the list of photos * @param limit the maximum number of photos to return * @return a list of {@link Photo}s in the specified album. * @throws ApiException if there is an error while communicating with Facebook. * @throws InsufficientPermissionException if the album is not public and if the user has not granted "user_photos" or "friends_photos" permission. - * @throws MissingAuthorizationException if FacebookTemplate was not created with an access token. * @deprecated Use {@link #getPhotos(String, PagingParameters)} instead. */ @Deprecated PagedList<Photo> getPhotos(String objectId, int offset, int limit); /** * Retrieves photo data from a specific album or that a user is tagged in. * If the objectId parameter is the ID of an album, the photos returned are the photos from that album. * If the objectId parameter is the ID of a user, the photos returned are the photos that the user is tagged in. * Requires "user_photos" or "friends_photos" permission if the album is not public. * @param objectId either an album ID or a user ID * @param pagedListParameters the parameters defining the bounds of the list to return. * @return a list of {@link Photo}s in the specified album. * @throws ApiException if there is an error while communicating with Facebook. * @throws InsufficientPermissionException if the album is not public and if the user has not granted "user_photos" or "friends_photos" permission. - * @throws MissingAuthorizationException if FacebookTemplate was not created with an access token. */ PagedList<Photo> getPhotos(String objectId, PagingParameters pagedListParameters); /** * Retrieve data for a specified photo. * Requires "user_photos" or "friends_photos" permission if the photo is not public. * @param photoId the photo's ID * @return the requested {@link Photo} * @throws ApiException if there is an error while communicating with Facebook. * @throws InsufficientPermissionException if the photo is not public and if the user has not granted "user_photos" or "friends_photos" permission. - * @throws MissingAuthorizationException if FacebookTemplate was not created with an access token. */ Photo getPhoto(String photoId); /** * Retrieves a photo's image as an array of bytes. Returns the image in Facebook's "normal" type. * Requires "user_photos" or "friends_photos" permission if the photo is not public. * @param photoId the photo ID * @return an array of bytes containing the photo's image. * @throws ApiException if there is an error while communicating with Facebook. * @throws InsufficientPermissionException if the photo is not public and if the user has not granted "user_photos" or "friends_photos" permission. - * @throws MissingAuthorizationException if FacebookTemplate was not created with an access token. */ byte[] getPhotoImage(String photoId); /** * Retrieves a photo's image as an array of bytes. * Requires "user_photos" or "friends_photos" permission if the photo is not public. * @param photoId the photo ID * @param imageType the image type (eg., small, normal, large. square) * @return an array of bytes containing the photo's image. * @throws ApiException if there is an error while communicating with Facebook. * @throws InsufficientPermissionException if the photo is not public and if the user has not granted "user_photos" or "friends_photos" permission. - * @throws MissingAuthorizationException if FacebookTemplate was not created with an access token. */ byte[] getPhotoImage(String photoId, ImageType imageType); /** * Uploads a photo to an album created specifically for the application. * Requires "publish_stream" permission. * If no album exists for the application, it will be created. * @param photo A {@link Resource} for the photo data. The given Resource must implement the getFilename() method (such as {@link FileSystemResource} or {@link ClassPathResource}). * @return the ID of the photo. * @throws ApiException if there is an error while communicating with Facebook. * @throws InsufficientPermissionException if the user has not granted "publish_stream" permission. * @throws MissingAuthorizationException if FacebookTemplate was not created with an access token. */ String postPhoto(Resource photo); /** * Uploads a photo to an album created specifically for the application. * If no album exists for the application, it will be created. * Requires "publish_stream" permission. * @param photo A {@link Resource} for the photo data. The given Resource must implement the getFilename() method (such as {@link FileSystemResource} or {@link ClassPathResource}). * @param caption A caption describing the photo. * @return the ID of the photo. * @throws ApiException if there is an error while communicating with Facebook. * @throws InsufficientPermissionException if the user has not granted "publish_stream" permission. * @throws MissingAuthorizationException if FacebookTemplate was not created with an access token. */ String postPhoto(Resource photo, String caption); /** * Uploads a photo to a specific album. * Requires "publish_stream" permission. * @param albumId the ID of the album to upload the photo to. * @param photo A {@link Resource} for the photo data. The given Resource must implement the getFilename() method (such as {@link FileSystemResource} or {@link ClassPathResource}). * @return the ID of the photo. * @throws ApiException if there is an error while communicating with Facebook. * @throws InsufficientPermissionException if the user has not granted "publish_stream" permission. * @throws MissingAuthorizationException if FacebookTemplate was not created with an access token. */ String postPhoto(String albumId, Resource photo); /** * Uploads a photo to a specific album. * Requires "publish_stream" permission. * @param albumId the ID of the album to upload the photo to. * @param photo A {@link Resource} for the photo data. The given Resource must implement the getFilename() method (such as {@link FileSystemResource} or {@link ClassPathResource}). * @param caption A caption describing the photo. * @return the ID of the photo. * @throws ApiException if there is an error while communicating with Facebook. * @throws InsufficientPermissionException if the user has not granted "publish_stream" permission. * @throws MissingAuthorizationException if FacebookTemplate was not created with an access token. */ String postPhoto(String albumId, Resource photo, String caption); /** * Retrieves a list of up to 25 videos that the authenticated user is tagged in. * Requires "user_videos" permission. * @return a list of {@link Video} belonging to the authenticated user. * @throws ApiException if there is an error while communicating with Facebook. * @throws InsufficientPermissionException if the user has not granted "user_videos" permission. * @throws MissingAuthorizationException if FacebookTemplate was not created with an access token. */ PagedList<Video> getVideos(); /** * Retrieves a list of videos that the authenticated user is tagged in. * Requires "user_videos" permission. * @param offset the offset into the list of videos * @param limit the maximum number of videos to return * @return a list of {@link Video} belonging to the authenticated user. * @throws ApiException if there is an error while communicating with Facebook. * @throws InsufficientPermissionException if the user has not granted "user_videos" permission. * @throws MissingAuthorizationException if FacebookTemplate was not created with an access token. * @deprecated Use {@link #getVideos(PagingParameters)} instead. */ @Deprecated PagedList<Video> getVideos(int offset, int limit); /** * Retrieves a list of videos that the authenticated user is tagged in. * Requires "user_videos" permission. * @param pagedListParameters the parameters defining the bounds of the list to return. * @return a list of {@link Video} belonging to the authenticated user. * @throws ApiException if there is an error while communicating with Facebook. * @throws InsufficientPermissionException if the user has not granted "user_videos" permission. * @throws MissingAuthorizationException if FacebookTemplate was not created with an access token. */ PagedList<Video> getVideos(PagingParameters pagedListParameters); /** * Retrieves a list of up to 25 videos that a specified user is tagged in. * Requires "user_videos" or "friends_videos" permission. * @param userId the ID of the user who is tagged in the videos * @return a list of {@link Video} which the specified user is tagged in. * @throws ApiException if there is an error while communicating with Facebook. * @throws InsufficientPermissionException if the user has not granted "user_videos" or "friends_videos" permission. * @throws MissingAuthorizationException if FacebookTemplate was not created with an access token. */ PagedList<Video> getVideos(String userId); /** * Retrieves a list of videos that a specified user is tagged in. * Requires "user_videos" or "friends_videos" permission. * @param userId the ID of the user who is tagged in the videos * @param offset the offset into the list of videos * @param limit the maximum number of videos to return * @return a list of {@link Video} which the specified user is tagged in. * @throws ApiException if there is an error while communicating with Facebook. * @throws InsufficientPermissionException if the user has not granted "user_videos" or "friends_videos" permission. * @throws MissingAuthorizationException if FacebookTemplate was not created with an access token. * @deprecated Use {@link #getVideos(String, PagingParameters)} instead. */ @Deprecated PagedList<Video> getVideos(String userId, int offset, int limit); /** * Retrieves a list of videos that a specified user is tagged in. * Requires "user_videos" or "friends_videos" permission. * @param userId the ID of the user who is tagged in the videos * @param pagedListParameters the parameters defining the bounds of the list to return. * @return a list of {@link Video} which the specified user is tagged in. * @throws ApiException if there is an error while communicating with Facebook. * @throws InsufficientPermissionException if the user has not granted "user_videos" or "friends_videos" permission. * @throws MissingAuthorizationException if FacebookTemplate was not created with an access token. */ PagedList<Video> getVideos(String userId, PagingParameters pagedListParameters); /** * Retrieves data for a specific video. * Requires "user_videos" or "friends_videos" permission. * @param videoId the ID of the video. * @return the requested {@link Video} data. * @throws ApiException if there is an error while communicating with Facebook. * @throws InsufficientPermissionException if the user has not granted "user_videos" or "friends_videos" permission. * @throws MissingAuthorizationException if FacebookTemplate was not created with an access token. */ Video getVideo(String videoId); /** * Retrieves a video's image as an array of bytes. Returns the image in Facebook's "normal" type. * Requires "user_videos" or "friends_videos" permission. * @param videoId the video ID * @return an array of bytes containing the video's image. * @throws ApiException if there is an error while communicating with Facebook. * @throws InsufficientPermissionException if the user has not granted "user_videos" or "friends_videos" permission. * @throws MissingAuthorizationException if FacebookTemplate was not created with an access token. */ byte[] getVideoImage(String videoId); /** * Retrieves a video's image as an array of bytes. * Requires "user_videos" or "friends_videos" permission. * @param videoId the video ID * @param imageType the image type (eg., small, normal, large. square) * @return an array of bytes containing the video's image. * @throws ApiException if there is an error while communicating with Facebook. * @throws InsufficientPermissionException if the user has not granted "user_videos" or "friends_videos" permission. * @throws MissingAuthorizationException if FacebookTemplate was not created with an access token. */ byte[] getVideoImage(String videoId, ImageType imageType); /** * Uploads a video for the authenticated user. * Requires "publish_stream" permission. * Note that the video will not be immediately available after uploading, as Facebook performs some post-upload processing on the video. * @param video A {@link Resource} for the video data. The given Resource must implement the getFilename() method (such as {@link FileSystemResource} or {@link ClassPathResource}). * @return the ID of the video. * @throws ApiException if there is an error while communicating with Facebook. * @throws InsufficientPermissionException if the user has not granted "publish_stream" permission. * @throws MissingAuthorizationException if FacebookTemplate was not created with an access token. */ String postVideo(Resource video); /** * Uploads a video for the authenticated user. * Note that the video will not be immediately available after uploading, as Facebook performs some post-upload processing on the video. * Requires "publish_stream" permission. * @param video A {@link Resource} for the video data. The given Resource must implement the getFilename() method (such as {@link FileSystemResource} or {@link ClassPathResource}). * @return the ID of the video. * @throws ApiException if there is an error while communicating with Facebook. * @throws InsufficientPermissionException if the user has not granted "publish_stream" permission. * @throws MissingAuthorizationException if FacebookTemplate was not created with an access token. */ String postVideo(Resource video, String title, String description); }
false
false
null
null
diff --git a/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/PinListEntry.java b/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/PinListEntry.java index 748606bdf..c05a391a0 100644 --- a/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/PinListEntry.java +++ b/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/PinListEntry.java @@ -1,155 +1,155 @@ /* * Copyright (C) 2012 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.harmony.xnet.provider.jsse; import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.cert.X509Certificate; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import libcore.io.EventLogger; /** * This class represents a single entry in the pin file. */ // public for testing by CertPinManagerTest public class PinListEntry { /** The Common Name (CN) as used on the SSL certificate */ private final String cn; /** * Determines whether a failed match here will prevent the chain from being accepted. If true, * an unpinned chain will log and cause a match failure. If false, it will merely log. */ private final boolean enforcing; private final Set<String> pinnedFingerprints = new HashSet<String>(); private static final boolean DEBUG = false; private final TrustedCertificateStore certStore; public String getCommonName() { return cn; } public boolean getEnforcing() { return enforcing; } public PinListEntry(String entry, TrustedCertificateStore store) throws PinEntryException { if (entry == null) { throw new NullPointerException("entry == null"); } - if (store == null) { - throw new NullPointerException("store == null"); - } certStore = store; // Examples: // *.google.com=true|34c8a0d...9e04ca05f,9e04ca05f...34c8a0d // *.android.com=true|ca05f...8a0d34c // clients.google.com=false|9e04ca05f...34c8a0d,34c8a0d...9e04ca05f String[] values = entry.split("[=,|]"); // entry must have a CN, an enforcement value, and at least one pin if (values.length < 3) { throw new PinEntryException("Received malformed pin entry"); } // get the cn cn = values[0]; // is there more validation we can do here? enforcing = enforcementValueFromString(values[1]); // the remainder should be pins addPins(Arrays.copyOfRange(values, 2, values.length)); } private static boolean enforcementValueFromString(String val) throws PinEntryException { if (val.equals("true")) { return true; } else if (val.equals("false")) { return false; } else { throw new PinEntryException("Enforcement status is not a valid value"); } } /** * Checks the given chain against the pin list corresponding to this entry. * * If the pin list does not contain the required certs and the enforcing field is true then * this returns true, indicating a verification error. Otherwise, it returns false and * verification should proceed. */ public boolean chainIsNotPinned(List<X509Certificate> chain) { for (X509Certificate cert : chain) { String fingerprint = getFingerprint(cert); if (pinnedFingerprints.contains(fingerprint)) { return false; } } logPinFailure(chain); return enforcing; } private static String getFingerprint(X509Certificate cert) { try { MessageDigest dgst = MessageDigest.getInstance("SHA512"); byte[] encoded = cert.getPublicKey().getEncoded(); byte[] fingerprint = dgst.digest(encoded); return IntegralToString.bytesToHexString(fingerprint, false); } catch (NoSuchAlgorithmException e) { throw new AssertionError(e); } } private void addPins(String[] pins) { for (String pin : pins) { validatePin(pin); } Collections.addAll(pinnedFingerprints, pins); } private static void validatePin(String pin) { // check to make sure the length is correct if (pin.length() != 128) { throw new IllegalArgumentException("Pin is not a valid length"); } // check to make sure that it's a valid hex string try { new BigInteger(pin, 16); } catch (NumberFormatException e) { throw new IllegalArgumentException("Pin is not a valid hex string", e); } } private boolean chainContainsUserCert(List<X509Certificate> chain) { + if (certStore == null) { + return false; + } for (X509Certificate cert : chain) { if (certStore.isUserAddedCertificate(cert)) { return true; } } return false; } private void logPinFailure(List<X509Certificate> chain) { PinFailureLogger.log(cn, chainContainsUserCert(chain), enforcing, chain); } }
false
false
null
null
diff --git a/de.neo.remote.mobile/src/de/neo/remote/mobile/util/PlayTatortTask.java b/de.neo.remote.mobile/src/de/neo/remote/mobile/util/PlayTatortTask.java index 7582c75..c40f8d3 100644 --- a/de.neo.remote.mobile/src/de/neo/remote/mobile/util/PlayTatortTask.java +++ b/de.neo.remote.mobile/src/de/neo/remote/mobile/util/PlayTatortTask.java @@ -1,55 +1,55 @@ package de.neo.remote.mobile.util; import android.os.AsyncTask; import android.widget.Toast; import de.neo.remote.mediaserver.api.IPlayer; import de.neo.remote.mobile.activities.BrowserBase; import de.neo.remote.mobile.services.PlayerBinder; public class PlayTatortTask extends AsyncTask<String, Integer, String> { private BrowserBase browserBase; private String tatortURL; private PlayerBinder binder; public PlayTatortTask(BrowserBase browserBase, String tatortURL, PlayerBinder binder) { this.tatortURL = tatortURL; this.browserBase = browserBase; this.binder = binder; } @Override protected void onPreExecute() { super.onPreExecute(); browserBase.startProgress("Start ARD stream", tatortURL); } @Override protected void onPostExecute(String result) { super.onPostExecute(result); browserBase.dismissProgress(); if (result != null) Toast.makeText(browserBase, "Error streaming ARD: " + result, Toast.LENGTH_SHORT).show(); } @Override protected String doInBackground(String... params) { try { if (binder == null) throw new Exception("not bindet"); if (binder.getLatestMediaServer() == null) throw new Exception("no mediaserver selected"); IPlayer player = binder.getLatestMediaServer().player; if (player != null) { player.playFromArdMediathek(tatortURL); } else throw new Exception("no player selected"); } catch (Exception e) { - return e.getMessage(); + return e.getClass().getSimpleName() + ": " + e.getMessage(); } return null; } } diff --git a/de.neo.remote.mobile/src/de/neo/remote/mobile/util/PlayYoutubeTask.java b/de.neo.remote.mobile/src/de/neo/remote/mobile/util/PlayYoutubeTask.java index b46eeb1..bfa7dd1 100644 --- a/de.neo.remote.mobile/src/de/neo/remote/mobile/util/PlayYoutubeTask.java +++ b/de.neo.remote.mobile/src/de/neo/remote/mobile/util/PlayYoutubeTask.java @@ -1,55 +1,55 @@ package de.neo.remote.mobile.util; import android.os.AsyncTask; import android.widget.Toast; import de.neo.remote.mediaserver.api.IPlayer; import de.neo.remote.mobile.activities.BrowserBase; import de.neo.remote.mobile.services.PlayerBinder; public class PlayYoutubeTask extends AsyncTask<String, Integer, String> { private BrowserBase browserBase; private String youtubeURL; private PlayerBinder binder; public PlayYoutubeTask(BrowserBase browserBase, String youtubeURL, PlayerBinder binder) { this.youtubeURL = youtubeURL; this.browserBase = browserBase; this.binder = binder; } @Override protected void onPreExecute() { super.onPreExecute(); browserBase.startProgress("Start youtube stream", youtubeURL); } @Override protected void onPostExecute(String result) { super.onPostExecute(result); browserBase.dismissProgress(); if (result != null) Toast.makeText(browserBase, "Error streaming youtube: " + result, Toast.LENGTH_SHORT).show(); } @Override protected String doInBackground(String... params) { try { if (binder == null) throw new Exception("not bindet"); if (binder.getLatestMediaServer() == null) throw new Exception("no mediaserver selected"); IPlayer player = binder.getLatestMediaServer().player; if (player != null) { player.playFromYoutube(youtubeURL); } else throw new Exception("no player selected"); } catch (Exception e) { - return e.getMessage(); + return e.getClass().getSimpleName() + ": " + e.getMessage(); } return null; } }
false
false
null
null
diff --git a/src/java/com/sapienter/jbilling/server/pluggableTask/BasicLineTotalTask.java b/src/java/com/sapienter/jbilling/server/pluggableTask/BasicLineTotalTask.java index 6ca2b614..c56648a5 100644 --- a/src/java/com/sapienter/jbilling/server/pluggableTask/BasicLineTotalTask.java +++ b/src/java/com/sapienter/jbilling/server/pluggableTask/BasicLineTotalTask.java @@ -1,258 +1,258 @@ /* * JBILLING CONFIDENTIAL * _____________________ * * [2003] - [2012] Enterprise jBilling Software Ltd. * All Rights Reserved. * * NOTICE: All information contained herein is, and remains * the property of Enterprise jBilling Software. * The intellectual and technical concepts contained * herein are proprietary to Enterprise jBilling Software * and are protected by trade secret or copyright law. * Dissemination of this information or reproduction of this material * is strictly forbidden. */ package com.sapienter.jbilling.server.pluggableTask; import java.math.BigDecimal; import java.util.Arrays; import java.util.List; import java.util.Set; import com.sapienter.jbilling.server.item.db.ItemTypeDTO; import com.sapienter.jbilling.server.order.OrderLineComparator; import org.apache.log4j.Logger; import com.sapienter.jbilling.server.item.ItemDecimalsException; import com.sapienter.jbilling.server.item.db.ItemDAS; import com.sapienter.jbilling.server.item.db.ItemDTO; import com.sapienter.jbilling.server.order.db.OrderDTO; import com.sapienter.jbilling.server.order.db.OrderLineDTO; import com.sapienter.jbilling.server.util.Constants; /** * Basic tasks that takes the quantity and multiplies it by the price to * get the lines total. It also updates the order total with the addition * of all line totals * */ public class BasicLineTotalTask extends PluggableTask implements OrderProcessingTask { private static final Logger LOG = Logger.getLogger(BasicLineTotalTask.class); private static final BigDecimal ONE_HUNDRED = new BigDecimal("100.00"); public void doProcessing(OrderDTO order) throws TaskException { validateLinesQuantity(order.getLines()); clearLineTotals(order.getLines()); ItemDAS itemDas = new ItemDAS(); /* Calculate non-percentage items, calculating price as $/unit */ for (OrderLineDTO line : order.getLines()) { if (line.getDeleted() == 1 || line.getTotalReadOnly()) continue; // calculate line total ItemDTO item = itemDas.find(line.getItemId()); if (item != null && item.getPercentage() == null) { line.setAmount(line.getQuantity().multiply(line.getPrice())); LOG.debug("normal line total: " + line.getQuantity() + " x " + line.getPrice() + " = " + line.getAmount()); } } /* Calculate non-tax percentage items (fees). Percentages are not compounded and charged only on normal item lines */ for (OrderLineDTO line : order.getLines()) { if (line.getDeleted() == 1 || line.getTotalReadOnly()) continue; // calculate line total ItemDTO percentageItem = itemDas.find(line.getItemId()); if (percentageItem != null && percentageItem.getPercentage() != null && !line.getTypeId().equals(Constants.ORDER_LINE_TYPE_TAX)) { // sum of applicable item charges * percentage BigDecimal total = getTotalForPercentage(order.getLines(), percentageItem.getExcludedTypes()); - line.setAmount(line.getPrice().divide(ONE_HUNDRED, Constants.BIGDECIMAL_ROUND).multiply(total)); + line.setAmount(line.getPrice().divide(ONE_HUNDRED, Constants.BIGDECIMAL_SCALE, Constants.BIGDECIMAL_ROUND).multiply(total)); LOG.debug("percentage line total: %" + line.getPrice() + "; " + "( " + line.getPrice() + " / 100 ) x " + total + " = " + line.getAmount()); } } /* Calculate tax percentage items. Taxes are not compounded and charged on all normal item lines and non-tax percentage amounts (fees). */ for (OrderLineDTO line : order.getLines()) { if (line.getDeleted() == 1 || line.getTotalReadOnly()) continue; // calculate line total ItemDTO taxItem = itemDas.find(line.getItemId()); if (taxItem != null && taxItem.getPercentage() != null && line.getTypeId().equals(Constants.ORDER_LINE_TYPE_TAX)) { // sum of applicable item charges + fees * percentage BigDecimal total = getTotalForTax(order.getLines(), taxItem.getExcludedTypes()); - line.setAmount(line.getPrice().divide(ONE_HUNDRED, BigDecimal.ROUND_HALF_EVEN).multiply(total)); + line.setAmount(line.getPrice().divide(ONE_HUNDRED, Constants.BIGDECIMAL_SCALE, BigDecimal.ROUND_HALF_EVEN).multiply(total)); LOG.debug("tax line total: %" + line.getPrice() + "; " + "( " + line.getPrice() + " / 100 ) x " + total + " = " + line.getAmount()); } } // order total order.setTotal(getTotal(order.getLines())); LOG.debug("Order total = " + order.getTotal()); } /** * Returns the sum total amount of all lines with items that do NOT belong to the given excluded type list. * * This total only includes normal item lines and not tax or penalty lines. * * @param lines order lines * @param excludedTypes excluded item types * @return total amount */ public BigDecimal getTotalForPercentage(List<OrderLineDTO> lines, Set<ItemTypeDTO> excludedTypes) { BigDecimal total = BigDecimal.ZERO; for (OrderLineDTO line : lines) { if (line.getDeleted() == 1) continue; // add line total for non-percentage & non-tax lines if (line.getItem().getPercentage() == null && line.getTypeId().equals(Constants.ORDER_LINE_TYPE_ITEM)) { // add if type is not in the excluded list if (!isItemExcluded(line.getItem(), excludedTypes)) { total = total.add(line.getAmount()); } else { LOG.debug("item " + line.getItem().getId() + " excluded from percentage."); } } } LOG.debug("total amount applicable for percentage: " + total); return total; } /** * Returns the sum total amount of all lines with items that do NOT belong to the given excluded type list. * * This total includes all non tax lines (i.e., normal items, percentage fees and penalty lines). * * @param lines order lines * @param excludedTypes excluded item types * @return total amount */ public BigDecimal getTotalForTax(List<OrderLineDTO> lines, Set<ItemTypeDTO> excludedTypes) { BigDecimal total = BigDecimal.ZERO; for (OrderLineDTO line : lines) { if (line.getDeleted() == 1) continue; // add line total for all non-tax items if (!line.getTypeId().equals(Constants.ORDER_LINE_TYPE_TAX)) { // add if type is not in the excluded list if (!isItemExcluded(line.getItem(), excludedTypes)) { total = total.add(line.getAmount()); } else { LOG.debug("item " + line.getItem().getId() + " excluded from tax."); } } } LOG.debug("total amount applicable for tax: " + total); return total; } /** * Returns true if the item is in the excluded item type list. * * @param item item to check * @param excludedTypes list of excluded item types * @return true if item is excluded, false if not */ private boolean isItemExcluded(ItemDTO item, Set<ItemTypeDTO> excludedTypes) { for (ItemTypeDTO excludedType : excludedTypes) { for (ItemTypeDTO itemType : item.getItemTypes()) { if (itemType.getId() == excludedType.getId()) { return true; } } } return false; } /** * Returns the total of all given order lines. * * @param lines order lines * @return total amount */ public BigDecimal getTotal(List<OrderLineDTO> lines) { BigDecimal total = BigDecimal.ZERO; for (OrderLineDTO line : lines) { if (line.getDeleted() == 1) continue; // add total total = total.add(line.getAmount()); } return total; } /** * Sets all order line amounts to null. * * @param lines order lines to clear */ public void clearLineTotals(List<OrderLineDTO> lines) { for (OrderLineDTO line : lines) { if (line.getDeleted() == 1) continue; // clear amount line.setAmount(null); } } /** * Validates that only order line items with {@link ItemDTO#hasDecimals} set to true has * a decimal quantity. * * @param lines order lines to validate * @throws TaskException thrown if an order line has decimals without the item hasDecimals flag */ public void validateLinesQuantity(List<OrderLineDTO> lines) throws TaskException { for (OrderLineDTO line : lines) { if (line.getDeleted() == 1) continue; // validate line quantity if (line.getItem() != null && line.getQuantity().remainder(Constants.BIGDECIMAL_ONE).compareTo(BigDecimal.ZERO) != 0.0 && line.getItem().getHasDecimals() == 0) { throw new TaskException(new ItemDecimalsException("Item does not allow Decimals")); } } } }
false
true
public void doProcessing(OrderDTO order) throws TaskException { validateLinesQuantity(order.getLines()); clearLineTotals(order.getLines()); ItemDAS itemDas = new ItemDAS(); /* Calculate non-percentage items, calculating price as $/unit */ for (OrderLineDTO line : order.getLines()) { if (line.getDeleted() == 1 || line.getTotalReadOnly()) continue; // calculate line total ItemDTO item = itemDas.find(line.getItemId()); if (item != null && item.getPercentage() == null) { line.setAmount(line.getQuantity().multiply(line.getPrice())); LOG.debug("normal line total: " + line.getQuantity() + " x " + line.getPrice() + " = " + line.getAmount()); } } /* Calculate non-tax percentage items (fees). Percentages are not compounded and charged only on normal item lines */ for (OrderLineDTO line : order.getLines()) { if (line.getDeleted() == 1 || line.getTotalReadOnly()) continue; // calculate line total ItemDTO percentageItem = itemDas.find(line.getItemId()); if (percentageItem != null && percentageItem.getPercentage() != null && !line.getTypeId().equals(Constants.ORDER_LINE_TYPE_TAX)) { // sum of applicable item charges * percentage BigDecimal total = getTotalForPercentage(order.getLines(), percentageItem.getExcludedTypes()); line.setAmount(line.getPrice().divide(ONE_HUNDRED, Constants.BIGDECIMAL_ROUND).multiply(total)); LOG.debug("percentage line total: %" + line.getPrice() + "; " + "( " + line.getPrice() + " / 100 ) x " + total + " = " + line.getAmount()); } } /* Calculate tax percentage items. Taxes are not compounded and charged on all normal item lines and non-tax percentage amounts (fees). */ for (OrderLineDTO line : order.getLines()) { if (line.getDeleted() == 1 || line.getTotalReadOnly()) continue; // calculate line total ItemDTO taxItem = itemDas.find(line.getItemId()); if (taxItem != null && taxItem.getPercentage() != null && line.getTypeId().equals(Constants.ORDER_LINE_TYPE_TAX)) { // sum of applicable item charges + fees * percentage BigDecimal total = getTotalForTax(order.getLines(), taxItem.getExcludedTypes()); line.setAmount(line.getPrice().divide(ONE_HUNDRED, BigDecimal.ROUND_HALF_EVEN).multiply(total)); LOG.debug("tax line total: %" + line.getPrice() + "; " + "( " + line.getPrice() + " / 100 ) x " + total + " = " + line.getAmount()); } } // order total order.setTotal(getTotal(order.getLines())); LOG.debug("Order total = " + order.getTotal()); }
public void doProcessing(OrderDTO order) throws TaskException { validateLinesQuantity(order.getLines()); clearLineTotals(order.getLines()); ItemDAS itemDas = new ItemDAS(); /* Calculate non-percentage items, calculating price as $/unit */ for (OrderLineDTO line : order.getLines()) { if (line.getDeleted() == 1 || line.getTotalReadOnly()) continue; // calculate line total ItemDTO item = itemDas.find(line.getItemId()); if (item != null && item.getPercentage() == null) { line.setAmount(line.getQuantity().multiply(line.getPrice())); LOG.debug("normal line total: " + line.getQuantity() + " x " + line.getPrice() + " = " + line.getAmount()); } } /* Calculate non-tax percentage items (fees). Percentages are not compounded and charged only on normal item lines */ for (OrderLineDTO line : order.getLines()) { if (line.getDeleted() == 1 || line.getTotalReadOnly()) continue; // calculate line total ItemDTO percentageItem = itemDas.find(line.getItemId()); if (percentageItem != null && percentageItem.getPercentage() != null && !line.getTypeId().equals(Constants.ORDER_LINE_TYPE_TAX)) { // sum of applicable item charges * percentage BigDecimal total = getTotalForPercentage(order.getLines(), percentageItem.getExcludedTypes()); line.setAmount(line.getPrice().divide(ONE_HUNDRED, Constants.BIGDECIMAL_SCALE, Constants.BIGDECIMAL_ROUND).multiply(total)); LOG.debug("percentage line total: %" + line.getPrice() + "; " + "( " + line.getPrice() + " / 100 ) x " + total + " = " + line.getAmount()); } } /* Calculate tax percentage items. Taxes are not compounded and charged on all normal item lines and non-tax percentage amounts (fees). */ for (OrderLineDTO line : order.getLines()) { if (line.getDeleted() == 1 || line.getTotalReadOnly()) continue; // calculate line total ItemDTO taxItem = itemDas.find(line.getItemId()); if (taxItem != null && taxItem.getPercentage() != null && line.getTypeId().equals(Constants.ORDER_LINE_TYPE_TAX)) { // sum of applicable item charges + fees * percentage BigDecimal total = getTotalForTax(order.getLines(), taxItem.getExcludedTypes()); line.setAmount(line.getPrice().divide(ONE_HUNDRED, Constants.BIGDECIMAL_SCALE, BigDecimal.ROUND_HALF_EVEN).multiply(total)); LOG.debug("tax line total: %" + line.getPrice() + "; " + "( " + line.getPrice() + " / 100 ) x " + total + " = " + line.getAmount()); } } // order total order.setTotal(getTotal(order.getLines())); LOG.debug("Order total = " + order.getTotal()); }
diff --git a/src/com/axelby/podax/GPodderSyncService.java b/src/com/axelby/podax/GPodderSyncService.java index 2f5c1a5..8967718 100644 --- a/src/com/axelby/podax/GPodderSyncService.java +++ b/src/com/axelby/podax/GPodderSyncService.java @@ -1,102 +1,107 @@ package com.axelby.podax; import android.accounts.Account; import android.accounts.AccountManager; import android.app.Service; import android.content.AbstractThreadedSyncAdapter; import android.content.ContentProviderClient; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.SyncResult; import android.database.Cursor; +import android.database.sqlite.SQLiteConstraintException; import android.os.Bundle; import android.os.IBinder; import com.axelby.podax.GPodderClient.Changes; public class GPodderSyncService extends Service { private static final Object _syncAdapterLock = new Object(); private static GPodderSyncAdapter _syncAdapter = null; @Override public void onCreate() { synchronized (_syncAdapterLock) { if (_syncAdapter == null) { _syncAdapter = new GPodderSyncAdapter(getApplicationContext(), true); } } } @Override public IBinder onBind(Intent intent) { return _syncAdapter.getSyncAdapterBinder(); } private static class GPodderSyncAdapter extends AbstractThreadedSyncAdapter { private Context _context; public GPodderSyncAdapter(Context context, boolean autoInitialize) { super(context, autoInitialize); _context = context; } @Override public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) { AccountManager accountManager = AccountManager.get(_context); GPodderClient client = new GPodderClient(_context, account.name, accountManager.getPassword(account)); if (!client.authenticate()) return; SharedPreferences gpodderPrefs = getContext().getSharedPreferences("gpodder", MODE_PRIVATE); int lastTimestamp = gpodderPrefs.getInt("lastTimestamp", 0); // get the changes since the last time we updated GPodderClient.Changes changes = client.getSubscriptionChanges(lastTimestamp); updateSubscriptions(changes); // get a list of all subscriptions to detect local changes // gpodderDiffs contains differences that need to be rectified GPodderClient.Changes gpodderDiffs = client.getSubscriptionChanges(0); // find the last time we updated String[] projection = { SubscriptionProvider.COLUMN_URL }; Cursor c = _context.getContentResolver().query(SubscriptionProvider.URI, projection, null, null, null); while (c.moveToNext()) { String url = c.getString(0); // if this url isn't in gpodder, send it if (!gpodderDiffs.added.contains(url)) { gpodderDiffs.removed.add(url); } // we know about it so don't remove it gpodderDiffs.added.remove(c.getString(0)); } c.close(); // send diffs to gpodder lastTimestamp = client.syncDiffs(gpodderDiffs); // remember when we last updated SharedPreferences.Editor gpodderPrefsEditor = gpodderPrefs.edit(); gpodderPrefsEditor.putInt("lastTimestamp", lastTimestamp + 1); gpodderPrefsEditor.commit(); UpdateService.updateSubscriptions(_context); } private void updateSubscriptions(Changes changes) { for (String newUrl : changes.added) { - ContentValues values = new ContentValues(); - values.put(SubscriptionProvider.COLUMN_URL, newUrl); - _context.getContentResolver().insert(SubscriptionProvider.URI, values); + try { + ContentValues values = new ContentValues(); + values.put(SubscriptionProvider.COLUMN_URL, newUrl); + _context.getContentResolver().insert(SubscriptionProvider.URI, values); + } catch (SQLiteConstraintException ex) { + // don't care if the url didn't get inserted because it's already there + } } for (String oldUrl : changes.removed) { _context.getContentResolver().delete(SubscriptionProvider.URI, "url = ?", new String[] { oldUrl }); } } } } \ No newline at end of file
false
false
null
null
diff --git a/src/org/ibex/nestedvm/UnixRuntime.java b/src/org/ibex/nestedvm/UnixRuntime.java index 306b70e..adddc51 100644 --- a/src/org/ibex/nestedvm/UnixRuntime.java +++ b/src/org/ibex/nestedvm/UnixRuntime.java @@ -1,1936 +1,1936 @@ // Copyright 2000-2005 the Contributors, as shown in the revision logs. // Licensed under the Apache License 2.0 ("the License"). // You may not use this file except in compliance with the License. package org.ibex.nestedvm; import org.ibex.nestedvm.util.*; import java.io.*; import java.util.*; import java.net.*; import java.lang.reflect.*; // For lazily linked RuntimeCompiler // FEATURE: vfork public abstract class UnixRuntime extends Runtime implements Cloneable { /** The pid of this "process" */ private int pid; private UnixRuntime parent; public final int getPid() { return pid; } private static final GlobalState defaultGS = new GlobalState(); private GlobalState gs; public void setGlobalState(GlobalState gs) { if(state != STOPPED) throw new IllegalStateException("can't change GlobalState when running"); if(gs == null) throw new NullPointerException("gs is null"); this.gs = gs; } /** proceses' current working directory - absolute path WITHOUT leading slash "" = root, "bin" = /bin "usr/bin" = /usr/bin */ private String cwd; /** The runtime that should be run next when in state == EXECED */ private UnixRuntime execedRuntime; private Object children; // used only for synchronizatin private Vector activeChildren; private Vector exitedChildren; protected UnixRuntime(int pageSize, int totalPages) { this(pageSize,totalPages,false); } protected UnixRuntime(int pageSize, int totalPages, boolean exec) { super(pageSize,totalPages,exec); if(!exec) { gs = defaultGS; String userdir = Platform.getProperty("user.dir"); cwd = userdir == null ? null : gs.mapHostPath(userdir); if(cwd == null) cwd = "/"; cwd = cwd.substring(1); } } private static String posixTZ() { StringBuffer sb = new StringBuffer(); TimeZone zone = TimeZone.getDefault(); int off = zone.getRawOffset() / 1000; sb.append(Platform.timeZoneGetDisplayName(zone,false,false)); if(off > 0) sb.append("-"); else off = -off; sb.append(off/3600); off = off%3600; if(off > 0) sb.append(":").append(off/60); off=off%60; if(off > 0) sb.append(":").append(off); if(zone.useDaylightTime()) sb.append(Platform.timeZoneGetDisplayName(zone,true,false)); return sb.toString(); } private static boolean envHas(String key,String[] environ) { for(int i=0;i<environ.length;i++) if(environ[i]!=null && environ[i].startsWith(key + "=")) return true; return false; } String[] createEnv(String[] extra) { String[] defaults = new String[7]; int n=0; if(extra == null) extra = new String[0]; String tmp; if(!envHas("USER",extra) && Platform.getProperty("user.name") != null) defaults[n++] = "USER=" + Platform.getProperty("user.name"); if(!envHas("HOME",extra) && (tmp=Platform.getProperty("user.home")) != null && (tmp=gs.mapHostPath(tmp)) != null) defaults[n++] = "HOME=" + tmp; if(!envHas("TMPDIR",extra) && (tmp=Platform.getProperty("java.io.tmpdir")) != null && (tmp=gs.mapHostPath(tmp)) != null) defaults[n++] = "TMPDIR=" + tmp; if(!envHas("SHELL",extra)) defaults[n++] = "SHELL=/bin/sh"; if(!envHas("TERM",extra) && !win32Hacks) defaults[n++] = "TERM=vt100"; if(!envHas("TZ",extra)) defaults[n++] = "TZ=" + posixTZ(); if(!envHas("PATH",extra)) defaults[n++] = "PATH=/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/sbin"; String[] env = new String[extra.length+n]; for(int i=0;i<n;i++) env[i] = defaults[i]; for(int i=0;i<extra.length;i++) env[n++] = extra[i]; return env; } private static class ProcessTableFullExn extends RuntimeException { } void _started() { UnixRuntime[] tasks = gs.tasks; synchronized(gs) { if(pid != 0) { UnixRuntime prev = tasks[pid]; if(prev == null || prev == this || prev.pid != pid || prev.parent != parent) throw new Error("should never happen"); synchronized(parent.children) { int i = parent.activeChildren.indexOf(prev); if(i == -1) throw new Error("should never happen"); parent.activeChildren.setElementAt(this,i); } } else { int newpid = -1; int nextPID = gs.nextPID; for(int i=nextPID;i<tasks.length;i++) if(tasks[i] == null) { newpid = i; break; } if(newpid == -1) for(int i=1;i<nextPID;i++) if(tasks[i] == null) { newpid = i; break; } if(newpid == -1) throw new ProcessTableFullExn(); pid = newpid; gs.nextPID = newpid + 1; } tasks[pid] = this; } } int _syscall(int syscall, int a, int b, int c, int d, int e, int f) throws ErrnoException, FaultException { switch(syscall) { case SYS_kill: return sys_kill(a,b); case SYS_fork: return sys_fork(); case SYS_pipe: return sys_pipe(a); case SYS_dup2: return sys_dup2(a,b); case SYS_dup: return sys_dup(a); case SYS_waitpid: return sys_waitpid(a,b,c); case SYS_stat: return sys_stat(a,b); case SYS_lstat: return sys_lstat(a,b); case SYS_mkdir: return sys_mkdir(a,b); case SYS_getcwd: return sys_getcwd(a,b); case SYS_chdir: return sys_chdir(a); case SYS_exec: return sys_exec(a,b,c); case SYS_getdents: return sys_getdents(a,b,c,d); case SYS_unlink: return sys_unlink(a); case SYS_getppid: return sys_getppid(); case SYS_socket: return sys_socket(a,b,c); case SYS_connect: return sys_connect(a,b,c); case SYS_resolve_hostname: return sys_resolve_hostname(a,b,c); case SYS_setsockopt: return sys_setsockopt(a,b,c,d,e); case SYS_getsockopt: return sys_getsockopt(a,b,c,d,e); case SYS_bind: return sys_bind(a,b,c); case SYS_listen: return sys_listen(a,b); case SYS_accept: return sys_accept(a,b,c); case SYS_shutdown: return sys_shutdown(a,b); case SYS_sysctl: return sys_sysctl(a,b,c,d,e,f); case SYS_sendto: return sys_sendto(a,b,c,d,e,f); case SYS_recvfrom: return sys_recvfrom(a,b,c,d,e,f); case SYS_select: return sys_select(a,b,c,d,e); case SYS_access: return sys_access(a,b); case SYS_realpath: return sys_realpath(a,b); case SYS_chown: return sys_chown(a,b,c); case SYS_lchown: return sys_chown(a,b,c); case SYS_fchown: return sys_fchown(a,b,c); case SYS_chmod: return sys_chmod(a,b,c); case SYS_fchmod: return sys_fchmod(a,b,c); case SYS_fcntl: return sys_fcntl_lock(a,b,c); case SYS_umask: return sys_umask(a); default: return super._syscall(syscall,a,b,c,d,e,f); } } FD _open(String path, int flags, int mode) throws ErrnoException { path = normalizePath(path); FD fd = gs.open(this,path,flags,mode); if (fd != null && path != null) fd.setNormalizedPath(path); return fd; } private int sys_getppid() { return parent == null ? 1 : parent.pid; } private int sys_chown(int fileAddr, int uid, int gid) { return 0; } private int sys_lchown(int fileAddr, int uid, int gid) { return 0; } private int sys_fchown(int fd, int uid, int gid) { return 0; } private int sys_chmod(int fileAddr, int uid, int gid) { return 0; } private int sys_fchmod(int fd, int uid, int gid) { return 0; } private int sys_umask(int mask) { return 0; } private int sys_access(int cstring, int mode) throws ErrnoException, ReadFaultException { // FEATURE: sys_access - return gs.stat(this,cstring(cstring)) == null ? -ENOENT : 0; + return gs.stat(this,normalizePath(cstring(cstring))) == null ? -ENOENT : 0; } private int sys_realpath(int inAddr, int outAddr) throws FaultException { String s = normalizePath(cstring(inAddr)); byte[] b = getNullTerminatedBytes(s); if(b.length > PATH_MAX) return -ERANGE; copyout(b,outAddr,b.length); return 0; } // FEATURE: Signal handling // check flag only on backwards jumps to basic blocks without compulsatory checks // (see A Portable Research Framework for the Execution of Java Bytecode - Etienne Gagnon, Chapter 2) /** The kill syscall. SIGSTOP, SIGTSTO, SIGTTIN, and SIGTTOUT pause the process. SIGCONT, SIGCHLD, SIGIO, and SIGWINCH are ignored. Anything else terminates the process. */ private int sys_kill(int pid, int signal) { // This will only be called by raise() in newlib to invoke the default handler // We don't have to worry about actually delivering the signal if(pid != pid) return -ESRCH; if(signal < 0 || signal >= 32) return -EINVAL; switch(signal) { case 0: return 0; case 17: // SIGSTOP case 18: // SIGTSTP case 21: // SIGTTIN case 22: // SIGTTOU case 19: // SIGCONT case 20: // SIGCHLD case 23: // SIGIO case 28: // SIGWINCH break; default: exit(128+signal, true); } return 0; } private int sys_waitpid(int pid, int statusAddr, int options) throws FaultException, ErrnoException { final int WNOHANG = 1; if((options & ~(WNOHANG)) != 0) return -EINVAL; if(pid == 0 || pid < -1) { if(STDERR_DIAG) System.err.println("WARNING: waitpid called with a pid of " + pid); return -ECHILD; } boolean blocking = (options&WNOHANG)==0; if(pid !=-1 && (pid <= 0 || pid >= gs.tasks.length)) return -ECHILD; if(children == null) return blocking ? -ECHILD : 0; UnixRuntime done = null; synchronized(children) { for(;;) { if(pid == -1) { if(exitedChildren.size() > 0) { done = (UnixRuntime)exitedChildren.elementAt(exitedChildren.size() - 1); exitedChildren.removeElementAt(exitedChildren.size() - 1); } } else if(pid > 0) { if(pid >= gs.tasks.length) return -ECHILD; UnixRuntime t = gs.tasks[pid]; if(t.parent != this) return -ECHILD; if(t.state == EXITED) { if(!exitedChildren.removeElement(t)) throw new Error("should never happen"); done = t; } } else { // process group stuff, EINVAL returned above throw new Error("should never happen"); } if(done == null) { if(!blocking) return 0; try { children.wait(); } catch(InterruptedException e) {} //System.err.println("waitpid woke up: " + exitedChildren.size()); } else { gs.tasks[done.pid] = null; break; } } } if(statusAddr!=0) memWrite(statusAddr,done.exitStatus()<<8); return done.pid; } void _exited() { if(children != null) synchronized(children) { for(Enumeration e = exitedChildren.elements(); e.hasMoreElements(); ) { UnixRuntime child = (UnixRuntime) e.nextElement(); gs.tasks[child.pid] = null; } exitedChildren.removeAllElements(); for(Enumeration e = activeChildren.elements(); e.hasMoreElements(); ) { UnixRuntime child = (UnixRuntime) e.nextElement(); child.parent = null; } activeChildren.removeAllElements(); } UnixRuntime _parent = parent; if(_parent == null) { gs.tasks[pid] = null; } else { synchronized(_parent.children) { if(parent == null) { gs.tasks[pid] = null; } else { if(!parent.activeChildren.removeElement(this)) throw new Error("should never happen _exited: pid: " + pid); parent.exitedChildren.addElement(this); parent.children.notify(); } } } } protected Object clone() throws CloneNotSupportedException { UnixRuntime r = (UnixRuntime) super.clone(); r.pid = 0; r.parent = null; r.children = null; r.activeChildren = r.exitedChildren = null; return r; } private int sys_fork() { final UnixRuntime r; try { r = (UnixRuntime) clone(); } catch(Exception e) { e.printStackTrace(); return -ENOMEM; } r.parent = this; try { r._started(); } catch(ProcessTableFullExn e) { return -ENOMEM; } //System.err.println("fork " + pid + " -> " + r.pid + " tasks[" + r.pid + "] = " + gd.tasks[r.pid]); if(children == null) { children = new Object(); activeChildren = new Vector(); exitedChildren = new Vector(); } activeChildren.addElement(r); CPUState state = new CPUState(); getCPUState(state); state.r[V0] = 0; // return 0 to child state.pc += 4; // skip over syscall instruction r.setCPUState(state); r.state = PAUSED; new ForkedProcess(r); return r.pid; } public static final class ForkedProcess extends Thread { private final UnixRuntime initial; public ForkedProcess(UnixRuntime initial) { this.initial = initial; start(); } public void run() { UnixRuntime.executeAndExec(initial); } } public static int runAndExec(UnixRuntime r, String argv0, String[] rest) { return runAndExec(r,concatArgv(argv0,rest)); } public static int runAndExec(UnixRuntime r, String[] argv) { r.start(argv); return executeAndExec(r); } public static int executeAndExec(UnixRuntime r) { for(;;) { for(;;) { if(r.execute()) break; if(STDERR_DIAG) System.err.println("WARNING: Pause requested while executing runAndExec()"); } if(r.state != EXECED) return r.exitStatus(); r = r.execedRuntime; } } private String[] readStringArray(int addr) throws ReadFaultException { int count = 0; for(int p=addr;memRead(p) != 0;p+=4) count++; String[] a = new String[count]; for(int i=0,p=addr;i<count;i++,p+=4) a[i] = cstring(memRead(p)); return a; } private int sys_exec(int cpath, int cargv, int cenvp) throws ErrnoException, FaultException { return exec(normalizePath(cstring(cpath)),readStringArray(cargv),readStringArray(cenvp)); } private final static Method runtimeCompilerCompile; static { Method m; try { m = Class.forName("org.ibex.nestedvm.RuntimeCompiler").getMethod("compile",new Class[]{Seekable.class,String.class,String.class}); } catch(NoSuchMethodException e) { m = null; } catch(ClassNotFoundException e) { m = null; } runtimeCompilerCompile = m; } public Class runtimeCompile(Seekable s, String sourceName) throws IOException { if(runtimeCompilerCompile == null) { if(STDERR_DIAG) System.err.println("WARNING: Exec attempted but RuntimeCompiler not found!"); return null; } try { return (Class) runtimeCompilerCompile.invoke(null,new Object[]{s,"unixruntime,maxinsnpermethod=256,lessconstants",sourceName}); } catch(IllegalAccessException e) { e.printStackTrace(); return null; } catch(InvocationTargetException e) { Throwable t = e.getTargetException(); if(t instanceof IOException) throw (IOException) t; if(t instanceof RuntimeException) throw (RuntimeException) t; if(t instanceof Error) throw (Error) t; if(STDERR_DIAG) t.printStackTrace(); return null; } } private int exec(String path, String[] argv, String[] envp) throws ErrnoException { if(argv.length == 0) argv = new String[]{""}; // HACK: Hideous hack to make a standalone busybox possible if(path.equals("bin/busybox") && getClass().getName().endsWith("BusyBox")) return execClass(getClass(),argv,envp); // NOTE: For this little hack to work nestedvm.root MUST be "." /*try { System.err.println("Execing normalized path: " + normalizedPath); if(true) return exec(new Interpreter(normalizedPath),argv,envp); } catch(IOException e) { throw new Error(e); }*/ FStat fstat = gs.stat(this,path); if(fstat == null) return -ENOENT; GlobalState.CacheEnt ent = (GlobalState.CacheEnt) gs.execCache.get(path); long mtime = fstat.mtime(); long size = fstat.size(); if(ent != null) { //System.err.println("Found cached entry for " + path); if(ent.time ==mtime && ent.size == size) { if(ent.o instanceof Class) return execClass((Class) ent.o,argv,envp); if(ent.o instanceof String[]) return execScript(path,(String[]) ent.o,argv,envp); throw new Error("should never happen"); } //System.err.println("Cache was out of date"); gs.execCache.remove(path); } FD fd = gs.open(this,path,RD_ONLY,0); if(fd == null) throw new ErrnoException(ENOENT); Seekable s = fd.seekable(); if(s == null) throw new ErrnoException(EACCES); byte[] buf = new byte[4096]; try { int n = s.read(buf,0,buf.length); if(n == -1) throw new ErrnoException(ENOEXEC); switch(buf[0]) { case '\177': // possible ELF if(n < 4) s.tryReadFully(buf,n,4-n); if(buf[1] != 'E' || buf[2] != 'L' || buf[3] != 'F') return -ENOEXEC; s.seek(0); if(STDERR_DIAG) System.err.println("Running RuntimeCompiler for " + path); Class c = runtimeCompile(s,path); if(STDERR_DIAG) System.err.println("RuntimeCompiler finished for " + path); if(c == null) throw new ErrnoException(ENOEXEC); gs.execCache.put(path,new GlobalState.CacheEnt(mtime,size,c)); return execClass(c,argv,envp); case '#': if(n == 1) { int n2 = s.read(buf,1,buf.length-1); if(n2 == -1) return -ENOEXEC; n += n2; } if(buf[1] != '!') return -ENOEXEC; int p = 2; n -= 2; OUTER: for(;;) { for(int i=p;i<p+n;i++) if(buf[i] == '\n') { p = i; break OUTER; } p += n; if(p == buf.length) break OUTER; n = s.read(buf,p,buf.length-p); } int cmdStart = 2; for(;cmdStart<p;cmdStart++) if(buf[cmdStart]!=' ') break; if(cmdStart == p) throw new ErrnoException(ENOEXEC); int argStart = cmdStart; for(;argStart<p;argStart++) if(buf[argStart] == ' ') break; int cmdEnd = argStart; while(argStart < p && buf[argStart] == ' ') argStart++; String[] command = new String[] { new String(buf,cmdStart,cmdEnd-cmdStart), argStart < p ? new String(buf,argStart,p-argStart) : null }; gs.execCache.put(path,new GlobalState.CacheEnt(mtime,size,command)); return execScript(path,command,argv,envp); default: return -ENOEXEC; } } catch(IOException e) { return -EIO; } finally { fd.close(); } } public int execScript(String path, String[] command, String[] argv, String[] envp) throws ErrnoException { String[] newArgv = new String[argv.length-1 + (command[1] != null ? 3 : 2)]; int p = command[0].lastIndexOf('/'); newArgv[0] = p == -1 ? command[0] : command[0].substring(p+1); newArgv[1] = "/" + path; p = 2; if(command[1] != null) newArgv[p++] = command[1]; for(int i=1;i<argv.length;i++) newArgv[p++] = argv[i]; if(p != newArgv.length) throw new Error("p != newArgv.length"); System.err.println("Execing: " + command[0]); for(int i=0;i<newArgv.length;i++) System.err.println("execing [" + i + "] " + newArgv[i]); return exec(command[0],newArgv,envp); } public int execClass(Class c,String[] argv, String[] envp) { try { UnixRuntime r = (UnixRuntime) c.getDeclaredConstructor(new Class[]{Boolean.TYPE}).newInstance(new Object[]{Boolean.TRUE}); return exec(r,argv,envp); } catch(Exception e) { e.printStackTrace(); return -ENOEXEC; } } private int exec(UnixRuntime r, String[] argv, String[] envp) { //System.err.println("Execing " + r); for(int i=0;i<OPEN_MAX;i++) if(closeOnExec[i]) closeFD(i); r.fds = fds; r.closeOnExec = closeOnExec; // make sure this doesn't get messed with these since we didn't copy them fds = null; closeOnExec = null; r.gs = gs; r.sm = sm; r.cwd = cwd; r.pid = pid; r.parent = parent; r.start(argv,envp); state = EXECED; execedRuntime = r; return 0; } - static class Pipe { + public static class Pipe { private final byte[] pipebuf = new byte[PIPE_BUF*4]; private int readPos; private int writePos; public final FD reader = new Reader(); public final FD writer = new Writer(); public class Reader extends FD { protected FStat _fstat() { return new SocketFStat(); } public int read(byte[] buf, int off, int len) throws ErrnoException { if(len == 0) return 0; synchronized(Pipe.this) { while(writePos != -1 && readPos == writePos) { try { Pipe.this.wait(); } catch(InterruptedException e) { /* ignore */ } } if(writePos == -1) return 0; // eof len = Math.min(len,writePos-readPos); System.arraycopy(pipebuf,readPos,buf,off,len); readPos += len; if(readPos == writePos) Pipe.this.notify(); return len; } } public int flags() { return O_RDONLY; } public void _close() { synchronized(Pipe.this) { readPos = -1; Pipe.this.notify(); } } } public class Writer extends FD { protected FStat _fstat() { return new SocketFStat(); } public int write(byte[] buf, int off, int len) throws ErrnoException { if(len == 0) return 0; synchronized(Pipe.this) { if(readPos == -1) throw new ErrnoException(EPIPE); if(pipebuf.length - writePos < Math.min(len,PIPE_BUF)) { // not enough space to atomicly write the data while(readPos != -1 && readPos != writePos) { try { Pipe.this.wait(); } catch(InterruptedException e) { /* ignore */ } } if(readPos == -1) throw new ErrnoException(EPIPE); readPos = writePos = 0; } len = Math.min(len,pipebuf.length - writePos); System.arraycopy(buf,off,pipebuf,writePos,len); if(readPos == writePos) Pipe.this.notify(); writePos += len; return len; } } public int flags() { return O_WRONLY; } public void _close() { synchronized(Pipe.this) { writePos = -1; Pipe.this.notify(); } } } } private int sys_pipe(int addr) { Pipe pipe = new Pipe(); int fd1 = addFD(pipe.reader); if(fd1 < 0) return -ENFILE; int fd2 = addFD(pipe.writer); if(fd2 < 0) { closeFD(fd1); return -ENFILE; } try { memWrite(addr,fd1); memWrite(addr+4,fd2); } catch(FaultException e) { closeFD(fd1); closeFD(fd2); return -EFAULT; } return 0; } private int sys_dup2(int oldd, int newd) { if(oldd == newd) return 0; if(oldd < 0 || oldd >= OPEN_MAX) return -EBADFD; if(newd < 0 || newd >= OPEN_MAX) return -EBADFD; if(fds[oldd] == null) return -EBADFD; if(fds[newd] != null) fds[newd].close(); fds[newd] = fds[oldd].dup(); return 0; } private int sys_dup(int oldd) { if(oldd < 0 || oldd >= OPEN_MAX) return -EBADFD; if(fds[oldd] == null) return -EBADFD; FD fd = fds[oldd].dup(); int newd = addFD(fd); if(newd < 0) { fd.close(); return -ENFILE; } return newd; } private int sys_stat(int cstring, int addr) throws FaultException, ErrnoException { FStat s = gs.stat(this,normalizePath(cstring(cstring))); if(s == null) return -ENOENT; return stat(s,addr); } private int sys_lstat(int cstring, int addr) throws FaultException, ErrnoException { FStat s = gs.lstat(this,normalizePath(cstring(cstring))); if(s == null) return -ENOENT; return stat(s,addr); } private int sys_mkdir(int cstring, int mode) throws FaultException, ErrnoException { gs.mkdir(this,normalizePath(cstring(cstring)),mode); return 0; } private int sys_unlink(int cstring) throws FaultException, ErrnoException { gs.unlink(this,normalizePath(cstring(cstring))); return 0; } private int sys_getcwd(int addr, int size) throws FaultException, ErrnoException { byte[] b = getBytes(cwd); if(size == 0) return -EINVAL; if(size < b.length+2) return -ERANGE; memset(addr,'/',1); copyout(b,addr+1,b.length); memset(addr+b.length+1,0,1); return addr; } private int sys_chdir(int addr) throws ErrnoException, FaultException { String path = normalizePath(cstring(addr)); FStat st = gs.stat(this,path); if(st == null) return -ENOENT; if(st.type() != FStat.S_IFDIR) return -ENOTDIR; cwd = path; return 0; } private int sys_getdents(int fdn, int addr, int count, int seekptr) throws FaultException, ErrnoException { count = Math.min(count,MAX_CHUNK); if(fdn < 0 || fdn >= OPEN_MAX) return -EBADFD; if(fds[fdn] == null) return -EBADFD; byte[] buf = byteBuf(count); int n = fds[fdn].getdents(buf,0,count); copyout(buf,addr,n); return n; } void _preCloseFD(FD fd) { // release all fcntl locks on this file Seekable s = fd.seekable(); if (s == null) return; try { for (int i=0; i < gs.locks.length; i++) { Seekable.Lock l = gs.locks[i]; if (l == null) continue; if (s.equals(l.seekable()) && l.getOwner() == this) { l.release(); gs.locks[i] = null; } } } catch (IOException e) { throw new RuntimeException(e); } } void _postCloseFD(FD fd) { if (fd.isMarkedForDeleteOnClose()) { try { gs.unlink(this, fd.getNormalizedPath()); } catch (Throwable t) {} } } /** Implements the F_GETLK and F_SETLK cases of fcntl syscall. * If l_start = 0 and l_len = 0 the lock refers to the entire file. * Uses GlobalState to ensure locking across processes in the same JVM. struct flock { short l_type; // lock type: F_UNLCK, F_RDLCK, F_WRLCK short l_whence; // type of l_start: SEEK_SET, SEEK_CUR, SEEK_END long l_start; // starting offset, bytes long l_len; // len = 0 means until EOF short l_pid; // lock owner short l_xxx; // padding }; */ private int sys_fcntl_lock(int fdn, int cmd, int arg) throws FaultException{ if (cmd != F_GETLK && cmd != F_SETLK) return sys_fcntl(fdn, cmd, arg); if(fdn < 0 || fdn >= OPEN_MAX) return -EBADFD; if(fds[fdn] == null) return -EBADFD; FD fd = fds[fdn]; if (arg == 0) return -EINVAL; int word = memRead(arg); int l_start = memRead(arg+4); int l_len = memRead(arg+8); int l_type = word>>16; int l_whence = word&0x00ff; Seekable.Lock[] locks = gs.locks; Seekable s = fd.seekable(); if (s == null) return -EINVAL; try { switch (l_whence) { case SEEK_SET: break; case SEEK_CUR: l_start += s.pos(); break; case SEEK_END: l_start += s.length(); break; default: return -1; } if (cmd == F_GETLK) { // The simple Java file locking below will happily return // a lock that overlaps one already held by the JVM. Thus // we must check over all the locks held by other Runtimes for (int i=0; i < locks.length; i++) { if (locks[i] == null || !s.equals(locks[i].seekable())) continue; if (!locks[i].overlaps(l_start, l_len)) continue; if (locks[i].getOwner() == this) continue; if (locks[i].isShared() && l_type == F_RDLCK) continue; // overlapping lock held by another process return 0; } // check if an area is lockable by attempting to obtain a lock Seekable.Lock lock = s.lock(l_start, l_len, l_type == F_RDLCK); if (lock != null) { // no lock exists memWrite(arg, SEEK_SET|(F_UNLCK<<16)); lock.release(); } return 0; } // now processing F_SETLK if (cmd != F_SETLK) return -EINVAL; if (l_type == F_UNLCK) { // release all locks that fall within the boundaries given for (int i=0; i < locks.length; i++) { if (locks[i] == null || !s.equals(locks[i].seekable())) continue; if (locks[i].getOwner() != this) continue; int pos = (int)locks[i].position(); if (pos < l_start) continue; if (l_start != 0 && l_len != 0) // start/len 0 means unlock all if (pos + locks[i].size() > l_start + l_len) continue; locks[i].release(); locks[i] = null; } return 0; } else if (l_type == F_RDLCK || l_type == F_WRLCK) { // first see if a lock already exists for (int i=0; i < locks.length; i++) { if (locks[i] == null || !s.equals(locks[i].seekable())) continue; if (locks[i].getOwner() == this) { // if this Runtime owns an overlapping lock work with it if (locks[i].contained(l_start, l_len)) { locks[i].release(); locks[i] = null; } else if (locks[i].contains(l_start, l_len)) { if (locks[i].isShared() == (l_type == F_RDLCK)) { // return this more general lock memWrite(arg+4, (int)locks[i].position()); memWrite(arg+8, (int)locks[i].size()); return 0; } else { locks[i].release(); locks[i] = null; } } } else { // if another Runtime has an lock and it is exclusive or // we want an exclusive lock then fail if (locks[i].overlaps(l_start, l_len) && (!locks[i].isShared() || l_type == F_WRLCK)) return -EAGAIN; } } // create the lock Seekable.Lock lock = s.lock(l_start, l_len, l_type == F_RDLCK); if (lock == null) return -EAGAIN; lock.setOwner(this); int i; for (i=0; i < locks.length; i++) if (locks[i] == null) break; if (i == locks.length) return -ENOLCK; locks[i] = lock; return 0; } else { return -EINVAL; } } catch (IOException e) { throw new RuntimeException(e); } } static class SocketFD extends FD { public static final int TYPE_STREAM = 0; public static final int TYPE_DGRAM = 1; public static final int LISTEN = 2; public int type() { return flags & 1; } public boolean listen() { return (flags & 2) != 0; } int flags; int options; Socket s; ServerSocket ss; DatagramSocket ds; InetAddress bindAddr; int bindPort = -1; InetAddress connectAddr; int connectPort = -1; DatagramPacket dp; InputStream is; OutputStream os; private static final byte[] EMPTY = new byte[0]; public SocketFD(int type) { flags = type; if(type == TYPE_DGRAM) dp = new DatagramPacket(EMPTY,0); } public void setOptions() { try { if(s != null && type() == TYPE_STREAM && !listen()) { Platform.socketSetKeepAlive(s,(options & SO_KEEPALIVE) != 0); } } catch(SocketException e) { if(STDERR_DIAG) e.printStackTrace(); } } public void _close() { try { if(s != null) s.close(); if(ss != null) ss.close(); if(ds != null) ds.close(); } catch(IOException e) { /* ignore */ } } public int read(byte[] a, int off, int length) throws ErrnoException { if(type() == TYPE_DGRAM) return recvfrom(a,off,length,null,null); if(is == null) throw new ErrnoException(EPIPE); try { int n = is.read(a,off,length); return n < 0 ? 0 : n; } catch(IOException e) { throw new ErrnoException(EIO); } } public int recvfrom(byte[] a, int off, int length, InetAddress[] sockAddr, int[] port) throws ErrnoException { if(type() == TYPE_STREAM) return read(a,off,length); if(off != 0) throw new IllegalArgumentException("off must be 0"); dp.setData(a); dp.setLength(length); try { if(ds == null) ds = new DatagramSocket(); ds.receive(dp); } catch(IOException e) { if(STDERR_DIAG) e.printStackTrace(); throw new ErrnoException(EIO); } if(sockAddr != null) { sockAddr[0] = dp.getAddress(); port[0] = dp.getPort(); } return dp.getLength(); } public int write(byte[] a, int off, int length) throws ErrnoException { if(type() == TYPE_DGRAM) return sendto(a,off,length,null,-1); if(os == null) throw new ErrnoException(EPIPE); try { os.write(a,off,length); return length; } catch(IOException e) { throw new ErrnoException(EIO); } } public int sendto(byte[] a, int off, int length, InetAddress destAddr, int destPort) throws ErrnoException { if(off != 0) throw new IllegalArgumentException("off must be 0"); if(type() == TYPE_STREAM) return write(a,off,length); if(destAddr == null) { destAddr = connectAddr; destPort = connectPort; if(destAddr == null) throw new ErrnoException(ENOTCONN); } dp.setAddress(destAddr); dp.setPort(destPort); dp.setData(a); dp.setLength(length); try { if(ds == null) ds = new DatagramSocket(); ds.send(dp); } catch(IOException e) { if(STDERR_DIAG) e.printStackTrace(); if("Network is unreachable".equals(e.getMessage())) throw new ErrnoException(EHOSTUNREACH); throw new ErrnoException(EIO); } return dp.getLength(); } public int flags() { return O_RDWR; } public FStat _fstat() { return new SocketFStat(); } } private int sys_socket(int domain, int type, int proto) { if(domain != AF_INET || (type != SOCK_STREAM && type != SOCK_DGRAM)) return -EPROTONOSUPPORT; return addFD(new SocketFD(type == SOCK_STREAM ? SocketFD.TYPE_STREAM : SocketFD.TYPE_DGRAM)); } private SocketFD getSocketFD(int fdn) throws ErrnoException { if(fdn < 0 || fdn >= OPEN_MAX) throw new ErrnoException(EBADFD); if(fds[fdn] == null) throw new ErrnoException(EBADFD); if(!(fds[fdn] instanceof SocketFD)) throw new ErrnoException(ENOTSOCK); return (SocketFD) fds[fdn]; } private int sys_connect(int fdn, int addr, int namelen) throws ErrnoException, FaultException { SocketFD fd = getSocketFD(fdn); if(fd.type() == SocketFD.TYPE_STREAM && (fd.s != null || fd.ss != null)) return -EISCONN; int word1 = memRead(addr); if( ((word1 >>> 16)&0xff) != AF_INET) return -EAFNOSUPPORT; int port = word1 & 0xffff; byte[] ip = new byte[4]; copyin(addr+4,ip,4); InetAddress inetAddr; try { inetAddr = Platform.inetAddressFromBytes(ip); } catch(UnknownHostException e) { return -EADDRNOTAVAIL; } fd.connectAddr = inetAddr; fd.connectPort = port; try { switch(fd.type()) { case SocketFD.TYPE_STREAM: { Socket s = new Socket(inetAddr,port); fd.s = s; fd.setOptions(); fd.is = s.getInputStream(); fd.os = s.getOutputStream(); break; } case SocketFD.TYPE_DGRAM: break; default: throw new Error("should never happen"); } } catch(IOException e) { return -ECONNREFUSED; } return 0; } private int sys_resolve_hostname(int chostname, int addr, int sizeAddr) throws FaultException { String hostname = cstring(chostname); int size = memRead(sizeAddr); InetAddress[] inetAddrs; try { inetAddrs = InetAddress.getAllByName(hostname); } catch(UnknownHostException e) { return HOST_NOT_FOUND; } int count = min(size/4,inetAddrs.length); for(int i=0;i<count;i++,addr+=4) { byte[] b = inetAddrs[i].getAddress(); copyout(b,addr,4); } memWrite(sizeAddr,count*4); return 0; } private int sys_setsockopt(int fdn, int level, int name, int valaddr, int len) throws ReadFaultException, ErrnoException { SocketFD fd = getSocketFD(fdn); switch(level) { case SOL_SOCKET: switch(name) { case SO_REUSEADDR: case SO_KEEPALIVE: { if(len != 4) return -EINVAL; int val = memRead(valaddr); if(val != 0) fd.options |= name; else fd.options &= ~name; fd.setOptions(); return 0; } default: if(STDERR_DIAG) System.err.println("Unknown setsockopt name passed: " + name); return -ENOPROTOOPT; } default: if(STDERR_DIAG) System.err.println("Unknown setsockopt leve passed: " + level); return -ENOPROTOOPT; } } private int sys_getsockopt(int fdn, int level, int name, int valaddr, int lenaddr) throws ErrnoException, FaultException { SocketFD fd = getSocketFD(fdn); switch(level) { case SOL_SOCKET: switch(name) { case SO_REUSEADDR: case SO_KEEPALIVE: { int len = memRead(lenaddr); if(len < 4) return -EINVAL; int val = (fd.options & name) != 0 ? 1 : 0; memWrite(valaddr,val); memWrite(lenaddr,4); return 0; } default: if(STDERR_DIAG) System.err.println("Unknown setsockopt name passed: " + name); return -ENOPROTOOPT; } default: if(STDERR_DIAG) System.err.println("Unknown setsockopt leve passed: " + level); return -ENOPROTOOPT; } } private int sys_bind(int fdn, int addr, int namelen) throws FaultException, ErrnoException { SocketFD fd = getSocketFD(fdn); if(fd.type() == SocketFD.TYPE_STREAM && (fd.s != null || fd.ss != null)) return -EISCONN; int word1 = memRead(addr); if( ((word1 >>> 16)&0xff) != AF_INET) return -EAFNOSUPPORT; int port = word1 & 0xffff; InetAddress inetAddr = null; if(memRead(addr+4) != 0) { byte[] ip = new byte[4]; copyin(addr+4,ip,4); try { inetAddr = Platform.inetAddressFromBytes(ip); } catch(UnknownHostException e) { return -EADDRNOTAVAIL; } } switch(fd.type()) { case SocketFD.TYPE_STREAM: { fd.bindAddr = inetAddr; fd.bindPort = port; return 0; } case SocketFD.TYPE_DGRAM: { if(fd.ds != null) fd.ds.close(); try { fd.ds = inetAddr != null ? new DatagramSocket(port,inetAddr) : new DatagramSocket(port); } catch(IOException e) { return -EADDRINUSE; } return 0; } default: throw new Error("should never happen"); } } private int sys_listen(int fdn, int backlog) throws ErrnoException { SocketFD fd = getSocketFD(fdn); if(fd.type() != SocketFD.TYPE_STREAM) return -EOPNOTSUPP; if(fd.ss != null || fd.s != null) return -EISCONN; if(fd.bindPort < 0) return -EOPNOTSUPP; try { fd.ss = new ServerSocket(fd.bindPort,backlog,fd.bindAddr); fd.flags |= SocketFD.LISTEN; return 0; } catch(IOException e) { return -EADDRINUSE; } } private int sys_accept(int fdn, int addr, int lenaddr) throws ErrnoException, FaultException { SocketFD fd = getSocketFD(fdn); if(fd.type() != SocketFD.TYPE_STREAM) return -EOPNOTSUPP; if(!fd.listen()) return -EOPNOTSUPP; int size = memRead(lenaddr); ServerSocket s = fd.ss; Socket client; try { client = s.accept(); } catch(IOException e) { return -EIO; } if(size >= 8) { memWrite(addr,(6 << 24) | (AF_INET << 16) | client.getPort()); byte[] b = client.getInetAddress().getAddress(); copyout(b,addr+4,4); memWrite(lenaddr,8); } SocketFD clientFD = new SocketFD(SocketFD.TYPE_STREAM); clientFD.s = client; try { clientFD.is = client.getInputStream(); clientFD.os = client.getOutputStream(); } catch(IOException e) { return -EIO; } int n = addFD(clientFD); if(n == -1) { clientFD.close(); return -ENFILE; } return n; } private int sys_shutdown(int fdn, int how) throws ErrnoException { SocketFD fd = getSocketFD(fdn); if(fd.type() != SocketFD.TYPE_STREAM || fd.listen()) return -EOPNOTSUPP; if(fd.s == null) return -ENOTCONN; Socket s = fd.s; try { if(how == SHUT_RD || how == SHUT_RDWR) Platform.socketHalfClose(s,false); if(how == SHUT_WR || how == SHUT_RDWR) Platform.socketHalfClose(s,true); } catch(IOException e) { return -EIO; } return 0; } private int sys_sendto(int fdn, int addr, int count, int flags, int destAddr, int socklen) throws ErrnoException,ReadFaultException { SocketFD fd = getSocketFD(fdn); if(flags != 0) throw new ErrnoException(EINVAL); int word1 = memRead(destAddr); if( ((word1 >>> 16)&0xff) != AF_INET) return -EAFNOSUPPORT; int port = word1 & 0xffff; InetAddress inetAddr; byte[] ip = new byte[4]; copyin(destAddr+4,ip,4); try { inetAddr = Platform.inetAddressFromBytes(ip); } catch(UnknownHostException e) { return -EADDRNOTAVAIL; } count = Math.min(count,MAX_CHUNK); byte[] buf = byteBuf(count); copyin(addr,buf,count); try { return fd.sendto(buf,0,count,inetAddr,port); } catch(ErrnoException e) { if(e.errno == EPIPE) exit(128+13,true); throw e; } } private int sys_recvfrom(int fdn, int addr, int count, int flags, int sourceAddr, int socklenAddr) throws ErrnoException, FaultException { SocketFD fd = getSocketFD(fdn); if(flags != 0) throw new ErrnoException(EINVAL); InetAddress[] inetAddr = sourceAddr == 0 ? null : new InetAddress[1]; int[] port = sourceAddr == 0 ? null : new int[1]; count = Math.min(count,MAX_CHUNK); byte[] buf = byteBuf(count); int n = fd.recvfrom(buf,0,count,inetAddr,port); copyout(buf,addr,n); if(sourceAddr != 0) { memWrite(sourceAddr,(AF_INET << 16) | port[0]); byte[] ip = inetAddr[0].getAddress(); copyout(ip,sourceAddr+4,4); } return n; } private int sys_select(int n, int readFDs, int writeFDs, int exceptFDs, int timevalAddr) throws ReadFaultException, ErrnoException { return -ENOSYS; } private static String hostName() { try { return InetAddress.getLocalHost().getHostName(); } catch(UnknownHostException e) { return "darkstar"; } } private int sys_sysctl(int nameaddr, int namelen, int oldp, int oldlenaddr, int newp, int newlen) throws FaultException { if(newp != 0) return -EPERM; if(namelen == 0) return -ENOENT; if(oldp == 0) return 0; Object o = null; switch(memRead(nameaddr)) { case CTL_KERN: if(namelen != 2) break; switch(memRead(nameaddr+4)) { case KERN_OSTYPE: o = "NestedVM"; break; case KERN_HOSTNAME: o = hostName(); break; case KERN_OSRELEASE: o = VERSION; break; case KERN_VERSION: o = "NestedVM Kernel Version " + VERSION; break; } break; case CTL_HW: if(namelen != 2) break; switch(memRead(nameaddr+4)) { case HW_MACHINE: o = "NestedVM Virtual Machine"; break; } break; } if(o == null) return -ENOENT; int len = memRead(oldlenaddr); if(o instanceof String) { byte[] b = getNullTerminatedBytes((String)o); if(len < b.length) return -ENOMEM; len = b.length; copyout(b,oldp,len); memWrite(oldlenaddr,len); } else if(o instanceof Integer) { if(len < 4) return -ENOMEM; memWrite(oldp,((Integer)o).intValue()); } else { throw new Error("should never happen"); } return 0; } public static final class GlobalState { Hashtable execCache = new Hashtable(); final UnixRuntime[] tasks; int nextPID = 1; /** Table of all current file locks held by this process. */ Seekable.Lock[] locks = new Seekable.Lock[16]; private MP[] mps = new MP[0]; private FS root; public GlobalState() { this(255); } public GlobalState(int maxProcs) { this(maxProcs,true); } public GlobalState(int maxProcs, boolean defaultMounts) { tasks = new UnixRuntime[maxProcs+1]; if(defaultMounts) { File root = null; if(Platform.getProperty("nestedvm.root") != null) { root = new File(Platform.getProperty("nestedvm.root")); if(!root.isDirectory()) throw new IllegalArgumentException("nestedvm.root is not a directory"); } else { String cwd = Platform.getProperty("user.dir"); root = Platform.getRoot(new File(cwd != null ? cwd : ".")); } addMount("/",new HostFS(root)); if(Platform.getProperty("nestedvm.root") == null) { File[] roots = Platform.listRoots(); for(int i=0;i<roots.length;i++) { String name = roots[i].getPath(); if(name.endsWith(File.separator)) name = name.substring(0,name.length()-1); if(name.length() == 0 || name.indexOf('/') != -1) continue; addMount("/" + name.toLowerCase(),new HostFS(roots[i])); } } addMount("/dev",new DevFS()); addMount("/resource",new ResourceFS()); addMount("/cygdrive",new CygdriveFS()); } } public String mapHostPath(String s) { return mapHostPath(new File(s)); } public String mapHostPath(File f) { MP[] list; FS root; synchronized(this) { mps = this.mps; root = this.root; } if(!f.isAbsolute()) f = new File(f.getAbsolutePath()); for(int i=mps.length;i>=0;i--) { FS fs = i == mps.length ? root : mps[i].fs; String path = i == mps.length ? "" : mps[i].path; if(!(fs instanceof HostFS)) continue; File fsroot = ((HostFS)fs).getRoot(); if(!fsroot.isAbsolute()) fsroot = new File(fsroot.getAbsolutePath()); if(f.getPath().startsWith(fsroot.getPath())) { char sep = File.separatorChar; String child = f.getPath().substring(fsroot.getPath().length()); if(sep != '/') { char[] child_ = child.toCharArray(); for(int j=0;j<child_.length;j++) { if(child_[j] == '/') child_[j] = sep; else if(child_[j] == sep) child_[j] = '/'; } child = new String(child_); } String mapped = "/" + (path.length()==0?"":path+"/") + child; return mapped; } } return null; } static class MP implements Sort.Comparable { public MP(String path, FS fs) { this.path = path; this.fs = fs; } public String path; public FS fs; public int compareTo(Object o) { if(!(o instanceof MP)) return 1; return -path.compareTo(((MP)o).path); } } public synchronized FS getMount(String path) { if(!path.startsWith("/")) throw new IllegalArgumentException("Mount point doesn't start with a /"); if(path.equals("/")) return root; path = path.substring(1); for(int i=0;i<mps.length;i++) if(mps[i].path.equals(path)) return mps[i].fs; return null; } public synchronized void addMount(String path, FS fs) { if(getMount(path) != null) throw new IllegalArgumentException("mount point already exists"); if(!path.startsWith("/")) throw new IllegalArgumentException("Mount point doesn't start with a /"); if(fs.owner != null) fs.owner.removeMount(fs); fs.owner = this; if(path.equals("/")) { root = fs; fs.devno = 1; return; } path = path.substring(1); int oldLength = mps.length; MP[] newMPS = new MP[oldLength + 1]; if(oldLength != 0) System.arraycopy(mps,0,newMPS,0,oldLength); newMPS[oldLength] = new MP(path,fs); Sort.sort(newMPS); mps = newMPS; int highdevno = 0; for(int i=0;i<mps.length;i++) highdevno = max(highdevno,mps[i].fs.devno); fs.devno = highdevno + 2; } public synchronized void removeMount(FS fs) { for(int i=0;i<mps.length;i++) if(mps[i].fs == fs) { removeMount(i); return; } throw new IllegalArgumentException("mount point doesn't exist"); } public synchronized void removeMount(String path) { if(!path.startsWith("/")) throw new IllegalArgumentException("Mount point doesn't start with a /"); if(path.equals("/")) { removeMount(-1); } else { path = path.substring(1); int p; for(p=0;p<mps.length;p++) if(mps[p].path.equals(path)) break; if(p == mps.length) throw new IllegalArgumentException("mount point doesn't exist"); removeMount(p); } } private void removeMount(int index) { if(index == -1) { root.owner = null; root = null; return; } MP[] newMPS = new MP[mps.length - 1]; System.arraycopy(mps,0,newMPS,0,index); System.arraycopy(mps,0,newMPS,index,mps.length-index-1); mps = newMPS; } private Object fsop(int op, UnixRuntime r, String normalizedPath, int arg1, int arg2) throws ErrnoException { int pl = normalizedPath.length(); if(pl != 0) { MP[] list; synchronized(this) { list = mps; } for(int i=0;i<list.length;i++) { MP mp = list[i]; int mpl = mp.path.length(); if(normalizedPath.startsWith(mp.path) && (pl == mpl || normalizedPath.charAt(mpl) == '/')) return mp.fs.dispatch(op,r,pl == mpl ? "" : normalizedPath.substring(mpl+1),arg1,arg2); } } return root.dispatch(op,r,normalizedPath,arg1,arg2); } public final FD open(UnixRuntime r, String path, int flags, int mode) throws ErrnoException { return (FD) fsop(FS.OPEN,r,path,flags,mode); } public final FStat stat(UnixRuntime r, String path) throws ErrnoException { return (FStat) fsop(FS.STAT,r,path,0,0); } public final FStat lstat(UnixRuntime r, String path) throws ErrnoException { return (FStat) fsop(FS.LSTAT,r,path,0,0); } public final void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException { fsop(FS.MKDIR,r,path,mode,0); } public final void unlink(UnixRuntime r, String path) throws ErrnoException { fsop(FS.UNLINK,r,path,0,0); } private static class CacheEnt { public final long time; public final long size; public final Object o; public CacheEnt(long time, long size, Object o) { this.time = time; this.size = size; this.o = o; } } } public abstract static class FS { static final int OPEN = 1; static final int STAT = 2; static final int LSTAT = 3; static final int MKDIR = 4; static final int UNLINK = 5; GlobalState owner; int devno; Object dispatch(int op, UnixRuntime r, String path, int arg1, int arg2) throws ErrnoException { switch(op) { case OPEN: return open(r,path,arg1,arg2); case STAT: return stat(r,path); case LSTAT: return lstat(r,path); case MKDIR: mkdir(r,path,arg1); return null; case UNLINK: unlink(r,path); return null; default: throw new Error("should never happen"); } } public FStat lstat(UnixRuntime r, String path) throws ErrnoException { return stat(r,path); } // If this returns null it'll be truned into an ENOENT public abstract FD open(UnixRuntime r, String path, int flags, int mode) throws ErrnoException; // If this returns null it'll be turned into an ENOENT public abstract FStat stat(UnixRuntime r, String path) throws ErrnoException; public abstract void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException; public abstract void unlink(UnixRuntime r, String path) throws ErrnoException; } // chroot support should go in here if it is ever implemented private String normalizePath(String path) { boolean absolute = path.startsWith("/"); int cwdl = cwd.length(); // NOTE: This isn't just a fast path, it handles cases the code below doesn't if(!path.startsWith(".") && path.indexOf("./") == -1 && path.indexOf("//") == -1 && !path.endsWith(".")) return absolute ? path.substring(1) : cwdl == 0 ? path : path.length() == 0 ? cwd : cwd + "/" + path; char[] in = new char[path.length()+1]; char[] out = new char[in.length + (absolute ? -1 : cwd.length())]; path.getChars(0,path.length(),in,0); int inp=0, outp=0; if(absolute) { do { inp++; } while(in[inp] == '/'); } else if(cwdl != 0) { cwd.getChars(0,cwdl,out,0); outp = cwdl; } while(in[inp] != 0) { if(inp != 0) { while(in[inp] != 0 && in[inp] != '/') { out[outp++] = in[inp++]; } if(in[inp] == '\0') break; while(in[inp] == '/') inp++; } // Just read a / if(in[inp] == '\0') break; if(in[inp] != '.') { out[outp++] = '/'; out[outp++] = in[inp++]; continue; } // Just read a /. if(in[inp+1] == '\0' || in[inp+1] == '/') { inp++; continue; } if(in[inp+1] == '.' && (in[inp+2] == '\0' || in[inp+2] == '/')) { // .. // Just read a /..{$,/} inp += 2; if(outp > 0) outp--; while(outp > 0 && out[outp] != '/') outp--; //System.err.println("After ..: " + new String(out,0,outp)); continue; } // Just read a /.[^.] or /..[^/$] inp++; out[outp++] = '/'; out[outp++] = '.'; } if(outp > 0 && out[outp-1] == '/') outp--; //System.err.println("normalize: " + path + " -> " + new String(out,0,outp) + " (cwd: " + cwd + ")"); int outStart = out[0] == '/' ? 1 : 0; return new String(out,outStart,outp - outStart); } FStat hostFStat(final File f, Object data) { boolean e = false; try { FileInputStream fis = new FileInputStream(f); switch(fis.read()) { case '\177': e = fis.read() == 'E' && fis.read() == 'L' && fis.read() == 'F'; break; case '#': e = fis.read() == '!'; } fis.close(); } catch(IOException e2) { } HostFS fs = (HostFS) data; final int inode = fs.inodes.get(f.getAbsolutePath()); final int devno = fs.devno; return new HostFStat(f,e) { public int inode() { return inode; } public int dev() { return devno; } }; } FD hostFSDirFD(File f, Object _fs) { HostFS fs = (HostFS) _fs; return fs.new HostDirFD(f); } public static class HostFS extends FS { InodeCache inodes = new InodeCache(4000); protected File root; public File getRoot() { return root; } protected File hostFile(String path) { char sep = File.separatorChar; if(sep != '/') { char buf[] = path.toCharArray(); for(int i=0;i<buf.length;i++) { char c = buf[i]; if(c == '/') buf[i] = sep; else if(c == sep) buf[i] = '/'; } path = new String(buf); } return new File(root,path); } public HostFS(String root) { this(new File(root)); } public HostFS(File root) { this.root = root; } public FD open(UnixRuntime r, String path, int flags, int mode) throws ErrnoException { final File f = hostFile(path); return r.hostFSOpen(f,flags,mode,this); } public void unlink(UnixRuntime r, String path) throws ErrnoException { File f = hostFile(path); if(r.sm != null && !r.sm.allowUnlink(f)) throw new ErrnoException(EPERM); if(!f.exists()) throw new ErrnoException(ENOENT); if(!f.delete()) { // Can't delete file immediately, so mark for // delete on close all matching FDs boolean marked = false; for(int i=0;i<OPEN_MAX;i++) { if(r.fds[i] != null) { String fdpath = r.fds[i].getNormalizedPath(); if(fdpath != null && fdpath.equals(path)) { r.fds[i].markDeleteOnClose(); marked = true; } } } if(!marked) throw new ErrnoException(EPERM); } } public FStat stat(UnixRuntime r, String path) throws ErrnoException { File f = hostFile(path); if(r.sm != null && !r.sm.allowStat(f)) throw new ErrnoException(EACCES); if(!f.exists()) return null; return r.hostFStat(f,this); } public void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException { File f = hostFile(path); if(r.sm != null && !r.sm.allowWrite(f)) throw new ErrnoException(EACCES); if(f.exists() && f.isDirectory()) throw new ErrnoException(EEXIST); if(f.exists()) throw new ErrnoException(ENOTDIR); File parent = getParentFile(f); if(parent!=null && (!parent.exists() || !parent.isDirectory())) throw new ErrnoException(ENOTDIR); if(!f.mkdir()) throw new ErrnoException(EIO); } private static File getParentFile(File f) { String p = f.getParent(); return p == null ? null : new File(p); } public class HostDirFD extends DirFD { private final File f; private final File[] children; public HostDirFD(File f) { this.f = f; String[] l = f.list(); children = new File[l.length]; for(int i=0;i<l.length;i++) children[i] = new File(f,l[i]); } public int size() { return children.length; } public String name(int n) { return children[n].getName(); } public int inode(int n) { return inodes.get(children[n].getAbsolutePath()); } public int parentInode() { File parent = getParentFile(f); // HACK: myInode() isn't really correct if we're not the root return parent == null ? myInode() : inodes.get(parent.getAbsolutePath()); } public int myInode() { return inodes.get(f.getAbsolutePath()); } public int myDev() { return devno; } } } /* Implements the Cygwin notation for accessing MS Windows drive letters * in a unix path. The path /cygdrive/c/myfile is converted to C:\file. * As there is no POSIX standard for this, little checking is done. */ public static class CygdriveFS extends HostFS { protected File hostFile(String path) { final char drive = path.charAt(0); if (drive < 'a' || drive > 'z' || path.charAt(1) != '/') return null; path = drive + ":" + path.substring(1).replace('/', '\\'); return new File(path); } public CygdriveFS() { super("/"); } } private static void putInt(byte[] buf, int off, int n) { buf[off+0] = (byte)((n>>>24)&0xff); buf[off+1] = (byte)((n>>>16)&0xff); buf[off+2] = (byte)((n>>> 8)&0xff); buf[off+3] = (byte)((n>>> 0)&0xff); } public static abstract class DirFD extends FD { private int pos = -2; protected abstract int size(); protected abstract String name(int n); protected abstract int inode(int n); protected abstract int myDev(); protected abstract int parentInode(); protected abstract int myInode(); public int flags() { return O_RDONLY; } public int getdents(byte[] buf, int off, int len) { int ooff = off; int ino; int reclen; OUTER: for(;len > 0 && pos < size();pos++){ switch(pos) { case -2: case -1: ino = pos == -1 ? parentInode() : myInode(); if(ino == -1) continue; reclen = 9 + (pos == -1 ? 2 : 1); if(reclen > len) break OUTER; buf[off+8] = '.'; if(pos == -1) buf[off+9] = '.'; break; default: { String f = name(pos); byte[] fb = getBytes(f); reclen = fb.length + 9; if(reclen > len) break OUTER; ino = inode(pos); System.arraycopy(fb,0,buf,off+8,fb.length); } } buf[off+reclen-1] = 0; // null terminate reclen = (reclen + 3) & ~3; // add padding putInt(buf,off,reclen); putInt(buf,off+4,ino); off += reclen; len -= reclen; } return off-ooff; } protected FStat _fstat() { return new FStat() { public int type() { return S_IFDIR; } public int inode() { return myInode(); } public int dev() { return myDev(); } }; } } public static class DevFS extends FS { private static final int ROOT_INODE = 1; private static final int NULL_INODE = 2; private static final int ZERO_INODE = 3; private static final int FD_INODE = 4; private static final int FD_INODES = 32; private abstract class DevFStat extends FStat { public int dev() { return devno; } public int mode() { return 0666; } public int type() { return S_IFCHR; } public int nlink() { return 1; } public abstract int inode(); } private abstract class DevDirFD extends DirFD { public int myDev() { return devno; } } private FD devZeroFD = new FD() { public int read(byte[] a, int off, int length) { /*Arrays.fill(a,off,off+length,(byte)0);*/ for(int i=off;i<off+length;i++) a[i] = 0; return length; } public int write(byte[] a, int off, int length) { return length; } public int seek(int n, int whence) { return 0; } public FStat _fstat() { return new DevFStat(){ public int inode() { return ZERO_INODE; } }; } public int flags() { return O_RDWR; } }; private FD devNullFD = new FD() { public int read(byte[] a, int off, int length) { return 0; } public int write(byte[] a, int off, int length) { return length; } public int seek(int n, int whence) { return 0; } public FStat _fstat() { return new DevFStat(){ public int inode() { return NULL_INODE; } }; } public int flags() { return O_RDWR; } }; public FD open(UnixRuntime r, String path, int mode, int flags) throws ErrnoException { if(path.equals("null")) return devNullFD; if(path.equals("zero")) return devZeroFD; if(path.startsWith("fd/")) { int n; try { - n = Integer.parseInt(path.substring(4)); + n = Integer.parseInt(path.substring(3)); } catch(NumberFormatException e) { return null; } if(n < 0 || n >= OPEN_MAX) return null; if(r.fds[n] == null) return null; return r.fds[n].dup(); } if(path.equals("fd")) { int count=0; for(int i=0;i<OPEN_MAX;i++) if(r.fds[i] != null) { count++; } final int[] files = new int[count]; count = 0; for(int i=0;i<OPEN_MAX;i++) if(r.fds[i] != null) files[count++] = i; return new DevDirFD() { public int myInode() { return FD_INODE; } public int parentInode() { return ROOT_INODE; } public int inode(int n) { return FD_INODES + n; } public String name(int n) { return Integer.toString(files[n]); } public int size() { return files.length; } }; } if(path.equals("")) { return new DevDirFD() { public int myInode() { return ROOT_INODE; } // HACK: We don't have any clean way to get the parent inode public int parentInode() { return ROOT_INODE; } public int inode(int n) { switch(n) { case 0: return NULL_INODE; case 1: return ZERO_INODE; case 2: return FD_INODE; default: return -1; } } public String name(int n) { switch(n) { case 0: return "null"; case 1: return "zero"; case 2: return "fd"; default: return null; } } public int size() { return 3; } }; } return null; } public FStat stat(UnixRuntime r,String path) throws ErrnoException { if(path.equals("null")) return devNullFD.fstat(); if(path.equals("zero")) return devZeroFD.fstat(); if(path.startsWith("fd/")) { int n; try { n = Integer.parseInt(path.substring(3)); } catch(NumberFormatException e) { return null; } if(n < 0 || n >= OPEN_MAX) return null; if(r.fds[n] == null) return null; return r.fds[n].fstat(); } if(path.equals("fd")) return new FStat() { public int inode() { return FD_INODE; } public int dev() { return devno; } public int type() { return S_IFDIR; } public int mode() { return 0444; }}; if(path.equals("")) return new FStat() { public int inode() { return ROOT_INODE; } public int dev() { return devno; } public int type() { return S_IFDIR; } public int mode() { return 0444; }}; return null; } public void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException { throw new ErrnoException(EROFS); } public void unlink(UnixRuntime r, String path) throws ErrnoException { throw new ErrnoException(EROFS); } } public static class ResourceFS extends FS { final InodeCache inodes = new InodeCache(500); public FStat lstat(UnixRuntime r, String path) throws ErrnoException { return stat(r,path); } public void mkdir(UnixRuntime r, String path, int mode) throws ErrnoException { throw new ErrnoException(EROFS); } public void unlink(UnixRuntime r, String path) throws ErrnoException { throw new ErrnoException(EROFS); } FStat connFStat(final URLConnection conn) { return new FStat() { public int type() { return S_IFREG; } public int nlink() { return 1; } public int mode() { return 0444; } public int size() { return conn.getContentLength(); } public int mtime() { return (int)(conn.getDate() / 1000); } public int inode() { return inodes.get(conn.getURL().toString()); } public int dev() { return devno; } }; } public FStat stat(UnixRuntime r, String path) throws ErrnoException { URL url = r.getClass().getResource("/" + path); if(url == null) return null; try { return connFStat(url.openConnection()); } catch(IOException e) { throw new ErrnoException(EIO); } } public FD open(UnixRuntime r, String path, int flags, int mode) throws ErrnoException { if((flags & ~3) != 0) { if(STDERR_DIAG) System.err.println("WARNING: Unsupported flags passed to ResourceFS.open(\"" + path + "\"): " + toHex(flags & ~3)); throw new ErrnoException(ENOTSUP); } if((flags&3) != RD_ONLY) throw new ErrnoException(EROFS); URL url = r.getClass().getResource("/" + path); if(url == null) return null; try { final URLConnection conn = url.openConnection(); Seekable.InputStream si = new Seekable.InputStream(conn.getInputStream()); return new SeekableFD(si,flags) { protected FStat _fstat() { return connFStat(conn); } }; } catch(FileNotFoundException e) { if(e.getMessage() != null && e.getMessage().indexOf("Permission denied") >= 0) throw new ErrnoException(EACCES); return null; } catch(IOException e) { throw new ErrnoException(EIO); } } } }
false
false
null
null
diff --git a/src/com/restaurant/adapter/AreaCategoryListAdapter.java b/src/com/restaurant/adapter/AreaCategoryListAdapter.java index c47c35d..4e14d7a 100644 --- a/src/com/restaurant/adapter/AreaCategoryListAdapter.java +++ b/src/com/restaurant/adapter/AreaCategoryListAdapter.java @@ -1,76 +1,76 @@ package com.restaurant.adapter; import java.util.ArrayList; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.View.OnClickListener; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.restaurant.collection.CategoryActivity; import com.restaurant.collection.R; import com.restaurant.collection.entity.Area; import com.restaurant.collection.entity.Category; public class AreaCategoryListAdapter extends BaseAdapter { private final Activity activity; private final ArrayList<Category> data; private int area_id; private static LayoutInflater inflater = null; public AreaCategoryListAdapter(Activity a, ArrayList<Category> cs, int a_id) { activity = a; data = cs; area_id = a_id; inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } public int getCount() { return data.size(); } public Object getItem(int position) { return position; } public long getItemId(int position) { return position; } public View getView(final int position, View convertView, ViewGroup parent) { View vi = convertView; if (convertView == null) vi = inflater.inflate(R.layout.item_listview_category, null); TextView text = (TextView) vi.findViewById(R.id.text_list); text.setText(data.get(position).getName()); vi.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(activity, CategoryActivity.class); Bundle bundle = new Bundle(); bundle.putInt("SecondCategoryId", data.get(position).getId()); bundle.putInt("AreaId", area_id); intent.putExtras(bundle); activity.startActivity(intent); } }); - vi.setBackground(activity.getResources().getDrawable(R.drawable.restaurant_list_selector)); +// vi.setBackground(activity.getResources().getDrawable(R.drawable.restaurant_list_selector)); return vi; } } \ No newline at end of file diff --git a/src/com/restaurant/adapter/AreaListAdapter.java b/src/com/restaurant/adapter/AreaListAdapter.java index 36073b1..f46fc78 100755 --- a/src/com/restaurant/adapter/AreaListAdapter.java +++ b/src/com/restaurant/adapter/AreaListAdapter.java @@ -1,52 +1,52 @@ package com.restaurant.adapter; import java.util.ArrayList; import android.app.Activity; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.restaurant.collection.R; import com.restaurant.collection.entity.Area; public class AreaListAdapter extends BaseAdapter { private final Activity activity; private final ArrayList<Area> data; private static LayoutInflater inflater = null; public AreaListAdapter(Activity a, ArrayList<Area> areas) { activity = a; data = areas; inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } public int getCount() { return data.size(); } public Object getItem(int position) { return position; } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { View vi = convertView; if (convertView == null) vi = inflater.inflate(R.layout.item_listview_category, null); TextView text = (TextView) vi.findViewById(R.id.text_list); text.setText(data.get(position).getName()); - vi.setBackground(activity.getResources().getDrawable(R.drawable.restaurant_list_selector)); +// vi.setBackground(activity.getResources().getDrawable(R.drawable.restaurant_list_selector)); return vi; } } \ No newline at end of file diff --git a/src/com/restaurant/adapter/AreaTypeListAdapter.java b/src/com/restaurant/adapter/AreaTypeListAdapter.java index 76e983d..263adee 100644 --- a/src/com/restaurant/adapter/AreaTypeListAdapter.java +++ b/src/com/restaurant/adapter/AreaTypeListAdapter.java @@ -1,74 +1,74 @@ package com.restaurant.adapter; import java.util.ArrayList; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.View.OnClickListener; import android.widget.BaseAdapter; import android.widget.TextView; import com.restaurant.collection.CategoryActivity; import com.restaurant.collection.R; import com.restaurant.collection.entity.Type; public class AreaTypeListAdapter extends BaseAdapter { private Activity activity; private ArrayList<Type> data; private int area_id; private static LayoutInflater inflater = null; public AreaTypeListAdapter(Activity a, ArrayList<Type> cs, int a_id) { activity = a; data = cs; area_id = a_id; inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } public int getCount() { return data.size(); } public Object getItem(int position) { return position; } public long getItemId(int position) { return position; } public View getView(final int position, View convertView, ViewGroup parent) { View vi = convertView; if (convertView == null) vi = inflater.inflate(R.layout.item_listview_category, null); TextView text = (TextView) vi.findViewById(R.id.text_list); text.setText(data.get(position).getName()); vi.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(activity, CategoryActivity.class); Bundle bundle = new Bundle(); bundle.putInt("TypeId", data.get(position).getId()); bundle.putInt("AreaId", area_id); intent.putExtras(bundle); activity.startActivity(intent); } }); - vi.setBackground(activity.getResources().getDrawable(R.drawable.restaurant_list_selector)); +// vi.setBackground(activity.getResources().getDrawable(R.drawable.restaurant_list_selector)); return vi; } } \ No newline at end of file diff --git a/src/com/restaurant/adapter/CategoryListAdapter.java b/src/com/restaurant/adapter/CategoryListAdapter.java index 8f855df..6f76a12 100644 --- a/src/com/restaurant/adapter/CategoryListAdapter.java +++ b/src/com/restaurant/adapter/CategoryListAdapter.java @@ -1,53 +1,53 @@ package com.restaurant.adapter; import java.util.ArrayList; import android.app.Activity; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.restaurant.collection.R; import com.restaurant.collection.entity.Area; import com.restaurant.collection.entity.Category; public class CategoryListAdapter extends BaseAdapter { private final Activity activity; private final ArrayList<Category> data; private static LayoutInflater inflater = null; public CategoryListAdapter(Activity a, ArrayList<Category> cs) { activity = a; data = cs; inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } public int getCount() { return data.size(); } public Object getItem(int position) { return position; } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { View vi = convertView; if (convertView == null) vi = inflater.inflate(R.layout.item_listview_category, null); TextView text = (TextView) vi.findViewById(R.id.text_list); text.setText(data.get(position).getName()); - vi.setBackground(activity.getResources().getDrawable(R.drawable.restaurant_list_selector)); +// vi.setBackground(activity.getResources().getDrawable(R.drawable.restaurant_list_selector)); return vi; } } \ No newline at end of file
false
false
null
null
diff --git a/bundles/org.eclipse.equinox.simpleconfigurator/src/org/eclipse/equinox/internal/simpleconfigurator/ConfigApplier.java b/bundles/org.eclipse.equinox.simpleconfigurator/src/org/eclipse/equinox/internal/simpleconfigurator/ConfigApplier.java index 1e68b052f..0a88d093a 100644 --- a/bundles/org.eclipse.equinox.simpleconfigurator/src/org/eclipse/equinox/internal/simpleconfigurator/ConfigApplier.java +++ b/bundles/org.eclipse.equinox.simpleconfigurator/src/org/eclipse/equinox/internal/simpleconfigurator/ConfigApplier.java @@ -1,356 +1,356 @@ /******************************************************************************* * Copyright (c) 2007, 2009 IBM Corporation and others. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html * * Contributors: IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.equinox.internal.simpleconfigurator; import java.io.*; import java.net.URI; import java.net.URL; import java.util.*; import org.eclipse.equinox.internal.simpleconfigurator.utils.*; import org.osgi.framework.*; import org.osgi.service.packageadmin.PackageAdmin; import org.osgi.service.startlevel.StartLevel; class ConfigApplier { private static final String LAST_BUNDLES_INFO = "last.bundles.info"; //$NON-NLS-1$ private static final String PROP_DEVMODE = "osgi.dev"; //$NON-NLS-1$ private final BundleContext manipulatingContext; private final PackageAdmin packageAdminService; private final StartLevel startLevelService; private final boolean runningOnEquinox; private final boolean inDevMode; private final Bundle callingBundle; private final URI baseLocation; ConfigApplier(BundleContext context, Bundle callingBundle) { manipulatingContext = context; this.callingBundle = callingBundle; runningOnEquinox = "Eclipse".equals(context.getProperty(Constants.FRAMEWORK_VENDOR)); //$NON-NLS-1$ inDevMode = manipulatingContext.getProperty(PROP_DEVMODE) != null; baseLocation = runningOnEquinox ? EquinoxUtils.getInstallLocationURI(context) : null; ServiceReference packageAdminRef = manipulatingContext.getServiceReference(PackageAdmin.class.getName()); if (packageAdminRef == null) throw new IllegalStateException("No PackageAdmin service is available."); //$NON-NLS-1$ packageAdminService = (PackageAdmin) manipulatingContext.getService(packageAdminRef); ServiceReference startLevelRef = manipulatingContext.getServiceReference(StartLevel.class.getName()); if (startLevelRef == null) throw new IllegalStateException("No StartLevelService service is available."); //$NON-NLS-1$ startLevelService = (StartLevel) manipulatingContext.getService(startLevelRef); } void install(URL url, boolean exclusiveMode) throws IOException { List bundleInfoList = SimpleConfiguratorUtils.readConfiguration(url, baseLocation); if (Activator.DEBUG) System.out.println("applyConfiguration() bundleInfoList.size()=" + bundleInfoList.size()); if (bundleInfoList.size() == 0) return; BundleInfo[] expectedState = Utils.getBundleInfosFromList(bundleInfoList); HashSet toUninstall = null; if (!exclusiveMode) { BundleInfo[] lastInstalledBundles = getLastState(); if (lastInstalledBundles != null) { toUninstall = new HashSet(Arrays.asList(lastInstalledBundles)); toUninstall.removeAll(Arrays.asList(expectedState)); } saveStateAsLast(url); } Collection prevouslyResolved = getResolvedBundles(); Collection toRefresh = new ArrayList(); Collection toStart = new ArrayList(); if (exclusiveMode) { toRefresh.addAll(installBundles(expectedState, toStart)); toRefresh.addAll(uninstallBundles(expectedState, packageAdminService)); } else { toRefresh.addAll(installBundles(expectedState, toStart)); if (toUninstall != null) toRefresh.addAll(uninstallBundles(toUninstall)); } refreshPackages((Bundle[]) toRefresh.toArray(new Bundle[toRefresh.size()]), manipulatingContext); if (toRefresh.size() > 0) try { manipulatingContext.getBundle().loadClass("org.eclipse.osgi.service.resolver.PlatformAdmin"); //$NON-NLS-1$ // now see if there are any currently resolved bundles with option imports which could be resolved or // if there are fragments with additional constraints which conflict with an already resolved host Bundle[] additionalRefresh = StateResolverUtils.getAdditionalRefresh(prevouslyResolved, manipulatingContext); if (additionalRefresh.length > 0) refreshPackages(additionalRefresh, manipulatingContext); } catch (ClassNotFoundException cnfe) { // do nothing; no resolver package available } startBundles((Bundle[]) toStart.toArray(new Bundle[toStart.size()])); } private Collection getResolvedBundles() { Collection resolved = new HashSet(); Bundle[] allBundles = manipulatingContext.getBundles(); for (int i = 0; i < allBundles.length; i++) if ((allBundles[i].getState() & (Bundle.INSTALLED | Bundle.UNINSTALLED)) == 0) resolved.add(allBundles[i]); return resolved; } private Collection uninstallBundles(HashSet toUninstall) { Collection removedBundles = new ArrayList(toUninstall.size()); for (Iterator iterator = toUninstall.iterator(); iterator.hasNext();) { BundleInfo current = (BundleInfo) iterator.next(); Bundle[] matchingBundles = packageAdminService.getBundles(current.getSymbolicName(), getVersionRange(current.getVersion())); for (int j = 0; matchingBundles != null && j < matchingBundles.length; j++) { try { removedBundles.add(matchingBundles[j]); matchingBundles[j].uninstall(); } catch (BundleException e) { //TODO log in debug mode... } } } return removedBundles; } private void saveStateAsLast(URL url) { InputStream sourceStream = null; OutputStream destinationStream = null; File lastBundlesTxt = getLastBundleInfo(); try { try { destinationStream = new FileOutputStream(lastBundlesTxt); sourceStream = url.openStream(); SimpleConfiguratorUtils.transferStreams(sourceStream, destinationStream); } finally { if (destinationStream != null) destinationStream.close(); if (sourceStream != null) sourceStream.close(); } } catch (IOException e) { //nothing } } private File getLastBundleInfo() { return manipulatingContext.getDataFile(LAST_BUNDLES_INFO); } private BundleInfo[] getLastState() { File lastBundlesInfo = getLastBundleInfo(); if (!lastBundlesInfo.isFile()) return null; try { return (BundleInfo[]) SimpleConfiguratorUtils.readConfiguration(lastBundlesInfo.toURL(), baseLocation).toArray(new BundleInfo[1]); } catch (IOException e) { return null; } } private ArrayList installBundles(BundleInfo[] finalList, Collection toStart) { ArrayList toRefresh = new ArrayList(); String useReferenceProperty = manipulatingContext.getProperty(SimpleConfiguratorConstants.PROP_KEY_USE_REFERENCE); boolean useReference = useReferenceProperty == null ? runningOnEquinox : Boolean.valueOf(useReferenceProperty).booleanValue(); for (int i = 0; i < finalList.length; i++) { if (finalList[i] == null) continue; //TODO here we do not deal with bundles that don't have a symbolic id //TODO Need to handle the case where getBundles return multiple value String symbolicName = finalList[i].getSymbolicName(); String version = finalList[i].getVersion(); Bundle[] matches = null; if (symbolicName != null && version != null) matches = packageAdminService.getBundles(symbolicName, getVersionRange(version)); String bundleLocation = SimpleConfiguratorUtils.getBundleLocation(finalList[i], useReference); Bundle current = matches == null ? null : (matches.length == 0 ? null : matches[0]); if (current == null) { try { //TODO Need to eliminate System Bundle. // If a system bundle doesn't have a SymbolicName header, like Knopflerfish 4.0.0, // it will be installed unfortunately. current = manipulatingContext.installBundle(bundleLocation); if (Activator.DEBUG) System.out.println("installed bundle:" + finalList[i]); //$NON-NLS-1$ toRefresh.add(current); } catch (BundleException e) { if (Activator.DEBUG) { System.err.println("Can't install " + symbolicName + '/' + version + " from location " + finalList[i].getLocation()); //$NON-NLS-1$ //$NON-NLS-2$ e.printStackTrace(); } continue; } } else if (inDevMode && current.getBundleId() != 0 && current != manipulatingContext.getBundle() && !bundleLocation.equals(current.getLocation()) && !current.getLocation().startsWith("initial@")) { // We do not do this for the system bundle (id==0), the manipulating bundle or any bundle installed from the osgi.bundles list (locations starting with "@initial" // The bundle exists; but the location is different. Uninstall the current and install the new one (bug 229700) try { current.uninstall(); toRefresh.add(current); } catch (BundleException e) { if (Activator.DEBUG) { System.err.println("Can't uninstall " + symbolicName + '/' + version + " from location " + current.getLocation()); //$NON-NLS-1$ //$NON-NLS-2$ e.printStackTrace(); } continue; } try { current = manipulatingContext.installBundle(bundleLocation); if (Activator.DEBUG) System.out.println("installed bundle:" + finalList[i]); //$NON-NLS-1$ toRefresh.add(current); } catch (BundleException e) { if (Activator.DEBUG) { System.err.println("Can't install " + symbolicName + '/' + version + " from location " + finalList[i].getLocation()); //$NON-NLS-1$ //$NON-NLS-2$ e.printStackTrace(); } continue; } } // Mark Started if (finalList[i].isMarkedAsStarted()) { toStart.add(current); } // Set Start Level int startLevel = finalList[i].getStartLevel(); if (startLevel < 1) continue; if (current.getBundleId() == 0) continue; if (packageAdminService.getBundleType(current) == PackageAdmin.BUNDLE_TYPE_FRAGMENT) continue; if (SimpleConfiguratorConstants.TARGET_CONFIGURATOR_NAME.equals(current.getSymbolicName())) continue; try { startLevelService.setBundleStartLevel(current, startLevel); } catch (IllegalArgumentException ex) { Utils.log(4, null, null, "Failed to set start level of Bundle:" + finalList[i], ex); //$NON-NLS-1$ } } return toRefresh; } private void refreshPackages(Bundle[] bundles, BundleContext context) { if (bundles.length == 0 || packageAdminService == null) return; final boolean[] flag = new boolean[] {false}; FrameworkListener listener = new FrameworkListener() { public void frameworkEvent(FrameworkEvent event) { if (event.getType() == FrameworkEvent.PACKAGES_REFRESHED) { synchronized (flag) { flag[0] = true; flag.notifyAll(); } } } }; context.addFrameworkListener(listener); packageAdminService.refreshPackages(bundles); synchronized (flag) { while (!flag[0]) { try { flag.wait(); } catch (InterruptedException e) { //ignore } } } // if (DEBUG) { // for (int i = 0; i < bundles.length; i++) { // System.out.println(SimpleConfiguratorUtils.getBundleStateString(bundles[i])); // } // } context.removeFrameworkListener(listener); } private void startBundles(Bundle[] bundles) { for (int i = 0; i < bundles.length; i++) { Bundle bundle = bundles[i]; if (bundle.getState() == Bundle.STARTING && (bundle == callingBundle || bundle == manipulatingContext.getBundle())) continue; - if (bundle.getHeaders().get(Constants.FRAGMENT_HOST) != null) + if (packageAdminService.getBundleType(bundle) == PackageAdmin.BUNDLE_TYPE_FRAGMENT) continue; try { bundle.start(); if (Activator.DEBUG) System.out.println("started Bundle:" + bundle.getSymbolicName() + '(' + bundle.getLocation() + ':' + bundle.getBundleId() + ')'); //$NON-NLS-1$ } catch (BundleException e) { e.printStackTrace(); // FrameworkLogEntry entry = new FrameworkLogEntry(FrameworkAdaptor.FRAMEWORK_SYMBOLICNAME, NLS.bind(EclipseAdaptorMsg.ECLIPSE_STARTUP_FAILED_START, bundle.getLocation()), 0, e, null); // log.log(entry); } } } /** * Uninstall bundles which are not listed on finalList. * * @param finalList bundles list not to be uninstalled. * @param packageAdmin package admin service. * @return Collection HashSet of bundles finally installed. */ private Collection uninstallBundles(BundleInfo[] finalList, PackageAdmin packageAdmin) { Bundle[] allBundles = manipulatingContext.getBundles(); //Build a set with all the bundles from the system Set removedBundles = new HashSet(allBundles.length); // configurator.setPrerequisiteBundles(allBundles); for (int i = 0; i < allBundles.length; i++) { if (allBundles[i].getBundleId() == 0) continue; removedBundles.add(allBundles[i]); } //Remove all the bundles appearing in the final list from the set of installed bundles for (int i = 0; i < finalList.length; i++) { if (finalList[i] == null) continue; Bundle[] toAdd = packageAdmin.getBundles(finalList[i].getSymbolicName(), getVersionRange(finalList[i].getVersion())); for (int j = 0; toAdd != null && j < toAdd.length; j++) { removedBundles.remove(toAdd[j]); } } for (Iterator iter = removedBundles.iterator(); iter.hasNext();) { try { Bundle bundle = ((Bundle) iter.next()); if (bundle.getLocation().startsWith("initial@")) { if (Activator.DEBUG) System.out.println("Simple configurator thinks a bundle installed by the boot strap should be uninstalled:" + bundle.getSymbolicName() + '(' + bundle.getLocation() + ':' + bundle.getBundleId() + ')'); //$NON-NLS-1$ // Avoid uninstalling bundles that the boot strap code thinks should be installed (bug 232191) iter.remove(); continue; } bundle.uninstall(); if (Activator.DEBUG) System.out.println("uninstalled Bundle:" + bundle.getSymbolicName() + '(' + bundle.getLocation() + ':' + bundle.getBundleId() + ')'); //$NON-NLS-1$ } catch (BundleException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return removedBundles; } private String getVersionRange(String version) { return version == null ? null : new StringBuffer().append('[').append(version).append(',').append(version).append(']').toString(); } }
true
false
null
null
diff --git a/FireRwar/src/com/example/firerwar/DatabaseManager.java b/FireRwar/src/com/example/firerwar/DatabaseManager.java index 293bacc..06c3267 100644 --- a/FireRwar/src/com/example/firerwar/DatabaseManager.java +++ b/FireRwar/src/com/example/firerwar/DatabaseManager.java @@ -1,188 +1,188 @@ package com.example.firerwar; import java.util.ArrayList; import java.util.List; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; public class DatabaseManager extends SQLiteOpenHelper { private static final String DATABASE_NAME ="portdatabase"; private static final String TABLE_TCP = "tcp"; private static final String TABLE_UDP = "udp"; private static final int DATABASE_VERSION = 1; private static final int OPEN = 1; private static final int CLOSED = 0; private static final int TCP = 1; private static final int UDP = 0; public static final String PORT_KEY_ID = "_id"; public static final String PORT_NUM = "port_num"; public static final String PORT_STATUS = "status"; /*open or closed*/ public static final String DATABASE_DROP_TCP = "drop table if exists " + TABLE_TCP; public static final String DATABASE_DROP_UDP = "drop table if exists " + TABLE_UDP; public DatabaseManager(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } /*how to fix the problem * 1.) add all the ports */ @Override public void onCreate(SQLiteDatabase databoots) { //databoots = this.getWritableDatabase(); String CREATE_TCP_TABLE = "CREATE TABLE " + TABLE_TCP + " (" + PORT_KEY_ID + " INTEGER PRIMARY KEY, " + PORT_NUM + " INTEGER UNIQUE, " + PORT_STATUS+" INTEGER "+")"; String CREATE_UDP_TABLE = "CREATE TABLE " + TABLE_UDP + " (" + PORT_KEY_ID + " INTEGER PRIMARY KEY, " + PORT_NUM + " INTEGER UNIQUE, " + PORT_STATUS+" INTEGER "+")"; Log.d("Database","created table to databoots"); databoots.execSQL(CREATE_TCP_TABLE); databoots.execSQL(CREATE_UDP_TABLE); } @Override public void onUpgrade(SQLiteDatabase databoots, int oldVersion, int newVersion) { Log.w("DatabaseManager.java", "Database being upgraded from " + Integer.toString(oldVersion) +" to " + Integer.toString(newVersion)); databoots.execSQL(DATABASE_DROP_TCP); databoots.execSQL(DATABASE_DROP_UDP); onCreate(databoots); } /*add status to this*/ public void addPort(int port,int port_status,int portType) { SQLiteDatabase databoots = this.getWritableDatabase(); ContentValues vals = new ContentValues(); vals.put(PORT_NUM, port); vals.put(PORT_STATUS,port_status); Log.d("Database","added port to databoots"); if(TCP == portType) { databoots.insert(TABLE_TCP, null, vals); } else if(UDP == portType) { databoots.insert(TABLE_UDP, null, vals); } databoots.close(); } public int getPort (int id,int portType) { SQLiteDatabase databoots = this.getReadableDatabase(); Cursor cursor = null; if (TCP == portType) { cursor = databoots.query(TABLE_TCP, new String[] {PORT_KEY_ID,PORT_NUM}, PORT_KEY_ID + "=?",new String[] {String.valueOf(id)},null,null,null,null); } else if (UDP == portType) { cursor = databoots.query(TABLE_UDP, new String[] {PORT_KEY_ID,PORT_NUM}, PORT_KEY_ID + "=?",new String[] {String.valueOf(id)},null,null,null,null); } if (cursor != null) cursor.moveToFirst(); /* retrieves the port number and returns it */ return cursor.getInt(1); } /*need to appened more data so you can see what type of port */ public ArrayList<String> getAllPorts(int portType) { /*Might need to be writable, but not sure why*/ SQLiteDatabase databoots = this.getReadableDatabase(); ArrayList<String> portList = new ArrayList<String>(); String selection = null; if(TCP == portType) { selection = "select * from "+ TABLE_TCP; } else if(UDP == portType) { selection = "select * from "+ TABLE_UDP; } Cursor cursor = databoots.rawQuery(selection, null); if(cursor !=null && cursor.moveToFirst()){ do { if(cursor.getInt(2) == OPEN) { - portList.add(Integer.toString(cursor.getInt(1))+" OPEN"); + portList.add(Integer.toString(cursor.getInt(1))+" opened"); } else if(cursor.getInt(2) == CLOSED) { - portList.add(Integer.toString(cursor.getInt(1))+" CLOSED"); + portList.add(Integer.toString(cursor.getInt(1))+" blocked"); } }while (cursor.moveToNext()); } return portList; } /*Change this so that it updates the ports from open to closed or vise versa*/ public int updatePortStatus(int port,int port_type,int port_status) { SQLiteDatabase databoots = this.getWritableDatabase(); int dataReturned = -1; ContentValues vals = new ContentValues(); vals.put(PORT_STATUS, port_status); /* might need the id in the list for this value, i believe we can find it, but * really there should only ever be a need to update a port status * not a port*/ if(TCP == port_type) { dataReturned = databoots.update(TABLE_TCP, vals, PORT_NUM+ " = ?", new String[] {Integer.toString(port)}); } else if (UDP == port_type) { dataReturned = databoots.update(TABLE_UDP, vals, PORT_NUM+ " = ?", new String[] {Integer.toString(port)}); } return dataReturned; } public void deletePort (int delPort,int port_type) { SQLiteDatabase databoots = this.getWritableDatabase(); if (port_type == TCP) { databoots.delete(TABLE_TCP, PORT_NUM+ " = ?", new String[] {String.valueOf(delPort)}); } else if (port_type == UDP) { databoots.delete(TABLE_UDP, PORT_NUM+ " = ?", new String[] {String.valueOf(delPort)}); } } public int getPortCount (int port_type) { SQLiteDatabase databoots = this.getReadableDatabase(); String numPorts = ""; if(port_type == TCP) { numPorts = "SELECT * FROM " + TABLE_TCP; } else if (port_type == UDP) { numPorts = "SELECT * FROM " + TABLE_UDP; } Cursor cursor = databoots.rawQuery(numPorts, null); return cursor.getCount(); } } diff --git a/FireRwar/src/com/example/firerwar/portBlocker.java b/FireRwar/src/com/example/firerwar/portBlocker.java index e85f36a..2f51e67 100644 --- a/FireRwar/src/com/example/firerwar/portBlocker.java +++ b/FireRwar/src/com/example/firerwar/portBlocker.java @@ -1,542 +1,543 @@ package com.example.firerwar; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList; import android.content.Context; import android.content.res.Configuration; import android.database.sqlite.SQLiteDatabase; import android.net.DhcpInfo; import android.net.wifi.WifiManager; import android.os.Bundle; import android.speech.tts.TextToSpeech.OnUtteranceCompletedListener; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AdapterView.*; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; public class portBlocker extends Fragment { ServerSocket sock; Socket temp; public EditText portText; public ArrayList<String> tcpViewText; public ArrayList<String> udpViewText; public ArrayList<String> tcpFilterList; public ArrayList<String> udpFilterList; public ArrayAdapter<String> adapter; public ArrayAdapter<String> adapter2; protected TextView tcpDisplay; protected TextView udpDisplay; protected LinearLayout tempView; protected ListView tcpPortsList; protected ListView udpPortsList; protected Button closeTCPButton; protected Button openTCPButton; protected Button closeUDPButton; protected Button openUDPButton; protected View rootView; Context mContext; protected int greenText; protected int redText; protected static final int FILTER_SHOW_ALL = 0; protected static final int FILTER_OPEN = 1; protected static final int FILTER_CLOSE = 2; protected static final int TCP = 1; protected static final int UDP = 0; protected static final int OPEN = 1; protected static final int CLOSED = 0; public static final String ARG_SECTION_NUMBER = "BOOP"; DatabaseManager db; @Override public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); db = new DatabaseManager(mContext); } public void setContext(Context mContext) { this.mContext = mContext; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { rootView = inflater.inflate(R.layout.port_enter, container, false); greenText = R.color.openGreen; redText = R.color.blockRed; try { System.out.println("derp"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } initLayout(); return printNetworkSettings(mContext); } protected void initLayout() { tcpDisplay = (TextView) rootView.findViewById(R.id.TCPports); udpDisplay = (TextView) rootView.findViewById(R.id.UDPports); tempView = (LinearLayout) rootView.findViewById(R.id.LinearPortHolder); tcpPortsList = (ListView) rootView.findViewById(R.id.PortItems); udpPortsList = (ListView) rootView.findViewById(R.id.UDPItems); closeTCPButton = (Button) rootView.findViewById(R.id.portClosedButton); openTCPButton = (Button) rootView.findViewById(R.id.portOpenButton); closeUDPButton = (Button)rootView.findViewById(R.id.UDPcloseButton); openUDPButton = (Button)rootView.findViewById(R.id.UDPopenButton); portText = (EditText) rootView.findViewById(R.id.portText); portText.setRawInputType(Configuration.KEYBOARD_12KEY); tcpViewText = new ArrayList<String>(); udpViewText = new ArrayList<String>(); tcpFilterList = new ArrayList<String>(); udpFilterList = new ArrayList<String>(); tcpDisplay.setText("TCP Ports"); udpDisplay.setText("UDP Ports"); adapter = new ArrayAdapter<String>(mContext, android.R.layout.simple_list_item_1, tcpFilterList); adapter2 = new ArrayAdapter<String>(mContext, android.R.layout.simple_list_item_1, udpFilterList); int i = 0; ArrayList<String> temp = db.getAllPorts(TCP); while(temp.size() != i){ tcpViewText.add(temp.get(i)); tcpFilterList.add(temp.get(i)); try { //TODO have it either open or close the port and parse the string that comes out. blockporttcp(Integer.parseInt(temp.get(i))); } catch (NumberFormatException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } i++; } + i = 0; temp = db.getAllPorts(UDP); while(temp.size() != i){ udpViewText.add(temp.get(i)); udpFilterList.add(temp.get(i)); try { //TODO have it either open or close the port blockportudp(Integer.parseInt(temp.get(i))); } catch (NumberFormatException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } i++; } tcpPortsList.setAdapter(adapter); udpPortsList.setAdapter(adapter2); } public void blockporttcp(final int port) throws IOException { temp = new Socket(); db.addPort(port,CLOSED,TCP); try { new Thread(new Runnable() { @Override public void run() { try { if (!sock.isClosed()) { if (!sock.isBound()) { sock = new ServerSocket(port); sock.close(); } else sock.close(); } } catch (Exception e) { System.out.println("thread blockport failed" + e); } // } } }).start(); } catch (Exception e) { Log.d("blockport Exception", "" + e); } } public void blockportudp(final int port) throws IOException { temp = new Socket(); db.addPort(port,CLOSED,UDP); try { new Thread(new Runnable() { @Override public void run() { try { if (!sock.isClosed()) { if (!sock.isBound()) { sock = new ServerSocket(port); sock.close(); } else sock.close(); } } catch (Exception e) { System.out.println("thread blockport failed" + e); } // } } }).start(); } catch (Exception e) { Log.d("blockport Exception", "" + e); } } public void openporttcp(final int port) throws IOException { sock = new ServerSocket(); db.addPort(port,OPEN,TCP); try { new Thread(new Runnable() { @Override public void run() { try { if (!sock.isBound()) { sock = new ServerSocket(port); sock.accept(); } } catch (Exception e) { System.out.println("thread openport failed: " + e); } } }).start(); } catch (Exception e) { Log.d("openport Exception", "" + e); } } public void openportudp(final int port) throws IOException { sock = new ServerSocket(); db.addPort(port,OPEN,UDP); try { new Thread(new Runnable() { @Override public void run() { try { if (!sock.isBound()) { sock = new ServerSocket(port); sock.accept(); } } catch (Exception e) { System.out.println("thread openport failed: " + e); } } }).start(); } catch (Exception e) { Log.d("openport Exception", "" + e); } } @Override public void onStart() { setHasOptionsMenu(true); super.onStart(); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { if (inflater != null) { inflater.inflate(R.menu.ports_menu, menu); } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_open: filterList(FILTER_OPEN); return true; case R.id.menu_close: filterList(FILTER_CLOSE); return true; case R.id.menu_all: filterList(FILTER_SHOW_ALL); return true; default: return super.onOptionsItemSelected(item); } } private void filterList(int filter) { int i; tcpFilterList.clear(); udpFilterList.clear(); switch (filter) { case FILTER_OPEN: for (i = 0; i < tcpViewText.size(); i++) { if (tcpViewText.get(i).contains("opened")) { tcpFilterList.add(tcpViewText.get(i)); } } for (i = 0; i < udpViewText.size(); i++) { if (udpViewText.get(i).contains("opened")) { udpFilterList.add(udpViewText.get(i)); } } break; case FILTER_CLOSE: for (i = 0; i < tcpViewText.size(); i++) { if (tcpViewText.get(i).contains("blocked")) { tcpFilterList.add(tcpViewText.get(i)); } } for (i = 0; i < udpViewText.size(); i++) { if (udpViewText.get(i).contains("blocked")) { udpFilterList.add(udpViewText.get(i)); } } break; case FILTER_SHOW_ALL: for (i = 0; i < tcpViewText.size(); i++) { tcpFilterList.add(tcpViewText.get(i)); } for (i = 0; i < udpViewText.size(); i++) { udpFilterList.add(udpViewText.get(i)); } break; } adapter.notifyDataSetChanged(); adapter2.notifyDataSetChanged(); } public View printNetworkSettings(Context mContext) { closeTCPButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { String portHold = portText.getText().toString(); int i; try { int port = Integer.parseInt(portHold); for (i = 0; i < tcpViewText.size(); i++) { if (tcpViewText.get(i).contains(portHold)) { tcpViewText.remove(i); break; } } for (i = 0; i < tcpFilterList.size(); i++) { if (tcpFilterList.get(i).contains(portHold)) { tcpFilterList.remove(i); break; } } tcpViewText.add(portHold + " closed"); tcpFilterList.add(portHold + " closed"); adapter.notifyDataSetChanged(); // TODO add error checking for the above here and below here //to notify the user that something went wrong with blocking the port. //there should probably be error checking else where as well. blockporttcp(port); } catch (IOException e) { System.out.println(e + " failed in block port"); } catch (Exception e) { System.out.println("failed in int conversion: " + e); } } }); openTCPButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { String portHold = portText.getText().toString(); int i; try { int port = Integer.parseInt(portHold); for (i = 0; i < tcpViewText.size(); i++) { if (tcpViewText.get(i).contains(portHold)) { tcpViewText.remove(i); break; } } for (i = 0; i < tcpFilterList.size(); i++) { if (tcpFilterList.get(i).contains(portHold)) { tcpFilterList.remove(i); break; } } tcpViewText.add(portHold + " opened"); tcpFilterList.add(portHold + " opened"); adapter.notifyDataSetChanged(); // TODO add error checking for the above here openporttcp(port); } catch (IOException e) { // TODO Auto-generated catch block System.out.println(e + " failed in open port"); } catch (Exception e) { System.out.println("failed in open int conversion: " + e); } } }); closeUDPButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { String portHold = portText.getText().toString(); int i; try { int port = Integer.parseInt(portHold); for (i = 0; i < udpViewText.size(); i++) { if (udpViewText.get(i).contains(portHold)) { udpViewText.remove(i); break; } } for (i = 0; i < udpFilterList.size(); i++) { if (udpFilterList.get(i).contains(portHold)) { udpFilterList.remove(i); break; } } udpViewText.add(portHold + " blocked"); udpFilterList.add(portHold + " blocked"); adapter2.notifyDataSetChanged(); // TODO add error checking for the above here blockportudp(port); } catch (IOException e) { System.out.println(e + " failed in block port"); } catch (Exception e) { System.out.println("failed in int conversion: " + e); } } }); openUDPButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { String portHold = portText.getText().toString(); int i; try { int port = Integer.parseInt(portHold); for (i = 0; i < udpViewText.size(); i++) { if (udpViewText.get(i).contains(portHold)) { udpViewText.remove(i); break; } } for (i = 0; i < udpFilterList.size(); i++) { if (udpFilterList.get(i).contains(portHold)) { udpFilterList.remove(i); break; } } udpViewText.add(portHold + " opened"); udpFilterList.add(portHold + " opened"); adapter2.notifyDataSetChanged(); // TODO add error checking for the above here openportudp(port); } catch (IOException e) { System.out.println(e + " failed in open port"); } catch (Exception e) { System.out.println("failed in open int conversion: " + e); } } }); adapter.notifyDataSetChanged(); adapter2.notifyDataSetChanged(); return tempView; } }
false
false
null
null
diff --git a/proton-j/src/main/java/org/apache/qpid/proton/engine/impl/ConnectionImpl.java b/proton-j/src/main/java/org/apache/qpid/proton/engine/impl/ConnectionImpl.java index 72aedb85..8f0893f2 100644 --- a/proton-j/src/main/java/org/apache/qpid/proton/engine/impl/ConnectionImpl.java +++ b/proton-j/src/main/java/org/apache/qpid/proton/engine/impl/ConnectionImpl.java @@ -1,387 +1,407 @@ /* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.qpid.proton.engine.impl; import java.util.ArrayList; import java.util.EnumSet; import java.util.List; import org.apache.qpid.proton.engine.*; import org.apache.qpid.proton.type.transport.Open; public class ConnectionImpl extends EndpointImpl implements Connection { public static final int MAX_CHANNELS = 255; private TransportFactory _transportFactory = TransportFactory.getDefaultTransportFactory(); private TransportImpl _transport; private List<SessionImpl> _sessions = new ArrayList<SessionImpl>(); private EndpointImpl _transportTail; private EndpointImpl _transportHead; private int _maxChannels = MAX_CHANNELS; private LinkNode<SessionImpl> _sessionHead; private LinkNode<SessionImpl> _sessionTail; private LinkNode<LinkImpl> _linkHead; private LinkNode<LinkImpl> _linkTail; private DeliveryImpl _workHead; private DeliveryImpl _workTail; private DeliveryImpl _transportWorkHead; private DeliveryImpl _transportWorkTail; private String _localContainerId = ""; public ConnectionImpl() { _transportFactory = TransportFactory.getDefaultTransportFactory(); } public SessionImpl session() { SessionImpl session = new SessionImpl(this); _sessions.add(session); return session; } protected LinkNode<SessionImpl> addSessionEndpoint(SessionImpl endpoint) { LinkNode<SessionImpl> node; if(_sessionHead == null) { node = _sessionHead = _sessionTail = LinkNode.newList(endpoint); } else { node = _sessionTail = _sessionTail.addAtTail(endpoint); } return node; } void removeSessionEndpoint(LinkNode<SessionImpl> node) { LinkNode<SessionImpl> prev = node.getPrev(); LinkNode<SessionImpl> next = node.getNext(); if(_sessionHead == node) { _sessionHead = next; } if(_sessionTail == node) { _sessionTail = prev; } node.remove(); } protected LinkNode<LinkImpl> addLinkEndpoint(LinkImpl endpoint) { LinkNode<LinkImpl> node; if(_linkHead == null) { node = _linkHead = _linkTail = LinkNode.newList(endpoint); } else { node = _linkTail = _linkTail.addAtTail(endpoint); } return node; } void removeLinkEndpoint(LinkNode<LinkImpl> node) { LinkNode<LinkImpl> prev = node.getPrev(); LinkNode<LinkImpl> next = node.getNext(); if(_linkHead == node) { _linkHead = next; } if(_linkTail == node) { _linkTail = prev; } node.remove(); } public Transport transport() { if(_transport == null) { _transport = (TransportImpl) _transportFactory.transport(this); } else { // todo - should error } return _transport; } public Session sessionHead(final EnumSet<EndpointState> local, final EnumSet<EndpointState> remote) { if(_sessionHead == null) { return null; } else { LinkNode.Query<SessionImpl> query = new EndpointImplQuery<SessionImpl>(local, remote); LinkNode<SessionImpl> node = query.matches(_sessionHead) ? _sessionHead : _sessionHead.next(query); return node == null ? null : node.getValue(); } } public Link linkHead(EnumSet<EndpointState> local, EnumSet<EndpointState> remote) { if(_linkHead == null) { return null; } else { LinkNode.Query<LinkImpl> query = new EndpointImplQuery<LinkImpl>(local, remote); LinkNode<LinkImpl> node = query.matches(_linkHead) ? _linkHead : _linkHead.next(query); return node == null ? null : node.getValue(); } } @Override protected ConnectionImpl getConnectionImpl() { return this; } public void free() { super.free(); for(Session session : _sessions) { session.free(); } _sessions = null; if(_transport != null) { _transport.free(); } } void clearTransport() { _transport = null; } public void handleOpen(Open open) { // TODO - store state setRemoteState(EndpointState.ACTIVE); } EndpointImpl getTransportHead() { return _transportHead; } EndpointImpl getTransportTail() { return _transportTail; } void addModified(EndpointImpl endpoint) { + dumpList(_transportHead); + if(_transportTail == null) { + endpoint.setTransportNext(null); + endpoint.setTransportPrev(null); _transportHead = _transportTail = endpoint; } else { _transportTail.setTransportNext(endpoint); endpoint.setTransportPrev(_transportTail); _transportTail = endpoint; + _transportTail.setTransportNext(null); + } + + dumpList(_transportHead); + } + + private void dumpList(EndpointImpl _transportHead) + { + StringBuffer buf = new StringBuffer(); + EndpointImpl p = _transportHead; + while (p != null) + { + buf.append(p + "->"); + p = p.transportNext(); } + System.out.println(buf.toString()); } void removeModified(EndpointImpl endpoint) { if(_transportHead == endpoint) { _transportHead = endpoint.transportNext(); } else { endpoint.transportPrev().setTransportNext(endpoint.transportNext()); } if(_transportTail == endpoint) { _transportTail = endpoint.transportPrev(); } else { endpoint.transportNext().setTransportPrev(endpoint.transportPrev()); } + dumpList(_transportHead); } public int getMaxChannels() { return _maxChannels; } public EndpointImpl next() { return getNext(); } public String getLocalContainerId() { return _localContainerId; } public void setLocalContainerId(String localContainerId) { _localContainerId = localContainerId; } public DeliveryImpl getWorkHead() { return _workHead; } DeliveryImpl getWorkTail() { return _workTail; } void removeWork(DeliveryImpl delivery) { if(_workHead == delivery) { _workHead = delivery.getWorkNext(); } if(_workTail == delivery) { _workTail = delivery.getWorkPrev(); } } void addWork(DeliveryImpl delivery) { if(_workHead != delivery && delivery.getWorkNext() == null && delivery.getWorkPrev() == null) { if(_workTail == null) { _workHead = _workTail = delivery; } else { _workTail.setWorkNext(delivery); delivery.setWorkPrev(_workTail); _workTail = delivery; } } } public Sequence<DeliveryImpl> getWorkSequence() { return new WorkSequence(_workHead); } private class WorkSequence implements Sequence<DeliveryImpl> { private DeliveryImpl _next; public WorkSequence(DeliveryImpl workHead) { _next = workHead; } public DeliveryImpl next() { DeliveryImpl next = _next; if(next != null) { _next = next.getWorkNext(); } return next; } } DeliveryImpl getTransportWorkHead() { return _transportWorkHead; } public void removeTransportWork(DeliveryImpl delivery) { DeliveryImpl oldHead = _transportWorkHead; DeliveryImpl oldTail = _transportWorkTail; if(_transportWorkHead == delivery) { _transportWorkHead = delivery.getTransportWorkNext(); } if(_transportWorkTail == delivery) { _transportWorkTail = delivery.getTransportWorkPrev(); } } void addTransportWork(DeliveryImpl delivery) { if(_transportWorkTail == null) { _transportWorkHead = _transportWorkTail = delivery; } else { _transportWorkTail.setTransportWorkNext(delivery); delivery.setTransportWorkPrev(_transportWorkTail); _transportWorkTail = delivery; } } void workUpdate(DeliveryImpl delivery) { if(delivery != null) { LinkImpl link = delivery.getLink(); if(link.workUpdate(delivery)) { addWork(delivery); } else { delivery.clearWork(); } } } }
false
false
null
null
diff --git a/src/com/andoutay/egorep/eGODBManager.java b/src/com/andoutay/egorep/eGODBManager.java index 683717a..fc16239 100644 --- a/src/com/andoutay/egorep/eGODBManager.java +++ b/src/com/andoutay/egorep/eGODBManager.java @@ -1,456 +1,459 @@ package com.andoutay.egorep; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.SQLSyntaxErrorException; import org.bukkit.ChatColor; import org.bukkit.scheduler.BukkitScheduler; public class eGODBManager { private eGORep plugin; private BukkitScheduler scheduler; public eGODBManager(eGORep plugin) { this.plugin = plugin; this.scheduler = plugin.getServer().getScheduler(); } public static Connection getSQLConnection() { Connection con; try { con = DriverManager.getConnection(eGORepConfig.sqlURL, eGORepConfig.sqlUser, eGORepConfig.sqlPassword); return con; } catch (SQLSyntaxErrorException e) { eGORep.log.info(eGORep.logPref + "Falling back on DB URL w/out database"); try { con = DriverManager.getConnection(eGORepConfig.shortSQLURL, eGORepConfig.sqlUser, eGORepConfig.sqlPassword); return con; } catch (SQLException f) { f.printStackTrace(); } } catch (SQLException e) { } return null; } public void setAll(String name, double rep, int points, final Long timestamp) { setRep(name, rep); setRemPoints(name, points); setTime(name, timestamp); } public void setVal(String dbField, String name, double val, String type) { Connection con = getSQLConnection(); PreparedStatement stmt = null; String q = "UPDATE " + eGORepConfig.sqlTableName + " SET " + dbField + " = ? WHERE `IGN` = ?"; int success = 0; try { stmt = con.prepareStatement(q); if (type == "int") stmt.setInt(1, (int)val); else if (type == "long") stmt.setLong(1, (long)val); else if (type == "double") stmt.setDouble(1, val); stmt.setString(2, name); success = stmt.executeUpdate(); stmt.close(); } catch (SQLException e) { } catch (NullPointerException e) { if (dbField.equalsIgnoreCase("rep")) eGORep.log.severe(eGORep.logPref + "Could not connect to database. Please check that the MySQL Server is running"); success = 1; } if (success < 1) { fixFringeCases(con, name, dbField); } } public Long getLong(String dbField, String name) { Connection con = getSQLConnection(); PreparedStatement stmt = null; String q = "SELECT " + dbField + " FROM " + eGORepConfig.sqlTableName + " WHERE `IGN` = ?"; ResultSet result; Long ans = (long)0; try { stmt = con.prepareStatement(q); stmt.setString(1, name); result = stmt.executeQuery(); if (result.next()) ans = result.getLong(dbField); stmt.close(); } catch (SQLException e) { } catch (NullPointerException e) { } return ans; } public Object getVal(String dbField, String name) { Connection con = getSQLConnection(); PreparedStatement stmt = null; String q = "SELECT " + dbField + " FROM " + eGORepConfig.sqlTableName + " WHERE `IGN` = ?"; ResultSet result; int success = 0; Object ans = null; try { stmt = con.prepareStatement(q); stmt.setString(1, name); result = stmt.executeQuery(); if (result.next()) success = 1; ans = result.getObject(dbField); stmt.close(); } catch (SQLException e) { } catch (NullPointerException e) { if (dbField.equalsIgnoreCase("rep")) eGORep.log.severe(eGORep.logPref + "Could not connect to database. Please check that the MySQL Server is running"); success = 1; } if (success < 1) fixFringeCases(con, name, dbField); + if (ans == null) + ans = new Double(0); + return ans; } public void setRep(final String name, final double rep) { if (eGORepConfig.useAsync) { scheduler.runTaskAsynchronously(plugin, new Runnable() { public void run() { setVal("rep", name, rep, "double"); } }); } else setVal("rep", name, rep, "double"); } public void setRemPoints(final String name, final int points) { if (eGORepConfig.useAsync) { scheduler.runTaskAsynchronously(plugin, new Runnable() { public void run() { setVal("points", name, points, "int"); } }); } else setVal("points", name, points, "int"); } public void setTime(final String name, final Long timestamp) { if (eGORepConfig.useAsync) { scheduler.runTaskAsynchronously(plugin, new Runnable() { public void run() { setVal("time", name, timestamp, "long"); } }); } else setVal("time", name, timestamp, "long"); } public double getRep(final String name) { return (Double)getVal("rep", name); } public int getRemPoints(String name) { return (Integer)getVal("points", name); } public Long getTime(String name) { return (Long)getVal("time", name); } private void fixFringeCases(Connection con, String name, String dbField) { if (eGORepConfig.sqlDBName.equalsIgnoreCase("")) eGORep.log.severe(eGORep.logPref + "Database name is blank! Edit config.yml to include a database name"); else if (eGORepConfig.sqlTableName.equalsIgnoreCase("")) eGORep.log.severe(eGORep.logPref + "Table name is blank! Edit config.yml to include a table name"); else { PreparedStatement stmt = null; int success = 0, i, j; String q; int insVal = 0; if (dbField.equalsIgnoreCase("points")) insVal = 3; for (i = 0; i < 2; i++) { success = 0; q = "INSERT INTO " + eGORepConfig.sqlTableName + " (`IGN`, `" + dbField + "`) VALUES (?, ?)"; try { stmt = con.prepareStatement(q); stmt.setString(1, name); stmt.setLong(2, insVal); success = stmt.executeUpdate(); stmt.close(); //break out of loop - we're done i = 2; } catch (SQLException e) { eGORep.log.warning(eGORep.logPref + "Could not add " + name + " to the database"); } if (success < 1 && i < 1) { for (j = 0; j < 2; j++) { success = 0; eGORep.log.info(eGORep.logPref + "Attempting to create table " + eGORepConfig.sqlTableName); q = "CREATE TABLE IF NOT EXISTS `" + eGORepConfig.sqlTableName + "` (`IGN` varchar(128) COLLATE utf8_unicode_ci NOT NULL, `rep` double NOT NULL DEFAULT '0', `points` int(11) NOT NULL DEFAULT '3', `time` bigint(20) NOT NULL DEFAULT '0', PRIMARY KEY (`IGN`)) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;"; try { stmt = con.prepareStatement(q); success = stmt.executeUpdate(); stmt.close(); eGORep.log.info("Created table " + eGORepConfig.sqlTableName); //break out of loop -- we're done j = 2; } catch (SQLException e) { eGORep.log.warning(eGORep.logPref + "Could not create table " + eGORepConfig.sqlTableName + "."); } if (success < 1 && j < 1) { success = 0; eGORep.log.info(eGORep.logPref + "Attempting to create database " + eGORepConfig.sqlDBName); q = "CREATE DATABASE IF NOT EXISTS `" + eGORepConfig.sqlDBName + "` ;"; try { stmt = con.prepareStatement(q); success = stmt.executeUpdate(); stmt.close(); eGORep.log.info(eGORep.logPref + "Created database " + eGORepConfig.sqlDBName); //re-get the connection so it will have the database this time con = getSQLConnection(); } catch (SQLException e) { eGORep.log.severe(eGORep.logPref + "Could not create user, table or database. Please check your config.yml and database setup."); e.printStackTrace(); } //nothing we tried worked - may as well exit the loops if (success < 1) { i = 2; j = 2; } } } } else i = 2; } } } public static void addLogEntry(String repper, String recipient, double amt, String direction) { Connection con = getSQLConnection(); PreparedStatement stmt = null; String q = "INSERT INTO " + eGORepConfig.sqlLogTableName + " (repper, recipient, amt, direction) VALUES (?, ?, ?, ?)"; for (int i = 0; i < 2; i++) { try { stmt = con.prepareStatement(q); stmt.setString(1, repper); stmt.setString(2, recipient); stmt.setDouble(3, amt); stmt.setString(4, direction); stmt.executeUpdate(); stmt.close(); i = 2; } catch (SQLException e) { createLogTable(); } } } public static String getLogEntry(String repper, String direction, int startIndex) { String ans = ""; Connection con = getSQLConnection(); ResultSet result; PreparedStatement stmt = null; String q = "SELECT * FROM " + eGORepConfig.sqlLogTableName; if (repper != null) q += " WHERE `repper`=? AND `direction`=?"; q += " ORDER BY time DESC LIMIT " + startIndex + ", " + 10; try { stmt = con.prepareStatement(q); if (repper != null) { stmt.setString(1, repper); stmt.setString(2, direction); } result = stmt.executeQuery(); while (result.next()) ans += "" + ChatColor.AQUA + result.getTimestamp(2) + ": " + ChatColor.RESET + result.getString(3) + (result.getString(6).equalsIgnoreCase("up") ? " gave " : (result.getString(6).equalsIgnoreCase("down") ? " took " : " set")) + (result.getString(6).equalsIgnoreCase("set") ? "" : result.getDouble(5)) + " points " + (result.getString(6).equalsIgnoreCase("up") ? "to " : (result.getString(6).equalsIgnoreCase("down") ? "from " : "for ")) + result.getString(4) + (result.getString(6).equalsIgnoreCase("set") ? (" to " + result.getDouble(5)) : "") + "\n"; } catch (SQLException e) { ans = ChatColor.RED + "Error feting log from database"; } if (ans.equalsIgnoreCase("")) ans = ChatColor.RED + "No results"; else ans = ans.substring(0, ans.length() - 1); return ans; } private static void createLogTable() { if (eGORepConfig.sqlTableName.equalsIgnoreCase("")) { eGORep.log.severe(eGORep.logPref + "Log table name is blank! Edit config.yml to include a log table name"); return; } Connection con = getSQLConnection(); PreparedStatement stmt = null; eGORep.log.info(eGORep.logPref + "Attempting to create table " + eGORepConfig.sqlLogTableName); String q = "CREATE TABLE IF NOT EXISTS `" + eGORepConfig.sqlLogTableName + "` (`id` int(11) NOT NULL AUTO_INCREMENT, `time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, `repper` varchar(64) COLLATE utf8_unicode_ci NOT NULL, `recipient` varchar(64) COLLATE utf8_unicode_ci NOT NULL, `amt` double NOT NULL, `direction` varchar(4) COLLATE utf8_unicode_ci NOT NULL, PRIMARY KEY (`id`)) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;"; try { stmt = con.prepareStatement(q); stmt.executeUpdate(); stmt.close(); eGORep.log.info("Created table " + eGORepConfig.sqlLogTableName); } catch (SQLException e) { eGORep.log.warning(eGORep.logPref + "Could not create table " + eGORepConfig.sqlLogTableName + "."); } } public static int logCount() { int ans = 0; Connection con = getSQLConnection(); ResultSet result; PreparedStatement stmt = null; String q = "SELECT COUNT(*) FROM " + eGORepConfig.sqlLogTableName; try { stmt = con.prepareStatement(q); result = stmt.executeQuery(); result.next(); ans = result.getInt(1); } catch (SQLException e) { } return ans; } } /* * Code to create table if necessary CREATE TABLE IF NOT EXISTS `egorep` ( `IGN` varchar(128) COLLATE utf8_unicode_ci NOT NULL, `rep` double NOT NULL DEFAULT '0', `points` int(11) NOT NULL DEFAULT '3', `time` bigint(20) NOT NULL DEFAULT '0', PRIMARY KEY (`IGN`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; SQL code to create log database CREATE TABLE IF NOT EXISTS `replog` ( `id` int(11) NOT NULL AUTO_INCREMENT, `time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, `repper` varchar(64) COLLATE utf8_unicode_ci NOT NULL, `recipient` varchar(64) COLLATE utf8_unicode_ci NOT NULL, `amt` double NOT NULL, `direction` varchar(4) COLLATE utf8_unicode_ci NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; */ \ No newline at end of file diff --git a/src/com/andoutay/egorep/eGORep.java b/src/com/andoutay/egorep/eGORep.java index a941c84..a3fa45d 100644 --- a/src/com/andoutay/egorep/eGORep.java +++ b/src/com/andoutay/egorep/eGORep.java @@ -1,474 +1,471 @@ package com.andoutay.egorep; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.logging.Logger; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.command.ConsoleCommandSender; import org.bukkit.entity.Player; import org.bukkit.plugin.PluginDescriptionFile; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; import com.andoutay.egorep.eGORepConfig; public final class eGORep extends JavaPlugin { public static Logger log = Logger.getLogger("Minecraft"); public static String chPref = ChatColor.GREEN + "[" + ChatColor.RESET + "Rep" + ChatColor.GREEN + "] " + ChatColor.RESET; public static String logPref = "[Rep] "; private eGORepCookieManager cManager; public void onLoad() { new eGORepConfig(this); cManager = new eGORepCookieManager(this); } @Override public void onEnable() { PluginManager pm = this.getServer().getPluginManager(); //get stuff from db for all currently connected players - e.g. if it's a reload pm.registerEvents(cManager, this); //load config eGORepConfig.onEnable(); //load the data for any connected for (Player p: getServer().getOnlinePlayers()) cManager.loadPlayer(p.getName()); log.info(logPref + "enabled successfully!"); } @Override public void onDisable() { //stop the syncing from the database from executing in new threads since we need to assure it finishes before the server stops eGORepConfig.useAsync = false; for (Player p: getServer().getOnlinePlayers()) - { - log.info(p.getName() + " is still here"); cManager.saveAndUnLoadPlayer(p.getName()); - } getServer().getScheduler().cancelTasks(this); log.info(logPref + "disabled"); } public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { Player player = null; if (isUp(cmd, player, args)) return execRep("up", sender, args); else if (isDown(cmd, player, args)) return execRep("down", sender, args); else if (isSetRep(cmd, sender, args)) return setRep(sender, args); else if (isHelp(cmd.getName(), args)) return help(sender); else if (isVersion(cmd.getName(), args)) return version(sender); else if (isLog(cmd.getName(), args)) return showLog(sender, args); else if (isReload(cmd.getName(), args)) return reloadConfig(sender); else if (isCheck(cmd, player, args)) return checkRep(sender, args); return false; } private static boolean isUp(Command cmd, Player p, String[] args) { return cmd.getName().equalsIgnoreCase("rep") && args.length == 2 && args[0].equalsIgnoreCase("up"); } private static boolean isDown(Command cmd, Player p, String[] args) { return cmd.getName().equalsIgnoreCase("rep") && args.length == 2 && args[0].equalsIgnoreCase("down"); } private static boolean isCheck(Command cmd, Player p, String[] args) { return cmd.getName().equalsIgnoreCase("rep") && (args.length == 0 || (args.length == 1 && !args[0].equalsIgnoreCase("up") && !args[0].equalsIgnoreCase("down") && !args[0].equalsIgnoreCase("help") && !args[0].equalsIgnoreCase("?") && !args[0].equalsIgnoreCase("set")) || (args.length >= 1 && args.length <= 2 && args[0].equalsIgnoreCase("check"))); } private static boolean isSetRep(Command cmd, CommandSender s, String[] args) { if (cmd.getName().equalsIgnoreCase("rep") && args.length == 3 && args[0].equalsIgnoreCase("set")) if (!(s instanceof ConsoleCommandSender)) { s.sendMessage(chPref + "Only the console may use that command"); return false; } else return true; else return false; } private static boolean isHelp(String name, String[] args) { return name.equalsIgnoreCase("rep") && args.length == 1 && (args[0].equalsIgnoreCase("help") || args[0].equalsIgnoreCase("?")); } private static boolean isVersion(String name, String[] args) { return name.equalsIgnoreCase("rep") && args.length == 1 && args[0].equalsIgnoreCase("version"); } private static boolean isReload(String name, String[] args) { return name.equalsIgnoreCase("rep") && args.length == 1 && args[0].equalsIgnoreCase("reload"); } private static boolean isLog(String name, String[] args) { return name.equalsIgnoreCase("rep") && (args.length == 1 || args.length == 2) && args[0].equalsIgnoreCase("log"); } public void tellAllPlayers(Player recipient, String str, int amt) { str = (str == "up") ? "increased" : "decreased"; String msg = ChatColor.GREEN + recipient.getDisplayName() + ChatColor.WHITE + "'s reputation " + str + " to " + amt; String personalMsg = ChatColor.GREEN + "Your" + ChatColor.RESET + " reputation was " + str + " to " + amt; for(Player p : getServer().getOnlinePlayers()) if(p.hasPermission("egorep.show")) if (p.getName().equalsIgnoreCase(recipient.getName())) p.sendMessage(personalMsg); else p.sendMessage(msg); } private boolean execRep(String direction, CommandSender sender, String[] args) { double newamt = 0.0, oldamt; boolean hasDS = false; Player player = null, recipient = null; if (sender instanceof Player) player = (Player)sender; if (player != null) { if (!player.hasPermission("egorep.rep." + direction)) return noAccess(player); if (player.hasPermission("egorep.ds")) hasDS = true; } recipient = getPlayerForName(args[1]); if (recipient == null) return playerNotFound(sender, args[1], true); oldamt = cManager.getCookieForName(recipient.getName()); if (direction == "up") newamt = cManager.incrCookieForName(sender, recipient.getName(), hasDS); else if (direction == "down") newamt = cManager.decrCookieForName(sender, recipient.getName(), hasDS); if (newamt - oldamt != 0) { tellAllPlayers(recipient, direction, (int)newamt); log.info(logPref + sender.getName() + (direction == "up" ? " increased " : " decreased ") + recipient.getName() + "'s reputation by " + eGORepUtils.round1Decimal(newamt - oldamt) + " to " + newamt); sender.sendMessage(chPref + "You have " + cManager.getPointsLeft(sender.getName()) + " reputation points left"); addLog(sender.getName(), recipient.getName(), 1, direction); } return true; } private boolean checkRep(final CommandSender sender, String[] args) { Player player = null, other = null; boolean offlinePlayer = false; if (sender instanceof Player) player = (Player)sender; final String name; double rep = 0; if (args.length == 0 || (args.length == 1 && args[0].equalsIgnoreCase("check"))) { if (player != null && !player.hasPermission("egorep.rep.check.self")) return noAccess(player); name = sender.getName(); } else if (args.length == 1 || (args.length == 2 && args[0].equalsIgnoreCase("check"))) { String recipName = null; if (player != null && !player.hasPermission("egorep.rep.check.others")) return noAccess(player); if (args.length == 1) recipName = args[0]; else recipName = args[1]; other = getPlayerForName(recipName); if (other == null) { //If a player with the name of recipName has not been on the server, they will have a lastPlayed time of 0 if (getServer().getOfflinePlayer(recipName).getLastPlayed() > 0) { name = getServer().getOfflinePlayer(recipName).getName(); offlinePlayer = true; } else return playerNotFound(sender, recipName, false); } else name = other.getName(); } else return false; if (offlinePlayer && eGORepConfig.useAsync) { final Player o = other; sender.sendMessage(ChatColor.GRAY + "Fetching reputation from database..."); final Future<Double> returnFuture = getServer().getScheduler().callSyncMethod(this, new Callable<Double>() { @Override public Double call() { return cManager.dbManager.getRep(name); } }); getServer().getScheduler().runTaskAsynchronously(this, new Runnable() { @Override public void run() { try { tellRep(sender, (int)(double)returnFuture.get(), name, o); } catch (InterruptedException e) { sender.sendMessage(chPref+ "DB connection interrupted. Unable to get reputation."); } catch (ExecutionException e) { sender.sendMessage(chPref + "Unable to get reputation"); } } }); return true; } else if (offlinePlayer) rep = cManager.dbManager.getRep(name); else rep = cManager.getCookieForName(name); tellRep(sender, (int)rep, name, other); return true; } private boolean setRep(CommandSender sender, String[] args) { double repVal = 0; try { repVal = Double.parseDouble(args[2]); } catch (NumberFormatException e) { sender.sendMessage(chPref + ChatColor.RED + "Invalid argument"); return false; } Player recipient = getPlayerForName(args[1]); if (recipient == null) return playerNotFound(sender, args[1], true); cManager.setCookieForName(recipient.getName(), repVal); sender.sendMessage(logPref + "Set reputation of " + recipient.getName() + " to " + repVal); if (recipient.hasPermission("egorep.showset")) recipient.sendMessage(chPref + ChatColor.GREEN + "Your" + ChatColor.RESET + " reputation was set to " + (int)repVal); addLog("CONSOLE", recipient.getName(), repVal, "set"); return true; } private boolean help(CommandSender s) { s.sendMessage(chPref + "Help:"); s.sendMessage("Use /rep up <username> and /rep down <username> to give and take other players' reputation"); s.sendMessage("Use /rep <username> or /rep check <username> to check the reputation of other players"); s.sendMessage("Use /rep or /rep check to check your own reputation"); s.sendMessage("Remember that Dedicated Supporters get two extra rep points to use every " + eGORepUtils.parseTime((long)eGORepConfig.refreshSecs)); return true; } private boolean version(CommandSender s) { PluginDescriptionFile pdf = getDescription(); String pref = null; if ((s instanceof Player) && ((Player)s).hasPermission("egorep.version")) pref = chPref; else if (s instanceof ConsoleCommandSender) pref = logPref; if (pref != null) s.sendMessage(pref + "Current version: " + pdf.getVersion()); else return noAccess(s); return true; } private boolean showLog(final CommandSender s, String[] args) { if ((s instanceof Player) && !((Player)s).hasPermission("egorep.getlog")) return noAccess(s); int startIndex = 0, totLogs = eGODBManager.logCount(); if (args.length == 2) { try { startIndex = Integer.parseInt(args[1]); startIndex = (startIndex - 1) * 10; } catch (NumberFormatException e) { if (args[1].equalsIgnoreCase("last")) startIndex = totLogs; else { s.sendMessage(chPref + ChatColor.RED + "Invalid argument"); return false; } } } if (startIndex > totLogs) startIndex = totLogs - (totLogs % 10); if (eGORepConfig.useAsync) { final int sIndex = startIndex, tLogs = totLogs; s.sendMessage(ChatColor.GRAY + "Fetching log from database..."); final Future<String> returnFuture = getServer().getScheduler().callSyncMethod(this, new Callable<String>() { @Override public String call() { return eGODBManager.getLogEntry(null, null, sIndex); } }); getServer().getScheduler().runTaskAsynchronously(this, new Runnable() { @Override public void run() { try { s.sendMessage(chPref + "Log page " + (sIndex / 10 + 1) + " of " + (tLogs / 10 + ((tLogs % 10 == 0) ? 0 : 1))); s.sendMessage(returnFuture.get()); } catch (InterruptedException e) { s.sendMessage(chPref+ "DB connection interrupted. Unable to get logs."); } catch (ExecutionException e) { s.sendMessage(chPref + "Unable to get logs"); } } }); } else { s.sendMessage(chPref + "Log page " + (startIndex / 10 + 1) + " of " + (totLogs / 10 + ((totLogs % 10 == 0) ? 0 : 1))); s.sendMessage(eGODBManager.getLogEntry(null, null, startIndex)); } return true; } private boolean reloadConfig(CommandSender s) { if (s instanceof Player && !((Player)s).hasPermission("egorep.reload")) return noAccess(s); eGORepConfig.reload(); s.sendMessage(chPref + "Config reloaded"); return true; } private void addLog(final String repper, final String recipient, final double amt, final String direction) { if (eGORepConfig.useAsync) { getServer().getScheduler().runTaskAsynchronously(this, new Runnable() { public void run() { eGODBManager.addLogEntry(repper, recipient, amt, direction); } }); } else eGODBManager.addLogEntry(repper, recipient, amt, direction); } private boolean playerNotFound(CommandSender sender, String name, boolean online) { sender.sendMessage(chPref + "Player matching " + name + " not found" + (online ? " online" : "")); return true; } private boolean noAccess(Player player) { player.sendMessage(ChatColor.RED + "You do not have access to that command"); return true; } private boolean noAccess(CommandSender s) { if (s instanceof Player) return noAccess((Player)s); s.sendMessage("You do not have access to that command"); return true; } private Player getPlayerForName(String partial) { Player player = null; boolean found = false, foundMult = false; player = getServer().getPlayer(partial); if (player == null) for (Player p: getServer().getOnlinePlayers()) if (p.getDisplayName().contains(partial)) { if (found) { foundMult = true; break; } player = p; found = true; } if (foundMult) player = null; return player; } public void tellRep(CommandSender sender, int rep, String name, Player other) { if (sender.getName().equalsIgnoreCase(name)) sender.sendMessage(chPref + "You have a reputation of " + rep); else sender.sendMessage(chPref + ((other == null) ? name : other.getDisplayName()) + " has a reputation of " + rep); } }
false
false
null
null
diff --git a/org.eclipse.help.ui/src/org/eclipse/help/internal/ui/ContextHelpDialog.java b/org.eclipse.help.ui/src/org/eclipse/help/internal/ui/ContextHelpDialog.java index 8f5b50799..1a4e53713 100644 --- a/org.eclipse.help.ui/src/org/eclipse/help/internal/ui/ContextHelpDialog.java +++ b/org.eclipse.help.ui/src/org/eclipse/help/internal/ui/ContextHelpDialog.java @@ -1,273 +1,273 @@ package org.eclipse.help.internal.ui; /* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ import java.util.*; import org.eclipse.help.*; import org.eclipse.help.internal.ui.util.*; import org.eclipse.help.internal.util.Logger; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.events.*; import org.eclipse.swt.graphics.*; import org.eclipse.swt.layout.*; import org.eclipse.swt.widgets.*; import org.eclipse.ui.help.WorkbenchHelp; /** * ContextHelpDialog */ public class ContextHelpDialog { private Color backgroundColour = null; private IContext context; private Color foregroundColour = null; private Color linkColour = null; private static HyperlinkHandler linkManager = new HyperlinkHandler(); private Map menuItems; private Shell shell; private int x; private int y; /** * Constructor: * @param context an array of String or an array of IContext * @param x the x mouse location in the current display * @param y the y mouse location in the current display */ ContextHelpDialog(IContext context, int x, int y) { this.context = context; this.x = x; this.y = y; Display display = Display.getCurrent(); backgroundColour = display.getSystemColor(SWT.COLOR_INFO_BACKGROUND); foregroundColour = display.getSystemColor(SWT.COLOR_INFO_FOREGROUND); linkColour = display.getSystemColor(SWT.COLOR_BLUE); shell = new Shell(display.getActiveShell(), SWT.NONE); if (Logger.DEBUG) Logger.logDebugMessage( "ContextHelpDialog", " Constructor: Shell is:" + shell.toString()); WorkbenchHelp.setHelp(shell, new String[] { IHelpUIConstants.F1_SHELL }); shell.addListener(SWT.Deactivate, new Listener() { public void handleEvent(Event e) { if (Logger.DEBUG) Logger.logDebugMessage( "ContextHelpDialog", "handleEvent: SWT.Deactivate called. "); close(); }; }); shell.addControlListener(new ControlAdapter() { public void controlMoved(ControlEvent e) { if (Logger.DEBUG) Logger.logDebugMessage("ContextHelpDialog", "controlMoved: called. "); Rectangle clientArea = shell.getClientArea(); shell.redraw( clientArea.x, clientArea.y, clientArea.width, clientArea.height, true); shell.update(); } }); if (Logger.DEBUG) Logger.logDebugMessage( "ContextHelpDialog", "Constructor: Focus owner is: " + Display.getCurrent().getFocusControl().toString()); linkManager.setHyperlinkUnderlineMode(HyperlinkHandler.UNDERLINE_ROLLOVER); createContents(shell); shell.pack(); // Correct x and y of the shell if it not contained within the screen int width = shell.getBounds().width; int height = shell.getBounds().height; // check lower boundaries x = x >= 0 ? x : 0; y = y >= 0 ? y : 0; // check upper boundaries int margin = 0; if (System.getProperty("os.name").startsWith("Win")) margin = 28; // for the Windows task bar in the ussual place; Rectangle screen = display.getBounds(); x = x + width <= screen.width ? x : screen.width - width; y = y + height <= screen.height - margin ? y : screen.height - margin - height; shell.setLocation(x, y); } public synchronized void close() { try { if (Logger.DEBUG) Logger.logDebugMessage("ContextHelpDialog", "close: called. "); if (shell != null) { shell.close(); if (!shell.isDisposed()) shell.dispose(); shell = null; } } catch (Throwable ex) { } } /** */ protected Control createContents(Composite contents) { contents.setBackground(backgroundColour); GridLayout layout = new GridLayout(); layout.marginHeight = 5; layout.marginWidth = 5; contents.setLayout(layout); contents.setLayoutData(new GridData(GridData.FILL_BOTH)); // create the dialog area and button bar createInfoArea(contents); createLinksArea(contents); // if any errors or parsing errors have occurred, display them in a pop-up ErrorUtil.displayStatus(); return contents; } private Control createInfoArea(Composite parent) { // Create the text field. String styledText = context.getText(); if (styledText == null) // no description found in context objects. styledText = WorkbenchResources.getString("WW002"); - StyledText text = new StyledText(parent, SWT.MULTI | SWT.READ_ONLY | SWT.WRAP); + StyledText text = new StyledText(parent, SWT.MULTI | SWT.READ_ONLY /* | SWT.WRAP*/); text.getCaret().setVisible(false); text.setBackground(backgroundColour); text.setForeground(foregroundColour); StyledLineWrapper content = new StyledLineWrapper(styledText); text.setContent(content); text.setStyleRanges(content.getStyles()); return text; } private Control createLink(Composite parent, IHelpResource topic) { Label image = new Label(parent, SWT.NONE); image.setImage(ElementLabelProvider.getDefault().getImage(topic)); image.setBackground(backgroundColour); GridData data = new GridData(); data.horizontalAlignment = data.HORIZONTAL_ALIGN_BEGINNING; data.verticalAlignment = data.VERTICAL_ALIGN_BEGINNING; //data.horizontalIndent = 4; image.setLayoutData(data); Label link = new Label(parent, SWT.NONE); link.setText(topic.getLabel()); link.setBackground(backgroundColour); link.setForeground(linkColour); data = new GridData(); data.horizontalAlignment = data.HORIZONTAL_ALIGN_BEGINNING; data.verticalAlignment = data.VERTICAL_ALIGN_BEGINNING; link.setLayoutData(data); linkManager.registerHyperlink(link, new LinkListener(topic)); return link; } private Control createLinksArea(Composite parent) { IHelpResource[] relatedTopics = context.getRelatedTopics(); relatedTopics = removeDuplicates(relatedTopics); if (relatedTopics == null) return null; // Create control Composite composite = new Composite(parent, SWT.NONE); composite.setBackground(backgroundColour); GridLayout layout = new GridLayout(); layout.marginHeight = 2; layout.marginWidth = 0; layout.verticalSpacing = 3; layout.horizontalSpacing = 2; layout.numColumns = 2; composite.setLayout(layout); GridData data = new GridData( GridData.FILL_BOTH | GridData.HORIZONTAL_ALIGN_BEGINNING | GridData.VERTICAL_ALIGN_CENTER); composite.setLayoutData(data); // Create separator. Label label = new Label(composite, SWT.SEPARATOR | SWT.HORIZONTAL); label.setBackground(backgroundColour); label.setForeground(foregroundColour); data = new GridData( GridData.HORIZONTAL_ALIGN_BEGINNING | GridData.VERTICAL_ALIGN_BEGINNING | GridData.FILL_HORIZONTAL); data.horizontalSpan = 2; label.setLayoutData(data); // Create related links for (int i = 0; i < relatedTopics.length; i++) { createLink(composite, relatedTopics[i]); } return composite; } /** * Check if two context topic are the same. * They are considered the same if both labels and href are equal */ private boolean equal(IHelpResource topic1, IHelpResource topic2) { return topic1.getHref().equals(topic2.getHref()) && topic1.getLabel().equals(topic2.getLabel()); } /** * Checks if topic labels and href are not null and not empty strings */ private boolean isValidTopic(IHelpResource topic) { return topic != null && topic.getHref() != null && !"".equals(topic.getHref()) && topic.getLabel() != null && !"".equals(topic.getLabel()); } /** * Called when related link has been chosen * Opens view with list of all related topics */ private void launchFullViewHelp(IHelpResource selectedTopic) { close(); if (Logger.DEBUG) Logger.logDebugMessage("ContextHelpDialog", "launchFullViewHelp: closes shell"); // launch help view DefaultHelp.getInstance().displayHelp(context, selectedTopic); } public synchronized void open() { try { shell.open(); if (Logger.DEBUG) Logger.logDebugMessage( "ContextHelpDialog", "open: Focus owner after open is: " + Display.getCurrent().getFocusControl().toString()); } catch (Throwable e) { } } /** * Filters out the duplicate topics from an array * TODO move this check to ContextManager */ private IHelpResource[] removeDuplicates(IHelpResource links[]) { if (links == null || links.length <= 0) return links; ArrayList filtered = new ArrayList(); for (int i = 0; i < links.length; i++) { IHelpResource topic1 = links[i]; if (!isValidTopic(topic1)) continue; boolean dup = false; for (int j = 0; j < filtered.size(); j++) { IHelpResource topic2 = (IHelpResource) filtered.get(j); if (!isValidTopic(topic2)) continue; if (equal(topic1, topic2)) { dup = true; break; } } if (!dup) filtered.add(links[i]); } return (IHelpResource[]) filtered.toArray(new IHelpResource[filtered.size()]); } class LinkListener extends HyperlinkAdapter { IHelpResource topic; public LinkListener(IHelpResource topic) { this.topic = topic; } public void linkActivated(Control c) { launchFullViewHelp(topic); } } } \ No newline at end of file
true
false
null
null
diff --git a/src/main/java/com/rakutec/weibo/utils/Twitter2Weibo.java b/src/main/java/com/rakutec/weibo/utils/Twitter2Weibo.java index 5b52692..28eea0b 100644 --- a/src/main/java/com/rakutec/weibo/utils/Twitter2Weibo.java +++ b/src/main/java/com/rakutec/weibo/utils/Twitter2Weibo.java @@ -1,106 +1,105 @@ package com.rakutec.weibo.utils; import com.rakutec.weibo.utils.filters.NoMentionFilter; import com.rakutec.weibo.utils.filters.StatusFilters; import com.rakutec.weibo.utils.filters.TagStatusFilter; import com.rakutec.weibo.utils.filters.URLStatusFilter; import org.apache.log4j.Logger; import twitter4j.*; import twitter4j.auth.AccessToken; import weibo4j.Weibo; import weibo4j.WeiboException; import java.util.List; /** * @author Rakuraku Jyo */ public class Twitter2Weibo { private static final Logger log = Logger.getLogger(Twitter2Weibo.class.getName()); private Weibo weibo; private Twitter twitter; private StatusFilters filters = new StatusFilters(); private T2WUser user; public Twitter2Weibo(String id) { user = T2WUser.findOneByUser(id); weibo = new Weibo(); weibo.setToken(user.getToken(), user.getTokenSecret()); twitter = new TwitterFactory().getInstance(); if (user.getTwitterToken() != null) { twitter.setOAuthAccessToken(new AccessToken(user.getTwitterToken(), user.getTwitterTokenSecret())); log.info("Using OAuth for " + id); } filters.use(new URLStatusFilter()).use(new TagStatusFilter()); + + if (user.isDropMentions()) { + filters.use(new NoMentionFilter()); + } } public void syncTwitter() { if (!user.ready()) { log.info("Skipping @" + user.getUserId() + " ..."); return; } // gets Twitter instance with default credentials String screenName = user.getUserId(); long latestId = user.getLatestId(); log.info("= TID: " + latestId + " = "); log.info("Checking @" + screenName + "'s userId timeline."); try { if (latestId == 0) { List<Status> statuses = twitter.getUserTimeline(screenName); if (statuses.size() > 0) user.updateLatestId(statuses.get(0).getId()); // Record latestId, and sync next time log.info("Updating @" + screenName + "'s latestId to " + user.getLatestId()); } else { Paging paging = new Paging(latestId); List<Status> statuses = twitter.getUserTimeline(screenName, paging); for (int i = statuses.size() - 1; i >= 0; i--) { twitter4j.Status status = statuses.get(i); log.info("@" + status.getUser().getScreenName() + " - " + status.getText()); try { if (user.isDropRTAndReply() && status.isRetweet()) { log.info("Skipped " + status.getText() + " because status is a retweet."); continue; } - if (user.isDropMentions() && (status.getUserMentionEntities() != null)) { - log.info("Skipped " + status.getText() + " because status has mentions."); - continue; - } - String filtered = filters.filter(status.getText()); if (filtered == null) { log.info("Skipped " + status.getText() + " because of the filter."); continue; } GeoLocation location = status.getGeoLocation(); if (user.isWithGeo() && location != null) { weibo.updateStatus(filtered, location.getLatitude(), location.getLongitude()); log.info("@" + status.getUser().getScreenName() + " - " + status.getText() + " sent with geo locations."); } else { weibo.updateStatus(filtered); log.info("@" + status.getUser().getScreenName() + " - " + status.getText() + " sent."); } } catch (WeiboException e) { if (e.getStatusCode() != 400) { // resending same tweet log.warn("Failed to update Weibo"); throw new RuntimeException(e); } } user.updateLatestId(status.getId()); // still update the latestId to skip Thread.sleep(500); } } } catch (Exception e) { log.error("Failed to get timeline: " + e.getMessage()); } } }
false
false
null
null
diff --git a/openFaces/source/org/openfaces/renderkit/input/FileUploadRenderer.java b/openFaces/source/org/openfaces/renderkit/input/FileUploadRenderer.java index 2887e9764..ac278bf49 100644 --- a/openFaces/source/org/openfaces/renderkit/input/FileUploadRenderer.java +++ b/openFaces/source/org/openfaces/renderkit/input/FileUploadRenderer.java @@ -1,474 +1,477 @@ /* * OpenFaces - JSF Component Library 2.0 * Copyright (C) 2007-2011, TeamDev Ltd. * licensing@openfaces.org * Unless agreed in writing the contents of this file are subject to * the GNU Lesser General Public License Version 2.1 (the "LGPL" License). * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * Please visit http://openfaces.org/licensing/ for more details. */ package org.openfaces.renderkit.input; import org.openfaces.component.input.FileUpload; import org.openfaces.component.output.ProgressBar; import org.openfaces.event.FileUploadItem; import org.openfaces.event.FileUploadStatus; import org.openfaces.event.UploadCompletionEvent; import org.openfaces.org.json.JSONArray; import org.openfaces.org.json.JSONException; import org.openfaces.org.json.JSONObject; import org.openfaces.renderkit.AjaxPortionRenderer; import org.openfaces.renderkit.RendererBase; import org.openfaces.util.AjaxUtil; import org.openfaces.util.Rendering; import org.openfaces.util.Resources; import org.openfaces.util.Script; import org.openfaces.util.ScriptBuilder; import org.openfaces.util.StyleGroup; import org.openfaces.util.Styles; import javax.el.MethodExpression; import javax.faces.component.UIComponent; import javax.faces.context.ExternalContext; import javax.faces.context.FacesContext; import javax.faces.context.ResponseWriter; import javax.servlet.http.HttpServletRequest; import java.io.IOException; import java.util.LinkedList; import java.util.List; import java.util.Map; public class FileUploadRenderer extends RendererBase implements AjaxPortionRenderer { private static final String DIV_FOR_INPUTS_ID = "::inputs"; private static final String INPUT_OF_FILE_ID = "::input"; private static final String DIV_FOR_INFO_ID = "::infoDiv"; public static final String DIV_HEADER_ID = "::header"; private static final String BROWSE_BTN_ID = "::addButton"; private static final String TITLE_ADD_BTN_DIV_ID = "::title"; private static final String INPUT_DIV_OF_ADD_BTN_ID = "::forInput"; /*facet names and components which is used in this component*/ private static final String F_BROWSE_BUTTON = "browseButton"; private static final String F_UPLOAD_BUTTON = "uploadButton"; private static final String F_CLEAR_ALL_BUTTON = "clearAllButton"; private static final String F_REMOVE_BUTTON = "removeButton"; private static final String F_STOP_BUTTON = "stopButton"; private static final String F_CLEAR_BUTTON = "clearButton"; private static final String F_PROGRESS_BAR = "progressBar"; /*id of elements*/ private static final String REMOVE_BTN_CONTAINER = "::removeFacet"; private static final String CLEAR_BTN_CONTAINER = "::clearFacet"; private static final String STOP_BTN_CONTAINER = "::stopFacet"; private static final String UPLOAD_BTN_CONTAINER = "::uploadFacet"; private static final String CLEAR_ALL_BTN_CONTAINER = "::clearAllFacet"; private static final String FOOTER_DIV_ID = "::footer"; private static final String HELP_ELEMENTS_ID = "::elements"; - private static final String HELPFUL_INPUT = "::helpfulInput"; private static final String DEF_PROGRESS_ID = "progressBar"; private static final String DEF_BROWSE_BTN_LABEL_SINGLE = "Upload..."; private static final String DEF_BROWSE_LABEL_MULTIPLE = "Add file..."; private static final String EXCEED_MAX_SIZE_ID = "exceedMaxSize_"; private UIComponent browseButton; private UIComponent uploadButton; private UIComponent clearAllButton; private UIComponent removeButton; private UIComponent stopButton; private UIComponent clearButton; private ProgressBar progressBar; /*progress*/ private static final String AJAX_PARAM_PROGRESS_REQUEST = "progressRequest"; private static final String AJAX_PARAM_FIELD_NAME = "fieldName"; private static final String PROGRESS_ID = "progress_"; /*listOfFiles*/ private static final String AJAX_FILES_REQUEST = "listOfFilesRequest"; private static final String AJAX_PARAM_FILES_ID = "idOfFiles"; @Override public void encodeBegin(FacesContext context, UIComponent component) throws IOException { AjaxUtil.prepareComponentForAjax(context, component); FileUpload fileUpload = (FileUpload) component; - ResponseWriter writer = context.getResponseWriter(); + if (((HttpServletRequest) context.getExternalContext().getRequest()).getAttribute("fileUploadRequest") != null) { uploadIfExistFiles(context, component); return; } setAllFacets(fileUpload); + renderComponent(context, component, fileUpload); + } + + private void renderComponent(FacesContext context, UIComponent component, FileUpload fileUpload) throws IOException { String clientId = component.getClientId(context); + ResponseWriter writer = context.getResponseWriter(); writer.startElement("div", component); Rendering.writeIdAttribute(context, fileUpload); Rendering.writeStyleAndClassAttributes(writer, fileUpload.getStyle(), fileUpload.getStyleClass(), "o_file_upload"); - Rendering.writeStandardEvents(writer, fileUpload); - - writer.writeAttribute("onuploadstart", fileUpload.getOnuploadstart(), null); - writer.writeAttribute("onuploadend", fileUpload.getOnuploadend(), null); + writeEvents(fileUpload, writer); writeHeader(context, fileUpload, writer, clientId + DIV_HEADER_ID); writeMainDivForInfos(context, writer, fileUpload, clientId + DIV_FOR_INFO_ID); writeFooter(context, fileUpload, writer, clientId + FOOTER_DIV_ID); writeHelpfulElements(context, fileUpload, writer, clientId + HELP_ELEMENTS_ID); encodeScriptAndStyles(context, fileUpload, clientId); writer.endElement("div"); + } - + private void writeEvents(FileUpload fileUpload, ResponseWriter writer) throws IOException { + Rendering.writeStandardEvents(writer, fileUpload); + writer.writeAttribute("onuploadstart", fileUpload.getOnuploadstart(), null); + writer.writeAttribute("onuploadend", fileUpload.getOnuploadend(), null); + writer.writeAttribute("onchangefiles", fileUpload.getOnchange(), null); } private void writeHelpfulInput(FacesContext context, FileUpload fileUpload, ResponseWriter writer, String elementId) throws IOException { writer.startElement("input", fileUpload); writer.writeAttribute("type", "text", null); writer.writeAttribute("id", elementId, null); writer.writeAttribute("style", "display:none", null); writer.writeAttribute("onchange", fileUpload.getOnchange(), null); - writer.endElement("input"); } private void writeHelpfulElements(FacesContext context, FileUpload fileUpload, ResponseWriter writer, String elementId) throws IOException { writer.startElement("div", fileUpload); writer.writeAttribute("id", elementId, null); writer.writeAttribute("style", "display:none", null); - writeHelpfulInput(context, fileUpload, writer, elementId + HELPFUL_INPUT); writeRemoveButton(context, fileUpload, writer, elementId + REMOVE_BTN_CONTAINER); writeClearButton(context, fileUpload, writer, elementId + CLEAR_BTN_CONTAINER); writeStopButton(context, fileUpload, writer, elementId + STOP_BTN_CONTAINER); writeProgressBar(context); writer.endElement("div"); } private void writeProgressBar(FacesContext context) throws IOException { if (progressBar == null) { progressBar = new ProgressBar(); } progressBar.encodeAll(context); - } private void writeClearButton(FacesContext context, FileUpload fileUpload, ResponseWriter writer, String elementId) throws IOException { writer.startElement("div", fileUpload); writer.writeAttribute("id", elementId, null); if (clearButton == null) { writer.startElement("input", fileUpload); writer.writeAttribute("type", "button", null); writer.writeAttribute("class", "o_file_clear_btn", null); writer.writeAttribute("value", "Clear", null); writer.endElement("input"); } else { clearButton.encodeAll(context); } writer.endElement("div"); } private void writeStopButton(FacesContext context, FileUpload fileUpload, ResponseWriter writer, String elementId) throws IOException { writer.startElement("div", fileUpload); writer.writeAttribute("id", elementId, null); if (stopButton == null) { writer.startElement("input", fileUpload); writer.writeAttribute("type", "button", null); writer.writeAttribute("class", "o_file_clear_btn", null); writer.writeAttribute("value", "Stop", null); writer.endElement("input"); } else { stopButton.encodeAll(context); } writer.endElement("div"); } private void writeRemoveButton(FacesContext context, FileUpload fileUpload, ResponseWriter writer, String elementId) throws IOException { writer.startElement("div", fileUpload); writer.writeAttribute("id", elementId, null); if (removeButton == null) { writer.startElement("input", fileUpload); writer.writeAttribute("type", "button", null); writer.writeAttribute("class", "o_file_clear_btn", null); writer.writeAttribute("value", "Remove", null); writer.endElement("input"); } else { removeButton.encodeAll(context); } writer.endElement("div"); } private void setAllFacets(FileUpload fileUpload) { browseButton = fileUpload.getFacet(F_BROWSE_BUTTON); uploadButton = fileUpload.getFacet(F_UPLOAD_BUTTON); clearAllButton = fileUpload.getFacet(F_CLEAR_ALL_BUTTON); removeButton = fileUpload.getFacet(F_REMOVE_BUTTON); stopButton = fileUpload.getFacet(F_STOP_BUTTON); clearButton = fileUpload.getFacet(F_CLEAR_BUTTON); progressBar = (ProgressBar) fileUpload.getFacet(F_PROGRESS_BAR); } private void writeMainDivForInfos(FacesContext context, ResponseWriter writer, FileUpload fileUpload, String elementId) throws IOException { String styleClass = Styles.getCSSClass(context, fileUpload, fileUpload.getAllInfosStyle(), StyleGroup.regularStyleGroup(), fileUpload.getAllInfosClass(), "o_file_upload_infos"); writer.startElement("table", fileUpload); writer.writeAttribute("id", elementId, null); writer.writeAttribute("class", styleClass, null); writer.endElement("table"); } private void writeHeader(FacesContext context, FileUpload fileUpload, ResponseWriter writer, String elementId) throws IOException { String styleClass = Styles.getCSSClass(context, fileUpload, fileUpload.getHeaderStyle(), StyleGroup.regularStyleGroup(), fileUpload.getHeaderClass(), "o_file_upload_header"); writer.startElement("table", fileUpload); writer.writeAttribute("id", elementId, null); writer.writeAttribute("class", styleClass, null); writer.startElement("tr", fileUpload); writer.startElement("td", fileUpload); writeBrowseButtonTable(context, fileUpload, writer, elementId + BROWSE_BTN_ID); writeUploadButton(context, fileUpload, writer, elementId + UPLOAD_BTN_CONTAINER); writer.endElement("td"); writer.endElement("tr"); writer.endElement("table"); } private void writeUploadButton(FacesContext context, FileUpload fileUpload, ResponseWriter writer, String elementId) throws IOException { writer.startElement("div", fileUpload); writer.writeAttribute("id", elementId, null); if (uploadButton == null) { writer.startElement("input", fileUpload); writer.writeAttribute("type", "button", null); writer.writeAttribute("class", "o_file_upload_btn", null); writer.writeAttribute("value", "Upload", null); writer.endElement("input"); } else { uploadButton.encodeAll(context); } writer.endElement("div"); } private void writeClearAllButton(FacesContext context, FileUpload fileUpload, ResponseWriter writer, String elementId) throws IOException { writer.startElement("div", fileUpload); writer.writeAttribute("id", elementId, null); if (clearAllButton == null) { writer.startElement("input", fileUpload); writer.writeAttribute("type", "button", null); writer.writeAttribute("value", "Clear all", null); writer.writeAttribute("class", "o_file_clear_all_btn", null); writer.endElement("input"); } else { clearAllButton.encodeAll(context); } writer.endElement("div"); } private void writeBrowseButtonTable(FacesContext context, FileUpload fileUpload, ResponseWriter writer, String elementId) throws IOException { writer.startElement("table", fileUpload); writer.writeAttribute("style", "float:left;", null); //todo temporary writer.writeAttribute("id", elementId, null); writer.startElement("tr", fileUpload); writer.startElement("td", fileUpload); writer.startElement("div", fileUpload); writer.writeAttribute("style", "position:relative", null); writer.startElement("div", fileUpload); writer.writeAttribute("id", elementId + TITLE_ADD_BTN_DIV_ID, null); if (browseButton == null) { writer.startElement("input", fileUpload); writer.writeAttribute("type", "button", null); String value; if (fileUpload.getBrowseButtonText() == null) { if (!fileUpload.isMultiple()) { value = DEF_BROWSE_BTN_LABEL_SINGLE; } else { value = DEF_BROWSE_LABEL_MULTIPLE; } } else { value = fileUpload.getBrowseButtonText(); } writer.writeAttribute("value", value, null); writer.endElement("input"); } else { browseButton.encodeAll(context); } writer.endElement("div"); writer.startElement("div", fileUpload); writer.writeAttribute("id", elementId + INPUT_DIV_OF_ADD_BTN_ID, null); writer.writeAttribute("style", "overflow:hidden;position:absolute;top:0;width:100%;height:100%", null); //todo temporary writer.endElement("div"); writer.endElement("div"); writer.endElement("td"); writer.endElement("tr"); writer.endElement("table"); } private void writeFooter(FacesContext context, FileUpload fileUpload, ResponseWriter writer, String elementId) throws IOException { writer.startElement("div", fileUpload); writer.writeAttribute("id", elementId, null); writeClearAllButton(context, fileUpload, writer, elementId + CLEAR_ALL_BTN_CONTAINER); writer.endElement("div"); } private void encodeScriptAndStyles(FacesContext context, FileUpload fileUpload, String clientId) throws IOException { String fileInfoClass = Styles.getCSSClass(context, fileUpload, fileUpload.getRowStyle(), StyleGroup.regularStyleGroup(), fileUpload.getRowClass(), "o_file_upload_info"); String infoTitleClass = Styles.getCSSClass(context, fileUpload, fileUpload.getFileNameStyle(), StyleGroup.regularStyleGroup(), fileUpload.getFileNameClass(), "o_file_upload_info_title"); String infoStatusClass = Styles.getCSSClass(context, fileUpload, fileUpload.getUploadStatusStyle(), StyleGroup.regularStyleGroup(), fileUpload.getUploadStatusClass(), "o_file_upload_info_status"); String progressBarClass = Styles.getCSSClass(context, fileUpload, fileUpload.getProgressBarStyle(), StyleGroup.regularStyleGroup(), fileUpload.getProgressBarClass(), "o_file_upload_info_progress"); String addButtonClass = Styles.getCSSClass(context, fileUpload, fileUpload.getBrowseButtonStyle(), StyleGroup.regularStyleGroup(), fileUpload.getBrowseButtonClass(), null); String addButtonOnMouseOverClass = Styles.getCSSClass(context, fileUpload, fileUpload.getBrowseButtonRolloverStyle(), StyleGroup.regularStyleGroup(), fileUpload.getBrowseButtonRolloverClass(), null); String addButtonOnMouseDownClass = Styles.getCSSClass(context, fileUpload, fileUpload.getBrowseButtonPressedStyle(), StyleGroup.regularStyleGroup(), fileUpload.getBrowseButtonPressedClass(), null); String addButtonOnFocusClass = Styles.getCSSClass(context, fileUpload, fileUpload.getBrowseButtonFocusedStyle(), StyleGroup.regularStyleGroup(), fileUpload.getBrowseButtonFocusedClass(), null); String addButtonDisabledClass = Styles.getCSSClass(context, fileUpload, fileUpload.getBrowseButtonDisabledStyle(), StyleGroup.regularStyleGroup(), fileUpload.getBrowseButtonDisabledClass(), "o_file_upload_addBtn_dis"); Styles.renderStyleClasses(context, fileUpload); int uploadedSize = 0; String headerId = clientId + DIV_HEADER_ID; boolean duplicateAllowed = true;//fileUpload.isDuplicateAllowed(); Script initScript = new ScriptBuilder().initScript(context, fileUpload, "O$.FileUpload._init", fileUpload.getMinQuantity(), fileUpload.getMaxQuantity(), uploadedSize, fileInfoClass, infoTitleClass, progressBarClass, infoStatusClass, fileUpload.getNotUploadedStatusText(), fileUpload.getInProgressStatusText(), fileUpload.getUploadedStatusText(), fileUpload.getFileSizeLimitErrorText(), fileUpload.getUnexpectedErrorText(), fileUpload.getAcceptedFileTypes(), duplicateAllowed, headerId + BROWSE_BTN_ID, addButtonClass, addButtonOnMouseOverClass, addButtonOnMouseDownClass, addButtonOnFocusClass, addButtonDisabledClass, fileUpload.isDisabled(), fileUpload.isAutoUpload(), fileUpload.getTabindex(), progressBar.getClientId(context), fileUpload.getStoppedStatusText(), fileUpload.getStoppingStatusText(), fileUpload.isMultiple(), generateUniqueId(clientId) ); Rendering.renderInitScript(context, initScript, Resources.utilJsURL(context), Resources.jsonJsURL(context), Resources.internalURL(context, "input/fileUpload.js") ); } private String generateUniqueId(String clientId) { return clientId + System.currentTimeMillis(); } private void uploadIfExistFiles(FacesContext context, UIComponent component) { FileUpload fileUpload = (FileUpload) component; ExternalContext extContext = context.getExternalContext(); String clientId = fileUpload.getClientId(context); try { HttpServletRequest request = (HttpServletRequest) extContext.getRequest(); FileUploadItem uploadedFile = (FileUploadItem) request.getAttribute(clientId + DIV_FOR_INPUTS_ID + INPUT_OF_FILE_ID); if (uploadedFile == null) return; String id = (String) request.getAttribute("FILE_ID"); request.getSession().setAttribute(id, uploadedFile); //file uploaded. //fileUpload.getFileUploadedListener().invoke(context.getELContext(), new Object[]{new FileUploadedEvent(fileUpload, uploadedFile)}); } catch (Exception e) { throw new RuntimeException("Could not handle file upload - please ensure that you have correctly configured the filter.", e); } } @Override public void encodeEnd(FacesContext context, UIComponent component) throws IOException { } @Override public void decode(FacesContext context, UIComponent component) { } public JSONObject encodeAjaxPortion(FacesContext context, UIComponent component, String portionName, JSONObject jsonParam) throws IOException, JSONException { if (jsonParam.has(AJAX_PARAM_PROGRESS_REQUEST)) { JSONObject jsonObj = new JSONObject(); String fieldName = (String) jsonParam.get(AJAX_PARAM_FIELD_NAME); Map<String, Object> sessionMap = context.getExternalContext().getSessionMap(); if (sessionMap.containsKey(PROGRESS_ID + fieldName)) { Integer progress = (Integer) sessionMap.get(PROGRESS_ID + fieldName); Rendering.addJsonParam(jsonObj, "progressInPercent", progress); Rendering.addJsonParam(jsonObj, "status", "inProgress"); if (progress.equals(100)) { sessionMap.remove(PROGRESS_ID + fieldName); } } else {//in case if any error Rendering.addJsonParam(jsonObj, "status", "error"); if (sessionMap.containsKey(EXCEED_MAX_SIZE_ID + fieldName)) { boolean maxFileExceeded = (Boolean) sessionMap.get(EXCEED_MAX_SIZE_ID + fieldName); Rendering.addJsonParam(jsonObj, "isFileSizeExceed", maxFileExceeded); sessionMap.remove(EXCEED_MAX_SIZE_ID + fieldName); } } return jsonObj; } else if (jsonParam.has(AJAX_FILES_REQUEST)) { JSONObject jsonObj = new JSONObject(); JSONArray files = (JSONArray) jsonParam.get(AJAX_PARAM_FILES_ID); boolean allUploaded = true; Map<String, Object> sessionMap = context.getExternalContext().getSessionMap(); for (int i = 0; i < files.length(); i++) { JSONArray file = files.getJSONArray(i); if (file.getString(3).equals("UPLOADED")) { if (!sessionMap.containsKey(file.getString(0))) { allUploaded = false; break; } } } if (allUploaded) { List<FileUploadItem> filesItems = new LinkedList<FileUploadItem>(); for (int i = 0; i < files.length(); i++) { JSONArray file = files.getJSONArray(i); if (file.getString(3).equals("UPLOADED")) { filesItems.add((FileUploadItem) sessionMap.get(file.getString(0))); sessionMap.remove(file.getString(0)); } else if (file.getString(3).equals("STOPPED")) { filesItems.add(new FileUploadItem(file.getString(2), null, FileUploadStatus.STOPPED)); sessionMap.remove(PROGRESS_ID + file.getString(1)); } else if (file.getString(3).equals("ERROR")) { filesItems.add(new FileUploadItem(file.getString(2), null, FileUploadStatus.FAILED)); } else if (file.getString(3).equals("SIZE_LIMIT_EXCEEDED")) { filesItems.add(new FileUploadItem(file.getString(2), null, FileUploadStatus.SIZE_LIMIT_EXCEEDED)); } } FileUpload fileUpload = (FileUpload) component; MethodExpression uploadCompletionListener = fileUpload.getUploadCompletionListener(); if (uploadCompletionListener != null) { uploadCompletionListener.invoke( context.getELContext(), new Object[]{ new UploadCompletionEvent(fileUpload, filesItems)}); } } Rendering.addJsonParam(jsonObj, "allUploaded", allUploaded); return jsonObj; } return null; } }
false
false
null
null
diff --git a/plugin/src/org/perfidix/perclipse/launcher/PerfidixLaunchConfiguration.java b/plugin/src/org/perfidix/perclipse/launcher/PerfidixLaunchConfiguration.java index dcce225..f15e3c2 100755 --- a/plugin/src/org/perfidix/perclipse/launcher/PerfidixLaunchConfiguration.java +++ b/plugin/src/org/perfidix/perclipse/launcher/PerfidixLaunchConfiguration.java @@ -1,282 +1,282 @@ /** * Copyright (c) 2012, University of Konstanz, Distributed Systems Group * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of Konstanz nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.perfidix.perclipse.launcher; import java.io.File; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.debug.core.ILaunch; import org.eclipse.debug.core.ILaunchConfiguration; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.launching.AbstractJavaLaunchConfigurationDelegate; import org.eclipse.jdt.launching.ExecutionArguments; import org.eclipse.jdt.launching.IJavaLaunchConfigurationConstants; import org.eclipse.jdt.launching.IVMInstall; import org.eclipse.jdt.launching.IVMRunner; import org.eclipse.jdt.launching.SocketUtil; import org.eclipse.jdt.launching.VMRunnerConfiguration; import org.perfidix.perclipse.model.PerclipseViewSkeleton; import org.perfidix.perclipse.util.BenchSearchEngine; /** * The PerfidixLaunchConfiguration class is a subclass of the * AbstractJavaLaunchConfigurationDelegate and so our implementation of * LaunchConfigurationDelegate. It contains the necessary configurations for * starting perfidix within our plugin. * * @author Graf S., Lewandowski L., DiSy, University of Konstanz */ public class PerfidixLaunchConfiguration extends AbstractJavaLaunchConfigurationDelegate { /** * The launch container attribute. */ public static final String LAUNCH_CONT_ATTR = PerclipseActivator.PLUGIN_ID + ".CONTAINER"; /** * The bench name attribute. */ public static final String BENCH_NAME_ATTR = PerclipseActivator.PLUGIN_ID + ".BENCHNAME"; /** * The id of perfidix application. */ public static final String ID_PERFIDIX_APP = "org.perfidix.configureBench"; /** {@inheritDoc} */ public void launch( final ILaunchConfiguration configuration, final String mode, final ILaunch launch, final IProgressMonitor monitor) throws CoreException { final IVMInstall vmInst = verifyVMInstall(configuration); final IVMRunner runner = vmInst.getVMRunner(mode); try { final BenchSearchResult searchResult = findBenchTypes(configuration); final int port = SocketUtil.findFreePort(); final PerclipseViewSkeleton skeleton = new PerclipseViewSkeleton(port); skeleton.start(); final VMRunnerConfiguration runConfig = launchTypes(configuration, mode, searchResult, port); runner.run(runConfig, launch, monitor); } catch (Exception e) { PerclipseActivator.log(e); } } /** * This method checks the configuration if you try to bench a * project/package or just a single class and gives as result the * BenchSearchResult object. * * @param configuration * @return The types representing benchs to be launched for this * configuration * @throws CoreException * @throws InterruptedException * @throws InvocationTargetException */ private BenchSearchResult findBenchTypes( final ILaunchConfiguration configuration) throws CoreException, InvocationTargetException, InterruptedException { final IJavaProject javaProject = getJavaProject(configuration); IType[] types = null; /* * Check LAUNCH_CONTAINER_ATTR to see if we are benching an entire * project/package or just a single class. */ final String containerHandle = configuration.getAttribute(LAUNCH_CONT_ATTR, ""); //$NON-NLS-1$ if (containerHandle.length() == 0) { // benching a single class final String benchTypeName = configuration .getAttribute( IJavaLaunchConfigurationConstants.ATTR_MAIN_TYPE_NAME, (String) null); types = new IType[] { javaProject.findType(benchTypeName) }; PerclipseActivator.logInfo("Benching a single class " + benchTypeName); } else { final IJavaElement element = JavaCore.create(containerHandle); if(element!=null && element.exists()){ types = BenchSearchEngine.findBenchs(new Object[] { element }); } // benching an entire project/package // types = BenchSearchEngine.findBenchs(new Object[] { javaProject }); PerclipseActivator.logInfo("Benching "+element.getElementName()); } return new BenchSearchResult(types); } /** * @param configuration * @param mode * @param benchs * @param port * @return * @throws CoreException */ private VMRunnerConfiguration launchTypes( final ILaunchConfiguration configuration, final String mode, final BenchSearchResult benchs, final int port) throws CoreException { final File workingDir = verifyWorkingDirectory(configuration); String workingDirName = null; if (workingDir != null) { workingDirName = workingDir.getAbsolutePath(); } // Program & VM args final String vmArgs = getVMArguments(configuration); final ExecutionArguments execArgs = new ExecutionArguments(vmArgs, ""); //$NON-NLS-1$ final String[] envp = getEnvironment(configuration); final VMRunnerConfiguration runConfig = createVMRunner(configuration, benchs, mode, port); runConfig.setVMArguments(execArgs.getVMArgumentsArray()); runConfig.setWorkingDirectory(workingDirName); runConfig.setEnvironment(envp); - final Map<?, ?> vmAttributesMap = + final Map<String, Object> vmAttributesMap = getVMSpecificAttributesMap(configuration); runConfig.setVMSpecificAttributesMap(vmAttributesMap); final String[] bootpath = getBootpath(configuration); runConfig.setBootClassPath(bootpath); return runConfig; } /** * This method creates a VMRunner for our perfidix project. * * @param configuration * The created launch configuration for the project which has to * be benched. * @param benchTypes * The result of the bench type search. * @param runMode * The launch mode run/debug. * @param port * The port where the * {@link org.perfidix.perclipse.model.PerclipseViewSkeleton} is * listening. * @return The runner configuration. * @throws CoreException * The exception. */ protected VMRunnerConfiguration createVMRunner( final ILaunchConfiguration configuration, final BenchSearchResult benchTypes, final String runMode, final int port) throws CoreException { // String[] classPath = createClassPath(configuration, // benchTypes.getTestKind()); final String[] classPath = getClasspath(configuration); final VMRunnerConfiguration vmConfig = new VMRunnerConfiguration( "org.perfidix.socketadapter.SocketAdapter", classPath); //$NON-NLS-1$ final List<String> argv = getVMArgs(configuration, benchTypes, runMode, port); String[] args = new String[argv.size()]; args = (String[]) argv.toArray(new String[argv.size()]); vmConfig.setProgramArguments(args); return vmConfig; } /** * This method returns the VM arguments in a Vector List for given launch * configuration, bench search result, the launch mode and the port for the * skeleton. * * @param configuration * The launch configuration. * @param result * The result of the search for bench elements within the * launching project. * @param runMode * The launch mode - run/debug. * @param port * The port where the skeleton is listening. * @return A Vector List containing the VM arguments for invoking perfidix's * main. * @throws CoreException * The exception. */ public List<String> getVMArgs( final ILaunchConfiguration configuration, final BenchSearchResult result, final String runMode, final int port) throws CoreException { final String progArgs = getProgramArguments(configuration); // insert the program arguments final List<String> argv = new ArrayList<String>(10); final ExecutionArguments execArgs = new ExecutionArguments("", progArgs); //$NON-NLS-1$ final String[] progArg = execArgs.getProgramArgumentsArray(); for (String string : progArg) { argv.add(string); } final IType[] benchTypes = result.getTypes(); for (int i = 0; i < benchTypes.length; i++) { argv.add(benchTypes[i].getFullyQualifiedName()); } argv.add("-Port"); final String stringPort = Integer.toString(port); argv.add(stringPort); return argv; } } \ No newline at end of file
true
false
null
null
diff --git a/src/org/eclipse/jface/viewers/ColumnViewer.java b/src/org/eclipse/jface/viewers/ColumnViewer.java index 281b9548..51149e10 100644 --- a/src/org/eclipse/jface/viewers/ColumnViewer.java +++ b/src/org/eclipse/jface/viewers/ColumnViewer.java @@ -1,560 +1,579 @@ /******************************************************************************* * Copyright (c) 2006 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation * Tom Schindl <tom.schindl@bestsolution.at> - initial API and implementation; bug 153993 * fix in bug 163317 - * fix in bug 151295, bug 167323 + * fix in bug 151295, bug 167323, bug 167858 ******************************************************************************/ package org.eclipse.jface.viewers; import org.eclipse.core.runtime.Assert; import org.eclipse.swt.events.MouseAdapter; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Item; import org.eclipse.swt.widgets.Widget; /** * The ColumnViewer is the abstract superclass of viewers that have columns * (e.g., AbstractTreeViewer and AbstractTableViewer). Concrete subclasses of * {@link ColumnViewer} should implement a matching concrete subclass of * {@link ViewerColumn}. * * <strong> This class is not intended to be subclassed outside of the JFace * viewers framework.</strong> * * @since 3.3 <strong>EXPERIMENTAL</strong> This class or interface has been * added as part of a work in progress. This API may change at any given * time. Please do not use this API without consulting with the * Platform/UI team. * */ public abstract class ColumnViewer extends StructuredViewer { private ToolTipSupport tooltipSupport; /** * The cell is a cached viewer cell used for refreshing. */ private ViewerCell cell = new ViewerCell(null, 0); private ColumnViewerEditor viewerEditor; private int tabEditingStyle = EditingSupport.TABBING_NONE; /** * Create a new instance of the receiver. */ public ColumnViewer() { viewerEditor = createViewerEditor(); } protected void hookControl(Control control) { super.hookControl(control); hookEditingSupport(control); } /** * Hook up the editing support. Subclasses may override. * * @param control * the control you want to hook on */ protected void hookEditingSupport(Control control) { // Needed for backwards comp with AbstractTreeViewer and TableTreeViewer // who are not hooked this way others may already overwrite and provide // their // own impl if (viewerEditor != null) { control.addMouseListener(new MouseAdapter() { public void mouseDown(MouseEvent e) { viewerEditor.handleMouseDown(e); } }); } } /** * Creates the viewer editor used for editing cell contents. To be implemented by subclasses. * * @return the editor, or <code>null</code> if this viewer does not support editing cell contents. */ protected abstract ColumnViewerEditor createViewerEditor(); /** * Returns the viewer cell at the given widget-relative coordinates, or * <code>null</code> if there is no cell at that location * * @param point * the widget-relative coordinates * @return the cell or <code>null</code> if no cell is found at the given point */ ViewerCell getCell(Point point) { ViewerRow row = getViewerRow(point); if (row != null) { return row.getCell(point); } return null; } /** * Returns the viewer row at the given widget-relative coordinates. * * @param point * the widget-relative coordinates of the viewer row * @return ViewerRow the row or <code>null</code> if no row is found at * the given coordinates */ protected ViewerRow getViewerRow(Point point) { Item item = getItemAt(point); if (item != null) { return getViewerRowFromItem(item); } return null; } /** * Returns the viewer row associated with the given row widget. * * @param item the row widget * @return ViewerRow the associated viewer row */ protected ViewerRow getViewerRowFromItem(Widget item) { return (ViewerRow) item.getData(ViewerRow.ROWPART_KEY); } /** * Returns the column widget at the given column index. * * @param columnIndex the column index * @return Widget the column widget */ protected abstract Widget getColumnViewerOwner(int columnIndex); /** * Returns the viewer column for the given column index. * * @param columnIndex * the column index * @return the viewer column at the given index, or <code>null</code> if * there is none for the given index */ /* package */ ViewerColumn getViewerColumn(final int columnIndex) { ViewerColumn viewer; Widget columnOwner = getColumnViewerOwner(columnIndex); if (columnOwner == null) { return null; } viewer = (ViewerColumn) columnOwner .getData(ViewerColumn.COLUMN_VIEWER_KEY); if (viewer == null) { viewer = createViewerColumn(columnOwner, CellLabelProvider .createViewerLabelProvider(getLabelProvider())); setupEditingSupport(columnIndex, viewer); } if (viewer.getEditingSupport() == null && getCellModifier() != null) { setupEditingSupport(columnIndex, viewer); } return viewer; } /** * Sets up editing support for the given column based on the "old" cell editor API. * * @param columnIndex * @param viewer */ private void setupEditingSupport(final int columnIndex, ViewerColumn viewer) { if (getCellModifier() != null) { viewer.setEditingSupport(new EditingSupport(this) { /* * (non-Javadoc) * * @see org.eclipse.jface.viewers.EditingSupport#canEdit(java.lang.Object) */ public boolean canEdit(Object element) { return getCellModifier().canModify(element, (String) getColumnProperties()[columnIndex]); } /* * (non-Javadoc) * * @see org.eclipse.jface.viewers.EditingSupport#getCellEditor(java.lang.Object) */ public CellEditor getCellEditor(Object element) { return getCellEditors()[columnIndex]; } /* * (non-Javadoc) * * @see org.eclipse.jface.viewers.EditingSupport#getValue(java.lang.Object) */ public Object getValue(Object element) { return getCellModifier().getValue(element, (String) getColumnProperties()[columnIndex]); } /* * (non-Javadoc) * * @see org.eclipse.jface.viewers.EditingSupport#setValue(java.lang.Object, * java.lang.Object) */ public void setValue(Object element, Object value) { getCellModifier().modify(findItem(element), (String) getColumnProperties()[columnIndex], value); } }); } } /** * Creates a generic viewer column for the given column widget, based on the given label provider. * * @param columnOwner the column widget * @param labelProvider the label provider to use for the column * @return ViewerColumn the viewer column */ private ViewerColumn createViewerColumn(Widget columnOwner, CellLabelProvider labelProvider) { ViewerColumn column = new ViewerColumn(this,columnOwner) {}; column.setLabelProvider(labelProvider, false); return column; } /** * Activate the support for custom tooltips. */ public void activateCustomTooltips() { if (tooltipSupport == null) { tooltipSupport = new ToolTipSupport(this); } else { tooltipSupport.activate(); } } /** * Deactivate the support for custom tooltips. */ public void deactivateCustomTooltips() { if (tooltipSupport != null) { tooltipSupport.deactivate(); } } /** * Update the cached cell object with the given row and column. * * @param rowItem * @param column * @return ViewerCell */ /* package */ ViewerCell updateCell(ViewerRow rowItem, int column) { cell.update(rowItem, column); return cell; } /** * Returns the {@link Item} at the given widget-relative coordinates, or * <code>null</code> if there is no item at the given coordinates. * * @param point * the widget-relative coordinates * @return the {@link Item} at the coordinates or <code>null</code> if there * is no item at the given coordinates */ protected abstract Item getItemAt(Point point); /* * (non-Javadoc) * * @see org.eclipse.jface.viewers.StructuredViewer#getItem(int, int) */ protected Item getItem(int x, int y) { return getItemAt(getControl().toControl(x, y)); } /** * The column viewer implementation of this <code>Viewer</code> framework * method ensures that the given label provider is an instance of * <code>ITableLabelProvider</code>, <code>ILabelProvider</code>, or * <code>CellLabelProvider</code>. * <p> * If the label provider is an {@link ITableLabelProvider}, then it * provides a separate label text and image for each column. Implementers of * <code>ITableLabelProvider</code> may also implement * {@link ITableColorProvider} and/or {@link ITableFontProvider} to provide * colors and/or fonts. * </p> * <p> * If the label provider is an <code>ILabelProvider</code>, then it * provides only the label text and image for the first column, and any * remaining columns are blank. Implementers of <code>ILabelProvider</code> * may also implement {@link IColorProvider} and/or {@link IFontProvider} to * provide colors and/or fonts. * </p> * */ public void setLabelProvider(IBaseLabelProvider labelProvider) { Assert.isTrue(labelProvider instanceof ITableLabelProvider || labelProvider instanceof ILabelProvider || labelProvider instanceof CellLabelProvider); updateColumnParts(labelProvider);// Reset the label providers in the // columns super.setLabelProvider(labelProvider); } /** * Clear the viewer parts for the columns */ private void updateColumnParts(IBaseLabelProvider labelProvider) { ViewerColumn column; int i = 0; while ((column = getViewerColumn(i++)) != null) { column.setLabelProvider(CellLabelProvider .createViewerLabelProvider(labelProvider), false); } } /** * Cancels a currently active cell editor if one is active. All changes * already done in the cell editor are lost. * * @since 3.1 (in subclasses, added in 3.3 to abstract class) */ public void cancelEditing() { if (viewerEditor != null) { viewerEditor.cancelEditing(); } } /** * Apply the value of the active cell editor if one is active. * * @since 3.3 */ protected void applyEditorValue() { if (viewerEditor != null) { viewerEditor.applyEditorValue(); } } /** * Starts editing the given element at the given column index. * * @param element * the element * @param column * the column index * @since 3.1 (in subclasses, added in 3.3 to abstract class) */ public void editElement(Object element, int column) { if (viewerEditor != null) { viewerEditor.editElement(element, column); } } /** * Return the CellEditors for the receiver, or <code>null</code> if no * cell editors are set. * <p> * Since 3.3, an alternative API is available, see * {@link ViewerColumn#setEditingSupport(EditingSupport)} for a more flexible * way of editing values in a column viewer. * </p> * * @return CellEditor[] * @since 3.1 (in subclasses, added in 3.3 to abstract class) * @see ViewerColumn#setEditingSupport(EditingSupport) * @see EditingSupport */ public CellEditor[] getCellEditors() { if (viewerEditor != null) { return viewerEditor.getCellEditors(); } return null; } /** * Returns the cell modifier of this viewer, or <code>null</code> if none * has been set. * * <p> * Since 3.3, an alternative API is available, see * {@link ViewerColumn#setEditingSupport(EditingSupport)} for a more flexible * way of editing values in a column viewer. * </p> * * @return the cell modifier, or <code>null</code> * @since 3.1 (in subclasses, added in 3.3 to abstract class) * @see ViewerColumn#setEditingSupport(EditingSupport) * @see EditingSupport */ public ICellModifier getCellModifier() { if (viewerEditor != null) { return viewerEditor.getCellModifier(); } return null; } /** * Returns the column properties of this table viewer. The properties must * correspond with the columns of the table control. They are used to * identify the column in a cell modifier. * * <p> * Since 3.3, an alternative API is available, see * {@link ViewerColumn#setEditingSupport(EditingSupport)} for a more flexible * way of editing values in a column viewer. * </p> * * @return the list of column properties * @since 3.1 (in subclasses, added in 3.3 to abstract class) * @see ViewerColumn#setEditingSupport(EditingSupport) * @see EditingSupport */ public Object[] getColumnProperties() { if (viewerEditor != null) { return viewerEditor.getColumnProperties(); } return null; } /** * Returns whether there is an active cell editor. * * <p> * Since 3.3, an alternative API is available, see * {@link ViewerColumn#setEditingSupport(EditingSupport)} for a more flexible * way of editing values in a column viewer. * </p> * * @return <code>true</code> if there is an active cell editor, and * <code>false</code> otherwise * @since 3.1 (in subclasses, added in 3.3 to abstract class) * @see ViewerColumn#setEditingSupport(EditingSupport) * @see EditingSupport */ public boolean isCellEditorActive() { if (viewerEditor != null) { return viewerEditor.isCellEditorActive(); } return false; } /** * Sets the cell editors of this column viewer. If editing is not supported * by this viewer the call simply has no effect. * * <p> * Since 3.3, an alternative API is available, see * {@link ViewerColumn#setEditingSupport(EditingSupport)} for a more flexible * way of editing values in a column viewer. * </p> * * @param editors * the list of cell editors * @since 3.1 (in subclasses, added in 3.3 to abstract class) * @see ViewerColumn#setEditingSupport(EditingSupport) * @see EditingSupport */ public void setCellEditors(CellEditor[] editors) { if (viewerEditor != null) { viewerEditor.setCellEditors(editors); } } /** * Sets the cell modifier for this column viewer. This method does nothing if editing * is not supported by this viewer. * * <p> * Since 3.3, an alternative API is available, see * {@link ViewerColumn#setEditingSupport(EditingSupport)} for a more flexible * way of editing values in a column viewer. * </p> * * @param modifier * the cell modifier * @since 3.1 (in subclasses, added in 3.3 to abstract class) * @see ViewerColumn#setEditingSupport(EditingSupport) * @see EditingSupport */ public void setCellModifier(ICellModifier modifier) { if (viewerEditor != null) { viewerEditor.setCellModifier(modifier); } } /** * Sets the column properties of this column viewer. The properties must * correspond with the columns of the control. They are used to identify the * column in a cell modifier. If editing is not supported by this viewer the * call simply has no effect. * * <p> * Since 3.3, an alternative API is available, see * {@link ViewerColumn#setEditingSupport(EditingSupport)} for a more flexible * way of editing values in a column viewer. * </p> * * @param columnProperties * the list of column properties * @since 3.1 (in subclasses, added in 3.3 to abstract class) * @see ViewerColumn#setEditingSupport(EditingSupport) * @see EditingSupport */ public void setColumnProperties(String[] columnProperties) { if (viewerEditor != null) { viewerEditor.setColumnProperties(columnProperties); } } /** * The tab-editing style used if the default implementation is used * * @param tabEditingStyle * bit mask for the tab editing style */ public void setTabEditingStyle(int tabEditingStyle) { this.tabEditingStyle = tabEditingStyle; } int getTabEditingStyle() { return this.tabEditingStyle; } /** * Returns the number of columns contained in the receiver. If no columns * were created by the programmer, this value is zero, despite the fact that * visually, one column of items may be visible. This occurs when the * programmer uses the column viewer like a list, adding elements but never * creating a column. * * @return the number of columns * * @since 3.3 */ protected abstract int doGetColumnCount(); + + /** + * Returns the label provider associated with the column at the given index + * or <code>null</code> if no column with this index is known. + * + * @param columnIndex + * the column index + * @return the label provider associated with the column or + * <code>null</code> if no column with this index is known + * + * @since 3.3 + */ + public CellLabelProvider getLabelProvider(int columnIndex) { + ViewerColumn column = getViewerColumn(columnIndex); + if (column != null) { + return column.getLabelProvider(); + } + return null; + } }
false
false
null
null
diff --git a/spring-orm/src/main/java/org/springframework/orm/hibernate3/support/OpenSessionInViewFilter.java b/spring-orm/src/main/java/org/springframework/orm/hibernate3/support/OpenSessionInViewFilter.java index 6c43e78f9..f55ae4e43 100644 --- a/spring-orm/src/main/java/org/springframework/orm/hibernate3/support/OpenSessionInViewFilter.java +++ b/spring-orm/src/main/java/org/springframework/orm/hibernate3/support/OpenSessionInViewFilter.java @@ -1,318 +1,318 @@ /* * Copyright 2002-2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.orm.hibernate3.support; import java.io.IOException; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.hibernate.FlushMode; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.dao.DataAccessResourceFailureException; import org.springframework.orm.hibernate3.SessionFactoryUtils; import org.springframework.orm.hibernate3.SessionHolder; import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.request.async.AbstractDelegatingCallable; import org.springframework.web.context.request.async.AsyncExecutionChain; import org.springframework.web.context.support.WebApplicationContextUtils; import org.springframework.web.filter.OncePerRequestFilter; /** * Servlet 2.3 Filter that binds a Hibernate Session to the thread for the entire * processing of the request. Intended for the "Open Session in View" pattern, * i.e. to allow for lazy loading in web views despite the original transactions * already being completed. * * <p>This filter makes Hibernate Sessions available via the current thread, which * will be autodetected by transaction managers. It is suitable for service layer * transactions via {@link org.springframework.orm.hibernate3.HibernateTransactionManager} * or {@link org.springframework.transaction.jta.JtaTransactionManager} as well * as for non-transactional execution (if configured appropriately). * * <p><b>NOTE</b>: This filter will by default <i>not</i> flush the Hibernate Session, * with the flush mode set to <code>FlushMode.NEVER</code>. It assumes to be used * in combination with service layer transactions that care for the flushing: The * active transaction manager will temporarily change the flush mode to * <code>FlushMode.AUTO</code> during a read-write transaction, with the flush * mode reset to <code>FlushMode.NEVER</code> at the end of each transaction. * If you intend to use this filter without transactions, consider changing * the default flush mode (through the "flushMode" property). * * <p><b>WARNING:</b> Applying this filter to existing logic can cause issues that * have not appeared before, through the use of a single Hibernate Session for the * processing of an entire request. In particular, the reassociation of persistent * objects with a Hibernate Session has to occur at the very beginning of request * processing, to avoid clashes with already loaded instances of the same objects. * * <p>Alternatively, turn this filter into deferred close mode, by specifying * "singleSession"="false": It will not use a single session per request then, * but rather let each data access operation or transaction use its own session * (like without Open Session in View). Each of those sessions will be registered * for deferred close, though, actually processed at request completion. * * <p>A single session per request allows for most efficient first-level caching, * but can cause side effects, for example on <code>saveOrUpdate</code> or when * continuing after a rolled-back transaction. The deferred close strategy is as safe * as no Open Session in View in that respect, while still allowing for lazy loading * in views (but not providing a first-level cache for the entire request). * * <p>Looks up the SessionFactory in Spring's root web application context. * Supports a "sessionFactoryBeanName" filter init-param in <code>web.xml</code>; * the default bean name is "sessionFactory". Looks up the SessionFactory on each * request, to avoid initialization order issues (when using ContextLoaderServlet, * the root application context will get initialized <i>after</i> this filter). * * @author Juergen Hoeller * @since 1.2 * @see #setSingleSession * @see #setFlushMode * @see #lookupSessionFactory * @see OpenSessionInViewInterceptor * @see org.springframework.orm.hibernate3.HibernateInterceptor * @see org.springframework.orm.hibernate3.HibernateTransactionManager * @see org.springframework.orm.hibernate3.SessionFactoryUtils#getSession * @see org.springframework.transaction.support.TransactionSynchronizationManager */ public class OpenSessionInViewFilter extends OncePerRequestFilter { public static final String DEFAULT_SESSION_FACTORY_BEAN_NAME = "sessionFactory"; private String sessionFactoryBeanName = DEFAULT_SESSION_FACTORY_BEAN_NAME; private boolean singleSession = true; private FlushMode flushMode = FlushMode.MANUAL; /** * Set the bean name of the SessionFactory to fetch from Spring's * root application context. Default is "sessionFactory". * @see #DEFAULT_SESSION_FACTORY_BEAN_NAME */ public void setSessionFactoryBeanName(String sessionFactoryBeanName) { this.sessionFactoryBeanName = sessionFactoryBeanName; } /** * Return the bean name of the SessionFactory to fetch from Spring's * root application context. */ protected String getSessionFactoryBeanName() { return this.sessionFactoryBeanName; } /** * Set whether to use a single session for each request. Default is "true". * <p>If set to "false", each data access operation or transaction will use * its own session (like without Open Session in View). Each of those * sessions will be registered for deferred close, though, actually * processed at request completion. * @see SessionFactoryUtils#initDeferredClose * @see SessionFactoryUtils#processDeferredClose */ public void setSingleSession(boolean singleSession) { this.singleSession = singleSession; } /** * Return whether to use a single session for each request. */ protected boolean isSingleSession() { return this.singleSession; } /** * Specify the Hibernate FlushMode to apply to this filter's * {@link org.hibernate.Session}. Only applied in single session mode. * <p>Can be populated with the corresponding constant name in XML bean * definitions: e.g. "AUTO". * <p>The default is "MANUAL". Specify "AUTO" if you intend to use * this filter without service layer transactions. * @see org.hibernate.Session#setFlushMode * @see org.hibernate.FlushMode#MANUAL * @see org.hibernate.FlushMode#AUTO */ public void setFlushMode(FlushMode flushMode) { this.flushMode = flushMode; } /** * Return the Hibernate FlushMode that this filter applies to its * {@link org.hibernate.Session} (in single session mode). */ protected FlushMode getFlushMode() { return this.flushMode; } @Override protected void doFilterInternal( HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { AsyncExecutionChain chain = AsyncExecutionChain.getForCurrentRequest(request); SessionFactory sessionFactory = lookupSessionFactory(request); boolean participate = false; if (isSingleSession()) { // single session mode if (TransactionSynchronizationManager.hasResource(sessionFactory)) { // Do not modify the Session: just set the participate flag. participate = true; } else { logger.debug("Opening single Hibernate Session in OpenSessionInViewFilter"); Session session = getSession(sessionFactory); SessionHolder sessionHolder = new SessionHolder(session); TransactionSynchronizationManager.bindResource(sessionFactory, sessionHolder); chain.push(getAsyncCallable(request, sessionFactory, sessionHolder)); } } else { // deferred close mode if (SessionFactoryUtils.isDeferredCloseActive(sessionFactory)) { // Do not modify deferred close: just set the participate flag. participate = true; } else { SessionFactoryUtils.initDeferredClose(sessionFactory); } } try { filterChain.doFilter(request, response); } finally { if (!participate) { if (isSingleSession()) { // single session mode SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.unbindResource(sessionFactory); if (!chain.pop()) { return; } logger.debug("Closing single Hibernate Session in OpenSessionInViewFilter"); closeSession(sessionHolder.getSession(), sessionFactory); } else { - if (!chain.pop()) { + if (chain.isAsyncStarted()) { throw new IllegalStateException("Deferred close is not supported with async requests."); } // deferred close mode SessionFactoryUtils.processDeferredClose(sessionFactory); } } } } /** * Look up the SessionFactory that this filter should use, * taking the current HTTP request as argument. * <p>The default implementation delegates to the {@link #lookupSessionFactory()} * variant without arguments. * @param request the current request * @return the SessionFactory to use */ protected SessionFactory lookupSessionFactory(HttpServletRequest request) { return lookupSessionFactory(); } /** * Look up the SessionFactory that this filter should use. * <p>The default implementation looks for a bean with the specified name * in Spring's root application context. * @return the SessionFactory to use * @see #getSessionFactoryBeanName */ protected SessionFactory lookupSessionFactory() { if (logger.isDebugEnabled()) { logger.debug("Using SessionFactory '" + getSessionFactoryBeanName() + "' for OpenSessionInViewFilter"); } WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext()); return wac.getBean(getSessionFactoryBeanName(), SessionFactory.class); } /** * Get a Session for the SessionFactory that this filter uses. * Note that this just applies in single session mode! * <p>The default implementation delegates to the * <code>SessionFactoryUtils.getSession</code> method and * sets the <code>Session</code>'s flush mode to "MANUAL". * <p>Can be overridden in subclasses for creating a Session with a * custom entity interceptor or JDBC exception translator. * @param sessionFactory the SessionFactory that this filter uses * @return the Session to use * @throws DataAccessResourceFailureException if the Session could not be created * @see org.springframework.orm.hibernate3.SessionFactoryUtils#getSession(SessionFactory, boolean) * @see org.hibernate.FlushMode#MANUAL */ protected Session getSession(SessionFactory sessionFactory) throws DataAccessResourceFailureException { Session session = SessionFactoryUtils.getSession(sessionFactory, true); FlushMode flushMode = getFlushMode(); if (flushMode != null) { session.setFlushMode(flushMode); } return session; } /** * Close the given Session. * Note that this just applies in single session mode! * <p>Can be overridden in subclasses, e.g. for flushing the Session before * closing it. See class-level javadoc for a discussion of flush handling. * Note that you should also override getSession accordingly, to set * the flush mode to something else than NEVER. * @param session the Session used for filtering * @param sessionFactory the SessionFactory that this filter uses */ protected void closeSession(Session session, SessionFactory sessionFactory) { SessionFactoryUtils.closeSession(session); } /** * Create a Callable to extend the use of the open Hibernate Session to the * async thread completing the request. */ private AbstractDelegatingCallable getAsyncCallable(final HttpServletRequest request, final SessionFactory sessionFactory, final SessionHolder sessionHolder) { return new AbstractDelegatingCallable() { public Object call() throws Exception { TransactionSynchronizationManager.bindResource(sessionFactory, sessionHolder); try { getNext().call(); } finally { SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.unbindResource(sessionFactory); logger.debug("Closing Hibernate Session in OpenSessionInViewFilter"); SessionFactoryUtils.closeSession(sessionHolder.getSession()); } return null; } }; } }
true
true
protected void doFilterInternal( HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { AsyncExecutionChain chain = AsyncExecutionChain.getForCurrentRequest(request); SessionFactory sessionFactory = lookupSessionFactory(request); boolean participate = false; if (isSingleSession()) { // single session mode if (TransactionSynchronizationManager.hasResource(sessionFactory)) { // Do not modify the Session: just set the participate flag. participate = true; } else { logger.debug("Opening single Hibernate Session in OpenSessionInViewFilter"); Session session = getSession(sessionFactory); SessionHolder sessionHolder = new SessionHolder(session); TransactionSynchronizationManager.bindResource(sessionFactory, sessionHolder); chain.push(getAsyncCallable(request, sessionFactory, sessionHolder)); } } else { // deferred close mode if (SessionFactoryUtils.isDeferredCloseActive(sessionFactory)) { // Do not modify deferred close: just set the participate flag. participate = true; } else { SessionFactoryUtils.initDeferredClose(sessionFactory); } } try { filterChain.doFilter(request, response); } finally { if (!participate) { if (isSingleSession()) { // single session mode SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.unbindResource(sessionFactory); if (!chain.pop()) { return; } logger.debug("Closing single Hibernate Session in OpenSessionInViewFilter"); closeSession(sessionHolder.getSession(), sessionFactory); } else { if (!chain.pop()) { throw new IllegalStateException("Deferred close is not supported with async requests."); } // deferred close mode SessionFactoryUtils.processDeferredClose(sessionFactory); } } } }
protected void doFilterInternal( HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { AsyncExecutionChain chain = AsyncExecutionChain.getForCurrentRequest(request); SessionFactory sessionFactory = lookupSessionFactory(request); boolean participate = false; if (isSingleSession()) { // single session mode if (TransactionSynchronizationManager.hasResource(sessionFactory)) { // Do not modify the Session: just set the participate flag. participate = true; } else { logger.debug("Opening single Hibernate Session in OpenSessionInViewFilter"); Session session = getSession(sessionFactory); SessionHolder sessionHolder = new SessionHolder(session); TransactionSynchronizationManager.bindResource(sessionFactory, sessionHolder); chain.push(getAsyncCallable(request, sessionFactory, sessionHolder)); } } else { // deferred close mode if (SessionFactoryUtils.isDeferredCloseActive(sessionFactory)) { // Do not modify deferred close: just set the participate flag. participate = true; } else { SessionFactoryUtils.initDeferredClose(sessionFactory); } } try { filterChain.doFilter(request, response); } finally { if (!participate) { if (isSingleSession()) { // single session mode SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.unbindResource(sessionFactory); if (!chain.pop()) { return; } logger.debug("Closing single Hibernate Session in OpenSessionInViewFilter"); closeSession(sessionHolder.getSession(), sessionFactory); } else { if (chain.isAsyncStarted()) { throw new IllegalStateException("Deferred close is not supported with async requests."); } // deferred close mode SessionFactoryUtils.processDeferredClose(sessionFactory); } } } }
diff --git a/WallStreet/src/WallStreet/Investor.java b/WallStreet/src/WallStreet/Investor.java index 10d4105..819f4ea 100644 --- a/WallStreet/src/WallStreet/Investor.java +++ b/WallStreet/src/WallStreet/Investor.java @@ -1,70 +1,70 @@ import java.util.Map; public class Investor { double _money; double _oldmoney; int _confidence; double _stockVal; double _stockValChanged; //lets the investor access the market Market _market; //list of the companies pointing to the int amount they have of the stock Map<Company, Integer> _stocks; public Investor(Market mar){ _money = 5000.0; _oldmoney = 0; - _confidence = _confidence = 43 + random(16); + _confidence = 43 + (int)(16*Math.random()); _stockVal = 0; _stockValChanged = 0; _market = mar; _stocks = new TreeMap<Company, Integer>(); } //find list of all the companies with risk < comfidence. public void changeStockVal(){ double old = _stockVal; _stockVal = 0; for(Company x: _stocks.keySet()){ _stockVal = x.getPrice() * _stocks.get(x); //Need and accessor method in Company that returns the price. } _stockValChanged = _stockVal - old; } public double getStockChange(){ return _stockValChanged; } public double getStockVal(){ return _stockVal; } public double getPort(){ return _money + _stockVal; } public void invest() { } //sell those stocks with the risk > than confidence public void sell() { } public void resetConfidence() { _confidence += (_money + _stockValChanged - _oldmoney) * Math.random()/50; } public double getMoney(){ return _money; } public int getConfidence(){ return _confidence; } } diff --git a/WallStreet/src/WallStreet/WallStreet.java b/WallStreet/src/WallStreet/WallStreet.java index da9c245..0d5b148 100644 --- a/WallStreet/src/WallStreet/WallStreet.java +++ b/WallStreet/src/WallStreet/WallStreet.java @@ -1,16 +1,15 @@ - public class WallStreet { Investor[] _investors; Market _market; public WallStreet() { } public void go() { } public String toString() { return "complete this"; } }
false
false
null
null
diff --git a/src/java/com/idega/block/login/presentation/Login.java b/src/java/com/idega/block/login/presentation/Login.java index 54495a8..0a59d81 100644 --- a/src/java/com/idega/block/login/presentation/Login.java +++ b/src/java/com/idega/block/login/presentation/Login.java @@ -1,1542 +1,1545 @@ // idega 2000 Grimur Jonsson - Tryggvi Larusson - Thorhallur Helgason /* * Copyright 2000-2001 idega.is All Rights Reserved. */ package com.idega.block.login.presentation; import java.rmi.RemoteException; import java.text.MessageFormat; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import javax.ejb.FinderException; import com.idega.business.IBOLookup; import com.idega.core.accesscontrol.business.LoginBusinessBean; import com.idega.core.accesscontrol.business.LoginDBHandler; import com.idega.core.accesscontrol.business.LoginState; import com.idega.core.accesscontrol.data.LoginInfo; import com.idega.core.accesscontrol.data.LoginInfoHome; import com.idega.core.accesscontrol.data.LoginTable; import com.idega.core.accesscontrol.data.LoginTableHome; import com.idega.core.builder.business.ICBuilderConstants; import com.idega.core.builder.data.ICPage; import com.idega.core.contact.data.Email; import com.idega.core.user.data.User; import com.idega.data.IDOLookup; import com.idega.data.IDOLookupException; import com.idega.idegaweb.IWBundle; import com.idega.idegaweb.IWConstants; import com.idega.idegaweb.IWResourceBundle; import com.idega.presentation.Block; import com.idega.presentation.IWContext; import com.idega.presentation.Image; import com.idega.presentation.PresentationObject; import com.idega.presentation.Script; import com.idega.presentation.Table; import com.idega.presentation.text.Link; import com.idega.presentation.text.Text; import com.idega.presentation.ui.CheckBox; import com.idega.presentation.ui.Form; import com.idega.presentation.ui.HiddenInput; import com.idega.presentation.ui.Label; import com.idega.presentation.ui.Parameter; import com.idega.presentation.ui.PasswordInput; import com.idega.presentation.ui.StyledButton; import com.idega.presentation.ui.SubmitButton; import com.idega.presentation.ui.TextInput; import com.idega.presentation.ui.Window; import com.idega.repository.data.RefactorClassRegistry; import com.idega.servlet.filter.IWAuthenticator; import com.idega.user.business.UserBusiness; import com.idega.user.util.Converter; import com.idega.util.SendMail; import com.idega.util.StringHandler; /** * Title: Login - The standard login block in idegaWeb Description: Copyright: * Copyright (c) 2000-2001 idega.is All Rights Reserved Company: idega * * @author <a href="mailto:gimmi@idega.is">Grimur Jonsson </a>, <a * href="mailto:tryggvi@idega.is">Tryggvi Larusson </a> * @version 1.1 */ public class Login extends Block { protected static final String ACTION_TRY_AGAIN = LoginBusinessBean.LOGIN_EVENT_TRYAGAIN; protected static final String ACTION_LOG_IN = LoginBusinessBean.LOGIN_EVENT_LOGIN; protected static final String ACTION_LOG_OFF = LoginBusinessBean.LOGIN_EVENT_LOGOFF; private static final String IB_PAGE_PARAMETER = ICBuilderConstants.IB_PAGE_PARAMETER; private boolean showOnlyInputs = false; private Link loggedOnLink; private String backgroundImageUrl; private String loginWidth = ""; private String loginHeight = ""; private String loginAlignment = "left"; private String userText; private String passwordText; private String color = ""; private String userTextColor = null; private String passwordTextColor = null; private int userTextSize = -1; private int passwordTextSize = -1; private int inputLength = 10; private int loggedOffPageId = -1; private String styleAttribute = "font-family: Verdana; font-size: 8pt; border: 1 solid #000000"; private String textStyles = "font-family: Arial,Helvetica,sans-serif; font-size: 8pt; font-weight: bold; color: #000000; text-decoration: none;"; private String submitButtonAlignment; private Form myForm; private Image loginImage; private Image logoutImage; private Image tryAgainImage; private boolean helpButton = false; private boolean onlyLogoutButton = false; private boolean register = false; private boolean forgot = false; private int _logOnPage = -1; public static String controlParameter; public final static String IW_BUNDLE_IDENTIFIER = "com.idega.block.login"; public static final int LAYOUT_VERTICAL = 1; public static final int LAYOUT_HORIZONTAL = 2; public static final int LAYOUT_STACKED = 3; public static final int SINGLE_LINE = 4; public static final int LAYOUT_FORWARD_LINK = 5; private int LAYOUT = -1; protected IWResourceBundle iwrb; protected IWBundle iwb; protected boolean sendToHTTPS = false; protected boolean sendUserToHomePage = false; private boolean allowCookieLogin = false; private boolean showHint = false; private int _spaceBetween = 4; private boolean _buttonAsLink = false; private boolean _loginImageAsForwardLink = false; private boolean _enterSubmit = false; private final String _linkStyleClass = "Link"; private Image _iconImage; private boolean useImageButton=true; private boolean setNoStyles=false; private int _loginPageID = -1; private final static String FROM_PAGE_PARAMETER = "log_from_page"; protected static final String LOGIN_PARAMETER_NAME = LoginBusinessBean.PARAMETER_USERNAME; protected static final String PASSWORD_PARAMETER_NAME = LoginBusinessBean.PARAMETER_PASSWORD; private static final String HINT_ANSWER_PARAMETER_NAME = "hint_answer"; //private IBPage _pageForInvalidLogin = null; private boolean lockedAsWapLayout = false; private String classToOpenOnLogin; private ICPage loggedOnPage; private ICPage firstLogOnPage; private String urlToForwardToOnLogin; public Login() { super(); setDefaultValues(); } public void main(IWContext iwc) throws Exception { this.iwb = getBundle(iwc); this.iwrb = getResourceBundle(iwc); String hintAnswer = iwc.getParameter(HINT_ANSWER_PARAMETER_NAME); String hintMessage = null; if (hintAnswer != null && hintAnswer.length() > 0) { try { boolean hintRight = testHint(iwc, hintAnswer); if (hintRight) { String sentTo = resetPasswordAndsendMessage(iwc); if(sentTo==null) { hintMessage = this.iwrb.getLocalizedString("login_hint_error", "Error validating hint answer"); } else { hintMessage = this.iwrb.getLocalizedString("login_hint_correct", "Correct answer, instructions have been sent to: ") + sentTo; } } else { hintMessage = this.iwrb.getLocalizedString("login_hint_incorrect", "Answer incorrect"); } } catch (Exception e) { hintMessage = this.iwrb.getLocalizedString("login_hint_error", "Error validating hint answer"); e.printStackTrace(); } } if (this._buttonAsLink) { if (getParentPage() != null) { Script script = null; if (getParentPage().getAssociatedScript() != null) { script = getParentPage().getAssociatedScript(); } else { script = new Script(); getParentPage().setAssociatedScript(script); } script.addFunction("enterSubmit", "function enterSubmit(myfield,e) { var keycode; if (window.event) keycode = window.event.keyCode; else if (e) keycode = e.which; else return true; if (keycode == 13) { myfield.form.submit(); return false; } else return true; }"); this._enterSubmit = true; } } if (this.allowCookieLogin) { //LoginCookieListener is swapped out for IWAuthenticator //iwc.getIWMainApplication().addApplicationEventListener(LoginCookieListener.class); } if (this.sendToHTTPS) { getMainForm().setToSendToHTTPS(); } this.userText = this.iwrb.getLocalizedString("user", "User"); this.passwordText = this.iwrb.getLocalizedString("password", "Password"); LoginState state = internalGetState(iwc); if(state.equals(LoginState.LoggedOn)){ isLoggedOn(iwc); } else if(state.equals(LoginState.LoggedOut)){ startState(iwc); } else if(state.equals(LoginState.Failed)){ loginFailed(iwc, this.iwrb.getLocalizedString("login_failed", "Login failed")); } else if(state.equals(LoginState.NoUser)){ loginFailed(iwc, this.iwrb.getLocalizedString("login_no_user", "Invalid user")); } else if(state.equals(LoginState.WrongPassword)){ loginFailed(iwc, this.iwrb.getLocalizedString("login_wrong", "Invalid password")); } else if(state.equals(LoginState.Expired)){ loginFailed(iwc, this.iwrb.getLocalizedString("login_expired", "Login expired")); } else if(state.equals(LoginState.FailedDisabledNextTime)){ loginFailed(iwc, this.iwrb.getLocalizedString("login_wrong_disabled_next_time", "Invalid password, access closed next time login fails")); if (hintMessage == null) { handleHint(iwc); } } else { if(this.lockedAsWapLayout || IWConstants.MARKUP_LANGUAGE_WML.equals(iwc.getMarkupLanguage())) { startStateWML(iwc); } else { startState(iwc); } } if(getUrlToForwardToOnLogin()!=null){ getMainForm().addParameter(IWAuthenticator.PARAMETER_REDIRECT_URI_ONLOGON,getUrlToForwardToOnLogin()); + } + else if (sendUserToHomePage) { + getMainForm().addParameter(IWAuthenticator.PARAMETER_REDIRECT_USER_TO_PRIMARY_GROUP_HOME_PAGE, "true"); } add(getMainForm()); if (hintMessage != null) { add(hintMessage); } } /** * @param lockedAsWapLayout The lockedAsWapLayout to set. */ public void setLockedAsWapLayout(boolean lockedAsWapLayout) { this.lockedAsWapLayout = lockedAsWapLayout; } private String resetPasswordAndsendMessage(IWContext iwc) { String login = iwc.getParameter(LOGIN_PARAMETER_NAME); User user = null; try { user = getUserBusiness(iwc).getUser(login); } catch (Exception e) { e.printStackTrace(); return null; } if (user == null) { System.out.println("no user found to change password and send notification to"); return null; } // temp password, sent to user so he can log in and change his password. String tmpPassword = StringHandler.getRandomStringNonAmbiguous(8); String server = this.iwb.getProperty("email_server"); if (server == null) { System.out.println("email server bundle property not set, no password email sent to user " + user.getName()); return null; } String letter = this.iwrb.getLocalizedString("login.password_email_body", "You are receiving this mail because you forgot your password on Felix and answered your hint question correctly.\n" + "You need to select a new password. " + "You have been given a new and temporary password on Felix so that you can log in and set a new password.\n " + "Your new and temporary password is \"{0}\"\n"); StringBuffer buf = null; if (letter != null) { try { Collection emailCol = ((com.idega.user.data.User) user).getEmails(); if (emailCol != null && !emailCol.isEmpty()) { Iterator emailIter = emailCol.iterator(); LoginBusinessBean loginBean = LoginBusinessBean.getLoginBusinessBean(iwc); loginBean.resetPassword(login, tmpPassword, true); try { LoginTableHome home = (LoginTableHome) IDOLookup.getHome(LoginTable.class); LoginTable loginTable = home.findByLogin(login); if(loginTable!=null) { LoginInfoHome loginInfoHome = (LoginInfoHome) IDOLookup.getHome(LoginInfo.class); LoginInfo loginInfo = loginInfoHome.findByPrimaryKey(loginTable.getPrimaryKey()); loginInfo.setChangeNextTime(true); loginInfo.setFailedAttemptCount(0); loginInfo.store(); } else { System.out.println("Login table not found for user " + login + ", very odd because password for it has just been changed!!!"); } } catch (Exception e) { System.out.println("Failed to reset login info after password change, not terrible but perhaps inconvenient"); e.printStackTrace(); } buf = new StringBuffer(); boolean firstAddress = true; while (emailIter.hasNext()) { String address = ((Email) emailIter.next()).getEmailAddress(); if (firstAddress) { firstAddress = false; } else { buf.append(";"); } buf.append(address); Object[] objs = { tmpPassword}; String body = MessageFormat.format(letter, objs); System.out.println("Sending password to " + address); SendMail.send(this.iwrb.getLocalizedString("register.email_sender", "<Felix-felagakerfi>felix@isi.is"), address, "", "", server, this.iwrb.getLocalizedString("login.password_email_subject", "Forgotten password on Felix"), body); } } } catch (Exception e) { System.out.println("Couldn't send email password notification to user " + user.getDisplayName()); e.printStackTrace(); return null; } } else { System.out.println("No password letter found, nothing sent to user " + user.getDisplayName()); return null; } return buf == null ? null : buf.toString(); } private boolean testHint(IWContext iwc, String answer) throws Exception { User user = null; boolean ok = false; user = getUserBusiness(iwc).getUser(iwc.getParameter(LOGIN_PARAMETER_NAME)); ok = answer.trim().equals(user.getMetaData("HINT_ANSWER").trim()); return ok; } private User getUserFromLogin(String login) { User user = null; LoginTable loginTable = null; try { LoginTableHome home = (LoginTableHome) IDOLookup.getHome(LoginTable.class); loginTable = home.findByLogin(login); } catch (IDOLookupException ile) { ile.printStackTrace(); } catch (FinderException e) { e.printStackTrace(); } if (loginTable !=null) { user = loginTable.getUser(); } return user; } private void handleHint(IWContext iwc) { if (this.showHint) { String userName = iwc.getParameter(LOGIN_PARAMETER_NAME); if (userName == null) { try { userName = LoginBusinessBean.getLoginSession(iwc).getUserLoginName(); //(String) iwc.getSessionAttribute(LoginBusinessBean.UserAttributeParameter); } catch (RemoteException e) { e.printStackTrace(); } } if (userName != null && userName.length() > 0) { try { User user = getUserFromLogin(userName);//getUserBusiness(iwc).getUser(userName); if(user==null) { user = getUserBusiness(iwc).getUser(userName); } String helpText = this.iwrb.getLocalizedString("login_hint_helptext", "You gave a hint question when you registered, provide the answer you gave at registration"); String question = user.getMetaData("HINT_QUESTION"); if (question != null && question.length() > 0) { TextInput input = new TextInput(HINT_ANSWER_PARAMETER_NAME); SubmitButton button = new SubmitButton(this.iwrb.getLocalizedString("hint_submit", "Answer")); HiddenInput hInput = new HiddenInput(LOGIN_PARAMETER_NAME, userName); Table qTable = new Table(); qTable.mergeCells(1, 1, 2, 1); qTable.add(helpText, 1, 1); qTable.mergeCells(1, 2, 2, 2); qTable.add(question, 1, 2); qTable.mergeCells(1, 3, 2, 3); qTable.add(input, 1, 3); qTable.add(button, 2, 4); Form form = new Form(); form.add(qTable); form.add(hInput); add(form); } } catch (Exception e) { e.printStackTrace(); } } else { System.out.println("Couldn't ask hint question, no login name found"); } } } /* * public static boolean isAdmin(IWContext iwc)throws Exception{ return iwc.is * Admin(); } */ public static User getUser(IWContext iwc) { return iwc.getCurrentUser(); } protected void startState(IWContext iwc) { if (this._logOnPage > 0) { getMainForm().setPageToSubmitTo(this._logOnPage); } /* * if (_redirectPage > 0) { //System.err.println("adding hidden redirect * parameter"); myForm.add(new * HiddenInput(LoginBusinessBean.LoginRedirectPageParameter, * String.valueOf(_redirectPage))); } * * if (_pageForInvalidLogin != null) { //System.err.println("adding hidden * redirect parameter"); myForm.add(new * HiddenInput(LoginBusinessBean.LoginFailedRedirectPageParameter, * _pageForInvalidLogin.getPrimaryKey().toString())); } */ Table loginTable = new Table(); loginTable.setBorder(0); if (this.loginWidth != null) { loginTable.setWidth(this.loginWidth); } if (this.loginHeight != null) { loginTable.setHeight(this.loginHeight); } if (!(this.color.equals(""))) { loginTable.setColor(this.color); } loginTable.setCellpadding(0); loginTable.setCellspacing(0); if (this.backgroundImageUrl != null) { loginTable.setBackgroundImage(new Image(this.backgroundImageUrl)); } int ypos = 1; int xpos = 1; /* * HelpButton helpImage = new HelpButton( * iwrb.getLocalizedString("help_headline", "Web Access"), * iwrb.getLocalizedString("help", ""), * iwrb.getImage("help_image.gif").getURL()); */ Text loginTexti = new Text(this.userText); if (this.userTextSize != -1) { loginTexti.setFontSize(this.userTextSize); } if (this.userTextColor != null) { loginTexti.setFontColor(this.userTextColor); } if(!this.setNoStyles){ loginTexti.setFontStyle(this.textStyles); } Text passwordTexti = new Text(this.passwordText); if (this.passwordTextSize != -1) { passwordTexti.setFontSize(this.passwordTextSize); } if (this.passwordTextColor != null) { passwordTexti.setFontColor(this.passwordTextColor); } if(!this.setNoStyles){ passwordTexti.setFontStyle(this.textStyles); } Table inputTable; TextInput login = new TextInput(LOGIN_PARAMETER_NAME); if(!this.setNoStyles){ login.setMarkupAttribute("style", this.styleAttribute); } login.setSize(this.inputLength); login.setInFocusOnPageLoad(true); if (this._enterSubmit) { login.setOnKeyPress("return enterSubmit(this,event)"); } PasswordInput passw = new PasswordInput(PASSWORD_PARAMETER_NAME); if(!this.setNoStyles){ passw.setMarkupAttribute("style", this.styleAttribute); } passw.setSize(this.inputLength); if (this._enterSubmit) { passw.setOnKeyPress("return enterSubmit(this,event)"); } switch (this.LAYOUT) { case LAYOUT_HORIZONTAL: inputTable = new Table(2, 2); inputTable.setBorder(0); if (!(this.color.equals(""))) { inputTable.setColor(this.color); } inputTable.setCellpadding(1); inputTable.setCellspacing(0); inputTable.add(loginTexti, 1, 1); inputTable.add(login, 1, 2); inputTable.add(passwordTexti, 2, 1); inputTable.add(passw, 2, 2); loginTable.setAlignment(xpos, ypos, "center"); loginTable.add(inputTable, xpos, ypos); ypos++; break; case LAYOUT_VERTICAL: inputTable = new Table(3, 3); inputTable.setBorder(0); if (!(this.color.equals(""))) { inputTable.setColor(this.color); } inputTable.setCellpadding(1); inputTable.setCellspacing(0); inputTable.mergeCells(1, 2, 3, 2); inputTable.setHeight(2, "2"); inputTable.setAlignment(1, 1, "right"); inputTable.setAlignment(1, 3, "right"); inputTable.add(loginTexti, 1, 1); inputTable.add(login, 3, 1); inputTable.add(passwordTexti, 1, 3); inputTable.add(passw, 3, 3); loginTable.setAlignment(xpos, ypos, "center"); loginTable.add(inputTable, xpos, ypos); ypos++; break; case LAYOUT_STACKED: inputTable = new Table(1, 5); inputTable.setBorder(0); inputTable.setCellpadding(0); inputTable.setCellspacing(0); inputTable.addText("", 1, 3); inputTable.setHeight(3, "5"); if (!(this.color.equals(""))) { inputTable.setColor(this.color); } inputTable.setAlignment(1, 1, "left"); inputTable.setAlignment(1, 4, "left"); inputTable.add(loginTexti, 1, 1); inputTable.add(login, 1, 2); inputTable.add(passwordTexti, 1, 4); inputTable.add(passw, 1, 5); loginTable.setAlignment(xpos, ypos, "center"); loginTable.add(inputTable, xpos, ypos); ypos++; break; case SINGLE_LINE: inputTable = new Table(7, 1); inputTable.setBorder(0); inputTable.setCellpadding(0); inputTable.setCellspacing(0); if (!(this.color.equals(""))) { inputTable.setColor(this.color); } inputTable.setAlignment(1, 1, "right"); inputTable.setAlignment(3, 1, "right"); inputTable.setWidth(2, 1, String.valueOf(this._spaceBetween)); inputTable.setWidth(4, 1, String.valueOf(this._spaceBetween * 2)); inputTable.setWidth(6, 1, String.valueOf(this._spaceBetween)); inputTable.add(loginTexti, 1, 1); inputTable.add(login, 3, 1); inputTable.add(passwordTexti, 5, 1); inputTable.add(passw, 7, 1); loginTable.setAlignment(xpos, ypos, "center"); loginTable.add(inputTable, xpos, ypos); xpos = 2; break; case LAYOUT_FORWARD_LINK: this._buttonAsLink = true; inputTable = new Table(1, 1); inputTable.setBorder(0); inputTable.setCellpadding(0); inputTable.setCellspacing(0); //inputTable.add(this.getLoginLinkForPopup(loginTexti)); break; } if (!this.showOnlyInputs) { Table submitTable = new Table(); //if ( helpButton ) { // submitTable = new Table(2,1); //} submitTable.setBorder(0); if (!(this.color.equals(""))) { submitTable.setColor(this.color); } submitTable.setRowVerticalAlignment(1, "middle"); if (!this.helpButton) { submitTable.setAlignment(1, 1, this.submitButtonAlignment); } else { submitTable.setAlignment(2, 1, "right"); } submitTable.setWidth("100%"); if (this._buttonAsLink) { submitTable.setCellpadding(0); submitTable.setCellspacing(0); int column = 1; Link link = null; if (this._loginImageAsForwardLink && this._iconImage != null) { link = new Link(this._iconImage); } else { link = this.getStyleLink(this.iwrb.getLocalizedString("login_text", "Login"), this._linkStyleClass); } switch (this.LAYOUT) { case LAYOUT_FORWARD_LINK: if (this._loginPageID != -1) { //PopUp Link parameters link.setPage(this._loginPageID); link.setParameter(FROM_PAGE_PARAMETER, String.valueOf(iwc.getCurrentIBPageID())); link.setHttps(this.sendToHTTPS); } else { try { throw new Exception(this.getClassName() + ": No login page is set"); } catch (Exception e) { System.err.println(e.getMessage()); e.printStackTrace(); } } break; default: link.setToFormSubmit(getMainForm()); } if (!this._loginImageAsForwardLink && this._iconImage != null) { submitTable.add(this._iconImage, column++, 1); submitTable.setWidth(column++, 1, String.valueOf(this._spaceBetween)); } submitTable.add(link, column, 1); switch (this.LAYOUT) { case LAYOUT_STACKED: loginTable.setHeight(xpos, ypos++, String.valueOf(this._spaceBetween * 2)); break; case LAYOUT_VERTICAL: loginTable.setHeight(xpos, ypos++, String.valueOf(this._spaceBetween * 2)); break; case LAYOUT_HORIZONTAL: loginTable.setWidth(xpos++, ypos, String.valueOf(this._spaceBetween * 2)); break; case SINGLE_LINE: loginTable.setWidth(xpos++, ypos, String.valueOf(this._spaceBetween * 2)); break; default: break; } loginTable.add(submitTable, xpos, ypos); } else { SubmitButton button; if(this.useImageButton && this.loginImage != null){ button = new SubmitButton(this.loginImage, "login_button"); } else{ button = new SubmitButton("login_button", this.iwrb.getLocalizedString("login_text", "Login")); } int pos = !this.helpButton?xpos:xpos+1; if (this.useImageButton && this.loginImage == null) { submitTable.add(new StyledButton(button), pos, 1); } else { submitTable.add(button, pos, 1); } if (this.register || this.forgot || this.allowCookieLogin) { Link registerLink = getRegisterLink(); Link forgotLink = getForgotLink(); int row = 2; int col = 1; switch (this.LAYOUT) { case LAYOUT_HORIZONTAL: case LAYOUT_VERTICAL: row = 2; if (this.register) { submitTable.add(registerLink, 1, row); } if (this.forgot) { submitTable.add(forgotLink, 2, row); } if (this.allowCookieLogin) { //CheckBox cookieCheck = new CheckBox(LoginCookieListener.prmUserAllowsLogin); CheckBox cookieCheck = new CheckBox(IWAuthenticator.PARAMETER_ALLOWS_COOKIE_LOGIN); Text cookieText = new Text(this.iwrb.getLocalizedString("cookie.allow", "Remember me")); if(!this.setNoStyles){ cookieText.setFontStyle(this.textStyles); } row++; submitTable.mergeCells(1, row, 2, row); submitTable.add(cookieCheck, 1, row); submitTable.add(cookieText, 1, row); } break; case LAYOUT_STACKED: row = 2; if (this.register) { submitTable.mergeCells(1, row, 2, row); submitTable.add(registerLink, 1, row); row++; } if (this.forgot) { submitTable.mergeCells(1, row, 2, row); submitTable.add(forgotLink, 1, row); row++; } if (this.allowCookieLogin) { //CheckBox cookieCheck = new CheckBox(LoginCookieListener.prmUserAllowsLogin); CheckBox cookieCheck = new CheckBox(IWAuthenticator.PARAMETER_ALLOWS_COOKIE_LOGIN); Text cookieText = new Text(this.iwrb.getLocalizedString("cookie.allow", "Remember me")); if(!this.setNoStyles){ cookieText.setFontStyle(this.textStyles); } submitTable.mergeCells(1, row, 2, row); submitTable.add(cookieCheck, 1, row); submitTable.add(cookieText, 1, row); row++; } break; case SINGLE_LINE: col = 3; if (this.register) { submitTable.add(registerLink, col++, 1); } if (this.forgot) { submitTable.add(forgotLink, col++, 1); } if (this.allowCookieLogin) { //CheckBox cookieCheck = new CheckBox(LoginCookieListener.prmUserAllowsLogin); CheckBox cookieCheck = new CheckBox(IWAuthenticator.PARAMETER_ALLOWS_COOKIE_LOGIN); Text cookieText = new Text(this.iwrb.getLocalizedString("cookie.allow", "Remember me")); if(!this.setNoStyles){ cookieText.setFontStyle(this.textStyles); } submitTable.add(cookieCheck, col, 1); submitTable.add(cookieText, col++, 1); } break; } } loginTable.add(submitTable, xpos, ypos); } } loginTable.add(new Parameter(LoginBusinessBean.LoginStateParameter, ACTION_LOG_IN)); getMainForm().add(loginTable); } protected void startStateWML(IWContext iwc) { if (this._logOnPage > 0) { getMainForm().setPageToSubmitTo(this._logOnPage); } Table myTable = new Table(1,5); TextInput login = new TextInput(LOGIN_PARAMETER_NAME); if(!this.setNoStyles){ login.setMarkupAttribute("style", this.styleAttribute); } login.setSize(this.inputLength); PasswordInput passw = new PasswordInput(PASSWORD_PARAMETER_NAME); if(!this.setNoStyles){ passw.setMarkupAttribute("style", this.styleAttribute); } passw.setSize(this.inputLength); Label loginTexti = new Label(this.userText,login); Label passwordTexti = new Label(this.passwordText,passw); SubmitButton button = new SubmitButton("login_button", this.iwrb.getLocalizedString("login_text", "Login")); int row = 1; myTable.add(loginTexti,1,row++); myTable.add(login,1,row++); myTable.add(passwordTexti,1,row++); myTable.add(passw,1,row++); myTable.add(new Parameter(LoginBusinessBean.LoginStateParameter, ACTION_LOG_IN)); myTable.add(button,1,row++); getMainForm().add(myTable); } private Link getRegisterLink() { Link link = new Link(this.iwrb.getLocalizedString("register.register", "Register")); if(!this.setNoStyles){ link.setFontStyle(this.textStyles); } link.setWindowToOpen(RegisterWindow.class); link.setAsImageButton(true); return link; } private Link getForgotLink() { Link L = new Link(this.iwrb.getLocalizedString("register.forgot", "Forgot password?")); if(!this.setNoStyles){ L.setFontStyle(this.textStyles); } L.setWindowToOpen(ForgotWindow.class); return L; } protected void isLoggedOn(IWContext iwc) throws Exception { if (this.loggedOffPageId != -1) { getMainForm().setPageToSubmitTo(this.loggedOffPageId); } User user = getUser(iwc); if (this.sendUserToHomePage && LoginBusinessBean.isLogOnAction(iwc)) { com.idega.user.data.User newUser = Converter.convertToNewUser(user); com.idega.user.data.Group newGroup = newUser.getPrimaryGroup(); if (getParentPage() != null) { if (newUser.getHomePageID() != -1) { iwc.forwardToIBPage(this.getParentPage(), newUser.getHomePage()); } if (newGroup != null && newGroup.getHomePageID() != -1) { iwc.forwardToIBPage(this.getParentPage(), newGroup.getHomePage()); } } } if (LoginBusinessBean.isLogOnAction(iwc)) { if (getParentPage() != null && LoginDBHandler.getNumberOfSuccessfulLogins((((Integer) LoginDBHandler.findUserLogin(user.getID()).getPrimaryKey()).intValue())) == 1 && this.firstLogOnPage != null) { iwc.forwardToIBPage(getParentPage(), this.firstLogOnPage); } } if (getParentPage() != null && this.loggedOnPage != null && LoginBusinessBean.isLogOnAction(iwc)) { iwc.forwardToIBPage(getParentPage(), this.loggedOnPage); } if (getParentPage() != null && getUrlToForwardToOnLogin() != null && LoginBusinessBean.isLogOnAction(iwc)) { iwc.forwardToURL(getParentPage(), getUrlToForwardToOnLogin()); } if (this.loggedOnLink != null) { if (this.userTextSize > -1) { this.loggedOnLink.setFontSize(this.userTextSize); } if (this.userTextColor != null && !this.userTextColor.equals("")) { this.loggedOnLink.setFontColor(this.userTextColor); } this.loggedOnLink.setText(user.getName()); if(!this.setNoStyles){ this.loggedOnLink.setFontStyle(this.textStyles); } } Text userText = new Text(user.getName()); if (this.userTextSize > -1) { userText.setFontSize(this.userTextSize); } if (this.userTextColor != null && !(this.userTextColor.equals(""))) { userText.setFontColor(this.userTextColor); } if(!this.setNoStyles){ userText.setFontStyle(this.textStyles); } Table loginTable = new Table(); loginTable.setBorder(0); if (this.backgroundImageUrl != null) { loginTable.setBackgroundImage(new Image(this.backgroundImageUrl)); } if (this.loginWidth != null) { loginTable.setWidth(this.loginWidth); } if (this.loginHeight != null) { loginTable.setHeight(this.loginHeight); } loginTable.setCellpadding(0); loginTable.setCellspacing(0); if (!(this.color.equals(""))) { loginTable.setColor(this.color); } if (this.LAYOUT != Login.SINGLE_LINE) { loginTable.setHeight(1, "50%"); loginTable.setHeight(2, "50%"); loginTable.setVerticalAlignment(1, 1, "bottom"); loginTable.setVerticalAlignment(1, 2, "top"); } else { loginTable.setWidth(1, 1, "100%"); loginTable.setCellpadding(3); loginTable.setAlignment(1, 1, "right"); } Table inputTable = new Table(1, 1); if (!(this.color.equals(""))) { inputTable.setColor(this.color); } inputTable.setBorder(0); inputTable.setCellpadding(0); inputTable.setCellspacing(0); if (this.LAYOUT != SINGLE_LINE) { inputTable.setAlignment(1, 1, "center"); inputTable.setVerticalAlignment(1, 1, "middle"); inputTable.setWidth("100%"); } if (this.loggedOnLink != null) { inputTable.add(this.loggedOnLink); } else { inputTable.add(userText); } Table submitTable = new Table(); submitTable.setBorder(0); if (!(this.color.equals(""))) { submitTable.setColor(this.color); } if (this.LAYOUT != SINGLE_LINE) { submitTable.setAlignment(1, 1, "center"); submitTable.setVerticalAlignment(1, 1, "middle"); } if (this.onlyLogoutButton) { submitTable.setWidth(this.loginWidth); submitTable.setHeight(this.loginHeight); submitTable.setAlignment(1, 1, this.loginAlignment); } else { submitTable.setWidth("100%"); } if (this._buttonAsLink) { submitTable.setCellpadding(0); submitTable.setCellspacing(0); loginTable.setCellpadding(0); int column = 1; Link link = this.getStyleLink(this.iwrb.getLocalizedString("logout_text", "Log out"), this._linkStyleClass); link.setToFormSubmit(getMainForm()); if (this._iconImage != null) { submitTable.add(this._iconImage, column++, 1); submitTable.setWidth(column++, 1, String.valueOf(this._spaceBetween)); } submitTable.add(link, column, 1); } else { SubmitButton button; if(this.useImageButton && this.logoutImage != null){ button = new SubmitButton(this.logoutImage, "logout_button"); } else { button = new SubmitButton("logout_button", this.iwrb.getLocalizedString("logout_text", "Log out")); } if (this.useImageButton && this.logoutImage == null) { submitTable.add(new StyledButton(button)); } else { submitTable.add(button); } } submitTable.add(new Parameter(LoginBusinessBean.LoginStateParameter, ACTION_LOG_OFF)); //TODO: TL Look into this. Is this Necessary? if (this.loggedOffPageId > 0) { submitTable.add(new Parameter(IB_PAGE_PARAMETER, String.valueOf(this.loggedOffPageId))); } if (this.LAYOUT != SINGLE_LINE) { loginTable.add(inputTable, 1, 1); loginTable.add(submitTable, 1, 2); } else { loginTable.add(inputTable, 1, 1); loginTable.add(submitTable, 2, 1); } if (this.onlyLogoutButton) { getMainForm().add(submitTable); } else { getMainForm().add(loginTable); } if (LoginBusinessBean.isLogOnAction(iwc)) { LoginInfo loginInfo = LoginDBHandler.getLoginInfo((LoginDBHandler.findUserLogin(user.getID()))); Script s = new Script(); boolean addScript = false; if (loginInfo.getAllowedToChange() && loginInfo.getChangeNextTime()) { LoginEditorWindow window = new LoginEditorWindow(); window.setMessage(this.iwrb.getLocalizedString("change_password", "You need to change your password")); window.setToChangeNextTime(); s.addMethod("wop", window.getCallingScriptString(iwc)); addScript = true; } if (this.classToOpenOnLogin != null) { Class classToOpen = RefactorClassRegistry.forName(this.classToOpenOnLogin); PresentationObject pObj = (PresentationObject) classToOpen.newInstance(); if (iwc.hasViewPermission(pObj) && pObj instanceof Window) { s.addMethod("openUserApplication", Window.getCallingScriptString(classToOpen, iwc)); addScript = true; } } if (addScript) { getMainForm().add(s); } } } protected void loginFailed(IWContext iwc, String message) { if (this.LAYOUT == Login.LAYOUT_FORWARD_LINK) { startState(iwc); } else { Text mistokst = new Text(message); if (this.userTextSize != -1) { mistokst.setFontSize(this.userTextSize); } if (this.userTextColor != null) { mistokst.setFontColor(this.userTextColor); } if(!this.setNoStyles){ mistokst.setFontStyle(this.textStyles); } Table loginTable = new Table(); loginTable.setBorder(0); if (this.backgroundImageUrl != null) { loginTable.setBackgroundImage(new Image(this.backgroundImageUrl)); } if (this.loginWidth != null) { loginTable.setWidth(this.loginWidth); } if (this.loginHeight != null) { loginTable.setHeight(this.loginHeight); } loginTable.setCellpadding(0); loginTable.setCellspacing(0); if (!(this.color.equals(""))) { loginTable.setColor(this.color); } if (this.LAYOUT != Login.SINGLE_LINE) { loginTable.setHeight(1, "50%"); loginTable.setHeight(2, "50%"); loginTable.setVerticalAlignment(1, 1, "bottom"); loginTable.setVerticalAlignment(1, 2, "top"); } else { //loginTable.setWidth(1, 1, "100%"); loginTable.setCellpadding(3); loginTable.setAlignment(1, 1, "right"); } Table inputTable = new Table(1, 1); inputTable.setBorder(0); if (!(this.color.equals(""))) { inputTable.setColor(this.color); } inputTable.setCellpadding(0); inputTable.setCellspacing(0); if (this.LAYOUT != SINGLE_LINE) { inputTable.setAlignment(1, 1, "center"); inputTable.setVerticalAlignment(1, 1, "middle"); inputTable.setWidth("100%"); } inputTable.add(mistokst, 1, 1); Table submitTable = new Table(); submitTable.setBorder(0); if (!(this.color.equals(""))) { submitTable.setColor(this.color); } if (this.LAYOUT != SINGLE_LINE) { submitTable.setAlignment(1, 1, "center"); submitTable.setVerticalAlignment(1, 1, "middle"); submitTable.setWidth("100%"); } if (this._buttonAsLink) { submitTable.setCellpadding(0); submitTable.setCellspacing(0); loginTable.setCellpadding(0); int column = 1; Link link = this.getStyleLink(this.iwrb.getLocalizedString("tryagain_text", "Try again"), this._linkStyleClass); link.setToFormSubmit(getMainForm()); if (this._iconImage != null) { submitTable.add(this._iconImage, column++, 1); submitTable.setWidth(column++, 1, String.valueOf(this._spaceBetween)); } submitTable.add(link, column, 1); } else{ SubmitButton button; if(this.useImageButton && this.tryAgainImage != null){ button = new SubmitButton(this.tryAgainImage,ACTION_TRY_AGAIN); } else{ button = new SubmitButton(ACTION_TRY_AGAIN, this.iwrb.getLocalizedString("tryagain_text", "Try again")); } if (this.useImageButton && this.tryAgainImage == null) { submitTable.add(new StyledButton(button)); } else { submitTable.add(button); } } submitTable.add(new Parameter(LoginBusinessBean.LoginStateParameter, ACTION_TRY_AGAIN)); if (this.LAYOUT != SINGLE_LINE) { loginTable.add(inputTable, 1, 1); loginTable.add(submitTable, 1, 2); } else { int column = 1; loginTable.add(inputTable, column++, 1); if (this._buttonAsLink) { loginTable.setWidth(column++, 1, String.valueOf(this._spaceBetween * 2)); } loginTable.add(submitTable, column, 1); } getMainForm().add(loginTable); } } public LoginState internalGetState(IWContext iwc) { return LoginBusinessBean.internalGetState(iwc); } public String getBundleIdentifier() { return IW_BUNDLE_IDENTIFIER; } public void setLayout(int layout) { this.LAYOUT = layout; } protected void setDefaultValues() { this.submitButtonAlignment = "center"; this.LAYOUT = LAYOUT_VERTICAL; //setMainForm(new Form()); //myForm.setEventListener(loginHandlerClass); //getMainForm().setMethod("post"); //myForm.maintainAllParameters(); } public void addHelpButton() { this.helpButton = true; } public void setHelpButton(boolean usehelp) { this.helpButton = usehelp; } public void setVertical() { this.LAYOUT = LAYOUT_VERTICAL; } public void setHorizontal() { this.LAYOUT = LAYOUT_HORIZONTAL; } public void setStacked() { this.LAYOUT = Login.LAYOUT_STACKED; } public void setStyle(String styleAttribute) { setInputStyle(styleAttribute); } public void setInputStyle(String styleAttribute) { this.styleAttribute = styleAttribute; this.setNoStyles=false; } public void setTextStyle(String styleAttribute) { this.textStyles = styleAttribute; this.setNoStyles=false; } public void setInputLength(int inputLength) { this.inputLength = inputLength; } public void setUserText(String text) { this.userText = text; } public void setUserTextSize(int size) { this.userTextSize = size; } public void setUserTextColor(String color) { this.userTextColor = color; } public void setPasswordText(String text) { this.passwordText = text; } public void setPasswordTextSize(int size) { this.passwordTextSize = size; } public void setPasswordTextColor(String color) { this.passwordTextColor = color; } public void setColor(String color) { this.color = color; } public void setHeight(String height) { this.loginHeight = height; } public void setWidth(String width) { this.loginWidth = width; } public void setBackgroundImageUrl(String url) { this.backgroundImageUrl = url; } public void setSubmitButtonAlignment(String alignment) { this.submitButtonAlignment = alignment; } public void setLoginButtonImageURL(String loginImageURL) { setLoginButton(new Image(loginImageURL)); } public void setLoginButton(Image loginImage) { this.loginImage = loginImage; setUseImageButton(); } public void setLogoutButtonImageURL(String logoutImageURL) { setLogoutButton(new Image(logoutImageURL)); } public void setLogoutButton(Image logoutImage) { this.logoutImage = logoutImage; setUseImageButton(); } public void setTryAgainButton(Image tryAgainImage) { this.tryAgainImage = tryAgainImage; setUseImageButton(); } public void setViewOnlyLogoutButton(boolean logout) { this.onlyLogoutButton = logout; } public void setLoginAlignment(String alignment) { this.loginAlignment = alignment; } public void setLoggedOnLink(Link link) { this.loggedOnLink = (Link) link.clone(); } public void setRegisterLink(boolean value) { this.register = value; } public void setShowHint(boolean value) { System.out.println("ShowHint set to " + value); this.showHint = value; } public void setLogOnPage(ICPage page) { this._logOnPage = page.getID(); } public void setLogOnPage(int page) { this._logOnPage = page; } public void setLoggedOnWindow(boolean window) { if (window) { this.loggedOnLink = new Link(); this.loggedOnLink.setWindowToOpen(LoginEditorWindow.class); } } public void setLoggedOnPage(ICPage page) { this.loggedOnLink = new Link(); this.loggedOnLink.setPage(page); } public void setFirstLogOnPage(ICPage page) { this.firstLogOnPage = page; } public void setLoggedOffPage(int ibPageId) { this.loggedOffPageId = ibPageId; } public void setLoggedOffPage(ICPage page) { this.loggedOffPageId = page.getID(); } public void setRegister(boolean register) { this.register = register; } public void setForgot(boolean forgot) { this.forgot = forgot; } public void setAllowCookieLogin(boolean cookies) { this.allowCookieLogin = cookies; } /** todo: implement */ /* * public void setRedirectPage(int page) { System.err.println("setting * redirect page"); _redirectPage = page; } */ public Object clone() { Login obj = null; try { obj = (Login) super.clone(); if (this.myForm != null) { obj.setMainForm((Form) this.myForm.clone()); } if (this.loginImage != null) { obj.loginImage = (Image) this.loginImage.clone(); } if (this.logoutImage != null) { obj.logoutImage = (Image) this.logoutImage.clone(); } if (this.tryAgainImage != null) { obj.tryAgainImage = (Image) this.tryAgainImage.clone(); } if (this.loggedOnLink != null) { obj.loggedOnLink = (Link) this.loggedOnLink.clone(); } } catch (Exception ex) { ex.printStackTrace(System.err); } return obj; } /** * Set the form to automatically send over to a corresponding HTTPS address */ public void setToSendToHTTPS() { setToSendToHTTPS(true); } /** * Set if the form should automatically send over to a corresponding HTTPS * address */ public void setToSendToHTTPS(boolean doSendToHTTPS) { if (getMainForm() != null) { getMainForm().setToSendToHTTPS(doSendToHTTPS); } this.sendToHTTPS = doSendToHTTPS; } /** * Set if the form should send the user to his home page after login. */ public void setToSendUserToHomePage(boolean doSendToHomePage) { this.sendUserToHomePage = doSendToHomePage; } /** * @see com.idega.presentation.Block#getStyleNames() */ public Map getStyleNames() { Map styleMap = new HashMap(); styleMap.put(this._linkStyleClass, ""); styleMap.put(this._linkStyleClass + ":hover", ""); return styleMap; } /** * Sets the submit button as link. * * @param buttonAsLink * The buttonAsLink to set */ public void setButtonAsLink(boolean buttonAsLink) { this._buttonAsLink = buttonAsLink; } /** * Sets the spaceBetween. * * @param spaceBetween * The spaceBetween to set */ public void setSpaceBetween(int spaceBetween) { this._spaceBetween = spaceBetween; } /** * Sets the iconImage. * * @param iconImage * The iconImage to set */ public void setIconImage(Image iconImage) { this._iconImage = iconImage; } /** * @return */ public int getPopupPageID() { return this._loginPageID; } /** * @param pageID * @deprecated replaced with setLogInPageID(int pageID) */ public void setPopupPageID(int pageID) { setLogInPageID(pageID); } /** * @param pageID * */ public void setLogInPageID(int pageID) { this._loginPageID = pageID; } /* * public void setPageForInvalidLogin(IBPage page) { _pageForInvalidLogin = * page; } */ private UserBusiness getUserBusiness(IWContext iwc) throws RemoteException { return (UserBusiness) IBOLookup.getServiceInstance(iwc.getApplicationContext(), UserBusiness.class); } public void empty() { super.empty(); this.myForm = null; } protected void setMainForm(Form myForm) { this.myForm = myForm; } protected Form getMainForm() { if (this.myForm == null) { this.myForm = new Form(); this.myForm.setID("loginForm"); } return this.myForm; } /** * @return Returns the inputLength. */ protected int getInputLength() { return this.inputLength; } /** * @return Returns the _enterSubmit. */ protected boolean isEnterSubmit() { return this._enterSubmit; } /** * @return Returns the iwrb. */ protected IWResourceBundle getResourceBundle() { return this.iwrb; } /** * @param classToOpen The class to open on login. The class must be an instance of Window. */ public void setClassToOpenOnLogin(String classToOpen) { this.classToOpenOnLogin = classToOpen; } public void setToForwardOnLogin(ICPage page) { this.loggedOnPage = page; } /** * @param showOnlyInputs The showOnlyInputs to set. */ public void setShowOnlyInputs(boolean showOnlyInputs) { this.showOnlyInputs = showOnlyInputs; } /** * @param imageAsForwardLink The _loginImageAsForwardLink to set. */ public void setLoginImageAsForwardLink(boolean imageAsForwardLink) { this._loginImageAsForwardLink = imageAsForwardLink; } public void setUrlToForwardToOnLogin(String url){ this.urlToForwardToOnLogin=url; } public String getUrlToForwardToOnLogin(){ return this.urlToForwardToOnLogin; } /** * Sets to use a "image" style button, either a set image or a generated button image. */ public void setUseImageButton(){ this.useImageButton=true; } /** * Sets to use a "regular" style submitbutton. * This can not be set at the same time as an Image button. */ public void setUseRegularButton(){ this.useImageButton=false; } /** * This must be called explicitly to make the login module by default set no styles on its inner objects. * This is done to maintain backwards compatability; */ public void setNoStyles(){ this.setNoStyles=true; } protected ICPage getFirstLogOnPage() { return this.firstLogOnPage; } } \ No newline at end of file
true
false
null
null
diff --git a/frontend/client/src/autotest/common/ui/TabView.java b/frontend/client/src/autotest/common/ui/TabView.java index 745b5f77..4e793d47 100644 --- a/frontend/client/src/autotest/common/ui/TabView.java +++ b/frontend/client/src/autotest/common/ui/TabView.java @@ -1,107 +1,109 @@ package autotest.common.ui; import autotest.common.CustomHistory; import autotest.common.CustomHistory.HistoryToken; import com.google.gwt.http.client.URL; import com.google.gwt.user.client.Event; import com.google.gwt.user.client.History; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.Composite; import java.util.Map; /** * A widget to facilitate building a tab panel from elements present in the * static HTML document. Each <code>TabView</code> grabs a certain HTML * element, removes it from the document, and wraps it. It can then be added * to a TabPanel. The <code>getTitle()</code> method retrieves a title for the * tab from the "title" attribute of the HTML element. This class also supports * lazy initialization of the tab by waiting until the tab is first displayed. */ public abstract class TabView extends Composite { protected boolean initialized = false; protected String title; protected boolean visible; private Map<String, String> savedState; public TabView() { ElementWidget thisTab = new ElementWidget(getElementId()); initWidget(thisTab); title = thisTab.getElement().getAttribute("title"); } public void ensureInitialized() { if (!initialized) { initialize(); initialized = true; } } // primarily for subclasses to override public void refresh() {} public void display() { ensureInitialized(); refresh(); visible = true; } public void hide() { visible = false; } protected boolean isTabVisible() { return visible; } @Override public String getTitle() { return title; } public void updateHistory() { CustomHistory.newItem(getHistoryArguments()); } /** * Subclasses should override this to store any additional history information. */ public HistoryToken getHistoryArguments() { HistoryToken arguments = new HistoryToken(); arguments.put("tab_id", getElementId()); return arguments; } /** * Subclasses should override this to actually handle the tokens. * Should *not* trigger a refresh. refresh() will be called separately. */ public void handleHistoryArguments(Map<String, String> arguments) {} public abstract void initialize(); public abstract String getElementId(); protected void saveHistoryState() { savedState = getHistoryArguments(); } protected void restoreHistoryState() { handleHistoryArguments(savedState); } protected void openHistoryToken(HistoryToken historyToken) { if (isOpenInNewWindowEvent()) { String newUrl = Window.Location.getPath() + "#" + historyToken; Window.open(URL.encode(newUrl), "_blank", ""); } else { History.newItem(historyToken.toString()); } } private static boolean isOpenInNewWindowEvent() { Event event = Event.getCurrentEvent(); boolean middleMouseButton = (event.getButton() & Event.BUTTON_MIDDLE) != 0; - return event.getCtrlKey() || middleMouseButton; + // allow control-click on windows or command-click on macs (control-click is overridden + // on macs to take the place of right-click) + return event.getCtrlKey() || event.getMetaKey() || middleMouseButton; } } diff --git a/frontend/client/src/autotest/tko/CommonPanel.java b/frontend/client/src/autotest/tko/CommonPanel.java index b901d2c9..2a15493a 100644 --- a/frontend/client/src/autotest/tko/CommonPanel.java +++ b/frontend/client/src/autotest/tko/CommonPanel.java @@ -1,370 +1,364 @@ package autotest.tko; import autotest.common.Utils; import autotest.common.ui.ElementWidget; import autotest.common.ui.SimpleHyperlink; import autotest.tko.TkoUtils.FieldInfo; import autotest.tko.WidgetList.ListWidgetFactory; import com.google.gwt.json.client.JSONObject; import com.google.gwt.json.client.JSONString; import com.google.gwt.user.client.ui.CheckBox; import com.google.gwt.user.client.ui.ClickListener; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.FlexTable; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.ListBox; import com.google.gwt.user.client.ui.Panel; import com.google.gwt.user.client.ui.PopupPanel; import com.google.gwt.user.client.ui.RootPanel; import com.google.gwt.user.client.ui.TextArea; import com.google.gwt.user.client.ui.TextBox; import com.google.gwt.user.client.ui.VerticalPanel; import com.google.gwt.user.client.ui.Widget; import com.google.gwt.user.client.ui.PopupPanel.PositionCallback; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; class CommonPanel extends Composite implements ClickListener, PositionCallback { private static final String WIKI_URL = "http://autotest.kernel.org/wiki/TkoHowTo"; private static final String SHOW_QUICK_REFERENCE = "Show quick reference"; private static final String HIDE_QUICK_REFERENCE = "Hide quick reference"; private static final String SHOW_CONTROLS = "Show controls"; private static final String HIDE_CONTROLS = "Hide controls"; private static final String INCLUDE_ATTRIBUTES_TABLE = "test_attributes_include"; private static final String EXCLUDE_ATTRIBUTES_TABLE = "test_attributes_exclude"; private static CommonPanel theInstance = new CommonPanel(); private static class AttributeFilterData { private boolean isInclude; private String attributeWhere, valueWhere; public AttributeFilterData(boolean isInclude, String attributeWhere, String valueWhere) { this.isInclude = isInclude; this.attributeWhere = attributeWhere; this.valueWhere = valueWhere; } public boolean isInclude() { return isInclude; } private String getFilterString() { - String tableName; - if (isInclude) { - tableName = INCLUDE_ATTRIBUTES_TABLE; - } else { - tableName = EXCLUDE_ATTRIBUTES_TABLE; - } - + String tableName = isInclude ? INCLUDE_ATTRIBUTES_TABLE : EXCLUDE_ATTRIBUTES_TABLE; return "(" + tableName + ".attribute " + attributeWhere + " AND " + tableName + ".value " + valueWhere + ")"; } public void addToHistory(Map<String, String> args, String prefix) { args.put(prefix + "_include", Boolean.toString(isInclude())); args.put(prefix + "_attribute", attributeWhere); args.put(prefix + "_value", valueWhere); } public static AttributeFilterData fromHistory(Map<String, String> args, String prefix) { String includeKey = prefix + "_include"; if (!args.containsKey(includeKey)) { return null; } boolean include = Boolean.valueOf(args.get(includeKey)); String attributeWhere = args.get(prefix + "_attribute"); String valueWhere = args.get(prefix + "_value"); return new AttributeFilterData(include, attributeWhere, valueWhere); } } private class AttributeFilter extends Composite implements ClickListener { private ListBox includeOrExclude = new ListBox(); private TextBox attributeWhere = new TextBox(), valueWhere = new TextBox(); public AttributeFilter() { includeOrExclude.addItem("Include"); includeOrExclude.addItem("Exclude"); Panel panel = new HorizontalPanel(); panel.add(includeOrExclude); panel.add(new Label("tests with attribute")); panel.add(attributeWhere); panel.add(new Label("and value")); panel.add(valueWhere); SimpleHyperlink deleteLink = new SimpleHyperlink("[X]"); deleteLink.addClickListener(this); panel.add(deleteLink); initWidget(panel); } public void onClick(Widget sender) { attributeFilterList.deleteWidget(this); } public AttributeFilterData getFilterData() { boolean isInclude = (includeOrExclude.getSelectedIndex() == 0); return new AttributeFilterData(isInclude, attributeWhere.getText(), valueWhere.getText()); } } private class AttributeFilterFactory implements ListWidgetFactory<AttributeFilter> { public AttributeFilter getNewWidget() { return new AttributeFilter(); } } private TextArea customSqlBox = new TextArea(); private CheckBox showInvalid = new CheckBox("Show invalidated tests"); private SimpleHyperlink quickReferenceLink = new SimpleHyperlink(SHOW_QUICK_REFERENCE); private PopupPanel quickReferencePopup; private SimpleHyperlink showHideControlsLink = new SimpleHyperlink(HIDE_CONTROLS); private Panel allControlsPanel = RootPanel.get("common_all_controls"); private Set<CommonPanelListener> listeners = new HashSet<CommonPanelListener>(); private WidgetList<AttributeFilter> attributeFilterList; private String savedSqlCondition; private boolean savedShowInvalid = false; private List<AttributeFilterData> savedAttributeFilters = new ArrayList<AttributeFilterData>(); public static interface CommonPanelListener { public void onSetControlsVisible(boolean visible); } private CommonPanel() { ElementWidget panelElement = new ElementWidget("common_panel"); initWidget(panelElement); } public void initialize() { customSqlBox.setSize("50em", "5em"); quickReferenceLink.addClickListener(this); showHideControlsLink.addClickListener(this); attributeFilterList = new WidgetList<AttributeFilter>(new AttributeFilterFactory(), "Add attribute filter"); Panel titlePanel = new HorizontalPanel(); titlePanel.add(getFieldLabel("Test attributes:")); titlePanel.add(new HTML("&nbsp;<a href=\"" + WIKI_URL + "#attribute_filtering\" " + "target=\"_blank\">[?]</a>")); Panel attributeFilters = new VerticalPanel(); attributeFilters.setStyleName("box"); attributeFilters.add(titlePanel); attributeFilters.add(attributeFilterList); Panel commonFilterPanel = new VerticalPanel(); commonFilterPanel.add(customSqlBox); commonFilterPanel.add(attributeFilters); commonFilterPanel.add(showInvalid); RootPanel.get("common_filters").add(commonFilterPanel); RootPanel.get("common_quick_reference").add(quickReferenceLink); RootPanel.get("common_show_hide_controls").add(showHideControlsLink); generateQuickReferencePopup(); } private Widget getFieldLabel(String string) { Label label = new Label(string); label.setStyleName("field-name"); return label; } public static CommonPanel getPanel() { return theInstance; } /** * For testability. */ public static void setInstance(CommonPanel panel) { theInstance = panel; } public void setConditionVisible(boolean visible) { RootPanel.get("common_condition_div").setVisible(visible); } public void setSqlCondition(String text) { customSqlBox.setText(text); updateStateFromView(); } public void updateStateFromView() { savedSqlCondition = customSqlBox.getText().trim(); savedShowInvalid = showInvalid.isChecked(); savedAttributeFilters.clear(); for (AttributeFilter filter : attributeFilterList.getWidgets()) { savedAttributeFilters.add(filter.getFilterData()); } } public AttributeFilter getFilterWidgetFromData(AttributeFilterData filterData) { AttributeFilter filter = new AttributeFilter(); filter.includeOrExclude.setSelectedIndex(filterData.isInclude() ? 0 : 1); filter.attributeWhere.setText(filterData.attributeWhere); filter.valueWhere.setText(filterData.valueWhere); return filter; } public void updateViewFromState() { customSqlBox.setText(savedSqlCondition); showInvalid.setChecked(savedShowInvalid); attributeFilterList.clear(); for (AttributeFilterData filterData : savedAttributeFilters) { attributeFilterList.addWidget(getFilterWidgetFromData(filterData)); } } private void addAttributeFilters(JSONObject conditionArgs) { List<String> include = new ArrayList<String>(), exclude = new ArrayList<String>(); for (AttributeFilterData filterData : savedAttributeFilters) { if (filterData.isInclude()) { include.add(filterData.getFilterString()); } else { exclude.add(filterData.getFilterString()); } } String includeSql = Utils.joinStrings(" OR ", include); String excludeSql = Utils.joinStrings(" OR ", exclude); addIfNonempty(conditionArgs, "include_attributes_where", includeSql); addIfNonempty(conditionArgs, "exclude_attributes_where", excludeSql); } public JSONObject getConditionArgs() { JSONObject conditionArgs = new JSONObject(); addIfNonempty(conditionArgs, "extra_where", savedSqlCondition); addAttributeFilters(conditionArgs); if (!savedShowInvalid) { List<String> labelsToExclude = Arrays.asList(new String[] {TestLabelManager.INVALIDATED_LABEL}); conditionArgs.put("exclude_labels", Utils.stringsToJSON(labelsToExclude)); } return conditionArgs; } private void addIfNonempty(JSONObject conditionArgs, String key, String value) { if (value.equals("")) { return; } conditionArgs.put(key, new JSONString(value)); } public void refineCondition(String newCondition) { setSqlCondition(TkoUtils.joinWithParens(" AND ", savedSqlCondition, newCondition)); } public void refineCondition(TestSet tests) { refineCondition(tests.getPartialSqlCondition()); } private String getListKey(String base, int index) { return base + "_" + Integer.toString(index); } public void handleHistoryArguments(Map<String, String> arguments) { setSqlCondition(arguments.get("condition")); savedShowInvalid = Boolean.valueOf(arguments.get("show_invalid")); showInvalid.setChecked(savedShowInvalid); attributeFilterList.clear(); for (int index = 0; ; index++) { AttributeFilterData filterData = AttributeFilterData.fromHistory( arguments, getListKey("attribute", index)); if (filterData == null) { break; } attributeFilterList.addWidget(getFilterWidgetFromData(filterData)); } } public void addHistoryArguments(Map<String, String> arguments) { arguments.put("condition", savedSqlCondition); arguments.put("show_invalid", Boolean.toString(savedShowInvalid)); int index = 0; for (AttributeFilterData filterData : savedAttributeFilters) { filterData.addToHistory(arguments, getListKey("attribute", index)); index++; } } public void fillDefaultHistoryValues(Map<String, String> arguments) { Utils.setDefaultValue(arguments, "condition", ""); Utils.setDefaultValue(arguments, "show_invalid", Boolean.toString(savedShowInvalid)); } public void onClick(Widget sender) { if (sender == quickReferenceLink) { handleQuickReferenceClick(); } else { assert sender == showHideControlsLink; handleShowHideControlsClick(); } } private void handleShowHideControlsClick() { boolean areControlsVisible = showHideControlsLink.getText().equals(SHOW_CONTROLS); allControlsPanel.setVisible(areControlsVisible); showHideControlsLink.setText(areControlsVisible ? HIDE_CONTROLS : SHOW_CONTROLS); for (CommonPanelListener listener : listeners) { listener.onSetControlsVisible(areControlsVisible); } } private void handleQuickReferenceClick() { if (isQuickReferenceShowing()) { quickReferencePopup.hide(); quickReferenceLink.setText(SHOW_QUICK_REFERENCE); } else { quickReferencePopup.setPopupPositionAndShow(this); quickReferenceLink.setText(HIDE_QUICK_REFERENCE); } } private boolean isQuickReferenceShowing() { return quickReferenceLink.getText().equals(HIDE_QUICK_REFERENCE); } private void generateQuickReferencePopup() { FlexTable fieldTable = new FlexTable(); fieldTable.setText(0, 0, "Name"); fieldTable.setText(0, 1, "Field"); fieldTable.getRowFormatter().setStyleName(0, "data-row-header"); int row = 1; for (FieldInfo fieldInfo : TkoUtils.getFieldList("all_fields")) { fieldTable.setText(row, 0, fieldInfo.name); fieldTable.setText(row, 1, fieldInfo.field); row++; } quickReferencePopup = new PopupPanel(false); quickReferencePopup.add(fieldTable); } /** * PopupListener callback. */ public void setPosition(int offsetWidth, int offsetHeight) { quickReferencePopup.setPopupPosition( customSqlBox.getAbsoluteLeft() + customSqlBox.getOffsetWidth(), customSqlBox.getAbsoluteTop()); } public void addListener(CommonPanelListener listener) { listeners.add(listener); } }
false
false
null
null
diff --git a/apps/i2psnark/java/src/org/klomp/snark/web/I2PSnarkServlet.java b/apps/i2psnark/java/src/org/klomp/snark/web/I2PSnarkServlet.java index 53ff2ff27..d5464459d 100644 --- a/apps/i2psnark/java/src/org/klomp/snark/web/I2PSnarkServlet.java +++ b/apps/i2psnark/java/src/org/klomp/snark/web/I2PSnarkServlet.java @@ -1,2546 +1,2547 @@ package org.klomp.snark.web; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URISyntaxException; import java.text.Collator; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.Enumeration; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.i2p.I2PAppContext; import net.i2p.data.Base64; import net.i2p.data.DataHelper; import net.i2p.util.I2PAppThread; import net.i2p.util.Log; import org.klomp.snark.I2PSnarkUtil; import org.klomp.snark.MagnetURI; import org.klomp.snark.MetaInfo; import org.klomp.snark.Peer; import org.klomp.snark.Snark; import org.klomp.snark.SnarkManager; import org.klomp.snark.Storage; import org.klomp.snark.Tracker; import org.klomp.snark.TrackerClient; import org.klomp.snark.dht.DHT; /** * Refactored to eliminate Jetty dependencies. */ public class I2PSnarkServlet extends BasicServlet { /** generally "/i2psnark" */ private String _contextPath; /** generally "i2psnark" */ private String _contextName; private SnarkManager _manager; private static long _nonce; private String _themePath; private String _imgPath; private String _lastAnnounceURL; private static final String DEFAULT_NAME = "i2psnark"; public static final String PROP_CONFIG_FILE = "i2psnark.configFile"; private static final int PAGE_SIZE = 50; public I2PSnarkServlet() { super(); } @Override public void init(ServletConfig cfg) throws ServletException { super.init(cfg); String cpath = getServletContext().getContextPath(); _contextPath = cpath == "" ? "/" : cpath; _contextName = cpath == "" ? DEFAULT_NAME : cpath.substring(1).replace("/", "_"); _nonce = _context.random().nextLong(); // limited protection against overwriting other config files or directories // in case you named your war "router.war" String configName = _contextName; if (!configName.equals(DEFAULT_NAME)) configName = DEFAULT_NAME + '_' + _contextName; _manager = new SnarkManager(_context, _contextPath, configName); String configFile = _context.getProperty(PROP_CONFIG_FILE); if ( (configFile == null) || (configFile.trim().length() <= 0) ) configFile = configName + ".config"; _manager.loadConfig(configFile); _manager.start(); loadMimeMap("org/klomp/snark/web/mime"); setResourceBase(_manager.getDataDir()); setWarBase("/.icons/"); } @Override public void destroy() { if (_manager != null) _manager.stop(); super.destroy(); } /** * We override this instead of passing a resource base to super(), because * if a resource base is set, super.getResource() always uses that base, * and we can't get any resources (like icons) out of the .war */ @Override public File getResource(String pathInContext) { if (pathInContext == null || pathInContext.equals("/") || pathInContext.equals("/index.jsp") || pathInContext.equals("/index.html") || pathInContext.startsWith("/.icons/")) return super.getResource(pathInContext); // files in the i2psnark/ directory return new File(_resourceBase, pathInContext); } /** * Handle what we can here, calling super.doGet() for the rest. * @since 0.8.3 */ @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGetAndPost(request, response); } /** * Handle what we can here, calling super.doPost() for the rest. * @since Jetty 7 */ @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGetAndPost(request, response); } /** * Handle what we can here, calling super.doGet() or super.doPost() for the rest. * * Some parts modified from: * <pre> // ======================================================================== // $Id: Default.java,v 1.51 2006/10/08 14:13:18 gregwilkins Exp $ // Copyright 199-2004 Mort Bay Consulting Pty. Ltd. // ------------------------------------------------------------------------ // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ======================================================================== * </pre> * */ private void doGetAndPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (_log.shouldLog(Log.DEBUG)) _log.debug("Service " + req.getMethod() + " \"" + req.getContextPath() + "\" \"" + req.getServletPath() + "\" \"" + req.getPathInfo() + '"'); // since we are not overriding handle*(), do this here String method = req.getMethod(); _themePath = "/themes/snark/" + _manager.getTheme() + '/'; _imgPath = _themePath + "images/"; // this is the part after /i2psnark String path = req.getServletPath(); resp.setHeader("X-Frame-Options", "SAMEORIGIN"); String peerParam = req.getParameter("p"); String stParam = req.getParameter("st"); String peerString; if (peerParam == null || (!_manager.util().connected()) || peerParam.replaceAll("[a-zA-Z0-9~=-]", "").length() > 0) { // XSS peerString = ""; } else { peerString = "?p=" + peerParam; } if (stParam != null && !stParam.equals("0")) { if (peerString.length() > 0) peerString += "&amp;st=" + stParam; else peerString = "?st="+ stParam; } // AJAX for mainsection if ("/.ajax/xhr1.html".equals(path)) { resp.setCharacterEncoding("UTF-8"); resp.setContentType("text/html; charset=UTF-8"); PrintWriter out = resp.getWriter(); //if (_log.shouldLog(Log.DEBUG)) // _manager.addMessage((_context.clock().now() / 1000) + " xhr1 p=" + req.getParameter("p")); writeMessages(out, false, peerString); writeTorrents(out, req); return; } boolean isConfigure = "/configure".equals(path); // index.jsp doesn't work, it is grabbed by the war handler before here if (!(path == null || path.equals("/") || path.equals("/index.jsp") || path.equals("/index.html") || path.equals("/_post") || isConfigure)) { if (path.endsWith("/")) { // Listing of a torrent (torrent detail page) // bypass the horrid Resource.getListHTML() String pathInfo = req.getPathInfo(); String pathInContext = addPaths(path, pathInfo); req.setCharacterEncoding("UTF-8"); resp.setCharacterEncoding("UTF-8"); resp.setContentType("text/html; charset=UTF-8"); File resource = getResource(pathInContext); if (resource == null) { resp.sendError(404); } else { String base = addPaths(req.getRequestURI(), "/"); String listing = getListHTML(resource, base, true, method.equals("POST") ? req.getParameterMap() : null); if (method.equals("POST")) { // P-R-G sendRedirect(req, resp, ""); } else if (listing != null) { resp.getWriter().write(listing); } else { // shouldn't happen resp.sendError(404); } } } else { // local completed files in torrent directories if (method.equals("GET") || method.equals("HEAD")) super.doGet(req, resp); else if (method.equals("POST")) super.doPost(req, resp); else resp.sendError(405); } return; } // Either the main page or /configure req.setCharacterEncoding("UTF-8"); resp.setCharacterEncoding("UTF-8"); resp.setContentType("text/html; charset=UTF-8"); String nonce = req.getParameter("nonce"); if (nonce != null) { if (nonce.equals(String.valueOf(_nonce))) processRequest(req); else // nonce is constant, shouldn't happen _manager.addMessage("Please retry form submission (bad nonce)"); // P-R-G (or G-R-G to hide the params from the address bar) sendRedirect(req, resp, peerString); return; } PrintWriter out = resp.getWriter(); out.write(DOCTYPE + "<html>\n" + "<head><link rel=\"shortcut icon\" href=\"" + _themePath + "favicon.ico\">\n" + "<title>"); out.write(_("I2PSnark - Anonymous BitTorrent Client")); if ("2".equals(peerParam)) out.write(" | Debug Mode"); out.write("</title>\n"); // we want it to go to the base URI so we don't refresh with some funky action= value int delay = 0; if (!isConfigure) { delay = _manager.getRefreshDelaySeconds(); if (delay > 0) { //out.write("<meta http-equiv=\"refresh\" content=\"" + delay + ";/i2psnark/" + peerString + "\">\n"); out.write("<script src=\"/js/ajax.js\" type=\"text/javascript\"></script>\n" + "<script type=\"text/javascript\">\n" + "var failMessage = \"<div class=\\\"routerdown\\\"><b>" + _("Router is down") + "<\\/b><\\/div>\";\n" + "function requestAjax1() { ajax(\"" + _contextPath + "/.ajax/xhr1.html" + peerString + "\", \"mainsection\", " + (delay*1000) + "); }\n" + "function initAjax() { setTimeout(requestAjax1, " + (delay*1000) +"); }\n" + "</script>\n"); } } out.write(HEADER_A + _themePath + HEADER_B + "</head>\n"); if (isConfigure || delay <= 0) out.write("<body>"); else out.write("<body onload=\"initAjax()\">"); out.write("<center>"); List<Tracker> sortedTrackers = null; if (isConfigure) { out.write("<div class=\"snarknavbar\"><a href=\"" + _contextPath + "/\" title=\""); out.write(_("Torrents")); out.write("\" class=\"snarkRefresh\">"); out.write("<img alt=\"\" border=\"0\" src=\"" + _imgPath + "arrow_refresh.png\">&nbsp;&nbsp;"); if (_contextName.equals(DEFAULT_NAME)) out.write(_("I2PSnark")); else out.write(_contextName); out.write("</a>"); } else { out.write("<div class=\"snarknavbar\"><a href=\"" + _contextPath + '/' + peerString + "\" title=\""); out.write(_("Refresh page")); out.write("\" class=\"snarkRefresh\">"); out.write("<img alt=\"\" border=\"0\" src=\"" + _imgPath + "arrow_refresh.png\">&nbsp;&nbsp;"); if (_contextName.equals(DEFAULT_NAME)) out.write(_("I2PSnark")); else out.write(_contextName); out.write("</a> <a href=\"http://forum.i2p/viewforum.php?f=21\" class=\"snarkRefresh\" target=\"_blank\">"); out.write(_("Forum")); out.write("</a>\n"); sortedTrackers = _manager.getSortedTrackers(); for (Tracker t : sortedTrackers) { if (t.baseURL == null || !t.baseURL.startsWith("http")) continue; out.write(" <a href=\"" + t.baseURL + "\" class=\"snarkRefresh\" target=\"_blank\">" + t.name + "</a>"); } } out.write("</div>\n"); String newURL = req.getParameter("newURL"); if (newURL != null && newURL.trim().length() > 0 && req.getMethod().equals("GET")) _manager.addMessage(_("Click \"Add torrent\" button to fetch torrent")); out.write("<div class=\"page\"><div id=\"mainsection\" class=\"mainsection\">"); writeMessages(out, isConfigure, peerString); if (isConfigure) { // end of mainsection div out.write("<div class=\"logshim\"></div></div>\n"); writeConfigForm(out, req); writeTrackerForm(out, req); } else { writeTorrents(out, req); // end of mainsection div out.write("</div><div id=\"lowersection\">\n"); writeAddForm(out, req); writeSeedForm(out, req, sortedTrackers); writeConfigLink(out); // end of lowersection div out.write("</div>\n"); } out.write(FOOTER); } private void writeMessages(PrintWriter out, boolean isConfigure, String peerString) throws IOException { List<String> msgs = _manager.getMessages(); if (!msgs.isEmpty()) { out.write("<div class=\"snarkMessages\">"); out.write("<a href=\"" + _contextPath + '/'); if (isConfigure) out.write("configure"); if (peerString.length() > 0) out.write(peerString + "&amp;"); else out.write("?"); out.write("action=Clear&amp;nonce=" + _nonce + "\">" + "<img src=\"" + _imgPath + "delete.png\" title=\"" + _("clear messages") + "\" alt=\"" + _("clear messages") + "\"></a>" + "<ul>"); for (int i = msgs.size()-1; i >= 0; i--) { String msg = msgs.get(i); out.write("<li>" + msg + "</li>\n"); } out.write("</ul></div>"); } } private void writeTorrents(PrintWriter out, HttpServletRequest req) throws IOException { /** dl, ul, down rate, up rate, peers, size */ final long stats[] = {0,0,0,0,0,0}; String peerParam = req.getParameter("p"); String stParam = req.getParameter("st"); List<Snark> snarks = getSortedSnarks(req); boolean isForm = _manager.util().connected() || !snarks.isEmpty(); if (isForm) { out.write("<form action=\"_post\" method=\"POST\">\n"); out.write("<input type=\"hidden\" name=\"nonce\" value=\"" + _nonce + "\" >\n"); // don't lose peer setting if (peerParam != null) out.write("<input type=\"hidden\" name=\"p\" value=\"" + peerParam + "\" >\n"); // ...or st setting if (stParam != null) out.write("<input type=\"hidden\" name=\"st\" value=\"" + stParam + "\" >\n"); } out.write(TABLE_HEADER); out.write("<img border=\"0\" src=\"" + _imgPath + "status.png\" title=\""); out.write(_("Status")); out.write("\" alt=\""); out.write(_("Status")); out.write("\"></th>\n<th>"); if (_manager.util().connected() && !snarks.isEmpty()) { out.write(" <a href=\"" + _contextPath + '/'); if (peerParam != null) { if (stParam != null) { out.write("?st="); out.write(stParam); } out.write("\">"); out.write("<img border=\"0\" src=\"" + _imgPath + "hidepeers.png\" title=\""); out.write(_("Hide Peers")); out.write("\" alt=\""); out.write(_("Hide Peers")); out.write("\">"); } else { out.write("?p=1"); if (stParam != null) { out.write("&amp;st="); out.write(stParam); } out.write("\">"); out.write("<img border=\"0\" src=\"" + _imgPath + "showpeers.png\" title=\""); out.write(_("Show Peers")); out.write("\" alt=\""); out.write(_("Show Peers")); out.write("\">"); } out.write("</a><br>\n"); } out.write("</th>\n<th colspan=\"3\" align=\"left\">"); out.write("<img border=\"0\" src=\"" + _imgPath + "torrent.png\" title=\""); out.write(_("Torrent")); out.write("\" alt=\""); out.write(_("Torrent")); out.write("\">"); out.write("</th>\n<th align=\"right\">"); if (_manager.util().connected() && !snarks.isEmpty()) { out.write("<img border=\"0\" src=\"" + _imgPath + "eta.png\" title=\""); out.write(_("Estimated time remaining")); out.write("\" alt=\""); // Translators: Please keep short or translate as " " out.write(_("ETA")); out.write("\">"); } out.write("</th>\n<th align=\"right\">"); out.write("<img border=\"0\" src=\"" + _imgPath + "head_rx.png\" title=\""); out.write(_("Downloaded")); out.write("\" alt=\""); // Translators: Please keep short or translate as " " out.write(_("RX")); out.write("\">"); out.write("</th>\n<th align=\"right\">"); if (_manager.util().connected() && !snarks.isEmpty()) { out.write("<img border=\"0\" src=\"" + _imgPath + "head_tx.png\" title=\""); out.write(_("Uploaded")); out.write("\" alt=\""); // Translators: Please keep short or translate as " " out.write(_("TX")); out.write("\">"); } out.write("</th>\n<th align=\"right\">"); if (_manager.util().connected() && !snarks.isEmpty()) { out.write("<img border=\"0\" src=\"" + _imgPath + "head_rxspeed.png\" title=\""); out.write(_("Down Rate")); out.write("\" alt=\""); // Translators: Please keep short or translate as " " out.write(_("RX Rate")); out.write(" \">"); } out.write("</th>\n<th align=\"right\">"); if (_manager.util().connected() && !snarks.isEmpty()) { out.write("<img border=\"0\" src=\"" + _imgPath + "head_txspeed.png\" title=\""); out.write(_("Up Rate")); out.write("\" alt=\""); // Translators: Please keep short or translate as " " out.write(_("TX Rate")); out.write(" \">"); } out.write("</th>\n<th align=\"center\">"); // Opera and text-mode browsers: no &thinsp; and no input type=image values submitted // Using a unique name fixes Opera, except for the buttons with js confirms, see below String ua = req.getHeader("User-Agent"); boolean isDegraded = ua != null && (ua.startsWith("Lynx") || ua.startsWith("w3m") || ua.startsWith("ELinks") || ua.startsWith("Links") || ua.startsWith("Dillo")); boolean noThinsp = isDegraded || (ua != null && ua.startsWith("Opera")); if (_manager.isStopping()) { out.write("&nbsp;"); } else if (_manager.util().connected()) { if (isDegraded) out.write("<a href=\"" + _contextPath + "/?action=StopAll&amp;nonce=" + _nonce + "\"><img title=\""); else { // http://www.onenaught.com/posts/382/firefox-4-change-input-type-image-only-submits-x-and-y-not-name //out.write("<input type=\"image\" name=\"action\" value=\"StopAll\" title=\""); out.write("<input type=\"image\" name=\"action_StopAll\" value=\"foo\" title=\""); } out.write(_("Stop all torrents and the I2P tunnel")); out.write("\" src=\"" + _imgPath + "stop_all.png\" alt=\""); out.write(_("Stop All")); out.write("\">"); if (isDegraded) out.write("</a>"); } else if ((!_manager.util().isConnecting()) && !snarks.isEmpty()) { if (isDegraded) out.write("<a href=\"/" + _contextPath + "/?action=StartAll&amp;nonce=" + _nonce + "\"><img title=\""); else out.write("<input type=\"image\" name=\"action_StartAll\" value=\"foo\" title=\""); out.write(_("Start all torrents and the I2P tunnel")); out.write("\" src=\"" + _imgPath + "start_all.png\" alt=\""); out.write(_("Start All")); out.write("\">"); if (isDegraded) out.write("</a>"); } else { out.write("&nbsp;"); } out.write("</th></tr></thead>\n"); String uri = _contextPath + '/'; boolean showDebug = "2".equals(peerParam); int start = 0; if (stParam != null) { try { start = Math.max(0, Math.min(snarks.size() - 1, Integer.parseInt(stParam))); } catch (NumberFormatException nfe) {} } for (int i = 0; i < snarks.size(); i++) { Snark snark = (Snark)snarks.get(i); boolean showPeers = showDebug || "1".equals(peerParam) || Base64.encode(snark.getInfoHash()).equals(peerParam); boolean hide = i < start || i >= start + PAGE_SIZE; displaySnark(out, snark, uri, i, stats, showPeers, isDegraded, noThinsp, showDebug, hide); } if (snarks.isEmpty()) { out.write("<tr class=\"snarkTorrentNoneLoaded\">" + "<td class=\"snarkTorrentNoneLoaded\"" + " colspan=\"11\"><i>"); out.write(_("No torrents loaded.")); out.write("</i></td></tr>\n"); } else /** if (snarks.size() > 1) */ { out.write("<tfoot><tr>\n" + " <th align=\"left\" colspan=\"6\">"); if (start > 0) { int prev = Math.max(0, start - PAGE_SIZE); out.write("&nbsp;<a href=\"" + _contextPath + "?st=" + prev); if (peerParam != null) out.write("&p=" + peerParam); out.write("\">" + "<img alt=\"" + _("Prev") + "\" title=\"" + _("Previous page") + "\" border=\"0\" src=\"" + _imgPath + "control_rewind_blue.png\">" + "</a>&nbsp;"); } if (start + PAGE_SIZE < snarks.size()) { int next = start + PAGE_SIZE; out.write("&nbsp;<a href=\"" + _contextPath + "?st=" + next); if (peerParam != null) out.write("&p=" + peerParam); out.write("\">" + "<img alt=\"" + _("Next") + "\" title=\"" + _("Next page") + "\" border=\"0\" src=\"" + _imgPath + "control_fastforward_blue.png\">" + "</a>&nbsp;"); } out.write("&nbsp;"); out.write(_("Totals")); out.write(":&nbsp;"); out.write(ngettext("1 torrent", "{0} torrents", snarks.size())); out.write(", "); out.write(DataHelper.formatSize2(stats[5]) + "B, "); out.write(ngettext("1 connected peer", "{0} connected peers", (int) stats[4])); DHT dht = _manager.util().getDHT(); if (dht != null) { int dhts = dht.size(); if (dhts > 0) { out.write(", "); out.write(ngettext("1 DHT peer", "{0} DHT peers", dhts)); } if (showDebug) out.write(dht.renderStatusHTML()); } out.write("</th>\n"); if (_manager.util().connected()) { out.write(" <th align=\"right\">" + formatSize(stats[0]) + "</th>\n" + " <th align=\"right\">" + formatSize(stats[1]) + "</th>\n" + " <th align=\"right\">" + formatSize(stats[2]) + "ps</th>\n" + " <th align=\"right\">" + formatSize(stats[3]) + "ps</th>\n" + " <th></th>"); } else { out.write("<th colspan=\"5\"></th>"); } out.write("</tr></tfoot>\n"); } out.write("</table>"); if (isForm) out.write("</form>\n"); } /** * Do what they ask, adding messages to _manager.addMessage as necessary */ private void processRequest(HttpServletRequest req) { String action = req.getParameter("action"); if (action == null) { // http://www.onenaught.com/posts/382/firefox-4-change-input-type-image-only-submits-x-and-y-not-name Map params = req.getParameterMap(); for (Object o : params.keySet()) { String key = (String) o; if (key.startsWith("action_") && key.endsWith(".x")) { action = key.substring(0, key.length() - 2).substring(7); break; } } if (action == null) { _manager.addMessage("No action specified"); return; } } // sadly, Opera doesn't send value with input type=image, so we have to use GET there //if (!"POST".equals(req.getMethod())) { // _manager.addMessage("Action must be with POST"); // return; //} if ("Add".equals(action)) { String newURL = req.getParameter("newURL"); /****** // NOTE - newFile currently disabled in HTML form - see below File f = null; if ( (newFile != null) && (newFile.trim().length() > 0) ) f = new File(newFile.trim()); if ( (f != null) && (!f.exists()) ) { _manager.addMessage(_("Torrent file {0} does not exist", newFile)); } if ( (f != null) && (f.exists()) ) { // NOTE - All this is disabled - load from local file disabled File local = new File(_manager.getDataDir(), f.getName()); String canonical = null; try { canonical = local.getCanonicalPath(); if (local.exists()) { if (_manager.getTorrent(canonical) != null) _manager.addMessage(_("Torrent already running: {0}", newFile)); else _manager.addMessage(_("Torrent already in the queue: {0}", newFile)); } else { boolean ok = FileUtil.copy(f.getAbsolutePath(), local.getAbsolutePath(), true); if (ok) { _manager.addMessage(_("Copying torrent to {0}", local.getAbsolutePath())); _manager.addTorrent(canonical); } else { _manager.addMessage(_("Unable to copy the torrent to {0}", local.getAbsolutePath()) + ' ' + _("from {0}", f.getAbsolutePath())); } } } catch (IOException ioe) { _log.warn("hrm: " + local, ioe); } } else *****/ if (newURL != null) { if (newURL.startsWith("http://")) { FetchAndAdd fetch = new FetchAndAdd(_context, _manager, newURL); _manager.addDownloader(fetch); } else if (newURL.startsWith(MagnetURI.MAGNET) || newURL.startsWith(MagnetURI.MAGGOT)) { addMagnet(newURL); } else if (newURL.length() == 40 && newURL.replaceAll("[a-fA-F0-9]", "").length() == 0) { addMagnet(MagnetURI.MAGNET_FULL + newURL); } else { _manager.addMessage(_("Invalid URL: Must start with \"http://\", \"{0}\", or \"{1}\"", MagnetURI.MAGNET, MagnetURI.MAGGOT)); } } else { // no file or URL specified } } else if (action.startsWith("Stop_")) { String torrent = action.substring(5); if (torrent != null) { byte infoHash[] = Base64.decode(torrent); if ( (infoHash != null) && (infoHash.length == 20) ) { // valid sha1 for (Iterator iter = _manager.listTorrentFiles().iterator(); iter.hasNext(); ) { String name = (String)iter.next(); Snark snark = _manager.getTorrent(name); if ( (snark != null) && (DataHelper.eq(infoHash, snark.getInfoHash())) ) { _manager.stopTorrent(snark, false); break; } } } } } else if (action.startsWith("Start_")) { String torrent = action.substring(6); if (torrent != null) { byte infoHash[] = Base64.decode(torrent); if ( (infoHash != null) && (infoHash.length == 20) ) { // valid sha1 _manager.startTorrent(infoHash); } } } else if (action.startsWith("Remove_")) { String torrent = action.substring(7); if (torrent != null) { byte infoHash[] = Base64.decode(torrent); if ( (infoHash != null) && (infoHash.length == 20) ) { // valid sha1 for (Iterator iter = _manager.listTorrentFiles().iterator(); iter.hasNext(); ) { String name = (String)iter.next(); Snark snark = _manager.getTorrent(name); if ( (snark != null) && (DataHelper.eq(infoHash, snark.getInfoHash())) ) { MetaInfo meta = snark.getMetaInfo(); if (meta == null) { // magnet - remove and delete are the same thing // Remove not shown on UI so we shouldn't get here _manager.deleteMagnet(snark); _manager.addMessage(_("Magnet deleted: {0}", name)); return; } _manager.stopTorrent(snark, true); // should we delete the torrent file? // yeah, need to, otherwise it'll get autoadded again (at the moment File f = new File(name); f.delete(); _manager.addMessage(_("Torrent file deleted: {0}", f.getAbsolutePath())); break; } } } } } else if (action.startsWith("Delete_")) { String torrent = action.substring(7); if (torrent != null) { byte infoHash[] = Base64.decode(torrent); if ( (infoHash != null) && (infoHash.length == 20) ) { // valid sha1 for (Iterator iter = _manager.listTorrentFiles().iterator(); iter.hasNext(); ) { String name = (String)iter.next(); Snark snark = _manager.getTorrent(name); if ( (snark != null) && (DataHelper.eq(infoHash, snark.getInfoHash())) ) { MetaInfo meta = snark.getMetaInfo(); if (meta == null) { // magnet - remove and delete are the same thing _manager.deleteMagnet(snark); if (snark instanceof FetchAndAdd) _manager.addMessage(_("Download deleted: {0}", name)); else _manager.addMessage(_("Magnet deleted: {0}", name)); return; } _manager.stopTorrent(snark, true); File f = new File(name); f.delete(); _manager.addMessage(_("Torrent file deleted: {0}", f.getAbsolutePath())); List<List<String>> files = meta.getFiles(); String dataFile = snark.getBaseName(); f = new File(_manager.getDataDir(), dataFile); if (files == null) { // single file torrent if (f.delete()) _manager.addMessage(_("Data file deleted: {0}", f.getAbsolutePath())); else _manager.addMessage(_("Data file could not be deleted: {0}", f.getAbsolutePath())); break; } // step 1 delete files for (int i = 0; i < files.size(); i++) { // multifile torrents have the getFiles() return lists of lists of filenames, but // each of those lists just contain a single file afaict... File df = Storage.getFileFromNames(f, files.get(i)); if (df.delete()) { //_manager.addMessage(_("Data file deleted: {0}", df.getAbsolutePath())); } else { _manager.addMessage(_("Data file could not be deleted: {0}", df.getAbsolutePath())); } } // step 2 make Set of dirs with reverse sort Set<File> dirs = new TreeSet(Collections.reverseOrder()); for (List<String> list : files) { for (int i = 1; i < list.size(); i++) { dirs.add(Storage.getFileFromNames(f, list.subList(0, i))); } } // step 3 delete dirs bottom-up for (File df : dirs) { if (df.delete()) { //_manager.addMessage(_("Data dir deleted: {0}", df.getAbsolutePath())); } else { _manager.addMessage(_("Directory could not be deleted: {0}", df.getAbsolutePath())); if (_log.shouldLog(Log.WARN)) _log.warn("Could not delete dir " + df); } } // step 4 delete base if (f.delete()) { _manager.addMessage(_("Directory deleted: {0}", f.getAbsolutePath())); } else { _manager.addMessage(_("Directory could not be deleted: {0}", f.getAbsolutePath())); if (_log.shouldLog(Log.WARN)) _log.warn("Could not delete dir " + f); } break; } } } } } else if ("Save".equals(action)) { String dataDir = req.getParameter("dataDir"); boolean filesPublic = req.getParameter("filesPublic") != null; boolean autoStart = req.getParameter("autoStart") != null; String seedPct = req.getParameter("seedPct"); String eepHost = req.getParameter("eepHost"); String eepPort = req.getParameter("eepPort"); String i2cpHost = req.getParameter("i2cpHost"); String i2cpPort = req.getParameter("i2cpPort"); String i2cpOpts = buildI2CPOpts(req); String upLimit = req.getParameter("upLimit"); String upBW = req.getParameter("upBW"); String refreshDel = req.getParameter("refreshDelay"); String startupDel = req.getParameter("startupDelay"); boolean useOpenTrackers = req.getParameter("useOpenTrackers") != null; boolean useDHT = req.getParameter("useDHT") != null; //String openTrackers = req.getParameter("openTrackers"); String theme = req.getParameter("theme"); _manager.updateConfig(dataDir, filesPublic, autoStart, refreshDel, startupDel, seedPct, eepHost, eepPort, i2cpHost, i2cpPort, i2cpOpts, upLimit, upBW, useOpenTrackers, useDHT, theme); } else if ("Save2".equals(action)) { String taction = req.getParameter("taction"); if (taction != null) processTrackerForm(taction, req); } else if ("Create".equals(action)) { String baseData = req.getParameter("baseFile"); if (baseData != null && baseData.trim().length() > 0) { File baseFile = new File(_manager.getDataDir(), baseData); String announceURL = req.getParameter("announceURL"); // make the user add a tracker on the config form now //String announceURLOther = req.getParameter("announceURLOther"); //if ( (announceURLOther != null) && (announceURLOther.trim().length() > "http://.i2p/announce".length()) ) // announceURL = announceURLOther; if (baseFile.exists()) { if (announceURL.equals("none")) announceURL = null; _lastAnnounceURL = announceURL; List<String> backupURLs = new ArrayList(); Enumeration e = req.getParameterNames(); while (e.hasMoreElements()) { Object o = e.nextElement(); if (!(o instanceof String)) continue; String k = (String) o; if (k.startsWith("backup_")) { String url = k.substring(7); if (!url.equals(announceURL)) backupURLs.add(url); } } List<List<String>> announceList = null; if (!backupURLs.isEmpty()) { // BEP 12 - Put primary first, then the others, each as the sole entry in their own list if (announceURL == null) { _manager.addMessage(_("Error - Cannot include alternate trackers without a primary tracker")); return; } backupURLs.add(0, announceURL); boolean hasPrivate = false; boolean hasPublic = false; for (String url : backupURLs) { if (_manager.getPrivateTrackers().contains(announceURL)) hasPrivate = true; else hasPublic = true; } if (hasPrivate && hasPublic) { _manager.addMessage(_("Error - Cannot mix private and public trackers in a torrent")); return; } announceList = new ArrayList(backupURLs.size()); for (String url : backupURLs) { announceList.add(Collections.singletonList(url)); } } try { // This may take a long time to check the storage, but since it already exists, // it shouldn't be THAT bad, so keep it in this thread. // TODO thread it for big torrents, perhaps a la FetchAndAdd boolean isPrivate = _manager.getPrivateTrackers().contains(announceURL); Storage s = new Storage(_manager.util(), baseFile, announceURL, announceList, isPrivate, null); s.close(); // close the files... maybe need a way to pass this Storage to addTorrent rather than starting over MetaInfo info = s.getMetaInfo(); File torrentFile = new File(_manager.getDataDir(), s.getBaseName() + ".torrent"); // FIXME is the storage going to stay around thanks to the info reference? // now add it, but don't automatically start it _manager.addTorrent(info, s.getBitField(), torrentFile.getAbsolutePath(), true); _manager.addMessage(_("Torrent created for \"{0}\"", baseFile.getName()) + ": " + torrentFile.getAbsolutePath()); if (announceURL != null && !_manager.util().getOpenTrackers().contains(announceURL)) _manager.addMessage(_("Many I2P trackers require you to register new torrents before seeding - please do so before starting \"{0}\"", baseFile.getName())); } catch (IOException ioe) { _manager.addMessage(_("Error creating a torrent for \"{0}\"", baseFile.getAbsolutePath()) + ": " + ioe.getMessage()); } } else { _manager.addMessage(_("Cannot create a torrent for the nonexistent data: {0}", baseFile.getAbsolutePath())); } } else { _manager.addMessage(_("Error creating torrent - you must enter a file or directory")); } } else if ("StopAll".equals(action)) { _manager.stopAllTorrents(false); } else if ("StartAll".equals(action)) { _manager.startAllTorrents(); } else if ("Clear".equals(action)) { _manager.clearMessages(); } else { _manager.addMessage("Unknown POST action: \"" + action + '\"'); } } /** * Redirect a POST to a GET (P-R-G), preserving the peer string * @since 0.9.5 */ private void sendRedirect(HttpServletRequest req, HttpServletResponse resp, String p) throws IOException { String url = req.getRequestURL().toString(); StringBuilder buf = new StringBuilder(128); if (url.endsWith("_post")) url = url.substring(0, url.length() - 5); buf.append(url); if (p.length() > 0) buf.append('?').append(p); resp.setHeader("Location", buf.toString()); resp.sendError(302, "Moved"); } /** @since 0.9 */ private void processTrackerForm(String action, HttpServletRequest req) { if (action.equals(_("Delete selected")) || action.equals(_("Save tracker configuration"))) { boolean changed = false; Map<String, Tracker> trackers = _manager.getTrackerMap(); List<String> removed = new ArrayList(); List<String> open = new ArrayList(); List<String> priv = new ArrayList(); Enumeration e = req.getParameterNames(); while (e.hasMoreElements()) { Object o = e.nextElement(); if (!(o instanceof String)) continue; String k = (String) o; if (k.startsWith("delete_")) { k = k.substring(7); Tracker t; if ((t = trackers.remove(k)) != null) { removed.add(t.announceURL); _manager.addMessage(_("Removed") + ": " + k); changed = true; } } else if (k.startsWith("open_")) { open.add(k.substring(5)); } else if (k.startsWith("private_")) { priv.add(k.substring(8)); } } if (changed) { _manager.saveTrackerMap(); } open.removeAll(removed); List<String> oldOpen = new ArrayList(_manager.util().getOpenTrackers()); Collections.sort(oldOpen); Collections.sort(open); if (!open.equals(oldOpen)) _manager.saveOpenTrackers(open); priv.removeAll(removed); // open trumps private priv.removeAll(open); List<String> oldPriv = new ArrayList(_manager.getPrivateTrackers()); Collections.sort(oldPriv); Collections.sort(priv); if (!priv.equals(oldPriv)) _manager.savePrivateTrackers(priv); } else if (action.equals(_("Add tracker"))) { String name = req.getParameter("tname"); String hurl = req.getParameter("thurl"); String aurl = req.getParameter("taurl"); if (name != null && hurl != null && aurl != null) { name = name.trim(); hurl = hurl.trim(); aurl = aurl.trim().replace("=", "&#61;"); if (name.length() > 0 && hurl.startsWith("http://") && TrackerClient.isValidAnnounce(aurl)) { Map<String, Tracker> trackers = _manager.getTrackerMap(); trackers.put(name, new Tracker(name, aurl, hurl)); _manager.saveTrackerMap(); // open trumps private if (req.getParameter("_add_open_") != null) { List newOpen = new ArrayList(_manager.util().getOpenTrackers()); newOpen.add(aurl); _manager.saveOpenTrackers(newOpen); } else if (req.getParameter("_add_private_") != null) { List newPriv = new ArrayList(_manager.getPrivateTrackers()); newPriv.add(aurl); _manager.savePrivateTrackers(newPriv); } } else { _manager.addMessage(_("Enter valid tracker name and URLs")); } } else { _manager.addMessage(_("Enter valid tracker name and URLs")); } } else if (action.equals(_("Restore defaults"))) { _manager.setDefaultTrackerMap(); _manager.saveOpenTrackers(null); _manager.addMessage(_("Restored default trackers")); } else { _manager.addMessage("Unknown POST action: \"" + action + '\"'); } } private static final String iopts[] = {"inbound.length", "inbound.quantity", "outbound.length", "outbound.quantity" }; /** put the individual i2cp selections into the option string */ private static String buildI2CPOpts(HttpServletRequest req) { StringBuilder buf = new StringBuilder(128); String p = req.getParameter("i2cpOpts"); if (p != null) buf.append(p); for (int i = 0; i < iopts.length; i++) { p = req.getParameter(iopts[i]); if (p != null) buf.append(' ').append(iopts[i]).append('=').append(p); } return buf.toString(); } /** * Sort alphabetically in current locale, ignore case, ignore leading "the " * (I guess this is worth it, a lot of torrents start with "The " * These are full path names which makes it harder * @since 0.7.14 */ private class TorrentNameComparator implements Comparator<String> { private final Comparator collator = Collator.getInstance(); private final String skip; public TorrentNameComparator() { String s; try { s = _manager.getDataDir().getCanonicalPath(); } catch (IOException ioe) { s = _manager.getDataDir().getAbsolutePath(); } skip = s + File.separator; } public int compare(String l, String r) { if (l.startsWith(skip)) l = l.substring(skip.length()); if (r.startsWith(skip)) r = r.substring(skip.length()); String llc = l.toLowerCase(Locale.US); if (llc.startsWith("the ") || llc.startsWith("the.") || llc.startsWith("the_")) l = l.substring(4); String rlc = r.toLowerCase(Locale.US); if (rlc.startsWith("the ") || rlc.startsWith("the.") || rlc.startsWith("the_")) r = r.substring(4); return collator.compare(l, r); } } private List<Snark> getSortedSnarks(HttpServletRequest req) { Set<String> files = _manager.listTorrentFiles(); TreeSet<String> fileNames = new TreeSet(new TorrentNameComparator()); fileNames.addAll(files); ArrayList<Snark> rv = new ArrayList(fileNames.size()); int magnet = 0; for (Iterator iter = fileNames.iterator(); iter.hasNext(); ) { String name = (String)iter.next(); Snark snark = _manager.getTorrent(name); if (snark != null) { // put downloads and magnets first if (snark.getStorage() == null) rv.add(magnet++, snark); else rv.add(snark); } } return rv; } private static final int MAX_DISPLAYED_FILENAME_LENGTH = 50; private static final int MAX_DISPLAYED_ERROR_LENGTH = 43; /** * Display one snark (one line in table, unless showPeers is true) * * @param stats in/out param (totals) * @param statsOnly if true, output nothing, update stats only */ private void displaySnark(PrintWriter out, Snark snark, String uri, int row, long stats[], boolean showPeers, boolean isDegraded, boolean noThinsp, boolean showDebug, boolean statsOnly) throws IOException { // stats long uploaded = snark.getUploaded(); stats[0] += snark.getDownloaded(); stats[1] += uploaded; long downBps = snark.getDownloadRate(); long upBps = snark.getUploadRate(); boolean isRunning = !snark.isStopped(); if (isRunning) { stats[2] += downBps; stats[3] += upBps; } int curPeers = snark.getPeerCount(); stats[4] += curPeers; long total = snark.getTotalLength(); if (total > 0) stats[5] += total; if (statsOnly) return; String filename = snark.getName(); if (snark.getMetaInfo() != null) { // Only do this if not a magnet or torrent download // Strip full path down to the local name File f = new File(filename); filename = f.getName(); } int i = filename.lastIndexOf(".torrent"); if (i > 0) filename = filename.substring(0, i); String fullFilename = filename; if (filename.length() > MAX_DISPLAYED_FILENAME_LENGTH) { String start = filename.substring(0, MAX_DISPLAYED_FILENAME_LENGTH); if (start.indexOf(" ") < 0 && start.indexOf("-") < 0) { // browser has nowhere to break it fullFilename = filename; filename = start + "&hellip;"; } } // includes skipped files, -1 for magnet mode long remaining = snark.getRemainingLength(); if (remaining > total) remaining = total; // does not include skipped files, -1 for magnet mode or when not running. long needed = snark.getNeededLength(); if (needed > total) needed = total; long remainingSeconds; if (downBps > 0 && needed > 0) remainingSeconds = needed / downBps; else remainingSeconds = -1; MetaInfo meta = snark.getMetaInfo(); // isValid means isNotMagnet boolean isValid = meta != null; boolean isMultiFile = isValid && meta.getFiles() != null; String err = snark.getTrackerProblems(); int knownPeers = Math.max(curPeers, snark.getTrackerSeenPeers()); String rowClass = (row % 2 == 0 ? "snarkTorrentEven" : "snarkTorrentOdd"); String statusString; if (snark.isChecking()) { statusString = "<img alt=\"\" border=\"0\" src=\"" + _imgPath + "stalled.png\" title=\"" + _("Checking") + "\"></td>" + "<td class=\"snarkTorrentStatus " + rowClass + "\">" + _("Checking"); } else if (snark.isAllocating()) { statusString = "<img alt=\"\" border=\"0\" src=\"" + _imgPath + "stalled.png\" title=\"" + _("Allocating") + "\"></td>" + "<td class=\"snarkTorrentStatus " + rowClass + "\">" + _("Allocating"); } else if (err != null && curPeers == 0) { // Also don't show if seeding... but then we won't see the not-registered error // && remaining != 0 && needed != 0) { // let's only show this if we have no peers, otherwise PEX and DHT should bail us out, user doesn't care //if (isRunning && curPeers > 0 && !showPeers) // statusString = "<img alt=\"\" border=\"0\" src=\"" + _imgPath + "trackererror.png\" title=\"" + err + "\"></td>" + // "<td class=\"snarkTorrentStatus " + rowClass + "\">" + _("Tracker Error") + // ": <a href=\"" + uri + "?p=" + Base64.encode(snark.getInfoHash()) + "\">" + // curPeers + thinsp(noThinsp) + // ngettext("1 peer", "{0} peers", knownPeers) + "</a>"; //else if (isRunning) if (isRunning) statusString = "<img alt=\"\" border=\"0\" src=\"" + _imgPath + "trackererror.png\" title=\"" + err + "\"></td>" + "<td class=\"snarkTorrentStatus " + rowClass + "\">" + _("Tracker Error") + ": " + curPeers + thinsp(noThinsp) + ngettext("1 peer", "{0} peers", knownPeers); else { if (err.length() > MAX_DISPLAYED_ERROR_LENGTH) err = err.substring(0, MAX_DISPLAYED_ERROR_LENGTH) + "&hellip;"; statusString = "<img alt=\"\" border=\"0\" src=\"" + _imgPath + "trackererror.png\" title=\"" + err + "\"></td>" + "<td class=\"snarkTorrentStatus " + rowClass + "\">" + _("Tracker Error"); } } else if (snark.isStarting()) { statusString = "<img alt=\"\" border=\"0\" src=\"" + _imgPath + "stalled.png\" title=\"" + _("Starting") + "\"></td>" + "<td class=\"snarkTorrentStatus " + rowClass + "\">" + _("Starting"); } else if (remaining == 0 || needed == 0) { // < 0 means no meta size yet // partial complete or seeding if (isRunning) { String img; String txt; if (remaining == 0) { img = "seeding"; txt = _("Seeding"); } else { // partial img = "complete"; txt = _("Complete"); } if (curPeers > 0 && !showPeers) statusString = "<img alt=\"\" border=\"0\" src=\"" + _imgPath + img + ".png\" title=\"" + txt + "\"></td>" + "<td class=\"snarkTorrentStatus " + rowClass + "\">" + txt + ": <a href=\"" + uri + "?p=" + Base64.encode(snark.getInfoHash()) + "\">" + curPeers + thinsp(noThinsp) + ngettext("1 peer", "{0} peers", knownPeers) + "</a>"; else statusString = "<img alt=\"\" border=\"0\" src=\"" + _imgPath + img + ".png\" title=\"" + txt + "\"></td>" + "<td class=\"snarkTorrentStatus " + rowClass + "\">" + txt + ": " + curPeers + thinsp(noThinsp) + ngettext("1 peer", "{0} peers", knownPeers); } else { statusString = "<img alt=\"\" border=\"0\" src=\"" + _imgPath + "complete.png\" title=\"" + _("Complete") + "\"></td>" + "<td class=\"snarkTorrentStatus " + rowClass + "\">" + _("Complete"); } } else { if (isRunning && curPeers > 0 && downBps > 0 && !showPeers) statusString = "<img alt=\"\" border=\"0\" src=\"" + _imgPath + "downloading.png\" title=\"" + _("OK") + "\"></td>" + "<td class=\"snarkTorrentStatus " + rowClass + "\">" + _("OK") + ": <a href=\"" + uri + "?p=" + Base64.encode(snark.getInfoHash()) + "\">" + curPeers + thinsp(noThinsp) + ngettext("1 peer", "{0} peers", knownPeers) + "</a>"; else if (isRunning && curPeers > 0 && downBps > 0) statusString = "<img alt=\"\" border=\"0\" src=\"" + _imgPath + "downloading.png\" title=\"" + _("OK") + "\"></td>" + "<td class=\"snarkTorrentStatus " + rowClass + "\">" + _("OK") + ": " + curPeers + thinsp(noThinsp) + ngettext("1 peer", "{0} peers", knownPeers); else if (isRunning && curPeers > 0 && !showPeers) statusString = "<img alt=\"\" border=\"0\" src=\"" + _imgPath + "stalled.png\" title=\"" + _("Stalled") + "\"></td>" + "<td class=\"snarkTorrentStatus " + rowClass + "\">" + _("Stalled") + ": <a href=\"" + uri + "?p=" + Base64.encode(snark.getInfoHash()) + "\">" + curPeers + thinsp(noThinsp) + ngettext("1 peer", "{0} peers", knownPeers) + "</a>"; else if (isRunning && curPeers > 0) statusString = "<img alt=\"\" border=\"0\" src=\"" + _imgPath + "stalled.png\" title=\"" + _("Stalled") + "\"></td>" + "<td class=\"snarkTorrentStatus " + rowClass + "\">" + _("Stalled") + ": " + curPeers + thinsp(noThinsp) + ngettext("1 peer", "{0} peers", knownPeers); else if (isRunning && knownPeers > 0) statusString = "<img alt=\"\" border=\"0\" src=\"" + _imgPath + "nopeers.png\" title=\"" + _("No Peers") + "\"></td>" + "<td class=\"snarkTorrentStatus " + rowClass + "\">" + _("No Peers") + ": 0" + thinsp(noThinsp) + knownPeers ; else if (isRunning) statusString = "<img alt=\"\" border=\"0\" src=\"" + _imgPath + "nopeers.png\" title=\"" + _("No Peers") + "\"></td>" + "<td class=\"snarkTorrentStatus " + rowClass + "\">" + _("No Peers"); else statusString = "<img alt=\"\" border=\"0\" src=\"" + _imgPath + "stopped.png\" title=\"" + _("Stopped") + "\"></td>" + "<td class=\"snarkTorrentStatus " + rowClass + "\">" + _("Stopped"); } out.write("<tr class=\"" + rowClass + "\">"); out.write("<td class=\"center " + rowClass + "\">"); out.write(statusString + "</td>\n\t"); // (i) icon column out.write("<td class=\"" + rowClass + "\">"); if (isValid && meta.getAnnounce() != null) { // Link to local details page - note that trailing slash on a single-file torrent // gets us to the details page instead of the file. //StringBuilder buf = new StringBuilder(128); //buf.append("<a href=\"").append(snark.getBaseName()) // .append("/\" title=\"").append(_("Torrent details")) // .append("\"><img alt=\"").append(_("Info")).append("\" border=\"0\" src=\"") // .append(_imgPath).append("details.png\"></a>"); //out.write(buf.toString()); // Link to tracker details page String trackerLink = getTrackerLink(meta.getAnnounce(), snark.getInfoHash()); if (trackerLink != null) out.write(trackerLink); } String encodedBaseName = urlEncode(snark.getBaseName()); // File type icon column out.write("</td>\n<td class=\"" + rowClass + "\">"); if (isValid) { // Link to local details page - note that trailing slash on a single-file torrent // gets us to the details page instead of the file. StringBuilder buf = new StringBuilder(128); buf.append("<a href=\"").append(encodedBaseName) .append("/\" title=\"").append(_("Torrent details")) .append("\">"); out.write(buf.toString()); } String icon; if (isMultiFile) icon = "folder"; else if (isValid) icon = toIcon(meta.getName()); else if (snark instanceof FetchAndAdd) icon = "basket_put"; else icon = "magnet"; if (isValid) { out.write(toImg(icon)); out.write("</a>"); } else { out.write(toImg(icon)); } // Torrent name column out.write("</td><td class=\"snarkTorrentName " + rowClass + "\">"); if (remaining == 0 || isMultiFile) { StringBuilder buf = new StringBuilder(128); buf.append("<a href=\"").append(encodedBaseName); if (isMultiFile) buf.append('/'); buf.append("\" title=\""); if (isMultiFile) buf.append(_("View files")); else buf.append(_("Open file")); buf.append("\">"); out.write(buf.toString()); } out.write(filename); if (remaining == 0 || isMultiFile) out.write("</a>"); out.write("<td align=\"right\" class=\"snarkTorrentETA " + rowClass + "\">"); if(isRunning && remainingSeconds > 0 && !snark.isChecking()) out.write(DataHelper.formatDuration2(Math.max(remainingSeconds, 10) * 1000)); // (eta 6h) out.write("</td>\n\t"); out.write("<td align=\"right\" class=\"snarkTorrentDownloaded " + rowClass + "\">"); if (remaining > 0) out.write(formatSize(total-remaining) + thinsp(noThinsp) + formatSize(total)); else if (remaining == 0) out.write(formatSize(total)); // 3GB //else // out.write("??"); // no meta size yet out.write("</td>\n\t"); out.write("<td align=\"right\" class=\"snarkTorrentUploaded " + rowClass + "\">"); if(isRunning && isValid) out.write(formatSize(uploaded)); out.write("</td>\n\t"); out.write("<td align=\"right\" class=\"snarkTorrentRateDown\">"); if(isRunning && needed > 0) out.write(formatSize(downBps) + "ps"); out.write("</td>\n\t"); out.write("<td align=\"right\" class=\"snarkTorrentRateUp\">"); if(isRunning && isValid) out.write(formatSize(upBps) + "ps"); out.write("</td>\n\t"); out.write("<td align=\"center\" class=\"snarkTorrentAction " + rowClass + "\">"); String parameters = "&nonce=" + _nonce + "&torrent=" + Base64.encode(snark.getInfoHash()); String b64 = Base64.encode(snark.getInfoHash()); if (showPeers) parameters = parameters + "&p=1"; if (snark.isChecking()) { // show no buttons } else if (isRunning) { // Stop Button if (isDegraded) out.write("<a href=\"" + _contextPath + "/?action=Stop_" + b64 + "&amp;nonce=" + _nonce + "\"><img title=\""); else out.write("<input type=\"image\" name=\"action_Stop_" + b64 + "\" value=\"foo\" title=\""); out.write(_("Stop the torrent")); out.write("\" src=\"" + _imgPath + "stop.png\" alt=\""); out.write(_("Stop")); out.write("\">"); if (isDegraded) out.write("</a>"); } else if (!snark.isStarting()) { if (!_manager.isStopping()) { // Start Button // This works in Opera but it's displayed a little differently, so use noThinsp here too so all 3 icons are consistent if (noThinsp) out.write("<a href=\"/" + _contextPath + "/?action=Start_" + b64 + "&amp;nonce=" + _nonce + "\"><img title=\""); else out.write("<input type=\"image\" name=\"action_Start_" + b64 + "\" value=\"foo\" title=\""); out.write(_("Start the torrent")); out.write("\" src=\"" + _imgPath + "start.png\" alt=\""); out.write(_("Start")); out.write("\">"); if (isDegraded) out.write("</a>"); } if (isValid) { // Remove Button // Doesnt work with Opera so use noThinsp instead of isDegraded if (noThinsp) out.write("<a href=\"" + _contextPath + "/?action=Remove_" + b64 + "&amp;nonce=" + _nonce + "\"><img title=\""); else out.write("<input type=\"image\" name=\"action_Remove_" + b64 + "\" value=\"foo\" title=\""); out.write(_("Remove the torrent from the active list, deleting the .torrent file")); out.write("\" onclick=\"if (!confirm('"); // Can't figure out how to escape double quotes inside the onclick string. // Single quotes in translate strings with parameters must be doubled. // Then the remaining single quote must be escaped out.write(_("Are you sure you want to delete the file \\''{0}.torrent\\'' (downloaded data will not be deleted) ?", fullFilename)); out.write("')) { return false; }\""); out.write(" src=\"" + _imgPath + "remove.png\" alt=\""); out.write(_("Remove")); out.write("\">"); if (isDegraded) out.write("</a>"); } // Delete Button // Doesnt work with Opera so use noThinsp instead of isDegraded if (noThinsp) out.write("<a href=\"" + _contextPath + "/?action=Delete_" + b64 + "&amp;nonce=" + _nonce + "\"><img title=\""); else out.write("<input type=\"image\" name=\"action_Delete_" + b64 + "\" value=\"foo\" title=\""); out.write(_("Delete the .torrent file and the associated data file(s)")); out.write("\" onclick=\"if (!confirm('"); // Can't figure out how to escape double quotes inside the onclick string. // Single quotes in translate strings with parameters must be doubled. // Then the remaining single quote must be escaped out.write(_("Are you sure you want to delete the torrent \\''{0}\\'' and all downloaded data?", fullFilename)); out.write("')) { return false; }\""); out.write(" src=\"" + _imgPath + "delete.png\" alt=\""); out.write(_("Delete")); out.write("\">"); if (isDegraded) out.write("</a>"); } out.write("</td>\n</tr>\n"); if(showPeers && isRunning && curPeers > 0) { List<Peer> peers = snark.getPeerList(); if (!showDebug) Collections.sort(peers, new PeerComparator()); for (Peer peer : peers) { if (!peer.isConnected()) continue; out.write("<tr class=\"" + rowClass + "\"><td></td>"); out.write("<td colspan=\"4\" align=\"right\" class=\"" + rowClass + "\">"); String ch = peer.toString().substring(0, 4); String client; if ("AwMD".equals(ch)) client = _("I2PSnark"); else if ("BFJT".equals(ch)) client = "I2PRufus"; else if ("TTMt".equals(ch)) client = "I2P-BT"; else if ("LUFa".equals(ch)) client = "Azureus"; else if ("CwsL".equals(ch)) client = "I2PSnarkXL"; else if ("ZV".equals(ch.substring(2,4)) || "VUZP".equals(ch)) client = "Robert"; else if (ch.startsWith("LV")) // LVCS 1.0.2?; LVRS 1.0.4 client = "Transmission"; else if ("LUtU".equals(ch)) client = "KTorrent"; else client = _("Unknown") + " (" + ch + ')'; out.write(client + "&nbsp;&nbsp;<tt>" + peer.toString().substring(5, 9)+ "</tt>"); if (showDebug) out.write(" inactive " + (peer.getInactiveTime() / 1000) + "s"); out.write("</td>\n\t"); out.write("<td class=\"snarkTorrentStatus " + rowClass + "\">"); out.write("</td>\n\t"); out.write("<td align=\"right\" class=\"snarkTorrentStatus " + rowClass + "\">"); float pct; if (isValid) { pct = (float) (100.0 * peer.completed() / meta.getPieces()); if (pct == 100.0) out.write(_("Seed")); else { String ps = String.valueOf(pct); if (ps.length() > 5) ps = ps.substring(0, 5); out.write(ps + "%"); } } else { pct = (float) 101.0; // until we get the metainfo we don't know how many pieces there are //out.write("??"); } out.write("</td>\n\t"); out.write("<td class=\"snarkTorrentStatus " + rowClass + "\">"); out.write("</td>\n\t"); out.write("<td align=\"right\" class=\"snarkTorrentStatus " + rowClass + "\">"); if (needed > 0) { if (peer.isInteresting() && !peer.isChoked()) { out.write("<span class=\"unchoked\">"); out.write(formatSize(peer.getDownloadRate()) + "ps</span>"); } else { out.write("<span class=\"choked\"><a title=\""); if (!peer.isInteresting()) out.write(_("Uninteresting (The peer has no pieces we need)")); else out.write(_("Choked (The peer is not allowing us to request pieces)")); out.write("\">"); out.write(formatSize(peer.getDownloadRate()) + "ps</a></span>"); } } else if (!isValid) { //if (peer supports metadata extension) { out.write("<span class=\"unchoked\">"); out.write(formatSize(peer.getDownloadRate()) + "ps</span>"); //} else { //} } out.write("</td>\n\t"); out.write("<td align=\"right\" class=\"snarkTorrentStatus " + rowClass + "\">"); if (isValid && pct < 100.0) { if (peer.isInterested() && !peer.isChoking()) { out.write("<span class=\"unchoked\">"); out.write(formatSize(peer.getUploadRate()) + "ps</span>"); } else { out.write("<span class=\"choked\"><a title=\""); if (!peer.isInterested()) out.write(_("Uninterested (We have no pieces the peer needs)")); else out.write(_("Choking (We are not allowing the peer to request pieces)")); out.write("\">"); out.write(formatSize(peer.getUploadRate()) + "ps</a></span>"); } } out.write("</td>\n\t"); out.write("<td class=\"snarkTorrentStatus " + rowClass + "\">"); out.write("</td></tr>\n\t"); if (showDebug) out.write("<tr class=\"" + rowClass + "\"><td></td><td colspan=\"10\" align=\"right\" class=\"" + rowClass + "\">" + peer.getSocket() + "</td></tr>"); } } } /** @since 0.8.2 */ private static String thinsp(boolean disable) { if (disable) return " / "; return ("&thinsp;/&thinsp;"); } /** * Sort by completeness (seeds first), then by ID * @since 0.8.1 */ private static class PeerComparator implements Comparator<Peer> { public int compare(Peer l, Peer r) { int diff = r.completed() - l.completed(); // reverse if (diff != 0) return diff; return l.toString().substring(5, 9).compareTo(r.toString().substring(5, 9)); } } /** * Start of anchor only, caller must add anchor text or img and close anchor * @return string or null * @since 0.8.4 */ private String getTrackerLinkUrl(String announce, byte[] infohash) { // temporarily hardcoded for postman* and anonymity, requires bytemonsoon patch for lookup by info_hash if (announce != null && (announce.startsWith("http://YRgrgTLG") || announce.startsWith("http://8EoJZIKr") || announce.startsWith("http://lnQ6yoBT") || announce.startsWith("http://tracker2.postman.i2p/") || announce.startsWith("http://ahsplxkbhemefwvvml7qovzl5a2b5xo5i7lyai7ntdunvcyfdtna.b32.i2p/"))) { for (Tracker t : _manager.getTrackers()) { String aURL = t.announceURL; if (!(aURL.startsWith(announce) || // vvv hack for non-b64 announce in list vvv (announce.startsWith("http://lnQ6yoBT") && aURL.startsWith("http://tracker2.postman.i2p/")) || (announce.startsWith("http://ahsplxkbhemefwvvml7qovzl5a2b5xo5i7lyai7ntdunvcyfdtna.b32.i2p/") && aURL.startsWith("http://tracker2.postman.i2p/")))) continue; String baseURL = t.baseURL; String name = t.name; StringBuilder buf = new StringBuilder(128); buf.append("<a href=\"").append(baseURL).append("details.php?dllist=1&amp;filelist=1&amp;info_hash=") .append(TrackerClient.urlencode(infohash)) .append("\" title=\"").append(_("Details at {0} tracker", name)).append("\" target=\"_blank\">"); return buf.toString(); } } return null; } /** * Full anchor with img * @return string or null * @since 0.8.4 */ private String getTrackerLink(String announce, byte[] infohash) { String linkUrl = getTrackerLinkUrl(announce, infohash); if (linkUrl != null) { StringBuilder buf = new StringBuilder(128); buf.append(linkUrl) .append("<img alt=\"").append(_("Info")).append("\" border=\"0\" src=\"") .append(_imgPath).append("details.png\"></a>"); return buf.toString(); } return null; } /** * Full anchor with shortened URL as anchor text * @return string, non-null * @since 0.9.5 */ private String getShortTrackerLink(String announce, byte[] infohash) { StringBuilder buf = new StringBuilder(128); String trackerLinkUrl = getTrackerLinkUrl(announce, infohash); if (trackerLinkUrl != null) buf.append(trackerLinkUrl); if (announce.startsWith("http://")) announce = announce.substring(7); int slsh = announce.indexOf('/'); if (slsh > 0) announce = announce.substring(0, slsh); if (announce.length() > 67) announce = announce.substring(0, 40) + "&hellip;" + announce.substring(announce.length() - 8); buf.append(announce); if (trackerLinkUrl != null) buf.append("</a>"); return buf.toString(); } private void writeAddForm(PrintWriter out, HttpServletRequest req) throws IOException { // display incoming parameter if a GET so links will work String newURL = req.getParameter("newURL"); if (newURL == null || newURL.trim().length() <= 0 || req.getMethod().equals("POST")) newURL = ""; else newURL = DataHelper.stripHTML(newURL); // XSS //String newFile = req.getParameter("newFile"); //if ( (newFile == null) || (newFile.trim().length() <= 0) ) newFile = ""; out.write("<div class=\"snarkNewTorrent\">\n"); // *not* enctype="multipart/form-data", so that the input type=file sends the filename, not the file out.write("<form action=\"_post\" method=\"POST\">\n"); out.write("<input type=\"hidden\" name=\"nonce\" value=\"" + _nonce + "\" >\n"); out.write("<input type=\"hidden\" name=\"action\" value=\"Add\" >\n"); // don't lose peer setting String peerParam = req.getParameter("p"); if (peerParam != null) out.write("<input type=\"hidden\" name=\"p\" value=\"" + peerParam + "\" >\n"); out.write("<div class=\"addtorrentsection\"><span class=\"snarkConfigTitle\">"); out.write("<img alt=\"\" border=\"0\" src=\"" + _imgPath + "add.png\"> "); out.write(_("Add Torrent")); out.write("</span><hr>\n<table border=\"0\"><tr><td>"); out.write(_("From URL")); out.write(":<td><input type=\"text\" name=\"newURL\" size=\"85\" value=\"" + newURL + "\""); out.write(" title=\""); out.write(_("Enter the torrent file download URL (I2P only), magnet link, maggot link, or info hash")); out.write("\"> \n"); // not supporting from file at the moment, since the file name passed isn't always absolute (so it may not resolve) //out.write("From file: <input type=\"file\" name=\"newFile\" size=\"50\" value=\"" + newFile + "\" /><br>"); out.write("<input type=\"submit\" class=\"add\" value=\""); out.write(_("Add torrent")); out.write("\" name=\"foo\" ><br>\n"); out.write("<tr><td>&nbsp;<td><span class=\"snarkAddInfo\">"); out.write(_("You can also copy .torrent files to: {0}.", "<code>" + _manager.getDataDir().getAbsolutePath () + "</code>")); out.write("\n"); out.write(_("Removing a .torrent will cause it to stop.")); out.write("<br></span></table>\n"); out.write("</div></form></div>"); } private void writeSeedForm(PrintWriter out, HttpServletRequest req, List<Tracker> sortedTrackers) throws IOException { String baseFile = req.getParameter("baseFile"); if (baseFile == null || baseFile.trim().length() <= 0) baseFile = ""; else baseFile = DataHelper.stripHTML(baseFile); // XSS out.write("<a name=\"add\"></a><div class=\"newtorrentsection\"><div class=\"snarkNewTorrent\">\n"); // *not* enctype="multipart/form-data", so that the input type=file sends the filename, not the file out.write("<form action=\"_post\" method=\"POST\">\n"); out.write("<input type=\"hidden\" name=\"nonce\" value=\"" + _nonce + "\" >\n"); out.write("<input type=\"hidden\" name=\"action\" value=\"Create\" >\n"); // don't lose peer setting String peerParam = req.getParameter("p"); if (peerParam != null) out.write("<input type=\"hidden\" name=\"p\" value=\"" + peerParam + "\" >\n"); out.write("<span class=\"snarkConfigTitle\">"); out.write("<img alt=\"\" border=\"0\" src=\"" + _imgPath + "create.png\"> "); out.write(_("Create Torrent")); out.write("</span><hr>\n<table border=\"0\"><tr><td>"); //out.write("From file: <input type=\"file\" name=\"newFile\" size=\"50\" value=\"" + newFile + "\" /><br>\n"); out.write(_("Data to seed")); out.write(":<td><code>" + _manager.getDataDir().getAbsolutePath() + File.separatorChar + "</code><input type=\"text\" name=\"baseFile\" size=\"58\" value=\"" + baseFile + "\" title=\""); out.write(_("File or directory to seed (must be within the specified path)")); out.write("\" ><tr><td>\n"); out.write(_("Trackers")); out.write(":<td><table style=\"width: 30%;\"><tr><td></td><td align=\"center\">"); out.write(_("Primary")); out.write("</td><td align=\"center\">"); out.write(_("Alternates")); out.write("</td><td rowspan=\"0\">" + " <input type=\"submit\" class=\"create\" value=\""); out.write(_("Create torrent")); out.write("\" name=\"foo\" >" + "</td></tr>\n"); for (Tracker t : sortedTrackers) { String name = t.name; String announceURL = t.announceURL.replace("&#61;", "="); out.write("<tr><td>"); out.write(name); out.write("</td><td align=\"center\"><input type=\"radio\" name=\"announceURL\" value=\""); out.write(announceURL); out.write("\""); if (announceURL.equals(_lastAnnounceURL)) out.write(" checked"); out.write("></td><td align=\"center\"><input type=\"checkbox\" name=\"backup_"); out.write(announceURL); out.write("\" value=\"foo\"></td></tr>\n"); } out.write("<tr><td><i>"); out.write(_("none")); out.write("</i></td><td align=\"center\"><input type=\"radio\" name=\"announceURL\" value=\"none\""); if (_lastAnnounceURL == null) out.write(" checked"); out.write("></td><td></td></tr></table>\n"); // make the user add a tracker on the config form now //out.write(_("or")); //out.write("&nbsp;<input type=\"text\" name=\"announceURLOther\" size=\"57\" value=\"http://\" " + // "title=\""); //out.write(_("Specify custom tracker announce URL")); //out.write("\" > " + out.write("</td></tr>" + "</table>\n" + "</form></div></div>"); } private static final int[] times = { 5, 15, 30, 60, 2*60, 5*60, 10*60, 30*60, -1 }; private void writeConfigForm(PrintWriter out, HttpServletRequest req) throws IOException { String dataDir = _manager.getDataDir().getAbsolutePath(); boolean filesPublic = _manager.areFilesPublic(); boolean autoStart = _manager.shouldAutoStart(); boolean useOpenTrackers = _manager.util().shouldUseOpenTrackers(); //String openTrackers = _manager.util().getOpenTrackerString(); boolean useDHT = _manager.util().shouldUseDHT(); //int seedPct = 0; out.write("<form action=\"" + _contextPath + "/configure\" method=\"POST\">\n" + "<div class=\"configsectionpanel\"><div class=\"snarkConfig\">\n" + "<input type=\"hidden\" name=\"nonce\" value=\"" + _nonce + "\" >\n" + "<input type=\"hidden\" name=\"action\" value=\"Save\" >\n" + "<span class=\"snarkConfigTitle\">" + "<img alt=\"\" border=\"0\" src=\"" + _imgPath + "config.png\"> "); out.write(_("Configuration")); out.write("</span><hr>\n" + "<table border=\"0\"><tr><td>"); out.write(_("Data directory")); out.write(": <td><code>" + dataDir + "</code> <i>("); // translators: parameter is a file name out.write(_("Edit {0} and restart to change", _manager.getConfigFilename())); out.write(")</i><br>\n" + "<tr><td>"); out.write(_("Files readable by all")); out.write(": <td><input type=\"checkbox\" class=\"optbox\" name=\"filesPublic\" value=\"true\" " + (filesPublic ? "checked " : "") + "title=\""); out.write(_("If checked, other users may access the downloaded files")); out.write("\" >" + "<tr><td>"); out.write(_("Auto start")); out.write(": <td><input type=\"checkbox\" class=\"optbox\" name=\"autoStart\" value=\"true\" " + (autoStart ? "checked " : "") + "title=\""); out.write(_("If checked, automatically start torrents that are added")); out.write("\" >" + "<tr><td>"); out.write(_("Theme")); out.write(": <td><select name='theme'>"); String theme = _manager.getTheme(); String[] themes = _manager.getThemes(); for(int i = 0; i < themes.length; i++) { if(themes[i].equals(theme)) out.write("\n<OPTION value=\"" + themes[i] + "\" SELECTED>" + themes[i]); else out.write("\n<OPTION value=\"" + themes[i] + "\">" + themes[i]); } out.write("</select>\n" + "<tr><td>"); out.write(_("Refresh time")); out.write(": <td><select name=\"refreshDelay\">"); int delay = _manager.getRefreshDelaySeconds(); for (int i = 0; i < times.length; i++) { out.write("<option value=\""); out.write(Integer.toString(times[i])); out.write("\""); if (times[i] == delay) out.write(" selected=\"selected\""); out.write(">"); if (times[i] > 0) out.write(DataHelper.formatDuration2(times[i] * 1000)); else out.write(_("Never")); out.write("</option>\n"); } out.write("</select><br>" + "<tr><td>"); out.write(_("Startup delay")); out.write(": <td><input name=\"startupDelay\" size=\"3\" class=\"r\" value=\"" + _manager.util().getStartupDelay() + "\"> "); out.write(_("minutes")); out.write("<br>\n"); //Auto add: <input type="checkbox" name="autoAdd" value="true" title="If true, automatically add torrents that are found in the data directory" /> //Auto stop: <input type="checkbox" name="autoStop" value="true" title="If true, automatically stop torrents that are removed from the data directory" /> //out.write("<br>\n"); /* out.write("Seed percentage: <select name=\"seedPct\" disabled=\"true\" >\n\t"); if (seedPct <= 0) out.write("<option value=\"0\" selected=\"selected\">Unlimited</option>\n\t"); else out.write("<option value=\"0\">Unlimited</option>\n\t"); if (seedPct == 100) out.write("<option value=\"100\" selected=\"selected\">100%</option>\n\t"); else out.write("<option value=\"100\">100%</option>\n\t"); if (seedPct == 150) out.write("<option value=\"150\" selected=\"selected\">150%</option>\n\t"); else out.write("<option value=\"150\">150%</option>\n\t"); out.write("</select><br>\n"); */ out.write("<tr><td>"); out.write(_("Total uploader limit")); out.write(": <td><input type=\"text\" name=\"upLimit\" class=\"r\" value=\"" + _manager.util().getMaxUploaders() + "\" size=\"3\" maxlength=\"3\" > "); out.write(_("peers")); out.write("<br>\n" + "<tr><td>"); out.write(_("Up bandwidth limit")); out.write(": <td><input type=\"text\" name=\"upBW\" class=\"r\" value=\"" + _manager.util().getMaxUpBW() + "\" size=\"4\" maxlength=\"4\" > KBps <i>"); out.write(_("Half available bandwidth recommended.")); out.write(" [<a href=\"/config.jsp\" target=\"blank\">"); out.write(_("View or change router bandwidth")); out.write("</a>]</i><br>\n" + "<tr><td>"); out.write(_("Use open trackers also")); out.write(": <td><input type=\"checkbox\" class=\"optbox\" name=\"useOpenTrackers\" value=\"true\" " + (useOpenTrackers ? "checked " : "") + "title=\""); out.write(_("If checked, announce torrents to open trackers as well as the tracker listed in the torrent file")); out.write("\" ></td></tr>\n" + "<tr><td>"); out.write(_("Enable DHT")); out.write(": <td><input type=\"checkbox\" class=\"optbox\" name=\"useDHT\" value=\"true\" " + (useDHT ? "checked " : "") + "title=\""); out.write(_("If checked, use DHT")); out.write("\" ></td></tr>\n"); // "<tr><td>"); //out.write(_("Open tracker announce URLs")); //out.write(": <td><input type=\"text\" name=\"openTrackers\" value=\"" // + openTrackers + "\" size=\"50\" ><br>\n"); //out.write("\n"); //out.write("EepProxy host: <input type=\"text\" name=\"eepHost\" value=\"" // + _manager.util().getEepProxyHost() + "\" size=\"15\" /> "); //out.write("port: <input type=\"text\" name=\"eepPort\" value=\"" // + _manager.util().getEepProxyPort() + "\" size=\"5\" maxlength=\"5\" /><br>\n"); Map<String, String> options = new TreeMap(_manager.util().getI2CPOptions()); out.write("<tr><td>"); out.write(_("Inbound Settings")); out.write(":<td>"); out.write(renderOptions(1, 6, options.remove("inbound.quantity"), "inbound.quantity", TUNNEL)); out.write("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"); out.write(renderOptions(0, 4, options.remove("inbound.length"), "inbound.length", HOP)); out.write("<tr><td>"); out.write(_("Outbound Settings")); out.write(":<td>"); out.write(renderOptions(1, 6, options.remove("outbound.quantity"), "outbound.quantity", TUNNEL)); out.write("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"); out.write(renderOptions(0, 4, options.remove("outbound.length"), "outbound.length", HOP)); if (!_context.isRouterContext()) { out.write("<tr><td>"); out.write(_("I2CP host")); out.write(": <td><input type=\"text\" name=\"i2cpHost\" value=\"" + _manager.util().getI2CPHost() + "\" size=\"15\" > " + "<tr><td>"); out.write(_("I2CP port")); out.write(": <td><input type=\"text\" name=\"i2cpPort\" class=\"r\" value=\"" + + _manager.util().getI2CPPort() + "\" size=\"5\" maxlength=\"5\" > <br>\n"); } options.remove(I2PSnarkUtil.PROP_MAX_BW); // was accidentally in the I2CP options prior to 0.8.9 so it will be in old config files options.remove(SnarkManager.PROP_OPENTRACKERS); StringBuilder opts = new StringBuilder(64); for (Map.Entry<String, String> e : options.entrySet()) { String key = e.getKey(); String val = e.getValue(); opts.append(key).append('=').append(val).append(' '); } out.write("<tr><td>"); out.write(_("I2CP options")); out.write(": <td><textarea name=\"i2cpOpts\" cols=\"60\" rows=\"1\" wrap=\"off\" spellcheck=\"false\" >" + opts.toString() + "</textarea><br>\n" + "<tr><td colspan=\"2\">&nbsp;\n" + // spacer "<tr><td>&nbsp;<td><input type=\"submit\" class=\"accept\" value=\""); out.write(_("Save configuration")); out.write("\" name=\"foo\" >\n" + "<tr><td colspan=\"2\">&nbsp;\n" + // spacer "</table></div></div></form>"); } /** @since 0.9 */ private void writeTrackerForm(PrintWriter out, HttpServletRequest req) throws IOException { StringBuilder buf = new StringBuilder(1024); buf.append("<form action=\"" + _contextPath + "/configure\" method=\"POST\">\n" + "<div class=\"configsectionpanel\"><div class=\"snarkConfig\">\n" + "<input type=\"hidden\" name=\"nonce\" value=\"" + _nonce + "\" >\n" + "<input type=\"hidden\" name=\"action\" value=\"Save2\" >\n" + "<span class=\"snarkConfigTitle\">" + "<img alt=\"\" border=\"0\" src=\"" + _imgPath + "config.png\"> "); buf.append(_("Trackers")); buf.append("</span><hr>\n" + "<table class=\"trackerconfig\"><tr><th>") //.append(_("Remove")) .append("</th><th>") .append(_("Name")) .append("</th><th>") .append(_("Website URL")) .append("</th><th>") .append(_("Open")) .append("</th><th>") .append(_("Private")) .append("</th><th>") .append(_("Announce URL")) .append("</th></tr>\n"); List<String> openTrackers = _manager.util().getOpenTrackers(); List<String> privateTrackers = _manager.getPrivateTrackers(); for (Tracker t : _manager.getSortedTrackers()) { String name = t.name; String homeURL = t.baseURL; String announceURL = t.announceURL.replace("&#61;", "="); buf.append("<tr><td><input type=\"checkbox\" class=\"optbox\" name=\"delete_") .append(name).append("\" title=\"").append(_("Delete")).append("\">" + "</td><td>").append(name) .append("</td><td>").append(urlify(homeURL, 35)) .append("</td><td><input type=\"checkbox\" class=\"optbox\" name=\"open_") .append(announceURL).append("\""); if (openTrackers.contains(t.announceURL)) buf.append(" checked=\"checked\""); buf.append(">" + "</td><td><input type=\"checkbox\" class=\"optbox\" name=\"private_") .append(announceURL).append("\""); if (privateTrackers.contains(t.announceURL)) { buf.append(" checked=\"checked\""); } else { for (int i = 1; i < SnarkManager.DEFAULT_TRACKERS.length; i += 2) { if (SnarkManager.DEFAULT_TRACKERS[i].contains(t.announceURL)) { buf.append(" disabled=\"disabled\""); break; } } } buf.append(">" + "</td><td>").append(urlify(announceURL, 35)) .append("</td></tr>\n"); } buf.append("<tr><td><b>") .append(_("Add")).append(":</b></td>" + "<td><input type=\"text\" class=\"trackername\" name=\"tname\"></td>" + "<td><input type=\"text\" class=\"trackerhome\" name=\"thurl\"></td>" + "<td><input type=\"checkbox\" class=\"optbox\" name=\"_add_open_\"></td>" + "<td><input type=\"checkbox\" class=\"optbox\" name=\"_add_private_\"></td>" + "<td><input type=\"text\" class=\"trackerannounce\" name=\"taurl\"></td></tr>\n" + "<tr><td colspan=\"6\">&nbsp;</td></tr>\n" + // spacer "<tr><td colspan=\"2\"></td><td colspan=\"4\">\n" + "<input type=\"submit\" name=\"taction\" class=\"default\" value=\"").append(_("Add tracker")).append("\">\n" + "<input type=\"submit\" name=\"taction\" class=\"delete\" value=\"").append(_("Delete selected")).append("\">\n" + "<input type=\"submit\" name=\"taction\" class=\"accept\" value=\"").append(_("Save tracker configuration")).append("\">\n" + // "<input type=\"reset\" class=\"cancel\" value=\"").append(_("Cancel")).append("\">\n" + "<input type=\"submit\" name=\"taction\" class=\"reload\" value=\"").append(_("Restore defaults")).append("\">\n" + "<input type=\"submit\" name=\"taction\" class=\"add\" value=\"").append(_("Add tracker")).append("\">\n" + "</td></tr>" + "<tr><td colspan=\"6\">&nbsp;</td></tr>\n" + // spacer "</table></div></div></form>\n"); out.write(buf.toString()); } private void writeConfigLink(PrintWriter out) throws IOException { out.write("<div class=\"configsection\"><span class=\"snarkConfig\">\n" + "<span class=\"snarkConfigTitle\"><a href=\"configure\">" + "<img alt=\"\" border=\"0\" src=\"" + _imgPath + "config.png\"> "); out.write(_("Configuration")); out.write("</a></span></span></div>\n"); } /** * @param url in base32 or hex * @since 0.8.4 */ private void addMagnet(String url) { try { MagnetURI magnet = new MagnetURI(_manager.util(), url); String name = magnet.getName(); byte[] ih = magnet.getInfoHash(); String trackerURL = magnet.getTrackerURL(); _manager.addMagnet(name, ih, trackerURL, true); } catch (IllegalArgumentException iae) { _manager.addMessage(_("Invalid magnet URL {0}", url)); } } /** copied from ConfigTunnelsHelper */ private static final String HOP = "hop"; private static final String TUNNEL = "tunnel"; /** dummies for translation */ private static final String HOPS = ngettext("1 hop", "{0} hops"); private static final String TUNNELS = ngettext("1 tunnel", "{0} tunnels"); /** prevents the ngettext line below from getting tagged */ private static final String DUMMY0 = "{0} "; private static final String DUMMY1 = "1 "; /** modded from ConfigTunnelsHelper @since 0.7.14 */ private String renderOptions(int min, int max, String strNow, String selName, String name) { int now = 2; try { now = Integer.parseInt(strNow); } catch (Throwable t) {} StringBuilder buf = new StringBuilder(128); buf.append("<select name=\"").append(selName).append("\">\n"); for (int i = min; i <= max; i++) { buf.append("<option value=\"").append(i).append("\" "); if (i == now) buf.append("selected=\"selected\" "); // constants to prevent tagging buf.append(">").append(ngettext(DUMMY1 + name, DUMMY0 + name + 's', i)); buf.append("</option>\n"); } buf.append("</select>\n"); return buf.toString(); } /** translate */ private String _(String s) { return _manager.util().getString(s); } /** translate */ private String _(String s, Object o) { return _manager.util().getString(s, o); } /** translate */ private String _(String s, Object o, Object o2) { return _manager.util().getString(s, o, o2); } /** translate (ngettext) @since 0.7.14 */ private String ngettext(String s, String p, int n) { return _manager.util().getString(n, s, p); } /** dummy for tagging */ private static String ngettext(String s, String p) { return null; } // rounding makes us look faster :) private static String formatSize(long bytes) { if (bytes < 5000) return bytes + "&nbsp;B"; else if (bytes < 5*1024*1024) return ((bytes + 512)/1024) + "&nbsp;KB"; else if (bytes < 10*1024*1024*1024l) return ((bytes + 512*1024)/(1024*1024)) + "&nbsp;MB"; else return ((bytes + 512*1024*1024)/(1024*1024*1024)) + "&nbsp;GB"; } /** @since 0.7.14 */ static String urlify(String s) { return urlify(s, 100); } /** @since 0.9 */ private static String urlify(String s, int max) { StringBuilder buf = new StringBuilder(256); // browsers seem to work without doing this but let's be strict String link = urlEncode(s); String display; if (s.length() <= max) display = link; else display = urlEncode(s.substring(0, max)) + "&hellip;"; buf.append("<a href=\"").append(link).append("\">").append(display).append("</a>"); return buf.toString(); } /** @since 0.8.13 */ private static String urlEncode(String s) { return s.replace(";", "%3B").replace("&", "&amp;").replace(" ", "%20"); } private static final String DOCTYPE = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n"; private static final String HEADER_A = "<link href=\""; private static final String HEADER_B = "snark.css\" rel=\"stylesheet\" type=\"text/css\" >"; private static final String TABLE_HEADER = "<table border=\"0\" class=\"snarkTorrents\" width=\"100%\" >\n" + "<thead>\n" + "<tr><th>"; private static final String FOOTER = "</div></center></body></html>"; /** * Modded heavily from the Jetty version in Resource.java, * pass Resource as 1st param * All the xxxResource constructors are package local so we can't extend them. * * <pre> // ======================================================================== // $Id: Resource.java,v 1.32 2009/05/16 01:53:36 gregwilkins Exp $ // Copyright 1996-2004 Mort Bay Consulting Pty. Ltd. // ------------------------------------------------------------------------ // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ======================================================================== * </pre> * * Get the resource list as a HTML directory listing. * @param r The Resource * @param base The base URL * @param parent True if the parent directory should be included * @param postParams map of POST parameters or null if not a POST * @return String of HTML or null if postParams != null * @since 0.7.14 */ private String getListHTML(File r, String base, boolean parent, Map postParams) throws IOException { String[] ls = null; if (r.isDirectory()) { ls = r.list(); Arrays.sort(ls, Collator.getInstance()); } // if r is not a directory, we are only showing torrent info section String title = decodePath(base); String cpath = _contextPath + '/'; if (title.startsWith(cpath)) title = title.substring(cpath.length()); // Get the snark associated with this directory String torrentName; int slash = title.indexOf('/'); if (slash > 0) torrentName = title.substring(0, slash); else torrentName = title; Snark snark = _manager.getTorrentByBaseName(torrentName); if (snark != null && postParams != null) { // caller must P-R-G savePriorities(snark, postParams); return null; } StringBuilder buf=new StringBuilder(4096); buf.append(DOCTYPE).append("<HTML><HEAD><TITLE>"); if (title.endsWith("/")) title = title.substring(0, title.length() - 1); String directory = title; title = _("Torrent") + ": " + title; buf.append(title); buf.append("</TITLE>").append(HEADER_A).append(_themePath).append(HEADER_B).append("<link rel=\"shortcut icon\" href=\"" + _themePath + "favicon.ico\">" + "</HEAD><BODY>\n<center><div class=\"snarknavbar\"><a href=\"").append(_contextPath).append("/\" title=\"Torrents\""); buf.append(" class=\"snarkRefresh\"><img alt=\"\" border=\"0\" src=\"" + _imgPath + "arrow_refresh.png\">&nbsp;&nbsp;"); if (_contextName.equals(DEFAULT_NAME)) buf.append(_("I2PSnark")); else buf.append(_contextName); buf.append("</a></div></center>\n"); if (parent) // always true buf.append("<div class=\"page\"><div class=\"mainsection\">"); boolean showPriority = ls != null && snark != null && snark.getStorage() != null && !snark.getStorage().complete(); if (showPriority) buf.append("<form action=\"").append(base).append("\" method=\"POST\">\n"); if (snark != null) { // first table - torrent info buf.append("<table class=\"snarkTorrentInfo\">\n"); buf.append("<tr><th><b>") .append(_("Torrent")) .append(":</b> ") .append(snark.getBaseName()) .append("</th></tr>\n"); String fullPath = snark.getName(); String baseName = urlEncode((new File(fullPath)).getName()); buf.append("<tr><td>") .append("<img alt=\"\" border=\"0\" src=\"" + _imgPath + "file.png\" >&nbsp;<b>") .append(_("Torrent file")) .append(":</b> <a href=\"").append(_contextPath).append('/').append(baseName).append("\">") .append(fullPath) .append("</a></td></tr>\n"); MetaInfo meta = snark.getMetaInfo(); if (meta != null) { String announce = meta.getAnnounce(); if (announce != null) { buf.append("<tr><td>"); String trackerLink = getTrackerLink(announce, snark.getInfoHash()); if (trackerLink != null) buf.append(trackerLink).append(' '); buf.append("<b>").append(_("Primary Tracker")).append(":</b> "); buf.append(getShortTrackerLink(announce, snark.getInfoHash())); buf.append("</td></tr>"); } List<List<String>> alist = meta.getAnnounceList(); if (alist != null) { buf.append("<tr><td><b>"); buf.append(_("Tracker List")).append(":</b> "); for (List<String> alist2 : alist) { buf.append('['); boolean more = false; for (String s : alist2) { if (more) buf.append(' '); else more = true; buf.append(getShortTrackerLink(s, snark.getInfoHash())); } buf.append("] "); } buf.append("</td></tr>"); } } String hex = I2PSnarkUtil.toHex(snark.getInfoHash()); if (meta == null || !meta.isPrivate()) { buf.append("<tr><td><a href=\"") .append(MagnetURI.MAGNET_FULL).append(hex).append("\">") .append(toImg("magnet", _("Magnet link"))) .append("</a> <b>Magnet:</b> <a href=\"") .append(MagnetURI.MAGNET_FULL).append(hex).append("\">") .append(MagnetURI.MAGNET_FULL).append(hex).append("</a>") .append("</td></tr>\n"); } else { buf.append("<tr><td>") .append(_("Private torrent")) .append("</td></tr>\n"); } // We don't have the hash of the torrent file //buf.append("<tr><td>").append(_("Maggot link")).append(": <a href=\"").append(MAGGOT).append(hex).append(':').append(hex).append("\">") // .append(MAGGOT).append(hex).append(':').append(hex).append("</a></td></tr>"); buf.append("<tr><td>") .append("<img alt=\"\" border=\"0\" src=\"" + _imgPath + "size.png\" >&nbsp;<b>") .append(_("Size")) .append(":</b> ") .append(formatSize(snark.getTotalLength())); int pieces = snark.getPieces(); double completion = (pieces - snark.getNeeded()) / (double) pieces; if (completion < 1.0) buf.append("&nbsp;<img alt=\"\" border=\"0\" src=\"" + _imgPath + "head_rx.png\" >&nbsp;<b>") .append(_("Completion")) .append(":</b> ") .append((new DecimalFormat("0.00%")).format(completion)); else buf.append("&nbsp;<img alt=\"\" border=\"0\" src=\"" + _imgPath + "head_rx.png\" >&nbsp;") .append(_("Complete")); // else unknown long needed = snark.getNeededLength(); if (needed > 0) buf.append("&nbsp;<img alt=\"\" border=\"0\" src=\"" + _imgPath + "head_rx.png\" >&nbsp;<b>") .append(_("Remaining")) .append(":</b> ") .append(formatSize(needed)); if (meta != null) { List files = meta.getFiles(); int fileCount = files != null ? files.size() : 1; buf.append("&nbsp;<img alt=\"\" border=\"0\" src=\"" + _imgPath + "file.png\" >&nbsp;<b>") .append(_("Files")) .append(":</b> ") .append(fileCount); } buf.append("&nbsp;<img alt=\"\" border=\"0\" src=\"" + _imgPath + "file.png\" >&nbsp;<b>") .append(_("Pieces")) .append(":</b> ") .append(pieces); buf.append("&nbsp;<img alt=\"\" border=\"0\" src=\"" + _imgPath + "file.png\" >&nbsp;<b>") .append(_("Piece size")) .append(":</b> ") .append(formatSize(snark.getPieceLength(0))) .append("</td></tr>\n"); } else { // shouldn't happen buf.append("<tr><th>Not found<br>resource=\"").append(r.toString()) .append("\"<br>base=\"").append(base) .append("\"<br>torrent=\"").append(torrentName) .append("\"</th></tr>\n"); } buf.append("</table>\n"); if (ls == null) { // We are only showing the torrent info section buf.append("</div></div></BODY></HTML>"); return buf.toString(); } // second table - dir info buf.append("<table class=\"snarkDirInfo\"><thead>\n"); buf.append("<tr>\n") .append("<th colspan=2>") .append("<img border=\"0\" src=\"" + _imgPath + "file.png\" title=\"") .append(_("Directory")) .append(": ") .append(directory) .append("\" alt=\"") .append(_("Directory")) .append("\"></th>\n"); buf.append("<th align=\"right\">") .append("<img border=\"0\" src=\"" + _imgPath + "size.png\" title=\"") .append(_("Size")) .append("\" alt=\"") .append(_("Size")) .append("\"></th>\n"); buf.append("<th class=\"headerstatus\">") .append("<img border=\"0\" src=\"" + _imgPath + "status.png\" title=\"") .append(_("Status")) .append("\" alt=\"") .append(_("Status")) .append("\"></th>\n"); if (showPriority) buf.append("<th class=\"headerpriority\">") .append("<img border=\"0\" src=\"" + _imgPath + "priority.png\" title=\"") .append(_("Priority")) .append("\" alt=\"") .append(_("Priority")) .append("\"></th>\n"); buf.append("</tr>\n</thead>\n"); buf.append("<tr><td colspan=\"" + (showPriority ? '5' : '4') + "\" class=\"ParentDir\"><A HREF=\""); buf.append(addPaths(base,"../")); buf.append("\"><img alt=\"\" border=\"0\" src=\"" + _imgPath + "up.png\"> ") .append(_("Up to higher level directory")) .append("</A></td></tr>\n"); //DateFormat dfmt=DateFormat.getDateTimeInstance(DateFormat.MEDIUM, // DateFormat.MEDIUM); boolean showSaveButton = false; for (int i=0 ; i< ls.length ; i++) { String encoded = encodePath(ls[i]); // bugfix for I2P - Backport from Jetty 6 (zero file lengths and last-modified times) // http://jira.codehaus.org/browse/JETTY-361?page=com.atlassian.jira.plugin.system.issuetabpanels%3Achangehistory-tabpanel#issue-tabs // See resource.diff attachment //Resource item = addPath(encoded); File item = new File(r, ls[i]); String rowClass = (i % 2 == 0 ? "snarkTorrentEven" : "snarkTorrentOdd"); buf.append("<TR class=\"").append(rowClass).append("\">"); // Get completeness and status string boolean complete = false; String status = ""; long length = item.length(); if (item.isDirectory()) { complete = true; status = toImg("tick") + ' ' + _("Directory"); } else { if (snark == null || snark.getStorage() == null) { // Assume complete, perhaps he removed a completed torrent but kept a bookmark complete = true; status = toImg("cancel") + ' ' + _("Torrent not found?"); } else { Storage storage = snark.getStorage(); try { File f = item; if (f != null) { long remaining = storage.remaining(f.getCanonicalPath()); if (remaining < 0) { complete = true; status = toImg("cancel") + ' ' + _("File not found in torrent?"); } else if (remaining == 0 || length <= 0) { complete = true; status = toImg("tick") + ' ' + _("Complete"); } else { int priority = storage.getPriority(f.getCanonicalPath()); if (priority < 0) status = toImg("cancel"); else if (priority == 0) status = toImg("clock"); else status = toImg("clock_red"); status += " " + (100 * (length - remaining) / length) + "% " + _("complete") + " (" + DataHelper.formatSize2(remaining) + "B " + _("remaining") + ")"; } } else { status = "Not a file?"; } } catch (IOException ioe) { status = "Not a file? " + ioe; } } } String path=addPaths(base,encoded); if (item.isDirectory() && !path.endsWith("/")) path=addPaths(path,"/"); String icon = toIcon(item); buf.append("<TD class=\"snarkFileIcon ") .append(rowClass).append("\">"); if (complete) { buf.append("<a href=\"").append(path).append("\">"); // thumbnail ? String plc = item.toString().toLowerCase(Locale.US); if (plc.endsWith(".jpg") || plc.endsWith(".jpeg") || plc.endsWith(".png") || plc.endsWith(".gif") || plc.endsWith(".ico")) { buf.append("<img alt=\"\" border=\"0\" class=\"thumb\" src=\"") .append(path).append("\"></a>"); } else { buf.append(toImg(icon, _("Open"))).append("</a>"); } } else { buf.append(toImg(icon)); } buf.append("</TD><TD class=\"snarkFileName ") .append(rowClass).append("\">"); if (complete) buf.append("<a href=\"").append(path).append("\">"); buf.append(ls[i]); if (complete) buf.append("</a>"); buf.append("</TD><TD ALIGN=right class=\"").append(rowClass).append(" snarkFileSize\">"); if (!item.isDirectory()) buf.append(DataHelper.formatSize2(length)).append('B'); buf.append("</TD><TD class=\"").append(rowClass).append(" snarkFileStatus\">"); //buf.append(dfmt.format(new Date(item.lastModified()))); buf.append(status); buf.append("</TD>"); if (showPriority) { buf.append("<td class=\"priority\">"); File f = item; if ((!complete) && (!item.isDirectory()) && f != null) { int pri = snark.getStorage().getPriority(f.getCanonicalPath()); buf.append("<input type=\"radio\" value=\"5\" name=\"pri.").append(f.getCanonicalPath()).append("\" "); if (pri > 0) buf.append("checked=\"true\""); buf.append('>').append(_("High")); buf.append("<input type=\"radio\" value=\"0\" name=\"pri.").append(f.getCanonicalPath()).append("\" "); if (pri == 0) buf.append("checked=\"true\""); buf.append('>').append(_("Normal")); buf.append("<input type=\"radio\" value=\"-9\" name=\"pri.").append(f.getCanonicalPath()).append("\" "); if (pri < 0) buf.append("checked=\"true\""); buf.append('>').append(_("Skip")); showSaveButton = true; } buf.append("</td>"); } buf.append("</TR>\n"); } if (showSaveButton) { buf.append("<thead><tr><th colspan=\"4\">&nbsp;</th><th class=\"headerpriority\"><input type=\"submit\" value=\""); buf.append(_("Save priorities")); buf.append("\" name=\"foo\" ></th></tr></thead>\n"); } buf.append("</table>\n"); if (showPriority) buf.append("</form>"); buf.append("</div></div></BODY></HTML>\n"); return buf.toString(); } /** @since 0.7.14 */ private String toIcon(File item) { if (item.isDirectory()) return "folder"; return toIcon(item.toString()); } /** * Pick an icon; try to catch the common types in an i2p environment * @return file name not including ".png" * @since 0.7.14 */ private String toIcon(String path) { String icon; // Note that for this to work well, our custom mime.properties file must be loaded. String plc = path.toLowerCase(Locale.US); String mime = getMimeType(path); if (mime == null) mime = ""; if (mime.equals("text/html")) icon = "html"; else if (mime.equals("text/plain") || mime.equals("application/rtf")) icon = "page"; else if (mime.equals("application/java-archive") || plc.endsWith(".deb")) icon = "package"; else if (plc.endsWith(".xpi2p")) icon = "plugin"; else if (mime.equals("application/pdf")) icon = "page_white_acrobat"; else if (mime.startsWith("image/")) icon = "photo"; else if (mime.startsWith("audio/") || mime.equals("application/ogg")) icon = "music"; else if (mime.startsWith("video/")) icon = "film"; else if (mime.equals("application/zip") || mime.equals("application/x-gtar") || mime.equals("application/compress") || mime.equals("application/gzip") || - mime.equals("application/x-tar")) + mime.equals("application/x-7z-compressed") || mime.equals("application/x-rar-compresed") || + mime.equals("application/x-tar") || mime.equals("application/x-bzip2")) icon = "compress"; else if (plc.endsWith(".exe")) icon = "application"; else if (plc.endsWith(".iso")) icon = "cd"; else icon = "page_white"; return icon; } /** @since 0.7.14 */ private String toImg(String icon) { return "<img alt=\"\" height=\"16\" width=\"16\" src=\"" + _contextPath + "/.icons/" + icon + ".png\">"; } /** @since 0.8.2 */ private String toImg(String icon, String altText) { return "<img alt=\"" + altText + "\" height=\"16\" width=\"16\" src=\"" + _contextPath + "/.icons/" + icon + ".png\">"; } /** @since 0.8.1 */ private void savePriorities(Snark snark, Map postParams) { Storage storage = snark.getStorage(); if (storage == null) return; Set<Map.Entry> entries = postParams.entrySet(); for (Map.Entry entry : entries) { String key = (String)entry.getKey(); if (key.startsWith("pri.")) { try { String file = key.substring(4); String val = ((String[])entry.getValue())[0]; // jetty arrays int pri = Integer.parseInt(val); storage.setPriority(file, pri); //System.err.println("Priority now " + pri + " for " + file); } catch (Throwable t) { t.printStackTrace(); } } } snark.updatePiecePriorities(); _manager.saveTorrentStatus(snark.getMetaInfo(), storage.getBitField(), storage.getFilePriorities()); } }
true
false
null
null
diff --git a/org.eclipse.scout.rt.client/src/org/eclipse/scout/rt/client/services/common/file/FileService.java b/org.eclipse.scout.rt.client/src/org/eclipse/scout/rt/client/services/common/file/FileService.java index cb5712b7a1..fbc4722a9e 100644 --- a/org.eclipse.scout.rt.client/src/org/eclipse/scout/rt/client/services/common/file/FileService.java +++ b/org.eclipse.scout.rt.client/src/org/eclipse/scout/rt/client/services/common/file/FileService.java @@ -1,290 +1,291 @@ /******************************************************************************* * Copyright (c) 2010 BSI Business Systems Integration AG. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html - * + * * Contributors: * BSI Business Systems Integration AG - initial API and implementation ******************************************************************************/ package org.eclipse.scout.rt.client.services.common.file; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Locale; import org.eclipse.core.runtime.Platform; import org.eclipse.scout.commons.annotations.Priority; import org.eclipse.scout.commons.exception.ProcessingException; import org.eclipse.scout.rt.client.ClientSyncJob; import org.eclipse.scout.rt.shared.OfflineState; import org.eclipse.scout.rt.shared.services.common.file.IRemoteFileService; import org.eclipse.scout.rt.shared.services.common.file.RemoteFile; import org.eclipse.scout.service.AbstractService; import org.eclipse.scout.service.SERVICES; import org.osgi.framework.Bundle; @Priority(-1) public class FileService extends AbstractService implements IFileService { private String m_rootPath = null; private Bundle getBundle() { return ClientSyncJob.getCurrentSession().getBundle(); } public File getLocalFile(String dir, String simpleName) throws ProcessingException { return getFileLocation(dir, simpleName, true); } public File getRemoteFile(String dir, String simpleName) throws ProcessingException { return getRemoteFile(dir, simpleName, null); } public File getRemoteFile(String dir, String simpleName, Locale locale) throws ProcessingException { return getRemoteFile(dir, simpleName, locale, true); } public File getRemoteFile(String dir, String simpleName, Locale locale, boolean checkCache) throws ProcessingException { RemoteFile spec = null; File f = null; if (locale != null && simpleName != null && simpleName.lastIndexOf(".") != -1) { String filename = simpleName; String language = locale.toString().replaceAll("__", "_"); String prefix = filename.substring(0, filename.lastIndexOf(".")) + "_"; String suffix = filename.substring(filename.lastIndexOf(".")); filename = prefix + language + suffix; File test = getFileLocation(dir, filename, false); while (!test.exists()) { if (language.indexOf("_") == -1) { filename = simpleName; break; } language = language.substring(0, language.lastIndexOf("_")); filename = prefix + language + suffix; test = getFileLocation(dir, filename, false); } f = getFileLocation(dir, filename, false); spec = new RemoteFile(dir, filename, locale, 0L); } else { f = getFileLocation(dir, simpleName, false); spec = new RemoteFile(dir, simpleName, locale, 0L); } if (f.exists()) { spec.setLastModified(f.lastModified()); } // if (checkCache && OfflineState.isOnlineInCurrentThread()) { IRemoteFileService svc = SERVICES.getService(IRemoteFileService.class); spec = svc.getRemoteFile(spec); try { if (spec.getName() != null && !spec.getName().equalsIgnoreCase(f.getName())) { if (locale != null && f.getName().length() > spec.getName().length()) { // if local file has longer name (including locale), this means that // this file was deleted on the server f.delete(); } f = getFileLocation(spec.getDirectory(), spec.getName(), false); } if (spec.exists() && spec.hasContent()) { spec.writeData(new FileOutputStream(f)); f.setLastModified(spec.getLastModified()); } else if (!spec.exists()) { f.delete(); } } catch (IOException e) { throw new ProcessingException("error writing remote file in local store", e); } } return f; } public void putRemoteFile(RemoteFile f) throws ProcessingException { IRemoteFileService svc = SERVICES.getService(IRemoteFileService.class); svc.putRemoteFile(f); } private String[][] getFiles(String folderBase, FilenameFilter filter, boolean useServerFolderStructureOnClient) throws ProcessingException { File path = getFileLocation(useServerFolderStructureOnClient ? folderBase : "", null, false); ArrayList<String> dirList = new ArrayList<String>(); ArrayList<String> fileList = new ArrayList<String>(); String[] dir = path.list(filter); for (int i = 0; i < dir.length; i++) { try { File file = new File(path.getCanonicalPath() + "/" + dir[i]); if (file.exists() && file.isDirectory()) { String[][] tmp = getFiles((folderBase == null ? dir[i] : folderBase + "/" + dir[i]), filter, true); for (String[] f : tmp) { dirList.add(f[0]); fileList.add(f[1]); } } else { dirList.add(folderBase); fileList.add(dir[i]); } } catch (IOException e) { throw new ProcessingException("FileService.getFiles:", e); } } String[][] retVal = new String[dirList.size()][2]; for (int i = 0; i < dirList.size(); i++) { retVal[i][0] = dirList.get(i); retVal[i][1] = fileList.get(i); } return retVal; } public void syncRemoteFilesToPath(String clientFolderPath, String serverFolderPath, FilenameFilter filter) throws ProcessingException { setDirectPath(clientFolderPath); syncRemoteFilesInternal(serverFolderPath, filter, false); setDirectPath(null); } public void syncRemoteFiles(String serverFolderPath, FilenameFilter filter) throws ProcessingException { syncRemoteFilesInternal(serverFolderPath, filter, true); } private void syncRemoteFilesInternal(String serverFolderPath, FilenameFilter filter, boolean useServerFolderStructureOnClient) throws ProcessingException { IRemoteFileService svc = SERVICES.getService(IRemoteFileService.class); String[][] realFiles = getFiles(serverFolderPath, filter, useServerFolderStructureOnClient); RemoteFile[] existingFileInfoOnClient = new RemoteFile[realFiles.length]; for (int i = 0; i < realFiles.length; i++) { RemoteFile rf = new RemoteFile(realFiles[i][0], realFiles[i][1], 0); - File f = getFileLocation(realFiles[i][0], realFiles[i][1], false); + String dir = m_rootPath == null ? realFiles[i][0] : ""; + File f = getFileLocation(dir, realFiles[i][1], false); if (f.exists()) { rf.setLastModified(f.lastModified()); } existingFileInfoOnClient[i] = rf; } existingFileInfoOnClient = svc.getRemoteFiles(serverFolderPath, filter, existingFileInfoOnClient); for (RemoteFile spec : existingFileInfoOnClient) { String fileDirectory = useServerFolderStructureOnClient ? spec.getDirectory() : null; File f = getFileLocation(fileDirectory, spec.getName(), false); if (spec.exists() && spec.hasContent()) { try { if (spec.hasMoreParts()) { // file is splitted - get all parts int counter = 0; long fileDate = spec.getLastModified(); File part = getFileLocation(fileDirectory, spec.getName() + "." + counter, false); spec.writeData(new FileOutputStream(part)); part.setLastModified(fileDate); RemoteFile specPart = spec; while (specPart.hasMoreParts()) { counter++; part = getFileLocation(fileDirectory, spec.getName() + "." + counter, false); if (!part.exists() || fileDate != part.lastModified()) { specPart = svc.getRemoteFilePart(spec, counter); specPart.writeData(new FileOutputStream(part)); part.setLastModified(fileDate); } else { // resuming canceled part: nothing to do } } // put together counter = 0; f = getFileLocation(fileDirectory, spec.getName(), false); OutputStream out = new FileOutputStream(f); part = getFileLocation(fileDirectory, spec.getName() + "." + counter, false); while (part.exists()) { InputStream in = new FileInputStream(part); byte[] buf = new byte[102400]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } out.flush(); in.close(); part.delete(); counter++; part = getFileLocation(fileDirectory, spec.getName() + "." + counter, false); } out.close(); f.setLastModified(fileDate); } else { // normal files spec.writeData(new FileOutputStream(f)); f.setLastModified(spec.getLastModified()); } } catch (IOException e) { throw new ProcessingException("error writing remote file in local store", e); } } else if (!spec.exists()) { f.delete(); } } } /** * @since 21.10.2009 */ public File getLocalFileLocation(String dir, String name) throws ProcessingException { return getFileLocation(dir, name, true); } /** * @since 21.10.2009 */ public File getRemoteFileLocation(String dir, String name) throws ProcessingException { return getFileLocation(dir, name, false); } private File getFileLocation(String dir, String name, boolean local) throws ProcessingException { try { String path = m_rootPath; if (path == null) { path = Platform.getStateLocation(getBundle()).toFile().getCanonicalPath(); if (!path.endsWith("/")) { path = path + "/"; } if (local) { path = path + "local"; } else { path = path + "remote"; } } if (dir != null) { dir = dir.replace("\\", "/"); if (!dir.startsWith("/")) { path = path + "/"; } path = path + dir; } if (!path.endsWith("/")) { path = path + "/"; } File file = new File(path); if (!file.exists()) { file.mkdirs(); } if (name != null) { file = new File(path + name); } return file; } catch (IOException e) { throw new ProcessingException("io error getting file", e); } } private void setDirectPath(String rootPath) { m_rootPath = rootPath; } }
false
false
null
null
diff --git a/mcpsrc/mod_oceanwaves.java b/mcpsrc/mod_oceanwaves.java index d7a89d4..91b3c1b 100644 --- a/mcpsrc/mod_oceanwaves.java +++ b/mcpsrc/mod_oceanwaves.java @@ -1,27 +1,27 @@ package net.minecraft.src; import java.util.Random; import net.minecraft.src.BaseMod; import net.minecraft.src.World; public class mod_oceanwaves extends BaseMod { private float[] heights = new float[]{0.2F, 0.3F, 0.5F, 0.8F, 1.0F, 1.1F, 0.9F, 0.3F}; public String getVersion() { - return "Minecraft 1.0.0 mod v0"; + return "Minecraft 1.0.0 mod v0.2"; } public void load() {} public float getHeight(World world, int posx, int posy, int posz, Random var5) { int tempid = world.getBlockId(posx,posy+1,posz); if(tempid == Block.waterMoving.blockID || tempid == Block.waterStill.blockID) { return 1f; //don't want water in the middle of ponds changing } return this.heights[((int)(world.getWorldTime() % 8L) + posx) % 8]; } } diff --git a/src/add.java b/src/add.java index cf6e384..7faaad0 100644 --- a/src/add.java +++ b/src/add.java @@ -1,80 +1,80 @@ import java.util.Random; /* Classes Used: yy - Block add - BlockStationary agw - BlockFluid p - Material aav - MapColor */ public class add extends agw // extends yy { - private p matinstance; + private p matInstance; protected add(int paramInt, p/*Material*/ paramp) { super(paramInt, paramp); matInstance = new p(aav.b); b(true);//setTickOnLoad //if (paramp == matInstance.h) //{ // if lava // b(true);//setTickOnLoad //} } public void a(ry world, int paramInt1, int paramInt2, int paramInt3, int paramInt4) { // onNeighborBlockChange super.a(world, paramInt1, paramInt2, paramInt3, paramInt4); if (world.a(paramInt1, paramInt2, paramInt3) == this.bM/*blockID*/) j(world, paramInt1, paramInt2, paramInt3); } private void j(ry world, int paramInt1, int paramInt2, int paramInt3) { // makeFlowing int i = world.d(paramInt1, paramInt2, paramInt3); world.t = true; world.b(paramInt1, paramInt2, paramInt3, this.bM - 1 /*block id - 1*/, i); world.c(paramInt1, paramInt2, paramInt3, paramInt1, paramInt2, paramInt3); world.a(paramInt1, paramInt2, paramInt3, this.bM - 1, d()/*Block.tickRate*/); world.t = false; } public void a(ry world, int posx, int paramInt2, int paramInt3, Random paramRandom) { // updateTick if (this.bZ == matInstance.h) { // if lava int i = paramRandom.nextInt(3); for (int j = 0; j < i; j++) { posx += paramRandom.nextInt(3) - 1; paramInt2++; paramInt3 += paramRandom.nextInt(3) - 1; int k = world.a(posx, paramInt2, paramInt3); if (k == 0) { if ((!k(world, posx - 1, paramInt2, paramInt3)) && (!k(world, posx + 1, paramInt2, paramInt3)) && (!k(world, posx, paramInt2, paramInt3 - 1)) && (!k(world, posx, paramInt2, paramInt3 + 1)) && (!k(world, posx, paramInt2 - 1, paramInt3)) && (!k(world, posx, paramInt2 + 1, paramInt3)) ) continue; world.g(posx, paramInt2, paramInt3, yy.ar.bM); return; } if (yy.k[k].bZ.d()) return; } } else { - a(0f,0f,0f,0f,mod_oceanwaves.getheight(world, posx, paramInt2, paramInt3, paramRandom), 0f); + a(0f,0f,0f,0f,mod_oceanwaves.getHeight(world, posx, paramInt2, paramInt3, paramRandom), 0f); //scheduleUpdate(); } } private boolean k(ry world, int paramInt1, int paramInt2, int paramInt3) { return world.e(paramInt1, paramInt2, paramInt3).g(); } } diff --git a/src/mod_oceanwaves.java b/src/mod_oceanwaves.java index 08f02cd..3e61823 100644 --- a/src/mod_oceanwaves.java +++ b/src/mod_oceanwaves.java @@ -1,28 +1,29 @@ import java.util.Random; /* Classes used: ry - World yy - Block */ public class mod_oceanwaves extends BaseMod { public String getVersion() { return "Minecraft 1.0.0 mod v0.2"; } private float[] heights = {0.2f,0.3f,0.5f,0.8f,1.0f,1.1f,0.9f,0.3f}; public void load() { // this is the BaseMod method to put all your shit in, like how mod_whatever() used to be. } - public float getHeight(ry world, int posx, int posy, int posz, Random rand) { + public float getHeight(ry world, int posx, int posy, int posz, Random rand) + { int tempid = world.a(posx,posy+1,posz); if(tempid == yy.A.bM || tempid == yy.B.bM) { return 1f; //don't want water in the middle of ponds changing } return heights[((int)(world.u() % 8)+posx) % 8]; } }
false
false
null
null
diff --git a/signserver/src/java/org/signserver/module/mrtdsodsigner/MRTDSODSigner.java b/signserver/src/java/org/signserver/module/mrtdsodsigner/MRTDSODSigner.java index abdfbb0ec..1969aa4c7 100644 --- a/signserver/src/java/org/signserver/module/mrtdsodsigner/MRTDSODSigner.java +++ b/signserver/src/java/org/signserver/module/mrtdsodsigner/MRTDSODSigner.java @@ -1,163 +1,163 @@ /************************************************************************* * * * SignServer: The OpenSource Automated Signing Server * * * * This software is free software; you can redistribute it and/or * * modify it under the terms of the GNU Lesser General Public * * License as published by the Free Software Foundation; either * * version 2.1 of the License, or any later version. * * * * See terms of license at gnu.org. * * * *************************************************************************/ package org.signserver.module.mrtdsodsigner; import java.security.GeneralSecurityException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.HashMap; import java.util.Map; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.ejbca.util.CertTools; import org.jmrtd.SODFile; import org.signserver.common.ArchiveData; import org.signserver.common.CryptoTokenOfflineException; import org.signserver.common.ISignRequest; import org.signserver.common.IllegalRequestException; import org.signserver.common.ProcessRequest; import org.signserver.common.ProcessResponse; import org.signserver.common.RequestContext; import org.signserver.common.SODSignRequest; import org.signserver.common.SODSignResponse; import org.signserver.common.SignServerException; import org.signserver.server.cryptotokens.ICryptoToken; import org.signserver.server.signers.BaseSigner; /** * A Signer signing creating a signed SOD file to be stored in ePassports. * * Properties: * <ul> * <li>DIGESTALGORITHM = Message digest algorithm applied to the datagroups. (Optional)</li> * <li>SIGNATUREALGORITHM = Signature algorithm for signing the SO(d), should match * the digest algorithm. (Optional)</li> * </ul> * * @author Markus Kilas * @version $Id$ */ public class MRTDSODSigner extends BaseSigner { private static final Logger log = Logger.getLogger(MRTDSODSigner.class); /** The digest algorithm, for example SHA1, SHA256. Defaults to SHA256. */ private static final String PROPERTY_DIGESTALGORITHM = "DIGESTALGORITHM"; /** Default value for the digestAlgorithm property */ private static final String DEFAULT_DIGESTALGORITHM = "SHA256"; /** The signature algorithm, for example SHA1withRSA, SHA256withRSA, SHA256withECDSA. Defaults to SHA256withRSA. */ private static final String PROPERTY_SIGNATUREALGORITHM = "SIGNATUREALGORITHM"; /** Default value for the signature algorithm property */ private static final String DEFAULT_SIGNATUREALGORITHM = "SHA256withRSA"; /** Determines if the the data group values should be hashed by the signer. If false we assume they are already hashed. */ private static final String PROPERTY_DODATAGROUPHASHING = "DODATAGROUPHASHING"; /** Default value if the data group values should be hashed by the signer. */ private static final String DEFAULT_DODATAGROUPHASHING = "false"; public ProcessResponse processData(ProcessRequest signRequest, RequestContext requestContext) throws IllegalRequestException, CryptoTokenOfflineException, SignServerException { if (log.isTraceEnabled()) { log.trace(">processData"); } ProcessResponse ret = null; ISignRequest sReq = (ISignRequest) signRequest; // Check that the request contains a valid SODSignRequest object. if (!(signRequest instanceof SODSignRequest)) { throw new IllegalRequestException("Recieved request wasn't an expected SODSignRequest."); } SODSignRequest sodRequest = (SODSignRequest) signRequest; // Construct SOD SODFile sod; X509Certificate cert = (X509Certificate) getSigningCertificate(); ICryptoToken token = getCryptoToken(); PrivateKey privKey = token.getPrivateKey(ICryptoToken.PURPOSE_SIGN); String provider = token.getProvider(ICryptoToken.PURPOSE_SIGN); if (log.isDebugEnabled()) { log.debug("Using signer certificate with subjectDN '"+CertTools.getSubjectDN(cert)+"', issuerDN '"+CertTools.getIssuerDN(cert)+", serNo "+CertTools.getSerialNumberAsString(cert)); } try { // Create the SODFile using the data group hashes that was sent to us in the request. String digestAlgorithm = config.getProperty(PROPERTY_DIGESTALGORITHM, DEFAULT_DIGESTALGORITHM); String digestEncryptionAlgorithm = config.getProperty(PROPERTY_SIGNATUREALGORITHM, DEFAULT_SIGNATUREALGORITHM); if (log.isDebugEnabled()) { log.debug("Using algorithms "+digestAlgorithm+", "+digestEncryptionAlgorithm); } String doHashing = config.getProperty(PROPERTY_DODATAGROUPHASHING, DEFAULT_DODATAGROUPHASHING); Map<Integer, byte[]> dgvalues = sodRequest.getDataGroupHashes(); Map<Integer, byte[]> dghashes = dgvalues; if (StringUtils.equalsIgnoreCase(doHashing, "true")) { if (log.isDebugEnabled()) { log.debug("Converting data group values to hashes using algorithm "+digestAlgorithm); } // If true here the "data group hashes" are not really hashes but values that we must hash. // The input is already decoded (if needed) and nice, so we just need to hash it dghashes = new HashMap<Integer, byte[]>(16); for (Integer dgId : dgvalues.keySet()) { byte[] value = dgvalues.get(dgId); if (log.isDebugEnabled()) { log.debug("Hashing data group "+dgId+", value is of length: "+value.length); } if ( (value != null) && (value.length > 0) ) { - MessageDigest digest = MessageDigest.getInstance("SHA1"); + MessageDigest digest = MessageDigest.getInstance(digestAlgorithm); byte[] result = digest.digest(value); if (log.isDebugEnabled()) { log.debug("Resulting hash is of length: "+result.length); } dghashes.put(dgId, result); } } } sod = new SODFile(digestAlgorithm, digestEncryptionAlgorithm, dghashes, privKey, cert, provider); } catch (NoSuchAlgorithmException ex) { throw new SignServerException("Problem constructing SOD", ex); } catch (CertificateException ex) { throw new SignServerException("Problem constructing SOD", ex); } // Verify the Signature before returning try { boolean verify = sod.checkDocSignature(cert); if (!verify) { log.error("Failed to verify the SOD we signed ourselves."); log.error("Cert: "+cert); log.error("SOD: "+sod); throw new SignServerException("Failed to verify the SOD we signed ourselves."); } else { log.debug("SOD verified correctly, returning SOD."); // Return response byte[] signedbytes = sod.getEncoded(); String fp = CertTools.getFingerprintAsString(signedbytes); ret = new SODSignResponse(sReq.getRequestID(), signedbytes, cert, fp, new ArchiveData(signedbytes)); } } catch (GeneralSecurityException e) { log.error("Error verifying the SOD we signed ourselves. ", e); } if (log.isTraceEnabled()) { log.trace("<processData"); } return ret; } }
true
true
public ProcessResponse processData(ProcessRequest signRequest, RequestContext requestContext) throws IllegalRequestException, CryptoTokenOfflineException, SignServerException { if (log.isTraceEnabled()) { log.trace(">processData"); } ProcessResponse ret = null; ISignRequest sReq = (ISignRequest) signRequest; // Check that the request contains a valid SODSignRequest object. if (!(signRequest instanceof SODSignRequest)) { throw new IllegalRequestException("Recieved request wasn't an expected SODSignRequest."); } SODSignRequest sodRequest = (SODSignRequest) signRequest; // Construct SOD SODFile sod; X509Certificate cert = (X509Certificate) getSigningCertificate(); ICryptoToken token = getCryptoToken(); PrivateKey privKey = token.getPrivateKey(ICryptoToken.PURPOSE_SIGN); String provider = token.getProvider(ICryptoToken.PURPOSE_SIGN); if (log.isDebugEnabled()) { log.debug("Using signer certificate with subjectDN '"+CertTools.getSubjectDN(cert)+"', issuerDN '"+CertTools.getIssuerDN(cert)+", serNo "+CertTools.getSerialNumberAsString(cert)); } try { // Create the SODFile using the data group hashes that was sent to us in the request. String digestAlgorithm = config.getProperty(PROPERTY_DIGESTALGORITHM, DEFAULT_DIGESTALGORITHM); String digestEncryptionAlgorithm = config.getProperty(PROPERTY_SIGNATUREALGORITHM, DEFAULT_SIGNATUREALGORITHM); if (log.isDebugEnabled()) { log.debug("Using algorithms "+digestAlgorithm+", "+digestEncryptionAlgorithm); } String doHashing = config.getProperty(PROPERTY_DODATAGROUPHASHING, DEFAULT_DODATAGROUPHASHING); Map<Integer, byte[]> dgvalues = sodRequest.getDataGroupHashes(); Map<Integer, byte[]> dghashes = dgvalues; if (StringUtils.equalsIgnoreCase(doHashing, "true")) { if (log.isDebugEnabled()) { log.debug("Converting data group values to hashes using algorithm "+digestAlgorithm); } // If true here the "data group hashes" are not really hashes but values that we must hash. // The input is already decoded (if needed) and nice, so we just need to hash it dghashes = new HashMap<Integer, byte[]>(16); for (Integer dgId : dgvalues.keySet()) { byte[] value = dgvalues.get(dgId); if (log.isDebugEnabled()) { log.debug("Hashing data group "+dgId+", value is of length: "+value.length); } if ( (value != null) && (value.length > 0) ) { MessageDigest digest = MessageDigest.getInstance("SHA1"); byte[] result = digest.digest(value); if (log.isDebugEnabled()) { log.debug("Resulting hash is of length: "+result.length); } dghashes.put(dgId, result); } } } sod = new SODFile(digestAlgorithm, digestEncryptionAlgorithm, dghashes, privKey, cert, provider); } catch (NoSuchAlgorithmException ex) { throw new SignServerException("Problem constructing SOD", ex); } catch (CertificateException ex) { throw new SignServerException("Problem constructing SOD", ex); } // Verify the Signature before returning try { boolean verify = sod.checkDocSignature(cert); if (!verify) { log.error("Failed to verify the SOD we signed ourselves."); log.error("Cert: "+cert); log.error("SOD: "+sod); throw new SignServerException("Failed to verify the SOD we signed ourselves."); } else { log.debug("SOD verified correctly, returning SOD."); // Return response byte[] signedbytes = sod.getEncoded(); String fp = CertTools.getFingerprintAsString(signedbytes); ret = new SODSignResponse(sReq.getRequestID(), signedbytes, cert, fp, new ArchiveData(signedbytes)); } } catch (GeneralSecurityException e) { log.error("Error verifying the SOD we signed ourselves. ", e); } if (log.isTraceEnabled()) { log.trace("<processData"); } return ret; }
public ProcessResponse processData(ProcessRequest signRequest, RequestContext requestContext) throws IllegalRequestException, CryptoTokenOfflineException, SignServerException { if (log.isTraceEnabled()) { log.trace(">processData"); } ProcessResponse ret = null; ISignRequest sReq = (ISignRequest) signRequest; // Check that the request contains a valid SODSignRequest object. if (!(signRequest instanceof SODSignRequest)) { throw new IllegalRequestException("Recieved request wasn't an expected SODSignRequest."); } SODSignRequest sodRequest = (SODSignRequest) signRequest; // Construct SOD SODFile sod; X509Certificate cert = (X509Certificate) getSigningCertificate(); ICryptoToken token = getCryptoToken(); PrivateKey privKey = token.getPrivateKey(ICryptoToken.PURPOSE_SIGN); String provider = token.getProvider(ICryptoToken.PURPOSE_SIGN); if (log.isDebugEnabled()) { log.debug("Using signer certificate with subjectDN '"+CertTools.getSubjectDN(cert)+"', issuerDN '"+CertTools.getIssuerDN(cert)+", serNo "+CertTools.getSerialNumberAsString(cert)); } try { // Create the SODFile using the data group hashes that was sent to us in the request. String digestAlgorithm = config.getProperty(PROPERTY_DIGESTALGORITHM, DEFAULT_DIGESTALGORITHM); String digestEncryptionAlgorithm = config.getProperty(PROPERTY_SIGNATUREALGORITHM, DEFAULT_SIGNATUREALGORITHM); if (log.isDebugEnabled()) { log.debug("Using algorithms "+digestAlgorithm+", "+digestEncryptionAlgorithm); } String doHashing = config.getProperty(PROPERTY_DODATAGROUPHASHING, DEFAULT_DODATAGROUPHASHING); Map<Integer, byte[]> dgvalues = sodRequest.getDataGroupHashes(); Map<Integer, byte[]> dghashes = dgvalues; if (StringUtils.equalsIgnoreCase(doHashing, "true")) { if (log.isDebugEnabled()) { log.debug("Converting data group values to hashes using algorithm "+digestAlgorithm); } // If true here the "data group hashes" are not really hashes but values that we must hash. // The input is already decoded (if needed) and nice, so we just need to hash it dghashes = new HashMap<Integer, byte[]>(16); for (Integer dgId : dgvalues.keySet()) { byte[] value = dgvalues.get(dgId); if (log.isDebugEnabled()) { log.debug("Hashing data group "+dgId+", value is of length: "+value.length); } if ( (value != null) && (value.length > 0) ) { MessageDigest digest = MessageDigest.getInstance(digestAlgorithm); byte[] result = digest.digest(value); if (log.isDebugEnabled()) { log.debug("Resulting hash is of length: "+result.length); } dghashes.put(dgId, result); } } } sod = new SODFile(digestAlgorithm, digestEncryptionAlgorithm, dghashes, privKey, cert, provider); } catch (NoSuchAlgorithmException ex) { throw new SignServerException("Problem constructing SOD", ex); } catch (CertificateException ex) { throw new SignServerException("Problem constructing SOD", ex); } // Verify the Signature before returning try { boolean verify = sod.checkDocSignature(cert); if (!verify) { log.error("Failed to verify the SOD we signed ourselves."); log.error("Cert: "+cert); log.error("SOD: "+sod); throw new SignServerException("Failed to verify the SOD we signed ourselves."); } else { log.debug("SOD verified correctly, returning SOD."); // Return response byte[] signedbytes = sod.getEncoded(); String fp = CertTools.getFingerprintAsString(signedbytes); ret = new SODSignResponse(sReq.getRequestID(), signedbytes, cert, fp, new ArchiveData(signedbytes)); } } catch (GeneralSecurityException e) { log.error("Error verifying the SOD we signed ourselves. ", e); } if (log.isTraceEnabled()) { log.trace("<processData"); } return ret; }
diff --git a/sphinx4/edu/cmu/sphinx/decoder/search/WordPruningBreadthFirstSearchManager.java b/sphinx4/edu/cmu/sphinx/decoder/search/WordPruningBreadthFirstSearchManager.java index ad6a44f54..c7aa44f9e 100644 --- a/sphinx4/edu/cmu/sphinx/decoder/search/WordPruningBreadthFirstSearchManager.java +++ b/sphinx4/edu/cmu/sphinx/decoder/search/WordPruningBreadthFirstSearchManager.java @@ -1,624 +1,625 @@ /* * Copyright 1999-2002 Carnegie Mellon University. * Portions Copyright 2002 Sun Microsystems, Inc. * Portions Copyright 2002 Mitsubishi Electronic Research Laboratories. * All Rights Reserved. Use is subject to license terms. * * See the file "license.terms" for information on usage and * redistribution of this file, and for a DISCLAIMER OF ALL * WARRANTIES. * */ package edu.cmu.sphinx.decoder.search; // a test search manager. import edu.cmu.sphinx.result.Result; import edu.cmu.sphinx.result.Lattice; import edu.cmu.sphinx.result.LatticeOptimizer; import edu.cmu.sphinx.util.LogMath; import edu.cmu.sphinx.util.SphinxProperties; import edu.cmu.sphinx.util.StatisticsVariable; import edu.cmu.sphinx.util.Timer; import edu.cmu.sphinx.decoder.search.Pruner; import edu.cmu.sphinx.decoder.search.SearchManager; import edu.cmu.sphinx.decoder.search.Token; import edu.cmu.sphinx.decoder.search.ActiveList; import edu.cmu.sphinx.decoder.scorer.AcousticScorer; import edu.cmu.sphinx.decoder.linguist.Linguist; import edu.cmu.sphinx.decoder.linguist.SearchState; import edu.cmu.sphinx.decoder.linguist.SearchStateArc; import edu.cmu.sphinx.decoder.linguist.WordSearchState; import edu.cmu.sphinx.decoder.linguist.lextree.LexTreeLinguist; import java.util.*; /** * Provides the breadth first search. To perform recognition * an application should call initialize before * recognition begins, and repeatedly call <code> recognize </code> * until Result.isFinal() returns true. Once a final result has been * obtained, <code> terminate </code> should be called. * * All scores and probabilities are maintained in the log math log * domain. */ public class WordPruningBreadthFirstSearchManager implements SearchManager { private final static String PROP_PREFIX = "edu.cmu.sphinx.decoder.search.BreadthFirstSearchManager."; /** * Sphinx property that defines the type of active list to use */ public final static String PROP_ACTIVE_LIST_TYPE = PROP_PREFIX + "activeListType"; /** * The default value for the PROP_ACTIVE_LIST_TYPE property */ public final static String PROP_ACTIVE_LIST_TYPE_DEFAULT = "edu.cmu.sphinx.decoder.search.SimpleActiveList"; /** * A sphinx property than, when set to <code>true</code> will * cause the recognizer to count up all the tokens in the active * list after every frame. */ public final static String PROP_SHOW_TOKEN_COUNT = PROP_PREFIX + "showTokenCount"; /** * The default value for the PROP_SHOW_TOKEN_COUNT property */ public final static boolean PROP_SHOW_TOKEN_COUNT_DEFAULT = false; private Linguist linguist; // Provides grammar/language info private Pruner pruner; // used to prune the active list private AcousticScorer scorer; // used to score the active list private int currentFrameNumber; // the current frame number private ActiveList activeList; // the list of active tokens private ActiveListManager activeBucket; private List resultList; // the current set of results private SphinxProperties props; // the sphinx properties private LogMath logMath; private Timer scoreTimer; private Timer pruneTimer; private Timer growTimer; private StatisticsVariable totalTokensScored; private StatisticsVariable curTokensScored; private StatisticsVariable tokensCreated; private boolean showTokenCount; private Map bestTokenMap; private AlternateHypothesisManager loserManager; private Class[] stateOrder; /** * Initializes this BreadthFirstSearchManager with the given * context, linguist, scorer and pruner. * * @param context the context to use * @param linguist the Linguist to use * @param scorer the AcousticScorer to use * @param pruner the Pruner to use */ public void initialize(String context, Linguist linguist, AcousticScorer scorer, Pruner pruner) { this.linguist = linguist; this.scorer = scorer; this.pruner = pruner; this.props = SphinxProperties.getSphinxProperties(context); this.logMath = LogMath.getLogMath(context); scoreTimer = Timer.getTimer(context, "Score"); pruneTimer = Timer.getTimer(context, "Prune"); growTimer = Timer.getTimer(context, "Grow"); totalTokensScored = StatisticsVariable.getStatisticsVariable( props.getContext(), "totalTokensScored"); curTokensScored = StatisticsVariable.getStatisticsVariable( props.getContext(), "curTokensScored"); tokensCreated = StatisticsVariable.getStatisticsVariable(props.getContext(), "tokensCreated"); showTokenCount = props.getBoolean(PROP_SHOW_TOKEN_COUNT, false); } /** * Called at the start of recognition. Gets the search manager * ready to recognize */ public void start() { linguist.start(); pruner.start(); scorer.start(); localStart(); } /** * Performs the recognition for the given number of frames. * * @param nFrames the number of frames to recognize * * @return the current result */ public Result recognize(int nFrames) { boolean done = false; Result result; resultList = new LinkedList(); for (int i = 0; i < nFrames && !done; i++) { // System.out.println("Frame " + currentFrameNumber); // score the emitting list activeList = activeBucket.getEmittingList(); if (activeList != null) { done = !scoreTokens(); if (!done) { bestTokenMap = new HashMap(activeList.size() * 5); // prune and grow the emitting list pruneBranches(); currentFrameNumber++; growBranches(); // prune and grow the non-emitting lists growNonEmittingLists(); } } } result = new Result(loserManager, activeList, resultList, currentFrameNumber, done); if (showTokenCount) { showTokenCount(); } return result; } /** * Terminates a recognition */ public void stop() { localStop(); scorer.stop(); pruner.stop(); linguist.stop(); } /** * Gets the initial grammar node from the linguist and * creates a GrammarNodeToken */ protected void localStart() { currentFrameNumber = 0; curTokensScored.value = 0; try { stateOrder = linguist.getSearchStateOrder(); activeBucket = new SimpleActiveListManager(props, stateOrder); loserManager = new AlternateHypothesisManager(props); SearchState state = linguist.getInitialSearchState(); activeList = (ActiveList) Class.forName (props.getString(PROP_ACTIVE_LIST_TYPE, PROP_ACTIVE_LIST_TYPE_DEFAULT)).newInstance(); activeList.setProperties(props); activeList.add(new Token(state, currentFrameNumber)); resultList = new LinkedList(); bestTokenMap = new HashMap(); growBranches(); growNonEmittingLists(); } catch (ClassNotFoundException fe) { throw new Error("Can't create active list", fe); } catch (InstantiationException ie) { throw new Error("Can't create active list", ie); } catch (IllegalAccessException iea) { throw new Error("Can't create active list", iea); } } /** * Local cleanup for this search manager */ protected void localStop() { } /** * Goes through the active list of tokens and expands each * token, finding the set of successor tokens until all the successor * tokens are emitting tokens. * */ protected void growBranches() { growTimer.start(); Iterator iterator = activeList.iterator(); while (iterator.hasNext()) { Token token = (Token) iterator.next(); if (activeList.isWorthGrowing(token)) { collectSuccessorTokens(token); } } growTimer.stop(); } /** * Grow the non-emitting ActiveLists, until the tokens reach * an emitting state. */ private void growNonEmittingLists() { for (Iterator i = activeBucket.getNonEmittingListIterator(); i.hasNext(); ) { activeList = (ActiveList) i.next(); if (activeList != null) { i.remove(); pruneBranches(); growBranches(); } } } /** * Calculate the acoustic scores for the active list. The active * list should contain only emitting tokens. * * @return <code>true</code> if there are more frames to score, * otherwise, false * */ protected boolean scoreTokens() { boolean moreTokens; scoreTimer.start(); moreTokens = scorer.calculateScores(activeList.getTokens()); scoreTimer.stop(); curTokensScored.value += activeList.size(); totalTokensScored.value += activeList.size(); return moreTokens; } /** * Removes unpromising branches from the active list * */ protected void pruneBranches() { pruneTimer.start(); activeList = pruner.prune(activeList); pruneTimer.stop(); } /** * Gets the best token for this state * * @param state the state of interest * * @return the best token */ protected Token getBestToken(SearchState state) { return (Token) bestTokenMap.get(state); } /** * Sets the best token for a given state * * @param token the best token * * @param state the state * * @return the previous best token for the given state, or null if * no previous best token */ protected Token setBestToken(Token token, SearchState state) { return (Token) bestTokenMap.put(state, token); } protected Token getWordPredecessor(Token token) { while (token != null && !token.isWord()) { token = token.getPredecessor(); } return token; } /** * Checks that the given two states are in legitimate order. */ private void checkStateOrder(SearchState fromState, SearchState toState) { Class fromClass = fromState.getClass(); Class toClass = toState.getClass(); // first, find where in stateOrder is the fromState int i = 0; for (; i < stateOrder.length; i++) { if (stateOrder[i] == fromClass) { break; } } // We are assuming that the last state in the state order // is an emitting state. We assume that emitting states can // expand to any state type. So if (i == (stateOrder.length)), // which means that fromState is an emitting state, we don't // do any checks. if (i < (stateOrder.length - 1)) { for (int j = 0; j <= i; j++) { if (stateOrder[j] == toClass) { throw new Error("IllegalState order: from " + - fromState + " to " + toState); + fromState.toPrettyString() + " to " + + toState.toPrettyString()); } } } } /** * Collects the next set of emitting tokens from a token * and accumulates them in the active or result lists * * @param token the token to collect successors from * be immediately expaned are placed. Null if we should always * expand all nodes. */ protected void collectSuccessorTokens(Token token) { // If this is a final state, add it to the final list if (token.isFinal()) { resultList.add(getWordPredecessor(token)); return; } SearchState state = token.getSearchState(); SearchStateArc[] arcs = state.getSuccessors(); // For each successor // calculate the entry score for the token based upon the // predecessor token score and the transition probabilities // if the score is better than the best score encountered for // the SearchState and frame then create a new token, add // it to the lattice and the SearchState. // If the token is an emitting token add it to the list, // othewise recursively collect the new tokens successors. for (int i = 0; i < arcs.length; i++) { SearchStateArc arc = arcs[i]; SearchState nextState = arc.getState(); checkStateOrder(state, nextState); // We're actually multiplying the variables, but since // these come in log(), multiply gets converted to add float logEntryScore = token.getScore() + arc.getProbability(); Token bestToken = getBestToken(nextState); boolean firstToken = bestToken == null ; if (firstToken || bestToken.getScore() < logEntryScore) { Token newBestToken = new Token(getWordPredecessor(token), nextState, logEntryScore, arc.getLanguageProbability(), arc.getInsertionProbability(), currentFrameNumber); tokensCreated.value++; setBestToken(newBestToken, nextState); if (firstToken) { activeBucket.add(newBestToken); } else { activeBucket.replace(bestToken, newBestToken); if (newBestToken.isWord()) { // Move predecessors of bestToken to precede newBestToken // bestToken is going to be garbage collected. loserManager.changeSuccessor(newBestToken,bestToken); loserManager.addAlternatePredecessor (newBestToken,bestToken.getPredecessor()); } } } else { if (nextState instanceof WordSearchState) { Token wordPredecessor = getWordPredecessor(token); if (wordPredecessor != null) { loserManager.addAlternatePredecessor (bestToken, wordPredecessor); } } } } } /** * Counts all the tokens in the active list (and displays them). * This is an expensive operation. */ private void showTokenCount() { Set tokenSet = new HashSet(); for (Iterator i = activeList.iterator(); i.hasNext(); ) { Token token = (Token) i.next(); while (token != null) { tokenSet.add(token); token = token.getPredecessor(); } } System.out.println("Token Lattice size: " + tokenSet.size()); tokenSet = new HashSet(); for (Iterator i = resultList.iterator(); i.hasNext(); ) { Token token = (Token) i.next(); while (token != null) { tokenSet.add(token); token = token.getPredecessor(); } } System.out.println("Result Lattice size: " + tokenSet.size()); } /** * Returns the Linguist. * * @return the Linguist */ public Linguist getLinguist() { return linguist; } /** * Returns the Pruner. * * @return the Pruner */ public Pruner getPruner() { return pruner; } /** * Returns the AcousticScorer. * * @return the AcousticScorer */ public AcousticScorer getAcousticScorer() { return scorer; } /** * Returns the LogMath used. * * @return the LogMath used */ public LogMath getLogMath() { return logMath; } /** * Returns the SphinxProperties used. * * @return the SphinxProperties used */ public SphinxProperties getSphinxProperties() { return props; } /** * Returns the best token map. * * @return the best token map */ protected Map getBestTokenMap() { return bestTokenMap; } /** * Sets the best token Map. * * @param bestTokenMap the new best token Map */ protected void setBestTokenMap(Map bestTokenMap) { this.bestTokenMap = bestTokenMap; } /** * Returns the ActiveList. * * @return the ActiveList */ public ActiveList getActiveList() { return activeList; } /** * Sets the ActiveList. * * @param activeList the new ActiveList */ public void setActiveList(ActiveList activeList) { this.activeList = activeList; } /** * Returns the result list. * * @return the result list */ public List getResultList() { return resultList; } /** * Sets the result list. * * @param resultList the new result list */ public void setResultList(List resultList) { this.resultList = resultList; } /** * Returns the current frame number. * * @return the current frame number */ public int getCurrentFrameNumber() { return currentFrameNumber; } /** * Returns the Timer for growing. * * @return the Timer for growing */ public Timer getGrowTimer() { return growTimer; } /** * Returns the tokensCreated StatisticsVariable. * * @return the tokensCreated StatisticsVariable. */ public StatisticsVariable getTokensCreated() { return tokensCreated; } }
true
false
null
null
diff --git a/api/src/test/java/org/openmrs/api/ConceptServiceTest.java b/api/src/test/java/org/openmrs/api/ConceptServiceTest.java index 0284ae27..4f8f4f94 100644 --- a/api/src/test/java/org/openmrs/api/ConceptServiceTest.java +++ b/api/src/test/java/org/openmrs/api/ConceptServiceTest.java @@ -1,1671 +1,1671 @@ /** * The contents of this file are subject to the OpenMRS Public License * Version 1.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://license.openmrs.org * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the * License for the specific language governing rights and limitations * under the License. * * Copyright (C) OpenMRS, LLC. All Rights Reserved. */ package org.openmrs.api; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Set; import junit.framework.Assert; import org.apache.commons.collections.CollectionUtils; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.openmrs.Concept; import org.openmrs.ConceptAnswer; import org.openmrs.ConceptClass; import org.openmrs.ConceptComplex; import org.openmrs.ConceptDatatype; import org.openmrs.ConceptDescription; import org.openmrs.ConceptMap; import org.openmrs.ConceptName; import org.openmrs.ConceptNameTag; import org.openmrs.ConceptNumeric; import org.openmrs.ConceptProposal; import org.openmrs.ConceptSearchResult; import org.openmrs.ConceptSet; import org.openmrs.ConceptSource; import org.openmrs.ConceptStopWord; import org.openmrs.Drug; import org.openmrs.Encounter; import org.openmrs.GlobalProperty; import org.openmrs.Location; import org.openmrs.Obs; import org.openmrs.Patient; import org.openmrs.Person; import org.openmrs.User; import org.openmrs.api.context.Context; import org.openmrs.test.BaseContextSensitiveTest; import org.openmrs.test.SkipBaseSetup; import org.openmrs.test.Verifies; import org.openmrs.util.LocaleUtility; import org.openmrs.util.OpenmrsConstants; import org.springframework.test.annotation.ExpectedException; /** * This test class (should) contain tests for all of the ConcepService methods TODO clean up and * finish this test class * * @see org.openmrs.api.ConceptService */ public class ConceptServiceTest extends BaseContextSensitiveTest { protected ConceptService conceptService = null; protected static final String INITIAL_CONCEPTS_XML = "org/openmrs/api/include/ConceptServiceTest-initialConcepts.xml"; protected static final String GET_CONCEPTS_BY_SET_XML = "org/openmrs/api/include/ConceptServiceTest-getConceptsBySet.xml"; /** * Run this before each unit test in this class. The "@Before" method in * {@link BaseContextSensitiveTest} is run right before this method. * * @throws Exception */ @Before public void runBeforeAllTests() throws Exception { conceptService = Context.getConceptService(); } /** * Test getting a concept by name and by partial name. * * @see {@link ConceptService#getConceptByName(String)} */ @Test @Verifies(value = "should get concept by name", method = "getConceptByName(String)") public void getConceptByName_shouldGetConceptByName() throws Exception { String nameToFetch = "Some non numeric concept name"; executeDataSet(INITIAL_CONCEPTS_XML); Concept conceptByName = conceptService.getConceptByName(nameToFetch); assertEquals("Unable to fetch concept by name", conceptByName, new Concept(1)); } /** * @see {@link ConceptService#getConceptByName(String)} */ @Test @Verifies(value = "should get concept by partial name", method = "getConceptByName(String)") public void getConceptByName_shouldGetConceptByPartialName() throws Exception { executeDataSet(INITIAL_CONCEPTS_XML); // substring of the name String partialNameToFetch = "So"; List<Concept> firstConceptsByPartialNameList = conceptService.getConceptsByName(partialNameToFetch); assertTrue("You should be able to get the concept by partial name", firstConceptsByPartialNameList .contains(new Concept(1))); } /** * @see {@link ConceptService#saveConcept(Concept)} */ @Test @SkipBaseSetup @Verifies(value = "should save a ConceptNumeric as a concept", method = "saveConcept(Concept)") public void saveConcept_shouldSaveAConceptNumericAsAConcept() throws Exception { initializeInMemoryDatabase(); executeDataSet(INITIAL_CONCEPTS_XML); authenticate(); //This will automatically add the given locale to the list of allowed locales Context.setLocale(Locale.US); // this tests saving a previously conceptnumeric as just a concept Concept c2 = new Concept(2); ConceptName cn = new ConceptName("not a numeric anymore", Locale.US); c2.addName(cn); c2.setDatatype(new ConceptDatatype(3)); conceptService.saveConcept(c2); Concept secondConcept = conceptService.getConcept(2); // this will probably still be a ConceptNumeric object. what to do about that? // revisit this problem when discriminators are in place //assertFalse(secondConcept instanceof ConceptNumeric); // this shouldn't think its a conceptnumeric object though assertFalse(secondConcept.isNumeric()); assertEquals("not a numeric anymore", secondConcept.getName(Locale.US).getName()); } /** * @see {@link ConceptService#saveConcept(Concept)} */ @Test @SkipBaseSetup @Verifies(value = "should save a new ConceptNumeric", method = "saveConcept(Concept)") public void saveConcept_shouldSaveANewConceptNumeric() throws Exception { initializeInMemoryDatabase(); executeDataSet(INITIAL_CONCEPTS_XML); authenticate(); Context.setLocale(Locale.US); // this tests saving a never before in the database conceptnumeric ConceptNumeric cn3 = new ConceptNumeric(); cn3.setDatatype(new ConceptDatatype(1)); ConceptName cn = new ConceptName("a brand new conceptnumeric", Locale.US); cn3.addName(cn); cn3.setHiAbsolute(50.0); conceptService.saveConcept(cn3); Concept thirdConcept = conceptService.getConcept(cn3.getConceptId()); assertTrue(thirdConcept instanceof ConceptNumeric); ConceptNumeric thirdConceptNumeric = (ConceptNumeric) thirdConcept; assertEquals("a brand new conceptnumeric", thirdConceptNumeric.getName(Locale.US).getName()); assertEquals(50.0, thirdConceptNumeric.getHiAbsolute().doubleValue(), 0); } /** * @see {@link ConceptService#saveConcept(Concept)} */ @Test @SkipBaseSetup @Verifies(value = "should save non ConceptNumeric object as conceptNumeric", method = "saveConcept(Concept)") public void saveConcept_shouldSaveNonConceptNumericObjectAsConceptNumeric() throws Exception { initializeInMemoryDatabase(); executeDataSet(INITIAL_CONCEPTS_XML); authenticate(); // this tests saving a current concept as a newly changed conceptnumeric // assumes there is already a concept in the database // with a concept id of #1 ConceptNumeric cn = new ConceptNumeric(1); cn.setDatatype(new ConceptDatatype(1)); cn.addName(new ConceptName("a new conceptnumeric", Locale.US)); cn.setHiAbsolute(20.0); conceptService.saveConcept(cn); Concept firstConcept = conceptService.getConceptNumeric(1); assertEquals("a new conceptnumeric", firstConcept.getName(Locale.US).getName()); assertTrue(firstConcept instanceof ConceptNumeric); ConceptNumeric firstConceptNumeric = (ConceptNumeric) firstConcept; assertEquals(20.0, firstConceptNumeric.getHiAbsolute().doubleValue(), 0); } /** * @see {@link ConceptService#getConceptComplex(Integer)} */ @Test @Verifies(value = "should return a concept complex object", method = "getConceptComplex(Integer)") public void getConceptComplex_shouldReturnAConceptComplexObject() throws Exception { executeDataSet("org/openmrs/api/include/ObsServiceTest-complex.xml"); ConceptComplex concept = Context.getConceptService().getConceptComplex(8473); Assert.assertNotNull(concept); } /** * @see {@link ConceptService#saveConcept(Concept)} */ @Test @Verifies(value = "should generate id for new concept if none is specified", method = "saveConcept(Concept)") public void saveConcept_shouldGenerateIdForNewConceptIfNoneIsSpecified() throws Exception { Concept concept = new Concept(); ConceptName cn = new ConceptName("Weight", Context.getLocale()); concept.addName(cn); concept.setConceptId(null); concept.setDatatype(Context.getConceptService().getConceptDatatypeByName("Numeric")); concept.setConceptClass(Context.getConceptService().getConceptClassByName("Finding")); concept = Context.getConceptService().saveConcept(concept); assertFalse(concept.getConceptId().equals(5089)); } /** * @see {@link ConceptService#saveConcept(Concept)} */ @Test @Verifies(value = "should keep id for new concept if one is specified", method = "saveConcept(Concept)") public void saveConcept_shouldKeepIdForNewConceptIfOneIsSpecified() throws Exception { Integer conceptId = 343434; // a nonexistent concept id; Assert.assertNull(conceptService.getConcept(conceptId)); // sanity check Concept concept = new Concept(); ConceptName cn = new ConceptName("Weight", Context.getLocale()); concept.addName(cn); concept.setConceptId(conceptId); concept.setDatatype(Context.getConceptService().getConceptDatatypeByName("Numeric")); concept.setConceptClass(Context.getConceptService().getConceptClassByName("Finding")); concept = Context.getConceptService().saveConcept(concept); assertTrue(concept.getConceptId().equals(conceptId)); } /** * @see {@link ConceptService#conceptIterator()} */ @Test @Verifies(value = "should iterate over all concepts", method = "conceptIterator()") public void conceptIterator_shouldIterateOverAllConcepts() throws Exception { Iterator<Concept> iterator = Context.getConceptService().conceptIterator(); Assert.assertTrue(iterator.hasNext()); Assert.assertEquals(3, iterator.next().getConceptId().intValue()); } /** * This test will fail if it takes more than 15 seconds to run. (Checks for an error with the * iterator looping forever) The @Timed annotation is used as an alternative to * "@Test(timeout=15000)" so that the Spring transactions work correctly. Junit has a "feature" * where it executes the befores/afters in a thread separate from the one that the actual test * ends up running in when timed. * * @see {@link ConceptService#conceptIterator()} */ @Test() @Verifies(value = "should start with the smallest concept id", method = "conceptIterator()") public void conceptIterator_shouldStartWithTheSmallestConceptId() throws Exception { List<Concept> allConcepts = Context.getConceptService().getAllConcepts(); int numberofconcepts = allConcepts.size(); // sanity check Assert.assertTrue(numberofconcepts > 0); // now count up the number of concepts the iterator returns int iteratorCount = 0; Iterator<Concept> iterator = Context.getConceptService().conceptIterator(); while (iterator.hasNext() && iteratorCount < numberofconcepts + 5) { // the lt check is in case of infinite loops iterator.next(); iteratorCount++; } Assert.assertEquals(numberofconcepts, iteratorCount); } /** * @see {@link ConceptService#saveConcept(Concept)} */ @Test @Verifies(value = "should reuse concept name tags that already exist in the database", method = "saveConcept(Concept)") public void saveConcept_shouldReuseConceptNameTagsThatAlreadyExistInTheDatabase() throws Exception { executeDataSet("org/openmrs/api/include/ConceptServiceTest-tags.xml"); ConceptService cs = Context.getConceptService(); // make sure the name tag exists already ConceptNameTag cnt = cs.getConceptNameTagByName("preferred_en"); Assert.assertNotNull(cnt); ConceptName cn = new ConceptName("Some name", Locale.ENGLISH); cn.addTag(new ConceptNameTag("preferred_en", "preferred name in a language")); Concept concept = new Concept(); concept.addName(cn); concept.setDatatype(new ConceptDatatype(1)); concept.setConceptClass(new ConceptClass(1)); cs.saveConcept(concept); Collection<ConceptNameTag> savedConceptNameTags = concept.getName(Locale.ENGLISH, false).getTags(); ConceptNameTag savedConceptNameTag = (ConceptNameTag) savedConceptNameTags.toArray()[0]; Assert.assertEquals(cnt.getConceptNameTagId(), savedConceptNameTag.getConceptNameTagId()); } /** * @see {@link ConceptService#saveConceptSource(ConceptSource)} */ @Test @Verifies(value = "should not set creator if one is supplied already", method = "saveConceptSource(ConceptSource)") public void saveConceptSource_shouldNotSetCreatorIfOneIsSuppliedAlready() throws Exception { User expectedCreator = new User(501); // a user that isn't logged in now ConceptSource newConceptSource = new ConceptSource(); newConceptSource.setName("name"); newConceptSource.setDescription("desc"); newConceptSource.setHl7Code("hl7Code"); newConceptSource.setCreator(expectedCreator); Context.getConceptService().saveConceptSource(newConceptSource); Assert.assertEquals(newConceptSource.getCreator(), expectedCreator); } /** * @see {@link ConceptService#saveConceptSource(ConceptSource)} */ @Test @Verifies(value = "should not set date created if one is supplied already", method = "saveConceptSource(ConceptSource)") public void saveConceptSource_shouldNotSetDateCreatedIfOneIsSuppliedAlready() throws Exception { Date expectedDate = new Date(new Date().getTime() - 10000); ConceptSource newConceptSource = new ConceptSource(); newConceptSource.setName("name"); newConceptSource.setDescription("desc"); newConceptSource.setHl7Code("hl7Code"); newConceptSource.setDateCreated(expectedDate); Context.getConceptService().saveConceptSource(newConceptSource); Assert.assertEquals(newConceptSource.getDateCreated(), expectedDate); } /** * @see {@link ConceptService#getConcept(String)} */ @Test @Verifies(value = "should return null given null parameter", method = "getConcept(String)") public void getConcept_shouldReturnNullGivenNullParameter() throws Exception { Assert.assertNull(Context.getConceptService().getConcept((String) null)); } /** * @see {@link ConceptService#getConceptByName(String)} */ @Test @Verifies(value = "should return null given null parameter", method = "getConceptByName(String)") public void getConceptByName_shouldReturnNullGivenNullParameter() throws Exception { Assert.assertNull(Context.getConceptService().getConceptByName(null)); } /** * This test verifies that {@link ConceptName}s are fetched correctly from the hibernate cache. * (Or really, not fetched from the cache but instead are mapped with lazy=false. For some * reason Hibernate isn't able to find objects in the cache if a parent object was the one that * loaded them) * * @throws Exception */ @Test public void shouldFetchNamesForConceptsThatWereFirstFetchedAsNumerics() throws Exception { Concept concept = Context.getConceptService().getConcept(5089); ConceptNumeric conceptNumeric = Context.getConceptService().getConceptNumeric(5089); conceptNumeric.getNames().size(); concept.getNames().size(); } /** * This test verifies that {@link ConceptDescription}s are fetched correctly from the hibernate * cache. (Or really, not fetched from the cache but instead are mapped with lazy=false. For * some reason Hibernate isn't able to find objects in the cache if a parent object was the one * that loaded them) * * @throws Exception */ @Test public void shouldFetchDescriptionsForConceptsThatWereFirstFetchedAsNumerics() throws Exception { Concept concept = Context.getConceptService().getConcept(5089); ConceptNumeric conceptNumeric = Context.getConceptService().getConceptNumeric(5089); conceptNumeric.getDescriptions().size(); concept.getDescriptions().size(); } /** * This test had to be added to ConceptServiceTest because ConceptTest does not currently * support context sensitive tests (and shouldn't need to). TODO This test case passes here, but * fails in the core reporting module. TODO: determine whether we want to remove this test case * * @see {@link Concept#equals(Object)} */ @Test @SkipBaseSetup @Verifies(value = "should return true when comparing two identical concept numeric objects", method = "equals(Object)") public void equals_shouldReturnTrueWhenComparingTwoIdenticalConceptNumericObjects() throws Exception { initializeInMemoryDatabase(); // TODO Cleanup - dataset has way more data than necessary executeDataSet("org/openmrs/api/include/ConceptServiceTest-numerics.xml"); authenticate(); Encounter encounter = Context.getEncounterService().getEncounter(14943); Assert.assertNotNull(encounter); Assert.assertNotNull(encounter.getObs()); boolean testedsomething = false; for (Obs obs : encounter.getObs()) { if (obs.getConcept().getConceptId().equals(1016)) { testedsomething = true; Concept concept = Context.getConceptService().getConcept(1016); Assert.assertEquals(obs.getConcept(), concept); Assert.assertEquals(concept, obs.getConcept()); } } Assert.assertEquals(true, testedsomething); } /** * @see {@link ConceptService#getConceptByMapping(String,String)} */ @Test @Verifies(value = "should get concept with given code and source hl7 code", method = "getConceptByMapping(String,String)") public void getConceptByMapping_shouldGetConceptWithGivenCodeAndSourceHl7Code() throws Exception { Concept concept = conceptService.getConceptByMapping("WGT234", "SSTRM"); Assert.assertEquals(new Concept(5089), concept); } /** * @see {@link ConceptService#getConceptByMapping(String,String)} */ @Test @Verifies(value = "should get concept with given code and source hl7 name", method = "getConceptByMapping(String,String)") public void getConceptByMapping_shouldGetConceptWithGivenCodeAndSourceName() throws Exception { Concept concept = conceptService.getConceptByMapping("WGT234", "Some Standardized Terminology"); Assert.assertEquals(new Concept(5089), concept); } /** * @see {@link ConceptService#getConceptByMapping(String,String)} */ @Test @Verifies(value = "should return null if source code does not exist", method = "getConceptByMapping(String,String)") public void getConceptByMapping_shouldReturnNullIfSourceCodeDoesNotExist() throws Exception { Concept concept = conceptService.getConceptByMapping("A random concept code", "A random source code"); Assert.assertNull(concept); } /** * @see {@link ConceptService#getConceptsByMapping(String,String)} */ @Test @Verifies(value = "should return null if no mapping exists", method = "getConceptByMapping(String,String)") public void getConceptByMapping_shouldReturnNullIfNoMappingExists() throws Exception { Concept concept = conceptService.getConceptByMapping("A random concept code", "SSTRM"); Assert.assertNull(concept); } /** * @see {@link ConceptService#getConceptsByMapping(String,String)} */ @Test @Verifies(value = "should return retired concept by default if that is the only match", method = "getConceptByMapping(String,String)") public void getConceptByMapping_shouldReturnRetiredConceptByDefaultIfOnlyMatch() throws Exception { Concept concept = conceptService.getConceptByMapping("454545", "SSTRM"); Assert.assertEquals(new Concept(24), concept); } /** * @see {@link ConceptService#getConceptsByMapping(String,String,Boolean)} */ @Test @Verifies(value = "should return retired concept if that is the only match", method = "getConceptByMapping(String,String,Boolean)") public void getConceptByMapping_shouldReturnRetiredConceptIfOnlyMatch() throws Exception { Concept concept = conceptService.getConceptByMapping("454545", "SSTRM", true); Assert.assertEquals(new Concept(24), concept); } /** * @see {@link ConceptService#getConceptsByMapping(String,String,Boolean)} */ @Test @Verifies(value = "should not return retired concept", method = "getConceptByMapping(String,String,Boolean)") public void getConceptByMapping_shouldNotReturnRetiredConcept() throws Exception { Concept concept = conceptService.getConceptByMapping("454545", "SSTRM", false); Assert.assertNull(concept); } /** * @see {@link ConceptService#getConceptsByMapping(String,String)} */ @Test @Verifies(value = "should get distinct concepts with given code and and source hl7 code", method = "getConceptsByMapping(String,String)") public void getConceptsByMapping_shouldGetConceptsWithGivenCodeAndSourceH17Code() throws Exception { List<Concept> concepts = conceptService.getConceptsByMapping("127689", "Some Standardized Terminology"); Assert.assertEquals(2, concepts.size()); Assert.assertTrue(concepts.contains(new Concept(16))); Assert.assertTrue(concepts.contains(new Concept(6))); } /** * @see {@link ConceptService#getConceptsByMapping(String,String)} */ @Test @Verifies(value = "should get distinct concepts with given code and source name", method = "getConceptsByMapping(String,String)") public void getConceptsByMapping_shouldGetConceptsWithGivenCodeAndSourceName() throws Exception { List<Concept> concepts = conceptService.getConceptsByMapping("127689", "SSTRM"); Assert.assertEquals(2, concepts.size()); Assert.assertTrue(concepts.contains(new Concept(16))); Assert.assertTrue(concepts.contains(new Concept(6))); } /** * @see {@link ConceptService#getConceptsByMapping(String,String)} */ @Test @Verifies(value = "should return empty list if code does not exist", method = "getConceptByMapping(String,String)") public void getConceptsByMapping_shouldReturnEmptyListIfSourceCodeDoesNotExist() throws Exception { List<Concept> concept = conceptService.getConceptsByMapping("A random concept code", "A random source code"); Assert.assertTrue(concept.isEmpty()); } /** * @see {@link ConceptService#getConceptsByMapping(String,String)} */ @Test @Verifies(value = "should return empty list if no mappings exist", method = "getConceptsByMapping(String,String)") public void getConceptsByMapping_shouldReturnEmptyListIfNoMappingsExist() throws Exception { List<Concept> concept = conceptService.getConceptsByMapping("A random concept code", "SSTRM"); Assert.assertTrue(concept.isEmpty()); } /** * @see {@link ConceptService#getConceptsByMapping(String,String,Boolean)} */ @Test @Verifies(value = "should return retired and non-retired concepts", method = "getConceptsByMapping(String,String)") public void getConceptsByMapping_shouldReturnRetiredAndNonRetiredConceptsByDefault() throws Exception { List<Concept> concepts = conceptService.getConceptsByMapping("766554", "SSTRM"); Assert.assertEquals(2, concepts.size()); Assert.assertTrue(concepts.contains(new Concept(16))); Assert.assertTrue(concepts.contains(new Concept(24))); } /** * @see {@link ConceptService#getConceptsByMapping(String,String,Boolean)} */ @Test @Verifies(value = "should only return non-retired concepts", method = "getConceptsByMapping(String,String,Boolean)") public void getConceptsByMapping_shouldOnlyReturnNonRetiredConcepts() throws Exception { List<Concept> concepts = conceptService.getConceptsByMapping("766554", "SSTRM", false); Assert.assertEquals(1, concepts.size()); Assert.assertTrue(concepts.contains(new Concept(16))); } /** * @see {@link ConceptService#getConceptsByMapping(String,String,Boolean)} */ @Test @Verifies(value = "should return retired and non-retired concepts", method = "getConceptsByMapping(String,String,Boolean)") public void getConceptsByMapping_shouldReturnRetiredAndNonRetiredConcepts() throws Exception { List<Concept> concepts = conceptService.getConceptsByMapping("766554", "SSTRM", true); Assert.assertEquals(2, concepts.size()); Assert.assertTrue(concepts.contains(new Concept(16))); Assert.assertTrue(concepts.contains(new Concept(24))); } /** * @see {@link ConceptService#getConceptsByMapping(String,String,Boolean)} */ @Test @Verifies(value = "should sort non-retired concepts first", method = "getConceptsByMapping(String,String,Boolean)") public void getConceptsByMapping_shouldSortNonRetiredConceptsFirst() throws Exception { List<Concept> concepts = conceptService.getConceptsByMapping("766554", "SSTRM", true); Assert.assertTrue(concepts.get(0).equals(new Concept(16))); } /** * @see {@link ConceptService#getConceptAnswerByUuid(String)} */ @Test @Verifies(value = "should find object given valid uuid", method = "getConceptAnswerByUuid(String)") public void getConceptAnswerByUuid_shouldFindObjectGivenValidUuid() throws Exception { String uuid = "b1230431-2fe5-49fc-b535-ae42bc849747"; ConceptAnswer conceptAnswer = Context.getConceptService().getConceptAnswerByUuid(uuid); Assert.assertEquals(1, (int) conceptAnswer.getConceptAnswerId()); } /** * @see {@link ConceptService#getConceptAnswerByUuid(String)} */ @Test @Verifies(value = "should return null if no object found with given uuid", method = "getConceptAnswerByUuid(String)") public void getConceptAnswerByUuid_shouldReturnNullIfNoObjectFoundWithGivenUuid() throws Exception { Assert.assertNull(Context.getConceptService().getConceptAnswerByUuid("some invalid uuid")); } /** * @see {@link ConceptService#getConceptByUuid(String)} */ @Test @Verifies(value = "should find object given valid uuid", method = "getConceptByUuid(String)") public void getConceptByUuid_shouldFindObjectGivenValidUuid() throws Exception { String uuid = "0cbe2ed3-cd5f-4f46-9459-26127c9265ab"; Concept concept = Context.getConceptService().getConceptByUuid(uuid); Assert.assertEquals(3, (int) concept.getConceptId()); } /** * @see {@link ConceptService#getConceptByUuid(String)} */ @Test @Verifies(value = "should return null if no object found with given uuid", method = "getConceptByUuid(String)") public void getConceptByUuid_shouldReturnNullIfNoObjectFoundWithGivenUuid() throws Exception { Assert.assertNull(Context.getConceptService().getConceptByUuid("some invalid uuid")); } /** * @see {@link ConceptService#getConceptClassByUuid(String)} */ @Test @Verifies(value = "should find object given valid uuid", method = "getConceptClassByUuid(String)") public void getConceptClassByUuid_shouldFindObjectGivenValidUuid() throws Exception { String uuid = "97097dd9-b092-4b68-a2dc-e5e5be961d42"; ConceptClass conceptClass = Context.getConceptService().getConceptClassByUuid(uuid); Assert.assertEquals(1, (int) conceptClass.getConceptClassId()); } /** * @see {@link ConceptService#getConceptClassByUuid(String)} */ @Test @Verifies(value = "should return null if no object found with given uuid", method = "getConceptClassByUuid(String)") public void getConceptClassByUuid_shouldReturnNullIfNoObjectFoundWithGivenUuid() throws Exception { Assert.assertNull(Context.getConceptService().getConceptClassByUuid("some invalid uuid")); } /** * @see {@link ConceptService#getConceptDatatypeByUuid(String)} */ @Test @Verifies(value = "should find object given valid uuid", method = "getConceptDatatypeByUuid(String)") public void getConceptDatatypeByUuid_shouldFindObjectGivenValidUuid() throws Exception { String uuid = "8d4a4488-c2cc-11de-8d13-0010c6dffd0f"; ConceptDatatype conceptDatatype = Context.getConceptService().getConceptDatatypeByUuid(uuid); Assert.assertEquals(1, (int) conceptDatatype.getConceptDatatypeId()); } /** * @see {@link ConceptService#getConceptDatatypeByUuid(String)} */ @Test @Verifies(value = "should return null if no object found with given uuid", method = "getConceptDatatypeByUuid(String)") public void getConceptDatatypeByUuid_shouldReturnNullIfNoObjectFoundWithGivenUuid() throws Exception { Assert.assertNull(Context.getConceptService().getConceptDatatypeByUuid("some invalid uuid")); } /** * @see {@link ConceptService#getConceptDescriptionByUuid(String)} */ @Test @Verifies(value = "should find object given valid uuid", method = "getConceptDescriptionByUuid(String)") public void getConceptDescriptionByUuid_shouldFindObjectGivenValidUuid() throws Exception { String uuid = "5f4d710b-d333-40b7-b449-6e0e739d15d0"; ConceptDescription conceptDescription = Context.getConceptService().getConceptDescriptionByUuid(uuid); Assert.assertEquals(1, (int) conceptDescription.getConceptDescriptionId()); } /** * @see {@link ConceptService#getConceptDescriptionByUuid(String)} */ @Test @Verifies(value = "should return null if no object found with given uuid", method = "getConceptDescriptionByUuid(String)") public void getConceptDescriptionByUuid_shouldReturnNullIfNoObjectFoundWithGivenUuid() throws Exception { Assert.assertNull(Context.getConceptService().getConceptDescriptionByUuid("some invalid uuid")); } /** * @see {@link ConceptService#getConceptNameByUuid(String)} */ @Test @Verifies(value = "should find object given valid uuid", method = "getConceptNameByUuid(String)") public void getConceptNameByUuid_shouldFindObjectGivenValidUuid() throws Exception { String uuid = "9bc5693a-f558-40c9-8177-145a4b119ca7"; ConceptName conceptName = Context.getConceptService().getConceptNameByUuid(uuid); Assert.assertEquals(1439, (int) conceptName.getConceptNameId()); } /** * @see {@link ConceptService#getConceptNameByUuid(String)} */ @Test @Verifies(value = "should return null if no object found with given uuid", method = "getConceptNameByUuid(String)") public void getConceptNameByUuid_shouldReturnNullIfNoObjectFoundWithGivenUuid() throws Exception { Assert.assertNull(Context.getConceptService().getConceptNameByUuid("some invalid uuid")); } /** * @see {@link ConceptService#getConceptNameTagByUuid(String)} */ @Test @Verifies(value = "should find object given valid uuid", method = "getConceptNameTagByUuid(String)") public void getConceptNameTagByUuid_shouldFindObjectGivenValidUuid() throws Exception { String uuid = "9e9df183-2328-4117-acd8-fb9bf400911d"; ConceptNameTag conceptNameTag = Context.getConceptService().getConceptNameTagByUuid(uuid); Assert.assertEquals(1, (int) conceptNameTag.getConceptNameTagId()); } /** * @see {@link ConceptService#getConceptNameTagByUuid(String)} */ @Test @Verifies(value = "should return null if no object found with given uuid", method = "getConceptNameTagByUuid(String)") public void getConceptNameTagByUuid_shouldReturnNullIfNoObjectFoundWithGivenUuid() throws Exception { Assert.assertNull(Context.getConceptService().getConceptNameTagByUuid("some invalid uuid")); } /** * @see {@link ConceptService#getConceptNumericByUuid(String)} */ @Test @Verifies(value = "should find object given valid uuid", method = "getConceptNumericByUuid(String)") public void getConceptNumericByUuid_shouldFindObjectGivenValidUuid() throws Exception { String uuid = "c607c80f-1ea9-4da3-bb88-6276ce8868dd"; ConceptNumeric conceptNumeric = Context.getConceptService().getConceptNumericByUuid(uuid); Assert.assertEquals(5089, (int) conceptNumeric.getConceptId()); } /** * @see {@link ConceptService#getConceptNumericByUuid(String)} */ @Test @Verifies(value = "should return null if no object found with given uuid", method = "getConceptNumericByUuid(String)") public void getConceptNumericByUuid_shouldReturnNullIfNoObjectFoundWithGivenUuid() throws Exception { Assert.assertNull(Context.getConceptService().getConceptNumericByUuid("some invalid uuid")); } /** * @see {@link ConceptService#getConceptProposalByUuid(String)} */ @Test @Verifies(value = "should find object given valid uuid", method = "getConceptProposalByUuid(String)") public void getConceptProposalByUuid_shouldFindObjectGivenValidUuid() throws Exception { String uuid = "57a68666-5067-11de-80cb-001e378eb67e"; ConceptProposal conceptProposal = Context.getConceptService().getConceptProposalByUuid(uuid); Assert.assertEquals(1, (int) conceptProposal.getConceptProposalId()); } /** * @see {@link ConceptService#getConceptProposalByUuid(String)} */ @Test @Verifies(value = "should return null if no object found with given uuid", method = "getConceptProposalByUuid(String)") public void getConceptProposalByUuid_shouldReturnNullIfNoObjectFoundWithGivenUuid() throws Exception { Assert.assertNull(Context.getConceptService().getConceptProposalByUuid("some invalid uuid")); } /** * @see {@link ConceptService#getConceptSetByUuid(String)} */ @Test @Verifies(value = "should find object given valid uuid", method = "getConceptSetByUuid(String)") public void getConceptSetByUuid_shouldFindObjectGivenValidUuid() throws Exception { String uuid = "1a111827-639f-4cb4-961f-1e025bf88d90"; ConceptSet conceptSet = Context.getConceptService().getConceptSetByUuid(uuid); Assert.assertEquals(1, (int) conceptSet.getConceptSetId()); } /** * @see {@link ConceptService#getConceptSetByUuid(String)} */ @Test @Verifies(value = "should return null if no object found with given uuid", method = "getConceptSetByUuid(String)") public void getConceptSetByUuid_shouldReturnNullIfNoObjectFoundWithGivenUuid() throws Exception { Assert.assertNull(Context.getConceptService().getConceptSetByUuid("some invalid uuid")); } /** * @see {@link ConceptService#getConceptSourceByUuid(String)} */ @Test @Verifies(value = "should find object given valid uuid", method = "getConceptSourceByUuid(String)") public void getConceptSourceByUuid_shouldFindObjectGivenValidUuid() throws Exception { String uuid = "75f5b378-5065-11de-80cb-001e378eb67e"; ConceptSource conceptSource = Context.getConceptService().getConceptSourceByUuid(uuid); Assert.assertEquals(3, (int) conceptSource.getConceptSourceId()); } /** * @see {@link ConceptService#getConceptSourceByUuid(String)} */ @Test @Verifies(value = "should return null if no object found with given uuid", method = "getConceptSourceByUuid(String)") public void getConceptSourceByUuid_shouldReturnNullIfNoObjectFoundWithGivenUuid() throws Exception { Assert.assertNull(Context.getConceptService().getConceptSourceByUuid("some invalid uuid")); } /** * @see {@link ConceptService#getDrugByUuid(String)} */ @Test @Verifies(value = "should find object given valid uuid", method = "getDrugByUuid(String)") public void getDrugByUuid_shouldFindObjectGivenValidUuid() throws Exception { String uuid = "3cfcf118-931c-46f7-8ff6-7b876f0d4202"; Drug drug = Context.getConceptService().getDrugByUuid(uuid); Assert.assertEquals(2, (int) drug.getDrugId()); } /** * @see {@link ConceptService#getDrugByUuid(String)} */ @Test @Verifies(value = "should return null if no object found with given uuid", method = "getDrugByUuid(String)") public void getDrugByUuid_shouldReturnNullIfNoObjectFoundWithGivenUuid() throws Exception { Assert.assertNull(Context.getConceptService().getDrugByUuid("some invalid uuid")); } /** * This tests for being able to find concepts with names in en_GB locale when the user is in the * en locale. * * @see {@link ConceptService#getConceptByName(String)} */ @Test @Verifies(value = "should find concepts with names in more specific locales", method = "getConceptByName(String)") public void getConceptByName_shouldFindConceptsWithNamesInMoreSpecificLocales() throws Exception { Locale origLocale = Context.getLocale(); executeDataSet(INITIAL_CONCEPTS_XML); Context.setLocale(Locale.ENGLISH); // make sure that concepts are found that have a specific locale on them Assert.assertNotNull(Context.getConceptService().getConceptByName("Numeric name with en_GB locale")); // find concepts with same generic locale Assert.assertNotNull(Context.getConceptService().getConceptByName("Some numeric concept name")); // reset the locale for the next test Context.setLocale(origLocale); } /** * This tests for being able to find concepts with names in the en locale when the user is in * the en_GB locale * * @see {@link ConceptService#getConceptByName(String)} */ @Test @Verifies(value = "should find concepts with names in more generic locales", method = "getConceptByName(String)") public void getConceptByName_shouldFindConceptsWithNamesInMoreGenericLocales() throws Exception { executeDataSet(INITIAL_CONCEPTS_XML); //prior tests have changed the locale to 'en_US', so we need to set it back Context.setLocale(Locale.UK); // make sure that concepts are found that have a specific locale on them Assert.assertNotNull(Context.getConceptService().getConceptByName("Some numeric concept name")); } /** * This tests for being able to find concepts with names in en_GB locale when the user is in the * en_GB locale. * * @see {@link ConceptService#getConceptByName(String)} */ @Test @Verifies(value = "should find concepts with names in same specific locale", method = "getConceptByName(String)") public void getConceptByName_shouldFindConceptsWithNamesInSameSpecificLocale() throws Exception { executeDataSet(INITIAL_CONCEPTS_XML); // sanity check Assert.assertEquals(Context.getLocale(), Locale.UK); // make sure that concepts are found that have a specific locale on them Assert.assertNotNull(Context.getConceptService().getConceptByName("Numeric name with en_GB locale")); } /** * @see {@link ConceptService#retireConceptSource(ConceptSource,String)} */ @Test @Verifies(value = "should retire concept source", method = "retireConceptSource(ConceptSource,String)") public void retireConceptSource_shouldRetireConceptSource() throws Exception { ConceptSource cs = conceptService.getConceptSource(3); conceptService.retireConceptSource(cs, "dummy reason for retirement"); cs = conceptService.getConceptSource(3); Assert.assertTrue(cs.isRetired()); Assert.assertEquals("dummy reason for retirement", cs.getRetireReason()); } /** * @verifies {@link ConceptService#saveConcept(Concept)} test = should create new concept in * database */ @SkipBaseSetup @Test @Verifies(value = "should create new concept in database", method = "saveConcept(Concept)") public void saveConcept_shouldCreateNewConceptInDatabase() throws Exception { initializeInMemoryDatabase(); executeDataSet(INITIAL_CONCEPTS_XML); authenticate(); Concept conceptToAdd = new Concept(); ConceptName cn = new ConceptName("new name", Context.getLocale()); conceptToAdd.addName(cn); assertFalse(conceptService.getAllConcepts().contains(conceptToAdd)); conceptService.saveConcept(conceptToAdd); assertTrue(conceptService.getAllConcepts().contains(conceptToAdd)); } /** * @verifies {@link ConceptService#saveConcept(Concept)} test = should update concept already * existing in database */ //@SkipBaseSetup @Test @Verifies(value = "should update concept already existing in database", method = "saveConcept(Concept)") public void saveConcept_shouldUpdateConceptAlreadyExistingInDatabase() throws Exception { initializeInMemoryDatabase(); executeDataSet(INITIAL_CONCEPTS_XML); authenticate(); // using isSet() as a value to check and change assertFalse(conceptService.getConcept(2).isSet()); Concept concept = conceptService.getConcept(2); // change a value concept.setSet(true); // save the concept conceptService.saveConcept(concept); // see if the value was updated in the database assertTrue(conceptService.getConcept(2).isSet()); } /** * @verifies {@link ConceptService#getConceptSourceByName(String)} test = should get * ConceptSource with the given name */ @Test public void getConceptSourceByName_shouldGetConceptSourceWithTheGivenName() throws Exception { ConceptSource conceptSource = conceptService.getConceptSourceByName("SNOMED CT"); assertEquals("Method did not retrieve ConceptSource by name", new Integer(2), conceptSource.getConceptSourceId()); } /** * @verifies {@link ConceptService#getConceptSourceByName(String)} test = should return null if * no ConceptSource with that name is found */ @Test public void getConceptSourceByName_shouldReturnNullIfNoConceptSourceWithThatNameIsFound() throws Exception { ConceptSource conceptSource = conceptService.getConceptSourceByName("Some invalid name"); assertNull("Method did not return null when no ConceptSource with that name is found", conceptSource); } /** * @verifies {@link ConceptService#getConceptsByConceptSource(ConceptSource)} test = should * return a List of ConceptMaps if concept mappings found */ @Test public void getConceptsByConceptSource_shouldReturnAListOfConceptMapsIfConceptMappingsFound() throws Exception { List<ConceptMap> list = conceptService .getConceptsByConceptSource(conceptService.getConceptSourceByName("SNOMED CT")); assertEquals(2, list.size()); } /** * @verifies {@link ConceptService#getConceptsByConceptSource(ConceptSource)} test = should * return empty List of ConceptMaps if none found */ @Test public void getConceptsByConceptSource_shouldReturnEmptyListOfConceptMapsIfNoneFound() throws Exception { List<ConceptMap> list = conceptService.getConceptsByConceptSource(conceptService .getConceptSourceByName("Some invalid name")); assertEquals(0, list.size()); } /** * @verifies {@link ConceptService#saveConceptSource(ConceptSource)} test = should save a * ConceptSource with a null hl7Code */ @Test public void saveConceptSource_shouldSaveAConceptSourceWithANullHl7Code() throws Exception { ConceptSource source = new ConceptSource(); String aNullString = null; String sourceName = "A concept source with null HL7 code"; source.setName(sourceName); source.setHl7Code(aNullString); conceptService.saveConceptSource(source); assertEquals("Did not save a ConceptSource with a null hl7Code", source, conceptService .getConceptSourceByName(sourceName)); } /** * @verifies {@link ConceptService#saveConceptSource(ConceptSource)} test = should not save a * ConceptSource if voided is null */ @Test(expected = Exception.class) public void saveConceptSource_shouldNotSaveAConceptSourceIfVoidedIsNull() throws Exception { ConceptSource source = new ConceptSource(); source.setVoided(null); assertNull(source.getVoided()); conceptService.saveConceptSource(source); } /** * @verifies {@link ConceptService#saveConceptNameTag(ConceptNameTag)} test = should save a * concept name tag if tag does not exist */ @Test(expected = Exception.class) public void saveConceptNameTag_shouldSaveAConceptNameTagIfATagDoesNotExist() throws Exception { ConceptNameTag nameTag = new ConceptNameTag(); nameTag.setTag("a new tag"); ConceptNameTag savedNameTag = conceptService.saveConceptNameTag(nameTag); assertNotNull(nameTag.getId()); assertEquals(savedNameTag.getId(), nameTag.getId()); } /** * @verifies {@link ConceptService#saveConceptNameTag(ConceptNameTag)} test = should not save a * concept name tag if tag exists */ @Test(expected = Exception.class) public void saveConceptNameTag_shouldNotSaveAConceptNameTagIfTagExists() throws Exception { String tag = "a new tag"; ConceptNameTag nameTag = new ConceptNameTag(); nameTag.setTag(tag); conceptService.saveConceptNameTag(nameTag); ConceptNameTag secondNameTag = new ConceptNameTag(); secondNameTag.setTag(tag); ConceptNameTag existingConceptNameTag = conceptService.saveConceptNameTag(secondNameTag); assertNull(secondNameTag.getId()); assertEquals(existingConceptNameTag.getId(), nameTag.getId()); } /** * @throws Exception to be asserted on * @verifies {@link ConceptService#saveConcept(Concept)} test = should not update a Concept * datatype if it is attached to an observation */ @Test(expected = ConceptInUseException.class) public void saveConcept_shouldNotUpdateConceptDataTypeIfConceptIsAttachedToAnObservation() throws Exception { executeDataSet(INITIAL_CONCEPTS_XML); Concept concept = conceptService.getConcept(1); assertNotNull(concept); ObsService obsService = Context.getObsService(); obsService.saveObs(new Obs(new Person(1), concept, new Date(), new Location(1)), "Creating a new observation with a concept"); ConceptDatatype newDatatype = conceptService.getConceptDatatypeByName("Text"); concept.setDatatype(newDatatype); conceptService.saveConcept(concept); } /** * @throws Exception to be asserted on * @verifies {@link ConceptService#saveConcept(Concept)} test = should update a Concept if * anything else other than the datatype is changed and it is attached to an * observation */ @Test public void saveConcept_shouldUpdateConceptIfConceptIsAttachedToAnObservationAndItIsANonDatatypeChange() throws Exception { executeDataSet(INITIAL_CONCEPTS_XML); Concept concept = conceptService.getConcept(1); assertNotNull(concept); ObsService obsService = Context.getObsService(); obsService.saveObs(new Obs(new Person(1), concept, new Date(), new Location(1)), "Creating a new observation with a concept"); try { conceptService.saveConcept(concept); } catch (ConceptInUseException e) { fail("Should not fail if anything other than the datatype is changed"); } } /** * @see {@link ConceptService#getFalseConcept()} */ @Test @Verifies(value = "should return the false concept", method = "getFalseConcept()") public void getFalse_shouldReturnTheFalseConcept() throws Exception { createTrueFalseGlobalProperties(); Assert.assertNotNull(conceptService.getFalseConcept()); Assert.assertEquals(new Concept(8), conceptService.getFalseConcept()); } /** * @see {@link ConceptService#getTrueConcept()} */ @Test @Verifies(value = "should return the true concept", method = "getTrueConcept()") public void getTrue_shouldReturnTheTrueConcept() throws Exception { createTrueFalseGlobalProperties(); Assert.assertNotNull(conceptService.getTrueConcept()); Assert.assertEquals(new Concept(7), conceptService.getTrueConcept()); } /** * @see {@link ConceptService#getConceptDatatypeByName(String)} */ @Test @Verifies(value = "should convert the datatype of a boolean concept to coded", method = "changeConceptFromBooleanToCoded(Concept)") public void changeConceptFromBooleanToCoded_shouldConvertTheDatatypeOfABooleanConceptToCoded() throws Exception { Concept concept = conceptService.getConcept(18); Assert.assertEquals(conceptService.getConceptDatatypeByName("Boolean"), concept.getDatatype()); conceptService.convertBooleanConceptToCoded(concept); Assert.assertEquals(conceptService.getConceptDatatypeByName("Coded"), concept.getDatatype()); } /** * @see {@link ConceptService#getConcept(Integer)} */ @Test(expected = APIException.class) @Verifies(value = "should fail if the datatype of the concept is not boolean", method = "changeConceptFromBooleanToCoded(Concept)") public void changeConceptFromBooleanToCoded_shouldFailIfTheDatatypeOfTheConceptIsNotBoolean() throws Exception { Concept concept = conceptService.getConcept(5497); conceptService.convertBooleanConceptToCoded(concept); } /** * @see {@link ConceptService#convertBooleanConceptToCoded(Concept)} */ @Test @Verifies(value = "should explicitly add false concept as a value_Coded answer", method = "changeConceptFromBooleanToCoded(Concept)") public void changeConceptFromBooleanToCoded_shouldExplicitlyAddFalseConceptAsAValue_CodedAnswer() throws Exception { Concept concept = conceptService.getConcept(18); Collection<ConceptAnswer> answers = concept.getAnswers(); boolean falseConceptFound = false; //initially the concept shouldn't present for (ConceptAnswer conceptAnswer : answers) { if (conceptAnswer.getAnswerConcept().equals(conceptService.getFalseConcept())) falseConceptFound = true; } Assert.assertEquals(false, falseConceptFound); conceptService.convertBooleanConceptToCoded(concept); answers = concept.getAnswers(); for (ConceptAnswer conceptAnswer : answers) { if (conceptAnswer.getAnswerConcept().equals(conceptService.getFalseConcept())) falseConceptFound = true; } Assert.assertEquals(true, falseConceptFound); } /** * @see {@link ConceptService#convertBooleanConceptToCoded(Concept)} */ @Test @Verifies(value = "should explicitly add true concept as a value_Coded answer", method = "changeConceptFromBooleanToCoded(Concept)") public void changeConceptFromBooleanToCoded_shouldExplicitlyAddTrueConceptAsAValue_CodedAnswer() throws Exception { Concept concept = conceptService.getConcept(18); Collection<ConceptAnswer> answers = concept.getAnswers(); boolean trueConceptFound = false; for (ConceptAnswer conceptAnswer : answers) { if (conceptAnswer.getAnswerConcept().equals(conceptService.getTrueConcept())) trueConceptFound = true; } Assert.assertEquals(false, trueConceptFound); conceptService.convertBooleanConceptToCoded(concept); answers = concept.getAnswers(); for (ConceptAnswer conceptAnswer : answers) { if (conceptAnswer.getAnswerConcept().equals(conceptService.getTrueConcept())) trueConceptFound = true; } Assert.assertEquals(true, trueConceptFound); } /** * @see {@link ConceptService#getFalseConcept()} */ @Test @Verifies(value = "should return the false concept", method = "getFalseConcept()") public void getFalseConcept_shouldReturnTheFalseConcept() throws Exception { createTrueFalseGlobalProperties(); Assert.assertEquals(8, conceptService.getFalseConcept().getConceptId().intValue()); } /** * @see {@link ConceptService#getTrueConcept()} */ @Test @Verifies(value = "should return the true concept", method = "getTrueConcept()") public void getTrueConcept_shouldReturnTheTrueConcept() throws Exception { createTrueFalseGlobalProperties(); Assert.assertEquals(7, conceptService.getTrueConcept().getConceptId().intValue()); } /** * Utility method that creates the global properties 'concept.true' and 'concept.false' */ private static void createTrueFalseGlobalProperties() { GlobalProperty trueConceptGlobalProperty = new GlobalProperty(OpenmrsConstants.GLOBAL_PROPERTY_TRUE_CONCEPT, "7", "Concept id of the concept defining the TRUE boolean concept"); GlobalProperty falseConceptGlobalProperty = new GlobalProperty(OpenmrsConstants.GLOBAL_PROPERTY_FALSE_CONCEPT, "8", "Concept id of the concept defining the TRUE boolean concept"); Context.getAdministrationService().saveGlobalProperty(trueConceptGlobalProperty); Context.getAdministrationService().saveGlobalProperty(falseConceptGlobalProperty); } /** * @see {@link ConceptService#getConceptDatatypeByName(String)} */ @Test @Verifies(value = "should not return a fuzzy match on name", method = "getConceptDatatypeByName(String)") public void getConceptDatatypeByName_shouldNotReturnAFuzzyMatchOnName() throws Exception { executeDataSet(INITIAL_CONCEPTS_XML); ConceptDatatype result = conceptService.getConceptDatatypeByName("Tex"); Assert.assertNull(result); } /** * @see {@link ConceptService#getConceptDatatypeByName(String)} */ @Test @Verifies(value = "should return an exact match on name", method = "getConceptDatatypeByName(String)") public void getConceptDatatypeByName_shouldReturnAnExactMatchOnName() throws Exception { // given executeDataSet(INITIAL_CONCEPTS_XML); // when ConceptDatatype result = conceptService.getConceptDatatypeByName("Text"); // then assertEquals("Text", result.getName()); } /** * @see {@link ConceptService#purgeConcept(Concept)} */ @Test(expected = ConceptNameInUseException.class) @Verifies(value = "should fail if any of the conceptNames of the concept is being used by an obs", method = "purgeConcept(Concept)") public void purgeConcept_shouldFailIfAnyOfTheConceptNamesOfTheConceptIsBeingUsedByAnObs() throws Exception { Obs o = new Obs(); o.setConcept(new Concept(3)); o.setPerson(new Patient(2)); o.setEncounter(new Encounter(3)); o.setObsDatetime(new Date()); o.setLocation(new Location(1)); ConceptName conceptName = new ConceptName(1847); o.setValueCodedName(conceptName); Context.getObsService().saveObs(o, null); //ensure that the association between the conceptName and the obs has been established Assert.assertEquals(true, conceptService.hasAnyObservation(conceptName)); Concept concept = conceptService.getConceptByName("cd4 count"); //make sure the name concept name exists Assert.assertNotNull(concept); conceptService.purgeConcept(concept); } /** * @see {@link ConceptService#saveConcept(Concept)} */ @Test @Verifies(value = "should create a new conceptName when the old name is changed", method = "saveConcept(Concept)") public void saveConcept_shouldCreateANewConceptNameWhenTheOldNameIsChanged() throws Exception { Concept concept = conceptService.getConceptByName("cd4 count"); Assert.assertEquals(3, concept.getNames(true).size()); for (ConceptName cn : concept.getNames()) { if (cn.getConceptNameId().equals(1847)) cn.setName("new name"); } conceptService.saveConcept(concept); Assert.assertEquals(4, concept.getNames(true).size()); } /** * @see {@link ConceptService#saveConcept(Concept)} */ @Test @Verifies(value = "should void the conceptName if the text of the name has changed", method = "saveConcept(Concept)") public void saveConcept_shouldVoidTheConceptNameIfTheTextOfTheNameHasChanged() throws Exception { Concept concept = conceptService.getConceptByName("cd4 count"); Assert.assertEquals(false, conceptService.getConceptName(1847).isVoided().booleanValue()); for (ConceptName cn : concept.getNames()) { if (cn.getConceptNameId().equals(1847)) cn.setName("new name"); } //ensure that the conceptName has actually been found and replaced Assert.assertEquals(true, concept.hasName("new name", new Locale("en"))); conceptService.saveConcept(concept); Assert.assertEquals(true, conceptService.getConceptName(1847).isVoided().booleanValue()); } /** * Test getting a concept by name and by partial name. * * @see {@link ConceptService#getConceptByName(String)} */ @Test @Verifies(value = "should return all concepts in set and subsets", method = "getConceptsByConceptSet(Concept)") public void getConceptsByConceptSet_shouldReturnAllConceptsInSet() throws Exception { executeDataSet(GET_CONCEPTS_BY_SET_XML); Concept concept = conceptService.getConcept(1); List<Concept> conceptSet = conceptService.getConceptsByConceptSet(concept); Assert.assertEquals(5, conceptSet.size()); Assert.assertEquals(true, conceptSet.contains(conceptService.getConcept(2))); Assert.assertEquals(true, conceptSet.contains(conceptService.getConcept(3))); Assert.assertEquals(true, conceptSet.contains(conceptService.getConcept(4))); Assert.assertEquals(true, conceptSet.contains(conceptService.getConcept(5))); Assert.assertEquals(true, conceptSet.contains(conceptService.getConcept(6))); } /** * @see {@link ConceptService#getConcepts(String, java.util.List, boolean, java.util.List, java.util.List, java.util.List, java.util.List, org.openmrs.Concept, Integer, Integer)} * */ @Test @Ignore @Verifies(value = "should return the best matched name as the first item in the searchResultsList", method = "getConcepts(String,List<Locale>,null,List<ConceptClass>,List<ConceptClass>,List<ConceptDatatype>,List<ConceptDatatype>,Concept,Integer,Integer)") public void getConcepts_shouldReturnTheBestMatchedNameAsTheFirstItemInTheSearchResultsList() throws Exception { executeDataSet("org/openmrs/api/include/ConceptServiceTest-words.xml"); - //TODO H2 requires cannot execute the generated SQL in the DAO layer + //TODO H2 cannot execute the generated SQL because it requires all fetched columns to be included in the group by clause List<ConceptSearchResult> searchResults = Context.getConceptService().getConcepts("cd4", Collections.singletonList(Locale.ENGLISH), false, null, null, null, null, null, null, null); Assert.assertEquals(1847, searchResults.get(0).getConceptName().getConceptNameId().intValue()); } /** * @see {@link ConceptService#saveConceptStopWord(org.openmrs.ConceptStopWord)} */ @Test @Verifies(value = "should save concept stop word into database", method = "saveConceptStopWord(ConceptStopWord)") public void saveConceptStopWord_shouldSaveConceptStopWordIntoDatabase() throws Exception { ConceptStopWord conceptStopWord = new ConceptStopWord("AND", Locale.FRANCE); conceptService.saveConceptStopWord(conceptStopWord); List<String> conceptStopWords = conceptService.getConceptStopWords(Locale.FRANCE); assertEquals(1, conceptStopWords.size()); assertEquals("AND", conceptStopWords.get(0)); } /** * @see {@link ConceptService#saveConceptStopWord(ConceptStopWord)} */ @Test @Verifies(value = "should assign default Locale ", method = "saveConceptStopWord(ConceptStopWord)") public void saveConceptStopWord_shouldSaveConceptStopWordAssignDefaultLocaleIsItNull() throws Exception { ConceptStopWord conceptStopWord = new ConceptStopWord("The"); conceptService.saveConceptStopWord(conceptStopWord); List<String> conceptStopWords = conceptService.getConceptStopWords(Locale.UK); assertEquals(2, conceptStopWords.size()); } /** * @see {@link ConceptService#getConceptStopWords(Locale)} */ @Test @Verifies(value = "should return default Locale ConceptStopWords if Locale is null", method = "getConceptStopWords(Locale)") public void getConceptStopWords_shouldReturnDefaultLocaleConceptStopWordsIfLocaleIsNull() throws Exception { List<String> conceptStopWords = conceptService.getConceptStopWords(null); assertEquals(1, conceptStopWords.size()); } /** * @see {@link ConceptService#saveConceptStopWord(ConceptStopWord)} */ @Test @Verifies(value = "should put generated concept stop word id onto returned concept stop word", method = "saveConceptStopWord(ConceptStopWord)") public void saveConceptStopWord_shouldSaveReturnConceptStopWordWithId() throws Exception { ConceptStopWord conceptStopWord = new ConceptStopWord("A"); ConceptStopWord savedConceptStopWord = conceptService.saveConceptStopWord(conceptStopWord); assertNotNull(savedConceptStopWord.getId()); } /** * @see {@link ConceptService#saveConceptStopWord(ConceptStopWord)} */ @Test @Verifies(value = "should fail if a duplicate conceptStopWord in a locale is added", method = "saveConceptStopWord(ConceptStopWord)") @ExpectedException(ConceptStopWordException.class) public void saveConceptStopWord_shouldFailIfADuplicateConceptStopWordInALocaleIsAdded() throws Exception { ConceptStopWord conceptStopWord = new ConceptStopWord("A"); try { conceptService.saveConceptStopWord(conceptStopWord); conceptService.saveConceptStopWord(conceptStopWord); } catch (ConceptStopWordException e) { assertEquals("ConceptStopWord.duplicated", e.getMessage()); throw e; } } /** * @see {@link ConceptService#saveConceptStopWord(ConceptStopWord)} */ @Test @Verifies(value = "should save concept stop word in uppercase", method = "saveConceptStopWord(ConceptStopWord)") public void saveConceptStopWord_shouldSaveConceptStopWordInUppercase() throws Exception { ConceptStopWord conceptStopWord = new ConceptStopWord("lowertoupper"); ConceptStopWord savedConceptStopWord = conceptService.saveConceptStopWord(conceptStopWord); assertEquals("LOWERTOUPPER", savedConceptStopWord.getValue()); } /** * @see {@link ConceptService#getConceptStopWords(Locale)} */ @Test @Verifies(value = "should return list of concept stop word for given locale", method = "getConceptStopWords(Locale)") public void getConceptStopWords_shouldReturnListOfConceptStopWordsForGivenLocale() throws Exception { List<String> conceptStopWords = conceptService.getConceptStopWords(Locale.ENGLISH); assertEquals(2, conceptStopWords.size()); assertEquals("A", conceptStopWords.get(0)); assertEquals("AN", conceptStopWords.get(1)); } /** * @see {@link ConceptService#getAllConceptStopWords()} */ @Test @Verifies(value = "should return all the concept stop words", method = "getAllConceptStopWords()") public void getAllConceptStopWords_shouldReturnAllConceptStopWords() throws Exception { List<ConceptStopWord> conceptStopWords = conceptService.getAllConceptStopWords(); assertEquals(4, conceptStopWords.size()); } /** * @see {@link ConceptService#getAllConceptStopWords()} */ @Test @Verifies(value = "should return empty list if nothing found", method = "getAllConceptStopWords()") public void getAllConceptStopWords_shouldReturnEmptyListIfNoRecordFound() throws Exception { conceptService.deleteConceptStopWord(1); conceptService.deleteConceptStopWord(2); conceptService.deleteConceptStopWord(3); conceptService.deleteConceptStopWord(4); List<ConceptStopWord> conceptStopWords = conceptService.getAllConceptStopWords(); assertEquals(0, conceptStopWords.size()); } /** * @see {@link ConceptService#getConceptStopWords(Locale)} */ @Test @Verifies(value = "should return empty list if no stop words are found for the given locale", method = "getConceptStopWords(Locale)") public void getConceptStopWords_shouldReturnEmptyListIfNoConceptStopWordsForGivenLocale() throws Exception { List<String> conceptStopWords = conceptService.getConceptStopWords(Locale.GERMANY); assertEquals(0, conceptStopWords.size()); } /** * @see {@link ConceptService#deleteConceptStopWord(Integer)} */ @Test @Verifies(value = "should delete the given concept stop word from the database", method = "deleteConceptStopWord(ConceptStopWordId)") public void deleteConceptStopWord_shouldDeleteTheGivenConceptStopWord() throws Exception { List<String> conceptStopWords = conceptService.getConceptStopWords(Locale.US); assertEquals(1, conceptStopWords.size()); conceptService.deleteConceptStopWord(4); conceptStopWords = conceptService.getConceptStopWords(Locale.US); assertEquals(0, conceptStopWords.size()); } /** * This test fetches all concepts in the xml test dataset and ensures that every locale for a * concept name is among those listed in the global property 'locale.allowed.list' and default * locale. NOTE that it doesn't test a particular API method directly. */ @Test @Verifies(value = "should not accept a locale that is neither among the localeAllowedList nor a default locale", method = "saveConcept(Concept)") public void saveConcept_shouldNotAcceptALocaleThatIsNeitherAmongTheLocaleAllowedListNorADefaultLocale() throws Exception { List<Concept> concepts = Context.getConceptService().getAllConcepts(); Set<Locale> allowedLocales = LocaleUtility.getLocalesInOrder(); for (Concept concept : concepts) { if (!CollectionUtils.isEmpty(concept.getNames())) { for (ConceptName cn : concept.getNames()) { Assert.assertTrue("The locale '" + cn.getLocale() + "' of conceptName with id: " + cn.getConceptNameId() + " is not among those listed in the global property 'locale.allowed.list'", allowedLocales .contains(cn.getLocale())); } } } } /** * This test fetches all concepts in the xml test dataset and ensures that every locale that has * atleast one conceptName has a name marked as preferred. NOTE that it doesn't test a * particular API method directly. */ @Test @Verifies(value = "should always return a preferred name for every locale that has atleast one unvoided name", method = "") public void saveConcept_shouldAlwaysReturnAPreferredNameForEveryLocaleThatHasAtleastOneUnvoidedName() throws Exception { List<Concept> concepts = Context.getConceptService().getAllConcepts(); Set<Locale> allowedLocales = LocaleUtility.getLocalesInOrder(); for (Concept concept : concepts) { for (Locale locale : allowedLocales) { if (!CollectionUtils.isEmpty(concept.getNames(locale))) { Assert.assertNotNull("Concept with Id: " + concept.getConceptId() + " has no preferred name in locale:" + locale, concept.getPreferredName(locale)); Assert.assertEquals(true, concept.getPreferredName(locale).isLocalePreferred().booleanValue()); } } } } /** * This test is run against the xml test dataset for all concepts to ensure that in every locale * with one or more names, there isn't more than one name explicitly marked as locale preferred. * NOTE that it doesn't test a particular API method directly */ @Test @Verifies(value = "should ensure that every concepName locale has exactly one preferred name", method = "") public void saveConcept_shouldEnsureThatEveryConcepNameLocaleHasExactlyOnePreferredName() throws Exception { List<Concept> concepts = Context.getConceptService().getAllConcepts(); Set<Locale> allowedLocales = LocaleUtility.getLocalesInOrder(); for (Concept concept : concepts) { for (Locale locale : allowedLocales) { Collection<ConceptName> namesInLocale = concept.getNames(locale); if (!CollectionUtils.isEmpty(namesInLocale)) { int preferredNamesFound = 0; for (ConceptName conceptName : namesInLocale) { if (conceptName.isLocalePreferred()) { preferredNamesFound++; Assert.assertTrue("Found multiple preferred names for conceptId: " + concept.getConceptId() + " in the locale '" + locale + "'", preferredNamesFound < 2); } } } } } } /** * @see {@link ConceptService#saveConcept(Concept)} */ @Test @Verifies(value = "should set a preferred name for each locale if none is marked", method = "saveConcept(Concept)") public void saveConcept_shouldSetAPreferredNameForEachLocaleIfNoneIsMarked() throws Exception { //add some other locales to locale.allowed.list for testing purposes GlobalProperty gp = Context.getAdministrationService().getGlobalPropertyObject( OpenmrsConstants.GLOBAL_PROPERTY_LOCALE_ALLOWED_LIST); gp.setPropertyValue(gp.getPropertyValue().concat(",fr,ja")); Context.getAdministrationService().saveGlobalProperty(gp); Concept concept = new Concept(); concept.addName(new ConceptName("name1", Locale.ENGLISH)); concept.addName(new ConceptName("name2", Locale.ENGLISH)); concept.addName(new ConceptName("name3", Locale.FRENCH)); concept.addName(new ConceptName("name4", Locale.FRENCH)); concept.addName(new ConceptName("name5", Locale.JAPANESE)); concept.addName(new ConceptName("name6", Locale.JAPANESE)); concept = Context.getConceptService().saveConcept(concept); Assert.assertNotNull(concept.getPreferredName(Locale.ENGLISH)); Assert.assertNotNull(concept.getPreferredName(Locale.FRENCH)); Assert.assertNotNull(concept.getPreferredName(Locale.JAPANESE)); } /** * @see ConceptService#mapConceptProposalToConcept(ConceptProposal,Concept) * @verifies not require mapped concept on reject action */ @Test public void mapConceptProposalToConcept_shouldNotRequireMappedConceptOnRejectAction() throws Exception { String uuid = "af4ae460-0e2b-11e0-a94b-469c3c5a0c2f"; ConceptProposal proposal = Context.getConceptService().getConceptProposalByUuid(uuid); Assert.assertNotNull("could not find proposal " + uuid, proposal); proposal.setState(OpenmrsConstants.CONCEPT_PROPOSAL_REJECT); try { Context.getConceptService().mapConceptProposalToConcept(proposal, null); } catch (APIException ex) { Assert.fail("cought APIException when rejecting a proposal with null mapped concept"); } } /** * @see ConceptService#mapConceptProposalToConcept(ConceptProposal,Concept) * @verifies allow rejecting proposals */ @Test public void mapConceptProposalToConcept_shouldAllowRejectingProposals() throws Exception { String uuid = "af4ae460-0e2b-11e0-a94b-469c3c5a0c2f"; ConceptProposal proposal = Context.getConceptService().getConceptProposalByUuid(uuid); Assert.assertNotNull("could not find proposal " + uuid, proposal); //because there is a different unit test for the case when mapped proposal is null, we use a non-null concept here for our testing Concept concept = conceptService.getConcept(3); Assert.assertNotNull("could not find target concept to use for the test", concept); proposal.setState(OpenmrsConstants.CONCEPT_PROPOSAL_REJECT); Context.getConceptService().mapConceptProposalToConcept(proposal, concept); //retrieve the proposal from the model and check its new state ConceptProposal persisted = Context.getConceptService().getConceptProposalByUuid(uuid); Assert.assertEquals(OpenmrsConstants.CONCEPT_PROPOSAL_REJECT, persisted.getState()); } /** * @see {@link * ConceptService#getConcepts(String,List<Locale>,null,List<ConceptClass>,List<ConceptClass * >,List<ConceptDatatype>,List<ConceptDatatype>,Concept,Integer,Integer)} */ @Test @Ignore @Verifies(value = "should return concept search results that match unique concepts", method = "getConcepts(String,List<Locale>,null,List<ConceptClass>,List<ConceptClass>,List<ConceptDatatype>,List<ConceptDatatype>,Concept,Integer,Integer)") public void getConcepts_shouldReturnConceptSearchResultsThatMatchUniqueConcepts() throws Exception { executeDataSet("org/openmrs/api/include/ConceptServiceTest-words.xml"); List<ConceptSearchResult> searchResults = conceptService.getConcepts("cd4", Collections .singletonList(Locale.ENGLISH), false, null, null, null, null, null, null, null); Set<Concept> uniqueConcepts = new HashSet<Concept>(); - //TODO H2 requires cannot execute the generated SQL in the DAO layer + //TODO H2 cannot execute the generated SQL because it requires all fetched columns to be included in the group by clause for (ConceptSearchResult conceptSearchResult : searchResults) { //if this fails, then a duplicate concept has been returned Assert.assertEquals(true, uniqueConcepts.add(conceptSearchResult.getConcept())); } } }
false
false
null
null
diff --git a/src/com/android/contacts/list/ContactPhotoLoader.java b/src/com/android/contacts/list/ContactPhotoLoader.java index 8681a4a28..83e9131ab 100644 --- a/src/com/android/contacts/list/ContactPhotoLoader.java +++ b/src/com/android/contacts/list/ContactPhotoLoader.java @@ -1,475 +1,479 @@ /* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.contacts.list; import com.google.android.collect.Lists; import android.content.ContentResolver; import android.content.Context; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Handler; import android.os.Handler.Callback; import android.os.HandlerThread; import android.os.Message; import android.provider.ContactsContract.Contacts.Photo; import android.provider.ContactsContract.Data; import android.util.Log; import android.widget.ImageView; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.lang.ref.SoftReference; import java.util.ArrayList; import java.util.Iterator; import java.util.concurrent.ConcurrentHashMap; /** * Asynchronously loads contact photos and maintains cache of photos. The class is * mostly single-threaded. The only two methods accessed by the loader thread are * {@link #cacheBitmap} and {@link #obtainPhotoIdsAndUrisToLoad}. Those methods access concurrent * hash maps shared with the main thread. */ public class ContactPhotoLoader implements Callback { private static final String TAG = "ContactPhotoLoader"; private static final String LOADER_THREAD_NAME = "ContactPhotoLoader"; /** * Type of message sent by the UI thread to itself to indicate that some photos * need to be loaded. */ private static final int MESSAGE_REQUEST_LOADING = 1; /** * Type of message sent by the loader thread to indicate that some photos have * been loaded. */ private static final int MESSAGE_PHOTOS_LOADED = 2; private static final String[] EMPTY_STRING_ARRAY = new String[0]; private final String[] COLUMNS = new String[] { Photo._ID, Photo.PHOTO }; /** * The resource ID of the image to be used when the photo is unavailable or being * loaded. */ private final int mDefaultResourceId; /** * Maintains the state of a particular photo. */ private static class BitmapHolder { private static final int NEEDED = 0; private static final int LOADING = 1; private static final int LOADED = 2; int state; SoftReference<Bitmap> bitmapRef; } /** * A soft cache for photos. */ private final ConcurrentHashMap<Object, BitmapHolder> mBitmapCache = new ConcurrentHashMap<Object, BitmapHolder>(); /** * A map from ImageView to the corresponding photo ID. Please note that this * photo ID may change before the photo loading request is started. */ private final ConcurrentHashMap<ImageView, Object> mPendingRequests = new ConcurrentHashMap<ImageView, Object>(); /** * Handler for messages sent to the UI thread. */ private final Handler mMainThreadHandler = new Handler(this); /** * Thread responsible for loading photos from the database. Created upon * the first request. */ private LoaderThread mLoaderThread; /** * A gate to make sure we only send one instance of MESSAGE_PHOTOS_NEEDED at a time. */ private boolean mLoadingRequested; /** * Flag indicating if the image loading is paused. */ private boolean mPaused; private final Context mContext; /** * Constructor. * * @param context content context * @param defaultResourceId the image resource ID to be used when there is * no photo for a contact */ public ContactPhotoLoader(Context context, int defaultResourceId) { mDefaultResourceId = defaultResourceId; mContext = context; } /** * Load photo into the supplied image view. If the photo is already cached, * it is displayed immediately. Otherwise a request is sent to load the photo * from the database. */ public void loadPhoto(ImageView view, long photoId) { if (photoId == 0) { // No photo is needed view.setImageResource(mDefaultResourceId); mPendingRequests.remove(view); } else { loadPhotoByIdOrUri(view, photoId); } } /** * Load photo into the supplied image view. If the photo is already cached, * it is displayed immediately. Otherwise a request is sent to load the photo * from the location specified by the URI. */ public void loadPhoto(ImageView view, Uri photoUri) { if (photoUri == null) { // No photo is needed view.setImageResource(mDefaultResourceId); mPendingRequests.remove(view); } else { loadPhotoByIdOrUri(view, photoUri); } } private void loadPhotoByIdOrUri(ImageView view, Object key) { boolean loaded = loadCachedPhoto(view, key); if (loaded) { mPendingRequests.remove(view); } else { mPendingRequests.put(view, key); if (!mPaused) { // Send a request to start loading photos requestLoading(); } } } /** * Checks if the photo is present in cache. If so, sets the photo on the view, * otherwise sets the state of the photo to {@link BitmapHolder#NEEDED} and * temporarily set the image to the default resource ID. */ private boolean loadCachedPhoto(ImageView view, Object key) { BitmapHolder holder = mBitmapCache.get(key); if (holder == null) { holder = new BitmapHolder(); mBitmapCache.put(key, holder); } else if (holder.state == BitmapHolder.LOADED) { // Null bitmap reference means that database contains no bytes for the photo if (holder.bitmapRef == null) { view.setImageResource(mDefaultResourceId); return true; } Bitmap bitmap = holder.bitmapRef.get(); if (bitmap != null) { view.setImageBitmap(bitmap); return true; } // Null bitmap means that the soft reference was released by the GC // and we need to reload the photo. holder.bitmapRef = null; } // The bitmap has not been loaded - should display the placeholder image. view.setImageResource(mDefaultResourceId); holder.state = BitmapHolder.NEEDED; return false; } /** * Stops loading images, kills the image loader thread and clears all caches. */ public void stop() { pause(); if (mLoaderThread != null) { mLoaderThread.quit(); mLoaderThread = null; } mPendingRequests.clear(); mBitmapCache.clear(); } public void clear() { mPendingRequests.clear(); mBitmapCache.clear(); } /** * Temporarily stops loading photos from the database. */ public void pause() { mPaused = true; } /** * Resumes loading photos from the database. */ public void resume() { mPaused = false; if (!mPendingRequests.isEmpty()) { requestLoading(); } } /** * Sends a message to this thread itself to start loading images. If the current * view contains multiple image views, all of those image views will get a chance * to request their respective photos before any of those requests are executed. * This allows us to load images in bulk. */ private void requestLoading() { if (!mLoadingRequested) { mLoadingRequested = true; mMainThreadHandler.sendEmptyMessage(MESSAGE_REQUEST_LOADING); } } /** * Processes requests on the main thread. */ public boolean handleMessage(Message msg) { switch (msg.what) { case MESSAGE_REQUEST_LOADING: { mLoadingRequested = false; if (!mPaused) { if (mLoaderThread == null) { mLoaderThread = new LoaderThread(mContext.getContentResolver()); mLoaderThread.start(); } mLoaderThread.requestLoading(); } return true; } case MESSAGE_PHOTOS_LOADED: { if (!mPaused) { processLoadedImages(); } return true; } } return false; } /** * Goes over pending loading requests and displays loaded photos. If some of the * photos still haven't been loaded, sends another request for image loading. */ private void processLoadedImages() { Iterator<ImageView> iterator = mPendingRequests.keySet().iterator(); while (iterator.hasNext()) { ImageView view = iterator.next(); Object key = mPendingRequests.get(view); boolean loaded = loadCachedPhoto(view, key); if (loaded) { iterator.remove(); } } if (!mPendingRequests.isEmpty()) { requestLoading(); } } /** * Stores the supplied bitmap in cache. */ private void cacheBitmap(Object key, byte[] bytes) { if (mPaused) { return; } BitmapHolder holder = new BitmapHolder(); holder.state = BitmapHolder.LOADED; if (bytes != null) { try { Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length, null); holder.bitmapRef = new SoftReference<Bitmap>(bitmap); } catch (OutOfMemoryError e) { // Do nothing - the photo will appear to be missing } } mBitmapCache.put(key, holder); } /** * Populates an array of photo IDs that need to be loaded. */ private void obtainPhotoIdsAndUrisToLoad(ArrayList<Long> photoIds, ArrayList<String> photoIdsAsStrings, ArrayList<Uri> uris) { photoIds.clear(); photoIdsAsStrings.clear(); + uris.clear(); /* * Since the call is made from the loader thread, the map could be * changing during the iteration. That's not really a problem: * ConcurrentHashMap will allow those changes to happen without throwing * exceptions. Since we may miss some requests in the situation of * concurrent change, we will need to check the map again once loading * is complete. */ Iterator<Object> iterator = mPendingRequests.values().iterator(); while (iterator.hasNext()) { Object key = iterator.next(); BitmapHolder holder = mBitmapCache.get(key); if (holder != null && holder.state == BitmapHolder.NEEDED) { // Assuming atomic behavior holder.state = BitmapHolder.LOADING; if (key instanceof Long) { photoIds.add((Long)key); photoIdsAsStrings.add(key.toString()); } else { uris.add((Uri)key); } } } } /** * The thread that performs loading of photos from the database. */ private class LoaderThread extends HandlerThread implements Callback { private static final int BUFFER_SIZE = 1024*16; private final ContentResolver mResolver; private final StringBuilder mStringBuilder = new StringBuilder(); private final ArrayList<Long> mPhotoIds = Lists.newArrayList(); private final ArrayList<String> mPhotoIdsAsStrings = Lists.newArrayList(); private final ArrayList<Uri> mPhotoUris = Lists.newArrayList(); private Handler mLoaderThreadHandler; private byte mBuffer[]; public LoaderThread(ContentResolver resolver) { super(LOADER_THREAD_NAME); mResolver = resolver; } /** * Sends a message to this thread to load requested photos. */ public void requestLoading() { if (mLoaderThreadHandler == null) { mLoaderThreadHandler = new Handler(getLooper(), this); } mLoaderThreadHandler.sendEmptyMessage(0); } /** * Receives the above message, loads photos and then sends a message * to the main thread to process them. */ public boolean handleMessage(Message msg) { loadPhotosFromDatabase(); return true; } private void loadPhotosFromDatabase() { obtainPhotoIdsAndUrisToLoad(mPhotoIds, mPhotoIdsAsStrings, mPhotoUris); int count = mPhotoIds.size(); if (count != 0) { mStringBuilder.setLength(0); mStringBuilder.append(Photo._ID + " IN("); for (int i = 0; i < count; i++) { if (i != 0) { mStringBuilder.append(','); } mStringBuilder.append('?'); } mStringBuilder.append(')'); Cursor cursor = null; try { cursor = mResolver.query(Data.CONTENT_URI, COLUMNS, mStringBuilder.toString(), mPhotoIdsAsStrings.toArray(EMPTY_STRING_ARRAY), null); if (cursor != null) { while (cursor.moveToNext()) { Long id = cursor.getLong(0); byte[] bytes = cursor.getBlob(1); cacheBitmap(id, bytes); mPhotoIds.remove(id); } } } finally { if (cursor != null) { cursor.close(); } } // Remaining photos were not found in the database - mark the cache accordingly. count = mPhotoIds.size(); for (int i = 0; i < count; i++) { cacheBitmap(mPhotoIds.get(i), null); } mMainThreadHandler.sendEmptyMessage(MESSAGE_PHOTOS_LOADED); } count = mPhotoUris.size(); for (int i = 0; i < count; i++) { Uri uri = mPhotoUris.get(i); if (mBuffer == null) { mBuffer = new byte[BUFFER_SIZE]; } try { InputStream is = mResolver.openInputStream(uri); if (is != null) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { int size; while ((size = is.read(mBuffer)) != -1) { baos.write(mBuffer, 0, size); } } finally { is.close(); } cacheBitmap(uri, baos.toByteArray()); mMainThreadHandler.sendEmptyMessage(MESSAGE_PHOTOS_LOADED); + } else { + Log.v(TAG, "Cannot load photo " + uri); + cacheBitmap(uri, null); } } catch (Exception ex) { Log.v(TAG, "Cannot load photo " + uri, ex); cacheBitmap(uri, null); } } } } }
false
false
null
null
diff --git a/src/main/java/hudson/maven/MojoInfo.java b/src/main/java/hudson/maven/MojoInfo.java index 92aadeb..6777338 100644 --- a/src/main/java/hudson/maven/MojoInfo.java +++ b/src/main/java/hudson/maven/MojoInfo.java @@ -1,244 +1,245 @@ /* * The MIT License * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package hudson.maven; import org.apache.maven.plugin.MojoExecution; import org.apache.maven.plugin.Mojo; import org.apache.maven.plugin.descriptor.PluginDescriptor; import org.codehaus.classworlds.ClassRealm; import org.codehaus.plexus.configuration.PlexusConfiguration; import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluator; import org.codehaus.plexus.component.configurator.converters.lookup.ConverterLookup; import org.codehaus.plexus.component.configurator.converters.lookup.DefaultConverterLookup; import org.codehaus.plexus.component.configurator.converters.ConfigurationConverter; import org.codehaus.plexus.component.configurator.ComponentConfigurationException; import java.io.File; import java.lang.reflect.Field; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Proxy; import java.lang.reflect.Method; import hudson.util.InvocationInterceptor; import hudson.util.ReflectionUtils; /** * Information about Mojo to be executed. This object provides * convenient access to various mojo information, so that {@link MavenReporter} * implementations are shielded to some extent from Maven internals. * * <p> * For each mojo to be executed, this object is created and passed to * {@link MavenReporter}. * * @author Kohsuke Kawaguchi * @see MavenReporter * @see MavenReportInfo */ public class MojoInfo { /** * Object from Maven that describes the Mojo to be executed. */ public final MojoExecution mojoExecution; /** * PluginName of the plugin that contains this mojo. */ public final PluginName pluginName; /** * Mojo object that carries out the actual execution. */ public final Mojo mojo; /** * Configuration of the mojo for the current execution. * This reflects the default values, as well as values configured from POM, * including inherited values. */ public final PlexusConfiguration configuration; /** * Object that Maven uses to resolve variables like "${project}" to its * corresponding object. */ public final ExpressionEvaluator expressionEvaluator; /** * Used to obtain a value from {@link PlexusConfiguration} as a typed object, * instead of String. */ private final ConverterLookup converterLookup = new DefaultConverterLookup(); public MojoInfo(MojoExecution mojoExecution, Mojo mojo, PlexusConfiguration configuration, ExpressionEvaluator expressionEvaluator) { if (mojo==null) throw new IllegalArgumentException(); // TODO: exactly what other variables are always non-null? this.mojo = mojo; this.mojoExecution = mojoExecution; this.configuration = configuration; this.expressionEvaluator = expressionEvaluator; this.pluginName = new PluginName(mojoExecution.getMojoDescriptor().getPluginDescriptor()); } /** * Gets the goal name of the mojo to be executed, * such as "javadoc". This is local to the plugin name. */ public String getGoal() { return mojoExecution.getMojoDescriptor().getGoal(); } /** * Obtains the configuration value of the mojo. * * @param configName * The name of the child element in the &lt;configuration> of mojo. * @param type * The Java class of the configuration value. While every element * can be read as {@link String}, often different types have a different * conversion rules associated with it (for example, {@link File} would * resolve relative path against POM base directory.) * * @return * The configuration value either specified in POM, or inherited from * parent POM, or default value if one is specified in mojo. * * @throws ComponentConfigurationException * Not sure when exactly this is thrown, but it's probably when * the configuration in POM is syntactically incorrect. */ public <T> T getConfigurationValue(String configName, Class<T> type) throws ComponentConfigurationException { PlexusConfiguration child = configuration.getChild(configName); if(child==null) return null; // no such config ClassLoader cl; PluginDescriptor pd = mojoExecution.getMojoDescriptor().getPluginDescriptor(); // for maven2 builds ClassRealm doesn't extends ClassLoader ! // so check stuff with reflection Method method = ReflectionUtils.getPublicMethodNamed( pd.getClass(), "getClassRealm" ); if ( ReflectionUtils.invokeMethod( method, pd ) instanceof ClassRealm) { ClassRealm cr = (ClassRealm) ReflectionUtils.invokeMethod( method, pd ); cl = cr.getClassLoader(); } else { cl = mojoExecution.getMojoDescriptor().getPluginDescriptor().getClassRealm(); } ConfigurationConverter converter = converterLookup.lookupConverterForType(type); return type.cast(converter.fromConfiguration(converterLookup,child,type, // the implementation seems to expect the type of the bean for which the configuration is done // in this parameter, but we have no such type. So passing in a dummy Object.class, cl, expressionEvaluator)); } /** * Returns true if this {@link MojoInfo} wraps the mojo of the given ID tuple. */ public boolean is(String groupId, String artifactId, String mojoName) { return pluginName.matches(groupId,artifactId) && getGoal().equals(mojoName); } /** * Injects the specified value (designated by the specified field name) into the mojo, * and returns its old value. * * @throws NoSuchFieldException * if the mojo doesn't have any field of the given name. * @since 1.232 */ public <T> T inject(String name, T value) throws NoSuchFieldException { for(Class c=mojo.getClass(); c!=Object.class; c=c.getSuperclass()) { try { Field f = c.getDeclaredField(name); f.setAccessible(true); Object oldValue = f.get(mojo); f.set(mojo,value); + return (T)oldValue; } catch (NoSuchFieldException e) { continue; } catch (IllegalAccessException e) { // shouldn't happen because we made it accessible IllegalAccessError x = new IllegalAccessError(e.getMessage()); x.initCause(e); throw x; } } throw new NoSuchFieldException(name); } /** * Intercept the invocation from the mojo to its injected component (designated by the given field name.) * * <p> * Often for a {@link MavenReporter} to really figure out what's going on in a build, you'd like * to intercept one of the components that Maven is injecting into the mojo, and inspect its parameter * and return values. * * <p> * This mehod provides a way to do this. You specify the name of the field in the Mojo class that receives * the injected component, then pass in {@link InvocationInterceptor}, which will in turn be invoked * for every invocation on that component. * * @throws NoSuchFieldException * if the specified field is not found on the mojo class, or it is found but the type is not an interface. * @since 1.232 */ public void intercept(String fieldName, final InvocationInterceptor interceptor) throws NoSuchFieldException { for(Class c=mojo.getClass(); c!=Object.class; c=c.getSuperclass()) { Field f; try { f = c.getDeclaredField(fieldName); } catch (NoSuchFieldException e) { continue; } f.setAccessible(true); Class<?> type = f.getType(); if(!type.isInterface()) throw new NoSuchFieldException(fieldName+" is of type "+type+" and it's not an interface"); try { final Object oldObject = f.get(mojo); Object newObject = Proxy.newProxyInstance(type.getClassLoader(), new Class[]{type}, new InvocationHandler() { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { return interceptor.invoke(proxy,method,args,new InvocationHandler() { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { return method.invoke(oldObject,args); } }); } }); f.set(mojo,newObject); } catch (IllegalAccessException e) { // shouldn't happen because we made it accessible IllegalAccessError x = new IllegalAccessError(e.getMessage()); x.initCause(e); throw x; } } } }
true
false
null
null
diff --git a/src/test/java/com/tngtech/configbuilder/ConfigBuilderTest.java b/src/test/java/com/tngtech/configbuilder/ConfigBuilderTest.java index 07f748a..dbf3878 100644 --- a/src/test/java/com/tngtech/configbuilder/ConfigBuilderTest.java +++ b/src/test/java/com/tngtech/configbuilder/ConfigBuilderTest.java @@ -1,101 +1,114 @@ package com.tngtech.configbuilder; import com.tngtech.configbuilder.annotationhandlers.AnnotationProcessor; import com.tngtech.configbuilder.annotations.PropertiesFile; import com.tngtech.configbuilder.impl.ConfigBuilderContext; import com.tngtech.propertyloader.PropertyLoader; +import com.tngtech.propertyloader.impl.PropertyLocation; +import com.tngtech.propertyloader.impl.PropertySuffix; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Matchers; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import java.lang.reflect.Field; import java.util.Properties; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.*; @RunWith(MockitoJUnitRunner.class) public class ConfigBuilderTest { private ConfigBuilder<Config> configBuilder; private Properties properties; - private Properties errors; @Mock private AnnotationProcessor annotationProcessor; @Mock private ConfigBuilderContext builderContext; @Mock private MiscFactory miscFactory; @Mock private PropertyLoader propertyLoader; + @Mock + private PropertySuffix propertySuffix; + + @Mock + private PropertyLocation propertyLocation; + @Before public void setUp(){ configBuilder = new ConfigBuilder<>(annotationProcessor, builderContext, miscFactory); properties = new Properties(); + when(builderContext.getPropertyLoader()).thenReturn(propertyLoader); + when(miscFactory.createPropertyLoader()).thenReturn(propertyLoader); + when(propertyLoader.getSuffixes()).thenReturn(propertySuffix); + when(propertyLoader.getLocations()).thenReturn(propertyLocation); + when(propertyLocation.atDefaultLocations()).thenReturn(propertyLocation); + when(propertySuffix.addDefaultConfig()).thenReturn(propertySuffix); when(annotationProcessor.loadProperties(Matchers.any(PropertiesFile.class))).thenReturn(properties); } @Test public void testWithCommandLineArguments() throws ParseException { String[] args = new String[]{"-u", "Mueller"}; Options options = mock(Options.class); when(miscFactory.createOptions()).thenReturn(options); CommandLineParser parser = mock(CommandLineParser.class); when(miscFactory.createCommandLineParser()).thenReturn(parser); CommandLine commandLine = mock(CommandLine.class); when(parser.parse(options, args)).thenReturn(commandLine); configBuilder.forClass(Config.class).withCommandLineArgs(args); verify(options).addOption("u", true, ""); verify(options).addOption("p", true, ""); verify(builderContext).setCommandLineArgs(commandLine); } @Test public void testThatForClassSetsClassToConfigBuilderAndReturnsConfigBuilder(){ assertEquals(configBuilder, configBuilder.forClass(Config.class)); assertEquals(configBuilder.getConfigClass(), Config.class); } @Test public void testThatForClassGetsFields(){ Field[] configFields = Config.class.getDeclaredFields(); configBuilder.forClass(Config.class); for(Field field : configFields) { assertTrue(configBuilder.getFields().contains(field)); } } @Test public void testThatForClassLoadsProperties(){ configBuilder.forClass(Config.class); - verify(annotationProcessor, times(2)).loadProperties(Matchers.any(PropertiesFile.class)); + verify(annotationProcessor).loadProperties(Matchers.any(PropertiesFile.class)); verify(builderContext).setProperties(properties); } }
false
false
null
null
diff --git a/HttpdConfigParser/src/org/akquinet/audit/bsi/httpd/Quest5b.java b/HttpdConfigParser/src/org/akquinet/audit/bsi/httpd/Quest5b.java index 4f80045..619a8fd 100644 --- a/HttpdConfigParser/src/org/akquinet/audit/bsi/httpd/Quest5b.java +++ b/HttpdConfigParser/src/org/akquinet/audit/bsi/httpd/Quest5b.java @@ -1,73 +1,77 @@ package org.akquinet.audit.bsi.httpd; import java.util.LinkedList; import java.util.List; import org.akquinet.audit.FormattedConsole; import org.akquinet.audit.YesNoQuestion; import org.akquinet.httpd.ConfigFile; import org.akquinet.httpd.syntax.Directive; public class Quest5b implements YesNoQuestion { private static final String _id = "Quest5b"; private ConfigFile _conf; private static final FormattedConsole _console = FormattedConsole.getDefault(); private static final FormattedConsole.OutputLevel _level = FormattedConsole.OutputLevel.Q2; public Quest5b(ConfigFile conf) { _conf = conf; } /** * Looking for AllowOverride-directives. Checking whether there is no with parameters other than None and at least one * in global context with parameter None. */ @Override public boolean answer() { List<Directive> dirList = _conf.getDirective("AllowOverride"); List<Directive> problems = new LinkedList<Directive>(); - boolean isSetGlobal = false; //will be changed if at least one directive in global context is found + boolean isSetGlobalRoot = false; //will be changed if at least one directive in global context is found for (Directive directive : dirList) { - if(!directive.getValue().matches("( |\t)*None( |\t)*")) + if(!directive.getValue().matches("[ \t]*None[ \t]*")) { problems.add(directive); } - else if(directive.getSurroundingContexts().get(0) == null) + else if(directive.getSurroundingContexts().size() == 2) //that means one real context and one context being null (i.e. global context) { - isSetGlobal = true; + if(directive.getSurroundingContexts().get(0).getName().equalsIgnoreCase("directory") && + directive.getSurroundingContexts().get(0).getValue().matches("[ \t]*/[ \t]*")) + { + isSetGlobalRoot = true; + } } } - String global = isSetGlobal ? - "Directive \"AllowOverride None\" is correctly stated in global context." : - "You haven't stated the directive \"AllowOverride None\" in global context."; + String global = isSetGlobalRoot ? + "Directive \"AllowOverride None\" is correctly stated in context for root directory being in global context." : + "You haven't stated the directive \"AllowOverride None\" in a directory context for the root directory which is itself placed in global context."; String overrides = problems.isEmpty() ? "Directive \"AllowOverride\" correctly doesn't appear with a parameter other than \"None\"" : "You have stated the directive \"AllowOverrid\" with parameters other than \"None\". Remove these:"; - _console.printAnswer(_level, isSetGlobal & problems.isEmpty(), global + " " + overrides); + _console.printAnswer(_level, isSetGlobalRoot & problems.isEmpty(), global + " " + overrides); for (Directive directive : problems) { _console.println(_level, "line " + directive.getLinenumber() + ": " + directive.getName() + " " + directive.getValue()); } - return isSetGlobal && problems.isEmpty(); + return isSetGlobalRoot && problems.isEmpty(); } - + @Override public boolean isCritical() { //Quest5 is critical, this is a subquestion so this is handled by Quest5 return false; } @Override public String getID() { return _id; } }
false
false
null
null
diff --git a/src/main/java/net/caseydunham/coderwall/service/impl/CoderWallImpl.java b/src/main/java/net/caseydunham/coderwall/service/impl/CoderWallImpl.java index af1cbdf..fe24cfe 100644 --- a/src/main/java/net/caseydunham/coderwall/service/impl/CoderWallImpl.java +++ b/src/main/java/net/caseydunham/coderwall/service/impl/CoderWallImpl.java @@ -1,46 +1,47 @@ package net.caseydunham.coderwall.service.impl; import com.google.gson.Gson; import net.caseydunham.coderwall.data.User; import net.caseydunham.coderwall.exception.CoderWallException; import net.caseydunham.coderwall.service.CoderWall; +import javax.net.ssl.HttpsURLConnection; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; public class CoderWallImpl implements CoderWall { - private static final String API_URL = "http://www.coderwall.com/"; + private static final String API_URL = "https://www.coderwall.com/"; private static final String FORMAT = ".json"; public CoderWallImpl() { } public User getUser(final String username) throws CoderWallException { return getUser(username, true); } public User getUser(final String username, final boolean full) throws CoderWallException { if (username == null || username.isEmpty()) { throw new CoderWallException("invalid username"); } try { final URL url = new URL(API_URL + username + FORMAT + (full ? "?full=true" : "")); - final HttpURLConnection conn = (HttpURLConnection) url.openConnection(); + final HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); int respCode = conn.getResponseCode(); if (respCode != HttpURLConnection.HTTP_OK) { throw new CoderWallException(respCode + " " + conn.getResponseMessage()); } return new Gson().fromJson(new InputStreamReader(conn.getInputStream()), User.class); } catch (final MalformedURLException ex) { throw new CoderWallException(ex); } catch (final IOException ex) { throw new CoderWallException(ex); } } }
false
false
null
null
diff --git a/server/src/main/java/org/apache/accumulo/server/tabletserver/log/TabletServerLogger.java b/server/src/main/java/org/apache/accumulo/server/tabletserver/log/TabletServerLogger.java index 6ca1ad0b5..d3c09f8e8 100644 --- a/server/src/main/java/org/apache/accumulo/server/tabletserver/log/TabletServerLogger.java +++ b/server/src/main/java/org/apache/accumulo/server/tabletserver/log/TabletServerLogger.java @@ -1,428 +1,428 @@ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.accumulo.server.tabletserver.log; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import org.apache.accumulo.core.conf.Property; import org.apache.accumulo.core.data.KeyExtent; import org.apache.accumulo.core.data.Mutation; import org.apache.accumulo.core.util.UtilWaitThread; import org.apache.accumulo.server.tabletserver.Tablet; import org.apache.accumulo.server.tabletserver.Tablet.CommitSession; import org.apache.accumulo.server.tabletserver.TabletMutations; import org.apache.accumulo.server.tabletserver.TabletServer; import org.apache.accumulo.server.tabletserver.log.DfsLogger.LoggerOperation; import org.apache.log4j.Logger; /** * Central logging facility for the TServerInfo. * * Forwards in-memory updates to remote logs, carefully writing the same data to every log, while maintaining the maximum thread parallelism for greater * performance. As new logs are used and minor compactions are performed, the metadata table is kept up-to-date. * */ public class TabletServerLogger { private static final Logger log = Logger.getLogger(TabletServerLogger.class); private final AtomicLong logSizeEstimate = new AtomicLong(); private final long maxSize; private final TabletServer tserver; // The current log set: always updated to a new set with every change of loggers private final List<DfsLogger> loggers = new ArrayList<DfsLogger>(); // The current generation of logSet. // Because multiple threads can be using a log set at one time, a log // failure is likely to affect multiple threads, who will all attempt to // create a new logSet. This will cause many unnecessary updates to the // metadata table. // We'll use this generational counter to determine if another thread has // already fetched a new logSet. private AtomicInteger logSetId = new AtomicInteger(); // Use a ReadWriteLock to allow multiple threads to use the log set, but obtain a write lock to change them private final ReentrantReadWriteLock logSetLock = new ReentrantReadWriteLock(); private final AtomicInteger seqGen = new AtomicInteger(); private static boolean enabled(Tablet tablet) { return tablet.getTableConfiguration().getBoolean(Property.TABLE_WALOG_ENABLED); } private static boolean enabled(CommitSession commitSession) { return enabled(commitSession.getTablet()); } static private abstract class TestCallWithWriteLock { abstract boolean test(); abstract void withWriteLock() throws IOException; } /** * Pattern taken from the documentation for ReentrantReadWriteLock * * @param rwlock * lock to use * @param code * a test/work pair * @throws IOException */ private static void testLockAndRun(final ReadWriteLock rwlock, TestCallWithWriteLock code) throws IOException { // Get a read lock rwlock.readLock().lock(); try { // does some condition exist that needs the write lock? if (code.test()) { // Yes, let go of the readlock rwlock.readLock().unlock(); // Grab the write lock rwlock.writeLock().lock(); try { // double-check the condition, since we let go of the lock if (code.test()) { // perform the work with with write lock held code.withWriteLock(); } } finally { // regain the readlock rwlock.readLock().lock(); // unlock the write lock rwlock.writeLock().unlock(); } } } finally { // always let go of the lock rwlock.readLock().unlock(); } } public TabletServerLogger(TabletServer tserver, long maxSize) { this.tserver = tserver; this.maxSize = maxSize; } private int initializeLoggers(final List<DfsLogger> copy) throws IOException { final int[] result = {-1}; testLockAndRun(logSetLock, new TestCallWithWriteLock() { boolean test() { copy.clear(); copy.addAll(loggers); if (!loggers.isEmpty()) result[0] = logSetId.get(); return loggers.isEmpty(); } void withWriteLock() throws IOException { try { createLoggers(); copy.clear(); copy.addAll(loggers); if (copy.size() > 0) result[0] = logSetId.get(); else result[0] = -1; } catch (IOException e) { log.error("Unable to create loggers", e); } } }); return result[0]; } public void getLoggers(Set<String> loggersOut) { logSetLock.readLock().lock(); try { for (DfsLogger logger : loggers) { loggersOut.add(logger.toString()); } } finally { logSetLock.readLock().unlock(); } } synchronized private void createLoggers() throws IOException { if (!logSetLock.isWriteLockedByCurrentThread()) { throw new IllegalStateException("createLoggers should be called with write lock held!"); } if (loggers.size() != 0) { throw new IllegalStateException("createLoggers should not be called when loggers.size() is " + loggers.size()); } try { DfsLogger alog = new DfsLogger(tserver.getServerConfig()); alog.open(tserver.getClientAddressString()); loggers.add(alog); logSetId.incrementAndGet(); return; } catch (Exception t) { throw new RuntimeException(t); } } public void resetLoggers() throws IOException { logSetLock.writeLock().lock(); try { close(); } finally { logSetLock.writeLock().unlock(); } } synchronized private void close() throws IOException { if (!logSetLock.isWriteLockedByCurrentThread()) { throw new IllegalStateException("close should be called with write lock held!"); } try { for (DfsLogger logger : loggers) { try { logger.close(); } catch (DfsLogger.LogClosedException ex) { // ignore } catch (Throwable ex) { - log.error("Unable to cleanly close log " + logger.getFileName() + ": " + ex); + log.error("Unable to cleanly close log " + logger.getFileName() + ": " + ex, ex); } } loggers.clear(); logSizeEstimate.set(0); } catch (Throwable t) { throw new IOException(t); } } interface Writer { LoggerOperation write(DfsLogger logger, int seq) throws Exception; } private int write(CommitSession commitSession, boolean mincFinish, Writer writer) throws IOException { List<CommitSession> sessions = Collections.singletonList(commitSession); return write(sessions, mincFinish, writer); } private int write(Collection<CommitSession> sessions, boolean mincFinish, Writer writer) throws IOException { // Work very hard not to lock this during calls to the outside world int currentLogSet = logSetId.get(); int seq = -1; int attempt = 0; boolean success = false; while (!success) { try { // get a reference to the loggers that no other thread can touch ArrayList<DfsLogger> copy = new ArrayList<DfsLogger>(); currentLogSet = initializeLoggers(copy); // add the logger to the log set for the memory in the tablet, // update the metadata table if we've never used this tablet if (currentLogSet == logSetId.get()) { for (CommitSession commitSession : sessions) { if (commitSession.beginUpdatingLogsUsed(copy, mincFinish)) { try { // Scribble out a tablet definition and then write to the metadata table defineTablet(commitSession); if (currentLogSet == logSetId.get()) tserver.addLoggersToMetadata(copy, commitSession.getExtent(), commitSession.getLogId()); } finally { commitSession.finishUpdatingLogsUsed(); } } } } // Make sure that the logs haven't changed out from underneath our copy if (currentLogSet == logSetId.get()) { // write the mutation to the logs seq = seqGen.incrementAndGet(); if (seq < 0) throw new RuntimeException("Logger sequence generator wrapped! Onos!!!11!eleven"); ArrayList<LoggerOperation> queuedOperations = new ArrayList<LoggerOperation>(copy.size()); for (DfsLogger wal : copy) { LoggerOperation lop = writer.write(wal, seq); if (lop != null) queuedOperations.add(lop); } for (LoggerOperation lop : queuedOperations) { lop.await(); } // double-check: did the log set change? success = (currentLogSet == logSetId.get()); } } catch (DfsLogger.LogClosedException ex) { log.debug("Logs closed while writing, retrying " + (attempt + 1)); } catch (Exception t) { log.error("Unexpected error writing to log, retrying attempt " + (attempt + 1), t); UtilWaitThread.sleep(100); } finally { attempt++; } // Some sort of write failure occurred. Grab the write lock and reset the logs. // But since multiple threads will attempt it, only attempt the reset when // the logs haven't changed. final int finalCurrent = currentLogSet; if (!success) { testLockAndRun(logSetLock, new TestCallWithWriteLock() { @Override boolean test() { return finalCurrent == logSetId.get(); } @Override void withWriteLock() throws IOException { close(); } }); } } // if the log gets too big, reset it .. grab the write lock first logSizeEstimate.addAndGet(4 * 3); // event, tid, seq overhead testLockAndRun(logSetLock, new TestCallWithWriteLock() { boolean test() { return logSizeEstimate.get() > maxSize; } void withWriteLock() throws IOException { close(); } }); return seq; } public int defineTablet(final CommitSession commitSession) throws IOException { // scribble this into the metadata tablet, too. if (!enabled(commitSession)) return -1; return write(commitSession, false, new Writer() { @Override public LoggerOperation write(DfsLogger logger, int ignored) throws Exception { logger.defineTablet(commitSession.getWALogSeq(), commitSession.getLogId(), commitSession.getExtent()); return null; } }); } public int log(final CommitSession commitSession, final int tabletSeq, final Mutation m) throws IOException { if (!enabled(commitSession)) return -1; int seq = write(commitSession, false, new Writer() { @Override public LoggerOperation write(DfsLogger logger, int ignored) throws Exception { return logger.log(tabletSeq, commitSession.getLogId(), m); } }); logSizeEstimate.addAndGet(m.numBytes()); return seq; } public int logManyTablets(Map<CommitSession,List<Mutation>> mutations) throws IOException { final Map<CommitSession,List<Mutation>> loggables = new HashMap<CommitSession,List<Mutation>>(mutations); for (CommitSession t : mutations.keySet()) { if (!enabled(t)) loggables.remove(t); } if (loggables.size() == 0) return -1; int seq = write(loggables.keySet(), false, new Writer() { @Override public LoggerOperation write(DfsLogger logger, int ignored) throws Exception { List<TabletMutations> copy = new ArrayList<TabletMutations>(loggables.size()); for (Entry<CommitSession,List<Mutation>> entry : loggables.entrySet()) { CommitSession cs = entry.getKey(); copy.add(new TabletMutations(cs.getLogId(), cs.getWALogSeq(), entry.getValue())); } return logger.logManyTablets(copy); } }); for (List<Mutation> entry : loggables.values()) { if (entry.size() < 1) throw new IllegalArgumentException("logManyTablets: logging empty mutation list"); for (Mutation m : entry) { logSizeEstimate.addAndGet(m.numBytes()); } } return seq; } public void minorCompactionFinished(final CommitSession commitSession, final String fullyQualifiedFileName, final int walogSeq) throws IOException { if (!enabled(commitSession)) return; long t1 = System.currentTimeMillis(); int seq = write(commitSession, true, new Writer() { @Override public LoggerOperation write(DfsLogger logger, int ignored) throws Exception { logger.minorCompactionFinished(walogSeq, commitSession.getLogId(), fullyQualifiedFileName).await(); return null; } }); long t2 = System.currentTimeMillis(); log.debug(" wrote MinC finish " + seq + ": writeTime:" + (t2 - t1) + "ms "); } public int minorCompactionStarted(final CommitSession commitSession, final int seq, final String fullyQualifiedFileName) throws IOException { if (!enabled(commitSession)) return -1; write(commitSession, false, new Writer() { @Override public LoggerOperation write(DfsLogger logger, int ignored) throws Exception { logger.minorCompactionStarted(seq, commitSession.getLogId(), fullyQualifiedFileName).await(); return null; } }); return seq; } public void recover(Tablet tablet, List<String> logs, Set<String> tabletFiles, MutationReceiver mr) throws IOException { if (!enabled(tablet)) return; try { SortedLogRecovery recovery = new SortedLogRecovery(); KeyExtent extent = tablet.getExtent(); recovery.recover(extent, logs, tabletFiles, mr); } catch (Exception e) { throw new IOException(e); } } }
true
false
null
null
diff --git a/q-web/src/main/java/q/web/login/AddLogin.java b/q-web/src/main/java/q/web/login/AddLogin.java index d503ec5f..68ba905e 100644 --- a/q-web/src/main/java/q/web/login/AddLogin.java +++ b/q-web/src/main/java/q/web/login/AddLogin.java @@ -1,64 +1,64 @@ /** * */ package q.web.login; import q.dao.PeopleDao; import q.domain.People; import q.web.DefaultResourceContext; import q.web.LoginCookie; import q.web.Resource; import q.web.ResourceContext; import q.web.exception.PeopleLoginPasswordException; import q.web.exception.PeopleNotExistException; /** * @author seanlinwang * @email xalinx at gmail dot com * @date Feb 20, 2011 * */ public class AddLogin extends Resource { private PeopleDao peopleDao; public void setPeopleDao(PeopleDao peopleDao) { this.peopleDao = peopleDao; } /* * (non-Javadoc) * * @see q.web.Resource#execute(q.web.ResourceContext) */ @Override public void execute(ResourceContext context) throws Exception { String email = context.getString("email"); String password = context.getString("password"); People people = this.peopleDao.getPeopleByEmail(email); if (null == people) { throw new PeopleNotExistException("email:邮箱不存在"); } if (!people.getPassword().equals(password)) { throw new PeopleLoginPasswordException("password:密码错误"); } context.setModel("people", people); ((DefaultResourceContext) context).addLoginCookie(new LoginCookie(people.getId(), people.getRealName(), people.getUsername(), people.getAvatarPath())); // set login cookie if (!context.isApiRequest()) { if (context.getString("from") == null) { - context.redirectServletPath(""); + context.redirectServletPath("/"); } } } /* * (non-Javadoc) * * @see q.web.Resource#validate(q.web.ResourceContext) */ @Override public void validate(ResourceContext context) throws Exception { } }
true
true
public void execute(ResourceContext context) throws Exception { String email = context.getString("email"); String password = context.getString("password"); People people = this.peopleDao.getPeopleByEmail(email); if (null == people) { throw new PeopleNotExistException("email:邮箱不存在"); } if (!people.getPassword().equals(password)) { throw new PeopleLoginPasswordException("password:密码错误"); } context.setModel("people", people); ((DefaultResourceContext) context).addLoginCookie(new LoginCookie(people.getId(), people.getRealName(), people.getUsername(), people.getAvatarPath())); // set login cookie if (!context.isApiRequest()) { if (context.getString("from") == null) { context.redirectServletPath(""); } } }
public void execute(ResourceContext context) throws Exception { String email = context.getString("email"); String password = context.getString("password"); People people = this.peopleDao.getPeopleByEmail(email); if (null == people) { throw new PeopleNotExistException("email:邮箱不存在"); } if (!people.getPassword().equals(password)) { throw new PeopleLoginPasswordException("password:密码错误"); } context.setModel("people", people); ((DefaultResourceContext) context).addLoginCookie(new LoginCookie(people.getId(), people.getRealName(), people.getUsername(), people.getAvatarPath())); // set login cookie if (!context.isApiRequest()) { if (context.getString("from") == null) { context.redirectServletPath("/"); } } }
diff --git a/java/src/org/geonames/GeoNamesException.java b/java/src/org/geonames/GeoNamesException.java index 75b2e33..da8a393 100644 --- a/java/src/org/geonames/GeoNamesException.java +++ b/java/src/org/geonames/GeoNamesException.java @@ -1,53 +1,55 @@ /* * Copyright 2011 Marc Wick, geonames.org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.geonames; /** * @author marc * @since 20.01.2011 * */ public class GeoNamesException extends Exception { private static final long serialVersionUID = 746586385626445380L; private String message; private int exceptionCode; public GeoNamesException(int exceptionCode, String msg) { super(msg); + this.message = msg; this.exceptionCode = exceptionCode; } public GeoNamesException(String msg) { super(msg); + this.message=msg; } /** * @return the message */ public String getMessage() { return message; } /** * @return the exceptionCode */ public int getExceptionCode() { return exceptionCode; } }
false
false
null
null
diff --git a/collect/src/main/java/org/calrissian/mango/collect/CloseableIterators.java b/collect/src/main/java/org/calrissian/mango/collect/CloseableIterators.java index 8d96594..03b7759 100644 --- a/collect/src/main/java/org/calrissian/mango/collect/CloseableIterators.java +++ b/collect/src/main/java/org/calrissian/mango/collect/CloseableIterators.java @@ -1,330 +1,330 @@ package org.calrissian.mango.collect; import com.google.common.base.Function; import com.google.common.base.Predicate; import com.google.common.collect.Iterators; import com.google.common.collect.PeekingIterator; import com.google.common.io.Closeables; import java.io.Closeable; import java.io.IOException; import java.util.Iterator; import java.util.NoSuchElementException; import static com.google.common.base.Preconditions.checkNotNull; /** * Utility class to develop commonly used closeable iterator functions. */ public class CloseableIterators { private static final CloseableIterator EMPTY_ITERATOR = wrap(Iterators.emptyIterator()); /** * Returns a closeable iterator that applies {@code function} to each element of {@code * fromIterator}. */ public static <F, T> CloseableIterator<T> transform(CloseableIterator<F> iterator, Function<F, T> function) { return wrap(Iterators.transform(iterator, function), iterator); } /** * /** * Returns a {@code PeekingCloseableIterator} backed by the given closeable iterator. * * Calls to peek do not change the state of the iterator. The subsequent call to next * after peeking will always return the same value. */ public static <T> PeekingCloseableIterator<T> peekingIterator(final CloseableIterator<T> iterator) { final PeekingIterator<T> peeking = Iterators.peekingIterator(iterator); return new PeekingCloseableIterator<T>() { @Override public void closeQuietly() { iterator.closeQuietly(); } @Override public void close() throws IOException { iterator.close(); } @Override public T peek() { return peeking.peek(); } @Override public T next() { return peeking.next(); } @Override public void remove() { peeking.remove(); } @Override public boolean hasNext() { return peeking.hasNext(); } }; } /** * Creates a closeable iterator returning the first {@code limitSize} elements of the * given closeable iterator. If the original closeable iterator does not contain that many * elements, the returned closeable iterator will have the same behavior as the original. */ public static <T> CloseableIterator<T> limit(CloseableIterator<T> iterator, int limitSize) { return wrap(Iterators.limit(iterator, limitSize), iterator); } /** * Returns the elements of {@code unfiltered} that satisfy a predicate. */ public static <T> CloseableIterator<T> filter(CloseableIterator<T> iterator, Predicate<T> filter) { return wrap(Iterators.filter(iterator, filter), iterator); } /** * Calls {@code next()} on {@code iterator}, either {@code numberToAdvance} times * or until {@code hasNext()} returns {@code false}, whichever comes first. */ public static <T> int advance (CloseableIterator<T> iterator, int numberToAdvance) { return Iterators.advance(iterator, numberToAdvance); } /** * Returns an empty closeable iterator. */ @SuppressWarnings("unchecked") public static <T> CloseableIterator<T> emptyIterator() { return (CloseableIterator<T>)EMPTY_ITERATOR; } /** * Combines multiple iterators into a single closeable iterator. The returned * closeable iterator iterates across the elements of each iterator in {@code inputs}. * The input iterators are not polled until necessary. * @param iterators * @param <T> * @return */ public static <T> CloseableIterator<T> concat(CloseableIterator<? extends Iterator<? extends T>> iterators) { return wrap(Iterators.concat(iterators), iterators); } /** * Combines multiple closeable iterators into a single closeable iterator. The returned * closeable iterator iterates across the elements of each closeable iterator in {@code inputs}. * The input iterators are not polled until necessary. * * As each closeable iterator is exhausted, it is closed before moving onto the next closeable * iterator. A call to close on the returned closeable iterator will quietly close all of - * the closeable iterators in {@code inputs} which having been exhausted. + * the closeable iterators in {@code inputs} which have not been exhausted. */ public static <T> CloseableIterator<T> chain(CloseableIterator<? extends T>... iterators) { return chain(Iterators.forArray(iterators)); } /** * Combines multiple closeable iterators into a single closeable iterator. The returned * closeable iterator iterates across the elements of each closeable iterator in {@code inputs}. * The input iterators are not polled until necessary. * * As each closeable iterator is exhausted, it is closed before moving onto the next closeable * iterator. A call to close on the returned closeable iterator will quietly close all of - * the closeable iterators in {@code inputs} which having been exhausted. + * the closeable iterators in {@code inputs} which have not been exhausted. */ public static <T> CloseableIterator<T> chain(final Iterator<? extends CloseableIterator<? extends T>> iterator) { checkNotNull(iterator); return new CloseableIterator<T>() { CloseableIterator<? extends T> curr = emptyIterator(); @Override public void closeQuietly() { Closeables.closeQuietly(this); } @Override public void close() throws IOException { //Close the current one then close all the others if (curr != null) curr.closeQuietly(); while (iterator.hasNext()) iterator.next().closeQuietly(); } @Override public boolean hasNext() { //autoclose will close when the iterator is exhausted while (!curr.hasNext() && iterator.hasNext()) curr = autoClose(iterator.next()); return curr.hasNext(); } @Override public T next() { if (hasNext()) return curr.next(); throw new NoSuchElementException(); } @Override public void remove() { curr.remove(); } }; } /** * If we can assume the closeable iterator is sorted, return the distinct elements. * This only works if the data provided is sorted. */ public static <T> CloseableIterator<T> distinct(final CloseableIterator<T> iterator) { checkNotNull(iterator); return wrap(Iterators2.distinct(iterator), iterator); } /** * Autoclose the iterator when exhausted or if an exception is thrown. It is currently set to protected, so that only * classes in this package can use. */ static <T> CloseableIterator<T> autoClose(final CloseableIterator<? extends T> iterator) { checkNotNull(iterator); return new CloseableIterator<T>() { private boolean closed = false; @Override public void closeQuietly() { Closeables.closeQuietly(this); } @Override public void close() throws IOException { if (closed) return; closed = true; iterator.close(); } @Override public boolean hasNext() { try { if (closed) return false; if (!iterator.hasNext()) { closeQuietly(); return false; } return true; } catch (RuntimeException re) { closeQuietly(); throw re; } } @Override public T next() { if (hasNext()) { try { return iterator.next(); } catch (RuntimeException re) { closeQuietly(); throw re; } } throw new NoSuchElementException(); } @Override public void remove() { try { if (hasNext()) { iterator.remove(); } } catch (RuntimeException re) { closeQuietly(); throw re; } } }; } /** * Creates a {@link CloseableIterator} from a standard iterator. */ public static <T> CloseableIterator<T> wrap(final Iterator<T> iterator) { checkNotNull(iterator); if (iterator instanceof CloseableIterator) return (CloseableIterator<T>) iterator; return new CloseableIterator<T>() { @Override public void closeQuietly() { Closeables.closeQuietly(this); } @Override public void close() throws IOException { if (iterator instanceof Closeable) ((Closeable) iterator).close(); } @Override public boolean hasNext() { return iterator.hasNext(); } @Override public T next() { return iterator.next(); } @Override public void remove() { iterator.remove(); } }; } /** * Creates a {@link CloseableIterable} from a standard iterable, while closing the provided * closeable. * * Intentionally left package private. */ static <T> CloseableIterator<T> wrap(final Iterator<T> iterator, final Closeable closeable) { return new CloseableIterator<T>() { @Override public void closeQuietly() { Closeables.closeQuietly(this); } @Override public void close() throws IOException { closeable.close(); } @Override public boolean hasNext() { return iterator.hasNext(); } @Override public T next() { return iterator.next(); } @Override public void remove() { iterator.remove(); } }; } }
false
false
null
null
diff --git a/src/org/apache/xerces/impl/xs/AttributePSVImpl.java b/src/org/apache/xerces/impl/xs/AttributePSVImpl.java index 8578dcd7..b5b714c9 100644 --- a/src/org/apache/xerces/impl/xs/AttributePSVImpl.java +++ b/src/org/apache/xerces/impl/xs/AttributePSVImpl.java @@ -1,220 +1,221 @@ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.xerces.impl.xs; import org.apache.xerces.impl.xs.util.StringListImpl; import org.apache.xerces.xs.AttributePSVI; import org.apache.xerces.xs.ShortList; import org.apache.xerces.xs.StringList; import org.apache.xerces.xs.XSAttributeDeclaration; import org.apache.xerces.xs.XSConstants; import org.apache.xerces.xs.XSSimpleTypeDefinition; import org.apache.xerces.xs.XSTypeDefinition; /** * Attribute PSV infoset augmentations implementation. * The PSVI information for attributes will be available at the startElement call. * * @xerces.internal * * @author Elena Litani IBM * @version $Id$ */ public class AttributePSVImpl implements AttributePSVI { /** attribute declaration */ protected XSAttributeDeclaration fDeclaration = null; /** type of attribute, simpleType */ protected XSTypeDefinition fTypeDecl = null; /** If this attribute was explicitly given a * value in the original document, this is false; otherwise, it is true */ protected boolean fSpecified = false; /** schema normalized value property */ protected String fNormalizedValue = null; /** schema actual value */ protected Object fActualValue = null; /** schema actual value type */ protected short fActualValueType = XSConstants.UNAVAILABLE_DT; /** actual value types if the value is a list */ protected ShortList fItemValueTypes = null; /** member type definition against which attribute was validated */ protected XSSimpleTypeDefinition fMemberType = null; /** validation attempted: none, partial, full */ protected short fValidationAttempted = AttributePSVI.VALIDATION_NONE; /** validity: valid, invalid, unknown */ protected short fValidity = AttributePSVI.VALIDITY_NOTKNOWN; /** error codes */ protected String[] fErrorCodes = null; /** validation context: could be QName or XPath expression*/ protected String fValidationContext = null; // // AttributePSVI methods // /** * [schema default] * * @return The canonical lexical representation of the declaration's {value constraint} value. * @see <a href="http://www.w3.org/TR/xmlschema-1/#e-schema_default>XML Schema Part 1: Structures [schema default]</a> */ public String getSchemaDefault() { return fDeclaration == null ? null : fDeclaration.getConstraintValue(); } /** * [schema normalized value] * * * @see <a href="http://www.w3.org/TR/xmlschema-1/#e-schema_normalized_value>XML Schema Part 1: Structures [schema normalized value]</a> * @return the normalized value of this item after validation */ public String getSchemaNormalizedValue() { return fNormalizedValue; } /** * [schema specified] * @see <a href="http://www.w3.org/TR/xmlschema-1/#e-schema_specified">XML Schema Part 1: Structures [schema specified]</a> * @return true - value was specified in schema, false - value comes from the infoset */ public boolean getIsSchemaSpecified() { return fSpecified; } /** * Determines the extent to which the document has been validated * * @return return the [validation attempted] property. The possible values are * NO_VALIDATION, PARTIAL_VALIDATION and FULL_VALIDATION */ public short getValidationAttempted() { return fValidationAttempted; } /** * Determine the validity of the node with respect * to the validation being attempted * * @return return the [validity] property. Possible values are: * UNKNOWN_VALIDITY, INVALID_VALIDITY, VALID_VALIDITY */ public short getValidity() { return fValidity; } /** * A list of error codes generated from validation attempts. * Need to find all the possible subclause reports that need reporting * * @return list of error codes */ public StringList getErrorCodes() { - if (fErrorCodes == null) - return null; + if (fErrorCodes == null) { + return StringListImpl.EMPTY_LIST; + } return new StringListImpl(fErrorCodes, fErrorCodes.length); } // This is the only information we can provide in a pipeline. public String getValidationContext() { return fValidationContext; } /** * An item isomorphic to the type definition used to validate this element. * * @return a type declaration */ public XSTypeDefinition getTypeDefinition() { return fTypeDecl; } /** * If and only if that type definition is a simple type definition * with {variety} union, or a complex type definition whose {content type} * is a simple thype definition with {variety} union, then an item isomorphic * to that member of the union's {member type definitions} which actually * validated the element item's normalized value. * * @return a simple type declaration */ public XSSimpleTypeDefinition getMemberTypeDefinition() { return fMemberType; } /** * An item isomorphic to the attribute declaration used to validate * this attribute. * * @return an attribute declaration */ public XSAttributeDeclaration getAttributeDeclaration() { return fDeclaration; } /* (non-Javadoc) * @see org.apache.xerces.xs.ItemPSVI#getActualNormalizedValue() */ public Object getActualNormalizedValue() { return this.fActualValue; } /* (non-Javadoc) * @see org.apache.xerces.xs.ItemPSVI#getActualNormalizedValueType() */ public short getActualNormalizedValueType() { return this.fActualValueType; } /* (non-Javadoc) * @see org.apache.xerces.xs.ItemPSVI#getItemValueTypes() */ public ShortList getItemValueTypes() { return this.fItemValueTypes; } /** * Reset() */ public void reset() { fNormalizedValue = null; fActualValue = null; fActualValueType = XSConstants.UNAVAILABLE_DT; fItemValueTypes = null; fDeclaration = null; fTypeDecl = null; fSpecified = false; fMemberType = null; fValidationAttempted = AttributePSVI.VALIDATION_NONE; fValidity = AttributePSVI.VALIDITY_NOTKNOWN; fErrorCodes = null; fValidationContext = null; } } diff --git a/src/org/apache/xerces/impl/xs/ElementPSVImpl.java b/src/org/apache/xerces/impl/xs/ElementPSVImpl.java index 2ad06664..834011a0 100644 --- a/src/org/apache/xerces/impl/xs/ElementPSVImpl.java +++ b/src/org/apache/xerces/impl/xs/ElementPSVImpl.java @@ -1,275 +1,276 @@ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.xerces.impl.xs; import org.apache.xerces.impl.xs.util.StringListImpl; import org.apache.xerces.xs.ElementPSVI; import org.apache.xerces.xs.ShortList; import org.apache.xerces.xs.StringList; import org.apache.xerces.xs.XSConstants; import org.apache.xerces.xs.XSElementDeclaration; import org.apache.xerces.xs.XSModel; import org.apache.xerces.xs.XSNotationDeclaration; import org.apache.xerces.xs.XSSimpleTypeDefinition; import org.apache.xerces.xs.XSTypeDefinition; /** * Element PSV infoset augmentations implementation. * The following information will be available at the startElement call: * name, namespace, type, notation, validation context * * The following information will be available at the endElement call: * nil, specified, normalized value, member type, validity, error codes, * default * * @xerces.internal * * @author Elena Litani IBM * @version $Id$ */ public class ElementPSVImpl implements ElementPSVI { /** element declaration */ protected XSElementDeclaration fDeclaration = null; /** type of element, could be xsi:type */ protected XSTypeDefinition fTypeDecl = null; /** true if clause 3.2 of Element Locally Valid (Element) (3.3.4) * is satisfied, otherwise false */ protected boolean fNil = false; /** true if the element value was provided by the schema; false otherwise. */ protected boolean fSpecified = false; /** schema normalized value property */ protected String fNormalizedValue = null; /** schema actual value */ protected Object fActualValue = null; /** schema actual value type */ protected short fActualValueType = XSConstants.UNAVAILABLE_DT; /** actual value types if the value is a list */ protected ShortList fItemValueTypes = null; /** http://www.w3.org/TR/xmlschema-1/#e-notation*/ protected XSNotationDeclaration fNotation = null; /** member type definition against which element was validated */ protected XSSimpleTypeDefinition fMemberType = null; /** validation attempted: none, partial, full */ protected short fValidationAttempted = ElementPSVI.VALIDATION_NONE; /** validity: valid, invalid, unknown */ protected short fValidity = ElementPSVI.VALIDITY_NOTKNOWN; /** error codes */ protected String[] fErrorCodes = null; /** validation context: could be QName or XPath expression*/ protected String fValidationContext = null; /** deferred XSModel **/ protected SchemaGrammar[] fGrammars = null; /** the schema information property */ protected XSModel fSchemaInformation = null; // // ElementPSVI methods // /** * [schema default] * * @return The canonical lexical representation of the declaration's {value constraint} value. * @see <a href="http://www.w3.org/TR/xmlschema-1/#e-schema_default>XML Schema Part 1: Structures [schema default]</a> */ public String getSchemaDefault() { return fDeclaration == null ? null : fDeclaration.getConstraintValue(); } /** * [schema normalized value] * * * @see <a href="http://www.w3.org/TR/xmlschema-1/#e-schema_normalized_value>XML Schema Part 1: Structures [schema normalized value]</a> * @return the normalized value of this item after validation */ public String getSchemaNormalizedValue() { return fNormalizedValue; } /** * [schema specified] * @see <a href="http://www.w3.org/TR/xmlschema-1/#e-schema_specified">XML Schema Part 1: Structures [schema specified]</a> * @return true - value was specified in schema, false - value comes from the infoset */ public boolean getIsSchemaSpecified() { return fSpecified; } /** * Determines the extent to which the document has been validated * * @return return the [validation attempted] property. The possible values are * NO_VALIDATION, PARTIAL_VALIDATION and FULL_VALIDATION */ public short getValidationAttempted() { return fValidationAttempted; } /** * Determine the validity of the node with respect * to the validation being attempted * * @return return the [validity] property. Possible values are: * UNKNOWN_VALIDITY, INVALID_VALIDITY, VALID_VALIDITY */ public short getValidity() { return fValidity; } /** * A list of error codes generated from validation attempts. * Need to find all the possible subclause reports that need reporting * * @return Array of error codes */ public StringList getErrorCodes() { - if (fErrorCodes == null) - return null; + if (fErrorCodes == null) { + return StringListImpl.EMPTY_LIST; + } return new StringListImpl(fErrorCodes, fErrorCodes.length); } // This is the only information we can provide in a pipeline. public String getValidationContext() { return fValidationContext; } /** * [nil] * @see <a href="http://www.w3.org/TR/xmlschema-1/#e-nil>XML Schema Part 1: Structures [nil]</a> * @return true if clause 3.2 of Element Locally Valid (Element) (3.3.4) above is satisfied, otherwise false */ public boolean getNil() { return fNil; } /** * [notation] * @see <a href="http://www.w3.org/TR/xmlschema-1/#e-notation>XML Schema Part 1: Structures [notation]</a> * @return The notation declaration. */ public XSNotationDeclaration getNotation() { return fNotation; } /** * An item isomorphic to the type definition used to validate this element. * * @return a type declaration */ public XSTypeDefinition getTypeDefinition() { return fTypeDecl; } /** * If and only if that type definition is a simple type definition * with {variety} union, or a complex type definition whose {content type} * is a simple thype definition with {variety} union, then an item isomorphic * to that member of the union's {member type definitions} which actually * validated the element item's normalized value. * * @return a simple type declaration */ public XSSimpleTypeDefinition getMemberTypeDefinition() { return fMemberType; } /** * An item isomorphic to the element declaration used to validate * this element. * * @return an element declaration */ public XSElementDeclaration getElementDeclaration() { return fDeclaration; } /** * [schema information] * @see <a href="http://www.w3.org/TR/xmlschema-1/#e-schema_information">XML Schema Part 1: Structures [schema information]</a> * @return The schema information property if it's the validation root, * null otherwise. */ public synchronized XSModel getSchemaInformation() { if (fSchemaInformation == null && fGrammars != null) { fSchemaInformation = new XSModelImpl(fGrammars); } return fSchemaInformation; } /* (non-Javadoc) * @see org.apache.xerces.xs.ItemPSVI#getActualNormalizedValue() */ public Object getActualNormalizedValue() { return this.fActualValue; } /* (non-Javadoc) * @see org.apache.xerces.xs.ItemPSVI#getActualNormalizedValueType() */ public short getActualNormalizedValueType() { return this.fActualValueType; } /* (non-Javadoc) * @see org.apache.xerces.xs.ItemPSVI#getItemValueTypes() */ public ShortList getItemValueTypes() { return this.fItemValueTypes; } /** * Reset() should be called in validator startElement(..) method. */ public void reset() { fDeclaration = null; fTypeDecl = null; fNil = false; fSpecified = false; fNotation = null; fMemberType = null; fValidationAttempted = ElementPSVI.VALIDATION_NONE; fValidity = ElementPSVI.VALIDITY_NOTKNOWN; fErrorCodes = null; fValidationContext = null; fNormalizedValue = null; fActualValue = null; fActualValueType = XSConstants.UNAVAILABLE_DT; fItemValueTypes = null; } }
false
false
null
null
diff --git a/container/test-impl-base/src/main/java/org/jboss/arquillian/container/test/impl/client/deployment/tool/ToolingDeploymentFormatter.java b/container/test-impl-base/src/main/java/org/jboss/arquillian/container/test/impl/client/deployment/tool/ToolingDeploymentFormatter.java index a7dd50ec..0e3ececb 100644 --- a/container/test-impl-base/src/main/java/org/jboss/arquillian/container/test/impl/client/deployment/tool/ToolingDeploymentFormatter.java +++ b/container/test-impl-base/src/main/java/org/jboss/arquillian/container/test/impl/client/deployment/tool/ToolingDeploymentFormatter.java @@ -1,163 +1,163 @@ /* * JBoss, Home of Professional Open Source * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.arquillian.container.test.impl.client.deployment.tool; import java.io.File; import java.lang.reflect.Field; import java.net.URL; import org.jboss.arquillian.core.spi.Validate; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ArchivePaths; import org.jboss.shrinkwrap.api.Node; +import org.jboss.shrinkwrap.api.asset.ArchiveAsset; import org.jboss.shrinkwrap.api.asset.Asset; +import org.jboss.shrinkwrap.api.asset.ClassAsset; +import org.jboss.shrinkwrap.api.asset.ClassLoaderAsset; import org.jboss.shrinkwrap.api.asset.FileAsset; import org.jboss.shrinkwrap.api.asset.UrlAsset; import org.jboss.shrinkwrap.api.formatter.Formatter; -import org.jboss.shrinkwrap.impl.base.asset.ArchiveAsset; -import org.jboss.shrinkwrap.impl.base.asset.ClassAsset; -import org.jboss.shrinkwrap.impl.base.asset.ClassLoaderAsset; /** * ToolingDeploymentFormatter * * @author <a href="mailto:aslak@redhat.com">Aslak Knutsen</a> * @version $Revision: $ */ public class ToolingDeploymentFormatter implements Formatter { private Class<?> testClass; public ToolingDeploymentFormatter(Class<?> testClass) { Validate.notNull(testClass, "TestClass must be specified"); this.testClass = testClass; } public String format(Archive<?> archive) throws IllegalArgumentException { StringBuilder xml = new StringBuilder(); xml.append("<?xml version=\"1.0\"?>\n<deployment") .append(" name=\"").append(archive.getName()).append("\"") .append(" testclass=\"").append(testClass.getName()).append("\"") .append(">\n"); formatNode(archive.get(ArchivePaths.root()), xml); xml.append("</deployment>").append("\n"); return xml.toString(); } public void formatNode(Node node, StringBuilder xml) { if(node.getAsset() != null) { String source = findResourceLocation(node.getAsset()); xml.append("\t<asset") .append(" type=\"").append(node.getAsset().getClass().getSimpleName()).append("\"") .append(" path=\"").append(node.getPath().get()).append("\""); if(source != null) { xml.append(" source=\"").append(source).append("\""); } if(node.getAsset().getClass() == ArchiveAsset.class) { xml.append(">"); xml.append("\n"); formatNode( ((ArchiveAsset)node.getAsset()).getArchive().get(ArchivePaths.root()), xml); xml.append("</asset>").append("\n"); } else { xml.append("/>").append("\n"); } } else { xml.append("\t<asset type=\"Directory\" path=\"").append(node.getPath().get()).append("\"/>\n"); } for(Node child : node.getChildren()) { formatNode(child, xml); } } private String findResourceLocation(Asset asset) { Class<?> assetClass = asset.getClass(); if(assetClass == FileAsset.class) { return getInternalFieldValue(File.class, "file", asset).getAbsolutePath(); } if(assetClass == ClassAsset.class) { return getInternalFieldValue(Class.class, "clazz", asset).getName(); } if(assetClass == UrlAsset.class) { return getInternalFieldValue(URL.class, "url", asset).toExternalForm(); } if(assetClass == ClassLoaderAsset.class) { return getInternalFieldValue(String.class, "resourceName", asset); } return null; } @SuppressWarnings("unchecked") private <T> T getInternalFieldValue(Class<T> type, String fieldName, Object obj) { try { Field field = obj.getClass().getDeclaredField(fieldName); field.setAccessible(true); return (T)field.get(obj); } catch (Exception e) { throw new RuntimeException("Could not extract field " + fieldName + " on " + obj, e); } } // private static class Deployment // { // // } // // private static class Node // { // // } // // private static class Source // { // // } // // private static class Content // { // // } }
false
false
null
null
diff --git a/src/com/android/launcher2/AppsCustomizePagedView.java b/src/com/android/launcher2/AppsCustomizePagedView.java index 4103141d..d8ff73c0 100644 --- a/src/com/android/launcher2/AppsCustomizePagedView.java +++ b/src/com/android/launcher2/AppsCustomizePagedView.java @@ -1,1443 +1,1447 @@ /* * Copyright (C) 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.launcher2; import android.animation.AnimatorSet; import android.animation.ObjectAnimator; import android.animation.ValueAnimator; import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetProviderInfo; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.content.res.Configuration; import android.content.res.Resources; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.Bitmap.Config; import android.graphics.Canvas; import android.graphics.PorterDuff; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.drawable.Drawable; import android.os.AsyncTask; import android.os.Process; import android.util.AttributeSet; import android.util.Log; import android.view.Gravity; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.animation.AccelerateInterpolator; import android.widget.GridLayout; import android.widget.ImageView; import android.widget.Toast; import com.android.launcher.R; import com.android.launcher2.DropTarget.DragObject; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; /** * A simple callback interface which also provides the results of the task. */ interface AsyncTaskCallback { void run(AppsCustomizeAsyncTask task, AsyncTaskPageData data); } /** * The data needed to perform either of the custom AsyncTasks. */ class AsyncTaskPageData { enum Type { LoadWidgetPreviewData, LoadHolographicIconsData } AsyncTaskPageData(int p, ArrayList<Object> l, ArrayList<Bitmap> si, AsyncTaskCallback bgR, AsyncTaskCallback postR) { page = p; items = l; sourceImages = si; generatedImages = new ArrayList<Bitmap>(); cellWidth = cellHeight = -1; doInBackgroundCallback = bgR; postExecuteCallback = postR; } AsyncTaskPageData(int p, ArrayList<Object> l, int cw, int ch, int ccx, AsyncTaskCallback bgR, AsyncTaskCallback postR) { page = p; items = l; generatedImages = new ArrayList<Bitmap>(); cellWidth = cw; cellHeight = ch; cellCountX = ccx; doInBackgroundCallback = bgR; postExecuteCallback = postR; } void cleanup(boolean cancelled) { // Clean up any references to source/generated bitmaps if (sourceImages != null) { if (cancelled) { for (Bitmap b : sourceImages) { b.recycle(); } } sourceImages.clear(); } if (generatedImages != null) { if (cancelled) { for (Bitmap b : generatedImages) { b.recycle(); } } generatedImages.clear(); } } int page; ArrayList<Object> items; ArrayList<Bitmap> sourceImages; ArrayList<Bitmap> generatedImages; int cellWidth; int cellHeight; int cellCountX; AsyncTaskCallback doInBackgroundCallback; AsyncTaskCallback postExecuteCallback; } /** * A generic template for an async task used in AppsCustomize. */ class AppsCustomizeAsyncTask extends AsyncTask<AsyncTaskPageData, Void, AsyncTaskPageData> { AppsCustomizeAsyncTask(int p, AsyncTaskPageData.Type ty) { page = p; threadPriority = Process.THREAD_PRIORITY_DEFAULT; dataType = ty; } @Override protected AsyncTaskPageData doInBackground(AsyncTaskPageData... params) { if (params.length != 1) return null; // Load each of the widget previews in the background params[0].doInBackgroundCallback.run(this, params[0]); return params[0]; } @Override protected void onPostExecute(AsyncTaskPageData result) { // All the widget previews are loaded, so we can just callback to inflate the page result.postExecuteCallback.run(this, result); } void setThreadPriority(int p) { threadPriority = p; } void syncThreadPriority() { Process.setThreadPriority(threadPriority); } // The page that this async task is associated with AsyncTaskPageData.Type dataType; int page; int threadPriority; } /** * The Apps/Customize page that displays all the applications, widgets, and shortcuts. */ public class AppsCustomizePagedView extends PagedViewWithDraggableItems implements AllAppsView, View.OnClickListener, DragSource { static final String LOG_TAG = "AppsCustomizePagedView"; /** * The different content types that this paged view can show. */ public enum ContentType { Applications, Widgets } // Refs private Launcher mLauncher; private DragController mDragController; private final LayoutInflater mLayoutInflater; private final PackageManager mPackageManager; // Save and Restore private int mSaveInstanceStateItemIndex = -1; // Content private ArrayList<ApplicationInfo> mApps; private ArrayList<Object> mWidgets; // Cling private int mClingFocusedX; private int mClingFocusedY; // Caching private Canvas mCanvas; private Drawable mDefaultWidgetBackground; private IconCache mIconCache; private int mDragViewMultiplyColor; // Dimens private int mContentWidth; private int mAppIconSize; private int mWidgetCountX, mWidgetCountY; private int mWidgetWidthGap, mWidgetHeightGap; private final int mWidgetPreviewIconPaddedDimension; private final float sWidgetPreviewIconPaddingPercentage = 0.25f; private PagedViewCellLayout mWidgetSpacingLayout; private int mNumAppsPages; private int mNumWidgetPages; // Relating to the scroll and overscroll effects Workspace.ZInterpolator mZInterpolator = new Workspace.ZInterpolator(0.5f); private static float CAMERA_DISTANCE = 6500; private static float TRANSITION_SCALE_FACTOR = 0.74f; private static float TRANSITION_PIVOT = 0.65f; private static float TRANSITION_MAX_ROTATION = 22; private static final boolean PERFORM_OVERSCROLL_ROTATION = true; private AccelerateInterpolator mAlphaInterpolator = new AccelerateInterpolator(0.9f); // Previews & outlines ArrayList<AppsCustomizeAsyncTask> mRunningTasks; private HolographicOutlineHelper mHolographicOutlineHelper; private static final int sPageSleepDelay = 150; public AppsCustomizePagedView(Context context, AttributeSet attrs) { super(context, attrs); mLayoutInflater = LayoutInflater.from(context); mPackageManager = context.getPackageManager(); mApps = new ArrayList<ApplicationInfo>(); mWidgets = new ArrayList<Object>(); mIconCache = ((LauncherApplication) context.getApplicationContext()).getIconCache(); mHolographicOutlineHelper = new HolographicOutlineHelper(); mCanvas = new Canvas(); mRunningTasks = new ArrayList<AppsCustomizeAsyncTask>(); // Save the default widget preview background Resources resources = context.getResources(); mDefaultWidgetBackground = resources.getDrawable(R.drawable.default_widget_preview_holo); mAppIconSize = resources.getDimensionPixelSize(R.dimen.app_icon_size); mDragViewMultiplyColor = resources.getColor(R.color.drag_view_multiply_color); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.PagedView, 0, 0); // TODO-APPS_CUSTOMIZE: remove these unnecessary attrs after mCellCountX = a.getInt(R.styleable.PagedView_cellCountX, 6); mCellCountY = a.getInt(R.styleable.PagedView_cellCountY, 4); a.recycle(); a = context.obtainStyledAttributes(attrs, R.styleable.AppsCustomizePagedView, 0, 0); mWidgetWidthGap = a.getDimensionPixelSize(R.styleable.AppsCustomizePagedView_widgetCellWidthGap, 0); mWidgetHeightGap = a.getDimensionPixelSize(R.styleable.AppsCustomizePagedView_widgetCellHeightGap, 0); mWidgetCountX = a.getInt(R.styleable.AppsCustomizePagedView_widgetCountX, 2); mWidgetCountY = a.getInt(R.styleable.AppsCustomizePagedView_widgetCountY, 2); mClingFocusedX = a.getInt(R.styleable.AppsCustomizePagedView_clingFocusedX, 0); mClingFocusedY = a.getInt(R.styleable.AppsCustomizePagedView_clingFocusedY, 0); a.recycle(); mWidgetSpacingLayout = new PagedViewCellLayout(getContext()); // The padding on the non-matched dimension for the default widget preview icons // (top + bottom) mWidgetPreviewIconPaddedDimension = (int) (mAppIconSize * (1 + (2 * sWidgetPreviewIconPaddingPercentage))); mFadeInAdjacentScreens = LauncherApplication.isScreenLarge(); } @Override protected void init() { super.init(); mCenterPagesVertically = true; Context context = getContext(); Resources r = context.getResources(); setDragSlopeThreshold(r.getInteger(R.integer.config_appsCustomizeDragSlopeThreshold)/100f); } @Override protected void onUnhandledTap(MotionEvent ev) { if (LauncherApplication.isScreenLarge()) { // Dismiss AppsCustomize if we tap mLauncher.showWorkspace(true); } } /** Returns the item index of the center item on this page so that we can restore to this * item index when we rotate. */ private int getMiddleComponentIndexOnCurrentPage() { int i = -1; if (getPageCount() > 0) { int currentPage = getCurrentPage(); if (currentPage < mNumAppsPages) { PagedViewCellLayout layout = (PagedViewCellLayout) getPageAt(currentPage); PagedViewCellLayoutChildren childrenLayout = layout.getChildrenLayout(); int numItemsPerPage = mCellCountX * mCellCountY; int childCount = childrenLayout.getChildCount(); if (childCount > 0) { i = (currentPage * numItemsPerPage) + (childCount / 2); } } else { int numApps = mApps.size(); PagedViewGridLayout layout = (PagedViewGridLayout) getPageAt(currentPage); int numItemsPerPage = mWidgetCountX * mWidgetCountY; int childCount = layout.getChildCount(); if (childCount > 0) { i = numApps + ((currentPage - mNumAppsPages) * numItemsPerPage) + (childCount / 2); } } } return i; } /** Get the index of the item to restore to if we need to restore the current page. */ int getSaveInstanceStateIndex() { if (mSaveInstanceStateItemIndex == -1) { mSaveInstanceStateItemIndex = getMiddleComponentIndexOnCurrentPage(); } return mSaveInstanceStateItemIndex; } /** Returns the page in the current orientation which is expected to contain the specified * item index. */ int getPageForComponent(int index) { if (index < 0) return 0; if (index < mApps.size()) { int numItemsPerPage = mCellCountX * mCellCountY; return (index / numItemsPerPage); } else { int numItemsPerPage = mWidgetCountX * mWidgetCountY; return mNumAppsPages + ((index - mApps.size()) / numItemsPerPage); } } /** * This differs from isDataReady as this is the test done if isDataReady is not set. */ private boolean testDataReady() { // We only do this test once, and we default to the Applications page, so we only really // have to wait for there to be apps. // TODO: What if one of them is validly empty return !mApps.isEmpty() && !mWidgets.isEmpty(); } /** Restores the page for an item at the specified index */ void restorePageForIndex(int index) { if (index < 0) return; mSaveInstanceStateItemIndex = index; } private void updatePageCounts() { mNumWidgetPages = (int) Math.ceil(mWidgets.size() / (float) (mWidgetCountX * mWidgetCountY)); mNumAppsPages = (int) Math.ceil((float) mApps.size() / (mCellCountX * mCellCountY)); } protected void onDataReady(int width, int height) { // Note that we transpose the counts in portrait so that we get a similar layout boolean isLandscape = getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE; int maxCellCountX = Integer.MAX_VALUE; int maxCellCountY = Integer.MAX_VALUE; if (LauncherApplication.isScreenLarge()) { maxCellCountX = (isLandscape ? LauncherModel.getCellCountX() : LauncherModel.getCellCountY()); maxCellCountY = (isLandscape ? LauncherModel.getCellCountY() : LauncherModel.getCellCountX()); } // Now that the data is ready, we can calculate the content width, the number of cells to // use for each page mWidgetSpacingLayout.setGap(mPageLayoutWidthGap, mPageLayoutHeightGap); mWidgetSpacingLayout.setPadding(mPageLayoutPaddingLeft, mPageLayoutPaddingTop, mPageLayoutPaddingRight, mPageLayoutPaddingBottom); mWidgetSpacingLayout.calculateCellCount(width, height, maxCellCountX, maxCellCountY); mCellCountX = mWidgetSpacingLayout.getCellCountX(); mCellCountY = mWidgetSpacingLayout.getCellCountY(); updatePageCounts(); // Force a measure to update recalculate the gaps int widthSpec = MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.AT_MOST); int heightSpec = MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.AT_MOST); mWidgetSpacingLayout.measure(widthSpec, heightSpec); mContentWidth = mWidgetSpacingLayout.getContentWidth(); // Restore the page int page = getPageForComponent(mSaveInstanceStateItemIndex); invalidatePageData(Math.max(0, page)); // Calculate the position for the cling punch through int[] offset = new int[2]; int[] pos = mWidgetSpacingLayout.estimateCellPosition(mClingFocusedX, mClingFocusedY); mLauncher.getDragLayer().getLocationInDragLayer(this, offset); pos[0] += (getMeasuredWidth() - mWidgetSpacingLayout.getMeasuredWidth()) / 2 + offset[0]; pos[1] += (getMeasuredHeight() - mWidgetSpacingLayout.getMeasuredHeight()) / 2 + offset[1]; mLauncher.showFirstRunAllAppsCling(pos); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int width = MeasureSpec.getSize(widthMeasureSpec); int height = MeasureSpec.getSize(heightMeasureSpec); if (!isDataReady()) { if (testDataReady()) { setDataIsReady(); setMeasuredDimension(width, height); onDataReady(width, height); } } super.onMeasure(widthMeasureSpec, heightMeasureSpec); } /** Removes and returns the ResolveInfo with the specified ComponentName */ private ResolveInfo removeResolveInfoWithComponentName(List<ResolveInfo> list, ComponentName cn) { Iterator<ResolveInfo> iter = list.iterator(); while (iter.hasNext()) { ResolveInfo rinfo = iter.next(); ActivityInfo info = rinfo.activityInfo; ComponentName c = new ComponentName(info.packageName, info.name); if (c.equals(cn)) { iter.remove(); return rinfo; } } return null; } public void onPackagesUpdated() { // TODO: this isn't ideal, but we actually need to delay here. This call is triggered // by a broadcast receiver, and in order for it to work correctly, we need to know that // the AppWidgetService has already received and processed the same broadcast. Since there // is no guarantee about ordering of broadcast receipt, we just delay here. Ideally, // we should have a more precise way of ensuring the AppWidgetService is up to date. postDelayed(new Runnable() { public void run() { updatePackages(); } }, 500); } public void updatePackages() { // Get the list of widgets and shortcuts boolean wasEmpty = mWidgets.isEmpty(); mWidgets.clear(); List<AppWidgetProviderInfo> widgets = AppWidgetManager.getInstance(mLauncher).getInstalledProviders(); Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT); List<ResolveInfo> shortcuts = mPackageManager.queryIntentActivities(shortcutsIntent, 0); mWidgets.addAll(widgets); mWidgets.addAll(shortcuts); Collections.sort(mWidgets, new LauncherModel.WidgetAndShortcutNameComparator(mPackageManager)); updatePageCounts(); if (wasEmpty) { // The next layout pass will trigger data-ready if both widgets and apps are set, so request // a layout to do this test and invalidate the page data when ready. if (testDataReady()) requestLayout(); } else { cancelAllTasks(); invalidatePageData(); } } @Override public void onClick(View v) { // When we have exited all apps or are in transition, disregard clicks if (!mLauncher.isAllAppsCustomizeOpen() || mLauncher.getWorkspace().isSwitchingState()) return; if (v instanceof PagedViewIcon) { // Animate some feedback to the click final ApplicationInfo appInfo = (ApplicationInfo) v.getTag(); animateClickFeedback(v, new Runnable() { @Override public void run() { mLauncher.startActivitySafely(appInfo.intent, appInfo); } }); } else if (v instanceof PagedViewWidget) { // Let the user know that they have to long press to add a widget Toast.makeText(getContext(), R.string.long_press_widget_to_add, Toast.LENGTH_SHORT).show(); // Create a little animation to show that the widget can move float offsetY = getResources().getDimensionPixelSize(R.dimen.dragViewOffsetY); final ImageView p = (ImageView) v.findViewById(R.id.widget_preview); AnimatorSet bounce = new AnimatorSet(); ValueAnimator tyuAnim = ObjectAnimator.ofFloat(p, "translationY", offsetY); tyuAnim.setDuration(125); ValueAnimator tydAnim = ObjectAnimator.ofFloat(p, "translationY", 0f); tydAnim.setDuration(100); bounce.play(tyuAnim).before(tydAnim); bounce.setInterpolator(new AccelerateInterpolator()); bounce.start(); } } /* * PagedViewWithDraggableItems implementation */ @Override protected void determineDraggingStart(android.view.MotionEvent ev) { // Disable dragging by pulling an app down for now. } private void beginDraggingApplication(View v) { mLauncher.getWorkspace().onDragStartedWithItem(v); mLauncher.getWorkspace().beginDragShared(v, this); } private void beginDraggingWidget(View v) { // Get the widget preview as the drag representation ImageView image = (ImageView) v.findViewById(R.id.widget_preview); PendingAddItemInfo createItemInfo = (PendingAddItemInfo) v.getTag(); // Compose the drag image Bitmap b; Drawable preview = image.getDrawable(); RectF mTmpScaleRect = new RectF(0f,0f,1f,1f); image.getImageMatrix().mapRect(mTmpScaleRect); float scale = mTmpScaleRect.right; int w = (int) (preview.getIntrinsicWidth() * scale); int h = (int) (preview.getIntrinsicHeight() * scale); if (createItemInfo instanceof PendingAddWidgetInfo) { PendingAddWidgetInfo createWidgetInfo = (PendingAddWidgetInfo) createItemInfo; int[] spanXY = mLauncher.getSpanForWidget(createWidgetInfo, null); createItemInfo.spanX = spanXY[0]; createItemInfo.spanY = spanXY[1]; b = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); renderDrawableToBitmap(preview, b, 0, 0, w, h, scale, mDragViewMultiplyColor); } else { // Workaround for the fact that we don't keep the original ResolveInfo associated with // the shortcut around. To get the icon, we just render the preview image (which has // the shortcut icon) to a new drag bitmap that clips the non-icon space. b = Bitmap.createBitmap(mWidgetPreviewIconPaddedDimension, mWidgetPreviewIconPaddedDimension, Bitmap.Config.ARGB_8888); mCanvas.setBitmap(b); mCanvas.save(); preview.draw(mCanvas); mCanvas.restore(); mCanvas.drawColor(mDragViewMultiplyColor, PorterDuff.Mode.MULTIPLY); mCanvas.setBitmap(null); createItemInfo.spanX = createItemInfo.spanY = 1; } // Start the drag mLauncher.lockScreenOrientationOnLargeUI(); mLauncher.getWorkspace().onDragStartedWithItemSpans(createItemInfo.spanX, createItemInfo.spanY, b); mDragController.startDrag(image, b, this, createItemInfo, DragController.DRAG_ACTION_COPY, null); b.recycle(); } @Override protected boolean beginDragging(View v) { // Dismiss the cling mLauncher.dismissAllAppsCling(null); if (!super.beginDragging(v)) return false; // Go into spring loaded mode (must happen before we startDrag()) mLauncher.enterSpringLoadedDragMode(); if (v instanceof PagedViewIcon) { beginDraggingApplication(v); } else if (v instanceof PagedViewWidget) { beginDraggingWidget(v); } return true; } private void endDragging(View target, boolean success) { mLauncher.getWorkspace().onDragStopped(success); if (!success || (target != mLauncher.getWorkspace() && !(target instanceof DeleteDropTarget))) { // Exit spring loaded mode if we have not successfully dropped or have not handled the // drop in Workspace mLauncher.exitSpringLoadedDragMode(); } mLauncher.unlockScreenOrientationOnLargeUI(); } @Override public void onDropCompleted(View target, DragObject d, boolean success) { endDragging(target, success); // Display an error message if the drag failed due to there not being enough space on the // target layout we were dropping on. if (!success) { boolean showOutOfSpaceMessage = false; if (target instanceof Workspace) { int currentScreen = mLauncher.getCurrentWorkspaceScreen(); Workspace workspace = (Workspace) target; CellLayout layout = (CellLayout) workspace.getChildAt(currentScreen); ItemInfo itemInfo = (ItemInfo) d.dragInfo; if (layout != null) { layout.calculateSpans(itemInfo); showOutOfSpaceMessage = !layout.findCellForSpan(null, itemInfo.spanX, itemInfo.spanY); } } if (showOutOfSpaceMessage) { mLauncher.showOutOfSpaceMessage(); } } } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); cancelAllTasks(); } private void cancelAllTasks() { // Clean up all the async tasks Iterator<AppsCustomizeAsyncTask> iter = mRunningTasks.iterator(); while (iter.hasNext()) { AppsCustomizeAsyncTask task = (AppsCustomizeAsyncTask) iter.next(); task.cancel(false); iter.remove(); } } public void setContentType(ContentType type) { if (type == ContentType.Widgets) { invalidatePageData(mNumAppsPages, true); } else if (type == ContentType.Applications) { invalidatePageData(0, true); } } protected void snapToPage(int whichPage, int delta, int duration) { super.snapToPage(whichPage, delta, duration); updateCurrentTab(whichPage); } private void updateCurrentTab(int currentPage) { AppsCustomizeTabHost tabHost = getTabHost(); String tag = tabHost.getCurrentTabTag(); - if (currentPage >= mNumAppsPages && - !tag.equals(tabHost.getTabTagForContentType(ContentType.Widgets))) { - tabHost.setCurrentTabFromContent(ContentType.Widgets); - } else if (currentPage < mNumAppsPages && - !tag.equals(tabHost.getTabTagForContentType(ContentType.Applications))) { - tabHost.setCurrentTabFromContent(ContentType.Applications); + if (tag != null) { + if (currentPage >= mNumAppsPages && + !tag.equals(tabHost.getTabTagForContentType(ContentType.Widgets))) { + tabHost.setCurrentTabFromContent(ContentType.Widgets); + } else if (currentPage < mNumAppsPages && + !tag.equals(tabHost.getTabTagForContentType(ContentType.Applications))) { + tabHost.setCurrentTabFromContent(ContentType.Applications); + } } } /* * Apps PagedView implementation */ private void setVisibilityOnChildren(ViewGroup layout, int visibility) { int childCount = layout.getChildCount(); for (int i = 0; i < childCount; ++i) { layout.getChildAt(i).setVisibility(visibility); } } private void setupPage(PagedViewCellLayout layout) { layout.setCellCount(mCellCountX, mCellCountY); layout.setGap(mPageLayoutWidthGap, mPageLayoutHeightGap); layout.setPadding(mPageLayoutPaddingLeft, mPageLayoutPaddingTop, mPageLayoutPaddingRight, mPageLayoutPaddingBottom); // Note: We force a measure here to get around the fact that when we do layout calculations // immediately after syncing, we don't have a proper width. That said, we already know the // expected page width, so we can actually optimize by hiding all the TextView-based // children that are expensive to measure, and let that happen naturally later. setVisibilityOnChildren(layout, View.GONE); int widthSpec = MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.AT_MOST); int heightSpec = MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.AT_MOST); layout.setMinimumWidth(getPageContentWidth()); layout.measure(widthSpec, heightSpec); setVisibilityOnChildren(layout, View.VISIBLE); } public void syncAppsPageItems(int page, boolean immediate) { // ensure that we have the right number of items on the pages int numCells = mCellCountX * mCellCountY; int startIndex = page * numCells; int endIndex = Math.min(startIndex + numCells, mApps.size()); PagedViewCellLayout layout = (PagedViewCellLayout) getPageAt(page); layout.removeAllViewsOnPage(); ArrayList<Object> items = new ArrayList<Object>(); ArrayList<Bitmap> images = new ArrayList<Bitmap>(); for (int i = startIndex; i < endIndex; ++i) { ApplicationInfo info = mApps.get(i); PagedViewIcon icon = (PagedViewIcon) mLayoutInflater.inflate( R.layout.apps_customize_application, layout, false); icon.applyFromApplicationInfo(info, true, mHolographicOutlineHelper); icon.setOnClickListener(this); icon.setOnLongClickListener(this); icon.setOnTouchListener(this); int index = i - startIndex; int x = index % mCellCountX; int y = index / mCellCountX; layout.addViewToCellLayout(icon, -1, i, new PagedViewCellLayout.LayoutParams(x,y, 1,1)); items.add(info); images.add(info.iconBitmap); } layout.createHardwareLayers(); /* TEMPORARILY DISABLE HOLOGRAPHIC ICONS if (mFadeInAdjacentScreens) { prepareGenerateHoloOutlinesTask(page, items, images); } */ } /** * Return the appropriate thread priority for loading for a given page (we give the current * page much higher priority) */ private int getThreadPriorityForPage(int page) { // TODO-APPS_CUSTOMIZE: detect number of cores and set thread priorities accordingly below int pageDiff = Math.abs(page - mCurrentPage); if (pageDiff <= 0) { // return Process.THREAD_PRIORITY_DEFAULT; return Process.THREAD_PRIORITY_MORE_FAVORABLE; } else if (pageDiff <= 1) { // return Process.THREAD_PRIORITY_BACKGROUND; return Process.THREAD_PRIORITY_DEFAULT; } else { // return Process.THREAD_PRIORITY_LOWEST; return Process.THREAD_PRIORITY_DEFAULT; } } private int getSleepForPage(int page) { int pageDiff = Math.abs(page - mCurrentPage) - 1; return Math.max(0, pageDiff * sPageSleepDelay); } /** * Creates and executes a new AsyncTask to load a page of widget previews. */ private void prepareLoadWidgetPreviewsTask(int page, ArrayList<Object> widgets, int cellWidth, int cellHeight, int cellCountX) { // Prune all tasks that are no longer needed Iterator<AppsCustomizeAsyncTask> iter = mRunningTasks.iterator(); while (iter.hasNext()) { AppsCustomizeAsyncTask task = (AppsCustomizeAsyncTask) iter.next(); int taskPage = task.page; if ((taskPage == page) || taskPage < getAssociatedLowerPageBound(mCurrentPage - mNumAppsPages) || taskPage > getAssociatedUpperPageBound(mCurrentPage - mNumAppsPages)) { task.cancel(false); iter.remove(); } else { task.setThreadPriority(getThreadPriorityForPage(taskPage + mNumAppsPages)); } } // We introduce a slight delay to order the loading of side pages so that we don't thrash final int sleepMs = getSleepForPage(page + mNumAppsPages); AsyncTaskPageData pageData = new AsyncTaskPageData(page, widgets, cellWidth, cellHeight, cellCountX, new AsyncTaskCallback() { @Override public void run(AppsCustomizeAsyncTask task, AsyncTaskPageData data) { try { try { Thread.sleep(sleepMs); } catch (Exception e) {} loadWidgetPreviewsInBackground(task, data); } finally { if (task.isCancelled()) { data.cleanup(true); } } } }, new AsyncTaskCallback() { @Override public void run(AppsCustomizeAsyncTask task, AsyncTaskPageData data) { try { mRunningTasks.remove(task); if (task.isCancelled()) return; onSyncWidgetPageItems(data); } finally { data.cleanup(task.isCancelled()); } } }); // Ensure that the task is appropriately prioritized and runs in parallel AppsCustomizeAsyncTask t = new AppsCustomizeAsyncTask(page, AsyncTaskPageData.Type.LoadWidgetPreviewData); t.setThreadPriority(getThreadPriorityForPage(page)); t.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, pageData); mRunningTasks.add(t); } /** * Creates and executes a new AsyncTask to load the outlines for a page of content. */ private void prepareGenerateHoloOutlinesTask(int page, ArrayList<Object> items, ArrayList<Bitmap> images) { // Prune old tasks for this page Iterator<AppsCustomizeAsyncTask> iter = mRunningTasks.iterator(); while (iter.hasNext()) { AppsCustomizeAsyncTask task = (AppsCustomizeAsyncTask) iter.next(); int taskPage = task.page; if ((taskPage == page) && (task.dataType == AsyncTaskPageData.Type.LoadHolographicIconsData)) { task.cancel(false); iter.remove(); } } AsyncTaskPageData pageData = new AsyncTaskPageData(page, items, images, new AsyncTaskCallback() { @Override public void run(AppsCustomizeAsyncTask task, AsyncTaskPageData data) { try { // Ensure that this task starts running at the correct priority task.syncThreadPriority(); ArrayList<Bitmap> images = data.generatedImages; ArrayList<Bitmap> srcImages = data.sourceImages; int count = srcImages.size(); Canvas c = new Canvas(); for (int i = 0; i < count && !task.isCancelled(); ++i) { // Before work on each item, ensure that this task is running at the correct // priority task.syncThreadPriority(); Bitmap b = srcImages.get(i); Bitmap outline = Bitmap.createBitmap(b.getWidth(), b.getHeight(), Bitmap.Config.ARGB_8888); c.setBitmap(outline); c.save(); c.drawBitmap(b, 0, 0, null); c.restore(); c.setBitmap(null); images.add(outline); } } finally { if (task.isCancelled()) { data.cleanup(true); } } } }, new AsyncTaskCallback() { @Override public void run(AppsCustomizeAsyncTask task, AsyncTaskPageData data) { try { mRunningTasks.remove(task); if (task.isCancelled()) return; onHolographicPageItemsLoaded(data); } finally { data.cleanup(task.isCancelled()); } } }); // Ensure that the outline task always runs in the background, serially AppsCustomizeAsyncTask t = new AppsCustomizeAsyncTask(page, AsyncTaskPageData.Type.LoadHolographicIconsData); t.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); t.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, pageData); mRunningTasks.add(t); } /* * Widgets PagedView implementation */ private void setupPage(PagedViewGridLayout layout) { layout.setPadding(mPageLayoutPaddingLeft, mPageLayoutPaddingTop, mPageLayoutPaddingRight, mPageLayoutPaddingBottom); // Note: We force a measure here to get around the fact that when we do layout calculations // immediately after syncing, we don't have a proper width. int widthSpec = MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.AT_MOST); int heightSpec = MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.AT_MOST); layout.setMinimumWidth(getPageContentWidth()); layout.measure(widthSpec, heightSpec); } private void renderDrawableToBitmap(Drawable d, Bitmap bitmap, int x, int y, int w, int h) { renderDrawableToBitmap(d, bitmap, x, y, w, h, 1f, 0xFFFFFFFF); } private void renderDrawableToBitmap(Drawable d, Bitmap bitmap, int x, int y, int w, int h, float scale) { renderDrawableToBitmap(d, bitmap, x, y, w, h, scale, 0xFFFFFFFF); } private void renderDrawableToBitmap(Drawable d, Bitmap bitmap, int x, int y, int w, int h, float scale, int multiplyColor) { if (bitmap != null) { Canvas c = new Canvas(bitmap); c.scale(scale, scale); Rect oldBounds = d.copyBounds(); d.setBounds(x, y, x + w, y + h); d.draw(c); d.setBounds(oldBounds); // Restore the bounds if (multiplyColor != 0xFFFFFFFF) { c.drawColor(mDragViewMultiplyColor, PorterDuff.Mode.MULTIPLY); } c.setBitmap(null); } } private Bitmap getShortcutPreview(ResolveInfo info, int cellWidth, int cellHeight) { // Render the background int offset = (int) (mAppIconSize * sWidgetPreviewIconPaddingPercentage); int bitmapSize = mAppIconSize + 2 * offset; Bitmap preview = Bitmap.createBitmap(bitmapSize, bitmapSize, Config.ARGB_8888); renderDrawableToBitmap(mDefaultWidgetBackground, preview, 0, 0, bitmapSize, bitmapSize); // Render the icon Drawable icon = mIconCache.getFullResIcon(info, mPackageManager); renderDrawableToBitmap(icon, preview, offset, offset, mAppIconSize, mAppIconSize); return preview; } private Bitmap getWidgetPreview(AppWidgetProviderInfo info, int cellHSpan, int cellVSpan, int cellWidth, int cellHeight) { // Load the preview image if possible String packageName = info.provider.getPackageName(); Drawable drawable = null; Bitmap preview = null; if (info.previewImage != 0) { drawable = mPackageManager.getDrawable(packageName, info.previewImage, null); if (drawable == null) { Log.w(LOG_TAG, "Can't load icon drawable 0x" + Integer.toHexString(info.icon) + " for provider: " + info.provider); } else { // Scale down the preview to something that is closer to the cellWidth/Height int imageWidth = drawable.getIntrinsicWidth(); int imageHeight = drawable.getIntrinsicHeight(); int bitmapWidth = imageWidth; int bitmapHeight = imageHeight; if (imageWidth > imageHeight) { bitmapWidth = cellWidth; bitmapHeight = (int) (imageHeight * ((float) bitmapWidth / imageWidth)); } else { bitmapHeight = cellHeight; bitmapWidth = (int) (imageWidth * ((float) bitmapHeight / imageHeight)); } preview = Bitmap.createBitmap(bitmapWidth, bitmapHeight, Config.ARGB_8888); renderDrawableToBitmap(drawable, preview, 0, 0, bitmapWidth, bitmapHeight); } } // Generate a preview image if we couldn't load one if (drawable == null) { Resources resources = mLauncher.getResources(); // TODO: This actually uses the apps customize cell layout params, where as we make want // the Workspace params for more accuracy. int targetWidth = mWidgetSpacingLayout.estimateCellWidth(cellHSpan); int targetHeight = mWidgetSpacingLayout.estimateCellHeight(cellVSpan); int bitmapWidth = targetWidth; int bitmapHeight = targetHeight; int offset = (int) (mAppIconSize * sWidgetPreviewIconPaddingPercentage); float iconScale = 1f; // Determine the size of the bitmap we want to draw if (cellHSpan == cellVSpan) { // For square widgets, we just have a fixed size for 1x1 and larger-than-1x1 if (cellHSpan <= 1) { bitmapWidth = bitmapHeight = mAppIconSize + 2 * offset; } else { bitmapWidth = bitmapHeight = mAppIconSize + 4 * offset; } } else { // Otherwise, ensure that we are properly sized within the cellWidth/Height if (targetWidth > targetHeight) { bitmapWidth = Math.min(targetWidth, cellWidth); bitmapHeight = (int) (targetHeight * ((float) bitmapWidth / targetWidth)); iconScale = Math.min((float) bitmapHeight / (mAppIconSize + 2 * offset), 1f); } else { bitmapHeight = Math.min(targetHeight, cellHeight); bitmapWidth = (int) (targetWidth * ((float) bitmapHeight / targetHeight)); iconScale = Math.min((float) bitmapWidth / (mAppIconSize + 2 * offset), 1f); } } preview = Bitmap.createBitmap(bitmapWidth, bitmapHeight, Config.ARGB_8888); renderDrawableToBitmap(mDefaultWidgetBackground, preview, 0, 0, bitmapWidth, bitmapWidth); // Draw the icon in the top left corner try { Drawable icon = null; if (info.icon > 0) icon = mPackageManager.getDrawable(packageName, info.icon, null); if (icon == null) icon = resources.getDrawable(R.drawable.ic_launcher_application); renderDrawableToBitmap(icon, preview, (int) (offset * iconScale), (int) (offset * iconScale), (int) (mAppIconSize * iconScale), (int) (mAppIconSize * iconScale)); } catch (Resources.NotFoundException e) {} } return preview; } public void syncWidgetPageItems(int page, boolean immediate) { int numItemsPerPage = mWidgetCountX * mWidgetCountY; int contentWidth = mWidgetSpacingLayout.getContentWidth(); int contentHeight = mWidgetSpacingLayout.getContentHeight(); // Calculate the dimensions of each cell we are giving to each widget ArrayList<Object> items = new ArrayList<Object>(); int cellWidth = ((contentWidth - mPageLayoutPaddingLeft - mPageLayoutPaddingRight - ((mWidgetCountX - 1) * mWidgetWidthGap)) / mWidgetCountX); int cellHeight = ((contentHeight - mPageLayoutPaddingTop - mPageLayoutPaddingBottom - ((mWidgetCountY - 1) * mWidgetHeightGap)) / mWidgetCountY); // Prepare the set of widgets to load previews for in the background int offset = page * numItemsPerPage; for (int i = offset; i < Math.min(offset + numItemsPerPage, mWidgets.size()); ++i) { items.add(mWidgets.get(i)); } // Prepopulate the pages with the other widget info, and fill in the previews later PagedViewGridLayout layout = (PagedViewGridLayout) getPageAt(page + mNumAppsPages); layout.setColumnCount(layout.getCellCountX()); for (int i = 0; i < items.size(); ++i) { Object rawInfo = items.get(i); PendingAddItemInfo createItemInfo = null; PagedViewWidget widget = (PagedViewWidget) mLayoutInflater.inflate( R.layout.apps_customize_widget, layout, false); if (rawInfo instanceof AppWidgetProviderInfo) { // Fill in the widget information AppWidgetProviderInfo info = (AppWidgetProviderInfo) rawInfo; createItemInfo = new PendingAddWidgetInfo(info, null, null); int[] cellSpans = mLauncher.getSpanForWidget(info, null); widget.applyFromAppWidgetProviderInfo(info, -1, cellSpans, mHolographicOutlineHelper); widget.setTag(createItemInfo); } else if (rawInfo instanceof ResolveInfo) { // Fill in the shortcuts information ResolveInfo info = (ResolveInfo) rawInfo; createItemInfo = new PendingAddItemInfo(); createItemInfo.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT; createItemInfo.componentName = new ComponentName(info.activityInfo.packageName, info.activityInfo.name); widget.applyFromResolveInfo(mPackageManager, info, mHolographicOutlineHelper); widget.setTag(createItemInfo); } widget.setOnClickListener(this); widget.setOnLongClickListener(this); widget.setOnTouchListener(this); // Layout each widget int ix = i % mWidgetCountX; int iy = i / mWidgetCountX; GridLayout.LayoutParams lp = new GridLayout.LayoutParams( GridLayout.spec(iy, GridLayout.LEFT), GridLayout.spec(ix, GridLayout.TOP)); lp.width = cellWidth; lp.height = cellHeight; lp.setGravity(Gravity.TOP | Gravity.LEFT); if (ix > 0) lp.leftMargin = mWidgetWidthGap; if (iy > 0) lp.topMargin = mWidgetHeightGap; layout.addView(widget, lp); } // Load the widget previews if (immediate) { AsyncTaskPageData data = new AsyncTaskPageData(page, items, cellWidth, cellHeight, mWidgetCountX, null, null); loadWidgetPreviewsInBackground(null, data); onSyncWidgetPageItems(data); } else { prepareLoadWidgetPreviewsTask(page, items, cellWidth, cellHeight, mWidgetCountX); } } private void loadWidgetPreviewsInBackground(AppsCustomizeAsyncTask task, AsyncTaskPageData data) { if (task != null) { // Ensure that this task starts running at the correct priority task.syncThreadPriority(); } // Load each of the widget/shortcut previews ArrayList<Object> items = data.items; ArrayList<Bitmap> images = data.generatedImages; int count = items.size(); int cellWidth = data.cellWidth; int cellHeight = data.cellHeight; for (int i = 0; i < count; ++i) { if (task != null) { // Ensure we haven't been cancelled yet if (task.isCancelled()) break; // Before work on each item, ensure that this task is running at the correct // priority task.syncThreadPriority(); } Object rawInfo = items.get(i); if (rawInfo instanceof AppWidgetProviderInfo) { AppWidgetProviderInfo info = (AppWidgetProviderInfo) rawInfo; int[] cellSpans = mLauncher.getSpanForWidget(info, null); images.add(getWidgetPreview(info, cellSpans[0],cellSpans[1], cellWidth, cellHeight)); } else if (rawInfo instanceof ResolveInfo) { // Fill in the shortcuts information ResolveInfo info = (ResolveInfo) rawInfo; images.add(getShortcutPreview(info, cellWidth, cellHeight)); } } } private void onSyncWidgetPageItems(AsyncTaskPageData data) { int page = data.page; PagedViewGridLayout layout = (PagedViewGridLayout) getPageAt(page + mNumAppsPages); ArrayList<Object> items = data.items; int count = items.size(); for (int i = 0; i < count; ++i) { PagedViewWidget widget = (PagedViewWidget) layout.getChildAt(i); if (widget != null) { Bitmap preview = data.generatedImages.get(i); boolean scale = (preview.getWidth() >= data.cellWidth || preview.getHeight() >= data.cellHeight); widget.applyPreview(new FastBitmapDrawable(preview), i, scale); } } layout.createHardwareLayer(); invalidate(); forceUpdateAdjacentPagesAlpha(); /* TEMPORARILY DISABLE HOLOGRAPHIC ICONS if (mFadeInAdjacentScreens) { prepareGenerateHoloOutlinesTask(data.page, data.items, data.generatedImages); } */ } private void onHolographicPageItemsLoaded(AsyncTaskPageData data) { // Invalidate early to short-circuit children invalidates invalidate(); int page = data.page; ViewGroup layout = (ViewGroup) getPageAt(page); if (layout instanceof PagedViewCellLayout) { PagedViewCellLayout cl = (PagedViewCellLayout) layout; int count = cl.getPageChildCount(); if (count != data.generatedImages.size()) return; for (int i = 0; i < count; ++i) { PagedViewIcon icon = (PagedViewIcon) cl.getChildOnPageAt(i); icon.setHolographicOutline(data.generatedImages.get(i)); } } else { int count = layout.getChildCount(); if (count != data.generatedImages.size()) return; for (int i = 0; i < count; ++i) { View v = layout.getChildAt(i); ((PagedViewWidget) v).setHolographicOutline(data.generatedImages.get(i)); } } } @Override public void syncPages() { removeAllViews(); cancelAllTasks(); Context context = getContext(); for (int j = 0; j < mNumWidgetPages; ++j) { PagedViewGridLayout layout = new PagedViewGridLayout(context, mWidgetCountX, mWidgetCountY); setupPage(layout); addView(layout, new PagedViewGridLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); } for (int i = 0; i < mNumAppsPages; ++i) { PagedViewCellLayout layout = new PagedViewCellLayout(context); setupPage(layout); addView(layout); } } @Override public void syncPageItems(int page, boolean immediate) { if (page < mNumAppsPages) { syncAppsPageItems(page, immediate); } else { syncWidgetPageItems(page - mNumAppsPages, immediate); } } // We want our pages to be z-ordered such that the further a page is to the left, the higher // it is in the z-order. This is important to insure touch events are handled correctly. View getPageAt(int index) { return getChildAt(getChildCount() - index - 1); } @Override protected int indexToPage(int index) { return getChildCount() - index - 1; } // In apps customize, we have a scrolling effect which emulates pulling cards off of a stack. @Override protected void screenScrolled(int screenCenter) { super.screenScrolled(screenCenter); for (int i = 0; i < getChildCount(); i++) { View v = getPageAt(i); if (v != null) { float scrollProgress = getScrollProgress(screenCenter, v, i); float interpolatedProgress = mZInterpolator.getInterpolation(Math.abs(Math.min(scrollProgress, 0))); float scale = (1 - interpolatedProgress) + interpolatedProgress * TRANSITION_SCALE_FACTOR; float translationX = Math.min(0, scrollProgress) * v.getMeasuredWidth(); float alpha = scrollProgress < 0 ? mAlphaInterpolator.getInterpolation( 1 - Math.abs(scrollProgress)) : 1.0f; v.setCameraDistance(mDensity * CAMERA_DISTANCE); int pageWidth = v.getMeasuredWidth(); int pageHeight = v.getMeasuredHeight(); if (PERFORM_OVERSCROLL_ROTATION) { if (i == 0 && scrollProgress < 0) { // Overscroll to the left v.setPivotX(TRANSITION_PIVOT * pageWidth); v.setRotationY(-TRANSITION_MAX_ROTATION * scrollProgress); scale = 1.0f; alpha = 1.0f; // On the first page, we don't want the page to have any lateral motion translationX = getScrollX(); } else if (i == getChildCount() - 1 && scrollProgress > 0) { // Overscroll to the right v.setPivotX((1 - TRANSITION_PIVOT) * pageWidth); v.setRotationY(-TRANSITION_MAX_ROTATION * scrollProgress); scale = 1.0f; alpha = 1.0f; // On the last page, we don't want the page to have any lateral motion. translationX = getScrollX() - mMaxScrollX; } else { v.setPivotY(pageHeight / 2.0f); v.setPivotX(pageWidth / 2.0f); v.setRotationY(0f); } } v.setTranslationX(translationX); v.setScaleX(scale); v.setScaleY(scale); v.setAlpha(alpha); } } } protected void overScroll(float amount) { acceleratedOverScroll(amount); } /** * Used by the parent to get the content width to set the tab bar to * @return */ public int getPageContentWidth() { return mContentWidth; } @Override protected void onPageEndMoving() { super.onPageEndMoving(); // We reset the save index when we change pages so that it will be recalculated on next // rotation mSaveInstanceStateItemIndex = -1; } /* * AllAppsView implementation */ @Override public void setup(Launcher launcher, DragController dragController) { mLauncher = launcher; mDragController = dragController; } @Override public void zoom(float zoom, boolean animate) { // TODO-APPS_CUSTOMIZE: Call back to mLauncher.zoomed() } @Override public boolean isVisible() { return (getVisibility() == VISIBLE); } @Override public boolean isAnimating() { return false; } @Override public void setApps(ArrayList<ApplicationInfo> list) { mApps = list; Collections.sort(mApps, LauncherModel.APP_NAME_COMPARATOR); updatePageCounts(); // The next layout pass will trigger data-ready if both widgets and apps are set, so // request a layout to do this test and invalidate the page data when ready. if (testDataReady()) requestLayout(); } private void addAppsWithoutInvalidate(ArrayList<ApplicationInfo> list) { // We add it in place, in alphabetical order int count = list.size(); for (int i = 0; i < count; ++i) { ApplicationInfo info = list.get(i); int index = Collections.binarySearch(mApps, info, LauncherModel.APP_NAME_COMPARATOR); if (index < 0) { mApps.add(-(index + 1), info); } } } @Override public void addApps(ArrayList<ApplicationInfo> list) { addAppsWithoutInvalidate(list); updatePageCounts(); invalidatePageData(); } private int findAppByComponent(List<ApplicationInfo> list, ApplicationInfo item) { ComponentName removeComponent = item.intent.getComponent(); int length = list.size(); for (int i = 0; i < length; ++i) { ApplicationInfo info = list.get(i); if (info.intent.getComponent().equals(removeComponent)) { return i; } } return -1; } private void removeAppsWithoutInvalidate(ArrayList<ApplicationInfo> list) { // loop through all the apps and remove apps that have the same component int length = list.size(); for (int i = 0; i < length; ++i) { ApplicationInfo info = list.get(i); int removeIndex = findAppByComponent(mApps, info); if (removeIndex > -1) { mApps.remove(removeIndex); } } } @Override public void removeApps(ArrayList<ApplicationInfo> list) { removeAppsWithoutInvalidate(list); updatePageCounts(); invalidatePageData(); } @Override public void updateApps(ArrayList<ApplicationInfo> list) { // We remove and re-add the updated applications list because it's properties may have // changed (ie. the title), and this will ensure that the items will be in their proper // place in the list. removeAppsWithoutInvalidate(list); addAppsWithoutInvalidate(list); updatePageCounts(); invalidatePageData(); } @Override public void reset() { AppsCustomizeTabHost tabHost = getTabHost(); String tag = tabHost.getCurrentTabTag(); - if (!tag.equals(tabHost.getTabTagForContentType(ContentType.Applications))) { - tabHost.setCurrentTabFromContent(ContentType.Applications); + if (tag != null) { + if (!tag.equals(tabHost.getTabTagForContentType(ContentType.Applications))) { + tabHost.setCurrentTabFromContent(ContentType.Applications); + } } if (mCurrentPage != 0) { invalidatePageData(0); } } private AppsCustomizeTabHost getTabHost() { return (AppsCustomizeTabHost) mLauncher.findViewById(R.id.apps_customize_pane); } @Override public void dumpState() { // TODO: Dump information related to current list of Applications, Widgets, etc. ApplicationInfo.dumpApplicationInfoList(LOG_TAG, "mApps", mApps); dumpAppWidgetProviderInfoList(LOG_TAG, "mWidgets", mWidgets); } private void dumpAppWidgetProviderInfoList(String tag, String label, ArrayList<Object> list) { Log.d(tag, label + " size=" + list.size()); for (Object i: list) { if (i instanceof AppWidgetProviderInfo) { AppWidgetProviderInfo info = (AppWidgetProviderInfo) i; Log.d(tag, " label=\"" + info.label + "\" previewImage=" + info.previewImage + " resizeMode=" + info.resizeMode + " configure=" + info.configure + " initialLayout=" + info.initialLayout + " minWidth=" + info.minWidth + " minHeight=" + info.minHeight); } else if (i instanceof ResolveInfo) { ResolveInfo info = (ResolveInfo) i; Log.d(tag, " label=\"" + info.loadLabel(mPackageManager) + "\" icon=" + info.icon); } } } @Override public void surrender() { // TODO: If we are in the middle of any process (ie. for holographic outlines, etc) we // should stop this now. // Stop all background tasks cancelAllTasks(); } /* * We load an extra page on each side to prevent flashes from scrolling and loading of the * widget previews in the background with the AsyncTasks. */ protected int getAssociatedLowerPageBound(int page) { return Math.max(0, page - 2); } protected int getAssociatedUpperPageBound(int page) { final int count = getChildCount(); return Math.min(page + 2, count - 1); } @Override protected String getCurrentPageDescription() { int page = (mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage; int stringId = R.string.default_scroll_format; int count = 0; if (page < mNumAppsPages) { stringId = R.string.apps_customize_apps_scroll_format; count = mNumAppsPages; } else { page -= mNumAppsPages; stringId = R.string.apps_customize_widgets_scroll_format; count = mNumWidgetPages; } return String.format(mContext.getString(stringId), page + 1, count); } }
false
false
null
null
diff --git a/tcap/tcap-impl/src/main/java/org/mobicents/protocols/ss7/tcap/DialogImpl.java b/tcap/tcap-impl/src/main/java/org/mobicents/protocols/ss7/tcap/DialogImpl.java index 267dacccd..0eef84a38 100644 --- a/tcap/tcap-impl/src/main/java/org/mobicents/protocols/ss7/tcap/DialogImpl.java +++ b/tcap/tcap-impl/src/main/java/org/mobicents/protocols/ss7/tcap/DialogImpl.java @@ -1,1202 +1,1204 @@ /* * JBoss, Home of Professional Open Source * Copyright 2011, Red Hat, Inc. and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.mobicents.protocols.ss7.tcap; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.mobicents.protocols.asn.AsnOutputStream; import org.mobicents.protocols.ss7.sccp.parameter.SccpAddress; import org.mobicents.protocols.ss7.tcap.api.TCAPException; import org.mobicents.protocols.ss7.tcap.api.TCAPSendException; import org.mobicents.protocols.ss7.tcap.api.tc.component.OperationState; import org.mobicents.protocols.ss7.tcap.api.tc.dialog.Dialog; import org.mobicents.protocols.ss7.tcap.api.tc.dialog.TRPseudoState; import org.mobicents.protocols.ss7.tcap.api.tc.dialog.events.TCBeginRequest; import org.mobicents.protocols.ss7.tcap.api.tc.dialog.events.TCContinueRequest; import org.mobicents.protocols.ss7.tcap.api.tc.dialog.events.TCEndRequest; import org.mobicents.protocols.ss7.tcap.api.tc.dialog.events.TCUniRequest; import org.mobicents.protocols.ss7.tcap.api.tc.dialog.events.TCUserAbortRequest; import org.mobicents.protocols.ss7.tcap.api.tc.dialog.events.TerminationType; import org.mobicents.protocols.ss7.tcap.asn.AbortSource; import org.mobicents.protocols.ss7.tcap.asn.AbortSourceType; import org.mobicents.protocols.ss7.tcap.asn.ApplicationContextName; import org.mobicents.protocols.ss7.tcap.asn.DialogAPDU; import org.mobicents.protocols.ss7.tcap.asn.DialogAPDUType; import org.mobicents.protocols.ss7.tcap.asn.DialogAbortAPDU; import org.mobicents.protocols.ss7.tcap.asn.DialogPortion; import org.mobicents.protocols.ss7.tcap.asn.DialogRequestAPDU; import org.mobicents.protocols.ss7.tcap.asn.DialogResponseAPDU; import org.mobicents.protocols.ss7.tcap.asn.DialogServiceUserType; import org.mobicents.protocols.ss7.tcap.asn.DialogUniAPDU; import org.mobicents.protocols.ss7.tcap.asn.InvokeImpl; import org.mobicents.protocols.ss7.tcap.asn.Result; import org.mobicents.protocols.ss7.tcap.asn.ResultSourceDiagnostic; import org.mobicents.protocols.ss7.tcap.asn.ResultType; import org.mobicents.protocols.ss7.tcap.asn.TCAbortMessageImpl; import org.mobicents.protocols.ss7.tcap.asn.TCBeginMessageImpl; import org.mobicents.protocols.ss7.tcap.asn.TCContinueMessageImpl; import org.mobicents.protocols.ss7.tcap.asn.TCEndMessageImpl; import org.mobicents.protocols.ss7.tcap.asn.TCUniMessageImpl; import org.mobicents.protocols.ss7.tcap.asn.TcapFactory; import org.mobicents.protocols.ss7.tcap.asn.UserInformation; import org.mobicents.protocols.ss7.tcap.asn.comp.Component; import org.mobicents.protocols.ss7.tcap.asn.comp.ComponentType; import org.mobicents.protocols.ss7.tcap.asn.comp.PAbortCauseType; import org.mobicents.protocols.ss7.tcap.asn.comp.TCAbortMessage; import org.mobicents.protocols.ss7.tcap.asn.comp.TCBeginMessage; import org.mobicents.protocols.ss7.tcap.asn.comp.TCContinueMessage; import org.mobicents.protocols.ss7.tcap.asn.comp.TCEndMessage; import org.mobicents.protocols.ss7.tcap.asn.comp.TCUniMessage; import org.mobicents.protocols.ss7.tcap.tc.dialog.events.DialogPrimitiveFactoryImpl; import org.mobicents.protocols.ss7.tcap.tc.dialog.events.TCBeginIndicationImpl; import org.mobicents.protocols.ss7.tcap.tc.dialog.events.TCContinueIndicationImpl; import org.mobicents.protocols.ss7.tcap.tc.dialog.events.TCEndIndicationImpl; import org.mobicents.protocols.ss7.tcap.tc.dialog.events.TCPAbortIndicationImpl; import org.mobicents.protocols.ss7.tcap.tc.dialog.events.TCUniIndicationImpl; import org.mobicents.protocols.ss7.tcap.tc.dialog.events.TCUserAbortIndicationImpl; /** * @author baranowb * @author amit bhayani * */ public class DialogImpl implements Dialog { // timeout of remove task after TC_END private static final int _REMOVE_TIMEOUT = 30000; private static final Logger logger = Logger.getLogger(DialogImpl.class); // sent/received acn, holds last acn/ui. private ApplicationContextName lastACN; private UserInformation lastUI; // optional private Long localTransactionId; private Long remoteTransactionId; private SccpAddress localAddress; private SccpAddress remoteAddress; private TRPseudoState state = TRPseudoState.Idle; private boolean structured = true; // invokde ID space :) private static final boolean _INVOKEID_TAKEN = true; private static final boolean _INVOKEID_FREE = false; private static final int _INVOKE_TABLE_SHIFT = 128; private boolean[] invokeIDTable = new boolean[255]; private int freeCount = invokeIDTable.length; // only originating side keeps FSM, see: Q.771 - 3.1.5 private InvokeImpl[] operationsSent = new InvokeImpl[invokeIDTable.length]; private ScheduledExecutorService executor; // scheduled components list private List<Component> scheduledComponentList = new ArrayList<Component>(); private TCAPProviderImpl provider; private int seqControl; // If the Dialogue Portion is sent in TCBegin message, the first received // Continue message should have the Dialogue Portio too private boolean dpSentInBegin = false; private static final int getIndexFromInvokeId(Long l) { int tmp = l.intValue(); return tmp + _INVOKE_TABLE_SHIFT; } private static final Long getInvokeIdFromIndex(int index) { int tmp = index - _INVOKE_TABLE_SHIFT; return new Long(tmp); } // DialogImpl(SccpAddress localAddress, SccpAddress remoteAddress, Long // origTransactionId, ScheduledExecutorService executor, // TCAProviderImpl provider, ApplicationContextName acn, UserInformation[] // ui) { DialogImpl(SccpAddress localAddress, SccpAddress remoteAddress, Long origTransactionId, boolean structured, ScheduledExecutorService executor, TCAPProviderImpl provider, int seqControl) { super(); this.localAddress = localAddress; this.remoteAddress = remoteAddress; this.localTransactionId = origTransactionId; this.executor = executor; this.provider = provider; // this.initialACN = acn; // this.initialUI = ui; if (origTransactionId > 0) { this.structured = true; } else { this.structured = false; } this.structured = structured; this.seqControl = seqControl; } public void release() { this.setState(TRPseudoState.Expunged); } /* * (non-Javadoc) * * @see org.mobicents.protocols.ss7.tcap.api.tc.dialog.Dialog#getDialogId() */ public Long getDialogId() { return localTransactionId; } /* * (non-Javadoc) * * @see * org.mobicents.protocols.ss7.tcap.api.tc.dialog.Dialog#getNewInvokeId() */ public synchronized Long getNewInvokeId() { if (freeCount == 0) { return null; } // find new... Long r = null; // tmp for test. // for (int index = 0; index < this.invokeIDTable.length; index++) { for (int index = _INVOKE_TABLE_SHIFT + 1; index < this.invokeIDTable.length; index++) { if (this.invokeIDTable[index] == _INVOKEID_FREE) { freeCount--; this.invokeIDTable[index] = _INVOKEID_TAKEN; r = this.getInvokeIdFromIndex(index); break; } } return r; } /* * (non-Javadoc) * * @see * org.mobicents.protocols.ss7.tcap.api.tc.dialog.Dialog#cancelInvocation * (java.lang.Long) */ public boolean cancelInvocation(Long invokeId) throws TCAPException { int index = getIndexFromInvokeId(invokeId); if (index < 0 || index >= operationsSent.length) { throw new TCAPException("Wrong invoke id passed."); } // lookup through send buffer. for (index = 0; index < scheduledComponentList.size(); index++) { Component cr = scheduledComponentList.get(index); if (cr.getType() == ComponentType.Invoke && cr.getInvokeId().equals(invokeId)) { // lucky // TCInvokeRequestImpl invoke = (TCInvokeRequestImpl) cr; // there is no notification on cancel? scheduledComponentList.remove(index); return true; } } return false; } private synchronized void freeInvokeId(Long l) { int index = getIndexFromInvokeId(l); this.freeCount--; this.invokeIDTable[index] = _INVOKEID_FREE; } /* * (non-Javadoc) * * @see * org.mobicents.protocols.ss7.tcap.api.tc.dialog.Dialog#getRemoteAddress() */ public SccpAddress getRemoteAddress() { return this.remoteAddress; } /* * (non-Javadoc) * * @see * org.mobicents.protocols.ss7.tcap.api.tc.dialog.Dialog#getLocalAddress() */ public SccpAddress getLocalAddress() { return this.localAddress; } /* * (non-Javadoc) * * @see * org.mobicents.protocols.ss7.tcap.api.tc.dialog.Dialog#isEstabilished() */ public boolean isEstabilished() { return this.state == TRPseudoState.Active; } /* * (non-Javadoc) * * @see org.mobicents.protocols.ss7.tcap.api.tc.dialog.Dialog#isStructured() */ public boolean isStructured() { return this.structured; } /** * @return the acn */ public ApplicationContextName getApplicationContextName() { return lastACN; } /** * @return the ui */ public UserInformation getUserInformation() { return lastUI; } /* * (non-Javadoc) * * @see * org.mobicents.protocols.ss7.tcap.api.tc.dialog.Dialog#send(org.mobicents * .protocols.ss7.tcap.api.tc.dialog.events.TCBeginRequest) */ public void send(TCBeginRequest event) throws TCAPSendException { if (this.state != TRPseudoState.Idle) { throw new TCAPSendException("Can not send Begin in this state: " + this.state); } if (!this.isStructured()) { throw new TCAPSendException("Unstructured dialogs do not use Begin"); } TCBeginMessageImpl tcbm = (TCBeginMessageImpl) TcapFactory.createTCBeginMessage(); // build DP if (event.getApplicationContextName() != null) { this.dpSentInBegin = true; DialogPortion dp = TcapFactory.createDialogPortion(); dp.setUnidirectional(false); DialogRequestAPDU apdu = TcapFactory.createDialogAPDURequest(); dp.setDialogAPDU(apdu); apdu.setApplicationContextName(event.getApplicationContextName()); + this.lastACN = event.getApplicationContextName(); if (event.getUserInformation() != null) { apdu.setUserInformation(event.getUserInformation()); + this.lastUI = event.getUserInformation(); } tcbm.setDialogPortion(dp); } // now comps tcbm.setOriginatingTransactionId(this.localTransactionId); if (this.scheduledComponentList.size() > 0) { Component[] componentsToSend = new Component[this.scheduledComponentList.size()]; this.prepareComponents(componentsToSend); tcbm.setComponent(componentsToSend); } AsnOutputStream aos = new AsnOutputStream(); try { tcbm.encode(aos); this.provider.send(aos.toByteArray(), event.getQOS() == null ? 0 : event.getQOS().byteValue(), this.remoteAddress, this.localAddress, this.seqControl); this.setState(TRPseudoState.InitialSent); this.scheduledComponentList.clear(); } catch (Exception e) { // FIXME: add proper handling here. TC-NOTICE ? // FIXME: remove freshly added invokes to free invoke ID?? if (logger.isEnabledFor(Level.ERROR)) { logger.error("Failed to send message: ", e); } } } /* * (non-Javadoc) * * @see * org.mobicents.protocols.ss7.tcap.api.tc.dialog.Dialog#send(org.mobicents * .protocols.ss7.tcap.api.tc.dialog.events.TCContinueRequest) */ public void send(TCContinueRequest event) throws TCAPSendException { if (!this.isStructured()) { throw new TCAPSendException("Unstructured dialogs do not use Continue"); } if (this.state == TRPseudoState.InitialReceived) { TCContinueMessageImpl tcbm = (TCContinueMessageImpl) TcapFactory.createTCContinueMessage(); if (event.getApplicationContextName() != null) { // set dialog portion DialogPortion dp = TcapFactory.createDialogPortion(); dp.setUnidirectional(false); DialogResponseAPDU apdu = TcapFactory.createDialogAPDUResponse(); dp.setDialogAPDU(apdu); apdu.setApplicationContextName(event.getApplicationContextName()); if (event.getUserInformation() != null) { apdu.setUserInformation(event.getUserInformation()); } // WHERE THE HELL THIS COMES FROM!!!! // WHEN REJECTED IS USED !!!!! Result res = TcapFactory.createResult(); res.setResultType(ResultType.Accepted); ResultSourceDiagnostic rsd = TcapFactory.createResultSourceDiagnostic(); rsd.setDialogServiceUserType(DialogServiceUserType.Null); apdu.setResultSourceDiagnostic(rsd); apdu.setResult(res); tcbm.setDialogPortion(dp); } tcbm.setOriginatingTransactionId(this.localTransactionId); tcbm.setDestinationTransactionId(this.remoteTransactionId); if (this.scheduledComponentList.size() > 0) { Component[] componentsToSend = new Component[this.scheduledComponentList.size()]; this.prepareComponents(componentsToSend); tcbm.setComponent(componentsToSend); } // local address may change, lets check it; if (event.getOriginatingAddress() != null && !event.getOriginatingAddress().equals(this.localAddress)) { this.localAddress = event.getOriginatingAddress(); } AsnOutputStream aos = new AsnOutputStream(); try { tcbm.encode(aos); this.provider.send(aos.toByteArray(), event.getQOS() == null ? 0 : event.getQOS().byteValue(), this.remoteAddress, this.localAddress, this.seqControl); this.setState(TRPseudoState.Active); this.scheduledComponentList.clear(); } catch (Exception e) { // FIXME: add proper handling here. TC-NOTICE ? // FIXME: remove freshly added invokes to free invoke ID?? if (logger.isEnabledFor(Level.ERROR)) { logger.error("Failed to send message: ", e); } } } else if (state == TRPseudoState.Active) { // in this we ignore acn and passed args(except qos) TCContinueMessageImpl tcbm = (TCContinueMessageImpl) TcapFactory.createTCContinueMessage(); tcbm.setOriginatingTransactionId(this.localTransactionId); tcbm.setDestinationTransactionId(this.remoteTransactionId); if (this.scheduledComponentList.size() > 0) { Component[] componentsToSend = new Component[this.scheduledComponentList.size()]; this.prepareComponents(componentsToSend); tcbm.setComponent(componentsToSend); } // FIXME: SPECS SAY HERE UI/ACN CAN BE SENT, HOOOOOOOWWW!? AsnOutputStream aos = new AsnOutputStream(); try { tcbm.encode(aos); this.provider.send(aos.toByteArray(), event.getQOS() == null ? 0 : event.getQOS().byteValue(), this.remoteAddress, this.localAddress, this.seqControl); this.scheduledComponentList.clear(); } catch (Exception e) { // FIXME: add proper handling here. TC-NOTICE ? if (logger.isEnabledFor(Level.ERROR)) { logger.error("Failed to send message: ", e); } } } else { throw new TCAPSendException("Wrong state: " + this.state); } } /* * (non-Javadoc) * * @see * org.mobicents.protocols.ss7.tcap.api.tc.dialog.Dialog#send(org.mobicents * .protocols.ss7.tcap.api.tc.dialog.events.TCEndRequest) */ public void send(TCEndRequest event) throws TCAPSendException { if (!this.isStructured()) { throw new TCAPSendException("Unstructured dialogs do not use End"); } TCEndMessageImpl tcbm = null; if (state == TRPseudoState.InitialReceived) { // TC-END request primitive issued in response to a TC-BEGIN // indication primitive tcbm = (TCEndMessageImpl) TcapFactory.createTCEndMessage(); tcbm.setDestinationTransactionId(this.remoteTransactionId); if (event.getTerminationType() == TerminationType.Basic) { if (this.scheduledComponentList.size() > 0) { Component[] componentsToSend = new Component[this.scheduledComponentList.size()]; this.prepareComponents(componentsToSend); tcbm.setComponent(componentsToSend); } } else if (event.getTerminationType() == TerminationType.PreArranged) { this.scheduledComponentList.clear(); // TODO : Bartek for pre-arranged no message is sent to peer, // isn't it? } else { throw new TCAPSendException("Termination TYPE must be present"); } ApplicationContextName acn = event.getApplicationContextName(); if (acn == null) { throw new TCAPSendException("Application Context Name must be present"); } // set dialog portion DialogPortion dp = TcapFactory.createDialogPortion(); dp.setUnidirectional(false); DialogResponseAPDU apdu = TcapFactory.createDialogAPDUResponse(); dp.setDialogAPDU(apdu); apdu.setApplicationContextName(event.getApplicationContextName()); if (event.getUserInformation() != null) { apdu.setUserInformation(event.getUserInformation()); } // WHERE THE HELL THIS COMES FROM!!!! // WHEN REJECTED IS USED !!!!! Result res = TcapFactory.createResult(); res.setResultType(ResultType.Accepted); ResultSourceDiagnostic rsd = TcapFactory.createResultSourceDiagnostic(); rsd.setDialogServiceUserType(DialogServiceUserType.Null); apdu.setResultSourceDiagnostic(rsd); apdu.setResult(res); tcbm.setDialogPortion(dp); } else if (state == TRPseudoState.Active) { tcbm = (TCEndMessageImpl) TcapFactory.createTCEndMessage(); tcbm.setDestinationTransactionId(this.remoteTransactionId); if (event.getTerminationType() == TerminationType.Basic) { if (this.scheduledComponentList.size() > 0) { Component[] componentsToSend = new Component[this.scheduledComponentList.size()]; this.prepareComponents(componentsToSend); tcbm.setComponent(componentsToSend); } } else if (event.getTerminationType() == TerminationType.PreArranged) { this.scheduledComponentList.clear(); } else { throw new TCAPSendException("Termination TYPE must be present"); } // ITU - T Q774 Section 3.2.2.1 Dialogue Control // when a dialogue portion is received inopportunely (e.g. a // dialogue APDU is received during the active state of a // transaction). // Don't set the Application Context or Dialogue Portion in Active // state } else { throw new TCAPSendException(String.format("State is not %s or %s: it is %s", TRPseudoState.Active, TRPseudoState.InitialReceived, this.state)); } // FIXME: SPECS SAY HERE UI/ACN CAN BE SENT, HOOOOOOOWWW!? AsnOutputStream aos = new AsnOutputStream(); try { tcbm.encode(aos); this.provider.send(aos.toByteArray(), event.getQOS() == null ? 0 : event.getQOS().byteValue(), this.remoteAddress, this.localAddress, this.seqControl); this.setState(TRPseudoState.Expunged); this.scheduledComponentList.clear(); } catch (Exception e) { // FIXME: add proper handling here. TC-NOTICE ? // FIXME: remove freshly added invokes to free invoke ID?? if (logger.isEnabledFor(Level.ERROR)) { logger.error("Failed to send message: ", e); } } } /* * (non-Javadoc) * * @see org.mobicents.protocols.ss7.tcap.api.tc.dialog.Dialog#sendUni() */ public void send(TCUniRequest event) throws TCAPSendException { if (this.isStructured()) { throw new TCAPSendException("Structured dialogs do not use Uni"); } TCUniMessageImpl msg = (TCUniMessageImpl) TcapFactory.createTCUniMessage(); if (event.getApplicationContextName() != null) { DialogPortion dp = TcapFactory.createDialogPortion(); DialogUniAPDU apdu = TcapFactory.createDialogAPDUUni(); apdu.setApplicationContextName(event.getApplicationContextName()); if (event.getUserInformation() != null) { apdu.setUserInformation(event.getUserInformation()); } dp.setUnidirectional(true); dp.setDialogAPDU(apdu); msg.setDialogPortion(dp); } if (this.scheduledComponentList.size() > 0) { Component[] componentsToSend = new Component[this.scheduledComponentList.size()]; this.prepareComponents(componentsToSend); msg.setComponent(componentsToSend); } AsnOutputStream aos = new AsnOutputStream(); try { msg.encode(aos); this.provider.send(aos.toByteArray(), event.getQOS() == null ? 0 : event.getQOS().byteValue(), this.remoteAddress, this.localAddress, this.seqControl); this.setState(TRPseudoState.Expunged); this.scheduledComponentList.clear(); } catch (Exception e) { // FIXME: add proper handling here. TC-NOTICE ? // FIXME: remove freshly added invokes to free invoke ID?? if (logger.isEnabledFor(Level.ERROR)) { logger.error("Failed to send message: ", e); } } } public void send(TCUserAbortRequest event) throws TCAPSendException { // is abort allowed in "Active" state ? if (!isStructured()) { throw new TCAPSendException("Unstructured dialog can not be aborted!"); } if (this.state == TRPseudoState.InitialReceived || this.state == TRPseudoState.InitialSent || this.state == TRPseudoState.Active) { // allowed if (event.getUserInformation() == null) { throw new IllegalArgumentException("User information MUST be present."); } DialogPortion dp = TcapFactory.createDialogPortion(); dp.setUnidirectional(false); if (event.getDialogServiceUserType() != null) { // ITU T Q.774 Read Dialogue end on page 12 and 3.2.2 Abnormal // procedures on page 13 and 14 DialogResponseAPDU apdu = TcapFactory.createDialogAPDUResponse(); apdu.setApplicationContextName(event.getApplicationContextName()); apdu.setUserInformation(event.getUserInformation()); Result res = TcapFactory.createResult(); res.setResultType(ResultType.RejectedPermanent); ResultSourceDiagnostic rsd = TcapFactory.createResultSourceDiagnostic(); rsd.setDialogServiceUserType(event.getDialogServiceUserType()); apdu.setResultSourceDiagnostic(rsd); apdu.setResult(res); dp.setDialogAPDU(apdu); } else { // When a BEGIN message has been received (i.e. the dialogue is // in the "Initiation Received" state) containing a Dialogue // Request (AARQ) APDU, the TC-User can abort for any user // defined reason. In such a situation, the TC-User issues a // TC-U-ABORT request primitive with the Abort Reason parameter // absent or with set to any value other than either // "application-context-name-not-supported" or // dialogue-refused". In such a case, a Dialogue Abort (ABRT) APDU is generated with abort-source coded as "dialogue-service-user", // and supplied as the User Data parameter of the TR-U-ABORT // request primitive. User information (if any) provided in the // TC-U-ABORT request primitive is coded in the user-information // field of the ABRT APDU. DialogAbortAPDU dapdu = TcapFactory.createDialogAPDUAbort(); AbortSource as = TcapFactory.createAbortSource(); as.setAbortSourceType(AbortSourceType.User); dapdu.setAbortSource(as); dapdu.setUserInformation(event.getUserInformation()); dp.setDialogAPDU(dapdu); } TCAbortMessageImpl msg = (TCAbortMessageImpl) TcapFactory.createTCAbortMessage(); msg.setDestinationTransactionId(this.remoteTransactionId); msg.setDialogPortion(dp); // no components // ... AsnOutputStream aos = new AsnOutputStream(); try { msg.encode(aos); this.provider.send(aos.toByteArray(), event.getQOS() == null ? 0 : event.getQOS().byteValue(), this.remoteAddress, this.localAddress, this.seqControl); this.setState(TRPseudoState.Expunged); this.scheduledComponentList.clear(); } catch (Exception e) { // FIXME: add proper handling here. TC-NOTICE ? // FIXME: remove freshly added invokes to free invoke ID?? if (logger.isEnabledFor(Level.ERROR)) { logger.error("Failed to send message: ", e); } } } } /* * (non-Javadoc) * * @see * org.mobicents.protocols.ss7.tcap.api.tc.dialog.Dialog#sendComponent(org * .mobicents.protocols.ss7.tcap.api.tc.component.ComponentRequest) */ public void sendComponent(Component componentRequest) throws TCAPSendException { if (componentRequest.getType() == ComponentType.Invoke) { InvokeImpl invoke = (InvokeImpl) componentRequest; // check if its taken! int invokeIndex = this.getIndexFromInvokeId(invoke.getInvokeId()); if (this.operationsSent[invokeIndex] != null) { // This is TC-L-REJECT? // TC-L-REJECT (local reject): Informs the local TC-user that a // Component sublayer detected // invalid component was received. <-- who wrote this? throw new TCAPSendException("There is already operation with such invoke id!"); } invoke.setState(OperationState.Pending); invoke.setDialog(this); } this.scheduledComponentList.add(componentRequest); } private void prepareComponents(Component[] res) { int index = 0; while (this.scheduledComponentList.size() > index) { Component cr = this.scheduledComponentList.get(index); // FIXME: add more ? if (cr.getType() == ComponentType.Invoke) { InvokeImpl in = (InvokeImpl) cr; // check not null? this.operationsSent[this.getIndexFromInvokeId(in.getInvokeId())] = in; // FIXME: deffer this ? in.setState(OperationState.Sent); } res[index++] = cr; } } // ///////////////// // LOCAL METHODS // // ///////////////// /** * @return the localTransactionId */ Long getLocalTransactionId() { return localTransactionId; } /** * @param localTransactionId * the localTransactionId to set */ void setLocalTransactionId(Long localTransactionId) { this.localTransactionId = localTransactionId; } /** * @return the remoteTransactionId */ Long getRemoteTransactionId() { return remoteTransactionId; } /** * @param remoteTransactionId * the remoteTransactionId to set */ void setRemoteTransactionId(Long remoteTransactionId) { this.remoteTransactionId = remoteTransactionId; } /** * @param localAddress * the localAddress to set */ void setLocalAddress(SccpAddress localAddress) { this.localAddress = localAddress; } /** * @param remoteAddress * the remoteAddress to set */ void setRemoteAddress(SccpAddress remoteAddress) { this.remoteAddress = remoteAddress; } void processUni(TCUniMessage msg, SccpAddress localAddress, SccpAddress remoteAddress) throws TCAPException { // this is invoked ONLY for server. if (state != TRPseudoState.Idle) { // should we terminate dialog here? if (logger.isEnabledFor(Level.ERROR)) { logger.error("Received Uni primitive, but state is not: " + TRPseudoState.Idle + ". Dialog: " + this); } throw new TCAPException("Received Uni primitive, but state is not: " + TRPseudoState.Idle + ". Dialog: " + this); } // lets setup this.setRemoteAddress(remoteAddress); this.setLocalAddress(localAddress); // no dialog portion! // convert to indications TCUniIndicationImpl tcUniIndication = (TCUniIndicationImpl) ((DialogPrimitiveFactoryImpl) this.provider .getDialogPrimitiveFactory()).createUniIndication(this); tcUniIndication.setDestinationAddress(localAddress); tcUniIndication.setOriginatingAddress(remoteAddress); // now comps Component[] comps = msg.getComponent(); tcUniIndication.setComponents(comps); if (msg.getDialogPortion() != null) { // it should be dialog req? DialogPortion dp = msg.getDialogPortion(); DialogUniAPDU apdu = (DialogUniAPDU) dp.getDialogAPDU(); this.lastACN = apdu.getApplicationContextName(); this.lastUI = apdu.getUserInformation(); tcUniIndication.setApplicationContextName(this.lastACN); tcUniIndication.setUserInformation(this.lastUI); } // lets deliver to provider, this MUST not throw anything this.provider.deliver(this, tcUniIndication); // schedule removal this.release(); } void processBegin(TCBeginMessage msg, SccpAddress localAddress, SccpAddress remoteAddress) throws TCAPException { // this is invoked ONLY for server. if (state != TRPseudoState.Idle) { // should we terminate dialog here? if (logger.isEnabledFor(Level.ERROR)) { logger.error("Received Begin primitive, but state is not: " + TRPseudoState.Idle + ". Dialog: " + this); } throw new TCAPException("Received Begin primitive, but state is not: " + TRPseudoState.Idle + ". Dialog: " + this); } // lets setup this.setRemoteAddress(remoteAddress); this.setLocalAddress(localAddress); this.setRemoteTransactionId(msg.getOriginatingTransactionId()); // convert to indications TCBeginIndicationImpl tcBeginIndication = (TCBeginIndicationImpl) ((DialogPrimitiveFactoryImpl) this.provider .getDialogPrimitiveFactory()).createBeginIndication(this); tcBeginIndication.setDestinationAddress(localAddress); tcBeginIndication.setOriginatingAddress(remoteAddress); // if APDU and context data present, lets store it DialogPortion dialogPortion = msg.getDialogPortion(); if (dialogPortion != null) { // this should not be null.... DialogAPDU apdu = dialogPortion.getDialogAPDU(); if (apdu.getType() != DialogAPDUType.Request) { throw new TCAPException("Received non-Request APDU: " + apdu.getType() + ". Dialog: " + this); } DialogRequestAPDU requestAPDU = (DialogRequestAPDU) apdu; this.lastACN = requestAPDU.getApplicationContextName(); this.lastUI = requestAPDU.getUserInformation(); tcBeginIndication.setApplicationContextName(this.lastACN); tcBeginIndication.setUserInformation(this.lastUI); } tcBeginIndication.setComponents(msg.getComponent()); // change state - before we deliver this.setState(TRPseudoState.InitialReceived); // lets deliver to provider this.provider.deliver(this, tcBeginIndication); } void processContinue(TCContinueMessage msg, SccpAddress localAddress, SccpAddress remoteAddress) throws TCAPException { if (state == TRPseudoState.InitialSent) { // TCContinueIndicationImpl tcContinueIndication = (TCContinueIndicationImpl) ((DialogPrimitiveFactoryImpl) this.provider .getDialogPrimitiveFactory()).createContinueIndication(this); // in continue remote address MAY change, so lets update! this.setRemoteAddress(remoteAddress); this.setRemoteTransactionId(msg.getOriginatingTransactionId()); tcContinueIndication.setOriginatingAddress(remoteAddress); // here we will receive DialogResponse APDU - if request was // present! DialogPortion dialogPortion = msg.getDialogPortion(); if (dialogPortion != null) { // this should not be null.... DialogAPDU apdu = dialogPortion.getDialogAPDU(); if (apdu.getType() != DialogAPDUType.Response) { throw new TCAPException("Received non-Response APDU: " + apdu.getType() + ". Dialog: " + this); } DialogResponseAPDU responseAPDU = (DialogResponseAPDU) apdu; // this will be present if APDU is present. if (!responseAPDU.getApplicationContextName().equals(this.lastACN)) { this.lastACN = responseAPDU.getApplicationContextName(); } if (responseAPDU.getUserInformation() != null) { this.lastUI = responseAPDU.getUserInformation(); } tcContinueIndication.setApplicationContextName(responseAPDU.getApplicationContextName()); tcContinueIndication.setUserInformation(responseAPDU.getUserInformation()); } else if (this.dpSentInBegin) { // ITU - T Q.774 3.2.2 : Abnormal procedure page 13 // when a dialogue portion is missing when its presence is // mandatory (e.g. an AARQ APDU was sent in a Begin message, but // no AARE APDU was received in the first backward Continue // message) or when a dialogue portion is received inopportunely // (e.g. a dialogue APDU is received during the active state of // a transaction). At the side where the abnormality is // detected, a TC-P-ABORT indication primitive is issued to the // local TC-user with the "P-Abort" parameter in the primitive // set to "abnormal dialogue". At the same time, a TR-U-ABORT // request primitive is issued to the transaction sub-layer with // an ABRT APDU as user data. The abort-source field of the ABRT // APDU is set to "dialogue-service-provider" and the user // information field is absent. // its TC-P-Abort TCPAbortIndicationImpl tcAbortIndication = (TCPAbortIndicationImpl) ((DialogPrimitiveFactoryImpl) this.provider .getDialogPrimitiveFactory()).createPAbortIndication(this); tcAbortIndication.setPAbortCause(PAbortCauseType.AbnormalDialogue); this.provider.deliver(this, tcAbortIndication); // Send P-Abort to remote sendPAbort(); return; } tcContinueIndication.setOriginatingAddress(remoteAddress); // now comps tcContinueIndication.setComponents(processOperationsState(msg.getComponent())); // change state this.setState(TRPseudoState.Active); // lets deliver to provider this.provider.deliver(this, tcContinueIndication); } else if (state == TRPseudoState.Active) { // XXX: here NO APDU will be present, hence, no ACN/UI change TCContinueIndicationImpl tcContinueIndication = (TCContinueIndicationImpl) ((DialogPrimitiveFactoryImpl) this.provider .getDialogPrimitiveFactory()).createContinueIndication(this); tcContinueIndication.setOriginatingAddress(remoteAddress); // now comps tcContinueIndication.setComponents(processOperationsState(msg.getComponent())); // lets deliver to provider this.provider.deliver(this, tcContinueIndication); } else { throw new TCAPException("Received Continue primitive, but state is not proper: " + this.state + ", Dialog: " + this); } } // Send P-Abort to peer private void sendPAbort() { DialogPortion dp = TcapFactory.createDialogPortion(); dp.setUnidirectional(false); DialogAbortAPDU dapdu = TcapFactory.createDialogAPDUAbort(); AbortSource as = TcapFactory.createAbortSource(); as.setAbortSourceType(AbortSourceType.Provider); dapdu.setAbortSource(as); dp.setDialogAPDU(dapdu); TCAbortMessageImpl msg = (TCAbortMessageImpl) TcapFactory.createTCAbortMessage(); msg.setDestinationTransactionId(this.remoteTransactionId); msg.setDialogPortion(dp); AsnOutputStream aos = new AsnOutputStream(); try { msg.encode(aos); // TODO how Qos will be calculated? this.provider.send(aos.toByteArray(), (byte) 0, this.remoteAddress, this.localAddress, this.seqControl); this.setState(TRPseudoState.Expunged); this.scheduledComponentList.clear(); } catch (Exception e) { // FIXME: remove freshly added invokes to free invoke ID?? if (logger.isEnabledFor(Level.ERROR)) { logger.error("Failed to send message: ", e); } } } void processEnd(TCEndMessage msg, SccpAddress localAddress, SccpAddress remoteAddress) throws TCAPException { TCEndIndicationImpl tcEndIndication = (TCEndIndicationImpl) ((DialogPrimitiveFactoryImpl) this.provider .getDialogPrimitiveFactory()).createEndIndication(this); DialogPortion dialogPortion = msg.getDialogPortion(); if (dialogPortion != null) { DialogAPDU apdu = dialogPortion.getDialogAPDU(); if (apdu.getType() != DialogAPDUType.Response) { throw new TCAPException("Received non-Response APDU: " + apdu.getType() + ". Dialog: " + this); } DialogResponseAPDU responseAPDU = (DialogResponseAPDU) apdu; // this will be present if APDU is present. if (!responseAPDU.getApplicationContextName().equals(this.lastACN)) { this.lastACN = responseAPDU.getApplicationContextName(); } if (responseAPDU.getUserInformation() != null) { this.lastUI = responseAPDU.getUserInformation(); } tcEndIndication.setApplicationContextName(responseAPDU.getApplicationContextName()); tcEndIndication.setUserInformation(responseAPDU.getUserInformation()); } // now comps tcEndIndication.setComponents(processOperationsState(msg.getComponent())); // FIXME: add ACN, UI, hooooow? // lets deliver to provider // change state before delivery this.setState(TRPseudoState.Expunged); this.provider.deliver(this, tcEndIndication); } void processAbort(TCAbortMessage msg, SccpAddress localAddress2, SccpAddress remoteAddress2) { // now set cause - it can have APDU or external ;[ // FIXME: handle external AbortSource abrtSrc = null; UserInformation userInfo = null; DialogPortion dp = msg.getDialogPortion(); if (dp != null) { DialogAPDU apdu = dp.getDialogAPDU(); if (apdu != null && apdu.getType() == DialogAPDUType.Abort) { DialogAbortAPDU abortApdu = (DialogAbortAPDU) apdu; abrtSrc = abortApdu.getAbortSource(); userInfo = abortApdu.getUserInformation(); } } if (msg.getPAbortCause() != null || (abrtSrc != null && abrtSrc.getAbortSourceType() == AbortSourceType.Provider)) { // its TC-P-Abort TCPAbortIndicationImpl tcAbortIndication = (TCPAbortIndicationImpl) ((DialogPrimitiveFactoryImpl) this.provider .getDialogPrimitiveFactory()).createPAbortIndication(this); tcAbortIndication.setPAbortCause(msg.getPAbortCause()); this.setState(TRPseudoState.Expunged); this.provider.deliver(this, tcAbortIndication); } else { // its TC-U-Abort TCUserAbortIndicationImpl tcAbortIndication = (TCUserAbortIndicationImpl) ((DialogPrimitiveFactoryImpl) this.provider .getDialogPrimitiveFactory()).createUAbortIndication(this); // FIXME: it can have External in apdu, add handling tcAbortIndication.setUserInformation(userInfo); tcAbortIndication.setAbortSource(abrtSrc); this.setState(TRPseudoState.Expunged); this.provider.deliver(this, tcAbortIndication); } // lets deliver to provider // change state before delivery } private Component[] processOperationsState(Component[] components) { if (components == null) { return null; } List<Component> resultingIndications = new ArrayList<Component>(); for (Component ci : components) { int index = getIndexFromInvokeId(ci.getInvokeId()); InvokeImpl invoke = this.operationsSent[index]; switch (ci.getType()) { case ReturnResultLast: if (invoke == null) { // FIXME: send something back? } else { invoke.onReturnResultLast(); if (invoke.isSuccessReported()) { resultingIndications.add(ci); } } break; // case Reject_U: // break; // case Reject_R: // break; case ReturnError: if (invoke == null) { // FIXME: send something back? } else { invoke.onError(); if (invoke.isErrorReported()) { resultingIndications.add(ci); } } break; default: resultingIndications.add(ci); break; } } components = new Component[resultingIndications.size()]; components = resultingIndications.toArray(components); return components; } private synchronized void setState(TRPseudoState newState) { // add checks? if (this.state == TRPseudoState.Expunged) { return; } this.state = newState; if (newState == TRPseudoState.Expunged) { RemovalTimerTask rtt = new RemovalTimerTask(); rtt.d = this; this.executor.schedule(rtt, _REMOVE_TIMEOUT, TimeUnit.MILLISECONDS); // provider.release(this); } } private class RemovalTimerTask implements Runnable { DialogImpl d; public void run() { provider.release(d); } } // //////////////////// // IND like methods // // /////////////////// public void operationEnded(InvokeImpl tcInvokeRequestImpl) { // this op died cause of timeout, TC-L-CANCEL! int index = getIndexFromInvokeId(tcInvokeRequestImpl.getInvokeId()); freeInvokeId(tcInvokeRequestImpl.getInvokeId()); this.operationsSent[index] = null; // lets call listener // This is done actually with COmponentIndication .... } /* * (non-Javadoc) * * @see * org.mobicents.protocols.ss7.tcap.api.tc.dialog.Dialog#operationEnded( * org.mobicents.protocols.ss7.tcap.tc.component.TCInvokeRequestImpl) */ public void operationTimedOut(InvokeImpl invoke) { // this op died cause of timeout, TC-L-CANCEL! int index = getIndexFromInvokeId(invoke.getInvokeId()); freeInvokeId(invoke.getInvokeId()); this.operationsSent[index] = null; // lets call listener this.provider.operationTimedOut(invoke); } // TC-TIMER-RESET public void resetTimer(Long invokeId) throws TCAPException { int index = getIndexFromInvokeId(invokeId); InvokeImpl invoke = operationsSent[index]; if (invoke == null) { throw new TCAPException("No operation with this ID"); } invoke.startTimer(); } public TRPseudoState getState() { return this.state; } /* * (non-Javadoc) * * @see java.lang.Object#toString() */ @Override public String toString() { return super.toString() + ": Local[" + this.localTransactionId + "] Remote[" + this.remoteTransactionId + "], LocalAddress[" + localAddress + "] RemoteAddress[" + this.remoteAddress + "]"; } }
false
false
null
null
diff --git a/src/net/cyclestreets/views/overlay/LocationOverlay.java b/src/net/cyclestreets/views/overlay/LocationOverlay.java index a04dfa2f..99278766 100644 --- a/src/net/cyclestreets/views/overlay/LocationOverlay.java +++ b/src/net/cyclestreets/views/overlay/LocationOverlay.java @@ -1,142 +1,142 @@ package net.cyclestreets.views.overlay; import net.cyclestreets.R; import org.osmdroid.util.GeoPoint; import org.osmdroid.views.MapView; import org.osmdroid.views.overlay.MyLocationOverlay; import android.content.Context; import android.content.res.Resources; import android.graphics.Canvas; import android.location.Location; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; public class LocationOverlay extends MyLocationOverlay implements TapListener, MenuListener { private final int offset_; private final float radius_; private final OverlayButton locationButton_; private final MapView mapView_; public LocationOverlay(final Context context, final MapView mapView) { super(context, mapView); mapView_ = mapView; offset_ = OverlayHelper.offset(context); radius_ = OverlayHelper.cornerRadius(context); final Resources res = context.getResources(); locationButton_ = new OverlayButton(res.getDrawable(R.drawable.ic_menu_mylocation), offset_, offset_, radius_); } // LocationOverlay public void enableLocation(final boolean enable) { if(enable) enableMyLocation(); else disableMyLocation(); } // enableLocation public void enableAndFollowLocation(final boolean enable) { if(enable) { try { enableMyLocation(); followLocation(true); final Location lastFix = getLastFix(); if (lastFix != null) mapView_.getController().setCenter(new GeoPoint(lastFix)); } // try catch(RuntimeException e) { // might not have location service } // catch } else { followLocation(false); disableMyLocation(); } // if ... mapView_.invalidate(); } // enableAndFollowLocation //////////////////////////////////////////// @Override public void onDraw(final Canvas canvas, final MapView mapView) { // I'm not thrilled about this but there isn't any other way (short of killing // and recreating the overlay) of turning off the little here-you-are man if(!isMyLocationEnabled()) return; super.onDraw(canvas, mapView); } // onDraw @Override protected void onDrawFinished(final Canvas canvas, final MapView mapView) { } // onDrawFinished public void drawButtons(final Canvas canvas, final MapView mapView) { drawButtons(canvas); } // onDrawFinished private void drawButtons(final Canvas canvas) { locationButton_.pressed(isMyLocationEnabled()); locationButton_.draw(canvas); } // drawLocationButton //////////////////////////////////////////////// public boolean onCreateOptionsMenu(final Menu menu) { menu.add(0, R.string.ic_menu_mylocation, Menu.NONE, R.string.ic_menu_mylocation).setIcon(R.drawable.ic_menu_mylocation); return true; } // onCreateOptionsMenu public boolean onMenuItemSelected(final int featureId, final MenuItem item) { - if(featureId != R.string.ic_menu_mylocation) + if(item.getItemId() != R.string.ic_menu_mylocation) return false; enableLocation(!isMyLocationEnabled()); return true; } // onMenuItemSelected ////////////////////////////////////////////// @Override public boolean onSingleTap(final MotionEvent event) { return tapLocation(event); } // onSingleTapUp @Override public boolean onDoubleTap(final MotionEvent event) { return locationButton_.hit(event); } // onDoubleTap private boolean tapLocation(final MotionEvent event) { if(!locationButton_.hit(event)) return false; enableAndFollowLocation(!isMyLocationEnabled()); return true; } // tapLocation } // LocationOverlay
true
false
null
null
diff --git a/tests/org/biojava/bio/ontology/OntologyTest.java b/tests/org/biojava/bio/ontology/OntologyTest.java index 6aa507587..fb9ce5bd7 100644 --- a/tests/org/biojava/bio/ontology/OntologyTest.java +++ b/tests/org/biojava/bio/ontology/OntologyTest.java @@ -1,131 +1,131 @@ /* * BioJava development code * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. If you do not have a copy, * see: * * http://www.gnu.org/copyleft/lesser.html * * Copyright for this code is held jointly by the individual * authors. These should be listed in @author doc comments. * * For more information on the BioJava project and its aims, * or to join the biojava-l mailing list, visit the home page * at: * * http://www.biojava.org/ * */ package org.biojava.bio.ontology; import java.util.*; import junit.framework.TestCase; /** * Tests for Ontology. * * @author Thomas Down * @since 1.4 */ public class OntologyTest extends TestCase { protected Ontology onto; protected Term widget; protected Term sprocket; protected Term machine; protected Term blueWidget; protected Term isa; protected Term partof; protected Term dummy; public OntologyTest(String name) { super(name); } protected void setUp() throws Exception { Ontology relations = new Ontology.Impl("relations", "Some standard relations"); Term master_isa = relations.createTerm("is-a", ""); Term master_partof = relations.createTerm("part-of", ""); onto = new Ontology.Impl("test", "Test ontology"); machine = onto.createTerm("machine", "A fancy machine"); sprocket = onto.createTerm("sprocket", ""); widget = onto.createTerm("widget", ""); blueWidget = onto.createTerm("blueWidget", ""); isa = onto.importTerm(master_isa); partof = onto.importTerm(master_partof); dummy = new Ontology.Impl("", "").createTerm("dummy", "Silly dummy term"); onto.createTriple(sprocket, machine, partof); onto.createTriple(widget, machine, partof); onto.createTriple(blueWidget, widget, isa); } public void testGetBySubject() { assertEquals(onto.getTriples(widget, null, null).size(), 1); assertEquals(onto.getTriples(machine, null, null).size(), 0); assertEquals(onto.getTriples(dummy, null, null).size(), 0); } public void testGetByObject() { assertEquals(onto.getTriples(null, machine, null).size(), 2); assertEquals(onto.getTriples(null, widget, null).size(), 1); assertEquals(onto.getTriples(null, dummy, null).size(), 0); } public void testGetByRelation() { assertEquals(onto.getTriples(null, null, partof).size(), 2); assertEquals(onto.getTriples(null, null, isa).size(), 1); assertEquals(onto.getTriples(null, null, dummy).size(), 0); } public void testGetByMulti() { assertEquals(onto.getTriples(sprocket, machine, null).size(), 1); assertEquals(onto.getTriples(sprocket, machine, partof).size(), 1); assertEquals(onto.getTriples(sprocket, machine, isa).size(), 0); } public void testOntoToos_Core() { Ontology onto = OntoTools.getCoreOntology(); onto.getTriples(null, null, null); } public void testCoreISA() throws OntologyException { Ontology onto = OntoTools.getCoreOntology(); doIsaTest(OntoTools.IS_A, OntoTools.IS_A, true); doIsaTest(OntoTools.HAS_A, OntoTools.IS_A, false); doIsaTest(OntoTools.RELATION, OntoTools.ANY, true); doIsaTest(OntoTools.REFLEXIVE, OntoTools.RELATION, true); doIsaTest(OntoTools.EQUIVALENCE, OntoTools.REFLEXIVE, true); doIsaTest(OntoTools.EQUIVALENCE, OntoTools.RELATION, true); doIsaTest(OntoTools.EQUIVALENCE, OntoTools.ANY, true); - doIsaTest(OntoTools.EQUIVALENCE, OntoTools.PARTIAL_ORDER, true); + doIsaTest(OntoTools.EQUIVALENCE, OntoTools.PARTIAL_ORDER, false); } private void doIsaTest(Term t1, Term t2, boolean yesno) throws OntologyException { boolean res = OntoTools.isa(t1, t2); assertEquals( "Terms: " + t1 + " , " + t2, yesno, res ); } public void testSimpleISA() throws OntologyException{ Ontology onto = OntoTools.getDefaultFactory().createOntology( "is-a tester", "Lets just get this is-a relationship stuff tested across ontologies" ); } } diff --git a/tests/org/biojava/ontology/OntologyTest.java b/tests/org/biojava/ontology/OntologyTest.java index 6aa507587..fb9ce5bd7 100644 --- a/tests/org/biojava/ontology/OntologyTest.java +++ b/tests/org/biojava/ontology/OntologyTest.java @@ -1,131 +1,131 @@ /* * BioJava development code * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. If you do not have a copy, * see: * * http://www.gnu.org/copyleft/lesser.html * * Copyright for this code is held jointly by the individual * authors. These should be listed in @author doc comments. * * For more information on the BioJava project and its aims, * or to join the biojava-l mailing list, visit the home page * at: * * http://www.biojava.org/ * */ package org.biojava.bio.ontology; import java.util.*; import junit.framework.TestCase; /** * Tests for Ontology. * * @author Thomas Down * @since 1.4 */ public class OntologyTest extends TestCase { protected Ontology onto; protected Term widget; protected Term sprocket; protected Term machine; protected Term blueWidget; protected Term isa; protected Term partof; protected Term dummy; public OntologyTest(String name) { super(name); } protected void setUp() throws Exception { Ontology relations = new Ontology.Impl("relations", "Some standard relations"); Term master_isa = relations.createTerm("is-a", ""); Term master_partof = relations.createTerm("part-of", ""); onto = new Ontology.Impl("test", "Test ontology"); machine = onto.createTerm("machine", "A fancy machine"); sprocket = onto.createTerm("sprocket", ""); widget = onto.createTerm("widget", ""); blueWidget = onto.createTerm("blueWidget", ""); isa = onto.importTerm(master_isa); partof = onto.importTerm(master_partof); dummy = new Ontology.Impl("", "").createTerm("dummy", "Silly dummy term"); onto.createTriple(sprocket, machine, partof); onto.createTriple(widget, machine, partof); onto.createTriple(blueWidget, widget, isa); } public void testGetBySubject() { assertEquals(onto.getTriples(widget, null, null).size(), 1); assertEquals(onto.getTriples(machine, null, null).size(), 0); assertEquals(onto.getTriples(dummy, null, null).size(), 0); } public void testGetByObject() { assertEquals(onto.getTriples(null, machine, null).size(), 2); assertEquals(onto.getTriples(null, widget, null).size(), 1); assertEquals(onto.getTriples(null, dummy, null).size(), 0); } public void testGetByRelation() { assertEquals(onto.getTriples(null, null, partof).size(), 2); assertEquals(onto.getTriples(null, null, isa).size(), 1); assertEquals(onto.getTriples(null, null, dummy).size(), 0); } public void testGetByMulti() { assertEquals(onto.getTriples(sprocket, machine, null).size(), 1); assertEquals(onto.getTriples(sprocket, machine, partof).size(), 1); assertEquals(onto.getTriples(sprocket, machine, isa).size(), 0); } public void testOntoToos_Core() { Ontology onto = OntoTools.getCoreOntology(); onto.getTriples(null, null, null); } public void testCoreISA() throws OntologyException { Ontology onto = OntoTools.getCoreOntology(); doIsaTest(OntoTools.IS_A, OntoTools.IS_A, true); doIsaTest(OntoTools.HAS_A, OntoTools.IS_A, false); doIsaTest(OntoTools.RELATION, OntoTools.ANY, true); doIsaTest(OntoTools.REFLEXIVE, OntoTools.RELATION, true); doIsaTest(OntoTools.EQUIVALENCE, OntoTools.REFLEXIVE, true); doIsaTest(OntoTools.EQUIVALENCE, OntoTools.RELATION, true); doIsaTest(OntoTools.EQUIVALENCE, OntoTools.ANY, true); - doIsaTest(OntoTools.EQUIVALENCE, OntoTools.PARTIAL_ORDER, true); + doIsaTest(OntoTools.EQUIVALENCE, OntoTools.PARTIAL_ORDER, false); } private void doIsaTest(Term t1, Term t2, boolean yesno) throws OntologyException { boolean res = OntoTools.isa(t1, t2); assertEquals( "Terms: " + t1 + " , " + t2, yesno, res ); } public void testSimpleISA() throws OntologyException{ Ontology onto = OntoTools.getDefaultFactory().createOntology( "is-a tester", "Lets just get this is-a relationship stuff tested across ontologies" ); } }
false
false
null
null
diff --git a/src/com/android/launcher3/WallpaperPickerActivity.java b/src/com/android/launcher3/WallpaperPickerActivity.java index 6c093471a..ec0106fe3 100644 --- a/src/com/android/launcher3/WallpaperPickerActivity.java +++ b/src/com/android/launcher3/WallpaperPickerActivity.java @@ -1,417 +1,419 @@ /* * Copyright (C) 2013 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.launcher3; import android.app.ActionBar; import android.app.Activity; import android.content.ComponentName; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.content.res.Resources; import android.graphics.Point; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.drawable.Drawable; import android.graphics.drawable.LevelListDrawable; import android.net.Uri; import android.util.Log; import android.util.Pair; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.SubMenu; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.animation.DecelerateInterpolator; import android.widget.BaseAdapter; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListAdapter; import android.widget.SpinnerAdapter; import android.widget.TextView; import com.android.photos.BitmapRegionTileSource; import java.util.ArrayList; import java.util.List; public class WallpaperPickerActivity extends WallpaperCropActivity { private static final String TAG = "Launcher.WallpaperPickerActivity"; private static final int IMAGE_PICK = 5; private static final int PICK_WALLPAPER_THIRD_PARTY_ACTIVITY = 6; private ArrayList<Drawable> mThumbs; private ArrayList<Integer> mImages; private Resources mWallpaperResources; private View mSelectedThumb; private boolean mIgnoreNextTap; private OnClickListener mThumbnailOnClickListener; private static class ThumbnailMetaData { public boolean mLaunchesGallery; public Uri mGalleryImageUri; public int mWallpaperResId; } // called by onCreate; this is subclassed to overwrite WallpaperCropActivity protected void init() { setContentView(R.layout.wallpaper_picker); mCropView = (CropView) findViewById(R.id.cropView); final View wallpaperStrip = findViewById(R.id.wallpaper_strip); mCropView.setTouchCallback(new CropView.TouchCallback() { LauncherViewPropertyAnimator mAnim; public void onTouchDown() { if (mAnim != null) { mAnim.cancel(); } if (wallpaperStrip.getTranslationY() == 0) { mIgnoreNextTap = true; } mAnim = new LauncherViewPropertyAnimator(wallpaperStrip); mAnim.translationY(wallpaperStrip.getHeight()) .setInterpolator(new DecelerateInterpolator(0.75f)); mAnim.start(); } public void onTap() { boolean ignoreTap = mIgnoreNextTap; mIgnoreNextTap = false; if (!ignoreTap) { if (mAnim != null) { mAnim.cancel(); } mAnim = new LauncherViewPropertyAnimator(wallpaperStrip); mAnim.translationY(0).setInterpolator(new DecelerateInterpolator(0.75f)); mAnim.start(); } } }); mThumbnailOnClickListener = new OnClickListener() { public void onClick(View v) { if (mSelectedThumb != null) { mSelectedThumb.setSelected(false); } ThumbnailMetaData meta = (ThumbnailMetaData) v.getTag(); if (!meta.mLaunchesGallery) { mSelectedThumb = v; v.setSelected(true); } if (meta.mLaunchesGallery) { Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.setType("image/*"); Utilities.startActivityForResultSafely( WallpaperPickerActivity.this, intent, IMAGE_PICK); } else if (meta.mGalleryImageUri != null) { mCropView.setTileSource(new BitmapRegionTileSource(WallpaperPickerActivity.this, meta.mGalleryImageUri, 1024, 0), null); mCropView.setTouchEnabled(true); } else { BitmapRegionTileSource source = new BitmapRegionTileSource(mWallpaperResources, WallpaperPickerActivity.this, meta.mWallpaperResId, 1024, 0); mCropView.setTileSource(source, null); Point wallpaperSize = WallpaperCropActivity.getDefaultWallpaperSize( getResources(), getWindowManager()); RectF crop = WallpaperCropActivity.getMaxCropRect( source.getImageWidth(), source.getImageHeight(), wallpaperSize.x, wallpaperSize.y); mCropView.setScale(wallpaperSize.x / crop.width()); mCropView.setTouchEnabled(false); } } }; // Populate the built-in wallpapers findWallpapers(); LinearLayout wallpapers = (LinearLayout) findViewById(R.id.wallpaper_list); ImageAdapter ia = new ImageAdapter(this); for (int i = 0; i < ia.getCount(); i++) { FrameLayout thumbnail = (FrameLayout) ia.getView(i, null, wallpapers); wallpapers.addView(thumbnail, i); ThumbnailMetaData meta = new ThumbnailMetaData(); meta.mWallpaperResId = mImages.get(i); thumbnail.setTag(meta); thumbnail.setOnClickListener(mThumbnailOnClickListener); if (i == 0) { mThumbnailOnClickListener.onClick(thumbnail); } } // Add a tile for the Gallery FrameLayout galleryThumbnail = (FrameLayout) getLayoutInflater(). inflate(R.layout.wallpaper_picker_gallery_item, wallpapers, false); setWallpaperItemPaddingToZero(galleryThumbnail); TextView galleryLabel = (TextView) galleryThumbnail.findViewById(R.id.wallpaper_item_label); galleryLabel.setText(R.string.gallery); wallpapers.addView(galleryThumbnail, 0); ThumbnailMetaData meta = new ThumbnailMetaData(); meta.mLaunchesGallery = true; galleryThumbnail.setTag(meta); galleryThumbnail.setOnClickListener(mThumbnailOnClickListener); // Action bar // Show the custom action bar view final ActionBar actionBar = getActionBar(); actionBar.setCustomView(R.layout.actionbar_set_wallpaper); actionBar.getCustomView().setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { ThumbnailMetaData meta = (ThumbnailMetaData) mSelectedThumb.getTag(); if (meta.mLaunchesGallery) { // shouldn't be selected, but do nothing } else if (meta.mGalleryImageUri != null) { boolean finishActivityWhenDone = true; cropImageAndSetWallpaper(meta.mGalleryImageUri, finishActivityWhenDone); } else if (meta.mWallpaperResId != 0) { boolean finishActivityWhenDone = true; cropImageAndSetWallpaper(mWallpaperResources, meta.mWallpaperResId, finishActivityWhenDone); } } }); } protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == IMAGE_PICK && resultCode == RESULT_OK) { Uri uri = data.getData(); // Add a tile for the image picked from Gallery LinearLayout wallpapers = (LinearLayout) findViewById(R.id.wallpaper_list); FrameLayout pickedImageThumbnail = (FrameLayout) getLayoutInflater(). inflate(R.layout.wallpaper_picker_item, wallpapers, false); setWallpaperItemPaddingToZero(pickedImageThumbnail); // Load the thumbnail ImageView image = (ImageView) pickedImageThumbnail.findViewById(R.id.wallpaper_image); Resources res = getResources(); int width = res.getDimensionPixelSize(R.dimen.wallpaperThumbnailWidth); int height = res.getDimensionPixelSize(R.dimen.wallpaperThumbnailHeight); BitmapCropTask cropTask = new BitmapCropTask(uri, null, width, height, false, true, null); Point bounds = cropTask.getImageBounds(); RectF cropRect = WallpaperCropActivity.getMaxCropRect( bounds.x, bounds.y, width, height); cropTask.setCropBounds(cropRect); if (cropTask.cropBitmap()) { image.setImageBitmap(cropTask.getCroppedBitmap()); Drawable thumbDrawable = image.getDrawable(); thumbDrawable.setDither(true); } else { Log.e(TAG, "Error loading thumbnail for uri=" + uri); } wallpapers.addView(pickedImageThumbnail, 0); ThumbnailMetaData meta = new ThumbnailMetaData(); meta.mGalleryImageUri = uri; pickedImageThumbnail.setTag(meta); pickedImageThumbnail.setOnClickListener(mThumbnailOnClickListener); mThumbnailOnClickListener.onClick(pickedImageThumbnail); } else if (requestCode == PICK_WALLPAPER_THIRD_PARTY_ACTIVITY) { // No result code is returned; just return setResult(RESULT_OK); finish(); } } private static void setWallpaperItemPaddingToZero(FrameLayout frameLayout) { frameLayout.setPadding(0, 0, 0, 0); frameLayout.setForeground(new ZeroPaddingDrawable(frameLayout.getForeground())); } public boolean onMenuItemSelected(int featureId, MenuItem item) { if (item.getIntent() == null) { return super.onMenuItemSelected(featureId, item); } else { Utilities.startActivityForResultSafely( this, item.getIntent(), PICK_WALLPAPER_THIRD_PARTY_ACTIVITY); return true; } } @Override public boolean onCreateOptionsMenu(Menu menu) { final Intent pickWallpaperIntent = new Intent(Intent.ACTION_SET_WALLPAPER); final PackageManager pm = getPackageManager(); final List<ResolveInfo> apps = pm.queryIntentActivities(pickWallpaperIntent, 0); SubMenu sub = menu.addSubMenu("Other\u2026"); // TODO: what's the better way to do this? sub.getItem().setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS); // Get list of image picker intents Intent pickImageIntent = new Intent(Intent.ACTION_GET_CONTENT); pickImageIntent.setType("image/*"); final List<ResolveInfo> imagePickerActivities = pm.queryIntentActivities(pickImageIntent, 0); final ComponentName[] imageActivities = new ComponentName[imagePickerActivities.size()]; for (int i = 0; i < imagePickerActivities.size(); i++) { ActivityInfo activityInfo = imagePickerActivities.get(i).activityInfo; imageActivities[i] = new ComponentName(activityInfo.packageName, activityInfo.name); } outerLoop: for (ResolveInfo info : apps) { final ComponentName itemComponentName = new ComponentName(info.activityInfo.packageName, info.activityInfo.name); final String itemPackageName = itemComponentName.getPackageName(); // Exclude anything from our own package, and the old Launcher if (itemPackageName.equals(getPackageName()) || itemPackageName.equals("com.android.launcher")) { continue; } // Exclude any package that already responds to the image picker intent for (ResolveInfo imagePickerActivityInfo : imagePickerActivities) { if (itemPackageName.equals( imagePickerActivityInfo.activityInfo.packageName)) { continue outerLoop; } } MenuItem mi = sub.add(info.loadLabel(pm)); Intent launchIntent = new Intent(Intent.ACTION_SET_WALLPAPER); launchIntent.setComponent(itemComponentName); mi.setIntent(launchIntent); Drawable icon = info.loadIcon(pm); if (icon != null) { mi.setIcon(icon); } } return super.onCreateOptionsMenu(menu); } private void findWallpapers() { mThumbs = new ArrayList<Drawable>(24); mImages = new ArrayList<Integer>(24); Pair<ApplicationInfo, Integer> r = getWallpaperArrayResourceId(); if (r != null) { try { mWallpaperResources = getPackageManager().getResourcesForApplication(r.first); addWallpapers(mWallpaperResources, r.first.packageName, r.second); } catch (PackageManager.NameNotFoundException e) { } } } public Pair<ApplicationInfo, Integer> getWallpaperArrayResourceId() { // Context.getPackageName() may return the "original" package name, // com.android.launcher3; Resources needs the real package name, // com.android.launcher3. So we ask Resources for what it thinks the // package name should be. final String packageName = getResources().getResourcePackageName(R.array.wallpapers); try { ApplicationInfo info = getPackageManager().getApplicationInfo(packageName, 0); return new Pair<ApplicationInfo, Integer>(info, R.array.wallpapers); } catch (PackageManager.NameNotFoundException e) { return null; } } private void addWallpapers(Resources resources, String packageName, int listResId) { final String[] extras = resources.getStringArray(listResId); for (String extra : extras) { int res = resources.getIdentifier(extra, "drawable", packageName); if (res != 0) { final int thumbRes = resources.getIdentifier(extra + "_small", "drawable", packageName); if (thumbRes != 0) { mThumbs.add(resources.getDrawable(thumbRes)); mImages.add(res); // Log.d(TAG, "add: [" + packageName + "]: " + extra + " (" + res + ")"); } + } else { + Log.e(TAG, "Couldn't find wallpaper " + extra); } } } static class ZeroPaddingDrawable extends LevelListDrawable { public ZeroPaddingDrawable(Drawable d) { super(); addLevel(0, 0, d); setLevel(0); } @Override public boolean getPadding(Rect padding) { padding.set(0, 0, 0, 0); return true; } } private class ImageAdapter extends BaseAdapter implements ListAdapter, SpinnerAdapter { private LayoutInflater mLayoutInflater; ImageAdapter(Activity activity) { mLayoutInflater = activity.getLayoutInflater(); } public int getCount() { return mThumbs.size(); } public Object getItem(int position) { return position; } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { View view; if (convertView == null) { view = mLayoutInflater.inflate(R.layout.wallpaper_picker_item, parent, false); } else { view = convertView; } setWallpaperItemPaddingToZero((FrameLayout) view); ImageView image = (ImageView) view.findViewById(R.id.wallpaper_image); Drawable thumbDrawable = mThumbs.get(position); if (thumbDrawable != null) { image.setImageDrawable(thumbDrawable); thumbDrawable.setDither(true); } else { Log.e(TAG, "Error decoding thumbnail for wallpaper #" + position); } return view; } } }
true
false
null
null
diff --git a/src/java/net/percederberg/mibble/Mib.java b/src/java/net/percederberg/mibble/Mib.java index d0071ea..ff3e922 100644 --- a/src/java/net/percederberg/mibble/Mib.java +++ b/src/java/net/percederberg/mibble/Mib.java @@ -1,638 +1,638 @@ /* * Mib.java * * This work is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 2 of the License, * or (at your option) any later version. * * This work is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA * * Copyright (c) 2004-2006 Per Cederberg. All rights reserved. */ package net.percederberg.mibble; import java.io.File; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import net.percederberg.mibble.value.NumberValue; import net.percederberg.mibble.value.ObjectIdentifierValue; /** * An SNMP MIB module. This class contains all the information * from a single MIB module, including all defined types and values. * Note that a single MIB file may contain several such modules, * although that is not very common. MIB files are loaded through a * {@link MibLoader MIB loader}. * * @author Per Cederberg, <per at percederberg dot net> * @version 2.7 * @since 2.0 * * @see <a href="http://www.ietf.org/rfc/rfc3411.txt">RFC 3411 - An * Architecture for Describing SNMP Management Frameworks</a> */ public class Mib implements MibContext { /** * The MIB file. */ private File file; /** * The loader used for this MIB. */ private MibLoader loader; /** * The loader log used for loading this MIB. */ private MibLoaderLog log; /** * The explicitly loaded flag. This flag is set when a MIB is * loaded by a direct call to the MibLoader, in contrast to when * it is loaded as the result of an import. */ private boolean loaded = false; /** * The MIB name. */ private String name = null; /** * The SMI version. */ private int smiVersion = 1; /** * The MIB file header comment. */ private String headerComment = null; /** * The MIB file footer comment. */ private String footerComment = null; /** * The references to imported MIB files. */ private ArrayList imports = new ArrayList(); /** * The MIB symbol list. This list contains the MIB symbol objects * in the order they were added (i.e. present in the file). */ private ArrayList symbolList = new ArrayList(); /** * The MIB symbol name map. This maps the symbol names to their * respective MIB symbol objects. */ private HashMap symbolNameMap = new HashMap(); /** * The MIB symbol value map. This maps the symbol values to their * respective MIB symbol objects. Only the value symbols with * either a number or an object identifier value is present in * this map. */ private HashMap symbolValueMap = new HashMap(); /** * Creates a new MIB module. This will NOT read the actual MIB * file, but only creates an empty container. The symbols are * then added during the first analysis pass (of two), leaving * symbols in the MIB possibly containing unresolved references. * A separate call to initialize() must be made once all * referenced MIB modules have also been loaded. * * @param file the MIB file name * @param loader the MIB loader to use for imports * @param log the MIB log to use for errors * * @see #initialize() */ Mib(File file, MibLoader loader, MibLoaderLog log) { this.file = file; this.loader = loader; this.log = log; } /** * Initializes the MIB file. This will resolve all imported MIB * file references. Note that this method shouldn't be called * until all referenced MIB files (and their respective * references) have been loaded. * * @throws MibLoaderException if the MIB file couldn't be * analyzed correctly * * @see #validate() */ void initialize() throws MibLoaderException { MibImport imp; int errors = log.errorCount(); // Resolve imported MIB files for (int i = 0; i < imports.size(); i++) { imp = (MibImport) imports.get(i); try { imp.initialize(log); } catch (MibException e) { log.addError(e.getLocation(), e.getMessage()); } } // Check for errors if (errors != log.errorCount()) { throw new MibLoaderException(log); } } /** * Validates the MIB file. This will resolve all type and value * references in the MIB symbols, while also validating them for * consistency. Note that this method shouldn't be called until * all referenced MIB files (and their respective references) * have been initialized. * * @throws MibLoaderException if the MIB file couldn't be * analyzed correctly * * @see #initialize() */ void validate() throws MibLoaderException { MibSymbol symbol; MibValueSymbol value; int errors = log.errorCount(); // Validate all symbols for (int i = 0; i < symbolList.size(); i++) { symbol = (MibSymbol) symbolList.get(i); try { symbol.initialize(log); } catch (MibException e) { log.addError(e.getLocation(), e.getMessage()); } if (symbol instanceof MibValueSymbol) { value = (MibValueSymbol) symbol; if (value.getValue() instanceof NumberValue || value.getValue() instanceof ObjectIdentifierValue) { symbolValueMap.put(value.getValue().toString(), symbol); } } } // Check for errors if (errors != log.errorCount()) { throw new MibLoaderException(log); } } /** * Clears and prepares this MIB for garbage collection. This method * will recursively clear all associated symbols, making sure that * no data structures references symbols from this MIB. Obviously, * this method shouldn't be called unless all dependant MIBs have * been cleared first. */ void clear() { loader = null; log = null; if (imports != null) { imports.clear(); } imports = null; if (symbolList != null) { for (int i = 0; i < symbolList.size(); i++) { ((MibSymbol) symbolList.get(i)).clear(); } symbolList.clear(); } symbolList = null; if (symbolNameMap != null) { symbolNameMap.clear(); } symbolNameMap = null; if (symbolValueMap != null) { symbolValueMap.clear(); } symbolValueMap = null; } /** * Compares this MIB to another object. This method will return * true if the object is a string containing the MIB name, a file * containing the MIB file, or a Mib having the same name. * * @param obj the object to compare with * * @return true if the objects are equal, or * false otherwise */ public boolean equals(Object obj) { if (obj instanceof String) { return name.equals(obj); } else if (file != null && obj instanceof File) { return file.equals(obj); } else if (obj instanceof Mib) { return obj.equals(name); } else { return false; } } /** * Returns the hash code value for the object. This method is * reimplemented to fulfil the contract of returning the same * hash code for objects that are considered equal. * * @return the hash code value for the object * * @since 2.6 */ public int hashCode() { return name.hashCode(); } /** * Checks if this MIB module has been explicitly loaded. A MIB * module is considered explicitly loaded if the file or resource * containing the MIB definition was loaded by a direct call to * the MIB loader. Implictly loaded MIB modules are loaded as a * result of import statements in explicitly loaded MIBs. * * @return true if this MIB module was explicitly loaded, or * false otherwise * * @since 2.7 */ public boolean isLoaded() { return loaded; } /** * Sets the the explicitly loaded flag. * * @param loaded the new flag value */ void setLoaded(boolean loaded) { this.loaded = loaded; } /** * Returns the MIB name. This is sometimes also referred to as * the MIB module name. * * @return the MIB name */ public String getName() { return name; } /** * Changes the MIB name. This method should only be called by * the MIB analysis classes. * * @param name the MIB name */ void setName(String name) { this.name = name; if (file == null) { file = new File(name); } } /** * Returns the MIB file. * * @return the MIB file */ public File getFile() { return file; } /** * Returns the MIB loader used when loading this MIB. * * @return the loader used */ public MibLoader getLoader() { return loader; } /** * Returns the loader log used when loading this MIB. * * @return the loader log used */ public MibLoaderLog getLog() { return log; } /** * Returns the SMI version used for defining this MIB. This * number can be either 1 (for SMIv1) or 2 (for SMIv2). It is set * based on which macros are used in the MIB file. * * @return the SMI version used for defining the MIB * * @since 2.6 */ public int getSmiVersion() { return smiVersion; } /** * Sets the SMI version used for defining this MIB. This method * should only be called by the MIB analysis classes. * * @param version the new SMI version * * @since 2.6 */ void setSmiVersion(int version) { this.smiVersion = version; } /** * Returns the MIB file header comment. * * @return the MIB file header comment, or * null if no comment was present * * @since 2.6 */ public String getHeaderComment() { return headerComment; } /** * Sets the MIB file header comment. * * @param comment the MIB header comment * * @since 2.6 */ void setHeaderComment(String comment) { this.headerComment = comment; } /** * Returns the MIB file footer comment. * * @return the MIB file footer comment, or * null if no comment was present * * @since 2.6 */ public String getFooterComment() { return footerComment; } /** * Sets the MIB file footer comment. * * @param comment the MIB footer comment * * @since 2.6 */ void setFooterComment(String comment) { this.footerComment = comment; } /** * Returns all MIB import references. * * @return a collection of all imports * * @see MibImport * * @since 2.6 */ public Collection getAllImports() { ArrayList res = new ArrayList(); MibImport imp; for (int i = 0; i < imports.size(); i++) { imp = (MibImport) imports.get(i); if (imp.hasSymbols()) { res.add(imp); } } return res; } /** * Returns a MIB import reference. * * @param name the imported MIB name * * @return the MIB import reference, or * null if not found */ MibImport getImport(String name) { MibImport imp; for (int i = 0; i < imports.size(); i++) { imp = (MibImport) imports.get(i); if (imp.getName().equals(name)) { return imp; } } return null; } /** * Adds a reference to an imported MIB file. * * @param ref the reference to add */ void addImport(MibImport ref) { imports.add(ref); } /** * Finds all MIB:s that are dependant on this one. The search * will iterate through all loaded MIB:s and return those that * import this one. * * @return the array of MIB:s importing this one * * @see MibLoader * * @since 2.7 */ public Mib[] getImportingMibs() { ArrayList res = new ArrayList(); Mib[] mibs = loader.getAllMibs(); for (int i = 0; i < mibs.length; i++) { if (mibs[i] != this && mibs[i].getImport(name) != null) { res.add(mibs[i]); } } mibs = new Mib[res.size()]; res.toArray(mibs); return mibs; } /** * Returns all symbols in this MIB. * * @return a collection of the MIB symbols * * @see MibSymbol */ public Collection getAllSymbols() { return symbolList; } /** * Returns a symbol from this MIB. * * @param name the symbol name * * @return the MIB symbol, or null if not found */ public MibSymbol getSymbol(String name) { return (MibSymbol) symbolNameMap.get(name); } /** * Returns a value symbol from this MIB. * * @param value the symbol value * * @return the MIB value symbol, or null if not found */ public MibValueSymbol getSymbolByValue(String value) { return (MibValueSymbol) symbolValueMap.get(value); } /** * Returns a value symbol from this MIB. * * @param value the symbol value * * @return the MIB value symbol, or null if not found */ public MibValueSymbol getSymbolByValue(MibValue value) { return (MibValueSymbol) symbolValueMap.get(value.toString()); } /** * Returns a value symbol from this MIB. The search is performed * by using the strictly numerical OID value specified. Differing * from the getSymbolByValue() methods, this method may return a * symbol with only a partial OID match. If an exact match for * the OID is present in the MIB, this method will always return * the same result as getSymbolByValue(). Otherwise, the symbol * with the longest matching OID will be returned, making it * possible to identify a MIB symbol from an OID containing table * row indices or similar. * * @param oid the numeric OID value * * @return the MIB value symbol, or null if not found * * @since 2.5 */ public MibValueSymbol getSymbolByOid(String oid) { MibValueSymbol sym; int pos; do { sym = getSymbolByValue(oid); if (sym != null) { return sym; } pos = oid.lastIndexOf("."); if (pos > 0) { oid = oid.substring(0, pos); } } while (pos > 0); return null; } /** * Returns the root MIB value symbol. This value symbol is * normally the module identifier (in SMIv2), but may also be * just the base object identifier in the MIB. * * @return the root MIB value symbol * * @since 2.6 */ public MibValueSymbol getRootSymbol() { MibValueSymbol root = null; MibValueSymbol parent; for (int i = 0; i < symbolList.size(); i++) { if (symbolList.get(i) instanceof MibValueSymbol) { root = (MibValueSymbol) symbolList.get(i); break; } } while (root != null && (parent = root.getParent()) != null) { - if (root.getMib().equals(parent.getMib())) { + if (!root.getMib().equals(parent.getMib())) { break; } - root = root.getParent(); + root = parent; } return root; } /** * Adds a symbol to this MIB. * * @param symbol the symbol to add */ void addSymbol(MibSymbol symbol) { symbolList.add(symbol); symbolNameMap.put(symbol.getName(), symbol); } /** * Searches for a named MIB symbol. This method is required to * implement the MibContext interface but returns the same results * as getSymbol(String).<p> * * <strong>NOTE:</strong> This is an internal method that should * only be called by the MIB loader. * * @param name the symbol name * @param expanded the expanded scope flag * * @return the MIB symbol, or null if not found * * @since 2.4 */ public MibSymbol findSymbol(String name, boolean expanded) { return getSymbol(name); } /** * Returns a string representation of this object. * * @return a string representation of this object */ public String toString() { return getName(); } }
false
false
null
null
diff --git a/lttng/org.eclipse.linuxtools.lttng.core/src/org/eclipse/linuxtools/internal/lttng/core/trace/LTTngTrace.java b/lttng/org.eclipse.linuxtools.lttng.core/src/org/eclipse/linuxtools/internal/lttng/core/trace/LTTngTrace.java index a856bea25..983cc27e5 100644 --- a/lttng/org.eclipse.linuxtools.lttng.core/src/org/eclipse/linuxtools/internal/lttng/core/trace/LTTngTrace.java +++ b/lttng/org.eclipse.linuxtools.lttng.core/src/org/eclipse/linuxtools/internal/lttng/core/trace/LTTngTrace.java @@ -1,1093 +1,1096 @@ /******************************************************************************* * Copyright (c) 2009, 2011 Ericsson, MontaVista Software * * All rights reserved. This program and the accompanying materials are * made available under the terms of the Eclipse Public License v1.0 which * accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * William Bourque (wbourque@gmail.com) - Initial API and implementation * Yufen Kuo (ykuo@mvista.com) - add support to allow user specify trace library path *******************************************************************************/ package org.eclipse.linuxtools.internal.lttng.core.trace; import java.util.HashMap; import java.util.Iterator; import java.util.Vector; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.linuxtools.internal.lttng.core.TraceHelper; import org.eclipse.linuxtools.internal.lttng.core.event.LttngEvent; import org.eclipse.linuxtools.internal.lttng.core.event.LttngEventContent; import org.eclipse.linuxtools.internal.lttng.core.event.LttngEventType; import org.eclipse.linuxtools.internal.lttng.core.event.LttngLocation; import org.eclipse.linuxtools.internal.lttng.core.event.LttngTimestamp; import org.eclipse.linuxtools.internal.lttng.core.exceptions.LttngException; import org.eclipse.linuxtools.internal.lttng.core.tracecontrol.utility.LiveTraceManager; import org.eclipse.linuxtools.internal.lttng.jni.common.JniTime; import org.eclipse.linuxtools.lttng.jni.JniEvent; import org.eclipse.linuxtools.lttng.jni.JniMarker; import org.eclipse.linuxtools.lttng.jni.JniTrace; import org.eclipse.linuxtools.lttng.jni.JniTracefile; import org.eclipse.linuxtools.lttng.jni.factory.JniTraceFactory; import org.eclipse.linuxtools.tmf.core.event.ITmfTimestamp; import org.eclipse.linuxtools.tmf.core.event.TmfEvent; import org.eclipse.linuxtools.tmf.core.event.TmfTimeRange; import org.eclipse.linuxtools.tmf.core.event.TmfTimestamp; import org.eclipse.linuxtools.tmf.core.exceptions.TmfTraceException; import org.eclipse.linuxtools.tmf.core.request.ITmfDataRequest.ExecutionType; import org.eclipse.linuxtools.tmf.core.request.TmfEventRequest; import org.eclipse.linuxtools.tmf.core.signal.TmfTraceUpdatedSignal; import org.eclipse.linuxtools.tmf.core.trace.ITmfContext; import org.eclipse.linuxtools.tmf.core.trace.ITmfEventParser; import org.eclipse.linuxtools.tmf.core.trace.ITmfLocation; +import org.eclipse.linuxtools.tmf.core.trace.TmfCheckpointIndexer; import org.eclipse.linuxtools.tmf.core.trace.TmfContext; import org.eclipse.linuxtools.tmf.core.trace.TmfExperiment; import org.eclipse.linuxtools.tmf.core.trace.TmfTrace; class LTTngTraceException extends LttngException { static final long serialVersionUID = -1636648737081868146L; public LTTngTraceException(final String errMsg) { super(errMsg); } } /** * <b><u>LTTngTrace</u></b> * <p> * * LTTng trace implementation. It accesses the C trace handling library * (seeking, reading and parsing) through the JNI component. */ public class LTTngTrace extends TmfTrace<LttngEvent> implements ITmfEventParser<LttngEvent> { public final static boolean PRINT_DEBUG = false; public final static boolean UNIQUE_EVENT = true; private final static boolean SHOW_LTT_DEBUG_DEFAULT = false; private final static boolean IS_PARSING_NEEDED_DEFAULT = !UNIQUE_EVENT; private final static int CHECKPOINT_PAGE_SIZE = 50000; private final static long LTTNG_STREAMING_INTERVAL = 2000; // in ms // Reference to our JNI trace private JniTrace currentJniTrace; LttngTimestamp eventTimestamp; String eventSource; LttngEventContent eventContent; String eventReference; // The actual event LttngEvent currentLttngEvent; // The current location LttngLocation previousLocation; LttngEventType eventType; // Hashmap of the possible types of events (Tracefile/CPU/Marker in the JNI) HashMap<Integer, LttngEventType> traceTypes; // This vector will be used to quickly find a marker name from a position Vector<Integer> traceTypeNames; private String traceLibPath; public LTTngTrace() { } @Override public boolean validate(final IProject project, final String path) { if (fileExists(path)) { final String traceLibPath = TraceHelper.getTraceLibDirFromProject(project); try { final LTTngTraceVersion version = new LTTngTraceVersion(path, traceLibPath); return version.isValidLttngTrace(); } catch (final LttngException e) { } } return false; } + @SuppressWarnings({ "unchecked", "rawtypes" }) @Override public synchronized void initTrace(final IResource resource, final String path, final Class<LttngEvent> eventType) throws TmfTraceException { super.initialize(resource, path, eventType); + setIndexer(new TmfCheckpointIndexer(this, getCacheSize())); initialize(resource, path, eventType); } @Override protected synchronized void initialize(final IResource resource, final String path, final Class<LttngEvent> eventType) throws TmfTraceException { try { currentJniTrace = JniTraceFactory.getJniTrace(path, traceLibPath, SHOW_LTT_DEBUG_DEFAULT); } catch (final Exception e) { throw new TmfTraceException(e.getMessage()); } // Export all the event types from the JNI side traceTypes = new HashMap<Integer, LttngEventType>(); traceTypeNames = new Vector<Integer>(); initialiseEventTypes(currentJniTrace); // Build the re-used event structure eventTimestamp = new LttngTimestamp(); eventSource = ""; //$NON-NLS-1$ this.eventType = new LttngEventType(); eventContent = new LttngEventContent(currentLttngEvent); eventReference = getName(); // Create the skeleton event currentLttngEvent = new LttngEvent(this, eventTimestamp, eventSource, this.eventType, eventContent, eventReference, null); // Create a new current location previousLocation = new LttngLocation(); // Set the currentEvent to the eventContent eventContent.setEvent(currentLttngEvent); setParser((ITmfEventParser<LttngEvent>) this); setCacheSize(CHECKPOINT_PAGE_SIZE); // // Bypass indexing if asked // if ( bypassIndexing == false ) { // indexTrace(true); // } // else { // Even if we don't have any index, set ONE checkpoint // fCheckpoints.add(new TmfCheckpoint(new LttngTimestamp(0L) , new // LttngLocation() ) ); initializeStreamingMonitor(); } private void initializeStreamingMonitor() { final JniTrace jniTrace = getCurrentJniTrace(); if (jniTrace == null || (!jniTrace.isLiveTraceSupported() || !LiveTraceManager.isLiveTrace(jniTrace.getTracepath()))) { // Set the time range of the trace final ITmfContext context = seekEvent(0); final LttngEvent event = getNext(context); final LttngTimestamp startTime = new LttngTimestamp(event.getTimestamp()); final LttngTimestamp endTime = new LttngTimestamp(currentJniTrace.getEndTime().getTime()); setTimeRange(new TmfTimeRange(startTime, endTime)); final TmfTraceUpdatedSignal signal = new TmfTraceUpdatedSignal(this, this, getTimeRange()); broadcast(signal); return; } // Set the time range of the trace final ITmfContext context = seekEvent(0); final LttngEvent event = getNext(context); setEndTime(TmfTimestamp.BIG_BANG); final long startTime = event != null ? event.getTimestamp().getValue() : TmfTimestamp.BIG_BANG.getValue(); setStreamingInterval(LTTNG_STREAMING_INTERVAL); final Thread thread = new Thread("Streaming Monitor for trace " + getName()) { //$NON-NLS-1$ LttngTimestamp safeTimestamp = null; TmfTimeRange timeRange = null; @SuppressWarnings("unchecked") @Override public void run() { while (!fExecutor.isShutdown()) { final TmfExperiment<?> experiment = TmfExperiment.getCurrentExperiment(); if (experiment != null) { @SuppressWarnings("rawtypes") final TmfEventRequest request = new TmfEventRequest<TmfEvent>(TmfEvent.class, TmfTimeRange.ETERNITY, 0, ExecutionType.FOREGROUND) { @Override public void handleCompleted() { updateJniTrace(); } }; synchronized (experiment) { experiment.sendRequest(request); } try { request.waitForCompletion(); } catch (final InterruptedException e) { } } else updateJniTrace(); try { Thread.sleep(LTTNG_STREAMING_INTERVAL); } catch (final InterruptedException e) { } } } private void updateJniTrace() { final JniTrace jniTrace = getCurrentJniTrace(); currentJniTrace.updateTrace(); final long endTime = jniTrace.getEndTime().getTime(); final LttngTimestamp startTimestamp = new LttngTimestamp(startTime); final LttngTimestamp endTimestamp = new LttngTimestamp(endTime); if (safeTimestamp != null && safeTimestamp.compareTo(getTimeRange().getEndTime(), false) > 0) timeRange = new TmfTimeRange(startTimestamp, safeTimestamp); else timeRange = null; safeTimestamp = endTimestamp; if (timeRange != null) setTimeRange(timeRange); } }; thread.start(); } /** * Default Constructor. * <p> * * @param name Name of the trace * @param path Path to a <b>directory</b> that contain an LTTng trace. * * @exception Exception (most likely LTTngTraceException or * FileNotFoundException) */ public LTTngTrace(final IResource resource, final String path) throws Exception { // Call with "wait for completion" true and "skip indexing" false this(resource, path, null, true, false); } /** * Constructor, with control over the indexing. * <p> * * @param name Name of the trace * @param path Path to a <b>directory</b> that contain an LTTng trace. * @param waitForCompletion Should we wait for indexign to complete before * moving on. * * @exception Exception (most likely LTTngTraceException or * FileNotFoundException) */ public LTTngTrace(final IResource resource, final String path, final boolean waitForCompletion) throws Exception { // Call with "skip indexing" false this(resource, path, null, waitForCompletion, true); } /** * Default constructor, with control over the indexing and possibility to * bypass indexation * <p> * * @param name Name of the trace * @param path Path to a <b>directory</b> that contain an LTTng trace. * @param traceLibPath Path to a <b>directory</b> that contains LTTng trace * libraries. * @param waitForCompletion Should we wait for indexign to complete before * moving on. * @param bypassIndexing Should we bypass indexing completly? This is should * only be useful for unit testing. * * @exception Exception (most likely LTTngTraceException or * FileNotFoundException) * */ public LTTngTrace(final IResource resource, final String path, final String traceLibPath, final boolean waitForCompletion, final boolean bypassIndexing) throws Exception { // super(resource, LttngEvent.class, path, CHECKPOINT_PAGE_SIZE, false); super(resource, LttngEvent.class, path, CHECKPOINT_PAGE_SIZE); initialize(resource, path, LttngEvent.class); // if (!bypassIndexing) // indexTrace(false); this.traceLibPath = traceLibPath; } /* * Copy constructor is forbidden for LttngEvenmStream */ public LTTngTrace(final LTTngTrace other) throws Exception { this(other.getResource(), other.getPath(), other.getTraceLibPath(), false, true); // this.fCheckpoints = other.fCheckpoints; setTimeRange(new TmfTimeRange(new LttngTimestamp(other.getStartTime()), new LttngTimestamp(other.getEndTime()))); } // @Override // public synchronized LTTngTrace clone() { // LTTngTrace clone = null; // clone = (LTTngTrace) super.clone(); // try { // clone.currentJniTrace = JniTraceFactory.getJniTrace(getPath(), getTraceLibPath(), // SHOW_LTT_DEBUG_DEFAULT); // } catch (final JniException e) { // // e.printStackTrace(); // } // // // Export all the event types from the JNI side // clone.traceTypes = new HashMap<Integer, LttngEventType>(); // clone.traceTypeNames = new Vector<Integer>(); // clone.initialiseEventTypes(clone.currentJniTrace); // // // Verify that all those "default constructor" are safe to use // clone.eventTimestamp = new LttngTimestamp(); // clone.eventSource = ""; //$NON-NLS-1$ // clone.eventType = new LttngEventType(); // clone.eventContent = new LttngEventContent(clone.currentLttngEvent); // clone.eventReference = getName(); // // // Create the skeleton event // clone.currentLttngEvent = new LttngEvent(this, clone.eventTimestamp, clone.eventSource, clone.eventType, // clone.eventContent, clone.eventReference, null); // // // Create a new current location // clone.previousLocation = new LttngLocation(); // // // Set the currentEvent to the eventContent // clone.eventContent.setEvent(clone.currentLttngEvent); // // // Set the start time of the trace // setTimeRange(new TmfTimeRange(new LttngTimestamp(clone.currentJniTrace.getStartTime().getTime()), // new LttngTimestamp(clone.currentJniTrace.getEndTime().getTime()))); // // return clone; // } public String getTraceLibPath() { return traceLibPath; } /* * Fill out the HashMap with "Type" (Tracefile/Marker) * * This should be called at construction once the trace is open */ private void initialiseEventTypes(final JniTrace trace) { // Work variables LttngEventType tmpType = null; String[] markerFieldsLabels = null; String newTracefileKey = null; Integer newMarkerKey = null; JniTracefile newTracefile = null; JniMarker newMarker = null; // First, obtain an iterator on TRACEFILES of owned by the TRACE final Iterator<String> tracefileItr = trace.getTracefilesMap().keySet().iterator(); while (tracefileItr.hasNext()) { newTracefileKey = tracefileItr.next(); newTracefile = trace.getTracefilesMap().get(newTracefileKey); // From the TRACEFILE read, obtain its MARKER final Iterator<Integer> markerItr = newTracefile.getTracefileMarkersMap().keySet().iterator(); while (markerItr.hasNext()) { newMarkerKey = markerItr.next(); newMarker = newTracefile.getTracefileMarkersMap().get(newMarkerKey); // From the MARKER we can obtain the MARKERFIELDS keys (i.e. // labels) markerFieldsLabels = newMarker.getMarkerFieldsHashMap().keySet() .toArray(new String[newMarker.getMarkerFieldsHashMap().size()]); tmpType = new LttngEventType(newTracefile.getTracefileName(), newTracefile.getCpuNumber(), newMarker.getName(), newMarkerKey.intValue(), markerFieldsLabels); // Add the type to the map/vector addEventTypeToMap(tmpType); } } } /* * Add a new type to the HashMap * * As the hashmap use a key format that is a bit dangerous to use, we should * always add using this function. */ private void addEventTypeToMap(final LttngEventType newEventType) { final int newTypeKey = EventTypeKey.getEventTypeHash(newEventType); this.traceTypes.put(newTypeKey, newEventType); this.traceTypeNames.add(newTypeKey); } /** * Return the latest saved location. Note : Modifying the returned location * may result in buggy positionning! * * @return The LttngLocation as it was after the last operation. * * @see org.eclipse.linuxtools.internal.lttng.core.event.LttngLocation */ @Override public synchronized ITmfLocation<?> getCurrentLocation() { return previousLocation; } /** * Position the trace to the event at the given location. * <p> * NOTE : Seeking by location is very fast compare to seeking by position * but is still slower than "ReadNext", avoid using it for small interval. * * @param location Location of the event in the trace. If no event available * at this exact location, we will position ourself to the next * one. * * @return The TmfContext that point to this event * * @see org.eclipse.linuxtools.internal.lttng.core.event.LttngLocation * @see org.eclipse.linuxtools.tmf.core.trace.TmfContext */ @Override public synchronized ITmfContext seekEvent(final ITmfLocation<?> location) { if (PRINT_DEBUG) System.out.println("seekLocation(location) location -> " + location); //$NON-NLS-1$ // If the location in context is null, create a new one if (location == null) { LttngLocation curLocation = new LttngLocation(); final ITmfContext context = seekEvent(curLocation.getOperationTime()); context.setRank(0); return context; } // The only seek valid in LTTng is with the time, we call // seekEvent(timestamp) LttngLocation curLocation = (LttngLocation) location; final ITmfContext context = seekEvent(curLocation.getOperationTime()); // If the location is marked with the read next flag // then it is pointing to the next event following the operation time if (curLocation.isLastOperationReadNext()) getNext(context); return context; } /** * Position the trace to the event at the given time. * <p> * NOTE : Seeking by time is very fast compare to seeking by position but is * still slower than "ReadNext", avoid using it for small interval. * * @param timestamp Time of the event in the trace. If no event available at * this exact time, we will position ourself to the next one. * * @return The TmfContext that point to this event * * @see org.eclipse.linuxtools.internal.lttng.core.event.LttngLocation * @see org.eclipse.linuxtools.tmf.core.trace.TmfContext */ @Override public synchronized TmfContext seekEvent(final ITmfTimestamp timestamp) { if (PRINT_DEBUG) System.out.println("seekEvent(timestamp) timestamp -> " + timestamp); //$NON-NLS-1$ // Call JNI to seek currentJniTrace.seekToTime(new JniTime(timestamp.getValue())); // Save the time at which we seeked previousLocation.setOperationTime(timestamp.getValue()); // Set the operation marker as seek, to be able to detect we did "seek" // this event previousLocation.setLastOperationSeek(); final LttngLocation curLocation = new LttngLocation(previousLocation); return new TmfContext(curLocation); } /** * Position the trace to the event at the given position (rank). * <p> * NOTE : Seeking by position is very slow in LTTng, consider seeking by * timestamp. * * @param rank Position (or rank) of the event in the trace, starting at 0. * * @return The TmfContext that point to this event * * @see org.eclipse.linuxtools.internal.lttng.core.event.LttngLocation * @see org.eclipse.linuxtools.tmf.core.trace.TmfContext */ @Override public synchronized TmfContext seekEvent(final long rank) { if (PRINT_DEBUG) System.out.println("seekEvent(rank) rank -> " + rank); //$NON-NLS-1$ // ITmfTimestamp timestamp = null; // long index = rank / getCacheSize(); // // // Get the timestamp of the closest check point to the given position // if (fCheckpoints.size() > 0) { // if (index >= fCheckpoints.size()) // index = fCheckpoints.size() - 1; // timestamp = fCheckpoints.elementAt((int) index).getTimestamp(); // } else // timestamp = getStartTime(); // Position the trace at the checkpoint final ITmfContext checkpointContext = getIndexer().seekIndex(rank); LttngLocation location = (LttngLocation) checkpointContext.getLocation(); ITmfTimestamp timestamp = location.getLocation(); long index = rank / getCacheSize(); // Seek to the found time final TmfContext tmpContext = seekEvent(timestamp); tmpContext.setRank((index + 1) * getCacheSize()); previousLocation = (LttngLocation) tmpContext.getLocation(); // Ajust the index of the event we found at this check point position Long currentPosition = index * getCacheSize(); Long lastTimeValueRead = 0L; // Get the event at current position. This won't move to the next one JniEvent tmpJniEvent = currentJniTrace.findNextEvent(); // Now that we are positionned at the checkpoint, // we need to "readNext" (Position - CheckpointPosition) times or until // trace "run out" while ((tmpJniEvent != null) && (currentPosition < rank)) { tmpJniEvent = currentJniTrace.readNextEvent(); currentPosition++; } // If we found our event, save its timestamp if (tmpJniEvent != null) lastTimeValueRead = tmpJniEvent.getEventTime().getTime(); // Set the operation marker as seek, to be able to detect we did "seek" // this event previousLocation.setLastOperationSeek(); // Save read event time previousLocation.setOperationTime(lastTimeValueRead); // *** VERIFY *** // Is that too paranoid? // // We don't trust what upper level could do with our internal location // so we create a new one to return instead final LttngLocation curLocation = new LttngLocation(previousLocation); return new TmfContext(curLocation, rank); } @Override public TmfContext seekEvent(final double ratio) { // TODO Auto-generated method stub return null; } @Override public double getLocationRatio(final ITmfLocation<?> location) { // TODO Auto-generated method stub return 0; } /** * Return the event in the trace according to the given context. Read it if * necessary. * <p> * Similar (same?) as ParseEvent except that calling GetNext twice read the * next one the second time. * * @param context Current TmfContext where to get the event * * @return The LttngEvent we read of null if no event are available * * @see org.eclipse.linuxtools.internal.lttng.core.event.LttngLocation * @see org.eclipse.linuxtools.tmf.core.trace.TmfContext */ public int nbEventsRead = 0; @Override public synchronized LttngEvent getNext(final ITmfContext context) { if (PRINT_DEBUG) System.out.println("getNextEvent(context) context.getLocation() -> " //$NON-NLS-1$ + context.getLocation()); LttngEvent returnedEvent = null; LttngLocation curLocation = null; curLocation = (LttngLocation) context.getLocation(); // If the location in context is null, create a new one if (curLocation == null) curLocation = getCurrentLocation(context); // *** Positioning trick : // GetNextEvent only read the trace if : // 1- The last operation was NOT a ParseEvent --> A read is required // OR // 2- The time of the previous location is different from the current // one --> A seek + a read is required if ((!(curLocation.isLastOperationParse())) || (previousLocation.getOperationTimeValue() != curLocation.getOperationTimeValue())) { if (previousLocation.getOperationTimeValue() != curLocation.getOperationTimeValue()) { if (PRINT_DEBUG) System.out.println("\t\tSeeking in getNextEvent. [ LastTime : " //$NON-NLS-1$ + previousLocation.getOperationTimeValue() + " CurrentTime" //$NON-NLS-1$ + curLocation.getOperationTimeValue() + " ]"); //$NON-NLS-1$ seekEvent(curLocation.getOperationTime()); } // Read the next event from the trace. The last one will NO LONGER // BE VALID. returnedEvent = readNextEvent(curLocation); } else { // No event was read, just return the one currently loaded (the last // one we read) returnedEvent = currentLttngEvent; // Set the operation marker as read to both locations, to be able to // detect we need to read the next event previousLocation.setLastOperationReadNext(); curLocation.setLastOperationReadNext(); } // If we read an event, set it's time to the locations (both previous // and current) if (returnedEvent != null) setPreviousAndCurrentTimes(context, returnedEvent, curLocation); return returnedEvent; } // this method was extracted for profiling purposes private synchronized void setPreviousAndCurrentTimes(final ITmfContext context, final LttngEvent returnedEvent, final LttngLocation curLocation) { final ITmfTimestamp eventTimestamp = returnedEvent.getTimestamp(); // long eventTime = eventTimestamp.getValue(); previousLocation.setOperationTime(eventTimestamp.getValue()); curLocation.setOperationTime(eventTimestamp.getValue()); updateAttributes(context, eventTimestamp); context.increaseRank(); } // protected void updateIndex(TmfContext context, long rank, ITmfTimestamp timestamp) { // // if (getStartTime().compareTo(timestamp, false) > 0) // setStartTime(timestamp); // if (getEndTime().compareTo(timestamp, false) < 0) // setEndTime(timestamp); // if (rank != ITmfContext.UNKNOWN_RANK) { // if (fNbEvents <= rank) // fNbEvents = rank + 1; // // Build the index as we go along // if ((rank % fIndexPageSize) == 0) { // // Determine the table position // long position = rank / fIndexPageSize; // // Add new entry at proper location (if empty) // if (fCheckpoints.size() == position) { // addCheckPoint(context, timestamp); // } // } // } // } // this method was extracted for profiling purposes private synchronized LttngEvent readNextEvent(final LttngLocation curLocation) { LttngEvent returnedEvent; // Read the next event from the trace. The last one will NO LONGER BE // VALID. returnedEvent = readEvent(curLocation); nbEventsRead++; // Set the operation marker as read to both locations, to be able to // detect we need to read the next event previousLocation.setLastOperationReadNext(); curLocation.setLastOperationReadNext(); return returnedEvent; } // this method was extracted for profiling purposes private LttngLocation getCurrentLocation(final ITmfContext context) { LttngLocation curLocation; curLocation = new LttngLocation(); context.setLocation(curLocation); return curLocation; } /** * Return the event in the trace according to the given context. Read it if * necessary. * <p> * Similar (same?) as GetNextEvent except that calling ParseEvent twice will * return the same event * * @param context Current TmfContext where to get the event * * @return The LttngEvent we read of null if no event are available * * @see org.eclipse.linuxtools.internal.lttng.core.event.LttngLocation * @see org.eclipse.linuxtools.tmf.core.trace.TmfContext */ @Override public synchronized LttngEvent parseEvent(final ITmfContext context) { if (PRINT_DEBUG) System.out.println("parseEvent(context) context.getLocation() -> " //$NON-NLS-1$ + context.getLocation()); LttngEvent returnedEvent = null; LttngLocation curLocation = null; // If the location in context is null, create a new one if (context.getLocation() == null) { curLocation = new LttngLocation(); context.setLocation(curLocation); } else curLocation = (LttngLocation) context.getLocation(); // *** HACK *** // TMF assumes it is possible to read (GetNextEvent) to the next Event // once ParseEvent() is called // In LTTNG, there is not difference between "Parsing" and "Reading" an // event. // So, before "Parsing" an event, we have to make sure we didn't "Read" // it alreafy. // Also, "Reading" invalidate the previous Event in LTTNG and seek back // is very costly, // so calling twice "Parse" will return the same event, giving a way to // get the "Currently loaded" event // *** Positionning trick : // ParseEvent only read the trace if : // 1- The last operation was NOT a ParseEvent --> A read is required // OR // 2- The time of the previous location is different from the current // one --> A seek + a read is required if (!curLocation.isLastOperationParse() || (previousLocation.getOperationTimeValue() != curLocation.getOperationTimeValue())) { // Previous time != Current time : We need to reposition to the // current time if (previousLocation.getOperationTimeValue() != curLocation.getOperationTimeValue()) { if (PRINT_DEBUG) System.out.println("\t\tSeeking in getNextEvent. [ LastTime : " //$NON-NLS-1$ + previousLocation.getOperationTimeValue() + " CurrentTime" //$NON-NLS-1$ + curLocation.getOperationTimeValue() + " ]"); //$NON-NLS-1$ seekEvent(curLocation.getOperationTime()); } // Read the next event from the trace. The last one will NO LONGER // BE VALID. returnedEvent = readEvent(curLocation); } else // No event was read, just return the one currently loaded (the last // one we read) returnedEvent = currentLttngEvent; // If we read an event, set it's time to the locations (both previous // and current) if (returnedEvent != null) { previousLocation.setOperationTime((LttngTimestamp) returnedEvent.getTimestamp()); curLocation.setOperationTime((LttngTimestamp) returnedEvent.getTimestamp()); } // Set the operation marker as parse to both location, to be able to // detect we already "read" this event previousLocation.setLastOperationParse(); curLocation.setLastOperationParse(); return returnedEvent; } /* * Read the next event from the JNI and convert it as Lttng Event<p> * * @param location Current LttngLocation that to be updated with the event * timestamp * * @return The LttngEvent we read of null if no event are available * * @see org.eclipse.linuxtools.lttng.event.LttngLocation * * @see org.eclipse.linuxtools.org.eclipse.linuxtools.lttng.jni.JniTrace */ private synchronized LttngEvent readEvent(final LttngLocation location) { LttngEvent returnedEvent = null; JniEvent tmpEvent = null; // Read the next event from JNI. THIS WILL INVALIDATE THE CURRENT LTTNG // EVENT. tmpEvent = currentJniTrace.readNextEvent(); if (tmpEvent != null) { // *** NOTE // Convert will update the currentLttngEvent returnedEvent = convertJniEventToTmf(tmpEvent); location.setOperationTime((LttngTimestamp) returnedEvent.getTimestamp()); } else location.setOperationTime(getEndTime().getValue() + 1); return returnedEvent; } /** * Method to convert a JniEvent into a LttngEvent. * <p> * * Note : This method will call LttngEvent convertEventJniToTmf(JniEvent, * boolean) with a default value for isParsingNeeded * * @param newEvent The JniEvent to convert into LttngEvent * * @return The converted LttngEvent * * @see org.eclipse.linuxtools.org.eclipse.linuxtools.lttng.jni.JniEvent * @see org.eclipse.linuxtools.internal.lttng.core.event.LttngEvent */ public synchronized LttngEvent convertJniEventToTmf(final JniEvent newEvent) { currentLttngEvent = convertJniEventToTmf(newEvent, IS_PARSING_NEEDED_DEFAULT); return currentLttngEvent; } /** * Method to convert a JniEvent into a LttngEvent * * @param jniEvent The JniEvent to convert into LttngEvent * @param isParsingNeeded A boolean value telling if the event should be * parsed or not. * * @return The converted LttngEvent * * @see org.eclipse.linuxtools.org.eclipse.linuxtools.lttng.jni.JniEvent * @see org.eclipse.linuxtools.internal.lttng.core.event.LttngEvent */ public synchronized LttngEvent convertJniEventToTmf(final JniEvent jniEvent, final boolean isParsingNeeded) { if (UNIQUE_EVENT) { // *** // UNHACKED : We can no longer do that because TCF need to maintain // several events at once. // This is very slow to do so in LTTng, this has to be temporary. // *** HACK *** // To save time here, we only set value instead of allocating new // object // This give an HUGE performance improvement // all allocation done in the LttngTrace constructor // *** eventTimestamp.setValue(jniEvent.getEventTime().getTime()); eventSource = jniEvent.requestEventSource(); eventType = traceTypes.get(EventTypeKey.getEventTypeHash(jniEvent)); final String fullTracePath = getName(); final String reference = fullTracePath.substring(fullTracePath.lastIndexOf('/') + 1); currentLttngEvent.setReference(reference); eventContent.emptyContent(); currentLttngEvent.setType(eventType); // Save the jni reference currentLttngEvent.updateJniEventReference(jniEvent); // Parse now if was asked // Warning : THIS IS SLOW if (isParsingNeeded) eventContent.getFields(); return currentLttngEvent; } else return convertJniEventToTmfMultipleEventEvilFix(jniEvent, isParsingNeeded); } /** * This method is a temporary fix to support multiple events at once in TMF * This is expected to be slow and should be fixed in another way. See * comment in convertJniEventToTmf(); * * @param jniEvent The current JNI Event * @return Current Lttng Event fully parsed */ private synchronized LttngEvent convertJniEventToTmfMultipleEventEvilFix(final JniEvent jniEvent, final boolean isParsingNeeded) { // *** HACK *** // Below : the "fix" with all the new and the full-parse // Allocating new memory is slow. // Parsing every events is very slow. eventTimestamp = new LttngTimestamp(jniEvent.getEventTime().getTime()); eventSource = jniEvent.requestEventSource(); eventReference = getName(); eventType = new LttngEventType(traceTypes.get(EventTypeKey.getEventTypeHash(jniEvent))); eventContent = new LttngEventContent(currentLttngEvent); currentLttngEvent = new LttngEvent(this, eventTimestamp, eventSource, eventType, eventContent, eventReference, null); // The jni reference is no longer reliable but we will keep it anyhow currentLttngEvent.updateJniEventReference(jniEvent); // Ensure that the content is correctly set eventContent.setEvent(currentLttngEvent); // Parse the event if it was needed // *** WARNING *** // ONLY for testing, NOT parsing events with non-unique events WILL // result in segfault in the JVM if (isParsingNeeded) eventContent.getFields(); return currentLttngEvent; } /** * Reference to the current LttngTrace we are reading from. * <p> * * Note : This bypass the framework and should not be use, except for * testing! * * @return Reference to the current LttngTrace * * @see org.eclipse.linuxtools.org.eclipse.linuxtools.lttng.jni.JniTrace */ public JniTrace getCurrentJniTrace() { return currentJniTrace; } /** * Return a reference to the current LttngEvent we have in memory. * * @return The current (last read) LttngEvent * * @see org.eclipse.linuxtools.internal.lttng.core.event.LttngEvent */ public synchronized LttngEvent getCurrentEvent() { return currentLttngEvent; } /** * Get the major version number for the current trace * * @return Version major or -1 if unknown * * @see org.eclipse.linuxtools.org.eclipse.linuxtools.lttng.jni.JniTrace * */ public short getVersionMajor() { if (currentJniTrace != null) return currentJniTrace.getLttMajorVersion(); else return -1; } /** * Get the minor version number for the current trace * * @return Version minor or -1 if unknown * * @see org.eclipse.linuxtools.org.eclipse.linuxtools.lttng.jni.JniTrace * */ public short getVersionMinor() { if (currentJniTrace != null) return currentJniTrace.getLttMinorVersion(); else return -1; } /** * Get the number of CPU for this trace * * @return Number of CPU or -1 if unknown * * @see org.eclipse.linuxtools.org.eclipse.linuxtools.lttng.jni.JniTrace * */ public int getCpuNumber() { if (currentJniTrace != null) return currentJniTrace.getCpuNumber(); else return -1; } // /** // * Print the content of the checkpoint vector. // * <p> // * // * This is intended for debug purpose only. // */ // public void printCheckpointsVector() { // System.out.println("StartTime : " //$NON-NLS-1$ // + getTimeRange().getStartTime().getValue()); // System.out.println("EndTime : " //$NON-NLS-1$ // + getTimeRange().getEndTime().getValue()); // // for (int pos = 0; pos < fCheckpoints.size(); pos++) { // System.out.print(pos + ": " + "\t"); //$NON-NLS-1$ //$NON-NLS-2$ // System.out.print(fCheckpoints.get(pos).getTimestamp() + "\t"); //$NON-NLS-1$ // System.out.println(fCheckpoints.get(pos).getLocation()); // } // } @Override public synchronized void dispose() { if (currentJniTrace != null) currentJniTrace.closeTrace(); super.dispose(); } /** * Return a String identifying this trace. * * @return String that identify this trace */ @Override @SuppressWarnings("nls") public String toString() { String returnedData = ""; returnedData += "Path :" + getPath() + " "; returnedData += "Trace:" + currentJniTrace + " "; returnedData += "Event:" + currentLttngEvent; return returnedData; } } /* * EventTypeKey inner class * * This class is used to make the process of generating the HashMap key more * transparent and so less error prone to use */ final class EventTypeKey { // *** WARNING *** // These two getEventTypeKey() functions should ALWAYS construct the key the // same ways! // Otherwise, every type search will fail! // added final to encourage inlining. // generating a hash code by hand to avoid a string creation final static public int getEventTypeHash(final LttngEventType newEventType) { return generateHash(newEventType.getTracefileName(), newEventType.getCpuId(), newEventType.getMarkerName()); } final private static int generateHash(final String traceFileName, final long cpuNumber, final String markerName) { // 0x1337 is a prime number. The number of CPUs is always under 8192 on // the current kernel, so this will work with the current linux kernel. final int cpuHash = (int) (cpuNumber * (0x1337)); return traceFileName.hashCode() ^ (cpuHash) ^ markerName.hashCode(); } // generating a hash code by hand to avoid a string creation final static public int getEventTypeHash(final JniEvent newEvent) { return generateHash(newEvent.getParentTracefile().getTracefileName(), newEvent.getParentTracefile() .getCpuNumber(), newEvent.requestEventMarker().getName()); } }
false
false
null
null
diff --git a/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/actions/RunToLineActionDelegate.java b/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/actions/RunToLineActionDelegate.java index cbc0e9e35..6d70ae803 100644 --- a/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/actions/RunToLineActionDelegate.java +++ b/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/actions/RunToLineActionDelegate.java @@ -1,190 +1,193 @@ package org.eclipse.jdt.internal.debug.ui.actions; /********************************************************************** Copyright (c) 2000, 2002 IBM Corp. All rights reserved. This file is made available under the terms of the Common Public License v1.0 which accompanies this distribution, and is available at http://www.eclipse.org/legal/cpl-v10.html **********************************************************************/ import java.util.HashMap; import java.util.Map; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.debug.core.DebugException; import org.eclipse.debug.core.DebugPlugin; import org.eclipse.debug.core.model.IBreakpoint; import org.eclipse.debug.core.model.IDebugElement; import org.eclipse.debug.core.model.IDebugTarget; import org.eclipse.debug.core.model.IThread; import org.eclipse.debug.ui.DebugUITools; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.debug.core.JDIDebugModel; import org.eclipse.jdt.internal.debug.ui.BreakpointUtils; import org.eclipse.jdt.internal.debug.ui.ExceptionHandler; import org.eclipse.jdt.internal.debug.ui.JDIDebugUIPlugin; import org.eclipse.jdt.internal.debug.ui.snippeteditor.ScrapbookLauncher; import org.eclipse.jface.action.IAction; import org.eclipse.jface.text.ITextSelection; -import org.eclipse.swt.widgets.Event; import org.eclipse.ui.IEditorActionDelegate; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.texteditor.ITextEditor; /** * Action to support run to line (i.e. where the cursor is in the active editor) */ public class RunToLineActionDelegate extends ManageBreakpointActionDelegate implements IEditorActionDelegate { public RunToLineActionDelegate() { } /** - * @see IActionDelegate2#runWithEvent(org.eclipse.jface.action.IAction, org.eclipse.swt.widgets.Event)(IAction) + * @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction) */ - public void runWithEvent(IAction action, Event event) { + public void run(IAction action) { try { IDebugTarget target= getContext(); if (target == null) { if (getTextEditor() != null) { getTextEditor().getSite().getShell().getDisplay().beep(); } return; } ITextSelection selection= (ITextSelection)getTextEditor().getSelectionProvider().getSelection(); setLineNumber(selection.getStartLine() + 1); IType type= getType(getTextEditor().getEditorInput()); if (type == null) { return; } IBreakpoint breakpoint= null; try { Map attributes = new HashMap(4); BreakpointUtils.addJavaBreakpointAttributes(attributes, type); BreakpointUtils.addRunToLineAttributes(attributes); breakpoint= JDIDebugModel.createLineBreakpoint(BreakpointUtils.getBreakpointResource(type), type.getFullyQualifiedName(), getLineNumber(), -1, -1, 1, false, attributes); } catch (CoreException ce) { ExceptionHandler.handle(ce, ActionMessages.getString("RunToLine.error.title1"), ActionMessages.getString("RunToLine.error.message1")); //$NON-NLS-1$ //$NON-NLS-2$ return; } target.breakpointAdded(breakpoint); IThread[] threads= target.getThreads(); for (int i= 0; i < threads.length; i++) { IThread thread= threads[i]; if (thread.canResume()) { try { thread.resume(); } catch (DebugException de) { JDIDebugUIPlugin.log(de); } break; } } } catch(DebugException de) { ExceptionHandler.handle(de, ActionMessages.getString("RunToLine.error.title1"), ActionMessages.getString("RunToLine.error.message1")); //$NON-NLS-1$ //$NON-NLS-2$ } } /** * Resolves the debug target context to set the run to line */ protected IDebugTarget getContext() throws DebugException{ IDebugTarget target= getContextFromUI(); if (target == null) { target= getContextFromModel(); //target has already been checked for suspended thread return target; } if (target == null) { return null; } if (target.getLaunch().getAttribute(ScrapbookLauncher.SCRAPBOOK_LAUNCH) != null) { //can't set run to line in scrapbook context return null; } IThread[] threads= target.getThreads(); for (int i= 0; i < threads.length; i++) { IThread thread= threads[i]; if (thread.canResume()) { return target; } } return null; } /** * Resolves a debug target context from the model */ protected IDebugTarget getContextFromModel() throws DebugException { IDebugTarget[] dts= DebugPlugin.getDefault().getLaunchManager().getDebugTargets(); for (int i= 0; i < dts.length; i++) { IDebugTarget dt= dts[i]; if (getContextFromDebugTarget(dt) != null) { return dt; } } return null; } /** * Resolves a debug target context from the model */ protected IDebugTarget getContextFromThread(IThread thread) throws DebugException { if (thread.isSuspended()) { return thread.getDebugTarget(); } return null; } /** * Resolves a stack frame context from the UI */ protected IDebugTarget getContextFromUI() throws DebugException { IAdaptable de= DebugUITools.getDebugContext(); if (de != null) { if (de instanceof IThread) { return getContextFromThread((IThread) de); } else if (de instanceof IDebugElement) { return ((IDebugElement)de).getDebugTarget(); } } return null; } /** * Updates the enabled state of this action and the plugin action * this action is the delegate for. */ protected void update() { setEnabledState(getTextEditor()); } /** * Resolves a stack frame context from the model. */ protected IDebugTarget getContextFromDebugTarget(IDebugTarget dt) throws DebugException { if (dt.isTerminated() || dt.isDisconnected()) { return null; } IThread[] threads= dt.getThreads(); for (int i= 0; i < threads.length; i++) { IThread thread= threads[i]; if (thread.isSuspended()) { return dt; } } return null; } /** * @see IEditorActionDelegate#setActiveEditor(IAction, IEditorPart) */ public void setActiveEditor(IAction action, IEditorPart targetEditor) { setAction(action); if (targetEditor instanceof ITextEditor) { setTextEditor((ITextEditor)targetEditor); } + if (!action.isEnabled()) { + //the xml specified enabler has set the action to be disabled + return; + } setEnabledState(getTextEditor()); } } \ No newline at end of file
false
false
null
null
diff --git a/org.openscada.da.client.dataitem.details/src/org/openscada/da/client/dataitem/details/part/AbstractBaseDetailsPart.java b/org.openscada.da.client.dataitem.details/src/org/openscada/da/client/dataitem/details/part/AbstractBaseDetailsPart.java index 07ea485be..97868e215 100644 --- a/org.openscada.da.client.dataitem.details/src/org/openscada/da/client/dataitem/details/part/AbstractBaseDetailsPart.java +++ b/org.openscada.da.client.dataitem.details/src/org/openscada/da/client/dataitem/details/part/AbstractBaseDetailsPart.java @@ -1,185 +1,184 @@ /* * This file is part of the OpenSCADA project * Copyright (C) 2006-2008 inavare GmbH (http://inavare.com) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package org.openscada.da.client.dataitem.details.part; import java.util.Observable; import java.util.Observer; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.openscada.core.Variant; import org.openscada.da.base.item.DataItemHolder; import org.openscada.da.client.DataItem; import org.openscada.da.client.DataItemValue; public abstract class AbstractBaseDetailsPart implements Observer, DetailsPart { protected Display display; protected DataItem item; protected DataItemValue value; protected DataItemHolder itemHolder; protected Shell shell; private Composite parent; public AbstractBaseDetailsPart () { super (); } public void createPart ( final Composite parent ) { this.display = parent.getDisplay (); this.shell = parent.getShell (); this.parent = parent; } public void setDataItem ( final DataItemHolder itemHolder, final DataItem item ) { this.itemHolder = itemHolder; if ( this.item != null ) { this.item.deleteObserver ( this ); this.item = null; } this.item = item; if ( this.item != null ) { // fetch the initial value this.value = this.item.getSnapshotValue (); - update (); - this.item.addObserver ( this ); + update (); } } public void dispose () { if ( this.item != null ) { this.item.deleteObserver ( this ); this.item = null; } } /** * called by DataItem */ public void update ( final Observable o, final Object arg ) { AbstractBaseDetailsPart.this.value = AbstractBaseDetailsPart.this.item.getSnapshotValue (); // trigger async update in display thread this.display.asyncExec ( new Runnable () { public void run () { if ( !AbstractBaseDetailsPart.this.parent.isDisposed () ) { AbstractBaseDetailsPart.this.update (); } } } ); } protected abstract void update (); /** * Return if the value is unsafe * @return <code>true</code> if the value part is unsafe, <code>false</code> otherwise */ protected boolean isUnsafe () { return this.value.isError () || !this.value.isConnected (); } protected boolean isError () { return this.value.isError (); } protected boolean isAlarm () { return this.value.isAlarm (); } protected boolean isManual () { return this.value.isManual (); } protected boolean getBooleanAttribute ( final String name ) { if ( this.value.getAttributes ().containsKey ( name ) ) { return this.value.getAttributes ().get ( name ).asBoolean (); } return false; } protected Number getNumberAttribute ( final String name, final Number defaultValue ) { final Variant value = this.value.getAttributes ().get ( name ); if ( value == null ) { return defaultValue; } if ( value.isNull () ) { return defaultValue; } try { if ( value.isDouble () ) { return value.asDouble (); } if ( value.isInteger () ) { return value.asInteger (); } if ( value.isLong () ) { return value.asLong (); } if ( value.isBoolean () ) { return value.asBoolean () ? 1 : 0; } return Double.parseDouble ( value.asString () ); } catch ( final Throwable e ) { } return defaultValue; } } \ No newline at end of file
false
false
null
null
diff --git a/de.remote.desktop/src/de/remote/desktop/ControlFrame.java b/de.remote.desktop/src/de/remote/desktop/ControlFrame.java index e64f861..9db2d70 100644 --- a/de.remote.desktop/src/de/remote/desktop/ControlFrame.java +++ b/de.remote.desktop/src/de/remote/desktop/ControlFrame.java @@ -1,342 +1,338 @@ package de.remote.desktop; import java.awt.BorderLayout; import java.awt.MenuBar; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.UnknownHostException; import javax.imageio.ImageIO; import javax.swing.JFrame; import javax.swing.JTabbedPane; import de.newsystem.rmi.api.Server; import de.newsystem.rmi.protokol.RemoteException; import de.remote.api.ControlConstants; import de.remote.api.IBrowser; import de.remote.api.IChatServer; import de.remote.api.IPlayList; import de.remote.api.IPlayer; import de.remote.api.IPlayerListener; import de.remote.api.IMusicStation; import de.remote.api.PlayerException; import de.remote.api.PlayingBean; import de.remote.desktop.menus.ControlMenu; import de.remote.desktop.menus.PlayerMenu; import de.remote.desktop.menus.RegistryMenu; import de.remote.desktop.panels.BrowserPanel; import de.remote.desktop.panels.ChatPanel; import de.remote.desktop.panels.PlayListPanel; import de.remote.desktop.panels.PlayerPanel; import de.remote.desktop.panels.RegistryPanel; import de.remote.desktop.panels.WebcamPanel; /** * The main frame for the gui. It creates all panels and menus that will be * needed. * * @author sebastian */ /** * @author sebastian * */ /** * @author sebastian * */ public class ControlFrame extends JFrame implements Connectable { /** * generated id */ private static final long serialVersionUID = 1222897455250462547L; /** * control panel for the player */ private PlayerPanel playerControl; /** * browser panel to display directories */ private BrowserPanel fileBrowser; /** * playlist panel to display playlists and items of playlists */ private PlayListPanel plsBrowser; /** * chat panel with textfields do write and get messages */ private ChatPanel chat; /** * the webcam panel displays a remote webcam */ private WebcamPanel webcam; /** * menu to choose different server to connect with */ private RegistryMenu serverMenu; /** * menu to choose different player */ private PlayerMenu playerMenu; /** * menu for main control options, example shutdown */ private ControlMenu controlMenu; /** * listener for the player */ private DesktopPlayerListener playerListener; /** * player object for the remote player */ private IPlayer currentPlayer; /** * remote factory object to get all other remote objects */ public IMusicStation station; /** * remote mplayer */ private IPlayer mPlayer; /** * remote totem */ private IPlayer totemPlayer; /** * chat server object */ private IChatServer chatServer; /** * the local server */ public Server server; /** * port for the local server */ private int port; /** * client name used for chat client */ private String clientName; /** * the server editor provides functionality to edit the server list. */ private RegistryPanel serverEditor; /** * allocate frame and create all panels and menus */ public ControlFrame() { super("Remote Control"); setDefaultCloseOperation(3); setSize(760, 400); loadIcon(); this.controlMenu = new ControlMenu(); this.serverMenu = new RegistryMenu(this); this.playerMenu = new PlayerMenu(this); this.playerControl = new PlayerPanel(); this.chat = new ChatPanel(); this.plsBrowser = new PlayListPanel(); this.fileBrowser = new BrowserPanel(); this.serverEditor = new RegistryPanel(serverMenu); this.webcam = new WebcamPanel(); this.playerListener = new DesktopPlayerListener(); setLayout(new BorderLayout()); add(BorderLayout.SOUTH, this.playerControl); JTabbedPane tabs = new JTabbedPane(); add(BorderLayout.CENTER, tabs); tabs.add(this.fileBrowser); tabs.add(this.plsBrowser); tabs.add(this.chat); tabs.add(this.serverEditor); tabs.add(this.webcam); setVisible(true); addWindowListener(new DesktopWindowListener()); MenuBar menuBar = new MenuBar(); menuBar.add(this.controlMenu); menuBar.add(this.serverMenu); menuBar.add(this.playerMenu); setMenuBar(menuBar); } /** * load icon for program */ private void loadIcon() { // first argument is location on local testing // second argument is in jar file String[] res = { "res/icon.png", "./icon.png" }; InputStream base = null; for (String str : res) { base = getClass().getClassLoader().getResourceAsStream(str); if (base != null) break; } try { BufferedImage image = ImageIO.read(base); setIconImage(image); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } /** * set new current player. playerpanel, browserpanel and plspanel will be * informed. * * @param player */ public void setPlayer(IPlayer player) { this.currentPlayer = player; this.fileBrowser.setPlayer(player); this.plsBrowser.setPlayer(player); this.playerControl.setPlayer(player); } /** * create new connection to server, read objects from new registry. start * new local server at given port. * * @param registry * @param port * @param name */ public void connectToServer(String registry, int port, String name) { try { closeConnections(); this.port = port; clientName = name; setTitle("connecting..."); server = Server.getServer(); server.connectToRegistry(registry); server.startServer(port); station = ((IMusicStation) server.find(ControlConstants.STATION_ID, IMusicStation.class)); mPlayer = station.getMPlayer(); totemPlayer = station.getTotemPlayer(); IBrowser browser = station.createBrowser(); mPlayer.addPlayerMessageListener(playerListener); try { playerListener.playerMessage(mPlayer.getPlayingBean()); } catch (PlayerException e) { e.printStackTrace(); } fileBrowser.setBrowser(browser); IPlayList playList = station.getPlayList(); fileBrowser.setPlayList(playList); plsBrowser.setPlayList(playList); chatServer = (IChatServer) server.find(ControlConstants.CHAT_ID, IChatServer.class); chat.setClientName(name); chat.setChatServer(chatServer); setPlayer(mPlayer); playerMenu.setPlayer(totemPlayer, mPlayer); controlMenu.setControl(station.getControl()); webcam.registerWebcamListener(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (RemoteException e) { e.printStackTrace(); } } /** * close connection from server, remove listeners. */ private void closeConnections() { try { if (this.mPlayer != null) this.mPlayer.removePlayerMessageListener(this.playerListener); } catch (Exception localException) { } try { this.chat.removeListener(); } catch (Exception localException1) { } try { Server.getServer().close(); } catch (Exception localException2) { } } @Override public void connectToServer(String registry) { connectToServer(registry, this.port, this.clientName); } public class DesktopPlayerListener implements IPlayerListener { public DesktopPlayerListener() { } public void playerMessage(PlayingBean playing) throws RemoteException { if (playing == null) return; System.out.println(playing.getTitle()); ControlFrame.this.setTitle(playing.getArtist() + " - " + playing.getTitle()); } } /** * listener to handle exit of the window, unregister listener from player * and chat server * * @author sebastian */ public class DesktopWindowListener extends WindowAdapter { public DesktopWindowListener() { } public void windowClosing(WindowEvent e) { super.windowClosing(e); try { if (ControlFrame.this.currentPlayer != null) ControlFrame.this.currentPlayer .removePlayerMessageListener(ControlFrame.this.playerListener); ControlFrame.this.chat.removeListener(); } catch (RemoteException e1) { e1.printStackTrace(); } - try { - ControlFrame.this.server.close(); - } catch (IOException e1) { - e1.printStackTrace(); - } + ControlFrame.this.server.close(); } } } \ No newline at end of file
true
false
null
null
diff --git a/src/test/java/javax/cache/DoNotUseTest.java b/src/test/java/javax/cache/DoNotUseTest.java index 3ec803e..247cbe1 100644 --- a/src/test/java/javax/cache/DoNotUseTest.java +++ b/src/test/java/javax/cache/DoNotUseTest.java @@ -1,195 +1,195 @@ /** * Copyright 2011 Terracotta, Inc. * Copyright 2011 Oracle, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package javax.cache; import junit.framework.Assert; import org.junit.Test; import javax.cache.implementation.RICache; /** * Unit tests to demonstrate some open decisions on semantics w.r.t. * storing null in key/value of a cache * * The open issues are * <ol> * <li>what is the behavior on attempting to read using key == null</li> * <li>what is the behavior when storing a null key</li> * <li>if storing a null value is allowed, what is the effect on get</li> * </ol> * The tests below should illustrate the options. * @author yannisc@gmail.com */ public class DoNotUseTest { /** * An attempt to get a value with key null causes a * NullPointerException */ @Test public void testGetNullKeyV1(){ Cache<Integer, String> cache = new RICache.Builder<Integer, String>(). setIgnoreNullKeyOnRead(false). build(); cache.start(); Integer key = null; try { cache.get(key); Assert.fail("get with key==null should throw NPE"); } catch (NullPointerException e) { // NPE as expected } } /** * An attempt to get a value with key null returns null. */ @Test public void testGetNullKeyV2(){ Cache<Integer, String> cache = new RICache.Builder<Integer, String>(). setIgnoreNullKeyOnRead(true). build(); cache.start(); Integer key = null; Assert.assertNull(cache.get(key)); } /** * An attempt to put using a null key causes a * NullPointerException */ @Test public void testPutNullKeyV1(){ Cache<Integer, String> cache = new RICache.Builder<Integer, String>(). setIgnoreNullKeyOnRead(true). build(); cache.start(); Integer key = null; String value = "v1"; try { cache.put(key, value); - Assert.fail("get with key==null should throw NPE"); + Assert.fail("put with key==null should throw NPE"); } catch (NullPointerException e) { // NPE as expected } } /** * An attempt to put using a null value causes a * NullPointerException */ @Test public void testPutNullValueV1(){ Cache<Integer, String> cache = new RICache.Builder<Integer, String>(). setAllowNullValue(false). build(); cache.start(); // we don't allow null in value Integer key = 1; try { cache.put(key, null); Assert.fail("put with value==null should throw NPE"); } catch (NullPointerException e) { // NPE as expected } Assert.assertFalse(cache.containsKey(key)); Assert.assertNull(cache.get(key)); } /** * An attempt to put using a null value stores the null */ @Test public void testPutNullValueV2(){ Cache<Integer, String> cache = new RICache.Builder<Integer, String>(). setAllowNullValue(true). build(); cache.start(); // We allow null in value Integer key = 1; cache.put(key, null); Assert.assertTrue(cache.containsKey(key)); Assert.assertNull(cache.get(key)); cache.remove(key); Assert.assertFalse(cache.containsKey(key)); Assert.assertNull(cache.get(key)); /* note: cache.get(key) == null can mean 1) there is no entry with key 2) there is an entry with key with value==null */ } /** * An attempt to put using a null value stores the null. * * This solution changes get to return Cache.Entry<K, V> rather than K. * For this test I use a private method {@link #get(Object, Cache)} which * stands in for a Cache.get returning Entry. */ @Test public void testPutNullValueV3(){ Cache<Integer, String> cache = new RICache.Builder<Integer, String>(). setAllowNullValue(true). build(); cache.start(); // We allow null in value, but get returns an entry Integer key = 1; cache.put(key, null); Assert.assertTrue(cache.containsKey(key)); Cache.Entry<Integer, String> entry = get(key, cache); Assert.assertEquals(key, entry.getKey()); Assert.assertNull(entry.getValue()); cache.remove(key); Assert.assertFalse(cache.containsKey(key)); Assert.assertNull(get(key, cache)); /* note: cache.get(key) == null can only mean 1) there is no entry with key */ } private <K,V> Cache.Entry<K, V> get(final K key, Cache<K, V> cache) { if (!cache.containsKey(key)) { return null; } else { final V value = cache.get(key); return new Cache.Entry<K, V>() { public K getKey() { return key; } public V getValue() { return value; } }; } } }
true
false
null
null
diff --git a/nuxeo-webengine-core/src/main/java/org/nuxeo/ecm/webengine/PathInfo.java b/nuxeo-webengine-core/src/main/java/org/nuxeo/ecm/webengine/PathInfo.java index a11a6d70..f4b56c00 100644 --- a/nuxeo-webengine-core/src/main/java/org/nuxeo/ecm/webengine/PathInfo.java +++ b/nuxeo-webengine-core/src/main/java/org/nuxeo/ecm/webengine/PathInfo.java @@ -1,222 +1,222 @@ /* * (C) Copyright 2006-2008 Nuxeo SAS (http://nuxeo.com/) and contributors. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 2.1 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * Contributors: * bstefanescu * * $Id$ */ package org.nuxeo.ecm.webengine; import org.nuxeo.common.utils.Path; import org.nuxeo.ecm.core.api.DocumentRef; import org.nuxeo.ecm.webengine.servlet.WebConst; import org.nuxeo.ecm.webengine.util.Attributes; /** * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a> * */ public class PathInfo { public static final Path EMPTY_PATH = new Path(""); public static final Path ROOT_PATH = new Path("/"); protected Path path; // original path (without action) protected Path applicationPath; // the application path protected Path traversalPath; // original path - application path protected Path trailingPath = EMPTY_PATH; // trailing segments that were not traversed protected String action; protected DocumentRef document; protected String script; protected Attributes attrs; public PathInfo(String path) { this (path, Attributes.EMPTY_ATTRS); } public PathInfo(String path, Attributes attrs) { if (path == null || path.length() == 0 || (path.length() == 1 && path.charAt(0) == '/')) { this.path = ROOT_PATH; } else { int p = path.lastIndexOf(WebConst.ACTION_SEPARATOR); if (p > -1) { action = path.substring(p+WebConst.ACTION_SEPARATOR.length()); path = path.substring(0, p); } this.path = new Path(path).makeAbsolute().removeTrailingSeparator(); } traversalPath = this.path; setAttributes(attrs); } public void setApplicationPath(Path appPath) { if (applicationPath != null) { throw new IllegalStateException("Application path already set"); } applicationPath = appPath; int cnt = appPath.segmentCount(); if (cnt > 0) { - traversalPath = path.removeFirstSegments(cnt); + traversalPath = path.removeFirstSegments(cnt).makeAbsolute(); } else { traversalPath = path; } } /** * @return the applicationPath. */ public Path getApplicationPath() { return applicationPath; } /** * @param attrs the attrs to set. */ public void setAttributes(Attributes attrs) { this.attrs = attrs == null ? Attributes.EMPTY_ATTRS : attrs; } /** * @return the path. */ public Path getPath() { return path; } /** * @param trailingPath the trailingPath to set. */ public void setTrailingPath(Path trailingPath) { this.trailingPath = trailingPath == null ? EMPTY_PATH : trailingPath.makeAbsolute(); } /** * @return the trailingPath. */ public Path getTrailingPath() { return trailingPath; } /** * @return the traversalPath. */ public Path getTraversalPath() { return traversalPath; } /** * @param script the script to set. */ public void setScript(String script) { this.script = script; } /** * @return the script. */ public String getScript() { return script; } /** * @param action the action to set. */ public void setAction(String action) { this.action = action; } /** * @return the action. */ public String getAction() { return action; } /** * @param root the root to set. */ public void setDocument(DocumentRef root) { this.document = root; } /** * @return the root. */ public DocumentRef getDocument() { return document; } /** * Tests whether this path info has a traversal path * (i.e. the traversal path contains at least one segment) * @return */ public boolean hasTraversalPath() { return traversalPath.segmentCount() > 0; } /** * Tests whether this path info has a traversal path * (i.e. the trailing path contains at least one segment) * @return */ public boolean hasTrailingPath() { return trailingPath.segmentCount() > 0; } /** * This pathInfo is empty (input path is either null, "" or "/") * @return true if this path info is empty false otherwise */ public boolean isEmpty() { return path.segmentCount() == 0; } /** * Tests whether this path info specify a document mapping * (i.e. the root property is a non empty string) * @return */ public boolean hasDocumentMapping() { return document != null; } /** * @return the attrs. */ public Attributes getAttributes() { return attrs; } @Override public String toString() { return path.toString() + " [traversal: " +traversalPath.toString()+"; trailing: " +trailingPath.toString()+"; root: "+document+"; script: "+script+"; action: "+action+"]"; } @Override public boolean equals(Object obj) { return path.equals(obj); } @Override public int hashCode() { return path.hashCode(); } }
true
false
null
null
diff --git a/src/org/jacorb/ir/InterfaceDef.java b/src/org/jacorb/ir/InterfaceDef.java index 119cd71e..eddadab6 100644 --- a/src/org/jacorb/ir/InterfaceDef.java +++ b/src/org/jacorb/ir/InterfaceDef.java @@ -1,985 +1,994 @@ package org.jacorb.ir; /* * JacORB - a free Java ORB * * Copyright (C) 1997-2002 Gerald Brose. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the Free * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ import org.jacorb.util.Debug; import java.lang.reflect.*; import java.io.*; import java.util.*; import org.omg.CORBA.IDLType; import org.omg.CORBA.ORB; import org.omg.CORBA.TypeCode; import org.omg.CORBA.InterfaceDefPackage.FullInterfaceDescription; import org.omg.CORBA.ContainerPackage.*; import org.omg.CORBA.OperationDescription; import org.omg.CORBA.AttributeDescription; import org.omg.CORBA.ConstantDescription; /** * JacORB implementation of org.omg.CORBA.InterfaceDef * * @author Gerald Brose - * @version $Id: InterfaceDef.java,v 1.10 2002-03-19 09:25:13 nicolas Exp $ + * @version $Id: InterfaceDef.java,v 1.11 2002-05-06 14:39:13 gerald Exp $ */ public class InterfaceDef extends org.jacorb.ir.Contained implements org.omg.CORBA.InterfaceDefOperations, ContainerType { protected static char fileSeparator = System.getProperty("file.separator").charAt(0); Class theClass; private Class helperClass; private Class signatureClass; private org.omg.CORBA.TypeCode typeCode; private OperationDef[] op_defs; private org.omg.CORBA.OperationDescription[] operations; + // to be done !! + private boolean is_abstract = false; + private AttributeDef[] att_defs; private org.omg.CORBA.AttributeDescription[] attributes; private ConstantDef[] constant_defs; private org.omg.CORBA.ConstantDescription[] constants; private org.omg.CORBA.InterfaceDef[] base_interfaces; private String [] base_names; private FullInterfaceDescription fullDescription; /** local references to contained objects */ private Hashtable containedLocals = new Hashtable(); /** CORBA references to contained objects */ private java.util.Hashtable contained = new java.util.Hashtable(); /* reference to my container as a contained object */ private org.omg.CORBA.Contained myContainer; private org.omg.CORBA.InterfaceDef myReference; private File my_dir; private Hashtable op = new Hashtable(); private Hashtable att = new Hashtable(); private Hashtable my_const = new Hashtable(); private org.omg.CORBA.Contained [] classes; private String path; private String [] class_names; private int size = 0; private boolean defined = false; private boolean loaded = false; private Class containedClass = null; private Class containerClass = null; /** * Class constructor */ InterfaceDef( Class c, Class helperClass, String path, org.omg.CORBA.Container def_in, org.omg.CORBA.Repository ir ) throws org.omg.CORBA.INTF_REPOS { Debug.myAssert( ir != null, "IR null!"); Debug.myAssert( def_in != null, "Defined?in null!"); def_kind = org.omg.CORBA.DefinitionKind.dk_Interface; containing_repository = ir; defined_in = def_in; if( def_in.equals(ir) ) myContainer = null; else myContainer = org.omg.CORBA.ContainedHelper.narrow( defined_in ); this.path = path; theClass = c; String classId = c.getName(); this.helperClass = helperClass; Hashtable irInfo= null; Class irHelperClass = null; try { irHelperClass = RepositoryImpl.loader.loadClass( theClass.getName() + "IRHelper"); irInfo = (Hashtable)irHelperClass.getDeclaredField("irInfo").get(null); } catch( ClassNotFoundException e ) { org.jacorb.util.Debug.output(1, "!! No IR helper class for interface " + theClass.getName()); } catch( Exception e ) { e.printStackTrace(); } Debug.myAssert( irInfo != null, "IR Info null!"); try { containedClass = RepositoryImpl.loader.loadClass("org.omg.CORBA.Contained"); signatureClass = RepositoryImpl.loader.loadClass(classId + "Operations"); id( (String)helperClass.getDeclaredMethod("id", null).invoke( null, null ) ); version( id().substring( id().lastIndexOf(':'))); typeCode = TypeCodeUtil.getTypeCode( c, null ); full_name = classId.replace('.', '/'); if( classId.indexOf('.') > 0 ) { name = classId.substring( classId.lastIndexOf('.')+1); Debug.myAssert( defined_in != null, "InterfaceDef " + name + " path " + path + " has no defined_in repository"); if( containedClass.isAssignableFrom( defined_in.getClass() )) absolute_name = ( myContainer != null ? myContainer.absolute_name() : "Global" ) + "::" + name; else absolute_name = "::" + name; } else { name = classId; defined_in = containing_repository; absolute_name = "::" + name; } org.jacorb.util.Debug.output(2, "InterfaceDef: " + absolute_name + " path: " + path); /* get directory for nested definitions' classes */ File f = new File( path + fileSeparator + classId.replace('.', fileSeparator) + "Package" ); if( f.exists() && f.isDirectory() ) my_dir = f; } catch ( Exception e ) { e.printStackTrace(); throw new org.omg.CORBA.INTF_REPOS( ErrorMsg.IR_Not_Implemented, org.omg.CORBA.CompletionStatus.COMPLETED_NO); } } public void loadContents() { org.jacorb.util.Debug.output(2, "Interface " +name+ " loading... "); // read from the interface class (operations and atributes) Debug.myAssert( getReference() != null, "my own ref null"); myReference = org.omg.CORBA.InterfaceDefHelper.narrow( getReference()); Debug.myAssert( myReference != null, "narrow failed for " + getReference() ); /* load nested definitions from interfacePackage directory */ String[] classes = null; if( my_dir != null ) { classes = my_dir.list( new IRFilenameFilter(".class") ); // load class files in this interface's Package directory if( classes != null) { for( int j = 0; j< classes.length; j++ ) { try { org.jacorb.util.Debug.output(2, "Interface " +name+ " tries " + full_name.replace('.', fileSeparator) + "Package" + fileSeparator + classes[j].substring( 0, classes[j].indexOf(".class")) ); ClassLoader loader = getClass().getClassLoader(); if( loader == null ) { loader = RepositoryImpl.loader; } Class cl = loader.loadClass( ( full_name.replace('.', fileSeparator) + "Package" + fileSeparator + classes[j].substring( 0, classes[j].indexOf(".class")) ).replace( fileSeparator, '/') ); Contained containedObject = Contained.createContained( cl, path, myReference, containing_repository ); if( containedObject == null ) continue; org.omg.CORBA.Contained containedRef = Contained.createContainedReference(containedObject); containedRef.move( myReference, containedRef.name(), containedRef.version() ); org.jacorb.util.Debug.output(2, "Interface " + full_name + " loads "+ containedRef.name() ); contained.put( containedRef.name() , containedRef ); containedLocals.put( containedRef.name(), containedObject ); if( containedObject instanceof ContainerType ) ((ContainerType)containedObject).loadContents(); } catch ( Exception e ) { e.printStackTrace(); } } } } loaded = true; org.jacorb.util.Debug.output(2, "Interface " + name + " loaded ]"); } void define() { Debug.myAssert( loaded, "Interface " + name + " not loaded!"); org.jacorb.util.Debug.output(2, "Interface " + name + " defining... ]"); org.jacorb.util.Debug.output(2, "Interface " +name+ " loads attributes/ops"); Vector ops = new Vector(); Vector atts = new Vector(); Hashtable irInfo= null; Class irHelperClass = null; try { irHelperClass = RepositoryImpl.loader.loadClass( theClass.getName() + "IRHelper"); irInfo = (Hashtable)irHelperClass.getDeclaredField("irInfo").get(null); } catch( ClassNotFoundException e ) { org.jacorb.util.Debug.output(1, "!! No IR helper class for interface " + theClass.getName()); } catch( Exception e ) { e.printStackTrace(); } Method methods[] = signatureClass.getDeclaredMethods(); for( int i = 0; i < methods.length; i++ ) { Object value = irInfo.get(methods[i].getName()); if( value == null || !((String)value).startsWith("attribute")) { ops.addElement( new OperationDef( methods[i], theClass, irHelperClass, myReference )); } else { if( ((String)value).startsWith("attribute") ) { String attrDescr = (String)value; if( methods[i].getReturnType() == Void.class ) continue; int idx = attrDescr.indexOf('-'); String attrTypeName = attrDescr.substring( attrDescr.indexOf(";")+1); atts.addElement( new AttributeDef( methods[i], attrTypeName, ( idx > 0 ? org.omg.CORBA.AttributeMode.ATTR_NORMAL : org.omg.CORBA.AttributeMode.ATTR_READONLY ), myReference, containing_repository )); } } } org.jacorb.util.Debug.output(2, "Interface " +name+ " defines ops"); op_defs = new OperationDef[ ops.size() ]; ops.copyInto( op_defs ); for( int i = 0; i < op_defs.length; i++ ) { op_defs[i].move( myReference , op_defs[i].name(), version ); containedLocals.put( op_defs[i].name(), op_defs[i] ); try { org.omg.CORBA.OperationDef operationRef = org.omg.CORBA.OperationDefHelper.narrow( RepositoryImpl.poa.servant_to_reference( new org.omg.CORBA.OperationDefPOATie( op_defs[i] ))); contained.put( op_defs[i].name(), operationRef ) ; op_defs[i].setReference(operationRef); } catch( Exception e ) { e.printStackTrace(); } } org.jacorb.util.Debug.output(2, "Interface " +name+ " defines attributes"); att_defs = new AttributeDef[ atts.size() ]; atts.copyInto( att_defs ); for( int i = 0; i < att_defs.length; i++ ) { att_defs[i].move( myReference , att_defs[i].name(), version ); containedLocals.put( att_defs[i].name(), att_defs[i] ); try { org.omg.CORBA.AttributeDef attribute = org.omg.CORBA.AttributeDefHelper.narrow( RepositoryImpl.poa.servant_to_reference( new org.omg.CORBA.AttributeDefPOATie( att_defs[i] ))); contained.put( att_defs[i].name(), attribute ); att_defs[i].setReference( attribute ); } catch( Exception e ) { e.printStackTrace(); } } /* constants */ org.jacorb.util.Debug.output(2, "Interface " + name + " defines constants"); Field[] fields = theClass.getDeclaredFields(); constant_defs = new ConstantDef[ fields.length ]; for( int i = 0; i < constant_defs.length; i++ ) { constant_defs[i] = new ConstantDef( fields[i], myReference, containing_repository ); constant_defs[i].move( myReference , constant_defs[i].name(), version ); containedLocals.put( constant_defs[i].name(), constant_defs[i] ); try { org.omg.CORBA.ConstantDef constRef = org.omg.CORBA.ConstantDefHelper.narrow( RepositoryImpl.poa.servant_to_reference( new org.omg.CORBA.ConstantDefPOATie( constant_defs[i] ))); contained.put( constant_defs[i].name(), constRef ) ; constant_defs[i].setReference(constRef); } catch( Exception e ) { e.printStackTrace(); } } for( Enumeration e = containedLocals.elements(); e.hasMoreElements(); ((IRObject)e.nextElement()).define()) ; /* get base interfaces */ Class class_interfaces [] = theClass.getInterfaces(); Hashtable si = new Hashtable(); Class objectClass = null; try { objectClass = RepositoryImpl.loader.loadClass( "org.omg.CORBA.Object"); } catch( ClassNotFoundException cnfe ) {} for( int i = 0; i < class_interfaces.length; i++ ) { if( objectClass.isAssignableFrom( class_interfaces[i] ) && !class_interfaces[i].getName().equals("org.omg.CORBA.Object") ) { si.put( class_interfaces[i], ""); } } Enumeration e = si.keys(); base_names = new String[ si.size() ]; int i = 0; Vector v = new Vector(); while( e.hasMoreElements() ) { try { Class baseClass = (Class)e.nextElement(); base_names[i] = baseClass.getName(); Class helperClass = RepositoryImpl.loader.loadClass( base_names[i] + "Helper"); String baseId = (String)helperClass.getDeclaredMethod( "id", null).invoke(null,null); org.omg.CORBA.InterfaceDef base_interface = org.omg.CORBA.InterfaceDefHelper.narrow( containing_repository.lookup_id( baseId )); if( base_interface == null ) { org.jacorb.util.Debug.output( 1, "Base interface def " + baseId + " is null!!!"); } else { v.addElement( base_interface ); } i++; } catch( Exception exc ) { exc.printStackTrace(); } } base_interfaces = new org.omg.CORBA.InterfaceDef[ v.size() ]; v.copyInto( base_interfaces ); defined = true; org.jacorb.util.Debug.output(2, "Interface " + name + " defined ]"); } public boolean is_abstract() { return false; } public void is_abstract(boolean arg) { } /** * @returns an array containing interface definitions of the superclass and * the interfaces extended by this class. Has length 0 if this class * is Object. */ public org.omg.CORBA.InterfaceDef[] base_interfaces() { return base_interfaces; } public FullInterfaceDescription describe_interface() { Debug.myAssert( defined, "InterfaceDef " + name + " not defined."); if( fullDescription == null ) { String def_in = "IDL:Global:1.0"; if( defined_in instanceof org.omg.CORBA.Contained ) def_in = ((org.omg.CORBA.Contained)defined_in).id(); /* before assembling descriptions, get hold of all super types' FullInterfaceDescriptions */ FullInterfaceDescription [] baseDescriptions = new FullInterfaceDescription[ base_interfaces().length ]; for( int b = 0; b < base_interfaces.length; b++ ) { baseDescriptions[b] = base_interfaces[b].describe_interface(); } /* build operation descriptions */ Hashtable ops = new Hashtable(); for( int c = 0; c < op_defs.length; c++ ) { OperationDescription operation = op_defs[c].describe_operation(); ops.put( operation.name, operation ); } /* get operation descriptions from super types, potentially duplicate descriptions due to diamond inheritance are removed by hashing */ for( int baseOps = 0; baseOps < baseDescriptions.length; baseOps++ ) { for( int bbaseOps = 0; bbaseOps < baseDescriptions[baseOps].operations.length; bbaseOps++ ) { OperationDescription base_op = baseDescriptions[baseOps].operations[bbaseOps]; if( !ops.containsKey( base_op.name )) ops.put( base_op.name, base_op ); } } operations = new OperationDescription[ ops.size() ]; int opsCount = 0; for( Enumeration e = ops.elements(); e.hasMoreElements(); opsCount++ ) { operations[ opsCount ] = (OperationDescription)e.nextElement(); } ops.clear(); /* build attribute descriptions */ Hashtable atts = new Hashtable(); for( int a = 0; a < att_defs.length; a++ ) { AttributeDescription att = att_defs[a].describe_attribute(); atts.put( att.name, att ); } /* get attribute descriptions from super types */ for( int baseAtts = 0; baseAtts < baseDescriptions.length; baseAtts++ ) { for( int bbaseAtts = 0; bbaseAtts < baseDescriptions[ baseAtts ].attributes.length; bbaseAtts++ ) { AttributeDescription base_att = baseDescriptions[ baseAtts ].attributes[ bbaseAtts ]; if( !atts.containsKey( base_att.name )) atts.put( base_att.name, base_att ); } } attributes = new AttributeDescription[ atts.size() ]; int attsCount = 0; for( Enumeration e = atts.elements(); e.hasMoreElements(); attsCount++ ) { attributes[ attsCount ] = (AttributeDescription)e.nextElement(); } atts.clear(); /* build constant descriptions */ constants = new org.omg.CORBA.ConstantDescription[ constant_defs.length ]; for( int b = 0; b < constant_defs.length; b++ ) { constants[b] = constant_defs[b].describe_constant(); } Debug.myAssert( operations != null, "operations null!"); Debug.myAssert( attributes != null, "attributes null!"); fullDescription = - new FullInterfaceDescription( name, id, def_in, version, - operations, attributes, base_names, - typeCode, false ); + new FullInterfaceDescription( name, + id, + def_in, + version, + is_abstract, + operations, + attributes, + base_names, + typeCode ); } return fullDescription; } public boolean is_a( String interface_id ) { Debug.output( 2, "Is interface " + id() + " a " + interface_id + "?" ); if( id().equals( interface_id )) return true; org.omg.CORBA.InterfaceDef[] bases = base_interfaces(); for( int i = 0; i < bases.length; i++ ) { if( bases[i].is_a( interface_id )) return true; if( bases[i].id().equals("IDL:omg.org/CORBA/Object:1.0")) continue; } Debug.output( 2, "Interface " + id() + " is not a " + interface_id ); return false; } // write methods on an InterfaceDef, // these are not supported at the moment !! public void base_interfaces( org.omg.CORBA.InterfaceDef[] a ) { throw new org.omg.CORBA.INTF_REPOS(ErrorMsg.IR_Not_Implemented, org.omg.CORBA.CompletionStatus.COMPLETED_NO); } public org.omg.CORBA.AttributeDef create_attribute( String id, String name, String version, IDLType type, org.omg.CORBA.AttributeMode mode ) { throw new org.omg.CORBA.INTF_REPOS( ErrorMsg.IR_Not_Implemented, org.omg.CORBA.CompletionStatus.COMPLETED_NO); } public org.omg.CORBA.OperationDef create_operation( String id, String name, String version, org.omg.CORBA.IDLType result, org.omg.CORBA.OperationMode mode, org.omg.CORBA.ParameterDescription[] params, org.omg.CORBA.ExceptionDef[] exceptions, String[] contexts ) { throw new org.omg.CORBA.INTF_REPOS( ErrorMsg.IR_Not_Implemented, org.omg.CORBA.CompletionStatus.COMPLETED_NO); } // from org.omg.CORBA.Container public org.omg.CORBA.Contained lookup( String scopedname ) { org.jacorb.util.Debug.output(2,"Interface " + this.name + " lookup " + scopedname ); String top_level_name; String rest_of_name; String name; if( scopedname.startsWith("::") ) { name = scopedname.substring(2); } else name = scopedname; if( name.indexOf("::") > 0 ) { top_level_name = name.substring( 0, name.indexOf("::") ); rest_of_name = name.substring( name.indexOf("::") + 2); } else { top_level_name = name; rest_of_name = null; } try { org.omg.CORBA.Contained top = (org.omg.CORBA.Contained)contained.get( top_level_name ); if( top == null ) { org.jacorb.util.Debug.output(2,"Interface " + this.name + " top " + top_level_name + " not found "); return null; } if( rest_of_name == null ) { return top; } else { if( top instanceof org.omg.CORBA.Container) { return ((org.omg.CORBA.Container)top).lookup( rest_of_name ); } else { org.jacorb.util.Debug.output(2,"Interface " + this.name + " " + scopedname + " not found "); return null; } } } catch( Exception e ) { e.printStackTrace(); return null; } } public org.omg.CORBA.Contained[] contents(org.omg.CORBA.DefinitionKind limit_type, boolean exclude_inherited) { Debug.myAssert( defined, "InterfaceDef " + name + " not defined."); Hashtable limited = new Hashtable(); // analog constants, exceptions etc. for( Enumeration e = contained.elements(); e.hasMoreElements(); ) { org.omg.CORBA.Contained c = (org.omg.CORBA.Contained)e.nextElement(); if( limit_type.value() == org.omg.CORBA.DefinitionKind._dk_all || limit_type.value() == c.def_kind().value() ) { limited.put( c, "" ); } } org.omg.CORBA.Contained[] c = new org.omg.CORBA.Contained[limited.size()]; int i; Enumeration e; for( e = limited.keys(), i=0 ; e.hasMoreElements(); i++ ) c[i] = (org.omg.CORBA.Contained)e.nextElement(); return c; } public org.omg.CORBA.Contained[] lookup_name(String search_name, int levels_to_search, org.omg.CORBA.DefinitionKind limit_type, boolean exclude_inherited) { if( levels_to_search == 0 ) return null; org.omg.CORBA.Contained[] c = contents( limit_type, exclude_inherited ); Hashtable found = new Hashtable(); for( int i = 0; i < c.length; i++) if( c[i].name().equals( search_name ) ) found.put( c[i], "" ); if( levels_to_search > 1 || levels_to_search < 0 ) { // search up to a specific depth or indefinitely for( int i = 0; i < c.length; i++) { if( c[i] instanceof org.omg.CORBA.Container ) { org.omg.CORBA.Contained[] tmp_seq = ((org.omg.CORBA.Container)c[i]).lookup_name( search_name, levels_to_search-1, limit_type, exclude_inherited); if( tmp_seq != null ) for( int j = 0; j < tmp_seq.length; j++) found.put( tmp_seq[j], "" ); } } } org.omg.CORBA.Contained[] result = new org.omg.CORBA.Contained[ found.size() ]; int idx = 0; for( Enumeration e = found.keys(); e.hasMoreElements(); ) result[ idx++] = (org.omg.CORBA.Contained)e.nextElement(); return result; } public Description[] describe_contents(org.omg.CORBA.DefinitionKind limit_type, boolean exclude_inherited, int max_returned_objs) { return null; } // write interface not supported! public org.omg.CORBA.ModuleDef create_module( String id, String name, String version) { return null; } public org.omg.CORBA.ConstantDef create_constant( /*RepositoryId*/ String id, /*Identifier*/ String name, /*VersionSpec*/ String version, IDLType type, org.omg.CORBA.Any value) { return null; } public org.omg.CORBA.StructDef create_struct(/*RepositoryId*/ String id, /*Identifier*/ String name, /*VersionSpec*/ String version, /*StructMemberSeq*/ org.omg.CORBA.StructMember[] members) { return null; } public org.omg.CORBA.UnionDef create_union( /*RepositoryId*/ String id, /*Identifier*/ String name, /*VersionSpec*/ String version, org.omg.CORBA.IDLType discriminator_type, /*UnionMemberSeq*/ org.omg.CORBA.UnionMember[] members) { return null; } public org.omg.CORBA.EnumDef create_enum(/*RepositoryId*/ String id, /*Identifier*/ String name, /*VersionSpec*/ String version, /*EnumMemberSeq*/ /*Identifier*/ String[] members) { return null; } public org.omg.CORBA.AliasDef create_alias(/*RepositoryId*/ String id, /*Identifier*/ String name, /*VersionSpec*/ String version, org.omg.CORBA.IDLType original_type) { return null; } /** * not supported */ public org.omg.CORBA.ExceptionDef create_exception(String id, String name , String version, org.omg.CORBA.StructMember[] member ) { return null; } /** * not supported */ public org.omg.CORBA.InterfaceDef create_interface(/*RepositoryId*/ String id, /*Identifier*/ String name, /*VersionSpec*/ String version, /*InterfaceDefSeq*/ org.omg.CORBA.InterfaceDef[] base_interfaces, boolean is_abstract ) { return null; } /** * not supported */ public org.omg.CORBA.ValueBoxDef create_value_box(String id, String name, String version, org.omg.CORBA.IDLType type) { return null; } /** * not supported */ public org.omg.CORBA.ValueDef create_value(String id, String name, String version, boolean is_custom, boolean is_abstract, org.omg.CORBA.ValueDef base_value, boolean is_truncatable, org.omg.CORBA.ValueDef[] abstract_base_values, org.omg.CORBA.InterfaceDef[] supported_interfaces, org.omg.CORBA.Initializer[] initializers) { return null; } /** * not supported */ public org.omg.CORBA.NativeDef create_native(String id, String name, String version) { return null; } // from Contained public org.omg.CORBA.ContainedPackage.Description describe() { Debug.myAssert( defined, "InterfaceDef " + name + " not defined."); org.omg.CORBA.Any a = orb.create_any(); String def_in = null; if( myContainer != null ) def_in = "Global"; else def_in = myContainer.id(); org.omg.CORBA.InterfaceDescriptionHelper.insert( a, new org.omg.CORBA.InterfaceDescription( name, id, def_in, version, base_names, false ) ); return new org.omg.CORBA.ContainedPackage.Description( org.omg.CORBA.DefinitionKind.dk_Interface, a); } // from IRObject public void destroy() { containedLocals.clear(); contained.clear(); } // from IDLType public org.omg.CORBA.TypeCode type() { return typeCode; } }
false
false
null
null
diff --git a/src/main/java/org/tal/basiccircuits/nand.java b/src/main/java/org/tal/basiccircuits/nand.java index 2ed1c70..68c3dc1 100644 --- a/src/main/java/org/tal/basiccircuits/nand.java +++ b/src/main/java/org/tal/basiccircuits/nand.java @@ -1,25 +1,26 @@ package org.tal.basiccircuits; import org.tal.redstonechips.circuit.BitSetCircuit; import org.tal.redstonechips.util.BitSet7; /** * * @author Tal Eisenberg */ public class nand extends BitSetCircuit { @Override protected void bitSetChanged(int bitSetidx, BitSet7 set) { BitSet7 out = (BitSet7)inputBitSets[0].clone(); for (int i=1; i<this.inputBitSets.length; i++) { out.and(inputBitSets[i]); - out.flip(0, wordlength); } + + out.flip(0, wordlength); this.sendBitSet(out); } }
false
false
null
null
diff --git a/src/org/mozilla/javascript/Parser.java b/src/org/mozilla/javascript/Parser.java index 6c63c47a..52331e6c 100644 --- a/src/org/mozilla/javascript/Parser.java +++ b/src/org/mozilla/javascript/Parser.java @@ -1,3766 +1,3767 @@ /* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Mike Ang * Igor Bukanov * Yuh-Ruey Chen * Ethan Hugg * Bob Jervis * Terry Lucas * Mike McCabe * Milen Nankov * Norris Boyd * Steve Yegge * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript; import org.mozilla.javascript.ast.*; // we use basically every class import java.io.BufferedReader; import java.io.IOException; import java.io.Reader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.HashSet; /** * This class implements the JavaScript parser.<p> * * It is based on the SpiderMonkey C source files jsparse.c and jsparse.h in the * jsref package.<p> * * The parser generates an {@link AstRoot} parse tree representing the source * code. No tree rewriting is permitted at this stage, so that the parse tree * is a faithful representation of the source for frontend processing tools and * IDEs.<p> * * This parser implementation is not intended to be reused after a parse * finishes, and will throw an IllegalStateException() if invoked again.<p> * * @see TokenStream * * @author Mike McCabe * @author Brendan Eich */ public class Parser { /** * Maximum number of allowed function or constructor arguments, * to follow SpiderMonkey. */ public static final int ARGC_LIMIT = 1 << 16; // TokenInformation flags : currentFlaggedToken stores them together // with token type final static int CLEAR_TI_MASK = 0xFFFF, // mask to clear token information bits TI_AFTER_EOL = 1 << 16, // first token of the source line TI_CHECK_LABEL = 1 << 17; // indicates to check for label CompilerEnvirons compilerEnv; private ErrorReporter errorReporter; private IdeErrorReporter errorCollector; private String sourceURI; private char[] sourceChars; boolean calledByCompileFunction; // ugly - set directly by Context private boolean parseFinished; // set when finished to prevent reuse private TokenStream ts; private int currentFlaggedToken = Token.EOF; private int currentToken; private int syntaxErrorCount; private List<Comment> scannedComments; private String currentJsDocComment; protected int nestingOfFunction; private LabeledStatement currentLabel; private boolean inDestructuringAssignment; protected boolean inUseStrictDirective; // The following are per function variables and should be saved/restored // during function parsing. See PerFunctionVariables class below. ScriptNode currentScriptOrFn; Scope currentScope; private int endFlags; private boolean inForInit; // bound temporarily during forStatement() private Map<String,LabeledStatement> labelSet; private List<Loop> loopSet; private List<Jump> loopAndSwitchSet; // end of per function variables // Lacking 2-token lookahead, labels become a problem. // These vars store the token info of the last matched name, // iff it wasn't the last matched token. private int prevNameTokenStart; private String prevNameTokenString = ""; private int prevNameTokenLineno; // Exception to unwind private static class ParserException extends RuntimeException { static final long serialVersionUID = 5882582646773765630L; } public Parser() { this(new CompilerEnvirons()); } public Parser(CompilerEnvirons compilerEnv) { this(compilerEnv, compilerEnv.getErrorReporter()); } public Parser(CompilerEnvirons compilerEnv, ErrorReporter errorReporter) { this.compilerEnv = compilerEnv; this.errorReporter = errorReporter; if (errorReporter instanceof IdeErrorReporter) { errorCollector = (IdeErrorReporter)errorReporter; } } // Add a strict warning on the last matched token. void addStrictWarning(String messageId, String messageArg) { int beg = -1, end = -1; if (ts != null) { beg = ts.tokenBeg; end = ts.tokenEnd - ts.tokenBeg; } addStrictWarning(messageId, messageArg, beg, end); } void addStrictWarning(String messageId, String messageArg, int position, int length) { if (compilerEnv.isStrictMode()) addWarning(messageId, messageArg, position, length); } void addWarning(String messageId, String messageArg) { int beg = -1, end = -1; if (ts != null) { beg = ts.tokenBeg; end = ts.tokenEnd - ts.tokenBeg; } addWarning(messageId, messageArg, beg, end); } void addWarning(String messageId, int position, int length) { addWarning(messageId, null, position, length); } void addWarning(String messageId, String messageArg, int position, int length) { String message = lookupMessage(messageId, messageArg); if (compilerEnv.reportWarningAsError()) { addError(messageId, messageArg, position, length); } else if (errorCollector != null) { errorCollector.warning(message, sourceURI, position, length); } else { errorReporter.warning(message, sourceURI, ts.getLineno(), ts.getLine(), ts.getOffset()); } } void addError(String messageId) { addError(messageId, ts.tokenBeg, ts.tokenEnd - ts.tokenBeg); } void addError(String messageId, int position, int length) { addError(messageId, null, position, length); } void addError(String messageId, String messageArg) { addError(messageId, messageArg, ts.tokenBeg, ts.tokenEnd - ts.tokenBeg); } void addError(String messageId, String messageArg, int position, int length) { ++syntaxErrorCount; String message = lookupMessage(messageId, messageArg); if (errorCollector != null) { errorCollector.error(message, sourceURI, position, length); } else { int lineno = 1, offset = 1; String line = ""; if (ts != null) { // happens in some regression tests lineno = ts.getLineno(); line = ts.getLine(); offset = ts.getOffset(); } errorReporter.error(message, sourceURI, lineno, line, offset); } } String lookupMessage(String messageId) { return lookupMessage(messageId, null); } String lookupMessage(String messageId, String messageArg) { return messageArg == null ? ScriptRuntime.getMessage0(messageId) : ScriptRuntime.getMessage1(messageId, messageArg); } void reportError(String messageId) { reportError(messageId, null); } void reportError(String messageId, String messageArg) { if (ts == null) { // happens in some regression tests reportError(messageId, messageArg, 1, 1); } else { reportError(messageId, messageArg, ts.tokenBeg, ts.tokenEnd - ts.tokenBeg); } } void reportError(String messageId, int position, int length) { reportError(messageId, null, position, length); } void reportError(String messageId, String messageArg, int position, int length) { addError(messageId, position, length); if (!compilerEnv.recoverFromErrors()) { throw new ParserException(); } } // Computes the absolute end offset of node N. // Use with caution! Assumes n.getPosition() is -absolute-, which // is only true before the node is added to its parent. private int getNodeEnd(AstNode n) { return n.getPosition() + n.getLength(); } private void recordComment(int lineno) { if (scannedComments == null) { scannedComments = new ArrayList<Comment>(); } String comment = ts.getAndResetCurrentComment(); if (ts.commentType == Token.CommentType.JSDOC && compilerEnv.isRecordingLocalJsDocComments()) { currentJsDocComment = comment; } Comment commentNode = new Comment(ts.tokenBeg, ts.getTokenLength(), ts.commentType, comment); commentNode.setLineno(lineno); scannedComments.add(commentNode); } private String getAndResetJsDoc() { String saved = currentJsDocComment; currentJsDocComment = null; return saved; } // Returns the next token without consuming it. // If previous token was consumed, calls scanner to get new token. // If previous token was -not- consumed, returns it (idempotent). // // This function will not return a newline (Token.EOL - instead, it // gobbles newlines until it finds a non-newline token, and flags // that token as appearing just after a newline. // // This function will also not return a Token.COMMENT. Instead, it // records comments in the scannedComments list. If the token // returned by this function immediately follows a jsdoc comment, // the token is flagged as such. // // Note that this function always returned the un-flagged token! // The flags, if any, are saved in currentFlaggedToken. private int peekToken() throws IOException { // By far the most common case: last token hasn't been consumed, // so return already-peeked token. if (currentFlaggedToken != Token.EOF) { return currentToken; } int lineno = ts.getLineno(); int tt = ts.getToken(); boolean sawEOL = false; // process comments and whitespace while (tt == Token.EOL || tt == Token.COMMENT) { if (tt == Token.EOL) { lineno++; sawEOL = true; } else { if (compilerEnv.isRecordingComments()) { recordComment(lineno); } } tt = ts.getToken(); } currentToken = tt; currentFlaggedToken = tt | (sawEOL ? TI_AFTER_EOL : 0); return currentToken; // return unflagged token } private int peekFlaggedToken() throws IOException { peekToken(); return currentFlaggedToken; } private void consumeToken() { currentFlaggedToken = Token.EOF; } private int nextToken() throws IOException { int tt = peekToken(); consumeToken(); return tt; } private int nextFlaggedToken() throws IOException { peekToken(); int ttFlagged = currentFlaggedToken; consumeToken(); return ttFlagged; } private boolean matchToken(int toMatch) throws IOException { if (peekToken() != toMatch) { return false; } consumeToken(); return true; } // Returns Token.EOL if the current token follows a newline, else returns // the current token. Used in situations where we don't consider certain // token types valid if they are preceded by a newline. One example is the // postfix ++ or -- operator, which has to be on the same line as its // operand. private int peekTokenOrEOL() throws IOException { int tt = peekToken(); // Check for last peeked token flags if ((currentFlaggedToken & TI_AFTER_EOL) != 0) { tt = Token.EOL; } return tt; } private boolean mustMatchToken(int toMatch, String messageId) throws IOException { return mustMatchToken(toMatch, messageId, ts.tokenBeg, ts.tokenEnd - ts.tokenBeg); } private boolean mustMatchToken(int toMatch, String msgId, int pos, int len) throws IOException { if (matchToken(toMatch)) { return true; } reportError(msgId, pos, len); return false; } private void mustHaveXML() { if (!compilerEnv.isXmlAvailable()) { reportError("msg.XML.not.available"); } } public boolean eof() { return ts.eof(); } boolean insideFunction() { return nestingOfFunction != 0; } void pushScope(Scope scope) { Scope parent = scope.getParentScope(); // During codegen, parent scope chain may already be initialized, // in which case we just need to set currentScope variable. if (parent != null) { if (parent != currentScope) codeBug(); } else { currentScope.addChildScope(scope); } currentScope = scope; } void popScope() { currentScope = currentScope.getParentScope(); } private void enterLoop(Loop loop) { if (loopSet == null) loopSet = new ArrayList<Loop>(); loopSet.add(loop); if (loopAndSwitchSet == null) loopAndSwitchSet = new ArrayList<Jump>(); loopAndSwitchSet.add(loop); pushScope(loop); if (currentLabel != null) { currentLabel.setStatement(loop); currentLabel.getFirstLabel().setLoop(loop); // This is the only time during parsing that we set a node's parent // before parsing the children. In order for the child node offsets // to be correct, we adjust the loop's reported position back to an // absolute source offset, and restore it when we call exitLoop(). loop.setRelative(-currentLabel.getPosition()); } } private void exitLoop() { Loop loop = loopSet.remove(loopSet.size() - 1); loopAndSwitchSet.remove(loopAndSwitchSet.size() - 1); if (loop.getParent() != null) { // see comment in enterLoop loop.setRelative(loop.getParent().getPosition()); } popScope(); } private void enterSwitch(SwitchStatement node) { if (loopAndSwitchSet == null) loopAndSwitchSet = new ArrayList<Jump>(); loopAndSwitchSet.add(node); } private void exitSwitch() { loopAndSwitchSet.remove(loopAndSwitchSet.size() - 1); } /** * Builds a parse tree from the given source string. * * @return an {@link AstRoot} object representing the parsed program. If * the parse fails, {@code null} will be returned. (The parse failure will * result in a call to the {@link ErrorReporter} from * {@link CompilerEnvirons}.) */ public AstRoot parse(String sourceString, String sourceURI, int lineno) { if (parseFinished) throw new IllegalStateException("parser reused"); this.sourceURI = sourceURI; if (compilerEnv.isIdeMode()) { this.sourceChars = sourceString.toCharArray(); } this.ts = new TokenStream(this, null, sourceString, lineno); try { return parse(); } catch (IOException iox) { // Should never happen throw new IllegalStateException(); } finally { parseFinished = true; } } /** * Builds a parse tree from the given sourcereader. * @see #parse(String,String,int) * @throws IOException if the {@link Reader} encounters an error */ public AstRoot parse(Reader sourceReader, String sourceURI, int lineno) throws IOException { if (parseFinished) throw new IllegalStateException("parser reused"); if (compilerEnv.isIdeMode()) { return parse(readFully(sourceReader), sourceURI, lineno); } try { this.sourceURI = sourceURI; ts = new TokenStream(this, sourceReader, null, lineno); return parse(); } finally { parseFinished = true; } } private AstRoot parse() throws IOException { int pos = 0; AstRoot root = new AstRoot(pos); currentScope = currentScriptOrFn = root; int baseLineno = ts.lineno; // line number where source starts int end = pos; // in case source is empty boolean inDirectivePrologue = true; boolean savedStrictMode = inUseStrictDirective; // TODO: eval code should get strict mode from invoking code inUseStrictDirective = false; try { for (;;) { int tt = peekToken(); if (tt <= Token.EOF) { break; } AstNode n; if (tt == Token.FUNCTION) { consumeToken(); try { n = function(calledByCompileFunction ? FunctionNode.FUNCTION_EXPRESSION : FunctionNode.FUNCTION_STATEMENT); } catch (ParserException e) { break; } } else { n = statement(); if (inDirectivePrologue) { String directive = getDirective(n); if (directive == null) { inDirectivePrologue = false; } else if (directive.equals("use strict")) { inUseStrictDirective = true; root.setInStrictMode(true); } } } end = getNodeEnd(n); root.addChildToBack(n); n.setParent(root); } } catch (StackOverflowError ex) { String msg = lookupMessage("msg.too.deep.parser.recursion"); if (!compilerEnv.isIdeMode()) throw Context.reportRuntimeError(msg, sourceURI, ts.lineno, null, 0); } finally { inUseStrictDirective = savedStrictMode; } if (this.syntaxErrorCount != 0) { String msg = String.valueOf(this.syntaxErrorCount); msg = lookupMessage("msg.got.syntax.errors", msg); if (!compilerEnv.isIdeMode()) throw errorReporter.runtimeError(msg, sourceURI, baseLineno, null, 0); } // add comments to root in lexical order if (scannedComments != null) { // If we find a comment beyond end of our last statement or // function, extend the root bounds to the end of that comment. int last = scannedComments.size() - 1; end = Math.max(end, getNodeEnd(scannedComments.get(last))); for (Comment c : scannedComments) { root.addComment(c); } } root.setLength(end - pos); root.setSourceName(sourceURI); root.setBaseLineno(baseLineno); root.setEndLineno(ts.lineno); return root; } private AstNode parseFunctionBody() throws IOException { if (!matchToken(Token.LC)) { if (compilerEnv.getLanguageVersion() < Context.VERSION_1_8) { reportError("msg.no.brace.body"); } return parseFunctionBodyExpr(); } ++nestingOfFunction; int pos = ts.tokenBeg; Block pn = new Block(pos); // starts at LC position boolean inDirectivePrologue = true; boolean savedStrictMode = inUseStrictDirective; // Don't set 'inUseStrictDirective' to false: inherit strict mode. pn.setLineno(ts.lineno); try { bodyLoop: for (;;) { AstNode n; int tt = peekToken(); switch (tt) { case Token.ERROR: case Token.EOF: case Token.RC: break bodyLoop; case Token.FUNCTION: consumeToken(); n = function(FunctionNode.FUNCTION_STATEMENT); break; default: n = statement(); if (inDirectivePrologue) { String directive = getDirective(n); if (directive == null) { inDirectivePrologue = false; } else if (directive.equals("use strict")) { inUseStrictDirective = true; } } break; } pn.addStatement(n); } } catch (ParserException e) { // Ignore it } finally { --nestingOfFunction; inUseStrictDirective = savedStrictMode; } int end = ts.tokenEnd; getAndResetJsDoc(); if (mustMatchToken(Token.RC, "msg.no.brace.after.body")) end = ts.tokenEnd; pn.setLength(end - pos); return pn; } private String getDirective(AstNode n) { if (n instanceof ExpressionStatement) { AstNode e = ((ExpressionStatement) n).getExpression(); if (e instanceof StringLiteral) { return ((StringLiteral) e).getValue(); } } return null; } private void parseFunctionParams(FunctionNode fnNode) throws IOException { if (matchToken(Token.RP)) { fnNode.setRp(ts.tokenBeg - fnNode.getPosition()); return; } // Would prefer not to call createDestructuringAssignment until codegen, // but the symbol definitions have to happen now, before body is parsed. Map<String, Node> destructuring = null; Set<String> paramNames = new HashSet<String>(); do { int tt = peekToken(); if (tt == Token.LB || tt == Token.LC) { AstNode expr = destructuringPrimaryExpr(); markDestructuring(expr); fnNode.addParam(expr); // Destructuring assignment for parameters: add a dummy // parameter name, and add a statement to the body to initialize // variables from the destructuring assignment if (destructuring == null) { destructuring = new HashMap<String, Node>(); } String pname = currentScriptOrFn.getNextTempName(); defineSymbol(Token.LP, pname, false); destructuring.put(pname, expr); } else { if (mustMatchToken(Token.NAME, "msg.no.parm")) { fnNode.addParam(createNameNode()); String paramName = ts.getString(); defineSymbol(Token.LP, paramName); if (this.inUseStrictDirective) { if ("eval".equals(paramName) || "arguments".equals(paramName)) { reportError("msg.bad.id.strict", paramName); } if (paramNames.contains(paramName)) addError("msg.dup.param.strict", paramName); paramNames.add(paramName); } } else { fnNode.addParam(makeErrorNode()); } } } while (matchToken(Token.COMMA)); if (destructuring != null) { Node destructuringNode = new Node(Token.COMMA); // Add assignment helper for each destructuring parameter for (Map.Entry<String, Node> param: destructuring.entrySet()) { Node assign = createDestructuringAssignment(Token.VAR, param.getValue(), createName(param.getKey())); destructuringNode.addChildToBack(assign); } fnNode.putProp(Node.DESTRUCTURING_PARAMS, destructuringNode); } if (mustMatchToken(Token.RP, "msg.no.paren.after.parms")) { fnNode.setRp(ts.tokenBeg - fnNode.getPosition()); } } private AstNode parseFunctionBodyExpr() throws IOException { ++nestingOfFunction; int lineno = ts.getLineno(); ReturnStatement n = new ReturnStatement(lineno); n.putProp(Node.EXPRESSION_CLOSURE_PROP, Boolean.TRUE); try { n.setReturnValue(assignExpr()); } finally { --nestingOfFunction; } return n; } private FunctionNode function(int type) throws IOException { int syntheticType = type; int baseLineno = ts.lineno; // line number where source starts int functionSourceStart = ts.tokenBeg; // start of "function" kwd Name name = null; AstNode memberExprNode = null; if (matchToken(Token.NAME)) { name = createNameNode(true, Token.NAME); if (inUseStrictDirective) { String id = name.getIdentifier(); if ("eval".equals(id)|| "arguments".equals(id)) { reportError("msg.bad.id.strict", id); } } if (!matchToken(Token.LP)) { if (compilerEnv.isAllowMemberExprAsFunctionName()) { AstNode memberExprHead = name; name = null; memberExprNode = memberExprTail(false, memberExprHead); } mustMatchToken(Token.LP, "msg.no.paren.parms"); } } else if (matchToken(Token.LP)) { // Anonymous function: leave name as null } else { if (compilerEnv.isAllowMemberExprAsFunctionName()) { // Note that memberExpr can not start with '(' like // in function (1+2).toString(), because 'function (' already // processed as anonymous function memberExprNode = memberExpr(false); } mustMatchToken(Token.LP, "msg.no.paren.parms"); } int lpPos = currentToken == Token.LP ? ts.tokenBeg : -1; if (memberExprNode != null) { syntheticType = FunctionNode.FUNCTION_EXPRESSION; } if (syntheticType != FunctionNode.FUNCTION_EXPRESSION && name != null && name.length() > 0) { // Function statements define a symbol in the enclosing scope defineSymbol(Token.FUNCTION, name.getIdentifier()); } FunctionNode fnNode = new FunctionNode(functionSourceStart, name); fnNode.setFunctionType(type); if (lpPos != -1) fnNode.setLp(lpPos - functionSourceStart); fnNode.setJsDoc(getAndResetJsDoc()); PerFunctionVariables savedVars = new PerFunctionVariables(fnNode); try { parseFunctionParams(fnNode); fnNode.setBody(parseFunctionBody()); fnNode.setEncodedSourceBounds(functionSourceStart, ts.tokenEnd); fnNode.setLength(ts.tokenEnd - functionSourceStart); if (compilerEnv.isStrictMode() && !fnNode.getBody().hasConsistentReturnUsage()) { String msg = (name != null && name.length() > 0) ? "msg.no.return.value" : "msg.anon.no.return.value"; addStrictWarning(msg, name == null ? "" : name.getIdentifier()); } } finally { savedVars.restore(); } if (memberExprNode != null) { // TODO(stevey): fix missing functionality Kit.codeBug(); fnNode.setMemberExprNode(memberExprNode); // rewrite later /* old code: if (memberExprNode != null) { pn = nf.createAssignment(Token.ASSIGN, memberExprNode, pn); if (functionType != FunctionNode.FUNCTION_EXPRESSION) { // XXX check JScript behavior: should it be createExprStatement? pn = nf.createExprStatementNoReturn(pn, baseLineno); } } */ } fnNode.setSourceName(sourceURI); fnNode.setBaseLineno(baseLineno); fnNode.setEndLineno(ts.lineno); // Set the parent scope. Needed for finding undeclared vars. // Have to wait until after parsing the function to set its parent // scope, since defineSymbol needs the defining-scope check to stop // at the function boundary when checking for redeclarations. if (compilerEnv.isIdeMode()) { fnNode.setParentScope(currentScope); } return fnNode; } // This function does not match the closing RC: the caller matches // the RC so it can provide a suitable error message if not matched. // This means it's up to the caller to set the length of the node to // include the closing RC. The node start pos is set to the // absolute buffer start position, and the caller should fix it up // to be relative to the parent node. All children of this block // node are given relative start positions and correct lengths. private AstNode statements(AstNode parent) throws IOException { if (currentToken != Token.LC // assertion can be invalid in bad code && !compilerEnv.isIdeMode()) codeBug(); int pos = ts.tokenBeg; AstNode block = parent != null ? parent : new Block(pos); block.setLineno(ts.lineno); int tt; while ((tt = peekToken()) > Token.EOF && tt != Token.RC) { block.addChild(statement()); } block.setLength(ts.tokenBeg - pos); return block; } private AstNode statements() throws IOException { return statements(null); } private static class ConditionData { AstNode condition; int lp = -1; int rp = -1; } // parse and return a parenthesized expression private ConditionData condition() throws IOException { ConditionData data = new ConditionData(); if (mustMatchToken(Token.LP, "msg.no.paren.cond")) data.lp = ts.tokenBeg; data.condition = expr(); if (mustMatchToken(Token.RP, "msg.no.paren.after.cond")) data.rp = ts.tokenBeg; // Report strict warning on code like "if (a = 7) ...". Suppress the // warning if the condition is parenthesized, like "if ((a = 7)) ...". if (data.condition instanceof Assignment) { addStrictWarning("msg.equal.as.assign", "", data.condition.getPosition(), data.condition.getLength()); } return data; } private AstNode statement() throws IOException { int pos = ts.tokenBeg; try { AstNode pn = statementHelper(); if (pn != null) { if (compilerEnv.isStrictMode() && !pn.hasSideEffects()) { int beg = pn.getPosition(); beg = Math.max(beg, lineBeginningFor(beg)); addStrictWarning(pn instanceof EmptyExpression ? "msg.extra.trailing.semi" : "msg.no.side.effects", "", beg, nodeEnd(pn) - beg); } return pn; } } catch (ParserException e) { // an ErrorNode was added to the ErrorReporter } // error: skip ahead to a probable statement boundary guessingStatementEnd: for (;;) { int tt = peekTokenOrEOL(); consumeToken(); switch (tt) { case Token.ERROR: case Token.EOF: case Token.EOL: case Token.SEMI: break guessingStatementEnd; } } // We don't make error nodes explicitly part of the tree; // they get added to the ErrorReporter. May need to do // something different here. return new EmptyExpression(pos, ts.tokenBeg - pos); } private AstNode statementHelper() throws IOException { // If the statement is set, then it's been told its label by now. if (currentLabel != null && currentLabel.getStatement() != null) currentLabel = null; AstNode pn = null; int tt = peekToken(), pos = ts.tokenBeg; switch (tt) { case Token.IF: return ifStatement(); case Token.SWITCH: return switchStatement(); case Token.WHILE: return whileLoop(); case Token.DO: return doLoop(); case Token.FOR: return forLoop(); case Token.TRY: return tryStatement(); case Token.THROW: pn = throwStatement(); break; case Token.BREAK: pn = breakStatement(); break; case Token.CONTINUE: pn = continueStatement(); break; case Token.WITH: if (this.inUseStrictDirective) { reportError("msg.no.with.strict"); } return withStatement(); case Token.CONST: case Token.VAR: consumeToken(); int lineno = ts.lineno; pn = variables(currentToken, ts.tokenBeg); pn.setLineno(lineno); break; case Token.LET: pn = letStatement(); if (pn instanceof VariableDeclaration && peekToken() == Token.SEMI) break; return pn; case Token.RETURN: case Token.YIELD: pn = returnOrYield(tt, false); break; case Token.DEBUGGER: consumeToken(); pn = new KeywordLiteral(ts.tokenBeg, ts.tokenEnd - ts.tokenBeg, tt); pn.setLineno(ts.lineno); break; case Token.LC: return block(); case Token.ERROR: consumeToken(); return makeErrorNode(); case Token.SEMI: consumeToken(); pos = ts.tokenBeg; pn = new EmptyExpression(pos, ts.tokenEnd - pos); pn.setLineno(ts.lineno); return pn; case Token.FUNCTION: consumeToken(); return function(FunctionNode.FUNCTION_EXPRESSION_STATEMENT); case Token.DEFAULT : pn = defaultXmlNamespace(); break; case Token.NAME: pn = nameOrLabel(); if (pn instanceof ExpressionStatement) break; return pn; // LabeledStatement default: lineno = ts.lineno; pn = new ExpressionStatement(expr(), !insideFunction()); pn.setLineno(lineno); break; } autoInsertSemicolon(pn); return pn; } private void autoInsertSemicolon(AstNode pn) throws IOException { int ttFlagged = peekFlaggedToken(); int pos = pn.getPosition(); switch (ttFlagged & CLEAR_TI_MASK) { case Token.SEMI: // Consume ';' as a part of expression consumeToken(); // extend the node bounds to include the semicolon. pn.setLength(ts.tokenEnd - pos); break; case Token.ERROR: case Token.EOF: case Token.RC: // Autoinsert ; warnMissingSemi(pos, nodeEnd(pn)); break; default: if ((ttFlagged & TI_AFTER_EOL) == 0) { // Report error if no EOL or autoinsert ; otherwise reportError("msg.no.semi.stmt"); } else { warnMissingSemi(pos, nodeEnd(pn)); } break; } } private IfStatement ifStatement() throws IOException { if (currentToken != Token.IF) codeBug(); consumeToken(); int pos = ts.tokenBeg, lineno = ts.lineno, elsePos = -1; ConditionData data = condition(); AstNode ifTrue = statement(), ifFalse = null; if (matchToken(Token.ELSE)) { elsePos = ts.tokenBeg - pos; ifFalse = statement(); } int end = getNodeEnd(ifFalse != null ? ifFalse : ifTrue); IfStatement pn = new IfStatement(pos, end - pos); pn.setCondition(data.condition); pn.setParens(data.lp - pos, data.rp - pos); pn.setThenPart(ifTrue); pn.setElsePart(ifFalse); pn.setElsePosition(elsePos); pn.setLineno(lineno); return pn; } private SwitchStatement switchStatement() throws IOException { if (currentToken != Token.SWITCH) codeBug(); consumeToken(); int pos = ts.tokenBeg; SwitchStatement pn = new SwitchStatement(pos); if (mustMatchToken(Token.LP, "msg.no.paren.switch")) pn.setLp(ts.tokenBeg - pos); pn.setLineno(ts.lineno); AstNode discriminant = expr(); pn.setExpression(discriminant); enterSwitch(pn); try { if (mustMatchToken(Token.RP, "msg.no.paren.after.switch")) pn.setRp(ts.tokenBeg - pos); mustMatchToken(Token.LC, "msg.no.brace.switch"); boolean hasDefault = false; int tt; switchLoop: for (;;) { tt = nextToken(); int casePos = ts.tokenBeg; int caseLineno = ts.lineno; AstNode caseExpression = null; switch (tt) { case Token.RC: pn.setLength(ts.tokenEnd - pos); break switchLoop; case Token.CASE: caseExpression = expr(); mustMatchToken(Token.COLON, "msg.no.colon.case"); break; case Token.DEFAULT: if (hasDefault) { reportError("msg.double.switch.default"); } hasDefault = true; caseExpression = null; mustMatchToken(Token.COLON, "msg.no.colon.case"); break; default: reportError("msg.bad.switch"); break switchLoop; } SwitchCase caseNode = new SwitchCase(casePos); caseNode.setExpression(caseExpression); caseNode.setLength(ts.tokenEnd - pos); // include colon caseNode.setLineno(caseLineno); while ((tt = peekToken()) != Token.RC && tt != Token.CASE && tt != Token.DEFAULT && tt != Token.EOF) { caseNode.addStatement(statement()); // updates length } pn.addCase(caseNode); } } finally { exitSwitch(); } return pn; } private WhileLoop whileLoop() throws IOException { if (currentToken != Token.WHILE) codeBug(); consumeToken(); int pos = ts.tokenBeg; WhileLoop pn = new WhileLoop(pos); pn.setLineno(ts.lineno); enterLoop(pn); try { ConditionData data = condition(); pn.setCondition(data.condition); pn.setParens(data.lp - pos, data.rp - pos); AstNode body = statement(); pn.setLength(getNodeEnd(body) - pos); pn.setBody(body); } finally { exitLoop(); } return pn; } private DoLoop doLoop() throws IOException { if (currentToken != Token.DO) codeBug(); consumeToken(); int pos = ts.tokenBeg, end; DoLoop pn = new DoLoop(pos); pn.setLineno(ts.lineno); enterLoop(pn); try { AstNode body = statement(); mustMatchToken(Token.WHILE, "msg.no.while.do"); pn.setWhilePosition(ts.tokenBeg - pos); ConditionData data = condition(); pn.setCondition(data.condition); pn.setParens(data.lp - pos, data.rp - pos); end = getNodeEnd(body); pn.setBody(body); } finally { exitLoop(); } // Always auto-insert semicolon to follow SpiderMonkey: // It is required by ECMAScript but is ignored by the rest of // world, see bug 238945 if (matchToken(Token.SEMI)) { end = ts.tokenEnd; } pn.setLength(end - pos); return pn; } private Loop forLoop() throws IOException { if (currentToken != Token.FOR) codeBug(); consumeToken(); int forPos = ts.tokenBeg, lineno = ts.lineno; boolean isForEach = false, isForIn = false; int eachPos = -1, inPos = -1, lp = -1, rp = -1; AstNode init = null; // init is also foo in 'foo in object' AstNode cond = null; // cond is also object in 'foo in object' AstNode incr = null; Loop pn = null; Scope tempScope = new Scope(); pushScope(tempScope); // decide below what AST class to use try { // See if this is a for each () instead of just a for () if (matchToken(Token.NAME)) { if ("each".equals(ts.getString())) { isForEach = true; eachPos = ts.tokenBeg - forPos; } else { reportError("msg.no.paren.for"); } } if (mustMatchToken(Token.LP, "msg.no.paren.for")) lp = ts.tokenBeg - forPos; int tt = peekToken(); init = forLoopInit(tt); if (matchToken(Token.IN)) { isForIn = true; inPos = ts.tokenBeg - forPos; cond = expr(); // object over which we're iterating } else { // ordinary for-loop mustMatchToken(Token.SEMI, "msg.no.semi.for"); if (peekToken() == Token.SEMI) { // no loop condition cond = new EmptyExpression(ts.tokenBeg, 1); cond.setLineno(ts.lineno); } else { cond = expr(); } mustMatchToken(Token.SEMI, "msg.no.semi.for.cond"); int tmpPos = ts.tokenEnd; if (peekToken() == Token.RP) { incr = new EmptyExpression(tmpPos, 1); incr.setLineno(ts.lineno); } else { incr = expr(); } } if (mustMatchToken(Token.RP, "msg.no.paren.for.ctrl")) rp = ts.tokenBeg - forPos; if (isForIn) { ForInLoop fis = new ForInLoop(forPos); if (init instanceof VariableDeclaration) { // check that there was only one variable given if (((VariableDeclaration)init).getVariables().size() > 1) { reportError("msg.mult.index"); } } fis.setIterator(init); fis.setIteratedObject(cond); fis.setInPosition(inPos); fis.setIsForEach(isForEach); fis.setEachPosition(eachPos); pn = fis; } else { ForLoop fl = new ForLoop(forPos); fl.setInitializer(init); fl.setCondition(cond); fl.setIncrement(incr); pn = fl; } // replace temp scope with the new loop object currentScope.replaceWith(pn); popScope(); // We have to parse the body -after- creating the loop node, // so that the loop node appears in the loopSet, allowing // break/continue statements to find the enclosing loop. enterLoop(pn); try { AstNode body = statement(); pn.setLength(getNodeEnd(body) - forPos); pn.setBody(body); } finally { exitLoop(); } } finally { if (currentScope == tempScope) { popScope(); } } pn.setParens(lp, rp); pn.setLineno(lineno); return pn; } private AstNode forLoopInit(int tt) throws IOException { try { inForInit = true; // checked by variables() and relExpr() AstNode init = null; if (tt == Token.SEMI) { init = new EmptyExpression(ts.tokenBeg, 1); init.setLineno(ts.lineno); } else if (tt == Token.VAR || tt == Token.LET) { consumeToken(); init = variables(tt, ts.tokenBeg); } else { init = expr(); markDestructuring(init); } return init; } finally { inForInit = false; } } private TryStatement tryStatement() throws IOException { if (currentToken != Token.TRY) codeBug(); consumeToken(); // Pull out JSDoc info and reset it before recursing. String jsdoc = getAndResetJsDoc(); int tryPos = ts.tokenBeg, lineno = ts.lineno, finallyPos = -1; if (peekToken() != Token.LC) { reportError("msg.no.brace.try"); } AstNode tryBlock = statement(); int tryEnd = getNodeEnd(tryBlock); List<CatchClause> clauses = null; boolean sawDefaultCatch = false; int peek = peekToken(); if (peek == Token.CATCH) { while (matchToken(Token.CATCH)) { int catchLineNum = ts.lineno; if (sawDefaultCatch) { reportError("msg.catch.unreachable"); } int catchPos = ts.tokenBeg, lp = -1, rp = -1, guardPos = -1; if (mustMatchToken(Token.LP, "msg.no.paren.catch")) lp = ts.tokenBeg; mustMatchToken(Token.NAME, "msg.bad.catchcond"); Name varName = createNameNode(); String varNameString = varName.getIdentifier(); if (inUseStrictDirective) { if ("eval".equals(varNameString) || "arguments".equals(varNameString)) { reportError("msg.bad.id.strict", varNameString); } } AstNode catchCond = null; if (matchToken(Token.IF)) { guardPos = ts.tokenBeg; catchCond = expr(); } else { sawDefaultCatch = true; } if (mustMatchToken(Token.RP, "msg.bad.catchcond")) rp = ts.tokenBeg; mustMatchToken(Token.LC, "msg.no.brace.catchblock"); Block catchBlock = (Block)statements(); tryEnd = getNodeEnd(catchBlock); CatchClause catchNode = new CatchClause(catchPos); catchNode.setVarName(varName); catchNode.setCatchCondition(catchCond); catchNode.setBody(catchBlock); if (guardPos != -1) { catchNode.setIfPosition(guardPos - catchPos); } catchNode.setParens(lp, rp); catchNode.setLineno(catchLineNum); if (mustMatchToken(Token.RC, "msg.no.brace.after.body")) tryEnd = ts.tokenEnd; catchNode.setLength(tryEnd - catchPos); if (clauses == null) clauses = new ArrayList<CatchClause>(); clauses.add(catchNode); } } else if (peek != Token.FINALLY) { mustMatchToken(Token.FINALLY, "msg.try.no.catchfinally"); } AstNode finallyBlock = null; if (matchToken(Token.FINALLY)) { finallyPos = ts.tokenBeg; finallyBlock = statement(); tryEnd = getNodeEnd(finallyBlock); } TryStatement pn = new TryStatement(tryPos, tryEnd - tryPos); pn.setTryBlock(tryBlock); pn.setCatchClauses(clauses); pn.setFinallyBlock(finallyBlock); if (finallyPos != -1) { pn.setFinallyPosition(finallyPos - tryPos); } pn.setLineno(lineno); if (jsdoc != null) { pn.setJsDoc(jsdoc); } return pn; } private ThrowStatement throwStatement() throws IOException { if (currentToken != Token.THROW) codeBug(); consumeToken(); int pos = ts.tokenBeg, lineno = ts.lineno; if (peekTokenOrEOL() == Token.EOL) { // ECMAScript does not allow new lines before throw expression, // see bug 256617 reportError("msg.bad.throw.eol"); } AstNode expr = expr(); ThrowStatement pn = new ThrowStatement(pos, getNodeEnd(expr), expr); pn.setLineno(lineno); return pn; } // If we match a NAME, consume the token and return the statement // with that label. If the name does not match an existing label, // reports an error. Returns the labeled statement node, or null if // the peeked token was not a name. Side effect: sets scanner token // information for the label identifier (tokenBeg, tokenEnd, etc.) private LabeledStatement matchJumpLabelName() throws IOException { LabeledStatement label = null; if (peekTokenOrEOL() == Token.NAME) { consumeToken(); if (labelSet != null) { label = labelSet.get(ts.getString()); } if (label == null) { reportError("msg.undef.label"); } } return label; } private BreakStatement breakStatement() throws IOException { if (currentToken != Token.BREAK) codeBug(); consumeToken(); int lineno = ts.lineno, pos = ts.tokenBeg, end = ts.tokenEnd; Name breakLabel = null; if (peekTokenOrEOL() == Token.NAME) { breakLabel = createNameNode(); end = getNodeEnd(breakLabel); } // matchJumpLabelName only matches if there is one LabeledStatement labels = matchJumpLabelName(); // always use first label as target Jump breakTarget = labels == null ? null : labels.getFirstLabel(); if (breakTarget == null && breakLabel == null) { if (loopAndSwitchSet == null || loopAndSwitchSet.size() == 0) { if (breakLabel == null) { reportError("msg.bad.break", pos, end - pos); } } else { breakTarget = loopAndSwitchSet.get(loopAndSwitchSet.size() - 1); } } BreakStatement pn = new BreakStatement(pos, end - pos); pn.setBreakLabel(breakLabel); // can be null if it's a bad break in error-recovery mode if (breakTarget != null) pn.setBreakTarget(breakTarget); pn.setLineno(lineno); return pn; } private ContinueStatement continueStatement() throws IOException { if (currentToken != Token.CONTINUE) codeBug(); consumeToken(); int lineno = ts.lineno, pos = ts.tokenBeg, end = ts.tokenEnd; Name label = null; if (peekTokenOrEOL() == Token.NAME) { label = createNameNode(); end = getNodeEnd(label); } // matchJumpLabelName only matches if there is one LabeledStatement labels = matchJumpLabelName(); Loop target = null; if (labels == null && label == null) { if (loopSet == null || loopSet.size() == 0) { reportError("msg.continue.outside"); } else { target = loopSet.get(loopSet.size() - 1); } } else { if (labels == null || !(labels.getStatement() instanceof Loop)) { reportError("msg.continue.nonloop", pos, end - pos); } target = labels == null ? null : (Loop)labels.getStatement(); } ContinueStatement pn = new ContinueStatement(pos, end - pos); if (target != null) // can be null in error-recovery mode pn.setTarget(target); pn.setLabel(label); pn.setLineno(lineno); return pn; } private WithStatement withStatement() throws IOException { if (currentToken != Token.WITH) codeBug(); consumeToken(); int lineno = ts.lineno, pos = ts.tokenBeg, lp = -1, rp = -1; if (mustMatchToken(Token.LP, "msg.no.paren.with")) lp = ts.tokenBeg; AstNode obj = expr(); if (mustMatchToken(Token.RP, "msg.no.paren.after.with")) rp = ts.tokenBeg; AstNode body = statement(); WithStatement pn = new WithStatement(pos, getNodeEnd(body) - pos); pn.setJsDoc(getAndResetJsDoc()); pn.setExpression(obj); pn.setStatement(body); pn.setParens(lp, rp); pn.setLineno(lineno); return pn; } private AstNode letStatement() throws IOException { if (currentToken != Token.LET) codeBug(); consumeToken(); int lineno = ts.lineno, pos = ts.tokenBeg; AstNode pn; if (peekToken() == Token.LP) { pn = let(true, pos); } else { pn = variables(Token.LET, pos); // else, e.g.: let x=6, y=7; } pn.setLineno(lineno); return pn; } /** * Returns whether or not the bits in the mask have changed to all set. * @param before bits before change * @param after bits after change * @param mask mask for bits * @return {@code true} if all the bits in the mask are set in "after" * but not in "before" */ private static final boolean nowAllSet(int before, int after, int mask) { return ((before & mask) != mask) && ((after & mask) == mask); } private AstNode returnOrYield(int tt, boolean exprContext) throws IOException { if (!insideFunction()) { reportError(tt == Token.RETURN ? "msg.bad.return" : "msg.bad.yield"); } consumeToken(); int lineno = ts.lineno, pos = ts.tokenBeg, end = ts.tokenEnd; AstNode e = null; // This is ugly, but we don't want to require a semicolon. switch (peekTokenOrEOL()) { case Token.SEMI: case Token.RC: case Token.RB: case Token.RP: case Token.EOF: case Token.EOL: case Token.ERROR: case Token.YIELD: break; default: e = expr(); end = getNodeEnd(e); } int before = endFlags; AstNode ret; if (tt == Token.RETURN) { endFlags |= e == null ? Node.END_RETURNS : Node.END_RETURNS_VALUE; ret = new ReturnStatement(pos, end - pos, e); // see if we need a strict mode warning if (nowAllSet(before, endFlags, Node.END_RETURNS|Node.END_RETURNS_VALUE)) addStrictWarning("msg.return.inconsistent", "", pos, end - pos); } else { if (!insideFunction()) reportError("msg.bad.yield"); endFlags |= Node.END_YIELDS; ret = new Yield(pos, end - pos, e); setRequiresActivation(); setIsGenerator(); if (!exprContext) { ret = new ExpressionStatement(ret); } } // see if we are mixing yields and value returns. if (insideFunction() && nowAllSet(before, endFlags, Node.END_YIELDS|Node.END_RETURNS_VALUE)) { Name name = ((FunctionNode)currentScriptOrFn).getFunctionName(); if (name == null || name.length() == 0) addError("msg.anon.generator.returns", ""); else addError("msg.generator.returns", name.getIdentifier()); } ret.setLineno(lineno); return ret; } private AstNode block() throws IOException { if (currentToken != Token.LC) codeBug(); consumeToken(); int pos = ts.tokenBeg; Scope block = new Scope(pos); block.setLineno(ts.lineno); pushScope(block); try { statements(block); mustMatchToken(Token.RC, "msg.no.brace.block"); block.setLength(ts.tokenEnd - pos); return block; } finally { popScope(); } } private AstNode defaultXmlNamespace() throws IOException { if (currentToken != Token.DEFAULT) codeBug(); consumeToken(); mustHaveXML(); setRequiresActivation(); int lineno = ts.lineno, pos = ts.tokenBeg; if (!(matchToken(Token.NAME) && "xml".equals(ts.getString()))) { reportError("msg.bad.namespace"); } if (!(matchToken(Token.NAME) && "namespace".equals(ts.getString()))) { reportError("msg.bad.namespace"); } if (!matchToken(Token.ASSIGN)) { reportError("msg.bad.namespace"); } AstNode e = expr(); UnaryExpression dxmln = new UnaryExpression(pos, getNodeEnd(e) - pos); dxmln.setOperator(Token.DEFAULTNAMESPACE); dxmln.setOperand(e); dxmln.setLineno(lineno); ExpressionStatement es = new ExpressionStatement(dxmln, true); return es; } private void recordLabel(Label label, LabeledStatement bundle) throws IOException { // current token should be colon that primaryExpr left untouched if (peekToken() != Token.COLON) codeBug(); consumeToken(); String name = label.getName(); if (labelSet == null) { labelSet = new HashMap<String,LabeledStatement>(); } else { LabeledStatement ls = labelSet.get(name); if (ls != null) { if (compilerEnv.isIdeMode()) { Label dup = ls.getLabelByName(name); reportError("msg.dup.label", dup.getAbsolutePosition(), dup.getLength()); } reportError("msg.dup.label", label.getPosition(), label.getLength()); } } bundle.addLabel(label); labelSet.put(name, bundle); } /** * Found a name in a statement context. If it's a label, we gather * up any following labels and the next non-label statement into a * {@link LabeledStatement} "bundle" and return that. Otherwise we parse * an expression and return it wrapped in an {@link ExpressionStatement}. */ private AstNode nameOrLabel() throws IOException { if (currentToken != Token.NAME) throw codeBug(); int pos = ts.tokenBeg; // set check for label and call down to primaryExpr currentFlaggedToken |= TI_CHECK_LABEL; AstNode expr = expr(); if (expr.getType() != Token.LABEL) { AstNode n = new ExpressionStatement(expr, !insideFunction()); n.lineno = expr.lineno; return n; } LabeledStatement bundle = new LabeledStatement(pos); recordLabel((Label)expr, bundle); bundle.setLineno(ts.lineno); // look for more labels AstNode stmt = null; while (peekToken() == Token.NAME) { currentFlaggedToken |= TI_CHECK_LABEL; expr = expr(); if (expr.getType() != Token.LABEL) { stmt = new ExpressionStatement(expr, !insideFunction()); autoInsertSemicolon(stmt); break; } recordLabel((Label)expr, bundle); } // no more labels; now parse the labeled statement try { currentLabel = bundle; if (stmt == null) { stmt = statementHelper(); } } finally { currentLabel = null; // remove the labels for this statement from the global set for (Label lb : bundle.getLabels()) { labelSet.remove(lb.getName()); } } // If stmt has parent assigned its position already is relative // (See bug #710225) bundle.setLength(stmt.getParent() == null ? getNodeEnd(stmt) - pos : getNodeEnd(stmt)); bundle.setStatement(stmt); return bundle; } /** * Parse a 'var' or 'const' statement, or a 'var' init list in a for * statement. * @param declType A token value: either VAR, CONST, or LET depending on * context. * @param pos the position where the node should start. It's sometimes * the var/const/let keyword, and other times the beginning of the first * token in the first variable declaration. * @return the parsed variable list */ private VariableDeclaration variables(int declType, int pos) throws IOException { int end; VariableDeclaration pn = new VariableDeclaration(pos); pn.setType(declType); pn.setLineno(ts.lineno); String varjsdoc = getAndResetJsDoc(); if (varjsdoc != null) { pn.setJsDoc(varjsdoc); } // Example: // var foo = {a: 1, b: 2}, bar = [3, 4]; // var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar; for (;;) { AstNode destructuring = null; Name name = null; int tt = peekToken(), kidPos = ts.tokenBeg; end = ts.tokenEnd; if (tt == Token.LB || tt == Token.LC) { // Destructuring assignment, e.g., var [a,b] = ... destructuring = destructuringPrimaryExpr(); end = getNodeEnd(destructuring); if (!(destructuring instanceof DestructuringForm)) reportError("msg.bad.assign.left", kidPos, end - kidPos); markDestructuring(destructuring); } else { // Simple variable name mustMatchToken(Token.NAME, "msg.bad.var"); name = createNameNode(); name.setLineno(ts.getLineno()); if (inUseStrictDirective) { String id = ts.getString(); if ("eval".equals(id) || "arguments".equals(ts.getString())) { reportError("msg.bad.id.strict", id); } } defineSymbol(declType, ts.getString(), inForInit); } int lineno = ts.lineno; String jsdoc = getAndResetJsDoc(); AstNode init = null; if (matchToken(Token.ASSIGN)) { init = assignExpr(); end = getNodeEnd(init); } VariableInitializer vi = new VariableInitializer(kidPos, end - kidPos); if (destructuring != null) { if (init == null && !inForInit) { reportError("msg.destruct.assign.no.init"); } vi.setTarget(destructuring); } else { vi.setTarget(name); } vi.setInitializer(init); vi.setType(declType); vi.setJsDoc(jsdoc); vi.setLineno(lineno); pn.addVariable(vi); if (!matchToken(Token.COMMA)) break; } pn.setLength(end - pos); return pn; } // have to pass in 'let' kwd position to compute kid offsets properly private AstNode let(boolean isStatement, int pos) throws IOException { LetNode pn = new LetNode(pos); pn.setLineno(ts.lineno); if (mustMatchToken(Token.LP, "msg.no.paren.after.let")) pn.setLp(ts.tokenBeg - pos); pushScope(pn); try { VariableDeclaration vars = variables(Token.LET, ts.tokenBeg); pn.setVariables(vars); if (mustMatchToken(Token.RP, "msg.no.paren.let")) { pn.setRp(ts.tokenBeg - pos); } if (isStatement && peekToken() == Token.LC) { // let statement consumeToken(); int beg = ts.tokenBeg; // position stmt at LC AstNode stmt = statements(); mustMatchToken(Token.RC, "msg.no.curly.let"); stmt.setLength(ts.tokenEnd - beg); pn.setLength(ts.tokenEnd - pos); pn.setBody(stmt); pn.setType(Token.LET); } else { // let expression AstNode expr = expr(); pn.setLength(getNodeEnd(expr) - pos); pn.setBody(expr); if (isStatement) { // let expression in statement context ExpressionStatement es = new ExpressionStatement(pn, !insideFunction()); es.setLineno(pn.getLineno()); return es; } } } finally { popScope(); } return pn; } void defineSymbol(int declType, String name) { defineSymbol(declType, name, false); } void defineSymbol(int declType, String name, boolean ignoreNotInBlock) { if (name == null) { if (compilerEnv.isIdeMode()) { // be robust in IDE-mode return; } else { codeBug(); } } Scope definingScope = currentScope.getDefiningScope(name); Symbol symbol = definingScope != null ? definingScope.getSymbol(name) : null; int symDeclType = symbol != null ? symbol.getDeclType() : -1; if (symbol != null && (symDeclType == Token.CONST || declType == Token.CONST || (definingScope == currentScope && symDeclType == Token.LET))) { addError(symDeclType == Token.CONST ? "msg.const.redecl" : symDeclType == Token.LET ? "msg.let.redecl" : symDeclType == Token.VAR ? "msg.var.redecl" : symDeclType == Token.FUNCTION ? "msg.fn.redecl" : "msg.parm.redecl", name); return; } switch (declType) { case Token.LET: if (!ignoreNotInBlock && ((currentScope.getType() == Token.IF) || currentScope instanceof Loop)) { addError("msg.let.decl.not.in.block"); return; } currentScope.putSymbol(new Symbol(declType, name)); return; case Token.VAR: case Token.CONST: case Token.FUNCTION: if (symbol != null) { if (symDeclType == Token.VAR) addStrictWarning("msg.var.redecl", name); else if (symDeclType == Token.LP) { addStrictWarning("msg.var.hides.arg", name); } } else { currentScriptOrFn.putSymbol(new Symbol(declType, name)); } return; case Token.LP: if (symbol != null) { // must be duplicate parameter. Second parameter hides the // first, so go ahead and add the second parameter addWarning("msg.dup.parms", name); } currentScriptOrFn.putSymbol(new Symbol(declType, name)); return; default: throw codeBug(); } } private AstNode expr() throws IOException { AstNode pn = assignExpr(); int pos = pn.getPosition(); while (matchToken(Token.COMMA)) { int lineno = ts.lineno; int opPos = ts.tokenBeg; if (compilerEnv.isStrictMode() && !pn.hasSideEffects()) addStrictWarning("msg.no.side.effects", "", pos, nodeEnd(pn) - pos); if (peekToken() == Token.YIELD) reportError("msg.yield.parenthesized"); pn = new InfixExpression(Token.COMMA, pn, assignExpr(), opPos); pn.setLineno(lineno); } return pn; } private AstNode assignExpr() throws IOException { int tt = peekToken(); if (tt == Token.YIELD) { return returnOrYield(tt, true); } AstNode pn = condExpr(); tt = peekToken(); if (Token.FIRST_ASSIGN <= tt && tt <= Token.LAST_ASSIGN) { consumeToken(); // Pull out JSDoc info and reset it before recursing. String jsdoc = getAndResetJsDoc(); markDestructuring(pn); int opPos = ts.tokenBeg; int opLineno = ts.getLineno(); pn = new Assignment(tt, pn, assignExpr(), opPos); pn.setLineno(opLineno); if (jsdoc != null) { pn.setJsDoc(jsdoc); } } else if (tt == Token.SEMI && pn.getType() == Token.GETPROP) { // This may be dead code added intentionally, for JSDoc purposes. // For example: /** @type Number */ C.prototype.x; if (currentJsDocComment != null) { pn.setJsDoc(getAndResetJsDoc()); } } return pn; } private AstNode condExpr() throws IOException { AstNode pn = orExpr(); if (matchToken(Token.HOOK)) { int line = ts.lineno; int qmarkPos = ts.tokenBeg, colonPos = -1; AstNode ifTrue = assignExpr(); if (mustMatchToken(Token.COLON, "msg.no.colon.cond")) colonPos = ts.tokenBeg; AstNode ifFalse = assignExpr(); int beg = pn.getPosition(), len = getNodeEnd(ifFalse) - beg; ConditionalExpression ce = new ConditionalExpression(beg, len); ce.setLineno(line); ce.setTestExpression(pn); ce.setTrueExpression(ifTrue); ce.setFalseExpression(ifFalse); ce.setQuestionMarkPosition(qmarkPos - beg); ce.setColonPosition(colonPos - beg); pn = ce; } return pn; } private AstNode orExpr() throws IOException { AstNode pn = andExpr(); if (matchToken(Token.OR)) { int opPos = ts.tokenBeg; int lineno = ts.lineno; pn = new InfixExpression(Token.OR, pn, orExpr(), opPos); pn.setLineno(lineno); } return pn; } private AstNode andExpr() throws IOException { AstNode pn = bitOrExpr(); if (matchToken(Token.AND)) { int opPos = ts.tokenBeg; int lineno = ts.lineno; pn = new InfixExpression(Token.AND, pn, andExpr(), opPos); pn.setLineno(lineno); } return pn; } private AstNode bitOrExpr() throws IOException { AstNode pn = bitXorExpr(); while (matchToken(Token.BITOR)) { int opPos = ts.tokenBeg; int lineno = ts.lineno; pn = new InfixExpression(Token.BITOR, pn, bitXorExpr(), opPos); pn.setLineno(lineno); } return pn; } private AstNode bitXorExpr() throws IOException { AstNode pn = bitAndExpr(); while (matchToken(Token.BITXOR)) { int opPos = ts.tokenBeg; int lineno = ts.lineno; pn = new InfixExpression(Token.BITXOR, pn, bitAndExpr(), opPos); pn.setLineno(lineno); } return pn; } private AstNode bitAndExpr() throws IOException { AstNode pn = eqExpr(); while (matchToken(Token.BITAND)) { int opPos = ts.tokenBeg; int lineno = ts.lineno; pn = new InfixExpression(Token.BITAND, pn, eqExpr(), opPos); pn.setLineno(lineno); } return pn; } private AstNode eqExpr() throws IOException { AstNode pn = relExpr(); for (;;) { int tt = peekToken(), opPos = ts.tokenBeg; int lineno = ts.lineno; switch (tt) { case Token.EQ: case Token.NE: case Token.SHEQ: case Token.SHNE: consumeToken(); int parseToken = tt; if (compilerEnv.getLanguageVersion() == Context.VERSION_1_2) { // JavaScript 1.2 uses shallow equality for == and != . if (tt == Token.EQ) parseToken = Token.SHEQ; else if (tt == Token.NE) parseToken = Token.SHNE; } pn = new InfixExpression(parseToken, pn, relExpr(), opPos); pn.setLineno(lineno); continue; } break; } return pn; } private AstNode relExpr() throws IOException { AstNode pn = shiftExpr(); for (;;) { int tt = peekToken(), opPos = ts.tokenBeg; int line = ts.lineno; switch (tt) { case Token.IN: if (inForInit) break; // fall through case Token.INSTANCEOF: case Token.LE: case Token.LT: case Token.GE: case Token.GT: consumeToken(); pn = new InfixExpression(tt, pn, shiftExpr(), opPos); pn.setLineno(line); continue; } break; } return pn; } private AstNode shiftExpr() throws IOException { AstNode pn = addExpr(); for (;;) { int tt = peekToken(), opPos = ts.tokenBeg; int lineno = ts.lineno; switch (tt) { case Token.LSH: case Token.URSH: case Token.RSH: consumeToken(); pn = new InfixExpression(tt, pn, addExpr(), opPos); pn.setLineno(lineno); continue; } break; } return pn; } private AstNode addExpr() throws IOException { AstNode pn = mulExpr(); for (;;) { int tt = peekToken(), opPos = ts.tokenBeg; if (tt == Token.ADD || tt == Token.SUB) { consumeToken(); int lineno = ts.lineno; pn = new InfixExpression(tt, pn, mulExpr(), opPos); pn.setLineno(lineno); continue; } break; } return pn; } private AstNode mulExpr() throws IOException { AstNode pn = unaryExpr(); for (;;) { int tt = peekToken(), opPos = ts.tokenBeg; switch (tt) { case Token.MUL: case Token.DIV: case Token.MOD: consumeToken(); int line = ts.lineno; pn = new InfixExpression(tt, pn, unaryExpr(), opPos); pn.setLineno(line); continue; } break; } return pn; } private AstNode unaryExpr() throws IOException { AstNode node; int tt = peekToken(); int line = ts.lineno; switch(tt) { case Token.VOID: case Token.NOT: case Token.BITNOT: case Token.TYPEOF: consumeToken(); node = new UnaryExpression(tt, ts.tokenBeg, unaryExpr()); node.setLineno(line); return node; case Token.ADD: consumeToken(); // Convert to special POS token in parse tree node = new UnaryExpression(Token.POS, ts.tokenBeg, unaryExpr()); node.setLineno(line); return node; case Token.SUB: consumeToken(); // Convert to special NEG token in parse tree node = new UnaryExpression(Token.NEG, ts.tokenBeg, unaryExpr()); node.setLineno(line); return node; case Token.INC: case Token.DEC: consumeToken(); UnaryExpression expr = new UnaryExpression(tt, ts.tokenBeg, memberExpr(true)); expr.setLineno(line); checkBadIncDec(expr); return expr; case Token.DELPROP: consumeToken(); node = new UnaryExpression(tt, ts.tokenBeg, unaryExpr()); node.setLineno(line); return node; case Token.ERROR: consumeToken(); return makeErrorNode(); case Token.LT: // XML stream encountered in expression. if (compilerEnv.isXmlAvailable()) { consumeToken(); return memberExprTail(true, xmlInitializer()); } // Fall thru to the default handling of RELOP default: AstNode pn = memberExpr(true); // Don't look across a newline boundary for a postfix incop. tt = peekTokenOrEOL(); if (!(tt == Token.INC || tt == Token.DEC)) { return pn; } consumeToken(); UnaryExpression uexpr = new UnaryExpression(tt, ts.tokenBeg, pn, true); uexpr.setLineno(line); checkBadIncDec(uexpr); return uexpr; } } private AstNode xmlInitializer() throws IOException { if (currentToken != Token.LT) codeBug(); int pos = ts.tokenBeg, tt = ts.getFirstXMLToken(); if (tt != Token.XML && tt != Token.XMLEND) { reportError("msg.syntax"); return makeErrorNode(); } XmlLiteral pn = new XmlLiteral(pos); pn.setLineno(ts.lineno); for (;;tt = ts.getNextXMLToken()) { switch (tt) { case Token.XML: pn.addFragment(new XmlString(ts.tokenBeg, ts.getString())); mustMatchToken(Token.LC, "msg.syntax"); int beg = ts.tokenBeg; AstNode expr = (peekToken() == Token.RC) ? new EmptyExpression(beg, ts.tokenEnd - beg) : expr(); mustMatchToken(Token.RC, "msg.syntax"); XmlExpression xexpr = new XmlExpression(beg, expr); xexpr.setIsXmlAttribute(ts.isXMLAttribute()); xexpr.setLength(ts.tokenEnd - beg); pn.addFragment(xexpr); break; case Token.XMLEND: pn.addFragment(new XmlString(ts.tokenBeg, ts.getString())); return pn; default: reportError("msg.syntax"); return makeErrorNode(); } } } private List<AstNode> argumentList() throws IOException { if (matchToken(Token.RP)) return null; List<AstNode> result = new ArrayList<AstNode>(); boolean wasInForInit = inForInit; inForInit = false; try { do { if (peekToken() == Token.YIELD) reportError("msg.yield.parenthesized"); result.add(assignExpr()); } while (matchToken(Token.COMMA)); } finally { inForInit = wasInForInit; } mustMatchToken(Token.RP, "msg.no.paren.arg"); return result; } /** * Parse a new-expression, or if next token isn't {@link Token#NEW}, * a primary expression. * @param allowCallSyntax passed down to {@link #memberExprTail} */ private AstNode memberExpr(boolean allowCallSyntax) throws IOException { int tt = peekToken(), lineno = ts.lineno; AstNode pn; if (tt != Token.NEW) { pn = primaryExpr(); } else { consumeToken(); int pos = ts.tokenBeg; NewExpression nx = new NewExpression(pos); AstNode target = memberExpr(false); int end = getNodeEnd(target); nx.setTarget(target); int lp = -1; if (matchToken(Token.LP)) { lp = ts.tokenBeg; List<AstNode> args = argumentList(); if (args != null && args.size() > ARGC_LIMIT) reportError("msg.too.many.constructor.args"); int rp = ts.tokenBeg; end = ts.tokenEnd; if (args != null) nx.setArguments(args); nx.setParens(lp - pos, rp - pos); } // Experimental syntax: allow an object literal to follow a new // expression, which will mean a kind of anonymous class built with // the JavaAdapter. the object literal will be passed as an // additional argument to the constructor. if (matchToken(Token.LC)) { ObjectLiteral initializer = objectLiteral(); end = getNodeEnd(initializer); nx.setInitializer(initializer); } nx.setLength(end - pos); pn = nx; } pn.setLineno(lineno); AstNode tail = memberExprTail(allowCallSyntax, pn); return tail; } /** * Parse any number of "(expr)", "[expr]" ".expr", "..expr", * or ".(expr)" constructs trailing the passed expression. * @param pn the non-null parent node * @return the outermost (lexically last occurring) expression, * which will have the passed parent node as a descendant */ private AstNode memberExprTail(boolean allowCallSyntax, AstNode pn) throws IOException { // we no longer return null for errors, so this won't be null if (pn == null) codeBug(); int pos = pn.getPosition(); int lineno; tailLoop: for (;;) { int tt = peekToken(); switch (tt) { case Token.DOT: case Token.DOTDOT: lineno = ts.lineno; pn = propertyAccess(tt, pn); pn.setLineno(lineno); break; case Token.DOTQUERY: consumeToken(); int opPos = ts.tokenBeg, rp = -1; lineno = ts.lineno; mustHaveXML(); setRequiresActivation(); AstNode filter = expr(); int end = getNodeEnd(filter); if (mustMatchToken(Token.RP, "msg.no.paren")) { rp = ts.tokenBeg; end = ts.tokenEnd; } XmlDotQuery q = new XmlDotQuery(pos, end - pos); q.setLeft(pn); q.setRight(filter); q.setOperatorPosition(opPos); q.setRp(rp - pos); q.setLineno(lineno); pn = q; break; case Token.LB: consumeToken(); int lb = ts.tokenBeg, rb = -1; lineno = ts.lineno; AstNode expr = expr(); end = getNodeEnd(expr); if (mustMatchToken(Token.RB, "msg.no.bracket.index")) { rb = ts.tokenBeg; end = ts.tokenEnd; } ElementGet g = new ElementGet(pos, end - pos); g.setTarget(pn); g.setElement(expr); g.setParens(lb, rb); g.setLineno(lineno); pn = g; break; case Token.LP: if (!allowCallSyntax) { break tailLoop; } lineno = ts.lineno; consumeToken(); checkCallRequiresActivation(pn); FunctionCall f = new FunctionCall(pos); f.setTarget(pn); // Assign the line number for the function call to where // the paren appeared, not where the name expression started. f.setLineno(lineno); f.setLp(ts.tokenBeg - pos); List<AstNode> args = argumentList(); if (args != null && args.size() > ARGC_LIMIT) reportError("msg.too.many.function.args"); f.setArguments(args); f.setRp(ts.tokenBeg - pos); f.setLength(ts.tokenEnd - pos); pn = f; break; default: break tailLoop; } } return pn; } /** * Handles any construct following a "." or ".." operator. * @param pn the left-hand side (target) of the operator. Never null. * @return a PropertyGet, XmlMemberGet, or ErrorNode */ private AstNode propertyAccess(int tt, AstNode pn) throws IOException { if (pn == null) codeBug(); int memberTypeFlags = 0, lineno = ts.lineno, dotPos = ts.tokenBeg; consumeToken(); if (tt == Token.DOTDOT) { mustHaveXML(); memberTypeFlags = Node.DESCENDANTS_FLAG; } if (!compilerEnv.isXmlAvailable()) { mustMatchToken(Token.NAME, "msg.no.name.after.dot"); Name name = createNameNode(true, Token.GETPROP); PropertyGet pg = new PropertyGet(pn, name, dotPos); pg.setLineno(lineno); return pg; } AstNode ref = null; // right side of . or .. operator int token = nextToken(); switch (token) { case Token.THROW: // needed for generator.throw(); saveNameTokenData(ts.tokenBeg, "throw", ts.lineno); ref = propertyName(-1, "throw", memberTypeFlags); break; case Token.NAME: // handles: name, ns::name, ns::*, ns::[expr] ref = propertyName(-1, ts.getString(), memberTypeFlags); break; case Token.MUL: // handles: *, *::name, *::*, *::[expr] saveNameTokenData(ts.tokenBeg, "*", ts.lineno); ref = propertyName(-1, "*", memberTypeFlags); break; case Token.XMLATTR: // handles: '@attr', '@ns::attr', '@ns::*', '@ns::*', // '@::attr', '@::*', '@*', '@*::attr', '@*::*' ref = attributeAccess(); break; default: if (compilerEnv.isReservedKeywordAsIdentifier()) { // allow keywords as property names, e.g. ({if: 1}) String name = Token.keywordToName(token); if (name != null) { saveNameTokenData(ts.tokenBeg, name, ts.lineno); ref = propertyName(-1, name, memberTypeFlags); break; } } reportError("msg.no.name.after.dot"); return makeErrorNode(); } boolean xml = ref instanceof XmlRef; InfixExpression result = xml ? new XmlMemberGet() : new PropertyGet(); if (xml && tt == Token.DOT) result.setType(Token.DOT); int pos = pn.getPosition(); result.setPosition(pos); result.setLength(getNodeEnd(ref) - pos); result.setOperatorPosition(dotPos - pos); result.setLineno(lineno); result.setLeft(pn); // do this after setting position result.setRight(ref); return result; } /** * Xml attribute expression:<p> * {@code @attr}, {@code @ns::attr}, {@code @ns::*}, {@code @ns::*}, * {@code @*}, {@code @*::attr}, {@code @*::*}, {@code @ns::[expr]}, * {@code @*::[expr]}, {@code @[expr]} <p> * Called if we peeked an '@' token. */ private AstNode attributeAccess() throws IOException { int tt = nextToken(), atPos = ts.tokenBeg; switch (tt) { // handles: @name, @ns::name, @ns::*, @ns::[expr] case Token.NAME: return propertyName(atPos, ts.getString(), 0); // handles: @*, @*::name, @*::*, @*::[expr] case Token.MUL: saveNameTokenData(ts.tokenBeg, "*", ts.lineno); return propertyName(atPos, "*", 0); // handles @[expr] case Token.LB: return xmlElemRef(atPos, null, -1); default: reportError("msg.no.name.after.xmlAttr"); return makeErrorNode(); } } /** * Check if :: follows name in which case it becomes a qualified name. * * @param atPos a natural number if we just read an '@' token, else -1 * * @param s the name or string that was matched (an identifier, "throw" or * "*"). * * @param memberTypeFlags flags tracking whether we're a '.' or '..' child * * @return an XmlRef node if it's an attribute access, a child of a * '..' operator, or the name is followed by ::. For a plain name, * returns a Name node. Returns an ErrorNode for malformed XML * expressions. (For now - might change to return a partial XmlRef.) */ private AstNode propertyName(int atPos, String s, int memberTypeFlags) throws IOException { int pos = atPos != -1 ? atPos : ts.tokenBeg, lineno = ts.lineno; int colonPos = -1; Name name = createNameNode(true, currentToken); Name ns = null; if (matchToken(Token.COLONCOLON)) { ns = name; colonPos = ts.tokenBeg; switch (nextToken()) { // handles name::name case Token.NAME: name = createNameNode(); break; // handles name::* case Token.MUL: saveNameTokenData(ts.tokenBeg, "*", ts.lineno); name = createNameNode(false, -1); break; // handles name::[expr] or *::[expr] case Token.LB: return xmlElemRef(atPos, ns, colonPos); default: reportError("msg.no.name.after.coloncolon"); return makeErrorNode(); } } if (ns == null && memberTypeFlags == 0 && atPos == -1) { return name; } XmlPropRef ref = new XmlPropRef(pos, getNodeEnd(name) - pos); ref.setAtPos(atPos); ref.setNamespace(ns); ref.setColonPos(colonPos); ref.setPropName(name); ref.setLineno(lineno); return ref; } /** * Parse the [expr] portion of an xml element reference, e.g. * @[expr], @*::[expr], or ns::[expr]. */ private XmlElemRef xmlElemRef(int atPos, Name namespace, int colonPos) throws IOException { int lb = ts.tokenBeg, rb = -1, pos = atPos != -1 ? atPos : lb; AstNode expr = expr(); int end = getNodeEnd(expr); if (mustMatchToken(Token.RB, "msg.no.bracket.index")) { rb = ts.tokenBeg; end = ts.tokenEnd; } XmlElemRef ref = new XmlElemRef(pos, end - pos); ref.setNamespace(namespace); ref.setColonPos(colonPos); ref.setAtPos(atPos); ref.setExpression(expr); ref.setBrackets(lb, rb); return ref; } private AstNode destructuringPrimaryExpr() throws IOException, ParserException { try { inDestructuringAssignment = true; return primaryExpr(); } finally { inDestructuringAssignment = false; } } private AstNode primaryExpr() throws IOException { int ttFlagged = nextFlaggedToken(); int tt = ttFlagged & CLEAR_TI_MASK; switch(tt) { case Token.FUNCTION: return function(FunctionNode.FUNCTION_EXPRESSION); case Token.LB: return arrayLiteral(); case Token.LC: return objectLiteral(); case Token.LET: return let(false, ts.tokenBeg); case Token.LP: return parenExpr(); case Token.XMLATTR: mustHaveXML(); return attributeAccess(); case Token.NAME: return name(ttFlagged, tt); case Token.NUMBER: { String s = ts.getString(); if (this.inUseStrictDirective && ts.isNumberOctal()) { reportError("msg.no.octal.strict"); } return new NumberLiteral(ts.tokenBeg, s, ts.getNumber()); } case Token.STRING: return createStringLiteral(); case Token.DIV: case Token.ASSIGN_DIV: // Got / or /= which in this context means a regexp ts.readRegExp(tt); int pos = ts.tokenBeg, end = ts.tokenEnd; RegExpLiteral re = new RegExpLiteral(pos, end - pos); re.setValue(ts.getString()); re.setFlags(ts.readAndClearRegExpFlags()); return re; case Token.NULL: case Token.THIS: case Token.FALSE: case Token.TRUE: pos = ts.tokenBeg; end = ts.tokenEnd; return new KeywordLiteral(pos, end - pos, tt); case Token.RESERVED: reportError("msg.reserved.id"); break; case Token.ERROR: // the scanner or one of its subroutines reported the error. break; case Token.EOF: reportError("msg.unexpected.eof"); break; default: reportError("msg.syntax"); break; } // should only be reachable in IDE/error-recovery mode return makeErrorNode(); } private AstNode parenExpr() throws IOException { boolean wasInForInit = inForInit; inForInit = false; try { String jsdoc = getAndResetJsDoc(); int lineno = ts.lineno; AstNode e = expr(); ParenthesizedExpression pn = new ParenthesizedExpression(e); if (jsdoc == null) { jsdoc = getAndResetJsDoc(); } if (jsdoc != null) { pn.setJsDoc(jsdoc); } mustMatchToken(Token.RP, "msg.no.paren"); pn.setLength(ts.tokenEnd - pn.getPosition()); pn.setLineno(lineno); return pn; } finally { inForInit = wasInForInit; } } private AstNode name(int ttFlagged, int tt) throws IOException { String nameString = ts.getString(); int namePos = ts.tokenBeg, nameLineno = ts.lineno; if (0 != (ttFlagged & TI_CHECK_LABEL) && peekToken() == Token.COLON) { // Do not consume colon. It is used as an unwind indicator // to return to statementHelper. Label label = new Label(namePos, ts.tokenEnd - namePos); label.setName(nameString); label.setLineno(ts.lineno); return label; } // Not a label. Unfortunately peeking the next token to check for // a colon has biffed ts.tokenBeg, ts.tokenEnd. We store the name's // bounds in instance vars and createNameNode uses them. saveNameTokenData(namePos, nameString, nameLineno); if (compilerEnv.isXmlAvailable()) { return propertyName(-1, nameString, 0); } else { return createNameNode(true, Token.NAME); } } /** * May return an {@link ArrayLiteral} or {@link ArrayComprehension}. */ private AstNode arrayLiteral() throws IOException { if (currentToken != Token.LB) codeBug(); int pos = ts.tokenBeg, end = ts.tokenEnd; List<AstNode> elements = new ArrayList<AstNode>(); ArrayLiteral pn = new ArrayLiteral(pos); boolean after_lb_or_comma = true; int afterComma = -1; int skipCount = 0; for (;;) { int tt = peekToken(); if (tt == Token.COMMA) { consumeToken(); afterComma = ts.tokenEnd; if (!after_lb_or_comma) { after_lb_or_comma = true; } else { elements.add(new EmptyExpression(ts.tokenBeg, 1)); skipCount++; } } else if (tt == Token.RB) { consumeToken(); // for ([a,] in obj) is legal, but for ([a] in obj) is // not since we have both key and value supplied. The // trick is that [a,] and [a] are equivalent in other // array literal contexts. So we calculate a special // length value just for destructuring assignment. end = ts.tokenEnd; pn.setDestructuringLength(elements.size() + (after_lb_or_comma ? 1 : 0)); pn.setSkipCount(skipCount); if (afterComma != -1) warnTrailingComma(pos, elements, afterComma); break; } else if (tt == Token.FOR && !after_lb_or_comma && elements.size() == 1) { return arrayComprehension(elements.get(0), pos); } else if (tt == Token.EOF) { reportError("msg.no.bracket.arg"); + break; } else { if (!after_lb_or_comma) { reportError("msg.no.bracket.arg"); } elements.add(assignExpr()); after_lb_or_comma = false; afterComma = -1; } } for (AstNode e : elements) { pn.addElement(e); } pn.setLength(end - pos); return pn; } /** * Parse a JavaScript 1.7 Array comprehension. * @param result the first expression after the opening left-bracket * @param pos start of LB token that begins the array comprehension * @return the array comprehension or an error node */ private AstNode arrayComprehension(AstNode result, int pos) throws IOException { List<ArrayComprehensionLoop> loops = new ArrayList<ArrayComprehensionLoop>(); while (peekToken() == Token.FOR) { loops.add(arrayComprehensionLoop()); } int ifPos = -1; ConditionData data = null; if (peekToken() == Token.IF) { consumeToken(); ifPos = ts.tokenBeg - pos; data = condition(); } mustMatchToken(Token.RB, "msg.no.bracket.arg"); ArrayComprehension pn = new ArrayComprehension(pos, ts.tokenEnd - pos); pn.setResult(result); pn.setLoops(loops); if (data != null) { pn.setIfPosition(ifPos); pn.setFilter(data.condition); pn.setFilterLp(data.lp - pos); pn.setFilterRp(data.rp - pos); } return pn; } private ArrayComprehensionLoop arrayComprehensionLoop() throws IOException { if (nextToken() != Token.FOR) codeBug(); int pos = ts.tokenBeg; int eachPos = -1, lp = -1, rp = -1, inPos = -1; ArrayComprehensionLoop pn = new ArrayComprehensionLoop(pos); pushScope(pn); try { if (matchToken(Token.NAME)) { if (ts.getString().equals("each")) { eachPos = ts.tokenBeg - pos; } else { reportError("msg.no.paren.for"); } } if (mustMatchToken(Token.LP, "msg.no.paren.for")) { lp = ts.tokenBeg - pos; } AstNode iter = null; switch (peekToken()) { case Token.LB: case Token.LC: // handle destructuring assignment iter = destructuringPrimaryExpr(); markDestructuring(iter); break; case Token.NAME: consumeToken(); iter = createNameNode(); break; default: reportError("msg.bad.var"); } // Define as a let since we want the scope of the variable to // be restricted to the array comprehension if (iter.getType() == Token.NAME) { defineSymbol(Token.LET, ts.getString(), true); } if (mustMatchToken(Token.IN, "msg.in.after.for.name")) inPos = ts.tokenBeg - pos; AstNode obj = expr(); if (mustMatchToken(Token.RP, "msg.no.paren.for.ctrl")) rp = ts.tokenBeg - pos; pn.setLength(ts.tokenEnd - pos); pn.setIterator(iter); pn.setIteratedObject(obj); pn.setInPosition(inPos); pn.setEachPosition(eachPos); pn.setIsForEach(eachPos != -1); pn.setParens(lp, rp); return pn; } finally { popScope(); } } private ObjectLiteral objectLiteral() throws IOException { int pos = ts.tokenBeg, lineno = ts.lineno; int afterComma = -1; List<ObjectProperty> elems = new ArrayList<ObjectProperty>(); Set<String> propertyNames = new HashSet<String>(); commaLoop: for (;;) { String propertyName = null; int tt = peekToken(); String jsdoc = getAndResetJsDoc(); switch(tt) { case Token.NAME: case Token.STRING: saveNameTokenData(ts.tokenBeg, ts.getString(), ts.lineno); consumeToken(); StringLiteral stringProp = null; if (tt == Token.STRING) { stringProp = createStringLiteral(); } Name name = createNameNode(); propertyName = ts.getString(); int ppos = ts.tokenBeg; if ((tt == Token.NAME && (peekToken() == Token.NAME || convertToName(peekToken())) && ("get".equals(propertyName) || "set".equals(propertyName)))) { consumeToken(); name = createNameNode(); name.setJsDoc(jsdoc); ObjectProperty objectProp = getterSetterProperty(ppos, name, "get".equals(propertyName)); elems.add(objectProp); propertyName = objectProp.getLeft().getString(); } else { AstNode pname = stringProp != null ? stringProp : name; pname.setJsDoc(jsdoc); elems.add(plainProperty(pname, tt)); } break; case Token.NUMBER: consumeToken(); AstNode nl = new NumberLiteral(ts.tokenBeg, ts.getString(), ts.getNumber()); nl.setJsDoc(jsdoc); propertyName = ts.getString(); elems.add(plainProperty(nl, tt)); break; case Token.RC: if (afterComma != -1) warnTrailingComma(pos, elems, afterComma); break commaLoop; default: if (convertToName(tt)) { consumeToken(); AstNode pname = createNameNode(); pname.setJsDoc(jsdoc); elems.add(plainProperty(pname, tt)); break; } reportError("msg.bad.prop"); break; } if (this.inUseStrictDirective) { if (propertyNames.contains(propertyName)) { addError("msg.dup.obj.lit.prop.strict", propertyName); } propertyNames.add(propertyName); } // Eat any dangling jsdoc in the property. getAndResetJsDoc(); if (matchToken(Token.COMMA)) { afterComma = ts.tokenEnd; } else { break commaLoop; } } mustMatchToken(Token.RC, "msg.no.brace.prop"); ObjectLiteral pn = new ObjectLiteral(pos, ts.tokenEnd - pos); pn.setElements(elems); pn.setLineno(lineno); return pn; } private ObjectProperty plainProperty(AstNode property, int ptt) throws IOException { // Support, e.g., |var {x, y} = o| as destructuring shorthand // for |var {x: x, y: y} = o|, as implemented in spidermonkey JS 1.8. int tt = peekToken(); if ((tt == Token.COMMA || tt == Token.RC) && ptt == Token.NAME && compilerEnv.getLanguageVersion() >= Context.VERSION_1_8) { if (!inDestructuringAssignment) { reportError("msg.bad.object.init"); } AstNode nn = new Name(property.getPosition(), property.getString()); ObjectProperty pn = new ObjectProperty(); pn.putProp(Node.DESTRUCTURING_SHORTHAND, Boolean.TRUE); pn.setLeftAndRight(property, nn); return pn; } mustMatchToken(Token.COLON, "msg.no.colon.prop"); ObjectProperty pn = new ObjectProperty(); pn.setOperatorPosition(ts.tokenBeg); pn.setLeftAndRight(property, assignExpr()); return pn; } private ObjectProperty getterSetterProperty(int pos, AstNode propName, boolean isGetter) throws IOException { FunctionNode fn = function(FunctionNode.FUNCTION_EXPRESSION); // We've already parsed the function name, so fn should be anonymous. Name name = fn.getFunctionName(); if (name != null && name.length() != 0) { reportError("msg.bad.prop"); } ObjectProperty pn = new ObjectProperty(pos); if (isGetter) { pn.setIsGetter(); } else { pn.setIsSetter(); } int end = getNodeEnd(fn); pn.setLeft(propName); pn.setRight(fn); pn.setLength(end - pos); return pn; } private Name createNameNode() { return createNameNode(false, Token.NAME); } /** * Create a {@code Name} node using the token info from the * last scanned name. In some cases we need to either synthesize * a name node, or we lost the name token information by peeking. * If the {@code token} parameter is not {@link Token#NAME}, then * we use token info saved in instance vars. */ private Name createNameNode(boolean checkActivation, int token) { int beg = ts.tokenBeg; String s = ts.getString(); int lineno = ts.lineno; if (!"".equals(prevNameTokenString)) { beg = prevNameTokenStart; s = prevNameTokenString; lineno = prevNameTokenLineno; prevNameTokenStart = 0; prevNameTokenString = ""; prevNameTokenLineno = 0; } if (s == null) { if (compilerEnv.isIdeMode()) { s = ""; } else { codeBug(); } } Name name = new Name(beg, s); name.setLineno(lineno); if (checkActivation) { checkActivationName(s, token); } return name; } private StringLiteral createStringLiteral() { int pos = ts.tokenBeg, end = ts.tokenEnd; StringLiteral s = new StringLiteral(pos, end - pos); s.setLineno(ts.lineno); s.setValue(ts.getString()); s.setQuoteCharacter(ts.getQuoteChar()); return s; } protected void checkActivationName(String name, int token) { if (!insideFunction()) { return; } boolean activation = false; if ("arguments".equals(name) || (compilerEnv.getActivationNames() != null && compilerEnv.getActivationNames().contains(name))) { activation = true; } else if ("length".equals(name)) { if (token == Token.GETPROP && compilerEnv.getLanguageVersion() == Context.VERSION_1_2) { // Use of "length" in 1.2 requires an activation object. activation = true; } } if (activation) { setRequiresActivation(); } } protected void setRequiresActivation() { if (insideFunction()) { ((FunctionNode)currentScriptOrFn).setRequiresActivation(); } } protected void setContainsEval() { if (insideFunction()) { ((FunctionNode)currentScriptOrFn).setContainsEval(); } } private void checkCallRequiresActivation(AstNode pn) { if ((pn.getType() == Token.NAME && "eval".equals(((Name)pn).getIdentifier())) || (pn.getType() == Token.GETPROP && "eval".equals(((PropertyGet)pn).getProperty().getIdentifier()))) { setRequiresActivation(); setContainsEval(); } } protected void setIsGenerator() { if (insideFunction()) { ((FunctionNode)currentScriptOrFn).setIsGenerator(); } } private void checkBadIncDec(UnaryExpression expr) { AstNode op = removeParens(expr.getOperand()); int tt = op.getType(); if (!(tt == Token.NAME || tt == Token.GETPROP || tt == Token.GETELEM || tt == Token.GET_REF || tt == Token.CALL)) reportError(expr.getType() == Token.INC ? "msg.bad.incr" : "msg.bad.decr"); } private ErrorNode makeErrorNode() { ErrorNode pn = new ErrorNode(ts.tokenBeg, ts.tokenEnd - ts.tokenBeg); pn.setLineno(ts.lineno); return pn; } // Return end of node. Assumes node does NOT have a parent yet. private int nodeEnd(AstNode node) { return node.getPosition() + node.getLength(); } private void saveNameTokenData(int pos, String name, int lineno) { prevNameTokenStart = pos; prevNameTokenString = name; prevNameTokenLineno = lineno; } // Check whether token is a reserved keyword that is allowed as property id. private boolean convertToName(int token) { if (compilerEnv.isReservedKeywordAsIdentifier()) { String conv = Token.keywordToName(token); if (conv != null) { saveNameTokenData(ts.tokenBeg, conv, ts.lineno); return true; } } return false; } /** * Return the file offset of the beginning of the input source line * containing the passed position. * * @param pos an offset into the input source stream. If the offset * is negative, it's converted to 0, and if it's beyond the end of * the source buffer, the last source position is used. * * @return the offset of the beginning of the line containing pos * (i.e. 1+ the offset of the first preceding newline). Returns -1 * if the {@link CompilerEnvirons} is not set to ide-mode, * and {@link #parse(java.io.Reader,String,int)} was used. */ private int lineBeginningFor(int pos) { if (sourceChars == null) { return -1; } if (pos <= 0) { return 0; } char[] buf = sourceChars; if (pos >= buf.length) { pos = buf.length - 1; } while (--pos >= 0) { char c = buf[pos]; if (c == '\n' || c == '\r') { return pos + 1; // want position after the newline } } return 0; } private void warnMissingSemi(int pos, int end) { // Should probably change this to be a CompilerEnvirons setting, // with an enum Never, Always, Permissive, where Permissive means // don't warn for 1-line functions like function (s) {return x+2} if (compilerEnv.isStrictMode()) { int beg = Math.max(pos, lineBeginningFor(end)); if (end == -1) end = ts.cursor; addStrictWarning("msg.missing.semi", "", beg, end - beg); } } private void warnTrailingComma(int pos, List<?> elems, int commaPos) { if (compilerEnv.getWarnTrailingComma()) { // back up from comma to beginning of line or array/objlit if (!elems.isEmpty()) { pos = ((AstNode)elems.get(0)).getPosition(); } pos = Math.max(pos, lineBeginningFor(commaPos)); addWarning("msg.extra.trailing.comma", pos, commaPos - pos); } } private String readFully(Reader reader) throws IOException { BufferedReader in = new BufferedReader(reader); try { char[] cbuf = new char[1024]; StringBuilder sb = new StringBuilder(1024); int bytes_read; while ((bytes_read = in.read(cbuf, 0, 1024)) != -1) { sb.append(cbuf, 0, bytes_read); } return sb.toString(); } finally { in.close(); } } // helps reduce clutter in the already-large function() method protected class PerFunctionVariables { private ScriptNode savedCurrentScriptOrFn; private Scope savedCurrentScope; private int savedEndFlags; private boolean savedInForInit; private Map<String,LabeledStatement> savedLabelSet; private List<Loop> savedLoopSet; private List<Jump> savedLoopAndSwitchSet; PerFunctionVariables(FunctionNode fnNode) { savedCurrentScriptOrFn = Parser.this.currentScriptOrFn; Parser.this.currentScriptOrFn = fnNode; savedCurrentScope = Parser.this.currentScope; Parser.this.currentScope = fnNode; savedLabelSet = Parser.this.labelSet; Parser.this.labelSet = null; savedLoopSet = Parser.this.loopSet; Parser.this.loopSet = null; savedLoopAndSwitchSet = Parser.this.loopAndSwitchSet; Parser.this.loopAndSwitchSet = null; savedEndFlags = Parser.this.endFlags; Parser.this.endFlags = 0; savedInForInit = Parser.this.inForInit; Parser.this.inForInit = false; } void restore() { Parser.this.currentScriptOrFn = savedCurrentScriptOrFn; Parser.this.currentScope = savedCurrentScope; Parser.this.labelSet = savedLabelSet; Parser.this.loopSet = savedLoopSet; Parser.this.loopAndSwitchSet = savedLoopAndSwitchSet; Parser.this.endFlags = savedEndFlags; Parser.this.inForInit = savedInForInit; } } /** * Given a destructuring assignment with a left hand side parsed * as an array or object literal and a right hand side expression, * rewrite as a series of assignments to the variables defined in * left from property accesses to the expression on the right. * @param type declaration type: Token.VAR or Token.LET or -1 * @param left array or object literal containing NAME nodes for * variables to assign * @param right expression to assign from * @return expression that performs a series of assignments to * the variables defined in left */ Node createDestructuringAssignment(int type, Node left, Node right) { String tempName = currentScriptOrFn.getNextTempName(); Node result = destructuringAssignmentHelper(type, left, right, tempName); Node comma = result.getLastChild(); comma.addChildToBack(createName(tempName)); return result; } Node destructuringAssignmentHelper(int variableType, Node left, Node right, String tempName) { Scope result = createScopeNode(Token.LETEXPR, left.getLineno()); result.addChildToFront(new Node(Token.LET, createName(Token.NAME, tempName, right))); try { pushScope(result); defineSymbol(Token.LET, tempName, true); } finally { popScope(); } Node comma = new Node(Token.COMMA); result.addChildToBack(comma); List<String> destructuringNames = new ArrayList<String>(); boolean empty = true; switch (left.getType()) { case Token.ARRAYLIT: empty = destructuringArray((ArrayLiteral)left, variableType, tempName, comma, destructuringNames); break; case Token.OBJECTLIT: empty = destructuringObject((ObjectLiteral)left, variableType, tempName, comma, destructuringNames); break; case Token.GETPROP: case Token.GETELEM: comma.addChildToBack(simpleAssignment(left, createName(tempName))); break; default: reportError("msg.bad.assign.left"); } if (empty) { // Don't want a COMMA node with no children. Just add a zero. comma.addChildToBack(createNumber(0)); } result.putProp(Node.DESTRUCTURING_NAMES, destructuringNames); return result; } boolean destructuringArray(ArrayLiteral array, int variableType, String tempName, Node parent, List<String> destructuringNames) { boolean empty = true; int setOp = variableType == Token.CONST ? Token.SETCONST : Token.SETNAME; int index = 0; for (AstNode n : array.getElements()) { if (n.getType() == Token.EMPTY) { index++; continue; } Node rightElem = new Node(Token.GETELEM, createName(tempName), createNumber(index)); if (n.getType() == Token.NAME) { String name = n.getString(); parent.addChildToBack(new Node(setOp, createName(Token.BINDNAME, name, null), rightElem)); if (variableType != -1) { defineSymbol(variableType, name, true); destructuringNames.add(name); } } else { parent.addChildToBack (destructuringAssignmentHelper (variableType, n, rightElem, currentScriptOrFn.getNextTempName())); } index++; empty = false; } return empty; } boolean destructuringObject(ObjectLiteral node, int variableType, String tempName, Node parent, List<String> destructuringNames) { boolean empty = true; int setOp = variableType == Token.CONST ? Token.SETCONST : Token.SETNAME; for (ObjectProperty prop : node.getElements()) { int lineno = 0; // This function is sometimes called from the IRFactory when // when executing regression tests, and in those cases the // tokenStream isn't set. Deal with it. if (ts != null) { lineno = ts.lineno; } AstNode id = prop.getLeft(); Node rightElem = null; if (id instanceof Name) { Node s = Node.newString(((Name)id).getIdentifier()); rightElem = new Node(Token.GETPROP, createName(tempName), s); } else if (id instanceof StringLiteral) { Node s = Node.newString(((StringLiteral)id).getValue()); rightElem = new Node(Token.GETPROP, createName(tempName), s); } else if (id instanceof NumberLiteral) { Node s = createNumber((int)((NumberLiteral)id).getNumber()); rightElem = new Node(Token.GETELEM, createName(tempName), s); } else { throw codeBug(); } rightElem.setLineno(lineno); AstNode value = prop.getRight(); if (value.getType() == Token.NAME) { String name = ((Name)value).getIdentifier(); parent.addChildToBack(new Node(setOp, createName(Token.BINDNAME, name, null), rightElem)); if (variableType != -1) { defineSymbol(variableType, name, true); destructuringNames.add(name); } } else { parent.addChildToBack (destructuringAssignmentHelper (variableType, value, rightElem, currentScriptOrFn.getNextTempName())); } empty = false; } return empty; } protected Node createName(String name) { checkActivationName(name, Token.NAME); return Node.newString(Token.NAME, name); } protected Node createName(int type, String name, Node child) { Node result = createName(name); result.setType(type); if (child != null) result.addChildToBack(child); return result; } protected Node createNumber(double number) { return Node.newNumber(number); } /** * Create a node that can be used to hold lexically scoped variable * definitions (via let declarations). * * @param token the token of the node to create * @param lineno line number of source * @return the created node */ protected Scope createScopeNode(int token, int lineno) { Scope scope =new Scope(); scope.setType(token); scope.setLineno(lineno); return scope; } // Quickie tutorial for some of the interpreter bytecodes. // // GETPROP - for normal foo.bar prop access; right side is a name // GETELEM - for normal foo[bar] element access; rhs is an expr // SETPROP - for assignment when left side is a GETPROP // SETELEM - for assignment when left side is a GETELEM // DELPROP - used for delete foo.bar or foo[bar] // // GET_REF, SET_REF, DEL_REF - in general, these mean you're using // get/set/delete on a right-hand side expression (possibly with no // explicit left-hand side) that doesn't use the normal JavaScript // Object (i.e. ScriptableObject) get/set/delete functions, but wants // to provide its own versions instead. It will ultimately implement // Ref, and currently SpecialRef (for __proto__ etc.) and XmlName // (for E4X XML objects) are the only implementations. The runtime // notices these bytecodes and delegates get/set/delete to the object. // // BINDNAME: used in assignments. LHS is evaluated first to get a // specific object containing the property ("binding" the property // to the object) so that it's always the same object, regardless of // side effects in the RHS. protected Node simpleAssignment(Node left, Node right) { int nodeType = left.getType(); switch (nodeType) { case Token.NAME: if (inUseStrictDirective && "eval".equals(((Name) left).getIdentifier())) { reportError("msg.bad.id.strict", ((Name) left).getIdentifier()); } left.setType(Token.BINDNAME); return new Node(Token.SETNAME, left, right); case Token.GETPROP: case Token.GETELEM: { Node obj, id; // If it's a PropertyGet or ElementGet, we're in the parse pass. // We could alternately have PropertyGet and ElementGet // override getFirstChild/getLastChild and return the appropriate // field, but that seems just as ugly as this casting. if (left instanceof PropertyGet) { obj = ((PropertyGet)left).getTarget(); id = ((PropertyGet)left).getProperty(); } else if (left instanceof ElementGet) { obj = ((ElementGet)left).getTarget(); id = ((ElementGet)left).getElement(); } else { // This branch is called during IRFactory transform pass. obj = left.getFirstChild(); id = left.getLastChild(); } int type; if (nodeType == Token.GETPROP) { type = Token.SETPROP; // TODO(stevey) - see https://bugzilla.mozilla.org/show_bug.cgi?id=492036 // The new AST code generates NAME tokens for GETPROP ids where the old parser // generated STRING nodes. If we don't set the type to STRING below, this will // cause java.lang.VerifyError in codegen for code like // "var obj={p:3};[obj.p]=[9];" id.setType(Token.STRING); } else { type = Token.SETELEM; } return new Node(type, obj, id, right); } case Token.GET_REF: { Node ref = left.getFirstChild(); checkMutableReference(ref); return new Node(Token.SET_REF, ref, right); } } throw codeBug(); } protected void checkMutableReference(Node n) { int memberTypeFlags = n.getIntProp(Node.MEMBER_TYPE_PROP, 0); if ((memberTypeFlags & Node.DESCENDANTS_FLAG) != 0) { reportError("msg.bad.assign.left"); } } // remove any ParenthesizedExpression wrappers protected AstNode removeParens(AstNode node) { while (node instanceof ParenthesizedExpression) { node = ((ParenthesizedExpression)node).getExpression(); } return node; } void markDestructuring(AstNode node) { if (node instanceof DestructuringForm) { ((DestructuringForm)node).setIsDestructuring(true); } else if (node instanceof ParenthesizedExpression) { markDestructuring(((ParenthesizedExpression)node).getExpression()); } } // throw a failed-assertion with some helpful debugging info private RuntimeException codeBug() throws RuntimeException { throw Kit.codeBug("ts.cursor=" + ts.cursor + ", ts.tokenBeg=" + ts.tokenBeg + ", currentToken=" + currentToken); } }
true
false
null
null
diff --git a/cdi/plugins/org.jboss.tools.cdi.core/src/org/jboss/tools/cdi/core/CDIImages.java b/cdi/plugins/org.jboss.tools.cdi.core/src/org/jboss/tools/cdi/core/CDIImages.java index 89b0b0648..581813084 100644 --- a/cdi/plugins/org.jboss.tools.cdi.core/src/org/jboss/tools/cdi/core/CDIImages.java +++ b/cdi/plugins/org.jboss.tools.cdi.core/src/org/jboss/tools/cdi/core/CDIImages.java @@ -1,121 +1,122 @@ /******************************************************************************* * Copyright (c) 2010 Red Hat, Inc. * Distributed under license by Red Hat, Inc. All rights reserved. * This program is made available under the terms of the * Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ package org.jboss.tools.cdi.core; import java.net.MalformedURLException; import java.net.URL; import org.eclipse.jface.action.IAction; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.swt.graphics.Image; import org.jboss.tools.cdi.internal.core.impl.EventBean; +import org.jboss.tools.cdi.xml.CDIXMLImages; public class CDIImages { private static CDIImages INSTANCE; static { try { INSTANCE = new CDIImages(new URL(CDICorePlugin.getDefault().getBundle().getEntry("/"), "images/")); //$NON-NLS-1$ //$NON-NLS-2$ } catch (MalformedURLException e) { CDICorePlugin.getDefault().logError(e); } } public static final Image CDI_BEAN_IMAGE = getImage("search/cdi_bean.gif"); //$NON-NLS-1$ public static final Image WELD_IMAGE = getImage("search/weld_icon_16x.gif"); //$NON-NLS-1$ - public static final Image BEAN_CLASS_IMAGE = getImage("bean_class.png"); //$NON-NLS-1$ + public static final Image BEAN_CLASS_IMAGE = CDIXMLImages.BEAN_CLASS_IMAGE; public static final Image BEAN_METHOD_IMAGE = getImage("bean_method.png"); //$NON-NLS-1$ public static final Image BEAN_FIELD_IMAGE = getImage("bean_field.png"); //$NON-NLS-1$ public static final Image INJECTION_POINT_IMAGE = getImage("injection_point.png"); //$NON-NLS-1$ public static final Image ANNOTATION_IMAGE = getImage("annotation.png"); //$NON-NLS-1$ public static final Image CDI_EVENT_IMAGE = getImage("event.png"); //$NON-NLS-1$ public static final Image QUICKFIX_ADD = getImage("quickfixes/cdi_add.png"); //$NON-NLS-1$ public static final Image QUICKFIX_REMOVE = getImage("quickfixes/cdi_remove.png"); //$NON-NLS-1$ public static final Image QUICKFIX_EDIT = getImage("quickfixes/cdi_edit.png"); //$NON-NLS-1$ public static final Image QUICKFIX_CHANGE = getImage("quickfixes/cdi_change.png"); //$NON-NLS-1$ public static final String WELD_WIZARD_IMAGE_PATH = "wizard/WeldWizBan.gif"; //$NON-NLS-1$ public static Image getImage(String key) { return INSTANCE.createImageDescriptor(key).createImage(); } public static ImageDescriptor getImageDescriptor(String key) { return INSTANCE.createImageDescriptor(key); } public static void setImageDescriptors(IAction action, String iconName) { action.setImageDescriptor(INSTANCE.createImageDescriptor(iconName)); } public static CDIImages getInstance() { return INSTANCE; } private URL baseUrl; private CDIImages parentRegistry; protected CDIImages(URL registryUrl, CDIImages parent){ if(registryUrl == null) throw new IllegalArgumentException(CDICoreMessages.CDI_IMAGESBASE_URL_FOR_IMAGE_REGISTRY_CANNOT_BE_NULL); baseUrl = registryUrl; parentRegistry = parent; } protected CDIImages(URL url){ this(url,null); } public Image getImageByFileName(String key) { return createImageDescriptor(key).createImage(); } public ImageDescriptor createImageDescriptor(String key) { try { return ImageDescriptor.createFromURL(makeIconFileURL(key)); } catch (MalformedURLException e) { if(parentRegistry == null) { return ImageDescriptor.getMissingImageDescriptor(); } else { return parentRegistry.createImageDescriptor(key); } } } private URL makeIconFileURL(String name) throws MalformedURLException { if (name == null) throw new MalformedURLException(CDICoreMessages.CDI_IMAGESIMAGE_NAME_CANNOT_BE_NULL); return new URL(baseUrl, name); } public static Image getImageByElement(ICDIElement element){ if(element instanceof IClassBean){ return BEAN_CLASS_IMAGE; }else if(element instanceof IInjectionPoint){ return INJECTION_POINT_IMAGE; }else if(element instanceof ICDIAnnotation){ return ANNOTATION_IMAGE; }else if(element instanceof EventBean){ return CDI_EVENT_IMAGE; }else if(element instanceof IBeanMethod){ return BEAN_METHOD_IMAGE; }else if(element instanceof IBeanField){ return BEAN_FIELD_IMAGE; } return WELD_IMAGE; } }
false
false
null
null
diff --git a/src/main/org/codehaus/groovy/ant/UberCompileTask.java b/src/main/org/codehaus/groovy/ant/UberCompileTask.java index ce9e18230..277e0ce55 100644 --- a/src/main/org/codehaus/groovy/ant/UberCompileTask.java +++ b/src/main/org/codehaus/groovy/ant/UberCompileTask.java @@ -1,251 +1,251 @@ /* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ant; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Task; import org.apache.tools.ant.taskdefs.Javac; import org.apache.tools.ant.types.FileSet; import org.apache.tools.ant.types.Path; import org.apache.tools.ant.types.Reference; import java.io.File; import java.io.IOException; /** * Compiles Java and Groovy source files. * * This works by invoking the {@link GenerateStubsTask} task, then the * {@link Javac} task and then the {@link GroovycTask}. Each task can * be configured by creating a nested element. Common configuration * such as the source dir and classpath is picked up from this tasks * configuration. * * @version $Id$ * @author <a href="mailto:jason@planet57.com">Jason Dillon</a> */ public class UberCompileTask extends Task { private final LoggingHelper log = new LoggingHelper(this); private Path src; private File destdir; private Path classpath; private GenStubsAdapter genStubsTask; private GroovycAdapter groovycTask; private JavacAdapter javacTask; public Path createSrc() { if (src == null) { src = new Path(getProject()); } return src.createPath(); } public void setSrcdir(final Path dir) { assert dir != null; if (src == null) { src = dir; } else { src.append(dir); } } public Path getSrcdir() { return src; } public void setDestdir(final File dir) { assert dir != null; this.destdir = dir; } public void setClasspath(final Path path) { assert path != null; if (classpath == null) { classpath = path; } else { classpath.append(path); } } public Path getClasspath() { return classpath; } public Path createClasspath() { if (classpath == null) { classpath = new Path(getProject()); } return classpath.createPath(); } public void setClasspathRef(final Reference r) { assert r != null; createClasspath().setRefid(r); } public GenStubsAdapter createGeneratestubs() { if (genStubsTask == null) { genStubsTask = new GenStubsAdapter(); genStubsTask.setProject(getProject()); } return genStubsTask; } public GroovycAdapter createGroovyc() { if (groovycTask == null) { groovycTask = new GroovycAdapter(); groovycTask.setProject(getProject()); } return groovycTask; } public JavacAdapter createJavac() { if (javacTask == null) { javacTask = new JavacAdapter(); javacTask.setProject(getProject()); } return javacTask; } protected void validate() throws BuildException { if (src == null) { throw new BuildException("Missing attribute: srcdir (or one or more nested <src> elements).", getLocation()); } if (destdir == null) { throw new BuildException("Missing attribute: destdir", getLocation()); } if (!destdir.exists()) { throw new BuildException("Destination directory does not exist: " + destdir, getLocation()); } } public void execute() throws BuildException { validate(); FileSet fileset; GenStubsAdapter genstubs = createGeneratestubs(); genstubs.classpath = classpath; genstubs.src = src; if (genstubs.destdir == null) { genstubs.destdir = createTempDir(); } fileset = genstubs.getFileSet(); if (!fileset.hasPatterns()) { genstubs.createInclude().setName("**/*.java"); genstubs.createInclude().setName("**/*.groovy"); } - // Append the stubs dir to the classpath for other tasks - classpath.createPathElement().setLocation(genstubs.destdir); - JavacAdapter javac = createJavac(); javac.setSrcdir(src); javac.setDestdir(destdir); javac.setClasspath(classpath); fileset = javac.getFileSet(); if (!fileset.hasPatterns()) { - genstubs.createInclude().setName("**/*.java"); + javac.createInclude().setName("**/*.java"); } + // Include the stubs in the Javac compilation + javac.createSrc().createPathElement().setLocation(genstubs.destdir); + GroovycAdapter groovyc = createGroovyc(); groovyc.classpath = classpath; groovyc.src = src; groovyc.destdir = destdir; fileset = groovyc.getFileSet(); if (!fileset.hasPatterns()) { - genstubs.createInclude().setName("**/*.groovy"); + groovyc.createInclude().setName("**/*.groovy"); } // Invoke each task in the right order genstubs.execute(); javac.execute(); groovyc.execute(); } private File createTempDir() { try { File dir = File.createTempFile("groovy-", "stubs"); dir.delete(); dir.mkdirs(); return dir; } catch (IOException e) { throw new BuildException(e, getLocation()); } } // // Nested task adapters // private class GenStubsAdapter extends GenerateStubsTask { public FileSet getFileSet() { return super.getImplicitFileSet(); } public String getTaskName() { return UberCompileTask.this.getTaskName() + ":genstubs"; } } private class JavacAdapter extends Javac { public FileSet getFileSet() { return super.getImplicitFileSet(); } public String getTaskName() { return UberCompileTask.this.getTaskName() + ":javac"; } } private class GroovycAdapter extends GroovycTask { public FileSet getFileSet() { return super.getImplicitFileSet(); } public String getTaskName() { return UberCompileTask.this.getTaskName() + ":groovyc"; } } } \ No newline at end of file
false
false
null
null
diff --git a/amibe/src/org/jcae/mesh/amibe/ds/HalfEdge.java b/amibe/src/org/jcae/mesh/amibe/ds/HalfEdge.java index 841e1bde..0ad12cde 100644 --- a/amibe/src/org/jcae/mesh/amibe/ds/HalfEdge.java +++ b/amibe/src/org/jcae/mesh/amibe/ds/HalfEdge.java @@ -1,1251 +1,1250 @@ /* jCAE stand for Java Computer Aided Engineering. Features are : Small CAD modeler, Finite element mesher, Plugin architecture. Copyright (C) 2006, by EADS CRC Copyright (C) 2007, by EADS France This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.jcae.mesh.amibe.ds; import org.jcae.mesh.amibe.traits.HalfEdgeTraitsBuilder; import org.jcae.mesh.amibe.metrics.Matrix3D; import java.util.Collection; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; import java.util.NoSuchElementException; import java.io.Serializable; import org.apache.log4j.Logger; public class HalfEdge extends AbstractHalfEdge implements Serializable { private static Logger logger = Logger.getLogger(HalfEdge.class); private TriangleHE tri; private byte localNumber = 8; private int attributes = 8; // For non manifold edges, a virtual triangle is added // Triangle(outerVertex, edge.origin(), edge.destination()) // and sym points to an edge of this triangle. It is said to // be outer. The list of adjacent HalfEdge is stored in this // triangle, more specifically in sym.next.sym // This is very handy because all HalfEdge of non-outer triangles // can be considered as being manifold. // TODO: replace ArrayList by HalfEdge[] private Object sym = null; private HalfEdge next = null; private static final int [] next3 = { 1, 2, 0 }; private static final int [] prev3 = { 2, 0, 1 }; private static final double [][] temp = new double[4][3]; public HalfEdge (HalfEdgeTraitsBuilder htb, TriangleHE tri, byte localNumber, byte attributes) { super(htb); this.tri = tri; this.localNumber = localNumber; this.attributes = attributes; } public void copy(HalfEdge src) { // Do not override tri! localNumber = src.localNumber; attributes = src.attributes; sym = src.sym; } /** * Return the triangle tied to this object. * * @return the triangle tied to this object. */ @Override public final Triangle getTri() { return tri; } /** * Return the edge local number. * * @return the edge local number. */ @Override public final int getLocalNumber() { return localNumber; } public final int getAttributes() { return attributes; } /** * Set the edge tied to this object. * * @param e the edge tied to this object. */ @Override public final void glue(AbstractHalfEdge e) { HEglue((HalfEdge) e); } private final void HEglue(HalfEdge s) { sym = s; if (s != null) s.sym = this; } public final HalfEdge notOriented() { assert sym instanceof HalfEdge; if (sym != null && sym.hashCode() < hashCode()) return (HalfEdge) sym; return this; } /** * Get the symmetric edge. */ @Override public final Object getAdj() { return sym; } /** * Set the sym link. */ @Override public final void setAdj(Object e) { sym = e; } private final HalfEdge HEsym() { return (HalfEdge) sym; } @Override public final AbstractHalfEdge sym() { return (AbstractHalfEdge) sym; } @Override public final AbstractHalfEdge sym(AbstractHalfEdge that) { that = (AbstractHalfEdge) sym; return that; } /** * Move to the next edge. */ @Override public final AbstractHalfEdge next() { return next; } @Override public final AbstractHalfEdge next(AbstractHalfEdge that) { that = next; return that; } /** * Move to the previous edge. */ @Override public final AbstractHalfEdge prev() { return next.next; } @Override public final AbstractHalfEdge prev(AbstractHalfEdge that) { that = next.next; return that; } /** * Move counterclockwise to the following edge with the same origin. */ @Override public final AbstractHalfEdge nextOrigin() { return next.next.sym(); } @Override public final AbstractHalfEdge nextOrigin(AbstractHalfEdge that) { that = next.next.sym(); return that; } /** * Move counterclockwise to the previous edge with the same origin. */ public final AbstractHalfEdge prevOrigin() { return HEsym().next; } public final AbstractHalfEdge prevOrigin(AbstractHalfEdge that) { that = HEsym().next; return that; } /** * Move counterclockwise to the following edge with the same * destination. */ public final AbstractHalfEdge nextDest() { return HEsym().prev(); } public final AbstractHalfEdge nextDest(AbstractHalfEdge that) { that = HEsym().prev(); return that; } /** * Move counterclockwise to the previous edge with the same * destination. */ public final AbstractHalfEdge prevDest() { return next.sym(); } public final AbstractHalfEdge prevDest(AbstractHalfEdge that) { that = next.sym(); return that; } /** * Move counterclockwise to the following edge with the same apex. */ public final AbstractHalfEdge nextApex() { return next.HEsym().next; } public final AbstractHalfEdge nextApex(AbstractHalfEdge that) { that = next.HEsym().next; return that; } /** * Move clockwise to the previous edge with the same apex. */ public final AbstractHalfEdge prevApex() { return next.next.HEsym().prev(); } public final AbstractHalfEdge prevApex(AbstractHalfEdge that) { that = next.next.HEsym().prev(); return that; } // The following 3 methods change the underlying triangle. // So they also modify all HalfEdge bound to this one. /** * Sets the start vertex of this edge. * * @param v the start vertex of this edge. */ public final void setOrigin(Vertex v) { tri.vertex[next3[localNumber]] = v; } /** * Sets the end vertex of this edge. * * @param v the end vertex of this edge. */ public final void setDestination(Vertex v) { tri.vertex[prev3[localNumber]] = v; } /** * Sets the apex of this edge. * * @param v the apex of this edge. */ public final void setApex(Vertex v) { tri.vertex[localNumber] = v; } /** * Set the next link. */ public final void setNext(HalfEdge e) { next = e; } /** * Check if some attributes of this edge are set. * * @param attr the attributes to check * @return <code>true</code> if this HalfEdge has all these * attributes set, <code>false</code> otherwise. */ @Override public final boolean hasAttributes(int attr) { return (attributes & attr) != 0; } /** * Set attributes of this edge. * * @param attr the attribute of this edge. */ @Override public final void setAttributes(int attr) { attributes |= attr; } /** * Reset attributes of this edge. * * @param attr the attributes of this edge to clear out. */ @Override public final void clearAttributes(int attr) { attributes &= ~attr; } /** * Returns the start vertex of this edge. * * @return the start vertex of this edge. */ @Override public final Vertex origin() { return tri.vertex[next3[localNumber]]; } /** * Returns the end vertex of this edge. * * @return the end vertex of this edge. */ @Override public final Vertex destination() { return tri.vertex[prev3[localNumber]]; } /** * Returns the apex of this edge. * * @return the apex of this edge. */ @Override public final Vertex apex() { return tri.vertex[localNumber]; } /** * Move counterclockwise to the following edge with the same origin. * If a boundary is reached, loop backward until another * boundary is found and start again from there. */ @Override public final AbstractHalfEdge nextOriginLoop() { HalfEdge ret = this; if (ret.hasAttributes(OUTER) && ret.hasAttributes(BOUNDARY | NONMANIFOLD)) { // Loop clockwise to another boundary // and start again from there. do { ret = (HalfEdge) ret.prevOrigin(); } while (!ret.hasAttributes(OUTER)); } else ret = (HalfEdge) ret.nextOrigin(); return ret; } /** * Move counterclockwise to the following edge with the same apex. * If a boundary is reached, loop backward until another * boundary is found and start again from there. */ public final HalfEdge nextApexLoop() { HalfEdge ret = this; if (ret.hasAttributes(OUTER) && ret.next.next.hasAttributes(BOUNDARY | NONMANIFOLD)) { // Loop clockwise to another boundary // and start again from there. do { ret = (HalfEdge) ret.prevApex(); } while (!ret.hasAttributes(AbstractHalfEdge.OUTER)); } else ret = (HalfEdge) ret.nextApex(); return ret; } /** * Checks the dihedral angle of an edge. * Warning: this method uses temp[0], temp[1], temp[2] and temp[3] temporary arrays. * * @param minCos if the dot product of the normals to adjacent * triangles is lower than monCos, then <code>-1.0</code> is * returned. * @return the minimum quality of the two trianglles generated * by swapping this edge. */ public final double checkSwap3D(double minCos) { double invalid = -1.0; // Check if there is an adjacent edge if (hasAttributes(OUTER | BOUNDARY | NONMANIFOLD)) return invalid; // Check for coplanarity HalfEdge f = HEsym(); Vertex o = origin(); Vertex d = destination(); Vertex a = apex(); double s1 = Matrix3D.computeNormal3D(o.getUV(), d.getUV(), a.getUV(), temp[0], temp[1], temp[2]); double s2 = Matrix3D.computeNormal3D(f.tri.vertex[0].getUV(), f.tri.vertex[1].getUV(), f.tri.vertex[2].getUV(), temp[0], temp[1], temp[3]); if (Matrix3D.prodSca(temp[2], temp[3]) < minCos) return invalid; // Check for quality improvement Vertex n = f.apex(); // Check for inverted triangles o.outer3D(n, a, temp[0]); double s3 = 0.5 * Matrix3D.prodSca(temp[2], temp[0]); if (s3 <= 0.0) return invalid; d.outer3D(a, n, temp[0]); double s4 = 0.5 * Matrix3D.prodSca(temp[2], temp[0]); if (s4 <= 0.0) return invalid; double p1 = o.distance3D(d) + d.distance3D(a) + a.distance3D(o); double p2 = d.distance3D(o) + o.distance3D(n) + n.distance3D(d); // No need to multiply by 12.0 * Math.sqrt(3.0) double Qbefore = Math.min(s1/p1/p1, s2/p2/p2); double p3 = o.distance3D(n) + n.distance3D(a) + a.distance3D(o); double p4 = d.distance3D(a) + a.distance3D(n) + n.distance3D(d); double Qafter = Math.min(s3/p3/p3, s4/p4/p4); if (Qafter > Qbefore) return Qafter; return invalid; } /** * Swaps an edge. * * This routine swaps an edge (od) to (na). (on) is returned * instead of (na), because this helps turning around o, eg. * at the end of {@link org.jcae.mesh.amibe.patch.VirtualHalfEdge2D#split3}. * * d d * . . * /|\ / \ * / | \ / \ * / | \ / \ * a + | + n ---&gt; a +-------+ n * \ | / \ / * \ | / \ / * \|/ \ / * ' ' * o o * @return swapped edge * @throws IllegalArgumentException if edge is on a boundary or belongs * to an outer triangle. * @see Mesh#edgeSwap */ @Override protected final AbstractHalfEdge swap() { return HEswap(); } private final HalfEdge HEswap() { if (hasAttributes(OUTER | BOUNDARY | NONMANIFOLD)) throw new IllegalArgumentException("Cannot swap "+this); Vertex o = origin(); Vertex d = destination(); Vertex a = apex(); /* * d d * . . * /|\ / \ * s0 / | \ s3 s0 / \ s3 * / | \ / T2 \ * a + T1|T2 + n ---> a +-------+ n * \ | / \ T1 / * s1 \ | / s2 s1 \ / s2 * \|/ \ / * ' ' * o o */ // T1 = (oda) --> (ona) // T2 = (don) --> (dan) HalfEdge [] e = new HalfEdge[6]; e[0] = next; e[1] = next.next; e[2] = HEsym().next; e[3] = HEsym().next.next; e[4] = this; e[5] = HEsym(); // Clear SWAPPED flag for all edges of the 2 triangles for (int i = 0; i < 6; i++) { e[i].clearAttributes(AbstractHalfEdge.SWAPPED); e[i].HEsym().clearAttributes(AbstractHalfEdge.SWAPPED); } // Adjust vertices Vertex n = e[5].apex(); e[4].setDestination(n); // (ona) e[5].setDestination(a); // (dan) // Adjust edge informations // T1: e[1] is unchanged TriangleHE T1 = e[1].tri; e[1].next = e[2]; e[2].next = e[4]; e[4].next = e[1]; e[2].tri = e[4].tri = T1; e[2].localNumber = (byte) next3[e[1].localNumber]; e[4].localNumber = (byte) prev3[e[1].localNumber]; // T2: e[3] is unchanged TriangleHE T2 = e[3].tri; e[3].next = e[0]; e[0].next = e[5]; e[5].next = e[3]; e[0].tri = e[5].tri = T2; e[0].localNumber = (byte) next3[e[3].localNumber]; e[5].localNumber = (byte) prev3[e[3].localNumber]; // Adjust edge pointers of triangles if (e[1].localNumber == 1) T1.setHalfEdge(e[4]); else if (e[1].localNumber == 2) T1.setHalfEdge(e[2]); if (e[3].localNumber == 1) T2.setHalfEdge(e[5]); else if (e[3].localNumber == 2) T2.setHalfEdge(e[0]); // Mark new edges e[4].attributes = 0; e[5].attributes = 0; e[4].setAttributes(AbstractHalfEdge.SWAPPED); e[5].setAttributes(AbstractHalfEdge.SWAPPED); // Fix links to triangles o.setLink(T1); d.setLink(T2); // Be consistent with AbstractHalfEdge.swap() return e[2]; } /** * Return the area of this triangle. * @return the area of this triangle. * Warning: this method uses temp[0], temp[1] and temp[2] temporary arrays. */ @Override public double area() { double [] p0 = origin().getUV(); double [] p1 = destination().getUV(); double [] p2 = apex().getUV(); temp[1][0] = p1[0] - p0[0]; temp[1][1] = p1[1] - p0[1]; temp[1][2] = p1[2] - p0[2]; temp[2][0] = p2[0] - p0[0]; temp[2][1] = p2[1] - p0[1]; temp[2][2] = p2[2] - p0[2]; Matrix3D.prodVect3D(temp[1], temp[2], temp[0]); return 0.5 * Matrix3D.norm(temp[0]); } /** * Checks that triangles are not inverted if origin vertex is moved. * * @param newpt the new position to be checked. * @return <code>false</code> if the new position produces * an inverted triangle, <code>true</code> otherwise. * Warning: this method uses temp[0], temp[1], temp[2] and temp[3] temporary arrays. */ @Override public final boolean checkNewRingNormals(double [] newpt) { return checkNewRingNormals(newpt, null, null); } /** * Check whether an edge can be contracted into a given vertex. * * @param n the resulting vertex * @return <code>true</code> if this edge can be contracted into the single vertex n, <code>false</code> otherwise. * @see Mesh#canCollapseEdge */ @Override protected final boolean canCollapse(AbstractVertex n) { // Be consistent with collapse() if (hasAttributes(AbstractHalfEdge.OUTER)) return false; HalfEdge s = HEsym(); // Check that origin vertex can be moved if (!checkInversionSameFan((Vertex) n, tri, s.tri)) return false; // Check that destination vertex can be moved if (!s.hasAttributes(OUTER) && !s.checkInversionSameFan((Vertex) n, tri, s.tri)) return false; // Topology check. // See in AbstractHalfEdgeTest.buildMeshTopo() why this // check is needed. Collection<Vertex> link = origin().getNeighboursNodes(); link.retainAll(destination().getNeighboursNodes()); return link.size() < 3; } private final boolean checkInversionSameFan(Vertex n, Triangle t1, Triangle t2) { // If both adjacent edges are on a boundary, do not contract if (next.hasAttributes(BOUNDARY | NONMANIFOLD) && next.next.hasAttributes(BOUNDARY | NONMANIFOLD)) return false; double [] xn = n.getUV(); if (!checkNewRingNormals(n.getUV(), t1, t2)) return false; return true; } private final boolean checkNewRingNormals(double [] xn, Triangle t1, Triangle t2) { HalfEdge f = next; Vertex o = f.origin(); + if (o.getLink() instanceof Triangle[]) + return false; double [] xa = f.apex().getUV(); do { - // TODO: allow contracting edges when a vertex is non manifold - if (f.origin().getLink() instanceof Triangle[]) - return false; if (f.tri != t1 && f.tri != t2 && !f.hasAttributes(OUTER)) { double [] x1 = f.origin().getUV(); double area = Matrix3D.computeNormal3DT(x1, f.destination().getUV(), xa, temp[0], temp[1], temp[2]); for (int i = 0; i < 3; i++) temp[3][i] = xn[i] - x1[i]; // Two triangles are removed when an edge is contracted. // So normally triangle areas should increase. If they // decrease significantly, there may be a problem. if (Matrix3D.prodSca(temp[3], temp[2]) >= - area) return false; } f = f.nextApexLoop(); } while (f.origin() != o); return true; } /** * Contract an edge. * * @param m mesh * @param n the resulting vertex * @return edge starting from <code>n</code> and pointing to original apex * @throws IllegalArgumentException if edge belongs to an outer triangle, * because there would be no valid return value. User must then run this * method against symmetric edge, this is not done automatically. * @see Mesh#edgeCollapse */ @Override protected final AbstractHalfEdge collapse(AbstractMesh m, AbstractVertex n) { if (hasAttributes(AbstractHalfEdge.OUTER)) throw new IllegalArgumentException("Cannot contract "+this); Vertex o = origin(); Vertex d = destination(); Vertex v = (Vertex) n; assert o.isWritable() && d.isWritable(): "Cannot contract "+this; if (logger.isDebugEnabled()) logger.debug("contract ("+o+" "+d+")"); // Replace o by n in all incident triangles if (o.getLink() instanceof Triangle) replaceEndpointsSameFan(v); else replaceEndpointsNonManifold(o, v); // Replace d by n in all incident triangles HalfEdge e = HEsym(); if (d.getLink() instanceof Triangle) e.replaceEndpointsSameFan(v); else replaceEndpointsNonManifold(d, v); // Set v links deepCopyVertexLinks(o, d, v); if (logger.isDebugEnabled()) logger.debug("new point: "+v); if (!hasAttributes(AbstractHalfEdge.NONMANIFOLD)) return HEcollapseSameFan((Mesh) m, v, true); // Edge is non-manifold assert e.hasAttributes(AbstractHalfEdge.OUTER); AbstractHalfEdge ret = null; // HEcollapseSameFan may modify LinkedHashMap structure // used by fanIterator(), we need a copy. ArrayList<AbstractHalfEdge> copy = new ArrayList<AbstractHalfEdge>(); for (Iterator<AbstractHalfEdge> it = fanIterator(); it.hasNext(); ) copy.add(it.next()); for (AbstractHalfEdge ah: copy) { HalfEdge h = (HalfEdge) ah; assert !h.hasAttributes(AbstractHalfEdge.OUTER); if (h == this) ret = h.HEcollapseSameFan((Mesh) m, v, false); else h.HEcollapseSameFan((Mesh) m, v, false); } assert ret != null; return ret; } private HalfEdge HEcollapseSameFan(Mesh m, Vertex n, boolean manifold) { /* * V1 V1 * V3+-------+-------+ V4 V3 +------+------+ V4 * \ t3 / \ t4 / \ t3 | t4 / * \ / \ / \ | / * \ / t1 \ / \ | / * o +-------+ d ------> n + * / \ t2 / \ / | \ * / \ / \ / | \ * / t5 \ / t6 \ / t5 | t6 \ * +-------+-------+ +------+------+ * V5 V2 V6 V5 V2 V6 */ // this = (odV1) // Update adjacency links. For clarity, o and d are // written instead of n. HalfEdge e, f, s; e = this; Triangle t1 = e.tri; e = e.HEsym(); Triangle t2 = e.tri; e = e.HEsym(); e = next; // (dV1o) int attr4 = e.attributes; s = e.HEsym(); // (V1dV4) e = e.next; // (V1od) int attr3 = e.attributes; f = e.HEsym(); // (oV1V3) if (f != null && f.hasAttributes(AbstractHalfEdge.NONMANIFOLD)) { // e is listed in adjacency list and // has to be replaced by s e.replaceEdgeLinks(s); f.HEglue(s); } else if (s != null && s.hasAttributes(AbstractHalfEdge.NONMANIFOLD)) { // s.HEsym() is listed in adjacency list and // has to be replaced by f s.HEsym().replaceEdgeLinks(f); s.HEglue(f); } else if (f != null) f.HEglue(s); else if (s != null) s.HEglue(null); if (f != null) f.attributes |= attr4; if (s != null) s.attributes |= attr3; if (!hasAttributes(AbstractHalfEdge.OUTER)) { TriangleHE t34 = f.tri; if (t34.isOuter()) t34 = s.tri; assert !t34.isOuter() : s+"\n"+f; replaceVertexLinks(f.destination(), t1, t2, t34); replaceVertexLinks(n, t1, t2, t34); } e = e.next; // (odV1) e = e.HEsym(); // (doV2) if (manifold) { e = e.next; // (oV2d) int attr5 = e.attributes; s = e.HEsym(); // (V2oV5) e = e.next; // (V2do) int attr6 = e.attributes; f = e.HEsym(); // (dV2V6) if (f != null && f.hasAttributes(AbstractHalfEdge.NONMANIFOLD)) { // e is listed in adjacency list and // has to be replaced by s e.replaceEdgeLinks(s); f.HEglue(s); } else if (s != null && s.hasAttributes(AbstractHalfEdge.NONMANIFOLD)) { // s.HEsym() is listed in adjacency list and // has to be replaced by f s.HEsym().replaceEdgeLinks(f); s.HEglue(f); } else if (f != null) f.HEglue(s); else if (s != null) s.HEglue(null); if (f != null) f.attributes |= attr5; if (s != null) s.attributes |= attr6; if (!e.hasAttributes(AbstractHalfEdge.OUTER)) { TriangleHE t56 = s.tri; if (t56.isOuter()) t56 = f.tri; assert !t56.isOuter(); replaceVertexLinks(s.origin(), t1, t2, t56); replaceVertexLinks(n, t1, t2, t56); } e = e.next; // (doV2) } else { assert e.hasAttributes(AbstractHalfEdge.OUTER); } // Must be called before T2 is removed s = e.HEsym(); // (odV1) // Remove T2 m.remove(e.tri); // Must be called before T1 is removed e = s.next.HEsym().HEsym(); // (oV1V3) // Remove T1 m.remove(s.tri); // Check that all o and d instances have been removed // This is costful, it is disabled by default but may // be enabled when debugging. /* boolean checkVertices = true; if (checkVertices) { for (AbstractTriangle at: m.getTriangles()) { Triangle t = (Triangle) at; assert t.vertex[0] != o && t.vertex[1] != o && t.vertex[2] != o : "Vertex "+o+" found in "+t; assert t.vertex[0] != d && t.vertex[1] != d && t.vertex[2] != d : "Vertex "+d+" found in "+t; } } */ // By convention, edge is moved into (dV4V1), but this may change. // This is why V1 cannot be m.outerVertex, otherwise we cannot // ensure that return HalfEdge is (oV1V3) return e; } private void replaceEndpointsSameFan(Vertex n) { HalfEdge e = this; Vertex d = destination(); do { e.setOrigin(n); e = (HalfEdge) e.nextOriginLoop(); } while (e.destination() != d); } private static final void replaceEndpointsNonManifold(Vertex o, Vertex n) { Triangle [] oList = (Triangle []) o.getLink(); for (Triangle t: oList) { TriangleHE tHE = (TriangleHE) t; HalfEdge f = tHE.getHalfEdge(); if (f.origin() != o) f = (HalfEdge) f.next(); if (f.origin() != o) f = (HalfEdge) f.next(); assert f.origin() == o : ""+o+" not in "+f; f.replaceEndpointsSameFan(n); } } private static void replaceVertexLinks(Vertex o, Triangle oldT1, Triangle oldT2, Triangle newT) { if (o.getLink() instanceof Triangle) o.setLink(newT); else { Triangle [] tArray = (Triangle []) o.getLink(); for (int i = 0; i < tArray.length; i++) { if (tArray[i] == oldT1 || tArray[i] == oldT2) { logger.debug("replaceVertexLinks: "+tArray[i]+" --> "+newT); tArray[i] = newT; } } } } private static void deepCopyVertexLinks(Vertex o, Vertex d, Vertex v) { boolean ot = o.getLink() instanceof Triangle; boolean dt = d.getLink() instanceof Triangle; // Prepare vertex links first if (ot && dt) { v.setLink(d.getLink()); } else if (ot) { Triangle [] dList = (Triangle []) d.getLink(); Triangle [] nList = new Triangle[dList.length]; System.arraycopy(dList, 0, nList, 0, dList.length); v.setLink(nList); } else if (dt) { Triangle [] oList = (Triangle []) o.getLink(); Triangle [] nList = new Triangle [oList.length]; System.arraycopy(oList, 0, nList, 0, oList.length); v.setLink(nList); } else { // Vertex.setLinkFan() cannot be called here because fans from // o and d have to be merged. Triangle [] oList = (Triangle []) o.getLink(); Triangle [] dList = (Triangle []) d.getLink(); Triangle [] nList = new Triangle[oList.length+dList.length]; System.arraycopy(oList, 0, nList, 0, oList.length); System.arraycopy(dList, 0, nList, oList.length, dList.length); ArrayList<Triangle> res = new ArrayList<Triangle>(); Set<Triangle> allTriangles = new HashSet<Triangle>(); for (Triangle t: nList) { if (allTriangles.contains(t)) continue; allTriangles.add(t); res.add(t); AbstractHalfEdge h = t.getAbstractHalfEdge(); if (h.origin() != o) h = h.next(); if (h.origin() != o) h = h.next(); if (h.origin() == o) { // Add all triangles of the same fan to allTriangles AbstractHalfEdge both = null; Vertex end = h.destination(); do { h = h.nextOriginLoop(); allTriangles.add(h.getTri()); if (h.destination() == d) both = h; } while (h.destination() != end); if (both != null) { both = both.next(); end = both.destination(); do { both = both.nextOriginLoop(); allTriangles.add(both.getTri()); } while (both.destination() != end); } } if (h.origin() != d) h = h.next(); if (h.origin() != d) h = h.next(); if (h.origin() == d) { // Add all triangles of the same fan to allTriangles AbstractHalfEdge both = null; Vertex end = h.destination(); do { h = h.nextOriginLoop(); allTriangles.add(h.getTri()); if (h.destination() == o) both = h; } while (h.destination() != end); if (both != null) { both = both.next(); end = both.destination(); do { both = both.nextOriginLoop(); allTriangles.add(both.getTri()); } while (both.destination() != end); } } } v.setLink(new Triangle[res.size()]); res.toArray((Triangle[]) v.getLink()); } } private void replaceEdgeLinks(HalfEdge that) { // Current instance is a non-manifold edge which has been // replaced by 'that'. Replace all occurrences in adjacency // list. assert hasAttributes(AbstractHalfEdge.NONMANIFOLD) && !hasAttributes(AbstractHalfEdge.OUTER); HalfEdge e = this; final LinkedHashMap<Triangle, Integer> list = (LinkedHashMap<Triangle, Integer>) e.HEsym().next.sym; Integer I = list.get(tri); assert I != null && I.intValue() == localNumber; list.remove(tri); list.put(that.tri, int3[that.localNumber]); } /** * Split an edge. This is the opposite of {@link #collapse}. * * @param m mesh * @param n the resulting vertex * @see Mesh#vertexSplit */ @Override protected final AbstractHalfEdge split(AbstractMesh m, AbstractVertex n) { HEsplit((Mesh) m, (Vertex) n); return this; } private final void HEsplit(Mesh m, Vertex n) { /* * V1 V1 * /'\ /|\ * / \ / | \ * / h1 \ / | \ * / \ / n1| h1 \ * / t1 \ / t1 | t3 \ * o +-------------------+ d ---> o +---------+---------+ d * \ t2 / \ t2 | t4 / * \ / \ n2| h2 / * \ h2 / \ | / * \ / \ | / * \,/ \|/ * V2 V2 */ HalfEdge h1 = next; // (dV1o) HalfEdge h2 = HEsym().next.next;// (v2do) TriangleHE t1 = h1.tri; TriangleHE t2 = h2.tri; TriangleHE t3 = (TriangleHE) m.createTriangle(t1); TriangleHE t4 = (TriangleHE) m.createTriangle(t2); m.add(t3); m.add(t4); // (dV1) is not modified by this operation, so we move // h1 into t3 so that it does not need to be updated by // the caller. HalfEdge n1 = t3.getHalfEdge(); for (int i = h1.localNumber; i > 0; i--) n1 = n1.next; // Update forward links HalfEdge h1next = h1.next; h1.next = n1.next; h1.next.next.next = h1; n1.next = h1next; n1.next.next.next = n1; if (t1.getHalfEdge() == h1) { t1.setHalfEdge(n1); t3.setHalfEdge(h1); } // Update Triangle links n1.tri = t1; h1.tri = t3; // (dV2) is not modified by this operation, so we move // h2 into t4 so that it does not need to be updated by // the caller. HalfEdge n2 = t4.getHalfEdge(); for (int i = h2.localNumber; i > 0; i--) n2 = n2.next; // Update links HalfEdge h2next = h2.next; h2.next = n2.next; h2.next.next.next = h2; n2.next = h2next; n2.next.next.next = n2; if (t2.getHalfEdge() == h2) { t2.setHalfEdge(n2); t4.setHalfEdge(h2); } // Update Triangle links n2.tri = t2; h2.tri = t4; // Update vertices n1.setOrigin(n); n2.setDestination(n); h1.setApex(n); h2.setApex(n); if (t1.isOuter()) { n.setLink(t2); h1.origin().setLink(t4); } else { n.setLink(t1); h1.origin().setLink(t3); } h1.next.HEglue(n1); h2.next.next.HEglue(n2); h2.next.HEglue(h1.next.next); n2.next.HEglue(n1.next.next); // Clear BOUNDARY and NONMANIFOLD flags on inner edges h1.next.clearAttributes(BOUNDARY | NONMANIFOLD); n1.clearAttributes(BOUNDARY | NONMANIFOLD); h2.next.next.clearAttributes(BOUNDARY | NONMANIFOLD); n2.clearAttributes(BOUNDARY | NONMANIFOLD); } private final Iterator<AbstractHalfEdge> identityFanIterator() { final HalfEdge current = this; return new Iterator<AbstractHalfEdge>() { private boolean nextFan = true; public boolean hasNext() { return nextFan; } public AbstractHalfEdge next() { if (!nextFan) throw new NoSuchElementException(); nextFan = false; return current; } public void remove() { } }; } @Override public final Iterator<AbstractHalfEdge> fanIterator() { if (!hasAttributes(NONMANIFOLD)) return identityFanIterator(); HalfEdge e = this; logger.debug("Non manifold fan iterator"); if (!e.hasAttributes(AbstractHalfEdge.OUTER)) e = e.HEsym(); final LinkedHashMap<Triangle, Integer> list = (LinkedHashMap<Triangle, Integer>) e.next.sym; return new Iterator<AbstractHalfEdge>() { private Iterator<Map.Entry<Triangle, Integer>> it = list.entrySet().iterator(); public boolean hasNext() { return it.hasNext(); } public AbstractHalfEdge next() { Map.Entry<Triangle, Integer> entry = it.next(); HalfEdge f = (HalfEdge) entry.getKey().getAbstractHalfEdge(); int l = entry.getValue().intValue(); if (l == 1) f = (HalfEdge) f.next; else if (l == 2) f = (HalfEdge) f.next.next; return f; } public void remove() { } }; } @Override public String toString() { StringBuilder r = new StringBuilder(); r.append("hashCode: "+hashCode()); r.append("\nTriangle: "+tri.hashCode()); r.append("\nGroup: "+tri.getGroupId()); r.append("\nLocal number: "+localNumber); if (sym != null) { if (sym instanceof HalfEdge) { HalfEdge e = (HalfEdge) sym; r.append("\nSym: "+e.tri.hashCode()+"["+e.localNumber+"]"); } else { LinkedHashMap<Triangle, Integer> list = (LinkedHashMap<Triangle, Integer>) sym; r.append("\nSym: ("); for (Map.Entry<Triangle, Integer> entry: list.entrySet()) r.append(entry.getKey().hashCode()+"["+entry.getValue().intValue()+"],"); r.setCharAt(r.length()-1, ')'); } } r.append("\nAttributes: "+Integer.toHexString(attributes)); r.append("\nVertices:"); r.append("\n Origin: "+origin()); r.append("\n Destination: "+destination()); r.append("\n Apex: "+apex()); return r.toString(); } }
false
false
null
null
diff --git a/paul/src/main/java/au/edu/uq/cmm/paul/queue/CopyingQueueFileManager.java b/paul/src/main/java/au/edu/uq/cmm/paul/queue/CopyingQueueFileManager.java index 2c752f6..599b1ce 100644 --- a/paul/src/main/java/au/edu/uq/cmm/paul/queue/CopyingQueueFileManager.java +++ b/paul/src/main/java/au/edu/uq/cmm/paul/queue/CopyingQueueFileManager.java @@ -1,184 +1,181 @@ /* * Copyright 2012, CMM, University of Queensland. * * This file is part of AclsLib. * * AclsLib is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * AclsLib is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with AclsLib. If not, see <http://www.gnu.org/licenses/>. */ package au.edu.uq.cmm.paul.queue; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import org.apache.commons.io.FilenameUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import au.edu.uq.cmm.paul.PaulConfiguration; public class CopyingQueueFileManager implements QueueFileManager { private static final Logger LOG = LoggerFactory.getLogger(CopyingQueueFileManager.class); private static final int RETRY = 10; private final File archiveDirectory; private final File captureDirectory; public CopyingQueueFileManager(PaulConfiguration config) { this.archiveDirectory = new File(config.getArchiveDirectory()); this.captureDirectory = new File(config.getCaptureDirectory()); } @Override public File enqueueFile(File source, String suffix, boolean regrabbing) throws QueueFileException, InterruptedException { // TODO - if the time taken to copy files is a problem, we could // potentially improve this by using NIO or memory mapped files. File target = generateUniqueFile(suffix, regrabbing); long size = source.length(); try (FileInputStream is = new FileInputStream(source); FileOutputStream os = new FileOutputStream(target)) { byte[] buffer = new byte[(int) Math.min(size, 8192)]; int nosRead; long totalRead = 0; while ((nosRead = is.read(buffer, 0, buffer.length)) > 0) { os.write(buffer, 0, nosRead); totalRead += nosRead; } // If these happen there is something wrong with our copying, locking // and / or file settling heuristics. if (totalRead != size) { LOG.error("Copied file size discrepancy - initial file size was " + size + "bytes but we copied " + totalRead + " bytes"); } else if (size != source.length()) { LOG.error("File size changed during copy - initial file size was " + size + "bytes and current size is " + source.length()); } LOG.info("Copied " + totalRead + " bytes from " + source + " to " + target); return target; } catch (IOException ex) { throw new QueueFileException("Problem while copying file to queue", ex); } } @Override public void enqueueFile(String contents, File target) throws QueueFileException { - if (!target.exists()) { - throw new QueueFileException("File " + target + " no longer exists"); - } - if (!isQueuedFile(target)) { - throw new QueueFileException("File " + target + " is not in the queue"); + if (target.exists()) { + throw new QueueFileException("File " + target + " already exists"); } try (Writer w = new FileWriter(target)) { w.write(contents); w.close(); } catch (IOException ex) { throw new QueueFileException("Problem while saving to a queue file", ex); } } @Override public File renameGrabbedDatafile(File file) throws QueueFileException { String extension = FilenameUtils.getExtension(file.toString()); if (!extension.isEmpty()) { extension = "." + extension; } for (int i = 0; i < RETRY; i++) { File newFile = generateUniqueFile(extension, false); if (!file.renameTo(newFile)) { if (!newFile.exists()) { throw new QueueFileException( "Unable to rename " + file + " to " + newFile); } } else { return newFile; } } throw new QueueFileException(RETRY + " attempts to rename file failed!"); } @Override public File archiveFile(File file) throws QueueFileException { if (!file.exists()) { throw new QueueFileException("File " + file + " no longer exists"); } if (!isQueuedFile(file)) { throw new QueueFileException("File " + file + " is not in the queue"); } File dest = new File(archiveDirectory, file.getName()); if (dest.exists()) { throw new QueueFileException("Archived file " + dest + " already exists"); } if (file.renameTo(dest)) { LOG.info("File " + file + " archived as " + dest); return dest; } else { throw new QueueFileException("File " + file + " could not be archived - " + "it remains in the queue area"); } } @Override public void removeFile(File file) throws QueueFileException { if (!file.exists()) { throw new QueueFileException("File " + file + " no longer exists"); } if (!isQueuedFile(file)) { throw new QueueFileException("File " + file + " is not in the queue"); } if (file.delete()) { LOG.info("File " + file + " deleted from queue area"); } else { throw new QueueFileException("File " + file + " could not be deleted from queue area"); } } @Override public boolean isCopiedFile(File file) { return file.getParentFile().equals(captureDirectory) || file.getParentFile().equals(archiveDirectory); } @Override public boolean isQueuedFile(File file) { return file.getParentFile().equals(captureDirectory); } @Override public boolean isArchivedFile(File file) { return file.getParentFile().equals(archiveDirectory); } @Override public File generateUniqueFile(String suffix, boolean regrabbing) throws QueueFileException { String template = regrabbing ? "regrabbed-%d-%d-%d%s" : "file-%d-%d-%d%s"; long threadId = Thread.currentThread().getId(); for (int i = 0; i < RETRY; i++) { long now = System.currentTimeMillis(); String name = String.format(template, now, threadId, i, suffix); File file = new File(captureDirectory, name); if (!file.exists()) { return file; } } throw new QueueFileException( RETRY + " attempts to generate a unique filename failed!"); } }
true
false
null
null
diff --git a/src/pt/up/fe/dceg/neptus/mra/api/ImcSidescanParser.java b/src/pt/up/fe/dceg/neptus/mra/api/ImcSidescanParser.java index 2332b2985..420c1ce15 100644 --- a/src/pt/up/fe/dceg/neptus/mra/api/ImcSidescanParser.java +++ b/src/pt/up/fe/dceg/neptus/mra/api/ImcSidescanParser.java @@ -1,184 +1,189 @@ /* * Copyright (c) 2004-2013 Universidade do Porto - Faculdade de Engenharia * Laboratório de Sistemas e Tecnologia Subaquática (LSTS) * All rights reserved. * Rua Dr. Roberto Frias s/n, sala I203, 4200-465 Porto, Portugal * * This file is part of Neptus, Command and Control Framework. * * Commercial Licence Usage * Licencees holding valid commercial Neptus licences may use this file * in accordance with the commercial licence agreement provided with the * Software or, alternatively, in accordance with the terms contained in a * written agreement between you and Universidade do Porto. For licensing * terms, conditions, and further information contact lsts@fe.up.pt. * * European Union Public Licence - EUPL v.1.1 Usage * Alternatively, this file may be used under the terms of the EUPL, * Version 1.1 only (the "Licence"), appearing in the file LICENCE.md * included in the packaging of this file. You may not use this work * except in compliance with the Licence. Unless required by applicable * law or agreed to in writing, software distributed under the Licence is * distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF * ANY KIND, either express or implied. See the Licence for the specific * language governing permissions and limitations at * https://www.lsts.pt/neptus/licence. * * For more information please see <http://lsts.fe.up.pt/neptus>. * * Author: José Correia * Feb 5, 2013 */ package pt.up.fe.dceg.neptus.mra.api; import java.util.ArrayList; import pt.up.fe.dceg.neptus.imc.IMCMessage; import pt.up.fe.dceg.neptus.imc.SonarData; import pt.up.fe.dceg.neptus.mp.SystemPositionAndAttitude; import pt.up.fe.dceg.neptus.mra.importers.IMraLog; import pt.up.fe.dceg.neptus.mra.importers.IMraLogGroup; import pt.up.fe.dceg.neptus.plugins.sidescan.SidescanConfig; /** * @author jqcorreia * */ public class ImcSidescanParser implements SidescanParser { IMraLog pingParser; IMraLog stateParser; long firstTimestamp = -1; long lastTimestamp = -1; long lastTimestampRequested; public ImcSidescanParser(IMraLogGroup source) { pingParser = source.getLog("SonarData"); stateParser = source.getLog("EstimatedState"); calcFirstAndLastTimestamps(); } private void calcFirstAndLastTimestamps() { IMCMessage msg; boolean firstFound = false; while((msg = getNextMessage(pingParser)) != null) { if(!firstFound) { firstFound = true; firstTimestamp = msg.getTimestampMillis(); } lastTimestamp = msg.getTimestampMillis(); } pingParser.firstLogEntry(); } @Override public long firstPingTimestamp() { return firstTimestamp; }; @Override public long lastPingTimestamp() { return lastTimestamp; } public ArrayList<Integer> getSubsystemList() { // For now just return a list with 1 item. In the future IMC will accomodate various SonarData subsystems ArrayList<Integer> l = new ArrayList<Integer>(); l.add(1); return l; }; public ArrayList<SidescanLine> getLinesBetween(long timestamp1, long timestamp2, int subsystem, SidescanConfig config) { // Preparation ArrayList<SidescanLine> list = new ArrayList<SidescanLine>(); double[] fData = null; if(lastTimestampRequested > timestamp1) { pingParser.firstLogEntry(); stateParser.firstLogEntry(); } lastTimestampRequested = timestamp1; - - IMCMessage ping = pingParser.getEntryAtOrAfter(timestamp1); + IMCMessage ping; + try { + ping = pingParser.getEntryAtOrAfter(timestamp1); + } + catch (Exception e) { + ping = null; + } if (ping == null) return list; if (ping.getInteger("type") != SonarData.TYPE.SIDESCAN.value()) { ping = getNextMessage(pingParser); //FIXME } IMCMessage state = stateParser.getEntryAtOrAfter(ping.getTimestampMillis()); // Null guards if (ping == null || state == null) return list; int range = ping.getInteger("range"); if (range == 0) range = ping.getInteger("max_range"); if (fData == null) { } while (ping == null || ping.getTimestampMillis() <= timestamp2) { // Null guards if (ping == null || state == null) break; fData = new double[ping.getRawData("data").length]; SystemPositionAndAttitude pose = new SystemPositionAndAttitude(); pose.setAltitude(state.getDouble("alt")); pose.getPosition().setLatitudeRads(state.getDouble("lat")); pose.getPosition().setLongitudeRads(state.getDouble("lon")); pose.getPosition().setOffsetNorth(state.getDouble("x")); pose.getPosition().setOffsetEast(state.getDouble("y")); pose.setRoll(state.getDouble("phi")); pose.setYaw(state.getDouble("psi")); pose.setP(state.getDouble("p")); pose.setQ(state.getDouble("q")); pose.setR(state.getDouble("r")); pose.setU(state.getDouble("u")); // Image building. Calculate and draw a line, scale and save it byte[] data = ping.getRawData("data"); for (int c = 0; c < data.length; c++) { fData[c] = (data[c] & 0xFF) / 255.0; } list.add(new SidescanLine(ping.getTimestampMillis(), range, pose, ping.getFloat("frequency"), fData)); ping = getNextMessage(pingParser); if (ping != null) state = stateParser.getEntryAtOrAfter(ping.getTimestampMillis()); } return list; } public long getCurrentTime() { return pingParser.currentTimeMillis(); } /** * Method used to get the next SonarData message of Sidescan Type * @param parser * @return */ public IMCMessage getNextMessage(IMraLog parser) { IMCMessage msg; while((msg = parser.nextLogEntry()) != null) { if(msg.getInteger("type") == SonarData.TYPE.SIDESCAN.value()) { return msg; } } return null; } }
true
false
null
null
diff --git a/source/de/anomic/plasma/plasmaHTCache.java b/source/de/anomic/plasma/plasmaHTCache.java index 18d083f85..496cd430e 100644 --- a/source/de/anomic/plasma/plasmaHTCache.java +++ b/source/de/anomic/plasma/plasmaHTCache.java @@ -1,1176 +1,1176 @@ // plasmaHTCache.java // ----------------------- // part of YaCy // (C) by Michael Peter Christen; mc@anomic.de // first published on http://www.anomic.de // Frankfurt, Germany, 2004 // // $LastChangedDate$ // $LastChangedRevision$ // $LastChangedBy$ // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Using this software in any meaning (reading, learning, copying, compiling, // running) means that you agree that the Author(s) is (are) not responsible // for cost, loss of data or any harm that may be caused directly or indirectly // by usage of this softare or this documentation. The usage of this software // is on your own risk. The installation and usage (starting/running) of this // software may allow other people or application to access your computer and // any attached devices and is highly dependent on the configuration of the // software which must be done by the user of the software; the author(s) is // (are) also not responsible for proper configuration and usage of the // software, even if provoked by documentation provided together with // the software. // // Any changes to this file according to the GPL as documented in the file // gpl.txt aside this file in the shipment you received can be done to the // lines that follows this copyright notice here, but changes must not be // done inside the copyright notive above. A re-distribution must contain // the intact and unchanged copyright notice. // Contributions and changes to the program code must be marked as such. /* Class documentation: This class has two purposes: 1. provide a object that carries path and header information that shall be used as objects within a scheduler's stack 2. static methods for a cache control and cache aging the class shall also be used to do a cache-cleaning and index creation */ package de.anomic.plasma; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.lang.StringBuffer; import java.net.InetAddress; import java.net.MalformedURLException; import java.util.Date; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.Map; import java.util.TreeMap; import java.util.regex.Matcher; import java.util.regex.Pattern; import de.anomic.http.httpc; import de.anomic.http.httpHeader; import de.anomic.index.indexEntryAttribute; import de.anomic.index.indexURL; import de.anomic.kelondro.kelondroBase64Order; import de.anomic.kelondro.kelondroDyn; import de.anomic.kelondro.kelondroMScoreCluster; import de.anomic.kelondro.kelondroMap; import de.anomic.net.URL; import de.anomic.plasma.cache.IResourceInfo; import de.anomic.plasma.cache.ResourceInfoFactory; import de.anomic.server.serverCodings; import de.anomic.server.serverFileUtils; import de.anomic.server.serverInstantThread; import de.anomic.server.serverSystem; import de.anomic.server.serverThread; import de.anomic.server.logging.serverLog; import de.anomic.tools.enumerateFiles; import de.anomic.yacy.yacySeed; public final class plasmaHTCache { private static final int stackLimit = 150; // if we exceed that limit, we do not check idle public static final long oneday = 1000 * 60 * 60 * 24; // milliseconds of a day kelondroMap responseHeaderDB = null; private final LinkedList cacheStack; private final TreeMap cacheAge; // a <date+hash, cache-path> - relation public long curCacheSize; public long maxCacheSize; public final File cachePath; public final serverLog log; public static final HashSet filesInUse = new HashSet(); // can we delete this file public String cacheLayout; public boolean cacheMigration; private ResourceInfoFactory objFactory; private serverThread cacheScanThread; public plasmaHTCache(File htCachePath, long maxCacheSize, int bufferkb, long preloadTime, String cacheLayout, boolean cacheMigration) { // this.switchboard = switchboard; this.log = new serverLog("HTCACHE"); this.cachePath = htCachePath; this.cacheLayout = cacheLayout; this.cacheMigration = cacheMigration; // create the object factory this.objFactory = new ResourceInfoFactory(); // reset old HTCache ? String[] list = this.cachePath.list(); if (list != null) { File object; for (int i = list.length - 1; i >= 0; i--) { object = new File(this.cachePath, list[i]); if (!object.isDirectory()) { continue; } if (!object.getName().equals("http") && !object.getName().equals("yacy") && !object.getName().equals("https") && !object.getName().equals("ftp")) { deleteOldHTCache(this.cachePath); break; } } } File testpath = new File(this.cachePath, "/http/"); list = testpath.list(); if (list != null) { File object; for (int i = list.length - 1; i >= 0; i--) { object = new File(testpath, list[i]); if (!object.isDirectory()) { continue; } if (!object.getName().equals("ip") && !object.getName().equals("other") && !object.getName().equals("www")) { deleteOldHTCache(this.cachePath); break; } } } testpath = null; // set/make cache path if (!htCachePath.exists()) { htCachePath.mkdirs(); } if (!htCachePath.isDirectory()) { // if the cache does not exists or is a file and not a directory, panic this.log.logSevere("the cache path " + htCachePath.toString() + " is not a directory or does not exists and cannot be created"); System.exit(0); } // open the response header database File dbfile = new File(this.cachePath, "responseHeader.db"); try { this.responseHeaderDB = new kelondroMap(new kelondroDyn(dbfile, bufferkb * 0x400, preloadTime, indexURL.urlHashLength, 150, '#')); } catch (IOException e) { this.log.logSevere("the request header database could not be opened: " + e.getMessage()); System.exit(0); } // init stack this.cacheStack = new LinkedList(); // init cache age and size management this.cacheAge = new TreeMap(); this.curCacheSize = 0; this.maxCacheSize = maxCacheSize; // start the cache startup thread // this will collect information about the current cache size and elements this.cacheScanThread = serverInstantThread.oneTimeJob(this, "cacheScan", this.log, 120000); } private void deleteOldHTCache(File directory) { String[] list = directory.list(); if (list != null) { File object; for (int i = list.length - 1; i >= 0; i--) { object = new File(directory, list[i]); if (object.isFile()) { object.delete(); } else { deleteOldHTCache(object); } } } directory.delete(); } public int size() { synchronized (this.cacheStack) { return this.cacheStack.size(); } } public int dbSize() { return this.responseHeaderDB.size(); } public int cacheNodeChunkSize() { return this.responseHeaderDB.cacheNodeChunkSize(); } public int cacheObjectChunkSize() { return this.responseHeaderDB.cacheObjectChunkSize(); } public int[] cacheNodeStatus() { return this.responseHeaderDB.cacheNodeStatus(); } public long[] cacheObjectStatus() { return this.responseHeaderDB.cacheObjectStatus(); } public void push(Entry entry) { synchronized (this.cacheStack) { this.cacheStack.add(entry); } } public Entry pop() { synchronized (this.cacheStack) { if (this.cacheStack.size() > 0) return (Entry) this.cacheStack.removeFirst(); return null; } } /** * This method changes the HTCache size.<br> * @param new cache size in bytes */ public void setCacheSize(long newCacheSize) { this.maxCacheSize = newCacheSize; } /** * This method returns the free HTCache size.<br> * @return the cache size in bytes */ public long getFreeSize() { return (this.curCacheSize >= this.maxCacheSize) ? 0 : this.maxCacheSize - this.curCacheSize; } public boolean writeResourceContent(URL url, byte[] array) { if (array == null) return false; File file = getCachePath(url); try { deleteFile(file); file.getParentFile().mkdirs(); serverFileUtils.write(array, file); } catch (FileNotFoundException e) { // this is the case of a "(Not a directory)" error, which should be prohibited // by the shallStoreCache() property. However, sometimes the error still occurs // In this case do nothing. this.log.logSevere("File storage failed (not a directory): " + e.getMessage()); return false; } catch (IOException e) { this.log.logSevere("File storage failed (IO error): " + e.getMessage()); return false; } writeFileAnnouncement(file); return true; } public void writeFileAnnouncement(File file) { synchronized (this.cacheAge) { if (file.exists()) { this.curCacheSize += file.length(); this.cacheAge.put(ageString(file.lastModified(), file), file); cleanup(); } } } public boolean deleteFile(URL url) { return deleteURLfromCache(url, "FROM"); } private boolean deleteURLfromCache(URL url, String msg) { if (deleteFileandDirs(getCachePath(url), msg)) { try { // As the file is gone, the entry in responseHeader.db is not needed anymore this.log.logFinest("Trying to remove responseHeader from URL: " + url.toString()); this.responseHeaderDB.remove(indexURL.urlHash(url)); } catch (IOException e) { this.log.logInfo("IOExeption removing response header from DB: " + e.getMessage(), e); } return true; } return false; } private boolean deleteFile(File obj) { if (obj.exists() && !filesInUse.contains(obj)) { long size = obj.length(); if (obj.delete()) { this.curCacheSize -= size; return true; } } return false; } private boolean deleteFileandDirs (File obj, String msg) { if (deleteFile(obj)) { this.log.logInfo("DELETED " + msg + " CACHE : " + obj.toString()); obj = obj.getParentFile(); // If the has been emptied, remove it // Loop as long as we produce empty driectoriers, but stop at HTCACHE while ((!(obj.equals(this.cachePath))) && (obj.isDirectory()) && (obj.list().length == 0)) { if (obj.delete()) this.log.logFine("DELETED EMPTY DIRECTORY : " + obj.toString()); obj = obj.getParentFile(); } return true; } return false; } private void cleanupDoIt(long newCacheSize) { File obj; synchronized (cacheAge) { Iterator iter = this.cacheAge.keySet().iterator(); while (iter.hasNext() && this.curCacheSize >= newCacheSize) { if (Thread.currentThread().isInterrupted()) return; Object key = iter.next(); obj = (File) this.cacheAge.get(key); if (obj != null) { if (filesInUse.contains(obj)) continue; this.log.logFinest("Trying to delete old file: " + obj.toString()); if (deleteFileandDirs (obj, "OLD")) { try { // As the file is gone, the entry in responseHeader.db is not needed anymore String urlHash = getHash(obj); if (urlHash != null) { this.log.logFinest("Trying to remove responseHeader for URLhash: " + urlHash); this.responseHeaderDB.remove(urlHash); } else { URL url = getURL(obj); if (url != null) { this.log.logFinest("Trying to remove responseHeader for URL: " + url.toString()); this.responseHeaderDB.remove(indexURL.urlHash(url)); } } } catch (IOException e) { this.log.logInfo("IOExeption removing response header from DB: " + e.getMessage(), e); } } } iter.remove(); } } } private void cleanup() { // clean up cache to have 4% (enough) space for next entries if (this.cacheAge.size() > 0 && this.curCacheSize >= this.maxCacheSize && this.maxCacheSize > 0) { cleanupDoIt(this.maxCacheSize - (this.maxCacheSize / 100) * 4); } } public void close() { // closing cache scan if still running if ((this.cacheScanThread != null) && (this.cacheScanThread.isAlive())) { this.cacheScanThread.terminate(true); } // closing DB try {this.responseHeaderDB.close();} catch (IOException e) {} } private String ageString(long date, File f) { StringBuffer sb = new StringBuffer(32); String s = Long.toHexString(date); for (int i = s.length(); i < 16; i++) sb.append('0'); sb.append(s); s = Integer.toHexString(f.hashCode()); for (int i = s.length(); i < 8; i++) sb.append('0'); sb.append(s); return sb.toString(); } public void cacheScan() { log.logConfig("STARTING HTCACHE SCANNING"); kelondroMScoreCluster doms = new kelondroMScoreCluster(); int fileCount = 0; enumerateFiles fileEnum = new enumerateFiles(this.cachePath, true, false, true, true); File dbfile = new File(this.cachePath, "responseHeader.db"); while (fileEnum.hasMoreElements()) { if (Thread.currentThread().isInterrupted()) return; fileCount++; File nextFile = (File) fileEnum.nextElement(); long nextFileModDate = nextFile.lastModified(); //System.out.println("Cache: " + dom(f)); doms.incScore(dom(nextFile)); this.curCacheSize += nextFile.length(); if (!dbfile.equals(nextFile)) this.cacheAge.put(ageString(nextFileModDate, nextFile), nextFile); try { Thread.sleep(10); } catch (InterruptedException e) { return; } } //System.out.println("%" + (String) cacheAge.firstKey() + "=" + cacheAge.get(cacheAge.firstKey())); long ageHours = 0; try { if (!this.cacheAge.isEmpty()) { ageHours = (System.currentTimeMillis() - Long.parseLong(((String) this.cacheAge.firstKey()).substring(0, 16), 16)) / 3600000; } } catch (NumberFormatException e) { //e.printStackTrace(); } this.log.logConfig("CACHE SCANNED, CONTAINS " + fileCount + " FILES = " + this.curCacheSize/1048576 + "MB, OLDEST IS " + ((ageHours < 24) ? (ageHours + " HOURS") : ((ageHours / 24) + " DAYS")) + " OLD"); cleanup(); log.logConfig("STARTING DNS PREFETCH"); // start to prefetch IPs from DNS String dom; long start = System.currentTimeMillis(); String result = ""; fileCount = 0; while ((doms.size() > 0) && (fileCount < 50) && ((System.currentTimeMillis() - start) < 60000)) { if (Thread.currentThread().isInterrupted()) return; dom = (String) doms.getMaxObject(); InetAddress ip = httpc.dnsResolve(dom); if (ip == null) continue; result += ", " + dom + "=" + ip.getHostAddress(); this.log.logConfig("PRE-FILLED " + dom + "=" + ip.getHostAddress()); fileCount++; doms.deleteScore(dom); // wait a short while to prevent that this looks like a DoS try { Thread.sleep(100); } catch (InterruptedException e) { return; } } if (result.length() > 2) this.log.logConfig("PRE-FILLED DNS CACHE, FETCHED " + fileCount + " ADDRESSES: " + result.substring(2)); } private String dom(File f) { String s = f.toString().substring(this.cachePath.toString().length() + 1); int p = s.indexOf("/"); if (p < 0) p = s.indexOf("\\"); if (p < 0) return null; // remove the protokoll s = s.substring(p + 1); p = s.indexOf("/"); if (p < 0) p = s.indexOf("\\"); if (p < 0) return null; String prefix = new String(""); if (s.startsWith("www")) prefix = new String("www."); // remove the www|other|ip directory s = s.substring(p + 1); p = s.indexOf("/"); if (p < 0) p = s.indexOf("\\"); if (p < 0) return null; int e = s.indexOf("!"); if ((e > 0) && (e < p)) p = e; // strip port return prefix + s.substring(0, p); } /** * Returns an object containing metadata about a cached resource * @param url the url of the resource * @return an {@link IResourceInfo info object} * @throws Exception of the info object could not be created, e.g. if the protocol is not supported */ public IResourceInfo loadResourceInfo(URL url) throws Exception { // getting the URL hash String urlHash = indexURL.urlHash(url.toNormalform()); // loading data from database Map hdb = this.responseHeaderDB.get(urlHash); if (hdb == null) return null; // generate the cached object IResourceInfo cachedObj = this.objFactory.buildResourceInfoObj(url, hdb); return cachedObj; } public ResourceInfoFactory getResourceInfoFactory() { return this.objFactory; } public boolean full() { return (this.cacheStack.size() > stackLimit); } public boolean empty() { return (this.cacheStack.size() == 0); } public static boolean isPicture(String mimeType) { if (mimeType == null) return false; return mimeType.toUpperCase().startsWith("IMAGE"); } public static boolean isText(String mimeType) { // Object ct = response.get(httpHeader.CONTENT_TYPE); // if (ct == null) return false; // String t = ((String)ct).toLowerCase(); // return ((t.startsWith("text")) || (t.equals("application/xhtml+xml"))); return plasmaParser.supportedMimeTypesContains(mimeType); } public static boolean noIndexingURL(String urlString) { if (urlString == null) return false; urlString = urlString.toLowerCase(); // return ( // (urlString.endsWith(".gz")) || // (urlString.endsWith(".msi")) || // (urlString.endsWith(".doc")) || // (urlString.endsWith(".zip")) || // (urlString.endsWith(".tgz")) || // (urlString.endsWith(".rar")) || // (urlString.endsWith(".pdf")) || // (urlString.endsWith(".ppt")) || // (urlString.endsWith(".xls")) || // (urlString.endsWith(".log")) || // (urlString.endsWith(".java")) || // (urlString.endsWith(".c")) || // (urlString.endsWith(".p")) // ); int idx = urlString.indexOf("?"); if (idx > 0) urlString = urlString.substring(0,idx); idx = urlString.lastIndexOf("."); if (idx > 0) urlString = urlString.substring(idx+1); return plasmaParser.mediaExtContains(urlString); } /* * This function moves an old cached object (if it exists) to the new position */ private void moveCachedObject(File oldpath, File newpath) { try { if (oldpath.exists() && oldpath.isFile() && (!newpath.exists())) { long d = oldpath.lastModified(); newpath.getParentFile().mkdirs(); if (oldpath.renameTo(newpath)) { cacheAge.put(ageString(d, newpath), newpath); File obj = oldpath.getParentFile(); while ((!(obj.equals(this.cachePath))) && (obj.isDirectory()) && (obj.list().length == 0)) { if (obj.delete()) this.log.logFine("DELETED EMPTY DIRECTORY : " + obj.toString()); obj = obj.getParentFile(); } } } } catch (Exception e) { log.logFine("moveCachedObject('" + oldpath.toString() + "','" + newpath.toString() + "')", e); } } private String replaceRegex(String input, String regex, String replacement) { if (input == null) { return ""; } if (input.length() > 0) { final Pattern searchPattern = Pattern.compile(regex); final Matcher matcher = searchPattern.matcher(input); while (matcher.find()) { input = matcher.replaceAll(replacement); matcher.reset(input); } } return input; } /** * this method creates from a given host and path a cache path * from a given host (which may also be an IPv4 - number, but not IPv6 or * a domain; all without leading 'http://') and a path (which must start * with a leading '/', and may also end in an '/') a path to a file * in the file system with root as given in cachePath is constructed * it will also be ensured, that the complete path exists; if necessary * that path will be generated * @return new File */ public File getCachePath(final URL url) { // this.log.logFinest("plasmaHTCache: getCachePath: IN=" + url.toString()); // peer.yacy || www.peer.yacy = http/yacy/peer // protocol://www.doamin.net = protocol/www/domain.net // protocol://other.doamin.net = protocol/other/other.domain.net // protocol://xxx.xxx.xxx.xxx = protocol/ip/xxx.xxx.xxx.xxx String host = url.getHost().toLowerCase(); String path = url.getPath(); final String query = url.getQuery(); if (!path.startsWith("/")) { path = "/" + path; } if (path.endsWith("/") && query == null) { path = path + "ndx"; } // yes this is not reversible, but that is not needed path = replaceRegex(path, "/\\.\\./", "/!!/"); path = replaceRegex(path, "(\"|\\\\|\\*|\\?|:|<|>|\\|+)", "_"); // hier wird kein '/' gefiltert String extention = null; int d = path.lastIndexOf("."); int s = path.lastIndexOf("/"); if ((d >= 0) && (d > s)) { extention = path.substring(d); } else if (path.endsWith("/ndx")) { extention = new String (".html"); // Just a wild guess } path = path.concat(replaceRegex(query, "(\"|\\\\|\\*|\\?|/|:|<|>|\\|+)", "_")); // only set NO default ports int port = url.getPort(); String protocol = url.getProtocol(); if (port >= 0) { if ((port == 80 && protocol.equals("http" )) || (port == 443 && protocol.equals("https")) || (port == 21 && protocol.equals("ftp" ))) { port = -1; } } if (host.endsWith(".yacy")) { host = host.substring(0, host.length() - 5); if (host.startsWith("www.")) { host = host.substring(4); } protocol = "yacy"; } else if (host.startsWith("www.")) { host = "www/" + host.substring(4); } else if (host.matches("\\d{2,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}")) { host = "ip/" + host; } else { host = "other/" + host; } StringBuffer fileName = new StringBuffer(); fileName.append(protocol).append('/').append(host); if (port >= 0) { fileName.append('!').append(port); } // generate cache path according to storage method if (cacheLayout.equals("tree")) { File FileTree = treeFile(fileName, "tree", path); if (cacheMigration) { moveCachedObject(hashFile(fileName, "hash", extention, url), FileTree); moveCachedObject(hashFile(fileName, null, extention, url), FileTree); // temporary migration moveCachedObject(treeFile(fileName, null, path), FileTree); // temporary migration } return FileTree; } if (cacheLayout.equals("hash")) { File FileFlat = hashFile(fileName, "hash", extention, url); if (cacheMigration) { moveCachedObject(treeFile(fileName, "tree", path), FileFlat); moveCachedObject(treeFile(fileName, null, path), FileFlat); // temporary migration moveCachedObject(hashFile(fileName, null, extention, url), FileFlat); // temporary migration } return FileFlat; } return null; } private File treeFile(StringBuffer fileName, String prefix, String path) { StringBuffer f = new StringBuffer(fileName.length() + 30); f.append(fileName); if (prefix != null) f.append('/').append(prefix); f.append(path); return new File(this.cachePath, f.toString()); } private File hashFile(StringBuffer fileName, String prefix, String extention, URL url) { String hexHash = yacySeed.b64Hash2hexHash(indexURL.urlHash(url)); StringBuffer f = new StringBuffer(fileName.length() + 30); f.append(fileName); if (prefix != null) f.append('/').append(prefix); f.append('/').append(hexHash.substring(0,2)).append('/').append(hexHash.substring(2,4)).append('/').append(hexHash); if (extention != null) fileName.append(extention); return new File(this.cachePath, f.toString()); } /** * This is a helper funktion that extracts the Hash from the filename */ public static String getHash(final File f) { - if ((f.getPath().indexOf("hash")) < 0) return null; + if ((!f.isFile()) || (f.getPath().indexOf("hash") < 0)) return null; String hexHash = f.getName().substring(0,18); if (hexHash.indexOf('.') >= 0) return null; try { String hash = kelondroBase64Order.enhancedCoder.encode(serverCodings.decodeHex(hexHash)); if (hash.length() == indexURL.urlHashLength) return hash; return null; } catch (Exception e) { //log.logWarning("getHash: " + e.getMessage(), e); return null; } } /** * this is the reverse function to getCachePath: it constructs the url as string * from a given storage path */ public URL getURL(final File f) { // this.log.logFinest("plasmaHTCache: getURL: IN: Path=[" + cachePath + "] File=[" + f + "]"); final String urlHash = getHash(f); if (urlHash != null) { URL url = null; // try the urlPool try { url = plasmaSwitchboard.getSwitchboard().urlPool.getURL(urlHash); } catch (Exception e) { log.logWarning("getURL(" + urlHash + "): " /*+ e.getMessage()*/, e); url = null; } if (url != null) return url; // try responseHeaderDB Map hdb; try { hdb = this.responseHeaderDB.get(urlHash); } catch (IOException e) { hdb = null; } if (hdb != null) { Object origRequestLine = hdb.get(httpHeader.X_YACY_ORIGINAL_REQUEST_LINE); if ((origRequestLine != null)&&(origRequestLine instanceof String)) { int i = ((String)origRequestLine).indexOf(" "); if (i >= 0) { String s = ((String)origRequestLine).substring(i).trim(); i = s.indexOf(" "); try { url = new URL((i<0) ? s : s.substring(0,i)); } catch (final Exception e) { url = null; } } } } if (url != null) return url; } // If we can't get the correct URL, it seems to be a treeed file String c = cachePath.toString().replace('\\', '/'); String path = f.toString().replace('\\', '/'); int pos; if ((pos = path.indexOf("/tree")) >= 0) path = path.substring(0, pos) + path.substring(pos + 5); if (path.endsWith("ndx")) { path = path.substring(0, path.length() - 3); } if ((pos = path.lastIndexOf(c)) == 0) { path = path.substring(pos + c.length()); while (path.startsWith("/")) { path = path.substring(1); } pos = path.indexOf("!"); if (pos >= 0) { path = path.substring(0, pos) + ":" + path.substring(pos + 1); } String protocol = "http://"; String host = ""; if (path.startsWith("yacy/")) { path = path.substring(5); pos = path.indexOf("/"); if (pos > 0) { host = path.substring(0, pos); path = path.substring(pos); } else { host = path; path = ""; } pos = host.indexOf(":"); if (pos > 0) { host = host.substring(0, pos) + ".yacy" + host.substring(pos); } else { host = host + ".yacy"; } } else { if (path.startsWith("http/")) { path = path.substring(5); } else if (path.startsWith("https/")) { protocol = "https://"; path = path.substring(6); } else if (path.startsWith("ftp/")) { protocol = "ftp://"; path = path.substring(4); } else { return null; } if (path.startsWith("www/")) { path = path.substring(4); host = "www."; } else if (path.startsWith("other/")) { path = path.substring(6); } else if (path.startsWith("ip/")) { path = path.substring(3); } pos = path.indexOf("/"); if (pos > 0) { host = host + path.substring(0, pos); path = path.substring(pos); } else { host = host + path; path = ""; } } if (!path.equals("")) { final Pattern pathPattern = Pattern.compile("/!!/"); final Matcher matcher = pathPattern.matcher(path); while (matcher.find()) { path = matcher.replaceAll("/\\.\\./"); matcher.reset(path); } } // this.log.logFinest("plasmaHTCache: getURL: OUT=" + s); try { return new URL(protocol + host + path); } catch (final Exception e) { return null; } } return null; } /** * Returns the content of a cached resource as {@link InputStream} * @param url the requested resource * @return the resource content as {@link InputStream}. In no data * is available or the cached file is not readable, <code>null</code> * is returned. */ public InputStream getResourceContentStream(URL url) { // load the url as resource from the cache File f = getCachePath(url); if (f.exists() && f.canRead()) try { return new BufferedInputStream(new FileInputStream(f)); } catch (IOException e) { this.log.logSevere("Unable to create a BufferedInputStream from file " + f,e); return null; } return null; } public long getResourceContentLength(URL url) { // load the url as resource from the cache File f = getCachePath(url); if (f.exists() && f.canRead()) { return f.length(); } return 0; } public static boolean isPOST(String urlString) { return (urlString.indexOf("?") >= 0 || urlString.indexOf("&") >= 0); } public static boolean isCGI(String urlString) { String ls = urlString.toLowerCase(); return ((ls.indexOf(".cgi") >= 0) || (ls.indexOf(".exe") >= 0) || (ls.indexOf(";jsessionid=") >= 0) || (ls.indexOf("sessionid/") >= 0) || (ls.indexOf("phpsessid=") >= 0) || (ls.indexOf("search.php?sid=") >= 0) || (ls.indexOf("memberlist.php?sid=") >= 0)); } public Entry newEntry( Date initDate, int depth, URL url, String name, //httpHeader requestHeader, String responseStatus, //httpHeader responseHeader, IResourceInfo docInfo, String initiator, plasmaCrawlProfile.entry profile ) { return new Entry( initDate, depth, url, name, //requestHeader, responseStatus, //responseHeader, docInfo, initiator, profile ); } public final class Entry { // the class objects private Date initDate; // the date when the request happened; will be used as a key private int depth; // the depth of prefetching // private httpHeader requestHeader; // we carry also the header to prevent too many file system access // private httpHeader responseHeader; // we carry also the header to prevent too many file system access private String responseStatus; private File cacheFile; // the cache file private byte[] cacheArray; // or the cache as byte-array private URL url; private String name; // the name of the link, read as anchor from an <a>-tag private String nomalizedURLHash; private String nomalizedURLString; //private int status; // cache load/hit/stale etc status private Date lastModified; private char doctype; private String language; private plasmaCrawlProfile.entry profile; private String initiator; /** * protocolspecific information about the resource */ private IResourceInfo resInfo; protected Object clone() throws CloneNotSupportedException { return new Entry( this.initDate, this.depth, this.url, this.name, //this.requestHeader, this.responseStatus, //this.responseHeader, this.resInfo, this.initiator, this.profile ); } public Entry(Date initDate, int depth, URL url, String name, //httpHeader requestHeader, String responseStatus, //httpHeader responseHeader, IResourceInfo resourceInfo, String initiator, plasmaCrawlProfile.entry profile ) { if (resourceInfo == null){ System.out.println("Content information object is null. " + url); System.exit(0); } this.resInfo = resourceInfo; // normalize url this.nomalizedURLString = url.toNormalform(); try { this.url = new URL(this.nomalizedURLString); } catch (MalformedURLException e) { System.out.println("internal error at httpdProxyCache.Entry: " + e); System.exit(-1); } this.name = name; this.cacheFile = getCachePath(this.url); this.nomalizedURLHash = indexURL.urlHash(this.nomalizedURLString); // assigned: this.initDate = initDate; this.depth = depth; //this.requestHeader = requestHeader; this.responseStatus = responseStatus; //this.responseHeader = responseHeader; this.profile = profile; this.initiator = (initiator == null) ? null : ((initiator.length() == 0) ? null : initiator); // getting the last modified date this.lastModified = resourceInfo.getModificationDate(); // getting the doctype this.doctype = indexEntryAttribute.docType(resourceInfo.getMimeType()); if (this.doctype == indexEntryAttribute.DT_UNKNOWN) this.doctype = indexEntryAttribute.docType(url); this.language = indexEntryAttribute.language(url); // to be defined later: this.cacheArray = null; } public String name() { return this.name; } public URL url() { return this.url; } public String urlHash() { return this.nomalizedURLHash; } public Date lastModified() { return this.lastModified; } public String language() { return this.language; } public plasmaCrawlProfile.entry profile() { return this.profile; } public String initiator() { return this.initiator; } public boolean proxy() { return initiator() == null; } public long size() { if (this.cacheArray == null) return 0; return this.cacheArray.length; } public int depth() { return this.depth; } public URL referrerURL() { return (this.resInfo==null)?null:this.resInfo.getRefererUrl(); } public File cacheFile() { return this.cacheFile; } public void setCacheArray(byte[] data) { this.cacheArray = data; } public byte[] cacheArray() { return this.cacheArray; } // public httpHeader requestHeader() { // return this.requestHeader; // } // public httpHeader responseHeader() { // return this.responseHeader; // } public IResourceInfo getDocumentInfo() { return this.resInfo; } public boolean writeResourceInfo() throws IOException { assert(this.nomalizedURLHash != null) : "URL Hash is null"; if (this.resInfo == null) return false; plasmaHTCache.this.responseHeaderDB.set(this.nomalizedURLHash, this.resInfo.getMap()); return true; } public String getMimeType() { return (this.resInfo == null) ? null : this.resInfo.getMimeType(); } public Date ifModifiedSince() { return (this.resInfo == null) ? null : this.resInfo.ifModifiedSince(); } public boolean requestWithCookie() { return (this.resInfo == null) ? false : this.resInfo.requestWithCookie(); } public boolean requestProhibitsIndexing() { return (this.resInfo == null) ? false : this.resInfo.requestProhibitsIndexing(); } /* public boolean update() { return ((status == CACHE_FILL) || (status == CACHE_STALE_RELOAD_GOOD)); } */ // the following three methods for cache read/write granting shall be as loose as possible // but also as strict as necessary to enable caching of most items /** * @return NULL if the answer is TRUE, in case of FALSE, the reason as String is returned */ public String shallStoreCacheForProxy() { // check profile (disabled: we will check this in the plasmaSwitchboard) //if (!this.profile.storeHTCache()) { return "storage_not_wanted"; } // decide upon header information if a specific file should be stored to the cache or not // if the storage was requested by prefetching, the request map is null // check status code if ((this.resInfo != null) && (!this.resInfo.validResponseStatus(this.responseStatus))) { return "bad_status_" + this.responseStatus.substring(0,3); } // if (!(this.responseStatus.startsWith("200") || // this.responseStatus.startsWith("203"))) { return "bad_status_" + this.responseStatus.substring(0,3); } // check storage location // sometimes a file name is equal to a path name in the same directory; // or sometimes a file name is equal a directory name created earlier; // we cannot match that here in the cache file path and therefore omit writing into the cache if (this.cacheFile.getParentFile().isFile() || this.cacheFile.isDirectory()) { return "path_ambiguous"; } if (this.cacheFile.toString().indexOf("..") >= 0) { return "path_dangerous"; } if (this.cacheFile.getAbsolutePath().length() > serverSystem.maxPathLength) { return "path too long"; } // -CGI access in request // CGI access makes the page very individual, and therefore not usable in caches if (isPOST(this.nomalizedURLString) && !this.profile.crawlingQ()) { return "dynamic_post"; } if (isCGI(this.nomalizedURLString)) { return "dynamic_cgi"; } if (this.resInfo != null) { return this.resInfo.shallStoreCacheForProxy(); } return null; } /** * decide upon header information if a specific file should be taken from the cache or not * @return */ public boolean shallUseCacheForProxy() { // System.out.println("SHALL READ CACHE: requestHeader = " + requestHeader.toString() + ", responseHeader = " + responseHeader.toString()); // -CGI access in request // CGI access makes the page very individual, and therefore not usable in caches if (isPOST(this.nomalizedURLString)) { return false; } if (isCGI(this.nomalizedURLString)) { return false; } if (this.resInfo != null) { return this.resInfo.shallUseCacheForProxy(); } return true; } } // class Entry }
true
false
null
null
diff --git a/src/com/vaadin/ui/DateField.java b/src/com/vaadin/ui/DateField.java index 6c4dfce66..dc062be66 100644 --- a/src/com/vaadin/ui/DateField.java +++ b/src/com/vaadin/ui/DateField.java @@ -1,521 +1,521 @@ /* @ITMillApache2LicenseForJavaFiles@ */ package com.vaadin.ui; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; import java.util.Map; import com.vaadin.data.Property; import com.vaadin.terminal.PaintException; import com.vaadin.terminal.PaintTarget; /** * <p> * A date editor component that can be bound to any bindable Property. that is * compatible with <code>java.util.Date</code>. * </p> * <p> * Since <code>DateField</code> extends <code>AbstractField</code> it implements * the {@link com.vaadin.data.Buffered}interface. A <code>DateField</code> is in * write-through mode by default, so * {@link com.vaadin.ui.AbstractField#setWriteThrough(boolean)}must be called to * enable buffering. * </p> * * @author IT Mill Ltd. * @version * @VERSION@ * @since 3.0 */ @SuppressWarnings("serial") public class DateField extends AbstractField { /* Private members */ /** * Resolution identifier: milliseconds. */ public static final int RESOLUTION_MSEC = 0; /** * Resolution identifier: seconds. */ public static final int RESOLUTION_SEC = 1; /** * Resolution identifier: minutes. */ public static final int RESOLUTION_MIN = 2; /** * Resolution identifier: hours. */ public static final int RESOLUTION_HOUR = 3; /** * Resolution identifier: days. */ public static final int RESOLUTION_DAY = 4; /** * Resolution identifier: months. */ public static final int RESOLUTION_MONTH = 5; /** * Resolution identifier: years. */ public static final int RESOLUTION_YEAR = 6; /** * Popup date selector (calendar). */ protected static final String TYPE_POPUP = "popup"; /** * Inline date selector (calendar). */ protected static final String TYPE_INLINE = "inline"; /** * Specified widget type. */ protected String type = TYPE_POPUP; /** * Specified smallest modifiable unit. */ private int resolution = RESOLUTION_MSEC; /** * Specified largest modifiable unit. */ private static final int largestModifiable = RESOLUTION_YEAR; /** * The internal calendar to be used in java.utl.Date conversions. */ - private Calendar calendar; + private transient Calendar calendar; /** * Overridden format string */ private String dateFormat; /** * Read-only content of an VTextualDate field - null for other types of date * fields. */ private String dateString; /* Constructors */ /** * Constructs an empty <code>DateField</code> with no caption. */ public DateField() { } /** * Constructs an empty <code>DateField</code> with caption. * * @param caption * the caption of the datefield. */ public DateField(String caption) { setCaption(caption); } /** * Constructs a new <code>DateField</code> that's bound to the specified * <code>Property</code> and has the given caption <code>String</code>. * * @param caption * the caption <code>String</code> for the editor. * @param dataSource * the Property to be edited with this editor. */ public DateField(String caption, Property dataSource) { this(dataSource); setCaption(caption); } /** * Constructs a new <code>DateField</code> that's bound to the specified * <code>Property</code> and has no caption. * * @param dataSource * the Property to be edited with this editor. */ public DateField(Property dataSource) throws IllegalArgumentException { if (!Date.class.isAssignableFrom(dataSource.getType())) { throw new IllegalArgumentException("Can't use " + dataSource.getType().getName() + " typed property as datasource"); } setPropertyDataSource(dataSource); } /** * Constructs a new <code>DateField</code> with the given caption and * initial text contents. The editor constructed this way will not be bound * to a Property unless * {@link com.vaadin.data.Property.Viewer#setPropertyDataSource(Property)} * is called to bind it. * * @param caption * the caption <code>String</code> for the editor. * @param value * the Date value. */ public DateField(String caption, Date value) { setValue(value); setCaption(caption); } /* Component basic features */ /* * Paints this component. Don't add a JavaDoc comment here, we use the * default documentation from implemented interface. */ @Override public void paintContent(PaintTarget target) throws PaintException { super.paintContent(target); // Adds the locale as attribute final Locale l = getLocale(); if (l != null) { target.addAttribute("locale", l.toString()); } if (getDateFormat() != null) { target.addAttribute("format", dateFormat); } target.addAttribute("type", type); // Gets the calendar final Calendar calendar = getCalendar(); final Date currentDate = (Date) getValue(); for (int r = resolution; r <= largestModifiable; r++) { switch (r) { case RESOLUTION_MSEC: target.addVariable(this, "msec", currentDate != null ? calendar .get(Calendar.MILLISECOND) : -1); break; case RESOLUTION_SEC: target.addVariable(this, "sec", currentDate != null ? calendar .get(Calendar.SECOND) : -1); break; case RESOLUTION_MIN: target.addVariable(this, "min", currentDate != null ? calendar .get(Calendar.MINUTE) : -1); break; case RESOLUTION_HOUR: target.addVariable(this, "hour", currentDate != null ? calendar .get(Calendar.HOUR_OF_DAY) : -1); break; case RESOLUTION_DAY: target.addVariable(this, "day", currentDate != null ? calendar .get(Calendar.DAY_OF_MONTH) : -1); break; case RESOLUTION_MONTH: target.addVariable(this, "month", currentDate != null ? calendar.get(Calendar.MONTH) + 1 : -1); break; case RESOLUTION_YEAR: target.addVariable(this, "year", currentDate != null ? calendar .get(Calendar.YEAR) : -1); break; } } } /* * Gets the components UIDL tag string. Don't add a JavaDoc comment here, we * use the default documentation from implemented interface. */ @Override public String getTag() { return "datefield"; } /* * Invoked when a variable of the component changes. Don't add a JavaDoc * comment here, we use the default documentation from implemented * interface. */ @Override public void changeVariables(Object source, Map variables) { super.changeVariables(source, variables); if (!isReadOnly() && (variables.containsKey("year") || variables.containsKey("month") || variables.containsKey("day") || variables.containsKey("hour") || variables.containsKey("min") || variables.containsKey("sec") || variables.containsKey("msec") || variables .containsKey("dateString"))) { // Old and new dates final Date oldDate = (Date) getValue(); final String oldDateString = dateString; Date newDate = null; // this enables analyzing invalid input on the server Object o = variables.get("dateString"); if (o != null) { dateString = o.toString(); } else { dateString = null; } // Gets the new date in parts // Null values are converted to negative values. int year = variables.containsKey("year") ? (variables.get("year") == null ? -1 : ((Integer) variables.get("year")).intValue()) : -1; int month = variables.containsKey("month") ? (variables .get("month") == null ? -1 : ((Integer) variables .get("month")).intValue() - 1) : -1; int day = variables.containsKey("day") ? (variables.get("day") == null ? -1 : ((Integer) variables.get("day")).intValue()) : -1; int hour = variables.containsKey("hour") ? (variables.get("hour") == null ? -1 : ((Integer) variables.get("hour")).intValue()) : -1; int min = variables.containsKey("min") ? (variables.get("min") == null ? -1 : ((Integer) variables.get("min")).intValue()) : -1; int sec = variables.containsKey("sec") ? (variables.get("sec") == null ? -1 : ((Integer) variables.get("sec")).intValue()) : -1; int msec = variables.containsKey("msec") ? (variables.get("msec") == null ? -1 : ((Integer) variables.get("msec")).intValue()) : -1; // If all of the components is < 0 use the previous value if (year < 0 && month < 0 && day < 0 && hour < 0 && min < 0 && sec < 0 && msec < 0) { newDate = null; } else { // Clone the calendar for date operation final Calendar cal = getCalendar(); // Make sure that meaningful values exists // Use the previous value if some of the variables // have not been changed. year = year < 0 ? cal.get(Calendar.YEAR) : year; month = month < 0 ? cal.get(Calendar.MONTH) : month; day = day < 0 ? cal.get(Calendar.DAY_OF_MONTH) : day; hour = hour < 0 ? cal.get(Calendar.HOUR_OF_DAY) : hour; min = min < 0 ? cal.get(Calendar.MINUTE) : min; sec = sec < 0 ? cal.get(Calendar.SECOND) : sec; msec = msec < 0 ? cal.get(Calendar.MILLISECOND) : msec; // Sets the calendar fields cal.set(Calendar.YEAR, year); cal.set(Calendar.MONTH, month); cal.set(Calendar.DAY_OF_MONTH, day); cal.set(Calendar.HOUR_OF_DAY, hour); cal.set(Calendar.MINUTE, min); cal.set(Calendar.SECOND, sec); cal.set(Calendar.MILLISECOND, msec); // Assigns the date newDate = cal.getTime(); } if (newDate != oldDate && (newDate == null || !newDate.equals(oldDate))) { setValue(newDate, true); // Don't require a repaint, client // updates itself } else if (dateString != null && !"".equals(dateString) && !dateString.equals(oldDateString)) { setValue(handleUnparsableDateString(dateString)); } } } /** * This method is called to handle a non-empty date string from the client * if the client could not parse it as a Date. * * By default, a Property.ConversionException is thrown, and the current * value is not modified. * * This can be overridden to handle conversions, to return null (equivalent * to empty input), to throw an exception or to fire an event. * * @param dateString * @return parsed Date * @throws Property.ConversionException * to keep the old value and indicate an error */ protected Date handleUnparsableDateString(String dateString) throws Property.ConversionException { throw new Property.ConversionException(); } /* Property features */ /* * Gets the edited property's type. Don't add a JavaDoc comment here, we use * the default documentation from implemented interface. */ @Override public Class getType() { return Date.class; } /* * Returns the value of the property in human readable textual format. Don't * add a JavaDoc comment here, we use the default documentation from * implemented interface. */ @Override public String toString() { final Date value = (Date) getValue(); if (value != null) { return value.toString(); } return null; } /* * Sets the value of the property. Don't add a JavaDoc comment here, we use * the default documentation from implemented interface. */ @Override public void setValue(Object newValue) throws Property.ReadOnlyException, Property.ConversionException { setValue(newValue, false); } @Override public void setValue(Object newValue, boolean repaintIsNotNeeded) throws Property.ReadOnlyException, Property.ConversionException { // Allows setting dates directly if (newValue == null || newValue instanceof Date) { super.setValue(newValue, repaintIsNotNeeded); } else { // Try to parse as string try { final SimpleDateFormat parser = new SimpleDateFormat(); final Date val = parser.parse(newValue.toString()); super.setValue(val, repaintIsNotNeeded); } catch (final ParseException e) { throw new Property.ConversionException(e.getMessage()); } } } /** * Sets the DateField datasource. Datasource type must assignable to Date. * * @see com.vaadin.data.Property.Viewer#setPropertyDataSource(Property) */ @Override public void setPropertyDataSource(Property newDataSource) { if (newDataSource == null || Date.class.isAssignableFrom(newDataSource.getType())) { super.setPropertyDataSource(newDataSource); } else { throw new IllegalArgumentException( "DateField only supports Date properties"); } } /** * Gets the resolution. * * @return int */ public int getResolution() { return resolution; } /** * Sets the resolution of the DateField. * * @param resolution * the resolution to set. */ public void setResolution(int resolution) { this.resolution = resolution; } /** * Returns new instance calendar used in Date conversions. * * Returns new clone of the calendar object initialized using the the * current date (if available) * * If this is no calendar is assigned the <code>Calendar.getInstance</code> * is used. * * @return the Calendar. * @see #setCalendar(Calendar) */ private Calendar getCalendar() { // Makes sure we have an calendar instance if (calendar == null) { calendar = Calendar.getInstance(); } // Clone the instance final Calendar newCal = (Calendar) calendar.clone(); // Assigns the current time tom calendar. final Date currentDate = (Date) getValue(); if (currentDate != null) { newCal.setTime(currentDate); } return newCal; } /** * Sets formatting used by some component implementations. See * {@link SimpleDateFormat} for format details. * * By default it is encouraged to used default formatting defined by Locale, * but due some JVM bugs it is sometimes necessary to use this method to * override formatting. See Vaadin issue #2200. * * @param dateFormat * the dateFormat to set * * @see com.vaadin.ui.AbstractComponent#setLocale(Locale)) */ public void setDateFormat(String dateFormat) { this.dateFormat = dateFormat; } /** * Reterns a format string used to format date value on client side or null * if default formatting from {@link Component#getLocale()} is used. * * @return the dateFormat */ public String getDateFormat() { return dateFormat; } }
true
false
null
null
diff --git a/src/com/dmdirc/addons/ui_swing/dialogs/StandardDialog.java b/src/com/dmdirc/addons/ui_swing/dialogs/StandardDialog.java index 54be8dd0..145f7770 100644 --- a/src/com/dmdirc/addons/ui_swing/dialogs/StandardDialog.java +++ b/src/com/dmdirc/addons/ui_swing/dialogs/StandardDialog.java @@ -1,432 +1,430 @@ /* * Copyright (c) 2006-2013 DMDirc Developers * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.dmdirc.addons.ui_swing.dialogs; import com.dmdirc.addons.ui_swing.MainFrame; import com.dmdirc.addons.ui_swing.SwingController; import com.dmdirc.ui.CoreUIUtils; import com.dmdirc.ui.IconManager; import java.awt.Component; import java.awt.Dialog; import java.awt.Dimension; import java.awt.Frame; import java.awt.Window; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.concurrent.Semaphore; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.SwingUtilities; import lombok.Getter; /** * Provides common methods for dialogs. */ @SuppressWarnings("unused") public class StandardDialog extends JDialog { /** Serial version UID. */ private static final long serialVersionUID = 1; /** Dialog manager. */ private final DialogManager dialogManager; /** Swing controller. */ @Getter private SwingController controller; /** The OK button for this frame. */ private JButton okButton; /** The cancel button for this frame. */ private JButton cancelButton; /** Parent window. */ private Window owner; - - /** * Creates a new instance of StandardDialog. * * @param controller Parent swing controller * @param modal Whether to display modally or not */ public StandardDialog(final SwingController controller, final ModalityType modal) { super(controller.getMainFrame(), modal); this.owner = controller.getMainFrame(); this.controller = controller; dialogManager = controller.getDialogManager(); if (owner != null) { setIconImages(owner.getIconImages()); } orderButtons(new JButton(), new JButton()); setDefaultCloseOperation(DISPOSE_ON_CLOSE); } /** * Creates a new instance of StandardDialog. * * @param controller Parent swing controller * @param modal Whether to display modally or not */ public StandardDialog(final SwingController controller, final boolean modal) { super(controller.getMainFrame(), modal); this.owner = controller.getMainFrame(); this.controller = controller; dialogManager = controller.getDialogManager(); if (owner != null) { setIconImages(owner.getIconImages()); } orderButtons(new JButton(), new JButton()); setDefaultCloseOperation(DISPOSE_ON_CLOSE); } /** * Creates a new instance of StandardDialog. * * @param controller Parent swing controller * @param owner The frame that owns this dialog * @param modal Whether to display modally or not */ public StandardDialog(final SwingController controller, final Frame owner, final boolean modal) { super(owner, modal); this.owner = owner; this.controller = controller; if (controller != null) { dialogManager = controller.getDialogManager(); } else { dialogManager = null; } if (owner != null) { setIconImages(owner.getIconImages()); } orderButtons(new JButton(), new JButton()); setDefaultCloseOperation(DISPOSE_ON_CLOSE); } /** * Creates a new instance of StandardDialog. * * @param controller Parent swing controller * @param owner The frame that owns this dialog * @param modal Whether to display modally or not */ public StandardDialog(final SwingController controller, final Window owner, final ModalityType modal) { super(owner, modal); this.owner = owner; this.controller = controller; if (controller != null) { dialogManager = controller.getDialogManager(); } else { dialogManager = null; } if (owner != null) { setIconImages(owner.getIconImages()); } orderButtons(new JButton(), new JButton()); setDefaultCloseOperation(DISPOSE_ON_CLOSE); } /** * Creates a new instance of StandardDialog. * * @param controller Parent swing controller * @param owner The frame that owns this dialog * @param modal Whether to display modally or not */ public StandardDialog(final SwingController controller, final Dialog owner, final boolean modal) { super(owner, modal); this.owner = owner; this.controller = controller; if (controller != null) { dialogManager = controller.getDialogManager(); } else { dialogManager = null; } if (owner != null) { setIconImages(owner.getIconImages()); } orderButtons(new JButton(), new JButton()); } /** {@inheritDoc} */ @Override public void setTitle(final String title) { super.setTitle("DMDirc: " + title); } /** {@inheritDoc} */ @Override public void dispose() { if (dialogManager != null) { dialogManager.dispose(this); } super.dispose(); } /** * Displays the dialog centering on the parent window. */ public void display() { display(owner); } /** * Displays the dialog centering on the specified window. * * @param owner Window to center on */ public void display(final Component owner) { if (isVisible()) { return; } addWindowListener(new WindowAdapter() { /** {@inheritDoc} */ @Override public void windowClosing(final WindowEvent e) { executeAction(getCancelButton()); } }); centreOnOwner(); pack(); centreOnOwner(); setVisible(false); setVisible(true); } /** * Displays the dialog centering on the parent window, blocking until * complete. */ public void displayBlocking() { displayBlocking(owner); } /** * Displays the dialog centering on the specified window, blocking until * complete. * * @param owner Window to center on */ public void displayBlocking(final Component owner) { if (SwingUtilities.isEventDispatchThread()) { throw new IllegalStateException("Unable to display blocking dialog" + " in the EDT."); } final Semaphore semaphore = new Semaphore(0); SwingUtilities.invokeLater(new Runnable() { /** {@inheritDoc} */ @Override public void run() { display(owner); addWindowListener(new WindowAdapter() { @Override public void windowClosed(final WindowEvent e) { semaphore.release(); } }); } }); semaphore.acquireUninterruptibly(); } /** * Centres this dialog on its owner, or the screen if no owner is present. */ public void centreOnOwner() { if (owner == null) { CoreUIUtils.centreWindow(this); } else { setLocationRelativeTo(owner); } } /** * Returns the window owner for this dialog. * * @return Parent window or null */ public Window getParentWindow() { return owner; } /** * Sets the specified button up as the OK button. * @param button The target button */ protected void setOkButton(final JButton button) { okButton = button; button.setText("OK"); button.setDefaultCapable(false); } /** * Sets the specified button up as the Cancel button. * @param button The target button */ protected void setCancelButton(final JButton button) { cancelButton = button; button.setText("Cancel"); button.setDefaultCapable(false); } /** * Gets the left hand button for a dialog. * @return left JButton */ protected final JButton getLeftButton() { if (System.getProperty("os.name").toLowerCase().startsWith("win")) { return getOkButton(); } else { return getCancelButton(); } } /** * Gets the right hand button for a dialog. * @return right JButton */ protected final JButton getRightButton() { if (System.getProperty("os.name").toLowerCase().startsWith("win")) { return getCancelButton(); } else { return getOkButton(); } } /** * Orders the OK and Cancel buttons in an appropriate order for the current * operating system. * @param leftButton The left-most button * @param rightButton The right-most button */ protected final void orderButtons(final JButton leftButton, final JButton rightButton) { if (System.getProperty("os.name").toLowerCase().startsWith("win")) { // Windows - put the OK button on the left setOkButton(leftButton); setCancelButton(rightButton); } else { // Everything else - adhere to usability guidelines and put it on // the right. setOkButton(rightButton); setCancelButton(leftButton); } leftButton.setPreferredSize(new Dimension(100, 25)); rightButton.setPreferredSize(new Dimension(100, 25)); leftButton.setMinimumSize(new Dimension(100, 25)); rightButton.setMinimumSize(new Dimension(100, 25)); } /** * Retrieves the OK button for this form. * @return The form's OK button */ public final JButton getOkButton() { return okButton; } /** * Retrieves the Cancel button for this form. * @return The form's cancel button */ public final JButton getCancelButton() { return cancelButton; } /** * Simulates the user clicking on the specified target button. * @param target The button to use */ public final void executeAction(final JButton target) { if (target != null && target.isEnabled()) { target.doClick(); } } /** * This method is called when enter is pressed anywhere in the dialog * except on a button. By default this method does nothing. * * @return Returns true if the key press has been handled and is not be * be forwarded on by default this is false */ public boolean enterPressed() { return false; } /** * This method is called when ctrl + enter is pressed anywhere in the * dialog. By default this method presses the OK button. * * @return Returns true if the key press has been handled and is not be * be forwarded on by default this is true */ public boolean ctrlEnterPressed() { executeAction(getOkButton()); return true; } /** * This method is called when enter is pressed anywhere in the dialog * except on a button. By default this method presses the cancel button. * * @return Returns true if the key press has been handled and is not be * be forwarded on by default this is true */ public boolean escapePressed() { executeAction(getCancelButton()); return true; } /** * Returns the Swing main frame. * * @return Main frame */ public MainFrame getMainFrame() { return getController().getMainFrame(); } /** * Returns the icon manager. * * @return Icon manager */ public IconManager getIconManager() { return getController().getIconManager(); } } diff --git a/src/com/dmdirc/addons/ui_swing/dialogs/actioneditor/ActionEditorDialog.java b/src/com/dmdirc/addons/ui_swing/dialogs/actioneditor/ActionEditorDialog.java index 83921075..bf6c5c69 100644 --- a/src/com/dmdirc/addons/ui_swing/dialogs/actioneditor/ActionEditorDialog.java +++ b/src/com/dmdirc/addons/ui_swing/dialogs/actioneditor/ActionEditorDialog.java @@ -1,304 +1,304 @@ /* * Copyright (c) 2006-2013 DMDirc Developers * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.dmdirc.addons.ui_swing.dialogs.actioneditor; import com.dmdirc.actions.Action; import com.dmdirc.actions.ActionFactory; import com.dmdirc.actions.ActionStatus; import com.dmdirc.addons.ui_swing.SwingController; import com.dmdirc.addons.ui_swing.dialogs.StandardDialog; import java.awt.Dimension; import java.awt.Window; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import javax.swing.JButton; import javax.swing.SwingUtilities; import lombok.extern.slf4j.Slf4j; import net.miginfocom.swing.MigLayout; /** * Action editor dialog. */ @Slf4j public class ActionEditorDialog extends StandardDialog implements ActionListener, PropertyChangeListener { /** Serial version UID. */ private static final long serialVersionUID = 1; /** Name panel. */ private ActionNamePanel name; /** Triggers panel. */ private ActionTriggersPanel triggers; /** Response panel. */ private ActionResponsePanel response; /** Conditions panel. */ private ActionConditionsPanel conditions; /** Substitutions panel. */ private ActionSubstitutionsPanel substitutions; /** Advanced panel. */ private ActionAdvancedPanel advanced; /** Show substitutions button. */ private JButton showSubstitutions; /** Show advanced button. */ private JButton showAdvanced; /** Is the name valid? */ private boolean nameValid = false; /** Are the triggers valid? */ private boolean triggersValid = false; /** Are the conditions valid? */ private boolean conditionsValid = false; /** Action to be edited. */ private final Action action; /** Action group. */ private final String group; /** Factory to use to create new actions. */ private final ActionFactory actionFactory; /** * Instantiates the panel. * * @param controller Swing controller * @param parentWindow Parent window * @param group Action's group */ public ActionEditorDialog(final SwingController controller, final Window parentWindow, final String group) { super(controller, parentWindow, ModalityType.DOCUMENT_MODAL); log.debug("loading with group: " + group); setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); setTitle("Action Editor"); this.group = group; this.action = null; this.actionFactory = controller.getActionFactory(); initComponents(); addListeners(); doComponents(); layoutComponents(); setResizable(false); } /** * Instantiates the panel. * * @param controller Swing controller * @param parentWindow Parent window * @param action Action to be edited */ public ActionEditorDialog(final SwingController controller, final Window parentWindow, final Action action) { super(controller, parentWindow, ModalityType.DOCUMENT_MODAL); log.debug("loading with action: " + action); setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); setTitle("Action Editor"); this.group = action.getGroup(); this.action = action; this.actionFactory = controller.getActionFactory(); initComponents(); addListeners(); doComponents(); layoutComponents(); setResizable(false); } /** Sets components initial states and stuff. */ private void doComponents() { triggers.setEnabled(action != null); response.setEnabled(action != null); conditions.setEnabled(action != null); substitutions.setVisible(false); advanced.setVisible(false); triggersValid = action != null; conditionsValid = true; nameValid = action != null; getOkButton().setEnabled(action != null); if (action != null) { name.setActionName(action.getName()); triggers.setTriggers(action.getTriggers()); response.setResponse(action.getResponse()); response.setFormatter(action.getNewFormat()); conditions.setActionTrigger(action.getTriggers()[0]); conditions.setConditions(action.getConditions()); conditions.setConditionTree(action.getRealConditionTree()); advanced.setActionEnabled(action.getStatus() != ActionStatus.DISABLED); advanced.setConcurrencyGroup(action.getConcurrencyGroup()); advanced.setActionStopped(action.isStopping()); } } /** Initialises the components. */ private void initComponents() { orderButtons(new JButton(), new JButton()); name = new ActionNamePanel(getIconManager(), "", group); triggers = new ActionTriggersPanel(getIconManager()); response = new ActionResponsePanel(getController()); conditions = new ActionConditionsPanel(getIconManager()); substitutions = new ActionSubstitutionsPanel(); advanced = new ActionAdvancedPanel(); showSubstitutions = new JButton("Show Substitutions"); showAdvanced = new JButton("Show Advanced Options"); } /** Adds the listeners. */ private void addListeners() { showSubstitutions.addActionListener(this); showAdvanced.addActionListener(this); getOkButton().addActionListener(this); getCancelButton().addActionListener(this); name.addPropertyChangeListener("validationResult", this); triggers.addPropertyChangeListener("validationResult", this); conditions.addPropertyChangeListener("validationResult", this); } /** Lays out the components. */ private void layoutComponents() { setMinimumSize(new Dimension(800, 600)); setLayout(new MigLayout("fill, hidemode 3, wrap 2, pack, hmax 80sp," + "wmin 800, wmax 800")); add(name, "grow, w 50%"); add(conditions, "spany 3, grow, pushx, w 50%"); add(triggers, "grow, w 50%"); add(response, "grow, pushy, w 50%"); add(substitutions, "spanx, grow, push"); add(advanced, "spanx, grow, push"); add(showSubstitutions, "left, sgx button, split 2"); add(showAdvanced, "left, sgx button"); add(getLeftButton(), "right, sgx button, gapleft push, split"); add(getRightButton(), "right, sgx button"); } /** * {@inheritDoc} * * @param e Action event */ @Override public void actionPerformed(final ActionEvent e) { if (e.getSource().equals(showSubstitutions)) { substitutions.setVisible(!substitutions.isVisible()); showSubstitutions .setText(substitutions.isVisible() ? "Hide Substitutions" : "Show Substitutions"); pack(); } else if (e.getSource().equals(showAdvanced)) { advanced.setVisible(!advanced.isVisible()); showAdvanced.setText(advanced.isVisible() ? "Hide Advanced Options" : "Show Advanced Options"); } else if (e.getSource().equals(getOkButton())) { save(); dispose(); } else if (e.getSource().equals(getCancelButton())) { dispose(); } } /** * {@inheritDoc} */ @Override public void validate() { super.validate(); SwingUtilities.invokeLater(new Runnable() { /** {@inheritDoc} */ @Override public void run() { centreOnOwner(); } }); } /** Saves the action being edited. */ private void save() { name.getActionName(); triggers.getTriggers(); response.getResponse(); response.getFormatter(); conditions.getConditions(); conditions.getConditionTree(); if (action == null) { - final Action newAction = actionFactory.create(group, name.getActionName(), + final Action newAction = actionFactory.getAction(group, name.getActionName(), triggers.getTriggers(), response.getResponse(), conditions.getConditions(), conditions.getConditionTree(), response.getFormatter()); newAction.setConcurrencyGroup(advanced.getConcurrencyGroup()); newAction.setEnabled(advanced.isActionEnabled()); newAction.setStopping(advanced.isActionStopped()); } else { action.setName(name.getActionName()); action.setConditionTree(conditions.getConditionTree()); action.setConditions(conditions.getConditions()); action.setNewFormat(response.getFormatter()); action.setResponse(response.getResponse()); action.setTriggers(triggers.getTriggers()); action.setConcurrencyGroup(advanced.getConcurrencyGroup()); action.setEnabled(advanced.isActionEnabled()); action.setStopping(advanced.isActionStopped()); action.save(); } } /** * {@inheritDoc} */ @Override public void propertyChange(final PropertyChangeEvent evt) { if (evt.getSource().equals(name)) { nameValid = (Boolean) evt.getNewValue(); triggers.setEnabled((Boolean) evt.getNewValue()); conditions.setEnabled((Boolean) evt.getNewValue()); response.setEnabled((Boolean) evt.getNewValue()); } else if (evt.getSource().equals(triggers)) { triggersValid = (Boolean) evt.getNewValue(); response.setEnabled((Boolean) evt.getNewValue()); conditions.setEnabled((Boolean) evt.getNewValue()); substitutions.setEnabled((Boolean) evt.getNewValue()); advanced.setEnabled((Boolean) evt.getNewValue()); substitutions.setType(triggers.getPrimaryTrigger()); conditions.setActionTrigger(triggers.getPrimaryTrigger()); } else if (evt.getSource().equals(conditions)) { conditionsValid = (Boolean) evt.getNewValue(); } getOkButton().setEnabled(triggersValid && conditionsValid && nameValid); } }
false
false
null
null
diff --git a/java/libraries/opengl/src/processing/opengl/PGraphicsOpenGL.java b/java/libraries/opengl/src/processing/opengl/PGraphicsOpenGL.java index a685907e4..7d701a3c1 100644 --- a/java/libraries/opengl/src/processing/opengl/PGraphicsOpenGL.java +++ b/java/libraries/opengl/src/processing/opengl/PGraphicsOpenGL.java @@ -1,10544 +1,10540 @@ /* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* Part of the Processing project - http://processing.org Copyright (c) 2004-12 Ben Fry and Casey Reas This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License version 2.1 as published by the Free Software Foundation. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package processing.opengl; import processing.core.PApplet; import processing.core.PFont; import processing.core.PGraphics; import processing.core.PImage; import processing.core.PMatrix; import processing.core.PMatrix2D; import processing.core.PMatrix3D; import processing.core.PShape; import processing.core.PVector; import java.net.URL; import java.nio.*; import java.util.ArrayList; import java.util.Collections; import java.util.EmptyStackException; import java.util.HashMap; import java.util.HashSet; import java.util.Set; import java.util.Stack; /** * OpenGL renderer. * */ public class PGraphicsOpenGL extends PGraphics { /** Interface between Processing and OpenGL */ public PGL pgl; /** The main PApplet renderer. */ protected static PGraphicsOpenGL pgPrimary = null; /** The renderer currently in use. */ protected static PGraphicsOpenGL pgCurrent = null; // ........................................................ // Basic rendering parameters: /** Flush modes: continuously (geometry is flushed after each call to * endShape) when-full (geometry is accumulated until a maximum size is * reached. */ static protected final int FLUSH_CONTINUOUSLY = 0; static protected final int FLUSH_WHEN_FULL = 1; /** Type of geometry: immediate is that generated with beginShape/vertex/ * endShape, retained is the result of creating a PShapeOpenGL object with * createShape. */ static protected final int IMMEDIATE = 0; static protected final int RETAINED = 1; /** Current flush mode. */ protected int flushMode = FLUSH_WHEN_FULL; // ........................................................ // VBOs for immediate rendering: public int glPolyVertexBufferID; public int glPolyColorBufferID; public int glPolyNormalBufferID; public int glPolyTexcoordBufferID; public int glPolyAmbientBufferID; public int glPolySpecularBufferID; public int glPolyEmissiveBufferID; public int glPolyShininessBufferID; public int glPolyIndexBufferID; protected boolean polyBuffersCreated = false; protected PGL.Context polyBuffersContext; public int glLineVertexBufferID; public int glLineColorBufferID; public int glLineAttribBufferID; public int glLineIndexBufferID; protected boolean lineBuffersCreated = false; protected PGL.Context lineBuffersContext; public int glPointVertexBufferID; public int glPointColorBufferID; public int glPointAttribBufferID; public int glPointIndexBufferID; protected boolean pointBuffersCreated = false; protected PGL.Context pointBuffersContext; protected static final int INIT_VERTEX_BUFFER_SIZE = 256; protected static final int INIT_INDEX_BUFFER_SIZE = 512; // ........................................................ // GL parameters static protected boolean glParamsRead = false; /** Extensions used by Processing */ static public boolean npotTexSupported; static public boolean autoMipmapGenSupported; static public boolean fboMultisampleSupported; static public boolean packedDepthStencilSupported; static public boolean blendEqSupported; /** Some hardware limits */ static public int maxTextureSize; static public int maxSamples; static public float maxPointSize; static public float maxLineWidth; static public int depthBits; static public int stencilBits; /** OpenGL information strings */ static public String OPENGL_VENDOR; static public String OPENGL_RENDERER; static public String OPENGL_VERSION; static public String OPENGL_EXTENSIONS; static public String GLSL_VERSION; // ........................................................ // GL objects: static protected HashMap<GLResource, Boolean> glTextureObjects = new HashMap<GLResource, Boolean>(); static protected HashMap<GLResource, Boolean> glVertexBuffers = new HashMap<GLResource, Boolean>(); static protected HashMap<GLResource, Boolean> glFrameBuffers = new HashMap<GLResource, Boolean>(); static protected HashMap<GLResource, Boolean> glRenderBuffers = new HashMap<GLResource, Boolean>(); static protected HashMap<GLResource, Boolean> glslPrograms = new HashMap<GLResource, Boolean>(); static protected HashMap<GLResource, Boolean> glslVertexShaders = new HashMap<GLResource, Boolean>(); static protected HashMap<GLResource, Boolean> glslFragmentShaders = new HashMap<GLResource, Boolean>(); // ........................................................ // Shaders static protected URL defPolyFlatShaderVertURL = PGraphicsOpenGL.class.getResource("PolyFlatShaderVert.glsl"); static protected URL defPolyTexShaderVertURL = PGraphicsOpenGL.class.getResource("PolyTexShaderVert.glsl"); static protected URL defPolyLightShaderVertURL = PGraphicsOpenGL.class.getResource("PolyLightShaderVert.glsl"); static protected URL defPolyFullShaderVertURL = PGraphicsOpenGL.class.getResource("PolyFullShaderVert.glsl"); static protected URL defPolyNoTexShaderFragURL = PGraphicsOpenGL.class.getResource("PolyNoTexShaderFrag.glsl"); static protected URL defPolyTexShaderFragURL = PGraphicsOpenGL.class.getResource("PolyTexShaderFrag.glsl"); static protected URL defLineShaderVertURL = PGraphicsOpenGL.class.getResource("LineShaderVert.glsl"); static protected URL defLineShaderFragURL = PGraphicsOpenGL.class.getResource("LineShaderFrag.glsl"); static protected URL defPointShaderVertURL = PGraphicsOpenGL.class.getResource("PointShaderVert.glsl"); static protected URL defPointShaderFragURL = PGraphicsOpenGL.class.getResource("PointShaderFrag.glsl"); static protected PolyFlatShader defPolyFlatShader; static protected PolyTexShader defPolyTexShader; static protected PolyLightShader defPolyLightShader; static protected PolyFullShader defPolyFullShader; static protected LineShader defLineShader; static protected PointShader defPointShader; protected PolyFlatShader polyFlatShader; protected PolyTexShader polyTexShader; protected PolyLightShader polyLightShader; protected PolyFullShader polyFullShader; protected LineShader lineShader; protected PointShader pointShader; // ........................................................ // Tessellator, geometry protected InGeometry inGeo; protected TessGeometry tessGeo; static protected Tessellator tessellator; protected TexCache texCache; // ........................................................ // Camera: /** Camera field of view. */ public float cameraFOV; /** Default position of the camera. */ public float cameraX, cameraY, cameraZ; /** Distance of the near and far planes. */ public float cameraNear, cameraFar; /** Aspect ratio of camera's view. */ public float cameraAspect; /** Actual position of the camera. */ protected float cameraEyeX, cameraEyeY, cameraEyeZ; /** Flag to indicate that we are inside beginCamera/endCamera block. */ protected boolean manipulatingCamera; // ........................................................ // All the matrices required for camera and geometry transformations. public PMatrix3D projection; public PMatrix3D camera; public PMatrix3D cameraInv; public PMatrix3D modelview; public PMatrix3D modelviewInv; public PMatrix3D projmodelview; // To pass to shaders protected float[] glProjection; protected float[] glModelview; protected float[] glProjmodelview; protected float[] glNormal; protected boolean matricesAllocated = false; /** * Marks when changes to the size have occurred, so that the camera * will be reset in beginDraw(). */ protected boolean sizeChanged; /** Modelview matrix stack **/ protected Stack<PMatrix3D> modelviewStack; /** Inverse modelview matrix stack **/ protected Stack<PMatrix3D> modelviewInvStack; /** Projection matrix stack **/ protected Stack<PMatrix3D> projectionStack; // ........................................................ // Lights: public boolean lights; public int lightCount = 0; /** Light types */ public int[] lightType; /** Light positions */ public float[] lightPosition; /** Light direction (normalized vector) */ public float[] lightNormal; /** * Ambient colors for lights. */ public float[] lightAmbient; /** * Diffuse colors for lights. */ public float[] lightDiffuse; /** * Specular colors for lights. Internally these are stored as numbers between * 0 and 1. */ public float[] lightSpecular; /** Light falloff */ public float[] lightFalloffCoefficients; /** Light spot parameters: Cosine of light spot angle * and concentration */ public float[] lightSpotParameters; /** Current specular color for lighting */ public float[] currentLightSpecular; /** Current light falloff */ public float currentLightFalloffConstant; public float currentLightFalloffLinear; public float currentLightFalloffQuadratic; protected boolean lightsAllocated = false; // ........................................................ // Texturing: public int textureWrap = Texture.CLAMP; public int textureSampling = Texture.TRILINEAR; // ........................................................ // Blending: protected int blendMode; // ........................................................ // Clipping protected boolean clip = false; // ........................................................ // Text: /** Font texture of currently selected font. */ PFontTexture textTex; // ....................................................... // Framebuffer stack: static protected Stack<FrameBuffer> fbStack; static protected FrameBuffer screenFramebuffer; static protected FrameBuffer currentFramebuffer; // ....................................................... // Offscreen rendering: protected FrameBuffer offscreenFramebuffer; protected FrameBuffer offscreenFramebufferMultisample; protected boolean offscreenMultisample; protected boolean offscreenNotCurrent; // ........................................................ // Screen surface: /** A handy reference to the PTexture bound to the drawing surface * (off or on-screen) */ protected Texture texture; /** IntBuffer wrapping the pixels array. */ protected IntBuffer pixelBuffer; /** Array to store pixels in OpenGL format. */ protected int[] rgbaPixels; /** Flag to indicate if the user is manipulating the * pixels array through the set()/get() methods */ protected boolean setgetPixels; // ........................................................ // Utility variables: /** True if we are inside a beginDraw()/endDraw() block. */ protected boolean drawing = false; /** Used to indicate an OpenGL surface recreation */ protected boolean restoreSurface = false; /** Type of pixels operation. */ static protected final int OP_NONE = 0; static protected final int OP_READ = 1; static protected final int OP_WRITE = 2; protected int pixelsOp = OP_NONE; /** Used to detect the occurrence of a frame resize event. */ protected boolean resized = false; /** Viewport dimensions. */ protected int[] viewport = {0, 0, 0, 0}; /** Used to register calls to glClear. */ protected boolean clearColorBuffer; protected boolean clearColorBuffer0; protected boolean openContour = false; protected boolean breakShape = false; protected boolean defaultEdges = false; protected PImage textureImage0; static protected final int EDGE_MIDDLE = 0; static protected final int EDGE_START = 1; static protected final int EDGE_STOP = 2; static protected final int EDGE_SINGLE = 3; protected boolean perspectiveCorrectedLines = false; /** Used in round point and ellipse tessellation. The * number of subdivisions per round point or ellipse is * calculated with the following formula: * n = max(N, (TWO_PI * size / F)) * where size is a measure of the dimensions of the circle * when projected on screen coordinates. F just sets the * minimum number of subdivisions, while a smaller F * would allow to have more detailed circles. * N = MIN_POINT_ACCURACY * F = POINT_ACCURACY_FACTOR */ final static protected int MIN_POINT_ACCURACY = 20; final static protected float POINT_ACCURACY_FACTOR = 10.0f; /** Used in quad point tessellation. */ final protected float[][] QUAD_POINT_SIGNS = { {-1, +1}, {-1, -1}, {+1, -1}, {+1, +1} }; ////////////////////////////////////////////////////////////// // INIT/ALLOCATE/FINISH public PGraphicsOpenGL() { pgl = new PGL(this); if (tessellator == null) { tessellator = new Tessellator(); } inGeo = newInGeometry(IMMEDIATE); tessGeo = newTessGeometry(IMMEDIATE); texCache = newTexCache(); glPolyVertexBufferID = 0; glPolyColorBufferID = 0; glPolyNormalBufferID = 0; glPolyTexcoordBufferID = 0; glPolyAmbientBufferID = 0; glPolySpecularBufferID = 0; glPolyEmissiveBufferID = 0; glPolyShininessBufferID = 0; glPolyIndexBufferID = 0; glLineVertexBufferID = 0; glLineColorBufferID = 0; glLineAttribBufferID = 0; glLineIndexBufferID = 0; glPointVertexBufferID = 0; glPointColorBufferID = 0; glPointAttribBufferID = 0; glPointIndexBufferID = 0; } //public void setParent(PApplet parent) // PGraphics public void setPrimary(boolean primary) { super.setPrimary(primary); format = ARGB; } //public void setPath(String path) // PGraphics //public void setAntiAlias(int samples) // PGraphics public void setFrameRate(float framerate) { pgl.setFramerate(framerate); } public void setSize(int iwidth, int iheight) { resized = (0 < width && width != iwidth) || (0 < height && height != iwidth); width = iwidth; height = iheight; // width1 = width - 1; // height1 = height - 1; allocate(); reapplySettings(); // init perspective projection based on new dimensions cameraFOV = 60 * DEG_TO_RAD; // at least for now cameraX = width / 2.0f; cameraY = height / 2.0f; cameraZ = cameraY / ((float) Math.tan(cameraFOV / 2.0f)); cameraNear = cameraZ / 10.0f; cameraFar = cameraZ * 10.0f; cameraAspect = (float) width / (float) height; // set this flag so that beginDraw() will do an update to the camera. sizeChanged = true; // Forces a restart of OpenGL so the canvas has the right size. pgl.initialized = false; } /** * Called by resize(), this handles creating the actual GLCanvas the * first time around, or simply resizing it on subsequent calls. * There is no pixel array to allocate for an OpenGL canvas * because OpenGL's pixel buffer is all handled internally. */ protected void allocate() { super.allocate(); if (!matricesAllocated) { projection = new PMatrix3D(); camera = new PMatrix3D(); cameraInv = new PMatrix3D(); modelview = new PMatrix3D(); modelviewInv = new PMatrix3D(); projmodelview = new PMatrix3D(); matricesAllocated = true; } if (!lightsAllocated) { lightType = new int[PGL.MAX_LIGHTS]; lightPosition = new float[4 * PGL.MAX_LIGHTS]; lightNormal = new float[3 * PGL.MAX_LIGHTS]; lightAmbient = new float[3 * PGL.MAX_LIGHTS]; lightDiffuse = new float[3 * PGL.MAX_LIGHTS]; lightSpecular = new float[3 * PGL.MAX_LIGHTS]; lightFalloffCoefficients = new float[3 * PGL.MAX_LIGHTS]; lightSpotParameters = new float[2 * PGL.MAX_LIGHTS]; currentLightSpecular = new float[3]; lightsAllocated = true; } } public void dispose() { // PGraphics super.dispose(); deleteFinalizedGLResources(); deletePolyBuffers(); deleteLineBuffers(); deletePointBuffers(); } protected void setFlushMode(int mode) { flushMode = mode; } ////////////////////////////////////////////////////////////// // RESOURCE HANDLING protected class GLResource { int id; int context; GLResource(int id, int context) { this.id = id; this.context = context; } public boolean equals(Object obj) { GLResource other = (GLResource)obj; return other.id == id && other.context == context; } } // Texture Objects ------------------------------------------- protected int createTextureObject(int context) { deleteFinalizedTextureObjects(); int[] temp = new int[1]; pgl.glGenTextures(1, temp, 0); int id = temp[0]; GLResource res = new GLResource(id, context); if (glTextureObjects.containsKey(res)) { showWarning("Adding same texture twice"); } else { glTextureObjects.put(res, false); } return id; } protected void deleteTextureObject(int id, int context) { GLResource res = new GLResource(id, context); if (glTextureObjects.containsKey(res)) { int[] temp = { id }; pgl.glDeleteTextures(1, temp, 0); glTextureObjects.remove(res); } } protected void deleteAllTextureObjects() { for (GLResource res : glTextureObjects.keySet()) { int[] temp = { res.id }; pgl.glDeleteTextures(1, temp, 0); } glTextureObjects.clear(); } // This is synchronized because it is called from the GC thread. synchronized protected void finalizeTextureObject(int id, int context) { GLResource res = new GLResource(id, context); if (glTextureObjects.containsKey(res)) { glTextureObjects.put(res, true); } } protected void deleteFinalizedTextureObjects() { Set<GLResource> finalized = new HashSet<GLResource>(); for (GLResource res : glTextureObjects.keySet()) { if (glTextureObjects.get(res)) { finalized.add(res); int[] temp = { res.id }; pgl.glDeleteTextures(1, temp, 0); } } for (GLResource res : finalized) { glTextureObjects.remove(res); } } protected void removeTextureObject(int id, int context) { GLResource res = new GLResource(id, context); if (glTextureObjects.containsKey(res)) { glTextureObjects.remove(res); } } // Vertex Buffer Objects ---------------------------------------------- protected int createVertexBufferObject(int context) { deleteFinalizedVertexBufferObjects(); int[] temp = new int[1]; pgl.glGenBuffers(1, temp, 0); int id = temp[0]; GLResource res = new GLResource(id, context); if (glVertexBuffers.containsKey(res)) { showWarning("Adding same VBO twice"); } else { glVertexBuffers.put(res, false); } return id; } protected void deleteVertexBufferObject(int id, int context) { GLResource res = new GLResource(id, context); if (glVertexBuffers.containsKey(res)) { int[] temp = { id }; pgl.glDeleteBuffers(1, temp, 0); glVertexBuffers.remove(res); } } protected void deleteAllVertexBufferObjects() { for (GLResource res : glVertexBuffers.keySet()) { int[] temp = { res.id }; pgl.glDeleteBuffers(1, temp, 0); } glVertexBuffers.clear(); } // This is synchronized because it is called from the GC thread. synchronized protected void finalizeVertexBufferObject(int id, int context) { GLResource res = new GLResource(id, context); if (glVertexBuffers.containsKey(res)) { glVertexBuffers.put(res, true); } } protected void deleteFinalizedVertexBufferObjects() { Set<GLResource> finalized = new HashSet<GLResource>(); for (GLResource res : glVertexBuffers.keySet()) { if (glVertexBuffers.get(res)) { finalized.add(res); int[] temp = { res.id }; pgl.glDeleteBuffers(1, temp, 0); } } for (GLResource res : finalized) { glVertexBuffers.remove(res); } } protected void removeVertexBufferObject(int id, int context) { GLResource res = new GLResource(id, context); if (glVertexBuffers.containsKey(res)) { glVertexBuffers.remove(res); } } // FrameBuffer Objects ----------------------------------------- protected int createFrameBufferObject(int context) { deleteFinalizedFrameBufferObjects(); int[] temp = new int[1]; pgl.glGenFramebuffers(1, temp, 0); int id = temp[0]; GLResource res = new GLResource(id, context); if (glFrameBuffers.containsKey(res)) { showWarning("Adding same FBO twice"); } else { glFrameBuffers.put(res, false); } return id; } protected void deleteFrameBufferObject(int id, int context) { GLResource res = new GLResource(id, context); if (glFrameBuffers.containsKey(res)) { int[] temp = { id }; pgl.glDeleteFramebuffers(1, temp, 0); glFrameBuffers.remove(res); } } protected void deleteAllFrameBufferObjects() { for (GLResource res : glFrameBuffers.keySet()) { int[] temp = { res.id }; pgl.glDeleteFramebuffers(1, temp, 0); } glFrameBuffers.clear(); } // This is synchronized because it is called from the GC thread. synchronized protected void finalizeFrameBufferObject(int id, int context) { GLResource res = new GLResource(id, context); if (glFrameBuffers.containsKey(res)) { glFrameBuffers.put(res, true); } } protected void deleteFinalizedFrameBufferObjects() { Set<GLResource> finalized = new HashSet<GLResource>(); for (GLResource res : glFrameBuffers.keySet()) { if (glFrameBuffers.get(res)) { finalized.add(res); int[] temp = { res.id }; pgl.glDeleteFramebuffers(1, temp, 0); } } for (GLResource res : finalized) { glFrameBuffers.remove(res); } } protected void removeFrameBufferObject(int id, int context) { GLResource res = new GLResource(id, context); if (glFrameBuffers.containsKey(res)) { glFrameBuffers.remove(res); } } // RenderBuffer Objects ----------------------------------------------- protected int createRenderBufferObject(int context) { deleteFinalizedRenderBufferObjects(); int[] temp = new int[1]; pgl.glGenRenderbuffers(1, temp, 0); int id = temp[0]; GLResource res = new GLResource(id, context); if (glRenderBuffers.containsKey(res)) { showWarning("Adding same renderbuffer twice"); } else { glRenderBuffers.put(res, false); } return id; } protected void deleteRenderBufferObject(int id, int context) { GLResource res = new GLResource(id, context); if (glRenderBuffers.containsKey(res)) { int[] temp = { id }; pgl.glDeleteRenderbuffers(1, temp, 0); glRenderBuffers.remove(res); } } protected void deleteAllRenderBufferObjects() { for (GLResource res : glRenderBuffers.keySet()) { int[] temp = { res.id }; pgl.glDeleteRenderbuffers(1, temp, 0); } glRenderBuffers.clear(); } // This is synchronized because it is called from the GC thread. synchronized protected void finalizeRenderBufferObject(int id, int context) { GLResource res = new GLResource(id, context); if (glRenderBuffers.containsKey(res)) { glRenderBuffers.put(res, true); } } protected void deleteFinalizedRenderBufferObjects() { Set<GLResource> finalized = new HashSet<GLResource>(); for (GLResource res : glRenderBuffers.keySet()) { if (glRenderBuffers.get(res)) { finalized.add(res); int[] temp = { res.id }; pgl.glDeleteRenderbuffers(1, temp, 0); } } for (GLResource res : finalized) { glRenderBuffers.remove(res); } } protected void removeRenderBufferObject(int id, int context) { GLResource res = new GLResource(id, context); if (glRenderBuffers.containsKey(res)) { glRenderBuffers.remove(res); } } // GLSL Program Objects ----------------------------------------------- protected int createGLSLProgramObject(int context) { deleteFinalizedGLSLProgramObjects(); int id = pgl.glCreateProgram(); GLResource res = new GLResource(id, context); if (glslPrograms.containsKey(res)) { showWarning("Adding same glsl program twice"); } else { glslPrograms.put(res, false); } return id; } protected void deleteGLSLProgramObject(int id, int context) { GLResource res = new GLResource(id, context); if (glslPrograms.containsKey(res)) { pgl.glDeleteProgram(res.id); glslPrograms.remove(res); } } protected void deleteAllGLSLProgramObjects() { for (GLResource res : glslPrograms.keySet()) { pgl.glDeleteProgram(res.id); } glslPrograms.clear(); } // This is synchronized because it is called from the GC thread. synchronized protected void finalizeGLSLProgramObject(int id, int context) { GLResource res = new GLResource(id, context); if (glslPrograms.containsKey(res)) { glslPrograms.put(res, true); } } protected void deleteFinalizedGLSLProgramObjects() { Set<GLResource> finalized = new HashSet<GLResource>(); for (GLResource res : glslPrograms.keySet()) { if (glslPrograms.get(res)) { finalized.add(res); pgl.glDeleteProgram(res.id); } } for (GLResource res : finalized) { glslPrograms.remove(res); } } protected void removeGLSLProgramObject(int id, int context) { GLResource res = new GLResource(id, context); if (glslPrograms.containsKey(res)) { glslPrograms.remove(res); } } // GLSL Vertex Shader Objects ----------------------------------------------- protected int createGLSLVertShaderObject(int context) { deleteFinalizedGLSLVertShaderObjects(); int id = pgl.glCreateShader(PGL.GL_VERTEX_SHADER); GLResource res = new GLResource(id, context); if (glslVertexShaders.containsKey(res)) { showWarning("Adding same glsl vertex shader twice"); } else { glslVertexShaders.put(res, false); } return id; } protected void deleteGLSLVertShaderObject(int id, int context) { GLResource res = new GLResource(id, context); if (glslVertexShaders.containsKey(res)) { pgl.glDeleteShader(res.id); glslVertexShaders.remove(res); } } protected void deleteAllGLSLVertShaderObjects() { for (GLResource res : glslVertexShaders.keySet()) { pgl.glDeleteShader(res.id); } glslVertexShaders.clear(); } // This is synchronized because it is called from the GC thread. synchronized protected void finalizeGLSLVertShaderObject(int id, int context) { GLResource res = new GLResource(id, context); if (glslVertexShaders.containsKey(res)) { glslVertexShaders.put(res, true); } } protected void deleteFinalizedGLSLVertShaderObjects() { Set<GLResource> finalized = new HashSet<GLResource>(); for (GLResource res : glslVertexShaders.keySet()) { if (glslVertexShaders.get(res)) { finalized.add(res); pgl.glDeleteShader(res.id); } } for (GLResource res : finalized) { glslVertexShaders.remove(res); } } protected void removeGLSLVertShaderObject(int id, int context) { GLResource res = new GLResource(id, context); if (glslVertexShaders.containsKey(res)) { glslVertexShaders.remove(res); } } // GLSL Fragment Shader Objects ----------------------------------------------- protected int createGLSLFragShaderObject(int context) { deleteFinalizedGLSLFragShaderObjects(); int id = pgl.glCreateShader(PGL.GL_FRAGMENT_SHADER); GLResource res = new GLResource(id, context); if (glslFragmentShaders.containsKey(res)) { showWarning("Adding same glsl fragment shader twice"); } else { glslFragmentShaders.put(res, false); } return id; } protected void deleteGLSLFragShaderObject(int id, int context) { GLResource res = new GLResource(id, context); if (glslFragmentShaders.containsKey(res)) { pgl.glDeleteShader(res.id); glslFragmentShaders.remove(res); } } protected void deleteAllGLSLFragShaderObjects() { for (GLResource res : glslFragmentShaders.keySet()) { pgl.glDeleteShader(res.id); } glslFragmentShaders.clear(); } // This is synchronized because it is called from the GC thread. synchronized protected void finalizeGLSLFragShaderObject(int id, int context) { GLResource res = new GLResource(id, context); if (glslFragmentShaders.containsKey(res)) { glslFragmentShaders.put(res, true); } } protected void deleteFinalizedGLSLFragShaderObjects() { Set<GLResource> finalized = new HashSet<GLResource>(); for (GLResource res : glslFragmentShaders.keySet()) { if (glslFragmentShaders.get(res)) { finalized.add(res); pgl.glDeleteShader(res.id); } } for (GLResource res : finalized) { glslFragmentShaders.remove(res); } } protected void removeGLSLFragShaderObject(int id, int context) { GLResource res = new GLResource(id, context); if (glslFragmentShaders.containsKey(res)) { glslFragmentShaders.remove(res); } } // All OpenGL resources ----------------------------------------------- protected void deleteFinalizedGLResources() { deleteFinalizedTextureObjects(); deleteFinalizedVertexBufferObjects(); deleteFinalizedFrameBufferObjects(); deleteFinalizedRenderBufferObjects(); deleteFinalizedGLSLProgramObjects(); deleteFinalizedGLSLVertShaderObjects(); deleteFinalizedGLSLFragShaderObjects(); } ////////////////////////////////////////////////////////////// // FRAMEBUFFERS public void pushFramebuffer() { fbStack.push(currentFramebuffer); } public void setFramebuffer(FrameBuffer fbo) { currentFramebuffer = fbo; currentFramebuffer.bind(); } public void popFramebuffer() { try { currentFramebuffer.finish(); currentFramebuffer = fbStack.pop(); currentFramebuffer.bind(); } catch (EmptyStackException e) { PGraphics.showWarning("P3D: Empty framebuffer stack"); } } ////////////////////////////////////////////////////////////// // FRAME RENDERING protected void createPolyBuffers() { if (!polyBuffersCreated || polyBuffersContextIsOutdated()) { polyBuffersContext = pgl.getCurrentContext(); int sizef = INIT_VERTEX_BUFFER_SIZE * PGL.SIZEOF_FLOAT; int sizei = INIT_VERTEX_BUFFER_SIZE * PGL.SIZEOF_INT; int sizex = INIT_INDEX_BUFFER_SIZE * PGL.SIZEOF_INDEX; glPolyVertexBufferID = createVertexBufferObject(polyBuffersContext.code()); pgl.glBindBuffer(PGL.GL_ARRAY_BUFFER, glPolyVertexBufferID); pgl.glBufferData(PGL.GL_ARRAY_BUFFER, 3 * sizef, null, PGL.GL_STATIC_DRAW); glPolyColorBufferID = createVertexBufferObject(polyBuffersContext.code()); pgl.glBindBuffer(PGL.GL_ARRAY_BUFFER, glPolyColorBufferID); pgl.glBufferData(PGL.GL_ARRAY_BUFFER, sizei, null, PGL.GL_STATIC_DRAW); glPolyNormalBufferID = createVertexBufferObject(polyBuffersContext.code()); pgl.glBindBuffer(PGL.GL_ARRAY_BUFFER, glPolyNormalBufferID); pgl.glBufferData(PGL.GL_ARRAY_BUFFER, 3 * sizef, null, PGL.GL_STATIC_DRAW); glPolyTexcoordBufferID = createVertexBufferObject(polyBuffersContext.code()); pgl.glBindBuffer(PGL.GL_ARRAY_BUFFER, glPolyTexcoordBufferID); pgl.glBufferData(PGL.GL_ARRAY_BUFFER, 2 * sizef, null, PGL.GL_STATIC_DRAW); glPolyAmbientBufferID = pgPrimary.createVertexBufferObject(polyBuffersContext.code()); pgl.glBindBuffer(PGL.GL_ARRAY_BUFFER, glPolyAmbientBufferID); pgl.glBufferData(PGL.GL_ARRAY_BUFFER, sizei, null, PGL.GL_STATIC_DRAW); glPolySpecularBufferID = pgPrimary.createVertexBufferObject(polyBuffersContext.code()); pgl.glBindBuffer(PGL.GL_ARRAY_BUFFER, glPolySpecularBufferID); pgl.glBufferData(PGL.GL_ARRAY_BUFFER, sizei, null, PGL.GL_STATIC_DRAW); glPolyEmissiveBufferID = pgPrimary.createVertexBufferObject(polyBuffersContext.code()); pgl.glBindBuffer(PGL.GL_ARRAY_BUFFER, glPolyEmissiveBufferID); pgl.glBufferData(PGL.GL_ARRAY_BUFFER, sizei, null, PGL.GL_STATIC_DRAW); glPolyShininessBufferID = pgPrimary.createVertexBufferObject(polyBuffersContext.code()); pgl.glBindBuffer(PGL.GL_ARRAY_BUFFER, glPolyShininessBufferID); pgl.glBufferData(PGL.GL_ARRAY_BUFFER, sizef, null, PGL.GL_STATIC_DRAW); pgl.glBindBuffer(PGL.GL_ARRAY_BUFFER, 0); glPolyIndexBufferID = createVertexBufferObject(polyBuffersContext.code()); pgl.glBindBuffer(PGL.GL_ELEMENT_ARRAY_BUFFER, glPolyIndexBufferID); pgl.glBufferData(PGL.GL_ELEMENT_ARRAY_BUFFER, sizex, null, PGL.GL_STATIC_DRAW); pgl.glBindBuffer(PGL.GL_ELEMENT_ARRAY_BUFFER, 0); polyBuffersCreated = true; } } protected void updatePolyBuffers(boolean lit, boolean tex) { createPolyBuffers(); int size = tessGeo.polyVertexCount; int sizef = size * PGL.SIZEOF_FLOAT; int sizei = size * PGL.SIZEOF_INT; pgl.glBindBuffer(PGL.GL_ARRAY_BUFFER, glPolyVertexBufferID); pgl.glBufferData(PGL.GL_ARRAY_BUFFER, 4 * sizef, FloatBuffer.wrap(tessGeo.polyVertices, 0, 4 * size), PGL.GL_STATIC_DRAW); pgl.glBindBuffer(PGL.GL_ARRAY_BUFFER, glPolyColorBufferID); pgl.glBufferData(PGL.GL_ARRAY_BUFFER, sizei, IntBuffer.wrap(tessGeo.polyColors, 0, size), PGL.GL_STATIC_DRAW); if (lit) { pgl.glBindBuffer(PGL.GL_ARRAY_BUFFER, glPolyNormalBufferID); pgl.glBufferData(PGL.GL_ARRAY_BUFFER, 3 * sizef, FloatBuffer.wrap(tessGeo.polyNormals, 0, 3 * size), PGL.GL_STATIC_DRAW); pgl.glBindBuffer(PGL.GL_ARRAY_BUFFER, glPolyAmbientBufferID); pgl.glBufferData(PGL.GL_ARRAY_BUFFER, sizei, IntBuffer.wrap(tessGeo.polyAmbient, 0, size), PGL.GL_STATIC_DRAW); pgl.glBindBuffer(PGL.GL_ARRAY_BUFFER, glPolySpecularBufferID); pgl.glBufferData(PGL.GL_ARRAY_BUFFER, sizei, IntBuffer.wrap(tessGeo.polySpecular, 0, size), PGL.GL_STATIC_DRAW); pgl.glBindBuffer(PGL.GL_ARRAY_BUFFER, glPolyEmissiveBufferID); pgl.glBufferData(PGL.GL_ARRAY_BUFFER, sizei, IntBuffer.wrap(tessGeo.polyEmissive, 0, size), PGL.GL_STATIC_DRAW); pgl.glBindBuffer(PGL.GL_ARRAY_BUFFER, glPolyShininessBufferID); pgl.glBufferData(PGL.GL_ARRAY_BUFFER, sizef, FloatBuffer.wrap(tessGeo.polyShininess, 0, size), PGL.GL_STATIC_DRAW); } if (tex) { pgl.glBindBuffer(PGL.GL_ARRAY_BUFFER, glPolyTexcoordBufferID); pgl.glBufferData(PGL.GL_ARRAY_BUFFER, 2 * sizef, FloatBuffer.wrap(tessGeo.polyTexcoords, 0, 2 * size), PGL.GL_STATIC_DRAW); } pgl.glBindBuffer(PGL.GL_ELEMENT_ARRAY_BUFFER, glPolyIndexBufferID); pgl.glBufferData(PGL.GL_ELEMENT_ARRAY_BUFFER, tessGeo.polyIndexCount * PGL.SIZEOF_INDEX, ShortBuffer.wrap(tessGeo.polyIndices, 0, tessGeo.polyIndexCount), PGL.GL_STATIC_DRAW); } protected void unbindPolyBuffers() { pgl.glBindBuffer(PGL.GL_ARRAY_BUFFER, 0); pgl.glBindBuffer(PGL.GL_ELEMENT_ARRAY_BUFFER, 0); } protected boolean polyBuffersContextIsOutdated() { return !pgl.contextIsCurrent(polyBuffersContext); } protected void deletePolyBuffers() { if (polyBuffersCreated) { deleteVertexBufferObject(glPolyVertexBufferID, polyBuffersContext.code()); glPolyVertexBufferID = 0; deleteVertexBufferObject(glPolyColorBufferID, polyBuffersContext.code()); glPolyColorBufferID = 0; deleteVertexBufferObject(glPolyNormalBufferID, polyBuffersContext.code()); glPolyNormalBufferID = 0; deleteVertexBufferObject(glPolyTexcoordBufferID, polyBuffersContext.code()); glPolyTexcoordBufferID = 0; deleteVertexBufferObject(glPolyAmbientBufferID, polyBuffersContext.code()); glPolyAmbientBufferID = 0; deleteVertexBufferObject(glPolySpecularBufferID, polyBuffersContext.code()); glPolySpecularBufferID = 0; deleteVertexBufferObject(glPolyEmissiveBufferID, polyBuffersContext.code()); glPolyEmissiveBufferID = 0; deleteVertexBufferObject(glPolyShininessBufferID, polyBuffersContext.code()); glPolyShininessBufferID = 0; deleteVertexBufferObject(glPolyIndexBufferID, polyBuffersContext.code()); glPolyIndexBufferID = 0; polyBuffersCreated = false; } } protected void createLineBuffers() { if (!lineBuffersCreated || lineBufferContextIsOutdated()) { lineBuffersContext = pgl.getCurrentContext(); int sizef = INIT_VERTEX_BUFFER_SIZE * PGL.SIZEOF_FLOAT; int sizei = INIT_VERTEX_BUFFER_SIZE * PGL.SIZEOF_INT; int sizex = INIT_INDEX_BUFFER_SIZE * PGL.SIZEOF_INDEX; glLineVertexBufferID = createVertexBufferObject(lineBuffersContext.code()); pgl.glBindBuffer(PGL.GL_ARRAY_BUFFER, glLineVertexBufferID); pgl.glBufferData(PGL.GL_ARRAY_BUFFER, 3 * sizef, null, PGL.GL_STATIC_DRAW); glLineColorBufferID = createVertexBufferObject(lineBuffersContext.code()); pgl.glBindBuffer(PGL.GL_ARRAY_BUFFER, glLineColorBufferID); pgl.glBufferData(PGL.GL_ARRAY_BUFFER, sizei, null, PGL.GL_STATIC_DRAW); glLineAttribBufferID = createVertexBufferObject(lineBuffersContext.code()); pgl.glBindBuffer(PGL.GL_ARRAY_BUFFER, glLineAttribBufferID); pgl.glBufferData(PGL.GL_ARRAY_BUFFER, 4 * sizef, null, PGL.GL_STATIC_DRAW); pgl.glBindBuffer(PGL.GL_ARRAY_BUFFER, 0); glLineIndexBufferID = createVertexBufferObject(lineBuffersContext.code()); pgl.glBindBuffer(PGL.GL_ELEMENT_ARRAY_BUFFER, glLineIndexBufferID); pgl.glBufferData(PGL.GL_ELEMENT_ARRAY_BUFFER, sizex, null, PGL.GL_STATIC_DRAW); pgl.glBindBuffer(PGL.GL_ELEMENT_ARRAY_BUFFER, 0); lineBuffersCreated = true; } } protected void updateLineBuffers() { createLineBuffers(); int size = tessGeo.lineVertexCount; int sizef = size * PGL.SIZEOF_FLOAT; int sizei = size * PGL.SIZEOF_INT; pgl.glBindBuffer(PGL.GL_ARRAY_BUFFER, glLineVertexBufferID); pgl.glBufferData(PGL.GL_ARRAY_BUFFER, 4 * sizef, FloatBuffer.wrap(tessGeo.lineVertices, 0, 4 * size), PGL.GL_STATIC_DRAW); pgl.glBindBuffer(PGL.GL_ARRAY_BUFFER, glLineColorBufferID); pgl.glBufferData(PGL.GL_ARRAY_BUFFER, sizei, IntBuffer.wrap(tessGeo.lineColors, 0, size), PGL.GL_STATIC_DRAW); pgl.glBindBuffer(PGL.GL_ARRAY_BUFFER, glLineAttribBufferID); pgl.glBufferData(PGL.GL_ARRAY_BUFFER, 4 * sizef, FloatBuffer.wrap(tessGeo.lineAttribs, 0, 4 * size), PGL.GL_STATIC_DRAW); pgl.glBindBuffer(PGL.GL_ELEMENT_ARRAY_BUFFER, glLineIndexBufferID); pgl.glBufferData(PGL.GL_ELEMENT_ARRAY_BUFFER, tessGeo.lineIndexCount * PGL.SIZEOF_INDEX, ShortBuffer.wrap(tessGeo.lineIndices, 0, tessGeo.lineIndexCount), PGL.GL_STATIC_DRAW); } protected void unbindLineBuffers() { pgl.glBindBuffer(PGL.GL_ARRAY_BUFFER, 0); pgl.glBindBuffer(PGL.GL_ELEMENT_ARRAY_BUFFER, 0); } protected boolean lineBufferContextIsOutdated() { return !pgl.contextIsCurrent(lineBuffersContext); } protected void deleteLineBuffers() { if (lineBuffersCreated) { deleteVertexBufferObject(glLineVertexBufferID, lineBuffersContext.code()); glLineVertexBufferID = 0; deleteVertexBufferObject(glLineColorBufferID, lineBuffersContext.code()); glLineColorBufferID = 0; deleteVertexBufferObject(glLineAttribBufferID, lineBuffersContext.code()); glLineAttribBufferID = 0; deleteVertexBufferObject(glLineIndexBufferID, lineBuffersContext.code()); glLineIndexBufferID = 0; lineBuffersCreated = false; } } protected void createPointBuffers() { if (!pointBuffersCreated || pointBuffersContextIsOutdated()) { pointBuffersContext = pgl.getCurrentContext(); int sizef = INIT_VERTEX_BUFFER_SIZE * PGL.SIZEOF_FLOAT; int sizei = INIT_VERTEX_BUFFER_SIZE * PGL.SIZEOF_INT; int sizex = INIT_INDEX_BUFFER_SIZE * PGL.SIZEOF_INDEX; glPointVertexBufferID = createVertexBufferObject(pointBuffersContext.code()); pgl.glBindBuffer(PGL.GL_ARRAY_BUFFER, glPointVertexBufferID); pgl.glBufferData(PGL.GL_ARRAY_BUFFER, 3 * sizef, null, PGL.GL_STATIC_DRAW); glPointColorBufferID = createVertexBufferObject(pointBuffersContext.code()); pgl.glBindBuffer(PGL.GL_ARRAY_BUFFER, glPointColorBufferID); pgl.glBufferData(PGL.GL_ARRAY_BUFFER, sizei, null, PGL.GL_STATIC_DRAW); glPointAttribBufferID = createVertexBufferObject(pointBuffersContext.code()); pgl.glBindBuffer(PGL.GL_ARRAY_BUFFER, glPointAttribBufferID); pgl.glBufferData(PGL.GL_ARRAY_BUFFER, 2 * sizef, null, PGL.GL_STATIC_DRAW); pgl.glBindBuffer(PGL.GL_ARRAY_BUFFER, 0); glPointIndexBufferID = createVertexBufferObject(pointBuffersContext.code()); pgl.glBindBuffer(PGL.GL_ELEMENT_ARRAY_BUFFER, glPointIndexBufferID); pgl.glBufferData(PGL.GL_ELEMENT_ARRAY_BUFFER, sizex, null, PGL.GL_STATIC_DRAW); pgl.glBindBuffer(PGL.GL_ELEMENT_ARRAY_BUFFER, 0); pointBuffersCreated = true; } } protected void updatePointBuffers() { createPointBuffers(); int size = tessGeo.pointVertexCount; int sizef = size * PGL.SIZEOF_FLOAT; int sizei = size * PGL.SIZEOF_INT; pgl.glBindBuffer(PGL.GL_ARRAY_BUFFER, glPointVertexBufferID); pgl.glBufferData(PGL.GL_ARRAY_BUFFER, 4 * sizef, FloatBuffer.wrap(tessGeo.pointVertices, 0, 4 * size), PGL.GL_STATIC_DRAW); pgl.glBindBuffer(PGL.GL_ARRAY_BUFFER, glPointColorBufferID); pgl.glBufferData(PGL.GL_ARRAY_BUFFER, sizei, IntBuffer.wrap(tessGeo.pointColors, 0, size), PGL.GL_STATIC_DRAW); pgl.glBindBuffer(PGL.GL_ARRAY_BUFFER, glPointAttribBufferID); pgl.glBufferData(PGL.GL_ARRAY_BUFFER, 2 * sizef, FloatBuffer.wrap(tessGeo.pointAttribs, 0, 2 * size), PGL.GL_STATIC_DRAW); pgl.glBindBuffer(PGL.GL_ELEMENT_ARRAY_BUFFER, glPointIndexBufferID); pgl.glBufferData(PGL.GL_ELEMENT_ARRAY_BUFFER, tessGeo.pointIndexCount * PGL.SIZEOF_INDEX, ShortBuffer.wrap(tessGeo.pointIndices, 0, tessGeo.pointIndexCount), PGL.GL_STATIC_DRAW); } protected void unbindPointBuffers() { pgl.glBindBuffer(PGL.GL_ARRAY_BUFFER, 0); pgl.glBindBuffer(PGL.GL_ELEMENT_ARRAY_BUFFER, 0); } protected boolean pointBuffersContextIsOutdated() { return !pgl.contextIsCurrent(pointBuffersContext); } protected void deletePointBuffers() { if (pointBuffersCreated) { deleteVertexBufferObject(glPointVertexBufferID, pointBuffersContext.code()); glPointVertexBufferID = 0; deleteVertexBufferObject(glPointColorBufferID, pointBuffersContext.code()); glPointColorBufferID = 0; deleteVertexBufferObject(glPointAttribBufferID, pointBuffersContext.code()); glPointAttribBufferID = 0; deleteVertexBufferObject(glPointIndexBufferID, pointBuffersContext.code()); glPointIndexBufferID = 0; pointBuffersCreated = false; } } /** * OpenGL cannot draw until a proper native peer is available, so this * returns the value of PApplet.isDisplayable() (inherited from Component). */ public boolean canDraw() { return pgl.canDraw(); } public void requestDraw() { if (primarySurface) { if (pgl.initialized) { pgl.requestDraw(); } else { initPrimary(); } } } public void beginDraw() { if (drawing) { showWarning("P3D: Already called beginDraw()."); return; } if (pgCurrent != pgPrimary && this != pgPrimary) { // It seems that the user is trying to start // another beginDraw()/endDraw() block for an // offscreen surface, still drawing on another // offscreen surface. This situation is not // catched by the drawing check above. showWarning("P3D: Already called beginDraw() for another P3D object."); return; } if (!glParamsRead) { getGLParameters(); } if (!settingsInited) { defaultSettings(); } if (primarySurface) { pgl.updatePrimary(); } else { if (!pgl.initialized) { initOffscreen(); } else { boolean outdated = offscreenFramebuffer != null && offscreenFramebuffer.contextIsOutdated(); boolean outdatedMulti = offscreenFramebufferMultisample != null && offscreenFramebufferMultisample.contextIsOutdated(); if (outdated || outdatedMulti) { pgl.initialized = false; initOffscreen(); } } pushFramebuffer(); if (offscreenMultisample) { setFramebuffer(offscreenFramebufferMultisample); } else { setFramebuffer(offscreenFramebuffer); } pgl.updateOffscreen(pgPrimary.pgl); pgl.glDrawBuffer(PGL.GL_COLOR_ATTACHMENT0); } // We are ready to go! report("top beginDraw()"); drawing = true; pgCurrent = this; inGeo.clear(); tessGeo.clear(); texCache.clear(); // Each frame starts with textures disabled. super.noTexture(); // Screen blend is needed for alpha (i.e. fonts) to work. // Using setDefaultBlend() instead of blendMode() because // the latter will set the blend mode only if it is different // from current. setDefaultBlend(); // this is necessary for 3D drawing if (hints[DISABLE_DEPTH_TEST]) { pgl.glDisable(PGL.GL_DEPTH_TEST); } else { pgl.glEnable(PGL.GL_DEPTH_TEST); } // use <= since that's what processing.core does pgl.glDepthFunc(PGL.GL_LEQUAL); if (hints[ENABLE_ACCURATE_2D]) { flushMode = FLUSH_CONTINUOUSLY; } else { flushMode = FLUSH_WHEN_FULL; } if (primarySurface) { int[] temp = new int[1]; pgl.glGetIntegerv(PGL.GL_SAMPLES, temp, 0); if (quality != temp[0] && 1 < temp[0] && 1 < quality) { quality = temp[0]; } } if (quality < 2) { pgl.glDisable(PGL.GL_MULTISAMPLE); } else { pgl.glEnable(PGL.GL_MULTISAMPLE); } pgl.glDisable(PGL.GL_POINT_SMOOTH); pgl.glDisable(PGL.GL_LINE_SMOOTH); pgl.glDisable(PGL.GL_POLYGON_SMOOTH); // setup opengl viewport. viewport[0] = 0; viewport[1] = 0; viewport[2] = width; viewport[3] = height; pgl.glViewport(viewport[0], viewport[1], viewport[2], viewport[3]); if (resized) { // To avoid having garbage in the screen after a resize, // in the case background is not called in draw(). background(0); if (texture != null) { // The screen texture should be deleted because it // corresponds to the old window size. this.removeCache(pgPrimary); this.removeParams(pgPrimary); texture = null; loadTexture(); } resized = false; } if (sizeChanged) { // Sets the default projection and camera (initializes modelview). // If the user has setup up their own projection, they'll need // to fix it after resize anyway. This helps the people who haven't // set up their own projection. defaultPerspective(); defaultCamera(); // clear the flag sizeChanged = false; } else { // The camera and projection matrices, saved when calling camera() and frustrum() // are set as the current modelview and projection matrices. This is done to // remove any additional modelview transformation (and less likely, projection // transformations) applied by the user after setting the camera and/or projection modelview.set(camera); modelviewInv.set(cameraInv); calcProjmodelview(); } if (is3D()) { noLights(); lightFalloff(1, 0, 0); lightSpecular(0, 0, 0); } // Because y is flipped, the vertices that should be specified by // the user in CCW order to define a front-facing facet, end up being // CW. pgl.glFrontFace(PGL.GL_CW); pgl.glDisable(PGL.GL_CULL_FACE); // Processing uses only one texture unit. pgl.glActiveTexture(PGL.GL_TEXTURE0); // The current normal vector is set to be parallel to the Z axis. normalX = normalY = normalZ = 0; perspectiveCorrectedLines = hints[ENABLE_PERSPECTIVE_CORRECTED_LINES]; // Clear depth and stencil buffers. pgl.glDepthMask(true); pgl.glClearColor(0, 0, 0, 0); pgl.glClear(PGL.GL_DEPTH_BUFFER_BIT | PGL.GL_STENCIL_BUFFER_BIT); if (primarySurface) { pgl.beginOnscreenDraw(clearColorBuffer); } else { pgl.beginOffscreenDraw(pgPrimary.clearColorBuffer); // Just in case the texture was recreated (in a resize event for example) offscreenFramebuffer.setColorBuffer(texture); } if (restoreSurface) { restoreSurfaceFromPixels(); restoreSurface = false; } if (hints[DISABLE_DEPTH_MASK]) { pgl.glDepthMask(false); } else { pgl.glDepthMask(true); } pixelsOp = OP_NONE; modified = false; setgetPixels = false; clearColorBuffer0 = clearColorBuffer; clearColorBuffer = false; report("bot beginDraw()"); } public void endDraw() { report("top endDraw()"); // Flushing any remaining geometry. flush(); if (!drawing) { showWarning("P3D: Cannot call endDraw() before beginDraw()."); return; } if (primarySurface) { pgl.endOnscreenDraw(clearColorBuffer0); if (!pgl.initialized || parent.frameCount == 0) { // Smooth was called at some point during drawing. We save // the current contents of the back buffer (because the // buffers haven't been swapped yet) to the pixels array. // The frameCount == 0 condition is to handle the situation when // no smooth is called in setup in the PDE, but the OpenGL appears to // be recreated due to the size() nastiness. saveSurfaceToPixels(); restoreSurface = true; } pgl.glFlush(); } else { if (offscreenMultisample) { offscreenFramebufferMultisample.copy(offscreenFramebuffer); } if (!pgl.initialized || !pgPrimary.pgl.initialized || parent.frameCount == 0) { // If the primary surface is re-initialized, this offscreen // surface needs to save its contents into the pixels array // so they can be restored after the FBOs are recreated. // Note that a consequence of how this is code works, is that // if the user changes th smooth level of the primary surface // in the middle of draw, but after drawing the offscreen surfaces // then these won't be restored in the next frame since their // endDraw() calls didn't pick up any change in the initialization // state of the primary surface. saveSurfaceToPixels(); restoreSurface = true; } popFramebuffer(); pgl.endOffscreenDraw(pgPrimary.clearColorBuffer0); pgPrimary.restoreGL(); } // Done! drawing = false; if (pgCurrent == pgPrimary) { // Done with the main surface pgCurrent = null; } else { // Done with an offscreen surface, // going back to onscreen drawing. pgCurrent = pgPrimary; } report("bot endDraw()"); } public PGL beginPGL() { return pgl; } public void endPGL() { restoreGL(); } public void restartPGL() { pgl.initialized = false; } protected void restoreGL() { blendMode(blendMode); if (hints[DISABLE_DEPTH_TEST]) { pgl.glDisable(PGL.GL_DEPTH_TEST); } else { pgl.glEnable(PGL.GL_DEPTH_TEST); } pgl.glDepthFunc(PGL.GL_LEQUAL); if (quality < 2) { pgl.glDisable(PGL.GL_MULTISAMPLE); // pgl.glEnable(PGL.GL_POINT_SMOOTH); // pgl.glEnable(PGL.GL_LINE_SMOOTH); // pgl.glEnable(PGL.GL_POLYGON_SMOOTH); } else { pgl.glEnable(PGL.GL_MULTISAMPLE); pgl.glDisable(PGL.GL_POINT_SMOOTH); pgl.glDisable(PGL.GL_LINE_SMOOTH); pgl.glDisable(PGL.GL_POLYGON_SMOOTH); } pgl.glViewport(viewport[0], viewport[1], viewport[2], viewport[3]); pgl.glFrontFace(PGL.GL_CW); pgl.glDisable(PGL.GL_CULL_FACE); pgl.glActiveTexture(PGL.GL_TEXTURE0); if (hints[DISABLE_DEPTH_MASK]) { pgl.glDepthMask(false); } else { pgl.glDepthMask(true); } } protected void beginPixelsOp(int op) { if (primarySurface) { if (pgl.primaryIsDoubleBuffered()) { // We read or write from the back buffer, where all the // drawing in the current frame is taking place. if (op == OP_READ) { pgl.glReadBuffer(PGL.GL_BACK); } else { pgl.glDrawBuffer(PGL.GL_BACK); } } offscreenNotCurrent = false; } else { // Making sure that the offscreen FBO is current. This allows to do calls // like loadPixels(), set() or get() without enclosing them between // beginDraw()/endDraw() when working with a PGraphics object. We don't // need the rest of the surface initialization/finalization, since only // the pixels are affected. if (op == OP_READ) { // We always read the screen pixels from the color FBO. offscreenNotCurrent = offscreenFramebuffer != currentFramebuffer; if (offscreenNotCurrent) { pushFramebuffer(); setFramebuffer(offscreenFramebuffer); pgl.updateOffscreen(pgPrimary.pgl); } pgl.glReadBuffer(PGL.GL_COLOR_ATTACHMENT0); } else { // We can write directly to the color FBO, or to the multisample FBO // if multisampling is enabled. if (offscreenMultisample) { offscreenNotCurrent = offscreenFramebufferMultisample != currentFramebuffer; } else { offscreenNotCurrent = offscreenFramebuffer != currentFramebuffer; } if (offscreenNotCurrent) { pushFramebuffer(); if (offscreenMultisample) { setFramebuffer(offscreenFramebufferMultisample); } else { setFramebuffer(offscreenFramebuffer); } pgl.updateOffscreen(pgPrimary.pgl); } pgl.glDrawBuffer(PGL.GL_COLOR_ATTACHMENT0); } } pixelsOp = op; } protected void endPixelsOp() { if (offscreenNotCurrent) { if (pixelsOp == OP_WRITE && offscreenMultisample) { // We were writing to the multisample FBO, so we need // to blit its contents to the color FBO. offscreenFramebufferMultisample.copy(offscreenFramebuffer); } popFramebuffer(); } pixelsOp = OP_NONE; } protected void updateGLProjection() { if (glProjection == null) { glProjection = new float[16]; } glProjection[0] = projection.m00; glProjection[1] = projection.m10; glProjection[2] = projection.m20; glProjection[3] = projection.m30; glProjection[4] = projection.m01; glProjection[5] = projection.m11; glProjection[6] = projection.m21; glProjection[7] = projection.m31; glProjection[8] = projection.m02; glProjection[9] = projection.m12; glProjection[10] = projection.m22; glProjection[11] = projection.m32; glProjection[12] = projection.m03; glProjection[13] = projection.m13; glProjection[14] = projection.m23; glProjection[15] = projection.m33; } protected void updateGLModelview() { if (glModelview == null) { glModelview = new float[16]; } glModelview[0] = modelview.m00; glModelview[1] = modelview.m10; glModelview[2] = modelview.m20; glModelview[3] = modelview.m30; glModelview[4] = modelview.m01; glModelview[5] = modelview.m11; glModelview[6] = modelview.m21; glModelview[7] = modelview.m31; glModelview[8] = modelview.m02; glModelview[9] = modelview.m12; glModelview[10] = modelview.m22; glModelview[11] = modelview.m32; glModelview[12] = modelview.m03; glModelview[13] = modelview.m13; glModelview[14] = modelview.m23; glModelview[15] = modelview.m33; } protected void calcProjmodelview() { projmodelview.set(projection); projmodelview.apply(modelview); } protected void updateGLProjmodelview() { if (glProjmodelview == null) { glProjmodelview = new float[16]; } glProjmodelview[0] = projmodelview.m00; glProjmodelview[1] = projmodelview.m10; glProjmodelview[2] = projmodelview.m20; glProjmodelview[3] = projmodelview.m30; glProjmodelview[4] = projmodelview.m01; glProjmodelview[5] = projmodelview.m11; glProjmodelview[6] = projmodelview.m21; glProjmodelview[7] = projmodelview.m31; glProjmodelview[8] = projmodelview.m02; glProjmodelview[9] = projmodelview.m12; glProjmodelview[10] = projmodelview.m22; glProjmodelview[11] = projmodelview.m32; glProjmodelview[12] = projmodelview.m03; glProjmodelview[13] = projmodelview.m13; glProjmodelview[14] = projmodelview.m23; glProjmodelview[15] = projmodelview.m33; } protected void updateGLNormal() { if (glNormal == null) { glNormal = new float[9]; } // The normal matrix is the transpose of the inverse of the // modelview (remember that gl matrices are column-major, // meaning that elements 0, 1, 2 are the first column, // 3, 4, 5 the second, etc.: glNormal[0] = modelviewInv.m00; glNormal[1] = modelviewInv.m01; glNormal[2] = modelviewInv.m02; glNormal[3] = modelviewInv.m10; glNormal[4] = modelviewInv.m11; glNormal[5] = modelviewInv.m12; glNormal[6] = modelviewInv.m20; glNormal[7] = modelviewInv.m21; glNormal[8] = modelviewInv.m22; } ////////////////////////////////////////////////////////////// // SETTINGS // protected void checkSettings() protected void defaultSettings() { super.defaultSettings(); manipulatingCamera = false; clearColorBuffer = false; if (fbStack == null) { fbStack = new Stack<FrameBuffer>(); screenFramebuffer = new FrameBuffer(parent, width, height, true); setFramebuffer(screenFramebuffer); } if (modelviewStack == null) { modelviewStack = new Stack<PMatrix3D>(); } if (modelviewInvStack == null) { modelviewInvStack = new Stack<PMatrix3D>(); } if (projectionStack == null) { projectionStack = new Stack<PMatrix3D>(); } // easiest for beginners textureMode(IMAGE); // Default material properties ambient(80); specular(125); emissive(0); shininess(1); // To indicate that the user hasn't set ambient setAmbient = false; } // reapplySettings ////////////////////////////////////////////////////////////// // HINTS public void hint(int which) { boolean oldValue = hints[PApplet.abs(which)]; super.hint(which); boolean newValue = hints[PApplet.abs(which)]; if (oldValue == newValue) { return; } if (which == DISABLE_DEPTH_TEST) { flush(); pgl.glDisable(PGL.GL_DEPTH_TEST); } else if (which == ENABLE_DEPTH_TEST) { flush(); pgl.glEnable(PGL.GL_DEPTH_TEST); } else if (which == DISABLE_DEPTH_MASK) { flush(); pgl.glDepthMask(false); } else if (which == ENABLE_DEPTH_MASK) { flush(); pgl.glDepthMask(true); } else if (which == DISABLE_ACCURATE_2D) { flush(); setFlushMode(FLUSH_WHEN_FULL); } else if (which == ENABLE_ACCURATE_2D) { flush(); setFlushMode(FLUSH_CONTINUOUSLY); } else if (which == DISABLE_TEXTURE_CACHE) { flush(); } else if (which == DISABLE_PERSPECTIVE_CORRECTED_LINES) { if (0 < tessGeo.lineVertexCount && 0 < tessGeo.lineIndexCount) { // We flush the geometry using the previous line setting. flush(); } perspectiveCorrectedLines = false; } else if (which == ENABLE_PERSPECTIVE_CORRECTED_LINES) { if (0 < tessGeo.lineVertexCount && 0 < tessGeo.lineIndexCount) { // We flush the geometry using the previous line setting. flush(); } perspectiveCorrectedLines = true; } } ////////////////////////////////////////////////////////////// // VERTEX SHAPES public void beginShape(int kind) { shape = kind; inGeo.clear(); breakShape = true; defaultEdges = true; textureImage0 = textureImage; // The superclass method is called to avoid an early flush. super.noTexture(); normalMode = NORMAL_MODE_AUTO; } public void endShape(int mode) { if (flushMode == FLUSH_WHEN_FULL && hints[DISABLE_TEXTURE_CACHE] && textureImage0 != null && textureImage == null) { // The previous shape had a texture and this one doesn't. So we need to flush // the textured geometry. textureImage = textureImage0; flush(); textureImage = null; } tessellate(mode); if ((flushMode == FLUSH_CONTINUOUSLY) || (flushMode == FLUSH_WHEN_FULL && tessGeo.isFull())) { flush(); } } protected void endShape(int[] indices) { endShape(indices, null); } protected void endShape(int[] indices, int[] edges) { if (shape != TRIANGLE && shape != TRIANGLES) { throw new RuntimeException("Indices and edges can only be set for TRIANGLE shapes"); } if (flushMode == FLUSH_WHEN_FULL && hints[DISABLE_TEXTURE_CACHE] && textureImage0 != null && textureImage == null) { // The previous shape had a texture and this one doesn't. So we need to flush // the textured geometry. textureImage = textureImage0; flush(); textureImage = null; } tessellate(indices, edges); if (flushMode == FLUSH_CONTINUOUSLY || (flushMode == FLUSH_WHEN_FULL && tessGeo.isFull())) { flush(); } } public void textureWrap(int wrap) { this.textureWrap = wrap; } public void textureSampling(int sampling) { this.textureSampling = sampling; } public void texture(PImage image) { if (flushMode == FLUSH_WHEN_FULL && hints[DISABLE_TEXTURE_CACHE] && image != textureImage0) { // Changing the texture image, so we need to flush the // tessellated geometry accumulated until now, so that // textures are not mixed. textureImage = textureImage0; flush(); } super.texture(image); } public void noTexture() { if (flushMode == FLUSH_WHEN_FULL && hints[DISABLE_TEXTURE_CACHE] && null != textureImage0) { // Changing the texture image, so we need to flush the // tessellated geometry accumulated until now, so that // textures are not mixed. textureImage = textureImage0; flush(); } super.noTexture(); } public void beginContour() { if (openContour) { showWarning("P3D: Already called beginContour()."); return; } openContour = true; breakShape = true; } public void endContour() { if (!openContour) { showWarning("P3D: Need to call beginContour() first."); return; } openContour = false; } public void vertex(float x, float y) { vertexImpl(x, y, 0, 0, 0); } public void vertex(float x, float y, float u, float v) { vertexImpl(x, y, 0, u, v); } public void vertex(float x, float y, float z) { vertexImpl(x, y, z, 0, 0); } public void vertex(float x, float y, float z, float u, float v) { vertexImpl(x, y, z, u, v); } protected void vertexImpl(float x, float y, float z, float u, float v) { boolean textured = textureImage != null; int fcolor = 0x00; if (fill || textured) { if (!textured) { fcolor = fillColor; } else { if (tint) { fcolor = tintColor; } else { fcolor = 0xffFFFFFF; } } } int scolor = 0x00; float sweight = 0; if (stroke) { scolor = strokeColor; sweight = strokeWeight; } if (textured && textureMode == IMAGE) { u = PApplet.min(1, u / textureImage.width); v = PApplet.min(1, v / textureImage.height); } inGeo.addVertex(x, y, z, fcolor, normalX, normalY, normalZ, u, v, scolor, sweight, ambientColor, specularColor, emissiveColor, shininess, vertexCode()); } protected int vertexCode() { int code = VERTEX; if (breakShape) { code = BREAK; breakShape = false; } return code; } public void clip(float a, float b, float c, float d) { if (imageMode == CORNER) { if (c < 0) { // reset a negative width a += c; c = -c; } if (d < 0) { // reset a negative height b += d; d = -d; } clipImpl(a, b, a + c, b + d); } else if (imageMode == CORNERS) { if (c < a) { // reverse because x2 < x1 float temp = a; a = c; c = temp; } if (d < b) { // reverse because y2 < y1 float temp = b; b = d; d = temp; } clipImpl(a, b, c, d); } else if (imageMode == CENTER) { // c and d are width/height if (c < 0) c = -c; if (d < 0) d = -d; float x1 = a - c/2; float y1 = b - d/2; clipImpl(x1, y1, x1 + c, y1 + d); } } protected void clipImpl(float x1, float y1, float x2, float y2) { flush(); pgl.glEnable(PGL.GL_SCISSOR_TEST); float h = y2 - y1; pgl.glScissor((int)x1, (int)(height - y1 - h), (int)(x2 - x1), (int)h); clip = true; } public void noClip() { if (clip) { flush(); pgl.glDisable(PGL.GL_SCISSOR_TEST); clip = false; } } ////////////////////////////////////////////////////////////// // RENDERING // protected void render() // protected void sort() protected void tessellate(int mode) { tessellator.setInGeometry(inGeo); tessellator.setTessGeometry(tessGeo); tessellator.setFill(fill || textureImage != null); tessellator.setStroke(stroke); tessellator.setStrokeColor(strokeColor); tessellator.setStrokeWeight(strokeWeight); tessellator.setStrokeCap(strokeCap); tessellator.setStrokeJoin(strokeJoin); tessellator.setTexCache(texCache, textureImage0, textureImage); tessellator.setTransform(modelview); tessellator.set3D(is3D()); if (shape == POINTS) { tessellator.tessellatePoints(); } else if (shape == LINES) { tessellator.tessellateLines(); } else if (shape == LINE_STRIP) { tessellator.tessellateLineStrip(); } else if (shape == LINE_LOOP) { tessellator.tessellateLineLoop(); } else if (shape == TRIANGLE || shape == TRIANGLES) { if (stroke && defaultEdges) inGeo.addTrianglesEdges(); if (normalMode == NORMAL_MODE_AUTO) inGeo.calcTrianglesNormals(); tessellator.tessellateTriangles(); } else if (shape == TRIANGLE_FAN) { if (stroke && defaultEdges) inGeo.addTriangleFanEdges(); if (normalMode == NORMAL_MODE_AUTO) inGeo.calcTriangleFanNormals(); tessellator.tessellateTriangleFan(); } else if (shape == TRIANGLE_STRIP) { if (stroke && defaultEdges) inGeo.addTriangleStripEdges(); if (normalMode == NORMAL_MODE_AUTO) inGeo.calcTriangleStripNormals(); tessellator.tessellateTriangleStrip(); } else if (shape == QUAD || shape == QUADS) { if (stroke && defaultEdges) inGeo.addQuadsEdges(); if (normalMode == NORMAL_MODE_AUTO) inGeo.calcQuadsNormals(); tessellator.tessellateQuads(); } else if (shape == QUAD_STRIP) { if (stroke && defaultEdges) inGeo.addQuadStripEdges(); if (normalMode == NORMAL_MODE_AUTO) inGeo.calcQuadStripNormals(); tessellator.tessellateQuadStrip(); } else if (shape == POLYGON) { if (stroke && defaultEdges) inGeo.addPolygonEdges(mode == CLOSE); tessellator.tessellatePolygon(false, mode == CLOSE, normalMode == NORMAL_MODE_AUTO); } } protected void tessellate(int[] indices, int[] edges) { if (edges != null) { int nedges = edges.length / 2; for (int n = 0; n < nedges; n++) { int i0 = edges[2 * n + 0]; int i1 = edges[2 * n + 1]; inGeo.addEdge(i0, i1, n == 0, n == nedges - 1); } } tessellator.setInGeometry(inGeo); tessellator.setTessGeometry(tessGeo); tessellator.setFill(fill || textureImage != null); tessellator.setStroke(stroke); tessellator.setStrokeColor(strokeColor); tessellator.setStrokeWeight(strokeWeight); tessellator.setStrokeCap(strokeCap); tessellator.setStrokeJoin(strokeJoin); tessellator.setTexCache(texCache, textureImage0, textureImage); tessellator.setTransform(modelview); tessellator.set3D(is3D()); if (stroke && defaultEdges && edges == null) inGeo.addTrianglesEdges(); if (normalMode == NORMAL_MODE_AUTO) inGeo.calcTrianglesNormals(); tessellator.tessellateTriangles(indices); } public void flush() { boolean hasPolys = 0 < tessGeo.polyVertexCount && 0 < tessGeo.polyIndexCount; boolean hasLines = 0 < tessGeo.lineVertexCount && 0 < tessGeo.lineIndexCount; boolean hasPoints = 0 < tessGeo.pointVertexCount && 0 < tessGeo.pointIndexCount; boolean hasPixels = modified && pixels != null; if (hasPixels) { // If the user has been manipulating individual pixels, // the changes need to be copied to the screen before // drawing any new geometry. flushPixels(); setgetPixels = false; } if (hasPoints || hasLines || hasPolys) { if (flushMode == FLUSH_WHEN_FULL && !hints[DISABLE_TRANSFORM_CACHE]) { // The modelview transformation has been applied already to the // tessellated vertices, so we set the OpenGL modelview matrix as // the identity to avoid applying the model transformations twice. pushMatrix(); resetMatrix(); } if (hasPolys) { flushPolys(); if (raw != null) { rawPolys(); } } if (is3D()) { if (hasLines) { flushLines(); if (raw != null) { rawLines(); } } if (hasPoints) { flushPoints(); if (raw != null) { rawPoints(); } } } if (flushMode == FLUSH_WHEN_FULL && !hints[DISABLE_TRANSFORM_CACHE]) { popMatrix(); } } tessGeo.clear(); texCache.clear(); } protected void flushPixels() { drawPixels(mx1, my1, mx2 - mx1 + 1, my2 - my1 + 1); modified = false; } protected void flushPolys() { updatePolyBuffers(lights, texCache.hasTexture); texCache.beginRender(); for (int i = 0; i < texCache.size; i++) { Texture tex = texCache.getTexture(i); // If the renderer is 2D, then lights should always be false, // so no need to worry about that. PolyShader shader = getPolyShader(lights, tex != null); shader.start(); int first = texCache.firstCache[i]; int last = texCache.lastCache[i]; IndexCache cache = tessGeo.polyIndexCache; for (int n = first; n <= last; n++) { int ioffset = n == first ? texCache.firstIndex[i] : cache.indexOffset[n]; int icount = n == last ? texCache.lastIndex[i] - ioffset + 1 : cache.indexOffset[n] + cache.indexCount[n] - ioffset; int voffset = cache.vertexOffset[n]; shader.setVertexAttribute(glPolyVertexBufferID, 4, PGL.GL_FLOAT, 0, 4 * voffset * PGL.SIZEOF_FLOAT); shader.setColorAttribute(glPolyColorBufferID, 4, PGL.GL_UNSIGNED_BYTE, 0, 4 * voffset * PGL.SIZEOF_BYTE); if (lights) { shader.setNormalAttribute(glPolyNormalBufferID, 3, PGL.GL_FLOAT, 0, 3 * voffset * PGL.SIZEOF_FLOAT); shader.setAmbientAttribute(glPolyAmbientBufferID, 4, PGL.GL_UNSIGNED_BYTE, 0, 4 * voffset * PGL.SIZEOF_BYTE); shader.setSpecularAttribute(glPolySpecularBufferID, 4, PGL.GL_UNSIGNED_BYTE, 0, 4 * voffset * PGL.SIZEOF_BYTE); shader.setEmissiveAttribute(glPolyEmissiveBufferID, 4, PGL.GL_UNSIGNED_BYTE, 0, 4 * voffset * PGL.SIZEOF_BYTE); shader.setShininessAttribute(glPolyShininessBufferID, 1, PGL.GL_FLOAT, 0, voffset * PGL.SIZEOF_FLOAT); } if (tex != null) { shader.setTexcoordAttribute(glPolyTexcoordBufferID, 2, PGL.GL_FLOAT, 0, 2 * voffset * PGL.SIZEOF_FLOAT); shader.setTexture(tex); } pgl.glBindBuffer(PGL.GL_ELEMENT_ARRAY_BUFFER, glPolyIndexBufferID); pgl.glDrawElements(PGL.GL_TRIANGLES, icount, PGL.INDEX_TYPE, ioffset * PGL.SIZEOF_INDEX); pgl.glBindBuffer(PGL.GL_ELEMENT_ARRAY_BUFFER, 0); } shader.stop(); } texCache.endRender(); unbindPolyBuffers(); } void rawPolys() { raw.colorMode(RGB); raw.noStroke(); raw.beginShape(TRIANGLES); float[] vertices = tessGeo.polyVertices; int[] color = tessGeo.polyColors; float[] uv = tessGeo.polyTexcoords; short[] indices = tessGeo.polyIndices; for (int i = 0; i < texCache.size; i++) { PImage textureImage = texCache.getTextureImage(i); int first = texCache.firstCache[i]; int last = texCache.lastCache[i]; IndexCache cache = tessGeo.polyIndexCache; for (int n = first; n <= last; n++) { int ioffset = n == first ? texCache.firstIndex[i] : cache.indexOffset[n]; int icount = n == last ? texCache.lastIndex[i] - ioffset + 1 : cache.indexOffset[n] + cache.indexCount[n] - ioffset; int voffset = cache.vertexOffset[n]; for (int tr = ioffset / 3; tr < (ioffset + icount) / 3; tr++) { int i0 = voffset + indices[3 * tr + 0]; int i1 = voffset + indices[3 * tr + 1]; int i2 = voffset + indices[3 * tr + 2]; float[] pt0 = {0, 0, 0, 0}; float[] pt1 = {0, 0, 0, 0}; float[] pt2 = {0, 0, 0, 0}; int argb0 = PGL.nativeToJavaARGB(color[i0]); int argb1 = PGL.nativeToJavaARGB(color[i1]); int argb2 = PGL.nativeToJavaARGB(color[i2]); if (flushMode == FLUSH_CONTINUOUSLY || hints[DISABLE_TRANSFORM_CACHE]) { float[] src0 = {0, 0, 0, 0}; float[] src1 = {0, 0, 0, 0}; float[] src2 = {0, 0, 0, 0}; PApplet.arrayCopy(vertices, 4 * i0, src0, 0, 4); PApplet.arrayCopy(vertices, 4 * i1, src1, 0, 4); PApplet.arrayCopy(vertices, 4 * i2, src2, 0, 4); modelview.mult(src0, pt0); modelview.mult(src1, pt1); modelview.mult(src2, pt2); } else { PApplet.arrayCopy(vertices, 4 * i0, pt0, 0, 4); PApplet.arrayCopy(vertices, 4 * i1, pt1, 0, 4); PApplet.arrayCopy(vertices, 4 * i2, pt2, 0, 4); } if (textureImage != null) { raw.texture(textureImage); if (raw.is3D()) { raw.fill(argb0); raw.vertex(pt0[X], pt0[Y], pt0[Z], uv[2 * i0 + 0], uv[2 * i0 + 1]); raw.fill(argb1); raw.vertex(pt1[X], pt1[Y], pt1[Z], uv[2 * i1 + 0], uv[2 * i1 + 1]); raw.fill(argb2); raw.vertex(pt2[X], pt2[Y], pt2[Z], uv[2 * i2 + 0], uv[2 * i2 + 1]); } else if (raw.is2D()) { float sx0 = screenXImpl(pt0[0], pt0[1], pt0[2], pt0[3]), sy0 = screenYImpl(pt0[0], pt0[1], pt0[2], pt0[3]); float sx1 = screenXImpl(pt1[0], pt1[1], pt1[2], pt1[3]), sy1 = screenYImpl(pt1[0], pt1[1], pt1[2], pt1[3]); float sx2 = screenXImpl(pt2[0], pt2[1], pt2[2], pt2[3]), sy2 = screenYImpl(pt2[0], pt2[1], pt2[2], pt2[3]); raw.fill(argb0); raw.vertex(sx0, sy0, uv[2 * i0 + 0], uv[2 * i0 + 1]); raw.fill(argb1); raw.vertex(sx1, sy1, uv[2 * i1 + 0], uv[2 * i1 + 1]); raw.fill(argb1); raw.vertex(sx2, sy2, uv[2 * i2 + 0], uv[2 * i2 + 1]); } } else { if (raw.is3D()) { raw.fill(argb0); raw.vertex(pt0[X], pt0[Y], pt0[Z]); raw.fill(argb1); raw.vertex(pt1[X], pt1[Y], pt1[Z]); raw.fill(argb2); raw.vertex(pt2[X], pt2[Y], pt2[Z]); } else if (raw.is2D()) { float sx0 = screenXImpl(pt0[0], pt0[1], pt0[2], pt0[3]), sy0 = screenYImpl(pt0[0], pt0[1], pt0[2], pt0[3]); float sx1 = screenXImpl(pt1[0], pt1[1], pt1[2], pt1[3]), sy1 = screenYImpl(pt1[0], pt1[1], pt1[2], pt1[3]); float sx2 = screenXImpl(pt2[0], pt2[1], pt2[2], pt2[3]), sy2 = screenYImpl(pt2[0], pt2[1], pt2[2], pt2[3]); raw.fill(argb0); raw.vertex(sx0, sy0); raw.fill(argb1); raw.vertex(sx1, sy1); raw.fill(argb2); raw.vertex(sx2, sy2); } } } } } raw.endShape(); } protected void flushLines() { updateLineBuffers(); LineShader shader = getLineShader(); shader.start(); IndexCache cache = tessGeo.lineIndexCache; for (int n = 0; n < cache.size; n++) { int ioffset = cache.indexOffset[n]; int icount = cache.indexCount[n]; int voffset = cache.vertexOffset[n]; shader.setVertexAttribute(glLineVertexBufferID, 4, PGL.GL_FLOAT, 0, 4 * voffset * PGL.SIZEOF_FLOAT); shader.setColorAttribute(glLineColorBufferID, 4, PGL.GL_UNSIGNED_BYTE, 0, 4 * voffset * PGL.SIZEOF_BYTE); shader.setLineAttribute(glLineAttribBufferID, 4, PGL.GL_FLOAT, 0, 4 * voffset * PGL.SIZEOF_FLOAT); pgl.glBindBuffer(PGL.GL_ELEMENT_ARRAY_BUFFER, glLineIndexBufferID); pgl.glDrawElements(PGL.GL_TRIANGLES, icount, PGL.INDEX_TYPE, ioffset * PGL.SIZEOF_INDEX); pgl.glBindBuffer(PGL.GL_ELEMENT_ARRAY_BUFFER, 0); } shader.stop(); unbindLineBuffers(); } void rawLines() { raw.colorMode(RGB); raw.noFill(); raw.strokeCap(strokeCap); raw.strokeJoin(strokeJoin); raw.beginShape(LINES); float[] vertices = tessGeo.lineVertices; int[] color = tessGeo.lineColors; float[] attribs = tessGeo.lineAttribs; short[] indices = tessGeo.lineIndices; IndexCache cache = tessGeo.lineIndexCache; for (int n = 0; n < cache.size; n++) { int ioffset = cache.indexOffset[n]; int icount = cache.indexCount[n]; int voffset = cache.vertexOffset[n]; for (int ln = ioffset / 6; ln < (ioffset + icount) / 6; ln++) { // Each line segment is defined by six indices since its // formed by two triangles. We only need the first and last // vertices. // This bunch of vertices could also be the bevel triangles, // with we detect this situation by looking at the line weight. int i0 = voffset + indices[6 * ln + 0]; int i1 = voffset + indices[6 * ln + 5]; float sw0 = 2 * attribs[4 * i0 + 3]; float sw1 = 2 * attribs[4 * i1 + 3]; if (zero(sw0)) continue; // Bevel triangles, skip. float[] pt0 = {0, 0, 0, 0}; float[] pt1 = {0, 0, 0, 0}; int argb0 = PGL.nativeToJavaARGB(color[i0]); int argb1 = PGL.nativeToJavaARGB(color[i1]); if (flushMode == FLUSH_CONTINUOUSLY || hints[DISABLE_TRANSFORM_CACHE]) { float[] src0 = {0, 0, 0, 0}; float[] src1 = {0, 0, 0, 0}; PApplet.arrayCopy(vertices, 4 * i0, src0, 0, 4); PApplet.arrayCopy(vertices, 4 * i1, src1, 0, 4); modelview.mult(src0, pt0); modelview.mult(src1, pt1); } else { PApplet.arrayCopy(vertices, 4 * i0, pt0, 0, 4); PApplet.arrayCopy(vertices, 4 * i1, pt1, 0, 4); } if (raw.is3D()) { raw.strokeWeight(sw0); raw.stroke(argb0); raw.vertex(pt0[X], pt0[Y], pt0[Z]); raw.strokeWeight(sw1); raw.stroke(argb1); raw.vertex(pt1[X], pt1[Y], pt1[Z]); } else if (raw.is2D()) { float sx0 = screenXImpl(pt0[0], pt0[1], pt0[2], pt0[3]), sy0 = screenYImpl(pt0[0], pt0[1], pt0[2], pt0[3]); float sx1 = screenXImpl(pt1[0], pt1[1], pt1[2], pt1[3]), sy1 = screenYImpl(pt1[0], pt1[1], pt1[2], pt1[3]); raw.strokeWeight(sw0); raw.stroke(argb0); raw.vertex(sx0, sy0); raw.strokeWeight(sw1); raw.stroke(argb1); raw.vertex(sx1, sy1); } } } raw.endShape(); } protected void flushPoints() { updatePointBuffers(); PointShader shader = getPointShader(); shader.start(); IndexCache cache = tessGeo.pointIndexCache; for (int n = 0; n < cache.size; n++) { int ioffset = cache.indexOffset[n]; int icount = cache.indexCount[n]; int voffset = cache.vertexOffset[n]; shader.setVertexAttribute(glPointVertexBufferID, 4, PGL.GL_FLOAT, 0, 4 * voffset * PGL.SIZEOF_FLOAT); shader.setColorAttribute(glPointColorBufferID, 4, PGL.GL_UNSIGNED_BYTE, 0, 4 * voffset * PGL.SIZEOF_BYTE); shader.setPointAttribute(glPointAttribBufferID, 2, PGL.GL_FLOAT, 0, 2 * voffset * PGL.SIZEOF_FLOAT); pgl.glBindBuffer(PGL.GL_ELEMENT_ARRAY_BUFFER, glPointIndexBufferID); pgl.glDrawElements(PGL.GL_TRIANGLES, icount, PGL.INDEX_TYPE, ioffset * PGL.SIZEOF_INDEX); pgl.glBindBuffer(PGL.GL_ELEMENT_ARRAY_BUFFER, 0); } shader.stop(); unbindPointBuffers(); } void rawPoints() { raw.colorMode(RGB); raw.noFill(); raw.strokeCap(strokeCap); raw.beginShape(POINTS); float[] vertices = tessGeo.pointVertices; int[] color = tessGeo.pointColors; float[] attribs = tessGeo.pointAttribs; short[] indices = tessGeo.pointIndices; IndexCache cache = tessGeo.pointIndexCache; for (int n = 0; n < cache.size; n++) { int ioffset = cache.indexOffset[n]; int icount = cache.indexCount[n]; int voffset = cache.vertexOffset[n]; int pt = ioffset; while (pt < (ioffset + icount) / 3) { float size = attribs[2 * pt + 2]; float weight; int perim; if (0 < size) { // round point weight = +size / 0.5f; perim = PApplet.max(MIN_POINT_ACCURACY, (int) (TWO_PI * weight / POINT_ACCURACY_FACTOR)) + 1; } else { // Square point weight = -size / 0.5f; perim = 5; } int i0 = voffset + indices[3 * pt]; int argb0 = PGL.nativeToJavaARGB(color[i0]); float[] pt0 = {0, 0, 0, 0}; if (flushMode == FLUSH_CONTINUOUSLY || hints[DISABLE_TRANSFORM_CACHE]) { float[] src0 = {0, 0, 0, 0}; PApplet.arrayCopy(vertices, 4 * i0, src0, 0, 4); modelview.mult(src0, pt0); } else { PApplet.arrayCopy(vertices, 4 * i0, pt0, 0, 4); } if (raw.is3D()) { raw.strokeWeight(weight); raw.stroke(argb0); raw.vertex(pt0[X], pt0[Y], pt0[Z]); } else if (raw.is2D()) { float sx0 = screenXImpl(pt0[0], pt0[1], pt0[2], pt0[3]), sy0 = screenYImpl(pt0[0], pt0[1], pt0[2], pt0[3]); raw.strokeWeight(weight); raw.stroke(argb0); raw.vertex(sx0, sy0); } pt += perim; } } raw.endShape(); } ////////////////////////////////////////////////////////////// // BEZIER CURVE VERTICES public void bezierVertex(float x2, float y2, float x3, float y3, float x4, float y4) { bezierVertexImpl(x2, y2, 0, x3, y3, 0, x4, y4, 0); } public void bezierVertex(float x2, float y2, float z2, float x3, float y3, float z3, float x4, float y4, float z4) { bezierVertexImpl(x2, y2, z2, x3, y3, z3, x4, y4, z4); } protected void bezierVertexImpl(float x2, float y2, float z2, float x3, float y3, float z3, float x4, float y4, float z4) { inGeo.setMaterial(fillColor, strokeColor, strokeWeight, ambientColor, specularColor, emissiveColor, shininess); inGeo.setNormal(normalX, normalY, normalZ); inGeo.addBezierVertex(x2, y2, z2, x3, y3, z3, x4, y4, z4, fill, stroke, bezierDetail, vertexCode(), shape); } public void quadraticVertex(float cx, float cy, float x3, float y3) { quadraticVertexImpl(cx, cy, 0, x3, y3, 0); } public void quadraticVertex(float cx, float cy, float cz, float x3, float y3, float z3) { quadraticVertexImpl(cx, cy, cz, x3, y3, z3); } protected void quadraticVertexImpl(float cx, float cy, float cz, float x3, float y3, float z3) { inGeo.setMaterial(fillColor, strokeColor, strokeWeight, ambientColor, specularColor, emissiveColor, shininess); inGeo.setNormal(normalX, normalY, normalZ); inGeo.addQuadraticVertex(cx, cy, cz, x3, y3, z3, fill, stroke, bezierDetail, vertexCode(), shape); } ////////////////////////////////////////////////////////////// // CATMULL-ROM CURVE VERTICES public void curveVertex(float x, float y) { curveVertexImpl(x, y, 0); } public void curveVertex(float x, float y, float z) { curveVertexImpl(x, y, z); } protected void curveVertexImpl(float x, float y, float z) { inGeo.setMaterial(fillColor, strokeColor, strokeWeight, ambientColor, specularColor, emissiveColor, shininess); inGeo.setNormal(normalX, normalY, normalZ); inGeo.addCurveVertex(x, y, z, fill, stroke, curveDetail, vertexCode(), shape); } ////////////////////////////////////////////////////////////// // POINT, LINE, TRIANGLE, QUAD public void point(float x, float y) { pointImpl(x, y, 0); } public void point(float x, float y, float z) { pointImpl(x, y, z); } protected void pointImpl(float x, float y, float z) { beginShape(POINTS); defaultEdges = false; normalMode = NORMAL_MODE_SHAPE; inGeo.setMaterial(fillColor, strokeColor, strokeWeight, ambientColor, specularColor, emissiveColor, shininess); inGeo.setNormal(normalX, normalY, normalZ); inGeo.addPoint(x, y, z, fill, stroke); endShape(); } public void line(float x1, float y1, float x2, float y2) { lineImpl(x1, y1, 0, x2, y2, 0); } public void line(float x1, float y1, float z1, float x2, float y2, float z2) { lineImpl(x1, y1, z1, x2, y2, z2); } protected void lineImpl(float x1, float y1, float z1, float x2, float y2, float z2) { beginShape(LINES); defaultEdges = false; normalMode = NORMAL_MODE_SHAPE; inGeo.setMaterial(fillColor, strokeColor, strokeWeight, ambientColor, specularColor, emissiveColor, shininess); inGeo.setNormal(normalX, normalY, normalZ); inGeo.addLine(x1, y1, z1, x2, y2, z2, fill, stroke); endShape(); } public void triangle(float x1, float y1, float x2, float y2, float x3, float y3) { beginShape(TRIANGLES); defaultEdges = false; normalMode = NORMAL_MODE_SHAPE; inGeo.setMaterial(fillColor, strokeColor, strokeWeight, ambientColor, specularColor, emissiveColor, shininess); inGeo.setNormal(normalX, normalY, normalZ); inGeo.addTriangle(x1, y1, 0, x2, y2, 0, x3, y3, 0, fill, stroke); endShape(); } public void quad(float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4) { beginShape(QUADS); defaultEdges = false; normalMode = NORMAL_MODE_SHAPE; inGeo.setMaterial(fillColor, strokeColor, strokeWeight, ambientColor, specularColor, emissiveColor, shininess); inGeo.setNormal(normalX, normalY, normalZ); inGeo.addQuad(x1, y1, 0, x2, y2, 0, x3, y3, 0, x4, y4, 0, fill, stroke); endShape(); } ////////////////////////////////////////////////////////////// // RECT // public void rectMode(int mode) public void rect(float a, float b, float c, float d) { beginShape(QUADS); defaultEdges = false; normalMode = NORMAL_MODE_SHAPE; inGeo.setMaterial(fillColor, strokeColor, strokeWeight, ambientColor, specularColor, emissiveColor, shininess); inGeo.setNormal(normalX, normalY, normalZ); inGeo.addRect(a, b, c, d, fill, stroke, rectMode); endShape(); } public void rect(float a, float b, float c, float d, float tl, float tr, float br, float bl) { beginShape(POLYGON); defaultEdges = false; normalMode = NORMAL_MODE_SHAPE; inGeo.setMaterial(fillColor, strokeColor, strokeWeight, ambientColor, specularColor, emissiveColor, shininess); inGeo.setNormal(normalX, normalY, normalZ); inGeo.addRect(a, b, c, d, tl, tr, br, bl, fill, stroke, bezierDetail, rectMode); endShape(CLOSE); } // protected void rectImpl(float x1, float y1, float x2, float y2) ////////////////////////////////////////////////////////////// // ELLIPSE // public void ellipseMode(int mode) public void ellipse(float a, float b, float c, float d) { beginShape(TRIANGLE_FAN); defaultEdges = false; normalMode = NORMAL_MODE_SHAPE; inGeo.setMaterial(fillColor, strokeColor, strokeWeight, ambientColor, specularColor, emissiveColor, shininess); inGeo.setNormal(normalX, normalY, normalZ); inGeo.addEllipse(a, b, c, d, fill, stroke, ellipseMode); endShape(); } // public void ellipse(float a, float b, float c, float d) public void arc(float a, float b, float c, float d, float start, float stop) { beginShape(TRIANGLE_FAN); defaultEdges = false; normalMode = NORMAL_MODE_SHAPE; inGeo.setMaterial(fillColor, strokeColor, strokeWeight, ambientColor, specularColor, emissiveColor, shininess); inGeo.setNormal(normalX, normalY, normalZ); inGeo.addArc(a, b, c, d, start, stop, fill, stroke, ellipseMode); endShape(); } ////////////////////////////////////////////////////////////// // BOX // public void box(float size) public void box(float w, float h, float d) { beginShape(QUADS); defaultEdges = false; normalMode = NORMAL_MODE_VERTEX; inGeo.setMaterial(fillColor, strokeColor, strokeWeight, ambientColor, specularColor, emissiveColor, shininess); inGeo.addBox(w, h, d, fill, stroke); endShape(); } ////////////////////////////////////////////////////////////// // SPHERE // public void sphereDetail(int res) // public void sphereDetail(int ures, int vres) public void sphere(float r) { beginShape(TRIANGLES); defaultEdges = false; normalMode = NORMAL_MODE_VERTEX; inGeo.setMaterial(fillColor, strokeColor, strokeWeight, ambientColor, specularColor, emissiveColor, shininess); int[] indices = inGeo.addSphere(r, sphereDetailU, sphereDetailV, fill, stroke); endShape(indices); } ////////////////////////////////////////////////////////////// // BEZIER // public float bezierPoint(float a, float b, float c, float d, float t) // public float bezierTangent(float a, float b, float c, float d, float t) // public void bezierDetail(int detail) // public void bezier(float x1, float y1, // float x2, float y2, // float x3, float y3, // float x4, float y4) // public void bezier(float x1, float y1, float z1, // float x2, float y2, float z2, // float x3, float y3, float z3, // float x4, float y4, float z4) ////////////////////////////////////////////////////////////// // CATMULL-ROM CURVES // public float curvePoint(float a, float b, float c, float d, float t) // public float curveTangent(float a, float b, float c, float d, float t) // public void curveDetail(int detail) // public void curveTightness(float tightness) // public void curve(float x1, float y1, // float x2, float y2, // float x3, float y3, // float x4, float y4) // public void curve(float x1, float y1, float z1, // float x2, float y2, float z2, // float x3, float y3, float z3, // float x4, float y4, float z4) ////////////////////////////////////////////////////////////// // IMAGES // public void imageMode(int mode) // public void image(PImage image, float x, float y) // public void image(PImage image, float x, float y, float c, float d) // public void image(PImage image, // float a, float b, float c, float d, // int u1, int v1, int u2, int v2) // protected void imageImpl(PImage image, // float x1, float y1, float x2, float y2, // int u1, int v1, int u2, int v2) ////////////////////////////////////////////////////////////// // SMOOTH public void smooth() { smooth(2); } public void smooth(int level) { smooth = true; if (maxSamples < level) { PGraphics.showWarning("Smooth level " + level + " is not supported by the hardware. Using " + maxSamples + " instead."); level = maxSamples; } if (quality != level) { quality = level; if (quality == 1) { quality = 0; } // This will trigger a surface restart next time // requestDraw() is called. pgl.initialized = false; } } public void noSmooth() { smooth = false; if (1 < quality) { quality = 0; // This will trigger a surface restart next time // requestDraw() is called. pgl.initialized = false; } } ////////////////////////////////////////////////////////////// // SHAPE // public void shapeMode(int mode) public void shape(PShape shape, float x, float y, float z) { if (shape.isVisible()) { // don't do expensive matrix ops if invisible flush(); pushMatrix(); if (shapeMode == CENTER) { translate(x - shape.getWidth() / 2, y - shape.getHeight() / 2, z - shape.getDepth() / 2); } else if ((shapeMode == CORNER) || (shapeMode == CORNERS)) { translate(x, y, z); } shape.draw(this); popMatrix(); } } public void shape(PShape shape, float x, float y, float z, float c, float d, float e) { if (shape.isVisible()) { // don't do expensive matrix ops if invisible flush(); pushMatrix(); if (shapeMode == CENTER) { // x, y and z are center, c, d and e refer to a diameter translate(x - c / 2f, y - d / 2f, z - e / 2f); scale(c / shape.getWidth(), d / shape.getHeight(), e / shape.getDepth()); } else if (shapeMode == CORNER) { translate(x, y, z); scale(c / shape.getWidth(), d / shape.getHeight(), e / shape.getDepth()); } else if (shapeMode == CORNERS) { // c, d, e are x2/y2/z2, make them into width/height/depth c -= x; d -= y; e -= z; // then same as above translate(x, y, z); scale(c / shape.getWidth(), d / shape.getHeight(), e / shape.getDepth()); } shape.draw(this); popMatrix(); } } ////////////////////////////////////////////////////////////// // SHAPE I/O public PShape loadShape(String filename) { String ext = PApplet.getExtension(filename); if (PGraphics2D.isSupportedExtension(ext)) { return PGraphics2D.loadShapeImpl(this, filename, ext); } if (PGraphics3D.isSupportedExtension(ext)) { return PGraphics3D.loadShapeImpl(this, filename, ext); } else { PGraphics.showWarning("Unsupported format"); return null; } } ////////////////////////////////////////////////////////////// // TEXT SETTINGS // public void textAlign(int align) // public void textAlign(int alignX, int alignY) // public float textAscent() // public float textDescent() // public void textFont(PFont which) // public void textFont(PFont which, float size) // public void textLeading(float leading) // public void textMode(int mode) protected boolean textModeCheck(int mode) { return mode == MODEL; } // public void textSize(float size) // public float textWidth(char c) // public float textWidth(String str) // protected float textWidthImpl(char buffer[], int start, int stop) ////////////////////////////////////////////////////////////// // TEXT IMPL // protected void textLineAlignImpl(char buffer[], int start, int stop, // float x, float y) /** * Implementation of actual drawing for a line of text. */ protected void textLineImpl(char buffer[], int start, int stop, float x, float y) { textTex = (PFontTexture)textFont.getCache(pgPrimary); if (textTex == null) { textTex = new PFontTexture(parent, textFont, maxTextureSize, maxTextureSize, is3D()); textFont.setCache(this, textTex); } else { if (textTex.contextIsOutdated()) { textTex = new PFontTexture(parent, textFont, PApplet.min(PGL.MAX_FONT_TEX_SIZE, maxTextureSize), PApplet.min(PGL.MAX_FONT_TEX_SIZE, maxTextureSize), is3D()); textFont.setCache(this, textTex); } } textTex.setFirstTexture(); // Saving style parameters modified by text rendering. int savedTextureMode = textureMode; boolean savedStroke = stroke; float savedNormalX = normalX; float savedNormalY = normalY; float savedNormalZ = normalZ; boolean savedTint = tint; int savedTintColor = tintColor; int savedBlendMode = blendMode; // Setting style used in text rendering. textureMode = NORMAL; stroke = false; normalX = 0; normalY = 0; normalZ = 1; tint = true; tintColor = fillColor; blendMode(BLEND); super.textLineImpl(buffer, start, stop, x, y); // Restoring original style. textureMode = savedTextureMode; stroke = savedStroke; normalX = savedNormalX; normalY = savedNormalY; normalZ = savedNormalZ; tint = savedTint; tintColor = savedTintColor; // Note that if the user is using a blending mode different from // BLEND, and has a bunch of continuous text rendering, the performance // won't be optimal because at the end of each text() call the geometry // will be flushed when restoring the user's blend. blendMode(savedBlendMode); } protected void textCharImpl(char ch, float x, float y) { PFont.Glyph glyph = textFont.getGlyph(ch); if (glyph != null) { PFontTexture.TextureInfo tinfo = textTex.getTexInfo(glyph); if (tinfo == null) { // Adding new glyph to the font texture. tinfo = textTex.addToTexture(glyph); } if (textMode == MODEL) { float high = glyph.height / (float) textFont.getSize(); float bwidth = glyph.width / (float) textFont.getSize(); float lextent = glyph.leftExtent / (float) textFont.getSize(); float textent = glyph.topExtent / (float) textFont.getSize(); float x1 = x + lextent * textSize; float y1 = y - textent * textSize; float x2 = x1 + bwidth * textSize; float y2 = y1 + high * textSize; textCharModelImpl(tinfo, x1, y1, x2, y2); } } } protected void textCharModelImpl(PFontTexture.TextureInfo info, float x0, float y0, float x1, float y1) { if (textTex.currentTex != info.texIndex) { textTex.setTexture(info.texIndex); } PImage tex = textTex.getCurrentTexture(); beginShape(QUADS); texture(tex); vertex(x0, y0, info.u0, info.v0); vertex(x1, y0, info.u1, info.v0); vertex(x1, y1, info.u1, info.v1); vertex(x0, y1, info.u0, info.v1); endShape(); } ////////////////////////////////////////////////////////////// // MATRIX STACK public void pushMatrix() { modelviewStack.push(new PMatrix3D(modelview)); modelviewInvStack.push(new PMatrix3D(modelviewInv)); } public void popMatrix() { if (hints[DISABLE_TRANSFORM_CACHE]) { flush(); } PMatrix3D mat; mat = modelviewStack.pop(); modelview.set(mat); mat = modelviewInvStack.pop(); modelviewInv.set(mat); calcProjmodelview(); } ////////////////////////////////////////////////////////////// // MATRIX TRANSFORMATIONS public void translate(float tx, float ty) { translateImpl(tx, ty, 0); } public void translate(float tx, float ty, float tz) { translateImpl(tx, ty, tz); } protected void translateImpl(float tx, float ty, float tz) { if (hints[DISABLE_TRANSFORM_CACHE]) { flush(); } modelview.translate(tx, ty, tz); invTranslate(modelviewInv, tx, ty, tz); projmodelview.translate(tx, ty, tz); } static protected void invTranslate(PMatrix3D matrix, float tx, float ty, float tz) { matrix.preApply(1, 0, 0, -tx, 0, 1, 0, -ty, 0, 0, 1, -tz, 0, 0, 0, 1); } /** * Two dimensional rotation. Same as rotateZ (this is identical to a 3D * rotation along the z-axis) but included for clarity -- it'd be weird for * people drawing 2D graphics to be using rotateZ. And they might kick our a-- * for the confusion. */ public void rotate(float angle) { rotateImpl(angle, 0, 0, 1); } public void rotateX(float angle) { rotateImpl(angle, 1, 0, 0); } public void rotateY(float angle) { rotateImpl(angle, 0, 1, 0); } public void rotateZ(float angle) { rotateImpl(angle, 0, 0, 1); } /** * Rotate around an arbitrary vector, similar to glRotate(), except that it * takes radians (instead of degrees). */ public void rotate(float angle, float v0, float v1, float v2) { rotateImpl(angle, v0, v1, v2); } protected void rotateImpl(float angle, float v0, float v1, float v2) { if (hints[DISABLE_TRANSFORM_CACHE]) { flush(); } float norm2 = v0 * v0 + v1 * v1 + v2 * v2; if (zero(norm2)) { // The vector is zero, cannot apply rotation. return; } if (diff(norm2, 1)) { // The rotation vector is not normalized. float norm = PApplet.sqrt(norm2); v0 /= norm; v1 /= norm; v2 /= norm; } modelview.rotate(angle, v0, v1, v2); invRotate(modelviewInv, angle, v0, v1, v2); calcProjmodelview(); // Possibly cheaper than doing projmodelview.rotate() } static private void invRotate(PMatrix3D matrix, float angle, float v0, float v1, float v2) { float c = PApplet.cos(-angle); float s = PApplet.sin(-angle); float t = 1.0f - c; matrix.preApply((t*v0*v0) + c, (t*v0*v1) - (s*v2), (t*v0*v2) + (s*v1), 0, (t*v0*v1) + (s*v2), (t*v1*v1) + c, (t*v1*v2) - (s*v0), 0, (t*v0*v2) - (s*v1), (t*v1*v2) + (s*v0), (t*v2*v2) + c, 0, 0, 0, 0, 1); } /** * Same as scale(s, s, s). */ public void scale(float s) { scaleImpl(s, s, s); } /** * Same as scale(sx, sy, 1). */ public void scale(float sx, float sy) { scaleImpl(sx, sy, 1); } /** * Scale in three dimensions. */ public void scale(float sx, float sy, float sz) { scaleImpl(sx, sy, sz); } /** * Scale in three dimensions. */ protected void scaleImpl(float sx, float sy, float sz) { if (hints[DISABLE_TRANSFORM_CACHE]) { flush(); } modelview.scale(sx, sy, sz); invScale(modelviewInv, sx, sy, sz); projmodelview.scale(sx, sy, sz); } static protected void invScale(PMatrix3D matrix, float x, float y, float z) { matrix.preApply(1/x, 0, 0, 0, 0, 1/y, 0, 0, 0, 0, 1/z, 0, 0, 0, 0, 1); } public void shearX(float angle) { float t = (float) Math.tan(angle); applyMatrixImpl(1, t, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); } public void shearY(float angle) { float t = (float) Math.tan(angle); applyMatrixImpl(1, 0, 0, 0, t, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); } ////////////////////////////////////////////////////////////// // MATRIX MORE! public void resetMatrix() { modelview.reset(); modelviewInv.reset(); projmodelview.set(projection); } public void applyMatrix(PMatrix2D source) { applyMatrixImpl(source.m00, source.m01, 0, source.m02, source.m10, source.m11, 0, source.m12, 0, 0, 1, 0, 0, 0, 0, 1); } public void applyMatrix(float n00, float n01, float n02, float n10, float n11, float n12) { applyMatrixImpl(n00, n01, 0, n02, n10, n11, 0, n12, 0, 0, 1, 0, 0, 0, 0, 1); } public void applyMatrix(PMatrix3D source) { applyMatrixImpl(source.m00, source.m01, source.m02, source.m03, source.m10, source.m11, source.m12, source.m13, source.m20, source.m21, source.m22, source.m23, source.m30, source.m31, source.m32, source.m33); } /** * Apply a 4x4 transformation matrix to the modelview stack. */ public void applyMatrix(float n00, float n01, float n02, float n03, float n10, float n11, float n12, float n13, float n20, float n21, float n22, float n23, float n30, float n31, float n32, float n33) { applyMatrixImpl(n00, n01, n02, n03, n10, n11, n12, n13, n20, n21, n22, n23, n30, n31, n32, n33); } protected void applyMatrixImpl(float n00, float n01, float n02, float n03, float n10, float n11, float n12, float n13, float n20, float n21, float n22, float n23, float n30, float n31, float n32, float n33) { if (hints[DISABLE_TRANSFORM_CACHE]) { flush(); } modelview.apply(n00, n01, n02, n03, n10, n11, n12, n13, n20, n21, n22, n23, n30, n31, n32, n33); projmodelview.apply(n00, n01, n02, n03, n10, n11, n12, n13, n20, n21, n22, n23, n30, n31, n32, n33); } ////////////////////////////////////////////////////////////// // MATRIX GET/SET/PRINT public PMatrix getMatrix() { return modelview.get(); } // public PMatrix2D getMatrix(PMatrix2D target) public PMatrix3D getMatrix(PMatrix3D target) { if (target == null) { target = new PMatrix3D(); } target.set(modelview); return target; } // public void setMatrix(PMatrix source) public void setMatrix(PMatrix2D source) { resetMatrix(); applyMatrix(source); } /** * Set the current transformation to the contents of the specified source. */ public void setMatrix(PMatrix3D source) { resetMatrix(); applyMatrix(source); } /** * Print the current model (or "transformation") matrix. */ public void printMatrix() { modelview.print(); } ////////////////////////////////////////////////////////////// // PROJECTION public void pushProjection() { projectionStack.push(new PMatrix3D(projection)); } public void popProjection() { PMatrix3D mat = projectionStack.pop(); projection.set(mat); } public void applyProjection(PMatrix3D mat) { projection.apply(mat); } public void setProjection(PMatrix3D mat) { projection.set(mat); } ////////////////////////////////////////////////////////////// // Some float math utilities protected static boolean same(float a, float b) { return Math.abs(a - b) < PGL.FLOAT_EPS; } protected static boolean diff(float a, float b) { return PGL.FLOAT_EPS <= Math.abs(a - b); } protected static boolean zero(float a) { return Math.abs(a) < PGL.FLOAT_EPS; } protected static boolean nonZero(float a) { return PGL.FLOAT_EPS <= Math.abs(a); } ////////////////////////////////////////////////////////////// // CAMERA /** * Set matrix mode to the camera matrix (instead of the current transformation * matrix). This means applyMatrix, resetMatrix, etc. will affect the camera. * <P> * Note that the camera matrix is *not* the perspective matrix, it contains * the values of the modelview matrix immediatly after the latter was * initialized with ortho() or camera(), or the modelview matrix as result of * the operations applied between beginCamera()/endCamera(). * <P> * beginCamera() specifies that all coordinate transforms until endCamera() * should be pre-applied in inverse to the camera transform matrix. Note that * this is only challenging when a user specifies an arbitrary matrix with * applyMatrix(). Then that matrix will need to be inverted, which may not be * possible. But take heart, if a user is applying a non-invertible matrix to * the camera transform, then he is clearly up to no good, and we can wash our * hands of those bad intentions. * <P> * begin/endCamera clauses do not automatically reset the camera transform * matrix. That's because we set up a nice default camera transform in * setup(), and we expect it to hold through draw(). So we don't reset the * camera transform matrix at the top of draw(). That means that an * innocuous-looking clause like * * <PRE> * beginCamera(); * translate(0, 0, 10); * endCamera(); * </PRE> * * at the top of draw(), will result in a runaway camera that shoots * infinitely out of the screen over time. In order to prevent this, it is * necessary to call some function that does a hard reset of the camera * transform matrix inside of begin/endCamera. Two options are * * <PRE> * camera(); // sets up the nice default camera transform * resetMatrix(); // sets up the identity camera transform * </PRE> * * So to rotate a camera a constant amount, you might try * * <PRE> * beginCamera(); * camera(); * rotateY(PI / 8); * endCamera(); * </PRE> */ public void beginCamera() { if (manipulatingCamera) { throw new RuntimeException("beginCamera() cannot be called again " + "before endCamera()"); } else { manipulatingCamera = true; } } /** * Record the current settings into the camera matrix, and set the matrix mode * back to the current transformation matrix. * <P> * Note that this will destroy any settings to scale(), translate(), or * whatever, because the final camera matrix will be copied (not multiplied) * into the modelview. */ public void endCamera() { if (!manipulatingCamera) { throw new RuntimeException("Cannot call endCamera() " + "without first calling beginCamera()"); } camera.set(modelview); cameraInv.set(modelviewInv); // all done manipulatingCamera = false; } /** * Set camera to the default settings. * <P> * Processing camera behavior: * <P> * Camera behavior can be split into two separate components, camera * transformation, and projection. The transformation corresponds to the * physical location, orientation, and scale of the camera. In a physical * camera metaphor, this is what can manipulated by handling the camera body * (with the exception of scale, which doesn't really have a physcial analog). * The projection corresponds to what can be changed by manipulating the lens. * <P> * We maintain separate matrices to represent the camera transform and * projection. An important distinction between the two is that the camera * transform should be invertible, where the projection matrix should not, * since it serves to map three dimensions to two. It is possible to bake the * two matrices into a single one just by multiplying them together, but it * isn't a good idea, since lighting, z-ordering, and z-buffering all demand a * true camera z coordinate after modelview and camera transforms have been * applied but before projection. If the camera transform and projection are * combined there is no way to recover a good camera-space z-coordinate from a * model coordinate. * <P> * Fortunately, there are no functions that manipulate both camera * transformation and projection. * <P> * camera() sets the camera position, orientation, and center of the scene. It * replaces the camera transform with a new one. * <P> * The transformation functions are the same ones used to manipulate the * modelview matrix (scale, translate, rotate, etc.). But they are bracketed * with beginCamera(), endCamera() to indicate that they should apply (in * inverse), to the camera transformation matrix. */ public void camera() { camera(cameraX, cameraY, cameraZ, cameraX, cameraY, 0, 0, 1, 0); } /** * More flexible method for dealing with camera(). * <P> * The actual call is like gluLookat. Here's the real skinny on what does * what: * * <PRE> * camera(); or * camera(ex, ey, ez, cx, cy, cz, ux, uy, uz); * </PRE> * * do not need to be called from with beginCamera();/endCamera(); That's * because they always apply to the camera transformation, and they always * totally replace it. That means that any coordinate transforms done before * camera(); in draw() will be wiped out. It also means that camera() always * operates in untransformed world coordinates. Therefore it is always * redundant to call resetMatrix(); before camera(); This isn't technically * true of gluLookat, but it's pretty much how it's used. * <P> * Now, beginCamera(); and endCamera(); are useful if you want to move the * camera around using transforms like translate(), etc. They will wipe out * any coordinate system transforms that occur before them in draw(), but they * will not automatically wipe out the camera transform. This means that they * should be at the top of draw(). It also means that the following: * * <PRE> * beginCamera(); * rotateY(PI / 8); * endCamera(); * </PRE> * * will result in a camera that spins without stopping. If you want to just * rotate a small constant amount, try this: * * <PRE> * beginCamera(); * camera(); // sets up the default view * rotateY(PI / 8); * endCamera(); * </PRE> * * That will rotate a little off of the default view. Note that this is * entirely equivalent to * * <PRE> * camera(); // sets up the default view * beginCamera(); * rotateY(PI / 8); * endCamera(); * </PRE> * * because camera() doesn't care whether or not it's inside a begin/end * clause. Basically it's safe to use camera() or camera(ex, ey, ez, cx, cy, * cz, ux, uy, uz) as naked calls because they do all the matrix resetting * automatically. */ public void camera(float eyeX, float eyeY, float eyeZ, float centerX, float centerY, float centerZ, float upX, float upY, float upZ) { if (hints[DISABLE_TRANSFORM_CACHE]) { flush(); } // Calculating Z vector float z0 = eyeX - centerX; float z1 = eyeY - centerY; float z2 = eyeZ - centerZ; float mag = PApplet.sqrt(z0 * z0 + z1 * z1 + z2 * z2); if (nonZero(mag)) { z0 /= mag; z1 /= mag; z2 /= mag; } cameraEyeX = eyeX; cameraEyeY = eyeY; cameraEyeZ = eyeZ; // Calculating Y vector float y0 = upX; float y1 = upY; float y2 = upZ; // Computing X vector as Y cross Z float x0 = y1 * z2 - y2 * z1; float x1 = -y0 * z2 + y2 * z0; float x2 = y0 * z1 - y1 * z0; // Recompute Y = Z cross X y0 = z1 * x2 - z2 * x1; y1 = -z0 * x2 + z2 * x0; y2 = z0 * x1 - z1 * x0; // Cross product gives area of parallelogram, which is < 1.0 for // non-perpendicular unit-length vectors; so normalize x, y here: mag = PApplet.sqrt(x0 * x0 + x1 * x1 + x2 * x2); if (nonZero(mag)) { x0 /= mag; x1 /= mag; x2 /= mag; } mag = PApplet.sqrt(y0 * y0 + y1 * y1 + y2 * y2); if (nonZero(mag)) { y0 /= mag; y1 /= mag; y2 /= mag; } modelview.set(x0, x1, x2, 0, y0, y1, y2, 0, z0, z1, z2, 0, 0, 0, 0, 1); float tx = -eyeX; float ty = -eyeY; float tz = -eyeZ; modelview.translate(tx, ty, tz); modelviewInv.set(modelview); modelviewInv.invert(); camera.set(modelview); cameraInv.set(modelviewInv); calcProjmodelview(); } /** * Print the current camera matrix. */ public void printCamera() { camera.print(); } protected void defaultCamera() { camera(); } ////////////////////////////////////////////////////////////// // PROJECTION /** * Calls ortho() with the proper parameters for Processing's standard * orthographic projection. */ public void ortho() { ortho(-width/2, +width/2, -height/2, +height/2, cameraNear, cameraFar); } /** * Calls ortho() with the specified size of the viewing volume along * the X and Z directions. */ public void ortho(float left, float right, float bottom, float top) { ortho(left, right, bottom, top, cameraNear, cameraFar); } /** * Sets orthographic projection. The left, right, bottom and top * values refer to the top left corner of the screen, not to the * center or eye of the camera. This is like this because making * it relative to the camera is not very intuitive if we think * of the perspective function, which is also independent of the * camera position. * */ public void ortho(float left, float right, float bottom, float top, float near, float far) { // Flushing geometry with a different perspective configuration. flush(); float x = 2.0f / (right - left); float y = 2.0f / (top - bottom); float z = -2.0f / (far - near); float tx = -(right + left) / (right - left); float ty = -(top + bottom) / (top - bottom); float tz = -(far + near) / (far - near); // The minus sign is needed to invert the Y axis. projection.set(x, 0, 0, tx, 0, -y, 0, ty, 0, 0, z, tz, 0, 0, 0, 1); + + calcProjmodelview(); } /** * Calls perspective() with Processing's standard coordinate projection. * <P> * Projection functions: * <UL> * <LI>frustrum() * <LI>ortho() * <LI>perspective() * </UL> * Each of these three functions completely replaces the projection matrix * with a new one. They can be called inside setup(), and their effects will * be felt inside draw(). At the top of draw(), the projection matrix is not * reset. Therefore the last projection function to be called always * dominates. On resize, the default projection is always established, which * has perspective. * <P> * This behavior is pretty much familiar from OpenGL, except where functions * replace matrices, rather than multiplying against the previous. * <P> */ public void perspective() { perspective(cameraFOV, cameraAspect, cameraNear, cameraFar); } /** * Similar to gluPerspective(). Implementation based on Mesa's glu.c */ public void perspective(float fov, float aspect, float zNear, float zFar) { float ymax = zNear * (float) Math.tan(fov / 2); float ymin = -ymax; float xmin = ymin * aspect; float xmax = ymax * aspect; frustum(xmin, xmax, ymin, ymax, zNear, zFar); } /** * Same as glFrustum(), except that it wipes out (rather than multiplies * against) the current perspective matrix. * <P> * Implementation based on the explanation in the OpenGL blue book. */ public void frustum(float left, float right, float bottom, float top, float znear, float zfar) { // Flushing geometry with a different perspective configuration. flush(); - float temp, temp2, temp3, temp4; - temp = 2.0f * znear; - temp2 = right - left; - temp3 = top - bottom; - temp4 = zfar - znear; - - // The minus sign in the temp / temp3 term is to invert the Y axis. - projection.set(temp / temp2, 0, (right + left) / temp2, 0, - 0, -temp / temp3, (top + bottom) / temp3, 0, - 0, 0, (-zfar - znear) / temp4, (-temp * zfar) / temp4, - 0, 0, -1, 1); - + //System.out.println(projection); + projection.set((2*znear)/(right-left), 0, (right+left)/(right-left), 0, + 0, -(2*znear)/(top-bottom), (top+bottom)/(top-bottom), 0, + 0, 0, -(zfar+znear)/(zfar-znear),-(2*zfar*znear)/(zfar-znear), + 0, 0, -1, 0); + calcProjmodelview(); } /** * Print the current projection matrix. */ public void printProjection() { projection.print(); } protected void defaultPerspective() { perspective(); } ////////////////////////////////////////////////////////////// // SCREEN AND MODEL COORDS public float screenX(float x, float y) { return screenXImpl(x, y, 0); } public float screenY(float x, float y) { return screenYImpl(x, y, 0); } public float screenX(float x, float y, float z) { return screenXImpl(x, y, z); } public float screenY(float x, float y, float z) { return screenYImpl(x, y, z); } public float screenZ(float x, float y, float z) { return screenZImpl(x, y, z); } protected float screenXImpl(float x, float y, float z) { float ax = modelview.m00 * x + modelview.m01 * y + modelview.m02 * z + modelview.m03; float ay = modelview.m10 * x + modelview.m11 * y + modelview.m12 * z + modelview.m13; float az = modelview.m20 * x + modelview.m21 * y + modelview.m22 * z + modelview.m23; float aw = modelview.m30 * x + modelview.m31 * y + modelview.m32 * z + modelview.m33; return screenXImpl(ax, ay, az, aw); } protected float screenXImpl(float x, float y, float z, float w) { float ox = projection.m00 * x + projection.m01 * y + projection.m02 * z + projection.m03 * w; float ow = projection.m30 * x + projection.m31 * y + projection.m32 * z + projection.m33 * w; if (nonZero(ow)) { ox /= ow; } float sx = width * (1 + ox) / 2.0f; return sx; } protected float screenYImpl(float x, float y, float z) { float ax = modelview.m00 * x + modelview.m01 * y + modelview.m02 * z + modelview.m03; float ay = modelview.m10 * x + modelview.m11 * y + modelview.m12 * z + modelview.m13; float az = modelview.m20 * x + modelview.m21 * y + modelview.m22 * z + modelview.m23; float aw = modelview.m30 * x + modelview.m31 * y + modelview.m32 * z + modelview.m33; return screenYImpl(ax, ay, az, aw); } protected float screenYImpl(float x, float y, float z, float w) { float oy = projection.m10 * x + projection.m11 * y + projection.m12 * z + projection.m13 * w; float ow = projection.m30 * x + projection.m31 * y + projection.m32 * z + projection.m33 * w; if (nonZero(ow)) { oy /= ow; } float sy = height * (1 + oy) / 2.0f; // Turning value upside down because of Processing's inverted Y axis. sy = height - sy; return sy; } protected float screenZImpl(float x, float y, float z) { float ax = modelview.m00 * x + modelview.m01 * y + modelview.m02 * z + modelview.m03; float ay = modelview.m10 * x + modelview.m11 * y + modelview.m12 * z + modelview.m13; float az = modelview.m20 * x + modelview.m21 * y + modelview.m22 * z + modelview.m23; float aw = modelview.m30 * x + modelview.m31 * y + modelview.m32 * z + modelview.m33; return screenZImpl(ax, ay, az, aw); } protected float screenZImpl(float x, float y, float z, float w) { float oz = projection.m20 * x + projection.m21 * y + projection.m22 * z + projection.m23 * w; float ow = projection.m30 * x + projection.m31 * y + projection.m32 * z + projection.m33 * w; if (nonZero(ow)) { oz /= ow; } float sz = (oz + 1) / 2.0f; return sz; } public float modelX(float x, float y, float z) { float ax = modelview.m00 * x + modelview.m01 * y + modelview.m02 * z + modelview.m03; float ay = modelview.m10 * x + modelview.m11 * y + modelview.m12 * z + modelview.m13; float az = modelview.m20 * x + modelview.m21 * y + modelview.m22 * z + modelview.m23; float aw = modelview.m30 * x + modelview.m31 * y + modelview.m32 * z + modelview.m33; float ox = cameraInv.m00 * ax + cameraInv.m01 * ay + cameraInv.m02 * az + cameraInv.m03 * aw; float ow = cameraInv.m30 * ax + cameraInv.m31 * ay + cameraInv.m32 * az + cameraInv.m33 * aw; return nonZero(ow) ? ox / ow : ox; } public float modelY(float x, float y, float z) { float ax = modelview.m00 * x + modelview.m01 * y + modelview.m02 * z + modelview.m03; float ay = modelview.m10 * x + modelview.m11 * y + modelview.m12 * z + modelview.m13; float az = modelview.m20 * x + modelview.m21 * y + modelview.m22 * z + modelview.m23; float aw = modelview.m30 * x + modelview.m31 * y + modelview.m32 * z + modelview.m33; float oy = cameraInv.m10 * ax + cameraInv.m11 * ay + cameraInv.m12 * az + cameraInv.m13 * aw; float ow = cameraInv.m30 * ax + cameraInv.m31 * ay + cameraInv.m32 * az + cameraInv.m33 * aw; return nonZero(ow) ? oy / ow : oy; } public float modelZ(float x, float y, float z) { float ax = modelview.m00 * x + modelview.m01 * y + modelview.m02 * z + modelview.m03; float ay = modelview.m10 * x + modelview.m11 * y + modelview.m12 * z + modelview.m13; float az = modelview.m20 * x + modelview.m21 * y + modelview.m22 * z + modelview.m23; float aw = modelview.m30 * x + modelview.m31 * y + modelview.m32 * z + modelview.m33; float oz = cameraInv.m20 * ax + cameraInv.m21 * ay + cameraInv.m22 * az + cameraInv.m23 * aw; float ow = cameraInv.m30 * ax + cameraInv.m31 * ay + cameraInv.m32 * az + cameraInv.m33 * aw; return nonZero(ow) ? oz / ow : oz; } // STYLES // public void pushStyle() // public void popStyle() // public void style(PStyle) // public PStyle getStyle() // public void getStyle(PStyle) ////////////////////////////////////////////////////////////// // COLOR MODE // public void colorMode(int mode) // public void colorMode(int mode, float max) // public void colorMode(int mode, float mx, float my, float mz); // public void colorMode(int mode, float mx, float my, float mz, float ma); ////////////////////////////////////////////////////////////// // COLOR CALC // protected void colorCalc(int rgb) // protected void colorCalc(int rgb, float alpha) // protected void colorCalc(float gray) // protected void colorCalc(float gray, float alpha) // protected void colorCalc(float x, float y, float z) // protected void colorCalc(float x, float y, float z, float a) // protected void colorCalcARGB(int argb, float alpha) ////////////////////////////////////////////////////////////// // STROKE CAP/JOIN/WEIGHT public void strokeWeight(float weight) { this.strokeWeight = weight; } public void strokeJoin(int join) { this.strokeJoin = join; } public void strokeCap(int cap) { this.strokeCap = cap; } ////////////////////////////////////////////////////////////// // FILL COLOR protected void fillFromCalc() { super.fillFromCalc(); if (!setAmbient) { // Setting the ambient color from the current fill // is what the old P3D did and allows to have an // default ambient color when the user doesn't specify // it explicitly. ambientFromCalc(); setAmbient = false; } } ////////////////////////////////////////////////////////////// // LIGHTING /** * Sets up an ambient and directional light using OpenGL. API taken from * PGraphics3D. * * <PRE> * The Lighting Skinny: * The way lighting works is complicated enough that it's worth * producing a document to describe it. Lighting calculations proceed * pretty much exactly as described in the OpenGL red book. * Light-affecting material properties: * AMBIENT COLOR * - multiplies by light's ambient component * - for believability this should match diffuse color * DIFFUSE COLOR * - multiplies by light's diffuse component * SPECULAR COLOR * - multiplies by light's specular component * - usually less colored than diffuse/ambient * SHININESS * - the concentration of specular effect * - this should be set pretty high (20-50) to see really * noticeable specularity * EMISSIVE COLOR * - constant additive color effect * Light types: * AMBIENT * - one color * - no specular color * - no direction * - may have falloff (constant, linear, and quadratic) * - may have position (which matters in non-constant falloff case) * - multiplies by a material's ambient reflection * DIRECTIONAL * - has diffuse color * - has specular color * - has direction * - no position * - no falloff * - multiplies by a material's diffuse and specular reflections * POINT * - has diffuse color * - has specular color * - has position * - no direction * - may have falloff (constant, linear, and quadratic) * - multiplies by a material's diffuse and specular reflections * SPOT * - has diffuse color * - has specular color * - has position * - has direction * - has cone angle (set to half the total cone angle) * - has concentration value * - may have falloff (constant, linear, and quadratic) * - multiplies by a material's diffuse and specular reflections * Normal modes: * All of the primitives (rect, box, sphere, etc.) have their normals * set nicely. During beginShape/endShape normals can be set by the user. * AUTO-NORMAL * - if no normal is set during the shape, we are in auto-normal mode * - auto-normal calculates one normal per triangle (face-normal mode) * SHAPE-NORMAL * - if one normal is set during the shape, it will be used for * all vertices * VERTEX-NORMAL * - if multiple normals are set, each normal applies to * subsequent vertices * - (except for the first one, which applies to previous * and subsequent vertices) * Efficiency consequences: * There is a major efficiency consequence of position-dependent * lighting calculations per vertex. (See below for determining * whether lighting is vertex position-dependent.) If there is no * position dependency then the only factors that affect the lighting * contribution per vertex are its colors and its normal. * There is a major efficiency win if * 1) lighting is not position dependent * 2) we are in AUTO-NORMAL or SHAPE-NORMAL mode * because then we can calculate one lighting contribution per shape * (SHAPE-NORMAL) or per triangle (AUTO-NORMAL) and simply multiply it * into the vertex colors. The converse is our worst-case performance when * 1) lighting is position dependent * 2) we are in AUTO-NORMAL mode * because then we must calculate lighting per-face * per-vertex. * Each vertex has a different lighting contribution per face in * which it appears. Yuck. * Determining vertex position dependency: * If any of the following factors are TRUE then lighting is * vertex position dependent: * 1) Any lights uses non-constant falloff * 2) There are any point or spot lights * 3) There is a light with specular color AND there is a * material with specular color * So worth noting is that default lighting (a no-falloff ambient * and a directional without specularity) is not position-dependent. * We should capitalize. * Simon Greenwold, April 2005 * </PRE> */ public void lights() { enableLighting(); // need to make sure colorMode is RGB 255 here int colorModeSaved = colorMode; colorMode = RGB; lightFalloff(1, 0, 0); lightSpecular(0, 0, 0); ambientLight(colorModeX * 0.5f, colorModeY * 0.5f, colorModeZ * 0.5f); directionalLight(colorModeX * 0.5f, colorModeY * 0.5f, colorModeZ * 0.5f, 0, 0, -1); colorMode = colorModeSaved; } /** * Disables lighting. */ public void noLights() { disableLighting(); lightCount = 0; } /** * Add an ambient light based on the current color mode. */ public void ambientLight(float r, float g, float b) { ambientLight(r, g, b, 0, 0, 0); } /** * Add an ambient light based on the current color mode. This version includes * an (x, y, z) position for situations where the falloff distance is used. */ public void ambientLight(float r, float g, float b, float x, float y, float z) { enableLighting(); if (lightCount == PGL.MAX_LIGHTS) { throw new RuntimeException("can only create " + PGL.MAX_LIGHTS + " lights"); } lightType[lightCount] = AMBIENT; lightPosition(lightCount, x, y, z, false); lightNormal(lightCount, 0, 0, 0); lightAmbient(lightCount, r, g, b); noLightDiffuse(lightCount); noLightSpecular(lightCount); noLightSpot(lightCount); lightFalloff(lightCount, currentLightFalloffConstant, currentLightFalloffLinear, currentLightFalloffQuadratic); lightCount++; } public void directionalLight(float r, float g, float b, float dx, float dy, float dz) { enableLighting(); if (lightCount == PGL.MAX_LIGHTS) { throw new RuntimeException("can only create " + PGL.MAX_LIGHTS + " lights"); } lightType[lightCount] = DIRECTIONAL; lightPosition(lightCount, 0, 0, 0, true); lightNormal(lightCount, dx, dy, dz); noLightAmbient(lightCount); lightDiffuse(lightCount, r, g, b); lightSpecular(lightCount, currentLightSpecular[0], currentLightSpecular[1], currentLightSpecular[2]); noLightSpot(lightCount); noLightFalloff(lightCount); lightCount++; } public void pointLight(float r, float g, float b, float x, float y, float z) { enableLighting(); if (lightCount == PGL.MAX_LIGHTS) { throw new RuntimeException("can only create " + PGL.MAX_LIGHTS + " lights"); } lightType[lightCount] = POINT; lightPosition(lightCount, x, y, z, false); lightNormal(lightCount, 0, 0, 0); noLightAmbient(lightCount); lightDiffuse(lightCount, r, g, b); lightSpecular(lightCount, currentLightSpecular[0], currentLightSpecular[1], currentLightSpecular[2]); noLightSpot(lightCount); lightFalloff(lightCount, currentLightFalloffConstant, currentLightFalloffLinear, currentLightFalloffQuadratic); lightCount++; } public void spotLight(float r, float g, float b, float x, float y, float z, float dx, float dy, float dz, float angle, float concentration) { enableLighting(); if (lightCount == PGL.MAX_LIGHTS) { throw new RuntimeException("can only create " + PGL.MAX_LIGHTS + " lights"); } lightType[lightCount] = SPOT; lightPosition(lightCount, x, y, z, false); lightNormal(lightCount, dx, dy, dz); noLightAmbient(lightCount); lightDiffuse(lightCount, r, g, b); lightSpecular(lightCount, currentLightSpecular[0], currentLightSpecular[1], currentLightSpecular[2]); lightSpot(lightCount, angle, concentration); lightFalloff(lightCount, currentLightFalloffConstant, currentLightFalloffLinear, currentLightFalloffQuadratic); lightCount++; } /** * Set the light falloff rates for the last light that was created. Default is * lightFalloff(1, 0, 0). */ public void lightFalloff(float constant, float linear, float quadratic) { currentLightFalloffConstant = constant; currentLightFalloffLinear = linear; currentLightFalloffQuadratic = quadratic; } /** * Set the specular color of the last light created. */ public void lightSpecular(float x, float y, float z) { colorCalc(x, y, z); currentLightSpecular[0] = calcR; currentLightSpecular[1] = calcG; currentLightSpecular[2] = calcB; } protected void enableLighting() { if (!lights) { flush(); // Flushing non-lit geometry. lights = true; } } protected void disableLighting() { if (lights) { flush(); // Flushing lit geometry. lights = false; } } protected void lightPosition(int num, float x, float y, float z, boolean dir) { lightPosition[4 * num + 0] = x * modelview.m00 + y * modelview.m01 + z * modelview.m02 + modelview.m03; lightPosition[4 * num + 1] = x * modelview.m10 + y * modelview.m11 + z * modelview.m12 + modelview.m13; lightPosition[4 * num + 2] = x * modelview.m20 + y * modelview.m21 + z * modelview.m22 + modelview.m23; // Used to inicate if the light is directional or not. lightPosition[4 * num + 3] = dir ? 1: 0; } protected void lightNormal(int num, float dx, float dy, float dz) { // Applying normal matrix to the light direction vector, which is the transpose of the inverse of the // modelview. float nx = dx * modelviewInv.m00 + dy * modelviewInv.m10 + dz * modelviewInv.m20; float ny = dx * modelviewInv.m01 + dy * modelviewInv.m11 + dz * modelviewInv.m21; float nz = dx * modelviewInv.m02 + dy * modelviewInv.m12 + dz * modelviewInv.m22; float invn = 1.0f / PApplet.dist(0, 0, 0, nx, ny, nz); lightNormal[3 * num + 0] = invn * nx; lightNormal[3 * num + 1] = invn * ny; lightNormal[3 * num + 2] = invn * nz; } protected void lightAmbient(int num, float r, float g, float b) { colorCalc(r, g, b); lightAmbient[3 * num + 0] = calcR; lightAmbient[3 * num + 1] = calcG; lightAmbient[3 * num + 2] = calcB; } protected void noLightAmbient(int num) { lightAmbient[3 * num + 0] = 0; lightAmbient[3 * num + 1] = 0; lightAmbient[3 * num + 2] = 0; } protected void lightDiffuse(int num, float r, float g, float b) { colorCalc(r, g, b); lightDiffuse[3 * num + 0] = calcR; lightDiffuse[3 * num + 1] = calcG; lightDiffuse[3 * num + 2] = calcB; } protected void noLightDiffuse(int num) { lightDiffuse[3 * num + 0] = 0; lightDiffuse[3 * num + 1] = 0; lightDiffuse[3 * num + 2] = 0; } protected void lightSpecular(int num, float r, float g, float b) { lightSpecular[3 * num + 0] = r; lightSpecular[3 * num + 1] = g; lightSpecular[3 * num + 2] = b; } protected void noLightSpecular(int num) { lightSpecular[3 * num + 0] = 0; lightSpecular[3 * num + 1] = 0; lightSpecular[3 * num + 2] = 0; } protected void lightFalloff(int num, float c0, float c1, float c2) { lightFalloffCoefficients[3 * num + 0] = c0; lightFalloffCoefficients[3 * num + 1] = c1; lightFalloffCoefficients[3 * num + 2] = c2; } protected void noLightFalloff(int num) { lightFalloffCoefficients[3 * num + 0] = 1; lightFalloffCoefficients[3 * num + 1] = 0; lightFalloffCoefficients[3 * num + 2] = 0; } protected void lightSpot(int num, float angle, float exponent) { lightSpotParameters[2 * num + 0] = Math.max(0, PApplet.cos(angle)); lightSpotParameters[2 * num + 1] = exponent; } protected void noLightSpot(int num) { lightSpotParameters[2 * num + 0] = 0; lightSpotParameters[2 * num + 1] = 0; } ////////////////////////////////////////////////////////////// // BACKGROUND protected void backgroundImpl(PImage image) { backgroundImpl(); set(0, 0, image); if (0 < parent.frameCount) { clearColorBuffer = true; } } protected void backgroundImpl() { flush(); pgl.glDepthMask(true); pgl.glClearColor(0, 0, 0, 0); pgl.glClear(PGL.GL_DEPTH_BUFFER_BIT); if (hints[DISABLE_DEPTH_MASK]) { pgl.glDepthMask(false); } else { pgl.glDepthMask(true); } pgl.glClearColor(backgroundR, backgroundG, backgroundB, backgroundA); pgl.glClear(PGL.GL_COLOR_BUFFER_BIT); if (0 < parent.frameCount) { clearColorBuffer = true; } } ////////////////////////////////////////////////////////////// // COLOR MODE // colorMode() is inherited from PGraphics. ////////////////////////////////////////////////////////////// // COLOR METHODS // public final int color(int gray) // public final int color(int gray, int alpha) // public final int color(int rgb, float alpha) // public final int color(int x, int y, int z) // public final float alpha(int what) // public final float red(int what) // public final float green(int what) // public final float blue(int what) // public final float hue(int what) // public final float saturation(int what) // public final float brightness(int what) // public int lerpColor(int c1, int c2, float amt) // static public int lerpColor(int c1, int c2, float amt, int mode) ////////////////////////////////////////////////////////////// // BEGINRAW/ENDRAW // beginRaw, endRaw() both inherited. ////////////////////////////////////////////////////////////// // WARNINGS and EXCEPTIONS // showWarning() and showException() available from PGraphics. /** * Report on anything from glError(). * Don't use this inside glBegin/glEnd otherwise it'll * throw an GL_INVALID_OPERATION error. */ public void report(String where) { if (!hints[DISABLE_OPENGL_ERROR_REPORT]) { int err = pgl.glGetError(); if (err != 0) { String errString = pgl.glErrorString(err); String msg = "OpenGL error " + err + " at " + where + ": " + errString; PGraphics.showWarning(msg); } } } ////////////////////////////////////////////////////////////// // RENDERER SUPPORT QUERIES // public boolean displayable() public boolean isGL() { return true; } ////////////////////////////////////////////////////////////// // PIMAGE METHODS // getImage // setCache, getCache, removeCache // isModified, setModified ////////////////////////////////////////////////////////////// // LOAD/UPDATE PIXELS // Initializes the pixels array, copying the current contents of the // color buffer into it. public void loadPixels() { boolean needEndDraw = false; if (!drawing) { beginDraw(); needEndDraw = true; } if (!setgetPixels) { // Draws any remaining geometry in case the user is still not // setting/getting new pixels. flush(); } allocatePixels(); if (!setgetPixels) { readPixels(); if (primarySurface) { loadTextureImpl(POINT, false); pixelsToTexture(); } } if (needEndDraw) { endDraw(); } } protected void saveSurfaceToPixels() { allocatePixels(); readPixels(); } protected void restoreSurfaceFromPixels() { drawPixels(0, 0, width, height); } protected void allocatePixels() { if ((pixels == null) || (pixels.length != width * height)) { pixels = new int[width * height]; pixelBuffer = IntBuffer.wrap(pixels); } } protected void readPixels() { beginPixelsOp(OP_READ); pixelBuffer.rewind(); pgl.glReadPixels(0, 0, width, height, PGL.GL_RGBA, PGL.GL_UNSIGNED_BYTE, pixelBuffer); endPixelsOp(); PGL.nativeToJavaARGB(pixels, width, height); } protected void drawPixels(int x, int y, int w, int h) { int i0 = y * width + x; int len = w * h; if (rgbaPixels == null || rgbaPixels.length < len) { rgbaPixels = new int[len]; } PApplet.arrayCopy(pixels, i0, rgbaPixels, 0, len); PGL.javaToNativeARGB(rgbaPixels, w, h); // Copying pixel buffer to screen texture... if (primarySurface) { loadTextureImpl(POINT, false); // (first making sure that the screen texture is valid). } pgl.copyToTexture(texture.glTarget, texture.glFormat, texture.glID, x, y, w, h, IntBuffer.wrap(rgbaPixels)); if (primarySurface || offscreenMultisample) { // ...and drawing the texture to screen... but only // if we are on the primary surface or we have // multisampled FBO. Why? Because in the case of non- // multisampled FBO, texture is actually the color buffer // used by the color FBO, so with the copy operation we // should be done updating the (off)screen buffer. beginPixelsOp(OP_WRITE); drawTexture(x, y, w, h); endPixelsOp(); } } ////////////////////////////////////////////////////////////// // GET/SET PIXELS public int get(int x, int y) { loadPixels(); setgetPixels = true; return super.get(x, y); } protected PImage getImpl(int x, int y, int w, int h) { loadPixels(); setgetPixels = true; return super.getImpl(x, y, w, h); } public void set(int x, int y, int argb) { loadPixels(); setgetPixels = true; super.set(x, y, argb); } protected void setImpl(int dx, int dy, int sx, int sy, int sw, int sh, PImage src) { loadPixels(); setgetPixels = true; super.setImpl(dx, dy, sx, sy, sw, sh, src); } ////////////////////////////////////////////////////////////// // LOAD/UPDATE TEXTURE // Copies the contents of the color buffer into the pixels // array, and then the pixels array into the screen texture. public void loadTexture() { if (primarySurface) { loadTextureImpl(POINT, false); loadPixels(); pixelsToTexture(); } } // Draws wherever it is in the screen texture right now to the screen. public void updateTexture() { flush(); beginPixelsOp(OP_WRITE); drawTexture(); endPixelsOp(); } protected void loadTextureImpl(int sampling, boolean mipmap) { if (width == 0 || height == 0) return; if (texture == null || texture.contextIsOutdated()) { Texture.Parameters params = new Texture.Parameters(ARGB, sampling, mipmap); texture = new Texture(parent, width, height, params); texture.setFlippedY(true); this.setCache(pgPrimary, texture); this.setParams(pgPrimary, params); } } protected void drawTexture() { pgl.drawTexture(texture.glTarget, texture.glID, texture.glWidth, texture.glHeight, 0, 0, width, height); } protected void drawTexture(int x, int y, int w, int h) { pgl.drawTexture(texture.glTarget, texture.glID, texture.glWidth, texture.glHeight, x, y, x + w, y + h); } protected void pixelsToTexture() { texture.set(pixels); } protected void textureToPixels() { texture.get(pixels); } ////////////////////////////////////////////////////////////// // IMAGE CONVERSION static public void nativeToJavaRGB(PImage image) { if (image.pixels != null) { PGL.nativeToJavaRGB(image.pixels, image.width, image.height); } } static public void nativeToJavaARGB(PImage image) { if (image.pixels != null) { PGL.nativeToJavaARGB(image.pixels, image.width, image.height); } } static public void javaToNativeRGB(PImage image) { if (image.pixels != null) { PGL.javaToNativeRGB(image.pixels, image.width, image.height); } } static public void javaToNativeARGB(PImage image) { if (image.pixels != null) { PGL.javaToNativeARGB(image.pixels, image.width, image.height); } } ////////////////////////////////////////////////////////////// // MASK public void mask(int alpha[]) { PGraphics.showMethodWarning("mask"); } public void mask(PImage alpha) { PGraphics.showMethodWarning("mask"); } ////////////////////////////////////////////////////////////// // FILTER /** * This is really inefficient and not a good idea in OpenGL. Use get() and * set() with a smaller image area, or call the filter on an image instead, * and then draw that. */ public void filter(int kind) { PImage temp = get(); temp.filter(kind); set(0, 0, temp); } /** * This is really inefficient and not a good idea in OpenGL. Use get() and * set() with a smaller image area, or call the filter on an image instead, * and then draw that. */ public void filter(int kind, float param) { PImage temp = get(); temp.filter(kind, param); set(0, 0, temp); } ////////////////////////////////////////////////////////////// /** * Extremely slow and not optimized, should use GL methods instead. Currently * calls a beginPixels() on the whole canvas, then does the copy, then it * calls endPixels(). */ // public void copy(int sx1, int sy1, int sx2, int sy2, // int dx1, int dy1, int dx2, int dy2) // public void copy(PImage src, // int sx1, int sy1, int sx2, int sy2, // int dx1, int dy1, int dx2, int dy2) ////////////////////////////////////////////////////////////// // BLEND // static public int blendColor(int c1, int c2, int mode) // public void blend(PImage src, // int sx, int sy, int dx, int dy, int mode) { // set(dx, dy, PImage.blendColor(src.get(sx, sy), get(dx, dy), mode)); // } /** * Extremely slow and not optimized, should use GL methods instead. Currently * calls a beginPixels() on the whole canvas, then does the copy, then it * calls endPixels(). Please help fix: <A * HREF="http://dev.processing.org/bugs/show_bug.cgi?id=941">Bug 941</A>, <A * HREF="http://dev.processing.org/bugs/show_bug.cgi?id=942">Bug 942</A>. */ // public void blend(int sx1, int sy1, int sx2, int sy2, // int dx1, int dy1, int dx2, int dy2, int mode) { // loadPixels(); // super.blend(sx1, sy1, sx2, sy2, dx1, dy1, dx2, dy2, mode); // updatePixels(); // } // public void blend(PImage src, // int sx1, int sy1, int sx2, int sy2, // int dx1, int dy1, int dx2, int dy2, int mode) { // loadPixels(); // super.blend(src, sx1, sy1, sx2, sy2, dx1, dy1, dx2, dy2, mode); // updatePixels(); // } /** * Allows to set custom blend modes for the entire scene, using openGL. * Reference article about blending modes: * http://www.pegtop.net/delphi/articles/blendmodes/ */ public void blendMode(int mode) { if (blendMode != mode) { // Flushing any remaining geometry that uses a different blending // mode. flush(); blendMode = mode; pgl.glEnable(PGL.GL_BLEND); if (mode == REPLACE) { if (blendEqSupported) { pgl.glBlendEquation(PGL.GL_FUNC_ADD); } pgl.glBlendFunc(PGL.GL_ONE, PGL.GL_ZERO); } else if (mode == BLEND) { if (blendEqSupported) { pgl.glBlendEquation(PGL.GL_FUNC_ADD); } pgl.glBlendFunc(PGL.GL_SRC_ALPHA, PGL.GL_ONE_MINUS_SRC_ALPHA); } else if (mode == ADD) { if (blendEqSupported) { pgl.glBlendEquation(PGL.GL_FUNC_ADD); } pgl.glBlendFunc(PGL.GL_SRC_ALPHA, PGL.GL_ONE); } else if (mode == SUBTRACT) { if (blendEqSupported) { pgl.glBlendEquation(PGL.GL_FUNC_ADD); } pgl.glBlendFunc(PGL.GL_ONE_MINUS_DST_COLOR, PGL.GL_ZERO); } else if (mode == LIGHTEST) { if (blendEqSupported) { pgl.glBlendEquation(PGL.GL_FUNC_MAX); } else { PGraphics.showWarning("This blend mode is not supported"); return; } pgl.glBlendFunc(PGL.GL_SRC_ALPHA, PGL.GL_DST_ALPHA); } else if (mode == DARKEST) { if (blendEqSupported) { pgl.glBlendEquation(PGL.GL_FUNC_MIN); } else { PGraphics.showWarning("This blend mode is not supported"); return; } pgl.glBlendFunc(PGL.GL_SRC_ALPHA, PGL.GL_DST_ALPHA); } else if (mode == DIFFERENCE) { if (blendEqSupported) { pgl.glBlendEquation(PGL.GL_FUNC_REVERSE_SUBTRACT); } else { PGraphics.showWarning("This blend mode is not supported"); return; } pgl.glBlendFunc(PGL.GL_ONE, PGL.GL_ONE); } else if (mode == EXCLUSION) { if (blendEqSupported) { pgl.glBlendEquation(PGL.GL_FUNC_ADD); } pgl.glBlendFunc(PGL.GL_ONE_MINUS_DST_COLOR, PGL.GL_ONE_MINUS_SRC_COLOR); } else if (mode == MULTIPLY) { if (blendEqSupported) { pgl.glBlendEquation(PGL.GL_FUNC_ADD); } pgl.glBlendFunc(PGL.GL_DST_COLOR, PGL.GL_SRC_COLOR); } else if (mode == SCREEN) { if (blendEqSupported) { pgl.glBlendEquation(PGL.GL_FUNC_ADD); } pgl.glBlendFunc(PGL.GL_ONE_MINUS_DST_COLOR, PGL.GL_ONE); } // HARD_LIGHT, SOFT_LIGHT, OVERLAY, DODGE, BURN modes cannot be implemented // in fixed-function pipeline because they require conditional blending and // non-linear blending equations. } } protected void setDefaultBlend() { blendMode = BLEND; pgl.glEnable(PGL.GL_BLEND); if (blendEqSupported) { pgl.glBlendEquation(PGL.GL_FUNC_ADD); } pgl.glBlendFunc(PGL.GL_SRC_ALPHA, PGL.GL_ONE_MINUS_SRC_ALPHA); } ////////////////////////////////////////////////////////////// // SAVE // public void save(String filename) // PImage calls loadPixels() ////////////////////////////////////////////////////////////// // TEXTURE UTILS /** * This utility method returns the texture associated to the renderer's. * drawing surface, making sure is updated to reflect the current contents * off the screen (or offscreen drawing surface). */ public Texture getTexture() { loadTexture(); return texture; } /** * This utility method returns the texture associated to the image. * creating and/or updating it if needed. * * @param img the image to have a texture metadata associated to it */ public Texture getTexture(PImage img) { Texture tex = (Texture)img.getCache(pgPrimary); if (tex == null) { tex = addTexture(img); } else { if (tex.contextIsOutdated()) { tex = addTexture(img); } if (img.isModified()) { if (img.width != tex.width || img.height != tex.height) { tex.init(img.width, img.height); } updateTexture(img, tex); } if (tex.hasBuffers()) { tex.bufferUpdate(); } } return tex; } /** * Copies the contents of the texture bound to img to its pixels array. * @param img the image to have a texture metadata associated to it */ /* public void loadPixels(PImage img) { if (img.pixels == null) { img.pixels = new int[img.width * img.height]; } Texture tex = (Texture)img.getCache(pgPrimary); if (tex == null) { tex = addTexture(img); } else { if (tex.contextIsOutdated()) { tex = addTexture(img); } if (tex.hasBuffers()) { // Updates the texture AND the pixels // array of the image at the same time, // getting the pixels directly from the // buffer data (avoiding expenive transfer // beteeen video and main memory). tex.bufferUpdate(img.pixels); } if (tex.isModified()) { // Regular pixel copy from texture. tex.get(img.pixels); } } } */ /** * This utility method creates a texture for the provided image, and adds it * to the metadata cache of the image. * @param img the image to have a texture metadata associated to it */ protected Texture addTexture(PImage img) { Texture.Parameters params = (Texture.Parameters)img.getParams(pgPrimary); if (params == null) { params = new Texture.Parameters(); if (hints[DISABLE_TEXTURE_MIPMAPS]) { params.mipmaps = false; } else { params.mipmaps = true; } params.sampling = textureSampling; if (params.sampling == Texture.TRILINEAR && !params.mipmaps) { params.sampling = Texture.BILINEAR; PGraphics.showWarning("TRILINEAR texture sampling requires mipmaps, which are disabled. Will use BILINEAR instead."); } params.wrapU = textureWrap; params.wrapV = textureWrap; img.setParams(pgPrimary, params); } if (img.parent == null) { img.parent = parent; } Texture tex = new Texture(img.parent, img.width, img.height, params); if (img.pixels == null) { img.loadPixels(); } if (img.pixels != null) tex.set(img.pixels); img.setCache(pgPrimary, tex); return tex; } protected PImage wrapTexture(Texture tex) { // We don't use the PImage(int width, int height, int mode) constructor to // avoid initializing the pixels array. PImage img = new PImage(); img.parent = parent; img.width = tex.width; img.height = tex.height; img.format = ARGB; img.setCache(pgPrimary, tex); return img; } protected void updateTexture(PImage img, Texture tex) { if (tex != null) { int x = img.getModifiedX1(); int y = img.getModifiedY1(); int w = img.getModifiedX2() - x + 1; int h = img.getModifiedY2() - y + 1; tex.set(img.pixels, x, y, w, h, img.format); } img.setModified(false); } ////////////////////////////////////////////////////////////// // RESIZE public void resize(int wide, int high) { PGraphics.showMethodWarning("resize"); } ////////////////////////////////////////////////////////////// // INITIALIZATION ROUTINES protected void initPrimary() { pgl.initPrimarySurface(quality); if (pgPrimary == null) { pgPrimary = this; } } protected void initOffscreen() { // Getting the context and capabilities from the main renderer. pgPrimary = (PGraphicsOpenGL)parent.g; pgl.initOffscreenSurface(pgPrimary.pgl); pgl.updateOffscreen(pgPrimary.pgl); loadTextureImpl(Texture.BILINEAR, false); // In case of reinitialization (for example, when the smooth level // is changed), we make sure that all the OpenGL resources associated // to the surface are released by calling delete(). if (offscreenFramebuffer != null) { offscreenFramebuffer.release(); } if (offscreenFramebufferMultisample != null) { offscreenFramebufferMultisample.release(); } if (PGraphicsOpenGL.fboMultisampleSupported && 1 < quality) { offscreenFramebufferMultisample = new FrameBuffer(parent, texture.glWidth, texture.glHeight, quality, 0, depthBits, stencilBits, depthBits == 24 && stencilBits == 8 && packedDepthStencilSupported, false); offscreenFramebufferMultisample.clear(); offscreenMultisample = true; // The offscreen framebuffer where the multisampled image is finally drawn to doesn't // need depth and stencil buffers since they are part of the multisampled framebuffer. offscreenFramebuffer = new FrameBuffer(parent, texture.glWidth, texture.glHeight, 1, 1, 0, 0, false, false); } else { quality = 0; offscreenFramebuffer = new FrameBuffer(parent, texture.glWidth, texture.glHeight, 1, 1, depthBits, stencilBits, depthBits == 24 && stencilBits == 8 && packedDepthStencilSupported, false); offscreenMultisample = false; } offscreenFramebuffer.setColorBuffer(texture); offscreenFramebuffer.clear(); } protected void getGLParameters() { OPENGL_VENDOR = pgl.glGetString(PGL.GL_VENDOR); OPENGL_RENDERER = pgl.glGetString(PGL.GL_RENDERER); OPENGL_VERSION = pgl.glGetString(PGL.GL_VERSION); OPENGL_EXTENSIONS = pgl.glGetString(PGL.GL_EXTENSIONS); GLSL_VERSION = pgl.glGetString(PGL.GL_SHADING_LANGUAGE_VERSION); npotTexSupported = -1 < OPENGL_EXTENSIONS.indexOf("texture_non_power_of_two"); autoMipmapGenSupported = -1 < OPENGL_EXTENSIONS.indexOf("generate_mipmap"); fboMultisampleSupported = -1 < OPENGL_EXTENSIONS.indexOf("framebuffer_multisample"); packedDepthStencilSupported = -1 < OPENGL_EXTENSIONS.indexOf("packed_depth_stencil"); try { pgl.glBlendEquation(PGL.GL_FUNC_ADD); blendEqSupported = true; } catch (UnsupportedOperationException e) { blendEqSupported = false; } int temp[] = new int[2]; pgl.glGetIntegerv(PGL.GL_MAX_TEXTURE_SIZE, temp, 0); maxTextureSize = temp[0]; pgl.glGetIntegerv(PGL.GL_MAX_SAMPLES, temp, 0); maxSamples = temp[0]; pgl.glGetIntegerv(PGL.GL_ALIASED_LINE_WIDTH_RANGE, temp, 0); maxLineWidth = temp[1]; pgl.glGetIntegerv(PGL.GL_ALIASED_POINT_SIZE_RANGE, temp, 0); maxPointSize = temp[1]; pgl.glGetIntegerv(PGL.GL_DEPTH_BITS, temp, 0); depthBits = temp[0]; pgl.glGetIntegerv(PGL.GL_STENCIL_BITS, temp, 0); stencilBits = temp[0]; glParamsRead = true; } ////////////////////////////////////////////////////////////// // SHADER HANDLING public PShader loadShader(String vertFilename, String fragFilename, int kind) { if (kind == PShader.FLAT) { return new PolyFlatShader(parent, vertFilename, fragFilename); } else if (kind == PShader.LIT) { return new PolyLightShader(parent, vertFilename, fragFilename); } else if (kind == PShader.TEXTURED) { return new PolyTexShader(parent, vertFilename, fragFilename); } else if (kind == PShader.FULL) { return new PolyFullShader(parent, vertFilename, fragFilename); } else if (kind == PShader.LINE) { return new LineShader(parent, vertFilename, fragFilename); } else if (kind == PShader.POINT) { return new PointShader(parent, vertFilename, fragFilename); } else { PGraphics.showWarning("Wrong shader type"); return null; } } public PShader loadShader(String fragFilename, int kind) { PShader shader; if (kind == PShader.FLAT) { shader = new PolyFlatShader(parent); shader.setVertexShader(defPolyFlatShaderVertURL); } else if (kind == PShader.LIT) { shader = new PolyLightShader(parent); shader.setVertexShader(defPolyLightShaderVertURL); } else if (kind == PShader.TEXTURED) { shader = new PolyTexShader(parent); shader.setVertexShader(defPolyTexShaderVertURL); } else if (kind == PShader.FULL) { shader = new PolyFullShader(parent); shader.setVertexShader(defPolyFullShaderVertURL); } else if (kind == PShader.LINE) { shader = new LineShader(parent); shader.setVertexShader(defLineShaderVertURL); } else if (kind == PShader.POINT) { shader = new PointShader(parent); shader.setVertexShader(defPointShaderVertURL); } else { PGraphics.showWarning("Wrong shader type"); return null; } shader.setFragmentShader(fragFilename); return shader; } public void setShader(PShader shader, int kind) { flush(); // Flushing geometry with a different shader. if (kind == PShader.FLAT) { polyFlatShader = (PolyFlatShader) shader; } else if (kind == PShader.LIT) { polyLightShader = (PolyLightShader) shader; } else if (kind == PShader.TEXTURED) { polyTexShader = (PolyTexShader) shader; } else if (kind == PShader.FULL) { polyFullShader = (PolyFullShader) shader; } else if (kind == PShader.LINE) { lineShader = (LineShader) shader; } else if (kind == PShader.POINT) { pointShader = (PointShader) shader; } else { PGraphics.showWarning("Wrong shader type"); } } public void defaultShader(int kind) { flush(); // Flushing geometry with a different shader. if (kind == PShader.FLAT) { if (defPolyFlatShader == null || defPolyFlatShader.contextIsOutdated()) { defPolyFlatShader = new PolyFlatShader(parent, defPolyFlatShaderVertURL, defPolyNoTexShaderFragURL); } polyFlatShader = defPolyFlatShader; } else if (kind == PShader.LIT) { if (defPolyLightShader == null || defPolyLightShader.contextIsOutdated()) { defPolyLightShader = new PolyLightShader(parent, defPolyLightShaderVertURL, defPolyNoTexShaderFragURL); } polyLightShader = defPolyLightShader; } else if (kind == PShader.TEXTURED) { if (defPolyTexShader == null || defPolyTexShader.contextIsOutdated()) { defPolyTexShader = new PolyTexShader(parent, defPolyTexShaderVertURL, defPolyTexShaderFragURL); } polyTexShader = defPolyTexShader; } else if (kind == PShader.FULL) { if (defPolyFullShader == null || defPolyFullShader.contextIsOutdated()) { defPolyFullShader = new PolyFullShader(parent, defPolyFullShaderVertURL, defPolyTexShaderFragURL); } polyFullShader = defPolyFullShader; } else if (kind == PShader.LINE) { if (defLineShader == null || defLineShader.contextIsOutdated()) { defLineShader = new LineShader(parent, defLineShaderVertURL, defLineShaderFragURL); } lineShader = defLineShader; } else if (kind == PShader.POINT) { if (defPointShader == null || defPointShader.contextIsOutdated()) { defPointShader = new PointShader(parent, defPointShaderVertURL, defPointShaderFragURL); } pointShader = defPointShader; } else { PGraphics.showWarning("Wrong shader type"); } } protected PolyShader getPolyShader(boolean lit, boolean tex) { PolyShader shader; if (lit) { if (tex) { if (defPolyFullShader == null || defPolyFullShader.contextIsOutdated()) { defPolyFullShader = new PolyFullShader(parent, defPolyFullShaderVertURL, defPolyTexShaderFragURL); } if (polyFullShader == null || polyFullShader.contextIsOutdated()) { polyFullShader = defPolyFullShader; } shader = polyFullShader; } else { if (defPolyLightShader == null || defPolyLightShader.contextIsOutdated()) { defPolyLightShader = new PolyLightShader(parent, defPolyLightShaderVertURL, defPolyNoTexShaderFragURL); } if (polyLightShader == null || polyLightShader.contextIsOutdated()) { polyLightShader = defPolyLightShader; } shader = polyLightShader; } } else { if (tex) { if (defPolyTexShader == null || defPolyTexShader.contextIsOutdated()) { defPolyTexShader = new PolyTexShader(parent, defPolyTexShaderVertURL, defPolyTexShaderFragURL); } if (polyTexShader == null || polyTexShader.contextIsOutdated()) { polyTexShader = defPolyTexShader; } shader = polyTexShader; } else { if (defPolyFlatShader == null || defPolyFlatShader.contextIsOutdated()) { defPolyFlatShader = new PolyFlatShader(parent, defPolyFlatShaderVertURL, defPolyNoTexShaderFragURL); } if (polyFlatShader == null || polyFlatShader.contextIsOutdated()) { polyFlatShader = defPolyFlatShader; } shader = polyFlatShader; } } shader.setRenderer(this); shader.loadAttributes(); shader.loadUniforms(); return shader; } protected LineShader getLineShader() { if (defLineShader == null || defLineShader.contextIsOutdated()) { defLineShader = new LineShader(parent, defLineShaderVertURL, defLineShaderFragURL); } if (lineShader == null || lineShader.contextIsOutdated()) { lineShader = defLineShader; } lineShader.setRenderer(this); lineShader.loadAttributes(); lineShader.loadUniforms(); return lineShader; } protected PointShader getPointShader() { if (defPointShader == null || defPointShader.contextIsOutdated()) { defPointShader = new PointShader(parent, defPointShaderVertURL, defPointShaderFragURL); } if (pointShader == null || pointShader.contextIsOutdated()) { pointShader = defPointShader; } pointShader.setRenderer(this); pointShader.loadAttributes(); pointShader.loadUniforms(); return pointShader; } protected class PolyShader extends PShader { // We need a reference to the renderer since a shader might // be called by different renderers within a single application // (the one corresponding to the main surface, or other offscreen // renderers). protected PGraphicsOpenGL renderer; public PolyShader(PApplet parent) { super(parent); } public PolyShader(PApplet parent, String vertFilename, String fragFilename) { super(parent, vertFilename, fragFilename); } public PolyShader(PApplet parent, URL vertURL, URL fragURL) { super(parent, vertURL, fragURL); } public void setRenderer(PGraphicsOpenGL pg) { this.renderer = pg; } public void loadAttributes() { } public void loadUniforms() { } public void setAttribute(int loc, int vboId, int size, int type, boolean normalized, int stride, int offset) { if (-1 < loc) { pgl.glBindBuffer(PGL.GL_ARRAY_BUFFER, vboId); pgl.glVertexAttribPointer(loc, size, type, normalized, stride, offset); } } public void setVertexAttribute(int vboId, int size, int type, int stride, int offset) { } public void setColorAttribute(int vboId, int size, int type, int stride, int offset) { } public void setNormalAttribute(int vboId, int size, int type, int stride, int offset) { } public void setAmbientAttribute(int vboId, int size, int type, int stride, int offset) { } public void setSpecularAttribute(int vboId, int size, int type, int stride, int offset) { } public void setEmissiveAttribute(int vboId, int size, int type, int stride, int offset) { } public void setShininessAttribute(int vboId, int size, int type, int stride, int offset) { } public void setTexcoordAttribute(int vboId, int size, int type, int stride, int offset) { } public void setTexture(Texture tex) { } } protected class PolyFlatShader extends PolyShader { protected int projmodelviewMatrixLoc; protected int inVertexLoc; protected int inColorLoc; public PolyFlatShader(PApplet parent) { super(parent); } public PolyFlatShader(PApplet parent, String vertFilename, String fragFilename) { super(parent, vertFilename, fragFilename); } public PolyFlatShader(PApplet parent, URL vertURL, URL fragURL) { super(parent, vertURL, fragURL); } public void loadAttributes() { inVertexLoc = getAttribLocation("inVertex"); inColorLoc = getAttribLocation("inColor"); } public void loadUniforms() { projmodelviewMatrixLoc = getUniformLocation("projmodelviewMatrix"); } public void setVertexAttribute(int vboId, int size, int type, int stride, int offset) { setAttribute(inVertexLoc, vboId, size, type, false, stride, offset); } public void setColorAttribute(int vboId, int size, int type, int stride, int offset) { setAttribute(inColorLoc, vboId, size, type, true, stride, offset); } public void start() { super.start(); if (-1 < inVertexLoc) pgl.glEnableVertexAttribArray(inVertexLoc); if (-1 < inColorLoc) pgl.glEnableVertexAttribArray(inColorLoc); if (renderer != null) { renderer.updateGLProjmodelview(); set4x4MatUniform(projmodelviewMatrixLoc, renderer.glProjmodelview); } } public void stop() { if (-1 < inVertexLoc) pgl.glDisableVertexAttribArray(inVertexLoc); if (-1 < inColorLoc) pgl.glDisableVertexAttribArray(inColorLoc); pgl.glBindBuffer(PGL.GL_ARRAY_BUFFER, 0); super.stop(); } } protected class PolyLightShader extends PolyShader { protected int projmodelviewMatrixLoc; protected int modelviewMatrixLoc; protected int normalMatrixLoc; protected int lightCountLoc; protected int lightPositionLoc; protected int lightNormalLoc; protected int lightAmbientLoc; protected int lightDiffuseLoc; protected int lightSpecularLoc; protected int lightFalloffCoefficientsLoc; protected int lightSpotParametersLoc; protected int inVertexLoc; protected int inColorLoc; protected int inNormalLoc; protected int inAmbientLoc; protected int inSpecularLoc; protected int inEmissiveLoc; protected int inShineLoc; public PolyLightShader(PApplet parent) { super(parent); } public PolyLightShader(PApplet parent, String vertFilename, String fragFilename) { super(parent, vertFilename, fragFilename); } public PolyLightShader(PApplet parent, URL vertURL, URL fragURL) { super(parent, vertURL, fragURL); } public void loadAttributes() { inVertexLoc = getAttribLocation("inVertex"); inColorLoc = getAttribLocation("inColor"); inNormalLoc = getAttribLocation("inNormal"); inAmbientLoc = getAttribLocation("inAmbient"); inSpecularLoc = getAttribLocation("inSpecular"); inEmissiveLoc = getAttribLocation("inEmissive"); inShineLoc = getAttribLocation("inShine"); } public void loadUniforms() { projmodelviewMatrixLoc = getUniformLocation("projmodelviewMatrix"); modelviewMatrixLoc = getUniformLocation("modelviewMatrix"); normalMatrixLoc = getUniformLocation("normalMatrix"); lightCountLoc = getUniformLocation("lightCount"); lightPositionLoc = getUniformLocation("lightPosition"); lightNormalLoc = getUniformLocation("lightNormal"); lightAmbientLoc = getUniformLocation("lightAmbient"); lightDiffuseLoc = getUniformLocation("lightDiffuse"); lightSpecularLoc = getUniformLocation("lightSpecular"); lightFalloffCoefficientsLoc = getUniformLocation("lightFalloffCoefficients"); lightSpotParametersLoc = getUniformLocation("lightSpotParameters"); } public void setVertexAttribute(int vboId, int size, int type, int stride, int offset) { setAttribute(inVertexLoc, vboId, size, type, false, stride, offset); } public void setColorAttribute(int vboId, int size, int type, int stride, int offset) { setAttribute(inColorLoc, vboId, size, type, true, stride, offset); } public void setNormalAttribute(int vboId, int size, int type, int stride, int offset) { setAttribute(inNormalLoc, vboId, size, type, false, stride, offset); } public void setAmbientAttribute(int vboId, int size, int type, int stride, int offset) { setAttribute(inAmbientLoc, vboId, size, type, true, stride, offset); } public void setSpecularAttribute(int vboId, int size, int type, int stride, int offset) { setAttribute(inSpecularLoc, vboId, size, type, true, stride, offset); } public void setEmissiveAttribute(int vboId, int size, int type, int stride, int offset) { setAttribute(inEmissiveLoc, vboId, size, type, true, stride, offset); } public void setShininessAttribute(int vboId, int size, int type, int stride, int offset) { setAttribute(inShineLoc, vboId, size, type, false, stride, offset); } public void start() { super.start(); if (-1 < inVertexLoc) pgl.glEnableVertexAttribArray(inVertexLoc); if (-1 < inColorLoc) pgl.glEnableVertexAttribArray(inColorLoc); if (-1 < inNormalLoc) pgl.glEnableVertexAttribArray(inNormalLoc); if (-1 < inAmbientLoc) pgl.glEnableVertexAttribArray(inAmbientLoc); if (-1 < inSpecularLoc) pgl.glEnableVertexAttribArray(inSpecularLoc); if (-1 < inEmissiveLoc) pgl.glEnableVertexAttribArray(inEmissiveLoc); if (-1 < inShineLoc) pgl.glEnableVertexAttribArray(inShineLoc); if (renderer != null) { renderer.updateGLProjmodelview(); set4x4MatUniform(projmodelviewMatrixLoc, renderer.glProjmodelview); renderer.updateGLModelview(); set4x4MatUniform(modelviewMatrixLoc, renderer.glModelview); renderer.updateGLNormal(); set3x3MatUniform(normalMatrixLoc, renderer.glNormal); setIntUniform(lightCountLoc, renderer.lightCount); set4FloatVecUniform(lightPositionLoc, renderer.lightPosition); set3FloatVecUniform(lightNormalLoc, renderer.lightNormal); set3FloatVecUniform(lightAmbientLoc, renderer.lightAmbient); set3FloatVecUniform(lightDiffuseLoc, renderer.lightDiffuse); set3FloatVecUniform(lightSpecularLoc, renderer.lightSpecular); set3FloatVecUniform(lightFalloffCoefficientsLoc, renderer.lightFalloffCoefficients); set2FloatVecUniform(lightSpotParametersLoc, renderer.lightSpotParameters); } } public void stop() { if (-1 < inVertexLoc) pgl.glDisableVertexAttribArray(inVertexLoc); if (-1 < inColorLoc) pgl.glDisableVertexAttribArray(inColorLoc); if (-1 < inNormalLoc) pgl.glDisableVertexAttribArray(inNormalLoc); if (-1 < inAmbientLoc) pgl.glDisableVertexAttribArray(inAmbientLoc); if (-1 < inSpecularLoc) pgl.glDisableVertexAttribArray(inSpecularLoc); if (-1 < inEmissiveLoc) pgl.glDisableVertexAttribArray(inEmissiveLoc); if (-1 < inShineLoc) pgl.glDisableVertexAttribArray(inShineLoc); pgl.glBindBuffer(PGL.GL_ARRAY_BUFFER, 0); super.stop(); } } protected class PolyTexShader extends PolyFlatShader { protected int inTexcoordLoc; protected int texcoordMatrixLoc; protected int texcoordOffsetLoc; protected float[] tcmat; public PolyTexShader(PApplet parent) { super(parent); } public PolyTexShader(PApplet parent, String vertFilename, String fragFilename) { super(parent, vertFilename, fragFilename); } public PolyTexShader(PApplet parent, URL vertURL, URL fragURL) { super(parent, vertURL, fragURL); } public void loadUniforms() { super.loadUniforms(); texcoordMatrixLoc = getUniformLocation("texcoordMatrix"); texcoordOffsetLoc = getUniformLocation("texcoordOffset"); } public void loadAttributes() { super.loadAttributes(); inTexcoordLoc = getAttribLocation("inTexcoord"); } public void setTexcoordAttribute(int vboId, int size, int type, int stride, int offset) { setAttribute(inTexcoordLoc, vboId, size, type, false, stride, offset); } public void setTexture(Texture tex) { float scaleu = 1; float scalev = 1; float dispu = 0; float dispv = 0; if (tex.isFlippedX()) { scaleu = -1; dispu = 1; } if (tex.isFlippedY()) { scalev = -1; dispv = 1; } scaleu *= tex.maxTexcoordU; dispu *= tex.maxTexcoordU; scalev *= tex.maxTexcoordV; dispv *= tex.maxTexcoordV; if (tcmat == null) { tcmat = new float[16]; } tcmat[0] = scaleu; tcmat[4] = 0; tcmat[ 8] = 0; tcmat[12] = dispu; tcmat[1] = 0; tcmat[5] = scalev; tcmat[ 9] = 0; tcmat[13] = dispv; tcmat[2] = 0; tcmat[6] = 0; tcmat[10] = 0; tcmat[14] = 0; tcmat[3] = 0; tcmat[7] = 0; tcmat[11] = 0; tcmat[15] = 0; set4x4MatUniform(texcoordMatrixLoc, tcmat); set2FloatUniform(texcoordOffsetLoc, 1.0f / tex.width, 1.0f / tex.height); } public void start() { super.start(); if (-1 < inTexcoordLoc) pgl.glEnableVertexAttribArray(inTexcoordLoc); } public void stop() { if (-1 < inTexcoordLoc) pgl.glDisableVertexAttribArray(inTexcoordLoc); super.stop(); } } protected class PolyFullShader extends PolyLightShader { protected int inTexcoordLoc; protected int texcoordMatrixLoc; protected int texcoordOffsetLoc; protected float[] tcmat; public PolyFullShader(PApplet parent) { super(parent); } public PolyFullShader(PApplet parent, String vertFilename, String fragFilename) { super(parent, vertFilename, fragFilename); } public PolyFullShader(PApplet parent, URL vertURL, URL fragURL) { super(parent, vertURL, fragURL); } public void loadUniforms() { super.loadUniforms(); texcoordMatrixLoc = getUniformLocation("texcoordMatrix"); texcoordOffsetLoc = getUniformLocation("texcoordOffset"); } public void loadAttributes() { super.loadAttributes(); inTexcoordLoc = getAttribLocation("inTexcoord"); } public void setTexcoordAttribute(int vboId, int size, int type, int stride, int offset) { setAttribute(inTexcoordLoc, vboId, size, type, false, stride, offset); } public void setTexture(Texture tex) { float scaleu = 1; float scalev = 1; float dispu = 0; float dispv = 0; if (tex.isFlippedX()) { scaleu = -1; dispu = 1; } if (tex.isFlippedY()) { scalev = -1; dispv = 1; } scaleu *= tex.maxTexcoordU; dispu *= tex.maxTexcoordU; scalev *= tex.maxTexcoordV; dispv *= tex.maxTexcoordV; if (tcmat == null) { tcmat = new float[16]; } tcmat[0] = scaleu; tcmat[4] = 0; tcmat[ 8] = 0; tcmat[12] = dispu; tcmat[1] = 0; tcmat[5] = scalev; tcmat[ 9] = 0; tcmat[13] = dispv; tcmat[2] = 0; tcmat[6] = 0; tcmat[10] = 0; tcmat[14] = 0; tcmat[3] = 0; tcmat[7] = 0; tcmat[11] = 0; tcmat[15] = 0; set4x4MatUniform(texcoordMatrixLoc, tcmat); set2FloatUniform(texcoordOffsetLoc, 1.0f / tex.width, 1.0f / tex.height); } public void start() { super.start(); if (-1 < inTexcoordLoc) pgl.glEnableVertexAttribArray(inTexcoordLoc); } public void stop() { if (-1 < inTexcoordLoc) pgl.glDisableVertexAttribArray(inTexcoordLoc); super.stop(); } } protected class LineShader extends PShader { protected PGraphicsOpenGL renderer; protected int projectionMatrixLoc; protected int modelviewMatrixLoc; protected int viewportLoc; protected int perspectiveLoc; protected int inVertexLoc; protected int inColorLoc; protected int inAttribLoc; public LineShader(PApplet parent) { super(parent); } public LineShader(PApplet parent, String vertFilename, String fragFilename) { super(parent, vertFilename, fragFilename); } public LineShader(PApplet parent, URL vertURL, URL fragURL) { super(parent, vertURL, fragURL); } public void setRenderer(PGraphicsOpenGL pg) { this.renderer = pg; } public void loadAttributes() { inVertexLoc = getAttribLocation("inVertex"); inColorLoc = getAttribLocation("inColor"); inAttribLoc = getAttribLocation("inLine"); } public void loadUniforms() { projectionMatrixLoc = getUniformLocation("projectionMatrix"); modelviewMatrixLoc = getUniformLocation("modelviewMatrix"); viewportLoc = getUniformLocation("viewport"); perspectiveLoc = getUniformLocation("perspective"); } public void setAttribute(int loc, int vboId, int size, int type, boolean normalized, int stride, int offset) { pgl.glBindBuffer(PGL.GL_ARRAY_BUFFER, vboId); pgl.glVertexAttribPointer(loc, size, type, normalized, stride, offset); } public void setVertexAttribute(int vboId, int size, int type, int stride, int offset) { setAttribute(inVertexLoc, vboId, size, type, false, stride, offset); } public void setColorAttribute(int vboId, int size, int type, int stride, int offset) { setAttribute(inColorLoc, vboId, size, type, true, stride, offset); } public void setLineAttribute(int vboId, int size, int type, int stride, int offset) { setAttribute(inAttribLoc, vboId, size, type, false, stride, offset); } public void start() { super.start(); if (-1 < inVertexLoc) pgl.glEnableVertexAttribArray(inVertexLoc); if (-1 < inColorLoc) pgl.glEnableVertexAttribArray(inColorLoc); if (-1 < inAttribLoc) pgl.glEnableVertexAttribArray(inAttribLoc); if (renderer != null) { renderer.updateGLProjection(); set4x4MatUniform(projectionMatrixLoc, renderer.glProjection); renderer.updateGLModelview(); set4x4MatUniform(modelviewMatrixLoc, renderer.glModelview); set4FloatUniform(viewportLoc, renderer.viewport[0], renderer.viewport[1], renderer.viewport[2], renderer.viewport[3]); } setIntUniform(perspectiveLoc, perspectiveCorrectedLines ? 1 : 0); } public void stop() { if (-1 < inVertexLoc) pgl.glDisableVertexAttribArray(inVertexLoc); if (-1 < inColorLoc) pgl.glDisableVertexAttribArray(inColorLoc); if (-1 < inAttribLoc) pgl.glDisableVertexAttribArray(inAttribLoc); pgl.glBindBuffer(PGL.GL_ARRAY_BUFFER, 0); super.stop(); } } protected class PointShader extends PShader { protected PGraphicsOpenGL renderer; protected int projectionMatrixLoc; protected int modelviewMatrixLoc; protected int inVertexLoc; protected int inColorLoc; protected int inPointLoc; public PointShader(PApplet parent) { super(parent); } public PointShader(PApplet parent, String vertFilename, String fragFilename) { super(parent, vertFilename, fragFilename); } public PointShader(PApplet parent, URL vertURL, URL fragURL) { super(parent, vertURL, fragURL); } public void setRenderer(PGraphicsOpenGL pg) { this.renderer = pg; } public void loadAttributes() { inVertexLoc = getAttribLocation("inVertex"); inColorLoc = getAttribLocation("inColor"); inPointLoc = getAttribLocation("inPoint"); } public void loadUniforms() { projectionMatrixLoc = getUniformLocation("projectionMatrix"); modelviewMatrixLoc = getUniformLocation("modelviewMatrix"); } public void setAttribute(int loc, int vboId, int size, int type, boolean normalized, int stride, int offset) { pgl.glBindBuffer(PGL.GL_ARRAY_BUFFER, vboId); pgl.glVertexAttribPointer(loc, size, type, normalized, stride, offset); } public void setVertexAttribute(int vboId, int size, int type, int stride, int offset) { setAttribute(inVertexLoc, vboId, size, type, false, stride, offset); } public void setColorAttribute(int vboId, int size, int type, int stride, int offset) { setAttribute(inColorLoc, vboId, size, type, true, stride, offset); } public void setPointAttribute(int vboId, int size, int type, int stride, int offset) { setAttribute(inPointLoc, vboId, size, type, false, stride, offset); } public void start() { super.start(); if (-1 < inVertexLoc) pgl.glEnableVertexAttribArray(inVertexLoc); if (-1 < inColorLoc) pgl.glEnableVertexAttribArray(inColorLoc); if (-1 < inPointLoc) pgl.glEnableVertexAttribArray(inPointLoc); if (renderer != null) { renderer.updateGLProjection(); set4x4MatUniform(projectionMatrixLoc, renderer.glProjection); renderer.updateGLModelview(); set4x4MatUniform(modelviewMatrixLoc, renderer.glModelview); } } public void stop() { if (-1 < inVertexLoc) pgl.glDisableVertexAttribArray(inVertexLoc); if (-1 < inColorLoc) pgl.glDisableVertexAttribArray(inColorLoc); if (-1 < inPointLoc) pgl.glDisableVertexAttribArray(inPointLoc); pgl.glBindBuffer(PGL.GL_ARRAY_BUFFER, 0); super.stop(); } } ////////////////////////////////////////////////////////////// // Utils static protected int expandArraySize(int currSize, int newMinSize) { int newSize = currSize; while (newSize < newMinSize) { newSize <<= 1; } return newSize; } ////////////////////////////////////////////////////////////// // Input (raw) and Tessellated geometry, tessellator. protected InGeometry newInGeometry(int mode) { return new InGeometry(mode); } protected TessGeometry newTessGeometry(int mode) { return new TessGeometry(mode); } protected TexCache newTexCache() { return new TexCache(); } // Holds an array of textures and the range of vertex // indices each texture applies to. protected class TexCache { int size; PImage[] textures; int[] firstIndex; int[] lastIndex; int[] firstCache; int[] lastCache; boolean hasTexture; Texture tex0; TexCache() { allocate(); } void allocate() { textures = new PImage[PGL.DEFAULT_IN_TEXTURES]; firstIndex = new int[PGL.DEFAULT_IN_TEXTURES]; lastIndex = new int[PGL.DEFAULT_IN_TEXTURES]; firstCache = new int[PGL.DEFAULT_IN_TEXTURES]; lastCache = new int[PGL.DEFAULT_IN_TEXTURES]; size = 0; hasTexture = false; } void clear() { java.util.Arrays.fill(textures, 0, size, null); size = 0; hasTexture = false; } void dispose() { textures = null; firstIndex = null; lastIndex = null; firstCache = null; lastCache = null; } void beginRender() { tex0 = null; } PImage getTextureImage(int i) { return textures[i]; } Texture getTexture(int i) { PImage img = textures[i]; Texture tex = null; if (img != null) { tex = pgPrimary.getTexture(img); if (tex != null) { tex.bind(); tex0 = tex; } } if (tex == null && tex0 != null) { tex0.unbind(); pgl.disableTexturing(tex0.glTarget); } return tex; } void endRender() { if (hasTexture) { // Unbinding all the textures in the cache. for (int i = 0; i < size; i++) { PImage img = textures[i]; if (img != null) { Texture tex = pgPrimary.getTexture(img); if (tex != null) { tex.unbind(); } } } // Disabling texturing for each of the targets used // by textures in the cache. for (int i = 0; i < size; i++) { PImage img = textures[i]; if (img != null) { Texture tex = pgPrimary.getTexture(img); if (tex != null) { pgl.disableTexturing(tex.glTarget); } } } } } void addTexture(PImage img, int firsti, int firstb, int lasti, int lastb) { arrayCheck(); textures[size] = img; firstIndex[size] = firsti; lastIndex[size] = lasti; firstCache[size] = firstb; lastCache[size] = lastb; // At least one non-null texture since last reset. hasTexture |= img != null; size++; } void setLastIndex(int lasti, int lastb) { lastIndex[size - 1] = lasti; lastCache[size - 1] = lastb; } void arrayCheck() { if (size == textures.length) { int newSize = size << 1; expandTextures(newSize); expandFirstIndex(newSize); expandLastIndex(newSize); expandFirstCache(newSize); expandLastCache(newSize); } } void expandTextures(int n) { PImage[] temp = new PImage[n]; PApplet.arrayCopy(textures, 0, temp, 0, size); textures = temp; } void expandFirstIndex(int n) { int[] temp = new int[n]; PApplet.arrayCopy(firstIndex, 0, temp, 0, size); firstIndex = temp; } void expandLastIndex(int n) { int[] temp = new int[n]; PApplet.arrayCopy(lastIndex, 0, temp, 0, size); lastIndex = temp; } void expandFirstCache(int n) { int[] temp = new int[n]; PApplet.arrayCopy(firstCache, 0, temp, 0, size); firstCache = temp; } void expandLastCache(int n) { int[] temp = new int[n]; PApplet.arrayCopy(lastCache, 0, temp, 0, size); lastCache = temp; } } // Stores the offsets and counts of indices and vertices // to render a piece of geometry that doesn't fit in a single // glDrawElements() call. protected class IndexCache { int size; int[] indexCount; int[] indexOffset; int[] vertexCount; int[] vertexOffset; IndexCache() { allocate(); } void allocate() { indexCount = new int[2]; indexOffset = new int[2]; vertexCount = new int[2]; vertexOffset = new int[2]; size = 0; } void clear() { size = 0; } int addNew() { arrayCheck(); init(size); size++; return size - 1; } int addNew(int index) { arrayCheck(); indexCount[size] = indexCount[index]; indexOffset[size] = indexOffset[index]; vertexCount[size] = vertexCount[index]; vertexOffset[size] = vertexOffset[index]; size++; return size - 1; } int getLast() { if (size == 0) { arrayCheck(); init(0); size = 1; } return size - 1; } void incCounts(int index, int icount, int vcount) { indexCount[index] += icount; vertexCount[index] += vcount; } void init(int n) { if (0 < n) { indexOffset[n] = indexOffset[n - 1] + indexCount[n - 1]; vertexOffset[n] = vertexOffset[n - 1] + vertexCount[n - 1]; } else { indexOffset[n] = 0; vertexOffset[n] = 0; } indexCount[n] = 0; vertexCount[n] = 0; } void arrayCheck() { if (size == indexCount.length) { int newSize = size << 1; expandIndexCount(newSize); expandIndexOffset(newSize); expandVertexCount(newSize); expandVertexOffset(newSize); } } void expandIndexCount(int n) { int[] temp = new int[n]; PApplet.arrayCopy(indexCount, 0, temp, 0, size); indexCount = temp; } void expandIndexOffset(int n) { int[] temp = new int[n]; PApplet.arrayCopy(indexOffset, 0, temp, 0, size); indexOffset = temp; } void expandVertexCount(int n) { int[] temp = new int[n]; PApplet.arrayCopy(vertexCount, 0, temp, 0, size); vertexCount = temp; } void expandVertexOffset(int n) { int[] temp = new int[n]; PApplet.arrayCopy(vertexOffset, 0, temp, 0, size); vertexOffset = temp; } } // Holds the input vertices: xyz coordinates, fill/tint color, // normal, texture coordinates and stroke color and weight. protected class InGeometry { int renderMode; int vertexCount; int edgeCount; // Range of vertices that will be processed by the // tessellator. They can be used in combination with the // edges array to have the tessellator using only a specific // range of vertices to generate fill geometry, while the // line geometry will be read from the edge vertices, which // could be completely different. int firstVertex; int lastVertex; int firstEdge; int lastEdge; float[] vertices; int[] colors; float[] normals; float[] texcoords; int[] strokeColors; float[] strokeWeights; // lines boolean[] breaks; int[][] edges; // Material properties int[] ambient; int[] specular; int[] emissive; float[] shininess; // Internally used by the addVertex() methods. int fillColor; int strokeColor; float strokeWeight; int ambientColor; int specularColor; int emissiveColor; float shininessFactor; float normalX, normalY, normalZ; InGeometry(int mode) { renderMode = mode; allocate(); } // ----------------------------------------------------------------- // // Allocate/dispose void clear() { vertexCount = firstVertex = lastVertex = 0; edgeCount = firstEdge = lastEdge = 0; } void clearEdges() { edgeCount = firstEdge = lastEdge = 0; } void allocate() { vertices = new float[3 * PGL.DEFAULT_IN_VERTICES]; colors = new int[PGL.DEFAULT_IN_VERTICES]; normals = new float[3 * PGL.DEFAULT_IN_VERTICES]; texcoords = new float[2 * PGL.DEFAULT_IN_VERTICES]; strokeColors = new int[PGL.DEFAULT_IN_VERTICES]; strokeWeights = new float[PGL.DEFAULT_IN_VERTICES]; ambient = new int[PGL.DEFAULT_IN_VERTICES]; specular = new int[PGL.DEFAULT_IN_VERTICES]; emissive = new int[PGL.DEFAULT_IN_VERTICES]; shininess = new float[PGL.DEFAULT_IN_VERTICES]; breaks = new boolean[PGL.DEFAULT_IN_VERTICES]; edges = new int[PGL.DEFAULT_IN_EDGES][3]; clear(); } void dispose() { breaks = null; vertices = null; colors = null; normals = null; texcoords = null; strokeColors = null; strokeWeights = null; ambient = null; specular = null; emissive = null; shininess = null; edges = null; } void vertexCheck() { if (vertexCount == vertices.length / 3) { int newSize = vertexCount << 1; expandVertices(newSize); expandColors(newSize); expandNormals(newSize); expandTexcoords(newSize); expandStrokeColors(newSize); expandStrokeWeights(newSize); expandAmbient(newSize); expandSpecular(newSize); expandEmissive(newSize); expandShininess(newSize); expandBreaks(newSize); } } void edgeCheck() { if (edgeCount == edges.length) { int newLen = edgeCount << 1; expandEdges(newLen); } } // ----------------------------------------------------------------- // // Query float getVertexX(int idx) { return vertices[3 * idx + 0]; } float getVertexY(int idx) { return vertices[3 * idx + 1]; } float getVertexZ(int idx) { return vertices[3 * idx + 2]; } float getLastVertexX() { return vertices[3 * (vertexCount - 1) + 0]; } float getLastVertexY() { return vertices[3 * (vertexCount - 1) + 1]; } float getLastVertexZ() { return vertices[3 * (vertexCount - 1) + 2]; } int getNumEdgeVertices(boolean bevel) { int segVert = 4 * (lastEdge - firstEdge + 1); int bevVert = 0; if (bevel) { for (int i = firstEdge; i <= lastEdge; i++) { int[] edge = edges[i]; if (edge[2] == EDGE_MIDDLE || edge[2] == EDGE_START) { bevVert++; } } } return segVert + bevVert; } int getNumEdgeIndices(boolean bevel) { int segInd = 6 * (lastEdge - firstEdge + 1); int bevInd = 0; if (bevel) { for (int i = firstEdge; i <= lastEdge; i++) { int[] edge = edges[i]; if (edge[2] == EDGE_MIDDLE || edge[2] == EDGE_START) { bevInd += 6; } } } return segInd + bevInd; } void getVertexMin(PVector v) { int index; for (int i = 0; i < vertexCount; i++) { index = 4 * i; v.x = PApplet.min(v.x, vertices[index++]); v.y = PApplet.min(v.y, vertices[index++]); v.z = PApplet.min(v.z, vertices[index ]); } } void getVertexMax(PVector v) { int index; for (int i = 0; i < vertexCount; i++) { index = 4 * i; v.x = PApplet.max(v.x, vertices[index++]); v.y = PApplet.max(v.y, vertices[index++]); v.z = PApplet.max(v.z, vertices[index ]); } } int getVertexSum(PVector v) { int index; for (int i = 0; i < vertexCount; i++) { index = 4 * i; v.x += vertices[index++]; v.y += vertices[index++]; v.z += vertices[index ]; } return vertexCount; } // ----------------------------------------------------------------- // // Expand arrays void expandVertices(int n) { float temp[] = new float[3 * n]; PApplet.arrayCopy(vertices, 0, temp, 0, 3 * vertexCount); vertices = temp; } void expandColors(int n) { int temp[] = new int[n]; PApplet.arrayCopy(colors, 0, temp, 0, vertexCount); colors = temp; } void expandNormals(int n) { float temp[] = new float[3 * n]; PApplet.arrayCopy(normals, 0, temp, 0, 3 * vertexCount); normals = temp; } void expandTexcoords(int n) { float temp[] = new float[2 * n]; PApplet.arrayCopy(texcoords, 0, temp, 0, 2 * vertexCount); texcoords = temp; } void expandStrokeColors(int n) { int temp[] = new int[n]; PApplet.arrayCopy(strokeColors, 0, temp, 0, vertexCount); strokeColors = temp; } void expandStrokeWeights(int n) { float temp[] = new float[n]; PApplet.arrayCopy(strokeWeights, 0, temp, 0, vertexCount); strokeWeights = temp; } void expandAmbient(int n) { int temp[] = new int[n]; PApplet.arrayCopy(ambient, 0, temp, 0, vertexCount); ambient = temp; } void expandSpecular(int n) { int temp[] = new int[n]; PApplet.arrayCopy(specular, 0, temp, 0, vertexCount); specular = temp; } void expandEmissive(int n) { int temp[] = new int[n]; PApplet.arrayCopy(emissive, 0, temp, 0, vertexCount); emissive = temp; } void expandShininess(int n) { float temp[] = new float[n]; PApplet.arrayCopy(shininess, 0, temp, 0, vertexCount); shininess = temp; } void expandBreaks(int n) { boolean temp[] = new boolean[n]; PApplet.arrayCopy(breaks, 0, temp, 0, vertexCount); breaks = temp; } void expandEdges(int n) { int temp[][] = new int[n][3]; PApplet.arrayCopy(edges, 0, temp, 0, edgeCount); edges = temp; } // ----------------------------------------------------------------- // // Trim arrays void trim() { if (0 < vertexCount && vertexCount < vertices.length / 3) { trimVertices(); trimColors(); trimNormals(); trimTexcoords(); trimStrokeColors(); trimStrokeWeights(); trimAmbient(); trimSpecular(); trimEmissive(); trimShininess(); trimBreaks(); } if (0 < edgeCount && edgeCount < edges.length) { trimEdges(); } } void trimVertices() { float temp[] = new float[3 * vertexCount]; PApplet.arrayCopy(vertices, 0, temp, 0, 3 * vertexCount); vertices = temp; } void trimColors() { int temp[] = new int[vertexCount]; PApplet.arrayCopy(colors, 0, temp, 0, vertexCount); colors = temp; } void trimNormals() { float temp[] = new float[3 * vertexCount]; PApplet.arrayCopy(normals, 0, temp, 0, 3 * vertexCount); normals = temp; } void trimTexcoords() { float temp[] = new float[2 * vertexCount]; PApplet.arrayCopy(texcoords, 0, temp, 0, 2 * vertexCount); texcoords = temp; } void trimStrokeColors() { int temp[] = new int[vertexCount]; PApplet.arrayCopy(strokeColors, 0, temp, 0, vertexCount); strokeColors = temp; } void trimStrokeWeights() { float temp[] = new float[vertexCount]; PApplet.arrayCopy(strokeWeights, 0, temp, 0, vertexCount); strokeWeights = temp; } void trimAmbient() { int temp[] = new int[vertexCount]; PApplet.arrayCopy(ambient, 0, temp, 0, vertexCount); ambient = temp; } void trimSpecular() { int temp[] = new int[vertexCount]; PApplet.arrayCopy(specular, 0, temp, 0, vertexCount); specular = temp; } void trimEmissive() { int temp[] = new int[vertexCount]; PApplet.arrayCopy(emissive, 0, temp, 0, vertexCount); emissive = temp; } void trimShininess() { float temp[] = new float[vertexCount]; PApplet.arrayCopy(shininess, 0, temp, 0, vertexCount); shininess = temp; } void trimBreaks() { boolean temp[] = new boolean[vertexCount]; PApplet.arrayCopy(breaks, 0, temp, 0, vertexCount); breaks = temp; } void trimEdges() { int temp[][] = new int[edgeCount][3]; PApplet.arrayCopy(edges, 0, temp, 0, edgeCount); edges = temp; } // ----------------------------------------------------------------- // // Vertices int addVertex(float x, float y, int code) { return addVertex(x, y, 0, fillColor, normalX, normalY, normalZ, 0, 0, strokeColor, strokeWeight, ambientColor, specularColor, emissiveColor, shininessFactor, code); } int addVertex(float x, float y, float u, float v, int code) { return addVertex(x, y, 0, fillColor, normalX, normalY, normalZ, u, v, strokeColor, strokeWeight, ambientColor, specularColor, emissiveColor, shininessFactor, code); } int addVertex(float x, float y, float z, int code) { return addVertex(x, y, z, fillColor, normalX, normalY, normalZ, 0, 0, strokeColor, strokeWeight, ambientColor, specularColor, emissiveColor, shininessFactor, code); } int addVertex(float x, float y, float z, float u, float v, int code) { return addVertex(x, y, z, fillColor, normalX, normalY, normalZ, u, v, strokeColor, strokeWeight, ambientColor, specularColor, emissiveColor, shininessFactor, code); } int addVertex(float x, float y, float z, int fcolor, float nx, float ny, float nz, float u, float v, int scolor, float sweight, int am, int sp, int em, float shine, int code) { vertexCheck(); int index; curveVertexCount = 0; index = 3 * vertexCount; vertices[index++] = x; vertices[index++] = y; vertices[index ] = z; colors[vertexCount] = PGL.javaToNativeARGB(fcolor); index = 3 * vertexCount; normals[index++] = nx; normals[index++] = ny; normals[index ] = nz; index = 2 * vertexCount; texcoords[index++] = u; texcoords[index ] = v; strokeColors[vertexCount] = PGL.javaToNativeARGB(scolor); strokeWeights[vertexCount] = sweight; ambient[vertexCount] = PGL.javaToNativeARGB(am); specular[vertexCount] = PGL.javaToNativeARGB(sp); emissive[vertexCount] = PGL.javaToNativeARGB(em); shininess[vertexCount] = shine; breaks[vertexCount] = code == BREAK; lastVertex = vertexCount; vertexCount++; return lastVertex; } void addBezierVertex(float x2, float y2, float z2, float x3, float y3, float z3, float x4, float y4, float z4, boolean fill, boolean stroke, int detail, int code) { addBezierVertex(x2, y2, z2, x3, y3, z3, x4, y4, z4, fill, stroke, detail, code, POLYGON); } void addBezierVertex(float x2, float y2, float z2, float x3, float y3, float z3, float x4, float y4, float z4, boolean fill, boolean stroke, int detail, int code, int shape) { bezierInitCheck(); bezierVertexCheck(shape, vertexCount); PMatrix3D draw = bezierDrawMatrix; float x1 = getLastVertexX(); float y1 = getLastVertexY(); float z1 = getLastVertexZ(); float xplot1 = draw.m10*x1 + draw.m11*x2 + draw.m12*x3 + draw.m13*x4; float xplot2 = draw.m20*x1 + draw.m21*x2 + draw.m22*x3 + draw.m23*x4; float xplot3 = draw.m30*x1 + draw.m31*x2 + draw.m32*x3 + draw.m33*x4; float yplot1 = draw.m10*y1 + draw.m11*y2 + draw.m12*y3 + draw.m13*y4; float yplot2 = draw.m20*y1 + draw.m21*y2 + draw.m22*y3 + draw.m23*y4; float yplot3 = draw.m30*y1 + draw.m31*y2 + draw.m32*y3 + draw.m33*y4; float zplot1 = draw.m10*z1 + draw.m11*z2 + draw.m12*z3 + draw.m13*z4; float zplot2 = draw.m20*z1 + draw.m21*z2 + draw.m22*z3 + draw.m23*z4; float zplot3 = draw.m30*z1 + draw.m31*z2 + draw.m32*z3 + draw.m33*z4; for (int j = 0; j < detail; j++) { x1 += xplot1; xplot1 += xplot2; xplot2 += xplot3; y1 += yplot1; yplot1 += yplot2; yplot2 += yplot3; z1 += zplot1; zplot1 += zplot2; zplot2 += zplot3; addVertex(x1, y1, z1, j == 0 && code == BREAK ? BREAK : VERTEX); } } public void addQuadraticVertex(float cx, float cy, float cz, float x3, float y3, float z3, boolean fill, boolean stroke, int detail, int code) { addQuadraticVertex(cx, cy, cz, x3, y3, z3, fill, stroke, detail, code, POLYGON); } public void addQuadraticVertex(float cx, float cy, float cz, float x3, float y3, float z3, boolean fill, boolean stroke, int detail, int code, int shape) { float x1 = getLastVertexX(); float y1 = getLastVertexY(); float z1 = getLastVertexZ(); addBezierVertex(x1 + ((cx-x1)*2/3.0f), y1 + ((cy-y1)*2/3.0f), z1 + ((cz-z1)*2/3.0f), x3 + ((cx-x3)*2/3.0f), y3 + ((cy-y3)*2/3.0f), z3 + ((cz-z3)*2/3.0f), x3, y3, z3, fill, stroke, detail, code, shape); } void addCurveVertex(float x, float y, float z, boolean fill, boolean stroke, int detail, int code) { addCurveVertex(x, y, z, fill, stroke, detail, code, POLYGON); } void addCurveVertex(float x, float y, float z, boolean fill, boolean stroke, int detail, int code, int shape) { curveVertexCheck(shape); float[] vertex = curveVertices[curveVertexCount]; vertex[X] = x; vertex[Y] = y; vertex[Z] = z; curveVertexCount++; // draw a segment if there are enough points if (curveVertexCount > 3) { float[] v1 = curveVertices[curveVertexCount-4]; float[] v2 = curveVertices[curveVertexCount-3]; float[] v3 = curveVertices[curveVertexCount-2]; float[] v4 = curveVertices[curveVertexCount-1]; addCurveVertexSegment(v1[X], v1[Y], v1[Z], v2[X], v2[Y], v2[Z], v3[X], v3[Y], v3[Z], v4[X], v4[Y], v4[Z], detail, code); } } void addCurveVertexSegment(float x1, float y1, float z1, float x2, float y2, float z2, float x3, float y3, float z3, float x4, float y4, float z4, int detail, int code) { float x0 = x2; float y0 = y2; float z0 = z2; PMatrix3D draw = curveDrawMatrix; float xplot1 = draw.m10*x1 + draw.m11*x2 + draw.m12*x3 + draw.m13*x4; float xplot2 = draw.m20*x1 + draw.m21*x2 + draw.m22*x3 + draw.m23*x4; float xplot3 = draw.m30*x1 + draw.m31*x2 + draw.m32*x3 + draw.m33*x4; float yplot1 = draw.m10*y1 + draw.m11*y2 + draw.m12*y3 + draw.m13*y4; float yplot2 = draw.m20*y1 + draw.m21*y2 + draw.m22*y3 + draw.m23*y4; float yplot3 = draw.m30*y1 + draw.m31*y2 + draw.m32*y3 + draw.m33*y4; float zplot1 = draw.m10*z1 + draw.m11*z2 + draw.m12*z3 + draw.m13*z4; float zplot2 = draw.m20*z1 + draw.m21*z2 + draw.m22*z3 + draw.m23*z4; float zplot3 = draw.m30*z1 + draw.m31*z2 + draw.m32*z3 + draw.m33*z4; // addVertex() will reset curveVertexCount, so save it int savedCount = curveVertexCount; addVertex(x0, y0, z0, code == BREAK ? BREAK : VERTEX); for (int j = 0; j < detail; j++) { x0 += xplot1; xplot1 += xplot2; xplot2 += xplot3; y0 += yplot1; yplot1 += yplot2; yplot2 += yplot3; z0 += zplot1; zplot1 += zplot2; zplot2 += zplot3; addVertex(x0, y0, z0, VERTEX); } curveVertexCount = savedCount; } // Returns the vertex data in the PGraphics double array format. float[][] getVertexData() { float[][] data = new float[vertexCount][VERTEX_FIELD_COUNT]; for (int i = 0; i < vertexCount; i++) { float[] vert = data[i]; vert[X] = vertices[3 * i + 0]; vert[Y] = vertices[3 * i + 1]; vert[Z] = vertices[3 * i + 2]; vert[R] = ((colors[i] >> 16) & 0xFF) / 255.0f; vert[G] = ((colors[i] >> 8) & 0xFF) / 255.0f; vert[B] = ((colors[i] >> 0) & 0xFF) / 255.0f; vert[A] = ((colors[i] >> 24) & 0xFF) / 255.0f; vert[U] = texcoords[2 * i + 0]; vert[V] = texcoords[2 * i + 1]; vert[NX] = normals[3 * i + 0]; vert[NY] = normals[3 * i + 1]; vert[NZ] = normals[3 * i + 2]; vert[SR] = ((strokeColors[i] >> 16) & 0xFF) / 255.0f; vert[SG] = ((strokeColors[i] >> 8) & 0xFF) / 255.0f; vert[SB] = ((strokeColors[i] >> 0) & 0xFF) / 255.0f; vert[SA] = ((strokeColors[i] >> 24) & 0xFF) / 255.0f; vert[SW] = strokeWeights[i]; vert[AR] = ((ambient[i] >> 16) & 0xFF) / 255.0f; vert[AG] = ((ambient[i] >> 8) & 0xFF) / 255.0f; vert[AB] = ((ambient[i] >> 0) & 0xFF) / 255.0f; vert[SPR] = ((specular[i] >> 16) & 0xFF) / 255.0f; vert[SPG] = ((specular[i] >> 8) & 0xFF) / 255.0f; vert[SPB] = ((specular[i] >> 0) & 0xFF) / 255.0f; vert[ER] = ((emissive[i] >> 16) & 0xFF) / 255.0f; vert[EG] = ((emissive[i] >> 8) & 0xFF) / 255.0f; vert[EB] = ((emissive[i] >> 0) & 0xFF) / 255.0f; vert[SHINE] = shininess[i]; } return data; } // ----------------------------------------------------------------- // // Edges int addEdge(int i, int j, boolean start, boolean end) { edgeCheck(); int[] edge = edges[edgeCount]; edge[0] = i; edge[1] = j; // Possible values for state: // 0 = middle edge (not start, not end) // 1 = start edge (start, not end) // 2 = end edge (not start, end) // 3 = isolated edge (start, end) edge[2] = (start ? 1 : 0) + 2 * (end ? 1 : 0); lastEdge = edgeCount; edgeCount++; return lastEdge; } void addTrianglesEdges() { for (int i = 0; i < (lastVertex - firstVertex + 1) / 3; i++) { int i0 = 3 * i + 0; int i1 = 3 * i + 1; int i2 = 3 * i + 2; addEdge(i0, i1, true, false); addEdge(i1, i2, false, false); addEdge(i2, i0, false, true); } } void addTriangleFanEdges() { for (int i = firstVertex + 1; i < lastVertex; i++) { int i0 = firstVertex; int i1 = i; int i2 = i + 1; addEdge(i0, i1, true, false); addEdge(i1, i2, false, false); addEdge(i2, i0, false, true); } } void addTriangleStripEdges() { for (int i = firstVertex + 1; i < lastVertex; i++) { int i0 = i; int i1, i2; if (i % 2 == 0) { i1 = i - 1; i2 = i + 1; } else { i1 = i + 1; i2 = i - 1; } addEdge(i0, i1, true, false); addEdge(i1, i2, false, false); addEdge(i2, i0, false, true); } } void addQuadsEdges() { for (int i = 0; i < (lastVertex - firstVertex + 1) / 4; i++) { int i0 = 4 * i + 0; int i1 = 4 * i + 1; int i2 = 4 * i + 2; int i3 = 4 * i + 3; addEdge(i0, i1, true, false); addEdge(i1, i2, false, false); addEdge(i2, i3, false, false); addEdge(i3, i0, false, true); } } void addQuadStripEdges() { for (int qd = 1; qd < (lastVertex - firstVertex + 1) / 2; qd++) { int i0 = firstVertex + 2 * (qd - 1); int i1 = firstVertex + 2 * (qd - 1) + 1; int i2 = firstVertex + 2 * qd + 1; int i3 = firstVertex + 2 * qd; addEdge(i0, i1, true, false); addEdge(i1, i2, false, false); addEdge(i2, i3, false, false); addEdge(i3, i0, false, true); } } void addPolygonEdges(boolean closed) { // Count number of edge segments in the perimeter. int edgeCount = 0; int lnMax = lastVertex - firstVertex + 1; int first = firstVertex; int contour0 = first; if (!closed) lnMax--; for (int ln = 0; ln < lnMax; ln++) { int i = first + ln + 1; if ((i == lnMax || breaks[i]) && closed) { i = first + ln; } if (!breaks[i]) { edgeCount++; } } if (0 < edgeCount) { boolean begin = true; contour0 = first; for (int ln = 0; ln < lnMax; ln++) { int i0 = first + ln; int i1 = first + ln + 1; if (breaks[i0]) contour0 = i0; if (i1 == lnMax || breaks[i1]) { // We are either at the end of a contour or at the end of the // edge path. if (closed) { // Draw line to the first vertex of the current contour, // if the polygon is closed. i0 = first + ln; i1 = contour0; addEdge(i0, i1, begin, true); } else if (!breaks[i1]) { addEdge(i0, i1, begin, false); } // We might start a new contour in the next iteration. begin = true; } else if (!breaks[i1]) { boolean end = i1 + 1 < lnMax && breaks[i1 + 1]; addEdge(i0, i1, begin, end); begin = false; } } } } // ----------------------------------------------------------------- // // Normal calculation void calcTriangleNormal(int i0, int i1, int i2) { int index; index = 3 * i0; float x0 = vertices[index++]; float y0 = vertices[index++]; float z0 = vertices[index ]; index = 3 * i1; float x1 = vertices[index++]; float y1 = vertices[index++]; float z1 = vertices[index ]; index = 3 * i2; float x2 = vertices[index++]; float y2 = vertices[index++]; float z2 = vertices[index ]; float v12x = x2 - x1; float v12y = y2 - y1; float v12z = z2 - z1; float v10x = x0 - x1; float v10y = y0 - y1; float v10z = z0 - z1; // The automatic normal calculation in Processing assumes // that vertices as given in CCW order so: // n = v12 x v10 // so that the normal outwards. float nx = v12y * v10z - v10y * v12z; float ny = v12z * v10x - v10z * v12x; float nz = v12x * v10y - v10x * v12y; float d = PApplet.sqrt(nx * nx + ny * ny + nz * nz); nx /= d; ny /= d; nz /= d; index = 3 * i0; normals[index++] = nx; normals[index++] = ny; normals[index ] = nz; index = 3 * i1; normals[index++] = nx; normals[index++] = ny; normals[index ] = nz; index = 3 * i2; normals[index++] = nx; normals[index++] = ny; normals[index ] = nz; } void calcTrianglesNormals() { for (int i = 0; i < (lastVertex - firstVertex + 1) / 3; i++) { int i0 = 3 * i + 0; int i1 = 3 * i + 1; int i2 = 3 * i + 2; calcTriangleNormal(i0, i1, i2); } } void calcTriangleFanNormals() { for (int i = firstVertex + 1; i < lastVertex; i++) { int i0 = firstVertex; int i1 = i; int i2 = i + 1; calcTriangleNormal(i0, i1, i2); } } void calcTriangleStripNormals() { for (int i = firstVertex + 1; i < lastVertex; i++) { int i1 = i; int i0, i2; if (i % 2 == 0) { // The even triangles (0, 2, 4...) should be CW i0 = i + 1; i2 = i - 1; } else { // The even triangles (1, 3, 5...) should be CCW i0 = i - 1; i2 = i + 1; } calcTriangleNormal(i0, i1, i2); } } void calcQuadsNormals() { for (int i = 0; i < (lastVertex - firstVertex + 1) / 4; i++) { int i0 = 4 * i + 0; int i1 = 4 * i + 1; int i2 = 4 * i + 2; int i3 = 4 * i + 3; calcTriangleNormal(i0, i1, i2); calcTriangleNormal(i2, i3, i0); } } void calcQuadStripNormals() { for (int qd = 1; qd < (lastVertex - firstVertex + 1) / 2; qd++) { int i0 = firstVertex + 2 * (qd - 1); int i1 = firstVertex + 2 * (qd - 1) + 1; int i2 = firstVertex + 2 * qd; int i3 = firstVertex + 2 * qd + 1; calcTriangleNormal(i0, i3, i1); calcTriangleNormal(i0, i2, i3); } } // ----------------------------------------------------------------- // // Primitives void setMaterial(int fillColor, int strokeColor, float strokeWeight, int ambientColor, int specularColor, int emissiveColor, float shininessFactor) { this.fillColor = fillColor; this.strokeColor = strokeColor; this.strokeWeight = strokeWeight; this.ambientColor = ambientColor; this.specularColor = specularColor; this.emissiveColor = emissiveColor; this.shininessFactor = shininessFactor; } void setNormal(float normalX, float normalY, float normalZ) { this.normalX = normalX; this.normalY = normalY; this.normalZ = normalZ; } void addPoint(float x, float y, float z, boolean fill, boolean stroke) { addVertex(x, y, z, VERTEX); } void addLine(float x1, float y1, float z1, float x2, float y2, float z2, boolean fill, boolean stroke) { int idx1 = addVertex(x1, y1, z1, VERTEX); int idx2 = addVertex(x2, y2, z2, VERTEX); if (stroke) addEdge(idx1, idx2, true, true); } void addTriangle(float x1, float y1, float z1, float x2, float y2, float z2, float x3, float y3, float z3, boolean fill, boolean stroke) { int idx1 = addVertex(x1, y1, z1, VERTEX); int idx2 = addVertex(x2, y2, z2, VERTEX); int idx3 = addVertex(x3, y3, z3, VERTEX); if (stroke) { addEdge(idx1, idx2, true, false); addEdge(idx2, idx3, false, false); addEdge(idx3, idx1, false, true); } } void addQuad(float x1, float y1, float z1, float x2, float y2, float z2, float x3, float y3, float z3, float x4, float y4, float z4, boolean fill, boolean stroke) { int idx1 = addVertex(x1, y1, z1, 0, 0, VERTEX); int idx2 = addVertex(x2, y2, z2, 1, 0, VERTEX); int idx3 = addVertex(x3, y3, z3, 1, 1, VERTEX); int idx4 = addVertex(x4, y4, z4, 0, 1, VERTEX); if (stroke) { addEdge(idx1, idx2, true, false); addEdge(idx2, idx3, false, false); addEdge(idx3, idx4, false, false); addEdge(idx4, idx1, false, true); } } void addRect(float a, float b, float c, float d, boolean fill, boolean stroke, int rectMode) { float hradius, vradius; switch (rectMode) { case CORNERS: break; case CORNER: c += a; d += b; break; case RADIUS: hradius = c; vradius = d; c = a + hradius; d = b + vradius; a -= hradius; b -= vradius; break; case CENTER: hradius = c / 2.0f; vradius = d / 2.0f; c = a + hradius; d = b + vradius; a -= hradius; b -= vradius; } if (a > c) { float temp = a; a = c; c = temp; } if (b > d) { float temp = b; b = d; d = temp; } addQuad(a, b, 0, c, b, 0, c, d, 0, a, d, 0, fill, stroke); } void addRect(float a, float b, float c, float d, float tl, float tr, float br, float bl, boolean fill, boolean stroke, int detail, int rectMode) { float hradius, vradius; switch (rectMode) { case CORNERS: break; case CORNER: c += a; d += b; break; case RADIUS: hradius = c; vradius = d; c = a + hradius; d = b + vradius; a -= hradius; b -= vradius; break; case CENTER: hradius = c / 2.0f; vradius = d / 2.0f; c = a + hradius; d = b + vradius; a -= hradius; b -= vradius; } if (a > c) { float temp = a; a = c; c = temp; } if (b > d) { float temp = b; b = d; d = temp; } float maxRounding = PApplet.min((c - a) / 2, (d - b) / 2); if (tl > maxRounding) tl = maxRounding; if (tr > maxRounding) tr = maxRounding; if (br > maxRounding) br = maxRounding; if (bl > maxRounding) bl = maxRounding; if (nonZero(tr)) { addVertex(c-tr, b, VERTEX); addQuadraticVertex(c, b, 0, c, b+tr, 0, fill, stroke, detail, VERTEX); } else { addVertex(c, b, VERTEX); } if (nonZero(br)) { addVertex(c, d-br, VERTEX); addQuadraticVertex(c, d, 0, c-br, d, 0, fill, stroke, detail, VERTEX); } else { addVertex(c, d, VERTEX); } if (nonZero(bl)) { addVertex(a+bl, d, VERTEX); addQuadraticVertex(a, d, 0, a, d-bl, 0, fill, stroke, detail, VERTEX); } else { addVertex(a, d, VERTEX); } if (nonZero(tl)) { addVertex(a, b+tl, VERTEX); addQuadraticVertex(a, b, 0, a+tl, b, 0, fill, stroke, detail, VERTEX); } else { addVertex(a, b, VERTEX); } if (stroke) addPolygonEdges(true); } void addEllipse(float a, float b, float c, float d, boolean fill, boolean stroke, int ellipseMode) { float x = a; float y = b; float w = c; float h = d; if (ellipseMode == CORNERS) { w = c - a; h = d - b; } else if (ellipseMode == RADIUS) { x = a - c; y = b - d; w = c * 2; h = d * 2; } else if (ellipseMode == DIAMETER) { x = a - c/2f; y = b - d/2f; } if (w < 0) { // undo negative width x += w; w = -w; } if (h < 0) { // undo negative height y += h; h = -h; } float radiusH = w / 2; float radiusV = h / 2; float centerX = x + radiusH; float centerY = y + radiusV; // should call screenX/Y using current renderer. float sx1 = pgCurrent.screenX(x, y); float sy1 = pgCurrent.screenY(x, y); float sx2 = pgCurrent.screenX(x + w, y + h); float sy2 = pgCurrent.screenY(x + w, y + h); int accuracy = PApplet.max(MIN_POINT_ACCURACY, (int) (TWO_PI * PApplet.dist(sx1, sy1, sx2, sy2) / POINT_ACCURACY_FACTOR)); float inc = (float) PGraphicsOpenGL.SINCOS_LENGTH / accuracy; if (fill) { addVertex(centerX, centerY, VERTEX); } int idx0, pidx, idx; idx0 = pidx = idx = 0; float val = 0; for (int i = 0; i < accuracy; i++) { idx = addVertex(centerX + PGraphicsOpenGL.cosLUT[(int) val] * radiusH, centerY + PGraphicsOpenGL.sinLUT[(int) val] * radiusV, VERTEX); val = (val + inc) % PGraphicsOpenGL.SINCOS_LENGTH; if (0 < i) { if (stroke) addEdge(pidx, idx, i == 1, false); } else { idx0 = idx; } pidx = idx; } // Back to the beginning addVertex(centerX + PGraphicsOpenGL.cosLUT[0] * radiusH, centerY + PGraphicsOpenGL.sinLUT[0] * radiusV, VERTEX); if (stroke) addEdge(idx, idx0, false, true); } void addArc(float a, float b, float c, float d, float start, float stop, boolean fill, boolean stroke, int ellipseMode) { float x = a; float y = b; float w = c; float h = d; if (ellipseMode == CORNERS) { w = c - a; h = d - b; } else if (ellipseMode == RADIUS) { x = a - c; y = b - d; w = c * 2; h = d * 2; } else if (ellipseMode == CENTER) { x = a - c/2f; y = b - d/2f; } // make sure this loop will exit before starting while if (Float.isInfinite(start) || Float.isInfinite(stop)) return; if (stop < start) return; // why bother // make sure that we're starting at a useful point while (start < 0) { start += TWO_PI; stop += TWO_PI; } if (stop - start > TWO_PI) { start = 0; stop = TWO_PI; } float hr = w / 2f; float vr = h / 2f; float centerX = x + hr; float centerY = y + vr; int startLUT = (int) (0.5f + (start / TWO_PI) * SINCOS_LENGTH); int stopLUT = (int) (0.5f + (stop / TWO_PI) * SINCOS_LENGTH); if (fill) { vertex(centerX, centerY, VERTEX); } int increment = 1; // what's a good algorithm? stopLUT - startLUT; int pidx, idx; pidx = idx = 0; for (int i = startLUT; i < stopLUT; i += increment) { int ii = i % SINCOS_LENGTH; // modulo won't make the value positive if (ii < 0) ii += SINCOS_LENGTH; idx = addVertex(centerX + cosLUT[ii] * hr, centerY + sinLUT[ii] * vr, VERTEX); if (0 < i) { if (stroke) addEdge(pidx, idx, i == 1, false); } pidx = idx; } // draw last point explicitly for accuracy idx = addVertex(centerX + cosLUT[stopLUT % SINCOS_LENGTH] * hr, centerY + sinLUT[stopLUT % SINCOS_LENGTH] * vr, VERTEX); if (stroke) addEdge(pidx, idx, false, true); } void addBox(float w, float h, float d, boolean fill, boolean stroke) { float x1 = -w/2f; float x2 = w/2f; float y1 = -h/2f; float y2 = h/2f; float z1 = -d/2f; float z2 = d/2f; if (fill || stroke) { // front face setNormal(0, 0, 1); addVertex(x1, y1, z1, 0, 0, VERTEX); addVertex(x2, y1, z1, 1, 0, VERTEX); addVertex(x2, y2, z1, 1, 1, VERTEX); addVertex(x1, y2, z1, 0, 1, VERTEX); // right face setNormal(1, 0, 0); addVertex(x2, y1, z1, 0, 0, VERTEX); addVertex(x2, y1, z2, 1, 0, VERTEX); addVertex(x2, y2, z2, 1, 1, VERTEX); addVertex(x2, y2, z1, 0, 1, VERTEX); // back face setNormal(0, 0, -1); addVertex(x2, y1, z2, 0, 0, VERTEX); addVertex(x1, y1, z2, 1, 0, VERTEX); addVertex(x1, y2, z2, 1, 1, VERTEX); addVertex(x2, y2, z2, 0, 1, VERTEX); // left face setNormal(-1, 0, 0); addVertex(x1, y1, z2, 0, 0, VERTEX); addVertex(x1, y1, z1, 1, 0, VERTEX); addVertex(x1, y2, z1, 1, 1, VERTEX); addVertex(x1, y2, z2, 0, 1, VERTEX);; // top face setNormal(0, 1, 0); addVertex(x1, y1, z2, 0, 0, VERTEX); addVertex(x2, y1, z2, 1, 0, VERTEX); addVertex(x2, y1, z1, 1, 1, VERTEX); addVertex(x1, y1, z1, 0, 1, VERTEX); // bottom face setNormal(0, -1, 0); addVertex(x1, y2, z1, 0, 0, VERTEX); addVertex(x2, y2, z1, 1, 0, VERTEX); addVertex(x2, y2, z2, 1, 1, VERTEX); addVertex(x1, y2, z2, 0, 1, VERTEX); } if (stroke) { addEdge(0, 1, true, true); addEdge(1, 2, true, true); addEdge(2, 3, true, true); addEdge(3, 0, true, true); addEdge(0, 9, true, true); addEdge(1, 8, true, true); addEdge(2, 11, true, true); addEdge(3, 10, true, true); addEdge( 8, 9, true, true); addEdge( 9, 10, true, true); addEdge(10, 11, true, true); addEdge(11, 8, true, true); } } // Adds the vertices that define an sphere, without duplicating // any vertex or edge. int[] addSphere(float r, int detailU, int detailV, boolean fill, boolean stroke) { if ((detailU < 3) || (detailV < 2)) { sphereDetail(30); detailU = detailV = 30; } else { sphereDetail(detailU, detailV); } int nind = 3 * detailU + (6 * detailU + 3) * (detailV - 2) + 3 * detailU; int[] indices = new int[nind]; int vertCount = 0; int indCount = 0; int vert0, vert1; float u, v; float du = 1.0f / (detailU); float dv = 1.0f / (detailV); // Southern cap ------------------------------------------------------- // Adding multiple copies of the south pole vertex, each one with a // different u coordinate, so the texture mapping is correct when // making the first strip of triangles. u = 1; v = 1; for (int i = 0; i < detailU; i++) { setNormal(0, 1, 0); addVertex(0, r, 0, u , v, VERTEX); u -= du; } vertCount = detailU; vert0 = vertCount; u = 1; v -= dv; for (int i = 0; i < detailU; i++) { setNormal(sphereX[i], sphereY[i], sphereZ[i]); addVertex(r * sphereX[i], r *sphereY[i], r * sphereZ[i], u , v, VERTEX); u -= du; } vertCount += detailU; vert1 = vertCount; setNormal(sphereX[0], sphereY[0], sphereZ[0]); addVertex(r * sphereX[0], r * sphereY[0], r * sphereZ[0], u, v, VERTEX); vertCount++; for (int i = 0; i < detailU; i++) { int i1 = vert0 + i; int i0 = vert0 + i - detailU; indices[3 * i + 0] = i1; indices[3 * i + 1] = i0; indices[3 * i + 2] = i1 + 1; addEdge(i0, i1, true, true); addEdge(i1, i1 + 1, true, true); } indCount += 3 * detailU; // Middle rings ------------------------------------------------------- int offset = 0; for (int j = 2; j < detailV; j++) { offset += detailU; vert0 = vertCount; u = 1; v -= dv; for (int i = 0; i < detailU; i++) { int ioff = offset + i; setNormal(sphereX[ioff], sphereY[ioff], sphereZ[ioff]); addVertex(r * sphereX[ioff], r *sphereY[ioff], r * sphereZ[ioff], u , v, VERTEX); u -= du; } vertCount += detailU; vert1 = vertCount; setNormal(sphereX[offset], sphereY[offset], sphereZ[offset]); addVertex(r * sphereX[offset], r * sphereY[offset], r * sphereZ[offset], u, v, VERTEX); vertCount++; for (int i = 0; i < detailU; i++) { int i1 = vert0 + i; int i0 = vert0 + i - detailU - 1; indices[indCount + 6 * i + 0] = i1; indices[indCount + 6 * i + 1] = i0; indices[indCount + 6 * i + 2] = i0 + 1; indices[indCount + 6 * i + 3] = i1; indices[indCount + 6 * i + 4] = i0 + 1; indices[indCount + 6 * i + 5] = i1 + 1; addEdge(i0, i1, true, true); addEdge(i1, i1 + 1, true, true); addEdge(i0 + 1, i1, true, true); } indCount += 6 * detailU; indices[indCount + 0] = vert1; indices[indCount + 1] = vert1 - detailU; indices[indCount + 2] = vert1 - 1; indCount += 3; addEdge(vert1 - detailU, vert1 - 1, true, true); addEdge(vert1 - 1, vert1, true, true); } // Northern cap ------------------------------------------------------- // Adding multiple copies of the north pole vertex, each one with a // different u coordinate, so the texture mapping is correct when // making the last strip of triangles. u = 1; v = 0; for (int i = 0; i < detailU; i++) { setNormal(0, -1, 0); addVertex(0, -r, 0, u , v, VERTEX); u -= du; } vertCount += detailU; for (int i = 0; i < detailU; i++) { int i0 = vert0 + i; int i1 = vert0 + i + detailU + 1; indices[indCount + 3 * i + 0] = i0; indices[indCount + 3 * i + 1] = i1; indices[indCount + 3 * i + 2] = i0 + 1; addEdge(i0, i0 + 1, true, true); addEdge(i0, i1, true, true); } indCount += 3 * detailU; return indices; } } // Holds tessellated data for polygon, line and point geometry. protected class TessGeometry { int renderMode; // Tessellated polygon data int polyVertexCount; int firstPolyVertex; int lastPolyVertex; float[] polyVertices; int[] polyColors; float[] polyNormals; float[] polyTexcoords; // Polygon material properties (polyColors is used // as the diffuse color when lighting is enabled) int[] polyAmbient; int[] polySpecular; int[] polyEmissive; float[] polyShininess; int polyIndexCount; int firstPolyIndex; int lastPolyIndex; short[] polyIndices; IndexCache polyIndexCache = new IndexCache(); // Tessellated line data int lineVertexCount; int firstLineVertex; int lastLineVertex; float[] lineVertices; int[] lineColors; float[] lineAttribs; int lineIndexCount; int firstLineIndex; int lastLineIndex; short[] lineIndices; IndexCache lineIndexCache = new IndexCache(); // Tessellated point data int pointVertexCount; int firstPointVertex; int lastPointVertex; float[] pointVertices; int[] pointColors; float[] pointAttribs; int pointIndexCount; int firstPointIndex; int lastPointIndex; short[] pointIndices; IndexCache pointIndexCache = new IndexCache(); TessGeometry(int mode) { renderMode = mode; allocate(); } // ----------------------------------------------------------------- // // Allocate/dispose void allocate() { polyVertices = new float[4 * PGL.DEFAULT_TESS_VERTICES]; polyColors = new int[PGL.DEFAULT_TESS_VERTICES]; polyNormals = new float[3 * PGL.DEFAULT_TESS_VERTICES]; polyTexcoords = new float[2 * PGL.DEFAULT_TESS_VERTICES]; polyAmbient = new int[PGL.DEFAULT_TESS_VERTICES]; polySpecular = new int[PGL.DEFAULT_TESS_VERTICES]; polyEmissive = new int[PGL.DEFAULT_TESS_VERTICES]; polyShininess = new float[PGL.DEFAULT_TESS_VERTICES]; polyIndices = new short[PGL.DEFAULT_TESS_VERTICES]; lineVertices = new float[4 * PGL.DEFAULT_TESS_VERTICES]; lineColors = new int[PGL.DEFAULT_TESS_VERTICES]; lineAttribs = new float[4 * PGL.DEFAULT_TESS_VERTICES]; lineIndices = new short[PGL.DEFAULT_TESS_VERTICES]; pointVertices = new float[4 * PGL.DEFAULT_TESS_VERTICES]; pointColors = new int[PGL.DEFAULT_TESS_VERTICES]; pointAttribs = new float[2 * PGL.DEFAULT_TESS_VERTICES]; pointIndices = new short[PGL.DEFAULT_TESS_VERTICES]; clear(); } void clear() { firstPolyVertex = lastPolyVertex = polyVertexCount = 0; firstPolyIndex = lastPolyIndex = polyIndexCount = 0; firstLineVertex = lastLineVertex = lineVertexCount = 0; firstLineIndex = lastLineIndex = lineIndexCount = 0; firstPointVertex = lastPointVertex = pointVertexCount = 0; firstPointIndex = lastPointIndex = pointIndexCount = 0; polyIndexCache.clear(); lineIndexCache.clear(); pointIndexCache.clear(); } void dipose() { polyVertices = null; polyColors = null; polyNormals = null; polyTexcoords = null; polyAmbient = null; polySpecular = null; polyEmissive = null; polyShininess = null; polyIndices = null; lineVertices = null; lineColors = null; lineAttribs = null; lineIndices = null; pointVertices = null; pointColors = null; pointAttribs = null; pointIndices = null; } void polyVertexCheck() { if (polyVertexCount == polyVertices.length / 4) { int newSize = polyVertexCount << 1; expandPolyVertices(newSize); expandPolyColors(newSize); expandPolyNormals(newSize); expandPolyTexcoords(newSize); expandPolyAmbient(newSize); expandPolySpecular(newSize); expandPolyEmissive(newSize); expandPolyShininess(newSize); } firstPolyVertex = polyVertexCount; polyVertexCount++; lastPolyVertex = polyVertexCount - 1; } void polyVertexCheck(int count) { int oldSize = polyVertices.length / 4; if (polyVertexCount + count > oldSize) { int newSize = expandArraySize(oldSize, polyVertexCount + count); expandPolyVertices(newSize); expandPolyColors(newSize); expandPolyNormals(newSize); expandPolyTexcoords(newSize); expandPolyAmbient(newSize); expandPolySpecular(newSize); expandPolyEmissive(newSize); expandPolyShininess(newSize); } firstPolyVertex = polyVertexCount; polyVertexCount += count; lastPolyVertex = polyVertexCount - 1; } void polyIndexCheck(int count) { int oldSize = polyIndices.length; if (polyIndexCount + count > oldSize) { int newSize = expandArraySize(oldSize, polyIndexCount + count); expandPolyIndices(newSize); } firstPolyIndex = polyIndexCount; polyIndexCount += count; lastPolyIndex = polyIndexCount - 1; } void polyIndexCheck() { if (polyIndexCount == polyIndices.length) { int newSize = polyIndexCount << 1; expandPolyIndices(newSize); } firstPolyIndex = polyIndexCount; polyIndexCount++; lastPolyIndex = polyIndexCount - 1; } void lineVertexCheck(int count) { int oldSize = lineVertices.length / 4; if (lineVertexCount + count > oldSize) { int newSize = expandArraySize(oldSize, lineVertexCount + count); expandLineVertices(newSize); expandLineColors(newSize); expandLineAttribs(newSize); } firstLineVertex = lineVertexCount; lineVertexCount += count; lastLineVertex = lineVertexCount - 1; } void lineIndexCheck(int count) { int oldSize = lineIndices.length; if (lineIndexCount + count > oldSize) { int newSize = expandArraySize(oldSize, lineIndexCount + count); expandLineIndices(newSize); } firstLineIndex = lineIndexCount; lineIndexCount += count; lastLineIndex = lineIndexCount - 1; } void pointVertexCheck(int count) { int oldSize = pointVertices.length / 4; if (pointVertexCount + count > oldSize) { int newSize = expandArraySize(oldSize, pointVertexCount + count); expandPointVertices(newSize); expandPointColors(newSize); expandPointAttribs(newSize); } firstPointVertex = pointVertexCount; pointVertexCount += count; lastPointVertex = pointVertexCount - 1; } void pointIndexCheck(int count) { int oldSize = pointIndices.length; if (pointIndexCount + count > oldSize) { int newSize = expandArraySize(oldSize, pointIndexCount + count); expandPointIndices(newSize); } firstPointIndex = pointIndexCount; pointIndexCount += count; lastPointIndex = pointIndexCount - 1; } // ----------------------------------------------------------------- // // Query boolean isFull() { return PGL.FLUSH_VERTEX_COUNT <= polyVertexCount || PGL.FLUSH_VERTEX_COUNT <= lineVertexCount || PGL.FLUSH_VERTEX_COUNT <= pointVertexCount; } void getPolyVertexMin(PVector v, int first, int last) { for (int i = first; i <= last; i++) { int index = 4 * i; v.x = PApplet.min(v.x, polyVertices[index++]); v.y = PApplet.min(v.y, polyVertices[index++]); v.z = PApplet.min(v.z, polyVertices[index ]); } } void getLineVertexMin(PVector v, int first, int last) { for (int i = first; i <= last; i++) { int index = 4 * i; v.x = PApplet.min(v.x, lineVertices[index++]); v.y = PApplet.min(v.y, lineVertices[index++]); v.z = PApplet.min(v.z, lineVertices[index ]); } } void getPointVertexMin(PVector v, int first, int last) { for (int i = first; i <= last; i++) { int index = 4 * i; v.x = PApplet.min(v.x, pointVertices[index++]); v.y = PApplet.min(v.y, pointVertices[index++]); v.z = PApplet.min(v.z, pointVertices[index ]); } } void getPolyVertexMax(PVector v, int first, int last) { for (int i = first; i <= last; i++) { int index = 4 * i; v.x = PApplet.max(v.x, polyVertices[index++]); v.y = PApplet.max(v.y, polyVertices[index++]); v.z = PApplet.max(v.z, polyVertices[index ]); } } void getLineVertexMax(PVector v, int first, int last) { for (int i = first; i <= last; i++) { int index = 4 * i; v.x = PApplet.max(v.x, lineVertices[index++]); v.y = PApplet.max(v.y, lineVertices[index++]); v.z = PApplet.max(v.z, lineVertices[index ]); } } void getPointVertexMax(PVector v, int first, int last) { for (int i = first; i <= last; i++) { int index = 4 * i; v.x = PApplet.max(v.x, pointVertices[index++]); v.y = PApplet.max(v.y, pointVertices[index++]); v.z = PApplet.max(v.z, pointVertices[index ]); } } int getPolyVertexSum(PVector v, int first, int last) { for (int i = first; i <= last; i++) { int index = 4 * i; v.x += polyVertices[index++]; v.y += polyVertices[index++]; v.z += polyVertices[index ]; } return last - first + 1; } int getLineVertexSum(PVector v, int first, int last) { for (int i = first; i <= last; i++) { int index = 4 * i; v.x += lineVertices[index++]; v.y += lineVertices[index++]; v.z += lineVertices[index ]; } return last - first + 1; } int getPointVertexSum(PVector v, int first, int last) { for (int i = first; i <= last; i++) { int index = 4 * i; v.x += pointVertices[index++]; v.y += pointVertices[index++]; v.z += pointVertices[index ]; } return last - first + 1; } // ----------------------------------------------------------------- // // Expand arrays void expandPolyVertices(int n) { float temp[] = new float[4 * n]; PApplet.arrayCopy(polyVertices, 0, temp, 0, 4 * polyVertexCount); polyVertices = temp; } void expandPolyColors(int n) { int temp[] = new int[n]; PApplet.arrayCopy(polyColors, 0, temp, 0, polyVertexCount); polyColors = temp; } void expandPolyNormals(int n) { float temp[] = new float[3 * n]; PApplet.arrayCopy(polyNormals, 0, temp, 0, 3 * polyVertexCount); polyNormals = temp; } void expandPolyTexcoords(int n) { float temp[] = new float[2 * n]; PApplet.arrayCopy(polyTexcoords, 0, temp, 0, 2 * polyVertexCount); polyTexcoords = temp; } void expandPolyAmbient(int n) { int temp[] = new int[n]; PApplet.arrayCopy(polyAmbient, 0, temp, 0, polyVertexCount); polyAmbient = temp; } void expandPolySpecular(int n) { int temp[] = new int[n]; PApplet.arrayCopy(polySpecular, 0, temp, 0, polyVertexCount); polySpecular = temp; } void expandPolyEmissive(int n) { int temp[] = new int[n]; PApplet.arrayCopy(polyEmissive, 0, temp, 0, polyVertexCount); polyEmissive = temp; } void expandPolyShininess(int n) { float temp[] = new float[n]; PApplet.arrayCopy(polyShininess, 0, temp, 0, polyVertexCount); polyShininess = temp; } void expandPolyIndices(int n) { short temp[] = new short[n]; PApplet.arrayCopy(polyIndices, 0, temp, 0, polyIndexCount); polyIndices = temp; } void expandLineVertices(int n) { float temp[] = new float[4 * n]; PApplet.arrayCopy(lineVertices, 0, temp, 0, 4 * lineVertexCount); lineVertices = temp; } void expandLineColors(int n) { int temp[] = new int[n]; PApplet.arrayCopy(lineColors, 0, temp, 0, lineVertexCount); lineColors = temp; } void expandLineAttribs(int n) { float temp[] = new float[4 * n]; PApplet.arrayCopy(lineAttribs, 0, temp, 0, 4 * lineVertexCount); lineAttribs = temp; } void expandLineIndices(int n) { short temp[] = new short[n]; PApplet.arrayCopy(lineIndices, 0, temp, 0, lineIndexCount); lineIndices = temp; } void expandPointVertices(int n) { float temp[] = new float[4 * n]; PApplet.arrayCopy(pointVertices, 0, temp, 0, 4 * pointVertexCount); pointVertices = temp; } void expandPointColors(int n) { int temp[] = new int[n]; PApplet.arrayCopy(pointColors, 0, temp, 0, pointVertexCount); pointColors = temp; } void expandPointAttribs(int n) { float temp[] = new float[2 * n]; PApplet.arrayCopy(pointAttribs, 0, temp, 0, 2 * pointVertexCount); pointAttribs = temp; } void expandPointIndices(int n) { short temp[] = new short[n]; PApplet.arrayCopy(pointIndices, 0, temp, 0, pointIndexCount); pointIndices = temp; } // ----------------------------------------------------------------- // // Trim arrays void trim() { if (0 < polyVertexCount && polyVertexCount < polyVertices.length / 4) { trimPolyVertices(); trimPolyColors(); trimPolyNormals(); trimPolyTexcoords(); trimPolyAmbient(); trimPolySpecular(); trimPolyEmissive(); trimPolyShininess(); } if (0 < polyIndexCount && polyIndexCount < polyIndices.length) { trimPolyIndices(); } if (0 < lineVertexCount && lineVertexCount < lineVertices.length / 4) { trimLineVertices(); trimLineColors(); trimLineAttribs(); } if (0 < lineIndexCount && lineIndexCount < lineIndices.length) { trimLineIndices(); } if (0 < pointVertexCount && pointVertexCount < pointVertices.length / 4) { trimPointVertices(); trimPointColors(); trimPointAttribs(); } if (0 < pointIndexCount && pointIndexCount < pointIndices.length) { trimPointIndices(); } } void trimPolyVertices() { float temp[] = new float[4 * polyVertexCount]; PApplet.arrayCopy(polyVertices, 0, temp, 0, 4 * polyVertexCount); polyVertices = temp; } void trimPolyColors() { int temp[] = new int[polyVertexCount]; PApplet.arrayCopy(polyColors, 0, temp, 0, polyVertexCount); polyColors = temp; } void trimPolyNormals() { float temp[] = new float[3 * polyVertexCount]; PApplet.arrayCopy(polyNormals, 0, temp, 0, 3 * polyVertexCount); polyNormals = temp; } void trimPolyTexcoords() { float temp[] = new float[2 * polyVertexCount]; PApplet.arrayCopy(polyTexcoords, 0, temp, 0, 2 * polyVertexCount); polyTexcoords = temp; } void trimPolyAmbient() { int temp[] = new int[polyVertexCount]; PApplet.arrayCopy(polyAmbient, 0, temp, 0, polyVertexCount); polyAmbient = temp; } void trimPolySpecular() { int temp[] = new int[polyVertexCount]; PApplet.arrayCopy(polySpecular, 0, temp, 0, polyVertexCount); polySpecular = temp; } void trimPolyEmissive() { int temp[] = new int[polyVertexCount]; PApplet.arrayCopy(polyEmissive, 0, temp, 0, polyVertexCount); polyEmissive = temp; } void trimPolyShininess() { float temp[] = new float[polyVertexCount]; PApplet.arrayCopy(polyShininess, 0, temp, 0, polyVertexCount); polyShininess = temp; } void trimPolyIndices() { short temp[] = new short[polyIndexCount]; PApplet.arrayCopy(polyIndices, 0, temp, 0, polyIndexCount); polyIndices = temp; } void trimLineVertices() { float temp[] = new float[4 * lineVertexCount]; PApplet.arrayCopy(lineVertices, 0, temp, 0, 4 * lineVertexCount); lineVertices = temp; } void trimLineColors() { int temp[] = new int[lineVertexCount]; PApplet.arrayCopy(lineColors, 0, temp, 0, lineVertexCount); lineColors = temp; } void trimLineAttribs() { float temp[] = new float[4 * lineVertexCount]; PApplet.arrayCopy(lineAttribs, 0, temp, 0, 4 * lineVertexCount); lineAttribs = temp; } void trimLineIndices() { short temp[] = new short[lineIndexCount]; PApplet.arrayCopy(lineIndices, 0, temp, 0, lineIndexCount); lineIndices = temp; } void trimPointVertices() { float temp[] = new float[4 * pointVertexCount]; PApplet.arrayCopy(pointVertices, 0, temp, 0, 4 * pointVertexCount); pointVertices = temp; } void trimPointColors() { int temp[] = new int[pointVertexCount]; PApplet.arrayCopy(pointColors, 0, temp, 0, pointVertexCount); pointColors = temp; } void trimPointAttribs() { float temp[] = new float[2 * pointVertexCount]; PApplet.arrayCopy(pointAttribs, 0, temp, 0, 2 * pointVertexCount); pointAttribs = temp; } void trimPointIndices() { short temp[] = new short[pointIndexCount]; PApplet.arrayCopy(pointIndices, 0, temp, 0, pointIndexCount); pointIndices = temp; } // ----------------------------------------------------------------- // // Aggregation methods void incPolyIndices(int first, int last, int inc) { for (int i = first; i <= last; i++) { polyIndices[i] += inc; } } void incLineIndices(int first, int last, int inc) { for (int i = first; i <= last; i++) { lineIndices[i] += inc; } } void incPointIndices(int first, int last, int inc) { for (int i = first; i <= last; i++) { pointIndices[i] += inc; } } // ----------------------------------------------------------------- // // Normal calculation void calcPolyNormal(int i0, int i1, int i2) { int index; index = 4 * i0; float x0 = polyVertices[index++]; float y0 = polyVertices[index++]; float z0 = polyVertices[index ]; index = 4 * i1; float x1 = polyVertices[index++]; float y1 = polyVertices[index++]; float z1 = polyVertices[index ]; index = 4 * i2; float x2 = polyVertices[index++]; float y2 = polyVertices[index++]; float z2 = polyVertices[index ]; float v12x = x2 - x1; float v12y = y2 - y1; float v12z = z2 - z1; float v10x = x0 - x1; float v10y = y0 - y1; float v10z = z0 - z1; float nx = v12y * v10z - v10y * v12z; float ny = v12z * v10x - v10z * v12x; float nz = v12x * v10y - v10x * v12y; float d = PApplet.sqrt(nx * nx + ny * ny + nz * nz); nx /= d; ny /= d; nz /= d; index = 3 * i0; polyNormals[index++] = nx; polyNormals[index++] = ny; polyNormals[index ] = nz; index = 3 * i1; polyNormals[index++] = nx; polyNormals[index++] = ny; polyNormals[index ] = nz; index = 3 * i2; polyNormals[index++] = nx; polyNormals[index++] = ny; polyNormals[index ] = nz; } // ----------------------------------------------------------------- // // Add point geometry // Sets point vertex with index tessIdx using the data from input vertex inIdx. void setPointVertex(int tessIdx, InGeometry in, int inIdx) { int index; index = 3 * inIdx; float x = in.vertices[index++]; float y = in.vertices[index++]; float z = in.vertices[index ]; if (renderMode == IMMEDIATE && flushMode == FLUSH_WHEN_FULL && !hints[DISABLE_TRANSFORM_CACHE]) { PMatrix3D mm = modelview; index = 4 * tessIdx; pointVertices[index++] = x * mm.m00 + y * mm.m01 + z * mm.m02 + mm.m03; pointVertices[index++] = x * mm.m10 + y * mm.m11 + z * mm.m12 + mm.m13; pointVertices[index++] = x * mm.m20 + y * mm.m21 + z * mm.m22 + mm.m23; pointVertices[index ] = x * mm.m30 + y * mm.m31 + z * mm.m32 + mm.m33; } else { index = 4 * tessIdx; pointVertices[index++] = x; pointVertices[index++] = y; pointVertices[index++] = z; pointVertices[index ] = 1; } pointColors[tessIdx] = in.strokeColors[inIdx]; } // ----------------------------------------------------------------- // // Add line geometry void setLineVertex(int tessIdx, InGeometry in, int inIdx0, int rgba) { int index; index = 3 * inIdx0; float x0 = in.vertices[index++]; float y0 = in.vertices[index++]; float z0 = in.vertices[index ]; if (renderMode == IMMEDIATE && flushMode == FLUSH_WHEN_FULL && !hints[DISABLE_TRANSFORM_CACHE]) { PMatrix3D mm = modelview; index = 4 * tessIdx; lineVertices[index++] = x0 * mm.m00 + y0 * mm.m01 + z0 * mm.m02 + mm.m03; lineVertices[index++] = x0 * mm.m10 + y0 * mm.m11 + z0 * mm.m12 + mm.m13; lineVertices[index++] = x0 * mm.m20 + y0 * mm.m21 + z0 * mm.m22 + mm.m23; lineVertices[index ] = x0 * mm.m30 + y0 * mm.m31 + z0 * mm.m32 + mm.m33; } else { index = 4 * tessIdx; lineVertices[index++] = x0; lineVertices[index++] = y0; lineVertices[index++] = z0; lineVertices[index ] = 1; } lineColors[tessIdx] = rgba; index = 4 * tessIdx; lineAttribs[index++] = 0; lineAttribs[index++] = 0; lineAttribs[index++] = 0; lineAttribs[index ] = 0; } // Sets line vertex with index tessIdx using the data from input vertices inIdx0 and inIdx1. void setLineVertex(int tessIdx, InGeometry in, int inIdx0, int inIdx1, int rgba, float weight) { int index; index = 3 * inIdx0; float x0 = in.vertices[index++]; float y0 = in.vertices[index++]; float z0 = in.vertices[index ]; index = 3 * inIdx1; float x1 = in.vertices[index++]; float y1 = in.vertices[index++]; float z1 = in.vertices[index ]; if (renderMode == IMMEDIATE && flushMode == FLUSH_WHEN_FULL && !hints[DISABLE_TRANSFORM_CACHE]) { PMatrix3D mm = modelview; index = 4 * tessIdx; lineVertices[index++] = x0 * mm.m00 + y0 * mm.m01 + z0 * mm.m02 + mm.m03; lineVertices[index++] = x0 * mm.m10 + y0 * mm.m11 + z0 * mm.m12 + mm.m13; lineVertices[index++] = x0 * mm.m20 + y0 * mm.m21 + z0 * mm.m22 + mm.m23; lineVertices[index ] = x0 * mm.m30 + y0 * mm.m31 + z0 * mm.m32 + mm.m33; index = 4 * tessIdx; lineAttribs[index++] = x1 * mm.m00 + y1 * mm.m01 + z1 * mm.m02 + mm.m03; lineAttribs[index++] = x1 * mm.m10 + y1 * mm.m11 + z1 * mm.m12 + mm.m13; lineAttribs[index ] = x1 * mm.m20 + y1 * mm.m21 + z1 * mm.m22 + mm.m23; } else { index = 4 * tessIdx; lineVertices[index++] = x0; lineVertices[index++] = y0; lineVertices[index++] = z0; lineVertices[index ] = 1; index = 4 * tessIdx; lineAttribs[index++] = x1; lineAttribs[index++] = y1; lineAttribs[index ] = z1; } lineColors[tessIdx] = rgba; lineAttribs[4 * tessIdx + 3] = weight; } // ----------------------------------------------------------------- // // Add poly geometry void setPolyVertex(int tessIdx, float x, float y, float z, int rgba) { setPolyVertex(tessIdx, x, y, z, rgba, 0, 0, 1, 0, 0, 0, 0, 0, 0); } void setPolyVertex(int tessIdx, float x, float y, float z, int rgba, float nx, float ny, float nz, float u, float v, int am, int sp, int em, float shine) { int index; if (renderMode == IMMEDIATE && flushMode == FLUSH_WHEN_FULL && !hints[DISABLE_TRANSFORM_CACHE]) { PMatrix3D mm = modelview; PMatrix3D nm = modelviewInv; index = 4 * tessIdx; polyVertices[index++] = x * mm.m00 + y * mm.m01 + z * mm.m02 + mm.m03; polyVertices[index++] = x * mm.m10 + y * mm.m11 + z * mm.m12 + mm.m13; polyVertices[index++] = x * mm.m20 + y * mm.m21 + z * mm.m22 + mm.m23; polyVertices[index ] = x * mm.m30 + y * mm.m31 + z * mm.m32 + mm.m33; index = 3 * tessIdx; polyNormals[index++] = nx * nm.m00 + ny * nm.m10 + nz * nm.m20; polyNormals[index++] = nx * nm.m01 + ny * nm.m11 + nz * nm.m21; polyNormals[index ] = nx * nm.m02 + ny * nm.m12 + nz * nm.m22; } else { index = 4 * tessIdx; polyVertices[index++] = x; polyVertices[index++] = y; polyVertices[index++] = z; polyVertices[index ] = 1; index = 3 * tessIdx; polyNormals[index++] = nx; polyNormals[index++] = ny; polyNormals[index ] = nz; } polyColors[tessIdx] = rgba; index = 2 * tessIdx; polyTexcoords[index++] = u; polyTexcoords[index ] = v; polyAmbient[tessIdx] = am; polySpecular[tessIdx] = sp; polyEmissive[tessIdx] = em; polyShininess[tessIdx] = shine; } void addPolyVertex(float x, float y, float z, int rgba, float nx, float ny, float nz, float u, float v, int am, int sp, int em, float shine) { polyVertexCheck(); int index; int count = polyVertexCount - 1; if (renderMode == IMMEDIATE && flushMode == FLUSH_WHEN_FULL && !hints[DISABLE_TRANSFORM_CACHE]) { PMatrix3D mm = modelview; PMatrix3D nm = modelviewInv; index = 4 * count; polyVertices[index++] = x * mm.m00 + y * mm.m01 + z * mm.m02 + mm.m03; polyVertices[index++] = x * mm.m10 + y * mm.m11 + z * mm.m12 + mm.m13; polyVertices[index++] = x * mm.m20 + y * mm.m21 + z * mm.m22 + mm.m23; polyVertices[index ] = x * mm.m30 + y * mm.m31 + z * mm.m32 + mm.m33; index = 3 * count; polyNormals[index++] = nx * nm.m00 + ny * nm.m10 + nz * nm.m20; polyNormals[index++] = nx * nm.m01 + ny * nm.m11 + nz * nm.m21; polyNormals[index ] = nx * nm.m02 + ny * nm.m12 + nz * nm.m22; } else { index = 4 * count; polyVertices[index++] = x; polyVertices[index++] = y; polyVertices[index++] = z; polyVertices[index ] = 1; index = 3 * count; polyNormals[index++] = nx; polyNormals[index++] = ny; polyNormals[index ] = nz; } polyColors[count] = rgba; index = 2 * count; polyTexcoords[index++] = u; polyTexcoords[index ] = v; polyAmbient[count] = am; polySpecular[count] = sp; polyEmissive[count] = em; polyShininess[count] = shine; } void addPolyVertices(InGeometry in) { addPolyVertices(in, in.firstVertex, in.lastVertex); } void addPolyVertex(InGeometry in, int i) { addPolyVertices(in, i, i); } void addPolyVertices(InGeometry in, int i0, int i1) { int index; int nvert = i1 - i0 + 1; polyVertexCheck(nvert); if (renderMode == IMMEDIATE && flushMode == FLUSH_WHEN_FULL && !hints[DISABLE_TRANSFORM_CACHE]) { PMatrix3D mm = modelview; PMatrix3D nm = modelviewInv; for (int i = 0; i < nvert; i++) { int inIdx = i0 + i; int tessIdx = firstPolyVertex + i; index = 3 * inIdx; float x = in.vertices[index++]; float y = in.vertices[index++]; float z = in.vertices[index ]; index = 3 * inIdx; float nx = in.normals[index++]; float ny = in.normals[index++]; float nz = in.normals[index ]; index = 4 * tessIdx; polyVertices[index++] = x * mm.m00 + y * mm.m01 + z * mm.m02 + mm.m03; polyVertices[index++] = x * mm.m10 + y * mm.m11 + z * mm.m12 + mm.m13; polyVertices[index++] = x * mm.m20 + y * mm.m21 + z * mm.m22 + mm.m23; polyVertices[index ] = x * mm.m30 + y * mm.m31 + z * mm.m32 + mm.m33; index = 3 * tessIdx; polyNormals[index++] = nx * nm.m00 + ny * nm.m10 + nz * nm.m20; polyNormals[index++] = nx * nm.m01 + ny * nm.m11 + nz * nm.m21; polyNormals[index ] = nx * nm.m02 + ny * nm.m12 + nz * nm.m22; } } else { if (nvert <= PGL.MIN_ARRAYCOPY_SIZE) { // Copying elements one by one instead of using arrayCopy is more efficient for // few vertices... for (int i = 0; i < nvert; i++) { int inIdx = i0 + i; int tessIdx = firstPolyVertex + i; index = 3 * inIdx; float x = in.vertices[index++]; float y = in.vertices[index++]; float z = in.vertices[index ]; index = 3 * inIdx; float nx = in.normals[index++]; float ny = in.normals[index++]; float nz = in.normals[index ]; index = 4 * tessIdx; polyVertices[index++] = x; polyVertices[index++] = y; polyVertices[index++] = z; polyVertices[index ] = 1; index = 3 * tessIdx; polyNormals[index++] = nx; polyNormals[index++] = ny; polyNormals[index ] = nz; } } else { for (int i = 0; i < nvert; i++) { int inIdx = i0 + i; int tessIdx = firstPolyVertex + i; PApplet.arrayCopy(in.vertices, 3 * inIdx, polyVertices, 4 * tessIdx, 3); polyVertices[4 * tessIdx + 3] = 1; } PApplet.arrayCopy(in.normals, 3 * i0, polyNormals, 3 * firstPolyVertex, 3 * nvert); } } if (nvert <= PGL.MIN_ARRAYCOPY_SIZE) { for (int i = 0; i < nvert; i++) { int inIdx = i0 + i; int tessIdx = firstPolyVertex + i; index = 2 * inIdx; float u = in.texcoords[index++]; float v = in.texcoords[index ]; polyColors[tessIdx] = in.colors[inIdx]; index = 2 * tessIdx; polyTexcoords[index++] = u; polyTexcoords[index ] = v; polyAmbient[tessIdx] = in.ambient[inIdx]; polySpecular[tessIdx] = in.specular[inIdx]; polyEmissive[tessIdx] = in.emissive[inIdx]; polyShininess[tessIdx] = in.shininess[inIdx]; } } else { PApplet.arrayCopy(in.colors, i0, polyColors, firstPolyVertex, nvert); PApplet.arrayCopy(in.texcoords, 2 * i0, polyTexcoords, 2 * firstPolyVertex, 2 * nvert); PApplet.arrayCopy(in.ambient, i0, polyAmbient, firstPolyVertex, nvert); PApplet.arrayCopy(in.specular, i0, polySpecular, firstPolyVertex, nvert); PApplet.arrayCopy(in.emissive, i0, polyEmissive, firstPolyVertex, nvert); PApplet.arrayCopy(in.shininess, i0, polyShininess, firstPolyVertex, nvert); } } // ----------------------------------------------------------------- // // Matrix transformations void applyMatrixOnPolyGeometry(PMatrix tr, int first, int last) { if (tr instanceof PMatrix2D) { applyMatrixOnPolyGeometry((PMatrix2D) tr, first, last); } else if (tr instanceof PMatrix3D) { applyMatrixOnPolyGeometry((PMatrix3D) tr, first, last); } } void applyMatrixOnLineGeometry(PMatrix tr, int first, int last) { if (tr instanceof PMatrix2D) { applyMatrixOnLineGeometry((PMatrix2D) tr, first, last); } else if (tr instanceof PMatrix3D) { applyMatrixOnLineGeometry((PMatrix3D) tr, first, last); } } void applyMatrixOnPointGeometry(PMatrix tr, int first, int last) { if (tr instanceof PMatrix2D) { applyMatrixOnPointGeometry((PMatrix2D) tr, first, last); } else if (tr instanceof PMatrix3D) { applyMatrixOnPointGeometry((PMatrix3D) tr, first, last); } } void applyMatrixOnPolyGeometry(PMatrix2D tr, int first, int last) { if (first < last) { int index; for (int i = first; i <= last; i++) { index = 4 * i; float x = polyVertices[index++]; float y = polyVertices[index ]; index = 3 * i; float nx = polyNormals[index++]; float ny = polyNormals[index ]; index = 4 * i; polyVertices[index++] = x * tr.m00 + y * tr.m01 + tr.m02; polyVertices[index ] = x * tr.m10 + y * tr.m11 + tr.m12; index = 3 * i; polyNormals[index++] = nx * tr.m00 + ny * tr.m01; polyNormals[index ] = nx * tr.m10 + ny * tr.m11; } } } void applyMatrixOnLineGeometry(PMatrix2D tr, int first, int last) { if (first < last) { int index; for (int i = first; i <= last; i++) { index = 4 * i; float x = lineVertices[index++]; float y = lineVertices[index ]; index = 4 * i; float xa = lineAttribs[index++]; float ya = lineAttribs[index ]; index = 4 * i; lineVertices[index++] = x * tr.m00 + y * tr.m01 + tr.m02; lineVertices[index ] = x * tr.m10 + y * tr.m11 + tr.m12; index = 4 * i; lineAttribs[index++] = xa * tr.m00 + ya * tr.m01 + tr.m02; lineAttribs[index ] = xa * tr.m10 + ya * tr.m11 + tr.m12; } } } void applyMatrixOnPointGeometry(PMatrix2D tr, int first, int last) { if (first < last) { int index; for (int i = first; i <= last; i++) { index = 4 * i; float x = pointVertices[index++]; float y = pointVertices[index ]; index = 4 * i; pointVertices[index++] = x * tr.m00 + y * tr.m01 + tr.m02; pointVertices[index ] = x * tr.m10 + y * tr.m11 + tr.m12; } } } void applyMatrixOnPolyGeometry(PMatrix3D tr, int first, int last) { if (first < last) { int index; for (int i = first; i <= last; i++) { index = 4 * i; float x = polyVertices[index++]; float y = polyVertices[index++]; float z = polyVertices[index++]; float w = polyVertices[index ]; index = 3 * i; float nx = polyNormals[index++]; float ny = polyNormals[index++]; float nz = polyNormals[index ]; index = 4 * i; polyVertices[index++] = x * tr.m00 + y * tr.m01 + z * tr.m02 + w * tr.m03; polyVertices[index++] = x * tr.m10 + y * tr.m11 + z * tr.m12 + w * tr.m13; polyVertices[index++] = x * tr.m20 + y * tr.m21 + z * tr.m22 + w * tr.m23; polyVertices[index ] = x * tr.m30 + y * tr.m31 + z * tr.m32 + w * tr.m33; index = 3 * i; polyNormals[index++] = nx * tr.m00 + ny * tr.m01 + nz * tr.m02; polyNormals[index++] = nx * tr.m10 + ny * tr.m11 + nz * tr.m12; polyNormals[index ] = nx * tr.m20 + ny * tr.m21 + nz * tr.m22; } } } void applyMatrixOnLineGeometry(PMatrix3D tr, int first, int last) { if (first < last) { int index; for (int i = first; i <= last; i++) { index = 4 * i; float x = lineVertices[index++]; float y = lineVertices[index++]; float z = lineVertices[index++]; float w = lineVertices[index ]; index = 4 * i; float xa = lineAttribs[index++]; float ya = lineAttribs[index++]; float za = lineAttribs[index ]; index = 4 * i; lineVertices[index++] = x * tr.m00 + y * tr.m01 + z * tr.m02 + w * tr.m03; lineVertices[index++] = x * tr.m10 + y * tr.m11 + z * tr.m12 + w * tr.m13; lineVertices[index++] = x * tr.m20 + y * tr.m21 + z * tr.m22 + w * tr.m23; lineVertices[index ] = x * tr.m30 + y * tr.m31 + z * tr.m32 + w * tr.m33; index = 4 * i; lineAttribs[index++] = xa * tr.m00 + ya * tr.m01 + za * tr.m02 + tr.m03; lineAttribs[index++] = xa * tr.m10 + ya * tr.m11 + za * tr.m12 + tr.m13; lineAttribs[index ] = xa * tr.m20 + ya * tr.m21 + za * tr.m22 + tr.m23; } } } void applyMatrixOnPointGeometry(PMatrix3D tr, int first, int last) { if (first < last) { int index; for (int i = first; i <= last; i++) { index = 4 * i; float x = pointVertices[index++]; float y = pointVertices[index++]; float z = pointVertices[index++]; float w = pointVertices[index ]; index = 4 * i; pointVertices[index++] = x * tr.m00 + y * tr.m01 + z * tr.m02 + w * tr.m03; pointVertices[index++] = x * tr.m10 + y * tr.m11 + z * tr.m12 + w * tr.m13; pointVertices[index++] = x * tr.m20 + y * tr.m21 + z * tr.m22 + w * tr.m23; pointVertices[index ] = x * tr.m30 + y * tr.m31 + z * tr.m32 + w * tr.m33; } } } } // Generates tessellated geometry given a batch of input vertices. protected class Tessellator { InGeometry in; TessGeometry tess; TexCache texCache; PImage prevTexImage; PImage newTexImage; int firstTexIndex; int firstTexCache; PGL.Tessellator gluTess; TessellatorCallback callback; boolean fill; boolean stroke; int strokeColor; float strokeWeight; int strokeJoin; int strokeCap; boolean accurate2DStrokes; PMatrix transform; boolean is2D, is3D; int[] rawIndices; int rawSize; int firstPolyIndexCache; int lastPolyIndexCache; int firstLineIndexCache; int lastLineIndexCache; int firstPointIndexCache; int lastPointIndexCache; Tessellator() { callback = new TessellatorCallback(); gluTess = pgl.createTessellator(callback); rawIndices = new int[512]; accurate2DStrokes = true; transform = null; is2D = false; is3D = true; } void setInGeometry(InGeometry in) { this.in = in; firstPolyIndexCache = -1; lastPolyIndexCache = -1; firstLineIndexCache = -1; lastLineIndexCache = -1; firstPointIndexCache = -1; lastPointIndexCache = -1; } void setTessGeometry(TessGeometry tess) { this.tess = tess; } void setFill(boolean fill) { this.fill = fill; } void setStroke(boolean stroke) { this.stroke = stroke; } void setStrokeColor(int color) { this.strokeColor = PGL.javaToNativeARGB(color); } void setStrokeWeight(float weight) { this.strokeWeight = weight; } void setStrokeJoin(int strokeJoin) { this.strokeJoin = strokeJoin; } void setStrokeCap(int strokeCap) { this.strokeCap = strokeCap; } void setAccurate2DStrokes(boolean accurate) { this.accurate2DStrokes = accurate; } void setTexCache(TexCache texCache, PImage prevTexImage, PImage newTexImage) { this.texCache = texCache; this.prevTexImage = prevTexImage; this.newTexImage = newTexImage; } void set3D(boolean value) { if (value) { this.is2D = false; this.is3D = true; } else { this.is2D = true; this.is3D = false; } } void setTransform(PMatrix transform) { this.transform = transform; } // ----------------------------------------------------------------- // // Point tessellation void tessellatePoints() { if (strokeCap == ROUND) { tessellateRoundPoints(); } else { tessellateSquarePoints(); } } void tessellateRoundPoints() { int nInVert = in.lastVertex - in.firstVertex + 1; if (stroke && 1 <= nInVert) { // Each point generates a separate triangle fan. // The number of triangles of each fan depends on the // stroke weight of the point. int nPtVert = PApplet.max(MIN_POINT_ACCURACY, (int) (TWO_PI * strokeWeight / POINT_ACCURACY_FACTOR)) + 1; if (PGL.MAX_VERTEX_INDEX1 <= nPtVert) { throw new RuntimeException("P3D: error in point tessellation."); } updateTex(); int nvertTot = nPtVert * nInVert; int nindTot = 3 * (nPtVert - 1) * nInVert; if (is3D) { tessellateRoundPoints3D(nvertTot, nindTot, nPtVert); } else if (is2D) { beginNoTex(); tessellateRoundPoints2D(nvertTot, nindTot, nPtVert); endNoTex(); } } } void tessellateRoundPoints3D(int nvertTot, int nindTot, int nPtVert) { int perim = nPtVert - 1; tess.pointVertexCheck(nvertTot); tess.pointIndexCheck(nindTot); int vertIdx = tess.firstPointVertex; int attribIdx = tess.firstPointVertex; int indIdx = tess.firstPointIndex; IndexCache cache = tess.pointIndexCache; int index = in.renderMode == RETAINED ? cache.addNew() : cache.getLast(); firstPointIndexCache = index; for (int i = in.firstVertex; i <= in.lastVertex; i++) { // Creating the triangle fan for each input vertex. int count = cache.vertexCount[index]; if (PGL.MAX_VERTEX_INDEX1 <= count + nPtVert) { // We need to start a new index block for this point. index = cache.addNew(); count = 0; } // All the tessellated vertices are identical to the center point for (int k = 0; k < nPtVert; k++) { tess.setPointVertex(vertIdx, in, i); vertIdx++; } // The attributes for each tessellated vertex are the displacement along // the circle perimeter. The point shader will read these attributes and // displace the vertices in screen coordinates so the circles are always // camera facing (bilboards) tess.pointAttribs[2 * attribIdx + 0] = 0; tess.pointAttribs[2 * attribIdx + 1] = 0; attribIdx++; float val = 0; float inc = (float) SINCOS_LENGTH / perim; for (int k = 0; k < perim; k++) { tess.pointAttribs[2 * attribIdx + 0] = 0.5f * cosLUT[(int) val] * strokeWeight; tess.pointAttribs[2 * attribIdx + 1] = 0.5f * sinLUT[(int) val] * strokeWeight; val = (val + inc) % SINCOS_LENGTH; attribIdx++; } // Adding vert0 to take into account the triangles of all // the preceding points. for (int k = 1; k < nPtVert - 1; k++) { tess.pointIndices[indIdx++] = (short) (count + 0); tess.pointIndices[indIdx++] = (short) (count + k); tess.pointIndices[indIdx++] = (short) (count + k + 1); } // Final triangle between the last and first point: tess.pointIndices[indIdx++] = (short) (count + 0); tess.pointIndices[indIdx++] = (short) (count + 1); tess.pointIndices[indIdx++] = (short) (count + nPtVert - 1); cache.incCounts(index, 3 * (nPtVert - 1), nPtVert); } lastPointIndexCache = index; } void tessellateRoundPoints2D(int nvertTot, int nindTot, int nPtVert) { int perim = nPtVert - 1; tess.polyVertexCheck(nvertTot); tess.polyIndexCheck(nindTot); int vertIdx = tess.firstPolyVertex; int indIdx = tess.firstPolyIndex; IndexCache cache = tess.polyIndexCache; int index = in.renderMode == RETAINED ? cache.addNew() : cache.getLast(); firstPointIndexCache = index; for (int i = in.firstVertex; i <= in.lastVertex; i++) { int count = cache.vertexCount[index]; if (PGL.MAX_VERTEX_INDEX1 <= count + nPtVert) { // We need to start a new index block for this point. index = cache.addNew(); count = 0; } float x0 = in.vertices[3 * i + 0]; float y0 = in.vertices[3 * i + 1]; int rgba = in.strokeColors[i]; float val = 0; float inc = (float) SINCOS_LENGTH / perim; tess.setPolyVertex(vertIdx, x0, y0, 0, rgba); vertIdx++; for (int k = 0; k < perim; k++) { tess.setPolyVertex(vertIdx, x0 + 0.5f * cosLUT[(int) val] * strokeWeight, y0 + 0.5f * sinLUT[(int) val] * strokeWeight, 0, rgba); vertIdx++; val = (val + inc) % SINCOS_LENGTH; } // Adding vert0 to take into account the triangles of all // the preceding points. for (int k = 1; k < nPtVert - 1; k++) { tess.polyIndices[indIdx++] = (short) (count + 0); tess.polyIndices[indIdx++] = (short) (count + k); tess.polyIndices[indIdx++] = (short) (count + k + 1); } // Final triangle between the last and first point: tess.polyIndices[indIdx++] = (short) (count + 0); tess.polyIndices[indIdx++] = (short) (count + 1); tess.polyIndices[indIdx++] = (short) (count + nPtVert - 1); cache.incCounts(index, 3 * (nPtVert - 1), nPtVert); } lastPointIndexCache = lastPolyIndexCache = index; } void tessellateSquarePoints() { int nInVert = in.lastVertex - in.firstVertex + 1; if (stroke && 1 <= nInVert) { updateTex(); int quadCount = nInVert; // Each point generates a separate quad. // Each quad is formed by 5 vertices, the center one // is the input vertex, and the other 4 define the // corners (so, a triangle fan again). int nvertTot = 5 * quadCount; // So the quad is formed by 4 triangles, each requires // 3 indices. int nindTot = 12 * quadCount; if (is3D) { tessellateSquarePoints3D(nvertTot, nindTot); } else if (is2D) { beginNoTex(); tessellateSquarePoints2D(nvertTot, nindTot); endNoTex(); } } } void tessellateSquarePoints3D(int nvertTot, int nindTot) { tess.pointVertexCheck(nvertTot); tess.pointIndexCheck(nindTot); int vertIdx = tess.firstPointVertex; int attribIdx = tess.firstPointVertex; int indIdx = tess.firstPointIndex; IndexCache cache = tess.pointIndexCache; int index = in.renderMode == RETAINED ? cache.addNew() : cache.getLast(); firstPointIndexCache = index; for (int i = in.firstVertex; i <= in.lastVertex; i++) { int nvert = 5; int count = cache.vertexCount[index]; if (PGL.MAX_VERTEX_INDEX1 <= count + nvert) { // We need to start a new index block for this point. index = cache.addNew(); count = 0; } for (int k = 0; k < nvert; k++) { tess.setPointVertex(vertIdx, in, i); vertIdx++; } // The attributes for each tessellated vertex are the displacement along // the quad corners. The point shader will read these attributes and // displace the vertices in screen coordinates so the quads are always // camera facing (bilboards) tess.pointAttribs[2 * attribIdx + 0] = 0; tess.pointAttribs[2 * attribIdx + 1] = 0; attribIdx++; for (int k = 0; k < 4; k++) { tess.pointAttribs[2 * attribIdx + 0] = 0.5f * QUAD_POINT_SIGNS[k][0] * strokeWeight; tess.pointAttribs[2 * attribIdx + 1] = 0.5f * QUAD_POINT_SIGNS[k][1] * strokeWeight; attribIdx++; } // Adding firstVert to take into account the triangles of all // the preceding points. for (int k = 1; k < nvert - 1; k++) { tess.pointIndices[indIdx++] = (short) (count + 0); tess.pointIndices[indIdx++] = (short) (count + k); tess.pointIndices[indIdx++] = (short) (count + k + 1); } // Final triangle between the last and first point: tess.pointIndices[indIdx++] = (short) (count + 0); tess.pointIndices[indIdx++] = (short) (count + 1); tess.pointIndices[indIdx++] = (short) (count + nvert - 1); cache.incCounts(index, 12, 5); } lastPointIndexCache = index; } void tessellateSquarePoints2D(int nvertTot, int nindTot) { tess.polyVertexCheck(nvertTot); tess.polyIndexCheck(nindTot); int vertIdx = tess.firstPolyVertex; int indIdx = tess.firstPolyIndex; IndexCache cache = tess.polyIndexCache; int index = in.renderMode == RETAINED ? cache.addNew() : cache.getLast(); firstPointIndexCache = index; for (int i = in.firstVertex; i <= in.lastVertex; i++) { int nvert = 5; int count = cache.vertexCount[index]; if (PGL.MAX_VERTEX_INDEX1 <= count + nvert) { // We need to start a new index block for this point. index = cache.addNew(); count = 0; } float x0 = in.vertices[3 * i + 0]; float y0 = in.vertices[3 * i + 1]; int rgba = in.strokeColors[i]; tess.setPolyVertex(vertIdx, x0, y0, 0, rgba); vertIdx++; for (int k = 0; k < nvert - 1; k++) { tess.setPolyVertex(vertIdx, x0 + 0.5f * QUAD_POINT_SIGNS[k][0] * strokeWeight, y0 + 0.5f * QUAD_POINT_SIGNS[k][1] * strokeWeight, 0, rgba); vertIdx++; } for (int k = 1; k < nvert - 1; k++) { tess.polyIndices[indIdx++] = (short) (count + 0); tess.polyIndices[indIdx++] = (short) (count + k); tess.polyIndices[indIdx++] = (short) (count + k + 1); } // Final triangle between the last and first point: tess.polyIndices[indIdx++] = (short) (count + 0); tess.polyIndices[indIdx++] = (short) (count + 1); tess.polyIndices[indIdx++] = (short) (count + nvert - 1); cache.incCounts(index, 12, 5); } lastPointIndexCache = lastPolyIndexCache = index; } // ----------------------------------------------------------------- // // Line tessellation void tessellateLines() { int nInVert = in.lastVertex - in.firstVertex + 1; if (stroke && 2 <= nInVert) { updateTex(); int lineCount = nInVert / 2; // Each individual line is formed by two consecutive input vertices. if (is3D) { tessellateLines3D(lineCount); } else if (is2D) { beginNoTex(); // Line geometry in 2D are stored in the poly array next to the fill triangles, but w/out textures. tessellateLines2D(lineCount); endNoTex(); } } } void tessellateLines3D(int lineCount) { // Lines are made up of 4 vertices defining the quad. int nvert = lineCount * 4; // Each stroke line has 4 vertices, defining 2 triangles, which // require 3 indices to specify their connectivities. int nind = lineCount * 2 * 3; int first = in.firstVertex; tess.lineVertexCheck(nvert); tess.lineIndexCheck(nind); int index = in.renderMode == RETAINED ? tess.lineIndexCache.addNew() : tess.lineIndexCache.getLast(); firstLineIndexCache = index; for (int ln = 0; ln < lineCount; ln++) { int i0 = first + 2 * ln + 0; int i1 = first + 2 * ln + 1; index = addLine3D(i0, i1, index, null, false); } lastLineIndexCache = index; } void tessellateLines2D(int lineCount) { int nvert = lineCount * 4; int nind = lineCount * 2 * 3; int first = in.firstVertex; if (noCapsJoins(nvert)) { tess.polyVertexCheck(nvert); tess.polyIndexCheck(nind); int index = in.renderMode == RETAINED ? tess.polyIndexCache.addNew() : tess.polyIndexCache.getLast(); firstLineIndexCache = index; if (firstPolyIndexCache == -1) firstPolyIndexCache = index; // If the geometry has no fill, needs the first poly index. for (int ln = 0; ln < lineCount; ln++) { int i0 = first + 2 * ln + 0; int i1 = first + 2 * ln + 1; index = addLine2D(i0, i1, index, false); } lastLineIndexCache = lastPolyIndexCache = index; } else { // full stroking algorithm LinePath path = new LinePath(LinePath.WIND_NON_ZERO); for (int ln = 0; ln < lineCount; ln++) { int i0 = first + 2 * ln + 0; int i1 = first + 2 * ln + 1; path.moveTo(in.vertices[3 * i0 + 0], in.vertices[3 * i0 + 1]); path.lineTo(in.vertices[3 * i1 + 0], in.vertices[3 * i1 + 1]); } tessellateLinePath(path); } } void tessellateLineStrip() { int nInVert = in.lastVertex - in.firstVertex + 1; if (stroke && 2 <= nInVert) { updateTex(); int lineCount = nInVert - 1; if (is3D) { tessellateLineStrip3D(lineCount); } else if (is2D) { beginNoTex(); tessellateLineStrip2D(lineCount); endNoTex(); } } } void tessellateLineStrip3D(int lineCount) { int nvert = lineCount * 4 + (lineCount - 1); // (lineCount - 1) for the bevel triangles int nind = lineCount * 2 * 3 + (lineCount - 1) * 2 * 3; // same thing tess.lineVertexCheck(nvert); tess.lineIndexCheck(nind); int index = in.renderMode == RETAINED ? tess.lineIndexCache.addNew() : tess.lineIndexCache.getLast(); firstLineIndexCache = index; int i0 = in.firstVertex; short[] lastInd = {-1, -1}; for (int ln = 0; ln < lineCount; ln++) { int i1 = in.firstVertex + ln + 1; index = addLine3D(i0, i1, index, lastInd, false); i0 = i1; } lastLineIndexCache = index; } void tessellateLineStrip2D(int lineCount) { int nvert = lineCount * 4; int nind = lineCount * 2 * 3; if (noCapsJoins(nvert)) { tess.polyVertexCheck(nvert); tess.polyIndexCheck(nind); int index = in.renderMode == RETAINED ? tess.polyIndexCache.addNew() : tess.polyIndexCache.getLast(); firstLineIndexCache = index; if (firstPolyIndexCache == -1) firstPolyIndexCache = index; // If the geometry has no fill, needs the first poly index. int i0 = in.firstVertex; for (int ln = 0; ln < lineCount; ln++) { int i1 = in.firstVertex + ln + 1; index = addLine2D(i0, i1, index, false); i0 = i1; } lastLineIndexCache = lastPolyIndexCache = index; } else { // full stroking algorithm int first = in.firstVertex; LinePath path = new LinePath(LinePath.WIND_NON_ZERO); path.moveTo(in.vertices[3 * first + 0], in.vertices[3 * first + 1]); for (int ln = 0; ln < lineCount; ln++) { int i1 = first + ln + 1; path.lineTo(in.vertices[3 * i1 + 0], in.vertices[3 * i1 + 1]); } tessellateLinePath(path); } } void tessellateLineLoop() { int nInVert = in.lastVertex - in.firstVertex + 1; if (stroke && 2 <= nInVert) { updateTex(); int lineCount = nInVert; if (is3D) { tessellateLineLoop3D(lineCount); } else if (is2D) { beginNoTex(); tessellateLineLoop2D(lineCount); endNoTex(); } } } void tessellateLineLoop3D(int lineCount) { // This calculation doesn't add the bevel join between // the first and last vertex, need to fix. int nvert = lineCount * 4 + (lineCount - 1); int nind = lineCount * 2 * 3 + (lineCount - 1) * 2 * 3; tess.lineVertexCheck(nvert); tess.lineIndexCheck(nind); int index = in.renderMode == RETAINED ? tess.lineIndexCache.addNew() : tess.lineIndexCache.getLast(); firstLineIndexCache = index; int i0 = in.firstVertex; short[] lastInd = {-1, -1}; for (int ln = 0; ln < lineCount - 1; ln++) { int i1 = in.firstVertex + ln + 1; index = addLine3D(i0, i1, index, lastInd, false); i0 = i1; } index = addLine3D(in.lastVertex, in.firstVertex, index, lastInd, false); lastLineIndexCache = index; } void tessellateLineLoop2D(int lineCount) { int nvert = lineCount * 4; int nind = lineCount * 2 * 3; if (noCapsJoins(nvert)) { tess.polyVertexCheck(nvert); tess.polyIndexCheck(nind); int index = in.renderMode == RETAINED ? tess.polyIndexCache.addNew() : tess.polyIndexCache.getLast(); firstLineIndexCache = index; if (firstPolyIndexCache == -1) firstPolyIndexCache = index; // If the geometry has no fill, needs the first poly index. int i0 = in.firstVertex; for (int ln = 0; ln < lineCount - 1; ln++) { int i1 = in.firstVertex + ln + 1; index = addLine2D(i0, i1, index, false); i0 = i1; } index = addLine2D(in.lastVertex, in.firstVertex, index, false); lastLineIndexCache = lastPolyIndexCache = index; } else { // full stroking algorithm int first = in.firstVertex; LinePath path = new LinePath(LinePath.WIND_NON_ZERO); path.moveTo(in.vertices[3 * first + 0], in.vertices[3 * first + 1]); for (int ln = 0; ln < lineCount - 1; ln++) { int i1 = first + ln + 1; path.lineTo(in.vertices[3 * i1 + 0], in.vertices[3 * i1 + 1]); } path.closePath(); tessellateLinePath(path); } } void tessellateEdges() { if (stroke) { if (is3D) { tessellateEdges3D(); } else if (is2D) { beginNoTex(); tessellateEdges2D(); endNoTex(); } } } void tessellateEdges3D() { // This calculation doesn't add the bevel join between // the first and last vertex, need to fix. int nInVert = in.getNumEdgeVertices(true); int nInInd = in.getNumEdgeIndices(true); tess.lineVertexCheck(nInVert); tess.lineIndexCheck(nInInd); int index = in.renderMode == RETAINED ? tess.lineIndexCache.addNew() : tess.lineIndexCache.getLast(); firstLineIndexCache = index; short[] lastInd = {-1, -1}; for (int i = in.firstEdge; i <= in.lastEdge; i++) { int[] edge = in.edges[i]; int i0 = edge[0]; int i1 = edge[1]; index = addLine3D(i0, i1, index, lastInd, true); if (edge[2] == EDGE_STOP || edge[2] == EDGE_SINGLE) { // No join with next line segment. lastInd[0] = lastInd[1] = -1; } } lastLineIndexCache = index; } void tessellateEdges2D() { int nInVert = in.getNumEdgeVertices(false); if (noCapsJoins(nInVert)) { int nInInd = in.getNumEdgeIndices(false); tess.polyVertexCheck(nInVert); tess.polyIndexCheck(nInInd); int index = in.renderMode == RETAINED ? tess.polyIndexCache.addNew() : tess.polyIndexCache.getLast(); firstLineIndexCache = index; if (firstPolyIndexCache == -1) firstPolyIndexCache = index; // If the geometry has no fill, needs the first poly index. for (int i = in.firstEdge; i <= in.lastEdge; i++) { int[] edge = in.edges[i]; int i0 = edge[0]; int i1 = edge[1]; index = addLine2D(i0, i1, index, true); } lastLineIndexCache = lastPolyIndexCache = index; } else { // full stroking algorithm LinePath path = new LinePath(LinePath.WIND_NON_ZERO); for (int i = in.firstEdge; i <= in.lastEdge; i++) { int[] edge = in.edges[i]; int i0 = edge[0]; int i1 = edge[1]; switch (edge[2]) { case EDGE_MIDDLE: path.lineTo(in.vertices[3 * i1 + 0], in.vertices[3 * i1 + 1]); break; case EDGE_START: path.moveTo(in.vertices[3 * i0 + 0], in.vertices[3 * i0 + 1]); path.lineTo(in.vertices[3 * i1 + 0], in.vertices[3 * i1 + 1]); break; case EDGE_STOP: path.lineTo(in.vertices[3 * i1 + 0], in.vertices[3 * i1 + 1]); path.closePath(); break; case EDGE_SINGLE: path.moveTo(in.vertices[3 * i0 + 0], in.vertices[3 * i0 + 1]); path.lineTo(in.vertices[3 * i1 + 0], in.vertices[3 * i1 + 1]); path.closePath(); break; } } tessellateLinePath(path); } } // Adding the data that defines a quad starting at vertex i0 and // ending at i1. int addLine3D(int i0, int i1, int index, short[] lastInd, boolean constStroke) { IndexCache cache = tess.lineIndexCache; int count = cache.vertexCount[index]; boolean addBevel = lastInd != null && -1 < lastInd[0] && -1 < lastInd[1]; if (PGL.MAX_VERTEX_INDEX1 <= count + 4 + (addBevel ? 1 : 0)) { // We need to start a new index block for this line. index = cache.addNew(); count = 0; } int iidx = cache.indexOffset[index] + cache.indexCount[index]; int vidx = cache.vertexOffset[index] + cache.vertexCount[index]; int color, color0; float weight; color0 = color = constStroke ? strokeColor : in.strokeColors[i0]; weight = constStroke ? strokeWeight : in.strokeWeights[i0]; tess.setLineVertex(vidx++, in, i0, i1, color, +weight/2); tess.lineIndices[iidx++] = (short) (count + 0); tess.setLineVertex(vidx++, in, i0, i1, color, -weight/2); tess.lineIndices[iidx++] = (short) (count + 1); color = constStroke ? strokeColor : in.strokeColors[i1]; weight = constStroke ? strokeWeight : in.strokeWeights[i1]; tess.setLineVertex(vidx++, in, i1, i0, color, -weight/2); tess.lineIndices[iidx++] = (short) (count + 2); // Starting a new triangle re-using prev vertices. tess.lineIndices[iidx++] = (short) (count + 2); tess.lineIndices[iidx++] = (short) (count + 1); tess.setLineVertex(vidx++, in, i1, i0, color, +weight/2); tess.lineIndices[iidx++] = (short) (count + 3); cache.incCounts(index, 6, 4); if (lastInd != null) { if (-1 < lastInd[0] && -1 < lastInd[1]) { // Adding bevel triangles tess.setLineVertex(vidx, in, i0, color0); tess.lineIndices[iidx++] = (short) (count + 4); tess.lineIndices[iidx++] = lastInd[0]; tess.lineIndices[iidx++] = (short) (count + 0); tess.lineIndices[iidx++] = (short) (count + 4); tess.lineIndices[iidx++] = lastInd[1]; tess.lineIndices[iidx ] = (short) (count + 1); cache.incCounts(index, 6, 1); } // Vertices for next bevel lastInd[0] = (short) (count + 2); lastInd[1] = (short) (count + 3); } return index; } // Adding the data that defines a quad starting at vertex i0 and // ending at i1, in the case of pure 2D renderers (line geometry // is added to the poly arrays). int addLine2D(int i0, int i1, int index, boolean constStroke) { IndexCache cache = tess.polyIndexCache; int count = cache.vertexCount[index]; if (PGL.MAX_VERTEX_INDEX1 <= count + 4) { // We need to start a new index block for this line. index = cache.addNew(); count = 0; } int iidx = cache.indexOffset[index] + cache.indexCount[index]; int vidx = cache.vertexOffset[index] + cache.vertexCount[index]; int color = constStroke ? strokeColor : in.strokeColors[i0]; float weight = constStroke ? strokeWeight : in.strokeWeights[i0]; float x0 = in.vertices[3 * i0 + 0]; float y0 = in.vertices[3 * i0 + 1]; float x1 = in.vertices[3 * i1 + 0]; float y1 = in.vertices[3 * i1 + 1]; // Calculating direction and normal of the line. float dirx = x1 - x0; float diry = y1 - y0; float llen = PApplet.sqrt(dirx * dirx + diry * diry); float normx = 0, normy = 0; if (nonZero(llen)) { normx = -diry / llen; normy = +dirx / llen; } tess.setPolyVertex(vidx++, x0 + normx * weight/2, y0 + normy * weight/2, 0, color); tess.polyIndices[iidx++] = (short) (count + 0); tess.setPolyVertex(vidx++, x0 - normx * weight/2, y0 - normy * weight/2, 0, color); tess.polyIndices[iidx++] = (short) (count + 1); if (!constStroke) { color = in.strokeColors[i1]; weight = in.strokeWeights[i1]; } tess.setPolyVertex(vidx++, x1 - normx * weight/2, y1 - normy * weight/2, 0, color); tess.polyIndices[iidx++] = (short) (count + 2); // Starting a new triangle re-using prev vertices. tess.polyIndices[iidx++] = (short) (count + 2); tess.polyIndices[iidx++] = (short) (count + 0); tess.setPolyVertex(vidx++, x1 + normx * weight/2, y1 + normy * weight/2, 0, color); tess.polyIndices[iidx++] = (short) (count + 3); cache.incCounts(index, 6, 4); return index; } boolean noCapsJoins(int nInVert) { if (!accurate2DStrokes) { return true; } else if (PGL.MAX_CAPS_JOINS_LENGTH <= nInVert) { // The line path is too long, so it could make the GLU tess // to run out of memory, so full caps and joins are disabled. return true; } else { // We first calculate the (volumetric) scaling factor that is associated // to the current transformation matrix, which is given by the absolute // value of its determinant: float scaleFactor = 1; if (transform != null) { if (transform instanceof PMatrix2D) { PMatrix2D tr = (PMatrix2D)transform; float areaScaleFactor = Math.abs(tr.m00 * tr.m11 - tr.m01 * tr.m10); scaleFactor = (float) Math.sqrt(areaScaleFactor); } else if (transform instanceof PMatrix3D) { PMatrix3D tr = (PMatrix3D)transform; float volumeScaleFactor = Math.abs(tr.m00 * (tr.m11 * tr.m22 - tr.m12 * tr.m21) + tr.m01 * (tr.m12 * tr.m20 - tr.m10 * tr.m22) + tr.m02 * (tr.m10 * tr.m21 - tr.m11 * tr.m20)); scaleFactor = (float) Math.pow(volumeScaleFactor, 1.0f / 3.0f); } } // The stroke weight is scaled so it correspons to the current // "zoom level" being applied on the geometry due to scaling: return scaleFactor * strokeWeight < PGL.MIN_CAPS_JOINS_WEIGHT; } } // ----------------------------------------------------------------- // // Polygon primitives tessellation void tessellateTriangles() { beginTex(); int nInVert = in.lastVertex - in.firstVertex + 1; if (fill && 3 <= nInVert) { int nInInd = nInVert; setRawSize(nInInd); int idx = 0; for (int i = in.firstVertex; i <= in.lastVertex; i++) { rawIndices[idx++] = i; } partitionRawIndices(); } endTex(); tessellateEdges(); } void tessellateTriangles(int[] indices) { beginTex(); int nInVert = in.lastVertex - in.firstVertex + 1; if (fill && 3 <= nInVert) { int nInInd = indices.length; setRawSize(nInInd); PApplet.arrayCopy(indices, rawIndices, nInInd); partitionRawIndices(); } endTex(); tessellateEdges(); } void tessellateTriangleFan() { beginTex(); int nInVert = in.lastVertex - in.firstVertex + 1; if (fill && 3 <= nInVert) { int nInInd = 3 * (nInVert - 2); setRawSize(nInInd); int idx = 0; for (int i = in.firstVertex + 1; i < in.lastVertex; i++) { rawIndices[idx++] = in.firstVertex; rawIndices[idx++] = i; rawIndices[idx++] = i + 1; } partitionRawIndices(); } endTex(); tessellateEdges(); } void tessellateTriangleStrip() { beginTex(); int nInVert = in.lastVertex - in.firstVertex + 1; if (fill && 3 <= nInVert) { int nInInd = 3 * (nInVert - 2); setRawSize(nInInd); int idx = 0; for (int i = in.firstVertex + 1; i < in.lastVertex; i++) { rawIndices[idx++] = i; if (i % 2 == 0) { rawIndices[idx++] = i - 1; rawIndices[idx++] = i + 1; } else { rawIndices[idx++] = i + 1; rawIndices[idx++] = i - 1; } } partitionRawIndices(); } endTex(); tessellateEdges(); } void tessellateQuads() { beginTex(); int nInVert = in.lastVertex - in.firstVertex + 1; if (fill && 4 <= nInVert) { int quadCount = nInVert / 4; int nInInd = 6 * quadCount; setRawSize(nInInd); int idx = 0; for (int qd = 0; qd < quadCount; qd++) { int i0 = in.firstVertex + 4 * qd + 0; int i1 = in.firstVertex + 4 * qd + 1; int i2 = in.firstVertex + 4 * qd + 2; int i3 = in.firstVertex + 4 * qd + 3; rawIndices[idx++] = i0; rawIndices[idx++] = i1; rawIndices[idx++] = i3; rawIndices[idx++] = i1; rawIndices[idx++] = i2; rawIndices[idx++] = i3; } partitionRawIndices(); } endTex(); tessellateEdges(); } void tessellateQuadStrip() { beginTex(); int nInVert = in.lastVertex - in.firstVertex + 1; if (fill && 4 <= nInVert) { int quadCount = nInVert / 2 - 1; int nInInd = 6 * quadCount; setRawSize(nInInd); int idx = 0; for (int qd = 1; qd < nInVert / 2; qd++) { int i0 = in.firstVertex + 2 * (qd - 1); int i1 = in.firstVertex + 2 * (qd - 1) + 1; int i2 = in.firstVertex + 2 * qd + 1; int i3 = in.firstVertex + 2 * qd; rawIndices[idx++] = i0; rawIndices[idx++] = i1; rawIndices[idx++] = i3; rawIndices[idx++] = i1; rawIndices[idx++] = i2; rawIndices[idx++] = i3; } partitionRawIndices(); } endTex(); tessellateEdges(); } // Uses the raw indices to partition the geometry into contiguous // index groups when the vertex indices become too large. The basic // idea of this algorithm is to scan through the array of raw indices // in groups of three vertices at the time (since we are always dealing // with triangles) and create a new offset in the index cache once the // index values go above the MAX_VERTEX_INDEX constant. The tricky part // is that triangles in the new group might refer to vertices in a // previous group. Since the index groups are by definition disjoint, // these vertices need to be duplicated at the end of the corresponding // region in the vertex array. void partitionRawIndices() { tess.polyIndexCheck(rawSize); int offset = tess.firstPolyIndex; int inInd0 = 0, inInd1 = 0; int inMaxVert0 = in.firstVertex, inMaxVert1 = in.firstVertex; int inMaxRel = 0; Set<Integer> inDupSet = null; IndexCache cache = tess.polyIndexCache; // In retained mode, each shape has with its own cache item, since // they should always be available to be rendererd individually, even // if contained in a larger hierarchy. int index = in.renderMode == RETAINED ? cache.addNew() : cache.getLast(); firstPolyIndexCache = index; int trCount = rawSize / 3; for (int tr = 0; tr < trCount; tr++) { if (index == -1) index = cache.addNew(); int i0 = rawIndices[3 * tr + 0]; int i1 = rawIndices[3 * tr + 1]; int i2 = rawIndices[3 * tr + 2]; // Vertex indices relative to the last copy position. int ii0 = i0 - inMaxVert0; int ii1 = i1 - inMaxVert0; int ii2 = i2 - inMaxVert0; // Vertex indices relative to the current group. int count = cache.vertexCount[index]; int ri0, ri1, ri2; if (ii0 < 0) { if (inDupSet == null) inDupSet = new HashSet<Integer>(); inDupSet.add(ii0); ri0 = ii0; } else ri0 = count + ii0; if (ii1 < 0) { if (inDupSet == null) inDupSet = new HashSet<Integer>(); inDupSet.add(ii1); ri1 = ii1; } else ri1 = count + ii1; if (ii2 < 0) { if (inDupSet == null) inDupSet = new HashSet<Integer>(); inDupSet.add(ii2); ri2 = ii2; } else ri2 = count + ii2; tess.polyIndices[offset + 3 * tr + 0] = (short) ri0; tess.polyIndices[offset + 3 * tr + 1] = (short) ri1; tess.polyIndices[offset + 3 * tr + 2] = (short) ri2; inInd1 = 3 * tr + 2; inMaxVert1 = PApplet.max(i0, i1, i2); inMaxRel = PApplet.max(inMaxRel, PApplet.max(ri0, ri1, ri2)); int dup = inDupSet == null ? 0 : inDupSet.size(); if ((PGL.MAX_VERTEX_INDEX1 - 3 <= inMaxRel + dup && inMaxRel + dup < PGL.MAX_VERTEX_INDEX1) || (tr == trCount - 1)) { // The vertex indices of the current group are about to // surpass the MAX_VERTEX_INDEX limit, or we are at the last triangle // so we need to wrap-up things anyways. // So, copy vertices in current region first tess.addPolyVertices(in, inMaxVert0, inMaxVert1); if (0 < dup) { // Adjusting the negative indices so they correspond to vertices added // at the end of the block. ArrayList<Integer> inDupList = new ArrayList<Integer>(inDupSet); Collections.sort(inDupList); for (int i = inInd0; i <= inInd1; i++) { int ri = tess.polyIndices[i]; if (ri < 0) { tess.polyIndices[i] = (short) (inMaxRel + 1 + inDupList.indexOf(ri)); } } // Copy duplicated vertices from previous regions last for (int i = 0; i < inDupList.size(); i++) { int ri = inDupList.get(i); tess.addPolyVertex(in, ri + inMaxVert0); } } // Increment counts: cache.incCounts(index, inInd1 - inInd0 + 1, inMaxVert1 - inMaxVert0 + 1 + dup); lastPolyIndexCache = index; index = -1; inMaxRel = 0; inMaxVert0 = inMaxVert1 + 1; inInd0 = inInd1 + 1; if (inDupSet != null) inDupSet.clear(); } } } void setRawSize(int size) { int size0 = rawIndices.length; if (size0 < size) { int size1 = expandArraySize(size0, size); expandRawIndices(size1); } rawSize = size; } void expandRawIndices(int n) { int temp[] = new int[n]; PApplet.arrayCopy(rawIndices, 0, temp, 0, rawSize); rawIndices = temp; } void beginTex() { setFirstTexIndex(tess.polyIndexCount, tess.polyIndexCache.size - 1); } void endTex() { setLastTexIndex(tess.lastPolyIndex, tess.polyIndexCache.size - 1); } void beginNoTex() { prevTexImage = newTexImage; newTexImage = null; setFirstTexIndex(tess.polyIndexCount, tess.polyIndexCache.size - 1); } void endNoTex() { setLastTexIndex(tess.lastPolyIndex, tess.polyIndexCache.size - 1); } void updateTex() { beginTex(); endTex(); } void setFirstTexIndex(int firstIndex, int firstCache) { if (texCache != null) { firstTexIndex = firstIndex; firstTexCache = PApplet.max(0, firstCache); } } void setLastTexIndex(int lastIndex, int lastCache) { if (texCache != null) { if (prevTexImage != newTexImage || texCache.size == 0) { texCache.addTexture(newTexImage, firstTexIndex, firstTexCache, lastIndex, lastCache); } else { texCache.setLastIndex(lastIndex, lastCache); } } } // ----------------------------------------------------------------- // // Polygon tessellation void tessellatePolygon(boolean solid, boolean closed, boolean calcNormals) { beginTex(); int nInVert = in.lastVertex - in.firstVertex + 1; if (fill && 3 <= nInVert) { firstPolyIndexCache = -1; callback.init(in.renderMode == RETAINED, false, calcNormals); gluTess.beginPolygon(); if (solid) { // Using NONZERO winding rule for solid polygons. gluTess.setWindingRule(PGL.GLU_TESS_WINDING_NONZERO); } else { // Using ODD winding rule to generate polygon with holes. gluTess.setWindingRule(PGL.GLU_TESS_WINDING_ODD); } gluTess.beginContour(); // Now, iterate over all input data and send to GLU tessellator.. for (int i = in.firstVertex; i <= in.lastVertex; i++) { boolean breakPt = in.breaks[i]; if (breakPt) { gluTess.endContour(); gluTess.beginContour(); } // Separting colors into individual rgba components for interpolation. int fa = (in.colors[i] >> 24) & 0xFF; int fr = (in.colors[i] >> 16) & 0xFF; int fg = (in.colors[i] >> 8) & 0xFF; int fb = (in.colors[i] >> 0) & 0xFF; int aa = (in.ambient[i] >> 24) & 0xFF; int ar = (in.ambient[i] >> 16) & 0xFF; int ag = (in.ambient[i] >> 8) & 0xFF; int ab = (in.ambient[i] >> 0) & 0xFF; int sa = (in.specular[i] >> 24) & 0xFF; int sr = (in.specular[i] >> 16) & 0xFF; int sg = (in.specular[i] >> 8) & 0xFF; int sb = (in.specular[i] >> 0) & 0xFF; int ea = (in.emissive[i] >> 24) & 0xFF; int er = (in.emissive[i] >> 16) & 0xFF; int eg = (in.emissive[i] >> 8) & 0xFF; int eb = (in.emissive[i] >> 0) & 0xFF; // Vertex data includes coordinates, colors, normals, texture coordinates, and material properties. double[] vertex = new double[] { in.vertices [3 * i + 0], in.vertices [3 * i + 1], in.vertices[3 * i + 2], fa, fr, fg, fb, in.normals [3 * i + 0], in.normals [3 * i + 1], in.normals [3 * i + 2], in.texcoords[2 * i + 0], in.texcoords[2 * i + 1], aa, ar, ag, ab, sa, sr, sg, sb, ea, er, eg, eb, in.shininess[i]}; gluTess.addVertex(vertex); } gluTess.endContour(); gluTess.endPolygon(); } endTex(); tessellateEdges(); } // Tessellates the path given as parameter. This will work only in 2D. // Based on the opengl stroke hack described here: // http://wiki.processing.org/w/Stroke_attributes_in_OpenGL public void tessellateLinePath(LinePath path) { callback.init(in.renderMode == RETAINED, true, false); int cap = strokeCap == ROUND ? LinePath.CAP_ROUND : strokeCap == PROJECT ? LinePath.CAP_SQUARE : LinePath.CAP_BUTT; int join = strokeJoin == ROUND ? LinePath.JOIN_ROUND : strokeJoin == BEVEL ? LinePath.JOIN_BEVEL : LinePath.JOIN_MITER; // Make the outline of the stroke from the path LinePath strokedPath = LinePath.createStrokedPath(path, strokeWeight, cap, join); gluTess.beginPolygon(); double[] vertex; float[] coords = new float[6]; LinePath.PathIterator iter = strokedPath.getPathIterator(); int rule = iter.getWindingRule(); switch(rule) { case LinePath.WIND_EVEN_ODD: gluTess.setWindingRule(PGL.GLU_TESS_WINDING_ODD); break; case LinePath.WIND_NON_ZERO: gluTess.setWindingRule(PGL.GLU_TESS_WINDING_NONZERO); break; } while (!iter.isDone()) { float sr = 0; float sg = 0; float sb = 0; float sa = 0; switch (iter.currentSegment(coords)) { case LinePath.SEG_MOVETO: gluTess.beginContour(); case LinePath.SEG_LINETO: sa = (strokeColor >> 24) & 0xFF; sr = (strokeColor >> 16) & 0xFF; sg = (strokeColor >> 8) & 0xFF; sb = (strokeColor >> 0) & 0xFF; // Vertex data includes coordinates, colors, normals, texture coordinates, and material properties. vertex = new double[] { coords[0], coords[1], 0, sa, sr, sg, sb, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; gluTess.addVertex(vertex); break; case LinePath.SEG_CLOSE: gluTess.endContour(); break; } iter.next(); } gluTess.endPolygon(); } ///////////////////////////////////////// // Interenting notes about using the GLU tessellator to render thick polylines: // http://stackoverflow.com/questions/687173/how-do-i-render-thick-2d-lines-as-polygons // // "...Since I disliked the tesselator API I lifted the tesselation code from the free // SGI OpenGL reference implementation, rewrote the entire front-end and added memory // pools to get the number of allocations down. It took two days to do this, but it was // well worth it (like factor five performance improvement)..." // // This C implementation of GLU could be useful: // http://code.google.com/p/glues/ // to eventually come up with an optimized GLU tessellator in native code. protected class TessellatorCallback implements PGL.TessellatorCallback { boolean calcNormals; boolean strokeTess; IndexCache cache; int cacheIndex; int vertFirst; int vertCount; int primitive; public void init(boolean addCache, boolean strokeTess, boolean calcNorm) { this.strokeTess = strokeTess; this.calcNormals = calcNorm; cache = tess.polyIndexCache; if (addCache) { cache.addNew(); } } public void begin(int type) { cacheIndex = cache.getLast(); if (firstPolyIndexCache == -1) { firstPolyIndexCache = cacheIndex; } if (strokeTess && firstLineIndexCache == -1) { firstLineIndexCache = cacheIndex; } vertFirst = cache.vertexCount[cacheIndex]; vertCount = 0; switch (type) { case PGL.GL_TRIANGLE_FAN: primitive = TRIANGLE_FAN; break; case PGL.GL_TRIANGLE_STRIP: primitive = TRIANGLE_STRIP; break; case PGL.GL_TRIANGLES: primitive = TRIANGLES; break; } } public void end() { if (PGL.MAX_VERTEX_INDEX1 <= vertFirst + vertCount) { // We need a new index block for the new batch of // vertices resulting from this primitive. tessCount can // be safely assumed here to be less or equal than // MAX_VERTEX_INDEX1 because the condition was checked // every time a new vertex was emitted (see vertex() below). //tessBlock = tess.addFillIndexBlock(tessBlock); cacheIndex = cache.addNew(); vertFirst = 0; } int indCount = 0; switch (primitive) { case TRIANGLE_FAN: indCount = 3 * (vertCount - 2); for (int i = 1; i < vertCount - 1; i++) { addIndex(0); addIndex(i); addIndex(i + 1); if (calcNormals) calcTriNormal(0, i, i + 1); } break; case TRIANGLE_STRIP: indCount = 3 * (vertCount - 2); for (int i = 1; i < vertCount - 1; i++) { if (i % 2 == 0) { addIndex(i + 1); addIndex(i); addIndex(i - 1); if (calcNormals) calcTriNormal(i + 1, i, i - 1); } else { addIndex(i - 1); addIndex(i); addIndex(i + 1); if (calcNormals) calcTriNormal(i - 1, i, i + 1); } } break; case TRIANGLES: indCount = vertCount; for (int i = 0; i < vertCount; i++) { addIndex(i); } if (calcNormals) { for (int tr = 0; tr < vertCount / 3; tr++) { int i0 = 3 * tr + 0; int i1 = 3 * tr + 1; int i2 = 3 * tr + 2; calcTriNormal(i0, i1, i2); } } break; } cache.incCounts(cacheIndex, indCount, vertCount); lastPolyIndexCache = cacheIndex; if (strokeTess) { lastLineIndexCache = cacheIndex; } } protected void addIndex(int tessIdx) { tess.polyIndexCheck(); tess.polyIndices[tess.polyIndexCount - 1] = (short) (vertFirst + tessIdx); } protected void calcTriNormal(int tessIdx0, int tessIdx1, int tessIdx2) { tess.calcPolyNormal(vertFirst + tessIdx0, vertFirst + tessIdx1, vertFirst + tessIdx2); } public void vertex(Object data) { if (data instanceof double[]) { double[] d = (double[]) data; int l = d.length; if (l < 25) { throw new RuntimeException("TessCallback vertex() data is not of length 25"); } if (vertCount < PGL.MAX_VERTEX_INDEX1) { // Combining individual rgba components back into int color values int fcolor = ((int) d[ 3] << 24) | ((int) d[ 4] << 16) | ((int) d[ 5] << 8) | (int) d[ 6]; int acolor = ((int) d[12] << 24) | ((int) d[13] << 16) | ((int) d[14] << 8) | (int) d[15]; int scolor = ((int) d[16] << 24) | ((int) d[17] << 16) | ((int) d[18] << 8) | (int) d[19]; int ecolor = ((int) d[20] << 24) | ((int) d[21] << 16) | ((int) d[22] << 8) | (int) d[23]; tess.addPolyVertex((float) d[ 0], (float) d[ 1], (float) d[ 2], fcolor, (float) d[ 7], (float) d[ 8], (float) d[ 9], (float) d[10], (float) d[11], acolor, scolor, ecolor, (float) d[24]); vertCount++; } else { throw new RuntimeException("P3D: the tessellator is generating too many vertices, reduce complexity of shape."); } } else { throw new RuntimeException("TessCallback vertex() data not understood"); } } public void error(int errnum) { String estring = pgl.gluErrorString(errnum); PGraphics.showWarning("Tessellation Error: " + estring); } /** * Implementation of the GLU_TESS_COMBINE callback. * @param coords is the 3-vector of the new vertex * @param data is the vertex data to be combined, up to four elements. * This is useful when mixing colors together or any other * user data that was passed in to gluTessVertex. * @param weight is an array of weights, one for each element of "data" * that should be linearly combined for new values. * @param outData is the set of new values of "data" after being * put back together based on the weights. it's passed back as a * single element Object[] array because that's the closest * that Java gets to a pointer. */ public void combine(double[] coords, Object[] data, float[] weight, Object[] outData) { double[] vertex = new double[25 + 8]; vertex[0] = coords[0]; vertex[1] = coords[1]; vertex[2] = coords[2]; // Calculating the rest of the vertex parameters (color, // normal, texcoords) as the linear combination of the // combined vertices. for (int i = 3; i < 25; i++) { vertex[i] = 0; for (int j = 0; j < 4; j++) { double[] vertData = (double[])data[j]; if (vertData != null) { vertex[i] += weight[j] * vertData[i]; } } } // Normalizing normal vector, since the weighted // combination of normal vectors is not necessarily // normal. double sum = vertex[7] * vertex[7] + vertex[8] * vertex[8] + vertex[9] * vertex[9]; double len = Math.sqrt(sum); vertex[7] /= len; vertex[8] /= len; vertex[9] /= len; outData[0] = vertex; } } } } \ No newline at end of file
false
false
null
null
diff --git a/src/com/vaadin/ui/themes/Reindeer.java b/src/com/vaadin/ui/themes/Reindeer.java index 33a91069a..2febbb930 100644 --- a/src/com/vaadin/ui/themes/Reindeer.java +++ b/src/com/vaadin/ui/themes/Reindeer.java @@ -1,214 +1,214 @@ /* @ITMillApache2LicenseForJavaFiles@ */ package com.vaadin.ui.themes; import com.vaadin.ui.CssLayout; import com.vaadin.ui.FormLayout; import com.vaadin.ui.GridLayout; import com.vaadin.ui.HorizontalLayout; import com.vaadin.ui.SplitPanel; import com.vaadin.ui.VerticalLayout; public class Reindeer extends BaseTheme { public static final String THEME_NAME = "Reindeer"; /*************************************************************************** * * Label styles * **************************************************************************/ /** * Large font for main application headings */ public static final String LABEL_H1 = "h1"; /** * Large font for different sections in the application */ public static final String LABEL_H2 = "h2"; /** * Small and a little lighter font */ public static final String LABEL_SMALL = "light"; /** * @deprecated Use {@link #LABEL_SMALL} instead. */ @Deprecated public static final String LABEL_LIGHT = "small"; /*************************************************************************** * * Button styles * **************************************************************************/ /** - * Default action style for buttons (the button that gets activated when - * user presses 'enter' in a form). Use sparingly, only one default button - * per screen should be visible. + * Default action style for buttons (the button that should get activated + * when the user presses 'enter' in a form). Use sparingly, only one default + * button per view should be visible. */ public static final String BUTTON_DEFAULT = "primary"; /** * @deprecated Use {@link #BUTTON_DEFAULT} instead */ @Deprecated public static final String BUTTON_PRIMARY = BUTTON_DEFAULT; /** * Small sized button, use for context specific actions for example */ public static final String BUTTON_SMALL = "small"; /*************************************************************************** * * TextField styles * **************************************************************************/ /** * Small sized text field with small font */ public static final String TEXTFIELD_SMALL = "small"; /*************************************************************************** * * Panel styles * **************************************************************************/ /** * Removes borders and background color from the panel */ public static final String PANEL_LIGHT = "light"; /*************************************************************************** * * SplitPanel styles * **************************************************************************/ /** * Reduces the split handle to a minimal size (1 pixel) */ public static final String SPLITPANEL_SMALL = "small"; /*************************************************************************** * * TabSheet styles * **************************************************************************/ /** * Removes borders from the default tab sheet style. */ public static final String TABSHEET_BORDERLESS = "borderless"; /** * Removes borders and background color from the tab sheet, and shows the * tabs as a small bar. */ public static final String TABSHEET_SMALL = "bar"; /** * @deprecated Use {@link #TABSHEET_SMALL} instead. */ @Deprecated public static final String TABSHEET_BAR = TABSHEET_SMALL; /** * Removes borders and background color from the tab sheet. The tabs are * presented with minimal lines indicating the selected tab. */ public static final String TABSHEET_MINIMAL = "minimal"; /** * Makes the tab close buttons visible only when the user is hovering over * the tab. */ public static final String TABSHEET_HOVER_CLOSABLE = "hover-closable"; /** * Makes the tab close buttons visible only when the tab is selected. */ public static final String TABSHEET_SELECTED_CLOSABLE = "selected-closable"; /*************************************************************************** * * Table styles * **************************************************************************/ /** * Removes borders from the table */ public static final String TABLE_BORDERLESS = "borderless"; /** * Makes the table headers dark and more prominent. */ public static final String TABLE_STRONG = "strong"; /*************************************************************************** * * Layout styles * **************************************************************************/ /** * Changes the background of a layout to white. Applies to * {@link VerticalLayout}, {@link HorizontalLayout}, {@link GridLayout}, * {@link FormLayout}, {@link CssLayout} and {@link SplitPanel}. * <p> * <em>Does not revert any contained components back to normal if some * parent layout has style {@link #LAYOUT_BLACK} applied.</em> */ public static final String LAYOUT_WHITE = "white"; /** * Changes the background of a layout to a shade of blue. Applies to * {@link VerticalLayout}, {@link HorizontalLayout}, {@link GridLayout}, * {@link FormLayout}, {@link CssLayout} and {@link SplitPanel}. * <p> * <em>Does not revert any contained components back to normal if some * parent layout has style {@link #LAYOUT_BLACK} applied.</em> */ public static final String LAYOUT_BLUE = "blue"; /** * <p> * Changes the background of a layout to almost black, and at the same time * transforms contained components to their black style correspondents when * available. At least texts, buttons, text fields, selects, date fields, * tables and a few other component styles should change. * </p> * <p> * Applies to {@link VerticalLayout}, {@link HorizontalLayout}, * {@link GridLayout}, {@link FormLayout} and {@link CssLayout}. * </p> * */ public static final String LAYOUT_BLACK = "black"; /*************************************************************************** * * Window styles * **************************************************************************/ /** * Makes the whole window white and increases the font size of the title. */ public static final String WINDOW_LIGHT = "light"; /** * Makes the whole window black, and changes contained components in the * same way as {@link #LAYOUT_BLACK} does. */ public static final String WINDOW_BLACK = "black"; }
true
false
null
null
diff --git a/src/java/com/idega/presentation/remotescripting/RemoteScriptHandler.java b/src/java/com/idega/presentation/remotescripting/RemoteScriptHandler.java index 206f803f2..6968a59e7 100644 --- a/src/java/com/idega/presentation/remotescripting/RemoteScriptHandler.java +++ b/src/java/com/idega/presentation/remotescripting/RemoteScriptHandler.java @@ -1,380 +1,380 @@ package com.idega.presentation.remotescripting; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; import com.idega.presentation.IWContext; import com.idega.presentation.Layer; import com.idega.presentation.PresentationObject; import com.idega.presentation.PresentationObjectContainer; import com.idega.presentation.Script; import com.idega.presentation.ui.DropdownMenu; import com.idega.presentation.ui.IFrame; import com.idega.presentation.ui.InterfaceObject; import com.idega.presentation.ui.TextInput; import com.idega.repository.data.RefactorClassRegistry; /** * A class for handling remote scripting between two objects. * @author gimmi */ public class RemoteScriptHandler extends PresentationObjectContainer { //implements RemoteScriptable { private static final String PARAMETER_REMOTE_SCRIPT_HANDLING_CLASS = "prc"; private static final String PARAMETER_SOURCE_NAME = "psn"; public static final String PARAMETER_SOURCE_PARAMETER_NAME = "prmp"; private InterfaceObject source; private PresentationObject target; private Map parameters = new HashMap(); private Map toClear = new HashMap(); private String iframeName; private RemoteScriptCollection remoteScriptCollection; private boolean sourceIsTrigger = true; /** * Default construction should never be used unless * class is receiving a remote call */ public RemoteScriptHandler() { // Should only be used for remote calls } /** * @param source The source object, that triggers the event * @param target The target object, the one affected by the event */ public RemoteScriptHandler(InterfaceObject source, PresentationObject target) { this.source = source; this.target = target; iframeName = source.getName()+"_"+target.getName(); } public void main(IWContext iwc) throws Exception{ if (isRemoteCall(iwc)) { handleRemoteCall(iwc); } else { // Adding object if they are not added already if (source.getParent() == null) { add(source); } if (target.getParent() == null) { add(target); } // source MUST BE added to something before these methods are called if (sourceIsTrigger) { if (source instanceof TextInput) { source.setOnKeyUp(getSubmitEvent(iwc)); } else { source.setOnChange(getSubmitEvent(iwc)); } } addRemoteScriptingScripts(iwc); } } private void addRemoteScriptingScripts(IWContext iwc) { if (target instanceof DropdownMenu) { addScriptForDropdown(); } else if (target instanceof Layer) { addScriptForLayer(); } else { throw new IllegalArgumentException("Unsupported target instance "+target.getClass().getName()); } addCallToServer(iwc); addBuildQueryScript(); addIFrame(); } private void addCallToServer(IWContext iwc) { StringBuffer buff = new StringBuffer(); buff.append("var IFrameObj; // our IFrame object").append("\n") .append("function callToServer_"+iframeName+"(theFormName) {").append("\n") .append(" if (!document.createElement) {return true};").append("\n") .append(" var IFrameDoc;").append("\n") .append(" if (!IFrameObj && document.createElement) {").append("\n") .append(" // create the IFrame and assign a reference to the").append("\n") .append(" // object to our global variable IFrameObj.").append("\n") .append(" // this will only happen the first time") .append("\n") .append(" // callToServer() is called").append("\n") .append(" try {").append("\n") .append(" var tempIFrame=document.createElement('iframe');").append("\n") .append(" tempIFrame.setAttribute('id','"+iframeName+"');").append("\n") .append(" tempIFrame.style.border='0px';").append("\n") .append(" tempIFrame.style.width='0px';").append("\n") .append(" tempIFrame.style.height='0px';").append("\n") .append(" IFrameObj = document.body.appendChild(tempIFrame);").append("\n") .append(" if (document.frames) {").append("\n") .append(" // this is for IE5 Mac, because it will only").append("\n") .append(" // allow access to the document object").append("\n") .append(" // of the IFrame if we access it through").append("\n") .append(" // the document.frames array").append("\n") .append(" IFrameObj = document.frames['"+iframeName+"'];").append("\n") .append(" }").append("\n") .append(" } catch(exception) {").append("\n") .append(" // This is for IE5 PC, which does not allow dynamic creation").append("\n") .append(" // and manipulation of an iframe object. Instead, we'll fake").append("\n") .append(" // it up by creating our own objects.").append("\n") .append(" iframeHTML='<iframe id=\""+iframeName+"\" style=\"';").append("\n") .append(" iframeHTML+='border:0px;';").append("\n") .append(" iframeHTML+='width:0px;';").append("\n") .append(" iframeHTML+='height:0px;';").append("\n") .append(" iframeHTML+='\"><\\/iframe>';").append("\n") .append(" document.body.innerHTML+=iframeHTML;").append("\n") .append(" IFrameObj = new Object();").append("\n") .append(" IFrameObj.document = new Object();").append("\n") .append(" IFrameObj.document.location = new Object();").append("\n") .append(" IFrameObj.document.location.iframe = document.getElementById('"+iframeName+"');").append("\n") .append(" IFrameObj.document.location.replace = function(location) {").append("\n") .append(" this.iframe.src = location;").append("\n") .append(" }").append("\n") .append(" }").append("\n") .append(" }").append("\n") .append(" if (navigator.userAgent.indexOf('Gecko') !=-1 && !IFrameObj.contentDocument) {").append("\n") .append(" // we have to give NS6 a fraction of a second").append("\n") .append(" // to recognize the new IFrame").append("\n") .append(" setTimeout('callToServer_"+iframeName+"(\"'+theFormName+'\")',10);").append("\n") .append(" return false;").append("\n") .append(" }").append("\n") .append(" if (IFrameObj.contentDocument) {").append("\n") .append(" // For NS6").append("\n") .append(" IFrameDoc = IFrameObj.contentDocument;").append("\n") .append(" } else if (IFrameObj.contentWindow) {").append("\n") .append(" // For IE5.5 and IE6").append("\n") .append(" IFrameDoc = IFrameObj.contentWindow.document;").append("\n") .append(" } else if (IFrameObj.document) {").append("\n") .append(" // For IE5").append("\n") .append(" IFrameDoc = IFrameObj.document;").append("\n") .append(" } else {").append("\n") .append(" return true;").append("\n") .append(" }").append("\n") - .append(" IFrameDoc.location.replace('"+getRemoteUrl(iwc)+"' + buildQueryString_"+source.getID()+"(document."+source.getForm().getID()+".name));").append("\n") + .append(" IFrameDoc.location.replace('"+getRemoteUrl(iwc)+"' + buildQueryString_"+source.getID()+"(findObj('"+source.getForm().getID()+"').name));").append("\n") .append(" return false;").append("\n") .append("}").append("\n"); if (getAssociatedScript() != null) { getAssociatedScript().addFunction("callToServer_"+iframeName, buff.toString()); } } private void addIFrame() { IFrame iframe = new IFrame(iframeName); iframe.setID(iframeName); iframe.setHeight(0); iframe.setWidth(0); iframe.setBorder(0); iframe.setSrc("blank.html"); add(iframe); } private void addBuildQueryScript() { StringBuffer params = new StringBuffer(); params.append("&").append(PARAMETER_SOURCE_PARAMETER_NAME).append("=").append(source.getName()); Set parNames = parameters.keySet(); Iterator iter = parNames.iterator(); while (iter.hasNext()) { String name = (String) iter.next(); String value = (String) parameters.get(name); params.append("&").append(name).append("=").append(value); } if (getAssociatedScript() != null) { getAssociatedScript().addFunction("buildQueryString_"+source.getID()+"(theFormName)", "function buildQueryString_"+source.getID()+"(theFormName){ \n" +" theForm = document.forms[theFormName];\n" +" var qs = ''\n" +" for (e=0;e<theForm.elements.length;e++) {\n" +" if (theForm.elements[e].name != '') {\n" +" qs+='&'\n" +" qs+=theForm.elements[e].name+'='+theForm.elements[e].value\n" // +" qs+=theForm.elements[e].name+'='+escape(theForm.elements[e].value)\n" +" }\n" +" } \n" +" qs+='"+params.toString()+"';" +" return qs\n" +"}\n"); } } private void addScriptForDropdown() { StringBuffer buff = new StringBuffer(); buff.append("function handleResponse_"+source.getID()+"(doc) {\n") .append(" var namesEl = document.getElementById('"+source.getID()+"');\n") .append(" var zipEl = document.getElementById('"+target.getID()+"');\n") .append(" zipEl.options.length = 0; \n") .append(" var dataElID = doc.getElementById('"+RemoteScriptHandler.getLayerName(source.getName(), "id")+"');\n") .append(" var dataElName = doc.getElementById('"+RemoteScriptHandler.getLayerName(source.getName(), "name")+"');\n") .append(" namesColl = dataElName.childNodes; \n") .append(" idsColl = dataElID.childNodes; \n") .append(" var numNames = namesColl.length; \n") .append(" var str = '';\n") .append(" var ids = '';\n") .append(" for (var q=0; q<numNames; q++) {\n") .append(" if (namesColl[q].nodeType!=1) continue; // it's not an element node, let's skedaddle\n") .append(" str = namesColl[q].name;\n") .append(" ids = idsColl[q].name;\n") .append(" zipEl.options[zipEl.options.length] = new Option(str, ids);\n") .append(" }\n"); buff = addClearMethods(buff); buff.append("}\n"); getAssociatedScript().addFunction("handleResponse_"+source.getID(), buff.toString()); } private void addScriptForLayer() { StringBuffer buff = new StringBuffer(); buff.append("function handleResponse_"+source.getID()+"(doc) {\n") .append(" var dataEl = doc.getElementById('"+RemoteScriptHandler.getLayerName(source.getName())+"');\n") .append(" var str = '';\n") .append(" if (dataEl != null) {\n") .append(" namesColl = dataEl.childNodes; \n") .append(" var numNames = namesColl.length; \n") .append(" for (var q=0; q<numNames; q++) {\n") .append(" if (namesColl[q].nodeType!=1) continue; // it's not an element node, let's skedaddle\n") .append(" str+= namesColl[q].name;\n") .append(" }\n") .append(" } else {\n") .append(" str = '';\n") .append(" }\n") .append(" var resultText = this.document.getElementById('"+target.getID()+"');\n") .append(" resultText.innerHTML = str;\n"); buff = addClearMethods(buff); buff.append("}\n"); Script s = getAssociatedScript(); if (s != null) { s.addFunction("handleResponse_"+source.getID(), buff.toString()); } } private StringBuffer addClearMethods(StringBuffer script) { Set keySet = toClear.keySet(); Iterator iter = keySet.iterator(); PresentationObject po; String value; while (iter.hasNext()) { po = (InterfaceObject) iter.next(); value = (String) toClear.get(po); if (po instanceof DropdownMenu) { script.append( " var zipEl = document.getElementById('"+po.getID()+"');\n"+ " zipEl.options.length = 0; \n" + " zipEl.options[zipEl.options.length] = new Option('"+value+"', '-1');\n"); } else if (po instanceof Layer) { if (value == null) { value = ""; } script.append( " var resultText = this.document.getElementById('"+po.getID()+"');\n"+ " resultText.innerHTML = '"+value+"';\n"); } else { throw new IllegalArgumentException("Unsupported target instance "+target.getClass().getName()); } } return script; } private void handleRemoteCall(IWContext iwc) throws InstantiationException, IllegalAccessException, ClassNotFoundException { String rscClassName = iwc.getParameter(PARAMETER_REMOTE_SCRIPT_HANDLING_CLASS); RemoteScriptCollection rsc = (RemoteScriptCollection) RefactorClassRegistry.forName(rscClassName).newInstance(); this.getParentPage().setOnLoad("if (parent != self) parent.handleResponse_"+iwc.getParameter(PARAMETER_SOURCE_NAME)+"(document)"); add(rsc.getResults(iwc)); } private String getRemoteUrl(IWContext iwc) { String url = iwc.getIWMainApplication().getObjectInstanciatorURI(getClass().getName()); if (url.indexOf("?") < 0) { url += "?"; } url += PARAMETER_REMOTE_SCRIPT_HANDLING_CLASS+"="+remoteScriptCollection.getClass().getName()+"&"+PARAMETER_SOURCE_NAME+"="+source.getID(); return url; } private boolean isRemoteCall(IWContext iwc) { return iwc.isParameterSet(PARAMETER_REMOTE_SCRIPT_HANDLING_CLASS); } /** * Method to get the name of a layer * @param sourceName The name of the source object * @return */ public static String getLayerName(String sourceName) { return sourceName+"_div"; } /** * Method to get the name of a layer * @param sourceName The name of the source object * @param addon A string to add to the name, e.g. <code>id</code> or <code>name</code> * @return */ public static String getLayerName(String sourceName, String addon) { return sourceName+"_"+addon+"_div"; } /** * Method to get the event to trigger the remote script, can be used with onChange, onBlur, and so on. * @param iwc IWContext * @return */ public String getSubmitEvent(IWContext iwc) { return "return callToServer_"+iframeName+"(findObj('"+source.getForm().getID()+"').name)"; } /** * Set which class handles the remote procedure * Class must implement RemoteScripCollection class * @param remoteScriptCollectionClass * @throws InstantiationException * @throws IllegalAccessException */ public void setRemoteScriptCollectionClass(Class remoteScriptCollectionClass) throws InstantiationException, IllegalAccessException { this.remoteScriptCollection = (RemoteScriptCollection) remoteScriptCollectionClass.newInstance(); } /** * Set wether or not the source object triggers the event. * Default value is <code>true</code> * @param isSourceTrigger */ public void setIsSourceTrigger(boolean isSourceTrigger) { this.sourceIsTrigger = isSourceTrigger; } /** * Add a parameter that is submitted to the remote page * @param name Name of the parameter * @param value Value of the parameter */ public void addParameter(String name, String value) { parameters.put(name, value); } /** * Set if the event is supposed to clear an object * @param po PresentationObject that is to be cleared * @param emptyValue A value to use instead of nothing */ public void setToClear(PresentationObject po, String emptyValue) { toClear.put(po, emptyValue); } }
true
true
private void addCallToServer(IWContext iwc) { StringBuffer buff = new StringBuffer(); buff.append("var IFrameObj; // our IFrame object").append("\n") .append("function callToServer_"+iframeName+"(theFormName) {").append("\n") .append(" if (!document.createElement) {return true};").append("\n") .append(" var IFrameDoc;").append("\n") .append(" if (!IFrameObj && document.createElement) {").append("\n") .append(" // create the IFrame and assign a reference to the").append("\n") .append(" // object to our global variable IFrameObj.").append("\n") .append(" // this will only happen the first time") .append("\n") .append(" // callToServer() is called").append("\n") .append(" try {").append("\n") .append(" var tempIFrame=document.createElement('iframe');").append("\n") .append(" tempIFrame.setAttribute('id','"+iframeName+"');").append("\n") .append(" tempIFrame.style.border='0px';").append("\n") .append(" tempIFrame.style.width='0px';").append("\n") .append(" tempIFrame.style.height='0px';").append("\n") .append(" IFrameObj = document.body.appendChild(tempIFrame);").append("\n") .append(" if (document.frames) {").append("\n") .append(" // this is for IE5 Mac, because it will only").append("\n") .append(" // allow access to the document object").append("\n") .append(" // of the IFrame if we access it through").append("\n") .append(" // the document.frames array").append("\n") .append(" IFrameObj = document.frames['"+iframeName+"'];").append("\n") .append(" }").append("\n") .append(" } catch(exception) {").append("\n") .append(" // This is for IE5 PC, which does not allow dynamic creation").append("\n") .append(" // and manipulation of an iframe object. Instead, we'll fake").append("\n") .append(" // it up by creating our own objects.").append("\n") .append(" iframeHTML='<iframe id=\""+iframeName+"\" style=\"';").append("\n") .append(" iframeHTML+='border:0px;';").append("\n") .append(" iframeHTML+='width:0px;';").append("\n") .append(" iframeHTML+='height:0px;';").append("\n") .append(" iframeHTML+='\"><\\/iframe>';").append("\n") .append(" document.body.innerHTML+=iframeHTML;").append("\n") .append(" IFrameObj = new Object();").append("\n") .append(" IFrameObj.document = new Object();").append("\n") .append(" IFrameObj.document.location = new Object();").append("\n") .append(" IFrameObj.document.location.iframe = document.getElementById('"+iframeName+"');").append("\n") .append(" IFrameObj.document.location.replace = function(location) {").append("\n") .append(" this.iframe.src = location;").append("\n") .append(" }").append("\n") .append(" }").append("\n") .append(" }").append("\n") .append(" if (navigator.userAgent.indexOf('Gecko') !=-1 && !IFrameObj.contentDocument) {").append("\n") .append(" // we have to give NS6 a fraction of a second").append("\n") .append(" // to recognize the new IFrame").append("\n") .append(" setTimeout('callToServer_"+iframeName+"(\"'+theFormName+'\")',10);").append("\n") .append(" return false;").append("\n") .append(" }").append("\n") .append(" if (IFrameObj.contentDocument) {").append("\n") .append(" // For NS6").append("\n") .append(" IFrameDoc = IFrameObj.contentDocument;").append("\n") .append(" } else if (IFrameObj.contentWindow) {").append("\n") .append(" // For IE5.5 and IE6").append("\n") .append(" IFrameDoc = IFrameObj.contentWindow.document;").append("\n") .append(" } else if (IFrameObj.document) {").append("\n") .append(" // For IE5").append("\n") .append(" IFrameDoc = IFrameObj.document;").append("\n") .append(" } else {").append("\n") .append(" return true;").append("\n") .append(" }").append("\n") .append(" IFrameDoc.location.replace('"+getRemoteUrl(iwc)+"' + buildQueryString_"+source.getID()+"(document."+source.getForm().getID()+".name));").append("\n") .append(" return false;").append("\n") .append("}").append("\n"); if (getAssociatedScript() != null) { getAssociatedScript().addFunction("callToServer_"+iframeName, buff.toString()); } }
private void addCallToServer(IWContext iwc) { StringBuffer buff = new StringBuffer(); buff.append("var IFrameObj; // our IFrame object").append("\n") .append("function callToServer_"+iframeName+"(theFormName) {").append("\n") .append(" if (!document.createElement) {return true};").append("\n") .append(" var IFrameDoc;").append("\n") .append(" if (!IFrameObj && document.createElement) {").append("\n") .append(" // create the IFrame and assign a reference to the").append("\n") .append(" // object to our global variable IFrameObj.").append("\n") .append(" // this will only happen the first time") .append("\n") .append(" // callToServer() is called").append("\n") .append(" try {").append("\n") .append(" var tempIFrame=document.createElement('iframe');").append("\n") .append(" tempIFrame.setAttribute('id','"+iframeName+"');").append("\n") .append(" tempIFrame.style.border='0px';").append("\n") .append(" tempIFrame.style.width='0px';").append("\n") .append(" tempIFrame.style.height='0px';").append("\n") .append(" IFrameObj = document.body.appendChild(tempIFrame);").append("\n") .append(" if (document.frames) {").append("\n") .append(" // this is for IE5 Mac, because it will only").append("\n") .append(" // allow access to the document object").append("\n") .append(" // of the IFrame if we access it through").append("\n") .append(" // the document.frames array").append("\n") .append(" IFrameObj = document.frames['"+iframeName+"'];").append("\n") .append(" }").append("\n") .append(" } catch(exception) {").append("\n") .append(" // This is for IE5 PC, which does not allow dynamic creation").append("\n") .append(" // and manipulation of an iframe object. Instead, we'll fake").append("\n") .append(" // it up by creating our own objects.").append("\n") .append(" iframeHTML='<iframe id=\""+iframeName+"\" style=\"';").append("\n") .append(" iframeHTML+='border:0px;';").append("\n") .append(" iframeHTML+='width:0px;';").append("\n") .append(" iframeHTML+='height:0px;';").append("\n") .append(" iframeHTML+='\"><\\/iframe>';").append("\n") .append(" document.body.innerHTML+=iframeHTML;").append("\n") .append(" IFrameObj = new Object();").append("\n") .append(" IFrameObj.document = new Object();").append("\n") .append(" IFrameObj.document.location = new Object();").append("\n") .append(" IFrameObj.document.location.iframe = document.getElementById('"+iframeName+"');").append("\n") .append(" IFrameObj.document.location.replace = function(location) {").append("\n") .append(" this.iframe.src = location;").append("\n") .append(" }").append("\n") .append(" }").append("\n") .append(" }").append("\n") .append(" if (navigator.userAgent.indexOf('Gecko') !=-1 && !IFrameObj.contentDocument) {").append("\n") .append(" // we have to give NS6 a fraction of a second").append("\n") .append(" // to recognize the new IFrame").append("\n") .append(" setTimeout('callToServer_"+iframeName+"(\"'+theFormName+'\")',10);").append("\n") .append(" return false;").append("\n") .append(" }").append("\n") .append(" if (IFrameObj.contentDocument) {").append("\n") .append(" // For NS6").append("\n") .append(" IFrameDoc = IFrameObj.contentDocument;").append("\n") .append(" } else if (IFrameObj.contentWindow) {").append("\n") .append(" // For IE5.5 and IE6").append("\n") .append(" IFrameDoc = IFrameObj.contentWindow.document;").append("\n") .append(" } else if (IFrameObj.document) {").append("\n") .append(" // For IE5").append("\n") .append(" IFrameDoc = IFrameObj.document;").append("\n") .append(" } else {").append("\n") .append(" return true;").append("\n") .append(" }").append("\n") .append(" IFrameDoc.location.replace('"+getRemoteUrl(iwc)+"' + buildQueryString_"+source.getID()+"(findObj('"+source.getForm().getID()+"').name));").append("\n") .append(" return false;").append("\n") .append("}").append("\n"); if (getAssociatedScript() != null) { getAssociatedScript().addFunction("callToServer_"+iframeName, buff.toString()); } }
diff --git a/src/contrib/corona/src/test/org/apache/hadoop/corona/MiniCoronaCluster.java b/src/contrib/corona/src/test/org/apache/hadoop/corona/MiniCoronaCluster.java index cc00465..d95355d 100644 --- a/src/contrib/corona/src/test/org/apache/hadoop/corona/MiniCoronaCluster.java +++ b/src/contrib/corona/src/test/org/apache/hadoop/corona/MiniCoronaCluster.java @@ -1,339 +1,340 @@ /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.corona; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; +import org.apache.hadoop.http.NettyMapOutputHttpServer; import org.apache.hadoop.mapred.CoronaJobTracker; import org.apache.hadoop.mapred.CoronaTaskTracker; import org.apache.hadoop.mapred.JobClient; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.mapred.ProxyJobTracker; import org.apache.hadoop.metrics.ContextFactory; import org.apache.hadoop.metrics.spi.NoEmitMetricsContext; import org.apache.hadoop.net.DNSToSwitchMapping; import org.apache.hadoop.net.NetUtils; import org.apache.hadoop.net.NetworkTopology; import org.apache.hadoop.net.StaticMapping; import org.apache.hadoop.security.UnixUserGroupInformation; /** * This class creates a single-process Map-Reduce cluster for junit testing. */ public class MiniCoronaCluster { private static final Log LOG = LogFactory.getLog(MiniCoronaCluster.class); private final JobConf conf; private ClusterManager clusterManager; private ClusterManagerServer clusterManagerServer; private final int clusterManagerPort; private final int proxyJobTrackerPort; private final List<TaskTrackerRunner> taskTrackerList = new ArrayList<TaskTrackerRunner>(); private final List<Thread> taskTrackerThreadList = new ArrayList<Thread>(); private final String namenode; private final UnixUserGroupInformation ugi; private final ProxyJobTracker pjt; /** * Create MiniCoronaCluster with builder pattern. * Example: * MiniCoronaCluster cluster = * new MiniCoronaCluster.numDir(3).hosts(hosts).build(); */ public static class Builder { private String namenode = "local"; private JobConf conf = null; private int numTaskTrackers = 1; private int numDir = 1; private String[] racks = null; private String[] hosts = null; private final UnixUserGroupInformation ugi = null; public Builder namenode(String val) { this.namenode = val; return this; } public Builder conf(JobConf val) { this.conf = val; return this; } public Builder numTaskTrackers(int val) { this.numTaskTrackers = val; return this; } public Builder numDir(int val) { this.numDir = val; return this; } public Builder racks(String[] val) { this.racks = val; return this; } public Builder hosts(String[] val) { this.hosts = val; return this; } public MiniCoronaCluster build() throws IOException { return new MiniCoronaCluster(this); } } private MiniCoronaCluster(Builder builder) throws IOException { ContextFactory.resetFactory(); setNoEmitMetricsContext(); if (builder.racks != null && builder.hosts != null) { if (builder.racks.length != builder.hosts.length) { throw new IllegalArgumentException( "The number of hosts and racks must be the same"); } } this.conf = builder.conf != null ? builder.conf : new JobConf(); this.namenode = builder.namenode; this.ugi = builder.ugi; this.conf.set(CoronaConf.CM_ADDRESS, "localhost:0"); this.conf.set(CoronaConf.CPU_TO_RESOURCE_PARTITIONING, TstUtils.std_cpu_to_resource_partitioning); this.clusterManagerPort = startClusterManager(this.conf); this.conf.set(CoronaConf.PROXY_JOB_TRACKER_ADDRESS, "localhost:0"); pjt = ProxyJobTracker.startProxyTracker(new CoronaConf(conf)); this.proxyJobTrackerPort = pjt.getRpcPort(); configureJobConf(conf, builder.namenode, clusterManagerPort, proxyJobTrackerPort, builder.ugi); for (int i = 0; i < builder.numTaskTrackers; ++i) { String host = builder.hosts == null ? "host" + i + ".foo.com" : builder.hosts[i]; String rack = builder.racks == null ? NetworkTopology.DEFAULT_RACK : builder.racks[i]; startTaskTracker(host, rack, i, builder.numDir); } waitTaskTrackers(); } private void setNoEmitMetricsContext() throws IOException { ContextFactory factory = ContextFactory.getFactory(); factory.setAttribute(ClusterManagerMetrics.CONTEXT_NAME + ".class", NoEmitMetricsContext.class.getName()); } int startClusterManager(Configuration conf) throws IOException { clusterManager = new ClusterManager(conf); clusterManagerServer = new ClusterManagerServer(conf, clusterManager); clusterManagerServer.start(); return clusterManagerServer.port; } public void startTaskTracker(String host, String rack, int idx, int numDir) throws IOException { if (rack != null) { StaticMapping.addNodeToRack(host, rack); } if (host != null) { NetUtils.addStaticResolution(host, "localhost"); } TaskTrackerRunner taskTracker; taskTracker = new TaskTrackerRunner(idx, numDir, host, conf); addTaskTracker(taskTracker); } void addTaskTracker(TaskTrackerRunner taskTracker) throws IOException { Thread taskTrackerThread = new Thread(taskTracker); taskTrackerList.add(taskTracker); taskTrackerThreadList.add(taskTrackerThread); taskTrackerThread.start(); } public int getClusterManagerPort() { return clusterManagerPort; } public ClusterManager getClusterManager() { return clusterManager; } public TaskTrackerRunner getTaskTrackerRunner(int i) { return taskTrackerList.get(i); } public JobConf createJobConf() { return createJobConf(new JobConf()); } public JobConf createJobConf(JobConf conf) { if(conf == null) { conf = new JobConf(); } configureJobConf(conf, namenode, clusterManagerPort, proxyJobTrackerPort, ugi); return conf; } static void configureJobConf(JobConf conf, String namenode, int clusterManagerPort, int proxyJobTrackerPort, UnixUserGroupInformation ugi) { FileSystem.setDefaultUri(conf, namenode); conf.set(CoronaConf.CM_ADDRESS, "localhost:" + clusterManagerPort); conf.set(CoronaConf.PROXY_JOB_TRACKER_ADDRESS, "localhost:" + proxyJobTrackerPort); conf.set("mapred.job.tracker", "corona"); conf.set("mapred.job.tracker.http.address", "127.0.0.1:0"); conf.setClass("topology.node.switch.mapping.impl", StaticMapping.class, DNSToSwitchMapping.class); conf.set("mapred.job.tracker.class", CoronaJobTracker.class.getName()); if (ugi != null) { conf.set("mapred.system.dir", "/mapred/system"); UnixUserGroupInformation.saveToConf(conf, UnixUserGroupInformation.UGI_PROPERTY_NAME, ugi); } // for debugging have all task output sent to the test output JobClient.setTaskOutputFilter(conf, JobClient.TaskStatusFilter.ALL); } /** * An inner class to run the corona task tracker. */ public static class TaskTrackerRunner implements Runnable { volatile CoronaTaskTracker tt; int trackerId; // the localDirs for this taskTracker String[] localDirs; volatile boolean isInitialized = false; volatile boolean isDead = false; int numDir; TaskTrackerRunner(int trackerId, int numDir, String hostname, JobConf inputConf) throws IOException { this.trackerId = trackerId; this.numDir = numDir; localDirs = new String[numDir]; JobConf conf = new JobConf(inputConf); if (hostname != null) { conf.set("slave.host.name", hostname); } conf.set("mapred.task.tracker.http.address", "0.0.0.0:0"); conf.set("mapred.task.tracker.report.address", "localhost:0"); - conf.set("mapred.task.tracker.netty.maxThreadPoolSize", 10); + conf.setInt(NettyMapOutputHttpServer.MAXIMUM_THREAD_POOL_SIZE, 10); File localDirBase = new File(conf.get("mapred.local.dir")).getAbsoluteFile(); localDirBase.mkdirs(); StringBuffer localPath = new StringBuffer(); for(int i=0; i < numDir; ++i) { File ttDir = new File(localDirBase, Integer.toString(trackerId) + "_" + 0); if (!ttDir.mkdirs()) { if (!ttDir.isDirectory()) { throw new IOException("Mkdirs failed to create " + ttDir); } } localDirs[i] = ttDir.toString(); if (i != 0) { localPath.append(","); } localPath.append(localDirs[i]); } conf.set("mapred.local.dir", localPath.toString()); LOG.info("mapred.local.dir is " + localPath); try { tt = new CoronaTaskTracker(conf); isInitialized = true; } catch (Throwable e) { isDead = true; tt = null; LOG.error("task tracker " + trackerId + " crashed", e); } } @Override public void run() { try { if (tt != null) { tt.run(); } } catch (Throwable e) { isDead = true; tt = null; LOG.error("task tracker " + trackerId + " crashed", e); } } public String[] getLocalDirs(){ return localDirs; } public CoronaTaskTracker getTaskTracker() { return tt; } public void shutdown() { if (tt != null) { try { tt.shutdown(); } catch (Throwable e) { LOG.error("task tracker " + trackerId + " could not shut down", e); } } } } public void shutdown() { try { waitTaskTrackers(); for (int idx = 0; idx < taskTrackerList.size(); idx++) { TaskTrackerRunner taskTracker = taskTrackerList.get(idx); Thread taskTrackerThread = taskTrackerThreadList.get(idx); taskTracker.shutdown(); taskTrackerThread.interrupt(); try { taskTrackerThread.join(); } catch (InterruptedException ex) { LOG.error("Problem shutting down task tracker", ex); } } } finally { File configDir = new File("build", "minimr"); File siteFile = new File(configDir, "mapred-site.xml"); siteFile.delete(); } } private void waitTaskTrackers() { for (TaskTrackerRunner runner : taskTrackerList) { while (!runner.isDead && (!runner.isInitialized || !runner.tt.isIdle())) { if (!runner.isInitialized) { LOG.info("Waiting for task tracker to start."); } else { LOG.info("Waiting for task tracker " + runner.tt.getName() + " to be idle."); } try { Thread.sleep(1000); } catch (InterruptedException ie) {} } } } } diff --git a/src/test/org/apache/hadoop/mapred/MiniMRCluster.java b/src/test/org/apache/hadoop/mapred/MiniMRCluster.java index 8526ed5..29d82f3 100644 --- a/src/test/org/apache/hadoop/mapred/MiniMRCluster.java +++ b/src/test/org/apache/hadoop/mapred/MiniMRCluster.java @@ -1,722 +1,723 @@ /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.mapred; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.fs.FileSystem; +import org.apache.hadoop.http.NettyMapOutputHttpServer; import org.apache.hadoop.net.DNSToSwitchMapping; import org.apache.hadoop.net.NetUtils; import org.apache.hadoop.net.NetworkTopology; import org.apache.hadoop.net.StaticMapping; import org.apache.hadoop.security.UnixUserGroupInformation; /** * This class creates a single-process Map-Reduce cluster for junit testing. * One thread is created for each server. */ public class MiniMRCluster { private static final Log LOG = LogFactory.getLog(MiniMRCluster.class); private Thread jobTrackerThread; private JobTrackerRunner jobTracker; private int jobTrackerPort = 0; private int taskTrackerPort = 0; private int jobTrackerInfoPort = 0; private int numTaskTrackers; private List<TaskTrackerRunner> taskTrackerList = new ArrayList<TaskTrackerRunner>(); private List<Thread> taskTrackerThreadList = new ArrayList<Thread>(); private String namenode; private UnixUserGroupInformation ugi = null; private JobConf conf; private int numTrackerToExclude; private JobConf job; /** * An inner class that runs a job tracker. */ class JobTrackerRunner implements Runnable { private JobTracker tracker = null; private volatile boolean isActive = true; JobConf jc = null; public JobTrackerRunner(JobConf conf) { jc = conf; } public boolean isUp() { return (tracker != null); } public boolean isActive() { return isActive; } public int getJobTrackerPort() { return tracker.getTrackerPort(); } public int getJobTrackerInfoPort() { return tracker.getInfoPort(); } public JobTracker getJobTracker() { return tracker; } /** * Create the job tracker and run it. */ public void run() { try { jc = (jc == null) ? createJobConf() : createJobConf(jc); File f = new File("build/test/mapred/local").getAbsoluteFile(); jc.set("mapred.local.dir",f.getAbsolutePath()); jc.setClass("topology.node.switch.mapping.impl", StaticMapping.class, DNSToSwitchMapping.class); String id = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()); tracker = JobTracker.startTracker(jc, id); tracker.offerService(); } catch (Throwable e) { LOG.error("Job tracker crashed", e); isActive = false; } } /** * Shutdown the job tracker and wait for it to finish. */ public void shutdown() { try { if (tracker != null) { tracker.stopTracker(); } } catch (Throwable e) { LOG.error("Problem shutting down job tracker", e); } isActive = false; } } /** * An inner class to run the task tracker. */ class TaskTrackerRunner implements Runnable { volatile TaskTracker tt; int trackerId; // the localDirs for this taskTracker String[] localDirs; volatile boolean isInitialized = false; volatile boolean isDead = false; int numDir; TaskTrackerRunner(int trackerId, int numDir, String hostname, JobConf cfg) throws IOException { this.trackerId = trackerId; this.numDir = numDir; localDirs = new String[numDir]; JobConf conf = null; if (cfg == null) { conf = createJobConf(); } else { conf = createJobConf(cfg); } if (hostname != null) { conf.set("slave.host.name", hostname); } conf.set("mapred.task.tracker.http.address", "0.0.0.0:0"); conf.set("mapred.task.tracker.report.address", "127.0.0.1:" + taskTrackerPort); - conf.set("mapred.task.tracker.netty.maxThreadPoolSize", 10); + conf.setInt(NettyMapOutputHttpServer.MAXIMUM_THREAD_POOL_SIZE, 10); File localDirBase = new File(conf.get("mapred.local.dir")).getAbsoluteFile(); localDirBase.mkdirs(); StringBuffer localPath = new StringBuffer(); for(int i=0; i < numDir; ++i) { File ttDir = new File(localDirBase, Integer.toString(trackerId) + "_" + 0); if (!ttDir.mkdirs()) { if (!ttDir.isDirectory()) { throw new IOException("Mkdirs failed to create " + ttDir); } } localDirs[i] = ttDir.toString(); if (i != 0) { localPath.append(","); } localPath.append(localDirs[i]); } conf.set("mapred.local.dir", localPath.toString()); LOG.info("mapred.local.dir is " + localPath); try { tt = createTaskTracker(conf); isInitialized = true; } catch (Throwable e) { isDead = true; tt = null; LOG.error("task tracker " + trackerId + " crashed", e); } } /** * Creates a default {@link TaskTracker} using the conf passed. */ TaskTracker createTaskTracker(JobConf conf) throws IOException { return new TaskTracker(conf); } /** * Create and run the task tracker. */ public void run() { try { if (tt != null) { tt.run(); } } catch (Throwable e) { isDead = true; tt = null; LOG.error("task tracker " + trackerId + " crashed", e); } } /** * Get the local dir for this TaskTracker. * This is there so that we do not break * previous tests. * @return the absolute pathname */ public String getLocalDir() { return localDirs[0]; } public String[] getLocalDirs(){ return localDirs; } public TaskTracker getTaskTracker() { return tt; } /** * Shut down the server and wait for it to finish. */ public void shutdown() { if (tt != null) { try { tt.shutdown(); } catch (Throwable e) { LOG.error("task tracker " + trackerId + " could not shut down", e); } } } } /** * Get the local directory for the Nth task tracker * @param taskTracker the index of the task tracker to check * @return the absolute pathname of the local dir */ public String getTaskTrackerLocalDir(int taskTracker) { return (taskTrackerList.get(taskTracker)).getLocalDir(); } public JobTrackerRunner getJobTrackerRunner() { return jobTracker; } TaskTrackerRunner getTaskTrackerRunner(int id) { return taskTrackerList.get(id); } /** * Get the number of task trackers in the cluster */ public int getNumTaskTrackers() { return taskTrackerList.size(); } /** * Wait until the system is idle. */ public void waitUntilIdle() { waitTaskTrackers(); JobClient client; try { client = new JobClient(job); ClusterStatus status = client.getClusterStatus(); while(status.getTaskTrackers() + numTrackerToExclude < taskTrackerList.size()) { for(TaskTrackerRunner runner : taskTrackerList) { if(runner.isDead) { throw new RuntimeException("TaskTracker is dead"); } } Thread.sleep(1000); status = client.getClusterStatus(); } } catch (IOException ex) { throw new RuntimeException(ex); } catch (InterruptedException ex) { throw new RuntimeException(ex); } } private void waitTaskTrackers() { for(Iterator<TaskTrackerRunner> itr= taskTrackerList.iterator(); itr.hasNext();) { TaskTrackerRunner runner = itr.next(); while (!runner.isDead && (!runner.isInitialized || !runner.tt.isIdle())) { if (!runner.isInitialized) { LOG.info("Waiting for task tracker to start."); } else { LOG.info("Waiting for task tracker " + runner.tt.getName() + " to be idle."); } try { Thread.sleep(1000); } catch (InterruptedException ie) {} } } } /** * Get the actual rpc port used. */ public int getJobTrackerPort() { return jobTrackerPort; } public JobConf createJobConf() { return createJobConf(new JobConf()); } public JobConf createJobConf(JobConf conf) { if(conf == null) { conf = new JobConf(); } return configureJobConf(conf, namenode, jobTrackerPort, jobTrackerInfoPort, ugi); } static JobConf configureJobConf(JobConf conf, String namenode, int jobTrackerPort, int jobTrackerInfoPort, UnixUserGroupInformation ugi) { JobConf result = new JobConf(conf); FileSystem.setDefaultUri(result, namenode); result.set("mapred.job.tracker", "localhost:"+jobTrackerPort); result.set("mapred.job.tracker.http.address", "127.0.0.1:" + jobTrackerInfoPort); if (ugi != null) { result.set("mapred.system.dir", "/mapred/system"); UnixUserGroupInformation.saveToConf(result, UnixUserGroupInformation.UGI_PROPERTY_NAME, ugi); } // for debugging have all task output sent to the test output JobClient.setTaskOutputFilter(result, JobClient.TaskStatusFilter.ALL); return result; } /** * Create the config and the cluster. * @param numTaskTrackers no. of tasktrackers in the cluster * @param namenode the namenode * @param numDir no. of directories * @throws IOException */ public MiniMRCluster(int numTaskTrackers, String namenode, int numDir, String[] racks, String[] hosts) throws IOException { this(0, 0, numTaskTrackers, namenode, numDir, racks, hosts); } /** * Create the config and the cluster. * @param numTaskTrackers no. of tasktrackers in the cluster * @param namenode the namenode * @param numDir no. of directories * @param racks Array of racks * @param hosts Array of hosts in the corresponding racks * @param conf Default conf for the jobtracker * @throws IOException */ public MiniMRCluster(int numTaskTrackers, String namenode, int numDir, String[] racks, String[] hosts, JobConf conf) throws IOException { this(0, 0, numTaskTrackers, namenode, numDir, racks, hosts, null, conf); } /** * Create the config and the cluster. * @param numTaskTrackers no. of tasktrackers in the cluster * @param namenode the namenode * @param numDir no. of directories * @throws IOException */ public MiniMRCluster(int numTaskTrackers, String namenode, int numDir) throws IOException { this(0, 0, numTaskTrackers, namenode, numDir); } public MiniMRCluster(int jobTrackerPort, int taskTrackerPort, int numTaskTrackers, String namenode, int numDir) throws IOException { this(jobTrackerPort, taskTrackerPort, numTaskTrackers, namenode, numDir, null); } public MiniMRCluster(int jobTrackerPort, int taskTrackerPort, int numTaskTrackers, String namenode, int numDir, String[] racks) throws IOException { this(jobTrackerPort, taskTrackerPort, numTaskTrackers, namenode, numDir, racks, null); } public MiniMRCluster(int jobTrackerPort, int taskTrackerPort, int numTaskTrackers, String namenode, int numDir, String[] racks, String[] hosts) throws IOException { this(jobTrackerPort, taskTrackerPort, numTaskTrackers, namenode, numDir, racks, hosts, null); } public MiniMRCluster(int jobTrackerPort, int taskTrackerPort, int numTaskTrackers, String namenode, int numDir, String[] racks, String[] hosts, UnixUserGroupInformation ugi ) throws IOException { this(jobTrackerPort, taskTrackerPort, numTaskTrackers, namenode, numDir, racks, hosts, ugi, null); } public MiniMRCluster(int jobTrackerPort, int taskTrackerPort, int numTaskTrackers, String namenode, int numDir, String[] racks, String[] hosts, UnixUserGroupInformation ugi, JobConf conf) throws IOException { this(jobTrackerPort, taskTrackerPort, numTaskTrackers, namenode, numDir, racks, hosts, ugi, conf, 0); } public MiniMRCluster(int jobTrackerPort, int taskTrackerPort, int numTaskTrackers, String namenode, int numDir, String[] racks, String[] hosts, UnixUserGroupInformation ugi, JobConf conf, int numTrackerToExclude) throws IOException { if (racks != null && racks.length < numTaskTrackers) { LOG.error("Invalid number of racks specified. It should be at least " + "equal to the number of tasktrackers"); shutdown(); } if (hosts != null && numTaskTrackers > hosts.length ) { throw new IllegalArgumentException( "The length of hosts [" + hosts.length + "] is less than the number of tasktrackers [" + numTaskTrackers + "]."); } //Generate rack names if required if (racks == null) { System.out.println("Generating rack names for tasktrackers"); racks = new String[numTaskTrackers]; for (int i=0; i < racks.length; ++i) { racks[i] = NetworkTopology.DEFAULT_RACK; } } //Generate some hostnames if required if (hosts == null) { System.out.println("Generating host names for tasktrackers"); hosts = new String[numTaskTrackers]; for (int i = 0; i < numTaskTrackers; i++) { hosts[i] = "host" + i + ".foo.com"; } } this.jobTrackerPort = jobTrackerPort; this.taskTrackerPort = taskTrackerPort; this.jobTrackerInfoPort = 0; this.numTaskTrackers = 0; this.namenode = namenode; this.ugi = ugi; this.conf = conf; // this is the conf the mr starts with this.numTrackerToExclude = numTrackerToExclude; // start the jobtracker startJobTracker(); // Create the TaskTrackers for (int idx = 0; idx < numTaskTrackers; idx++) { String rack = null; String host = null; if (racks != null) { rack = racks[idx]; } if (hosts != null) { host = hosts[idx]; } startTaskTracker(host, rack, idx, numDir); } this.job = createJobConf(conf); waitUntilIdle(); } /** * Get the task completion events */ public TaskCompletionEvent[] getTaskCompletionEvents(JobID id, int from, int max) throws IOException { return jobTracker.getJobTracker().getTaskCompletionEvents(id, from, max); } /** * Change the job's priority */ public void setJobPriority(JobID jobId, JobPriority priority) { jobTracker.getJobTracker().setJobPriority(jobId, priority); } /** * Get the job's priority */ public JobPriority getJobPriority(JobID jobId) { return jobTracker.getJobTracker().getJob(jobId).getPriority(); } /** * Get the job finish time */ public long getJobFinishTime(JobID jobId) { return jobTracker.getJobTracker().getJob(jobId).getFinishTime(); } /** * Init the job */ public void initializeJob(JobID jobId) throws IOException { JobInProgress job = jobTracker.getJobTracker().getJob(jobId); jobTracker.getJobTracker().initJob(job); } /** * Get the events list at the tasktracker */ public MapTaskCompletionEventsUpdate getMapTaskCompletionEventsUpdates(int index, JobID jobId, int max) throws IOException { String jtId = jobTracker.getJobTracker().getTrackerIdentifier(); TaskAttemptID dummy = new TaskAttemptID(jtId, jobId.getId(), false, 0, 0); return taskTrackerList.get(index).getTaskTracker() .getMapCompletionEvents(jobId, 0, max, dummy); } /** * Get jobtracker conf */ public JobConf getJobTrackerConf() { return this.conf; } public int getFaultCount(String hostName) { return jobTracker.getJobTracker().getFaultCount(hostName); } /** * Start the jobtracker. */ public void startJobTracker() { startJobTracker(true); } void startJobTracker(boolean wait) { // Create the JobTracker jobTracker = new JobTrackerRunner(conf); jobTrackerThread = new Thread(jobTracker); jobTrackerThread.start(); if (!wait) { return; } while (jobTracker.isActive() && !jobTracker.isUp()) { try { // let daemons get started Thread.sleep(1000); } catch(InterruptedException e) { } } // is the jobtracker has started then wait for it to init ClusterStatus status = null; if (jobTracker.isUp()) { status = jobTracker.getJobTracker().getClusterStatus(false); while (jobTracker.isActive() && status.getJobTrackerState() == JobTracker.State.INITIALIZING) { try { LOG.info("JobTracker still initializing. Waiting."); Thread.sleep(1000); } catch(InterruptedException e) {} status = jobTracker.getJobTracker().getClusterStatus(false); } } if (!jobTracker.isActive()) { // return if jobtracker has crashed LOG.error("Job Tracker is not active"); return; } // Set the configuration for the task-trackers this.jobTrackerPort = jobTracker.getJobTrackerPort(); this.jobTrackerInfoPort = jobTracker.getJobTrackerInfoPort(); } /** * Kill the jobtracker. */ public void stopJobTracker() { //jobTracker.exit(-1); jobTracker.shutdown(); jobTrackerThread.interrupt(); try { jobTrackerThread.join(); } catch (InterruptedException ex) { LOG.error("Problem waiting for job tracker to finish", ex); } } /** * Kill the tasktracker. */ public void stopTaskTracker(int id) { TaskTrackerRunner tracker = taskTrackerList.remove(id); tracker.shutdown(); Thread thread = taskTrackerThreadList.remove(id); thread.interrupt(); try { thread.join(); // This will break the wait until idle loop tracker.isDead = true; --numTaskTrackers; } catch (InterruptedException ex) { LOG.error("Problem waiting for task tracker to finish", ex); } } /** * Start the tasktracker. */ public void startTaskTracker(String host, String rack, int idx, int numDir) throws IOException { if (rack != null) { StaticMapping.addNodeToRack(host, rack); } if (host != null) { NetUtils.addStaticResolution(host, "localhost"); } TaskTrackerRunner taskTracker; taskTracker = new TaskTrackerRunner(idx, numDir, host, conf); addTaskTracker(taskTracker); } /** * Add a tasktracker to the Mini-MR cluster. */ void addTaskTracker(TaskTrackerRunner taskTracker) throws IOException { Thread taskTrackerThread = new Thread(taskTracker); taskTrackerList.add(taskTracker); taskTrackerThreadList.add(taskTrackerThread); taskTrackerThread.start(); ++numTaskTrackers; } /** * Get the tasktrackerID in MiniMRCluster with given trackerName. */ int getTaskTrackerID(String trackerName) { for (int id=0; id < numTaskTrackers; id++) { if (taskTrackerList.get(id).getTaskTracker().getName().equals( trackerName)) { return id; } } return -1; } /** * Shut down the servers. */ public void shutdown() { try { waitTaskTrackers(); for (int idx = 0; idx < numTaskTrackers; idx++) { TaskTrackerRunner taskTracker = taskTrackerList.get(idx); Thread taskTrackerThread = taskTrackerThreadList.get(idx); taskTracker.shutdown(); taskTrackerThread.interrupt(); try { taskTrackerThread.join(); } catch (InterruptedException ex) { LOG.error("Problem shutting down task tracker", ex); } } stopJobTracker(); } finally { File configDir = new File("build", "minimr"); File siteFile = new File(configDir, "mapred-site.xml"); siteFile.delete(); } } public static void main(String[] args) throws IOException { LOG.info("Bringing up Jobtracker and tasktrackers."); MiniMRCluster mr = new MiniMRCluster(4, "file:///", 1); LOG.info("JobTracker and TaskTrackers are up."); mr.shutdown(); LOG.info("JobTracker and TaskTrackers brought down."); } }
false
false
null
null
diff --git a/freehost3270/client/src/main/java/net/sf/freehost3270/client/RWTn3270StreamParser.java b/freehost3270/client/src/main/java/net/sf/freehost3270/client/RWTn3270StreamParser.java index d905333..1f5eff7 100644 --- a/freehost3270/client/src/main/java/net/sf/freehost3270/client/RWTn3270StreamParser.java +++ b/freehost3270/client/src/main/java/net/sf/freehost3270/client/RWTn3270StreamParser.java @@ -1,1738 +1,1742 @@ /* * Freehost3270 - A web deployment system for TN3270 clients * * Copyright (C) 1998,2001 Art Gillespie * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * The Author can be contacted at agillesp@i-no.com or * 185 Captain Whitney Road (Becket) * Chester, MA 01011 */ package net.sf.freehost3270.client; import java.io.IOException; import java.util.Enumeration; import java.util.Vector; import java.util.logging.Level; import java.util.logging.Logger; /** * This class is the mack-daddy of the 3270 Engine, it takes * the data from the RWTelnet class (through the incomingData method * of the RWTnAction interface.) and makes sense of it. * * <p> It also implements all of the commands and orders outlined in * the "3270 Data Stream Programmer's Reference" (GA23-0059-07) in * chapters 3 & 4. * * @since 0.1 */ public class RWTn3270StreamParser { private final static Logger log = Logger.getLogger(RWTn3270StreamParser.class.getName()); // this logger is used to log low level parsing operations private final static Logger logP = Logger.getLogger("net.sf.freehost3270.Parsing"); static final short[] addrTable = { 0x40, 0xC1, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, 0x50, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 0xD8, 0xD9, 0x5A, 0x5B, 0x5C, 0x5D, 0x5E, 0x5F, 0x60, 0x61, 0xE2, 0xE3, 0xE4, 0xE5, 0xE6, 0xE7, 0xE8, 0xE9, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F, 0xF0, 0xF1, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7, 0xF8, 0xF9, 0x7A, 0x7B, 0x7C, 0x7D, 0x7E, 0x7F }; private static final int[] ebc2asc = { 0, 1, 2, 3, 156, 9, 134, 127, 151, 141, 142, 11, 12, 13, 14, 15, 16, 17, 18, 19, 157, 133, 8, 135, 24, 25, 146, 143, 28, 29, 30, 31, 128, 129, 130, 131, 132, 10, 23, 27, 136, 137, 138, 139, 140, 5, 6, 7, 144, 145, 22, 147, 148, 149, 150, 4, 152, 153, 154, 155, 20, 21, 158, 26, 32, 160, 161, 162, 163, 164, 165, 166, 167, 168, 213, 46, 60, 40, 43, 124, 38, 169, 170, 171, 172, 173, 174, 175, 176, 177, 33, 36, 42, 41, 59, 126, 45, 47, 178, 179, 180, 181, 182, 183, 184, 185, 203, 44, 37, 95, 62, 63, 186, 187, 188, 189, 190, 191, 192, 193, 194, 96, 58, 35, 64, 39, 61, 34, 195, 97, 98, 99, 100, 101, 102, 103, 104, 105, 196, 197, 198, 199, 200, 201, 202, 106, 107, 108, 109, 110, 111, 112, 113, 114, 94, 204, 205, 206, 207, 208, 209, 229, 115, 116, 117, 118, 119, 120, 121, 122, 210, 211, 212, 91, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 93, 230, 231, 123, 65, 66, 67, 68, 69, 70, 71, 72, 73, 232, 233, 234, 235, 236, 237, 125, 74, 75, 76, 77, 78, 79, 80, 81, 82, 238, 239, 240, 241, 242, 243, 92, 159, 83, 84, 85, 86, 87, 88, 89, 90, 244, 245, 246, 247, 248, 249, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 250, 251, 252, 253, 254, 255 }; private static final int[] asc2ebc = { 0, 1, 2, 3, 55, 45, 46, 47, 22, 5, 37, 11, 12, 13, 14, 15, 16, 17, 18, 19, 60, 61, 50, 38, 24, 25, 63, 39, 28, 29, 30, 31, 64, 90, 127, 123, 91, 108, 80, 125, 77, 93, 92, 78, 107, 96, 75, 97, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 122, 94, 76, 126, 110, 111, 124, 193, 194, 195, 196, 197, 198, 199, 200, 201, 209, 210, 211, 212, 213, 214, 215, 216, 217, 226, 227, 228, 229, 230, 231, 232, 233, 173, 224, 189, 154, 109, 121, 129, 130, 131, 132, 133, 134, 135, 136, 137, 145, 146, 147, 148, 149, 150, 151, 152, 153, 162, 163, 164, 165, 166, 167, 168, 169, 192, 79, 208, 95, 7, 32, 33, 34, 35, 36, 21, 6, 23, 40, 41, 42, 43, 44, 9, 10, 27, 48, 49, 26, 51, 52, 53, 54, 8, 56, 57, 58, 59, 4, 20, 62, 225, 65, 66, 67, 68, 69, 70, 71, 72, 73, 81, 82, 83, 84, 85, 86, 87, 88, 89, 98, 99, 100, 101, 102, 103, 104, 105, 112, 113, 114, 115, 116, 117, 118, 119, 120, 128, 138, 139, 140, 141, 142, 143, 144, 106, 155, 156, 157, 158, 159, 160, 170, 171, 172, 74, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 161, 190, 191, 202, 203, 204, 205, 206, 207, 218, 219, 220, 221, 222, 223, 234, 235, 236, 237, 238, 239, 250, 251, 252, 253, 254, 255 }; /****************************************************************/ /* TN3270 Commands */ /* See "Data Stream Programmer's reference p. 3.3 */ /****************************************************************/ /** * Write command p. 3.5.1 */ final static short CMD_W = 0x01; final static short CMD_W_EBCDIC = 0xF1; /** * Erase/Write command p. 3.5.2 */ final static short CMD_EW = 0x05; final static short CMD_EW_EBCDIC = 0xF5; /** * Erase/Write Alternate command p 3.5.3 */ final static short CMD_EWA = 0x0D; final static short CMD_EWA_EBCDIC = 0x7E; /** * Read Buffer Command p 3.6.1 */ final static short CMD_RB = 0x02; final static short CMD_RB_EBCDIC = 0xF2; /** * Read Modified Command p 3.6.2 */ final static short CMD_RM = 0x06; final static short CMD_RM_EBCDIC = 0xF6; /** * Read Modified All Command p 3.6.2.5 */ final static short CMD_RMA = 0x0E; final static short CMD_RMA_EBCDIC = 0x6E; /** * Erase all unprotected command p. 3.5.5 */ final static short CMD_EAU = 0x0F; final static short CMD_EAU_EBCDIC = 0x6F; /** * Write Structured Field command p. 3.5.4 (Not supported in ASCII) */ final static short CMD_WSF = 0x11; final static short CMD_WSF_EBCDIC = 0xF3; /** * No-op */ final static short CMD_NOOP = 0x03; /*************************************************************/ /* TN3270 ORDERS */ /* p 4.3 table 4-1 */ /*************************************************************/ /** * Start Field Order p 4.3.1 */ final static short ORDER_SF = 0x1D; /** * Start Field Extended p 4.3.2 */ final static short ORDER_SFE = 0x29; /** * Set Buffer Address p 4.3.3 */ final static short ORDER_SBA = 0x11; /** * Set Attribute p 4.3.4 */ final static short ORDER_SA = 0x28; /** * Modify Field p 4.3.5 */ final static short ORDER_MF = 0x2C; /** * Insert Cursor p 4.3.6 */ final static short ORDER_IC = 0x13; /** * Program Tab p 4.3.7 */ final static short ORDER_PT = 0x05; /** * Repeat to Address p 4.3.8 */ final static short ORDER_RA = 0x3C; /** * Erase Unprotected to Address p 4.3.9 */ final static short ORDER_EUA = 0x12; /** * Graphic Escape p 4.3.10 */ final static short ORDER_GE = 0x08; /********************************************************************/ /* Extended Attributes (see table 4-6 p 4.4.5) */ /********************************************************************/ /** * 3270 Field Attributes p 4.4.6.2 */ final static short XA_SF = 0xC0; /** * Field Validation p 4.4.6.3 */ final static short XA_VALIDATION = 0xC1; /** * Field Outlining p 4.4.6.6 */ final static short XA_OUTLINING = 0xC2; /** * Extended Highlighting p 4.4.6.3 */ final static short XA_HIGHLIGHTING = 0x41; /** * Foreground Color p 4.4.6.4 */ final static short XA_FGCOLOR = 0x42; /** * Character Set 4.4.6.5 */ final static short XA_CHARSET = 0x43; /** * Background Color p 4.4.6.4 */ final static short XA_BGCOLOR = 0x45; /** * Transparency p 4.4.6.7 */ final static short XA_TRANSPARENCY = 0x46; final static short SF_RPQ_LIST = 0x00; final static short SF_READ_PART = 0x01; final static short SF_RP_QUERY = 0x02; final static short SF_RP_QLIST = 0x03; final static short SF_RPQ_EQUIV = 0x40; final static short SF_RPQ_ALL = 0x80; private RW3270 rw; private RW3270Char[] chars; private char[] display; private RWTelnet tn; protected RWTnAction client; private Vector fields; private int counter; private short[] dataIn; private int dataInLen; private boolean lastWasCommand; private int bufferAddr; private short foreground; private short background; private short highlight; public RWTn3270StreamParser(RW3270 rw, RWTnAction client) { this.client = client; this.rw = rw; display = rw.getDisplay(); } /** * This method takes an input buffer and executes the appropriate * tn3270 commands and orders. */ protected synchronized void parse(short[] inBuf, int inBufLen) throws IOException { if (log.isLoggable(Level.FINEST)) { StringBuffer inBufStr = new StringBuffer("parsing buffer: "); for (int i = 0; i < inBufLen; i++) { // prepending the hex digit with 0x prefix for // convenience of putting dumped data into tests inBufStr.append("0x").append(Integer.toHexString(inBuf[i])) .append(", "); } log.finest(inBufStr.toString()); } else if (log.isLoggable(Level.FINE)) { log.fine("parsing buffer"); } bufferAddr = rw.getCursorPosition(); fields = rw.getFields(); chars = rw.getDataBuffer(); dataIn = inBuf; dataInLen = inBufLen; //is the first byte an EBCDIC cmd, if so convert it switch (dataIn[0]) { case CMD_W_EBCDIC: dataIn[0] = CMD_W; break; case CMD_EW_EBCDIC: dataIn[0] = CMD_EW; break; case CMD_EWA_EBCDIC: dataIn[0] = CMD_EWA; break; case CMD_EAU_EBCDIC: dataIn[0] = CMD_EAU; break; case CMD_WSF_EBCDIC: dataIn[0] = CMD_WSF; break; case CMD_RB_EBCDIC: dataIn[0] = CMD_RB; break; case CMD_RM_EBCDIC: dataIn[0] = CMD_RM; break; case CMD_RMA_EBCDIC: dataIn[0] = CMD_RMA; break; } //now let's send the commands off to their appropriate methods: switch (dataIn[0]) { case CMD_W: case CMD_EW: case CMD_EWA: case CMD_EAU: log.finest("write operation"); lastWasCommand = true; writeOperation(); buildFields(); client.incomingData(); break; case CMD_WSF: lastWasCommand = true; log.finest("WSF"); writeStructuredField(dataIn); break; case CMD_RB: lastWasCommand = true; //System.out.println("Read Buffer..."); readBuffer(); break; case CMD_RM: lastWasCommand = true; //System.out.println("Read Modified..."); readModified(); break; case CMD_RMA: lastWasCommand = true; //System.out.println("Read Modified All..."); readModifiedAll(); break; default: throw new IOException("Invalid 3270 Command"); } rw.resumeParentThread(); } /** * From <i>3270 Data Stream Programmer's Reference</i>: * <h3>3.5 Write Operation</h3> * The process of sending a write type command and performing that command * is called a <i>write</i> operation. Five write commands are initiated by * the application program and performed by the display: * <UL> * <LI>Write(W)</LI> * <LI>Erase/Write(EW)</LI> * <LI>Erase/Write Alternate(EWA)</LI> * <LI>Erase All Unprotected(EAU)</LI> * <LI>Write Structured Field(WSF)</LI> * </UL> * * <i>From 3.1</i> * The format of a write command is as follows: * <table border="1"> * <tr><th>Byte 1</th><th>Byte 2</th><th>Byte 3 ... <i>n</i></th></tr> * <tr><td align="center">Write Command</td> * <td align="center">WCC (Write Control Character)</td> * <td align="center">Orders and Data</td> * </tr> * </table> * * <h3>3.4 Write Control Character (WCC) Byte</h3> * The following table explains the interpretation of the WCC byte * <table border="1"> * <TR><TH colspan = 2>Table 3-2. Write Control Character (WCC) Bit Definitions for Displays</TH></TR> * <TR><TH>Bit</TH><TH>Explanation</TH></TR> * <TR><TD>0</TD><TD>N/A</TD></TR> * <TR><TD>1</TD><TD>WCC reset bit. When set to 1, it resets partition * characteristics to their system-defined defaults. When set to 0, the * current characteristics remain unchanged (no reset operations are performed).</TD></TR> * <TR><TD>2, 3 & 4</TD><TD>Printer Operations N/A</TD></TR> * <TR><TD>5</TD><TD>Sound alarm bit. When set to 1, it sounds the audible alarm * at the end of the operation if that device has an audible alarm.</TD></TR> * <TR><TD>6</TD><TD>Keyboard Restore Bit. When set to 1, this bit unlocks the keyboard. * it also resets the AID byte.</TD></TR> * <TR><TD>7</TD> * <TD>Bit 7 resets MDT bits in the field attributes. When set to 1, all * MDT bits in the device's existing character buffer are reset before any * data is written or orders are performed.</TD></TR></TABLE> * */ private synchronized void writeOperation() { if (dataIn[0] == CMD_EAU) { logP.fine("erase all unprotected"); eraseAllUnprotected(); return; } //now let's check the WCC for bit 0 if ((dataIn[1] & 0x01) != 0) { //Bit 7 is set to 1, reset all modified bits logP.fine("reset MDT"); resetMDT(); lastWasCommand = true; } switch (dataIn[0]) { case CMD_EW: case CMD_EWA: //System.err.println("Erase Write..."); lastWasCommand = true; eraseWrite(); break; case CMD_W: //System.err.println("Write..."); lastWasCommand = true; write(); break; } //check the post-operation functions in the WCC if ((dataIn[1] & 0x04) != 0) { //Bit 5 is set to 1 beep(); } if ((dataIn[1] & 0x02) != 0) { //Bit 2 is set to 1 rw.unlockKeyboard(); client.status(RWTnAction.READY); } } /** * <h3>3.5.1 Write Command</h3> * The Write command writes data into specified locations of the character * buffer of partition 0 without erasing or modifying data in the other * locations. Data is stored in sucessive buffer locations until an order * is encountered in the data stream that alters the buffer address, or until * all the data has been stored. During the write operation, the buffer * address is advanced one location as each character is stored. */ private synchronized void write() { lastWasCommand = true; //System.out.println(dataInLen); for (counter = 2; counter < dataInLen; counter++) { switch (dataIn[counter]) { case ORDER_SF: //System.err.println("SF: " + bufferAddr + " "); startField(); lastWasCommand = true; break; case ORDER_SFE: //System.err.println("SFE " + bufferAddr + " "); startFieldExtended(); lastWasCommand = true; break; case ORDER_SBA: //System.err.println("SBA " + bufferAddr + " "); bufferAddr = setBufferAddress(); //System.err.println("to: " + bufferAddr); lastWasCommand = true; break; case ORDER_SA: //System.err.println("SA " + bufferAddr + " "); setAttribute(); lastWasCommand = true; break; case ORDER_MF: //System.err.println("MF " + bufferAddr + " "); modifyField(); lastWasCommand = true; break; case ORDER_IC: //System.err.println("IC " + bufferAddr + " "); insertCursor(); lastWasCommand = true; break; case ORDER_PT: //System.err.println("PT " + lastWasCommand + " " + bufferAddr); programTab(); //System.out.println(" " + bufferAddr); break; case ORDER_RA: //System.err.print("RA " + bufferAddr + " "); repeatToAddress(); lastWasCommand = true; break; case ORDER_EUA: //System.err.print("EUA " + bufferAddr + " "); eraseUnprotectedToAddress(); lastWasCommand = true; break; case ORDER_GE: //System.err.print("GE " + " "); graphicEscape(); lastWasCommand = true; break; default: display[bufferAddr] = (dataIn[counter] == 0x00) ? ' ' : (char) ebc2asc[dataIn[counter]]; RW3270Char currChar = (RW3270Char) chars[bufferAddr++]; currChar.clear(); currChar.setChar((char) ebc2asc[dataIn[counter]]); //System.out.print(currChar.getChar()); currChar.setForeground(foreground); currChar.setBackground(background); currChar.setHighlighting(highlight); lastWasCommand = false; if (bufferAddr == chars.length) { bufferAddr = 0; } } } } /** * <h3>3.5.2 Erase/Write Command</h3> * The EW command does the following: * <UL> * <LI>Sets the implicit partition size to the default size, if in implicit * state</LI> * <LI>Resets a Program Check Indication, if one exists.</LI> * <LI>Erases the character buffer by writing null characters into all buffer * locations.</LI> * <LI>Sets all the associated character attributes and extended field attributes * to their default value(X'00).</LI> * <LI>Erases all field validation attributes.</LI> * <LI>Sets the current cursor position to 0. If directed to a partition, * autoscroll is performed, if necessary, to position the window at offset * (0, 0).</LI> * <LI>If bit 1 of the WCC is set to 1, EW does the following: </LI> * <UL> * <LI>Resets the inbound reply mode to Field.</LI> * <LI>Resets to implicit partition state, if currently in explicit * partitioned state. It destroys all partitions, creates implicit * partition 0 with default screen size, and sets inboud PID to 0 and * INOP to Read Modified.</LI> * </UL> * <LI>Provides an acknoledgment of any outstanding read or enter if the * keyboard restore bit in the WCC is set to 1.</LI> * <LI>Performs a write operation</LI> * </UL> */ private synchronized void eraseWrite() { //set all buffer positions to 'null' for (int i = 0; i < chars.length; i++) { ((RW3270Char) chars[i]).clear(); display[i] = ' '; } rw.setCursorPosition((short) 0); bufferAddr = 0; write(); } /** * <h3>3.5.5 Erase All Unprotected Command</h3> * EAU does the following: * <UL> * <LI>Clears all the unprotected character locations of the partition * to nulls and sets any character attributes affected to their default * values.</LI> * <LI>Resets to 0 the MDT bit in the field attribute for each unprotected field</LI> * <LI>Unlocks the keyboard</LI> * <LI>Resets the AID</LI> * <LI>Repositions the cursor to the first character location, after * the field attribute, in the first unprotected field of the * partition's character buffer.</LI> * </UL> */ private synchronized void eraseAllUnprotected() { for (int i = 0; i < chars.length; i++) { RW3270Char c = (RW3270Char) chars[i]; RW3270Field f = c.getField(); if ((f != null) && !f.isProtected()) { display[i] = ' '; c.clear(); try { f.setModified(false); } catch (Exception e) { log.warning(e.getMessage()); } } else if (f == null) { //not in a field -- unprotected by default c.clear(); } //unlock the keyboard rw.unlockKeyboard(); //move the cursor to the first unprotected field rw.setCursorPosition((short) 0); rw.setCursorPosition(rw.getNextUnprotectedField( rw.getCursorPosition())); //TO-DO reset the AID } } /** * <h3>3.5.4 Write Structured Field</h3> * WSF is used to send structured fields from the spplication program * to the display. On the application-to-display flow [outbound], structured * fields can be sent only with the WSF command. *<P> * The format of a WSF data stream is as follows: * <TABLE border = 1> * <TR><TD>WSF Command</TD><TD>Structured Field</TD><TD>Structured Field...</TD></TR></TABLE> *</P> * In our case, we're really only concerned with responding to * queries, so we can inform the host of our capabilities on demand. * Query replies are covered in agonizing detail in chapter 6 of the * <i>3270 Data Stream Programmer's Reference</i>. Suffice it to say * That we're telling the host: * <LI>How big our screen is</LI> * <LI>How many colors we support</LI> * <LI>Do we handle outlining</LI> */ private synchronized void writeStructuredField(short[] buf) { log.finest("Write Structured Field..."); int cmnd; int length; int offset; int nleft; int pid; int sfid; int type; int buflen; int i; int n; buflen = buf.length; offset = 1; nleft = buflen - 1; while (nleft > 0) { if (nleft < 3) { return; //WSF too small } length = (buf[offset] << 8) + buf[offset + 1]; sfid = buf[offset + 2]; switch (sfid) { case SF_READ_PART: /* * Read Partion - p. 5-47 */ if (length < 5) { return; //WSF-RP too small } pid = buf[offset + 3]; type = buf[offset + 4]; /* Check to see if it is a Query 0x02 */ switch( type ) { case SF_RP_QUERY: if( pid != 0xFF ) return; try { short[] queryReply = buildQueryReply( 2, true ); rw.getTelnet().sendData(queryReply, queryReply.length); } catch (IOException e) { log.severe(e.getMessage()); } break; case SF_RP_QLIST: if( pid != 0xFF ) return; switch( buf[offset + 5] ) { case SF_RPQ_LIST: System.out.println( "List" ); return; case SF_RPQ_EQUIV: System.out.println( "Equivalent+List" ); return; case SF_RPQ_ALL: System.out.println( "All" ); try { short[] queryReply = buildQueryReply( 2, true ); rw.getTelnet().sendData(queryReply, queryReply.length); } catch (IOException e) { log.severe(e.getMessage()); } break; } break; default: return; } break; case SF_RPQ_EQUIV: /* * Outbound 3270DS - p. 5-41 */ if (length < 5) { return; //WSF-OBDS too small } pid = buf[offset + 3]; cmnd = buf[offset + 4]; if (pid != 0x00) { return; //WSF-OBDS invalid PID } switch (cmnd) { case CMD_W_EBCDIC: case CMD_EW_EBCDIC: case CMD_EWA_EBCDIC: case CMD_EAU_EBCDIC: n = length - 4; dataIn = new short[n]; for (i = 0; i < n; ++i) { dataIn[i] = buf[i + 4]; } writeOperation(); break; default: return; //WSF-OBDS unsupported } break; default: return; //unsupported WFS ID } offset += length; nleft -= length; } } /** <h2>3.6 Read Operations</h2> * The process of sending data inbound is called a <i>read operation</i>. * A read operation can be initiated by the following: * <UL> * <LI>The host application sending an explicit read command</LI> * <LI>The host application program sending a Read Partition structured * field specifying Read Buffer, Read Modified, or Read Modified All.</LI> * <LI>An operator action, for example, pressing the Enter key.</LI> * </UL> * A read operation sends an inbound data stream (from the terminal to the * application program) with an AID byte as the first byte of the inbound * data stream. The inbound data stream usually consists of an AID followed * by the cursor address (2 bytes). These 3 bytes of the read data stream * the AID, and cursor address are known as the <i>read heading</i>. The inbound * data stream format is as follows: * <P> * <TABLE border = 1> * <TR><TH>Byte 1</TH><TH>Byte 2</TH><TH>Byte 3</TH><TH>Byte 4</TH></TR> * <TR><TD>AID</TD><TD colspan = 2>Cursor Address (2 bytes)</TD><TD>Data</TD></TR> * </TABLE> * </P> * <h2>3.6.1 Read Commands</h2> * Three read commands can be sent by the application program: Read Buffer * Read Modified, and Read Modified All. * </h3>3.6.1.1 Read Buffer Command</h3> * Operation of the Read Buffer command causes all data in the addressed * display buffer, from the buffer location at which reading starts through * the last buffer location, to be transmitted to the host. For displays * the transfer of data begins from buffer address 0. */ private synchronized void readBuffer() { int byteCount = 0; short[] dataOut = new short[((chars.length) * 2) + 40]; //get the current AID dataOut[byteCount++] = rw.getAID(); //convert the current cursor position to 14-bit addressing dataOut[byteCount++] = addrTable[(rw.getCursorPosition() >> 6) & 0x3F]; dataOut[byteCount++] = addrTable[rw.getCursorPosition() & 0x3F]; //iterate through the screen buffer, if a position //contains an FA send it instead of the character. for (int i = 0; i < (chars.length); i++) { RW3270Char currChar = (RW3270Char) chars[i]; if (currChar.isStartField()) { dataOut[byteCount++] = ORDER_SF; dataOut[byteCount++] = currChar.getFieldAttribute(); } else { dataOut[byteCount++] = (short) asc2ebc[currChar.getChar()]; } } try { rw.getTelnet().sendData(dataOut, byteCount); } catch (IOException e) { } } /** * <h3>3.6.2.1 Read Modified Operation</h3> * During a read modified operation, if an AID other than selector pen * attention, cursor select key, PAkey, or Clear key is generated, all * fields that have been modified by keyboard, selector pen, or magnetic * reader activity are transferred to the application program. A major * feature of the read modified operation is null suppression. Only * non-null character data and corresponding character attribute data (in * Character mode)are transmitted. All null character data and all extended * attributes for null character data are suppressed. * <BR><BR> * If a space or null selector pen AID is generated, fields are not * transferred to main storage during the read modified operation. Instead, * when a set MDTbit is found (indicating selector pen and/or keyboard * activity), only the read heading, the SBA order code, and the attribute * address +1 are transferred. * <BR><BR> * If the buffer is unformatted (contains no fields), the read data stream * consists of the 3-byte read heading followed by all alphanumeric data in * the buffer (nulls are suppressed), even when part or all of the data has * not been modified. Since an unformatted buffer contains no attribute bytes * no SBA codes with associated addresses or address characters included in the * data stream, and the modification of data cannot be determined. * Data transfer starts at address 0 and continues to the end of the buffer. * At the end of the operation, the buffer address is set to 0. */ protected synchronized void readModified() { client.status(RWTnAction.X_WAIT); rw.lockKeyboard(); int byteCount = 0; short[] dataOut = new short[(chars.length * 2) + 40]; dataOut[byteCount++] = rw.getAID(); switch (rw.getAID()) { case RW3270.PA1: case RW3270.PA2: case RW3270.PA3: case RW3270.CLEAR: try { rw.getTelnet().sendData(dataOut, byteCount); } catch (Exception e) { } return; } //cursor position dataOut[byteCount++] = addrTable[(rw.getCursorPosition() >> 6) & 0x3F]; dataOut[byteCount++] = addrTable[rw.getCursorPosition() & 0x3F]; //are there any fields? (formatted/unformatted) if (fields.size() == 0) { for (int i = 0; i < chars.length; i++) { RW3270Char currChar = (RW3270Char) chars[i]; if (currChar.getChar() != ' ') { dataOut[byteCount++] = (short) asc2ebc[currChar.getChar()]; } } try { rw.getTelnet().sendData(dataOut, byteCount); } catch (IOException e) { } bufferAddr = 0; return; } //get an enumeration of the current fields Enumeration e = fields.elements(); //iterate through the fields, checking for modification while (e.hasMoreElements()) { RW3270Field f = (RW3270Field) e.nextElement(); if (f.isModified()) { //field has been modified... get characters stored in the //field. RW3270Char[] fieldChars = f.getChars(); //send an SBA on the beginning of this field + 1 //(ignore the field attribute) dataOut[byteCount++] = ORDER_SBA; dataOut[byteCount++] = addrTable[((f.getBegin() + 1) >> 6) & 0x3F]; dataOut[byteCount++] = addrTable[(f.getBegin() + 1) & 0x3F]; //put the characters in the output buffer for (int i = 1; i < fieldChars.length; i++) { if (fieldChars[i].getChar() != 0) //null suppression { dataOut[byteCount++] = (short) asc2ebc[fieldChars[i].getChar()]; //System.out.print("Hey..." + fieldChars.length + fieldChars[i].getChar()); } } } } try { //System.out.println("Sending data..."); rw.getTelnet().sendData(dataOut, byteCount); } catch (IOException ioe) { log.warning("exception in readModified: " + ioe.getMessage()); } } private synchronized void readModifiedAll() { readModified(); } private synchronized void resetMDT() { Enumeration e = fields.elements(); while (e.hasMoreElements()) { try { ((RW3270Field) e.nextElement()).setModified(false); } catch (IsProtectedException ipe) { //the field is protected, how can it be modified? Move on. log.finest("the field is protected. pass it"); } } } private void beep() { //TODO: Add beep code here... use a callback interface to the consumer. //System.out.println("Beep.."); log.fine("beep"); } /** * <h3>4.3.1 Start Field(SF)</h3> * The SF order indicates the start of a field. * <h3>Table 4-4 - Bit Definitions for 3270 Field Attributes</h3> * <TABLE border = 1> * <TR><TH>Bit</TH><TH>Description</th></tr> * <TR><TD>0, 1</td><td>N/A</td></tr> * <TR><TD>2</TD><TD>0 - Field is Unprotected<BR> * 1 - Field is Protected</TD></TR> * <TR><TD>3</TD><TD>0 - Alphanumeric<BR> * 1 - Numeric</TD></TR> * <TR><TD>4, 5</TD><TD>00 - Display/not selector pen detectable<BR> * 01 - Display/selector pen detectable<BR> * 10 - Intensified display/selector pen detectable(BOLD)<BR> * 11 - Nondisplay, nondetectable (PASSWORDS, etc.)</TD></TR> * <TR><TD>6</TD><TD>Reserved. Must Always be 0</TD></TR> * <TR><TD>7</TD><TD>MDT identifies modified fields during Read Modified Command * operations.<BR> * 0 - Field has not been modified.<BR> * 1 - Field has been modified by the operator.<BR></TD></TR> * */ private synchronized void startField() { ((RW3270Char) chars[bufferAddr]).clear(); //increment the buffer address, //and clear the existing character ((RW3270Char) chars[bufferAddr]).setStartField(); ((RW3270Char) chars[bufferAddr]).setFieldAttribute(dataIn[++counter]); display[bufferAddr] = ' '; if (++bufferAddr == chars.length) { bufferAddr = 0; } } /** * <h3>4.3.2 Start Field Extended (SFE)</h3> * The SFE order is also used to indicate the start of a field. However, * the SFE control sequence contains information on the field's properties that * are described in the extended field attribute. The SFE order has the * following format: * <TABLE border=1> * <TR><TD>0x29</TD><TD>Number of Attribute Type-Value pairs</TD><TD>Attribute Type</TD><TD>Attribute Value</TD></TR> * </TABLE> */ private synchronized void startFieldExtended() { counter++; ((RW3270Char) chars[bufferAddr]).clear(); display[bufferAddr] = ' '; int pairs = dataIn[counter]; //get the number of attribute type pairs if (!((RW3270Char) chars[bufferAddr]).isStartField()) { // Hard-learned lesson: if no StartField is specified, // but extended attributes have been defined, you must // define a default start field. ((RW3270Char) chars[bufferAddr]).clear(); ((RW3270Char) chars[bufferAddr]).setStartField(); ((RW3270Char) chars[bufferAddr]).setFieldAttribute((short) 0x00); } for (int i = 0; i < pairs; i++) { //System.out.println("SFE: " + Integer.toHexString(dataIn[++counter])); switch (dataIn[++counter]) { // get the next value from dataIn // which will tell us what kind of attribute // it is case XA_SF: // same as SF command above ((RW3270Char) chars[bufferAddr]).setStartField(); ((RW3270Char) chars[bufferAddr]).setFieldAttribute(dataIn[++counter]); break; case XA_VALIDATION: ((RW3270Char) chars[bufferAddr]).setValidation(dataIn[++counter]); break; case XA_OUTLINING: ((RW3270Char) chars[bufferAddr]).setOutlining(dataIn[++counter]); break; case XA_HIGHLIGHTING: ((RW3270Char) chars[bufferAddr]).setHighlighting(dataIn[++counter]); break; case XA_FGCOLOR: ((RW3270Char) chars[bufferAddr]).setForeground(dataIn[++counter]); break; case XA_CHARSET: //not supported - nightmare counter++; break; case XA_BGCOLOR: ((RW3270Char) chars[bufferAddr]).setBackground(dataIn[++counter]); break; case XA_TRANSPARENCY: //not supported - What does it do? counter++; break; } } bufferAddr++; } /** * <h3>4.3.3 Set Buffer Address</h3> * The Set Buffer Address function converts a two-byte segment into * an integer corresponding to the buffer address. If the first 2 bits * of the first byte are 00, it signals that a 14-bit binary address follos * (the remaining 6 bits of byte 1 and 8 bits of byte 2). This is easily * arrived at by shifting the first byte 8 positions left and adding the second * byte. If the first two bits of the first byte contain any other bit * pattern (01, 10, 11), the two bytes comprise a 12-bit coded address which * can be arrived at by <code>((counter1 & 0x3F) << 6) + (counter2 & 0x3F)</code> */ private synchronized int setBufferAddress() { int counter1 = dataIn[++counter]; int counter2 = dataIn[++counter]; if ((counter1 & 0xC0) == 0x00) { return ((counter1 & 0x3F) << 8) + counter2; } else { return ((counter1 & 0x3F) << 6) + (counter2 & 0x3F); } } /** * <h3>4.3.4 Set Attribute(SA)</h3> * The SA order is used to specify a character's attribute type and its value * so that subsequently interpreted characters in the data stream apply * the character properties defined by the type-value pair. The format * of the SA control sequence is as follows: * <TABLE border=1> * <TR> * <TD>0x28</TD><TD>Attribute Type</TD><TD>Attribute Value</TD> * </TR> * </TABLE> */ private synchronized void setAttribute() { int att = dataIn[++counter]; switch (att) { case 0: foreground = 247; background = 240; highlight = 240; return; case XA_HIGHLIGHTING: highlight = dataIn[++counter]; return; case XA_FGCOLOR: foreground = dataIn[++counter]; return; case XA_BGCOLOR: background = dataIn[++counter]; return; default: return; } } /** * <h3>4.3.5 Modify Field (MF)</h3> * The MF order begins a sequence that updates field and extended field * attributes at the current buffer address. After the attributes have * been updated, the current buffer address is incremented by one. * <P>The MF control sequence has the following format: * </P> * <TABLE border=1> * <TR> * <TD>0x2C</TD><TD>Number of Attribute Type/Value Pairs</TD> * <TD>Attribute Type</TD><TD>Attribute Value</TD> * </TR> * </TABLE> * Gotchas:<BR> * * <UL> * <li><b>Attribute types not specified remain unchanged</b></li> * <li><b>If the current buffer address is not a field attribute, the MF * order should be rejected</b></li> * </ul> */ private synchronized void modifyField() { // reject if not a FA RW3270Char currChar = (RW3270Char) chars[bufferAddr]; //System.out.println(" " + currChar.isStartField()); if (!currChar.isStartField()) { return; } int pairs = dataIn[++counter]; for (int i = 0; i < pairs; i++) { //System.out.println("Attribute to modify: " + Integer.toHexString(dataIn[++counter])); switch (dataIn[++counter]) { case ORDER_SFE: case ORDER_SF: case XA_SF: currChar.setFieldAttribute(dataIn[++counter]); break; case XA_VALIDATION: currChar.setValidation(dataIn[++counter]); break; case XA_HIGHLIGHTING: currChar.setHighlighting(dataIn[++counter]); break; case XA_FGCOLOR: currChar.setForeground(dataIn[++counter]); break; case XA_BGCOLOR: currChar.setBackground(dataIn[++counter]); break; case XA_OUTLINING: currChar.setOutlining(dataIn[++counter]); break; default: counter++; } } bufferAddr++; } /** * <h3>4.3.6 Insert Cursor (IC)</h3> * The IC order repositions the cursor to the locations specified by the * current buffer address. Execution of this order does not change the * current buffer address. */ private synchronized void insertCursor() { rw.setCursorPosition((short) bufferAddr); } /** * <h3>4.3.7 Program Tab (PT)</h3> * The PT order advances the current buffer address to the address of * the first character position of the next unprotected field. If PT * is issued when the current buffer address is the location of a field * attribute of an unprotected field, the buffer advances to the next * location of that field (one location). In addition, if PT does not * immediately follow a command order, or order sequence (such as after * the WCC, IC, and RA respectively), nulls are inserted in the buffer * from the current buffer address to the end of the field, regardless of * the value of bit 2 (protected/unprotected) of the field attribute for * the field. When PT immediately follows a command, order, or order * sequence, the buffer is not modified. */ private synchronized void programTab() { log.finest("Program Tab..."); int newAddr; int oldAddr = bufferAddr; newAddr = rw.getNextUnprotectedField(bufferAddr); //System.out.println("next unprotected: " + newAddr); if (newAddr <= bufferAddr) { bufferAddr = 0; } else { bufferAddr = newAddr; } if (!lastWasCommand) { //if bufferAddr = 0, there's no more FAs so //clear from here. //if(!chars[oldAddr].getField().isProtected()) // newAddr = oldAddr; //else RW3270Char currChar = null; while ((oldAddr < chars.length) && !(currChar = chars[oldAddr]).isStartField()) { currChar.clear(); oldAddr++; } //System.out.println("Buffer Address.." + bufferAddr); /* newAddr = (bufferAddr == 0)?oldAddr:bufferAddr; System.out.println("Get field..." + newAddr); int end = 0; try { end = chars[oldAddr].getField().getEnd(); } catch(NullPointerException e) { e.printStackTrace(); } System.out.println("Clearing: " + oldAddr + " to " + end); for(int c = oldAddr; c <= end; c++) { try { chars[c].clear(); display[c] = ' '; } catch(ArrayIndexOutOfBoundsException e){} } */ } } /** * <h3>4.3.8 Repeat to Address (RA)</h3> * The RA order stores a specified character in all character buffer * locations, starting at the current bufer address and ending at * (but not including) the specified stop address. */ private synchronized void repeatToAddress() { //counter++; int address = setBufferAddress(); int charIn = dataIn[++counter]; char c = (char) ebc2asc[charIn]; while (bufferAddr != address) { RW3270Char currChar = (RW3270Char) chars[bufferAddr]; currChar.clear(); currChar.setForeground(foreground); currChar.setBackground(background); currChar.setHighlighting(highlight); currChar.setChar(c); display[bufferAddr] = c; if (++bufferAddr > (chars.length - 1)) { bufferAddr = 0; } } } /** * <h3>4.3.9 Erase Unprotected to Address (EUA)</h3> * The EUA Order stores nulls in all unprotected character locations, * starting at the current buffer address and ending at, but not * including, the specified stop address. */ private synchronized void eraseUnprotectedToAddress() { //counter++; int address = setBufferAddress(); if (address == bufferAddr) { eraseAllUnprotected(); } while (bufferAddr < address) { RW3270Char currChar = (RW3270Char) chars[bufferAddr]; RW3270Field f = currChar.getField(); if (!f.isProtected()) { currChar.setChar((char) 0); display[currChar.getPosition()] = ' '; if (currChar.isStartField()) { currChar.isModified(false); } } if (++bufferAddr > (chars.length - 1)) { bufferAddr = 0; } } } private synchronized void graphicEscape() { //not supported counter++; } /** * This is a utility method that builds the field vector after data comes in by reading * the data buffer and creating a Field Object for each Start Field character. * * <p> The Field objects merely 'point' the the corresponding * Start Field character for conceptual ease for end-programmers. * No data is 'contained' in a field object */ private synchronized void buildFields() { fields.removeAllElements(); RW3270Field lastField = null; for (int i = 0; i < chars.length; i++) { RW3270Char currChar = chars[i]; if (currChar.isStartField()) { if (lastField != null) { lastField.setEnd(i - 1); } //since it's a Start Field FA, create a new field RW3270Field currField = new RW3270Field(currChar, rw); //set it's begin point as the current counter position currField.setBegin(i); //add it to the fields vector fields.addElement(currField); //move it to the last field variable, so we can set its //end point. lastField = currField; } currChar.setField(lastField); } // now we have to find the end point for the last field. We // can't just set it to the last address in the buffer, // because fields that aren't terminated wrap to the beginning // of the buffer. if (fields.size() > 0) { RW3270Field firstField = (RW3270Field) fields.elementAt(0); lastField.setEnd((firstField.getBegin() == 0) ? chars.length : (firstField.getBegin() - 1)); for (int c = 0; c < firstField.getBegin(); c++) { chars[c].setField(lastField); } } } /** * This method builds the reply packet to send to the host, it contains our capabilities * as a 3270 host. * */ private synchronized short[] buildQueryReply( int model, boolean summary ) { /* * We have several capabilities which we need to report * 1. Color * 2. Highlighting * 3. Partition */ final short HIGHLIGHT_DEFAULT = 0x00; final short HIGHLIGHT_NORMAL = 0xF0; final short HIGHLIGHT_BLINK = 0xF1; final short HIGHLIGHT_REVERSE = 0xF2; final short HIGHLIGHT_UNDERSCORE = 0xF4; final short HIGHLIGHT_INTENSIFY = 0xF8; /* Colors: Listed in 6.13.3 */ final short COLOR_NEUTRAL1 = 0x00; final short COLOR_BLUE = 0xF1; final short COLOR_RED = 0xF2; final short COLOR_PINK = 0xF3; final short COLOR_GREEN = 0xF4; final short COLOR_TURQUOISE = 0xF5; final short COLOR_YELLOW = 0xF6; final short COLOR_NEUTRAL2 = 0xF7; final short COLOR_BLACK = 0xF8; final short COLOR_DEEP_BLUE = 0xF9; final short COLOR_ORANGE = 0xFA; final short COLOR_PURPLE = 0xFB; final short COLOR_PALE_GREEN = 0xFC; final short COLOR_PALE_TURQUOISE = 0xFD; final short COLOR_GREY = 0xFE; final short COLOR_WHITE = 0xFF; final short QUERY_REPLY = 0x81; final short SUMMARY_QUERY_REPLY = 0x80; final short COLOR_QUERY_REPLY = 0x86; final short HIGHLIGHT_QUERY_REPLY = 0x87; final short IMP_PART_QUERY_REPLY = 0xA6; /* Highlighting */ short[] highlightReply = new short[15]; /* Bytes 0-1 Length of the Structured Field */ highlightReply[0] = (short)0x00; highlightReply[1] = (short)0x0F; /* Byte 2 Query Reply */ highlightReply[2] = QUERY_REPLY; /* Byte 3 Highlighting */ highlightReply[3] = HIGHLIGHT_QUERY_REPLY; /* Byte 4 Number of attribute-value/action pairs */ - highlightReply[4] = (short)0x50; + highlightReply[4] = (short)0x05; /* Part 1: Data stream attribute value accepted */ /* Part 2: Data stream action */ /* Pair 1 */ highlightReply[5] = HIGHLIGHT_DEFAULT; highlightReply[6] = HIGHLIGHT_NORMAL; /* Pair 2 */ highlightReply[7] = HIGHLIGHT_BLINK; highlightReply[8] = HIGHLIGHT_BLINK; /* Pair 3 */ highlightReply[9] = HIGHLIGHT_REVERSE; highlightReply[10] = HIGHLIGHT_REVERSE; /* Pair 4 */ highlightReply[11] = HIGHLIGHT_UNDERSCORE; highlightReply[12] = HIGHLIGHT_UNDERSCORE; /* Pair 5 */ highlightReply[13] = HIGHLIGHT_INTENSIFY; highlightReply[14] = HIGHLIGHT_INTENSIFY; /* Color */ short[] colorReply = new short[40]; /* Bytes 0-1 Length of the Structured Field */ colorReply[0] = (short)0x00; colorReply[1] = (short)0x26; colorReply[2] = QUERY_REPLY; colorReply[3] = COLOR_QUERY_REPLY; colorReply[4] = (short)0x00; /* Number of Pairs */ colorReply[5] = (short)0x10; /* Pair 1 */ colorReply[6] = COLOR_NEUTRAL1; - colorReply[7] = COLOR_WHITE; + colorReply[7] = COLOR_GREEN; /* Pair 2 */ colorReply[8] = COLOR_BLUE; colorReply[9] = COLOR_BLUE; /* Pair 3 */ colorReply[10] = COLOR_RED; colorReply[11] = COLOR_RED; /* Pair 4 */ colorReply[12] = COLOR_PINK; colorReply[13] = COLOR_PINK; /* Pair 5 */ colorReply[14] = COLOR_GREEN; colorReply[15] = COLOR_GREEN; /* Pair 6 */ colorReply[16] = COLOR_TURQUOISE; colorReply[17] = COLOR_TURQUOISE; /* Pair 7 */ colorReply[18] = COLOR_YELLOW; colorReply[19] = COLOR_YELLOW; /* Pair 8 */ colorReply[20] = COLOR_NEUTRAL2; colorReply[21] = COLOR_NEUTRAL2; /* Pair 9 */ colorReply[22] = COLOR_BLACK; colorReply[23] = COLOR_BLACK; /* Pair 10 */ colorReply[24] = COLOR_DEEP_BLUE; colorReply[25] = COLOR_DEEP_BLUE; /* Pair 11 */ colorReply[26] = COLOR_ORANGE; colorReply[27] = COLOR_ORANGE; /* Pair 12 */ colorReply[28] = COLOR_PURPLE; colorReply[29] = COLOR_PURPLE; /* Pair 13 */ colorReply[30] = COLOR_PALE_GREEN; colorReply[31] = COLOR_PALE_GREEN; /* Pair 14 */ colorReply[32] = COLOR_PALE_TURQUOISE; colorReply[33] = COLOR_PALE_TURQUOISE; /* Pair 15 */ colorReply[34] = COLOR_GREY; colorReply[35] = COLOR_GREY; /* Pair 16 */ colorReply[36] = COLOR_WHITE; colorReply[37] = COLOR_WHITE; /* Pair 17 */ - colorReply[38] = COLOR_GREY; - colorReply[39] = COLOR_GREY; + colorReply[38] = COLOR_WHITE; + colorReply[39] = COLOR_WHITE; /* Implicit Partition. See 6.31.2 */ short[] partitionReply = new short[17]; - partitionReply[0] = (short)QUERY_REPLY; - /* Bytes 1-2 Length */ - partitionReply[1] = (short)0x00; - partitionReply[2] = (short)0x11; + + /* Bytes 0-1 Length */ + partitionReply[0] = (short)0x00; + partitionReply[1] = (short)0x11; + partitionReply[2] = (short)QUERY_REPLY; /* Byte 3 QCODE Identifier */ partitionReply[3] = (short)IMP_PART_QUERY_REPLY; /* Bytes 4-5 Reserved */ partitionReply[4] = (short)0x00; partitionReply[5] = (short)0x00; /* 6.31.3 Implicit Partition Sizes for Display Devices Self-Defining Parameter */ partitionReply[6] = (short)0x0B; partitionReply[7] = (short)0x01; partitionReply[8] = (short)0x00; /* Bytes 9-10 Width of the Implicit Partition default screen size (in character cells) */ partitionReply[9] = (short)0x00; partitionReply[10] = (short)0x50; /* Bytes 11-12 Height of the Implicit Partition default screen size */ partitionReply[11] = (short)0x00; partitionReply[12] = (short)0x18; /* FIXME The alternate size should be the dimensions of the terminal model selected */ /* Bytes 13-14 Width of the Implicit Partition alternate screen size */ partitionReply[13] = (short)0x00; partitionReply[14] = (short)0x50; /* Bytes 15-16 Height of the Implicit Partition alternate screen size */ partitionReply[15] = (short)0x00; partitionReply[16] = (short)0x18; /* Summary */ short[] summaryReply = new short[8]; summaryReply[0] = (short)0x00; summaryReply[1] = (short)0x08; /* Byte 2 Query Reply */ summaryReply[2] = QUERY_REPLY; /* Byte 3 Summary Query Reply */ summaryReply[3] = SUMMARY_QUERY_REPLY; /* These are our capabilities... * Kind of silly to indicate we're capable of a summary reply * in a summary reply...that's how it works though. */ summaryReply[4] = SUMMARY_QUERY_REPLY; summaryReply[5] = COLOR_QUERY_REPLY; summaryReply[6] = HIGHLIGHT_QUERY_REPLY; summaryReply[7] = IMP_PART_QUERY_REPLY; /* Assembly of the Reply Packet */ /* Create a buffer the length of each of the member pieces, plus the header and footer */ int qReplyLength = 1 + summaryReply.length + highlightReply.length + colorReply.length + partitionReply.length; /* Initialize the queryReply packet buffer */ short[] queryReply = new short[qReplyLength]; queryReply[0] = 0x88; int bufPos = 1; /* Add the summary Capability */ for( int i = 0; i < summaryReply.length; i++ ) { queryReply[bufPos] = summaryReply[i]; bufPos++; } /* Add the Color Capability */ for( int i = 0; i < colorReply.length; i++ ) { queryReply[bufPos] = colorReply[i]; bufPos++; } /* Add the Highlight Capability */ for( int i = 0; i < highlightReply.length; i++ ) { queryReply[bufPos] = highlightReply[i]; bufPos++; } /* Add the Partition Capability */ for( int i = 0; i < partitionReply.length; i++ ) { queryReply[bufPos] = partitionReply[i]; bufPos++; } - /*for(int i = 0; i < queryReply.length; i++ ) { + /* for(int i = 0; i < queryReply.length; i++ ) { String myStr = Long.toHexString(new Short( queryReply[i] ).longValue()); - System.out.print( myStr + " " ); + if( myStr.length() == 1 ) { + myStr = "0" + myStr; + } + System.out.print( myStr ); }*/ return queryReply; } }
false
false
null
null
diff --git a/instance/src/main/java/com/prealpha/extempdb/instance/client/article/MetaPanelPresenter.java b/instance/src/main/java/com/prealpha/extempdb/instance/client/article/MetaPanelPresenter.java index 9a7be77..8bdcc34 100755 --- a/instance/src/main/java/com/prealpha/extempdb/instance/client/article/MetaPanelPresenter.java +++ b/instance/src/main/java/com/prealpha/extempdb/instance/client/article/MetaPanelPresenter.java @@ -1,92 +1,99 @@ /* * MetaPanelPresenter.java * Copyright (C) 2011 Meyer Kizner * All rights reserved. */ package com.prealpha.extempdb.instance.client.article; +import com.google.gwt.user.client.ui.HasHTML; import com.google.gwt.user.client.ui.HasText; import com.google.gwt.user.client.ui.HasWidgets; import com.google.gwt.user.client.ui.IsWidget; import com.google.inject.Inject; import com.google.inject.Provider; import com.prealpha.dispatch.shared.DispatcherAsync; import com.prealpha.extempdb.instance.client.Presenter; import com.prealpha.extempdb.instance.client.error.ManagedCallback; import com.prealpha.extempdb.instance.shared.action.GetMappingsByArticle; import com.prealpha.extempdb.instance.shared.action.GetMappingsResult; import com.prealpha.extempdb.instance.shared.dto.ArticleDto; import com.prealpha.extempdb.instance.shared.dto.TagMappingDto; import com.prealpha.extempdb.instance.shared.dto.TagMappingDto.State; public class MetaPanelPresenter implements Presenter<ArticleDto> { public static interface Display extends IsWidget { - HasText getHashLabel(); + HasHTML getHashLabel(); HasText getDateLabel(); HasText getSearchDateLabel(); HasText getParseDateLabel(); HasWidgets getTagsPanel(); HasWidgets getMappingInputPanel(); } private final Display display; private final DispatcherAsync dispatcher; private final MappingInputPresenter mappingInputPresenter; private final Provider<TagMappingPresenter> mappingPresenterProvider; @Inject public MetaPanelPresenter(Display display, DispatcherAsync dispatcher, MappingInputPresenter mappingInputPresenter, Provider<TagMappingPresenter> mappingPresenterProvider) { this.display = display; this.dispatcher = dispatcher; this.mappingInputPresenter = mappingInputPresenter; this.mappingPresenterProvider = mappingPresenterProvider; display.getMappingInputPanel().add( mappingInputPresenter.getDisplay().asWidget()); } @Override public Display getDisplay() { return display; } @Override public void bind(ArticleDto article) { - display.getHashLabel().setText(article.getHash()); + String hash = article.getHash(); + String hashHtml = ""; + hashHtml += hash.substring(0, 24) + "<br />"; + hashHtml += hash.substring(24, 48) + "<br />"; + hashHtml += hash.substring(48, 64) + "<br />"; + + display.getHashLabel().setHTML(hashHtml); display.getDateLabel().setText(article.getDate()); display.getSearchDateLabel().setText(article.getUrl().getCreateDate()); display.getParseDateLabel().setText(article.getCreateDate()); display.getTagsPanel().clear(); mappingInputPresenter.bind(article); GetMappingsByArticle action = new GetMappingsByArticle(article.getHash()); dispatcher.execute(action, new MappingsCallback()); } private class MappingsCallback extends ManagedCallback<GetMappingsResult> { @Override public void onSuccess(GetMappingsResult result) { for (TagMappingDto mapping : result.getMappings()) { if (!mapping.getState().equals(State.REMOVED)) { TagMappingPresenter mappingPresenter = mappingPresenterProvider .get(); mappingPresenter.bind(mapping); display.getTagsPanel().add( mappingPresenter.getDisplay().asWidget()); } } } } } diff --git a/instance/src/main/java/com/prealpha/extempdb/instance/client/article/MetaPanelWidget.java b/instance/src/main/java/com/prealpha/extempdb/instance/client/article/MetaPanelWidget.java index 40ac677..999ac4c 100755 --- a/instance/src/main/java/com/prealpha/extempdb/instance/client/article/MetaPanelWidget.java +++ b/instance/src/main/java/com/prealpha/extempdb/instance/client/article/MetaPanelWidget.java @@ -1,75 +1,76 @@ /* * MetaPanelWidget.java * Copyright (C) 2011 Meyer Kizner * All rights reserved. */ package com.prealpha.extempdb.instance.client.article; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.user.client.ui.Composite; +import com.google.gwt.user.client.ui.HasHTML; import com.google.gwt.user.client.ui.HasText; import com.google.gwt.user.client.ui.HasWidgets; import com.google.gwt.user.client.ui.Widget; import com.google.inject.Inject; public class MetaPanelWidget extends Composite implements MetaPanelPresenter.Display { public static interface MetaPanelUiBinder extends UiBinder<Widget, MetaPanelWidget> { } @UiField - HasText hashLabel; + HasHTML hashLabel; @UiField HasText dateLabel; @UiField HasText searchDateLabel; @UiField HasText parseDateLabel; @UiField HasWidgets tagsPanel; @UiField HasWidgets mappingInputPanel; @Inject public MetaPanelWidget(MetaPanelUiBinder uiBinder) { initWidget(uiBinder.createAndBindUi(this)); } @Override - public HasText getHashLabel() { + public HasHTML getHashLabel() { return hashLabel; } @Override public HasText getDateLabel() { return dateLabel; } @Override public HasText getSearchDateLabel() { return searchDateLabel; } @Override public HasText getParseDateLabel() { return parseDateLabel; } @Override public HasWidgets getTagsPanel() { return tagsPanel; } @Override public HasWidgets getMappingInputPanel() { return mappingInputPanel; } } diff --git a/instance/src/main/java/com/prealpha/extempdb/instance/server/action/ActionModule.java b/instance/src/main/java/com/prealpha/extempdb/instance/server/action/ActionModule.java index 3f434ec..48a7dbc 100755 --- a/instance/src/main/java/com/prealpha/extempdb/instance/server/action/ActionModule.java +++ b/instance/src/main/java/com/prealpha/extempdb/instance/server/action/ActionModule.java @@ -1,59 +1,60 @@ /* * ActionModule.java * Copyright (C) 2011 Meyer Kizner * All rights reserved. */ package com.prealpha.extempdb.instance.server.action; import java.util.List; import org.dozer.DozerBeanMapper; import org.dozer.Mapper; import com.google.common.collect.ImmutableList; import com.google.inject.Inject; import com.google.inject.Provides; import com.google.inject.Singleton; import com.prealpha.dispatch.server.ActionHandlerModule; import com.prealpha.extempdb.instance.shared.action.AddArticle; import com.prealpha.extempdb.instance.shared.action.AddMapping; import com.prealpha.extempdb.instance.shared.action.GetArticleByHash; import com.prealpha.extempdb.instance.shared.action.GetArticleByUrl; import com.prealpha.extempdb.instance.shared.action.GetHierarchy; import com.prealpha.extempdb.instance.shared.action.GetMapping; import com.prealpha.extempdb.instance.shared.action.GetMappingsByArticle; import com.prealpha.extempdb.instance.shared.action.GetMappingsByTag; import com.prealpha.extempdb.instance.shared.action.GetParagraphs; import com.prealpha.extempdb.instance.shared.action.GetTag; import com.prealpha.extempdb.instance.shared.action.GetTagSuggestions; public class ActionModule extends ActionHandlerModule { public ActionModule() { } @Override protected void configure() { bindHandler(AddArticle.class, AddArticleHandler.class); bindHandler(AddMapping.class, AddMappingHandler.class); bindHandler(GetArticleByHash.class, GetArticleByHashHandler.class); bindHandler(GetArticleByUrl.class, GetArticleByUrlHandler.class); bindHandler(GetHierarchy.class, GetHierarchyHandler.class); bindHandler(GetMapping.class, GetMappingHandler.class); bindHandler(GetMappingsByArticle.class, GetMappingsByArticleHandler.class); bindHandler(GetMappingsByTag.class, GetMappingsByTagHandler.class); bindHandler(GetParagraphs.class, GetParagraphsHandler.class); bindHandler(GetTag.class, GetTagHandler.class); bindHandler(GetTagSuggestions.class, GetTagSuggestionsHandler.class); } @Provides @Singleton @Inject Mapper getMapper(DozerBeanMapper mapper) { - List<String> mappingFiles = ImmutableList.of("bean-mapping.xml"); + List<String> mappingFiles = ImmutableList + .of("META-INF/bean-mapping.xml"); mapper.setMappingFiles(mappingFiles); return mapper; } }
false
false
null
null
diff --git a/src/modelo/DescuentoServicios.java b/src/modelo/DescuentoServicios.java index 7133447..2fea307 100644 --- a/src/modelo/DescuentoServicios.java +++ b/src/modelo/DescuentoServicios.java @@ -1,36 +1,36 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package modelo; import java.util.ArrayList; /** * * @author HP */ public class DescuentoServicios extends SueldoDecorador{ ArrayList<Servicio> servicios; private double descuentoPorServicios; public DescuentoServicios(String idEmpleado, Sueldo sueldoDecorado) { this.idEmpleado = idEmpleado; this.sueldoDecorado = sueldoDecorado; } public double calcularDescuentoPorServicios() { double descuento = 0.0; for (int i = 0; i < servicios.size(); i++) { descuento += servicios.get(i).getMonto(); } - return 0.0; + return descuento; } public double calcularSueldo() { return sueldoDecorado.calcularSueldo()- descuentoPorServicios; } }
true
true
public double calcularDescuentoPorServicios() { double descuento = 0.0; for (int i = 0; i < servicios.size(); i++) { descuento += servicios.get(i).getMonto(); } return 0.0; }
public double calcularDescuentoPorServicios() { double descuento = 0.0; for (int i = 0; i < servicios.size(); i++) { descuento += servicios.get(i).getMonto(); } return descuento; }
diff --git a/src/main/java/com/algolia/search/saas/APIClient.java b/src/main/java/com/algolia/search/saas/APIClient.java index 0340daa..22a22b7 100644 --- a/src/main/java/com/algolia/search/saas/APIClient.java +++ b/src/main/java/com/algolia/search/saas/APIClient.java @@ -1,409 +1,414 @@ package com.algolia.search.saas; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.message.BasicHeader; import org.apache.http.protocol.HTTP; +import org.apache.http.util.EntityUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.json.JSONTokener; /* * Copyright (c) 2013 Algolia * http://www.algolia.com/ * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ /** * Entry point in the Java API. * You should instantiate a Client object with your ApplicationID, ApiKey and Hosts * to start using Algolia Search API */ public class APIClient { private final String applicationID; private final String apiKey; private final List<String> hostsArray; private final HttpClient httpClient; /** * Algolia Search initialization * @param applicationID the application ID you have in your admin interface * @param apiKey a valid API key for the service */ public APIClient(String applicationID, String apiKey) { this(applicationID, apiKey, Arrays.asList(applicationID + "-1.algolia.io", applicationID + "-2.algolia.io", applicationID + "-3.algolia.io")); } /** * Algolia Search initialization * @param applicationID the application ID you have in your admin interface * @param apiKey a valid API key for the service * @param hostsArray the list of hosts that you have received for the service */ public APIClient(String applicationID, String apiKey, List<String> hostsArray) { if (applicationID == null || applicationID.length() == 0) { throw new RuntimeException("AlgoliaSearch requires an applicationID."); } this.applicationID = applicationID; if (apiKey == null || apiKey.length() == 0) { throw new RuntimeException("AlgoliaSearch requires an apiKey."); } this.apiKey = apiKey; if (hostsArray == null || hostsArray.size() == 0) { throw new RuntimeException("AlgoliaSearch requires a list of hostnames."); } // randomize elements of hostsArray (act as a kind of load-balancer) Collections.shuffle(hostsArray); this.hostsArray = hostsArray; httpClient = HttpClientBuilder.create().build(); } /** * List all existing indexes * return an JSON Object in the form: * { "items": [ {"name": "contacts", "createdAt": "2013-01-18T15:33:13.556Z"}, * {"name": "notes", "createdAt": "2013-01-18T15:33:13.556Z"}]} */ public JSONObject listIndexes() throws AlgoliaException { return _getRequest("/1/indexes/"); } /** * Delete an index * * @param indexName the name of index to delete * return an object containing a "deletedAt" attribute */ public JSONObject deleteIndex(String indexName) throws AlgoliaException { try { return _deleteRequest("/1/indexes/" + URLEncoder.encode(indexName, "UTF-8")); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } /** * Move an existing index. * @param srcIndexName the name of index to copy. * @param dstIndexName the new index name that will contains a copy of srcIndexName (destination will be overriten if it already exist). */ public JSONObject moveIndex(String srcIndexName, String dstIndexName) throws AlgoliaException { try { JSONObject content = new JSONObject(); content.put("operation", "move"); content.put("destination", dstIndexName); return _postRequest("/1/indexes/" + URLEncoder.encode(srcIndexName, "UTF-8") + "/operation", content.toString()); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } catch (JSONException e) { throw new AlgoliaException(e.getMessage()); } } /** * Copy an existing index. * @param srcIndexName the name of index to copy. * @param dstIndexName the new index name that will contains a copy of srcIndexName (destination will be overriten if it already exist). */ public JSONObject copyIndex(String srcIndexName, String dstIndexName) throws AlgoliaException { try { JSONObject content = new JSONObject(); content.put("operation", "copy"); content.put("destination", dstIndexName); return _postRequest("/1/indexes/" + URLEncoder.encode(srcIndexName, "UTF-8") + "/operation", content.toString()); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } catch (JSONException e) { throw new AlgoliaException(e.getMessage()); } } /** * Return 10 last log entries. */ public JSONObject getLogs() throws AlgoliaException { return _getRequest("/1/logs"); } /** * Return last logs entries. * @param offset Specify the first entry to retrieve (0-based, 0 is the most recent log entry). * @param length Specify the maximum number of entries to retrieve starting at offset. Maximum allowed value: 1000. */ public JSONObject getLogs(int offset, int length) throws AlgoliaException { return _getRequest("/1/logs?offset=" + offset + "&length=" + length); } /** * Get the index object initialized (no server call needed for initialization) * * @param indexName the name of index */ public Index initIndex(String indexName) { return new Index(this, indexName); } /** * List all existing user keys with their associated ACLs */ public JSONObject listUserKeys() throws AlgoliaException { return _getRequest("/1/keys"); } /** * Get ACL of a user key */ public JSONObject getUserKeyACL(String key) throws AlgoliaException { return _getRequest("/1/keys/" + key); } /** * Delete an existing user key */ public JSONObject deleteUserKey(String key) throws AlgoliaException { return _deleteRequest("/1/keys/" + key); } /** * Create a new user key * * @param acls the list of ACL for this key. Defined by an array of strings that * can contains the following values: * - search: allow to search (https and http) * - addObject: allows to add/update an object in the index (https only) * - deleteObject : allows to delete an existing object (https only) * - deleteIndex : allows to delete index content (https only) * - settings : allows to get index settings (https only) * - editSettings : allows to change index settings (https only) */ public JSONObject addUserKey(List<String> acls) throws AlgoliaException { JSONArray array = new JSONArray(acls); JSONObject jsonObject = new JSONObject(); try { jsonObject.put("acl", array); } catch (JSONException e) { throw new RuntimeException(e); } return _postRequest("/1/keys", jsonObject.toString()); } /** * Create a new user key * * @param acls the list of ACL for this key. Defined by an array of strings that * can contains the following values: * - search: allow to search (https and http) * - addObject: allows to add/update an object in the index (https only) * - deleteObject : allows to delete an existing object (https only) * - deleteIndex : allows to delete index content (https only) * - settings : allows to get index settings (https only) * - editSettings : allows to change index settings (https only) * @param validity the number of seconds after which the key will be automatically removed (0 means no time limit for this key) */ public JSONObject addUserKey(List<String> acls, int validity) throws AlgoliaException { JSONArray array = new JSONArray(acls); JSONObject jsonObject = new JSONObject(); try { jsonObject.put("acl", array); jsonObject.put("validity", validity); } catch (JSONException e) { throw new RuntimeException(e); } return _postRequest("/1/keys", jsonObject.toString()); } protected JSONObject _getRequest(String url) throws AlgoliaException { for (String host : this.hostsArray) { HttpGet httpGet = new HttpGet("https://" + host + url); httpGet.setHeader("X-Algolia-Application-Id", this.applicationID); httpGet.setHeader("X-Algolia-API-Key", this.apiKey); try { HttpResponse response = httpClient.execute(httpGet); int code = response.getStatusLine().getStatusCode(); if (code == 403) { + EntityUtils.consumeQuietly(response.getEntity()); throw new AlgoliaException("Invalid Application-ID or API-Key"); } if (code == 404) { + EntityUtils.consumeQuietly(response.getEntity()); throw new AlgoliaException("Resource does not exist"); } - if (code == 503) + if (code == 503) { + EntityUtils.consumeQuietly(response.getEntity()); continue; + } InputStream istream = response.getEntity().getContent(); InputStreamReader is = new InputStreamReader(istream, "UTF-8"); BufferedReader reader = new BufferedReader(is); String json = reader.readLine(); JSONTokener tokener = new JSONTokener(json); JSONObject res = new JSONObject(tokener); reader.close(); is.close(); is.close(); return res; } catch (IOException e) { // on error continue on the next host } catch (JSONException e) { throw new AlgoliaException("JSON decode error:" + e.getMessage()); } } throw new AlgoliaException("Hosts unreachable"); } protected JSONObject _deleteRequest(String url) throws AlgoliaException { for (String host : this.hostsArray) { HttpDelete httpDelete = new HttpDelete("https://" + host + url); httpDelete.setHeader("X-Algolia-Application-Id", this.applicationID); httpDelete.setHeader("X-Algolia-API-Key", this.apiKey); try { HttpResponse response = httpClient.execute(httpDelete); int code = response.getStatusLine().getStatusCode(); if (code == 403) { throw new AlgoliaException("Invalid Application-ID or API-Key"); } if (code == 404) { throw new AlgoliaException("Resource does not exist"); } if (code == 503) continue; InputStream istream = response.getEntity().getContent(); InputStreamReader is = new InputStreamReader(istream, "UTF-8"); BufferedReader reader = new BufferedReader(is); String json = reader.readLine(); JSONTokener tokener = new JSONTokener(json); JSONObject res = new JSONObject(tokener); reader.close(); is.close(); is.close(); return res; } catch (IOException e) { // on error continue on the next host } catch (JSONException e) { throw new AlgoliaException("JSON decode error:" + e.getMessage()); } } throw new AlgoliaException("Hosts unreachable"); } protected JSONObject _postRequest(String url, String obj) throws AlgoliaException { for (String host : this.hostsArray) { HttpPost httpPost = new HttpPost("https://" + host + url); httpPost.setHeader("X-Algolia-Application-Id", this.applicationID); httpPost.setHeader("X-Algolia-API-Key", this.apiKey); httpPost.setHeader("Content-type", "application/json"); try { StringEntity se = new StringEntity(obj, "UTF-8"); se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); httpPost.setEntity(se); } catch (UnsupportedEncodingException e) { throw new AlgoliaException("Invalid JSON Object: " + obj); } try { HttpResponse response = httpClient.execute(httpPost); int code = response.getStatusLine().getStatusCode(); if (code == 403) { throw new AlgoliaException("Invalid Application-ID or API-Key"); } if (code == 404) { throw new AlgoliaException("Resource does not exist"); } if (code == 503) continue; InputStream istream = response.getEntity().getContent(); InputStreamReader is = new InputStreamReader(istream, "UTF-8"); BufferedReader reader = new BufferedReader(is); String json = reader.readLine(); JSONTokener tokener = new JSONTokener(json); JSONObject res = new JSONObject(tokener); reader.close(); is.close(); is.close(); return res; } catch (IOException e) { // on error continue on the next host } catch (JSONException e) { throw new AlgoliaException("JSON decode error:" + e.getMessage()); } } throw new AlgoliaException("Hosts unreachable"); } protected JSONObject _putRequest(String url, String obj) throws AlgoliaException { for (String host : this.hostsArray) { HttpPut httpPut = new HttpPut("https://" + host + url); httpPut.setHeader("X-Algolia-Application-Id", this.applicationID); httpPut.setHeader("X-Algolia-API-Key", this.apiKey); httpPut.setHeader("Content-type", "application/json"); try { StringEntity se = new StringEntity(obj, "UTF-8"); se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); httpPut.setEntity(se); } catch (UnsupportedEncodingException e) { throw new AlgoliaException("Invalid JSON Object: " + obj); } try { HttpResponse response = httpClient.execute(httpPut); int code = response.getStatusLine().getStatusCode(); if (code == 403) { throw new AlgoliaException("Invalid Application-ID or API-Key"); } if (code == 404) { throw new AlgoliaException("Resource does not exist"); } if (code == 503) continue; InputStream istream = response.getEntity().getContent(); InputStreamReader is = new InputStreamReader(istream, "UTF-8"); BufferedReader reader = new BufferedReader(is); String json = reader.readLine(); JSONTokener tokener = new JSONTokener(json); JSONObject res = new JSONObject(tokener); reader.close(); is.close(); is.close(); return res; } catch (IOException e) { // on error continue on the next host } catch (JSONException e) { throw new AlgoliaException("JSON decode error:" + e.getMessage()); } } throw new AlgoliaException("Hosts unreachable"); } }
false
false
null
null
diff --git a/src/main/java/jline/ConsoleReader.java b/src/main/java/jline/ConsoleReader.java index 1a56156..88b7096 100644 --- a/src/main/java/jline/ConsoleReader.java +++ b/src/main/java/jline/ConsoleReader.java @@ -1,1496 +1,1496 @@ /* * Copyright (c) 2002-2007, Marc Prud'hommeaux. All rights reserved. * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. */ package jline; import java.awt.*; import java.awt.datatransfer.*; import java.io.*; import java.util.*; import java.util.List; /** * A reader for console applications. It supports custom tab-completion, * saveable command history, and command line editing. On some platforms, * platform-specific commands will need to be issued before the reader will * function properly. See {@link Terminal#initializeTerminal} for convenience * methods for issuing platform-specific setup commands. * * @author <a href="mailto:mwp1@cornell.edu">Marc Prud'hommeaux</a> */ public class ConsoleReader implements ConsoleOperations { String prompt; private boolean useHistory = true; private boolean usePagination = false; public static final String CR = System.getProperty("line.separator"); private static ResourceBundle loc = ResourceBundle .getBundle(CandidateListCompletionHandler.class.getName()); /** * Map that contains the operation name to keymay operation mapping. */ public static SortedMap KEYMAP_NAMES; static { Map names = new TreeMap(); names.put("MOVE_TO_BEG", new Short(MOVE_TO_BEG)); names.put("MOVE_TO_END", new Short(MOVE_TO_END)); names.put("PREV_CHAR", new Short(PREV_CHAR)); names.put("NEWLINE", new Short(NEWLINE)); names.put("KILL_LINE", new Short(KILL_LINE)); names.put("PASTE", new Short(PASTE)); names.put("CLEAR_SCREEN", new Short(CLEAR_SCREEN)); names.put("NEXT_HISTORY", new Short(NEXT_HISTORY)); names.put("PREV_HISTORY", new Short(PREV_HISTORY)); names.put("START_OF_HISTORY", new Short(START_OF_HISTORY)); names.put("END_OF_HISTORY", new Short(END_OF_HISTORY)); names.put("REDISPLAY", new Short(REDISPLAY)); names.put("KILL_LINE_PREV", new Short(KILL_LINE_PREV)); names.put("DELETE_PREV_WORD", new Short(DELETE_PREV_WORD)); names.put("NEXT_CHAR", new Short(NEXT_CHAR)); names.put("REPEAT_PREV_CHAR", new Short(REPEAT_PREV_CHAR)); names.put("SEARCH_PREV", new Short(SEARCH_PREV)); names.put("REPEAT_NEXT_CHAR", new Short(REPEAT_NEXT_CHAR)); names.put("SEARCH_NEXT", new Short(SEARCH_NEXT)); names.put("PREV_SPACE_WORD", new Short(PREV_SPACE_WORD)); names.put("TO_END_WORD", new Short(TO_END_WORD)); names.put("REPEAT_SEARCH_PREV", new Short(REPEAT_SEARCH_PREV)); names.put("PASTE_PREV", new Short(PASTE_PREV)); names.put("REPLACE_MODE", new Short(REPLACE_MODE)); names.put("SUBSTITUTE_LINE", new Short(SUBSTITUTE_LINE)); names.put("TO_PREV_CHAR", new Short(TO_PREV_CHAR)); names.put("NEXT_SPACE_WORD", new Short(NEXT_SPACE_WORD)); names.put("DELETE_PREV_CHAR", new Short(DELETE_PREV_CHAR)); names.put("ADD", new Short(ADD)); names.put("PREV_WORD", new Short(PREV_WORD)); names.put("CHANGE_META", new Short(CHANGE_META)); names.put("DELETE_META", new Short(DELETE_META)); names.put("END_WORD", new Short(END_WORD)); names.put("NEXT_CHAR", new Short(NEXT_CHAR)); names.put("INSERT", new Short(INSERT)); names.put("REPEAT_SEARCH_NEXT", new Short(REPEAT_SEARCH_NEXT)); names.put("PASTE_NEXT", new Short(PASTE_NEXT)); names.put("REPLACE_CHAR", new Short(REPLACE_CHAR)); names.put("SUBSTITUTE_CHAR", new Short(SUBSTITUTE_CHAR)); names.put("TO_NEXT_CHAR", new Short(TO_NEXT_CHAR)); names.put("UNDO", new Short(UNDO)); names.put("NEXT_WORD", new Short(NEXT_WORD)); names.put("DELETE_NEXT_CHAR", new Short(DELETE_NEXT_CHAR)); names.put("CHANGE_CASE", new Short(CHANGE_CASE)); names.put("COMPLETE", new Short(COMPLETE)); names.put("EXIT", new Short(EXIT)); names.put("CLEAR_LINE", new Short(CLEAR_LINE)); KEYMAP_NAMES = new TreeMap(Collections.unmodifiableMap(names)); } /** * The map for logical operations. */ private final short[] keybindings; /** * If true, issue an audible keyboard bell when appropriate. */ private boolean bellEnabled = true; /** * The current character mask. */ private Character mask = null; /** * The null mask. */ private static final Character NULL_MASK = new Character((char) 0); /** * The number of tab-completion candidates above which a warning will be * prompted before showing all the candidates. */ private int autoprintThreshhold = Integer.getInteger( "jline.completion.threshold", 100).intValue(); // same default as // bash /** * The Terminal to use. */ private final Terminal terminal; private CompletionHandler completionHandler = new CandidateListCompletionHandler(); InputStream in; final Writer out; final CursorBuffer buf = new CursorBuffer(); static PrintWriter debugger; History history = new History(); final List completors = new LinkedList(); private Character echoCharacter = null; /** * Create a new reader using {@link FileDescriptor#in} for input and * {@link System#out} for output. {@link FileDescriptor#in} is used because * it has a better chance of being unbuffered. */ public ConsoleReader() throws IOException { this(new FileInputStream(FileDescriptor.in), new PrintWriter(System.out)); } /** * Create a new reader using the specified {@link InputStream} for input and * the specific writer for output, using the default keybindings resource. */ public ConsoleReader(final InputStream in, final Writer out) throws IOException { this(in, out, null); } public ConsoleReader(final InputStream in, final Writer out, final InputStream bindings) throws IOException { this(in, out, bindings, Terminal.getTerminal()); } /** * Create a new reader. * * @param in * the input * @param out * the output * @param bindings * the key bindings to use * @param term * the terminal to use */ public ConsoleReader(InputStream in, Writer out, InputStream bindings, Terminal term) throws IOException { this.terminal = term; setInput(in); this.out = out; if (bindings == null) { String bindingFile = System.getProperty("jline.keybindings", new File(System.getProperty("user.home", ".jlinebindings.properties")).getAbsolutePath()); if (!(new File(bindingFile).isFile())) { bindings = terminal.getDefaultBindings(); } else { bindings = new FileInputStream(new File(bindingFile)); } } this.keybindings = new short[Character.MAX_VALUE * 2]; Arrays.fill(this.keybindings, UNKNOWN); /** * Loads the key bindings. Bindings file is in the format: * * keycode: operation name */ if (bindings != null) { Properties p = new Properties(); p.load(bindings); bindings.close(); for (Iterator i = p.keySet().iterator(); i.hasNext();) { String val = (String) i.next(); try { Short code = new Short(val); String op = (String) p.getProperty(val); Short opval = (Short) KEYMAP_NAMES.get(op); if (opval != null) { keybindings[code.shortValue()] = opval.shortValue(); } } catch (NumberFormatException nfe) { consumeException(nfe); } } // hardwired arrow key bindings // keybindings[VK_UP] = PREV_HISTORY; // keybindings[VK_DOWN] = NEXT_HISTORY; // keybindings[VK_LEFT] = PREV_CHAR; // keybindings[VK_RIGHT] = NEXT_CHAR; } } public Terminal getTerminal() { return this.terminal; } /** * Set the stream for debugging. Development use only. */ public void setDebug(final PrintWriter debugger) { ConsoleReader.debugger = debugger; } /** * Set the stream to be used for console input. */ public void setInput(final InputStream in) { this.in = in; } /** * Returns the stream used for console input. */ public InputStream getInput() { return this.in; } /** * Read the next line and return the contents of the buffer. */ public String readLine() throws IOException { return readLine((String) null); } /** * Read the next line with the specified character mask. If null, then * characters will be echoed. If 0, then no characters will be echoed. */ public String readLine(final Character mask) throws IOException { return readLine(null, mask); } /** * @param bellEnabled * if true, enable audible keyboard bells if an alert is * required. */ public void setBellEnabled(final boolean bellEnabled) { this.bellEnabled = bellEnabled; } /** * @return true is audible keyboard bell is enabled. */ public boolean getBellEnabled() { return this.bellEnabled; } /** * Query the terminal to find the current width; * * @see Terminal#getTerminalWidth * @return the width of the current terminal. */ public int getTermwidth() { return Terminal.setupTerminal().getTerminalWidth(); } /** * Query the terminal to find the current width; * * @see Terminal#getTerminalHeight * * @return the height of the current terminal. */ public int getTermheight() { return Terminal.setupTerminal().getTerminalHeight(); } /** * @param autoprintThreshhold * the number of candidates to print without issuing a warning. */ public void setAutoprintThreshhold(final int autoprintThreshhold) { this.autoprintThreshhold = autoprintThreshhold; } /** * @return the number of candidates to print without issing a warning. */ public int getAutoprintThreshhold() { return this.autoprintThreshhold; } int getKeyForAction(short logicalAction) { for (int i = 0; i < keybindings.length; i++) { if (keybindings[i] == logicalAction) { return i; } } return -1; } /** * Clear the echoed characters for the specified character code. */ int clearEcho(int c) throws IOException { // if the terminal is not echoing, then just return... if (!terminal.getEcho()) { return 0; } // otherwise, clear int num = countEchoCharacters((char) c); back(num); drawBuffer(num); return num; } int countEchoCharacters(char c) { // tabs as special: we need to determine the number of spaces // to cancel based on what out current cursor position is if (c == 9) { int tabstop = 8; // will this ever be different? int position = getCursorPosition(); return tabstop - (position % tabstop); } return getPrintableCharacters(c).length(); } /** * Return the number of characters that will be printed when the specified * character is echoed to the screen. Adapted from cat by Torbjorn Granlund, * as repeated in stty by David MacKenzie. */ StringBuffer getPrintableCharacters(char ch) { StringBuffer sbuff = new StringBuffer(); if (ch >= 32) { if (ch < 127) { sbuff.append(ch); } else if (ch == 127) { sbuff.append('^'); sbuff.append('?'); } else { sbuff.append('M'); sbuff.append('-'); if (ch >= (128 + 32)) { if (ch < (128 + 127)) { sbuff.append((char) (ch - 128)); } else { sbuff.append('^'); sbuff.append('?'); } } else { sbuff.append('^'); sbuff.append((char) (ch - 128 + 64)); } } } else { sbuff.append('^'); sbuff.append((char) (ch + 64)); } return sbuff; } int getCursorPosition() { // FIXME: does not handle anything but a line with a prompt // absolute position return ((prompt == null) ? 0 : prompt.length()) + buf.cursor; } public String readLine(final String prompt) throws IOException { return readLine(prompt, null); } /** * The default prompt that will be issued. */ public void setDefaultPrompt(String prompt) { this.prompt = prompt; } /** * The default prompt that will be issued. */ public String getDefaultPrompt() { return prompt; } /** * Read a line from the <i>in</i> {@link InputStream}, and return the line * (without any trailing newlines). * * @param prompt * the prompt to issue to the console, may be null. * @return a line that is read from the terminal, or null if there was null * input (e.g., <i>CTRL-D</i> was pressed). */ public String readLine(final String prompt, final Character mask) throws IOException { this.mask = mask; if (prompt != null) this.prompt = prompt; try { terminal.beforeReadLine(this, this.prompt, mask); if ((this.prompt != null) && (this.prompt.length() > 0)) { out.write(this.prompt); out.flush(); } // if the terminal is unsupported, just use plain-java reading if (!terminal.isSupported()) { return readLine(in); } while (true) { int[] next = readBinding(); if (next == null) { return null; } int c = next[0]; int code = next[1]; if (c == -1) { return null; } boolean success = true; switch (code) { case EXIT: // ctrl-d if (buf.buffer.length() == 0) { return null; } case COMPLETE: // tab success = complete(); break; case MOVE_TO_BEG: success = setCursorPosition(0); break; case KILL_LINE: // CTRL-K success = killLine(); break; case CLEAR_SCREEN: // CTRL-L success = clearScreen(); break; case KILL_LINE_PREV: // CTRL-U success = resetLine(); break; case NEWLINE: // enter printNewline(); // output newline return finishBuffer(); case DELETE_PREV_CHAR: // backspace success = backspace(); break; case DELETE_NEXT_CHAR: // delete success = deleteCurrentCharacter(); break; case MOVE_TO_END: success = moveToEnd(); break; case PREV_CHAR: success = moveCursor(-1) != 0; break; case NEXT_CHAR: success = moveCursor(1) != 0; break; case NEXT_HISTORY: success = moveHistory(true); break; case PREV_HISTORY: success = moveHistory(false); break; case REDISPLAY: break; case PASTE: success = paste(); break; case DELETE_PREV_WORD: success = deletePreviousWord(); break; case PREV_WORD: success = previousWord(); break; case NEXT_WORD: success = nextWord(); break; case START_OF_HISTORY: success = history.moveToFirstEntry(); if (success) setBuffer(history.current()); break; case END_OF_HISTORY: success = history.moveToLastEntry(); if (success) setBuffer(history.current()); break; case CLEAR_LINE: moveInternal(-(buf.buffer.length())); killLine(); break; case INSERT: buf.setOvertyping(!buf.isOvertyping()); break; case UNKNOWN: default: if (c != 0) // ignore null chars putChar(c, true); else success = false; } if (!(success)) { beep(); } flushConsole(); } } finally { terminal.afterReadLine(this, this.prompt, mask); } } private String readLine(InputStream in) throws IOException { StringBuffer buf = new StringBuffer(); while (true) { int i = in.read(); if ((i == -1) || (i == '\n') || (i == '\r')) { return buf.toString(); } buf.append((char) i); } // return new BufferedReader (new InputStreamReader (in)).readLine (); } /** * Reads the console input and returns an array of the form [raw, key * binding]. */ private int[] readBinding() throws IOException { int c = readVirtualKey(); if (c == -1) { return null; } // extract the appropriate key binding short code = keybindings[c]; if (debugger != null) { debug(" translated: " + (int) c + ": " + code); } return new int[] { c, code }; } /** * Move up or down the history tree. * * @param direction * less than 0 to move up the tree, down otherwise */ private final boolean moveHistory(final boolean next) throws IOException { if (next && !history.next()) { return false; } else if (!next && !history.previous()) { return false; } setBuffer(history.current()); return true; } /** * Paste the contents of the clipboard into the console buffer * * @return true if clipboard contents pasted */ public boolean paste() throws IOException { Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); if (clipboard == null) { return false; } Transferable transferable = clipboard.getContents(null); if (transferable == null) { return false; } try { Object content = transferable .getTransferData(DataFlavor.plainTextFlavor); /* * This fix was suggested in bug #1060649 at * http://sourceforge.net/tracker/index.php?func=detail&aid=1060649&group_id=64033&atid=506056 * to get around the deprecated DataFlavor.plainTextFlavor, but it * raises a UnsupportedFlavorException on Mac OS X */ if (content == null) { try { content = new DataFlavor().getReaderForText(transferable); } catch (Exception e) { } } if (content == null) { return false; } String value; if (content instanceof Reader) { // TODO: we might want instead connect to the input stream // so we can interpret individual lines value = ""; String line = null; for (BufferedReader read = new BufferedReader((Reader) content); (line = read .readLine()) != null;) { if (value.length() > 0) { value += "\n"; } value += line; } } else { value = content.toString(); } if (value == null) { return true; } putString(value); return true; } catch (UnsupportedFlavorException ufe) { if (debugger != null) debug(ufe + ""); return false; } } /** * Kill the buffer ahead of the current cursor position. * * @return true if successful */ public boolean killLine() throws IOException { int cp = buf.cursor; int len = buf.buffer.length(); if (cp >= len) { return false; } int num = buf.buffer.length() - cp; clearAhead(num); for (int i = 0; i < num; i++) { buf.buffer.deleteCharAt(len - i - 1); } return true; } /** * Clear the screen by issuing the ANSI "clear screen" code. */ public boolean clearScreen() throws IOException { if (!terminal.isANSISupported()) { return false; } // send the ANSI code to clear the screen printString(((char) 27) + "[2J"); flushConsole(); // then send the ANSI code to go to position 1,1 printString(((char) 27) + "[1;1H"); flushConsole(); redrawLine(); return true; } /** * Use the completors to modify the buffer with the appropriate completions. * * @return true if successful */ private final boolean complete() throws IOException { // debug ("tab for (" + buf + ")"); if (completors.size() == 0) { return false; } List candidates = new LinkedList(); String bufstr = buf.buffer.toString(); int cursor = buf.cursor; int position = -1; for (Iterator i = completors.iterator(); i.hasNext();) { Completor comp = (Completor) i.next(); if ((position = comp.complete(bufstr, cursor, candidates)) != -1) { break; } } // no candidates? Fail. if (candidates.size() == 0) { return false; } return completionHandler.complete(this, candidates, position); } public CursorBuffer getCursorBuffer() { return buf; } /** * Output the specified {@link Collection} in proper columns. * * @param stuff * the stuff to print */ public void printColumns(final Collection stuff) throws IOException { if ((stuff == null) || (stuff.size() == 0)) { return; } int width = getTermwidth(); int maxwidth = 0; for (Iterator i = stuff.iterator(); i.hasNext(); maxwidth = Math.max( maxwidth, i.next().toString().length())) { ; } StringBuffer line = new StringBuffer(); int showLines; if (usePagination) showLines = getTermheight() - 1; // page limit else showLines = Integer.MAX_VALUE; for (Iterator i = stuff.iterator(); i.hasNext();) { String cur = (String) i.next(); if ((line.length() + maxwidth) > width) { printString(line.toString().trim()); printNewline(); line.setLength(0); if (--showLines == 0) { // Overflow printString(loc.getString("display-more")); flushConsole(); int c = readVirtualKey(); if (c == '\r' || c == '\n') showLines = 1; // one step forward else if (c != 'q') showLines = getTermheight() - 1; // page forward back(loc.getString("display-more").length()); if (c == 'q') break; // cancel } } pad(cur, maxwidth + 3, line); } if (line.length() > 0) { printString(line.toString().trim()); printNewline(); line.setLength(0); } } /** * Append <i>toPad</i> to the specified <i>appendTo</i>, as well as (<i>toPad.length () - * len</i>) spaces. * * @param toPad * the {@link String} to pad * @param len * the target length * @param appendTo * the {@link StringBuffer} to which to append the padded * {@link String}. */ private final void pad(final String toPad, final int len, final StringBuffer appendTo) { appendTo.append(toPad); for (int i = 0; i < (len - toPad.length()); i++, appendTo.append(' ')) { ; } } /** * Add the specified {@link Completor} to the list of handlers for * tab-completion. * * @param completor * the {@link Completor} to add * @return true if it was successfully added */ public boolean addCompletor(final Completor completor) { return completors.add(completor); } /** * Remove the specified {@link Completor} from the list of handlers for * tab-completion. * * @param completor * the {@link Completor} to remove * @return true if it was successfully removed */ public boolean removeCompletor(final Completor completor) { return completors.remove(completor); } /** * Returns an unmodifiable list of all the completors. */ public Collection getCompletors() { return Collections.unmodifiableList(completors); } /** * Erase the current line. * * @return false if we failed (e.g., the buffer was empty) */ final boolean resetLine() throws IOException { if (buf.cursor == 0) { return false; } backspaceAll(); return true; } /** * Move the cursor position to the specified absolute index. */ public final boolean setCursorPosition(final int position) throws IOException { return moveCursor(position - buf.cursor) != 0; } /** * Set the current buffer's content to the specified {@link String}. The * visual console will be modified to show the current buffer. * * @param buffer * the new contents of the buffer. */ private final void setBuffer(final String buffer) throws IOException { // don't bother modifying it if it is unchanged if (buffer.equals(buf.buffer.toString())) { return; } // obtain the difference between the current buffer and the new one int sameIndex = 0; for (int i = 0, l1 = buffer.length(), l2 = buf.buffer.length(); (i < l1) && (i < l2); i++) { if (buffer.charAt(i) == buf.buffer.charAt(i)) { sameIndex++; } else { break; } } int diff = buf.buffer.length() - sameIndex; backspace(diff); // go back for the differences killLine(); // clear to the end of the line buf.buffer.setLength(sameIndex); // the new length putString(buffer.substring(sameIndex)); // append the differences } /** * Clear the line and redraw it. */ public final void redrawLine() throws IOException { printCharacter(RESET_LINE); flushConsole(); drawLine(); } /** * Output put the prompt + the current buffer */ public final void drawLine() throws IOException { if (prompt != null) { printString(prompt); } printString(buf.buffer.toString()); if (buf.length() != buf.cursor) // not at end of line back(buf.length() - buf.cursor); // sync } /** * Output a platform-dependant newline. */ public final void printNewline() throws IOException { printString(CR); flushConsole(); } /** * Clear the buffer and add its contents to the history. * * @return the former contents of the buffer. */ final String finishBuffer() { String str = buf.buffer.toString(); // we only add it to the history if the buffer is not empty // and if mask is null, since having a mask typically means // the string was a password. We clear the mask after this call if (str.length() > 0) { if (mask == null && useHistory) { history.addToHistory(str); } else { mask = null; } } history.moveToEnd(); buf.buffer.setLength(0); buf.cursor = 0; return str; } /** * Write out the specified string to the buffer and the output stream. */ public final void putString(final String str) throws IOException { buf.write(str); printString(str); drawBuffer(); } /** * Output the specified string to the output stream (but not the buffer). */ public final void printString(final String str) throws IOException { printCharacters(str.toCharArray()); } /** * Output the specified character, both to the buffer and the output stream. */ private final void putChar(final int c, final boolean print) throws IOException { buf.write((char) c); if (print) { // no masking... if (mask == null) { printCharacter(c); } // null mask: don't print anything... else if (mask.charValue() == 0) { ; } // otherwise print the mask... else { printCharacter(mask.charValue()); } drawBuffer(); } } /** * Redraw the rest of the buffer from the cursor onwards. This is necessary * for inserting text into the buffer. * * @param clear * the number of characters to clear after the end of the buffer */ private final void drawBuffer(final int clear) throws IOException { // debug ("drawBuffer: " + clear); char[] chars = buf.buffer.substring(buf.cursor).toCharArray(); if (mask != null) Arrays.fill(chars, mask.charValue()); printCharacters(chars); clearAhead(clear); back(chars.length); flushConsole(); } /** * Redraw the rest of the buffer from the cursor onwards. This is necessary * for inserting text into the buffer. */ private final void drawBuffer() throws IOException { drawBuffer(0); } /** * Clear ahead the specified number of characters without moving the cursor. */ private final void clearAhead(final int num) throws IOException { if (num == 0) { return; } // debug ("clearAhead: " + num); // print blank extra characters printCharacters(' ', num); // we need to flush here so a "clever" console // doesn't just ignore the redundancy of a space followed by // a backspace. flushConsole(); // reset the visual cursor back(num); flushConsole(); } /** * Move the visual cursor backwards without modifying the buffer cursor. */ private final void back(final int num) throws IOException { printCharacters(BACKSPACE, num); flushConsole(); } /** * Issue an audible keyboard bell, if {@link #getBellEnabled} return true. */ public final void beep() throws IOException { if (!(getBellEnabled())) { return; } printCharacter(KEYBOARD_BELL); // need to flush so the console actually beeps flushConsole(); } /** * Output the specified character to the output stream without manipulating * the current buffer. */ private final void printCharacter(final int c) throws IOException { out.write(c); } /** * Output the specified characters to the output stream without manipulating * the current buffer. */ private final void printCharacters(final char[] c) throws IOException { out.write(c); } private final void printCharacters(final char c, final int num) throws IOException { if (num == 1) { printCharacter(c); } else { char[] chars = new char[num]; Arrays.fill(chars, c); printCharacters(chars); } } /** * Flush the console output stream. This is important for printout out * single characters (like a backspace or keyboard) that we want the console * to handle immedately. */ public final void flushConsole() throws IOException { out.flush(); } private final int backspaceAll() throws IOException { return backspace(Integer.MAX_VALUE); } /** * Issue <em>num</em> backspaces. * * @return the number of characters backed up */ private final int backspace(final int num) throws IOException { if (buf.cursor == 0) { return 0; } int count = 0; count = moveCursor(-1 * num) * -1; // debug ("Deleting from " + buf.cursor + " for " + count); buf.buffer.delete(buf.cursor, buf.cursor + count); drawBuffer(count); return count; } /** * Issue a backspace. * * @return true if successful */ public final boolean backspace() throws IOException { return backspace(1) == 1; } private final boolean moveToEnd() throws IOException { if (moveCursor(1) == 0) { return false; } while (moveCursor(1) != 0) { ; } return true; } /** * Delete the character at the current position and redraw the remainder of * the buffer. */ private final boolean deleteCurrentCharacter() throws IOException { boolean success = buf.buffer.length() > 0; if (!success) { return false; } if (buf.cursor == buf.buffer.length()) { return false; } buf.buffer.deleteCharAt(buf.cursor); drawBuffer(1); return true; } private final boolean previousWord() throws IOException { while (isDelimiter(buf.current()) && (moveCursor(-1) != 0)) { ; } while (!isDelimiter(buf.current()) && (moveCursor(-1) != 0)) { ; } return true; } private final boolean nextWord() throws IOException { while (isDelimiter(buf.current()) && (moveCursor(1) != 0)) { ; } while (!isDelimiter(buf.current()) && (moveCursor(1) != 0)) { ; } return true; } private final boolean deletePreviousWord() throws IOException { while (isDelimiter(buf.current()) && backspace()) { ; } while (!isDelimiter(buf.current()) && backspace()) { ; } return true; } /** * Move the cursor <i>where</i> characters. * * @param where * if less than 0, move abs(<i>where</i>) to the left, * otherwise move <i>where</i> to the right. * * @return the number of spaces we moved */ private final int moveCursor(final int num) throws IOException { int where = num; if ((buf.cursor == 0) && (where < 0)) { return 0; } if ((buf.cursor == buf.buffer.length()) && (where > 0)) { return 0; } if ((buf.cursor + where) < 0) { where = -buf.cursor; } else if ((buf.cursor + where) > buf.buffer.length()) { where = buf.buffer.length() - buf.cursor; } moveInternal(where); return where; } /** * debug. * * @param str * the message to issue. */ public static void debug(final String str) { if (debugger != null) { debugger.println(str); debugger.flush(); } } /** * Move the cursor <i>where</i> characters, withough checking the current * buffer. * * @see #where * * @param where * the number of characters to move to the right or left. */ private final void moveInternal(final int where) throws IOException { // debug ("move cursor " + where + " (" // + buf.cursor + " => " + (buf.cursor + where) + ")"); buf.cursor += where; char c; if (where < 0) { c = BACKSPACE; } else if (buf.cursor == 0) { return; } else if (mask != null) { c = mask.charValue(); } else { c = buf.buffer.charAt(buf.cursor - 1); // draw replacement } // null character mask: don't output anything if (NULL_MASK.equals(mask)) { return; } printCharacters(c, Math.abs(where)); } /** * Read a character from the console. * * @return the character, or -1 if an EOF is received. */ public final int readVirtualKey() throws IOException { int c = terminal.readVirtualKey(in); if (debugger != null) { debug("keystroke: " + c + ""); } // clear any echo characters clearEcho(c); return c; } public final int readCharacter(final char[] allowed) throws IOException { // if we restrict to a limited set and the current character // is not in the set, then try again. char c; Arrays.sort(allowed); // always need to sort before binarySearch - while (Arrays.binarySearch(allowed, c = (char) readVirtualKey()) == -1) + while (Arrays.binarySearch(allowed, c = (char) readVirtualKey()) < 0) ; return c; } public void setHistory(final History history) { this.history = history; } public History getHistory() { return this.history; } public void setCompletionHandler(final CompletionHandler completionHandler) { this.completionHandler = completionHandler; } public CompletionHandler getCompletionHandler() { return this.completionHandler; } /** * <p> * Set the echo character. For example, to have "*" entered when a password * is typed: * </p> * * <pre> * myConsoleReader.setEchoCharacter(new Character('*')); * </pre> * * <p> * Setting the character to * * <pre> * null * </pre> * * will restore normal character echoing. Setting the character to * * <pre> * new Character(0) * </pre> * * will cause nothing to be echoed. * </p> * * @param echoCharacter * the character to echo to the console in place of the typed * character. */ public void setEchoCharacter(final Character echoCharacter) { this.echoCharacter = echoCharacter; } /** * Returns the echo character. */ public Character getEchoCharacter() { return this.echoCharacter; } /** * No-op for exceptions we want to silently consume. */ private void consumeException(final Throwable e) { } /** * Checks to see if the specified character is a delimiter. We consider a * character a delimiter if it is anything but a letter or digit. * * @param c * the character to test * @return true if it is a delimiter */ private boolean isDelimiter(char c) { return !Character.isLetterOrDigit(c); } /** * Whether or not to add new commands to the history buffer. */ public void setUseHistory(boolean useHistory) { this.useHistory = useHistory; } /** * Whether or not to add new commands to the history buffer. */ public boolean getUseHistory() { return useHistory; } /** * Whether to use pagination when the number of rows of candidates exceeds * the height of the temrinal. */ public void setUsePagination(boolean usePagination) { this.usePagination = usePagination; } /** * Whether to use pagination when the number of rows of candidates exceeds * the height of the temrinal. */ public boolean getUsePagination() { return this.usePagination; } }
true
false
null
null
diff --git a/job/converter/src/main/java/org/talend/esb/job/converter/internal/ConverterImpl.java b/job/converter/src/main/java/org/talend/esb/job/converter/internal/ConverterImpl.java index 4e01dfa25..bd9116369 100644 --- a/job/converter/src/main/java/org/talend/esb/job/converter/internal/ConverterImpl.java +++ b/job/converter/src/main/java/org/talend/esb/job/converter/internal/ConverterImpl.java @@ -1,169 +1,168 @@ package org.talend.esb.job.converter.internal; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; +import java.io.*; import java.util.Enumeration; +import java.util.Properties; +import java.util.jar.Manifest; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; +import java.util.zip.ZipOutputStream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.talend.esb.job.converter.Converter; import aQute.lib.osgi.Builder; import aQute.lib.osgi.Jar; /** * Default implementation of a job transformer. */ public class ConverterImpl implements Converter { private Logger logger = LoggerFactory.getLogger(ConverterImpl.class); public void convertToBundle(File sourceJob, String jobName, String jobClassName, boolean deleteSourceJob) throws Exception { logger.info("Converting Talend job into OSGi bundle ..."); logger.debug("Creating Talend job OSGi jar ..."); long timestamp = System.currentTimeMillis(); File uncompressDir = new File("convert" + timestamp); logger.debug("Create working directory {}", uncompressDir.getPath()); uncompressDir.mkdirs(); String outputName = sourceJob.getName(); if (outputName.length() > 0 && outputName.endsWith(".zip")) { outputName = outputName.substring(0, outputName.length()-4); } File osgiJobLocation = new File(sourceJob.getParentFile(), outputName + ".jar"); logger.debug("Unzip Talend job {} ...", osgiJobLocation); ZipFile jobZipFile = new ZipFile(sourceJob); Enumeration<? extends ZipEntry> jobZipEntries = jobZipFile.entries(); while (jobZipEntries.hasMoreElements()) { ZipEntry jobZipEntry = jobZipEntries.nextElement(); if (!jobZipEntry.isDirectory() && jobZipEntry.getName().endsWith(".jar")) { logger.debug("Unzip {}", jobZipEntry.getName()); String name = jobZipEntry.getName(); int index = name.lastIndexOf("/"); if (index != 0) { name = name.substring(index); } InputStream inputStream = jobZipFile.getInputStream(jobZipEntry); FileOutputStream fos = new FileOutputStream(new File(uncompressDir, name)); copyInputStream(inputStream, fos); inputStream.close(); fos.flush(); fos.close(); } } logger.debug("Create job.properties"); Properties jobProperties = new Properties(); jobProperties.setProperty("version", "1.0"); logger.debug("Add job.properties in the resources zip"); ZipOutputStream resourcesZip = new ZipOutputStream(new FileOutputStream(new File(uncompressDir, "resources_" + timestamp + ".zip"))); if (jobName != null && jobClassName != null) { logger.debug("Update job.properties"); jobProperties.setProperty("job.blueprint", "true"); jobProperties.setProperty("job.name", jobName); jobProperties.setProperty("job.class.name", jobClassName); logger.debug("Append OSGi blueprint descriptor"); // TODO logger.debug("Replace in the OSGi blueprint descriptor"); // TODO logger.debug("Add OSGi blueprint descriptor in the resources zip"); ZipEntry resourceBlueprint = new ZipEntry("resources/OSGI-INF/blueprint/job.xml"); resourcesZip.putNextEntry(resourceBlueprint); copyInputStream(Thread.currentThread().getContextClassLoader().getResourceAsStream("resources/OSGI-INF/blueprint/job.xml"), resourcesZip); } logger.debug("Write job.properties"); File jobPropertiesFile = new File(uncompressDir, "job.properties"); jobProperties.store(new FileOutputStream(jobPropertiesFile), null); logger.debug("Add job.properties in the resources zip"); ZipEntry resourceJobProperties = new ZipEntry("META-INF/job.properties"); resourcesZip.putNextEntry(resourceJobProperties); copyInputStream(new FileInputStream(jobPropertiesFile), resourcesZip); logger.debug("Close the resources zip"); resourcesZip.flush(); resourcesZip.close(); logger.debug("Creating Talend bundle jar (using BND)"); Builder builder = new Builder(); builder.setProperty("Bundle-Name", outputName); builder.setProperty("Bundle-SymbolicName", outputName); // TODO extract the bundle version from the file name builder.setProperty("Bundle-Version", "4.0"); builder.setProperty("Export-Package", "!routines*,*"); builder.setProperty("Private-Package", "routines*"); builder.setProperty("Import-Package", "*;resolution:=optional"); logger.debug("Iterate in the working directory"); File[] files = uncompressDir.listFiles(); for (int i = 0; i < files.length; i++) { if (files[i].getName().endsWith(".jar") || files[i].getName().endsWith(".zip")) { logger.debug("Add jar file {}", files[i].getName()); builder.addClasspath(files[i]); } files[i].delete(); } Jar jar = builder.build(); Manifest manifest = jar.getManifest(); jar.write(osgiJobLocation); logger.debug("Delete working directory {}", uncompressDir.getPath()); uncompressDir.delete(); if (deleteSourceJob) { logger.debug("Delete source job {}", sourceJob); sourceJob.delete(); } } public void convertToBundle(File sourceJob, boolean deleteSourceJob) throws Exception { this.convertToBundle(sourceJob, null, null, deleteSourceJob); } /** * Just copy from an input stream to an output stream. * * @param in the input stream. * @param out the output stream. * @throws IOException in case of copy failure. */ private static void copyInputStream(InputStream in, OutputStream out) throws IOException { byte[] buffer = new byte[8192]; int len = in.read(buffer); while (len >= 0) { out.write(buffer, 0, len); len = in.read(buffer); } } private static boolean deleteDir(File path) { if( path.exists() ) { File[] files = path.listFiles(); for(int i=0; i<files.length; i++) { if(files[i].isDirectory()) { deleteDir(files[i]); } else { files[i].delete(); } } } return( path.delete() ); } }
false
false
null
null
diff --git a/java/marytts/modules/PronunciationModel.java b/java/marytts/modules/PronunciationModel.java index 243153f02..82a662dfb 100644 --- a/java/marytts/modules/PronunciationModel.java +++ b/java/marytts/modules/PronunciationModel.java @@ -1,389 +1,392 @@ /** * Copyright 2008 DFKI GmbH. * All Rights Reserved. Use is subject to license terms. * * This file is part of MARY TTS. * * MARY TTS is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, version 3 of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package marytts.modules; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.StringTokenizer; import java.util.regex.Matcher; import java.util.regex.Pattern; import marytts.cart.StringPredictionTree; import marytts.datatypes.MaryData; import marytts.datatypes.MaryDataType; import marytts.datatypes.MaryXML; import marytts.features.FeatureDefinition; import marytts.features.FeatureProcessorManager; import marytts.features.TargetFeatureComputer; import marytts.modules.phonemiser.Allophone; import marytts.modules.phonemiser.AllophoneSet; import marytts.modules.synthesis.Voice; import marytts.server.MaryProperties; import marytts.unitselection.select.Target; import marytts.util.MaryUtils; import marytts.util.dom.MaryDomUtils; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.traversal.TreeWalker; /** * * This module serves as a post-lexical pronunciation model. * Its appropriate place in the module chain is after intonisation. * The target features are taken * and fed into decision trees that predict the new pronunciation. * A new mary xml is output, with the difference being that the old * pronunciation is replaced by the newly predicted one, and a finer grained * xml structure. * * @author ben * */ public class PronunciationModel extends InternalModule { // for prediction, core of the model - maps phones to decision trees private Map<String, StringPredictionTree> treeMap; // used in startup() and later for convenience private FeatureDefinition featDef; private TargetFeatureComputer featureComputer; /** * Constructor, stating that the input is of type INTONATION, the output * of type ALLOPHONES. * */ public PronunciationModel() { this(null); } public PronunciationModel(Locale locale) { super("PronunciationModel", MaryDataType.INTONATION, MaryDataType.ALLOPHONES, locale); } public void startup() throws Exception { super.startup(); // TODO: pronunciation model tree and feature definition should be voice-specific // get featureDefinition used for trees - just to tell the tree that the // features are discrete String fdFilename = null; if (getLocale() != null) { fdFilename = MaryProperties.getFilename(MaryProperties.localePrefix(getLocale()) +".pronunciation.featuredefinition"); } if (fdFilename != null) { File fdFile = new File(fdFilename); // reader for file, readweights = false featDef = new FeatureDefinition(new BufferedReader(new FileReader(fdFile)), false); // get path where the prediction trees lie File treePath = new File(MaryProperties.needFilename( MaryProperties.localePrefix(getLocale())+".pronunciation.treepath")); // valid predicion tree files are named prediction_<phone_symbol>.tree Pattern treeFilePattern = Pattern.compile("^prediction_(.*)\\.tree$"); // initialize the map that contains the trees this.treeMap = new HashMap<String, StringPredictionTree>(); // iterate through potential prediction tree files File[] fileArray = treePath.listFiles(); for ( int fileIndex = 0 ; fileIndex < fileArray.length ; fileIndex++ ) { File f = fileArray[ fileIndex ]; // is file name valid? Matcher filePatternMatcher = treeFilePattern.matcher(f.getName()); if ( filePatternMatcher.matches() ){ // phone of file name is a group in the regex String phoneId = filePatternMatcher.group(1); // construct tree from file and map phone to it StringPredictionTree predictionTree = new StringPredictionTree( new BufferedReader( new FileReader( f ) ), featDef ); // back mapping from short id int index = this.featDef.getFeatureIndex("phone"); this.treeMap.put( this.featDef.getFeatureValueAsString(index, Short.parseShort(phoneId)), predictionTree); //logger.debug("Read in tree for " + PhoneNameConverter.normForm2phone(phone)); } } logger.debug("Reading in feature definition and decision trees finished."); // TODO: change property name to german.pronunciation.featuremanager/features String managerClass = MaryProperties.needProperty( MaryProperties.localePrefix(getLocale())+".pronunciation.targetfeaturelister.featuremanager"); FeatureProcessorManager manager = (FeatureProcessorManager) Class.forName(managerClass).newInstance(); String features = MaryProperties.needProperty( MaryProperties.localePrefix(getLocale())+".pronunciation.targetfeaturelister.features"); this.featureComputer = new TargetFeatureComputer(manager, features); } logger.debug("Building feature computer finished."); } /** * Optionally, a language-specific subclass can implement any postlexical rules * on the document. * @param token a <t> element with a <syllable> and <ph> substructure. * @param allophoneSet * @return true if something was changed, false otherwise */ protected boolean postlexicalRules(Element token, AllophoneSet allophoneSet) { return false; } /** * This computes a new pronunciation for the elements of some MaryData, that * is phonemised. */ public MaryData process(MaryData d) throws Exception { // get the xml document Document doc = d.getDocument(); logger.debug("Getting xml-data from document finished."); TreeWalker tw = MaryDomUtils.createTreeWalker(doc, doc, MaryXML.TOKEN); Element t; AllophoneSet allophoneSet = null; while ((t = (Element) tw.nextNode()) != null) { // First, create the substructure of <t> elements: <syllable> and <ph>. if (allophoneSet == null) { // need to determine it once, then assume it is the same for all allophoneSet = AllophoneSet.determineAllophoneSet(t); } createSubStructure(t, allophoneSet); // Modify by rule: boolean changedSomething = postlexicalRules(t, allophoneSet); if (changedSomething) { updatePhAttributesFromPhElements(t); } if (treeMap == null) continue; // Modify by trained model: assert featureComputer != null; // Now, predict modified pronunciations, adapt <ph> elements accordingly, // and update ph for syllable and t elements where necessary StringBuilder tPh = new StringBuilder(); TreeWalker sylWalker = MaryDomUtils.createTreeWalker(doc, t, MaryXML.SYLLABLE); Element syllable; while ((syllable = (Element) sylWalker.nextNode()) != null) { StringBuilder sylPh = new StringBuilder(); String stressed = syllable.getAttribute("stress"); if (stressed.equals("1")) { sylPh.append("'"); } else if (stressed.equals("2")) { sylPh.append(","); } TreeWalker segWalker = MaryDomUtils.createTreeWalker(doc, syllable, MaryXML.PHONE); Element seg; // Cannot use tree walker directly, because we concurrently modify the tree: List<Element> originalSegments = new ArrayList<Element>(); while ((seg = (Element) segWalker.nextNode()) != null) { originalSegments.add(seg); } for (Element s : originalSegments) { String phoneString = s.getAttribute("p"); String[] predicted; // in case we have a decision tree for phone, predict - otherwise leave unchanged if ( treeMap.containsKey( phoneString ) ) { Target tgt = new Target(phoneString, s); tgt.setFeatureVector(featureComputer.computeFeatureVector(tgt)); StringPredictionTree tree = ( StringPredictionTree ) treeMap.get(phoneString); String predictStr = tree.getMostProbableString(tgt); if (sylPh.length() > 0) sylPh.append(" "); sylPh.append(predictStr); // if phone is deleted: if ( predictStr.equals("") ){ predicted = null; } else { // predictStr contains whitespace between phones predicted = predictStr.split(" "); } } else { logger.debug("didn't find decision tree for phone ("+ phoneString + "). Just keeping it."); predicted = new String[]{phoneString}; } logger.debug(" Predicted phone in sequence of " + predicted.length + " phones." ); // deletions: if (predicted == null || predicted.length == 0) { syllable.removeChild(s); continue; // skip what follows } assert predicted != null && predicted.length > 0; // insertions: for each but the last predicted phone, make a new element for ( int lc = 0 ; lc < predicted.length - 1 ; lc++) { Element newPh = MaryXML.createElement(doc, MaryXML.PHONE); newPh.setAttribute("p", predicted[lc]); syllable.insertBefore(newPh, s); } // for the last (or only) predicted segment, just update the phone label if (!phoneString.equals(predicted[predicted.length - 1])) { s.setAttribute("p", predicted[predicted.length - 1]); } } // for each segment in syllable String newSylPh = sylPh.toString(); syllable.setAttribute("ph", newSylPh); if (tPh.length() > 0) tPh.append(" -"); // syllable boundary tPh.append(newSylPh); } // for each syllable in token t.setAttribute("ph", tPh.toString()); } // for each token in document // return new MaryData with changed phonology MaryData result = new MaryData(outputType(), d.getLocale()); result.setDocument(doc); logger.debug("Setting the changed xml document finished."); return result; } private void createSubStructure(Element token, AllophoneSet allophoneSet) { String phone = token.getAttribute("ph"); if (phone.equals("")) return; // nothing to do if (token.getElementsByTagName(MaryXML.SYLLABLE).getLength() > 0) { return; // there is already a substructure under this token; nothing to do } StringTokenizer tok = new StringTokenizer(phone, "-"); Document document = token.getOwnerDocument(); Element prosody = (Element) MaryDomUtils.getAncestor(token, MaryXML.PROSODY); String vq = null; // voice quality if (prosody != null) { // Ignore any effects of ancestor prosody tags for now: String volumeString = prosody.getAttribute("volume"); int volume = -1; try { volume = Integer.parseInt(volumeString); } catch (NumberFormatException e) {} if (volume >= 0) { if (volume >= 60) { vq = "loud"; } else if (volume <= 40) { vq = "soft"; } else { vq = null; } } } while (tok.hasMoreTokens()) { String sylString = tok.nextToken(); + if (sylString.trim().isEmpty()) { + continue; + } Allophone[] allophones = allophoneSet.splitIntoAllophones(sylString); Element syllable = MaryXML.createElement(document, MaryXML.SYLLABLE); token.appendChild(syllable); String syllableText = ""; for (int i = 0; i < allophones.length; i++) { if(allophones[i].isTone()) { syllable.setAttribute("tone", allophones[i].name()); continue; } if(i==0) { syllableText = allophones[i].name(); } else { syllableText = syllableText+" "+allophones[i].name(); } } // Check for stress signs: String first = sylString.trim().substring(0, 1); if (first.equals("'")) { syllable.setAttribute("stress", "1"); // The primary stressed syllable of a word // inherits the accent: if (token.hasAttribute("accent")) { syllable.setAttribute("accent", token.getAttribute("accent")); } } else if (first.equals(",")) { syllable.setAttribute("stress", "2"); } // Remember transcription in ph attribute: syllable.setAttribute("ph", syllableText); // Now identify the composing segments: for (int i = 0; i < allophones.length; i++) { if (allophones[i].isTone()) { continue; } Element segment = MaryXML.createElement(document, MaryXML.PHONE); syllable.appendChild(segment); segment.setAttribute("p", allophones[i].name()); if (vq != null && !(allophones[i].name().equals("_") || allophones[i].name().equals("?"))) { segment.setAttribute("vq", vq); } } } } protected void updatePhAttributesFromPhElements(Element token) { if (token == null) throw new NullPointerException("Got null token"); if (!token.getTagName().equals(MaryXML.TOKEN)) { throw new IllegalArgumentException("Argument should be a <"+MaryXML.TOKEN+">, not a <"+token.getTagName()+">"); } StringBuilder tPh = new StringBuilder(); TreeWalker sylWalker = MaryDomUtils.createTreeWalker(token, MaryXML.SYLLABLE); Element syl; while ((syl = (Element) sylWalker.nextNode()) != null) { StringBuilder sylPh = new StringBuilder(); String stress = syl.getAttribute("stress"); if (stress.equals("1")) sylPh.append("'"); else if (stress.equals("2")) sylPh.append(","); TreeWalker phWalker = MaryDomUtils.createTreeWalker(syl, MaryXML.PHONE); Element ph; while ((ph = (Element) phWalker.nextNode()) != null) { if (sylPh.length() > 0) sylPh.append(" "); sylPh.append(ph.getAttribute("p")); } String sylPhString = sylPh.toString(); syl.setAttribute("ph", sylPhString); if (tPh.length() > 0) tPh.append(" - "); tPh.append(sylPhString); if (syl.hasAttribute("tone")) { tPh.append(" "+syl.getAttribute("tone")); } } token.setAttribute("ph", tPh.toString()); } }
true
false
null
null
diff --git a/src/com/themagpi/activities/MagpiMainActivity.java b/src/com/themagpi/activities/MagpiMainActivity.java index 5b589f3..4a4f155 100644 --- a/src/com/themagpi/activities/MagpiMainActivity.java +++ b/src/com/themagpi/activities/MagpiMainActivity.java @@ -1,170 +1,174 @@ package com.themagpi.activities; import java.util.Calendar; import java.util.List; import java.util.Vector; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.view.ViewPager; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.widget.ArrayAdapter; import android.widget.SpinnerAdapter; import com.actionbarsherlock.app.ActionBar.OnNavigationListener; import com.actionbarsherlock.app.SherlockFragment; import com.actionbarsherlock.app.SherlockFragmentActivity; import com.actionbarsherlock.view.Menu; import com.google.android.gcm.GCMRegistrar; import com.themagpi.adapters.PagerAdapter; import com.themagpi.android.CompatActionBarNavHandler; import com.themagpi.android.CompatActionBarNavListener; import com.themagpi.android.Config; import com.themagpi.android.R; import com.themagpi.api.MagPiClient; import com.themagpi.fragments.IssuesFragment; import com.themagpi.fragments.NewsFragment; import com.themagpi.interfaces.Refreshable; import com.themagpi.interfaces.RefreshableContainer; public class MagpiMainActivity extends SherlockFragmentActivity implements ViewPager.OnPageChangeListener , CompatActionBarNavListener, RefreshableContainer { OnNavigationListener mOnNavigationListener; SherlockFragment currentFragment; private PagerAdapter mPagerAdapter; private ViewPager mViewPager; private Menu menu; private LayoutInflater inflater; @Override public boolean onCreateOptionsMenu(Menu menu) { this.menu = menu; getSupportMenuInflater().inflate(R.menu.activity_magpi, menu); this.inflater = (LayoutInflater) ((SherlockFragmentActivity) this).getSupportActionBar().getThemedContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); return true; } private void intialiseViewPager() { List<Fragment> fragments = new Vector<Fragment>(); fragments.add(Fragment.instantiate(this, IssuesFragment.class.getName())); fragments.add(Fragment.instantiate(this, NewsFragment.class.getName())); this.mPagerAdapter = new PagerAdapter(super.getSupportFragmentManager(), fragments); this.mViewPager = (ViewPager)super.findViewById(R.id.viewpager); this.mViewPager.setAdapter(this.mPagerAdapter); this.mViewPager.setOnPageChangeListener(this); } @Override public boolean onOptionsItemSelected(com.actionbarsherlock.view.MenuItem item) { switch(item.getItemId()) { case R.id.menu_refresh: refreshFragment((Refreshable)this.mPagerAdapter.getItem(mViewPager.getCurrentItem())); break; case R.id.menu_settings: Intent intent = new Intent(this, MagpiSettingsActivity.class); startActivity(intent); break; } return super.onOptionsItemSelected(item); } public void refreshFragment(Refreshable fragment) { if(fragment != null) fragment.refresh(); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_magpi_main); - GCMRegistrar.checkDevice(this); - GCMRegistrar.checkManifest(this); - final String idGcm = GCMRegistrar.getRegistrationId(this); - if (TextUtils.isEmpty(idGcm)) { - Log.e("GCM", "NOT registered"); - GCMRegistrar.register(MagpiMainActivity.this, Config.SENDER_ID); - } else { - Log.e("GCM", "Already registered" + idGcm); - if(isTimeToRegister()) - new MagPiClient().registerDevice(this, idGcm); - } + try { + GCMRegistrar.checkDevice(this); + GCMRegistrar.checkManifest(this); + final String idGcm = GCMRegistrar.getRegistrationId(this); + if (TextUtils.isEmpty(idGcm)) { + Log.e("GCM", "NOT registered"); + GCMRegistrar.register(MagpiMainActivity.this, Config.SENDER_ID); + } else { + Log.e("GCM", "Already registered" + idGcm); + if(isTimeToRegister()) + new MagPiClient().registerDevice(this, idGcm); + } + } catch (UnsupportedOperationException ex) { + Log.e("GCM", "Google Cloud Messaging not supported - please install Google Apps package!"); + } mOnNavigationListener = new OnNavigationListener() { @Override public boolean onNavigationItemSelected(int position, long itemId) { return true; } }; this.intialiseViewPager(); CompatActionBarNavHandler handler = new CompatActionBarNavHandler(this); SpinnerAdapter mSpinnerAdapter = ArrayAdapter.createFromResource(this, R.array.dropdown_array, android.R.layout.simple_spinner_dropdown_item); getSupportActionBar().setListNavigationCallbacks(mSpinnerAdapter, mOnNavigationListener); getSupportActionBar().setNavigationMode(android.app.ActionBar.NAVIGATION_MODE_TABS); final String CATEGORIES[] = getResources().getStringArray(R.array.dropdown_array); for (int i = 0; i < CATEGORIES.length; i++) { this.getSupportActionBar().addTab(this.getSupportActionBar().newTab().setText( CATEGORIES[i]).setTabListener(handler)); } getSupportActionBar().setSelectedNavigationItem(0); } private boolean isTimeToRegister() { SharedPreferences prefs = this.getSharedPreferences("MAGPI_REGISTRATION", Context.MODE_PRIVATE); long timeLastRegistration = prefs.getLong("TIME_LAST_REG", 0L); long currentTime = Calendar.getInstance().getTimeInMillis(); Log.e("NOW", ""+ currentTime); Log.e("LAST",""+timeLastRegistration); if(currentTime > timeLastRegistration + 86400000L) return true; return false; } @Override public void onCategorySelected(int catIndex) { this.mViewPager.setCurrentItem(catIndex); } @Override public void onPageScrollStateChanged(int arg0) { } @Override public void onPageScrolled(int arg0, float arg1, int arg2) { } @Override public void onPageSelected(int pos) { getSupportActionBar().setSelectedNavigationItem(pos); } @Override public void startRefreshIndicator() { if(menu != null) menu.findItem(R.id.menu_refresh).setActionView(inflater.inflate(R.layout.actionbar_refresh_progress, null)); } @Override public void stopRefreshIndicator() { if(menu != null) menu.findItem(R.id.menu_refresh).setActionView(null); } }
true
true
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_magpi_main); GCMRegistrar.checkDevice(this); GCMRegistrar.checkManifest(this); final String idGcm = GCMRegistrar.getRegistrationId(this); if (TextUtils.isEmpty(idGcm)) { Log.e("GCM", "NOT registered"); GCMRegistrar.register(MagpiMainActivity.this, Config.SENDER_ID); } else { Log.e("GCM", "Already registered" + idGcm); if(isTimeToRegister()) new MagPiClient().registerDevice(this, idGcm); } mOnNavigationListener = new OnNavigationListener() { @Override public boolean onNavigationItemSelected(int position, long itemId) { return true; } }; this.intialiseViewPager(); CompatActionBarNavHandler handler = new CompatActionBarNavHandler(this); SpinnerAdapter mSpinnerAdapter = ArrayAdapter.createFromResource(this, R.array.dropdown_array, android.R.layout.simple_spinner_dropdown_item); getSupportActionBar().setListNavigationCallbacks(mSpinnerAdapter, mOnNavigationListener); getSupportActionBar().setNavigationMode(android.app.ActionBar.NAVIGATION_MODE_TABS); final String CATEGORIES[] = getResources().getStringArray(R.array.dropdown_array); for (int i = 0; i < CATEGORIES.length; i++) { this.getSupportActionBar().addTab(this.getSupportActionBar().newTab().setText( CATEGORIES[i]).setTabListener(handler)); } getSupportActionBar().setSelectedNavigationItem(0); }
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_magpi_main); try { GCMRegistrar.checkDevice(this); GCMRegistrar.checkManifest(this); final String idGcm = GCMRegistrar.getRegistrationId(this); if (TextUtils.isEmpty(idGcm)) { Log.e("GCM", "NOT registered"); GCMRegistrar.register(MagpiMainActivity.this, Config.SENDER_ID); } else { Log.e("GCM", "Already registered" + idGcm); if(isTimeToRegister()) new MagPiClient().registerDevice(this, idGcm); } } catch (UnsupportedOperationException ex) { Log.e("GCM", "Google Cloud Messaging not supported - please install Google Apps package!"); } mOnNavigationListener = new OnNavigationListener() { @Override public boolean onNavigationItemSelected(int position, long itemId) { return true; } }; this.intialiseViewPager(); CompatActionBarNavHandler handler = new CompatActionBarNavHandler(this); SpinnerAdapter mSpinnerAdapter = ArrayAdapter.createFromResource(this, R.array.dropdown_array, android.R.layout.simple_spinner_dropdown_item); getSupportActionBar().setListNavigationCallbacks(mSpinnerAdapter, mOnNavigationListener); getSupportActionBar().setNavigationMode(android.app.ActionBar.NAVIGATION_MODE_TABS); final String CATEGORIES[] = getResources().getStringArray(R.array.dropdown_array); for (int i = 0; i < CATEGORIES.length; i++) { this.getSupportActionBar().addTab(this.getSupportActionBar().newTab().setText( CATEGORIES[i]).setTabListener(handler)); } getSupportActionBar().setSelectedNavigationItem(0); }
diff --git a/application/src/com.phdroid/smsb/utility/SmsMessageTransferObject.java b/application/src/com.phdroid/smsb/utility/SmsMessageTransferObject.java index 495f597..3f0316f 100644 --- a/application/src/com.phdroid/smsb/utility/SmsMessageTransferObject.java +++ b/application/src/com.phdroid/smsb/utility/SmsMessageTransferObject.java @@ -1,31 +1,30 @@ package com.phdroid.smsb.utility; import android.telephony.SmsMessage; /** * Android Sms Message with pretty interface. */ public class SmsMessageTransferObject { private SmsMessage innerMessage; public SmsMessageTransferObject(SmsMessage message) { - this.innerMessage = innerMessage; + this.innerMessage = message; } public String getSender() { return innerMessage.getDisplayOriginatingAddress(); } public boolean isRead() { return false; } public String getMessage() { return innerMessage.getDisplayMessageBody(); } public long getReceived() { return innerMessage.getTimestampMillis(); } - }
false
false
null
null
diff --git a/wayback-core/src/main/java/org/archive/wayback/util/htmllex/ParseContext.java b/wayback-core/src/main/java/org/archive/wayback/util/htmllex/ParseContext.java index 3e2b68f58..1af54f87e 100644 --- a/wayback-core/src/main/java/org/archive/wayback/util/htmllex/ParseContext.java +++ b/wayback-core/src/main/java/org/archive/wayback/util/htmllex/ParseContext.java @@ -1,174 +1,178 @@ /* * This file is part of the Wayback archival access software * (http://archive-access.sourceforge.net/projects/wayback/). * * Licensed to the Internet Archive (IA) by one or more individual * contributors. * * The IA licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.archive.wayback.util.htmllex; import java.net.URISyntaxException; import java.net.URL; import java.util.HashMap; import java.util.Map; import org.apache.commons.httpclient.URIException; import org.apache.commons.lang.StringEscapeUtils; import org.archive.net.UURI; import org.archive.net.UURIFactory; -import org.htmlparser.util.Translate; /** * Class which tracks the context and state involved with parsing an HTML * document via SAX events. * * Also holds some page URL information, and provides some URL resolving * functionality. * * Lastly, this class exposes a general purpose HashMap<String,String> for use * by specific applications. * * @author brad * @version $Date$, $Revision$ */ public class ParseContext { protected UURI baseUrl = null; private boolean inCSS = false; private boolean inJS = false; private boolean inScriptText = false; private HashMap<String,String> data = null; /** * constructor */ public ParseContext() { data = new HashMap<String, String>(); } /** * Stores arbitrary key value pairs in this ParseContext * @param key for storage * @param value for storage */ public void putData(String key, String value) { data.put(key, value); } /** * Retrieves previously stored data for key key from this ParseContext * @param key under which value was stored * @return previously stored value for key or null, if nothing was stored */ public String getData(String key) { return data.get(key); } + + /** + * @return the full Map of String to String for this parsing context. + */ public Map<String,String> getMap() { return data; } /** * @param url against which relative URLs should be resolved for this parse */ public void setBaseUrl(URL url) { try { baseUrl = UURIFactory.getInstance(url.toExternalForm()); } catch (URIException e) { e.printStackTrace(); } } /** * @param url which should be resolved against the baseUrl for this * ParseContext. * @return absolute form of url, resolved against baseUrl if relative. * @throws URISyntaxException if the input URL is malformed */ public String resolve(String url) throws URISyntaxException { // BUG in Translate.decode(): "foo?a=b&lang=en" acts as if it // was "&lang;" // url = Translate.decode(url); url = StringEscapeUtils.unescapeHtml(url); int hashIdx = url.indexOf('#'); String frag = ""; if(hashIdx != -1) { frag = url.substring(hashIdx); url = url.substring(0,hashIdx); } + + if(baseUrl == null) { + // TODO: log ? + return url + frag; + } + try { - if(baseUrl == null) { - // TODO: log - System.err.println("No url to resolve!"); - return url; - } - return baseUrl.resolve(url,true).toString() + frag; -// return baseUrl.resolve(url,false).toString() + frag; -// return UURIFactory.getInstance(baseUrl, url).toString() + frag; + + return UURIFactory.getInstance(baseUrl, url).toString() + frag; } catch (URIException e) { e.printStackTrace(); } return url; - } + } + /** * @param url which should be resolved. * @return absolute form of input url, or url itself if javascript: */ public String contextualizeUrl(String url) { if(url.startsWith("javascript:")) { return url; } try { return resolve(url); } catch (URISyntaxException e) { e.printStackTrace(); return url; } } /** * @return the inCSS */ public boolean isInCSS() { return inCSS; } /** * @param inCSS the inCSS to set */ public void setInCSS(boolean inCSS) { this.inCSS = inCSS; } /** * @return the inJS */ public boolean isInJS() { return inJS; } /** * @param inJS the inJS to set */ public void setInJS(boolean inJS) { this.inJS = inJS; } /** * @return the inScriptText */ public boolean isInScriptText() { return inScriptText; } /** * @param inScriptText the inScriptText to set */ public void setInScriptText(boolean inScriptText) { this.inScriptText = inScriptText; } }
false
false
null
null
diff --git a/src/minechess/common/MineChessUtils.java b/src/minechess/common/MineChessUtils.java index 73f3eed..c0c4d87 100644 --- a/src/minechess/common/MineChessUtils.java +++ b/src/minechess/common/MineChessUtils.java @@ -1,130 +1,131 @@ package minechess.common; import java.util.List; import java.util.Random; import net.minecraft.block.Block; import net.minecraft.entity.monster.EntityCreeper; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.potion.Potion; import net.minecraft.potion.PotionEffect; import net.minecraft.util.EnumChatFormatting; import net.minecraft.util.MathHelper; import net.minecraft.world.World; import cpw.mods.fml.common.network.PacketDispatcher; import cpw.mods.fml.common.network.Player; public class MineChessUtils{ // private Potion[] badPotions = {Potion.blindness, Potion.confusion, // Potion.digSlowdown, Potion.hunger, Potion.moveSlowdown, Potion.poison, // Potion.weakness}; public static int determineOrientation(EntityPlayer par4EntityPlayer){ return MathHelper.floor_double(par4EntityPlayer.rotationYaw * 4.0F / 360.0F) & 3; } public static void generateChessBoard(World world, int x, int y, int z){ for(int i = 0; i < 8; i++) { for(int j = 0; j < 8; j++) { boolean even = (i + j) % 2 == 0; world.setBlock(i + x, y, j + z, Block.cloth.blockID, even ? 0 : 15, 3); } } } public static void spawnParticle(String particleName, double x, double y, double z, double velX, double velY, double velZ){ PacketDispatcher.sendPacketToAllPlayers(PacketHandler.spawnParticle(particleName, x, y, z, velX, velY, velZ)); } public static void onPuzzleFail(World world, EntityPlayer player, EntityBaseChessPiece piece, int x, int y, int z, Random rand){ int randEffect = 0; do { randEffect = rand.nextInt(4); } while(randEffect == 3 && player == null);//Only allow the potion effect punishment when we have a player to apply the effects to. switch(randEffect){ case 0: // generate fire underneath the chessboard, under each of the 64 // tiles. for(int i = 0; i < 8; i++) { for(int j = 0; j < 8; j++) { world.setBlock(x + i, y - 2, z + j, Block.fire.blockID, 1, 3); } } if(player != null) AchievementHandler.giveAchievement(player, AchievementHandler.PUZZLE_FAIL_FIRE); return; case 1: // play a creepy sound. A maximum of 5 creepers spawn around the // chessboard. PacketDispatcher.sendPacketToAllAround(x, y, z, Constants.PACKET_UPDATE_DISTANCE, world.provider.dimensionId, PacketHandler.playSound(x, y, z, "ambient.cave.cave", 1.0F, 1.0F, true)); int entityCount = 0; boolean firstCreeper = true; for(int i = 0; i < 50; i++) { int randX = x + rand.nextInt(20) - 12; if(randX >= x - 2 && randX <= x + 9) randX += 12; int randZ = z + rand.nextInt(20) - 10; if(randZ >= z - 2 && randZ <= z + 9) randZ += 12; int randY = y + rand.nextInt(6) - 3; - if(world.getBlockId(randX, randY, randZ) == 0 && world.getBlockId(randX, randY + 1, randZ) == 0) { + if(world.isAirBlock(randX, randY, randZ) && world.isAirBlock(randX, randY + 1, randZ)) { EntityCreeper creeper = new EntityCreeper(world); + creeper.setPosition(randX + 0.5D, randY, randZ + 0.5D); creeper.setTarget(player); // make the creeper already // knowing where the player // is. if(firstCreeper) creeper.onStruckByLightning(null); firstCreeper = false; world.spawnEntityInWorld(creeper); entityCount++; if(entityCount >= 5) return; } } if(player != null) AchievementHandler.giveAchievement(player, AchievementHandler.PUZZLE_FAIL_CREEPER); return; case 2: // Turn every dying enemy chesspiece into mobs. List<EntityBaseChessPiece> pieces = piece.getChessPieces(false); for(EntityBaseChessPiece chessPiece : pieces) { if(chessPiece.isBlack() != piece.isBlack()) chessPiece.turnToMobOnDeath = true; } if(player != null) AchievementHandler.giveAchievement(player, AchievementHandler.PUZZLE_FAIL_TRANSFORM); return; case 3: // give the player random potion effects. int potionAmount = 2 + rand.nextInt(3); // 2-4 potion effects for(int i = 0; i < potionAmount; i++) { Potion randomPotion; do { randomPotion = Potion.potionTypes[rand.nextInt(20) + 1]; } while(!isPotionBadEffect(randomPotion.id) || randomPotion == Potion.harm); player.addPotionEffect(new PotionEffect(randomPotion.id, 200 + rand.nextInt(400))); //make the potion effect last for 10-30 secs. } if(player != null) AchievementHandler.giveAchievement(player, AchievementHandler.PUZZLE_FAIL_POTION); return; } } public static boolean isPotionBadEffect(int potionID){ switch(potionID){ case 2: case 4: case 9: case 15: case 17: case 18: case 19: case 20: return true; } return false; } public static void sendUnlocalizedMessage(EntityPlayer player, String message){ sendUnlocalizedMessage(player, message, EnumChatFormatting.WHITE.toString()); } public static void sendUnlocalizedMessage(EntityPlayer player, String message, String... replacements){ PacketDispatcher.sendPacketToPlayer(PacketHandler.getChatMessagePacket(message, replacements), (Player)player); } }
false
false
null
null
diff --git a/src/test/java/com/sensetecnic/client/SenseTecnicClientTest.java b/src/test/java/com/sensetecnic/client/SenseTecnicClientTest.java index cb2710e..3514ab1 100644 --- a/src/test/java/com/sensetecnic/client/SenseTecnicClientTest.java +++ b/src/test/java/com/sensetecnic/client/SenseTecnicClientTest.java @@ -1,90 +1,90 @@ package com.sensetecnic.client; import java.io.IOException; import java.io.StringReader; import junit.framework.TestCase; import org.junit.After; import org.junit.Before; import org.junit.Test; import com.csvreader.CsvReader; public class SenseTecnicClientTest extends TestCase { private SenseTecnicClient client; @Before protected void setUp() throws Exception { super.setUp(); client = new SenseTecnicClient(); client.setStsBaseUrl("http://demo.sensetecnic.com/SenseTecnic/api"); } @After protected void tearDown() throws Exception { super.tearDown(); } @Test public void testGetData() throws SenseTecnicException, IOException { String csvData = client.getSensorDataCsv("sensetecnic.mule1", 10, "mike", "aMUSEment2"); CsvReader reader = new CsvReader(new StringReader(csvData)); // populating the lists while (reader.readRecord()) { for (int i=0; i<reader.getColumnCount(); i++) { System.out.print(reader.get(i)+" "); } System.out.println(); } } @Test public void testGetDataBadSensor() throws SenseTecnicException, IOException { try { String csvData = client.getSensorDataCsv("random.mule333", 10, "mike", "spidey7"); - } catch (SenseTecnicException e) { + } catch (Exception e) { // success - should be a 404 return; } fail("exception not thrown"); } @Test public void testRegisterSensor() throws SenseTecnicException, IOException { // } @Test public void testDeleteSensor() throws SenseTecnicException, IOException { //TODO: test deleting a sensor } @Test public void testSendReceiveData() throws SenseTecnicException, IOException { //TODO: send it and receive it to check it goes in and out. } @Test public void testActuator() throws SenseTecnicException, IOException { //TODO: create a listening actuator, send messages to it and compare } @Test public void testBadSubscriber() throws SenseTecnicException, IOException { //TODO: check to see we receive correct error when subscription does not exist } @Test public void testUnsubscribe() throws SenseTecnicException, IOException { //TODO: check to see we receive correct error when subscription does not exist } }
true
false
null
null
diff --git a/workflow/drools/service-engine/src/test/java/org/openengsb/drools/GuvnorInterface.java b/workflow/drools/service-engine/src/test/java/org/openengsb/drools/GuvnorInterface.java index c621dc9d7..70eb85ff4 100644 --- a/workflow/drools/service-engine/src/test/java/org/openengsb/drools/GuvnorInterface.java +++ b/workflow/drools/service-engine/src/test/java/org/openengsb/drools/GuvnorInterface.java @@ -1,55 +1,55 @@ /** Copyright 2009 OpenEngSB Division, Vienna University of Technology Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE\-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.openengsb.drools; import java.util.Properties; import org.drools.RuleBase; import org.drools.WorkingMemory; import org.drools.agent.RuleAgent; import org.junit.Test; -import org.openengsb.drools.model.Event; +import org.openengsb.core.model.Event; import org.openengsb.drools.model.MessageHelperImpl; /** * A Testmethod that connects to a guvnor-rulebase. */ public class GuvnorInterface { /** * URL to the remote guvnor-base. */ public static final String URL = "http://localhost:8081/drools-guvnor/" + "org.drools.guvnor.Guvnor/package/org.openengsb/LATEST"; /** * a simple hello-world-example using drools+guvnor. */ @Test public void testInit() { Properties config = new Properties(); config.put("url", URL); RuleAgent agent = RuleAgent.newRuleAgent(config); RuleBase ruleBase = agent.getRuleBase(); WorkingMemory workingMemory = ruleBase.newStatefulSession(); workingMemory.setGlobal("helper", new MessageHelperImpl()); - Event e = new Event("hello"); + Event e = new Event("domain", "name"); workingMemory.insert(e); workingMemory.fireAllRules(); } }
false
false
null
null
diff --git a/src/org/joval/oval/adapter/windows/LockoutpolicyAdapter.java b/src/org/joval/oval/adapter/windows/LockoutpolicyAdapter.java index 3774d3b0..4f192ce7 100755 --- a/src/org/joval/oval/adapter/windows/LockoutpolicyAdapter.java +++ b/src/org/joval/oval/adapter/windows/LockoutpolicyAdapter.java @@ -1,126 +1,127 @@ // Copyright (C) 2012 jOVAL.org. All rights reserved. // This software is licensed under the AGPL 3.0 license available at http://www.joval.org/agpl_v3.txt package org.joval.oval.adapter.windows; import java.io.InputStream; import java.util.Collection; import java.util.Vector; import oval.schemas.common.MessageType; import oval.schemas.common.MessageLevelEnumeration; import oval.schemas.common.SimpleDatatypeEnumeration; import oval.schemas.definitions.core.ObjectType; import oval.schemas.definitions.windows.LockoutpolicyObject; import oval.schemas.systemcharacteristics.core.EntityItemIntType; import oval.schemas.systemcharacteristics.core.FlagEnumeration; import oval.schemas.systemcharacteristics.core.ItemType; import oval.schemas.systemcharacteristics.core.StatusEnumeration; import oval.schemas.systemcharacteristics.windows.LockoutpolicyItem; import org.joval.intf.plugin.IAdapter; import org.joval.intf.plugin.IRequestContext; import org.joval.intf.system.IBaseSession; import org.joval.intf.windows.powershell.IRunspace; import org.joval.intf.windows.system.IWindowsSession; import org.joval.oval.CollectException; import org.joval.oval.Factories; import org.joval.oval.OvalException; import org.joval.util.JOVALMsg; /** * Retrieves the unary windows:lockoutpolicy_item. * * @author David A. Solin * @version %I% %G% */ public class LockoutpolicyAdapter implements IAdapter { private IWindowsSession session; private String runspaceId; private Collection<LockoutpolicyItem> items = null; private CollectException error = null; // Implement IAdapter public Collection<Class> init(IBaseSession session) { Collection<Class> classes = new Vector<Class>(); if (session instanceof IWindowsSession) { this.session = (IWindowsSession)session; classes.add(LockoutpolicyObject.class); } return classes; } public Collection<? extends ItemType> getItems(ObjectType obj, IRequestContext rc) throws CollectException { if (error != null) { throw error; } else if (items == null) { makeItem(); } return items; } // Private private void makeItem() throws CollectException { try { // // Get a runspace if there are any in the pool, or create a new one, and load the Get-LockoutPolicy // Powershell module code. // IRunspace runspace = null; for (IRunspace rs : session.getRunspacePool().enumerate()) { runspace = rs; break; } if (runspace == null) { runspace = session.getRunspacePool().spawn(); } runspace.loadModule(getClass().getResourceAsStream("Lockoutpolicy.psm1")); // // Run the Get-LockoutPolicy module and parse the output // LockoutpolicyItem item = Factories.sc.windows.createLockoutpolicyItem(); for (String line : runspace.invoke("Get-LockoutPolicy").split("\n")) { + line = line.trim(); int ptr = line.indexOf("="); String key=null, val=null; if (ptr > 0) { key = line.substring(0,ptr); val = line.substring(ptr+1); } try { if ("force_logoff".equals(key)) { EntityItemIntType type = Factories.sc.core.createEntityItemIntType(); type.setDatatype(SimpleDatatypeEnumeration.INT.value()); type.setValue(new Integer(val).toString()); item.setForceLogoff(type); } else if ("lockout_duration".equals(key)) { EntityItemIntType type = Factories.sc.core.createEntityItemIntType(); type.setDatatype(SimpleDatatypeEnumeration.INT.value()); type.setValue(new Integer(val).toString()); item.setLockoutDuration(type); } else if ("lockout_observation_window".equals(key)) { EntityItemIntType type = Factories.sc.core.createEntityItemIntType(); type.setDatatype(SimpleDatatypeEnumeration.INT.value()); type.setValue(new Integer(val).toString()); item.setLockoutObservationWindow(type); } else if ("lockout_threshold".equals(key)) { EntityItemIntType type = Factories.sc.core.createEntityItemIntType(); type.setDatatype(SimpleDatatypeEnumeration.INT.value()); type.setValue(new Integer(val).toString()); item.setLockoutThreshold(type); } } catch (IllegalArgumentException e) { session.getLogger().warn(JOVALMsg.ERROR_WIN_LOCKOUTPOLICY_VALUE, e.getMessage(), key); } } items = new Vector<LockoutpolicyItem>(); items.add(item); } catch (Exception e) { session.getLogger().warn(JOVALMsg.getMessage(JOVALMsg.ERROR_EXCEPTION), e); error = new CollectException(e.getMessage(), FlagEnumeration.ERROR); throw error; } } } diff --git a/src/org/joval/test/Reg.java b/src/org/joval/test/Reg.java index 17856817..90169436 100755 --- a/src/org/joval/test/Reg.java +++ b/src/org/joval/test/Reg.java @@ -1,117 +1,117 @@ // Copyright (C) 2011 jOVAL.org. All rights reserved. // This software is licensed under the AGPL 3.0 license available at http://www.joval.org/agpl_v3.txt package org.joval.test; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.net.UnknownHostException; import java.util.Hashtable; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Properties; import java.util.logging.*; import org.joval.intf.system.IBaseSession; import org.joval.intf.windows.registry.IRegistry; import org.joval.intf.windows.registry.IKey; import org.joval.intf.windows.registry.IValue; import org.joval.intf.windows.registry.IBinaryValue; import org.joval.intf.windows.registry.IDwordValue; import org.joval.intf.windows.registry.IExpandStringValue; import org.joval.intf.windows.registry.ILicenseData; import org.joval.intf.windows.registry.ILicenseData.IEntry; import org.joval.intf.windows.registry.IMultiStringValue; import org.joval.intf.windows.registry.IStringValue; import org.joval.intf.windows.system.IWindowsSession; import org.joval.io.LittleEndian; public class Reg { IWindowsSession session; public Reg(IBaseSession session) { if (session instanceof IWindowsSession) { this.session = (IWindowsSession)session; } } public void testLicense() { try { IRegistry r = session.getRegistry(IWindowsSession.View._64BIT); Hashtable<String, IEntry> ht = r.getLicenseData().getEntries(); for (IEntry entry : ht.values()) { System.out.println(entry.toString()); } - } catch (NoSuchElementException e) { + } catch (Exception e) { e.printStackTrace(); } } public void test(String keyName, String valueName) { try { IRegistry r = session.getRegistry(IWindowsSession.View._64BIT); IKey key = r.fetchKey(keyName); if (valueName == null) { String[] sa = key.listSubkeys(); System.out.println("Subkeys: " + sa.length); for (int i=0; i < sa.length; i++) { System.out.println(" Subkey name: " + sa[i]); } sa = key.listValues(); System.out.println("Values: " + sa.length); for (int i=0; i < sa.length; i++) { System.out.println(" Value name: " + sa[i] + " val: " + key.getValue(sa[i]).toString()); } } else { IValue value = r.fetchValue(key, valueName); switch(value.getType()) { case IValue.REG_DWORD: System.out.println("Dword: " + ((IDwordValue)value).getData()); break; case IValue.REG_BINARY: { byte[] buff = ((IBinaryValue)value).getData(); StringBuffer sb = new StringBuffer(); System.out.println("Binary:"); for (int i=0; i < buff.length; i++) { if (i > 0 && (i % 16) == 0) { sb.append("\n"); } sb.append(" ").append(LittleEndian.toHexString(buff[i])); } System.out.println(sb.toString()); break; } case IValue.REG_SZ: System.out.println("String: " + ((IDwordValue)value).getData()); break; case IValue.REG_EXPAND_SZ: System.out.println("Expand String: " + ((IDwordValue)value).getData()); break; case IValue.REG_MULTI_SZ: { String[] sa = ((IMultiStringValue)value).getData(); System.out.println("Multi String: (len " + sa.length + ")"); for (int i=0; i < sa.length; i++) { System.out.println(" " + sa[i]); } break; } default: System.out.println("Unexpected type: " + value.getType()); break; } } key.closeAll(); } catch (NoSuchElementException e) { e.printStackTrace(); } } }
false
false
null
null
diff --git a/Application/src/mvhsbandinventory/Display.java b/Application/src/mvhsbandinventory/Display.java index 8b9e009..589205f 100644 --- a/Application/src/mvhsbandinventory/Display.java +++ b/Application/src/mvhsbandinventory/Display.java @@ -1,1167 +1,1166 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package mvhsbandinventory; import java.awt.Component; import java.awt.Dimension; import java.awt.GridBagConstraints; import javax.swing.JComboBox; import javax.swing.JOptionPane; import javax.swing.JTextField; /** * * @author nicholson */ public class Display extends javax.swing.JPanel implements java.beans.Customizer { private Object bean; private InstrumentList instruments; private HistoryTableModel histModel; private JComboBox contains; /** Creates new customizer DispTest */ public Display(InstrumentList instruments) { this.instruments = instruments; histModel = new HistoryTableModel(this); contains = new JComboBox(); contains.addItem("Contains"); initComponents(); for(String s : Instrument.attributes) { sortCombo.addItem(s); } //TODO: remove crappy test code. // instruBox.setText("Flute"); // brandBox.setText("Yamaha"); // serialBox.setText("4B212A"); // rankBox.setText("2"); // valueBox.setText("250.49"); // strapCombo.setSelectedIndex(3); // ligCombo.setSelectedIndex(3); // mpieceCombo.setSelectedIndex(1); // capCombo.setSelectedIndex(2); // bowCombo.setSelectedIndex(3); // notesTPane.setText("It's shiny, like a flute, but it's slightly flat."); } public Instrument getSelectedInstrument() { try { int i = instruTable.getSelectedRow(); - if(i < 0) return Instrument.NULL_INSTRUMENT; + return instruments.get((String) instruTable.getValueAt(i, 0), (String) instruTable.getValueAt(i, 1), (String) instruTable.getValueAt(i, 2)); } - catch (Exception e) {} - finally + catch (Exception e) { return Instrument.NULL_INSTRUMENT; } } public void saveDetails() { try { Instrument instru = getSelectedInstrument(); instru.set("Rank", rankBox.getText()); instru.set("Value", valueBox.getText()); instru.set("Status", (String) statusCombo.getSelectedItem()); instru.set("Ligature", (String) ligCombo.getSelectedItem()); instru.set("Mouthpiece", (String) mpieceCombo.getSelectedItem()); instru.set("MouthpieceCap", (String) capCombo.getSelectedItem()); instru.set("Bow", (String) bowCombo.getSelectedItem()); instru.set("NeckStrap", (String) statusCombo.getSelectedItem()); instru.set("Notes", notesTPane.getText()); instruments.update(instru); } catch(Exception ex) { JOptionPane.showMessageDialog(jopDialog, "An Error has occurred while saving the instrument:\n" + ex.getMessage(), "Save Failed", JOptionPane.ERROR_MESSAGE); } } public void displayInstrument() { Instrument instru = getSelectedInstrument(); //set the Details panel statusCombo.setSelectedItem((String) instru.get("Status")); instruBox.setText((String) instru.get("Name")); brandBox.setText((String) instru.get("Brand")); serialBox.setText((String) instru.get("Serial")); rankBox.setText((String) instru.get("Rank")); valueBox.setText((String) instru.get("Value")); strapCombo.setSelectedItem((String) instru.get("NeckStrap")); ligCombo.setSelectedItem((String) instru.get("Ligature")); mpieceCombo.setSelectedItem((String) instru.get("Mouthpiece")); capCombo.setSelectedItem((String) instru.get("MouthpieceCap")); bowCombo.setSelectedItem((String) instru.get("Bow")); notesTPane.setText((String) instru.get("Notes")); //set the History panel renterBox.setText((String) instru.get("Renter")); schoolyearBox.setText((String) instru.get("SchoolYear")); dateoutBox.setText((String) instru.get("DateOut")); feeCombo.setSelectedItem((String) instru.get("Fee")); periodCombo.setSelectedItem((String) instru.get("Period")); otherBox.setText((String) instru.get("Other")); //set the History table histModel.fireTableDataChanged(); } public void saveHistory() { try { Instrument instru = getSelectedInstrument(); instru.set("Renter", renterBox.getText()); instru.set("SchoolYear", schoolyearBox.getText()); instru.set("DateOut", dateoutBox.getText()); instru.set("Fee", (String) feeCombo.getSelectedItem()); instru.set("Period", (String) periodCombo.getSelectedItem()); instru.set("Other", otherBox.getText()); instruments.update(instru); } catch(Exception ex) { JOptionPane.showMessageDialog(jopDialog, "An Error has occurred while saving the instrument:\n" + ex.getMessage(), "Save Failed", JOptionPane.ERROR_MESSAGE); } } public InstrumentAttributeMatcher jcomps2matcher(JComboBox contains, JComboBox attribute, JTextField value) { return new InstrumentAttributeMatcher((String) attribute.getSelectedItem(), value.getText(), contains.getSelectedItem().equals("Contains")); } public void setObject(Object bean) { this.bean = bean; } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the FormEditor. */ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; advsearchAddFieldButton = new javax.swing.JButton(); advsearchButtonPanel = new javax.swing.JPanel(); advsearchSearchButton = new javax.swing.JButton(); advsearchResetButton = new javax.swing.JButton(); advsearchCancelButton = new javax.swing.JButton(); jopDialog = new javax.swing.JDialog(); advsearchDialog = new javax.swing.JDialog(); advsearchPanel = new javax.swing.JPanel(); addDialog = new javax.swing.JDialog(); addTextLabel = new javax.swing.JLabel(); addTypeLabel = new javax.swing.JLabel(); addTypeBox = new javax.swing.JTextField(); addBrandLabel = new javax.swing.JLabel(); addBrandBox = new javax.swing.JTextField(); addSerialLabel = new javax.swing.JLabel(); addSerialBox = new javax.swing.JTextField(); addButtonPanel = new javax.swing.JPanel(); addAcceptButton = new javax.swing.JButton(); addCancelButton = new javax.swing.JButton(); overlord = new javax.swing.JSplitPane(); leftsplitPanel = new javax.swing.JPanel(); leftsplitButtonPanel = new javax.swing.JPanel(); sortLabel = new javax.swing.JLabel(); sortCombo = new javax.swing.JComboBox(); sortButton = new javax.swing.JButton(); showallButton = new javax.swing.JButton(); advSearchButton = new javax.swing.JButton(); leftsplitSortByPanel = new javax.swing.JPanel(); leftsplitinstruTablePane = new javax.swing.JScrollPane(); instruTable = new javax.swing.JTable(); leftsplitaddButtonPanel = new javax.swing.JPanel(); addButton = new javax.swing.JButton(); rightsplitPanel = new javax.swing.JPanel(); infoTabs = new javax.swing.JTabbedPane(); detailPanel = new javax.swing.JPanel(); statusLabel = new javax.swing.JLabel(); statusCombo = new javax.swing.JComboBox(); instrumentLabel = new javax.swing.JLabel(); instruBox = new javax.swing.JTextField(); brandLabel = new javax.swing.JLabel(); brandBox = new javax.swing.JTextField(); serialLabel = new javax.swing.JLabel(); serialBox = new javax.swing.JTextField(); rankLabel = new javax.swing.JLabel(); rankBox = new javax.swing.JTextField(); valueLabel = new javax.swing.JLabel(); valueBox = new javax.swing.JTextField(); strapLabel = new javax.swing.JLabel(); strapCombo = new javax.swing.JComboBox(); ligatureLabel = new javax.swing.JLabel(); ligCombo = new javax.swing.JComboBox(); mpieceLabel = new javax.swing.JLabel(); mpieceCombo = new javax.swing.JComboBox(); capLabel = new javax.swing.JLabel(); capCombo = new javax.swing.JComboBox(); bowLabel = new javax.swing.JLabel(); bowCombo = new javax.swing.JComboBox(); noteLabel = new javax.swing.JLabel(); detailNotePanel = new javax.swing.JScrollPane(); notesTPane = new javax.swing.JTextPane(); historyPanel = new javax.swing.JPanel(); historySplit = new javax.swing.JSplitPane(); historyTablePanel = new javax.swing.JScrollPane(); historyTable = new javax.swing.JTable(); checkoutPanel = new javax.swing.JPanel(); renterLabel = new javax.swing.JLabel(); renterBox = new javax.swing.JTextField(); schoolyearLabel = new javax.swing.JLabel(); schoolyearBox = new javax.swing.JTextField(); dateoutLabel = new javax.swing.JLabel(); dateoutBox = new javax.swing.JTextField(); periodLabel = new javax.swing.JLabel(); periodCombo = new javax.swing.JComboBox(); feeLabel = new javax.swing.JLabel(); feeCombo = new javax.swing.JComboBox(); contractLabel = new javax.swing.JLabel(); contractCombo = new javax.swing.JComboBox(); otherLabel = new javax.swing.JLabel(); otherBox = new javax.swing.JTextField(); checkoutButtonPanel = new javax.swing.JPanel(); formButton = new javax.swing.JButton(); checkoutButton = new javax.swing.JButton(); checkinButton = new javax.swing.JButton(); lostButton = new javax.swing.JButton(); rightsplitButtonPanel = new javax.swing.JPanel(); saveButton = new javax.swing.JButton(); cancelButton = new javax.swing.JButton(); deleteButton = new javax.swing.JButton(); advsearchAddFieldButton.setText("Add Search Field"); advsearchAddFieldButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { advsearchAddFieldButtonActionPerformed(evt); } }); advsearchSearchButton.setText("SEARCH"); advsearchSearchButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { advsearchSearchButtonActionPerformed(evt); } }); advsearchButtonPanel.add(advsearchSearchButton); advsearchResetButton.setText("RESET"); advsearchResetButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { advsearchResetButtonActionPerformed(evt); } }); advsearchButtonPanel.add(advsearchResetButton); advsearchCancelButton.setText("CANCEL"); advsearchCancelButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { advsearchCancelButtonActionPerformed(evt); } }); advsearchButtonPanel.add(advsearchCancelButton); jopDialog.setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE); jopDialog.getContentPane().setLayout(new java.awt.GridBagLayout()); advsearchDialog.setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE); advsearchDialog.setTitle("Advanced Search"); advsearchDialog.setMinimumSize(new java.awt.Dimension(470, 150)); advsearchDialog.getContentPane().setLayout(new java.awt.GridBagLayout()); advsearchPanel.setLayout(new java.awt.GridBagLayout()); advsearchDialog.getContentPane().add(advsearchPanel, new java.awt.GridBagConstraints()); addDialog.setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE); addDialog.setTitle("ADD NEW INSTRUMENT"); addDialog.setMinimumSize(new java.awt.Dimension(300, 200)); addDialog.getContentPane().setLayout(new java.awt.GridBagLayout()); addTextLabel.setText("Enter Instrument Characteristics"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.ipady = 5; addDialog.getContentPane().add(addTextLabel, gridBagConstraints); addTypeLabel.setText("Type:"); addDialog.getContentPane().add(addTypeLabel, new java.awt.GridBagConstraints()); addTypeBox.setColumns(20); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; addDialog.getContentPane().add(addTypeBox, gridBagConstraints); addBrandLabel.setText("Brand:"); addDialog.getContentPane().add(addBrandLabel, new java.awt.GridBagConstraints()); addBrandBox.setColumns(20); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; addDialog.getContentPane().add(addBrandBox, gridBagConstraints); addSerialLabel.setText("Serial #:"); addDialog.getContentPane().add(addSerialLabel, new java.awt.GridBagConstraints()); addSerialBox.setColumns(20); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; addDialog.getContentPane().add(addSerialBox, gridBagConstraints); addAcceptButton.setText("CREATE"); addAcceptButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { addAcceptButtonActionPerformed(evt); } }); addButtonPanel.add(addAcceptButton); addCancelButton.setText("CANCEL"); addCancelButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { addCancelButtonActionPerformed(evt); } }); addButtonPanel.add(addCancelButton); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; addDialog.getContentPane().add(addButtonPanel, gridBagConstraints); setLayout(new java.awt.BorderLayout()); overlord.setAutoscrolls(true); overlord.setContinuousLayout(true); overlord.setName(""); // NOI18N leftsplitPanel.setMinimumSize(new java.awt.Dimension(480, 79)); leftsplitPanel.setLayout(new java.awt.GridBagLayout()); sortLabel.setText("Sort By:"); leftsplitButtonPanel.add(sortLabel); leftsplitButtonPanel.add(sortCombo); sortButton.setText("Sort"); sortButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { sortButtonActionPerformed(evt); } }); leftsplitButtonPanel.add(sortButton); showallButton.setText("Show All"); showallButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { showallButtonActionPerformed(evt); } }); leftsplitButtonPanel.add(showallButton); advSearchButton.setText("Search"); advSearchButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { advSearchButtonActionPerformed(evt); } }); leftsplitButtonPanel.add(advSearchButton); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; leftsplitPanel.add(leftsplitButtonPanel, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; leftsplitPanel.add(leftsplitSortByPanel, gridBagConstraints); instruTable.setModel(instruments); instruTable.getTableHeader().setReorderingAllowed(false); instruTable.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { instruTableMouseClicked(evt); } }); leftsplitinstruTablePane.setViewportView(instruTable); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.gridheight = java.awt.GridBagConstraints.RELATIVE; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH; gridBagConstraints.weighty = 1.0; leftsplitPanel.add(leftsplitinstruTablePane, gridBagConstraints); addButton.setText("ADD NEW INSTRUMENT"); addButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { addButtonActionPerformed(evt); } }); leftsplitaddButtonPanel.add(addButton); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.SOUTH; leftsplitPanel.add(leftsplitaddButtonPanel, gridBagConstraints); overlord.setLeftComponent(leftsplitPanel); rightsplitPanel.setMinimumSize(new java.awt.Dimension(450, 308)); rightsplitPanel.setLayout(new java.awt.BorderLayout()); detailPanel.setLayout(new java.awt.GridBagLayout()); statusLabel.setText("Status:"); statusLabel.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; detailPanel.add(statusLabel, gridBagConstraints); statusCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "In Storage", "At Shop", "On Loan", "Missing" })); statusCombo.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.ipadx = 18; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; detailPanel.add(statusCombo, gridBagConstraints); instrumentLabel.setText("Instrument:"); instrumentLabel.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; detailPanel.add(instrumentLabel, gridBagConstraints); instruBox.setBackground(new java.awt.Color(240, 240, 240)); instruBox.setColumns(10); instruBox.setEditable(false); instruBox.setAutoscrolls(false); instruBox.setMaximumSize(new java.awt.Dimension(1000, 20)); instruBox.setMinimumSize(new java.awt.Dimension(1000, 20)); instruBox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { instruBoxActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; detailPanel.add(instruBox, gridBagConstraints); brandLabel.setText("Brand:"); brandLabel.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; detailPanel.add(brandLabel, gridBagConstraints); brandBox.setBackground(new java.awt.Color(240, 240, 240)); brandBox.setColumns(10); brandBox.setEditable(false); brandBox.setAutoscrolls(false); brandBox.setMinimumSize(new java.awt.Dimension(200, 20)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; detailPanel.add(brandBox, gridBagConstraints); serialLabel.setText("Serial Number:"); serialLabel.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; detailPanel.add(serialLabel, gridBagConstraints); serialBox.setBackground(new java.awt.Color(240, 240, 240)); serialBox.setColumns(10); serialBox.setEditable(false); serialBox.setAutoscrolls(false); serialBox.setMinimumSize(new java.awt.Dimension(200, 20)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; detailPanel.add(serialBox, gridBagConstraints); rankLabel.setText("Rank:"); rankLabel.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; detailPanel.add(rankLabel, gridBagConstraints); rankBox.setColumns(2); rankBox.setHorizontalAlignment(javax.swing.JTextField.CENTER); rankBox.setText("3"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; detailPanel.add(rankBox, gridBagConstraints); valueLabel.setText("Value: $"); valueLabel.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; detailPanel.add(valueLabel, gridBagConstraints); valueBox.setColumns(10); valueBox.setHorizontalAlignment(javax.swing.JTextField.RIGHT); valueBox.setText("0"); valueBox.setAutoscrolls(false); valueBox.setMinimumSize(new java.awt.Dimension(200, 20)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; detailPanel.add(valueBox, gridBagConstraints); strapLabel.setText("Neck Strap:"); strapLabel.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; detailPanel.add(strapLabel, gridBagConstraints); strapCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { " ", "Yes", "No", "n/a" })); strapCombo.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; detailPanel.add(strapCombo, gridBagConstraints); ligatureLabel.setText("Ligature:"); ligatureLabel.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; detailPanel.add(ligatureLabel, gridBagConstraints); ligCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { " ", "Yes", "No", "n/a" })); ligCombo.setPreferredSize(null); ligCombo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ligComboActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; detailPanel.add(ligCombo, gridBagConstraints); mpieceLabel.setText("Mouthpiece:"); mpieceLabel.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; detailPanel.add(mpieceLabel, gridBagConstraints); mpieceCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { " ", "Yes", "No", "n/a" })); mpieceCombo.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; detailPanel.add(mpieceCombo, gridBagConstraints); capLabel.setText("Mouthpiece Cap:"); capLabel.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; detailPanel.add(capLabel, gridBagConstraints); capCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { " ", "Yes", "No", "n/a" })); capCombo.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; detailPanel.add(capCombo, gridBagConstraints); bowLabel.setText("Bow:"); bowLabel.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; detailPanel.add(bowLabel, gridBagConstraints); bowCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { " ", "Yes", "No", "n/a" })); bowCombo.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; detailPanel.add(bowCombo, gridBagConstraints); noteLabel.setText("Notes:"); noteLabel.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; detailPanel.add(noteLabel, gridBagConstraints); detailNotePanel.setMinimumSize(new java.awt.Dimension(25, 25)); notesTPane.setMinimumSize(new java.awt.Dimension(25, 25)); notesTPane.setPreferredSize(null); detailNotePanel.setViewportView(notesTPane); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.gridheight = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.SOUTHWEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; detailPanel.add(detailNotePanel, gridBagConstraints); infoTabs.addTab("Details", detailPanel); historyPanel.setLayout(new java.awt.BorderLayout()); historySplit.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT); historyTablePanel.setMinimumSize(new java.awt.Dimension(100, 200)); historyTable.setModel(histModel); historyTable.getTableHeader().setReorderingAllowed(false); historyTablePanel.setViewportView(historyTable); historySplit.setTopComponent(historyTablePanel); checkoutPanel.setLayout(new java.awt.GridBagLayout()); renterLabel.setText("Renter:"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; checkoutPanel.add(renterLabel, gridBagConstraints); renterBox.setColumns(25); renterBox.setAutoscrolls(false); renterBox.setMinimumSize(new java.awt.Dimension(200, 20)); renterBox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { renterBoxActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; checkoutPanel.add(renterBox, gridBagConstraints); schoolyearLabel.setText("School Year:"); schoolyearLabel.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; checkoutPanel.add(schoolyearLabel, gridBagConstraints); schoolyearBox.setColumns(25); schoolyearBox.setAutoscrolls(false); schoolyearBox.setMinimumSize(new java.awt.Dimension(200, 20)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; checkoutPanel.add(schoolyearBox, gridBagConstraints); dateoutLabel.setText("Date Out:"); dateoutLabel.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; checkoutPanel.add(dateoutLabel, gridBagConstraints); dateoutBox.setColumns(25); dateoutBox.setAutoscrolls(false); dateoutBox.setMinimumSize(new java.awt.Dimension(200, 20)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; checkoutPanel.add(dateoutBox, gridBagConstraints); periodLabel.setText("For Use In:"); periodLabel.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; checkoutPanel.add(periodLabel, gridBagConstraints); periodCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "0", "1", "2", "3", "4", "5", "6", "7" })); periodCombo.setPreferredSize(null); periodCombo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { periodComboActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; checkoutPanel.add(periodCombo, gridBagConstraints); feeLabel.setText("Fee Paid:"); feeLabel.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; checkoutPanel.add(feeLabel, gridBagConstraints); feeCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Paid", "Unpaid", "Waived" })); feeCombo.setSelectedIndex(1); feeCombo.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; checkoutPanel.add(feeCombo, gridBagConstraints); contractLabel.setText("Contract:"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; checkoutPanel.add(contractLabel, gridBagConstraints); contractCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Uncreated", "Created", "Signed" })); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; checkoutPanel.add(contractCombo, gridBagConstraints); otherLabel.setText("Other:"); otherLabel.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; checkoutPanel.add(otherLabel, gridBagConstraints); otherBox.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.ipadx = 300; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; checkoutPanel.add(otherBox, gridBagConstraints); checkoutButtonPanel.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT)); formButton.setText("Generate Form"); formButton.setPreferredSize(null); formButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { formButtonActionPerformed(evt); } }); checkoutButtonPanel.add(formButton); checkoutButton.setText("Check Out"); checkoutButton.setPreferredSize(null); checkoutButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { checkoutButtonActionPerformed(evt); } }); checkoutButtonPanel.add(checkoutButton); checkinButton.setText("Check In"); checkinButton.setPreferredSize(null); checkinButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { checkinButtonActionPerformed(evt); } }); checkoutButtonPanel.add(checkinButton); lostButton.setText("Lost"); lostButton.setPreferredSize(null); lostButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { lostButtonActionPerformed(evt); } }); checkoutButtonPanel.add(lostButton); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.ipadx = 300; gridBagConstraints.ipady = 10; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; checkoutPanel.add(checkoutButtonPanel, gridBagConstraints); historySplit.setRightComponent(checkoutPanel); historyPanel.add(historySplit, java.awt.BorderLayout.CENTER); infoTabs.addTab("History", historyPanel); rightsplitPanel.add(infoTabs, java.awt.BorderLayout.CENTER); saveButton.setText("SAVE CHANGES"); saveButton.setPreferredSize(null); saveButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { saveButtonActionPerformed(evt); } }); rightsplitButtonPanel.add(saveButton); cancelButton.setText("CANCEL CHANGES"); cancelButton.setPreferredSize(null); cancelButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cancelButtonActionPerformed(evt); } }); rightsplitButtonPanel.add(cancelButton); deleteButton.setText("DELETE INSTRUMENT"); deleteButton.setPreferredSize(null); deleteButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { deleteButtonActionPerformed(evt); } }); rightsplitButtonPanel.add(deleteButton); rightsplitPanel.add(rightsplitButtonPanel, java.awt.BorderLayout.SOUTH); overlord.setRightComponent(rightsplitPanel); add(overlord, java.awt.BorderLayout.CENTER); }// </editor-fold>//GEN-END:initComponents private void instruBoxActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_instruBoxActionPerformed {//GEN-HEADEREND:event_instruBoxActionPerformed // TODO add your handling code here: }//GEN-LAST:event_instruBoxActionPerformed private void ligComboActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_ligComboActionPerformed {//GEN-HEADEREND:event_ligComboActionPerformed // TODO add your handling code here: }//GEN-LAST:event_ligComboActionPerformed private void renterBoxActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_renterBoxActionPerformed {//GEN-HEADEREND:event_renterBoxActionPerformed // TODO add your handling code here: }//GEN-LAST:event_renterBoxActionPerformed private void periodComboActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_periodComboActionPerformed {//GEN-HEADEREND:event_periodComboActionPerformed // TODO add your handling code here: }//GEN-LAST:event_periodComboActionPerformed private void deleteButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_deleteButtonActionPerformed {//GEN-HEADEREND:event_deleteButtonActionPerformed Main.window.setEnabled(false); int n = JOptionPane.showConfirmDialog(jopDialog, "Are you sure you want to delete this instrument?", "Confirm Delete", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE); switch(n) {//TODO: Hook the delete confirmation dialog to something. case JOptionPane.YES_OPTION: instruments.delete(getSelectedInstrument()); } Main.window.setEnabled(true); Main.window.requestFocus(); }//GEN-LAST:event_deleteButtonActionPerformed private void addButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_addButtonActionPerformed {//GEN-HEADEREND:event_addButtonActionPerformed Main.window.setEnabled(false); addTypeBox.setText(""); addBrandBox.setText(""); addSerialBox.setText(""); addDialog.setVisible(true); }//GEN-LAST:event_addButtonActionPerformed private void advSearchButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_advSearchButtonActionPerformed {//GEN-HEADEREND:event_advSearchButtonActionPerformed Main.window.setEnabled(false); advsearchResetButtonActionPerformed(evt); advsearchDialog.setVisible(true); }//GEN-LAST:event_advSearchButtonActionPerformed private void advsearchResetButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_advsearchResetButtonActionPerformed {//GEN-HEADEREND:event_advsearchResetButtonActionPerformed advsearchPanel.removeAll(); advsearchAddFieldButtonActionPerformed(evt); advsearchDialog.setMinimumSize(new Dimension(470, 150)); advsearchDialog.setSize(0, 0); }//GEN-LAST:event_advsearchResetButtonActionPerformed private void advsearchCancelButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_advsearchCancelButtonActionPerformed {//GEN-HEADEREND:event_advsearchCancelButtonActionPerformed advsearchDialog.setVisible(false); Main.window.setEnabled(true); Main.window.requestFocus(); }//GEN-LAST:event_advsearchCancelButtonActionPerformed private void advsearchAddFieldButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_advsearchAddFieldButtonActionPerformed {//GEN-HEADEREND:event_advsearchAddFieldButtonActionPerformed advsearchPanel.remove(advsearchAddFieldButton); advsearchPanel.remove(advsearchButtonPanel); JComboBox cb = new JComboBox(); GridBagConstraints gbc = new GridBagConstraints(); gbc.gridwidth = GridBagConstraints.REMAINDER; cb.addItem("Contains"); cb.addItem("Without"); advsearchPanel.add(cb); cb = new JComboBox(); for(String s : Instrument.attributes) { cb.addItem(s); } advsearchPanel.add(cb); JTextField txt = new JTextField(); txt.setColumns(20); advsearchPanel.add(txt, gbc); advsearchPanel.add(advsearchAddFieldButton, gbc); advsearchPanel.add(advsearchButtonPanel, gbc); Dimension size = advsearchDialog.getSize(); Dimension minSize = advsearchDialog.getMinimumSize(); advsearchDialog.setSize(size.width, size.height + 25); minSize.setSize(minSize.width, minSize.height + 25); advsearchDialog.setMinimumSize(minSize); }//GEN-LAST:event_advsearchAddFieldButtonActionPerformed private void addCancelButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_addCancelButtonActionPerformed {//GEN-HEADEREND:event_addCancelButtonActionPerformed addDialog.setVisible(false); Main.window.setEnabled(true); Main.window.requestFocus(); }//GEN-LAST:event_addCancelButtonActionPerformed private void addAcceptButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_addAcceptButtonActionPerformed {//GEN-HEADEREND:event_addAcceptButtonActionPerformed // Check to make sure that all of the fields were properly filled in if(addTypeBox.getText().equals("") || addBrandBox.getText().equals("") || addSerialBox.getText().equals("")) { JOptionPane.showMessageDialog(jopDialog, "All of the three fields on the \"Add Instrument\" form \n" + "are required to be filled in. One of them was left blank.", "Data Entry Error", JOptionPane.ERROR_MESSAGE); } else { // TODO: delete test print System.out.println("Name: " + addTypeBox.getText() + " Brand: " + addBrandBox.getText() + " Serial: " + addSerialBox.getText()); // Creating a new instrument Instrument instru = new Instrument(); try { // Adding core fields from the "Add Instrument" window instru.set("Name", addTypeBox.getText()); instru.set("Brand", addBrandBox.getText()); instru.set("Serial", addSerialBox.getText()); // Adding default values for new instruments // TODO: Move these into some sort of configuration system instru.set("Rank", "3"); instru.set("Value", "0"); instru.set("Period", "0"); instru.set("Fee", "Unpaid"); instru.set("Contract", "Uncreated"); } catch(Exception ex) { JOptionPane.showMessageDialog(jopDialog, "An internal error has occurred while creating the " + "instrument:\n" + ex.getMessage(), "Instrument Creation Failed", JOptionPane.ERROR_MESSAGE); } // Add the instrument to the instrument list instruments.add(instru); addDialog.setVisible(false); Main.window.setEnabled(true); Main.window.requestFocus(); } }//GEN-LAST:event_addAcceptButtonActionPerformed private void sortButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_sortButtonActionPerformed {//GEN-HEADEREND:event_sortButtonActionPerformed String s = (String) sortCombo.getSelectedItem(); instruments.sort(s, true); }//GEN-LAST:event_sortButtonActionPerformed private void saveButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_saveButtonActionPerformed {//GEN-HEADEREND:event_saveButtonActionPerformed saveDetails(); saveHistory(); displayInstrument(); }//GEN-LAST:event_saveButtonActionPerformed private void instruTableMouseClicked(java.awt.event.MouseEvent evt)//GEN-FIRST:event_instruTableMouseClicked {//GEN-HEADEREND:event_instruTableMouseClicked displayInstrument(); }//GEN-LAST:event_instruTableMouseClicked private void lostButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_lostButtonActionPerformed {//GEN-HEADEREND:event_lostButtonActionPerformed statusCombo.setSelectedItem("Missing"); saveHistory(); }//GEN-LAST:event_lostButtonActionPerformed private void checkinButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_checkinButtonActionPerformed {//GEN-HEADEREND:event_checkinButtonActionPerformed statusCombo.setSelectedItem("In Storage"); saveHistory(); }//GEN-LAST:event_checkinButtonActionPerformed private void checkoutButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_checkoutButtonActionPerformed {//GEN-HEADEREND:event_checkoutButtonActionPerformed statusCombo.setSelectedItem("On Loan"); saveHistory(); }//GEN-LAST:event_checkoutButtonActionPerformed private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_cancelButtonActionPerformed {//GEN-HEADEREND:event_cancelButtonActionPerformed displayInstrument(); }//GEN-LAST:event_cancelButtonActionPerformed private void formButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_formButtonActionPerformed {//GEN-HEADEREND:event_formButtonActionPerformed //conGen.generateContract(getSelectedInstrument()); }//GEN-LAST:event_formButtonActionPerformed private void advsearchSearchButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_advsearchSearchButtonActionPerformed {//GEN-HEADEREND:event_advsearchSearchButtonActionPerformed Component[] comps = advsearchPanel.getComponents(); int end = comps.length-2; int stop = end/3; InstrumentAttributeMatcher[] matchers = new InstrumentAttributeMatcher[stop/3]; for(int i = 0; i<stop; i++) { matchers[i] = jcomps2matcher((JComboBox) comps[i*3], (JComboBox) comps[i*3+1], (JTextField) comps[i*3+2]); } instruments.selectList(matchers); }//GEN-LAST:event_advsearchSearchButtonActionPerformed private void showallButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_showallButtonActionPerformed {//GEN-HEADEREND:event_showallButtonActionPerformed instruments.selectList(instruments.SHOWALL); }//GEN-LAST:event_showallButtonActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton addAcceptButton; private javax.swing.JTextField addBrandBox; private javax.swing.JLabel addBrandLabel; private javax.swing.JButton addButton; private javax.swing.JPanel addButtonPanel; private javax.swing.JButton addCancelButton; private javax.swing.JDialog addDialog; private javax.swing.JTextField addSerialBox; private javax.swing.JLabel addSerialLabel; private javax.swing.JLabel addTextLabel; private javax.swing.JTextField addTypeBox; private javax.swing.JLabel addTypeLabel; private javax.swing.JButton advSearchButton; private javax.swing.JButton advsearchAddFieldButton; private javax.swing.JPanel advsearchButtonPanel; private javax.swing.JButton advsearchCancelButton; private javax.swing.JDialog advsearchDialog; private javax.swing.JPanel advsearchPanel; private javax.swing.JButton advsearchResetButton; private javax.swing.JButton advsearchSearchButton; private javax.swing.JComboBox bowCombo; private javax.swing.JLabel bowLabel; private javax.swing.JTextField brandBox; private javax.swing.JLabel brandLabel; private javax.swing.JButton cancelButton; private javax.swing.JComboBox capCombo; private javax.swing.JLabel capLabel; private javax.swing.JButton checkinButton; private javax.swing.JButton checkoutButton; private javax.swing.JPanel checkoutButtonPanel; private javax.swing.JPanel checkoutPanel; private javax.swing.JComboBox contractCombo; private javax.swing.JLabel contractLabel; private javax.swing.JTextField dateoutBox; private javax.swing.JLabel dateoutLabel; private javax.swing.JButton deleteButton; private javax.swing.JScrollPane detailNotePanel; private javax.swing.JPanel detailPanel; private javax.swing.JComboBox feeCombo; private javax.swing.JLabel feeLabel; private javax.swing.JButton formButton; private javax.swing.JPanel historyPanel; private javax.swing.JSplitPane historySplit; private javax.swing.JTable historyTable; private javax.swing.JScrollPane historyTablePanel; private javax.swing.JTabbedPane infoTabs; private javax.swing.JTextField instruBox; private javax.swing.JTable instruTable; private javax.swing.JLabel instrumentLabel; private javax.swing.JDialog jopDialog; private javax.swing.JPanel leftsplitButtonPanel; private javax.swing.JPanel leftsplitPanel; private javax.swing.JPanel leftsplitSortByPanel; private javax.swing.JPanel leftsplitaddButtonPanel; private javax.swing.JScrollPane leftsplitinstruTablePane; private javax.swing.JComboBox ligCombo; private javax.swing.JLabel ligatureLabel; private javax.swing.JButton lostButton; private javax.swing.JComboBox mpieceCombo; private javax.swing.JLabel mpieceLabel; private javax.swing.JLabel noteLabel; private javax.swing.JTextPane notesTPane; private javax.swing.JTextField otherBox; private javax.swing.JLabel otherLabel; private javax.swing.JSplitPane overlord; private javax.swing.JComboBox periodCombo; private javax.swing.JLabel periodLabel; private javax.swing.JTextField rankBox; private javax.swing.JLabel rankLabel; private javax.swing.JTextField renterBox; private javax.swing.JLabel renterLabel; private javax.swing.JPanel rightsplitButtonPanel; private javax.swing.JPanel rightsplitPanel; private javax.swing.JButton saveButton; private javax.swing.JTextField schoolyearBox; private javax.swing.JLabel schoolyearLabel; private javax.swing.JTextField serialBox; private javax.swing.JLabel serialLabel; private javax.swing.JButton showallButton; private javax.swing.JButton sortButton; private javax.swing.JComboBox sortCombo; private javax.swing.JLabel sortLabel; private javax.swing.JComboBox statusCombo; private javax.swing.JLabel statusLabel; private javax.swing.JComboBox strapCombo; private javax.swing.JLabel strapLabel; private javax.swing.JTextField valueBox; private javax.swing.JLabel valueLabel; // End of variables declaration//GEN-END:variables }
false
false
null
null
diff --git a/Source/HisClient/src/gov/niarl/his/StandaloneHIS.java b/Source/HisClient/src/gov/niarl/his/StandaloneHIS.java index 88eb4b2..83d1d0c 100644 --- a/Source/HisClient/src/gov/niarl/his/StandaloneHIS.java +++ b/Source/HisClient/src/gov/niarl/his/StandaloneHIS.java @@ -1,2305 +1,2308 @@ /************************************************************************** * 2012, U.S. Government, National Security Agency, National Information Assurance Research Laboratory * * This is a work of the UNITED STATES GOVERNMENT and is not subject to copyright * protection in the United States. Foreign copyrights may apply. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * ...Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * ...Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * ...Neither the name of the NATIONAL SECURITY AGENCY/NATIONAL INFORMATION ASSURANCE RESEARCH LABORATORY * nor the names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. **************************************************************************/ package gov.niarl.his; import gov.niarl.sal.webservices.hisWebService.client.*; import gov.niarl.sal.webservices.hisWebServices.clientWsImport.Action; import gov.niarl.sal.webservices.hisWebServices.clientWsImport.ActionDelay; import gov.niarl.sal.webservices.hisWebServices.clientWsImport.HisPollingWebService; import gov.niarl.sal.webservices.hisWebServices.clientWsImport.HisWebService; import gov.niarl.sal.webservices.hisWebServices.clientWsImport.NonceSelect; import gov.niarl.sal.webservices.hisWebServices.clientWsImport.Quote; import java.util.Properties; import org.apache.log4j.Logger; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.math.BigInteger; import java.net.InetAddress; import java.net.UnknownHostException; import java.net.NetworkInterface; import java.net.SocketException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import java.util.List; import java.util.StringTokenizer; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBElement; import javax.xml.bind.Marshaller; import org.apache.log4j.PropertyConfigurator; import org.trustedcomputinggroup.xml.schema.core_integrity_v1_0_1_.ComponentIDType; import org.trustedcomputinggroup.xml.schema.core_integrity_v1_0_1_.DigestMethodType; import org.trustedcomputinggroup.xml.schema.core_integrity_v1_0_1_.ObjectFactory; import org.trustedcomputinggroup.xml.schema.core_integrity_v1_0_1_.ValueType; import org.trustedcomputinggroup.xml.schema.core_integrity_v1_0_1_.VendorIdType; import org.trustedcomputinggroup.xml.schema.integrity_report_v1_0_.PcrCompositeType; import org.trustedcomputinggroup.xml.schema.integrity_report_v1_0_.PcrSelectionType; import org.trustedcomputinggroup.xml.schema.integrity_report_v1_0_.QuoteDataType; import org.trustedcomputinggroup.xml.schema.integrity_report_v1_0_.QuoteInfoType; import org.trustedcomputinggroup.xml.schema.integrity_report_v1_0_.QuoteSignatureType; import org.trustedcomputinggroup.xml.schema.integrity_report_v1_0_.QuoteType; import org.trustedcomputinggroup.xml.schema.integrity_report_v1_0_.ReportType; import org.trustedcomputinggroup.xml.schema.integrity_report_v1_0_.SnapshotType; import org.trustedcomputinggroup.xml.schema.integrity_report_v1_0_.PcrCompositeType.PcrValue; import org.trustedcomputinggroup.xml.schema.integrity_report_v1_0_.TpmDigestValueType; import org.trustedcomputinggroup.xml.schema.simple_object_v1_0_.SimpleObjectType; import org.trustedcomputinggroup.xml.schema.simple_object_v1_0_.ValuesType; import org.trustedcomputinggroup.xml.schema.core_integrity_v1_0_1_.DigestValueType; import org.w3._2000._09.xmldsig_.KeyInfoType; import org.w3._2000._09.xmldsig_.KeyValueType; import org.w3._2000._09.xmldsig_.SignatureMethodType; import org.w3._2000._09.xmldsig_.SignatureValueType; /** StandaloneHIS is a self contained client application for the Host Integrity at Startup (HIS) system. * This application can be run as any other and will query the local Trusted Platform Module (TPM) for * host integrity measurements in the form of a signed Quote.<br> * <br> * The HIS Client makes use of binary TPM Interface Module to access the TPM via a system call, * a TCG defined XML integrity report format and web service stype communications with a back end HIS server.<br> * <br> * The HIS Client can be run in a once through mode that runs the reporting process and then terminates or * an On Demand mode that sets the process to poll for instructions via web services. * The On Demand mode has expanded the range of functions that the HIS Client can carry out * including capabilities for system reboot (in order to generate fresh measurements) and process * specially configured commands in order to handle scenarios with virtualized guest environments.<br> * <br> * The HIS Client application uses log4j logging as well as sending special Error Reports to the back end server. * In addition to this certain errors also print to Std Out or Std Err to better enable field debugging. * <br> * The HIS Client also makes use of a HIS.properties file located in the root of the application path supplied as an argument. * This property file contains all of the Client's configuration data. While defaults can be substituted lack of a * proper configuration will cause the HIS Client to not function. * <br> * Other dependencies include both a binary TPM interface module and splash screen image, the location of which are pointed to in the HIS.properties file. * <br> * * * @author mcbrotz */ public class StandaloneHIS { //Version for the UUID public static String UUID_VERSION = "1"; //Prefix to differentiate the snapshot ID space public static final String SNAPSHOT_PREFIX = "S"; //Prefix to differentiate the snapshot ID space public static final String QUOTE_PREFIX = "Q"; //TCG Required Quote Version Major Value - placeholder public static final short QUOTE_VERSION_MAJOR = 0x01; //TCG Required Quote Version Minor Value - placeholder public static final short QUOTE_VERSION_MINOR = 0x01; //TCG Required Quote Version Rev Major Value - placeholder public static final short QUOTE_VERSION_REV_MAJOR = 0x00; //TCG Required Quote Version Rev Minor Value - placeholder public static final short QUOTE_VERSION_REV_MINOR = 0x00; //Fimename for auto-reg cert file //public static final String AIC_FILNAME = "AIK.cer"; //Snapshot Revision Number public static final String SNAPSHOT_REV_LEVEL = "0"; //size of the PCR bitmask in bytes //TODO make this a property? //public static final int PCR_BITMASK_SIZE = 3; //variable for the PCR bitmask private byte[] pcrBitmask; //default value for the pcr bitmask public static final byte[] DEFAULT_PCR_BITMASK = {(byte)0xff, (byte)0xff, (byte)0xff}; //Default blocking timeout value in whole seconds. public static final String DEFAULT_TIMEOUT_VALUE = "10"; //command flags for the native interface public static final String MODE_FLAG = "-mode"; public static final String NONCE_FLAG = "-nonce"; public static final String BITMASK_FLAG = "-mask"; public static final String KEY_AUTH_FLAG = "-key_auth"; public static final String KEY_INDEX_FLAG = "-key_index"; //Properties file object for the application Properties hisProperties = new Properties(); //The timeout in approximate ms for any blocking function to wait for a process to return int blockingTimeout=10000; int splashDuration = 3000; //The nonce for the TPM quote String nonce=""; //This is the raw bitmask as sent by the web service String rawBitmask=""; //global String for the applications working directory String hisPath="./"; //The type of appraiser registration to use, manual or auto //String regType = "manual"; //the flag for the running OS int hostOS=0; //host name of the local computer String computerName= "unknownHost"; //name for the log4j properties file public static final String LOG4J_PROPERTIES_FILE = "log4j.properties"; public static Logger s_logger; //Web Service variables HisWebService hisAuthenticationWebService; String webServiceUrl = ""; //Property labels and defaults public static final String TPM_QUOTE_EXECUTABLE_NAME_LABEL = "TpmQuoteExecutableName"; public static final String TPM_QUOTE_EXECUTABLE_PATH_LABEL = "TpmQuoteExecutablePath"; public static final String VENDOR_GUID_LABEL = "VendorGUID"; public static final String VENDOR_NAME_LABEL = "Vendor"; public static final String MODEL_NAME_LABEL = "ModelName"; public static final String MODEL_NUMBER_LABEL = "ModelNumber"; public static final String VERSION_MAJOR_LABEL = "ModelMajorRev"; public static final String VERSION_MINOR_LABEL = "ModelMinorRev"; public static final String WEB_SERVICE_URL_LABEL = "WebServiceUrl"; public static final String MODEL_SN_LABEL = "ModelSerialNumber"; public static final String MODEL_PATCH_LEVEL_LABEL = "PatchLevel"; public static final String MODEL_MFG_DATE_LABEL = "MfgDate"; public static final String BLOCKING_TIMEOUT_LABEL = "BlockingTimeout"; public static final String KEY_AUTH_LABEL = "KeyAuth"; public static final String KEY_INDEX_LABEL = "KeyIndex"; public static final String TRUST_STORE_LABEL = "TrustStore"; public static final String SPLASH_IMAGE_LABEL = "SplashImage"; public static final String POLLING_PERIOD_LABEL = "PollingPeriod"; public static final String UUID_VERSION_LABEL = "UUIDversion"; //public static final String REGISTRATION_TYPE_LABEL = "RegistrationType"; public static final String OS_TYPE_LABEL = "OSType"; public static final String VERIFY_COMMAND_LABEL = "VerifyClientAction"; public static final String CLEAN_COMMAND_LABEL = "CleanClientAction"; //OS Type ID static final int WINDOWS_OS = 1; static final int LINUX_OS = 2; public static final String WINDOWS_OS_TAG ="W"; public static final String LINUX_OS_TAG ="X"; //Various Constants public static final String DEFAULT_HIS_PATH = "/OAT/"; public static final String PROPERTIES_NAME = "OAT.properties"; public static final String PROPERTIES_EXTENSION = ".properties"; public static final String DEFAULT_KEY_AUTH = "0123456789012345678901234567890123456789"; public static final String DEFAULT_KEY_INDEX = "1"; public static final String DEFAULT_POLLING_VALUE = "30"; public static final String TPM_QUOTE_MODE = "5"; public static final String TPM_QUOTE1_MODE = "56"; public static final String TPM_QUOTE2_MODE = "24"; public static final String ERROR_MESSAGE_ID = "0001"; public static final String UNLOCK_SCREEN_MESSAGE_ID = "0002"; public static final String WINDOWS_REBOOT_CMD = "shutdown -r"; public static final String LINUX_REBOOT_CMD = "shutdown -r 15"; public static boolean clientStartUpDone = false; public static boolean lastReportSendSuccess = true; String reportType = "start"; //global variable that indicates the quote type to be used int quoteType=2; //TPM Quote Struct Constants public static final String EXPECTED_QUOTE_VERSION_TAG = "01010000"; public static final String QUOTE_FIXED = "QUOT";//TCG Defined Quote Info Fxied Value //public static final int SEGMENT_LENGH_FIELD_SIZE = 4; public static final int PCR_MAX_NUM = 24; public static final int PCR_FIELD_SIZE = 2; public static final int PCR_LENGTH_SIZE = 2; public static final int PCR_SIZE = 20; public static final int QUOTE_SIZE = 48; public static final int QUOTE_VERSION_SIZE = 4; public static final int QUOTE_FIXED_SIZE = 4; public static final int PCR_HASH_SIZE = 20; public static final int NONCE_SIZE = 20; public static final int SIGNATURE_SIZE = 256; //TPM Quote 2 Struct Constants public static final int QUOTE2_SIZE_BASE = 49;//not including variable length bitmask public static final byte[] EXPECTED_QUOTE2_VERSION_TAG = {(byte)0x00, (byte)0x36}; public static final String QUOTE2_FIXED = "QUT2"; //TCG Defined Quote 2 Info Fxied Value public static final String QUOTE2_FILLER_BYTE = "01"; public static final int QUOTE2_VERSION_SIZE = 2; public static final int QUOTE2_BITMASK_LENGTH_SIZE = 2; String tpmOutput = ""; private static long lastByteBIOS; private static long lastByteIMA; private static byte[][] lastPcrHash = new byte[PCR_MAX_NUM][20]; private static int[] lastEventCount = new int[PCR_MAX_NUM]; /** * Removes white space from a string. * @param string String from which white space will be removed. * @return String without white space. */ public static String removeWhiteSpace(String string) { string = string.replace("\r", ""); string = string.replace("\n", ""); string = string.replace("\t", ""); string = string.replace(" ", ""); return string; } /** * Turns a hexadecimal string representation to a byte array. * @param string Hexadecimal formatted string. * @return Byte array generated from a hexadecimal string representation */ public static byte[] unHexString(String string) { string = removeWhiteSpace(string); string = string.toUpperCase().replace("0X", ""); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); for (int i = 0; i < string.length(); i += 2) { byteArrayOutputStream.write(Integer.parseInt(string.substring(i, i + 2), 16)); } return byteArrayOutputStream.toByteArray(); } /** * Turn a byte array into a hexadecimal string representation. * @param byteArray Byte array to be converted into a hexadecimal * string representation. * @return A string containing a hexadecimal representation of a byte * array without space or 0x's. */ public static String hexString(byte[] byteArray) { String returnstring = new String(); for (int i = 0; i < byteArray.length; i++) { Integer integer = byteArray[i] < 0 ? byteArray[i] + 256 : byteArray[i]; String integerString = Integer.toString(integer, 16); returnstring += integerString.length() == 1 ? "0" + integerString : integerString; } return returnstring.toUpperCase(); } /** Main medhod for running the application.<br> *<br> * @param args the command line arguments<br> *<br> * The first parameter is the working directory. *<br> * The second is the flasg to handle the splash screen:<br> * -s if the splash screen is to be displayed<br> * -b if the splash screen is to be displayed without running the TPM report<br> * -d if the HIS client is to be run in dynamic mode (disables splash screen)<br> *<br> * The parameters can be used individually, but only one of each<br> */ public static void main(String[] args) { String path=DEFAULT_HIS_PATH; StandaloneHIS his=null; boolean dynamicHIS = false; boolean showSplash = false; boolean brandHIS = false; //bounds check for presence of the first argument if(args.length>=1) { //check for the presence of a second argument, path first if(args.length>=2 && (args[1].equals("-s")||args[1].equals("-b")||args[1].equals("-d"))) { if(args[1].equals("-s")) { showSplash = true; path = args[0]; } if(args[1].equals("-b")) { brandHIS=true; path = args[0]; } if(args[1].equals("-d")) { dynamicHIS = true; path = args[0]; } } //check for the presence of a second argument, path second just in case the user screws up else if(args.length>=2 && (args[0].equals("-s")||args[0].equals("-b")||args[0].equals("-d"))) { if(args[0].equals("-s")) { showSplash = true; path = args[1]; } if(args[0].equals("-b")) { brandHIS=true; path = args[1]; } if(args[0].equals("-d")) { dynamicHIS = true; path = args[1]; } } else if(args[0].equals("-d")) { dynamicHIS=true; } else if(args[0].equals("-b")) { brandHIS=true; } else if(args[0].equals("-s")) { showSplash = true; } else { path = args[0]; } } System.out.println("Flags recieved: Brand = "+brandHIS+", Show Splash = "+showSplash+", On Demand = "+dynamicHIS+", Path = "+path); try { his = new StandaloneHIS(path, showSplash, brandHIS); } catch(Exception e) { e.printStackTrace(); System.exit(1); } //run the integrity check once try { his.checkIntegrity(); clientStartUpDone = true; } catch(Exception e) { e.printStackTrace(); //System.exit(1); } //if we are setting up dynamic polling do it //If entered this function will not return. if(dynamicHIS) { his.dynamicPoll(); } } /** Constructor. Loads HIS property file, various properties and other global variables * * @param path The path to where the HIS files have been installed * @param splash Is the splash scteen to be displayed * @param brand Is HIS in branding mode * @throws java.lang.Exception Thown is HIS has a problem */ public StandaloneHIS(String path, boolean splash, boolean brand) throws Exception { resetScalabilityCounters(); if(path.length() == 0) { path = DEFAULT_HIS_PATH; } hisPath = path; //set up the logging. PropertyConfigurator.configure(hisPath+LOG4J_PROPERTIES_FILE); s_logger = Logger.getLogger( "HIS" ); //Set up the HIS properties file. FileInputStream HISPropertyFile = null; try { HISPropertyFile = new FileInputStream(hisPath+PROPERTIES_NAME); } catch (java.io.FileNotFoundException fnfe) { s_logger.warn( "HIS Property file not found!" ); //Try to create the Property File if it is not present try { File fileName= new File(hisPath+PROPERTIES_NAME); // create the directory fileName.createNewFile(); HISPropertyFile = new FileInputStream(fileName); s_logger.debug( "Using HIS Property File: "+ HISPropertyFile.toString()); } catch (Exception ioe) { s_logger.error("HIS Property File empty.\n Unable to create new HIS property file!\n"); } } //If we load in a file put it in to a proprties object if(HISPropertyFile!=null) { try { hisProperties.load(HISPropertyFile); } catch (java.io.FileNotFoundException fnfe) { s_logger.error( "HIS Property file not found on Property load!" ); } catch (java.io.IOException ioe) { s_logger.error( "Error loading HIS Property file!" ); } finally{ HISPropertyFile.close(); } } else { s_logger.error( "Error loading HIS Property file!" ); } //Set various properties blockingTimeout = 1000 * new Integer(hisProperties.getProperty(BLOCKING_TIMEOUT_LABEL, DEFAULT_TIMEOUT_VALUE)).intValue(); //Set up the Web services //Initialize the SSL Trust store String trustStoreUrl = hisPath+hisProperties.getProperty(TRUST_STORE_LABEL,"./TrustStore.jks"); System.setProperty("javax.net.ssl.trustStore", trustStoreUrl); //Pull the URLs from properties webServiceUrl = hisProperties.getProperty(WEB_SERVICE_URL_LABEL,""); //Set the UUID version number UUID_VERSION = hisProperties.getProperty(UUID_VERSION_LABEL, "1"); //get the registration type //regType = hisProperties.getProperty(REGISTRATION_TYPE_LABEL, "manual"); //Set the web service URL webServiceUrl = hisProperties.getProperty(WEB_SERVICE_URL_LABEL,""); //check for valid URLs. if(webServiceUrl.length() == 0) { throw new Exception("Web Service URL not present. Unable to initialize HIS client."); } //get the OS type String hostOSstr = hisProperties.getProperty(OS_TYPE_LABEL, ""); if(hostOSstr.equals(WINDOWS_OS_TAG)) { hostOS = WINDOWS_OS; } else if(hostOSstr.equals(LINUX_OS_TAG)) { hostOS = LINUX_OS ; } else{hostOS=0;} //Obtain the computer name try { //computerName = InetAddress.getLocalHost().getCanonicalHostName(); computerName = InetAddress.getLocalHost().getHostName(); s_logger.debug("Computer name found as: "+computerName); } catch(Exception ex) { //computerName="DefaultHost"; //s_logger.warn("Computer name set to default"); //UnknownHostException will be thrown sometime on RHEL, //so get computer name from the exception msg StringTokenizer st = new StringTokenizer(ex.getMessage()); while (st.hasMoreTokens()) computerName = st.nextToken(); } //pull the splash image from properties String splashFile = hisProperties.getProperty(SPLASH_IMAGE_LABEL); System.out.println("Splash path = "+hisPath + splashFile); //only display a splash screen if a splash image file has been entered and the flag is set if(splashFile!=null && (splash == true || brand == true)) { new HisSplash(splashDuration, hisPath + splashFile).showSplash(); //if we are in Branding mode show the splash screen and exit if(brand == true) { s_logger.info( "HIS branding display complete" ); Thread.sleep(splashDuration+100); System.exit(0); } } } /** This function sets up the HIS application into a dynamic polling mode where the app will poll a web service to determine if it needs to send back a report. * * The poll interval is set within the property file and defaults to 30 seconds. * * */ public void dynamicPoll() { HisPollingWebService hisPollingWebService = null; ActionDelay actionDelay = null; Action action = null; long pollInterval; int defaultPollInterval; //load the default polling interval value in whole seconds defaultPollInterval = new Integer(hisProperties.getProperty(POLLING_PERIOD_LABEL, DEFAULT_POLLING_VALUE)).intValue(); //make a call to the web service to get the type of action and action delay hisPollingWebService = HisWebServicesClientInvoker.getHisPollingWebService(webServiceUrl);//"http://toc.dod.mil:8080/HisWebServices"); //enter a polling loop while(true) { pollInterval = 0; action = Action.DO_NOTHING; try { if(hisPollingWebService==null) { System.out.println("Web service object null"); } else{ actionDelay = hisPollingWebService.getNextAction(computerName); action = actionDelay.getAction(); //save the delay until the next poll pollInterval = actionDelay.getDelayMilliseconds(); } } catch (Exception e) { + resetScalabilityCounters(); + lastReportSendSuccess = false; + //we want to trigger the default polling interval if there is a web service exception pollInterval=0; //Handle the exception by reporting the error, but do not kill the loop s_logger.error( "On Demand web service Error: "+e.getMessage() ); System.out.println( "On Demand web service Error: "+e.getMessage() ); //e.printStackTrace(); } switch (action) { case DO_NOTHING: System.out.println("Action:DO_NOTHING"); s_logger.debug("Action:DO_NOTHING"); break; case SEND_REPORT: System.out.println("Action:SEND_REPORT"); s_logger.debug("Action:SEND_REPORT"); try { checkIntegrity(); lastReportSendSuccess = true; } catch(Exception e) { resetScalabilityCounters(); lastReportSendSuccess = false; e.printStackTrace(); s_logger.error( "Error checking integrity on demand: "+e.getMessage() ); } break; case REBOOT: System.out.println("Action:REBOOT"); s_logger.debug("Action:REBOOT"); //TODO ENABLE THIS WHEN SAFE restartComputer(hostOS); break; case VERIFY_CLIENT: System.out.println("Action: VERIFY CLIENT"); s_logger.debug("Action: VERIFY CLIENT"); if (actionDelay != null) commandProcessor(VERIFY_COMMAND_LABEL, actionDelay.getArgs() == null? "":actionDelay.getArgs()); break; case CLEAN_CLIENT: System.out.println("Action: CLEAN CLIENT"); s_logger.debug("Action: CLEAN CLIENT"); if (actionDelay != null) commandProcessor(CLEAN_COMMAND_LABEL, actionDelay.getArgs() == null? "":actionDelay.getArgs()); break; } action = null; //delay for the poll interval try { if(pollInterval==0) { Thread.sleep(defaultPollInterval*1000); } else { if (actionDelay != null) Thread.sleep(pollInterval); } } //do we care about this o.0 catch(InterruptedException e) { e.printStackTrace(); } } } /** Method performs a system integrity check by calling the TPM and returning the Report. * * @throws java.lang.Exception */ public void checkIntegrity() throws Exception { s_logger.debug( "Checking system integrity" ); int bitCount=0; //number of PCR values asked for in the bitmask String userName; String tpmInput=""; byte[] b = new byte[4]; ReportType report; SnapshotType snap; QuoteDataType quote; String errMsg="*"; String quoteMode = TPM_QUOTE_MODE; //get the key Auth and Index properties String keyAuth = hisProperties.getProperty(KEY_AUTH_LABEL, DEFAULT_KEY_AUTH); String keyIndex = hisProperties.getProperty(KEY_INDEX_LABEL, DEFAULT_KEY_INDEX); s_logger.debug("Using Key Auth " + keyAuth + " and Key Index " + keyIndex + ".\n"); //Get the username userName = System.getProperty("user.name"); s_logger.debug("User name found as: "+userName); //Initialize the web service hisAuthenticationWebService = HisWebServicesClientInvoker.getHisWebService(webServiceUrl); //this sets the nonce and bitmask global variables via a web service call try { getReportParams(userName, computerName); } //Failure to get proper params will result in an error report catch(Exception e) { s_logger.error("Error recieving server Nonce and Bitmask."); report = createEmptyReport("Error recieving server Nonce and Bitmask: "+ e.getMessage(), ERROR_MESSAGE_ID); sendIntegrityReport(report); throw new Exception( "Error recieving server Nonce and Bitmask. " + e.getMessage()); } //log the nonce and bitmask s_logger.debug("Nonce recieved: "+nonce); s_logger.debug("Bitmask recieved: "+rawBitmask); //convert the raw bitmask to one that we can use try { pcrBitmask = unHexString(rawBitmask); } //if there is a problem, use default catch(Exception e) { pcrBitmask = DEFAULT_PCR_BITMASK; s_logger.error("Error recieving PCR Bitmask. Using default value."); } //if the bitmask is invalid, use default if(pcrBitmask.length>3 || pcrBitmask.length<1) { pcrBitmask = DEFAULT_PCR_BITMASK; s_logger.error("Error recieving PCR Bitmask. Using default value."); } //select the TPM QUOTE Mode (v1 or v2) based on the parameter from the web service (formerly bitmask length) if(quoteType == 2)//pcrBitmask.length == 3)// quoteType == 2) { //quoteType = 2; quoteMode = TPM_QUOTE2_MODE; } else if(quoteType == 1)//pcrBitmask.length == 2) { //quoteType = 1; quoteMode = TPM_QUOTE_MODE; } else { //quoteType = 1; quoteMode = TPM_QUOTE_MODE; } //construct the input string tpmInput = MODE_FLAG + " " + quoteMode + " " + BITMASK_FLAG + " "+ rawBitmask + " " + NONCE_FLAG + " " + nonce + " " + KEY_AUTH_FLAG + " " + keyAuth + " " + KEY_INDEX_FLAG + " " + keyIndex; //make the TPM call that gets the required PCR values. The complete return is stored in the member variable tpmOutput errMsg = runTPMrequest(tpmInput); //If we don't get a responce handle the error by creating an empty report and sending that back // if(!errMsg.equals("")) if (errMsg.length() != 0) { report = createEmptyReport(errMsg, ERROR_MESSAGE_ID); sendIntegrityReport(report); throw new Exception( "Error retrieving TPM data! " + errMsg); } //count all the bits in the mask //Made more complicated by Java's lack of support for bits for(int i = 0; i<pcrBitmask.length; i++) { //s_logger.debug("Byte = "+pcrBitmask[i]); b[3]=pcrBitmask[i]; BigInteger bi = new BigInteger(b); int bitInt = bi.intValue(); bitCount = bitCount+Integer.bitCount(bitInt); } s_logger.debug("Bit count = "+bitCount); //create the base integrity report report = createIntegrityReport(computerName); createMeasureSnapshot(report, "bios"); createMeasureSnapshot(report, "ima"); //parse the Quote and add it to the integrity report try { quote = parseQuote(quoteType, bitCount, report.getID()); report.getQuoteData().add(quote); } catch(Exception e) { report = createEmptyReport(errMsg + " Invalid TPM Data: "+e.getMessage(), ERROR_MESSAGE_ID); throw new Exception(e.getMessage()); } //if everything works out send the report onto the server try { sendIntegrityReport(report); } catch (Exception e) { throw new Exception(e.getMessage()); } } /** Invokes the auto-registration process that sends the AIC to the back end if the back end has indicated that it lacks it * */ /* private void registerHost() throws Exception { FileInputStream fin; X509Certificate aic; try { fin = new FileInputStream(hisPath + AIC_FILNAME); } catch (FileNotFoundException fnfe) { throw new Exception("AIC cert file not found"); } try { aic = X509Certificate.getInstance(fin); //TODO call the web service to send the AIC to the apraiser } catch (CertificateException ce) { s_logger.error("Unable to load AIC: " + ce.getMessage()); throw ce; } //TODO call the web service to send the AIC to the apraiser } * */ /** Makes a runtime call to the TPM executable interface and captures its output * * @param tpmInput The input string to the TPM Quote function */ private String runTPMrequest(String tpmInput) { //set up the call to the TPM executable interface int i = 0 ; int exitVal=99999; int j = 0; int dataTimeout = blockingTimeout /10; StreamPrinter sp=null; StreamOutput so=null; Runtime rt = Runtime.getRuntime(); String tpmInterfacePath = hisProperties.getProperty(TPM_QUOTE_EXECUTABLE_PATH_LABEL, hisPath); String tpmInterfaceName = hisProperties.getProperty(TPM_QUOTE_EXECUTABLE_NAME_LABEL, "NIARL_TPM_Module.exe"); this.tpmOutput = ""; try { //Run the process Process proc = rt.exec(tpmInterfacePath+tpmInterfaceName + " " + tpmInput); //make sure to grab any error messages sp = new StreamPrinter(proc.getErrorStream(), "ERROR", this); //and grab the input from the process for the integrity report so = new StreamOutput(proc.getInputStream(), this); sp.start(); so.start(); //now loop until we get a return value or we reach a timeout while(i<=blockingTimeout) { try { exitVal = proc.exitValue(); } catch(Exception e) { //if the process has not completed we get an exception, just catch and loop Thread.sleep(1); } if(exitVal!=99999) { //if we get a valid exit code break out of the loop break; } i++; } //if i has reached the blocking timeout value we need to throw an error if(i>=blockingTimeout) { //kill the threads sp.interrupt(); so.interrupt(); //kill the process proc.destroy(); so.stopThread(); sp.stopThread(); System.out.println("TPM Quote interface timeout, process aborted. Unable to capture quote."); s_logger.error("TPM Quote interface timeout, process aborted. Unable to capture quote."); return "TPM Interface Timeout"; } //if we get a non-0 return value then we also have a problem if(exitVal!=0) { System.out.println("TPM Quote interface returned error code "+exitVal+"."); s_logger.error("TPM Quote interface returned error code "+exitVal+"."); return "TPM error: "+exitVal; } //Provide time for the output to be read from StdOut while(j<=dataTimeout ) { if (this.tpmOutput.length() < 1) Thread.sleep(1);// give a litte extra time before stopping the other threads so Output can be updated else break; j++; } //if j has reached the data wait timeout if(j>=dataTimeout ) { //kill the process proc.destroy(); //kill the threads sp.interrupt(); so.interrupt(); so.stopThread(); sp.stopThread(); //throw new IOException("TPM interface data wait timeout, process aborted. Unable to capture TPM data."); s_logger.error("TPM interface data wait timeout, process aborted. Unable to capture TPM data."); return "TPM Data Timeout"; } so.stopThread(); sp.stopThread(); } catch(Throwable t) { t.printStackTrace(); System.out.println("Error running TPM Quote interface! Unable to capture quote."); s_logger.error("Error running TPM Quote interface! Unable to capture quote.", t); return "TPM Interface Unavailable: "+t.getMessage(); } return ""; } /** Generates the base XML integrity report accouting to the TCG Integrity Report 1.0 Scheema * Report needs to have the Quote and Snapshot data added to it later * * @param hostName The hostname of the machine * */ private ReportType createIntegrityReport(String hostName) { ReportType report = new ReportType(); String reportID; //Set the Report ID to the host name concatonated with the time ++ reportID = hostName + "-" + reportType + "-" + System.currentTimeMillis(); report.setID(reportID); //Set the UUID to the UUID prefix concatonated with the reportID ++ report.setUUID(generateUUID(UUID_VERSION)); return report; } /** Creates an empty report with no quote structure. This is used in case there is an issue accessing the TPM or no TPM is installed. * @param message a message proviging the reason for the empty report * @param messageTag a code setting the class of message sent in the Empty report * * @return the empty integrity report with message in the snapshot */ private ReportType createEmptyReport(String message, String messageTag) { ReportType report; SnapshotType snap; String taggedMessage; //combine the message and the ID to avoid problems using the any type taggedMessage = messageTag + "-" + message; //create the base integrity report report = createIntegrityReport(computerName); //Set up the system snapshot with the error message snap = createSnapshot(report.getID(), taggedMessage); report.getSnapshotCollection().add(snap); return report; } /** This creates the system snapshot object. The snapshot can contain a listing of all the system components and their various attributes * Only one component is required along with various snapshot ID. Each component element itself have a large list of optional data that pertains solely to that component. * * This method is currently only filling in the single required component element with default values. * * Also used for the error report by stuffing the error report into the Value Type field. * * The PcrHash must be added seperately. * * @param id The ID number for the overall integrity report. * @param taggedMessage A message string tagged with an appropiate value for use in Error reports or to send other information to the server */ private SnapshotType createSnapshot(String id, String taggedMessage) { SnapshotType snap = new SnapshotType(); ComponentIDType component = new ComponentIDType(); VendorIdType vendorID = new VendorIdType(); JAXBElement<String> vendorGUID = new ObjectFactory().createVendorIdTypeVendorGUID(hisProperties.getProperty(VENDOR_GUID_LABEL, "0000")); ValueType messageValue = new ValueType();//Error message storage KeyValueType kv = new KeyValueType();//Error message storage org.w3._2000._09.xmldsig_.ObjectFactory of = new org.w3._2000._09.xmldsig_.ObjectFactory(); //Get the Vendor GUID and other info from a from a property file vendorID.getTcgVendorIdOrSmiVendorIdOrVendorGUID().add(vendorGUID); vendorID.setName(hisProperties.getProperty(VENDOR_NAME_LABEL, "Unknown Vendor")); //construct the component type component.setVendorID(vendorID); component.setId("Default_Component"); //optional data fields, use TBD component.setModelName(hisProperties.getProperty(MODEL_NAME_LABEL, "")); component.setModelNumber(hisProperties.getProperty(MODEL_NUMBER_LABEL, "XXXX")); component.setVersionMajor(new BigInteger(hisProperties.getProperty(VERSION_MAJOR_LABEL, "00"))); component.setVersionMinor(new BigInteger(hisProperties.getProperty(VERSION_MINOR_LABEL, "00"))); component.setModelSerialNumber(hisProperties.getProperty(MODEL_SN_LABEL, "XXXX")); component.setPatchLevel(hisProperties.getProperty(MODEL_PATCH_LEVEL_LABEL, "")); //construct the Composite Hash Type //pcrHashType.setId(id); //pcrHashType.setValue(pcrHash); //Now construct the snapshot object //Set the IDs snap.setUUID(generateUUID(UUID_VERSION));//UUID_PREFIX + "."+SNAPSHOT_PREFIX+"."+id); snap.setId(SNAPSHOT_PREFIX+"."+id); snap.setRevLevel(new BigInteger(SNAPSHOT_REV_LEVEL)); //add the component snap.setComponentID(component); //Add the pcr hash returned from the TPM quote into a digest value //snap.getCompositeHash().add(pcrHash); //if a message is set add it to a Value type to be reported to the server // if(!taggedMessage.equals("")) if (taggedMessage.length() != 0) { //construct the ValueType with the message //To match the schema we must add a Key Value object with a placeholder value kv.getContent().add("-"); messageValue.setAny(of.createKeyName("placeholder")); messageValue.setId(taggedMessage);//the message is stored in the Value type ID field snap.getValues().add(messageValue); } return snap; } /** * Calls the right function depending on the received IML type * and returns the final report. * * @param report The report that will contain the SnapshotCollection * elements * @param imlType The type of integrity measurements to be parsed */ private void createMeasureSnapshot(ReportType report, String imlType) { try { if (imlType.equals("bios")) createBIOSSnapshot(report); else if (imlType.equals("ima")) createIMASnapshot(report); } catch (Exception e) { if (e instanceof NoSuchAlgorithmException) s_logger.error("SHA-1 is required to create a valid snapshot"); else s_logger.error(e.getMessage()); e.printStackTrace(); } } private String getValueFromPcrNumber(int pcrNumber) { int intBitmask = (pcrBitmask[2] & 0xFF) | ((pcrBitmask[1] & 0xFF) << 8) | ((pcrBitmask[0] & 0xFF) << 16); int pcrPosition = -1; for (int i = 0; i < PCR_MAX_NUM; i++) { if ((intBitmask & (0x00800000 >> i)) != 0) pcrPosition++; if (i == pcrNumber) break; } if (pcrPosition == -1) return null; return tpmOutput.split(" ")[pcrPosition]; } /** * Creates an element SnapshotCollection, writes IMA measurements * inside it and adds it to the given ReportType element. * * @param report The report that will contain the SnapshotCollection * elements */ private void createIMASnapshot(ReportType report) throws NoSuchAlgorithmException, Exception { int intBitmask = (pcrBitmask[2] & 0xFF) | ((pcrBitmask[1] & 0xFF) << 8) | ((pcrBitmask[0] & 0xFF) << 16); SnapshotType snap = null; String UUID = generateUUID("4"); byte[] tmpBytes = new byte[4]; int eventCount = 0; int pcrNumber; byte[] hashValue = null; byte[] digestValue = null; byte[] readImageSize = null; int imageSize; File ima_file = new File("/sys/kernel/security/ima/binary_runtime_measurements"); if (!ima_file.exists()) return; InputStream in = new FileInputStream("/sys/kernel/security/ima/binary_runtime_measurements"); in.skip(lastByteIMA); while (in.read(tmpBytes, 0, 4) == 4) { pcrNumber = ByteBuffer.wrap(tmpBytes).order(ByteOrder.nativeOrder()).getInt(); if ((intBitmask & (0x00800000 >> pcrNumber)) == 0) return; eventCount = lastEventCount[pcrNumber]; hashValue = new byte[PCR_SIZE]; in.read(hashValue, 0, PCR_SIZE); in.read(tmpBytes, 0, 4); int templateNameSize = ByteBuffer.wrap(tmpBytes).order(ByteOrder.nativeOrder()).getInt(); byte[] templateName = new byte[templateNameSize]; in.read(templateName, 0, templateNameSize); imageSize = 0; digestValue = null; if (new String(templateName).equals("ima")) { digestValue = new byte[PCR_SIZE]; in.read(digestValue, 0, PCR_SIZE); imageSize += PCR_SIZE; } readImageSize = new byte[4]; in.read(readImageSize, 0, 4); int templateDataSize = ByteBuffer.wrap(readImageSize).order(ByteOrder.nativeOrder()).getInt(); byte[] templateData = new byte[templateDataSize]; in.read(templateData, 0, templateDataSize); imageSize += templateDataSize; ByteBuffer imageBuffer = ByteBuffer.allocate(imageSize); if (digestValue != null) imageBuffer.put(digestValue); imageBuffer.put(templateData); if (snap == null) { snap = initializeSnapshot(UUID, 10); } snap = createValuesType(snap, UUID, 10, new String(templateName), eventCount, hashValue, imageBuffer.array()); eventCount++; /* 4 * 3 bytes are for PCR number, template name length and template data length */ lastByteIMA += 4 * 3 + templateNameSize + imageSize + PCR_SIZE + ((digestValue != null) ? PCR_SIZE : 0); lastEventCount[pcrNumber] = eventCount; if (hexString(lastPcrHash[pcrNumber]).toUpperCase().equals(getValueFromPcrNumber(pcrNumber).toUpperCase())) break; } report.getSnapshotCollection().add(snap); in.close(); } /** * Creates an element SnapshotCollection for each PCR entry * read from the BIOS measurements file and adds it to the * given ReportType element. * * @param report The report that will contain the SnapshotCollection * elements */ private void createBIOSSnapshot(ReportType report) throws NoSuchAlgorithmException, Exception { int intBitmask = (pcrBitmask[2] & 0xFF) | ((pcrBitmask[1] & 0xFF) << 8) | ((pcrBitmask[0] & 0xFF) << 16); byte[] tmpBytes = new byte[4]; String UUID = generateUUID("4"); SnapshotType snap = null; int pcrNumber; byte[] hashValue = null; String eventType; byte[] readImageSize = null; int imageSize; byte[] digestValue = null; int imageBufferSize; int[] eventCount = new int[PCR_MAX_NUM]; for (int i=0; i<PCR_MAX_NUM; i++) eventCount[i] = lastEventCount[i]; boolean[] pcrValueReached = new boolean[PCR_MAX_NUM]; for (int i=0; i<PCR_MAX_NUM; i++) pcrValueReached[i] = false; FileInputStream tpmFileStream = new FileInputStream("/sys/kernel/security/tpm0/binary_bios_measurements"); if (tpmFileStream == null) throw new Exception("Can't read file \"/sys/kernel/security/tpm0/binary_bios_measurements\""); tpmFileStream.skip(lastByteBIOS); while (tpmFileStream.read(tmpBytes, 0, 4) == 4) { pcrNumber = ByteBuffer.wrap(tmpBytes).order(ByteOrder.nativeOrder()).getInt(); tpmFileStream.read(tmpBytes, 0, 4); StringBuilder sb = new StringBuilder(); for(int i = 3; i >= 0; i--) sb.append(String.format("%02x", tmpBytes[i]&0xff)); eventType = sb.toString().replaceFirst("^(00)+(?!$)", ""); hashValue = new byte[PCR_SIZE]; tpmFileStream.read(hashValue, 0, PCR_SIZE); readImageSize = new byte[4]; tpmFileStream.read(readImageSize, 0, 4); imageSize = ByteBuffer.wrap(readImageSize).order(ByteOrder.nativeOrder()).getInt(); digestValue = new byte[imageSize]; tpmFileStream.read(digestValue, 0, imageSize); imageBufferSize = readImageSize.length + digestValue.length; ByteBuffer imageBuffer = ByteBuffer.allocate(imageBufferSize); imageBuffer.put(readImageSize); imageBuffer.put(digestValue); /* 4 * 3 bytes are for PCR number, template name length and template data length */ lastByteBIOS += 4 * 3 + PCR_SIZE + imageSize; if (pcrValueReached[pcrNumber] || (intBitmask & (0x00800000 >> pcrNumber)) == 0) continue; snap = null; for (SnapshotType tmpSnap : report.getSnapshotCollection()) { if (tmpSnap.getComponentID().getId().equals("CID_" + pcrNumber)) { snap = tmpSnap; break; } } if (snap == null) { snap = initializeSnapshot(UUID, pcrNumber); snap = createValuesType(snap, UUID, pcrNumber, eventType, eventCount[pcrNumber], hashValue, imageBuffer.array()); report.getSnapshotCollection().add(snap); } else { createValuesType(snap, UUID, pcrNumber, eventType, eventCount[pcrNumber], hashValue, imageBuffer.array()); } eventCount[pcrNumber]++; lastEventCount[pcrNumber] = eventCount[pcrNumber]; if (hexString(lastPcrHash[pcrNumber]).toUpperCase().equals(getValueFromPcrNumber(pcrNumber).toUpperCase())) pcrValueReached[pcrNumber] = true; } tpmFileStream.close(); } /** * Creates an element SnapshotCollection for the given PCR number. * * @param pcrIndex Number of the PCR whose measurements will be * placed in the SnapshotCollection * @param UUID UUID of the SnapshotCollection * @return The SnapshotCollection to be included in the report */ private SnapshotType initializeSnapshot(String UUID, int pcrIndex) { SnapshotType snap = new SnapshotType(); ComponentIDType component = new ComponentIDType(); VendorIdType vendorID = new VendorIdType(); vendorID.setName(hisProperties.getProperty(VENDOR_NAME_LABEL, "JJ")); vendorID.getTcgVendorIdOrSmiVendorIdOrVendorGUID().add(new ObjectFactory().createVendorIdTypeSmiVendorId(new BigInteger("0"))); vendorID.getTcgVendorIdOrSmiVendorIdOrVendorGUID().add(new ObjectFactory().createVendorIdTypeTcgVendorId("DEMO")); component.setVendorID(vendorID); component.setId("CID_" + pcrIndex); component.setModelSystemClass ("TBD"); if (pcrIndex == 10) component.setSimpleName ("OAT IMA"); else component.setSimpleName ("JJ"); component.setVersionBuild (new BigInteger ("1250694000000")); component.setVersionString ("JJ"); DigestMethodType digestMethod = new DigestMethodType(); digestMethod.setAlgorithm ("unknown"); digestMethod.setId ("sha1"); snap.getDigestMethod().add(digestMethod); //Set the IDs snap.setUUID(UUID); snap.setId("IR_" + UUID); snap.setRevLevel(new BigInteger(SNAPSHOT_REV_LEVEL)); snap.setComponentID(component); return snap; } /** * Creates an element Values and adds it to the received * SnapshotCollection; if the SnapshotCollection is null * the function also creates it. * * @param snap SnapshotCollection to be created or extended * @param UUID UUID of the SnapshotCollection * @param pcrIndex Index of the PCR the hash refers to * @param eventType Number used to compose the Id of element Hash * @param eventCount Number used to compose the Id of element Hash * @param hashValue Content of element Hash * @param imageValue Content of parameter Image in element Objects * @return The SnapshotCollection to be included in the report */ private SnapshotType createValuesType(SnapshotType snap, String UUID, int pcrIndex, String eventType, int eventCount, byte[] hashValue, byte[] imageValue) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("SHA-1"); byte[] startHash = new byte[PCR_SIZE]; ValueType messageValue = new ValueType(); TpmDigestValueType pcrHash; ValuesType objects = new ValuesType(); DigestValueType hash = new DigestValueType(); SimpleObjectType simpleObject = (new org.trustedcomputinggroup.xml.schema.simple_object_v1_0_.ObjectFactory()).createSimpleObjectType(); String levelString = "LV0"; String eventTypeString = eventType.replaceFirst("^0+(?!$)", ""); if (pcrIndex == 10) { levelString = "LV1"; eventTypeString = "0"; } hash.setId("PCR_" + pcrIndex + "_" + levelString + "_" + eventTypeString + "_" + eventCount + "_EVENT"); hash.setAlgRef(snap.getDigestMethod().get(0).getId()); hash.setValue(hashValue); objects.getHash().add(hash); objects.setImage(imageValue); objects.setType(eventType); simpleObject.getObjects().add(objects); messageValue.setAny(new org.trustedcomputinggroup.xml.schema.simple_object_v1_0_.ObjectFactory().createSimpleObject (simpleObject)); snap.getValues().add(messageValue); /* * PcrHash */ if (snap.getPcrHash().size() == 0) { pcrHash = new TpmDigestValueType(); pcrHash.setAlgRef("sha1"); pcrHash.setId("PCR_" + pcrIndex + "_" + levelString + "_HASH"); pcrHash.setIsResetable(false); pcrHash.setNumber(BigInteger.valueOf(pcrIndex)); startHash = lastPcrHash[pcrIndex]; pcrHash.setStartHash(startHash); snap.getPcrHash().add(pcrHash); } else { pcrHash = snap.getPcrHash().get(0); startHash = lastPcrHash[pcrIndex]; } md.reset(); md.update (startHash, 0, PCR_SIZE); if (hexString(hashValue).equals("0000000000000000000000000000000000000000")) md.update(unHexString("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"), 0, PCR_SIZE); else md.update(hashValue, 0, PCR_SIZE); pcrHash.setValue(md.digest()); lastPcrHash[pcrIndex] = pcrHash.getValue(); return snap; } /** Takes raw PCR data and constructs a QuoteData element that conrails the a PCR value quote and a corresponding signature. * @param id The report ID to for use by the Quote Data object. * @param pcrComposite This object is loaded with all of the PCR values from the TPM * @param quoteSignature The object containing the TPM signature over the returned PCR data * @param nonce The nonce returned with the TPM quote * @param pcrHash a hash of all the returned PCR values which is signed in the quote */ private QuoteDataType createQuoteDataEntry(String reportId, PcrCompositeType pcrComposite, QuoteSignatureType quoteSignature, byte[] nonce, byte[] pcrHash, short quoteVersion) { //Here is the element we return QuoteDataType qData = new QuoteDataType(); //set the ID field qData.setID(QUOTE_PREFIX+"."+reportId); //QuoteData needs these two other objects QuoteType quote = new QuoteType(); QuoteSignatureType tpmSIG =quoteSignature; //Quote needs the following objects, PcrComposite and QuoteInfo quote.setPcrComposite(pcrComposite); QuoteInfoType quoteInfo = new QuoteInfoType(); //Now set up the Quote Info first with various pre-configured values quoteInfo.setVersionMajor(QUOTE_VERSION_MAJOR); quoteInfo.setVersionMinor(QUOTE_VERSION_MINOR); quoteInfo.setVersionRevMajor(QUOTE_VERSION_REV_MAJOR); quoteInfo.setVersionRevMinor(QUOTE_VERSION_REV_MINOR); if(quoteVersion==1) { quoteInfo.setFixed(QUOTE_FIXED); } if(quoteVersion==2) { quoteInfo.setFixed(QUOTE2_FIXED); } //then the nonce and pcr hash quoteInfo.setExternalData(nonce); quoteInfo.setDigestValue(pcrHash); quote.setQuoteInfo(quoteInfo); //add the components to the quote data type qData.setQuote(quote); qData.setTpmSignature(tpmSIG); return qData; } /** Parses a raw TPM version 1 quote (in Hex String format) and puts the PCR values into an TCG Integrity report * * This function does not attempt to check if the Quote values are valid * * @param quoteVer The version of quote to parse against, Quote or Quote 2 * @param pcrNumber The number of PCR values being returned * @param reportID The Report ID. * @return A Quate Data object containing the data parsed from the TPM output * @throws java.io.IOException */ private QuoteDataType parseQuote(int quoteVer, int pcrNumber, String reportID) throws IOException { //All HexString sizes are BYTES TIMES TWO int segmentSize=0; int sizeCounter = 0; String quoteVersionTag= ""; byte[] bitmask = pcrBitmask; String bitmaskLenStr= ""; int bitmaskLen=1; String returnedNonce=""; byte[] nonceBytes; String pcrHash=""; byte[] pcrHashBytes; String signature=""; PcrCompositeType pcrComposite; PcrSelectionType pcrSelect = new PcrSelectionType(); QuoteSignatureType quoteSig = new QuoteSignatureType(); QuoteDataType quote; //This parcer scans through the output of the TPM module and rigorously checks to make sure the returned value meet the spec //---------------------READ PCR VALUES-------------------------------// s_logger.debug("Parsing "+pcrNumber+" PCR values."); pcrComposite = new PcrCompositeType(); //pull the PCR list from the snapshot to add the values to List pcrs = pcrComposite.getPcrValue(); //Loop through the PCR values adding them to the list for(int i = 0; i < 8 * bitmask.length; i++) { PcrValue pcrEntry = new org.trustedcomputinggroup.xml.schema.integrity_report_v1_0_.ObjectFactory().createPcrCompositeTypePcrValue(); String pcrValue; byte[] pcrValueBytes; if ((128 >> (i % 8) & bitmask[i/8]) == 0) continue; //Set the index number of the first PCR value pcrEntry.setPcrNumber(new BigInteger(new Integer(i).toString())); //pull off the PCR chunk segmentSize = PCR_SIZE; pcrValue = tpmOutput.substring(sizeCounter, sizeCounter+(segmentSize*2)); //parse the PCR value try { pcrValueBytes = unHexString(pcrValue); } catch(Exception e) { s_logger.error( "Error parsing PCR Value hex string #"+i+" , invalid input. Error at count: "+ sizeCounter + ".\n"+ tpmOutput, e); throw new IOException("Error parsing PCR Value hex string #"+i+" , invalid input."); } //set the value and add it to the list pcrEntry.setValue(pcrValueBytes); pcrs.add(pcrEntry); sizeCounter = sizeCounter+(segmentSize*2); //Check for the space? if(tpmOutput.charAt(sizeCounter)!=' ') { s_logger.error("Parsing error at PCR #"+i+". Unexpected length. Error at count: "+ sizeCounter + ".\n"+ tpmOutput); throw new IOException("Parsing error at PCR #"+i+". Unexpected length."); } //One for the space sizeCounter++; } s_logger.debug("Parsing quote."); //--------------------INPUT NONCE------------------------// //just skip it and the extra space after it. The nonce is also included in the Quote sizeCounter = sizeCounter+(NONCE_SIZE*2)+1; //--------------------QUOTE------------------------------// //parse Version 1 quote if(quoteVer==1) { segmentSize = QUOTE_SIZE; //Get the quote version try { quoteVersionTag = tpmOutput.substring(sizeCounter, sizeCounter+QUOTE_VERSION_SIZE*2); } catch(Exception e) { s_logger.error( "Unable to read TPM Quote Version Hex String! Error at count: "+ sizeCounter +".\n"+ tpmOutput, e); throw new IOException("Unable to read TPM Quote Version Hex String!"); } if(!quoteVersionTag.equals(EXPECTED_QUOTE_VERSION_TAG)) { s_logger.warn( "Quote version "+quoteVersionTag+ " does not match expected version "+EXPECTED_QUOTE_VERSION_TAG); } sizeCounter = sizeCounter+(QUOTE_VERSION_SIZE*2); //skip over the fixed value sizeCounter = sizeCounter+(QUOTE_FIXED_SIZE*2); //Get the PCR Hash PCR_HASH_SIZE pcrHash = tpmOutput.substring(sizeCounter, sizeCounter+PCR_HASH_SIZE*2); sizeCounter = sizeCounter+(PCR_HASH_SIZE*2); //Get the nonce returnedNonce = tpmOutput.substring(sizeCounter, sizeCounter+NONCE_SIZE*2); sizeCounter = sizeCounter+(NONCE_SIZE*2); bitmaskLen=bitmask.length;//PCR_BITMASK_SIZE; } //parse Version 2 quote if(quoteVer==2) { //QUOTE 2 can have a variable length of between 50 and 52 bytes //Get the quote version/tag The value for Quote 2 is 0x0036 try { quoteVersionTag = tpmOutput.substring(sizeCounter, sizeCounter+QUOTE2_VERSION_SIZE*2); if(!Arrays.equals(unHexString(quoteVersionTag), EXPECTED_QUOTE2_VERSION_TAG)) { s_logger.warn( "Quote version "+quoteVersionTag+ " does not match expected version "+hexString(EXPECTED_QUOTE2_VERSION_TAG)); } } catch(Exception e) { s_logger.error( "Unable to read TPM Quote Version Hex String! Error at count: "+ sizeCounter +".\n"+ tpmOutput, e); throw new IOException("Unable to read TPM Quote Version Hex String!"); } sizeCounter = sizeCounter+(QUOTE2_VERSION_SIZE*2); //skip over the fixed value sizeCounter = sizeCounter+(QUOTE_FIXED_SIZE*2); //Get the nonce returnedNonce = tpmOutput.substring(sizeCounter, sizeCounter+NONCE_SIZE*2); sizeCounter = sizeCounter+(NONCE_SIZE*2); bitmaskLenStr = tpmOutput.substring(sizeCounter, sizeCounter+QUOTE2_BITMASK_LENGTH_SIZE*2); sizeCounter = sizeCounter+(QUOTE2_BITMASK_LENGTH_SIZE*2); //pull the size of the bitmask in bytes from the length field if(bitmaskLenStr.endsWith("1")){bitmaskLen=1;} else if(bitmaskLenStr.endsWith("2")){bitmaskLen=2;} else if(bitmaskLenStr.endsWith("3")){bitmaskLen=3;} //calculate the segment size segmentSize = QUOTE2_SIZE_BASE+bitmaskLen; //pull out the bitmask try { bitmask = unHexString(tpmOutput.substring(sizeCounter, sizeCounter+bitmaskLen*2)); sizeCounter = sizeCounter+(bitmaskLen*2); } catch(Exception e) { s_logger.error( "Error parsing Quote 2 bitmask hex string, invalid input.", e); throw new IOException("Error parsing Quote 2 bitmask hex string, invalid input."); } //Parse the one byte filler byte if(!tpmOutput.substring(sizeCounter, sizeCounter+2).equals(QUOTE2_FILLER_BYTE)) { s_logger.warn("TPM Quote 2 Filler byte incorrect: "+tpmOutput.substring(sizeCounter, sizeCounter+2)); } sizeCounter = sizeCounter+2; //Get the PCR Hash PCR_HASH_SIZE pcrHash = tpmOutput.substring(sizeCounter, sizeCounter+PCR_HASH_SIZE*2); sizeCounter = sizeCounter+(PCR_HASH_SIZE*2); } //Check for the space if(tpmOutput.charAt(sizeCounter)!=' ') { s_logger.error( "Parsing error in TPM Quote - "+tpmOutput.charAt(sizeCounter)+" - Unexpected length at count " + sizeCounter + ".\n"+ tpmOutput); throw new IOException("Parsing error in TPM Quote - "+tpmOutput.charAt(sizeCounter)+" - Unexpected length at count " + sizeCounter); } sizeCounter++; //----------------------------SIGNATURE------------------------------// s_logger.debug("Parsing signature."); segmentSize=SIGNATURE_SIZE; //grab the signature block using the dynamic size signature = tpmOutput.substring(sizeCounter, sizeCounter+segmentSize*2); //Now we populate the TPM signature information //First set the signature method SignatureMethodType sm = new SignatureMethodType(); sm.setAlgorithm(""); quoteSig.setSignatureMethod(sm); //Then the key info //NOTE Currently no info on the signature/cert/key are available from the TPM so default values are used KeyInfoType ki = new KeyInfoType(); JAXBElement<String> kn = new org.w3._2000._09.xmldsig_.ObjectFactory().createKeyName(computerName); ki.getContent().add(kn); quoteSig.setKeyInfo(ki); //Finally add the actual signature bytes SignatureValueType sigVal = new SignatureValueType(); try { sigVal.setValue(unHexString(signature)); } catch(Exception e) { s_logger.error( "Error parsing signature hex string, invalid input.", e); throw new IOException("Error parsing signature hex string, invalid input."); } quoteSig.setSignatureValue(sigVal); //------------------------QUOTE DATA PROCESSING --------------------------------// s_logger.debug("Processing Quote data."); //here all of the info we just parsed from the quote is assembled into a Quote Data structure pcrComposite.setValueSize(new BigInteger(new Integer(PCR_SIZE * pcrNumber).toString())); pcrSelect.setPcrSelect(bitmask); pcrSelect.setSizeOfSelect(bitmaskLen); pcrComposite.setPcrSelection(pcrSelect); //parse the nonce try { nonceBytes = unHexString(returnedNonce); } catch(Exception e) { s_logger.error( "Error parsing nonce hex string, invalid input.", e); throw new IOException("Error parsing nonce hex string, invalid input."); } //parse the PCR Composite try { pcrHashBytes = unHexString(pcrHash); } catch(Exception e) { s_logger.error( "Error parsing PCR Compisite hash hex string, invalid input.", e); throw new IOException("Error parsing PCR Compisite hash hex string, invalid input."); } //now create the Quote Data object in the report quote = createQuoteDataEntry(reportID, pcrComposite, quoteSig, nonceBytes, pcrHashBytes, (short)quoteVer); return quote; } /** * Resets counters used by the client to * implement the scalability mechanism. */ private void resetScalabilityCounters() { reportType = "start"; lastByteBIOS = 0; lastByteIMA = 0; for (int i = 0; i < PCR_MAX_NUM; i++) { lastPcrHash[i] = unHexString("0000000000000000000000000000000000000000"); lastEventCount[i] = 0; } } /** Makes a web service call to get the parameters for the Integrity check. * The parameters include a Quote type (1 or 2) nonce and PCR selection and are customized for the computer and user. * * @param userName The username of the principal logging in * @param compName The name of the workstation being logged into * */ private void getReportParams(String userName, String compName) { //get the web service object with the correct computer name NonceSelect nonceSelect = hisAuthenticationWebService.getNonce(compName, userName); /* * Ignore the report type requested by the Appraiser, * if the Client service restarted or last report was * not successfully sent. */ if (clientStartUpDone && lastReportSendSuccess) { reportType = nonceSelect.getReportType(); } if (reportType.equals("start")) { resetScalabilityCounters(); } //NOTE: This can be considered input filtering for command line arguments as the Hex tool can only generate 0-9 A-F //This selection must account for null return from older versions of the web service try { if(nonceSelect.getQuote() == Quote.QUOTE_2) { quoteType = 2; } else { quoteType = 1; } } catch(Exception e){quoteType = 1;} System.out.println("Quote type = "+quoteType); nonce = hexString(nonceSelect.getNonce()); rawBitmask = hexString(nonceSelect.getSelect()); } /** Marshalls the integrity report object into a string format and sends it to the server via a web service * * @param reportType The integrity report to be sent */ private void sendIntegrityReport(ReportType reportType) throws Exception { JAXBContext jc=null; Marshaller m=null; System.out.println("Sending integrity report"); try { jc = JAXBContext.newInstance("org.trustedcomputinggroup.xml.schema.integrity_report_v1_0_:org.trustedcomputinggroup.xml.schema.simple_object_v1_0_"); m = jc.createMarshaller(); } catch(Exception e) { throw new Exception( "Error setting up TCG report marshaller: " + e.getMessage() ); } //make an output stream for the marshaller and then turn the object into bytes ByteArrayOutputStream bOut = new ByteArrayOutputStream(); try { JAXBElement<ReportType> report = new org.trustedcomputinggroup.xml.schema.integrity_report_v1_0_.ObjectFactory().createReport(reportType); m.marshal(report, bOut); } catch(Exception e) { e.printStackTrace(); throw new Exception( "Error marshalling TCG Integrity report: " + e.getMessage() ); } //Make a web service call to send the report try { hisAuthenticationWebService.postIntegrityReport(new String(bOut.toByteArray())); } catch(Exception e) { throw new Exception( "Web service error: " + e.getMessage() ); } } /** Performs a system call to reboot the system to enable fresh measurements to be taken. * This is not intended as a sophisticated administrative tool, only a quick and dirty proof of concept/ * * @param osType The type of OS runnign the application */ private void restartComputer(int osType) { Runtime rt = Runtime.getRuntime(); String cmd = ""; String cmd1 = "shutdown"; //try to send an OS specific command based on the configured OS type or if not configured, use both switch(osType) { case WINDOWS_OS: cmd = WINDOWS_REBOOT_CMD; break; case LINUX_OS: cmd = LINUX_REBOOT_CMD; break; default: //If no OS is specified then just try both commands. cmd = WINDOWS_REBOOT_CMD; cmd1 = LINUX_REBOOT_CMD; } try { rt.exec(cmd); //if this is "shutdown" then nothing will happen, not like it matters anyway with a reboot rt.exec(cmd1); } //If the command fails there's no much we can really do except possibly send an error report catch (IOException ioe) { System.out.println("Error rebooting client."); ioe.printStackTrace(); ReportType report = createEmptyReport("Error rebooting client: "+ ioe.getMessage(), ERROR_MESSAGE_ID); try { sendIntegrityReport(report); } catch(Exception e) { System.out.println("Error sending error report: "+e.getMessage()+"\nI give up."); e.printStackTrace(); } } return; } /** A wrapper method to log and send an error report with the specified error message * * @param errMsg The error message * @return true for sucess, false for a sending error */ private boolean sendErrorReport(String errMsg) { s_logger.error( errMsg); //create a new Integrity report of the empty/error type ReportType report = createEmptyReport(errMsg, ERROR_MESSAGE_ID); //then send it using the normal method try { sendIntegrityReport(report); } catch(Exception e) { s_logger.error("Error sending error report after \""+errMsg+"\" error: "+e.getMessage()); e.printStackTrace(); return false; } return true; } /** Processes generic commands from the on demand system. * Takes in an index which points to a command in a properties file and applies the arguments. * * @param commandLabel The command index in the properties file * @param args The arguments applied to the command */ private void commandProcessor(String commandLabel, String args) { Runtime rt = Runtime.getRuntime(); String commandRoot=""; String command=""; int exitVal=99999; int i = 0 ; //pull the command from the property specified by the index commandRoot = hisProperties.getProperty(commandLabel); if(commandRoot==null || commandRoot.length() == 0) { sendErrorReport( "Command not found at specified index."); return; } //assemble the command, the arg string is single quote escaped to prevent command injection command= commandRoot + " \'"+args+"\'"; try { //Run the process Process proc = rt.exec(command); //now loop until we get a return value or we reach a timeout while(i<=blockingTimeout) { try { exitVal = proc.exitValue(); } catch(Exception e) { //if the process has not completed we get an exception, just catch and loop Thread.sleep(1); } if(exitVal!=99999) { //if we get a valid exit code break out of the loop break; } i++; } //if i has reached the blocking timeout value we need to throw an error if(i>=blockingTimeout) { System.out.println("No Return value from "+command+" command."); s_logger.warn("No Return value from "+command+" command."); return; //TODO report this via an error report? } //if we get a non-0 return value then we also have a problem and should report it to the server if(exitVal!=0) { System.out.println("Error code returned from "+command+" command: "+exitVal); sendErrorReport("Error code returned from "+command+" command: "+exitVal); return; } } catch(Throwable t) { t.printStackTrace(); sendErrorReport("Error running On Demand command: "+t.getMessage()); s_logger.error("Error running On Demand command: "+t.getMessage(), t); return; } } /** Generated a UUID vased on the supplied version number. Currently UUID versions 1, 3 and 4 are supported. * Unsupported versions will result in a default value being returned. * * @param version the version number of the UUID to be geerated. Ver 1, 3 and 4 supported. * @return a properly formatted UUID */ public static String generateUUID(String version) { String uuid=""; if(version.equals("1")) { //UUID Version 1 uses MAC address and timestamp com.eaio.uuid.UUID u = new com.eaio.uuid.UUID(); uuid=u.toString(); } else if(version.equals("3")) { //UUID version 3 uses the machine's full domain name byte[] name; try { //name = InetAddress.getLocalHost().getCanonicalHostName().getBytes(); name = InetAddress.getLocalHost().getHostName().getBytes(); } catch(Exception e) { //if we can't find the official hostname use localhost s_logger.error( "Unable to obtain POSIX domain nane for Version 3 UUID. Using default name localhost.", e); name = "localhost".getBytes(); } java.util.UUID u = java.util.UUID.nameUUIDFromBytes(name); uuid = u.toString(); } else if(version.equals("4")) { //UUID version 4 uses a random number java.util.UUID u = java.util.UUID.randomUUID(); uuid = u.toString(); } else { s_logger.error( "Invalid UUID version: "+ version+ ". Using random UUID as default."); java.util.UUID u = java.util.UUID.randomUUID(); uuid = u.toString(); } return uuid; } } /** Helper class that provides general stream printing capability to Std out * * */ //This was copied from an online template with minimal modifications class StreamPrinter extends Thread { InputStream is; String type; StandaloneHIS his; private volatile Thread streamPrinterThread; /** Basic constructor * * @param is The output stream to print from, either stdErr or stdOut * @param type String label for the stream being printed * @param h Pointer to the HIS Client in order to use its logging functions */ StreamPrinter(InputStream is, String type, StandaloneHIS h) { this.is = is; this.type = type; this.his = h; } /** Main method of class. Pulls anything written to the stream and sends it to the HIS Client logger * */ public void run() { try { //prepare a buffered reader to read from InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line=null; //loop until thread terminated while ( (line = br.readLine()) != null) { //Log to the HIS plugin logger his.s_logger.error("Executable interface output: " +type + "> " + line); System.out.println(type + ">" + line); } } catch (IOException ioe) { ioe.printStackTrace(); } } /** Starts the thread * * */ public void start (boolean RequestTempCertRButton) { streamPrinterThread = new Thread (this); streamPrinterThread.start (); } /** Stops the thread * */ public void stopThread () { streamPrinterThread = null; } } /** Helper class that returns all of the output from the specified stream into a string * */ //This was copied from an online template with minimal modifications class StreamOutput extends Thread { InputStream is; String output; StandaloneHIS his; private volatile Thread streamOutputThread; /** Basic constructor * * @param is The output stream to print from, either stdErr or stdOut * @param h Pointer to the HIS Client in order to write to its tpmOutput buffer */ StreamOutput(InputStream is, StandaloneHIS h) { this.is = is; his=h; } /** Main method of class. Pulls anything written to the stream and sends it to the HIS Client tpmOutput buffer * */ public void run() { try { //set up the buffered reader InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); StringBuffer sb = new StringBuffer(); String line=null; //keeps reading until terminated while ( (line = br.readLine()) != null) { //concatonate the new line to the existing output his.tpmOutput = sb.append(line).toString(); } //System.out.println(hisPlug.tpmOutput); } catch (Exception ioe) { his.tpmOutput = ""; ioe.printStackTrace(); } } /** Starts the thread * */ public void start (boolean RequestTempCertRButton) { streamOutputThread = new Thread (this); streamOutputThread.start (); } /** Stops the thread * */ public void stopThread () { streamOutputThread = null; } }
true
false
null
null
diff --git a/src/checkstyle/com/puppycrawl/tools/checkstyle/Scope.java b/src/checkstyle/com/puppycrawl/tools/checkstyle/Scope.java index 867b820d8..cf0625e9a 100644 --- a/src/checkstyle/com/puppycrawl/tools/checkstyle/Scope.java +++ b/src/checkstyle/com/puppycrawl/tools/checkstyle/Scope.java @@ -1,183 +1,183 @@ //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2002 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle; import java.io.Serializable; import java.io.ObjectStreamException; import java.util.Map; import java.util.HashMap; /** * Represents a Java visibility scope. * * @author <a href="mailto:lkuehne@users.sourceforge.net">Lars K�hne</a> */ public final class Scope implements Comparable, Serializable { // Note that although this class might seem to be an // implementation detail, this class has to be public because it // is used as a parameter in Configuration.setJavadocScope() /** poor man's enum for nothing scope */ private static final int SCOPECODE_NOTHING = 0; /** poor man's enum for public scope */ private static final int SCOPECODE_PUBLIC = 1; /** poor man's enum for protected scope */ private static final int SCOPECODE_PROTECTED = 2; /** poor man's enum for package scope */ private static final int SCOPECODE_PACKAGE = 3; /** poor man's enum for private scope */ private static final int SCOPECODE_PRIVATE = 4; /** poor man's enum for anonymous inner class scope */ private static final int SCOPECODE_ANONINNER = 5; /** none scopename */ private static final String SCOPENAME_NOTHING = "nothing"; /** public scopename */ private static final String SCOPENAME_PUBLIC = "public"; /** protected scopename */ private static final String SCOPENAME_PROTECTED = "protected"; /** package scopename */ private static final String SCOPENAME_PACKAGE = "package"; /** private scopename */ private static final String SCOPENAME_PRIVATE = "private"; /** anon inner scopename */ private static final String SCOPENAME_ANONINNER = "anoninner"; /** nothing scope */ static final Scope NOTHING = new Scope(SCOPECODE_NOTHING, SCOPENAME_NOTHING); /** public scope */ static final Scope PUBLIC = new Scope(SCOPECODE_PUBLIC, SCOPENAME_PUBLIC); /** protected scope */ static final Scope PROTECTED = new Scope(SCOPECODE_PROTECTED, SCOPENAME_PROTECTED); /** package scope */ static final Scope PACKAGE = new Scope(SCOPECODE_PACKAGE, SCOPENAME_PACKAGE); /** private scope */ static final Scope PRIVATE = new Scope(SCOPECODE_PRIVATE, SCOPENAME_PRIVATE); /** anon inner scope */ static final Scope ANONINNER = new Scope(SCOPECODE_ANONINNER, SCOPENAME_ANONINNER); /** map from scope names to the respective Scope */ private static final Map NAME_TO_SCOPE = new HashMap(); static { NAME_TO_SCOPE.put(SCOPENAME_NOTHING, NOTHING); NAME_TO_SCOPE.put(SCOPENAME_PUBLIC, PUBLIC); NAME_TO_SCOPE.put(SCOPENAME_PROTECTED, PROTECTED); NAME_TO_SCOPE.put(SCOPENAME_PACKAGE, PACKAGE); NAME_TO_SCOPE.put(SCOPENAME_PRIVATE, PRIVATE); NAME_TO_SCOPE.put(SCOPENAME_ANONINNER, ANONINNER); }; /** the SCOPECODE_XYZ value of this scope. */ private final int mCode; /** the name of this scope. */ private final String mName; /** * @see Object */ public String toString() { return "Scope[" + mCode + " (" + mName + ")]"; } /** * @return the name of this scope. */ String getName() { return mName; } /** * @see Comparable */ public int compareTo(Object aObject) { Scope scope = (Scope) aObject; return this.mCode - scope.mCode; } /** * Checks if this scope is a subscope of another scope. * Example: PUBLIC is a subscope of PRIVATE. * * @param aScope a <code>Scope</code> value * @return if <code>this</code> is a subscope of <code>aScope</code>. */ boolean isIn(Scope aScope) { return (compareTo(aScope) <= 0); } /** * Creates a new <code>Scope</code> instance. * * @param aCode one of the SCOPECODE_XYZ values. * @param aName one of the SCOPENAME_XYZ values. */ private Scope(int aCode, String aName) { mCode = aCode; mName = aName; } /** * Scope factory method. * * @param aScopeName scope name, such as "nothing", "public", etc. * @return the <code>Scope</code> associated with <code>aScopeName</code> */ static Scope getInstance(String aScopeName) { // canonicalize argument - String scopeName = aScopeName.toLowerCase(); + final String scopeName = aScopeName.trim().toLowerCase(); final Scope retVal = (Scope) NAME_TO_SCOPE.get(scopeName); if (retVal == null) { throw new IllegalArgumentException(scopeName); } return retVal; } /** * Ensures that we don't get multiple instances of one Scope * during deserialization. See Section 3.6 of the Java Object * Serialization Specification for details. * * @return the serialization replacement object * @throws ObjectStreamException if a deserialization error occurs */ private Object readResolve() throws ObjectStreamException { return getInstance(mName); } }
true
true
static Scope getInstance(String aScopeName) { // canonicalize argument String scopeName = aScopeName.toLowerCase(); final Scope retVal = (Scope) NAME_TO_SCOPE.get(scopeName); if (retVal == null) { throw new IllegalArgumentException(scopeName); } return retVal; }
static Scope getInstance(String aScopeName) { // canonicalize argument final String scopeName = aScopeName.trim().toLowerCase(); final Scope retVal = (Scope) NAME_TO_SCOPE.get(scopeName); if (retVal == null) { throw new IllegalArgumentException(scopeName); } return retVal; }
diff --git a/src/com/trydish/find/FindHome.java b/src/com/trydish/find/FindHome.java index eeabbd3..2219eaa 100644 --- a/src/com/trydish/find/FindHome.java +++ b/src/com/trydish/find/FindHome.java @@ -1,217 +1,218 @@ package com.trydish.find; import java.io.IOException; import java.util.List; import java.util.Locale; import com.trydish.main.R; import android.location.Address; import android.location.Criteria; import android.location.Geocoder; import android.location.Location; import android.location.LocationManager; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.app.Activity; import android.app.Fragment; import android.app.FragmentTransaction; import android.content.Context; import android.content.Intent; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup.LayoutParams; import android.view.WindowManager; import android.widget.AdapterView.OnItemClickListener; import android.view.ViewGroup; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputMethodManager; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.GridView; import android.widget.ImageButton; import android.widget.Spinner; import android.widget.TableLayout; import android.widget.TextView; import android.widget.Toast; import android.view.KeyEvent; public class FindHome extends Fragment implements OnClickListener { //Implements OnClickListener so that we don't have to define onClick methods in the LoginHome //Keep track of what distance user has selected from drop down menu. Saving now b/c likely later passed to other function private String searchDistance = "1 mile"; private static Context context; private View myView; private LocationManager manager; private Location location; private double latitude; private double longitude; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.activity_find_home, container, false); myView = view; context = view.getContext(); //Note we have to call findViewById on the view b/c we are not in an Activity Spinner distanceSpinner = (Spinner) view.findViewById(R.id.distance_spinner); ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(view.getContext(), R.array.distance_array, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); distanceSpinner.setAdapter(adapter); //Create a new OnItemSelectedListener for the Spinner using anonymous class to define necessary methods OnItemSelectedListener listener = new OnItemSelectedListener() { //comment public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { String itemSelected = (String) parent.getItemAtPosition(pos); searchDistance = itemSelected; Log.d("FindHome", searchDistance); //note that when this tab is selected, this method is executed } //comment public void onNothingSelected(AdapterView<?> parent) { } }; //Set the spinners listener distanceSpinner.setOnItemSelectedListener(listener); //Grab the buttons and set their onClickListeners to be this Fragment ImageButton ib = (ImageButton) view.findViewById(R.id.search); Button b = (Button) view.findViewById(R.id.my_location); ib.setOnClickListener(this); b.setOnClickListener(this); GridView gridview = (GridView) view.findViewById(R.id.food_images); + gridview.setPadding(5, 5, 5, 5); gridview.setAdapter(new ImageAdapter(view.getContext())); gridview.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View v, int position, long id) { Fragment view_dish = new ViewDish(); FragmentTransaction trans = getFragmentManager().beginTransaction(); trans.replace(((ViewGroup) myView.getParent()).getId(), view_dish); trans.addToBackStack(null); trans.commit(); } }); //Hide keyboard getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); //define the behavior of the "DONE" key on the keyboard /* EditText et = (EditText) myView.findViewById(R.id.search_box); et.setOnEditorActionListener(new EditText.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_DONE){ //Do your stuff here Log.d("FindHome","DONE pressed"); donePressed(); return true; } else { return false; } } }); */ // manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); setLocation(); return view; } public void setLocation() { String providerName = manager.getBestProvider(new Criteria(), true); location = manager.getLastKnownLocation(providerName); Button location_button = (Button) myView.findViewById(R.id.my_location); location_button.setText("My Location"); if (location == null) { location_button.setText("GPS Off"); } else { latitude = location.getLatitude(); longitude = location.getLongitude(); try { ConnectivityManager cm = (ConnectivityManager) this.context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetworkInfo = cm.getActiveNetworkInfo(); boolean isConnected = activeNetworkInfo != null && activeNetworkInfo.isConnected(); if (isConnected) { Geocoder myLocation = new Geocoder(context.getApplicationContext(), Locale.getDefault()); List<Address> myList = myLocation.getFromLocation(latitude, longitude, 1); int address_lines = myList.get(0).getMaxAddressLineIndex(); if (address_lines >= 1) { String address = myList.get(0).getAddressLine(address_lines - 1); String city = address.split(",", 2)[0]; location_button.setText(city); } } } catch (Exception e) { e.printStackTrace(); } } } //Called when search icon is clicked public void searchClicked(View v) { //EditText et = (EditText) myView.findViewById(R.id.search_box); //et.setLayoutParams(new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1f)); //hideSoftKeyboard(myView); Log.d("Find Home", "search clicked"); InputMethodManager imm = (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE); EditText et = (EditText) myView.findViewById(R.id.search_box); imm.hideSoftInputFromWindow(et.getWindowToken(), 0); } //Called when the My Location button is clicked to change location public void myLocationClicked(View v) { Log.d("Find Home", "location clicked"); } //Decides which method to call based on which button is clicked. Again, this is needed because by default buttons //onClickListener is not the Fragment @Override public void onClick(View arg0) { switch(arg0.getId()) { //search button clicked case R.id.search: searchClicked(arg0); break; //my location button clicked case R.id.my_location: myLocationClicked(arg0); break; } } public void donePressed() { searchClicked(myView); } } diff --git a/src/com/trydish/find/ImageAdapter.java b/src/com/trydish/find/ImageAdapter.java index bafe2c1..f86bfdf 100644 --- a/src/com/trydish/find/ImageAdapter.java +++ b/src/com/trydish/find/ImageAdapter.java @@ -1,64 +1,61 @@ package com.trydish.find; import com.trydish.main.R; import com.trydish.main.R.drawable; import android.content.Context; import android.graphics.Matrix; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.GridView; import android.widget.ImageView; public class ImageAdapter extends BaseAdapter { private Context mContext; public ImageAdapter(Context c) { mContext = c; } public int getCount() { return mThumbIds.length; } public Object getItem(int position) { return null; } public long getItemId(int position) { return 0; } // create a new ImageView for each item referenced by the Adapter public View getView(int position, View convertView, ViewGroup parent) { ImageView imageView; if (convertView == null) { // if it's not recycled, initialize some attributes imageView = new ImageView(mContext); imageView.setLayoutParams(new GridView.LayoutParams(400, 400)); // 255, 200 - imageView.setMaxHeight(300); - imageView.setMaxWidth(300); - imageView.setScaleType(ImageView.ScaleType.FIT_CENTER); - imageView.setPadding(0, 0, 0, 0); + imageView.setScaleType(ImageView.ScaleType.FIT_XY); } else { imageView = (ImageView) convertView; } imageView.setImageResource(mThumbIds[position]); return imageView; } // references to our images private Integer[] mThumbIds = { R.drawable.food, R.drawable.wings, R.drawable.dimsum, R.drawable.burger, - R.drawable.food1, R.drawable.food, R.drawable.wings, - R.drawable.dimsum, R.drawable.burger, - R.drawable.food1, R.drawable.food, R.drawable.wings, - R.drawable.dimsum, R.drawable.burger, - R.drawable.food1, R.drawable.food, R.drawable.wings, - R.drawable.dimsum, R.drawable.burger, - R.drawable.food1, R.drawable.food, R.drawable.wings, - R.drawable.dimsum, R.drawable.burger, - R.drawable.food1 +// R.drawable.food1, R.drawable.food, R.drawable.wings, +// R.drawable.dimsum, R.drawable.burger, +// R.drawable.food1, R.drawable.food, R.drawable.wings, +// R.drawable.dimsum, R.drawable.burger, +// R.drawable.food1, R.drawable.food, R.drawable.wings, +// R.drawable.dimsum, R.drawable.burger, +// R.drawable.food1, R.drawable.food, R.drawable.wings, +// R.drawable.dimsum, R.drawable.burger, +// R.drawable.food1 }; } \ No newline at end of file
false
false
null
null
diff --git a/src/com/wimbli/TexturePackMenu/Config.java b/src/com/wimbli/TexturePackMenu/Config.java index 135167c..9542618 100644 --- a/src/com/wimbli/TexturePackMenu/Config.java +++ b/src/com/wimbli/TexturePackMenu/Config.java @@ -1,247 +1,247 @@ package com.wimbli.TexturePackMenu; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.util.LinkedHashMap; import java.util.HashMap; import java.util.Map; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.reader.UnicodeReader; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import org.bukkit.Material; import org.getspout.spoutapi.player.SpoutPlayer; import org.getspout.spoutapi.SpoutManager; -import org.getspout.spoutapi.io.CRCStore; +import org.getspout.commons.io.CRCStore; public class Config { // private stuff used within this class private static TexturePackMenu plugin; private static Yaml yaml; private static File configFile; private static File playerFile; private static Map<String, String> texturePacks = new LinkedHashMap<String, String>(); // (Pack Name, URL) private static Map<String, String> playerPacks = new HashMap<String, String>(); // (Player Name, Pack Name) private static byte[] crcBuffer = new byte[16384]; // load config public static void load(TexturePackMenu master) { plugin = master; configFile = new File(plugin.getDataFolder(), "config.yml"); playerFile = new File(plugin.getDataFolder(), "players.yml"); // make our yml output more easily human readable, instead of compact and ugly DumperOptions options = new DumperOptions(); options.setPrettyFlow(true); options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); options.setDefaultScalarStyle(DumperOptions.ScalarStyle.DOUBLE_QUOTED); yaml = new Yaml(options); loadTexturePackList(); loadPlayerPacks(); } public static String[] texPackNames() { return texturePacks.keySet().toArray(new String[0]); } public static String[] texPackURLs() { return texturePacks.values().toArray(new String[0]); } public static int texturePackCount() { return texturePacks.size(); } public static String getPack(String playerName) { if (!playerPacks.containsKey(playerName.toLowerCase())) return ""; return playerPacks.get(playerName.toLowerCase()); } public static void setPack(SpoutPlayer sPlayer, String packName) { if (!texturePacks.containsKey(packName)) { setPack(sPlayer, 0); if (sPlayer.hasPermission("texturepackmenu.texture")) sPlayer.sendNotification("Texture packs available", "Use command: "+ChatColor.AQUA+"/texture", Material.PAPER, (short)0, 10000); } else setPlayerTexturePack(sPlayer, packName); } public static void setPack(SpoutPlayer sPlayer, int index) { if (texturePacks.size() < index - 1) index = 0; setPlayerTexturePack(sPlayer, texPackNames()[index]); } public static void setPackDelayed(final SpoutPlayer sPlayer, final int index) { plugin.getServer().getScheduler().scheduleAsyncDelayedTask(plugin, new Runnable() { @Override public void run() { setPack(sPlayer, index); } }, 10); } private static void setPlayerTexturePack(SpoutPlayer sPlayer, String packName) { if (sPlayer == null || !sPlayer.isOnline()) return; String packURL = texturePacks.get(packName); sPlayer.sendNotification("Texture pack selected:", packName, Material.PAINTING); storePlayerTexturePack(sPlayer.getName(), packName); if (packURL == null || packURL.isEmpty()) sPlayer.resetTexturePack(); else { sPlayer.setTexturePack(packURL); // make sure it checks out as valid, by getting CRC value for it Long crc = null; crc = CRCStore.getCRC(packURL, crcBuffer); if (crc == null || crc == 0) plugin.logWarn("Bad CRC value for texture pack. It is probably an invalid URL: "+packURL); } } public static void storePlayerTexturePack(String playerName, String packName) { playerPacks.put(playerName.toLowerCase(), packName); } public static void resetPlayerTexturePack(String playerName) { playerPacks.remove(playerName.toLowerCase()); Player player = plugin.getServer().getPlayer(playerName); if (player != null) { SpoutPlayer sPlayer = SpoutManager.getPlayer(player); if (sPlayer != null && sPlayer.isSpoutCraftEnabled()) setPack(sPlayer, 0); } } public static void loadTexturePackList() { try { FileInputStream in = new FileInputStream(configFile); texturePacks = (Map<String, String>)yaml.load(new UnicodeReader(in)); } catch (FileNotFoundException e) { } if (texturePacks == null || texturePacks.isEmpty()) useDefaults(); } // load player data private static void loadPlayerPacks() { if (!playerFile.getParentFile().exists() || !playerFile.exists()) return; try { FileInputStream in = new FileInputStream(playerFile); playerPacks = (Map<String, String>)yaml.load(new UnicodeReader(in)); } catch (FileNotFoundException e) { } } // save player data public static void savePlayerPacks() { if (!playerFile.getParentFile().exists()) return; try { BufferedWriter out = new BufferedWriter(new FileWriter(playerFile, false)); out.write(yaml.dump(playerPacks)); out.close(); } catch (IOException e) { plugin.logWarn("ERROR SAVING PLAYER DATA: " + e.getLocalizedMessage()); } } // set default values, and save new config file private static void useDefaults() { plugin.logConfig("Configuration not present, creating new default config.yml file. YOU WILL NEED TO EDIT IT MANUALLY."); texturePacks = new LinkedHashMap<String, String>(); texturePacks.put("Player Choice", ""); texturePacks.put("Minecraft Default", "https://github.com/Brettflan/TexturePackMenu/raw/master/packs/default.zip"); texturePacks.put("Default Pack Copy", "https://github.com/Brettflan/TexturePackMenu/raw/master/packs/default.zip"); if (!configFile.getParentFile().exists()) { if (!configFile.getParentFile().mkdirs()) { plugin.logWarn("FAILED TO CREATE PLUGIN FOLDER."); return; } } String newLine = System.getProperty("line.separator"); try { BufferedWriter out = new BufferedWriter(new FileWriter(configFile, false)); out.write("# Below is a default config which you will need to update to contain your own texture pack choices. You will need to restart your server after making changes." + newLine); out.write("# Each entry consists of the displayed name of the texture pack, followed by the download URL that will be used. There is no limit to the number of entries." + newLine); out.write("# Texture pack names must be limited to 26 characters long at most. Longer ones will cause errors." + newLine); out.write("# The first entry will always be the default, which players new to the server will be set to." + newLine); out.write("# Be sure to test each one you add to make sure it works. An invalid URL will cause an error, and an URL which fails will make that entry do nothing." + newLine); out.write("# If a texture pack fails to load properly, try changing the URL filename. In particular, try replacing spaces (\" \") and other special characters with underscores (\"_\")." + newLine); out.write("# If you do want to allow players to use their own texture pack, you can leave a blank URL as seen below for \"Player Choice\"." + newLine); out.write("# Note that if you want to use quotation marks (\") in texture pack names, you will need to add them with a backslash like so to prevent parsing errors: \\\"" + newLine); out.write("# example: \"The \\\"Silly\\\" Pack\": \"http://fake-server.net/sillypack.zip\"" + newLine); out.write("# would display as: The \"Silly\" Pack" + newLine); out.write("#" + newLine); out.write("# For more information, head here: http://dev.bukkit.org/server-mods/texturepackmenu/" + newLine); out.write(newLine); out.write(yaml.dump(texturePacks)); out.close(); } catch (IOException e) { plugin.logWarn("ERROR SAVING DEFAULT CONFIG: " + e.getLocalizedMessage()); } } } diff --git a/src/com/wimbli/TexturePackMenu/TPMPopup.java b/src/com/wimbli/TexturePackMenu/TPMPopup.java index ab163cb..5369c3a 100644 --- a/src/com/wimbli/TexturePackMenu/TPMPopup.java +++ b/src/com/wimbli/TexturePackMenu/TPMPopup.java @@ -1,247 +1,250 @@ package com.wimbli.TexturePackMenu; import java.util.ArrayList; import org.bukkit.entity.Player; import org.bukkit.ChatColor; import org.getspout.spoutapi.event.screen.ButtonClickEvent; import org.getspout.spoutapi.gui.Color; import org.getspout.spoutapi.gui.GenericButton; import org.getspout.spoutapi.gui.GenericPopup; import org.getspout.spoutapi.gui.GenericLabel; import org.getspout.spoutapi.player.SpoutPlayer; import org.getspout.spoutapi.SpoutManager; // SCREEN SIZE NOTE: scaled screen size seems to always be precisely 427x240... not sure why 427 width, but there you have it public class TPMPopup extends GenericPopup { private TexturePackMenu tmpPlugin; private SpoutPlayer sPlayer; private GenericButton bNext, bPrev; private ArrayList<GenericButton> bChoice = new ArrayList<GenericButton>(10); private String[] packNames = new String[0]; private int page = 0, maxPage = 0; public static void create(TexturePackMenu plugin, Player player) { if (!player.hasPermission("texturepackmenu.texture")) { player.sendMessage("You do not have the necessary permission to choose a texture pack."); return; } TPMPopup newPopup = new TPMPopup(plugin, player); newPopup.initiate(); } public TPMPopup(TexturePackMenu mainPlugin, Player player) { if (player == null) return; sPlayer = SpoutManager.getPlayer(player); if (sPlayer == null) return; this.tmpPlugin = mainPlugin; if (Config.texturePackCount() == 0) { player.sendMessage("Sorry, but no texture packs are currently configured."); return; } if (!sPlayer.isSpoutCraftEnabled()) { player.sendMessage("This only works with the Spoutcraft client. See here:"); player.sendMessage(" "+ChatColor.BLUE+"http://bit.ly/spoutclient"); return; } packNames = Config.texPackNames(); maxPage = (int)Math.ceil((double)packNames.length / 10.0) - 1; } public void initiate() { this.initLabels(); this.initOtherButtons(); this.initChoiceButtons(); this.refreshButtons(); sPlayer.getMainScreen().attachPopupScreen(this); // Show the player the popup } public void exit() { sPlayer.getMainScreen().closePopup(); } private void makeChoice(int buttonIndex) { Config.setPackDelayed(sPlayer, (page * 10) + buttonIndex); exit(); } private void refreshButtons() { bPrev.setEnabled(page > 0); bNext.setEnabled(page < maxPage); bPrev.setDirty(true); bNext.setDirty(true); int loop, offset = page * 10; for (loop = 0; loop < 10; loop++) { int index = offset + loop; if (index > packNames.length - 1) break; String text = packNames[index]; GenericButton btn = bChoice.get(loop); btn.setTextColor(new Color(255,255,255,0)); if (index == 0) { // default pack text = "* " + text; btn.setTextColor(new Color(127,255,255,0)); } if (Config.getPack(sPlayer.getName()).equals(packNames[index])) { // current pack text = "@ " + text; btn.setTextColor(new Color(191,255,191,0)); } btn.setText(text); btn.setVisible(true); btn.setDirty(true); } while (loop < 10) { bChoice.get(loop).setVisible(false); bChoice.get(loop).setDirty(true); loop++; } } private void nextPage() { if (page < maxPage) page += 1; refreshButtons(); } private void lastPage() { if (page > 0) page -= 1; refreshButtons(); } private void initLabels() { GenericLabel label = new GenericLabel("Choose a texture pack below:"); + label.setWidth(1).setHeight(1); // prevent Spout's questionable "no default size" warning; how a variable width/height text widget benefits from a width and height being set is beyond me label.setTextColor(new Color(63,255,63,0)); label.setScale(2.0f); label.setX(64).setY(20); this.attachWidget(tmpPlugin, label); label = new GenericLabel("* - Default Pack"); + label.setWidth(1).setHeight(1); // prevent Spout's questionable "no default size" warning label.setX(207).setY(191); label.setTextColor(new Color(127,255,255,0)); this.attachWidget(tmpPlugin, label); label = new GenericLabel("@ - Current Pack"); + label.setWidth(1).setHeight(1); // prevent Spout's questionable "no default size" warning label.setX(204).setY(201); label.setTextColor(new Color(191,255,191,0)); this.attachWidget(tmpPlugin, label); } private void initOtherButtons() { GenericButton cancel = new GenericButton("Cancel") { @Override public void onButtonClick(ButtonClickEvent event) { exit(); } }; cancel.setWidth(95).setHeight(20); cancel.setX(311).setY(190); cancel.setTextColor(new Color(255,191,191,0)); this.attachWidget(tmpPlugin, cancel); bPrev = new GenericButton("< Prev Page") { @Override public void onButtonClick(ButtonClickEvent event) { lastPage(); } }; bPrev.setWidth(80).setHeight(20); bPrev.setX(21).setY(190); if (maxPage == 0) bPrev.setVisible(false); this.attachWidget(tmpPlugin, bPrev); bNext = new GenericButton("Next Page >") { @Override public void onButtonClick(ButtonClickEvent event) { nextPage(); } }; bNext.setWidth(80).setHeight(20); bNext.setX(105).setY(190); if (maxPage == 0) bNext.setVisible(false); this.attachWidget(tmpPlugin, bNext); } private void initChoiceButtons() { bChoice = new ArrayList<GenericButton>(10); boolean rowToggle = true; GenericButton current; final int bWidth = 190, bHeight = 20, offsetLeft1 = 21, offsetLeft2 = 216; int offsetTop = 50; for (int i = 0; i < 10; i++) { final int idx = i; current = new GenericButton(Integer.toString(i+1)) { int index = idx; @Override public void onButtonClick(ButtonClickEvent event) { makeChoice(index); } }; current.setWidth(bWidth).setHeight(bHeight); current.setX(rowToggle ? offsetLeft1 : offsetLeft2).setY(offsetTop); bChoice.add(current); this.attachWidget(tmpPlugin, current); rowToggle ^= true; if (rowToggle) offsetTop += 25; } } }
false
false
null
null
diff --git a/src/test/org/apache/hadoop/dfs/TestDFSShellGenericOptions.java b/src/test/org/apache/hadoop/dfs/TestDFSShellGenericOptions.java index 99c833c26..89d7c4622 100644 --- a/src/test/org/apache/hadoop/dfs/TestDFSShellGenericOptions.java +++ b/src/test/org/apache/hadoop/dfs/TestDFSShellGenericOptions.java @@ -1,105 +1,105 @@ package org.apache.hadoop.dfs; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintWriter; import junit.framework.TestCase; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.dfs.DFSShell; import org.apache.hadoop.dfs.DataNode; import org.apache.hadoop.dfs.MiniDFSCluster; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; public class TestDFSShellGenericOptions extends TestCase { public void testDFSCommand() throws IOException { String namenode = null; MiniDFSCluster cluster = null; try { Configuration conf = new Configuration(); cluster = new MiniDFSCluster(65316, conf, true); namenode = conf.get("fs.default.name", "local"); String [] args = new String[4]; args[2] = "-mkdir"; args[3] = "/data"; testFsOption(args, namenode); testConfOption(args, namenode); testPropertyOption(args, namenode); } finally { if (cluster != null) { cluster.shutdown(); } } } private void testFsOption(String [] args, String namenode) { // prepare arguments to create a directory /data args[0] = "-fs"; args[1] = namenode; execute(args, namenode); } private void testConfOption(String[] args, String namenode) { // prepare configuration hadoop-site.xml - File configDir = new File("conf", "minidfs"); + File configDir = new File(new File("build", "test"), "minidfs"); configDir.mkdirs(); File siteFile = new File(configDir, "hadoop-site.xml"); PrintWriter pw; try { pw = new PrintWriter(siteFile); pw.print("<?xml version=\"1.0\"?>\n"+ "<?xml-stylesheet type=\"text/xsl\" href=\"configuration.xsl\"?>\n"+ "<configuration>\n"+ " <property>\n"+ " <name>fs.default.name</name>\n"+ " <value>"+namenode+"</value>\n"+ " </property>\n"+ "</configuration>\n"); pw.close(); // prepare arguments to create a directory /data args[0] = "-conf"; - args[1] = "conf/minidfs/hadoop-site.xml"; + args[1] = siteFile.getPath(); execute(args, namenode); } catch (FileNotFoundException e) { - // TODO Auto-generated catch block e.printStackTrace(); + } finally { + siteFile.delete(); + configDir.delete(); } - - configDir.delete(); } private void testPropertyOption(String[] args, String namenode) { // prepare arguments to create a directory /data args[0] = "-D"; args[1] = "fs.default.name="+namenode; execute(args, namenode); } private void execute( String [] args, String namenode ) { DFSShell shell=new DFSShell(); FileSystem fs=null; try { shell.doMain(new Configuration(), args); fs = new DistributedFileSystem( DataNode.createSocketAddr(namenode), shell.getConf()); assertTrue( "Directory does not get created", fs.isDirectory(new Path("/data")) ); fs.delete(new Path("/data")); } catch (Exception e) { System.err.println(e.getMessage()); e.printStackTrace(); } finally { if( fs!=null ) { try { fs.close(); } catch (IOException ignored) { } } } } }
false
false
null
null
diff --git a/plugins/org.teiid.designer.spi/src/org/teiid/designer/query/sql/ISQLConstants.java b/plugins/org.teiid.designer.spi/src/org/teiid/designer/query/sql/ISQLConstants.java index 9afcc90d5..492dea06a 100644 --- a/plugins/org.teiid.designer.spi/src/org/teiid/designer/query/sql/ISQLConstants.java +++ b/plugins/org.teiid.designer.spi/src/org/teiid/designer/query/sql/ISQLConstants.java @@ -1,103 +1,101 @@ /* * JBoss, Home of Professional Open Source. * * See the LEGAL.txt file distributed with this work for information regarding copyright ownership and licensing. * * See the AUTHORS.txt file distributed with this work for a full listing of individual contributors. */ package org.teiid.designer.query.sql; /** * SqlConstants * * @since 8.0 */ public interface ISQLConstants { String EMPTY_STR = ""; //$NON-NLS-1$ String TAB = "\t"; //$NON-NLS-1$ String TAB2 = "\t\t"; //$NON-NLS-1$ String TAB3 = "\t\t\t"; //$NON-NLS-1$ String TAB4 = "\t\t\t\t"; //$NON-NLS-1$ String CR = "\n"; //$NON-NLS-1$ String CR_1 = "\\r\\n"; //$NON-NLS-1$ String CR_2 = "\\n"; //$NON-NLS-1$ String BLANK = ""; //$NON-NLS-1$ String DBL_SPACE = " "; //$NON-NLS-1$ String SPACE = " "; //$NON-NLS-1$ String COMMA = ","; //$NON-NLS-1$ String TRUE = "TRUE"; //$NON-NLS-1$ String FALSE = "FALSE"; //$NON-NLS-1$ String RETURN = "\n"; //$NON-NLS-1$ String SELECT = "SELECT"; //$NON-NLS-1$ String FROM = "FROM"; //$NON-NLS-1$ String WHERE = "WHERE"; //$NON-NLS-1$ String HAVING = "HAVING"; //$NON-NLS-1$ String DOT = "."; //$NON-NLS-1$ String STAR = "*"; //$NON-NLS-1$ String L_PAREN = "("; //$NON-NLS-1$ String R_PAREN = ")"; //$NON-NLS-1$ String S_QUOTE = "\'"; //$NON-NLS-1$ String D_QUOTE = "\""; //$NON-NLS-1$ String SEMI_COLON = ";"; //$NON-NLS-1$ String COLON = ":"; //$NON-NLS-1$ String BAR = "|"; //$NON-NLS-1$ String AS = "AS"; //$NON-NLS-1$ String COLUMNS = "COLUMNS"; //$NON-NLS-1$ String BEGIN = "BEGIN"; //$NON-NLS-1$ String END = "END"; //$NON-NLS-1$ String XMLELEMENT = "XMLELEMENT"; //$NON-NLS-1$ String XMLATTRIBUTES = "XMLATTRIBUTES"; //$NON-NLS-1$ String NAME = "NAME"; //$NON-NLS-1$ String XMLNAMESPACES = "XMLNAMESPACES"; //$NON-NLS-1$ String DEFAULT = "DEFAULT"; //$NON-NLS-1$ String NO_DEFAULT = "NO DEFAULT"; //$NON-NLS-1$ String XMLTABLE = "XMLTABLE"; //$NON-NLS-1$ String TEXTTABLE = "TEXTTABLE"; //$NON-NLS-1$ String TABLE = "TABLE"; //$NON-NLS-1$ String EXEC = "EXEC"; //$NON-NLS-1$ String CONVERT = "CONVERT"; //$NON-NLS-1$ + String NULL = "NULL"; //$NON-NLS-1$ String ENVELOPE_NS = "http://schemas.xmlsoap.org/soap/envelope/"; //$NON-NLS-1$ String ENVELOPE_NS_ALIAS = "soap"; //$NON-NLS-1$ String ENVELOPE_NAME = ENVELOPE_NS_ALIAS+":Envelope"; //$NON-NLS-1$ String HEADER_NAME = ENVELOPE_NS_ALIAS+":Header"; //$NON-NLS-1$ String BODY_NAME = ENVELOPE_NS_ALIAS+":Body"; //$NON-NLS-1$ String PATH = "PATH"; //$NON-NLS-1$ String FOR_ORDINALITY = "FOR ORDINALITY"; //$NON-NLS-1$ String DEFAULT_XQUERY = "/"; //$NON-NLS-1$ String GET = "GET"; //$NON-NLS-1$ String PASSING = "PASSING"; //$NON-NLS-1$ String SQL_TYPE_CREATE_STRING = "CREATE"; //$NON-NLS-1$ String SQL_TYPE_SELECT_STRING = "SELECT"; //$NON-NLS-1$ String SQL_TYPE_UPDATE_STRING = "UPDATE"; //$NON-NLS-1$ String SQL_TYPE_INSERT_STRING = "INSERT"; //$NON-NLS-1$ String SQL_TYPE_DELETE_STRING = "DELETE"; //$NON-NLS-1$ String SQL_TYPE_UNKNOWN_STRING = "UNKNOWN"; //$NON-NLS-1$ String FUNCTION_GET_FILES = "getFiles"; //$NON-NLS-1$ String FUNCTION_GET_TEXT_FILES = "getTextFiles"; //$NON-NLS-1$ String FUNCTION_SAVE_FILE = "saveFile"; //$NON-NLS-1$ String FUNCTION_INVOKE = "invoke"; //$NON-NLS-1$ String FUNCTION_INVOKE_HTTP = "invokeHttp"; //$NON-NLS-1$ String ROWCOUNT = "ROWCOUNT"; //$NON-NLS-1 String CHANGING = "CHANGING"; //$NON-NLS-1$ String VARIABLES = "VARIABLES"; //$NON-NLS-1$ String DVARS = "DVARS"; //$NON-NLS-1$ String DEFAULT_DELIMITER = ","; String DEFAULT_QUOTE = "'"; String DEFAULT_ESCAPE = "\\"; String HEADER = "HEADER"; //$NON-NLS-1$ String SKIP = "SKIP"; //$NON-NLS-1$ String WIDTH = "width"; //$NON-NLS-1$ - - String NULL = "null"; //$NON-NLS-1$ - - + } diff --git a/plugins/org.teiid.designer.spi/src/org/teiid/designer/query/sql/ISQLStringVisitor.java b/plugins/org.teiid.designer.spi/src/org/teiid/designer/query/sql/ISQLStringVisitor.java index 0cd23c26b..a7ff6084b 100644 --- a/plugins/org.teiid.designer.spi/src/org/teiid/designer/query/sql/ISQLStringVisitor.java +++ b/plugins/org.teiid.designer.spi/src/org/teiid/designer/query/sql/ISQLStringVisitor.java @@ -1,31 +1,31 @@ /* * JBoss, Home of Professional Open Source. * * See the LEGAL.txt file distributed with this work for information regarding copyright ownership and licensing. * * See the AUTHORS.txt file distributed with this work for a full listing of individual contributors. */ package org.teiid.designer.query.sql; import org.teiid.designer.query.sql.lang.ILanguageObject; /** * */ -public interface ISQLStringVisitor<LO extends ILanguageObject> extends ILanguageVisitor, ISQLConstants { +public interface ISQLStringVisitor<LO extends ILanguageObject> extends ILanguageVisitor { /** * Should the visitor fail to evaluate then this * text is returned */ public static final String UNDEFINED = "<undefined>"; //$NON-NLS-1$ /** * Find the string representation of the given object * * @param languageObject * * @return SQL string */ String returnSQLString(LO languageObject); }
false
false
null
null
diff --git a/opentripplanner-routing/src/main/java/org/opentripplanner/routing/impl/raptor/Raptor.java b/opentripplanner-routing/src/main/java/org/opentripplanner/routing/impl/raptor/Raptor.java index 772ac7b50..e36889cbc 100644 --- a/opentripplanner-routing/src/main/java/org/opentripplanner/routing/impl/raptor/Raptor.java +++ b/opentripplanner-routing/src/main/java/org/opentripplanner/routing/impl/raptor/Raptor.java @@ -1,747 +1,752 @@ /* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.opentripplanner.routing.impl.raptor; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.ListIterator; import javax.annotation.PostConstruct; import org.onebusaway.gtfs.model.AgencyAndId; import org.onebusaway.gtfs.model.Stop; import org.opentripplanner.common.geometry.DistanceLibrary; import org.opentripplanner.common.geometry.SphericalDistanceLibrary; import org.opentripplanner.routing.core.RoutingRequest; import org.opentripplanner.routing.core.ServiceDay; import org.opentripplanner.routing.core.State; import org.opentripplanner.routing.core.TraverseModeSet; import org.opentripplanner.routing.edgetype.PatternDwell; import org.opentripplanner.routing.edgetype.PatternHop; import org.opentripplanner.routing.edgetype.PatternInterlineDwell; import org.opentripplanner.routing.edgetype.PreAlightEdge; import org.opentripplanner.routing.edgetype.PreBoardEdge; import org.opentripplanner.routing.edgetype.TransitBoardAlight; import org.opentripplanner.routing.graph.Edge; import org.opentripplanner.routing.graph.Graph; import org.opentripplanner.routing.graph.Vertex; import org.opentripplanner.routing.impl.RetryingPathServiceImpl; import org.opentripplanner.routing.pathparser.BasicPathParser; import org.opentripplanner.routing.pathparser.NoThruTrafficPathParser; import org.opentripplanner.routing.pathparser.PathParser; import org.opentripplanner.routing.services.GraphService; import org.opentripplanner.routing.services.PathService; import org.opentripplanner.routing.services.SPTService; import org.opentripplanner.routing.spt.GraphPath; import org.opentripplanner.routing.vertextype.TransitStop; import org.opentripplanner.routing.vertextype.TransitVertex; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; public class Raptor implements PathService { private static final Logger log = LoggerFactory.getLogger(Raptor.class); static final double MAX_TRANSIT_SPEED = 25; private static final int MAX_WALK_MULTIPLE = 8; public static final double WALK_EPSILON = 1.10; @Autowired private GraphService graphService; private List<ServiceDay> cachedServiceDays; private RaptorData cachedRaptorData; private double multiPathTimeout = 0; // seconds /** * This is used for short paths (under shortPathCutoff). */ RetryingPathServiceImpl shortPathService = new RetryingPathServiceImpl(); /** * The max length, in meters, that will use the shortPathService. */ private double shortPathCutoff = 10000; @PostConstruct public void setup() { shortPathService.setGraphService(graphService); shortPathService.setSptService(sptService); } /** * Stop searching for additional itineraries (beyond the first one) after this many seconds * have elapsed, relative to the beginning of the search for the first itinerary. * A negative or zero value means search forever. */ public void setMultiPathTimeout (double seconds) { multiPathTimeout = seconds; } //fallback for nontransit trips @Autowired public SPTService sptService; private DistanceLibrary distanceLibrary = SphericalDistanceLibrary.getInstance(); @Override public List<GraphPath> getPaths(RoutingRequest options) { final Graph graph = graphService.getGraph(options.getRouterId()); if (options.rctx == null) { options.setRoutingContext(graph); options.rctx.pathParsers = new PathParser[] { new BasicPathParser(), new NoThruTrafficPathParser() }; } if (!options.getModes().isTransit()) { return sptService.getShortestPathTree(options).getPaths(); } //also fall back to A* for short trips double distance = distanceLibrary.distance(options.rctx.origin.getCoordinate(), options.rctx.target.getCoordinate()); if (distance < shortPathCutoff) { log.debug("Falling back to A* for very short path"); return shortPathService.getPaths(options); } RaptorDataService service = graph.getService(RaptorDataService.class); if (service == null) { log.warn("No raptor data. Rebuild with RaptorDataBuilder"); return Collections.emptyList(); } RaptorData data = service.getData(); //we multiply the initial walk distance to account for epsilon dominance. double initialWalk = options.getMaxWalkDistance() * WALK_EPSILON; options.setMaxWalkDistance(initialWalk); //do not even bother with obviously impossible walks double minWalk = options.rctx.origin.getDistanceToNearestTransitStop() + options.rctx.target.getDistanceToNearestTransitStop(); if (options.getMaxWalkDistance() < minWalk) { options.setMaxWalkDistance(minWalk); } RoutingRequest walkOptions = options.clone(); walkOptions.rctx.pathParsers = new PathParser[0]; TraverseModeSet modes = options.getModes().clone(); modes.setTransit(false); walkOptions.setModes(modes); RaptorSearch search = new RaptorSearch(data, options); if (data.maxTransitRegions != null) { Calendar tripDate = Calendar.getInstance(graph.getTimeZone()); tripDate.setTime(new Date(1000L * options.dateTime)); Calendar maxTransitStart = Calendar.getInstance(graph.getTimeZone()); maxTransitStart.set(Calendar.YEAR, data.maxTransitRegions.startYear); maxTransitStart.set(Calendar.MONTH, data.maxTransitRegions.startMonth); maxTransitStart.set(Calendar.DAY_OF_MONTH, data.maxTransitRegions.startDay); int day = 0; while (tripDate.after(maxTransitStart)) { day++; tripDate.add(Calendar.DAY_OF_MONTH, -1); } if (day > data.maxTransitRegions.maxTransit.length || options.isWheelchairAccessible()) { day = -1; } search.maxTimeDayIndex = day; } int rushAheadRound = preliminaryRaptorSearch(data, options, walkOptions, search); long searchBeginTime = System.currentTimeMillis(); double expectedWorstTime = 1.5 * distanceLibrary.distance(options.rctx.origin.getCoordinate(), options.rctx.target.getCoordinate()) / options.getWalkSpeed(); int foundSoFar = 0; double firstWalkDistance = 0; List<RaptorState> targetStates = new ArrayList<RaptorState>(); do { int bestElapsedTime = Integer.MAX_VALUE; RETRY: do { for (int round = 0; round < options.getMaxTransfers() + 2; ++round) { if (!round(data, options, walkOptions, search, round)) break; long elapsed = System.currentTimeMillis() - searchBeginTime; if (elapsed > multiPathTimeout * 1000 && multiPathTimeout > 0 && targetStates.size() > 0) break RETRY; ArrayList<RaptorState> toRemove = new ArrayList<RaptorState>(); for (RaptorState state : search.getTargetStates()) { if (state.nBoardings == 0 && options.getMaxWalkDistance() > initialWalk) { toRemove.add(state); } } if (search.getTargetStates().size() > 0) { if (firstWalkDistance == 0) { firstWalkDistance = options.getMaxWalkDistance(); } for (RaptorState state : toRemove) { search.removeTargetState(state.walkPath); } } if (targetStates.size() >= options.getNumItineraries() && round >= rushAheadRound) { int oldBest = bestElapsedTime; for (RaptorState state : search.getTargetStates()) { final int elapsedTime = (int) Math.abs(state.arrivalTime - options.dateTime); if (elapsedTime < bestElapsedTime) { bestElapsedTime = elapsedTime; } } int improvement = oldBest - bestElapsedTime; if (improvement < 600 && bestElapsedTime < expectedWorstTime) break RETRY; } } if (foundSoFar < search.getTargetStates().size()) { foundSoFar = search.getTargetStates().size(); } else if (foundSoFar > 0) { // we didn't find anything new in this round, and we already have // some paths, so bail out break; } options = options.clone(); walkOptions = walkOptions.clone(); if (search.getTargetStates().size() > 0 && bestElapsedTime < expectedWorstTime) { // we have found some paths so we no longer want to expand the max walk distance break RETRY; } else { options.setMaxWalkDistance(options.getMaxWalkDistance() * 2); walkOptions.setMaxWalkDistance(options.getMaxWalkDistance()); options.setWalkReluctance(options.getWalkReluctance() * 2); walkOptions.setWalkReluctance(options.getWalkReluctance()); } search.reset(options); } while (options.getMaxWalkDistance() < initialWalk * MAX_WALK_MULTIPLE && initialWalk < Double.MAX_VALUE); options = options.clone(); walkOptions = walkOptions.clone(); for (RaptorState state : search.getTargetStates()) { for (AgencyAndId trip : state.getTrips()) { options.banTrip(trip); } } if (search.getTargetStates().size() == 0) break; // no paths found; searching more won't help options.setMaxWalkDistance(firstWalkDistance); walkOptions.setMaxWalkDistance(firstWalkDistance); targetStates.addAll(search.getTargetStates()); search = new RaptorSearch(data, options); } while (targetStates.size() < options.getNumItineraries()); collectRoutesUsed(data, options, targetStates); if (targetStates.isEmpty()) { log.info("RAPTOR found no paths"); } Collections.sort(targetStates); if (targetStates.size() > options.getNumItineraries()) targetStates = targetStates.subList(0, options.getNumItineraries()); List<GraphPath> paths = new ArrayList<GraphPath>(); for (RaptorState targetState : targetStates) { // reconstruct path ArrayList<RaptorState> states = new ArrayList<RaptorState>(); RaptorState cur = targetState; while (cur != null) { states.add(cur); cur = cur.getParent(); } // states is in reverse order of time State state = getState(targetState.getRequest(), data, states); paths.add(new GraphPath(state, true)); } return paths; } private void collectRoutesUsed(RaptorData data, RoutingRequest options, List<RaptorState> targetStates) { // find start/end regions List<Integer> startRegions = getRegionsForVertex(data.regionData, options.rctx.fromVertex); int startRegion; if (startRegions.size() == 1) { startRegion = startRegions.get(0); } else { // on boundary return; } List<Integer> endRegions = getRegionsForVertex(data.regionData, options.rctx.toVertex); int endRegion; if (endRegions.size() == 1) { endRegion = endRegions.get(0); } else { // on boundary return; } HashSet<RaptorRoute> routes = data.regionData.routes[startRegion][endRegion]; HashSet<RaptorStop> stops = data.regionData.stops[startRegion][endRegion]; TARGETSTATE: for (RaptorState state : targetStates) { for (RaptorState dom : targetStates) { if (dom.nBoardings <= state.nBoardings && dom.arrivalTime < state.arrivalTime) { continue TARGETSTATE; } } synchronized(data) { while (state != null) { if (state.route != null) routes.add(state.route); if (state.stop != null) { stops.add(state.stop); } state = state.getParent(); } } } } /** * This does preliminary search over just routes and stops that have been used in the * past between these regions. */ private int preliminaryRaptorSearch(RaptorData data, RoutingRequest options, RoutingRequest walkOptions, RaptorSearch search) { //find start/end regions List<Integer> startRegions = getRegionsForVertex(data.regionData, options.rctx.fromVertex); int startRegion; //for trips that span regions, we can safely pick either region startRegion = startRegions.get(0); List<Integer> endRegions = getRegionsForVertex(data.regionData, options.rctx.toVertex); int endRegion; endRegion = endRegions.get(0); // create a reduced set of RaptorData with only the stops/routes previously seen on trips // from the start region to the end region RaptorData trimmedData = new RaptorData(); trimmedData.raptorStopsForStopId = new HashMap<AgencyAndId, RaptorStop>(); HashSet<RaptorStop> stops = data.regionData.stops[startRegion][endRegion]; for (RaptorStop stop : stops) { trimmedData.raptorStopsForStopId.put(stop.stopVertex.getStopId(), stop); } trimmedData.regionData = data.regionData; trimmedData.routes = data.regionData.routes[startRegion][endRegion]; trimmedData.stops = data.stops; //trimmedData.allowedStops = stops; trimmedData.routesForStop = data.routesForStop; double walkDistance = options.getMaxWalkDistance(); options = options.clone(); walkOptions = walkOptions.clone(); if (walkDistance > 4000) { // this is a really long walk. We'll almost never actually need this. So let's do our // preliminary search over just 4km first. options.setMaxWalkDistance(4000); walkOptions.setMaxWalkDistance(4000); } int round; if (trimmedData.routes.size() > 0) { log.debug("Doing preliminary search on limited route set (" + trimmedData.routes.size() + ", " + stops.size() + ")"); round = doPreliminarySearch(options, walkOptions, search, trimmedData); } else { round = 0; } if (search.getTargetStates().size() == 0 && walkDistance > 5000) { // nothing found in preliminary search // so we'll do a search with full set of routes & stops, but still limited distance log.debug("Doing preliminary search at limited distance"); round = doPreliminarySearch(options, walkOptions, search, data); } return round; } private int doPreliminarySearch(RoutingRequest options, RoutingRequest walkOptions, RaptorSearch search, RaptorData trimmedData) { RaptorSearch rushSearch = new RaptorSearch(trimmedData, options); int bestElapsedTime = Integer.MAX_VALUE; int round; for (round = 0; round < options.getMaxTransfers() + 2; round++) { if (!round(trimmedData, options, walkOptions, rushSearch, round)) break; if (rushSearch.getTargetStates().size() > 0) { int oldBest = bestElapsedTime; for (RaptorState state : rushSearch.getTargetStates()) { final int elapsedTime = (int) Math .abs(state.arrivalTime - options.dateTime); if (elapsedTime < bestElapsedTime) { bestElapsedTime = elapsedTime; } } int improvement = oldBest - bestElapsedTime; if (improvement < 600) break; } } for (RaptorState state : rushSearch.getTargetStates()) { search.bounder.addBounder(state.walkPath); search.addTargetState(state); } return round; } /** * Some vertices aren't associated with a region, because they're synthetic, or * maybe for some other region. So instead, we check their connected vertices, * recursively, to try to find their region. * * @param regionData * @param vertex * @return */ static List<Integer> getRegionsForVertex(RegionData regionData, Vertex vertex) { return new ArrayList<Integer>(getRegionsForVertex(regionData, vertex, new HashSet<Vertex>(), 0)); } /** * Internals of getRegionsForVertex; keeps track of seen vertices to avoid loops. * @param regionData * @param vertex * @param seen * @param depth * @return */ private static HashSet<Integer> getRegionsForVertex(RegionData regionData, Vertex vertex, HashSet<Vertex> seen, int depth) { seen.add(vertex); HashSet<Integer> regions = new HashSet<Integer>(); int region = vertex.getGroupIndex(); if (region >= 0) { regions.add(region); } else { for (Edge e: vertex.getOutgoing()) { final Vertex tov = e.getToVertex(); if (!seen.contains(tov)) regions.addAll(getRegionsForVertex(regionData, tov, seen, depth + 1)); } for (Edge e: vertex.getIncoming()) { final Vertex fromv = e.getFromVertex(); if (!seen.contains(fromv)) regions.addAll(getRegionsForVertex(regionData, fromv, seen, depth + 1)); } } return regions; } private State getState(RoutingRequest options, RaptorData data, ArrayList<RaptorState> states) { if (options.arriveBy) { return getStateArriveBy(data, states); } else { return getStateDepartAt(data, states); } } private State getStateDepartAt(RaptorData data, ArrayList<RaptorState> states) { State state = new State(states.get(0).getRequest()); for (int i = states.size() - 1; i >= 0; --i) { RaptorState cur = states.get(i); if (cur.walkPath != null) { //a walking step GraphPath path = new GraphPath(cur.walkPath, false); Edge edge0 = path.edges.getFirst(); if (edge0.getFromVertex() != state.getVertex()) { state = state.getBackState(); } for (Edge e : path.edges) { state = e.traverse(state); } } else { // so, cur is at this point at a transit stop; we have a route to board if (cur.getParent() == null || ! cur.getParent().interlining) { for (Edge e : state.getVertex().getOutgoing()) { if (e instanceof PreAlightEdge) { state = e.traverse(state); break; } } for (Edge e : state.getVertex().getOutgoing()) { if (e instanceof PreBoardEdge) { state = e.traverse(state); break; } } TransitBoardAlight board = cur.getRoute().boards[cur.boardStopSequence][cur.patternIndex]; state = board.traverse(state); } // now traverse the hops and dwells until we find the alight we're looking for HOP: while (true) { for (Edge e : state.getVertex().getOutgoing()) { if (e instanceof PatternDwell) { state = e.traverse(state); } else if (e instanceof PatternHop) { state = e.traverse(state); if (cur.interlining) { for (Edge e2 : state.getVertex().getOutgoing()) { RaptorState next = states.get(i - 1); if (e2 instanceof PatternInterlineDwell) { Stop toStop = ((TransitVertex) e2.getToVertex()).getStop(); Stop expectedStop = next.boardStop.stopVertex.getStop(); if (toStop.equals(expectedStop)) { State newState = e2.traverse(state); if (newState == null) continue; if (newState.getTripId() != next.tripId) continue; state = newState; break HOP; } } } } else { for (Edge e2 : state.getVertex().getOutgoing()) { if (e2 instanceof TransitBoardAlight) { for (Edge e3 : e2.getToVertex().getOutgoing()) { if (e3 instanceof PreAlightEdge) { if (data.raptorStopsForStopId.get(((TransitStop) e3 .getToVertex()).getStopId()) == cur.stop) { state = e2.traverse(state); state = e3.traverse(state); break HOP; } } } } } } } } } } } return state; } private State getStateArriveBy(RaptorData data, ArrayList<RaptorState> states) { RoutingRequest options = states.get(0).getRequest(); State state = new State(options.rctx.origin, options); for (int i = states.size() - 1; i >= 0; --i) { RaptorState cur = states.get(i); if (cur.walkPath != null) { GraphPath path = new GraphPath(cur.walkPath, false); + Edge edge0 = path.edges.getLast(); + if (edge0.getToVertex() != state.getVertex()) { + state = state.getBackState(); + } + for (ListIterator<Edge> it = path.edges.listIterator(path.edges.size()); it.hasPrevious();) { Edge e = it.previous(); state = e.traverse(state); } } else { // so, cur is at this point at a transit stop departure; we have a route to alight from if (cur.getParent() == null || ! cur.getParent().interlining) { for (Edge e : state.getVertex().getIncoming()) { if (e instanceof PreAlightEdge) { state = e.traverse(state); } } TransitBoardAlight alight = cur.getRoute().alights[cur.boardStopSequence - 1][cur.patternIndex]; state = alight.traverse(state); } // now traverse the hops and dwells until we find the board we're looking for HOP: while (true) { for (Edge e : state.getVertex().getIncoming()) { if (e instanceof PatternDwell) { state = e.traverse(state); } else if (e instanceof PatternHop) { state = e.traverse(state); if (cur.interlining) { for (Edge e2 : state.getVertex().getIncoming()) { RaptorState next = states.get(i - 1); if (e2 instanceof PatternInterlineDwell) { Stop fromStop = ((TransitVertex) e2.getFromVertex()).getStop(); Stop expectedStop = next.boardStop.stopVertex.getStop(); if (fromStop.equals(expectedStop)) { State newState = e2.traverse(state); if (newState == null) continue; if (newState.getTripId() != next.tripId) continue; state = newState; break HOP; } } } } else { for (Edge e2 : state.getVertex().getIncoming()) { if (e2 instanceof TransitBoardAlight) { for (Edge e3 : e2.getFromVertex().getIncoming()) { if (e3 instanceof PreBoardEdge) { if (data.raptorStopsForStopId.get(((TransitStop) e3 .getFromVertex()).getStopId()) == cur.stop) { state = e2.traverse(state); state = e3.traverse(state); break HOP; } } } } } } } } } } } return state; } /** * Prune raptor data to include only routes and boardings which have trips today. Doesn't * actually improve speed */ @SuppressWarnings("unchecked") private RaptorData pruneDataForServiceDays(Graph graph, ArrayList<ServiceDay> serviceDays) { if (serviceDays.equals(cachedServiceDays)) return cachedRaptorData; RaptorData data = graph.getService(RaptorDataService.class).getData(); RaptorData pruned = new RaptorData(); pruned.raptorStopsForStopId = data.raptorStopsForStopId; pruned.stops = data.stops; pruned.routes = new ArrayList<RaptorRoute>(); pruned.routesForStop = new List[pruned.stops.length]; for (RaptorRoute route : data.routes) { ArrayList<Integer> keep = new ArrayList<Integer>(); for (int i = 0; i < route.boards[0].length; ++i) { Edge board = route.boards[0][i]; int serviceId; if (board instanceof TransitBoardAlight) { serviceId = ((TransitBoardAlight) board).getPattern().getServiceId(); } else { log.debug("Unexpected nonboard among boards"); continue; } for (ServiceDay day : serviceDays) { if (day.serviceIdRunning(serviceId)) { keep.add(i); break; } } } if (keep.isEmpty()) continue; int nPatterns = keep.size(); RaptorRoute prunedRoute = new RaptorRoute(route.getNStops(), nPatterns); for (int stop = 0; stop < route.getNStops() - 1; ++stop) { for (int pattern = 0; pattern < nPatterns; ++pattern) { prunedRoute.boards[stop][pattern] = route.boards[stop][keep.get(pattern)]; } } pruned.routes.add(route); for (RaptorStop stop : route.stops) { List<RaptorRoute> routes = pruned.routesForStop[stop.index]; if (routes == null) { routes = new ArrayList<RaptorRoute>(); pruned.routesForStop[stop.index] = routes; } routes.add(route); } } for (RaptorStop stop : data.stops) { if (pruned.routesForStop[stop.index] == null) { pruned.routesForStop[stop.index] = Collections.emptyList(); } } cachedServiceDays = serviceDays; cachedRaptorData = pruned; return pruned; } private boolean round(RaptorData data, RoutingRequest options, RoutingRequest walkOptions, final RaptorSearch search, int nBoardings) { log.debug("Round " + nBoardings); /* Phase 2: handle transit */ List<RaptorState> createdStates = search.transitPhase(options, nBoardings); /* Phase 3: handle walking paths */ return search.walkPhase(options, walkOptions, nBoardings, createdStates); } public RaptorStateSet getStateSet(RoutingRequest options) { final Graph graph; if (options.rctx == null) { graph = graphService.getGraph(options.getRouterId()); options.setRoutingContext(graph); options.rctx.pathParsers = new PathParser[] { new BasicPathParser(), new NoThruTrafficPathParser() }; } else { graph = options.rctx.graph; } RaptorData data = graph.getService(RaptorDataService.class).getData(); //we multiply the initial walk distance to account for epsilon dominance. options.setMaxWalkDistance(options.getMaxWalkDistance() * WALK_EPSILON); RoutingRequest walkOptions = options.clone(); walkOptions.rctx.pathParsers = new PathParser[0]; TraverseModeSet modes = options.getModes().clone(); modes.setTransit(false); walkOptions.setModes(modes); RaptorSearch search = new RaptorSearch(data, options); for (int i = 0; i < options.getMaxTransfers() + 2; ++i) { if (!round(data, options, walkOptions, search, i)) break; } RaptorStateSet result = new RaptorStateSet(); result.statesByStop = search.statesByStop; return result; } public double getShortPathCutoff() { return shortPathCutoff; } public void setShortPathCutoff(double shortPathCutoff) { this.shortPathCutoff = shortPathCutoff; } }
true
false
null
null
diff --git a/src/InventoryFrame.java b/src/InventoryFrame.java index 88a256c..ba9816d 100644 --- a/src/InventoryFrame.java +++ b/src/InventoryFrame.java @@ -1,152 +1,153 @@ import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Vector; import javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.ListSelectionModel; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; public class InventoryFrame extends JFrame { private Player thePlayer; private JButton use; private JButton drop; private JButton back; private JList inventory; private JTextArea descriptionArea; private DefaultListModel inventoryList; private JScrollPane scroll; private JPanel buttons; private JPanel itemPanel; private JLabel message; private Vector<Integer> usableItems; // Let Bryant decide what is usable public InventoryFrame(Player player) { super("Inventory"); thePlayer = player; use = new JButton("Use"); drop = new JButton("Drop"); back = new JButton("Back"); buttons = new JPanel(); ButtonListener handler = new ButtonListener(); use.addActionListener(handler); drop.addActionListener(handler); back.addActionListener(handler); buttons.add(use); buttons.add(drop); buttons.add(back); itemPanel = new JPanel(); descriptionArea = new JTextArea(); descriptionArea.setPreferredSize(new Dimension(200, 200)); + descriptionArea.setWrapStyleWord(true); descriptionArea.setLineWrap(true); descriptionArea.setEditable(false); usableItems = new Vector<Integer>(); fillUsuable(); message = new JLabel(); makeInventory(); inventory = new JList(inventoryList); inventory.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); inventory.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent arg0) { descriptionArea.setText(((Item) inventory.getSelectedValue()) .getDescription()); } }); scroll = new JScrollPane(inventory); scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); itemPanel.add(scroll); itemPanel.add(descriptionArea); this.setLayout(new BorderLayout()); this.add(itemPanel, BorderLayout.CENTER); this.add(buttons, BorderLayout.SOUTH); this.add(message, BorderLayout.NORTH); } /** * Use this method to fill the array of Items that can be used. If the name of * the item is not added to this array it won't be able to be used.!!!! Use * the number that is assigned to each Item * */ private void fillUsuable() { usableItems.add(4); usableItems.add(32); usableItems.add(31); usableItems.add(30); } private void makeInventory() { inventoryList = new DefaultListModel(); Vector<Item> v = thePlayer.getInventory(); for (Item item : v) { inventoryList.addElement(item); } } private class ButtonListener implements ActionListener { @Override public void actionPerformed(ActionEvent event) { Item item = (Item) inventory.getSelectedValue(); int itemNumber = item.getIDNumber(); if (event.getSource().equals(use)) { if (usableItems.contains(itemNumber)) { thePlayer.use(item); message.setText("Fuel increased to: " + thePlayer.getFuelLevel()); } else { message.setText("You can't use this item"); } } else if (event.getSource().equals(drop)) { thePlayer.drop(item); } repaint(); //not working I think it has something to do with the list selection listener. } } }
true
true
public InventoryFrame(Player player) { super("Inventory"); thePlayer = player; use = new JButton("Use"); drop = new JButton("Drop"); back = new JButton("Back"); buttons = new JPanel(); ButtonListener handler = new ButtonListener(); use.addActionListener(handler); drop.addActionListener(handler); back.addActionListener(handler); buttons.add(use); buttons.add(drop); buttons.add(back); itemPanel = new JPanel(); descriptionArea = new JTextArea(); descriptionArea.setPreferredSize(new Dimension(200, 200)); descriptionArea.setLineWrap(true); descriptionArea.setEditable(false); usableItems = new Vector<Integer>(); fillUsuable(); message = new JLabel(); makeInventory(); inventory = new JList(inventoryList); inventory.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); inventory.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent arg0) { descriptionArea.setText(((Item) inventory.getSelectedValue()) .getDescription()); } }); scroll = new JScrollPane(inventory); scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); itemPanel.add(scroll); itemPanel.add(descriptionArea); this.setLayout(new BorderLayout()); this.add(itemPanel, BorderLayout.CENTER); this.add(buttons, BorderLayout.SOUTH); this.add(message, BorderLayout.NORTH); }
public InventoryFrame(Player player) { super("Inventory"); thePlayer = player; use = new JButton("Use"); drop = new JButton("Drop"); back = new JButton("Back"); buttons = new JPanel(); ButtonListener handler = new ButtonListener(); use.addActionListener(handler); drop.addActionListener(handler); back.addActionListener(handler); buttons.add(use); buttons.add(drop); buttons.add(back); itemPanel = new JPanel(); descriptionArea = new JTextArea(); descriptionArea.setPreferredSize(new Dimension(200, 200)); descriptionArea.setWrapStyleWord(true); descriptionArea.setLineWrap(true); descriptionArea.setEditable(false); usableItems = new Vector<Integer>(); fillUsuable(); message = new JLabel(); makeInventory(); inventory = new JList(inventoryList); inventory.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); inventory.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent arg0) { descriptionArea.setText(((Item) inventory.getSelectedValue()) .getDescription()); } }); scroll = new JScrollPane(inventory); scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); itemPanel.add(scroll); itemPanel.add(descriptionArea); this.setLayout(new BorderLayout()); this.add(itemPanel, BorderLayout.CENTER); this.add(buttons, BorderLayout.SOUTH); this.add(message, BorderLayout.NORTH); }
diff --git a/src/edu/mit/mitmobile2/facilities/FacilitiesLeasedBuildingActivity.java b/src/edu/mit/mitmobile2/facilities/FacilitiesLeasedBuildingActivity.java index 93cd0937..b97f51dc 100644 --- a/src/edu/mit/mitmobile2/facilities/FacilitiesLeasedBuildingActivity.java +++ b/src/edu/mit/mitmobile2/facilities/FacilitiesLeasedBuildingActivity.java @@ -1,107 +1,102 @@ package edu.mit.mitmobile2.facilities; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; import edu.mit.mitmobile2.CommonActions; import edu.mit.mitmobile2.DividerView; import edu.mit.mitmobile2.Global; import edu.mit.mitmobile2.Module; import edu.mit.mitmobile2.ModuleActivity; import edu.mit.mitmobile2.R; import edu.mit.mitmobile2.TwoLineActionRow; import edu.mit.mitmobile2.objs.FacilitiesItem.LocationRecord; public class FacilitiesLeasedBuildingActivity extends ModuleActivity { private final static String CONTACT_EMAIL_KEY = "contact_email"; private final static String CONTACT_NAME_KEY = "contact_name"; private final static String CONTACT_PHONE_KEY = "contact_phone"; private String mEmail; private String mName; private String mPhone; private Context mContext; public static void launch(Context context, LocationRecord location) { Intent intent = new Intent(context, FacilitiesLeasedBuildingActivity.class); intent.putExtra(CONTACT_EMAIL_KEY, location.contact_email_bldg_services); intent.putExtra(CONTACT_NAME_KEY, location.contact_name_bldg_services); intent.putExtra(CONTACT_PHONE_KEY, location.contact_phone_bldg_services); context.startActivity(intent); } @Override protected void onCreate(Bundle bundle) { super.onCreate(bundle); mContext = this; mEmail = getIntent().getStringExtra(CONTACT_EMAIL_KEY); mName = getIntent().getStringExtra(CONTACT_NAME_KEY); mPhone = getIntent().getStringExtra(CONTACT_PHONE_KEY); setContentView(R.layout.facilities_leased_building); String message = "The Department of Facilities is not responsible for the maintenance of"; message += " " + Global.sharedData.getFacilitiesData().getBuildingNumber(); message += " - " + Global.sharedData.getFacilitiesData().getLocationName() + ". "; message += "Please contact " + mName + " to report any issues."; TextView maintainerMessageTV = (TextView) findViewById(R.id.facilitiesLeasedTV); maintainerMessageTV.setText(message); - LinearLayout mainLinearLayout = (LinearLayout) findViewById(R.id.facilitiesLeasedMainLinearLayout); if(mEmail.length() > 0) { - TwoLineActionRow emailActionRow = new TwoLineActionRow(this); - emailActionRow.setBackgroundColor(getResources().getColor(R.color.rowBackground)); + View emailActionContainer = findViewById(R.id.facilitiesLeasedEmailContainer); + emailActionContainer.setVisibility(View.VISIBLE); + TwoLineActionRow emailActionRow = (TwoLineActionRow) findViewById(R.id.facilitiesLeasedEmailActionRow); emailActionRow.setActionIconResource(R.drawable.action_email); emailActionRow.setTitle("Email (" + mEmail + ")"); emailActionRow.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { CommonActions.composeEmail(mContext, mEmail); } }); - mainLinearLayout.addView(new DividerView(this, null)); - mainLinearLayout.addView(emailActionRow); } if(mPhone.length() > 0) { - TwoLineActionRow phoneActionRow = new TwoLineActionRow(this); - phoneActionRow.setBackgroundColor(getResources().getColor(R.color.rowBackground)); + View phoneActionContainer = findViewById(R.id.facilitiesLeasedPhoneContainer); + phoneActionContainer.setVisibility(View.VISIBLE); + TwoLineActionRow phoneActionRow = (TwoLineActionRow) findViewById(R.id.facilitiesLeasedPhoneActionRow); phoneActionRow.setActionIconResource(R.drawable.action_phone); - phoneActionRow.setTitle("Call (" + mPhone + ")"); + String dotDelimitedNumber = mPhone.substring(0, 3) + "." + mPhone.substring(3, 6) + "." + mPhone.substring(6); + phoneActionRow.setTitle("Call (" + dotDelimitedNumber + ")"); phoneActionRow.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { CommonActions.callPhone(mContext, mPhone); } }); - - mainLinearLayout.addView(new DividerView(this, null)); - mainLinearLayout.addView(phoneActionRow); } - - } @Override protected Module getModule() { return new FacilitiesModule(); } @Override public boolean isModuleHomeActivity() { return false; } @Override protected void prepareActivityOptionsMenu(Menu menu) { } }
false
false
null
null
diff --git a/pmd/test-data/IfStmtsMustUseBraces2.java b/pmd/test-data/IfStmtsMustUseBraces2.java index 804889874..a33a43b65 100644 --- a/pmd/test-data/IfStmtsMustUseBraces2.java +++ b/pmd/test-data/IfStmtsMustUseBraces2.java @@ -1,7 +1,7 @@ -public class IfStmtsMustUseBraces3 { +public class IfStmtsMustUseBraces2 { public void foo() { if (true) { int x=2; } } -} \ No newline at end of file +}
false
false
null
null
diff --git a/src/dudes/Player.java b/src/dudes/Player.java index 2ed4a68..8288c01 100644 --- a/src/dudes/Player.java +++ b/src/dudes/Player.java @@ -1,156 +1,156 @@ package dudes; import java.util.HashMap; import org.newdawn.slick.Animation; import org.newdawn.slick.Color; import org.newdawn.slick.Graphics; import org.newdawn.slick.Input; import org.newdawn.slick.SlickException; import org.newdawn.slick.SpriteSheet; import org.newdawn.slick.geom.Rectangle; import core.MainGame; import weapons.Fist; public class Player extends Dude { public HashMap<String, Integer> buttons; public int playerID; public int score; public Player(HashMap<String, Integer> buttons, float xPos, float yPos) { this.buttons = buttons; this.isRight = true; pos[0] = xPos; pos[1] = yPos; moveSpeed = 3; maxHealth = 100; health = maxHealth; score = 0; healthFill = new Color(0f, 1f, 0f, 1f); attackTime = 0; - hitbox = new Rectangle(pos[0], pos[1], weapon.playerSize, weapon.playerSize); this.weapon = new Fist(this); + hitbox = new Rectangle(pos[0], pos[1], weapon.playerSize, weapon.playerSize); } public void init(int playerID) throws SlickException { this.playerID = playerID; this.sprites = new SpriteSheet("Assets/players/player"+playerID+"Death.png",64,64); // create spritesheets for the weapon: this.weapon.init(); } public void move(Input input, int delta) { if (currentAnimation != null) { if (currentAnimation.isStopped()) { currentAnimation.restart(); currentAnimation = null; } } if (flinching) { flinchTime += delta; if (flinchTime < flinchDur) { return; } else { flinching = false; } } if (isAttacking) { attackTime += delta; if (attackTime < this.weapon.attackTime) { return; } else { isAttacking = false; delayed = true; delayTime = 0; } } float moveDist = (float) .1 * delta * moveSpeed; for (String key : buttons.keySet()) { // TODO: fix diagonally } if (input.isKeyPressed(buttons.get("action"))) { this.isAttacking = true; currentAnimation = handleAnimation("punch"); currentAnimation.start(); attackTime = 0; this.weapon.attack(); return; } else if (input.isKeyDown(buttons.get("right")) || input.isKeyDown(buttons.get("left")) || input.isKeyDown(buttons.get("down")) || input.isKeyDown(buttons.get("up"))) { currentAnimation = handleAnimation("walk"); currentAnimation.start(); if (input.isKeyDown(buttons.get("right"))) this.moveRight(moveDist); if (input.isKeyDown(buttons.get("left"))) this.moveLeft(moveDist); if (input.isKeyDown(buttons.get("down"))) this.moveDown(moveDist); if (input.isKeyDown(buttons.get("up"))) this.moveUp(moveDist); } else { if (currentAnimation != null) { currentAnimation.stop(); } } } @Override public Animation handleAnimation(String whichAnim) { if (isRight) { if (whichAnim.equals("flinch")) { return weapon.anims[1]; } else if (whichAnim.equals("punch")) { return weapon.anims[3]; } else { // else, the walk animation for now return weapon.anims[5]; } } else { if (whichAnim.equals("flinch")) { return weapon.anims[0]; } else if (whichAnim.equals("punch")) { return weapon.anims[2]; } else { // else, the walk animation for now return weapon.anims[4]; } } } public void pickup() { // tries to pick up what might be nearby. } public void incrementScore(int points) { this.score += points; } @Override public void renderHealthBar(Graphics g) { float x = 25 + (MainGame.GAME_WIDTH - 200) * playerID; float y = 75; int width = 150; int height = 10; int padding = 2; int healthRemaining = width * health / maxHealth; g.drawRect(x - padding, y - padding, width + padding * 2, height + padding * 2); g.setColor(healthFill); g.fillRect(x, y, healthRemaining, height); } @Override public float[] weaponLoc() { if (this.isRight) { return new float[] { pos[0] + 64 + 4, pos[1] + 40 }; } else { return new float[] { pos[0] - 4, pos[1] + 40 }; } } } \ No newline at end of file diff --git a/src/weapons/Fist.java b/src/weapons/Fist.java index 1944e3e..1d45795 100644 --- a/src/weapons/Fist.java +++ b/src/weapons/Fist.java @@ -1,63 +1,63 @@ package weapons; import org.newdawn.slick.SlickException; import org.newdawn.slick.SpriteSheet; import org.newdawn.slick.geom.Rectangle; import dudes.Dude; import dudes.Player; public class Fist extends Weapon { public Fist(Dude owner) { this(owner.pos[0], owner.pos[1]); assignOwner(owner); } public Fist(float x, float y) { super(); damage = 5; attackWidth = 30; attackHeight = 6; attackTime = 200; delayTime = 500; - playerSize = 16; + playerSize = 64; } @Override public void init() throws SlickException { super.init(); weaponSheet = new SpriteSheet("Assets/Weapons/Fist/player" + ((Player)owner).playerID + "Fist.png", playerSize, playerSize); playerSheet = ((Player)owner).sprites; defaultSprite[0] = weaponSheet.getSprite(0, 5); defaultSprite[1] = weaponSheet.getSprite(0, 4); initAnimations(); } @Override public void attack() { float[] corner = owner.weaponLoc(); //corner[0] -= attackWidth / 2; //corner[1] -= attackHeight / 2; Rectangle hitbox; if (owner.isRight){ hitbox = new Rectangle(corner[0], corner[1], attackWidth, attackHeight); } else { hitbox = new Rectangle(corner[0]-attackWidth, corner[1], attackWidth, attackHeight); } attacks.add(new Attack(owner.isRight, hitbox, "player")); } @Override protected boolean updateAttack(Attack attack) { if(owner.isAttacking) { return true; } else{ return false; } } }
false
false
null
null
diff --git a/src/org/opensaml/xml/encryption/Decrypter.java b/src/org/opensaml/xml/encryption/Decrypter.java index 5b58398..c0e3ce4 100644 --- a/src/org/opensaml/xml/encryption/Decrypter.java +++ b/src/org/opensaml/xml/encryption/Decrypter.java @@ -1,454 +1,462 @@ /* * Copyright [2006] [University Corporation for Advanced Internet Development, Inc.] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.opensaml.xml.encryption; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.security.Key; import java.security.KeyException; +import java.util.HashMap; import java.util.List; import javolution.util.FastList; import org.apache.log4j.Logger; import org.apache.xml.security.encryption.XMLCipher; import org.apache.xml.security.encryption.XMLEncryptionException; import org.opensaml.xml.Configuration; import org.opensaml.xml.XMLObject; import org.opensaml.xml.io.Marshaller; import org.opensaml.xml.io.MarshallingException; import org.opensaml.xml.io.UnmarshallerFactory; import org.opensaml.xml.io.UnmarshallingException; import org.opensaml.xml.parse.ParserPool; import org.opensaml.xml.parse.XMLParserException; import org.opensaml.xml.security.KeyInfoResolver; import org.w3c.dom.Document; import org.w3c.dom.DocumentFragment; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * Decrypts XMLObject and their keys. */ public class Decrypter { /** ParserPool used in parsing decrypted data. */ private final ParserPool parserPool; /** Unmarshaller factory, used in decryption of EncryptedData objects. */ private UnmarshallerFactory unmarshallerFactory; /** Load-and-Save DOM Implementation singleton. */ //private DOMImplementationLS domImplLS; /** Class logger. */ private Logger log = Logger.getLogger(Decrypter.class); /** Resolver for data encryption keys. */ private KeyInfoResolver resolver; /** Resolver for key encryption keys. */ private KeyInfoResolver kekResolver; /** * Constructor. * * @param newKEKResolver resolver for key encryption keys. * @param newResolver resolver for data encryption keys. */ public Decrypter(KeyInfoResolver newKEKResolver, KeyInfoResolver newResolver) { kekResolver = newKEKResolver; resolver = newResolver; + parserPool = new ParserPool(); + parserPool.setNamespaceAware(true); + + HashMap<String, Boolean> features = new HashMap<String, Boolean>(); + features.put("http://apache.org/xml/features/dom/defer-node-expansion", Boolean.FALSE); + parserPool.setFeatures(features); + unmarshallerFactory = Configuration.getUnmarshallerFactory(); } public Decrypter(KeyInfoResolver newKEKResolver, KeyInfoResolver newResolver, ParserPool pool){ kekResolver = newKEKResolver; resolver = newResolver; parserPool = pool; } /** * Set a new key encryption key resolver. * * @param newKEKResolver the new key encryption key resolver */ public void setKEKREsolver(KeyInfoResolver newKEKResolver) { this.kekResolver = newKEKResolver; } /** * Set a new data encryption key resolver. * * @param newResolver the new data encryption key resolver */ public void setKeyResolver(KeyInfoResolver newResolver) { this.resolver = newResolver; } /** * Decrypts the supplied EncryptedData and returns the resulting XMLObject. * * This will only succeed if the decrypted EncryptedData contains exactly one * DOM node of type Element. * * @param encryptedData encrypted data element containing the data to be decrypted * @return the decrypted XMLObject * @throws DecryptionException exception indicating a decryption error, possibly because * the decrypted data contained more than one top-level Element, or some * non-Element Node type. */ public XMLObject decryptData(EncryptedData encryptedData) throws DecryptionException { List<XMLObject> xmlObjects = decryptDataToList(encryptedData); if (xmlObjects.size() != 1) { throw new DecryptionException("The decrypted data contained more than one XMLObject child"); } return xmlObjects.get(0); } /** * Decrypts the supplied EncryptedData and returns the resulting list of XMLObjects. * * This will only succeed if the decrypted EncryptedData contains at the top-level * only DOM Elements (not other types of DOM Nodes). * * @param encryptedData encrypted data element containing the data to be decrypted * @return the list decrypted top-level XMLObjects * @throws DecryptionException exception indicating a decryption error, possibly because * the decrypted data contained DOM nodes other than type of Element */ public List<XMLObject> decryptDataToList(EncryptedData encryptedData) throws DecryptionException { List<XMLObject> xmlObjects = new FastList<XMLObject>(); DocumentFragment docFragment = decryptDataToDOM(encryptedData); XMLObject xmlObject; Node node; Element element; NodeList children = docFragment.getChildNodes(); for (int i=0; i<children.getLength(); i++) { node = children.item(i); if (node.getNodeType() != Node.ELEMENT_NODE) { throw new DecryptionException("Top-level node was not of type Element: " + node.getNodeType()); } else { element = (Element) node; } try { xmlObject = unmarshallerFactory.getUnmarshaller(element).unmarshall(element); } catch (UnmarshallingException e) { throw new DecryptionException("Unmarshalling error during decryption", e); } xmlObjects.add(xmlObject); } return xmlObjects; } /** * Decrypts the supplied EncryptedData and returns the resulting DOM {@link DocumentFragment}. * * @param encryptedData encrypted data element containing the data to be decrypted * @return the decrypted DOM {@link DocumentFragment} * @throws DecryptionException exception indicating a decryption error */ public DocumentFragment decryptDataToDOM(EncryptedData encryptedData) throws DecryptionException { if (resolver == null && kekResolver == null) { throw new DecryptionException("Unable to decrypt EncryptedData, no key resolvers are set"); } // TODO - Until Xerces supports LSParser.parseWithContext(), or we come up with another solution // to parse a bytestream into a DocumentFragment, we can only support encryption of Elements, // not content. if (encryptedData.getType().equals(EncryptionConstants.TYPE_CONTENT)) { throw new DecryptionException("Decryption of EncryptedData elements of type 'Content' " + "is not currently supported"); } // This is the key that will ultimately be used to decrypt the EncryptedData Key dataEncKey = resolveDataDecryptionKey(encryptedData); if (dataEncKey == null) { throw new DecryptionException("Unable to resolve the data encryption key"); } Element targetElement = encryptedData.getDOM(); if (targetElement == null) { Marshaller marshaller = Configuration.getMarshallerFactory().getMarshaller(EncryptedData.DEFAULT_ELEMENT_NAME); try { targetElement = marshaller.marshall(encryptedData); } catch (MarshallingException e) { throw new DecryptionException("Error marshalling EncryptedData for decryption", e); } } XMLCipher xmlCipher; try { xmlCipher = XMLCipher.getInstance(); xmlCipher.init(XMLCipher.DECRYPT_MODE, dataEncKey); } catch (XMLEncryptionException e) { throw new DecryptionException("Error initialzing cipher instance on data decryption", e); } byte[] bytes = null; try { bytes = xmlCipher.decryptToByteArray(targetElement); } catch (XMLEncryptionException e) { throw new DecryptionException("Error decrypting the encrypted data element", e); } if (bytes == null) { throw new DecryptionException("EncryptedData could not be decrypted"); } ByteArrayInputStream input = new ByteArrayInputStream(bytes); DocumentFragment docFragment = parseInputStream(input, encryptedData.getDOM().getOwnerDocument()); return docFragment; } /** * Decrypts the supplied EncryptedKey and returns the resulting Java security Key object. * The algorithm of the decrypted key must be supplied by the caller based on knowledge of * the associated EncryptedData information. * * @param encryptedKey encrypted key element containing the encrypted key to be decrypted * @param algorithm the algorithm associated with the decrypted key * @return the decrypted key * @throws DecryptionException exception indicating a decryption error */ public Key decryptKey(EncryptedKey encryptedKey, String algorithm) throws DecryptionException { if (kekResolver == null) { throw new DecryptionException("Unable to decrypt EncryptedKey, no key encryption key resolver is set"); } Element targetElement = encryptedKey.getDOM(); if (targetElement == null) { Marshaller marshaller = Configuration.getMarshallerFactory().getMarshaller(EncryptedKey.DEFAULT_ELEMENT_NAME); try { targetElement = marshaller.marshall(encryptedKey); } catch (MarshallingException e) { throw new DecryptionException("Error marshalling EncryptedKey for decryption", e); } } Key kek = null; try { kek = kekResolver.resolveKey(encryptedKey.getKeyInfo()); } catch (KeyException e) { throw new DecryptionException("Error resolving the key encryption key", e); } if (kek == null) { throw new DecryptionException("Failed to resolve key encryption key"); } XMLCipher xmlCipher; try { xmlCipher = XMLCipher.getInstance(); xmlCipher.init(XMLCipher.UNWRAP_MODE, kek); } catch (XMLEncryptionException e) { throw new DecryptionException("Error initialzing cipher instance on key decryption", e); } org.apache.xml.security.encryption.EncryptedKey encKey; try { encKey = xmlCipher.loadEncryptedKey(targetElement.getOwnerDocument(), targetElement); } catch (XMLEncryptionException e) { throw new DecryptionException("Error when loading library native encrypted key representation", e); } Key key = null; try { key = xmlCipher.decryptKey(encKey, algorithm); } catch (XMLEncryptionException e) { throw new DecryptionException("Error decrypting kek encryption key", e); } if (key == null) { throw new DecryptionException("Key could not be decrypted"); } return key; } /** * Resolve the data decryption key for the specified EncryptedData element. * * @param encryptedData the EncryptedData which is to be decrypted * @return the data decryption key * @throws DecryptionException exception indicating a decryption error */ private Key resolveDataDecryptionKey(EncryptedData encryptedData) throws DecryptionException { Key dataEncKey = null; // This logic is pretty much straight from the C++ decrypter... // First try and resolve the data encryption key directly if (resolver != null) { try { dataEncKey = resolver.resolveKey(encryptedData.getKeyInfo()); } catch (KeyException e) { throw new DecryptionException("Error resolving data encryption key", e); } } // If no key was resolved and have a KEK resolver, try to resolve keys from // KeyInfo/EncryptedKey's obtained from directly within this EncryptedData. if (dataEncKey == null && kekResolver != null) { String algorithm = encryptedData.getEncryptionMethod().getAlgorithm(); if (algorithm == null || algorithm.equals("")) { throw new DecryptionException("No EncryptionMethod/@Algorithm set, key decryption cannot proceed."); } if (encryptedData.getKeyInfo() != null) { List<EncryptedKey> encryptedKeys = encryptedData.getKeyInfo().getEncryptedKeys(); for (EncryptedKey encryptedKey: encryptedKeys) { try { dataEncKey = decryptKey(encryptedKey, algorithm); if (dataEncKey != null) { break; } } catch (DecryptionException e) { log.warn(e.getMessage()); } } } // If no key was resolved, and our data encryption key resolver is an EncryptedKey resolver // specialization capable of resolving EncryptedKey's from another context, try that. if (dataEncKey == null && resolver instanceof EncryptedKeyInfoResolver) { EncryptedKeyInfoResolver ekr = (EncryptedKeyInfoResolver) resolver; EncryptedKey encryptedKey = null; try { encryptedKey = ekr.resolveKey(encryptedData); } catch (KeyException e) { throw new DecryptionException("Error in EncryptedKeyInfoResolver", e); } if (encryptedKey != null) { try { dataEncKey = decryptKey(encryptedKey, algorithm); } catch (DecryptionException e) { log.warn(e.getMessage()); } } } } return dataEncKey; } /* NOTE: this currently won't work because Xerces doesn't implement LSParser.parseWithContext(). * Hopefully they will in the future. */ /* private DocumentFragment parseInputStreamLS(InputStream input, Document owningDocument) throws DecryptionException { DOMImplementationLS domImpl = getDOMImplemenationLS(); LSParser parser = domImpl.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null); if (parser == null) { throw new DecryptionException("LSParser was null"); } //DOMConfiguration config=parser.getDomConfig(); //DOMErrorHandlerImpl errorHandler=new DOMErrorHandlerImpl(); //config.setParameter("error-handler", errorHandler); LSInput lsInput = domImpl.createLSInput(); if (lsInput == null) { throw new DecryptionException("LSInput was null"); } lsInput.setByteStream(input); DocumentFragment container = owningDocument.createDocumentFragment(); //TODO Xerces currently doesn't support LSParser.parseWithContext() parser.parseWithContext(lsInput, container, LSParser.ACTION_REPLACE_CHILDREN); return container; } */ /* private DOMImplementationLS getDOMImplemenationLS() throws DecryptionException { if (domImplLS != null) { return domImplLS; } // get an instance of the DOMImplementation registry DOMImplementationRegistry registry; try { registry = DOMImplementationRegistry.newInstance(); } catch (ClassCastException e) { throw new DecryptionException("Error creating new error of DOMImplementationRegistry", e); } catch (ClassNotFoundException e) { throw new DecryptionException("Error creating new error of DOMImplementationRegistry", e); } catch (InstantiationException e) { throw new DecryptionException("Error creating new error of DOMImplementationRegistry", e); } catch (IllegalAccessException e) { throw new DecryptionException("Error creating new error of DOMImplementationRegistry", e); } // get a new instance of the DOM Level 3 Load/Save implementation DOMImplementationLS newDOMImplLS = (DOMImplementationLS) registry.getDOMImplementation("LS 3.0"); if (newDOMImplLS == null) { throw new DecryptionException("No LS DOMImplementation could be found"); } else { domImplLS = newDOMImplLS; } return domImplLS; } */ /** * Parse the specified input stream in a DOM DocumentFragment, owned by the specified * Document. * * @param input the InputStream to parse * @param owningDocument the Document which will own the returned DocumentFragment * @return a DocumentFragment * @throws DecryptionException thrown if there is an error parsing the input stream */ private DocumentFragment parseInputStream(InputStream input, Document owningDocument) throws DecryptionException { // Since Xerces currently seems not to handle parsing into a DocumentFragment // without a bit hackery, use this to simulate, so we can keep the API // the way it hopefully will look in the future. Obviously this only works for // input streams containing valid XML instances, not fragments. Document newDocument = null; try { newDocument = parserPool.parse(input); } catch (XMLParserException e) { throw new DecryptionException("Error parsing decrypted input stream", e); } Element element = newDocument.getDocumentElement(); owningDocument.adoptNode(element); DocumentFragment container = owningDocument.createDocumentFragment(); container.appendChild(element); return container; } } \ No newline at end of file
false
false
null
null
diff --git a/server/src/de/hpi/bpmn2execpn/converter/ExecConverter.java b/server/src/de/hpi/bpmn2execpn/converter/ExecConverter.java index d51c9025..81dd8274 100644 --- a/server/src/de/hpi/bpmn2execpn/converter/ExecConverter.java +++ b/server/src/de/hpi/bpmn2execpn/converter/ExecConverter.java @@ -1,499 +1,497 @@ package de.hpi.bpmn2execpn.converter; import java.util.ArrayList; import java.util.List; import java.io.*; import sun.reflect.generics.reflectiveObjects.NotImplementedException; import de.hpi.bpmn.BPMNDiagram; import de.hpi.bpmn.DataObject; import de.hpi.bpmn.ExecDataObject; import de.hpi.bpmn.Edge; import de.hpi.bpmn.IntermediateEvent; import de.hpi.bpmn.SubProcess; import de.hpi.bpmn.Task; import de.hpi.bpmn2execpn.model.ExecTask; import de.hpi.bpmn2pn.converter.Converter; import de.hpi.bpmn2pn.converter.DataObjectNoInitStateException; import de.hpi.bpmn2pn.model.ConversionContext; import de.hpi.bpmn2pn.model.SubProcessPlaces; import de.hpi.execpn.AutomaticTransition; import de.hpi.execpn.ExecFlowRelationship; import de.hpi.execpn.ExecPetriNet; import de.hpi.execpn.FormTransition; import de.hpi.execpn.impl.ExecPNFactoryImpl; import de.hpi.execpn.pnml.Locator; import de.hpi.petrinet.PetriNet; import de.hpi.petrinet.Place; import de.hpi.petrinet.Transition; import javax.xml.parsers.*; import org.w3c.dom.*; import org.w3c.dom.ls.*; import org.w3c.dom.bootstrap.DOMImplementationRegistry; public class ExecConverter extends Converter { private static final boolean abortWhenFinalize = true; private static final String baseXsltURL = "http://localhost:3000/examples/contextPlace/"; private static final String copyXsltURL = baseXsltURL + "copy_xslt.xsl"; private static final String extractDataURL = baseXsltURL + "extract_processdata.xsl"; protected String standardModel; protected String baseFileName; private List<ExecTask> taskList; public ExecConverter(BPMNDiagram diagram, String modelURL) { super(diagram, new ExecPNFactoryImpl(modelURL)); this.standardModel = modelURL; this.taskList = new ArrayList<ExecTask>(); } public void setBaseFileName(String basefilename) { this.baseFileName = basefilename; } @Override protected void handleDiagram(PetriNet net, ConversionContext c) { ((ExecPetriNet) net).setName(diagram.getTitle()); } @Override protected void createStartPlaces(PetriNet net, ConversionContext c) { // do nothing...: we want start transitions instead of start places } // TODO this is a dirty hack... @Override protected void handleTask(PetriNet net, Task task, ConversionContext c) { ExecTask exTask = new ExecTask(); exTask.setId(task.getId()); exTask.setLabel(task.getLabel()); // create proper model, form and bindings String model = null; String form = null; String bindings = null; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance ( ) ; try { DocumentBuilder parser = factory.newDocumentBuilder ( ) ; Document modelDoc = parser.newDocument(); Element dataEl = modelDoc.createElement("data"); Node data = modelDoc.appendChild(dataEl); Node metaData = data.appendChild(modelDoc.createElement("metadata")); Node processData = data.appendChild(modelDoc.createElement("processdata")); // create MetaData Layout for Task model // (take attention to the fact, that the attributes are again defined in the engine) Node startTime = metaData.appendChild(modelDoc.createElement("startTime")); Node endTime = metaData.appendChild(modelDoc.createElement("endTime")); Node status = metaData.appendChild(modelDoc.createElement("status")); Node owner = metaData.appendChild(modelDoc.createElement("owner")); Node isDelegated = metaData.appendChild(modelDoc.createElement("isDelegated")); Node reviewRequested = metaData.appendChild(modelDoc.createElement("reviewRequested")); Node firstOwner = metaData.appendChild(modelDoc.createElement("firstOwner")); Node actions = metaData.appendChild(modelDoc.createElement("actions")); // create MetaData Layout Actions, that will be logged --> here not regarded // interrogate all incoming data objects for task, create DataPlaces for them and create Task model List<Edge> edges = task.getIncomingEdges(); for (Edge edge : edges) { if (edge.getSource() instanceof ExecDataObject) { ExecDataObject dataObject = (ExecDataObject)edge.getSource(); // create XML Structure for Task String modelXML = dataObject.getModel(); StringBufferInputStream in = new StringBufferInputStream(modelXML); try { //TODO why is Parser not working? Document doc = parser.parse(in); Node dataObjectId = processData.appendChild(modelDoc.createElement(dataObject.getId())); Node dataTagOfDataModel = doc.getDocumentElement().getFirstChild(); Node child = dataTagOfDataModel.getFirstChild(); while (child != null) { dataObjectId.appendChild(child.cloneNode(true)); child = child.getNextSibling(); }; } catch (Exception io) { io.printStackTrace(); } } } // persist model and deliver URL try { DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance(); DOMImplementationLS implLS = (DOMImplementationLS)registry.getDOMImplementation("LS"); LSSerializer dom3Writer = implLS.createLSSerializer(); LSOutput output=implLS.createLSOutput(); OutputStream outputStream = new FileOutputStream(new File(this.baseFileName+"_"+ task.getId() +"_model"+".xml")); output.setByteStream(outputStream); dom3Writer.write(modelDoc,output); } catch (Exception e) { System.out.println("Model could not be persisted"); e.printStackTrace(); } // TODO with model create formular and bindings // TODO persist form and bindings and save URL } catch (ParserConfigurationException e) { e.printStackTrace(); } exTask.pl_ready = addPlace(net, "pl_ready_" + task.getId()); exTask.pl_running = addPlace(net, "pl_running_" + task.getId()); exTask.pl_deciding = addPlace(net, "pl_deciding_" + task.getId()); exTask.pl_suspended = addPlace(net, "pl_suspended_" + task.getId()); exTask.pl_complete = addPlace(net, "pl_complete_" + task.getId()); exTask.pl_context = addPlace(net, "pl_context_" + task.getId()); // add role dependencies String rolename = task.getRolename(); // integrate context place exTask.pl_context.addLocator(new Locator("startTime", "xsd:string", "/data/metadata/startTime")); exTask.pl_context.addLocator(new Locator("endTime", "xsd:string", "/data/metadata/endTime")); exTask.pl_context.addLocator(new Locator("status", "xsd:string", "/data/metadata/status")); exTask.pl_context.addLocator(new Locator("owner", "xsd:string", "/data/metadata/owner")); exTask.pl_context.addLocator(new Locator("isDelegated", "xsd:string", "/data/metadata/isdelegated")); exTask.pl_context.addLocator(new Locator("isReviewed", "xsd:string", "/data/metadata/isreviewed")); exTask.pl_context.addLocator(new Locator("reviewRequested", "xsd:string", "/data/metadata/reviewRequested")); exTask.pl_context.addLocator(new Locator("startTime", "xsd:string", "/data/metadata/firstOwner")); exTask.pl_context.addLocator(new Locator("actions", "xsd:string", "/data/metadata/actions")); //enable transition //TODO: read/write to context place exTask.tr_enable = exTask.tr_done = addAutomaticTransition(net, "tr_enable_" + task.getId(), task.getLabel(), "", copyXsltURL, false); addFlowRelationship(net, c.map.get(getIncomingSequenceFlow(task)), exTask.tr_enable); addFlowRelationship(net, exTask.tr_enable, exTask.pl_ready); // allocate Transition //TODO: change context_allocate when context place gets initialized at start of process exTask.tr_allocate = addAutomaticTransition(net, "tr_allocate_" + task.getId(), task.getLabel(), "allocate", copyXsltURL, true); addFlowRelationship(net, exTask.pl_ready, exTask.tr_allocate); addExecFlowRelationship(net, exTask.tr_allocate, exTask.pl_running, extractDataURL); //addFlowRelationship(net, exTask.pl_context, exTask.tr_allocate); addExecFlowRelationship(net, exTask.tr_allocate, exTask.pl_context, baseXsltURL + "context_allocate.xsl"); exTask.tr_allocate.setRolename(rolename); if (task.isSkippable()) { // skip Transition exTask.setSkippable(true); exTask.tr_skip = addAutomaticTransition(net, "tr_skip_" + task.getId(), task.getLabel(), "skip", copyXsltURL, true); addFlowRelationship(net, exTask.pl_ready, exTask.tr_skip); addExecFlowRelationship(net, exTask.tr_skip, exTask.pl_complete, extractDataURL); addFlowRelationship(net, exTask.pl_context, exTask.tr_skip); addExecFlowRelationship(net, exTask.tr_skip, exTask.pl_context, baseXsltURL + "context_skip.xsl"); } // submit Transition FormTransition submit = addFormTransition(net, "tr_submit_" + task.getId(), task.getLabel(), model, form, bindings); submit.setAction("submit"); exTask.tr_submit = submit; addFlowRelationship(net, exTask.pl_running, exTask.tr_submit); addExecFlowRelationship(net, exTask.tr_submit, exTask.pl_deciding, extractDataURL); addFlowRelationship(net, exTask.pl_context, exTask.tr_submit); addExecFlowRelationship(net, exTask.tr_submit, exTask.pl_context, baseXsltURL + "context_submit.xsl"); exTask.tr_submit.setRolename(rolename); // delegate Transition FormTransition delegate = addFormTransition(net, "tr_delegate_" + task.getId(), task.getLabel(),model,form,bindings); delegate.setAction("delegate"); delegate.setGuard(exTask.pl_deciding.getId() + ".isDelegated == 'true'"); exTask.tr_delegate = delegate; addFlowRelationship(net, exTask.pl_deciding, exTask.tr_delegate); addExecFlowRelationship(net, exTask.tr_delegate, exTask.pl_running, extractDataURL); addFlowRelationship(net, exTask.pl_context, exTask.tr_delegate); addExecFlowRelationship(net, exTask.tr_delegate, exTask.pl_context, baseXsltURL + "context_delegate.xsl"); exTask.tr_delegate.setRolename(rolename); // review Transition FormTransition review = addFormTransition(net, "tr_review_" + task.getId(), task.getLabel(),model,form,bindings); review.setAction("review"); review.setGuard(exTask.pl_context.getId() + ".isDelegated != 'true' && " + exTask.pl_context.getId() + ".isReviewed == 'true'"); exTask.tr_review = review; addFlowRelationship(net, exTask.pl_deciding, exTask.tr_review); addExecFlowRelationship(net, exTask.tr_review, exTask.pl_complete, extractDataURL); addFlowRelationship(net, exTask.pl_context, exTask.tr_review); addExecFlowRelationship(net, exTask.tr_review, exTask.pl_context, baseXsltURL + "context_review.xsl"); exTask.tr_review.setRolename(rolename); // done Transition exTask.tr_done = addAutomaticTransition(net, "tr_done_" + task.getId(), task.getLabel(), "", copyXsltURL, false); addFlowRelationship(net, exTask.pl_deciding, exTask.tr_done); addFlowRelationship(net, exTask.tr_done, exTask.pl_complete); addFlowRelationship(net, exTask.pl_context, exTask.tr_done); addExecFlowRelationship(net, exTask.tr_done, exTask.pl_context, baseXsltURL + "context_done.xsl"); exTask.tr_done.setGuard(exTask.pl_context.getId() + ".isDelegated != 'true' && " + exTask.pl_context.getId() + ".isReviewed != 'true'"); // suspend/resume exTask.tr_suspend = addAutomaticTransition(net, "tr_suspend_" + task.getId(), task.getLabel(), "suspend", copyXsltURL, true); addFlowRelationship(net, exTask.pl_running, exTask.tr_suspend); addExecFlowRelationship(net, exTask.tr_suspend, exTask.pl_suspended, extractDataURL); addFlowRelationship(net, exTask.pl_context, exTask.tr_suspend); addExecFlowRelationship(net, exTask.tr_suspend, exTask.pl_context, baseXsltURL + "context_suspend.xsl"); exTask.tr_suspend.setRolename(rolename); exTask.tr_resume = addAutomaticTransition(net, "tr_resume_" + task.getId(), task.getLabel(), "resume", copyXsltURL, true); addFlowRelationship(net, exTask.pl_suspended, exTask.tr_resume); addExecFlowRelationship(net, exTask.tr_resume, exTask.pl_running, extractDataURL); addFlowRelationship(net, exTask.pl_context, exTask.tr_resume); addExecFlowRelationship(net, exTask.tr_resume, exTask.pl_context, baseXsltURL + "context_resume.xsl"); exTask.tr_resume.setRolename(rolename); // finish transition - //TODO: create context_finish.xsl - exTask.tr_finish =exTask.tr_done = addAutomaticTransition(net, "tr_finish_" + task.getId(), task.getLabel(), "", copyXsltURL, false); + exTask.tr_finish = addAutomaticTransition(net, "tr_finish_" + task.getId(), task.getLabel(), "", copyXsltURL, false); addFlowRelationship(net, exTask.pl_complete, exTask.tr_finish); addExecFlowRelationship(net, exTask.tr_finish, c.map.get(getOutgoingSequenceFlow(task)), extractDataURL); - /*addFlowRelationship(net, exTask.pl_context, exTask.tr_finish); + addFlowRelationship(net, exTask.pl_context, exTask.tr_finish); addExecFlowRelationship(net, exTask.tr_finish, exTask.pl_context, baseXsltURL + "context_finish.xsl"); - */ taskList.add(exTask); handleMessageFlow(net, task, exTask.tr_allocate, exTask.tr_submit, c); if (c.ancestorHasExcpH) handleExceptions(net, task, exTask.tr_submit, c); for (IntermediateEvent event : task.getAttachedEvents()) handleAttachedIntermediateEventForTask(net, event, c); } @Override protected void handleSubProcess(PetriNet net, SubProcess process, ConversionContext c) { super.handleSubProcess(net, process, c); if (process.isAdhoc()) { handleSubProcessAdHoc(net, process, c); } } // TODO: Data dependencies // TODO missing completion condition concept protected void handleSubProcessAdHoc(PetriNet net, SubProcess process, ConversionContext c) { SubProcessPlaces pl = c.getSubprocessPlaces(process); // start and end transitions Transition startT = addTauTransition(net, "ad-hoc_start_" + process.getId()); Transition endT = addTauTransition(net, "ad-hoc_end_" + process.getId()); Transition defaultEndT = addTauTransition(net, "ad-hoc_defaultEnd_" + process.getId()); Place execState = addPlace(net, "ad-hoc_execState_" + process.getId()); addFlowRelationship(net, pl.startP, startT); addFlowRelationship(net, startT, execState); addFlowRelationship(net, execState, defaultEndT); addFlowRelationship(net, execState, endT); addFlowRelationship(net, defaultEndT, pl.endP); addFlowRelationship(net, endT, pl.endP); // standard completion condition check Place updatedState = addPlace(net, "ad-hoc_updatedState_" + process.getId()); Place ccStatus = addPlace(net, "ad-hoc_ccStatus_" + process.getId()); // TODO: make AutomaticTransition with functionality to evaluate completion condition //Transition ccCheck = addLabeledTransition(net, "ad-hoc_ccCheck_" + process.getId(), "ad-hoc_cc_" + process.getCompletionCondition()); Transition ccCheck = addTauTransition(net, "ad-hoc_ccCheck_" + process.getId()); // TODO: make Tau when guards work Transition finalize = addLabeledTransition(net, "ad-hoc_finalize_" + process.getId(), "ad-hoc_finalize"); // TODO: make Tau when guards work //Transition resume = addLabeledTransition(net, "ad-hoc_resume_" + process.getId(), "ad-hoc_resume"); Transition resume = addTauTransition(net, "ad-hoc_resume_" + process.getId()); addFlowRelationship(net, updatedState, ccCheck); addFlowRelationship(net, execState, ccCheck); addFlowRelationship(net, ccCheck, execState); addFlowRelationship(net, ccCheck, ccStatus); if (process.isParallelOrdering() && abortWhenFinalize) { // parallel ad-hoc construct with abortion of tasks when completion condition is true ------------------------------- // synchronization and completionCondition checks(enableStarting, enableFinishing) Place enableStarting = addPlace(net, "ad-hoc_enableStarting_" + process.getId()); Place enableFinishing = addPlace(net, "ad-hoc_enableFinishing_" + process.getId()); addFlowRelationship(net, startT, enableStarting); addFlowRelationship(net, startT, enableFinishing); addFlowRelationship(net, enableStarting, defaultEndT); addFlowRelationship(net, enableFinishing, defaultEndT); addFlowRelationship(net, enableStarting, ccCheck); addFlowRelationship(net, resume, enableStarting); addFlowRelationship(net, resume, enableFinishing); // TODO: add guard expressions addFlowRelationship(net, ccStatus, resume); //guard expression: ccStatus == false addFlowRelationship(net, ccStatus, finalize); // guard expression: ccStatus == true // task specific constructs for (ExecTask exTask : taskList) { // execution(enabledP, executedP, connections in between) Place enabled = addPlace(net, "ad-hoc_task_enabled_" + exTask.getId()); Place executed = addPlace(net, "ad-hoc_task_executed_" + exTask.getId()); addFlowRelationship(net, startT, enabled); addFlowRelationship(net, enabled, exTask.tr_enable); addFlowRelationship(net, enableStarting, exTask.tr_allocate); addFlowRelationship(net, exTask.tr_allocate, enableStarting); addFlowRelationship(net, enableFinishing, exTask.tr_finish); addFlowRelationship(net, exTask.tr_finish, executed); addFlowRelationship(net, exTask.tr_finish, updatedState); if (exTask.isSkippable()) { addFlowRelationship(net, enableStarting, exTask.tr_skip); addFlowRelationship(net, exTask.tr_skip, enableStarting); } // finishing construct(finalize with skip, finish, abort and leave_suspend) Place enableFinalize = addPlace(net, "ad-hoc_enable_finalize_task_" + exTask.getId()); Place taskFinalized = addPlace(net, "ad-hoc_task_finalized_" + exTask.getId()); Transition skip = addTauTransition(net, "ad-hoc_skip_task_" + exTask.getId()); Transition finish = addTauTransition(net, "ad-hoc_finish_task_" + exTask.getId()); Transition abort = addTauTransition(net, "ad-hoc_abort_task_" + exTask.getId()); Transition leaveSuspended = addTauTransition(net, "ad-hoc_leave_suspended_task_" + exTask.getId()); addFlowRelationship(net, finalize, enableFinalize); addFlowRelationship(net, enableFinalize, skip); addFlowRelationship(net, enabled, skip); addFlowRelationship(net, skip, taskFinalized); addFlowRelationship(net, enableFinalize, finish); addFlowRelationship(net, executed, finish); addFlowRelationship(net, finish, taskFinalized); //TODO: remove ability to abort? addFlowRelationship(net, enableFinalize, abort); addFlowRelationship(net, exTask.pl_running, abort); addFlowRelationship(net, abort, taskFinalized); addFlowRelationship(net, enableFinalize, leaveSuspended); addFlowRelationship(net, exTask.pl_suspended, leaveSuspended); addFlowRelationship(net, leaveSuspended, taskFinalized); addFlowRelationship(net, taskFinalized, endT); } }else if (process.isParallelOrdering() && !abortWhenFinalize) { // parallel ad-hoc construct, running tasks can finish on their own after completion condition is true ------------- throw new NotImplementedException(); }else { // sequential ad-hoc construct ----------------------------------------------------------------------------------------------- // synchronization and completionCondition checks(synch, corresponds to enableStarting) Place synch = addPlace(net, "ad-hoc_synch_" + process.getId()); addFlowRelationship(net, startT, synch); addFlowRelationship(net, synch, defaultEndT); addFlowRelationship(net, resume, synch); // TODO: add guard expressions addFlowRelationship(net, ccStatus, resume); //guard expression: ccStatus == false addFlowRelationship(net, ccStatus, finalize); // guard expression: ccStatus == true // task specific constructs for (ExecTask exTask : taskList) { // execution(enabledP, executedP, connections in between) Place enabled = addPlace(net, "ad-hoc_task_enabled_" + exTask.getId()); Place executed = addPlace(net, "ad-hoc_task_executed_" + exTask.getId()); addFlowRelationship(net, startT, enabled); addFlowRelationship(net, enabled, exTask.tr_enable); addFlowRelationship(net, synch, exTask.tr_allocate); addFlowRelationship(net, exTask.tr_finish, executed); addFlowRelationship(net, exTask.tr_finish, updatedState); addFlowRelationship(net, executed, defaultEndT); if (exTask.isSkippable()) { addFlowRelationship(net, synch, exTask.tr_skip); } // finishing construct(finalize with skip, finish and abort) Place enableFinalize = addPlace(net, "ad-hoc_enable_finalize_task_" + exTask.getId()); Place taskFinalized = addPlace(net, "ad-hoc_task_finalized_" + exTask.getId()); Transition skip = addTauTransition(net, "ad-hoc_skip_task_" + exTask.getId()); Transition finish = addTauTransition(net, "ad-hoc_finish_task_" + exTask.getId()); addFlowRelationship(net, finalize, enableFinalize); addFlowRelationship(net, enableFinalize, skip); addFlowRelationship(net, enabled, skip); addFlowRelationship(net, skip, taskFinalized); addFlowRelationship(net, enableFinalize, finish); addFlowRelationship(net, executed, finish); addFlowRelationship(net, finish, taskFinalized); addFlowRelationship(net, taskFinalized, endT); } } } @Override protected void handleDataObject(PetriNet net, DataObject object, ConversionContext c){ try { if (object instanceof ExecDataObject) { ExecDataObject dataobject = (ExecDataObject) object; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance ( ) ; DocumentBuilder parser = factory.newDocumentBuilder ( ) ; //create data place for Task Place dataPlace = addPlace(net,"pl_data_"+dataobject.getId()); ExecTask.addDataPlace(dataPlace); // for data place add locators String modelXML = dataobject.getModel(); StringBufferInputStream in = new StringBufferInputStream(modelXML); Document doc = parser.parse(in); Node dataTagOfDataModel = doc.getDocumentElement().getFirstChild(); Node child = dataTagOfDataModel.getFirstChild(); while (child != null) { dataPlace.addLocator(new Locator( child.getNodeName(), "xsd:string", "/data/processdata/"+dataobject.getId()+"/"+child.getNodeName())); child = child.getNextSibling(); }; } } catch (Exception io) { io.printStackTrace(); } } public AutomaticTransition addAutomaticTransition(PetriNet net, String id, String label, String action, String xsltURL, boolean triggerManually) { AutomaticTransition t =((ExecPNFactoryImpl) pnfactory).createAutomaticTransition(); t.setId(id); t.setLabel(label); t.setAction(action); t.setXsltURL(xsltURL); t.setManuallyTriggered(triggerManually); net.getTransitions().add(t); return t; } public ExecFlowRelationship addExecFlowRelationship(PetriNet net, de.hpi.petrinet.Node source, de.hpi.petrinet.Node target, String xsltURL) { if (source == null || target == null) return null; ExecFlowRelationship rel = ((ExecPNFactoryImpl) pnfactory).createExecFlowRelationship(); rel.setSource(source); rel.setTarget(target); rel.setTransformationURL(xsltURL); net.getFlowRelationships().add(rel); return rel; } public FormTransition addFormTransition(PetriNet net, String id, String label, String model, String form, String bindings) { FormTransition t = ((ExecPNFactoryImpl)pnfactory).createFormTransition(); t.setId(id); t.setLabel(label); t.setFormURL(form); t.setBindingsURL(bindings); t.setModelURL(model); net.getTransitions().add(t); return t; } }
false
true
protected void handleTask(PetriNet net, Task task, ConversionContext c) { ExecTask exTask = new ExecTask(); exTask.setId(task.getId()); exTask.setLabel(task.getLabel()); // create proper model, form and bindings String model = null; String form = null; String bindings = null; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance ( ) ; try { DocumentBuilder parser = factory.newDocumentBuilder ( ) ; Document modelDoc = parser.newDocument(); Element dataEl = modelDoc.createElement("data"); Node data = modelDoc.appendChild(dataEl); Node metaData = data.appendChild(modelDoc.createElement("metadata")); Node processData = data.appendChild(modelDoc.createElement("processdata")); // create MetaData Layout for Task model // (take attention to the fact, that the attributes are again defined in the engine) Node startTime = metaData.appendChild(modelDoc.createElement("startTime")); Node endTime = metaData.appendChild(modelDoc.createElement("endTime")); Node status = metaData.appendChild(modelDoc.createElement("status")); Node owner = metaData.appendChild(modelDoc.createElement("owner")); Node isDelegated = metaData.appendChild(modelDoc.createElement("isDelegated")); Node reviewRequested = metaData.appendChild(modelDoc.createElement("reviewRequested")); Node firstOwner = metaData.appendChild(modelDoc.createElement("firstOwner")); Node actions = metaData.appendChild(modelDoc.createElement("actions")); // create MetaData Layout Actions, that will be logged --> here not regarded // interrogate all incoming data objects for task, create DataPlaces for them and create Task model List<Edge> edges = task.getIncomingEdges(); for (Edge edge : edges) { if (edge.getSource() instanceof ExecDataObject) { ExecDataObject dataObject = (ExecDataObject)edge.getSource(); // create XML Structure for Task String modelXML = dataObject.getModel(); StringBufferInputStream in = new StringBufferInputStream(modelXML); try { //TODO why is Parser not working? Document doc = parser.parse(in); Node dataObjectId = processData.appendChild(modelDoc.createElement(dataObject.getId())); Node dataTagOfDataModel = doc.getDocumentElement().getFirstChild(); Node child = dataTagOfDataModel.getFirstChild(); while (child != null) { dataObjectId.appendChild(child.cloneNode(true)); child = child.getNextSibling(); }; } catch (Exception io) { io.printStackTrace(); } } } // persist model and deliver URL try { DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance(); DOMImplementationLS implLS = (DOMImplementationLS)registry.getDOMImplementation("LS"); LSSerializer dom3Writer = implLS.createLSSerializer(); LSOutput output=implLS.createLSOutput(); OutputStream outputStream = new FileOutputStream(new File(this.baseFileName+"_"+ task.getId() +"_model"+".xml")); output.setByteStream(outputStream); dom3Writer.write(modelDoc,output); } catch (Exception e) { System.out.println("Model could not be persisted"); e.printStackTrace(); } // TODO with model create formular and bindings // TODO persist form and bindings and save URL } catch (ParserConfigurationException e) { e.printStackTrace(); } exTask.pl_ready = addPlace(net, "pl_ready_" + task.getId()); exTask.pl_running = addPlace(net, "pl_running_" + task.getId()); exTask.pl_deciding = addPlace(net, "pl_deciding_" + task.getId()); exTask.pl_suspended = addPlace(net, "pl_suspended_" + task.getId()); exTask.pl_complete = addPlace(net, "pl_complete_" + task.getId()); exTask.pl_context = addPlace(net, "pl_context_" + task.getId()); // add role dependencies String rolename = task.getRolename(); // integrate context place exTask.pl_context.addLocator(new Locator("startTime", "xsd:string", "/data/metadata/startTime")); exTask.pl_context.addLocator(new Locator("endTime", "xsd:string", "/data/metadata/endTime")); exTask.pl_context.addLocator(new Locator("status", "xsd:string", "/data/metadata/status")); exTask.pl_context.addLocator(new Locator("owner", "xsd:string", "/data/metadata/owner")); exTask.pl_context.addLocator(new Locator("isDelegated", "xsd:string", "/data/metadata/isdelegated")); exTask.pl_context.addLocator(new Locator("isReviewed", "xsd:string", "/data/metadata/isreviewed")); exTask.pl_context.addLocator(new Locator("reviewRequested", "xsd:string", "/data/metadata/reviewRequested")); exTask.pl_context.addLocator(new Locator("startTime", "xsd:string", "/data/metadata/firstOwner")); exTask.pl_context.addLocator(new Locator("actions", "xsd:string", "/data/metadata/actions")); //enable transition //TODO: read/write to context place exTask.tr_enable = exTask.tr_done = addAutomaticTransition(net, "tr_enable_" + task.getId(), task.getLabel(), "", copyXsltURL, false); addFlowRelationship(net, c.map.get(getIncomingSequenceFlow(task)), exTask.tr_enable); addFlowRelationship(net, exTask.tr_enable, exTask.pl_ready); // allocate Transition //TODO: change context_allocate when context place gets initialized at start of process exTask.tr_allocate = addAutomaticTransition(net, "tr_allocate_" + task.getId(), task.getLabel(), "allocate", copyXsltURL, true); addFlowRelationship(net, exTask.pl_ready, exTask.tr_allocate); addExecFlowRelationship(net, exTask.tr_allocate, exTask.pl_running, extractDataURL); //addFlowRelationship(net, exTask.pl_context, exTask.tr_allocate); addExecFlowRelationship(net, exTask.tr_allocate, exTask.pl_context, baseXsltURL + "context_allocate.xsl"); exTask.tr_allocate.setRolename(rolename); if (task.isSkippable()) { // skip Transition exTask.setSkippable(true); exTask.tr_skip = addAutomaticTransition(net, "tr_skip_" + task.getId(), task.getLabel(), "skip", copyXsltURL, true); addFlowRelationship(net, exTask.pl_ready, exTask.tr_skip); addExecFlowRelationship(net, exTask.tr_skip, exTask.pl_complete, extractDataURL); addFlowRelationship(net, exTask.pl_context, exTask.tr_skip); addExecFlowRelationship(net, exTask.tr_skip, exTask.pl_context, baseXsltURL + "context_skip.xsl"); } // submit Transition FormTransition submit = addFormTransition(net, "tr_submit_" + task.getId(), task.getLabel(), model, form, bindings); submit.setAction("submit"); exTask.tr_submit = submit; addFlowRelationship(net, exTask.pl_running, exTask.tr_submit); addExecFlowRelationship(net, exTask.tr_submit, exTask.pl_deciding, extractDataURL); addFlowRelationship(net, exTask.pl_context, exTask.tr_submit); addExecFlowRelationship(net, exTask.tr_submit, exTask.pl_context, baseXsltURL + "context_submit.xsl"); exTask.tr_submit.setRolename(rolename); // delegate Transition FormTransition delegate = addFormTransition(net, "tr_delegate_" + task.getId(), task.getLabel(),model,form,bindings); delegate.setAction("delegate"); delegate.setGuard(exTask.pl_deciding.getId() + ".isDelegated == 'true'"); exTask.tr_delegate = delegate; addFlowRelationship(net, exTask.pl_deciding, exTask.tr_delegate); addExecFlowRelationship(net, exTask.tr_delegate, exTask.pl_running, extractDataURL); addFlowRelationship(net, exTask.pl_context, exTask.tr_delegate); addExecFlowRelationship(net, exTask.tr_delegate, exTask.pl_context, baseXsltURL + "context_delegate.xsl"); exTask.tr_delegate.setRolename(rolename); // review Transition FormTransition review = addFormTransition(net, "tr_review_" + task.getId(), task.getLabel(),model,form,bindings); review.setAction("review"); review.setGuard(exTask.pl_context.getId() + ".isDelegated != 'true' && " + exTask.pl_context.getId() + ".isReviewed == 'true'"); exTask.tr_review = review; addFlowRelationship(net, exTask.pl_deciding, exTask.tr_review); addExecFlowRelationship(net, exTask.tr_review, exTask.pl_complete, extractDataURL); addFlowRelationship(net, exTask.pl_context, exTask.tr_review); addExecFlowRelationship(net, exTask.tr_review, exTask.pl_context, baseXsltURL + "context_review.xsl"); exTask.tr_review.setRolename(rolename); // done Transition exTask.tr_done = addAutomaticTransition(net, "tr_done_" + task.getId(), task.getLabel(), "", copyXsltURL, false); addFlowRelationship(net, exTask.pl_deciding, exTask.tr_done); addFlowRelationship(net, exTask.tr_done, exTask.pl_complete); addFlowRelationship(net, exTask.pl_context, exTask.tr_done); addExecFlowRelationship(net, exTask.tr_done, exTask.pl_context, baseXsltURL + "context_done.xsl"); exTask.tr_done.setGuard(exTask.pl_context.getId() + ".isDelegated != 'true' && " + exTask.pl_context.getId() + ".isReviewed != 'true'"); // suspend/resume exTask.tr_suspend = addAutomaticTransition(net, "tr_suspend_" + task.getId(), task.getLabel(), "suspend", copyXsltURL, true); addFlowRelationship(net, exTask.pl_running, exTask.tr_suspend); addExecFlowRelationship(net, exTask.tr_suspend, exTask.pl_suspended, extractDataURL); addFlowRelationship(net, exTask.pl_context, exTask.tr_suspend); addExecFlowRelationship(net, exTask.tr_suspend, exTask.pl_context, baseXsltURL + "context_suspend.xsl"); exTask.tr_suspend.setRolename(rolename); exTask.tr_resume = addAutomaticTransition(net, "tr_resume_" + task.getId(), task.getLabel(), "resume", copyXsltURL, true); addFlowRelationship(net, exTask.pl_suspended, exTask.tr_resume); addExecFlowRelationship(net, exTask.tr_resume, exTask.pl_running, extractDataURL); addFlowRelationship(net, exTask.pl_context, exTask.tr_resume); addExecFlowRelationship(net, exTask.tr_resume, exTask.pl_context, baseXsltURL + "context_resume.xsl"); exTask.tr_resume.setRolename(rolename); // finish transition //TODO: create context_finish.xsl exTask.tr_finish =exTask.tr_done = addAutomaticTransition(net, "tr_finish_" + task.getId(), task.getLabel(), "", copyXsltURL, false); addFlowRelationship(net, exTask.pl_complete, exTask.tr_finish); addExecFlowRelationship(net, exTask.tr_finish, c.map.get(getOutgoingSequenceFlow(task)), extractDataURL); /*addFlowRelationship(net, exTask.pl_context, exTask.tr_finish); addExecFlowRelationship(net, exTask.tr_finish, exTask.pl_context, baseXsltURL + "context_finish.xsl"); */ taskList.add(exTask); handleMessageFlow(net, task, exTask.tr_allocate, exTask.tr_submit, c); if (c.ancestorHasExcpH) handleExceptions(net, task, exTask.tr_submit, c); for (IntermediateEvent event : task.getAttachedEvents()) handleAttachedIntermediateEventForTask(net, event, c); }
protected void handleTask(PetriNet net, Task task, ConversionContext c) { ExecTask exTask = new ExecTask(); exTask.setId(task.getId()); exTask.setLabel(task.getLabel()); // create proper model, form and bindings String model = null; String form = null; String bindings = null; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance ( ) ; try { DocumentBuilder parser = factory.newDocumentBuilder ( ) ; Document modelDoc = parser.newDocument(); Element dataEl = modelDoc.createElement("data"); Node data = modelDoc.appendChild(dataEl); Node metaData = data.appendChild(modelDoc.createElement("metadata")); Node processData = data.appendChild(modelDoc.createElement("processdata")); // create MetaData Layout for Task model // (take attention to the fact, that the attributes are again defined in the engine) Node startTime = metaData.appendChild(modelDoc.createElement("startTime")); Node endTime = metaData.appendChild(modelDoc.createElement("endTime")); Node status = metaData.appendChild(modelDoc.createElement("status")); Node owner = metaData.appendChild(modelDoc.createElement("owner")); Node isDelegated = metaData.appendChild(modelDoc.createElement("isDelegated")); Node reviewRequested = metaData.appendChild(modelDoc.createElement("reviewRequested")); Node firstOwner = metaData.appendChild(modelDoc.createElement("firstOwner")); Node actions = metaData.appendChild(modelDoc.createElement("actions")); // create MetaData Layout Actions, that will be logged --> here not regarded // interrogate all incoming data objects for task, create DataPlaces for them and create Task model List<Edge> edges = task.getIncomingEdges(); for (Edge edge : edges) { if (edge.getSource() instanceof ExecDataObject) { ExecDataObject dataObject = (ExecDataObject)edge.getSource(); // create XML Structure for Task String modelXML = dataObject.getModel(); StringBufferInputStream in = new StringBufferInputStream(modelXML); try { //TODO why is Parser not working? Document doc = parser.parse(in); Node dataObjectId = processData.appendChild(modelDoc.createElement(dataObject.getId())); Node dataTagOfDataModel = doc.getDocumentElement().getFirstChild(); Node child = dataTagOfDataModel.getFirstChild(); while (child != null) { dataObjectId.appendChild(child.cloneNode(true)); child = child.getNextSibling(); }; } catch (Exception io) { io.printStackTrace(); } } } // persist model and deliver URL try { DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance(); DOMImplementationLS implLS = (DOMImplementationLS)registry.getDOMImplementation("LS"); LSSerializer dom3Writer = implLS.createLSSerializer(); LSOutput output=implLS.createLSOutput(); OutputStream outputStream = new FileOutputStream(new File(this.baseFileName+"_"+ task.getId() +"_model"+".xml")); output.setByteStream(outputStream); dom3Writer.write(modelDoc,output); } catch (Exception e) { System.out.println("Model could not be persisted"); e.printStackTrace(); } // TODO with model create formular and bindings // TODO persist form and bindings and save URL } catch (ParserConfigurationException e) { e.printStackTrace(); } exTask.pl_ready = addPlace(net, "pl_ready_" + task.getId()); exTask.pl_running = addPlace(net, "pl_running_" + task.getId()); exTask.pl_deciding = addPlace(net, "pl_deciding_" + task.getId()); exTask.pl_suspended = addPlace(net, "pl_suspended_" + task.getId()); exTask.pl_complete = addPlace(net, "pl_complete_" + task.getId()); exTask.pl_context = addPlace(net, "pl_context_" + task.getId()); // add role dependencies String rolename = task.getRolename(); // integrate context place exTask.pl_context.addLocator(new Locator("startTime", "xsd:string", "/data/metadata/startTime")); exTask.pl_context.addLocator(new Locator("endTime", "xsd:string", "/data/metadata/endTime")); exTask.pl_context.addLocator(new Locator("status", "xsd:string", "/data/metadata/status")); exTask.pl_context.addLocator(new Locator("owner", "xsd:string", "/data/metadata/owner")); exTask.pl_context.addLocator(new Locator("isDelegated", "xsd:string", "/data/metadata/isdelegated")); exTask.pl_context.addLocator(new Locator("isReviewed", "xsd:string", "/data/metadata/isreviewed")); exTask.pl_context.addLocator(new Locator("reviewRequested", "xsd:string", "/data/metadata/reviewRequested")); exTask.pl_context.addLocator(new Locator("startTime", "xsd:string", "/data/metadata/firstOwner")); exTask.pl_context.addLocator(new Locator("actions", "xsd:string", "/data/metadata/actions")); //enable transition //TODO: read/write to context place exTask.tr_enable = exTask.tr_done = addAutomaticTransition(net, "tr_enable_" + task.getId(), task.getLabel(), "", copyXsltURL, false); addFlowRelationship(net, c.map.get(getIncomingSequenceFlow(task)), exTask.tr_enable); addFlowRelationship(net, exTask.tr_enable, exTask.pl_ready); // allocate Transition //TODO: change context_allocate when context place gets initialized at start of process exTask.tr_allocate = addAutomaticTransition(net, "tr_allocate_" + task.getId(), task.getLabel(), "allocate", copyXsltURL, true); addFlowRelationship(net, exTask.pl_ready, exTask.tr_allocate); addExecFlowRelationship(net, exTask.tr_allocate, exTask.pl_running, extractDataURL); //addFlowRelationship(net, exTask.pl_context, exTask.tr_allocate); addExecFlowRelationship(net, exTask.tr_allocate, exTask.pl_context, baseXsltURL + "context_allocate.xsl"); exTask.tr_allocate.setRolename(rolename); if (task.isSkippable()) { // skip Transition exTask.setSkippable(true); exTask.tr_skip = addAutomaticTransition(net, "tr_skip_" + task.getId(), task.getLabel(), "skip", copyXsltURL, true); addFlowRelationship(net, exTask.pl_ready, exTask.tr_skip); addExecFlowRelationship(net, exTask.tr_skip, exTask.pl_complete, extractDataURL); addFlowRelationship(net, exTask.pl_context, exTask.tr_skip); addExecFlowRelationship(net, exTask.tr_skip, exTask.pl_context, baseXsltURL + "context_skip.xsl"); } // submit Transition FormTransition submit = addFormTransition(net, "tr_submit_" + task.getId(), task.getLabel(), model, form, bindings); submit.setAction("submit"); exTask.tr_submit = submit; addFlowRelationship(net, exTask.pl_running, exTask.tr_submit); addExecFlowRelationship(net, exTask.tr_submit, exTask.pl_deciding, extractDataURL); addFlowRelationship(net, exTask.pl_context, exTask.tr_submit); addExecFlowRelationship(net, exTask.tr_submit, exTask.pl_context, baseXsltURL + "context_submit.xsl"); exTask.tr_submit.setRolename(rolename); // delegate Transition FormTransition delegate = addFormTransition(net, "tr_delegate_" + task.getId(), task.getLabel(),model,form,bindings); delegate.setAction("delegate"); delegate.setGuard(exTask.pl_deciding.getId() + ".isDelegated == 'true'"); exTask.tr_delegate = delegate; addFlowRelationship(net, exTask.pl_deciding, exTask.tr_delegate); addExecFlowRelationship(net, exTask.tr_delegate, exTask.pl_running, extractDataURL); addFlowRelationship(net, exTask.pl_context, exTask.tr_delegate); addExecFlowRelationship(net, exTask.tr_delegate, exTask.pl_context, baseXsltURL + "context_delegate.xsl"); exTask.tr_delegate.setRolename(rolename); // review Transition FormTransition review = addFormTransition(net, "tr_review_" + task.getId(), task.getLabel(),model,form,bindings); review.setAction("review"); review.setGuard(exTask.pl_context.getId() + ".isDelegated != 'true' && " + exTask.pl_context.getId() + ".isReviewed == 'true'"); exTask.tr_review = review; addFlowRelationship(net, exTask.pl_deciding, exTask.tr_review); addExecFlowRelationship(net, exTask.tr_review, exTask.pl_complete, extractDataURL); addFlowRelationship(net, exTask.pl_context, exTask.tr_review); addExecFlowRelationship(net, exTask.tr_review, exTask.pl_context, baseXsltURL + "context_review.xsl"); exTask.tr_review.setRolename(rolename); // done Transition exTask.tr_done = addAutomaticTransition(net, "tr_done_" + task.getId(), task.getLabel(), "", copyXsltURL, false); addFlowRelationship(net, exTask.pl_deciding, exTask.tr_done); addFlowRelationship(net, exTask.tr_done, exTask.pl_complete); addFlowRelationship(net, exTask.pl_context, exTask.tr_done); addExecFlowRelationship(net, exTask.tr_done, exTask.pl_context, baseXsltURL + "context_done.xsl"); exTask.tr_done.setGuard(exTask.pl_context.getId() + ".isDelegated != 'true' && " + exTask.pl_context.getId() + ".isReviewed != 'true'"); // suspend/resume exTask.tr_suspend = addAutomaticTransition(net, "tr_suspend_" + task.getId(), task.getLabel(), "suspend", copyXsltURL, true); addFlowRelationship(net, exTask.pl_running, exTask.tr_suspend); addExecFlowRelationship(net, exTask.tr_suspend, exTask.pl_suspended, extractDataURL); addFlowRelationship(net, exTask.pl_context, exTask.tr_suspend); addExecFlowRelationship(net, exTask.tr_suspend, exTask.pl_context, baseXsltURL + "context_suspend.xsl"); exTask.tr_suspend.setRolename(rolename); exTask.tr_resume = addAutomaticTransition(net, "tr_resume_" + task.getId(), task.getLabel(), "resume", copyXsltURL, true); addFlowRelationship(net, exTask.pl_suspended, exTask.tr_resume); addExecFlowRelationship(net, exTask.tr_resume, exTask.pl_running, extractDataURL); addFlowRelationship(net, exTask.pl_context, exTask.tr_resume); addExecFlowRelationship(net, exTask.tr_resume, exTask.pl_context, baseXsltURL + "context_resume.xsl"); exTask.tr_resume.setRolename(rolename); // finish transition exTask.tr_finish = addAutomaticTransition(net, "tr_finish_" + task.getId(), task.getLabel(), "", copyXsltURL, false); addFlowRelationship(net, exTask.pl_complete, exTask.tr_finish); addExecFlowRelationship(net, exTask.tr_finish, c.map.get(getOutgoingSequenceFlow(task)), extractDataURL); addFlowRelationship(net, exTask.pl_context, exTask.tr_finish); addExecFlowRelationship(net, exTask.tr_finish, exTask.pl_context, baseXsltURL + "context_finish.xsl"); taskList.add(exTask); handleMessageFlow(net, task, exTask.tr_allocate, exTask.tr_submit, c); if (c.ancestorHasExcpH) handleExceptions(net, task, exTask.tr_submit, c); for (IntermediateEvent event : task.getAttachedEvents()) handleAttachedIntermediateEventForTask(net, event, c); }
diff --git a/src/org/mozilla/javascript/ScriptableObject.java b/src/org/mozilla/javascript/ScriptableObject.java index 3069d5fb..369e431f 100644 --- a/src/org/mozilla/javascript/ScriptableObject.java +++ b/src/org/mozilla/javascript/ScriptableObject.java @@ -1,1969 +1,1970 @@ /* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * The contents of this file are subject to the Netscape Public * License Version 1.1 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.mozilla.org/NPL/ * * Software distributed under the License is distributed on an "AS * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or * implied. See the License for the specific language governing * rights and limitations under the License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is Netscape * Communications Corporation. Portions created by Netscape are * Copyright (C) 1997-1999 Netscape Communications Corporation. All * Rights Reserved. * * Contributor(s): * Norris Boyd * Igor Bukanov * Roger Lawrence * * Alternatively, the contents of this file may be used under the * terms of the GNU Public License (the "GPL"), in which case the * provisions of the GPL are applicable instead of those above. * If you wish to allow use of your version of this file only * under the terms of the GPL and not to allow others to use your * version of this file under the NPL, indicate your decision by * deleting the provisions above and replace them with the notice * and other provisions required by the GPL. If you do not delete * the provisions above, a recipient may use your version of this * file under either the NPL or the GPL. */ // API class package org.mozilla.javascript; import java.lang.reflect.*; import java.util.Hashtable; import java.io.*; import org.mozilla.javascript.debug.DebuggableObject; /** * This is the default implementation of the Scriptable interface. This * class provides convenient default behavior that makes it easier to * define host objects. * <p> * Various properties and methods of JavaScript objects can be conveniently * defined using methods of ScriptableObject. * <p> * Classes extending ScriptableObject must define the getClassName method. * * @see org.mozilla.javascript.Scriptable * @author Norris Boyd */ public abstract class ScriptableObject implements Scriptable, Serializable, DebuggableObject { /** * The empty property attribute. * * Used by getAttributes() and setAttributes(). * * @see org.mozilla.javascript.ScriptableObject#getAttributes * @see org.mozilla.javascript.ScriptableObject#setAttributes */ public static final int EMPTY = 0x00; /** * Property attribute indicating assignment to this property is ignored. * * @see org.mozilla.javascript.ScriptableObject#put * @see org.mozilla.javascript.ScriptableObject#getAttributes * @see org.mozilla.javascript.ScriptableObject#setAttributes */ public static final int READONLY = 0x01; /** * Property attribute indicating property is not enumerated. * * Only enumerated properties will be returned by getIds(). * * @see org.mozilla.javascript.ScriptableObject#getIds * @see org.mozilla.javascript.ScriptableObject#getAttributes * @see org.mozilla.javascript.ScriptableObject#setAttributes */ public static final int DONTENUM = 0x02; /** * Property attribute indicating property cannot be deleted. * * @see org.mozilla.javascript.ScriptableObject#delete * @see org.mozilla.javascript.ScriptableObject#getAttributes * @see org.mozilla.javascript.ScriptableObject#setAttributes */ public static final int PERMANENT = 0x04; static void checkValidAttributes(int attributes) { final int mask = READONLY | DONTENUM | PERMANENT; if ((attributes & ~mask) != 0) { throw new IllegalArgumentException(String.valueOf(attributes)); } } public ScriptableObject() { } public ScriptableObject(Scriptable scope, Scriptable prototype) { if (scope == null) throw new IllegalArgumentException(); parentScopeObject = scope; prototypeObject = prototype; } /** * Return the name of the class. * * This is typically the same name as the constructor. * Classes extending ScriptableObject must implement this abstract * method. */ public abstract String getClassName(); /** * Returns true if the named property is defined. * * @param name the name of the property * @param start the object in which the lookup began * @return true if and only if the property was found in the object */ public boolean has(String name, Scriptable start) { return null != getNamedSlot(name); } /** * Returns true if the property index is defined. * * @param index the numeric index for the property * @param start the object in which the lookup began * @return true if and only if the property was found in the object */ public boolean has(int index, Scriptable start) { return null != getSlot(null, index); } /** * Returns the value of the named property or NOT_FOUND. * * If the property was created using defineProperty, the * appropriate getter method is called. * * @param name the name of the property * @param start the object in which the lookup began * @return the value of the property (may be null), or NOT_FOUND */ public Object get(String name, Scriptable start) { Slot slot = getNamedSlot(name); if (slot == null) { return Scriptable.NOT_FOUND; } if (slot.complexSlotFlag != 0) { GetterSlot gslot = (GetterSlot)slot; if (gslot.getter != null) { return getByGetter(gslot, start); } } return slot.value; } /** * Returns the value of the indexed property or NOT_FOUND. * * @param index the numeric index for the property * @param start the object in which the lookup began * @return the value of the property (may be null), or NOT_FOUND */ public Object get(int index, Scriptable start) { Slot slot = getSlot(null, index); if (slot == null) { return Scriptable.NOT_FOUND; } return slot.value; } /** * Sets the value of the named property, creating it if need be. * * If the property was created using defineProperty, the * appropriate setter method is called. <p> * * If the property's attributes include READONLY, no action is * taken. * This method will actually set the property in the start * object. * * @param name the name of the property * @param start the object whose property is being set * @param value value to set the property to */ public void put(String name, Scriptable start, Object value) { Slot slot = lastAccess; // Get local copy if (name != slot.stringKey || slot.wasDeleted != 0) { int hash = name.hashCode(); slot = getSlot(name, hash); if (slot == null) { if (start != this) { start.put(name, start, value); return; } slot = addSlot(name, hash, null); } // Note: cache is not updated in put } if (start == this && isSealed()) { throw Context.reportRuntimeError1("msg.modify.sealed", name); } if ((slot.attributes & ScriptableObject.READONLY) != 0) { return; } if (slot.complexSlotFlag != 0) { GetterSlot gslot = (GetterSlot)slot; if (gslot.setter != null) { setBySetter(gslot, start, value); } return; } if (this == start) { slot.value = value; } else { start.put(name, start, value); } } /** * Sets the value of the indexed property, creating it if need be. * * @param index the numeric index for the property * @param start the object whose property is being set * @param value value to set the property to */ public void put(int index, Scriptable start, Object value) { Slot slot = getSlot(null, index); if (slot == null) { if (start != this) { start.put(index, start, value); return; } slot = addSlot(null, index, null); } if (start == this && isSealed()) { throw Context.reportRuntimeError1("msg.modify.sealed", Integer.toString(index)); } if ((slot.attributes & ScriptableObject.READONLY) != 0) { return; } if (this == start) { slot.value = value; } else { start.put(index, start, value); } } /** * Removes a named property from the object. * * If the property is not found, or it has the PERMANENT attribute, * no action is taken. * * @param name the name of the property */ public void delete(String name) { removeSlot(name, name.hashCode()); } /** * Removes the indexed property from the object. * * If the property is not found, or it has the PERMANENT attribute, * no action is taken. * * @param index the numeric index for the property */ public void delete(int index) { removeSlot(null, index); } /** * @deprecated Use {@link #getAttributes(String name)}. The engine always * ignored the start argument. */ public final int getAttributes(String name, Scriptable start) { return getAttributes(name); } /** * @deprecated Use {@link #getAttributes(int index)}. The engine always * ignored the start argument. */ public final int getAttributes(int index, Scriptable start) { return getAttributes(index); } /** * @deprecated Use {@link #setAttributes(String name, int attributes)}. * The engine always ignored the start argument. */ public final void setAttributes(String name, Scriptable start, int attributes) { setAttributes(name, attributes); } /** * @deprecated Use {@link #setAttributes(int index, int attributes)}. * The engine always ignored the start argument. */ public void setAttributes(int index, Scriptable start, int attributes) { setAttributes(index, attributes); } /** * Get the attributes of a named property. * * The property is specified by <code>name</code> * as defined for <code>has</code>.<p> * * @param name the identifier for the property * @return the bitset of attributes * @exception EvaluatorException if the named property is not found * @see org.mozilla.javascript.ScriptableObject#has * @see org.mozilla.javascript.ScriptableObject#READONLY * @see org.mozilla.javascript.ScriptableObject#DONTENUM * @see org.mozilla.javascript.ScriptableObject#PERMANENT * @see org.mozilla.javascript.ScriptableObject#EMPTY */ public int getAttributes(String name) { Slot slot = getNamedSlot(name); if (slot == null) { throw Context.reportRuntimeError1("msg.prop.not.found", name); } return slot.attributes; } /** * Get the attributes of an indexed property. * * @param index the numeric index for the property * @exception EvaluatorException if the named property is not found * is not found * @return the bitset of attributes * @see org.mozilla.javascript.ScriptableObject#has * @see org.mozilla.javascript.ScriptableObject#READONLY * @see org.mozilla.javascript.ScriptableObject#DONTENUM * @see org.mozilla.javascript.ScriptableObject#PERMANENT * @see org.mozilla.javascript.ScriptableObject#EMPTY */ public int getAttributes(int index) { Slot slot = getSlot(null, index); if (slot == null) { throw Context.reportRuntimeError1("msg.prop.not.found", String.valueOf(index)); } return slot.attributes; } /** * Set the attributes of a named property. * * The property is specified by <code>name</code> * as defined for <code>has</code>.<p> * * The possible attributes are READONLY, DONTENUM, * and PERMANENT. Combinations of attributes * are expressed by the bitwise OR of attributes. * EMPTY is the state of no attributes set. Any unused * bits are reserved for future use. * * @param name the name of the property * @param attributes the bitset of attributes * @exception EvaluatorException if the named property is not found * @see org.mozilla.javascript.Scriptable#has * @see org.mozilla.javascript.ScriptableObject#READONLY * @see org.mozilla.javascript.ScriptableObject#DONTENUM * @see org.mozilla.javascript.ScriptableObject#PERMANENT * @see org.mozilla.javascript.ScriptableObject#EMPTY */ public void setAttributes(String name, int attributes) { checkValidAttributes(attributes); Slot slot = getNamedSlot(name); if (slot == null) { throw Context.reportRuntimeError1("msg.prop.not.found", name); } slot.attributes = (short) attributes; } /** * Set the attributes of an indexed property. * * @param index the numeric index for the property * @param attributes the bitset of attributes * @exception EvaluatorException if the named property is not found * @see org.mozilla.javascript.Scriptable#has * @see org.mozilla.javascript.ScriptableObject#READONLY * @see org.mozilla.javascript.ScriptableObject#DONTENUM * @see org.mozilla.javascript.ScriptableObject#PERMANENT * @see org.mozilla.javascript.ScriptableObject#EMPTY */ public void setAttributes(int index, int attributes) { checkValidAttributes(attributes); Slot slot = getSlot(null, index); if (slot == null) { throw Context.reportRuntimeError1("msg.prop.not.found", String.valueOf(index)); } slot.attributes = (short) attributes; } /** * Returns the prototype of the object. */ public Scriptable getPrototype() { return prototypeObject; } /** * Sets the prototype of the object. */ public void setPrototype(Scriptable m) { prototypeObject = m; } /** * Returns the parent (enclosing) scope of the object. */ public Scriptable getParentScope() { return parentScopeObject; } /** * Sets the parent (enclosing) scope of the object. */ public void setParentScope(Scriptable m) { parentScopeObject = m; } /** * Returns an array of ids for the properties of the object. * * <p>Any properties with the attribute DONTENUM are not listed. <p> * * @return an array of java.lang.Objects with an entry for every * listed property. Properties accessed via an integer index will * have a corresponding * Integer entry in the returned array. Properties accessed by * a String will have a String entry in the returned array. */ public Object[] getIds() { return getIds(false); } /** * Returns an array of ids for the properties of the object. * * <p>All properties, even those with attribute DONTENUM, are listed. <p> * * @return an array of java.lang.Objects with an entry for every * listed property. Properties accessed via an integer index will * have a corresponding * Integer entry in the returned array. Properties accessed by * a String will have a String entry in the returned array. */ public Object[] getAllIds() { return getIds(true); } /** * Implements the [[DefaultValue]] internal method. * * <p>Note that the toPrimitive conversion is a no-op for * every type other than Object, for which [[DefaultValue]] * is called. See ECMA 9.1.<p> * * A <code>hint</code> of null means "no hint". * * @param typeHint the type hint * @return the default value for the object * * See ECMA 8.6.2.6. */ public Object getDefaultValue(Class typeHint) { Context cx = null; for (int i=0; i < 2; i++) { boolean tryToString; if (typeHint == ScriptRuntime.StringClass) { tryToString = (i == 0); } else { tryToString = (i == 1); } String methodName; Object[] args; if (tryToString) { methodName = "toString"; args = ScriptRuntime.emptyArgs; } else { methodName = "valueOf"; args = new Object[1]; String hint; if (typeHint == null) { hint = "undefined"; } else if (typeHint == ScriptRuntime.StringClass) { hint = "string"; } else if (typeHint == ScriptRuntime.ScriptableClass) { hint = "object"; } else if (typeHint == ScriptRuntime.FunctionClass) { hint = "function"; } else if (typeHint == ScriptRuntime.BooleanClass || typeHint == Boolean.TYPE) { hint = "boolean"; } else if (typeHint == ScriptRuntime.NumberClass || typeHint == ScriptRuntime.ByteClass || typeHint == Byte.TYPE || typeHint == ScriptRuntime.ShortClass || typeHint == Short.TYPE || typeHint == ScriptRuntime.IntegerClass || typeHint == Integer.TYPE || typeHint == ScriptRuntime.FloatClass || typeHint == Float.TYPE || typeHint == ScriptRuntime.DoubleClass || typeHint == Double.TYPE) { hint = "number"; } else { throw Context.reportRuntimeError1( "msg.invalid.type", typeHint.toString()); } args[0] = hint; } Object v = getProperty(this, methodName); if (!(v instanceof Function)) continue; Function fun = (Function) v; if (cx == null) cx = Context.getContext(); v = fun.call(cx, fun.getParentScope(), this, args); if (v != null) { if (!(v instanceof Scriptable)) { return v; } if (v == Undefined.instance || typeHint == ScriptRuntime.ScriptableClass || typeHint == ScriptRuntime.FunctionClass) { return v; } if (tryToString && v instanceof Wrapper) { // Let a wrapped java.lang.String pass for a primitive // string. Object u = ((Wrapper)v).unwrap(); if (u instanceof String) return u; } } } // fall through to error String arg = (typeHint == null) ? "undefined" : typeHint.getName(); throw ScriptRuntime.typeError1("msg.default.value", arg); } /** * Implements the instanceof operator. * * <p>This operator has been proposed to ECMA. * * @param instance The value that appeared on the LHS of the instanceof * operator * @return true if "this" appears in value's prototype chain * */ public boolean hasInstance(Scriptable instance) { // Default for JS objects (other than Function) is to do prototype // chasing. This will be overridden in NativeFunction and non-JS // objects. return ScriptRuntime.jsDelegatesTo(instance, this); } /** * Custom <tt>==</tt> operator. * Must return {@link Scriptable#NOT_FOUND} if this object does not * have custom equality operator for the given value, * <tt>Boolean.TRUE</tt> if this object is equivalent to <tt>value</tt>, * <tt>Boolean.FALSE</tt> if this object is not equivalent to * <tt>value</tt>. * <p> * The default implementation returns Boolean.TRUE * if <tt>this == value</tt> or {@link Scriptable#NOT_FOUND} otherwise. * It indicates that by default custom equality is available only if * <tt>value</tt> is <tt>this</tt> in which case true is returned. */ protected Object equivalentValues(Object value) { return (this == value) ? Boolean.TRUE : Scriptable.NOT_FOUND; } /** * Defines JavaScript objects from a Java class that implements Scriptable. * * If the given class has a method * <pre> * static void init(Context cx, Scriptable scope, boolean sealed);</pre> * * or its compatibility form * <pre> * static void init(Scriptable scope);</pre> * * then it is invoked and no further initialization is done.<p> * * However, if no such a method is found, then the class's constructors and * methods are used to initialize a class in the following manner.<p> * * First, the zero-parameter constructor of the class is called to * create the prototype. If no such constructor exists, * a {@link EvaluatorException} is thrown. <p> * * Next, all methods are scanned for special prefixes that indicate that they * have special meaning for defining JavaScript objects. * These special prefixes are * <ul> * <li><code>jsFunction_</code> for a JavaScript function * <li><code>jsStaticFunction_</code> for a JavaScript function that * is a property of the constructor * <li><code>jsGet_</code> for a getter of a JavaScript property * <li><code>jsSet_</code> for a setter of a JavaScript property * <li><code>jsConstructor</code> for a JavaScript function that * is the constructor * </ul><p> * * If the method's name begins with "jsFunction_", a JavaScript function * is created with a name formed from the rest of the Java method name * following "jsFunction_". So a Java method named "jsFunction_foo" will * define a JavaScript method "foo". Calling this JavaScript function * will cause the Java method to be called. The parameters of the method * must be of number and types as defined by the FunctionObject class. * The JavaScript function is then added as a property * of the prototype. <p> * * If the method's name begins with "jsStaticFunction_", it is handled * similarly except that the resulting JavaScript function is added as a * property of the constructor object. The Java method must be static. * * If the method's name begins with "jsGet_" or "jsSet_", the method is * considered to define a property. Accesses to the defined property * will result in calls to these getter and setter methods. If no * setter is defined, the property is defined as READONLY.<p> * * If the method's name is "jsConstructor", the method is * considered to define the body of the constructor. Only one * method of this name may be defined. * If no method is found that can serve as constructor, a Java * constructor will be selected to serve as the JavaScript * constructor in the following manner. If the class has only one * Java constructor, that constructor is used to define * the JavaScript constructor. If the the class has two constructors, * one must be the zero-argument constructor (otherwise an * {@link EvaluatorException} would have already been thrown * when the prototype was to be created). In this case * the Java constructor with one or more parameters will be used * to define the JavaScript constructor. If the class has three * or more constructors, an {@link EvaluatorException} * will be thrown.<p> * * Finally, if there is a method * <pre> * static void finishInit(Scriptable scope, FunctionObject constructor, * Scriptable prototype)</pre> * * it will be called to finish any initialization. The <code>scope</code> * argument will be passed, along with the newly created constructor and * the newly created prototype.<p> * * @param scope The scope in which to define the constructor * @param clazz The Java class to use to define the JavaScript objects * and properties * @exception IllegalAccessException if access is not available * to a reflected class member * @exception InstantiationException if unable to instantiate * the named class * @exception InvocationTargetException if an exception is thrown * during execution of methods of the named class * @see org.mozilla.javascript.Function * @see org.mozilla.javascript.FunctionObject * @see org.mozilla.javascript.ScriptableObject#READONLY * @see org.mozilla.javascript.ScriptableObject#defineProperty */ public static void defineClass(Scriptable scope, Class clazz) throws IllegalAccessException, InstantiationException, InvocationTargetException { defineClass(scope, clazz, false); } /** * Defines JavaScript objects from a Java class, optionally * allowing sealing. * * Similar to <code>defineClass(Scriptable scope, Class clazz)</code> * except that sealing is allowed. An object that is sealed cannot have * properties added or removed. Note that sealing is not allowed in * the current ECMA/ISO language specification, but is likely for * the next version. * * @param scope The scope in which to define the constructor * @param clazz The Java class to use to define the JavaScript objects * and properties. The class must implement Scriptable. * @param sealed whether or not to create sealed standard objects that * cannot be modified. * @exception IllegalAccessException if access is not available * to a reflected class member * @exception InstantiationException if unable to instantiate * the named class * @exception InvocationTargetException if an exception is thrown * during execution of methods of the named class * @since 1.4R3 */ public static void defineClass(Scriptable scope, Class clazz, boolean sealed) throws IllegalAccessException, InstantiationException, InvocationTargetException { Method[] methods = FunctionObject.getMethodList(clazz); for (int i=0; i < methods.length; i++) { Method method = methods[i]; if (!method.getName().equals("init")) continue; Class[] parmTypes = method.getParameterTypes(); if (parmTypes.length == 3 && parmTypes[0] == ScriptRuntime.ContextClass && parmTypes[1] == ScriptRuntime.ScriptableClass && parmTypes[2] == Boolean.TYPE && Modifier.isStatic(method.getModifiers())) { Object args[] = { Context.getContext(), scope, sealed ? Boolean.TRUE : Boolean.FALSE }; method.invoke(null, args); return; } if (parmTypes.length == 1 && parmTypes[0] == ScriptRuntime.ScriptableClass && Modifier.isStatic(method.getModifiers())) { Object args[] = { scope }; method.invoke(null, args); return; } } // If we got here, there isn't an "init" method with the right // parameter types. Constructor[] ctors = clazz.getConstructors(); Constructor protoCtor = null; for (int i=0; i < ctors.length; i++) { if (ctors[i].getParameterTypes().length == 0) { protoCtor = ctors[i]; break; } } if (protoCtor == null) { throw Context.reportRuntimeError1( "msg.zero.arg.ctor", clazz.getName()); } Scriptable proto = (Scriptable) protoCtor.newInstance(ScriptRuntime.emptyArgs); proto.setPrototype(getObjectPrototype(scope)); String className = proto.getClassName(); // Find out whether there are any methods that begin with // "js". If so, then only methods that begin with special // prefixes will be defined as JavaScript entities. final String functionPrefix = "jsFunction_"; final String staticFunctionPrefix = "jsStaticFunction_"; final String getterPrefix = "jsGet_"; final String setterPrefix = "jsSet_"; final String ctorName = "jsConstructor"; Member ctorMember = FunctionObject.findSingleMethod(methods, ctorName); if (ctorMember == null) { if (ctors.length == 1) { ctorMember = ctors[0]; } else if (ctors.length == 2) { if (ctors[0].getParameterTypes().length == 0) ctorMember = ctors[1]; else if (ctors[1].getParameterTypes().length == 0) ctorMember = ctors[0]; } if (ctorMember == null) { throw Context.reportRuntimeError1( "msg.ctor.multiple.parms", clazz.getName()); } } FunctionObject ctor = new FunctionObject(className, ctorMember, scope); if (ctor.isVarArgsMethod()) { throw Context.reportRuntimeError1 ("msg.varargs.ctor", ctorMember.getName()); } ctor.addAsConstructor(scope, proto); Method finishInit = null; for (int i=0; i < methods.length; i++) { if (methods[i] == ctorMember) { continue; } String name = methods[i].getName(); if (name.equals("finishInit")) { Class[] parmTypes = methods[i].getParameterTypes(); if (parmTypes.length == 3 && parmTypes[0] == ScriptRuntime.ScriptableClass && parmTypes[1] == FunctionObject.class && parmTypes[2] == ScriptRuntime.ScriptableClass && Modifier.isStatic(methods[i].getModifiers())) { finishInit = methods[i]; continue; } } // ignore any compiler generated methods. if (name.indexOf('$') != -1) continue; if (name.equals(ctorName)) continue; String prefix = null; if (name.startsWith(functionPrefix)) { prefix = functionPrefix; } else if (name.startsWith(staticFunctionPrefix)) { prefix = staticFunctionPrefix; if (!Modifier.isStatic(methods[i].getModifiers())) { throw Context.reportRuntimeError( "jsStaticFunction must be used with static method."); } } else if (name.startsWith(getterPrefix)) { prefix = getterPrefix; } else if (name.startsWith(setterPrefix)) { prefix = setterPrefix; } else { continue; } name = name.substring(prefix.length()); if (prefix == setterPrefix) continue; // deal with set when we see get if (prefix == getterPrefix) { if (!(proto instanceof ScriptableObject)) { throw Context.reportRuntimeError2( "msg.extend.scriptable", proto.getClass().toString(), name); } Method setter = FunctionObject.findSingleMethod( methods, setterPrefix + name); int attr = ScriptableObject.PERMANENT | ScriptableObject.DONTENUM | (setter != null ? 0 : ScriptableObject.READONLY); ((ScriptableObject) proto).defineProperty(name, null, methods[i], setter, attr); continue; } FunctionObject f = new FunctionObject(name, methods[i], proto); if (f.isVarArgsConstructor()) { throw Context.reportRuntimeError1 ("msg.varargs.fun", ctorMember.getName()); } Scriptable dest = prefix == staticFunctionPrefix ? ctor : proto; defineProperty(dest, name, f, DONTENUM); if (sealed) { f.sealObject(); } } if (finishInit != null) { // call user code to complete the initialization Object[] finishArgs = { scope, ctor, proto }; finishInit.invoke(null, finishArgs); } if (sealed) { ctor.sealObject(); if (proto instanceof ScriptableObject) { ((ScriptableObject) proto).sealObject(); } } } /** * Define a JavaScript property. * * Creates the property with an initial value and sets its attributes. * * @param propertyName the name of the property to define. * @param value the initial value of the property * @param attributes the attributes of the JavaScript property * @see org.mozilla.javascript.Scriptable#put */ public void defineProperty(String propertyName, Object value, int attributes) { put(propertyName, this, value); setAttributes(propertyName, attributes); } /** * Utility method to add properties to arbitrary Scriptable object. * If destination is instance of ScriptableObject, calls * defineProperty there, otherwise calls put in destination * ignoring attributes */ public static void defineProperty(Scriptable destination, String propertyName, Object value, int attributes) { if (!(destination instanceof ScriptableObject)) { destination.put(propertyName, destination, value); return; } ScriptableObject so = (ScriptableObject)destination; so.defineProperty(propertyName, value, attributes); } /** * Define a JavaScript property with getter and setter side effects. * * If the setter is not found, the attribute READONLY is added to * the given attributes. <p> * * The getter must be a method with zero parameters, and the setter, if * found, must be a method with one parameter.<p> * * @param propertyName the name of the property to define. This name * also affects the name of the setter and getter * to search for. If the propertyId is "foo", then * <code>clazz</code> will be searched for "getFoo" * and "setFoo" methods. * @param clazz the Java class to search for the getter and setter * @param attributes the attributes of the JavaScript property * @see org.mozilla.javascript.Scriptable#put */ public void defineProperty(String propertyName, Class clazz, int attributes) { int length = propertyName.length(); if (length == 0) throw new IllegalArgumentException(); char[] buf = new char[3 + length]; propertyName.getChars(0, length, buf, 3); buf[3] = Character.toUpperCase(buf[3]); buf[0] = 'g'; buf[1] = 'e'; buf[2] = 't'; String getterName = new String(buf); buf[0] = 's'; String setterName = new String(buf); Method[] methods = FunctionObject.getMethodList(clazz); Method getter = FunctionObject.findSingleMethod(methods, getterName); Method setter = FunctionObject.findSingleMethod(methods, setterName); if (setter == null) attributes |= ScriptableObject.READONLY; defineProperty(propertyName, null, getter, setter == null ? null : setter, attributes); } /** * Define a JavaScript property. * * Use this method only if you wish to define getters and setters for * a given property in a ScriptableObject. To create a property without * special getter or setter side effects, use * <code>defineProperty(String,int)</code>. * * If <code>setter</code> is null, the attribute READONLY is added to * the given attributes.<p> * * Several forms of getters or setters are allowed. In all cases the * type of the value parameter can be any one of the following types: * Object, String, boolean, Scriptable, byte, short, int, long, float, * or double. The runtime will perform appropriate conversions based * upon the type of the parameter (see description in FunctionObject). * The first forms are nonstatic methods of the class referred to * by 'this': * <pre> * Object getFoo(); * void setFoo(SomeType value);</pre> * Next are static methods that may be of any class; the object whose * property is being accessed is passed in as an extra argument: * <pre> * static Object getFoo(ScriptableObject obj); * static void setFoo(ScriptableObject obj, SomeType value);</pre> * Finally, it is possible to delegate to another object entirely using * the <code>delegateTo</code> parameter. In this case the methods are * nonstatic methods of the class delegated to, and the object whose * property is being accessed is passed in as an extra argument: * <pre> * Object getFoo(ScriptableObject obj); * void setFoo(ScriptableObject obj, SomeType value);</pre> * * @param propertyName the name of the property to define. * @param delegateTo an object to call the getter and setter methods on, * or null, depending on the form used above. * @param getter the method to invoke to get the value of the property * @param setter the method to invoke to set the value of the property * @param attributes the attributes of the JavaScript property */ public void defineProperty(String propertyName, Object delegateTo, Method getter, Method setter, int attributes) { if (delegateTo == null && (Modifier.isStatic(getter.getModifiers()))) delegateTo = HAS_STATIC_ACCESSORS; Class[] parmTypes = getter.getParameterTypes(); if (parmTypes.length != 0) { if (parmTypes.length != 1 || parmTypes[0] != ScriptRuntime.ScriptableObjectClass) { throw Context.reportRuntimeError1( "msg.bad.getter.parms", getter.toString()); } } else if (delegateTo != null) { throw Context.reportRuntimeError1( "msg.obj.getter.parms", getter.toString()); } if (setter != null) { if ((delegateTo == HAS_STATIC_ACCESSORS) != (Modifier.isStatic(setter.getModifiers()))) { throw Context.reportRuntimeError0("msg.getter.static"); } parmTypes = setter.getParameterTypes(); if (parmTypes.length == 2) { if (parmTypes[0] != ScriptRuntime.ScriptableObjectClass) { throw Context.reportRuntimeError0("msg.setter2.parms"); } if (delegateTo == null) { throw Context.reportRuntimeError1( "msg.setter1.parms", setter.toString()); } } else if (parmTypes.length == 1) { if (delegateTo != null) { throw Context.reportRuntimeError1( "msg.setter2.expected", setter.toString()); } } else { throw Context.reportRuntimeError0("msg.setter.parms"); } Class setterType = parmTypes[parmTypes.length - 1]; int setterTypeTag = FunctionObject.getTypeTag(setterType); if (setterTypeTag == FunctionObject.JAVA_UNSUPPORTED_TYPE) { throw Context.reportRuntimeError2( "msg.setter2.expected", setterType.getName(), setter.toString()); } } ClassCache cache = ClassCache.get(this); GetterSlot gslot = new GetterSlot(); gslot.delegateTo = delegateTo; gslot.getter = new MemberBox(getter, cache); gslot.getter.prepareInvokerOptimization(); if (setter != null) { gslot.setter = new MemberBox(setter, cache); gslot.setter.prepareInvokerOptimization(); } gslot.attributes = (short) attributes; gslot.complexSlotFlag = 1; Slot inserted = addSlot(propertyName, propertyName.hashCode(), gslot); if (inserted != gslot) { throw new RuntimeException("Property already exists"); } } /** * Search for names in a class, adding the resulting methods * as properties. * * <p> Uses reflection to find the methods of the given names. Then * FunctionObjects are constructed from the methods found, and * are added to this object as properties with the given names. * * @param names the names of the Methods to add as function properties * @param clazz the class to search for the Methods * @param attributes the attributes of the new properties * @see org.mozilla.javascript.FunctionObject */ public void defineFunctionProperties(String[] names, Class clazz, int attributes) { Method[] methods = FunctionObject.getMethodList(clazz); for (int i=0; i < names.length; i++) { String name = names[i]; Method m = FunctionObject.findSingleMethod(methods, name); if (m == null) { throw Context.reportRuntimeError2( "msg.method.not.found", name, clazz.getName()); } FunctionObject f = new FunctionObject(name, m, this); defineProperty(name, f, attributes); } } /** * Get the Object.prototype property. * See ECMA 15.2.4. */ public static Scriptable getObjectPrototype(Scriptable scope) { return getClassPrototype(scope, "Object"); } /** * Get the Function.prototype property. * See ECMA 15.3.4. */ public static Scriptable getFunctionPrototype(Scriptable scope) { return getClassPrototype(scope, "Function"); } /** * Get the prototype for the named class. * * For example, <code>getClassPrototype(s, "Date")</code> will first * walk up the parent chain to find the outermost scope, then will * search that scope for the Date constructor, and then will * return Date.prototype. If any of the lookups fail, or * the prototype is not a JavaScript object, then null will * be returned. * * @param scope an object in the scope chain * @param className the name of the constructor * @return the prototype for the named class, or null if it * cannot be found. */ public static Scriptable getClassPrototype(Scriptable scope, String className) { scope = getTopLevelScope(scope); Object ctor = getProperty(scope, className); Object proto; if (ctor instanceof BaseFunction) { proto = ((BaseFunction)ctor).getPrototypeProperty(); } else if (ctor instanceof Scriptable) { Scriptable ctorObj = (Scriptable)ctor; proto = ctorObj.get("prototype", ctorObj); } else { return null; } if (proto instanceof Scriptable) { return (Scriptable)proto; } return null; } /** * Get the global scope. * * <p>Walks the parent scope chain to find an object with a null * parent scope (the global object). * * @param obj a JavaScript object * @return the corresponding global scope */ public static Scriptable getTopLevelScope(Scriptable obj) { for (;;) { Scriptable parent = obj.getParentScope(); if (parent == null) { return obj; } obj = parent; } } /** * Seal this object. * * A sealed object may not have properties added or removed. Once * an object is sealed it may not be unsealed. * * @since 1.4R3 */ public synchronized void sealObject() { if (count >= 0) { count = -1 - count; } } /** * Return true if this object is sealed. * * It is an error to attempt to add or remove properties to * a sealed object. * * @return true if sealed, false otherwise. * @since 1.4R3 */ public final boolean isSealed() { return count < 0; } /** * Gets a named property from an object or any object in its prototype chain. * <p> * Searches the prototype chain for a property named <code>name</code>. * <p> * @param obj a JavaScript object * @param name a property name * @return the value of a property with name <code>name</code> found in * <code>obj</code> or any object in its prototype chain, or * <code>Scriptable.NOT_FOUND</code> if not found * @since 1.5R2 */ public static Object getProperty(Scriptable obj, String name) { Scriptable start = obj; Object result; do { result = obj.get(name, start); if (result != Scriptable.NOT_FOUND) break; obj = obj.getPrototype(); } while (obj != null); return result; } /** * Gets an indexed property from an object or any object in its prototype chain. * <p> * Searches the prototype chain for a property with integral index * <code>index</code>. Note that if you wish to look for properties with numerical * but non-integral indicies, you should use getProperty(Scriptable,String) with * the string value of the index. * <p> * @param obj a JavaScript object * @param index an integral index * @return the value of a property with index <code>index</code> found in * <code>obj</code> or any object in its prototype chain, or * <code>Scriptable.NOT_FOUND</code> if not found * @since 1.5R2 */ public static Object getProperty(Scriptable obj, int index) { Scriptable start = obj; Object result; do { result = obj.get(index, start); if (result != Scriptable.NOT_FOUND) break; obj = obj.getPrototype(); } while (obj != null); return result; } /** * Returns whether a named property is defined in an object or any object * in its prototype chain. * <p> * Searches the prototype chain for a property named <code>name</code>. * <p> * @param obj a JavaScript object * @param name a property name * @return the true if property was found * @since 1.5R2 */ public static boolean hasProperty(Scriptable obj, String name) { return null != getBase(obj, name); } /** * Returns whether an indexed property is defined in an object or any object * in its prototype chain. * <p> * Searches the prototype chain for a property with index <code>index</code>. * <p> * @param obj a JavaScript object * @param index a property index * @return the true if property was found * @since 1.5R2 */ public static boolean hasProperty(Scriptable obj, int index) { return null != getBase(obj, index); } /** * Puts a named property in an object or in an object in its prototype chain. * <p> * Seaches for the named property in the prototype chain. If it is found, * the value of the property is changed. If it is not found, a new * property is added in <code>obj</code>. * @param obj a JavaScript object * @param name a property name * @param value any JavaScript value accepted by Scriptable.put * @since 1.5R2 */ public static void putProperty(Scriptable obj, String name, Object value) { Scriptable base = getBase(obj, name); if (base == null) base = obj; base.put(name, obj, value); } /** * Puts an indexed property in an object or in an object in its prototype chain. * <p> * Seaches for the indexed property in the prototype chain. If it is found, * the value of the property is changed. If it is not found, a new * property is added in <code>obj</code>. * @param obj a JavaScript object * @param index a property index * @param value any JavaScript value accepted by Scriptable.put * @since 1.5R2 */ public static void putProperty(Scriptable obj, int index, Object value) { Scriptable base = getBase(obj, index); if (base == null) base = obj; base.put(index, obj, value); } /** * Removes the property from an object or its prototype chain. * <p> * Searches for a property with <code>name</code> in obj or * its prototype chain. If it is found, the object's delete * method is called. * @param obj a JavaScript object * @param name a property name * @return true if the property doesn't exist or was successfully removed * @since 1.5R2 */ public static boolean deleteProperty(Scriptable obj, String name) { Scriptable base = getBase(obj, name); if (base == null) return true; base.delete(name); return !base.has(name, obj); } /** * Removes the property from an object or its prototype chain. * <p> * Searches for a property with <code>index</code> in obj or * its prototype chain. If it is found, the object's delete * method is called. * @param obj a JavaScript object * @param index a property index * @return true if the property doesn't exist or was successfully removed * @since 1.5R2 */ public static boolean deleteProperty(Scriptable obj, int index) { Scriptable base = getBase(obj, index); if (base == null) return true; base.delete(index); return !base.has(index, obj); } /** * Returns an array of all ids from an object and its prototypes. * <p> * @param obj a JavaScript object * @return an array of all ids from all object in the prototype chain. * If a given id occurs multiple times in the prototype chain, * it will occur only once in this list. * @since 1.5R2 */ public static Object[] getPropertyIds(Scriptable obj) { if (obj == null) { return ScriptRuntime.emptyArgs; } Object[] result = obj.getIds(); ObjToIntMap map = null; for (;;) { obj = obj.getPrototype(); if (obj == null) { break; } Object[] ids = obj.getIds(); if (ids.length == 0) { continue; } - if (result.length == 0) { - result = ids; - continue; - } if (map == null) { + if (result.length == 0) { + result = ids; + continue; + } + map = new ObjToIntMap(result.length + ids.length); for (int i = 0; i != result.length; ++i) { map.intern(result[i]); } - result = null; + result = null; // Allow to GC the result } for (int i = 0; i != ids.length; ++i) { map.intern(ids[i]); } } if (map != null) { result = map.getKeys(); } return result; } /** * Call a method of an object. * @param obj the JavaScript object * @param methodName the name of the function property * @param args the arguments for the call * * @see Context#getCurrentContext() */ public static Object callMethod(Scriptable obj, String methodName, Object[] args) { return callMethod(null, obj, methodName, args); } /** * Call a method of an object. * @param cx the Context object associated with the current thread. * @param obj the JavaScript object * @param methodName the name of the function property * @param args the arguments for the call */ public static Object callMethod(Context cx, Scriptable obj, String methodName, Object[] args) { Object funObj = getProperty(obj, methodName); if (!(funObj instanceof Function)) { throw ScriptRuntime.notFunctionError(obj, methodName); } Function fun = (Function)funObj; Scriptable scope = ScriptableObject.getTopLevelScope(fun); // XXX: The following is only necessary for dynamic scope setup, // but to check for that Context instance is required. // Since it should not harm non-dynamic scope setup, do it always // for now. Scriptable dynamicScope = ScriptableObject.getTopLevelScope(obj); scope = ScriptRuntime.checkDynamicScope(dynamicScope, scope); if (cx != null) { return fun.call(cx, scope, obj, args); } else { return Context.call(null, fun, scope, obj, args); } } private static Scriptable getBase(Scriptable obj, String name) { do { if (obj.has(name, obj)) break; obj = obj.getPrototype(); } while(obj != null); return obj; } private static Scriptable getBase(Scriptable obj, int index) { do { if (obj.has(index, obj)) break; obj = obj.getPrototype(); } while(obj != null); return obj; } /** * Get arbitrary application-specific value associated with this object. * @param key key object to select particular value. * @see #associateValue(Object key, Object value) */ public final Object getAssociatedValue(Object key) { Hashtable h = associatedValues; if (h == null) return null; return h.get(key); } /** * Get arbitrary application-specific value associated with the top scope * of the given scope. * The method first calls {@link #getTopLevelScope(Scriptable scope)} * and then searches the prototype chain of the top scope for the first * object containing the associated value with the given key. * * @param scope the starting scope. * @param key key object to select particular value. * @see #getAssociatedValue(Object key) */ public static Object getTopScopeValue(Scriptable scope, Object key) { scope = ScriptableObject.getTopLevelScope(scope); for (;;) { if (scope instanceof ScriptableObject) { ScriptableObject so = (ScriptableObject)scope; Object value = so.getAssociatedValue(key); if (value != null) { return value; } } scope = scope.getPrototype(); if (scope == null) { return null; } } } /** * Associate arbitrary application-specific value with this object. * Value can only be associated with the given object and key only once. * The method ignores any subsequent attempts to change the already * associated value. * <p> The associated values are not serilized. * @param key key object to select particular value. * @param value the value to associate * @return the passed value if the method is called first time for the * given key or old value for any subsequent calls. * @see #getAssociatedValue(Object key) */ public final Object associateValue(Object key, Object value) { if (value == null) throw new IllegalArgumentException(); Hashtable h = associatedValues; if (h == null) { synchronized (this) { h = associatedValues; if (h == null) { h = new Hashtable(); associatedValues = h; } } } return Kit.initHash(h, key, value); } private Object getByGetter(GetterSlot slot, Scriptable start) { Object getterThis; Object[] args; if (slot.delegateTo == null) { if (start != this) { // Walk the prototype chain to find an appropriate // object to invoke the getter on. Class clazz = slot.getter.getDeclaringClass(); while (!clazz.isInstance(start)) { start = start.getPrototype(); if (start == this) { break; } if (start == null) { start = this; break; } } } getterThis = start; args = ScriptRuntime.emptyArgs; } else { getterThis = slot.delegateTo; args = new Object[] { this }; } return slot.getter.invoke(getterThis, args); } private void setBySetter(GetterSlot slot, Scriptable start, Object value) { if (start != this) { if (slot.delegateTo != null || !slot.setter.getDeclaringClass().isInstance(start)) { start.put(slot.stringKey, start, value); return; } } Object setterThis; Object[] args; Object setterResult; Context cx = Context.getContext(); Class pTypes[] = slot.setter.argTypes; Class desired = pTypes[pTypes.length - 1]; // ALERT: cache tag since it is already calculated in defineProperty ? int tag = FunctionObject.getTypeTag(desired); Object actualArg = FunctionObject.convertArg(cx, start, value, tag); if (slot.delegateTo == null) { setterThis = start; args = new Object[] { actualArg }; } else { if (start != this) Kit.codeBug(); setterThis = slot.delegateTo; args = new Object[] { this, actualArg }; } // Check start is sealed: start is always instance of ScriptableObject // due to logic in if (start != this) above if (((ScriptableObject)start).isSealed()) { throw Context.reportRuntimeError1("msg.modify.sealed", slot.stringKey); } setterResult = slot.setter.invoke(setterThis, args); if (slot.setter.method().getReturnType() != Void.TYPE) { // Replace Getter slot by a simple one Slot replacement = new Slot(); replacement.intKey = slot.intKey; replacement.stringKey = slot.stringKey; replacement.attributes = slot.attributes; replacement.value = setterResult; synchronized (this) { int i = getSlotPosition(slots, slot.stringKey, slot.intKey); // Check slot was not deleted/replaced before synchronization if (i >= 0 && slots[i] == slot) { slots[i] = replacement; // It is important to make sure that lastAccess != slot // to prevent accessing the old slot via lastAccess and // then invoking setter one more time lastAccess = replacement; } } } } private Slot getNamedSlot(String name) { // Query last access cache and check that it was not deleted Slot slot = lastAccess; if (name == slot.stringKey && slot.wasDeleted == 0) { return slot; } int hash = name.hashCode(); Slot[] slots = this.slots; // Get stable local reference int i = getSlotPosition(slots, name, hash); if (i < 0) { return null; } slot = slots[i]; // Update cache - here stringKey.equals(name) holds, but it can be // that slot.stringKey != name. To make last name cache work, need // to change the key slot.stringKey = name; lastAccess = slot; return slot; } private Slot getSlot(String id, int index) { Slot[] slots = this.slots; // Get local copy int i = getSlotPosition(slots, id, index); return (i < 0) ? null : slots[i]; } private static int getSlotPosition(Slot[] slots, String id, int index) { if (slots != null) { int start = (index & 0x7fffffff) % slots.length; int i = start; do { Slot slot = slots[i]; if (slot == null) break; if (slot != REMOVED && slot.intKey == index && (slot.stringKey == id || (id != null && id.equals(slot.stringKey)))) { return i; } if (++i == slots.length) i = 0; } while (i != start); } return -1; } /** * Add a new slot to the hash table. * * This method must be synchronized since it is altering the hash * table itself. Note that we search again for the slot to set * since another thread could have added the given property or * caused the table to grow while this thread was searching. */ private synchronized Slot addSlot(String id, int index, Slot newSlot) { if (isSealed()) { String str = (id != null) ? id : Integer.toString(index); throw Context.reportRuntimeError1("msg.add.sealed", str); } if (slots == null) { slots = new Slot[5]; } return addSlotImpl(id, index, newSlot); } // Must be inside synchronized (this) private Slot addSlotImpl(String id, int index, Slot newSlot) { int start = (index & 0x7fffffff) % slots.length; int i = start; for (;;) { Slot slot = slots[i]; if (slot == null || slot == REMOVED) { if ((4 * (count + 1)) > (3 * slots.length)) { grow(); return addSlotImpl(id, index, newSlot); } slot = (newSlot == null) ? new Slot() : newSlot; slot.stringKey = id; slot.intKey = index; slots[i] = slot; count++; return slot; } if (slot.intKey == index && (slot.stringKey == id || (id != null && id.equals(slot.stringKey)))) { return slot; } if (++i == slots.length) i = 0; if (i == start) { // slots should never be full or bug in grow code throw new IllegalStateException(); } } } /** * Remove a slot from the hash table. * * This method must be synchronized since it is altering the hash * table itself. We might be able to optimize this more, but * deletes are not common. */ private synchronized void removeSlot(String name, int index) { if (isSealed()) { String str = (name != null) ? name : Integer.toString(index); throw Context.reportRuntimeError1("msg.remove.sealed", str); } int i = getSlotPosition(slots, name, index); if (i >= 0) { Slot slot = slots[i]; if ((slot.attributes & PERMANENT) == 0) { // Mark the slot as removed to handle a case when // another thread manages to put just removed slot // into lastAccess cache. slot.wasDeleted = (byte)1; if (slot == lastAccess) { lastAccess = REMOVED; } count--; if (count != 0) { slots[i] = REMOVED; } else { // With no slots it is OK to mark with null. slots[i] = null; } } } } // Grow the hash table to accommodate new entries. // // Note that by assigning the new array back at the end we // can continue reading the array from other threads. // Must be inside synchronized (this) private void grow() { Slot[] newSlots = new Slot[slots.length*2 + 1]; for (int j=slots.length-1; j >= 0 ; j--) { Slot slot = slots[j]; if (slot == null || slot == REMOVED) continue; int k = (slot.intKey & 0x7fffffff) % newSlots.length; while (newSlots[k] != null) if (++k == newSlots.length) k = 0; // The end of the "synchronized" statement will cause the memory // writes to be propagated on a multiprocessor machine. We want // to make sure that the new table is prepared to be read. // XXX causes the 'this' pointer to be null in calling stack frames // on the MS JVM //synchronized (slot) { } newSlots[k] = slot; } slots = newSlots; } Object[] getIds(boolean getAll) { Slot[] s = slots; Object[] a = ScriptRuntime.emptyArgs; if (s == null) return a; int c = 0; for (int i=0; i < s.length; i++) { Slot slot = s[i]; if (slot == null || slot == REMOVED) continue; if (getAll || (slot.attributes & DONTENUM) == 0) { if (c == 0) a = new Object[s.length - i]; a[c++] = slot.stringKey != null ? (Object) slot.stringKey : new Integer(slot.intKey); } } if (c == a.length) return a; Object[] result = new Object[c]; System.arraycopy(a, 0, result, 0, c); return result; } private synchronized void writeObject(ObjectOutputStream out) throws IOException { out.defaultWriteObject(); int N = count; if (N < 0) { N = -1 - count; } Slot[] s = slots; if (s == null) { if (N != 0) Kit.codeBug(); out.writeInt(0); } else { out.writeInt(s.length); for (int i = 0; N != 0; ++i) { Slot slot = s[i]; if (slot != null && slot != REMOVED) { --N; out.writeObject(slot); } } } } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); lastAccess = REMOVED; int capacity = in.readInt(); if (capacity != 0) { slots = new Slot[capacity]; int N = count; boolean wasSealed = false; if (N < 0) { N = -1 - N; wasSealed = true; } count = 0; for (int i = 0; i != N; ++i) { Slot s = (Slot)in.readObject(); addSlotImpl(s.stringKey, s.intKey, s); } if (wasSealed) { count = - 1 - count; } } } /** * The prototype of this object. */ private Scriptable prototypeObject; /** * The parent scope of this object. */ private Scriptable parentScopeObject; private static final Object HAS_STATIC_ACCESSORS = Void.TYPE; private static final Slot REMOVED = new Slot(); private transient Slot[] slots; // If count >= 0, it gives number of keys or if count < 0, // it indicates sealed object where -1 - count gives number of keys private int count; // cache; may be removed for smaller memory footprint private transient Slot lastAccess = REMOVED; // associated values are not serialized private transient volatile Hashtable associatedValues; private static class Slot implements Serializable { static final int HAS_GETTER = 0x01; static final int HAS_SETTER = 0x02; private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); if (stringKey != null) { intKey = stringKey.hashCode(); } complexSlotFlag = (this instanceof GetterSlot) ? (byte)1 : (byte)0; } int intKey; String stringKey; Object value; short attributes; transient byte complexSlotFlag; transient byte wasDeleted; } private static class GetterSlot extends Slot { Object delegateTo; MemberBox getter; MemberBox setter; } }
false
false
null
null
diff --git a/onebusaway-nyc-admin-webapp/src/main/java/org/onebusaway/nyc/admin/service/bundle/impl/BundleBuildingServiceImpl.java b/onebusaway-nyc-admin-webapp/src/main/java/org/onebusaway/nyc/admin/service/bundle/impl/BundleBuildingServiceImpl.java index 4527c1c95..0e628a2c2 100644 --- a/onebusaway-nyc-admin-webapp/src/main/java/org/onebusaway/nyc/admin/service/bundle/impl/BundleBuildingServiceImpl.java +++ b/onebusaway-nyc-admin-webapp/src/main/java/org/onebusaway/nyc/admin/service/bundle/impl/BundleBuildingServiceImpl.java @@ -1,492 +1,493 @@ package org.onebusaway.nyc.admin.service.bundle.impl; import org.onebusaway.container.ContainerLibrary; import org.onebusaway.gtfs.impl.GtfsRelationalDaoImpl; import org.onebusaway.nyc.admin.model.BundleBuildRequest; import org.onebusaway.nyc.admin.model.BundleBuildResponse; import org.onebusaway.nyc.admin.service.FileService; import org.onebusaway.nyc.admin.service.bundle.BundleBuildingService; import org.onebusaway.nyc.admin.util.FileUtils; import org.onebusaway.nyc.admin.util.ProcessUtil; import org.onebusaway.nyc.transit_data_federation.bundle.model.NycFederatedTransitDataBundle; import org.onebusaway.nyc.transit_data_federation.bundle.tasks.stif.StifTask; import org.onebusaway.nyc.util.configuration.ConfigurationService; import org.onebusaway.transit_data_federation.bundle.FederatedTransitDataBundleCreator; import org.onebusaway.transit_data_federation.bundle.model.GtfsBundle; import org.onebusaway.transit_data_federation.bundle.model.GtfsBundles; import org.onebusaway.transit_data_federation.bundle.model.TaskDefinition; import org.onebusaway.transit_data_federation.services.FederatedTransitDataBundle; import org.apache.log4j.Layout; import org.apache.log4j.SimpleLayout; import org.apache.log4j.WriterAppender; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.remoting.RemoteConnectFailureException; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class BundleBuildingServiceImpl implements BundleBuildingService { private static final String BUNDLE_RESOURCE = "classpath:org/onebusaway/transit_data_federation/bundle/application-context-bundle-admin.xml"; private static final String DEFAULT_STIF_CLEANUP_URL = "https://github.com/camsys/onebusaway-nyc/raw/master/onebusaway-nyc-stif-loader/fix-stif-date-codes.py"; private static final String DEFAULT_AGENCY = "MTA"; private static final String DATA_DIR = "data"; private static final String OUTPUT_DIR = "outputs"; private static final String INPUTS_DIR = "inputs"; private static Logger _log = LoggerFactory.getLogger(BundleBuildingServiceImpl.class); private FileService _fileService; private ConfigurationService configurationService; @Autowired public void setFileService(FileService service) { _fileService = service; } /** * @param configurationService the configurationService to set */ @Autowired public void setConfigurationService(ConfigurationService configurationService) { this.configurationService = configurationService; } @Override public void setup() { } @Override public void doBuild(BundleBuildRequest request, BundleBuildResponse response) { response.setId(request.getId()); download(request, response); prepare(request, response); build(request, response); assemble(request, response); upload(request, response); response.addStatusMessage("Bundle build process complete"); } /** * download from S3 and stage for building */ @Override public void download(BundleBuildRequest request, BundleBuildResponse response) { String bundleDir = request.getBundleDirectory(); String tmpDirectory = request.getTmpDirectory(); if (tmpDirectory == null) { tmpDirectory = new FileUtils().createTmpDirectory(); request.setTmpDirectory(tmpDirectory); } response.setTmpDirectory(tmpDirectory); // download gtfs List<String> gtfs = _fileService.list( bundleDir + "/" + _fileService.getGtfsPath(), -1); for (String file : gtfs) { response.addStatusMessage("downloading gtfs " + file); response.addGtfsFile(_fileService.get(file, tmpDirectory)); } // download stifs List<String> stif = _fileService.list( bundleDir + "/" + _fileService.getStifPath(), -1); for (String file : stif) { response.addStatusMessage("downloading stif " + file); response.addStifZipFile(_fileService.get(file, tmpDirectory)); } } /** * stage file locations for bundle building. */ @Override public void prepare(BundleBuildRequest request, BundleBuildResponse response) { response.addStatusMessage("preparing for build"); FileUtils fs = new FileUtils(); // copy source data to inputs String rootPath = request.getTmpDirectory() + File.separator + request.getBundleName(); response.setBundleRootDirectory(rootPath); File rootDir = new File(rootPath); rootDir.mkdirs(); String inputsPath = request.getTmpDirectory() + File.separator + request.getBundleName() + File.separator + INPUTS_DIR; response.setBundleInputDirectory(inputsPath); File inputsDir = new File(inputsPath); inputsDir.mkdirs(); String outputsPath = request.getTmpDirectory() + File.separator + request.getBundleName() + File.separator + OUTPUT_DIR; response.setBundleOutputDirectory(outputsPath); File outputsDir = new File(outputsPath); outputsDir.mkdirs(); String dataPath = request.getTmpDirectory() + File.separator + request.getBundleName() + File.separator + DATA_DIR; // create STIF dir as well String stifPath = request.getTmpDirectory() + File.separator + "stif"; File stifDir = new File(stifPath); _log.info("creating stif directory=" + stifPath); stifDir.mkdirs(); File dataDir = new File(dataPath); response.setBundleDataDirectory(dataPath); dataDir.mkdirs(); for (String gtfs : response.getGtfsList()) { String outputFilename = inputsPath + File.separator + fs.parseFileName(gtfs); fs.copyFiles(new File(gtfs), new File(outputFilename)); } for (String stif: response.getStifZipList()) { String outputFilename = inputsPath + File.separator + fs.parseFileName(stif); fs.copyFiles(new File(stif), new File(outputFilename)); } for (String stifZip : response.getStifZipList()) { _log.info("stif copying " + stifZip + " to " + request.getTmpDirectory() + File.separator + "stif"); new FileUtils().unzip(stifZip, request.getTmpDirectory() + File.separator + "stif"); } // stage baseLocations InputStream baseLocationsStream = this.getClass().getResourceAsStream("/BaseLocations.txt"); new FileUtils().copy(baseLocationsStream, dataPath + File.separator + "BaseLocations.txt"); // clean stifs via STIF_PYTHON_CLEANUP_SCRIPT try { File[] stifDirectories = stifDir.listFiles(); if (stifDirectories != null) { fs = new FileUtils(request.getTmpDirectory()); String stifUtilUrl = getStifCleanupUrl(); response.addStatusMessage("downloading " + stifUtilUrl + " to clean stifs"); fs.wget(stifUtilUrl); String stifUtilName = fs.parseFileName(stifUtilUrl); // make executable fs.chmod("500", request.getTmpDirectory() + File.separator + stifUtilName); // for each subdirectory of stif, run the script for (File stifSubDir : stifDirectories) { String cmd = request.getTmpDirectory() + File.separator + stifUtilName + " " + stifSubDir.getCanonicalPath(); // kick off process and collect output ProcessUtil pu = new ProcessUtil(cmd); pu.exec(); if (pu.getReturnCode() == null || !pu.getReturnCode().equals(0)) { // obanyc-1692, do not send to client String returnCodeMessage = stifUtilName + " exited with return code " + pu.getReturnCode(); _log.info(returnCodeMessage); _log.info("output=" + pu.getOutput()); _log.info("error=" + pu.getError()); } if (pu.getException() != null) { response.setException(pu.getException()); } } response.addStatusMessage("stif cleaning complete"); } } catch (Exception any) { response.setException(any); } } private String getStifCleanupUrl() { if (configurationService != null) { try { return configurationService.getConfigurationValueAsString("admin.stif_cleanup_url", DEFAULT_STIF_CLEANUP_URL); } catch (RemoteConnectFailureException e){ _log.error("stifCleanupUrl failed:", e); return DEFAULT_STIF_CLEANUP_URL; } } return DEFAULT_STIF_CLEANUP_URL; } /** * call FederatedTransitDataBundleCreator */ @Override public int build(BundleBuildRequest request, BundleBuildResponse response) { /* * this follows the example from FederatedTransitDataBundleCreatorMain */ PrintStream stdOut = System.out; PrintStream logFile = null; // pass a mini spring context to the bundle builder so we can cleanup ConfigurableApplicationContext context = null; try { File outputPath = new File(response.getBundleDataDirectory()); // beans assume bundlePath is set -- this will be where files are written! System.setProperty("bundlePath", outputPath.getAbsolutePath()); String logFilename = outputPath + File.separator + "bundleBuilder.out.txt"; logFile = new PrintStream(new FileOutputStream(new File(logFilename))); // swap standard out for logging System.setOut(logFile); configureLogging(System.out); FederatedTransitDataBundleCreator creator = new FederatedTransitDataBundleCreator(); Map<String, BeanDefinition> beans = new HashMap<String, BeanDefinition>(); creator.setContextBeans(beans); List<GtfsBundle> gtfsBundles = createGtfsBundles(response); List<String> contextPaths = new ArrayList<String>(); contextPaths.add(BUNDLE_RESOURCE); BeanDefinitionBuilder bean = BeanDefinitionBuilder.genericBeanDefinition(GtfsBundles.class); bean.addPropertyValue("bundles", gtfsBundles); beans.put("gtfs-bundles", bean.getBeanDefinition()); bean = BeanDefinitionBuilder.genericBeanDefinition(GtfsRelationalDaoImpl.class); beans.put("gtfsRelationalDaoImpl", bean.getBeanDefinition()); // configure for NYC specifics BeanDefinitionBuilder bundle = BeanDefinitionBuilder.genericBeanDefinition(FederatedTransitDataBundle.class); bundle.addPropertyValue("path", outputPath); beans.put("bundle", bundle.getBeanDefinition()); BeanDefinitionBuilder nycBundle = BeanDefinitionBuilder.genericBeanDefinition(NycFederatedTransitDataBundle.class); nycBundle.addPropertyValue("path", outputPath); beans.put("nycBundle", nycBundle.getBeanDefinition()); BeanDefinitionBuilder stifLoaderTask = BeanDefinitionBuilder.genericBeanDefinition(StifTask.class); stifLoaderTask.addPropertyValue("stifPath", request.getTmpDirectory() + File.separator + "stif");// TODO this is a convention, pull out into config? String notInServiceFilename = request.getTmpDirectory() + File.separator + "NotInServiceDSCs.txt"; new FileUtils().createFile(notInServiceFilename, listToFile(request.getNotInServiceDSCList())); stifLoaderTask.addPropertyValue("notInServiceDscPath", notInServiceFilename); stifLoaderTask.addPropertyValue("fallBackToStifBlocks", Boolean.TRUE); stifLoaderTask.addPropertyValue("logPath", response.getBundleOutputDirectory()); beans.put("stifLoaderTask", stifLoaderTask.getBeanDefinition()); BeanDefinitionBuilder task = BeanDefinitionBuilder.genericBeanDefinition(TaskDefinition.class); task.addPropertyValue("taskName", "stif"); task.addPropertyValue("afterTaskName", "gtfs"); task.addPropertyValue("beforeTaskName", "transit_graph"); task.addPropertyReference("task", "stifLoaderTask"); // this name is not significant, its loaded by type beans.put("nycStifTask", task.getBeanDefinition()); _log.debug("setting outputPath=" + outputPath); creator.setOutputPath(outputPath); creator.setContextPaths(contextPaths); // manage our own context to recover from exceptions Map<String, BeanDefinition> contextBeans = new HashMap<String, BeanDefinition>(); contextBeans.putAll(beans); context = ContainerLibrary.createContext(contextPaths, contextBeans); creator.setContext(context); response.addStatusMessage("building bundle"); creator.run(); response.addStatusMessage("bundle build complete"); return 0; } catch (Exception e) { _log.error(e.toString(), e); response.setException(e); return 1; } catch (Throwable t) { _log.error(t.toString(), t); response.setException(new RuntimeException(t.toString())); return -1; } finally { if (context != null) { try { /* * here we cleanup the spring context so we can process follow on requests. */ context.stop(); context.close(); } catch (Throwable t) { _log.error("buried context close:", t); } } // restore standard out deconfigureLogging(System.out); System.setOut(stdOut); if (logFile != null) { logFile.close(); } } } /** * tear down the logger for the bundle building activity. */ private void deconfigureLogging(OutputStream os) { _log.info("deconfiguring logging"); try { os.flush(); os.close(); } catch (Exception any) { _log.error("deconfigure logging failed:", any); } org.apache.log4j.Logger logger = org.apache.log4j.Logger.getRootLogger(); logger.removeAppender("bundlebuilder.out"); } /** * setup a logger just for the bundle building activity. */ private void configureLogging(OutputStream os) { Layout layout = new SimpleLayout(); WriterAppender wa = new WriterAppender(layout, os); wa.setName("bundlebuilder.out"); // introducing log4j dependency here org.apache.log4j.Logger logger = org.apache.log4j.Logger.getRootLogger(); logger.addAppender(wa); _log.info("configuring logging"); } /** * arrange files for tar'ing into bundle format */ @Override public void assemble(BundleBuildRequest request, BundleBuildResponse response) { response.addStatusMessage("compressing results"); FileUtils fs = new FileUtils(); // build BundleMetaData.json new BundleBuildingUtil().generateJsonMetadata(request, response); String[] paths = {request.getBundleName()}; String filename = request.getTmpDirectory() + File.separator + request.getBundleName() + ".tar.gz"; response.setBundleTarFilename(filename); response.addStatusMessage("creating bundle=" + filename + " for root dir=" + request.getTmpDirectory()); String baseDir = request.getTmpDirectory(); fs.tarcvf(baseDir, paths, filename); // now copy inputs and outputs to root for easy access // inputs String inputsPath = request.getTmpDirectory() + File.separator + INPUTS_DIR; File inputsDestDir = new File(inputsPath); inputsDestDir.mkdir(); File inputsDir = new File(response.getBundleInputDirectory()); File[] inputFiles = inputsDir.listFiles(); if (inputFiles != null) { for (File input : inputFiles) { fs.copyFiles(input, new File(inputsPath + File.separator + input.getName())); } } // outputs String outputsPath = request.getTmpDirectory() + File.separator + OUTPUT_DIR; File outputsDestDir = new File(outputsPath); outputsDestDir.mkdir(); // copy log file to outputs File outputPath = new File(response.getBundleDataDirectory()); String logFilename = outputPath + File.separator + "bundleBuilder.out.txt"; fs.copyFiles(new File(logFilename), new File(response.getBundleOutputDirectory() + File.separator + "bundleBuilder.out.txt")); // copy the rest of the bundle content to outputs directory File outputsDir = new File(response.getBundleOutputDirectory()); File[] outputFiles = outputsDir.listFiles(); if (outputFiles != null) { for (File output : outputFiles) { response.addOutputFile(output.getName()); fs.copyFiles(output, new File(outputsPath + File.separator + output.getName())); } } } private StringBuffer listToFile(List<String> notInServiceDSCList) { StringBuffer sb = new StringBuffer(); for (String s : notInServiceDSCList) { sb.append(s).append("\n"); } return sb; } private List<GtfsBundle> createGtfsBundles(BundleBuildResponse response) { List<String> gtfsList = response.getGtfsList(); final String gtfsMsg = "constructing configuration for bundles=" + gtfsList; response.addStatusMessage(gtfsMsg); _log.info(gtfsMsg); List<GtfsBundle> bundles = new ArrayList<GtfsBundle>(gtfsList.size()); String defaultAgencyId = getDefaultAgencyId(); + response.addStatusMessage("default agency configured to be |" + defaultAgencyId + "|"); for (String path : gtfsList) { GtfsBundle gtfsBundle = new GtfsBundle(); gtfsBundle.setPath(new File(path)); - if (defaultAgencyId != null && defaultAgencyId.length() == 0) { + if (defaultAgencyId != null && defaultAgencyId.length() > 0) { final String msg = "for bundle " + path + " setting defaultAgencyId='" + defaultAgencyId + "'"; response.addStatusMessage(msg); _log.info(msg); gtfsBundle.setDefaultAgencyId(defaultAgencyId); } bundles.add(gtfsBundle); } return bundles; } @Override public String getDefaultAgencyId() { return configurationService.getConfigurationValueAsString("admin.default_agency", DEFAULT_AGENCY); } @Override /** * push it back to S3 */ public void upload(BundleBuildRequest request, BundleBuildResponse response) { String versionString = createVersionString(request, response); response.setVersionString(versionString); response.addStatusMessage("uploading to " + versionString); _log.info("uploading " + response.getBundleOutputDirectory() + " to " + versionString); _fileService.put(versionString + File.separator + INPUTS_DIR, response.getBundleInputDirectory()); response.setRemoteInputDirectory(versionString + File.separator + INPUTS_DIR); _fileService.put(versionString + File.separator + OUTPUT_DIR, response.getBundleOutputDirectory()); response.setRemoteOutputDirectory(versionString + File.separator + OUTPUT_DIR); _fileService.put(versionString + File.separator + request.getBundleName() + ".tar.gz", response.getBundleTarFilename()); /* TODO implement delete * for now we rely on cloud restart to delete volume for us, but that is lazy */ } private String createVersionString(BundleBuildRequest request, BundleBuildResponse response) { String bundleName = request.getBundleName(); _log.info("createVersionString found bundleName=" + bundleName); if (bundleName == null || bundleName.length() == 0) { bundleName = "b" + System.currentTimeMillis(); } return request.getBundleDirectory() + File.separator + _fileService.getBuildPath() + File.separator + bundleName; } }
false
false
null
null
diff --git a/src/main/java/net/greghaines/jesque/meta/dao/impl/WorkerInfoDAORedisImpl.java b/src/main/java/net/greghaines/jesque/meta/dao/impl/WorkerInfoDAORedisImpl.java index ede701d..1a988e0 100644 --- a/src/main/java/net/greghaines/jesque/meta/dao/impl/WorkerInfoDAORedisImpl.java +++ b/src/main/java/net/greghaines/jesque/meta/dao/impl/WorkerInfoDAORedisImpl.java @@ -1,250 +1,252 @@ /* * Copyright 2011 Greg Haines * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.greghaines.jesque.meta.dao.impl; import static net.greghaines.jesque.utils.ResqueConstants.FAILED; import static net.greghaines.jesque.utils.ResqueConstants.PROCESSED; import static net.greghaines.jesque.utils.ResqueConstants.STARTED; import static net.greghaines.jesque.utils.ResqueConstants.STAT; import static net.greghaines.jesque.utils.ResqueConstants.WORKER; import static net.greghaines.jesque.utils.ResqueConstants.WORKERS; import java.io.IOException; import java.text.ParseException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.regex.Pattern; import net.greghaines.jesque.Config; import net.greghaines.jesque.WorkerStatus; import net.greghaines.jesque.json.ObjectMapperFactory; import net.greghaines.jesque.meta.WorkerInfo; import net.greghaines.jesque.meta.dao.WorkerInfoDAO; import net.greghaines.jesque.utils.CompositeDateFormat; import net.greghaines.jesque.utils.JesqueUtils; import net.greghaines.jesque.utils.PoolUtils; import net.greghaines.jesque.utils.PoolUtils.PoolWork; import redis.clients.jedis.Jedis; import redis.clients.util.Pool; public class WorkerInfoDAORedisImpl implements WorkerInfoDAO { private static final Pattern colonPattern = Pattern.compile(":"); private static final Pattern commaPattern = Pattern.compile(","); private final Config config; private final Pool<Jedis> jedisPool; public WorkerInfoDAORedisImpl(final Config config, final Pool<Jedis> jedisPool) { if (config == null) { throw new IllegalArgumentException("config must not be null"); } if (jedisPool == null) { throw new IllegalArgumentException("jedisPool must not be null"); } this.config = config; this.jedisPool = jedisPool; } public long getWorkerCount() { return PoolUtils.doWorkInPoolNicely(this.jedisPool, new PoolWork<Jedis, Long>() { public Long doWork(final Jedis jedis) throws Exception { return jedis.scard(key(WORKERS)); } }); } public long getActiveWorkerCount() { return PoolUtils.doWorkInPoolNicely(this.jedisPool, new PoolWork<Jedis, Long>() { public Long doWork(final Jedis jedis) throws Exception { long activeCount = 0L; final Set<String> workerNames = jedis.smembers(key(WORKERS)); for (final String workerName : workerNames) { if (isWorkerInState(workerName, WorkerInfo.State.WORKING, jedis)) { activeCount++; } } return activeCount; } }); } public long getPausedWorkerCount() { return PoolUtils.doWorkInPoolNicely(this.jedisPool, new PoolWork<Jedis, Long>() { public Long doWork(final Jedis jedis) throws Exception { long pausedCount = 0L; final Set<String> workerNames = jedis.smembers(key(WORKERS)); for (final String workerName : workerNames) { if (isWorkerInState(workerName, WorkerInfo.State.PAUSED, jedis)) { pausedCount++; } } return pausedCount; } }); } public List<WorkerInfo> getActiveWorkers() { return getWorkerInfos(WorkerInfo.State.WORKING); } public List<WorkerInfo> getPausedWorkers() { return getWorkerInfos(WorkerInfo.State.PAUSED); } public List<WorkerInfo> getAllWorkers() { return getWorkerInfos(null); } private List<WorkerInfo> getWorkerInfos(final WorkerInfo.State requestedState) { return PoolUtils.doWorkInPoolNicely(this.jedisPool, new PoolWork<Jedis, List<WorkerInfo>>() { public List<WorkerInfo> doWork(final Jedis jedis) throws Exception { final Set<String> workerNames = jedis.smembers(key(WORKERS)); final List<WorkerInfo> workerInfos = new ArrayList<WorkerInfo>(workerNames.size()); for (final String workerName : workerNames) { if (isWorkerInState(workerName, requestedState, jedis)) { workerInfos.add(createWorker(workerName, jedis)); } } Collections.sort(workerInfos); return workerInfos; } }); } public WorkerInfo getWorker(final String workerName) { return PoolUtils.doWorkInPoolNicely(this.jedisPool, new PoolWork<Jedis, WorkerInfo>() { public WorkerInfo doWork(final Jedis jedis) throws Exception { WorkerInfo workerInfo = null; if (jedis.sismember(key(WORKERS), workerName)) { workerInfo = createWorker(workerName, jedis); } return workerInfo; } }); } public Map<String, List<WorkerInfo>> getWorkerHostMap() { final List<WorkerInfo> workerInfos = getAllWorkers(); final Map<String, List<WorkerInfo>> hostMap = new TreeMap<String, List<WorkerInfo>>(); for (final WorkerInfo workerInfo : workerInfos) { List<WorkerInfo> hostWIs = hostMap.get(workerInfo.getHost()); if (hostWIs == null) { hostWIs = new ArrayList<WorkerInfo>(); hostMap.put(workerInfo.getHost(), hostWIs); } hostWIs.add(workerInfo); } return hostMap; } /** * Builds a namespaced Redis key with the given arguments. * * @param parts * the key parts to be joined * @return an assembled String key */ private String key(final String... parts) { return JesqueUtils.createKey(this.config.getNamespace(), parts); } private WorkerInfo createWorker(final String workerName, final Jedis jedis) throws ParseException, IOException { final WorkerInfo workerInfo = new WorkerInfo(); workerInfo.setName(workerName); final String[] nameParts = colonPattern.split(workerName, 3); if (nameParts.length < 3) { throw new ParseException("Malformed worker name: " + workerName, 0); } workerInfo.setHost(nameParts[0]); workerInfo.setPid(nameParts[1]); workerInfo.setQueues(new ArrayList<String>(Arrays.asList(commaPattern.split(nameParts[2])))); final String statusPayload = jedis.get(key(WORKER, workerName)); if (statusPayload != null) { workerInfo.setStatus(ObjectMapperFactory.get().readValue(statusPayload, WorkerStatus.class)); final WorkerInfo.State state = (workerInfo.getStatus().isPaused()) ? WorkerInfo.State.PAUSED : WorkerInfo.State.WORKING; workerInfo.setState(state); } else { workerInfo.setState(WorkerInfo.State.IDLE); } final String startedStr = jedis.get(key(WORKER, workerName, STARTED)); if (startedStr != null) { workerInfo.setStarted(new CompositeDateFormat().parse(startedStr)); } final String failedStr = jedis.get(key(STAT, FAILED, workerName)); if (failedStr != null) { workerInfo.setFailed(Long.parseLong(failedStr)); } else { workerInfo.setFailed(0L); } final String processedStr = jedis.get(key(STAT, PROCESSED, workerName)); if (processedStr != null) { workerInfo.setProcessed(Long.parseLong(processedStr)); } else { workerInfo.setProcessed(0L); } return workerInfo; } /** * Remove the metadata about a worker * * @param workerName * The worker name to remove */ public void removeWorker(final String workerName) { PoolUtils.doWorkInPoolNicely(this.jedisPool, new PoolWork<Jedis, Void>() { public Void doWork(final Jedis jedis) throws Exception { jedis.srem(key(WORKERS), workerName); jedis.del(key(WORKER, workerName), key(WORKER, workerName, STARTED), key(STAT, FAILED, workerName), key(STAT, PROCESSED, workerName)); return null; } }); } private boolean isWorkerInState(final String workerName, final WorkerInfo.State requestedState, final Jedis jedis) throws IOException { boolean proceed = true; if (requestedState != null) { final String statusPayload = jedis.get(key(WORKER, workerName)); switch (requestedState) { case IDLE: proceed = (statusPayload == null); break; case PAUSED: if (statusPayload != null) { final WorkerStatus status = ObjectMapperFactory.get().readValue(statusPayload, WorkerStatus.class); proceed = status.isPaused(); } break; case WORKING: if (statusPayload != null) { final WorkerStatus status = ObjectMapperFactory.get().readValue(statusPayload, WorkerStatus.class); proceed = !status.isPaused(); + } else { + proceed = false; } break; default: proceed = true; break; } } return proceed; } }
true
false
null
null