diff
stringlengths
262
553k
is_single_chunk
bool
2 classes
is_single_function
bool
1 class
buggy_function
stringlengths
20
391k
fixed_function
stringlengths
0
392k
diff --git a/src/main/java/com/novemberain/quartz/mongodb/MongoDBJobStore.java b/src/main/java/com/novemberain/quartz/mongodb/MongoDBJobStore.java index 5abbf58..659331e 100755 --- a/src/main/java/com/novemberain/quartz/mongodb/MongoDBJobStore.java +++ b/src/main/java/com/novemberain/quartz/mongodb/MongoDBJobStore.java @@ -1,1039 +1,1039 @@ /* * $Id$ * -------------------------------------------------------------------------------------- * Copyright (c) MuleSoft, Inc. All rights reserved. http://www.mulesoft.com * * The software in this package is published under the terms of the CPAL v1.0 * license, a copy of which has been included with this distribution in the * LICENSE.txt file. */ package com.novemberain.quartz.mongodb; import com.mongodb.*; import com.mongodb.MongoException.DuplicateKey; import org.bson.types.ObjectId; import org.quartz.Calendar; import org.quartz.*; import org.quartz.Trigger.CompletedExecutionInstruction; import org.quartz.Trigger.TriggerState; import org.quartz.impl.matchers.GroupMatcher; import org.quartz.spi.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.net.UnknownHostException; import java.util.*; import com.novemberain.quartz.mongodb.Constants; import static com.novemberain.quartz.mongodb.Keys.*; public class MongoDBJobStore implements JobStore, Constants { protected final Logger log = LoggerFactory.getLogger(getClass()); public static final DBObject KEY_AND_GROUP_FIELDS = BasicDBObjectBuilder.start(). append(KEY_GROUP, 1). append(KEY_NAME, 1). get(); private Mongo mongo; private String collectionPrefix = "quartz_"; private String dbName; private DBCollection jobCollection; private DBCollection triggerCollection; private DBCollection calendarCollection; private ClassLoadHelper loadHelper; private DBCollection locksCollection; private DBCollection pausedTriggerGroupsCollection; private DBCollection pausedJobGroupsCollection; private String instanceId; private String[] addresses; private String username; private String password; private SchedulerSignaler signaler; protected long misfireThreshold = 5000l; private long triggerTimeoutMillis = 10 * 60 * 1000L; private List<TriggerPersistenceHelper> persistenceHelpers; private QueryHelper queryHelper; public void initialize(ClassLoadHelper loadHelper, SchedulerSignaler signaler) throws SchedulerConfigException { this.loadHelper = loadHelper; this.signaler = signaler; if (addresses == null || addresses.length == 0) { throw new SchedulerConfigException("At least one MongoDB address must be specified."); } this.mongo = connectToMongoDB(); DB db = selectDatabase(this.mongo); initializeCollections(db); ensureIndexes(); initializeHelpers(); } public void schedulerStarted() throws SchedulerException { // No-op } public void schedulerPaused() { // No-op } public void schedulerResumed() { } public void shutdown() { mongo.close(); } public boolean supportsPersistence() { return true; } public long getEstimatedTimeToReleaseAndAcquireTrigger() { // this will vary... return 200; } public boolean isClustered() { return true; } /** * Job and Trigger storage Methods */ public void storeJobAndTrigger(JobDetail newJob, OperableTrigger newTrigger) throws ObjectAlreadyExistsException, JobPersistenceException { ObjectId jobId = storeJobInMongo(newJob, false); log.debug("Storing job " + newJob.getKey() + " and trigger " + newTrigger.getKey()); storeTrigger(newTrigger, jobId, false); } public void storeJob(JobDetail newJob, boolean replaceExisting) throws ObjectAlreadyExistsException, JobPersistenceException { storeJobInMongo(newJob, replaceExisting); } public void storeJobsAndTriggers(Map<JobDetail, List<Trigger>> triggersAndJobs, boolean replace) throws ObjectAlreadyExistsException, JobPersistenceException { throw new UnsupportedOperationException(); } @SuppressWarnings("LoopStatementThatDoesntLoop") public boolean removeJob(JobKey jobKey) throws JobPersistenceException { BasicDBObject keyObject = Keys.keyToDBObject(jobKey); DBCursor find = jobCollection.find(keyObject); while (find.hasNext()) { DBObject jobObj = find.next(); jobCollection.remove(keyObject); triggerCollection.remove(new BasicDBObject(TRIGGER_JOB_ID, jobObj.get("_id"))); return true; } return false; } public boolean removeJobs(List<JobKey> jobKeys) throws JobPersistenceException { for (JobKey key : jobKeys) { removeJob(key); } return false; } @SuppressWarnings("unchecked") public JobDetail retrieveJob(JobKey jobKey) throws JobPersistenceException { DBObject dbObject = findJobDocumentByKey(jobKey); if (dbObject == null) { //Return null if job does not exist, per interface return null; } try { Class<Job> jobClass = (Class<Job>) getJobClassLoader().loadClass((String) dbObject.get(JOB_CLASS)); JobBuilder builder = JobBuilder.newJob(jobClass) .withIdentity((String) dbObject.get(JOB_KEY_NAME), (String) dbObject.get(JOB_KEY_GROUP)) .withDescription((String) dbObject.get(JOB_DESCRIPTION)); JobDataMap jobData = new JobDataMap(); for (String key : dbObject.keySet()) { if (!key.equals(JOB_KEY_NAME) && !key.equals(JOB_KEY_GROUP) && !key.equals(JOB_CLASS) && !key.equals(JOB_DESCRIPTION) && !key.equals("_id")) { jobData.put(key, dbObject.get(key)); } } return builder.usingJobData(jobData).build(); } catch (ClassNotFoundException e) { throw new JobPersistenceException("Could not load job class " + dbObject.get(JOB_CLASS), e); } } public void storeTrigger(OperableTrigger newTrigger, boolean replaceExisting) throws ObjectAlreadyExistsException, JobPersistenceException { if (newTrigger.getJobKey() == null) { throw new JobPersistenceException("Trigger must be associated with a job. Please specify a JobKey."); } DBObject dbObject = jobCollection.findOne(Keys.keyToDBObject(newTrigger.getJobKey())); if (dbObject != null) { storeTrigger(newTrigger, (ObjectId) dbObject.get("_id"), replaceExisting); } else { throw new JobPersistenceException("Could not find job with key " + newTrigger.getJobKey()); } } // If the removal of the Trigger results in an 'orphaned' Job that is not 'durable', // then the job should be removed also. public boolean removeTrigger(TriggerKey triggerKey) throws JobPersistenceException { BasicDBObject dbObject = Keys.keyToDBObject(triggerKey); DBCursor triggers = triggerCollection.find(dbObject); if (triggers.count() > 0) { DBObject trigger = triggers.next(); if (trigger.containsField( TRIGGER_JOB_ID )) { // There is only 1 job per trigger so no need to look further than 1 job. DBObject job = jobCollection.findOne(new BasicDBObject("_id", trigger.get(TRIGGER_JOB_ID))); // Durability is not yet implemented in MongoDBJOBStore so next will always be true if (!job.containsField( JOB_DURABILITY ) || job.get( JOB_DURABILITY ).toString() == "false") { // Check if this job is referenced by other triggers. BasicDBObject query = new BasicDBObject(); query.put(TRIGGER_JOB_ID, job.get( "_id" )); DBCursor referencedTriggers = triggerCollection.find(query); if (referencedTriggers != null && referencedTriggers.count() <= 1) { jobCollection.remove( job ); } } } else { log.debug("The triggger had no associated jobs"); } triggerCollection.remove(dbObject); return true; } return false; } public boolean removeTriggers(List<TriggerKey> triggerKeys) throws JobPersistenceException { for (TriggerKey key : triggerKeys) { removeTrigger(key); } return false; } public boolean replaceTrigger(TriggerKey triggerKey, OperableTrigger newTrigger) throws JobPersistenceException { removeTrigger(triggerKey); storeTrigger(newTrigger, false); return true; } public OperableTrigger retrieveTrigger(TriggerKey triggerKey) throws JobPersistenceException { DBObject dbObject = triggerCollection.findOne(Keys.keyToDBObject(triggerKey)); if (dbObject == null) { return null; } return toTrigger(triggerKey, dbObject); } public boolean checkExists(JobKey jobKey) throws JobPersistenceException { return jobCollection.count(Keys.keyToDBObject(jobKey)) > 0; } public boolean checkExists(TriggerKey triggerKey) throws JobPersistenceException { return triggerCollection.count(Keys.keyToDBObject(triggerKey)) > 0; } public void clearAllSchedulingData() throws JobPersistenceException { jobCollection.remove(new BasicDBObject()); triggerCollection.remove(new BasicDBObject()); calendarCollection.remove(new BasicDBObject()); pausedJobGroupsCollection.remove(new BasicDBObject()); pausedTriggerGroupsCollection.remove(new BasicDBObject()); } public void storeCalendar(String name, Calendar calendar, boolean replaceExisting, boolean updateTriggers) throws ObjectAlreadyExistsException, JobPersistenceException { // TODO if (updateTriggers) { throw new UnsupportedOperationException("Updating triggers is not supported."); } BasicDBObject dbObject = new BasicDBObject(); dbObject.put(CALENDAR_NAME, name); dbObject.put(CALENDAR_SERIALIZED_OBJECT, serialize(calendar)); calendarCollection.insert(dbObject); } public boolean removeCalendar(String calName) throws JobPersistenceException { BasicDBObject searchObj = new BasicDBObject(CALENDAR_NAME, calName); if (calendarCollection.count(searchObj) > 0) { calendarCollection.remove(searchObj); return true; } return false; } public Calendar retrieveCalendar(String calName) throws JobPersistenceException { // TODO throw new UnsupportedOperationException(); } public int getNumberOfJobs() throws JobPersistenceException { return (int) jobCollection.count(); } public int getNumberOfTriggers() throws JobPersistenceException { return (int) triggerCollection.count(); } public int getNumberOfCalendars() throws JobPersistenceException { return (int) calendarCollection.count(); } public int getNumberOfLocks() { return (int) locksCollection.count(); } public Set<JobKey> getJobKeys(GroupMatcher<JobKey> matcher) throws JobPersistenceException { DBCursor cursor = jobCollection.find(queryHelper.matchingKeysConditionFor(matcher), KEY_AND_GROUP_FIELDS); Set<JobKey> result = new HashSet<JobKey>(); while (cursor.hasNext()) { DBObject dbo = cursor.next(); JobKey key = Keys.dbObjectToJobKey(dbo); result.add(key); } return result; } public Set<TriggerKey> getTriggerKeys(GroupMatcher<TriggerKey> matcher) throws JobPersistenceException { DBCursor cursor = triggerCollection.find(queryHelper.matchingKeysConditionFor(matcher), KEY_AND_GROUP_FIELDS); Set<TriggerKey> result = new HashSet<TriggerKey>(); while (cursor.hasNext()) { DBObject dbo = cursor.next(); TriggerKey key = Keys.dbObjectToTriggerKey(dbo); result.add(key); } return result; } public List<String> getJobGroupNames() throws JobPersistenceException { return new ArrayList<String>(jobCollection.distinct(KEY_GROUP)); } public List<String> getTriggerGroupNames() throws JobPersistenceException { return new ArrayList<String>(triggerCollection.distinct(KEY_GROUP)); } public List<String> getCalendarNames() throws JobPersistenceException { throw new UnsupportedOperationException(); } public List<OperableTrigger> getTriggersForJob(JobKey jobKey) throws JobPersistenceException { DBObject dbObject = findJobDocumentByKey(jobKey); List<OperableTrigger> triggers = new ArrayList<OperableTrigger>(); DBCursor cursor = triggerCollection.find(new BasicDBObject(TRIGGER_JOB_ID, dbObject.get("_id"))); while (cursor.hasNext()) { triggers.add(toTrigger(cursor.next())); } return triggers; } public TriggerState getTriggerState(TriggerKey triggerKey) throws JobPersistenceException { DBObject doc = findTriggerDocumentByKey(triggerKey); return triggerStateForValue((String) doc.get(TRIGGER_STATE)); } public void pauseTrigger(TriggerKey triggerKey) throws JobPersistenceException { triggerCollection.update(Keys.keyToDBObject(triggerKey), updateThatSetsTriggerStateTo(STATE_PAUSED)); } public Collection<String> pauseTriggers(GroupMatcher<TriggerKey> matcher) throws JobPersistenceException { final GroupHelper groupHelper = new GroupHelper(triggerCollection, queryHelper); triggerCollection.update(queryHelper.matchingKeysConditionFor(matcher), updateThatSetsTriggerStateTo(STATE_PAUSED), false, true); final Set<String> set = groupHelper.groupsThatMatch(matcher); markTriggerGroupsAsPaused(set); return set; } public void resumeTrigger(TriggerKey triggerKey) throws JobPersistenceException { // TODO: port blocking behavior and misfired triggers handling from StdJDBCDelegate in Quartz triggerCollection.update(Keys.keyToDBObject(triggerKey), updateThatSetsTriggerStateTo(STATE_WAITING)); } public Collection<String> resumeTriggers(GroupMatcher<TriggerKey> matcher) throws JobPersistenceException { final GroupHelper groupHelper = new GroupHelper(triggerCollection, queryHelper); triggerCollection.update(queryHelper.matchingKeysConditionFor(matcher), updateThatSetsTriggerStateTo(STATE_WAITING), false, true); final Set<String> set = groupHelper.groupsThatMatch(matcher); this.unmarkTriggerGroupsAsPaused(set); return set; } @SuppressWarnings("unchecked") public Set<String> getPausedTriggerGroups() throws JobPersistenceException { return new HashSet<String>(pausedTriggerGroupsCollection.distinct(KEY_GROUP)); } @SuppressWarnings("unchecked") public Set<String> getPausedJobGroups() throws JobPersistenceException { return new HashSet<String>(pausedJobGroupsCollection.distinct(KEY_GROUP)); } public void pauseAll() throws JobPersistenceException { final GroupHelper groupHelper = new GroupHelper(triggerCollection, queryHelper); triggerCollection.update(new BasicDBObject(), updateThatSetsTriggerStateTo(STATE_PAUSED)); this.markTriggerGroupsAsPaused(groupHelper.allGroups()); } public void resumeAll() throws JobPersistenceException { final GroupHelper groupHelper = new GroupHelper(triggerCollection, queryHelper); triggerCollection.update(new BasicDBObject(), updateThatSetsTriggerStateTo(STATE_WAITING)); this.unmarkTriggerGroupsAsPaused(groupHelper.allGroups()); } public void pauseJob(JobKey jobKey) throws JobPersistenceException { final ObjectId jobId = (ObjectId) findJobDocumentByKey(jobKey).get("_id"); final TriggerGroupHelper groupHelper = new TriggerGroupHelper(triggerCollection, queryHelper); List<String> groups = groupHelper.groupsForJobId(jobId); triggerCollection.update(new BasicDBObject(TRIGGER_JOB_ID, jobId), updateThatSetsTriggerStateTo(STATE_PAUSED)); this.markTriggerGroupsAsPaused(groups); } public Collection<String> pauseJobs(GroupMatcher<JobKey> groupMatcher) throws JobPersistenceException { final TriggerGroupHelper groupHelper = new TriggerGroupHelper(triggerCollection, queryHelper); List<String> groups = groupHelper.groupsForJobIds(idsFrom(findJobDocumentsThatMatch(groupMatcher))); triggerCollection.update(queryHelper.inGroups(groups), updateThatSetsTriggerStateTo(STATE_PAUSED)); this.markJobGroupsAsPaused(groups); return groups; } public void resumeJob(JobKey jobKey) throws JobPersistenceException { final ObjectId jobId = (ObjectId) findJobDocumentByKey(jobKey).get("_id"); // TODO: port blocking behavior and misfired triggers handling from StdJDBCDelegate in Quartz triggerCollection.update(new BasicDBObject(TRIGGER_JOB_ID, jobId), updateThatSetsTriggerStateTo(STATE_WAITING)); } public Collection<String> resumeJobs(GroupMatcher<JobKey> groupMatcher) throws JobPersistenceException { final TriggerGroupHelper groupHelper = new TriggerGroupHelper(triggerCollection, queryHelper); List<String> groups = groupHelper.groupsForJobIds(idsFrom(findJobDocumentsThatMatch(groupMatcher))); triggerCollection.update(queryHelper.inGroups(groups), updateThatSetsTriggerStateTo(STATE_WAITING)); this.unmarkJobGroupsAsPaused(groups); return groups; } public List<OperableTrigger> acquireNextTriggers(long noLaterThan, int maxCount, long timeWindow) throws JobPersistenceException { BasicDBObject query = new BasicDBObject(); query.put(TRIGGER_NEXT_FIRE_TIME, new BasicDBObject("$lte", new Date(noLaterThan))); if (log.isDebugEnabled()) { log.debug("Finding up to " + maxCount + " triggers which have time less than " + new Date(noLaterThan)); } List<OperableTrigger> triggers = new ArrayList<OperableTrigger>(); DBCursor cursor = triggerCollection.find(query); BasicDBObject sort = new BasicDBObject(); sort.put(TRIGGER_NEXT_FIRE_TIME, Integer.valueOf(1)); cursor.sort(sort); if (log.isDebugEnabled()) { log.debug("Found " + cursor.count() + " triggers which are eligible to be run."); } while (cursor.hasNext() && maxCount > triggers.size()) { DBObject dbObj = cursor.next(); BasicDBObject lock = new BasicDBObject(); lock.put(LOCK_KEY_NAME, dbObj.get(KEY_NAME)); lock.put(LOCK_KEY_GROUP, dbObj.get(KEY_GROUP)); lock.put(LOCK_INSTANCE_ID, instanceId); lock.put(LOCK_TIME, new Date()); try { OperableTrigger trigger = toTrigger(dbObj); if (trigger.getNextFireTime() == null) { if (log.isDebugEnabled()) { log.debug("Skipping trigger " + trigger.getKey() + " as it has no next fire time."); } continue; } // deal with misfires if (applyMisfire(trigger) && trigger.getNextFireTime() == null) { if (log.isDebugEnabled()) { log.debug("Skipping trigger " + trigger.getKey() + " as it has no next fire time after the misfire was applied."); } continue; } log.debug("Inserting lock for trigger " + trigger.getKey()); locksCollection.insert(lock); log.debug("Aquired trigger " + trigger.getKey()); triggers.add(trigger); } catch (DuplicateKey e) { OperableTrigger trigger = toTrigger(dbObj); // someone else acquired this lock. Move on. log.debug("Failed to acquire trigger " + trigger.getKey() + " due to a lock"); lock = new BasicDBObject(); lock.put(LOCK_KEY_NAME, dbObj.get(KEY_NAME)); lock.put(LOCK_KEY_GROUP, dbObj.get(KEY_GROUP)); DBObject existingLock; DBCursor lockCursor = locksCollection.find(lock); if (lockCursor.hasNext()) { existingLock = lockCursor.next(); } else { log.warn("Error retrieving expired lock from the database. Maybe it was deleted"); return acquireNextTriggers(noLaterThan, maxCount, timeWindow); } // support for trigger lock expirations if (isTriggerLockExpired(existingLock)) { - log.error("Lock for trigger " + trigger.getKey() + " is expired - removing lock and retrying trigger acquisition"); + log.warn("Lock for trigger " + trigger.getKey() + " is expired - removing lock and retrying trigger acquisition"); removeTriggerLock(trigger); return acquireNextTriggers(noLaterThan, maxCount, timeWindow); } } } return triggers; } public void releaseAcquiredTrigger(OperableTrigger trigger) throws JobPersistenceException { try { removeTriggerLock(trigger); } catch (Exception e) { throw new JobPersistenceException(e.getLocalizedMessage(), e); } } public List<TriggerFiredResult> triggersFired(List<OperableTrigger> triggers) throws JobPersistenceException { List<TriggerFiredResult> results = new ArrayList<TriggerFiredResult>(); for (OperableTrigger trigger : triggers) { log.debug("Fired trigger " + trigger.getKey()); Calendar cal = null; if (trigger.getCalendarName() != null) { cal = retrieveCalendar(trigger.getCalendarName()); if (cal == null) continue; } Date prevFireTime = trigger.getPreviousFireTime(); TriggerFiredBundle bndle = new TriggerFiredBundle(retrieveJob( trigger), trigger, cal, false, new Date(), trigger.getPreviousFireTime(), prevFireTime, trigger.getNextFireTime()); JobDetail job = bndle.getJobDetail(); if (job.isConcurrentExectionDisallowed()) { throw new UnsupportedOperationException("ConcurrentExecutionDisallowed is not supported currently."); } results.add(new TriggerFiredResult(bndle)); trigger.triggered(cal); storeTrigger(trigger, true); } return results; } public void triggeredJobComplete(OperableTrigger trigger, JobDetail jobDetail, CompletedExecutionInstruction triggerInstCode) throws JobPersistenceException { log.debug("Trigger completed " + trigger.getKey()); // check for trigger deleted during execution... OperableTrigger trigger2 = retrieveTrigger(trigger.getKey()); if (trigger2 != null) { if (triggerInstCode == CompletedExecutionInstruction.DELETE_TRIGGER) { if (trigger.getNextFireTime() == null) { // double check for possible reschedule within job // execution, which would cancel the need to delete... if (trigger2.getNextFireTime() == null) { removeTrigger(trigger.getKey()); } } else { removeTrigger(trigger.getKey()); signaler.signalSchedulingChange(0L); } } else if (triggerInstCode == CompletedExecutionInstruction.SET_TRIGGER_COMPLETE) { // TODO: need to store state signaler.signalSchedulingChange(0L); } else if (triggerInstCode == CompletedExecutionInstruction.SET_TRIGGER_ERROR) { // TODO: need to store state signaler.signalSchedulingChange(0L); } else if (triggerInstCode == CompletedExecutionInstruction.SET_ALL_JOB_TRIGGERS_ERROR) { // TODO: need to store state signaler.signalSchedulingChange(0L); } else if (triggerInstCode == CompletedExecutionInstruction.SET_ALL_JOB_TRIGGERS_COMPLETE) { // TODO: need to store state signaler.signalSchedulingChange(0L); } } removeTriggerLock(trigger); } public void setInstanceId(String instanceId) { this.instanceId = instanceId; } public void setInstanceName(String schedName) { // No-op } public void setThreadPoolSize(int poolSize) { // No-op } public void setAddresses(String addresses) { this.addresses = addresses.split(","); } public DBCollection getJobCollection() { return jobCollection; } public DBCollection getTriggerCollection() { return triggerCollection; } public DBCollection getCalendarCollection() { return calendarCollection; } public DBCollection getLocksCollection() { return locksCollection; } public String getDbName() { return dbName; } public void setDbName(String dbName) { this.dbName = dbName; } public void setCollectionPrefix(String prefix) { collectionPrefix = prefix + "_"; } public void setUsername(String username) { this.username = username; } public void setPassword(String password) { this.password = password; } public long getMisfireThreshold() { return misfireThreshold; } public void setMisfireThreshold(long misfireThreshold) { this.misfireThreshold = misfireThreshold; } public void setTriggerTimeoutMillis(long triggerTimeoutMillis) { this.triggerTimeoutMillis = triggerTimeoutMillis; } // // Implementation // private void initializeCollections(DB db) { jobCollection = db.getCollection(collectionPrefix + "jobs"); triggerCollection = db.getCollection(collectionPrefix + "triggers"); calendarCollection = db.getCollection(collectionPrefix + "calendars"); locksCollection = db.getCollection(collectionPrefix + "locks"); pausedTriggerGroupsCollection = db.getCollection(collectionPrefix + "paused_trigger_groups"); pausedJobGroupsCollection = db.getCollection(collectionPrefix + "paused_job_groups"); } private DB selectDatabase(Mongo mongo) { DB db = this.mongo.getDB(dbName); // MongoDB defaults are insane, set a reasonable write concern explicitly. MK. db.setWriteConcern(WriteConcern.JOURNAL_SAFE); if (username != null) { db.authenticate(username, password.toCharArray()); } return db; } private Mongo connectToMongoDB() throws SchedulerConfigException { MongoOptions options = new MongoOptions(); options.safe = true; try { ArrayList<ServerAddress> serverAddresses = new ArrayList<ServerAddress>(); for (String a : addresses) { serverAddresses.add(new ServerAddress(a)); } return new Mongo(serverAddresses, options); } catch (UnknownHostException e) { throw new SchedulerConfigException("Could not connect to MongoDB.", e); } catch (MongoException e) { throw new SchedulerConfigException("Could not connect to MongoDB.", e); } } protected OperableTrigger toTrigger(DBObject dbObj) throws JobPersistenceException { TriggerKey key = new TriggerKey((String) dbObj.get(KEY_NAME), (String) dbObj.get(KEY_GROUP)); return toTrigger(key, dbObj); } protected OperableTrigger toTrigger(TriggerKey triggerKey, DBObject dbObject) throws JobPersistenceException { OperableTrigger trigger; try { Class<OperableTrigger> triggerClass = (Class<OperableTrigger>) getTriggerClassLoader().loadClass((String) dbObject.get(TRIGGER_CLASS)); trigger = triggerClass.newInstance(); } catch (ClassNotFoundException e) { throw new JobPersistenceException("Could not find trigger class " + (String) dbObject.get(TRIGGER_CLASS)); } catch (Exception e) { throw new JobPersistenceException("Could not instantiate trigger class " + (String) dbObject.get(TRIGGER_CLASS)); } TriggerPersistenceHelper tpd = triggerPersistenceDelegateFor(trigger); trigger.setKey(triggerKey); trigger.setCalendarName((String) dbObject.get(TRIGGER_CALENDAR_NAME)); trigger.setDescription((String) dbObject.get(TRIGGER_DESCRIPTION)); trigger.setStartTime((Date) dbObject.get(TRIGGER_START_TIME)); trigger.setEndTime((Date) dbObject.get(TRIGGER_END_TIME)); trigger.setFireInstanceId((String) dbObject.get(TRIGGER_FIRE_INSTANCE_ID)); trigger.setMisfireInstruction((Integer) dbObject.get(TRIGGER_MISFIRE_INSTRUCTION)); trigger.setNextFireTime((Date) dbObject.get(TRIGGER_NEXT_FIRE_TIME)); trigger.setPreviousFireTime((Date) dbObject.get(TRIGGER_PREVIOUS_FIRE_TIME)); trigger.setPriority((Integer) dbObject.get(TRIGGER_PRIORITY)); trigger = tpd.setExtraPropertiesAfterInstantiation(trigger, dbObject); DBObject job = jobCollection.findOne(new BasicDBObject("_id", dbObject.get(TRIGGER_JOB_ID))); if (job != null) { trigger.setJobKey(new JobKey((String) job.get(JOB_KEY_NAME), (String) job.get(JOB_KEY_GROUP))); return trigger; } else { // job was deleted return null; } } protected ClassLoader getTriggerClassLoader() { return org.quartz.Job.class.getClassLoader(); } private TriggerPersistenceHelper triggerPersistenceDelegateFor(OperableTrigger trigger) { TriggerPersistenceHelper result = null; for (TriggerPersistenceHelper d : persistenceHelpers) { if (d.canHandleTriggerType(trigger)) { result = d; break; } } assert result != null; return result; } protected boolean isTriggerLockExpired(DBObject lock) { Date lockTime = (Date) lock.get(LOCK_TIME); long elaspedTime = System.currentTimeMillis() - lockTime.getTime(); return (elaspedTime > triggerTimeoutMillis); } protected boolean applyMisfire(OperableTrigger trigger) throws JobPersistenceException { long misfireTime = System.currentTimeMillis(); if (getMisfireThreshold() > 0) { misfireTime -= getMisfireThreshold(); } Date tnft = trigger.getNextFireTime(); if (tnft == null || tnft.getTime() > misfireTime || trigger.getMisfireInstruction() == Trigger.MISFIRE_INSTRUCTION_IGNORE_MISFIRE_POLICY) { return false; } Calendar cal = null; if (trigger.getCalendarName() != null) { cal = retrieveCalendar(trigger.getCalendarName()); } signaler.notifyTriggerListenersMisfired((OperableTrigger) trigger.clone()); trigger.updateAfterMisfire(cal); if (trigger.getNextFireTime() == null) { signaler.notifySchedulerListenersFinalized(trigger); } else if (tnft.equals(trigger.getNextFireTime())) { return false; } storeTrigger(trigger, true); return true; } private Object serialize(Calendar calendar) throws JobPersistenceException { ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); try { ObjectOutputStream objectStream = new ObjectOutputStream(byteStream); objectStream.writeObject(calendar); objectStream.close(); return byteStream.toByteArray(); } catch (IOException e) { throw new JobPersistenceException("Could not serialize Calendar.", e); } } private void ensureIndexes() { BasicDBObject keys = new BasicDBObject(); keys.put(JOB_KEY_NAME, 1); keys.put(JOB_KEY_GROUP, 1); jobCollection.ensureIndex(keys, null, true); keys = new BasicDBObject(); keys.put(KEY_NAME, 1); keys.put(KEY_GROUP, 1); triggerCollection.ensureIndex(keys, null, true); keys = new BasicDBObject(); keys.put(LOCK_KEY_NAME, 1); keys.put(LOCK_KEY_GROUP, 1); locksCollection.ensureIndex(keys, null, true); // remove all locks for this instance on startup locksCollection.remove(new BasicDBObject(LOCK_INSTANCE_ID, instanceId)); keys = new BasicDBObject(); keys.put(CALENDAR_NAME, 1); calendarCollection.ensureIndex(keys, null, true); } protected void storeTrigger(OperableTrigger newTrigger, ObjectId jobId, boolean replaceExisting) throws ObjectAlreadyExistsException { BasicDBObject trigger = new BasicDBObject(); trigger.put(TRIGGER_STATE, STATE_WAITING); trigger.put(TRIGGER_CALENDAR_NAME, newTrigger.getCalendarName()); trigger.put(TRIGGER_CLASS, newTrigger.getClass().getName()); trigger.put(TRIGGER_DESCRIPTION, newTrigger.getDescription()); trigger.put(TRIGGER_END_TIME, newTrigger.getEndTime()); trigger.put(TRIGGER_FINAL_FIRE_TIME, newTrigger.getFinalFireTime()); trigger.put(TRIGGER_FIRE_INSTANCE_ID, newTrigger.getFireInstanceId()); trigger.put(TRIGGER_JOB_ID, jobId); trigger.put(KEY_NAME, newTrigger.getKey().getName()); trigger.put(KEY_GROUP, newTrigger.getKey().getGroup()); trigger.put(TRIGGER_MISFIRE_INSTRUCTION, newTrigger.getMisfireInstruction()); trigger.put(TRIGGER_NEXT_FIRE_TIME, newTrigger.getNextFireTime()); trigger.put(TRIGGER_PREVIOUS_FIRE_TIME, newTrigger.getPreviousFireTime()); trigger.put(TRIGGER_PRIORITY, newTrigger.getPriority()); trigger.put(TRIGGER_START_TIME, newTrigger.getStartTime()); TriggerPersistenceHelper tpd = triggerPersistenceDelegateFor(newTrigger); trigger = (BasicDBObject) tpd.injectExtraPropertiesForInsert(newTrigger, trigger); try { triggerCollection.insert(trigger); } catch (DuplicateKey key) { if (replaceExisting) { trigger.remove("_id"); triggerCollection.update(keyToDBObject(newTrigger.getKey()), trigger); } else { throw new ObjectAlreadyExistsException(newTrigger); } } } protected ObjectId storeJobInMongo(JobDetail newJob, boolean replaceExisting) throws ObjectAlreadyExistsException { JobKey key = newJob.getKey(); BasicDBObject job = keyToDBObject(key); if (replaceExisting) { DBObject result = jobCollection.findOne(job); if (result != null) { result = job; } } job.put(JOB_KEY_NAME, key.getName()); job.put(JOB_KEY_GROUP, key.getGroup()); job.put(JOB_DESCRIPTION, newJob.getDescription()); job.put(JOB_CLASS, newJob.getJobClass().getName()); job.putAll(newJob.getJobDataMap()); try { jobCollection.insert(job); return (ObjectId) job.get("_id"); } catch (DuplicateKey e) { throw new ObjectAlreadyExistsException(e.getMessage()); } } protected void removeTriggerLock(OperableTrigger trigger) { log.debug("Removing trigger lock " + trigger.getKey() + "." + instanceId); BasicDBObject lock = new BasicDBObject(); lock.put(LOCK_KEY_NAME, trigger.getKey().getName()); lock.put(LOCK_KEY_GROUP, trigger.getKey().getGroup()); // Coment this out, as expired trigger locks should be deleted by any another instance // lock.put(LOCK_INSTANCE_ID, instanceId); locksCollection.remove(lock); log.debug("Trigger lock " + trigger.getKey() + "." + instanceId + " removed."); } protected ClassLoader getJobClassLoader() { return loadHelper.getClassLoader(); } private JobDetail retrieveJob(OperableTrigger trigger) throws JobPersistenceException { try { return retrieveJob(trigger.getJobKey()); } catch (JobPersistenceException e) { removeTriggerLock(trigger); throw e; } } protected DBObject findJobDocumentByKey(JobKey key) { return jobCollection.findOne(keyToDBObject(key)); } protected DBObject findTriggerDocumentByKey(TriggerKey key) { return triggerCollection.findOne(keyToDBObject(key)); } private void initializeHelpers() { this.persistenceHelpers = new ArrayList<TriggerPersistenceHelper>(); persistenceHelpers.add(new SimpleTriggerPersistenceHelper()); persistenceHelpers.add(new CalendarIntervalTriggerPersistenceHelper()); persistenceHelpers.add(new CronTriggerPersistenceHelper()); persistenceHelpers.add(new DailyTimeIntervalTriggerPersistenceHelper()); this.queryHelper = new QueryHelper(); } private TriggerState triggerStateForValue(String ts) { if (ts == null) { return TriggerState.NONE; } if (ts.equals(STATE_DELETED)) { return TriggerState.NONE; } if (ts.equals(STATE_COMPLETE)) { return TriggerState.COMPLETE; } if (ts.equals(STATE_PAUSED)) { return TriggerState.PAUSED; } if (ts.equals(STATE_PAUSED_BLOCKED)) { return TriggerState.PAUSED; } if (ts.equals(STATE_ERROR)) { return TriggerState.ERROR; } if (ts.equals(STATE_BLOCKED)) { return TriggerState.BLOCKED; } // waiting or acquired return TriggerState.NORMAL; } private DBObject updateThatSetsTriggerStateTo(String state) { return BasicDBObjectBuilder. start("$set", new BasicDBObject(TRIGGER_STATE, state)). get(); } private void markTriggerGroupsAsPaused(Collection<String> groups) { List<DBObject> list = new ArrayList<DBObject>(); for (String s : groups) { list.add(new BasicDBObject(KEY_GROUP, s)); } pausedTriggerGroupsCollection.insert(list); } private void unmarkTriggerGroupsAsPaused(Collection<String> groups) { pausedTriggerGroupsCollection.remove(QueryBuilder.start(KEY_GROUP).in(groups).get()); } private void markJobGroupsAsPaused(List<String> groups) { if (groups == null) { throw new IllegalArgumentException("groups cannot be null!"); } List<DBObject> list = new ArrayList<DBObject>(); for (String s : groups) { list.add(new BasicDBObject(KEY_GROUP, s)); } pausedJobGroupsCollection.insert(list); } private void unmarkJobGroupsAsPaused(Collection<String> groups) { pausedJobGroupsCollection.remove(QueryBuilder.start(KEY_GROUP).in(groups).get()); } private Collection<ObjectId> idsFrom(Collection<DBObject> docs) { // so much repetitive code would be gone if Java collections just had .map and .filter… List<ObjectId> list = new ArrayList<ObjectId>(); for (DBObject doc : docs) { list.add((ObjectId) doc.get("_id")); } return list; } private Collection<DBObject> findJobDocumentsThatMatch(GroupMatcher<JobKey> matcher) { final GroupHelper groupHelper = new GroupHelper(jobCollection, queryHelper); return groupHelper.inGroupsThatMatch(matcher); } }
true
true
public List<OperableTrigger> acquireNextTriggers(long noLaterThan, int maxCount, long timeWindow) throws JobPersistenceException { BasicDBObject query = new BasicDBObject(); query.put(TRIGGER_NEXT_FIRE_TIME, new BasicDBObject("$lte", new Date(noLaterThan))); if (log.isDebugEnabled()) { log.debug("Finding up to " + maxCount + " triggers which have time less than " + new Date(noLaterThan)); } List<OperableTrigger> triggers = new ArrayList<OperableTrigger>(); DBCursor cursor = triggerCollection.find(query); BasicDBObject sort = new BasicDBObject(); sort.put(TRIGGER_NEXT_FIRE_TIME, Integer.valueOf(1)); cursor.sort(sort); if (log.isDebugEnabled()) { log.debug("Found " + cursor.count() + " triggers which are eligible to be run."); } while (cursor.hasNext() && maxCount > triggers.size()) { DBObject dbObj = cursor.next(); BasicDBObject lock = new BasicDBObject(); lock.put(LOCK_KEY_NAME, dbObj.get(KEY_NAME)); lock.put(LOCK_KEY_GROUP, dbObj.get(KEY_GROUP)); lock.put(LOCK_INSTANCE_ID, instanceId); lock.put(LOCK_TIME, new Date()); try { OperableTrigger trigger = toTrigger(dbObj); if (trigger.getNextFireTime() == null) { if (log.isDebugEnabled()) { log.debug("Skipping trigger " + trigger.getKey() + " as it has no next fire time."); } continue; } // deal with misfires if (applyMisfire(trigger) && trigger.getNextFireTime() == null) { if (log.isDebugEnabled()) { log.debug("Skipping trigger " + trigger.getKey() + " as it has no next fire time after the misfire was applied."); } continue; } log.debug("Inserting lock for trigger " + trigger.getKey()); locksCollection.insert(lock); log.debug("Aquired trigger " + trigger.getKey()); triggers.add(trigger); } catch (DuplicateKey e) { OperableTrigger trigger = toTrigger(dbObj); // someone else acquired this lock. Move on. log.debug("Failed to acquire trigger " + trigger.getKey() + " due to a lock"); lock = new BasicDBObject(); lock.put(LOCK_KEY_NAME, dbObj.get(KEY_NAME)); lock.put(LOCK_KEY_GROUP, dbObj.get(KEY_GROUP)); DBObject existingLock; DBCursor lockCursor = locksCollection.find(lock); if (lockCursor.hasNext()) { existingLock = lockCursor.next(); } else { log.warn("Error retrieving expired lock from the database. Maybe it was deleted"); return acquireNextTriggers(noLaterThan, maxCount, timeWindow); } // support for trigger lock expirations if (isTriggerLockExpired(existingLock)) { log.error("Lock for trigger " + trigger.getKey() + " is expired - removing lock and retrying trigger acquisition"); removeTriggerLock(trigger); return acquireNextTriggers(noLaterThan, maxCount, timeWindow); } } } return triggers; }
public List<OperableTrigger> acquireNextTriggers(long noLaterThan, int maxCount, long timeWindow) throws JobPersistenceException { BasicDBObject query = new BasicDBObject(); query.put(TRIGGER_NEXT_FIRE_TIME, new BasicDBObject("$lte", new Date(noLaterThan))); if (log.isDebugEnabled()) { log.debug("Finding up to " + maxCount + " triggers which have time less than " + new Date(noLaterThan)); } List<OperableTrigger> triggers = new ArrayList<OperableTrigger>(); DBCursor cursor = triggerCollection.find(query); BasicDBObject sort = new BasicDBObject(); sort.put(TRIGGER_NEXT_FIRE_TIME, Integer.valueOf(1)); cursor.sort(sort); if (log.isDebugEnabled()) { log.debug("Found " + cursor.count() + " triggers which are eligible to be run."); } while (cursor.hasNext() && maxCount > triggers.size()) { DBObject dbObj = cursor.next(); BasicDBObject lock = new BasicDBObject(); lock.put(LOCK_KEY_NAME, dbObj.get(KEY_NAME)); lock.put(LOCK_KEY_GROUP, dbObj.get(KEY_GROUP)); lock.put(LOCK_INSTANCE_ID, instanceId); lock.put(LOCK_TIME, new Date()); try { OperableTrigger trigger = toTrigger(dbObj); if (trigger.getNextFireTime() == null) { if (log.isDebugEnabled()) { log.debug("Skipping trigger " + trigger.getKey() + " as it has no next fire time."); } continue; } // deal with misfires if (applyMisfire(trigger) && trigger.getNextFireTime() == null) { if (log.isDebugEnabled()) { log.debug("Skipping trigger " + trigger.getKey() + " as it has no next fire time after the misfire was applied."); } continue; } log.debug("Inserting lock for trigger " + trigger.getKey()); locksCollection.insert(lock); log.debug("Aquired trigger " + trigger.getKey()); triggers.add(trigger); } catch (DuplicateKey e) { OperableTrigger trigger = toTrigger(dbObj); // someone else acquired this lock. Move on. log.debug("Failed to acquire trigger " + trigger.getKey() + " due to a lock"); lock = new BasicDBObject(); lock.put(LOCK_KEY_NAME, dbObj.get(KEY_NAME)); lock.put(LOCK_KEY_GROUP, dbObj.get(KEY_GROUP)); DBObject existingLock; DBCursor lockCursor = locksCollection.find(lock); if (lockCursor.hasNext()) { existingLock = lockCursor.next(); } else { log.warn("Error retrieving expired lock from the database. Maybe it was deleted"); return acquireNextTriggers(noLaterThan, maxCount, timeWindow); } // support for trigger lock expirations if (isTriggerLockExpired(existingLock)) { log.warn("Lock for trigger " + trigger.getKey() + " is expired - removing lock and retrying trigger acquisition"); removeTriggerLock(trigger); return acquireNextTriggers(noLaterThan, maxCount, timeWindow); } } } return triggers; }
diff --git a/src/com/NYXDigital/NiceSupportMapFragment.java b/src/com/NYXDigital/NiceSupportMapFragment.java index 7ece844..96e1bdf 100644 --- a/src/com/NYXDigital/NiceSupportMapFragment.java +++ b/src/com/NYXDigital/NiceSupportMapFragment.java @@ -1,148 +1,148 @@ package com.NYXDigital; import android.annotation.SuppressLint; import android.graphics.PixelFormat; import android.os.Bundle; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.TextureView; import android.view.View; import android.view.View.OnTouchListener; import android.view.ViewGroup; import com.google.android.gms.maps.SupportMapFragment; public class NiceSupportMapFragment extends SupportMapFragment { private View drawingView; private boolean hasTextureViewSupport = false; private boolean preventParentScrolling = true; private boolean textureViewSupport() { boolean exist = true; try { Class.forName("android.view.TextureView"); } catch (ClassNotFoundException e) { exist = false; } return exist; } private View searchAndFindDrawingView(ViewGroup group) { int childCount = group.getChildCount(); for (int i = 0; i < childCount; i++) { View child = group.getChildAt(i); if (child instanceof ViewGroup) { View view = searchAndFindDrawingView((ViewGroup) child); if (view != null) { return view; } } if (child instanceof SurfaceView) { return (View) child; } if (hasTextureViewSupport) { // if we have support for texture view if (child instanceof TextureView) { return (View) child; } } } return null; } @SuppressLint("NewApi") public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ViewGroup view = (ViewGroup) super.onCreateView(inflater, container, savedInstanceState); view.setBackgroundColor(0x00000000); // Set Root View to be transparent // to prevent black screen on // load hasTextureViewSupport = textureViewSupport(); // Find out if we support // texture view on this // device drawingView = searchAndFindDrawingView(view); // Find the view the map // is using for Open GL if (drawingView == null) return view; // If we didn't get anything then abort drawingView.setBackgroundColor(0x00000000); // Stop black artifact from // being left behind on // scroll // Create On Touch Listener for MapView Parent Scrolling Fix OnTouchListener touchListener = new OnTouchListener() { public boolean onTouch(View view, MotionEvent event) { int action = event.getAction(); switch (action) { case MotionEvent.ACTION_DOWN: // Disallow Parent to intercept touch events. view.getParent().requestDisallowInterceptTouchEvent( - preventParentScrolling); + true); break; case MotionEvent.ACTION_UP: // Allow Parent to intercept touch events. view.getParent().requestDisallowInterceptTouchEvent(false); break; } // Handle View touch events. view.onTouchEvent(event); - return true; + return false; } }; // texture view if (hasTextureViewSupport) { // If we support texture view and the // drawing view is a TextureView then // tweak it and return the fragment view if (drawingView instanceof TextureView) { TextureView textureView = (TextureView) drawingView; // Stop Containing Views from moving when a user is interacting // with Map View Directly textureView.setOnTouchListener(touchListener); return view; } } // Otherwise continue onto legacy surface view hack final SurfaceView surfaceView = (SurfaceView) drawingView; // Fix for reducing black view flash issues SurfaceHolder holder = surfaceView.getHolder(); holder.setFormat(PixelFormat.RGB_888); // Stop Containing Views from moving when a user is interacting with // Map View Directly surfaceView.setOnTouchListener(touchListener); return view; } public boolean getPreventParentScrolling() { return preventParentScrolling; } public void setPreventParentScrolling(boolean value) { preventParentScrolling = value; } }
false
true
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ViewGroup view = (ViewGroup) super.onCreateView(inflater, container, savedInstanceState); view.setBackgroundColor(0x00000000); // Set Root View to be transparent // to prevent black screen on // load hasTextureViewSupport = textureViewSupport(); // Find out if we support // texture view on this // device drawingView = searchAndFindDrawingView(view); // Find the view the map // is using for Open GL if (drawingView == null) return view; // If we didn't get anything then abort drawingView.setBackgroundColor(0x00000000); // Stop black artifact from // being left behind on // scroll // Create On Touch Listener for MapView Parent Scrolling Fix OnTouchListener touchListener = new OnTouchListener() { public boolean onTouch(View view, MotionEvent event) { int action = event.getAction(); switch (action) { case MotionEvent.ACTION_DOWN: // Disallow Parent to intercept touch events. view.getParent().requestDisallowInterceptTouchEvent( preventParentScrolling); break; case MotionEvent.ACTION_UP: // Allow Parent to intercept touch events. view.getParent().requestDisallowInterceptTouchEvent(false); break; } // Handle View touch events. view.onTouchEvent(event); return true; } }; // texture view if (hasTextureViewSupport) { // If we support texture view and the // drawing view is a TextureView then // tweak it and return the fragment view if (drawingView instanceof TextureView) { TextureView textureView = (TextureView) drawingView; // Stop Containing Views from moving when a user is interacting // with Map View Directly textureView.setOnTouchListener(touchListener); return view; } } // Otherwise continue onto legacy surface view hack final SurfaceView surfaceView = (SurfaceView) drawingView; // Fix for reducing black view flash issues SurfaceHolder holder = surfaceView.getHolder(); holder.setFormat(PixelFormat.RGB_888); // Stop Containing Views from moving when a user is interacting with // Map View Directly surfaceView.setOnTouchListener(touchListener); return view; }
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ViewGroup view = (ViewGroup) super.onCreateView(inflater, container, savedInstanceState); view.setBackgroundColor(0x00000000); // Set Root View to be transparent // to prevent black screen on // load hasTextureViewSupport = textureViewSupport(); // Find out if we support // texture view on this // device drawingView = searchAndFindDrawingView(view); // Find the view the map // is using for Open GL if (drawingView == null) return view; // If we didn't get anything then abort drawingView.setBackgroundColor(0x00000000); // Stop black artifact from // being left behind on // scroll // Create On Touch Listener for MapView Parent Scrolling Fix OnTouchListener touchListener = new OnTouchListener() { public boolean onTouch(View view, MotionEvent event) { int action = event.getAction(); switch (action) { case MotionEvent.ACTION_DOWN: // Disallow Parent to intercept touch events. view.getParent().requestDisallowInterceptTouchEvent( true); break; case MotionEvent.ACTION_UP: // Allow Parent to intercept touch events. view.getParent().requestDisallowInterceptTouchEvent(false); break; } // Handle View touch events. view.onTouchEvent(event); return false; } }; // texture view if (hasTextureViewSupport) { // If we support texture view and the // drawing view is a TextureView then // tweak it and return the fragment view if (drawingView instanceof TextureView) { TextureView textureView = (TextureView) drawingView; // Stop Containing Views from moving when a user is interacting // with Map View Directly textureView.setOnTouchListener(touchListener); return view; } } // Otherwise continue onto legacy surface view hack final SurfaceView surfaceView = (SurfaceView) drawingView; // Fix for reducing black view flash issues SurfaceHolder holder = surfaceView.getHolder(); holder.setFormat(PixelFormat.RGB_888); // Stop Containing Views from moving when a user is interacting with // Map View Directly surfaceView.setOnTouchListener(touchListener); return view; }
diff --git a/jsystem-core-projects/jsystemAnt/src/main/java/com/aqua/anttask/jsystem/JSystemDataDrivenTask.java b/jsystem-core-projects/jsystemAnt/src/main/java/com/aqua/anttask/jsystem/JSystemDataDrivenTask.java index ecbdd4c..0aeb28a 100644 --- a/jsystem-core-projects/jsystemAnt/src/main/java/com/aqua/anttask/jsystem/JSystemDataDrivenTask.java +++ b/jsystem-core-projects/jsystemAnt/src/main/java/com/aqua/anttask/jsystem/JSystemDataDrivenTask.java @@ -1,238 +1,240 @@ package com.aqua.anttask.jsystem; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import jsystem.framework.FrameworkOptions; import jsystem.framework.JSystemProperties; import jsystem.framework.scenario.Parameter.ParameterType; import jsystem.framework.scenario.ParametersManager; import jsystem.framework.scenario.flow_control.datadriven.CsvDataProvider; import jsystem.framework.scenario.flow_control.datadriven.DataCollectorException; import jsystem.framework.scenario.flow_control.datadriven.DataProvider; import jsystem.utils.StringUtils; import jsystem.utils.beans.BeanUtils; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.taskdefs.MacroInstance; public class JSystemDataDrivenTask extends PropertyReaderTask { private static final String DELIMITER = ";"; static Logger log = Logger.getLogger(JSystemDataDrivenTask.class.getName()); private String type; private String file; private String param; private String lineIndexes; private boolean shuffle; private long shuffleSeed; private boolean reverseOrder; private List<Map<String, Object>> data; private int iterationNum = 0; public void execute() throws BuildException { if (!JSystemAntUtil.doesContainerHaveEnabledTests(getUuid())) { return; } loadParameters(); final DataProvider provider = initProvider(); try { + // in case file is a reference, if not the file name will be as entered by the user - nir + String fileName = (String) ParametersManager.replaceReferenceWithValue(file, ParameterType.FILE); data = provider.provide(new File(file), param); } catch (DataCollectorException e) { log.log(Level.WARNING, "Failed to collect data due to " + e.getMessage()); return; } if (data == null || data.size() == 0) { log.log(Level.INFO, "Invalid data"); return; } filterData(); convertDataToLoop(); if (shuffle) { shuffleData(); } if (reverseOrder) { Collections.reverse(data); } super.execute(); } private DataProvider initProvider() { if (StringUtils.isEmpty(type)) { log.log(Level.WARNING, "No data provider type was specified. Rolling back to CSV provider"); return new CsvDataProvider(); } final String allProviderTypes = JSystemProperties.getInstance().getPreferenceOrDefault( FrameworkOptions.DATA_PROVIDER_CLASSES); if (StringUtils.isEmpty(allProviderTypes)) { log.log(Level.WARNING, "No providers were specified in the framework options. Rolling back to CSV provider"); return new CsvDataProvider(); } List<DataProvider> dataProvidersList = new ArrayList<DataProvider>(); for (String providerType : allProviderTypes.split(DELIMITER)) { final DataProvider provider = BeanUtils.createInstanceFromClassName(providerType, DataProvider.class); if (provider != null) { dataProvidersList.add(provider); } } for (DataProvider provider : dataProvidersList) { if (provider.getName() != null && provider.getName().trim().equals(type.trim())) { return provider; } } log.log(Level.WARNING, "No provider was found with name " + type + ". Rolling back to CSV provider"); return new CsvDataProvider(); } private void shuffleData() { if (shuffleSeed <= 0) { Collections.shuffle(data); } else { Collections.shuffle(data, new Random(shuffleSeed)); } } private void loadParameters() { type = getParameterFromProperties("Type", new CsvDataProvider().getName()); file = getParameterFromProperties("File", ""); param = getParameterFromProperties("Parameter", ""); try { param = ParametersManager.replaceAllReferenceValues(param, ParameterType.STRING); } catch (Exception e) { log.log(Level.SEVERE, "Error trying to replace reference parameters for input: " + param, e); } lineIndexes = getParameterFromProperties("LineIndexes", ""); shuffle = Boolean.valueOf(getParameterFromProperties("Shuffle", "false")); shuffleSeed = Long.parseLong(getParameterFromProperties("ShuffleSeed", "0")); reverseOrder = Boolean.parseBoolean(getParameterFromProperties("ReverseOrder", "false")); } /** * Change the data received from the collector to include only the lines * that are specified in the line indexes parameter */ private void filterData() { if (null == lineIndexes || lineIndexes.isEmpty()) { return; } final List<Integer> requiredNumbers = convertStringOfNumbersToList(lineIndexes.trim()); if (null == requiredNumbers || requiredNumbers.size() == 0) { return; } final List<Map<String, Object>> filteredData = new ArrayList<Map<String, Object>>(); for (int lineNumber : requiredNumbers) { // Notice that the line indexes are one-based if (data.size() < lineNumber) { continue; } filteredData.add(data.get(lineNumber - 1)); } if (filteredData.size() > 0) { // Only if there is something in the filtered data we will replace // the data with the filtered one. We do this to avoid exception at // run time when trying to iterate over empty list data = filteredData; } } private void convertDataToLoop() { final String paramName = data.get(0).keySet().toArray(new String[] {})[0]; StringBuilder sb = new StringBuilder(); for (Map<String, Object> dataRow : data) { sb.append(DELIMITER).append(dataRow.get(paramName)); } // Actually, we are not using this parameter, but we need it in order // for the the task to work. setParam("unusedparam"); // And, we are also not really using the list values, only pass it to // the for task in order to create the number of iterations required. setList(sb.toString().replaceFirst(DELIMITER, "")); } private static List<Integer> convertStringOfNumbersToList(final String numbers) { final Set<Integer> result = new HashSet<Integer>(); for (String numberStr : numbers.split(",")) { try { if (numberStr.contains("-")) { final String rangeNumbersStr[] = numberStr.split("-"); for (int i = Integer.parseInt(rangeNumbersStr[0]); i <= Integer.parseInt(rangeNumbersStr[1]); i++) { if (i > 0) { result.add(i); } } } else { int tempInt = Integer.parseInt(numberStr); if (tempInt > 0) { result.add(Integer.parseInt(numberStr)); } } } catch (NumberFormatException e) { continue; } } final List<Integer> sortedResult = new ArrayList<Integer>(result); Collections.sort(sortedResult); return sortedResult; } @Override protected void doSequentialIteration(String val) { MacroInstance instance = new MacroInstance(); instance.setProject(getProject()); instance.setOwningTarget(getOwningTarget()); instance.setMacroDef(getMacroDef()); Map<String, Object> dataRow = data.get(iterationNum++); for (String key : dataRow.keySet()) { if (dataRow.get(key) == null) { continue; } getProject().setProperty(key, dataRow.get(key).toString()); } // This parameter is not really used but we need to pass it to the for // loop. instance.setDynamicAttribute(getParam().toLowerCase(), val); instance.execute(); } public String getFile() { return file; } public void setFile(String file) { this.file = file; } public String getLineIndexes() { return lineIndexes; } public void setLineIndexes(String lineIndexes) { this.lineIndexes = lineIndexes; } }
true
true
public void execute() throws BuildException { if (!JSystemAntUtil.doesContainerHaveEnabledTests(getUuid())) { return; } loadParameters(); final DataProvider provider = initProvider(); try { data = provider.provide(new File(file), param); } catch (DataCollectorException e) { log.log(Level.WARNING, "Failed to collect data due to " + e.getMessage()); return; } if (data == null || data.size() == 0) { log.log(Level.INFO, "Invalid data"); return; } filterData(); convertDataToLoop(); if (shuffle) { shuffleData(); } if (reverseOrder) { Collections.reverse(data); } super.execute(); }
public void execute() throws BuildException { if (!JSystemAntUtil.doesContainerHaveEnabledTests(getUuid())) { return; } loadParameters(); final DataProvider provider = initProvider(); try { // in case file is a reference, if not the file name will be as entered by the user - nir String fileName = (String) ParametersManager.replaceReferenceWithValue(file, ParameterType.FILE); data = provider.provide(new File(file), param); } catch (DataCollectorException e) { log.log(Level.WARNING, "Failed to collect data due to " + e.getMessage()); return; } if (data == null || data.size() == 0) { log.log(Level.INFO, "Invalid data"); return; } filterData(); convertDataToLoop(); if (shuffle) { shuffleData(); } if (reverseOrder) { Collections.reverse(data); } super.execute(); }
diff --git a/src/share/classes/com/sun/tools/javafx/comp/JavafxMemberEnter.java b/src/share/classes/com/sun/tools/javafx/comp/JavafxMemberEnter.java index 1f0276acc..f3a8aaacd 100644 --- a/src/share/classes/com/sun/tools/javafx/comp/JavafxMemberEnter.java +++ b/src/share/classes/com/sun/tools/javafx/comp/JavafxMemberEnter.java @@ -1,961 +1,970 @@ /* * Copyright 1999-2007 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. */ package com.sun.tools.javafx.comp; import com.sun.tools.javac.code.*; import com.sun.tools.javac.jvm.*; import com.sun.tools.javac.tree.*; import com.sun.tools.javac.util.*; import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition; import com.sun.tools.javac.code.Symbol.*; import com.sun.tools.javac.code.Type.*; import com.sun.tools.javac.tree.JCTree.*; import static com.sun.tools.javac.code.Flags.*; import static com.sun.tools.javac.code.Kinds.*; import static com.sun.tools.javac.code.TypeTags.*; import static com.sun.tools.javac.tree.JCTree.SELECT; import com.sun.tools.javafx.tree.*; import com.sun.tools.javafx.code.JavafxClassSymbol; import com.sun.tools.javafx.code.JavafxFlags; import com.sun.tools.javafx.code.JavafxSymtab; import com.sun.tools.javafx.code.JavafxVarSymbol; import com.sun.tools.javafx.util.MsgSym; import javax.tools.JavaFileObject; import java.util.Set; import java.util.HashSet; /** * Add local declaratuions to current environment. * The main entry point is {@code memberEnter}, which is called from * {@link JavafxAttr} when {@code visit}-ing a tree that contains local * declarations. * * <p><b>This is NOT part of any API supported by Sun Microsystems. If * you write code that depends on this, you do so at your own risk. * This code and its internal interfaces are subject to change or * deletion without notice.</b> */ public class JavafxMemberEnter extends JavafxTreeScanner implements JavafxVisitor, Completer { protected static final Context.Key<JavafxMemberEnter> javafxMemberEnterKey = new Context.Key<JavafxMemberEnter>(); // JavaFX change protected final static boolean checkClash = true; private final Name.Table names; private final JavafxEnter enter; private final Log log; private final JavafxCheck chk; private final JavafxAttr attr; private final JavafxSymtab syms; private final JavafxTreeMaker make; private final ClassReader reader; private final JavafxTodo todo; private final JavafxAnnotate annotate; private final Types types; private final Target target; private final boolean skipAnnotations; public static JavafxMemberEnter instance(Context context) { JavafxMemberEnter instance = context.get(javafxMemberEnterKey); if (instance == null) instance = new JavafxMemberEnter(context); return instance; } protected JavafxMemberEnter(Context context) { context.put(javafxMemberEnterKey, this); names = Name.Table.instance(context); enter = JavafxEnter.instance(context); log = Log.instance(context); chk = (JavafxCheck)JavafxCheck.instance(context); attr = JavafxAttr.instance(context); syms = (JavafxSymtab)JavafxSymtab.instance(context); make = (JavafxTreeMaker)JavafxTreeMaker.instance(context); reader = JavafxClassReader.instance(context); todo = JavafxTodo.instance(context); annotate = JavafxAnnotate.instance(context); types = Types.instance(context); target = Target.instance(context); skipAnnotations = Options.instance(context).get("skipAnnotations") != null; } /** A queue for classes whose members still need to be entered into the * symbol table. */ ListBuffer<JavafxEnv<JavafxAttrContext>> halfcompleted = new ListBuffer<JavafxEnv<JavafxAttrContext>>(); /** Set to true only when the first of a set of classes is * processed from the halfcompleted queue. */ boolean isFirst = true; /** A flag to disable completion from time to time during member * enter, as we only need to look up types. This avoids * unnecessarily deep recursion. */ boolean completionEnabled = true; /* ---------- Processing import clauses ---------------- */ /** Import all classes of a class or package on demand. * @param pos Position to be used for error reporting. * @param tsym The class or package the members of which are imported. * @param toScope The (import) scope in which imported classes * are entered. */ // JavaFX change protected void importAll(int pos, final TypeSymbol tsym, JavafxEnv<JavafxAttrContext> env) { // Check that packages imported from exist (JLS ???). if (tsym.kind == PCK && tsym.members().elems == null && !tsym.exists()) { // If we can't find java.lang, exit immediately. if (((PackageSymbol)tsym).fullname.equals(names.java_lang)) { JCDiagnostic msg = JCDiagnostic.fragment(MsgSym.MESSAGE_FATAL_ERR_NO_JAVA_LANG); throw new FatalError(msg); } else { log.error(pos, MsgSym.MESSAGE_DOES_NOT_EXIST, tsym); } } final Scope fromScope = tsym.members(); final Scope toScope = env.toplevel.starImportScope; for (Scope.Entry e = fromScope.elems; e != null; e = e.sibling) { if (e.sym.kind == TYP && !toScope.includes(e.sym)) toScope.enter(e.sym, fromScope); } } /** Import all static members of a class or package on demand. * @param pos Position to be used for error reporting. * @param tsym The class or package the members of which are imported. * @param toScope The (import) scope in which imported classes * are entered. */ private void importStaticAll(int pos, final TypeSymbol tsym, JavafxEnv<JavafxAttrContext> env) { final JavaFileObject sourcefile = env.toplevel.sourcefile; final Scope toScope = env.toplevel.starImportScope; final PackageSymbol packge = env.toplevel.packge; final TypeSymbol origin = tsym; // enter imported types immediately new Object() { Set<Symbol> processed = new HashSet<Symbol>(); void importFrom(TypeSymbol tsym) { if (tsym == null || !processed.add(tsym)) return; // also import inherited names importFrom(types.supertype(tsym.type).tsym); for (Type t : types.interfaces(tsym.type)) importFrom(t.tsym); final Scope fromScope = tsym.members(); for (Scope.Entry e = fromScope.elems; e != null; e = e.sibling) { Symbol sym = e.sym; if (sym.kind == TYP && (sym.flags() & STATIC) != 0 && staticImportAccessible(sym, packge) && sym.isMemberOf(origin, types) && !toScope.includes(sym)) toScope.enter(sym, fromScope, origin.members()); } } }.importFrom(tsym); // enter non-types before annotations that might use them annotate.earlier(new JavafxAnnotate.Annotator() { Set<Symbol> processed = new HashSet<Symbol>(); @Override public String toString() { return "import static " + tsym + ".*" + " in " + sourcefile; } void importFrom(TypeSymbol tsym) { if (tsym == null || !processed.add(tsym)) return; // also import inherited names importFrom(types.supertype(tsym.type).tsym); for (Type t : types.interfaces(tsym.type)) importFrom(t.tsym); final Scope fromScope = tsym.members(); for (Scope.Entry e = fromScope.elems; e != null; e = e.sibling) { Symbol sym = e.sym; if (sym.isStatic() && sym.kind != TYP && staticImportAccessible(sym, packge) && !toScope.includes(sym) && sym.isMemberOf(origin, types)) { toScope.enter(sym, fromScope, origin.members()); } } } public void enterAnnotation() { importFrom(tsym); } }); } // is the sym accessible everywhere in packge? boolean staticImportAccessible(Symbol sym, PackageSymbol packge) { int flags = (int)(sym.flags() & AccessFlags); switch (flags) { default: case PUBLIC: return true; case PRIVATE: return false; case 0: case PROTECTED: return sym.packge() == packge; } } /** Import statics types of a given name. Non-types are handled in Attr. * @param pos Position to be used for error reporting. * @param tsym The class from which the name is imported. * @param name The (simple) name being imported. * @param env The environment containing the named import * scope to add to. */ private void importNamedStatic(final DiagnosticPosition pos, final TypeSymbol tsym, final Name name, final JavafxEnv<JavafxAttrContext> env) { if (tsym.kind != TYP) { log.error(pos, MsgSym.MESSAGE_STATIC_IMP_ONLY_CLASSES_AND_INTERFACES); return; } final Scope toScope = env.toplevel.namedImportScope; final PackageSymbol packge = env.toplevel.packge; final TypeSymbol origin = tsym; // enter imported types immediately new Object() { Set<Symbol> processed = new HashSet<Symbol>(); void importFrom(TypeSymbol tsym) { if (tsym == null || !processed.add(tsym)) return; // also import inherited names importFrom(types.supertype(tsym.type).tsym); for (Type t : types.interfaces(tsym.type)) importFrom(t.tsym); for (Scope.Entry e = tsym.members().lookup(name); e.scope != null; e = e.next()) { Symbol sym = e.sym; if (sym.isStatic() && sym.kind == TYP && staticImportAccessible(sym, packge) && sym.isMemberOf(origin, types) && chk.checkUniqueStaticImport(pos, sym, toScope)) toScope.enter(sym, sym.owner.members(), origin.members()); } } }.importFrom(tsym); // enter non-types before annotations that might use them annotate.earlier(new JavafxAnnotate.Annotator() { Set<Symbol> processed = new HashSet<Symbol>(); boolean found = false; @Override public String toString() { return "import static " + tsym + "." + name; } void importFrom(TypeSymbol tsym) { if (tsym == null || !processed.add(tsym)) return; // also import inherited names importFrom(types.supertype(tsym.type).tsym); for (Type t : types.interfaces(tsym.type)) importFrom(t.tsym); for (Scope.Entry e = tsym.members().lookup(name); e.scope != null; e = e.next()) { Symbol sym = e.sym; if (sym.isStatic() && staticImportAccessible(sym, packge) && sym.isMemberOf(origin, types)) { found = true; if (sym.kind == MTH || sym.kind != TYP && chk.checkUniqueStaticImport(pos, sym, toScope)) toScope.enter(sym, sym.owner.members(), origin.members()); } } } public void enterAnnotation() { JavaFileObject prev = log.useSource(env.toplevel.sourcefile); try { importFrom(tsym); if (!found) { log.error(pos, MsgSym.MESSAGE_CANNOT_RESOLVE_LOCATION, JCDiagnostic.fragment(MsgSym.KINDNAME_STATIC), name, "", "", JavafxResolve.typeKindName(tsym.type), tsym.type); } } finally { log.useSource(prev); } } }); } /** Import given class. * @param pos Position to be used for error reporting. * @param tsym The class to be imported. * @param env The environment containing the named import * scope to add to. */ void importNamed(DiagnosticPosition pos, Symbol tsym, JavafxEnv<JavafxAttrContext> env) { if (tsym.kind == TYP && chk.checkUniqueImport(pos, tsym, env.toplevel.namedImportScope)) env.toplevel.namedImportScope.enter(tsym, tsym.owner.members()); } /* ******************************************************************** * Visitor methods for member enter *********************************************************************/ /** Visitor argument: the current environment */ protected JavafxEnv<JavafxAttrContext> env; /** Enter field and method definitions and process import * clauses, catching any completion failure exceptions. */ void memberEnter(JCTree tree, JavafxEnv<JavafxAttrContext> env) { JavafxEnv<JavafxAttrContext> prevEnv = this.env; try { this.env = env; tree.accept(this); } catch (CompletionFailure ex) { chk.completionError(tree.pos(), ex); } finally { this.env = prevEnv; } } /** Enter members from a list of trees. */ void memberEnter(List<? extends JCTree> trees, JavafxEnv<JavafxAttrContext> env) { for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail) memberEnter(l.head, env); } @Override public void visitTree(JCTree tree) { if (tree instanceof JFXBlockExpression) visitBlockExpression((JFXBlockExpression) tree); else super.visitTree(tree); } @Override public void visitErroneous(JCErroneous tree) { memberEnter(tree.errs, env); } @Override public void visitTopLevel(JCCompilationUnit tree) { if (tree.starImportScope.elems != null) { // we must have already processed this toplevel return; } // check that no class exists with same fully qualified name as // toplevel package if (checkClash && tree.pid != null) { Symbol p = tree.packge; while (p.owner != syms.rootPackage) { p.owner.complete(); // enter all class members of p if (syms.classes.get(p.getQualifiedName()) != null) { log.error(tree.pos, MsgSym.MESSAGE_PKG_CLASHES_WITH_CLASS_OF_SAME_NAME, p); } p = p.owner; } } // process package annotations annotateLater(tree.packageAnnotations, env, tree.packge); // Import-on-demand the JavaFX types importNamed(tree.pos(), syms.javafx_StringType.tsym, env); importNamed(tree.pos(), syms.javafx_IntegerType.tsym, env); importNamed(tree.pos(), syms.javafx_BooleanType.tsym, env); importNamed(tree.pos(), syms.javafx_NumberType.tsym, env); // Process all import clauses. memberEnter(tree.defs, env); } @Override public void visitImport(JCImport tree) { JCTree imp = tree.qualid; Name name = TreeInfo.name(imp); TypeSymbol p; if (!tree.isStatic()) { if (tree.qualid.getTag() == SELECT) { if (name == names.fromString("Integer")) { // TODO: use the constant in the new NameTable when available. log.error(tree.pos, MsgSym.MESSAGE_JAVAFX_CANNOT_IMPORT_INTEGER_PRIMITIVE_TYPE); } else if (name == names.fromString("Number")) { // TODO: use the constant in the new NameTable when available. log.error(tree.pos, MsgSym.MESSAGE_JAVAFX_CANNOT_IMPORT_NUMBER_PRIMITIVE_TYPE); } else if (name == names.fromString("Boolean")) { // TODO: use the constant in the new NameTable when available. log.error(tree.pos, MsgSym.MESSAGE_JAVAFX_CANNOT_IMPORT_BOOLEAN_PRIMITIVE_TYPE); } else if (name == names.fromString("String")) { // TODO: use the constant in the new NameTable when available. log.error(tree.pos, MsgSym.MESSAGE_JAVAFX_CANNOT_IMPORT_STRING_PRIMITIVE_TYPE); } } } // Create a local environment pointing to this tree to disable // effects of other imports in Resolve.findGlobalType JavafxEnv<JavafxAttrContext> localEnv = env.dup(tree); // Attribute qualifying package or class. // The code structure here is rather ugly, but we'll // fix it when we do implicit-static-import. FIXME. if (imp instanceof JCFieldAccess) { JCFieldAccess s = (JCFieldAccess) imp; p = attr. attribTree(s.selected, localEnv, tree.staticImport ? TYP : (TYP | PCK), Type.noType).tsym; if (name == names.asterisk) { // Import on demand. chk.checkCanonical(s.selected); if (tree.staticImport) importStaticAll(tree.pos, p, env); else importAll(tree.pos, p, env); return; } else { // Named type import. if (tree.staticImport) { importNamedStatic(tree.pos(), p, name, localEnv); chk.checkCanonical(s.selected); return; } } } TypeSymbol c = attribImportType(imp, localEnv).tsym; chk.checkCanonical(imp); importNamed(tree.pos(), c, env); } /** Create a fresh environment for method bodies. * @param tree The method definition. * @param env The environment current outside of the method definition. */ JavafxEnv<JavafxAttrContext> methodEnv(JFXFunctionDefinition tree, JavafxEnv<JavafxAttrContext> env) { Scope localScope = new Scope(tree.sym); localScope.next = env.info.scope; JavafxEnv<JavafxAttrContext> localEnv = env.dup(tree, env.info.dup(localScope)); localEnv.outer = env; localEnv.enclMethod = tree; if ((tree.mods.flags & STATIC) != 0) localEnv.info.staticLevel++; return localEnv; } @Override public void scan(JCTree tree) { } @Override public void visitVarDef(JCVariableDecl tree) { assert false : "should not be here"; } @Override public void visitVar(JFXVar tree) { JavafxEnv<JavafxAttrContext> localEnv = env; if ((tree.mods.flags & STATIC) != 0 || (env.info.scope.owner.flags() & INTERFACE) != 0) { localEnv = env.dup(tree, env.info.dup()); localEnv.info.staticLevel++; } Scope enclScope = JavafxEnter.enterScope(env); JavafxVarSymbol v = new JavafxVarSymbol(0, tree.name, null, enclScope.owner); attr.varSymToTree.put(v, tree); tree.sym = v; SymbolCompleter completer = new SymbolCompleter(); completer.env = env; completer.tree = tree; completer.attr = attr; v.completer = completer; v.flags_field = chk.checkFlags(tree.pos(), tree.mods.flags, v, tree); if (tree.init != null) { v.flags_field |= HASINIT; } if (chk.checkUnique(tree.pos(), v, enclScope)) { chk.checkTransparentVar(tree.pos(), v, enclScope); enclScope.enter(v); } annotateLater(tree.mods.annotations, localEnv, v); v.pos = tree.pos; } @Override public void visitMethodDef(JCMethodDecl tree) { assert false; } static class SymbolCompleter implements Completer { JavafxEnv<JavafxAttrContext> env; JCTree tree; JavafxAttr attr; public void complete(Symbol m) throws CompletionFailure { if (tree instanceof JFXVar) attr.finishVar((JFXVar) tree, env); else if (attr.pt != Type.noType) { // finishOperationDefinition makes use of the expected type pt. // This is useful when coming from visitFunctionValue - i.e. // attributing an anonymous function. However, using the // expected type from a random call-site (which can happen if // we're called via complete) is a bit too flakey. // (ML can do it, because they unify across all the call-sites.) // This is a trick to run finishOperationDefinition, but in a // context where we're cleared the expected type attr.pt. m.completer = this; attr.attribExpr(tree, env); } else attr.finishOperationDefinition((JFXFunctionDefinition) tree, env); } } @Override public void visitFunctionDefinition(JFXFunctionDefinition tree) { Scope enclScope = JavafxEnter.enterScope(env); MethodSymbol m = new MethodSymbol(0, tree.name, null, enclScope.owner); m.flags_field = chk.checkFlags(tree.pos(), tree.mods.flags, m, tree); tree.sym = m; enclScope.enter(m); SymbolCompleter completer = new SymbolCompleter(); completer.env = env; completer.tree = tree; completer.attr = attr; m.completer = completer; attr.methodSymToTree.put(m, tree); } @Override public void visitReturn(JCReturn tree) { super.visitReturn(tree); } // Javafx modification // Begin JavaFX trees @Override public void visitClassDeclaration(JFXClassDeclaration that) { for (JCExpression superClass : that.getSupertypes()) { Type superType = attr.attribType(superClass, env); if (that.sym != null && that.sym instanceof JavafxClassSymbol) { if (superType != null && superType != Type.noType) { ((JavafxClassSymbol)that.sym).addSuperType(superType); } } } } /* ******************************************************************** * Type completion *********************************************************************/ Type attribImportType(JCTree tree, JavafxEnv<JavafxAttrContext> env) { assert completionEnabled; try { // To prevent deep recursion, suppress completion of some // types. completionEnabled = false; return attr.attribType(tree, env); } finally { completionEnabled = true; } } /* ******************************************************************** * Annotation processing *********************************************************************/ /** Queue annotations for later processing. */ // JavaFX change protected // JavaFX change void annotateLater(final List<JCAnnotation> annotations, final JavafxEnv<JavafxAttrContext> localEnv, final Symbol s) { if (annotations.isEmpty()) return; if (s.kind != PCK) s.attributes_field = null; // mark it incomplete for now annotate.later(new JavafxAnnotate.Annotator() { @Override public String toString() { return "annotate " + annotations + " onto " + s + " in " + s.owner; } public void enterAnnotation() { assert s.kind == PCK || s.attributes_field == null; JavaFileObject prev = log.useSource(localEnv.toplevel.sourcefile); try { if (s.attributes_field != null && s.attributes_field.nonEmpty() && annotations.nonEmpty()) log.error(annotations.head.pos, MsgSym.MESSAGE_ALREADY_ANNOTATED, JavafxResolve.kindName(s), s); enterAnnotations(annotations, localEnv, s); } finally { log.useSource(prev); } } }); } /** * Check if a list of annotations contains a reference to * java.lang.Deprecated. **/ private boolean hasDeprecatedAnnotation(List<JCAnnotation> annotations) { for (List<JCAnnotation> al = annotations; al.nonEmpty(); al = al.tail) { JCAnnotation a = al.head; if (a.annotationType.type == syms.deprecatedType && a.args.isEmpty()) return true; } return false; } /** Enter a set of annotations. */ private void enterAnnotations(List<JCAnnotation> annotations, JavafxEnv<JavafxAttrContext> env, Symbol s) { ListBuffer<Attribute.Compound> buf = new ListBuffer<Attribute.Compound>(); Set<TypeSymbol> annotated = new HashSet<TypeSymbol>(); if (!skipAnnotations) for (List<JCAnnotation> al = annotations; al.nonEmpty(); al = al.tail) { JCAnnotation a = al.head; Attribute.Compound c = annotate.enterAnnotation(a, syms.annotationType, env); if (c == null) continue; buf.append(c); // Note: @Deprecated has no effect on local variables and parameters if (!c.type.isErroneous() && s.owner.kind != MTH && types.isSameType(c.type, syms.deprecatedType)) s.flags_field |= Flags.DEPRECATED; if (!annotated.add(a.type.tsym)) log.error(a.pos, MsgSym.MESSAGE_DUPLICATE_ANNOTATION); } s.attributes_field = buf.toList(); } // Javafx change protected // Javafx change /** Queue processing of an attribute default value. */ void annotateDefaultValueLater(final JCExpression defaultValue, final JavafxEnv<JavafxAttrContext> localEnv, final MethodSymbol m) { annotate.later(new JavafxAnnotate.Annotator() { @Override public String toString() { return "annotate " + m.owner + "." + m + " default " + defaultValue; } public void enterAnnotation() { JavaFileObject prev = log.useSource(localEnv.toplevel.sourcefile); try { enterDefaultValue(defaultValue, localEnv, m); } finally { log.useSource(prev); } } }); } /** Enter a default value for an attribute method. */ private void enterDefaultValue(final JCExpression defaultValue, final JavafxEnv<JavafxAttrContext> localEnv, final MethodSymbol m) { m.defaultValue = annotate.enterAttributeValue(m.type.getReturnType(), defaultValue, localEnv); } /* ******************************************************************** * Source completer *********************************************************************/ /** Complete entering a class. * @param sym The symbol of the class to be completed. */ public void complete(Symbol sym) throws CompletionFailure { // Suppress some (recursive) MemberEnter invocations if (!completionEnabled) { // Re-install same completer for next time around and return. assert (sym.flags() & Flags.COMPOUND) == 0; sym.completer = this; return; } ClassSymbol c = (ClassSymbol)sym; ClassType ct = (ClassType)c.type; JavafxEnv<JavafxAttrContext> localEnv = enter.typeEnvs.get(c); JFXClassDeclaration tree = (JFXClassDeclaration)localEnv.tree; boolean wasFirst = isFirst; isFirst = false; JavaFileObject prev = log.useSource(localEnv.toplevel.sourcefile); try { // Save class environment for later member enter (2) processing. halfcompleted.append(localEnv); // If this is a toplevel-class, make sure any preceding import // clauses have been seen. if (c.owner.kind == PCK) { - memberEnter(localEnv.toplevel, localEnv.enclosing(JCTree.TOPLEVEL)); + for (JCTree def : localEnv.toplevel.defs) { + // Note we have to be careful to not yet visit member + // classes (and attribute their super-type), until + // we've set the super-types of this class. + // Otherwise we risk a stack overflow, at least in the + // tricky case of an inheritance cycle that includes the + // module class. There probably is a cleaner way ... + if (def instanceof JCImport) + memberEnter(localEnv.toplevel, localEnv.enclosing(JCTree.TOPLEVEL)); + } todo.append(localEnv); } // Mark class as not yet attributed. c.flags_field |= UNATTRIBUTED; if (c.owner.kind == TYP) c.owner.complete(); // create an environment for evaluating the base clauses JavafxEnv<JavafxAttrContext> baseEnv = baseEnv(tree, localEnv); //TODO: solesupertype implies a bug Type supertype = null, solesupertype = null; ListBuffer<Type> interfaces = new ListBuffer<Type>(); Set<Type> interfaceSet = new HashSet<Type>(); { ListBuffer<JCExpression> extending = ListBuffer.<JCExpression>lb(); ListBuffer<JCExpression> implementing = ListBuffer.<JCExpression>lb(); boolean compound = (tree.getModifiers().flags & Flags.FINAL) == 0; for (JCExpression stype : tree.getSupertypes()) { Type st = attr.attribType(stype, localEnv); if (st.isInterface()) { implementing.append(stype); } else { solesupertype = extending.isEmpty() ? st : null; extending.append(stype); if ((st.tsym.flags_field & JavafxFlags.COMPOUND_CLASS) == 0) { compound = false; supertype = st; } else { interfaces.append(st); chk.checkNotRepeated(stype.pos(), types.erasure(st), interfaceSet); } } } if (compound) c.flags_field |= JavafxFlags.COMPOUND_CLASS; tree.setDifferentiatedExtendingImplementing(extending.toList(), implementing.toList()); } if (supertype == null) supertype = ((tree.mods.flags & Flags.ENUM) != 0 && !target.compilerBootstrap(c)) ? attr.attribBase(enumBase(tree.pos, c), baseEnv, true, false, false) : (c.fullname == names.java_lang_Object) ? Type.noType : syms.objectType; ct.supertype_field = supertype; // Determine interfaces. List<JCExpression> interfaceTrees = tree.getImplementing(); if ((tree.mods.flags & Flags.ENUM) != 0 && target.compilerBootstrap(c)) { // add interface Comparable<T> interfaceTrees = interfaceTrees.prepend(make.Type(new ClassType(syms.comparableType.getEnclosingType(), List.of(c.type), syms.comparableType.tsym))); // add interface Serializable interfaceTrees = interfaceTrees.prepend(make.Type(syms.serializableType)); } for (JCExpression iface : interfaceTrees) { Type i = attr.attribBase(iface, baseEnv, false, true, true); if (i.tag == CLASS) { interfaces.append(i); chk.checkNotRepeated(iface.pos(), types.erasure(i), interfaceSet); } } if ((c.flags_field & ANNOTATION) != 0) ct.interfaces_field = List.of(syms.annotationType); else ct.interfaces_field = interfaces.toList(); if (c.fullname == names.java_lang_Object) { if (tree.getExtending().head != null) { chk.checkNonCyclic(tree.getExtending().head.pos(), supertype); ct.supertype_field = Type.noType; } else if (tree.getImplementing().nonEmpty()) { chk.checkNonCyclic(tree.getImplementing().head.pos(), ct.interfaces_field.head); ct.interfaces_field = List.nil(); } } // Annotations. // In general, we cannot fully process annotations yet, but we // can attribute the annotation types and then check to see if the // @Deprecated annotation is present. attr.attribAnnotationTypes(tree.mods.annotations, baseEnv); if (hasDeprecatedAnnotation(tree.mods.annotations)) c.flags_field |= DEPRECATED; annotateLater(tree.mods.annotations, baseEnv, c); attr.attribTypeVariables(tree.getEmptyTypeParameters(), baseEnv); chk.checkNonCyclic(tree.pos(), c.type); // If this is a class, enter symbols for this and super into // current scope. if ((c.flags_field & INTERFACE) == 0) { VarSymbol thisSym = new VarSymbol(FINAL | HASINIT, names._this, c.type, c); thisSym.pos = Position.FIRSTPOS; localEnv.info.scope.enter(thisSym); if (ct.supertype_field.tag == CLASS && solesupertype != null) { VarSymbol superSym = new VarSymbol(FINAL | HASINIT, names._super, solesupertype, c); superSym.pos = Position.FIRSTPOS; localEnv.info.scope.enter(superSym); } } // check that no package exists with same fully qualified name, // but admit classes in the unnamed package which have the same // name as a top-level package. if (checkClash && c.owner.kind == PCK && c.owner != syms.unnamedPackage && reader.packageExists(c.fullname)) { log.error(tree.pos, MsgSym.MESSAGE_CLASH_WITH_PKG_OF_SAME_NAME, c); } } catch (CompletionFailure ex) { chk.completionError(tree.pos(), ex); } finally { log.useSource(prev); } // Enter all member fields and methods of a set of half completed // classes in a second phase. if (wasFirst) { try { while (halfcompleted.nonEmpty()) { finish(halfcompleted.next()); } } finally { isFirst = true; } // commit pending annotations annotate.flush(); } } private JavafxEnv<JavafxAttrContext> baseEnv(JFXClassDeclaration tree, JavafxEnv<JavafxAttrContext> env) { Scope typaramScope = new Scope(tree.sym); if (tree.getEmptyTypeParameters() != null) for (List<JCTypeParameter> typarams = tree.getEmptyTypeParameters(); typarams.nonEmpty(); typarams = typarams.tail) typaramScope.enter(typarams.head.type.tsym); JavafxEnv<JavafxAttrContext> outer = env.outer; // the base clause can't see members of this class JavafxEnv<JavafxAttrContext> localEnv = outer.dup(tree, outer.info.dup(typaramScope)); localEnv.baseClause = true; localEnv.outer = outer; localEnv.info.isSelfCall = false; return localEnv; } /** Enter member fields and methods of a class * @param env the environment current for the class block. */ private void finish(JavafxEnv<JavafxAttrContext> env) { JavaFileObject prev = log.useSource(env.toplevel.sourcefile); try { JFXClassDeclaration tree = (JFXClassDeclaration)env.tree; memberEnter(tree.getMembers(), env); } finally { log.useSource(prev); } } /** Generate a base clause for an enum type. * @param pos The position for trees and diagnostics, if any * @param c The class symbol of the enum */ private JCExpression enumBase(int pos, ClassSymbol c) { JCExpression result = make.at(pos). TypeApply(make.QualIdent(syms.enumSym), List.<JCExpression>of(make.Type(c.type))); return result; } }
true
true
public void complete(Symbol sym) throws CompletionFailure { // Suppress some (recursive) MemberEnter invocations if (!completionEnabled) { // Re-install same completer for next time around and return. assert (sym.flags() & Flags.COMPOUND) == 0; sym.completer = this; return; } ClassSymbol c = (ClassSymbol)sym; ClassType ct = (ClassType)c.type; JavafxEnv<JavafxAttrContext> localEnv = enter.typeEnvs.get(c); JFXClassDeclaration tree = (JFXClassDeclaration)localEnv.tree; boolean wasFirst = isFirst; isFirst = false; JavaFileObject prev = log.useSource(localEnv.toplevel.sourcefile); try { // Save class environment for later member enter (2) processing. halfcompleted.append(localEnv); // If this is a toplevel-class, make sure any preceding import // clauses have been seen. if (c.owner.kind == PCK) { memberEnter(localEnv.toplevel, localEnv.enclosing(JCTree.TOPLEVEL)); todo.append(localEnv); } // Mark class as not yet attributed. c.flags_field |= UNATTRIBUTED; if (c.owner.kind == TYP) c.owner.complete(); // create an environment for evaluating the base clauses JavafxEnv<JavafxAttrContext> baseEnv = baseEnv(tree, localEnv); //TODO: solesupertype implies a bug Type supertype = null, solesupertype = null; ListBuffer<Type> interfaces = new ListBuffer<Type>(); Set<Type> interfaceSet = new HashSet<Type>(); { ListBuffer<JCExpression> extending = ListBuffer.<JCExpression>lb(); ListBuffer<JCExpression> implementing = ListBuffer.<JCExpression>lb(); boolean compound = (tree.getModifiers().flags & Flags.FINAL) == 0; for (JCExpression stype : tree.getSupertypes()) { Type st = attr.attribType(stype, localEnv); if (st.isInterface()) { implementing.append(stype); } else { solesupertype = extending.isEmpty() ? st : null; extending.append(stype); if ((st.tsym.flags_field & JavafxFlags.COMPOUND_CLASS) == 0) { compound = false; supertype = st; } else { interfaces.append(st); chk.checkNotRepeated(stype.pos(), types.erasure(st), interfaceSet); } } } if (compound) c.flags_field |= JavafxFlags.COMPOUND_CLASS; tree.setDifferentiatedExtendingImplementing(extending.toList(), implementing.toList()); } if (supertype == null) supertype = ((tree.mods.flags & Flags.ENUM) != 0 && !target.compilerBootstrap(c)) ? attr.attribBase(enumBase(tree.pos, c), baseEnv, true, false, false) : (c.fullname == names.java_lang_Object) ? Type.noType : syms.objectType; ct.supertype_field = supertype; // Determine interfaces. List<JCExpression> interfaceTrees = tree.getImplementing(); if ((tree.mods.flags & Flags.ENUM) != 0 && target.compilerBootstrap(c)) { // add interface Comparable<T> interfaceTrees = interfaceTrees.prepend(make.Type(new ClassType(syms.comparableType.getEnclosingType(), List.of(c.type), syms.comparableType.tsym))); // add interface Serializable interfaceTrees = interfaceTrees.prepend(make.Type(syms.serializableType)); } for (JCExpression iface : interfaceTrees) { Type i = attr.attribBase(iface, baseEnv, false, true, true); if (i.tag == CLASS) { interfaces.append(i); chk.checkNotRepeated(iface.pos(), types.erasure(i), interfaceSet); } } if ((c.flags_field & ANNOTATION) != 0) ct.interfaces_field = List.of(syms.annotationType); else ct.interfaces_field = interfaces.toList(); if (c.fullname == names.java_lang_Object) { if (tree.getExtending().head != null) { chk.checkNonCyclic(tree.getExtending().head.pos(), supertype); ct.supertype_field = Type.noType; } else if (tree.getImplementing().nonEmpty()) { chk.checkNonCyclic(tree.getImplementing().head.pos(), ct.interfaces_field.head); ct.interfaces_field = List.nil(); } } // Annotations. // In general, we cannot fully process annotations yet, but we // can attribute the annotation types and then check to see if the // @Deprecated annotation is present. attr.attribAnnotationTypes(tree.mods.annotations, baseEnv); if (hasDeprecatedAnnotation(tree.mods.annotations)) c.flags_field |= DEPRECATED; annotateLater(tree.mods.annotations, baseEnv, c); attr.attribTypeVariables(tree.getEmptyTypeParameters(), baseEnv); chk.checkNonCyclic(tree.pos(), c.type); // If this is a class, enter symbols for this and super into // current scope. if ((c.flags_field & INTERFACE) == 0) { VarSymbol thisSym = new VarSymbol(FINAL | HASINIT, names._this, c.type, c); thisSym.pos = Position.FIRSTPOS; localEnv.info.scope.enter(thisSym); if (ct.supertype_field.tag == CLASS && solesupertype != null) { VarSymbol superSym = new VarSymbol(FINAL | HASINIT, names._super, solesupertype, c); superSym.pos = Position.FIRSTPOS; localEnv.info.scope.enter(superSym); } } // check that no package exists with same fully qualified name, // but admit classes in the unnamed package which have the same // name as a top-level package. if (checkClash && c.owner.kind == PCK && c.owner != syms.unnamedPackage && reader.packageExists(c.fullname)) { log.error(tree.pos, MsgSym.MESSAGE_CLASH_WITH_PKG_OF_SAME_NAME, c); } } catch (CompletionFailure ex) { chk.completionError(tree.pos(), ex); } finally { log.useSource(prev); } // Enter all member fields and methods of a set of half completed // classes in a second phase. if (wasFirst) { try { while (halfcompleted.nonEmpty()) { finish(halfcompleted.next()); } } finally { isFirst = true; } // commit pending annotations annotate.flush(); } }
public void complete(Symbol sym) throws CompletionFailure { // Suppress some (recursive) MemberEnter invocations if (!completionEnabled) { // Re-install same completer for next time around and return. assert (sym.flags() & Flags.COMPOUND) == 0; sym.completer = this; return; } ClassSymbol c = (ClassSymbol)sym; ClassType ct = (ClassType)c.type; JavafxEnv<JavafxAttrContext> localEnv = enter.typeEnvs.get(c); JFXClassDeclaration tree = (JFXClassDeclaration)localEnv.tree; boolean wasFirst = isFirst; isFirst = false; JavaFileObject prev = log.useSource(localEnv.toplevel.sourcefile); try { // Save class environment for later member enter (2) processing. halfcompleted.append(localEnv); // If this is a toplevel-class, make sure any preceding import // clauses have been seen. if (c.owner.kind == PCK) { for (JCTree def : localEnv.toplevel.defs) { // Note we have to be careful to not yet visit member // classes (and attribute their super-type), until // we've set the super-types of this class. // Otherwise we risk a stack overflow, at least in the // tricky case of an inheritance cycle that includes the // module class. There probably is a cleaner way ... if (def instanceof JCImport) memberEnter(localEnv.toplevel, localEnv.enclosing(JCTree.TOPLEVEL)); } todo.append(localEnv); } // Mark class as not yet attributed. c.flags_field |= UNATTRIBUTED; if (c.owner.kind == TYP) c.owner.complete(); // create an environment for evaluating the base clauses JavafxEnv<JavafxAttrContext> baseEnv = baseEnv(tree, localEnv); //TODO: solesupertype implies a bug Type supertype = null, solesupertype = null; ListBuffer<Type> interfaces = new ListBuffer<Type>(); Set<Type> interfaceSet = new HashSet<Type>(); { ListBuffer<JCExpression> extending = ListBuffer.<JCExpression>lb(); ListBuffer<JCExpression> implementing = ListBuffer.<JCExpression>lb(); boolean compound = (tree.getModifiers().flags & Flags.FINAL) == 0; for (JCExpression stype : tree.getSupertypes()) { Type st = attr.attribType(stype, localEnv); if (st.isInterface()) { implementing.append(stype); } else { solesupertype = extending.isEmpty() ? st : null; extending.append(stype); if ((st.tsym.flags_field & JavafxFlags.COMPOUND_CLASS) == 0) { compound = false; supertype = st; } else { interfaces.append(st); chk.checkNotRepeated(stype.pos(), types.erasure(st), interfaceSet); } } } if (compound) c.flags_field |= JavafxFlags.COMPOUND_CLASS; tree.setDifferentiatedExtendingImplementing(extending.toList(), implementing.toList()); } if (supertype == null) supertype = ((tree.mods.flags & Flags.ENUM) != 0 && !target.compilerBootstrap(c)) ? attr.attribBase(enumBase(tree.pos, c), baseEnv, true, false, false) : (c.fullname == names.java_lang_Object) ? Type.noType : syms.objectType; ct.supertype_field = supertype; // Determine interfaces. List<JCExpression> interfaceTrees = tree.getImplementing(); if ((tree.mods.flags & Flags.ENUM) != 0 && target.compilerBootstrap(c)) { // add interface Comparable<T> interfaceTrees = interfaceTrees.prepend(make.Type(new ClassType(syms.comparableType.getEnclosingType(), List.of(c.type), syms.comparableType.tsym))); // add interface Serializable interfaceTrees = interfaceTrees.prepend(make.Type(syms.serializableType)); } for (JCExpression iface : interfaceTrees) { Type i = attr.attribBase(iface, baseEnv, false, true, true); if (i.tag == CLASS) { interfaces.append(i); chk.checkNotRepeated(iface.pos(), types.erasure(i), interfaceSet); } } if ((c.flags_field & ANNOTATION) != 0) ct.interfaces_field = List.of(syms.annotationType); else ct.interfaces_field = interfaces.toList(); if (c.fullname == names.java_lang_Object) { if (tree.getExtending().head != null) { chk.checkNonCyclic(tree.getExtending().head.pos(), supertype); ct.supertype_field = Type.noType; } else if (tree.getImplementing().nonEmpty()) { chk.checkNonCyclic(tree.getImplementing().head.pos(), ct.interfaces_field.head); ct.interfaces_field = List.nil(); } } // Annotations. // In general, we cannot fully process annotations yet, but we // can attribute the annotation types and then check to see if the // @Deprecated annotation is present. attr.attribAnnotationTypes(tree.mods.annotations, baseEnv); if (hasDeprecatedAnnotation(tree.mods.annotations)) c.flags_field |= DEPRECATED; annotateLater(tree.mods.annotations, baseEnv, c); attr.attribTypeVariables(tree.getEmptyTypeParameters(), baseEnv); chk.checkNonCyclic(tree.pos(), c.type); // If this is a class, enter symbols for this and super into // current scope. if ((c.flags_field & INTERFACE) == 0) { VarSymbol thisSym = new VarSymbol(FINAL | HASINIT, names._this, c.type, c); thisSym.pos = Position.FIRSTPOS; localEnv.info.scope.enter(thisSym); if (ct.supertype_field.tag == CLASS && solesupertype != null) { VarSymbol superSym = new VarSymbol(FINAL | HASINIT, names._super, solesupertype, c); superSym.pos = Position.FIRSTPOS; localEnv.info.scope.enter(superSym); } } // check that no package exists with same fully qualified name, // but admit classes in the unnamed package which have the same // name as a top-level package. if (checkClash && c.owner.kind == PCK && c.owner != syms.unnamedPackage && reader.packageExists(c.fullname)) { log.error(tree.pos, MsgSym.MESSAGE_CLASH_WITH_PKG_OF_SAME_NAME, c); } } catch (CompletionFailure ex) { chk.completionError(tree.pos(), ex); } finally { log.useSource(prev); } // Enter all member fields and methods of a set of half completed // classes in a second phase. if (wasFirst) { try { while (halfcompleted.nonEmpty()) { finish(halfcompleted.next()); } } finally { isFirst = true; } // commit pending annotations annotate.flush(); } }
diff --git a/src/com/android/launcher2/LauncherModel.java b/src/com/android/launcher2/LauncherModel.java index d76e0260..fc97832a 100644 --- a/src/com/android/launcher2/LauncherModel.java +++ b/src/com/android/launcher2/LauncherModel.java @@ -1,1187 +1,1190 @@ /* * Copyright (C) 2008 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.content.BroadcastReceiver; import android.content.ComponentName; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Intent; import android.content.Context; import android.content.pm.ActivityInfo; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.content.res.Resources; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.util.Log; import android.os.Process; import android.os.SystemClock; import java.lang.ref.WeakReference; import java.net.URISyntaxException; import java.text.Collator; import java.util.ArrayList; import java.util.Comparator; import java.util.Collections; import java.util.HashMap; import java.util.List; /** * Maintains in-memory state of the Launcher. It is expected that there should be only one * LauncherModel object held in a static. Also provide APIs for updating the database state * for the Launcher. */ public class LauncherModel extends BroadcastReceiver { static final boolean DEBUG_LOADERS = true; static final String TAG = "Launcher.Model"; private final LauncherApplication mApp; private final Object mLock = new Object(); private DeferredHandler mHandler = new DeferredHandler(); private Loader mLoader = new Loader(); private boolean mBeforeFirstLoad = true; private WeakReference<Callbacks> mCallbacks; private AllAppsList mAllAppsList = new AllAppsList(); public interface Callbacks { public int getCurrentWorkspaceScreen(); public void startBinding(); public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end); public void bindFolders(HashMap<Long,FolderInfo> folders); public void finishBindingItems(); public void bindAppWidget(LauncherAppWidgetInfo info); public void bindAllApplications(ArrayList<ApplicationInfo> apps); public void bindPackageAdded(ArrayList<ApplicationInfo> apps); public void bindPackageUpdated(String packageName, ArrayList<ApplicationInfo> apps); public void bindPackageRemoved(String packageName, ArrayList<ApplicationInfo> apps); } LauncherModel(LauncherApplication app) { mApp = app; } /** * Adds an item to the DB if it was not created previously, or move it to a new * <container, screen, cellX, cellY> */ static void addOrMoveItemInDatabase(Context context, ItemInfo item, long container, int screen, int cellX, int cellY) { if (item.container == ItemInfo.NO_ID) { // From all apps addItemToDatabase(context, item, container, screen, cellX, cellY, false); } else { // From somewhere else moveItemInDatabase(context, item, container, screen, cellX, cellY); } } /** * Move an item in the DB to a new <container, screen, cellX, cellY> */ static void moveItemInDatabase(Context context, ItemInfo item, long container, int screen, int cellX, int cellY) { item.container = container; item.screen = screen; item.cellX = cellX; item.cellY = cellY; final ContentValues values = new ContentValues(); final ContentResolver cr = context.getContentResolver(); values.put(LauncherSettings.Favorites.CONTAINER, item.container); values.put(LauncherSettings.Favorites.CELLX, item.cellX); values.put(LauncherSettings.Favorites.CELLY, item.cellY); values.put(LauncherSettings.Favorites.SCREEN, item.screen); cr.update(LauncherSettings.Favorites.getContentUri(item.id, false), values, null, null); } /** * Returns true if the shortcuts already exists in the database. * we identify a shortcut by its title and intent. */ static boolean shortcutExists(Context context, String title, Intent intent) { final ContentResolver cr = context.getContentResolver(); Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] { "title", "intent" }, "title=? and intent=?", new String[] { title, intent.toUri(0) }, null); boolean result = false; try { result = c.moveToFirst(); } finally { c.close(); } return result; } /** * Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList. */ FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) { final ContentResolver cr = context.getContentResolver(); Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null, "_id=? and (itemType=? or itemType=?)", new String[] { String.valueOf(id), String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER), String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER) }, null); try { if (c.moveToFirst()) { final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE); final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE); final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER); final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN); final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX); final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY); FolderInfo folderInfo = null; switch (c.getInt(itemTypeIndex)) { case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER: folderInfo = findOrMakeUserFolder(folderList, id); break; case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER: folderInfo = findOrMakeLiveFolder(folderList, id); break; } folderInfo.title = c.getString(titleIndex); folderInfo.id = id; folderInfo.container = c.getInt(containerIndex); folderInfo.screen = c.getInt(screenIndex); folderInfo.cellX = c.getInt(cellXIndex); folderInfo.cellY = c.getInt(cellYIndex); return folderInfo; } } finally { c.close(); } return null; } /** * Add an item to the database in a specified container. Sets the container, screen, cellX and * cellY fields of the item. Also assigns an ID to the item. */ static void addItemToDatabase(Context context, ItemInfo item, long container, int screen, int cellX, int cellY, boolean notify) { item.container = container; item.screen = screen; item.cellX = cellX; item.cellY = cellY; final ContentValues values = new ContentValues(); final ContentResolver cr = context.getContentResolver(); item.onAddToDatabase(values); Uri result = cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI : LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values); if (result != null) { item.id = Integer.parseInt(result.getPathSegments().get(1)); } } /** * Update an item to the database in a specified container. */ static void updateItemInDatabase(Context context, ItemInfo item) { final ContentValues values = new ContentValues(); final ContentResolver cr = context.getContentResolver(); item.onAddToDatabase(values); cr.update(LauncherSettings.Favorites.getContentUri(item.id, false), values, null, null); } /** * Removes the specified item from the database * @param context * @param item */ static void deleteItemFromDatabase(Context context, ItemInfo item) { final ContentResolver cr = context.getContentResolver(); cr.delete(LauncherSettings.Favorites.getContentUri(item.id, false), null, null); } /** * Remove the contents of the specified folder from the database */ static void deleteUserFolderContentsFromDatabase(Context context, UserFolderInfo info) { final ContentResolver cr = context.getContentResolver(); cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null); cr.delete(LauncherSettings.Favorites.CONTENT_URI, LauncherSettings.Favorites.CONTAINER + "=" + info.id, null); } /** * Set this as the current Launcher activity object for the loader. */ public void initialize(Callbacks callbacks) { synchronized (mLock) { mCallbacks = new WeakReference<Callbacks>(callbacks); } } public void startLoader(Context context, boolean isLaunching) { mLoader.startLoader(context, isLaunching); } public void stopLoader() { mLoader.stopLoader(); } /** * We pick up most of the changes to all apps. */ public void setAllAppsDirty() { mLoader.setAllAppsDirty(); } public void setWorkspaceDirty() { mLoader.setWorkspaceDirty(); } /** * Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and * ACTION_PACKAGE_CHANGED. */ public void onReceive(Context context, Intent intent) { Log.d(TAG, "onReceive intent=" + intent); // Use the app as the context. context = mApp; final String packageName = intent.getData().getSchemeSpecificPart(); ArrayList<ApplicationInfo> added = null; ArrayList<ApplicationInfo> removed = null; ArrayList<ApplicationInfo> modified = null; boolean update = false; boolean remove = false; synchronized (mLock) { if (mBeforeFirstLoad) { // If we haven't even loaded yet, don't bother, since we'll just pick // up the changes. return; } final String action = intent.getAction(); final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false); if (packageName == null || packageName.length() == 0) { // they sent us a bad intent return; } if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) { mAllAppsList.updatePackage(context, packageName); update = true; } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) { if (!replacing) { mAllAppsList.removePackage(packageName); remove = true; } // else, we are replacing the package, so a PACKAGE_ADDED will be sent // later, we will update the package at this time } else { if (!replacing) { mAllAppsList.addPackage(context, packageName); } else { mAllAppsList.updatePackage(context, packageName); update = true; } } if (mAllAppsList.added.size() > 0) { added = mAllAppsList.added; mAllAppsList.added = new ArrayList<ApplicationInfo>(); } if (mAllAppsList.removed.size() > 0) { removed = mAllAppsList.removed; mAllAppsList.removed = new ArrayList<ApplicationInfo>(); for (ApplicationInfo info: removed) { AppInfoCache.remove(info.intent.getComponent()); } } if (mAllAppsList.modified.size() > 0) { modified = mAllAppsList.modified; mAllAppsList.modified = new ArrayList<ApplicationInfo>(); } final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == null) { Log.d(TAG, "nobody to tell about the new app"); return; } if (added != null) { final ArrayList<ApplicationInfo> addedFinal = added; mHandler.post(new Runnable() { public void run() { callbacks.bindPackageAdded(addedFinal); } }); } if (update || modified != null) { final ArrayList<ApplicationInfo> modifiedFinal = modified; mHandler.post(new Runnable() { public void run() { callbacks.bindPackageUpdated(packageName, modifiedFinal); } }); } if (remove || removed != null) { final ArrayList<ApplicationInfo> removedFinal = removed; mHandler.post(new Runnable() { public void run() { callbacks.bindPackageRemoved(packageName, removedFinal); } }); } } } public class Loader { private static final int ITEMS_CHUNK = 6; private LoaderThread mLoaderThread; private int mLastWorkspaceSeq = 0; private int mWorkspaceSeq = 1; private int mLastAllAppsSeq = 0; private int mAllAppsSeq = 1; final ArrayList<ItemInfo> mItems = new ArrayList<ItemInfo>(); final ArrayList<LauncherAppWidgetInfo> mAppWidgets = new ArrayList<LauncherAppWidgetInfo>(); final HashMap<Long, FolderInfo> mFolders = new HashMap<Long, FolderInfo>(); /** * Call this from the ui thread so the handler is initialized on the correct thread. */ public Loader() { } public void startLoader(Context context, boolean isLaunching) { synchronized (mLock) { Log.d(TAG, "startLoader isLaunching=" + isLaunching); // Don't bother to start the thread if we know it's not going to do anything if (mCallbacks.get() != null) { LoaderThread oldThread = mLoaderThread; if (oldThread != null) { if (oldThread.isLaunching()) { // don't downgrade isLaunching if we're already running isLaunching = true; } oldThread.stopLocked(); } mLoaderThread = new LoaderThread(context, oldThread, isLaunching); mLoaderThread.start(); } } } public void stopLoader() { synchronized (mLock) { if (mLoaderThread != null) { mLoaderThread.stopLocked(); } } } public void setWorkspaceDirty() { synchronized (mLock) { mWorkspaceSeq++; } } public void setAllAppsDirty() { synchronized (mLock) { mAllAppsSeq++; } } /** * Runnable for the thread that loads the contents of the launcher: * - workspace icons * - widgets * - all apps icons */ private class LoaderThread extends Thread { private Context mContext; private Thread mWaitThread; private boolean mIsLaunching; private boolean mStopped; private boolean mWorkspaceDoneBinding; LoaderThread(Context context, Thread waitThread, boolean isLaunching) { mContext = context; mWaitThread = waitThread; mIsLaunching = isLaunching; } boolean isLaunching() { return mIsLaunching; } /** * If another LoaderThread was supplied, we need to wait for that to finish before * we start our processing. This keeps the ordering of the setting and clearing * of the dirty flags correct by making sure we don't start processing stuff until * they've had a chance to re-set them. We do this waiting the worker thread, not * the ui thread to avoid ANRs. */ private void waitForOtherThread() { if (mWaitThread != null) { boolean done = false; while (!done) { try { mWaitThread.join(); done = true; } catch (InterruptedException ex) { // Ignore } } mWaitThread = null; } } public void run() { waitForOtherThread(); // Elevate priority when Home launches for the first time to avoid // starving at boot time. Staring at a blank home is not cool. synchronized (mLock) { android.os.Process.setThreadPriority(mIsLaunching ? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND); } // Load the workspace only if it's dirty. int workspaceSeq; boolean workspaceDirty; synchronized (mLock) { workspaceSeq = mWorkspaceSeq; workspaceDirty = mWorkspaceSeq != mLastWorkspaceSeq; } if (workspaceDirty) { loadWorkspace(); } synchronized (mLock) { // If we're not stopped, and nobody has incremented mWorkspaceSeq. if (mStopped) { return; } if (workspaceSeq == mWorkspaceSeq) { mLastWorkspaceSeq = mWorkspaceSeq; } } // Bind the workspace bindWorkspace(); // Wait until the either we're stopped or the other threads are done. // This way we don't start loading all apps until the workspace has settled // down. synchronized (LoaderThread.this) { mHandler.postIdle(new Runnable() { public void run() { synchronized (LoaderThread.this) { mWorkspaceDoneBinding = true; Log.d(TAG, "done with workspace"); LoaderThread.this.notify(); } } }); Log.d(TAG, "waiting to be done with workspace"); while (!mStopped && !mWorkspaceDoneBinding) { try { this.wait(); } catch (InterruptedException ex) { // Ignore } } Log.d(TAG, "done waiting to be done with workspace"); } // Load all apps if they're dirty int allAppsSeq; boolean allAppsDirty; synchronized (mLock) { allAppsSeq = mAllAppsSeq; allAppsDirty = mAllAppsSeq != mLastAllAppsSeq; //Log.d(TAG, "mAllAppsSeq=" + mAllAppsSeq // + " mLastAllAppsSeq=" + mLastAllAppsSeq + " allAppsDirty"); } if (allAppsDirty) { loadAllApps(); } synchronized (mLock) { // If we're not stopped, and nobody has incremented mAllAppsSeq. if (mStopped) { return; } if (allAppsSeq == mAllAppsSeq) { mLastAllAppsSeq = mAllAppsSeq; } } // Bind all apps if (allAppsDirty) { bindAllApps(); } // Clear out this reference, otherwise we end up holding it until all of the // callback runnables are done. mContext = null; synchronized (mLock) { // Setting the reference is atomic, but we can't do it inside the other critical // sections. mLoaderThread = null; } } public void stopLocked() { synchronized (LoaderThread.this) { mStopped = true; this.notify(); } } /** * Gets the callbacks object. If we've been stopped, or if the launcher object * has somehow been garbage collected, return null instead. */ Callbacks tryGetCallbacks() { synchronized (mLock) { if (mStopped) { return null; } final Callbacks callbacks = mCallbacks.get(); if (callbacks == null) { Log.w(TAG, "no mCallbacks"); return null; } return callbacks; } } private void loadWorkspace() { long t = SystemClock.uptimeMillis(); final Context context = mContext; final ContentResolver contentResolver = context.getContentResolver(); final PackageManager manager = context.getPackageManager(); /* TODO if (mLocaleChanged) { updateShortcutLabels(contentResolver, manager); } */ mItems.clear(); mAppWidgets.clear(); final Cursor c = contentResolver.query( LauncherSettings.Favorites.CONTENT_URI, null, null, null, null); try { final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID); final int intentIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.INTENT); final int titleIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.TITLE); final int iconTypeIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ICON_TYPE); final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON); final int iconPackageIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ICON_PACKAGE); final int iconResourceIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ICON_RESOURCE); final int containerIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.CONTAINER); final int itemTypeIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ITEM_TYPE); final int appWidgetIdIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.APPWIDGET_ID); final int screenIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.SCREEN); final int cellXIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.CELLX); final int cellYIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.CELLY); final int spanXIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.SPANX); final int spanYIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.SPANY); final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI); final int displayModeIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.DISPLAY_MODE); ApplicationInfo info; String intentDescription; Widget widgetInfo; LauncherAppWidgetInfo appWidgetInfo; int container; long id; Intent intent; while (!mStopped && c.moveToNext()) { try { int itemType = c.getInt(itemTypeIndex); switch (itemType) { case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: intentDescription = c.getString(intentIndex); try { intent = Intent.parseUri(intentDescription, 0); } catch (URISyntaxException e) { continue; } if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) { info = getApplicationInfo(manager, intent, context); } else { info = getApplicationInfoShortcut(c, context, iconTypeIndex, iconPackageIndex, iconResourceIndex, iconIndex); } if (info == null) { info = new ApplicationInfo(); info.icon = manager.getDefaultActivityIcon(); } if (info != null) { - info.title = c.getString(titleIndex); + if (itemType + != LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) { + info.title = c.getString(titleIndex); + } info.intent = intent; info.id = c.getLong(idIndex); container = c.getInt(containerIndex); info.container = container; info.screen = c.getInt(screenIndex); info.cellX = c.getInt(cellXIndex); info.cellY = c.getInt(cellYIndex); switch (container) { case LauncherSettings.Favorites.CONTAINER_DESKTOP: mItems.add(info); break; default: // Item is in a user folder UserFolderInfo folderInfo = findOrMakeUserFolder(mFolders, container); folderInfo.add(info); break; } } break; case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER: id = c.getLong(idIndex); UserFolderInfo folderInfo = findOrMakeUserFolder(mFolders, id); folderInfo.title = c.getString(titleIndex); folderInfo.id = id; container = c.getInt(containerIndex); folderInfo.container = container; folderInfo.screen = c.getInt(screenIndex); folderInfo.cellX = c.getInt(cellXIndex); folderInfo.cellY = c.getInt(cellYIndex); switch (container) { case LauncherSettings.Favorites.CONTAINER_DESKTOP: mItems.add(folderInfo); break; } mFolders.put(folderInfo.id, folderInfo); break; case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER: id = c.getLong(idIndex); LiveFolderInfo liveFolderInfo = findOrMakeLiveFolder(mFolders, id); intentDescription = c.getString(intentIndex); intent = null; if (intentDescription != null) { try { intent = Intent.parseUri(intentDescription, 0); } catch (URISyntaxException e) { // Ignore, a live folder might not have a base intent } } liveFolderInfo.title = c.getString(titleIndex); liveFolderInfo.id = id; container = c.getInt(containerIndex); liveFolderInfo.container = container; liveFolderInfo.screen = c.getInt(screenIndex); liveFolderInfo.cellX = c.getInt(cellXIndex); liveFolderInfo.cellY = c.getInt(cellYIndex); liveFolderInfo.uri = Uri.parse(c.getString(uriIndex)); liveFolderInfo.baseIntent = intent; liveFolderInfo.displayMode = c.getInt(displayModeIndex); loadLiveFolderIcon(context, c, iconTypeIndex, iconPackageIndex, iconResourceIndex, liveFolderInfo); switch (container) { case LauncherSettings.Favorites.CONTAINER_DESKTOP: mItems.add(liveFolderInfo); break; } mFolders.put(liveFolderInfo.id, liveFolderInfo); break; case LauncherSettings.Favorites.ITEM_TYPE_WIDGET_SEARCH: widgetInfo = Widget.makeSearch(); container = c.getInt(containerIndex); if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) { Log.e(TAG, "Widget found where container " + "!= CONTAINER_DESKTOP ignoring!"); continue; } widgetInfo.id = c.getLong(idIndex); widgetInfo.screen = c.getInt(screenIndex); widgetInfo.container = container; widgetInfo.cellX = c.getInt(cellXIndex); widgetInfo.cellY = c.getInt(cellYIndex); mItems.add(widgetInfo); break; case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET: // Read all Launcher-specific widget details int appWidgetId = c.getInt(appWidgetIdIndex); appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId); appWidgetInfo.id = c.getLong(idIndex); appWidgetInfo.screen = c.getInt(screenIndex); appWidgetInfo.cellX = c.getInt(cellXIndex); appWidgetInfo.cellY = c.getInt(cellYIndex); appWidgetInfo.spanX = c.getInt(spanXIndex); appWidgetInfo.spanY = c.getInt(spanYIndex); container = c.getInt(containerIndex); if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) { Log.e(TAG, "Widget found where container " + "!= CONTAINER_DESKTOP -- ignoring!"); continue; } appWidgetInfo.container = c.getInt(containerIndex); mAppWidgets.add(appWidgetInfo); break; } } catch (Exception e) { Log.w(TAG, "Desktop items loading interrupted:", e); } } } finally { c.close(); } Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms"); } /** * Read everything out of our database. */ private void bindWorkspace() { final long t = SystemClock.uptimeMillis(); // Don't use these two variables in any of the callback runnables. // Otherwise we hold a reference to them. Callbacks callbacks = mCallbacks.get(); if (callbacks == null) { // This launcher has exited and nobody bothered to tell us. Just bail. Log.w(TAG, "LoaderThread running with no launcher"); return; } int N; // Tell the workspace that we're about to start firing items at it mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(); if (callbacks != null) { callbacks.startBinding(); } } }); // Add the items to the workspace. N = mItems.size(); for (int i=0; i<N; i+=ITEMS_CHUNK) { final int start = i; final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i); mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(); if (callbacks != null) { callbacks.bindItems(mItems, start, start+chunkSize); } } }); } mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(); if (callbacks != null) { callbacks.bindFolders(mFolders); } } }); // Wait until the queue goes empty. mHandler.postIdle(new Runnable() { public void run() { Log.d(TAG, "Going to start binding widgets soon."); } }); // Bind the widgets, one at a time. // WARNING: this is calling into the workspace from the background thread, // but since getCurrentScreen() just returns the int, we should be okay. This // is just a hint for the order, and if it's wrong, we'll be okay. // TODO: instead, we should have that push the current screen into here. final int currentScreen = callbacks.getCurrentWorkspaceScreen(); N = mAppWidgets.size(); // once for the current screen for (int i=0; i<N; i++) { final LauncherAppWidgetInfo widget = mAppWidgets.get(i); if (widget.screen == currentScreen) { mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(); if (callbacks != null) { callbacks.bindAppWidget(widget); } } }); } } // once for the other screens for (int i=0; i<N; i++) { final LauncherAppWidgetInfo widget = mAppWidgets.get(i); if (widget.screen != currentScreen) { mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(); if (callbacks != null) { callbacks.bindAppWidget(widget); } } }); } } // Tell the workspace that we're done. mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(); if (callbacks != null) { callbacks.finishBindingItems(); } } }); // If we're profiling, this is the last thing in the queue. mHandler.post(new Runnable() { public void run() { Log.d(TAG, "bound workspace in " + (SystemClock.uptimeMillis()-t) + "ms"); if (Launcher.PROFILE_ROTATE) { android.os.Debug.stopMethodTracing(); } } }); } private void loadAllApps() { final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null); mainIntent.addCategory(Intent.CATEGORY_LAUNCHER); final Callbacks callbacks = tryGetCallbacks(); if (callbacks == null) { return; } final Context context = mContext; final PackageManager packageManager = context.getPackageManager(); final List<ResolveInfo> apps = packageManager.queryIntentActivities(mainIntent, 0); synchronized (mLock) { mBeforeFirstLoad = false; mAllAppsList.clear(); if (apps != null) { long t = SystemClock.uptimeMillis(); int N = apps.size(); Utilities.BubbleText bubble = new Utilities.BubbleText(context); for (int i=0; i<N && !mStopped; i++) { // This builds the icon bitmaps. mAllAppsList.add(AppInfoCache.cache(apps.get(i), context, bubble)); } Collections.sort(mAllAppsList.data, sComparator); Collections.sort(mAllAppsList.added, sComparator); Log.d(TAG, "cached app icons in " + (SystemClock.uptimeMillis()-t) + "ms"); } } } private void bindAllApps() { synchronized (mLock) { final ArrayList<ApplicationInfo> results = mAllAppsList.added; mAllAppsList.added = new ArrayList<ApplicationInfo>(); mHandler.post(new Runnable() { public void run() { final long t = SystemClock.uptimeMillis(); final int count = results.size(); Callbacks callbacks = tryGetCallbacks(); if (callbacks != null) { callbacks.bindAllApplications(results); } Log.d(TAG, "bound app " + count + " icons in " + (SystemClock.uptimeMillis()-t) + "ms"); } }); } } } } /** * Make an ApplicationInfo object for an application. */ private static ApplicationInfo getApplicationInfo(PackageManager manager, Intent intent, Context context) { final ResolveInfo resolveInfo = manager.resolveActivity(intent, 0); if (resolveInfo == null) { return null; } final ApplicationInfo info = new ApplicationInfo(); final ActivityInfo activityInfo = resolveInfo.activityInfo; info.icon = Utilities.createIconThumbnail(activityInfo.loadIcon(manager), context); if (info.title == null || info.title.length() == 0) { info.title = activityInfo.loadLabel(manager); } if (info.title == null) { info.title = ""; } info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION; return info; } /** * Make an ApplicationInfo object for a sortcut */ private static ApplicationInfo getApplicationInfoShortcut(Cursor c, Context context, int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex) { final ApplicationInfo info = new ApplicationInfo(); info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT; int iconType = c.getInt(iconTypeIndex); switch (iconType) { case LauncherSettings.Favorites.ICON_TYPE_RESOURCE: String packageName = c.getString(iconPackageIndex); String resourceName = c.getString(iconResourceIndex); PackageManager packageManager = context.getPackageManager(); try { Resources resources = packageManager.getResourcesForApplication(packageName); final int id = resources.getIdentifier(resourceName, null, null); info.icon = Utilities.createIconThumbnail(resources.getDrawable(id), context); } catch (Exception e) { info.icon = packageManager.getDefaultActivityIcon(); } info.iconResource = new Intent.ShortcutIconResource(); info.iconResource.packageName = packageName; info.iconResource.resourceName = resourceName; info.customIcon = false; break; case LauncherSettings.Favorites.ICON_TYPE_BITMAP: byte[] data = c.getBlob(iconIndex); try { Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length); info.icon = new FastBitmapDrawable( Utilities.createBitmapThumbnail(bitmap, context)); } catch (Exception e) { packageManager = context.getPackageManager(); info.icon = packageManager.getDefaultActivityIcon(); } info.filtered = true; info.customIcon = true; break; default: info.icon = context.getPackageManager().getDefaultActivityIcon(); info.customIcon = false; break; } return info; } private static void loadLiveFolderIcon(Context context, Cursor c, int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, LiveFolderInfo liveFolderInfo) { int iconType = c.getInt(iconTypeIndex); switch (iconType) { case LauncherSettings.Favorites.ICON_TYPE_RESOURCE: String packageName = c.getString(iconPackageIndex); String resourceName = c.getString(iconResourceIndex); PackageManager packageManager = context.getPackageManager(); try { Resources resources = packageManager.getResourcesForApplication(packageName); final int id = resources.getIdentifier(resourceName, null, null); liveFolderInfo.icon = resources.getDrawable(id); } catch (Exception e) { liveFolderInfo.icon = context.getResources().getDrawable(R.drawable.ic_launcher_folder); } liveFolderInfo.iconResource = new Intent.ShortcutIconResource(); liveFolderInfo.iconResource.packageName = packageName; liveFolderInfo.iconResource.resourceName = resourceName; break; default: liveFolderInfo.icon = context.getResources().getDrawable(R.drawable.ic_launcher_folder); } } /** * Return an existing UserFolderInfo object if we have encountered this ID previously, * or make a new one. */ private static UserFolderInfo findOrMakeUserFolder(HashMap<Long, FolderInfo> folders, long id) { // See if a placeholder was created for us already FolderInfo folderInfo = folders.get(id); if (folderInfo == null || !(folderInfo instanceof UserFolderInfo)) { // No placeholder -- create a new instance folderInfo = new UserFolderInfo(); folders.put(id, folderInfo); } return (UserFolderInfo) folderInfo; } /** * Return an existing UserFolderInfo object if we have encountered this ID previously, or make a * new one. */ private static LiveFolderInfo findOrMakeLiveFolder(HashMap<Long, FolderInfo> folders, long id) { // See if a placeholder was created for us already FolderInfo folderInfo = folders.get(id); if (folderInfo == null || !(folderInfo instanceof LiveFolderInfo)) { // No placeholder -- create a new instance folderInfo = new LiveFolderInfo(); folders.put(id, folderInfo); } return (LiveFolderInfo) folderInfo; } private static void updateShortcutLabels(ContentResolver resolver, PackageManager manager) { final Cursor c = resolver.query(LauncherSettings.Favorites.CONTENT_URI, new String[] { LauncherSettings.Favorites._ID, LauncherSettings.Favorites.TITLE, LauncherSettings.Favorites.INTENT, LauncherSettings.Favorites.ITEM_TYPE }, null, null, null); final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID); final int intentIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT); final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE); final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE); // boolean changed = false; try { while (c.moveToNext()) { try { if (c.getInt(itemTypeIndex) != LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) { continue; } final String intentUri = c.getString(intentIndex); if (intentUri != null) { final Intent shortcut = Intent.parseUri(intentUri, 0); if (Intent.ACTION_MAIN.equals(shortcut.getAction())) { final ComponentName name = shortcut.getComponent(); if (name != null) { final ActivityInfo activityInfo = manager.getActivityInfo(name, 0); final String title = c.getString(titleIndex); String label = getLabel(manager, activityInfo); if (title == null || !title.equals(label)) { final ContentValues values = new ContentValues(); values.put(LauncherSettings.Favorites.TITLE, label); resolver.update( LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values, "_id=?", new String[] { String.valueOf(c.getLong(idIndex)) }); // changed = true; } } } } } catch (URISyntaxException e) { // Ignore } catch (PackageManager.NameNotFoundException e) { // Ignore } } } finally { c.close(); } // if (changed) resolver.notifyChange(Settings.Favorites.CONTENT_URI, null); } private static String getLabel(PackageManager manager, ActivityInfo activityInfo) { String label = activityInfo.loadLabel(manager).toString(); if (label == null) { label = manager.getApplicationLabel(activityInfo.applicationInfo).toString(); if (label == null) { label = activityInfo.name; } } return label; } private static final Collator sCollator = Collator.getInstance(); private static final Comparator<ApplicationInfo> sComparator = new Comparator<ApplicationInfo>() { public final int compare(ApplicationInfo a, ApplicationInfo b) { return sCollator.compare(a.title.toString(), b.title.toString()); } }; }
true
true
static boolean shortcutExists(Context context, String title, Intent intent) { final ContentResolver cr = context.getContentResolver(); Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] { "title", "intent" }, "title=? and intent=?", new String[] { title, intent.toUri(0) }, null); boolean result = false; try { result = c.moveToFirst(); } finally { c.close(); } return result; } /** * Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList. */ FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) { final ContentResolver cr = context.getContentResolver(); Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null, "_id=? and (itemType=? or itemType=?)", new String[] { String.valueOf(id), String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER), String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER) }, null); try { if (c.moveToFirst()) { final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE); final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE); final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER); final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN); final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX); final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY); FolderInfo folderInfo = null; switch (c.getInt(itemTypeIndex)) { case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER: folderInfo = findOrMakeUserFolder(folderList, id); break; case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER: folderInfo = findOrMakeLiveFolder(folderList, id); break; } folderInfo.title = c.getString(titleIndex); folderInfo.id = id; folderInfo.container = c.getInt(containerIndex); folderInfo.screen = c.getInt(screenIndex); folderInfo.cellX = c.getInt(cellXIndex); folderInfo.cellY = c.getInt(cellYIndex); return folderInfo; } } finally { c.close(); } return null; } /** * Add an item to the database in a specified container. Sets the container, screen, cellX and * cellY fields of the item. Also assigns an ID to the item. */ static void addItemToDatabase(Context context, ItemInfo item, long container, int screen, int cellX, int cellY, boolean notify) { item.container = container; item.screen = screen; item.cellX = cellX; item.cellY = cellY; final ContentValues values = new ContentValues(); final ContentResolver cr = context.getContentResolver(); item.onAddToDatabase(values); Uri result = cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI : LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values); if (result != null) { item.id = Integer.parseInt(result.getPathSegments().get(1)); } } /** * Update an item to the database in a specified container. */ static void updateItemInDatabase(Context context, ItemInfo item) { final ContentValues values = new ContentValues(); final ContentResolver cr = context.getContentResolver(); item.onAddToDatabase(values); cr.update(LauncherSettings.Favorites.getContentUri(item.id, false), values, null, null); } /** * Removes the specified item from the database * @param context * @param item */ static void deleteItemFromDatabase(Context context, ItemInfo item) { final ContentResolver cr = context.getContentResolver(); cr.delete(LauncherSettings.Favorites.getContentUri(item.id, false), null, null); } /** * Remove the contents of the specified folder from the database */ static void deleteUserFolderContentsFromDatabase(Context context, UserFolderInfo info) { final ContentResolver cr = context.getContentResolver(); cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null); cr.delete(LauncherSettings.Favorites.CONTENT_URI, LauncherSettings.Favorites.CONTAINER + "=" + info.id, null); } /** * Set this as the current Launcher activity object for the loader. */ public void initialize(Callbacks callbacks) { synchronized (mLock) { mCallbacks = new WeakReference<Callbacks>(callbacks); } } public void startLoader(Context context, boolean isLaunching) { mLoader.startLoader(context, isLaunching); } public void stopLoader() { mLoader.stopLoader(); } /** * We pick up most of the changes to all apps. */ public void setAllAppsDirty() { mLoader.setAllAppsDirty(); } public void setWorkspaceDirty() { mLoader.setWorkspaceDirty(); } /** * Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and * ACTION_PACKAGE_CHANGED. */ public void onReceive(Context context, Intent intent) { Log.d(TAG, "onReceive intent=" + intent); // Use the app as the context. context = mApp; final String packageName = intent.getData().getSchemeSpecificPart(); ArrayList<ApplicationInfo> added = null; ArrayList<ApplicationInfo> removed = null; ArrayList<ApplicationInfo> modified = null; boolean update = false; boolean remove = false; synchronized (mLock) { if (mBeforeFirstLoad) { // If we haven't even loaded yet, don't bother, since we'll just pick // up the changes. return; } final String action = intent.getAction(); final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false); if (packageName == null || packageName.length() == 0) { // they sent us a bad intent return; } if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) { mAllAppsList.updatePackage(context, packageName); update = true; } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) { if (!replacing) { mAllAppsList.removePackage(packageName); remove = true; } // else, we are replacing the package, so a PACKAGE_ADDED will be sent // later, we will update the package at this time } else { if (!replacing) { mAllAppsList.addPackage(context, packageName); } else { mAllAppsList.updatePackage(context, packageName); update = true; } } if (mAllAppsList.added.size() > 0) { added = mAllAppsList.added; mAllAppsList.added = new ArrayList<ApplicationInfo>(); } if (mAllAppsList.removed.size() > 0) { removed = mAllAppsList.removed; mAllAppsList.removed = new ArrayList<ApplicationInfo>(); for (ApplicationInfo info: removed) { AppInfoCache.remove(info.intent.getComponent()); } } if (mAllAppsList.modified.size() > 0) { modified = mAllAppsList.modified; mAllAppsList.modified = new ArrayList<ApplicationInfo>(); } final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == null) { Log.d(TAG, "nobody to tell about the new app"); return; } if (added != null) { final ArrayList<ApplicationInfo> addedFinal = added; mHandler.post(new Runnable() { public void run() { callbacks.bindPackageAdded(addedFinal); } }); } if (update || modified != null) { final ArrayList<ApplicationInfo> modifiedFinal = modified; mHandler.post(new Runnable() { public void run() { callbacks.bindPackageUpdated(packageName, modifiedFinal); } }); } if (remove || removed != null) { final ArrayList<ApplicationInfo> removedFinal = removed; mHandler.post(new Runnable() { public void run() { callbacks.bindPackageRemoved(packageName, removedFinal); } }); } } } public class Loader { private static final int ITEMS_CHUNK = 6; private LoaderThread mLoaderThread; private int mLastWorkspaceSeq = 0; private int mWorkspaceSeq = 1; private int mLastAllAppsSeq = 0; private int mAllAppsSeq = 1; final ArrayList<ItemInfo> mItems = new ArrayList<ItemInfo>(); final ArrayList<LauncherAppWidgetInfo> mAppWidgets = new ArrayList<LauncherAppWidgetInfo>(); final HashMap<Long, FolderInfo> mFolders = new HashMap<Long, FolderInfo>(); /** * Call this from the ui thread so the handler is initialized on the correct thread. */ public Loader() { } public void startLoader(Context context, boolean isLaunching) { synchronized (mLock) { Log.d(TAG, "startLoader isLaunching=" + isLaunching); // Don't bother to start the thread if we know it's not going to do anything if (mCallbacks.get() != null) { LoaderThread oldThread = mLoaderThread; if (oldThread != null) { if (oldThread.isLaunching()) { // don't downgrade isLaunching if we're already running isLaunching = true; } oldThread.stopLocked(); } mLoaderThread = new LoaderThread(context, oldThread, isLaunching); mLoaderThread.start(); } } } public void stopLoader() { synchronized (mLock) { if (mLoaderThread != null) { mLoaderThread.stopLocked(); } } } public void setWorkspaceDirty() { synchronized (mLock) { mWorkspaceSeq++; } } public void setAllAppsDirty() { synchronized (mLock) { mAllAppsSeq++; } } /** * Runnable for the thread that loads the contents of the launcher: * - workspace icons * - widgets * - all apps icons */ private class LoaderThread extends Thread { private Context mContext; private Thread mWaitThread; private boolean mIsLaunching; private boolean mStopped; private boolean mWorkspaceDoneBinding; LoaderThread(Context context, Thread waitThread, boolean isLaunching) { mContext = context; mWaitThread = waitThread; mIsLaunching = isLaunching; } boolean isLaunching() { return mIsLaunching; } /** * If another LoaderThread was supplied, we need to wait for that to finish before * we start our processing. This keeps the ordering of the setting and clearing * of the dirty flags correct by making sure we don't start processing stuff until * they've had a chance to re-set them. We do this waiting the worker thread, not * the ui thread to avoid ANRs. */ private void waitForOtherThread() { if (mWaitThread != null) { boolean done = false; while (!done) { try { mWaitThread.join(); done = true; } catch (InterruptedException ex) { // Ignore } } mWaitThread = null; } } public void run() { waitForOtherThread(); // Elevate priority when Home launches for the first time to avoid // starving at boot time. Staring at a blank home is not cool. synchronized (mLock) { android.os.Process.setThreadPriority(mIsLaunching ? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND); } // Load the workspace only if it's dirty. int workspaceSeq; boolean workspaceDirty; synchronized (mLock) { workspaceSeq = mWorkspaceSeq; workspaceDirty = mWorkspaceSeq != mLastWorkspaceSeq; } if (workspaceDirty) { loadWorkspace(); } synchronized (mLock) { // If we're not stopped, and nobody has incremented mWorkspaceSeq. if (mStopped) { return; } if (workspaceSeq == mWorkspaceSeq) { mLastWorkspaceSeq = mWorkspaceSeq; } } // Bind the workspace bindWorkspace(); // Wait until the either we're stopped or the other threads are done. // This way we don't start loading all apps until the workspace has settled // down. synchronized (LoaderThread.this) { mHandler.postIdle(new Runnable() { public void run() { synchronized (LoaderThread.this) { mWorkspaceDoneBinding = true; Log.d(TAG, "done with workspace"); LoaderThread.this.notify(); } } }); Log.d(TAG, "waiting to be done with workspace"); while (!mStopped && !mWorkspaceDoneBinding) { try { this.wait(); } catch (InterruptedException ex) { // Ignore } } Log.d(TAG, "done waiting to be done with workspace"); } // Load all apps if they're dirty int allAppsSeq; boolean allAppsDirty; synchronized (mLock) { allAppsSeq = mAllAppsSeq; allAppsDirty = mAllAppsSeq != mLastAllAppsSeq; //Log.d(TAG, "mAllAppsSeq=" + mAllAppsSeq // + " mLastAllAppsSeq=" + mLastAllAppsSeq + " allAppsDirty"); } if (allAppsDirty) { loadAllApps(); } synchronized (mLock) { // If we're not stopped, and nobody has incremented mAllAppsSeq. if (mStopped) { return; } if (allAppsSeq == mAllAppsSeq) { mLastAllAppsSeq = mAllAppsSeq; } } // Bind all apps if (allAppsDirty) { bindAllApps(); } // Clear out this reference, otherwise we end up holding it until all of the // callback runnables are done. mContext = null; synchronized (mLock) { // Setting the reference is atomic, but we can't do it inside the other critical // sections. mLoaderThread = null; } } public void stopLocked() { synchronized (LoaderThread.this) { mStopped = true; this.notify(); } } /** * Gets the callbacks object. If we've been stopped, or if the launcher object * has somehow been garbage collected, return null instead. */ Callbacks tryGetCallbacks() { synchronized (mLock) { if (mStopped) { return null; } final Callbacks callbacks = mCallbacks.get(); if (callbacks == null) { Log.w(TAG, "no mCallbacks"); return null; } return callbacks; } } private void loadWorkspace() { long t = SystemClock.uptimeMillis(); final Context context = mContext; final ContentResolver contentResolver = context.getContentResolver(); final PackageManager manager = context.getPackageManager(); /* TODO if (mLocaleChanged) { updateShortcutLabels(contentResolver, manager); } */ mItems.clear(); mAppWidgets.clear(); final Cursor c = contentResolver.query( LauncherSettings.Favorites.CONTENT_URI, null, null, null, null); try { final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID); final int intentIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.INTENT); final int titleIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.TITLE); final int iconTypeIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ICON_TYPE); final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON); final int iconPackageIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ICON_PACKAGE); final int iconResourceIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ICON_RESOURCE); final int containerIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.CONTAINER); final int itemTypeIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ITEM_TYPE); final int appWidgetIdIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.APPWIDGET_ID); final int screenIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.SCREEN); final int cellXIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.CELLX); final int cellYIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.CELLY); final int spanXIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.SPANX); final int spanYIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.SPANY); final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI); final int displayModeIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.DISPLAY_MODE); ApplicationInfo info; String intentDescription; Widget widgetInfo; LauncherAppWidgetInfo appWidgetInfo; int container; long id; Intent intent; while (!mStopped && c.moveToNext()) { try { int itemType = c.getInt(itemTypeIndex); switch (itemType) { case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: intentDescription = c.getString(intentIndex); try { intent = Intent.parseUri(intentDescription, 0); } catch (URISyntaxException e) { continue; } if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) { info = getApplicationInfo(manager, intent, context); } else { info = getApplicationInfoShortcut(c, context, iconTypeIndex, iconPackageIndex, iconResourceIndex, iconIndex); } if (info == null) { info = new ApplicationInfo(); info.icon = manager.getDefaultActivityIcon(); } if (info != null) { info.title = c.getString(titleIndex); info.intent = intent; info.id = c.getLong(idIndex); container = c.getInt(containerIndex); info.container = container; info.screen = c.getInt(screenIndex); info.cellX = c.getInt(cellXIndex); info.cellY = c.getInt(cellYIndex); switch (container) { case LauncherSettings.Favorites.CONTAINER_DESKTOP: mItems.add(info); break; default: // Item is in a user folder UserFolderInfo folderInfo = findOrMakeUserFolder(mFolders, container); folderInfo.add(info); break; } } break; case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER: id = c.getLong(idIndex); UserFolderInfo folderInfo = findOrMakeUserFolder(mFolders, id); folderInfo.title = c.getString(titleIndex); folderInfo.id = id; container = c.getInt(containerIndex); folderInfo.container = container; folderInfo.screen = c.getInt(screenIndex); folderInfo.cellX = c.getInt(cellXIndex); folderInfo.cellY = c.getInt(cellYIndex); switch (container) { case LauncherSettings.Favorites.CONTAINER_DESKTOP: mItems.add(folderInfo); break; } mFolders.put(folderInfo.id, folderInfo); break; case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER: id = c.getLong(idIndex); LiveFolderInfo liveFolderInfo = findOrMakeLiveFolder(mFolders, id); intentDescription = c.getString(intentIndex); intent = null; if (intentDescription != null) { try { intent = Intent.parseUri(intentDescription, 0); } catch (URISyntaxException e) { // Ignore, a live folder might not have a base intent } } liveFolderInfo.title = c.getString(titleIndex); liveFolderInfo.id = id; container = c.getInt(containerIndex); liveFolderInfo.container = container; liveFolderInfo.screen = c.getInt(screenIndex); liveFolderInfo.cellX = c.getInt(cellXIndex); liveFolderInfo.cellY = c.getInt(cellYIndex); liveFolderInfo.uri = Uri.parse(c.getString(uriIndex)); liveFolderInfo.baseIntent = intent; liveFolderInfo.displayMode = c.getInt(displayModeIndex); loadLiveFolderIcon(context, c, iconTypeIndex, iconPackageIndex, iconResourceIndex, liveFolderInfo); switch (container) { case LauncherSettings.Favorites.CONTAINER_DESKTOP: mItems.add(liveFolderInfo); break; } mFolders.put(liveFolderInfo.id, liveFolderInfo); break; case LauncherSettings.Favorites.ITEM_TYPE_WIDGET_SEARCH: widgetInfo = Widget.makeSearch(); container = c.getInt(containerIndex); if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) { Log.e(TAG, "Widget found where container " + "!= CONTAINER_DESKTOP ignoring!"); continue; } widgetInfo.id = c.getLong(idIndex); widgetInfo.screen = c.getInt(screenIndex); widgetInfo.container = container; widgetInfo.cellX = c.getInt(cellXIndex); widgetInfo.cellY = c.getInt(cellYIndex); mItems.add(widgetInfo); break; case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET: // Read all Launcher-specific widget details int appWidgetId = c.getInt(appWidgetIdIndex); appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId); appWidgetInfo.id = c.getLong(idIndex); appWidgetInfo.screen = c.getInt(screenIndex); appWidgetInfo.cellX = c.getInt(cellXIndex); appWidgetInfo.cellY = c.getInt(cellYIndex); appWidgetInfo.spanX = c.getInt(spanXIndex); appWidgetInfo.spanY = c.getInt(spanYIndex); container = c.getInt(containerIndex); if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) { Log.e(TAG, "Widget found where container " + "!= CONTAINER_DESKTOP -- ignoring!"); continue; } appWidgetInfo.container = c.getInt(containerIndex); mAppWidgets.add(appWidgetInfo); break; } } catch (Exception e) { Log.w(TAG, "Desktop items loading interrupted:", e); } } } finally { c.close(); } Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms"); } /** * Read everything out of our database. */ private void bindWorkspace() { final long t = SystemClock.uptimeMillis(); // Don't use these two variables in any of the callback runnables. // Otherwise we hold a reference to them. Callbacks callbacks = mCallbacks.get(); if (callbacks == null) { // This launcher has exited and nobody bothered to tell us. Just bail. Log.w(TAG, "LoaderThread running with no launcher"); return; } int N; // Tell the workspace that we're about to start firing items at it mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(); if (callbacks != null) { callbacks.startBinding(); } } }); // Add the items to the workspace. N = mItems.size(); for (int i=0; i<N; i+=ITEMS_CHUNK) { final int start = i; final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i); mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(); if (callbacks != null) { callbacks.bindItems(mItems, start, start+chunkSize); } } }); } mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(); if (callbacks != null) { callbacks.bindFolders(mFolders); } } }); // Wait until the queue goes empty. mHandler.postIdle(new Runnable() { public void run() { Log.d(TAG, "Going to start binding widgets soon."); } }); // Bind the widgets, one at a time. // WARNING: this is calling into the workspace from the background thread, // but since getCurrentScreen() just returns the int, we should be okay. This // is just a hint for the order, and if it's wrong, we'll be okay. // TODO: instead, we should have that push the current screen into here. final int currentScreen = callbacks.getCurrentWorkspaceScreen(); N = mAppWidgets.size(); // once for the current screen for (int i=0; i<N; i++) { final LauncherAppWidgetInfo widget = mAppWidgets.get(i); if (widget.screen == currentScreen) { mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(); if (callbacks != null) { callbacks.bindAppWidget(widget); } } }); } } // once for the other screens for (int i=0; i<N; i++) { final LauncherAppWidgetInfo widget = mAppWidgets.get(i); if (widget.screen != currentScreen) { mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(); if (callbacks != null) { callbacks.bindAppWidget(widget); } } }); } } // Tell the workspace that we're done. mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(); if (callbacks != null) { callbacks.finishBindingItems(); } } }); // If we're profiling, this is the last thing in the queue. mHandler.post(new Runnable() { public void run() { Log.d(TAG, "bound workspace in " + (SystemClock.uptimeMillis()-t) + "ms"); if (Launcher.PROFILE_ROTATE) { android.os.Debug.stopMethodTracing(); } } }); } private void loadAllApps() { final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null); mainIntent.addCategory(Intent.CATEGORY_LAUNCHER); final Callbacks callbacks = tryGetCallbacks(); if (callbacks == null) { return; } final Context context = mContext; final PackageManager packageManager = context.getPackageManager(); final List<ResolveInfo> apps = packageManager.queryIntentActivities(mainIntent, 0); synchronized (mLock) { mBeforeFirstLoad = false; mAllAppsList.clear(); if (apps != null) { long t = SystemClock.uptimeMillis(); int N = apps.size(); Utilities.BubbleText bubble = new Utilities.BubbleText(context); for (int i=0; i<N && !mStopped; i++) { // This builds the icon bitmaps. mAllAppsList.add(AppInfoCache.cache(apps.get(i), context, bubble)); } Collections.sort(mAllAppsList.data, sComparator); Collections.sort(mAllAppsList.added, sComparator); Log.d(TAG, "cached app icons in " + (SystemClock.uptimeMillis()-t) + "ms"); } } } private void bindAllApps() { synchronized (mLock) { final ArrayList<ApplicationInfo> results = mAllAppsList.added; mAllAppsList.added = new ArrayList<ApplicationInfo>(); mHandler.post(new Runnable() { public void run() { final long t = SystemClock.uptimeMillis(); final int count = results.size(); Callbacks callbacks = tryGetCallbacks(); if (callbacks != null) { callbacks.bindAllApplications(results); } Log.d(TAG, "bound app " + count + " icons in " + (SystemClock.uptimeMillis()-t) + "ms"); } }); } } } } /** * Make an ApplicationInfo object for an application. */ private static ApplicationInfo getApplicationInfo(PackageManager manager, Intent intent, Context context) { final ResolveInfo resolveInfo = manager.resolveActivity(intent, 0); if (resolveInfo == null) { return null; } final ApplicationInfo info = new ApplicationInfo(); final ActivityInfo activityInfo = resolveInfo.activityInfo; info.icon = Utilities.createIconThumbnail(activityInfo.loadIcon(manager), context); if (info.title == null || info.title.length() == 0) { info.title = activityInfo.loadLabel(manager); } if (info.title == null) { info.title = ""; } info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION; return info; } /** * Make an ApplicationInfo object for a sortcut */ private static ApplicationInfo getApplicationInfoShortcut(Cursor c, Context context, int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex) { final ApplicationInfo info = new ApplicationInfo(); info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT; int iconType = c.getInt(iconTypeIndex); switch (iconType) { case LauncherSettings.Favorites.ICON_TYPE_RESOURCE: String packageName = c.getString(iconPackageIndex); String resourceName = c.getString(iconResourceIndex); PackageManager packageManager = context.getPackageManager(); try { Resources resources = packageManager.getResourcesForApplication(packageName); final int id = resources.getIdentifier(resourceName, null, null); info.icon = Utilities.createIconThumbnail(resources.getDrawable(id), context); } catch (Exception e) { info.icon = packageManager.getDefaultActivityIcon(); } info.iconResource = new Intent.ShortcutIconResource(); info.iconResource.packageName = packageName; info.iconResource.resourceName = resourceName; info.customIcon = false; break; case LauncherSettings.Favorites.ICON_TYPE_BITMAP: byte[] data = c.getBlob(iconIndex); try { Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length); info.icon = new FastBitmapDrawable( Utilities.createBitmapThumbnail(bitmap, context)); } catch (Exception e) { packageManager = context.getPackageManager(); info.icon = packageManager.getDefaultActivityIcon(); } info.filtered = true; info.customIcon = true; break; default: info.icon = context.getPackageManager().getDefaultActivityIcon(); info.customIcon = false; break; } return info; } private static void loadLiveFolderIcon(Context context, Cursor c, int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, LiveFolderInfo liveFolderInfo) { int iconType = c.getInt(iconTypeIndex); switch (iconType) { case LauncherSettings.Favorites.ICON_TYPE_RESOURCE: String packageName = c.getString(iconPackageIndex); String resourceName = c.getString(iconResourceIndex); PackageManager packageManager = context.getPackageManager(); try { Resources resources = packageManager.getResourcesForApplication(packageName); final int id = resources.getIdentifier(resourceName, null, null); liveFolderInfo.icon = resources.getDrawable(id); } catch (Exception e) { liveFolderInfo.icon = context.getResources().getDrawable(R.drawable.ic_launcher_folder); } liveFolderInfo.iconResource = new Intent.ShortcutIconResource(); liveFolderInfo.iconResource.packageName = packageName; liveFolderInfo.iconResource.resourceName = resourceName; break; default: liveFolderInfo.icon = context.getResources().getDrawable(R.drawable.ic_launcher_folder); } } /** * Return an existing UserFolderInfo object if we have encountered this ID previously, * or make a new one. */ private static UserFolderInfo findOrMakeUserFolder(HashMap<Long, FolderInfo> folders, long id) { // See if a placeholder was created for us already FolderInfo folderInfo = folders.get(id); if (folderInfo == null || !(folderInfo instanceof UserFolderInfo)) { // No placeholder -- create a new instance folderInfo = new UserFolderInfo(); folders.put(id, folderInfo); } return (UserFolderInfo) folderInfo; } /** * Return an existing UserFolderInfo object if we have encountered this ID previously, or make a * new one. */ private static LiveFolderInfo findOrMakeLiveFolder(HashMap<Long, FolderInfo> folders, long id) { // See if a placeholder was created for us already FolderInfo folderInfo = folders.get(id); if (folderInfo == null || !(folderInfo instanceof LiveFolderInfo)) { // No placeholder -- create a new instance folderInfo = new LiveFolderInfo(); folders.put(id, folderInfo); } return (LiveFolderInfo) folderInfo; } private static void updateShortcutLabels(ContentResolver resolver, PackageManager manager) { final Cursor c = resolver.query(LauncherSettings.Favorites.CONTENT_URI, new String[] { LauncherSettings.Favorites._ID, LauncherSettings.Favorites.TITLE, LauncherSettings.Favorites.INTENT, LauncherSettings.Favorites.ITEM_TYPE }, null, null, null); final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID); final int intentIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT); final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE); final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE); // boolean changed = false; try { while (c.moveToNext()) { try { if (c.getInt(itemTypeIndex) != LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) { continue; } final String intentUri = c.getString(intentIndex); if (intentUri != null) { final Intent shortcut = Intent.parseUri(intentUri, 0); if (Intent.ACTION_MAIN.equals(shortcut.getAction())) { final ComponentName name = shortcut.getComponent(); if (name != null) { final ActivityInfo activityInfo = manager.getActivityInfo(name, 0); final String title = c.getString(titleIndex); String label = getLabel(manager, activityInfo); if (title == null || !title.equals(label)) { final ContentValues values = new ContentValues(); values.put(LauncherSettings.Favorites.TITLE, label); resolver.update( LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values, "_id=?", new String[] { String.valueOf(c.getLong(idIndex)) }); // changed = true; } } } } } catch (URISyntaxException e) { // Ignore } catch (PackageManager.NameNotFoundException e) { // Ignore } } } finally { c.close(); } // if (changed) resolver.notifyChange(Settings.Favorites.CONTENT_URI, null); } private static String getLabel(PackageManager manager, ActivityInfo activityInfo) { String label = activityInfo.loadLabel(manager).toString(); if (label == null) { label = manager.getApplicationLabel(activityInfo.applicationInfo).toString(); if (label == null) { label = activityInfo.name; } } return label; } private static final Collator sCollator = Collator.getInstance(); private static final Comparator<ApplicationInfo> sComparator = new Comparator<ApplicationInfo>() { public final int compare(ApplicationInfo a, ApplicationInfo b) { return sCollator.compare(a.title.toString(), b.title.toString()); } }; }
static boolean shortcutExists(Context context, String title, Intent intent) { final ContentResolver cr = context.getContentResolver(); Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] { "title", "intent" }, "title=? and intent=?", new String[] { title, intent.toUri(0) }, null); boolean result = false; try { result = c.moveToFirst(); } finally { c.close(); } return result; } /** * Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList. */ FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) { final ContentResolver cr = context.getContentResolver(); Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null, "_id=? and (itemType=? or itemType=?)", new String[] { String.valueOf(id), String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER), String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER) }, null); try { if (c.moveToFirst()) { final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE); final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE); final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER); final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN); final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX); final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY); FolderInfo folderInfo = null; switch (c.getInt(itemTypeIndex)) { case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER: folderInfo = findOrMakeUserFolder(folderList, id); break; case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER: folderInfo = findOrMakeLiveFolder(folderList, id); break; } folderInfo.title = c.getString(titleIndex); folderInfo.id = id; folderInfo.container = c.getInt(containerIndex); folderInfo.screen = c.getInt(screenIndex); folderInfo.cellX = c.getInt(cellXIndex); folderInfo.cellY = c.getInt(cellYIndex); return folderInfo; } } finally { c.close(); } return null; } /** * Add an item to the database in a specified container. Sets the container, screen, cellX and * cellY fields of the item. Also assigns an ID to the item. */ static void addItemToDatabase(Context context, ItemInfo item, long container, int screen, int cellX, int cellY, boolean notify) { item.container = container; item.screen = screen; item.cellX = cellX; item.cellY = cellY; final ContentValues values = new ContentValues(); final ContentResolver cr = context.getContentResolver(); item.onAddToDatabase(values); Uri result = cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI : LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values); if (result != null) { item.id = Integer.parseInt(result.getPathSegments().get(1)); } } /** * Update an item to the database in a specified container. */ static void updateItemInDatabase(Context context, ItemInfo item) { final ContentValues values = new ContentValues(); final ContentResolver cr = context.getContentResolver(); item.onAddToDatabase(values); cr.update(LauncherSettings.Favorites.getContentUri(item.id, false), values, null, null); } /** * Removes the specified item from the database * @param context * @param item */ static void deleteItemFromDatabase(Context context, ItemInfo item) { final ContentResolver cr = context.getContentResolver(); cr.delete(LauncherSettings.Favorites.getContentUri(item.id, false), null, null); } /** * Remove the contents of the specified folder from the database */ static void deleteUserFolderContentsFromDatabase(Context context, UserFolderInfo info) { final ContentResolver cr = context.getContentResolver(); cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null); cr.delete(LauncherSettings.Favorites.CONTENT_URI, LauncherSettings.Favorites.CONTAINER + "=" + info.id, null); } /** * Set this as the current Launcher activity object for the loader. */ public void initialize(Callbacks callbacks) { synchronized (mLock) { mCallbacks = new WeakReference<Callbacks>(callbacks); } } public void startLoader(Context context, boolean isLaunching) { mLoader.startLoader(context, isLaunching); } public void stopLoader() { mLoader.stopLoader(); } /** * We pick up most of the changes to all apps. */ public void setAllAppsDirty() { mLoader.setAllAppsDirty(); } public void setWorkspaceDirty() { mLoader.setWorkspaceDirty(); } /** * Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and * ACTION_PACKAGE_CHANGED. */ public void onReceive(Context context, Intent intent) { Log.d(TAG, "onReceive intent=" + intent); // Use the app as the context. context = mApp; final String packageName = intent.getData().getSchemeSpecificPart(); ArrayList<ApplicationInfo> added = null; ArrayList<ApplicationInfo> removed = null; ArrayList<ApplicationInfo> modified = null; boolean update = false; boolean remove = false; synchronized (mLock) { if (mBeforeFirstLoad) { // If we haven't even loaded yet, don't bother, since we'll just pick // up the changes. return; } final String action = intent.getAction(); final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false); if (packageName == null || packageName.length() == 0) { // they sent us a bad intent return; } if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) { mAllAppsList.updatePackage(context, packageName); update = true; } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) { if (!replacing) { mAllAppsList.removePackage(packageName); remove = true; } // else, we are replacing the package, so a PACKAGE_ADDED will be sent // later, we will update the package at this time } else { if (!replacing) { mAllAppsList.addPackage(context, packageName); } else { mAllAppsList.updatePackage(context, packageName); update = true; } } if (mAllAppsList.added.size() > 0) { added = mAllAppsList.added; mAllAppsList.added = new ArrayList<ApplicationInfo>(); } if (mAllAppsList.removed.size() > 0) { removed = mAllAppsList.removed; mAllAppsList.removed = new ArrayList<ApplicationInfo>(); for (ApplicationInfo info: removed) { AppInfoCache.remove(info.intent.getComponent()); } } if (mAllAppsList.modified.size() > 0) { modified = mAllAppsList.modified; mAllAppsList.modified = new ArrayList<ApplicationInfo>(); } final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == null) { Log.d(TAG, "nobody to tell about the new app"); return; } if (added != null) { final ArrayList<ApplicationInfo> addedFinal = added; mHandler.post(new Runnable() { public void run() { callbacks.bindPackageAdded(addedFinal); } }); } if (update || modified != null) { final ArrayList<ApplicationInfo> modifiedFinal = modified; mHandler.post(new Runnable() { public void run() { callbacks.bindPackageUpdated(packageName, modifiedFinal); } }); } if (remove || removed != null) { final ArrayList<ApplicationInfo> removedFinal = removed; mHandler.post(new Runnable() { public void run() { callbacks.bindPackageRemoved(packageName, removedFinal); } }); } } } public class Loader { private static final int ITEMS_CHUNK = 6; private LoaderThread mLoaderThread; private int mLastWorkspaceSeq = 0; private int mWorkspaceSeq = 1; private int mLastAllAppsSeq = 0; private int mAllAppsSeq = 1; final ArrayList<ItemInfo> mItems = new ArrayList<ItemInfo>(); final ArrayList<LauncherAppWidgetInfo> mAppWidgets = new ArrayList<LauncherAppWidgetInfo>(); final HashMap<Long, FolderInfo> mFolders = new HashMap<Long, FolderInfo>(); /** * Call this from the ui thread so the handler is initialized on the correct thread. */ public Loader() { } public void startLoader(Context context, boolean isLaunching) { synchronized (mLock) { Log.d(TAG, "startLoader isLaunching=" + isLaunching); // Don't bother to start the thread if we know it's not going to do anything if (mCallbacks.get() != null) { LoaderThread oldThread = mLoaderThread; if (oldThread != null) { if (oldThread.isLaunching()) { // don't downgrade isLaunching if we're already running isLaunching = true; } oldThread.stopLocked(); } mLoaderThread = new LoaderThread(context, oldThread, isLaunching); mLoaderThread.start(); } } } public void stopLoader() { synchronized (mLock) { if (mLoaderThread != null) { mLoaderThread.stopLocked(); } } } public void setWorkspaceDirty() { synchronized (mLock) { mWorkspaceSeq++; } } public void setAllAppsDirty() { synchronized (mLock) { mAllAppsSeq++; } } /** * Runnable for the thread that loads the contents of the launcher: * - workspace icons * - widgets * - all apps icons */ private class LoaderThread extends Thread { private Context mContext; private Thread mWaitThread; private boolean mIsLaunching; private boolean mStopped; private boolean mWorkspaceDoneBinding; LoaderThread(Context context, Thread waitThread, boolean isLaunching) { mContext = context; mWaitThread = waitThread; mIsLaunching = isLaunching; } boolean isLaunching() { return mIsLaunching; } /** * If another LoaderThread was supplied, we need to wait for that to finish before * we start our processing. This keeps the ordering of the setting and clearing * of the dirty flags correct by making sure we don't start processing stuff until * they've had a chance to re-set them. We do this waiting the worker thread, not * the ui thread to avoid ANRs. */ private void waitForOtherThread() { if (mWaitThread != null) { boolean done = false; while (!done) { try { mWaitThread.join(); done = true; } catch (InterruptedException ex) { // Ignore } } mWaitThread = null; } } public void run() { waitForOtherThread(); // Elevate priority when Home launches for the first time to avoid // starving at boot time. Staring at a blank home is not cool. synchronized (mLock) { android.os.Process.setThreadPriority(mIsLaunching ? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND); } // Load the workspace only if it's dirty. int workspaceSeq; boolean workspaceDirty; synchronized (mLock) { workspaceSeq = mWorkspaceSeq; workspaceDirty = mWorkspaceSeq != mLastWorkspaceSeq; } if (workspaceDirty) { loadWorkspace(); } synchronized (mLock) { // If we're not stopped, and nobody has incremented mWorkspaceSeq. if (mStopped) { return; } if (workspaceSeq == mWorkspaceSeq) { mLastWorkspaceSeq = mWorkspaceSeq; } } // Bind the workspace bindWorkspace(); // Wait until the either we're stopped or the other threads are done. // This way we don't start loading all apps until the workspace has settled // down. synchronized (LoaderThread.this) { mHandler.postIdle(new Runnable() { public void run() { synchronized (LoaderThread.this) { mWorkspaceDoneBinding = true; Log.d(TAG, "done with workspace"); LoaderThread.this.notify(); } } }); Log.d(TAG, "waiting to be done with workspace"); while (!mStopped && !mWorkspaceDoneBinding) { try { this.wait(); } catch (InterruptedException ex) { // Ignore } } Log.d(TAG, "done waiting to be done with workspace"); } // Load all apps if they're dirty int allAppsSeq; boolean allAppsDirty; synchronized (mLock) { allAppsSeq = mAllAppsSeq; allAppsDirty = mAllAppsSeq != mLastAllAppsSeq; //Log.d(TAG, "mAllAppsSeq=" + mAllAppsSeq // + " mLastAllAppsSeq=" + mLastAllAppsSeq + " allAppsDirty"); } if (allAppsDirty) { loadAllApps(); } synchronized (mLock) { // If we're not stopped, and nobody has incremented mAllAppsSeq. if (mStopped) { return; } if (allAppsSeq == mAllAppsSeq) { mLastAllAppsSeq = mAllAppsSeq; } } // Bind all apps if (allAppsDirty) { bindAllApps(); } // Clear out this reference, otherwise we end up holding it until all of the // callback runnables are done. mContext = null; synchronized (mLock) { // Setting the reference is atomic, but we can't do it inside the other critical // sections. mLoaderThread = null; } } public void stopLocked() { synchronized (LoaderThread.this) { mStopped = true; this.notify(); } } /** * Gets the callbacks object. If we've been stopped, or if the launcher object * has somehow been garbage collected, return null instead. */ Callbacks tryGetCallbacks() { synchronized (mLock) { if (mStopped) { return null; } final Callbacks callbacks = mCallbacks.get(); if (callbacks == null) { Log.w(TAG, "no mCallbacks"); return null; } return callbacks; } } private void loadWorkspace() { long t = SystemClock.uptimeMillis(); final Context context = mContext; final ContentResolver contentResolver = context.getContentResolver(); final PackageManager manager = context.getPackageManager(); /* TODO if (mLocaleChanged) { updateShortcutLabels(contentResolver, manager); } */ mItems.clear(); mAppWidgets.clear(); final Cursor c = contentResolver.query( LauncherSettings.Favorites.CONTENT_URI, null, null, null, null); try { final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID); final int intentIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.INTENT); final int titleIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.TITLE); final int iconTypeIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ICON_TYPE); final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON); final int iconPackageIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ICON_PACKAGE); final int iconResourceIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ICON_RESOURCE); final int containerIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.CONTAINER); final int itemTypeIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ITEM_TYPE); final int appWidgetIdIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.APPWIDGET_ID); final int screenIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.SCREEN); final int cellXIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.CELLX); final int cellYIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.CELLY); final int spanXIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.SPANX); final int spanYIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.SPANY); final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI); final int displayModeIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.DISPLAY_MODE); ApplicationInfo info; String intentDescription; Widget widgetInfo; LauncherAppWidgetInfo appWidgetInfo; int container; long id; Intent intent; while (!mStopped && c.moveToNext()) { try { int itemType = c.getInt(itemTypeIndex); switch (itemType) { case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: intentDescription = c.getString(intentIndex); try { intent = Intent.parseUri(intentDescription, 0); } catch (URISyntaxException e) { continue; } if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) { info = getApplicationInfo(manager, intent, context); } else { info = getApplicationInfoShortcut(c, context, iconTypeIndex, iconPackageIndex, iconResourceIndex, iconIndex); } if (info == null) { info = new ApplicationInfo(); info.icon = manager.getDefaultActivityIcon(); } if (info != null) { if (itemType != LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) { info.title = c.getString(titleIndex); } info.intent = intent; info.id = c.getLong(idIndex); container = c.getInt(containerIndex); info.container = container; info.screen = c.getInt(screenIndex); info.cellX = c.getInt(cellXIndex); info.cellY = c.getInt(cellYIndex); switch (container) { case LauncherSettings.Favorites.CONTAINER_DESKTOP: mItems.add(info); break; default: // Item is in a user folder UserFolderInfo folderInfo = findOrMakeUserFolder(mFolders, container); folderInfo.add(info); break; } } break; case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER: id = c.getLong(idIndex); UserFolderInfo folderInfo = findOrMakeUserFolder(mFolders, id); folderInfo.title = c.getString(titleIndex); folderInfo.id = id; container = c.getInt(containerIndex); folderInfo.container = container; folderInfo.screen = c.getInt(screenIndex); folderInfo.cellX = c.getInt(cellXIndex); folderInfo.cellY = c.getInt(cellYIndex); switch (container) { case LauncherSettings.Favorites.CONTAINER_DESKTOP: mItems.add(folderInfo); break; } mFolders.put(folderInfo.id, folderInfo); break; case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER: id = c.getLong(idIndex); LiveFolderInfo liveFolderInfo = findOrMakeLiveFolder(mFolders, id); intentDescription = c.getString(intentIndex); intent = null; if (intentDescription != null) { try { intent = Intent.parseUri(intentDescription, 0); } catch (URISyntaxException e) { // Ignore, a live folder might not have a base intent } } liveFolderInfo.title = c.getString(titleIndex); liveFolderInfo.id = id; container = c.getInt(containerIndex); liveFolderInfo.container = container; liveFolderInfo.screen = c.getInt(screenIndex); liveFolderInfo.cellX = c.getInt(cellXIndex); liveFolderInfo.cellY = c.getInt(cellYIndex); liveFolderInfo.uri = Uri.parse(c.getString(uriIndex)); liveFolderInfo.baseIntent = intent; liveFolderInfo.displayMode = c.getInt(displayModeIndex); loadLiveFolderIcon(context, c, iconTypeIndex, iconPackageIndex, iconResourceIndex, liveFolderInfo); switch (container) { case LauncherSettings.Favorites.CONTAINER_DESKTOP: mItems.add(liveFolderInfo); break; } mFolders.put(liveFolderInfo.id, liveFolderInfo); break; case LauncherSettings.Favorites.ITEM_TYPE_WIDGET_SEARCH: widgetInfo = Widget.makeSearch(); container = c.getInt(containerIndex); if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) { Log.e(TAG, "Widget found where container " + "!= CONTAINER_DESKTOP ignoring!"); continue; } widgetInfo.id = c.getLong(idIndex); widgetInfo.screen = c.getInt(screenIndex); widgetInfo.container = container; widgetInfo.cellX = c.getInt(cellXIndex); widgetInfo.cellY = c.getInt(cellYIndex); mItems.add(widgetInfo); break; case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET: // Read all Launcher-specific widget details int appWidgetId = c.getInt(appWidgetIdIndex); appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId); appWidgetInfo.id = c.getLong(idIndex); appWidgetInfo.screen = c.getInt(screenIndex); appWidgetInfo.cellX = c.getInt(cellXIndex); appWidgetInfo.cellY = c.getInt(cellYIndex); appWidgetInfo.spanX = c.getInt(spanXIndex); appWidgetInfo.spanY = c.getInt(spanYIndex); container = c.getInt(containerIndex); if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) { Log.e(TAG, "Widget found where container " + "!= CONTAINER_DESKTOP -- ignoring!"); continue; } appWidgetInfo.container = c.getInt(containerIndex); mAppWidgets.add(appWidgetInfo); break; } } catch (Exception e) { Log.w(TAG, "Desktop items loading interrupted:", e); } } } finally { c.close(); } Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms"); } /** * Read everything out of our database. */ private void bindWorkspace() { final long t = SystemClock.uptimeMillis(); // Don't use these two variables in any of the callback runnables. // Otherwise we hold a reference to them. Callbacks callbacks = mCallbacks.get(); if (callbacks == null) { // This launcher has exited and nobody bothered to tell us. Just bail. Log.w(TAG, "LoaderThread running with no launcher"); return; } int N; // Tell the workspace that we're about to start firing items at it mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(); if (callbacks != null) { callbacks.startBinding(); } } }); // Add the items to the workspace. N = mItems.size(); for (int i=0; i<N; i+=ITEMS_CHUNK) { final int start = i; final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i); mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(); if (callbacks != null) { callbacks.bindItems(mItems, start, start+chunkSize); } } }); } mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(); if (callbacks != null) { callbacks.bindFolders(mFolders); } } }); // Wait until the queue goes empty. mHandler.postIdle(new Runnable() { public void run() { Log.d(TAG, "Going to start binding widgets soon."); } }); // Bind the widgets, one at a time. // WARNING: this is calling into the workspace from the background thread, // but since getCurrentScreen() just returns the int, we should be okay. This // is just a hint for the order, and if it's wrong, we'll be okay. // TODO: instead, we should have that push the current screen into here. final int currentScreen = callbacks.getCurrentWorkspaceScreen(); N = mAppWidgets.size(); // once for the current screen for (int i=0; i<N; i++) { final LauncherAppWidgetInfo widget = mAppWidgets.get(i); if (widget.screen == currentScreen) { mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(); if (callbacks != null) { callbacks.bindAppWidget(widget); } } }); } } // once for the other screens for (int i=0; i<N; i++) { final LauncherAppWidgetInfo widget = mAppWidgets.get(i); if (widget.screen != currentScreen) { mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(); if (callbacks != null) { callbacks.bindAppWidget(widget); } } }); } } // Tell the workspace that we're done. mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(); if (callbacks != null) { callbacks.finishBindingItems(); } } }); // If we're profiling, this is the last thing in the queue. mHandler.post(new Runnable() { public void run() { Log.d(TAG, "bound workspace in " + (SystemClock.uptimeMillis()-t) + "ms"); if (Launcher.PROFILE_ROTATE) { android.os.Debug.stopMethodTracing(); } } }); } private void loadAllApps() { final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null); mainIntent.addCategory(Intent.CATEGORY_LAUNCHER); final Callbacks callbacks = tryGetCallbacks(); if (callbacks == null) { return; } final Context context = mContext; final PackageManager packageManager = context.getPackageManager(); final List<ResolveInfo> apps = packageManager.queryIntentActivities(mainIntent, 0); synchronized (mLock) { mBeforeFirstLoad = false; mAllAppsList.clear(); if (apps != null) { long t = SystemClock.uptimeMillis(); int N = apps.size(); Utilities.BubbleText bubble = new Utilities.BubbleText(context); for (int i=0; i<N && !mStopped; i++) { // This builds the icon bitmaps. mAllAppsList.add(AppInfoCache.cache(apps.get(i), context, bubble)); } Collections.sort(mAllAppsList.data, sComparator); Collections.sort(mAllAppsList.added, sComparator); Log.d(TAG, "cached app icons in " + (SystemClock.uptimeMillis()-t) + "ms"); } } } private void bindAllApps() { synchronized (mLock) { final ArrayList<ApplicationInfo> results = mAllAppsList.added; mAllAppsList.added = new ArrayList<ApplicationInfo>(); mHandler.post(new Runnable() { public void run() { final long t = SystemClock.uptimeMillis(); final int count = results.size(); Callbacks callbacks = tryGetCallbacks(); if (callbacks != null) { callbacks.bindAllApplications(results); } Log.d(TAG, "bound app " + count + " icons in " + (SystemClock.uptimeMillis()-t) + "ms"); } }); } } } } /** * Make an ApplicationInfo object for an application. */ private static ApplicationInfo getApplicationInfo(PackageManager manager, Intent intent, Context context) { final ResolveInfo resolveInfo = manager.resolveActivity(intent, 0); if (resolveInfo == null) { return null; } final ApplicationInfo info = new ApplicationInfo(); final ActivityInfo activityInfo = resolveInfo.activityInfo; info.icon = Utilities.createIconThumbnail(activityInfo.loadIcon(manager), context); if (info.title == null || info.title.length() == 0) { info.title = activityInfo.loadLabel(manager); } if (info.title == null) { info.title = ""; } info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION; return info; } /** * Make an ApplicationInfo object for a sortcut */ private static ApplicationInfo getApplicationInfoShortcut(Cursor c, Context context, int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex) { final ApplicationInfo info = new ApplicationInfo(); info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT; int iconType = c.getInt(iconTypeIndex); switch (iconType) { case LauncherSettings.Favorites.ICON_TYPE_RESOURCE: String packageName = c.getString(iconPackageIndex); String resourceName = c.getString(iconResourceIndex); PackageManager packageManager = context.getPackageManager(); try { Resources resources = packageManager.getResourcesForApplication(packageName); final int id = resources.getIdentifier(resourceName, null, null); info.icon = Utilities.createIconThumbnail(resources.getDrawable(id), context); } catch (Exception e) { info.icon = packageManager.getDefaultActivityIcon(); } info.iconResource = new Intent.ShortcutIconResource(); info.iconResource.packageName = packageName; info.iconResource.resourceName = resourceName; info.customIcon = false; break; case LauncherSettings.Favorites.ICON_TYPE_BITMAP: byte[] data = c.getBlob(iconIndex); try { Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length); info.icon = new FastBitmapDrawable( Utilities.createBitmapThumbnail(bitmap, context)); } catch (Exception e) { packageManager = context.getPackageManager(); info.icon = packageManager.getDefaultActivityIcon(); } info.filtered = true; info.customIcon = true; break; default: info.icon = context.getPackageManager().getDefaultActivityIcon(); info.customIcon = false; break; } return info; } private static void loadLiveFolderIcon(Context context, Cursor c, int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, LiveFolderInfo liveFolderInfo) { int iconType = c.getInt(iconTypeIndex); switch (iconType) { case LauncherSettings.Favorites.ICON_TYPE_RESOURCE: String packageName = c.getString(iconPackageIndex); String resourceName = c.getString(iconResourceIndex); PackageManager packageManager = context.getPackageManager(); try { Resources resources = packageManager.getResourcesForApplication(packageName); final int id = resources.getIdentifier(resourceName, null, null); liveFolderInfo.icon = resources.getDrawable(id); } catch (Exception e) { liveFolderInfo.icon = context.getResources().getDrawable(R.drawable.ic_launcher_folder); } liveFolderInfo.iconResource = new Intent.ShortcutIconResource(); liveFolderInfo.iconResource.packageName = packageName; liveFolderInfo.iconResource.resourceName = resourceName; break; default: liveFolderInfo.icon = context.getResources().getDrawable(R.drawable.ic_launcher_folder); } } /** * Return an existing UserFolderInfo object if we have encountered this ID previously, * or make a new one. */ private static UserFolderInfo findOrMakeUserFolder(HashMap<Long, FolderInfo> folders, long id) { // See if a placeholder was created for us already FolderInfo folderInfo = folders.get(id); if (folderInfo == null || !(folderInfo instanceof UserFolderInfo)) { // No placeholder -- create a new instance folderInfo = new UserFolderInfo(); folders.put(id, folderInfo); } return (UserFolderInfo) folderInfo; } /** * Return an existing UserFolderInfo object if we have encountered this ID previously, or make a * new one. */ private static LiveFolderInfo findOrMakeLiveFolder(HashMap<Long, FolderInfo> folders, long id) { // See if a placeholder was created for us already FolderInfo folderInfo = folders.get(id); if (folderInfo == null || !(folderInfo instanceof LiveFolderInfo)) { // No placeholder -- create a new instance folderInfo = new LiveFolderInfo(); folders.put(id, folderInfo); } return (LiveFolderInfo) folderInfo; } private static void updateShortcutLabels(ContentResolver resolver, PackageManager manager) { final Cursor c = resolver.query(LauncherSettings.Favorites.CONTENT_URI, new String[] { LauncherSettings.Favorites._ID, LauncherSettings.Favorites.TITLE, LauncherSettings.Favorites.INTENT, LauncherSettings.Favorites.ITEM_TYPE }, null, null, null); final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID); final int intentIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT); final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE); final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE); // boolean changed = false; try { while (c.moveToNext()) { try { if (c.getInt(itemTypeIndex) != LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) { continue; } final String intentUri = c.getString(intentIndex); if (intentUri != null) { final Intent shortcut = Intent.parseUri(intentUri, 0); if (Intent.ACTION_MAIN.equals(shortcut.getAction())) { final ComponentName name = shortcut.getComponent(); if (name != null) { final ActivityInfo activityInfo = manager.getActivityInfo(name, 0); final String title = c.getString(titleIndex); String label = getLabel(manager, activityInfo); if (title == null || !title.equals(label)) { final ContentValues values = new ContentValues(); values.put(LauncherSettings.Favorites.TITLE, label); resolver.update( LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values, "_id=?", new String[] { String.valueOf(c.getLong(idIndex)) }); // changed = true; } } } } } catch (URISyntaxException e) { // Ignore } catch (PackageManager.NameNotFoundException e) { // Ignore } } } finally { c.close(); } // if (changed) resolver.notifyChange(Settings.Favorites.CONTENT_URI, null); } private static String getLabel(PackageManager manager, ActivityInfo activityInfo) { String label = activityInfo.loadLabel(manager).toString(); if (label == null) { label = manager.getApplicationLabel(activityInfo.applicationInfo).toString(); if (label == null) { label = activityInfo.name; } } return label; } private static final Collator sCollator = Collator.getInstance(); private static final Comparator<ApplicationInfo> sComparator = new Comparator<ApplicationInfo>() { public final int compare(ApplicationInfo a, ApplicationInfo b) { return sCollator.compare(a.title.toString(), b.title.toString()); } }; }
diff --git a/src/edacc/EDACCManageDBMode.java b/src/edacc/EDACCManageDBMode.java index b3d3e4a..58f1659 100755 --- a/src/edacc/EDACCManageDBMode.java +++ b/src/edacc/EDACCManageDBMode.java @@ -1,2528 +1,2527 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * EDACCManageDBMode.java * @author * Created on 03.01.2010, 16:02:23 */ package edacc; import edacc.events.TaskEvents; import edacc.manageDB.*; import edacc.manageDB.InstanceException; import edacc.model.Instance; import edacc.model.InstanceIsInExperimentException; import edacc.model.InstanceNotInDBException; import edacc.model.InstanceClass; import edacc.model.InstanceDAO; import edacc.model.InstanceSourceClassHasInstance; import edacc.model.MD5CheckFailedException; import edacc.model.NoConnectionToDBException; import edacc.model.Parameter; import edacc.model.Solver; import edacc.model.SolverBinaries; import edacc.model.TaskCancelledException; import edacc.model.Tasks; import java.awt.*; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.security.NoSuchAlgorithmException; import java.sql.SQLException; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.LinkedList; import java.util.Vector; import java.util.logging.Level; import java.util.logging.Logger; import javax.sound.midi.ControllerEventListener; import javax.swing.ImageIcon; import javax.swing.InputVerifier; import javax.swing.JComponent; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.table.*; import javax.swing.JOptionPane; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.JTree; import javax.swing.RowSorter.SortKey; import javax.swing.SwingUtilities; import javax.swing.event.TableModelEvent; import javax.swing.event.TableModelListener; import javax.swing.table.TableRowSorter; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreePath; import javax.swing.tree.TreeSelectionModel; import org.jdesktop.application.Action; /** * * @author rretz */ public class EDACCManageDBMode extends javax.swing.JPanel implements TaskEvents { public boolean unsavedChanges; public ManageDBInstances manageDBInstances; public InstanceTableModel instanceTableModel; public DefaultTreeModel instanceClassTreeModel; public TableRowSorter<InstanceTableModel> sorter; private ManageDBSolvers manageDBSolvers; private SolverTableModel solverTableModel; private ManageDBParameters manageDBParameters; private ParameterTableModel parameterTableModel; public EDACCCreateEditInstanceClassDialog createInstanceClassDialog; public EDACCAddNewInstanceSelectClassDialog addInstanceDialog; public EDACCInstanceGeneratorUnifKCNF instanceGenKCNF; public EDACCInstanceFilter instanceFilter; private SolverBinariesTableModel solverBinariesTableModel; public EDACCManageDBMode() { initComponents(); unsavedChanges = false; manageDBInstances = new ManageDBInstances(this, panelManageDBInstances, jFileChooserManageDBInstance, jFileChooserManageDBExportInstance, tableInstances); // initialize instance table instanceTableModel = new InstanceTableModel(); sorter = new TableRowSorter<InstanceTableModel>(instanceTableModel); tableInstances.setModel(instanceTableModel); tableInstances.setRowSorter(sorter); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { instanceFilter = new EDACCInstanceFilter(EDACCApp.getApplication().getMainFrame(), true, tableInstances, true); } }); tableInstances.getSelectionModel().addListSelectionListener(new InstanceTableSelectionListener(tableInstances, manageDBInstances)); tableInstances.addMouseListener(new InstanceTableMouseListener(jPMInstanceTable)); // initialize instance class table instanceClassTreeModel = new DefaultTreeModel(new DefaultMutableTreeNode("test1")); jTreeInstanceClass.setModel(instanceClassTreeModel); jTreeInstanceClass.getSelectionModel().setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION); jTreeInstanceClass.addTreeSelectionListener(new InstanceClassTreeSelectionListener(manageDBInstances, jTreeInstanceClass)); jTreeInstanceClass.addMouseListener(new InstanceClassTreeMouseListener(jPMInstanceTreeInstanceClass)); // initialize parameter table parameterTableModel = new ParameterTableModel(); manageDBParameters = new ManageDBParameters(this, parameterTableModel); tableParameters.setModel(parameterTableModel); tableParameters.setRowSorter(new TableRowSorter<ParameterTableModel>(parameterTableModel)); // initialize the solver binaries table solverBinariesTableModel = new SolverBinariesTableModel(); tableSolverBinaries.setModel(solverBinariesTableModel); // initialize solver table solverTableModel = new SolverTableModel(); manageDBSolvers = new ManageDBSolvers(this, solverTableModel, manageDBParameters, solverBinariesTableModel); tableSolver.setModel(solverTableModel); tableSolver.setRowSorter(new TableRowSorter<SolverTableModel>(solverTableModel)); tableSolver.getSelectionModel().addListSelectionListener(new SolverTableSelectionListener(tableSolver, manageDBSolvers)); tableParameters.getSelectionModel().addListSelectionListener(new ParameterTableSelectionListener(tableParameters, manageDBParameters)); showSolverDetails(null); tableParameters.setDefaultRenderer(tableParameters.getColumnClass(2), new DefaultTableCellRenderer() { @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { JLabel lbl = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); lbl.setHorizontalAlignment(JLabel.CENTER); return lbl; } }); //TODO: FontMetrics verwenden!!! //tableParameters.getColumnModel().getColumn(0).setMaxWidth(metric.stringWidth(tableParameters.getModel().getColumnName(0))+10); //tableParameters.getColumnModel().getColumn(0).setMinWidth(metric.stringWidth(tableParameters.getModel().getColumnName(0))+5); /*tableParameters.getColumnModel().getColumn(3).setMaxWidth(50); tableInstanceClass.getColumnModel().getColumn(2).setMaxWidth(55); tableInstanceClass.getColumnModel().getColumn(3).setMaxWidth(55); tableInstanceClass.getColumnModel().getColumn(2).setMinWidth(40); tableInstanceClass.getColumnModel().getColumn(3).setMinWidth(40); this.jSplitPane2.setDividerLocation(-1);*/ } public void initialize() throws NoConnectionToDBException, SQLException { manageDBSolvers.loadSolvers(); manageDBParameters.loadParametersOfSolvers(solverTableModel.getSolvers()); manageDBInstances.loadInstanceClasses(); manageDBInstances.loadInstances(); instanceTableModel.updateProperties(); instanceTableModel.fireTableDataChanged(); jTreeInstanceClass.updateUI(); unsavedChanges = false; } /** 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 Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jFileChooserManageDBInstance = new javax.swing.JFileChooser(); jFileChooserManageDBExportInstance = new javax.swing.JFileChooser(); jPMInstanceTable = new javax.swing.JPopupMenu(); jMIAddInstance = new javax.swing.JMenuItem(); jMIRemoveInstance = new javax.swing.JMenuItem(); jMIExportInstance = new javax.swing.JMenuItem(); jPMInstanceTreeInstanceClass = new javax.swing.JPopupMenu(); jMINewInstanceClass = new javax.swing.JMenuItem(); jMIEditInstanceClass = new javax.swing.JMenuItem(); jMIRemoveInstanceClass = new javax.swing.JMenuItem(); jMIExportInstanceClass = new javax.swing.JMenuItem(); manageDBPane = new javax.swing.JTabbedPane(); panelManageDBSolver = new javax.swing.JPanel(); jSplitPane2 = new javax.swing.JSplitPane(); panelParametersOverall = new javax.swing.JPanel(); panelParameters = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); tableParameters = new javax.swing.JTable(); jPanel2 = new javax.swing.JPanel(); jlParametersName = new javax.swing.JLabel(); tfParametersName = new javax.swing.JTextField(); jlParametersPrefix = new javax.swing.JLabel(); tfParametersPrefix = new javax.swing.JTextField(); jlParametersOrder = new javax.swing.JLabel(); tfParametersOrder = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); chkHasNoValue = new javax.swing.JCheckBox(); lMandatory = new javax.swing.JLabel(); chkMandatory = new javax.swing.JCheckBox(); chkSpace = new javax.swing.JCheckBox(); lSpace = new javax.swing.JLabel(); jlParametersDefaultValue = new javax.swing.JLabel(); tfParametersDefaultValue = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); chkAttachToPrevious = new javax.swing.JCheckBox(); panelParametersButons = new javax.swing.JPanel(); btnParametersDelete = new javax.swing.JButton(); btnParametersNew = new javax.swing.JButton(); panelSolverOverall = new javax.swing.JPanel(); panelSolver = new javax.swing.JPanel(); jScrollPane2 = new javax.swing.JScrollPane(); tableSolver = new javax.swing.JTable(); jPanel1 = new javax.swing.JPanel(); jlSolverName = new javax.swing.JLabel(); tfSolverName = new javax.swing.JTextField(); jlSolverDescription = new javax.swing.JLabel(); jScrollPane3 = new javax.swing.JScrollPane(); taSolverDescription = new javax.swing.JTextArea(); jlSolverBinary = new javax.swing.JLabel(); jlSolverCode = new javax.swing.JLabel(); btnSolverAddCode = new javax.swing.JButton(); tfSolverAuthors = new javax.swing.JTextField(); tfSolverVersion = new javax.swing.JTextField(); jlSolverAuthors = new javax.swing.JLabel(); jlSolverVersion = new javax.swing.JLabel(); btnSolverAddBinary = new javax.swing.JButton(); jScrollPane4 = new javax.swing.JScrollPane(); tableSolverBinaries = new javax.swing.JTable(); btnSolverEditBinary = new javax.swing.JButton(); btnSolverDeleteBinary = new javax.swing.JButton(); panelSolverButtons = new javax.swing.JPanel(); btnSolverDelete = new javax.swing.JButton(); btnSolverNew = new javax.swing.JButton(); jPanel3 = new javax.swing.JPanel(); btnSolverSaveToDB = new javax.swing.JButton(); btnSolverRefresh = new javax.swing.JButton(); btnSolverExport = new javax.swing.JButton(); panelManageDBInstances = new javax.swing.JPanel(); jSplitPane1 = new javax.swing.JSplitPane(); panelInstanceClass = new javax.swing.JPanel(); panelButtonsInstanceClass = new javax.swing.JPanel(); btnNewInstanceClass = new javax.swing.JButton(); btnEditInstanceClass = new javax.swing.JButton(); btnRemoveInstanceClass = new javax.swing.JButton(); btnExportInstanceClass = new javax.swing.JButton(); panelInstanceClassTable = new javax.swing.JScrollPane(); jTreeInstanceClass = new javax.swing.JTree(); panelInstance = new javax.swing.JPanel(); panelInstanceTable = new javax.swing.JScrollPane(); tableInstances = new javax.swing.JTable(); panelButtonsInstances = new javax.swing.JPanel(); btnAddInstances = new javax.swing.JButton(); btnRemoveInstances = new javax.swing.JButton(); btnExportInstances = new javax.swing.JButton(); btnAddToClass = new javax.swing.JButton(); btnRemoveFromClass = new javax.swing.JButton(); btnAddInstances1 = new javax.swing.JButton(); bComputeProperty = new javax.swing.JButton(); btnGenerate = new javax.swing.JButton(); lblFilterStatus = new javax.swing.JLabel(); btnFilterInstances = new javax.swing.JButton(); btnSelectInstanceColumns = new javax.swing.JButton(); jFileChooserManageDBInstance.setFileSelectionMode(javax.swing.JFileChooser.FILES_AND_DIRECTORIES); jFileChooserManageDBInstance.setName("jFileChooserManageDBInstance"); // NOI18N jFileChooserManageDBExportInstance.setFileSelectionMode(javax.swing.JFileChooser.DIRECTORIES_ONLY); jFileChooserManageDBExportInstance.setName("jFileChooserManageDBExportInstance"); // NOI18N jPMInstanceTable.setBorderPainted(false); jPMInstanceTable.setComponentPopupMenu(jPMInstanceTable); org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(edacc.EDACCApp.class).getContext().getResourceMap(EDACCManageDBMode.class); jPMInstanceTable.setLabel(resourceMap.getString("jPMInstanceTable.label")); // NOI18N jPMInstanceTable.setMaximumSize(new java.awt.Dimension(10, 10)); jPMInstanceTable.setMinimumSize(new java.awt.Dimension(10, 10)); jPMInstanceTable.setName("jPMInstanceTable"); // NOI18N jMIAddInstance.setText(resourceMap.getString("jMIAddInstance.text")); // NOI18N jMIAddInstance.setName("jMIAddInstance"); // NOI18N jMIAddInstance.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMIAddInstanceActionPerformed(evt); } }); jPMInstanceTable.add(jMIAddInstance); jMIRemoveInstance.setText(resourceMap.getString("jMIRemoveInstance.text")); // NOI18N jMIRemoveInstance.setName("jMIRemoveInstance"); // NOI18N jMIRemoveInstance.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMIRemoveInstanceActionPerformed(evt); } }); jPMInstanceTable.add(jMIRemoveInstance); jMIExportInstance.setText(resourceMap.getString("jMIExportInstance.text")); // NOI18N jMIExportInstance.setName("jMIExportInstance"); // NOI18N jMIExportInstance.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMIExportInstanceActionPerformed(evt); } }); jPMInstanceTable.add(jMIExportInstance); jPMInstanceTreeInstanceClass.setName("jPMInstanceTreeInstanceClass"); // NOI18N jMINewInstanceClass.setText(resourceMap.getString("jMINewInstanceClass.text")); // NOI18N jMINewInstanceClass.setName("jMINewInstanceClass"); // NOI18N jMINewInstanceClass.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMINewInstanceClassActionPerformed(evt); } }); jPMInstanceTreeInstanceClass.add(jMINewInstanceClass); jMIEditInstanceClass.setText(resourceMap.getString("jMIEditInstanceClass.text")); // NOI18N jMIEditInstanceClass.setName("jMIEditInstanceClass"); // NOI18N jMIEditInstanceClass.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMIEditInstanceClassActionPerformed(evt); } }); jPMInstanceTreeInstanceClass.add(jMIEditInstanceClass); jMIRemoveInstanceClass.setText(resourceMap.getString("jMIRemoveInstanceClass.text")); // NOI18N jMIRemoveInstanceClass.setName("jMIRemoveInstanceClass"); // NOI18N jMIRemoveInstanceClass.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMIRemoveInstanceClassActionPerformed(evt); } }); jPMInstanceTreeInstanceClass.add(jMIRemoveInstanceClass); jMIExportInstanceClass.setText(resourceMap.getString("jMIExportInstanceClass.text")); // NOI18N jMIExportInstanceClass.setName("jMIExportInstanceClass"); // NOI18N jMIExportInstanceClass.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMIExportInstanceClassActionPerformed(evt); } }); jPMInstanceTreeInstanceClass.add(jMIExportInstanceClass); setMinimumSize(new java.awt.Dimension(0, 0)); setName("Form"); // NOI18N setPreferredSize(new java.awt.Dimension(500, 591)); manageDBPane.setMinimumSize(new java.awt.Dimension(0, 0)); manageDBPane.setName("manageDBPane"); // NOI18N manageDBPane.setRequestFocusEnabled(false); panelManageDBSolver.setName("panelManageDBSolver"); // NOI18N panelManageDBSolver.setPreferredSize(new java.awt.Dimension(0, 0)); jSplitPane2.setDividerLocation(0.6); jSplitPane2.setResizeWeight(0.5); jSplitPane2.setName("jSplitPane2"); // NOI18N panelParametersOverall.setName("panelParametersOverall"); // NOI18N panelParametersOverall.setPreferredSize(new java.awt.Dimension(0, 0)); panelParameters.setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("panelParameters.border.title"))); // NOI18N panelParameters.setName("panelParameters"); // NOI18N panelParameters.setPreferredSize(new java.awt.Dimension(0, 0)); jScrollPane1.setMinimumSize(new java.awt.Dimension(0, 0)); jScrollPane1.setName("jScrollPane1"); // NOI18N jScrollPane1.setPreferredSize(new java.awt.Dimension(0, 0)); tableParameters.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null} }, new String [] { "Title 1", "Title 2", "Title 3", "Title 4" } )); tableParameters.setToolTipText(resourceMap.getString("tableParameters.toolTipText")); // NOI18N tableParameters.setName("tableParameters"); // NOI18N - tableParameters.setPreferredSize(new java.awt.Dimension(100, 72)); tableParameters.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); jScrollPane1.setViewportView(tableParameters); jPanel2.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel2.setName("jPanel2"); // NOI18N jlParametersName.setText(resourceMap.getString("jlParametersName.text")); // NOI18N jlParametersName.setName("jlParametersName"); // NOI18N tfParametersName.setText(resourceMap.getString("tfParametersName.text")); // NOI18N tfParametersName.setToolTipText(resourceMap.getString("tfParametersName.toolTipText")); // NOI18N tfParametersName.setInputVerifier(new ParameterNameVerifier()); tfParametersName.setName("tfParametersName"); // NOI18N tfParametersName.addFocusListener(new java.awt.event.FocusAdapter() { public void focusLost(java.awt.event.FocusEvent evt) { parameterChangedOnFocusLost(evt); } }); tfParametersName.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { parameterChangedOnKeyReleased(evt); } }); jlParametersPrefix.setText(resourceMap.getString("jlParametersPrefix.text")); // NOI18N jlParametersPrefix.setName("jlParametersPrefix"); // NOI18N tfParametersPrefix.setText(resourceMap.getString("tfParametersPrefix.text")); // NOI18N tfParametersPrefix.setToolTipText(resourceMap.getString("tfParametersPrefix.toolTipText")); // NOI18N tfParametersPrefix.setName("tfParametersPrefix"); // NOI18N tfParametersPrefix.addFocusListener(new java.awt.event.FocusAdapter() { public void focusLost(java.awt.event.FocusEvent evt) { parameterChangedOnFocusLost(evt); } }); tfParametersPrefix.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { parameterChangedOnKeyReleased(evt); } }); jlParametersOrder.setText(resourceMap.getString("jlParametersOrder.text")); // NOI18N jlParametersOrder.setName("jlParametersOrder"); // NOI18N tfParametersOrder.setText(resourceMap.getString("tfParametersOrder.text")); // NOI18N tfParametersOrder.setToolTipText(resourceMap.getString("tfParametersOrder.toolTipText")); // NOI18N tfParametersOrder.setName("tfParametersOrder"); // NOI18N tfParametersOrder.addFocusListener(new java.awt.event.FocusAdapter() { public void focusLost(java.awt.event.FocusEvent evt) { parameterChangedOnFocusLost(evt); } }); tfParametersOrder.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { parameterChangedOnKeyReleased(evt); } }); jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N jLabel1.setToolTipText(resourceMap.getString("jLabel1.toolTipText")); // NOI18N jLabel1.setName("jLabel1"); // NOI18N chkHasNoValue.setText(resourceMap.getString("chkHasNoValue.text")); // NOI18N chkHasNoValue.setToolTipText(resourceMap.getString("chkHasNoValue.toolTipText")); // NOI18N chkHasNoValue.setName("chkHasNoValue"); // NOI18N chkHasNoValue.addChangeListener(new javax.swing.event.ChangeListener() { public void stateChanged(javax.swing.event.ChangeEvent evt) { chkHasNoValueStateChanged(evt); } }); lMandatory.setText(resourceMap.getString("lMandatory.text")); // NOI18N lMandatory.setToolTipText(resourceMap.getString("lMandatory.toolTipText")); // NOI18N lMandatory.setName("lMandatory"); // NOI18N chkMandatory.setToolTipText(resourceMap.getString("chkMandatory.toolTipText")); // NOI18N chkMandatory.setName("chkMandatory"); // NOI18N chkMandatory.addChangeListener(new javax.swing.event.ChangeListener() { public void stateChanged(javax.swing.event.ChangeEvent evt) { chkMandatoryStateChanged(evt); } }); chkSpace.setToolTipText(resourceMap.getString("chkSpace.toolTipText")); // NOI18N chkSpace.setName("chkSpace"); // NOI18N chkSpace.addChangeListener(new javax.swing.event.ChangeListener() { public void stateChanged(javax.swing.event.ChangeEvent evt) { chkSpaceChanged(evt); } }); lSpace.setText(resourceMap.getString("lSpace.text")); // NOI18N lSpace.setToolTipText(resourceMap.getString("lSpace.toolTipText")); // NOI18N lSpace.setName("lSpace"); // NOI18N jlParametersDefaultValue.setText(resourceMap.getString("jlParametersDefaultValue.text")); // NOI18N jlParametersDefaultValue.setName("jlParametersDefaultValue"); // NOI18N tfParametersDefaultValue.setText(resourceMap.getString("tfParametersDefaultValue.text")); // NOI18N tfParametersDefaultValue.setName("tfParametersDefaultValue"); // NOI18N tfParametersDefaultValue.addFocusListener(new java.awt.event.FocusAdapter() { public void focusLost(java.awt.event.FocusEvent evt) { parameterChangedOnFocusLost(evt); } }); tfParametersDefaultValue.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { parameterChangedOnKeyReleased(evt); } }); jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N jLabel2.setToolTipText(resourceMap.getString("jLabel2.toolTipText")); // NOI18N jLabel2.setName("jLabel2"); // NOI18N chkAttachToPrevious.setToolTipText(resourceMap.getString("chkAttachToPrevious.toolTipText")); // NOI18N chkAttachToPrevious.setName("chkAttachToPrevious"); // NOI18N chkAttachToPrevious.addChangeListener(new javax.swing.event.ChangeListener() { public void stateChanged(javax.swing.event.ChangeEvent evt) { chkAttachToPreviousStateChanged(evt); } }); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jlParametersName, javax.swing.GroupLayout.DEFAULT_SIZE, 81, Short.MAX_VALUE) .addComponent(jlParametersPrefix, javax.swing.GroupLayout.DEFAULT_SIZE, 81, Short.MAX_VALUE) .addComponent(jlParametersOrder, javax.swing.GroupLayout.DEFAULT_SIZE, 81, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)) .addGroup(jPanel2Layout.createSequentialGroup() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1) .addComponent(lMandatory) .addComponent(lSpace) .addComponent(jlParametersDefaultValue)) .addGap(12, 12, 12)))) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(tfParametersName, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 71, Short.MAX_VALUE) .addComponent(tfParametersPrefix, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 71, Short.MAX_VALUE) .addComponent(tfParametersOrder, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 71, Short.MAX_VALUE) .addComponent(tfParametersDefaultValue, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 71, Short.MAX_VALUE) .addComponent(chkSpace)) .addComponent(chkAttachToPrevious, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(chkMandatory, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(chkHasNoValue, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap()) ); jPanel2Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jLabel1, jlParametersName, jlParametersOrder, jlParametersPrefix}); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap(61, Short.MAX_VALUE) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jlParametersName) .addComponent(tfParametersName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jlParametersPrefix, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(tfParametersPrefix, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jlParametersOrder) .addComponent(tfParametersOrder, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(tfParametersDefaultValue, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jlParametersDefaultValue)) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(8, 8, 8) .addComponent(jLabel1)) .addGroup(jPanel2Layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(chkHasNoValue))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(8, 8, 8) .addComponent(lMandatory)) .addComponent(chkMandatory)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(lSpace) .addComponent(chkSpace)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel2) .addComponent(chkAttachToPrevious)) .addContainerGap()) ); panelParametersButons.setName("panelParametersButons"); // NOI18N btnParametersDelete.setText(resourceMap.getString("btnParametersDelete.text")); // NOI18N btnParametersDelete.setToolTipText(resourceMap.getString("btnParametersDelete.toolTipText")); // NOI18N btnParametersDelete.setName("btnParametersDelete"); // NOI18N btnParametersDelete.setPreferredSize(new java.awt.Dimension(81, 25)); btnParametersDelete.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnParametersDeleteActionPerformed(evt); } }); btnParametersNew.setText(resourceMap.getString("btnParametersNew.text")); // NOI18N btnParametersNew.setToolTipText(resourceMap.getString("btnParametersNew.toolTipText")); // NOI18N btnParametersNew.setName("btnParametersNew"); // NOI18N btnParametersNew.setPreferredSize(new java.awt.Dimension(81, 25)); btnParametersNew.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnParametersNewActionPerformed(evt); } }); javax.swing.GroupLayout panelParametersButonsLayout = new javax.swing.GroupLayout(panelParametersButons); panelParametersButons.setLayout(panelParametersButonsLayout); panelParametersButonsLayout.setHorizontalGroup( panelParametersButonsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panelParametersButonsLayout.createSequentialGroup() .addContainerGap() .addComponent(btnParametersNew, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnParametersDelete, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); panelParametersButonsLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btnParametersDelete, btnParametersNew}); panelParametersButonsLayout.setVerticalGroup( panelParametersButonsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panelParametersButonsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnParametersNew, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnParametersDelete, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) ); javax.swing.GroupLayout panelParametersLayout = new javax.swing.GroupLayout(panelParameters); panelParameters.setLayout(panelParametersLayout); panelParametersLayout.setHorizontalGroup( panelParametersLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelParametersLayout.createSequentialGroup() .addContainerGap() .addGroup(panelParametersLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jPanel2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 192, Short.MAX_VALUE) .addComponent(panelParametersButons, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap()) ); panelParametersLayout.setVerticalGroup( panelParametersLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelParametersLayout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 73, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(panelParametersButons, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); javax.swing.GroupLayout panelParametersOverallLayout = new javax.swing.GroupLayout(panelParametersOverall); panelParametersOverall.setLayout(panelParametersOverallLayout); panelParametersOverallLayout.setHorizontalGroup( panelParametersOverallLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(panelParameters, javax.swing.GroupLayout.DEFAULT_SIZE, 228, Short.MAX_VALUE) ); panelParametersOverallLayout.setVerticalGroup( panelParametersOverallLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panelParametersOverallLayout.createSequentialGroup() .addContainerGap() .addComponent(panelParameters, javax.swing.GroupLayout.DEFAULT_SIZE, 464, Short.MAX_VALUE) .addContainerGap()) ); jSplitPane2.setRightComponent(panelParametersOverall); panelParametersOverall.getAccessibleContext().setAccessibleName(resourceMap.getString("panelParameters.AccessibleContext.accessibleName")); // NOI18N panelSolverOverall.setName("panelSolverOverall"); // NOI18N panelSolverOverall.setPreferredSize(new java.awt.Dimension(500, 489)); panelSolver.setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("panelSolver.border.title"))); // NOI18N panelSolver.setAutoscrolls(true); panelSolver.setName("panelSolver"); // NOI18N jScrollPane2.setToolTipText(resourceMap.getString("jScrollPane2.toolTipText")); // NOI18N jScrollPane2.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); jScrollPane2.setAutoscrolls(true); jScrollPane2.setEnabled(false); jScrollPane2.setMinimumSize(new java.awt.Dimension(100, 100)); jScrollPane2.setName("jScrollPane2"); // NOI18N jScrollPane2.setPreferredSize(new java.awt.Dimension(100, 100)); tableSolver.setAutoCreateRowSorter(true); tableSolver.setMinimumSize(new java.awt.Dimension(50, 0)); tableSolver.setName("tableSolver"); // NOI18N tableSolver.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); jScrollPane2.setViewportView(tableSolver); jPanel1.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel1.setName("jPanel1"); // NOI18N jlSolverName.setText(resourceMap.getString("jlSolverName.text")); // NOI18N jlSolverName.setName("jlSolverName"); // NOI18N tfSolverName.setText(resourceMap.getString("tfSolverName.text")); // NOI18N tfSolverName.setToolTipText(resourceMap.getString("tfSolverName.toolTipText")); // NOI18N tfSolverName.setName("tfSolverName"); // NOI18N tfSolverName.addFocusListener(new java.awt.event.FocusAdapter() { public void focusLost(java.awt.event.FocusEvent evt) { solverChangedOnFocusLost(evt); } }); tfSolverName.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { solverChangedOnKey(evt); } }); jlSolverDescription.setText(resourceMap.getString("jlSolverDescription.text")); // NOI18N jlSolverDescription.setName("jlSolverDescription"); // NOI18N jScrollPane3.setName("jScrollPane3"); // NOI18N taSolverDescription.setColumns(20); taSolverDescription.setLineWrap(true); taSolverDescription.setRows(5); taSolverDescription.setToolTipText(resourceMap.getString("taSolverDescription.toolTipText")); // NOI18N taSolverDescription.setName("taSolverDescription"); // NOI18N taSolverDescription.addFocusListener(new java.awt.event.FocusAdapter() { public void focusLost(java.awt.event.FocusEvent evt) { solverChangedOnFocusLost(evt); } }); taSolverDescription.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { solverChangedOnKey(evt); } }); jScrollPane3.setViewportView(taSolverDescription); jlSolverBinary.setText(resourceMap.getString("jlSolverBinary.text")); // NOI18N jlSolverBinary.setName("jlSolverBinary"); // NOI18N jlSolverCode.setText(resourceMap.getString("jlSolverCode.text")); // NOI18N jlSolverCode.setName("jlSolverCode"); // NOI18N btnSolverAddCode.setText(resourceMap.getString("btnSolverAddCode.text")); // NOI18N btnSolverAddCode.setToolTipText(resourceMap.getString("btnSolverAddCode.toolTipText")); // NOI18N btnSolverAddCode.setName("btnSolverAddCode"); // NOI18N btnSolverAddCode.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnSolverAddCodeActionPerformed(evt); } }); tfSolverAuthors.setText(resourceMap.getString("tfSolverAuthors.text")); // NOI18N tfSolverAuthors.setName("tfSolverAuthors"); // NOI18N tfSolverAuthors.addFocusListener(new java.awt.event.FocusAdapter() { public void focusLost(java.awt.event.FocusEvent evt) { solverChangedOnFocusLost(evt); } }); tfSolverAuthors.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { solverChangedOnKey(evt); } }); tfSolverVersion.setText(resourceMap.getString("tfSolverVersion.text")); // NOI18N tfSolverVersion.setName("tfSolverVersion"); // NOI18N tfSolverVersion.addFocusListener(new java.awt.event.FocusAdapter() { public void focusLost(java.awt.event.FocusEvent evt) { solverChangedOnFocusLost(evt); } }); tfSolverVersion.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { solverChangedOnKey(evt); } }); jlSolverAuthors.setText(resourceMap.getString("jlSolverAuthors.text")); // NOI18N jlSolverAuthors.setName("jlSolverAuthors"); // NOI18N jlSolverVersion.setText(resourceMap.getString("jlSolverVersion.text")); // NOI18N jlSolverVersion.setName("jlSolverVersion"); // NOI18N btnSolverAddBinary.setText(resourceMap.getString("btnSolverAddBinary.text")); // NOI18N btnSolverAddBinary.setToolTipText(resourceMap.getString("btnSolverAddBinary.toolTipText")); // NOI18N btnSolverAddBinary.setName("btnSolverAddBinary"); // NOI18N btnSolverAddBinary.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnSolverAddBinaryActionPerformed(evt); } }); jScrollPane4.setName("jScrollPane4"); // NOI18N tableSolverBinaries.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null} }, new String [] { "Title 1", "Title 2", "Title 3", "Title 4" } )); tableSolverBinaries.setName("tableSolverBinaries"); // NOI18N jScrollPane4.setViewportView(tableSolverBinaries); btnSolverEditBinary.setText(resourceMap.getString("btnSolverEditBinary.text")); // NOI18N btnSolverEditBinary.setActionCommand(resourceMap.getString("btnSolverEditBinary.actionCommand")); // NOI18N btnSolverEditBinary.setName("btnSolverEditBinary"); // NOI18N btnSolverEditBinary.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnSolverEditBinaryActionPerformed(evt); } }); btnSolverDeleteBinary.setText(resourceMap.getString("btnSolverDeleteBinary.text")); // NOI18N btnSolverDeleteBinary.setActionCommand(resourceMap.getString("btnSolverDeleteBinary.actionCommand")); // NOI18N btnSolverDeleteBinary.setName("btnSolverDeleteBinary"); // NOI18N btnSolverDeleteBinary.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnSolverDeleteBinaryActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jlSolverBinary) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(btnSolverAddBinary, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnSolverEditBinary, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 178, Short.MAX_VALUE) .addComponent(btnSolverDeleteBinary, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 409, Short.MAX_VALUE))) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jlSolverName, javax.swing.GroupLayout.DEFAULT_SIZE, 91, Short.MAX_VALUE) .addComponent(jlSolverDescription, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jlSolverVersion) .addGap(56, 56, 56)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jlSolverCode) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))) .addComponent(jlSolverAuthors)) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(tfSolverAuthors, javax.swing.GroupLayout.DEFAULT_SIZE, 409, Short.MAX_VALUE) .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 409, Short.MAX_VALUE) .addComponent(tfSolverName, javax.swing.GroupLayout.DEFAULT_SIZE, 409, Short.MAX_VALUE) .addGroup(jPanel1Layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(btnSolverAddCode) .addComponent(tfSolverVersion, javax.swing.GroupLayout.DEFAULT_SIZE, 409, Short.MAX_VALUE)))))) .addContainerGap()) ); jPanel1Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jlSolverBinary, jlSolverCode, jlSolverDescription, jlSolverName}); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(tfSolverName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jlSolverName)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jlSolverDescription, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jlSolverAuthors) .addComponent(tfSolverAuthors, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jlSolverVersion) .addComponent(tfSolverVersion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jlSolverCode) .addComponent(btnSolverAddCode)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jlSolverBinary) .addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 97, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnSolverAddBinary) .addComponent(btnSolverEditBinary) .addComponent(btnSolverDeleteBinary)) .addContainerGap()) ); panelSolverButtons.setName("panelSolverButtons"); // NOI18N btnSolverDelete.setText(resourceMap.getString("btnSolverDelete.text")); // NOI18N btnSolverDelete.setToolTipText(resourceMap.getString("btnSolverDelete.toolTipText")); // NOI18N btnSolverDelete.setName("btnSolverDelete"); // NOI18N btnSolverDelete.setPreferredSize(new java.awt.Dimension(81, 25)); btnSolverDelete.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnSolverDeleteActionPerformed(evt); } }); btnSolverNew.setText(resourceMap.getString("btnNew.text")); // NOI18N btnSolverNew.setToolTipText(resourceMap.getString("btnNew.toolTipText")); // NOI18N btnSolverNew.setMaximumSize(new java.awt.Dimension(81, 25)); btnSolverNew.setMinimumSize(new java.awt.Dimension(81, 25)); btnSolverNew.setName("btnNew"); // NOI18N btnSolverNew.setPreferredSize(new java.awt.Dimension(81, 25)); btnSolverNew.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnSolverNewActionPerformed(evt); } }); javax.swing.GroupLayout panelSolverButtonsLayout = new javax.swing.GroupLayout(panelSolverButtons); panelSolverButtons.setLayout(panelSolverButtonsLayout); panelSolverButtonsLayout.setHorizontalGroup( panelSolverButtonsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panelSolverButtonsLayout.createSequentialGroup() .addContainerGap() .addComponent(btnSolverNew, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnSolverDelete, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(360, Short.MAX_VALUE)) ); panelSolverButtonsLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btnSolverDelete, btnSolverNew}); panelSolverButtonsLayout.setVerticalGroup( panelSolverButtonsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panelSolverButtonsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnSolverNew, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnSolverDelete, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) ); javax.swing.GroupLayout panelSolverLayout = new javax.swing.GroupLayout(panelSolver); panelSolver.setLayout(panelSolverLayout); panelSolverLayout.setHorizontalGroup( panelSolverLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelSolverLayout.createSequentialGroup() .addGroup(panelSolverLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 540, Short.MAX_VALUE) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(panelSolverButtons, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap()) ); panelSolverLayout.setVerticalGroup( panelSolverLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelSolverLayout.createSequentialGroup() .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 47, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(panelSolverButtons, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(4, 4, 4)) ); jScrollPane2.getAccessibleContext().setAccessibleParent(manageDBPane); javax.swing.GroupLayout panelSolverOverallLayout = new javax.swing.GroupLayout(panelSolverOverall); panelSolverOverall.setLayout(panelSolverOverallLayout); panelSolverOverallLayout.setHorizontalGroup( panelSolverOverallLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(panelSolver, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); panelSolverOverallLayout.setVerticalGroup( panelSolverOverallLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panelSolverOverallLayout.createSequentialGroup() .addContainerGap() .addComponent(panelSolver, javax.swing.GroupLayout.DEFAULT_SIZE, 464, Short.MAX_VALUE) .addContainerGap()) ); jSplitPane2.setLeftComponent(panelSolverOverall); jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("")); jPanel3.setName("jPanel3"); // NOI18N btnSolverSaveToDB.setText(resourceMap.getString("btnSolverSaveToDB.text")); // NOI18N btnSolverSaveToDB.setToolTipText(resourceMap.getString("btnSolverSaveToDB.toolTipText")); // NOI18N btnSolverSaveToDB.setName("btnSolverSaveToDB"); // NOI18N btnSolverSaveToDB.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnSolverSaveToDBActionPerformed(evt); } }); btnSolverRefresh.setText(resourceMap.getString("btnSolverRefresh.text")); // NOI18N btnSolverRefresh.setToolTipText(resourceMap.getString("btnSolverRefresh.toolTipText")); // NOI18N btnSolverRefresh.setName("btnSolverRefresh"); // NOI18N btnSolverRefresh.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnSolverRefreshActionPerformed(evt); } }); btnSolverExport.setText(resourceMap.getString("exportSolver.text")); // NOI18N btnSolverExport.setToolTipText(resourceMap.getString("exportSolver.toolTipText")); // NOI18N btnSolverExport.setName("exportSolver"); // NOI18N btnSolverExport.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnExport(evt); } }); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup() .addContainerGap() .addComponent(btnSolverRefresh) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 495, Short.MAX_VALUE) .addComponent(btnSolverExport, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(btnSolverSaveToDB) .addContainerGap()) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnSolverRefresh) .addComponent(btnSolverSaveToDB) .addComponent(btnSolverExport)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); javax.swing.GroupLayout panelManageDBSolverLayout = new javax.swing.GroupLayout(panelManageDBSolver); panelManageDBSolver.setLayout(panelManageDBSolverLayout); panelManageDBSolverLayout.setHorizontalGroup( panelManageDBSolverLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panelManageDBSolverLayout.createSequentialGroup() .addContainerGap() .addGroup(panelManageDBSolverLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel3, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jSplitPane2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 798, Short.MAX_VALUE)) .addContainerGap()) ); panelManageDBSolverLayout.setVerticalGroup( panelManageDBSolverLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelManageDBSolverLayout.createSequentialGroup() .addContainerGap() .addComponent(jSplitPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 488, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); manageDBPane.addTab("Solvers", panelManageDBSolver); panelManageDBInstances.setName("panelManageDBInstances"); // NOI18N panelManageDBInstances.setPreferredSize(new java.awt.Dimension(0, 0)); jSplitPane1.setDividerLocation(0.6); jSplitPane1.setResizeWeight(0.4); jSplitPane1.setName("jSplitPane1"); // NOI18N panelInstanceClass.setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("panelInstanceClass.border.title"))); // NOI18N panelInstanceClass.setName("panelInstanceClass"); // NOI18N panelInstanceClass.setPreferredSize(new java.awt.Dimension(0, 0)); panelButtonsInstanceClass.setName("panelButtonsInstanceClass"); // NOI18N btnNewInstanceClass.setText(resourceMap.getString("btnNewInstanceClass.text")); // NOI18N btnNewInstanceClass.setToolTipText(resourceMap.getString("btnNewInstanceClass.toolTipText")); // NOI18N btnNewInstanceClass.setName("btnNewInstanceClass"); // NOI18N btnNewInstanceClass.setPreferredSize(new java.awt.Dimension(89, 25)); btnNewInstanceClass.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnNewInstanceClassActionPerformed(evt); } }); btnEditInstanceClass.setText(resourceMap.getString("btnEditInstanceClass.text")); // NOI18N btnEditInstanceClass.setToolTipText(resourceMap.getString("btnEditInstanceClass.toolTipText")); // NOI18N btnEditInstanceClass.setEnabled(false); btnEditInstanceClass.setName("btnEditInstanceClass"); // NOI18N btnEditInstanceClass.setPreferredSize(new java.awt.Dimension(89, 25)); btnEditInstanceClass.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnEditInstanceClassActionPerformed(evt); } }); btnRemoveInstanceClass.setText(resourceMap.getString("btnRemoveInstanceClass.text")); // NOI18N btnRemoveInstanceClass.setToolTipText(resourceMap.getString("btnRemoveInstanceClass.toolTipText")); // NOI18N btnRemoveInstanceClass.setEnabled(false); btnRemoveInstanceClass.setName("btnRemoveInstanceClass"); // NOI18N btnRemoveInstanceClass.setPreferredSize(new java.awt.Dimension(89, 25)); btnRemoveInstanceClass.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnRemoveInstanceClassActionPerformed(evt); } }); btnExportInstanceClass.setText(resourceMap.getString("btnExportInstanceClass.text")); // NOI18N btnExportInstanceClass.setName("btnExportInstanceClass"); // NOI18N btnExportInstanceClass.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnExportInstanceClassActionPerformed(evt); } }); javax.swing.GroupLayout panelButtonsInstanceClassLayout = new javax.swing.GroupLayout(panelButtonsInstanceClass); panelButtonsInstanceClass.setLayout(panelButtonsInstanceClassLayout); panelButtonsInstanceClassLayout.setHorizontalGroup( panelButtonsInstanceClassLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panelButtonsInstanceClassLayout.createSequentialGroup() .addContainerGap() .addComponent(btnNewInstanceClass, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(btnEditInstanceClass, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(btnRemoveInstanceClass, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(btnExportInstanceClass) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); panelButtonsInstanceClassLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btnEditInstanceClass, btnExportInstanceClass, btnNewInstanceClass, btnRemoveInstanceClass}); panelButtonsInstanceClassLayout.setVerticalGroup( panelButtonsInstanceClassLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panelButtonsInstanceClassLayout.createSequentialGroup() .addContainerGap() .addGroup(panelButtonsInstanceClassLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnNewInstanceClass, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnEditInstanceClass, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnRemoveInstanceClass, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnExportInstanceClass)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); panelButtonsInstanceClassLayout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {btnEditInstanceClass, btnExportInstanceClass, btnNewInstanceClass, btnRemoveInstanceClass}); panelInstanceClassTable.setToolTipText(resourceMap.getString("panelInstanceClassTable.toolTipText")); // NOI18N panelInstanceClassTable.setName("panelInstanceClassTable"); // NOI18N jTreeInstanceClass.setName("jTreeInstanceClass"); // NOI18N panelInstanceClassTable.setViewportView(jTreeInstanceClass); javax.swing.GroupLayout panelInstanceClassLayout = new javax.swing.GroupLayout(panelInstanceClass); panelInstanceClass.setLayout(panelInstanceClassLayout); panelInstanceClassLayout.setHorizontalGroup( panelInstanceClassLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelInstanceClassLayout.createSequentialGroup() .addContainerGap() .addGroup(panelInstanceClassLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(panelButtonsInstanceClass, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(panelInstanceClassTable, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 416, Short.MAX_VALUE)) .addContainerGap()) ); panelInstanceClassLayout.setVerticalGroup( panelInstanceClassLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelInstanceClassLayout.createSequentialGroup() .addComponent(panelInstanceClassTable, javax.swing.GroupLayout.DEFAULT_SIZE, 399, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(panelButtonsInstanceClass, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); jSplitPane1.setLeftComponent(panelInstanceClass); panelInstance.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("panelInstance.border.border.title")))); // NOI18N panelInstance.setName("panelInstance"); // NOI18N panelInstance.setPreferredSize(new java.awt.Dimension(0, 0)); panelInstanceTable.setName("panelInstanceTable"); // NOI18N tableInstances.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null, null}, {null, null, null, null, null}, {null, null, null, null, null}, {null, null, null, null, null}, {null, null, null, null, null} }, new String [] { "Name", "numAtoms", "numClauses", "ratio", "maxClauseLength" } )); tableInstances.setToolTipText(resourceMap.getString("tableInstances.toolTipText")); // NOI18N tableInstances.setMaximumSize(new java.awt.Dimension(2147483647, 8000)); tableInstances.setName("tableInstances"); // NOI18N tableInstances.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { tableInstancesMouseClicked(evt); } public void mousePressed(java.awt.event.MouseEvent evt) { tableInstancesMousePressed(evt); } }); panelInstanceTable.setViewportView(tableInstances); tableInstances.getColumnModel().getColumn(0).setHeaderValue(resourceMap.getString("tableInstances.columnModel.title0")); // NOI18N tableInstances.getColumnModel().getColumn(1).setHeaderValue(resourceMap.getString("tableInstances.columnModel.title1")); // NOI18N tableInstances.getColumnModel().getColumn(2).setHeaderValue(resourceMap.getString("tableInstances.columnModel.title2")); // NOI18N tableInstances.getColumnModel().getColumn(3).setHeaderValue(resourceMap.getString("tableInstances.columnModel.title3")); // NOI18N tableInstances.getColumnModel().getColumn(4).setHeaderValue(resourceMap.getString("tableInstances.columnModel.title4")); // NOI18N panelButtonsInstances.setName("panelButtonsInstances"); // NOI18N btnAddInstances.setText(resourceMap.getString("btnAddInstances.text")); // NOI18N btnAddInstances.setToolTipText(resourceMap.getString("btnAddInstances.toolTipText")); // NOI18N btnAddInstances.setName("btnAddInstances"); // NOI18N btnAddInstances.setPreferredSize(new java.awt.Dimension(83, 25)); btnAddInstances.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnAddInstancesActionPerformed(evt); } }); btnRemoveInstances.setText(resourceMap.getString("btnRemoveInstances.text")); // NOI18N btnRemoveInstances.setToolTipText(resourceMap.getString("btnRemoveInstances.toolTipText")); // NOI18N btnRemoveInstances.setEnabled(false); btnRemoveInstances.setName("btnRemoveInstances"); // NOI18N btnRemoveInstances.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnRemoveInstancesActionPerformed(evt); } }); btnExportInstances.setText(resourceMap.getString("btnExportInstances.text")); // NOI18N btnExportInstances.setToolTipText(resourceMap.getString("btnExportInstances.toolTipText")); // NOI18N btnExportInstances.setEnabled(false); btnExportInstances.setName("btnExportInstances"); // NOI18N btnExportInstances.setPreferredSize(new java.awt.Dimension(83, 25)); btnExportInstances.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnExportInstancesActionPerformed(evt); } }); btnAddToClass.setText(resourceMap.getString("btnAddToClass.text")); // NOI18N btnAddToClass.setToolTipText(resourceMap.getString("btnAddToClass.toolTipText")); // NOI18N btnAddToClass.setEnabled(false); btnAddToClass.setName("btnAddToClass"); // NOI18N btnAddToClass.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnAddToClassActionPerformed(evt); } }); btnRemoveFromClass.setToolTipText(resourceMap.getString("btnRemoveFromClass.toolTipText")); // NOI18N btnRemoveFromClass.setActionCommand(resourceMap.getString("btnRemoveFromClass.actionCommand")); // NOI18N btnRemoveFromClass.setEnabled(false); btnRemoveFromClass.setLabel(resourceMap.getString("btnRemoveFromClass.label")); // NOI18N btnRemoveFromClass.setName("btnRemoveFromClass"); // NOI18N btnRemoveFromClass.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnRemoveFromClassActionPerformed(evt); } }); btnAddInstances1.setText(resourceMap.getString("btnAddInstances1.text")); // NOI18N btnAddInstances1.setToolTipText(resourceMap.getString("btnAddInstances1.toolTipText")); // NOI18N btnAddInstances1.setName("btnAddInstances1"); // NOI18N btnAddInstances1.setPreferredSize(new java.awt.Dimension(83, 25)); btnAddInstances1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnAddInstances1ActionPerformed(evt); } }); bComputeProperty.setText(resourceMap.getString("bComputeProperty.text")); // NOI18N bComputeProperty.setName("bComputeProperty"); // NOI18N bComputeProperty.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { bComputePropertyActionPerformed(evt); } }); btnGenerate.setText(resourceMap.getString("btnGenerateInstances.text")); // NOI18N btnGenerate.setName("btnGenerateInstances"); // NOI18N btnGenerate.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnGenerateActionPerformed(evt); } }); javax.swing.GroupLayout panelButtonsInstancesLayout = new javax.swing.GroupLayout(panelButtonsInstances); panelButtonsInstances.setLayout(panelButtonsInstancesLayout); panelButtonsInstancesLayout.setHorizontalGroup( panelButtonsInstancesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panelButtonsInstancesLayout.createSequentialGroup() .addContainerGap() .addGroup(panelButtonsInstancesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panelButtonsInstancesLayout.createSequentialGroup() .addComponent(btnAddToClass, javax.swing.GroupLayout.PREFERRED_SIZE, 151, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(btnRemoveFromClass) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 60, Short.MAX_VALUE) .addComponent(bComputeProperty)) .addGroup(panelButtonsInstancesLayout.createSequentialGroup() .addComponent(btnAddInstances, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(btnRemoveInstances) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(btnAddInstances1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(btnGenerate) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 74, Short.MAX_VALUE) .addComponent(btnExportInstances, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap()) ); panelButtonsInstancesLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btnAddInstances, btnRemoveInstances}); panelButtonsInstancesLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btnAddToClass, btnRemoveFromClass}); panelButtonsInstancesLayout.setVerticalGroup( panelButtonsInstancesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panelButtonsInstancesLayout.createSequentialGroup() .addContainerGap() .addGroup(panelButtonsInstancesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnAddInstances, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnRemoveInstances) .addComponent(btnExportInstances, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnAddInstances1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnGenerate)) .addGap(18, 18, 18) .addGroup(panelButtonsInstancesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnAddToClass) .addComponent(btnRemoveFromClass) .addComponent(bComputeProperty)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); lblFilterStatus.setText(resourceMap.getString("lblFilterStatus.text")); // NOI18N lblFilterStatus.setName("lblFilterStatus"); // NOI18N btnFilterInstances.setText(resourceMap.getString("btnFilterInstances.text")); // NOI18N btnFilterInstances.setToolTipText(resourceMap.getString("btnFilterInstances.toolTipText")); // NOI18N btnFilterInstances.setName("btnFilterInstances"); // NOI18N btnFilterInstances.setPreferredSize(new java.awt.Dimension(83, 25)); btnFilterInstances.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnFilterInstancesActionPerformed(evt); } }); btnSelectInstanceColumns.setText(resourceMap.getString("btnSelectInstanceColumns.text")); // NOI18N btnSelectInstanceColumns.setName("btnSelectInstanceColumns"); // NOI18N btnSelectInstanceColumns.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnSelectInstanceColumnsActionPerformed(evt); } }); javax.swing.GroupLayout panelInstanceLayout = new javax.swing.GroupLayout(panelInstance); panelInstance.setLayout(panelInstanceLayout); panelInstanceLayout.setHorizontalGroup( panelInstanceLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panelInstanceLayout.createSequentialGroup() .addContainerGap() .addGroup(panelInstanceLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(panelInstanceTable, javax.swing.GroupLayout.DEFAULT_SIZE, 543, Short.MAX_VALUE) .addGroup(panelInstanceLayout.createSequentialGroup() .addComponent(btnFilterInstances, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(panelInstanceLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lblFilterStatus, javax.swing.GroupLayout.DEFAULT_SIZE, 448, Short.MAX_VALUE) .addComponent(btnSelectInstanceColumns, javax.swing.GroupLayout.Alignment.TRAILING))) .addGroup(panelInstanceLayout.createSequentialGroup() .addComponent(panelButtonsInstances, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()))) ); panelInstanceLayout.setVerticalGroup( panelInstanceLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panelInstanceLayout.createSequentialGroup() .addComponent(lblFilterStatus) .addGroup(panelInstanceLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnSelectInstanceColumns) .addComponent(btnFilterInstances, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(panelInstanceTable, javax.swing.GroupLayout.DEFAULT_SIZE, 333, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(panelButtonsInstances, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) ); panelInstanceLayout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {btnFilterInstances, btnSelectInstanceColumns}); jSplitPane1.setRightComponent(panelInstance); javax.swing.GroupLayout panelManageDBInstancesLayout = new javax.swing.GroupLayout(panelManageDBInstances); panelManageDBInstances.setLayout(panelManageDBInstancesLayout); panelManageDBInstancesLayout.setHorizontalGroup( panelManageDBInstancesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelManageDBInstancesLayout.createSequentialGroup() .addContainerGap() .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 964, Short.MAX_VALUE) .addContainerGap()) ); panelManageDBInstancesLayout.setVerticalGroup( panelManageDBInstancesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panelManageDBInstancesLayout.createSequentialGroup() .addContainerGap() .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 500, Short.MAX_VALUE)) ); manageDBPane.addTab("Instances", panelManageDBInstances); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(manageDBPane, javax.swing.GroupLayout.DEFAULT_SIZE, 834, Short.MAX_VALUE) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(manageDBPane, javax.swing.GroupLayout.DEFAULT_SIZE, 552, Short.MAX_VALUE) .addContainerGap()) ); }// </editor-fold>//GEN-END:initComponents public void btnAddInstancesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddInstancesActionPerformed //Starts the dialog at which the user has to choose a instance source class or the autogeneration. try { if (addInstanceDialog == null) { JFrame mainFrame = EDACCApp.getApplication().getMainFrame(); this.addInstanceDialog = new EDACCAddNewInstanceSelectClassDialog(mainFrame, true, null); this.addInstanceDialog.setLocationRelativeTo(mainFrame); } else{ addInstanceDialog.refresh(); } EDACCApp.getApplication().show(this.addInstanceDialog); Boolean compress = this.addInstanceDialog.isCompress(); InstanceClass input = this.addInstanceDialog.getInput(); String fileExtension = this.addInstanceDialog.getFileExtension(); Boolean autoClass = this.addInstanceDialog.isAutoClass(); //If the user doesn't cancel the dialog above, the fileChooser is shown. if (input != null) { if (fileExtension.isEmpty()) { JOptionPane.showMessageDialog(panelManageDBInstances, "No fileextension is given.", "Warning", JOptionPane.WARNING_MESSAGE); return; } //When the user choos autogenerate only directorys can be choosen, else files and directorys. if (input.getName().equals("")) { jFileChooserManageDBInstance.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); } else { jFileChooserManageDBInstance.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); } int returnVal = jFileChooserManageDBInstance.showOpenDialog(panelManageDBInstances); File ret = jFileChooserManageDBInstance.getSelectedFile(); if (returnVal == JFileChooser.APPROVE_OPTION) { Tasks.startTask("addInstances", new Class[]{edacc.model.InstanceClass.class, java.io.File.class, edacc.model.Tasks.class, String.class, Boolean.class, Boolean.class}, new Object[]{input, ret, null, fileExtension, compress, autoClass}, manageDBInstances, EDACCManageDBMode.this); } } input = null; unsavedChanges = true; } catch (NoConnectionToDBException ex) { Logger.getLogger(EDACCManageDBMode.class.getName()).log(Level.SEVERE, null, ex); } catch (SQLException ex) { Logger.getLogger(EDACCManageDBMode.class.getName()).log(Level.SEVERE, null, ex); } jTreeInstanceClass.clearSelection(); tableInstances.clearSelection(); this.instanceClassTreeModel.reload(); this.instanceTableModel.fireTableDataChanged(); }//GEN-LAST:event_btnAddInstancesActionPerformed private void btnRemoveInstancesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRemoveInstancesActionPerformed if (tableInstances.getSelectedRows().length == 0) { JOptionPane.showMessageDialog(panelManageDBInstances, "No instances selected.", "Warning", JOptionPane.WARNING_MESSAGE); } else { try { manageDBInstances.removeInstances(tableInstances.getSelectedRows()); tableInstances.clearSelection(); instanceTableModel.fireTableDataChanged(); } catch (NoConnectionToDBException ex) { Logger.getLogger(EDACCManageDBMode.class.getName()).log(Level.SEVERE, null, ex); } catch (SQLException ex) { Logger.getLogger(EDACCManageDBMode.class.getName()).log(Level.SEVERE, null, ex); } } this.tableInstances.requestFocus(); }//GEN-LAST:event_btnRemoveInstancesActionPerformed private void btnFilterInstancesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnFilterInstancesActionPerformed EDACCApp.getApplication().show(instanceFilter); instanceTableModel.fireTableDataChanged(); if (instanceFilter.hasFiltersApplied()) { setFilterStatus("This list of instances has filters applied to it. Use the filter button below to modify."); } else { setFilterStatus(""); } }//GEN-LAST:event_btnFilterInstancesActionPerformed private void btnSolverSaveToDBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSolverSaveToDBActionPerformed manageDBSolvers.saveSolvers(); unsavedChanges = false; }//GEN-LAST:event_btnSolverSaveToDBActionPerformed private void btnSolverNewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSolverNewActionPerformed manageDBSolvers.newSolver(); tableSolver.getSelectionModel().setSelectionInterval(tableSolver.getRowCount() - 1, tableSolver.getRowCount() - 1); tableSolver.updateUI(); unsavedChanges = true; tfSolverName.requestFocus(); }//GEN-LAST:event_btnSolverNewActionPerformed JFileChooser binaryFileChooser; private void btnSolverAddBinaryActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSolverAddBinaryActionPerformed try { if (binaryFileChooser == null) { binaryFileChooser = new JFileChooser(); binaryFileChooser.setMultiSelectionEnabled(true); binaryFileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); } if (binaryFileChooser.showDialog(this, "Add Solver Binaries") == JFileChooser.APPROVE_OPTION) { manageDBSolvers.addSolverBinary(binaryFileChooser.getSelectedFiles()); unsavedChanges = true; } } catch (FileNotFoundException ex) { ex.printStackTrace(); JOptionPane.showMessageDialog(panelManageDBInstances, "The binary of the solver couldn't be found: " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } catch (Exception ex) { ex.printStackTrace(); JOptionPane.showMessageDialog(panelManageDBInstances, "An error occured while adding the binary of the solver: " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } tableSolver.updateUI(); }//GEN-LAST:event_btnSolverAddBinaryActionPerformed private void btnParametersNewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnParametersNewActionPerformed manageDBParameters.newParam(); tableParameters.getSelectionModel().setSelectionInterval(tableParameters.getRowCount() - 1, tableParameters.getRowCount() - 1); tableParameters.updateUI(); unsavedChanges = true; this.tfParametersName.requestFocus(); }//GEN-LAST:event_btnParametersNewActionPerformed /** * Handles the key released events of the textfields "solver name" and "solver description". * @param evt */ private void solverChangedOnKey(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_solverChangedOnKey solverChanged(); }//GEN-LAST:event_solverChangedOnKey /** * Applies the solver name and description and updates the UI of the table. */ private void solverChanged() { manageDBSolvers.applySolver(tfSolverName.getText(), taSolverDescription.getText(), tfSolverAuthors.getText(), tfSolverVersion.getText()); tableSolver.updateUI(); unsavedChanges = true; } private JFileChooser codeFileChooser; private void btnSolverAddCodeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSolverAddCodeActionPerformed try { if (codeFileChooser == null) { codeFileChooser = new JFileChooser(); codeFileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); codeFileChooser.setMultiSelectionEnabled(true); } if (codeFileChooser.showDialog(this, "Choose code") == JFileChooser.APPROVE_OPTION) { manageDBSolvers.addSolverCode(codeFileChooser.getSelectedFiles()); unsavedChanges = true; } } catch (FileNotFoundException ex) { JOptionPane.showMessageDialog(panelManageDBInstances, "The code of the solver couldn't be found: " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } tableSolver.updateUI(); }//GEN-LAST:event_btnSolverAddCodeActionPerformed /** * Handles the focus lost event of the solver textfields "name" and "description". * @param evt */ private void solverChangedOnFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_solverChangedOnFocusLost solverChanged(); }//GEN-LAST:event_solverChangedOnFocusLost private void btnSolverDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSolverDeleteActionPerformed // show warning first final int userAnswer = JOptionPane.showConfirmDialog(panelSolver, "The selected solvers will be deleted. Do you wish to continue?", "Delete selected solvers", JOptionPane.YES_NO_OPTION); if (userAnswer == JOptionPane.NO_OPTION) { return; } int[] rows = tableSolver.getSelectedRows(); LinkedList<Solver> selectedSolvers = new LinkedList<Solver>(); int lastSelectedIndex = -1; for (int i : rows) { selectedSolvers.add(solverTableModel.getSolver(tableSolver.convertRowIndexToModel(i))); lastSelectedIndex = i; } if (selectedSolvers.isEmpty()) { JOptionPane.showMessageDialog(panelSolver, "No solver selected!", "Warning", JOptionPane.WARNING_MESSAGE); } else { while (!selectedSolvers.isEmpty()) { // are there remaining solvers to delete? try { Solver s = selectedSolvers.removeFirst(); manageDBSolvers.removeSolver(s); } catch (Exception ex) { JOptionPane.showMessageDialog(this, "An error occured while deleting a solver: " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } finally { tableSolver.getSelectionModel().clearSelection(); solverTableModel.fireTableDataChanged(); tableSolver.updateUI(); tableParameters.updateUI(); // try to select the solver which stood one row over the last deleted solver if (lastSelectedIndex >= tableSolver.getRowCount()) { lastSelectedIndex = tableSolver.getRowCount() - 1; } if (lastSelectedIndex >= 0) { tableSolver.getSelectionModel().setSelectionInterval(lastSelectedIndex, lastSelectedIndex); } } } } tfSolverName.setText(""); taSolverDescription.setText(""); tfSolverAuthors.setText(""); tfSolverVersion.setText(""); }//GEN-LAST:event_btnSolverDeleteActionPerformed private void btnExportInstancesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExportInstancesActionPerformed if (tableInstances.getSelectedRowCount() == 0) { JOptionPane.showMessageDialog(panelManageDBInstances, "No instances are selected. ", "Error", JOptionPane.ERROR_MESSAGE); } else { int returnVal = jFileChooserManageDBExportInstance.showOpenDialog(panelManageDBInstances); String path = jFileChooserManageDBExportInstance.getSelectedFile().getAbsolutePath(); Tasks.startTask("exportInstances", new Class[]{int[].class, String.class, edacc.model.Tasks.class}, new Object[]{tableInstances.getSelectedRows(), path, null}, manageDBInstances, EDACCManageDBMode.this); } }//GEN-LAST:event_btnExportInstancesActionPerformed private void btnEditInstanceClassActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditInstanceClassActionPerformed if (jTreeInstanceClass.getSelectionCount() == 0) { JOptionPane.showMessageDialog(panelManageDBInstances, "Please select an instance class to edit!", "Warning", JOptionPane.WARNING_MESSAGE); } else if (jTreeInstanceClass.getSelectionCount() > 1) { JOptionPane.showMessageDialog(panelManageDBInstances, "Please select only one instance class to edit!", "Warning", JOptionPane.WARNING_MESSAGE); } else { try { manageDBInstances.editInstanceClass(); this.manageDBInstances.loadInstanceClasses(); } catch (SQLException ex) { Logger.getLogger(EDACCManageDBMode.class.getName()).log(Level.SEVERE, null, ex); } } }//GEN-LAST:event_btnEditInstanceClassActionPerformed private void btnParametersDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnParametersDeleteActionPerformed if (tableParameters.getSelectedRow() == -1) { JOptionPane.showMessageDialog(this, "No parameters selected!", "Warning", JOptionPane.WARNING_MESSAGE); return; } int selectedIndex = tableParameters.getSelectedRow(); Parameter p = parameterTableModel.getParameter(tableParameters.convertRowIndexToModel(selectedIndex)); try { manageDBParameters.removeParameter(p); } catch (NoConnectionToDBException ex) { JOptionPane.showMessageDialog(panelManageDBInstances, "No connection to database: " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } catch (SQLException ex) { JOptionPane.showMessageDialog(panelManageDBInstances, "SQL-Exception while deleting parameter: " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } // try select the parameter which stood on row over the deleted param if (selectedIndex >= tableParameters.getRowCount()) { selectedIndex--; } Parameter selected = null; tableParameters.clearSelection(); if (selectedIndex >= 0) { selected = parameterTableModel.getParameter(tableParameters.convertRowIndexToModel(selectedIndex)); tableParameters.getSelectionModel().setSelectionInterval(selectedIndex, selectedIndex); } showParameterDetails( selected); tableParameters.updateUI(); }//GEN-LAST:event_btnParametersDeleteActionPerformed private void btnSolverRefreshActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSolverRefreshActionPerformed //if (this.unsavedChanges) if ((JOptionPane.showConfirmDialog(this, "This will reload all data from DB. You are going to lose all your unsaved changes. Do you wish to continue?", "Warning!", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE) == JOptionPane.YES_OPTION)) { try { int row = tableSolver.getSelectedRow(); manageDBSolvers.loadSolvers(); manageDBParameters.loadParametersOfSolvers(solverTableModel.getSolvers()); tableSolver.updateUI(); panelSolverOverall.updateUI(); tableParameters.updateUI(); tableSolver.clearSelection(); unsavedChanges = false; } catch (NoConnectionToDBException ex) { JOptionPane.showMessageDialog(panelManageDBInstances, "No connection to database: " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } catch (SQLException ex) { JOptionPane.showMessageDialog(panelManageDBInstances, "SQL-Exception while refreshing tables: " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } } }//GEN-LAST:event_btnSolverRefreshActionPerformed private void btnNewInstanceClassActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNewInstanceClassActionPerformed saveExpandedState(); jTreeInstanceClass.setSelectionPath(null); manageDBInstances.addInstanceClasses(); manageDBInstances.UpdateInstanceClasses(); jTreeInstanceClass.setExpandsSelectedPaths(true); restoreExpandedState(); /*tableInstanceClass.updateUI(); unsavedChanges = true;*/ }//GEN-LAST:event_btnNewInstanceClassActionPerformed private void parameterChangedOnFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_parameterChangedOnFocusLost parameterChanged(); }//GEN-LAST:event_parameterChangedOnFocusLost private void btnAddToClassActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddToClassActionPerformed try { int[] selectedRowsInstance = tableInstances.getSelectedRows(); for (int i = 0; i < selectedRowsInstance.length; i++) { selectedRowsInstance[i] = tableInstances.convertRowIndexToModel(selectedRowsInstance[i]); } manageDBInstances.addInstancesToClass(selectedRowsInstance); unsavedChanges = true; tableInstances.requestFocus(); if (instanceTableModel.getRowCount() != 0) { tableInstances.addRowSelectionInterval(0, 0); } } catch (IOException ex) { Logger.getLogger(EDACCManageDBMode.class.getName()).log(Level.SEVERE, null, ex); } }//GEN-LAST:event_btnAddToClassActionPerformed private void btnRemoveFromClassActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRemoveFromClassActionPerformed manageDBInstances.RemoveInstanceFromInstanceClass(tableInstances.getSelectedRows(), jTreeInstanceClass.getSelectionPaths()); this.instanceTableModel.fireTableDataChanged(); }//GEN-LAST:event_btnRemoveFromClassActionPerformed private JFileChooser exportFileChooser; private void btnExport(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExport if (exportFileChooser == null) { exportFileChooser = new JFileChooser(); exportFileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); } if (exportFileChooser.showDialog(this, "Export code and binary of selected solvers to directory") == JFileChooser.APPROVE_OPTION) { int[] rows = tableSolver.getSelectedRows(); for (int i : rows) { try { manageDBSolvers.exportSolver(solverTableModel.getSolver(tableSolver.convertRowIndexToModel(i)), exportFileChooser.getSelectedFile()); manageDBSolvers.exportSolverCode(solverTableModel.getSolver(tableSolver.convertRowIndexToModel(i)), exportFileChooser.getSelectedFile()); } catch (Exception ex) { JOptionPane.showMessageDialog(this, "An error occured while exporting solver \"" + solverTableModel.getSolver(tableSolver.convertRowIndexToModel(i)).getName() + "\": " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } } } }//GEN-LAST:event_btnExport private void parameterChangedOnKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_parameterChangedOnKeyReleased parameterChanged(); }//GEN-LAST:event_parameterChangedOnKeyReleased private void chkHasNoValueStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_chkHasNoValueStateChanged parameterChanged(); }//GEN-LAST:event_chkHasNoValueStateChanged private void tableInstancesMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tableInstancesMouseClicked }//GEN-LAST:event_tableInstancesMouseClicked private void btnRemoveInstanceClassActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRemoveInstanceClassActionPerformed if (jTreeInstanceClass.getSelectionCount() == 0) { JOptionPane.showMessageDialog(panelManageDBInstances, "No instance class selected.", "Warning", JOptionPane.WARNING_MESSAGE); } else { try { manageDBInstances.RemoveInstanceClass((DefaultMutableTreeNode) jTreeInstanceClass.getSelectionPath().getLastPathComponent()); tableInstances.clearSelection(); instanceTableModel.fireTableDataChanged(); } catch (InstanceIsInExperimentException ex) { Logger.getLogger(EDACCManageDBMode.class.getName()).log(Level.SEVERE, null, ex); //instanceClassTableModel.fireTableDataChanged(); ; } catch (NoConnectionToDBException ex) { Logger.getLogger(EDACCManageDBMode.class.getName()).log(Level.SEVERE, null, ex); } catch (InstanceSourceClassHasInstance ex) { JOptionPane.showMessageDialog(panelManageDBInstances, "The selected instance class cannot be removed. Because it is a source class with" + " related instances.", "Error", JOptionPane.ERROR_MESSAGE); } catch (SQLException ex) { Logger.getLogger(EDACCManageDBMode.class.getName()).log(Level.SEVERE, null, ex); } } }//GEN-LAST:event_btnRemoveInstanceClassActionPerformed private void tableInstancesMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tableInstancesMousePressed }//GEN-LAST:event_tableInstancesMousePressed private void btnAddInstances1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddInstances1ActionPerformed if (this.tableInstances.getSelectedRowCount() == 0) { JOptionPane.showMessageDialog(panelManageDBInstances, "No instances selected.", "Warning", JOptionPane.WARNING_MESSAGE); return; } this.manageDBInstances.showInstanceInfoDialog(this.tableInstances.getSelectedRows()); }//GEN-LAST:event_btnAddInstances1ActionPerformed private EDACCComputeInstancePropertyDialog computeInstancePropertyDlg; private void bComputePropertyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bComputePropertyActionPerformed Vector<Instance> instances = new Vector<Instance>(); for (int i : tableInstances.getSelectedRows()) { instances.add(instanceTableModel.getInstance(i)); } computeInstancePropertyDlg = new EDACCComputeInstancePropertyDialog(EDACCApp.getApplication().getMainFrame(), manageDBInstances, instances); computeInstancePropertyDlg.setLocationRelativeTo(this); computeInstancePropertyDlg.setVisible(true); }//GEN-LAST:event_bComputePropertyActionPerformed private void btnGenerateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGenerateActionPerformed if (instanceGenKCNF == null) { JFrame mainFrame = EDACCApp.getApplication().getMainFrame(); this.instanceGenKCNF = new EDACCInstanceGeneratorUnifKCNF(mainFrame, true); this.instanceGenKCNF.setLocationRelativeTo(mainFrame); } EDACCApp.getApplication().show(this.instanceGenKCNF); try { manageDBInstances.loadInstanceClasses(); jTreeInstanceClass.updateUI(); //try { /* } catch (NoConnectionToDBException ex) { Logger.getLogger(EDACCManageDBMode.class.getName()).log(Level.SEVERE, null, ex); } catch (SQLException ex) { Logger.getLogger(EDACCManageDBMode.class.getName()).log(Level.SEVERE, null, ex); }*/ } catch (SQLException ex) { Logger.getLogger(EDACCManageDBMode.class.getName()).log(Level.SEVERE, null, ex); } //try { /* } catch (NoConnectionToDBException ex) { Logger.getLogger(EDACCManageDBMode.class.getName()).log(Level.SEVERE, null, ex); } catch (SQLException ex) { Logger.getLogger(EDACCManageDBMode.class.getName()).log(Level.SEVERE, null, ex); }*/ }//GEN-LAST:event_btnGenerateActionPerformed private void btnExportInstanceClassActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExportInstanceClassActionPerformed if (jTreeInstanceClass.getSelectionCount() == 0) { JOptionPane.showMessageDialog(panelManageDBInstances, "No instance class selected.", "Warning", JOptionPane.WARNING_MESSAGE); return; } else if (jTreeInstanceClass.getSelectionCount() > 1) { JOptionPane.showMessageDialog(panelManageDBInstances, "Only select one instance class to export.", "Warning", JOptionPane.WARNING_MESSAGE); return; } else { int returnVal = jFileChooserManageDBExportInstance.showOpenDialog(panelManageDBInstances); String path = jFileChooserManageDBExportInstance.getSelectedFile().getAbsolutePath(); Tasks.startTask("exportInstanceClass", new Class[]{DefaultMutableTreeNode.class, String.class, edacc.model.Tasks.class}, new Object[]{(DefaultMutableTreeNode) jTreeInstanceClass.getSelectionPath().getLastPathComponent(), path, null}, manageDBInstances, EDACCManageDBMode.this); } }//GEN-LAST:event_btnExportInstanceClassActionPerformed private void jMIAddInstanceActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMIAddInstanceActionPerformed btnAddInstancesActionPerformed(evt); }//GEN-LAST:event_jMIAddInstanceActionPerformed private void jMIRemoveInstanceActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMIRemoveInstanceActionPerformed btnRemoveInstancesActionPerformed(evt); }//GEN-LAST:event_jMIRemoveInstanceActionPerformed private void jMIExportInstanceActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMIExportInstanceActionPerformed btnExportInstancesActionPerformed(evt); }//GEN-LAST:event_jMIExportInstanceActionPerformed private void jMINewInstanceClassActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMINewInstanceClassActionPerformed btnNewInstanceClassActionPerformed(evt); }//GEN-LAST:event_jMINewInstanceClassActionPerformed private void jMIEditInstanceClassActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMIEditInstanceClassActionPerformed btnEditInstanceClassActionPerformed(evt); }//GEN-LAST:event_jMIEditInstanceClassActionPerformed private void jMIRemoveInstanceClassActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMIRemoveInstanceClassActionPerformed btnRemoveInstanceClassActionPerformed(evt); }//GEN-LAST:event_jMIRemoveInstanceClassActionPerformed private void jMIExportInstanceClassActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMIExportInstanceClassActionPerformed btnExportInstanceClassActionPerformed(evt); }//GEN-LAST:event_jMIExportInstanceClassActionPerformed private void chkMandatoryStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_chkMandatoryStateChanged parameterChanged(); }//GEN-LAST:event_chkMandatoryStateChanged private void chkSpaceChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_chkSpaceChanged parameterChanged(); }//GEN-LAST:event_chkSpaceChanged private void btnSelectInstanceColumnsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSelectInstanceColumnsActionPerformed List<SortKey> sortKeys = (List<SortKey>) tableInstances.getRowSorter().getSortKeys(); List<String> columnNames = new ArrayList<String>(); for (SortKey sk : sortKeys) { columnNames.add(tableInstances.getColumnName(tableInstances.convertColumnIndexToView(sk.getColumn()))); } EDACCManageInstanceColumnSelection dialog = new EDACCManageInstanceColumnSelection(EDACCApp.getApplication().getMainFrame(), true, instanceTableModel); dialog.setLocationRelativeTo(EDACCApp.getApplication().getMainFrame()); dialog.setVisible(true); List<SortKey> newSortKeys = new ArrayList<SortKey>(); for (int k = 0; k < columnNames.size(); k++) { String col = columnNames.get(k); for (int i = 0; i < tableInstances.getColumnCount(); i++) { if (tableInstances.getColumnName(i).equals(col)) { newSortKeys.add(new SortKey(tableInstances.convertColumnIndexToModel(i), sortKeys.get(k).getSortOrder())); } } } tableInstances.getRowSorter().setSortKeys(newSortKeys); edacc.experiment.Util.updateTableColumnWidth(tableInstances); tableInstances.updateUI(); }//GEN-LAST:event_btnSelectInstanceColumnsActionPerformed private void btnSolverEditBinaryActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSolverEditBinaryActionPerformed }//GEN-LAST:event_btnSolverEditBinaryActionPerformed private void btnSolverDeleteBinaryActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSolverDeleteBinaryActionPerformed // show warning first final int userAnswer = JOptionPane.showConfirmDialog(panelSolver, "The selected solver binaries will be deleted. Do you wish to continue?", "Delete selected solver binaries", JOptionPane.YES_NO_OPTION); if (userAnswer == JOptionPane.NO_OPTION) { return; } int[] rows = tableSolverBinaries.getSelectedRows(); LinkedList<SolverBinaries> selectedSolverBinaries = new LinkedList<SolverBinaries>(); int lastSelectedIndex = -1; for (int i : rows) { selectedSolverBinaries.add(solverBinariesTableModel.getSolverBinaries(tableSolverBinaries.convertRowIndexToModel(i))); lastSelectedIndex = i; } if (selectedSolverBinaries.isEmpty()) { JOptionPane.showMessageDialog(panelSolver, "No solver binary selected!", "Warning", JOptionPane.WARNING_MESSAGE); } else { while (!selectedSolverBinaries.isEmpty()) { // are there remaining solvers to delete? try { SolverBinaries s = selectedSolverBinaries.removeFirst(); manageDBSolvers.removeSolverBinary(s); } catch (Exception ex) { JOptionPane.showMessageDialog(this, "An error occured while deleting a solver binary: " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } finally { tableSolverBinaries.getSelectionModel().clearSelection(); solverBinariesTableModel.fireTableDataChanged(); tableSolverBinaries.updateUI(); // try to select the solver which stood one row over the last deleted solver if (lastSelectedIndex >= tableSolverBinaries.getRowCount()) { lastSelectedIndex = tableSolverBinaries.getRowCount() - 1; } if (lastSelectedIndex >= 0) { tableSolverBinaries.getSelectionModel().setSelectionInterval(lastSelectedIndex, lastSelectedIndex); } } } } }//GEN-LAST:event_btnSolverDeleteBinaryActionPerformed private void chkAttachToPreviousStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_chkAttachToPreviousStateChanged parameterChanged(); }//GEN-LAST:event_chkAttachToPreviousStateChanged private void parameterChanged() { int selectedRow = tableParameters.getSelectedRow(); if (selectedRow == -1) { return; } selectedRow = tableParameters.convertRowIndexToModel(selectedRow); Parameter p = parameterTableModel.getParameter(selectedRow); p.setName(tfParametersName.getText()); try { p.setOrder(Integer.parseInt(tfParametersOrder.getText())); } catch (NumberFormatException e) { if (!tfParametersOrder.getText().equals("")) { tfParametersOrder.setText(Integer.toString(p.getOrder())); } } p.setDefaultValue(tfParametersDefaultValue.getText()); p.setPrefix(tfParametersPrefix.getText()); p.setHasValue(!chkHasNoValue.isSelected()); p.setMandatory(chkMandatory.isSelected()); p.setSpace(chkSpace.isSelected()); p.setAttachToPrevious(chkAttachToPrevious.isSelected()); tableParameters.updateUI(); unsavedChanges = true; // show error message if necessary tfParametersName.getInputVerifier().shouldYieldFocus(tfParametersName); } public void showSolverDetails(Solver currentSolver) { boolean enabled = false; if (currentSolver != null) { enabled = true; tfSolverName.setText(currentSolver.getName()); taSolverDescription.setText(currentSolver.getDescription()); tfSolverAuthors.setText(currentSolver.getAuthors()); tfSolverVersion.setText(currentSolver.getVersion()); manageDBParameters.setCurrentSolver(currentSolver); tableParameters.updateUI(); } else { tfSolverName.setText(""); taSolverDescription.setText(""); tfSolverAuthors.setText(""); tfSolverVersion.setText(""); manageDBParameters.setCurrentSolver(currentSolver); tableParameters.updateUI(); } jlSolverName.setEnabled(enabled); jlSolverDescription.setEnabled(enabled); jlSolverAuthors.setEnabled(enabled); jlSolverVersion.setEnabled(enabled); jlSolverBinary.setEnabled(enabled); jlSolverCode.setEnabled(enabled); tfSolverName.setEnabled(enabled); taSolverDescription.setEnabled(enabled); tfSolverAuthors.setEnabled(enabled); tfSolverVersion.setEnabled(enabled); btnSolverAddBinary.setEnabled(enabled); btnSolverEditBinary.setEnabled(false); // TODO implement btnSolverDeleteBinary.setEnabled(enabled); btnSolverAddCode.setEnabled(enabled); btnSolverExport.setEnabled(enabled); if (currentSolver != null) { parameterTableModel.setCurrentSolver(currentSolver); parameterTableModel.fireTableDataChanged(); } btnParametersNew.setEnabled(enabled); btnParametersDelete.setEnabled(enabled); tableParameters.getSelectionModel().clearSelection(); showParameterDetails( null); } public void showParameterDetails(Parameter currentParameter) { boolean enabled = false; if (currentParameter != null) { enabled = true; tfParametersName.setText(currentParameter.getName()); tfParametersOrder.setText(Integer.toString(currentParameter.getOrder())); tfParametersPrefix.setText(currentParameter.getPrefix()); tfParametersDefaultValue.setText(currentParameter.getDefaultValue()); chkHasNoValue.setSelected(!currentParameter.getHasValue()); chkMandatory.setSelected(currentParameter.isMandatory()); chkSpace.setSelected(currentParameter.getSpace()); chkAttachToPrevious.setSelected(currentParameter.isAttachToPrevious()); tfParametersName.getInputVerifier().shouldYieldFocus(tfParametersName); } else { tfParametersName.setText(""); tfParametersOrder.setText(""); tfParametersPrefix.setText(""); tfParametersDefaultValue.setText(""); chkHasNoValue.setSelected(false); chkMandatory.setSelected(false); chkSpace.setSelected(false); chkAttachToPrevious.setSelected(false); showInvalidParameterNameError(false); showInvalidParameterNameError(false); } tfParametersName.setEnabled(enabled); tfParametersPrefix.setEnabled(enabled); tfParametersOrder.setEnabled(enabled); tfParametersDefaultValue.setEnabled(enabled); chkHasNoValue.setEnabled(enabled); chkMandatory.setEnabled(enabled); chkSpace.setEnabled(enabled); chkAttachToPrevious.setEnabled(enabled); } @Action public void btnSaveParam() { if (tableParameters.getSelectedRow() == -1) { return; } Parameter p = parameterTableModel.getParameter(tableParameters.getSelectedRow()); p.setName(tfParametersName.getText()); p.setOrder(Integer.parseInt(tfParametersOrder.getText())); p.setPrefix(tfParametersPrefix.getText()); parameterTableModel.fireTableDataChanged(); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton bComputeProperty; private javax.swing.JButton btnAddInstances; private javax.swing.JButton btnAddInstances1; private javax.swing.JButton btnAddToClass; private javax.swing.JButton btnEditInstanceClass; private javax.swing.JButton btnExportInstanceClass; private javax.swing.JButton btnExportInstances; private javax.swing.JButton btnFilterInstances; private javax.swing.JButton btnGenerate; private javax.swing.JButton btnNewInstanceClass; private javax.swing.JButton btnParametersDelete; private javax.swing.JButton btnParametersNew; private javax.swing.JButton btnRemoveFromClass; private javax.swing.JButton btnRemoveInstanceClass; private javax.swing.JButton btnRemoveInstances; private javax.swing.JButton btnSelectInstanceColumns; private javax.swing.JButton btnSolverAddBinary; private javax.swing.JButton btnSolverAddCode; private javax.swing.JButton btnSolverDelete; private javax.swing.JButton btnSolverDeleteBinary; private javax.swing.JButton btnSolverEditBinary; private javax.swing.JButton btnSolverExport; private javax.swing.JButton btnSolverNew; private javax.swing.JButton btnSolverRefresh; private javax.swing.JButton btnSolverSaveToDB; private javax.swing.JCheckBox chkAttachToPrevious; private javax.swing.JCheckBox chkHasNoValue; private javax.swing.JCheckBox chkMandatory; private javax.swing.JCheckBox chkSpace; private javax.swing.JFileChooser jFileChooserManageDBExportInstance; private javax.swing.JFileChooser jFileChooserManageDBInstance; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JMenuItem jMIAddInstance; private javax.swing.JMenuItem jMIEditInstanceClass; private javax.swing.JMenuItem jMIExportInstance; private javax.swing.JMenuItem jMIExportInstanceClass; private javax.swing.JMenuItem jMINewInstanceClass; private javax.swing.JMenuItem jMIRemoveInstance; private javax.swing.JMenuItem jMIRemoveInstanceClass; private javax.swing.JPopupMenu jPMInstanceTable; private javax.swing.JPopupMenu jPMInstanceTreeInstanceClass; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JScrollPane jScrollPane3; private javax.swing.JScrollPane jScrollPane4; private javax.swing.JSplitPane jSplitPane1; private javax.swing.JSplitPane jSplitPane2; private javax.swing.JTree jTreeInstanceClass; private javax.swing.JLabel jlParametersDefaultValue; private javax.swing.JLabel jlParametersName; private javax.swing.JLabel jlParametersOrder; private javax.swing.JLabel jlParametersPrefix; private javax.swing.JLabel jlSolverAuthors; private javax.swing.JLabel jlSolverBinary; private javax.swing.JLabel jlSolverCode; private javax.swing.JLabel jlSolverDescription; private javax.swing.JLabel jlSolverName; private javax.swing.JLabel jlSolverVersion; private javax.swing.JLabel lMandatory; private javax.swing.JLabel lSpace; private javax.swing.JLabel lblFilterStatus; private javax.swing.JTabbedPane manageDBPane; private javax.swing.JPanel panelButtonsInstanceClass; private javax.swing.JPanel panelButtonsInstances; private javax.swing.JPanel panelInstance; private javax.swing.JPanel panelInstanceClass; private javax.swing.JScrollPane panelInstanceClassTable; private javax.swing.JScrollPane panelInstanceTable; private javax.swing.JPanel panelManageDBInstances; private javax.swing.JPanel panelManageDBSolver; private javax.swing.JPanel panelParameters; private javax.swing.JPanel panelParametersButons; private javax.swing.JPanel panelParametersOverall; private javax.swing.JPanel panelSolver; private javax.swing.JPanel panelSolverButtons; private javax.swing.JPanel panelSolverOverall; private javax.swing.JTextArea taSolverDescription; private javax.swing.JTable tableInstances; private javax.swing.JTable tableParameters; private javax.swing.JTable tableSolver; private javax.swing.JTable tableSolverBinaries; private javax.swing.JTextField tfParametersDefaultValue; private javax.swing.JTextField tfParametersName; private javax.swing.JTextField tfParametersOrder; private javax.swing.JTextField tfParametersPrefix; private javax.swing.JTextField tfSolverAuthors; private javax.swing.JTextField tfSolverName; private javax.swing.JTextField tfSolverVersion; // End of variables declaration//GEN-END:variables public void onTaskStart(String methodName) { } public void onTaskFailed(String methodName, Throwable e) { if (methodName.equals("exportInstanceClass")) { if (e instanceof IOException) { JOptionPane.showMessageDialog(panelManageDBInstances, "The instances couldn't be written: " + e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } else if (e instanceof NoConnectionToDBException) { JOptionPane.showMessageDialog(panelManageDBInstances, "No connection to database: " + e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } else if (e instanceof SQLException) { JOptionPane.showMessageDialog(panelManageDBInstances, "SQL-Exception: " + e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } else if (e instanceof InstanceNotInDBException) { JOptionPane.showMessageDialog(panelManageDBInstances, "There is a problem with the data consistency ", "Error", JOptionPane.ERROR_MESSAGE); } else if (e instanceof MD5CheckFailedException) { JOptionPane.showMessageDialog(panelManageDBInstances, e, "Error", JOptionPane.ERROR_MESSAGE); } else if (e instanceof NoSuchAlgorithmException) { JOptionPane.showMessageDialog(panelManageDBInstances, "An error occured while exporting solver binary: " + e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } } else if (methodName.equals("exportInstances")) { if (e instanceof IOException) { JOptionPane.showMessageDialog(panelManageDBInstances, "The instances couldn't be written: " + e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } else if (e instanceof NoConnectionToDBException) { JOptionPane.showMessageDialog(panelManageDBInstances, "No connection to database: " + e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } else if (e instanceof SQLException) { JOptionPane.showMessageDialog(panelManageDBInstances, "SQL-Exception: " + e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } else if (e instanceof InstanceNotInDBException) { JOptionPane.showMessageDialog(panelManageDBInstances, "There is a problem with the data consistency ", "Error", JOptionPane.ERROR_MESSAGE); } else if (e instanceof MD5CheckFailedException) { JOptionPane.showMessageDialog(panelManageDBInstances, e, "Error", JOptionPane.ERROR_MESSAGE); } else if (e instanceof NoSuchAlgorithmException) { JOptionPane.showMessageDialog(panelManageDBInstances, "An error occured while exporting solver binary: " + e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } } else if (methodName.equals("addInstances")) { if (e instanceof NoConnectionToDBException) { JOptionPane.showMessageDialog(panelManageDBInstances, "No connection to database: " + e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } else if (e instanceof SQLException) { JOptionPane.showMessageDialog(panelManageDBInstances, "SQL-Exception: " + e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } else if (e instanceof InstanceException) { JOptionPane.showMessageDialog(panelManageDBInstances, "No Instances have been found.", "Error", JOptionPane.WARNING_MESSAGE); } else if (e instanceof TaskCancelledException) { InstanceTableModel tableModel = new InstanceTableModel(); tableModel.addInstances(manageDBInstances.getTmp()); if (EDACCExtendedWarning.showMessageDialog(EDACCExtendedWarning.OK_CANCEL_OPTIONS, EDACCApp.getApplication().getMainFrame(), "Do you want to remove the already added instances in the list?", new JTable(tableModel)) == EDACCExtendedWarning.RET_OK_OPTION) { try { InstanceDAO.deleteAll(manageDBInstances.getTmp()); } catch (SQLException ex) { Logger.getLogger(EDACCManageDBMode.class.getName()).log(Level.SEVERE, null, ex); } manageDBInstances.setTmp(new Vector<Instance>()); } } } } public void onTaskSuccessful(String methodName, Object result) { if (methodName.equals("addInstances")) { this.instanceTableModel.fireTableDataChanged(); this.instanceClassTreeModel.reload(); } else if (methodName.equals("exportInstancnes")) { } else if (methodName.equals("TryToRemoveInstances")) { this.instanceTableModel.fireTableDataChanged(); this.instanceClassTreeModel.reload(); } } public void setFilterStatus(String status) { lblFilterStatus.setForeground(Color.red); lblFilterStatus.setText(status); lblFilterStatus.setIcon(new ImageIcon("warning-icon.png")); lblFilterStatus.updateUI(); } public void showInstanceClassButtons(boolean enable) { btnEditInstanceClass.setEnabled(enable); btnRemoveInstanceClass.setEnabled(enable); btnExportInstanceClass.setEnabled(enable); jMIEditInstanceClass.setEnabled(enable); jMIRemoveInstanceClass.setEnabled(enable); jMIExportInstanceClass.setEnabled(enable); } public void showInstanceButtons(boolean enable) { btnRemoveInstances.setEnabled(enable); btnAddToClass.setEnabled(enable); btnRemoveFromClass.setEnabled(enable); btnExportInstances.setEnabled(enable); jMIAddInstance.setEnabled(enable); jMIExportInstance.setEnabled(enable); jMIRemoveInstance.setEnabled(enable); } public void showSolverBinariesDetails(Vector<SolverBinaries> solverBinaries) { solverBinariesTableModel.setSolverBinaries(solverBinaries); } public void updateInstanceTable() { instanceFilter.clearInstanceClassIds(); if (jTreeInstanceClass.getSelectionPaths() != null) { for (TreePath path : jTreeInstanceClass.getSelectionPaths()) { for (Integer id : edacc.experiment.Util.getInstanceClassIdsFromPath((DefaultMutableTreeNode) (path.getLastPathComponent()))) { instanceFilter.addInstanceClassId(id); } } instanceTableModel.fireTableDataChanged(); } } public void reinitialize() { tableInstances.clearSelection(); instanceTableModel.clearTable(); jTreeInstanceClass.clearSelection(); } public void JTreeStateChanged() { instanceFilter.clearInstanceClassIds(); if (jTreeInstanceClass.getSelectionPaths() != null) { for (TreePath path : jTreeInstanceClass.getSelectionPaths()) { for (Integer id : edacc.experiment.Util.getInstanceClassIdsFromPath((DefaultMutableTreeNode) (path.getLastPathComponent()))) { instanceFilter.addInstanceClassId(id); } } instanceTableModel.fireTableDataChanged(); } } /** * Verifies the input of the Parameter name TextField. */ class ParameterNameVerifier extends InputVerifier { @Override public boolean verify(JComponent input) { String text = ((JTextField) input).getText(); try { return !text.equals("") && !manageDBParameters.parameterExists(text); } catch (Exception ex) { return false; } } @Override public boolean shouldYieldFocus(javax.swing.JComponent input) { boolean valid = verify(input); showInvalidParameterNameError(!valid); return valid; } } private void showInvalidParameterNameError(boolean show) { if (show) { // set the color of the TextField to a nice red tfParametersName.setBackground(new Color(255, 102, 102)); } else { tfParametersName.setBackground(Color.white); } } public JTree getInstanceClassTree() { return jTreeInstanceClass; } private Enumeration descendantExpandedPathsBeforeDrag; private TreePath selectedPathStored; public void saveExpandedState() { descendantExpandedPathsBeforeDrag = jTreeInstanceClass.getExpandedDescendants(new TreePath(((DefaultMutableTreeNode) instanceClassTreeModel.getRoot()).getPath())); selectedPathStored = jTreeInstanceClass.getSelectionModel().getSelectionPath(); } public void restoreExpandedState() { if (descendantExpandedPathsBeforeDrag != null) { for (Enumeration e = descendantExpandedPathsBeforeDrag; e.hasMoreElements();) { TreePath tmpPath = (TreePath) (e.nextElement()); jTreeInstanceClass.expandPath( new TreePath(((DefaultMutableTreeNode) tmpPath.getLastPathComponent()).getPath())); } } jTreeInstanceClass.getSelectionModel().setSelectionPath(selectedPathStored); } }
true
true
private void initComponents() { jFileChooserManageDBInstance = new javax.swing.JFileChooser(); jFileChooserManageDBExportInstance = new javax.swing.JFileChooser(); jPMInstanceTable = new javax.swing.JPopupMenu(); jMIAddInstance = new javax.swing.JMenuItem(); jMIRemoveInstance = new javax.swing.JMenuItem(); jMIExportInstance = new javax.swing.JMenuItem(); jPMInstanceTreeInstanceClass = new javax.swing.JPopupMenu(); jMINewInstanceClass = new javax.swing.JMenuItem(); jMIEditInstanceClass = new javax.swing.JMenuItem(); jMIRemoveInstanceClass = new javax.swing.JMenuItem(); jMIExportInstanceClass = new javax.swing.JMenuItem(); manageDBPane = new javax.swing.JTabbedPane(); panelManageDBSolver = new javax.swing.JPanel(); jSplitPane2 = new javax.swing.JSplitPane(); panelParametersOverall = new javax.swing.JPanel(); panelParameters = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); tableParameters = new javax.swing.JTable(); jPanel2 = new javax.swing.JPanel(); jlParametersName = new javax.swing.JLabel(); tfParametersName = new javax.swing.JTextField(); jlParametersPrefix = new javax.swing.JLabel(); tfParametersPrefix = new javax.swing.JTextField(); jlParametersOrder = new javax.swing.JLabel(); tfParametersOrder = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); chkHasNoValue = new javax.swing.JCheckBox(); lMandatory = new javax.swing.JLabel(); chkMandatory = new javax.swing.JCheckBox(); chkSpace = new javax.swing.JCheckBox(); lSpace = new javax.swing.JLabel(); jlParametersDefaultValue = new javax.swing.JLabel(); tfParametersDefaultValue = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); chkAttachToPrevious = new javax.swing.JCheckBox(); panelParametersButons = new javax.swing.JPanel(); btnParametersDelete = new javax.swing.JButton(); btnParametersNew = new javax.swing.JButton(); panelSolverOverall = new javax.swing.JPanel(); panelSolver = new javax.swing.JPanel(); jScrollPane2 = new javax.swing.JScrollPane(); tableSolver = new javax.swing.JTable(); jPanel1 = new javax.swing.JPanel(); jlSolverName = new javax.swing.JLabel(); tfSolverName = new javax.swing.JTextField(); jlSolverDescription = new javax.swing.JLabel(); jScrollPane3 = new javax.swing.JScrollPane(); taSolverDescription = new javax.swing.JTextArea(); jlSolverBinary = new javax.swing.JLabel(); jlSolverCode = new javax.swing.JLabel(); btnSolverAddCode = new javax.swing.JButton(); tfSolverAuthors = new javax.swing.JTextField(); tfSolverVersion = new javax.swing.JTextField(); jlSolverAuthors = new javax.swing.JLabel(); jlSolverVersion = new javax.swing.JLabel(); btnSolverAddBinary = new javax.swing.JButton(); jScrollPane4 = new javax.swing.JScrollPane(); tableSolverBinaries = new javax.swing.JTable(); btnSolverEditBinary = new javax.swing.JButton(); btnSolverDeleteBinary = new javax.swing.JButton(); panelSolverButtons = new javax.swing.JPanel(); btnSolverDelete = new javax.swing.JButton(); btnSolverNew = new javax.swing.JButton(); jPanel3 = new javax.swing.JPanel(); btnSolverSaveToDB = new javax.swing.JButton(); btnSolverRefresh = new javax.swing.JButton(); btnSolverExport = new javax.swing.JButton(); panelManageDBInstances = new javax.swing.JPanel(); jSplitPane1 = new javax.swing.JSplitPane(); panelInstanceClass = new javax.swing.JPanel(); panelButtonsInstanceClass = new javax.swing.JPanel(); btnNewInstanceClass = new javax.swing.JButton(); btnEditInstanceClass = new javax.swing.JButton(); btnRemoveInstanceClass = new javax.swing.JButton(); btnExportInstanceClass = new javax.swing.JButton(); panelInstanceClassTable = new javax.swing.JScrollPane(); jTreeInstanceClass = new javax.swing.JTree(); panelInstance = new javax.swing.JPanel(); panelInstanceTable = new javax.swing.JScrollPane(); tableInstances = new javax.swing.JTable(); panelButtonsInstances = new javax.swing.JPanel(); btnAddInstances = new javax.swing.JButton(); btnRemoveInstances = new javax.swing.JButton(); btnExportInstances = new javax.swing.JButton(); btnAddToClass = new javax.swing.JButton(); btnRemoveFromClass = new javax.swing.JButton(); btnAddInstances1 = new javax.swing.JButton(); bComputeProperty = new javax.swing.JButton(); btnGenerate = new javax.swing.JButton(); lblFilterStatus = new javax.swing.JLabel(); btnFilterInstances = new javax.swing.JButton(); btnSelectInstanceColumns = new javax.swing.JButton(); jFileChooserManageDBInstance.setFileSelectionMode(javax.swing.JFileChooser.FILES_AND_DIRECTORIES); jFileChooserManageDBInstance.setName("jFileChooserManageDBInstance"); // NOI18N jFileChooserManageDBExportInstance.setFileSelectionMode(javax.swing.JFileChooser.DIRECTORIES_ONLY); jFileChooserManageDBExportInstance.setName("jFileChooserManageDBExportInstance"); // NOI18N jPMInstanceTable.setBorderPainted(false); jPMInstanceTable.setComponentPopupMenu(jPMInstanceTable); org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(edacc.EDACCApp.class).getContext().getResourceMap(EDACCManageDBMode.class); jPMInstanceTable.setLabel(resourceMap.getString("jPMInstanceTable.label")); // NOI18N jPMInstanceTable.setMaximumSize(new java.awt.Dimension(10, 10)); jPMInstanceTable.setMinimumSize(new java.awt.Dimension(10, 10)); jPMInstanceTable.setName("jPMInstanceTable"); // NOI18N jMIAddInstance.setText(resourceMap.getString("jMIAddInstance.text")); // NOI18N jMIAddInstance.setName("jMIAddInstance"); // NOI18N jMIAddInstance.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMIAddInstanceActionPerformed(evt); } }); jPMInstanceTable.add(jMIAddInstance); jMIRemoveInstance.setText(resourceMap.getString("jMIRemoveInstance.text")); // NOI18N jMIRemoveInstance.setName("jMIRemoveInstance"); // NOI18N jMIRemoveInstance.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMIRemoveInstanceActionPerformed(evt); } }); jPMInstanceTable.add(jMIRemoveInstance); jMIExportInstance.setText(resourceMap.getString("jMIExportInstance.text")); // NOI18N jMIExportInstance.setName("jMIExportInstance"); // NOI18N jMIExportInstance.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMIExportInstanceActionPerformed(evt); } }); jPMInstanceTable.add(jMIExportInstance); jPMInstanceTreeInstanceClass.setName("jPMInstanceTreeInstanceClass"); // NOI18N jMINewInstanceClass.setText(resourceMap.getString("jMINewInstanceClass.text")); // NOI18N jMINewInstanceClass.setName("jMINewInstanceClass"); // NOI18N jMINewInstanceClass.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMINewInstanceClassActionPerformed(evt); } }); jPMInstanceTreeInstanceClass.add(jMINewInstanceClass); jMIEditInstanceClass.setText(resourceMap.getString("jMIEditInstanceClass.text")); // NOI18N jMIEditInstanceClass.setName("jMIEditInstanceClass"); // NOI18N jMIEditInstanceClass.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMIEditInstanceClassActionPerformed(evt); } }); jPMInstanceTreeInstanceClass.add(jMIEditInstanceClass); jMIRemoveInstanceClass.setText(resourceMap.getString("jMIRemoveInstanceClass.text")); // NOI18N jMIRemoveInstanceClass.setName("jMIRemoveInstanceClass"); // NOI18N jMIRemoveInstanceClass.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMIRemoveInstanceClassActionPerformed(evt); } }); jPMInstanceTreeInstanceClass.add(jMIRemoveInstanceClass); jMIExportInstanceClass.setText(resourceMap.getString("jMIExportInstanceClass.text")); // NOI18N jMIExportInstanceClass.setName("jMIExportInstanceClass"); // NOI18N jMIExportInstanceClass.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMIExportInstanceClassActionPerformed(evt); } }); jPMInstanceTreeInstanceClass.add(jMIExportInstanceClass); setMinimumSize(new java.awt.Dimension(0, 0)); setName("Form"); // NOI18N setPreferredSize(new java.awt.Dimension(500, 591)); manageDBPane.setMinimumSize(new java.awt.Dimension(0, 0)); manageDBPane.setName("manageDBPane"); // NOI18N manageDBPane.setRequestFocusEnabled(false); panelManageDBSolver.setName("panelManageDBSolver"); // NOI18N panelManageDBSolver.setPreferredSize(new java.awt.Dimension(0, 0)); jSplitPane2.setDividerLocation(0.6); jSplitPane2.setResizeWeight(0.5); jSplitPane2.setName("jSplitPane2"); // NOI18N panelParametersOverall.setName("panelParametersOverall"); // NOI18N panelParametersOverall.setPreferredSize(new java.awt.Dimension(0, 0)); panelParameters.setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("panelParameters.border.title"))); // NOI18N panelParameters.setName("panelParameters"); // NOI18N panelParameters.setPreferredSize(new java.awt.Dimension(0, 0)); jScrollPane1.setMinimumSize(new java.awt.Dimension(0, 0)); jScrollPane1.setName("jScrollPane1"); // NOI18N jScrollPane1.setPreferredSize(new java.awt.Dimension(0, 0)); tableParameters.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null} }, new String [] { "Title 1", "Title 2", "Title 3", "Title 4" } )); tableParameters.setToolTipText(resourceMap.getString("tableParameters.toolTipText")); // NOI18N tableParameters.setName("tableParameters"); // NOI18N tableParameters.setPreferredSize(new java.awt.Dimension(100, 72)); tableParameters.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); jScrollPane1.setViewportView(tableParameters); jPanel2.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel2.setName("jPanel2"); // NOI18N jlParametersName.setText(resourceMap.getString("jlParametersName.text")); // NOI18N jlParametersName.setName("jlParametersName"); // NOI18N tfParametersName.setText(resourceMap.getString("tfParametersName.text")); // NOI18N tfParametersName.setToolTipText(resourceMap.getString("tfParametersName.toolTipText")); // NOI18N tfParametersName.setInputVerifier(new ParameterNameVerifier()); tfParametersName.setName("tfParametersName"); // NOI18N tfParametersName.addFocusListener(new java.awt.event.FocusAdapter() { public void focusLost(java.awt.event.FocusEvent evt) { parameterChangedOnFocusLost(evt); } }); tfParametersName.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { parameterChangedOnKeyReleased(evt); } }); jlParametersPrefix.setText(resourceMap.getString("jlParametersPrefix.text")); // NOI18N jlParametersPrefix.setName("jlParametersPrefix"); // NOI18N tfParametersPrefix.setText(resourceMap.getString("tfParametersPrefix.text")); // NOI18N tfParametersPrefix.setToolTipText(resourceMap.getString("tfParametersPrefix.toolTipText")); // NOI18N tfParametersPrefix.setName("tfParametersPrefix"); // NOI18N tfParametersPrefix.addFocusListener(new java.awt.event.FocusAdapter() { public void focusLost(java.awt.event.FocusEvent evt) { parameterChangedOnFocusLost(evt); } }); tfParametersPrefix.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { parameterChangedOnKeyReleased(evt); } }); jlParametersOrder.setText(resourceMap.getString("jlParametersOrder.text")); // NOI18N jlParametersOrder.setName("jlParametersOrder"); // NOI18N tfParametersOrder.setText(resourceMap.getString("tfParametersOrder.text")); // NOI18N tfParametersOrder.setToolTipText(resourceMap.getString("tfParametersOrder.toolTipText")); // NOI18N tfParametersOrder.setName("tfParametersOrder"); // NOI18N tfParametersOrder.addFocusListener(new java.awt.event.FocusAdapter() { public void focusLost(java.awt.event.FocusEvent evt) { parameterChangedOnFocusLost(evt); } }); tfParametersOrder.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { parameterChangedOnKeyReleased(evt); } }); jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N jLabel1.setToolTipText(resourceMap.getString("jLabel1.toolTipText")); // NOI18N jLabel1.setName("jLabel1"); // NOI18N chkHasNoValue.setText(resourceMap.getString("chkHasNoValue.text")); // NOI18N chkHasNoValue.setToolTipText(resourceMap.getString("chkHasNoValue.toolTipText")); // NOI18N chkHasNoValue.setName("chkHasNoValue"); // NOI18N chkHasNoValue.addChangeListener(new javax.swing.event.ChangeListener() { public void stateChanged(javax.swing.event.ChangeEvent evt) { chkHasNoValueStateChanged(evt); } }); lMandatory.setText(resourceMap.getString("lMandatory.text")); // NOI18N lMandatory.setToolTipText(resourceMap.getString("lMandatory.toolTipText")); // NOI18N lMandatory.setName("lMandatory"); // NOI18N chkMandatory.setToolTipText(resourceMap.getString("chkMandatory.toolTipText")); // NOI18N chkMandatory.setName("chkMandatory"); // NOI18N chkMandatory.addChangeListener(new javax.swing.event.ChangeListener() { public void stateChanged(javax.swing.event.ChangeEvent evt) { chkMandatoryStateChanged(evt); } }); chkSpace.setToolTipText(resourceMap.getString("chkSpace.toolTipText")); // NOI18N chkSpace.setName("chkSpace"); // NOI18N chkSpace.addChangeListener(new javax.swing.event.ChangeListener() { public void stateChanged(javax.swing.event.ChangeEvent evt) { chkSpaceChanged(evt); } }); lSpace.setText(resourceMap.getString("lSpace.text")); // NOI18N lSpace.setToolTipText(resourceMap.getString("lSpace.toolTipText")); // NOI18N lSpace.setName("lSpace"); // NOI18N jlParametersDefaultValue.setText(resourceMap.getString("jlParametersDefaultValue.text")); // NOI18N jlParametersDefaultValue.setName("jlParametersDefaultValue"); // NOI18N tfParametersDefaultValue.setText(resourceMap.getString("tfParametersDefaultValue.text")); // NOI18N tfParametersDefaultValue.setName("tfParametersDefaultValue"); // NOI18N tfParametersDefaultValue.addFocusListener(new java.awt.event.FocusAdapter() { public void focusLost(java.awt.event.FocusEvent evt) { parameterChangedOnFocusLost(evt); } }); tfParametersDefaultValue.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { parameterChangedOnKeyReleased(evt); } }); jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N jLabel2.setToolTipText(resourceMap.getString("jLabel2.toolTipText")); // NOI18N jLabel2.setName("jLabel2"); // NOI18N chkAttachToPrevious.setToolTipText(resourceMap.getString("chkAttachToPrevious.toolTipText")); // NOI18N chkAttachToPrevious.setName("chkAttachToPrevious"); // NOI18N chkAttachToPrevious.addChangeListener(new javax.swing.event.ChangeListener() { public void stateChanged(javax.swing.event.ChangeEvent evt) { chkAttachToPreviousStateChanged(evt); } }); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jlParametersName, javax.swing.GroupLayout.DEFAULT_SIZE, 81, Short.MAX_VALUE) .addComponent(jlParametersPrefix, javax.swing.GroupLayout.DEFAULT_SIZE, 81, Short.MAX_VALUE) .addComponent(jlParametersOrder, javax.swing.GroupLayout.DEFAULT_SIZE, 81, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)) .addGroup(jPanel2Layout.createSequentialGroup() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1) .addComponent(lMandatory) .addComponent(lSpace) .addComponent(jlParametersDefaultValue)) .addGap(12, 12, 12)))) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(tfParametersName, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 71, Short.MAX_VALUE) .addComponent(tfParametersPrefix, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 71, Short.MAX_VALUE) .addComponent(tfParametersOrder, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 71, Short.MAX_VALUE) .addComponent(tfParametersDefaultValue, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 71, Short.MAX_VALUE) .addComponent(chkSpace)) .addComponent(chkAttachToPrevious, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(chkMandatory, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(chkHasNoValue, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap()) ); jPanel2Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jLabel1, jlParametersName, jlParametersOrder, jlParametersPrefix}); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap(61, Short.MAX_VALUE) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jlParametersName) .addComponent(tfParametersName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jlParametersPrefix, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(tfParametersPrefix, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jlParametersOrder) .addComponent(tfParametersOrder, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(tfParametersDefaultValue, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jlParametersDefaultValue)) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(8, 8, 8) .addComponent(jLabel1)) .addGroup(jPanel2Layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(chkHasNoValue))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(8, 8, 8) .addComponent(lMandatory)) .addComponent(chkMandatory)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(lSpace) .addComponent(chkSpace)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel2) .addComponent(chkAttachToPrevious)) .addContainerGap()) ); panelParametersButons.setName("panelParametersButons"); // NOI18N btnParametersDelete.setText(resourceMap.getString("btnParametersDelete.text")); // NOI18N btnParametersDelete.setToolTipText(resourceMap.getString("btnParametersDelete.toolTipText")); // NOI18N btnParametersDelete.setName("btnParametersDelete"); // NOI18N btnParametersDelete.setPreferredSize(new java.awt.Dimension(81, 25)); btnParametersDelete.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnParametersDeleteActionPerformed(evt); } }); btnParametersNew.setText(resourceMap.getString("btnParametersNew.text")); // NOI18N btnParametersNew.setToolTipText(resourceMap.getString("btnParametersNew.toolTipText")); // NOI18N btnParametersNew.setName("btnParametersNew"); // NOI18N btnParametersNew.setPreferredSize(new java.awt.Dimension(81, 25)); btnParametersNew.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnParametersNewActionPerformed(evt); } }); javax.swing.GroupLayout panelParametersButonsLayout = new javax.swing.GroupLayout(panelParametersButons); panelParametersButons.setLayout(panelParametersButonsLayout); panelParametersButonsLayout.setHorizontalGroup( panelParametersButonsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panelParametersButonsLayout.createSequentialGroup() .addContainerGap() .addComponent(btnParametersNew, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnParametersDelete, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); panelParametersButonsLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btnParametersDelete, btnParametersNew}); panelParametersButonsLayout.setVerticalGroup( panelParametersButonsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panelParametersButonsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnParametersNew, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnParametersDelete, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) ); javax.swing.GroupLayout panelParametersLayout = new javax.swing.GroupLayout(panelParameters); panelParameters.setLayout(panelParametersLayout); panelParametersLayout.setHorizontalGroup( panelParametersLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelParametersLayout.createSequentialGroup() .addContainerGap() .addGroup(panelParametersLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jPanel2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 192, Short.MAX_VALUE) .addComponent(panelParametersButons, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap()) ); panelParametersLayout.setVerticalGroup( panelParametersLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelParametersLayout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 73, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(panelParametersButons, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); javax.swing.GroupLayout panelParametersOverallLayout = new javax.swing.GroupLayout(panelParametersOverall); panelParametersOverall.setLayout(panelParametersOverallLayout); panelParametersOverallLayout.setHorizontalGroup( panelParametersOverallLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(panelParameters, javax.swing.GroupLayout.DEFAULT_SIZE, 228, Short.MAX_VALUE) ); panelParametersOverallLayout.setVerticalGroup( panelParametersOverallLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panelParametersOverallLayout.createSequentialGroup() .addContainerGap() .addComponent(panelParameters, javax.swing.GroupLayout.DEFAULT_SIZE, 464, Short.MAX_VALUE) .addContainerGap()) ); jSplitPane2.setRightComponent(panelParametersOverall); panelParametersOverall.getAccessibleContext().setAccessibleName(resourceMap.getString("panelParameters.AccessibleContext.accessibleName")); // NOI18N panelSolverOverall.setName("panelSolverOverall"); // NOI18N panelSolverOverall.setPreferredSize(new java.awt.Dimension(500, 489)); panelSolver.setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("panelSolver.border.title"))); // NOI18N panelSolver.setAutoscrolls(true); panelSolver.setName("panelSolver"); // NOI18N jScrollPane2.setToolTipText(resourceMap.getString("jScrollPane2.toolTipText")); // NOI18N jScrollPane2.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); jScrollPane2.setAutoscrolls(true); jScrollPane2.setEnabled(false); jScrollPane2.setMinimumSize(new java.awt.Dimension(100, 100)); jScrollPane2.setName("jScrollPane2"); // NOI18N jScrollPane2.setPreferredSize(new java.awt.Dimension(100, 100)); tableSolver.setAutoCreateRowSorter(true); tableSolver.setMinimumSize(new java.awt.Dimension(50, 0)); tableSolver.setName("tableSolver"); // NOI18N tableSolver.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); jScrollPane2.setViewportView(tableSolver); jPanel1.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel1.setName("jPanel1"); // NOI18N jlSolverName.setText(resourceMap.getString("jlSolverName.text")); // NOI18N jlSolverName.setName("jlSolverName"); // NOI18N tfSolverName.setText(resourceMap.getString("tfSolverName.text")); // NOI18N tfSolverName.setToolTipText(resourceMap.getString("tfSolverName.toolTipText")); // NOI18N tfSolverName.setName("tfSolverName"); // NOI18N tfSolverName.addFocusListener(new java.awt.event.FocusAdapter() { public void focusLost(java.awt.event.FocusEvent evt) { solverChangedOnFocusLost(evt); } }); tfSolverName.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { solverChangedOnKey(evt); } }); jlSolverDescription.setText(resourceMap.getString("jlSolverDescription.text")); // NOI18N jlSolverDescription.setName("jlSolverDescription"); // NOI18N jScrollPane3.setName("jScrollPane3"); // NOI18N taSolverDescription.setColumns(20); taSolverDescription.setLineWrap(true); taSolverDescription.setRows(5); taSolverDescription.setToolTipText(resourceMap.getString("taSolverDescription.toolTipText")); // NOI18N taSolverDescription.setName("taSolverDescription"); // NOI18N taSolverDescription.addFocusListener(new java.awt.event.FocusAdapter() { public void focusLost(java.awt.event.FocusEvent evt) { solverChangedOnFocusLost(evt); } }); taSolverDescription.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { solverChangedOnKey(evt); } }); jScrollPane3.setViewportView(taSolverDescription); jlSolverBinary.setText(resourceMap.getString("jlSolverBinary.text")); // NOI18N jlSolverBinary.setName("jlSolverBinary"); // NOI18N jlSolverCode.setText(resourceMap.getString("jlSolverCode.text")); // NOI18N jlSolverCode.setName("jlSolverCode"); // NOI18N btnSolverAddCode.setText(resourceMap.getString("btnSolverAddCode.text")); // NOI18N btnSolverAddCode.setToolTipText(resourceMap.getString("btnSolverAddCode.toolTipText")); // NOI18N btnSolverAddCode.setName("btnSolverAddCode"); // NOI18N btnSolverAddCode.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnSolverAddCodeActionPerformed(evt); } }); tfSolverAuthors.setText(resourceMap.getString("tfSolverAuthors.text")); // NOI18N tfSolverAuthors.setName("tfSolverAuthors"); // NOI18N tfSolverAuthors.addFocusListener(new java.awt.event.FocusAdapter() { public void focusLost(java.awt.event.FocusEvent evt) { solverChangedOnFocusLost(evt); } }); tfSolverAuthors.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { solverChangedOnKey(evt); } }); tfSolverVersion.setText(resourceMap.getString("tfSolverVersion.text")); // NOI18N tfSolverVersion.setName("tfSolverVersion"); // NOI18N tfSolverVersion.addFocusListener(new java.awt.event.FocusAdapter() { public void focusLost(java.awt.event.FocusEvent evt) { solverChangedOnFocusLost(evt); } }); tfSolverVersion.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { solverChangedOnKey(evt); } }); jlSolverAuthors.setText(resourceMap.getString("jlSolverAuthors.text")); // NOI18N jlSolverAuthors.setName("jlSolverAuthors"); // NOI18N jlSolverVersion.setText(resourceMap.getString("jlSolverVersion.text")); // NOI18N jlSolverVersion.setName("jlSolverVersion"); // NOI18N btnSolverAddBinary.setText(resourceMap.getString("btnSolverAddBinary.text")); // NOI18N btnSolverAddBinary.setToolTipText(resourceMap.getString("btnSolverAddBinary.toolTipText")); // NOI18N btnSolverAddBinary.setName("btnSolverAddBinary"); // NOI18N btnSolverAddBinary.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnSolverAddBinaryActionPerformed(evt); } }); jScrollPane4.setName("jScrollPane4"); // NOI18N tableSolverBinaries.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null} }, new String [] { "Title 1", "Title 2", "Title 3", "Title 4" } )); tableSolverBinaries.setName("tableSolverBinaries"); // NOI18N jScrollPane4.setViewportView(tableSolverBinaries); btnSolverEditBinary.setText(resourceMap.getString("btnSolverEditBinary.text")); // NOI18N btnSolverEditBinary.setActionCommand(resourceMap.getString("btnSolverEditBinary.actionCommand")); // NOI18N btnSolverEditBinary.setName("btnSolverEditBinary"); // NOI18N btnSolverEditBinary.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnSolverEditBinaryActionPerformed(evt); } }); btnSolverDeleteBinary.setText(resourceMap.getString("btnSolverDeleteBinary.text")); // NOI18N btnSolverDeleteBinary.setActionCommand(resourceMap.getString("btnSolverDeleteBinary.actionCommand")); // NOI18N btnSolverDeleteBinary.setName("btnSolverDeleteBinary"); // NOI18N btnSolverDeleteBinary.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnSolverDeleteBinaryActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jlSolverBinary) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(btnSolverAddBinary, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnSolverEditBinary, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 178, Short.MAX_VALUE) .addComponent(btnSolverDeleteBinary, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 409, Short.MAX_VALUE))) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jlSolverName, javax.swing.GroupLayout.DEFAULT_SIZE, 91, Short.MAX_VALUE) .addComponent(jlSolverDescription, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jlSolverVersion) .addGap(56, 56, 56)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jlSolverCode) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))) .addComponent(jlSolverAuthors)) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(tfSolverAuthors, javax.swing.GroupLayout.DEFAULT_SIZE, 409, Short.MAX_VALUE) .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 409, Short.MAX_VALUE) .addComponent(tfSolverName, javax.swing.GroupLayout.DEFAULT_SIZE, 409, Short.MAX_VALUE) .addGroup(jPanel1Layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(btnSolverAddCode) .addComponent(tfSolverVersion, javax.swing.GroupLayout.DEFAULT_SIZE, 409, Short.MAX_VALUE)))))) .addContainerGap()) ); jPanel1Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jlSolverBinary, jlSolverCode, jlSolverDescription, jlSolverName}); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(tfSolverName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jlSolverName)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jlSolverDescription, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jlSolverAuthors) .addComponent(tfSolverAuthors, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jlSolverVersion) .addComponent(tfSolverVersion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jlSolverCode) .addComponent(btnSolverAddCode)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jlSolverBinary) .addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 97, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnSolverAddBinary) .addComponent(btnSolverEditBinary) .addComponent(btnSolverDeleteBinary)) .addContainerGap()) ); panelSolverButtons.setName("panelSolverButtons"); // NOI18N btnSolverDelete.setText(resourceMap.getString("btnSolverDelete.text")); // NOI18N btnSolverDelete.setToolTipText(resourceMap.getString("btnSolverDelete.toolTipText")); // NOI18N btnSolverDelete.setName("btnSolverDelete"); // NOI18N btnSolverDelete.setPreferredSize(new java.awt.Dimension(81, 25)); btnSolverDelete.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnSolverDeleteActionPerformed(evt); } }); btnSolverNew.setText(resourceMap.getString("btnNew.text")); // NOI18N btnSolverNew.setToolTipText(resourceMap.getString("btnNew.toolTipText")); // NOI18N btnSolverNew.setMaximumSize(new java.awt.Dimension(81, 25)); btnSolverNew.setMinimumSize(new java.awt.Dimension(81, 25)); btnSolverNew.setName("btnNew"); // NOI18N btnSolverNew.setPreferredSize(new java.awt.Dimension(81, 25)); btnSolverNew.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnSolverNewActionPerformed(evt); } }); javax.swing.GroupLayout panelSolverButtonsLayout = new javax.swing.GroupLayout(panelSolverButtons); panelSolverButtons.setLayout(panelSolverButtonsLayout); panelSolverButtonsLayout.setHorizontalGroup( panelSolverButtonsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panelSolverButtonsLayout.createSequentialGroup() .addContainerGap() .addComponent(btnSolverNew, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnSolverDelete, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(360, Short.MAX_VALUE)) ); panelSolverButtonsLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btnSolverDelete, btnSolverNew}); panelSolverButtonsLayout.setVerticalGroup( panelSolverButtonsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panelSolverButtonsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnSolverNew, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnSolverDelete, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) ); javax.swing.GroupLayout panelSolverLayout = new javax.swing.GroupLayout(panelSolver); panelSolver.setLayout(panelSolverLayout); panelSolverLayout.setHorizontalGroup( panelSolverLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelSolverLayout.createSequentialGroup() .addGroup(panelSolverLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 540, Short.MAX_VALUE) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(panelSolverButtons, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap()) ); panelSolverLayout.setVerticalGroup( panelSolverLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelSolverLayout.createSequentialGroup() .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 47, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(panelSolverButtons, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(4, 4, 4)) ); jScrollPane2.getAccessibleContext().setAccessibleParent(manageDBPane); javax.swing.GroupLayout panelSolverOverallLayout = new javax.swing.GroupLayout(panelSolverOverall); panelSolverOverall.setLayout(panelSolverOverallLayout); panelSolverOverallLayout.setHorizontalGroup( panelSolverOverallLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(panelSolver, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); panelSolverOverallLayout.setVerticalGroup( panelSolverOverallLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panelSolverOverallLayout.createSequentialGroup() .addContainerGap() .addComponent(panelSolver, javax.swing.GroupLayout.DEFAULT_SIZE, 464, Short.MAX_VALUE) .addContainerGap()) ); jSplitPane2.setLeftComponent(panelSolverOverall); jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("")); jPanel3.setName("jPanel3"); // NOI18N btnSolverSaveToDB.setText(resourceMap.getString("btnSolverSaveToDB.text")); // NOI18N btnSolverSaveToDB.setToolTipText(resourceMap.getString("btnSolverSaveToDB.toolTipText")); // NOI18N btnSolverSaveToDB.setName("btnSolverSaveToDB"); // NOI18N btnSolverSaveToDB.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnSolverSaveToDBActionPerformed(evt); } }); btnSolverRefresh.setText(resourceMap.getString("btnSolverRefresh.text")); // NOI18N btnSolverRefresh.setToolTipText(resourceMap.getString("btnSolverRefresh.toolTipText")); // NOI18N btnSolverRefresh.setName("btnSolverRefresh"); // NOI18N btnSolverRefresh.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnSolverRefreshActionPerformed(evt); } }); btnSolverExport.setText(resourceMap.getString("exportSolver.text")); // NOI18N btnSolverExport.setToolTipText(resourceMap.getString("exportSolver.toolTipText")); // NOI18N btnSolverExport.setName("exportSolver"); // NOI18N btnSolverExport.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnExport(evt); } }); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup() .addContainerGap() .addComponent(btnSolverRefresh) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 495, Short.MAX_VALUE) .addComponent(btnSolverExport, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(btnSolverSaveToDB) .addContainerGap()) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnSolverRefresh) .addComponent(btnSolverSaveToDB) .addComponent(btnSolverExport)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); javax.swing.GroupLayout panelManageDBSolverLayout = new javax.swing.GroupLayout(panelManageDBSolver); panelManageDBSolver.setLayout(panelManageDBSolverLayout); panelManageDBSolverLayout.setHorizontalGroup( panelManageDBSolverLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panelManageDBSolverLayout.createSequentialGroup() .addContainerGap() .addGroup(panelManageDBSolverLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel3, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jSplitPane2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 798, Short.MAX_VALUE)) .addContainerGap()) ); panelManageDBSolverLayout.setVerticalGroup( panelManageDBSolverLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelManageDBSolverLayout.createSequentialGroup() .addContainerGap() .addComponent(jSplitPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 488, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); manageDBPane.addTab("Solvers", panelManageDBSolver); panelManageDBInstances.setName("panelManageDBInstances"); // NOI18N panelManageDBInstances.setPreferredSize(new java.awt.Dimension(0, 0)); jSplitPane1.setDividerLocation(0.6); jSplitPane1.setResizeWeight(0.4); jSplitPane1.setName("jSplitPane1"); // NOI18N panelInstanceClass.setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("panelInstanceClass.border.title"))); // NOI18N panelInstanceClass.setName("panelInstanceClass"); // NOI18N panelInstanceClass.setPreferredSize(new java.awt.Dimension(0, 0)); panelButtonsInstanceClass.setName("panelButtonsInstanceClass"); // NOI18N btnNewInstanceClass.setText(resourceMap.getString("btnNewInstanceClass.text")); // NOI18N btnNewInstanceClass.setToolTipText(resourceMap.getString("btnNewInstanceClass.toolTipText")); // NOI18N btnNewInstanceClass.setName("btnNewInstanceClass"); // NOI18N btnNewInstanceClass.setPreferredSize(new java.awt.Dimension(89, 25)); btnNewInstanceClass.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnNewInstanceClassActionPerformed(evt); } }); btnEditInstanceClass.setText(resourceMap.getString("btnEditInstanceClass.text")); // NOI18N btnEditInstanceClass.setToolTipText(resourceMap.getString("btnEditInstanceClass.toolTipText")); // NOI18N btnEditInstanceClass.setEnabled(false); btnEditInstanceClass.setName("btnEditInstanceClass"); // NOI18N btnEditInstanceClass.setPreferredSize(new java.awt.Dimension(89, 25)); btnEditInstanceClass.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnEditInstanceClassActionPerformed(evt); } }); btnRemoveInstanceClass.setText(resourceMap.getString("btnRemoveInstanceClass.text")); // NOI18N btnRemoveInstanceClass.setToolTipText(resourceMap.getString("btnRemoveInstanceClass.toolTipText")); // NOI18N btnRemoveInstanceClass.setEnabled(false); btnRemoveInstanceClass.setName("btnRemoveInstanceClass"); // NOI18N btnRemoveInstanceClass.setPreferredSize(new java.awt.Dimension(89, 25)); btnRemoveInstanceClass.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnRemoveInstanceClassActionPerformed(evt); } }); btnExportInstanceClass.setText(resourceMap.getString("btnExportInstanceClass.text")); // NOI18N btnExportInstanceClass.setName("btnExportInstanceClass"); // NOI18N btnExportInstanceClass.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnExportInstanceClassActionPerformed(evt); } }); javax.swing.GroupLayout panelButtonsInstanceClassLayout = new javax.swing.GroupLayout(panelButtonsInstanceClass); panelButtonsInstanceClass.setLayout(panelButtonsInstanceClassLayout); panelButtonsInstanceClassLayout.setHorizontalGroup( panelButtonsInstanceClassLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panelButtonsInstanceClassLayout.createSequentialGroup() .addContainerGap() .addComponent(btnNewInstanceClass, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(btnEditInstanceClass, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(btnRemoveInstanceClass, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(btnExportInstanceClass) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); panelButtonsInstanceClassLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btnEditInstanceClass, btnExportInstanceClass, btnNewInstanceClass, btnRemoveInstanceClass}); panelButtonsInstanceClassLayout.setVerticalGroup( panelButtonsInstanceClassLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panelButtonsInstanceClassLayout.createSequentialGroup() .addContainerGap() .addGroup(panelButtonsInstanceClassLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnNewInstanceClass, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnEditInstanceClass, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnRemoveInstanceClass, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnExportInstanceClass)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); panelButtonsInstanceClassLayout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {btnEditInstanceClass, btnExportInstanceClass, btnNewInstanceClass, btnRemoveInstanceClass}); panelInstanceClassTable.setToolTipText(resourceMap.getString("panelInstanceClassTable.toolTipText")); // NOI18N panelInstanceClassTable.setName("panelInstanceClassTable"); // NOI18N jTreeInstanceClass.setName("jTreeInstanceClass"); // NOI18N panelInstanceClassTable.setViewportView(jTreeInstanceClass); javax.swing.GroupLayout panelInstanceClassLayout = new javax.swing.GroupLayout(panelInstanceClass); panelInstanceClass.setLayout(panelInstanceClassLayout); panelInstanceClassLayout.setHorizontalGroup( panelInstanceClassLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelInstanceClassLayout.createSequentialGroup() .addContainerGap() .addGroup(panelInstanceClassLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(panelButtonsInstanceClass, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(panelInstanceClassTable, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 416, Short.MAX_VALUE)) .addContainerGap()) ); panelInstanceClassLayout.setVerticalGroup( panelInstanceClassLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelInstanceClassLayout.createSequentialGroup() .addComponent(panelInstanceClassTable, javax.swing.GroupLayout.DEFAULT_SIZE, 399, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(panelButtonsInstanceClass, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); jSplitPane1.setLeftComponent(panelInstanceClass); panelInstance.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("panelInstance.border.border.title")))); // NOI18N panelInstance.setName("panelInstance"); // NOI18N panelInstance.setPreferredSize(new java.awt.Dimension(0, 0)); panelInstanceTable.setName("panelInstanceTable"); // NOI18N tableInstances.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null, null}, {null, null, null, null, null}, {null, null, null, null, null}, {null, null, null, null, null}, {null, null, null, null, null} }, new String [] { "Name", "numAtoms", "numClauses", "ratio", "maxClauseLength" } )); tableInstances.setToolTipText(resourceMap.getString("tableInstances.toolTipText")); // NOI18N tableInstances.setMaximumSize(new java.awt.Dimension(2147483647, 8000)); tableInstances.setName("tableInstances"); // NOI18N tableInstances.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { tableInstancesMouseClicked(evt); } public void mousePressed(java.awt.event.MouseEvent evt) { tableInstancesMousePressed(evt); } }); panelInstanceTable.setViewportView(tableInstances); tableInstances.getColumnModel().getColumn(0).setHeaderValue(resourceMap.getString("tableInstances.columnModel.title0")); // NOI18N tableInstances.getColumnModel().getColumn(1).setHeaderValue(resourceMap.getString("tableInstances.columnModel.title1")); // NOI18N tableInstances.getColumnModel().getColumn(2).setHeaderValue(resourceMap.getString("tableInstances.columnModel.title2")); // NOI18N tableInstances.getColumnModel().getColumn(3).setHeaderValue(resourceMap.getString("tableInstances.columnModel.title3")); // NOI18N tableInstances.getColumnModel().getColumn(4).setHeaderValue(resourceMap.getString("tableInstances.columnModel.title4")); // NOI18N panelButtonsInstances.setName("panelButtonsInstances"); // NOI18N btnAddInstances.setText(resourceMap.getString("btnAddInstances.text")); // NOI18N btnAddInstances.setToolTipText(resourceMap.getString("btnAddInstances.toolTipText")); // NOI18N btnAddInstances.setName("btnAddInstances"); // NOI18N btnAddInstances.setPreferredSize(new java.awt.Dimension(83, 25)); btnAddInstances.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnAddInstancesActionPerformed(evt); } }); btnRemoveInstances.setText(resourceMap.getString("btnRemoveInstances.text")); // NOI18N btnRemoveInstances.setToolTipText(resourceMap.getString("btnRemoveInstances.toolTipText")); // NOI18N btnRemoveInstances.setEnabled(false); btnRemoveInstances.setName("btnRemoveInstances"); // NOI18N btnRemoveInstances.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnRemoveInstancesActionPerformed(evt); } }); btnExportInstances.setText(resourceMap.getString("btnExportInstances.text")); // NOI18N btnExportInstances.setToolTipText(resourceMap.getString("btnExportInstances.toolTipText")); // NOI18N btnExportInstances.setEnabled(false); btnExportInstances.setName("btnExportInstances"); // NOI18N btnExportInstances.setPreferredSize(new java.awt.Dimension(83, 25)); btnExportInstances.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnExportInstancesActionPerformed(evt); } }); btnAddToClass.setText(resourceMap.getString("btnAddToClass.text")); // NOI18N btnAddToClass.setToolTipText(resourceMap.getString("btnAddToClass.toolTipText")); // NOI18N btnAddToClass.setEnabled(false); btnAddToClass.setName("btnAddToClass"); // NOI18N btnAddToClass.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnAddToClassActionPerformed(evt); } }); btnRemoveFromClass.setToolTipText(resourceMap.getString("btnRemoveFromClass.toolTipText")); // NOI18N btnRemoveFromClass.setActionCommand(resourceMap.getString("btnRemoveFromClass.actionCommand")); // NOI18N btnRemoveFromClass.setEnabled(false); btnRemoveFromClass.setLabel(resourceMap.getString("btnRemoveFromClass.label")); // NOI18N btnRemoveFromClass.setName("btnRemoveFromClass"); // NOI18N btnRemoveFromClass.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnRemoveFromClassActionPerformed(evt); } }); btnAddInstances1.setText(resourceMap.getString("btnAddInstances1.text")); // NOI18N btnAddInstances1.setToolTipText(resourceMap.getString("btnAddInstances1.toolTipText")); // NOI18N btnAddInstances1.setName("btnAddInstances1"); // NOI18N btnAddInstances1.setPreferredSize(new java.awt.Dimension(83, 25)); btnAddInstances1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnAddInstances1ActionPerformed(evt); } }); bComputeProperty.setText(resourceMap.getString("bComputeProperty.text")); // NOI18N bComputeProperty.setName("bComputeProperty"); // NOI18N bComputeProperty.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { bComputePropertyActionPerformed(evt); } }); btnGenerate.setText(resourceMap.getString("btnGenerateInstances.text")); // NOI18N btnGenerate.setName("btnGenerateInstances"); // NOI18N btnGenerate.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnGenerateActionPerformed(evt); } }); javax.swing.GroupLayout panelButtonsInstancesLayout = new javax.swing.GroupLayout(panelButtonsInstances); panelButtonsInstances.setLayout(panelButtonsInstancesLayout); panelButtonsInstancesLayout.setHorizontalGroup( panelButtonsInstancesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panelButtonsInstancesLayout.createSequentialGroup() .addContainerGap() .addGroup(panelButtonsInstancesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panelButtonsInstancesLayout.createSequentialGroup() .addComponent(btnAddToClass, javax.swing.GroupLayout.PREFERRED_SIZE, 151, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(btnRemoveFromClass) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 60, Short.MAX_VALUE) .addComponent(bComputeProperty)) .addGroup(panelButtonsInstancesLayout.createSequentialGroup() .addComponent(btnAddInstances, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(btnRemoveInstances) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(btnAddInstances1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(btnGenerate) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 74, Short.MAX_VALUE) .addComponent(btnExportInstances, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap()) ); panelButtonsInstancesLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btnAddInstances, btnRemoveInstances}); panelButtonsInstancesLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btnAddToClass, btnRemoveFromClass}); panelButtonsInstancesLayout.setVerticalGroup( panelButtonsInstancesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panelButtonsInstancesLayout.createSequentialGroup() .addContainerGap() .addGroup(panelButtonsInstancesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnAddInstances, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnRemoveInstances) .addComponent(btnExportInstances, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnAddInstances1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnGenerate)) .addGap(18, 18, 18) .addGroup(panelButtonsInstancesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnAddToClass) .addComponent(btnRemoveFromClass) .addComponent(bComputeProperty)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); lblFilterStatus.setText(resourceMap.getString("lblFilterStatus.text")); // NOI18N lblFilterStatus.setName("lblFilterStatus"); // NOI18N btnFilterInstances.setText(resourceMap.getString("btnFilterInstances.text")); // NOI18N btnFilterInstances.setToolTipText(resourceMap.getString("btnFilterInstances.toolTipText")); // NOI18N btnFilterInstances.setName("btnFilterInstances"); // NOI18N btnFilterInstances.setPreferredSize(new java.awt.Dimension(83, 25)); btnFilterInstances.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnFilterInstancesActionPerformed(evt); } }); btnSelectInstanceColumns.setText(resourceMap.getString("btnSelectInstanceColumns.text")); // NOI18N btnSelectInstanceColumns.setName("btnSelectInstanceColumns"); // NOI18N btnSelectInstanceColumns.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnSelectInstanceColumnsActionPerformed(evt); } }); javax.swing.GroupLayout panelInstanceLayout = new javax.swing.GroupLayout(panelInstance); panelInstance.setLayout(panelInstanceLayout); panelInstanceLayout.setHorizontalGroup( panelInstanceLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panelInstanceLayout.createSequentialGroup() .addContainerGap() .addGroup(panelInstanceLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(panelInstanceTable, javax.swing.GroupLayout.DEFAULT_SIZE, 543, Short.MAX_VALUE) .addGroup(panelInstanceLayout.createSequentialGroup() .addComponent(btnFilterInstances, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(panelInstanceLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lblFilterStatus, javax.swing.GroupLayout.DEFAULT_SIZE, 448, Short.MAX_VALUE) .addComponent(btnSelectInstanceColumns, javax.swing.GroupLayout.Alignment.TRAILING))) .addGroup(panelInstanceLayout.createSequentialGroup() .addComponent(panelButtonsInstances, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()))) ); panelInstanceLayout.setVerticalGroup( panelInstanceLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panelInstanceLayout.createSequentialGroup() .addComponent(lblFilterStatus) .addGroup(panelInstanceLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnSelectInstanceColumns) .addComponent(btnFilterInstances, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(panelInstanceTable, javax.swing.GroupLayout.DEFAULT_SIZE, 333, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(panelButtonsInstances, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) ); panelInstanceLayout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {btnFilterInstances, btnSelectInstanceColumns}); jSplitPane1.setRightComponent(panelInstance); javax.swing.GroupLayout panelManageDBInstancesLayout = new javax.swing.GroupLayout(panelManageDBInstances); panelManageDBInstances.setLayout(panelManageDBInstancesLayout); panelManageDBInstancesLayout.setHorizontalGroup( panelManageDBInstancesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelManageDBInstancesLayout.createSequentialGroup() .addContainerGap() .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 964, Short.MAX_VALUE) .addContainerGap()) ); panelManageDBInstancesLayout.setVerticalGroup( panelManageDBInstancesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panelManageDBInstancesLayout.createSequentialGroup() .addContainerGap() .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 500, Short.MAX_VALUE)) ); manageDBPane.addTab("Instances", panelManageDBInstances); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(manageDBPane, javax.swing.GroupLayout.DEFAULT_SIZE, 834, Short.MAX_VALUE) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(manageDBPane, javax.swing.GroupLayout.DEFAULT_SIZE, 552, Short.MAX_VALUE) .addContainerGap()) ); }// </editor-fold>//GEN-END:initComponents
private void initComponents() { jFileChooserManageDBInstance = new javax.swing.JFileChooser(); jFileChooserManageDBExportInstance = new javax.swing.JFileChooser(); jPMInstanceTable = new javax.swing.JPopupMenu(); jMIAddInstance = new javax.swing.JMenuItem(); jMIRemoveInstance = new javax.swing.JMenuItem(); jMIExportInstance = new javax.swing.JMenuItem(); jPMInstanceTreeInstanceClass = new javax.swing.JPopupMenu(); jMINewInstanceClass = new javax.swing.JMenuItem(); jMIEditInstanceClass = new javax.swing.JMenuItem(); jMIRemoveInstanceClass = new javax.swing.JMenuItem(); jMIExportInstanceClass = new javax.swing.JMenuItem(); manageDBPane = new javax.swing.JTabbedPane(); panelManageDBSolver = new javax.swing.JPanel(); jSplitPane2 = new javax.swing.JSplitPane(); panelParametersOverall = new javax.swing.JPanel(); panelParameters = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); tableParameters = new javax.swing.JTable(); jPanel2 = new javax.swing.JPanel(); jlParametersName = new javax.swing.JLabel(); tfParametersName = new javax.swing.JTextField(); jlParametersPrefix = new javax.swing.JLabel(); tfParametersPrefix = new javax.swing.JTextField(); jlParametersOrder = new javax.swing.JLabel(); tfParametersOrder = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); chkHasNoValue = new javax.swing.JCheckBox(); lMandatory = new javax.swing.JLabel(); chkMandatory = new javax.swing.JCheckBox(); chkSpace = new javax.swing.JCheckBox(); lSpace = new javax.swing.JLabel(); jlParametersDefaultValue = new javax.swing.JLabel(); tfParametersDefaultValue = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); chkAttachToPrevious = new javax.swing.JCheckBox(); panelParametersButons = new javax.swing.JPanel(); btnParametersDelete = new javax.swing.JButton(); btnParametersNew = new javax.swing.JButton(); panelSolverOverall = new javax.swing.JPanel(); panelSolver = new javax.swing.JPanel(); jScrollPane2 = new javax.swing.JScrollPane(); tableSolver = new javax.swing.JTable(); jPanel1 = new javax.swing.JPanel(); jlSolverName = new javax.swing.JLabel(); tfSolverName = new javax.swing.JTextField(); jlSolverDescription = new javax.swing.JLabel(); jScrollPane3 = new javax.swing.JScrollPane(); taSolverDescription = new javax.swing.JTextArea(); jlSolverBinary = new javax.swing.JLabel(); jlSolverCode = new javax.swing.JLabel(); btnSolverAddCode = new javax.swing.JButton(); tfSolverAuthors = new javax.swing.JTextField(); tfSolverVersion = new javax.swing.JTextField(); jlSolverAuthors = new javax.swing.JLabel(); jlSolverVersion = new javax.swing.JLabel(); btnSolverAddBinary = new javax.swing.JButton(); jScrollPane4 = new javax.swing.JScrollPane(); tableSolverBinaries = new javax.swing.JTable(); btnSolverEditBinary = new javax.swing.JButton(); btnSolverDeleteBinary = new javax.swing.JButton(); panelSolverButtons = new javax.swing.JPanel(); btnSolverDelete = new javax.swing.JButton(); btnSolverNew = new javax.swing.JButton(); jPanel3 = new javax.swing.JPanel(); btnSolverSaveToDB = new javax.swing.JButton(); btnSolverRefresh = new javax.swing.JButton(); btnSolverExport = new javax.swing.JButton(); panelManageDBInstances = new javax.swing.JPanel(); jSplitPane1 = new javax.swing.JSplitPane(); panelInstanceClass = new javax.swing.JPanel(); panelButtonsInstanceClass = new javax.swing.JPanel(); btnNewInstanceClass = new javax.swing.JButton(); btnEditInstanceClass = new javax.swing.JButton(); btnRemoveInstanceClass = new javax.swing.JButton(); btnExportInstanceClass = new javax.swing.JButton(); panelInstanceClassTable = new javax.swing.JScrollPane(); jTreeInstanceClass = new javax.swing.JTree(); panelInstance = new javax.swing.JPanel(); panelInstanceTable = new javax.swing.JScrollPane(); tableInstances = new javax.swing.JTable(); panelButtonsInstances = new javax.swing.JPanel(); btnAddInstances = new javax.swing.JButton(); btnRemoveInstances = new javax.swing.JButton(); btnExportInstances = new javax.swing.JButton(); btnAddToClass = new javax.swing.JButton(); btnRemoveFromClass = new javax.swing.JButton(); btnAddInstances1 = new javax.swing.JButton(); bComputeProperty = new javax.swing.JButton(); btnGenerate = new javax.swing.JButton(); lblFilterStatus = new javax.swing.JLabel(); btnFilterInstances = new javax.swing.JButton(); btnSelectInstanceColumns = new javax.swing.JButton(); jFileChooserManageDBInstance.setFileSelectionMode(javax.swing.JFileChooser.FILES_AND_DIRECTORIES); jFileChooserManageDBInstance.setName("jFileChooserManageDBInstance"); // NOI18N jFileChooserManageDBExportInstance.setFileSelectionMode(javax.swing.JFileChooser.DIRECTORIES_ONLY); jFileChooserManageDBExportInstance.setName("jFileChooserManageDBExportInstance"); // NOI18N jPMInstanceTable.setBorderPainted(false); jPMInstanceTable.setComponentPopupMenu(jPMInstanceTable); org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(edacc.EDACCApp.class).getContext().getResourceMap(EDACCManageDBMode.class); jPMInstanceTable.setLabel(resourceMap.getString("jPMInstanceTable.label")); // NOI18N jPMInstanceTable.setMaximumSize(new java.awt.Dimension(10, 10)); jPMInstanceTable.setMinimumSize(new java.awt.Dimension(10, 10)); jPMInstanceTable.setName("jPMInstanceTable"); // NOI18N jMIAddInstance.setText(resourceMap.getString("jMIAddInstance.text")); // NOI18N jMIAddInstance.setName("jMIAddInstance"); // NOI18N jMIAddInstance.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMIAddInstanceActionPerformed(evt); } }); jPMInstanceTable.add(jMIAddInstance); jMIRemoveInstance.setText(resourceMap.getString("jMIRemoveInstance.text")); // NOI18N jMIRemoveInstance.setName("jMIRemoveInstance"); // NOI18N jMIRemoveInstance.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMIRemoveInstanceActionPerformed(evt); } }); jPMInstanceTable.add(jMIRemoveInstance); jMIExportInstance.setText(resourceMap.getString("jMIExportInstance.text")); // NOI18N jMIExportInstance.setName("jMIExportInstance"); // NOI18N jMIExportInstance.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMIExportInstanceActionPerformed(evt); } }); jPMInstanceTable.add(jMIExportInstance); jPMInstanceTreeInstanceClass.setName("jPMInstanceTreeInstanceClass"); // NOI18N jMINewInstanceClass.setText(resourceMap.getString("jMINewInstanceClass.text")); // NOI18N jMINewInstanceClass.setName("jMINewInstanceClass"); // NOI18N jMINewInstanceClass.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMINewInstanceClassActionPerformed(evt); } }); jPMInstanceTreeInstanceClass.add(jMINewInstanceClass); jMIEditInstanceClass.setText(resourceMap.getString("jMIEditInstanceClass.text")); // NOI18N jMIEditInstanceClass.setName("jMIEditInstanceClass"); // NOI18N jMIEditInstanceClass.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMIEditInstanceClassActionPerformed(evt); } }); jPMInstanceTreeInstanceClass.add(jMIEditInstanceClass); jMIRemoveInstanceClass.setText(resourceMap.getString("jMIRemoveInstanceClass.text")); // NOI18N jMIRemoveInstanceClass.setName("jMIRemoveInstanceClass"); // NOI18N jMIRemoveInstanceClass.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMIRemoveInstanceClassActionPerformed(evt); } }); jPMInstanceTreeInstanceClass.add(jMIRemoveInstanceClass); jMIExportInstanceClass.setText(resourceMap.getString("jMIExportInstanceClass.text")); // NOI18N jMIExportInstanceClass.setName("jMIExportInstanceClass"); // NOI18N jMIExportInstanceClass.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMIExportInstanceClassActionPerformed(evt); } }); jPMInstanceTreeInstanceClass.add(jMIExportInstanceClass); setMinimumSize(new java.awt.Dimension(0, 0)); setName("Form"); // NOI18N setPreferredSize(new java.awt.Dimension(500, 591)); manageDBPane.setMinimumSize(new java.awt.Dimension(0, 0)); manageDBPane.setName("manageDBPane"); // NOI18N manageDBPane.setRequestFocusEnabled(false); panelManageDBSolver.setName("panelManageDBSolver"); // NOI18N panelManageDBSolver.setPreferredSize(new java.awt.Dimension(0, 0)); jSplitPane2.setDividerLocation(0.6); jSplitPane2.setResizeWeight(0.5); jSplitPane2.setName("jSplitPane2"); // NOI18N panelParametersOverall.setName("panelParametersOverall"); // NOI18N panelParametersOverall.setPreferredSize(new java.awt.Dimension(0, 0)); panelParameters.setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("panelParameters.border.title"))); // NOI18N panelParameters.setName("panelParameters"); // NOI18N panelParameters.setPreferredSize(new java.awt.Dimension(0, 0)); jScrollPane1.setMinimumSize(new java.awt.Dimension(0, 0)); jScrollPane1.setName("jScrollPane1"); // NOI18N jScrollPane1.setPreferredSize(new java.awt.Dimension(0, 0)); tableParameters.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null} }, new String [] { "Title 1", "Title 2", "Title 3", "Title 4" } )); tableParameters.setToolTipText(resourceMap.getString("tableParameters.toolTipText")); // NOI18N tableParameters.setName("tableParameters"); // NOI18N tableParameters.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); jScrollPane1.setViewportView(tableParameters); jPanel2.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel2.setName("jPanel2"); // NOI18N jlParametersName.setText(resourceMap.getString("jlParametersName.text")); // NOI18N jlParametersName.setName("jlParametersName"); // NOI18N tfParametersName.setText(resourceMap.getString("tfParametersName.text")); // NOI18N tfParametersName.setToolTipText(resourceMap.getString("tfParametersName.toolTipText")); // NOI18N tfParametersName.setInputVerifier(new ParameterNameVerifier()); tfParametersName.setName("tfParametersName"); // NOI18N tfParametersName.addFocusListener(new java.awt.event.FocusAdapter() { public void focusLost(java.awt.event.FocusEvent evt) { parameterChangedOnFocusLost(evt); } }); tfParametersName.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { parameterChangedOnKeyReleased(evt); } }); jlParametersPrefix.setText(resourceMap.getString("jlParametersPrefix.text")); // NOI18N jlParametersPrefix.setName("jlParametersPrefix"); // NOI18N tfParametersPrefix.setText(resourceMap.getString("tfParametersPrefix.text")); // NOI18N tfParametersPrefix.setToolTipText(resourceMap.getString("tfParametersPrefix.toolTipText")); // NOI18N tfParametersPrefix.setName("tfParametersPrefix"); // NOI18N tfParametersPrefix.addFocusListener(new java.awt.event.FocusAdapter() { public void focusLost(java.awt.event.FocusEvent evt) { parameterChangedOnFocusLost(evt); } }); tfParametersPrefix.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { parameterChangedOnKeyReleased(evt); } }); jlParametersOrder.setText(resourceMap.getString("jlParametersOrder.text")); // NOI18N jlParametersOrder.setName("jlParametersOrder"); // NOI18N tfParametersOrder.setText(resourceMap.getString("tfParametersOrder.text")); // NOI18N tfParametersOrder.setToolTipText(resourceMap.getString("tfParametersOrder.toolTipText")); // NOI18N tfParametersOrder.setName("tfParametersOrder"); // NOI18N tfParametersOrder.addFocusListener(new java.awt.event.FocusAdapter() { public void focusLost(java.awt.event.FocusEvent evt) { parameterChangedOnFocusLost(evt); } }); tfParametersOrder.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { parameterChangedOnKeyReleased(evt); } }); jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N jLabel1.setToolTipText(resourceMap.getString("jLabel1.toolTipText")); // NOI18N jLabel1.setName("jLabel1"); // NOI18N chkHasNoValue.setText(resourceMap.getString("chkHasNoValue.text")); // NOI18N chkHasNoValue.setToolTipText(resourceMap.getString("chkHasNoValue.toolTipText")); // NOI18N chkHasNoValue.setName("chkHasNoValue"); // NOI18N chkHasNoValue.addChangeListener(new javax.swing.event.ChangeListener() { public void stateChanged(javax.swing.event.ChangeEvent evt) { chkHasNoValueStateChanged(evt); } }); lMandatory.setText(resourceMap.getString("lMandatory.text")); // NOI18N lMandatory.setToolTipText(resourceMap.getString("lMandatory.toolTipText")); // NOI18N lMandatory.setName("lMandatory"); // NOI18N chkMandatory.setToolTipText(resourceMap.getString("chkMandatory.toolTipText")); // NOI18N chkMandatory.setName("chkMandatory"); // NOI18N chkMandatory.addChangeListener(new javax.swing.event.ChangeListener() { public void stateChanged(javax.swing.event.ChangeEvent evt) { chkMandatoryStateChanged(evt); } }); chkSpace.setToolTipText(resourceMap.getString("chkSpace.toolTipText")); // NOI18N chkSpace.setName("chkSpace"); // NOI18N chkSpace.addChangeListener(new javax.swing.event.ChangeListener() { public void stateChanged(javax.swing.event.ChangeEvent evt) { chkSpaceChanged(evt); } }); lSpace.setText(resourceMap.getString("lSpace.text")); // NOI18N lSpace.setToolTipText(resourceMap.getString("lSpace.toolTipText")); // NOI18N lSpace.setName("lSpace"); // NOI18N jlParametersDefaultValue.setText(resourceMap.getString("jlParametersDefaultValue.text")); // NOI18N jlParametersDefaultValue.setName("jlParametersDefaultValue"); // NOI18N tfParametersDefaultValue.setText(resourceMap.getString("tfParametersDefaultValue.text")); // NOI18N tfParametersDefaultValue.setName("tfParametersDefaultValue"); // NOI18N tfParametersDefaultValue.addFocusListener(new java.awt.event.FocusAdapter() { public void focusLost(java.awt.event.FocusEvent evt) { parameterChangedOnFocusLost(evt); } }); tfParametersDefaultValue.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { parameterChangedOnKeyReleased(evt); } }); jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N jLabel2.setToolTipText(resourceMap.getString("jLabel2.toolTipText")); // NOI18N jLabel2.setName("jLabel2"); // NOI18N chkAttachToPrevious.setToolTipText(resourceMap.getString("chkAttachToPrevious.toolTipText")); // NOI18N chkAttachToPrevious.setName("chkAttachToPrevious"); // NOI18N chkAttachToPrevious.addChangeListener(new javax.swing.event.ChangeListener() { public void stateChanged(javax.swing.event.ChangeEvent evt) { chkAttachToPreviousStateChanged(evt); } }); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jlParametersName, javax.swing.GroupLayout.DEFAULT_SIZE, 81, Short.MAX_VALUE) .addComponent(jlParametersPrefix, javax.swing.GroupLayout.DEFAULT_SIZE, 81, Short.MAX_VALUE) .addComponent(jlParametersOrder, javax.swing.GroupLayout.DEFAULT_SIZE, 81, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)) .addGroup(jPanel2Layout.createSequentialGroup() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1) .addComponent(lMandatory) .addComponent(lSpace) .addComponent(jlParametersDefaultValue)) .addGap(12, 12, 12)))) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(tfParametersName, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 71, Short.MAX_VALUE) .addComponent(tfParametersPrefix, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 71, Short.MAX_VALUE) .addComponent(tfParametersOrder, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 71, Short.MAX_VALUE) .addComponent(tfParametersDefaultValue, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 71, Short.MAX_VALUE) .addComponent(chkSpace)) .addComponent(chkAttachToPrevious, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(chkMandatory, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(chkHasNoValue, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap()) ); jPanel2Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jLabel1, jlParametersName, jlParametersOrder, jlParametersPrefix}); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap(61, Short.MAX_VALUE) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jlParametersName) .addComponent(tfParametersName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jlParametersPrefix, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(tfParametersPrefix, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jlParametersOrder) .addComponent(tfParametersOrder, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(tfParametersDefaultValue, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jlParametersDefaultValue)) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(8, 8, 8) .addComponent(jLabel1)) .addGroup(jPanel2Layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(chkHasNoValue))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(8, 8, 8) .addComponent(lMandatory)) .addComponent(chkMandatory)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(lSpace) .addComponent(chkSpace)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel2) .addComponent(chkAttachToPrevious)) .addContainerGap()) ); panelParametersButons.setName("panelParametersButons"); // NOI18N btnParametersDelete.setText(resourceMap.getString("btnParametersDelete.text")); // NOI18N btnParametersDelete.setToolTipText(resourceMap.getString("btnParametersDelete.toolTipText")); // NOI18N btnParametersDelete.setName("btnParametersDelete"); // NOI18N btnParametersDelete.setPreferredSize(new java.awt.Dimension(81, 25)); btnParametersDelete.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnParametersDeleteActionPerformed(evt); } }); btnParametersNew.setText(resourceMap.getString("btnParametersNew.text")); // NOI18N btnParametersNew.setToolTipText(resourceMap.getString("btnParametersNew.toolTipText")); // NOI18N btnParametersNew.setName("btnParametersNew"); // NOI18N btnParametersNew.setPreferredSize(new java.awt.Dimension(81, 25)); btnParametersNew.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnParametersNewActionPerformed(evt); } }); javax.swing.GroupLayout panelParametersButonsLayout = new javax.swing.GroupLayout(panelParametersButons); panelParametersButons.setLayout(panelParametersButonsLayout); panelParametersButonsLayout.setHorizontalGroup( panelParametersButonsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panelParametersButonsLayout.createSequentialGroup() .addContainerGap() .addComponent(btnParametersNew, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnParametersDelete, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); panelParametersButonsLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btnParametersDelete, btnParametersNew}); panelParametersButonsLayout.setVerticalGroup( panelParametersButonsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panelParametersButonsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnParametersNew, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnParametersDelete, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) ); javax.swing.GroupLayout panelParametersLayout = new javax.swing.GroupLayout(panelParameters); panelParameters.setLayout(panelParametersLayout); panelParametersLayout.setHorizontalGroup( panelParametersLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelParametersLayout.createSequentialGroup() .addContainerGap() .addGroup(panelParametersLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jPanel2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 192, Short.MAX_VALUE) .addComponent(panelParametersButons, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap()) ); panelParametersLayout.setVerticalGroup( panelParametersLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelParametersLayout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 73, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(panelParametersButons, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); javax.swing.GroupLayout panelParametersOverallLayout = new javax.swing.GroupLayout(panelParametersOverall); panelParametersOverall.setLayout(panelParametersOverallLayout); panelParametersOverallLayout.setHorizontalGroup( panelParametersOverallLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(panelParameters, javax.swing.GroupLayout.DEFAULT_SIZE, 228, Short.MAX_VALUE) ); panelParametersOverallLayout.setVerticalGroup( panelParametersOverallLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panelParametersOverallLayout.createSequentialGroup() .addContainerGap() .addComponent(panelParameters, javax.swing.GroupLayout.DEFAULT_SIZE, 464, Short.MAX_VALUE) .addContainerGap()) ); jSplitPane2.setRightComponent(panelParametersOverall); panelParametersOverall.getAccessibleContext().setAccessibleName(resourceMap.getString("panelParameters.AccessibleContext.accessibleName")); // NOI18N panelSolverOverall.setName("panelSolverOverall"); // NOI18N panelSolverOverall.setPreferredSize(new java.awt.Dimension(500, 489)); panelSolver.setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("panelSolver.border.title"))); // NOI18N panelSolver.setAutoscrolls(true); panelSolver.setName("panelSolver"); // NOI18N jScrollPane2.setToolTipText(resourceMap.getString("jScrollPane2.toolTipText")); // NOI18N jScrollPane2.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); jScrollPane2.setAutoscrolls(true); jScrollPane2.setEnabled(false); jScrollPane2.setMinimumSize(new java.awt.Dimension(100, 100)); jScrollPane2.setName("jScrollPane2"); // NOI18N jScrollPane2.setPreferredSize(new java.awt.Dimension(100, 100)); tableSolver.setAutoCreateRowSorter(true); tableSolver.setMinimumSize(new java.awt.Dimension(50, 0)); tableSolver.setName("tableSolver"); // NOI18N tableSolver.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); jScrollPane2.setViewportView(tableSolver); jPanel1.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel1.setName("jPanel1"); // NOI18N jlSolverName.setText(resourceMap.getString("jlSolverName.text")); // NOI18N jlSolverName.setName("jlSolverName"); // NOI18N tfSolverName.setText(resourceMap.getString("tfSolverName.text")); // NOI18N tfSolverName.setToolTipText(resourceMap.getString("tfSolverName.toolTipText")); // NOI18N tfSolverName.setName("tfSolverName"); // NOI18N tfSolverName.addFocusListener(new java.awt.event.FocusAdapter() { public void focusLost(java.awt.event.FocusEvent evt) { solverChangedOnFocusLost(evt); } }); tfSolverName.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { solverChangedOnKey(evt); } }); jlSolverDescription.setText(resourceMap.getString("jlSolverDescription.text")); // NOI18N jlSolverDescription.setName("jlSolverDescription"); // NOI18N jScrollPane3.setName("jScrollPane3"); // NOI18N taSolverDescription.setColumns(20); taSolverDescription.setLineWrap(true); taSolverDescription.setRows(5); taSolverDescription.setToolTipText(resourceMap.getString("taSolverDescription.toolTipText")); // NOI18N taSolverDescription.setName("taSolverDescription"); // NOI18N taSolverDescription.addFocusListener(new java.awt.event.FocusAdapter() { public void focusLost(java.awt.event.FocusEvent evt) { solverChangedOnFocusLost(evt); } }); taSolverDescription.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { solverChangedOnKey(evt); } }); jScrollPane3.setViewportView(taSolverDescription); jlSolverBinary.setText(resourceMap.getString("jlSolverBinary.text")); // NOI18N jlSolverBinary.setName("jlSolverBinary"); // NOI18N jlSolverCode.setText(resourceMap.getString("jlSolverCode.text")); // NOI18N jlSolverCode.setName("jlSolverCode"); // NOI18N btnSolverAddCode.setText(resourceMap.getString("btnSolverAddCode.text")); // NOI18N btnSolverAddCode.setToolTipText(resourceMap.getString("btnSolverAddCode.toolTipText")); // NOI18N btnSolverAddCode.setName("btnSolverAddCode"); // NOI18N btnSolverAddCode.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnSolverAddCodeActionPerformed(evt); } }); tfSolverAuthors.setText(resourceMap.getString("tfSolverAuthors.text")); // NOI18N tfSolverAuthors.setName("tfSolverAuthors"); // NOI18N tfSolverAuthors.addFocusListener(new java.awt.event.FocusAdapter() { public void focusLost(java.awt.event.FocusEvent evt) { solverChangedOnFocusLost(evt); } }); tfSolverAuthors.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { solverChangedOnKey(evt); } }); tfSolverVersion.setText(resourceMap.getString("tfSolverVersion.text")); // NOI18N tfSolverVersion.setName("tfSolverVersion"); // NOI18N tfSolverVersion.addFocusListener(new java.awt.event.FocusAdapter() { public void focusLost(java.awt.event.FocusEvent evt) { solverChangedOnFocusLost(evt); } }); tfSolverVersion.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { solverChangedOnKey(evt); } }); jlSolverAuthors.setText(resourceMap.getString("jlSolverAuthors.text")); // NOI18N jlSolverAuthors.setName("jlSolverAuthors"); // NOI18N jlSolverVersion.setText(resourceMap.getString("jlSolverVersion.text")); // NOI18N jlSolverVersion.setName("jlSolverVersion"); // NOI18N btnSolverAddBinary.setText(resourceMap.getString("btnSolverAddBinary.text")); // NOI18N btnSolverAddBinary.setToolTipText(resourceMap.getString("btnSolverAddBinary.toolTipText")); // NOI18N btnSolverAddBinary.setName("btnSolverAddBinary"); // NOI18N btnSolverAddBinary.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnSolverAddBinaryActionPerformed(evt); } }); jScrollPane4.setName("jScrollPane4"); // NOI18N tableSolverBinaries.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null} }, new String [] { "Title 1", "Title 2", "Title 3", "Title 4" } )); tableSolverBinaries.setName("tableSolverBinaries"); // NOI18N jScrollPane4.setViewportView(tableSolverBinaries); btnSolverEditBinary.setText(resourceMap.getString("btnSolverEditBinary.text")); // NOI18N btnSolverEditBinary.setActionCommand(resourceMap.getString("btnSolverEditBinary.actionCommand")); // NOI18N btnSolverEditBinary.setName("btnSolverEditBinary"); // NOI18N btnSolverEditBinary.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnSolverEditBinaryActionPerformed(evt); } }); btnSolverDeleteBinary.setText(resourceMap.getString("btnSolverDeleteBinary.text")); // NOI18N btnSolverDeleteBinary.setActionCommand(resourceMap.getString("btnSolverDeleteBinary.actionCommand")); // NOI18N btnSolverDeleteBinary.setName("btnSolverDeleteBinary"); // NOI18N btnSolverDeleteBinary.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnSolverDeleteBinaryActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jlSolverBinary) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(btnSolverAddBinary, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnSolverEditBinary, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 178, Short.MAX_VALUE) .addComponent(btnSolverDeleteBinary, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 409, Short.MAX_VALUE))) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jlSolverName, javax.swing.GroupLayout.DEFAULT_SIZE, 91, Short.MAX_VALUE) .addComponent(jlSolverDescription, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jlSolverVersion) .addGap(56, 56, 56)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jlSolverCode) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))) .addComponent(jlSolverAuthors)) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(tfSolverAuthors, javax.swing.GroupLayout.DEFAULT_SIZE, 409, Short.MAX_VALUE) .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 409, Short.MAX_VALUE) .addComponent(tfSolverName, javax.swing.GroupLayout.DEFAULT_SIZE, 409, Short.MAX_VALUE) .addGroup(jPanel1Layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(btnSolverAddCode) .addComponent(tfSolverVersion, javax.swing.GroupLayout.DEFAULT_SIZE, 409, Short.MAX_VALUE)))))) .addContainerGap()) ); jPanel1Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jlSolverBinary, jlSolverCode, jlSolverDescription, jlSolverName}); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(tfSolverName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jlSolverName)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jlSolverDescription, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jlSolverAuthors) .addComponent(tfSolverAuthors, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jlSolverVersion) .addComponent(tfSolverVersion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jlSolverCode) .addComponent(btnSolverAddCode)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jlSolverBinary) .addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 97, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnSolverAddBinary) .addComponent(btnSolverEditBinary) .addComponent(btnSolverDeleteBinary)) .addContainerGap()) ); panelSolverButtons.setName("panelSolverButtons"); // NOI18N btnSolverDelete.setText(resourceMap.getString("btnSolverDelete.text")); // NOI18N btnSolverDelete.setToolTipText(resourceMap.getString("btnSolverDelete.toolTipText")); // NOI18N btnSolverDelete.setName("btnSolverDelete"); // NOI18N btnSolverDelete.setPreferredSize(new java.awt.Dimension(81, 25)); btnSolverDelete.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnSolverDeleteActionPerformed(evt); } }); btnSolverNew.setText(resourceMap.getString("btnNew.text")); // NOI18N btnSolverNew.setToolTipText(resourceMap.getString("btnNew.toolTipText")); // NOI18N btnSolverNew.setMaximumSize(new java.awt.Dimension(81, 25)); btnSolverNew.setMinimumSize(new java.awt.Dimension(81, 25)); btnSolverNew.setName("btnNew"); // NOI18N btnSolverNew.setPreferredSize(new java.awt.Dimension(81, 25)); btnSolverNew.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnSolverNewActionPerformed(evt); } }); javax.swing.GroupLayout panelSolverButtonsLayout = new javax.swing.GroupLayout(panelSolverButtons); panelSolverButtons.setLayout(panelSolverButtonsLayout); panelSolverButtonsLayout.setHorizontalGroup( panelSolverButtonsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panelSolverButtonsLayout.createSequentialGroup() .addContainerGap() .addComponent(btnSolverNew, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnSolverDelete, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(360, Short.MAX_VALUE)) ); panelSolverButtonsLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btnSolverDelete, btnSolverNew}); panelSolverButtonsLayout.setVerticalGroup( panelSolverButtonsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panelSolverButtonsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnSolverNew, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnSolverDelete, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) ); javax.swing.GroupLayout panelSolverLayout = new javax.swing.GroupLayout(panelSolver); panelSolver.setLayout(panelSolverLayout); panelSolverLayout.setHorizontalGroup( panelSolverLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelSolverLayout.createSequentialGroup() .addGroup(panelSolverLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 540, Short.MAX_VALUE) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(panelSolverButtons, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap()) ); panelSolverLayout.setVerticalGroup( panelSolverLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelSolverLayout.createSequentialGroup() .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 47, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(panelSolverButtons, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(4, 4, 4)) ); jScrollPane2.getAccessibleContext().setAccessibleParent(manageDBPane); javax.swing.GroupLayout panelSolverOverallLayout = new javax.swing.GroupLayout(panelSolverOverall); panelSolverOverall.setLayout(panelSolverOverallLayout); panelSolverOverallLayout.setHorizontalGroup( panelSolverOverallLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(panelSolver, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); panelSolverOverallLayout.setVerticalGroup( panelSolverOverallLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panelSolverOverallLayout.createSequentialGroup() .addContainerGap() .addComponent(panelSolver, javax.swing.GroupLayout.DEFAULT_SIZE, 464, Short.MAX_VALUE) .addContainerGap()) ); jSplitPane2.setLeftComponent(panelSolverOverall); jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("")); jPanel3.setName("jPanel3"); // NOI18N btnSolverSaveToDB.setText(resourceMap.getString("btnSolverSaveToDB.text")); // NOI18N btnSolverSaveToDB.setToolTipText(resourceMap.getString("btnSolverSaveToDB.toolTipText")); // NOI18N btnSolverSaveToDB.setName("btnSolverSaveToDB"); // NOI18N btnSolverSaveToDB.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnSolverSaveToDBActionPerformed(evt); } }); btnSolverRefresh.setText(resourceMap.getString("btnSolverRefresh.text")); // NOI18N btnSolverRefresh.setToolTipText(resourceMap.getString("btnSolverRefresh.toolTipText")); // NOI18N btnSolverRefresh.setName("btnSolverRefresh"); // NOI18N btnSolverRefresh.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnSolverRefreshActionPerformed(evt); } }); btnSolverExport.setText(resourceMap.getString("exportSolver.text")); // NOI18N btnSolverExport.setToolTipText(resourceMap.getString("exportSolver.toolTipText")); // NOI18N btnSolverExport.setName("exportSolver"); // NOI18N btnSolverExport.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnExport(evt); } }); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup() .addContainerGap() .addComponent(btnSolverRefresh) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 495, Short.MAX_VALUE) .addComponent(btnSolverExport, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(btnSolverSaveToDB) .addContainerGap()) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnSolverRefresh) .addComponent(btnSolverSaveToDB) .addComponent(btnSolverExport)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); javax.swing.GroupLayout panelManageDBSolverLayout = new javax.swing.GroupLayout(panelManageDBSolver); panelManageDBSolver.setLayout(panelManageDBSolverLayout); panelManageDBSolverLayout.setHorizontalGroup( panelManageDBSolverLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panelManageDBSolverLayout.createSequentialGroup() .addContainerGap() .addGroup(panelManageDBSolverLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel3, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jSplitPane2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 798, Short.MAX_VALUE)) .addContainerGap()) ); panelManageDBSolverLayout.setVerticalGroup( panelManageDBSolverLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelManageDBSolverLayout.createSequentialGroup() .addContainerGap() .addComponent(jSplitPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 488, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); manageDBPane.addTab("Solvers", panelManageDBSolver); panelManageDBInstances.setName("panelManageDBInstances"); // NOI18N panelManageDBInstances.setPreferredSize(new java.awt.Dimension(0, 0)); jSplitPane1.setDividerLocation(0.6); jSplitPane1.setResizeWeight(0.4); jSplitPane1.setName("jSplitPane1"); // NOI18N panelInstanceClass.setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("panelInstanceClass.border.title"))); // NOI18N panelInstanceClass.setName("panelInstanceClass"); // NOI18N panelInstanceClass.setPreferredSize(new java.awt.Dimension(0, 0)); panelButtonsInstanceClass.setName("panelButtonsInstanceClass"); // NOI18N btnNewInstanceClass.setText(resourceMap.getString("btnNewInstanceClass.text")); // NOI18N btnNewInstanceClass.setToolTipText(resourceMap.getString("btnNewInstanceClass.toolTipText")); // NOI18N btnNewInstanceClass.setName("btnNewInstanceClass"); // NOI18N btnNewInstanceClass.setPreferredSize(new java.awt.Dimension(89, 25)); btnNewInstanceClass.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnNewInstanceClassActionPerformed(evt); } }); btnEditInstanceClass.setText(resourceMap.getString("btnEditInstanceClass.text")); // NOI18N btnEditInstanceClass.setToolTipText(resourceMap.getString("btnEditInstanceClass.toolTipText")); // NOI18N btnEditInstanceClass.setEnabled(false); btnEditInstanceClass.setName("btnEditInstanceClass"); // NOI18N btnEditInstanceClass.setPreferredSize(new java.awt.Dimension(89, 25)); btnEditInstanceClass.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnEditInstanceClassActionPerformed(evt); } }); btnRemoveInstanceClass.setText(resourceMap.getString("btnRemoveInstanceClass.text")); // NOI18N btnRemoveInstanceClass.setToolTipText(resourceMap.getString("btnRemoveInstanceClass.toolTipText")); // NOI18N btnRemoveInstanceClass.setEnabled(false); btnRemoveInstanceClass.setName("btnRemoveInstanceClass"); // NOI18N btnRemoveInstanceClass.setPreferredSize(new java.awt.Dimension(89, 25)); btnRemoveInstanceClass.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnRemoveInstanceClassActionPerformed(evt); } }); btnExportInstanceClass.setText(resourceMap.getString("btnExportInstanceClass.text")); // NOI18N btnExportInstanceClass.setName("btnExportInstanceClass"); // NOI18N btnExportInstanceClass.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnExportInstanceClassActionPerformed(evt); } }); javax.swing.GroupLayout panelButtonsInstanceClassLayout = new javax.swing.GroupLayout(panelButtonsInstanceClass); panelButtonsInstanceClass.setLayout(panelButtonsInstanceClassLayout); panelButtonsInstanceClassLayout.setHorizontalGroup( panelButtonsInstanceClassLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panelButtonsInstanceClassLayout.createSequentialGroup() .addContainerGap() .addComponent(btnNewInstanceClass, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(btnEditInstanceClass, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(btnRemoveInstanceClass, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(btnExportInstanceClass) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); panelButtonsInstanceClassLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btnEditInstanceClass, btnExportInstanceClass, btnNewInstanceClass, btnRemoveInstanceClass}); panelButtonsInstanceClassLayout.setVerticalGroup( panelButtonsInstanceClassLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panelButtonsInstanceClassLayout.createSequentialGroup() .addContainerGap() .addGroup(panelButtonsInstanceClassLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnNewInstanceClass, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnEditInstanceClass, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnRemoveInstanceClass, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnExportInstanceClass)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); panelButtonsInstanceClassLayout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {btnEditInstanceClass, btnExportInstanceClass, btnNewInstanceClass, btnRemoveInstanceClass}); panelInstanceClassTable.setToolTipText(resourceMap.getString("panelInstanceClassTable.toolTipText")); // NOI18N panelInstanceClassTable.setName("panelInstanceClassTable"); // NOI18N jTreeInstanceClass.setName("jTreeInstanceClass"); // NOI18N panelInstanceClassTable.setViewportView(jTreeInstanceClass); javax.swing.GroupLayout panelInstanceClassLayout = new javax.swing.GroupLayout(panelInstanceClass); panelInstanceClass.setLayout(panelInstanceClassLayout); panelInstanceClassLayout.setHorizontalGroup( panelInstanceClassLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelInstanceClassLayout.createSequentialGroup() .addContainerGap() .addGroup(panelInstanceClassLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(panelButtonsInstanceClass, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(panelInstanceClassTable, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 416, Short.MAX_VALUE)) .addContainerGap()) ); panelInstanceClassLayout.setVerticalGroup( panelInstanceClassLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelInstanceClassLayout.createSequentialGroup() .addComponent(panelInstanceClassTable, javax.swing.GroupLayout.DEFAULT_SIZE, 399, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(panelButtonsInstanceClass, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); jSplitPane1.setLeftComponent(panelInstanceClass); panelInstance.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("panelInstance.border.border.title")))); // NOI18N panelInstance.setName("panelInstance"); // NOI18N panelInstance.setPreferredSize(new java.awt.Dimension(0, 0)); panelInstanceTable.setName("panelInstanceTable"); // NOI18N tableInstances.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null, null}, {null, null, null, null, null}, {null, null, null, null, null}, {null, null, null, null, null}, {null, null, null, null, null} }, new String [] { "Name", "numAtoms", "numClauses", "ratio", "maxClauseLength" } )); tableInstances.setToolTipText(resourceMap.getString("tableInstances.toolTipText")); // NOI18N tableInstances.setMaximumSize(new java.awt.Dimension(2147483647, 8000)); tableInstances.setName("tableInstances"); // NOI18N tableInstances.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { tableInstancesMouseClicked(evt); } public void mousePressed(java.awt.event.MouseEvent evt) { tableInstancesMousePressed(evt); } }); panelInstanceTable.setViewportView(tableInstances); tableInstances.getColumnModel().getColumn(0).setHeaderValue(resourceMap.getString("tableInstances.columnModel.title0")); // NOI18N tableInstances.getColumnModel().getColumn(1).setHeaderValue(resourceMap.getString("tableInstances.columnModel.title1")); // NOI18N tableInstances.getColumnModel().getColumn(2).setHeaderValue(resourceMap.getString("tableInstances.columnModel.title2")); // NOI18N tableInstances.getColumnModel().getColumn(3).setHeaderValue(resourceMap.getString("tableInstances.columnModel.title3")); // NOI18N tableInstances.getColumnModel().getColumn(4).setHeaderValue(resourceMap.getString("tableInstances.columnModel.title4")); // NOI18N panelButtonsInstances.setName("panelButtonsInstances"); // NOI18N btnAddInstances.setText(resourceMap.getString("btnAddInstances.text")); // NOI18N btnAddInstances.setToolTipText(resourceMap.getString("btnAddInstances.toolTipText")); // NOI18N btnAddInstances.setName("btnAddInstances"); // NOI18N btnAddInstances.setPreferredSize(new java.awt.Dimension(83, 25)); btnAddInstances.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnAddInstancesActionPerformed(evt); } }); btnRemoveInstances.setText(resourceMap.getString("btnRemoveInstances.text")); // NOI18N btnRemoveInstances.setToolTipText(resourceMap.getString("btnRemoveInstances.toolTipText")); // NOI18N btnRemoveInstances.setEnabled(false); btnRemoveInstances.setName("btnRemoveInstances"); // NOI18N btnRemoveInstances.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnRemoveInstancesActionPerformed(evt); } }); btnExportInstances.setText(resourceMap.getString("btnExportInstances.text")); // NOI18N btnExportInstances.setToolTipText(resourceMap.getString("btnExportInstances.toolTipText")); // NOI18N btnExportInstances.setEnabled(false); btnExportInstances.setName("btnExportInstances"); // NOI18N btnExportInstances.setPreferredSize(new java.awt.Dimension(83, 25)); btnExportInstances.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnExportInstancesActionPerformed(evt); } }); btnAddToClass.setText(resourceMap.getString("btnAddToClass.text")); // NOI18N btnAddToClass.setToolTipText(resourceMap.getString("btnAddToClass.toolTipText")); // NOI18N btnAddToClass.setEnabled(false); btnAddToClass.setName("btnAddToClass"); // NOI18N btnAddToClass.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnAddToClassActionPerformed(evt); } }); btnRemoveFromClass.setToolTipText(resourceMap.getString("btnRemoveFromClass.toolTipText")); // NOI18N btnRemoveFromClass.setActionCommand(resourceMap.getString("btnRemoveFromClass.actionCommand")); // NOI18N btnRemoveFromClass.setEnabled(false); btnRemoveFromClass.setLabel(resourceMap.getString("btnRemoveFromClass.label")); // NOI18N btnRemoveFromClass.setName("btnRemoveFromClass"); // NOI18N btnRemoveFromClass.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnRemoveFromClassActionPerformed(evt); } }); btnAddInstances1.setText(resourceMap.getString("btnAddInstances1.text")); // NOI18N btnAddInstances1.setToolTipText(resourceMap.getString("btnAddInstances1.toolTipText")); // NOI18N btnAddInstances1.setName("btnAddInstances1"); // NOI18N btnAddInstances1.setPreferredSize(new java.awt.Dimension(83, 25)); btnAddInstances1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnAddInstances1ActionPerformed(evt); } }); bComputeProperty.setText(resourceMap.getString("bComputeProperty.text")); // NOI18N bComputeProperty.setName("bComputeProperty"); // NOI18N bComputeProperty.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { bComputePropertyActionPerformed(evt); } }); btnGenerate.setText(resourceMap.getString("btnGenerateInstances.text")); // NOI18N btnGenerate.setName("btnGenerateInstances"); // NOI18N btnGenerate.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnGenerateActionPerformed(evt); } }); javax.swing.GroupLayout panelButtonsInstancesLayout = new javax.swing.GroupLayout(panelButtonsInstances); panelButtonsInstances.setLayout(panelButtonsInstancesLayout); panelButtonsInstancesLayout.setHorizontalGroup( panelButtonsInstancesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panelButtonsInstancesLayout.createSequentialGroup() .addContainerGap() .addGroup(panelButtonsInstancesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panelButtonsInstancesLayout.createSequentialGroup() .addComponent(btnAddToClass, javax.swing.GroupLayout.PREFERRED_SIZE, 151, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(btnRemoveFromClass) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 60, Short.MAX_VALUE) .addComponent(bComputeProperty)) .addGroup(panelButtonsInstancesLayout.createSequentialGroup() .addComponent(btnAddInstances, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(btnRemoveInstances) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(btnAddInstances1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(btnGenerate) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 74, Short.MAX_VALUE) .addComponent(btnExportInstances, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap()) ); panelButtonsInstancesLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btnAddInstances, btnRemoveInstances}); panelButtonsInstancesLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btnAddToClass, btnRemoveFromClass}); panelButtonsInstancesLayout.setVerticalGroup( panelButtonsInstancesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panelButtonsInstancesLayout.createSequentialGroup() .addContainerGap() .addGroup(panelButtonsInstancesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnAddInstances, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnRemoveInstances) .addComponent(btnExportInstances, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnAddInstances1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnGenerate)) .addGap(18, 18, 18) .addGroup(panelButtonsInstancesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnAddToClass) .addComponent(btnRemoveFromClass) .addComponent(bComputeProperty)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); lblFilterStatus.setText(resourceMap.getString("lblFilterStatus.text")); // NOI18N lblFilterStatus.setName("lblFilterStatus"); // NOI18N btnFilterInstances.setText(resourceMap.getString("btnFilterInstances.text")); // NOI18N btnFilterInstances.setToolTipText(resourceMap.getString("btnFilterInstances.toolTipText")); // NOI18N btnFilterInstances.setName("btnFilterInstances"); // NOI18N btnFilterInstances.setPreferredSize(new java.awt.Dimension(83, 25)); btnFilterInstances.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnFilterInstancesActionPerformed(evt); } }); btnSelectInstanceColumns.setText(resourceMap.getString("btnSelectInstanceColumns.text")); // NOI18N btnSelectInstanceColumns.setName("btnSelectInstanceColumns"); // NOI18N btnSelectInstanceColumns.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnSelectInstanceColumnsActionPerformed(evt); } }); javax.swing.GroupLayout panelInstanceLayout = new javax.swing.GroupLayout(panelInstance); panelInstance.setLayout(panelInstanceLayout); panelInstanceLayout.setHorizontalGroup( panelInstanceLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panelInstanceLayout.createSequentialGroup() .addContainerGap() .addGroup(panelInstanceLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(panelInstanceTable, javax.swing.GroupLayout.DEFAULT_SIZE, 543, Short.MAX_VALUE) .addGroup(panelInstanceLayout.createSequentialGroup() .addComponent(btnFilterInstances, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(panelInstanceLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lblFilterStatus, javax.swing.GroupLayout.DEFAULT_SIZE, 448, Short.MAX_VALUE) .addComponent(btnSelectInstanceColumns, javax.swing.GroupLayout.Alignment.TRAILING))) .addGroup(panelInstanceLayout.createSequentialGroup() .addComponent(panelButtonsInstances, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()))) ); panelInstanceLayout.setVerticalGroup( panelInstanceLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panelInstanceLayout.createSequentialGroup() .addComponent(lblFilterStatus) .addGroup(panelInstanceLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnSelectInstanceColumns) .addComponent(btnFilterInstances, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(panelInstanceTable, javax.swing.GroupLayout.DEFAULT_SIZE, 333, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(panelButtonsInstances, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) ); panelInstanceLayout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {btnFilterInstances, btnSelectInstanceColumns}); jSplitPane1.setRightComponent(panelInstance); javax.swing.GroupLayout panelManageDBInstancesLayout = new javax.swing.GroupLayout(panelManageDBInstances); panelManageDBInstances.setLayout(panelManageDBInstancesLayout); panelManageDBInstancesLayout.setHorizontalGroup( panelManageDBInstancesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelManageDBInstancesLayout.createSequentialGroup() .addContainerGap() .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 964, Short.MAX_VALUE) .addContainerGap()) ); panelManageDBInstancesLayout.setVerticalGroup( panelManageDBInstancesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panelManageDBInstancesLayout.createSequentialGroup() .addContainerGap() .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 500, Short.MAX_VALUE)) ); manageDBPane.addTab("Instances", panelManageDBInstances); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(manageDBPane, javax.swing.GroupLayout.DEFAULT_SIZE, 834, Short.MAX_VALUE) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(manageDBPane, javax.swing.GroupLayout.DEFAULT_SIZE, 552, Short.MAX_VALUE) .addContainerGap()) ); }// </editor-fold>//GEN-END:initComponents
diff --git a/src/com/speakwrite/api/Client.java b/src/com/speakwrite/api/Client.java index 254e102..a474c2a 100644 --- a/src/com/speakwrite/api/Client.java +++ b/src/com/speakwrite/api/Client.java @@ -1,119 +1,119 @@ package com.speakwrite.api; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.util.Scanner; import java.util.ArrayList; import java.util.List; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.mime.MultipartEntity; import org.apache.http.entity.mime.content.FileBody; import org.apache.http.entity.mime.content.StringBody; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.protocol.HTTP; import org.apache.http.util.EntityUtils; import com.google.gson.Gson; import com.speakwrite.api.JobDownloadRequest.DownloadType; public class Client { public static String API_BASE_URL = "https://service.speak-write.com/integration/api/v1/"; public Client() { } public CompletedJobsResponse getCompletedJobs(CompletedJobsRequest request) throws Exception { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(API_BASE_URL + "completedjobs.ashx"); List<NameValuePair> nvps = GetBaseParams(request); if(request.maxAge != null) { nvps.add(new BasicNameValuePair("maxAge", request.maxAge.toString())); } httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); HttpResponse response = httpClient.execute(httpPost); return ReadJson(CompletedJobsResponse.class, response); } public JobUploadResponse uploadJob(JobUploadRequest request) throws Exception { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost filePost = new HttpPost(API_BASE_URL + "submitjob.ashx"); FileBody bin = new FileBody(request.audioFile); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("applicationId", new StringBody(request.applicationId)); reqEntity.addPart("accountNumber", new StringBody(request.accountNumber)); reqEntity.addPart("pin", new StringBody(request.pin)); reqEntity.addPart("audioFile", bin); filePost.setEntity(reqEntity); HttpResponse response = httpClient.execute(filePost); return ReadJson(JobUploadResponse.class, response); } public JobDownloadResponse download(JobDownloadRequest request) throws Exception { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(API_BASE_URL + "download.ashx"); List<NameValuePair> nvps = GetBaseParams(request); if(request.fileName == null || request.fileName == "") { if(request.customFileName == null || request.customFileName == "") { throw new IllegalArgumentException("Must supply either fileName or customFileName"); } nvps.add(new BasicNameValuePair("customFileName", request.customFileName)); } else { nvps.add(new BasicNameValuePair("filename", request.fileName)); } - nvps.add(new BasicNameValuePair("filetype", request.type == DownloadType.Document ? "document" : "audio-wav")); + nvps.add(new BasicNameValuePair("filetype", request.type == DownloadType.Document ? "document" : "audio-source")); httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); HttpResponse response = httpClient.execute(httpPost); HttpEntity entity = response.getEntity(); InputStream result = entity.getContent(); File destinationFile = new File(request.destinationFileName); BufferedOutputStream fOut = new BufferedOutputStream(new FileOutputStream(destinationFile)); byte[] buffer = new byte[32*1024]; int bytesRead = 0; while((bytesRead = result.read(buffer)) != -1) { fOut.write(buffer, 0, bytesRead); } fOut.close(); EntityUtils.consume(entity); JobDownloadResponse downloadResponse = new JobDownloadResponse(); downloadResponse.success = true; return downloadResponse; } private static <T> T ReadJson(Class<T> clazz, HttpResponse response) throws Exception { HttpEntity entity = response.getEntity(); InputStream result = entity.getContent(); String json = new Scanner(result, "UTF-8").useDelimiter("\\A").next(); System.out.println(json); T jsonObject = new Gson().fromJson(json, clazz); EntityUtils.consume(entity); return jsonObject; } private static List<NameValuePair> GetBaseParams(BaseApiRequest request) { List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("applicationId", request.applicationId)); nvps.add(new BasicNameValuePair("accountNumber", request.accountNumber)); nvps.add(new BasicNameValuePair("pin", request.pin)); return nvps; } }
true
true
public JobDownloadResponse download(JobDownloadRequest request) throws Exception { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(API_BASE_URL + "download.ashx"); List<NameValuePair> nvps = GetBaseParams(request); if(request.fileName == null || request.fileName == "") { if(request.customFileName == null || request.customFileName == "") { throw new IllegalArgumentException("Must supply either fileName or customFileName"); } nvps.add(new BasicNameValuePair("customFileName", request.customFileName)); } else { nvps.add(new BasicNameValuePair("filename", request.fileName)); } nvps.add(new BasicNameValuePair("filetype", request.type == DownloadType.Document ? "document" : "audio-wav")); httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); HttpResponse response = httpClient.execute(httpPost); HttpEntity entity = response.getEntity(); InputStream result = entity.getContent(); File destinationFile = new File(request.destinationFileName); BufferedOutputStream fOut = new BufferedOutputStream(new FileOutputStream(destinationFile)); byte[] buffer = new byte[32*1024]; int bytesRead = 0; while((bytesRead = result.read(buffer)) != -1) { fOut.write(buffer, 0, bytesRead); } fOut.close(); EntityUtils.consume(entity); JobDownloadResponse downloadResponse = new JobDownloadResponse(); downloadResponse.success = true; return downloadResponse; }
public JobDownloadResponse download(JobDownloadRequest request) throws Exception { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(API_BASE_URL + "download.ashx"); List<NameValuePair> nvps = GetBaseParams(request); if(request.fileName == null || request.fileName == "") { if(request.customFileName == null || request.customFileName == "") { throw new IllegalArgumentException("Must supply either fileName or customFileName"); } nvps.add(new BasicNameValuePair("customFileName", request.customFileName)); } else { nvps.add(new BasicNameValuePair("filename", request.fileName)); } nvps.add(new BasicNameValuePair("filetype", request.type == DownloadType.Document ? "document" : "audio-source")); httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); HttpResponse response = httpClient.execute(httpPost); HttpEntity entity = response.getEntity(); InputStream result = entity.getContent(); File destinationFile = new File(request.destinationFileName); BufferedOutputStream fOut = new BufferedOutputStream(new FileOutputStream(destinationFile)); byte[] buffer = new byte[32*1024]; int bytesRead = 0; while((bytesRead = result.read(buffer)) != -1) { fOut.write(buffer, 0, bytesRead); } fOut.close(); EntityUtils.consume(entity); JobDownloadResponse downloadResponse = new JobDownloadResponse(); downloadResponse.success = true; return downloadResponse; }
diff --git a/bundles/org.eclipse.orion.server.git/src/org/eclipse/orion/server/git/objects/Log.java b/bundles/org.eclipse.orion.server.git/src/org/eclipse/orion/server/git/objects/Log.java index 8fd49dda..02205393 100644 --- a/bundles/org.eclipse.orion.server.git/src/org/eclipse/orion/server/git/objects/Log.java +++ b/bundles/org.eclipse.orion.server.git/src/org/eclipse/orion/server/git/objects/Log.java @@ -1,126 +1,126 @@ /******************************************************************************* * Copyright (c) 2011, 2012 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.orion.server.git.objects; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.*; import org.eclipse.core.runtime.CoreException; import org.eclipse.jgit.api.Git; import org.eclipse.jgit.api.ListBranchCommand.ListMode; import org.eclipse.jgit.lib.*; import org.eclipse.jgit.revwalk.RevCommit; import org.eclipse.orion.internal.server.servlets.ProtocolConstants; import org.eclipse.orion.server.git.BaseToCommitConverter; import org.eclipse.orion.server.git.GitConstants; import org.json.*; public class Log extends GitObject { private Iterable<RevCommit> commits; private String pattern; private Ref toRefId; private Ref fromRefId; public Log(URI cloneLocation, Repository db, Iterable<RevCommit> commits, String pattern, Ref toRefId, Ref fromRefId) { super(cloneLocation, db); this.commits = commits; this.pattern = pattern; this.toRefId = toRefId; this.fromRefId = fromRefId; } public void setCommits(Iterable<RevCommit> commits) { this.commits = commits; } public JSONObject toJSON(int page, int pageSize) throws JSONException, URISyntaxException, IOException, CoreException { if (commits == null) throw new IllegalStateException("'commits' is null"); Map<ObjectId, JSONArray> commitToBranchMap = getCommitToBranchMap(db); JSONObject result = new JSONObject(); JSONArray children = new JSONArray(); int i = 0; Iterator<RevCommit> iterator = commits.iterator(); while (iterator.hasNext()) { RevCommit revCommit = (RevCommit) iterator.next(); Commit commit = new Commit(cloneLocation, db, revCommit, pattern); commit.setCommitToBranchMap(commitToBranchMap); children.put(commit.toJSON()); if (i++ == pageSize - 1) break; } boolean hasNextPage = iterator.hasNext(); result.put(ProtocolConstants.KEY_CHILDREN, children); result.put(GitConstants.KEY_REPOSITORY_PATH, pattern == null ? "" : pattern); //$NON-NLS-1$ result.put(GitConstants.KEY_CLONE, cloneLocation); if (toRefId != null) { String refTargetName = toRefId.getTarget().getName(); if (refTargetName.startsWith(Constants.R_HEADS)) { // this is a branch result.put(GitConstants.KEY_LOG_TO_REF, new Branch(cloneLocation, db, toRefId.getTarget()).toJSON()); } } if (fromRefId != null) { String refTargetName = fromRefId.getTarget().getName(); if (refTargetName.startsWith(Constants.R_HEADS)) { // this is a branch result.put(GitConstants.KEY_LOG_FROM_REF, new Branch(cloneLocation, db, fromRefId.getTarget()).toJSON()); } } if (page > 0) { StringBuilder c = new StringBuilder(""); //$NON-NLS-1$ if (fromRefId != null) c.append(fromRefId.getName()); if (fromRefId != null && toRefId != null) c.append(".."); //$NON-NLS-1$ if (toRefId != null) - c.append(toRefId.getName()); + c.append(Repository.shortenRefName(toRefId.getName())); final String q = "page=%d&pageSize=%d"; //$NON-NLS-1$ if (page > 1) { result.put(ProtocolConstants.KEY_PREVIOUS_LOCATION, BaseToCommitConverter.getCommitLocation(cloneLocation, c.toString(), pattern, BaseToCommitConverter.REMOVE_FIRST_2.setQuery(String.format(q, page - 1, pageSize)))); } if (hasNextPage) { result.put(ProtocolConstants.KEY_NEXT_LOCATION, BaseToCommitConverter.getCommitLocation(cloneLocation, c.toString(), pattern, BaseToCommitConverter.REMOVE_FIRST_2.setQuery(String.format(q, page + 1, pageSize)))); } } return result; } static Map<ObjectId, JSONArray> getCommitToBranchMap(Repository db) throws JSONException { HashMap<ObjectId, JSONArray> commitToBranch = new HashMap<ObjectId, JSONArray>(); Git git = new Git(db); List<Ref> branchRefs = git.branchList().setListMode(ListMode.ALL).call(); for (Ref branchRef : branchRefs) { ObjectId commitId = branchRef.getLeaf().getObjectId(); JSONObject branch = new JSONObject(); branch.put(ProtocolConstants.KEY_FULL_NAME, branchRef.getName()); JSONArray branchesArray = commitToBranch.get(commitId); if (branchesArray != null) { branchesArray.put(branch); } else { branchesArray = new JSONArray(); branchesArray.put(branch); commitToBranch.put(commitId, branchesArray); } } return commitToBranch; } }
true
true
public JSONObject toJSON(int page, int pageSize) throws JSONException, URISyntaxException, IOException, CoreException { if (commits == null) throw new IllegalStateException("'commits' is null"); Map<ObjectId, JSONArray> commitToBranchMap = getCommitToBranchMap(db); JSONObject result = new JSONObject(); JSONArray children = new JSONArray(); int i = 0; Iterator<RevCommit> iterator = commits.iterator(); while (iterator.hasNext()) { RevCommit revCommit = (RevCommit) iterator.next(); Commit commit = new Commit(cloneLocation, db, revCommit, pattern); commit.setCommitToBranchMap(commitToBranchMap); children.put(commit.toJSON()); if (i++ == pageSize - 1) break; } boolean hasNextPage = iterator.hasNext(); result.put(ProtocolConstants.KEY_CHILDREN, children); result.put(GitConstants.KEY_REPOSITORY_PATH, pattern == null ? "" : pattern); //$NON-NLS-1$ result.put(GitConstants.KEY_CLONE, cloneLocation); if (toRefId != null) { String refTargetName = toRefId.getTarget().getName(); if (refTargetName.startsWith(Constants.R_HEADS)) { // this is a branch result.put(GitConstants.KEY_LOG_TO_REF, new Branch(cloneLocation, db, toRefId.getTarget()).toJSON()); } } if (fromRefId != null) { String refTargetName = fromRefId.getTarget().getName(); if (refTargetName.startsWith(Constants.R_HEADS)) { // this is a branch result.put(GitConstants.KEY_LOG_FROM_REF, new Branch(cloneLocation, db, fromRefId.getTarget()).toJSON()); } } if (page > 0) { StringBuilder c = new StringBuilder(""); //$NON-NLS-1$ if (fromRefId != null) c.append(fromRefId.getName()); if (fromRefId != null && toRefId != null) c.append(".."); //$NON-NLS-1$ if (toRefId != null) c.append(toRefId.getName()); final String q = "page=%d&pageSize=%d"; //$NON-NLS-1$ if (page > 1) { result.put(ProtocolConstants.KEY_PREVIOUS_LOCATION, BaseToCommitConverter.getCommitLocation(cloneLocation, c.toString(), pattern, BaseToCommitConverter.REMOVE_FIRST_2.setQuery(String.format(q, page - 1, pageSize)))); } if (hasNextPage) { result.put(ProtocolConstants.KEY_NEXT_LOCATION, BaseToCommitConverter.getCommitLocation(cloneLocation, c.toString(), pattern, BaseToCommitConverter.REMOVE_FIRST_2.setQuery(String.format(q, page + 1, pageSize)))); } } return result; }
public JSONObject toJSON(int page, int pageSize) throws JSONException, URISyntaxException, IOException, CoreException { if (commits == null) throw new IllegalStateException("'commits' is null"); Map<ObjectId, JSONArray> commitToBranchMap = getCommitToBranchMap(db); JSONObject result = new JSONObject(); JSONArray children = new JSONArray(); int i = 0; Iterator<RevCommit> iterator = commits.iterator(); while (iterator.hasNext()) { RevCommit revCommit = (RevCommit) iterator.next(); Commit commit = new Commit(cloneLocation, db, revCommit, pattern); commit.setCommitToBranchMap(commitToBranchMap); children.put(commit.toJSON()); if (i++ == pageSize - 1) break; } boolean hasNextPage = iterator.hasNext(); result.put(ProtocolConstants.KEY_CHILDREN, children); result.put(GitConstants.KEY_REPOSITORY_PATH, pattern == null ? "" : pattern); //$NON-NLS-1$ result.put(GitConstants.KEY_CLONE, cloneLocation); if (toRefId != null) { String refTargetName = toRefId.getTarget().getName(); if (refTargetName.startsWith(Constants.R_HEADS)) { // this is a branch result.put(GitConstants.KEY_LOG_TO_REF, new Branch(cloneLocation, db, toRefId.getTarget()).toJSON()); } } if (fromRefId != null) { String refTargetName = fromRefId.getTarget().getName(); if (refTargetName.startsWith(Constants.R_HEADS)) { // this is a branch result.put(GitConstants.KEY_LOG_FROM_REF, new Branch(cloneLocation, db, fromRefId.getTarget()).toJSON()); } } if (page > 0) { StringBuilder c = new StringBuilder(""); //$NON-NLS-1$ if (fromRefId != null) c.append(fromRefId.getName()); if (fromRefId != null && toRefId != null) c.append(".."); //$NON-NLS-1$ if (toRefId != null) c.append(Repository.shortenRefName(toRefId.getName())); final String q = "page=%d&pageSize=%d"; //$NON-NLS-1$ if (page > 1) { result.put(ProtocolConstants.KEY_PREVIOUS_LOCATION, BaseToCommitConverter.getCommitLocation(cloneLocation, c.toString(), pattern, BaseToCommitConverter.REMOVE_FIRST_2.setQuery(String.format(q, page - 1, pageSize)))); } if (hasNextPage) { result.put(ProtocolConstants.KEY_NEXT_LOCATION, BaseToCommitConverter.getCommitLocation(cloneLocation, c.toString(), pattern, BaseToCommitConverter.REMOVE_FIRST_2.setQuery(String.format(q, page + 1, pageSize)))); } } return result; }
diff --git a/spring-integration-http/src/main/java/org/springframework/integration/http/inbound/HttpRequestHandlingEndpointSupport.java b/spring-integration-http/src/main/java/org/springframework/integration/http/inbound/HttpRequestHandlingEndpointSupport.java index 385884dafd..8d48528660 100644 --- a/spring-integration-http/src/main/java/org/springframework/integration/http/inbound/HttpRequestHandlingEndpointSupport.java +++ b/spring-integration-http/src/main/java/org/springframework/integration/http/inbound/HttpRequestHandlingEndpointSupport.java @@ -1,360 +1,361 @@ /* * Copyright 2002-2010 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.integration.http.inbound; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; import org.springframework.http.converter.ByteArrayHttpMessageConverter; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.ResourceHttpMessageConverter; import org.springframework.http.converter.StringHttpMessageConverter; import org.springframework.http.converter.json.MappingJacksonHttpMessageConverter; import org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter; import org.springframework.http.converter.xml.SourceHttpMessageConverter; import org.springframework.http.server.ServletServerHttpRequest; import org.springframework.http.server.ServletServerHttpResponse; import org.springframework.integration.Message; import org.springframework.integration.MessagingException; import org.springframework.integration.gateway.MessagingGatewaySupport; import org.springframework.integration.http.converter.MultipartAwareFormHttpMessageConverter; import org.springframework.integration.http.converter.SerializingHttpMessageConverter; import org.springframework.integration.http.multipart.MultipartHttpInputMessage; import org.springframework.integration.http.support.DefaultHttpHeaderMapper; import org.springframework.integration.mapping.HeaderMapper; import org.springframework.integration.support.MessageBuilder; import org.springframework.util.Assert; import org.springframework.util.ClassUtils; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.multipart.MultipartHttpServletRequest; import org.springframework.web.multipart.MultipartResolver; import org.springframework.web.servlet.DispatcherServlet; /** * Base class for HTTP request handling endpoints. * <p/> * By default GET and POST requests are accepted, but the 'supportedMethods' property may be set to include others or * limit the options (e.g. POST only). A GET request will generate a payload containing its 'parameterMap' while a POST * request will be converted to a Message payload according to the registered {@link HttpMessageConverter}s. Several are * registered by default, but the list can be explicitly set via {@link #setMessageConverters(List)}. * <p/> * To customize the mapping of request headers to the MessageHeaders, provide a reference to a {@link HeaderMapper * HeaderMapper<HttpHeaders>} implementation to the {@link #setHeaderMapper(HeaderMapper)} method. * <p/> * The behavior is "request/reply" by default. Pass <code>false</code> to the constructor to force send-only as opposed * to sendAndReceive. Send-only means that as soon as the Message is created and passed to the * {@link #setRequestChannel(org.springframework.integration.MessageChannel) request channel}, a response will be * generated. Subclasses determine how that response is generated (e.g. simple status response or rendering a View). * <p/> * In a request-reply scenario, the reply Message's payload will be extracted prior to generating a response by default. * To have the entire serialized Message available for the response, switch the {@link #extractReplyPayload} value to * <code>false</code>. * * @author Mark Fisher * @since 2.0 */ abstract class HttpRequestHandlingEndpointSupport extends MessagingGatewaySupport { private static final boolean jaxb2Present = ClassUtils.isPresent("javax.xml.bind.Binder", HttpRequestHandlingEndpointSupport.class.getClassLoader()); private static final boolean jacksonPresent = ClassUtils.isPresent("org.codehaus.jackson.map.ObjectMapper", HttpRequestHandlingEndpointSupport.class.getClassLoader()) && ClassUtils.isPresent("org.codehaus.jackson.JsonGenerator", HttpRequestHandlingEndpointSupport.class .getClassLoader()); private static boolean romePresent = ClassUtils.isPresent("com.sun.syndication.feed.WireFeed", HttpRequestHandlingEndpointSupport.class.getClassLoader()); private volatile List<HttpMethod> supportedMethods = Arrays.asList(HttpMethod.GET, HttpMethod.POST); private volatile Class<?> requestPayloadType = null; private volatile List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>(); private volatile HeaderMapper<HttpHeaders> headerMapper = DefaultHttpHeaderMapper.inboundMapper(); private final boolean expectReply; private volatile boolean extractReplyPayload = true; private volatile MultipartResolver multipartResolver; public HttpRequestHandlingEndpointSupport() { this(true); } @SuppressWarnings("rawtypes") public HttpRequestHandlingEndpointSupport(boolean expectReply) { this.expectReply = expectReply; this.messageConverters.add(new MultipartAwareFormHttpMessageConverter()); this.messageConverters.add(new SerializingHttpMessageConverter()); this.messageConverters.add(new ByteArrayHttpMessageConverter()); this.messageConverters.add(new StringHttpMessageConverter()); this.messageConverters.add(new ResourceHttpMessageConverter()); this.messageConverters.add(new SourceHttpMessageConverter()); if (jaxb2Present) { this.messageConverters.add(new Jaxb2RootElementHttpMessageConverter()); } if (jacksonPresent) { this.messageConverters.add(new MappingJacksonHttpMessageConverter()); } if (romePresent) { // TODO add deps for: // this.messageConverters.add(new AtomFeedHttpMessageConverter()); // this.messageConverters.add(new RssChannelHttpMessageConverter()); } } /** * @return whether to expect reply */ protected boolean isExpectReply() { return expectReply; } /** * Set the message body converters to use. These converters are used to convert from and to HTTP requests and * responses. */ public void setMessageConverters(List<HttpMessageConverter<?>> messageConverters) { Assert.notEmpty(messageConverters, "'messageConverters' must not be empty"); this.messageConverters = messageConverters; } protected List<HttpMessageConverter<?>> getMessageConverters() { return this.messageConverters; } /** * Set the {@link HeaderMapper} to use when mapping between HTTP headers and MessageHeaders. */ public void setHeaderMapper(HeaderMapper<HttpHeaders> headerMapper) { Assert.notNull(headerMapper, "headerMapper must not be null"); this.headerMapper = headerMapper; } /** * Specify the supported request method names for this gateway. By default, only GET and POST are supported. */ public void setSupportedMethodNames(String... supportedMethods) { Assert.notEmpty(supportedMethods, "at least one supported method is required"); HttpMethod[] methodArray = new HttpMethod[supportedMethods.length]; for (int i = 0; i < methodArray.length; i++) { methodArray[i] = HttpMethod.valueOf(supportedMethods[i].toUpperCase()); } this.supportedMethods = Arrays.asList(methodArray); } /** * Specify the supported request methods for this gateway. By default, only GET and POST are supported. */ public void setSupportedMethods(HttpMethod... supportedMethods) { Assert.notEmpty(supportedMethods, "at least one supported method is required"); this.supportedMethods = Arrays.asList(supportedMethods); } /** * Specify the type of payload to be generated when the inbound HTTP request content is read by the * {@link HttpMessageConverter}s. By default this value is null which means at runtime any "text" Content-Type will * result in String while all others default to <code>byte[].class</code>. */ public void setRequestPayloadType(Class<?> requestPayloadType) { this.requestPayloadType = requestPayloadType; } /** * Specify whether only the reply Message's payload should be passed in the response. If this is set to 'false', the * entire Message will be used to generate the response. The default is 'true'. */ public void setExtractReplyPayload(boolean extractReplyPayload) { this.extractReplyPayload = extractReplyPayload; } /** * Specify the {@link MultipartResolver} to use when checking requests. If no resolver is provided, the * "multipartResolver" bean in the context will be used as a fallback. If that is not available either, this * endpoint will not support multipart requests. */ public void setMultipartResolver(MultipartResolver multipartResolver) { this.multipartResolver = multipartResolver; } @Override public String getComponentType() { return (this.expectReply) ? "http:inbound-gateway" : "http:inbound-channel-adapter"; } /** * Locates the {@link MultipartResolver} bean based on the default name defined by the * {@link DispatcherServlet#MULTIPART_RESOLVER_BEAN_NAME} constant if available. */ @Override protected void onInit() throws Exception { super.onInit(); BeanFactory beanFactory = this.getBeanFactory(); if (this.multipartResolver == null && beanFactory != null) { try { MultipartResolver multipartResolver = this.getBeanFactory().getBean( DispatcherServlet.MULTIPART_RESOLVER_BEAN_NAME, MultipartResolver.class); if (logger.isDebugEnabled()) { logger.debug("Using MultipartResolver [" + multipartResolver + "]"); } this.multipartResolver = multipartResolver; } catch (NoSuchBeanDefinitionException e) { if (logger.isDebugEnabled()) { logger.debug("Unable to locate MultipartResolver with name '" + DispatcherServlet.MULTIPART_RESOLVER_BEAN_NAME + "': no multipart request handling will be supported."); } } } } /** * Handles the HTTP request by generating a Message and sending it to the request channel. If this gateway's * 'expectReply' property is true, it will also generate a response from the reply Message once received. */ protected final Object doHandleRequest(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws IOException { try { ServletServerHttpRequest request = this.prepareRequest(servletRequest); if (!this.supportedMethods.contains(request.getMethod())) { servletResponse.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED); return null; } Object payload = null; if (this.isReadable(request)) { payload = this.generatePayloadFromRequestBody(request); } else { payload = this.convertParameterMap(servletRequest.getParameterMap()); } Map<String, ?> headers = this.headerMapper.toHeaders(request.getHeaders()); Message<?> message = MessageBuilder.withPayload(payload).copyHeaders(headers).setHeader( org.springframework.integration.http.HttpHeaders.REQUEST_URL, request.getURI().toString()) .setHeader(org.springframework.integration.http.HttpHeaders.REQUEST_METHOD, request.getMethod().toString()).setHeader( org.springframework.integration.http.HttpHeaders.USER_PRINCIPAL, servletRequest.getUserPrincipal()).build(); Object reply = null; if (this.expectReply) { reply = this.sendAndReceiveMessage(message); if (reply != null) { ServletServerHttpResponse response = new ServletServerHttpResponse(servletResponse); this.headerMapper.fromHeaders(((Message<?>) reply).getHeaders(), response.getHeaders()); + response.close(); if (this.extractReplyPayload) { reply = ((Message<?>) reply).getPayload(); } } } else { this.send(message); } return reply; } finally { this.postProcessRequest(servletRequest); } } /** * Prepares an instance of {@link ServletServerHttpRequest} from the raw {@link HttpServletRequest}. Also converts * the request into a multipart request to make multiparts available if necessary. If no multipart resolver is set, * simply returns the existing request. * @param request current HTTP request * @return the processed request (multipart wrapper if necessary) * @see MultipartResolver#resolveMultipart */ private ServletServerHttpRequest prepareRequest(HttpServletRequest servletRequest) { if (servletRequest instanceof MultipartHttpServletRequest) { return new MultipartHttpInputMessage((MultipartHttpServletRequest) servletRequest); } if (this.multipartResolver != null && this.multipartResolver.isMultipart(servletRequest)) { return new MultipartHttpInputMessage(this.multipartResolver.resolveMultipart(servletRequest)); } return new ServletServerHttpRequest(servletRequest); } /** * Checks if the request has a readable body (not a GET, HEAD, or OPTIONS request) and a Content-Type header. */ private boolean isReadable(ServletServerHttpRequest request) { HttpMethod method = request.getMethod(); if (HttpMethod.GET.equals(method) || HttpMethod.HEAD.equals(method) || HttpMethod.OPTIONS.equals(method)) { return false; } return request.getHeaders().getContentType() != null; } /** * Clean up any resources used by the given multipart request (if any). * @param request current HTTP request * @see MultipartResolver#cleanupMultipart */ private void postProcessRequest(HttpServletRequest request) { if (this.multipartResolver != null && request instanceof MultipartHttpServletRequest) { this.multipartResolver.cleanupMultipart((MultipartHttpServletRequest) request); } } /** * Converts a servlet request's parameterMap to a {@link MultiValueMap}. */ @SuppressWarnings("rawtypes") private LinkedMultiValueMap<String, String> convertParameterMap(Map parameterMap) { LinkedMultiValueMap<String, String> convertedMap = new LinkedMultiValueMap<String, String>(); for (Object key : parameterMap.keySet()) { String[] values = (String[]) parameterMap.get(key); for (String value : values) { convertedMap.add((String) key, value); } } return convertedMap; } @SuppressWarnings({"unchecked", "rawtypes"}) private Object generatePayloadFromRequestBody(ServletServerHttpRequest request) throws IOException { MediaType contentType = request.getHeaders().getContentType(); Class<?> expectedType = this.requestPayloadType; if (expectedType == null) { expectedType = ("text".equals(contentType.getType())) ? String.class : byte[].class; } for (HttpMessageConverter<?> converter : this.messageConverters) { if (converter.canRead(expectedType, contentType)) { return converter.read((Class) expectedType, request); } } throw new MessagingException( "Could not convert request: no suitable HttpMessageConverter found for expected type [" + expectedType.getName() + "] and content type [" + contentType + "]"); } }
true
true
protected final Object doHandleRequest(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws IOException { try { ServletServerHttpRequest request = this.prepareRequest(servletRequest); if (!this.supportedMethods.contains(request.getMethod())) { servletResponse.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED); return null; } Object payload = null; if (this.isReadable(request)) { payload = this.generatePayloadFromRequestBody(request); } else { payload = this.convertParameterMap(servletRequest.getParameterMap()); } Map<String, ?> headers = this.headerMapper.toHeaders(request.getHeaders()); Message<?> message = MessageBuilder.withPayload(payload).copyHeaders(headers).setHeader( org.springframework.integration.http.HttpHeaders.REQUEST_URL, request.getURI().toString()) .setHeader(org.springframework.integration.http.HttpHeaders.REQUEST_METHOD, request.getMethod().toString()).setHeader( org.springframework.integration.http.HttpHeaders.USER_PRINCIPAL, servletRequest.getUserPrincipal()).build(); Object reply = null; if (this.expectReply) { reply = this.sendAndReceiveMessage(message); if (reply != null) { ServletServerHttpResponse response = new ServletServerHttpResponse(servletResponse); this.headerMapper.fromHeaders(((Message<?>) reply).getHeaders(), response.getHeaders()); if (this.extractReplyPayload) { reply = ((Message<?>) reply).getPayload(); } } } else { this.send(message); } return reply; } finally { this.postProcessRequest(servletRequest); } }
protected final Object doHandleRequest(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws IOException { try { ServletServerHttpRequest request = this.prepareRequest(servletRequest); if (!this.supportedMethods.contains(request.getMethod())) { servletResponse.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED); return null; } Object payload = null; if (this.isReadable(request)) { payload = this.generatePayloadFromRequestBody(request); } else { payload = this.convertParameterMap(servletRequest.getParameterMap()); } Map<String, ?> headers = this.headerMapper.toHeaders(request.getHeaders()); Message<?> message = MessageBuilder.withPayload(payload).copyHeaders(headers).setHeader( org.springframework.integration.http.HttpHeaders.REQUEST_URL, request.getURI().toString()) .setHeader(org.springframework.integration.http.HttpHeaders.REQUEST_METHOD, request.getMethod().toString()).setHeader( org.springframework.integration.http.HttpHeaders.USER_PRINCIPAL, servletRequest.getUserPrincipal()).build(); Object reply = null; if (this.expectReply) { reply = this.sendAndReceiveMessage(message); if (reply != null) { ServletServerHttpResponse response = new ServletServerHttpResponse(servletResponse); this.headerMapper.fromHeaders(((Message<?>) reply).getHeaders(), response.getHeaders()); response.close(); if (this.extractReplyPayload) { reply = ((Message<?>) reply).getPayload(); } } } else { this.send(message); } return reply; } finally { this.postProcessRequest(servletRequest); } }
diff --git a/src/com/orangeleap/tangerine/web/flow/batch/ErrorBatchAction.java b/src/com/orangeleap/tangerine/web/flow/batch/ErrorBatchAction.java index 8388e875..aaea44a2 100644 --- a/src/com/orangeleap/tangerine/web/flow/batch/ErrorBatchAction.java +++ b/src/com/orangeleap/tangerine/web/flow/batch/ErrorBatchAction.java @@ -1,259 +1,262 @@ /* * Copyright (c) 2009. Orange Leap Inc. Active Constituent * Relationship Management Platform. * * 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 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 com.orangeleap.tangerine.web.flow.batch; import com.orangeleap.tangerine.controller.TangerineForm; import com.orangeleap.tangerine.domain.PostBatch; import com.orangeleap.tangerine.type.PageType; import com.orangeleap.tangerine.util.OLLogger; import com.orangeleap.tangerine.util.StringConstants; import com.orangeleap.tangerine.util.TangerineMessageAccessor; import com.orangeleap.tangerine.web.common.SortInfo; import com.orangeleap.tangerine.web.customization.tag.fields.handlers.ExtTypeHandler; import org.apache.commons.logging.Log; import org.springframework.stereotype.Component; import org.springframework.ui.ModelMap; import org.springframework.util.StringUtils; import org.springframework.webflow.execution.RequestContext; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; @Component("errorBatchAction") public class ErrorBatchAction extends EditBatchAction { protected final Log logger = OLLogger.getLog(getClass()); /** * Display the batch description for this error batch * @param flowRequestContext * @param batchId * @return model */ @SuppressWarnings("unchecked") public ModelMap errorStep1(final RequestContext flowRequestContext, final Long batchId) { if (logger.isTraceEnabled()) { logger.trace("errorStep1: batchId = " + batchId); } tangerineListHelper.checkAccess(getRequest(flowRequestContext), PageType.createBatch); // TODO: do as annotation determineStepToSave(flowRequestContext); PostBatch batch = getBatchFromFlowScope(flowRequestContext); if (batch == null || (batchId != null && ! batchId.equals(batch.getId()))) { batch = postBatchService.readBatch(batchId); setFlowScopeAttribute(flowRequestContext, batch, StringConstants.BATCH); } final ModelMap model = new ModelMap(); model.put(StringConstants.SUCCESS, Boolean.TRUE); if (batch != null) { final Map<String, String> dataMap = new HashMap<String, String>(); dataMap.put("batchDesc", (String) escapeStringValues(batch.getBatchDesc())); dataMap.put("batchType", TangerineMessageAccessor.getMessage(batch.getBatchType())); dataMap.put("criteriaFields", batch.isForTouchPoints() ? TangerineMessageAccessor.getMessage("touchPointFields") : TangerineMessageAccessor.getMessage("batchTypeFields")); dataMap.put("hiddenErrorBatchType", batch.getBatchType()); model.put(StringConstants.DATA, dataMap); } return model; } /** * Display the rows that make up this error batch, in addition to the actual errors * @param flowRequestContext * @return model */ @SuppressWarnings("unchecked") public ModelMap errorStep2(final RequestContext flowRequestContext) { if (logger.isTraceEnabled()) { logger.trace("errorStep2:"); } tangerineListHelper.checkAccess(getRequest(flowRequestContext), PageType.createBatch); // TODO: do as annotation determineStepToSave(flowRequestContext); final SortInfo sortInfo = getSortInfo(flowRequestContext); final PostBatch batch = getBatchFromFlowScope(flowRequestContext); final ModelMap model = new ModelMap(); // MetaData final Map<String, Object> metaDataMap = tangerineListHelper.initMetaData(sortInfo.getStart(), sortInfo.getLimit()); final Map<String, String> sortInfoMap = new HashMap<String, String>(); if ( ! StringUtils.hasText(sortInfo.getSort()) || (StringConstants.GIFT.equals(batch.getBatchType()) && ( ! sortInfo.getSort().equals(StringConstants.GIFT_ID) && ! sortInfo.getSort().equals("errorMsg"))) || (StringConstants.ADJUSTED_GIFT.equals(batch.getBatchType()) && ( ! sortInfo.getSort().equals(StringConstants.ADJUSTED_GIFT_ID) && ! sortInfo.getSort().equals("errorMsg"))) || (StringConstants.CONSTITUENT.equals(batch.getBatchType()) && ( ! sortInfo.getSort().equals(StringConstants.CONSTITUENT_ID) && ! sortInfo.getSort().equals("errorMsg"))) ) { if (StringConstants.GIFT.equals(batch.getBatchType())) { sortInfo.setSort(StringConstants.GIFT_ID); } else if (StringConstants.ADJUSTED_GIFT.equals(batch.getBatchType())) { sortInfo.setSort(StringConstants.ADJUSTED_GIFT_ID); } else if (StringConstants.CONSTITUENT.equals(batch.getBatchType())) { sortInfo.setSort(StringConstants.CONSTITUENT_ID); } sortInfo.setDir(StringConstants.ASC); } sortInfoMap.put(StringConstants.FIELD, sortInfo.getSort()); sortInfoMap.put(StringConstants.DIRECTION, sortInfo.getDir()); metaDataMap.put(StringConstants.SORT_INFO, sortInfoMap); final List<Map<String, Object>> rowList = postBatchService.readPostBatchEntryErrorsByBatchId(batch.getId(), sortInfo); addUniqueSequenceAsIdEscapeErrorMsg(rowList); final int totalRows = postBatchService.countPostBatchEntryErrorsByBatchId(batch.getId()); // Fields final List<Map<String, Object>> fieldList = new ArrayList<Map<String, Object>>(); String idName = null; String constituentIdName = null; if (StringConstants.GIFT.equals(batch.getBatchType())) { idName = TangerineForm.escapeFieldName(StringConstants.GIFT_ID); constituentIdName = "giftConstituentId"; } else if (StringConstants.ADJUSTED_GIFT.equals(batch.getBatchType())) { idName = TangerineForm.escapeFieldName(StringConstants.ADJUSTED_GIFT_ID); constituentIdName = "adjustedGiftConstituentId"; } + else if (StringConstants.CONSTITUENT.equals(batch.getBatchType())) { + idName = TangerineForm.escapeFieldName(StringConstants.CONSTITUENT_ID); + } if (idName != null) { Map<String, Object> fieldMap = new HashMap<String, Object>(); fieldMap.put(StringConstants.NAME, idName); fieldMap.put(StringConstants.MAPPING, idName); fieldMap.put(StringConstants.TYPE, ExtTypeHandler.EXT_INT); fieldMap.put(StringConstants.HEADER, escapeStringValues(TangerineMessageAccessor.getMessage(StringConstants.ID))); fieldList.add(fieldMap); } Map<String, Object> fieldMap = new HashMap<String, Object>(); String errorMsg = TangerineForm.escapeFieldName("errorMsg"); fieldMap.put(StringConstants.NAME, errorMsg); fieldMap.put(StringConstants.MAPPING, errorMsg); fieldMap.put(StringConstants.TYPE, ExtTypeHandler.EXT_STRING); fieldMap.put(StringConstants.HEADER, escapeStringValues(TangerineMessageAccessor.getMessage("errors"))); fieldList.add(fieldMap); if (constituentIdName != null) { fieldMap = new HashMap<String, Object>(); fieldMap.put(StringConstants.NAME, constituentIdName); fieldMap.put(StringConstants.MAPPING, constituentIdName); fieldMap.put(StringConstants.TYPE, ExtTypeHandler.EXT_INT); fieldMap.put(StringConstants.HEADER, escapeStringValues(TangerineMessageAccessor.getMessage(StringConstants.CONSTITUENT_ID))); fieldList.add(fieldMap); } metaDataMap.put(StringConstants.FIELDS, fieldList); model.put(StringConstants.META_DATA, metaDataMap); model.put(StringConstants.TOTAL_ROWS, totalRows); model.put(StringConstants.ROWS, rowList); model.put(StringConstants.SUCCESS, Boolean.TRUE); return model; } /** * Get the batch update fields * @param flowRequestContext * @return model */ @SuppressWarnings("unchecked") public ModelMap errorStep3(final RequestContext flowRequestContext) { if (logger.isTraceEnabled()) { logger.trace("errorStep3:"); } tangerineListHelper.checkAccess(getRequest(flowRequestContext), PageType.createBatch); // TODO: do as annotation determineStepToSave(flowRequestContext); return findUpdateFields(flowRequestContext); } /** * Show the update field changes (before and after) * @param flowRequestContext * @return model */ @SuppressWarnings("unchecked") public ModelMap errorStep4(final RequestContext flowRequestContext) { if (logger.isTraceEnabled()) { logger.trace("errorStep4:"); } tangerineListHelper.checkAccess(getRequest(flowRequestContext), PageType.createBatch); // TODO: do as annotation determineStepToSave(flowRequestContext); final PostBatch batch = getBatchFromFlowScope(flowRequestContext); final SortInfo sortInfo = getSortInfo(flowRequestContext); final ModelMap model = new ModelMap(); initReviewUpdateFields(batch, model, sortInfo); final List<Map<String, Object>> rowValues = new ArrayList<Map<String, Object>>(); List rows = null; int totalRows = 0; unescapeSortField(sortInfo); if (StringConstants.GIFT.equals(batch.getBatchType())) { final Set<Long> giftIds = batch.getEntryGiftIds(); rows = giftService.readLimitedGiftsByIds(giftIds, sortInfo, getRequest(flowRequestContext).getLocale()); totalRows = giftIds.size(); } else if (StringConstants.ADJUSTED_GIFT.equals(batch.getBatchType())) { final Set<Long> adjustedGiftIds = batch.getEntryAdjustedGiftIds(); rows = adjustedGiftService.readLimitedAdjustedGiftsByIds(adjustedGiftIds, sortInfo, getRequest(flowRequestContext).getLocale()); totalRows = adjustedGiftIds.size(); } else if (StringConstants.CONSTITUENT.equals(batch.getBatchType())) { final Set<Long> constituentIds = batch.getEntryConstituentIds(); rows = constituentService.readLimitedConstituentsByIds(constituentIds, sortInfo, getRequest(flowRequestContext).getLocale()); totalRows = constituentIds.size(); } contrastUpdatedValues(batch, rows, rowValues, batch.getUpdateFields()); model.put(StringConstants.ROWS, rowValues); model.put(StringConstants.TOTAL_ROWS, totalRows); model.put(StringConstants.SUCCESS, Boolean.TRUE); return model; } protected void determineStepToSave(final RequestContext flowRequestContext) { final String previousStep = getRequestParameter(flowRequestContext, PREVIOUS_STEP); if ("step1Error".equals(previousStep)) { saveBatchDesc(flowRequestContext); } else if ("step3Error".equals(previousStep)) { saveBatchUpdateFields(flowRequestContext); } } private void saveBatchDesc(final RequestContext flowRequestContext) { final PostBatch batch = getBatchFromFlowScope(flowRequestContext); if (batch != null) { final String batchDesc = getRequestParameter(flowRequestContext, StringConstants.BATCH_DESC); batch.setBatchDesc(batchDesc); } } private void addUniqueSequenceAsIdEscapeErrorMsg(final List<Map<String, Object>> rowList) { for (int x = 0; x < rowList.size(); x++) { final Map<String, Object> rowMap = rowList.get(x); rowMap.put(StringConstants.ID, x); rowMap.put(TangerineForm.escapeFieldName("errorMsg"), escapeStringValues(rowMap.get(TangerineForm.escapeFieldName("errorMsg")))); } } }
true
true
public ModelMap errorStep2(final RequestContext flowRequestContext) { if (logger.isTraceEnabled()) { logger.trace("errorStep2:"); } tangerineListHelper.checkAccess(getRequest(flowRequestContext), PageType.createBatch); // TODO: do as annotation determineStepToSave(flowRequestContext); final SortInfo sortInfo = getSortInfo(flowRequestContext); final PostBatch batch = getBatchFromFlowScope(flowRequestContext); final ModelMap model = new ModelMap(); // MetaData final Map<String, Object> metaDataMap = tangerineListHelper.initMetaData(sortInfo.getStart(), sortInfo.getLimit()); final Map<String, String> sortInfoMap = new HashMap<String, String>(); if ( ! StringUtils.hasText(sortInfo.getSort()) || (StringConstants.GIFT.equals(batch.getBatchType()) && ( ! sortInfo.getSort().equals(StringConstants.GIFT_ID) && ! sortInfo.getSort().equals("errorMsg"))) || (StringConstants.ADJUSTED_GIFT.equals(batch.getBatchType()) && ( ! sortInfo.getSort().equals(StringConstants.ADJUSTED_GIFT_ID) && ! sortInfo.getSort().equals("errorMsg"))) || (StringConstants.CONSTITUENT.equals(batch.getBatchType()) && ( ! sortInfo.getSort().equals(StringConstants.CONSTITUENT_ID) && ! sortInfo.getSort().equals("errorMsg"))) ) { if (StringConstants.GIFT.equals(batch.getBatchType())) { sortInfo.setSort(StringConstants.GIFT_ID); } else if (StringConstants.ADJUSTED_GIFT.equals(batch.getBatchType())) { sortInfo.setSort(StringConstants.ADJUSTED_GIFT_ID); } else if (StringConstants.CONSTITUENT.equals(batch.getBatchType())) { sortInfo.setSort(StringConstants.CONSTITUENT_ID); } sortInfo.setDir(StringConstants.ASC); } sortInfoMap.put(StringConstants.FIELD, sortInfo.getSort()); sortInfoMap.put(StringConstants.DIRECTION, sortInfo.getDir()); metaDataMap.put(StringConstants.SORT_INFO, sortInfoMap); final List<Map<String, Object>> rowList = postBatchService.readPostBatchEntryErrorsByBatchId(batch.getId(), sortInfo); addUniqueSequenceAsIdEscapeErrorMsg(rowList); final int totalRows = postBatchService.countPostBatchEntryErrorsByBatchId(batch.getId()); // Fields final List<Map<String, Object>> fieldList = new ArrayList<Map<String, Object>>(); String idName = null; String constituentIdName = null; if (StringConstants.GIFT.equals(batch.getBatchType())) { idName = TangerineForm.escapeFieldName(StringConstants.GIFT_ID); constituentIdName = "giftConstituentId"; } else if (StringConstants.ADJUSTED_GIFT.equals(batch.getBatchType())) { idName = TangerineForm.escapeFieldName(StringConstants.ADJUSTED_GIFT_ID); constituentIdName = "adjustedGiftConstituentId"; } if (idName != null) { Map<String, Object> fieldMap = new HashMap<String, Object>(); fieldMap.put(StringConstants.NAME, idName); fieldMap.put(StringConstants.MAPPING, idName); fieldMap.put(StringConstants.TYPE, ExtTypeHandler.EXT_INT); fieldMap.put(StringConstants.HEADER, escapeStringValues(TangerineMessageAccessor.getMessage(StringConstants.ID))); fieldList.add(fieldMap); } Map<String, Object> fieldMap = new HashMap<String, Object>(); String errorMsg = TangerineForm.escapeFieldName("errorMsg"); fieldMap.put(StringConstants.NAME, errorMsg); fieldMap.put(StringConstants.MAPPING, errorMsg); fieldMap.put(StringConstants.TYPE, ExtTypeHandler.EXT_STRING); fieldMap.put(StringConstants.HEADER, escapeStringValues(TangerineMessageAccessor.getMessage("errors"))); fieldList.add(fieldMap); if (constituentIdName != null) { fieldMap = new HashMap<String, Object>(); fieldMap.put(StringConstants.NAME, constituentIdName); fieldMap.put(StringConstants.MAPPING, constituentIdName); fieldMap.put(StringConstants.TYPE, ExtTypeHandler.EXT_INT); fieldMap.put(StringConstants.HEADER, escapeStringValues(TangerineMessageAccessor.getMessage(StringConstants.CONSTITUENT_ID))); fieldList.add(fieldMap); } metaDataMap.put(StringConstants.FIELDS, fieldList); model.put(StringConstants.META_DATA, metaDataMap); model.put(StringConstants.TOTAL_ROWS, totalRows); model.put(StringConstants.ROWS, rowList); model.put(StringConstants.SUCCESS, Boolean.TRUE); return model; }
public ModelMap errorStep2(final RequestContext flowRequestContext) { if (logger.isTraceEnabled()) { logger.trace("errorStep2:"); } tangerineListHelper.checkAccess(getRequest(flowRequestContext), PageType.createBatch); // TODO: do as annotation determineStepToSave(flowRequestContext); final SortInfo sortInfo = getSortInfo(flowRequestContext); final PostBatch batch = getBatchFromFlowScope(flowRequestContext); final ModelMap model = new ModelMap(); // MetaData final Map<String, Object> metaDataMap = tangerineListHelper.initMetaData(sortInfo.getStart(), sortInfo.getLimit()); final Map<String, String> sortInfoMap = new HashMap<String, String>(); if ( ! StringUtils.hasText(sortInfo.getSort()) || (StringConstants.GIFT.equals(batch.getBatchType()) && ( ! sortInfo.getSort().equals(StringConstants.GIFT_ID) && ! sortInfo.getSort().equals("errorMsg"))) || (StringConstants.ADJUSTED_GIFT.equals(batch.getBatchType()) && ( ! sortInfo.getSort().equals(StringConstants.ADJUSTED_GIFT_ID) && ! sortInfo.getSort().equals("errorMsg"))) || (StringConstants.CONSTITUENT.equals(batch.getBatchType()) && ( ! sortInfo.getSort().equals(StringConstants.CONSTITUENT_ID) && ! sortInfo.getSort().equals("errorMsg"))) ) { if (StringConstants.GIFT.equals(batch.getBatchType())) { sortInfo.setSort(StringConstants.GIFT_ID); } else if (StringConstants.ADJUSTED_GIFT.equals(batch.getBatchType())) { sortInfo.setSort(StringConstants.ADJUSTED_GIFT_ID); } else if (StringConstants.CONSTITUENT.equals(batch.getBatchType())) { sortInfo.setSort(StringConstants.CONSTITUENT_ID); } sortInfo.setDir(StringConstants.ASC); } sortInfoMap.put(StringConstants.FIELD, sortInfo.getSort()); sortInfoMap.put(StringConstants.DIRECTION, sortInfo.getDir()); metaDataMap.put(StringConstants.SORT_INFO, sortInfoMap); final List<Map<String, Object>> rowList = postBatchService.readPostBatchEntryErrorsByBatchId(batch.getId(), sortInfo); addUniqueSequenceAsIdEscapeErrorMsg(rowList); final int totalRows = postBatchService.countPostBatchEntryErrorsByBatchId(batch.getId()); // Fields final List<Map<String, Object>> fieldList = new ArrayList<Map<String, Object>>(); String idName = null; String constituentIdName = null; if (StringConstants.GIFT.equals(batch.getBatchType())) { idName = TangerineForm.escapeFieldName(StringConstants.GIFT_ID); constituentIdName = "giftConstituentId"; } else if (StringConstants.ADJUSTED_GIFT.equals(batch.getBatchType())) { idName = TangerineForm.escapeFieldName(StringConstants.ADJUSTED_GIFT_ID); constituentIdName = "adjustedGiftConstituentId"; } else if (StringConstants.CONSTITUENT.equals(batch.getBatchType())) { idName = TangerineForm.escapeFieldName(StringConstants.CONSTITUENT_ID); } if (idName != null) { Map<String, Object> fieldMap = new HashMap<String, Object>(); fieldMap.put(StringConstants.NAME, idName); fieldMap.put(StringConstants.MAPPING, idName); fieldMap.put(StringConstants.TYPE, ExtTypeHandler.EXT_INT); fieldMap.put(StringConstants.HEADER, escapeStringValues(TangerineMessageAccessor.getMessage(StringConstants.ID))); fieldList.add(fieldMap); } Map<String, Object> fieldMap = new HashMap<String, Object>(); String errorMsg = TangerineForm.escapeFieldName("errorMsg"); fieldMap.put(StringConstants.NAME, errorMsg); fieldMap.put(StringConstants.MAPPING, errorMsg); fieldMap.put(StringConstants.TYPE, ExtTypeHandler.EXT_STRING); fieldMap.put(StringConstants.HEADER, escapeStringValues(TangerineMessageAccessor.getMessage("errors"))); fieldList.add(fieldMap); if (constituentIdName != null) { fieldMap = new HashMap<String, Object>(); fieldMap.put(StringConstants.NAME, constituentIdName); fieldMap.put(StringConstants.MAPPING, constituentIdName); fieldMap.put(StringConstants.TYPE, ExtTypeHandler.EXT_INT); fieldMap.put(StringConstants.HEADER, escapeStringValues(TangerineMessageAccessor.getMessage(StringConstants.CONSTITUENT_ID))); fieldList.add(fieldMap); } metaDataMap.put(StringConstants.FIELDS, fieldList); model.put(StringConstants.META_DATA, metaDataMap); model.put(StringConstants.TOTAL_ROWS, totalRows); model.put(StringConstants.ROWS, rowList); model.put(StringConstants.SUCCESS, Boolean.TRUE); return model; }
diff --git a/app/src/processing/app/debug/AvrdudeUploader.java b/app/src/processing/app/debug/AvrdudeUploader.java index 641e4412..a9254d99 100755 --- a/app/src/processing/app/debug/AvrdudeUploader.java +++ b/app/src/processing/app/debug/AvrdudeUploader.java @@ -1,334 +1,335 @@ /* -*- mode: jde; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* AvrdudeUploader - uploader implementation using avrdude Part of the Arduino project - http://www.arduino.cc/ Copyright (c) 2004-05 Hernando Barragan 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 $Id$ */ package processing.app.debug; import processing.app.Base; import processing.app.Preferences; import processing.app.Serial; import processing.app.SerialException; import static processing.app.I18n._; import java.io.*; import java.util.*; import java.util.zip.*; import javax.swing.*; import gnu.io.*; public class AvrdudeUploader extends Uploader { public AvrdudeUploader() { } public boolean uploadUsingPreferences(String buildPath, String className, boolean usingProgrammer) throws RunnerException, SerialException { this.verbose = verbose; Map<String, String> boardPreferences = Base.getBoardPreferences(); // if no protocol is specified for this board, assume it lacks a // bootloader and upload using the selected programmer. if (usingProgrammer || boardPreferences.get("upload.protocol") == null) { String programmer = Preferences.get("programmer"); Target target = Base.getTarget(); if (programmer.indexOf(":") != -1) { target = Base.targetsTable.get(programmer.substring(0, programmer.indexOf(":"))); programmer = programmer.substring(programmer.indexOf(":") + 1); } Collection params = getProgrammerCommands(target, programmer); params.add("-Uflash:w:" + buildPath + File.separator + className + ".hex:i"); return avrdude(params); } return uploadViaBootloader(buildPath, className); } private boolean uploadViaBootloader(String buildPath, String className) throws RunnerException, SerialException { Map<String, String> boardPreferences = Base.getBoardPreferences(); List commandDownloader = new ArrayList(); String protocol = boardPreferences.get("upload.protocol"); // avrdude wants "stk500v1" to distinguish it from stk500v2 if (protocol.equals("stk500")) protocol = "stk500v1"; String uploadPort = Preferences.get("serial.port"); // need to do a little dance for Leonardo and derivatives: // open then close the port at the magic baudrate (usually 1200 bps) first // to signal to the sketch that it should reset into bootloader. after doing // this wait a moment for the bootloader to enumerate. On Windows, also must // deal with the fact that the COM port number changes from bootloader to // sketch. if (boardPreferences.get("bootloader.path") != null && (boardPreferences.get("bootloader.path").equals("caterina") || boardPreferences.get("bootloader.path").equals("caterina-Arduino_Robot") || boardPreferences.get("bootloader.path").equals("caterina-LilyPadUSB"))) { String caterinaUploadPort = null; try { // Toggle 1200 bps on selected serial port to force board reset. List<String> before = Serial.list(); if (before.contains(uploadPort)) { if (verbose || Preferences.getBoolean("upload.verbose")) System.out .println(_("Forcing reset using 1200bps open/close on port ") + uploadPort); Serial.touchPort(uploadPort, 1200); // Scanning for available ports seems to open the port or // otherwise assert DTR, which would cancel the WDT reset if // it happened within 250 ms. So we wait until the reset should // have already occured before we start scanning. if (!Base.isMacOS()) Thread.sleep(300); } // Wait for a port to appear on the list int elapsed = 0; while (elapsed < 10000) { List<String> now = Serial.list(); List<String> diff = new ArrayList<String>(now); diff.removeAll(before); if (verbose || Preferences.getBoolean("upload.verbose")) { System.out.print("PORTS {"); for (String p : before) System.out.print(p+", "); System.out.print("} / {"); for (String p : now) System.out.print(p+", "); System.out.print("} => {"); for (String p : diff) System.out.print(p+", "); System.out.println("}"); } if (diff.size() > 0) { caterinaUploadPort = diff.get(0); if (verbose || Preferences.getBoolean("upload.verbose")) System.out.println("Found Leonardo upload port: " + caterinaUploadPort); break; } // Keep track of port that disappears before = now; Thread.sleep(250); elapsed += 250; // On Windows, it can take a long time for the port to disappear and // come back, so use a longer time out before assuming that the selected // port is the bootloader (not the sketch). if (((!Base.isWindows() && elapsed >= 500) || elapsed >= 5000) && now.contains(uploadPort)) { if (verbose || Preferences.getBoolean("upload.verbose")) System.out.println("Uploading using selected port: " + uploadPort); caterinaUploadPort = uploadPort; break; } } if (caterinaUploadPort == null) // Something happened while detecting port throw new RunnerException( _("Couldn’t find a Leonardo on the selected port. Check that you have the correct port selected. If it is correct, try pressing the board's reset button after initiating the upload.")); uploadPort = caterinaUploadPort; } catch (SerialException e) { throw new RunnerException(e.getMessage()); } catch (InterruptedException e) { throw new RunnerException(e.getMessage()); } } commandDownloader.add("-c" + protocol); commandDownloader.add("-P" + (Base.isWindows() ? "\\\\.\\" : "") + uploadPort); commandDownloader.add( "-b" + Integer.parseInt(boardPreferences.get("upload.speed"))); commandDownloader.add("-D"); // don't erase if (!Preferences.getBoolean("upload.verify")) commandDownloader.add("-V"); // disable verify commandDownloader.add("-Uflash:w:" + buildPath + File.separator + className + ".hex:i"); if (boardPreferences.get("upload.disable_flushing") == null || boardPreferences.get("upload.disable_flushing").toLowerCase().equals("false")) { flushSerialBuffer(); } boolean avrdudeResult = avrdude(commandDownloader); // For Leonardo wait until the bootloader serial port disconnects and the sketch serial // port reconnects (or timeout after a few seconds if the sketch port never comes back). // Doing this saves users from accidentally opening Serial Monitor on the soon-to-be-orphaned // bootloader port. if (true == avrdudeResult && boardPreferences.get("bootloader.path") != null && (boardPreferences.get("bootloader.path").equals("caterina") || + boardPreferences.get("bootloader.path").equals("caterina-Arduino_Robot") || boardPreferences.get("bootloader.path").equals("caterina-LilyPadUSB"))) { try { Thread.sleep(500); } catch (InterruptedException ex) { } long timeout = System.currentTimeMillis() + 2000; while (timeout > System.currentTimeMillis()) { List<String> portList = Serial.list(); uploadPort = Preferences.get("serial.port"); if (portList.contains(uploadPort)) { try { Thread.sleep(100); // delay to avoid port in use and invalid parameters errors } catch (InterruptedException ex) { } // Remove the magic baud rate (1200bps) to avoid future unwanted board resets int serialRate = Preferences.getInteger("serial.debug_rate"); if (verbose || Preferences.getBoolean("upload.verbose")) System.out.println("Setting baud rate to " + serialRate + " on " + uploadPort); Serial.touchPort(uploadPort, serialRate); break; } try { Thread.sleep(100); } catch (InterruptedException ex) { } } } return avrdudeResult; } public boolean burnBootloader() throws RunnerException { String programmer = Preferences.get("programmer"); Target target = Base.getTarget(); if (programmer.indexOf(":") != -1) { target = Base.targetsTable.get(programmer.substring(0, programmer.indexOf(":"))); programmer = programmer.substring(programmer.indexOf(":") + 1); } return burnBootloader(getProgrammerCommands(target, programmer)); } private Collection getProgrammerCommands(Target target, String programmer) { Map<String, String> programmerPreferences = target.getProgrammers().get(programmer); List params = new ArrayList(); params.add("-c" + programmerPreferences.get("protocol")); if ("usb".equals(programmerPreferences.get("communication"))) { params.add("-Pusb"); } else if ("serial".equals(programmerPreferences.get("communication"))) { params.add("-P" + (Base.isWindows() ? "\\\\.\\" : "") + Preferences.get("serial.port")); if (programmerPreferences.get("speed") != null) { params.add("-b" + Integer.parseInt(programmerPreferences.get("speed"))); } } // XXX: add support for specifying the port address for parallel // programmers, although avrdude has a default that works in most cases. if (programmerPreferences.get("force") != null && programmerPreferences.get("force").toLowerCase().equals("true")) params.add("-F"); if (programmerPreferences.get("delay") != null) params.add("-i" + programmerPreferences.get("delay")); return params; } protected boolean burnBootloader(Collection params) throws RunnerException { Map<String, String> boardPreferences = Base.getBoardPreferences(); List fuses = new ArrayList(); fuses.add("-e"); // erase the chip if (boardPreferences.get("bootloader.unlock_bits") != null) fuses.add("-Ulock:w:" + boardPreferences.get("bootloader.unlock_bits") + ":m"); if (boardPreferences.get("bootloader.extended_fuses") != null) fuses.add("-Uefuse:w:" + boardPreferences.get("bootloader.extended_fuses") + ":m"); fuses.add("-Uhfuse:w:" + boardPreferences.get("bootloader.high_fuses") + ":m"); fuses.add("-Ulfuse:w:" + boardPreferences.get("bootloader.low_fuses") + ":m"); if (!avrdude(params, fuses)) return false; try { Thread.sleep(1000); } catch (InterruptedException e) {} Target t; List bootloader = new ArrayList(); String bootloaderPath = boardPreferences.get("bootloader.path"); if (bootloaderPath != null) { if (bootloaderPath.indexOf(':') == -1) { t = Base.getTarget(); // the current target (associated with the board) } else { String targetName = bootloaderPath.substring(0, bootloaderPath.indexOf(':')); t = Base.targetsTable.get(targetName); bootloaderPath = bootloaderPath.substring(bootloaderPath.indexOf(':') + 1); } File bootloadersFile = new File(t.getFolder(), "bootloaders"); File bootloaderFile = new File(bootloadersFile, bootloaderPath); bootloaderPath = bootloaderFile.getAbsolutePath(); bootloader.add("-Uflash:w:" + bootloaderPath + File.separator + boardPreferences.get("bootloader.file") + ":i"); } if (boardPreferences.get("bootloader.lock_bits") != null) bootloader.add("-Ulock:w:" + boardPreferences.get("bootloader.lock_bits") + ":m"); if (bootloader.size() > 0) return avrdude(params, bootloader); return true; } public boolean avrdude(Collection p1, Collection p2) throws RunnerException { ArrayList p = new ArrayList(p1); p.addAll(p2); return avrdude(p); } public boolean avrdude(Collection params) throws RunnerException { List commandDownloader = new ArrayList(); if(Base.isLinux()) { if ((new File(Base.getHardwarePath() + "/tools/" + "avrdude")).exists()) { commandDownloader.add(Base.getHardwarePath() + "/tools/" + "avrdude"); commandDownloader.add("-C" + Base.getHardwarePath() + "/tools/avrdude.conf"); } else { commandDownloader.add("avrdude"); } } else { commandDownloader.add(Base.getHardwarePath() + "/tools/avr/bin/" + "avrdude"); commandDownloader.add("-C" + Base.getHardwarePath() + "/tools/avr/etc/avrdude.conf"); } if (verbose || Preferences.getBoolean("upload.verbose")) { commandDownloader.add("-v"); commandDownloader.add("-v"); commandDownloader.add("-v"); commandDownloader.add("-v"); } else { commandDownloader.add("-q"); commandDownloader.add("-q"); } commandDownloader.add("-p" + Base.getBoardPreferences().get("build.mcu")); commandDownloader.addAll(params); return executeUploadCommand(commandDownloader); } }
true
true
private boolean uploadViaBootloader(String buildPath, String className) throws RunnerException, SerialException { Map<String, String> boardPreferences = Base.getBoardPreferences(); List commandDownloader = new ArrayList(); String protocol = boardPreferences.get("upload.protocol"); // avrdude wants "stk500v1" to distinguish it from stk500v2 if (protocol.equals("stk500")) protocol = "stk500v1"; String uploadPort = Preferences.get("serial.port"); // need to do a little dance for Leonardo and derivatives: // open then close the port at the magic baudrate (usually 1200 bps) first // to signal to the sketch that it should reset into bootloader. after doing // this wait a moment for the bootloader to enumerate. On Windows, also must // deal with the fact that the COM port number changes from bootloader to // sketch. if (boardPreferences.get("bootloader.path") != null && (boardPreferences.get("bootloader.path").equals("caterina") || boardPreferences.get("bootloader.path").equals("caterina-Arduino_Robot") || boardPreferences.get("bootloader.path").equals("caterina-LilyPadUSB"))) { String caterinaUploadPort = null; try { // Toggle 1200 bps on selected serial port to force board reset. List<String> before = Serial.list(); if (before.contains(uploadPort)) { if (verbose || Preferences.getBoolean("upload.verbose")) System.out .println(_("Forcing reset using 1200bps open/close on port ") + uploadPort); Serial.touchPort(uploadPort, 1200); // Scanning for available ports seems to open the port or // otherwise assert DTR, which would cancel the WDT reset if // it happened within 250 ms. So we wait until the reset should // have already occured before we start scanning. if (!Base.isMacOS()) Thread.sleep(300); } // Wait for a port to appear on the list int elapsed = 0; while (elapsed < 10000) { List<String> now = Serial.list(); List<String> diff = new ArrayList<String>(now); diff.removeAll(before); if (verbose || Preferences.getBoolean("upload.verbose")) { System.out.print("PORTS {"); for (String p : before) System.out.print(p+", "); System.out.print("} / {"); for (String p : now) System.out.print(p+", "); System.out.print("} => {"); for (String p : diff) System.out.print(p+", "); System.out.println("}"); } if (diff.size() > 0) { caterinaUploadPort = diff.get(0); if (verbose || Preferences.getBoolean("upload.verbose")) System.out.println("Found Leonardo upload port: " + caterinaUploadPort); break; } // Keep track of port that disappears before = now; Thread.sleep(250); elapsed += 250; // On Windows, it can take a long time for the port to disappear and // come back, so use a longer time out before assuming that the selected // port is the bootloader (not the sketch). if (((!Base.isWindows() && elapsed >= 500) || elapsed >= 5000) && now.contains(uploadPort)) { if (verbose || Preferences.getBoolean("upload.verbose")) System.out.println("Uploading using selected port: " + uploadPort); caterinaUploadPort = uploadPort; break; } } if (caterinaUploadPort == null) // Something happened while detecting port throw new RunnerException( _("Couldn’t find a Leonardo on the selected port. Check that you have the correct port selected. If it is correct, try pressing the board's reset button after initiating the upload.")); uploadPort = caterinaUploadPort; } catch (SerialException e) { throw new RunnerException(e.getMessage()); } catch (InterruptedException e) { throw new RunnerException(e.getMessage()); } } commandDownloader.add("-c" + protocol); commandDownloader.add("-P" + (Base.isWindows() ? "\\\\.\\" : "") + uploadPort); commandDownloader.add( "-b" + Integer.parseInt(boardPreferences.get("upload.speed"))); commandDownloader.add("-D"); // don't erase if (!Preferences.getBoolean("upload.verify")) commandDownloader.add("-V"); // disable verify commandDownloader.add("-Uflash:w:" + buildPath + File.separator + className + ".hex:i"); if (boardPreferences.get("upload.disable_flushing") == null || boardPreferences.get("upload.disable_flushing").toLowerCase().equals("false")) { flushSerialBuffer(); } boolean avrdudeResult = avrdude(commandDownloader); // For Leonardo wait until the bootloader serial port disconnects and the sketch serial // port reconnects (or timeout after a few seconds if the sketch port never comes back). // Doing this saves users from accidentally opening Serial Monitor on the soon-to-be-orphaned // bootloader port. if (true == avrdudeResult && boardPreferences.get("bootloader.path") != null && (boardPreferences.get("bootloader.path").equals("caterina") || boardPreferences.get("bootloader.path").equals("caterina-LilyPadUSB"))) { try { Thread.sleep(500); } catch (InterruptedException ex) { } long timeout = System.currentTimeMillis() + 2000; while (timeout > System.currentTimeMillis()) { List<String> portList = Serial.list(); uploadPort = Preferences.get("serial.port"); if (portList.contains(uploadPort)) { try { Thread.sleep(100); // delay to avoid port in use and invalid parameters errors } catch (InterruptedException ex) { } // Remove the magic baud rate (1200bps) to avoid future unwanted board resets int serialRate = Preferences.getInteger("serial.debug_rate"); if (verbose || Preferences.getBoolean("upload.verbose")) System.out.println("Setting baud rate to " + serialRate + " on " + uploadPort); Serial.touchPort(uploadPort, serialRate); break; } try { Thread.sleep(100); } catch (InterruptedException ex) { } } } return avrdudeResult; }
private boolean uploadViaBootloader(String buildPath, String className) throws RunnerException, SerialException { Map<String, String> boardPreferences = Base.getBoardPreferences(); List commandDownloader = new ArrayList(); String protocol = boardPreferences.get("upload.protocol"); // avrdude wants "stk500v1" to distinguish it from stk500v2 if (protocol.equals("stk500")) protocol = "stk500v1"; String uploadPort = Preferences.get("serial.port"); // need to do a little dance for Leonardo and derivatives: // open then close the port at the magic baudrate (usually 1200 bps) first // to signal to the sketch that it should reset into bootloader. after doing // this wait a moment for the bootloader to enumerate. On Windows, also must // deal with the fact that the COM port number changes from bootloader to // sketch. if (boardPreferences.get("bootloader.path") != null && (boardPreferences.get("bootloader.path").equals("caterina") || boardPreferences.get("bootloader.path").equals("caterina-Arduino_Robot") || boardPreferences.get("bootloader.path").equals("caterina-LilyPadUSB"))) { String caterinaUploadPort = null; try { // Toggle 1200 bps on selected serial port to force board reset. List<String> before = Serial.list(); if (before.contains(uploadPort)) { if (verbose || Preferences.getBoolean("upload.verbose")) System.out .println(_("Forcing reset using 1200bps open/close on port ") + uploadPort); Serial.touchPort(uploadPort, 1200); // Scanning for available ports seems to open the port or // otherwise assert DTR, which would cancel the WDT reset if // it happened within 250 ms. So we wait until the reset should // have already occured before we start scanning. if (!Base.isMacOS()) Thread.sleep(300); } // Wait for a port to appear on the list int elapsed = 0; while (elapsed < 10000) { List<String> now = Serial.list(); List<String> diff = new ArrayList<String>(now); diff.removeAll(before); if (verbose || Preferences.getBoolean("upload.verbose")) { System.out.print("PORTS {"); for (String p : before) System.out.print(p+", "); System.out.print("} / {"); for (String p : now) System.out.print(p+", "); System.out.print("} => {"); for (String p : diff) System.out.print(p+", "); System.out.println("}"); } if (diff.size() > 0) { caterinaUploadPort = diff.get(0); if (verbose || Preferences.getBoolean("upload.verbose")) System.out.println("Found Leonardo upload port: " + caterinaUploadPort); break; } // Keep track of port that disappears before = now; Thread.sleep(250); elapsed += 250; // On Windows, it can take a long time for the port to disappear and // come back, so use a longer time out before assuming that the selected // port is the bootloader (not the sketch). if (((!Base.isWindows() && elapsed >= 500) || elapsed >= 5000) && now.contains(uploadPort)) { if (verbose || Preferences.getBoolean("upload.verbose")) System.out.println("Uploading using selected port: " + uploadPort); caterinaUploadPort = uploadPort; break; } } if (caterinaUploadPort == null) // Something happened while detecting port throw new RunnerException( _("Couldn’t find a Leonardo on the selected port. Check that you have the correct port selected. If it is correct, try pressing the board's reset button after initiating the upload.")); uploadPort = caterinaUploadPort; } catch (SerialException e) { throw new RunnerException(e.getMessage()); } catch (InterruptedException e) { throw new RunnerException(e.getMessage()); } } commandDownloader.add("-c" + protocol); commandDownloader.add("-P" + (Base.isWindows() ? "\\\\.\\" : "") + uploadPort); commandDownloader.add( "-b" + Integer.parseInt(boardPreferences.get("upload.speed"))); commandDownloader.add("-D"); // don't erase if (!Preferences.getBoolean("upload.verify")) commandDownloader.add("-V"); // disable verify commandDownloader.add("-Uflash:w:" + buildPath + File.separator + className + ".hex:i"); if (boardPreferences.get("upload.disable_flushing") == null || boardPreferences.get("upload.disable_flushing").toLowerCase().equals("false")) { flushSerialBuffer(); } boolean avrdudeResult = avrdude(commandDownloader); // For Leonardo wait until the bootloader serial port disconnects and the sketch serial // port reconnects (or timeout after a few seconds if the sketch port never comes back). // Doing this saves users from accidentally opening Serial Monitor on the soon-to-be-orphaned // bootloader port. if (true == avrdudeResult && boardPreferences.get("bootloader.path") != null && (boardPreferences.get("bootloader.path").equals("caterina") || boardPreferences.get("bootloader.path").equals("caterina-Arduino_Robot") || boardPreferences.get("bootloader.path").equals("caterina-LilyPadUSB"))) { try { Thread.sleep(500); } catch (InterruptedException ex) { } long timeout = System.currentTimeMillis() + 2000; while (timeout > System.currentTimeMillis()) { List<String> portList = Serial.list(); uploadPort = Preferences.get("serial.port"); if (portList.contains(uploadPort)) { try { Thread.sleep(100); // delay to avoid port in use and invalid parameters errors } catch (InterruptedException ex) { } // Remove the magic baud rate (1200bps) to avoid future unwanted board resets int serialRate = Preferences.getInteger("serial.debug_rate"); if (verbose || Preferences.getBoolean("upload.verbose")) System.out.println("Setting baud rate to " + serialRate + " on " + uploadPort); Serial.touchPort(uploadPort, serialRate); break; } try { Thread.sleep(100); } catch (InterruptedException ex) { } } } return avrdudeResult; }
diff --git a/cadpage/src/net/anei/cadpage/parsers/general/GeneralParser.java b/cadpage/src/net/anei/cadpage/parsers/general/GeneralParser.java index e4b84912b..c7f88918a 100644 --- a/cadpage/src/net/anei/cadpage/parsers/general/GeneralParser.java +++ b/cadpage/src/net/anei/cadpage/parsers/general/GeneralParser.java @@ -1,319 +1,320 @@ package net.anei.cadpage.parsers.general; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import net.anei.cadpage.ManagePreferences; import net.anei.cadpage.SmsMsgInfo.Data; import net.anei.cadpage.parsers.SmartAddressParser; public class GeneralParser extends SmartAddressParser { private static final Pattern DATE_PATTERN = Pattern.compile("\\b\\d\\d/\\d\\d/\\d\\d(\\d\\d)?\\b"); private static final Pattern TIME_PATTERN = Pattern.compile("\\b\\d\\d:\\d\\d\\b"); private static final Pattern DELIM_PATTERN = Pattern.compile(";|,|\\*|\\n|\\||\\b[A-Z][A-Za-z0-9-#]*:|\\bC/S:|\\b[A-Z][A-Za-z]*#"); private static final Pattern CALL_ID_PATTERN = Pattern.compile("\\d[\\d-]+\\d"); private static final Pattern UNIT_PATTERN = Pattern.compile("([A-Z]{1,4}[0-9]{1,4}\\s+)+"); // Field types that we can identify private enum FieldType {SKIP, CALL, PLACE, ADDRESS, CITY, APT, CROSS, BOX, UNIT, MAP, ID, PHONE, SUPP, CODE, SRC, NAME}; // Map of keywords to field types private Map<String, FieldType> keywordMap = new HashMap<String, FieldType>(); public GeneralParser() { super("",""); // Initialize keyword map loadMap(FieldType.SKIP, "TIME", "TOA", "DATE", "TM", "TOC"); loadMap(FieldType.CALL, "CALL", "TYPE", "TYP", "CT", "NAT", "NATURE", "INC"); loadMap(FieldType.PLACE, "NAME", "COMMON", "CN", "O"); loadMap(FieldType.ADDRESS, "ADDRESS", "LOC", "ADDR", "AD", "ADR", "ADD", "LOCATION"); loadMap(FieldType.CITY, "CITY", "CTY", "VENUE", "VEN"); loadMap(FieldType.APT, "APT", "BLDG", "BLD"); loadMap(FieldType.CROSS, "CROSS", "X", "XS", "XST", "XST2", "X-ST", "C/S", "CS", "BTWN"); loadMap(FieldType.BOX, "BOX", "BX", "ADC"); loadMap(FieldType.UNIT, "UNIT", "UNITS", "RESPONSE", "DUE", "UNTS", "UNT"); loadMap(FieldType.MAP, "MAP", "GRID", "GRIDS", "QUADRANT", "QUAD"); loadMap(FieldType.ID, "ID", "CFS", "RUN", "EVT#", "INC#"); loadMap(FieldType.PHONE, "PHONE", "PH"); loadMap(FieldType.SUPP, "INFO", "CMT", "CMT1", "CMT2", "SCRIPT", "COMMENTS", "RMK"); loadMap(FieldType.SRC, "STA", "ST", "DISP", "DIS", "DIST", "DISTRICT", "AGENCY"); loadMap(FieldType.NAME, "CALLER"); } private void loadMap(FieldType type, String ... keywords) { for (String keyword : keywords) { keywordMap.put(keyword, type); } } @Override protected boolean parseMsg(String body, Data data) { // Accept anything, but only if there is a valid sender filter + if (! ManagePreferences.overrideFilter()) return false; if (ManagePreferences.filter().length() <= 1) return false; // Starting with CAD: confuses things if (body.startsWith("CAD:")) body = body.substring(4).trim(); // Strip out any date and time fields body = DATE_PATTERN.matcher(body).replaceAll(""); body = TIME_PATTERN.matcher(body).replaceAll(""); // Parse text into different fields separated by delimiters // that match DELIM_PATTERN Matcher match = DELIM_PATTERN.matcher(body); String nextDelim = ""; int pt = 0; String last = null; boolean keywordDesc = false; boolean foundAddr = false; Result bestRes = null; String bestAddr = null; String secondAddr = null; while (nextDelim != null) { // Parse the next field String delim = nextDelim; String fld; if (match.find(pt)) { nextDelim = body.substring(match.start(), match.end()); fld = body.substring(pt, match.start()); pt = match.end(); } else { nextDelim = null; fld = body.substring(pt); } fld = fld.trim(); // fld is the data field being processed // delim is the delimiter that started this field // If zero length field, nothing to worry about if (fld.length() == 0) continue; // Check delimiter to see if this is something we recognize? FieldType type = null; if (delim.endsWith(":")) { type = keywordMap.get(delim.substring(0, delim.length()-1).toUpperCase()); } else if (delim.endsWith("#")) { type = FieldType.ID; } // If we have found a recognizable keyword, assign this field to that keyword value if (type != null) { switch (type) { case SKIP: break; case CALL: // Call description, ignore if less than 3 characters if (fld.length() <= 2) break; keywordDesc = true; // If we already have a call desc, append this to it if (data.strCall.length() > 0) { data.strCall += " / "; data.strCall += fld; } // Otherwise run it through the smart parser just in case the // call desc is followed by an address else { parseAddress(StartType.START_CALL, fld, data); if (data.strSupp.length() == 0) data.strSupp = getLeft(); } break; case PLACE: if (data.strPlace.length() == 0) data.strPlace = fld; break; case ADDRESS: // We might have multiple address fields // Keep track of which one looks like the best address // Also keep the first second place address in case we want to // use it as a call description foundAddr = true; StartType st = (data.strCall.length() == 0 ? StartType.START_CALL : data.strPlace.length() == 0 ? StartType.START_PLACE : StartType.START_SKIP); Result res = parseAddress(st, fld); if (bestRes == null || res.getStatus() > bestRes.getStatus()) { if (secondAddr == null) secondAddr = bestAddr; bestAddr = fld; bestRes = res; } else { if (secondAddr == null) secondAddr = fld; } // If we have some leading call info, use it. If not, // treat the last unidentified field as the call if (data.strCall.length() == 0 && last != null) data.strCall = last; break; case CITY: data.strCity = fld; break; case APT: if (data.strApt.length() > 0) data.strApt += "-"; data.strApt += fld; break; case CROSS: if (data.strCross.length() > 0) data.strCross += " & "; data.strCross += fld; break; case BOX: data.strBox = fld; break; case UNIT: data.strUnit = fld; break; case MAP: data.strMap = fld; break; case ID: data.strCallId = fld; break; case PHONE: data.strPhone = fld; break; case SUPP: if (data.strSupp.length() > 0) data.strSupp += " / "; data.strSupp += fld; break; case CODE: data.strCode = fld; break; case SRC: data.strSource = fld; break; case NAME: data.strName = fld; break; } } // Otherwise we have to try to figure out fields by position else { // If we haven't found an address yet, see if this is it if (!foundAddr) { StartType st = (data.strCall.length() == 0 ? StartType.START_CALL : data.strPlace.length() == 0 ? StartType.START_PLACE : StartType.START_SKIP); Result res = parseAddress(st, fld); if (res.getStatus() > 0) { // Bingo! Anything past the address goes into info foundAddr = true; res.getData(data); // If we have some leading call info, use it. If not, // treat the last unidentified field as the call if (data.strCall.length() == 0 && last != null) data.strCall = last; // If we got any call info from anywhere, extra stuff goes into info // otherwise it goes into the call description if (data.strCall.length() == 0) { data.strCall = getLeft(); } else { data.strSupp = getLeft(); } continue; } } // Does this look like a call ID? if (data.strCallId.length() == 0 && CALL_ID_PATTERN.matcher(fld).matches()) { data.strCallId = fld; continue; } // Nope, lets see if it looks like a unit list if (data.strUnit.length() == 0 && UNIT_PATTERN.matcher(fld + " ").matches()) { data.strUnit = fld; continue; } // None of the above // If we haven't found an address yet, save this field for use as a possible // call field when we find the address. if (! foundAddr) { last = fld; continue; } // If field has an &, assume it is a set of cross streets if (data.strCross.length() == 0 && fld.contains("&")) { data.strCross = fld; continue; } // If field parse out as an complete address // Assume it is a cross street if (checkAddress(fld) > 0) { if (data.strCross.length() > 0) data.strCross += " & "; data.strCross += fld; continue; } // If we have found an address but have no call description, assume this is it if (data.strCall.length() == 0) { data.strCall = fld; continue; } // Otherwise bundle this into supplemental info StringBuilder sb = new StringBuilder(data.strSupp); if (sb.length() > 0 && delim.length()>0 && ",;\n".indexOf(delim.charAt(0))<0) sb.append(' '); if (sb.length() > 0 || delim.length() > 0 && Character.isUpperCase(delim.charAt(0))) sb.append(delim); if (sb.length() > 0) sb.append(' '); sb.append(fld); data.strSupp = sb.toString(); } } // next resolve any multiple address keyword fields if (bestRes != null) { String saveCall = data.strCall; bestRes.getData(data); if (data.strCall.length() == 0 || keywordDesc) data.strCall = saveCall; String supp = bestRes.getLeft(); if (supp.length() > 0) { if (data.strSupp.length() > 0) { supp = supp + " / " + data.strSupp; } data.strSupp = supp; } // If there were multiple address keywords, the second best one // becomes the place. Any existing place is demoted to a name if (secondAddr != null) { if (data.strPlace.length() > 0) data.strName = data.strPlace; data.strPlace = secondAddr; } } // Return success if we found an address return data.strAddress.length() > 0; } }
true
true
protected boolean parseMsg(String body, Data data) { // Accept anything, but only if there is a valid sender filter if (ManagePreferences.filter().length() <= 1) return false; // Starting with CAD: confuses things if (body.startsWith("CAD:")) body = body.substring(4).trim(); // Strip out any date and time fields body = DATE_PATTERN.matcher(body).replaceAll(""); body = TIME_PATTERN.matcher(body).replaceAll(""); // Parse text into different fields separated by delimiters // that match DELIM_PATTERN Matcher match = DELIM_PATTERN.matcher(body); String nextDelim = ""; int pt = 0; String last = null; boolean keywordDesc = false; boolean foundAddr = false; Result bestRes = null; String bestAddr = null; String secondAddr = null; while (nextDelim != null) { // Parse the next field String delim = nextDelim; String fld; if (match.find(pt)) { nextDelim = body.substring(match.start(), match.end()); fld = body.substring(pt, match.start()); pt = match.end(); } else { nextDelim = null; fld = body.substring(pt); } fld = fld.trim(); // fld is the data field being processed // delim is the delimiter that started this field // If zero length field, nothing to worry about if (fld.length() == 0) continue; // Check delimiter to see if this is something we recognize? FieldType type = null; if (delim.endsWith(":")) { type = keywordMap.get(delim.substring(0, delim.length()-1).toUpperCase()); } else if (delim.endsWith("#")) { type = FieldType.ID; } // If we have found a recognizable keyword, assign this field to that keyword value if (type != null) { switch (type) { case SKIP: break; case CALL: // Call description, ignore if less than 3 characters if (fld.length() <= 2) break; keywordDesc = true; // If we already have a call desc, append this to it if (data.strCall.length() > 0) { data.strCall += " / "; data.strCall += fld; } // Otherwise run it through the smart parser just in case the // call desc is followed by an address else { parseAddress(StartType.START_CALL, fld, data); if (data.strSupp.length() == 0) data.strSupp = getLeft(); } break; case PLACE: if (data.strPlace.length() == 0) data.strPlace = fld; break; case ADDRESS: // We might have multiple address fields // Keep track of which one looks like the best address // Also keep the first second place address in case we want to // use it as a call description foundAddr = true; StartType st = (data.strCall.length() == 0 ? StartType.START_CALL : data.strPlace.length() == 0 ? StartType.START_PLACE : StartType.START_SKIP); Result res = parseAddress(st, fld); if (bestRes == null || res.getStatus() > bestRes.getStatus()) { if (secondAddr == null) secondAddr = bestAddr; bestAddr = fld; bestRes = res; } else { if (secondAddr == null) secondAddr = fld; } // If we have some leading call info, use it. If not, // treat the last unidentified field as the call if (data.strCall.length() == 0 && last != null) data.strCall = last; break; case CITY: data.strCity = fld; break; case APT: if (data.strApt.length() > 0) data.strApt += "-"; data.strApt += fld; break; case CROSS: if (data.strCross.length() > 0) data.strCross += " & "; data.strCross += fld; break; case BOX: data.strBox = fld; break; case UNIT: data.strUnit = fld; break; case MAP: data.strMap = fld; break; case ID: data.strCallId = fld; break; case PHONE: data.strPhone = fld; break; case SUPP: if (data.strSupp.length() > 0) data.strSupp += " / "; data.strSupp += fld; break; case CODE: data.strCode = fld; break; case SRC: data.strSource = fld; break; case NAME: data.strName = fld; break; } } // Otherwise we have to try to figure out fields by position else { // If we haven't found an address yet, see if this is it if (!foundAddr) { StartType st = (data.strCall.length() == 0 ? StartType.START_CALL : data.strPlace.length() == 0 ? StartType.START_PLACE : StartType.START_SKIP); Result res = parseAddress(st, fld); if (res.getStatus() > 0) { // Bingo! Anything past the address goes into info foundAddr = true; res.getData(data); // If we have some leading call info, use it. If not, // treat the last unidentified field as the call if (data.strCall.length() == 0 && last != null) data.strCall = last; // If we got any call info from anywhere, extra stuff goes into info // otherwise it goes into the call description if (data.strCall.length() == 0) { data.strCall = getLeft(); } else { data.strSupp = getLeft(); } continue; } } // Does this look like a call ID? if (data.strCallId.length() == 0 && CALL_ID_PATTERN.matcher(fld).matches()) { data.strCallId = fld; continue; } // Nope, lets see if it looks like a unit list if (data.strUnit.length() == 0 && UNIT_PATTERN.matcher(fld + " ").matches()) { data.strUnit = fld; continue; } // None of the above // If we haven't found an address yet, save this field for use as a possible // call field when we find the address. if (! foundAddr) { last = fld; continue; } // If field has an &, assume it is a set of cross streets if (data.strCross.length() == 0 && fld.contains("&")) { data.strCross = fld; continue; } // If field parse out as an complete address // Assume it is a cross street if (checkAddress(fld) > 0) { if (data.strCross.length() > 0) data.strCross += " & "; data.strCross += fld; continue; } // If we have found an address but have no call description, assume this is it if (data.strCall.length() == 0) { data.strCall = fld; continue; } // Otherwise bundle this into supplemental info StringBuilder sb = new StringBuilder(data.strSupp); if (sb.length() > 0 && delim.length()>0 && ",;\n".indexOf(delim.charAt(0))<0) sb.append(' '); if (sb.length() > 0 || delim.length() > 0 && Character.isUpperCase(delim.charAt(0))) sb.append(delim); if (sb.length() > 0) sb.append(' '); sb.append(fld); data.strSupp = sb.toString(); } } // next resolve any multiple address keyword fields if (bestRes != null) { String saveCall = data.strCall; bestRes.getData(data); if (data.strCall.length() == 0 || keywordDesc) data.strCall = saveCall; String supp = bestRes.getLeft(); if (supp.length() > 0) { if (data.strSupp.length() > 0) { supp = supp + " / " + data.strSupp; } data.strSupp = supp; } // If there were multiple address keywords, the second best one // becomes the place. Any existing place is demoted to a name if (secondAddr != null) { if (data.strPlace.length() > 0) data.strName = data.strPlace; data.strPlace = secondAddr; } } // Return success if we found an address return data.strAddress.length() > 0; }
protected boolean parseMsg(String body, Data data) { // Accept anything, but only if there is a valid sender filter if (! ManagePreferences.overrideFilter()) return false; if (ManagePreferences.filter().length() <= 1) return false; // Starting with CAD: confuses things if (body.startsWith("CAD:")) body = body.substring(4).trim(); // Strip out any date and time fields body = DATE_PATTERN.matcher(body).replaceAll(""); body = TIME_PATTERN.matcher(body).replaceAll(""); // Parse text into different fields separated by delimiters // that match DELIM_PATTERN Matcher match = DELIM_PATTERN.matcher(body); String nextDelim = ""; int pt = 0; String last = null; boolean keywordDesc = false; boolean foundAddr = false; Result bestRes = null; String bestAddr = null; String secondAddr = null; while (nextDelim != null) { // Parse the next field String delim = nextDelim; String fld; if (match.find(pt)) { nextDelim = body.substring(match.start(), match.end()); fld = body.substring(pt, match.start()); pt = match.end(); } else { nextDelim = null; fld = body.substring(pt); } fld = fld.trim(); // fld is the data field being processed // delim is the delimiter that started this field // If zero length field, nothing to worry about if (fld.length() == 0) continue; // Check delimiter to see if this is something we recognize? FieldType type = null; if (delim.endsWith(":")) { type = keywordMap.get(delim.substring(0, delim.length()-1).toUpperCase()); } else if (delim.endsWith("#")) { type = FieldType.ID; } // If we have found a recognizable keyword, assign this field to that keyword value if (type != null) { switch (type) { case SKIP: break; case CALL: // Call description, ignore if less than 3 characters if (fld.length() <= 2) break; keywordDesc = true; // If we already have a call desc, append this to it if (data.strCall.length() > 0) { data.strCall += " / "; data.strCall += fld; } // Otherwise run it through the smart parser just in case the // call desc is followed by an address else { parseAddress(StartType.START_CALL, fld, data); if (data.strSupp.length() == 0) data.strSupp = getLeft(); } break; case PLACE: if (data.strPlace.length() == 0) data.strPlace = fld; break; case ADDRESS: // We might have multiple address fields // Keep track of which one looks like the best address // Also keep the first second place address in case we want to // use it as a call description foundAddr = true; StartType st = (data.strCall.length() == 0 ? StartType.START_CALL : data.strPlace.length() == 0 ? StartType.START_PLACE : StartType.START_SKIP); Result res = parseAddress(st, fld); if (bestRes == null || res.getStatus() > bestRes.getStatus()) { if (secondAddr == null) secondAddr = bestAddr; bestAddr = fld; bestRes = res; } else { if (secondAddr == null) secondAddr = fld; } // If we have some leading call info, use it. If not, // treat the last unidentified field as the call if (data.strCall.length() == 0 && last != null) data.strCall = last; break; case CITY: data.strCity = fld; break; case APT: if (data.strApt.length() > 0) data.strApt += "-"; data.strApt += fld; break; case CROSS: if (data.strCross.length() > 0) data.strCross += " & "; data.strCross += fld; break; case BOX: data.strBox = fld; break; case UNIT: data.strUnit = fld; break; case MAP: data.strMap = fld; break; case ID: data.strCallId = fld; break; case PHONE: data.strPhone = fld; break; case SUPP: if (data.strSupp.length() > 0) data.strSupp += " / "; data.strSupp += fld; break; case CODE: data.strCode = fld; break; case SRC: data.strSource = fld; break; case NAME: data.strName = fld; break; } } // Otherwise we have to try to figure out fields by position else { // If we haven't found an address yet, see if this is it if (!foundAddr) { StartType st = (data.strCall.length() == 0 ? StartType.START_CALL : data.strPlace.length() == 0 ? StartType.START_PLACE : StartType.START_SKIP); Result res = parseAddress(st, fld); if (res.getStatus() > 0) { // Bingo! Anything past the address goes into info foundAddr = true; res.getData(data); // If we have some leading call info, use it. If not, // treat the last unidentified field as the call if (data.strCall.length() == 0 && last != null) data.strCall = last; // If we got any call info from anywhere, extra stuff goes into info // otherwise it goes into the call description if (data.strCall.length() == 0) { data.strCall = getLeft(); } else { data.strSupp = getLeft(); } continue; } } // Does this look like a call ID? if (data.strCallId.length() == 0 && CALL_ID_PATTERN.matcher(fld).matches()) { data.strCallId = fld; continue; } // Nope, lets see if it looks like a unit list if (data.strUnit.length() == 0 && UNIT_PATTERN.matcher(fld + " ").matches()) { data.strUnit = fld; continue; } // None of the above // If we haven't found an address yet, save this field for use as a possible // call field when we find the address. if (! foundAddr) { last = fld; continue; } // If field has an &, assume it is a set of cross streets if (data.strCross.length() == 0 && fld.contains("&")) { data.strCross = fld; continue; } // If field parse out as an complete address // Assume it is a cross street if (checkAddress(fld) > 0) { if (data.strCross.length() > 0) data.strCross += " & "; data.strCross += fld; continue; } // If we have found an address but have no call description, assume this is it if (data.strCall.length() == 0) { data.strCall = fld; continue; } // Otherwise bundle this into supplemental info StringBuilder sb = new StringBuilder(data.strSupp); if (sb.length() > 0 && delim.length()>0 && ",;\n".indexOf(delim.charAt(0))<0) sb.append(' '); if (sb.length() > 0 || delim.length() > 0 && Character.isUpperCase(delim.charAt(0))) sb.append(delim); if (sb.length() > 0) sb.append(' '); sb.append(fld); data.strSupp = sb.toString(); } } // next resolve any multiple address keyword fields if (bestRes != null) { String saveCall = data.strCall; bestRes.getData(data); if (data.strCall.length() == 0 || keywordDesc) data.strCall = saveCall; String supp = bestRes.getLeft(); if (supp.length() > 0) { if (data.strSupp.length() > 0) { supp = supp + " / " + data.strSupp; } data.strSupp = supp; } // If there were multiple address keywords, the second best one // becomes the place. Any existing place is demoted to a name if (secondAddr != null) { if (data.strPlace.length() > 0) data.strName = data.strPlace; data.strPlace = secondAddr; } } // Return success if we found an address return data.strAddress.length() > 0; }
diff --git a/src/com/untamedears/JukeAlert/JukeAlert.java b/src/com/untamedears/JukeAlert/JukeAlert.java index 8455cf4..a7fff30 100644 --- a/src/com/untamedears/JukeAlert/JukeAlert.java +++ b/src/com/untamedears/JukeAlert/JukeAlert.java @@ -1,88 +1,88 @@ package com.untamedears.JukeAlert; import com.untamedears.JukeAlert.command.CommandHandler; import com.untamedears.JukeAlert.command.commands.HelpCommand; import com.untamedears.JukeAlert.command.commands.InfoCommand; import com.untamedears.JukeAlert.group.GroupMediator; import com.untamedears.JukeAlert.listener.JukeAlertListener; import com.untamedears.JukeAlert.manager.ConfigManager; import com.untamedears.JukeAlert.manager.SnitchManager; import com.untamedears.JukeAlert.storage.JukeAlertLogger; import java.util.logging.Level; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; public class JukeAlert extends JavaPlugin { private static JukeAlert instance; private JukeAlertLogger jaLogger; private ConfigManager configManager; private SnitchManager snitchManager; private CommandHandler commandHandler; private GroupMediator groupMediator; @Override public void onEnable() { instance = this; configManager = new ConfigManager(); + groupMediator = new GroupMediator(); jaLogger = new JukeAlertLogger(); snitchManager = new SnitchManager(); - groupMediator = new GroupMediator(); registerEvents(); registerCommands(); snitchManager.loadSnitches(); } @Override public void onDisable() { snitchManager.saveSnitches(); } public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { return commandHandler.dispatch(sender, label, args); } private void registerEvents() { PluginManager pm = getServer().getPluginManager(); pm.registerEvents(new JukeAlertListener(), this); } private void registerCommands() { commandHandler = new CommandHandler(); commandHandler.addCommand(new InfoCommand()); commandHandler.addCommand(new HelpCommand()); } public static JukeAlert getInstance() { return instance; } public JukeAlertLogger getJaLogger() { return jaLogger; } public ConfigManager getConfigManager() { return configManager; } public SnitchManager getSnitchManager() { return snitchManager; } public GroupMediator getGroupMediator() { return groupMediator; } public CommandHandler getCommandHandler() { return commandHandler; } //Logs a message with the level of Info. public void log(String message) { this.getLogger().log(Level.INFO, message); } }
false
true
public void onEnable() { instance = this; configManager = new ConfigManager(); jaLogger = new JukeAlertLogger(); snitchManager = new SnitchManager(); groupMediator = new GroupMediator(); registerEvents(); registerCommands(); snitchManager.loadSnitches(); }
public void onEnable() { instance = this; configManager = new ConfigManager(); groupMediator = new GroupMediator(); jaLogger = new JukeAlertLogger(); snitchManager = new SnitchManager(); registerEvents(); registerCommands(); snitchManager.loadSnitches(); }
diff --git a/src/me/ellbristow/setXP/setXP.java b/src/me/ellbristow/setXP/setXP.java index 8a50505..955a653 100644 --- a/src/me/ellbristow/setXP/setXP.java +++ b/src/me/ellbristow/setXP/setXP.java @@ -1,486 +1,492 @@ package me.ellbristow.setXP; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerLevelChangeEvent; import org.bukkit.plugin.java.JavaPlugin; public class setXP extends JavaPlugin implements Listener { private static boolean gotVault = false; private static boolean gotEconomy = false; private static FileConfiguration config; private static double xpPrice; private static double refundPercent; private static vaultBridge vault; private int maxLevel; private boolean forceMaxLevel; @Override public void onDisable() { } @Override public void onEnable() { if (getServer().getPluginManager().isPluginEnabled("Vault")) { gotVault = true; getLogger().info("[Vault] found and hooked!"); vault = new vaultBridge(this); gotEconomy = vault.foundEconomy; } initConfig(); getServer().getPluginManager().registerEvents(this, this); } @Override public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args ) { if (sender instanceof Player) { // Command sent by player Boolean comreturn = readCommand((Player) sender, commandLabel, args); return comreturn; } else { // Command sent by console return consoleCommand(sender, commandLabel, args); } } private boolean readCommand(Player player, String command, String[] args) { if(command.equalsIgnoreCase("setxp")) { /* * Set XP level */ if (args.length == 0) { // No arguments sent, report error player.sendMessage(ChatColor.GOLD + "== SetXP v" + ChatColor.WHITE + getDescription().getVersion() + ChatColor.GOLD + " by " + ChatColor.WHITE + "ellbristow" + ChatColor.GOLD + " =="); if (gotVault) { String eco = ""; if (gotEconomy) { eco = " and [" + vault.economyName + "]"; } player.sendMessage(ChatColor.GOLD + "== Using [Vault]" + eco + " =="); if (gotEconomy && !player.hasPermission("setxp.free")) { player.sendMessage(ChatColor.GOLD + "XP level price : " + vault.economy.format(xpPrice) ); player.sendMessage(ChatColor.GOLD + "Refunds Given : " + refundPercent + "%" ); } } return true; } else if (args.length == 1) { // 1 argument sent, apply level to player int level; // Check that level is an integer try { level = Integer.parseInt(args[0]); } catch(NumberFormatException nfe) { // Failed. Number not an integer player.sendMessage(ChatColor.RED + "Level must be a number!" ); return false; } if (level > maxLevel) { level = maxLevel; } int oldLevel = player.getLevel(); double balance = 0; double cost = 0; if (gotEconomy) { balance = vault.economy.getBalance(player.getName()); if (oldLevel < level) { cost = xpPrice*(level-oldLevel); } } if (balance < cost) { player.sendMessage(ChatColor.RED + "You cannot afford that XP! ("+vault.economy.format(cost)+")" ); return false; } // Good to go! player.setLevel(level); player.sendMessage(ChatColor.GOLD + "XP level set to " + ChatColor.WHITE + player.getLevel()); if (gotVault && gotEconomy && xpPrice != 0 && !player.hasPermission("setxp.free")) { if (oldLevel < level) { vault.economy.withdrawPlayer(player.getName(), cost); player.sendMessage(ChatColor.GOLD + "You were charged " + vault.economy.format(cost)); } else if (oldLevel > level) { cost = (xpPrice/100*refundPercent)*(oldLevel-level); vault.economy.depositPlayer(player.getName(), cost); player.sendMessage(ChatColor.GOLD + "You were refunded " + vault.economy.format(cost)); } } return true; } else if (args.length == 2) { if (args[0].equalsIgnoreCase("add")) { // ADD levels to self if (!player.hasPermission("setxp.add")) { player.sendMessage(ChatColor.RED + "You do not have permission to add to your XP level!"); return true; } int level; // Check that level is an integer try { level = Integer.parseInt(args[1]); } catch(NumberFormatException nfe) { // Failed. Number not an integer player.sendMessage(ChatColor.RED + "Level must be a number!" ); return false; } if (player.getLevel() + level > maxLevel) { level = maxLevel - player.getLevel(); } double balance = 0; double cost = 0; if (gotEconomy) { balance = vault.economy.getBalance(player.getName()); cost = xpPrice*level; } if (balance < cost) { player.sendMessage(ChatColor.RED + "You cannot afford that XP! ("+vault.economy.format(cost)+")" ); return false; } player.setLevel(player.getLevel() + level); player.sendMessage(ChatColor.GOLD + "XP level set to " + ChatColor.WHITE + player.getLevel()); if (gotVault && gotEconomy && xpPrice != 0 && !player.hasPermission("setxp.free")) { vault.economy.withdrawPlayer(player.getName(), cost); player.sendMessage(ChatColor.GOLD + "You were charged " + vault.economy.format(cost)); } return true; } else if (args[0].equalsIgnoreCase("remove")) { // Remove levels from self if (!player.hasPermission("setxp.remove")) { player.sendMessage(ChatColor.RED + "You do not have permission to remove from your XP level!"); return true; } int level; // Check that level is an integer try { level = Integer.parseInt(args[1]); } catch(NumberFormatException nfe) { // Failed. Number not an integer player.sendMessage(ChatColor.RED + "Level must be a number!" ); return false; } + if (level > player.getLevel()) { + level = player.getLevel(); + } double refund = 0; if (gotEconomy && xpPrice != 0 && refundPercent != 0) { refund = xpPrice*refundPercent*level; } player.setLevel(player.getLevel() - level); player.sendMessage(ChatColor.GOLD + "XP level set to " + ChatColor.WHITE + player.getLevel()); if (gotVault && gotEconomy && refund != 0 && !player.hasPermission("setxp.free")) { vault.economy.depositPlayer(player.getName(), refund); player.sendMessage(ChatColor.GOLD + "You were refunded " + vault.economy.format(refund)); } return true; } else { // SET level of another player Player target = getServer().getPlayer(args[0]); // Check permission to set other players' level if (!player.hasPermission("setxp.setxp.others") && !player.isOp()) { player.sendMessage(ChatColor.RED + "You do not have permission to set another player's XP level!"); return true; } // Check target player exists if (target == null) { // Target player not found player.sendMessage(ChatColor.RED + "Player " + ChatColor.WHITE + args[0] + ChatColor.RED + " not found or not online!"); return false; } // Check if target layer is exempt from setXP if (target.hasPermission("setxp.exempt") && !player.hasPermission("setxp.override")) { player.sendMessage(target.getDisplayName() + ChatColor.RED + " is exempt from setXP!"); return true; } int level; // Check that level is an integer try { level = Integer.parseInt(args[1]); } catch(NumberFormatException nfe) { // Failed. Number not an integer player.sendMessage(ChatColor.RED + "Level must be a number!" ); return false; } if (level > maxLevel) { level = maxLevel; } int oldLevel = player.getLevel(); double balance = 0; double cost = 0; if (gotEconomy) { balance = vault.economy.getBalance(player.getName()); if (oldLevel < level) { cost = xpPrice*(level-oldLevel); } } if (balance < cost) { player.sendMessage(ChatColor.RED + "You cannot afford that XP! ("+vault.economy.format(cost)+")" ); return false; } // Good to go! target.setLevel(level); player.sendMessage(target.getDisplayName() + ChatColor.GOLD + " is now at XP level " + ChatColor.WHITE + target.getLevel()); if (gotVault && gotEconomy && xpPrice != 0 && !player.hasPermission("setxp.free")) { if (oldLevel < level) { vault.economy.withdrawPlayer(player.getName(), cost); player.sendMessage(ChatColor.GOLD + "You were charged " + vault.economy.format(cost)); } else if (oldLevel > level) { cost = (xpPrice/100*refundPercent)*(oldLevel-level); vault.economy.depositPlayer(player.getName(), cost); player.sendMessage(ChatColor.GOLD + "You were refunded " + vault.economy.format(cost)); } } if (target.isOnline()) { // Target player is online, send message target.sendMessage(player.getDisplayName() + ChatColor.GOLD + " set your XP level to " + ChatColor.WHITE + target.getLevel()); } return true; } } else if (args.length == 3 && args[0].equalsIgnoreCase("add")) { // 2 arguments sent, apply level to another player Player target = getServer().getPlayer(args[1]); // Check permission to set other players' level if (!player.hasPermission("setxp.add.others") && !player.isOp()) { player.sendMessage(ChatColor.RED + "You do not have permission to add to another player's XP level!"); return true; } // Check target player exists if (target == null) { // Target player not found player.sendMessage(ChatColor.RED + "Player " + ChatColor.WHITE + args[1] + ChatColor.RED + " not found or not online!"); return false; } // Check if target layer is exempt from setXP if (target.hasPermission("setxp.exempt") && !player.hasPermission("setxp.override")) { player.sendMessage(target.getDisplayName() + ChatColor.RED + " is exempt from setXP!"); return true; } int level; // Check that level is an integer try { level = Integer.parseInt(args[2]); } catch(NumberFormatException nfe) { // Failed. Number not an integer player.sendMessage(ChatColor.RED + "Level must be a number!" ); return false; } if (target.getLevel() + level > maxLevel) { level = maxLevel - target.getLevel(); } double balance = 0; double cost = 0; if (gotEconomy) { balance = vault.economy.getBalance(player.getName()); cost = xpPrice*level; } if (balance < cost) { player.sendMessage(ChatColor.RED + "You cannot afford that XP! ("+vault.economy.format(cost)+")" ); return false; } // Good to go! target.setLevel(target.getLevel() + level); player.sendMessage(target.getDisplayName() + ChatColor.GOLD + " is now at XP level " + ChatColor.WHITE + target.getLevel()); if (gotVault && gotEconomy && xpPrice != 0 && !player.hasPermission("setxp.free")) { vault.economy.withdrawPlayer(player.getName(), cost); player.sendMessage(ChatColor.GOLD + "You were charged " + vault.economy.format(cost)); } if (target.isOnline()) { // Target player is online, send message target.sendMessage(player.getDisplayName() + ChatColor.GOLD + " set your XP level to " + ChatColor.WHITE + target.getLevel()); } return true; } else if (args.length == 3 && args[0].equalsIgnoreCase("remove")) { // 2 arguments sent, apply level to another player Player target = getServer().getPlayer(args[1]); // Check permission to set other players' level if (!player.hasPermission("setxp.remove.others") && !player.isOp()) { player.sendMessage(ChatColor.RED + "You do not have permission to remove from another player's XP level!"); return true; } // Check target player exists if (target == null) { // Target player not found player.sendMessage(ChatColor.RED + "Player " + ChatColor.WHITE + args[1] + ChatColor.RED + " not found or not online!"); return false; } // Check if target layer is exempt from setXP if (target.hasPermission("setxp.exempt") && !player.hasPermission("setxp.override")) { player.sendMessage(target.getDisplayName() + ChatColor.RED + " is exempt from setXP!"); return true; } int level; // Check that level is an integer try { level = Integer.parseInt(args[2]); } catch(NumberFormatException nfe) { // Failed. Number not an integer player.sendMessage(ChatColor.RED + "Level must be a number!" ); return false; } + if (level > target.getLevel()) { + level = target.getLevel(); + } double refund = 0; if (gotEconomy && xpPrice != 0 && refundPercent != 0) { refund = xpPrice*refundPercent*level; } // Good to go! target.setLevel(target.getLevel() - level); player.sendMessage(target.getDisplayName() + ChatColor.GOLD + " is now at XP level " + ChatColor.WHITE + target.getLevel()); if (gotVault && gotEconomy && xpPrice != 0 && !player.hasPermission("setxp.free")) { vault.economy.withdrawPlayer(player.getName(), refund); player.sendMessage(ChatColor.GOLD + "You were refunded " + vault.economy.format(refund)); } if (target.isOnline()) { // Target player is online, send message target.sendMessage(player.getDisplayName() + ChatColor.GOLD + " set your XP level to " + ChatColor.WHITE + target.getLevel()); } return true; } return false; } else if (command.equalsIgnoreCase("getxp")) { /* * Fetch XP level of target player */ if (args.length == 0) { // No arguments sent player.sendMessage(ChatColor.RED + "You must specify a player!"); return false; } Player target = getServer().getPlayer(args[0]); if (target == null) { // Target player not found player.sendMessage(ChatColor.RED + "Player " + ChatColor.WHITE + args[0] + ChatColor.RED + " not found or not online!"); return false; } // Good to Go! player.sendMessage(target.getDisplayName() + ChatColor.GOLD + " is at level " + ChatColor.WHITE + target.getLevel()); return true; } return false; } private boolean consoleCommand(CommandSender sender, String command, String[] args) { if (command.equalsIgnoreCase("getxp")) { /* * Fetch XP level of target player */ if (args.length == 0) { // No player requested sender.sendMessage(ChatColor.RED + "No target player specified!"); return false; } Player target = getServer().getPlayer(args[0]); if (target == null) { // Player not found sender.sendMessage(ChatColor.RED + "Player " + ChatColor.WHITE + args[0] + ChatColor.RED + " not found or not online!"); return true; } sender.sendMessage(target.getDisplayName() + ChatColor.GOLD + "'s XP level is " + ChatColor.WHITE + target.getLevel()); return true; } else if (command.equalsIgnoreCase("setxp")) { /* * Set XP level of target player */ if (args[0].equalsIgnoreCase("add")) { // ADD levels if (args.length != 3) { // Incorrect number of arguments sender.sendMessage("/setxp add [player] [level]"); return true; } Player target = getServer().getPlayer(args[1]); if (target == null) { // Player not found sender.sendMessage(ChatColor.RED + "Player " + ChatColor.WHITE + args[1] + ChatColor.RED + " not found or not online!"); return true; } int level; // Check that level is an integer try { level = Integer.parseInt(args[2]); } catch(NumberFormatException nfe) { // Failed. Number not an integer sender.sendMessage(ChatColor.RED + "Level must be a number!" ); sender.sendMessage("/setxp add [player] [level]" ); return true; } target.setLevel(target.getLevel() + level); sender.sendMessage(target.getDisplayName() + ChatColor.GOLD + "'s XP level is now " + ChatColor.WHITE + target.getLevel()); target.sendMessage("SERVER " + ChatColor.GOLD + "set your XP level to " + ChatColor.WHITE + target.getLevel()); return true; } else { // SET level if (args.length != 2) { // Incorrect number of arguments sender.sendMessage("/setxp [player] [level]"); return true; } Player target = getServer().getPlayer(args[0]); if (target == null) { // Player not found sender.sendMessage(ChatColor.RED + "Player " + ChatColor.WHITE + args[0] + ChatColor.RED + " not found or not online!"); return true; } int level; // Check that level is an integer try { level = Integer.parseInt(args[1]); } catch(NumberFormatException nfe) { // Failed. Number not an integer sender.sendMessage(ChatColor.RED + "Level must be a number!" ); sender.sendMessage("/setxp [player] [level]" ); return true; } target.setLevel(level); sender.sendMessage(target.getDisplayName() + ChatColor.GOLD + "'s XP level is now " + ChatColor.WHITE + target.getLevel()); target.sendMessage("SERVER " + ChatColor.GOLD + "set your XP level to " + ChatColor.WHITE + target.getLevel()); return true; } } else { sender.sendMessage("This command cannot be run in the console!"); return true; } } private void initConfig() { config = getConfig(); xpPrice = config.getDouble("price_per_xp_level", 0.0); refundPercent = config.getDouble("reduce_xp_refund_percentage", 100.0); maxLevel = config.getInt("max_level", 32767); forceMaxLevel = config.getBoolean("force_max_level", false); if (maxLevel > 32767) { maxLevel = 32767; } config.set("price_per_xp_level", xpPrice); config.set("reduce_xp_refund_percentage", refundPercent); config.set("max_level", maxLevel); config.set("force_max_level", forceMaxLevel); saveConfig(); } @EventHandler (priority = EventPriority.NORMAL) public void onLevel(PlayerLevelChangeEvent event) { if (!forceMaxLevel) return; if (event.getNewLevel() > maxLevel) { Player player = event.getPlayer(); player.setExp(1f); player.setLevel(maxLevel); } } }
false
true
private boolean readCommand(Player player, String command, String[] args) { if(command.equalsIgnoreCase("setxp")) { /* * Set XP level */ if (args.length == 0) { // No arguments sent, report error player.sendMessage(ChatColor.GOLD + "== SetXP v" + ChatColor.WHITE + getDescription().getVersion() + ChatColor.GOLD + " by " + ChatColor.WHITE + "ellbristow" + ChatColor.GOLD + " =="); if (gotVault) { String eco = ""; if (gotEconomy) { eco = " and [" + vault.economyName + "]"; } player.sendMessage(ChatColor.GOLD + "== Using [Vault]" + eco + " =="); if (gotEconomy && !player.hasPermission("setxp.free")) { player.sendMessage(ChatColor.GOLD + "XP level price : " + vault.economy.format(xpPrice) ); player.sendMessage(ChatColor.GOLD + "Refunds Given : " + refundPercent + "%" ); } } return true; } else if (args.length == 1) { // 1 argument sent, apply level to player int level; // Check that level is an integer try { level = Integer.parseInt(args[0]); } catch(NumberFormatException nfe) { // Failed. Number not an integer player.sendMessage(ChatColor.RED + "Level must be a number!" ); return false; } if (level > maxLevel) { level = maxLevel; } int oldLevel = player.getLevel(); double balance = 0; double cost = 0; if (gotEconomy) { balance = vault.economy.getBalance(player.getName()); if (oldLevel < level) { cost = xpPrice*(level-oldLevel); } } if (balance < cost) { player.sendMessage(ChatColor.RED + "You cannot afford that XP! ("+vault.economy.format(cost)+")" ); return false; } // Good to go! player.setLevel(level); player.sendMessage(ChatColor.GOLD + "XP level set to " + ChatColor.WHITE + player.getLevel()); if (gotVault && gotEconomy && xpPrice != 0 && !player.hasPermission("setxp.free")) { if (oldLevel < level) { vault.economy.withdrawPlayer(player.getName(), cost); player.sendMessage(ChatColor.GOLD + "You were charged " + vault.economy.format(cost)); } else if (oldLevel > level) { cost = (xpPrice/100*refundPercent)*(oldLevel-level); vault.economy.depositPlayer(player.getName(), cost); player.sendMessage(ChatColor.GOLD + "You were refunded " + vault.economy.format(cost)); } } return true; } else if (args.length == 2) { if (args[0].equalsIgnoreCase("add")) { // ADD levels to self if (!player.hasPermission("setxp.add")) { player.sendMessage(ChatColor.RED + "You do not have permission to add to your XP level!"); return true; } int level; // Check that level is an integer try { level = Integer.parseInt(args[1]); } catch(NumberFormatException nfe) { // Failed. Number not an integer player.sendMessage(ChatColor.RED + "Level must be a number!" ); return false; } if (player.getLevel() + level > maxLevel) { level = maxLevel - player.getLevel(); } double balance = 0; double cost = 0; if (gotEconomy) { balance = vault.economy.getBalance(player.getName()); cost = xpPrice*level; } if (balance < cost) { player.sendMessage(ChatColor.RED + "You cannot afford that XP! ("+vault.economy.format(cost)+")" ); return false; } player.setLevel(player.getLevel() + level); player.sendMessage(ChatColor.GOLD + "XP level set to " + ChatColor.WHITE + player.getLevel()); if (gotVault && gotEconomy && xpPrice != 0 && !player.hasPermission("setxp.free")) { vault.economy.withdrawPlayer(player.getName(), cost); player.sendMessage(ChatColor.GOLD + "You were charged " + vault.economy.format(cost)); } return true; } else if (args[0].equalsIgnoreCase("remove")) { // Remove levels from self if (!player.hasPermission("setxp.remove")) { player.sendMessage(ChatColor.RED + "You do not have permission to remove from your XP level!"); return true; } int level; // Check that level is an integer try { level = Integer.parseInt(args[1]); } catch(NumberFormatException nfe) { // Failed. Number not an integer player.sendMessage(ChatColor.RED + "Level must be a number!" ); return false; } double refund = 0; if (gotEconomy && xpPrice != 0 && refundPercent != 0) { refund = xpPrice*refundPercent*level; } player.setLevel(player.getLevel() - level); player.sendMessage(ChatColor.GOLD + "XP level set to " + ChatColor.WHITE + player.getLevel()); if (gotVault && gotEconomy && refund != 0 && !player.hasPermission("setxp.free")) { vault.economy.depositPlayer(player.getName(), refund); player.sendMessage(ChatColor.GOLD + "You were refunded " + vault.economy.format(refund)); } return true; } else { // SET level of another player Player target = getServer().getPlayer(args[0]); // Check permission to set other players' level if (!player.hasPermission("setxp.setxp.others") && !player.isOp()) { player.sendMessage(ChatColor.RED + "You do not have permission to set another player's XP level!"); return true; } // Check target player exists if (target == null) { // Target player not found player.sendMessage(ChatColor.RED + "Player " + ChatColor.WHITE + args[0] + ChatColor.RED + " not found or not online!"); return false; } // Check if target layer is exempt from setXP if (target.hasPermission("setxp.exempt") && !player.hasPermission("setxp.override")) { player.sendMessage(target.getDisplayName() + ChatColor.RED + " is exempt from setXP!"); return true; } int level; // Check that level is an integer try { level = Integer.parseInt(args[1]); } catch(NumberFormatException nfe) { // Failed. Number not an integer player.sendMessage(ChatColor.RED + "Level must be a number!" ); return false; } if (level > maxLevel) { level = maxLevel; } int oldLevel = player.getLevel(); double balance = 0; double cost = 0; if (gotEconomy) { balance = vault.economy.getBalance(player.getName()); if (oldLevel < level) { cost = xpPrice*(level-oldLevel); } } if (balance < cost) { player.sendMessage(ChatColor.RED + "You cannot afford that XP! ("+vault.economy.format(cost)+")" ); return false; } // Good to go! target.setLevel(level); player.sendMessage(target.getDisplayName() + ChatColor.GOLD + " is now at XP level " + ChatColor.WHITE + target.getLevel()); if (gotVault && gotEconomy && xpPrice != 0 && !player.hasPermission("setxp.free")) { if (oldLevel < level) { vault.economy.withdrawPlayer(player.getName(), cost); player.sendMessage(ChatColor.GOLD + "You were charged " + vault.economy.format(cost)); } else if (oldLevel > level) { cost = (xpPrice/100*refundPercent)*(oldLevel-level); vault.economy.depositPlayer(player.getName(), cost); player.sendMessage(ChatColor.GOLD + "You were refunded " + vault.economy.format(cost)); } } if (target.isOnline()) { // Target player is online, send message target.sendMessage(player.getDisplayName() + ChatColor.GOLD + " set your XP level to " + ChatColor.WHITE + target.getLevel()); } return true; } } else if (args.length == 3 && args[0].equalsIgnoreCase("add")) { // 2 arguments sent, apply level to another player Player target = getServer().getPlayer(args[1]); // Check permission to set other players' level if (!player.hasPermission("setxp.add.others") && !player.isOp()) { player.sendMessage(ChatColor.RED + "You do not have permission to add to another player's XP level!"); return true; } // Check target player exists if (target == null) { // Target player not found player.sendMessage(ChatColor.RED + "Player " + ChatColor.WHITE + args[1] + ChatColor.RED + " not found or not online!"); return false; } // Check if target layer is exempt from setXP if (target.hasPermission("setxp.exempt") && !player.hasPermission("setxp.override")) { player.sendMessage(target.getDisplayName() + ChatColor.RED + " is exempt from setXP!"); return true; } int level; // Check that level is an integer try { level = Integer.parseInt(args[2]); } catch(NumberFormatException nfe) { // Failed. Number not an integer player.sendMessage(ChatColor.RED + "Level must be a number!" ); return false; } if (target.getLevel() + level > maxLevel) { level = maxLevel - target.getLevel(); } double balance = 0; double cost = 0; if (gotEconomy) { balance = vault.economy.getBalance(player.getName()); cost = xpPrice*level; } if (balance < cost) { player.sendMessage(ChatColor.RED + "You cannot afford that XP! ("+vault.economy.format(cost)+")" ); return false; } // Good to go! target.setLevel(target.getLevel() + level); player.sendMessage(target.getDisplayName() + ChatColor.GOLD + " is now at XP level " + ChatColor.WHITE + target.getLevel()); if (gotVault && gotEconomy && xpPrice != 0 && !player.hasPermission("setxp.free")) { vault.economy.withdrawPlayer(player.getName(), cost); player.sendMessage(ChatColor.GOLD + "You were charged " + vault.economy.format(cost)); } if (target.isOnline()) { // Target player is online, send message target.sendMessage(player.getDisplayName() + ChatColor.GOLD + " set your XP level to " + ChatColor.WHITE + target.getLevel()); } return true; } else if (args.length == 3 && args[0].equalsIgnoreCase("remove")) { // 2 arguments sent, apply level to another player Player target = getServer().getPlayer(args[1]); // Check permission to set other players' level if (!player.hasPermission("setxp.remove.others") && !player.isOp()) { player.sendMessage(ChatColor.RED + "You do not have permission to remove from another player's XP level!"); return true; } // Check target player exists if (target == null) { // Target player not found player.sendMessage(ChatColor.RED + "Player " + ChatColor.WHITE + args[1] + ChatColor.RED + " not found or not online!"); return false; } // Check if target layer is exempt from setXP if (target.hasPermission("setxp.exempt") && !player.hasPermission("setxp.override")) { player.sendMessage(target.getDisplayName() + ChatColor.RED + " is exempt from setXP!"); return true; } int level; // Check that level is an integer try { level = Integer.parseInt(args[2]); } catch(NumberFormatException nfe) { // Failed. Number not an integer player.sendMessage(ChatColor.RED + "Level must be a number!" ); return false; } double refund = 0; if (gotEconomy && xpPrice != 0 && refundPercent != 0) { refund = xpPrice*refundPercent*level; } // Good to go! target.setLevel(target.getLevel() - level); player.sendMessage(target.getDisplayName() + ChatColor.GOLD + " is now at XP level " + ChatColor.WHITE + target.getLevel()); if (gotVault && gotEconomy && xpPrice != 0 && !player.hasPermission("setxp.free")) { vault.economy.withdrawPlayer(player.getName(), refund); player.sendMessage(ChatColor.GOLD + "You were refunded " + vault.economy.format(refund)); } if (target.isOnline()) { // Target player is online, send message target.sendMessage(player.getDisplayName() + ChatColor.GOLD + " set your XP level to " + ChatColor.WHITE + target.getLevel()); } return true; } return false; } else if (command.equalsIgnoreCase("getxp")) { /* * Fetch XP level of target player */ if (args.length == 0) { // No arguments sent player.sendMessage(ChatColor.RED + "You must specify a player!"); return false; } Player target = getServer().getPlayer(args[0]); if (target == null) { // Target player not found player.sendMessage(ChatColor.RED + "Player " + ChatColor.WHITE + args[0] + ChatColor.RED + " not found or not online!"); return false; } // Good to Go! player.sendMessage(target.getDisplayName() + ChatColor.GOLD + " is at level " + ChatColor.WHITE + target.getLevel()); return true; } return false; }
private boolean readCommand(Player player, String command, String[] args) { if(command.equalsIgnoreCase("setxp")) { /* * Set XP level */ if (args.length == 0) { // No arguments sent, report error player.sendMessage(ChatColor.GOLD + "== SetXP v" + ChatColor.WHITE + getDescription().getVersion() + ChatColor.GOLD + " by " + ChatColor.WHITE + "ellbristow" + ChatColor.GOLD + " =="); if (gotVault) { String eco = ""; if (gotEconomy) { eco = " and [" + vault.economyName + "]"; } player.sendMessage(ChatColor.GOLD + "== Using [Vault]" + eco + " =="); if (gotEconomy && !player.hasPermission("setxp.free")) { player.sendMessage(ChatColor.GOLD + "XP level price : " + vault.economy.format(xpPrice) ); player.sendMessage(ChatColor.GOLD + "Refunds Given : " + refundPercent + "%" ); } } return true; } else if (args.length == 1) { // 1 argument sent, apply level to player int level; // Check that level is an integer try { level = Integer.parseInt(args[0]); } catch(NumberFormatException nfe) { // Failed. Number not an integer player.sendMessage(ChatColor.RED + "Level must be a number!" ); return false; } if (level > maxLevel) { level = maxLevel; } int oldLevel = player.getLevel(); double balance = 0; double cost = 0; if (gotEconomy) { balance = vault.economy.getBalance(player.getName()); if (oldLevel < level) { cost = xpPrice*(level-oldLevel); } } if (balance < cost) { player.sendMessage(ChatColor.RED + "You cannot afford that XP! ("+vault.economy.format(cost)+")" ); return false; } // Good to go! player.setLevel(level); player.sendMessage(ChatColor.GOLD + "XP level set to " + ChatColor.WHITE + player.getLevel()); if (gotVault && gotEconomy && xpPrice != 0 && !player.hasPermission("setxp.free")) { if (oldLevel < level) { vault.economy.withdrawPlayer(player.getName(), cost); player.sendMessage(ChatColor.GOLD + "You were charged " + vault.economy.format(cost)); } else if (oldLevel > level) { cost = (xpPrice/100*refundPercent)*(oldLevel-level); vault.economy.depositPlayer(player.getName(), cost); player.sendMessage(ChatColor.GOLD + "You were refunded " + vault.economy.format(cost)); } } return true; } else if (args.length == 2) { if (args[0].equalsIgnoreCase("add")) { // ADD levels to self if (!player.hasPermission("setxp.add")) { player.sendMessage(ChatColor.RED + "You do not have permission to add to your XP level!"); return true; } int level; // Check that level is an integer try { level = Integer.parseInt(args[1]); } catch(NumberFormatException nfe) { // Failed. Number not an integer player.sendMessage(ChatColor.RED + "Level must be a number!" ); return false; } if (player.getLevel() + level > maxLevel) { level = maxLevel - player.getLevel(); } double balance = 0; double cost = 0; if (gotEconomy) { balance = vault.economy.getBalance(player.getName()); cost = xpPrice*level; } if (balance < cost) { player.sendMessage(ChatColor.RED + "You cannot afford that XP! ("+vault.economy.format(cost)+")" ); return false; } player.setLevel(player.getLevel() + level); player.sendMessage(ChatColor.GOLD + "XP level set to " + ChatColor.WHITE + player.getLevel()); if (gotVault && gotEconomy && xpPrice != 0 && !player.hasPermission("setxp.free")) { vault.economy.withdrawPlayer(player.getName(), cost); player.sendMessage(ChatColor.GOLD + "You were charged " + vault.economy.format(cost)); } return true; } else if (args[0].equalsIgnoreCase("remove")) { // Remove levels from self if (!player.hasPermission("setxp.remove")) { player.sendMessage(ChatColor.RED + "You do not have permission to remove from your XP level!"); return true; } int level; // Check that level is an integer try { level = Integer.parseInt(args[1]); } catch(NumberFormatException nfe) { // Failed. Number not an integer player.sendMessage(ChatColor.RED + "Level must be a number!" ); return false; } if (level > player.getLevel()) { level = player.getLevel(); } double refund = 0; if (gotEconomy && xpPrice != 0 && refundPercent != 0) { refund = xpPrice*refundPercent*level; } player.setLevel(player.getLevel() - level); player.sendMessage(ChatColor.GOLD + "XP level set to " + ChatColor.WHITE + player.getLevel()); if (gotVault && gotEconomy && refund != 0 && !player.hasPermission("setxp.free")) { vault.economy.depositPlayer(player.getName(), refund); player.sendMessage(ChatColor.GOLD + "You were refunded " + vault.economy.format(refund)); } return true; } else { // SET level of another player Player target = getServer().getPlayer(args[0]); // Check permission to set other players' level if (!player.hasPermission("setxp.setxp.others") && !player.isOp()) { player.sendMessage(ChatColor.RED + "You do not have permission to set another player's XP level!"); return true; } // Check target player exists if (target == null) { // Target player not found player.sendMessage(ChatColor.RED + "Player " + ChatColor.WHITE + args[0] + ChatColor.RED + " not found or not online!"); return false; } // Check if target layer is exempt from setXP if (target.hasPermission("setxp.exempt") && !player.hasPermission("setxp.override")) { player.sendMessage(target.getDisplayName() + ChatColor.RED + " is exempt from setXP!"); return true; } int level; // Check that level is an integer try { level = Integer.parseInt(args[1]); } catch(NumberFormatException nfe) { // Failed. Number not an integer player.sendMessage(ChatColor.RED + "Level must be a number!" ); return false; } if (level > maxLevel) { level = maxLevel; } int oldLevel = player.getLevel(); double balance = 0; double cost = 0; if (gotEconomy) { balance = vault.economy.getBalance(player.getName()); if (oldLevel < level) { cost = xpPrice*(level-oldLevel); } } if (balance < cost) { player.sendMessage(ChatColor.RED + "You cannot afford that XP! ("+vault.economy.format(cost)+")" ); return false; } // Good to go! target.setLevel(level); player.sendMessage(target.getDisplayName() + ChatColor.GOLD + " is now at XP level " + ChatColor.WHITE + target.getLevel()); if (gotVault && gotEconomy && xpPrice != 0 && !player.hasPermission("setxp.free")) { if (oldLevel < level) { vault.economy.withdrawPlayer(player.getName(), cost); player.sendMessage(ChatColor.GOLD + "You were charged " + vault.economy.format(cost)); } else if (oldLevel > level) { cost = (xpPrice/100*refundPercent)*(oldLevel-level); vault.economy.depositPlayer(player.getName(), cost); player.sendMessage(ChatColor.GOLD + "You were refunded " + vault.economy.format(cost)); } } if (target.isOnline()) { // Target player is online, send message target.sendMessage(player.getDisplayName() + ChatColor.GOLD + " set your XP level to " + ChatColor.WHITE + target.getLevel()); } return true; } } else if (args.length == 3 && args[0].equalsIgnoreCase("add")) { // 2 arguments sent, apply level to another player Player target = getServer().getPlayer(args[1]); // Check permission to set other players' level if (!player.hasPermission("setxp.add.others") && !player.isOp()) { player.sendMessage(ChatColor.RED + "You do not have permission to add to another player's XP level!"); return true; } // Check target player exists if (target == null) { // Target player not found player.sendMessage(ChatColor.RED + "Player " + ChatColor.WHITE + args[1] + ChatColor.RED + " not found or not online!"); return false; } // Check if target layer is exempt from setXP if (target.hasPermission("setxp.exempt") && !player.hasPermission("setxp.override")) { player.sendMessage(target.getDisplayName() + ChatColor.RED + " is exempt from setXP!"); return true; } int level; // Check that level is an integer try { level = Integer.parseInt(args[2]); } catch(NumberFormatException nfe) { // Failed. Number not an integer player.sendMessage(ChatColor.RED + "Level must be a number!" ); return false; } if (target.getLevel() + level > maxLevel) { level = maxLevel - target.getLevel(); } double balance = 0; double cost = 0; if (gotEconomy) { balance = vault.economy.getBalance(player.getName()); cost = xpPrice*level; } if (balance < cost) { player.sendMessage(ChatColor.RED + "You cannot afford that XP! ("+vault.economy.format(cost)+")" ); return false; } // Good to go! target.setLevel(target.getLevel() + level); player.sendMessage(target.getDisplayName() + ChatColor.GOLD + " is now at XP level " + ChatColor.WHITE + target.getLevel()); if (gotVault && gotEconomy && xpPrice != 0 && !player.hasPermission("setxp.free")) { vault.economy.withdrawPlayer(player.getName(), cost); player.sendMessage(ChatColor.GOLD + "You were charged " + vault.economy.format(cost)); } if (target.isOnline()) { // Target player is online, send message target.sendMessage(player.getDisplayName() + ChatColor.GOLD + " set your XP level to " + ChatColor.WHITE + target.getLevel()); } return true; } else if (args.length == 3 && args[0].equalsIgnoreCase("remove")) { // 2 arguments sent, apply level to another player Player target = getServer().getPlayer(args[1]); // Check permission to set other players' level if (!player.hasPermission("setxp.remove.others") && !player.isOp()) { player.sendMessage(ChatColor.RED + "You do not have permission to remove from another player's XP level!"); return true; } // Check target player exists if (target == null) { // Target player not found player.sendMessage(ChatColor.RED + "Player " + ChatColor.WHITE + args[1] + ChatColor.RED + " not found or not online!"); return false; } // Check if target layer is exempt from setXP if (target.hasPermission("setxp.exempt") && !player.hasPermission("setxp.override")) { player.sendMessage(target.getDisplayName() + ChatColor.RED + " is exempt from setXP!"); return true; } int level; // Check that level is an integer try { level = Integer.parseInt(args[2]); } catch(NumberFormatException nfe) { // Failed. Number not an integer player.sendMessage(ChatColor.RED + "Level must be a number!" ); return false; } if (level > target.getLevel()) { level = target.getLevel(); } double refund = 0; if (gotEconomy && xpPrice != 0 && refundPercent != 0) { refund = xpPrice*refundPercent*level; } // Good to go! target.setLevel(target.getLevel() - level); player.sendMessage(target.getDisplayName() + ChatColor.GOLD + " is now at XP level " + ChatColor.WHITE + target.getLevel()); if (gotVault && gotEconomy && xpPrice != 0 && !player.hasPermission("setxp.free")) { vault.economy.withdrawPlayer(player.getName(), refund); player.sendMessage(ChatColor.GOLD + "You were refunded " + vault.economy.format(refund)); } if (target.isOnline()) { // Target player is online, send message target.sendMessage(player.getDisplayName() + ChatColor.GOLD + " set your XP level to " + ChatColor.WHITE + target.getLevel()); } return true; } return false; } else if (command.equalsIgnoreCase("getxp")) { /* * Fetch XP level of target player */ if (args.length == 0) { // No arguments sent player.sendMessage(ChatColor.RED + "You must specify a player!"); return false; } Player target = getServer().getPlayer(args[0]); if (target == null) { // Target player not found player.sendMessage(ChatColor.RED + "Player " + ChatColor.WHITE + args[0] + ChatColor.RED + " not found or not online!"); return false; } // Good to Go! player.sendMessage(target.getDisplayName() + ChatColor.GOLD + " is at level " + ChatColor.WHITE + target.getLevel()); return true; } return false; }
diff --git a/kmean/src/mapreduce/KmeansDriver.java b/kmean/src/mapreduce/KmeansDriver.java index a45aca3..135c35f 100644 --- a/kmean/src/mapreduce/KmeansDriver.java +++ b/kmean/src/mapreduce/KmeansDriver.java @@ -1,114 +1,114 @@ package mapreduce; import java.util.Date; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Counter; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.input.TextInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat; import clusterer.KmeansCluster; import config.Constants; public class KmeansDriver { public static void configure() { } public static void main(String[] args) { Date start = new Date(); if (args.length < 2) { System.out.println("Usage: program <input> <clusters>"); System.exit(0); } Configuration conf = new Configuration(); Counter converge = null; Counter total = null; Counter totalfile = null; Path in = new Path(args[0]); Path out; int iterCounter = 0; - conf.setFloat(Constants.THRESHOLD, 0.000001f); + conf.setFloat(Constants.THRESHOLD, 0.00001f); try { do { if (iterCounter == 0) conf.set(Constants.CLUSTER_PATH, args[1]); else // load the output of last iteration conf.set(Constants.CLUSTER_PATH, args[1] + ".part" + (iterCounter - 1) + "/part-r-00000"); Job job = new Job(conf); job.setNumReduceTasks(Constants.REDUCERAMOUNT); job.setJobName("K-means clustering"); job.setJarByClass(KmeansDriver.class); job.setMapperClass(KmeansMapper.class); job.setCombinerClass(KmeansCombiner.class); job.setReducerClass(KmeansReducer.class); job.setOutputKeyClass(LongWritable.class); job.setOutputValueClass(KmeansCluster.class); job.setMapOutputKeyClass(LongWritable.class); job.setMapOutputValueClass(KmeansCluster.class); job.setInputFormatClass(TextInputFormat.class); job.setOutputFormatClass(SequenceFileOutputFormat.class); out = new Path(args[1] + ".part" + iterCounter); FileInputFormat.addInputPath(job, in); SequenceFileOutputFormat.setOutputPath(job, out); job.waitForCompletion(true); converge = job.getCounters().getGroup(Constants.COUNTER_GROUP) .findCounter(Constants.COUNTER_CONVERGED); total = job.getCounters().getGroup(Constants.COUNTER_GROUP) .findCounter(Constants.COUNTER_TOTAL); totalfile = job.getCounters().getGroup(Constants.COUNTER_GROUP) .findCounter(Constants.COUNTER_FILE); System.out .println("CONVERGED: " + converge.getValue() + "\tTotal: " + total.getValue() / totalfile.getValue()); iterCounter++; } while (converge.getValue() < total.getValue() / totalfile.getValue()); conf.set(Constants.CLUSTER_PATH, args[1] + ".part" + (iterCounter - 1) + "/part-r-00000"); Job job = new Job(conf); job.setNumReduceTasks(0); job.setJobName("K-means clustering"); job.setJarByClass(KmeansDriver.class); job.setMapperClass(KmeansClusterMapper.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(Text.class); job.setMapOutputKeyClass(Text.class); job.setMapOutputValueClass(Text.class); out = new Path(args[1] + ".final"); FileInputFormat.addInputPath(job, in); FileOutputFormat.setOutputPath(job, out); job.waitForCompletion(true); } catch (Exception e) { // TODO: // a better error report routine e.printStackTrace(); } Date finish = new Date(); System.out.println("All clusters converged. k-means finishs."); System.out.println("It takes " + (finish.getTime() - start.getTime()) / 1000.0 + "s to accomplish clustering."); } }
true
true
public static void main(String[] args) { Date start = new Date(); if (args.length < 2) { System.out.println("Usage: program <input> <clusters>"); System.exit(0); } Configuration conf = new Configuration(); Counter converge = null; Counter total = null; Counter totalfile = null; Path in = new Path(args[0]); Path out; int iterCounter = 0; conf.setFloat(Constants.THRESHOLD, 0.000001f); try { do { if (iterCounter == 0) conf.set(Constants.CLUSTER_PATH, args[1]); else // load the output of last iteration conf.set(Constants.CLUSTER_PATH, args[1] + ".part" + (iterCounter - 1) + "/part-r-00000"); Job job = new Job(conf); job.setNumReduceTasks(Constants.REDUCERAMOUNT); job.setJobName("K-means clustering"); job.setJarByClass(KmeansDriver.class); job.setMapperClass(KmeansMapper.class); job.setCombinerClass(KmeansCombiner.class); job.setReducerClass(KmeansReducer.class); job.setOutputKeyClass(LongWritable.class); job.setOutputValueClass(KmeansCluster.class); job.setMapOutputKeyClass(LongWritable.class); job.setMapOutputValueClass(KmeansCluster.class); job.setInputFormatClass(TextInputFormat.class); job.setOutputFormatClass(SequenceFileOutputFormat.class); out = new Path(args[1] + ".part" + iterCounter); FileInputFormat.addInputPath(job, in); SequenceFileOutputFormat.setOutputPath(job, out); job.waitForCompletion(true); converge = job.getCounters().getGroup(Constants.COUNTER_GROUP) .findCounter(Constants.COUNTER_CONVERGED); total = job.getCounters().getGroup(Constants.COUNTER_GROUP) .findCounter(Constants.COUNTER_TOTAL); totalfile = job.getCounters().getGroup(Constants.COUNTER_GROUP) .findCounter(Constants.COUNTER_FILE); System.out .println("CONVERGED: " + converge.getValue() + "\tTotal: " + total.getValue() / totalfile.getValue()); iterCounter++; } while (converge.getValue() < total.getValue() / totalfile.getValue()); conf.set(Constants.CLUSTER_PATH, args[1] + ".part" + (iterCounter - 1) + "/part-r-00000"); Job job = new Job(conf); job.setNumReduceTasks(0); job.setJobName("K-means clustering"); job.setJarByClass(KmeansDriver.class); job.setMapperClass(KmeansClusterMapper.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(Text.class); job.setMapOutputKeyClass(Text.class); job.setMapOutputValueClass(Text.class); out = new Path(args[1] + ".final"); FileInputFormat.addInputPath(job, in); FileOutputFormat.setOutputPath(job, out); job.waitForCompletion(true); } catch (Exception e) { // TODO: // a better error report routine e.printStackTrace(); } Date finish = new Date(); System.out.println("All clusters converged. k-means finishs."); System.out.println("It takes " + (finish.getTime() - start.getTime()) / 1000.0 + "s to accomplish clustering."); }
public static void main(String[] args) { Date start = new Date(); if (args.length < 2) { System.out.println("Usage: program <input> <clusters>"); System.exit(0); } Configuration conf = new Configuration(); Counter converge = null; Counter total = null; Counter totalfile = null; Path in = new Path(args[0]); Path out; int iterCounter = 0; conf.setFloat(Constants.THRESHOLD, 0.00001f); try { do { if (iterCounter == 0) conf.set(Constants.CLUSTER_PATH, args[1]); else // load the output of last iteration conf.set(Constants.CLUSTER_PATH, args[1] + ".part" + (iterCounter - 1) + "/part-r-00000"); Job job = new Job(conf); job.setNumReduceTasks(Constants.REDUCERAMOUNT); job.setJobName("K-means clustering"); job.setJarByClass(KmeansDriver.class); job.setMapperClass(KmeansMapper.class); job.setCombinerClass(KmeansCombiner.class); job.setReducerClass(KmeansReducer.class); job.setOutputKeyClass(LongWritable.class); job.setOutputValueClass(KmeansCluster.class); job.setMapOutputKeyClass(LongWritable.class); job.setMapOutputValueClass(KmeansCluster.class); job.setInputFormatClass(TextInputFormat.class); job.setOutputFormatClass(SequenceFileOutputFormat.class); out = new Path(args[1] + ".part" + iterCounter); FileInputFormat.addInputPath(job, in); SequenceFileOutputFormat.setOutputPath(job, out); job.waitForCompletion(true); converge = job.getCounters().getGroup(Constants.COUNTER_GROUP) .findCounter(Constants.COUNTER_CONVERGED); total = job.getCounters().getGroup(Constants.COUNTER_GROUP) .findCounter(Constants.COUNTER_TOTAL); totalfile = job.getCounters().getGroup(Constants.COUNTER_GROUP) .findCounter(Constants.COUNTER_FILE); System.out .println("CONVERGED: " + converge.getValue() + "\tTotal: " + total.getValue() / totalfile.getValue()); iterCounter++; } while (converge.getValue() < total.getValue() / totalfile.getValue()); conf.set(Constants.CLUSTER_PATH, args[1] + ".part" + (iterCounter - 1) + "/part-r-00000"); Job job = new Job(conf); job.setNumReduceTasks(0); job.setJobName("K-means clustering"); job.setJarByClass(KmeansDriver.class); job.setMapperClass(KmeansClusterMapper.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(Text.class); job.setMapOutputKeyClass(Text.class); job.setMapOutputValueClass(Text.class); out = new Path(args[1] + ".final"); FileInputFormat.addInputPath(job, in); FileOutputFormat.setOutputPath(job, out); job.waitForCompletion(true); } catch (Exception e) { // TODO: // a better error report routine e.printStackTrace(); } Date finish = new Date(); System.out.println("All clusters converged. k-means finishs."); System.out.println("It takes " + (finish.getTime() - start.getTime()) / 1000.0 + "s to accomplish clustering."); }
diff --git a/src/frontend/edu/brown/hstore/SpecExecScheduler.java b/src/frontend/edu/brown/hstore/SpecExecScheduler.java index cfb37e48e..2b7cd8c75 100644 --- a/src/frontend/edu/brown/hstore/SpecExecScheduler.java +++ b/src/frontend/edu/brown/hstore/SpecExecScheduler.java @@ -1,409 +1,408 @@ package edu.brown.hstore; import java.util.HashSet; import java.util.Iterator; import java.util.Random; import java.util.Set; import org.apache.log4j.Logger; import org.voltdb.catalog.Procedure; import org.voltdb.types.SpecExecSchedulerPolicyType; import org.voltdb.types.SpeculationType; import edu.brown.hstore.conf.HStoreConf; import edu.brown.hstore.estimators.EstimatorState; import edu.brown.hstore.internal.InternalMessage; import edu.brown.hstore.specexec.checkers.AbstractConflictChecker; import edu.brown.hstore.txns.AbstractTransaction; import edu.brown.hstore.txns.LocalTransaction; import edu.brown.interfaces.DebugContext; import edu.brown.logging.LoggerUtil; import edu.brown.logging.LoggerUtil.LoggerBoolean; import edu.brown.profilers.SpecExecProfiler; import edu.brown.statistics.FastIntHistogram; import edu.brown.utils.StringUtil; /** * Special scheduler that can figure out what the next best single-partition * to speculatively execute at a partition based on the current distributed transaction * @author pavlo */ public class SpecExecScheduler { private static final Logger LOG = Logger.getLogger(SpecExecScheduler.class); private static final LoggerBoolean debug = new LoggerBoolean(LOG.isDebugEnabled()); private static final LoggerBoolean trace = new LoggerBoolean(LOG.isTraceEnabled()); static { LoggerUtil.attachObserver(LOG, debug, trace); } private final int partitionId; private final PartitionLockQueue queue; private AbstractConflictChecker checker; private SpecExecSchedulerPolicyType policyType; private int windowSize = 1; /** Ignore all LocalTransaction handles **/ private boolean ignore_all_local = false; /** Don't reset the iterator if the queue size changes **/ private boolean ignore_queue_size_change = false; /** Don't reset the iterator if the current SpeculationType changes */ private boolean ignore_speculation_type_change = false; private Set<SpeculationType> ignore_types = null; private AbstractTransaction lastDtxn; private SpeculationType lastSpecType; private Iterator<AbstractTransaction> lastIterator; private int lastSize = 0; private boolean interrupted = false; private Class<? extends InternalMessage> latchMsg; /** * Maintain a separate SpecExecProfiler per SpeculationType. */ private final SpecExecProfiler profilerMap[]; private boolean profiling = false; private double profiling_sample; private final Random profiling_rand = new Random(); private AbstractTransaction profilerCurrentTxn; private boolean profilerSkipCurrentTxn = true; private final FastIntHistogram profilerExecuteCounter = new FastIntHistogram(SpeculationType.values().length); /** * Constructor * @param catalogContext * @param checker TODO * @param partitionId * @param queue */ public SpecExecScheduler(AbstractConflictChecker checker, int partitionId, PartitionLockQueue queue, SpecExecSchedulerPolicyType schedule_policy, int window_size) { assert(schedule_policy != null) : "Unsupported schedule policy parameter passed in"; this.partitionId = partitionId; this.queue = queue; this.checker = checker; this.policyType = schedule_policy; this.windowSize = window_size; this.profiling = HStoreConf.singleton().site.specexec_profiling; this.profiling_sample = HStoreConf.singleton().site.specexec_profiling_sample; this.profilerExecuteCounter.setKeepZeroEntries(true); this.profilerMap = new SpecExecProfiler[SpeculationType.values().length]; if (this.profiling) { for (int i = 0; i < this.profilerMap.length; i++) { this.profilerMap[i] = new SpecExecProfiler(); } // FOR } } /** * Replace the ConflictChecker. This should only be used for testing * @param checker */ protected void setConflictChecker(AbstractConflictChecker checker) { LOG.warn(String.format("Replacing original checker %s with %s", this.checker.getClass().getSimpleName(), checker.getClass().getCanonicalName())); this.checker = checker; } protected void setIgnoreAllLocal(boolean ignore_all_local) { this.ignore_all_local = ignore_all_local; } protected void setIgnoreQueueSizeChange(boolean ignore_queue_changes) { this.ignore_queue_size_change = ignore_queue_changes; } protected void setIgnoreSpeculationTypeChange(boolean ignore_speculation_type_change) { this.ignore_speculation_type_change = ignore_speculation_type_change; } protected void setWindowSize(int window) { this.windowSize = window; } protected void setPolicyType(SpecExecSchedulerPolicyType policy) { this.policyType = policy; } protected void reset() { this.lastIterator = null; } public boolean shouldIgnoreProcedure(Procedure catalog_proc) { return (this.checker.shouldIgnoreProcedure(catalog_proc)); } public void ignoreSpeculationType(SpeculationType specType) { if (this.ignore_types == null) { this.ignore_types = new HashSet<SpeculationType>(); } this.ignore_types.add(specType); if (debug.val) LOG.debug(String.format("Setting %s to ignore speculation at stall point %s", this.getClass().getSimpleName(), specType)); } public void interruptSearch(InternalMessage msg) { if (this.interrupted == false) { this.interrupted = true; this.latchMsg = msg.getClass(); } } /** * Find the next non-conflicting txn that we can speculatively execute. * Note that if we find one, it will be immediately removed from the queue * and returned. If you do this and then find out for some reason that you * can't execute the StartTxnMessage that is returned, you must be sure * to requeue it back. * @param dtxn The current distributed txn at this partition. * @return */ public LocalTransaction next(AbstractTransaction dtxn, SpeculationType specType) { this.interrupted = false; if (debug.val) { LOG.debug(String.format("%s - Checking queue for transaction to speculatively execute " + "[specType=%s, windowSize=%d, queueSize=%d, policy=%s]", dtxn, specType, this.windowSize, this.queue.size(), this.policyType)); if (trace.val) LOG.trace(String.format("%s - Last Invocation [lastDtxn=%s, lastSpecType=%s, lastIterator=%s]", dtxn, this.lastDtxn, this.lastSpecType, this.lastIterator)); } SpecExecProfiler profiler = null; if (this.profiling) { // This is the first time that we've seen this dtxn, so // we need to dump out its stats. This is not entirely accurate, // since we won't have the last txn's info, but it's good enough. if (this.profilerCurrentTxn != dtxn) { if (this.profilerCurrentTxn != null && this.profilerSkipCurrentTxn == false) { for (int i = 0; i < this.profilerMap.length; i++) { int cnt = (int)this.profilerExecuteCounter.get(i, 0); this.profilerMap[i].num_executed.put(i, cnt); } // FOR this.profilerExecuteCounter.clearValues(); this.profilerCurrentTxn = null; } this.profilerCurrentTxn = dtxn; // Check whether we should enable it for this new txn if (this.profiling_rand.nextDouble() < this.profiling_sample) { this.profilerSkipCurrentTxn = false; - profiler = this.profilerMap[specType.ordinal()]; - profiler.total_time.start(); } else { this.profilerSkipCurrentTxn = true; } } if (this.profilerSkipCurrentTxn == false) { profiler = this.profilerMap[specType.ordinal()]; + profiler.total_time.start(); } } // Check whether we need to ignore this speculation stall point if (this.ignore_types != null && this.ignore_types.contains(specType)) { if (debug.val) LOG.debug(String.format("%s - Ignoring txn because we are set to ignore %s", dtxn, specType)); if (profiler != null) profiler.total_time.stop(); return (null); } // If we have a distributed txn, then check make sure it's legit if (dtxn != null) { assert(this.checker.shouldIgnoreProcedure(dtxn.getProcedure()) == false) : String.format("Trying to check for speculative txns for %s but the txn " + "should have been ignored", dtxn); // If this is a LocalTransaction and all of the remote partitions that it needs are // on the same site, then we won't bother with trying to pick something out // because there is going to be very small wait times. if (this.ignore_all_local && dtxn instanceof LocalTransaction && ((LocalTransaction)dtxn).isPredictAllLocal()) { if (debug.val) LOG.debug(String.format("%s - Ignoring current distributed txn because all of the partitions that " + "it is using are on the same HStoreSite [%s]", dtxn, dtxn.getProcedure())); if (profiler != null) profiler.total_time.stop(); return (null); } } // Now peek in the queue looking for single-partition txns that do not // conflict with the current dtxn LocalTransaction next = null; int txn_ctr = 0; int examined_ctr = 0; long bestTime = (this.policyType == SpecExecSchedulerPolicyType.LONGEST ? Long.MIN_VALUE : Long.MAX_VALUE); // Check whether we can use our same iterator from the last call if (this.policyType != SpecExecSchedulerPolicyType.FIRST || this.lastDtxn != dtxn || this.lastIterator == null || (this.ignore_speculation_type_change == false && this.lastSpecType != specType) || (this.ignore_queue_size_change == false && this.lastSize != this.queue.size())) { this.lastIterator = this.queue.iterator(); } boolean resetIterator = true; if (profiler != null) profiler.queue_size.put(this.queue.size()); boolean lastHasNext; if (trace.val) LOG.trace(StringUtil.header("BEGIN QUEUE CHECK :: " + dtxn)); while ((lastHasNext = this.lastIterator.hasNext()) == true) { if (this.interrupted) { if (debug.val) LOG.warn(String.format("Search interrupted after %d examinations [%s]", examined_ctr, this.latchMsg.getSimpleName())); if (profiler != null) profiler.interrupts++; break; } AbstractTransaction txn = this.lastIterator.next(); assert(txn != null) : "Null transaction handle " + txn; boolean singlePartition = txn.isPredictSinglePartition(); txn_ctr++; // Skip any distributed or non-local transactions if ((txn instanceof LocalTransaction) == false || singlePartition == false) { if (trace.val) LOG.trace(String.format("Skipping non-speculative candidate %s", txn)); continue; } LocalTransaction localTxn = (LocalTransaction)txn; // Skip anything already executed if (localTxn.isMarkExecuted()) { if (trace.val) LOG.trace(String.format("Skipping %s because it was already executed", txn)); continue; } // Let's check it out! if (profiler != null) profiler.compute_time.start(); if (singlePartition == false) { if (trace.val) LOG.trace(String.format("Skipping %s because it is not single-partitioned", localTxn)); continue; } if (debug.val) LOG.debug(String.format("Examining whether %s conflicts with current dtxn", localTxn)); examined_ctr++; try { switch (specType) { // We can execute anything when we are in 2PC or idle case IDLE: case SP2_REMOTE_BEFORE: case SP3_LOCAL: case SP3_REMOTE: { break; } // For SP1 + SP2 we can execute anything if the txn has not // executed a query at this partition. case SP1_LOCAL: case SP2_REMOTE_AFTER: { if (this.checker.canExecute(dtxn, localTxn, this.partitionId) == false) { continue; } break; } // BUSTED! default: String msg = String.format("Unexpected %s.%s", specType.getClass().getSimpleName(), specType); throw new RuntimeException(msg); } // SWITCH // Scheduling Policy: FIRST MATCH if (this.policyType == SpecExecSchedulerPolicyType.FIRST) { next = localTxn; resetIterator = false; break; } // Estimate the time that remains. EstimatorState es = localTxn.getEstimatorState(); if (es != null) { long remainingTime = es.getLastEstimate().getRemainingExecutionTime(); if ((this.policyType == SpecExecSchedulerPolicyType.SHORTEST && remainingTime < bestTime) || (this.policyType == SpecExecSchedulerPolicyType.LONGEST && remainingTime > bestTime)) { bestTime = remainingTime; next = localTxn; if (debug.val) LOG.debug(String.format("[%s %d/%d] New Match -> %s / remainingTime=%d", this.policyType, examined_ctr, this.windowSize, next, remainingTime)); } } // Stop if we've reached our window size if (examined_ctr == this.windowSize) break; } finally { if (profiler != null) profiler.compute_time.stop(); } } // WHILE if (trace.val) LOG.trace(StringUtil.header("END QUEUE CHECK")); if (profiler != null) profiler.num_comparisons.put(txn_ctr); // We found somebody to execute right now! // Make sure that we set the speculative flag to true! if (next != null) { next.markReleased(this.partitionId); if (profiler != null) { this.profilerExecuteCounter.put(specType.ordinal()); profiler.success++; } if (this.policyType == SpecExecSchedulerPolicyType.FIRST) { this.lastIterator.remove(); } else { this.queue.remove(next); } if (debug.val) LOG.debug(dtxn + " - Found next non-conflicting speculative txn " + next); } else if (debug.val && this.queue.isEmpty() == false) { LOG.debug(String.format("Failed to find non-conflicting speculative txn " + "[dtxn=%s, txnCtr=%d, examinedCtr=%d]", dtxn, txn_ctr, examined_ctr)); } this.lastDtxn = dtxn; this.lastSpecType = specType; if (resetIterator || lastHasNext == false) this.lastIterator = null; else if (this.ignore_queue_size_change == false) this.lastSize = this.queue.size(); if (profiler != null) profiler.total_time.stop(); return (next); } // ---------------------------------------------------------------------------- // DEBUG METHODS // ---------------------------------------------------------------------------- public class Debug implements DebugContext { public AbstractTransaction getLastDtxn() { return (lastDtxn); } public int getLastSize() { return (lastSize); } public Iterator<AbstractTransaction> getLastIterator() { return (lastIterator); } public SpeculationType getLastSpecType() { return (lastSpecType); } public SpecExecProfiler[] getProfilers() { return (profilerMap); } public SpecExecProfiler getProfiler(SpeculationType stype) { return (profilerMap[stype.ordinal()]); } } // CLASS private SpecExecScheduler.Debug cachedDebugContext; public SpecExecScheduler.Debug getDebugContext() { if (this.cachedDebugContext == null) { // We don't care if we're thread-safe here... this.cachedDebugContext = new SpecExecScheduler.Debug(); } return this.cachedDebugContext; } }
false
true
public LocalTransaction next(AbstractTransaction dtxn, SpeculationType specType) { this.interrupted = false; if (debug.val) { LOG.debug(String.format("%s - Checking queue for transaction to speculatively execute " + "[specType=%s, windowSize=%d, queueSize=%d, policy=%s]", dtxn, specType, this.windowSize, this.queue.size(), this.policyType)); if (trace.val) LOG.trace(String.format("%s - Last Invocation [lastDtxn=%s, lastSpecType=%s, lastIterator=%s]", dtxn, this.lastDtxn, this.lastSpecType, this.lastIterator)); } SpecExecProfiler profiler = null; if (this.profiling) { // This is the first time that we've seen this dtxn, so // we need to dump out its stats. This is not entirely accurate, // since we won't have the last txn's info, but it's good enough. if (this.profilerCurrentTxn != dtxn) { if (this.profilerCurrentTxn != null && this.profilerSkipCurrentTxn == false) { for (int i = 0; i < this.profilerMap.length; i++) { int cnt = (int)this.profilerExecuteCounter.get(i, 0); this.profilerMap[i].num_executed.put(i, cnt); } // FOR this.profilerExecuteCounter.clearValues(); this.profilerCurrentTxn = null; } this.profilerCurrentTxn = dtxn; // Check whether we should enable it for this new txn if (this.profiling_rand.nextDouble() < this.profiling_sample) { this.profilerSkipCurrentTxn = false; profiler = this.profilerMap[specType.ordinal()]; profiler.total_time.start(); } else { this.profilerSkipCurrentTxn = true; } } if (this.profilerSkipCurrentTxn == false) { profiler = this.profilerMap[specType.ordinal()]; } } // Check whether we need to ignore this speculation stall point if (this.ignore_types != null && this.ignore_types.contains(specType)) { if (debug.val) LOG.debug(String.format("%s - Ignoring txn because we are set to ignore %s", dtxn, specType)); if (profiler != null) profiler.total_time.stop(); return (null); } // If we have a distributed txn, then check make sure it's legit if (dtxn != null) { assert(this.checker.shouldIgnoreProcedure(dtxn.getProcedure()) == false) : String.format("Trying to check for speculative txns for %s but the txn " + "should have been ignored", dtxn); // If this is a LocalTransaction and all of the remote partitions that it needs are // on the same site, then we won't bother with trying to pick something out // because there is going to be very small wait times. if (this.ignore_all_local && dtxn instanceof LocalTransaction && ((LocalTransaction)dtxn).isPredictAllLocal()) { if (debug.val) LOG.debug(String.format("%s - Ignoring current distributed txn because all of the partitions that " + "it is using are on the same HStoreSite [%s]", dtxn, dtxn.getProcedure())); if (profiler != null) profiler.total_time.stop(); return (null); } } // Now peek in the queue looking for single-partition txns that do not // conflict with the current dtxn LocalTransaction next = null; int txn_ctr = 0; int examined_ctr = 0; long bestTime = (this.policyType == SpecExecSchedulerPolicyType.LONGEST ? Long.MIN_VALUE : Long.MAX_VALUE); // Check whether we can use our same iterator from the last call if (this.policyType != SpecExecSchedulerPolicyType.FIRST || this.lastDtxn != dtxn || this.lastIterator == null || (this.ignore_speculation_type_change == false && this.lastSpecType != specType) || (this.ignore_queue_size_change == false && this.lastSize != this.queue.size())) { this.lastIterator = this.queue.iterator(); } boolean resetIterator = true; if (profiler != null) profiler.queue_size.put(this.queue.size()); boolean lastHasNext; if (trace.val) LOG.trace(StringUtil.header("BEGIN QUEUE CHECK :: " + dtxn)); while ((lastHasNext = this.lastIterator.hasNext()) == true) { if (this.interrupted) { if (debug.val) LOG.warn(String.format("Search interrupted after %d examinations [%s]", examined_ctr, this.latchMsg.getSimpleName())); if (profiler != null) profiler.interrupts++; break; } AbstractTransaction txn = this.lastIterator.next(); assert(txn != null) : "Null transaction handle " + txn; boolean singlePartition = txn.isPredictSinglePartition(); txn_ctr++; // Skip any distributed or non-local transactions if ((txn instanceof LocalTransaction) == false || singlePartition == false) { if (trace.val) LOG.trace(String.format("Skipping non-speculative candidate %s", txn)); continue; } LocalTransaction localTxn = (LocalTransaction)txn; // Skip anything already executed if (localTxn.isMarkExecuted()) { if (trace.val) LOG.trace(String.format("Skipping %s because it was already executed", txn)); continue; } // Let's check it out! if (profiler != null) profiler.compute_time.start(); if (singlePartition == false) { if (trace.val) LOG.trace(String.format("Skipping %s because it is not single-partitioned", localTxn)); continue; } if (debug.val) LOG.debug(String.format("Examining whether %s conflicts with current dtxn", localTxn)); examined_ctr++; try { switch (specType) { // We can execute anything when we are in 2PC or idle case IDLE: case SP2_REMOTE_BEFORE: case SP3_LOCAL: case SP3_REMOTE: { break; } // For SP1 + SP2 we can execute anything if the txn has not // executed a query at this partition. case SP1_LOCAL: case SP2_REMOTE_AFTER: { if (this.checker.canExecute(dtxn, localTxn, this.partitionId) == false) { continue; } break; } // BUSTED! default: String msg = String.format("Unexpected %s.%s", specType.getClass().getSimpleName(), specType); throw new RuntimeException(msg); } // SWITCH // Scheduling Policy: FIRST MATCH if (this.policyType == SpecExecSchedulerPolicyType.FIRST) { next = localTxn; resetIterator = false; break; } // Estimate the time that remains. EstimatorState es = localTxn.getEstimatorState(); if (es != null) { long remainingTime = es.getLastEstimate().getRemainingExecutionTime(); if ((this.policyType == SpecExecSchedulerPolicyType.SHORTEST && remainingTime < bestTime) || (this.policyType == SpecExecSchedulerPolicyType.LONGEST && remainingTime > bestTime)) { bestTime = remainingTime; next = localTxn; if (debug.val) LOG.debug(String.format("[%s %d/%d] New Match -> %s / remainingTime=%d", this.policyType, examined_ctr, this.windowSize, next, remainingTime)); } } // Stop if we've reached our window size if (examined_ctr == this.windowSize) break; } finally { if (profiler != null) profiler.compute_time.stop(); } } // WHILE if (trace.val) LOG.trace(StringUtil.header("END QUEUE CHECK")); if (profiler != null) profiler.num_comparisons.put(txn_ctr); // We found somebody to execute right now! // Make sure that we set the speculative flag to true! if (next != null) { next.markReleased(this.partitionId); if (profiler != null) { this.profilerExecuteCounter.put(specType.ordinal()); profiler.success++; } if (this.policyType == SpecExecSchedulerPolicyType.FIRST) { this.lastIterator.remove(); } else { this.queue.remove(next); } if (debug.val) LOG.debug(dtxn + " - Found next non-conflicting speculative txn " + next); } else if (debug.val && this.queue.isEmpty() == false) { LOG.debug(String.format("Failed to find non-conflicting speculative txn " + "[dtxn=%s, txnCtr=%d, examinedCtr=%d]", dtxn, txn_ctr, examined_ctr)); } this.lastDtxn = dtxn; this.lastSpecType = specType; if (resetIterator || lastHasNext == false) this.lastIterator = null; else if (this.ignore_queue_size_change == false) this.lastSize = this.queue.size(); if (profiler != null) profiler.total_time.stop(); return (next); }
public LocalTransaction next(AbstractTransaction dtxn, SpeculationType specType) { this.interrupted = false; if (debug.val) { LOG.debug(String.format("%s - Checking queue for transaction to speculatively execute " + "[specType=%s, windowSize=%d, queueSize=%d, policy=%s]", dtxn, specType, this.windowSize, this.queue.size(), this.policyType)); if (trace.val) LOG.trace(String.format("%s - Last Invocation [lastDtxn=%s, lastSpecType=%s, lastIterator=%s]", dtxn, this.lastDtxn, this.lastSpecType, this.lastIterator)); } SpecExecProfiler profiler = null; if (this.profiling) { // This is the first time that we've seen this dtxn, so // we need to dump out its stats. This is not entirely accurate, // since we won't have the last txn's info, but it's good enough. if (this.profilerCurrentTxn != dtxn) { if (this.profilerCurrentTxn != null && this.profilerSkipCurrentTxn == false) { for (int i = 0; i < this.profilerMap.length; i++) { int cnt = (int)this.profilerExecuteCounter.get(i, 0); this.profilerMap[i].num_executed.put(i, cnt); } // FOR this.profilerExecuteCounter.clearValues(); this.profilerCurrentTxn = null; } this.profilerCurrentTxn = dtxn; // Check whether we should enable it for this new txn if (this.profiling_rand.nextDouble() < this.profiling_sample) { this.profilerSkipCurrentTxn = false; } else { this.profilerSkipCurrentTxn = true; } } if (this.profilerSkipCurrentTxn == false) { profiler = this.profilerMap[specType.ordinal()]; profiler.total_time.start(); } } // Check whether we need to ignore this speculation stall point if (this.ignore_types != null && this.ignore_types.contains(specType)) { if (debug.val) LOG.debug(String.format("%s - Ignoring txn because we are set to ignore %s", dtxn, specType)); if (profiler != null) profiler.total_time.stop(); return (null); } // If we have a distributed txn, then check make sure it's legit if (dtxn != null) { assert(this.checker.shouldIgnoreProcedure(dtxn.getProcedure()) == false) : String.format("Trying to check for speculative txns for %s but the txn " + "should have been ignored", dtxn); // If this is a LocalTransaction and all of the remote partitions that it needs are // on the same site, then we won't bother with trying to pick something out // because there is going to be very small wait times. if (this.ignore_all_local && dtxn instanceof LocalTransaction && ((LocalTransaction)dtxn).isPredictAllLocal()) { if (debug.val) LOG.debug(String.format("%s - Ignoring current distributed txn because all of the partitions that " + "it is using are on the same HStoreSite [%s]", dtxn, dtxn.getProcedure())); if (profiler != null) profiler.total_time.stop(); return (null); } } // Now peek in the queue looking for single-partition txns that do not // conflict with the current dtxn LocalTransaction next = null; int txn_ctr = 0; int examined_ctr = 0; long bestTime = (this.policyType == SpecExecSchedulerPolicyType.LONGEST ? Long.MIN_VALUE : Long.MAX_VALUE); // Check whether we can use our same iterator from the last call if (this.policyType != SpecExecSchedulerPolicyType.FIRST || this.lastDtxn != dtxn || this.lastIterator == null || (this.ignore_speculation_type_change == false && this.lastSpecType != specType) || (this.ignore_queue_size_change == false && this.lastSize != this.queue.size())) { this.lastIterator = this.queue.iterator(); } boolean resetIterator = true; if (profiler != null) profiler.queue_size.put(this.queue.size()); boolean lastHasNext; if (trace.val) LOG.trace(StringUtil.header("BEGIN QUEUE CHECK :: " + dtxn)); while ((lastHasNext = this.lastIterator.hasNext()) == true) { if (this.interrupted) { if (debug.val) LOG.warn(String.format("Search interrupted after %d examinations [%s]", examined_ctr, this.latchMsg.getSimpleName())); if (profiler != null) profiler.interrupts++; break; } AbstractTransaction txn = this.lastIterator.next(); assert(txn != null) : "Null transaction handle " + txn; boolean singlePartition = txn.isPredictSinglePartition(); txn_ctr++; // Skip any distributed or non-local transactions if ((txn instanceof LocalTransaction) == false || singlePartition == false) { if (trace.val) LOG.trace(String.format("Skipping non-speculative candidate %s", txn)); continue; } LocalTransaction localTxn = (LocalTransaction)txn; // Skip anything already executed if (localTxn.isMarkExecuted()) { if (trace.val) LOG.trace(String.format("Skipping %s because it was already executed", txn)); continue; } // Let's check it out! if (profiler != null) profiler.compute_time.start(); if (singlePartition == false) { if (trace.val) LOG.trace(String.format("Skipping %s because it is not single-partitioned", localTxn)); continue; } if (debug.val) LOG.debug(String.format("Examining whether %s conflicts with current dtxn", localTxn)); examined_ctr++; try { switch (specType) { // We can execute anything when we are in 2PC or idle case IDLE: case SP2_REMOTE_BEFORE: case SP3_LOCAL: case SP3_REMOTE: { break; } // For SP1 + SP2 we can execute anything if the txn has not // executed a query at this partition. case SP1_LOCAL: case SP2_REMOTE_AFTER: { if (this.checker.canExecute(dtxn, localTxn, this.partitionId) == false) { continue; } break; } // BUSTED! default: String msg = String.format("Unexpected %s.%s", specType.getClass().getSimpleName(), specType); throw new RuntimeException(msg); } // SWITCH // Scheduling Policy: FIRST MATCH if (this.policyType == SpecExecSchedulerPolicyType.FIRST) { next = localTxn; resetIterator = false; break; } // Estimate the time that remains. EstimatorState es = localTxn.getEstimatorState(); if (es != null) { long remainingTime = es.getLastEstimate().getRemainingExecutionTime(); if ((this.policyType == SpecExecSchedulerPolicyType.SHORTEST && remainingTime < bestTime) || (this.policyType == SpecExecSchedulerPolicyType.LONGEST && remainingTime > bestTime)) { bestTime = remainingTime; next = localTxn; if (debug.val) LOG.debug(String.format("[%s %d/%d] New Match -> %s / remainingTime=%d", this.policyType, examined_ctr, this.windowSize, next, remainingTime)); } } // Stop if we've reached our window size if (examined_ctr == this.windowSize) break; } finally { if (profiler != null) profiler.compute_time.stop(); } } // WHILE if (trace.val) LOG.trace(StringUtil.header("END QUEUE CHECK")); if (profiler != null) profiler.num_comparisons.put(txn_ctr); // We found somebody to execute right now! // Make sure that we set the speculative flag to true! if (next != null) { next.markReleased(this.partitionId); if (profiler != null) { this.profilerExecuteCounter.put(specType.ordinal()); profiler.success++; } if (this.policyType == SpecExecSchedulerPolicyType.FIRST) { this.lastIterator.remove(); } else { this.queue.remove(next); } if (debug.val) LOG.debug(dtxn + " - Found next non-conflicting speculative txn " + next); } else if (debug.val && this.queue.isEmpty() == false) { LOG.debug(String.format("Failed to find non-conflicting speculative txn " + "[dtxn=%s, txnCtr=%d, examinedCtr=%d]", dtxn, txn_ctr, examined_ctr)); } this.lastDtxn = dtxn; this.lastSpecType = specType; if (resetIterator || lastHasNext == false) this.lastIterator = null; else if (this.ignore_queue_size_change == false) this.lastSize = this.queue.size(); if (profiler != null) profiler.total_time.stop(); return (next); }
diff --git a/org.eclipse.riena.navigation.ui.swt/src/org/eclipse/riena/navigation/ui/swt/login/ILoginSplashView.java b/org.eclipse.riena.navigation.ui.swt/src/org/eclipse/riena/navigation/ui/swt/login/ILoginSplashView.java index 9734c73fe..0162db365 100644 --- a/org.eclipse.riena.navigation.ui.swt/src/org/eclipse/riena/navigation/ui/swt/login/ILoginSplashView.java +++ b/org.eclipse.riena.navigation.ui.swt/src/org/eclipse/riena/navigation/ui/swt/login/ILoginSplashView.java @@ -1,36 +1,36 @@ /******************************************************************************* * Copyright (c) 2007, 2008 compeople AG 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: * compeople AG - initial API and implementation *******************************************************************************/ package org.eclipse.riena.navigation.ui.swt.login; import org.eclipse.swt.widgets.Composite; /** * The interface which the login splash dialog view should implement. */ public interface ILoginSplashView { /** * Build and open the dialog using parent. */ - public void build(Composite parent); + void build(Composite parent); /** * Returns the result of the login operation. The following conventions have * to be considered: * <ol> * <li>IApplication.EXIT_OK indicates that the login was successful,</li> * <li>In case of some other result the login operation was aborted.</li> * </ol> * * @return the result of the login. */ int getResult(); }
true
true
public void build(Composite parent);
void build(Composite parent);
diff --git a/src/main/java/com/survivorserver/GlobalMarket/Lib/ItemIndex.java b/src/main/java/com/survivorserver/GlobalMarket/Lib/ItemIndex.java index 5bccdd7..8842cc4 100644 --- a/src/main/java/com/survivorserver/GlobalMarket/Lib/ItemIndex.java +++ b/src/main/java/com/survivorserver/GlobalMarket/Lib/ItemIndex.java @@ -1,711 +1,711 @@ package com.survivorserver.GlobalMarket.Lib; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.util.HashMap; import java.util.Map; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.SkullMeta; import com.survivorserver.GlobalMarket.Market; public class ItemIndex { private Market market; private Map<String, String> lang; private Map<MaterialData, String> materialLangMap; private Map<Integer, String> monsterLangMap; private Map<Integer, String[]> potionLangMap; public ItemIndex(Market market) { this.market = market; lang = new HashMap<String, String>(); materialLangMap = new HashMap<MaterialData, String>() { private static final long serialVersionUID = 1L; @Override public String put(MaterialData data, String path) { if (data.material == null) { return path; } return super.put(data, path); } }; monsterLangMap = new HashMap<Integer, String>(); potionLangMap = new HashMap<Integer, String[]>(); market.getConfig().addDefault("language_file", "en_US.lang"); market.getConfig().options().copyDefaults(true); market.saveConfig(); loadLang(); mapMaterials(); } private void loadLang() { File langFile = new File(market.getDataFolder().getAbsolutePath() + File.separator + market.getConfig().getString("language_file")); if (!langFile.exists()) { market.log.warning("No language file could be found, defaulting to internal Bukkit item names"); return; } try { BufferedReader reader = new BufferedReader(new FileReader(langFile)); String line; while((line = reader.readLine()) != null) { // We only need item/block/potion/entity names if (line.contains("=") && (line.contains("item.") || line.contains("tile.") || line.contains("potion.") || line.contains("entity."))) { String[] entry = line.split("="); if (entry.length == 2) { lang.put(entry[0], entry[1]); } } } reader.close(); } catch (Exception e) { market.log.warning(String.format("An error occurred while loading language file %s:", market.getConfig().getString("language_file"))); e.printStackTrace(); } } public String getItemName(ItemStack item) { Material mat = item.getType(); int damage = item.getDurability(); if (mat == Material.POTION) { if (potionLangMap.containsKey(damage)) { String[] potionLang = potionLangMap.get(damage); return (potionLang.length == 2 ? getLocalized(potionLang[1]) + " " : "") + getLocalized(potionLang[0]); } } if (mat == Material.MONSTER_EGG) { if (monsterLangMap.containsKey(damage)) { return getLocalized(materialLangMap.get(new MaterialData(mat))) + " " + getLocalized(monsterLangMap.get(damage)); } } if (item.getType().getMaxDurability() > 64) { // Tools damage = 0; } MaterialData data = new MaterialData(mat, damage); if (!materialLangMap.containsKey(data)) { return mat.name(); } String name = getLocalized(materialLangMap.get(data)); if (mat == Material.SKULL_ITEM && damage == 3) { SkullMeta meta = (SkullMeta) item.getItemMeta(); if (meta.hasOwner()) { name = String.format(name, meta.getOwner()); } else { name = getLocalized("item.skull.char.name"); } } return name; } public String getLocalized(String path) { if (lang.containsKey(path)) { return lang.get(path); } return path; } private void mapMaterials() { monsterLangMap.put(50, "entity.Creeper.name"); monsterLangMap.put(51, "entity.Skeleton.name"); monsterLangMap.put(52, "entity.Spider.name"); monsterLangMap.put(54, "entity.Zombie.name"); monsterLangMap.put(55, "entity.Slime.name"); monsterLangMap.put(56, "entity.Ghast.name"); monsterLangMap.put(57, "entity.PigZombie.name"); monsterLangMap.put(58, "entity.Enderman.name"); monsterLangMap.put(59, "entity.CaveSpider.name"); monsterLangMap.put(60, "entity.Silverfish.name"); monsterLangMap.put(61, "entity.Blaze.name"); monsterLangMap.put(62, "entity.LavaSlime.name"); monsterLangMap.put(65, "entity.Bat.name"); monsterLangMap.put(66, "entity.Witch.name"); monsterLangMap.put(90, "entity.Pig.name"); monsterLangMap.put(91, "entity.Sheep.name"); monsterLangMap.put(92, "entity.Cow.name"); monsterLangMap.put(93, "entity.Chicken.name"); monsterLangMap.put(94, "entity.Squid.name"); monsterLangMap.put(95, "entity.Wolf.name"); monsterLangMap.put(96, "entity.MushroomCow.name"); monsterLangMap.put(98, "entity.Ozelot.name"); monsterLangMap.put(100, "entity.horse.name"); monsterLangMap.put(120, "entity.Villager.name"); potionLangMap.put(16, new String[] {"potion.prefix.awkward"}); potionLangMap.put(32, new String[] {"potion.prefix.thick"}); potionLangMap.put(64, new String[] {"potion.prefix.mundane"}); potionLangMap.put(8193, new String[] {"potion.regeneration.postfix"}); potionLangMap.put(8194, new String[] {"potion.moveSpeed.postfix"}); potionLangMap.put(8196, new String[] {"potion.poison.postfix"}); potionLangMap.put(8201, new String[] {"potion.damageBoost.postfix"}); potionLangMap.put(8226, new String[] {"potion.moveSpeed.postfix"}); potionLangMap.put(8227, new String[] {"potion.fireResistance.postfix"}); potionLangMap.put(8228, new String[] {"potion.poison.postfix"}); potionLangMap.put(8229, new String[] {"potion.heal.postfix"}); potionLangMap.put(8230, new String[] {"potion.nightVision.postfix"}); potionLangMap.put(8232, new String[] {"potion.weakness.postfix"}); potionLangMap.put(8233, new String[] {"potion.damageBoost.postfix"}); potionLangMap.put(8234, new String[] {"potion.moveSlowdown.postfix"}); potionLangMap.put(8236, new String[] {"potion.harm.postfix"}); potionLangMap.put(8237, new String[] {"potion.waterBreathing.postfix"}); potionLangMap.put(8238, new String[] {"potion.invisibility.postfix"}); potionLangMap.put(8255, new String[] {"potion.regeneration.postfix"}); potionLangMap.put(8257, new String[] {"potion.regeneration.postfix"}); potionLangMap.put(8258, new String[] {"potion.moveSpeed.postfix"}); potionLangMap.put(8259, new String[] {"potion.fireResistance.postfix"}); potionLangMap.put(8260, new String[] {"potion.poison.postfix"}); potionLangMap.put(8261, new String[] {"potion.heal.postfix"}); potionLangMap.put(8262, new String[] {"potion.nightVision.postfix"}); potionLangMap.put(8264, new String[] {"potion.weakness.postfix"}); potionLangMap.put(8265, new String[] {"potion.damageBoost.postfix"}); potionLangMap.put(8266, new String[] {"potion.moveSlowdown.postfix"}); potionLangMap.put(8268, new String[] {"potion.harm.postfix"}); potionLangMap.put(8269, new String[] {"potion.waterBreathing.postfix"}); potionLangMap.put(8270, new String[] {"potion.invisibility.postfix"}); potionLangMap.put(16385, new String[] {"potion.regeneration.postfix", "potion.prefix.grenade"}); potionLangMap.put(16386, new String[] {"potion.moveSpeed.postfix", "potion.prefix.grenade"}); potionLangMap.put(16388, new String[] {"potion.poison.postfix", "potion.prefix.grenade"}); potionLangMap.put(16393, new String[] {"potion.damageBoost.postfix", "potion.prefix.grenade"}); potionLangMap.put(16417, new String[] {"potion.regeneration.postfix", "potion.prefix.grenade"}); potionLangMap.put(16418, new String[] {"potion.moveSpeed.postfix", "potion.prefix.grenade"}); potionLangMap.put(16419, new String[] {"potion.fireResistance.postfix", "potion.prefix.grenade"}); potionLangMap.put(16420, new String[] {"potion.poison.postfix", "potion.prefix.grenade"}); potionLangMap.put(16421, new String[] {"potion.heal.postfix", "potion.prefix.grenade"}); potionLangMap.put(16422, new String[] {"potion.nightVision.postfix", "potion.prefix.grenade"}); potionLangMap.put(16424, new String[] {"potion.weakness.postfix", "potion.prefix.grenade"}); potionLangMap.put(16425, new String[] {"potion.damageBoost.postfix", "potion.prefix.grenade"}); potionLangMap.put(16426, new String[] {"potion.invisibility.postfix", "potion.prefix.grenade"}); potionLangMap.put(16428, new String[] {"potion.harm.postfix", "potion.prefix.grenade"}); potionLangMap.put(16429, new String[] {"potion.waterBreathing.postfix", "potion.prefix.grenade"}); potionLangMap.put(16430, new String[] {"potion.invisibility.postfix", "potion.prefix.grenade"}); potionLangMap.put(16449, new String[] {"potion.regeneration.postfix", "potion.prefix.grenade"}); potionLangMap.put(16450, new String[] {"potion.moveSpeed.postfix", "potion.prefix.grenade"}); potionLangMap.put(16451, new String[] {"potion.fireResistance.postfix", "potion.prefix.grenade"}); potionLangMap.put(16452, new String[] {"potion.poison.postfix", "potion.prefix.grenade"}); potionLangMap.put(16453, new String[] {"potion.heal.postfix", "potion.prefix.grenade"}); potionLangMap.put(16454, new String[] {"potion.nightVision.postfix", "potion.prefix.grenade"}); potionLangMap.put(16456, new String[] {"potion.weakness.postfix", "potion.prefix.grenade"}); potionLangMap.put(16457, new String[] {"potion.damageBoost.postfix", "potion.prefix.grenade"}); potionLangMap.put(16458, new String[] {"potion.moveSlowdown.postfix", "potion.prefix.grenade"}); potionLangMap.put(16460, new String[] {"potion.harm.postfix", "potion.prefix.grenade"}); potionLangMap.put(16461, new String[] {"potion.waterBreathing.postfix", "potion.prefix.grenade"}); potionLangMap.put(16462, new String[] {"potion.invisibility.postfix", "potion.prefix.grenade"}); materialLangMap.put(new MaterialData(m("APPLE")), "item.apple.name"); materialLangMap.put(new MaterialData(m("GOLDEN_APPLE")), "item.appleGold.name"); materialLangMap.put(new MaterialData(m("ARROW")), "item.arrow.name"); materialLangMap.put(new MaterialData(m("BED")), "item.bed.name"); materialLangMap.put(new MaterialData(m("COOKED_BEEF")), "item.beefCooked.name"); materialLangMap.put(new MaterialData(m("RAW_BEEF")), "item.beefRaw.name"); materialLangMap.put(new MaterialData(m("BLAZE_POWDER")), "item.blazePowder.name"); materialLangMap.put(new MaterialData(m("BLAZE_ROD")), "item.blazeRod.name"); materialLangMap.put(new MaterialData(m("BOAT")), "item.boat.name"); materialLangMap.put(new MaterialData(m("BONE")), "item.bone.name"); materialLangMap.put(new MaterialData(m("BOOK")), "item.book.name"); materialLangMap.put(new MaterialData(m("CHAINMAIL_BOOTS")), "item.bootsChain.name"); materialLangMap.put(new MaterialData(m("LEATHER_BOOTS")), "item.bootsCloth.name"); materialLangMap.put(new MaterialData(m("DIAMOND_BOOTS")), "item.bootsDiamond.name"); materialLangMap.put(new MaterialData(m("GOLD_BOOTS")), "item.bootsGold.name"); materialLangMap.put(new MaterialData(m("IRON_BOOTS")), "item.bootsIron.name"); materialLangMap.put(new MaterialData(m("BOW")), "item.bow.name"); materialLangMap.put(new MaterialData(m("BOWL")), "item.bowl.name"); materialLangMap.put(new MaterialData(m("BREAD")), "item.bread.name"); materialLangMap.put(new MaterialData(m("BREWING_STAND_ITEM")), "item.brewingStand.name"); materialLangMap.put(new MaterialData(m("CLAY_BRICK")), "item.brick.name"); materialLangMap.put(new MaterialData(m("BUCKET")), "item.bucket.name"); materialLangMap.put(new MaterialData(m("LAVA_BUCKET")), "item.bucketLava.name"); materialLangMap.put(new MaterialData(m("WATER_BUCKET")), "item.bucketWater.name"); materialLangMap.put(new MaterialData(m("CAKE")), "item.cake.name"); materialLangMap.put(new MaterialData(m("GOLDEN_CARROT")), "item.carrotGolden.name"); materialLangMap.put(new MaterialData(m("CARROT_STICK")), "item.carrotOnAStick.name"); materialLangMap.put(new MaterialData(m("CARROT_ITEM")), "item.carrots.name"); materialLangMap.put(new MaterialData(m("CAULDRON_ITEM")), "item.cauldron.name"); materialLangMap.put(new MaterialData(m("COAL, 1")), "item.charcoal.name"); materialLangMap.put(new MaterialData(m("CHAINMAIL_CHESTPLATE")), "item.chestplateChain.name"); materialLangMap.put(new MaterialData(m("LEATHER_CHESTPLATE")), "item.chestplateCloth.name"); materialLangMap.put(new MaterialData(m("DIAMOND_CHESTPLATE")), "item.chestplateDiamond.name"); materialLangMap.put(new MaterialData(m("GOLD_CHESTPLATE")), "item.chestplateGold.name"); materialLangMap.put(new MaterialData(m("IRON_CHESTPLATE")), "item.chestplateIron.name"); materialLangMap.put(new MaterialData(m("COOKED_CHICKEN")), "item.chickenCooked.name"); materialLangMap.put(new MaterialData(m("RAW_CHICKEN")), "item.chickenRaw.name"); materialLangMap.put(new MaterialData(m("CLAY_BALL")), "item.clay.name"); materialLangMap.put(new MaterialData(m("WATCH")), "item.clock.name"); materialLangMap.put(new MaterialData(m("COAL")), "item.coal.name"); materialLangMap.put(new MaterialData(m("REDSTONE_COMPARATOR")), "item.comparator.name"); materialLangMap.put(new MaterialData(m("COMPASS")), "item.compass.name"); materialLangMap.put(new MaterialData(m("COOKIE")), "item.cookie.name"); materialLangMap.put(new MaterialData(m("DIAMOND")), "item.diamond.name"); materialLangMap.put(new MaterialData(m("DIODE")), "item.diode.name"); materialLangMap.put(new MaterialData(m("IRON_DOOR")), "item.doorIron.name"); materialLangMap.put(new MaterialData(m("WOOD_DOOR")), "item.doorWood.name"); materialLangMap.put(new MaterialData(m("INK_SACK")), "item.dyePowder.black.name"); materialLangMap.put(new MaterialData(m("INK_SACK"), 4), "item.dyePowder.blue.name"); materialLangMap.put(new MaterialData(m("INK_SACK"), 3), "item.dyePowder.brown.name"); materialLangMap.put(new MaterialData(m("INK_SACK"), 6), "item.dyePowder.cyan.name"); materialLangMap.put(new MaterialData(m("INK_SACK"), 8), "item.dyePowder.gray.name"); materialLangMap.put(new MaterialData(m("INK_SACK"), 2), "item.dyePowder.green.name"); materialLangMap.put(new MaterialData(m("INK_SACK"), 12), "item.dyePowder.lightBlue.name"); materialLangMap.put(new MaterialData(m("INK_SACK"), 10), "item.dyePowder.lime.name"); materialLangMap.put(new MaterialData(m("INK_SACK"), 13), "item.dyePowder.magenta.name"); materialLangMap.put(new MaterialData(m("INK_SACK"), 14), "item.dyePowder.orange.name"); materialLangMap.put(new MaterialData(m("INK_SACK"), 9), "item.dyePowder.pink.name"); materialLangMap.put(new MaterialData(m("INK_SACK"), 5), "item.dyePowder.purple.name"); materialLangMap.put(new MaterialData(m("INK_SACK"), 1), "item.dyePowder.red.name"); materialLangMap.put(new MaterialData(m("INK_SACK"), 7), "item.dyePowder.silver.name"); materialLangMap.put(new MaterialData(m("INK_SACK"), 15), "item.dyePowder.white.name"); materialLangMap.put(new MaterialData(m("INK_SACK"), 11), "item.dyePowder.yellow.name"); materialLangMap.put(new MaterialData(m("EGG")), "item.egg.name"); materialLangMap.put(new MaterialData(m("EMERALD")), "item.emerald.name"); materialLangMap.put(new MaterialData(m("EMPTY_MAP")), "item.emptyMap.name"); materialLangMap.put(new MaterialData(m("POTION")), "item.emptyPotion.name"); materialLangMap.put(new MaterialData(m("ENCHANTED_BOOK")), "item.enchantedBook.name"); materialLangMap.put(new MaterialData(m("ENDER_PEARL")), "item.enderPearl.name"); materialLangMap.put(new MaterialData(m("EXP_BOTTLE")), "item.expBottle.name"); materialLangMap.put(new MaterialData(m("EYE_OF_ENDER")), "item.eyeOfEnder.name"); materialLangMap.put(new MaterialData(m("FEATHER")), "item.feather.name"); materialLangMap.put(new MaterialData(m("FERMENTED_SPIDER_EYE")), "item.fermentedSpiderEye.name"); materialLangMap.put(new MaterialData(m("FIREBALL")), "item.fireball.name"); materialLangMap.put(new MaterialData(m("FIREWORK")), "item.fireworks.name"); materialLangMap.put(new MaterialData(m("FIREWORK_CHARGE")), "item.fireworksCharge.name"); // TODO firework charge types? materialLangMap.put(new MaterialData(m("RAW_FISH"), 2), "item.fish.clownfish.raw.name"); materialLangMap.put(new MaterialData(m("COOKED_FISH")), "item.fish.cod.cooked.name"); materialLangMap.put(new MaterialData(m("RAW_FISH")), "item.fish.cod.raw.name"); materialLangMap.put(new MaterialData(m("RAW_FISH"), 3), "item.fish.pufferfish.raw.name"); materialLangMap.put(new MaterialData(m("COOKED_FISH"), 1), "item.fish.salmon.cooked.name"); materialLangMap.put(new MaterialData(m("RAW_FISH"), 1), "item.fish.salmon.raw.name"); materialLangMap.put(new MaterialData(m("FISHING_ROD")), "item.fishingRod.name"); materialLangMap.put(new MaterialData(m("FLINT")), "item.flint.name"); materialLangMap.put(new MaterialData(m("FLINT_AND_STEEL")), "item.flintAndSteel.name"); materialLangMap.put(new MaterialData(m("FLOWER_POT_ITEM")), "item.flowerPot.name"); materialLangMap.put(new MaterialData(m("ITEM_FRAME")), "item.frame.name"); materialLangMap.put(new MaterialData(m("GHAST_TEAR")), "item.ghastTear.name"); materialLangMap.put(new MaterialData(m("GLASS_BOTTLE")), "item.glassBottle.name"); materialLangMap.put(new MaterialData(m("GOLD_NUGGET")), "item.goldNugget.name"); materialLangMap.put(new MaterialData(m("DIAMOND_AXE")), "item.hatchetDiamond.name"); materialLangMap.put(new MaterialData(m("GOLD_AXE")), "item.hatchetGold.name"); materialLangMap.put(new MaterialData(m("IRON_AXE")), "item.hatchetIron.name"); materialLangMap.put(new MaterialData(m("STONE_AXE")), "item.hatchetStone.name"); materialLangMap.put(new MaterialData(m("WOOD_AXE")), "item.hatchetWood.name"); materialLangMap.put(new MaterialData(m("CHAINMAIL_HELMET")), "item.helmetChain.name"); materialLangMap.put(new MaterialData(m("LEATHER_HELMET")), "item.helmetCloth.name"); materialLangMap.put(new MaterialData(m("DIAMOND_HELMET")), "item.helmetDiamond.name"); materialLangMap.put(new MaterialData(m("GOLD_HELMET")), "item.helmetGold.name"); materialLangMap.put(new MaterialData(m("IRON_HELMET")), "item.helmetIron.name"); materialLangMap.put(new MaterialData(m("DIAMOND_HOE")), "item.hoeDiamond.name"); materialLangMap.put(new MaterialData(m("GOLD_HOE")), "item.hoeGold.name"); materialLangMap.put(new MaterialData(m("IRON_HOE")), "item.hoeIron.name"); materialLangMap.put(new MaterialData(m("STONE_HOE")), "item.hoeStone.name"); materialLangMap.put(new MaterialData(m("WOOD_HOE")), "item.hoeWood.name"); materialLangMap.put(new MaterialData(m("DIAMOND_BARDING")), "item.horsearmordiamond.name"); materialLangMap.put(new MaterialData(m("GOLD_BARDING")), "item.horsearmorgold.name"); materialLangMap.put(new MaterialData(m("IRON_BARDING")), "item.horsearmormetal.name"); materialLangMap.put(new MaterialData(m("GOLD_INGOT")), "item.ingotGold.name"); materialLangMap.put(new MaterialData(m("IRON_INGOT")), "item.ingotIron.name"); materialLangMap.put(new MaterialData(m("LEASH")), "item.leash.name"); materialLangMap.put(new MaterialData(m("LEATHER")), "item.leather.name"); materialLangMap.put(new MaterialData(m("CHAINMAIL_LEGGINGS")), "item.leggingsChain.name"); materialLangMap.put(new MaterialData(m("LEATHER_LEGGINGS")), "item.leggingsCloth.name"); materialLangMap.put(new MaterialData(m("DIAMOND_LEGGINGS")), "item.leggingsDiamond.name"); materialLangMap.put(new MaterialData(m("GOLD_LEGGINGS")), "item.leggingsGold.name"); materialLangMap.put(new MaterialData(m("IRON_LEGGINGS")), "item.leggingsIron.name"); materialLangMap.put(new MaterialData(m("MAGMA_CREAM")), "item.magmaCream.name"); materialLangMap.put(new MaterialData(m("MAP")), "item.map.name"); materialLangMap.put(new MaterialData(m("MELON")), "item.melon.name"); materialLangMap.put(new MaterialData(m("MILK_BUCKET")), "item.milk.name"); materialLangMap.put(new MaterialData(m("MINECART")), "item.minecart.name"); materialLangMap.put(new MaterialData(m("STORAGE_MINECART")), "item.minecartChest.name"); materialLangMap.put(new MaterialData(m("COMMAND_MINECART")), "item.minecartCommandBlock.name"); materialLangMap.put(new MaterialData(m("POWERED_MINECART")), "item.minecartFurnace.name"); materialLangMap.put(new MaterialData(m("HOPPER_MINECART")), "item.minecartHopper.name"); materialLangMap.put(new MaterialData(m("EXPLOSIVE_MINECART")), "item.minecartTnt.name"); materialLangMap.put(new MaterialData(m("MONSTER_EGG")), "item.monsterPlacer.name"); materialLangMap.put(new MaterialData(m("MUSHROOM_SOUP")), "item.mushroomStew.name"); materialLangMap.put(new MaterialData(m("NAME_TAG")), "item.nameTag.name"); materialLangMap.put(new MaterialData(m("NETHER_WARTS")), "item.netherStalkSeeds.name"); materialLangMap.put(new MaterialData(m("NETHER_STAR")), "item.netherStar.name"); materialLangMap.put(new MaterialData(m("NETHER_BRICK_ITEM")), "item.netherbrick.name"); materialLangMap.put(new MaterialData(m("QUARTZ")), "item.netherquartz.name"); materialLangMap.put(new MaterialData(m("PAINTING")), "item.painting.name"); materialLangMap.put(new MaterialData(m("PAPER")), "item.paper.name"); materialLangMap.put(new MaterialData(m("DIAMOND_PICKAXE")), "item.pickaxeDiamond.name"); materialLangMap.put(new MaterialData(m("GOLD_PICKAXE")), "item.pickaxeGold.name"); materialLangMap.put(new MaterialData(m("IRON_PICKAXE")), "item.pickaxeIron.name"); materialLangMap.put(new MaterialData(m("STONE_PICKAXE")), "item.pickaxeStone.name"); materialLangMap.put(new MaterialData(m("WOOD_PICKAXE")), "item.pickaxeWood.name"); materialLangMap.put(new MaterialData(m("GRILLED_PORK")), "item.porkchopCooked.name"); materialLangMap.put(new MaterialData(m("PORK")), "item.porkchopRaw.name"); materialLangMap.put(new MaterialData(m("POTATO_ITEM")), "item.potato.name"); materialLangMap.put(new MaterialData(m("BAKED_POTATO")), "item.potatoBaked.name"); materialLangMap.put(new MaterialData(m("POISONOUS_POTATO")), "item.potatoPoisonous.name"); materialLangMap.put(new MaterialData(m("PUMPKIN_PIE")), "item.pumpkinPie.name"); // TODO proper record names? materialLangMap.put(new MaterialData(m("GOLD_RECORD")), "item.record.name"); materialLangMap.put(new MaterialData(m("GREEN_RECORD")), "item.record.name"); materialLangMap.put(new MaterialData(m("RECORD_3")), "item.record.name"); materialLangMap.put(new MaterialData(m("RECORD_4")), "item.record.name"); materialLangMap.put(new MaterialData(m("RECORD_5")), "item.record.name"); materialLangMap.put(new MaterialData(m("RECORD_6")), "item.record.name"); materialLangMap.put(new MaterialData(m("RECORD_7")), "item.record.name"); materialLangMap.put(new MaterialData(m("RECORD_8")), "item.record.name"); materialLangMap.put(new MaterialData(m("RECORD_9")), "item.record.name"); materialLangMap.put(new MaterialData(m("RECORD_10")), "item.record.name"); materialLangMap.put(new MaterialData(m("RECORD_11")), "item.record.name"); materialLangMap.put(new MaterialData(m("RECORD_12")), "item.record.name"); // materialLangMap.put(new MaterialData(m("REDSTONE")), "item.redstone.name"); materialLangMap.put(new MaterialData(m("SUGAR_CANE")), "item.reeds.name"); materialLangMap.put(new MaterialData(m("ROTTEN_FLESH")), "item.rottenFlesh.name"); materialLangMap.put(new MaterialData(m("SADDLE")), "item.saddle.name"); materialLangMap.put(new MaterialData(m("SEEDS")), "item.seeds.name"); materialLangMap.put(new MaterialData(m("MELON_SEEDS")), "item.seeds_melon.name"); materialLangMap.put(new MaterialData(m("PUMPKIN_SEEDS")), "item.seeds_pumpkin.name"); materialLangMap.put(new MaterialData(m("SHEARS")), "item.shears.name"); materialLangMap.put(new MaterialData(m("DIAMOND_SPADE")), "item.shovelDiamond.name"); materialLangMap.put(new MaterialData(m("GOLD_SPADE")), "item.shovelGold.name"); materialLangMap.put(new MaterialData(m("IRON_SPADE")), "item.shovelIron.name"); materialLangMap.put(new MaterialData(m("STONE_SPADE")), "item.shovelStone.name"); materialLangMap.put(new MaterialData(m("WOOD_SPADE")), "item.shovelWood.name"); materialLangMap.put(new MaterialData(m("SIGN")), "item.sign.name"); - materialLangMap.put(new MaterialData(m("SKULL"), 4), "item.skull.creeper.name"); - materialLangMap.put(new MaterialData(m("SKULL"), 3), "item.skull.player.name"); - materialLangMap.put(new MaterialData(m("SKULL")), "item.skull.skeleton.name"); - materialLangMap.put(new MaterialData(m("SKULL"), 1), "item.skull.wither.name"); - materialLangMap.put(new MaterialData(m("SKULL"), 2), "item.skull.zombie.name"); + materialLangMap.put(new MaterialData(m("SKULL_ITEM"), 4), "item.skull.creeper.name"); + materialLangMap.put(new MaterialData(m("SKULL_ITEM"), 3), "item.skull.player.name"); + materialLangMap.put(new MaterialData(m("SKULL_ITEM")), "item.skull.skeleton.name"); + materialLangMap.put(new MaterialData(m("SKULL_ITEM"), 1), "item.skull.wither.name"); + materialLangMap.put(new MaterialData(m("SKULL_ITEM"), 2), "item.skull.zombie.name"); materialLangMap.put(new MaterialData(m("SLIME_BALL")), "item.slimeball.name"); materialLangMap.put(new MaterialData(m("SNOW_BALL")), "item.snowball.name"); materialLangMap.put(new MaterialData(m("SPECKLED_MELON")), "item.speckledMelon.name"); materialLangMap.put(new MaterialData(m("SPIDER_EYE")), "item.spiderEye.name"); materialLangMap.put(new MaterialData(m("STICK")), "item.stick.name"); materialLangMap.put(new MaterialData(m("STRING")), "item.string.name"); materialLangMap.put(new MaterialData(m("SUGAR")), "item.sugar.name"); materialLangMap.put(new MaterialData(m("SULPHUR")), "item.sulphur.name"); materialLangMap.put(new MaterialData(m("DIAMOND_SWORD")), "item.swordDiamond.name"); materialLangMap.put(new MaterialData(m("GOLD_SWORD")), "item.swordGold.name"); materialLangMap.put(new MaterialData(m("IRON_SWORD")), "item.swordIron.name"); materialLangMap.put(new MaterialData(m("STONE_SWORD")), "item.swordStone.name"); materialLangMap.put(new MaterialData(m("WOOD_SWORD")), "item.swordWood.name"); materialLangMap.put(new MaterialData(m("WHEAT")), "item.wheat.name"); materialLangMap.put(new MaterialData(m("BOOK_AND_QUILL")), "item.writingBook.name"); materialLangMap.put(new MaterialData(m("WRITTEN_BOOK")), "item.writtenBook.name"); materialLangMap.put(new MaterialData(m("GLOWSTONE_DUST")), "item.yellowDust.name"); materialLangMap.put(new MaterialData(m("ACTIVATOR_RAIL")), "tile.activatorRail.name"); materialLangMap.put(new MaterialData(m("ANVIL")), "tile.anvil.name"); materialLangMap.put(new MaterialData(m("BEACON")), "tile.beacon.name"); materialLangMap.put(new MaterialData(m("BED_BLOCK")), "tile.bed.name"); materialLangMap.put(new MaterialData(m("BEDROCK")), "tile.bedrock.name"); materialLangMap.put(new MaterialData(m("COAL_BLOCK")), "tile.blockCoal.name"); materialLangMap.put(new MaterialData(m("DIAMOND_BLOCK")), "tile.blockDiamond.name"); materialLangMap.put(new MaterialData(m("EMERALD_BLOCK")), "tile.blockEmerald.name"); materialLangMap.put(new MaterialData(m("GOLD_BLOCK")), "tile.blockGold.name"); materialLangMap.put(new MaterialData(m("IRON_BLOCK")), "tile.blockIron.name"); materialLangMap.put(new MaterialData(m("LAPIS_BLOCK")), "tile.blockLapis.name"); materialLangMap.put(new MaterialData(m("REDSTONE_BLOCK")), "tile.blockRedstone.name"); materialLangMap.put(new MaterialData(m("BOOKSHELF")), "tile.bookshelf.name"); materialLangMap.put(new MaterialData(m("BRICK")), "tile.brick.name"); materialLangMap.put(new MaterialData(m("STONE_BUTTON")), "tile.button.name"); materialLangMap.put(new MaterialData(m("CACTUS")), "tile.cactus.name"); materialLangMap.put(new MaterialData(m("CAKE_BLOCK")), "tile.cake.name"); materialLangMap.put(new MaterialData(m("CARROT")), "tile.carrots.name"); materialLangMap.put(new MaterialData(m("CAULDRON")), "tile.cauldron.name"); materialLangMap.put(new MaterialData(m("CHEST")), "tile.chest.name"); materialLangMap.put(new MaterialData(m("TRAPPED_CHEST")), "tile.chestTrap.name"); materialLangMap.put(new MaterialData(m("CLAY")), "tile.clay.name"); materialLangMap.put(new MaterialData(m("HARD_CLAY")), "tile.clayHardened.name"); materialLangMap.put(new MaterialData(m("STAINED_CLAY"), 15), "tile.clayHardenedStained.black.name"); materialLangMap.put(new MaterialData(m("STAINED_CLAY"), 11), "tile.clayHardenedStained.blue.name"); materialLangMap.put(new MaterialData(m("STAINED_CLAY"), 12), "tile.clayHardenedStained.brown.name"); materialLangMap.put(new MaterialData(m("STAINED_CLAY"), 9), "tile.clayHardenedStained.cyan.name"); materialLangMap.put(new MaterialData(m("STAINED_CLAY"), 7), "tile.clayHardenedStained.gray.name"); materialLangMap.put(new MaterialData(m("STAINED_CLAY"), 13), "tile.clayHardenedStained.green.name"); materialLangMap.put(new MaterialData(m("STAINED_CLAY"), 3), "tile.clayHardenedStained.lightBlue.name"); materialLangMap.put(new MaterialData(m("STAINED_CLAY"), 5), "tile.clayHardenedStained.lime.name"); materialLangMap.put(new MaterialData(m("STAINED_CLAY"), 2), "tile.clayHardenedStained.magenta.name"); materialLangMap.put(new MaterialData(m("STAINED_CLAY"), 1), "tile.clayHardenedStained.orange.name"); materialLangMap.put(new MaterialData(m("STAINED_CLAY"), 6), "tile.clayHardenedStained.pink.name"); materialLangMap.put(new MaterialData(m("STAINED_CLAY"), 10), "tile.clayHardenedStained.purple.name"); materialLangMap.put(new MaterialData(m("STAINED_CLAY"), 14), "tile.clayHardenedStained.red.name"); materialLangMap.put(new MaterialData(m("STAINED_CLAY"), 8), "tile.clayHardenedStained.silver.name"); materialLangMap.put(new MaterialData(m("STAINED_CLAY")), "tile.clayHardenedStained.white.name"); materialLangMap.put(new MaterialData(m("STAINED_CLAY"), 4), "tile.clayHardenedStained.yellow.name"); materialLangMap.put(new MaterialData(m("WOOL"), 15), "tile.cloth.black.name"); materialLangMap.put(new MaterialData(m("WOOL"), 11), "tile.cloth.blue.name"); materialLangMap.put(new MaterialData(m("WOOL"), 12), "tile.cloth.brown.name"); materialLangMap.put(new MaterialData(m("WOOL"), 9), "tile.cloth.cyan.name"); materialLangMap.put(new MaterialData(m("WOOL"), 7), "tile.cloth.gray.name"); materialLangMap.put(new MaterialData(m("WOOL"), 13), "tile.cloth.green.name"); materialLangMap.put(new MaterialData(m("WOOL"), 3), "tile.cloth.lightBlue.name"); materialLangMap.put(new MaterialData(m("WOOL"), 5), "tile.cloth.lime.name"); materialLangMap.put(new MaterialData(m("WOOL"), 2), "tile.cloth.magenta.name"); materialLangMap.put(new MaterialData(m("WOOL"), 1), "tile.cloth.orange.name"); materialLangMap.put(new MaterialData(m("WOOL"), 6), "tile.cloth.pink.name"); materialLangMap.put(new MaterialData(m("WOOL"), 10), "tile.cloth.purple.name"); materialLangMap.put(new MaterialData(m("WOOL"), 14), "tile.cloth.red.name"); materialLangMap.put(new MaterialData(m("WOOL"), 8), "tile.cloth.silver.name"); materialLangMap.put(new MaterialData(m("WOOL")), "tile.cloth.white.name"); materialLangMap.put(new MaterialData(m("WOOL"), 4), "tile.cloth.yellow.name"); materialLangMap.put(new MaterialData(m("COBBLE_WALL"), 1), "tile.cobbleWall.mossy.name"); materialLangMap.put(new MaterialData(m("COBBLE_WALL")), "tile.cobbleWall.normal.name"); materialLangMap.put(new MaterialData(m("COCOA")), "tile.cocoa.name"); materialLangMap.put(new MaterialData(m("COMMAND")), "tile.commandBlock.name"); materialLangMap.put(new MaterialData(m("CROPS")), "tile.crops.name"); materialLangMap.put(new MaterialData(m("DAYLIGHT_DETECTOR")), "tile.daylightDetector.name"); materialLangMap.put(new MaterialData(m("DEAD_BUSH")), "tile.deadbush.name"); materialLangMap.put(new MaterialData(m("DETECTOR_RAIL")), "tile.detectorRail.name"); materialLangMap.put(new MaterialData(m("DIRT")), "tile.dirt.default.name"); materialLangMap.put(new MaterialData(m("DIRT"), 2), "tile.dirt.podzol.name"); materialLangMap.put(new MaterialData(m("DISPENSER")), "tile.dispenser.name"); materialLangMap.put(new MaterialData(m("IRON_DOOR_BLOCK")), "tile.doorIron.name"); materialLangMap.put(new MaterialData(m("WOODEN_DOOR")), "tile.doorWood.name"); materialLangMap.put(new MaterialData(m("DOUBLE_PLANT"), 3), "tile.doublePlant.fern.name"); materialLangMap.put(new MaterialData(m("DOUBLE_PLANT"), 2), "tile.doublePlant.grass.name"); materialLangMap.put(new MaterialData(m("DOUBLE_PLANT"), 5), "tile.doublePlant.paeonia.name"); materialLangMap.put(new MaterialData(m("DOUBLE_PLANT"), 4), "tile.doublePlant.rose.name"); materialLangMap.put(new MaterialData(m("DOUBLE_PLANT")), "tile.doublePlant.sunflower.name"); materialLangMap.put(new MaterialData(m("DOUBLE_PLANT"), 1), "tile.doublePlant.syringa.name"); materialLangMap.put(new MaterialData(m("DRAGON_EGG")), "tile.dragonEgg.name"); materialLangMap.put(new MaterialData(m("DROPPER")), "tile.dropper.name"); materialLangMap.put(new MaterialData(m("ENCHANTMENT_TABLE")), "tile.enchantmentTable.name"); materialLangMap.put(new MaterialData(m("ENDER_PORTAL_FRAME")), "tile.endPortalFrame.name"); materialLangMap.put(new MaterialData(m("ENDER_CHEST")), "tile.enderChest.name"); materialLangMap.put(new MaterialData(m("SOIL")), "tile.farmland.name"); materialLangMap.put(new MaterialData(m("FENCE")), "tile.fence.name"); materialLangMap.put(new MaterialData(m("FENCE_GATE")), "tile.fenceGate.name"); materialLangMap.put(new MaterialData(m("IRON_FENCE")), "tile.fenceIron.name"); materialLangMap.put(new MaterialData(m("FIRE")), "tile.fire.name"); materialLangMap.put(new MaterialData(m("YELLOW_FLOWER")), "tile.flower1.dandelion.name"); materialLangMap.put(new MaterialData(m("RED_ROSE"), 2), "tile.flower2.allium.name"); materialLangMap.put(new MaterialData(m("RED_ROSE"), 1), "tile.flower2.blueOrchid.name"); //materialLangMap.put(new MaterialData(m("RED_ROSE")), "tile.flower2.houstonia.name"); materialLangMap.put(new MaterialData(m("RED_ROSE"), 8), "tile.flower2.oxeyeDaisy.name"); materialLangMap.put(new MaterialData(m("RED_ROSE")), "tile.flower2.poppy.name"); materialLangMap.put(new MaterialData(m("RED_ROSE"), 5), "tile.flower2.tulipOrange.name"); materialLangMap.put(new MaterialData(m("RED_ROSE"), 7), "tile.flower2.tulipPink.name"); materialLangMap.put(new MaterialData(m("RED_ROSE"), 4), "tile.flower2.tulipRed.name"); materialLangMap.put(new MaterialData(m("RED_ROSE"), 6), "tile.flower2.tulipWhite.name"); materialLangMap.put(new MaterialData(m("FURNACE")), "tile.furnace.name"); materialLangMap.put(new MaterialData(m("GLASS")), "tile.glass.name"); materialLangMap.put(new MaterialData(m("POWERED_RAIL")), "tile.goldenRail.name"); materialLangMap.put(new MaterialData(m("GRASS")), "tile.grass.name"); materialLangMap.put(new MaterialData(m("GRAVEL")), "tile.gravel.name"); materialLangMap.put(new MaterialData(m("HAY_BLOCK")), "tile.hayBlock.name"); materialLangMap.put(new MaterialData(m("NETHERRACK")), "tile.hellrock.name"); materialLangMap.put(new MaterialData(m("SOUL_SAND")), "tile.hellsand.name"); materialLangMap.put(new MaterialData(m("HOPPER")), "tile.hopper.name"); materialLangMap.put(new MaterialData(m("ICE")), "tile.ice.name"); materialLangMap.put(new MaterialData(m("PACKED_ICE")), "tile.icePacked.name"); materialLangMap.put(new MaterialData(m("JUKEBOX")), "tile.jukebox.name"); materialLangMap.put(new MaterialData(m("LADDER")), "tile.ladder.name"); materialLangMap.put(new MaterialData(m("LAVA")), "tile.lava.name"); materialLangMap.put(new MaterialData(m("LEAVES_2")), "tile.leaves.acacia.name"); materialLangMap.put(new MaterialData(m("LEAVES_2"), 1), "tile.leaves.big_oak.name"); materialLangMap.put(new MaterialData(m("LEAVES"), 2), "tile.leaves.birch.name"); materialLangMap.put(new MaterialData(m("LEAVES"), 3), "tile.leaves.jungle.name"); materialLangMap.put(new MaterialData(m("LEAVES")), "tile.leaves.oak.name"); materialLangMap.put(new MaterialData(m("LEAVES"), 1), "tile.leaves.spruce.name"); materialLangMap.put(new MaterialData(m("LEVER")), "tile.lever.name"); materialLangMap.put(new MaterialData(m("GLOWSTONE")), "tile.lightgem.name"); materialLangMap.put(new MaterialData(m("JACK_O_LANTERN")), "tile.litpumpkin.name"); materialLangMap.put(new MaterialData(m("LOG_2")), "tile.log.acacia.name"); materialLangMap.put(new MaterialData(m("LOG_2"), 1), "tile.log.big_oak.name"); materialLangMap.put(new MaterialData(m("LOG"), 2), "tile.log.birch.name"); materialLangMap.put(new MaterialData(m("LOG"), 3), "tile.log.jungle.name"); materialLangMap.put(new MaterialData(m("LOG")), "tile.log.name"); materialLangMap.put(new MaterialData(m("LOG")), "tile.log.oak.name"); materialLangMap.put(new MaterialData(m("LOG"), 1), "tile.log.spruce.name"); materialLangMap.put(new MaterialData(m("MELON_BLOCK")), "tile.melon.name"); materialLangMap.put(new MaterialData(m("MOB_SPAWNER")), "tile.mobSpawner.name"); materialLangMap.put(new MaterialData(m("MONSTER_EGGS"), 2), "tile.monsterStoneEgg.brick.name"); materialLangMap.put(new MaterialData(m("MONSTER_EGGS"), 5), "tile.monsterStoneEgg.chiseledbrick.name"); materialLangMap.put(new MaterialData(m("MONSTER_EGGS"), 1), "tile.monsterStoneEgg.cobble.name"); materialLangMap.put(new MaterialData(m("MONSTER_EGGS"), 4), "tile.monsterStoneEgg.crackedbrick.name"); materialLangMap.put(new MaterialData(m("MONSTER_EGGS"), 3), "tile.monsterStoneEgg.mossybrick.name"); materialLangMap.put(new MaterialData(m("MONSTER_EGGS")), "tile.monsterStoneEgg.stone.name"); materialLangMap.put(new MaterialData(m("NOTE_BLOCK")), "tile.musicBlock.name"); materialLangMap.put(new MaterialData(m("MYCEL")), "tile.mycel.name"); materialLangMap.put(new MaterialData(m("NETHER_BRICK")), "tile.netherBrick.name"); materialLangMap.put(new MaterialData(m("NETHER_FENCE")), "tile.netherFence.name"); materialLangMap.put(new MaterialData(m("NETHER_STALK")), "tile.netherStalk.name"); materialLangMap.put(new MaterialData(m("QUARTZ_ORE")), "tile.netherquartz.name"); materialLangMap.put(new MaterialData(m("REDSTONE_TORCH_ON")), "tile.notGate.name"); materialLangMap.put(new MaterialData(m("OBSIDIAN")), "tile.obsidian.name"); materialLangMap.put(new MaterialData(m("COAL_ORE")), "tile.oreCoal.name"); materialLangMap.put(new MaterialData(m("DIAMOND_ORE")), "tile.oreDiamond.name"); materialLangMap.put(new MaterialData(m("EMERALD_ORE")), "tile.oreEmerald.name"); materialLangMap.put(new MaterialData(m("GOLD_ORE")), "tile.oreGold.name"); materialLangMap.put(new MaterialData(m("IRON_ORE")), "tile.oreIron.name"); materialLangMap.put(new MaterialData(m("LAPIS_ORE")), "tile.oreLapis.name"); materialLangMap.put(new MaterialData(m("REDSTONE_ORE")), "tile.oreRedstone.name"); materialLangMap.put(new MaterialData(m("PISTON_BASE")), "tile.pistonBase.name"); materialLangMap.put(new MaterialData(m("PISTON_STICKY_BASE")), "tile.pistonStickyBase.name"); materialLangMap.put(new MaterialData(m("PORTAL")), "tile.portal.name"); materialLangMap.put(new MaterialData(m("POTATO")), "tile.potatoes.name"); materialLangMap.put(new MaterialData(m("STONE_PLATE")), "tile.pressurePlate.name"); materialLangMap.put(new MaterialData(m("PUMPKIN")), "tile.pumpkin.name"); materialLangMap.put(new MaterialData(m("QUARTZ_BLOCK"), 1), "tile.quartzBlock.chiseled.name"); materialLangMap.put(new MaterialData(m("QUARTZ_BLOCK")), "tile.quartzBlock.default.name"); materialLangMap.put(new MaterialData(m("QUARTZ_BLOCK"), 2), "tile.quartzBlock.lines.name"); materialLangMap.put(new MaterialData(m("RAILS")), "tile.rail.name"); materialLangMap.put(new MaterialData(m("REDSTONE_WIRE")), "tile.redstoneDust.name"); materialLangMap.put(new MaterialData(m("REDSTONE_LAMP_OFF")), "tile.redstoneLight.name"); materialLangMap.put(new MaterialData(m("REDSTONE_LAMP_ON")), "tile.redstoneLight.name"); materialLangMap.put(new MaterialData(m("SUGAR_CANE_BLOCK")), "tile.reeds.name"); materialLangMap.put(new MaterialData(m("SAND")), "tile.sand.default.name"); materialLangMap.put(new MaterialData(m("SAND"), 1), "tile.sand.red.name"); materialLangMap.put(new MaterialData(m("SANDSTONE"), 1), "tile.sandStone.chiseled.name"); materialLangMap.put(new MaterialData(m("SANDSTONE")), "tile.sandStone.default.name"); materialLangMap.put(new MaterialData(m("SANDSTONE"), 2), "tile.sandStone.smooth.name"); materialLangMap.put(new MaterialData(m("SAPLING"), 4), "tile.sapling.acacia.name"); materialLangMap.put(new MaterialData(m("SAPLING"), 2), "tile.sapling.birch.name"); materialLangMap.put(new MaterialData(m("SAPLING"), 3), "tile.sapling.jungle.name"); materialLangMap.put(new MaterialData(m("SAPLING")), "tile.sapling.oak.name"); materialLangMap.put(new MaterialData(m("SAPLING"), 5), "tile.sapling.roofed_oak.name"); materialLangMap.put(new MaterialData(m("SAPLING"), 1), "tile.sapling.spruce.name"); materialLangMap.put(new MaterialData(m("SNOW")), "tile.snow.name"); materialLangMap.put(new MaterialData(m("SPONGE")), "tile.sponge.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS"), 15), "tile.stainedGlass.black.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS"), 11), "tile.stainedGlass.blue.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS"), 12), "tile.stainedGlass.brown.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS"), 9), "tile.stainedGlass.cyan.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS"), 7), "tile.stainedGlass.gray.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS"), 13), "tile.stainedGlass.green.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS"), 3), "tile.stainedGlass.lightBlue.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS"), 5), "tile.stainedGlass.lime.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS"), 2), "tile.stainedGlass.magenta.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS"), 1), "tile.stainedGlass.orange.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS"), 6), "tile.stainedGlass.pink.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS"), 10), "tile.stainedGlass.purple.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS"), 14), "tile.stainedGlass.red.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS"), 8), "tile.stainedGlass.silver.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS")), "tile.stainedGlass.white.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS"), 4), "tile.stainedGlass.yellow.name"); materialLangMap.put(new MaterialData(m("BRICK_STAIRS")), "tile.stairsBrick.name"); materialLangMap.put(new MaterialData(m("NETHER_BRICK_STAIRS")), "tile.stairsNetherBrick.name"); materialLangMap.put(new MaterialData(m("QUARTZ_STAIRS")), "tile.stairsQuartz.name"); materialLangMap.put(new MaterialData(m("SANDSTONE_STAIRS")), "tile.stairsSandStone.name"); materialLangMap.put(new MaterialData(m("COBBLESTONE_STAIRS")), "tile.stairsStone.name"); materialLangMap.put(new MaterialData(m("SMOOTH_STAIRS")), "tile.stairsStoneBrickSmooth.name"); materialLangMap.put(new MaterialData(m("WOOD_STAIRS")), "tile.stairsWood.name"); materialLangMap.put(new MaterialData(m("ACACIA_STAIRS")), "tile.stairsWoodAcacia.name"); materialLangMap.put(new MaterialData(m("BIRCH_WOOD_STAIRS")), "tile.stairsWoodBirch.name"); materialLangMap.put(new MaterialData(m("DARK_OAK_STAIRS")), "tile.stairsWoodDarkOak.name"); materialLangMap.put(new MaterialData(m("JUNGLE_WOOD_STAIRS")), "tile.stairsWoodJungle.name"); materialLangMap.put(new MaterialData(m("SPRUCE_WOOD_STAIRS")), "tile.stairsWoodSpruce.name"); materialLangMap.put(new MaterialData(m("STONE")), "tile.stone.name"); materialLangMap.put(new MaterialData(m("MOSSY_COBBLESTONE")), "tile.stoneMoss.name"); materialLangMap.put(new MaterialData(m("STEP"), 4), "tile.stoneSlab.brick.name"); materialLangMap.put(new MaterialData(m("STEP"), 3), "tile.stoneSlab.cobble.name"); materialLangMap.put(new MaterialData(m("STEP"), 6), "tile.stoneSlab.netherBrick.name"); materialLangMap.put(new MaterialData(m("STEP"), 7), "tile.stoneSlab.quartz.name"); materialLangMap.put(new MaterialData(m("STEP"), 1), "tile.stoneSlab.sand.name"); materialLangMap.put(new MaterialData(m("STEP"), 5), "tile.stoneSlab.smoothStoneBrick.name"); materialLangMap.put(new MaterialData(m("STEP")), "tile.stoneSlab.stone.name"); materialLangMap.put(new MaterialData(m("STEP"), 2), "tile.stoneSlab.wood.name"); materialLangMap.put(new MaterialData(m("SMOOTH_BRICK"), 3), "tile.stonebricksmooth.chiseled.name"); materialLangMap.put(new MaterialData(m("SMOOTH_BRICK"), 2), "tile.stonebricksmooth.cracked.name"); materialLangMap.put(new MaterialData(m("SMOOTH_BRICK")), "tile.stonebricksmooth.default.name"); materialLangMap.put(new MaterialData(m("SMOOTH_BRICK"), 1), "tile.stonebricksmooth.mossy.name"); materialLangMap.put(new MaterialData(m("LONG_GRASS"), 2), "tile.tallgrass.fern.name"); materialLangMap.put(new MaterialData(m("LONG_GRASS"), 1), "tile.tallgrass.grass.name"); materialLangMap.put(new MaterialData(m("LONG_GRASS")), "tile.tallgrass.shrub.name"); materialLangMap.put(new MaterialData(m("THIN_GLASS")), "tile.thinGlass.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS_PANE"), 15), "tile.thinStainedGlass.black.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS_PANE"), 11), "tile.thinStainedGlass.blue.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS_PANE"), 12), "tile.thinStainedGlass.brown.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS_PANE"), 9), "tile.thinStainedGlass.cyan.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS_PANE"), 7), "tile.thinStainedGlass.gray.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS_PANE"), 13), "tile.thinStainedGlass.green.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS_PANE"), 3), "tile.thinStainedGlass.lightBlue.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS_PANE"), 5), "tile.thinStainedGlass.lime.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS_PANE"), 2), "tile.thinStainedGlass.magenta.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS_PANE"), 1), "tile.thinStainedGlass.orange.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS_PANE"), 6), "tile.thinStainedGlass.pink.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS_PANE"), 10), "tile.thinStainedGlass.purple.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS_PANE"), 14), "tile.thinStainedGlass.red.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS_PANE"), 8), "tile.thinStainedGlass.silver.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS_PANE")), "tile.thinStainedGlass.white.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS_PANE"), 4), "tile.thinStainedGlass.yellow.name"); materialLangMap.put(new MaterialData(m("TNT")), "tile.tnt.name"); materialLangMap.put(new MaterialData(m("TORCH")), "tile.torch.name"); materialLangMap.put(new MaterialData(m("TRAP_DOOR")), "tile.trapdoor.name"); materialLangMap.put(new MaterialData(m("TRIPWIRE")), "tile.tripWire.name"); materialLangMap.put(new MaterialData(m("TRIPWIRE_HOOK")), "tile.tripWireSource.name"); materialLangMap.put(new MaterialData(m("VINE")), "tile.vine.name"); materialLangMap.put(new MaterialData(m("WATER")), "tile.water.name"); materialLangMap.put(new MaterialData(m("WATER_LILY")), "tile.waterlily.name"); materialLangMap.put(new MaterialData(m("WEB")), "tile.web.name"); materialLangMap.put(new MaterialData(m("GOLD_PLATE")), "tile.weightedPlate_heavy.name"); materialLangMap.put(new MaterialData(m("IRON_PLATE")), "tile.weightedPlate_light.name"); materialLangMap.put(new MaterialData(m("ENDER_STONE")), "tile.whiteStone.name"); materialLangMap.put(new MaterialData(m("WOOD"), 4), "tile.wood.acacia.name"); materialLangMap.put(new MaterialData(m("WOOD"), 5), "tile.wood.big_oak.name"); materialLangMap.put(new MaterialData(m("WOOD"), 2), "tile.wood.birch.name"); materialLangMap.put(new MaterialData(m("WOOD"), 3), "tile.wood.jungle.name"); materialLangMap.put(new MaterialData(m("WOOD")), "tile.wood.oak.name"); materialLangMap.put(new MaterialData(m("WOOD"), 1), "tile.wood.spruce.name"); materialLangMap.put(new MaterialData(m("WOOD_STEP"), 4), "tile.woodSlab.acacia.name"); materialLangMap.put(new MaterialData(m("WOOD_STEP"), 5), "tile.woodSlab.big_oak.name"); materialLangMap.put(new MaterialData(m("WOOD_STEP"), 2), "tile.woodSlab.birch.name"); materialLangMap.put(new MaterialData(m("WOOD_STEP"), 3), "tile.woodSlab.jungle.name"); materialLangMap.put(new MaterialData(m("WOOD_STEP")), "tile.woodSlab.oak.name"); materialLangMap.put(new MaterialData(m("WOOD_STEP"), 1), "tile.woodSlab.spruce.name"); materialLangMap.put(new MaterialData(m("CARPET"), 15), "tile.woolCarpet.black.name"); materialLangMap.put(new MaterialData(m("CARPET"), 11), "tile.woolCarpet.blue.name"); materialLangMap.put(new MaterialData(m("CARPET"), 12), "tile.woolCarpet.brown.name"); materialLangMap.put(new MaterialData(m("CARPET"), 9), "tile.woolCarpet.cyan.name"); materialLangMap.put(new MaterialData(m("CARPET"), 7), "tile.woolCarpet.gray.name"); materialLangMap.put(new MaterialData(m("CARPET"), 13), "tile.woolCarpet.green.name"); materialLangMap.put(new MaterialData(m("CARPET"), 3), "tile.woolCarpet.lightBlue.name"); materialLangMap.put(new MaterialData(m("CARPET"), 5), "tile.woolCarpet.lime.name"); materialLangMap.put(new MaterialData(m("CARPET"), 2), "tile.woolCarpet.magenta.name"); materialLangMap.put(new MaterialData(m("CARPET"), 1), "tile.woolCarpet.orange.name"); materialLangMap.put(new MaterialData(m("CARPET"), 6), "tile.woolCarpet.pink.name"); materialLangMap.put(new MaterialData(m("CARPET"), 10), "tile.woolCarpet.purple.name"); materialLangMap.put(new MaterialData(m("CARPET"), 14), "tile.woolCarpet.red.name"); materialLangMap.put(new MaterialData(m("CARPET"), 8), "tile.woolCarpet.silver.name"); materialLangMap.put(new MaterialData(m("CARPET")), "tile.woolCarpet.white.name"); materialLangMap.put(new MaterialData(m("CARPET"), 4), "tile.woolCarpet.yellow.name"); materialLangMap.put(new MaterialData(m("WORKBENCH")), "tile.workbench.name"); materialLangMap.put(new MaterialData(m("COBBLESTONE")), "tile.stonebrick.name"); } public Material m(String name) { return Material.getMaterial(name); } public class MaterialData { public Material material; public int damage = 0; private MaterialData(Material material) { this.material = material; } private MaterialData(Material material, int damage) { this.material = material; this.damage = damage; } @Override public boolean equals(Object object) { if (object instanceof MaterialData) { return ((MaterialData) object).material == material && ((MaterialData) object).damage == damage; } return false; } @SuppressWarnings("deprecation") @Override public int hashCode() { return material.name().length() + damage + material.getId(); } } }
true
true
private void mapMaterials() { monsterLangMap.put(50, "entity.Creeper.name"); monsterLangMap.put(51, "entity.Skeleton.name"); monsterLangMap.put(52, "entity.Spider.name"); monsterLangMap.put(54, "entity.Zombie.name"); monsterLangMap.put(55, "entity.Slime.name"); monsterLangMap.put(56, "entity.Ghast.name"); monsterLangMap.put(57, "entity.PigZombie.name"); monsterLangMap.put(58, "entity.Enderman.name"); monsterLangMap.put(59, "entity.CaveSpider.name"); monsterLangMap.put(60, "entity.Silverfish.name"); monsterLangMap.put(61, "entity.Blaze.name"); monsterLangMap.put(62, "entity.LavaSlime.name"); monsterLangMap.put(65, "entity.Bat.name"); monsterLangMap.put(66, "entity.Witch.name"); monsterLangMap.put(90, "entity.Pig.name"); monsterLangMap.put(91, "entity.Sheep.name"); monsterLangMap.put(92, "entity.Cow.name"); monsterLangMap.put(93, "entity.Chicken.name"); monsterLangMap.put(94, "entity.Squid.name"); monsterLangMap.put(95, "entity.Wolf.name"); monsterLangMap.put(96, "entity.MushroomCow.name"); monsterLangMap.put(98, "entity.Ozelot.name"); monsterLangMap.put(100, "entity.horse.name"); monsterLangMap.put(120, "entity.Villager.name"); potionLangMap.put(16, new String[] {"potion.prefix.awkward"}); potionLangMap.put(32, new String[] {"potion.prefix.thick"}); potionLangMap.put(64, new String[] {"potion.prefix.mundane"}); potionLangMap.put(8193, new String[] {"potion.regeneration.postfix"}); potionLangMap.put(8194, new String[] {"potion.moveSpeed.postfix"}); potionLangMap.put(8196, new String[] {"potion.poison.postfix"}); potionLangMap.put(8201, new String[] {"potion.damageBoost.postfix"}); potionLangMap.put(8226, new String[] {"potion.moveSpeed.postfix"}); potionLangMap.put(8227, new String[] {"potion.fireResistance.postfix"}); potionLangMap.put(8228, new String[] {"potion.poison.postfix"}); potionLangMap.put(8229, new String[] {"potion.heal.postfix"}); potionLangMap.put(8230, new String[] {"potion.nightVision.postfix"}); potionLangMap.put(8232, new String[] {"potion.weakness.postfix"}); potionLangMap.put(8233, new String[] {"potion.damageBoost.postfix"}); potionLangMap.put(8234, new String[] {"potion.moveSlowdown.postfix"}); potionLangMap.put(8236, new String[] {"potion.harm.postfix"}); potionLangMap.put(8237, new String[] {"potion.waterBreathing.postfix"}); potionLangMap.put(8238, new String[] {"potion.invisibility.postfix"}); potionLangMap.put(8255, new String[] {"potion.regeneration.postfix"}); potionLangMap.put(8257, new String[] {"potion.regeneration.postfix"}); potionLangMap.put(8258, new String[] {"potion.moveSpeed.postfix"}); potionLangMap.put(8259, new String[] {"potion.fireResistance.postfix"}); potionLangMap.put(8260, new String[] {"potion.poison.postfix"}); potionLangMap.put(8261, new String[] {"potion.heal.postfix"}); potionLangMap.put(8262, new String[] {"potion.nightVision.postfix"}); potionLangMap.put(8264, new String[] {"potion.weakness.postfix"}); potionLangMap.put(8265, new String[] {"potion.damageBoost.postfix"}); potionLangMap.put(8266, new String[] {"potion.moveSlowdown.postfix"}); potionLangMap.put(8268, new String[] {"potion.harm.postfix"}); potionLangMap.put(8269, new String[] {"potion.waterBreathing.postfix"}); potionLangMap.put(8270, new String[] {"potion.invisibility.postfix"}); potionLangMap.put(16385, new String[] {"potion.regeneration.postfix", "potion.prefix.grenade"}); potionLangMap.put(16386, new String[] {"potion.moveSpeed.postfix", "potion.prefix.grenade"}); potionLangMap.put(16388, new String[] {"potion.poison.postfix", "potion.prefix.grenade"}); potionLangMap.put(16393, new String[] {"potion.damageBoost.postfix", "potion.prefix.grenade"}); potionLangMap.put(16417, new String[] {"potion.regeneration.postfix", "potion.prefix.grenade"}); potionLangMap.put(16418, new String[] {"potion.moveSpeed.postfix", "potion.prefix.grenade"}); potionLangMap.put(16419, new String[] {"potion.fireResistance.postfix", "potion.prefix.grenade"}); potionLangMap.put(16420, new String[] {"potion.poison.postfix", "potion.prefix.grenade"}); potionLangMap.put(16421, new String[] {"potion.heal.postfix", "potion.prefix.grenade"}); potionLangMap.put(16422, new String[] {"potion.nightVision.postfix", "potion.prefix.grenade"}); potionLangMap.put(16424, new String[] {"potion.weakness.postfix", "potion.prefix.grenade"}); potionLangMap.put(16425, new String[] {"potion.damageBoost.postfix", "potion.prefix.grenade"}); potionLangMap.put(16426, new String[] {"potion.invisibility.postfix", "potion.prefix.grenade"}); potionLangMap.put(16428, new String[] {"potion.harm.postfix", "potion.prefix.grenade"}); potionLangMap.put(16429, new String[] {"potion.waterBreathing.postfix", "potion.prefix.grenade"}); potionLangMap.put(16430, new String[] {"potion.invisibility.postfix", "potion.prefix.grenade"}); potionLangMap.put(16449, new String[] {"potion.regeneration.postfix", "potion.prefix.grenade"}); potionLangMap.put(16450, new String[] {"potion.moveSpeed.postfix", "potion.prefix.grenade"}); potionLangMap.put(16451, new String[] {"potion.fireResistance.postfix", "potion.prefix.grenade"}); potionLangMap.put(16452, new String[] {"potion.poison.postfix", "potion.prefix.grenade"}); potionLangMap.put(16453, new String[] {"potion.heal.postfix", "potion.prefix.grenade"}); potionLangMap.put(16454, new String[] {"potion.nightVision.postfix", "potion.prefix.grenade"}); potionLangMap.put(16456, new String[] {"potion.weakness.postfix", "potion.prefix.grenade"}); potionLangMap.put(16457, new String[] {"potion.damageBoost.postfix", "potion.prefix.grenade"}); potionLangMap.put(16458, new String[] {"potion.moveSlowdown.postfix", "potion.prefix.grenade"}); potionLangMap.put(16460, new String[] {"potion.harm.postfix", "potion.prefix.grenade"}); potionLangMap.put(16461, new String[] {"potion.waterBreathing.postfix", "potion.prefix.grenade"}); potionLangMap.put(16462, new String[] {"potion.invisibility.postfix", "potion.prefix.grenade"}); materialLangMap.put(new MaterialData(m("APPLE")), "item.apple.name"); materialLangMap.put(new MaterialData(m("GOLDEN_APPLE")), "item.appleGold.name"); materialLangMap.put(new MaterialData(m("ARROW")), "item.arrow.name"); materialLangMap.put(new MaterialData(m("BED")), "item.bed.name"); materialLangMap.put(new MaterialData(m("COOKED_BEEF")), "item.beefCooked.name"); materialLangMap.put(new MaterialData(m("RAW_BEEF")), "item.beefRaw.name"); materialLangMap.put(new MaterialData(m("BLAZE_POWDER")), "item.blazePowder.name"); materialLangMap.put(new MaterialData(m("BLAZE_ROD")), "item.blazeRod.name"); materialLangMap.put(new MaterialData(m("BOAT")), "item.boat.name"); materialLangMap.put(new MaterialData(m("BONE")), "item.bone.name"); materialLangMap.put(new MaterialData(m("BOOK")), "item.book.name"); materialLangMap.put(new MaterialData(m("CHAINMAIL_BOOTS")), "item.bootsChain.name"); materialLangMap.put(new MaterialData(m("LEATHER_BOOTS")), "item.bootsCloth.name"); materialLangMap.put(new MaterialData(m("DIAMOND_BOOTS")), "item.bootsDiamond.name"); materialLangMap.put(new MaterialData(m("GOLD_BOOTS")), "item.bootsGold.name"); materialLangMap.put(new MaterialData(m("IRON_BOOTS")), "item.bootsIron.name"); materialLangMap.put(new MaterialData(m("BOW")), "item.bow.name"); materialLangMap.put(new MaterialData(m("BOWL")), "item.bowl.name"); materialLangMap.put(new MaterialData(m("BREAD")), "item.bread.name"); materialLangMap.put(new MaterialData(m("BREWING_STAND_ITEM")), "item.brewingStand.name"); materialLangMap.put(new MaterialData(m("CLAY_BRICK")), "item.brick.name"); materialLangMap.put(new MaterialData(m("BUCKET")), "item.bucket.name"); materialLangMap.put(new MaterialData(m("LAVA_BUCKET")), "item.bucketLava.name"); materialLangMap.put(new MaterialData(m("WATER_BUCKET")), "item.bucketWater.name"); materialLangMap.put(new MaterialData(m("CAKE")), "item.cake.name"); materialLangMap.put(new MaterialData(m("GOLDEN_CARROT")), "item.carrotGolden.name"); materialLangMap.put(new MaterialData(m("CARROT_STICK")), "item.carrotOnAStick.name"); materialLangMap.put(new MaterialData(m("CARROT_ITEM")), "item.carrots.name"); materialLangMap.put(new MaterialData(m("CAULDRON_ITEM")), "item.cauldron.name"); materialLangMap.put(new MaterialData(m("COAL, 1")), "item.charcoal.name"); materialLangMap.put(new MaterialData(m("CHAINMAIL_CHESTPLATE")), "item.chestplateChain.name"); materialLangMap.put(new MaterialData(m("LEATHER_CHESTPLATE")), "item.chestplateCloth.name"); materialLangMap.put(new MaterialData(m("DIAMOND_CHESTPLATE")), "item.chestplateDiamond.name"); materialLangMap.put(new MaterialData(m("GOLD_CHESTPLATE")), "item.chestplateGold.name"); materialLangMap.put(new MaterialData(m("IRON_CHESTPLATE")), "item.chestplateIron.name"); materialLangMap.put(new MaterialData(m("COOKED_CHICKEN")), "item.chickenCooked.name"); materialLangMap.put(new MaterialData(m("RAW_CHICKEN")), "item.chickenRaw.name"); materialLangMap.put(new MaterialData(m("CLAY_BALL")), "item.clay.name"); materialLangMap.put(new MaterialData(m("WATCH")), "item.clock.name"); materialLangMap.put(new MaterialData(m("COAL")), "item.coal.name"); materialLangMap.put(new MaterialData(m("REDSTONE_COMPARATOR")), "item.comparator.name"); materialLangMap.put(new MaterialData(m("COMPASS")), "item.compass.name"); materialLangMap.put(new MaterialData(m("COOKIE")), "item.cookie.name"); materialLangMap.put(new MaterialData(m("DIAMOND")), "item.diamond.name"); materialLangMap.put(new MaterialData(m("DIODE")), "item.diode.name"); materialLangMap.put(new MaterialData(m("IRON_DOOR")), "item.doorIron.name"); materialLangMap.put(new MaterialData(m("WOOD_DOOR")), "item.doorWood.name"); materialLangMap.put(new MaterialData(m("INK_SACK")), "item.dyePowder.black.name"); materialLangMap.put(new MaterialData(m("INK_SACK"), 4), "item.dyePowder.blue.name"); materialLangMap.put(new MaterialData(m("INK_SACK"), 3), "item.dyePowder.brown.name"); materialLangMap.put(new MaterialData(m("INK_SACK"), 6), "item.dyePowder.cyan.name"); materialLangMap.put(new MaterialData(m("INK_SACK"), 8), "item.dyePowder.gray.name"); materialLangMap.put(new MaterialData(m("INK_SACK"), 2), "item.dyePowder.green.name"); materialLangMap.put(new MaterialData(m("INK_SACK"), 12), "item.dyePowder.lightBlue.name"); materialLangMap.put(new MaterialData(m("INK_SACK"), 10), "item.dyePowder.lime.name"); materialLangMap.put(new MaterialData(m("INK_SACK"), 13), "item.dyePowder.magenta.name"); materialLangMap.put(new MaterialData(m("INK_SACK"), 14), "item.dyePowder.orange.name"); materialLangMap.put(new MaterialData(m("INK_SACK"), 9), "item.dyePowder.pink.name"); materialLangMap.put(new MaterialData(m("INK_SACK"), 5), "item.dyePowder.purple.name"); materialLangMap.put(new MaterialData(m("INK_SACK"), 1), "item.dyePowder.red.name"); materialLangMap.put(new MaterialData(m("INK_SACK"), 7), "item.dyePowder.silver.name"); materialLangMap.put(new MaterialData(m("INK_SACK"), 15), "item.dyePowder.white.name"); materialLangMap.put(new MaterialData(m("INK_SACK"), 11), "item.dyePowder.yellow.name"); materialLangMap.put(new MaterialData(m("EGG")), "item.egg.name"); materialLangMap.put(new MaterialData(m("EMERALD")), "item.emerald.name"); materialLangMap.put(new MaterialData(m("EMPTY_MAP")), "item.emptyMap.name"); materialLangMap.put(new MaterialData(m("POTION")), "item.emptyPotion.name"); materialLangMap.put(new MaterialData(m("ENCHANTED_BOOK")), "item.enchantedBook.name"); materialLangMap.put(new MaterialData(m("ENDER_PEARL")), "item.enderPearl.name"); materialLangMap.put(new MaterialData(m("EXP_BOTTLE")), "item.expBottle.name"); materialLangMap.put(new MaterialData(m("EYE_OF_ENDER")), "item.eyeOfEnder.name"); materialLangMap.put(new MaterialData(m("FEATHER")), "item.feather.name"); materialLangMap.put(new MaterialData(m("FERMENTED_SPIDER_EYE")), "item.fermentedSpiderEye.name"); materialLangMap.put(new MaterialData(m("FIREBALL")), "item.fireball.name"); materialLangMap.put(new MaterialData(m("FIREWORK")), "item.fireworks.name"); materialLangMap.put(new MaterialData(m("FIREWORK_CHARGE")), "item.fireworksCharge.name"); // TODO firework charge types? materialLangMap.put(new MaterialData(m("RAW_FISH"), 2), "item.fish.clownfish.raw.name"); materialLangMap.put(new MaterialData(m("COOKED_FISH")), "item.fish.cod.cooked.name"); materialLangMap.put(new MaterialData(m("RAW_FISH")), "item.fish.cod.raw.name"); materialLangMap.put(new MaterialData(m("RAW_FISH"), 3), "item.fish.pufferfish.raw.name"); materialLangMap.put(new MaterialData(m("COOKED_FISH"), 1), "item.fish.salmon.cooked.name"); materialLangMap.put(new MaterialData(m("RAW_FISH"), 1), "item.fish.salmon.raw.name"); materialLangMap.put(new MaterialData(m("FISHING_ROD")), "item.fishingRod.name"); materialLangMap.put(new MaterialData(m("FLINT")), "item.flint.name"); materialLangMap.put(new MaterialData(m("FLINT_AND_STEEL")), "item.flintAndSteel.name"); materialLangMap.put(new MaterialData(m("FLOWER_POT_ITEM")), "item.flowerPot.name"); materialLangMap.put(new MaterialData(m("ITEM_FRAME")), "item.frame.name"); materialLangMap.put(new MaterialData(m("GHAST_TEAR")), "item.ghastTear.name"); materialLangMap.put(new MaterialData(m("GLASS_BOTTLE")), "item.glassBottle.name"); materialLangMap.put(new MaterialData(m("GOLD_NUGGET")), "item.goldNugget.name"); materialLangMap.put(new MaterialData(m("DIAMOND_AXE")), "item.hatchetDiamond.name"); materialLangMap.put(new MaterialData(m("GOLD_AXE")), "item.hatchetGold.name"); materialLangMap.put(new MaterialData(m("IRON_AXE")), "item.hatchetIron.name"); materialLangMap.put(new MaterialData(m("STONE_AXE")), "item.hatchetStone.name"); materialLangMap.put(new MaterialData(m("WOOD_AXE")), "item.hatchetWood.name"); materialLangMap.put(new MaterialData(m("CHAINMAIL_HELMET")), "item.helmetChain.name"); materialLangMap.put(new MaterialData(m("LEATHER_HELMET")), "item.helmetCloth.name"); materialLangMap.put(new MaterialData(m("DIAMOND_HELMET")), "item.helmetDiamond.name"); materialLangMap.put(new MaterialData(m("GOLD_HELMET")), "item.helmetGold.name"); materialLangMap.put(new MaterialData(m("IRON_HELMET")), "item.helmetIron.name"); materialLangMap.put(new MaterialData(m("DIAMOND_HOE")), "item.hoeDiamond.name"); materialLangMap.put(new MaterialData(m("GOLD_HOE")), "item.hoeGold.name"); materialLangMap.put(new MaterialData(m("IRON_HOE")), "item.hoeIron.name"); materialLangMap.put(new MaterialData(m("STONE_HOE")), "item.hoeStone.name"); materialLangMap.put(new MaterialData(m("WOOD_HOE")), "item.hoeWood.name"); materialLangMap.put(new MaterialData(m("DIAMOND_BARDING")), "item.horsearmordiamond.name"); materialLangMap.put(new MaterialData(m("GOLD_BARDING")), "item.horsearmorgold.name"); materialLangMap.put(new MaterialData(m("IRON_BARDING")), "item.horsearmormetal.name"); materialLangMap.put(new MaterialData(m("GOLD_INGOT")), "item.ingotGold.name"); materialLangMap.put(new MaterialData(m("IRON_INGOT")), "item.ingotIron.name"); materialLangMap.put(new MaterialData(m("LEASH")), "item.leash.name"); materialLangMap.put(new MaterialData(m("LEATHER")), "item.leather.name"); materialLangMap.put(new MaterialData(m("CHAINMAIL_LEGGINGS")), "item.leggingsChain.name"); materialLangMap.put(new MaterialData(m("LEATHER_LEGGINGS")), "item.leggingsCloth.name"); materialLangMap.put(new MaterialData(m("DIAMOND_LEGGINGS")), "item.leggingsDiamond.name"); materialLangMap.put(new MaterialData(m("GOLD_LEGGINGS")), "item.leggingsGold.name"); materialLangMap.put(new MaterialData(m("IRON_LEGGINGS")), "item.leggingsIron.name"); materialLangMap.put(new MaterialData(m("MAGMA_CREAM")), "item.magmaCream.name"); materialLangMap.put(new MaterialData(m("MAP")), "item.map.name"); materialLangMap.put(new MaterialData(m("MELON")), "item.melon.name"); materialLangMap.put(new MaterialData(m("MILK_BUCKET")), "item.milk.name"); materialLangMap.put(new MaterialData(m("MINECART")), "item.minecart.name"); materialLangMap.put(new MaterialData(m("STORAGE_MINECART")), "item.minecartChest.name"); materialLangMap.put(new MaterialData(m("COMMAND_MINECART")), "item.minecartCommandBlock.name"); materialLangMap.put(new MaterialData(m("POWERED_MINECART")), "item.minecartFurnace.name"); materialLangMap.put(new MaterialData(m("HOPPER_MINECART")), "item.minecartHopper.name"); materialLangMap.put(new MaterialData(m("EXPLOSIVE_MINECART")), "item.minecartTnt.name"); materialLangMap.put(new MaterialData(m("MONSTER_EGG")), "item.monsterPlacer.name"); materialLangMap.put(new MaterialData(m("MUSHROOM_SOUP")), "item.mushroomStew.name"); materialLangMap.put(new MaterialData(m("NAME_TAG")), "item.nameTag.name"); materialLangMap.put(new MaterialData(m("NETHER_WARTS")), "item.netherStalkSeeds.name"); materialLangMap.put(new MaterialData(m("NETHER_STAR")), "item.netherStar.name"); materialLangMap.put(new MaterialData(m("NETHER_BRICK_ITEM")), "item.netherbrick.name"); materialLangMap.put(new MaterialData(m("QUARTZ")), "item.netherquartz.name"); materialLangMap.put(new MaterialData(m("PAINTING")), "item.painting.name"); materialLangMap.put(new MaterialData(m("PAPER")), "item.paper.name"); materialLangMap.put(new MaterialData(m("DIAMOND_PICKAXE")), "item.pickaxeDiamond.name"); materialLangMap.put(new MaterialData(m("GOLD_PICKAXE")), "item.pickaxeGold.name"); materialLangMap.put(new MaterialData(m("IRON_PICKAXE")), "item.pickaxeIron.name"); materialLangMap.put(new MaterialData(m("STONE_PICKAXE")), "item.pickaxeStone.name"); materialLangMap.put(new MaterialData(m("WOOD_PICKAXE")), "item.pickaxeWood.name"); materialLangMap.put(new MaterialData(m("GRILLED_PORK")), "item.porkchopCooked.name"); materialLangMap.put(new MaterialData(m("PORK")), "item.porkchopRaw.name"); materialLangMap.put(new MaterialData(m("POTATO_ITEM")), "item.potato.name"); materialLangMap.put(new MaterialData(m("BAKED_POTATO")), "item.potatoBaked.name"); materialLangMap.put(new MaterialData(m("POISONOUS_POTATO")), "item.potatoPoisonous.name"); materialLangMap.put(new MaterialData(m("PUMPKIN_PIE")), "item.pumpkinPie.name"); // TODO proper record names? materialLangMap.put(new MaterialData(m("GOLD_RECORD")), "item.record.name"); materialLangMap.put(new MaterialData(m("GREEN_RECORD")), "item.record.name"); materialLangMap.put(new MaterialData(m("RECORD_3")), "item.record.name"); materialLangMap.put(new MaterialData(m("RECORD_4")), "item.record.name"); materialLangMap.put(new MaterialData(m("RECORD_5")), "item.record.name"); materialLangMap.put(new MaterialData(m("RECORD_6")), "item.record.name"); materialLangMap.put(new MaterialData(m("RECORD_7")), "item.record.name"); materialLangMap.put(new MaterialData(m("RECORD_8")), "item.record.name"); materialLangMap.put(new MaterialData(m("RECORD_9")), "item.record.name"); materialLangMap.put(new MaterialData(m("RECORD_10")), "item.record.name"); materialLangMap.put(new MaterialData(m("RECORD_11")), "item.record.name"); materialLangMap.put(new MaterialData(m("RECORD_12")), "item.record.name"); // materialLangMap.put(new MaterialData(m("REDSTONE")), "item.redstone.name"); materialLangMap.put(new MaterialData(m("SUGAR_CANE")), "item.reeds.name"); materialLangMap.put(new MaterialData(m("ROTTEN_FLESH")), "item.rottenFlesh.name"); materialLangMap.put(new MaterialData(m("SADDLE")), "item.saddle.name"); materialLangMap.put(new MaterialData(m("SEEDS")), "item.seeds.name"); materialLangMap.put(new MaterialData(m("MELON_SEEDS")), "item.seeds_melon.name"); materialLangMap.put(new MaterialData(m("PUMPKIN_SEEDS")), "item.seeds_pumpkin.name"); materialLangMap.put(new MaterialData(m("SHEARS")), "item.shears.name"); materialLangMap.put(new MaterialData(m("DIAMOND_SPADE")), "item.shovelDiamond.name"); materialLangMap.put(new MaterialData(m("GOLD_SPADE")), "item.shovelGold.name"); materialLangMap.put(new MaterialData(m("IRON_SPADE")), "item.shovelIron.name"); materialLangMap.put(new MaterialData(m("STONE_SPADE")), "item.shovelStone.name"); materialLangMap.put(new MaterialData(m("WOOD_SPADE")), "item.shovelWood.name"); materialLangMap.put(new MaterialData(m("SIGN")), "item.sign.name"); materialLangMap.put(new MaterialData(m("SKULL"), 4), "item.skull.creeper.name"); materialLangMap.put(new MaterialData(m("SKULL"), 3), "item.skull.player.name"); materialLangMap.put(new MaterialData(m("SKULL")), "item.skull.skeleton.name"); materialLangMap.put(new MaterialData(m("SKULL"), 1), "item.skull.wither.name"); materialLangMap.put(new MaterialData(m("SKULL"), 2), "item.skull.zombie.name"); materialLangMap.put(new MaterialData(m("SLIME_BALL")), "item.slimeball.name"); materialLangMap.put(new MaterialData(m("SNOW_BALL")), "item.snowball.name"); materialLangMap.put(new MaterialData(m("SPECKLED_MELON")), "item.speckledMelon.name"); materialLangMap.put(new MaterialData(m("SPIDER_EYE")), "item.spiderEye.name"); materialLangMap.put(new MaterialData(m("STICK")), "item.stick.name"); materialLangMap.put(new MaterialData(m("STRING")), "item.string.name"); materialLangMap.put(new MaterialData(m("SUGAR")), "item.sugar.name"); materialLangMap.put(new MaterialData(m("SULPHUR")), "item.sulphur.name"); materialLangMap.put(new MaterialData(m("DIAMOND_SWORD")), "item.swordDiamond.name"); materialLangMap.put(new MaterialData(m("GOLD_SWORD")), "item.swordGold.name"); materialLangMap.put(new MaterialData(m("IRON_SWORD")), "item.swordIron.name"); materialLangMap.put(new MaterialData(m("STONE_SWORD")), "item.swordStone.name"); materialLangMap.put(new MaterialData(m("WOOD_SWORD")), "item.swordWood.name"); materialLangMap.put(new MaterialData(m("WHEAT")), "item.wheat.name"); materialLangMap.put(new MaterialData(m("BOOK_AND_QUILL")), "item.writingBook.name"); materialLangMap.put(new MaterialData(m("WRITTEN_BOOK")), "item.writtenBook.name"); materialLangMap.put(new MaterialData(m("GLOWSTONE_DUST")), "item.yellowDust.name"); materialLangMap.put(new MaterialData(m("ACTIVATOR_RAIL")), "tile.activatorRail.name"); materialLangMap.put(new MaterialData(m("ANVIL")), "tile.anvil.name"); materialLangMap.put(new MaterialData(m("BEACON")), "tile.beacon.name"); materialLangMap.put(new MaterialData(m("BED_BLOCK")), "tile.bed.name"); materialLangMap.put(new MaterialData(m("BEDROCK")), "tile.bedrock.name"); materialLangMap.put(new MaterialData(m("COAL_BLOCK")), "tile.blockCoal.name"); materialLangMap.put(new MaterialData(m("DIAMOND_BLOCK")), "tile.blockDiamond.name"); materialLangMap.put(new MaterialData(m("EMERALD_BLOCK")), "tile.blockEmerald.name"); materialLangMap.put(new MaterialData(m("GOLD_BLOCK")), "tile.blockGold.name"); materialLangMap.put(new MaterialData(m("IRON_BLOCK")), "tile.blockIron.name"); materialLangMap.put(new MaterialData(m("LAPIS_BLOCK")), "tile.blockLapis.name"); materialLangMap.put(new MaterialData(m("REDSTONE_BLOCK")), "tile.blockRedstone.name"); materialLangMap.put(new MaterialData(m("BOOKSHELF")), "tile.bookshelf.name"); materialLangMap.put(new MaterialData(m("BRICK")), "tile.brick.name"); materialLangMap.put(new MaterialData(m("STONE_BUTTON")), "tile.button.name"); materialLangMap.put(new MaterialData(m("CACTUS")), "tile.cactus.name"); materialLangMap.put(new MaterialData(m("CAKE_BLOCK")), "tile.cake.name"); materialLangMap.put(new MaterialData(m("CARROT")), "tile.carrots.name"); materialLangMap.put(new MaterialData(m("CAULDRON")), "tile.cauldron.name"); materialLangMap.put(new MaterialData(m("CHEST")), "tile.chest.name"); materialLangMap.put(new MaterialData(m("TRAPPED_CHEST")), "tile.chestTrap.name"); materialLangMap.put(new MaterialData(m("CLAY")), "tile.clay.name"); materialLangMap.put(new MaterialData(m("HARD_CLAY")), "tile.clayHardened.name"); materialLangMap.put(new MaterialData(m("STAINED_CLAY"), 15), "tile.clayHardenedStained.black.name"); materialLangMap.put(new MaterialData(m("STAINED_CLAY"), 11), "tile.clayHardenedStained.blue.name"); materialLangMap.put(new MaterialData(m("STAINED_CLAY"), 12), "tile.clayHardenedStained.brown.name"); materialLangMap.put(new MaterialData(m("STAINED_CLAY"), 9), "tile.clayHardenedStained.cyan.name"); materialLangMap.put(new MaterialData(m("STAINED_CLAY"), 7), "tile.clayHardenedStained.gray.name"); materialLangMap.put(new MaterialData(m("STAINED_CLAY"), 13), "tile.clayHardenedStained.green.name"); materialLangMap.put(new MaterialData(m("STAINED_CLAY"), 3), "tile.clayHardenedStained.lightBlue.name"); materialLangMap.put(new MaterialData(m("STAINED_CLAY"), 5), "tile.clayHardenedStained.lime.name"); materialLangMap.put(new MaterialData(m("STAINED_CLAY"), 2), "tile.clayHardenedStained.magenta.name"); materialLangMap.put(new MaterialData(m("STAINED_CLAY"), 1), "tile.clayHardenedStained.orange.name"); materialLangMap.put(new MaterialData(m("STAINED_CLAY"), 6), "tile.clayHardenedStained.pink.name"); materialLangMap.put(new MaterialData(m("STAINED_CLAY"), 10), "tile.clayHardenedStained.purple.name"); materialLangMap.put(new MaterialData(m("STAINED_CLAY"), 14), "tile.clayHardenedStained.red.name"); materialLangMap.put(new MaterialData(m("STAINED_CLAY"), 8), "tile.clayHardenedStained.silver.name"); materialLangMap.put(new MaterialData(m("STAINED_CLAY")), "tile.clayHardenedStained.white.name"); materialLangMap.put(new MaterialData(m("STAINED_CLAY"), 4), "tile.clayHardenedStained.yellow.name"); materialLangMap.put(new MaterialData(m("WOOL"), 15), "tile.cloth.black.name"); materialLangMap.put(new MaterialData(m("WOOL"), 11), "tile.cloth.blue.name"); materialLangMap.put(new MaterialData(m("WOOL"), 12), "tile.cloth.brown.name"); materialLangMap.put(new MaterialData(m("WOOL"), 9), "tile.cloth.cyan.name"); materialLangMap.put(new MaterialData(m("WOOL"), 7), "tile.cloth.gray.name"); materialLangMap.put(new MaterialData(m("WOOL"), 13), "tile.cloth.green.name"); materialLangMap.put(new MaterialData(m("WOOL"), 3), "tile.cloth.lightBlue.name"); materialLangMap.put(new MaterialData(m("WOOL"), 5), "tile.cloth.lime.name"); materialLangMap.put(new MaterialData(m("WOOL"), 2), "tile.cloth.magenta.name"); materialLangMap.put(new MaterialData(m("WOOL"), 1), "tile.cloth.orange.name"); materialLangMap.put(new MaterialData(m("WOOL"), 6), "tile.cloth.pink.name"); materialLangMap.put(new MaterialData(m("WOOL"), 10), "tile.cloth.purple.name"); materialLangMap.put(new MaterialData(m("WOOL"), 14), "tile.cloth.red.name"); materialLangMap.put(new MaterialData(m("WOOL"), 8), "tile.cloth.silver.name"); materialLangMap.put(new MaterialData(m("WOOL")), "tile.cloth.white.name"); materialLangMap.put(new MaterialData(m("WOOL"), 4), "tile.cloth.yellow.name"); materialLangMap.put(new MaterialData(m("COBBLE_WALL"), 1), "tile.cobbleWall.mossy.name"); materialLangMap.put(new MaterialData(m("COBBLE_WALL")), "tile.cobbleWall.normal.name"); materialLangMap.put(new MaterialData(m("COCOA")), "tile.cocoa.name"); materialLangMap.put(new MaterialData(m("COMMAND")), "tile.commandBlock.name"); materialLangMap.put(new MaterialData(m("CROPS")), "tile.crops.name"); materialLangMap.put(new MaterialData(m("DAYLIGHT_DETECTOR")), "tile.daylightDetector.name"); materialLangMap.put(new MaterialData(m("DEAD_BUSH")), "tile.deadbush.name"); materialLangMap.put(new MaterialData(m("DETECTOR_RAIL")), "tile.detectorRail.name"); materialLangMap.put(new MaterialData(m("DIRT")), "tile.dirt.default.name"); materialLangMap.put(new MaterialData(m("DIRT"), 2), "tile.dirt.podzol.name"); materialLangMap.put(new MaterialData(m("DISPENSER")), "tile.dispenser.name"); materialLangMap.put(new MaterialData(m("IRON_DOOR_BLOCK")), "tile.doorIron.name"); materialLangMap.put(new MaterialData(m("WOODEN_DOOR")), "tile.doorWood.name"); materialLangMap.put(new MaterialData(m("DOUBLE_PLANT"), 3), "tile.doublePlant.fern.name"); materialLangMap.put(new MaterialData(m("DOUBLE_PLANT"), 2), "tile.doublePlant.grass.name"); materialLangMap.put(new MaterialData(m("DOUBLE_PLANT"), 5), "tile.doublePlant.paeonia.name"); materialLangMap.put(new MaterialData(m("DOUBLE_PLANT"), 4), "tile.doublePlant.rose.name"); materialLangMap.put(new MaterialData(m("DOUBLE_PLANT")), "tile.doublePlant.sunflower.name"); materialLangMap.put(new MaterialData(m("DOUBLE_PLANT"), 1), "tile.doublePlant.syringa.name"); materialLangMap.put(new MaterialData(m("DRAGON_EGG")), "tile.dragonEgg.name"); materialLangMap.put(new MaterialData(m("DROPPER")), "tile.dropper.name"); materialLangMap.put(new MaterialData(m("ENCHANTMENT_TABLE")), "tile.enchantmentTable.name"); materialLangMap.put(new MaterialData(m("ENDER_PORTAL_FRAME")), "tile.endPortalFrame.name"); materialLangMap.put(new MaterialData(m("ENDER_CHEST")), "tile.enderChest.name"); materialLangMap.put(new MaterialData(m("SOIL")), "tile.farmland.name"); materialLangMap.put(new MaterialData(m("FENCE")), "tile.fence.name"); materialLangMap.put(new MaterialData(m("FENCE_GATE")), "tile.fenceGate.name"); materialLangMap.put(new MaterialData(m("IRON_FENCE")), "tile.fenceIron.name"); materialLangMap.put(new MaterialData(m("FIRE")), "tile.fire.name"); materialLangMap.put(new MaterialData(m("YELLOW_FLOWER")), "tile.flower1.dandelion.name"); materialLangMap.put(new MaterialData(m("RED_ROSE"), 2), "tile.flower2.allium.name"); materialLangMap.put(new MaterialData(m("RED_ROSE"), 1), "tile.flower2.blueOrchid.name"); //materialLangMap.put(new MaterialData(m("RED_ROSE")), "tile.flower2.houstonia.name"); materialLangMap.put(new MaterialData(m("RED_ROSE"), 8), "tile.flower2.oxeyeDaisy.name"); materialLangMap.put(new MaterialData(m("RED_ROSE")), "tile.flower2.poppy.name"); materialLangMap.put(new MaterialData(m("RED_ROSE"), 5), "tile.flower2.tulipOrange.name"); materialLangMap.put(new MaterialData(m("RED_ROSE"), 7), "tile.flower2.tulipPink.name"); materialLangMap.put(new MaterialData(m("RED_ROSE"), 4), "tile.flower2.tulipRed.name"); materialLangMap.put(new MaterialData(m("RED_ROSE"), 6), "tile.flower2.tulipWhite.name"); materialLangMap.put(new MaterialData(m("FURNACE")), "tile.furnace.name"); materialLangMap.put(new MaterialData(m("GLASS")), "tile.glass.name"); materialLangMap.put(new MaterialData(m("POWERED_RAIL")), "tile.goldenRail.name"); materialLangMap.put(new MaterialData(m("GRASS")), "tile.grass.name"); materialLangMap.put(new MaterialData(m("GRAVEL")), "tile.gravel.name"); materialLangMap.put(new MaterialData(m("HAY_BLOCK")), "tile.hayBlock.name"); materialLangMap.put(new MaterialData(m("NETHERRACK")), "tile.hellrock.name"); materialLangMap.put(new MaterialData(m("SOUL_SAND")), "tile.hellsand.name"); materialLangMap.put(new MaterialData(m("HOPPER")), "tile.hopper.name"); materialLangMap.put(new MaterialData(m("ICE")), "tile.ice.name"); materialLangMap.put(new MaterialData(m("PACKED_ICE")), "tile.icePacked.name"); materialLangMap.put(new MaterialData(m("JUKEBOX")), "tile.jukebox.name"); materialLangMap.put(new MaterialData(m("LADDER")), "tile.ladder.name"); materialLangMap.put(new MaterialData(m("LAVA")), "tile.lava.name"); materialLangMap.put(new MaterialData(m("LEAVES_2")), "tile.leaves.acacia.name"); materialLangMap.put(new MaterialData(m("LEAVES_2"), 1), "tile.leaves.big_oak.name"); materialLangMap.put(new MaterialData(m("LEAVES"), 2), "tile.leaves.birch.name"); materialLangMap.put(new MaterialData(m("LEAVES"), 3), "tile.leaves.jungle.name"); materialLangMap.put(new MaterialData(m("LEAVES")), "tile.leaves.oak.name"); materialLangMap.put(new MaterialData(m("LEAVES"), 1), "tile.leaves.spruce.name"); materialLangMap.put(new MaterialData(m("LEVER")), "tile.lever.name"); materialLangMap.put(new MaterialData(m("GLOWSTONE")), "tile.lightgem.name"); materialLangMap.put(new MaterialData(m("JACK_O_LANTERN")), "tile.litpumpkin.name"); materialLangMap.put(new MaterialData(m("LOG_2")), "tile.log.acacia.name"); materialLangMap.put(new MaterialData(m("LOG_2"), 1), "tile.log.big_oak.name"); materialLangMap.put(new MaterialData(m("LOG"), 2), "tile.log.birch.name"); materialLangMap.put(new MaterialData(m("LOG"), 3), "tile.log.jungle.name"); materialLangMap.put(new MaterialData(m("LOG")), "tile.log.name"); materialLangMap.put(new MaterialData(m("LOG")), "tile.log.oak.name"); materialLangMap.put(new MaterialData(m("LOG"), 1), "tile.log.spruce.name"); materialLangMap.put(new MaterialData(m("MELON_BLOCK")), "tile.melon.name"); materialLangMap.put(new MaterialData(m("MOB_SPAWNER")), "tile.mobSpawner.name"); materialLangMap.put(new MaterialData(m("MONSTER_EGGS"), 2), "tile.monsterStoneEgg.brick.name"); materialLangMap.put(new MaterialData(m("MONSTER_EGGS"), 5), "tile.monsterStoneEgg.chiseledbrick.name"); materialLangMap.put(new MaterialData(m("MONSTER_EGGS"), 1), "tile.monsterStoneEgg.cobble.name"); materialLangMap.put(new MaterialData(m("MONSTER_EGGS"), 4), "tile.monsterStoneEgg.crackedbrick.name"); materialLangMap.put(new MaterialData(m("MONSTER_EGGS"), 3), "tile.monsterStoneEgg.mossybrick.name"); materialLangMap.put(new MaterialData(m("MONSTER_EGGS")), "tile.monsterStoneEgg.stone.name"); materialLangMap.put(new MaterialData(m("NOTE_BLOCK")), "tile.musicBlock.name"); materialLangMap.put(new MaterialData(m("MYCEL")), "tile.mycel.name"); materialLangMap.put(new MaterialData(m("NETHER_BRICK")), "tile.netherBrick.name"); materialLangMap.put(new MaterialData(m("NETHER_FENCE")), "tile.netherFence.name"); materialLangMap.put(new MaterialData(m("NETHER_STALK")), "tile.netherStalk.name"); materialLangMap.put(new MaterialData(m("QUARTZ_ORE")), "tile.netherquartz.name"); materialLangMap.put(new MaterialData(m("REDSTONE_TORCH_ON")), "tile.notGate.name"); materialLangMap.put(new MaterialData(m("OBSIDIAN")), "tile.obsidian.name"); materialLangMap.put(new MaterialData(m("COAL_ORE")), "tile.oreCoal.name"); materialLangMap.put(new MaterialData(m("DIAMOND_ORE")), "tile.oreDiamond.name"); materialLangMap.put(new MaterialData(m("EMERALD_ORE")), "tile.oreEmerald.name"); materialLangMap.put(new MaterialData(m("GOLD_ORE")), "tile.oreGold.name"); materialLangMap.put(new MaterialData(m("IRON_ORE")), "tile.oreIron.name"); materialLangMap.put(new MaterialData(m("LAPIS_ORE")), "tile.oreLapis.name"); materialLangMap.put(new MaterialData(m("REDSTONE_ORE")), "tile.oreRedstone.name"); materialLangMap.put(new MaterialData(m("PISTON_BASE")), "tile.pistonBase.name"); materialLangMap.put(new MaterialData(m("PISTON_STICKY_BASE")), "tile.pistonStickyBase.name"); materialLangMap.put(new MaterialData(m("PORTAL")), "tile.portal.name"); materialLangMap.put(new MaterialData(m("POTATO")), "tile.potatoes.name"); materialLangMap.put(new MaterialData(m("STONE_PLATE")), "tile.pressurePlate.name"); materialLangMap.put(new MaterialData(m("PUMPKIN")), "tile.pumpkin.name"); materialLangMap.put(new MaterialData(m("QUARTZ_BLOCK"), 1), "tile.quartzBlock.chiseled.name"); materialLangMap.put(new MaterialData(m("QUARTZ_BLOCK")), "tile.quartzBlock.default.name"); materialLangMap.put(new MaterialData(m("QUARTZ_BLOCK"), 2), "tile.quartzBlock.lines.name"); materialLangMap.put(new MaterialData(m("RAILS")), "tile.rail.name"); materialLangMap.put(new MaterialData(m("REDSTONE_WIRE")), "tile.redstoneDust.name"); materialLangMap.put(new MaterialData(m("REDSTONE_LAMP_OFF")), "tile.redstoneLight.name"); materialLangMap.put(new MaterialData(m("REDSTONE_LAMP_ON")), "tile.redstoneLight.name"); materialLangMap.put(new MaterialData(m("SUGAR_CANE_BLOCK")), "tile.reeds.name"); materialLangMap.put(new MaterialData(m("SAND")), "tile.sand.default.name"); materialLangMap.put(new MaterialData(m("SAND"), 1), "tile.sand.red.name"); materialLangMap.put(new MaterialData(m("SANDSTONE"), 1), "tile.sandStone.chiseled.name"); materialLangMap.put(new MaterialData(m("SANDSTONE")), "tile.sandStone.default.name"); materialLangMap.put(new MaterialData(m("SANDSTONE"), 2), "tile.sandStone.smooth.name"); materialLangMap.put(new MaterialData(m("SAPLING"), 4), "tile.sapling.acacia.name"); materialLangMap.put(new MaterialData(m("SAPLING"), 2), "tile.sapling.birch.name"); materialLangMap.put(new MaterialData(m("SAPLING"), 3), "tile.sapling.jungle.name"); materialLangMap.put(new MaterialData(m("SAPLING")), "tile.sapling.oak.name"); materialLangMap.put(new MaterialData(m("SAPLING"), 5), "tile.sapling.roofed_oak.name"); materialLangMap.put(new MaterialData(m("SAPLING"), 1), "tile.sapling.spruce.name"); materialLangMap.put(new MaterialData(m("SNOW")), "tile.snow.name"); materialLangMap.put(new MaterialData(m("SPONGE")), "tile.sponge.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS"), 15), "tile.stainedGlass.black.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS"), 11), "tile.stainedGlass.blue.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS"), 12), "tile.stainedGlass.brown.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS"), 9), "tile.stainedGlass.cyan.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS"), 7), "tile.stainedGlass.gray.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS"), 13), "tile.stainedGlass.green.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS"), 3), "tile.stainedGlass.lightBlue.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS"), 5), "tile.stainedGlass.lime.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS"), 2), "tile.stainedGlass.magenta.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS"), 1), "tile.stainedGlass.orange.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS"), 6), "tile.stainedGlass.pink.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS"), 10), "tile.stainedGlass.purple.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS"), 14), "tile.stainedGlass.red.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS"), 8), "tile.stainedGlass.silver.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS")), "tile.stainedGlass.white.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS"), 4), "tile.stainedGlass.yellow.name"); materialLangMap.put(new MaterialData(m("BRICK_STAIRS")), "tile.stairsBrick.name"); materialLangMap.put(new MaterialData(m("NETHER_BRICK_STAIRS")), "tile.stairsNetherBrick.name"); materialLangMap.put(new MaterialData(m("QUARTZ_STAIRS")), "tile.stairsQuartz.name"); materialLangMap.put(new MaterialData(m("SANDSTONE_STAIRS")), "tile.stairsSandStone.name"); materialLangMap.put(new MaterialData(m("COBBLESTONE_STAIRS")), "tile.stairsStone.name"); materialLangMap.put(new MaterialData(m("SMOOTH_STAIRS")), "tile.stairsStoneBrickSmooth.name"); materialLangMap.put(new MaterialData(m("WOOD_STAIRS")), "tile.stairsWood.name"); materialLangMap.put(new MaterialData(m("ACACIA_STAIRS")), "tile.stairsWoodAcacia.name"); materialLangMap.put(new MaterialData(m("BIRCH_WOOD_STAIRS")), "tile.stairsWoodBirch.name"); materialLangMap.put(new MaterialData(m("DARK_OAK_STAIRS")), "tile.stairsWoodDarkOak.name"); materialLangMap.put(new MaterialData(m("JUNGLE_WOOD_STAIRS")), "tile.stairsWoodJungle.name"); materialLangMap.put(new MaterialData(m("SPRUCE_WOOD_STAIRS")), "tile.stairsWoodSpruce.name"); materialLangMap.put(new MaterialData(m("STONE")), "tile.stone.name"); materialLangMap.put(new MaterialData(m("MOSSY_COBBLESTONE")), "tile.stoneMoss.name"); materialLangMap.put(new MaterialData(m("STEP"), 4), "tile.stoneSlab.brick.name"); materialLangMap.put(new MaterialData(m("STEP"), 3), "tile.stoneSlab.cobble.name"); materialLangMap.put(new MaterialData(m("STEP"), 6), "tile.stoneSlab.netherBrick.name"); materialLangMap.put(new MaterialData(m("STEP"), 7), "tile.stoneSlab.quartz.name"); materialLangMap.put(new MaterialData(m("STEP"), 1), "tile.stoneSlab.sand.name"); materialLangMap.put(new MaterialData(m("STEP"), 5), "tile.stoneSlab.smoothStoneBrick.name"); materialLangMap.put(new MaterialData(m("STEP")), "tile.stoneSlab.stone.name"); materialLangMap.put(new MaterialData(m("STEP"), 2), "tile.stoneSlab.wood.name"); materialLangMap.put(new MaterialData(m("SMOOTH_BRICK"), 3), "tile.stonebricksmooth.chiseled.name"); materialLangMap.put(new MaterialData(m("SMOOTH_BRICK"), 2), "tile.stonebricksmooth.cracked.name"); materialLangMap.put(new MaterialData(m("SMOOTH_BRICK")), "tile.stonebricksmooth.default.name"); materialLangMap.put(new MaterialData(m("SMOOTH_BRICK"), 1), "tile.stonebricksmooth.mossy.name"); materialLangMap.put(new MaterialData(m("LONG_GRASS"), 2), "tile.tallgrass.fern.name"); materialLangMap.put(new MaterialData(m("LONG_GRASS"), 1), "tile.tallgrass.grass.name"); materialLangMap.put(new MaterialData(m("LONG_GRASS")), "tile.tallgrass.shrub.name"); materialLangMap.put(new MaterialData(m("THIN_GLASS")), "tile.thinGlass.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS_PANE"), 15), "tile.thinStainedGlass.black.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS_PANE"), 11), "tile.thinStainedGlass.blue.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS_PANE"), 12), "tile.thinStainedGlass.brown.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS_PANE"), 9), "tile.thinStainedGlass.cyan.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS_PANE"), 7), "tile.thinStainedGlass.gray.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS_PANE"), 13), "tile.thinStainedGlass.green.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS_PANE"), 3), "tile.thinStainedGlass.lightBlue.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS_PANE"), 5), "tile.thinStainedGlass.lime.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS_PANE"), 2), "tile.thinStainedGlass.magenta.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS_PANE"), 1), "tile.thinStainedGlass.orange.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS_PANE"), 6), "tile.thinStainedGlass.pink.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS_PANE"), 10), "tile.thinStainedGlass.purple.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS_PANE"), 14), "tile.thinStainedGlass.red.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS_PANE"), 8), "tile.thinStainedGlass.silver.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS_PANE")), "tile.thinStainedGlass.white.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS_PANE"), 4), "tile.thinStainedGlass.yellow.name"); materialLangMap.put(new MaterialData(m("TNT")), "tile.tnt.name"); materialLangMap.put(new MaterialData(m("TORCH")), "tile.torch.name"); materialLangMap.put(new MaterialData(m("TRAP_DOOR")), "tile.trapdoor.name"); materialLangMap.put(new MaterialData(m("TRIPWIRE")), "tile.tripWire.name"); materialLangMap.put(new MaterialData(m("TRIPWIRE_HOOK")), "tile.tripWireSource.name"); materialLangMap.put(new MaterialData(m("VINE")), "tile.vine.name"); materialLangMap.put(new MaterialData(m("WATER")), "tile.water.name"); materialLangMap.put(new MaterialData(m("WATER_LILY")), "tile.waterlily.name"); materialLangMap.put(new MaterialData(m("WEB")), "tile.web.name"); materialLangMap.put(new MaterialData(m("GOLD_PLATE")), "tile.weightedPlate_heavy.name"); materialLangMap.put(new MaterialData(m("IRON_PLATE")), "tile.weightedPlate_light.name"); materialLangMap.put(new MaterialData(m("ENDER_STONE")), "tile.whiteStone.name"); materialLangMap.put(new MaterialData(m("WOOD"), 4), "tile.wood.acacia.name"); materialLangMap.put(new MaterialData(m("WOOD"), 5), "tile.wood.big_oak.name"); materialLangMap.put(new MaterialData(m("WOOD"), 2), "tile.wood.birch.name"); materialLangMap.put(new MaterialData(m("WOOD"), 3), "tile.wood.jungle.name"); materialLangMap.put(new MaterialData(m("WOOD")), "tile.wood.oak.name"); materialLangMap.put(new MaterialData(m("WOOD"), 1), "tile.wood.spruce.name"); materialLangMap.put(new MaterialData(m("WOOD_STEP"), 4), "tile.woodSlab.acacia.name"); materialLangMap.put(new MaterialData(m("WOOD_STEP"), 5), "tile.woodSlab.big_oak.name"); materialLangMap.put(new MaterialData(m("WOOD_STEP"), 2), "tile.woodSlab.birch.name"); materialLangMap.put(new MaterialData(m("WOOD_STEP"), 3), "tile.woodSlab.jungle.name"); materialLangMap.put(new MaterialData(m("WOOD_STEP")), "tile.woodSlab.oak.name"); materialLangMap.put(new MaterialData(m("WOOD_STEP"), 1), "tile.woodSlab.spruce.name"); materialLangMap.put(new MaterialData(m("CARPET"), 15), "tile.woolCarpet.black.name"); materialLangMap.put(new MaterialData(m("CARPET"), 11), "tile.woolCarpet.blue.name"); materialLangMap.put(new MaterialData(m("CARPET"), 12), "tile.woolCarpet.brown.name"); materialLangMap.put(new MaterialData(m("CARPET"), 9), "tile.woolCarpet.cyan.name"); materialLangMap.put(new MaterialData(m("CARPET"), 7), "tile.woolCarpet.gray.name"); materialLangMap.put(new MaterialData(m("CARPET"), 13), "tile.woolCarpet.green.name"); materialLangMap.put(new MaterialData(m("CARPET"), 3), "tile.woolCarpet.lightBlue.name"); materialLangMap.put(new MaterialData(m("CARPET"), 5), "tile.woolCarpet.lime.name"); materialLangMap.put(new MaterialData(m("CARPET"), 2), "tile.woolCarpet.magenta.name"); materialLangMap.put(new MaterialData(m("CARPET"), 1), "tile.woolCarpet.orange.name"); materialLangMap.put(new MaterialData(m("CARPET"), 6), "tile.woolCarpet.pink.name"); materialLangMap.put(new MaterialData(m("CARPET"), 10), "tile.woolCarpet.purple.name"); materialLangMap.put(new MaterialData(m("CARPET"), 14), "tile.woolCarpet.red.name"); materialLangMap.put(new MaterialData(m("CARPET"), 8), "tile.woolCarpet.silver.name"); materialLangMap.put(new MaterialData(m("CARPET")), "tile.woolCarpet.white.name"); materialLangMap.put(new MaterialData(m("CARPET"), 4), "tile.woolCarpet.yellow.name"); materialLangMap.put(new MaterialData(m("WORKBENCH")), "tile.workbench.name"); materialLangMap.put(new MaterialData(m("COBBLESTONE")), "tile.stonebrick.name"); }
private void mapMaterials() { monsterLangMap.put(50, "entity.Creeper.name"); monsterLangMap.put(51, "entity.Skeleton.name"); monsterLangMap.put(52, "entity.Spider.name"); monsterLangMap.put(54, "entity.Zombie.name"); monsterLangMap.put(55, "entity.Slime.name"); monsterLangMap.put(56, "entity.Ghast.name"); monsterLangMap.put(57, "entity.PigZombie.name"); monsterLangMap.put(58, "entity.Enderman.name"); monsterLangMap.put(59, "entity.CaveSpider.name"); monsterLangMap.put(60, "entity.Silverfish.name"); monsterLangMap.put(61, "entity.Blaze.name"); monsterLangMap.put(62, "entity.LavaSlime.name"); monsterLangMap.put(65, "entity.Bat.name"); monsterLangMap.put(66, "entity.Witch.name"); monsterLangMap.put(90, "entity.Pig.name"); monsterLangMap.put(91, "entity.Sheep.name"); monsterLangMap.put(92, "entity.Cow.name"); monsterLangMap.put(93, "entity.Chicken.name"); monsterLangMap.put(94, "entity.Squid.name"); monsterLangMap.put(95, "entity.Wolf.name"); monsterLangMap.put(96, "entity.MushroomCow.name"); monsterLangMap.put(98, "entity.Ozelot.name"); monsterLangMap.put(100, "entity.horse.name"); monsterLangMap.put(120, "entity.Villager.name"); potionLangMap.put(16, new String[] {"potion.prefix.awkward"}); potionLangMap.put(32, new String[] {"potion.prefix.thick"}); potionLangMap.put(64, new String[] {"potion.prefix.mundane"}); potionLangMap.put(8193, new String[] {"potion.regeneration.postfix"}); potionLangMap.put(8194, new String[] {"potion.moveSpeed.postfix"}); potionLangMap.put(8196, new String[] {"potion.poison.postfix"}); potionLangMap.put(8201, new String[] {"potion.damageBoost.postfix"}); potionLangMap.put(8226, new String[] {"potion.moveSpeed.postfix"}); potionLangMap.put(8227, new String[] {"potion.fireResistance.postfix"}); potionLangMap.put(8228, new String[] {"potion.poison.postfix"}); potionLangMap.put(8229, new String[] {"potion.heal.postfix"}); potionLangMap.put(8230, new String[] {"potion.nightVision.postfix"}); potionLangMap.put(8232, new String[] {"potion.weakness.postfix"}); potionLangMap.put(8233, new String[] {"potion.damageBoost.postfix"}); potionLangMap.put(8234, new String[] {"potion.moveSlowdown.postfix"}); potionLangMap.put(8236, new String[] {"potion.harm.postfix"}); potionLangMap.put(8237, new String[] {"potion.waterBreathing.postfix"}); potionLangMap.put(8238, new String[] {"potion.invisibility.postfix"}); potionLangMap.put(8255, new String[] {"potion.regeneration.postfix"}); potionLangMap.put(8257, new String[] {"potion.regeneration.postfix"}); potionLangMap.put(8258, new String[] {"potion.moveSpeed.postfix"}); potionLangMap.put(8259, new String[] {"potion.fireResistance.postfix"}); potionLangMap.put(8260, new String[] {"potion.poison.postfix"}); potionLangMap.put(8261, new String[] {"potion.heal.postfix"}); potionLangMap.put(8262, new String[] {"potion.nightVision.postfix"}); potionLangMap.put(8264, new String[] {"potion.weakness.postfix"}); potionLangMap.put(8265, new String[] {"potion.damageBoost.postfix"}); potionLangMap.put(8266, new String[] {"potion.moveSlowdown.postfix"}); potionLangMap.put(8268, new String[] {"potion.harm.postfix"}); potionLangMap.put(8269, new String[] {"potion.waterBreathing.postfix"}); potionLangMap.put(8270, new String[] {"potion.invisibility.postfix"}); potionLangMap.put(16385, new String[] {"potion.regeneration.postfix", "potion.prefix.grenade"}); potionLangMap.put(16386, new String[] {"potion.moveSpeed.postfix", "potion.prefix.grenade"}); potionLangMap.put(16388, new String[] {"potion.poison.postfix", "potion.prefix.grenade"}); potionLangMap.put(16393, new String[] {"potion.damageBoost.postfix", "potion.prefix.grenade"}); potionLangMap.put(16417, new String[] {"potion.regeneration.postfix", "potion.prefix.grenade"}); potionLangMap.put(16418, new String[] {"potion.moveSpeed.postfix", "potion.prefix.grenade"}); potionLangMap.put(16419, new String[] {"potion.fireResistance.postfix", "potion.prefix.grenade"}); potionLangMap.put(16420, new String[] {"potion.poison.postfix", "potion.prefix.grenade"}); potionLangMap.put(16421, new String[] {"potion.heal.postfix", "potion.prefix.grenade"}); potionLangMap.put(16422, new String[] {"potion.nightVision.postfix", "potion.prefix.grenade"}); potionLangMap.put(16424, new String[] {"potion.weakness.postfix", "potion.prefix.grenade"}); potionLangMap.put(16425, new String[] {"potion.damageBoost.postfix", "potion.prefix.grenade"}); potionLangMap.put(16426, new String[] {"potion.invisibility.postfix", "potion.prefix.grenade"}); potionLangMap.put(16428, new String[] {"potion.harm.postfix", "potion.prefix.grenade"}); potionLangMap.put(16429, new String[] {"potion.waterBreathing.postfix", "potion.prefix.grenade"}); potionLangMap.put(16430, new String[] {"potion.invisibility.postfix", "potion.prefix.grenade"}); potionLangMap.put(16449, new String[] {"potion.regeneration.postfix", "potion.prefix.grenade"}); potionLangMap.put(16450, new String[] {"potion.moveSpeed.postfix", "potion.prefix.grenade"}); potionLangMap.put(16451, new String[] {"potion.fireResistance.postfix", "potion.prefix.grenade"}); potionLangMap.put(16452, new String[] {"potion.poison.postfix", "potion.prefix.grenade"}); potionLangMap.put(16453, new String[] {"potion.heal.postfix", "potion.prefix.grenade"}); potionLangMap.put(16454, new String[] {"potion.nightVision.postfix", "potion.prefix.grenade"}); potionLangMap.put(16456, new String[] {"potion.weakness.postfix", "potion.prefix.grenade"}); potionLangMap.put(16457, new String[] {"potion.damageBoost.postfix", "potion.prefix.grenade"}); potionLangMap.put(16458, new String[] {"potion.moveSlowdown.postfix", "potion.prefix.grenade"}); potionLangMap.put(16460, new String[] {"potion.harm.postfix", "potion.prefix.grenade"}); potionLangMap.put(16461, new String[] {"potion.waterBreathing.postfix", "potion.prefix.grenade"}); potionLangMap.put(16462, new String[] {"potion.invisibility.postfix", "potion.prefix.grenade"}); materialLangMap.put(new MaterialData(m("APPLE")), "item.apple.name"); materialLangMap.put(new MaterialData(m("GOLDEN_APPLE")), "item.appleGold.name"); materialLangMap.put(new MaterialData(m("ARROW")), "item.arrow.name"); materialLangMap.put(new MaterialData(m("BED")), "item.bed.name"); materialLangMap.put(new MaterialData(m("COOKED_BEEF")), "item.beefCooked.name"); materialLangMap.put(new MaterialData(m("RAW_BEEF")), "item.beefRaw.name"); materialLangMap.put(new MaterialData(m("BLAZE_POWDER")), "item.blazePowder.name"); materialLangMap.put(new MaterialData(m("BLAZE_ROD")), "item.blazeRod.name"); materialLangMap.put(new MaterialData(m("BOAT")), "item.boat.name"); materialLangMap.put(new MaterialData(m("BONE")), "item.bone.name"); materialLangMap.put(new MaterialData(m("BOOK")), "item.book.name"); materialLangMap.put(new MaterialData(m("CHAINMAIL_BOOTS")), "item.bootsChain.name"); materialLangMap.put(new MaterialData(m("LEATHER_BOOTS")), "item.bootsCloth.name"); materialLangMap.put(new MaterialData(m("DIAMOND_BOOTS")), "item.bootsDiamond.name"); materialLangMap.put(new MaterialData(m("GOLD_BOOTS")), "item.bootsGold.name"); materialLangMap.put(new MaterialData(m("IRON_BOOTS")), "item.bootsIron.name"); materialLangMap.put(new MaterialData(m("BOW")), "item.bow.name"); materialLangMap.put(new MaterialData(m("BOWL")), "item.bowl.name"); materialLangMap.put(new MaterialData(m("BREAD")), "item.bread.name"); materialLangMap.put(new MaterialData(m("BREWING_STAND_ITEM")), "item.brewingStand.name"); materialLangMap.put(new MaterialData(m("CLAY_BRICK")), "item.brick.name"); materialLangMap.put(new MaterialData(m("BUCKET")), "item.bucket.name"); materialLangMap.put(new MaterialData(m("LAVA_BUCKET")), "item.bucketLava.name"); materialLangMap.put(new MaterialData(m("WATER_BUCKET")), "item.bucketWater.name"); materialLangMap.put(new MaterialData(m("CAKE")), "item.cake.name"); materialLangMap.put(new MaterialData(m("GOLDEN_CARROT")), "item.carrotGolden.name"); materialLangMap.put(new MaterialData(m("CARROT_STICK")), "item.carrotOnAStick.name"); materialLangMap.put(new MaterialData(m("CARROT_ITEM")), "item.carrots.name"); materialLangMap.put(new MaterialData(m("CAULDRON_ITEM")), "item.cauldron.name"); materialLangMap.put(new MaterialData(m("COAL, 1")), "item.charcoal.name"); materialLangMap.put(new MaterialData(m("CHAINMAIL_CHESTPLATE")), "item.chestplateChain.name"); materialLangMap.put(new MaterialData(m("LEATHER_CHESTPLATE")), "item.chestplateCloth.name"); materialLangMap.put(new MaterialData(m("DIAMOND_CHESTPLATE")), "item.chestplateDiamond.name"); materialLangMap.put(new MaterialData(m("GOLD_CHESTPLATE")), "item.chestplateGold.name"); materialLangMap.put(new MaterialData(m("IRON_CHESTPLATE")), "item.chestplateIron.name"); materialLangMap.put(new MaterialData(m("COOKED_CHICKEN")), "item.chickenCooked.name"); materialLangMap.put(new MaterialData(m("RAW_CHICKEN")), "item.chickenRaw.name"); materialLangMap.put(new MaterialData(m("CLAY_BALL")), "item.clay.name"); materialLangMap.put(new MaterialData(m("WATCH")), "item.clock.name"); materialLangMap.put(new MaterialData(m("COAL")), "item.coal.name"); materialLangMap.put(new MaterialData(m("REDSTONE_COMPARATOR")), "item.comparator.name"); materialLangMap.put(new MaterialData(m("COMPASS")), "item.compass.name"); materialLangMap.put(new MaterialData(m("COOKIE")), "item.cookie.name"); materialLangMap.put(new MaterialData(m("DIAMOND")), "item.diamond.name"); materialLangMap.put(new MaterialData(m("DIODE")), "item.diode.name"); materialLangMap.put(new MaterialData(m("IRON_DOOR")), "item.doorIron.name"); materialLangMap.put(new MaterialData(m("WOOD_DOOR")), "item.doorWood.name"); materialLangMap.put(new MaterialData(m("INK_SACK")), "item.dyePowder.black.name"); materialLangMap.put(new MaterialData(m("INK_SACK"), 4), "item.dyePowder.blue.name"); materialLangMap.put(new MaterialData(m("INK_SACK"), 3), "item.dyePowder.brown.name"); materialLangMap.put(new MaterialData(m("INK_SACK"), 6), "item.dyePowder.cyan.name"); materialLangMap.put(new MaterialData(m("INK_SACK"), 8), "item.dyePowder.gray.name"); materialLangMap.put(new MaterialData(m("INK_SACK"), 2), "item.dyePowder.green.name"); materialLangMap.put(new MaterialData(m("INK_SACK"), 12), "item.dyePowder.lightBlue.name"); materialLangMap.put(new MaterialData(m("INK_SACK"), 10), "item.dyePowder.lime.name"); materialLangMap.put(new MaterialData(m("INK_SACK"), 13), "item.dyePowder.magenta.name"); materialLangMap.put(new MaterialData(m("INK_SACK"), 14), "item.dyePowder.orange.name"); materialLangMap.put(new MaterialData(m("INK_SACK"), 9), "item.dyePowder.pink.name"); materialLangMap.put(new MaterialData(m("INK_SACK"), 5), "item.dyePowder.purple.name"); materialLangMap.put(new MaterialData(m("INK_SACK"), 1), "item.dyePowder.red.name"); materialLangMap.put(new MaterialData(m("INK_SACK"), 7), "item.dyePowder.silver.name"); materialLangMap.put(new MaterialData(m("INK_SACK"), 15), "item.dyePowder.white.name"); materialLangMap.put(new MaterialData(m("INK_SACK"), 11), "item.dyePowder.yellow.name"); materialLangMap.put(new MaterialData(m("EGG")), "item.egg.name"); materialLangMap.put(new MaterialData(m("EMERALD")), "item.emerald.name"); materialLangMap.put(new MaterialData(m("EMPTY_MAP")), "item.emptyMap.name"); materialLangMap.put(new MaterialData(m("POTION")), "item.emptyPotion.name"); materialLangMap.put(new MaterialData(m("ENCHANTED_BOOK")), "item.enchantedBook.name"); materialLangMap.put(new MaterialData(m("ENDER_PEARL")), "item.enderPearl.name"); materialLangMap.put(new MaterialData(m("EXP_BOTTLE")), "item.expBottle.name"); materialLangMap.put(new MaterialData(m("EYE_OF_ENDER")), "item.eyeOfEnder.name"); materialLangMap.put(new MaterialData(m("FEATHER")), "item.feather.name"); materialLangMap.put(new MaterialData(m("FERMENTED_SPIDER_EYE")), "item.fermentedSpiderEye.name"); materialLangMap.put(new MaterialData(m("FIREBALL")), "item.fireball.name"); materialLangMap.put(new MaterialData(m("FIREWORK")), "item.fireworks.name"); materialLangMap.put(new MaterialData(m("FIREWORK_CHARGE")), "item.fireworksCharge.name"); // TODO firework charge types? materialLangMap.put(new MaterialData(m("RAW_FISH"), 2), "item.fish.clownfish.raw.name"); materialLangMap.put(new MaterialData(m("COOKED_FISH")), "item.fish.cod.cooked.name"); materialLangMap.put(new MaterialData(m("RAW_FISH")), "item.fish.cod.raw.name"); materialLangMap.put(new MaterialData(m("RAW_FISH"), 3), "item.fish.pufferfish.raw.name"); materialLangMap.put(new MaterialData(m("COOKED_FISH"), 1), "item.fish.salmon.cooked.name"); materialLangMap.put(new MaterialData(m("RAW_FISH"), 1), "item.fish.salmon.raw.name"); materialLangMap.put(new MaterialData(m("FISHING_ROD")), "item.fishingRod.name"); materialLangMap.put(new MaterialData(m("FLINT")), "item.flint.name"); materialLangMap.put(new MaterialData(m("FLINT_AND_STEEL")), "item.flintAndSteel.name"); materialLangMap.put(new MaterialData(m("FLOWER_POT_ITEM")), "item.flowerPot.name"); materialLangMap.put(new MaterialData(m("ITEM_FRAME")), "item.frame.name"); materialLangMap.put(new MaterialData(m("GHAST_TEAR")), "item.ghastTear.name"); materialLangMap.put(new MaterialData(m("GLASS_BOTTLE")), "item.glassBottle.name"); materialLangMap.put(new MaterialData(m("GOLD_NUGGET")), "item.goldNugget.name"); materialLangMap.put(new MaterialData(m("DIAMOND_AXE")), "item.hatchetDiamond.name"); materialLangMap.put(new MaterialData(m("GOLD_AXE")), "item.hatchetGold.name"); materialLangMap.put(new MaterialData(m("IRON_AXE")), "item.hatchetIron.name"); materialLangMap.put(new MaterialData(m("STONE_AXE")), "item.hatchetStone.name"); materialLangMap.put(new MaterialData(m("WOOD_AXE")), "item.hatchetWood.name"); materialLangMap.put(new MaterialData(m("CHAINMAIL_HELMET")), "item.helmetChain.name"); materialLangMap.put(new MaterialData(m("LEATHER_HELMET")), "item.helmetCloth.name"); materialLangMap.put(new MaterialData(m("DIAMOND_HELMET")), "item.helmetDiamond.name"); materialLangMap.put(new MaterialData(m("GOLD_HELMET")), "item.helmetGold.name"); materialLangMap.put(new MaterialData(m("IRON_HELMET")), "item.helmetIron.name"); materialLangMap.put(new MaterialData(m("DIAMOND_HOE")), "item.hoeDiamond.name"); materialLangMap.put(new MaterialData(m("GOLD_HOE")), "item.hoeGold.name"); materialLangMap.put(new MaterialData(m("IRON_HOE")), "item.hoeIron.name"); materialLangMap.put(new MaterialData(m("STONE_HOE")), "item.hoeStone.name"); materialLangMap.put(new MaterialData(m("WOOD_HOE")), "item.hoeWood.name"); materialLangMap.put(new MaterialData(m("DIAMOND_BARDING")), "item.horsearmordiamond.name"); materialLangMap.put(new MaterialData(m("GOLD_BARDING")), "item.horsearmorgold.name"); materialLangMap.put(new MaterialData(m("IRON_BARDING")), "item.horsearmormetal.name"); materialLangMap.put(new MaterialData(m("GOLD_INGOT")), "item.ingotGold.name"); materialLangMap.put(new MaterialData(m("IRON_INGOT")), "item.ingotIron.name"); materialLangMap.put(new MaterialData(m("LEASH")), "item.leash.name"); materialLangMap.put(new MaterialData(m("LEATHER")), "item.leather.name"); materialLangMap.put(new MaterialData(m("CHAINMAIL_LEGGINGS")), "item.leggingsChain.name"); materialLangMap.put(new MaterialData(m("LEATHER_LEGGINGS")), "item.leggingsCloth.name"); materialLangMap.put(new MaterialData(m("DIAMOND_LEGGINGS")), "item.leggingsDiamond.name"); materialLangMap.put(new MaterialData(m("GOLD_LEGGINGS")), "item.leggingsGold.name"); materialLangMap.put(new MaterialData(m("IRON_LEGGINGS")), "item.leggingsIron.name"); materialLangMap.put(new MaterialData(m("MAGMA_CREAM")), "item.magmaCream.name"); materialLangMap.put(new MaterialData(m("MAP")), "item.map.name"); materialLangMap.put(new MaterialData(m("MELON")), "item.melon.name"); materialLangMap.put(new MaterialData(m("MILK_BUCKET")), "item.milk.name"); materialLangMap.put(new MaterialData(m("MINECART")), "item.minecart.name"); materialLangMap.put(new MaterialData(m("STORAGE_MINECART")), "item.minecartChest.name"); materialLangMap.put(new MaterialData(m("COMMAND_MINECART")), "item.minecartCommandBlock.name"); materialLangMap.put(new MaterialData(m("POWERED_MINECART")), "item.minecartFurnace.name"); materialLangMap.put(new MaterialData(m("HOPPER_MINECART")), "item.minecartHopper.name"); materialLangMap.put(new MaterialData(m("EXPLOSIVE_MINECART")), "item.minecartTnt.name"); materialLangMap.put(new MaterialData(m("MONSTER_EGG")), "item.monsterPlacer.name"); materialLangMap.put(new MaterialData(m("MUSHROOM_SOUP")), "item.mushroomStew.name"); materialLangMap.put(new MaterialData(m("NAME_TAG")), "item.nameTag.name"); materialLangMap.put(new MaterialData(m("NETHER_WARTS")), "item.netherStalkSeeds.name"); materialLangMap.put(new MaterialData(m("NETHER_STAR")), "item.netherStar.name"); materialLangMap.put(new MaterialData(m("NETHER_BRICK_ITEM")), "item.netherbrick.name"); materialLangMap.put(new MaterialData(m("QUARTZ")), "item.netherquartz.name"); materialLangMap.put(new MaterialData(m("PAINTING")), "item.painting.name"); materialLangMap.put(new MaterialData(m("PAPER")), "item.paper.name"); materialLangMap.put(new MaterialData(m("DIAMOND_PICKAXE")), "item.pickaxeDiamond.name"); materialLangMap.put(new MaterialData(m("GOLD_PICKAXE")), "item.pickaxeGold.name"); materialLangMap.put(new MaterialData(m("IRON_PICKAXE")), "item.pickaxeIron.name"); materialLangMap.put(new MaterialData(m("STONE_PICKAXE")), "item.pickaxeStone.name"); materialLangMap.put(new MaterialData(m("WOOD_PICKAXE")), "item.pickaxeWood.name"); materialLangMap.put(new MaterialData(m("GRILLED_PORK")), "item.porkchopCooked.name"); materialLangMap.put(new MaterialData(m("PORK")), "item.porkchopRaw.name"); materialLangMap.put(new MaterialData(m("POTATO_ITEM")), "item.potato.name"); materialLangMap.put(new MaterialData(m("BAKED_POTATO")), "item.potatoBaked.name"); materialLangMap.put(new MaterialData(m("POISONOUS_POTATO")), "item.potatoPoisonous.name"); materialLangMap.put(new MaterialData(m("PUMPKIN_PIE")), "item.pumpkinPie.name"); // TODO proper record names? materialLangMap.put(new MaterialData(m("GOLD_RECORD")), "item.record.name"); materialLangMap.put(new MaterialData(m("GREEN_RECORD")), "item.record.name"); materialLangMap.put(new MaterialData(m("RECORD_3")), "item.record.name"); materialLangMap.put(new MaterialData(m("RECORD_4")), "item.record.name"); materialLangMap.put(new MaterialData(m("RECORD_5")), "item.record.name"); materialLangMap.put(new MaterialData(m("RECORD_6")), "item.record.name"); materialLangMap.put(new MaterialData(m("RECORD_7")), "item.record.name"); materialLangMap.put(new MaterialData(m("RECORD_8")), "item.record.name"); materialLangMap.put(new MaterialData(m("RECORD_9")), "item.record.name"); materialLangMap.put(new MaterialData(m("RECORD_10")), "item.record.name"); materialLangMap.put(new MaterialData(m("RECORD_11")), "item.record.name"); materialLangMap.put(new MaterialData(m("RECORD_12")), "item.record.name"); // materialLangMap.put(new MaterialData(m("REDSTONE")), "item.redstone.name"); materialLangMap.put(new MaterialData(m("SUGAR_CANE")), "item.reeds.name"); materialLangMap.put(new MaterialData(m("ROTTEN_FLESH")), "item.rottenFlesh.name"); materialLangMap.put(new MaterialData(m("SADDLE")), "item.saddle.name"); materialLangMap.put(new MaterialData(m("SEEDS")), "item.seeds.name"); materialLangMap.put(new MaterialData(m("MELON_SEEDS")), "item.seeds_melon.name"); materialLangMap.put(new MaterialData(m("PUMPKIN_SEEDS")), "item.seeds_pumpkin.name"); materialLangMap.put(new MaterialData(m("SHEARS")), "item.shears.name"); materialLangMap.put(new MaterialData(m("DIAMOND_SPADE")), "item.shovelDiamond.name"); materialLangMap.put(new MaterialData(m("GOLD_SPADE")), "item.shovelGold.name"); materialLangMap.put(new MaterialData(m("IRON_SPADE")), "item.shovelIron.name"); materialLangMap.put(new MaterialData(m("STONE_SPADE")), "item.shovelStone.name"); materialLangMap.put(new MaterialData(m("WOOD_SPADE")), "item.shovelWood.name"); materialLangMap.put(new MaterialData(m("SIGN")), "item.sign.name"); materialLangMap.put(new MaterialData(m("SKULL_ITEM"), 4), "item.skull.creeper.name"); materialLangMap.put(new MaterialData(m("SKULL_ITEM"), 3), "item.skull.player.name"); materialLangMap.put(new MaterialData(m("SKULL_ITEM")), "item.skull.skeleton.name"); materialLangMap.put(new MaterialData(m("SKULL_ITEM"), 1), "item.skull.wither.name"); materialLangMap.put(new MaterialData(m("SKULL_ITEM"), 2), "item.skull.zombie.name"); materialLangMap.put(new MaterialData(m("SLIME_BALL")), "item.slimeball.name"); materialLangMap.put(new MaterialData(m("SNOW_BALL")), "item.snowball.name"); materialLangMap.put(new MaterialData(m("SPECKLED_MELON")), "item.speckledMelon.name"); materialLangMap.put(new MaterialData(m("SPIDER_EYE")), "item.spiderEye.name"); materialLangMap.put(new MaterialData(m("STICK")), "item.stick.name"); materialLangMap.put(new MaterialData(m("STRING")), "item.string.name"); materialLangMap.put(new MaterialData(m("SUGAR")), "item.sugar.name"); materialLangMap.put(new MaterialData(m("SULPHUR")), "item.sulphur.name"); materialLangMap.put(new MaterialData(m("DIAMOND_SWORD")), "item.swordDiamond.name"); materialLangMap.put(new MaterialData(m("GOLD_SWORD")), "item.swordGold.name"); materialLangMap.put(new MaterialData(m("IRON_SWORD")), "item.swordIron.name"); materialLangMap.put(new MaterialData(m("STONE_SWORD")), "item.swordStone.name"); materialLangMap.put(new MaterialData(m("WOOD_SWORD")), "item.swordWood.name"); materialLangMap.put(new MaterialData(m("WHEAT")), "item.wheat.name"); materialLangMap.put(new MaterialData(m("BOOK_AND_QUILL")), "item.writingBook.name"); materialLangMap.put(new MaterialData(m("WRITTEN_BOOK")), "item.writtenBook.name"); materialLangMap.put(new MaterialData(m("GLOWSTONE_DUST")), "item.yellowDust.name"); materialLangMap.put(new MaterialData(m("ACTIVATOR_RAIL")), "tile.activatorRail.name"); materialLangMap.put(new MaterialData(m("ANVIL")), "tile.anvil.name"); materialLangMap.put(new MaterialData(m("BEACON")), "tile.beacon.name"); materialLangMap.put(new MaterialData(m("BED_BLOCK")), "tile.bed.name"); materialLangMap.put(new MaterialData(m("BEDROCK")), "tile.bedrock.name"); materialLangMap.put(new MaterialData(m("COAL_BLOCK")), "tile.blockCoal.name"); materialLangMap.put(new MaterialData(m("DIAMOND_BLOCK")), "tile.blockDiamond.name"); materialLangMap.put(new MaterialData(m("EMERALD_BLOCK")), "tile.blockEmerald.name"); materialLangMap.put(new MaterialData(m("GOLD_BLOCK")), "tile.blockGold.name"); materialLangMap.put(new MaterialData(m("IRON_BLOCK")), "tile.blockIron.name"); materialLangMap.put(new MaterialData(m("LAPIS_BLOCK")), "tile.blockLapis.name"); materialLangMap.put(new MaterialData(m("REDSTONE_BLOCK")), "tile.blockRedstone.name"); materialLangMap.put(new MaterialData(m("BOOKSHELF")), "tile.bookshelf.name"); materialLangMap.put(new MaterialData(m("BRICK")), "tile.brick.name"); materialLangMap.put(new MaterialData(m("STONE_BUTTON")), "tile.button.name"); materialLangMap.put(new MaterialData(m("CACTUS")), "tile.cactus.name"); materialLangMap.put(new MaterialData(m("CAKE_BLOCK")), "tile.cake.name"); materialLangMap.put(new MaterialData(m("CARROT")), "tile.carrots.name"); materialLangMap.put(new MaterialData(m("CAULDRON")), "tile.cauldron.name"); materialLangMap.put(new MaterialData(m("CHEST")), "tile.chest.name"); materialLangMap.put(new MaterialData(m("TRAPPED_CHEST")), "tile.chestTrap.name"); materialLangMap.put(new MaterialData(m("CLAY")), "tile.clay.name"); materialLangMap.put(new MaterialData(m("HARD_CLAY")), "tile.clayHardened.name"); materialLangMap.put(new MaterialData(m("STAINED_CLAY"), 15), "tile.clayHardenedStained.black.name"); materialLangMap.put(new MaterialData(m("STAINED_CLAY"), 11), "tile.clayHardenedStained.blue.name"); materialLangMap.put(new MaterialData(m("STAINED_CLAY"), 12), "tile.clayHardenedStained.brown.name"); materialLangMap.put(new MaterialData(m("STAINED_CLAY"), 9), "tile.clayHardenedStained.cyan.name"); materialLangMap.put(new MaterialData(m("STAINED_CLAY"), 7), "tile.clayHardenedStained.gray.name"); materialLangMap.put(new MaterialData(m("STAINED_CLAY"), 13), "tile.clayHardenedStained.green.name"); materialLangMap.put(new MaterialData(m("STAINED_CLAY"), 3), "tile.clayHardenedStained.lightBlue.name"); materialLangMap.put(new MaterialData(m("STAINED_CLAY"), 5), "tile.clayHardenedStained.lime.name"); materialLangMap.put(new MaterialData(m("STAINED_CLAY"), 2), "tile.clayHardenedStained.magenta.name"); materialLangMap.put(new MaterialData(m("STAINED_CLAY"), 1), "tile.clayHardenedStained.orange.name"); materialLangMap.put(new MaterialData(m("STAINED_CLAY"), 6), "tile.clayHardenedStained.pink.name"); materialLangMap.put(new MaterialData(m("STAINED_CLAY"), 10), "tile.clayHardenedStained.purple.name"); materialLangMap.put(new MaterialData(m("STAINED_CLAY"), 14), "tile.clayHardenedStained.red.name"); materialLangMap.put(new MaterialData(m("STAINED_CLAY"), 8), "tile.clayHardenedStained.silver.name"); materialLangMap.put(new MaterialData(m("STAINED_CLAY")), "tile.clayHardenedStained.white.name"); materialLangMap.put(new MaterialData(m("STAINED_CLAY"), 4), "tile.clayHardenedStained.yellow.name"); materialLangMap.put(new MaterialData(m("WOOL"), 15), "tile.cloth.black.name"); materialLangMap.put(new MaterialData(m("WOOL"), 11), "tile.cloth.blue.name"); materialLangMap.put(new MaterialData(m("WOOL"), 12), "tile.cloth.brown.name"); materialLangMap.put(new MaterialData(m("WOOL"), 9), "tile.cloth.cyan.name"); materialLangMap.put(new MaterialData(m("WOOL"), 7), "tile.cloth.gray.name"); materialLangMap.put(new MaterialData(m("WOOL"), 13), "tile.cloth.green.name"); materialLangMap.put(new MaterialData(m("WOOL"), 3), "tile.cloth.lightBlue.name"); materialLangMap.put(new MaterialData(m("WOOL"), 5), "tile.cloth.lime.name"); materialLangMap.put(new MaterialData(m("WOOL"), 2), "tile.cloth.magenta.name"); materialLangMap.put(new MaterialData(m("WOOL"), 1), "tile.cloth.orange.name"); materialLangMap.put(new MaterialData(m("WOOL"), 6), "tile.cloth.pink.name"); materialLangMap.put(new MaterialData(m("WOOL"), 10), "tile.cloth.purple.name"); materialLangMap.put(new MaterialData(m("WOOL"), 14), "tile.cloth.red.name"); materialLangMap.put(new MaterialData(m("WOOL"), 8), "tile.cloth.silver.name"); materialLangMap.put(new MaterialData(m("WOOL")), "tile.cloth.white.name"); materialLangMap.put(new MaterialData(m("WOOL"), 4), "tile.cloth.yellow.name"); materialLangMap.put(new MaterialData(m("COBBLE_WALL"), 1), "tile.cobbleWall.mossy.name"); materialLangMap.put(new MaterialData(m("COBBLE_WALL")), "tile.cobbleWall.normal.name"); materialLangMap.put(new MaterialData(m("COCOA")), "tile.cocoa.name"); materialLangMap.put(new MaterialData(m("COMMAND")), "tile.commandBlock.name"); materialLangMap.put(new MaterialData(m("CROPS")), "tile.crops.name"); materialLangMap.put(new MaterialData(m("DAYLIGHT_DETECTOR")), "tile.daylightDetector.name"); materialLangMap.put(new MaterialData(m("DEAD_BUSH")), "tile.deadbush.name"); materialLangMap.put(new MaterialData(m("DETECTOR_RAIL")), "tile.detectorRail.name"); materialLangMap.put(new MaterialData(m("DIRT")), "tile.dirt.default.name"); materialLangMap.put(new MaterialData(m("DIRT"), 2), "tile.dirt.podzol.name"); materialLangMap.put(new MaterialData(m("DISPENSER")), "tile.dispenser.name"); materialLangMap.put(new MaterialData(m("IRON_DOOR_BLOCK")), "tile.doorIron.name"); materialLangMap.put(new MaterialData(m("WOODEN_DOOR")), "tile.doorWood.name"); materialLangMap.put(new MaterialData(m("DOUBLE_PLANT"), 3), "tile.doublePlant.fern.name"); materialLangMap.put(new MaterialData(m("DOUBLE_PLANT"), 2), "tile.doublePlant.grass.name"); materialLangMap.put(new MaterialData(m("DOUBLE_PLANT"), 5), "tile.doublePlant.paeonia.name"); materialLangMap.put(new MaterialData(m("DOUBLE_PLANT"), 4), "tile.doublePlant.rose.name"); materialLangMap.put(new MaterialData(m("DOUBLE_PLANT")), "tile.doublePlant.sunflower.name"); materialLangMap.put(new MaterialData(m("DOUBLE_PLANT"), 1), "tile.doublePlant.syringa.name"); materialLangMap.put(new MaterialData(m("DRAGON_EGG")), "tile.dragonEgg.name"); materialLangMap.put(new MaterialData(m("DROPPER")), "tile.dropper.name"); materialLangMap.put(new MaterialData(m("ENCHANTMENT_TABLE")), "tile.enchantmentTable.name"); materialLangMap.put(new MaterialData(m("ENDER_PORTAL_FRAME")), "tile.endPortalFrame.name"); materialLangMap.put(new MaterialData(m("ENDER_CHEST")), "tile.enderChest.name"); materialLangMap.put(new MaterialData(m("SOIL")), "tile.farmland.name"); materialLangMap.put(new MaterialData(m("FENCE")), "tile.fence.name"); materialLangMap.put(new MaterialData(m("FENCE_GATE")), "tile.fenceGate.name"); materialLangMap.put(new MaterialData(m("IRON_FENCE")), "tile.fenceIron.name"); materialLangMap.put(new MaterialData(m("FIRE")), "tile.fire.name"); materialLangMap.put(new MaterialData(m("YELLOW_FLOWER")), "tile.flower1.dandelion.name"); materialLangMap.put(new MaterialData(m("RED_ROSE"), 2), "tile.flower2.allium.name"); materialLangMap.put(new MaterialData(m("RED_ROSE"), 1), "tile.flower2.blueOrchid.name"); //materialLangMap.put(new MaterialData(m("RED_ROSE")), "tile.flower2.houstonia.name"); materialLangMap.put(new MaterialData(m("RED_ROSE"), 8), "tile.flower2.oxeyeDaisy.name"); materialLangMap.put(new MaterialData(m("RED_ROSE")), "tile.flower2.poppy.name"); materialLangMap.put(new MaterialData(m("RED_ROSE"), 5), "tile.flower2.tulipOrange.name"); materialLangMap.put(new MaterialData(m("RED_ROSE"), 7), "tile.flower2.tulipPink.name"); materialLangMap.put(new MaterialData(m("RED_ROSE"), 4), "tile.flower2.tulipRed.name"); materialLangMap.put(new MaterialData(m("RED_ROSE"), 6), "tile.flower2.tulipWhite.name"); materialLangMap.put(new MaterialData(m("FURNACE")), "tile.furnace.name"); materialLangMap.put(new MaterialData(m("GLASS")), "tile.glass.name"); materialLangMap.put(new MaterialData(m("POWERED_RAIL")), "tile.goldenRail.name"); materialLangMap.put(new MaterialData(m("GRASS")), "tile.grass.name"); materialLangMap.put(new MaterialData(m("GRAVEL")), "tile.gravel.name"); materialLangMap.put(new MaterialData(m("HAY_BLOCK")), "tile.hayBlock.name"); materialLangMap.put(new MaterialData(m("NETHERRACK")), "tile.hellrock.name"); materialLangMap.put(new MaterialData(m("SOUL_SAND")), "tile.hellsand.name"); materialLangMap.put(new MaterialData(m("HOPPER")), "tile.hopper.name"); materialLangMap.put(new MaterialData(m("ICE")), "tile.ice.name"); materialLangMap.put(new MaterialData(m("PACKED_ICE")), "tile.icePacked.name"); materialLangMap.put(new MaterialData(m("JUKEBOX")), "tile.jukebox.name"); materialLangMap.put(new MaterialData(m("LADDER")), "tile.ladder.name"); materialLangMap.put(new MaterialData(m("LAVA")), "tile.lava.name"); materialLangMap.put(new MaterialData(m("LEAVES_2")), "tile.leaves.acacia.name"); materialLangMap.put(new MaterialData(m("LEAVES_2"), 1), "tile.leaves.big_oak.name"); materialLangMap.put(new MaterialData(m("LEAVES"), 2), "tile.leaves.birch.name"); materialLangMap.put(new MaterialData(m("LEAVES"), 3), "tile.leaves.jungle.name"); materialLangMap.put(new MaterialData(m("LEAVES")), "tile.leaves.oak.name"); materialLangMap.put(new MaterialData(m("LEAVES"), 1), "tile.leaves.spruce.name"); materialLangMap.put(new MaterialData(m("LEVER")), "tile.lever.name"); materialLangMap.put(new MaterialData(m("GLOWSTONE")), "tile.lightgem.name"); materialLangMap.put(new MaterialData(m("JACK_O_LANTERN")), "tile.litpumpkin.name"); materialLangMap.put(new MaterialData(m("LOG_2")), "tile.log.acacia.name"); materialLangMap.put(new MaterialData(m("LOG_2"), 1), "tile.log.big_oak.name"); materialLangMap.put(new MaterialData(m("LOG"), 2), "tile.log.birch.name"); materialLangMap.put(new MaterialData(m("LOG"), 3), "tile.log.jungle.name"); materialLangMap.put(new MaterialData(m("LOG")), "tile.log.name"); materialLangMap.put(new MaterialData(m("LOG")), "tile.log.oak.name"); materialLangMap.put(new MaterialData(m("LOG"), 1), "tile.log.spruce.name"); materialLangMap.put(new MaterialData(m("MELON_BLOCK")), "tile.melon.name"); materialLangMap.put(new MaterialData(m("MOB_SPAWNER")), "tile.mobSpawner.name"); materialLangMap.put(new MaterialData(m("MONSTER_EGGS"), 2), "tile.monsterStoneEgg.brick.name"); materialLangMap.put(new MaterialData(m("MONSTER_EGGS"), 5), "tile.monsterStoneEgg.chiseledbrick.name"); materialLangMap.put(new MaterialData(m("MONSTER_EGGS"), 1), "tile.monsterStoneEgg.cobble.name"); materialLangMap.put(new MaterialData(m("MONSTER_EGGS"), 4), "tile.monsterStoneEgg.crackedbrick.name"); materialLangMap.put(new MaterialData(m("MONSTER_EGGS"), 3), "tile.monsterStoneEgg.mossybrick.name"); materialLangMap.put(new MaterialData(m("MONSTER_EGGS")), "tile.monsterStoneEgg.stone.name"); materialLangMap.put(new MaterialData(m("NOTE_BLOCK")), "tile.musicBlock.name"); materialLangMap.put(new MaterialData(m("MYCEL")), "tile.mycel.name"); materialLangMap.put(new MaterialData(m("NETHER_BRICK")), "tile.netherBrick.name"); materialLangMap.put(new MaterialData(m("NETHER_FENCE")), "tile.netherFence.name"); materialLangMap.put(new MaterialData(m("NETHER_STALK")), "tile.netherStalk.name"); materialLangMap.put(new MaterialData(m("QUARTZ_ORE")), "tile.netherquartz.name"); materialLangMap.put(new MaterialData(m("REDSTONE_TORCH_ON")), "tile.notGate.name"); materialLangMap.put(new MaterialData(m("OBSIDIAN")), "tile.obsidian.name"); materialLangMap.put(new MaterialData(m("COAL_ORE")), "tile.oreCoal.name"); materialLangMap.put(new MaterialData(m("DIAMOND_ORE")), "tile.oreDiamond.name"); materialLangMap.put(new MaterialData(m("EMERALD_ORE")), "tile.oreEmerald.name"); materialLangMap.put(new MaterialData(m("GOLD_ORE")), "tile.oreGold.name"); materialLangMap.put(new MaterialData(m("IRON_ORE")), "tile.oreIron.name"); materialLangMap.put(new MaterialData(m("LAPIS_ORE")), "tile.oreLapis.name"); materialLangMap.put(new MaterialData(m("REDSTONE_ORE")), "tile.oreRedstone.name"); materialLangMap.put(new MaterialData(m("PISTON_BASE")), "tile.pistonBase.name"); materialLangMap.put(new MaterialData(m("PISTON_STICKY_BASE")), "tile.pistonStickyBase.name"); materialLangMap.put(new MaterialData(m("PORTAL")), "tile.portal.name"); materialLangMap.put(new MaterialData(m("POTATO")), "tile.potatoes.name"); materialLangMap.put(new MaterialData(m("STONE_PLATE")), "tile.pressurePlate.name"); materialLangMap.put(new MaterialData(m("PUMPKIN")), "tile.pumpkin.name"); materialLangMap.put(new MaterialData(m("QUARTZ_BLOCK"), 1), "tile.quartzBlock.chiseled.name"); materialLangMap.put(new MaterialData(m("QUARTZ_BLOCK")), "tile.quartzBlock.default.name"); materialLangMap.put(new MaterialData(m("QUARTZ_BLOCK"), 2), "tile.quartzBlock.lines.name"); materialLangMap.put(new MaterialData(m("RAILS")), "tile.rail.name"); materialLangMap.put(new MaterialData(m("REDSTONE_WIRE")), "tile.redstoneDust.name"); materialLangMap.put(new MaterialData(m("REDSTONE_LAMP_OFF")), "tile.redstoneLight.name"); materialLangMap.put(new MaterialData(m("REDSTONE_LAMP_ON")), "tile.redstoneLight.name"); materialLangMap.put(new MaterialData(m("SUGAR_CANE_BLOCK")), "tile.reeds.name"); materialLangMap.put(new MaterialData(m("SAND")), "tile.sand.default.name"); materialLangMap.put(new MaterialData(m("SAND"), 1), "tile.sand.red.name"); materialLangMap.put(new MaterialData(m("SANDSTONE"), 1), "tile.sandStone.chiseled.name"); materialLangMap.put(new MaterialData(m("SANDSTONE")), "tile.sandStone.default.name"); materialLangMap.put(new MaterialData(m("SANDSTONE"), 2), "tile.sandStone.smooth.name"); materialLangMap.put(new MaterialData(m("SAPLING"), 4), "tile.sapling.acacia.name"); materialLangMap.put(new MaterialData(m("SAPLING"), 2), "tile.sapling.birch.name"); materialLangMap.put(new MaterialData(m("SAPLING"), 3), "tile.sapling.jungle.name"); materialLangMap.put(new MaterialData(m("SAPLING")), "tile.sapling.oak.name"); materialLangMap.put(new MaterialData(m("SAPLING"), 5), "tile.sapling.roofed_oak.name"); materialLangMap.put(new MaterialData(m("SAPLING"), 1), "tile.sapling.spruce.name"); materialLangMap.put(new MaterialData(m("SNOW")), "tile.snow.name"); materialLangMap.put(new MaterialData(m("SPONGE")), "tile.sponge.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS"), 15), "tile.stainedGlass.black.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS"), 11), "tile.stainedGlass.blue.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS"), 12), "tile.stainedGlass.brown.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS"), 9), "tile.stainedGlass.cyan.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS"), 7), "tile.stainedGlass.gray.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS"), 13), "tile.stainedGlass.green.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS"), 3), "tile.stainedGlass.lightBlue.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS"), 5), "tile.stainedGlass.lime.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS"), 2), "tile.stainedGlass.magenta.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS"), 1), "tile.stainedGlass.orange.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS"), 6), "tile.stainedGlass.pink.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS"), 10), "tile.stainedGlass.purple.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS"), 14), "tile.stainedGlass.red.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS"), 8), "tile.stainedGlass.silver.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS")), "tile.stainedGlass.white.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS"), 4), "tile.stainedGlass.yellow.name"); materialLangMap.put(new MaterialData(m("BRICK_STAIRS")), "tile.stairsBrick.name"); materialLangMap.put(new MaterialData(m("NETHER_BRICK_STAIRS")), "tile.stairsNetherBrick.name"); materialLangMap.put(new MaterialData(m("QUARTZ_STAIRS")), "tile.stairsQuartz.name"); materialLangMap.put(new MaterialData(m("SANDSTONE_STAIRS")), "tile.stairsSandStone.name"); materialLangMap.put(new MaterialData(m("COBBLESTONE_STAIRS")), "tile.stairsStone.name"); materialLangMap.put(new MaterialData(m("SMOOTH_STAIRS")), "tile.stairsStoneBrickSmooth.name"); materialLangMap.put(new MaterialData(m("WOOD_STAIRS")), "tile.stairsWood.name"); materialLangMap.put(new MaterialData(m("ACACIA_STAIRS")), "tile.stairsWoodAcacia.name"); materialLangMap.put(new MaterialData(m("BIRCH_WOOD_STAIRS")), "tile.stairsWoodBirch.name"); materialLangMap.put(new MaterialData(m("DARK_OAK_STAIRS")), "tile.stairsWoodDarkOak.name"); materialLangMap.put(new MaterialData(m("JUNGLE_WOOD_STAIRS")), "tile.stairsWoodJungle.name"); materialLangMap.put(new MaterialData(m("SPRUCE_WOOD_STAIRS")), "tile.stairsWoodSpruce.name"); materialLangMap.put(new MaterialData(m("STONE")), "tile.stone.name"); materialLangMap.put(new MaterialData(m("MOSSY_COBBLESTONE")), "tile.stoneMoss.name"); materialLangMap.put(new MaterialData(m("STEP"), 4), "tile.stoneSlab.brick.name"); materialLangMap.put(new MaterialData(m("STEP"), 3), "tile.stoneSlab.cobble.name"); materialLangMap.put(new MaterialData(m("STEP"), 6), "tile.stoneSlab.netherBrick.name"); materialLangMap.put(new MaterialData(m("STEP"), 7), "tile.stoneSlab.quartz.name"); materialLangMap.put(new MaterialData(m("STEP"), 1), "tile.stoneSlab.sand.name"); materialLangMap.put(new MaterialData(m("STEP"), 5), "tile.stoneSlab.smoothStoneBrick.name"); materialLangMap.put(new MaterialData(m("STEP")), "tile.stoneSlab.stone.name"); materialLangMap.put(new MaterialData(m("STEP"), 2), "tile.stoneSlab.wood.name"); materialLangMap.put(new MaterialData(m("SMOOTH_BRICK"), 3), "tile.stonebricksmooth.chiseled.name"); materialLangMap.put(new MaterialData(m("SMOOTH_BRICK"), 2), "tile.stonebricksmooth.cracked.name"); materialLangMap.put(new MaterialData(m("SMOOTH_BRICK")), "tile.stonebricksmooth.default.name"); materialLangMap.put(new MaterialData(m("SMOOTH_BRICK"), 1), "tile.stonebricksmooth.mossy.name"); materialLangMap.put(new MaterialData(m("LONG_GRASS"), 2), "tile.tallgrass.fern.name"); materialLangMap.put(new MaterialData(m("LONG_GRASS"), 1), "tile.tallgrass.grass.name"); materialLangMap.put(new MaterialData(m("LONG_GRASS")), "tile.tallgrass.shrub.name"); materialLangMap.put(new MaterialData(m("THIN_GLASS")), "tile.thinGlass.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS_PANE"), 15), "tile.thinStainedGlass.black.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS_PANE"), 11), "tile.thinStainedGlass.blue.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS_PANE"), 12), "tile.thinStainedGlass.brown.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS_PANE"), 9), "tile.thinStainedGlass.cyan.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS_PANE"), 7), "tile.thinStainedGlass.gray.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS_PANE"), 13), "tile.thinStainedGlass.green.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS_PANE"), 3), "tile.thinStainedGlass.lightBlue.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS_PANE"), 5), "tile.thinStainedGlass.lime.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS_PANE"), 2), "tile.thinStainedGlass.magenta.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS_PANE"), 1), "tile.thinStainedGlass.orange.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS_PANE"), 6), "tile.thinStainedGlass.pink.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS_PANE"), 10), "tile.thinStainedGlass.purple.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS_PANE"), 14), "tile.thinStainedGlass.red.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS_PANE"), 8), "tile.thinStainedGlass.silver.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS_PANE")), "tile.thinStainedGlass.white.name"); materialLangMap.put(new MaterialData(m("STAINED_GLASS_PANE"), 4), "tile.thinStainedGlass.yellow.name"); materialLangMap.put(new MaterialData(m("TNT")), "tile.tnt.name"); materialLangMap.put(new MaterialData(m("TORCH")), "tile.torch.name"); materialLangMap.put(new MaterialData(m("TRAP_DOOR")), "tile.trapdoor.name"); materialLangMap.put(new MaterialData(m("TRIPWIRE")), "tile.tripWire.name"); materialLangMap.put(new MaterialData(m("TRIPWIRE_HOOK")), "tile.tripWireSource.name"); materialLangMap.put(new MaterialData(m("VINE")), "tile.vine.name"); materialLangMap.put(new MaterialData(m("WATER")), "tile.water.name"); materialLangMap.put(new MaterialData(m("WATER_LILY")), "tile.waterlily.name"); materialLangMap.put(new MaterialData(m("WEB")), "tile.web.name"); materialLangMap.put(new MaterialData(m("GOLD_PLATE")), "tile.weightedPlate_heavy.name"); materialLangMap.put(new MaterialData(m("IRON_PLATE")), "tile.weightedPlate_light.name"); materialLangMap.put(new MaterialData(m("ENDER_STONE")), "tile.whiteStone.name"); materialLangMap.put(new MaterialData(m("WOOD"), 4), "tile.wood.acacia.name"); materialLangMap.put(new MaterialData(m("WOOD"), 5), "tile.wood.big_oak.name"); materialLangMap.put(new MaterialData(m("WOOD"), 2), "tile.wood.birch.name"); materialLangMap.put(new MaterialData(m("WOOD"), 3), "tile.wood.jungle.name"); materialLangMap.put(new MaterialData(m("WOOD")), "tile.wood.oak.name"); materialLangMap.put(new MaterialData(m("WOOD"), 1), "tile.wood.spruce.name"); materialLangMap.put(new MaterialData(m("WOOD_STEP"), 4), "tile.woodSlab.acacia.name"); materialLangMap.put(new MaterialData(m("WOOD_STEP"), 5), "tile.woodSlab.big_oak.name"); materialLangMap.put(new MaterialData(m("WOOD_STEP"), 2), "tile.woodSlab.birch.name"); materialLangMap.put(new MaterialData(m("WOOD_STEP"), 3), "tile.woodSlab.jungle.name"); materialLangMap.put(new MaterialData(m("WOOD_STEP")), "tile.woodSlab.oak.name"); materialLangMap.put(new MaterialData(m("WOOD_STEP"), 1), "tile.woodSlab.spruce.name"); materialLangMap.put(new MaterialData(m("CARPET"), 15), "tile.woolCarpet.black.name"); materialLangMap.put(new MaterialData(m("CARPET"), 11), "tile.woolCarpet.blue.name"); materialLangMap.put(new MaterialData(m("CARPET"), 12), "tile.woolCarpet.brown.name"); materialLangMap.put(new MaterialData(m("CARPET"), 9), "tile.woolCarpet.cyan.name"); materialLangMap.put(new MaterialData(m("CARPET"), 7), "tile.woolCarpet.gray.name"); materialLangMap.put(new MaterialData(m("CARPET"), 13), "tile.woolCarpet.green.name"); materialLangMap.put(new MaterialData(m("CARPET"), 3), "tile.woolCarpet.lightBlue.name"); materialLangMap.put(new MaterialData(m("CARPET"), 5), "tile.woolCarpet.lime.name"); materialLangMap.put(new MaterialData(m("CARPET"), 2), "tile.woolCarpet.magenta.name"); materialLangMap.put(new MaterialData(m("CARPET"), 1), "tile.woolCarpet.orange.name"); materialLangMap.put(new MaterialData(m("CARPET"), 6), "tile.woolCarpet.pink.name"); materialLangMap.put(new MaterialData(m("CARPET"), 10), "tile.woolCarpet.purple.name"); materialLangMap.put(new MaterialData(m("CARPET"), 14), "tile.woolCarpet.red.name"); materialLangMap.put(new MaterialData(m("CARPET"), 8), "tile.woolCarpet.silver.name"); materialLangMap.put(new MaterialData(m("CARPET")), "tile.woolCarpet.white.name"); materialLangMap.put(new MaterialData(m("CARPET"), 4), "tile.woolCarpet.yellow.name"); materialLangMap.put(new MaterialData(m("WORKBENCH")), "tile.workbench.name"); materialLangMap.put(new MaterialData(m("COBBLESTONE")), "tile.stonebrick.name"); }
diff --git a/svnkit/src/main/java/org/tmatesoft/svn/core/internal/wc17/db/SvnWcDbCopy.java b/svnkit/src/main/java/org/tmatesoft/svn/core/internal/wc17/db/SvnWcDbCopy.java index d7256cd43..9668a020c 100644 --- a/svnkit/src/main/java/org/tmatesoft/svn/core/internal/wc17/db/SvnWcDbCopy.java +++ b/svnkit/src/main/java/org/tmatesoft/svn/core/internal/wc17/db/SvnWcDbCopy.java @@ -1,703 +1,703 @@ package org.tmatesoft.svn.core.internal.wc17.db; import static org.tmatesoft.svn.core.internal.wc17.db.SvnWcDbStatementUtil.bindf; import static org.tmatesoft.svn.core.internal.wc17.db.SvnWcDbStatementUtil.getColumnBlob; import static org.tmatesoft.svn.core.internal.wc17.db.SvnWcDbStatementUtil.getColumnInt64; import static org.tmatesoft.svn.core.internal.wc17.db.SvnWcDbStatementUtil.getColumnPath; import static org.tmatesoft.svn.core.internal.wc17.db.SvnWcDbStatementUtil.getColumnPresence; import static org.tmatesoft.svn.core.internal.wc17.db.SvnWcDbStatementUtil.getColumnText; import static org.tmatesoft.svn.core.internal.wc17.db.SvnWcDbStatementUtil.reset; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.tmatesoft.sqljet.core.SqlJetException; import org.tmatesoft.sqljet.core.schema.SqlJetConflictAction; import org.tmatesoft.sqljet.core.table.ISqlJetCursor; import org.tmatesoft.svn.core.SVNDepth; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNProperties; import org.tmatesoft.svn.core.SVNURL; import org.tmatesoft.svn.core.internal.db.SVNSqlJetDb; import org.tmatesoft.svn.core.internal.db.SVNSqlJetInsertStatement; import org.tmatesoft.svn.core.internal.db.SVNSqlJetSelectStatement; import org.tmatesoft.svn.core.internal.db.SVNSqlJetStatement; import org.tmatesoft.svn.core.internal.util.SVNDate; import org.tmatesoft.svn.core.internal.util.SVNSkel; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.core.internal.wc.SVNFileUtil; import org.tmatesoft.svn.core.internal.wc17.SVNWCUtils; import org.tmatesoft.svn.core.internal.wc17.db.ISVNWCDb.SVNWCDbKind; import org.tmatesoft.svn.core.internal.wc17.db.ISVNWCDb.SVNWCDbStatus; import org.tmatesoft.svn.core.internal.wc17.db.SVNWCDb.InsertWorking; import org.tmatesoft.svn.core.internal.wc17.db.SVNWCDb.ReposInfo; import org.tmatesoft.svn.core.internal.wc17.db.StructureFields.AdditionInfo; import org.tmatesoft.svn.core.internal.wc17.db.StructureFields.DeletionInfo; import org.tmatesoft.svn.core.internal.wc17.db.StructureFields.NodeInfo; import org.tmatesoft.svn.core.internal.wc17.db.statement.SVNWCDbSchema; import org.tmatesoft.svn.core.internal.wc17.db.statement.SVNWCDbSchema.ACTUAL_NODE__Fields; import org.tmatesoft.svn.core.internal.wc17.db.statement.SVNWCDbSchema.NODES__Fields; import org.tmatesoft.svn.core.internal.wc17.db.statement.SVNWCDbStatements; import org.tmatesoft.svn.core.wc2.SvnChecksum; import org.tmatesoft.svn.util.SVNLogType; public class SvnWcDbCopy extends SvnWcDbShared { private enum CopyInfo { copyFromId, copyFromRelpath, copyFromRev, status, kind, opRoot, haveWork } public static void copyFile(SVNWCDbDir pdh, File localRelpath, SVNProperties props, long changedRev, SVNDate changedDate, String changedAuthor, File originalReposRelPath, SVNURL originalRootUrl, String originalUuid, long originalRevision, SvnChecksum checksum, SVNSkel conflict, SVNSkel workItems) throws SVNException { InsertWorking iw = pdh.getWCRoot().getDb().new InsertWorking(); iw.status = SVNWCDbStatus.Normal; iw.kind = SVNWCDbKind.File; iw.props = props; iw.changedAuthor = changedAuthor; iw.changedDate = changedDate; iw.changedRev = changedRev; if (originalRootUrl != null) { long reposId = pdh.getWCRoot().getDb().createReposId(pdh.getWCRoot().getSDb(), originalRootUrl, originalUuid); iw.originalReposId = reposId; iw.originalReposRelPath = originalReposRelPath; iw.originalRevision = originalRevision; } long[] depths = getOpDepthForCopy(pdh.getWCRoot(), localRelpath, iw.originalReposId, originalReposRelPath, originalRevision); iw.opDepth = depths[0]; iw.notPresentOpDepth = depths[1]; iw.checksum = checksum; iw.workItems = workItems; iw.wcId = pdh.getWCRoot().getWcId(); iw.localRelpath = localRelpath; pdh.getWCRoot().getSDb().runTransaction(iw); pdh.flushEntries(pdh.getWCRoot().getAbsPath()); } private static void copyShadowedLayer(SVNWCDbDir srcPdh, File srcRelpath, long srcOpDepth, SVNWCDbDir dstPdh, File dstRelpath, long dstOpDepth, long delOpDepth, long reposId, File reposRelPath, long revision) throws SVNException { Structure<NodeInfo> depthInfo = null; try { depthInfo = SvnWcDbReader.getDepthInfo(srcPdh.getWCRoot(), srcRelpath, srcOpDepth, NodeInfo.status, NodeInfo.kind, NodeInfo.revision, NodeInfo.reposRelPath, NodeInfo.reposId); } catch (SVNException e) { if (e.getErrorMessage().getErrorCode() != SVNErrorCode.WC_PATH_NOT_FOUND) { throw e; } return; } SVNWCDbStatus status = depthInfo.get(NodeInfo.status); if (srcOpDepth == 0) { long nodeRevision = depthInfo.lng(NodeInfo.revision); long nodeReposId = depthInfo.lng(NodeInfo.reposId); File nodeReposRelPath = depthInfo.get(NodeInfo.reposRelPath); if (status == SVNWCDbStatus.NotPresent || status == SVNWCDbStatus.Excluded || status == SVNWCDbStatus.ServerExcluded || nodeRevision != revision || nodeReposId != reposId || !nodeReposRelPath.equals(reposRelPath)) { ReposInfo reposInfo = srcPdh.getWCRoot().getDb().fetchReposInfo(srcPdh.getWCRoot().getSDb(), nodeReposId); nodeReposId = dstPdh.getWCRoot().getDb().createReposId(dstPdh.getWCRoot().getSDb(), SVNURL.parseURIEncoded(reposInfo.reposRootUrl), reposInfo.reposUuid); InsertWorking iw = dstPdh.getWCRoot().getDb().new InsertWorking(); iw.opDepth = dstOpDepth; if (status != SVNWCDbStatus.Excluded) { iw.status = SVNWCDbStatus.NotPresent; } else { iw.status = SVNWCDbStatus.Excluded; } iw.kind = depthInfo.get(NodeInfo.kind); iw.originalReposId = nodeReposId; iw.originalRevision = nodeRevision; iw.originalReposRelPath = nodeReposRelPath; iw.changedRev = -1; iw.depth = SVNDepth.INFINITY; iw.wcId = dstPdh.getWCRoot().getWcId(); iw.localRelpath = dstRelpath; dstPdh.getWCRoot().getSDb().runTransaction(iw); return; } } SVNWCDbStatus dstPresence = null; switch (status) { case Normal: case Added: case MovedHere: case Copied: dstPresence = SVNWCDbStatus.Normal; break; case Deleted: case NotPresent: dstPresence = SVNWCDbStatus.NotPresent; break; case Excluded: dstPresence = SVNWCDbStatus.Excluded; break; case ServerExcluded: SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_PATH_UNEXPECTED_STATUS, "Cannot copy ''{0}'' excluded by server", srcPdh.getWCRoot().getAbsPath(srcRelpath)); SVNErrorManager.error(err, SVNLogType.WC); break; default: SVNErrorMessage err2 = SVNErrorMessage.create(SVNErrorCode.WC_PATH_UNEXPECTED_STATUS, "Cannot handle status of ''{0}''", srcPdh.getWCRoot().getAbsPath(srcRelpath)); SVNErrorManager.error(err2, SVNLogType.WC); } if (dstPresence == SVNWCDbStatus.Normal && srcPdh.getWCRoot().getSDb() == dstPdh.getWCRoot().getSDb()) { SVNSqlJetStatement stmt; if (srcOpDepth > 0) { stmt = new InsertWorkingNodeCopy(srcPdh.getWCRoot().getSDb(), srcOpDepth); } else { stmt = new InsertWorkingNodeCopy(srcPdh.getWCRoot().getSDb(), 0); } stmt.bindf("issist", srcPdh.getWCRoot().getWcId(), srcRelpath, dstRelpath, dstOpDepth, SVNFileUtil.getFileDir(dstRelpath), - dstPresence); + SvnWcDbStatementUtil.getPresenceText(dstPresence)); stmt.done(); InsertWorking iw = dstPdh.getWCRoot().getDb().new InsertWorking(); iw.opDepth = delOpDepth; - iw.status = SVNWCDbStatus.Deleted; + iw.status = SVNWCDbStatus.BaseDeleted; iw.kind = depthInfo.get(NodeInfo.kind); iw.changedRev = -1; iw.depth = SVNDepth.INFINITY; iw.wcId = dstPdh.getWCRoot().getWcId(); iw.localRelpath = dstRelpath; dstPdh.getWCRoot().getSDb().runTransaction(iw); } else { if (dstPresence == SVNWCDbStatus.Normal) { dstPresence = SVNWCDbStatus.NotPresent; } InsertWorking iw = dstPdh.getWCRoot().getDb().new InsertWorking(); iw.opDepth = dstOpDepth; iw.status = dstPresence; iw.kind = depthInfo.get(NodeInfo.kind); iw.changedRev = -1; iw.depth = SVNDepth.INFINITY; iw.wcId = dstPdh.getWCRoot().getWcId(); iw.localRelpath = dstRelpath; dstPdh.getWCRoot().getSDb().runTransaction(iw); } List<String> children = srcPdh.getWCRoot().getDb().gatherRepoChildren(srcPdh, srcRelpath, srcOpDepth); for (String name : children) { File srcChildRelpath = SVNFileUtil.createFilePath(srcRelpath, name); File dstChildRelpath = SVNFileUtil.createFilePath(dstRelpath, name); File childReposRelPath = null; if (reposRelPath != null) { childReposRelPath = SVNFileUtil.createFilePath(reposRelPath, name); } copyShadowedLayer(srcPdh, srcChildRelpath, srcOpDepth, dstPdh, dstChildRelpath, dstOpDepth, delOpDepth, reposId, childReposRelPath, revision); } } public static void copyShadowedLayer(SVNWCDbDir srcPdh, File localSrcRelpath, SVNWCDbDir dstPdh, File localDstRelpath) throws SVNException { boolean dstLocked = false; begingWriteTransaction(srcPdh.getWCRoot()); try { if (srcPdh.getWCRoot().getSDb() != dstPdh.getWCRoot().getSDb()) { begingWriteTransaction(dstPdh.getWCRoot()); dstLocked = true; } File srcParentRelPath = SVNFileUtil.getFileDir(localSrcRelpath); File dstParentRelPath = SVNFileUtil.getFileDir(localDstRelpath); long srcOpDepth = getOpDepthOf(srcPdh.getWCRoot(), srcParentRelPath); long dstOpDepth = getOpDepthOf(dstPdh.getWCRoot(), dstParentRelPath); long delOpDepth = SVNWCUtils.relpathDepth(localDstRelpath); Structure<NodeInfo> depthInfo = SvnWcDbReader.getDepthInfo(srcPdh.getWCRoot(), srcParentRelPath, srcOpDepth, NodeInfo.revision, NodeInfo.reposRelPath, NodeInfo.reposId); File reposRelpath = depthInfo.get(NodeInfo.reposRelPath); if (reposRelpath == null) { return; } reposRelpath = SVNFileUtil.createFilePath(reposRelpath, SVNFileUtil.getFileName(localSrcRelpath)); copyShadowedLayer(srcPdh, localSrcRelpath, srcOpDepth, dstPdh, localDstRelpath, dstOpDepth, delOpDepth, depthInfo.lng(NodeInfo.reposId), reposRelpath, depthInfo.lng(NodeInfo.revision)); depthInfo.release(); } catch (SVNException e) { try { rollbackTransaction(srcPdh.getWCRoot()); } finally { if (dstLocked) { rollbackTransaction(dstPdh.getWCRoot()); } } } finally { try { commitTransaction(srcPdh.getWCRoot()); } finally { if (dstLocked) { commitTransaction(dstPdh.getWCRoot()); } } } } public static void copy(SVNWCDbDir srcPdh, File localSrcRelpath, SVNWCDbDir dstPdh, File localDstRelpath, SVNSkel workItems) throws SVNException { boolean dstLocked = false; begingWriteTransaction(srcPdh.getWCRoot()); try { if (srcPdh.getWCRoot().getSDb() != dstPdh.getWCRoot().getSDb()) { begingWriteTransaction(dstPdh.getWCRoot()); dstLocked = true; } doCopy(srcPdh, localSrcRelpath, dstPdh, localDstRelpath, workItems); } catch (SVNException e) { try { rollbackTransaction(srcPdh.getWCRoot()); } finally { if (dstLocked) { rollbackTransaction(dstPdh.getWCRoot()); } } } finally { try { commitTransaction(srcPdh.getWCRoot()); } finally { if (dstLocked) { commitTransaction(dstPdh.getWCRoot()); } } } } private static void doCopy(SVNWCDbDir srcPdh, File localSrcRelpath, SVNWCDbDir dstPdh, File localDstRelpath, SVNSkel workItems) throws SVNException { Structure<CopyInfo> copyInfo = getCopyInfo(srcPdh.getWCRoot(), localSrcRelpath); long[] dstOpDepths = getOpDepthForCopy(dstPdh.getWCRoot(), localDstRelpath, copyInfo.lng(CopyInfo.copyFromId), copyInfo.<File>get(CopyInfo.copyFromRelpath), copyInfo.lng(CopyInfo.copyFromRev)); SVNWCDbStatus status = copyInfo.get(CopyInfo.status); SVNWCDbStatus dstPresence = null; boolean opRoot = copyInfo.is(CopyInfo.opRoot); switch (status) { case Normal: case Added: case MovedHere: case Copied: dstPresence = SVNWCDbStatus.Normal; break; case Deleted: if (opRoot) { try { Structure<NodeInfo> dstInfo = SvnWcDbReader.readInfo(dstPdh.getWCRoot(), localDstRelpath, NodeInfo.status); SVNWCDbStatus dstStatus = dstInfo.get(NodeInfo.status); dstInfo.release(); if (dstStatus == SVNWCDbStatus.Deleted) { dstPdh.getWCRoot().getDb().addWorkQueue(dstPdh.getWCRoot().getAbsPath(), workItems); return; } } catch (SVNException e) { if (e.getErrorMessage().getErrorCode() != SVNErrorCode.WC_PATH_NOT_FOUND) { throw e; } } } case NotPresent: case Excluded: if (dstOpDepths[1] > 0) { dstOpDepths[0] = dstOpDepths[1]; dstOpDepths[1] = -1; } if (status == SVNWCDbStatus.Excluded) { dstPresence = SVNWCDbStatus.Excluded; } else { dstPresence = SVNWCDbStatus.NotPresent; } break; case ServerExcluded: SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_PATH_UNEXPECTED_STATUS, "Cannot copy ''{0}'' excluded by server", srcPdh.getWCRoot().getAbsPath(localSrcRelpath)); SVNErrorManager.error(err, SVNLogType.WC); default: SVNErrorMessage err1 = SVNErrorMessage.create(SVNErrorCode.WC_PATH_UNEXPECTED_STATUS, "Cannot handle status of ''{0}''", srcPdh.getWCRoot().getAbsPath(localSrcRelpath)); SVNErrorManager.error(err1, SVNLogType.WC); } SVNWCDbKind kind = copyInfo.get(CopyInfo.kind); List<String> children = null; if (kind == SVNWCDbKind.Dir) { long opDepth = getOpDepthOf(srcPdh.getWCRoot(), localSrcRelpath); children = srcPdh.getWCRoot().getDb().gatherRepoChildren(srcPdh, localSrcRelpath, opDepth); } if (srcPdh.getWCRoot() == dstPdh.getWCRoot()) { File dstParentRelpath = SVNFileUtil.getFileDir(localDstRelpath); SVNSqlJetStatement stmt = new InsertWorkingNodeCopy(srcPdh.getWCRoot().getSDb(), !copyInfo.is(CopyInfo.haveWork)); stmt.bindf("issist", srcPdh.getWCRoot().getWcId(), localSrcRelpath, localDstRelpath, dstOpDepths[0], dstParentRelpath, SvnWcDbStatementUtil.getPresenceText(dstPresence)); stmt.done(); copyActual(srcPdh, localSrcRelpath, dstPdh, localDstRelpath); if (dstOpDepths[1] > 0) { stmt = srcPdh.getWCRoot().getSDb().getStatement(SVNWCDbStatements.INSERT_NODE); stmt.bindf("isisisrtnt", srcPdh.getWCRoot().getWcId(), localDstRelpath, dstOpDepths[1], dstParentRelpath, copyInfo.lng(CopyInfo.copyFromId), copyInfo.get(CopyInfo.copyFromRelpath), copyInfo.lng(CopyInfo.copyFromRev), SvnWcDbStatementUtil.getPresenceText(SVNWCDbStatus.NotPresent), SvnWcDbStatementUtil.getKindText(kind)); stmt.done(); } if (kind == SVNWCDbKind.Dir && dstPresence == SVNWCDbStatus.Normal) { List<File> fileChildren = new LinkedList<File>(); for (String childName : children) { fileChildren.add(new File(childName)); } srcPdh.getWCRoot().getDb().insertIncompleteChildren(srcPdh.getWCRoot().getSDb(), srcPdh.getWCRoot().getWcId(), localDstRelpath, copyInfo.lng(CopyInfo.copyFromRev), fileChildren, dstOpDepths[0]); } } else { crossDbCopy(srcPdh, localSrcRelpath, dstPdh, localDstRelpath, dstPresence, dstOpDepths[0], dstOpDepths[1], kind, children, copyInfo.lng(CopyInfo.copyFromId), copyInfo.<File>get(CopyInfo.copyFromRelpath), copyInfo.lng(CopyInfo.copyFromRev)); } dstPdh.getWCRoot().getDb().addWorkQueue(dstPdh.getWCRoot().getAbsPath(), workItems); } private static void crossDbCopy(SVNWCDbDir srcPdh, File localSrcRelpath, SVNWCDbDir dstPdh, File localDstRelpath, SVNWCDbStatus dstPresence, long dstOpDepth, long dstNpOpDepth, SVNWCDbKind kind, List<String> children, long copyFromId, File copyFromRelpath, long copyFromRev) throws SVNException { Structure<NodeInfo> nodeInfo = SvnWcDbShared.readInfo(srcPdh.getWCRoot(), localSrcRelpath, NodeInfo.changedRev, NodeInfo.changedDate, NodeInfo.changedAuthor, NodeInfo.depth, NodeInfo.checksum); SVNProperties properties = SvnWcDbProperties.readPristineProperties(srcPdh.getWCRoot(), localSrcRelpath); InsertWorking iw = dstPdh.getWCRoot().getDb().new InsertWorking(); iw.status = dstPresence; iw.kind = kind; iw.props = properties; iw.changedRev = nodeInfo.lng(NodeInfo.changedRev); iw.changedDate = nodeInfo.get(NodeInfo.changedDate); iw.changedAuthor = nodeInfo.text(NodeInfo.changedAuthor); iw.opDepth = dstOpDepth; iw.checksum = nodeInfo.get(NodeInfo.checksum); List<File> childrenAsFiles = null; if (children != null) { childrenAsFiles = new ArrayList<File>(); for (String name : children) { childrenAsFiles.add(new File(name)); } } iw.children = childrenAsFiles; iw.depth = nodeInfo.get(NodeInfo.depth); iw.notPresentOpDepth = dstNpOpDepth; iw.originalReposId = copyFromId; iw.originalRevision = copyFromRev; iw.originalReposRelPath = copyFromRelpath; iw.wcId = dstPdh.getWCRoot().getWcId(); iw.localRelpath = localDstRelpath; dstPdh.getWCRoot().getSDb().runTransaction(iw); copyActual(srcPdh, localSrcRelpath, dstPdh, localDstRelpath); nodeInfo.release(); } private static void copyActual(SVNWCDbDir srcPdh, File localSrcRelpath, SVNWCDbDir dstPdh, File localDstRelpath) throws SVNException { SVNSqlJetStatement stmt = srcPdh.getWCRoot().getSDb().getStatement(SVNWCDbStatements.SELECT_ACTUAL_NODE); stmt.bindf("is", srcPdh.getWCRoot().getWcId(), localSrcRelpath); try { if (stmt.next()) { String changelist = getColumnText(stmt, ACTUAL_NODE__Fields.changelist); byte[] properties = getColumnBlob(stmt, ACTUAL_NODE__Fields.properties); if (changelist != null || properties != null) { reset(stmt); stmt = srcPdh.getWCRoot().getSDb().getStatement(SVNWCDbStatements.INSERT_ACTUAL_NODE); stmt.bindf("issbssssss", dstPdh.getWCRoot().getWcId(), localDstRelpath, SVNFileUtil.getFileDir(localDstRelpath), properties, null, null, null, null, changelist, null); stmt.done(); } } } finally { reset(stmt); } } private static Structure<CopyInfo> getCopyInfo(SVNWCDbRoot wcRoot, File localRelPath) throws SVNException { Structure<CopyInfo> result = Structure.obtain(CopyInfo.class); result.set(CopyInfo.haveWork, false); Structure<NodeInfo> nodeInfo = SvnWcDbReader.readInfo(wcRoot, localRelPath, NodeInfo.status, NodeInfo.kind, NodeInfo.revision, NodeInfo.reposRelPath, NodeInfo.reposId, NodeInfo.opRoot, NodeInfo.haveWork); nodeInfo.from(NodeInfo.kind, NodeInfo.status, NodeInfo.reposId, NodeInfo.haveWork, NodeInfo.opRoot) .into(result, CopyInfo.kind, CopyInfo.status, CopyInfo.copyFromId, CopyInfo.haveWork, CopyInfo.opRoot); SVNWCDbStatus status = nodeInfo.get(NodeInfo.status); File reposRelpath = nodeInfo.get(NodeInfo.reposRelPath); long revision = nodeInfo.lng(NodeInfo.revision); nodeInfo.release(); if (status == SVNWCDbStatus.Excluded) { File parentRelpath = SVNFileUtil.getFileDir(localRelPath); String name = SVNFileUtil.getFileName(localRelPath); Structure<CopyInfo> parentCopyInfo = getCopyInfo(wcRoot, parentRelpath); parentCopyInfo.from(CopyInfo.copyFromId, CopyInfo.copyFromRev) .into(result, CopyInfo.copyFromId, CopyInfo.copyFromRev); if (parentCopyInfo.get(CopyInfo.copyFromRelpath) != null) { result.set(CopyInfo.copyFromRelpath, SVNFileUtil.createFilePath(parentCopyInfo.<File>get(CopyInfo.copyFromRelpath), name)); } parentCopyInfo.release(); } else if (status == SVNWCDbStatus.Added) { Structure<AdditionInfo> additionInfo = scanAddition(wcRoot, localRelPath, AdditionInfo.opRootRelPath, AdditionInfo.originalReposRelPath, AdditionInfo.originalReposId, AdditionInfo.originalRevision); additionInfo.from(AdditionInfo.originalReposRelPath, AdditionInfo.originalReposId, AdditionInfo.originalRevision) .into(result, CopyInfo.copyFromRelpath, CopyInfo.copyFromId, CopyInfo.copyFromRev); if (additionInfo.get(AdditionInfo.originalReposRelPath) != null) { File opRootRelPath = additionInfo.get(AdditionInfo.opRootRelPath); File copyFromRelPath = additionInfo.get(AdditionInfo.originalReposRelPath); File relPath = SVNFileUtil.createFilePath(copyFromRelPath, SVNWCUtils.skipAncestor(opRootRelPath, localRelPath)); result.set(CopyInfo.copyFromRelpath, relPath); } additionInfo.release(); } else if (status == SVNWCDbStatus.Deleted) { Structure<DeletionInfo> deletionInfo = scanDeletion(wcRoot, localRelPath); if (deletionInfo.get(DeletionInfo.workDelRelPath) != null) { File parentDelRelpath = SVNFileUtil.getFileDir(deletionInfo.<File>get(DeletionInfo.workDelRelPath)); Structure<AdditionInfo> additionInfo = scanAddition(wcRoot, parentDelRelpath, AdditionInfo.opRootRelPath, AdditionInfo.originalReposRelPath, AdditionInfo.originalReposId, AdditionInfo.originalRevision); additionInfo.from(AdditionInfo.originalReposRelPath, AdditionInfo.originalReposId, AdditionInfo.originalRevision) .into(result, CopyInfo.copyFromRelpath, CopyInfo.copyFromId, CopyInfo.copyFromRev); File opRootRelPath = additionInfo.get(AdditionInfo.opRootRelPath); File copyFromRelPath = additionInfo.get(AdditionInfo.originalReposRelPath); File relPath = SVNFileUtil.createFilePath(copyFromRelPath, SVNWCUtils.skipAncestor(opRootRelPath, localRelPath)); result.set(CopyInfo.copyFromRelpath, relPath); additionInfo.release(); } else if (deletionInfo.get(DeletionInfo.baseDelRelPath) != null) { Structure<NodeInfo> baseInfo = getDepthInfo(wcRoot, localRelPath, 0, NodeInfo.revision, NodeInfo.reposRelPath, NodeInfo.reposId); baseInfo.from(NodeInfo.revision, NodeInfo.reposRelPath, NodeInfo.reposId). into(result, CopyInfo.copyFromRev, CopyInfo.copyFromRelpath, CopyInfo.copyFromId); baseInfo.release(); } deletionInfo.release(); } else { result.set(CopyInfo.copyFromRelpath, reposRelpath); result.set(CopyInfo.copyFromRev, revision); } return result; } private static long[] getOpDepthForCopy(SVNWCDbRoot wcRoot, File localRelpath, long copyFromReposId, File copyFromRelpath, long copyFromRevision) throws SVNException { long[] result = new long[] {SVNWCUtils.relpathDepth(localRelpath), -1}; if (copyFromRelpath == null) { return result; } long minOpDepth = 1; long incompleteOpDepth = -1; SVNSqlJetStatement stmt = wcRoot.getSDb().getStatement(SVNWCDbStatements.SELECT_WORKING_NODE); bindf(stmt, "is", wcRoot.getWcId(), localRelpath); if (stmt.next()) { SVNWCDbStatus status = getColumnPresence(stmt); minOpDepth = getColumnInt64(stmt, NODES__Fields.op_depth); if (status == SVNWCDbStatus.Incomplete) { incompleteOpDepth = minOpDepth; } } reset(stmt); File parentRelpath = SVNFileUtil.getFileDir(localRelpath); bindf(stmt, "is", wcRoot.getWcId(), parentRelpath); if (stmt.next()) { long parentOpDepth = getColumnInt64(stmt, NODES__Fields.op_depth); if (parentOpDepth < minOpDepth) { reset(stmt); return result; } if (incompleteOpDepth < 0 || incompleteOpDepth == parentOpDepth) { long parentCopyFromReposId = getColumnInt64(stmt, NODES__Fields.repos_id); File parentCopyFromRelpath = getColumnPath(stmt, NODES__Fields.repos_path); long parentCopyFromRevision = getColumnInt64(stmt, NODES__Fields.revision); if (parentCopyFromReposId == copyFromReposId) { if (copyFromRevision == parentCopyFromRevision && copyFromRelpath.equals(SVNFileUtil.createFilePath(parentCopyFromRelpath, localRelpath.getName()))) { result[0] = parentOpDepth; } else if (incompleteOpDepth > 0) { result[1] = incompleteOpDepth; } } } } reset(stmt); return result; } private static long getOpDepthOf(SVNWCDbRoot wcRoot, File localRelpath) throws SVNException { SVNSqlJetStatement stmt = wcRoot.getSDb().getStatement(SVNWCDbStatements.SELECT_NODE_INFO); bindf(stmt, "is", wcRoot.getWcId(), localRelpath); try { if (stmt.next()) { return getColumnInt64(stmt, NODES__Fields.op_depth); } } finally { reset(stmt); } return 0; } private static class InsertWorkingNodeCopy extends SVNSqlJetInsertStatement { private SelectNodeToCopy select; public InsertWorkingNodeCopy(SVNSqlJetDb sDb, boolean base) throws SVNException { this(sDb, base ? 0 : -1); } public InsertWorkingNodeCopy(SVNSqlJetDb sDb, long depth) throws SVNException { super(sDb, SVNWCDbSchema.NODES, SqlJetConflictAction.REPLACE); select = new SelectNodeToCopy(sDb, depth); } @Override protected Map<String, Object> getInsertValues() throws SVNException { // run select once and return values. select.bindf("is", getBind(1), getBind(2)); try { if (select.next()) { Map<String, Object> values = new HashMap<String, Object>(); values.put(NODES__Fields.wc_id.toString(), select.getColumn(NODES__Fields.wc_id)); values.put(NODES__Fields.local_relpath.toString(), getBind(3)); values.put(NODES__Fields.op_depth.toString(), getBind(4)); values.put(NODES__Fields.parent_relpath.toString(), getBind(5)); values.put(NODES__Fields.repos_id.toString(), select.getColumn(NODES__Fields.repos_id)); values.put(NODES__Fields.repos_path.toString(), select.getColumn(NODES__Fields.repos_path)); values.put(NODES__Fields.revision.toString(), select.getColumn(NODES__Fields.revision)); values.put(NODES__Fields.presence.toString(), getBind(6)); values.put(NODES__Fields.depth.toString(), select.getColumn(NODES__Fields.depth)); values.put(NODES__Fields.kind.toString(), select.getColumn(NODES__Fields.kind)); values.put(NODES__Fields.changed_revision.toString(), select.getColumn(NODES__Fields.changed_revision)); values.put(NODES__Fields.changed_date.toString(), select.getColumn(NODES__Fields.changed_date)); values.put(NODES__Fields.changed_author.toString(), select.getColumn(NODES__Fields.changed_author)); values.put(NODES__Fields.checksum.toString(), select.getColumn(NODES__Fields.checksum)); values.put(NODES__Fields.properties.toString(), select.getColumn(NODES__Fields.properties)); values.put(NODES__Fields.translated_size.toString(), select.getColumn(NODES__Fields.translated_size)); values.put(NODES__Fields.last_mod_time.toString(), select.getColumn(NODES__Fields.last_mod_time)); values.put(NODES__Fields.symlink_target.toString(), select.getColumn(NODES__Fields.symlink_target)); return values; } } finally { select.reset(); } return null; } } /** * SELECT wc_id, ?3 (local_relpath), ?4 (op_depth), ?5 (parent_relpath), * repos_id, repos_path, revision, ?6 (presence), depth, * kind, changed_revision, changed_date, changed_author, checksum, properties, * translated_size, last_mod_time, symlink_target * FROM nodes * * WHERE wc_id = ?1 AND local_relpath = ?2 AND op_depth > 0 * ORDER BY op_depth DESC * LIMIT 1 * * or for base: * * FROM nodes * WHERE wc_id = ?1 AND local_relpath = ?2 AND op_depth = 0 * @author alex * */ private static class SelectNodeToCopy extends SVNSqlJetSelectStatement { private long limit; private long depth; public SelectNodeToCopy(SVNSqlJetDb sDb, long depth) throws SVNException { super(sDb, SVNWCDbSchema.NODES); this.depth = depth; } @Override protected Object[] getWhere() throws SVNException { if (depth >= 0) { return new Object[] {getBind(1), getBind(2), depth}; } return super.getWhere(); } @Override protected boolean isFilterPassed() throws SVNException { limit++; return super.isFilterPassed() && limit == 1; } @Override protected ISqlJetCursor openCursor() throws SVNException { if (depth == 0) { return super.openCursor(); } try { return super.openCursor().reverse(); } catch (SqlJetException e) { SVNSqlJetDb.createSqlJetError(e); } return null; } } }
false
true
private static void copyShadowedLayer(SVNWCDbDir srcPdh, File srcRelpath, long srcOpDepth, SVNWCDbDir dstPdh, File dstRelpath, long dstOpDepth, long delOpDepth, long reposId, File reposRelPath, long revision) throws SVNException { Structure<NodeInfo> depthInfo = null; try { depthInfo = SvnWcDbReader.getDepthInfo(srcPdh.getWCRoot(), srcRelpath, srcOpDepth, NodeInfo.status, NodeInfo.kind, NodeInfo.revision, NodeInfo.reposRelPath, NodeInfo.reposId); } catch (SVNException e) { if (e.getErrorMessage().getErrorCode() != SVNErrorCode.WC_PATH_NOT_FOUND) { throw e; } return; } SVNWCDbStatus status = depthInfo.get(NodeInfo.status); if (srcOpDepth == 0) { long nodeRevision = depthInfo.lng(NodeInfo.revision); long nodeReposId = depthInfo.lng(NodeInfo.reposId); File nodeReposRelPath = depthInfo.get(NodeInfo.reposRelPath); if (status == SVNWCDbStatus.NotPresent || status == SVNWCDbStatus.Excluded || status == SVNWCDbStatus.ServerExcluded || nodeRevision != revision || nodeReposId != reposId || !nodeReposRelPath.equals(reposRelPath)) { ReposInfo reposInfo = srcPdh.getWCRoot().getDb().fetchReposInfo(srcPdh.getWCRoot().getSDb(), nodeReposId); nodeReposId = dstPdh.getWCRoot().getDb().createReposId(dstPdh.getWCRoot().getSDb(), SVNURL.parseURIEncoded(reposInfo.reposRootUrl), reposInfo.reposUuid); InsertWorking iw = dstPdh.getWCRoot().getDb().new InsertWorking(); iw.opDepth = dstOpDepth; if (status != SVNWCDbStatus.Excluded) { iw.status = SVNWCDbStatus.NotPresent; } else { iw.status = SVNWCDbStatus.Excluded; } iw.kind = depthInfo.get(NodeInfo.kind); iw.originalReposId = nodeReposId; iw.originalRevision = nodeRevision; iw.originalReposRelPath = nodeReposRelPath; iw.changedRev = -1; iw.depth = SVNDepth.INFINITY; iw.wcId = dstPdh.getWCRoot().getWcId(); iw.localRelpath = dstRelpath; dstPdh.getWCRoot().getSDb().runTransaction(iw); return; } } SVNWCDbStatus dstPresence = null; switch (status) { case Normal: case Added: case MovedHere: case Copied: dstPresence = SVNWCDbStatus.Normal; break; case Deleted: case NotPresent: dstPresence = SVNWCDbStatus.NotPresent; break; case Excluded: dstPresence = SVNWCDbStatus.Excluded; break; case ServerExcluded: SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_PATH_UNEXPECTED_STATUS, "Cannot copy ''{0}'' excluded by server", srcPdh.getWCRoot().getAbsPath(srcRelpath)); SVNErrorManager.error(err, SVNLogType.WC); break; default: SVNErrorMessage err2 = SVNErrorMessage.create(SVNErrorCode.WC_PATH_UNEXPECTED_STATUS, "Cannot handle status of ''{0}''", srcPdh.getWCRoot().getAbsPath(srcRelpath)); SVNErrorManager.error(err2, SVNLogType.WC); } if (dstPresence == SVNWCDbStatus.Normal && srcPdh.getWCRoot().getSDb() == dstPdh.getWCRoot().getSDb()) { SVNSqlJetStatement stmt; if (srcOpDepth > 0) { stmt = new InsertWorkingNodeCopy(srcPdh.getWCRoot().getSDb(), srcOpDepth); } else { stmt = new InsertWorkingNodeCopy(srcPdh.getWCRoot().getSDb(), 0); } stmt.bindf("issist", srcPdh.getWCRoot().getWcId(), srcRelpath, dstRelpath, dstOpDepth, SVNFileUtil.getFileDir(dstRelpath), dstPresence); stmt.done(); InsertWorking iw = dstPdh.getWCRoot().getDb().new InsertWorking(); iw.opDepth = delOpDepth; iw.status = SVNWCDbStatus.Deleted; iw.kind = depthInfo.get(NodeInfo.kind); iw.changedRev = -1; iw.depth = SVNDepth.INFINITY; iw.wcId = dstPdh.getWCRoot().getWcId(); iw.localRelpath = dstRelpath; dstPdh.getWCRoot().getSDb().runTransaction(iw); } else { if (dstPresence == SVNWCDbStatus.Normal) { dstPresence = SVNWCDbStatus.NotPresent; } InsertWorking iw = dstPdh.getWCRoot().getDb().new InsertWorking(); iw.opDepth = dstOpDepth; iw.status = dstPresence; iw.kind = depthInfo.get(NodeInfo.kind); iw.changedRev = -1; iw.depth = SVNDepth.INFINITY; iw.wcId = dstPdh.getWCRoot().getWcId(); iw.localRelpath = dstRelpath; dstPdh.getWCRoot().getSDb().runTransaction(iw); } List<String> children = srcPdh.getWCRoot().getDb().gatherRepoChildren(srcPdh, srcRelpath, srcOpDepth); for (String name : children) { File srcChildRelpath = SVNFileUtil.createFilePath(srcRelpath, name); File dstChildRelpath = SVNFileUtil.createFilePath(dstRelpath, name); File childReposRelPath = null; if (reposRelPath != null) { childReposRelPath = SVNFileUtil.createFilePath(reposRelPath, name); } copyShadowedLayer(srcPdh, srcChildRelpath, srcOpDepth, dstPdh, dstChildRelpath, dstOpDepth, delOpDepth, reposId, childReposRelPath, revision); } }
private static void copyShadowedLayer(SVNWCDbDir srcPdh, File srcRelpath, long srcOpDepth, SVNWCDbDir dstPdh, File dstRelpath, long dstOpDepth, long delOpDepth, long reposId, File reposRelPath, long revision) throws SVNException { Structure<NodeInfo> depthInfo = null; try { depthInfo = SvnWcDbReader.getDepthInfo(srcPdh.getWCRoot(), srcRelpath, srcOpDepth, NodeInfo.status, NodeInfo.kind, NodeInfo.revision, NodeInfo.reposRelPath, NodeInfo.reposId); } catch (SVNException e) { if (e.getErrorMessage().getErrorCode() != SVNErrorCode.WC_PATH_NOT_FOUND) { throw e; } return; } SVNWCDbStatus status = depthInfo.get(NodeInfo.status); if (srcOpDepth == 0) { long nodeRevision = depthInfo.lng(NodeInfo.revision); long nodeReposId = depthInfo.lng(NodeInfo.reposId); File nodeReposRelPath = depthInfo.get(NodeInfo.reposRelPath); if (status == SVNWCDbStatus.NotPresent || status == SVNWCDbStatus.Excluded || status == SVNWCDbStatus.ServerExcluded || nodeRevision != revision || nodeReposId != reposId || !nodeReposRelPath.equals(reposRelPath)) { ReposInfo reposInfo = srcPdh.getWCRoot().getDb().fetchReposInfo(srcPdh.getWCRoot().getSDb(), nodeReposId); nodeReposId = dstPdh.getWCRoot().getDb().createReposId(dstPdh.getWCRoot().getSDb(), SVNURL.parseURIEncoded(reposInfo.reposRootUrl), reposInfo.reposUuid); InsertWorking iw = dstPdh.getWCRoot().getDb().new InsertWorking(); iw.opDepth = dstOpDepth; if (status != SVNWCDbStatus.Excluded) { iw.status = SVNWCDbStatus.NotPresent; } else { iw.status = SVNWCDbStatus.Excluded; } iw.kind = depthInfo.get(NodeInfo.kind); iw.originalReposId = nodeReposId; iw.originalRevision = nodeRevision; iw.originalReposRelPath = nodeReposRelPath; iw.changedRev = -1; iw.depth = SVNDepth.INFINITY; iw.wcId = dstPdh.getWCRoot().getWcId(); iw.localRelpath = dstRelpath; dstPdh.getWCRoot().getSDb().runTransaction(iw); return; } } SVNWCDbStatus dstPresence = null; switch (status) { case Normal: case Added: case MovedHere: case Copied: dstPresence = SVNWCDbStatus.Normal; break; case Deleted: case NotPresent: dstPresence = SVNWCDbStatus.NotPresent; break; case Excluded: dstPresence = SVNWCDbStatus.Excluded; break; case ServerExcluded: SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_PATH_UNEXPECTED_STATUS, "Cannot copy ''{0}'' excluded by server", srcPdh.getWCRoot().getAbsPath(srcRelpath)); SVNErrorManager.error(err, SVNLogType.WC); break; default: SVNErrorMessage err2 = SVNErrorMessage.create(SVNErrorCode.WC_PATH_UNEXPECTED_STATUS, "Cannot handle status of ''{0}''", srcPdh.getWCRoot().getAbsPath(srcRelpath)); SVNErrorManager.error(err2, SVNLogType.WC); } if (dstPresence == SVNWCDbStatus.Normal && srcPdh.getWCRoot().getSDb() == dstPdh.getWCRoot().getSDb()) { SVNSqlJetStatement stmt; if (srcOpDepth > 0) { stmt = new InsertWorkingNodeCopy(srcPdh.getWCRoot().getSDb(), srcOpDepth); } else { stmt = new InsertWorkingNodeCopy(srcPdh.getWCRoot().getSDb(), 0); } stmt.bindf("issist", srcPdh.getWCRoot().getWcId(), srcRelpath, dstRelpath, dstOpDepth, SVNFileUtil.getFileDir(dstRelpath), SvnWcDbStatementUtil.getPresenceText(dstPresence)); stmt.done(); InsertWorking iw = dstPdh.getWCRoot().getDb().new InsertWorking(); iw.opDepth = delOpDepth; iw.status = SVNWCDbStatus.BaseDeleted; iw.kind = depthInfo.get(NodeInfo.kind); iw.changedRev = -1; iw.depth = SVNDepth.INFINITY; iw.wcId = dstPdh.getWCRoot().getWcId(); iw.localRelpath = dstRelpath; dstPdh.getWCRoot().getSDb().runTransaction(iw); } else { if (dstPresence == SVNWCDbStatus.Normal) { dstPresence = SVNWCDbStatus.NotPresent; } InsertWorking iw = dstPdh.getWCRoot().getDb().new InsertWorking(); iw.opDepth = dstOpDepth; iw.status = dstPresence; iw.kind = depthInfo.get(NodeInfo.kind); iw.changedRev = -1; iw.depth = SVNDepth.INFINITY; iw.wcId = dstPdh.getWCRoot().getWcId(); iw.localRelpath = dstRelpath; dstPdh.getWCRoot().getSDb().runTransaction(iw); } List<String> children = srcPdh.getWCRoot().getDb().gatherRepoChildren(srcPdh, srcRelpath, srcOpDepth); for (String name : children) { File srcChildRelpath = SVNFileUtil.createFilePath(srcRelpath, name); File dstChildRelpath = SVNFileUtil.createFilePath(dstRelpath, name); File childReposRelPath = null; if (reposRelPath != null) { childReposRelPath = SVNFileUtil.createFilePath(reposRelPath, name); } copyShadowedLayer(srcPdh, srcChildRelpath, srcOpDepth, dstPdh, dstChildRelpath, dstOpDepth, delOpDepth, reposId, childReposRelPath, revision); } }
diff --git a/infrastructure/tools/java/database/src/edu/uci/ics/sourcerer/db/tools/FileAccessor.java b/infrastructure/tools/java/database/src/edu/uci/ics/sourcerer/db/tools/FileAccessor.java index aa653485..d70ee24d 100755 --- a/infrastructure/tools/java/database/src/edu/uci/ics/sourcerer/db/tools/FileAccessor.java +++ b/infrastructure/tools/java/database/src/edu/uci/ics/sourcerer/db/tools/FileAccessor.java @@ -1,337 +1,337 @@ /* * Sourcerer: an infrastructure for large-scale source code analysis. * Copyright (C) by contributors. See CONTRIBUTORS.txt for full list. * * 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 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 edu.uci.ics.sourcerer.db.tools; import static edu.uci.ics.sourcerer.util.io.Logging.logger; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.logging.Level; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import edu.uci.ics.sourcerer.db.schema.DatabaseAccessor; import edu.uci.ics.sourcerer.db.util.DatabaseConnection; import edu.uci.ics.sourcerer.model.File; import edu.uci.ics.sourcerer.model.Project; import edu.uci.ics.sourcerer.model.db.FileDB; import edu.uci.ics.sourcerer.model.db.LocationDB; import edu.uci.ics.sourcerer.model.db.ProjectDB; import edu.uci.ics.sourcerer.repo.base.IJavaFile; import edu.uci.ics.sourcerer.repo.base.Repository; import edu.uci.ics.sourcerer.repo.extracted.ExtractedRepository; import edu.uci.ics.sourcerer.repo.general.AbstractRepository; import edu.uci.ics.sourcerer.repo.general.IndexedJar; import edu.uci.ics.sourcerer.repo.general.JarIndex; import edu.uci.ics.sourcerer.util.TimeoutManager; import edu.uci.ics.sourcerer.util.io.FileUtils; /** * @author Joel Ossher ([email protected]) */ public class FileAccessor { private static TimeoutManager<FileDatabaseAccessor> accessorManager = new TimeoutManager<FileDatabaseAccessor>(new TimeoutManager.Instantiator<FileDatabaseAccessor>() { @Override public FileDatabaseAccessor create() { DatabaseConnection conn = new DatabaseConnection(); conn.open(); return new FileDatabaseAccessor(conn); } }, 10 * 60 * 1000); private static Repository repo = Repository.getRepository(AbstractRepository.INPUT_REPO.getValue()); private static ExtractedRepository extracted = ExtractedRepository.getRepository(AbstractRepository.OUTPUT_REPO.getValue()); public static byte[] lookupByProjectID(String projectID) { FileDatabaseAccessor db = accessorManager.get(); ProjectDB project = db.getProjectByProjectID(projectID); if (project == null) { logger.log(Level.SEVERE, "Unable to find project: " + projectID); return null; } else { if (project.getType() == Project.SYSTEM) { logger.log(Level.SEVERE, project + " is a SYSTEM project"); return null; } else if (project.getType() == Project.JAR || project.getType() == Project.MAVEN) { JarIndex index = repo.getJarIndex(); IndexedJar indexed = index.getIndexedJar(project.getHash()); if (indexed == null) { logger.log(Level.SEVERE, "Unable to find " + project + " with hash " + project.getHash()); return null; } else { return FileUtils.getFileAsByteArray(indexed.getJarFile()); } } else if (project.getType() == Project.JAVA_LIBRARY) { return FileUtils.getFileAsByteArray(extracted.getJavaLibrary(project.getPath())); } else if (project.getType() == Project.CRAWLED) { logger.log(Level.SEVERE, "Crawled projects not supported: " + project); return null; } else { return null; } } } public static byte[] lookupByFileID(String fileID) { FileDatabaseAccessor db = accessorManager.get(); FileDB file = db.getFileByFileID(fileID); if (file == null) { logger.log(Level.SEVERE, "Unable to find file: " + fileID); return null; } else { ProjectDB project = db.getProjectByProjectID(file.getProjectID()); return getFile(project, file, null); } } public static byte[] lookupByEntityID(String entityID) { FileDatabaseAccessor db = accessorManager.get(); LocationDB loc = db.getLocationByEntityID(entityID); if (loc == null) { logger.log(Level.SEVERE, "Entity " + entityID + " has no associated file"); return null; } else { FileDB file = db.getFileByFileID(loc.getFileID()); if (file == null) { logger.log(Level.SEVERE, "Unable to find file: " + loc.getFileID()); return null; } else { ProjectDB project = db.getProjectByProjectID(file.getProjectID()); return getFile(project, file, loc); } } } public static byte[] lookupByRelationID(String relationID) { FileDatabaseAccessor db = accessorManager.get(); LocationDB loc = db.getLocationByRelationID(relationID); if (loc == null) { logger.log(Level.SEVERE, "Relation " + relationID + " has no associated file"); return null; } else { FileDB file = db.getFileByFileID(loc.getFileID()); if (file == null) { logger.log(Level.SEVERE, "Unable to find file: " + loc.getFileID()); return null; } else { ProjectDB project = db.getProjectByProjectID(file.getProjectID()); return getFile(project, file, loc); } } } public static byte[] lookupByCommentID(String commentID) { FileDatabaseAccessor db = accessorManager.get(); LocationDB loc = db.getLocationByCommentID(commentID); if (loc == null) { logger.log(Level.SEVERE, "Comment " + commentID + " has no associated file"); return null; } else { FileDB file = db.getFileByFileID(loc.getFileID()); if (file == null) { logger.log(Level.SEVERE, "Unable to find file: " + loc.getFileID()); return null; } else { ProjectDB project = db.getProjectByProjectID(file.getProjectID()); return getFile(project, file, loc); } } } private static byte[] getFile(ProjectDB project, FileDB file, LocationDB location) { if (file.getType() == File.JAR) { JarIndex index = repo.getJarIndex(); IndexedJar indexed = index.getIndexedJar(file.getHash()); if (indexed == null) { logger.log(Level.SEVERE, "Unable to find " + file + " with hash " + file.getHash()); return null; } else { if (location == null) { return FileUtils.getFileAsByteArray(indexed.getJarFile()); } else { logger.log(Level.SEVERE, "Cannot get a fragment of a jar file"); return null; } } } else if (file.getType() == File.SOURCE) { if (project.getType() == Project.CRAWLED) { IJavaFile javaFile = repo.getFile(file.getPath()); if (javaFile == null) { logger.log(Level.SEVERE, "Unable to find " + file.getPath() + " for " + file); return null; } else { if (location == null) { return FileUtils.getFileAsByteArray(javaFile.getFile()); } else { return FileUtils.getFileFragmentAsByteArray(javaFile.getFile(), location.getOffset(), location.getLength()); } } } else { java.io.File sourceFile = null; if (project.getType() == Project.JAR || project.getType() == Project.MAVEN) { JarIndex index = repo.getJarIndex(); IndexedJar indexed = index.getIndexedJar(project.getHash()); if (indexed == null) { logger.log(Level.SEVERE, "Unable to find " + project + " for class " + file + " with hash " + project.getHash()); return null; } else { sourceFile = indexed.getSourceFile(); if (sourceFile == null) { IndexedJar source = index.getPossibleSourceMatch(indexed); if (source == null) { sourceFile = indexed.getJarFile(); } else { sourceFile = source.getJarFile(); } } } } else if (project.getType() == Project.JAVA_LIBRARY) { sourceFile = extracted.getJavaLibrarySource(project.getPath()); } else { logger.log(Level.SEVERE, project + " has improper type " + project.getType() + " for looking up source files"); return null; } if (sourceFile == null) { logger.log(Level.SEVERE, "Null source file for " + file + " in " + project); return null; } else if (!sourceFile.exists()) { logger.log(Level.SEVERE, "Missing source file for " + file + " in " + project); return null; } else { ZipFile zip = null; try { zip = new ZipFile(sourceFile); String minusClass = file.getPath().substring(0, file.getPath().lastIndexOf('.')); String entryName = minusClass.replace('.', '/') + ".java"; ZipEntry entry = zip.getEntry(entryName); if (entry == null) { logger.log(Level.SEVERE, "Unable to find entry " + entryName + " in " + sourceFile.getName() + " for " + file + " and " + project); return null; } else { if (location == null) { return FileUtils.getInputStreamAsByteArray(zip.getInputStream(entry), (int)entry.getSize()); } else { return FileUtils.getInputStreamFragmentAsByteArray(zip.getInputStream(entry), location.getOffset(), location.getLength()); } } } catch (Exception e) { logger.log(Level.SEVERE, "Unable to read jar file", e); return null; } finally { FileUtils.close(zip); } } } } else { - logger.log(Level.SEVERE, "Unable to look up source for class " + file + " and " + project); + logger.log(Level.SEVERE, file + " from " + project + " is a class file with no corresponding source"); return null; } } public static void testConsole() { try { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); while (true) { System.out.println( "\nPlease enter type of item to lookup\n" + "Project (p)\n" + "File (f)\n" + "Entity (e)\n" + "Relation (r)\n" + "Comment (c)"); System.out.print(":>"); String input = reader.readLine(); if (input.equals("p") || input.equals("f") || input.equals("e") || input.equals("r") || input.equals("c")) { System.out.println("Please enter the id number"); System.out.print(":>"); String id = reader.readLine(); if (input.equals("p")) { byte[] result = lookupByProjectID(id); if (result == null) { System.out.println("Unable to find project"); } else { System.out.println("Found project with " + result.length + " bytes"); } } else if (input.equals("f")) { byte[] result = lookupByFileID(id); if (result == null) { System.out.println("Unable to find file"); } else { System.out.println(new String(result)); System.out.println("Found file with " + result.length + " bytes"); } } else if (input.equals("e")) { byte[] result = lookupByEntityID(id); if (result == null) { System.out.println("Unable to find entity"); } else { System.out.println(new String(result)); System.out.println("Found entity with " + result.length + " bytes"); } } else if (input.equals("r")) { byte[] result = lookupByRelationID(id); if (result == null) { System.out.println("Unable to find relation"); } else { System.out.println(new String(result)); System.out.println("Found relation with " + result.length + " bytes"); } } else if (input.equals("c")) { byte[] result = lookupByCommentID(id); if (result == null) { System.out.println("Unable to find comment"); } else { System.out.println(new String(result)); System.out.println("Found comment with " + result.length + " bytes"); } } } } } catch (IOException e) { e.printStackTrace(); } } private static class FileDatabaseAccessor extends DatabaseAccessor { protected FileDatabaseAccessor(DatabaseConnection connection) { super(connection); } public synchronized LocationDB getLocationByEntityID(String entityID) { return entitiesTable.getLocationByEntityID(entityID); } public synchronized LocationDB getLocationByRelationID(String relationID) { return relationsTable.getLocationByRelationID(relationID); } public synchronized LocationDB getLocationByCommentID(String commentID) { return commentsTable.getLocationByCommentID(commentID); } public synchronized FileDB getFileByFileID(String fileID) { return filesTable.getFileByFileID(fileID); } public synchronized ProjectDB getProjectByProjectID(String projectID) { return projectsTable.getProjectByProjectID(projectID); } } }
true
true
private static byte[] getFile(ProjectDB project, FileDB file, LocationDB location) { if (file.getType() == File.JAR) { JarIndex index = repo.getJarIndex(); IndexedJar indexed = index.getIndexedJar(file.getHash()); if (indexed == null) { logger.log(Level.SEVERE, "Unable to find " + file + " with hash " + file.getHash()); return null; } else { if (location == null) { return FileUtils.getFileAsByteArray(indexed.getJarFile()); } else { logger.log(Level.SEVERE, "Cannot get a fragment of a jar file"); return null; } } } else if (file.getType() == File.SOURCE) { if (project.getType() == Project.CRAWLED) { IJavaFile javaFile = repo.getFile(file.getPath()); if (javaFile == null) { logger.log(Level.SEVERE, "Unable to find " + file.getPath() + " for " + file); return null; } else { if (location == null) { return FileUtils.getFileAsByteArray(javaFile.getFile()); } else { return FileUtils.getFileFragmentAsByteArray(javaFile.getFile(), location.getOffset(), location.getLength()); } } } else { java.io.File sourceFile = null; if (project.getType() == Project.JAR || project.getType() == Project.MAVEN) { JarIndex index = repo.getJarIndex(); IndexedJar indexed = index.getIndexedJar(project.getHash()); if (indexed == null) { logger.log(Level.SEVERE, "Unable to find " + project + " for class " + file + " with hash " + project.getHash()); return null; } else { sourceFile = indexed.getSourceFile(); if (sourceFile == null) { IndexedJar source = index.getPossibleSourceMatch(indexed); if (source == null) { sourceFile = indexed.getJarFile(); } else { sourceFile = source.getJarFile(); } } } } else if (project.getType() == Project.JAVA_LIBRARY) { sourceFile = extracted.getJavaLibrarySource(project.getPath()); } else { logger.log(Level.SEVERE, project + " has improper type " + project.getType() + " for looking up source files"); return null; } if (sourceFile == null) { logger.log(Level.SEVERE, "Null source file for " + file + " in " + project); return null; } else if (!sourceFile.exists()) { logger.log(Level.SEVERE, "Missing source file for " + file + " in " + project); return null; } else { ZipFile zip = null; try { zip = new ZipFile(sourceFile); String minusClass = file.getPath().substring(0, file.getPath().lastIndexOf('.')); String entryName = minusClass.replace('.', '/') + ".java"; ZipEntry entry = zip.getEntry(entryName); if (entry == null) { logger.log(Level.SEVERE, "Unable to find entry " + entryName + " in " + sourceFile.getName() + " for " + file + " and " + project); return null; } else { if (location == null) { return FileUtils.getInputStreamAsByteArray(zip.getInputStream(entry), (int)entry.getSize()); } else { return FileUtils.getInputStreamFragmentAsByteArray(zip.getInputStream(entry), location.getOffset(), location.getLength()); } } } catch (Exception e) { logger.log(Level.SEVERE, "Unable to read jar file", e); return null; } finally { FileUtils.close(zip); } } } } else { logger.log(Level.SEVERE, "Unable to look up source for class " + file + " and " + project); return null; } }
private static byte[] getFile(ProjectDB project, FileDB file, LocationDB location) { if (file.getType() == File.JAR) { JarIndex index = repo.getJarIndex(); IndexedJar indexed = index.getIndexedJar(file.getHash()); if (indexed == null) { logger.log(Level.SEVERE, "Unable to find " + file + " with hash " + file.getHash()); return null; } else { if (location == null) { return FileUtils.getFileAsByteArray(indexed.getJarFile()); } else { logger.log(Level.SEVERE, "Cannot get a fragment of a jar file"); return null; } } } else if (file.getType() == File.SOURCE) { if (project.getType() == Project.CRAWLED) { IJavaFile javaFile = repo.getFile(file.getPath()); if (javaFile == null) { logger.log(Level.SEVERE, "Unable to find " + file.getPath() + " for " + file); return null; } else { if (location == null) { return FileUtils.getFileAsByteArray(javaFile.getFile()); } else { return FileUtils.getFileFragmentAsByteArray(javaFile.getFile(), location.getOffset(), location.getLength()); } } } else { java.io.File sourceFile = null; if (project.getType() == Project.JAR || project.getType() == Project.MAVEN) { JarIndex index = repo.getJarIndex(); IndexedJar indexed = index.getIndexedJar(project.getHash()); if (indexed == null) { logger.log(Level.SEVERE, "Unable to find " + project + " for class " + file + " with hash " + project.getHash()); return null; } else { sourceFile = indexed.getSourceFile(); if (sourceFile == null) { IndexedJar source = index.getPossibleSourceMatch(indexed); if (source == null) { sourceFile = indexed.getJarFile(); } else { sourceFile = source.getJarFile(); } } } } else if (project.getType() == Project.JAVA_LIBRARY) { sourceFile = extracted.getJavaLibrarySource(project.getPath()); } else { logger.log(Level.SEVERE, project + " has improper type " + project.getType() + " for looking up source files"); return null; } if (sourceFile == null) { logger.log(Level.SEVERE, "Null source file for " + file + " in " + project); return null; } else if (!sourceFile.exists()) { logger.log(Level.SEVERE, "Missing source file for " + file + " in " + project); return null; } else { ZipFile zip = null; try { zip = new ZipFile(sourceFile); String minusClass = file.getPath().substring(0, file.getPath().lastIndexOf('.')); String entryName = minusClass.replace('.', '/') + ".java"; ZipEntry entry = zip.getEntry(entryName); if (entry == null) { logger.log(Level.SEVERE, "Unable to find entry " + entryName + " in " + sourceFile.getName() + " for " + file + " and " + project); return null; } else { if (location == null) { return FileUtils.getInputStreamAsByteArray(zip.getInputStream(entry), (int)entry.getSize()); } else { return FileUtils.getInputStreamFragmentAsByteArray(zip.getInputStream(entry), location.getOffset(), location.getLength()); } } } catch (Exception e) { logger.log(Level.SEVERE, "Unable to read jar file", e); return null; } finally { FileUtils.close(zip); } } } } else { logger.log(Level.SEVERE, file + " from " + project + " is a class file with no corresponding source"); return null; } }
diff --git a/src/fitnesse/testsystems/slim/HtmlTable.java b/src/fitnesse/testsystems/slim/HtmlTable.java index d5fbc873f..f9f4619cb 100644 --- a/src/fitnesse/testsystems/slim/HtmlTable.java +++ b/src/fitnesse/testsystems/slim/HtmlTable.java @@ -1,383 +1,387 @@ // Copyright (C) 2003-2009 by Object Mentor, Inc. All rights reserved. // Released under the terms of the CPL Common Public License version 1.0. package fitnesse.testsystems.slim; import fitnesse.testsystems.slim.results.ExceptionResult; import fitnesse.testsystems.slim.results.TestResult; import fitnesse.testsystems.slim.tables.SyntaxError; import fitnesse.wikitext.Utils; import fitnesse.wikitext.parser.Collapsible; import org.htmlparser.Node; import org.htmlparser.Tag; import org.htmlparser.nodes.TextNode; import org.htmlparser.tags.*; import org.htmlparser.util.NodeList; import java.util.ArrayList; import java.util.List; import java.util.Stack; public class HtmlTable implements Table { private List<Row> rows = new ArrayList<Row>(); private TableTag tableNode; private List<ExceptionResult> exceptions = new ArrayList<ExceptionResult>(); public HtmlTable(TableTag tableNode) { this.tableNode = tableNode; NodeList nodeList = tableNode.getChildren(); for (int i = 0; i < nodeList.size(); i++) { Node node = nodeList.elementAt(i); if (node instanceof TableRow || node instanceof TableHeader) { rows.add(new Row((CompositeTag) node)); } } tableNode.getChildren().prepend(new ExceptionTextNode()); } public TableTag getTableNode() { return tableNode; } public String getCellContents(int columnIndex, int rowIndex) { return rows.get(rowIndex).getColumn(columnIndex).getContent(); } public String getUnescapedCellContents(int col, int row) { return Utils.unescapeHTML(getCellContents(col, row)); } public int getRowCount() { return rows.size(); } public int getColumnCountInRow(int rowIndex) { return rows.get(rowIndex).getColumnCount(); } public void substitute(int col, int row, String contents) { Cell cell = rows.get(row).getColumn(col); // TODO: need escaping here? cell.setContent(Utils.escapeHTML(contents)); } public List<List<String>> asList() { List<List<String>> list = new ArrayList<List<String>>(); for (Row row : rows) list.add(row.asList()); return list; } public String toString() { return asList().toString(); } public String toHtml() { return tableNode.toHtml(); } public int addRow(List<String> list) { Row row = new Row(); rows.add(row); tableNode.getChildren().add(row.getRowNode()); for (String s : list) row.appendCell(s == null ? "" : Utils.escapeHTML(s)); return rows.size() - 1; } public void addColumnToRow(int rowIndex, String contents) { Row row = rows.get(rowIndex); row.appendCell(Utils.escapeHTML(contents)); } /** * Scenario tables (mainly) are added on the next row. A bit of javascript allows for collapsing and * expanding. * * @see fitnesse.testsystems.slim.Table#appendChildTable(int, fitnesse.testsystems.slim.Table) */ public void appendChildTable(int rowIndex, Table childTable) { Row row = rows.get(rowIndex); row.rowNode.setAttribute("class", "scenario closed", '"'); Row childRow = new Row(); TableColumn column = (TableColumn) newTag(TableColumn.class); column.setChildren(new NodeList(((HtmlTable) childTable).getTableNode())); column.setAttribute("colspan", "" + colspan(row), '"'); childRow.appendCell(new Cell(column)); childRow.rowNode.setAttribute("class", "scenario-detail", '"'); insertRowAfter(row, childRow); } private int colspan(Row row) { NodeList rowNodes = row.rowNode.getChildren(); int colspan = 0; for (int i = 0; i < rowNodes.size(); i++) { if (rowNodes.elementAt(i) instanceof TableColumn) { String s = ((TableColumn)rowNodes.elementAt(i)).getAttribute("colspan"); if (s != null) { colspan += Integer.parseInt(s); } else { colspan++; } } } return colspan; } // It's a bit of work to insert a node with the htmlparser module. private void insertRowAfter(Row existingRow, Row childRow) { NodeList rowNodes = tableNode.getChildren(); int index = rowNodes.indexOf(existingRow.rowNode); Stack<Node> tempStack = new Stack<Node>(); while (rowNodes.size() - 1 > index) { tempStack.push(rowNodes.elementAt(tableNode.getChildren().size() - 1)); rowNodes.remove(rowNodes.size() - 1); } rowNodes.add(childRow.rowNode); while (tempStack.size() > 0) { rowNodes.add(tempStack.pop()); } } @Override public void updateContent(int row, TestResult testResult) { rows.get(row).setTestResult(testResult); } @Override public void updateContent(int col, int row, TestResult testResult) { Cell cell = rows.get(row).getColumn(col); cell.setTestResult(testResult); cell.setContent(cell.formatTestResult()); } @Override public void updateContent(int col, int row, ExceptionResult exceptionResult) { Cell cell = rows.get(row).getColumn(col); if (cell.exceptionResult == null) { cell.setExceptionResult(exceptionResult); cell.setContent(cell.formatExceptionResult()); exceptions.add(exceptionResult); } } private Tag newTag(Class<? extends Tag> klass) { Tag tag = null; try { tag = klass.newInstance(); tag.setTagName(tag.getTagName().toLowerCase()); Tag endTag = klass.newInstance(); endTag.setTagName("/" + tag.getTagName().toLowerCase()); endTag.setParent(tag); tag.setEndTag(endTag); } catch (Exception e) { e.printStackTrace(); } return tag; } class Row { private List<Cell> cells = new ArrayList<Cell>(); private CompositeTag rowNode; public Row(CompositeTag rowNode) { this.rowNode = rowNode; NodeList nodeList = rowNode.getChildren(); for (int i = 0; i < nodeList.size(); i++) { Node node = nodeList.elementAt(i); if (node instanceof TableColumn) cells.add(new Cell((TableColumn) node)); } } public Row() { rowNode = (TableRow) newTag(TableRow.class); rowNode.setChildren(new NodeList()); Tag endNode = new TableRow(); endNode.setTagName("/" + rowNode.getTagName().toLowerCase()); rowNode.setEndTag(endNode); } public int getColumnCount() { return cells.size(); } public Cell getColumn(int columnIndex) { return cells.get(columnIndex); } public void appendCell(String contents) { Cell newCell = new Cell(contents); appendCell(newCell); } private void appendCell(Cell newCell) { rowNode.getChildren().add(newCell.getColumnNode()); cells.add(newCell); } public CompositeTag getRowNode() { return rowNode; } private List<String> asList() { List<String> list = new ArrayList<String>(); for (Cell cell : cells) { // was "colorized" list.add(cell.getTestResult()); } return list; } private void setTestResult(TestResult testResult) { NodeList cells = rowNode.getChildren(); for (int i = 0; i < cells.size(); i++) { Node cell = cells.elementAt(i); if (cell instanceof Tag) { Tag tag = (Tag) cell; tag.setAttribute("class", testResult.getExecutionResult().toString(), '"'); } } } } class Cell { private final TableColumn columnNode; private final String originalContent; private TestResult testResult; private ExceptionResult exceptionResult; public Cell(TableColumn tableColumn) { columnNode = tableColumn; originalContent = Utils.unescapeHTML(columnNode.getChildrenHTML()); } public Cell(String contents) { if (contents == null) contents = ""; TextNode text = new TextNode(contents); text.setChildren(new NodeList()); columnNode = (TableColumn) newTag(TableColumn.class); columnNode.setChildren(new NodeList(text)); originalContent = contents; } public String getContent() { return Utils.unescapeHTML(getEscapedContent()); } public String getEscapedContent() { String unescaped = columnNode.getChildrenHTML(); //Some browsers need &nbsp; inside an empty table cell, so we remove it here. return "&nbsp;".equals(unescaped) ? "" : unescaped; } private void setContent(String s) { // No HTML escaping here. TextNode textNode = new TextNode(s); NodeList nodeList = new NodeList(textNode); columnNode.setChildren(nodeList); } public String getTestResult() { return testResult != null ? testResult.toString(originalContent) : getContent(); } public TableColumn getColumnNode() { return columnNode; } public void setTestResult(TestResult testResult) { this.testResult = testResult; } public void setExceptionResult(ExceptionResult exceptionResult) { this.exceptionResult = exceptionResult; } public String formatTestResult() { if (testResult.getExecutionResult() == null) { return testResult.getMessage() != null ? testResult.getMessage() : originalContent; } final String escapedMessage = testResult.hasMessage() ? Utils.escapeHTML(testResult.getMessage()) : originalContent; switch (testResult.getExecutionResult()) { case PASS: return String.format("<span class=\"pass\">%s</span>", escapedMessage); case FAIL: if (testResult.hasActual() && testResult.hasExpected()) { return String.format("[%s] <span class=\"fail\">expected [%s]</span>", Utils.escapeHTML(testResult.getActual()), Utils.escapeHTML(testResult.getExpected())); + } else if ((testResult.hasActual() || testResult.hasExpected()) && testResult.hasMessage()) { + return String.format("[%s] <span class=\"fail\">%s</span>", + Utils.escapeHTML(testResult.hasActual() ? testResult.getActual() : testResult.getExpected()), + Utils.escapeHTML(testResult.getMessage())); } return String.format("<span class=\"fail\">%s</span>", escapedMessage); case IGNORE: return String.format("%s <span class=\"ignore\">%s</span>", originalContent, escapedMessage); case ERROR: return String.format("%s <span class=\"error\">%s</span>", originalContent, escapedMessage); } return "Should not be here"; } public String formatExceptionResult() { if (exceptionResult.hasMessage()) { return String.format("%s <span class=\"%s\">%s</span>", originalContent, exceptionResult.getExecutionResult().toString(), Utils.escapeHTML(exceptionResult.getMessage())); } else { // See below where exception block is formatted return String.format("%s <span class=\"%s\">Exception: <a href=\"#%s\">%s</a></span>", originalContent, exceptionResult.getExecutionResult().toString(), exceptionResult.getResultKey(), exceptionResult.getResultKey()); } } } @Override public HtmlTable asTemplate(CellContentSubstitution substitution) throws SyntaxError { String script = this.toHtml(); // Quick 'n' Dirty script = substitution.substitute(0, 0, script); return new HtmlTableScanner(script).getTable(0); } // This is not the nicest solution, since the the exceptions are put inside the <table> tag. class ExceptionTextNode extends TextNode { public ExceptionTextNode() { super(""); } @Override public String toHtml(boolean verbatim) { if(!haveExceptionsWithoutMessage()) { return ""; } StringBuilder buffer = new StringBuilder(512); buffer.append("<div class=\"exceptions\"><h3>Exceptions</h3>"); for (ExceptionResult exceptionResult : exceptions) { if (!exceptionResult.hasMessage()) { buffer.append(String.format("<a name=\"%s\"></a>", exceptionResult.getResultKey())); buffer.append(Collapsible.generateHtml(Collapsible.CLOSED, Utils.escapeHTML(exceptionResult.getResultKey()), "<pre>" + Utils.escapeHTML(exceptionResult.getException()) + "</pre>")); } } buffer.append("</div>"); return buffer.toString(); } private boolean haveExceptionsWithoutMessage() { for (ExceptionResult exception : exceptions) { if (!exception.hasMessage()) { return true; } } return false; } } }
true
true
public String formatTestResult() { if (testResult.getExecutionResult() == null) { return testResult.getMessage() != null ? testResult.getMessage() : originalContent; } final String escapedMessage = testResult.hasMessage() ? Utils.escapeHTML(testResult.getMessage()) : originalContent; switch (testResult.getExecutionResult()) { case PASS: return String.format("<span class=\"pass\">%s</span>", escapedMessage); case FAIL: if (testResult.hasActual() && testResult.hasExpected()) { return String.format("[%s] <span class=\"fail\">expected [%s]</span>", Utils.escapeHTML(testResult.getActual()), Utils.escapeHTML(testResult.getExpected())); } return String.format("<span class=\"fail\">%s</span>", escapedMessage); case IGNORE: return String.format("%s <span class=\"ignore\">%s</span>", originalContent, escapedMessage); case ERROR: return String.format("%s <span class=\"error\">%s</span>", originalContent, escapedMessage); } return "Should not be here"; }
public String formatTestResult() { if (testResult.getExecutionResult() == null) { return testResult.getMessage() != null ? testResult.getMessage() : originalContent; } final String escapedMessage = testResult.hasMessage() ? Utils.escapeHTML(testResult.getMessage()) : originalContent; switch (testResult.getExecutionResult()) { case PASS: return String.format("<span class=\"pass\">%s</span>", escapedMessage); case FAIL: if (testResult.hasActual() && testResult.hasExpected()) { return String.format("[%s] <span class=\"fail\">expected [%s]</span>", Utils.escapeHTML(testResult.getActual()), Utils.escapeHTML(testResult.getExpected())); } else if ((testResult.hasActual() || testResult.hasExpected()) && testResult.hasMessage()) { return String.format("[%s] <span class=\"fail\">%s</span>", Utils.escapeHTML(testResult.hasActual() ? testResult.getActual() : testResult.getExpected()), Utils.escapeHTML(testResult.getMessage())); } return String.format("<span class=\"fail\">%s</span>", escapedMessage); case IGNORE: return String.format("%s <span class=\"ignore\">%s</span>", originalContent, escapedMessage); case ERROR: return String.format("%s <span class=\"error\">%s</span>", originalContent, escapedMessage); } return "Should not be here"; }
diff --git a/freeplane/src/org/freeplane/view/swing/map/attribute/CursorUpdater.java b/freeplane/src/org/freeplane/view/swing/map/attribute/CursorUpdater.java index ede64830a..17dbf634f 100644 --- a/freeplane/src/org/freeplane/view/swing/map/attribute/CursorUpdater.java +++ b/freeplane/src/org/freeplane/view/swing/map/attribute/CursorUpdater.java @@ -1,94 +1,94 @@ /* * Freeplane - mind map editor * Copyright (C) 2011 dimitry * * This file author is dimitry * * 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, see <http://www.gnu.org/licenses/>. */ package org.freeplane.view.swing.map.attribute; import java.awt.Component; import java.awt.Cursor; import java.awt.Point; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionListener; import java.net.URI; import javax.swing.Icon; /** * @author Dimitry Polivaev * Mar 4, 2011 */ class CursorUpdater extends MouseAdapter implements MouseMotionListener{ public void mouseDragged(MouseEvent e) { } public void mouseMoved(MouseEvent e) { updateCursor(e); } @Override public void mouseEntered(MouseEvent e) { updateCursor(e); } @Override public void mouseExited(MouseEvent e) { updateCursor(e.getComponent(), Cursor.DEFAULT_CURSOR); } private void updateCursor(MouseEvent e) { final int cursor = getCursor(e); updateCursor(e.getComponent(), cursor); } private int getCursor(MouseEvent e) { final AttributeTable table = (AttributeTable) e.getComponent(); final Point point = e.getPoint(); final int col = table.columnAtPoint(point); if(col != 1){ return Cursor.DEFAULT_CURSOR; } final int row = table.rowAtPoint(e.getPoint()); - if(row >= table.getRowCount()){ + if(row == -1 || row >= table.getRowCount()){ return Cursor.DEFAULT_CURSOR; } Object value = table.getValueAt(row, col); if(!(value instanceof URI)){ return Cursor.DEFAULT_CURSOR; } final Icon linkIcon = table.getLinkIcon((URI) value); if (linkIcon == null) return Cursor.DEFAULT_CURSOR; final int leftColumnWidth = table.getColumnModel().getColumn(0).getWidth(); if (point.x < leftColumnWidth + linkIcon.getIconWidth()) { return Cursor.HAND_CURSOR; } return Cursor.DEFAULT_CURSOR; } private void updateCursor(Component component, int cursor) { final Cursor newCursor = Cursor.getPredefinedCursor(cursor); if( component.getCursor().equals(newCursor)) return; component.setCursor(cursor == Cursor.DEFAULT_CURSOR ? null : newCursor); } }
true
true
private int getCursor(MouseEvent e) { final AttributeTable table = (AttributeTable) e.getComponent(); final Point point = e.getPoint(); final int col = table.columnAtPoint(point); if(col != 1){ return Cursor.DEFAULT_CURSOR; } final int row = table.rowAtPoint(e.getPoint()); if(row >= table.getRowCount()){ return Cursor.DEFAULT_CURSOR; } Object value = table.getValueAt(row, col); if(!(value instanceof URI)){ return Cursor.DEFAULT_CURSOR; } final Icon linkIcon = table.getLinkIcon((URI) value); if (linkIcon == null) return Cursor.DEFAULT_CURSOR; final int leftColumnWidth = table.getColumnModel().getColumn(0).getWidth(); if (point.x < leftColumnWidth + linkIcon.getIconWidth()) { return Cursor.HAND_CURSOR; } return Cursor.DEFAULT_CURSOR; }
private int getCursor(MouseEvent e) { final AttributeTable table = (AttributeTable) e.getComponent(); final Point point = e.getPoint(); final int col = table.columnAtPoint(point); if(col != 1){ return Cursor.DEFAULT_CURSOR; } final int row = table.rowAtPoint(e.getPoint()); if(row == -1 || row >= table.getRowCount()){ return Cursor.DEFAULT_CURSOR; } Object value = table.getValueAt(row, col); if(!(value instanceof URI)){ return Cursor.DEFAULT_CURSOR; } final Icon linkIcon = table.getLinkIcon((URI) value); if (linkIcon == null) return Cursor.DEFAULT_CURSOR; final int leftColumnWidth = table.getColumnModel().getColumn(0).getWidth(); if (point.x < leftColumnWidth + linkIcon.getIconWidth()) { return Cursor.HAND_CURSOR; } return Cursor.DEFAULT_CURSOR; }
diff --git a/pmd-netbeans/src/pmd/RunPMDAction.java b/pmd-netbeans/src/pmd/RunPMDAction.java index 16277275d..ac0d2b59f 100644 --- a/pmd-netbeans/src/pmd/RunPMDAction.java +++ b/pmd-netbeans/src/pmd/RunPMDAction.java @@ -1,392 +1,392 @@ /* * Copyright (c) 2002-2003, the pmd-netbeans team * 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. * * 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 REGENTS 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 pmd; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.io.StringReader; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; import java.util.Iterator; import java.util.List; import net.sourceforge.pmd.PMD; import net.sourceforge.pmd.PMDException; import net.sourceforge.pmd.Report; import net.sourceforge.pmd.Rule; import net.sourceforge.pmd.RuleContext; import net.sourceforge.pmd.RuleSet; import net.sourceforge.pmd.RuleViolation; import net.sourceforge.pmd.TargetJDK1_3; import net.sourceforge.pmd.TargetJDK1_4; import net.sourceforge.pmd.TargetJDK1_5; import org.netbeans.api.java.classpath.ClassPath; import org.netbeans.api.java.queries.SourceLevelQuery; import org.netbeans.api.progress.ProgressHandle; import org.netbeans.api.progress.ProgressHandleFactory; import org.openide.ErrorManager; import org.openide.awt.StatusDisplayer; import org.openide.cookies.EditorCookie; import org.openide.cookies.LineCookie; import org.openide.cookies.SourceCookie; import org.openide.filesystems.FileObject; import org.openide.loaders.DataFolder; import org.openide.loaders.DataObject; import org.openide.nodes.Node; import org.openide.util.Cancellable; import org.openide.util.HelpCtx; import org.openide.util.Lookup; import org.openide.util.NbBundle; import org.openide.util.actions.CookieAction; import org.openide.windows.IOProvider; import org.openide.windows.InputOutput; import org.openide.windows.OutputWriter; import pmd.config.ConfigUtils; import pmd.scan.EditorChangeListener; /** * Action that runs PMD on the currently selected Java file or set of Java files. * This is called both by NetBeans when the action is manually invoked by the user * ({@link #performAction}), * and by the real-time scanner when a Java file needs to be scanned * ({@link #checkCookies}). */ public class RunPMDAction extends CookieAction { /** True means verbose trace logging should be performed. **/ public static final boolean TRACE_LOGGING = Boolean.getBoolean("pmd-netbeans.trace.logging"); /** * Overridden to log that the action is being initialized, and to register an editor change listener for * scanning. */ protected void initialize() { super.initialize(); EditorChangeListener.initialize(); putValue("noIconInMenu", Boolean.TRUE); } /** * Gets the name of this action * * @return the name of this action */ public String getName() { return NbBundle.getMessage( RunPMDAction.class, "LBL_Action" ); } /** * Gets the filename of the icon associated with this action * * @return the name of the icon */ protected String iconResource() { return "pmd/resources/PMDOptionsSettingsIcon.gif"; } /** * Returns default help * * @return HelpCtx.DEFAULT_HELP */ public HelpCtx getHelpCtx() { return HelpCtx.DEFAULT_HELP; } /** * Returns the cookies that can use this action * * @return an array of the two elements DataFolder.class and SourceCookie.class */ protected Class[] cookieClasses() { return new Class[]{DataFolder.class, SourceCookie.class}; } /** * Returns the mode of this action * * @return the mode of this action * @see org.openide.util.actions.CookieAction#MODE_ALL */ protected int mode() { return MODE_ALL; } /** * Runs PMD on the given list of DataObjects, with no callback. * This just calls {@link #checkCookies(List, RunPMDCallback)} with a default callback that displays * progress in the status bar. * * @param dataobjects the list of data objects to run PMD on, not null. Elements are instanceof * {@link DataObject}. * @return the list of rule violations found in the run, not null. Elements are instanceof {@link Fault}. * @throws IOException on failure to read one of the files or to write to the output window. */ public static List checkCookies( List dataobjects ) throws IOException { SourceLevelQuery sourceLevelQuery = (SourceLevelQuery) Lookup.getDefault().lookup(SourceLevelQuery.class); RuleSet set = constructRuleSets(); PMD pmd_1_3 = null; PMD pmd_1_4 = null; PMD pmd_1_5 = null; ArrayList list = new ArrayList( 100 ); CancelCallback cancel = new CancelCallback (); ProgressHandle prgHdl = ProgressHandleFactory.createHandle("PMD check", cancel); // PENDING action to show output prgHdl.start(dataobjects.size()); for( int i = 0; i < dataobjects.size(); i++ ) { if (cancel.isCancelled()) break; DataObject dataobject = ( DataObject )dataobjects.get( i ); prgHdl.progress(dataobject.getName(), i); // TODO: I18N 'name', x of y FileObject fobj = dataobject.getPrimaryFile(); String name = ClassPath.getClassPath( fobj, ClassPath.SOURCE ).getResourceName( fobj, '.', false ); //The file is not a java file if( !dataobject.getPrimaryFile().hasExt( "java" ) || dataobject.getCookie( LineCookie.class ) == null ) { continue; } String sourceLevel = sourceLevelQuery.getSourceLevel(fobj); // choose the correct PMD to use according to the source level PMD pmd = null; if (sourceLevel != null) { if (sourceLevel.equals("1.5")) { if (pmd_1_5 == null) pmd_1_5 = new PMD(new TargetJDK1_5()); pmd = pmd_1_5; } else if (sourceLevel.equals("1.3")) { if (pmd_1_3 == null) pmd_1_3 = new PMD(new TargetJDK1_3()); pmd = pmd_1_3; } } // default to JDK 1.4 if we don't know any better... if (pmd == null) { if (pmd_1_4 == null) pmd_1_4 = new PMD(new TargetJDK1_4()); pmd = pmd_1_4; } Reader reader; try { reader = getSourceReader( dataobject ); } catch( IOException ioe) { Fault fault = new Fault( 1, name, "IOException reading file for class " + name + ": " + ioe.toString()); ErrorManager.getDefault().notify( ioe ); list.add( fault ); FaultRegistry.getInstance().registerFault( fault, dataobject ); continue; } RuleContext ctx = new RuleContext(); Report report = new Report(); ctx.setReport( report ); ctx.setSourceCodeFilename( name ); try { pmd.processFile( reader, set, ctx ); } catch( PMDException e ) { Fault fault = new Fault( 1, name, e ); ErrorManager.getDefault().log(ErrorManager.ERROR, "PMD threw exception " + e.toString()); ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, e); // XXX why to report this ? list.add( fault ); FaultRegistry.getInstance().registerFault( fault, dataobject ); } Iterator iterator = ctx.getReport().iterator(); while( iterator.hasNext() ) { RuleViolation violation = ( RuleViolation )iterator.next(); StringBuffer buffer = new StringBuffer(); buffer.append( violation.getRule().getName() ).append( ", " ); buffer.append( violation.getDescription() ); - Fault fault = new Fault( violation.getLine(), + Fault fault = new Fault( violation.getNode().getBeginLine(), violation.getFilename(), buffer.toString() ); list.add( fault ); FaultRegistry.getInstance().registerFault( fault, dataobject ); } } prgHdl.finish(); Collections.sort( list ); return list; } /** * Performs the action this action is set up to do on the specified nodes * * @param node the nodes that the action is involved on */ protected void performAction( Node[] node ) { PMDOutputListener listener = PMDOutputListener.getInstance(); listener.detach(); FaultRegistry.getInstance().clearRegistry(); OutputWriter out = null; try { StatusDisplayer.getDefault().setStatusText("PMD checking for rule violations"); List list = getDataObjects(node); List violations = checkCookies(list); IOProvider ioProvider = (IOProvider)Lookup.getDefault().lookup(IOProvider.class); InputOutput output = ioProvider.getIO("PMD output", false); if(violations.isEmpty()) { StatusDisplayer.getDefault().setStatusText("PMD found no rule violations"); output.closeInputOutput(); } else { output.select(); out = output.getOut(); out.reset(); for(int i = 0; i < violations.size(); i++) { Fault fault = (Fault)violations.get(i); if(fault.getLine() == -1) { output.getOut().println(String.valueOf(fault)); } else { output.getOut().println(String.valueOf(fault), listener); } } StatusDisplayer.getDefault().setStatusText("PMD found rule violations"); } } catch(IOException e) { ErrorManager.getDefault().notify(e); } finally { if (out != null) { out.close(); } } } /** * Constructs the ruleset. * * @return the constructed ruleset * @see pmd.config.PMDOptionsSettings#getRulesets() */ private static RuleSet constructRuleSets() { RuleSet rules = new RuleSet(); List list = ConfigUtils.getRuleList(); Iterator iterator = list.iterator(); while( iterator.hasNext() ) { rules.addRule( ( Rule )iterator.next() ); } return rules; } /** * Get the reader for the specified dataobject * * @param dataobject the dataobject to read * @return a reader for the dataobject * @exception IOException if the object can't be read */ private static Reader getSourceReader( DataObject dataobject ) throws IOException { Reader reader; EditorCookie editor = ( EditorCookie )dataobject.getCookie( EditorCookie.class ); //If it's the currently open document that's being checked if( editor != null && editor.getOpenedPanes() != null ) { String text = editor.getOpenedPanes()[0].getText(); reader = new StringReader( text ); } else { Iterator iterator = dataobject.files().iterator(); FileObject file = ( FileObject )iterator.next(); reader = new BufferedReader( new InputStreamReader( file.getInputStream() ) ); } return reader; } /** * Gets the data objects associated with the given nodes. * * @param node the nodes to get data objects for * @return a list of the data objects. Each element is instanceof DataObject. */ private List getDataObjects( Node[] node ) { ArrayList list = new ArrayList(); for( int i = 0; i < node.length; i++ ) { DataObject data = (DataObject)node[i].getCookie( DataObject.class ); //Checks to see if it's a java source file if( data.getPrimaryFile().hasExt( "java" ) ) { list.add( data ); } //Or if it's a folder else { DataFolder folder = ( DataFolder )node[i].getCookie( DataFolder.class ); Enumeration enumeration = folder.children( true ); while( enumeration.hasMoreElements() ) { DataObject dataobject = ( DataObject )enumeration.nextElement(); if( dataobject.getPrimaryFile().hasExt( "java" ) ) { list.add( dataobject ); } } } } return list; } protected boolean asynchronous() { // PENDING need to rewriet to synchronous action return true; } private static class CancelCallback implements Cancellable { private boolean cancelled = false; public CancelCallback () {} public boolean cancel() { cancelled = true; return true; } public boolean isCancelled () { return cancelled; } } }
true
true
public static List checkCookies( List dataobjects ) throws IOException { SourceLevelQuery sourceLevelQuery = (SourceLevelQuery) Lookup.getDefault().lookup(SourceLevelQuery.class); RuleSet set = constructRuleSets(); PMD pmd_1_3 = null; PMD pmd_1_4 = null; PMD pmd_1_5 = null; ArrayList list = new ArrayList( 100 ); CancelCallback cancel = new CancelCallback (); ProgressHandle prgHdl = ProgressHandleFactory.createHandle("PMD check", cancel); // PENDING action to show output prgHdl.start(dataobjects.size()); for( int i = 0; i < dataobjects.size(); i++ ) { if (cancel.isCancelled()) break; DataObject dataobject = ( DataObject )dataobjects.get( i ); prgHdl.progress(dataobject.getName(), i); // TODO: I18N 'name', x of y FileObject fobj = dataobject.getPrimaryFile(); String name = ClassPath.getClassPath( fobj, ClassPath.SOURCE ).getResourceName( fobj, '.', false ); //The file is not a java file if( !dataobject.getPrimaryFile().hasExt( "java" ) || dataobject.getCookie( LineCookie.class ) == null ) { continue; } String sourceLevel = sourceLevelQuery.getSourceLevel(fobj); // choose the correct PMD to use according to the source level PMD pmd = null; if (sourceLevel != null) { if (sourceLevel.equals("1.5")) { if (pmd_1_5 == null) pmd_1_5 = new PMD(new TargetJDK1_5()); pmd = pmd_1_5; } else if (sourceLevel.equals("1.3")) { if (pmd_1_3 == null) pmd_1_3 = new PMD(new TargetJDK1_3()); pmd = pmd_1_3; } } // default to JDK 1.4 if we don't know any better... if (pmd == null) { if (pmd_1_4 == null) pmd_1_4 = new PMD(new TargetJDK1_4()); pmd = pmd_1_4; } Reader reader; try { reader = getSourceReader( dataobject ); } catch( IOException ioe) { Fault fault = new Fault( 1, name, "IOException reading file for class " + name + ": " + ioe.toString()); ErrorManager.getDefault().notify( ioe ); list.add( fault ); FaultRegistry.getInstance().registerFault( fault, dataobject ); continue; } RuleContext ctx = new RuleContext(); Report report = new Report(); ctx.setReport( report ); ctx.setSourceCodeFilename( name ); try { pmd.processFile( reader, set, ctx ); } catch( PMDException e ) { Fault fault = new Fault( 1, name, e ); ErrorManager.getDefault().log(ErrorManager.ERROR, "PMD threw exception " + e.toString()); ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, e); // XXX why to report this ? list.add( fault ); FaultRegistry.getInstance().registerFault( fault, dataobject ); } Iterator iterator = ctx.getReport().iterator(); while( iterator.hasNext() ) { RuleViolation violation = ( RuleViolation )iterator.next(); StringBuffer buffer = new StringBuffer(); buffer.append( violation.getRule().getName() ).append( ", " ); buffer.append( violation.getDescription() ); Fault fault = new Fault( violation.getLine(), violation.getFilename(), buffer.toString() ); list.add( fault ); FaultRegistry.getInstance().registerFault( fault, dataobject ); } } prgHdl.finish(); Collections.sort( list ); return list; }
public static List checkCookies( List dataobjects ) throws IOException { SourceLevelQuery sourceLevelQuery = (SourceLevelQuery) Lookup.getDefault().lookup(SourceLevelQuery.class); RuleSet set = constructRuleSets(); PMD pmd_1_3 = null; PMD pmd_1_4 = null; PMD pmd_1_5 = null; ArrayList list = new ArrayList( 100 ); CancelCallback cancel = new CancelCallback (); ProgressHandle prgHdl = ProgressHandleFactory.createHandle("PMD check", cancel); // PENDING action to show output prgHdl.start(dataobjects.size()); for( int i = 0; i < dataobjects.size(); i++ ) { if (cancel.isCancelled()) break; DataObject dataobject = ( DataObject )dataobjects.get( i ); prgHdl.progress(dataobject.getName(), i); // TODO: I18N 'name', x of y FileObject fobj = dataobject.getPrimaryFile(); String name = ClassPath.getClassPath( fobj, ClassPath.SOURCE ).getResourceName( fobj, '.', false ); //The file is not a java file if( !dataobject.getPrimaryFile().hasExt( "java" ) || dataobject.getCookie( LineCookie.class ) == null ) { continue; } String sourceLevel = sourceLevelQuery.getSourceLevel(fobj); // choose the correct PMD to use according to the source level PMD pmd = null; if (sourceLevel != null) { if (sourceLevel.equals("1.5")) { if (pmd_1_5 == null) pmd_1_5 = new PMD(new TargetJDK1_5()); pmd = pmd_1_5; } else if (sourceLevel.equals("1.3")) { if (pmd_1_3 == null) pmd_1_3 = new PMD(new TargetJDK1_3()); pmd = pmd_1_3; } } // default to JDK 1.4 if we don't know any better... if (pmd == null) { if (pmd_1_4 == null) pmd_1_4 = new PMD(new TargetJDK1_4()); pmd = pmd_1_4; } Reader reader; try { reader = getSourceReader( dataobject ); } catch( IOException ioe) { Fault fault = new Fault( 1, name, "IOException reading file for class " + name + ": " + ioe.toString()); ErrorManager.getDefault().notify( ioe ); list.add( fault ); FaultRegistry.getInstance().registerFault( fault, dataobject ); continue; } RuleContext ctx = new RuleContext(); Report report = new Report(); ctx.setReport( report ); ctx.setSourceCodeFilename( name ); try { pmd.processFile( reader, set, ctx ); } catch( PMDException e ) { Fault fault = new Fault( 1, name, e ); ErrorManager.getDefault().log(ErrorManager.ERROR, "PMD threw exception " + e.toString()); ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, e); // XXX why to report this ? list.add( fault ); FaultRegistry.getInstance().registerFault( fault, dataobject ); } Iterator iterator = ctx.getReport().iterator(); while( iterator.hasNext() ) { RuleViolation violation = ( RuleViolation )iterator.next(); StringBuffer buffer = new StringBuffer(); buffer.append( violation.getRule().getName() ).append( ", " ); buffer.append( violation.getDescription() ); Fault fault = new Fault( violation.getNode().getBeginLine(), violation.getFilename(), buffer.toString() ); list.add( fault ); FaultRegistry.getInstance().registerFault( fault, dataobject ); } } prgHdl.finish(); Collections.sort( list ); return list; }
diff --git a/src/main/java/com/freeroom/projectci/beans/ReportService.java b/src/main/java/com/freeroom/projectci/beans/ReportService.java index 18ee643..08888c8 100644 --- a/src/main/java/com/freeroom/projectci/beans/ReportService.java +++ b/src/main/java/com/freeroom/projectci/beans/ReportService.java @@ -1,72 +1,72 @@ package com.freeroom.projectci.beans; import com.freeroom.di.annotations.Bean; import com.freeroom.di.annotations.Inject; import com.freeroom.persistence.Athena; import com.freeroom.util.Pair; import org.joda.time.DateTime; import org.joda.time.Days; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import java.util.List; import static com.freeroom.projectci.beans.ReportType.*; import static java.lang.String.format; @Bean public class ReportService { @Inject private Athena athena; public Collection getCollection(ReportType type) { return new Collection(type, type.getEstimatedEffort(), calculateUsedEffort(athena.from(TimeReport.class).find(format("type='%s'", type)))); } public Pair<Integer, Integer> getTickBar() { final DateTime now = new DateTime(); final DateTime begin = new DateTime(2014, 4, 15, 0, 0, 0); final DateTime end = new DateTime(2014, 10, 13, 0, 0, 0); return Pair.of(Days.daysBetween(begin, end).getDays(), Days.daysBetween(begin, now).getDays()); } public void addReport(TimeReport report) { athena.persist(report); } private long calculateUsedEffort(List<Object> reports) { long usedEffort = 0; for (Object report : reports) { usedEffort += ((TimeReport) report).getHours(); } return usedEffort; } public String utilityData() { final DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyyMMdd"); final DateTime yesterday = new DateTime().minusDays(1); - DateTime date = new DateTime(2013, 7, 23, 0, 0, 0); + DateTime date = new DateTime(2014, 4, 15, 0, 0, 0); final StringBuilder sb = new StringBuilder(); sb.append("date\tMust\tOthers\r\n"); while(date.isBefore(yesterday)) { final List<Object> mustReports = athena.from(TimeReport.class).find( format("date='%s' and (type='%s' or type='%s' or type='%s' or type='%s' or type='%s')", date.toDate().getTime(), UserStory, FunctionalTesting, PerformanceTesting, IntegrationTesting, Document)); final List<Object> othersReports = athena.from(TimeReport.class).find( format("date='%s' and (type='%s' or type='%s' or type='%s' or type='%s')", date.toDate().getTime(), OverTime, BugFixing, Leave, Others)); sb.append(format("%s\t%d\t%d\r\n", formatter.print(date), calculateUsedEffort(mustReports), calculateUsedEffort(othersReports))); date = date.plusDays(1); } return sb.toString(); } }
true
true
public String utilityData() { final DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyyMMdd"); final DateTime yesterday = new DateTime().minusDays(1); DateTime date = new DateTime(2013, 7, 23, 0, 0, 0); final StringBuilder sb = new StringBuilder(); sb.append("date\tMust\tOthers\r\n"); while(date.isBefore(yesterday)) { final List<Object> mustReports = athena.from(TimeReport.class).find( format("date='%s' and (type='%s' or type='%s' or type='%s' or type='%s' or type='%s')", date.toDate().getTime(), UserStory, FunctionalTesting, PerformanceTesting, IntegrationTesting, Document)); final List<Object> othersReports = athena.from(TimeReport.class).find( format("date='%s' and (type='%s' or type='%s' or type='%s' or type='%s')", date.toDate().getTime(), OverTime, BugFixing, Leave, Others)); sb.append(format("%s\t%d\t%d\r\n", formatter.print(date), calculateUsedEffort(mustReports), calculateUsedEffort(othersReports))); date = date.plusDays(1); } return sb.toString(); }
public String utilityData() { final DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyyMMdd"); final DateTime yesterday = new DateTime().minusDays(1); DateTime date = new DateTime(2014, 4, 15, 0, 0, 0); final StringBuilder sb = new StringBuilder(); sb.append("date\tMust\tOthers\r\n"); while(date.isBefore(yesterday)) { final List<Object> mustReports = athena.from(TimeReport.class).find( format("date='%s' and (type='%s' or type='%s' or type='%s' or type='%s' or type='%s')", date.toDate().getTime(), UserStory, FunctionalTesting, PerformanceTesting, IntegrationTesting, Document)); final List<Object> othersReports = athena.from(TimeReport.class).find( format("date='%s' and (type='%s' or type='%s' or type='%s' or type='%s')", date.toDate().getTime(), OverTime, BugFixing, Leave, Others)); sb.append(format("%s\t%d\t%d\r\n", formatter.print(date), calculateUsedEffort(mustReports), calculateUsedEffort(othersReports))); date = date.plusDays(1); } return sb.toString(); }
diff --git a/MonTransit/src/org/montrealtransit/android/activity/SplashScreen.java b/MonTransit/src/org/montrealtransit/android/activity/SplashScreen.java index 3607dabf..66801380 100755 --- a/MonTransit/src/org/montrealtransit/android/activity/SplashScreen.java +++ b/MonTransit/src/org/montrealtransit/android/activity/SplashScreen.java @@ -1,253 +1,254 @@ package org.montrealtransit.android.activity; import java.text.NumberFormat; import org.montrealtransit.android.AnalyticsUtils; import org.montrealtransit.android.Constant; import org.montrealtransit.android.MyLog; import org.montrealtransit.android.R; import org.montrealtransit.android.Utils; import org.montrealtransit.android.provider.StmDbHelper; import android.app.Activity; import android.app.ProgressDialog; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager.NameNotFoundException; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.text.Spannable; import android.text.SpannableString; import android.text.style.StyleSpan; import android.view.View; import android.widget.ProgressBar; import android.widget.TextView; /** * This class is the first screen displayed by the application. * @author Mathieu Méa */ // TODO add version checking here (start asynchronously and the send a notification to the user). public class SplashScreen extends Activity { /** * The log tag. */ private static final String TAG = SplashScreen.class.getSimpleName(); /** * The tracker tag. */ private static final String TRACKER_TAG = "/SplashScreen"; /** * The progress bar title message. */ private TextView progressBarMessageTitle; /** * The progress bar description message. */ private TextView progressBarMessageDesc; /** * The progress bar. */ private ProgressBar progressBar; /** * The progress bar percent. */ private TextView progressBarPercent; /** * The progress bar number. */ private TextView progressBarNumber; /** * The progress bar percent format. */ private NumberFormat progressPercentFormat; /** * The progress bar number format. */ private String progressNumberFormat; /** * The progress bar update handler (from AOSP {@link ProgressDialog}). */ private Handler progressBarUpdateHandler; @Override protected void onCreate(Bundle savedInstanceState) { Utils.logAppVersion(this); MyLog.v(TAG, "onCreate()"); super.onCreate(savedInstanceState); // CHECK DB for initialize/update int currentDeployedStmDbVersion = Utils.getSharedPreferences(this, UserPreferences.PREFS_STM_DB_VERSION, 0); switch (currentDeployedStmDbVersion) { case StmDbHelper.DB_VERSION: showMainScreen(); break; default: deploy(); break; } } @Override protected void onResume() { MyLog.v(TAG, "onResume()"); AnalyticsUtils.trackPageView(this, TRACKER_TAG); super.onResume(); } /** * Deploy or update the STM DB. */ private void deploy() { MyLog.v(TAG, "deploy()"); if (!StmDbHelper.isDbExist(this)) { showSplashScreen(); addProgressBar(); // show a progress dialog this.progressBar.setIndeterminate(true); this.progressBarMessageTitle.setVisibility(View.VISIBLE); this.progressBarMessageTitle.setText(R.string.init_dialog_title); this.progressBarMessageDesc.setVisibility(View.VISIBLE); this.progressBarMessageDesc.setText(getString(R.string.init_dialog_message)); // initialize the database new InitializationTask().execute(false); } else { StmDbHelper tmp = new StmDbHelper(this, null); tmp.getReadableDatabase(); boolean updateAvailable = tmp.isUpdateAvailable(); tmp.close(); if (updateAvailable) { showSplashScreen(); + addProgressBar(); // show a progress dialog this.progressBar.setIndeterminate(true); this.progressBarMessageTitle.setVisibility(View.VISIBLE); this.progressBarMessageTitle.setText(R.string.update_dialog_title); this.progressBarMessageDesc.setVisibility(View.VISIBLE); this.progressBarMessageDesc.setText(R.string.update_dialog_message); // initialize the database new InitializationTask().execute(true); } else { // Show main Screen showMainScreen(); } } } /** * Show the progress bar. */ private void addProgressBar() { this.progressBarMessageTitle = (TextView) findViewById(R.id.message_title); this.progressBarMessageDesc = (TextView) findViewById(R.id.message_desc); this.progressBar = (ProgressBar) findViewById(R.id.progress); this.progressBarPercent = (TextView) findViewById(R.id.progress_percent); this.progressPercentFormat = NumberFormat.getPercentInstance(); this.progressPercentFormat.setMaximumFractionDigits(0); this.progressBarNumber = (TextView) findViewById(R.id.progress_number); this.progressNumberFormat = "%d/%d"; progressBarUpdateHandler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); /* Update the number and percent */ int progress = SplashScreen.this.progressBar.getProgress(); int max = SplashScreen.this.progressBar.getMax(); double percent = (double) progress / (double) max; String format = SplashScreen.this.progressNumberFormat; SplashScreen.this.progressBarNumber.setText(String.format(format, progress, max)); SpannableString tmp = new SpannableString(SplashScreen.this.progressPercentFormat.format(percent)); tmp.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 0, tmp.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); SplashScreen.this.progressBarPercent.setText(tmp); } }; findViewById(R.id.progress_layout).setVisibility(View.VISIBLE); } /** * Show the splash screen. */ private void showSplashScreen() { MyLog.v(TAG, "showSplashScreen()"); // Show splash screen setContentView(R.layout.splash_screen); try { PackageInfo packageInfo = getPackageManager().getPackageInfo(Constant.PKG, 0); String versionName = packageInfo.versionName; String versionCode = String.valueOf(packageInfo.versionCode); TextView versionTv = (TextView) findViewById(R.id.app_version); versionTv.setText(getString(R.string.about_version, versionName, versionCode)); } catch (NameNotFoundException e) { } } /** * Show the main screen. */ private void showMainScreen() { MyLog.v(TAG, "showMainScreen()"); Intent intent = new Intent(this, MainScreen.class); startActivity(intent); this.finish(); } /** * This task initialize the application. */ public class InitializationTask extends AsyncTask<Boolean, String, String> { /** * The log tag. */ private final String TAG = InitializationTask.class.getSimpleName(); @Override protected String doInBackground(Boolean... arg0) { MyLog.v(TAG, "doInBackground()"); StmDbHelper db = new StmDbHelper(SplashScreen.this, this); if (arg0[0]) { db.forceReset(SplashScreen.this, this); // clean old favorites Utils.cleanFavorites(getContentResolver()); } return null; } /** * Initialized the progress bar with max value. * @param maxValue the max value */ public void initProgressBar(int maxValue) { MyLog.v(TAG, "initProgressBar(%s)", maxValue); SplashScreen.this.progressBar.setIndeterminate(false); SplashScreen.this.progressBar.setMax(maxValue); SplashScreen.this.progressBarUpdateHandler.sendEmptyMessage(0); } /** * Set the progress bar progress to the new progress. * @param value the new progress */ public void incrementProgressBar(int value) { // MyLog.v(TAG, "incrementProgressBar(%s)", value); SplashScreen.this.progressBar.setProgress(value); SplashScreen.this.progressBarUpdateHandler.sendEmptyMessage(0); } @Override protected void onPostExecute(String result) { MyLog.v(TAG, "onPostExecute()", result); super.onPostExecute(result); SplashScreen.this.findViewById(R.id.progress_layout).setVisibility(View.GONE); showMainScreen(); } } }
true
true
private void deploy() { MyLog.v(TAG, "deploy()"); if (!StmDbHelper.isDbExist(this)) { showSplashScreen(); addProgressBar(); // show a progress dialog this.progressBar.setIndeterminate(true); this.progressBarMessageTitle.setVisibility(View.VISIBLE); this.progressBarMessageTitle.setText(R.string.init_dialog_title); this.progressBarMessageDesc.setVisibility(View.VISIBLE); this.progressBarMessageDesc.setText(getString(R.string.init_dialog_message)); // initialize the database new InitializationTask().execute(false); } else { StmDbHelper tmp = new StmDbHelper(this, null); tmp.getReadableDatabase(); boolean updateAvailable = tmp.isUpdateAvailable(); tmp.close(); if (updateAvailable) { showSplashScreen(); // show a progress dialog this.progressBar.setIndeterminate(true); this.progressBarMessageTitle.setVisibility(View.VISIBLE); this.progressBarMessageTitle.setText(R.string.update_dialog_title); this.progressBarMessageDesc.setVisibility(View.VISIBLE); this.progressBarMessageDesc.setText(R.string.update_dialog_message); // initialize the database new InitializationTask().execute(true); } else { // Show main Screen showMainScreen(); } } }
private void deploy() { MyLog.v(TAG, "deploy()"); if (!StmDbHelper.isDbExist(this)) { showSplashScreen(); addProgressBar(); // show a progress dialog this.progressBar.setIndeterminate(true); this.progressBarMessageTitle.setVisibility(View.VISIBLE); this.progressBarMessageTitle.setText(R.string.init_dialog_title); this.progressBarMessageDesc.setVisibility(View.VISIBLE); this.progressBarMessageDesc.setText(getString(R.string.init_dialog_message)); // initialize the database new InitializationTask().execute(false); } else { StmDbHelper tmp = new StmDbHelper(this, null); tmp.getReadableDatabase(); boolean updateAvailable = tmp.isUpdateAvailable(); tmp.close(); if (updateAvailable) { showSplashScreen(); addProgressBar(); // show a progress dialog this.progressBar.setIndeterminate(true); this.progressBarMessageTitle.setVisibility(View.VISIBLE); this.progressBarMessageTitle.setText(R.string.update_dialog_title); this.progressBarMessageDesc.setVisibility(View.VISIBLE); this.progressBarMessageDesc.setText(R.string.update_dialog_message); // initialize the database new InitializationTask().execute(true); } else { // Show main Screen showMainScreen(); } } }
diff --git a/LabBook/source/GraphTool.java b/LabBook/source/GraphTool.java index ff18aaf..33fda3e 100644 --- a/LabBook/source/GraphTool.java +++ b/LabBook/source/GraphTool.java @@ -1,341 +1,341 @@ /* Copyright (C) 2001 Concord Consortium 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. */ package org.concord.LabBook; import waba.ui.*; import waba.fx.*; import waba.io.*; import waba.sys.*; import waba.util.*; import graph.*; import extra.ui.*; import org.concord.waba.extra.probware.*; import org.concord.waba.extra.probware.probs.*; import org.concord.waba.extra.event.*; public class GraphTool extends Container implements DataListener { ProbManager pm = null; AnnotView lg; Pushbutton [] modControl; int i; Label tOffVal, tVal; LabelBuf curVal, curTime; Label localLabel; Button clearB, exitB; TextLine convertor = new TextLine("0"); // Transform startingTrans; // int curProbe = 3; Label bytesRead = new Label("-2"); Label line2 = new Label("-1"); MainWindow mw = null; String units = ""; CCProb curProbe = null; Bin curBin = null; Vector bins = new Vector(); boolean slowUpdate = false; // int [] [] pTimes = new int [1000][]; int [] [] pTimes = null; LObjDataControl dc = null; public GraphTool(AnnotView av, LObjDataControl dc, String units, int w, int h) { convertor.maxDigits = 2; this.dc = dc; pm = ProbManager.getProbManager(dc.interfaceId); int xPos = 0; int buttonWidth; this.units = units; lg = av; // curProbe = probeId; convertor.maxDigits = 2; setRect(0,0,w, h); String [] names = new String [2]; names [0] = "Start"; names [1] = "Stop"; modControl = Pushbutton.createGroup(names, 1); buttonWidth = h-2; if(h < 30) buttonWidth = 30; modControl[0].setRect(xPos,0,buttonWidth,h-2); xPos += buttonWidth+2; modControl[1].setRect(xPos,0,buttonWidth,h-2); xPos += buttonWidth; add(modControl[0]); add(modControl[1]); curVal = new LabelBuf(""); curVal.setRect(xPos,0,w*50/160,h/2); curVal.setFont(new Font("Helvetica", Font.BOLD, h*12/20 - (h-20)*8/20)); add(curVal); curTime = new LabelBuf("0.0s"); curTime.setRect(xPos,h/2,w*50/160,h/2); curTime.setFont(new Font("Helvetica", Font.BOLD, h*12/20 - (h-20)*8/20)); add(curTime); xPos += w*50/160; if(w < 170){ clearB = new Button("Clear"); clearB.setRect(w-26, 0, 25, 17); add(clearB); } else { exitB = new Button("Exit"); exitB.setRect(w-32, 0, 32, h/2); add(exitB); clearB = new Button("Clear"); clearB.setRect(w-32, h/2, 32, h/2); add(clearB); } curBin = lg.getBin(); curProbe = dc.getProbe(); pm.registerProb(curProbe); pm.addDataListenerToProb(curProbe.getName(),this); bytesRead.setRect(105, 0, 30, 10); //add(bytesRead); line2.setRect(0, 10, 160, 10); //add(line2); mw = MainWindow.getMainWindow(); } float val= 0f; float time = 0f; int numVals = 0; public void dataReceived(DataEvent dataEvent) { if(dataEvent.type == DataEvent.DATA_READY_TO_START){ if(pm.getMode() == CCInterfaceManager.A2D_10_MODE){ slowUpdate = true; } else { slowUpdate = false; } numVals = 0; curPtime = 0; return; } if(slowUpdate){ if(dataEvent.type == DataEvent.DATA_RECEIVED){ if(lg.active){ int startPTime = Vm.getTimeStamp(); if(!curBin.dataReceived(dataEvent)){ stop(); lg.curView.draw(); return; } dataEvent.pTimes[dataEvent.numPTimes++] = Vm.getTimeStamp() - startPTime; savePTimes(dataEvent); } numVals += dataEvent.numbSamples; val = dataEvent.data[dataEvent.dataOffset]; - time = dataEvent.time; + time = dataEvent.getTime(); } else { int startPTime = Vm.getTimeStamp(); if(pTimes != null){ pTimes [curPtime] = new int [6]; pTimes[curPtime][0] = 1; pTimes[curPtime][1] = startPTime; pTimes[curPtime][2] = numVals; } // if(lg.active){ lg.update(); int newTime = Vm.getTimeStamp(); if(pTimes != null){ pTimes[curPtime][3] = (newTime - startPTime); } String output1, output2; output1 = Convert.toString(val); output2 = Convert.toString(time); startPTime = Vm.getTimeStamp(); if(pTimes != null){ pTimes[curPtime][4] = (startPTime - newTime); } curVal.setText(output1); curTime.setText(output2); if(pTimes != null){ pTimes[curPtime][5] = (Vm.getTimeStamp() - startPTime); } numVals = 0; curPtime++; } } else { // System.out.println("Data: " + dataEvent.data[0]); if(lg.active){ if(!curBin.dataReceived(dataEvent)){ stop(); lg.curView.draw(); return; } lg.update(); } curVal.setText(dataEvent.data[dataEvent.dataOffset] + ""); - curTime.setText(dataEvent.time + "s"); + curTime.setText(dataEvent.getTime() + "s"); } } public String pTimeText = ""; int curPtime = 0; public void savePTimes(DataEvent dEvent) { if(pTimes != null){ pTimes [curPtime] = new int [dEvent.numPTimes + 1]; pTimes [curPtime][0] = 0; for(int i=0; i< dEvent.numPTimes; i++){ pTimes [curPtime][i+1] = dEvent.pTimes[i]; } curPtime++; } } public void setPos(int x, int y) { setRect(x,y,width,height); } float oldVal; public void onExit() { pm.stop(); if(curProbe != null){ pm.unRegisterProb(curProbe); } lg.free(); curVal.free(); curTime.free(); } void stop() { if(lg.active){ lg.active = false; curBin = lg.pause(); } pm.stop(); modControl[1].setSelected(true); repaint(); } public void onEvent(Event e) { float newVal; if(e.type == ControlEvent.PRESSED){ Control target = (Control)e.target; int index; if(target == modControl[0] && modControl[0].isSelected()){ // start if(bins.getCount() == 0){ lg.active = true; bins.add(curBin); curBin.time = new Time(); curBin.description = dc.getObj(0).name; } slowUpdate = false; bytesRead.setText((byte)'C' + ""); pTimeText = ""; pm.start(); } else if(target == modControl[1] && modControl[1].isSelected()){ stop(); } else if(target == clearB){ // ask for confirmation stop(); lg.reset(); curVal.setText(""); curTime.setText("0.0s"); bins = new Vector(); } else if(target == exitB){ // doit mw.exit(0); } } else if(e.type == 1003){ // System.out.println("Got 1003"); if(lg.lgView.selAnnot != null){ curVal.setText(convertor.fToString(lg.lgView.selAnnot.value) + units); curTime.setText(convertor.fToString(lg.lgView.selAnnot.time) + "s"); } else { // hack curVal.setText(""); curTime.setText(""); } } } }
false
true
public void dataReceived(DataEvent dataEvent) { if(dataEvent.type == DataEvent.DATA_READY_TO_START){ if(pm.getMode() == CCInterfaceManager.A2D_10_MODE){ slowUpdate = true; } else { slowUpdate = false; } numVals = 0; curPtime = 0; return; } if(slowUpdate){ if(dataEvent.type == DataEvent.DATA_RECEIVED){ if(lg.active){ int startPTime = Vm.getTimeStamp(); if(!curBin.dataReceived(dataEvent)){ stop(); lg.curView.draw(); return; } dataEvent.pTimes[dataEvent.numPTimes++] = Vm.getTimeStamp() - startPTime; savePTimes(dataEvent); } numVals += dataEvent.numbSamples; val = dataEvent.data[dataEvent.dataOffset]; time = dataEvent.time; } else { int startPTime = Vm.getTimeStamp(); if(pTimes != null){ pTimes [curPtime] = new int [6]; pTimes[curPtime][0] = 1; pTimes[curPtime][1] = startPTime; pTimes[curPtime][2] = numVals; } // if(lg.active){ lg.update(); int newTime = Vm.getTimeStamp(); if(pTimes != null){ pTimes[curPtime][3] = (newTime - startPTime); } String output1, output2; output1 = Convert.toString(val); output2 = Convert.toString(time); startPTime = Vm.getTimeStamp(); if(pTimes != null){ pTimes[curPtime][4] = (startPTime - newTime); } curVal.setText(output1); curTime.setText(output2); if(pTimes != null){ pTimes[curPtime][5] = (Vm.getTimeStamp() - startPTime); } numVals = 0; curPtime++; } } else { // System.out.println("Data: " + dataEvent.data[0]); if(lg.active){ if(!curBin.dataReceived(dataEvent)){ stop(); lg.curView.draw(); return; } lg.update(); } curVal.setText(dataEvent.data[dataEvent.dataOffset] + ""); curTime.setText(dataEvent.time + "s"); } }
public void dataReceived(DataEvent dataEvent) { if(dataEvent.type == DataEvent.DATA_READY_TO_START){ if(pm.getMode() == CCInterfaceManager.A2D_10_MODE){ slowUpdate = true; } else { slowUpdate = false; } numVals = 0; curPtime = 0; return; } if(slowUpdate){ if(dataEvent.type == DataEvent.DATA_RECEIVED){ if(lg.active){ int startPTime = Vm.getTimeStamp(); if(!curBin.dataReceived(dataEvent)){ stop(); lg.curView.draw(); return; } dataEvent.pTimes[dataEvent.numPTimes++] = Vm.getTimeStamp() - startPTime; savePTimes(dataEvent); } numVals += dataEvent.numbSamples; val = dataEvent.data[dataEvent.dataOffset]; time = dataEvent.getTime(); } else { int startPTime = Vm.getTimeStamp(); if(pTimes != null){ pTimes [curPtime] = new int [6]; pTimes[curPtime][0] = 1; pTimes[curPtime][1] = startPTime; pTimes[curPtime][2] = numVals; } // if(lg.active){ lg.update(); int newTime = Vm.getTimeStamp(); if(pTimes != null){ pTimes[curPtime][3] = (newTime - startPTime); } String output1, output2; output1 = Convert.toString(val); output2 = Convert.toString(time); startPTime = Vm.getTimeStamp(); if(pTimes != null){ pTimes[curPtime][4] = (startPTime - newTime); } curVal.setText(output1); curTime.setText(output2); if(pTimes != null){ pTimes[curPtime][5] = (Vm.getTimeStamp() - startPTime); } numVals = 0; curPtime++; } } else { // System.out.println("Data: " + dataEvent.data[0]); if(lg.active){ if(!curBin.dataReceived(dataEvent)){ stop(); lg.curView.draw(); return; } lg.update(); } curVal.setText(dataEvent.data[dataEvent.dataOffset] + ""); curTime.setText(dataEvent.getTime() + "s"); } }
diff --git a/org.whole.lang.e4.ui/src/org/whole/lang/e4/ui/expressions/NotationsVisibleWhen.java b/org.whole.lang.e4.ui/src/org/whole/lang/e4/ui/expressions/NotationsVisibleWhen.java index 080102518..247add40d 100644 --- a/org.whole.lang.e4.ui/src/org/whole/lang/e4/ui/expressions/NotationsVisibleWhen.java +++ b/org.whole.lang.e4.ui/src/org/whole/lang/e4/ui/expressions/NotationsVisibleWhen.java @@ -1,34 +1,34 @@ /** * Copyright 2004-2013 Riccardo Solmi. All rights reserved. * This file is part of the Whole Platform. * * The Whole Platform 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. * * The Whole Platform 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 the Whole Platform. If not, see <http://www.gnu.org/licenses/>. */ package org.whole.lang.e4.ui.expressions; import org.whole.lang.bindings.IBindingManager; import org.whole.lang.e4.ui.viewers.E4GraphicalViewer; /** * @author Enrico Persiani */ public class NotationsVisibleWhen extends ValidSingleSelectionVisibleWhen { @Override public boolean isVisible(IBindingManager bm) { if (!super.isVisible(bm)) return false; - return bm.wGet("viewer") instanceof E4GraphicalViewer; + return bm.wGetValue("viewer") instanceof E4GraphicalViewer; } }
true
true
public boolean isVisible(IBindingManager bm) { if (!super.isVisible(bm)) return false; return bm.wGet("viewer") instanceof E4GraphicalViewer; }
public boolean isVisible(IBindingManager bm) { if (!super.isVisible(bm)) return false; return bm.wGetValue("viewer") instanceof E4GraphicalViewer; }
diff --git a/src/net/leifandersen/mobile/android/netcatch/activities/EpisodesListActivity.java b/src/net/leifandersen/mobile/android/netcatch/activities/EpisodesListActivity.java index b2ca076..f4727fa 100644 --- a/src/net/leifandersen/mobile/android/netcatch/activities/EpisodesListActivity.java +++ b/src/net/leifandersen/mobile/android/netcatch/activities/EpisodesListActivity.java @@ -1,543 +1,544 @@ /*Copyright 2010 NetCatch Team *Licensed under the Apache License, Version 2.0 (the "License"); *you may not use this file except in compliance with the License. *You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * *Unless required by applicable law or agreed to in writing, software *distributed under the License is distributed on an "AS IS" BASIS, *WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *See the License for the specific language governing permissions and *limitations under the License. */ package net.leifandersen.mobile.android.netcatch.activities; import java.io.File; import java.sql.Date; import java.util.ArrayList; import java.util.List; import net.leifandersen.mobile.android.netcatch.R; import net.leifandersen.mobile.android.netcatch.other.ThemeTools; import net.leifandersen.mobile.android.netcatch.other.Tools; import net.leifandersen.mobile.android.netcatch.providers.Episode; import net.leifandersen.mobile.android.netcatch.providers.ShowsProvider; import net.leifandersen.mobile.android.netcatch.services.MediaDownloadService; import net.leifandersen.mobile.android.netcatch.services.RSSService; import net.leifandersen.mobile.android.netcatch.services.UnsubscribeService; import android.app.AlertDialog; import android.app.Dialog; import android.app.ListActivity; import android.app.ProgressDialog; import android.content.BroadcastReceiver; import android.content.ContentValues; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.database.Cursor; import android.graphics.PorterDuff; import android.graphics.PorterDuffColorFilter; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.preference.PreferenceManager; import android.text.TextUtils; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; /** * * @author Leif Andersen * */ public class EpisodesListActivity extends ListActivity { private static final class ViewHolder { TextView title; TextView description; TextView date; } private class EpisodeAdapter extends ArrayAdapter<Episode> { LayoutInflater mInflater; public EpisodeAdapter(Context context) { super(context, R.layout.episode_list_item); mInflater = getLayoutInflater(); } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if(convertView == null) { convertView = mInflater.inflate(R.layout.episode_list_item, null); holder = new ViewHolder(); holder.title = (TextView)convertView.findViewById(R.id.eli_title); holder.description = (TextView)convertView.findViewById(R.id.eli_description); holder.date = (TextView)convertView.findViewById(R.id.eli_release_date); convertView.setTag(holder); } else holder = (ViewHolder)convertView.getTag(); Episode episode = getItem(position); holder.title.setText(episode.getTitle()); holder.description.setText(episode.getDescription()); // holder.date.setText(episode.getDate()); holder.date.setTag(new Date(episode.getDate()).toString()); return convertView; } } public static final String SHOW_ID = "show_id"; public static final String SHOW_NAME = "show_name"; private LinearLayout background; private FrameLayout header; private String mShowName; private long mShowID; private EpisodeAdapter mAdapter; private static final int NEW_FEED = 1; private static final int UNSUBSCRIBE = 2; private static final int IMPLICIT_NEW_FEED = 3; private List<Episode> mEpisodes; private SharedPreferences mSharedPrefs; private String mFeed; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.episodes_list); mSharedPrefs = PreferenceManager.getDefaultSharedPreferences(this); if(getIntent().getDataString() == null) explicitInitiate(); else implicitInitiate(); // Set up the view background = (LinearLayout)findViewById(R.id.background); header = (FrameLayout)findViewById(R.id.header); int x = mSharedPrefs.getInt("theme_color", -1); if(x != -1) ThemeTools.setColorOverlay(new PorterDuffColorFilter(x, PorterDuff.Mode.MULTIPLY), background, header); // Set the List Adapter refreshList(); // Register the list for context menus registerForContextMenu(getListView()); } private void implicitInitiate() { mFeed = getIntent().getDataString(); showDialog(IMPLICIT_NEW_FEED); } private void explicitInitiate() { // Get the show name // If no show was passed in, the activity was called poorly, abort. Bundle b = getIntent().getExtras(); if (b == null) throw new IllegalArgumentException("No Bundle Given"); mShowID = b.getLong(SHOW_ID, -1); mShowName = b.getString(SHOW_NAME); if(mShowID < 0 || mShowName == null) throw new IllegalArgumentException("No show ID and name given"); } @Override protected void onRestart() { super.onResume(); // Set up the color int x = mSharedPrefs.getInt("theme_color", -1); if(x != -1) ThemeTools.setColorOverlay(new PorterDuffColorFilter(x, PorterDuff.Mode.MULTIPLY), background, header); // Refresh the list refreshList(); } @Override protected void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); Episode e = mEpisodes.get(position); Intent i = new Intent(); i.putExtra(EpisodeActivity.ID, e.getId()); // TODO i.setClass(this, EpisodeActivity.class); startActivity(i); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.episodes_options, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { Intent activity; switch (item.getItemId()) { case R.id.home_item: activity = new Intent(); activity.setClass(this, NCMain.class); startActivity(activity); return true; case R.id.unsubscribe_item: showDialog(UNSUBSCRIBE); break; case R.id.new_show_item: showDialog(NEW_FEED); return true; case R.id.preferences_item: activity = new Intent(); activity.setClass(this, Preferences.class); startActivity(activity); return true; } return false; } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); // If menuInfo is null abort if(menuInfo == null) return; MenuInflater inflater = getMenuInflater(); AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo; Episode episode = mEpisodes.get((int)info.id); if(TextUtils.isEmpty(episode.getMedia())) { if(episode.isPlayed()) inflater.inflate( R.menu.episodes_context_not_downloaded_played, menu); else inflater.inflate( R.menu.episodes_context_not_downloaded_unplayed, menu); } else { if(episode.isPlayed()) inflater.inflate( R.menu.episodes_context_downloaded_played, menu); else inflater.inflate( R.menu.episodes_context_downloaded_unplayed, menu); } } @Override public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo)item.getMenuInfo(); final Episode episode = mEpisodes.get((int)info.id); switch(item.getItemId()) { case R.id.download: if(Environment.MEDIA_MOUNTED.equals( Environment.getExternalStorageState()) && episode.getMediaUrl() != null) { // Calculate the download directory // Setup files, save data int slashIndex = episode.getMediaUrl().lastIndexOf('/'); String filename = episode.getMediaUrl().substring(slashIndex + 1); SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this); final File file = new File(Environment.getExternalStorageDirectory(), pref.getString(Preferences.DOWNLOAD_LOCATION, "PODCASTS") + "/" + mShowName + "/" + filename); // Initiate the download Intent service = new Intent(); service.setClass(this, MediaDownloadService.class) .putExtra(MediaDownloadService.MEDIA_ID, episode.getId()) .putExtra(MediaDownloadService.MEDIA_URL,episode.getMediaUrl()) .putExtra(MediaDownloadService.MEDIA_LOCATION, file.getPath()) .putExtra(MediaDownloadService.BACKGROUND_UPDATE, false); startService(service); // Set up the receivers on finish // finished receiver final BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { // Update the media locatioin in the database ContentValues values = new ContentValues(); values.put(ShowsProvider.MEDIA, file.getPath()); getContentResolver().update(Uri.parse(ShowsProvider. EPISODES_CONTENT_URI + "/" + episode.getId()), values, null, null); // Finish up, unregister receivers Log.v("EpisodeDownload", "Finished downloading episode"); unregisterReceiver(this); } }; registerReceiver(receiver, new IntentFilter(MediaDownloadService.MEDIA_FINISHED + episode.getMediaUrl() + " " + file.getPath())); return true; } else return false; case R.id.delete: if(Environment.MEDIA_MOUNTED.equals( Environment.getExternalStorageState()) && episode.getMedia() != null) { File file = new File(episode.getMedia()); if(!file.delete()) { Toast.makeText(this, R.string.could_not_delete, Toast.LENGTH_LONG).show(); } // Clear out the location in the episode object episode.setMedia(null); // Remove it form the database too. ContentValues v = new ContentValues(); v.put(ShowsProvider.MEDIA, ""); getContentResolver().update(Uri.parse( ShowsProvider.EPISODES_CONTENT_URI + "/" + episode.getId()), v, null, null); return true; } else return false; case R.id.play: Intent intent = new Intent(); intent.putExtra(EpisodeActivity.ID, episode.getId()); startActivity(intent); } return false; } @Override protected Dialog onCreateDialog(int id) { return onCreateDialog(id, new Bundle()); } @Override protected Dialog onCreateDialog(int id, Bundle args) { Dialog dialog = null; switch(id) { case NEW_FEED: dialog = Tools.createSubscriptionDialog(this); break; case UNSUBSCRIBE: dialog = Tools.createUnsubscribeDialog(this, new DialogInterface.OnClickListener() { BroadcastReceiver finishedReceiver; ProgressDialog progressDialog; public void onClick(DialogInterface dialog, int id) { // Register the broadcast receiver finishedReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { // Clean up the mess that was made. unregisterReceiver(finishedReceiver); progressDialog.cancel(); refreshList(); finish(); } }; registerReceiver(finishedReceiver, new IntentFilter(UnsubscribeService.FINISHED +mShowID)); // Pop up a dialog while waiting progressDialog = ProgressDialog.show(EpisodesListActivity.this, "", EpisodesListActivity.this.getString( R.string.unsubscribing_from_show) + mShowName + EpisodesListActivity.this.getString( R.string.end_quotation)); progressDialog.setCancelable(false); progressDialog.show(); // Unsubscribe from the show Intent service = new Intent(); service.putExtra(UnsubscribeService.SHOW_ID, mShowID); service.setClass(EpisodesListActivity.this, UnsubscribeService.class); startService(service); } }, mShowName, mShowID); break; case IMPLICIT_NEW_FEED: AlertDialog.Builder builder = new AlertDialog.Builder(this); // Set up the layout LayoutInflater inflater = (LayoutInflater)getSystemService( Context.LAYOUT_INFLATER_SERVICE); View layout = inflater.inflate(R.layout.subscription_feed_dialog, null); final EditText editFeed = (EditText)layout.findViewById(R.id.sfd_editText); editFeed.setText(mFeed); builder.setView(layout); builder.setCancelable(false); builder.setPositiveButton(getString(android.R.string.ok), new DialogInterface.OnClickListener() { BroadcastReceiver finishedReceiver; BroadcastReceiver failedReciever; ProgressDialog progressDialog; @Override public void onClick(DialogInterface dialog, int which) { final String newFeed = editFeed.getText().toString(); // Get the feed's data // Set the broadcast reciever finishedReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { // Clean up progressDialog.dismiss(); unregisterReceiver(finishedReceiver); unregisterReceiver(failedReciever); // Refresh the list mShowID = intent.getLongExtra(RSSService.ID, -1); mShowName = intent.getStringExtra(RSSService.NAME); if(mShowID < 0) { finish(); return; } refreshList(); } }; registerReceiver(finishedReceiver, new IntentFilter(RSSService.RSSFINISH + newFeed)); // Set up the failed dialog failedReciever = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { progressDialog.dismiss(); Toast.makeText(EpisodesListActivity.this, "Failed to fetch feed", Toast.LENGTH_LONG).show(); unregisterReceiver(finishedReceiver); unregisterReceiver(failedReciever); finish(); } }; registerReceiver(failedReciever, new IntentFilter(RSSService.RSSFAILED + newFeed)); // Show a waiting dialog (that can be canceled) progressDialog = ProgressDialog.show(EpisodesListActivity.this, "", getString(R.string.getting_show_details)); progressDialog.setOnCancelListener( new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { try { unregisterReceiver(finishedReceiver); } catch (Exception e) { Log.w("EpisodesListActivity", "finishedReceiver already " + "unregistered"); } try { unregisterReceiver(failedReciever); } catch (Exception e) { Log.w("EpisodesListActivity", "failedReceiver already " + "unregistered"); } finish(); } }); progressDialog.setCancelable(true); progressDialog.show(); // Start the service Intent service = new Intent(); service.putExtra(RSSService.FEED, newFeed); service.putExtra(RSSService.BACKGROUND_UPDATE, false); service.setClass(EpisodesListActivity.this, RSSService.class); startService(service); } }); builder.setNegativeButton(getString(android.R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { + finish(); dialog.cancel(); } }); dialog = builder.create(); break; default: dialog = null; } return dialog; } private void refreshList() { mAdapter = new EpisodeAdapter(this); setListAdapter(mAdapter); // Get a list of all of the elements. // Add the list to the adapter mEpisodes = new ArrayList<Episode>(); Cursor c = managedQuery(Uri.parse(ShowsProvider.SHOWS_CONTENT_URI + "/" + mShowID + "/episodes"), null, null, null, null); if (c.moveToLast()) do { Episode ep = new Episode( c.getLong(c.getColumnIndex(ShowsProvider._ID)), mShowID, c.getString(c.getColumnIndex(ShowsProvider.TITLE)), c.getString(c.getColumnIndex(ShowsProvider.AUTHOR)), c.getString(c.getColumnIndex(ShowsProvider.DESCRIPTION)) , c.getString(c.getColumnIndex(ShowsProvider.MEDIA)), c.getString(c.getColumnIndex(ShowsProvider.MEDIA_URL)), c.getLong(c.getColumnIndex(ShowsProvider.DATE)), c.getLong(c.getColumnIndex(ShowsProvider.BOOKMARK)), c.getLong(c.getColumnIndex(ShowsProvider.PLAYED)) == ShowsProvider.IS_PLAYED); mAdapter.add(ep); mEpisodes.add(ep); } while (c.moveToPrevious()); } }
true
true
protected Dialog onCreateDialog(int id, Bundle args) { Dialog dialog = null; switch(id) { case NEW_FEED: dialog = Tools.createSubscriptionDialog(this); break; case UNSUBSCRIBE: dialog = Tools.createUnsubscribeDialog(this, new DialogInterface.OnClickListener() { BroadcastReceiver finishedReceiver; ProgressDialog progressDialog; public void onClick(DialogInterface dialog, int id) { // Register the broadcast receiver finishedReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { // Clean up the mess that was made. unregisterReceiver(finishedReceiver); progressDialog.cancel(); refreshList(); finish(); } }; registerReceiver(finishedReceiver, new IntentFilter(UnsubscribeService.FINISHED +mShowID)); // Pop up a dialog while waiting progressDialog = ProgressDialog.show(EpisodesListActivity.this, "", EpisodesListActivity.this.getString( R.string.unsubscribing_from_show) + mShowName + EpisodesListActivity.this.getString( R.string.end_quotation)); progressDialog.setCancelable(false); progressDialog.show(); // Unsubscribe from the show Intent service = new Intent(); service.putExtra(UnsubscribeService.SHOW_ID, mShowID); service.setClass(EpisodesListActivity.this, UnsubscribeService.class); startService(service); } }, mShowName, mShowID); break; case IMPLICIT_NEW_FEED: AlertDialog.Builder builder = new AlertDialog.Builder(this); // Set up the layout LayoutInflater inflater = (LayoutInflater)getSystemService( Context.LAYOUT_INFLATER_SERVICE); View layout = inflater.inflate(R.layout.subscription_feed_dialog, null); final EditText editFeed = (EditText)layout.findViewById(R.id.sfd_editText); editFeed.setText(mFeed); builder.setView(layout); builder.setCancelable(false); builder.setPositiveButton(getString(android.R.string.ok), new DialogInterface.OnClickListener() { BroadcastReceiver finishedReceiver; BroadcastReceiver failedReciever; ProgressDialog progressDialog; @Override public void onClick(DialogInterface dialog, int which) { final String newFeed = editFeed.getText().toString(); // Get the feed's data // Set the broadcast reciever finishedReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { // Clean up progressDialog.dismiss(); unregisterReceiver(finishedReceiver); unregisterReceiver(failedReciever); // Refresh the list mShowID = intent.getLongExtra(RSSService.ID, -1); mShowName = intent.getStringExtra(RSSService.NAME); if(mShowID < 0) { finish(); return; } refreshList(); } }; registerReceiver(finishedReceiver, new IntentFilter(RSSService.RSSFINISH + newFeed)); // Set up the failed dialog failedReciever = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { progressDialog.dismiss(); Toast.makeText(EpisodesListActivity.this, "Failed to fetch feed", Toast.LENGTH_LONG).show(); unregisterReceiver(finishedReceiver); unregisterReceiver(failedReciever); finish(); } }; registerReceiver(failedReciever, new IntentFilter(RSSService.RSSFAILED + newFeed)); // Show a waiting dialog (that can be canceled) progressDialog = ProgressDialog.show(EpisodesListActivity.this, "", getString(R.string.getting_show_details)); progressDialog.setOnCancelListener( new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { try { unregisterReceiver(finishedReceiver); } catch (Exception e) { Log.w("EpisodesListActivity", "finishedReceiver already " + "unregistered"); } try { unregisterReceiver(failedReciever); } catch (Exception e) { Log.w("EpisodesListActivity", "failedReceiver already " + "unregistered"); } finish(); } }); progressDialog.setCancelable(true); progressDialog.show(); // Start the service Intent service = new Intent(); service.putExtra(RSSService.FEED, newFeed); service.putExtra(RSSService.BACKGROUND_UPDATE, false); service.setClass(EpisodesListActivity.this, RSSService.class); startService(service); } }); builder.setNegativeButton(getString(android.R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); dialog = builder.create(); break; default: dialog = null; } return dialog; }
protected Dialog onCreateDialog(int id, Bundle args) { Dialog dialog = null; switch(id) { case NEW_FEED: dialog = Tools.createSubscriptionDialog(this); break; case UNSUBSCRIBE: dialog = Tools.createUnsubscribeDialog(this, new DialogInterface.OnClickListener() { BroadcastReceiver finishedReceiver; ProgressDialog progressDialog; public void onClick(DialogInterface dialog, int id) { // Register the broadcast receiver finishedReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { // Clean up the mess that was made. unregisterReceiver(finishedReceiver); progressDialog.cancel(); refreshList(); finish(); } }; registerReceiver(finishedReceiver, new IntentFilter(UnsubscribeService.FINISHED +mShowID)); // Pop up a dialog while waiting progressDialog = ProgressDialog.show(EpisodesListActivity.this, "", EpisodesListActivity.this.getString( R.string.unsubscribing_from_show) + mShowName + EpisodesListActivity.this.getString( R.string.end_quotation)); progressDialog.setCancelable(false); progressDialog.show(); // Unsubscribe from the show Intent service = new Intent(); service.putExtra(UnsubscribeService.SHOW_ID, mShowID); service.setClass(EpisodesListActivity.this, UnsubscribeService.class); startService(service); } }, mShowName, mShowID); break; case IMPLICIT_NEW_FEED: AlertDialog.Builder builder = new AlertDialog.Builder(this); // Set up the layout LayoutInflater inflater = (LayoutInflater)getSystemService( Context.LAYOUT_INFLATER_SERVICE); View layout = inflater.inflate(R.layout.subscription_feed_dialog, null); final EditText editFeed = (EditText)layout.findViewById(R.id.sfd_editText); editFeed.setText(mFeed); builder.setView(layout); builder.setCancelable(false); builder.setPositiveButton(getString(android.R.string.ok), new DialogInterface.OnClickListener() { BroadcastReceiver finishedReceiver; BroadcastReceiver failedReciever; ProgressDialog progressDialog; @Override public void onClick(DialogInterface dialog, int which) { final String newFeed = editFeed.getText().toString(); // Get the feed's data // Set the broadcast reciever finishedReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { // Clean up progressDialog.dismiss(); unregisterReceiver(finishedReceiver); unregisterReceiver(failedReciever); // Refresh the list mShowID = intent.getLongExtra(RSSService.ID, -1); mShowName = intent.getStringExtra(RSSService.NAME); if(mShowID < 0) { finish(); return; } refreshList(); } }; registerReceiver(finishedReceiver, new IntentFilter(RSSService.RSSFINISH + newFeed)); // Set up the failed dialog failedReciever = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { progressDialog.dismiss(); Toast.makeText(EpisodesListActivity.this, "Failed to fetch feed", Toast.LENGTH_LONG).show(); unregisterReceiver(finishedReceiver); unregisterReceiver(failedReciever); finish(); } }; registerReceiver(failedReciever, new IntentFilter(RSSService.RSSFAILED + newFeed)); // Show a waiting dialog (that can be canceled) progressDialog = ProgressDialog.show(EpisodesListActivity.this, "", getString(R.string.getting_show_details)); progressDialog.setOnCancelListener( new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { try { unregisterReceiver(finishedReceiver); } catch (Exception e) { Log.w("EpisodesListActivity", "finishedReceiver already " + "unregistered"); } try { unregisterReceiver(failedReciever); } catch (Exception e) { Log.w("EpisodesListActivity", "failedReceiver already " + "unregistered"); } finish(); } }); progressDialog.setCancelable(true); progressDialog.show(); // Start the service Intent service = new Intent(); service.putExtra(RSSService.FEED, newFeed); service.putExtra(RSSService.BACKGROUND_UPDATE, false); service.setClass(EpisodesListActivity.this, RSSService.class); startService(service); } }); builder.setNegativeButton(getString(android.R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finish(); dialog.cancel(); } }); dialog = builder.create(); break; default: dialog = null; } return dialog; }
diff --git a/source/de/anomic/yacy/yacyRelease.java b/source/de/anomic/yacy/yacyRelease.java index fb5c4f5df..2bdb0f7d6 100644 --- a/source/de/anomic/yacy/yacyRelease.java +++ b/source/de/anomic/yacy/yacyRelease.java @@ -1,660 +1,661 @@ // yacyVersion.java // ---------------- // (C) 2007 by Michael Peter Christen; [email protected], Frankfurt a. M., Germany // first published 27.04.2007 on http://yacy.net // // This is a part of YaCy, a peer-to-peer based web search engine // // $LastChangedDate: 2009-04-17 16:52:42 +0200 (Fr, 17. Apr 2009) $ // $LastChangedRevision: 5828 $ // $LastChangedBy: f1ori $ // // LICENSE // // 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 package de.anomic.yacy; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.PublicKey; import java.security.SignatureException; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.SortedSet; import java.util.TreeSet; import net.yacy.document.parser.html.ContentScraper; import net.yacy.kelondro.data.meta.DigestURI; import net.yacy.kelondro.io.CharBuffer; import net.yacy.kelondro.logging.Log; import net.yacy.kelondro.order.Base64Order; import net.yacy.kelondro.util.FileUtils; import net.yacy.kelondro.util.OS; import net.yacy.repository.LoaderDispatcher; import de.anomic.crawler.CrawlProfile; import de.anomic.crawler.retrieval.HTTPLoader; import de.anomic.http.client.Client; import de.anomic.http.server.HeaderFramework; import de.anomic.http.server.RequestHeader; import de.anomic.http.server.ResponseContainer; import de.anomic.search.Switchboard; import de.anomic.server.serverCore; import de.anomic.tools.CryptoLib; import de.anomic.tools.SignatureOutputStream; import de.anomic.tools.tarTools; import de.anomic.yacy.yacyBuildProperties; public final class yacyRelease extends yacyVersion { // information about latest release, retrieved from download pages // this static information should be overwritten by network-specific locations // for details see defaults/yacy.network.freeworld.unit private static HashMap<yacyUpdateLocation, DevAndMainVersions> latestReleases = new HashMap<yacyUpdateLocation, DevAndMainVersions>(); public final static ArrayList<yacyUpdateLocation> latestReleaseLocations = new ArrayList<yacyUpdateLocation>(); // will be initialized with value in defaults/yacy.network.freeworld.unit private DigestURI url; private File releaseFile; private PublicKey publicKey; public yacyRelease(final DigestURI url) { super(url.getFileName()); this.url = url; } public yacyRelease(final DigestURI url, PublicKey publicKey) { this(url); this.publicKey = publicKey; } public yacyRelease(final File releaseFile) { super(releaseFile.getName()); this.releaseFile = releaseFile; } public DigestURI getUrl() { return url; } public static final yacyRelease rulebasedUpdateInfo(final boolean manual) { // according to update properties, decide if we should retrieve update information // if true, the release that can be obtained is returned. // if false, null is returned final Switchboard sb = Switchboard.getSwitchboard(); // check if release was installed by packagemanager if (yacyBuildProperties.isPkgManager()) { yacyCore.log.logInfo("rulebasedUpdateInfo: package manager is used for update"); return null; } // check if update process allows update retrieve final String process = sb.getConfig("update.process", "manual"); if ((!manual) && (!process.equals("auto"))) { yacyCore.log.logInfo("rulebasedUpdateInfo: not an automatic update selected"); return null; // no, its a manual or guided process } // check if the last retrieve time is a minimum time ago final long cycle = Math.max(1, sb.getConfigLong("update.cycle", 168)) * 60 * 60 * 1000; // update.cycle is hours final long timeLookup = sb.getConfigLong("update.time.lookup", System.currentTimeMillis()); if ((!manual) && (timeLookup + cycle > System.currentTimeMillis())) { yacyCore.log.logInfo("rulebasedUpdateInfo: too early for a lookup for a new release (timeLookup = " + timeLookup + ", cycle = " + cycle + ", now = " + System.currentTimeMillis() + ")"); return null; // no we have recently made a lookup } // check if we know that there is a release that is more recent than that which we are using final DevAndMainVersions releases = yacyRelease.allReleases(true, sb.getConfig("update.onlySignedFiles", "1").equals("1")); final yacyRelease latestmain = (releases.main.isEmpty()) ? null : releases.main.last(); final yacyRelease latestdev = (releases.dev.isEmpty()) ? null : releases.dev.last(); final String concept = sb.getConfig("update.concept", "any"); String blacklist = sb.getConfig("update.blacklist", "...[123]"); if (blacklist.equals("....[123]")) { // patch the blacklist because of a release strategy change from 0.7 and up blacklist = "...[123]"; sb.setConfig("update.blacklist", blacklist); } if ((manual) || (concept.equals("any"))) { // return a dev-release or a main-release if ((latestdev != null) && ((latestmain == null) || (latestdev.compareTo(latestmain) > 0)) && (!(Float.toString(latestdev.getReleaseNr()).matches(blacklist)))) { // consider a dev-release if (latestdev.compareTo(thisVersion()) <= 0) { yacyCore.log.logInfo( "rulebasedUpdateInfo: latest dev " + latestdev.getName() + " is not more recent than installed release " + thisVersion().getName()); return null; } return latestdev; } if (latestmain != null) { // consider a main release if ((Float.toString(latestmain.getReleaseNr()).matches(blacklist))) { yacyCore.log.logInfo( "rulebasedUpdateInfo: latest dev " + (latestdev == null ? "null" : latestdev.getName()) + " matches with blacklist '" + blacklist + "'"); return null; } if (latestmain.compareTo(thisVersion()) <= 0) { yacyCore.log.logInfo( "rulebasedUpdateInfo: latest main " + latestmain.getName() + " is not more recent than installed release (1) " + thisVersion().getName()); return null; } return latestmain; } } if ((concept.equals("main")) && (latestmain != null)) { // return a main-release if ((Float.toString(latestmain.getReleaseNr()).matches(blacklist))) { yacyCore.log.logInfo( "rulebasedUpdateInfo: latest main " + latestmain.getName() + " matches with blacklist'" + blacklist + "'"); return null; } if (latestmain.compareTo(thisVersion()) <= 0) { yacyCore.log.logInfo( "rulebasedUpdateInfo: latest main " + latestmain.getName() + " is not more recent than installed release (2) " + thisVersion().getName()); return null; } return latestmain; } yacyCore.log.logInfo("rulebasedUpdateInfo: failed to find more recent release"); return null; } public static DevAndMainVersions allReleases(final boolean force, final boolean onlySigned) { // join the release infos final TreeSet<yacyRelease> alldev = new TreeSet<yacyRelease>(); final TreeSet<yacyRelease> allmain = new TreeSet<yacyRelease>(); for (yacyUpdateLocation updateLocation : latestReleaseLocations) { if(!onlySigned || updateLocation.getPublicKey() != null) { DevAndMainVersions versions = getReleases(updateLocation, force); if ((versions != null) && (versions.dev != null)) alldev.addAll(versions.dev); if ((versions != null) && (versions.main != null)) allmain.addAll(versions.main); } } return new DevAndMainVersions(alldev, allmain); } /** * get all Releases from update location using cache * @param location Update location * @param force when true, don't fetch from cache * @return */ private static DevAndMainVersions getReleases(final yacyUpdateLocation location, final boolean force) { // get release info from a Internet resource DevAndMainVersions locLatestRelease = latestReleases.get(location); if (force || (locLatestRelease == null) /*|| ((latestRelease[0].isEmpty()) && (latestRelease[1].isEmpty()) && (latestRelease[2].isEmpty()) && (latestRelease[3].isEmpty()) )*/) { locLatestRelease = allReleaseFrom(location); latestReleases.put(location, locLatestRelease); } return locLatestRelease; } /** * get all releases from update location * @param location * @return */ private static DevAndMainVersions allReleaseFrom(yacyUpdateLocation location) { // retrieves the latest info about releases // this is done by contacting a release location, // parsing the content and filtering+parsing links // returns the version info if successful, null otherwise ContentScraper scraper; try { scraper = LoaderDispatcher.parseResource(Switchboard.getSwitchboard().loader, location.getLocationURL(), CrawlProfile.CACHE_STRATEGY_NOCACHE); } catch (final IOException e) { return null; } // analyse links in scraper resource, and find link to latest release in it final Map<DigestURI, String> anchors = scraper.getAnchors(); // a url (String) / name (String) relation final TreeSet<yacyRelease> mainReleases = new TreeSet<yacyRelease>(); final TreeSet<yacyRelease> devReleases = new TreeSet<yacyRelease>(); for(DigestURI url : anchors.keySet()) { try { yacyRelease release = new yacyRelease(url, location.getPublicKey()); //System.out.println("r " + release.toAnchor()); if(release.isMainRelease()) { mainReleases.add(release); } else { devReleases.add(release); } } catch (final RuntimeException e) { // the release string was not well-formed. // that might have been another link // just don't care continue; } } Switchboard.getSwitchboard().setConfig("update.time.lookup", System.currentTimeMillis()); return new DevAndMainVersions(devReleases, mainReleases); } public static final class DevAndMainVersions { public TreeSet<yacyRelease> dev, main; public DevAndMainVersions(final TreeSet<yacyRelease> dev, final TreeSet<yacyRelease> main) { this.dev = dev; this.main = main; } } /** * <p>download this release and if public key is know, download signature and check it. * <p>The signature is named $releaseurl.sig and contains the base64 encoded signature * (@see de.anomic.tools.CryptoLib) * @return file object of release file, null in case of failure */ public File downloadRelease() { final File storagePath = Switchboard.getSwitchboard().releasePath; File download = null; // setup httpClient final RequestHeader reqHeader = new RequestHeader(); reqHeader.put(HeaderFramework.USER_AGENT, HTTPLoader.yacyUserAgent); ResponseContainer res = null; final String name = this.getUrl().getFileName(); byte[] signatureBytes = null; // download signature first, if public key is available if (this.publicKey != null) { final byte[] signatureData = Client.wget(this.getUrl().toString() + ".sig", reqHeader, 6000); if (signatureData == null) { Log.logWarning("yacyVersion", "download of signature " + this.getUrl().toString() + " failed. ignoring signature file."); } else try { signatureBytes = Base64Order.standardCoder.decode(new String(signatureData, "UTF8").trim()); } catch (UnsupportedEncodingException e) { Log.logWarning("yacyVersion", "download of signature " + this.getUrl().toString() + " failed: unsupported encoding"); } // in case that the download of a signature file failed (can be caused by bad working http servers), then it is assumed that no signature exists } try { final Client client = new Client(120000, reqHeader); res = client.GET(this.getUrl().toString()); final boolean unzipped = res.getResponseHeader().gzip() && (res.getResponseHeader().mime().toLowerCase().equals("application/x-tar")); // if true, then the httpc has unzipped the file if ((unzipped) && (name.endsWith(".tar.gz"))) { download = new File(storagePath, name.substring(0, name.length() - 3)); } else { download = new File(storagePath, name); } if (this.publicKey != null && signatureBytes != null) { // copy to file and check signature SignatureOutputStream verifyOutput = null; try { verifyOutput = new SignatureOutputStream(new FileOutputStream(download), CryptoLib.signAlgorithm, publicKey); FileUtils.copyToStream(new BufferedInputStream(res.getDataAsStream()), new BufferedOutputStream(verifyOutput)); if (!verifyOutput.verify(signatureBytes)) throw new IOException("Bad Signature!"); } catch (NoSuchAlgorithmException e) { throw new IOException("No such algorithm"); } catch (SignatureException e) { throw new IOException("Signature exception"); } finally { if (verifyOutput != null) verifyOutput.close(); } // Save signature File signatureFile = new File(download.getAbsoluteFile() + ".sig"); FileUtils.copy(Base64Order.standardCoder.encode(signatureBytes).getBytes("UTF-8"), signatureFile); if ((!signatureFile.exists()) || (signatureFile.length() == 0)) throw new IOException("create signature file failed"); } else { // just copy into file FileUtils.copyToStream(new BufferedInputStream(res.getDataAsStream()), new BufferedOutputStream(new FileOutputStream(download))); } if ((!download.exists()) || (download.length() == 0)) throw new IOException("wget of url " + this.getUrl() + " failed"); } catch (final IOException e) { // Saving file failed, abort download if (res != null) res.abort(); Log.logSevere("yacyVersion", "download of " + this.getName() + " failed: " + e.getMessage()); if (download != null && download.exists()) { FileUtils.deletedelete(download); if (download.exists()) Log.logWarning("yacyVersion", "could not delete file "+ download); } download = null; } finally { if (res != null) { // release connection res.closeStream(); } } this.releaseFile = download; Switchboard.getSwitchboard().setConfig("update.time.download", System.currentTimeMillis()); return this.releaseFile; } public boolean checkSignature() { if(releaseFile != null) { try { CharBuffer signBuffer; signBuffer = new CharBuffer(getSignatureFile()); byte[] signByteBuffer = Base64Order.standardCoder.decode(signBuffer.toString().trim()); CryptoLib cl = new CryptoLib(); for(yacyUpdateLocation updateLocation : latestReleaseLocations) { try { if(cl.verifySignature(updateLocation.getPublicKey(), new FileInputStream(releaseFile), signByteBuffer)) { return true; } } catch (InvalidKeyException e) { } catch (SignatureException e) { } } } catch (IOException e1) { } catch (NoSuchAlgorithmException e) { } } return false; } /** * restart yacy by stopping yacy and previously running a batch * script, which waits until yacy is terminated and starts it again */ public static void restart() { final Switchboard sb = Switchboard.getSwitchboard(); final String apphome = sb.getRootPath().toString(); if (OS.isWindows) { final File startType = new File(sb.getRootPath(), "DATA/yacy.noconsole".replace("/", File.separator)); String starterFile = "startYACY_debug.bat"; if (startType.exists()) starterFile = "startYACY.bat"; // startType noconsole try{ Log.logInfo("RESTART", "INITIATED"); final String script = "@echo off" + serverCore.LF_STRING + "title YaCy restarter" + serverCore.LF_STRING + "set loading=YACY RESTARTER" + serverCore.LF_STRING + "echo %loading%" + serverCore.LF_STRING + "cd \"" + apphome + "/DATA/RELEASE/".replace("/", File.separator) + "\"" + serverCore.LF_STRING + ":WAIT" + serverCore.LF_STRING + "set loading=%loading%." + serverCore.LF_STRING + "cls" + serverCore.LF_STRING + "echo %loading%" + serverCore.LF_STRING + "ping -n 2 127.0.0.1 >nul" + serverCore.LF_STRING + "IF exist ..\\yacy.running goto WAIT" + serverCore.LF_STRING + "cd \"" + apphome + "\"" + serverCore.LF_STRING + "start /MIN CMD /C " + starterFile + serverCore.LF_STRING; final File scriptFile = new File(sb.getRootPath(), "DATA/RELEASE/restart.bat".replace("/", File.separator)); OS.deployScript(scriptFile, script); Log.logInfo("RESTART", "wrote restart-script to " + scriptFile.getAbsolutePath()); OS.execAsynchronous(scriptFile); Log.logInfo("RESTART", "script is running"); sb.terminate(5000, "windows restart"); } catch (final IOException e) { Log.logSevere("RESTART", "restart failed", e); } // create yacy.restart file which is used in Windows startscript /* final File yacyRestart = new File(sb.getRootPath(), "DATA/yacy.restart"); if (!yacyRestart.exists()) { try { yacyRestart.createNewFile(); plasmaSwitchboard.getSwitchboard().terminate(5000); } catch (IOException e) { serverLog.logSevere("SHUTDOWN", "restart failed", e); } }*/ } if (yacyBuildProperties.isPkgManager()) { // start a re-start daemon try { Log.logInfo("RESTART", "INITIATED"); final String script = "#!/bin/sh" + serverCore.LF_STRING + yacyBuildProperties.getRestartCmd() + " >/var/lib/yacy/RELEASE/log" + serverCore.LF_STRING; final File scriptFile = new File(sb.getRootPath(), "DATA/RELEASE/restart.sh"); OS.deployScript(scriptFile, script); Log.logInfo("RESTART", "wrote restart-script to " + scriptFile.getAbsolutePath()); OS.execAsynchronous(scriptFile); Log.logInfo("RESTART", "script is running"); } catch (final IOException e) { Log.logSevere("RESTART", "restart failed", e); } } else if (OS.canExecUnix) { // start a re-start daemon try { Log.logInfo("RESTART", "INITIATED"); final String script = "#!/bin/sh" + serverCore.LF_STRING + "cd " + sb.getRootPath() + "/DATA/RELEASE/" + serverCore.LF_STRING + "while [ -f ../yacy.running ]; do" + serverCore.LF_STRING + "sleep 1" + serverCore.LF_STRING + "done" + serverCore.LF_STRING + "cd ../../" + serverCore.LF_STRING + "nohup ./startYACY.sh > /dev/null" + serverCore.LF_STRING; final File scriptFile = new File(sb.getRootPath(), "DATA/RELEASE/restart.sh"); OS.deployScript(scriptFile, script); Log.logInfo("RESTART", "wrote restart-script to " + scriptFile.getAbsolutePath()); OS.execAsynchronous(scriptFile); Log.logInfo("RESTART", "script is running"); sb.terminate(5000, "unix restart"); } catch (final IOException e) { Log.logSevere("RESTART", "restart failed", e); } } } /** * stop yacy and run a batch script, applies a new release and restarts yacy * @param releaseFile */ public static void deployRelease(final File releaseFile) { if(yacyBuildProperties.isPkgManager()) { return; } //byte[] script = ("cd " + plasmaSwitchboard.getSwitchboard().getRootPath() + ";while [ -e ../yacy.running ]; do sleep 1;done;tar xfz " + release + ";cp -Rf yacy/* ../../;rm -Rf yacy;cd ../../;startYACY.sh").getBytes(); try { final Switchboard sb = Switchboard.getSwitchboard(); final String apphome = sb.getRootPath().toString(); Log.logInfo("UPDATE", "INITIATED"); try{ tarTools.unTar(tarTools.getInputStream(releaseFile), sb.getRootPath() + "/DATA/RELEASE/".replace("/", File.separator)); } catch (final Exception e){ Log.logSevere("UNTAR", "failed", e); } String script = null; String scriptFileName = null; if (OS.isWindows) { final File startType = new File(sb.getRootPath(), "DATA/yacy.noconsole".replace("/", File.separator)); String starterFile = "startYACY_debug.bat"; if (startType.exists()) starterFile = "startYACY.bat"; // startType noconsole script = "@echo off" + serverCore.LF_STRING + "title YaCy updater" + serverCore.LF_STRING + "set loading=YACY UPDATER" + serverCore.LF_STRING + "echo %loading%" + serverCore.LF_STRING + "cd \"" + apphome + "/DATA/RELEASE/".replace("/", File.separator) + "\"" + serverCore.LF_STRING + ":WAIT" + serverCore.LF_STRING + "set loading=%loading%." + serverCore.LF_STRING + "cls" + serverCore.LF_STRING + "echo %loading%" + serverCore.LF_STRING + "ping -n 2 127.0.0.1 >nul" + serverCore.LF_STRING + "IF exist ..\\yacy.running goto WAIT" + serverCore.LF_STRING + "IF not exist yacy goto NODATA" + serverCore.LF_STRING + "cd yacy" + serverCore.LF_STRING + "xcopy *.* \"" + apphome + "\" /E /Y >nul" + serverCore.LF_STRING + // /E - all subdirectories // /Y - don't ask "cd .." + serverCore.LF_STRING + "rd yacy /S /Q" + serverCore.LF_STRING + // /S delete tree // /Q don't ask "goto END" + serverCore.LF_STRING + ":NODATA" + serverCore.LF_STRING + "echo YACY UPDATER ERROR: NO UPDATE SOURCE FILES ON FILESYSTEM" + serverCore.LF_STRING + "pause" + serverCore.LF_STRING + ":END" + serverCore.LF_STRING + "cd \"" + apphome + "\"" + serverCore.LF_STRING + "start /MIN CMD /C " + starterFile + serverCore.LF_STRING; scriptFileName = "update.bat"; } else { // unix/linux script = "#!/bin/sh" + serverCore.LF_STRING + "cd " + sb.getRootPath() + "/DATA/RELEASE/" + serverCore.LF_STRING + /* ((releaseFile.getName().endsWith(".gz")) ? // test gz-file for integrity and tar xfz then ("if gunzip -t " + releaseFile.getAbsolutePath() + serverCore.LF_STRING + "then" + serverCore.LF_STRING + "gunzip -c " + releaseFile.getAbsolutePath() + " | tar xf -" + serverCore.LF_STRING) : // just tar xf the file, no integrity test possible? ("tar xf " + releaseFile.getAbsolutePath() + serverCore.LF_STRING) ) +*/ "while [ -f ../yacy.running ]; do" + serverCore.LF_STRING + "sleep 1" + serverCore.LF_STRING + "done" + serverCore.LF_STRING + + "rm " + apphome + "/lib/*" + serverCore.LF_STRING + "cp -Rf yacy/* " + apphome + serverCore.LF_STRING + "rm -Rf yacy" + serverCore.LF_STRING + /* ((releaseFile.getName().endsWith(".gz")) ? // else-case of gunzip -t test: if failed, just restart ("else" + serverCore.LF_STRING + "while [ -f ../yacy.running ]; do" + serverCore.LF_STRING + "sleep 1" + serverCore.LF_STRING + "done" + serverCore.LF_STRING + "fi" + serverCore.LF_STRING) : // in case that we did not made the integrity test, there is no else case "" ) +*/ "cd " + apphome + serverCore.LF_STRING + "nohup ./startYACY.sh > /dev/null" + serverCore.LF_STRING; scriptFileName = "update.sh"; } final File scriptFile = new File(sb.getRootPath(), "DATA/RELEASE/".replace("/", File.separator) + scriptFileName); OS.deployScript(scriptFile, script); Log.logInfo("UPDATE", "wrote update-script to " + scriptFile.getAbsolutePath()); OS.execAsynchronous(scriptFile); Log.logInfo("UPDATE", "script is running"); sb.setConfig("update.time.deploy", System.currentTimeMillis()); sb.terminate(5000, "auto-deploy for " + releaseFile.getName()); } catch (final IOException e) { Log.logSevere("UPDATE", "update failed", e); } } public static void main(final String[] args) { System.out.println(thisVersion()); final float base = (float) 0.53; final String blacklist = "....[123]"; String test; for (int i = 0; i < 20; i++) { test = Float.toString(base + (((float) i) / 1000)); System.out.println(test + " is " + ((test.matches(blacklist)) ? "blacklisted" : " not blacklisted")); } } /** * keep only releases of last month (minimum latest and 1 main (maybe the same)) * * @param filesPath where all downloaded files reside * @param deleteAfterDays */ public static void deleteOldDownloads(final File filesPath, final int deleteAfterDays) { // list downloaded releases yacyVersion release; final String[] downloaded = filesPath.list(); // parse all filenames and put them in a sorted set final SortedSet<yacyVersion> downloadedreleases = new TreeSet<yacyVersion>(); for (int j = 0; j < downloaded.length; j++) { try { release = new yacyVersion(downloaded[j]); downloadedreleases.add(release); } catch (final RuntimeException e) { // not a valid release } } // if we have some files if (!downloadedreleases.isEmpty()) { Log.logFine("STARTUP", "deleting downloaded releases older than "+ deleteAfterDays +" days"); // keep latest version final yacyVersion latest = downloadedreleases.last(); downloadedreleases.remove(latest); // if latest is a developer release, we also keep a main release final boolean keepMain = !latest.isMainRelease(); // remove old files final long now = System.currentTimeMillis(); final long deleteAfterMillis = deleteAfterDays * 24L * 60 * 60000; String lastMain = null; String filename; for (final yacyVersion aVersion : downloadedreleases) { filename = aVersion.getName(); if (keepMain && aVersion.isMainRelease()) { // keep this one, delete last remembered main release file if (lastMain != null) { filename = lastMain; } lastMain = aVersion.getName(); } // check file age final File downloadedFile = new File(filesPath + File.separator + filename); if (now - downloadedFile.lastModified() > deleteAfterMillis) { // delete file FileUtils.deletedelete(downloadedFile); if (downloadedFile.exists()) { Log.logWarning("STARTUP", "cannot delete old release " + downloadedFile.getAbsolutePath()); } } } } } public File getReleaseFile() { return releaseFile; } public File getSignatureFile() { return new File(releaseFile.getAbsoluteFile() + ".sig"); } public PublicKey getPublicKey() { return publicKey; } }
true
true
public static void deployRelease(final File releaseFile) { if(yacyBuildProperties.isPkgManager()) { return; } //byte[] script = ("cd " + plasmaSwitchboard.getSwitchboard().getRootPath() + ";while [ -e ../yacy.running ]; do sleep 1;done;tar xfz " + release + ";cp -Rf yacy/* ../../;rm -Rf yacy;cd ../../;startYACY.sh").getBytes(); try { final Switchboard sb = Switchboard.getSwitchboard(); final String apphome = sb.getRootPath().toString(); Log.logInfo("UPDATE", "INITIATED"); try{ tarTools.unTar(tarTools.getInputStream(releaseFile), sb.getRootPath() + "/DATA/RELEASE/".replace("/", File.separator)); } catch (final Exception e){ Log.logSevere("UNTAR", "failed", e); } String script = null; String scriptFileName = null; if (OS.isWindows) { final File startType = new File(sb.getRootPath(), "DATA/yacy.noconsole".replace("/", File.separator)); String starterFile = "startYACY_debug.bat"; if (startType.exists()) starterFile = "startYACY.bat"; // startType noconsole script = "@echo off" + serverCore.LF_STRING + "title YaCy updater" + serverCore.LF_STRING + "set loading=YACY UPDATER" + serverCore.LF_STRING + "echo %loading%" + serverCore.LF_STRING + "cd \"" + apphome + "/DATA/RELEASE/".replace("/", File.separator) + "\"" + serverCore.LF_STRING + ":WAIT" + serverCore.LF_STRING + "set loading=%loading%." + serverCore.LF_STRING + "cls" + serverCore.LF_STRING + "echo %loading%" + serverCore.LF_STRING + "ping -n 2 127.0.0.1 >nul" + serverCore.LF_STRING + "IF exist ..\\yacy.running goto WAIT" + serverCore.LF_STRING + "IF not exist yacy goto NODATA" + serverCore.LF_STRING + "cd yacy" + serverCore.LF_STRING + "xcopy *.* \"" + apphome + "\" /E /Y >nul" + serverCore.LF_STRING + // /E - all subdirectories // /Y - don't ask "cd .." + serverCore.LF_STRING + "rd yacy /S /Q" + serverCore.LF_STRING + // /S delete tree // /Q don't ask "goto END" + serverCore.LF_STRING + ":NODATA" + serverCore.LF_STRING + "echo YACY UPDATER ERROR: NO UPDATE SOURCE FILES ON FILESYSTEM" + serverCore.LF_STRING + "pause" + serverCore.LF_STRING + ":END" + serverCore.LF_STRING + "cd \"" + apphome + "\"" + serverCore.LF_STRING + "start /MIN CMD /C " + starterFile + serverCore.LF_STRING; scriptFileName = "update.bat"; } else { // unix/linux script = "#!/bin/sh" + serverCore.LF_STRING + "cd " + sb.getRootPath() + "/DATA/RELEASE/" + serverCore.LF_STRING + /* ((releaseFile.getName().endsWith(".gz")) ? // test gz-file for integrity and tar xfz then ("if gunzip -t " + releaseFile.getAbsolutePath() + serverCore.LF_STRING + "then" + serverCore.LF_STRING + "gunzip -c " + releaseFile.getAbsolutePath() + " | tar xf -" + serverCore.LF_STRING) : // just tar xf the file, no integrity test possible? ("tar xf " + releaseFile.getAbsolutePath() + serverCore.LF_STRING) ) +*/ "while [ -f ../yacy.running ]; do" + serverCore.LF_STRING + "sleep 1" + serverCore.LF_STRING + "done" + serverCore.LF_STRING + "cp -Rf yacy/* " + apphome + serverCore.LF_STRING + "rm -Rf yacy" + serverCore.LF_STRING + /* ((releaseFile.getName().endsWith(".gz")) ? // else-case of gunzip -t test: if failed, just restart ("else" + serverCore.LF_STRING + "while [ -f ../yacy.running ]; do" + serverCore.LF_STRING + "sleep 1" + serverCore.LF_STRING + "done" + serverCore.LF_STRING + "fi" + serverCore.LF_STRING) : // in case that we did not made the integrity test, there is no else case "" ) +*/ "cd " + apphome + serverCore.LF_STRING + "nohup ./startYACY.sh > /dev/null" + serverCore.LF_STRING; scriptFileName = "update.sh"; } final File scriptFile = new File(sb.getRootPath(), "DATA/RELEASE/".replace("/", File.separator) + scriptFileName); OS.deployScript(scriptFile, script); Log.logInfo("UPDATE", "wrote update-script to " + scriptFile.getAbsolutePath()); OS.execAsynchronous(scriptFile); Log.logInfo("UPDATE", "script is running"); sb.setConfig("update.time.deploy", System.currentTimeMillis()); sb.terminate(5000, "auto-deploy for " + releaseFile.getName()); } catch (final IOException e) { Log.logSevere("UPDATE", "update failed", e); } }
public static void deployRelease(final File releaseFile) { if(yacyBuildProperties.isPkgManager()) { return; } //byte[] script = ("cd " + plasmaSwitchboard.getSwitchboard().getRootPath() + ";while [ -e ../yacy.running ]; do sleep 1;done;tar xfz " + release + ";cp -Rf yacy/* ../../;rm -Rf yacy;cd ../../;startYACY.sh").getBytes(); try { final Switchboard sb = Switchboard.getSwitchboard(); final String apphome = sb.getRootPath().toString(); Log.logInfo("UPDATE", "INITIATED"); try{ tarTools.unTar(tarTools.getInputStream(releaseFile), sb.getRootPath() + "/DATA/RELEASE/".replace("/", File.separator)); } catch (final Exception e){ Log.logSevere("UNTAR", "failed", e); } String script = null; String scriptFileName = null; if (OS.isWindows) { final File startType = new File(sb.getRootPath(), "DATA/yacy.noconsole".replace("/", File.separator)); String starterFile = "startYACY_debug.bat"; if (startType.exists()) starterFile = "startYACY.bat"; // startType noconsole script = "@echo off" + serverCore.LF_STRING + "title YaCy updater" + serverCore.LF_STRING + "set loading=YACY UPDATER" + serverCore.LF_STRING + "echo %loading%" + serverCore.LF_STRING + "cd \"" + apphome + "/DATA/RELEASE/".replace("/", File.separator) + "\"" + serverCore.LF_STRING + ":WAIT" + serverCore.LF_STRING + "set loading=%loading%." + serverCore.LF_STRING + "cls" + serverCore.LF_STRING + "echo %loading%" + serverCore.LF_STRING + "ping -n 2 127.0.0.1 >nul" + serverCore.LF_STRING + "IF exist ..\\yacy.running goto WAIT" + serverCore.LF_STRING + "IF not exist yacy goto NODATA" + serverCore.LF_STRING + "cd yacy" + serverCore.LF_STRING + "xcopy *.* \"" + apphome + "\" /E /Y >nul" + serverCore.LF_STRING + // /E - all subdirectories // /Y - don't ask "cd .." + serverCore.LF_STRING + "rd yacy /S /Q" + serverCore.LF_STRING + // /S delete tree // /Q don't ask "goto END" + serverCore.LF_STRING + ":NODATA" + serverCore.LF_STRING + "echo YACY UPDATER ERROR: NO UPDATE SOURCE FILES ON FILESYSTEM" + serverCore.LF_STRING + "pause" + serverCore.LF_STRING + ":END" + serverCore.LF_STRING + "cd \"" + apphome + "\"" + serverCore.LF_STRING + "start /MIN CMD /C " + starterFile + serverCore.LF_STRING; scriptFileName = "update.bat"; } else { // unix/linux script = "#!/bin/sh" + serverCore.LF_STRING + "cd " + sb.getRootPath() + "/DATA/RELEASE/" + serverCore.LF_STRING + /* ((releaseFile.getName().endsWith(".gz")) ? // test gz-file for integrity and tar xfz then ("if gunzip -t " + releaseFile.getAbsolutePath() + serverCore.LF_STRING + "then" + serverCore.LF_STRING + "gunzip -c " + releaseFile.getAbsolutePath() + " | tar xf -" + serverCore.LF_STRING) : // just tar xf the file, no integrity test possible? ("tar xf " + releaseFile.getAbsolutePath() + serverCore.LF_STRING) ) +*/ "while [ -f ../yacy.running ]; do" + serverCore.LF_STRING + "sleep 1" + serverCore.LF_STRING + "done" + serverCore.LF_STRING + "rm " + apphome + "/lib/*" + serverCore.LF_STRING + "cp -Rf yacy/* " + apphome + serverCore.LF_STRING + "rm -Rf yacy" + serverCore.LF_STRING + /* ((releaseFile.getName().endsWith(".gz")) ? // else-case of gunzip -t test: if failed, just restart ("else" + serverCore.LF_STRING + "while [ -f ../yacy.running ]; do" + serverCore.LF_STRING + "sleep 1" + serverCore.LF_STRING + "done" + serverCore.LF_STRING + "fi" + serverCore.LF_STRING) : // in case that we did not made the integrity test, there is no else case "" ) +*/ "cd " + apphome + serverCore.LF_STRING + "nohup ./startYACY.sh > /dev/null" + serverCore.LF_STRING; scriptFileName = "update.sh"; } final File scriptFile = new File(sb.getRootPath(), "DATA/RELEASE/".replace("/", File.separator) + scriptFileName); OS.deployScript(scriptFile, script); Log.logInfo("UPDATE", "wrote update-script to " + scriptFile.getAbsolutePath()); OS.execAsynchronous(scriptFile); Log.logInfo("UPDATE", "script is running"); sb.setConfig("update.time.deploy", System.currentTimeMillis()); sb.terminate(5000, "auto-deploy for " + releaseFile.getName()); } catch (final IOException e) { Log.logSevere("UPDATE", "update failed", e); } }
diff --git a/jason/asSemantics/TransitionSystem.java b/jason/asSemantics/TransitionSystem.java index 7e8b98f..6ea8867 100644 --- a/jason/asSemantics/TransitionSystem.java +++ b/jason/asSemantics/TransitionSystem.java @@ -1,880 +1,885 @@ // ---------------------------------------------------------------------------- // Copyright (C) 2003 Rafael H. Bordini, Jomi F. Hubner, et al. // // 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 // // To contact the authors: // http://www.dur.ac.uk/r.bordini // http://www.inf.furb.br/~jomi // //---------------------------------------------------------------------------- package jason.asSemantics; import jason.JasonException; import jason.architecture.AgArch; import jason.asSyntax.Atom; import jason.asSyntax.BodyLiteral; import jason.asSyntax.DefaultTerm; import jason.asSyntax.Literal; import jason.asSyntax.LogicalFormula; import jason.asSyntax.Plan; import jason.asSyntax.PlanLibrary; import jason.asSyntax.Pred; import jason.asSyntax.Term; import jason.asSyntax.Trigger; import jason.asSyntax.BodyLiteral.BodyType; import jason.bb.BeliefBase; import jason.runtime.Settings; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; import java.util.logging.Level; import java.util.logging.Logger; public class TransitionSystem { public enum State { StartRC, SelEv, RelPl, ApplPl, SelAppl, AddIM, ProcAct, SelInt, ExecInt, ClrInt } private Logger logger = null; Agent ag = null; AgArch agArch = null; Circumstance C = null; Settings setts = null; // first step of the SOS private State step = State.StartRC; // number of reasoning cycles since last belief revision private int nrcslbr; // both configuration and configuration' point to this // object, this is just to make it look more like the SOS TransitionSystem confP; // both configuration and configuration' point to this // object, this is just to make it look more like the SOS TransitionSystem conf; public TransitionSystem(Agent a, Circumstance c, Settings s, AgArch ar) { ag = a; C = c; agArch = ar; if (s == null) { setts = new Settings(); } else { setts = s; } // we need to initialise this "aliases" conf = confP = this; nrcslbr = setts.nrcbp(); // to do BR to start with setLogger(agArch); if (setts != null) { logger.setLevel(setts.logLevel()); } } public void setLogger(AgArch arch) { if (arch != null) { logger = Logger.getLogger(TransitionSystem.class.getName() + "." + arch.getAgName()); } else { logger = Logger.getLogger(TransitionSystem.class.getName()); } } /** ******************************************************************* */ /* SEMANTIC RULES */ /** ******************************************************************* */ private void applySemanticRule() throws JasonException { // check the current step in the reasoning cycle // only the main parts of the interpretation appear here // the individual semantic rules appear below switch (step) { case StartRC: applyProcMsg(); break; case SelEv: applySelEv(); break; case RelPl: applyRelPl(); break; case ApplPl: applyApplPl(); break; case SelAppl: applySelAppl(); break; case AddIM: applyAddIM(); break; case ProcAct: applyProcAct(); break; case SelInt: applySelInt(); break; case ExecInt: applyExecInt(); break; case ClrInt: confP.step = State.StartRC; applyClrInt(conf.C.SI); break; } } // the semantic rules are referred to in comments in the functions below private void applyProcMsg() throws JasonException { if (!conf.C.MB.isEmpty()) { Message m = conf.ag.selectMessage(conf.C.MB); // get the content, it can be any term (literal, list, number, ...; see ask) Term content = DefaultTerm.parse(m.getPropCont().toString()); // check if an intention was suspended waiting this message Intention intention = null; if (m.getInReplyTo() != null) { intention = getC().getPendingIntentions().remove(m.getInReplyTo()); } // is it a pending intention? if (intention != null) { // unify the message answer with the .send fourth argument // the send that put the intention in Pending state was // something like // .send(ag1,askOne, value, X) // if the answer was 3, unifies X=3 BodyLiteral send = intention.peek().removeCurrentStep(); if (intention.peek().getUnif().unifies(send.getLiteralFormula().getTerm(3), content)) { getC().addIntention(intention); } else { conf.C.SI = intention; generateGoalDeletion(); } // the message is not an ask answer } else if (conf.ag.socAcc(m)) { // generate an event Literal received = new Literal("kqml_received"); received.addTerm(new Atom(m.getSender())); received.addTerm(new Atom(m.getIlForce())); received.addTerm(content); received.addTerm(new Atom(m.getMsgId())); updateEvents(new Event(new Trigger(Trigger.TEAdd, Trigger.TEAchvG, received), Intention.EmptyInt)); } } confP.step = State.SelEv; } private void applySelEv() throws JasonException { // Rule for atomic, if there is an atomic intention, do not select event if (C.hasAtomicIntention()) { confP.step = State.SelInt; return; } if (conf.C.hasEvent()) { // Rule for atomic, events from atomic intention has priority confP.C.SE = C.removeAtomicEvent(); if (confP.C.SE != null) { confP.step = State.RelPl; return; } // Rule SelEv1 confP.C.SE = conf.ag.selectEvent(confP.C.getEvents()); if (confP.C.SE != null) { confP.step = State.RelPl; return; } } // Rule SelEv2 // directly to ProcAct if no event to handle confP.step = State.ProcAct; } private void applyRelPl() throws JasonException { // get all relevant plans for the selected event if (conf.C.SE.trigger == null) { logger.log(Level.SEVERE, "Event " + C.SE + " has null as trigger! I should not get relevant plan!"); return; } confP.C.RP = relevantPlans(conf.C.SE.trigger); // Rule Rel1 if (!confP.C.RP.isEmpty() || setts.retrieve()) { // retrieve is mainly for Coo-AgentSpeak confP.step = State.ApplPl; } // Rule Rel2 else { if (conf.C.SE.trigger.isGoal()) { logger.warning("Found a goal for which there is no relevant plan:" + conf.C.SE); generateGoalDeletionFromEvent(); } // e.g. belief addition as internal event, just go ahead else if (conf.C.SE.isInternal()) { confP.C.SI = conf.C.SE.intention; updateIntention(); } // if external, then needs to check settings else if (setts.requeue()) { confP.C.addEvent(conf.C.SE); } confP.step = State.ProcAct; } } private void applyApplPl() throws JasonException { if (confP.C.RP == null) { logger.warning("applyPl was called even when RP is null!"); confP.step = State.ProcAct; return; } confP.C.AP = applicablePlans(confP.C.RP); // Rule Appl1 if (!confP.C.AP.isEmpty() || setts.retrieve()) { // retrieve is mainly for Coo-AgentSpeak confP.step = State.SelAppl; } else { // Rule Appl2 if (conf.C.SE.trigger.isGoal()) { // can't carry on, no applicable plan. logger.warning("Found a goal for which there is no applicable plan:\n" + conf.C.SE); generateGoalDeletionFromEvent(); } // e.g. belief addition as internal event, just go ahead // but note that the event was relevant, yet it is possible // the programmer just wanted to add the belief and it was // relevant by chance, so just carry on instead of dropping the // intention else if (conf.C.SE.isInternal()) { confP.C.SI = conf.C.SE.intention; updateIntention(); } // if external, then needs to check settings else if (setts.requeue()) { confP.C.addEvent(conf.C.SE); } confP.step = State.ProcAct; } } private void applySelAppl() throws JasonException { // Rule SelAppl confP.C.SO = conf.ag.selectOption(confP.C.AP); if (confP.C.SO != null) { confP.step = State.AddIM; if (logger.isLoggable(Level.FINE)) { logger.fine("Selected option "+confP.C.SO+" for event "+confP.C.SE); } } else { logger.warning("selectOption returned null."); generateGoalDeletionFromEvent(); // can't carry on, no applicable plan. confP.step = State.ProcAct; } } private void applyAddIM() throws JasonException { // create a new intended means IntendedMeans im = new IntendedMeans(conf.C.SO, (Trigger)conf.C.SE.getTrigger().clone()); // Rule ExtEv if (conf.C.SE.intention == Intention.EmptyInt) { Intention intention = new Intention(); intention.push(im); confP.C.addIntention(intention); } // Rule IntEv else { confP.C.SE.intention.push(im); confP.C.addIntention(confP.C.SE.intention); } confP.step = State.ProcAct; } private void applyProcAct() throws JasonException { if (conf.C.FA.isEmpty()) { confP.step = State.SelInt; } else { ActionExec a = conf.ag.selectAction(conf.C.FA); confP.C.SI = a.getIntention(); if (a.getResult()) { updateIntention(); } else { generateGoalDeletion(); } confP.step = State.ClrInt; } } private void applySelInt() throws JasonException { confP.step = State.ExecInt; // default next step // Rule for Atomic Intentions confP.C.SI = C.removeAtomicIntention(); if (confP.C.SI != null) { return; } // Rule SelInt1 if (conf.C.hasIntention()) { confP.C.SI = conf.ag.selectIntention(conf.C.getIntentions()); return; } confP.step = State.StartRC; } @SuppressWarnings("unchecked") private void applyExecInt() throws JasonException { confP.step = State.ClrInt; // default next stop if (conf.C.SI.isFinished()) { return; } // get next formula in the body of the intended means // on the top of the selected intention IntendedMeans im = conf.C.SI.peek(); if (im.isFinished()) { // for empty plans! may need unif, etc updateIntention(); return; } Unifier u = im.unif; BodyLiteral h = im.getCurrentStep(); Literal body = null; if (h.getType() != BodyType.constraint) { // constraint body is not a literal body = (Literal)h.getLiteralFormula().clone(); body.apply(u); } switch (h.getType()) { // Rule Action case action: confP.C.A = new ActionExec((Pred) body, conf.C.SI); break; case internalAction: boolean ok = false; try { InternalAction ia = ag.getIA(body); Object oresult = ia.execute(this, u, body.getTermsArray()); if (oresult != null) { ok = oresult instanceof Boolean && (Boolean)oresult; if (!ok && oresult instanceof Iterator) { // ia result is an Iterator Iterator<Unifier> iu = (Iterator<Unifier>)oresult; if (iu.hasNext()) { // change the unifier of the current IM to the first returned by the IA im.unif = iu.next(); ok = true; } } } if (ok && !ia.suspendIntention()) { updateIntention(); } } catch (Exception e) { logger.log(Level.SEVERE, "Error in IA ", e); ok = false; } if (!ok) { generateGoalDeletion(); } break; case constraint: Iterator<Unifier> iu = ((LogicalFormula)h.getLogicalFormula().clone()).logicalConsequence(ag, u); if (iu.hasNext()) { im.unif = iu.next(); updateIntention(); } else { generateGoalDeletion(); } break; // Rule Achieve case achieve: // free variables in an event cannot conflict with those in the plan body.makeVarsAnnon(); conf.C.addAchvGoal(body, conf.C.SI); break; // Rule Achieve as a New Focus case achieveNF: conf.C.addAchvGoal(body, Intention.EmptyInt); updateIntention(); break; // Rule Test case test: Literal lInBB = conf.ag.believes(body, u); if (lInBB != null) { updateIntention(); } else { body.makeVarsAnnon(); Trigger te = new Trigger(Trigger.TEAdd, Trigger.TETestG, body); if (ag.getPL().isRelevant(te.getPredicateIndicator())) { Event evt = new Event(te, conf.C.SI); logger.warning("Test Goal '" + h + "' failed as simple query. Generating internal event for it..."); conf.C.addEvent(evt); } else { generateGoalDeletion(); } } break; case delAddBel: // -+a(1,X) ===> remove a(_,_), add a(1,X) // change all vars to anon vars to remove it + if (!body.hasSource()) { + // do not add source(self) in case the + // programmer set the source + body.addAnnot(BeliefBase.TSelf); + } Literal bc = (Literal)body.clone(); bc.makeTermsAnnon(); // to delete, create events as external to avoid that // remove/add create two events for the same intention List<Literal>[] result = ag.brf(null, bc, conf.C.SI); // the intention is not the new focus - if (result != null) { // really add something + if (result != null) { // really delete something // generate events updateEvents(result,Intention.EmptyInt); } // add the belief, so no break; // Rule AddBel case addBel: if (!body.hasSource()) { // do not add source(self) in case the // programmer set the source body.addAnnot(BeliefBase.TSelf); } // calculate focus Intention newfocus = Intention.EmptyInt; if (setts.sameFocus()) { newfocus = conf.C.SI; } // call BRF result = ag.brf(body,null,conf.C.SI); // the intention is not the new focus if (result != null) { // really add something // generate events updateEvents(result,newfocus); if (!setts.sameFocus()) { updateIntention(); } } else { updateIntention(); } break; case delBel: if (!body.hasSource()) { // do not add source(self) in case the // programmer set the source body.addAnnot(BeliefBase.TSelf); } newfocus = Intention.EmptyInt; if (setts.sameFocus()) { newfocus = conf.C.SI; } // call BRF result = ag.brf(null,body, conf.C.SI); // the intention is not the new focus if (result != null) { // really change something // generate events updateEvents(result,newfocus); if (!setts.sameFocus()) { updateIntention(); } } else { updateIntention(); } break; } } public void applyClrInt(Intention i) throws JasonException { // Rule ClrInt if (i == null) { return; } if (i.isFinished()) { // intention finished, remove it confP.C.removeIntention(i); //conf.C.SI = null; return; } IntendedMeans im = i.peek(); if (!im.isFinished()) { // nothing todo return; } // remove the finished IM from the top of the intention IntendedMeans topIM = i.pop(); if (logger.isLoggable(Level.FINE)) logger.fine("Returning from IM "+topIM.getPlan().getLabel()); // if finished a failure handling IM ... if (im.getTrigger().isGoal() && !im.getTrigger().isAddition()) { // needs to get rid of the IM until a goal that // has failure handling. E.g, // -!b // +!c // +!d // +!b // +!s: !b; !z // should became // +!s: !z im = i.pop(); // +!c above, old while (!im.unif.unifies(topIM.getTrigger().getLiteral(), im.getTrigger().getLiteral())) { im = i.pop(); } } if (!i.isFinished()) { im = i.peek(); // +!s if (!im.isFinished()) { // removes !b BodyLiteral g = im.removeCurrentStep(); // make the TE of finished plan ground and unify that // with goal in the body Literal tel = topIM.getPlan().getTriggerEvent().getLiteral(); tel.apply(topIM.unif); im.unif.unifies(tel, g.getLiteralFormula()); } } // the new top may have become // empty! need to keep checking. applyClrInt(i); } /** ******************************************* */ /* auxiliary functions for the semantic rules */ /** ******************************************* */ public List<Option> relevantPlans(Trigger teP) throws JasonException { Trigger te = (Trigger) teP.clone(); List<Option> rp = new LinkedList<Option>(); List<Plan> candidateRPs = conf.ag.fPL.getAllRelevant(te.getPredicateIndicator()); if (candidateRPs == null) return rp; for (Plan pl : candidateRPs) { Unifier relUn = pl.relevant(te); if (relUn != null) { rp.add(new Option(pl, relUn)); } } return rp; } public List<Option> applicablePlans(List<Option> rp) throws JasonException { List<Option> ap = new LinkedList<Option>(); for (Option opt: rp) { LogicalFormula context = opt.plan.getContext(); if (context == null) { // context is true ap.add(opt); } else { boolean allUnifs = opt.getPlan().isAllUnifs(); Iterator<Unifier> r = context.logicalConsequence(ag, opt.unif); if (r != null) { while (r.hasNext()) { opt.unif = r.next(); ap.add(opt); if (!allUnifs) break; // returns only one unification if (r.hasNext()) { // create a new option opt = new Option((Plan)opt.plan.clone(), null); } } } } } return ap; } public void updateEvents(List<Literal>[] result, Intention focus) { if (result == null) return; // create the events for (Literal ladd: result[0]) { Trigger te = new Trigger(Trigger.TEAdd, Trigger.TEBel, ladd); updateEvents(new Event(te, focus)); } for (Literal lrem: result[1]) { Trigger te = new Trigger(Trigger.TEDel, Trigger.TEBel, lrem); updateEvents(new Event(te, focus)); } } // only add External Event if it is relevant in respect to the PlanLibrary public void updateEvents(Event e) { if (e.isInternal() || C.hasListener() || ag.getPL().isRelevant(e.trigger.getPredicateIndicator())) { C.addEvent(e); if (logger.isLoggable(Level.FINE)) logger.fine("Added event " + e); } } /** remove the top action and requeue the current intention */ private void updateIntention() { IntendedMeans im = conf.C.SI.peek(); if (!im.getPlan().getBody().isEmpty()) { // maybe it had an empty plan body im.getPlan().getBody().remove(0); } confP.C.addIntention(conf.C.SI); } private void generateGoalDeletion() throws JasonException { IntendedMeans im = conf.C.SI.peek(); if (im.isGoalAdd()) { Event failEvent = findEventForFailure(conf.C.SI, im.getTrigger()); if (failEvent != null) { confP.C.addEvent(failEvent); logger.warning("Generating goal deletion " + failEvent.getTrigger() + " from goal: " + im.getTrigger()); } else { logger.warning("No fail event was generated for " + im.getTrigger()); } } // if "discard" is set, we are deleting the whole intention! // it is simply not going back to 'I' nor anywhere else! else if (setts.requeue()) { // get the external event (or the one that started // the whole focus of attention) and requeue it im = conf.C.SI.get(0); confP.C.addExternalEv(im.getTrigger()); } else { logger.warning("Could not finish intention: " + conf.C.SI); } } // similar to the one above, but for an Event rather than intention private void generateGoalDeletionFromEvent() throws JasonException { Event ev = conf.C.SE; Trigger tevent = ev.trigger; if (tevent.isAddition() && tevent.isGoal() && ev.isInternal()) { Event failEvent = findEventForFailure(ev.intention, tevent); if (failEvent != null) { logger.warning("Generating goal deletion " + failEvent.getTrigger() + " from event: " + ev.getTrigger()); confP.C.addEvent(failEvent); } else { logger.warning("No fail event was generated for " + ev.getTrigger()); } } else if (ev.isInternal()) { logger.warning("Could not finish intention:\n" + ev.intention); } // if "discard" is set, we are deleting the whole intention! // it is simply not going back to I nor anywhere else! else if (setts.requeue()) { confP.C.addEvent(ev); logger.warning("Requeing external event: " + ev); } else logger.warning("Discarding external event: " + ev); } public Event findEventForFailure(Intention i, Trigger tevent) { Trigger failTrigger = new Trigger(Trigger.TEDel, tevent.getGoal(), tevent.getLiteral()); ListIterator<IntendedMeans> ii = i.iterator(); while (!getAg().getPL().isRelevant(failTrigger.getPredicateIndicator()) && ii.hasPrevious()) { IntendedMeans im = ii.previous(); tevent = im.getTrigger(); failTrigger = new Trigger(Trigger.TEDel, tevent.getGoal(), tevent.getLiteral()); } // if some failure handling plan is found if (tevent.isGoal() && getAg().getPL().isRelevant(failTrigger.getPredicateIndicator())) { return new Event(failTrigger, i); } return null; } /** ********************************************************************* */ boolean canSleep() { return !conf.C.hasEvent() && !conf.C.hasIntention() && conf.C.MB.isEmpty() && conf.C.FA.isEmpty() && agArch.canSleep(); } /** waits for a new message */ synchronized private void waitMessage() { try { logger.fine("Waiting message...."); wait(500); // wait for messages } catch (Exception e) { e.printStackTrace(); } } synchronized public void newMessageHasArrived() { notifyAll(); // notify waitMessage method } private Object syncMonitor = new Object(); private boolean inWaitSyncMonitor = false; /** * waits for a signal to continue the execution (used in synchronized * execution mode) */ private void waitSyncSignal() { try { synchronized (syncMonitor) { inWaitSyncMonitor = true; syncMonitor.wait(); inWaitSyncMonitor = false; } } catch (Exception e) { e.printStackTrace(); } } /** * inform this agent that it can continue, if it is in sync mode and * wainting a signal */ public void receiveSyncSignal() { try { synchronized (syncMonitor) { while (!inWaitSyncMonitor) { // waits the agent to enter in waitSyncSignal syncMonitor.wait(50); if (!agArch.isRunning()) { break; } } syncMonitor.notifyAll(); } } catch (Exception e) { e.printStackTrace(); } } /** ******************************************************************* */ /* MAIN LOOP */ /** ******************************************************************* */ /* infinite loop on one reasoning cycle */ /* plus the other parts of the agent architecture besides */ /* the actual transition system of the AS interpreter */ /** ******************************************************************* */ public void reasoningCycle() { try { if (setts.isSync()) { waitSyncSignal(); } else if (canSleep()) { if (getAg().fPL.getIdlePlans() != null) { logger.fine("generating idle event"); C.addExternalEv(PlanLibrary.TE_IDLE); } else { if (nrcslbr <= 1) { waitMessage(); } } } C.reset(); if (nrcslbr >= setts.nrcbp() || canSleep()) { nrcslbr = 0; // logger.fine("perceiving..."); List<Literal> percept = agArch.perceive(); // logger.fine("doing belief revision..."); ag.buf(percept); // logger.fine("checking mail..."); agArch.checkMail(); } do { applySemanticRule(); } while (step != State.StartRC); // finished a reasoning cycle if (C.getAction() != null) { agArch.act(C.getAction(), C.getFeedbackActions()); } // counting number of cycles since last belief revision nrcslbr++; if (setts.isSync()) { boolean isBreakPoint = false; try { isBreakPoint = getC().getSelectedOption().getPlan().hasBreakpoint(); if (logger.isLoggable(Level.FINE)) { logger.fine("Informing controller that I finished a reasoning cycle. Breakpoint is " + isBreakPoint); } } catch (NullPointerException e) { // no problem, the is no sel opt, no plan .... } agArch.getArchInfraTier().informCycleFinished(isBreakPoint, agArch.getCycleNumber()); } } catch (Exception e) { logger.log(Level.SEVERE, "*** ERROR in the transition system.", e); } } // Auxiliary functions // (for Internal Actions to be able to access the configuration) public Agent getAg() { return ag; } public Circumstance getC() { return C; } public State getStep() { return step; } public Settings getSettings() { return setts; } public AgArch getUserAgArch() { return agArch; } public Logger getLogger() { return logger; } }
false
true
private void applyExecInt() throws JasonException { confP.step = State.ClrInt; // default next stop if (conf.C.SI.isFinished()) { return; } // get next formula in the body of the intended means // on the top of the selected intention IntendedMeans im = conf.C.SI.peek(); if (im.isFinished()) { // for empty plans! may need unif, etc updateIntention(); return; } Unifier u = im.unif; BodyLiteral h = im.getCurrentStep(); Literal body = null; if (h.getType() != BodyType.constraint) { // constraint body is not a literal body = (Literal)h.getLiteralFormula().clone(); body.apply(u); } switch (h.getType()) { // Rule Action case action: confP.C.A = new ActionExec((Pred) body, conf.C.SI); break; case internalAction: boolean ok = false; try { InternalAction ia = ag.getIA(body); Object oresult = ia.execute(this, u, body.getTermsArray()); if (oresult != null) { ok = oresult instanceof Boolean && (Boolean)oresult; if (!ok && oresult instanceof Iterator) { // ia result is an Iterator Iterator<Unifier> iu = (Iterator<Unifier>)oresult; if (iu.hasNext()) { // change the unifier of the current IM to the first returned by the IA im.unif = iu.next(); ok = true; } } } if (ok && !ia.suspendIntention()) { updateIntention(); } } catch (Exception e) { logger.log(Level.SEVERE, "Error in IA ", e); ok = false; } if (!ok) { generateGoalDeletion(); } break; case constraint: Iterator<Unifier> iu = ((LogicalFormula)h.getLogicalFormula().clone()).logicalConsequence(ag, u); if (iu.hasNext()) { im.unif = iu.next(); updateIntention(); } else { generateGoalDeletion(); } break; // Rule Achieve case achieve: // free variables in an event cannot conflict with those in the plan body.makeVarsAnnon(); conf.C.addAchvGoal(body, conf.C.SI); break; // Rule Achieve as a New Focus case achieveNF: conf.C.addAchvGoal(body, Intention.EmptyInt); updateIntention(); break; // Rule Test case test: Literal lInBB = conf.ag.believes(body, u); if (lInBB != null) { updateIntention(); } else { body.makeVarsAnnon(); Trigger te = new Trigger(Trigger.TEAdd, Trigger.TETestG, body); if (ag.getPL().isRelevant(te.getPredicateIndicator())) { Event evt = new Event(te, conf.C.SI); logger.warning("Test Goal '" + h + "' failed as simple query. Generating internal event for it..."); conf.C.addEvent(evt); } else { generateGoalDeletion(); } } break; case delAddBel: // -+a(1,X) ===> remove a(_,_), add a(1,X) // change all vars to anon vars to remove it Literal bc = (Literal)body.clone(); bc.makeTermsAnnon(); // to delete, create events as external to avoid that // remove/add create two events for the same intention List<Literal>[] result = ag.brf(null, bc, conf.C.SI); // the intention is not the new focus if (result != null) { // really add something // generate events updateEvents(result,Intention.EmptyInt); } // add the belief, so no break; // Rule AddBel case addBel: if (!body.hasSource()) { // do not add source(self) in case the // programmer set the source body.addAnnot(BeliefBase.TSelf); } // calculate focus Intention newfocus = Intention.EmptyInt; if (setts.sameFocus()) { newfocus = conf.C.SI; } // call BRF result = ag.brf(body,null,conf.C.SI); // the intention is not the new focus if (result != null) { // really add something // generate events updateEvents(result,newfocus); if (!setts.sameFocus()) { updateIntention(); } } else { updateIntention(); } break; case delBel: if (!body.hasSource()) { // do not add source(self) in case the // programmer set the source body.addAnnot(BeliefBase.TSelf); } newfocus = Intention.EmptyInt; if (setts.sameFocus()) { newfocus = conf.C.SI; } // call BRF result = ag.brf(null,body, conf.C.SI); // the intention is not the new focus if (result != null) { // really change something // generate events updateEvents(result,newfocus); if (!setts.sameFocus()) { updateIntention(); } } else { updateIntention(); } break; } }
private void applyExecInt() throws JasonException { confP.step = State.ClrInt; // default next stop if (conf.C.SI.isFinished()) { return; } // get next formula in the body of the intended means // on the top of the selected intention IntendedMeans im = conf.C.SI.peek(); if (im.isFinished()) { // for empty plans! may need unif, etc updateIntention(); return; } Unifier u = im.unif; BodyLiteral h = im.getCurrentStep(); Literal body = null; if (h.getType() != BodyType.constraint) { // constraint body is not a literal body = (Literal)h.getLiteralFormula().clone(); body.apply(u); } switch (h.getType()) { // Rule Action case action: confP.C.A = new ActionExec((Pred) body, conf.C.SI); break; case internalAction: boolean ok = false; try { InternalAction ia = ag.getIA(body); Object oresult = ia.execute(this, u, body.getTermsArray()); if (oresult != null) { ok = oresult instanceof Boolean && (Boolean)oresult; if (!ok && oresult instanceof Iterator) { // ia result is an Iterator Iterator<Unifier> iu = (Iterator<Unifier>)oresult; if (iu.hasNext()) { // change the unifier of the current IM to the first returned by the IA im.unif = iu.next(); ok = true; } } } if (ok && !ia.suspendIntention()) { updateIntention(); } } catch (Exception e) { logger.log(Level.SEVERE, "Error in IA ", e); ok = false; } if (!ok) { generateGoalDeletion(); } break; case constraint: Iterator<Unifier> iu = ((LogicalFormula)h.getLogicalFormula().clone()).logicalConsequence(ag, u); if (iu.hasNext()) { im.unif = iu.next(); updateIntention(); } else { generateGoalDeletion(); } break; // Rule Achieve case achieve: // free variables in an event cannot conflict with those in the plan body.makeVarsAnnon(); conf.C.addAchvGoal(body, conf.C.SI); break; // Rule Achieve as a New Focus case achieveNF: conf.C.addAchvGoal(body, Intention.EmptyInt); updateIntention(); break; // Rule Test case test: Literal lInBB = conf.ag.believes(body, u); if (lInBB != null) { updateIntention(); } else { body.makeVarsAnnon(); Trigger te = new Trigger(Trigger.TEAdd, Trigger.TETestG, body); if (ag.getPL().isRelevant(te.getPredicateIndicator())) { Event evt = new Event(te, conf.C.SI); logger.warning("Test Goal '" + h + "' failed as simple query. Generating internal event for it..."); conf.C.addEvent(evt); } else { generateGoalDeletion(); } } break; case delAddBel: // -+a(1,X) ===> remove a(_,_), add a(1,X) // change all vars to anon vars to remove it if (!body.hasSource()) { // do not add source(self) in case the // programmer set the source body.addAnnot(BeliefBase.TSelf); } Literal bc = (Literal)body.clone(); bc.makeTermsAnnon(); // to delete, create events as external to avoid that // remove/add create two events for the same intention List<Literal>[] result = ag.brf(null, bc, conf.C.SI); // the intention is not the new focus if (result != null) { // really delete something // generate events updateEvents(result,Intention.EmptyInt); } // add the belief, so no break; // Rule AddBel case addBel: if (!body.hasSource()) { // do not add source(self) in case the // programmer set the source body.addAnnot(BeliefBase.TSelf); } // calculate focus Intention newfocus = Intention.EmptyInt; if (setts.sameFocus()) { newfocus = conf.C.SI; } // call BRF result = ag.brf(body,null,conf.C.SI); // the intention is not the new focus if (result != null) { // really add something // generate events updateEvents(result,newfocus); if (!setts.sameFocus()) { updateIntention(); } } else { updateIntention(); } break; case delBel: if (!body.hasSource()) { // do not add source(self) in case the // programmer set the source body.addAnnot(BeliefBase.TSelf); } newfocus = Intention.EmptyInt; if (setts.sameFocus()) { newfocus = conf.C.SI; } // call BRF result = ag.brf(null,body, conf.C.SI); // the intention is not the new focus if (result != null) { // really change something // generate events updateEvents(result,newfocus); if (!setts.sameFocus()) { updateIntention(); } } else { updateIntention(); } break; } }
diff --git a/srcj/com/sun/electric/tool/user/menus/WindowMenu.java b/srcj/com/sun/electric/tool/user/menus/WindowMenu.java index 3d1b322f2..53377e744 100644 --- a/srcj/com/sun/electric/tool/user/menus/WindowMenu.java +++ b/srcj/com/sun/electric/tool/user/menus/WindowMenu.java @@ -1,898 +1,898 @@ /* -*- tab-width: 4 -*- * * Electric(tm) VLSI Design System * * File: WindowMenu.java * * Copyright (c) 2003 Sun Microsystems and Static Free Software * * Electric(tm) 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. * * Electric(tm) 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 Electric(tm); see the file COPYING. If not, write to * the Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, Mass 02111-1307, USA. */ package com.sun.electric.tool.user.menus; import static com.sun.electric.tool.user.menus.EMenuItem.SEPARATOR; import com.sun.electric.database.text.TextUtils; import com.sun.electric.database.text.Pref; import com.sun.electric.technology.technologies.Generic; import com.sun.electric.tool.user.MessagesStream; import com.sun.electric.tool.user.User; import com.sun.electric.tool.user.Resources; import com.sun.electric.tool.user.dialogs.SetFocus; import com.sun.electric.tool.user.dialogs.OpenFile; import com.sun.electric.tool.user.ui.ClickZoomWireListener; import com.sun.electric.tool.user.ui.EditWindow; import com.sun.electric.tool.user.ui.EditWindowFocusBrowser; import com.sun.electric.tool.user.ui.MessagesWindow; import com.sun.electric.tool.user.ui.TopLevel; import com.sun.electric.tool.user.ui.WindowContent; import com.sun.electric.tool.user.ui.WindowFrame; import com.sun.electric.tool.user.ui.ZoomAndPanListener; import com.sun.electric.tool.user.waveform.WaveformWindow; import com.sun.electric.tool.Job; import com.sun.electric.tool.JobException; import com.sun.electric.tool.io.FileType; import java.awt.Color; import java.awt.Dimension; import java.awt.GraphicsConfiguration; import java.awt.GraphicsDevice; import java.awt.GraphicsEnvironment; import java.awt.Point; import java.awt.Rectangle; import java.awt.Toolkit; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.util.ArrayList; import java.util.Collections; import java.util.EventListener; import java.util.Iterator; import java.util.List; import java.net.URL; import javax.swing.KeyStroke; /** * Class to handle the commands in the "Window" pulldown menu. */ public class WindowMenu { public static KeyStroke getCloseWindowAccelerator() { return EMenuItem.shortcut(KeyEvent.VK_W); } private static EMenu thisWindowMenu = null; private static EMenuItem hiddenWindowCycleMenuItem = null; static EMenu makeMenu() { /****************************** THE WINDOW MENU ******************************/ // bindings for numpad keys. Need extra one because over VNC, they get sent as shift+KP_* int ctrlshift = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask() | InputEvent.SHIFT_MASK; KeyStroke [] numpad4 = new KeyStroke [] { EMenuItem.shortcut('4'), EMenuItem.shortcut(KeyEvent.VK_NUMPAD4), KeyStroke.getKeyStroke(KeyEvent.VK_KP_LEFT, ctrlshift)}; KeyStroke [] numpad6 = new KeyStroke [] { EMenuItem.shortcut('6'), EMenuItem.shortcut(KeyEvent.VK_NUMPAD6), KeyStroke.getKeyStroke(KeyEvent.VK_KP_RIGHT, ctrlshift)}; KeyStroke [] numpad8 = new KeyStroke [] { EMenuItem.shortcut('8'), EMenuItem.shortcut(KeyEvent.VK_NUMPAD8), KeyStroke.getKeyStroke(KeyEvent.VK_KP_UP, ctrlshift)}; KeyStroke [] numpad2 = new KeyStroke [] { EMenuItem.shortcut('2'), EMenuItem.shortcut(KeyEvent.VK_NUMPAD2), KeyStroke.getKeyStroke(KeyEvent.VK_KP_DOWN, ctrlshift)}; KeyStroke [] numpad9 = new KeyStroke [] { EMenuItem.shortcut('9'), EMenuItem.shortcut(KeyEvent.VK_NUMPAD9), KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, ctrlshift)}; KeyStroke [] numpad7 = new KeyStroke [] { EMenuItem.shortcut('7'), EMenuItem.shortcut(KeyEvent.VK_NUMPAD7), KeyStroke.getKeyStroke(KeyEvent.VK_HOME, ctrlshift)}; KeyStroke [] numpad0 = new KeyStroke [] { EMenuItem.shortcut('0'), EMenuItem.shortcut(KeyEvent.VK_NUMPAD0), KeyStroke.getKeyStroke(KeyEvent.VK_INSERT, ctrlshift)}; KeyStroke [] numpad5 = new KeyStroke [] { EMenuItem.shortcut('5'), EMenuItem.shortcut(KeyEvent.VK_NUMPAD5), KeyStroke.getKeyStroke(KeyEvent.VK_BEGIN, ctrlshift)}; // mnemonic keys available: A K Q T Y EMenu menu = new EMenu("_Window", new EMenuItem("_Fill Window", numpad9) { public void run() { fullDisplay(); }}, new EMenuItem("Redisplay _Window") { public void run() { ZoomAndPanListener.redrawDisplay(); }}, new EMenuItem("Zoom _Out", numpad0) { public void run() { zoomOutDisplay(); }}, new EMenuItem("Zoom _In", numpad7) { public void run() { zoomInDisplay(); }}, // mnemonic keys available: ABCDEF IJKLMNOPQRSTUV XY new EMenu("Special _Zoom", new EMenuItem("Focus on _Highlighted", 'F') { public void run() { focusOnHighlighted(); }}, new EMenuItem("_Zoom Box") { public void run() { zoomBoxCommand(); }}, new EMenuItem("Make _Grid Just Visible") { public void run() { makeGridJustVisibleCommand(); }}, new EMenuItem("Match Other _Window") { public void run() { matchOtherWindowCommand(0); }}), SEPARATOR, new EMenuItem("Pan _Left", numpad4) { public void run() { ZoomAndPanListener.panXOrY(0, WindowFrame.getCurrentWindowFrame(), 1); }}, new EMenuItem("Pan _Right", numpad6) { public void run() { ZoomAndPanListener.panXOrY(0, WindowFrame.getCurrentWindowFrame(), -1); }}, new EMenuItem("Pan _Up", numpad8) { public void run() { ZoomAndPanListener.panXOrY(1, WindowFrame.getCurrentWindowFrame(), -1); }}, new EMenuItem("Pan _Down", numpad2) { public void run() { ZoomAndPanListener.panXOrY(1, WindowFrame.getCurrentWindowFrame(), 1); }}, // mnemonic keys available: B DEFGHIJKLMNOPQR TUVW Z new EMenu("Special _Pan", new EMenuItem("Center _Selection") { public void run() { ZoomAndPanListener.centerSelection(); }}, new EMenuItem("Center _Cursor", numpad5) { public void run() { ZoomAndPanListener.centerCursor(); }}, new EMenuItem("Match Other Window in _X") { public void run() { matchOtherWindowCommand(1); }}, new EMenuItem("Match Other Window in _Y") { public void run() { matchOtherWindowCommand(2); }}, new EMenuItem("Match Other Window in X, Y, _and Scale") { public void run() { matchOtherWindowCommand(3); }}), // new EMenuItem("Saved Views...") { public void run() { // SavedViews.showSavedViewsDialog(); }}, new EMenuItem("Go To Pre_vious Focus") { public void run() { goToPreviousSavedFocus(); }}, new EMenuItem("Go To Ne_xt Focus") { public void run() { goToNextSavedFocus(); }}, new EMenuItem("_Set Focus...") { public void run() { SetFocus.showSetFocusDialog(); }}, SEPARATOR, new EMenuItem("Toggle _Grid", 'G') { public void run() { toggleGridCommand(); }}, SEPARATOR, // mnemonic keys available: AB DEFG IJKLMNOPQRSTU WXYZ new EMenu("Ad_just Position", new EMenuItem("Tile _Horizontally") { public void run() { tileHorizontallyCommand(); }}, new EMenuItem("Tile _Vertically", KeyStroke.getKeyStroke(KeyEvent.VK_F9, 0)) { public void run() { tileVerticallyCommand(); }}, new EMenuItem("_Cascade") { public void run() { cascadeWindowsCommand(); }}), new EMenuItem("Clos_e Window", getCloseWindowAccelerator()) { public void run() { closeWindowCommand(); }}, // new EMenuItem("Select Next Window") { public void run() { // nextWindowCommand(); }}, !TopLevel.isMDIMode() ? SEPARATOR : null, !TopLevel.isMDIMode() && getAllGraphicsDevices().length >= 2 ? new EMenuItem("Move to Ot_her Display") { public void run() { moveToOtherDisplayCommand(); }} : null, !TopLevel.isMDIMode() ? new EMenuItem("Remember Locatio_n of Display") { public void run() { rememberDisplayLocation(); }} : null, SEPARATOR, - // mnemonic keys available: A CDEFGHIJKLMNOPQ STUV XYZ + // mnemonic keys available: A DEFGHIJKLMNOPQ STUV XYZ new EMenu("_Color Schemes", new EMenuItem("_Restore Default Colors") { public void run() { defaultBackgroundCommand(); }}, new EMenuItem("_Black Background Colors") { public void run() { blackBackgroundCommand(); }}, new EMenuItem("_White Background Colors") { public void run() { whiteBackgroundCommand(); }}, - new EMenuItem("Cadence Colors") { public void run() { + new EMenuItem("_Cadence Colors and Keystrokes") { public void run() { importCadencePreferences(); }} ), // mnemonic keys available: ABC FGHIJKLMNOPQ TUVWXYZ new EMenu("W_aveform Window", new EMenuItem("_Save Waveform Window Configuration to Disk...") { public void run() { WaveformWindow.saveConfiguration(); }}, new EMenuItem("_Restore Waveform Window Configuration from Disk...") { public void run() { WaveformWindow.restoreConfiguration(); }}, SEPARATOR, new EMenuItem("Refresh Simulation _Data") { public void run() { WaveformWindow.refreshSimulationData(); }}, SEPARATOR, new EMenuItem("_Export Simulation Data...") { public void run() { WaveformWindow.exportSimulationData(); }} ), // mnemonic keys available: AB DE GHIJKLMNOPQR TUVWXYZ new EMenu("_Messages Window", new EMenuItem("_Save Messages...") { public void run() { MessagesStream.getMessagesStream().save(); }}, new EMenuItem("_Clear") { public void run() { TopLevel.getMessagesWindow().clear(); }}, new EMenuItem("Set F_ont...") { public void run() { TopLevel.getMessagesWindow().selectFont(); }}), MenuCommands.makeExtraMenu("j3d.ui.J3DMenu"), // mnemonic keys available: ABCDEFGHIJK MNOPQ STUVWXYZ new EMenu("Side _Bar", new EMenuItem("On _Left") { public void run() { WindowFrame.setSideBarLocation(true); }}, new EMenuItem("On _Right") { public void run() { WindowFrame.setSideBarLocation(false); }}), SEPARATOR ); thisWindowMenu = menu; return menu; } static EMenuItem getHiddenWindowCycleMenuItem() { if (hiddenWindowCycleMenuItem == null) { hiddenWindowCycleMenuItem = new EMenuItem("Window Cycle", KeyStroke.getKeyStroke('Q', 0)) { public void run() { WindowFrame.getWindows().next().requestFocus(); }}; } return hiddenWindowCycleMenuItem; } private static DynamicEMenuItem messageDynamicMenu = null; public static void setDynamicMenus() { List<DynamicEMenuItem> list = new ArrayList<DynamicEMenuItem>(); KeyStroke accelerator = getHiddenWindowCycleMenuItem().getAccelerator(); for (Iterator<WindowFrame> it = WindowFrame.getWindows(); it.hasNext();) { WindowFrame wf = it.next(); list.add(new DynamicEMenuItem(wf, accelerator)); accelerator = null; } if (messageDynamicMenu == null) messageDynamicMenu = new DynamicEMenuItem(accelerator); list.add(messageDynamicMenu); // Sort list of dynamic menus before adding into the menus Collections.sort(list, new TextUtils.ObjectsByToString()); thisWindowMenu.setDynamicItems(list); } private static class DynamicEMenuItem extends EMenuItem { WindowFrame window; public DynamicEMenuItem(WindowFrame w, KeyStroke accelerator) { super(w.getTitle(), accelerator); window = w; } public DynamicEMenuItem(KeyStroke accelerator) { super("Electric Messages", accelerator); window = null; } public String getDescription() { return "Window Cycle"; } protected void updateButtons() {} public void run() { if (window != null) window.requestFocus(); else // message window. This could be done by creating another interface TopLevel.getMessagesWindow().requestFocus(); } } public static void fullDisplay() { // get the current frame WindowFrame wf = WindowFrame.getCurrentWindowFrame(); if (wf == null) return; // make the circuit fill the window wf.getContent().fillScreen(); } public static void zoomOutDisplay() { // get the current frame WindowFrame wf = WindowFrame.getCurrentWindowFrame(); if (wf == null) return; // zoom out wf.getContent().zoomOutContents(); } public static void zoomInDisplay() { // get the current frame WindowFrame wf = WindowFrame.getCurrentWindowFrame(); if (wf == null) return; // zoom in wf.getContent().zoomInContents(); } public static void zoomBoxCommand() { // only works with click zoom wire listener EventListener oldListener = WindowFrame.getListener(); WindowFrame.setListener(ClickZoomWireListener.theOne); ClickZoomWireListener.theOne.zoomBoxSingleShot(oldListener); } /** * Method to make the current window's grid be just visible. * If it is zoomed-out beyond grid visibility, it is zoomed-in so that the grid is shown. * If it is zoomed-in such that the grid is not at minimum pitch, * it is zoomed-out so that the grid is barely able to fit. */ public static void makeGridJustVisibleCommand() { EditWindow wnd = EditWindow.needCurrent(); if (wnd == null) return; Rectangle2D displayable = wnd.displayableBounds(); Dimension sz = wnd.getSize(); double scaleX = wnd.getGridXSpacing() * sz.width / 5.01 / displayable.getWidth(); double scaleY = wnd.getGridYSpacing() * sz.height / 5.01 / displayable.getHeight(); double scale = Math.min(scaleX, scaleY); wnd.setScale(wnd.getScale() / scale); wnd.setGrid(true); } /** * Method to adjust the current window so that it matches that of the "other" window. * For this to work, there must be exactly one other window shown. * @param how 0 to match scale; 1 to match in X; 2 to match in Y; 3 to match all. */ public static void matchOtherWindowCommand(int how) { EditWindow wnd = EditWindow.needCurrent(); if (wnd == null) return; int numOthers = 0; EditWindow other = null; for(Iterator<WindowFrame> it = WindowFrame.getWindows(); it.hasNext(); ) { WindowFrame wf = it.next(); if (wf.getContent() instanceof EditWindow) { EditWindow wfWnd = (EditWindow)wf.getContent(); if (wfWnd == wnd) continue; numOthers++; other = wfWnd; } } if (numOthers != 1) { System.out.println("There must be exactly two windows in order for one to match the other"); return; } switch (how) { case 0: wnd.setScale(other.getScale()); break; case 1: wnd.setOffset(new Point2D.Double(other.getOffset().getX(), wnd.getOffset().getY())); break; case 2: wnd.setOffset(new Point2D.Double(wnd.getOffset().getX(), other.getOffset().getY())); break; case 3: wnd.setScale(other.getScale()); wnd.setOffset(new Point2D.Double(other.getOffset().getX(), other.getOffset().getY())); break; } wnd.repaintContents(null, false); } public static void focusOnHighlighted() { // get the current frame WindowFrame wf = WindowFrame.getCurrentWindowFrame(); if (wf == null) return; // focus on highlighted wf.getContent().focusOnHighlighted(); } /** * This method implements the command to toggle the display of the grid. */ public static void toggleGridCommand() { // get the current frame WindowFrame wf = WindowFrame.getCurrentWindowFrame(); if (wf == null) return; if (wf.getContent() instanceof EditWindow) { EditWindow wnd = (EditWindow)wf.getContent(); if (wnd == null) return; wnd.setGrid(!wnd.isGrid()); } else if (wf.getContent() instanceof WaveformWindow) { WaveformWindow ww = (WaveformWindow)wf.getContent(); ww.toggleGridPoints(); } else { System.out.println("Cannot draw a grid in this type of window"); } } /** * This method implements the command to tile the windows horizontally. */ public static void tileHorizontallyCommand() { // get the overall area in which to work Rectangle [] areas = getWindowAreas(); // tile the windows in each area for (Rectangle area : areas) { // see how many windows are on this screen int count = 0; for(Iterator<WindowFrame> it = WindowFrame.getWindows(); it.hasNext(); ) { WindowFrame wf = it.next(); Rectangle wfBounds = wf.getFrame().getBounds(); int locX = (int)wfBounds.getCenterX(); int locY = (int)wfBounds.getCenterY(); if (locX >= area.x && locX < area.x+area.width && locY >= area.y && locY < area.y+area.height) count++; } if (count == 0) continue; int windowHeight = area.height / count; count = 0; for(Iterator<WindowFrame> it = WindowFrame.getWindows(); it.hasNext(); ) { WindowFrame wf = it.next(); Rectangle wfBounds = wf.getFrame().getBounds(); int locX = (int)wfBounds.getCenterX(); int locY = (int)wfBounds.getCenterY(); if (locX >= area.x && locX < area.x+area.width && locY >= area.y && locY < area.y+area.height) { Rectangle windowArea = new Rectangle(area.x, area.y + count*windowHeight, area.width, windowHeight); count++; wf.setWindowSize(windowArea); } } } } /** * This method implements the command to tile the windows vertically. */ public static void tileVerticallyCommand() { // get the overall area in which to work Rectangle [] areas = getWindowAreas(); // tile the windows in each area for (Rectangle area : areas) { // see how many windows are on this screen int count = 0; for(Iterator<WindowFrame> it = WindowFrame.getWindows(); it.hasNext(); ) { WindowFrame wf = it.next(); Rectangle wfBounds = wf.getFrame().getBounds(); int locX = (int)wfBounds.getCenterX(); int locY = (int)wfBounds.getCenterY(); if (locX >= area.x && locX < area.x+area.width && locY >= area.y && locY < area.y+area.height) count++; } if (count == 0) continue; int windowWidth = area.width / count; count = 0; for(Iterator<WindowFrame> it = WindowFrame.getWindows(); it.hasNext(); ) { WindowFrame wf = it.next(); Rectangle wfBounds = wf.getFrame().getBounds(); int locX = (int)wfBounds.getCenterX(); int locY = (int)wfBounds.getCenterY(); if (locX >= area.x && locX < area.x+area.width && locY >= area.y && locY < area.y+area.height) { Rectangle windowArea = new Rectangle(area.x + count*windowWidth, area.y, windowWidth, area.height); count++; wf.setWindowSize(windowArea); } } } } /** * This method implements the command to tile the windows cascaded. */ public static void cascadeWindowsCommand() { // get the overall area in which to work Rectangle [] areas = getWindowAreas(); // tile the windows in each area for (Rectangle area : areas) { // see how many windows are on this screen int count = 0; for(Iterator<WindowFrame> it = WindowFrame.getWindows(); it.hasNext(); ) { WindowFrame wf = it.next(); Rectangle wfBounds = wf.getFrame().getBounds(); int locX = (int)wfBounds.getCenterX(); int locY = (int)wfBounds.getCenterY(); if (locX >= area.x && locX < area.x+area.width && locY >= area.y && locY < area.y+area.height) count++; } if (count == 0) continue; int numRuns = 1; int windowXSpacing = 0, windowYSpacing = 0; int windowWidth = area.width; int windowHeight = area.height; if (count > 1) { windowWidth = area.width * 3 / 4; windowHeight = area.height * 3 / 4; int windowSpacing = Math.min(area.width - windowWidth, area.height - windowHeight) / (count-1); if (windowSpacing < 70) { numRuns = 70 / windowSpacing; if (70 % windowSpacing != 0) numRuns++; windowSpacing *= numRuns; } windowXSpacing = (area.width - windowWidth) / (count-1) * numRuns; windowYSpacing = (area.height - windowHeight) / (count-1) * numRuns; } count = 0; for(Iterator<WindowFrame> it = WindowFrame.getWindows(); it.hasNext(); ) { WindowFrame wf = it.next(); Rectangle wfBounds = wf.getFrame().getBounds(); int locX = (int)wfBounds.getCenterX(); int locY = (int)wfBounds.getCenterY(); if (locX >= area.x && locX < area.x+area.width && locY >= area.y && locY < area.y+area.height) { int index = count / numRuns; Rectangle windowArea = new Rectangle(area.x + index*windowXSpacing, area.y + index*windowYSpacing, windowWidth, windowHeight); count++; wf.setWindowSize(windowArea); } } } } private static void closeWindowCommand() { WindowFrame curWF = WindowFrame.getCurrentWindowFrame(); curWF.finished(); } // private static void nextWindowCommand() // { // Object cur = null; // List<Object> frames = new ArrayList<Object>(); // for(Iterator<WindowFrame> it = WindowFrame.getWindows(); it.hasNext(); ) // { // WindowFrame wf = it.next(); // if (wf.isFocusOwner()) cur = wf; // frames.add(wf); // } // MessagesWindow mw = TopLevel.getMessagesWindow(); // if (mw.isFocusOwner()) cur = mw; // frames.add(mw); // // // find current frame in the list // int found = -1; // for(int i=0; i<frames.size(); i++) // { // if (cur == frames.get(i)) // { // found = i; // break; // } // } // if (found >= 0) // { // found++; // if (found >= frames.size()) found = 0; // Object newCur = frames.get(found); // if (newCur instanceof WindowFrame) // ((WindowFrame)newCur).requestFocus(); else // ((MessagesWindow)newCur).requestFocus(); // } // } private static Rectangle [] getWindowAreas() { Rectangle [] areas = null; if (TopLevel.isMDIMode()) { TopLevel tl = TopLevel.getCurrentJFrame(); Dimension sz = tl.getContentPane().getSize(); areas = new Rectangle[1]; areas[0] = new Rectangle(0, 0, sz.width, sz.height); } else { GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice [] gs = ge.getScreenDevices(); areas = new Rectangle[gs.length]; for (int j = 0; j < gs.length; j++) { GraphicsDevice gd = gs[j]; GraphicsConfiguration gc = gd.getDefaultConfiguration(); areas[j] = gc.getBounds(); } } // remove the messages window MessagesWindow mw = TopLevel.getMessagesWindow(); Rectangle mb = mw.getMessagesLocation(); removeOccludingRectangle(areas, mb); return areas; } private static void removeOccludingRectangle(Rectangle [] areas, Rectangle occluding) { int cX = occluding.x + occluding.width/2; int cY = occluding.y + occluding.height/2; for (Rectangle area : areas) { int lX = (int)area.getMinX(); int hX = (int)area.getMaxX(); int lY = (int)area.getMinY(); int hY = (int)area.getMaxY(); if (cX > lX && cX < hX && cY > lY && cY < hY) { if (occluding.width > occluding.height) { // horizontally occluding window if (occluding.getMaxY() - lY < hY - occluding.getMinY()) { // occluding window on top lY = (int)occluding.getMaxY(); } else { // occluding window on bottom hY = (int)occluding.getMinY(); } } else { if (occluding.getMaxX() - lX < hX - occluding.getMinX()) { // occluding window on left lX = (int)occluding.getMaxX(); } else { // occluding window on right hX = (int)occluding.getMinX(); } } area.x = lX; area.width = hX - lX; area.y = lY; area.height = hY - lY; } } } /** * This method implements the command to set default colors. */ public static void defaultBackgroundCommand() { User.setColorBackground(Color.LIGHT_GRAY.getRGB()); User.setColorGrid(Color.BLACK.getRGB()); User.setColorHighlight(Color.WHITE.getRGB()); User.setColorPortHighlight(Color.YELLOW.getRGB()); User.setColorText(Color.BLACK.getRGB()); User.setColorInstanceOutline(Color.BLACK.getRGB()); User.setColorWaveformBackground(Color.BLACK.getRGB()); User.setColorWaveformForeground(Color.WHITE.getRGB()); User.setColorWaveformStimuli(Color.RED.getRGB()); // change the colors in the "Generic" technology Generic.setBackgroudColor(Color.BLACK); // redraw redrawNewColors(); } /** * This method implements the command to set colors so that there is a black background. */ public static void blackBackgroundCommand() { User.setColorBackground(Color.BLACK.getRGB()); User.setColorGrid(Color.WHITE.getRGB()); User.setColorHighlight(Color.RED.getRGB()); User.setColorPortHighlight(Color.YELLOW.getRGB()); User.setColorText(Color.WHITE.getRGB()); User.setColorInstanceOutline(Color.WHITE.getRGB()); User.setColorWaveformBackground(Color.BLACK.getRGB()); User.setColorWaveformForeground(Color.WHITE.getRGB()); User.setColorWaveformStimuli(Color.RED.getRGB()); // change the colors in the "Generic" technology Generic.setBackgroudColor(Color.WHITE); // redraw redrawNewColors(); } /** * This method implements the command to set colors so that there is a white background. */ public static void whiteBackgroundCommand() { User.setColorBackground(Color.WHITE.getRGB()); User.setColorGrid(Color.BLACK.getRGB()); User.setColorHighlight(Color.RED.getRGB()); User.setColorPortHighlight(Color.DARK_GRAY.getRGB()); User.setColorText(Color.BLACK.getRGB()); User.setColorInstanceOutline(Color.BLACK.getRGB()); User.setColorWaveformBackground(Color.WHITE.getRGB()); User.setColorWaveformForeground(Color.BLACK.getRGB()); User.setColorWaveformStimuli(Color.RED.getRGB()); // change the colors in the "Generic" technology Generic.setBackgroudColor(Color.BLACK); // redraw redrawNewColors(); } private static void redrawNewColors() { for(Iterator<WindowFrame> it = WindowFrame.getWindows(); it.hasNext(); ) { WindowFrame wf = it.next(); WindowContent content = wf.getContent(); content.fullRepaint(); } for(Iterator<WindowFrame> it = WindowFrame.getWindows(); it.hasNext(); ) { WindowFrame wf = it.next(); wf.loadComponentMenuForTechnology(); } } private static GraphicsDevice [] getAllGraphicsDevices() { GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice[] gs = ge.getScreenDevices(); return gs; } public static void moveToOtherDisplayCommand() { // this only works in SDI mode if (TopLevel.isMDIMode()) return; // find current screen WindowFrame curWF = WindowFrame.getCurrentWindowFrame(); WindowContent content = curWF.getContent(); GraphicsConfiguration curConfig = content.getPanel().getGraphicsConfiguration(); GraphicsDevice curDevice = curConfig.getDevice(); // get all screens GraphicsDevice[] gs = getAllGraphicsDevices(); // for (int j=0; j<gs.length; j++) { // //System.out.println("Found GraphicsDevice: "+gs[j]+", type: "+gs[j].getType()); // } // find screen after current screen int i; for (i=0; i<gs.length; i++) { if (gs[i] == curDevice) break; } if (i == (gs.length - 1)) i = 0; else i++; // go to next device curWF.moveEditWindow(gs[i].getDefaultConfiguration()); } public static void rememberDisplayLocation() { // this only works in SDI mode if (TopLevel.isMDIMode()) return; // remember main window information WindowFrame curWF = WindowFrame.getCurrentWindowFrame(); TopLevel tl = curWF.getFrame(); Point pt = tl.getLocation(); User.setDefaultWindowPos(pt); Dimension sz = tl.getSize(); User.setDefaultWindowSize(sz); // remember messages information MessagesWindow mw = TopLevel.getMessagesWindow(); Rectangle rect = mw.getMessagesLocation(); User.setDefaultMessagesPos(new Point(rect.x, rect.y)); User.setDefaultMessagesSize(new Dimension(rect.width, rect.height)); } /** * Go to the previous saved view for the current Edit Window */ public static void goToPreviousSavedFocus() { EditWindow wnd = EditWindow.needCurrent(); if (wnd == null) return; EditWindowFocusBrowser browser = wnd.getSavedFocusBrowser(); browser.goBack(); } /** * Go to the previous saved view for the current Edit Window */ public static void goToNextSavedFocus() { EditWindow wnd = EditWindow.needCurrent(); if (wnd == null) return; EditWindowFocusBrowser browser = wnd.getSavedFocusBrowser(); browser.goForward(); } /** * Inner job class to import Cadence colors */ private static class ImportCadenceColorJob extends Job { private int response; private String backFileName; ImportCadenceColorJob(int r, String file) { super("Importing Cadence Colors", User.getUserTool(), Job.Type.EXAMINE, null, null, Job.Priority.USER); response = r; backFileName = file; this.startJob(); } public boolean doIt() throws JobException { if (response == 0) // Save previous preferences { if (backFileName != null) Pref.exportPrefs(backFileName); else System.out.println("Previous Preferences not backup"); } if (response != 2) // cancel { String cadenceFileName = "CadencePrefs.xml"; URL fileURL = Resources.getURLResource(TopLevel.class, cadenceFileName); if (fileURL != null) Pref.importPrefs(fileURL); else System.out.println("Cannot import '" + cadenceFileName + "'"); } return true; } } /** * Method to import color pattern used in Cadence */ private static void importCadencePreferences() { String backFileName = null; String [] options = { "Yes", "No", "Cancel Import"}; int response = Job.getUserInterface().askForChoice("Do you want to backup your preferences " + "before importing Cadence values?", "Import Cadence Preferences", options, options[1]); if (response == 0) // Save previous preferences { String fileName = OpenFile.chooseOutputFile(FileType.XML, "Backup Preferences", "electricPrefsBack.xml"); if (fileName != null) backFileName = fileName; // only if it didn't cancel the dialog } new ImportCadenceColorJob(response, backFileName); } }
false
true
static EMenu makeMenu() { /****************************** THE WINDOW MENU ******************************/ // bindings for numpad keys. Need extra one because over VNC, they get sent as shift+KP_* int ctrlshift = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask() | InputEvent.SHIFT_MASK; KeyStroke [] numpad4 = new KeyStroke [] { EMenuItem.shortcut('4'), EMenuItem.shortcut(KeyEvent.VK_NUMPAD4), KeyStroke.getKeyStroke(KeyEvent.VK_KP_LEFT, ctrlshift)}; KeyStroke [] numpad6 = new KeyStroke [] { EMenuItem.shortcut('6'), EMenuItem.shortcut(KeyEvent.VK_NUMPAD6), KeyStroke.getKeyStroke(KeyEvent.VK_KP_RIGHT, ctrlshift)}; KeyStroke [] numpad8 = new KeyStroke [] { EMenuItem.shortcut('8'), EMenuItem.shortcut(KeyEvent.VK_NUMPAD8), KeyStroke.getKeyStroke(KeyEvent.VK_KP_UP, ctrlshift)}; KeyStroke [] numpad2 = new KeyStroke [] { EMenuItem.shortcut('2'), EMenuItem.shortcut(KeyEvent.VK_NUMPAD2), KeyStroke.getKeyStroke(KeyEvent.VK_KP_DOWN, ctrlshift)}; KeyStroke [] numpad9 = new KeyStroke [] { EMenuItem.shortcut('9'), EMenuItem.shortcut(KeyEvent.VK_NUMPAD9), KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, ctrlshift)}; KeyStroke [] numpad7 = new KeyStroke [] { EMenuItem.shortcut('7'), EMenuItem.shortcut(KeyEvent.VK_NUMPAD7), KeyStroke.getKeyStroke(KeyEvent.VK_HOME, ctrlshift)}; KeyStroke [] numpad0 = new KeyStroke [] { EMenuItem.shortcut('0'), EMenuItem.shortcut(KeyEvent.VK_NUMPAD0), KeyStroke.getKeyStroke(KeyEvent.VK_INSERT, ctrlshift)}; KeyStroke [] numpad5 = new KeyStroke [] { EMenuItem.shortcut('5'), EMenuItem.shortcut(KeyEvent.VK_NUMPAD5), KeyStroke.getKeyStroke(KeyEvent.VK_BEGIN, ctrlshift)}; // mnemonic keys available: A K Q T Y EMenu menu = new EMenu("_Window", new EMenuItem("_Fill Window", numpad9) { public void run() { fullDisplay(); }}, new EMenuItem("Redisplay _Window") { public void run() { ZoomAndPanListener.redrawDisplay(); }}, new EMenuItem("Zoom _Out", numpad0) { public void run() { zoomOutDisplay(); }}, new EMenuItem("Zoom _In", numpad7) { public void run() { zoomInDisplay(); }}, // mnemonic keys available: ABCDEF IJKLMNOPQRSTUV XY new EMenu("Special _Zoom", new EMenuItem("Focus on _Highlighted", 'F') { public void run() { focusOnHighlighted(); }}, new EMenuItem("_Zoom Box") { public void run() { zoomBoxCommand(); }}, new EMenuItem("Make _Grid Just Visible") { public void run() { makeGridJustVisibleCommand(); }}, new EMenuItem("Match Other _Window") { public void run() { matchOtherWindowCommand(0); }}), SEPARATOR, new EMenuItem("Pan _Left", numpad4) { public void run() { ZoomAndPanListener.panXOrY(0, WindowFrame.getCurrentWindowFrame(), 1); }}, new EMenuItem("Pan _Right", numpad6) { public void run() { ZoomAndPanListener.panXOrY(0, WindowFrame.getCurrentWindowFrame(), -1); }}, new EMenuItem("Pan _Up", numpad8) { public void run() { ZoomAndPanListener.panXOrY(1, WindowFrame.getCurrentWindowFrame(), -1); }}, new EMenuItem("Pan _Down", numpad2) { public void run() { ZoomAndPanListener.panXOrY(1, WindowFrame.getCurrentWindowFrame(), 1); }}, // mnemonic keys available: B DEFGHIJKLMNOPQR TUVW Z new EMenu("Special _Pan", new EMenuItem("Center _Selection") { public void run() { ZoomAndPanListener.centerSelection(); }}, new EMenuItem("Center _Cursor", numpad5) { public void run() { ZoomAndPanListener.centerCursor(); }}, new EMenuItem("Match Other Window in _X") { public void run() { matchOtherWindowCommand(1); }}, new EMenuItem("Match Other Window in _Y") { public void run() { matchOtherWindowCommand(2); }}, new EMenuItem("Match Other Window in X, Y, _and Scale") { public void run() { matchOtherWindowCommand(3); }}), // new EMenuItem("Saved Views...") { public void run() { // SavedViews.showSavedViewsDialog(); }}, new EMenuItem("Go To Pre_vious Focus") { public void run() { goToPreviousSavedFocus(); }}, new EMenuItem("Go To Ne_xt Focus") { public void run() { goToNextSavedFocus(); }}, new EMenuItem("_Set Focus...") { public void run() { SetFocus.showSetFocusDialog(); }}, SEPARATOR, new EMenuItem("Toggle _Grid", 'G') { public void run() { toggleGridCommand(); }}, SEPARATOR, // mnemonic keys available: AB DEFG IJKLMNOPQRSTU WXYZ new EMenu("Ad_just Position", new EMenuItem("Tile _Horizontally") { public void run() { tileHorizontallyCommand(); }}, new EMenuItem("Tile _Vertically", KeyStroke.getKeyStroke(KeyEvent.VK_F9, 0)) { public void run() { tileVerticallyCommand(); }}, new EMenuItem("_Cascade") { public void run() { cascadeWindowsCommand(); }}), new EMenuItem("Clos_e Window", getCloseWindowAccelerator()) { public void run() { closeWindowCommand(); }}, // new EMenuItem("Select Next Window") { public void run() { // nextWindowCommand(); }}, !TopLevel.isMDIMode() ? SEPARATOR : null, !TopLevel.isMDIMode() && getAllGraphicsDevices().length >= 2 ? new EMenuItem("Move to Ot_her Display") { public void run() { moveToOtherDisplayCommand(); }} : null, !TopLevel.isMDIMode() ? new EMenuItem("Remember Locatio_n of Display") { public void run() { rememberDisplayLocation(); }} : null, SEPARATOR, // mnemonic keys available: A CDEFGHIJKLMNOPQ STUV XYZ new EMenu("_Color Schemes", new EMenuItem("_Restore Default Colors") { public void run() { defaultBackgroundCommand(); }}, new EMenuItem("_Black Background Colors") { public void run() { blackBackgroundCommand(); }}, new EMenuItem("_White Background Colors") { public void run() { whiteBackgroundCommand(); }}, new EMenuItem("Cadence Colors") { public void run() { importCadencePreferences(); }} ), // mnemonic keys available: ABC FGHIJKLMNOPQ TUVWXYZ new EMenu("W_aveform Window", new EMenuItem("_Save Waveform Window Configuration to Disk...") { public void run() { WaveformWindow.saveConfiguration(); }}, new EMenuItem("_Restore Waveform Window Configuration from Disk...") { public void run() { WaveformWindow.restoreConfiguration(); }}, SEPARATOR, new EMenuItem("Refresh Simulation _Data") { public void run() { WaveformWindow.refreshSimulationData(); }}, SEPARATOR, new EMenuItem("_Export Simulation Data...") { public void run() { WaveformWindow.exportSimulationData(); }} ), // mnemonic keys available: AB DE GHIJKLMNOPQR TUVWXYZ new EMenu("_Messages Window", new EMenuItem("_Save Messages...") { public void run() { MessagesStream.getMessagesStream().save(); }}, new EMenuItem("_Clear") { public void run() { TopLevel.getMessagesWindow().clear(); }}, new EMenuItem("Set F_ont...") { public void run() { TopLevel.getMessagesWindow().selectFont(); }}), MenuCommands.makeExtraMenu("j3d.ui.J3DMenu"), // mnemonic keys available: ABCDEFGHIJK MNOPQ STUVWXYZ new EMenu("Side _Bar", new EMenuItem("On _Left") { public void run() { WindowFrame.setSideBarLocation(true); }}, new EMenuItem("On _Right") { public void run() { WindowFrame.setSideBarLocation(false); }}), SEPARATOR ); thisWindowMenu = menu; return menu; }
static EMenu makeMenu() { /****************************** THE WINDOW MENU ******************************/ // bindings for numpad keys. Need extra one because over VNC, they get sent as shift+KP_* int ctrlshift = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask() | InputEvent.SHIFT_MASK; KeyStroke [] numpad4 = new KeyStroke [] { EMenuItem.shortcut('4'), EMenuItem.shortcut(KeyEvent.VK_NUMPAD4), KeyStroke.getKeyStroke(KeyEvent.VK_KP_LEFT, ctrlshift)}; KeyStroke [] numpad6 = new KeyStroke [] { EMenuItem.shortcut('6'), EMenuItem.shortcut(KeyEvent.VK_NUMPAD6), KeyStroke.getKeyStroke(KeyEvent.VK_KP_RIGHT, ctrlshift)}; KeyStroke [] numpad8 = new KeyStroke [] { EMenuItem.shortcut('8'), EMenuItem.shortcut(KeyEvent.VK_NUMPAD8), KeyStroke.getKeyStroke(KeyEvent.VK_KP_UP, ctrlshift)}; KeyStroke [] numpad2 = new KeyStroke [] { EMenuItem.shortcut('2'), EMenuItem.shortcut(KeyEvent.VK_NUMPAD2), KeyStroke.getKeyStroke(KeyEvent.VK_KP_DOWN, ctrlshift)}; KeyStroke [] numpad9 = new KeyStroke [] { EMenuItem.shortcut('9'), EMenuItem.shortcut(KeyEvent.VK_NUMPAD9), KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, ctrlshift)}; KeyStroke [] numpad7 = new KeyStroke [] { EMenuItem.shortcut('7'), EMenuItem.shortcut(KeyEvent.VK_NUMPAD7), KeyStroke.getKeyStroke(KeyEvent.VK_HOME, ctrlshift)}; KeyStroke [] numpad0 = new KeyStroke [] { EMenuItem.shortcut('0'), EMenuItem.shortcut(KeyEvent.VK_NUMPAD0), KeyStroke.getKeyStroke(KeyEvent.VK_INSERT, ctrlshift)}; KeyStroke [] numpad5 = new KeyStroke [] { EMenuItem.shortcut('5'), EMenuItem.shortcut(KeyEvent.VK_NUMPAD5), KeyStroke.getKeyStroke(KeyEvent.VK_BEGIN, ctrlshift)}; // mnemonic keys available: A K Q T Y EMenu menu = new EMenu("_Window", new EMenuItem("_Fill Window", numpad9) { public void run() { fullDisplay(); }}, new EMenuItem("Redisplay _Window") { public void run() { ZoomAndPanListener.redrawDisplay(); }}, new EMenuItem("Zoom _Out", numpad0) { public void run() { zoomOutDisplay(); }}, new EMenuItem("Zoom _In", numpad7) { public void run() { zoomInDisplay(); }}, // mnemonic keys available: ABCDEF IJKLMNOPQRSTUV XY new EMenu("Special _Zoom", new EMenuItem("Focus on _Highlighted", 'F') { public void run() { focusOnHighlighted(); }}, new EMenuItem("_Zoom Box") { public void run() { zoomBoxCommand(); }}, new EMenuItem("Make _Grid Just Visible") { public void run() { makeGridJustVisibleCommand(); }}, new EMenuItem("Match Other _Window") { public void run() { matchOtherWindowCommand(0); }}), SEPARATOR, new EMenuItem("Pan _Left", numpad4) { public void run() { ZoomAndPanListener.panXOrY(0, WindowFrame.getCurrentWindowFrame(), 1); }}, new EMenuItem("Pan _Right", numpad6) { public void run() { ZoomAndPanListener.panXOrY(0, WindowFrame.getCurrentWindowFrame(), -1); }}, new EMenuItem("Pan _Up", numpad8) { public void run() { ZoomAndPanListener.panXOrY(1, WindowFrame.getCurrentWindowFrame(), -1); }}, new EMenuItem("Pan _Down", numpad2) { public void run() { ZoomAndPanListener.panXOrY(1, WindowFrame.getCurrentWindowFrame(), 1); }}, // mnemonic keys available: B DEFGHIJKLMNOPQR TUVW Z new EMenu("Special _Pan", new EMenuItem("Center _Selection") { public void run() { ZoomAndPanListener.centerSelection(); }}, new EMenuItem("Center _Cursor", numpad5) { public void run() { ZoomAndPanListener.centerCursor(); }}, new EMenuItem("Match Other Window in _X") { public void run() { matchOtherWindowCommand(1); }}, new EMenuItem("Match Other Window in _Y") { public void run() { matchOtherWindowCommand(2); }}, new EMenuItem("Match Other Window in X, Y, _and Scale") { public void run() { matchOtherWindowCommand(3); }}), // new EMenuItem("Saved Views...") { public void run() { // SavedViews.showSavedViewsDialog(); }}, new EMenuItem("Go To Pre_vious Focus") { public void run() { goToPreviousSavedFocus(); }}, new EMenuItem("Go To Ne_xt Focus") { public void run() { goToNextSavedFocus(); }}, new EMenuItem("_Set Focus...") { public void run() { SetFocus.showSetFocusDialog(); }}, SEPARATOR, new EMenuItem("Toggle _Grid", 'G') { public void run() { toggleGridCommand(); }}, SEPARATOR, // mnemonic keys available: AB DEFG IJKLMNOPQRSTU WXYZ new EMenu("Ad_just Position", new EMenuItem("Tile _Horizontally") { public void run() { tileHorizontallyCommand(); }}, new EMenuItem("Tile _Vertically", KeyStroke.getKeyStroke(KeyEvent.VK_F9, 0)) { public void run() { tileVerticallyCommand(); }}, new EMenuItem("_Cascade") { public void run() { cascadeWindowsCommand(); }}), new EMenuItem("Clos_e Window", getCloseWindowAccelerator()) { public void run() { closeWindowCommand(); }}, // new EMenuItem("Select Next Window") { public void run() { // nextWindowCommand(); }}, !TopLevel.isMDIMode() ? SEPARATOR : null, !TopLevel.isMDIMode() && getAllGraphicsDevices().length >= 2 ? new EMenuItem("Move to Ot_her Display") { public void run() { moveToOtherDisplayCommand(); }} : null, !TopLevel.isMDIMode() ? new EMenuItem("Remember Locatio_n of Display") { public void run() { rememberDisplayLocation(); }} : null, SEPARATOR, // mnemonic keys available: A DEFGHIJKLMNOPQ STUV XYZ new EMenu("_Color Schemes", new EMenuItem("_Restore Default Colors") { public void run() { defaultBackgroundCommand(); }}, new EMenuItem("_Black Background Colors") { public void run() { blackBackgroundCommand(); }}, new EMenuItem("_White Background Colors") { public void run() { whiteBackgroundCommand(); }}, new EMenuItem("_Cadence Colors and Keystrokes") { public void run() { importCadencePreferences(); }} ), // mnemonic keys available: ABC FGHIJKLMNOPQ TUVWXYZ new EMenu("W_aveform Window", new EMenuItem("_Save Waveform Window Configuration to Disk...") { public void run() { WaveformWindow.saveConfiguration(); }}, new EMenuItem("_Restore Waveform Window Configuration from Disk...") { public void run() { WaveformWindow.restoreConfiguration(); }}, SEPARATOR, new EMenuItem("Refresh Simulation _Data") { public void run() { WaveformWindow.refreshSimulationData(); }}, SEPARATOR, new EMenuItem("_Export Simulation Data...") { public void run() { WaveformWindow.exportSimulationData(); }} ), // mnemonic keys available: AB DE GHIJKLMNOPQR TUVWXYZ new EMenu("_Messages Window", new EMenuItem("_Save Messages...") { public void run() { MessagesStream.getMessagesStream().save(); }}, new EMenuItem("_Clear") { public void run() { TopLevel.getMessagesWindow().clear(); }}, new EMenuItem("Set F_ont...") { public void run() { TopLevel.getMessagesWindow().selectFont(); }}), MenuCommands.makeExtraMenu("j3d.ui.J3DMenu"), // mnemonic keys available: ABCDEFGHIJK MNOPQ STUVWXYZ new EMenu("Side _Bar", new EMenuItem("On _Left") { public void run() { WindowFrame.setSideBarLocation(true); }}, new EMenuItem("On _Right") { public void run() { WindowFrame.setSideBarLocation(false); }}), SEPARATOR ); thisWindowMenu = menu; return menu; }
diff --git a/core/src/main/java/org/apache/mahout/cf/taste/impl/eval/GenericRecommenderIRStatsEvaluator.java b/core/src/main/java/org/apache/mahout/cf/taste/impl/eval/GenericRecommenderIRStatsEvaluator.java index 1069bd51e..6c8463e72 100644 --- a/core/src/main/java/org/apache/mahout/cf/taste/impl/eval/GenericRecommenderIRStatsEvaluator.java +++ b/core/src/main/java/org/apache/mahout/cf/taste/impl/eval/GenericRecommenderIRStatsEvaluator.java @@ -1,239 +1,239 @@ /** * 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.mahout.cf.taste.impl.eval; import java.util.List; import java.util.Random; import org.apache.mahout.cf.taste.common.NoSuchUserException; import org.apache.mahout.cf.taste.common.TasteException; import org.apache.mahout.cf.taste.eval.DataModelBuilder; import org.apache.mahout.cf.taste.eval.IRStatistics; import org.apache.mahout.cf.taste.eval.RecommenderBuilder; import org.apache.mahout.cf.taste.eval.RecommenderIRStatsEvaluator; import org.apache.mahout.cf.taste.eval.RelevantItemsDataSplitter; import org.apache.mahout.cf.taste.impl.common.FastByIDMap; import org.apache.mahout.cf.taste.impl.common.FastIDSet; import org.apache.mahout.cf.taste.impl.common.FullRunningAverage; import org.apache.mahout.cf.taste.impl.common.FullRunningAverageAndStdDev; import org.apache.mahout.cf.taste.impl.common.LongPrimitiveIterator; import org.apache.mahout.cf.taste.impl.common.RunningAverage; import org.apache.mahout.cf.taste.impl.common.RunningAverageAndStdDev; import org.apache.mahout.cf.taste.impl.model.GenericDataModel; import org.apache.mahout.cf.taste.model.DataModel; import org.apache.mahout.cf.taste.model.PreferenceArray; import org.apache.mahout.cf.taste.recommender.IDRescorer; import org.apache.mahout.cf.taste.recommender.RecommendedItem; import org.apache.mahout.cf.taste.recommender.Recommender; import org.apache.mahout.common.RandomUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Preconditions; /** * <p> * For each user, these implementation determine the top {@code n} preferences, then evaluate the IR * statistics based on a {@link DataModel} that does not have these values. This number {@code n} is the * "at" value, as in "precision at 5". For example, this would mean precision evaluated by removing the top 5 * preferences for a user and then finding the percentage of those 5 items included in the top 5 * recommendations for that user. * </p> */ public final class GenericRecommenderIRStatsEvaluator implements RecommenderIRStatsEvaluator { private static final Logger log = LoggerFactory.getLogger(GenericRecommenderIRStatsEvaluator.class); private static final double LOG2 = Math.log(2.0); /** * Pass as "relevanceThreshold" argument to * {@link #evaluate(RecommenderBuilder, DataModelBuilder, DataModel, IDRescorer, int, double, double)} to * have it attempt to compute a reasonable threshold. Note that this will impact performance. */ public static final double CHOOSE_THRESHOLD = Double.NaN; private final Random random; private final RelevantItemsDataSplitter dataSplitter; public GenericRecommenderIRStatsEvaluator() { this(new GenericRelevantItemsDataSplitter()); } public GenericRecommenderIRStatsEvaluator(RelevantItemsDataSplitter dataSplitter) { Preconditions.checkNotNull(dataSplitter); random = RandomUtils.getRandom(); this.dataSplitter = dataSplitter; } @Override public IRStatistics evaluate(RecommenderBuilder recommenderBuilder, DataModelBuilder dataModelBuilder, DataModel dataModel, IDRescorer rescorer, int at, double relevanceThreshold, double evaluationPercentage) throws TasteException { Preconditions.checkArgument(recommenderBuilder != null, "recommenderBuilder is null"); Preconditions.checkArgument(dataModel != null, "dataModel is null"); Preconditions.checkArgument(at >= 1, "at must be at least 1"); Preconditions.checkArgument(evaluationPercentage > 0.0 && evaluationPercentage <= 1.0, "Invalid evaluationPercentage: %s", evaluationPercentage); int numItems = dataModel.getNumItems(); RunningAverage precision = new FullRunningAverage(); RunningAverage recall = new FullRunningAverage(); RunningAverage fallOut = new FullRunningAverage(); RunningAverage nDCG = new FullRunningAverage(); int numUsersRecommendedFor = 0; int numUsersWithRecommendations = 0; LongPrimitiveIterator it = dataModel.getUserIDs(); while (it.hasNext()) { long userID = it.nextLong(); if (random.nextDouble() >= evaluationPercentage) { // Skipped continue; } long start = System.currentTimeMillis(); PreferenceArray prefs = dataModel.getPreferencesFromUser(userID); // List some most-preferred items that would count as (most) "relevant" results double theRelevanceThreshold = Double.isNaN(relevanceThreshold) ? computeThreshold(prefs) : relevanceThreshold; FastIDSet relevantItemIDs = dataSplitter.getRelevantItemsIDs(userID, at, theRelevanceThreshold, dataModel); int numRelevantItems = relevantItemIDs.size(); if (numRelevantItems <= 0) { continue; } FastByIDMap<PreferenceArray> trainingUsers = new FastByIDMap<PreferenceArray>(dataModel.getNumUsers()); LongPrimitiveIterator it2 = dataModel.getUserIDs(); while (it2.hasNext()) { dataSplitter.processOtherUser(userID, relevantItemIDs, trainingUsers, it2.nextLong(), dataModel); } DataModel trainingModel = dataModelBuilder == null ? new GenericDataModel(trainingUsers) : dataModelBuilder.buildDataModel(trainingUsers); try { trainingModel.getPreferencesFromUser(userID); } catch (NoSuchUserException nsee) { continue; // Oops we excluded all prefs for the user -- just move on } int size = relevantItemIDs.size() + trainingModel.getItemIDsFromUser(userID).size(); if (size < 2 * at) { // Really not enough prefs to meaningfully evaluate this user continue; } Recommender recommender = recommenderBuilder.buildRecommender(trainingModel); int intersectionSize = 0; List<RecommendedItem> recommendedItems = recommender.recommend(userID, at, rescorer); for (RecommendedItem recommendedItem : recommendedItems) { if (relevantItemIDs.contains(recommendedItem.getItemID())) { intersectionSize++; } } int numRecommendedItems = recommendedItems.size(); // Precision if (numRecommendedItems > 0) { precision.addDatum((double) intersectionSize / (double) numRecommendedItems); } // Recall recall.addDatum((double) intersectionSize / (double) numRelevantItems); // Fall-out if (numRelevantItems < size) { fallOut.addDatum((double) (numRecommendedItems - intersectionSize) / (double) (numItems - numRelevantItems)); } // nDCG // In computing, assume relevant IDs have relevance 1 and others 0 double cumulativeGain = 0.0; double idealizedGain = 0.0; for (int i = 0; i < recommendedItems.size(); i++) { RecommendedItem item = recommendedItems.get(i); - double discount = i == 0 ? 1.0 : 1.0 / log2(i + 1); + double discount = 1.0 / log2(i + 2.0); // Classical formulation says log(i+1), but i is 0-based here if (relevantItemIDs.contains(item.getItemID())) { cumulativeGain += discount; } // otherwise we're multiplying discount by relevance 0 so it doesn't do anything // Ideally results would be ordered with all relevant ones first, so this theoretical // ideal list starts with number of relevant items equal to the total number of relevant items if (i < relevantItemIDs.size()) { idealizedGain += discount; } } if (idealizedGain > 0.0) { nDCG.addDatum(cumulativeGain / idealizedGain); } // Reach numUsersRecommendedFor++; if (numRecommendedItems > 0) { numUsersWithRecommendations++; } long end = System.currentTimeMillis(); log.info("Evaluated with user {} in {}ms", userID, end - start); log.info("Precision/recall/fall-out/nDCG: {} / {} / {} / {}", new Object[] { precision.getAverage(), recall.getAverage(), fallOut.getAverage(), nDCG.getAverage() }); } double reach = (double) numUsersWithRecommendations / (double) numUsersRecommendedFor; return new IRStatisticsImpl( precision.getAverage(), recall.getAverage(), fallOut.getAverage(), nDCG.getAverage(), reach); } private static double computeThreshold(PreferenceArray prefs) { if (prefs.length() < 2) { // Not enough data points -- return a threshold that allows everything return Double.NEGATIVE_INFINITY; } RunningAverageAndStdDev stdDev = new FullRunningAverageAndStdDev(); int size = prefs.length(); for (int i = 0; i < size; i++) { stdDev.addDatum(prefs.getValue(i)); } return stdDev.getAverage() + stdDev.getStandardDeviation(); } private static double log2(double value) { return Math.log(value) / LOG2; } }
true
true
public IRStatistics evaluate(RecommenderBuilder recommenderBuilder, DataModelBuilder dataModelBuilder, DataModel dataModel, IDRescorer rescorer, int at, double relevanceThreshold, double evaluationPercentage) throws TasteException { Preconditions.checkArgument(recommenderBuilder != null, "recommenderBuilder is null"); Preconditions.checkArgument(dataModel != null, "dataModel is null"); Preconditions.checkArgument(at >= 1, "at must be at least 1"); Preconditions.checkArgument(evaluationPercentage > 0.0 && evaluationPercentage <= 1.0, "Invalid evaluationPercentage: %s", evaluationPercentage); int numItems = dataModel.getNumItems(); RunningAverage precision = new FullRunningAverage(); RunningAverage recall = new FullRunningAverage(); RunningAverage fallOut = new FullRunningAverage(); RunningAverage nDCG = new FullRunningAverage(); int numUsersRecommendedFor = 0; int numUsersWithRecommendations = 0; LongPrimitiveIterator it = dataModel.getUserIDs(); while (it.hasNext()) { long userID = it.nextLong(); if (random.nextDouble() >= evaluationPercentage) { // Skipped continue; } long start = System.currentTimeMillis(); PreferenceArray prefs = dataModel.getPreferencesFromUser(userID); // List some most-preferred items that would count as (most) "relevant" results double theRelevanceThreshold = Double.isNaN(relevanceThreshold) ? computeThreshold(prefs) : relevanceThreshold; FastIDSet relevantItemIDs = dataSplitter.getRelevantItemsIDs(userID, at, theRelevanceThreshold, dataModel); int numRelevantItems = relevantItemIDs.size(); if (numRelevantItems <= 0) { continue; } FastByIDMap<PreferenceArray> trainingUsers = new FastByIDMap<PreferenceArray>(dataModel.getNumUsers()); LongPrimitiveIterator it2 = dataModel.getUserIDs(); while (it2.hasNext()) { dataSplitter.processOtherUser(userID, relevantItemIDs, trainingUsers, it2.nextLong(), dataModel); } DataModel trainingModel = dataModelBuilder == null ? new GenericDataModel(trainingUsers) : dataModelBuilder.buildDataModel(trainingUsers); try { trainingModel.getPreferencesFromUser(userID); } catch (NoSuchUserException nsee) { continue; // Oops we excluded all prefs for the user -- just move on } int size = relevantItemIDs.size() + trainingModel.getItemIDsFromUser(userID).size(); if (size < 2 * at) { // Really not enough prefs to meaningfully evaluate this user continue; } Recommender recommender = recommenderBuilder.buildRecommender(trainingModel); int intersectionSize = 0; List<RecommendedItem> recommendedItems = recommender.recommend(userID, at, rescorer); for (RecommendedItem recommendedItem : recommendedItems) { if (relevantItemIDs.contains(recommendedItem.getItemID())) { intersectionSize++; } } int numRecommendedItems = recommendedItems.size(); // Precision if (numRecommendedItems > 0) { precision.addDatum((double) intersectionSize / (double) numRecommendedItems); } // Recall recall.addDatum((double) intersectionSize / (double) numRelevantItems); // Fall-out if (numRelevantItems < size) { fallOut.addDatum((double) (numRecommendedItems - intersectionSize) / (double) (numItems - numRelevantItems)); } // nDCG // In computing, assume relevant IDs have relevance 1 and others 0 double cumulativeGain = 0.0; double idealizedGain = 0.0; for (int i = 0; i < recommendedItems.size(); i++) { RecommendedItem item = recommendedItems.get(i); double discount = i == 0 ? 1.0 : 1.0 / log2(i + 1); if (relevantItemIDs.contains(item.getItemID())) { cumulativeGain += discount; } // otherwise we're multiplying discount by relevance 0 so it doesn't do anything // Ideally results would be ordered with all relevant ones first, so this theoretical // ideal list starts with number of relevant items equal to the total number of relevant items if (i < relevantItemIDs.size()) { idealizedGain += discount; } } if (idealizedGain > 0.0) { nDCG.addDatum(cumulativeGain / idealizedGain); } // Reach numUsersRecommendedFor++; if (numRecommendedItems > 0) { numUsersWithRecommendations++; } long end = System.currentTimeMillis(); log.info("Evaluated with user {} in {}ms", userID, end - start); log.info("Precision/recall/fall-out/nDCG: {} / {} / {} / {}", new Object[] { precision.getAverage(), recall.getAverage(), fallOut.getAverage(), nDCG.getAverage() }); } double reach = (double) numUsersWithRecommendations / (double) numUsersRecommendedFor; return new IRStatisticsImpl( precision.getAverage(), recall.getAverage(), fallOut.getAverage(), nDCG.getAverage(), reach); }
public IRStatistics evaluate(RecommenderBuilder recommenderBuilder, DataModelBuilder dataModelBuilder, DataModel dataModel, IDRescorer rescorer, int at, double relevanceThreshold, double evaluationPercentage) throws TasteException { Preconditions.checkArgument(recommenderBuilder != null, "recommenderBuilder is null"); Preconditions.checkArgument(dataModel != null, "dataModel is null"); Preconditions.checkArgument(at >= 1, "at must be at least 1"); Preconditions.checkArgument(evaluationPercentage > 0.0 && evaluationPercentage <= 1.0, "Invalid evaluationPercentage: %s", evaluationPercentage); int numItems = dataModel.getNumItems(); RunningAverage precision = new FullRunningAverage(); RunningAverage recall = new FullRunningAverage(); RunningAverage fallOut = new FullRunningAverage(); RunningAverage nDCG = new FullRunningAverage(); int numUsersRecommendedFor = 0; int numUsersWithRecommendations = 0; LongPrimitiveIterator it = dataModel.getUserIDs(); while (it.hasNext()) { long userID = it.nextLong(); if (random.nextDouble() >= evaluationPercentage) { // Skipped continue; } long start = System.currentTimeMillis(); PreferenceArray prefs = dataModel.getPreferencesFromUser(userID); // List some most-preferred items that would count as (most) "relevant" results double theRelevanceThreshold = Double.isNaN(relevanceThreshold) ? computeThreshold(prefs) : relevanceThreshold; FastIDSet relevantItemIDs = dataSplitter.getRelevantItemsIDs(userID, at, theRelevanceThreshold, dataModel); int numRelevantItems = relevantItemIDs.size(); if (numRelevantItems <= 0) { continue; } FastByIDMap<PreferenceArray> trainingUsers = new FastByIDMap<PreferenceArray>(dataModel.getNumUsers()); LongPrimitiveIterator it2 = dataModel.getUserIDs(); while (it2.hasNext()) { dataSplitter.processOtherUser(userID, relevantItemIDs, trainingUsers, it2.nextLong(), dataModel); } DataModel trainingModel = dataModelBuilder == null ? new GenericDataModel(trainingUsers) : dataModelBuilder.buildDataModel(trainingUsers); try { trainingModel.getPreferencesFromUser(userID); } catch (NoSuchUserException nsee) { continue; // Oops we excluded all prefs for the user -- just move on } int size = relevantItemIDs.size() + trainingModel.getItemIDsFromUser(userID).size(); if (size < 2 * at) { // Really not enough prefs to meaningfully evaluate this user continue; } Recommender recommender = recommenderBuilder.buildRecommender(trainingModel); int intersectionSize = 0; List<RecommendedItem> recommendedItems = recommender.recommend(userID, at, rescorer); for (RecommendedItem recommendedItem : recommendedItems) { if (relevantItemIDs.contains(recommendedItem.getItemID())) { intersectionSize++; } } int numRecommendedItems = recommendedItems.size(); // Precision if (numRecommendedItems > 0) { precision.addDatum((double) intersectionSize / (double) numRecommendedItems); } // Recall recall.addDatum((double) intersectionSize / (double) numRelevantItems); // Fall-out if (numRelevantItems < size) { fallOut.addDatum((double) (numRecommendedItems - intersectionSize) / (double) (numItems - numRelevantItems)); } // nDCG // In computing, assume relevant IDs have relevance 1 and others 0 double cumulativeGain = 0.0; double idealizedGain = 0.0; for (int i = 0; i < recommendedItems.size(); i++) { RecommendedItem item = recommendedItems.get(i); double discount = 1.0 / log2(i + 2.0); // Classical formulation says log(i+1), but i is 0-based here if (relevantItemIDs.contains(item.getItemID())) { cumulativeGain += discount; } // otherwise we're multiplying discount by relevance 0 so it doesn't do anything // Ideally results would be ordered with all relevant ones first, so this theoretical // ideal list starts with number of relevant items equal to the total number of relevant items if (i < relevantItemIDs.size()) { idealizedGain += discount; } } if (idealizedGain > 0.0) { nDCG.addDatum(cumulativeGain / idealizedGain); } // Reach numUsersRecommendedFor++; if (numRecommendedItems > 0) { numUsersWithRecommendations++; } long end = System.currentTimeMillis(); log.info("Evaluated with user {} in {}ms", userID, end - start); log.info("Precision/recall/fall-out/nDCG: {} / {} / {} / {}", new Object[] { precision.getAverage(), recall.getAverage(), fallOut.getAverage(), nDCG.getAverage() }); } double reach = (double) numUsersWithRecommendations / (double) numUsersRecommendedFor; return new IRStatisticsImpl( precision.getAverage(), recall.getAverage(), fallOut.getAverage(), nDCG.getAverage(), reach); }
diff --git a/tests/plugins/org.jboss.tools.ui.bot.ext/src/org/jboss/tools/ui/bot/ext/helper/FileRenameHelper.java b/tests/plugins/org.jboss.tools.ui.bot.ext/src/org/jboss/tools/ui/bot/ext/helper/FileRenameHelper.java index 971490636..ab63201c9 100644 --- a/tests/plugins/org.jboss.tools.ui.bot.ext/src/org/jboss/tools/ui/bot/ext/helper/FileRenameHelper.java +++ b/tests/plugins/org.jboss.tools.ui.bot.ext/src/org/jboss/tools/ui/bot/ext/helper/FileRenameHelper.java @@ -1,170 +1,171 @@ /******************************************************************************* * Copyright (c) 2007-2009 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 * * Contributor: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ package org.jboss.tools.ui.bot.ext.helper; import static org.jboss.tools.ui.bot.ext.SWTTestExt.eclipse; import org.eclipse.swtbot.eclipse.finder.SWTWorkbenchBot; import org.eclipse.swtbot.swt.finder.SWTBot; import org.eclipse.swtbot.swt.finder.exceptions.WidgetNotFoundException; import org.eclipse.swtbot.swt.finder.widgets.SWTBotMenu; import org.eclipse.swtbot.swt.finder.widgets.SWTBotTree; import org.eclipse.swtbot.swt.finder.widgets.SWTBotTreeItem; import org.jboss.tools.ui.bot.ext.SWTUtilExt; import org.jboss.tools.ui.bot.ext.Timing; import org.jboss.tools.ui.bot.ext.types.IDELabel; import org.jboss.tools.ui.bot.ext.types.ViewType; /** * Check Renaming Functionality within WebProjects View * Tests if file was properly renamed in WebProjects View * and Title of file in Editor was renamed also. * @author Vladimir Pakan * */ public class FileRenameHelper { private static final int sleepTime = Timing.time2S(); /** * Check File Renaming * @param bot * @param oldFileName * @param newFileName * @param treePathItems * @param fileTreeItemSuffix * @return */ public static String checkFileRenamingWithinWebProjects(SWTWorkbenchBot bot , String oldFileName, String newFileName, String[] treePathItems , String fileTreeItemSuffix){ bot.sleep(sleepTime); SWTBot webProjects = eclipse.showView(ViewType.WEB_PROJECTS); SWTBotTree tree = webProjects.tree(); tree.setFocus(); if (treePathItems != null && treePathItems.length > 0){ SWTBotTreeItem parentTreeItem = tree.getTreeItem(treePathItems[0]); parentTreeItem.expand(); bot.sleep(Timing.time1S()); parentTreeItem.select(); bot.sleep(Timing.time1S()); // Do not remove this part of code otherwise tree view is not populated properly parentTreeItem.collapse(); bot.sleep(Timing.time1S()); parentTreeItem.expand(); bot.sleep(Timing.time1S()); int index = 1; while (treePathItems.length > index){ parentTreeItem = parentTreeItem.getNode(treePathItems[index]); parentTreeItem.expand(); index++; } // Open File ContextMenuHelper.prepareTreeItemForContextMenu(tree , parentTreeItem.getNode(oldFileName + fileTreeItemSuffix)); new SWTBotMenu(ContextMenuHelper.getContextMenu(tree, IDELabel.Menu.OPEN, true)).click(); bot.sleep(sleepTime); // Rename file new SWTBotMenu(ContextMenuHelper.getContextMenu(tree, IDELabel.Menu.RENAME, true)).click(); bot.sleep(sleepTime); bot.shell(IDELabel.Shell.RENAME_RESOURCE).activate(); bot.textWithLabel(IDELabel.RenameResourceDialog.NEW_NAME) .setText(newFileName); bot.button(IDELabel.Button.OK).click(); new SWTUtilExt(bot).waitForAll(60 * 1000L); bot.sleep(Timing.time5S()); // Check Results // File with Old Name doesn't exists within WebProjects View try{ parentTreeItem.getNode(oldFileName + fileTreeItemSuffix); return "File " + oldFileName + " was not renamed to " + newFileName + "."; }catch (WidgetNotFoundException wnfe) { // do nothing } // File with New Name exists within WebProjects View try{ parentTreeItem.getNode(newFileName + fileTreeItemSuffix); }catch (WidgetNotFoundException wnfe) { return "Renamed File " + newFileName + " was not found."; } // Editor Title was renamed + bot.sleep(Timing.time2S()); try{ bot.editorByTitle(newFileName); }catch (WidgetNotFoundException wnfe) { return "Editor Title was not changed to " + newFileName + " after renaming."; } } else{ return "Unable to find file for renaming."; } return null; } /** * Check File Renaming * @param bot * @param oldFileName * @param newFileName * @param treePathItems * @return */ public static String checkFileRenamingWithinWebProjects(SWTWorkbenchBot bot , String oldFileName, String newFileName, String[] treePathItems){ return checkFileRenamingWithinWebProjects(bot, oldFileName, newFileName, treePathItems, ""); } /** * Check Project Renaming within Package Explorer * @param bot * @param oldProjectName * @param newProjectName * @return */ public static String checkProjectRenamingWithinPackageExplorer(SWTWorkbenchBot bot , String oldProjectName, String newProjectName, String renameShellTitle){ bot.sleep(sleepTime); SWTBotTree tree = eclipse.showView(ViewType.PACKAGE_EXPLORER).tree(); tree.setFocus(); tree.getTreeItem(oldProjectName).select(); bot.sleep(Timing.time1S()); // Rename project bot.menu(IDELabel.Menu.FILE). menu("Rename...") .click(); bot.sleep(Timing.time1S()); bot.shell(renameShellTitle).activate(); bot.textWithLabel(IDELabel.RenameResourceDialog.NEW_NAME) .setText(newProjectName); bot.button(IDELabel.Button.OK).click(); new SWTUtilExt(bot).waitForAll(Timing.time10S()); // Check Results // Project with Old Name doesn't exists within Package explorer try{ tree.getTreeItem(oldProjectName); return "Project " + oldProjectName + " was not renamed to " + newProjectName + "."; }catch (WidgetNotFoundException wnfe) { // do nothing } // Project with New Name exists within Package Explorer try{ tree.getTreeItem(newProjectName); }catch (WidgetNotFoundException wnfe) { return "Renamed Project " + newProjectName + " was not found."; } return null; } }
true
true
public static String checkFileRenamingWithinWebProjects(SWTWorkbenchBot bot , String oldFileName, String newFileName, String[] treePathItems , String fileTreeItemSuffix){ bot.sleep(sleepTime); SWTBot webProjects = eclipse.showView(ViewType.WEB_PROJECTS); SWTBotTree tree = webProjects.tree(); tree.setFocus(); if (treePathItems != null && treePathItems.length > 0){ SWTBotTreeItem parentTreeItem = tree.getTreeItem(treePathItems[0]); parentTreeItem.expand(); bot.sleep(Timing.time1S()); parentTreeItem.select(); bot.sleep(Timing.time1S()); // Do not remove this part of code otherwise tree view is not populated properly parentTreeItem.collapse(); bot.sleep(Timing.time1S()); parentTreeItem.expand(); bot.sleep(Timing.time1S()); int index = 1; while (treePathItems.length > index){ parentTreeItem = parentTreeItem.getNode(treePathItems[index]); parentTreeItem.expand(); index++; } // Open File ContextMenuHelper.prepareTreeItemForContextMenu(tree , parentTreeItem.getNode(oldFileName + fileTreeItemSuffix)); new SWTBotMenu(ContextMenuHelper.getContextMenu(tree, IDELabel.Menu.OPEN, true)).click(); bot.sleep(sleepTime); // Rename file new SWTBotMenu(ContextMenuHelper.getContextMenu(tree, IDELabel.Menu.RENAME, true)).click(); bot.sleep(sleepTime); bot.shell(IDELabel.Shell.RENAME_RESOURCE).activate(); bot.textWithLabel(IDELabel.RenameResourceDialog.NEW_NAME) .setText(newFileName); bot.button(IDELabel.Button.OK).click(); new SWTUtilExt(bot).waitForAll(60 * 1000L); bot.sleep(Timing.time5S()); // Check Results // File with Old Name doesn't exists within WebProjects View try{ parentTreeItem.getNode(oldFileName + fileTreeItemSuffix); return "File " + oldFileName + " was not renamed to " + newFileName + "."; }catch (WidgetNotFoundException wnfe) { // do nothing } // File with New Name exists within WebProjects View try{ parentTreeItem.getNode(newFileName + fileTreeItemSuffix); }catch (WidgetNotFoundException wnfe) { return "Renamed File " + newFileName + " was not found."; } // Editor Title was renamed try{ bot.editorByTitle(newFileName); }catch (WidgetNotFoundException wnfe) { return "Editor Title was not changed to " + newFileName + " after renaming."; } } else{ return "Unable to find file for renaming."; } return null; }
public static String checkFileRenamingWithinWebProjects(SWTWorkbenchBot bot , String oldFileName, String newFileName, String[] treePathItems , String fileTreeItemSuffix){ bot.sleep(sleepTime); SWTBot webProjects = eclipse.showView(ViewType.WEB_PROJECTS); SWTBotTree tree = webProjects.tree(); tree.setFocus(); if (treePathItems != null && treePathItems.length > 0){ SWTBotTreeItem parentTreeItem = tree.getTreeItem(treePathItems[0]); parentTreeItem.expand(); bot.sleep(Timing.time1S()); parentTreeItem.select(); bot.sleep(Timing.time1S()); // Do not remove this part of code otherwise tree view is not populated properly parentTreeItem.collapse(); bot.sleep(Timing.time1S()); parentTreeItem.expand(); bot.sleep(Timing.time1S()); int index = 1; while (treePathItems.length > index){ parentTreeItem = parentTreeItem.getNode(treePathItems[index]); parentTreeItem.expand(); index++; } // Open File ContextMenuHelper.prepareTreeItemForContextMenu(tree , parentTreeItem.getNode(oldFileName + fileTreeItemSuffix)); new SWTBotMenu(ContextMenuHelper.getContextMenu(tree, IDELabel.Menu.OPEN, true)).click(); bot.sleep(sleepTime); // Rename file new SWTBotMenu(ContextMenuHelper.getContextMenu(tree, IDELabel.Menu.RENAME, true)).click(); bot.sleep(sleepTime); bot.shell(IDELabel.Shell.RENAME_RESOURCE).activate(); bot.textWithLabel(IDELabel.RenameResourceDialog.NEW_NAME) .setText(newFileName); bot.button(IDELabel.Button.OK).click(); new SWTUtilExt(bot).waitForAll(60 * 1000L); bot.sleep(Timing.time5S()); // Check Results // File with Old Name doesn't exists within WebProjects View try{ parentTreeItem.getNode(oldFileName + fileTreeItemSuffix); return "File " + oldFileName + " was not renamed to " + newFileName + "."; }catch (WidgetNotFoundException wnfe) { // do nothing } // File with New Name exists within WebProjects View try{ parentTreeItem.getNode(newFileName + fileTreeItemSuffix); }catch (WidgetNotFoundException wnfe) { return "Renamed File " + newFileName + " was not found."; } // Editor Title was renamed bot.sleep(Timing.time2S()); try{ bot.editorByTitle(newFileName); }catch (WidgetNotFoundException wnfe) { return "Editor Title was not changed to " + newFileName + " after renaming."; } } else{ return "Unable to find file for renaming."; } return null; }
diff --git a/src/com/android/email/view/CertificateSelector.java b/src/com/android/email/view/CertificateSelector.java index d9d9e3eb..e180d11b 100644 --- a/src/com/android/email/view/CertificateSelector.java +++ b/src/com/android/email/view/CertificateSelector.java @@ -1,167 +1,169 @@ /* * 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.email.view; import com.android.email.R; import com.android.email.activity.UiUtilities; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Parcel; import android.os.Parcelable; import android.security.KeyChain; import android.security.KeyChainAliasCallback; import android.util.AttributeSet; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; /** * A simple view that can be used to select a certificate from the system {@link KeyChain}. * * Host activities must register themselves view {@link #setActivity} for this selector to work, * since it requires firing system {@link Intent}s. */ public class CertificateSelector extends LinearLayout implements OnClickListener, KeyChainAliasCallback { /** Button to select or remove the certificate. */ private Button mSelectButton; private TextView mAliasText; /** The host activity. */ private Activity mActivity; public CertificateSelector(Context context) { super(context); } public CertificateSelector(Context context, AttributeSet attrs) { super(context, attrs); } public CertificateSelector(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } public void setActivity(Activity activity) { mActivity = activity; } @Override protected void onFinishInflate() { super.onFinishInflate(); mAliasText = UiUtilities.getView(this, R.id.certificate_alias); mSelectButton = UiUtilities.getView(this, R.id.select_button); mSelectButton.setOnClickListener(this); setCertificate(null); } public void setCertificate(String alias) { mAliasText.setText(alias); mAliasText.setVisibility((alias == null) ? View.GONE : View.VISIBLE); mSelectButton.setText(getResources().getString( (alias == null) ? R.string.account_setup_exchange_use_certificate : R.string.account_setup_exchange_remove_certificate)); } public boolean hasCertificate() { return mAliasText.getVisibility() == View.VISIBLE; } /** * Gets the alias for the currently selected certificate, or null if one is not selected. */ public String getCertificate() { return hasCertificate() ? mAliasText.getText().toString() : null; } @Override public void onClick(View target) { if (target == mSelectButton && mActivity != null) { if (hasCertificate()) { // Handle the click on the button when it says "Remove" setCertificate(null); } else { // We don't restrict the chooser for certificate types since 95% of the time the // user will probably only have one certificate installed and it'll be the right // "type". Just let them fail and select a different one if it doesn't match. KeyChain.choosePrivateKeyAlias( mActivity, this, - null /* keytypes */, null /* issuers */, null /* host */, -1 /* port */); + null /* keytypes */, null /* issuers */, + null /* host */, -1 /* port */, + null /* alias */); } } } // KeyChainAliasCallback @Override public void alias(String alias) { if (alias != null) { setCertificate(alias); } } @Override protected void onRestoreInstanceState(Parcelable parcel) { SavedState savedState = (SavedState) parcel; super.onRestoreInstanceState(savedState.getSuperState()); setCertificate(savedState.mValue); } @Override protected Parcelable onSaveInstanceState() { return new SavedState(super.onSaveInstanceState(), getCertificate()); } public static class SavedState extends BaseSavedState { final String mValue; SavedState(Parcelable superState, String value) { super(superState); mValue = value; } @Override public void writeToParcel(Parcel out, int flags) { super.writeToParcel(out, flags); out.writeString(mValue); } @SuppressWarnings("hiding") public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() { public SavedState createFromParcel(Parcel in) { return new SavedState(in); } public SavedState[] newArray(int size) { return new SavedState[size]; } }; private SavedState(Parcel in) { super(in); mValue = in.readString(); } } }
true
true
public void onClick(View target) { if (target == mSelectButton && mActivity != null) { if (hasCertificate()) { // Handle the click on the button when it says "Remove" setCertificate(null); } else { // We don't restrict the chooser for certificate types since 95% of the time the // user will probably only have one certificate installed and it'll be the right // "type". Just let them fail and select a different one if it doesn't match. KeyChain.choosePrivateKeyAlias( mActivity, this, null /* keytypes */, null /* issuers */, null /* host */, -1 /* port */); } } }
public void onClick(View target) { if (target == mSelectButton && mActivity != null) { if (hasCertificate()) { // Handle the click on the button when it says "Remove" setCertificate(null); } else { // We don't restrict the chooser for certificate types since 95% of the time the // user will probably only have one certificate installed and it'll be the right // "type". Just let them fail and select a different one if it doesn't match. KeyChain.choosePrivateKeyAlias( mActivity, this, null /* keytypes */, null /* issuers */, null /* host */, -1 /* port */, null /* alias */); } } }
diff --git a/dspace-xmlui/dspace-xmlui-api/src/main/java/org/dspace/app/xmlui/aspect/artifactbrowser/FeedbackForm.java b/dspace-xmlui/dspace-xmlui-api/src/main/java/org/dspace/app/xmlui/aspect/artifactbrowser/FeedbackForm.java index e730f596f..12b7a2932 100644 --- a/dspace-xmlui/dspace-xmlui-api/src/main/java/org/dspace/app/xmlui/aspect/artifactbrowser/FeedbackForm.java +++ b/dspace-xmlui/dspace-xmlui-api/src/main/java/org/dspace/app/xmlui/aspect/artifactbrowser/FeedbackForm.java @@ -1,158 +1,157 @@ /* * FeedbackForm.java * * Version: $Revision: 1.4 $ * * Date: $Date: 2006/07/27 18:24:34 $ * * Copyright (c) 2002, Hewlett-Packard Company and Massachusetts * Institute of Technology. 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 Hewlett-Packard Company nor the name of the * Massachusetts Institute of Technology nor the names of their * 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 * HOLDERS 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 org.dspace.app.xmlui.aspect.artifactbrowser; import java.io.IOException; import java.io.Serializable; import java.sql.SQLException; import org.apache.cocoon.caching.CacheableProcessingComponent; import org.apache.cocoon.util.HashUtil; import org.apache.excalibur.source.SourceValidity; import org.apache.excalibur.source.impl.validity.NOPValidity; import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer; import org.dspace.app.xmlui.utils.UIException; import org.dspace.app.xmlui.wing.Message; import org.dspace.app.xmlui.wing.WingException; import org.dspace.app.xmlui.wing.element.Body; import org.dspace.app.xmlui.wing.element.Division; import org.dspace.app.xmlui.wing.element.List; import org.dspace.app.xmlui.wing.element.PageMeta; import org.dspace.app.xmlui.wing.element.Text; import org.dspace.app.xmlui.wing.element.TextArea; import org.dspace.authorize.AuthorizeException; import org.xml.sax.SAXException; /** * Display to the user a simple form letting the user give feedback. * * @author Scott Phillips */ public class FeedbackForm extends AbstractDSpaceTransformer implements CacheableProcessingComponent { /** Language Strings */ private static final Message T_title = message("xmlui.ArtifactBrowser.FeedbackForm.title"); private static final Message T_dspace_home = message("xmlui.general.dspace_home"); private static final Message T_trail = message("xmlui.ArtifactBrowser.FeedbackForm.trail"); private static final Message T_head = message("xmlui.ArtifactBrowser.FeedbackForm.head"); private static final Message T_para1 = message("xmlui.ArtifactBrowser.FeedbackForm.para1"); private static final Message T_email = message("xmlui.ArtifactBrowser.FeedbackForm.email"); private static final Message T_email_help = message("xmlui.ArtifactBrowser.FeedbackForm.email_help"); private static final Message T_comments = message("xmlui.ArtifactBrowser.FeedbackForm.comments"); private static final Message T_submit = message("xmlui.ArtifactBrowser.FeedbackForm.submit"); /** * Generate the unique caching key. * This key must be unique inside the space of this component. */ public Serializable getKey() { String email = parameters.getParameter("email",""); String comments = parameters.getParameter("comments",""); String page = parameters.getParameter("page","unknown"); return HashUtil.hash(email + "-" + comments + "-" + page); } /** * Generate the cache validity object. */ public SourceValidity getValidity() { return NOPValidity.SHARED_INSTANCE; } public void addPageMeta(PageMeta pageMeta) throws SAXException, WingException, UIException, SQLException, IOException, AuthorizeException { pageMeta.addMetadata("title").addContent(T_title); pageMeta.addTrailLink(contextPath + "/",T_dspace_home); pageMeta.addTrail().addContent(T_trail); } public void addBody(Body body) throws SAXException, WingException, UIException, SQLException, IOException, AuthorizeException { // Build the item viewer division. Division feedback = body.addInteractiveDivision("feedback-form", contextPath+"/feedback",Division.METHOD_POST,"primary"); feedback.setHead(T_head); feedback.addPara(T_para1); List form = feedback.addList("form",List.TYPE_FORM); Text email = form.addItem().addText("email"); email.setLabel(T_email); email.setHelp(T_email_help); email.setValue(parameters.getParameter("email","")); TextArea comments = form.addItem().addTextArea("comments"); comments.setLabel(T_comments); - comments.setSize(5,60); comments.setValue(parameters.getParameter("comments","")); form.addItem().addButton("submit").setValue(T_submit); feedback.addHidden("page").setValue(parameters.getParameter("page","unknown")); } }
true
true
public void addBody(Body body) throws SAXException, WingException, UIException, SQLException, IOException, AuthorizeException { // Build the item viewer division. Division feedback = body.addInteractiveDivision("feedback-form", contextPath+"/feedback",Division.METHOD_POST,"primary"); feedback.setHead(T_head); feedback.addPara(T_para1); List form = feedback.addList("form",List.TYPE_FORM); Text email = form.addItem().addText("email"); email.setLabel(T_email); email.setHelp(T_email_help); email.setValue(parameters.getParameter("email","")); TextArea comments = form.addItem().addTextArea("comments"); comments.setLabel(T_comments); comments.setSize(5,60); comments.setValue(parameters.getParameter("comments","")); form.addItem().addButton("submit").setValue(T_submit); feedback.addHidden("page").setValue(parameters.getParameter("page","unknown")); }
public void addBody(Body body) throws SAXException, WingException, UIException, SQLException, IOException, AuthorizeException { // Build the item viewer division. Division feedback = body.addInteractiveDivision("feedback-form", contextPath+"/feedback",Division.METHOD_POST,"primary"); feedback.setHead(T_head); feedback.addPara(T_para1); List form = feedback.addList("form",List.TYPE_FORM); Text email = form.addItem().addText("email"); email.setLabel(T_email); email.setHelp(T_email_help); email.setValue(parameters.getParameter("email","")); TextArea comments = form.addItem().addTextArea("comments"); comments.setLabel(T_comments); comments.setValue(parameters.getParameter("comments","")); form.addItem().addButton("submit").setValue(T_submit); feedback.addHidden("page").setValue(parameters.getParameter("page","unknown")); }
diff --git a/poulpe-view/poulpe-web-controller/src/main/java/org/jtalks/poulpe/web/controller/section/dialogs/DeleteBranchDialogVm.java b/poulpe-view/poulpe-web-controller/src/main/java/org/jtalks/poulpe/web/controller/section/dialogs/DeleteBranchDialogVm.java index bd311d60..52289d47 100644 --- a/poulpe-view/poulpe-web-controller/src/main/java/org/jtalks/poulpe/web/controller/section/dialogs/DeleteBranchDialogVm.java +++ b/poulpe-view/poulpe-web-controller/src/main/java/org/jtalks/poulpe/web/controller/section/dialogs/DeleteBranchDialogVm.java @@ -1,75 +1,76 @@ /** * Copyright (C) 2011 JTalks.org Team * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package org.jtalks.poulpe.web.controller.section.dialogs; import org.jtalks.poulpe.model.entity.PoulpeBranch; import org.jtalks.poulpe.service.BranchService; import org.jtalks.poulpe.service.ForumStructureService; import org.jtalks.poulpe.service.exceptions.JcommuneUrlNotConfiguratedException; import org.jtalks.poulpe.web.controller.section.ForumStructureVm; import org.zkoss.bind.annotation.Command; import org.zkoss.bind.annotation.GlobalCommand; import org.zkoss.bind.annotation.NotifyChange; import org.jtalks.poulpe.service.exceptions.JcommuneRespondedWithErrorException; import org.jtalks.poulpe.service.exceptions.NoConnectionToJcommuneException; import org.zkoss.util.resource.Labels; import org.zkoss.zul.Messagebox; /** * This VM is responsible for deleting the branch: whether to move the content of the branch to the other branch or * should the branch be deleted with whole its content. * * @author stanislav bashkirtsev */ public class DeleteBranchDialogVm extends AbstractDialogVm { private static final String SHOW_DIALOG = "showDialog"; private final ForumStructureVm forumStructureVm; private final ForumStructureService forumStructureService; private final String JCOMMUNE_CONNECTION_FAILED = "branches.error.jcommune_no_connection"; private final String JCOMMUNE_RESPONSE_FAILED = "branches.error.jcommune_no_response"; private final String JCOMMUNE_URL_FAILED = "branches.error.jcommune_no_url"; private final String BRANCH_DELETING_FAILED_DIALOG_TITLE = "branches.deleting_problem_dialog.title"; public DeleteBranchDialogVm(ForumStructureVm forumStructureVm, ForumStructureService forumStructureService) { this.forumStructureVm = forumStructureVm; this.forumStructureService = forumStructureService; } @Command @NotifyChange(SHOW_DIALOG) public void confirmDeleteBranchWithContent() { PoulpeBranch selectedBranch = forumStructureVm.getSelectedItemInTree().getBranchItem(); try { forumStructureService.removeBranch(selectedBranch); + forumStructureVm.removeBranchFromTree(selectedBranch); } catch (NoConnectionToJcommuneException e) { Messagebox.show(Labels.getLabel(JCOMMUNE_CONNECTION_FAILED), Labels.getLabel(BRANCH_DELETING_FAILED_DIALOG_TITLE), Messagebox.OK, Messagebox.ERROR); }catch (JcommuneRespondedWithErrorException ex) { Messagebox.show(Labels.getLabel(JCOMMUNE_RESPONSE_FAILED), Labels.getLabel(BRANCH_DELETING_FAILED_DIALOG_TITLE), Messagebox.OK, Messagebox.ERROR); }catch (JcommuneUrlNotConfiguratedException ex) { Messagebox.show(Labels.getLabel(JCOMMUNE_URL_FAILED), Labels.getLabel(BRANCH_DELETING_FAILED_DIALOG_TITLE), Messagebox.OK, Messagebox.ERROR); } } @GlobalCommand("deleteBranch") @NotifyChange(SHOW_DIALOG) public void deleteBranch() { showDialog(); } }
true
true
public void confirmDeleteBranchWithContent() { PoulpeBranch selectedBranch = forumStructureVm.getSelectedItemInTree().getBranchItem(); try { forumStructureService.removeBranch(selectedBranch); } catch (NoConnectionToJcommuneException e) { Messagebox.show(Labels.getLabel(JCOMMUNE_CONNECTION_FAILED), Labels.getLabel(BRANCH_DELETING_FAILED_DIALOG_TITLE), Messagebox.OK, Messagebox.ERROR); }catch (JcommuneRespondedWithErrorException ex) { Messagebox.show(Labels.getLabel(JCOMMUNE_RESPONSE_FAILED), Labels.getLabel(BRANCH_DELETING_FAILED_DIALOG_TITLE), Messagebox.OK, Messagebox.ERROR); }catch (JcommuneUrlNotConfiguratedException ex) { Messagebox.show(Labels.getLabel(JCOMMUNE_URL_FAILED), Labels.getLabel(BRANCH_DELETING_FAILED_DIALOG_TITLE), Messagebox.OK, Messagebox.ERROR); } }
public void confirmDeleteBranchWithContent() { PoulpeBranch selectedBranch = forumStructureVm.getSelectedItemInTree().getBranchItem(); try { forumStructureService.removeBranch(selectedBranch); forumStructureVm.removeBranchFromTree(selectedBranch); } catch (NoConnectionToJcommuneException e) { Messagebox.show(Labels.getLabel(JCOMMUNE_CONNECTION_FAILED), Labels.getLabel(BRANCH_DELETING_FAILED_DIALOG_TITLE), Messagebox.OK, Messagebox.ERROR); }catch (JcommuneRespondedWithErrorException ex) { Messagebox.show(Labels.getLabel(JCOMMUNE_RESPONSE_FAILED), Labels.getLabel(BRANCH_DELETING_FAILED_DIALOG_TITLE), Messagebox.OK, Messagebox.ERROR); }catch (JcommuneUrlNotConfiguratedException ex) { Messagebox.show(Labels.getLabel(JCOMMUNE_URL_FAILED), Labels.getLabel(BRANCH_DELETING_FAILED_DIALOG_TITLE), Messagebox.OK, Messagebox.ERROR); } }
diff --git a/org.eclipse.mylyn.bugzilla.ui/src/org/eclipse/mylyn/bugzilla/ui/editor/AbstractBugEditor.java b/org.eclipse.mylyn.bugzilla.ui/src/org/eclipse/mylyn/bugzilla/ui/editor/AbstractBugEditor.java index 484b99962..0e298be17 100644 --- a/org.eclipse.mylyn.bugzilla.ui/src/org/eclipse/mylyn/bugzilla/ui/editor/AbstractBugEditor.java +++ b/org.eclipse.mylyn.bugzilla.ui/src/org/eclipse/mylyn/bugzilla/ui/editor/AbstractBugEditor.java @@ -1,1588 +1,1592 @@ /******************************************************************************* * Copyright (c) 2003 - 2005 University Of British Columbia 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: * University Of British Columbia - initial API and implementation *******************************************************************************/ package org.eclipse.mylar.bugzilla.ui.editor; import java.net.MalformedURLException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jface.action.GroupMarker; import org.eclipse.jface.action.IMenuListener; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.resource.JFaceColors; import org.eclipse.jface.resource.JFaceResources; import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.ListenerList; import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.jface.util.SafeRunnable; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.ISelectionProvider; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.mylar.bugzilla.core.Attribute; import org.eclipse.mylar.bugzilla.core.BugPost; import org.eclipse.mylar.bugzilla.core.BugzillaPlugin; import org.eclipse.mylar.bugzilla.core.BugzillaPreferencePage; import org.eclipse.mylar.bugzilla.core.BugzillaRepository; import org.eclipse.mylar.bugzilla.core.BugzillaTools; import org.eclipse.mylar.bugzilla.core.Comment; import org.eclipse.mylar.bugzilla.core.IBugzillaAttributeListener; import org.eclipse.mylar.bugzilla.core.IBugzillaBug; import org.eclipse.mylar.bugzilla.core.IBugzillaConstants; import org.eclipse.mylar.bugzilla.core.IBugzillaReportSelection; import org.eclipse.mylar.bugzilla.core.IOfflineBugListener.BugzillaOfflineStaus; import org.eclipse.mylar.bugzilla.ui.BugzillaUITools; import org.eclipse.mylar.bugzilla.ui.OfflineView; import org.eclipse.mylar.bugzilla.ui.outline.BugzillaOutlineNode; import org.eclipse.mylar.bugzilla.ui.outline.BugzillaOutlinePage; import org.eclipse.mylar.bugzilla.ui.outline.BugzillaReportSelection; import org.eclipse.mylar.bugzilla.ui.tasklist.BugzillaTaskEditor; import org.eclipse.mylar.core.MylarPlugin; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CLabel; import org.eclipse.swt.custom.ScrolledComposite; import org.eclipse.swt.custom.StyleRange; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.events.ControlEvent; import org.eclipse.swt.events.ControlListener; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.MouseListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.FontData; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.ISelectionListener; import org.eclipse.ui.ISharedImages; import org.eclipse.ui.IWorkbenchActionConstants; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.actions.ActionFactory; import org.eclipse.ui.actions.RetargetAction; import org.eclipse.ui.forms.widgets.Hyperlink; import org.eclipse.ui.internal.WorkbenchImages; import org.eclipse.ui.internal.WorkbenchMessages; import org.eclipse.ui.internal.help.WorkbenchHelpSystem; import org.eclipse.ui.internal.ide.IDEInternalWorkbenchImages; import org.eclipse.ui.part.EditorPart; import org.eclipse.ui.views.contentoutline.ContentOutline; import org.eclipse.ui.views.contentoutline.IContentOutlinePage; /** * Abstract base implementation for an editor to view a bugzilla report. * * @author Mik Kersten (some hardening of prototype) */ public abstract class AbstractBugEditor extends EditorPart implements Listener { public static final int WRAP_LENGTH = 90; protected Display display; public static final Font TITLE_FONT = JFaceResources.getHeaderFont(); // TODO: don't use hard-coded font public static final Font TEXT_FONT = JFaceResources.getDefaultFont(); public static final Font COMMENT_FONT = JFaceResources.getFontRegistry().get(JFaceResources.TEXT_FONT); // new Font(null, "Courier New", 9, SWT.NORMAL); public static final Font HEADER_FONT = JFaceResources.getDefaultFont(); public static final int DESCRIPTION_WIDTH = 79 * 7; public static final int DESCRIPTION_HEIGHT = 10 * 14; protected Color background; protected Color foreground; protected AbstractBugEditorInput bugzillaInput; private BugzillaTaskEditor parentEditor = null; /** * Style option for function <code>newLayout</code>. This will create a * plain-styled, selectable text label. */ protected final String VALUE = "VALUE"; /** * Style option for function <code>newLayout</code>. This will create a * bolded, selectable header. It will also have an arrow image before the * text (simply for decoration). */ protected final String HEADER = "HEADER"; /** * Style option for function <code>newLayout</code>. This will create a * bolded, unselectable label. */ protected final String PROPERTY = "PROPERTY"; protected final int HORZ_INDENT = 0; protected Combo oSCombo; protected Combo versionCombo; protected Combo platformCombo; protected Combo priorityCombo; protected Combo severityCombo; protected Combo milestoneCombo; protected Combo componentCombo; protected Text urlText; protected Text summaryText; protected Text assignedTo; protected Button submitButton; // protected Button saveButton; protected int scrollIncrement; protected int scrollVertPageIncrement; protected int scrollHorzPageIncrement; public boolean isDirty = false; /** Manager controlling the context menu */ protected MenuManager contextMenuManager; protected StyledText currentSelectedText; protected static final String cutActionDefId = "org.eclipse.ui.edit.cut"; //$NON-NLS-1$ protected static final String copyActionDefId = "org.eclipse.ui.edit.copy"; //$NON-NLS-1$ protected static final String pasteActionDefId = "org.eclipse.ui.edit.paste"; //$NON-NLS-1$ protected RetargetAction cutAction; protected BugzillaEditorCopyAction copyAction; protected RetargetAction pasteAction; protected Composite editorComposite; protected CLabel titleLabel; protected ScrolledComposite scrolledComposite; protected Composite infoArea; protected Hyperlink linkToBug; protected StyledText generalTitleText; private List<IBugzillaAttributeListener> attributesListeners = new ArrayList<IBugzillaAttributeListener>(); protected final ISelectionProvider selectionProvider = new ISelectionProvider() { public void addSelectionChangedListener(ISelectionChangedListener listener) { selectionChangedListeners.add(listener); } public ISelection getSelection() { return null; } public void removeSelectionChangedListener(ISelectionChangedListener listener) { selectionChangedListeners.remove(listener); } public void setSelection(ISelection selection) { // No implementation. } }; protected ListenerList selectionChangedListeners = new ListenerList(); protected HashMap<Combo, String> comboListenerMap = new HashMap<Combo, String>(); private IBugzillaReportSelection lastSelected = null; protected final ISelectionListener selectionListener = new ISelectionListener() { public void selectionChanged(IWorkbenchPart part, ISelection selection) { if ((part instanceof ContentOutline) && (selection instanceof StructuredSelection)) { Object select = ((StructuredSelection) selection).getFirstElement(); if (select instanceof BugzillaOutlineNode) { BugzillaOutlineNode n = (BugzillaOutlineNode) select; if (n != null && lastSelected != null && BugzillaTools.getHandle(n).equals(BugzillaTools.getHandle(lastSelected))) { // we don't need to set the selection if it is alredy set return; } lastSelected = n; Object data = n.getData(); boolean highlight = true; if (n.getKey().toLowerCase().equals("comments")) { highlight = false; } if (n.getKey().toLowerCase().equals("new comment")) { selectNewComment(); } else if (n.getKey().toLowerCase().equals("new description")) { selectNewDescription(); } else if (data != null) { select(data, highlight); } } } } }; /** * Creates a new <code>AbstractBugEditor</code>. Sets up the default fonts and * cut/copy/paste actions. */ public AbstractBugEditor() { // set the scroll increments so the editor scrolls normally with the scroll wheel FontData[] fd = TEXT_FONT.getFontData(); int cushion = 4; scrollIncrement = fd[0].getHeight() + cushion; scrollVertPageIncrement = 0; scrollHorzPageIncrement = 0; // set up actions for the context menu cutAction = new RetargetAction(ActionFactory.CUT.getId(), WorkbenchMessages.Workbench_cut); cutAction.setToolTipText(WorkbenchMessages.Workbench_cutToolTip);//WorkbenchMessages.getString("Workbench.cutToolTip")); //$NON-NLS-1$ cutAction.setImageDescriptor(WorkbenchImages.getImageDescriptor(ISharedImages.IMG_TOOL_CUT)); cutAction.setHoverImageDescriptor(WorkbenchImages.getImageDescriptor(ISharedImages.IMG_TOOL_CUT)); cutAction.setDisabledImageDescriptor(WorkbenchImages.getImageDescriptor(ISharedImages.IMG_TOOL_CUT_DISABLED)); cutAction.setAccelerator(SWT.CTRL | 'x'); cutAction.setActionDefinitionId(cutActionDefId); pasteAction = new RetargetAction(ActionFactory.PASTE.getId(), WorkbenchMessages.Workbench_paste); pasteAction.setToolTipText(WorkbenchMessages.Workbench_pasteToolTip);//WorkbenchMessages.getString("Workbench.pasteToolTip")); //$NON-NLS-1$ pasteAction.setImageDescriptor(WorkbenchImages.getImageDescriptor(ISharedImages.IMG_TOOL_PASTE)); pasteAction.setHoverImageDescriptor(WorkbenchImages.getImageDescriptor(ISharedImages.IMG_TOOL_PASTE)); pasteAction.setDisabledImageDescriptor(WorkbenchImages.getImageDescriptor(ISharedImages.IMG_TOOL_PASTE_DISABLED)); pasteAction.setAccelerator(SWT.CTRL | 'v'); pasteAction.setActionDefinitionId(pasteActionDefId); copyAction = new BugzillaEditorCopyAction(this); copyAction.setText(WorkbenchMessages.Workbench_copy);//WorkbenchMessages.getString("Workbench.copy")); copyAction.setImageDescriptor(WorkbenchImages.getImageDescriptor(ISharedImages.IMG_TOOL_COPY)); copyAction.setHoverImageDescriptor(WorkbenchImages.getImageDescriptor(ISharedImages.IMG_TOOL_COPY)); copyAction.setDisabledImageDescriptor(WorkbenchImages.getImageDescriptor(ISharedImages.IMG_TOOL_COPY_DISABLED)); copyAction.setAccelerator(SWT.CTRL | 'c'); copyAction.setEnabled(false); } /** * @return The bug this editor is displaying. */ public abstract IBugzillaBug getBug(); /** * @return Any currently selected text. */ protected StyledText getCurrentText() { return currentSelectedText; } /** * @return The action used to copy selected text from a bug editor to the clipboard. */ protected BugzillaEditorCopyAction getCopyAction() { return copyAction; } @Override public void createPartControl(Composite parent) { editorComposite = new Composite(parent, SWT.NONE); GridLayout layout = new GridLayout(); layout.marginHeight = 0; layout.marginWidth = 0; layout.verticalSpacing = 0; layout.horizontalSpacing = 0; editorComposite.setLayout(layout); // Create the title for the editor createTitleArea(editorComposite); Label titleBarSeparator = new Label(editorComposite, SWT.HORIZONTAL | SWT.SEPARATOR); background = JFaceColors.getBannerBackground(display); foreground = JFaceColors.getBannerForeground(display); GridData gd = new GridData(GridData.FILL_HORIZONTAL); titleBarSeparator.setLayoutData(gd); // Put the bug info onto the editor createInfoArea(editorComposite); WorkbenchHelpSystem.getInstance().setHelp(editorComposite, IBugzillaConstants.EDITOR_PAGE_CONTEXT); infoArea.setMenu(contextMenuManager.createContextMenu(infoArea)); getSite().getPage().addSelectionListener(selectionListener); getSite().setSelectionProvider(selectionProvider); } /** * Creates the title label at the top of the editor. * * @param parent * The composite to put the title label into. * @return The title composite. */ protected Composite createTitleArea(Composite parent) { // Get the background color for the title area display = parent.getDisplay(); background = JFaceColors.getBannerBackground(display); foreground = JFaceColors.getBannerForeground(display); // Create the title area which will contain // a title, message, and image. Composite titleArea = new Composite(parent, SWT.NO_FOCUS); GridLayout layout = new GridLayout(); layout.marginHeight = 0; layout.marginWidth = 0; layout.verticalSpacing = 0; layout.horizontalSpacing = 0; layout.numColumns = 2; titleArea.setLayout(layout); titleArea.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); titleArea.setBackground(background); // Message label titleLabel = new CLabel(titleArea, SWT.LEFT); JFaceColors.setColors(titleLabel, foreground, background); titleLabel.setFont(TITLE_FONT); final IPropertyChangeListener fontListener = new IPropertyChangeListener() { public void propertyChange(PropertyChangeEvent event) { if (JFaceResources.HEADER_FONT.equals(event.getProperty())) { titleLabel.setFont(TITLE_FONT); } } }; titleLabel.addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent event) { JFaceResources.getFontRegistry().removeListener(fontListener); } }); JFaceResources.getFontRegistry().addListener(fontListener); GridData gd = new GridData(GridData.FILL_BOTH); titleLabel.setLayoutData(gd); // Title image Label titleImage = new Label(titleArea, SWT.LEFT); titleImage.setBackground(background); titleImage.setImage(WorkbenchImages.getImage(IDEInternalWorkbenchImages.IMG_OBJS_WELCOME_BANNER)); gd = new GridData(); gd.horizontalAlignment = GridData.END; titleImage.setLayoutData(gd); return titleArea; } /** * Creates the part of the editor that contains the information about the * the bug. * * @param parent * The composite to put the info area into. * @return The info area composite. */ protected Composite createInfoArea(Composite parent) { createContextMenu(); scrolledComposite = new ScrolledComposite(parent, SWT.V_SCROLL | SWT.H_SCROLL); scrolledComposite.setLayoutData(new GridData(GridData.FILL_BOTH)); infoArea = new Composite(this.scrolledComposite, SWT.NONE); scrolledComposite.setMinSize(infoArea.computeSize(SWT.DEFAULT, SWT.DEFAULT)); GridLayout infoLayout = new GridLayout(); infoLayout.numColumns = 1; infoLayout.verticalSpacing = 0; infoLayout.horizontalSpacing = 0; infoLayout.marginWidth = 0; infoArea.setLayout(infoLayout); infoArea.setBackground(background); if (getBug() == null) { // close(); MessageDialog.openError(Display.getDefault().getActiveShell(), "Bugzilla Client Errror", "Could not resolve the requested bug, check Bugzilla server and version."); Composite composite = new Composite(parent, SWT.NULL); Label noBugLabel = new Label(composite, SWT.NULL); noBugLabel.setText("Could not resolve bug"); return composite; } createLayouts(); this.scrolledComposite.setContent(infoArea); Point p = infoArea.computeSize(SWT.DEFAULT, SWT.DEFAULT, true); this.scrolledComposite.setMinHeight(p.y); this.scrolledComposite.setMinWidth(p.x); this.scrolledComposite.setExpandHorizontal(true); this.scrolledComposite.setExpandVertical(true); // make the editor scroll properly with a scroll editor scrolledComposite.addControlListener(new ControlListener() { public void controlMoved(ControlEvent e) { // don't care when the control moved } public void controlResized(ControlEvent e) { scrolledComposite.getVerticalBar().setIncrement(scrollIncrement); scrolledComposite.getHorizontalBar().setIncrement(scrollIncrement); scrollVertPageIncrement = scrolledComposite.getClientArea().height; scrollHorzPageIncrement = scrolledComposite.getClientArea().width; scrolledComposite.getVerticalBar().setPageIncrement(scrollVertPageIncrement); scrolledComposite.getHorizontalBar().setPageIncrement(scrollHorzPageIncrement); } }); return infoArea; } /** * Create a context menu for this editor. */ protected void createContextMenu() { contextMenuManager = new MenuManager("#BugEditor"); contextMenuManager.setRemoveAllWhenShown(true); contextMenuManager.addMenuListener(new IMenuListener() { public void menuAboutToShow(IMenuManager manager) { manager.add(cutAction); manager.add(copyAction); manager.add(pasteAction); manager.add(new Separator()); manager.add(new GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS)); if (currentSelectedText == null || currentSelectedText.getSelectionText().length() == 0) { copyAction.setEnabled(false); } else { copyAction.setEnabled(true); } } }); getSite().registerContextMenu("#BugEditor", contextMenuManager, getSite().getSelectionProvider()); } /** * Creates all of the layouts that display the information on * the bug. */ protected void createLayouts() { createAttributeLayout(); createDescriptionLayout(); createCommentLayout(); createButtonLayouts(); } /** * Creates the attribute layout, which contains most of the basic attributes * of the bug (some of which are editable). */ protected void createAttributeLayout() { String title = getTitleString(); String keywords = ""; String url = ""; // Attributes Composite- this holds all the combo fiels and text // fields Composite attributesComposite = new Composite(infoArea, SWT.NONE); GridLayout attributesLayout = new GridLayout(); attributesLayout.numColumns = 4; attributesLayout.horizontalSpacing = 14; attributesLayout.verticalSpacing = 6; attributesComposite.setLayout(attributesLayout); GridData attributesData = new GridData(GridData.FILL_BOTH); attributesData.horizontalSpan = 1; attributesData.grabExcessVerticalSpace = false; attributesComposite.setLayoutData(attributesData); attributesComposite.setBackground(background); // End Attributes Composite // Attributes Title Area Composite attributesTitleComposite = new Composite(attributesComposite, SWT.NONE); GridLayout attributesTitleLayout = new GridLayout(); attributesTitleLayout.horizontalSpacing = 0; attributesTitleLayout.marginWidth = 0; attributesTitleComposite.setLayout(attributesTitleLayout); attributesTitleComposite.setBackground(background); GridData attributesTitleData = new GridData(GridData.HORIZONTAL_ALIGN_FILL); attributesTitleData.horizontalSpan = 4; attributesTitleData.grabExcessVerticalSpace = false; attributesTitleComposite.setLayoutData(attributesTitleData); // End Attributes Title // Set the Attributes Title newAttributesLayout(attributesTitleComposite); titleLabel.setText(title); bugzillaInput.setToolTipText(title); int currentCol = 1; String ccValue = null; // Populate Attributes for (Iterator<Attribute> it = getBug().getAttributes().iterator(); it.hasNext();) { Attribute attribute = it.next(); String key = attribute.getParameterName(); String name = attribute.getName(); String value = checkText(attribute.getValue()); Map<String, String> values = attribute.getOptionValues(); // make sure we don't try to display a hidden field if (attribute.isHidden() || (key != null && key.equals("status_whiteboard"))) continue; if (values == null) values = new HashMap<String, String>(); if (key == null) key = ""; GridData data = new GridData(GridData.HORIZONTAL_ALIGN_FILL); data.horizontalSpan = 1; data.horizontalIndent = HORZ_INDENT; if (key.equals("short_desc") || key.equals("keywords")) { keywords = value; } else if (key.equals("newcc")) { ccValue = value; if (value == null) ccValue = ""; } else if (key.equals("bug_file_loc")) { url = value; } else if (key.equals("op_sys")) { newLayout(attributesComposite, 1, name, PROPERTY); oSCombo = new Combo(attributesComposite, SWT.NO_BACKGROUND | SWT.MULTI | SWT.V_SCROLL | SWT.READ_ONLY); oSCombo.setFont(TEXT_FONT); oSCombo.setLayoutData(data); oSCombo.setBackground(background); Set<String> s = values.keySet(); String[] a = s.toArray(new String[s.size()]); Arrays.sort(a); for (int i = 0; i < a.length; i++) { oSCombo.add(a[i]); } - oSCombo.select(oSCombo.indexOf(value)); + if (oSCombo.indexOf(value) != -1) { + oSCombo.select(oSCombo.indexOf(value)); + } else { + oSCombo.select(oSCombo.indexOf("All")); + } oSCombo.addListener(SWT.Modify, this); comboListenerMap.put(oSCombo, name); oSCombo.addListener(SWT.FocusIn, new GenericListener()); currentCol += 2; } else if (key.equals("version")) { newLayout(attributesComposite, 1, name, PROPERTY); versionCombo = new Combo(attributesComposite, SWT.NO_BACKGROUND | SWT.MULTI | SWT.V_SCROLL | SWT.READ_ONLY); versionCombo.setFont(TEXT_FONT); versionCombo.setLayoutData(data); versionCombo.setBackground(background); Set<String> s = values.keySet(); String[] a = s.toArray(new String[s.size()]); Arrays.sort(a); for (int i = 0; i < a.length; i++) { versionCombo.add(a[i]); } versionCombo.select(versionCombo.indexOf(value)); versionCombo.addListener(SWT.Modify, this); versionCombo.addListener(SWT.FocusIn, new GenericListener()); comboListenerMap.put(versionCombo, name); currentCol += 2; } else if (key.equals("priority")) { newLayout(attributesComposite, 1, name, PROPERTY); priorityCombo = new Combo(attributesComposite, SWT.NO_BACKGROUND | SWT.MULTI | SWT.V_SCROLL | SWT.READ_ONLY); priorityCombo.setFont(TEXT_FONT); priorityCombo.setLayoutData(data); priorityCombo.setBackground(background); Set<String> s = values.keySet(); String[] a = s.toArray(new String[s.size()]); Arrays.sort(a); for (int i = 0; i < a.length; i++) { priorityCombo.add(a[i]); } priorityCombo.select(priorityCombo.indexOf(value)); priorityCombo.addListener(SWT.Modify, this); priorityCombo.addListener(SWT.FocusIn, new GenericListener()); comboListenerMap.put(priorityCombo, name); currentCol += 2; } else if (key.equals("bug_severity")) { newLayout(attributesComposite, 1, name, PROPERTY); severityCombo = new Combo(attributesComposite, SWT.NO_BACKGROUND | SWT.MULTI | SWT.V_SCROLL | SWT.READ_ONLY); severityCombo.setFont(TEXT_FONT); severityCombo.setLayoutData(data); severityCombo.setBackground(background); Set<String> s = values.keySet(); String[] a = s.toArray(new String[s.size()]); Arrays.sort(a); for (int i = 0; i < a.length; i++) { severityCombo.add(a[i]); } severityCombo.select(severityCombo.indexOf(value)); severityCombo.addListener(SWT.Modify, this); severityCombo.addListener(SWT.FocusIn, new GenericListener()); comboListenerMap.put(severityCombo, name); currentCol += 2; } else if (key.equals("target_milestone")) { newLayout(attributesComposite, 1, name, PROPERTY); milestoneCombo = new Combo(attributesComposite, SWT.NO_BACKGROUND | SWT.MULTI | SWT.V_SCROLL | SWT.READ_ONLY); milestoneCombo.setFont(TEXT_FONT); milestoneCombo.setLayoutData(data); milestoneCombo.setBackground(background); Set<String> s = values.keySet(); String[] a = s.toArray(new String[s.size()]); Arrays.sort(a); for (int i = 0; i < a.length; i++) { milestoneCombo.add(a[i]); } milestoneCombo.select(milestoneCombo.indexOf(value)); milestoneCombo.addListener(SWT.Modify, this); milestoneCombo.addListener(SWT.FocusIn, new GenericListener()); comboListenerMap.put(milestoneCombo, name); currentCol += 2; } else if (key.equals("rep_platform")) { newLayout(attributesComposite, 1, name, PROPERTY); platformCombo = new Combo(attributesComposite, SWT.NO_BACKGROUND | SWT.MULTI | SWT.V_SCROLL | SWT.READ_ONLY); platformCombo.setFont(TEXT_FONT); platformCombo.setLayoutData(data); platformCombo.setBackground(background); Set<String> s = values.keySet(); String[] a = s.toArray(new String[s.size()]); Arrays.sort(a); for (int i = 0; i < a.length; i++) { platformCombo.add(a[i]); } platformCombo.select(platformCombo.indexOf(value)); platformCombo.addListener(SWT.Modify, this); platformCombo.addListener(SWT.FocusIn, new GenericListener()); comboListenerMap.put(platformCombo, name); currentCol += 2; } else if (key.equals("product")) { newLayout(attributesComposite, 1, name, PROPERTY); newLayout(attributesComposite, 1, value, VALUE).addListener(SWT.FocusIn, new GenericListener()); currentCol += 2; } else if (key.equals("assigned_to")) { newLayout(attributesComposite, 1, name, PROPERTY); assignedTo = new Text(attributesComposite, SWT.BORDER | SWT.SINGLE | SWT.WRAP); assignedTo.setFont(TEXT_FONT); assignedTo.setText(value); data = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); data.horizontalSpan = 1; assignedTo.setLayoutData(data); assignedTo.addListener(SWT.KeyUp, new Listener() { public void handleEvent(Event event) { String sel = assignedTo.getText(); Attribute a = getBug().getAttribute("Assign To"); if (!(a.getNewValue().equals(sel))) { a.setNewValue(sel); changeDirtyStatus(true); } } }); assignedTo.addListener(SWT.FocusIn, new GenericListener()); currentCol += 2; } else if (key.equals("component")) { newLayout(attributesComposite, 1, name, PROPERTY); componentCombo = new Combo(attributesComposite, SWT.NO_BACKGROUND | SWT.MULTI | SWT.V_SCROLL | SWT.READ_ONLY); componentCombo.setFont(TEXT_FONT); componentCombo.setLayoutData(data); componentCombo.setBackground(background); Set<String> s = values.keySet(); String[] a = s.toArray(new String[s.size()]); Arrays.sort(a); for (int i = 0; i < a.length; i++) { componentCombo.add(a[i]); } componentCombo.select(componentCombo.indexOf(value)); componentCombo.addListener(SWT.Modify, this); componentCombo.addListener(SWT.FocusIn, new GenericListener()); comboListenerMap.put(componentCombo, name); currentCol += 2; } else if (name.equals("Summary")) { // Don't show the summary here. continue; } else if (values.isEmpty()) { newLayout(attributesComposite, 1, name, PROPERTY); newLayout(attributesComposite, 1, value, VALUE).addListener(SWT.FocusIn, new GenericListener()); currentCol += 2; } if (currentCol > attributesLayout.numColumns) { currentCol -= attributesLayout.numColumns; } } // End Populate Attributes // make sure that we are in the first column if (currentCol > 1) { while (currentCol <= attributesLayout.numColumns) { newLayout(attributesComposite, 1, "", PROPERTY); currentCol++; } } // URL, Keywords, Summary Text Fields addUrlText(url, attributesComposite); // keywords text field (not editable) addKeywordsList(keywords, attributesComposite); if (ccValue != null) { addCCList(ccValue, attributesComposite); } addSummaryText(attributesComposite); // End URL, Keywords, Summary Text Fields } /** * Adds a text field to display and edit the bug's URL attribute. * * @param url * The URL attribute of the bug. * @param attributesComposite * The composite to add the text field to. */ protected void addUrlText(String url, Composite attributesComposite) { newLayout(attributesComposite, 1, "URL:", PROPERTY); urlText = new Text(attributesComposite, SWT.BORDER | SWT.SINGLE | SWT.WRAP); urlText.setFont(TEXT_FONT); GridData urlTextData = new GridData(GridData.HORIZONTAL_ALIGN_FILL); urlTextData.horizontalSpan = 3; urlTextData.widthHint = 200; urlText.setLayoutData(urlTextData); urlText.setText(url); urlText.addListener(SWT.KeyUp, new Listener() { public void handleEvent(Event event) { String sel = urlText.getText(); Attribute a = getBug().getAttribute("URL"); if (!(a.getNewValue().equals(sel))) { a.setNewValue(sel); changeDirtyStatus(true); } } }); urlText.addListener(SWT.FocusIn, new GenericListener()); } /** * Adds a text field and selection list to display and edit the bug's * keywords. * * @param keywords * The current list of keywords for this bug. * @param attributesComposite * The composite to add the widgets to. */ protected abstract void addKeywordsList(String keywords, Composite attributesComposite); protected abstract void addCCList(String value, Composite attributesComposite); /** * Adds a text field to display and edit the bug's summary. * * @param attributesComposite * The composite to add the text field to. */ protected void addSummaryText(Composite attributesComposite) { newLayout(attributesComposite, 1, "Summary:", PROPERTY); summaryText = new Text(attributesComposite, SWT.BORDER | SWT.SINGLE | SWT.WRAP); summaryText.setFont(TEXT_FONT); GridData summaryTextData = new GridData(GridData.HORIZONTAL_ALIGN_FILL); summaryTextData.horizontalSpan = 3; summaryTextData.widthHint = 200; summaryText.setLayoutData(summaryTextData); summaryText.setText(getBug().getSummary()); summaryText.addListener(SWT.KeyUp, new SummaryListener()); summaryText.addListener(SWT.FocusIn, new GenericListener()); } /** * Creates the description layout, which displays and possibly edits the * bug's description. */ protected abstract void createDescriptionLayout(); /** * Creates the comment layout, which displays the bug's comments and * possibly lets the user enter a new one. */ protected abstract void createCommentLayout(); /** * Creates the button layout. This displays options and buttons at the * bottom of the editor to allow actions to be performed on the bug. */ protected void createButtonLayouts() { Composite buttonComposite = new Composite(infoArea, SWT.NONE); GridLayout buttonLayout = new GridLayout(); buttonLayout.numColumns = 4; buttonComposite.setLayout(buttonLayout); buttonComposite.setBackground(background); GridData buttonData = new GridData(GridData.FILL_BOTH); buttonData.horizontalSpan = 1; buttonData.grabExcessVerticalSpace = false; buttonComposite.setLayoutData(buttonData); addRadioButtons(buttonComposite); addActionButtons(buttonComposite); } /** * Adds radio buttons to this composite. * @param buttonComposite Composite to add the radio buttons to. */ abstract protected void addRadioButtons(Composite buttonComposite); /** * Adds buttons to this composite. * Subclasses can override this method to provide different/additional buttons. * @param buttonComposite Composite to add the buttons to. */ protected void addActionButtons(Composite buttonComposite) { submitButton = new Button(buttonComposite, SWT.NONE); submitButton.setFont(TEXT_FONT); GridData submitButtonData = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); submitButtonData.widthHint = AbstractBugEditor.WRAP_LENGTH; submitButtonData.heightHint = 20; submitButton.setText("Submit"); submitButton.setLayoutData(submitButtonData); submitButton.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { submitBug(); } }); submitButton.addListener(SWT.FocusIn, new GenericListener()); // This is not needed anymore since we have the save working properly with ctrl-s and file->save // saveButton = new Button(buttonComposite, SWT.NONE); // saveButton.setFont(TEXT_FONT); // GridData saveButtonData = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); // saveButtonData.widthHint = 100; // saveButtonData.heightHint = 20; // saveButton.setText("Save Offline"); // saveButton.setLayoutData(saveButtonData); // saveButton.addListener(SWT.Selection, new Listener() { // public void handleEvent(Event e) { // saveBug(); // updateEditor(); // } // }); // saveButton.addListener(SWT.FocusIn, new GenericListener()); } /** * Make sure that a String that is <code>null</code> is changed to a null * string * * @param text * The text to check if it is null or not * @return If the text is <code>null</code>, then return the null string (<code>""</code>). * Otherwise, return the text. */ public String checkText(String text) { if (text == null) return ""; else return text; } /** * @return A string to use as a title for this editor. */ protected abstract String getTitleString(); /** * Creates an uneditable text field for displaying data. * * @param composite * The composite to put this text field into. Its layout style * should be a grid with columns. * @param colSpan * The number of columns that this text field should span. * @param text * The text that for this text field. * @param style * The style for this text field. See below for valid values * (default is HEADER). * @return The new styled text. * @see VALUE * @see PROPERTY * @see HEADER */ protected StyledText newLayout(Composite composite, int colSpan, String text, String style) { GridData data = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); data.horizontalSpan = colSpan; StyledText stext; if (style.equalsIgnoreCase(VALUE)) { StyledText styledText = new StyledText(composite, SWT.MULTI | SWT.READ_ONLY); styledText.setFont(TEXT_FONT); styledText.setText(checkText(text)); styledText.setBackground(background); data.horizontalIndent = HORZ_INDENT; styledText.setLayoutData(data); styledText.setEditable(false); styledText.getCaret().setVisible(false); styledText.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { StyledText c = (StyledText) e.widget; if (c != null && c.getSelectionCount() > 0) { if (currentSelectedText != null) { if (!c.equals(currentSelectedText)) { currentSelectedText.setSelectionRange(0, 0); } } } currentSelectedText = c; } }); styledText.setMenu(contextMenuManager.createContextMenu(styledText)); stext = styledText; } else if (style.equalsIgnoreCase(PROPERTY)) { StyledText styledText = new StyledText(composite, SWT.MULTI | SWT.READ_ONLY); styledText.setFont(TEXT_FONT); styledText.setText(checkText(text)); styledText.setBackground(background); data.horizontalIndent = HORZ_INDENT; styledText.setLayoutData(data); StyleRange sr = new StyleRange(styledText.getOffsetAtLine(0), text.length(), foreground, background, SWT.BOLD); styledText.setStyleRange(sr); styledText.getCaret().setVisible(false); styledText.setEnabled(false); styledText.setMenu(contextMenuManager.createContextMenu(styledText)); stext = styledText; } else { Composite generalTitleGroup = new Composite(composite, SWT.NONE); generalTitleGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); generalTitleGroup.setLayoutData(data); GridLayout generalTitleLayout = new GridLayout(); generalTitleLayout.numColumns = 2; generalTitleLayout.marginWidth = 0; generalTitleLayout.marginHeight = 9; generalTitleGroup.setLayout(generalTitleLayout); generalTitleGroup.setBackground(background); Label image = new Label(generalTitleGroup, SWT.NONE); image.setBackground(background); image.setImage(WorkbenchImages.getImage(IDEInternalWorkbenchImages.IMG_OBJS_WELCOME_ITEM)); GridData gd = new GridData(GridData.FILL_BOTH); gd.verticalAlignment = GridData.VERTICAL_ALIGN_BEGINNING; image.setLayoutData(gd); StyledText titleText = new StyledText(generalTitleGroup, SWT.MULTI | SWT.READ_ONLY); titleText.setText(checkText(text)); titleText.setFont(HEADER_FONT); titleText.setBackground(background); StyleRange sr = new StyleRange(titleText.getOffsetAtLine(0), text.length(), foreground, background, SWT.BOLD); titleText.setStyleRange(sr); titleText.getCaret().setVisible(false); titleText.setEditable(false); titleText.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { StyledText c = (StyledText) e.widget; if (c != null && c.getSelectionCount() > 0) { if (currentSelectedText != null) { if (!c.equals(currentSelectedText)) { currentSelectedText.setSelectionRange(0, 0); } } } currentSelectedText = c; } }); // create context menu generalTitleGroup.setMenu(contextMenuManager.createContextMenu(generalTitleGroup)); titleText.setMenu(contextMenuManager.createContextMenu(titleText)); image.setMenu(contextMenuManager.createContextMenu(image)); stext = titleText; } composite.setMenu(contextMenuManager.createContextMenu(composite)); return stext; } /** * This creates the title header for the info area. Its style is similar to * one from calling the function <code>newLayout</code> with the style * <code>HEADER</code>. * * @param composite * The composite to put this text field into. Its layout style * should be a grid with columns. */ protected void newAttributesLayout(Composite composite) { GridData data = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); data.horizontalSpan = 4; Composite generalTitleGroup = new Composite(composite, SWT.NONE); generalTitleGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); generalTitleGroup.setLayoutData(data); GridLayout generalTitleLayout = new GridLayout(); generalTitleLayout.numColumns = 3; generalTitleLayout.marginWidth = 0; generalTitleLayout.marginHeight = 9; generalTitleGroup.setLayout(generalTitleLayout); generalTitleGroup.setBackground(background); Label image = new Label(generalTitleGroup, SWT.NONE); image.setBackground(background); image.setImage(WorkbenchImages.getImage(IDEInternalWorkbenchImages.IMG_OBJS_WELCOME_ITEM)); GridData gd = new GridData(GridData.FILL_BOTH); gd.verticalAlignment = GridData.VERTICAL_ALIGN_BEGINNING; image.setLayoutData(gd); generalTitleText = new StyledText(generalTitleGroup, SWT.MULTI | SWT.READ_ONLY); generalTitleText.setBackground(background); generalTitleText.getCaret().setVisible(false); generalTitleText.setEditable(false); generalTitleText.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { StyledText c = (StyledText) e.widget; if (c != null && c.getSelectionCount() > 0) { if (currentSelectedText != null) { if (!c.equals(currentSelectedText)) { currentSelectedText.setSelectionRange(0, 0); } } } currentSelectedText = c; } }); // create context menu generalTitleGroup.setMenu(contextMenuManager.createContextMenu(generalTitleGroup)); generalTitleText.setMenu(contextMenuManager.createContextMenu(generalTitleText)); linkToBug = new Hyperlink(generalTitleGroup, SWT.MULTI | SWT.READ_ONLY); linkToBug.setBackground(background); setGeneralTitleText(); image.setMenu(contextMenuManager.createContextMenu(image)); composite.setMenu(contextMenuManager.createContextMenu(composite)); } /** * This refreshes the text in the title label of the info area (it contains * elements which can change). */ protected void setGeneralTitleText() { String text = "[Open in New Browser]"; linkToBug.setText(text); linkToBug.setFont(TEXT_FONT); if (this instanceof ExistingBugEditor) { linkToBug.setUnderlined(true); linkToBug.setForeground(JFaceColors.getHyperlinkText(Display.getCurrent())); linkToBug.addMouseListener(new MouseListener() { public void mouseDoubleClick(MouseEvent e) { } public void mouseUp(MouseEvent e) { } public void mouseDown(MouseEvent e) { BugzillaUITools.openUrl(getTitle(), getTitleToolTip(), BugzillaRepository.getBugUrlWithoutLogin(bugzillaInput.getBug().getId())); if (e.stateMask == SWT.MOD3) { // XXX come back to look at this ui close(); } } }); } else { linkToBug.setEnabled(false); } linkToBug.addListener(SWT.FocusIn, new GenericListener()); // Resize the composite, in case the new summary is longer than the // previous one. // Then redraw it to show the changes. linkToBug.getParent().pack(true); linkToBug.redraw(); text = getTitleString(); generalTitleText.setText(text); StyleRange sr = new StyleRange(generalTitleText.getOffsetAtLine(0), text.length(), foreground, background, SWT.BOLD); generalTitleText.setStyleRange(sr); generalTitleText.addListener(SWT.FocusIn, new GenericListener()); // Resize the composite, in case the new summary is longer than the // previous one. // Then redraw it to show the changes. generalTitleText.getParent().pack(true); generalTitleText.redraw(); } /** * Creates some blank space underneath the supplied composite. * * @param parent * The composite to add the blank space to. */ protected void createSeparatorSpace(Composite parent) { GridData separatorData = new GridData(GridData.HORIZONTAL_ALIGN_FILL); separatorData.verticalSpan = 1; separatorData.grabExcessVerticalSpace = false; Composite separatorComposite = new Composite(parent, SWT.NONE); GridLayout separatorLayout = new GridLayout(); separatorLayout.marginHeight = 0; separatorLayout.verticalSpacing = 0; separatorComposite.setLayout(separatorLayout); separatorComposite.setBackground(background); separatorComposite.setLayoutData(separatorData); newLayout(separatorComposite, 1, "", VALUE); } /** * Submit the changes to the bug to the bugzilla server. */ protected abstract void submitBug(); /** * If there is no locally saved copy of the current bug, then it saved * offline. Otherwise, any changes are updated in the file. */ public void saveBug() { try { updateBug(); IBugzillaBug bug = getBug(); if (bug.hasChanges()) { BugzillaPlugin.getDefault().fireOfflineStatusChanged(bug, BugzillaOfflineStaus.SAVED_WITH_OUTGOING_CHANGES); } else { BugzillaPlugin.getDefault().fireOfflineStatusChanged(bug, BugzillaOfflineStaus.SAVED); } changeDirtyStatus(false); OfflineView.saveOffline(getBug(), true); } catch (Exception e) { MylarPlugin.fail(e, "bug save offline failed", true); } // OfflineView.checkWindow(); // OfflineView.refreshView(); } /** * Updates the <code>IBugzillaBug</code> object to contain the latest data * entered in the data fields. */ protected abstract void updateBug(); /** * Resets the data fields to contain the data currently in the * <code>IBugzillaBug</code> object. */ protected abstract void restoreBug(); /** * Refreshes any text labels in the editor that contain information that * might change. */ protected void updateEditor() { // Reset all summary occurrences, since it might have // been edited. String title = getTitleString(); titleLabel.setText(title); setGeneralTitleText(); } /** * Break text up into lines of about 80 characters so that it is displayed * properly in bugzilla * * @param origText The string to be formatted * @return The formatted text */ protected String formatText(String origText) { if (BugzillaPlugin.getDefault().isServerCompatability220()) { return origText; } String[] textArray = new String[(origText.length() / WRAP_LENGTH + 1) * 2]; for (int i = 0; i < textArray.length; i++) textArray[i] = null; int j = 0; while (true) { int spaceIndex = origText.indexOf(" ", WRAP_LENGTH - 5); if (spaceIndex == origText.length() || spaceIndex == -1) { textArray[j] = origText; break; } textArray[j] = origText.substring(0, spaceIndex); origText = origText.substring(spaceIndex + 1, origText.length()); j++; } String newText = ""; for (int i = 0; i < textArray.length; i++) { if (textArray[i] == null) break; newText += textArray[i] + "\n"; } return newText; } /** * function to set the url to post the bug to * @param form A reference to a BugPost that the bug is going to be posted to * @param formName The form that we wish to use to submit the bug */ protected void setURL(BugPost form, String formName) { String baseURL = BugzillaPlugin.getDefault().getServerName(); if (!baseURL.endsWith("/")) baseURL += "/"; try { form.setURL(baseURL + formName); } catch (MalformedURLException e) { // we should be ok here } // add the login information to the bug post form.add("Bugzilla_login", BugzillaPreferencePage.getUserName()); form.add("Bugzilla_password", BugzillaPreferencePage.getPassword()); } @Override public void setFocus() { scrolledComposite.setFocus(); } @Override public boolean isDirty() { return isDirty; } /** * Updates the dirty status of this editor page. The dirty status is true if * the bug report has been modified but not saved. The title of the editor * is also updated to reflect the status. * * @param newDirtyStatus * is true when the bug report has been modified but not saved */ public void changeDirtyStatus(boolean newDirtyStatus) { isDirty = newDirtyStatus; if (parentEditor == null) { firePropertyChange(PROP_DIRTY); } else { parentEditor.updatePartName(); } } /** * Updates the title of the editor to reflect dirty status. * If the bug report has been modified but not saved, then * an indicator will appear in the title. */ protected void updateEditorTitle() { setPartName(bugzillaInput.getName()); } @Override public boolean isSaveAsAllowed() { return false; } @Override public void doSave(IProgressMonitor monitor) { saveBug(); updateEditor(); // XXX notify that saved ofline? } @Override public void doSaveAs() { // we don't save, so no need to implement } /** * @return The composite for the whole editor. */ public Composite getEditorComposite() { return editorComposite; } @Override public void dispose() { super.dispose(); isDisposed = true; getSite().getPage().removeSelectionListener(selectionListener); } public void handleEvent(Event event) { if (event.widget instanceof Combo) { Combo combo = (Combo) event.widget; if (comboListenerMap.containsKey(combo)) { String sel = combo.getItem(combo.getSelectionIndex()); Attribute a = getBug().getAttribute(comboListenerMap.get(combo)); if (!(a.getNewValue().equals(sel))) { a.setNewValue(sel); for (IBugzillaAttributeListener client : attributesListeners) { client.attributeChanged(a.getName(), sel); } changeDirtyStatus(true); } } } } /** * Fires a <code>SelectionChangedEvent</code> to all listeners registered * under <code>selectionChangedListeners</code>. * * @param event * The selection event. */ protected void fireSelectionChanged(final SelectionChangedEvent event) { Object[] listeners = selectionChangedListeners.getListeners(); for (int i = 0; i < listeners.length; i++) { final ISelectionChangedListener l = (ISelectionChangedListener) listeners[i]; SafeRunnable.run(new SafeRunnable() { public void run() { l.selectionChanged(event); } }); } } /** * A generic listener for selection of unimportant items. The default * selection item sent out is the entire bug object. */ protected class GenericListener implements Listener { public void handleEvent(Event event) { IBugzillaBug bug = getBug(); fireSelectionChanged(new SelectionChangedEvent(selectionProvider, new StructuredSelection(new BugzillaReportSelection(bug.getId(), bug.getServer(), bug.getLabel(), false, bug.getSummary())))); } } /** * A listener to check if the summary field was modified. */ protected class SummaryListener implements Listener { public void handleEvent(Event event) { handleSummaryEvent(); } } /** * Check if the summary field was modified, and update it if necessary. */ public abstract void handleSummaryEvent(); /*----------------------------------------------------------* * CODE TO SCROLL TO A COMMENT OR OTHER PIECE OF TEXT *----------------------------------------------------------*/ /** List of the StyledText's so that we can get the previous and the next */ protected ArrayList<StyledText> texts = new ArrayList<StyledText>(); protected HashMap<Object, StyledText> textHash = new HashMap<Object, StyledText>(); /** Index into the styled texts*/ protected int textsindex = 0; protected Text addCommentsTextBox = null; protected Text descriptionTextBox = null; private StyledText previousText = null; /** * Selects the given object in the editor. * * @param commentNumber * The comment number to be selected */ public void select(int commentNumber) { if (commentNumber == -1) return; for (Object o : textHash.keySet()) { if (o instanceof Comment) { if (((Comment) o).getNumber() == commentNumber) { select(o, true); } } } } /** * Selects the given object in the editor. * * @param o * The object to be selected. * @param highlight * Whether or not the object should be highlighted. */ public void select(Object o, boolean highlight) { if (textHash.containsKey(o)) { StyledText t = textHash.get(o); if (t != null) { focusOn(t, highlight); } } else if (o instanceof IBugzillaBug) { focusOn(null, highlight); } } public void selectDescription() { for (Object o : textHash.keySet()) { if (o.equals(bugzillaInput.getBug().getDescription())) { select(o, true); } } } public void selectNewComment() { focusOn(addCommentsTextBox, false); } public void selectNewDescription() { focusOn(descriptionTextBox, false); } /** * Scroll to a specified piece of text * @param selectionComposite The StyledText to scroll to */ private void focusOn(Control selectionComposite, boolean highlight) { int pos = 0; if (previousText != null && !previousText.isDisposed()) { previousText.setSelection(0); } if (selectionComposite instanceof StyledText) previousText = (StyledText) selectionComposite; if (selectionComposite != null) { if (highlight && selectionComposite instanceof StyledText && !selectionComposite.isDisposed()) ((StyledText) selectionComposite).setSelection(0, ((StyledText) selectionComposite).getText().length()); // get the position of the text in the composite pos = 0; Control s = selectionComposite; if (s.isDisposed()) return; s.setEnabled(true); s.setFocus(); s.forceFocus(); while (s != null && s != getEditorComposite()) { if (!s.isDisposed()) { pos += s.getLocation().y; s = s.getParent(); } } pos = scrolledComposite.getOrigin().y + pos - 60; } if (!scrolledComposite.isDisposed()) scrolledComposite.setOrigin(0, pos); } private BugzillaOutlinePage outlinePage = null; @Override public Object getAdapter(Class adapter) { if (IContentOutlinePage.class.equals(adapter)) { if (outlinePage == null && bugzillaInput != null) { outlinePage = new BugzillaOutlinePage(model); } return outlinePage; } return super.getAdapter(adapter); } protected BugzillaOutlineNode model = null; public BugzillaOutlineNode getModel() { return model; } public BugzillaOutlinePage getOutline() { return outlinePage; } private boolean isDisposed = false; public boolean isDisposed() { return isDisposed; } public void close() { Display activeDisplay = getSite().getShell().getDisplay(); activeDisplay.asyncExec(new Runnable() { public void run() { if (getSite() != null && getSite().getPage() != null && !AbstractBugEditor.this.isDisposed()) getSite().getPage().closeEditor(AbstractBugEditor.this, false); } }); } public void addAttributeListener(IBugzillaAttributeListener listener) { attributesListeners.add(listener); } public void removeAttributeListener(IBugzillaAttributeListener listener) { attributesListeners.remove(listener); } public void setParentEditor(BugzillaTaskEditor editor) { parentEditor = editor; } }
true
true
protected void createAttributeLayout() { String title = getTitleString(); String keywords = ""; String url = ""; // Attributes Composite- this holds all the combo fiels and text // fields Composite attributesComposite = new Composite(infoArea, SWT.NONE); GridLayout attributesLayout = new GridLayout(); attributesLayout.numColumns = 4; attributesLayout.horizontalSpacing = 14; attributesLayout.verticalSpacing = 6; attributesComposite.setLayout(attributesLayout); GridData attributesData = new GridData(GridData.FILL_BOTH); attributesData.horizontalSpan = 1; attributesData.grabExcessVerticalSpace = false; attributesComposite.setLayoutData(attributesData); attributesComposite.setBackground(background); // End Attributes Composite // Attributes Title Area Composite attributesTitleComposite = new Composite(attributesComposite, SWT.NONE); GridLayout attributesTitleLayout = new GridLayout(); attributesTitleLayout.horizontalSpacing = 0; attributesTitleLayout.marginWidth = 0; attributesTitleComposite.setLayout(attributesTitleLayout); attributesTitleComposite.setBackground(background); GridData attributesTitleData = new GridData(GridData.HORIZONTAL_ALIGN_FILL); attributesTitleData.horizontalSpan = 4; attributesTitleData.grabExcessVerticalSpace = false; attributesTitleComposite.setLayoutData(attributesTitleData); // End Attributes Title // Set the Attributes Title newAttributesLayout(attributesTitleComposite); titleLabel.setText(title); bugzillaInput.setToolTipText(title); int currentCol = 1; String ccValue = null; // Populate Attributes for (Iterator<Attribute> it = getBug().getAttributes().iterator(); it.hasNext();) { Attribute attribute = it.next(); String key = attribute.getParameterName(); String name = attribute.getName(); String value = checkText(attribute.getValue()); Map<String, String> values = attribute.getOptionValues(); // make sure we don't try to display a hidden field if (attribute.isHidden() || (key != null && key.equals("status_whiteboard"))) continue; if (values == null) values = new HashMap<String, String>(); if (key == null) key = ""; GridData data = new GridData(GridData.HORIZONTAL_ALIGN_FILL); data.horizontalSpan = 1; data.horizontalIndent = HORZ_INDENT; if (key.equals("short_desc") || key.equals("keywords")) { keywords = value; } else if (key.equals("newcc")) { ccValue = value; if (value == null) ccValue = ""; } else if (key.equals("bug_file_loc")) { url = value; } else if (key.equals("op_sys")) { newLayout(attributesComposite, 1, name, PROPERTY); oSCombo = new Combo(attributesComposite, SWT.NO_BACKGROUND | SWT.MULTI | SWT.V_SCROLL | SWT.READ_ONLY); oSCombo.setFont(TEXT_FONT); oSCombo.setLayoutData(data); oSCombo.setBackground(background); Set<String> s = values.keySet(); String[] a = s.toArray(new String[s.size()]); Arrays.sort(a); for (int i = 0; i < a.length; i++) { oSCombo.add(a[i]); } oSCombo.select(oSCombo.indexOf(value)); oSCombo.addListener(SWT.Modify, this); comboListenerMap.put(oSCombo, name); oSCombo.addListener(SWT.FocusIn, new GenericListener()); currentCol += 2; } else if (key.equals("version")) { newLayout(attributesComposite, 1, name, PROPERTY); versionCombo = new Combo(attributesComposite, SWT.NO_BACKGROUND | SWT.MULTI | SWT.V_SCROLL | SWT.READ_ONLY); versionCombo.setFont(TEXT_FONT); versionCombo.setLayoutData(data); versionCombo.setBackground(background); Set<String> s = values.keySet(); String[] a = s.toArray(new String[s.size()]); Arrays.sort(a); for (int i = 0; i < a.length; i++) { versionCombo.add(a[i]); } versionCombo.select(versionCombo.indexOf(value)); versionCombo.addListener(SWT.Modify, this); versionCombo.addListener(SWT.FocusIn, new GenericListener()); comboListenerMap.put(versionCombo, name); currentCol += 2; } else if (key.equals("priority")) { newLayout(attributesComposite, 1, name, PROPERTY); priorityCombo = new Combo(attributesComposite, SWT.NO_BACKGROUND | SWT.MULTI | SWT.V_SCROLL | SWT.READ_ONLY); priorityCombo.setFont(TEXT_FONT); priorityCombo.setLayoutData(data); priorityCombo.setBackground(background); Set<String> s = values.keySet(); String[] a = s.toArray(new String[s.size()]); Arrays.sort(a); for (int i = 0; i < a.length; i++) { priorityCombo.add(a[i]); } priorityCombo.select(priorityCombo.indexOf(value)); priorityCombo.addListener(SWT.Modify, this); priorityCombo.addListener(SWT.FocusIn, new GenericListener()); comboListenerMap.put(priorityCombo, name); currentCol += 2; } else if (key.equals("bug_severity")) { newLayout(attributesComposite, 1, name, PROPERTY); severityCombo = new Combo(attributesComposite, SWT.NO_BACKGROUND | SWT.MULTI | SWT.V_SCROLL | SWT.READ_ONLY); severityCombo.setFont(TEXT_FONT); severityCombo.setLayoutData(data); severityCombo.setBackground(background); Set<String> s = values.keySet(); String[] a = s.toArray(new String[s.size()]); Arrays.sort(a); for (int i = 0; i < a.length; i++) { severityCombo.add(a[i]); } severityCombo.select(severityCombo.indexOf(value)); severityCombo.addListener(SWT.Modify, this); severityCombo.addListener(SWT.FocusIn, new GenericListener()); comboListenerMap.put(severityCombo, name); currentCol += 2; } else if (key.equals("target_milestone")) { newLayout(attributesComposite, 1, name, PROPERTY); milestoneCombo = new Combo(attributesComposite, SWT.NO_BACKGROUND | SWT.MULTI | SWT.V_SCROLL | SWT.READ_ONLY); milestoneCombo.setFont(TEXT_FONT); milestoneCombo.setLayoutData(data); milestoneCombo.setBackground(background); Set<String> s = values.keySet(); String[] a = s.toArray(new String[s.size()]); Arrays.sort(a); for (int i = 0; i < a.length; i++) { milestoneCombo.add(a[i]); } milestoneCombo.select(milestoneCombo.indexOf(value)); milestoneCombo.addListener(SWT.Modify, this); milestoneCombo.addListener(SWT.FocusIn, new GenericListener()); comboListenerMap.put(milestoneCombo, name); currentCol += 2; } else if (key.equals("rep_platform")) { newLayout(attributesComposite, 1, name, PROPERTY); platformCombo = new Combo(attributesComposite, SWT.NO_BACKGROUND | SWT.MULTI | SWT.V_SCROLL | SWT.READ_ONLY); platformCombo.setFont(TEXT_FONT); platformCombo.setLayoutData(data); platformCombo.setBackground(background); Set<String> s = values.keySet(); String[] a = s.toArray(new String[s.size()]); Arrays.sort(a); for (int i = 0; i < a.length; i++) { platformCombo.add(a[i]); } platformCombo.select(platformCombo.indexOf(value)); platformCombo.addListener(SWT.Modify, this); platformCombo.addListener(SWT.FocusIn, new GenericListener()); comboListenerMap.put(platformCombo, name); currentCol += 2; } else if (key.equals("product")) { newLayout(attributesComposite, 1, name, PROPERTY); newLayout(attributesComposite, 1, value, VALUE).addListener(SWT.FocusIn, new GenericListener()); currentCol += 2; } else if (key.equals("assigned_to")) { newLayout(attributesComposite, 1, name, PROPERTY); assignedTo = new Text(attributesComposite, SWT.BORDER | SWT.SINGLE | SWT.WRAP); assignedTo.setFont(TEXT_FONT); assignedTo.setText(value); data = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); data.horizontalSpan = 1; assignedTo.setLayoutData(data); assignedTo.addListener(SWT.KeyUp, new Listener() { public void handleEvent(Event event) { String sel = assignedTo.getText(); Attribute a = getBug().getAttribute("Assign To"); if (!(a.getNewValue().equals(sel))) { a.setNewValue(sel); changeDirtyStatus(true); } } }); assignedTo.addListener(SWT.FocusIn, new GenericListener()); currentCol += 2; } else if (key.equals("component")) { newLayout(attributesComposite, 1, name, PROPERTY); componentCombo = new Combo(attributesComposite, SWT.NO_BACKGROUND | SWT.MULTI | SWT.V_SCROLL | SWT.READ_ONLY); componentCombo.setFont(TEXT_FONT); componentCombo.setLayoutData(data); componentCombo.setBackground(background); Set<String> s = values.keySet(); String[] a = s.toArray(new String[s.size()]); Arrays.sort(a); for (int i = 0; i < a.length; i++) { componentCombo.add(a[i]); } componentCombo.select(componentCombo.indexOf(value)); componentCombo.addListener(SWT.Modify, this); componentCombo.addListener(SWT.FocusIn, new GenericListener()); comboListenerMap.put(componentCombo, name); currentCol += 2; } else if (name.equals("Summary")) { // Don't show the summary here. continue; } else if (values.isEmpty()) { newLayout(attributesComposite, 1, name, PROPERTY); newLayout(attributesComposite, 1, value, VALUE).addListener(SWT.FocusIn, new GenericListener()); currentCol += 2; } if (currentCol > attributesLayout.numColumns) { currentCol -= attributesLayout.numColumns; } } // End Populate Attributes // make sure that we are in the first column if (currentCol > 1) { while (currentCol <= attributesLayout.numColumns) { newLayout(attributesComposite, 1, "", PROPERTY); currentCol++; } } // URL, Keywords, Summary Text Fields addUrlText(url, attributesComposite); // keywords text field (not editable) addKeywordsList(keywords, attributesComposite); if (ccValue != null) { addCCList(ccValue, attributesComposite); } addSummaryText(attributesComposite); // End URL, Keywords, Summary Text Fields }
protected void createAttributeLayout() { String title = getTitleString(); String keywords = ""; String url = ""; // Attributes Composite- this holds all the combo fiels and text // fields Composite attributesComposite = new Composite(infoArea, SWT.NONE); GridLayout attributesLayout = new GridLayout(); attributesLayout.numColumns = 4; attributesLayout.horizontalSpacing = 14; attributesLayout.verticalSpacing = 6; attributesComposite.setLayout(attributesLayout); GridData attributesData = new GridData(GridData.FILL_BOTH); attributesData.horizontalSpan = 1; attributesData.grabExcessVerticalSpace = false; attributesComposite.setLayoutData(attributesData); attributesComposite.setBackground(background); // End Attributes Composite // Attributes Title Area Composite attributesTitleComposite = new Composite(attributesComposite, SWT.NONE); GridLayout attributesTitleLayout = new GridLayout(); attributesTitleLayout.horizontalSpacing = 0; attributesTitleLayout.marginWidth = 0; attributesTitleComposite.setLayout(attributesTitleLayout); attributesTitleComposite.setBackground(background); GridData attributesTitleData = new GridData(GridData.HORIZONTAL_ALIGN_FILL); attributesTitleData.horizontalSpan = 4; attributesTitleData.grabExcessVerticalSpace = false; attributesTitleComposite.setLayoutData(attributesTitleData); // End Attributes Title // Set the Attributes Title newAttributesLayout(attributesTitleComposite); titleLabel.setText(title); bugzillaInput.setToolTipText(title); int currentCol = 1; String ccValue = null; // Populate Attributes for (Iterator<Attribute> it = getBug().getAttributes().iterator(); it.hasNext();) { Attribute attribute = it.next(); String key = attribute.getParameterName(); String name = attribute.getName(); String value = checkText(attribute.getValue()); Map<String, String> values = attribute.getOptionValues(); // make sure we don't try to display a hidden field if (attribute.isHidden() || (key != null && key.equals("status_whiteboard"))) continue; if (values == null) values = new HashMap<String, String>(); if (key == null) key = ""; GridData data = new GridData(GridData.HORIZONTAL_ALIGN_FILL); data.horizontalSpan = 1; data.horizontalIndent = HORZ_INDENT; if (key.equals("short_desc") || key.equals("keywords")) { keywords = value; } else if (key.equals("newcc")) { ccValue = value; if (value == null) ccValue = ""; } else if (key.equals("bug_file_loc")) { url = value; } else if (key.equals("op_sys")) { newLayout(attributesComposite, 1, name, PROPERTY); oSCombo = new Combo(attributesComposite, SWT.NO_BACKGROUND | SWT.MULTI | SWT.V_SCROLL | SWT.READ_ONLY); oSCombo.setFont(TEXT_FONT); oSCombo.setLayoutData(data); oSCombo.setBackground(background); Set<String> s = values.keySet(); String[] a = s.toArray(new String[s.size()]); Arrays.sort(a); for (int i = 0; i < a.length; i++) { oSCombo.add(a[i]); } if (oSCombo.indexOf(value) != -1) { oSCombo.select(oSCombo.indexOf(value)); } else { oSCombo.select(oSCombo.indexOf("All")); } oSCombo.addListener(SWT.Modify, this); comboListenerMap.put(oSCombo, name); oSCombo.addListener(SWT.FocusIn, new GenericListener()); currentCol += 2; } else if (key.equals("version")) { newLayout(attributesComposite, 1, name, PROPERTY); versionCombo = new Combo(attributesComposite, SWT.NO_BACKGROUND | SWT.MULTI | SWT.V_SCROLL | SWT.READ_ONLY); versionCombo.setFont(TEXT_FONT); versionCombo.setLayoutData(data); versionCombo.setBackground(background); Set<String> s = values.keySet(); String[] a = s.toArray(new String[s.size()]); Arrays.sort(a); for (int i = 0; i < a.length; i++) { versionCombo.add(a[i]); } versionCombo.select(versionCombo.indexOf(value)); versionCombo.addListener(SWT.Modify, this); versionCombo.addListener(SWT.FocusIn, new GenericListener()); comboListenerMap.put(versionCombo, name); currentCol += 2; } else if (key.equals("priority")) { newLayout(attributesComposite, 1, name, PROPERTY); priorityCombo = new Combo(attributesComposite, SWT.NO_BACKGROUND | SWT.MULTI | SWT.V_SCROLL | SWT.READ_ONLY); priorityCombo.setFont(TEXT_FONT); priorityCombo.setLayoutData(data); priorityCombo.setBackground(background); Set<String> s = values.keySet(); String[] a = s.toArray(new String[s.size()]); Arrays.sort(a); for (int i = 0; i < a.length; i++) { priorityCombo.add(a[i]); } priorityCombo.select(priorityCombo.indexOf(value)); priorityCombo.addListener(SWT.Modify, this); priorityCombo.addListener(SWT.FocusIn, new GenericListener()); comboListenerMap.put(priorityCombo, name); currentCol += 2; } else if (key.equals("bug_severity")) { newLayout(attributesComposite, 1, name, PROPERTY); severityCombo = new Combo(attributesComposite, SWT.NO_BACKGROUND | SWT.MULTI | SWT.V_SCROLL | SWT.READ_ONLY); severityCombo.setFont(TEXT_FONT); severityCombo.setLayoutData(data); severityCombo.setBackground(background); Set<String> s = values.keySet(); String[] a = s.toArray(new String[s.size()]); Arrays.sort(a); for (int i = 0; i < a.length; i++) { severityCombo.add(a[i]); } severityCombo.select(severityCombo.indexOf(value)); severityCombo.addListener(SWT.Modify, this); severityCombo.addListener(SWT.FocusIn, new GenericListener()); comboListenerMap.put(severityCombo, name); currentCol += 2; } else if (key.equals("target_milestone")) { newLayout(attributesComposite, 1, name, PROPERTY); milestoneCombo = new Combo(attributesComposite, SWT.NO_BACKGROUND | SWT.MULTI | SWT.V_SCROLL | SWT.READ_ONLY); milestoneCombo.setFont(TEXT_FONT); milestoneCombo.setLayoutData(data); milestoneCombo.setBackground(background); Set<String> s = values.keySet(); String[] a = s.toArray(new String[s.size()]); Arrays.sort(a); for (int i = 0; i < a.length; i++) { milestoneCombo.add(a[i]); } milestoneCombo.select(milestoneCombo.indexOf(value)); milestoneCombo.addListener(SWT.Modify, this); milestoneCombo.addListener(SWT.FocusIn, new GenericListener()); comboListenerMap.put(milestoneCombo, name); currentCol += 2; } else if (key.equals("rep_platform")) { newLayout(attributesComposite, 1, name, PROPERTY); platformCombo = new Combo(attributesComposite, SWT.NO_BACKGROUND | SWT.MULTI | SWT.V_SCROLL | SWT.READ_ONLY); platformCombo.setFont(TEXT_FONT); platformCombo.setLayoutData(data); platformCombo.setBackground(background); Set<String> s = values.keySet(); String[] a = s.toArray(new String[s.size()]); Arrays.sort(a); for (int i = 0; i < a.length; i++) { platformCombo.add(a[i]); } platformCombo.select(platformCombo.indexOf(value)); platformCombo.addListener(SWT.Modify, this); platformCombo.addListener(SWT.FocusIn, new GenericListener()); comboListenerMap.put(platformCombo, name); currentCol += 2; } else if (key.equals("product")) { newLayout(attributesComposite, 1, name, PROPERTY); newLayout(attributesComposite, 1, value, VALUE).addListener(SWT.FocusIn, new GenericListener()); currentCol += 2; } else if (key.equals("assigned_to")) { newLayout(attributesComposite, 1, name, PROPERTY); assignedTo = new Text(attributesComposite, SWT.BORDER | SWT.SINGLE | SWT.WRAP); assignedTo.setFont(TEXT_FONT); assignedTo.setText(value); data = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); data.horizontalSpan = 1; assignedTo.setLayoutData(data); assignedTo.addListener(SWT.KeyUp, new Listener() { public void handleEvent(Event event) { String sel = assignedTo.getText(); Attribute a = getBug().getAttribute("Assign To"); if (!(a.getNewValue().equals(sel))) { a.setNewValue(sel); changeDirtyStatus(true); } } }); assignedTo.addListener(SWT.FocusIn, new GenericListener()); currentCol += 2; } else if (key.equals("component")) { newLayout(attributesComposite, 1, name, PROPERTY); componentCombo = new Combo(attributesComposite, SWT.NO_BACKGROUND | SWT.MULTI | SWT.V_SCROLL | SWT.READ_ONLY); componentCombo.setFont(TEXT_FONT); componentCombo.setLayoutData(data); componentCombo.setBackground(background); Set<String> s = values.keySet(); String[] a = s.toArray(new String[s.size()]); Arrays.sort(a); for (int i = 0; i < a.length; i++) { componentCombo.add(a[i]); } componentCombo.select(componentCombo.indexOf(value)); componentCombo.addListener(SWT.Modify, this); componentCombo.addListener(SWT.FocusIn, new GenericListener()); comboListenerMap.put(componentCombo, name); currentCol += 2; } else if (name.equals("Summary")) { // Don't show the summary here. continue; } else if (values.isEmpty()) { newLayout(attributesComposite, 1, name, PROPERTY); newLayout(attributesComposite, 1, value, VALUE).addListener(SWT.FocusIn, new GenericListener()); currentCol += 2; } if (currentCol > attributesLayout.numColumns) { currentCol -= attributesLayout.numColumns; } } // End Populate Attributes // make sure that we are in the first column if (currentCol > 1) { while (currentCol <= attributesLayout.numColumns) { newLayout(attributesComposite, 1, "", PROPERTY); currentCol++; } } // URL, Keywords, Summary Text Fields addUrlText(url, attributesComposite); // keywords text field (not editable) addKeywordsList(keywords, attributesComposite); if (ccValue != null) { addCCList(ccValue, attributesComposite); } addSummaryText(attributesComposite); // End URL, Keywords, Summary Text Fields }
diff --git a/source/src/main/java/com/redcats/tst/dao/impl/ProjectDAO.java b/source/src/main/java/com/redcats/tst/dao/impl/ProjectDAO.java index b68d27f20..8d34d1790 100644 --- a/source/src/main/java/com/redcats/tst/dao/impl/ProjectDAO.java +++ b/source/src/main/java/com/redcats/tst/dao/impl/ProjectDAO.java @@ -1,80 +1,80 @@ package com.redcats.tst.dao.impl; import com.redcats.tst.dao.IProjectDAO; import com.redcats.tst.database.DatabaseSpring; import com.redcats.tst.entity.Project; import com.redcats.tst.factory.IFactoryProject; import com.redcats.tst.log.MyLogger; import org.apache.log4j.Level; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; /** * @author bcivel */ @Repository public class ProjectDAO implements IProjectDAO { @Autowired private DatabaseSpring databaseSpring; @Autowired private IFactoryProject factoryProject; @Override public List<Project> findAllProject() { List<Project> result = null; String idProject; String vcCode; String description; final String query = "SELECT * FROM project ORDER BY idproject"; Connection connection = this.databaseSpring.connect(); try { PreparedStatement preStat = connection.prepareStatement(query); try { ResultSet resultSet = preStat.executeQuery(); try { result = new ArrayList<Project>(); while (resultSet.next()) { idProject = resultSet.getString("idproject") == null ? "" : resultSet.getString("idproject"); vcCode = resultSet.getString("VCCode") == null ? "" : resultSet.getString("VCCode"); description = resultSet.getString("Description") == null ? "" : resultSet.getString("Description"); String active = resultSet.getString("active") == null ? "" : resultSet.getString("active"); - String dateCreation = resultSet.getString("dateCreation") == null ? "" : resultSet.getString("dateCreation"); + String dateCreation = resultSet.getString("datecre") == null ? "" : resultSet.getString("datecre"); result.add(factoryProject.create(idProject, vcCode, description, active, dateCreation)); } } catch (SQLException exception) { MyLogger.log(ProjectDAO.class.getName(), Level.ERROR, exception.toString()); } finally { resultSet.close(); } } catch (SQLException exception) { MyLogger.log(ProjectDAO.class.getName(), Level.ERROR, exception.toString()); } finally { preStat.close(); } } catch (SQLException exception) { MyLogger.log(ProjectDAO.class.getName(), Level.ERROR, exception.toString()); } finally { try { if (connection != null) { connection.close(); } } catch (SQLException e) { MyLogger.log(ProjectDAO.class.getName(), Level.WARN, e.toString()); } } return result; } }
true
true
public List<Project> findAllProject() { List<Project> result = null; String idProject; String vcCode; String description; final String query = "SELECT * FROM project ORDER BY idproject"; Connection connection = this.databaseSpring.connect(); try { PreparedStatement preStat = connection.prepareStatement(query); try { ResultSet resultSet = preStat.executeQuery(); try { result = new ArrayList<Project>(); while (resultSet.next()) { idProject = resultSet.getString("idproject") == null ? "" : resultSet.getString("idproject"); vcCode = resultSet.getString("VCCode") == null ? "" : resultSet.getString("VCCode"); description = resultSet.getString("Description") == null ? "" : resultSet.getString("Description"); String active = resultSet.getString("active") == null ? "" : resultSet.getString("active"); String dateCreation = resultSet.getString("dateCreation") == null ? "" : resultSet.getString("dateCreation"); result.add(factoryProject.create(idProject, vcCode, description, active, dateCreation)); } } catch (SQLException exception) { MyLogger.log(ProjectDAO.class.getName(), Level.ERROR, exception.toString()); } finally { resultSet.close(); } } catch (SQLException exception) { MyLogger.log(ProjectDAO.class.getName(), Level.ERROR, exception.toString()); } finally { preStat.close(); } } catch (SQLException exception) { MyLogger.log(ProjectDAO.class.getName(), Level.ERROR, exception.toString()); } finally { try { if (connection != null) { connection.close(); } } catch (SQLException e) { MyLogger.log(ProjectDAO.class.getName(), Level.WARN, e.toString()); } } return result; }
public List<Project> findAllProject() { List<Project> result = null; String idProject; String vcCode; String description; final String query = "SELECT * FROM project ORDER BY idproject"; Connection connection = this.databaseSpring.connect(); try { PreparedStatement preStat = connection.prepareStatement(query); try { ResultSet resultSet = preStat.executeQuery(); try { result = new ArrayList<Project>(); while (resultSet.next()) { idProject = resultSet.getString("idproject") == null ? "" : resultSet.getString("idproject"); vcCode = resultSet.getString("VCCode") == null ? "" : resultSet.getString("VCCode"); description = resultSet.getString("Description") == null ? "" : resultSet.getString("Description"); String active = resultSet.getString("active") == null ? "" : resultSet.getString("active"); String dateCreation = resultSet.getString("datecre") == null ? "" : resultSet.getString("datecre"); result.add(factoryProject.create(idProject, vcCode, description, active, dateCreation)); } } catch (SQLException exception) { MyLogger.log(ProjectDAO.class.getName(), Level.ERROR, exception.toString()); } finally { resultSet.close(); } } catch (SQLException exception) { MyLogger.log(ProjectDAO.class.getName(), Level.ERROR, exception.toString()); } finally { preStat.close(); } } catch (SQLException exception) { MyLogger.log(ProjectDAO.class.getName(), Level.ERROR, exception.toString()); } finally { try { if (connection != null) { connection.close(); } } catch (SQLException e) { MyLogger.log(ProjectDAO.class.getName(), Level.WARN, e.toString()); } } return result; }
diff --git a/src/main/java/org/codehaus/mojo/nbm/RunNetBeansMojo.java b/src/main/java/org/codehaus/mojo/nbm/RunNetBeansMojo.java index 6311d4d..421b8b1 100644 --- a/src/main/java/org/codehaus/mojo/nbm/RunNetBeansMojo.java +++ b/src/main/java/org/codehaus/mojo/nbm/RunNetBeansMojo.java @@ -1,183 +1,186 @@ /* ========================================================================== * Copyright 2003-2007 Mevenide Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ========================================================================= */ package org.codehaus.mojo.nbm; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.StringReader; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.project.MavenProject; import org.codehaus.plexus.util.IOUtil; import org.codehaus.plexus.util.Os; import org.codehaus.plexus.util.cli.CommandLineUtils; import org.codehaus.plexus.util.cli.Commandline; import org.codehaus.plexus.util.cli.StreamConsumer; /** * Run NetBeans IDE with additional custom module clusters, * to be used in conjunction with nbm:cluster. * @author <a href="mailto:[email protected]">Milos Kleint</a> * @goal run-ide * @aggregator * @requiresDependencyResolution runtime * */ public class RunNetBeansMojo extends AbstractMojo { /** * directory where the module(s)' netbeans cluster(s) are located. * is related to nbm:cluster goal. * @parameter default-value="${project.build.directory}/netbeans_clusters" * @required */ protected File clusterBuildDir; /** * directory where the the netbeans platform/IDE installation is, * denotes the root directory of netbeans installation. * @parameter expression="${netbeans.installation}" * @required */ protected File netbeansInstallation; /** * netbeans user directory for the executed instance. * @parameter default-value="${project.build.directory}/userdir" expression="${netbeans.userdir}" * @required */ protected File netbeansUserdir; /** * additional command line arguments. Eg. * -J-Xdebug -J-Xnoagent -J-Xrunjdwp:transport=dt_socket,suspend=n,server=n,address=8888 * can be used to debug the IDE. * @parameter expression="${netbeans.run.params}" */ protected String additionalArguments; /** * The Maven Project. * * @parameter expression="${project}" * @required * @readonly */ private MavenProject project; /** * * @throws org.apache.maven.plugin.MojoExecutionException * @throws org.apache.maven.plugin.MojoFailureException */ public void execute() throws MojoExecutionException, MojoFailureException { netbeansUserdir.mkdirs(); List clusters = new ArrayList(); + if (!clusterBuildDir.exists() || clusterBuildDir.listFiles() == null) { + throw new MojoExecutionException("No clusters to include in execution found. Please run the nbm:cluster or nbm:cluster-app goals before this one."); + } File[] fls = clusterBuildDir.listFiles(); for ( int i = 0; i < fls.length; i++ ) { if ( fls[i].isDirectory() ) { clusters.add( fls[i] ); } } StringBuffer buff = new StringBuffer(); buff.append( "netbeans_extraclusters=\"" ); Iterator it = clusters.iterator(); while ( it.hasNext() ) { File cluster = (File) it.next(); buff.append( cluster.getAbsolutePath() ); buff.append( ":" ); } if (buff.lastIndexOf( ":") > -1) { buff.deleteCharAt( buff.lastIndexOf( ":" ) ); } buff.append( "\"" ); StringReader sr = new StringReader( buff.toString() ); // write netbeans.conf file with cluster information... File etc = new File( netbeansUserdir, "etc" ); etc.mkdirs(); File confFile = new File( etc, "netbeans.conf" ); FileOutputStream conf = null; try { conf = new FileOutputStream( confFile ); IOUtil.copy( sr, conf ); } catch ( IOException ex ) { throw new MojoExecutionException( "Error writing " + confFile, ex ); } finally { IOUtil.close( conf ); } boolean windows = Os.isFamily( "windows" ); Commandline cmdLine = new Commandline(); File exec; if (windows) { exec = new File( netbeansInstallation, "bin\\nb.exe" ); if (!exec.exists()) { // in 6.7 and onward, there's no nb.exe file. exec = new File( netbeansInstallation, "bin\\netbeans.exe" ); } } else { exec = new File(netbeansInstallation, "bin/netbeans" ); } cmdLine.setExecutable( exec.getAbsolutePath() ); try { String[] args = new String[] { //TODO --jdkhome "--userdir", Commandline.quoteArgument( netbeansUserdir.getAbsolutePath() ), "-J-Dnetbeans.logger.console=true", "-J-ea", }; cmdLine.addArguments( args ); getLog().info( "Additional arguments=" + additionalArguments ); cmdLine.addArguments( cmdLine.translateCommandline( additionalArguments ) ); for ( int i = 0; i < cmdLine.getArguments().length; i++ ) { getLog().info( " " + cmdLine.getArguments()[i] ); } getLog().info( "Executing: " + cmdLine.toString() ); StreamConsumer out = new StreamConsumer() { public void consumeLine( String line ) { getLog().info( line ); } }; CommandLineUtils.executeCommandLine( cmdLine, out, out ); } catch ( Exception e ) { throw new MojoExecutionException( "Failed executing NetBeans", e ); } } }
true
true
public void execute() throws MojoExecutionException, MojoFailureException { netbeansUserdir.mkdirs(); List clusters = new ArrayList(); File[] fls = clusterBuildDir.listFiles(); for ( int i = 0; i < fls.length; i++ ) { if ( fls[i].isDirectory() ) { clusters.add( fls[i] ); } } StringBuffer buff = new StringBuffer(); buff.append( "netbeans_extraclusters=\"" ); Iterator it = clusters.iterator(); while ( it.hasNext() ) { File cluster = (File) it.next(); buff.append( cluster.getAbsolutePath() ); buff.append( ":" ); } if (buff.lastIndexOf( ":") > -1) { buff.deleteCharAt( buff.lastIndexOf( ":" ) ); } buff.append( "\"" ); StringReader sr = new StringReader( buff.toString() ); // write netbeans.conf file with cluster information... File etc = new File( netbeansUserdir, "etc" ); etc.mkdirs(); File confFile = new File( etc, "netbeans.conf" ); FileOutputStream conf = null; try { conf = new FileOutputStream( confFile ); IOUtil.copy( sr, conf ); } catch ( IOException ex ) { throw new MojoExecutionException( "Error writing " + confFile, ex ); } finally { IOUtil.close( conf ); } boolean windows = Os.isFamily( "windows" ); Commandline cmdLine = new Commandline(); File exec; if (windows) { exec = new File( netbeansInstallation, "bin\\nb.exe" ); if (!exec.exists()) { // in 6.7 and onward, there's no nb.exe file. exec = new File( netbeansInstallation, "bin\\netbeans.exe" ); } } else { exec = new File(netbeansInstallation, "bin/netbeans" ); } cmdLine.setExecutable( exec.getAbsolutePath() ); try { String[] args = new String[] { //TODO --jdkhome "--userdir", Commandline.quoteArgument( netbeansUserdir.getAbsolutePath() ), "-J-Dnetbeans.logger.console=true", "-J-ea", }; cmdLine.addArguments( args ); getLog().info( "Additional arguments=" + additionalArguments ); cmdLine.addArguments( cmdLine.translateCommandline( additionalArguments ) ); for ( int i = 0; i < cmdLine.getArguments().length; i++ ) { getLog().info( " " + cmdLine.getArguments()[i] ); } getLog().info( "Executing: " + cmdLine.toString() ); StreamConsumer out = new StreamConsumer() { public void consumeLine( String line ) { getLog().info( line ); } }; CommandLineUtils.executeCommandLine( cmdLine, out, out ); } catch ( Exception e ) { throw new MojoExecutionException( "Failed executing NetBeans", e ); } }
public void execute() throws MojoExecutionException, MojoFailureException { netbeansUserdir.mkdirs(); List clusters = new ArrayList(); if (!clusterBuildDir.exists() || clusterBuildDir.listFiles() == null) { throw new MojoExecutionException("No clusters to include in execution found. Please run the nbm:cluster or nbm:cluster-app goals before this one."); } File[] fls = clusterBuildDir.listFiles(); for ( int i = 0; i < fls.length; i++ ) { if ( fls[i].isDirectory() ) { clusters.add( fls[i] ); } } StringBuffer buff = new StringBuffer(); buff.append( "netbeans_extraclusters=\"" ); Iterator it = clusters.iterator(); while ( it.hasNext() ) { File cluster = (File) it.next(); buff.append( cluster.getAbsolutePath() ); buff.append( ":" ); } if (buff.lastIndexOf( ":") > -1) { buff.deleteCharAt( buff.lastIndexOf( ":" ) ); } buff.append( "\"" ); StringReader sr = new StringReader( buff.toString() ); // write netbeans.conf file with cluster information... File etc = new File( netbeansUserdir, "etc" ); etc.mkdirs(); File confFile = new File( etc, "netbeans.conf" ); FileOutputStream conf = null; try { conf = new FileOutputStream( confFile ); IOUtil.copy( sr, conf ); } catch ( IOException ex ) { throw new MojoExecutionException( "Error writing " + confFile, ex ); } finally { IOUtil.close( conf ); } boolean windows = Os.isFamily( "windows" ); Commandline cmdLine = new Commandline(); File exec; if (windows) { exec = new File( netbeansInstallation, "bin\\nb.exe" ); if (!exec.exists()) { // in 6.7 and onward, there's no nb.exe file. exec = new File( netbeansInstallation, "bin\\netbeans.exe" ); } } else { exec = new File(netbeansInstallation, "bin/netbeans" ); } cmdLine.setExecutable( exec.getAbsolutePath() ); try { String[] args = new String[] { //TODO --jdkhome "--userdir", Commandline.quoteArgument( netbeansUserdir.getAbsolutePath() ), "-J-Dnetbeans.logger.console=true", "-J-ea", }; cmdLine.addArguments( args ); getLog().info( "Additional arguments=" + additionalArguments ); cmdLine.addArguments( cmdLine.translateCommandline( additionalArguments ) ); for ( int i = 0; i < cmdLine.getArguments().length; i++ ) { getLog().info( " " + cmdLine.getArguments()[i] ); } getLog().info( "Executing: " + cmdLine.toString() ); StreamConsumer out = new StreamConsumer() { public void consumeLine( String line ) { getLog().info( line ); } }; CommandLineUtils.executeCommandLine( cmdLine, out, out ); } catch ( Exception e ) { throw new MojoExecutionException( "Failed executing NetBeans", e ); } }
diff --git a/main/src/cgeo/geocaching/MainActivity.java b/main/src/cgeo/geocaching/MainActivity.java index 6d8999198..ba7795a65 100644 --- a/main/src/cgeo/geocaching/MainActivity.java +++ b/main/src/cgeo/geocaching/MainActivity.java @@ -1,726 +1,727 @@ package cgeo.geocaching; import butterknife.ButterKnife; import butterknife.InjectView; import cgeo.geocaching.activity.AbstractActivity; import cgeo.geocaching.connector.ConnectorFactory; import cgeo.geocaching.connector.capability.ILogin; import cgeo.geocaching.enumerations.CacheType; import cgeo.geocaching.enumerations.StatusCode; import cgeo.geocaching.geopoint.Geopoint; import cgeo.geocaching.geopoint.Units; import cgeo.geocaching.list.PseudoList; import cgeo.geocaching.list.StoredList; import cgeo.geocaching.maps.CGeoMap; import cgeo.geocaching.settings.Settings; import cgeo.geocaching.settings.SettingsActivity; import cgeo.geocaching.ui.Formatter; import cgeo.geocaching.ui.dialog.Dialogs; import cgeo.geocaching.utils.DatabaseBackupUtils; import cgeo.geocaching.utils.GeoDirHandler; import cgeo.geocaching.utils.Log; import cgeo.geocaching.utils.Version; import com.google.zxing.integration.android.IntentIntegrator; import com.google.zxing.integration.android.IntentResult; import org.apache.commons.lang3.StringUtils; import rx.Observable; import rx.Observable.OnSubscribe; import rx.Subscriber; import rx.android.observables.AndroidObservable; import rx.schedulers.Schedulers; import rx.functions.Action1; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.app.SearchManager; import android.content.DialogInterface; import android.content.Intent; import android.content.res.Configuration; import android.location.Address; import android.location.Geocoder; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Locale; public class MainActivity extends AbstractActivity { @InjectView(R.id.nav_satellites) protected TextView navSatellites; @InjectView(R.id.filter_button_title)protected TextView filterTitle; @InjectView(R.id.map) protected ImageView findOnMap; @InjectView(R.id.search_offline) protected ImageView findByOffline; @InjectView(R.id.advanced_button) protected ImageView advanced; @InjectView(R.id.any_button) protected ImageView any; @InjectView(R.id.filter_button) protected ImageView filter; @InjectView(R.id.nearest) protected ImageView nearestView; @InjectView(R.id.nav_type) protected TextView navType; @InjectView(R.id.nav_accuracy) protected TextView navAccuracy; @InjectView(R.id.nav_location) protected TextView navLocation; @InjectView(R.id.offline_count) protected TextView countBubble; @InjectView(R.id.info_area) protected LinearLayout infoArea; public static final int SEARCH_REQUEST_CODE = 2; private int version = 0; private boolean cleanupRunning = false; private int countBubbleCnt = 0; private Geopoint addCoords = null; private boolean initialized = false; private final UpdateLocation locationUpdater = new UpdateLocation(); private Handler updateUserInfoHandler = new Handler() { @Override public void handleMessage(final Message msg) { // Get active connectors with login status ILogin[] loginConns = ConnectorFactory.getActiveLiveConnectors(); // Update UI infoArea.removeAllViews(); LayoutInflater inflater = getLayoutInflater(); for (ILogin conn : loginConns) { TextView connectorInfo = (TextView) inflater.inflate(R.layout.main_activity_connectorstatus, null); infoArea.addView(connectorInfo); StringBuilder userInfo = new StringBuilder(conn.getName()).append(Formatter.SEPARATOR); if (conn.isLoggedIn()) { userInfo.append(conn.getUserName()); if (conn.getCachesFound() >= 0) { userInfo.append(" (").append(conn.getCachesFound()).append(')'); } userInfo.append(Formatter.SEPARATOR); } userInfo.append(conn.getLoginStatusString()); connectorInfo.setText(userInfo); } } }; private static String formatAddress(final Address address) { final ArrayList<String> addressParts = new ArrayList<String>(); final String countryName = address.getCountryName(); if (countryName != null) { addressParts.add(countryName); } final String locality = address.getLocality(); if (locality != null) { addressParts.add(locality); } else { final String adminArea = address.getAdminArea(); if (adminArea != null) { addressParts.add(adminArea); } } return StringUtils.join(addressParts, ", "); } private class SatellitesHandler extends GeoDirHandler { private boolean gpsEnabled = false; private int satellitesFixed = 0; private int satellitesVisible = 0; @Override public void updateGeoData(final IGeoData data) { if (data.getGpsEnabled() == gpsEnabled && data.getSatellitesFixed() == satellitesFixed && data.getSatellitesVisible() == satellitesVisible) { return; } gpsEnabled = data.getGpsEnabled(); satellitesFixed = data.getSatellitesFixed(); satellitesVisible = data.getSatellitesVisible(); if (gpsEnabled) { if (satellitesFixed > 0) { navSatellites.setText(res.getString(R.string.loc_sat) + ": " + satellitesFixed + '/' + satellitesVisible); } else if (satellitesVisible >= 0) { navSatellites.setText(res.getString(R.string.loc_sat) + ": 0/" + satellitesVisible); } } else { navSatellites.setText(res.getString(R.string.loc_gps_disabled)); } } } private SatellitesHandler satellitesHandler = new SatellitesHandler(); private Handler firstLoginHandler = new Handler() { @Override public void handleMessage(final Message msg) { try { final StatusCode reason = (StatusCode) msg.obj; if (reason != null && reason != StatusCode.NO_ERROR) { //LoginFailed showToast(res.getString(reason == StatusCode.MAINTENANCE ? reason.getErrorString() : R.string.err_login_failed_toast)); } } catch (Exception e) { Log.w("MainActivity.firstLoginHander", e); } } }; @Override public void onCreate(final Bundle savedInstanceState) { // don't call the super implementation with the layout argument, as that would set the wrong theme super.onCreate(savedInstanceState); setContentView(R.layout.main_activity); ButterKnife.inject(this); if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) { // If we had been open already, start from the last used activity. finish(); return; } setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL); // type to search version = Version.getVersionCode(this); Log.i("Starting " + getPackageName() + ' ' + version + " a.k.a " + Version.getVersionName(this)); init(); } @Override public void onConfigurationChanged(final Configuration newConfig) { super.onConfigurationChanged(newConfig); init(); } @Override public void onResume() { super.onResume(); locationUpdater.startGeo(); satellitesHandler.startGeo(); updateUserInfoHandler.sendEmptyMessage(-1); startBackgroundLogin(); init(); } private void startBackgroundLogin() { assert(app != null); final boolean mustLogin = app.mustRelog(); for (final ILogin conn : ConnectorFactory.getActiveLiveConnectors()) { if (mustLogin || !conn.isLoggedIn()) { new Thread() { @Override public void run() { conn.login(firstLoginHandler, MainActivity.this); updateUserInfoHandler.sendEmptyMessage(-1); } }.start(); } } } @Override public void onDestroy() { initialized = false; app.showLoginToast = true; super.onDestroy(); } @Override public void onStop() { initialized = false; super.onStop(); } @Override public void onPause() { initialized = false; locationUpdater.stopGeo(); satellitesHandler.stopGeo(); super.onPause(); } @Override public boolean onCreateOptionsMenu(final Menu menu) { getMenuInflater().inflate(R.menu.main_activity_options, menu); return true; } @Override public boolean onPrepareOptionsMenu(final Menu menu) { super.onPrepareOptionsMenu(menu); menu.findItem(R.id.menu_pocket_queries).setVisible(Settings.isGCPremiumMember()); return true; } @Override public boolean onOptionsItemSelected(final MenuItem item) { final int id = item.getItemId(); switch (id) { case R.id.menu_about: showAbout(null); return true; case R.id.menu_helpers: startActivity(new Intent(this, UsefulAppsActivity.class)); return true; case R.id.menu_settings: startActivity(new Intent(this, SettingsActivity.class)); return true; case R.id.menu_history: CacheListActivity.startActivityHistory(this); return true; case R.id.menu_scan: startScannerApplication(); return true; case R.id.menu_pocket_queries: if (!Settings.isGCPremiumMember()) { return true; } PocketQueryList.promptForListSelection(this, new Action1<PocketQueryList>() { @Override public void call(final PocketQueryList pql) { CacheListActivity.startActivityPocket(MainActivity.this, pql); } }); return true; default: return super.onOptionsItemSelected(item); } } private void startScannerApplication() { IntentIntegrator integrator = new IntentIntegrator(this); // integrator dialog is English only, therefore localize it integrator.setButtonYesByID(android.R.string.yes); integrator.setButtonNoByID(android.R.string.no); integrator.setTitleByID(R.string.menu_scan_geo); integrator.setMessageByID(R.string.menu_scan_description); integrator.initiateScan(IntentIntegrator.QR_CODE_TYPES); } @Override public void onActivityResult(final int requestCode, final int resultCode, final Intent intent) { IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent); if (scanResult != null) { String scan = scanResult.getContents(); if (StringUtils.isBlank(scan)) { return; } SearchActivity.startActivityScan(scan, this); } else if (requestCode == SEARCH_REQUEST_CODE) { // SearchActivity activity returned without making a search if (resultCode == RESULT_CANCELED) { String query = intent.getStringExtra(SearchManager.QUERY); if (query == null) { query = ""; } Dialogs.message(this, res.getString(R.string.unknown_scan) + "\n\n" + query); } } } private void setFilterTitle() { filterTitle.setText(Settings.getCacheType().getL10n()); } private void init() { if (initialized) { return; } initialized = true; Settings.setLanguage(Settings.isUseEnglish()); findOnMap.setClickable(true); findOnMap.setOnClickListener(new OnClickListener() { @Override public void onClick(final View v) { cgeoFindOnMap(v); } }); findByOffline.setClickable(true); findByOffline.setOnClickListener(new OnClickListener() { @Override public void onClick(final View v) { cgeoFindByOffline(v); } }); findByOffline.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(final View v) { new StoredList.UserInterface(MainActivity.this).promptForListSelection(R.string.list_title, new Action1<Integer>() { @Override public void call(final Integer selectedListId) { Settings.saveLastList(selectedListId); CacheListActivity.startActivityOffline(MainActivity.this); } }, false, PseudoList.HISTORY_LIST.id); return true; } }); findByOffline.setLongClickable(true); advanced.setClickable(true); advanced.setOnClickListener(new OnClickListener() { @Override public void onClick(final View v) { cgeoSearch(v); } }); any.setClickable(true); any.setOnClickListener(new OnClickListener() { @Override public void onClick(final View v) { cgeoPoint(v); } }); filter.setClickable(true); filter.setOnClickListener(new View.OnClickListener() { @Override public void onClick(final View v) { selectGlobalTypeFilter(); } }); filter.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(final View v) { - selectGlobalTypeFilter(); + Settings.setCacheType(CacheType.ALL); + setFilterTitle(); return true; } }); updateCacheCounter(); setFilterTitle(); checkRestore(); (new CleanDatabaseThread()).start(); } protected void selectGlobalTypeFilter() { final List<CacheType> cacheTypes = new ArrayList<CacheType>(); //first add the most used types cacheTypes.add(CacheType.ALL); cacheTypes.add(CacheType.TRADITIONAL); cacheTypes.add(CacheType.MULTI); cacheTypes.add(CacheType.MYSTERY); // then add all other cache types sorted alphabetically List<CacheType> sorted = new ArrayList<CacheType>(); sorted.addAll(Arrays.asList(CacheType.values())); sorted.removeAll(cacheTypes); Collections.sort(sorted, new Comparator<CacheType>() { @Override public int compare(final CacheType left, final CacheType right) { return left.getL10n().compareToIgnoreCase(right.getL10n()); } }); cacheTypes.addAll(sorted); int checkedItem = cacheTypes.indexOf(Settings.getCacheType()); if (checkedItem < 0) { checkedItem = 0; } String[] items = new String[cacheTypes.size()]; for (int i = 0; i < cacheTypes.size(); i++) { items[i] = cacheTypes.get(i).getL10n(); } Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.menu_filter); builder.setSingleChoiceItems(items, checkedItem, new DialogInterface.OnClickListener() { @Override public void onClick(final DialogInterface dialog, final int position) { CacheType cacheType = cacheTypes.get(position); Settings.setCacheType(cacheType); setFilterTitle(); dialog.dismiss(); } }); builder.create().show(); } public void updateCacheCounter() { (new CountBubbleUpdateThread()).start(); } private void checkRestore() { if (!DataStore.isNewlyCreatedDatebase() || null == DatabaseBackupUtils.getRestoreFile()) { return; } new AlertDialog.Builder(this) .setTitle(res.getString(R.string.init_backup_restore)) .setMessage(res.getString(R.string.init_restore_confirm)) .setCancelable(false) .setPositiveButton(getString(android.R.string.yes), new DialogInterface.OnClickListener() { @Override public void onClick(final DialogInterface dialog, final int id) { dialog.dismiss(); DataStore.resetNewlyCreatedDatabase(); DatabaseBackupUtils.restoreDatabase(MainActivity.this); } }) .setNegativeButton(getString(android.R.string.no), new DialogInterface.OnClickListener() { @Override public void onClick(final DialogInterface dialog, final int id) { dialog.cancel(); DataStore.resetNewlyCreatedDatabase(); } }) .create() .show(); } private class UpdateLocation extends GeoDirHandler { @Override public void updateGeoData(final IGeoData geo) { if (!nearestView.isClickable()) { nearestView.setFocusable(true); nearestView.setClickable(true); nearestView.setOnClickListener(new OnClickListener() { @Override public void onClick(final View v) { cgeoFindNearest(v); } }); nearestView.setBackgroundResource(R.drawable.main_nearby); } navType.setText(res.getString(geo.getLocationProvider().resourceId)); if (geo.getAccuracy() >= 0) { int speed = Math.round(geo.getSpeed()) * 60 * 60 / 1000; navAccuracy.setText("±" + Units.getDistanceFromMeters(geo.getAccuracy()) + Formatter.SEPARATOR + Units.getSpeed(speed)); } else { navAccuracy.setText(null); } if (Settings.isShowAddress()) { if (addCoords == null) { navLocation.setText(R.string.loc_no_addr); } if (addCoords == null || (geo.getCoords().distanceTo(addCoords) > 0.5)) { final Observable<String> address = Observable.create(new OnSubscribe<String>() { @Override public void call(final Subscriber<? super String> subscriber) { try { addCoords = geo.getCoords(); final Geocoder geocoder = new Geocoder(MainActivity.this, Locale.getDefault()); final Geopoint coords = app.currentGeo().getCoords(); final List<Address> addresses = geocoder.getFromLocation(coords.getLatitude(), coords.getLongitude(), 1); if (!addresses.isEmpty()) { subscriber.onNext(formatAddress(addresses.get(0))); } subscriber.onCompleted(); } catch (final Exception e) { subscriber.onError(e); } } }).subscribeOn(Schedulers.io()); AndroidObservable.fromActivity(MainActivity.this, address) .onErrorResumeNext(Observable.from(geo.getCoords().toString())) .subscribe(new Action1<String>() { @Override public void call(final String address) { navLocation.setText(address); } }); } } else { navLocation.setText(geo.getCoords().toString()); } } } /** * @param v * unused here but needed since this method is referenced from XML layout */ public void cgeoFindOnMap(@SuppressWarnings("unused") final View v) { findOnMap.setPressed(true); CGeoMap.startActivityLiveMap(this); } /** * @param v * unused here but needed since this method is referenced from XML layout */ public void cgeoFindNearest(@SuppressWarnings("unused") final View v) { if (app.currentGeo().getCoords() == null) { return; } nearestView.setPressed(true); CacheListActivity.startActivityNearest(this, app.currentGeo().getCoords()); } /** * @param v * unused here but needed since this method is referenced from XML layout */ public void cgeoFindByOffline(@SuppressWarnings("unused") final View v) { findByOffline.setPressed(true); CacheListActivity.startActivityOffline(this); } /** * @param v * unused here but needed since this method is referenced from XML layout */ public void cgeoSearch(@SuppressWarnings("unused") final View v) { advanced.setPressed(true); startActivity(new Intent(this, SearchActivity.class)); } /** * @param v * unused here but needed since this method is referenced from XML layout */ public void cgeoPoint(@SuppressWarnings("unused") final View v) { any.setPressed(true); startActivity(new Intent(this, NavigateAnyPointActivity.class)); } /** * @param v * unused here but needed since this method is referenced from XML layout */ public void cgeoFilter(@SuppressWarnings("unused") final View v) { filter.setPressed(true); filter.performClick(); } /** * @param v * unused here but needed since this method is referenced from XML layout */ public void cgeoNavSettings(@SuppressWarnings("unused") final View v) { startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS)); } private class CountBubbleUpdateThread extends Thread { private Handler countBubbleHandler = new Handler() { @Override public void handleMessage(final Message msg) { try { if (countBubbleCnt == 0) { countBubble.setVisibility(View.GONE); } else { countBubble.setText(Integer.toString(countBubbleCnt)); countBubble.bringToFront(); countBubble.setVisibility(View.VISIBLE); } } catch (Exception e) { Log.w("MainActivity.countBubbleHander", e); } } }; @Override public void run() { if (app == null) { return; } int checks = 0; while (!DataStore.isInitialized()) { try { sleep(500); checks++; } catch (Exception e) { Log.e("MainActivity.CountBubbleUpdateThread.run", e); } if (checks > 10) { return; } } countBubbleCnt = DataStore.getAllCachesCount(); countBubbleHandler.sendEmptyMessage(0); } } private class CleanDatabaseThread extends Thread { @Override public void run() { if (app == null) { return; } if (cleanupRunning) { return; } boolean more = false; if (version != Settings.getVersion()) { Log.i("Initializing hard cleanup - version changed from " + Settings.getVersion() + " to " + version + "."); more = true; } cleanupRunning = true; DataStore.clean(more); cleanupRunning = false; if (version > 0) { Settings.setVersion(version); } } } /** * @param view * unused here but needed since this method is referenced from XML layout */ public void showAbout(@SuppressWarnings("unused") final View view) { startActivity(new Intent(this, AboutActivity.class)); } /** * @param view * unused here but needed since this method is referenced from XML layout */ public void goSearch(@SuppressWarnings("unused") final View view) { onSearchRequested(); } }
true
true
private void init() { if (initialized) { return; } initialized = true; Settings.setLanguage(Settings.isUseEnglish()); findOnMap.setClickable(true); findOnMap.setOnClickListener(new OnClickListener() { @Override public void onClick(final View v) { cgeoFindOnMap(v); } }); findByOffline.setClickable(true); findByOffline.setOnClickListener(new OnClickListener() { @Override public void onClick(final View v) { cgeoFindByOffline(v); } }); findByOffline.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(final View v) { new StoredList.UserInterface(MainActivity.this).promptForListSelection(R.string.list_title, new Action1<Integer>() { @Override public void call(final Integer selectedListId) { Settings.saveLastList(selectedListId); CacheListActivity.startActivityOffline(MainActivity.this); } }, false, PseudoList.HISTORY_LIST.id); return true; } }); findByOffline.setLongClickable(true); advanced.setClickable(true); advanced.setOnClickListener(new OnClickListener() { @Override public void onClick(final View v) { cgeoSearch(v); } }); any.setClickable(true); any.setOnClickListener(new OnClickListener() { @Override public void onClick(final View v) { cgeoPoint(v); } }); filter.setClickable(true); filter.setOnClickListener(new View.OnClickListener() { @Override public void onClick(final View v) { selectGlobalTypeFilter(); } }); filter.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(final View v) { selectGlobalTypeFilter(); return true; } }); updateCacheCounter(); setFilterTitle(); checkRestore(); (new CleanDatabaseThread()).start(); }
private void init() { if (initialized) { return; } initialized = true; Settings.setLanguage(Settings.isUseEnglish()); findOnMap.setClickable(true); findOnMap.setOnClickListener(new OnClickListener() { @Override public void onClick(final View v) { cgeoFindOnMap(v); } }); findByOffline.setClickable(true); findByOffline.setOnClickListener(new OnClickListener() { @Override public void onClick(final View v) { cgeoFindByOffline(v); } }); findByOffline.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(final View v) { new StoredList.UserInterface(MainActivity.this).promptForListSelection(R.string.list_title, new Action1<Integer>() { @Override public void call(final Integer selectedListId) { Settings.saveLastList(selectedListId); CacheListActivity.startActivityOffline(MainActivity.this); } }, false, PseudoList.HISTORY_LIST.id); return true; } }); findByOffline.setLongClickable(true); advanced.setClickable(true); advanced.setOnClickListener(new OnClickListener() { @Override public void onClick(final View v) { cgeoSearch(v); } }); any.setClickable(true); any.setOnClickListener(new OnClickListener() { @Override public void onClick(final View v) { cgeoPoint(v); } }); filter.setClickable(true); filter.setOnClickListener(new View.OnClickListener() { @Override public void onClick(final View v) { selectGlobalTypeFilter(); } }); filter.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(final View v) { Settings.setCacheType(CacheType.ALL); setFilterTitle(); return true; } }); updateCacheCounter(); setFilterTitle(); checkRestore(); (new CleanDatabaseThread()).start(); }
diff --git a/tools/host/src/com/android/cts/TestSession.java b/tools/host/src/com/android/cts/TestSession.java index 2ac840b1..3a159e22 100644 --- a/tools/host/src/com/android/cts/TestSession.java +++ b/tools/host/src/com/android/cts/TestSession.java @@ -1,615 +1,618 @@ /* * Copyright (C) 2008 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.cts; import java.io.IOException; import java.util.Collection; /** * Represents a runtime session for a test plan, takes charge in running a * plan and the setup&tear-downs. */ public class TestSession { private SessionObserver mSessionObserver; private TestSessionLog mSessionLog; private TestDevice mDevice; private int mId; private STATUS mStatus; private static int sIdCounter = 0; enum STATUS { INIT, STARTED, INSTALLING, RUNNING, PAUSED, RESUMED, STOPPED, FINISHED } private int mRequiredDeviceNumber; private boolean mTestStop; private TestSessionThread mTestThread; private boolean mNeedRestartAdbServer; private static boolean mADBServerRestartedMode; /** Running count of tests executed since last reboot. */ private static long mTestCount; public TestSession(final TestSessionLog sessionLog, final int requiredDeviceNum) { mStatus = STATUS.INIT; mNeedRestartAdbServer = false; mADBServerRestartedMode = false; mTestCount = 0; mSessionLog = sessionLog; mDevice = null; mRequiredDeviceNumber = requiredDeviceNum; mTestStop = false; mId = sIdCounter++; } /** * Get the last session ID. * * @return The last session ID. */ public static int getLastSessionId() { return sIdCounter-1; } /** * Set ADB server restarted mode. */ public static void setADBServerRestartedMode() { mADBServerRestartedMode = true; } /** * Reset ADB server restarted mode. */ public static void resetADBServerRestartedMode() { mADBServerRestartedMode = false; } /** * Check if it's in ADB server restarted mode. * * @return If in ADB server restarted mode, return true; else, return false. */ public static boolean isADBServerRestartedMode() { return mADBServerRestartedMode; } /** * Increase the test count. */ public static void incTestCount() { mTestCount++; } /** * Reset the test count. */ public static void resetTestCount() { mTestCount = 0; } /** * Get the test count recently has been run. * * @return The test count recently has been run. */ public static long getTestCount() { return mTestCount; } /** * Check if the test count exceeds the max test count. If the max test count is disabled * (HostConfig.getMaxTestCount() <= 0), this method always returns false. * * @return true, if the max count is enabled and exceeded. */ public static boolean exceedsMaxCount() { final long maxTestCount = HostConfig.getMaxTestCount(); return (maxTestCount > 0) && (mTestCount >= maxTestCount); } /** * Get status. * * @return The status. */ public STATUS getStatus() { return mStatus; } /** * Get device ID. * * @return device ID. */ public String getDeviceId() { if (mDevice == null) { return null; } return mDevice.getSerialNumber(); } /** * Get the test device. * * @return the test device. */ public TestDevice getDevice() { return mDevice; } /** * Get the number of required devices. * * @return The number of required devices. */ public int getNumOfRequiredDevices() { return mRequiredDeviceNumber; } /** * Get ID. * * @return ID. */ public int getId() { return mId; } /** * Start the single test with full name. * * @param testFullName The test full name. */ public void start(final String testFullName) throws TestNotFoundException, IllegalTestNameException, ADBServerNeedRestartException { if ((testFullName == null) || (testFullName.length() == 0)) { throw new IllegalArgumentException(); } // The test full name follows the following rule: // java_package_name.class_name#method_name. // Other forms will be treated as illegal. if (!testFullName.matches("(\\w+.)+\\w+")) { throw new IllegalTestNameException(testFullName); } Test test = null; TestPackage pkg = null; if (-1 != testFullName.indexOf(Test.METHOD_SEPARATOR)) { test = searchTest(testFullName); if (test == null) { throw new TestNotFoundException( "The specific test does not exist: " + testFullName); } mTestThread = new TestSessionThread(this, test); CUIOutputStream.println("start test " + testFullName); } else { pkg = searchTestPackage(testFullName); if (pkg == null) { throw new TestNotFoundException( "The specific test package does not exist: " + testFullName); } mTestThread = new TestSessionThread(this, pkg, testFullName); CUIOutputStream.println("start java package " + testFullName); } mStatus = STATUS.STARTED; startImpl(); } /** * Implement starting/resuming session. */ private void startImpl() throws ADBServerNeedRestartException { String resultPath = mSessionLog.getResultPath(); if ((resultPath == null) || (resultPath.length() == 0)) { mSessionLog.setStartTime(System.currentTimeMillis()); } resetTestCount(); mTestThread.start(); try { mTestThread.join(); } catch (InterruptedException e) { e.printStackTrace(); } if (mNeedRestartAdbServer && HostConfig.getMaxTestCount() > 0) { throw new ADBServerNeedRestartException("Need restart ADB server"); } } /** * Resume the test session. */ public void resume() throws ADBServerNeedRestartException { mStatus = STATUS.RESUMED; mTestThread = new TestSessionThread(this); if (!isADBServerRestartedMode()) { CUIOutputStream.println("resume test plan " + getSessionLog().getTestPlanName() + " (session id = " + mId + ")"); } startImpl(); } /** * Search the test with the test full name given among the test * packages contained within this session. * * @param testFullName The full name of the test. * @return The test with the full name given. */ private Test searchTest(final String testFullName) { Test test = null; for (TestPackage pkg : mSessionLog.getTestPackages()) { test = pkg.searchTest(testFullName); if (test != null) { break; } } return test; } /** * Search the test package with the specified java package name. * * @param javaPkgName The java package name. * @return The test package with the specified java package name. */ private TestPackage searchTestPackage(String javaPkgName) { for (TestPackage pkg : mSessionLog.getTestPackages()) { Collection<Test> tests = pkg.getTests(); for (Test test : tests) { String testFullName = test.getFullName(); if (testFullName.startsWith(javaPkgName)) { //adjust the java package name to make it equal to some java package name if (testFullName.charAt(javaPkgName.length()) != '.') { javaPkgName = javaPkgName.substring(0, javaPkgName.lastIndexOf(".")); } return pkg; } } } return null; } /** * Start a new test session thread to execute the specific test plan. */ public void start() throws ADBServerNeedRestartException { mStatus = STATUS.STARTED; mSessionLog.setStartTime(System.currentTimeMillis()); mTestThread = new TestSessionThread(this); CUIOutputStream.println("start test plan " + getSessionLog().getTestPlanName()); startImpl(); } /** * Set observer. * * @param so Session observer. */ public void setObserver(final SessionObserver so) { mSessionObserver = so; } /** * Print the message by appending the new line mark. * * @param msg The message to be print. */ private void println(final String msg) { if (!mTestStop) { CUIOutputStream.println(msg); } } /** * Set the {@link TestDevice} which will run the test. * * @param device The {@link TestDevice} will run the test. */ public void setTestDevice(final TestDevice device) { mDevice = device; } /** * Get the session log of this session. * * @return The session log of this session. */ public TestSessionLog getSessionLog() { return mSessionLog; } /** * Get the test packages contained within this session. * * @return The test packages contained within this session. */ public Collection<TestPackage> getTestPackages() { return mSessionLog.getTestPackages(); } /** * The Thread to be run the {@link TestSession} */ class TestSessionThread extends Thread { private final int MSEC_PER_SECOND = 1000; private TestSession mTestSession; private Test mTest; private TestPackage mTestPackage; private String mJavaPackageName; private ResultObserver mResultObserver; public TestSessionThread(final TestSession ts) { mTestSession = ts; mResultObserver = ResultObserver.getInstance(); } public TestSessionThread(final TestSession ts, final Test test) { mTestSession = ts; mResultObserver = ResultObserver.getInstance(); mTest = test; } public TestSessionThread(final TestSession ts, final TestPackage pkg, final String javaPkgName) { mTestSession = ts; mResultObserver = ResultObserver.getInstance(); mTestPackage = pkg; mJavaPackageName = javaPkgName; } /** {@inheritDoc} */ @Override public void run() { Log.d("Start a test session."); mNeedRestartAdbServer = false; mResultObserver.setTestSessionLog(getSessionLog()); mResultObserver.start(); try { if (mTest != null) { TestPackage pkg = mTest.getTestPackage(); pkg.setSessionThread(this); pkg.runTest(mDevice, mTest); } else if (mTestPackage != null) { mTestPackage.setSessionThread(this); mTestPackage.run(mDevice, mJavaPackageName, mSessionLog); } else { for (TestPackage pkg : mSessionLog.getTestPackages()) { if (!pkg.isAllTestsRun()) { pkg.setSessionThread(this); pkg.run(mDevice, null, mSessionLog); if (!isAllTestsRun()) { - markNeedRestartADBServer(); - return; + if (HostConfig.getMaxTestCount() > 0) { + // ADB server restart enabled + markNeedRestartADBServer(); + return; + } } else { Log.d("All tests have been run."); break; } } } mNeedRestartAdbServer = false; displayTestResultSummary(); } } catch (IOException e) { Log.e("Got exception when running the package", e); } catch (DeviceDisconnectedException e) { Log.e("Device " + e.getMessage() + " disconnected ", null); } catch (ADBServerNeedRestartException e) { Log.d(e.getMessage()); if (mTest == null) { markNeedRestartADBServer(); return; } } catch (InvalidApkPathException e) { Log.e(e.getMessage(), null); } catch (InvalidNameSpaceException e) { Log.e(e.getMessage(), null); } long startTime = getSessionLog().getStartTime().getTime(); displayTimeInfo(startTime, System.currentTimeMillis()); mStatus = STATUS.FINISHED; mTestSession.getSessionLog().setEndTime(System.currentTimeMillis()); mSessionObserver.notifyFinished(mTestSession); notifyResultObserver(); } /** * Mark need restarting ADB server. */ private void markNeedRestartADBServer() { Log.d("mark mNeedRestartAdbServer to true"); mNeedRestartAdbServer = true; mStatus = STATUS.FINISHED; notifyResultObserver(); return; } /** * Notify result observer. */ private void notifyResultObserver() { mResultObserver.notifyUpdate(); mResultObserver.finish(); } /** * Check if all tests contained in all of the test packages has been run. * * @return If all tests have been run, return true; else, return false. */ private boolean isAllTestsRun() { Collection<TestPackage> pkgs = getTestPackages(); for (TestPackage pkg : pkgs) { if (!pkg.isAllTestsRun()) { return false; } } return true; } /** * Display the summary of test result. */ private void displayTestResultSummary() { int passNum = mSessionLog.getTestList(CtsTestResult.CODE_PASS).size(); int failNum = mSessionLog.getTestList(CtsTestResult.CODE_FAIL).size(); int notExecutedNum = mSessionLog.getTestList(CtsTestResult.CODE_NOT_EXECUTED).size(); int timeOutNum = mSessionLog.getTestList(CtsTestResult.CODE_TIMEOUT).size(); int total = passNum + failNum + notExecutedNum + timeOutNum; println("Test summary: pass=" + passNum + " fail=" + failNum + " timeOut=" + timeOutNum + " notExecuted=" + notExecutedNum + " Total=" + total); } /** * Display the time information of running a test plan. * * @param startTime start time in milliseconds. * @param endTime end time in milliseconds. */ private void displayTimeInfo(final long startTime, final long endTime) { long diff = endTime - startTime; long seconds = diff / MSEC_PER_SECOND; long millisec = diff % MSEC_PER_SECOND; println("Time: " + seconds + "." + millisec + "s\n"); } } /** * Update test result after executing each test. * During running test, the process may be interrupted. To avoid * test result losing, it's needed to update the test result into * xml file after executing each test, which is done by this observer. * The possible reasons causing interruption to the process include: * <ul> * <li> Device disconnected * <li> Run time exception * <li> System crash * <li> User action to cause the system exit * </ul> * */ static class ResultObserver { static private boolean mFinished = false; static private boolean mNotified = false; //used for avoiding race condition static private boolean mNeedUpdate = true; static private TestSessionLog mSessionLog; static final ResultObserver sInstance = new ResultObserver(); private Observer mObserver; /** * Get the static instance. * * @return The static instance. */ public static final ResultObserver getInstance() { return sInstance; } /** * Set TestSessionLog. * * @param log The TestSessionLog. */ public void setTestSessionLog(TestSessionLog log) { mSessionLog = log; } /** * Notify this updating thread to update the test result to xml file. */ public void notifyUpdate() { if (mObserver != null) { synchronized (mObserver) { mNotified = true; mObserver.notify(); } } } /** * Start the observer. */ public void start() { mFinished = false; mNeedUpdate = true; mObserver = new Observer(); mObserver.start(); } /** * Finish updating. */ public void finish() { mFinished = true; mNeedUpdate = false; notifyUpdate(); try { mObserver.join(); mObserver = null; } catch (InterruptedException e) { } } /** * Observer which updates the test result to result XML file. * */ class Observer extends Thread { /** {@inheritDoc} */ @Override public void run() { while (!mFinished) { try { synchronized (this) { if ((!mNotified) && (!mFinished)) { wait(); } mNotified = false; } if (mNeedUpdate && (mSessionLog != null)) { mSessionLog.sessionComplete(); } } catch (InterruptedException e) { } } } } } }
true
true
public void run() { Log.d("Start a test session."); mNeedRestartAdbServer = false; mResultObserver.setTestSessionLog(getSessionLog()); mResultObserver.start(); try { if (mTest != null) { TestPackage pkg = mTest.getTestPackage(); pkg.setSessionThread(this); pkg.runTest(mDevice, mTest); } else if (mTestPackage != null) { mTestPackage.setSessionThread(this); mTestPackage.run(mDevice, mJavaPackageName, mSessionLog); } else { for (TestPackage pkg : mSessionLog.getTestPackages()) { if (!pkg.isAllTestsRun()) { pkg.setSessionThread(this); pkg.run(mDevice, null, mSessionLog); if (!isAllTestsRun()) { markNeedRestartADBServer(); return; } else { Log.d("All tests have been run."); break; } } } mNeedRestartAdbServer = false; displayTestResultSummary(); } } catch (IOException e) { Log.e("Got exception when running the package", e); } catch (DeviceDisconnectedException e) { Log.e("Device " + e.getMessage() + " disconnected ", null); } catch (ADBServerNeedRestartException e) { Log.d(e.getMessage()); if (mTest == null) { markNeedRestartADBServer(); return; } } catch (InvalidApkPathException e) { Log.e(e.getMessage(), null); } catch (InvalidNameSpaceException e) { Log.e(e.getMessage(), null); } long startTime = getSessionLog().getStartTime().getTime(); displayTimeInfo(startTime, System.currentTimeMillis()); mStatus = STATUS.FINISHED; mTestSession.getSessionLog().setEndTime(System.currentTimeMillis()); mSessionObserver.notifyFinished(mTestSession); notifyResultObserver(); }
public void run() { Log.d("Start a test session."); mNeedRestartAdbServer = false; mResultObserver.setTestSessionLog(getSessionLog()); mResultObserver.start(); try { if (mTest != null) { TestPackage pkg = mTest.getTestPackage(); pkg.setSessionThread(this); pkg.runTest(mDevice, mTest); } else if (mTestPackage != null) { mTestPackage.setSessionThread(this); mTestPackage.run(mDevice, mJavaPackageName, mSessionLog); } else { for (TestPackage pkg : mSessionLog.getTestPackages()) { if (!pkg.isAllTestsRun()) { pkg.setSessionThread(this); pkg.run(mDevice, null, mSessionLog); if (!isAllTestsRun()) { if (HostConfig.getMaxTestCount() > 0) { // ADB server restart enabled markNeedRestartADBServer(); return; } } else { Log.d("All tests have been run."); break; } } } mNeedRestartAdbServer = false; displayTestResultSummary(); } } catch (IOException e) { Log.e("Got exception when running the package", e); } catch (DeviceDisconnectedException e) { Log.e("Device " + e.getMessage() + " disconnected ", null); } catch (ADBServerNeedRestartException e) { Log.d(e.getMessage()); if (mTest == null) { markNeedRestartADBServer(); return; } } catch (InvalidApkPathException e) { Log.e(e.getMessage(), null); } catch (InvalidNameSpaceException e) { Log.e(e.getMessage(), null); } long startTime = getSessionLog().getStartTime().getTime(); displayTimeInfo(startTime, System.currentTimeMillis()); mStatus = STATUS.FINISHED; mTestSession.getSessionLog().setEndTime(System.currentTimeMillis()); mSessionObserver.notifyFinished(mTestSession); notifyResultObserver(); }
diff --git a/sip-servlets-test-suite/testsuite/src/main/java/org/mobicents/servlet/sip/SipEmbedded.java b/sip-servlets-test-suite/testsuite/src/main/java/org/mobicents/servlet/sip/SipEmbedded.java index 36191538b..246ce34b2 100644 --- a/sip-servlets-test-suite/testsuite/src/main/java/org/mobicents/servlet/sip/SipEmbedded.java +++ b/sip-servlets-test-suite/testsuite/src/main/java/org/mobicents/servlet/sip/SipEmbedded.java @@ -1,543 +1,544 @@ package org.mobicents.servlet.sip; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.StringTokenizer; import javax.management.MBeanServer; import javax.management.MBeanServerFactory; import javax.management.ObjectName; import org.apache.catalina.Container; import org.apache.catalina.Engine; import org.apache.catalina.connector.Connector; import org.apache.catalina.core.StandardContext; import org.apache.catalina.core.StandardEngine; import org.apache.catalina.core.StandardHost; import org.apache.catalina.loader.StandardClassLoader; import org.apache.catalina.security.SecurityClassLoad; import org.apache.catalina.security.SecurityConfig; import org.apache.catalina.startup.CatalinaProperties; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.log4j.BasicConfigurator; import org.apache.log4j.PropertyConfigurator; import org.apache.tomcat.util.IntrospectionUtils; import org.mobicents.servlet.sip.core.SipApplicationDispatcherImpl; import org.mobicents.servlet.sip.router.DefaultApplicationRouter; import org.mobicents.servlet.sip.startup.SipContextConfig; import org.mobicents.servlet.sip.startup.SipHostConfig; import org.mobicents.servlet.sip.startup.SipProtocolHandler; import org.mobicents.servlet.sip.startup.SipStandardContext; import org.mobicents.servlet.sip.startup.SipStandardService; /** * This class is emulating an embedded tomcat configured with sip servlets extension * to allow deployment of sip servlets apps to it. It is for the test suite purposes only for now... */ public class SipEmbedded { private static Log log = LogFactory.getLog(SipEmbedded.class); private String loggingFilePath = null; private String darConfigurationFilePath = null; private String path = null; private SipStandardService sipStandardService = null; private StandardHost host = null; /** * Default Constructor * */ public SipEmbedded() { } /** * Basic Accessor setting the value of the context path * * @param path - * the path */ public void setPath(String path) { this.path = path; } /** * Basic Accessor returning the value of the context path * * @return - the context path */ public String getPath() { return path; } /** * This method Starts the Tomcat server. */ public void startTomcat() throws Exception { // Set the home directory System.setProperty("catalina.home", getPath()); System.setProperty("catalina.base", getPath()); //logging configuration System.setProperty("java.util.logging.config.file", loggingFilePath); BasicConfigurator.configure(); PropertyConfigurator.configure(loggingFilePath); //Those are for trying to make it work under mvn test command // don't know why but some jars aren't loaded setSecurityProtection(); initDirs(); initNaming(); initClassLoaders(); Thread.currentThread().setContextClassLoader(catalinaLoader); SecurityClassLoad.securityClassLoad(catalinaLoader); /* * <Service className="org.mobicents.servlet.sip.startup.SipStandardService" * darConfigurationFileLocation="file:///E:/sip-serv/sip-servlets-impl/docs/dar.properties" * name="Catalina" * sipApplicationDispatcherClassName="org.mobicents.servlet.sip.core.SipApplicationDispatcherImpl" * sipApplicationRouterClassName="org.mobicents.servlet.sip.router.DefaultApplicationRouter"> */ SipApplicationDispatcherImpl sipApplicationDispatcher = new SipApplicationDispatcherImpl(); // Create an embedded server sipStandardService = new SipStandardService(); sipStandardService.setName("Catalina"); sipStandardService.setSipApplicationDispatcher(sipApplicationDispatcher); sipStandardService.setSipApplicationDispatcherClassName(SipApplicationDispatcherImpl.class.getName()); sipStandardService.setSipApplicationRouterClassName(DefaultApplicationRouter.class.getName()); sipStandardService.setDarConfigurationFileLocation(darConfigurationFilePath); // Create an engine Engine engine = new StandardEngine(); engine.setName("Catalina"); engine.setDefaultHost("localhost"); engine.setService(sipStandardService); // Create a default virtual host // host = (StandardHost) embedded.createHost("localhost", getPath() + "/webapps"); host = new StandardHost(); host.setAppBase(getPath() + "/webapps"); host.setName("localhost"); host.setConfigClass(StandardContext.class.getName()); host.setAppBase("webapps"); host.addLifecycleListener(new SipHostConfig()); host.setAutoDeploy(false); host.setDeployOnStartup(false); engine.addChild(host); // Install the assembled container hierarchy sipStandardService.setContainer(engine); /* * <Connector debugLog="../logs/debuglog.txt" ipAddress="0.0.0.0" * logLevel="DEBUG" port="5070" * protocol="org.mobicents.servlet.sip.startup.SipProtocolHandler" * serverLog="../logs/serverlog.txt" signalingTransport="udp" * sipPathName="gov.nist" sipStackName="SIP-Servlet-Tomcat-Server"/> */ Connector connector = new Connector( SipProtocolHandler.class.getName()); SipProtocolHandler ph = (SipProtocolHandler) connector .getProtocolHandler(); ph.setPort(5070); ph.setDebugLog("../logs/debuglog.txt"); ph.setIpAddress("127.0.0.1"); ph.setLogLevel("DEBUG"); ph.setServerLog("../logs/serverlog.txt"); ph.setSignalingTransport("udp"); ph.setSipPathName("gov.nist"); ph.setSipStackName("SIP-Servlet-Tomcat-Server"); sipStandardService.addConnector(connector); // Start the embedded server sipStandardService.start(); } /** * This method Stops the Tomcat server. */ public void stopTomcat() throws Exception { // Stop the embedded server sipStandardService.stop(); } /** * Deploy a context to the embedded tomcat container * @param contextPath the context Path of the context to deploy */ public Container deployContext(String docBase, String name, String path) { SipStandardContext context = new SipStandardContext(); context.setDocBase(docBase); context.setName(name); context.setPath(path); context.setParent(host); context.addLifecycleListener(new SipContextConfig()); host.addChild(context); return context; } public void undeployContext(Container context) { host.removeChild(context); } public String getDarConfigurationFilePath() { return darConfigurationFilePath; } public void setDarConfigurationFilePath(String darConfigurationFilePath) { this.darConfigurationFilePath = darConfigurationFilePath; } public String getLoggingFilePath() { return loggingFilePath; } public void setLoggingFilePath(String loggingFilePath) { this.loggingFilePath = loggingFilePath; } /** * Is naming enabled ? */ protected boolean useNaming = true; protected static final String CATALINA_HOME_TOKEN = "${catalina.home}"; protected static final String CATALINA_BASE_TOKEN = "${catalina.base}"; protected static final Integer IS_DIR = new Integer(0); protected static final Integer IS_JAR = new Integer(1); protected static final Integer IS_GLOB = new Integer(2); protected static final Integer IS_URL = new Integer(3); protected ClassLoader commonLoader = null; protected ClassLoader catalinaLoader = null; protected ClassLoader sharedLoader = null; private void initClassLoaders() throws Exception { commonLoader = createClassLoader("common", null); if( commonLoader == null ) { // no config file, default to this loader - we might be in a 'single' env. commonLoader=this.getClass().getClassLoader(); } catalinaLoader = createClassLoader("server", commonLoader); sharedLoader = createClassLoader("shared", commonLoader); } private ClassLoader createClassLoader(String name, ClassLoader parent) throws Exception { String value = CatalinaProperties.getProperty(name + ".loader"); if ((value == null) || (value.equals(""))) return parent; ArrayList repositoryLocations = new ArrayList(); ArrayList repositoryTypes = new ArrayList(); int i; StringTokenizer tokenizer = new StringTokenizer(value, ","); while (tokenizer.hasMoreElements()) { String repository = tokenizer.nextToken(); // Local repository boolean replace = false; String before = repository; while ((i=repository.indexOf(CATALINA_HOME_TOKEN))>=0) { replace=true; if (i>0) { repository = repository.substring(0,i) + getCatalinaHome() + repository.substring(i+CATALINA_HOME_TOKEN.length()); } else { repository = getCatalinaHome() + repository.substring(CATALINA_HOME_TOKEN.length()); } } while ((i=repository.indexOf(CATALINA_BASE_TOKEN))>=0) { replace=true; if (i>0) { repository = repository.substring(0,i) + getCatalinaBase() + repository.substring(i+CATALINA_BASE_TOKEN.length()); } else { repository = getCatalinaBase() + repository.substring(CATALINA_BASE_TOKEN.length()); } } if (replace && log.isDebugEnabled()) log.debug("Expanded " + before + " to " + replace); // Check for a JAR URL repository try { URL url=new URL(repository); repositoryLocations.add(repository); repositoryTypes.add(IS_URL); continue; } catch (MalformedURLException e) { // Ignore } if (repository.endsWith("*.jar")) { repository = repository.substring (0, repository.length() - "*.jar".length()); repositoryLocations.add(repository); repositoryTypes.add(IS_GLOB); } else if (repository.endsWith(".jar")) { repositoryLocations.add(repository); repositoryTypes.add(IS_JAR); } else { repositoryLocations.add(repository); repositoryTypes.add(IS_DIR); } } String[] locations = (String[]) repositoryLocations.toArray(new String[0]); Integer[] types = (Integer[]) repositoryTypes.toArray(new Integer[0]); ClassLoader classLoader = createClassLoader (locations, types, parent); // Retrieving MBean server MBeanServer mBeanServer = null; if (MBeanServerFactory.findMBeanServer(null).size() > 0) { mBeanServer = (MBeanServer) MBeanServerFactory.findMBeanServer(null).get(0); } else { mBeanServer = MBeanServerFactory.createMBeanServer(); } // Register the server classloader ObjectName objectName = new ObjectName("Catalina:type=ServerClassLoader,name=" + name); - mBeanServer.registerMBean(classLoader, objectName); + if(!mBeanServer.isRegistered(objectName)) + mBeanServer.registerMBean(classLoader, objectName); return classLoader; } /** * Get the value of the catalina.home environment variable. */ public static String getCatalinaHome() { return System.getProperty("catalina.home", System.getProperty("user.dir")); } /** * Get the value of the catalina.base environment variable. */ public static String getCatalinaBase() { return System.getProperty("catalina.base", getCatalinaHome()); } /** * Create and return a new class loader, based on the configuration * defaults and the specified directory paths: * * @param locations Array of strings containing class directories, jar files, * jar directories or URLS that should be added to the repositories of * the class loader. The type is given by the member of param types. * @param types Array of types for the members of param locations. * Possible values are IS_DIR (class directory), IS_JAR (single jar file), * IS_GLOB (directory of jar files) and IS_URL (URL). * @param parent Parent class loader for the new class loader, or * <code>null</code> for the system class loader. * * @exception Exception if an error occurs constructing the class loader */ public static ClassLoader createClassLoader(String locations[], Integer types[], ClassLoader parent) throws Exception { if (log.isDebugEnabled()) log.debug("Creating new class loader"); // Construct the "class path" for this class loader ArrayList list = new ArrayList(); if (locations != null && types != null && locations.length == types.length) { for (int i = 0; i < locations.length; i++) { String location = locations[i]; if ( types[i] == IS_URL ) { URL url = new URL(location); if (log.isDebugEnabled()) log.debug(" Including URL " + url); list.add(url); } else if ( types[i] == IS_DIR ) { File directory = new File(location); directory = new File(directory.getCanonicalPath()); if (!directory.exists() || !directory.isDirectory() || !directory.canRead()) continue; URL url = directory.toURL(); if (log.isDebugEnabled()) log.debug(" Including directory " + url); list.add(url); } else if ( types[i] == IS_JAR ) { File file=new File(location); file = new File(file.getCanonicalPath()); if (!file.exists() || !file.canRead()) continue; URL url = file.toURL(); if (log.isDebugEnabled()) log.debug(" Including jar file " + url); list.add(url); } else if ( types[i] == IS_GLOB ) { File directory=new File(location); if (!directory.exists() || !directory.isDirectory() || !directory.canRead()) continue; if (log.isDebugEnabled()) log.debug(" Including directory glob " + directory.getAbsolutePath()); String filenames[] = directory.list(); for (int j = 0; j < filenames.length; j++) { String filename = filenames[j].toLowerCase(); if (!filename.endsWith(".jar")) continue; File file = new File(directory, filenames[j]); file = new File(file.getCanonicalPath()); if (!file.exists() || !file.canRead()) continue; if (log.isDebugEnabled()) log.debug(" Including glob jar file " + file.getAbsolutePath()); URL url = file.toURL(); list.add(url); } } } } // Construct the class loader itself URL[] array = (URL[]) list.toArray(new URL[list.size()]); if (log.isDebugEnabled()) for (int i = 0; i < array.length; i++) { log.debug(" location " + i + " is " + array[i]); } StandardClassLoader classLoader = null; if (parent == null) classLoader = new StandardClassLoader(array); else classLoader = new StandardClassLoader(array, parent); return (classLoader); } /** * Set the security package access/protection. */ protected void setSecurityProtection(){ SecurityConfig securityConfig = SecurityConfig.newInstance(); securityConfig.setPackageDefinition(); securityConfig.setPackageAccess(); } /** Initialize naming - this should only enable java:env and root naming. * If tomcat is embeded in an application that already defines those - * it shouldn't do it. * * XXX The 2 should be separated, you may want to enable java: but not * the initial context and the reverse * XXX Can we "guess" - i.e. lookup java: and if something is returned assume * false ? * XXX We have a major problem with the current setting for java: url */ protected void initNaming() { // Setting additional variables if (!useNaming) { log.info( "Catalina naming disabled"); System.setProperty("catalina.useNaming", "false"); } else { System.setProperty("catalina.useNaming", "true"); String value = "org.apache.naming"; String oldValue = System.getProperty(javax.naming.Context.URL_PKG_PREFIXES); if (oldValue != null) { value = value + ":" + oldValue; } System.setProperty(javax.naming.Context.URL_PKG_PREFIXES, value); if( log.isDebugEnabled() ) log.debug("Setting naming prefix=" + value); value = System.getProperty (javax.naming.Context.INITIAL_CONTEXT_FACTORY); if (value == null) { System.setProperty (javax.naming.Context.INITIAL_CONTEXT_FACTORY, "org.apache.naming.java.javaURLContextFactory"); } else { log.debug( "INITIAL_CONTEXT_FACTORY alread set " + value ); } } } protected void initDirs() { String catalinaHome = System.getProperty("catalina.home"); if (catalinaHome == null) { // Backwards compatibility patch for J2EE RI 1.3 String j2eeHome = System.getProperty("com.sun.enterprise.home"); if (j2eeHome != null) { catalinaHome=System.getProperty("com.sun.enterprise.home"); } else if (System.getProperty("catalina.base") != null) { catalinaHome = System.getProperty("catalina.base"); } else { // Use IntrospectionUtils and guess the dir catalinaHome = IntrospectionUtils.guessInstall ("catalina.home", "catalina.base", "catalina.jar"); if (catalinaHome == null) { catalinaHome = IntrospectionUtils.guessInstall ("tomcat.install", "catalina.home", "tomcat.jar"); } } } // last resort - for minimal/embedded cases. if(catalinaHome==null) { catalinaHome=System.getProperty("user.dir"); } if (catalinaHome != null) { File home = new File(catalinaHome); if (!home.isAbsolute()) { try { catalinaHome = home.getCanonicalPath(); } catch (IOException e) { catalinaHome = home.getAbsolutePath(); } } System.setProperty("catalina.home", catalinaHome); } if (System.getProperty("catalina.base") == null) { System.setProperty("catalina.base", catalinaHome); } else { String catalinaBase = System.getProperty("catalina.base"); File base = new File(catalinaBase); if (!base.isAbsolute()) { try { catalinaBase = base.getCanonicalPath(); } catch (IOException e) { catalinaBase = base.getAbsolutePath(); } } System.setProperty("catalina.base", catalinaBase); } String temp = System.getProperty("java.io.tmpdir"); if (temp == null || (!(new File(temp)).exists()) || (!(new File(temp)).isDirectory())) { log.error("no temp directory"+ temp); } } }
true
true
private ClassLoader createClassLoader(String name, ClassLoader parent) throws Exception { String value = CatalinaProperties.getProperty(name + ".loader"); if ((value == null) || (value.equals(""))) return parent; ArrayList repositoryLocations = new ArrayList(); ArrayList repositoryTypes = new ArrayList(); int i; StringTokenizer tokenizer = new StringTokenizer(value, ","); while (tokenizer.hasMoreElements()) { String repository = tokenizer.nextToken(); // Local repository boolean replace = false; String before = repository; while ((i=repository.indexOf(CATALINA_HOME_TOKEN))>=0) { replace=true; if (i>0) { repository = repository.substring(0,i) + getCatalinaHome() + repository.substring(i+CATALINA_HOME_TOKEN.length()); } else { repository = getCatalinaHome() + repository.substring(CATALINA_HOME_TOKEN.length()); } } while ((i=repository.indexOf(CATALINA_BASE_TOKEN))>=0) { replace=true; if (i>0) { repository = repository.substring(0,i) + getCatalinaBase() + repository.substring(i+CATALINA_BASE_TOKEN.length()); } else { repository = getCatalinaBase() + repository.substring(CATALINA_BASE_TOKEN.length()); } } if (replace && log.isDebugEnabled()) log.debug("Expanded " + before + " to " + replace); // Check for a JAR URL repository try { URL url=new URL(repository); repositoryLocations.add(repository); repositoryTypes.add(IS_URL); continue; } catch (MalformedURLException e) { // Ignore } if (repository.endsWith("*.jar")) { repository = repository.substring (0, repository.length() - "*.jar".length()); repositoryLocations.add(repository); repositoryTypes.add(IS_GLOB); } else if (repository.endsWith(".jar")) { repositoryLocations.add(repository); repositoryTypes.add(IS_JAR); } else { repositoryLocations.add(repository); repositoryTypes.add(IS_DIR); } } String[] locations = (String[]) repositoryLocations.toArray(new String[0]); Integer[] types = (Integer[]) repositoryTypes.toArray(new Integer[0]); ClassLoader classLoader = createClassLoader (locations, types, parent); // Retrieving MBean server MBeanServer mBeanServer = null; if (MBeanServerFactory.findMBeanServer(null).size() > 0) { mBeanServer = (MBeanServer) MBeanServerFactory.findMBeanServer(null).get(0); } else { mBeanServer = MBeanServerFactory.createMBeanServer(); } // Register the server classloader ObjectName objectName = new ObjectName("Catalina:type=ServerClassLoader,name=" + name); mBeanServer.registerMBean(classLoader, objectName); return classLoader; }
private ClassLoader createClassLoader(String name, ClassLoader parent) throws Exception { String value = CatalinaProperties.getProperty(name + ".loader"); if ((value == null) || (value.equals(""))) return parent; ArrayList repositoryLocations = new ArrayList(); ArrayList repositoryTypes = new ArrayList(); int i; StringTokenizer tokenizer = new StringTokenizer(value, ","); while (tokenizer.hasMoreElements()) { String repository = tokenizer.nextToken(); // Local repository boolean replace = false; String before = repository; while ((i=repository.indexOf(CATALINA_HOME_TOKEN))>=0) { replace=true; if (i>0) { repository = repository.substring(0,i) + getCatalinaHome() + repository.substring(i+CATALINA_HOME_TOKEN.length()); } else { repository = getCatalinaHome() + repository.substring(CATALINA_HOME_TOKEN.length()); } } while ((i=repository.indexOf(CATALINA_BASE_TOKEN))>=0) { replace=true; if (i>0) { repository = repository.substring(0,i) + getCatalinaBase() + repository.substring(i+CATALINA_BASE_TOKEN.length()); } else { repository = getCatalinaBase() + repository.substring(CATALINA_BASE_TOKEN.length()); } } if (replace && log.isDebugEnabled()) log.debug("Expanded " + before + " to " + replace); // Check for a JAR URL repository try { URL url=new URL(repository); repositoryLocations.add(repository); repositoryTypes.add(IS_URL); continue; } catch (MalformedURLException e) { // Ignore } if (repository.endsWith("*.jar")) { repository = repository.substring (0, repository.length() - "*.jar".length()); repositoryLocations.add(repository); repositoryTypes.add(IS_GLOB); } else if (repository.endsWith(".jar")) { repositoryLocations.add(repository); repositoryTypes.add(IS_JAR); } else { repositoryLocations.add(repository); repositoryTypes.add(IS_DIR); } } String[] locations = (String[]) repositoryLocations.toArray(new String[0]); Integer[] types = (Integer[]) repositoryTypes.toArray(new Integer[0]); ClassLoader classLoader = createClassLoader (locations, types, parent); // Retrieving MBean server MBeanServer mBeanServer = null; if (MBeanServerFactory.findMBeanServer(null).size() > 0) { mBeanServer = (MBeanServer) MBeanServerFactory.findMBeanServer(null).get(0); } else { mBeanServer = MBeanServerFactory.createMBeanServer(); } // Register the server classloader ObjectName objectName = new ObjectName("Catalina:type=ServerClassLoader,name=" + name); if(!mBeanServer.isRegistered(objectName)) mBeanServer.registerMBean(classLoader, objectName); return classLoader; }
diff --git a/src/net/java/sip/communicator/impl/neomedia/jmfext/media/renderer/video/JAWTRenderer.java b/src/net/java/sip/communicator/impl/neomedia/jmfext/media/renderer/video/JAWTRenderer.java index 609b28089..1e0aa1770 100644 --- a/src/net/java/sip/communicator/impl/neomedia/jmfext/media/renderer/video/JAWTRenderer.java +++ b/src/net/java/sip/communicator/impl/neomedia/jmfext/media/renderer/video/JAWTRenderer.java @@ -1,487 +1,490 @@ /* * SIP Communicator, the OpenSource Java VoIP and Instant Messaging client. * * Distributable under LGPL license. * See terms of license at gnu.org. */ package net.java.sip.communicator.impl.neomedia.jmfext.media.renderer.video; import java.awt.*; import javax.media.*; import javax.media.format.*; import javax.media.renderer.*; import net.java.sip.communicator.impl.neomedia.control.*; /** * Implements a <tt>VideoRenderer</tt> which uses JAWT to perform native * painting in an AWT <tt>Canvas</tt>. * * @author Lubomir Marinov */ public class JAWTRenderer extends ControlsAdapter implements VideoRenderer { /** * The human-readable <tt>PlugIn</tt> name of the <tt>JAWTRenderer</tt> * instances. */ private static final String PLUGIN_NAME = "JAWT Renderer"; private static final Format[] SUPPORTED_INPUT_FORMATS = new Format[] { new RGBFormat( null, Format.NOT_SPECIFIED, Format.intArray, Format.NOT_SPECIFIED, 32, 0x00FF0000, 0x0000FF00, 0x000000FF) }; static { System.loadLibrary("jawtrenderer"); } /** * The AWT <tt>Component</tt> into which this <tt>VideoRenderer</tt> draws. */ private Component component; /** * The handle of the native counterpart of this <tt>JAWTRenderer</tt>. */ long handle = 0; /** * The <tt>VideoFormat</tt> of the input processed by this * <tt>Renderer</tt>. */ private VideoFormat inputFormat; /** * The last known height of the input processed by this * <tt>JAWTRenderer</tt>. */ private int inputHeight = 0; /** * The last known width of the input processed by this * <tt>JAWTRenderer</tt>. */ private int inputWidth = 0; /** * Initializes a new <tt>JAWTRenderer</tt> instance. */ public JAWTRenderer() { } /** * Closes this <tt>PlugIn</tt> and releases the resources it has retained * during its execution. No more data will be accepted by this * <tt>PlugIn</tt> afterwards. A closed <tt>PlugIn</tt> can be reinstated by * calling <tt>open</tt> again. */ public synchronized void close() { if (handle != 0) { close(handle, getComponent()); handle = 0; } } /** * Closes the native counterpart of a <tt>JAWTRenderer</tt> specified by its * handle as returned by {@link #open(Component)} and rendering into a * specific AWT <tt>Component</tt>. Releases the resources which the * specified native counterpart has retained during its execution and its * handle is considered to be invalid afterwards. * * @param handle the handle to the native counterpart of a * <tt>JAWTRenderer</tt> as returned by {@link #open(Component)} which is to * be closed * @param component the AWT <tt>Component</tt> into which the * <tt>JAWTRenderer</tt> and its native counterpart are drawing. The * platform-specific info of <tt>component</tt> is not guranteed to be * valid. */ private static native void close(long handle, Component component); /** * Gets the region in the component of this <tt>VideoRenderer</tt> where the * video is rendered. * * @return the region in the component of this <tt>VideoRenderer</tt> where * the video is rendered; <tt>null</tt> if the entire component is used */ public Rectangle getBounds() { // TODO Auto-generated method stub return null; } /** * Gets the AWT <tt>Component</tt> into which this <tt>VideoRenderer</tt> * draws. * * @return the AWT <tt>Component</tt> into which this <tt>VideoRenderer</tt> * draws */ public synchronized Component getComponent() { if (component == null) { component = new Canvas() { /** * The indicator which determines whether the native counterpart * of this <tt>JAWTRenderer</tt> wants <tt>paint</tt> calls on * its AWT <tt>Component</tt> to be delivered. For example, * after the native counterpart has been able to acquire the * native handle of the AWT <tt>Component</tt>, it may be able * to determine when the native handle needs painting without * waiting for AWT to call <tt>paint</tt> on the * <tt>Component</tt>. In such a scenario, the native * counterpart may indicate with <tt>false</tt> that it does not * need further <tt>paint</tt> deliveries. */ private boolean wantsPaint = true; @Override public void addNotify() { super.addNotify(); wantsPaint = true; } @Override public void paint(Graphics g) { synchronized (JAWTRenderer.this) { if (wantsPaint && (handle != 0)) { wantsPaint = JAWTRenderer.this.paint(handle, this, g); } } } @Override public void removeNotify() { wantsPaint = true; super.removeNotify(); } @Override public void update(Graphics g) { - /* do not clear screen since it cause flickering */ + /* + * Skip the filling with the background color because it + * causes flickering. + */ paint(g); } }; } return component; } /** * Gets the human-readable name of this <tt>PlugIn</tt>. * * @return the human-readable name of this <tt>PlugIn</tt> */ public String getName() { return PLUGIN_NAME; } /** * Gets the list of input <tt>Format</tt>s supported by this * <tt>Renderer</tt>. * * @return an array of <tt>Format</tt> elements which represent the input * <tt>Format</tt>s supported by this <tt>Renderer</tt> */ public Format[] getSupportedInputFormats() { return SUPPORTED_INPUT_FORMATS.clone(); } /** * Opens this <tt>PlugIn</tt> and acquires the resources that it needs to * operate. The input format of this <tt>Renderer</tt> has to be set before * <tt>open</tt> is called. Buffers should not be passed into this * <tt>PlugIn</tt> without first calling <tt>open</tt>. */ public synchronized void open() throws ResourceUnavailableException { if (handle == 0) { handle = open(getComponent()); if (handle == 0) { throw new ResourceUnavailableException( "Failed to open the native counterpart of" + " JAWTRenderer"); } } } /** * Opens a handle to a native counterpart of a <tt>JAWTRenderer</tt> which * is to draw into a specific AWT <tt>Component</tt>. * * @param component the AWT <tt>Component</tt> into which a * <tt>JAWTRenderer</tt> and the native counterpart to be opened are to * draw. The platform-specific info of <tt>component</tt> is not guaranteed * to be valid. * @return a handle to a native counterpart of a <tt>JAWTRenderer</tt> which * is to draw into the specified AWT <tt>Component</tt> */ private static native long open(Component component) throws ResourceUnavailableException; /** * Paints a specific <tt>Component</tt> which is the AWT <tt>Component</tt> * of a <tt>JAWTRenderer</tt> specified by the handle to its native * counterpart. * * @param handle the handle to the native counterpart of a * <tt>JAWTRenderer</tt> which is to draw into the specified AWT * <tt>Component</tt> * @param component the AWT <tt>Component</tt> into which the * <tt>JAWTRenderer</tt> and its native counterpart specified by * <tt>handle</tt> are to draw. The platform-specific info of * <tt>component</tt> is guaranteed to be valid only during the execution of * <tt>paint</tt>. * @param g the <tt>Graphics</tt> context into which the drawing is to be * performed * @return <tt>true</tt> if the native counterpart of a * <tt>JAWTRenderer</tt> wants to continue receiving the <tt>paint</tt> * calls on the AWT <tt>Component</tt>; otherwise, false. For example, after * the native counterpart has been able to acquire the native handle of the * AWT <tt>Component</tt>, it may be able to determine when the native * handle needs painting without waiting for AWT to call <tt>paint</tt> on * the <tt>Component</tt>. In such a scenario, the native counterpart may * indicate with <tt>false</tt> that it does not need further <tt>paint</tt> * deliveries. */ private static native boolean paint( long handle, Component component, Graphics g); /** * Processes the data provided in a specific <tt>Buffer</tt> and renders it * to the output device represented by this <tt>Renderer</tt>. * * @param buffer a <tt>Buffer</tt> containing the data to be processed and * rendered * @return <tt>BUFFER_PROCESSED_OK</tt> if the processing is successful; * otherwise, the other possible return codes defined in the <tt>PlugIn</tt> * interface */ public synchronized int process(Buffer buffer) { if (buffer.isDiscard()) return BUFFER_PROCESSED_OK; int bufferLength = buffer.getLength(); if (bufferLength == 0) return BUFFER_PROCESSED_OK; Format bufferFormat = buffer.getFormat(); if ((bufferFormat != null) && (bufferFormat != this.inputFormat) && !bufferFormat.equals(this.inputFormat)) { if (setInputFormat(bufferFormat) == null) return BUFFER_PROCESSED_FAILED; } if (handle == 0) return BUFFER_PROCESSED_FAILED; else { Dimension size = null; if (bufferFormat != null) size = ((VideoFormat) bufferFormat).getSize(); if (size == null) { size = this.inputFormat.getSize(); if (size == null) return BUFFER_PROCESSED_FAILED; } Component component = getComponent(); boolean processed = process( handle, component, (int[]) buffer.getData(), buffer.getOffset(), bufferLength, size.width, size.height); if (processed) { component.repaint(); return BUFFER_PROCESSED_OK; } else return BUFFER_PROCESSED_FAILED; } } /** * Processes the data provided in a specific <tt>int</tt> array with a * specific offset and length and renders it to the output device * represented by a <tt>JAWTRenderer</tt> specified by the handle to it * native counterpart. * * @param handle the handle to the native counterpart of a * <tt>JAWTRenderer</tt> to process the specified data and render it * @param component the <tt>AWT</tt> component into which the specified * <tt>JAWTRenderer</tt> and its native counterpart draw * @param data an <tt>int</tt> array which contains the data to be processed * and rendered * @param offset the index in <tt>data</tt> at which the data to be * processed and rendered starts * @param length the number of elements in <tt>data</tt> starting at * <tt>offset</tt> which represent the data to be processed and rendered * @param width the width of the video frame in <tt>data</tt> * @param height the height of the video frame in <tt>data</tt> */ private static native boolean process( long handle, Component component, int[] data, int offset, int length, int width, int height); /** * Resets the state of this <tt>PlugIn</tt>. */ public void reset() { // TODO Auto-generated method stub } /** * Sets the region in the component of this <tt>VideoRenderer</tt> where the * video is to be rendered. * * @param bounds the region in the component of this <tt>VideoRenderer</tt> * where the video is to be rendered; <tt>null</tt> if the entire component * is to be used */ public void setBounds(Rectangle bounds) { // TODO Auto-generated method stub } /** * Sets the AWT <tt>Component</tt> into which this <tt>VideoRenderer</tt> is * to draw. <tt>JAWTRenderer</tt> cannot draw into any other AWT * <tt>Component</tt> but its own so it always returns <tt>false</tt>. * * @param component the AWT <tt>Component</tt> into which this * <tt>VideoRenderer</tt> is to draw * @return <tt>true</tt> if this <tt>VideoRenderer</tt> accepted the * specified <tt>component</tt> as the AWT <tt>Component</tt> into which it * is to draw; <tt>false</tt>, otherwise */ public boolean setComponent(Component component) { // We cannot draw into any other AWT Component but our own. return false; } /** * Sets the <tt>Format</tt> of the input to be processed by this * <tt>Renderer</tt>. * * @param format the <tt>Format</tt> to be set as the <tt>Format</tt> of the * input to be processed by this <tt>Renderer</tt> * @return the <tt>Format</tt> of the input to be processed by this * <tt>Renderer</tt> if the specified <tt>format</tt> is supported or * <tt>null</tt> if the specified <tt>format</tt> is not supported by this * <tt>Renderer</tt>. Typically, it is the supported input <tt>Format</tt> * which most closely matches the specified <tt>Format</tt>. */ public Format setInputFormat(Format format) { Format matchingFormat = null; for (Format supportedInputFormat : getSupportedInputFormats()) { if (supportedInputFormat.matches(format)) { matchingFormat = supportedInputFormat.intersects(format); break; } } if (matchingFormat == null) return null; inputFormat = (VideoFormat) format; /* * Know the width and height of the input because we'll be depicting it * and we may want, for example, to report it as the preferred size of * our AWT Component. */ Dimension inputSize = inputFormat.getSize(); if (inputSize != null) { inputWidth = inputSize.width; inputHeight = inputSize.height; } /* * Reflect the width and height of the input onto the preferredSize of * our AWT Component (if necessary). */ if ((inputWidth > 0) && (inputHeight > 0)) { Component component = getComponent(); Dimension preferredSize = component.getPreferredSize(); if ((preferredSize == null) || (preferredSize.width < 1) || (preferredSize.height < 1)) { component.setPreferredSize( new Dimension(inputWidth, inputHeight)); } } return inputFormat; } /** * Starts the rendering process. Begins rendering any data available in the * internal buffers of this <tt>Renderer</tt>. */ public void start() { } /** * Stops the rendering process. */ public void stop() { } }
true
true
public synchronized Component getComponent() { if (component == null) { component = new Canvas() { /** * The indicator which determines whether the native counterpart * of this <tt>JAWTRenderer</tt> wants <tt>paint</tt> calls on * its AWT <tt>Component</tt> to be delivered. For example, * after the native counterpart has been able to acquire the * native handle of the AWT <tt>Component</tt>, it may be able * to determine when the native handle needs painting without * waiting for AWT to call <tt>paint</tt> on the * <tt>Component</tt>. In such a scenario, the native * counterpart may indicate with <tt>false</tt> that it does not * need further <tt>paint</tt> deliveries. */ private boolean wantsPaint = true; @Override public void addNotify() { super.addNotify(); wantsPaint = true; } @Override public void paint(Graphics g) { synchronized (JAWTRenderer.this) { if (wantsPaint && (handle != 0)) { wantsPaint = JAWTRenderer.this.paint(handle, this, g); } } } @Override public void removeNotify() { wantsPaint = true; super.removeNotify(); } @Override public void update(Graphics g) { /* do not clear screen since it cause flickering */ paint(g); } }; } return component; }
public synchronized Component getComponent() { if (component == null) { component = new Canvas() { /** * The indicator which determines whether the native counterpart * of this <tt>JAWTRenderer</tt> wants <tt>paint</tt> calls on * its AWT <tt>Component</tt> to be delivered. For example, * after the native counterpart has been able to acquire the * native handle of the AWT <tt>Component</tt>, it may be able * to determine when the native handle needs painting without * waiting for AWT to call <tt>paint</tt> on the * <tt>Component</tt>. In such a scenario, the native * counterpart may indicate with <tt>false</tt> that it does not * need further <tt>paint</tt> deliveries. */ private boolean wantsPaint = true; @Override public void addNotify() { super.addNotify(); wantsPaint = true; } @Override public void paint(Graphics g) { synchronized (JAWTRenderer.this) { if (wantsPaint && (handle != 0)) { wantsPaint = JAWTRenderer.this.paint(handle, this, g); } } } @Override public void removeNotify() { wantsPaint = true; super.removeNotify(); } @Override public void update(Graphics g) { /* * Skip the filling with the background color because it * causes flickering. */ paint(g); } }; } return component; }
diff --git a/tests/DiagTalker.java b/tests/DiagTalker.java index 85a6671e..04e12327 100644 --- a/tests/DiagTalker.java +++ b/tests/DiagTalker.java @@ -1,69 +1,70 @@ /* A yet very simple tool to talk to imdiag. * * Copyright 2009 Rainer Gerhards and Adiscon GmbH. * * This file is part of rsyslog. * * Rsyslog 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. * * Rsyslog 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 Rsyslog. If not, see <http://www.gnu.org/licenses/>. * * A copy of the GPL can be found in the file "COPYING" in this distribution. */ //package com.rsyslog.diag; import java.io.*; import java.net.*; public class DiagTalker { public static void main(String[] args) throws IOException { Socket diagSocket = null; PrintWriter out = null; BufferedReader in = null; final String host = "127.0.0.1"; final int port = 13500; try { diagSocket = new Socket(host, port); + diagSocket.setSoTimeout(0); /* wait for lenghty operations */ out = new PrintWriter(diagSocket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader( diagSocket.getInputStream())); } catch (UnknownHostException e) { System.err.println("can not resolve " + host + "!"); System.exit(1); } catch (IOException e) { System.err.println("Couldn't get I/O for " + "the connection to: " + host + "."); System.exit(1); } BufferedReader stdIn = new BufferedReader( new InputStreamReader(System.in)); String userInput; try { while ((userInput = stdIn.readLine()) != null) { out.println(userInput); System.out.println("imdiag returns: " + in.readLine()); } } catch (SocketException e) { System.err.println("We had a socket exception and consider this to be OK: " + e.getMessage()); } out.close(); in.close(); stdIn.close(); diagSocket.close(); } }
true
true
public static void main(String[] args) throws IOException { Socket diagSocket = null; PrintWriter out = null; BufferedReader in = null; final String host = "127.0.0.1"; final int port = 13500; try { diagSocket = new Socket(host, port); out = new PrintWriter(diagSocket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader( diagSocket.getInputStream())); } catch (UnknownHostException e) { System.err.println("can not resolve " + host + "!"); System.exit(1); } catch (IOException e) { System.err.println("Couldn't get I/O for " + "the connection to: " + host + "."); System.exit(1); } BufferedReader stdIn = new BufferedReader( new InputStreamReader(System.in)); String userInput; try { while ((userInput = stdIn.readLine()) != null) { out.println(userInput); System.out.println("imdiag returns: " + in.readLine()); } } catch (SocketException e) { System.err.println("We had a socket exception and consider this to be OK: " + e.getMessage()); } out.close(); in.close(); stdIn.close(); diagSocket.close(); }
public static void main(String[] args) throws IOException { Socket diagSocket = null; PrintWriter out = null; BufferedReader in = null; final String host = "127.0.0.1"; final int port = 13500; try { diagSocket = new Socket(host, port); diagSocket.setSoTimeout(0); /* wait for lenghty operations */ out = new PrintWriter(diagSocket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader( diagSocket.getInputStream())); } catch (UnknownHostException e) { System.err.println("can not resolve " + host + "!"); System.exit(1); } catch (IOException e) { System.err.println("Couldn't get I/O for " + "the connection to: " + host + "."); System.exit(1); } BufferedReader stdIn = new BufferedReader( new InputStreamReader(System.in)); String userInput; try { while ((userInput = stdIn.readLine()) != null) { out.println(userInput); System.out.println("imdiag returns: " + in.readLine()); } } catch (SocketException e) { System.err.println("We had a socket exception and consider this to be OK: " + e.getMessage()); } out.close(); in.close(); stdIn.close(); diagSocket.close(); }
diff --git a/main/src/cgeo/geocaching/export/GpxExport.java b/main/src/cgeo/geocaching/export/GpxExport.java index 084a37855..6ed0a3ecd 100644 --- a/main/src/cgeo/geocaching/export/GpxExport.java +++ b/main/src/cgeo/geocaching/export/GpxExport.java @@ -1,325 +1,325 @@ package cgeo.geocaching.export; import cgeo.geocaching.LogEntry; import cgeo.geocaching.R; import cgeo.geocaching.cgCache; import cgeo.geocaching.cgWaypoint; import cgeo.geocaching.cgeoapplication; import cgeo.geocaching.activity.ActivityMixin; import cgeo.geocaching.activity.Progress; import cgeo.geocaching.enumerations.CacheAttribute; import cgeo.geocaching.enumerations.LoadFlags; import cgeo.geocaching.utils.BaseUtils; import cgeo.geocaching.utils.Log; import org.apache.commons.lang3.StringEscapeUtils; import android.app.Activity; import android.app.ProgressDialog; import android.os.AsyncTask; import android.os.Environment; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; class GpxExport extends AbstractExport { private static final File exportLocation = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/gpx"); private static final SimpleDateFormat dateFormatZ = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); protected GpxExport() { super(getString(R.string.export_gpx)); } @Override public void export(final List<cgCache> caches, final Activity activity) { new ExportTask(caches, activity).execute((Void) null); } private class ExportTask extends AsyncTask<Void, Integer, Boolean> { private final List<cgCache> caches; private final Activity activity; private final Progress progress = new Progress(); private File exportFile; /** * Instantiates and configures the task for exporting field notes. * * @param caches * The {@link List} of {@link cgCache} to be exported * @param activity * optional: Show a progress bar and toasts */ public ExportTask(final List<cgCache> caches, final Activity activity) { this.caches = caches; this.activity = activity; } @Override protected void onPreExecute() { if (null != activity) { progress.show(activity, null, getString(R.string.export) + ": " + getName(), ProgressDialog.STYLE_HORIZONTAL, null); progress.setMaxProgressAndReset(caches.size()); } } @Override protected Boolean doInBackground(Void... params) { // quick check for being able to write the GPX file if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { return false; } Writer gpx = null; try { exportLocation.mkdirs(); final SimpleDateFormat fileNameDateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); exportFile = new File(exportLocation.toString() + File.separatorChar + "export_" + fileNameDateFormat.format(new Date()) + ".gpx"); gpx = new BufferedWriter(new FileWriter(exportFile)); gpx.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); gpx.write("<gpx version=\"1.0\" creator=\"c:geo - http://www.cgeo.org\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://www.topografix.com/GPX/1/0\" xsi:schemaLocation=\"http://www.topografix.com/GPX/1/0 http://www.topografix.com/GPX/1/0/gpx.xsd http://www.topografix.com/GPX/1/0 http://www.topografix.com/GPX/1/0/gpx.xsd http://www.groundspeak.com/cache/1/0/1 http://www.groundspeak.com/cache/1/0/1/cache.xsd\">"); for (int i = 0; i < caches.size(); i++) { // reload the cache. otherwise logs, attributes and other detailed information is not available final cgCache cache = cgeoapplication.getInstance().loadCache(caches.get(i).getGeocode(), LoadFlags.LOAD_ALL_DB_ONLY); gpx.write("<wpt "); gpx.write("lat=\""); gpx.write(Double.toString(cache.getCoords().getLatitude())); gpx.write("\" "); gpx.write("lon=\""); gpx.write(Double.toString(cache.getCoords().getLongitude())); gpx.write("\">"); gpx.write("<time>"); gpx.write(StringEscapeUtils.escapeXml(dateFormatZ.format(cache.getHiddenDate()))); gpx.write("</time>"); gpx.write("<name>"); gpx.write(StringEscapeUtils.escapeXml(cache.getGeocode())); gpx.write("</name>"); gpx.write("<desc>"); gpx.write(StringEscapeUtils.escapeXml(cache.getName())); gpx.write("</desc>"); gpx.write("<sym>"); gpx.write(cache.isFound() ? "Geocache Found" : "Geocache"); gpx.write("</sym>"); gpx.write("<type>"); - gpx.write(StringEscapeUtils.escapeXml("Geocache|" + cache.getType().id)); + gpx.write(StringEscapeUtils.escapeXml("Geocache|" + cache.getType().pattern)); gpx.write("</type>"); gpx.write("<groundspeak:cache "); gpx.write("available=\""); gpx.write(!cache.isDisabled() ? "True" : "False"); gpx.write("\" archived=\""); gpx.write(cache.isArchived() ? "True" : "False"); gpx.write("\" "); gpx.write("xmlns:groundspeak=\"http://www.groundspeak.com/cache/1/0/1\">"); gpx.write("<groundspeak:name>"); gpx.write(StringEscapeUtils.escapeXml(cache.getName())); gpx.write("</groundspeak:name>"); gpx.write("<groundspeak:placed_by>"); gpx.write(StringEscapeUtils.escapeXml(cache.getOwner())); gpx.write("</groundspeak:placed_by>"); gpx.write("<groundspeak:owner>"); gpx.write(StringEscapeUtils.escapeXml(cache.getOwnerReal())); gpx.write("</groundspeak:owner>"); gpx.write("<groundspeak:type>"); - gpx.write(StringEscapeUtils.escapeXml(cache.getType().id)); + gpx.write(StringEscapeUtils.escapeXml(cache.getType().pattern)); gpx.write("</groundspeak:type>"); gpx.write("<groundspeak:container>"); gpx.write(StringEscapeUtils.escapeXml(cache.getSize().id)); gpx.write("</groundspeak:container>"); if (cache.hasAttributes()) { //TODO: Attribute conversion required: English verbose name, gpx-id gpx.write("<groundspeak:attributes>"); for (String attribute : cache.getAttributes()) { final CacheAttribute attr = CacheAttribute.getByGcRawName(CacheAttribute.trimAttributeName(attribute)); final boolean enabled = CacheAttribute.isEnabled(attribute); gpx.write("<groundspeak:attribute id=\""); gpx.write(Integer.toString(attr.id)); gpx.write("\" inc=\""); if (enabled) { gpx.write('1'); } else { gpx.write('0'); } gpx.write("\">"); gpx.write(StringEscapeUtils.escapeXml(attr.getL10n(enabled))); gpx.write("</groundspeak:attribute>"); } gpx.write("</groundspeak:attributes>"); } gpx.write("<groundspeak:difficulty>"); gpx.write(Float.toString(cache.getDifficulty())); gpx.write("</groundspeak:difficulty>"); gpx.write("<groundspeak:terrain>"); gpx.write(Float.toString(cache.getTerrain())); gpx.write("</groundspeak:terrain>"); gpx.write("<groundspeak:country>"); gpx.write(StringEscapeUtils.escapeXml(cache.getLocation())); gpx.write("</groundspeak:country>"); gpx.write("<groundspeak:state>"); gpx.write(StringEscapeUtils.escapeXml(cache.getLocation())); gpx.write("</groundspeak:state>"); gpx.write("<groundspeak:short_description html=\""); if (BaseUtils.containsHtml(cache.getShortDescription())) { gpx.write("True"); } else { gpx.write("False"); } gpx.write("\">"); gpx.write(StringEscapeUtils.escapeXml(cache.getShortDescription())); gpx.write("</groundspeak:short_description>"); gpx.write("<groundspeak:long_description html=\""); if (BaseUtils.containsHtml(cache.getDescription())) { gpx.write("True"); } else { gpx.write("False"); } gpx.write("\">"); gpx.write(StringEscapeUtils.escapeXml(cache.getDescription())); gpx.write("</groundspeak:long_description>"); gpx.write("<groundspeak:encoded_hints>"); gpx.write(StringEscapeUtils.escapeXml(cache.getHint())); gpx.write("</groundspeak:encoded_hints>"); gpx.write("</groundspeak:cache>"); if (cache.getLogs().size() > 0) { gpx.write("<groundspeak:logs>"); for (LogEntry log : cache.getLogs()) { gpx.write("<groundspeak:log id=\""); gpx.write(Integer.toString(log.id)); gpx.write("\">"); gpx.write("<groundspeak:date>"); gpx.write(StringEscapeUtils.escapeXml(dateFormatZ.format(new Date(log.date)))); gpx.write("</groundspeak:date>"); gpx.write("<groundspeak:type>"); gpx.write(StringEscapeUtils.escapeXml(log.type.type)); gpx.write("</groundspeak:type>"); gpx.write("<groundspeak:finder id=\"\">"); gpx.write(StringEscapeUtils.escapeXml(log.author)); gpx.write("</groundspeak:finder>"); gpx.write("<groundspeak:text encoded=\"False\">"); gpx.write(StringEscapeUtils.escapeXml(log.log)); gpx.write("</groundspeak:text>"); gpx.write("</groundspeak:log>"); } gpx.write("</groundspeak:logs>"); } gpx.write("</wpt>"); for (cgWaypoint wp : cache.getWaypoints()) { gpx.write("<wpt lat=\""); gpx.write(Double.toString(wp.getCoords().getLatitude())); gpx.write("\" lon=\""); gpx.write(Double.toString(wp.getCoords().getLongitude())); gpx.write("\">"); gpx.write("<name>"); gpx.write(StringEscapeUtils.escapeXml(wp.getPrefix())); gpx.write(StringEscapeUtils.escapeXml(cache.getGeocode().substring(2))); gpx.write("</name>"); gpx.write("<cmt />"); gpx.write("<desc>"); gpx.write(StringEscapeUtils.escapeXml(wp.getNote())); gpx.write("</desc>"); gpx.write("<sym>"); gpx.write(StringEscapeUtils.escapeXml(wp.getWaypointType().toString())); //TODO: Correct identifier string gpx.write("</sym>"); gpx.write("<type>Waypoint|"); gpx.write(StringEscapeUtils.escapeXml(wp.getWaypointType().toString())); //TODO: Correct identifier string gpx.write("</type>"); gpx.write("</wpt>"); } publishProgress(i + 1); } gpx.write("</gpx>"); gpx.close(); } catch (Exception e) { Log.e("GpxExport.ExportTask export", e); if (gpx != null) { try { gpx.close(); } catch (IOException ee) { } } // delete partial gpx file on error if (exportFile.exists()) { exportFile.delete(); } return false; } return true; } @Override protected void onPostExecute(Boolean result) { if (null != activity) { progress.dismiss(); if (result) { ActivityMixin.showToast(activity, getName() + ' ' + getString(R.string.export_exportedto) + ": " + exportFile.toString()); } else { ActivityMixin.showToast(activity, getString(R.string.export_failed)); } } } @Override protected void onProgressUpdate(Integer... status) { if (null != activity) { progress.setProgress(status[0]); } } } }
false
true
protected Boolean doInBackground(Void... params) { // quick check for being able to write the GPX file if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { return false; } Writer gpx = null; try { exportLocation.mkdirs(); final SimpleDateFormat fileNameDateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); exportFile = new File(exportLocation.toString() + File.separatorChar + "export_" + fileNameDateFormat.format(new Date()) + ".gpx"); gpx = new BufferedWriter(new FileWriter(exportFile)); gpx.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); gpx.write("<gpx version=\"1.0\" creator=\"c:geo - http://www.cgeo.org\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://www.topografix.com/GPX/1/0\" xsi:schemaLocation=\"http://www.topografix.com/GPX/1/0 http://www.topografix.com/GPX/1/0/gpx.xsd http://www.topografix.com/GPX/1/0 http://www.topografix.com/GPX/1/0/gpx.xsd http://www.groundspeak.com/cache/1/0/1 http://www.groundspeak.com/cache/1/0/1/cache.xsd\">"); for (int i = 0; i < caches.size(); i++) { // reload the cache. otherwise logs, attributes and other detailed information is not available final cgCache cache = cgeoapplication.getInstance().loadCache(caches.get(i).getGeocode(), LoadFlags.LOAD_ALL_DB_ONLY); gpx.write("<wpt "); gpx.write("lat=\""); gpx.write(Double.toString(cache.getCoords().getLatitude())); gpx.write("\" "); gpx.write("lon=\""); gpx.write(Double.toString(cache.getCoords().getLongitude())); gpx.write("\">"); gpx.write("<time>"); gpx.write(StringEscapeUtils.escapeXml(dateFormatZ.format(cache.getHiddenDate()))); gpx.write("</time>"); gpx.write("<name>"); gpx.write(StringEscapeUtils.escapeXml(cache.getGeocode())); gpx.write("</name>"); gpx.write("<desc>"); gpx.write(StringEscapeUtils.escapeXml(cache.getName())); gpx.write("</desc>"); gpx.write("<sym>"); gpx.write(cache.isFound() ? "Geocache Found" : "Geocache"); gpx.write("</sym>"); gpx.write("<type>"); gpx.write(StringEscapeUtils.escapeXml("Geocache|" + cache.getType().id)); gpx.write("</type>"); gpx.write("<groundspeak:cache "); gpx.write("available=\""); gpx.write(!cache.isDisabled() ? "True" : "False"); gpx.write("\" archived=\""); gpx.write(cache.isArchived() ? "True" : "False"); gpx.write("\" "); gpx.write("xmlns:groundspeak=\"http://www.groundspeak.com/cache/1/0/1\">"); gpx.write("<groundspeak:name>"); gpx.write(StringEscapeUtils.escapeXml(cache.getName())); gpx.write("</groundspeak:name>"); gpx.write("<groundspeak:placed_by>"); gpx.write(StringEscapeUtils.escapeXml(cache.getOwner())); gpx.write("</groundspeak:placed_by>"); gpx.write("<groundspeak:owner>"); gpx.write(StringEscapeUtils.escapeXml(cache.getOwnerReal())); gpx.write("</groundspeak:owner>"); gpx.write("<groundspeak:type>"); gpx.write(StringEscapeUtils.escapeXml(cache.getType().id)); gpx.write("</groundspeak:type>"); gpx.write("<groundspeak:container>"); gpx.write(StringEscapeUtils.escapeXml(cache.getSize().id)); gpx.write("</groundspeak:container>"); if (cache.hasAttributes()) { //TODO: Attribute conversion required: English verbose name, gpx-id gpx.write("<groundspeak:attributes>"); for (String attribute : cache.getAttributes()) { final CacheAttribute attr = CacheAttribute.getByGcRawName(CacheAttribute.trimAttributeName(attribute)); final boolean enabled = CacheAttribute.isEnabled(attribute); gpx.write("<groundspeak:attribute id=\""); gpx.write(Integer.toString(attr.id)); gpx.write("\" inc=\""); if (enabled) { gpx.write('1'); } else { gpx.write('0'); } gpx.write("\">"); gpx.write(StringEscapeUtils.escapeXml(attr.getL10n(enabled))); gpx.write("</groundspeak:attribute>"); } gpx.write("</groundspeak:attributes>"); } gpx.write("<groundspeak:difficulty>"); gpx.write(Float.toString(cache.getDifficulty())); gpx.write("</groundspeak:difficulty>"); gpx.write("<groundspeak:terrain>"); gpx.write(Float.toString(cache.getTerrain())); gpx.write("</groundspeak:terrain>"); gpx.write("<groundspeak:country>"); gpx.write(StringEscapeUtils.escapeXml(cache.getLocation())); gpx.write("</groundspeak:country>"); gpx.write("<groundspeak:state>"); gpx.write(StringEscapeUtils.escapeXml(cache.getLocation())); gpx.write("</groundspeak:state>"); gpx.write("<groundspeak:short_description html=\""); if (BaseUtils.containsHtml(cache.getShortDescription())) { gpx.write("True"); } else { gpx.write("False"); } gpx.write("\">"); gpx.write(StringEscapeUtils.escapeXml(cache.getShortDescription())); gpx.write("</groundspeak:short_description>"); gpx.write("<groundspeak:long_description html=\""); if (BaseUtils.containsHtml(cache.getDescription())) { gpx.write("True"); } else { gpx.write("False"); } gpx.write("\">"); gpx.write(StringEscapeUtils.escapeXml(cache.getDescription())); gpx.write("</groundspeak:long_description>"); gpx.write("<groundspeak:encoded_hints>"); gpx.write(StringEscapeUtils.escapeXml(cache.getHint())); gpx.write("</groundspeak:encoded_hints>"); gpx.write("</groundspeak:cache>"); if (cache.getLogs().size() > 0) { gpx.write("<groundspeak:logs>"); for (LogEntry log : cache.getLogs()) { gpx.write("<groundspeak:log id=\""); gpx.write(Integer.toString(log.id)); gpx.write("\">"); gpx.write("<groundspeak:date>"); gpx.write(StringEscapeUtils.escapeXml(dateFormatZ.format(new Date(log.date)))); gpx.write("</groundspeak:date>"); gpx.write("<groundspeak:type>"); gpx.write(StringEscapeUtils.escapeXml(log.type.type)); gpx.write("</groundspeak:type>"); gpx.write("<groundspeak:finder id=\"\">"); gpx.write(StringEscapeUtils.escapeXml(log.author)); gpx.write("</groundspeak:finder>"); gpx.write("<groundspeak:text encoded=\"False\">"); gpx.write(StringEscapeUtils.escapeXml(log.log)); gpx.write("</groundspeak:text>"); gpx.write("</groundspeak:log>"); } gpx.write("</groundspeak:logs>"); } gpx.write("</wpt>"); for (cgWaypoint wp : cache.getWaypoints()) { gpx.write("<wpt lat=\""); gpx.write(Double.toString(wp.getCoords().getLatitude())); gpx.write("\" lon=\""); gpx.write(Double.toString(wp.getCoords().getLongitude())); gpx.write("\">"); gpx.write("<name>"); gpx.write(StringEscapeUtils.escapeXml(wp.getPrefix())); gpx.write(StringEscapeUtils.escapeXml(cache.getGeocode().substring(2))); gpx.write("</name>"); gpx.write("<cmt />"); gpx.write("<desc>"); gpx.write(StringEscapeUtils.escapeXml(wp.getNote())); gpx.write("</desc>"); gpx.write("<sym>"); gpx.write(StringEscapeUtils.escapeXml(wp.getWaypointType().toString())); //TODO: Correct identifier string gpx.write("</sym>"); gpx.write("<type>Waypoint|"); gpx.write(StringEscapeUtils.escapeXml(wp.getWaypointType().toString())); //TODO: Correct identifier string gpx.write("</type>"); gpx.write("</wpt>"); } publishProgress(i + 1); } gpx.write("</gpx>"); gpx.close(); } catch (Exception e) { Log.e("GpxExport.ExportTask export", e); if (gpx != null) { try { gpx.close(); } catch (IOException ee) { } } // delete partial gpx file on error if (exportFile.exists()) { exportFile.delete(); } return false; } return true; }
protected Boolean doInBackground(Void... params) { // quick check for being able to write the GPX file if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { return false; } Writer gpx = null; try { exportLocation.mkdirs(); final SimpleDateFormat fileNameDateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); exportFile = new File(exportLocation.toString() + File.separatorChar + "export_" + fileNameDateFormat.format(new Date()) + ".gpx"); gpx = new BufferedWriter(new FileWriter(exportFile)); gpx.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); gpx.write("<gpx version=\"1.0\" creator=\"c:geo - http://www.cgeo.org\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://www.topografix.com/GPX/1/0\" xsi:schemaLocation=\"http://www.topografix.com/GPX/1/0 http://www.topografix.com/GPX/1/0/gpx.xsd http://www.topografix.com/GPX/1/0 http://www.topografix.com/GPX/1/0/gpx.xsd http://www.groundspeak.com/cache/1/0/1 http://www.groundspeak.com/cache/1/0/1/cache.xsd\">"); for (int i = 0; i < caches.size(); i++) { // reload the cache. otherwise logs, attributes and other detailed information is not available final cgCache cache = cgeoapplication.getInstance().loadCache(caches.get(i).getGeocode(), LoadFlags.LOAD_ALL_DB_ONLY); gpx.write("<wpt "); gpx.write("lat=\""); gpx.write(Double.toString(cache.getCoords().getLatitude())); gpx.write("\" "); gpx.write("lon=\""); gpx.write(Double.toString(cache.getCoords().getLongitude())); gpx.write("\">"); gpx.write("<time>"); gpx.write(StringEscapeUtils.escapeXml(dateFormatZ.format(cache.getHiddenDate()))); gpx.write("</time>"); gpx.write("<name>"); gpx.write(StringEscapeUtils.escapeXml(cache.getGeocode())); gpx.write("</name>"); gpx.write("<desc>"); gpx.write(StringEscapeUtils.escapeXml(cache.getName())); gpx.write("</desc>"); gpx.write("<sym>"); gpx.write(cache.isFound() ? "Geocache Found" : "Geocache"); gpx.write("</sym>"); gpx.write("<type>"); gpx.write(StringEscapeUtils.escapeXml("Geocache|" + cache.getType().pattern)); gpx.write("</type>"); gpx.write("<groundspeak:cache "); gpx.write("available=\""); gpx.write(!cache.isDisabled() ? "True" : "False"); gpx.write("\" archived=\""); gpx.write(cache.isArchived() ? "True" : "False"); gpx.write("\" "); gpx.write("xmlns:groundspeak=\"http://www.groundspeak.com/cache/1/0/1\">"); gpx.write("<groundspeak:name>"); gpx.write(StringEscapeUtils.escapeXml(cache.getName())); gpx.write("</groundspeak:name>"); gpx.write("<groundspeak:placed_by>"); gpx.write(StringEscapeUtils.escapeXml(cache.getOwner())); gpx.write("</groundspeak:placed_by>"); gpx.write("<groundspeak:owner>"); gpx.write(StringEscapeUtils.escapeXml(cache.getOwnerReal())); gpx.write("</groundspeak:owner>"); gpx.write("<groundspeak:type>"); gpx.write(StringEscapeUtils.escapeXml(cache.getType().pattern)); gpx.write("</groundspeak:type>"); gpx.write("<groundspeak:container>"); gpx.write(StringEscapeUtils.escapeXml(cache.getSize().id)); gpx.write("</groundspeak:container>"); if (cache.hasAttributes()) { //TODO: Attribute conversion required: English verbose name, gpx-id gpx.write("<groundspeak:attributes>"); for (String attribute : cache.getAttributes()) { final CacheAttribute attr = CacheAttribute.getByGcRawName(CacheAttribute.trimAttributeName(attribute)); final boolean enabled = CacheAttribute.isEnabled(attribute); gpx.write("<groundspeak:attribute id=\""); gpx.write(Integer.toString(attr.id)); gpx.write("\" inc=\""); if (enabled) { gpx.write('1'); } else { gpx.write('0'); } gpx.write("\">"); gpx.write(StringEscapeUtils.escapeXml(attr.getL10n(enabled))); gpx.write("</groundspeak:attribute>"); } gpx.write("</groundspeak:attributes>"); } gpx.write("<groundspeak:difficulty>"); gpx.write(Float.toString(cache.getDifficulty())); gpx.write("</groundspeak:difficulty>"); gpx.write("<groundspeak:terrain>"); gpx.write(Float.toString(cache.getTerrain())); gpx.write("</groundspeak:terrain>"); gpx.write("<groundspeak:country>"); gpx.write(StringEscapeUtils.escapeXml(cache.getLocation())); gpx.write("</groundspeak:country>"); gpx.write("<groundspeak:state>"); gpx.write(StringEscapeUtils.escapeXml(cache.getLocation())); gpx.write("</groundspeak:state>"); gpx.write("<groundspeak:short_description html=\""); if (BaseUtils.containsHtml(cache.getShortDescription())) { gpx.write("True"); } else { gpx.write("False"); } gpx.write("\">"); gpx.write(StringEscapeUtils.escapeXml(cache.getShortDescription())); gpx.write("</groundspeak:short_description>"); gpx.write("<groundspeak:long_description html=\""); if (BaseUtils.containsHtml(cache.getDescription())) { gpx.write("True"); } else { gpx.write("False"); } gpx.write("\">"); gpx.write(StringEscapeUtils.escapeXml(cache.getDescription())); gpx.write("</groundspeak:long_description>"); gpx.write("<groundspeak:encoded_hints>"); gpx.write(StringEscapeUtils.escapeXml(cache.getHint())); gpx.write("</groundspeak:encoded_hints>"); gpx.write("</groundspeak:cache>"); if (cache.getLogs().size() > 0) { gpx.write("<groundspeak:logs>"); for (LogEntry log : cache.getLogs()) { gpx.write("<groundspeak:log id=\""); gpx.write(Integer.toString(log.id)); gpx.write("\">"); gpx.write("<groundspeak:date>"); gpx.write(StringEscapeUtils.escapeXml(dateFormatZ.format(new Date(log.date)))); gpx.write("</groundspeak:date>"); gpx.write("<groundspeak:type>"); gpx.write(StringEscapeUtils.escapeXml(log.type.type)); gpx.write("</groundspeak:type>"); gpx.write("<groundspeak:finder id=\"\">"); gpx.write(StringEscapeUtils.escapeXml(log.author)); gpx.write("</groundspeak:finder>"); gpx.write("<groundspeak:text encoded=\"False\">"); gpx.write(StringEscapeUtils.escapeXml(log.log)); gpx.write("</groundspeak:text>"); gpx.write("</groundspeak:log>"); } gpx.write("</groundspeak:logs>"); } gpx.write("</wpt>"); for (cgWaypoint wp : cache.getWaypoints()) { gpx.write("<wpt lat=\""); gpx.write(Double.toString(wp.getCoords().getLatitude())); gpx.write("\" lon=\""); gpx.write(Double.toString(wp.getCoords().getLongitude())); gpx.write("\">"); gpx.write("<name>"); gpx.write(StringEscapeUtils.escapeXml(wp.getPrefix())); gpx.write(StringEscapeUtils.escapeXml(cache.getGeocode().substring(2))); gpx.write("</name>"); gpx.write("<cmt />"); gpx.write("<desc>"); gpx.write(StringEscapeUtils.escapeXml(wp.getNote())); gpx.write("</desc>"); gpx.write("<sym>"); gpx.write(StringEscapeUtils.escapeXml(wp.getWaypointType().toString())); //TODO: Correct identifier string gpx.write("</sym>"); gpx.write("<type>Waypoint|"); gpx.write(StringEscapeUtils.escapeXml(wp.getWaypointType().toString())); //TODO: Correct identifier string gpx.write("</type>"); gpx.write("</wpt>"); } publishProgress(i + 1); } gpx.write("</gpx>"); gpx.close(); } catch (Exception e) { Log.e("GpxExport.ExportTask export", e); if (gpx != null) { try { gpx.close(); } catch (IOException ee) { } } // delete partial gpx file on error if (exportFile.exists()) { exportFile.delete(); } return false; } return true; }
diff --git a/expleo/app/models/Template.java b/expleo/app/models/Template.java index c94d73c..6cf1c6d 100644 --- a/expleo/app/models/Template.java +++ b/expleo/app/models/Template.java @@ -1,161 +1,161 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package models; import java.io.File; import play.db.jpa.*; import play.data.validation.*; import java.util.*; import javax.persistence.*; import utils.io.FileStringReader; @Entity public class Template extends Model { public String name_; public String filename_; public String author_; public Date dateCreated_; public String description_; public int counterDownloads_; public HashMap templates_ = new HashMap<String, String>(); public TextFile textFile; public Template(String name_, String filename_, String author_, Date dateCreated_, String description_, int counterDownloads_) { this.name_ = name_; this.filename_ = filename_; this.author_ = author_; this.dateCreated_ = dateCreated_; this.description_ = description_; this.counterDownloads_ = counterDownloads_; } public void calculateForm() { this.textFile = new TextFile("/home/dave/sw11/Alt_F4/expleo/public/templates/" + filename_); Set<String> commands = new TreeSet<String>(); String[] commands_temp = this.textFile.getText().split("%%"); for (int i = 1; i < commands_temp.length; i += 2) { commands.add(commands_temp[i]); } Iterator iterator = commands.iterator(); while (iterator.hasNext()) { String command = (String) iterator.next(); templates_.put(command, ""); } } public static String upload(String name, String description, File template) { try { FileStringReader reader = new FileStringReader(template); String text = reader.read(); if(!Helper.isUtf8(text)) { - return "File must be in UTF 8."; + return "File must be in Plaintext (UTF 8)."; } Date now = new Date(); Template temp = new Template(name, template.getName(), "DummyAuthor", now, description, 4); temp.save(); int dotPos = template.getName().lastIndexOf("."); String newName; String extension; if (dotPos != -1) { extension = template.getName().substring(dotPos); newName = temp.id + "_" + name + extension; } else { newName = temp.id + "_" + name; } File copy_to = new File("expleo/public/templates/" + newName); System.out.println(copy_to.getAbsolutePath()); Helper.copy(template, copy_to); temp.filename_ = newName; temp.save(); return null; } catch (Exception e) { System.out.println(e.toString()); return e.toString(); } } public static void delete(long id) { Template temp = Template.find("id", id).first(); if (temp != null) { temp.delete(); } } public void addCommand(String command) { templates_.put(command, ""); } public void addSubstitution(String key, String userInput) { templates_.put(key, userInput); } public String getValue(String command) { return templates_.get(command).toString(); } @Override public String toString() { return this.name_; } public HashMap getTemplates_() { return templates_; } public void doMap(Map<String, String[]> map) { Iterator mapIterator = map.keySet().iterator(); while (mapIterator.hasNext()) { String temp = (String) mapIterator.next(); if (this.templates_.containsKey(temp)) { this.addSubstitution(temp, map.get(temp)[0]); } } } }
true
true
public static String upload(String name, String description, File template) { try { FileStringReader reader = new FileStringReader(template); String text = reader.read(); if(!Helper.isUtf8(text)) { return "File must be in UTF 8."; } Date now = new Date(); Template temp = new Template(name, template.getName(), "DummyAuthor", now, description, 4); temp.save(); int dotPos = template.getName().lastIndexOf("."); String newName; String extension; if (dotPos != -1) { extension = template.getName().substring(dotPos); newName = temp.id + "_" + name + extension; } else { newName = temp.id + "_" + name; } File copy_to = new File("expleo/public/templates/" + newName); System.out.println(copy_to.getAbsolutePath()); Helper.copy(template, copy_to); temp.filename_ = newName; temp.save(); return null; } catch (Exception e) { System.out.println(e.toString()); return e.toString(); } }
public static String upload(String name, String description, File template) { try { FileStringReader reader = new FileStringReader(template); String text = reader.read(); if(!Helper.isUtf8(text)) { return "File must be in Plaintext (UTF 8)."; } Date now = new Date(); Template temp = new Template(name, template.getName(), "DummyAuthor", now, description, 4); temp.save(); int dotPos = template.getName().lastIndexOf("."); String newName; String extension; if (dotPos != -1) { extension = template.getName().substring(dotPos); newName = temp.id + "_" + name + extension; } else { newName = temp.id + "_" + name; } File copy_to = new File("expleo/public/templates/" + newName); System.out.println(copy_to.getAbsolutePath()); Helper.copy(template, copy_to); temp.filename_ = newName; temp.save(); return null; } catch (Exception e) { System.out.println(e.toString()); return e.toString(); } }
diff --git a/src/org/ebookdroid/core/DecodeServiceBase.java b/src/org/ebookdroid/core/DecodeServiceBase.java index 3e9b8bfc..4ff193f2 100644 --- a/src/org/ebookdroid/core/DecodeServiceBase.java +++ b/src/org/ebookdroid/core/DecodeServiceBase.java @@ -1,643 +1,645 @@ package org.ebookdroid.core; import org.ebookdroid.core.bitmaps.BitmapManager; import org.ebookdroid.core.bitmaps.BitmapRef; import org.ebookdroid.core.codec.CodecContext; import org.ebookdroid.core.codec.CodecDocument; import org.ebookdroid.core.codec.CodecPage; import org.ebookdroid.core.codec.CodecPageInfo; import org.ebookdroid.core.log.EmergencyHandler; import org.ebookdroid.core.log.LogContext; import org.ebookdroid.core.settings.SettingsManager; import android.graphics.Bitmap; import android.graphics.Bitmap.Config; import android.graphics.PixelFormat; import android.graphics.Rect; import android.graphics.RectF; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.lang.ref.SoftReference; import java.util.ArrayList; import java.util.Comparator; import java.util.IdentityHashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.locks.ReentrantLock; public class DecodeServiceBase implements DecodeService { public static final LogContext LCTX = LogContext.ROOT.lctx("Decoding"); static final AtomicLong TASK_ID_SEQ = new AtomicLong(); final CodecContext codecContext; final Executor executor = new Executor(); final AtomicBoolean isRecycled = new AtomicBoolean(); final AtomicReference<ViewState> viewState = new AtomicReference<ViewState>(); final AtomicLong memoryLimit = new AtomicLong(Long.MAX_VALUE); CodecDocument document; final Map<Integer, SoftReference<CodecPage>> pages = new LinkedHashMap<Integer, SoftReference<CodecPage>>() { private static final long serialVersionUID = -8845124816503128098L; @Override protected boolean removeEldestEntry(final Map.Entry<Integer, SoftReference<CodecPage>> eldest) { if (this.size() > getCacheSize()) { final SoftReference<CodecPage> value = eldest != null ? eldest.getValue() : null; final CodecPage codecPage = value != null ? value.get() : null; if (codecPage == null || codecPage.isRecycled()) { if (LCTX.isDebugEnabled()) { LCTX.d("Remove auto-recycled codec page reference: " + eldest.getKey()); } } else { if (LCTX.isDebugEnabled()) { LCTX.d("Recycle and remove old codec page: " + eldest.getKey()); } codecPage.recycle(); } return true; } return false; } }; public DecodeServiceBase(final CodecContext codecContext) { this.codecContext = codecContext; } @Override public int getPixelFormat() { final Config cfg = getBitmapConfig(); switch (cfg) { case ALPHA_8: return PixelFormat.A_8; case ARGB_4444: return PixelFormat.RGBA_4444; case RGB_565: return PixelFormat.RGB_565; case ARGB_8888: return PixelFormat.RGBA_8888; default: return PixelFormat.RGB_565; } } @Override public Config getBitmapConfig() { return this.codecContext.getBitmapConfig(); } @Override public long getMemoryLimit() { return memoryLimit.get(); } @Override public void decreaseMemortLimit() { memoryLimit.decrementAndGet(); } @Override public void open(final String fileName, final String password) { document = codecContext.openDocument(fileName, password); } @Override public CodecPageInfo getPageInfo(final int pageIndex) { return document.getPageInfo(pageIndex); } @Override public void updateViewState(final ViewState viewState) { this.viewState.set(viewState); } @Override public void decodePage(final ViewState viewState, final PageTreeNode node, final RectF nodeBounds) { final DecodeTask decodeTask = new DecodeTask(viewState, node, nodeBounds, node.getSliceGeneration()); updateViewState(viewState); if (isRecycled.get()) { if (LCTX.isDebugEnabled()) { LCTX.d("Decoding not allowed on recycling"); } return; } executor.add(decodeTask); } @Override public void stopDecoding(final PageTreeNode node, final String reason) { executor.stopDecoding(null, node, reason); } void performDecode(final DecodeTask task) { if (executor.isTaskDead(task)) { if (LCTX.isDebugEnabled()) { LCTX.d("Task " + task.id + ": Skipping dead decode task for " + task.node); } return; } if (LCTX.isDebugEnabled()) { LCTX.d("Task " + task.id + ": Starting decoding for " + task.node); } CodecPage vuPage = null; Rect r = null; try { vuPage = getPage(task.pageNumber); if (executor.isTaskDead(task)) { if (LCTX.isDebugEnabled()) { LCTX.d("Task " + task.id + ": Abort dead decode task for " + task.node); } return; } r = getScaledSize(task, vuPage); - LCTX.d("Task " + task.id + ": Rendering rect: " + r); + if (LCTX.isDebugEnabled()) { + LCTX.d("Task " + task.id + ": Rendering rect: " + r); + } final BitmapRef bitmap = vuPage.renderBitmap(r.width(), r.height(), task.pageSliceBounds); if (executor.isTaskDead(task)) { if (LCTX.isDebugEnabled()) { LCTX.d("Task " + task.id + ": Abort dead decode task for " + task.node); } BitmapManager.release(bitmap); return; } finishDecoding(task, vuPage, bitmap, r); } catch (final OutOfMemoryError ex) { if (r != null) { final int limit = BitmapManager.getBitmapBufferSize(r.width(), r.height(), codecContext.getBitmapConfig()); memoryLimit.set(Math.min(memoryLimit.get(), limit)); LCTX.e("Task " + task.id + ": No memory to decode " + task.node + ": new memory limit: " + memoryLimit.get()); } else { LCTX.e("Task " + task.id + ": No memory to decode " + task.node); } for (int i = 0; i <= SettingsManager.getAppSettings().getPagesInMemory(); i++) { pages.put(Integer.MAX_VALUE - i, null); } pages.clear(); vuPage.recycle(); BitmapManager.clear("DecodeService OutOfMemoryError: "); abortDecoding(task, null, null); } catch (final Throwable th) { LCTX.e("Task " + task.id + ": Decoding failed for " + task.node + ": " + th.getMessage(), th); abortDecoding(task, vuPage, null); } } Rect getScaledSize(final DecodeTask task, final CodecPage vuPage) { final int pageWidth = vuPage.getWidth(); final int pageHeight = vuPage.getHeight(); final RectF nodeBounds = task.pageSliceBounds; if (task.viewState.decodeMode == DecodeMode.NATIVE_RESOLUTION) { return getNativeSize(pageWidth, pageHeight, nodeBounds, task.node.page.getTargetRectScale()); } return getScaledSize(task.viewState, pageWidth, pageHeight, nodeBounds, task.node.page.getTargetRectScale(), task.sliceGeneration); } @Override public Rect getNativeSize(final float pageWidth, final float pageHeight, final RectF nodeBounds, final float pageTypeWidthScale) { final int scaledWidth = Math.round((pageWidth * pageTypeWidthScale) * nodeBounds.width()); final int scaledHeight = Math.round((pageHeight * pageTypeWidthScale) * nodeBounds.height()); return new Rect(0, 0, scaledWidth, scaledHeight); } @Override public Rect getScaledSize(final ViewState viewState, final float pageWidth, final float pageHeight, final RectF nodeBounds, final float pageTypeWidthScale, final int sliceGeneration) { final float viewWidth = viewState.realRect.width(); final float viewHeight = viewState.realRect.height(); final float nodeWidth = pageWidth * nodeBounds.width(); final float nodeHeight = pageHeight * nodeBounds.height(); final int scaledWidth; final int scaledHeight; // && PageAlign effectiveAlign = viewState.pageAlign; if (effectiveAlign == PageAlign.AUTO) { final float viewAspect = viewWidth / viewHeight; final float nodeAspect = nodeWidth / nodeHeight; effectiveAlign = nodeAspect < viewAspect ? PageAlign.HEIGHT : PageAlign.WIDTH; } if (effectiveAlign == PageAlign.WIDTH) { final float scale = 1.0f * (viewWidth / pageWidth) * viewState.zoom / sliceGeneration; scaledWidth = Math.round((scale * pageWidth)); scaledHeight = Math.round((scale * nodeHeight) / nodeBounds.width()); } else { final float scale = 1.0f * (viewHeight / pageHeight) * viewState.zoom / sliceGeneration; scaledHeight = Math.round((scale * pageHeight)); scaledWidth = Math.round((scale * nodeWidth) / nodeBounds.height()); } return new Rect(0, 0, scaledWidth, scaledHeight); } void finishDecoding(final DecodeTask currentDecodeTask, final CodecPage page, final BitmapRef bitmap, final Rect bitmapBounds) { stopDecoding(currentDecodeTask.node, "complete"); updateImage(currentDecodeTask, page, bitmap, bitmapBounds); } void abortDecoding(final DecodeTask currentDecodeTask, final CodecPage page, final BitmapRef bitmap) { stopDecoding(currentDecodeTask.node, "failed"); updateImage(currentDecodeTask, page, bitmap, null); } CodecPage getPage(final int pageIndex) { if (LCTX.isDebugEnabled()) { LCTX.d("Codec pages in cache: " + pages.size()); } for (final Iterator<Map.Entry<Integer, SoftReference<CodecPage>>> i = pages.entrySet().iterator(); i.hasNext();) { final Map.Entry<Integer, SoftReference<CodecPage>> entry = i.next(); final int index = entry.getKey(); final SoftReference<CodecPage> ref = entry.getValue(); final CodecPage page = ref != null ? ref.get() : null; if (page == null || page.isRecycled()) { if (LCTX.isDebugEnabled()) { LCTX.d("Remove auto-recycled codec page reference: " + index); } i.remove(); } } final SoftReference<CodecPage> ref = pages.get(pageIndex); CodecPage page = ref != null ? ref.get() : null; if (page == null || page.isRecycled()) { // Cause native recycling last used page if page cache is full now // before opening new native page pages.put(pageIndex, null); page = document.getPage(pageIndex); } pages.put(pageIndex, new SoftReference<CodecPage>(page)); return page; } void updateImage(final DecodeTask currentDecodeTask, final CodecPage page, final BitmapRef bitmap, final Rect bitmapBounds) { currentDecodeTask.node.decodeComplete(page, bitmap, bitmapBounds); } @Override public int getPageCount() { return document.getPageCount(); } @Override public List<OutlineLink> getOutline() { return document.getOutline(); } @Override public void recycle() { if (isRecycled.compareAndSet(false, true)) { executor.recycle(); } } protected int getCacheSize() { final ViewState vs = viewState.get(); int minSize = 3; if (vs != null) { minSize = vs.lastVisible - vs.firstVisible + 1; } return Math.max(minSize, SettingsManager.getAppSettings().getPagesInMemory() + 1); } class Executor implements Runnable { final Map<PageTreeNode, DecodeTask> decodingTasks = new IdentityHashMap<PageTreeNode, DecodeTask>(); final ArrayList<Runnable> queue; final Thread thread; final ReentrantLock lock = new ReentrantLock(); final AtomicBoolean run = new AtomicBoolean(true); Executor() { queue = new ArrayList<Runnable>(); thread = new Thread(this); thread.setPriority(Thread.MIN_PRIORITY); thread.start(); } @Override public void run() { try { while (run.get()) { final Runnable r = nextTask(); if (r != null) { r.run(); } } } catch (final Throwable th) { LCTX.e("Decoding service executor failed: " + th.getMessage(), th); EmergencyHandler.onUnexpectedError(th); } } Runnable nextTask() { lock.lock(); try { if (!queue.isEmpty()) { final TaskComparator comp = new TaskComparator(viewState.get()); Runnable candidate = null; int cindex = 0; int index = 0; while (index < queue.size() && candidate == null) { candidate = queue.get(index); cindex = index; index++; } if (candidate == null) { queue.clear(); } else { while (index < queue.size()) { final Runnable next = queue.get(index); if (next != null && comp.compare(next, candidate) < 0) { candidate = next; cindex = index; } index++; } queue.set(cindex, null); } return candidate; } } finally { lock.unlock(); } synchronized (run) { try { run.wait(1000); } catch (final InterruptedException ex) { Thread.interrupted(); } } return null; } public void add(final DecodeTask task) { if (LCTX.isDebugEnabled()) { LCTX.d("Adding decoding task: " + task + " for " + task.node); } lock.lock(); try { final DecodeTask running = decodingTasks.get(task.node); if (running != null && running.equals(task) && !isTaskDead(running)) { if (LCTX.isDebugEnabled()) { LCTX.d("The similar task is running: " + running.id + " for " + task.node); } return; } else if (running != null) { if (LCTX.isDebugEnabled()) { LCTX.d("The another task is running: " + running.id + " for " + task.node); } } decodingTasks.put(task.node, task); boolean added = false; for (int index = 0; index < queue.size() && !added; index++) { if (null == queue.get(index)) { queue.set(index, task); added = true; } } if (!added) { queue.add(task); } synchronized (run) { run.notifyAll(); } if (running != null) { stopDecoding(running, null, "canceled by new one"); } } finally { lock.unlock(); } } public void stopDecoding(final DecodeTask task, final PageTreeNode node, final String reason) { lock.lock(); try { final DecodeTask removed = task == null ? decodingTasks.remove(node) : task; if (removed != null) { removed.cancelled.set(true); queue.remove(removed); if (LCTX.isDebugEnabled()) { LCTX.d("Task " + removed.id + ": Stop decoding task with reason: " + reason + " for " + removed.node); } } } finally { lock.unlock(); } } public boolean isTaskDead(final DecodeTask task) { return task.cancelled.get(); } public void recycle() { lock.lock(); try { for (final DecodeTask task : decodingTasks.values()) { stopDecoding(task, null, "recycling"); } queue.add(new Runnable() { @Override public void run() { for (final SoftReference<CodecPage> ref : pages.values()) { final CodecPage page = ref != null ? ref.get() : null; if (page != null) { page.recycle(); } } pages.clear(); if (document != null) { document.recycle(); } codecContext.recycle(); run.set(false); } }); synchronized (run) { run.notifyAll(); } } finally { lock.unlock(); } } } class TaskComparator implements Comparator<Runnable> { final PageTreeNodeComparator cmp; public TaskComparator(final ViewState viewState) { cmp = viewState != null ? new PageTreeNodeComparator(viewState) : null; } @Override public int compare(final Runnable r1, final Runnable r2) { final boolean isTask1 = r1 instanceof DecodeTask; final boolean isTask2 = r2 instanceof DecodeTask; if (isTask1 != isTask2) { return isTask1 ? -1 : 1; } if (!isTask1) { return 0; } final DecodeTask t1 = (DecodeTask) r1; final DecodeTask t2 = (DecodeTask) r2; if (cmp != null) { return cmp.compare(t1.node, t2.node); } return 0; } } class DecodeTask implements Runnable { final long id = TASK_ID_SEQ.incrementAndGet(); final AtomicBoolean cancelled = new AtomicBoolean(); final PageTreeNode node; final ViewState viewState; final int pageNumber; final RectF pageSliceBounds; final int sliceGeneration; DecodeTask(final ViewState viewState, final PageTreeNode node, final RectF nodeBounds, final int sliceGeneration) { this.pageNumber = node.getDocumentPageIndex(); this.viewState = viewState; this.node = node; this.pageSliceBounds = nodeBounds; this.sliceGeneration = sliceGeneration; } @Override public void run() { BitmapManager.release(); performDecode(this); } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj instanceof DecodeTask) { final DecodeTask that = (DecodeTask) obj; return this.pageNumber == that.pageNumber && this.pageSliceBounds.equals(that.pageSliceBounds) && this.viewState.realRect.width() == that.viewState.realRect.width() && this.viewState.zoom == that.viewState.zoom; } return false; } @Override public String toString() { final StringBuilder buf = new StringBuilder("DecodeTask"); buf.append("["); buf.append("id").append("=").append(id); buf.append(", "); buf.append("target").append("=").append(node); buf.append(", "); buf.append("width").append("=").append((int) viewState.realRect.width()); buf.append(", "); buf.append("zoom").append("=").append(viewState.zoom); buf.append(", "); buf.append("bounds").append("=").append(pageSliceBounds); buf.append("]"); return buf.toString(); } } @Override public void createThumbnail(final File thumbnailFile, int width, int height, final int pageNo, final RectF region) { Bitmap thumbnail = document.getEmbeddedThumbnail(); BitmapRef bmp = null; if (thumbnail != null) { width = 200; height = 200; if (thumbnail.getHeight() > thumbnail.getWidth()) { width = 200 * thumbnail.getWidth() / thumbnail.getHeight(); } else { height = 200 * thumbnail.getHeight() / thumbnail.getWidth(); } thumbnail = Bitmap.createScaledBitmap(thumbnail, width, height, true); } else { final CodecPage page = getPage(pageNo); bmp = page.renderBitmap(width, height, region); thumbnail = bmp.getBitmap(); } FileOutputStream out; try { out = new FileOutputStream(thumbnailFile); thumbnail.compress(Bitmap.CompressFormat.JPEG, 50, out); out.close(); } catch (final FileNotFoundException e) { } catch (final IOException e) { } finally { BitmapManager.release(bmp); } } @Override public boolean isPageSizeCacheable() { return codecContext.isPageSizeCacheable(); } }
true
true
void performDecode(final DecodeTask task) { if (executor.isTaskDead(task)) { if (LCTX.isDebugEnabled()) { LCTX.d("Task " + task.id + ": Skipping dead decode task for " + task.node); } return; } if (LCTX.isDebugEnabled()) { LCTX.d("Task " + task.id + ": Starting decoding for " + task.node); } CodecPage vuPage = null; Rect r = null; try { vuPage = getPage(task.pageNumber); if (executor.isTaskDead(task)) { if (LCTX.isDebugEnabled()) { LCTX.d("Task " + task.id + ": Abort dead decode task for " + task.node); } return; } r = getScaledSize(task, vuPage); LCTX.d("Task " + task.id + ": Rendering rect: " + r); final BitmapRef bitmap = vuPage.renderBitmap(r.width(), r.height(), task.pageSliceBounds); if (executor.isTaskDead(task)) { if (LCTX.isDebugEnabled()) { LCTX.d("Task " + task.id + ": Abort dead decode task for " + task.node); } BitmapManager.release(bitmap); return; } finishDecoding(task, vuPage, bitmap, r); } catch (final OutOfMemoryError ex) { if (r != null) { final int limit = BitmapManager.getBitmapBufferSize(r.width(), r.height(), codecContext.getBitmapConfig()); memoryLimit.set(Math.min(memoryLimit.get(), limit)); LCTX.e("Task " + task.id + ": No memory to decode " + task.node + ": new memory limit: " + memoryLimit.get()); } else { LCTX.e("Task " + task.id + ": No memory to decode " + task.node); } for (int i = 0; i <= SettingsManager.getAppSettings().getPagesInMemory(); i++) { pages.put(Integer.MAX_VALUE - i, null); } pages.clear(); vuPage.recycle(); BitmapManager.clear("DecodeService OutOfMemoryError: "); abortDecoding(task, null, null); } catch (final Throwable th) { LCTX.e("Task " + task.id + ": Decoding failed for " + task.node + ": " + th.getMessage(), th); abortDecoding(task, vuPage, null); } }
void performDecode(final DecodeTask task) { if (executor.isTaskDead(task)) { if (LCTX.isDebugEnabled()) { LCTX.d("Task " + task.id + ": Skipping dead decode task for " + task.node); } return; } if (LCTX.isDebugEnabled()) { LCTX.d("Task " + task.id + ": Starting decoding for " + task.node); } CodecPage vuPage = null; Rect r = null; try { vuPage = getPage(task.pageNumber); if (executor.isTaskDead(task)) { if (LCTX.isDebugEnabled()) { LCTX.d("Task " + task.id + ": Abort dead decode task for " + task.node); } return; } r = getScaledSize(task, vuPage); if (LCTX.isDebugEnabled()) { LCTX.d("Task " + task.id + ": Rendering rect: " + r); } final BitmapRef bitmap = vuPage.renderBitmap(r.width(), r.height(), task.pageSliceBounds); if (executor.isTaskDead(task)) { if (LCTX.isDebugEnabled()) { LCTX.d("Task " + task.id + ": Abort dead decode task for " + task.node); } BitmapManager.release(bitmap); return; } finishDecoding(task, vuPage, bitmap, r); } catch (final OutOfMemoryError ex) { if (r != null) { final int limit = BitmapManager.getBitmapBufferSize(r.width(), r.height(), codecContext.getBitmapConfig()); memoryLimit.set(Math.min(memoryLimit.get(), limit)); LCTX.e("Task " + task.id + ": No memory to decode " + task.node + ": new memory limit: " + memoryLimit.get()); } else { LCTX.e("Task " + task.id + ": No memory to decode " + task.node); } for (int i = 0; i <= SettingsManager.getAppSettings().getPagesInMemory(); i++) { pages.put(Integer.MAX_VALUE - i, null); } pages.clear(); vuPage.recycle(); BitmapManager.clear("DecodeService OutOfMemoryError: "); abortDecoding(task, null, null); } catch (final Throwable th) { LCTX.e("Task " + task.id + ": Decoding failed for " + task.node + ": " + th.getMessage(), th); abortDecoding(task, vuPage, null); } }
diff --git a/src/com/qiniu/utils/MultipartEntity.java b/src/com/qiniu/utils/MultipartEntity.java index 0765262..bf2e06a 100644 --- a/src/com/qiniu/utils/MultipartEntity.java +++ b/src/com/qiniu/utils/MultipartEntity.java @@ -1,120 +1,120 @@ package com.qiniu.utils; import org.apache.http.entity.AbstractHttpEntity; import org.apache.http.message.BasicHeader; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Random; public class MultipartEntity extends AbstractHttpEntity { private String mBoundary; private StringBuffer mData = new StringBuffer(); private ArrayList<FileInfo> mFiles = new ArrayList<FileInfo>(); public MultipartEntity() { mBoundary = getRandomString(32); contentType = new BasicHeader("Content-Type", "multipart/form-data; boundary=" + mBoundary); } public void addField(String key, String value) { String tmp = "--%s\r\nContent-Disposition: form-data; name=\"%s\"\r\n\r\n%s\r\n"; mData.append(String.format(tmp, mBoundary, key, value)); } public void addFile(String field, String contentType, String fileName, InputStreamAt isa) { mFiles.add(new FileInfo(field, contentType, fileName, isa)); } @Override public boolean isRepeatable() { return false; } @Override public long getContentLength() { long len = mData.length(); for (FileInfo fi: mFiles) { len += fi.length(); } len += 6 + mBoundary.length(); return len; } @Override public InputStream getContent() throws IOException, IllegalStateException { return null; } @Override public void writeTo(OutputStream outputStream) throws IOException { outputStream.write(mData.toString().getBytes()); outputStream.flush(); for (FileInfo i: mFiles) { i.writeTo(outputStream); } outputStream.write(("--" + mBoundary + "--\r\n").getBytes()); outputStream.flush(); outputStream.close(); } @Override public boolean isStreaming() { return false; } private String fileTpl = "--%s\r\nContent-Disposition: form-data;name=\"%s\";filename=\"%s\"\r\nContent-Type: %s\r\n\r\n"; class FileInfo { public String mField; public String mContentType; public String mFilename; public InputStreamAt mIsa; public FileInfo(String field, String contentType, String filename, InputStreamAt isa) { mField = field; mContentType = contentType; mFilename = filename; mIsa = isa; if (mContentType == null || mContentType.length() == 0) { mContentType = "application/octet-stream"; } } public long length() { return fileTpl.length() - 2*4 + mBoundary.length() + mIsa.length() + 2 + mField.getBytes().length + mContentType.length() + mFilename.getBytes().length; } public void writeTo(OutputStream outputStream) throws IOException { outputStream.write(String.format(fileTpl, mBoundary, mField, mFilename, mContentType).getBytes()); outputStream.flush(); - int blockSize = 256 * 1 << 10; + int blockSize = 256 * 1024; long index = 0; long length = mIsa.length(); - while(index < length) { + while (index < length) { int readLength = (int) StrictMath.min((long) blockSize, mIsa.length() - index); outputStream.write(mIsa.read(index, readLength)); index += blockSize; outputStream.flush(); } outputStream.write("\r\n".getBytes()); outputStream.flush(); } } private static String getRandomString(int length) { String base = "abcdefghijklmnopqrstuvwxyz0123456789"; Random random = new Random(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < length; i++) { int number = random.nextInt(base.length()); sb.append(base.charAt(number)); } return sb.toString(); } }
false
true
public void writeTo(OutputStream outputStream) throws IOException { outputStream.write(String.format(fileTpl, mBoundary, mField, mFilename, mContentType).getBytes()); outputStream.flush(); int blockSize = 256 * 1 << 10; long index = 0; long length = mIsa.length(); while(index < length) { int readLength = (int) StrictMath.min((long) blockSize, mIsa.length() - index); outputStream.write(mIsa.read(index, readLength)); index += blockSize; outputStream.flush(); } outputStream.write("\r\n".getBytes()); outputStream.flush(); }
public void writeTo(OutputStream outputStream) throws IOException { outputStream.write(String.format(fileTpl, mBoundary, mField, mFilename, mContentType).getBytes()); outputStream.flush(); int blockSize = 256 * 1024; long index = 0; long length = mIsa.length(); while (index < length) { int readLength = (int) StrictMath.min((long) blockSize, mIsa.length() - index); outputStream.write(mIsa.read(index, readLength)); index += blockSize; outputStream.flush(); } outputStream.write("\r\n".getBytes()); outputStream.flush(); }
diff --git a/src/org/geometerplus/fbreader/fbreader/FBView.java b/src/org/geometerplus/fbreader/fbreader/FBView.java index c62b417b..b8365cde 100644 --- a/src/org/geometerplus/fbreader/fbreader/FBView.java +++ b/src/org/geometerplus/fbreader/fbreader/FBView.java @@ -1,599 +1,599 @@ /* * Copyright (C) 2007-2011 Geometer Plus <[email protected]> * * 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.geometerplus.fbreader.fbreader; import java.util.*; import org.geometerplus.zlibrary.core.application.ZLApplication; import org.geometerplus.zlibrary.core.util.ZLColor; import org.geometerplus.zlibrary.core.library.ZLibrary; import org.geometerplus.zlibrary.core.view.ZLPaintContext; import org.geometerplus.zlibrary.core.filesystem.ZLFile; import org.geometerplus.zlibrary.core.filesystem.ZLResourceFile; import org.geometerplus.zlibrary.text.model.ZLTextModel; import org.geometerplus.zlibrary.text.view.*; import org.geometerplus.fbreader.bookmodel.BookModel; import org.geometerplus.fbreader.bookmodel.FBHyperlinkType; import org.geometerplus.fbreader.bookmodel.TOCTree; public final class FBView extends ZLTextView { private FBReaderApp myReader; FBView(FBReaderApp reader) { myReader = reader; } public void setModel(ZLTextModel model) { myIsManualScrollingActive = false; super.setModel(model); if (myFooter != null) { myFooter.resetTOCMarks(); } } private int myStartX; private int myStartY; private boolean myIsManualScrollingActive; private boolean myIsBrightnessAdjustmentInProgress; private int myStartBrightness; private String myZoneMapId; private TapZoneMap myZoneMap; private TapZoneMap getZoneMap() { //final String id = // ScrollingPreferences.Instance().TapZonesSchemeOption.getValue().toString(); final String id = ScrollingPreferences.Instance().HorizontalOption.getValue() ? "right_to_left" : "up"; if (!id.equals(myZoneMapId)) { myZoneMap = new TapZoneMap(id); myZoneMapId = id; } return myZoneMap; } public boolean onFingerSingleTap(int x, int y) { if (super.onFingerSingleTap(x, y)) { return true; } if (isScrollingActive()) { return false; } if (myReader.FooterIsSensitiveOption.getValue()) { Footer footer = getFooterArea(); if (footer != null && y > myContext.getHeight() - footer.getTapHeight()) { myReader.addInvisibleBookmark(); footer.setProgress(x); return true; } } final ZLTextElementRegion region = findRegion(x, y, 10, ZLTextElementRegion.HyperlinkFilter); if (region != null) { selectRegion(region); myReader.resetView(); myReader.repaintView(); myReader.doAction(ActionCode.PROCESS_HYPERLINK); return true; } myReader.doActionWithCoordinates(getZoneMap().getActionByCoordinates( x, y, myContext.getWidth(), myContext.getHeight(), isDoubleTapSupported() ? TapZoneMap.Tap.singleNotDoubleTap : TapZoneMap.Tap.singleTap ), x, y); return true; } @Override public boolean isDoubleTapSupported() { return myReader.EnableDoubleTapOption.getValue(); } @Override public boolean onFingerDoubleTap(int x, int y) { if (super.onFingerDoubleTap(x, y)) { return true; } myReader.doActionWithCoordinates(getZoneMap().getActionByCoordinates( x, y, myContext.getWidth(), myContext.getHeight(), TapZoneMap.Tap.doubleTap ), x, y); return true; } public boolean onFingerPress(int x, int y) { if (super.onFingerPress(x, y)) { return true; } if (isScrollingActive()) { return false; } if (myReader.FooterIsSensitiveOption.getValue()) { Footer footer = getFooterArea(); if (footer != null && y > myContext.getHeight() - footer.getTapHeight()) { footer.setProgress(x); return true; } } if (myReader.AllowScreenBrightnessAdjustmentOption.getValue() && x < myContext.getWidth() / 10) { myIsBrightnessAdjustmentInProgress = true; myStartY = y; myStartBrightness = ZLibrary.Instance().getScreenBrightness(); return true; } startManualScrolling(x, y); return true; } private void startManualScrolling(int x, int y) { final ScrollingPreferences.FingerScrolling fingerScrolling = ScrollingPreferences.Instance().FingerScrollingOption.getValue(); if (fingerScrolling == ScrollingPreferences.FingerScrolling.byFlick || fingerScrolling == ScrollingPreferences.FingerScrolling.byTapAndFlick) { myStartX = x; myStartY = y; setScrollingActive(true); myIsManualScrollingActive = true; } } public boolean onFingerMove(int x, int y) { if (super.onFingerMove(x, y)) { return true; } synchronized (this) { if (myIsBrightnessAdjustmentInProgress) { if (x >= myContext.getWidth() / 5) { myIsBrightnessAdjustmentInProgress = false; startManualScrolling(x, y); } else { final int delta = (myStartBrightness + 30) * (myStartY - y) / myContext.getHeight(); ZLibrary.Instance().setScreenBrightness(myStartBrightness + delta); return true; } } if (isScrollingActive() && myIsManualScrollingActive) { final boolean horizontal = ScrollingPreferences.Instance().HorizontalOption.getValue(); final int diff = horizontal ? x - myStartX : y - myStartY; final Direction direction = horizontal ? Direction.rightToLeft : Direction.up; if (diff >= 0) { final ZLTextWordCursor cursor = getStartCursor(); if (cursor == null || cursor.isNull()) { return false; } if (!cursor.isStartOfParagraph() || !cursor.getParagraphCursor().isFirst()) { myReader.scrollViewManually(myStartX, myStartY, x, y, direction); } } else { final ZLTextWordCursor cursor = getEndCursor(); if (cursor == null || cursor.isNull()) { return false; } if (!cursor.isEndOfParagraph() || !cursor.getParagraphCursor().isLast()) { myReader.scrollViewManually(myStartX, myStartY, x, y, direction); } } return true; } } return false; } public boolean onFingerRelease(int x, int y) { if (super.onFingerRelease(x, y)) { return true; } synchronized (this) { myIsBrightnessAdjustmentInProgress = false; if (isScrollingActive() && myIsManualScrollingActive) { setScrollingActive(false); myIsManualScrollingActive = false; final boolean horizontal = ScrollingPreferences.Instance().HorizontalOption.getValue(); final int diff = horizontal ? x - myStartX : y - myStartY; boolean doScroll = false; if (diff > 0) { ZLTextWordCursor cursor = getStartCursor(); if (cursor != null && !cursor.isNull()) { doScroll = !cursor.isStartOfParagraph() || !cursor.getParagraphCursor().isFirst(); } } else if (diff < 0) { ZLTextWordCursor cursor = getEndCursor(); if (cursor != null && !cursor.isNull()) { doScroll = !cursor.isEndOfParagraph() || !cursor.getParagraphCursor().isLast(); } } if (doScroll) { final int h = myContext.getHeight(); final int w = myContext.getWidth(); final int minDiff = horizontal ? (w > h ? w / 4 : w / 3) : (h > w ? h / 4 : h / 3); final PageIndex pageIndex = Math.abs(diff) < minDiff ? PageIndex.current : (diff < 0 ? PageIndex.next : PageIndex.previous); startAutoScrolling(pageIndex, horizontal ? Direction.rightToLeft : Direction.up, ScrollingPreferences.Instance().AnimationSpeedOption.getValue()); } return true; } } return false; } public boolean onFingerLongPress(int x, int y) { if (super.onFingerLongPress(x, y)) { return true; } if (myReader.DictionaryTappingActionOption.getValue() != FBReaderApp.DictionaryTappingAction.doNothing) { final ZLTextElementRegion region = findRegion(x, y, 10, ZLTextElementRegion.AnyRegionFilter); if (region != null) { selectRegion(region); myReader.resetView(); myReader.repaintView(); return true; } } return false; } public boolean onFingerMoveAfterLongPress(int x, int y) { if (super.onFingerMoveAfterLongPress(x, y)) { return true; } if (myReader.DictionaryTappingActionOption.getValue() != FBReaderApp.DictionaryTappingAction.doNothing) { final ZLTextElementRegion region = findRegion(x, y, 10, ZLTextElementRegion.AnyRegionFilter); if (region != null) { selectRegion(region); myReader.resetView(); myReader.repaintView(); } } return true; } public boolean onFingerReleaseAfterLongPress(int x, int y) { if (super.onFingerReleaseAfterLongPress(x, y)) { return true; } if (myReader.DictionaryTappingActionOption.getValue() == FBReaderApp.DictionaryTappingAction.openDictionary) { myReader.doAction(ActionCode.PROCESS_HYPERLINK); return true; } return false; } public boolean onTrackballRotated(int diffX, int diffY) { if (diffX == 0 && diffY == 0) { return true; } final Direction direction = (diffY != 0) ? (diffY > 0 ? Direction.down : Direction.up) : (diffX > 0 ? Direction.leftToRight : Direction.rightToLeft); ZLTextElementRegion region = currentRegion(); final ZLTextElementRegion.Filter filter = region instanceof ZLTextWordRegion || myReader.NavigateAllWordsOption.getValue() ? ZLTextElementRegion.AnyRegionFilter : ZLTextElementRegion.ImageOrHyperlinkFilter; region = nextRegion(direction, filter); if (region != null) { selectRegion(region); } else { if (direction == Direction.down) { scrollPage(true, ZLTextView.ScrollingMode.SCROLL_LINES, 1); } else if (direction == Direction.up) { scrollPage(false, ZLTextView.ScrollingMode.SCROLL_LINES, 1); } } myReader.resetView(); myReader.repaintView(); return true; } @Override public int getLeftMargin() { return myReader.LeftMarginOption.getValue(); } @Override public int getRightMargin() { return myReader.RightMarginOption.getValue(); } @Override public int getTopMargin() { return myReader.TopMarginOption.getValue(); } @Override public int getBottomMargin() { return myReader.BottomMarginOption.getValue(); } @Override public ZLFile getWallpaperFile() { final String filePath = myReader.getColorProfile().WallpaperOption.getValue(); if ("".equals(filePath)) { return null; } final ZLFile file = ZLFile.createFileByPath(filePath); if (file == null || !file.exists()) { return null; } return file; } @Override public ZLColor getBackgroundColor() { return myReader.getColorProfile().BackgroundOption.getValue(); } @Override public ZLColor getSelectedBackgroundColor() { return myReader.getColorProfile().SelectionBackgroundOption.getValue(); } @Override public ZLColor getTextColor(ZLTextHyperlink hyperlink) { final ColorProfile profile = myReader.getColorProfile(); switch (hyperlink.Type) { default: case FBHyperlinkType.NONE: return profile.RegularTextOption.getValue(); case FBHyperlinkType.INTERNAL: return myReader.Model.Book.isHyperlinkVisited(hyperlink.Id) ? profile.VisitedHyperlinkTextOption.getValue() : profile.HyperlinkTextOption.getValue(); case FBHyperlinkType.EXTERNAL: return profile.HyperlinkTextOption.getValue(); } } @Override public ZLColor getHighlightingColor() { return myReader.getColorProfile().HighlightingOption.getValue(); } private class Footer implements FooterArea { private Runnable UpdateTask = new Runnable() { public void run() { ZLApplication.Instance().repaintView(); } }; private ArrayList<TOCTree> myTOCMarks; public int getHeight() { return myReader.FooterHeightOption.getValue(); } public synchronized void resetTOCMarks() { myTOCMarks = null; } private final int MAX_TOC_MARKS_NUMBER = 100; private synchronized void updateTOCMarks(BookModel model) { myTOCMarks = new ArrayList<TOCTree>(); TOCTree toc = model.TOCTree; if (toc == null) { return; } int maxLevel = Integer.MAX_VALUE; if (toc.getSize() >= MAX_TOC_MARKS_NUMBER) { final int[] sizes = new int[10]; for (TOCTree tocItem : toc) { if (tocItem.Level < 10) { ++sizes[tocItem.Level]; } } for (int i = 1; i < sizes.length; ++i) { sizes[i] += sizes[i - 1]; } for (maxLevel = sizes.length - 1; maxLevel >= 0; --maxLevel) { if (sizes[maxLevel] < MAX_TOC_MARKS_NUMBER) { break; } } } for (TOCTree tocItem : toc.allSubTrees(maxLevel)) { myTOCMarks.add(tocItem); } } public synchronized void paint(ZLPaintContext context) { final FBReaderApp reader = myReader; if (reader == null) { return; } final BookModel model = reader.Model; if (model == null) { return; } //final ZLColor bgColor = getBackgroundColor(); // TODO: separate color option for footer color final ZLColor fgColor = getTextColor(ZLTextHyperlink.NO_LINK); final ZLColor fillColor = reader.getColorProfile().FooterFillOption.getValue(); final int left = getLeftMargin(); final int right = context.getWidth() - getRightMargin(); final int height = getHeight(); final int lineWidth = height <= 10 ? 1 : 2; final int delta = height <= 10 ? 0 : 1; context.setFont( reader.FooterFontOption.getValue(), height <= 10 ? height + 3 : height + 1, height > 10, false, false ); final int pagesProgress = computeCurrentPage(); final int bookLength = computePageNumber(); final StringBuilder info = new StringBuilder(); if (reader.FooterShowProgressOption.getValue()) { info.append(pagesProgress); info.append("/"); info.append(bookLength); } if (reader.FooterShowBatteryOption.getValue()) { if (info.length() > 0) { info.append(" "); } info.append(reader.getBatteryLevel()); info.append("%"); } if (reader.FooterShowClockOption.getValue()) { if (info.length() > 0) { info.append(" "); } info.append(ZLibrary.Instance().getCurrentTimeString()); } final String infoString = info.toString(); final int infoWidth = context.getStringWidth(infoString); final ZLFile wallpaper = getWallpaperFile(); if (wallpaper != null) { context.clear(wallpaper, wallpaper instanceof ZLResourceFile); } else { context.clear(getBackgroundColor()); } // draw info text context.setTextColor(fgColor); context.drawString(right - infoWidth, height - delta, infoString); // draw gauge final int gaugeRight = right - (infoWidth == 0 ? 0 : infoWidth + 10); myGaugeWidth = gaugeRight - left - 2 * lineWidth; context.setLineColor(fgColor); context.setLineWidth(lineWidth); context.drawLine(left, lineWidth, left, height - lineWidth); context.drawLine(left, height - lineWidth, gaugeRight, height - lineWidth); context.drawLine(gaugeRight, height - lineWidth, gaugeRight, lineWidth); context.drawLine(gaugeRight, lineWidth, left, lineWidth); final int gaugeInternalRight = left + lineWidth + (int)(1.0 * myGaugeWidth * pagesProgress / bookLength); context.setFillColor(fillColor); - context.fillRectangle(left + lineWidth, height - 2 * lineWidth, gaugeInternalRight, 2 * lineWidth); + context.fillRectangle(left + 1, height - 2 * lineWidth, gaugeInternalRight, lineWidth + 1); if (reader.FooterShowTOCMarksOption.getValue()) { if (myTOCMarks == null) { updateTOCMarks(model); } final int fullLength = sizeOfFullText(); for (TOCTree tocItem : myTOCMarks) { TOCTree.Reference reference = tocItem.getReference(); if (reference != null) { final int refCoord = sizeOfTextBeforeParagraph(reference.ParagraphIndex); final int xCoord = left + 2 * lineWidth + (int)(1.0 * myGaugeWidth * refCoord / fullLength); context.drawLine(xCoord, height - lineWidth, xCoord, lineWidth); } } } } // TODO: remove int myGaugeWidth = 1; public int getGaugeWidth() { return myGaugeWidth; } public int getTapHeight() { return 30; } public void setProgress(int x) { // set progress according to tap coordinate int gaugeWidth = getGaugeWidth(); float progress = 1.0f * Math.min(x, gaugeWidth) / gaugeWidth; int page = (int)(progress * computePageNumber()); if (page <= 1) { gotoHome(); } else { gotoPage(page); } myReader.resetView(); myReader.repaintView(); } } private Footer myFooter; @Override public Footer getFooterArea() { if (myReader.ScrollbarTypeOption.getValue() == SCROLLBAR_SHOW_AS_FOOTER) { if (myFooter == null) { myFooter = new Footer(); ZLApplication.Instance().addTimerTask(myFooter.UpdateTask, 15000); } } else { if (myFooter != null) { ZLApplication.Instance().removeTimerTask(myFooter.UpdateTask); myFooter = null; } } return myFooter; } @Override protected boolean isSelectionEnabled() { return myReader.SelectionEnabledOption.getValue(); } public static final int SCROLLBAR_SHOW_AS_FOOTER = 3; @Override public int scrollbarType() { return myReader.ScrollbarTypeOption.getValue(); } @Override public Animation getAnimationType() { return ScrollingPreferences.Instance().AnimationOption.getValue(); } }
true
true
public synchronized void paint(ZLPaintContext context) { final FBReaderApp reader = myReader; if (reader == null) { return; } final BookModel model = reader.Model; if (model == null) { return; } //final ZLColor bgColor = getBackgroundColor(); // TODO: separate color option for footer color final ZLColor fgColor = getTextColor(ZLTextHyperlink.NO_LINK); final ZLColor fillColor = reader.getColorProfile().FooterFillOption.getValue(); final int left = getLeftMargin(); final int right = context.getWidth() - getRightMargin(); final int height = getHeight(); final int lineWidth = height <= 10 ? 1 : 2; final int delta = height <= 10 ? 0 : 1; context.setFont( reader.FooterFontOption.getValue(), height <= 10 ? height + 3 : height + 1, height > 10, false, false ); final int pagesProgress = computeCurrentPage(); final int bookLength = computePageNumber(); final StringBuilder info = new StringBuilder(); if (reader.FooterShowProgressOption.getValue()) { info.append(pagesProgress); info.append("/"); info.append(bookLength); } if (reader.FooterShowBatteryOption.getValue()) { if (info.length() > 0) { info.append(" "); } info.append(reader.getBatteryLevel()); info.append("%"); } if (reader.FooterShowClockOption.getValue()) { if (info.length() > 0) { info.append(" "); } info.append(ZLibrary.Instance().getCurrentTimeString()); } final String infoString = info.toString(); final int infoWidth = context.getStringWidth(infoString); final ZLFile wallpaper = getWallpaperFile(); if (wallpaper != null) { context.clear(wallpaper, wallpaper instanceof ZLResourceFile); } else { context.clear(getBackgroundColor()); } // draw info text context.setTextColor(fgColor); context.drawString(right - infoWidth, height - delta, infoString); // draw gauge final int gaugeRight = right - (infoWidth == 0 ? 0 : infoWidth + 10); myGaugeWidth = gaugeRight - left - 2 * lineWidth; context.setLineColor(fgColor); context.setLineWidth(lineWidth); context.drawLine(left, lineWidth, left, height - lineWidth); context.drawLine(left, height - lineWidth, gaugeRight, height - lineWidth); context.drawLine(gaugeRight, height - lineWidth, gaugeRight, lineWidth); context.drawLine(gaugeRight, lineWidth, left, lineWidth); final int gaugeInternalRight = left + lineWidth + (int)(1.0 * myGaugeWidth * pagesProgress / bookLength); context.setFillColor(fillColor); context.fillRectangle(left + lineWidth, height - 2 * lineWidth, gaugeInternalRight, 2 * lineWidth); if (reader.FooterShowTOCMarksOption.getValue()) { if (myTOCMarks == null) { updateTOCMarks(model); } final int fullLength = sizeOfFullText(); for (TOCTree tocItem : myTOCMarks) { TOCTree.Reference reference = tocItem.getReference(); if (reference != null) { final int refCoord = sizeOfTextBeforeParagraph(reference.ParagraphIndex); final int xCoord = left + 2 * lineWidth + (int)(1.0 * myGaugeWidth * refCoord / fullLength); context.drawLine(xCoord, height - lineWidth, xCoord, lineWidth); } } } }
public synchronized void paint(ZLPaintContext context) { final FBReaderApp reader = myReader; if (reader == null) { return; } final BookModel model = reader.Model; if (model == null) { return; } //final ZLColor bgColor = getBackgroundColor(); // TODO: separate color option for footer color final ZLColor fgColor = getTextColor(ZLTextHyperlink.NO_LINK); final ZLColor fillColor = reader.getColorProfile().FooterFillOption.getValue(); final int left = getLeftMargin(); final int right = context.getWidth() - getRightMargin(); final int height = getHeight(); final int lineWidth = height <= 10 ? 1 : 2; final int delta = height <= 10 ? 0 : 1; context.setFont( reader.FooterFontOption.getValue(), height <= 10 ? height + 3 : height + 1, height > 10, false, false ); final int pagesProgress = computeCurrentPage(); final int bookLength = computePageNumber(); final StringBuilder info = new StringBuilder(); if (reader.FooterShowProgressOption.getValue()) { info.append(pagesProgress); info.append("/"); info.append(bookLength); } if (reader.FooterShowBatteryOption.getValue()) { if (info.length() > 0) { info.append(" "); } info.append(reader.getBatteryLevel()); info.append("%"); } if (reader.FooterShowClockOption.getValue()) { if (info.length() > 0) { info.append(" "); } info.append(ZLibrary.Instance().getCurrentTimeString()); } final String infoString = info.toString(); final int infoWidth = context.getStringWidth(infoString); final ZLFile wallpaper = getWallpaperFile(); if (wallpaper != null) { context.clear(wallpaper, wallpaper instanceof ZLResourceFile); } else { context.clear(getBackgroundColor()); } // draw info text context.setTextColor(fgColor); context.drawString(right - infoWidth, height - delta, infoString); // draw gauge final int gaugeRight = right - (infoWidth == 0 ? 0 : infoWidth + 10); myGaugeWidth = gaugeRight - left - 2 * lineWidth; context.setLineColor(fgColor); context.setLineWidth(lineWidth); context.drawLine(left, lineWidth, left, height - lineWidth); context.drawLine(left, height - lineWidth, gaugeRight, height - lineWidth); context.drawLine(gaugeRight, height - lineWidth, gaugeRight, lineWidth); context.drawLine(gaugeRight, lineWidth, left, lineWidth); final int gaugeInternalRight = left + lineWidth + (int)(1.0 * myGaugeWidth * pagesProgress / bookLength); context.setFillColor(fillColor); context.fillRectangle(left + 1, height - 2 * lineWidth, gaugeInternalRight, lineWidth + 1); if (reader.FooterShowTOCMarksOption.getValue()) { if (myTOCMarks == null) { updateTOCMarks(model); } final int fullLength = sizeOfFullText(); for (TOCTree tocItem : myTOCMarks) { TOCTree.Reference reference = tocItem.getReference(); if (reference != null) { final int refCoord = sizeOfTextBeforeParagraph(reference.ParagraphIndex); final int xCoord = left + 2 * lineWidth + (int)(1.0 * myGaugeWidth * refCoord / fullLength); context.drawLine(xCoord, height - lineWidth, xCoord, lineWidth); } } } }
diff --git a/src/java/azkaban/utils/Utils.java b/src/java/azkaban/utils/Utils.java index 257508ad..44edfaab 100644 --- a/src/java/azkaban/utils/Utils.java +++ b/src/java/azkaban/utils/Utils.java @@ -1,393 +1,393 @@ /* * Copyright 2012 LinkedIn Corp. * * 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 azkaban.utils; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Collection; import java.util.Enumeration; import java.util.Random; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import java.util.zip.ZipOutputStream; import org.apache.commons.io.IOUtils; import org.joda.time.Days; import org.joda.time.DurationFieldType; import org.joda.time.Hours; import org.joda.time.Minutes; import org.joda.time.Months; import org.joda.time.ReadablePeriod; import org.joda.time.Seconds; import org.joda.time.Weeks; import org.joda.time.Years; /** * A util helper class full of static methods that are commonly used. */ public class Utils { public static final Random RANDOM = new Random(); /** * Private constructor. */ private Utils() { } /** * Equivalent to Object.equals except that it handles nulls. If a and b are * both null, true is returned. * * @param a * @param b * @return */ public static boolean equals(Object a, Object b) { if (a == null || b == null) { return a == b; } return a.equals(b); } /** * Return the object if it is non-null, otherwise throw an exception * * @param <T> * The type of the object * @param t * The object * @return The object if it is not null * @throws IllegalArgumentException * if the object is null */ public static <T> T nonNull(T t) { if (t == null) { throw new IllegalArgumentException("Null value not allowed."); } else { return t; } } public static File findFilefromDir(File dir, String fn){ if(dir.isDirectory()) { for(File f : dir.listFiles()) { if(f.getName().equals(fn)) { return f; } } } return null; } /** * Print the message and then exit with the given exit code * * @param message * The message to print * @param exitCode * The exit code */ public static void croak(String message, int exitCode) { System.err.println(message); System.exit(exitCode); } public static File createTempDir() { return createTempDir(new File(System.getProperty("java.io.tmpdir"))); } public static File createTempDir(File parent) { File temp = new File(parent, Integer.toString(Math.abs(RANDOM.nextInt()) % 100000000)); temp.delete(); temp.mkdir(); temp.deleteOnExit(); return temp; } public static void zip(File input, File output) throws IOException { FileOutputStream out = new FileOutputStream(output); ZipOutputStream zOut = new ZipOutputStream(out); zipFile("", input, zOut); zOut.close(); } public static void zipFolderContent(File folder, File output) throws IOException { FileOutputStream out = new FileOutputStream(output); ZipOutputStream zOut = new ZipOutputStream(out); File[] files = folder.listFiles(); if (files != null) { for (File f : files) { zipFile("", f, zOut); } } zOut.close(); } private static void zipFile(String path, File input, ZipOutputStream zOut) throws IOException { if (input.isDirectory()) { File[] files = input.listFiles(); if (files != null) { for (File f : files) { String childPath = path + input.getName() + (f.isDirectory() ? "/" : ""); zipFile(childPath, f, zOut); } } } else { String childPath = path + (path.length() > 0 ? "/" : "") + input.getName(); ZipEntry entry = new ZipEntry(childPath); zOut.putNextEntry(entry); InputStream fileInputStream = new BufferedInputStream( new FileInputStream(input)); IOUtils.copy(fileInputStream, zOut); fileInputStream.close(); } } public static void unzip(ZipFile source, File dest) throws IOException { Enumeration<?> entries = source.entries(); while (entries.hasMoreElements()) { ZipEntry entry = (ZipEntry) entries.nextElement(); File newFile = new File(dest, entry.getName()); if (entry.isDirectory()) { newFile.mkdirs(); } else { newFile.getParentFile().mkdirs(); InputStream src = source.getInputStream(entry); OutputStream output = new BufferedOutputStream( new FileOutputStream(newFile)); IOUtils.copy(src, output); src.close(); output.close(); } } } public static String flattenToString(Collection<?> collection, String delimiter) { StringBuffer buffer = new StringBuffer(); for (Object obj : collection) { buffer.append(obj.toString()); buffer.append(','); } if (buffer.length() > 0) { buffer.setLength(buffer.length() - 1); } return buffer.toString(); } public static Double convertToDouble(Object obj) { if (obj instanceof String) { return Double.parseDouble((String) obj); } return (Double) obj; } /** * Get the root cause of the Exception * * @param e The Exception * @return The root cause of the Exception */ private static RuntimeException getCause(InvocationTargetException e) { Throwable cause = e.getCause(); if(cause instanceof RuntimeException) throw (RuntimeException) cause; else throw new IllegalStateException(e.getCause()); } /** * Get the Class of all the objects * * @param args The objects to get the Classes from * @return The classes as an array */ public static Class<?>[] getTypes(Object... args) { Class<?>[] argTypes = new Class<?>[args.length]; for(int i = 0; i < argTypes.length; i++) argTypes[i] = args[i].getClass(); return argTypes; } public static Object callConstructor(Class<?> c, Object... args) { return callConstructor(c, getTypes(args), args); } /** * Call the class constructor with the given arguments * * @param c The class * @param args The arguments * @return The constructed object */ public static Object callConstructor(Class<?> c, Class<?>[] argTypes, Object[] args) { try { Constructor<?> cons = c.getConstructor(argTypes); return cons.newInstance(args); } catch(InvocationTargetException e) { throw getCause(e); } catch(IllegalAccessException e) { throw new IllegalStateException(e); } catch(NoSuchMethodException e) { throw new IllegalStateException(e); } catch(InstantiationException e) { throw new IllegalStateException(e); } } public static String formatDuration(long startTime, long endTime) { if (startTime == -1) { return "-"; } long durationMS; if (endTime == -1) { durationMS = System.currentTimeMillis() - startTime; } else { durationMS = endTime - startTime; } long seconds = durationMS/1000; if (seconds < 60) { return seconds + " sec"; } long minutes = seconds / 60; seconds %= 60; if (minutes < 60) { return minutes + "m " + seconds + "s"; } long hours = minutes / 60; minutes %= 60; if (hours < 24) { return hours + "h " + minutes + "m " + seconds + "s"; } long days = hours / 24; hours %= 24; return days + "d " + hours + "h " + minutes + "m"; } public static Object invokeStaticMethod(ClassLoader loader, String className, String methodName, Object ... args) throws ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException { Class<?> clazz = loader.loadClass(className); Class<?>[] argTypes = new Class[args.length]; for (int i=0; i < args.length; ++i) { //argTypes[i] = args[i].getClass(); argTypes[i] = args[i].getClass(); } Method method = clazz.getDeclaredMethod(methodName, argTypes); return method.invoke(null, args); } public static void copyStream(InputStream input, OutputStream output) throws IOException { byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = input.read(buffer)) != -1) { output.write(buffer, 0, bytesRead); } } public static ReadablePeriod parsePeriodString(String periodStr) { ReadablePeriod period; char periodUnit = periodStr.charAt(periodStr.length() - 1); - if (periodUnit == 'n') { + if (periodStr.equals("null") || periodUnit == 'n') { return null; } int periodInt = Integer.parseInt(periodStr.substring(0, periodStr.length() - 1)); switch (periodUnit) { case 'y': period = Years.years(periodInt); break; case 'M': period = Months.months(periodInt); break; case 'w': period = Weeks.weeks(periodInt); break; case 'd': period = Days.days(periodInt); break; case 'h': period = Hours.hours(periodInt); break; case 'm': period = Minutes.minutes(periodInt); break; case 's': period = Seconds.seconds(periodInt); break; default: throw new IllegalArgumentException("Invalid schedule period unit '" + periodUnit); } return period; } public static String createPeriodString(ReadablePeriod period) { String periodStr = "null"; if (period == null) { return "null"; } if (period.get(DurationFieldType.years()) > 0) { int years = period.get(DurationFieldType.years()); periodStr = years + "y"; } else if (period.get(DurationFieldType.months()) > 0) { int months = period.get(DurationFieldType.months()); periodStr = months + "M"; } else if (period.get(DurationFieldType.weeks()) > 0) { int weeks = period.get(DurationFieldType.weeks()); periodStr = weeks + "w"; } else if (period.get(DurationFieldType.days()) > 0) { int days = period.get(DurationFieldType.days()); periodStr = days + "d"; } else if (period.get(DurationFieldType.hours()) > 0) { int hours = period.get(DurationFieldType.hours()); periodStr = hours + "h"; } else if (period.get(DurationFieldType.minutes()) > 0) { int minutes = period.get(DurationFieldType.minutes()); periodStr = minutes + "m"; } else if (period.get(DurationFieldType.seconds()) > 0) { int seconds = period.get(DurationFieldType.seconds()); periodStr = seconds + "s"; } return periodStr; } }
true
true
public static ReadablePeriod parsePeriodString(String periodStr) { ReadablePeriod period; char periodUnit = periodStr.charAt(periodStr.length() - 1); if (periodUnit == 'n') { return null; } int periodInt = Integer.parseInt(periodStr.substring(0, periodStr.length() - 1)); switch (periodUnit) { case 'y': period = Years.years(periodInt); break; case 'M': period = Months.months(periodInt); break; case 'w': period = Weeks.weeks(periodInt); break; case 'd': period = Days.days(periodInt); break; case 'h': period = Hours.hours(periodInt); break; case 'm': period = Minutes.minutes(periodInt); break; case 's': period = Seconds.seconds(periodInt); break; default: throw new IllegalArgumentException("Invalid schedule period unit '" + periodUnit); } return period; }
public static ReadablePeriod parsePeriodString(String periodStr) { ReadablePeriod period; char periodUnit = periodStr.charAt(periodStr.length() - 1); if (periodStr.equals("null") || periodUnit == 'n') { return null; } int periodInt = Integer.parseInt(periodStr.substring(0, periodStr.length() - 1)); switch (periodUnit) { case 'y': period = Years.years(periodInt); break; case 'M': period = Months.months(periodInt); break; case 'w': period = Weeks.weeks(periodInt); break; case 'd': period = Days.days(periodInt); break; case 'h': period = Hours.hours(periodInt); break; case 'm': period = Minutes.minutes(periodInt); break; case 's': period = Seconds.seconds(periodInt); break; default: throw new IllegalArgumentException("Invalid schedule period unit '" + periodUnit); } return period; }
diff --git a/components/src/org/riotfamily/components/config/ComponentListConfig.java b/components/src/org/riotfamily/components/config/ComponentListConfig.java index d26366cf0..37c9ab68d 100644 --- a/components/src/org/riotfamily/components/config/ComponentListConfig.java +++ b/components/src/org/riotfamily/components/config/ComponentListConfig.java @@ -1,101 +1,101 @@ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1 * 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 Riot. * * The Initial Developer of the Original Code is * Neteye GmbH. * Portions created by the Initial Developer are Copyright (C) 2006 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Felix Gnass [fgnass at neteye dot de] * * ***** END LICENSE BLOCK ***** */ package org.riotfamily.components.config; import java.util.Collection; import java.util.List; import java.util.Map; import net.sf.json.JSONObject; import org.riotfamily.common.util.Generics; public class ComponentListConfig { private Integer min; private Integer max; private Map<String, ComponentConfig> validTypes = Generics.newHashMap(); private List<String> initialTypes = Generics.newArrayList(); public ComponentListConfig(Integer min, Integer max, List<String> initial, List<?> valid) { this.min = min; this.max = max; if (initial != null) { initialTypes.addAll(initial); } - if (valid != null) { + if (valid != null && !valid.isEmpty()) { for (Object obj : valid) { ComponentConfig config = new ComponentConfig(obj); validTypes.put(config.getType(), config); if (config.getMin() > 0) { int count = 0; for (String initialType : initialTypes) { if (initialType.equals(config.getType())) { count++; } } for (int i = count; i < config.getMin(); i++) { initialTypes.add(config.getType()); } } } } else if (initial != null) { for (String initialType : initial) { if (!validTypes.containsKey(initialType)) { validTypes.put(initialType, new ComponentConfig(initialType)); } } } } public Integer getMin() { return min; } public Integer getMax() { return max; } public Collection<ComponentConfig> getValidTypes() { return validTypes.values(); } public List<String> getInitialTypes() { return initialTypes; } public ComponentConfig getConfig(String type) { return validTypes.get(type); } public String toJSON() { return JSONObject.fromObject(this).toString(); } }
true
true
public ComponentListConfig(Integer min, Integer max, List<String> initial, List<?> valid) { this.min = min; this.max = max; if (initial != null) { initialTypes.addAll(initial); } if (valid != null) { for (Object obj : valid) { ComponentConfig config = new ComponentConfig(obj); validTypes.put(config.getType(), config); if (config.getMin() > 0) { int count = 0; for (String initialType : initialTypes) { if (initialType.equals(config.getType())) { count++; } } for (int i = count; i < config.getMin(); i++) { initialTypes.add(config.getType()); } } } } else if (initial != null) { for (String initialType : initial) { if (!validTypes.containsKey(initialType)) { validTypes.put(initialType, new ComponentConfig(initialType)); } } } }
public ComponentListConfig(Integer min, Integer max, List<String> initial, List<?> valid) { this.min = min; this.max = max; if (initial != null) { initialTypes.addAll(initial); } if (valid != null && !valid.isEmpty()) { for (Object obj : valid) { ComponentConfig config = new ComponentConfig(obj); validTypes.put(config.getType(), config); if (config.getMin() > 0) { int count = 0; for (String initialType : initialTypes) { if (initialType.equals(config.getType())) { count++; } } for (int i = count; i < config.getMin(); i++) { initialTypes.add(config.getType()); } } } } else if (initial != null) { for (String initialType : initial) { if (!validTypes.containsKey(initialType)) { validTypes.put(initialType, new ComponentConfig(initialType)); } } } }
diff --git a/libs/gino-runner/src/main/java/gino/Runner.java b/libs/gino-runner/src/main/java/gino/Runner.java index e47bac7..abc679f 100644 --- a/libs/gino-runner/src/main/java/gino/Runner.java +++ b/libs/gino-runner/src/main/java/gino/Runner.java @@ -1,48 +1,48 @@ package gino; import java.io.IOException; import org.mozilla.javascript.Context; import org.mozilla.javascript.ContextFactory; import org.mozilla.javascript.Function; import org.mozilla.javascript.ImporterTopLevel; import org.mozilla.javascript.ScriptableObject; public class Runner { public static Context enterContext(ClassLoader classLoader) { Context cx = ContextFactory.getGlobal().enterContext(); cx.setLanguageVersion(Context.VERSION_1_8); cx.setApplicationClassLoader(classLoader); return cx; } public static ScriptableObject createScope(Context cx, Object logger) throws IOException { ScriptableObject scope = new ImporterTopLevel(cx); if (logger != null) scope.put("logger", scope, Context.javaToJS(logger, scope)); Functions.defineFunctions(scope); Functions.loadScript(cx, scope, "gino/scope.js", true); return scope; } public static void exitContext() { Context.exit(); } public static Object run(String scriptFileName, Object[] args, ClassLoader classLoader, Object logger) throws IOException { Object result; Context cx = enterContext(classLoader); try { ScriptableObject scope = createScope(cx, logger); Object bootFunc = Functions.loadScript(cx, scope, "gino/boot.js", true); if (!(bootFunc instanceof Function)) throw new RuntimeException("result of boot script is expected to be a function"); - Object[] bootArgs = new Object[] { Context.javaToJS(scriptFileName, scope), args }; + Object[] bootArgs = new Object[] { Context.javaToJS(scriptFileName, scope), Context.javaToJS(args, scope) }; result = ((Function) bootFunc).call(cx, scope, null, bootArgs); } finally { exitContext(); } return result; } }
true
true
public static Object run(String scriptFileName, Object[] args, ClassLoader classLoader, Object logger) throws IOException { Object result; Context cx = enterContext(classLoader); try { ScriptableObject scope = createScope(cx, logger); Object bootFunc = Functions.loadScript(cx, scope, "gino/boot.js", true); if (!(bootFunc instanceof Function)) throw new RuntimeException("result of boot script is expected to be a function"); Object[] bootArgs = new Object[] { Context.javaToJS(scriptFileName, scope), args }; result = ((Function) bootFunc).call(cx, scope, null, bootArgs); } finally { exitContext(); } return result; }
public static Object run(String scriptFileName, Object[] args, ClassLoader classLoader, Object logger) throws IOException { Object result; Context cx = enterContext(classLoader); try { ScriptableObject scope = createScope(cx, logger); Object bootFunc = Functions.loadScript(cx, scope, "gino/boot.js", true); if (!(bootFunc instanceof Function)) throw new RuntimeException("result of boot script is expected to be a function"); Object[] bootArgs = new Object[] { Context.javaToJS(scriptFileName, scope), Context.javaToJS(args, scope) }; result = ((Function) bootFunc).call(cx, scope, null, bootArgs); } finally { exitContext(); } return result; }
diff --git a/asm/src/org/objectweb/asm/tree/FrameNode.java b/asm/src/org/objectweb/asm/tree/FrameNode.java index f0137b65..45250245 100644 --- a/asm/src/org/objectweb/asm/tree/FrameNode.java +++ b/asm/src/org/objectweb/asm/tree/FrameNode.java @@ -1,208 +1,206 @@ /*** * ASM: a very small and fast Java bytecode manipulation framework * Copyright (c) 2000-2007 INRIA, France Telecom * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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. * 3. Neither the name of the copyright holders 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 OWNER 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 org.objectweb.asm.tree; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; /** * A node that represents a stack map frame. These nodes are pseudo instruction * nodes in order to be inserted in an instruction list. In fact these nodes * must(*) be inserted <i>just before</i> any instruction node <b>i</b> that * follows an unconditionnal branch instruction such as GOTO or THROW, that is * the target of a jump instruction, or that starts an exception handler block. * The stack map frame types must describe the values of the local variables and * of the operand stack elements <i>just before</i> <b>i</b> is executed. <br> * <br> (*) this is mandatory only for classes whose version is greater than or * equal to {@link Opcodes#V1_6 V1_6}. * * @author Eric Bruneton */ public class FrameNode extends AbstractInsnNode { /** * The type of this frame. Must be {@link Opcodes#F_NEW} for expanded * frames, or {@link Opcodes#F_FULL}, {@link Opcodes#F_APPEND}, * {@link Opcodes#F_CHOP}, {@link Opcodes#F_SAME} or * {@link Opcodes#F_APPEND}, {@link Opcodes#F_SAME1} for compressed frames. */ public int type; /** * The types of the local variables of this stack map frame. Elements of * this list can be Integer, String or LabelNode objects (for primitive, * reference and uninitialized types respectively - see * {@link MethodVisitor}). */ public List local; /** * The types of the operand stack elements of this stack map frame. Elements * of this list can be Integer, String or LabelNode objects (for primitive, * reference and uninitialized types respectively - see * {@link MethodVisitor}). */ public List stack; private FrameNode() { super(-1); } /** * Constructs a new {@link FrameNode}. * * @param type the type of this frame. Must be {@link Opcodes#F_NEW} for * expanded frames, or {@link Opcodes#F_FULL}, * {@link Opcodes#F_APPEND}, {@link Opcodes#F_CHOP}, * {@link Opcodes#F_SAME} or {@link Opcodes#F_APPEND}, * {@link Opcodes#F_SAME1} for compressed frames. * @param nLocal number of local variables of this stack map frame. * @param local the types of the local variables of this stack map frame. * Elements of this list can be Integer, String or LabelNode objects * (for primitive, reference and uninitialized types respectively - * see {@link MethodVisitor}). * @param nStack number of operand stack elements of this stack map frame. * @param stack the types of the operand stack elements of this stack map * frame. Elements of this list can be Integer, String or LabelNode * objects (for primitive, reference and uninitialized types * respectively - see {@link MethodVisitor}). */ public FrameNode( final int type, final int nLocal, final Object[] local, final int nStack, final Object[] stack) { super(-1); this.type = type; switch (type) { case Opcodes.F_NEW: case Opcodes.F_FULL: this.local = asList(nLocal, local); this.stack = asList(nStack, stack); break; case Opcodes.F_APPEND: this.local = asList(nLocal, local); break; case Opcodes.F_CHOP: - this.local = asList(nLocal, local); - break; case Opcodes.F_SAME: break; case Opcodes.F_SAME1: this.stack = asList(1, stack); break; } } public int getType() { return FRAME; } /** * Makes the given visitor visit this stack map frame. * * @param mv a method visitor. */ public void accept(final MethodVisitor mv) { switch (type) { case Opcodes.F_NEW: case Opcodes.F_FULL: mv.visitFrame(type, local.size(), asArray(local), stack.size(), asArray(stack)); break; case Opcodes.F_APPEND: mv.visitFrame(type, local.size(), asArray(local), 0, null); break; case Opcodes.F_CHOP: mv.visitFrame(type, local.size(), asArray(local), 0, null); break; case Opcodes.F_SAME: mv.visitFrame(type, 0, null, 0, null); break; case Opcodes.F_SAME1: mv.visitFrame(type, 0, null, 1, asArray(stack)); break; } } public AbstractInsnNode clone(final Map labels) { FrameNode clone = new FrameNode(); clone.type = type; if (local != null) { clone.local = new ArrayList(); for (int i = 0; i < local.size(); ++i) { Object l = local.get(i); if (l instanceof LabelNode) { l = labels.get(l); } clone.local.add(l); } } if (stack != null) { clone.stack = new ArrayList(); for (int i = 0; i < stack.size(); ++i) { Object s = stack.get(i); if (s instanceof LabelNode) { s = labels.get(s); } clone.stack.add(s); } } return clone; } // ------------------------------------------------------------------------ private static List asList(final int n, final Object[] o) { return Arrays.asList(o).subList(0, n); } private static Object[] asArray(final List l) { Object[] objs = new Object[l.size()]; for (int i = 0; i < objs.length; ++i) { Object o = l.get(i); if (o instanceof LabelNode) { o = ((LabelNode) o).getLabel(); } objs[i] = o; } return objs; } }
true
true
public FrameNode( final int type, final int nLocal, final Object[] local, final int nStack, final Object[] stack) { super(-1); this.type = type; switch (type) { case Opcodes.F_NEW: case Opcodes.F_FULL: this.local = asList(nLocal, local); this.stack = asList(nStack, stack); break; case Opcodes.F_APPEND: this.local = asList(nLocal, local); break; case Opcodes.F_CHOP: this.local = asList(nLocal, local); break; case Opcodes.F_SAME: break; case Opcodes.F_SAME1: this.stack = asList(1, stack); break; } }
public FrameNode( final int type, final int nLocal, final Object[] local, final int nStack, final Object[] stack) { super(-1); this.type = type; switch (type) { case Opcodes.F_NEW: case Opcodes.F_FULL: this.local = asList(nLocal, local); this.stack = asList(nStack, stack); break; case Opcodes.F_APPEND: this.local = asList(nLocal, local); break; case Opcodes.F_CHOP: case Opcodes.F_SAME: break; case Opcodes.F_SAME1: this.stack = asList(1, stack); break; } }
diff --git a/src/InvTweaksHandlerSorting.java b/src/InvTweaksHandlerSorting.java index 03b4c06..2108f58 100644 --- a/src/InvTweaksHandlerSorting.java +++ b/src/InvTweaksHandlerSorting.java @@ -1,659 +1,659 @@ import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Vector; import java.util.concurrent.TimeoutException; import java.util.logging.Logger; import net.minecraft.client.Minecraft; /** * Core of the sorting behaviour. Allows to move items in a container * (inventory or chest) with respect to the mod's configuration. * * @author Jimeo Wan * */ public class InvTweaksHandlerSorting extends InvTweaksObfuscation { private static final Logger log = Logger.getLogger("InvTweaks"); public static final boolean STACK_NOT_EMPTIED = true; public static final boolean STACK_EMPTIED = false; private static int[] DEFAULT_LOCK_PRIORITIES = null; private static boolean[] DEFAULT_FROZEN_SLOTS = null; private static final int MAX_CONTAINER_SIZE = 200; public static final int ALGORITHM_DEFAULT = 0; public static final int ALGORITHM_VERTICAL = 1; public static final int ALGORITHM_HORIZONTAL = 2; public static final int ALGORITHM_INVENTORY = 3; private InvTweaksContainerSectionManager containerMgr; private int algorithm; private int size; private boolean sortArmorParts; private InvTweaksItemTree tree; private Vector<InvTweaksConfigSortingRule> rules; private int[] rulePriority; private int[] keywordOrder; private int[] lockPriorities; private boolean[] frozenSlots; public InvTweaksHandlerSorting(Minecraft mc, InvTweaksConfig config, InvTweaksContainerSection section, int algorithm, int rowSize) throws Exception { super(mc); // Init constants if (DEFAULT_LOCK_PRIORITIES == null) { DEFAULT_LOCK_PRIORITIES = new int[MAX_CONTAINER_SIZE]; for (int i = 0; i < MAX_CONTAINER_SIZE; i++) { DEFAULT_LOCK_PRIORITIES[i] = 0; } } if (DEFAULT_FROZEN_SLOTS == null) { DEFAULT_FROZEN_SLOTS = new boolean[MAX_CONTAINER_SIZE]; for (int i = 0; i < MAX_CONTAINER_SIZE; i++) { DEFAULT_FROZEN_SLOTS[i] = false; } } // Init attributes this.containerMgr = new InvTweaksContainerSectionManager(mc, section); this.size = containerMgr.getSize(); this.sortArmorParts = config.getProperty(InvTweaksConfig.PROP_ENABLE_AUTO_EQUIP_ARMOR).equals(InvTweaksConfig.VALUE_TRUE); this.rules = config.getRules(); this.tree = config.getTree(); if (section == InvTweaksContainerSection.INVENTORY) { this.lockPriorities = config.getLockPriorities(); this.frozenSlots = config.getFrozenSlots(); this.algorithm = ALGORITHM_INVENTORY; } else { this.lockPriorities = DEFAULT_LOCK_PRIORITIES; this.frozenSlots = DEFAULT_FROZEN_SLOTS; this.algorithm = algorithm; if (algorithm != ALGORITHM_DEFAULT) { computeLineSortingRules(rowSize, algorithm == ALGORITHM_HORIZONTAL); } } this.rulePriority = new int[size]; this.keywordOrder = new int[size]; for (int i = 0; i < size; i++) { this.rulePriority[i] = -1; yq stack = containerMgr.getItemStack(i); if (stack != null) { this.keywordOrder[i] = getItemOrder(stack); } else { this.keywordOrder[i] = -1; } } } public void sort() throws TimeoutException { // Do nothing if the inventory is closed // if (!mc.hrrentScreen instanceof GuiContainer) // return; long timer = System.nanoTime(); InvTweaksContainerManager globalContainer = new InvTweaksContainerManager(mc); //// Empty hand (needed in SMP) if (isMultiplayerWorld()) { putHoldItemDown(); } if (algorithm != ALGORITHM_DEFAULT) { if (algorithm == ALGORITHM_INVENTORY) { //// Move items out of the crafting slots log.info("Handling crafting slots."); if (globalContainer.hasSection(InvTweaksContainerSection.CRAFTING_IN)) { List<wz> craftingSlots = globalContainer.getSlots(InvTweaksContainerSection.CRAFTING_IN); int emptyIndex = globalContainer.getFirstEmptyIndex(InvTweaksContainerSection.INVENTORY); if (emptyIndex != -1) { for (wz craftingSlot : craftingSlots) { if (hasStack(craftingSlot)) { globalContainer.move( InvTweaksContainerSection.CRAFTING_IN, globalContainer.getSlotIndex(getSlotNumber(craftingSlot)), InvTweaksContainerSection.INVENTORY, emptyIndex); emptyIndex = globalContainer.getFirstEmptyIndex(InvTweaksContainerSection.INVENTORY); if(emptyIndex == -1) { break; } } } } } //// Merge stacks to fill the ones in locked slots //// + Move armor parts to the armor slots log.info("Merging stacks."); for (int i = size - 1; i >= 0; i--) { yq from = containerMgr.getItemStack(i); if (from != null) { // Move armor parts - if (sortArmorParts) { - ww fromItem = getItem(from); - if (isDamageable(fromItem)) { + ww fromItem = getItem(from); + if (isDamageable(fromItem)) { + if (sortArmorParts) { if (isItemArmor(fromItem)) { po fromItemArmor = (po) fromItem; if (globalContainer.hasSection(InvTweaksContainerSection.ARMOR)) { List<wz> armorSlots = globalContainer.getSlots(InvTweaksContainerSection.ARMOR); for (wz slot : armorSlots) { if (isItemValid(slot, from) && (!hasStack(slot) || getArmorLevel(fromItemArmor) > getArmorLevel(((po) getItem(getStack(slot)))))) { globalContainer.move(InvTweaksContainerSection.INVENTORY, i, InvTweaksContainerSection.ARMOR, globalContainer.getSlotIndex(getSlotNumber(slot))); } } } } } } // Stackable objects are never damageable else { int j = 0; for (Integer lockPriority : lockPriorities) { if (lockPriority > 0) { yq to = containerMgr.getItemStack(j); if (to != null && areItemsEqual(from, to)) { move(i, j, Integer.MAX_VALUE); markAsNotMoved(j); if (containerMgr.getItemStack(i) == null) { break; } } } j++; } } } } } //// Apply rules log.info("Applying rules."); // Sorts rule by rule, themselves being already sorted by decreasing priority Iterator<InvTweaksConfigSortingRule> rulesIt = rules.iterator(); while (rulesIt.hasNext()) { InvTweaksConfigSortingRule rule = rulesIt.next(); int rulePriority = rule.getPriority(); if (log.getLevel() == InvTweaksConst.DEBUG) log.info("Rule : "+rule.getKeyword()+"("+rulePriority+")"); // For every item in the inventory for (int i = 0; i < size; i++) { yq from = containerMgr.getItemStack(i); // If the rule is strong enough to move the item and it matches the item if (hasToBeMoved(i) && lockPriorities[i] < rulePriority) { List<InvTweaksItemTreeItem> fromItems = tree.getItems( getItemID(from), getItemDamage(from)); if (tree.matches(fromItems, rule.getKeyword())) { // Test preffered slots int[] preferredSlots = rule.getPreferredSlots(); int stackToMove = i; for (int j = 0; j < preferredSlots.length; j++) { int k = preferredSlots[j]; int moveResult = move(stackToMove, k, rulePriority); if (moveResult != -1) { if (moveResult == k) { break; } else { from = containerMgr.getItemStack(moveResult); fromItems = tree.getItems(getItemID(from), getItemDamage(from)); if (!tree.matches(fromItems, rule.getKeyword())) { break; } else { stackToMove = moveResult; j = -1; } } } } } } } } //// Don't move locked stacks log.info("Locking stacks."); for (int i = 0; i < size; i++) { if (hasToBeMoved(i) && lockPriorities[i] > 0) { markAsMoved(i, 1); } } } //// Sort remaining defaultSorting(); if (log.getLevel() == InvTweaksConst.DEBUG) { timer = System.nanoTime()-timer; log.info("Sorting done in " + timer + "ns"); } } private void defaultSorting() throws TimeoutException { log.info("Default sorting."); Vector<Integer> remaining = new Vector<Integer>(), nextRemaining = new Vector<Integer>(); for (int i = 0; i < size; i++) { if (hasToBeMoved(i)) { remaining.add(i); nextRemaining.add(i); } } int iterations = 0; while (remaining.size() > 0 && iterations++ < 50) { for (int i : remaining) { if (hasToBeMoved(i)) { for (int j = 0; j < size; j++) { if (move(i, j, 1) != -1) { nextRemaining.remove((Object) j); break; } } } else { nextRemaining.remove((Object) i); } } remaining.clear(); remaining.addAll(nextRemaining); } if (iterations == 50) { log.warning("Sorting takes too long, aborting."); } } /** * If an item is in hand (= attached to the cursor), puts it down. * * @return -1 if there is no room to put the item, or the hand is not holding anything. * @throws Exception */ private int putHoldItemDown() throws TimeoutException { yq holdStack = getHoldStack(); if (holdStack != null) { // Try to find an unlocked slot first, to avoid // impacting too much the sorting for (int step = 1; step <= 2; step++) { for (int i = size - 1; i >= 0; i--) { if (containerMgr.getItemStack(i) == null && (lockPriorities[i] == 0 && !frozenSlots[i]) || step == 2) { containerMgr.leftClick(i); return i; } } } return -1; } return -1; } /** * Tries to move a stack from i to j, and swaps them if j is already * occupied but i is of greater priority (even if they are of same ID). * * @param i from slot * @param j to slot * @param priority The rule priority. Use 1 if the stack was not moved using a rule. * @return -1 if it failed, * j if the stacks were merged into one, * n if the j stack has been moved to the n slot. * @throws TimeoutException */ private int move(int i, int j, int priority) throws TimeoutException { yq from = containerMgr.getItemStack(i); yq to = containerMgr.getItemStack(j); if (from == null || frozenSlots[j] || frozenSlots[i]) { return -1; } //log.info("Moving " + i + " (" + from + ") to " + j + " (" + to + ") "); if (lockPriorities[i] <= priority) { if (i == j) { markAsMoved(i, priority); return j; } // Move to empty slot if (to == null && lockPriorities[j] <= priority && !frozenSlots[j]) { rulePriority[i] = -1; keywordOrder[i] = -1; rulePriority[j] = priority; keywordOrder[j] = getItemOrder(from); containerMgr.move(i, j); return j; } // Try to swap/merge else if (to != null) { boolean canBeSwappedOrMerged = false; // Can be swapped? if (lockPriorities[j] <= priority) { if (rulePriority[j] < priority) { canBeSwappedOrMerged = true; } else if (rulePriority[j] == priority) { if (isOrderedBefore(i, j)) { canBeSwappedOrMerged = true; } } } // Can be merged? if (!canBeSwappedOrMerged && areItemsEqual(from, to) && getStackSize(to) < getMaxStackSize(to)) { canBeSwappedOrMerged = true; } if (canBeSwappedOrMerged) { keywordOrder[j] = keywordOrder[i]; rulePriority[j] = priority; rulePriority[i] = -1; rulePriority[i] = -1; containerMgr.move(i, j); yq remains = containerMgr.getItemStack(i); if (remains != null) { int dropSlot = i; if (lockPriorities[j] > lockPriorities[i]) { for (int k = 0; k < size; k++) { if (containerMgr.getItemStack(k) == null && lockPriorities[k] == 0) { dropSlot = k; break; } } } if (dropSlot != i) { containerMgr.move(i, dropSlot); } rulePriority[dropSlot] = -1; keywordOrder[dropSlot] = getItemOrder(remains); return dropSlot; } else { return j; } } } } return -1; } private void markAsMoved(int i, int priority) { rulePriority[i] = priority; } private void markAsNotMoved(int i) { rulePriority[i] = -1; } private boolean hasToBeMoved(int slot) { return containerMgr.getItemStack(slot) != null && rulePriority[slot] == -1; } private boolean isOrderedBefore(int i, int j) { yq iStack = containerMgr.getItemStack(i), jStack = containerMgr.getItemStack(j); if (jStack == null) { return true; } else if (iStack == null || keywordOrder[i] == -1) { return false; } else { if (keywordOrder[i] == keywordOrder[j]) { // Items of same keyword orders can have different IDs, // in the case of categories defined by a range of IDs if (getItemID(iStack) == getItemID(jStack)) { if (getStackSize(iStack) == getStackSize(jStack)) { // Highest damage first for tools, else lowest damage. // No tool ordering for same ID (cannot swap directly) int damageDiff = getItemDamage(iStack) - getItemDamage(jStack); return (damageDiff < 0 && !isItemStackDamageable(iStack) || damageDiff > 0 && isItemStackDamageable(iStack)); } else { return getStackSize(iStack) > getStackSize(jStack); } } else { return getItemID(iStack) > getItemID(jStack); } } else { return keywordOrder[i] < keywordOrder[j]; } } } private int getItemOrder(yq item) { List<InvTweaksItemTreeItem> items = tree.getItems( getItemID(item), getItemDamage(item)); return (items != null && items.size() > 0) ? items.get(0).getOrder() : Integer.MAX_VALUE; } private void computeLineSortingRules(int rowSize, boolean horizontal) { rules = new Vector<InvTweaksConfigSortingRule>(); Map<InvTweaksItemTreeItem, Integer> stats = computeContainerStats(); List<InvTweaksItemTreeItem> itemOrder = new ArrayList<InvTweaksItemTreeItem>(); int distinctItems = stats.size(); int columnSize = getContainerColumnSize(rowSize); int spaceWidth; int spaceHeight; int availableSlots = size; int remainingStacks = 0; for (Integer stacks : stats.values()) { remainingStacks += stacks; } // No need to compute rules for an empty chest if (distinctItems == 0) return; // (Partially) sort stats by decreasing item stack count List<InvTweaksItemTreeItem> unorderedItems = new ArrayList<InvTweaksItemTreeItem>(stats.keySet()); boolean hasStacksToOrderFirst = true; while (hasStacksToOrderFirst) { hasStacksToOrderFirst = false; for (InvTweaksItemTreeItem item : unorderedItems) { Integer value = stats.get(item); if (value > ((horizontal) ? rowSize : columnSize) && !itemOrder.contains(item)) { hasStacksToOrderFirst = true; itemOrder.add(item); unorderedItems.remove(item); break; } } } Collections.sort(unorderedItems, Collections.reverseOrder()); itemOrder.addAll(unorderedItems); // Define space size used for each item type. if (horizontal) { spaceHeight = 1; spaceWidth = rowSize/((distinctItems+columnSize-1)/columnSize); } else { spaceWidth = 1; spaceHeight = columnSize/((distinctItems+rowSize-1)/rowSize); } char row = 'a', maxRow = (char) (row - 1 + columnSize); char column = '1', maxColumn = (char) (column - 1 + rowSize); // Create rules Iterator<InvTweaksItemTreeItem> it = itemOrder.iterator(); while (it.hasNext()) { InvTweaksItemTreeItem item = it.next(); // Adapt rule dimensions to fit the amount int thisSpaceWidth = spaceWidth, thisSpaceHeight = spaceHeight; while (stats.get(item) > thisSpaceHeight*thisSpaceWidth) { if (horizontal) { if (column + thisSpaceWidth < maxColumn) { thisSpaceWidth = maxColumn - column + 1; } else if (row + thisSpaceHeight < maxRow) { thisSpaceHeight++; } else { break; } } else { if (row + thisSpaceHeight < maxRow) { thisSpaceHeight = maxRow - row + 1; } else if (column + thisSpaceWidth < maxColumn) { thisSpaceWidth++; } else { break; } } } // Adjust line/column ends to fill empty space if (horizontal && (column + thisSpaceWidth == maxColumn)) { thisSpaceWidth++; } else if (!horizontal && row + thisSpaceHeight == maxRow) { thisSpaceHeight++; } // Create rule String constraint = row + "" + column + "-" + (char)(row - 1 + thisSpaceHeight) + (char)(column - 1 + thisSpaceWidth); if (!horizontal) { constraint += 'v'; } rules.add(new InvTweaksConfigSortingRule(tree, constraint, item.getName(), size, rowSize)); // Check if ther's still room for more rules availableSlots -= thisSpaceHeight*thisSpaceWidth; remainingStacks -= stats.get(item); if (availableSlots >= remainingStacks) { // Move origin for next rule if (horizontal) { if (column + thisSpaceWidth + spaceWidth <= maxColumn + 1) { column += thisSpaceWidth; } else { column = '1'; row += thisSpaceHeight; } } else { if (row + thisSpaceHeight + spaceHeight <= maxRow + 1) { row += thisSpaceHeight; } else { row = 'a'; column += thisSpaceWidth; } } if (row > maxRow || column > maxColumn) break; } else { break; } } String defaultRule; if (horizontal) { defaultRule = maxRow + "1-a" + maxColumn; } else { defaultRule = "a" + maxColumn + "-" + maxRow + "1v"; } rules.add(new InvTweaksConfigSortingRule(tree, defaultRule, tree.getRootCategory().getName(), size, rowSize)); } private Map<InvTweaksItemTreeItem, Integer> computeContainerStats() { Map<InvTweaksItemTreeItem, Integer> stats = new HashMap<InvTweaksItemTreeItem, Integer>(); Map<Integer, InvTweaksItemTreeItem> itemSearch = new HashMap<Integer, InvTweaksItemTreeItem>(); for (int i = 0; i < size; i++) { yq stack = containerMgr.getItemStack(i); if (stack != null) { int itemSearchKey = getItemID(stack)*100000 + ((getMaxStackSize(stack) != 1) ? getItemDamage(stack) : 0); InvTweaksItemTreeItem item = itemSearch.get(itemSearchKey); if (item == null) { item = tree.getItems(getItemID(stack), getItemDamage(stack)).get(0); itemSearch.put(itemSearchKey, item); stats.put(item, 1); } else { stats.put(item, stats.get(item) + 1); } } } return stats; } private int getContainerColumnSize(int rowSize) { return size / rowSize; } }
true
true
public void sort() throws TimeoutException { // Do nothing if the inventory is closed // if (!mc.hrrentScreen instanceof GuiContainer) // return; long timer = System.nanoTime(); InvTweaksContainerManager globalContainer = new InvTweaksContainerManager(mc); //// Empty hand (needed in SMP) if (isMultiplayerWorld()) { putHoldItemDown(); } if (algorithm != ALGORITHM_DEFAULT) { if (algorithm == ALGORITHM_INVENTORY) { //// Move items out of the crafting slots log.info("Handling crafting slots."); if (globalContainer.hasSection(InvTweaksContainerSection.CRAFTING_IN)) { List<wz> craftingSlots = globalContainer.getSlots(InvTweaksContainerSection.CRAFTING_IN); int emptyIndex = globalContainer.getFirstEmptyIndex(InvTweaksContainerSection.INVENTORY); if (emptyIndex != -1) { for (wz craftingSlot : craftingSlots) { if (hasStack(craftingSlot)) { globalContainer.move( InvTweaksContainerSection.CRAFTING_IN, globalContainer.getSlotIndex(getSlotNumber(craftingSlot)), InvTweaksContainerSection.INVENTORY, emptyIndex); emptyIndex = globalContainer.getFirstEmptyIndex(InvTweaksContainerSection.INVENTORY); if(emptyIndex == -1) { break; } } } } } //// Merge stacks to fill the ones in locked slots //// + Move armor parts to the armor slots log.info("Merging stacks."); for (int i = size - 1; i >= 0; i--) { yq from = containerMgr.getItemStack(i); if (from != null) { // Move armor parts if (sortArmorParts) { ww fromItem = getItem(from); if (isDamageable(fromItem)) { if (isItemArmor(fromItem)) { po fromItemArmor = (po) fromItem; if (globalContainer.hasSection(InvTweaksContainerSection.ARMOR)) { List<wz> armorSlots = globalContainer.getSlots(InvTweaksContainerSection.ARMOR); for (wz slot : armorSlots) { if (isItemValid(slot, from) && (!hasStack(slot) || getArmorLevel(fromItemArmor) > getArmorLevel(((po) getItem(getStack(slot)))))) { globalContainer.move(InvTweaksContainerSection.INVENTORY, i, InvTweaksContainerSection.ARMOR, globalContainer.getSlotIndex(getSlotNumber(slot))); } } } } } } // Stackable objects are never damageable else { int j = 0; for (Integer lockPriority : lockPriorities) { if (lockPriority > 0) { yq to = containerMgr.getItemStack(j); if (to != null && areItemsEqual(from, to)) { move(i, j, Integer.MAX_VALUE); markAsNotMoved(j); if (containerMgr.getItemStack(i) == null) { break; } } } j++; } } } } } //// Apply rules log.info("Applying rules."); // Sorts rule by rule, themselves being already sorted by decreasing priority Iterator<InvTweaksConfigSortingRule> rulesIt = rules.iterator(); while (rulesIt.hasNext()) { InvTweaksConfigSortingRule rule = rulesIt.next(); int rulePriority = rule.getPriority(); if (log.getLevel() == InvTweaksConst.DEBUG) log.info("Rule : "+rule.getKeyword()+"("+rulePriority+")"); // For every item in the inventory for (int i = 0; i < size; i++) { yq from = containerMgr.getItemStack(i); // If the rule is strong enough to move the item and it matches the item if (hasToBeMoved(i) && lockPriorities[i] < rulePriority) { List<InvTweaksItemTreeItem> fromItems = tree.getItems( getItemID(from), getItemDamage(from)); if (tree.matches(fromItems, rule.getKeyword())) { // Test preffered slots int[] preferredSlots = rule.getPreferredSlots(); int stackToMove = i; for (int j = 0; j < preferredSlots.length; j++) { int k = preferredSlots[j]; int moveResult = move(stackToMove, k, rulePriority); if (moveResult != -1) { if (moveResult == k) { break; } else { from = containerMgr.getItemStack(moveResult); fromItems = tree.getItems(getItemID(from), getItemDamage(from)); if (!tree.matches(fromItems, rule.getKeyword())) { break; } else { stackToMove = moveResult; j = -1; } } } } } } } } //// Don't move locked stacks log.info("Locking stacks."); for (int i = 0; i < size; i++) { if (hasToBeMoved(i) && lockPriorities[i] > 0) { markAsMoved(i, 1); } } } //// Sort remaining defaultSorting(); if (log.getLevel() == InvTweaksConst.DEBUG) { timer = System.nanoTime()-timer; log.info("Sorting done in " + timer + "ns"); } }
public void sort() throws TimeoutException { // Do nothing if the inventory is closed // if (!mc.hrrentScreen instanceof GuiContainer) // return; long timer = System.nanoTime(); InvTweaksContainerManager globalContainer = new InvTweaksContainerManager(mc); //// Empty hand (needed in SMP) if (isMultiplayerWorld()) { putHoldItemDown(); } if (algorithm != ALGORITHM_DEFAULT) { if (algorithm == ALGORITHM_INVENTORY) { //// Move items out of the crafting slots log.info("Handling crafting slots."); if (globalContainer.hasSection(InvTweaksContainerSection.CRAFTING_IN)) { List<wz> craftingSlots = globalContainer.getSlots(InvTweaksContainerSection.CRAFTING_IN); int emptyIndex = globalContainer.getFirstEmptyIndex(InvTweaksContainerSection.INVENTORY); if (emptyIndex != -1) { for (wz craftingSlot : craftingSlots) { if (hasStack(craftingSlot)) { globalContainer.move( InvTweaksContainerSection.CRAFTING_IN, globalContainer.getSlotIndex(getSlotNumber(craftingSlot)), InvTweaksContainerSection.INVENTORY, emptyIndex); emptyIndex = globalContainer.getFirstEmptyIndex(InvTweaksContainerSection.INVENTORY); if(emptyIndex == -1) { break; } } } } } //// Merge stacks to fill the ones in locked slots //// + Move armor parts to the armor slots log.info("Merging stacks."); for (int i = size - 1; i >= 0; i--) { yq from = containerMgr.getItemStack(i); if (from != null) { // Move armor parts ww fromItem = getItem(from); if (isDamageable(fromItem)) { if (sortArmorParts) { if (isItemArmor(fromItem)) { po fromItemArmor = (po) fromItem; if (globalContainer.hasSection(InvTweaksContainerSection.ARMOR)) { List<wz> armorSlots = globalContainer.getSlots(InvTweaksContainerSection.ARMOR); for (wz slot : armorSlots) { if (isItemValid(slot, from) && (!hasStack(slot) || getArmorLevel(fromItemArmor) > getArmorLevel(((po) getItem(getStack(slot)))))) { globalContainer.move(InvTweaksContainerSection.INVENTORY, i, InvTweaksContainerSection.ARMOR, globalContainer.getSlotIndex(getSlotNumber(slot))); } } } } } } // Stackable objects are never damageable else { int j = 0; for (Integer lockPriority : lockPriorities) { if (lockPriority > 0) { yq to = containerMgr.getItemStack(j); if (to != null && areItemsEqual(from, to)) { move(i, j, Integer.MAX_VALUE); markAsNotMoved(j); if (containerMgr.getItemStack(i) == null) { break; } } } j++; } } } } } //// Apply rules log.info("Applying rules."); // Sorts rule by rule, themselves being already sorted by decreasing priority Iterator<InvTweaksConfigSortingRule> rulesIt = rules.iterator(); while (rulesIt.hasNext()) { InvTweaksConfigSortingRule rule = rulesIt.next(); int rulePriority = rule.getPriority(); if (log.getLevel() == InvTweaksConst.DEBUG) log.info("Rule : "+rule.getKeyword()+"("+rulePriority+")"); // For every item in the inventory for (int i = 0; i < size; i++) { yq from = containerMgr.getItemStack(i); // If the rule is strong enough to move the item and it matches the item if (hasToBeMoved(i) && lockPriorities[i] < rulePriority) { List<InvTweaksItemTreeItem> fromItems = tree.getItems( getItemID(from), getItemDamage(from)); if (tree.matches(fromItems, rule.getKeyword())) { // Test preffered slots int[] preferredSlots = rule.getPreferredSlots(); int stackToMove = i; for (int j = 0; j < preferredSlots.length; j++) { int k = preferredSlots[j]; int moveResult = move(stackToMove, k, rulePriority); if (moveResult != -1) { if (moveResult == k) { break; } else { from = containerMgr.getItemStack(moveResult); fromItems = tree.getItems(getItemID(from), getItemDamage(from)); if (!tree.matches(fromItems, rule.getKeyword())) { break; } else { stackToMove = moveResult; j = -1; } } } } } } } } //// Don't move locked stacks log.info("Locking stacks."); for (int i = 0; i < size; i++) { if (hasToBeMoved(i) && lockPriorities[i] > 0) { markAsMoved(i, 1); } } } //// Sort remaining defaultSorting(); if (log.getLevel() == InvTweaksConst.DEBUG) { timer = System.nanoTime()-timer; log.info("Sorting done in " + timer + "ns"); } }
diff --git a/Essentials/src/com/earth2me/essentials/EssentialsConf.java b/Essentials/src/com/earth2me/essentials/EssentialsConf.java index 616f39a6..124dc6fd 100644 --- a/Essentials/src/com/earth2me/essentials/EssentialsConf.java +++ b/Essentials/src/com/earth2me/essentials/EssentialsConf.java @@ -1,120 +1,121 @@ package com.earth2me.essentials; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.HashMap; import java.util.logging.Level; import java.util.logging.Logger; import org.bukkit.util.config.Configuration; public class EssentialsConf extends Configuration { private static final Logger logger = Logger.getLogger("Minecraft"); private File configFile; private String templateName = null; private Class<?> resourceClass = EssentialsConf.class; public EssentialsConf(File configFile) { super(configFile); this.configFile = configFile; if (this.root == null) { this.root = new HashMap<String, Object>(); } } @Override public void load() { configFile = configFile.getAbsoluteFile(); if (!configFile.getParentFile().exists()) { configFile.getParentFile().mkdirs(); } if (!configFile.exists()) { if (templateName != null) { logger.log(Level.INFO, "Creating config from template: " + configFile.toString()); createFromTemplate(); } else { try { logger.log(Level.INFO, "Creating empty config: " + configFile.toString()); configFile.createNewFile(); } catch (IOException ex) { logger.log(Level.SEVERE, "Failed to create config " + configFile.toString(), ex); } } } super.load(); if (this.root == null) { this.root = new HashMap<String, Object>(); } } private void createFromTemplate() { OutputStream ostr = null; try { InputStream istr = resourceClass.getResourceAsStream(templateName); if (istr == null) { logger.log(Level.SEVERE, "Could not find template " + templateName); return; } ostr = new FileOutputStream(configFile); byte[] buffer = new byte[1024]; int length = 0; length = istr.read(buffer); while (length > 0) { ostr.write(buffer, 0, length); length = istr.read(buffer); } - ostr.close(); istr.close(); } catch (IOException ex) { logger.log(Level.SEVERE, "Failed to write config " + configFile.toString(), ex); return; } finally { try { - ostr.close(); + if (ostr != null) { + ostr.close(); + } } catch (IOException ex) { logger.log(Level.SEVERE, "Failed to close config " + configFile.toString(), ex); return; } } } public void setTemplateName(String templateName) { this.templateName = templateName; } public File getFile() { return configFile; } public void setTemplateName(String templateName, Class<?> resClass) { this.templateName = templateName; this.resourceClass = resClass; } }
false
true
private void createFromTemplate() { OutputStream ostr = null; try { InputStream istr = resourceClass.getResourceAsStream(templateName); if (istr == null) { logger.log(Level.SEVERE, "Could not find template " + templateName); return; } ostr = new FileOutputStream(configFile); byte[] buffer = new byte[1024]; int length = 0; length = istr.read(buffer); while (length > 0) { ostr.write(buffer, 0, length); length = istr.read(buffer); } ostr.close(); istr.close(); } catch (IOException ex) { logger.log(Level.SEVERE, "Failed to write config " + configFile.toString(), ex); return; } finally { try { ostr.close(); } catch (IOException ex) { logger.log(Level.SEVERE, "Failed to close config " + configFile.toString(), ex); return; } } }
private void createFromTemplate() { OutputStream ostr = null; try { InputStream istr = resourceClass.getResourceAsStream(templateName); if (istr == null) { logger.log(Level.SEVERE, "Could not find template " + templateName); return; } ostr = new FileOutputStream(configFile); byte[] buffer = new byte[1024]; int length = 0; length = istr.read(buffer); while (length > 0) { ostr.write(buffer, 0, length); length = istr.read(buffer); } istr.close(); } catch (IOException ex) { logger.log(Level.SEVERE, "Failed to write config " + configFile.toString(), ex); return; } finally { try { if (ostr != null) { ostr.close(); } } catch (IOException ex) { logger.log(Level.SEVERE, "Failed to close config " + configFile.toString(), ex); return; } } }
diff --git a/x10.compiler/src/x10/types/X10TypeMixin.java b/x10.compiler/src/x10/types/X10TypeMixin.java index 7b2634a6e..e95d4f401 100644 --- a/x10.compiler/src/x10/types/X10TypeMixin.java +++ b/x10.compiler/src/x10/types/X10TypeMixin.java @@ -1,1761 +1,1765 @@ /* * This file is part of the X10 project (http://x10-lang.org). * * This file is licensed to You under the Eclipse Public License (EPL); * You may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.opensource.org/licenses/eclipse-1.0.php * * (C) Copyright IBM Corporation 2006-2010. */ package x10.types; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import polyglot.ast.Binary; import polyglot.ast.Cast; import polyglot.ast.Expr; import polyglot.ast.Field; import polyglot.ast.Lit; import polyglot.ast.NodeFactory; import polyglot.ast.Receiver; import polyglot.ast.Special; import polyglot.ast.Unary; import polyglot.ast.Unary_c; import polyglot.ast.Variable; import polyglot.ast.FloatLit; import polyglot.ast.TypeNode; import polyglot.ast.IntLit; import polyglot.ast.Binary.Operator; import polyglot.types.ClassDef; import polyglot.types.ClassType; import polyglot.types.ConstructorInstance; import polyglot.types.Context; import polyglot.types.FieldInstance; import polyglot.types.Flags; import polyglot.types.LazyRef_c; import polyglot.types.MemberInstance; import polyglot.types.MethodInstance; import polyglot.types.Name; import polyglot.types.ProcedureInstance; import polyglot.types.Ref; import polyglot.types.SemanticException; import polyglot.types.Type; import polyglot.types.TypeSystem; import polyglot.types.Types; import polyglot.types.UnknownType; import polyglot.types.QName; import polyglot.types.FieldDef; import polyglot.types.StructType; import polyglot.util.InternalCompilerError; import polyglot.util.Position; import polyglot.util.ErrorInfo; import polyglot.visit.ContextVisitor; import polyglot.frontend.Job; import x10.ast.Here; import x10.ast.ParExpr; import x10.ast.SemanticError; import x10.ast.SubtypeTest; import x10.ast.HasZeroTest; import x10.constraint.XFailure; import x10.constraint.XLit; import x10.constraint.XNameWrapper; import x10.constraint.XVar; import x10.constraint.XTerm; import x10.constraint.XTerms; import x10.errors.Errors; import x10.types.constraints.CConstraint; import x10.types.constraints.TypeConstraint; import x10.types.constraints.XConstrainedTerm; import x10.types.constraints.SubtypeConstraint; import x10.types.matcher.Matcher; /** * Utilities for dealing with X10 dependent types. * @author nystrom */ public class X10TypeMixin { public static X10FieldInstance getProperty(Type t, Name propName) { TypeSystem xts = (TypeSystem) t.typeSystem(); try { Context c = xts.emptyContext(); X10FieldInstance fi = (X10FieldInstance) xts.findField(t, xts.FieldMatcher(t, propName, c)); if (fi != null && fi.isProperty()) { return fi; } } catch (SemanticException e) { // ignore } return null; } /** * Return the type Array[type]{self.region.rank==1, self.size==size}. * @param type * @param pos * @return */ public static Type makeArrayRailOf(Type type, int size, Position pos) { TypeSystem ts = (TypeSystem) type.typeSystem(); Type r = ts.Array(); Type t = (X10ClassType) X10TypeMixin.instantiate(r, type); CConstraint c = new CConstraint(); FieldInstance sizeField = ((X10ClassType) t).fieldNamed(Name.make("size")); if (sizeField == null) throw new InternalCompilerError("Could not find size field of " + t, pos); FieldInstance regionField = ((X10ClassType) t).fieldNamed(Name.make("region")); if (regionField == null) throw new InternalCompilerError("Could not find region field of " + t, pos); FieldInstance rankField = ((X10ClassType) ts.Region()).fieldNamed(Name.make("rank")); if (rankField == null) throw new InternalCompilerError("Could not find rank field of " + ts.Region(), pos); FieldInstance rectField = ((X10ClassType) ts.Region()).fieldNamed(Name.make("rect")); if (rectField == null) throw new InternalCompilerError("Could not find rect field of " + ts.Region(), pos); FieldInstance zeroBasedField = ((X10ClassType) ts.Region()).fieldNamed(Name.make("zeroBased")); if (zeroBasedField == null) throw new InternalCompilerError("Could not find zeroBased field of " + ts.Region(), pos); try { XVar selfSize = ts.xtypeTranslator().trans(c, c.self(), sizeField); XLit sizeLiteral = ts.xtypeTranslator().trans(size); c.addBinding(selfSize, sizeLiteral); XVar selfRegion = ts.xtypeTranslator().trans(c, c.self(), regionField); XVar selfRegionRank = ts.xtypeTranslator().trans(c, selfRegion, rankField); XLit rankLiteral = XTerms.makeLit(1); c.addBinding(selfRegionRank, rankLiteral); XVar selfRegionRect = ts.xtypeTranslator().trans(c, selfRegion, rectField); XLit trueLiteral = XTerms.makeLit(true); c.addBinding(selfRegionRect, trueLiteral); XVar selfRegionZeroBased = ts.xtypeTranslator().trans(c, selfRegion, zeroBasedField); c.addBinding(selfRegionZeroBased, trueLiteral); //c.toString(); t = X10TypeMixin.xclause(t, c); } catch (XFailure z) { throw new InternalCompilerError("Could not create Array[T]{self.region.rank==1,self.size==size}"); } return t; } /** * Return the type Array[type]{self.region.rank==1,self.region.rect==true,self.region.zeroBased==true}. * @param type * @param pos * @return */ public static Type makeArrayRailOf(Type type, Position pos) { TypeSystem ts = (TypeSystem) type.typeSystem(); Type r = ts.Array(); Type t = (X10ClassType) X10TypeMixin.instantiate(r, type); CConstraint c = new CConstraint(); FieldInstance regionField = ((X10ClassType) t).fieldNamed(Name.make("region")); if (regionField == null) throw new InternalCompilerError("Could not find region field of " + t, pos); FieldInstance rankField = ((X10ClassType) ts.Region()).fieldNamed(Name.make("rank")); if (rankField == null) throw new InternalCompilerError("Could not find rank field of " + ts.Region(), pos); FieldInstance rectField = ((X10ClassType) ts.Region()).fieldNamed(Name.make("rect")); if (rectField == null) throw new InternalCompilerError("Could not find rectField field of " + ts.Region(), pos); FieldInstance zeroBasedField = ((X10ClassType) ts.Region()).fieldNamed(Name.make("zeroBased")); if (zeroBasedField == null) throw new InternalCompilerError("Could not find zeroBased field of " + ts.Region(), pos); try { XVar selfRegion = ts.xtypeTranslator().trans(c, c.self(), regionField); XVar selfRegionRank = ts.xtypeTranslator().trans(c, selfRegion, rankField); XVar selfRegionRect = ts.xtypeTranslator().trans(c, selfRegion, rectField); XVar selfRegionZeroBased = ts.xtypeTranslator().trans(c, selfRegion, zeroBasedField); XLit rankLiteral = XTerms.makeLit(1); c.addBinding(selfRegionRank, rankLiteral); c.addBinding(selfRegionRect, XTerms.TRUE); c.addBinding(selfRegionZeroBased, XTerms.TRUE); c.toString(); t = X10TypeMixin.xclause(t, c); } catch (XFailure z) { throw new InternalCompilerError("Could not create Array[T]{self.region.rank==1,self.region.rect==true,self.region.zeroBased==true}"); } return t; } public static Type typeArg(Type t, int i) { if (t instanceof X10ParsedClassType) { X10ParsedClassType ct = (X10ParsedClassType) t; return ct.typeArguments().get(i); } return typeArg(X10TypeMixin.baseType(t), i); } public static Type instantiate(Type t, Type... typeArg) { if (t instanceof X10ParsedClassType) { X10ParsedClassType ct = (X10ParsedClassType) t; return ct.typeArguments(Arrays.asList(typeArg)); } else { throw new InternalCompilerError("Cannot instantiate non-class " + t); } } public static Type instantiate(Type t, Ref<? extends Type> typeArg) { // TODO: should not deref now, since could be called by class loader return instantiate(t, Types.get(typeArg)); } public static TypeConstraint parameterBounds(Type t) { if (t instanceof ParameterType) { } else if (t instanceof ConstrainedType) { ConstrainedType ct = (ConstrainedType) t; TypeConstraint bounds = parameterBounds(Types.get(ct.baseType())); if (bounds == null) assert bounds != null; return bounds; } else if (t instanceof X10ClassType) { X10ClassType ct = (X10ClassType) t; TypeConstraint c = Types.get(ct.x10Def().typeBounds()); if (c != null) return TypeParamSubst.reinstantiateTypeConstraint(ct, c); } else if (t instanceof MacroType) { MacroType mt = (MacroType) t; TypeConstraint c = parameterBounds(mt.definedType()); TypeConstraint w = mt.typeGuard(); if (w != null) { c = (TypeConstraint) c.copy(); c.addIn(w); } return c; } return new TypeConstraint(); } public static CConstraint realX(Type t) { if (t instanceof ParameterType) { return new CConstraint(); } else if (t instanceof ConstrainedType) { return ((ConstrainedType) t).getRealXClause(); } else if (t instanceof X10ClassType) { X10ClassType ct = (X10ClassType) t; CConstraint c = ct.x10Def().getRootClause(); return TypeParamSubst.reinstantiateConstraint(ct, c); } else if (t instanceof MacroType) { MacroType mt = (MacroType) t; CConstraint c = realX(mt.definedType()); CConstraint w = mt.guard(); if (w != null) { c = c.copy(); try { c.addIn(w); } catch (XFailure e) { c.setInconsistent(); } } return c; } return new CConstraint(); } /** * Return the constraint c entailed by the assertion v is of type t. * @param v * @param t * @return */ public static CConstraint xclause(XVar v, Type t) { CConstraint c = xclause(t); try { return c.substitute(v, c.self()); } catch (XFailure z) { CConstraint c1 = new CConstraint(); c1.setInconsistent(); return c1; } } /** * Returns a copy of t's constraint, if it has one, null otherwise. * @param t * @return */ public static CConstraint xclause(Type t) { if (t instanceof AnnotatedType) { AnnotatedType at = (AnnotatedType) t; return xclause(at.baseType()); } if (t instanceof MacroType) { MacroType mt = (MacroType) t; return xclause(mt.definedType()); } if (t instanceof ConstrainedType) { ConstrainedType ct = (ConstrainedType) t; return Types.get(ct.constraint()).copy(); } if (t instanceof X10ParsedClassType) { X10ParsedClassType ct = (X10ParsedClassType) t; return ct.getXClause().copy(); } return null; } /** * If x is a class type, return struct x. Else return x. * @param x * @return */ public static Type makeX10Struct(Type t) { if (! (t instanceof X10Struct)) return t; X10Struct type = (X10Struct) t; return type.makeX10Struct(); } public static Type processFlags(Flags f, Type x) { if (f==null || !(f instanceof X10Flags)) return x; X10Flags xf = (X10Flags) f; if (xf.isStruct()) { x = ((X10Struct) x).makeX10Struct(); } return x; } public static void checkVariance(TypeNode t, ParameterType.Variance variance, Job errs) { checkVariance(t.type(),variance,errs,t.position()); } public static void checkVariance(Type t, ParameterType.Variance variance, Job errs, Position pos) { Type base = null; if (t instanceof ParameterType) { ParameterType pt = (ParameterType) t; ParameterType.Variance var = pt.getVariance(); if (var==variance || var==ParameterType.Variance.INVARIANT) { // ok } else { Errors.issue(errs, new SemanticException("Illegal variance! Type parameter has variance "+var+" but it is used in a "+variance+" position.",pos)); // todo: t.position() is incorrect (see XTENLANG-1439) } } else if (t instanceof X10ParsedClassType_c) { X10ParsedClassType_c pt = (X10ParsedClassType_c) t; List<Type> args = pt.typeArguments(); if (args == null) args = Collections.<Type>emptyList(); X10ClassDef def = (X10ClassDef) pt.def(); final List<ParameterType.Variance> variances = def.variances(); for (int i=0; i<Math.min(args.size(), variances.size()); i++) { Type arg = args.get(i); ParameterType.Variance var = variances.get(i); checkVariance(arg, variance.mult(var), errs, pos); } } else if (t instanceof ConstrainedType_c) { ConstrainedType ct = (ConstrainedType) t; base = Types.get(ct.baseType()); } else if (t instanceof AnnotatedType_c) { AnnotatedType_c at = (AnnotatedType_c) t; base = at.baseType(); } else if (t instanceof MacroType_c) { MacroType mt = (MacroType) t; base = mt.definedType(); } if (base!=null) checkVariance(base,variance,errs,pos); } public static Type baseType(Type t) { if (t instanceof AnnotatedType) { AnnotatedType at = (AnnotatedType) t; return baseType(at.baseType()); } if (t instanceof MacroType) { MacroType mt = (MacroType) t; return baseType(mt.definedType()); } if (t instanceof ConstrainedType) { ConstrainedType ct = (ConstrainedType) t; return baseType(Types.get(ct.baseType())); } return t; } public static Type erasedType(Type t) { if (t instanceof AnnotatedType) { AnnotatedType at = (AnnotatedType) t; return erasedType(at.baseType()); } if (t instanceof MacroType) { MacroType mt = (MacroType) t; return erasedType(mt.definedType()); } if (t instanceof ConstrainedType) { ConstrainedType ct = (ConstrainedType) t; return erasedType(baseType(Types.get(ct.baseType()))); } if (t instanceof ConstrainedType) { ConstrainedType ct = (ConstrainedType) t; return erasedType(baseType(Types.get(ct.baseType()))); } return t; } public static Type stripConstraints(Type t) { TypeSystem ts = (TypeSystem) t.typeSystem(); t = ts.expandMacros(t); t = X10TypeMixin.baseType(t); if (t instanceof X10ClassType) { X10ClassType ct = (X10ClassType) t; if (ct.typeArguments() == null) return ct; List<Type> types = new ArrayList<Type>(ct.typeArguments().size()); for (Type ti : ct.typeArguments()) { Type ti2 = stripConstraints(ti); types.add(ti2); } return ct.typeArguments(types); } return t; } public static Type xclause(Type t, CConstraint c) { if (t == null) return null; if (c == null || c.valid()) { return baseType(t); } return xclause(Types.ref(t), Types.ref(c)); } public static Type constrainedType(Type base, CConstraint c) { return new ConstrainedType_c((TypeSystem) base.typeSystem(), base.position(), Types.ref(base), Types.ref(c)); } // vj: 08/11/09 -- have to recursively walk the // type parameters and add the constraint to them. public static Type xclause(final Ref<? extends Type> t, final Ref<CConstraint> c) { if (t == null) { return null; } if (t.known() && c != null && c.known()) { Type tx = Types.get(t); TypeSystem ts = (TypeSystem) tx.typeSystem(); tx = ts.expandMacros(tx); CConstraint oldc = X10TypeMixin.xclause(tx); CConstraint newc = Types.get(c); if (newc == null) return tx; if (oldc == null) { return new ConstrainedType_c(ts, tx.position(), t, c); } else { newc = newc.copy(); try { newc.addIn(oldc); } catch (XFailure e) { newc.setInconsistent(); } assert tx != null; return new ConstrainedType_c(ts, tx.position(), Types.ref(X10TypeMixin.baseType(tx)), Types.ref(newc)); } } final LazyRef_c<Type> tref = new LazyRef_c<Type>(null); tref.setResolver(new Runnable() { public void run() { Type oldt = X10TypeMixin.baseType(Types.get(t)); tref.update(oldt); } }); final LazyRef_c<CConstraint> cref = new LazyRef_c<CConstraint>(null); cref.setResolver(new Runnable() { public void run() { CConstraint oldc = X10TypeMixin.xclause(Types.get(t)); if (oldc != null) { CConstraint newc = Types.get(c); if (newc != null) { newc = newc.copy(); try { newc.addIn(oldc); } catch (XFailure e) { newc.setInconsistent(); } cref.update(newc); } else { cref.update(oldc); } } else { cref.update(oldc); } } }); Type tx = t.getCached(); assert tx != null; return new ConstrainedType_c((TypeSystem) tx.typeSystem(), tx.position(), t.known()? t: tref, cref); } public static boolean isConstrained(Type t) { if (t instanceof AnnotatedType) { AnnotatedType at = (AnnotatedType) t; return isConstrained(at.baseType()); } if (t instanceof MacroType) { MacroType mt = (MacroType) t; return isConstrained(mt.definedType()); } if (t instanceof ConstrainedType) { return true; } return false; } public static boolean isX10Struct(Type t) { if (! (t instanceof X10Struct)) return false; return ((X10Struct) t).isX10Struct(); } public static boolean isClass(Type t) { return ! isX10Struct(t); } public static Type superClass(Type t) { t = baseType(t); assert t instanceof ClassType; return ((ClassType) t).superClass(); } public static Type addBinding(Type t, XTerm t1, XTerm t2) throws XFailure { //assert (! (t instanceof UnknownType)); CConstraint c = xclause(t); c = c == null ? new CConstraint() :c.copy(); c.addBinding(t1, t2); return xclause(X10TypeMixin.baseType(t), c); } public static Type instantiateSelf(XTerm t, Type type) { assert (! (t instanceof UnknownType)); CConstraint c = xclause(type); if (! ((c==null) || c.valid())) { CConstraint env = c = c.copy().instantiateSelf(t); if (! c.consistent()) { throw new InternalCompilerError("X10TypeMixin: Instantiating self on " + type + " with " + t + " is inconsistent."); } return xclause(X10TypeMixin.baseType(type), c); } return type; } public static Type addBinding(Type t, XTerm t1, XConstrainedTerm t2) { assert (! (t instanceof UnknownType)); try { CConstraint c = xclause(t); c = c == null ? new CConstraint() :c.copy(); c.addBinding(t1, t2); return xclause(X10TypeMixin.baseType(t), c); } catch (XFailure f) { throw new InternalCompilerError("Cannot bind " + t1 + " to " + t2 + ".", f); } } public static Type addSelfBinding(Type t, XTerm t1) throws XFailure { assert (! (t instanceof UnknownType)); CConstraint c = xclause(t); c = c == null ? new CConstraint() :c.copy(); c.addSelfBinding(t1); return xclause(X10TypeMixin.baseType(t), c); } public static Type addDisBinding(Type t, XTerm t1, XTerm t2) { assert (! (t instanceof UnknownType)); try { CConstraint c = xclause(t); c = c == null ? new CConstraint() :c.copy(); c.addDisBinding(t1, t2); return xclause(X10TypeMixin.baseType(t), c); } catch (XFailure f) { throw new InternalCompilerError("Cannot bind " + t1 + " to " + t2 + ".", f); } } static CConstraint tryAddingConstraint(Type t, CConstraint xc) throws XFailure { CConstraint c = xclause(t); c = c == null ? new CConstraint() :c.copy(); c.addIn(xc); return c; } public static Type addConstraint(Type t, CConstraint xc) { try { CConstraint c = tryAddingConstraint(t, xc); return xclause(X10TypeMixin.baseType(t), c); } catch (XFailure f) { throw new InternalCompilerError("X10TypeMixin: Cannot add " + xc + "to " + t + ".", f); } } public static Type addTerm(Type t, XTerm term) { try { CConstraint c = xclause(t); c = c == null ? new CConstraint() :c.copy(); c.addTerm(term); return xclause(X10TypeMixin.baseType(t), c); } catch (XFailure f) { throw new InternalCompilerError("Cannot add term " + term + " to " + t + ".", f); } } public static boolean consistent(Type t) { CConstraint c = xclause(t); if (c == null) return true; return c.consistent(); } public static void setInconsistent(Type t) { if (t instanceof AnnotatedType) { AnnotatedType at = (AnnotatedType) t; setInconsistent(at.baseType()); } if (t instanceof MacroType) { MacroType mt = (MacroType) t; setInconsistent(mt.definedType()); } if (t instanceof ConstrainedType) { ConstrainedType ct = (ConstrainedType) t; CConstraint c = Types.get(ct.constraint()); c.setInconsistent(); return; } } public static XVar selfVar(Type thisType) { CConstraint c = xclause(thisType); // Should this be realX(thisType) ??? - Bowen return selfVar(c); } public static XVar selfVar(CConstraint c) { if (c == null) return null; return c.self(); } public static XVar selfVarBinding(Type thisType) { CConstraint c = xclause(thisType); // Should this be realX(thisType) ??? - Bowen return selfVarBinding(c); } public static XVar selfVarBinding(CConstraint c) { if (c == null) return null; return c.bindingForVar(c.self()); } public static XTerm selfBinding(Type thisType) { CConstraint c = realX(thisType); return selfBinding(c); } public static XTerm selfBinding(CConstraint c) { if (c == null) return null; return c.bindingForVar(c.self()); } public static Type setSelfVar(Type t, XVar v) throws SemanticException { CConstraint c = xclause(t); if (c == null) { c = new CConstraint(); } else { c = c.copy(); } try { c.addSelfBinding(v); } catch (XFailure e) { throw new SemanticException(e.getMessage(), t.position()); } return xclause(X10TypeMixin.baseType(t), c); } public static Type setThisVar(Type t, XVar v) throws SemanticException { CConstraint c = xclause(t); if (c == null) { c = new CConstraint(); } else { c = c.copy(); } c.setThisVar(v); return xclause(X10TypeMixin.baseType(t), c); } /** * If the type constrains the given property to * a particular value, then return that value, otherwise * return null * @param name -- the name of the property. * @return null if there is no value associated with the property in the type. */ public static XTerm propVal(Type t, Name name) { CConstraint c = xclause(t); if (c == null) return null; return c.bindingForSelfField(new XNameWrapper<Name>(name)); } // Helper functions for the various type tests // At the top of test foo(o), put: // if (Mixin.isConstrained(this) || Mixin.isParametric(this) || Mixin.isConstrained(o) || Mixin.isParametric(o)) // return Mixin.foo(this, o) // ... public static boolean eitherIsDependent(Type t1, Type t2) { return isDependentOrDependentPath(t1) || isDependentOrDependentPath(t2); } public static boolean isDependentOrDependentPath(Type t) { return isConstrained(t); } public static X10PrimitiveType promote(Unary.Operator op, X10PrimitiveType t) throws SemanticException { TypeSystem ts = (TypeSystem) t.typeSystem(); X10PrimitiveType pt = (X10PrimitiveType) ts.promote(t); return (X10PrimitiveType) xclause(X10TypeMixin.baseType(pt), promoteClause(ts, op, xclause(t))); } public static CConstraint promoteClause(TypeSystem ts, polyglot.ast.Unary.Operator op, CConstraint c) { if (c == null) return null; return ts.xtypeTranslator().unaryOp(op, c); } public static X10PrimitiveType promote(Binary.Operator op, X10PrimitiveType t1, X10PrimitiveType t2) throws SemanticException { TypeSystem ts = (TypeSystem) t1.typeSystem(); X10PrimitiveType pt = (X10PrimitiveType) ts.promote(t1, t2); return (X10PrimitiveType) xclause(X10TypeMixin.baseType(pt), promoteClause(ts, op, xclause(t1), xclause(t2))); } public static CConstraint promoteClause(TypeSystem ts, Operator op, CConstraint c1, CConstraint c2) { if (c1 == null || c2 == null) return null; return ts.xtypeTranslator().binaryOp(op, c1, c2); } public static Type getParameterType(Type theType, int i) { Type b = baseType(theType); if (b instanceof X10ClassType) { X10ClassType ct = (X10ClassType) b; if (ct.typeArguments() != null && i < ct.typeArguments().size()) { return ct.typeArguments().get(i); } } return null; } public static List<FieldInstance> properties(Type t) { t = baseType(t); if (t instanceof X10ClassType) { X10ClassType ct = (X10ClassType) t; return ct.properties(); } return Collections.<FieldInstance>emptyList(); } /** * Returns the var that is thisvar of all the terms in {t1,t2} that have a thisvar. * If none do, return null. Else throw a SemanticError. * @param t1 * @param t2 * @return * @throws SemanticError */ public static XVar getThisVar(Type t1, Type t2) throws XFailure { XVar thisVar = t1 == null ? null : ((X10ThisVar) t1).thisVar(); if (thisVar == null) return t2==null ? null : ((X10ThisVar) t2).thisVar(); if (t2 != null && ! thisVar.equals(((X10ThisVar) t2).thisVar())) throw new XFailure("Inconsistent this vars " + thisVar + " and " + ((X10ThisVar) t2).thisVar()); return thisVar; } public static XVar getThisVar(CConstraint t1, CConstraint t2) throws XFailure { XVar thisVar = t1 == null ? null : t1.thisVar(); if (thisVar == null) return t2==null ? null : t2.thisVar(); if (t2 != null && ! thisVar.equals( t2.thisVar())) throw new XFailure("Inconsistent this vars " + thisVar + " and " + ((X10ThisVar) t2).thisVar()); return thisVar; } public static XVar getThisVar(List<Type> typeArgs) throws XFailure { XVar thisVar = null; if (typeArgs != null) for (Type type : typeArgs) { if (type instanceof X10ThisVar) { X10ThisVar xtype = (X10ThisVar)type; XVar o = xtype.thisVar(); if (thisVar == null) { thisVar = o; } else { if (o != null && !thisVar.equals(o)) throw new XFailure("Inconsistent thisVars in " + typeArgs + "; cannot instantiate "); } } } return thisVar; } public static XTerm getRegionLowerBound(Type type) { return null; } public static XTerm getRegionUpperBound(Type type) { return null; } public static boolean hasVar(Type t, XVar x) { if (t instanceof ConstrainedType) { ConstrainedType ct = (ConstrainedType) t; Type b = baseType(t); CConstraint c = xclause(t); if ( hasVar(b, x)) return true; for (XTerm term : c.constraints()) { if (term.hasVar(x)) return true; } } if (t instanceof MacroType) { MacroType pt = (MacroType) t; return hasVar(pt.definedType(), x); } return false; } public static boolean entails(Type t, XTerm t1, XTerm t2) { CConstraint c = realX(t); if (c==null) c = new CConstraint(); return c.entails(t1, t2); } public static boolean disEntails(Type t, XTerm t1, XTerm t2) { CConstraint c = realX(t); if (c==null) c = new CConstraint(); return c.disEntails(t1, t2); } public static boolean disEntailsSelf(Type t, XTerm t2) { CConstraint c = realX(t); if (c==null) c = new CConstraint(); return c.disEntails(c.self(), t2); } protected static boolean amIProperty(Type t, Name propName, Context context) { TypeSystem xts = (TypeSystem) t.typeSystem(); CConstraint r = realX(t); // first try self.p X10FieldInstance fi = getProperty(t, propName); if (fi != null) { try { CConstraint c = new CConstraint(); XVar term = xts.xtypeTranslator().trans(c, c.self(), fi); c.addBinding(term, xts.xtypeTranslator().trans(true)); return r.entails(c, context.constraintProjection(r, c)); } catch (XFailure f) { return false; } } else { // try self.p() try { X10MethodInstance mi = xts.findMethod(t, xts.MethodMatcher(t, propName, Collections.<Type>emptyList(), xts.emptyContext())); XTerm body = mi.body(); CConstraint c = new CConstraint(); body = body.subst(c.self(), mi.x10Def().thisVar()); c.addTerm(body); return r.entails(c, context.constraintProjection(r, c)); } catch (XFailure f) { return false; } catch (SemanticException f) { return false; } } } public static boolean isRect(Type t, Context context) { return amIProperty(t, Name.make("rect"), context); } public static XTerm onePlace(Type t) { return find(t, Name.make("onePlace")); } public static boolean isZeroBased(Type t, Context context) { return amIProperty(t, Name.make("zeroBased"), context); } public static XTerm distribution(Type t) { return findProperty(t, Name.make("dist")); } public static XTerm region(Type t) { return findProperty(t, Name.make("region")); } public static XTerm zeroBased(Type t) { return findProperty(t, Name.make("zeroBased")); } public static XTerm makeZeroBased(Type t) { return makeProperty(t, "zeroBased"); } public static XTerm makeProperty(Type t, String propStr) { Name propName = Name.make(propStr); CConstraint c = realX(t); if (c != null) { // build the synthetic term. XTerm var = selfVar(t); if (var !=null) { X10FieldInstance fi = getProperty(t, propName); if (fi != null) { TypeSystem xts = (TypeSystem) t.typeSystem(); XTerm val = xts.xtypeTranslator().trans(c, var, fi); return val; } } } return null; } public static XTerm find(Type t, Name propName) { XTerm val = findProperty(t, propName); if (val == null) { CConstraint c = realX(t); if (c != null) { // build the synthetic term. XTerm var = selfVar(c); if (var !=null) { X10FieldInstance fi = getProperty(t, propName); if (fi != null) { TypeSystem xts = (TypeSystem) t.typeSystem(); val = xts.xtypeTranslator().trans(c, var, fi); } } } } return val; } public static boolean isRankOne(Type t, Context context) { TypeSystem xts = (TypeSystem) t.typeSystem(); return xts.ONE().equals(X10TypeMixin.rank(t, context)); } public static boolean isRankTwo(Type t, Context context) { TypeSystem xts = (TypeSystem) t.typeSystem(); return xts.TWO().equals(X10TypeMixin.rank(t, context)); } public static boolean isRankThree(Type t, Context context) { TypeSystem xts = (TypeSystem) t.typeSystem(); return xts.THREE().equals(X10TypeMixin.rank(t, context)); } public static boolean isNonNull(Type t) { return disEntails(t, self(t), XTerms.NULL); } static XTerm findProperty(Type t, Name propName) { CConstraint c = realX(t); if (c == null) return null; // TODO: check dist.region.p and region.p FieldInstance fi = getProperty(t, propName); if (fi != null) return c.bindingForSelfField(XTerms.makeName(fi.def())); return null; } public static XTerm rank(Type t, Context context) { TypeSystem xts = (TypeSystem) t.typeSystem(); return findOrSynthesize(t, Name.make("rank")); } /** * Add the constraint self.rank==x to t unless * that causes an inconsistency. * @param t * @param x * @return */ public static Type addRank(Type t, int x) { TypeSystem xts = (TypeSystem) t.typeSystem(); XTerm xt = findOrSynthesize(t, Name.make("rank")); try { t = addBinding(t, xt, XTerms.makeLit(new Integer(x))); return t; } catch (XFailure f) { return t; // without the binding added. } } public static Type addRect(Type t) { TypeSystem xts = (TypeSystem) t.typeSystem(); XTerm xt = findOrSynthesize(t, Name.make("rect")); try { t = addBinding(t, xt, XTerms.TRUE); return t; } catch (XFailure f) { return t; // without the binding added. } } public static Type addZeroBased(Type t) { TypeSystem xts = (TypeSystem) t.typeSystem(); XTerm xt = findOrSynthesize(t, Name.make("zeroBased")); try { t = addBinding(t, xt, XTerms.TRUE); return t; } catch (XFailure f) { return t; // without the binding added. } } public static Type railBaseType(Type t) { t = baseType(t); if (t instanceof X10ClassType) { X10ClassType ct = (X10ClassType) t; TypeSystem ts = (TypeSystem) t.typeSystem(); ClassType a = (ClassType) ts.Rail(); if (ct.def() == a.def()) return ct.typeArguments().get(0); else arrayBaseType(ct.superClass()); } return null; } public static Type arrayBaseType(Type t) { t = baseType(t); if (t instanceof X10ClassType) { X10ClassType ct = (X10ClassType) t; TypeSystem ts = (TypeSystem) t.typeSystem(); ClassType a = (ClassType) ts.Array(); ClassType da = (ClassType) ts.Array(); if (ct.def() == a.def() || ct.def() == da.def()) return ct.typeArguments().get(0); else arrayBaseType(ct.superClass()); } return null; } public static boolean isX10Array(Type t) { TypeSystem ts = (TypeSystem) t.typeSystem(); Type tt = baseType(t); Type at = baseType(ts.Array()); if (tt instanceof ClassType && at instanceof ClassType) { ClassDef tdef = ((ClassType) tt).def(); ClassDef adef = ((ClassType) at).def(); return ts.descendsFrom(tdef, adef); } return false; } public static boolean isX10DistArray(Type t) { TypeSystem ts = (TypeSystem) t.typeSystem(); Type tt = baseType(t); Type at = baseType(ts.DistArray()); if (tt instanceof ClassType && at instanceof ClassType) { ClassDef tdef = ((ClassType) tt).def(); ClassDef adef = ((ClassType) at).def(); return ts.descendsFrom(tdef, adef); } return false; } public static XTerm findOrSynthesize(Type t, Name propName) { return find(t, propName); } public static XVar self(Type t) { CConstraint c = realX(t); if (c == null) return null; return selfVar(c); } /** * Are instances of this type accessible from anywhere? * @param t * @return public static boolean isGlobalType(Type t) { if (isX10Struct(t)) return true; return false; } */ /** * We need to ensure that there is a symbolic name for this type. i.e. self is bound to some variable. * So if it is not, please create a new EQV and bind self to it. * * This is done in particular before getting field instances of this type. This ensures * that the field instance can be computed accurately, that is the constraint * self = t.f can be added to it, where t is the selfBinding for the container (i.e. this). * */ /*public static Type ensureSelfBound(Type t) { if (t instanceof ConstrainedType) { ((ConstrainedType) t).ensureSelfBound(); return t; } XVar v = selfVarBinding(t); if (v !=null) return t; try { t = setSelfVar(t,XTerms.makeUQV()); } catch (SemanticException z) { } if (selfVarBinding(t) == null) assert selfVarBinding(t) != null; return t; } */ /** * Returns a new constraint that allows null. * E.g., given "{self.home==here, self!=null}" it returns "{self.home==here}" * @param c a constraint "c" that doesn't allow null * @return a new constraint with all the constraints in "c" except {self!=null} */ public static CConstraint allowNull(CConstraint c) { final XVar self = c.self(); CConstraint res = new CConstraint(self); assert !res.disEntails(self,XTerms.NULL); for (XTerm term : c.constraints()) { CConstraint copy = res.copy(); try { copy.addTerm(term); } catch (XFailure xFailure) { assert false : xFailure; } if (!copy.disEntails(self,XTerms.NULL)) res = copy; } return res; } public static boolean isUninitializedField(X10FieldDef def,TypeSystem ts) { return isDefAnnotated(def,ts,"x10.compiler.Uninitialized"); } public static boolean isSuppressTransientErrorField(X10FieldDef def,TypeSystem ts) { return isDefAnnotated(def,ts,"x10.compiler.SuppressTransientError"); } public static boolean isNoThisAccess(X10ProcedureDef def,TypeSystem ts) { return isDefAnnotated(def,ts,"x10.compiler.NoThisAccess"); } public static boolean isNonEscaping(X10ProcedureDef def,TypeSystem ts) { return isDefAnnotated(def,ts,"x10.compiler.NonEscaping"); } public static boolean isDefAnnotated(X10Def def,TypeSystem ts, String name) { try { Type at = (Type) ts.systemResolver().find(QName.make(name)); return !def.annotationsMatching(at).isEmpty(); } catch (SemanticException e) { return false; } } // this is an under-approximation (it is always safe to return false, i.e., the user will just get more errors). In the future we will improve the precision so more types will have zero. public static boolean isHaszero(Type t, Context xc) { TypeSystem ts = xc.typeSystem(); XLit zeroLit = null; // see Lit_c.constantValue() in its decendants if (t.isBoolean()) { zeroLit = XTerms.FALSE; } else if (ts.isChar(t)) { zeroLit = XTerms.ZERO_CHAR; } else if (ts.isInt(t) || ts.isByte(t) || ts.isUByte(t) || ts.isShort(t) || ts.isUShort(t)) { zeroLit = XTerms.ZERO_INT; } else if (ts.isUInt(t) || ts.isULong(t) || ts.isLong(t)) { zeroLit = XTerms.ZERO_LONG; } else if (ts.isFloat(t)) { zeroLit = XTerms.ZERO_FLOAT; } else if (ts.isDouble(t)) { zeroLit = XTerms.ZERO_DOUBLE; } else if (ts.isObjectOrInterfaceType(t, xc)) { if (permitsNull(t)) return true; //zeroLit = XTerms.NULL; } else if (ts.isParameterType(t)) { // we have some type "T" which is a type parameter. Does it have a zero value? // So, type bounds (e.g., T<:Int) do not help, because Int{self!=0}<:Int // Similarly, Int<:T doesn't help, because Int<:Any{self!=null} // However, T==Int does help if (isConstrained(t)) return false; // if we have constraints on the type parameter, e.g., T{self!=null}, then we give up and return false. TypeConstraint typeConst = xc.currentTypeConstraint(); List<SubtypeConstraint> env = typeConst.terms(); for (SubtypeConstraint sc : env) { if (sc.isEqualityConstraint()) { Type other = null; final Type sub = sc.subtype(); final Type sup = sc.supertype(); if (ts.typeEquals(t, sub,xc)) { if (!ts.isParameterType(sub)) other = sub; if (!ts.isParameterType(sup)) other = sup; } if (other!=null && isHaszero(other,xc)) // careful of infinite recursion when calling isHaszero // We cannot have infinite recursion because other is not a ParameterType // (we can have that T==U, U==Int. but then typeEquals(T,Int,xc) should return true) return true; // T is equal to another type that has zero } else if (sc.isSubtypeConstraint()) { // doesn't help } else { assert sc.isHaszero(); if (ts.typeEquals(t,sc.subtype(),xc)) { return true; } } } } else if (isX10Struct(t)) { if (!(t instanceof StructType)) return false; StructType structType = (StructType) t; // user-defined structs (such as Complex) can have zero iff // 1) They do not have a class invariant // 2) all their fields have zero // todo: When ConstrainedType_c.fields() is fixed (it should add the constraint to the fields), then I can remove this "if" if (isConstrained(t)) return false; // currently I don't handle constrained user-defined types, i.e., Complex{re!=3.0} doesn't haszero // far to do: if t is constrained, then a constraint with all fields=zero entails t's constraint // e.g., Complex and Complex{re!=3.0} haszero, // Complex{re!=0.0} and Complex{re==3.0} doesn't haszero { // do we have an classInvariant? todo: class invariant are not treated correctly: X10ClassDecl_c.classInvariant is fine, but X10ClassDef_c.classInvariant is wrong final Type base = baseType(t); if (!(base instanceof X10ParsedClassType_c)) return false; X10ParsedClassType_c xlass = (X10ParsedClassType_c) base; final ClassDef def = xlass.def(); if (!(def instanceof X10ClassDef_c)) return false; X10ClassDef_c x10ClassDef = (X10ClassDef_c) def; final Ref<CConstraint> ref = x10ClassDef.classInvariant(); if (ref!=null && ref.get().constraints().size()>0) return false; // the struct has a class invariant (so the zero value might not satisfy it) } // make sure all the fields and properties haszero - for (FieldInstance field : structType.fields()) + for (FieldInstance field : structType.fields()) { + if (field.flags().isStatic()) { + continue; + } if (!isHaszero(field.type(),xc)) return false; + } return true; } if (zeroLit==null) return false; if (!isConstrained(t)) return true; final CConstraint constraint = xclause(t); final CConstraint zeroCons = new CConstraint(constraint.self()); // make sure the zeroLit is not in the constraint try { zeroCons.addSelfBinding(zeroLit); return zeroCons.entails(constraint); } catch (XFailure xFailure) { return false; } } public static Expr getZeroVal(TypeNode typeNode, Position p, ContextVisitor tc) { // see X10FieldDecl_c.typeCheck try { Type t = typeNode.type(); TypeSystem ts = tc.typeSystem(); NodeFactory nf = tc.nodeFactory(); Context context = tc.context(); if (!isHaszero(t,context)) return null; Expr e = null; if (t.isBoolean()) { e = nf.BooleanLit(p, false); } else if (ts.isShort(t)) { e = nf.IntLit(p, IntLit.SHORT, 0L); } else if (ts.isUShort(t)) { e = nf.IntLit(p, IntLit.USHORT, 0L); } else if (ts.isByte(t)) { e = nf.IntLit(p, IntLit.BYTE, 0L); } else if (ts.isUByte(t)) { e = nf.IntLit(p, IntLit.UBYTE, 0L); } else if (ts.isChar(t)) { e = nf.CharLit(p, '\0'); } else if (ts.isInt(t)) { e = nf.IntLit(p, IntLit.INT, 0L); } else if (ts.isUInt(t)) { e = nf.IntLit(p, IntLit.UINT, 0L); } else if (ts.isLong(t)) { e = nf.IntLit(p, IntLit.LONG, 0L); } else if (ts.isULong(t)) { e = nf.IntLit(p, IntLit.ULONG, 0L); } else if (ts.isFloat(t)) { e = nf.FloatLit(p, FloatLit.FLOAT, 0.0); } else if (ts.isDouble(t)) { e = nf.FloatLit(p, FloatLit.DOUBLE, 0.0); } else if (ts.isObjectOrInterfaceType(t, context)) { e = nf.NullLit(p); } else if (ts.isParameterType(t) || isX10Struct(t)) { // call Zero.get[T]() (e.g., "0 as T" doesn't work if T is String) TypeNode receiver = (TypeNode) nf.CanonicalTypeNode(p, (Type) ts.systemResolver().find(QName.make("x10.lang.Zero"))); //receiver = (TypeNode) receiver.del().typeCheck(tc).checkConstants(tc); e = nf.X10Call(p,receiver, nf.Id(p,"get"),Collections.singletonList(typeNode), Collections.<Expr>emptyList()); } if (e != null) { e = (Expr) e.del().typeCheck(tc).checkConstants(tc); if (ts.isSubtype(e.type(), t, context)) { // suppose the field is "var i:Int{self!=0}", then you cannot create an initializer which is 0! return e; } } return null; } catch (Throwable e1) { throw new InternalCompilerError(e1); } } public static boolean permitsNull(Type t) { if (isX10Struct(t)) return false; if (X10TypeMixin.disEntailsSelf(t, XTerms.NULL)) return false; TypeSystem ts = ((TypeSystem) t.typeSystem()); if (ts.isParameterType(t)) { return false; // a parameter type might be instantiated with a struct that doesn't permit null. } return true; } public static XVar thisVar(XVar xthis, Type thisType) { Type base = baseType(thisType); if (base instanceof X10ClassType) { XVar supVar = ((X10ClassType) base).x10Def().thisVar(); return supVar; } return xthis; } public static List<Type> expandTypes(List<Type> formals, TypeSystem xts) { List<Type> result = new ArrayList<Type>(); for (Type f : formals) { result.add(xts.expandMacros(f)); } return result; } public static <PI extends X10ProcedureInstance<?>> boolean isStatic(PI me) { if (me instanceof ConstructorInstance) return true; if (me instanceof MethodInstance) { MethodInstance mi = (MethodInstance) me; return mi.flags().isStatic(); } return false; } public static Type meetTypes(TypeSystem xts, Type t1, Type t2, Context context) { if (xts.isSubtype(t1, t2, context)) return t1; if (xts.isSubtype(t2, t1, context)) return t2; return null; } /** * Determine if xp1 is more specific than xp2 given some (unknown) current call c to a method m or a constructor * for a class or interface Q (in the given context). (Note that xp1 and xp2 may not be function definitions since * no method resolution is not necessary for function definitions.) * * <p> We may assume that xp1 and xp2 are instantiations of underlying (possibly generic) procedure definitions, * pd1 and pd2 (respectively) that lie in the applicable and available method call set for c. * * <p> The determination is done as follows. First, if xp1 is an instance of a static method on a class C1, and xp2 * is an instance of a static method on a class C2, and C1 is distinct from C2 but descends from it, * Otherwise we examine pd1 and pd2 -- the underlying possibly generic method definitions. Now pd1 is more * specific than pd2 if a call can be made to pd2 with the information available about pd1's arguments. As usual, * type parameters of pd2 (if any) are permitted to be instantiated during this process. * @param ct -- represents the container on which both xp1 and xp2 are available. Ignored now. TODO: Remove the machinery * introduced to permit ct to be available in this call to moreSpecificImpl. * @param xp1 -- the instantiated procedure definition. * @param xp2 * @param context * @return */ public static String MORE_SEPCIFIC_WARNING = "Please check definitions p1 and p2. "; public static boolean moreSpecificImpl(Type ct, ProcedureInstance<?> xp1, ProcedureInstance<?> xp2, Context context) { TypeSystem ts = (TypeSystem) xp1.typeSystem(); Type ct1 = xp2 instanceof MemberInstance<?> ? ((MemberInstance<?>) xp1).container() : null; Type ct2 = xp2 instanceof MemberInstance<?> ? ((MemberInstance<?>) xp2).container() : null; Type t1 = ct1; Type t2 = ct2; if (t1 != null && t2 != null) { t1 = baseType(t1); t2 = baseType(t2); } boolean descends = t1 != null && t2 != null && ts.descendsFrom(ts.classDefOf(t1), ts.classDefOf(t2)); Flags flags1 = xp1 instanceof MemberInstance<?> ? ((MemberInstance<?>) xp1).flags() : Flags.NONE; Flags flags2 = xp2 instanceof MemberInstance<?> ? ((MemberInstance<?>) xp2).flags() : Flags.NONE; // A static method in a subclass is always more specific. // Note: this rule differs from Java but avoids an anomaly with conversion methods. if (descends && ! ts.hasSameClassDef(t1, t2) && flags1.isStatic() && flags2.isStatic()) { return true; } // For now (10/10/10) we check using both styles and mark the cases in which results are different // as a diagnostic output for the compiler. boolean java = javaStyleMoreSpecificMethod(xp1, xp2, (Context) context, ct1, t1, t2,descends); boolean old = oldStyleMoreSpecificMethod(xp1, xp2, (Context) context, ts, ct1, t1, t2, descends); if (java != old) { String msg = MORE_SEPCIFIC_WARNING + ((java && ! old) ? "p1 is now more specific than p2; it was not in 2.0.6." : "p1 is now not more specific than p2; it was in 2.0.6.") + "\n\t: p1: " + getOrigMI(xp1) + "\n\t: at " + xp1.position() + "\n\t: p2: " + getOrigMI(xp2) + "\n\t: at " + xp2.position(); ts.extensionInfo().compiler().errorQueue().enqueue(ErrorInfo.WARNING,msg); } // Change this to return old to re-enable 2.0.6 style computation. return java; } static ProcedureInstance<?> getOrigMI(ProcedureInstance<?> xp) { if (xp instanceof MethodInstance) return ((MethodInstance) xp).origMI(); if (xp instanceof ConstructorInstance) return ((ConstructorInstance) xp).origMI(); return xp; } // This is taken from the 2.0.6 implementation. // This contains logic for pre-generic Java. One determines // that a method MI1 is more specific than MI2 if each argument of // MI1 is a subtype of the corresponding argument of MI2. That is, // MI2 is taken as the instance of the method definition for the given // call. Hence no type inference is done. private static boolean oldStyleMoreSpecificMethod( ProcedureInstance<?> xp1, ProcedureInstance<?> xp2, Context context, TypeSystem ts, Type ct1, Type t1, Type t2, boolean descends) { // if the formal params of p1 can be used to call p2, p1 is more specific if (xp1.formalTypes().size() == xp2.formalTypes().size() ) { for (int i = 0; i < xp1.formalTypes().size(); i++) { Type f1 = xp1.formalTypes().get(i); Type f2 = xp2.formalTypes().get(i); // Ignore constraints. This avoids an anomaly with the translation with erased constraints // having inverting the result of the most-specific test. Fixes XTENLANG-455. Type b1 = baseType(f1); Type b2 = baseType(f2); if (! ts.isImplicitCastValid(b1, b2, context)) { return false; } } } // If the formal types are all equal, check the containers; otherwise p1 is more specific. for (int i = 0; i < xp1.formalTypes().size(); i++) { Type f1 = xp1.formalTypes().get(i); Type f2 = xp2.formalTypes().get(i); if (! ts.typeEquals(f1, f2, context)) { return true; } } if (t1 != null && t2 != null) { // If p1 overrides p2 or if p1 is in an inner class of p2, pick p1. if (descends) { return true; } if (t1.isClass() && t2.isClass()) { if (t1.toClass().isEnclosed(t2.toClass())) { return true; } } return false; } return true; } /** * * @param xp1 -- the first procedure instance * @param xp2 -- the second procedure instance * @param context -- the context for the original call * @param ts * @param ct1 * @param t1 -- base type of ct1 * @param t2 -- base type of the container of xp2. * @param descends -- does t1 descend from t2? * @return */ private static boolean javaStyleMoreSpecificMethod( ProcedureInstance<?> xp1, ProcedureInstance<?> xp2, Context context, Type ct1, Type t1, Type t2, boolean descends) { assert xp1 != null; assert xp2 != null; assert context != null; TypeSystem ts = (TypeSystem) context.typeSystem(); List<Type> typeArgs = Collections.<Type>emptyList(); try { if (xp2 instanceof X10MethodInstance) { // Both xp1 and xp2 should be X10MethodInstance's X10MethodInstance xmi2 = (X10MethodInstance) xp2; X10MethodInstance origMI2 = (X10MethodInstance) xmi2.origMI(); assert origMI2 != null; if (! (xp1 instanceof X10MethodInstance)) return false; X10MethodInstance xmi1 = (X10MethodInstance) xp1; X10MethodInstance origMI1 = (X10MethodInstance)xmi1.origMI(); assert origMI1 != null; // Now determine that a call can be made to thisMI2 using the // argument list obtained from thisMI1. If not, return false. List<Type> argTypes = new ArrayList<Type>(origMI1.formalTypes()); if (xp2.formalTypes().size() != argTypes.size()) return false; // TODO: Establish that the current context is aware of the method // guard for xmi1. if (typeArgs.isEmpty() || typeArgs.size() == xmi2.typeParameters().size()) { MethodInstance r = Matcher.inferAndCheckAndInstantiate(context, origMI2, ct1, typeArgs, argTypes, xp2.position()); if (r == null) return false; } } else if (xp2 instanceof X10ConstructorInstance) { // Both xp1 and xp2 should be X10ConstructorInstance's X10ConstructorInstance xmi2 = (X10ConstructorInstance) xp2; X10ConstructorInstance origMI2 = (X10ConstructorInstance) xmi2.origMI(); assert origMI2 != null; if (! (xp1 instanceof X10ConstructorInstance)) return false; X10ConstructorInstance xmi1 = (X10ConstructorInstance) xp1; X10ConstructorInstance origMI1 = (X10ConstructorInstance) xmi1.origMI(); assert origMI1 != null; List<Type> argTypes = new ArrayList<Type>(origMI1.formalTypes()); if (xp2.formalTypes().size() != argTypes.size()) return false; // TODO: Figure out how to do type inference. X10ConstructorInstance r = Matcher.inferAndCheckAndInstantiate( context, origMI2, ct1, typeArgs, argTypes, xp2.position()); if (r == null) return false; } else { // Should not happen. // System.out.println("Diagnostic. Unhandled MoreSpecificMatcher case: " + xp2 + " class " + xp2.getClass()); assert false; } } catch (SemanticException z) { return false; } // I have kept the logic below from 2.0.6 for now. // TODO: Determine whether this should stay or not. // If the formal types are all equal, check the containers; otherwise p1 is more specific. for (int i = 0; i < xp1.formalTypes().size(); i++) { Type f1 = xp1.formalTypes().get(i); Type f2 = xp2.formalTypes().get(i); if (! ts.typeEquals(f1, f2, context)) { return true; } } if (t1 != null && t2 != null) { // If p1 overrides p2 or if p1 is in an inner class of p2, pick p1. if (descends) { return true; } if (t1.isClass() && t2.isClass()) { if (t1.toClass().isEnclosed(t2.toClass())) { return true; } } return false; } return true; } public static void checkMissingParameters(Receiver receiver) throws SemanticException { Type xt = receiver.type(); checkMissingParameters(xt,receiver.position()); } public static void checkMissingParameters(Type xt, Position pos) throws SemanticException { if (xt == null) return; xt = baseType(xt); if (xt instanceof X10ParsedClassType) { X10ParsedClassType xt1 = (X10ParsedClassType) xt; final X10ClassDef classDef = (X10ClassDef) xt1.def(); if (xt1.isMissingTypeArguments()) { List<ParameterType> expectedArgs = classDef.typeParameters(); throw new Errors.TypeIsMissingParameters(xt, expectedArgs, pos); } else { // todo check the TypeConstraint of the class invariant is satisfied } } } public static Type arrayElementType(Type t) { t = baseType(t); TypeSystem xt = (TypeSystem) t.typeSystem(); if (xt.isX10Array(t) || xt.isX10DistArray(t) || xt.isRail(t)) { if (t instanceof X10ParsedClassType) { Type result = ((X10ParsedClassType) t).typeArguments().get(0); return result; } } return null; } public static boolean isTypeConstraintExpression(Expr e) { if (e instanceof ParExpr) return isTypeConstraintExpression(((ParExpr) e).expr()); else if (e instanceof Unary_c) return isTypeConstraintExpression(((Unary) e).expr()); else if (e instanceof SubtypeTest) return true; else if (e instanceof HasZeroTest) return true; return false; } public static boolean contextKnowsType(Receiver r) { if (r instanceof Variable) return ((Variable) r).flags().isFinal(); if (r instanceof Field) return contextKnowsType( ((Field) r).target()); if (r instanceof Special || r instanceof Here || r instanceof Lit) return true; if (r instanceof ParExpr) return contextKnowsType(((ParExpr) r).expr()); if (r instanceof Cast) return contextKnowsType(((Cast) r).expr()); return false; } /** * Return T if type implements Reducer[T]; * @param type * @return */ public static Type reducerType(Type type) { TypeSystem ts = (TypeSystem) type.typeSystem(); Type base = X10TypeMixin.baseType(type); if (base instanceof X10ClassType) { if (ts.hasSameClassDef(base, ts.Reducible())) { return X10TypeMixin.getParameterType(base, 0); } else { Type sup = ts.superClass(type); if (sup != null) { Type t = reducerType(sup); if (t != null) return t; } for (Type ti : ts.interfaces(type)) { Type t = reducerType(ti); if (t != null) { return t; } } } } return null; } public static boolean areConsistent(Type t1, Type t2) { try { if ( isConstrained(t1) && isConstrained(t2)) tryAddingConstraint(t1, xclause(t2)); return true; } catch (XFailure z) { return false; } } public static Type instantiateTypeParametersExplicitly(Type t) { if (t instanceof AnnotatedType) { AnnotatedType at = (AnnotatedType) t; Type bt = at.baseType(); Type ibt = instantiateTypeParametersExplicitly(bt); if (ibt != bt) return at.baseType(ibt); return at; } else if (t instanceof ConstrainedType) { ConstrainedType ct = (ConstrainedType) t; Type bt = Types.get(ct.baseType()); Type ibt = instantiateTypeParametersExplicitly(bt); if (ibt != bt) ct = ct.baseType(Types.ref(ibt)); return ct; } else if (t instanceof X10ParsedClassType) { X10ParsedClassType pct = (X10ParsedClassType) t; pct = pct.instantiateTypeParametersExplicitly(); List<Type> typeArguments = pct.typeArguments(); List<Type> newTypeArguments = typeArguments; if (typeArguments != null) { List<Type> res = new ArrayList<Type>(); for (Type a : typeArguments) { Type ia = instantiateTypeParametersExplicitly(a); if (ia != a) newTypeArguments = res; res.add(ia); } } pct = pct.typeArguments(newTypeArguments); return pct; } else { return t; } } }
false
true
public static boolean isHaszero(Type t, Context xc) { TypeSystem ts = xc.typeSystem(); XLit zeroLit = null; // see Lit_c.constantValue() in its decendants if (t.isBoolean()) { zeroLit = XTerms.FALSE; } else if (ts.isChar(t)) { zeroLit = XTerms.ZERO_CHAR; } else if (ts.isInt(t) || ts.isByte(t) || ts.isUByte(t) || ts.isShort(t) || ts.isUShort(t)) { zeroLit = XTerms.ZERO_INT; } else if (ts.isUInt(t) || ts.isULong(t) || ts.isLong(t)) { zeroLit = XTerms.ZERO_LONG; } else if (ts.isFloat(t)) { zeroLit = XTerms.ZERO_FLOAT; } else if (ts.isDouble(t)) { zeroLit = XTerms.ZERO_DOUBLE; } else if (ts.isObjectOrInterfaceType(t, xc)) { if (permitsNull(t)) return true; //zeroLit = XTerms.NULL; } else if (ts.isParameterType(t)) { // we have some type "T" which is a type parameter. Does it have a zero value? // So, type bounds (e.g., T<:Int) do not help, because Int{self!=0}<:Int // Similarly, Int<:T doesn't help, because Int<:Any{self!=null} // However, T==Int does help if (isConstrained(t)) return false; // if we have constraints on the type parameter, e.g., T{self!=null}, then we give up and return false. TypeConstraint typeConst = xc.currentTypeConstraint(); List<SubtypeConstraint> env = typeConst.terms(); for (SubtypeConstraint sc : env) { if (sc.isEqualityConstraint()) { Type other = null; final Type sub = sc.subtype(); final Type sup = sc.supertype(); if (ts.typeEquals(t, sub,xc)) { if (!ts.isParameterType(sub)) other = sub; if (!ts.isParameterType(sup)) other = sup; } if (other!=null && isHaszero(other,xc)) // careful of infinite recursion when calling isHaszero // We cannot have infinite recursion because other is not a ParameterType // (we can have that T==U, U==Int. but then typeEquals(T,Int,xc) should return true) return true; // T is equal to another type that has zero } else if (sc.isSubtypeConstraint()) { // doesn't help } else { assert sc.isHaszero(); if (ts.typeEquals(t,sc.subtype(),xc)) { return true; } } } } else if (isX10Struct(t)) { if (!(t instanceof StructType)) return false; StructType structType = (StructType) t; // user-defined structs (such as Complex) can have zero iff // 1) They do not have a class invariant // 2) all their fields have zero // todo: When ConstrainedType_c.fields() is fixed (it should add the constraint to the fields), then I can remove this "if" if (isConstrained(t)) return false; // currently I don't handle constrained user-defined types, i.e., Complex{re!=3.0} doesn't haszero // far to do: if t is constrained, then a constraint with all fields=zero entails t's constraint // e.g., Complex and Complex{re!=3.0} haszero, // Complex{re!=0.0} and Complex{re==3.0} doesn't haszero { // do we have an classInvariant? todo: class invariant are not treated correctly: X10ClassDecl_c.classInvariant is fine, but X10ClassDef_c.classInvariant is wrong final Type base = baseType(t); if (!(base instanceof X10ParsedClassType_c)) return false; X10ParsedClassType_c xlass = (X10ParsedClassType_c) base; final ClassDef def = xlass.def(); if (!(def instanceof X10ClassDef_c)) return false; X10ClassDef_c x10ClassDef = (X10ClassDef_c) def; final Ref<CConstraint> ref = x10ClassDef.classInvariant(); if (ref!=null && ref.get().constraints().size()>0) return false; // the struct has a class invariant (so the zero value might not satisfy it) } // make sure all the fields and properties haszero for (FieldInstance field : structType.fields()) if (!isHaszero(field.type(),xc)) return false; return true; } if (zeroLit==null) return false; if (!isConstrained(t)) return true; final CConstraint constraint = xclause(t); final CConstraint zeroCons = new CConstraint(constraint.self()); // make sure the zeroLit is not in the constraint try { zeroCons.addSelfBinding(zeroLit); return zeroCons.entails(constraint); } catch (XFailure xFailure) { return false; } }
public static boolean isHaszero(Type t, Context xc) { TypeSystem ts = xc.typeSystem(); XLit zeroLit = null; // see Lit_c.constantValue() in its decendants if (t.isBoolean()) { zeroLit = XTerms.FALSE; } else if (ts.isChar(t)) { zeroLit = XTerms.ZERO_CHAR; } else if (ts.isInt(t) || ts.isByte(t) || ts.isUByte(t) || ts.isShort(t) || ts.isUShort(t)) { zeroLit = XTerms.ZERO_INT; } else if (ts.isUInt(t) || ts.isULong(t) || ts.isLong(t)) { zeroLit = XTerms.ZERO_LONG; } else if (ts.isFloat(t)) { zeroLit = XTerms.ZERO_FLOAT; } else if (ts.isDouble(t)) { zeroLit = XTerms.ZERO_DOUBLE; } else if (ts.isObjectOrInterfaceType(t, xc)) { if (permitsNull(t)) return true; //zeroLit = XTerms.NULL; } else if (ts.isParameterType(t)) { // we have some type "T" which is a type parameter. Does it have a zero value? // So, type bounds (e.g., T<:Int) do not help, because Int{self!=0}<:Int // Similarly, Int<:T doesn't help, because Int<:Any{self!=null} // However, T==Int does help if (isConstrained(t)) return false; // if we have constraints on the type parameter, e.g., T{self!=null}, then we give up and return false. TypeConstraint typeConst = xc.currentTypeConstraint(); List<SubtypeConstraint> env = typeConst.terms(); for (SubtypeConstraint sc : env) { if (sc.isEqualityConstraint()) { Type other = null; final Type sub = sc.subtype(); final Type sup = sc.supertype(); if (ts.typeEquals(t, sub,xc)) { if (!ts.isParameterType(sub)) other = sub; if (!ts.isParameterType(sup)) other = sup; } if (other!=null && isHaszero(other,xc)) // careful of infinite recursion when calling isHaszero // We cannot have infinite recursion because other is not a ParameterType // (we can have that T==U, U==Int. but then typeEquals(T,Int,xc) should return true) return true; // T is equal to another type that has zero } else if (sc.isSubtypeConstraint()) { // doesn't help } else { assert sc.isHaszero(); if (ts.typeEquals(t,sc.subtype(),xc)) { return true; } } } } else if (isX10Struct(t)) { if (!(t instanceof StructType)) return false; StructType structType = (StructType) t; // user-defined structs (such as Complex) can have zero iff // 1) They do not have a class invariant // 2) all their fields have zero // todo: When ConstrainedType_c.fields() is fixed (it should add the constraint to the fields), then I can remove this "if" if (isConstrained(t)) return false; // currently I don't handle constrained user-defined types, i.e., Complex{re!=3.0} doesn't haszero // far to do: if t is constrained, then a constraint with all fields=zero entails t's constraint // e.g., Complex and Complex{re!=3.0} haszero, // Complex{re!=0.0} and Complex{re==3.0} doesn't haszero { // do we have an classInvariant? todo: class invariant are not treated correctly: X10ClassDecl_c.classInvariant is fine, but X10ClassDef_c.classInvariant is wrong final Type base = baseType(t); if (!(base instanceof X10ParsedClassType_c)) return false; X10ParsedClassType_c xlass = (X10ParsedClassType_c) base; final ClassDef def = xlass.def(); if (!(def instanceof X10ClassDef_c)) return false; X10ClassDef_c x10ClassDef = (X10ClassDef_c) def; final Ref<CConstraint> ref = x10ClassDef.classInvariant(); if (ref!=null && ref.get().constraints().size()>0) return false; // the struct has a class invariant (so the zero value might not satisfy it) } // make sure all the fields and properties haszero for (FieldInstance field : structType.fields()) { if (field.flags().isStatic()) { continue; } if (!isHaszero(field.type(),xc)) return false; } return true; } if (zeroLit==null) return false; if (!isConstrained(t)) return true; final CConstraint constraint = xclause(t); final CConstraint zeroCons = new CConstraint(constraint.self()); // make sure the zeroLit is not in the constraint try { zeroCons.addSelfBinding(zeroLit); return zeroCons.entails(constraint); } catch (XFailure xFailure) { return false; } }
diff --git a/src/gb-actions-unredd/script/src/main/java/it/geosolutions/geobatch/unredd/script/util/GeoStoreFacade.java b/src/gb-actions-unredd/script/src/main/java/it/geosolutions/geobatch/unredd/script/util/GeoStoreFacade.java index 2f2f308..29b15e6 100644 --- a/src/gb-actions-unredd/script/src/main/java/it/geosolutions/geobatch/unredd/script/util/GeoStoreFacade.java +++ b/src/gb-actions-unredd/script/src/main/java/it/geosolutions/geobatch/unredd/script/util/GeoStoreFacade.java @@ -1,365 +1,365 @@ /* * GeoBatch - Open Source geospatial batch processing system * https://github.com/nfms4redd/nfms-geobatch * Copyright (C) 2007-2008-2009 GeoSolutions S.A.S. * http://www.geo-solutions.it * * GPLv3 + Classpath exception * * 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 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 it.geosolutions.geobatch.unredd.script.util; import it.geosolutions.unredd.geostore.model.AttributeDef; import it.geosolutions.unredd.geostore.model.ReverseAttributeDef; import it.geosolutions.unredd.geostore.model.UNREDDCategories; import it.geosolutions.unredd.geostore.model.UNREDDChartScript; import it.geosolutions.unredd.geostore.model.UNREDDLayerUpdate; import it.geosolutions.unredd.geostore.model.UNREDDStatsDef; import it.geosolutions.geostore.core.model.Resource; import it.geosolutions.geostore.services.dto.ShortResource; import it.geosolutions.geostore.services.dto.search.AndFilter; import it.geosolutions.geostore.services.dto.search.AttributeFilter; import it.geosolutions.geostore.services.dto.search.BaseField; import it.geosolutions.geostore.services.dto.search.CategoryFilter; import it.geosolutions.geostore.services.dto.search.FieldFilter; import it.geosolutions.geostore.services.dto.search.SearchFilter; import it.geosolutions.geostore.services.dto.search.SearchOperator; import it.geosolutions.geostore.services.rest.model.RESTResource; import it.geosolutions.geobatch.unredd.script.exception.GeoStoreException; import it.geosolutions.geobatch.unredd.script.model.GeoStoreConfig; import it.geosolutions.geostore.services.rest.model.RESTStoredData; import it.geosolutions.unredd.geostore.model.*; import it.geosolutions.unredd.geostore.utils.NameUtils; import java.io.File; import java.util.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Basic GeoStoreUtil operations. * * A GeoStoreUtil action is used to execute the various operations. */ public abstract class GeoStoreFacade { private final Logger LOGGER = LoggerFactory.getLogger(GeoStoreFacade.class); private String gsurl; private String gsuser; private String gspwd; public GeoStoreFacade(String url, String user, String pwd) { this.gsurl = url; this.gsuser = user; this.gspwd = pwd; } public GeoStoreFacade(GeoStoreConfig config, File tempDir) { this.gsurl = config.getUrl(); this.gsuser = config.getUsername(); this.gspwd = config.getPassword(); } /** * Insert or update the storedData of a StatsData. */ public void setStatsData(Resource statsDef, String statsContent, String year, String month, String day) throws GeoStoreException { try { Resource statsData = this.searchStatsData(statsDef.getName(), year, month, day); if (statsData == null) { LOGGER.info("No StatsData found for " + statsDef.getName() + ", Year=" + year + ", Month=" + month + ". Inserting StatsData"); - insertStatsData(statsDef.getName(), year, month, statsContent, day); + insertStatsData(statsDef.getName(), year, month, day, statsContent); } else { long id = statsData.getId(); LOGGER.info("StatsData found for " + statsDef.getName() + ", Year=" + year + ", Month=" + month + ". Updating StatsData " + id); updateData(id, statsContent); } } catch (GeoStoreException ex) { throw ex; } catch (Exception ex) { LOGGER.error("Error computing stats: " + ex.getMessage(), ex); throw new GeoStoreException("Error while setting StatsData", ex); } } public void insertStatsData(String statsDefName, String year, String month, String day, String content) throws GeoStoreException { try { RESTResource statsDataResource = createStatsDataResource(statsDefName, year, month, day, content); insert(statsDataResource); } catch (Exception e) { throw new GeoStoreException("Error while inserting StatsData: " + statsDefName, e); } } /** * Generic search in GeoStoreUtil. * * @param filter the filter to apply for searching * @param getShortResource true if a list of resource is required, false if a RESTResource list is sufficient * * @return always a not null list * @throws GeoStoreException */ abstract protected List search(SearchFilter filter, boolean getShortResource) throws GeoStoreException; abstract protected List search(SearchFilter filter, boolean getShortResource, String fileNameHint) throws GeoStoreException; /** * generic insert into geostore * * @param resource the resource to insert * @throws GeoStoreException */ abstract public Long insert(RESTResource resource) throws GeoStoreException; abstract public void updateData(long id, String data) throws GeoStoreException; /** * ************ * this method allows to search a layer resource given its name * * @param layername the name of the layer resource to find * @return * @throws GeoStoreException */ public Resource searchLayer(String layername) throws GeoStoreException { if(LOGGER.isInfoEnabled()) LOGGER.info("Searching Layer " + layername); // the filter to search a resource in the layer category SearchFilter filter = new AndFilter( new FieldFilter(BaseField.NAME, layername, SearchOperator.EQUAL_TO), createCategoryFilter(UNREDDCategories.LAYER)); List<Resource> list = search(filter, false, "searchLayer_"+layername+"_"); return getSingleResource(list); } protected Resource getSingleResource(List<Resource> list) { if (list == null || list.isEmpty()) { return null; } else { Resource r0 = list.get(0); if(list.size() > 1) LOGGER.warn("Found " + list.size() + " resources of type " + r0.getCategory().getName() + " -- sample: "+ r0 ); return r0; } } public Resource searchLayerUpdate(String layer, String year, String month, String day) throws GeoStoreException { String layerSnapshot = NameUtils.buildLayerUpdateName(layer, year, month, day); if(LOGGER.isInfoEnabled()) LOGGER.info("Searching LayerUpdate " + layerSnapshot); SearchFilter filter = new AndFilter( new FieldFilter(BaseField.NAME, layerSnapshot, SearchOperator.EQUAL_TO), createCategoryFilter(UNREDDCategories.LAYERUPDATE)); return getSingleResource(search(filter, false, "searchLU_"+layer+"_")); } public List<Resource> searchLayerUpdateByLayer(String layername) throws GeoStoreException { SearchFilter filter = new AndFilter( createCategoryFilter(UNREDDCategories.LAYERUPDATE), createAttributeFilter(UNREDDLayerUpdate.Attributes.LAYER, layername)); return search(filter, false); } public List searchStatsDefByLayer(String layername, boolean getShortResource) throws GeoStoreException { if(LOGGER.isInfoEnabled()) LOGGER.info("Searching StatsDef by layer " + layername); SearchFilter filter = new AndFilter( createCategoryFilter(UNREDDCategories.STATSDEF), createAttributeFilter(UNREDDStatsDef.ReverseAttributes.LAYER, layername)); return search(filter, getShortResource); } public Resource searchStatsDefByName(String statsdefname) throws GeoStoreException { if(LOGGER.isInfoEnabled()) LOGGER.info("Searching StatsDef " + statsdefname); SearchFilter filter = new AndFilter( new FieldFilter(BaseField.NAME, statsdefname, SearchOperator.EQUAL_TO), createCategoryFilter(UNREDDCategories.STATSDEF)); List<Resource> list = search(filter, false, "searchStatsDef_"+statsdefname); return getSingleResource(list); } public Resource searchStatsData(String statsDefName, String year, String month, String day) throws GeoStoreException { String statsDataName = NameUtils.buildStatsDataName(statsDefName, year, month, day); if(LOGGER.isInfoEnabled()) LOGGER.info("Searching StatsData" + statsDataName); SearchFilter filter = new AndFilter( new FieldFilter(BaseField.NAME, statsDataName, SearchOperator.EQUAL_TO), createCategoryFilter(UNREDDCategories.STATSDATA)); return getSingleResource(search(filter, false, "searchStatsData_"+statsDataName)); } public boolean existStatsData(String statsDefName, String year, String month, String day) throws GeoStoreException { String statsDataName = NameUtils.buildStatsDataName(statsDefName, year, month, day); SearchFilter filter = new AndFilter( new FieldFilter(BaseField.NAME, statsDataName, SearchOperator.EQUAL_TO), createCategoryFilter(UNREDDCategories.STATSDATA)); List<ShortResource> list = search(filter, true); return list != null && ! list.isEmpty(); // will be not null only if at least 1 entry exist; we'll check also for isEMpty to be protected from future changes } public Resource searchChartScript(String scriptname) throws GeoStoreException { SearchFilter filter = new AndFilter( new FieldFilter(BaseField.NAME, scriptname, SearchOperator.EQUAL_TO), createCategoryFilter(UNREDDCategories.CHARTSCRIPT)); List<Resource> scripts = search(filter, false); return getSingleResource(scripts); } public List<Resource> searchChartScriptByStatsDef(String statsDefName) throws GeoStoreException { SearchFilter filter = new AndFilter( createCategoryFilter(UNREDDCategories.CHARTSCRIPT), createAttributeFilter(UNREDDChartScript.ReverseAttributes.STATSDEF, statsDefName)); return search(filter, false); } public List<ShortResource> searchChartDataByChartScript(String chartScriptName) throws GeoStoreException { SearchFilter filter = new AndFilter( createCategoryFilter(UNREDDCategories.CHARTDATA), createAttributeFilter(UNREDDChartData.Attributes.CHARTSCRIPT, chartScriptName)); return search(filter, true); } public List<Resource> searchChartDataPublished(String chartScriptName) throws GeoStoreException { SearchFilter filter = new AndFilter( createCategoryFilter(UNREDDCategories.CHARTDATA), createAttributeFilter(UNREDDChartData.Attributes.CHARTSCRIPT, chartScriptName), createAttributeFilter(UNREDDChartData.Attributes.PUBLISHED, "true")); return search(filter, false); } public void insertLayerUpdate(String layername, String year, String month, String day) throws GeoStoreException { RESTResource res = createLayerUpdate(layername, year, month, day); try { insert(res); } catch (Exception e) { LOGGER.error("Error while inserting LayerUpdate: " + res, e); throw new GeoStoreException("Error while inserting LayerUpdate on Layer " + layername, e); } } /** * Delete a resource. * Delete the resource identified by id. * * @param id */ abstract public void delete(long id) throws GeoStoreException; /** * delete all the resources in the geostore repository * * @deprecated DANGEROUS! */ public void delete() throws GeoStoreException { SearchFilter filter = new FieldFilter(BaseField.NAME, "*", SearchOperator.IS_NOT_NULL); List<ShortResource> resourceList = search(filter, true); if (resourceList == null || resourceList.isEmpty()) { LOGGER.info("No Resource to delete"); return; } LOGGER.warn("Deleting " + resourceList.size() + " resources"); for (ShortResource shortResource : resourceList) { LOGGER.info("Deleting " + shortResource); delete(shortResource.getId()); } } private static <A extends AttributeDef> AttributeFilter createAttributeFilter(A att, String value) { return new AttributeFilter(att.getName(), value, att.getDataType(), SearchOperator.EQUAL_TO); } private static <R extends ReverseAttributeDef> AttributeFilter createAttributeFilter(R att, String value) { return new AttributeFilter(value, att.getName(), att.getType(), SearchOperator.EQUAL_TO); } private static CategoryFilter createCategoryFilter(UNREDDCategories category) { return new CategoryFilter(category.getName(), SearchOperator.EQUAL_TO); } protected static RESTResource createStatsDataResource(String statsDefName, String year, String month, String day, String csv) { UNREDDStatsData statsData = new UNREDDStatsData(); statsData.setAttribute(UNREDDStatsData.Attributes.STATSDEF, statsDefName); statsData.setAttribute(UNREDDStatsData.Attributes.YEAR, year); if (month != null) { statsData.setAttribute(UNREDDStatsData.Attributes.MONTH, month); } if (day != null) { statsData.setAttribute(UNREDDStatsData.Attributes.DAY, day); } RESTResource res = statsData.createRESTResource(); String resName = NameUtils.buildStatsDataName(statsDefName, year, month, day); res.setName(resName); RESTStoredData storedData = new RESTStoredData(); storedData.setData(csv); res.setStore(storedData); return res; } protected static RESTResource createLayerUpdate(String layername, String year, String month, String day) { UNREDDLayerUpdate layerUpdate = new UNREDDLayerUpdate(); layerUpdate.setAttribute(UNREDDLayerUpdate.Attributes.LAYER, layername); layerUpdate.setAttribute(UNREDDLayerUpdate.Attributes.YEAR, year); if (month != null) { layerUpdate.setAttribute(UNREDDLayerUpdate.Attributes.MONTH, month); } if (day != null) { layerUpdate.setAttribute(UNREDDLayerUpdate.Attributes.DAY, day); } RESTResource res = layerUpdate.createRESTResource(); String resName = NameUtils.buildLayerUpdateName(layername, year, month, day); res.setName(resName); return res; } public String getConfigPassword() { return gspwd; } public String getConfigUrl() { return gsurl; } public String getConfigUsername() { return gsuser; } }
true
true
public void setStatsData(Resource statsDef, String statsContent, String year, String month, String day) throws GeoStoreException { try { Resource statsData = this.searchStatsData(statsDef.getName(), year, month, day); if (statsData == null) { LOGGER.info("No StatsData found for " + statsDef.getName() + ", Year=" + year + ", Month=" + month + ". Inserting StatsData"); insertStatsData(statsDef.getName(), year, month, statsContent, day); } else { long id = statsData.getId(); LOGGER.info("StatsData found for " + statsDef.getName() + ", Year=" + year + ", Month=" + month + ". Updating StatsData " + id); updateData(id, statsContent); } } catch (GeoStoreException ex) { throw ex; } catch (Exception ex) { LOGGER.error("Error computing stats: " + ex.getMessage(), ex); throw new GeoStoreException("Error while setting StatsData", ex); } }
public void setStatsData(Resource statsDef, String statsContent, String year, String month, String day) throws GeoStoreException { try { Resource statsData = this.searchStatsData(statsDef.getName(), year, month, day); if (statsData == null) { LOGGER.info("No StatsData found for " + statsDef.getName() + ", Year=" + year + ", Month=" + month + ". Inserting StatsData"); insertStatsData(statsDef.getName(), year, month, day, statsContent); } else { long id = statsData.getId(); LOGGER.info("StatsData found for " + statsDef.getName() + ", Year=" + year + ", Month=" + month + ". Updating StatsData " + id); updateData(id, statsContent); } } catch (GeoStoreException ex) { throw ex; } catch (Exception ex) { LOGGER.error("Error computing stats: " + ex.getMessage(), ex); throw new GeoStoreException("Error while setting StatsData", ex); } }
diff --git a/src/main/java/net/aufdemrand/denizen/scripts/commands/core/RunCommand.java b/src/main/java/net/aufdemrand/denizen/scripts/commands/core/RunCommand.java index 48ba327ff..194e373d6 100644 --- a/src/main/java/net/aufdemrand/denizen/scripts/commands/core/RunCommand.java +++ b/src/main/java/net/aufdemrand/denizen/scripts/commands/core/RunCommand.java @@ -1,236 +1,238 @@ package net.aufdemrand.denizen.scripts.commands.core; import java.util.List; import net.aufdemrand.denizen.exceptions.CommandExecutionException; import net.aufdemrand.denizen.exceptions.InvalidArgumentsException; import net.aufdemrand.denizen.objects.Duration; import net.aufdemrand.denizen.objects.Element; import net.aufdemrand.denizen.objects.aH; import net.aufdemrand.denizen.objects.dList; import net.aufdemrand.denizen.objects.dNPC; import net.aufdemrand.denizen.objects.dPlayer; import net.aufdemrand.denizen.objects.dScript; import net.aufdemrand.denizen.scripts.ScriptEntry; import net.aufdemrand.denizen.scripts.commands.AbstractCommand; import net.aufdemrand.denizen.scripts.commands.Holdable; import net.aufdemrand.denizen.scripts.queues.ScriptQueue; import net.aufdemrand.denizen.scripts.queues.core.InstantQueue; import net.aufdemrand.denizen.scripts.queues.core.TimedQueue; import net.aufdemrand.denizen.utilities.debugging.dB; /** * Runs a task script in a new ScriptQueue. * This replaces the now-deprecated runtask command with queue argument. * * @author Jeremy Schroeder * */ public class RunCommand extends AbstractCommand implements Holdable { // <--[example] // @Title Using Local Scripts tutorial // @Description // Use local scripts as a way to avoid making unnecessary script containers // or to group together utility task scripts. // // @Code // # +-------------------- // # | Using Local Scripts tutorial // # | // # | Since Script Containers are stored inside Denizen on a global level, // # | the problem of duplicate container names can become a problem. // # | // # | Using local scripts can be a good way to avoid situations by cutting // # | down on the amount of total script containers needed by allowing task utility // # | scripts to be included in other containers, or grouped together in a single // # | container. // // Local Script Tutorial: // type: task // // # As you probably already know, to run a 'base script' inside a task script // # the 'run' or 'inject' commands can be used. This requires the name of the // # script container as an argument in the commands. For example, type // # /ex run 's@Local Script Tutorial' .. to run the script // # below. // // script: // - narrate "This is the 'base script' of this task script container." // - narrate "The current time is <util.date.time>!" // // // # Local Script support by Denizen allows you to stash more scripts. Just specify // # a new node. To run this script from other containers, specify the script as well as // # the local script name node with a 'p' or 'path:' prefix. For example, to run the // # script below, type /ex run 's@Local Script Tutorial' 'p:subscript_1' // // subscript_1: // - narrate "This is a 'local script' in the task script container 'LocalScript Tutorial'." // // # But wait, there's more! If wanting to run a local script that is within the // # same container, the run command can be even simpler by specifying 'local' // # in place of the script name. Take a look at the next two local scripts. Type // # /ex run 's@Local Script Tutorial' 'p:subscript_2' .. to run the script below // # which will in turn run 'subscript_3' locally. Notice if you specify locally, // # the script used is // // subscript_2: // - narrate "This is the second 'local script' in this task script container." // - narrate "This script will now run 'subscript_3'." // - run locally 'subscript_3' // // subscript_3: // - narrate "Done. This has been a message from subscript_3!" // // // # There you have it! Three separate scripts inside a single task script container! // # Both the 'run' command and 'inject' command support local scripts. // // --> @Override public void parseArgs(ScriptEntry scriptEntry) throws InvalidArgumentsException { for (aH.Argument arg : aH.interpret(scriptEntry.getArguments())) { if (arg.matchesPrefix("i", "id")) scriptEntry.addObject("id", arg.asElement()); else if (arg.matchesPrefix("a", "as") && arg.matchesArgumentType(dPlayer.class)) scriptEntry.setPlayer(arg.asType(dPlayer.class)); else if (arg.matchesPrefix("a", "as") && arg.matchesArgumentType(dNPC.class)) scriptEntry.setNPC(arg.asType(dNPC.class)); // Catch invalid entry for 'as' argument else if (arg.matchesPrefix("a", "as")) dB.echoDebug(scriptEntry, "Specified target was not attached. Value must contain a valid PLAYER or NPC object."); else if (arg.matchesPrefix("d", "def", "define", "c", "context")) scriptEntry.addObject("definitions", arg.asType(dList.class)); else if (arg.matches("instant", "instantly")) scriptEntry.addObject("instant", new Element(true)); else if (arg.matchesPrefix("delay") && arg.matchesArgumentType(Duration.class)) scriptEntry.addObject("delay", arg.asType(Duration.class)); else if (arg.matches("local", "locally")) scriptEntry.addObject("local", new Element(true)); else if (!scriptEntry.hasObject("script") && arg.matchesArgumentType(dScript.class) && !arg.matchesPrefix("p", "path")) scriptEntry.addObject("script", arg.asType(dScript.class)); else if (!scriptEntry.hasObject("path")) scriptEntry.addObject("path", arg.asElement()); else arg.reportUnhandled(); } if (!scriptEntry.hasObject("script") && !scriptEntry.hasObject("local")) throw new InvalidArgumentsException("Must define a SCRIPT to be run."); if (!scriptEntry.hasObject("path") && scriptEntry.hasObject("local")) throw new InvalidArgumentsException("Must specify a PATH."); } @Override public void execute(ScriptEntry scriptEntry) throws CommandExecutionException { dB.report(scriptEntry, getName(), (scriptEntry.hasObject("script") ? scriptEntry.getdObject("script").debug() : scriptEntry.getScript().debug()) + (scriptEntry.hasObject("instant") ? scriptEntry.getdObject("instant").debug() : "") + (scriptEntry.hasObject("path") ? scriptEntry.getElement("path").debug() : "") + (scriptEntry.hasObject("local") ? scriptEntry.getElement("local").debug() : "") + (scriptEntry.hasObject("delay") ? scriptEntry.getdObject("delay").debug() : "") + (scriptEntry.hasObject("id") ? scriptEntry.getdObject("id").debug() : "")); // Get the script dScript script = (dScript) scriptEntry.getObject("script"); // Get the entries List<ScriptEntry> entries; // If it's local - if (scriptEntry.hasObject("local")) + if (scriptEntry.hasObject("local")) { entries = scriptEntry.getScript().getContainer().getEntries( scriptEntry.getPlayer(), scriptEntry.getNPC(), scriptEntry.getElement("path").asString()); + script = scriptEntry.getScript(); + } // If it has a path else if (scriptEntry.hasObject("path") && scriptEntry.getObject("path") != null) entries = script.getContainer().getEntries( scriptEntry.getPlayer(), scriptEntry.getNPC(), scriptEntry.getElement("path").asString()); // Else, assume standard path else entries = script.getContainer().getBaseEntries( scriptEntry.getPlayer(), scriptEntry.getNPC()); // Get the 'id' if specified String id = (scriptEntry.hasObject("id") ? (scriptEntry.getElement("id")).asString() : ScriptQueue._getNextId()); // Build the queue ScriptQueue queue; if (scriptEntry.hasObject("instant")) { queue = InstantQueue.getQueue(id).addEntries(entries); scriptEntry.setFinished(true); } else { queue = TimedQueue.getQueue(id).addEntries(entries); // Check speed of the script if a TimedQueue -- if identified, use the speed from the script. - if (script != null && script.getContainer().contains("speed")) - ((TimedQueue) queue).setSpeed(Duration.valueOf(script.getContainer().getString("speed")).getTicks()); + if (script != null && script.getContainer().contains("SPEED")) + ((TimedQueue) queue).setSpeed(Duration.valueOf(script.getContainer().getString("SPEED", "0")).getTicks()); } // Set any delay if (scriptEntry.hasObject("delay")) queue.delayUntil(System.currentTimeMillis() + ((Duration) scriptEntry.getObject("delay")).getMillis()); // Set any definitions if (scriptEntry.hasObject("definitions")) { int x = 1; dList definitions = (dList) scriptEntry.getObject("definitions"); String[] definition_names = null; try { definition_names = script.getContainer().getString("definitions").split("\\|"); } catch (Exception e) { } for (String definition : definitions) { String name = definition_names != null && definition_names.length >= x ? definition_names[x - 1].trim() : String.valueOf(x); queue.addDefinition(name, definition); dB.echoDebug(scriptEntry, "Adding definition %" + name + "% as " + definition); x++; } } // Setup a callback if the queue is being waited on if (scriptEntry.shouldWaitFor()) { // Record the ScriptEntry final ScriptEntry se = scriptEntry; queue.callBack(new Runnable() { @Override public void run() { se.setFinished(true); } }); } // OK, GO! queue.start(); } }
false
true
public void execute(ScriptEntry scriptEntry) throws CommandExecutionException { dB.report(scriptEntry, getName(), (scriptEntry.hasObject("script") ? scriptEntry.getdObject("script").debug() : scriptEntry.getScript().debug()) + (scriptEntry.hasObject("instant") ? scriptEntry.getdObject("instant").debug() : "") + (scriptEntry.hasObject("path") ? scriptEntry.getElement("path").debug() : "") + (scriptEntry.hasObject("local") ? scriptEntry.getElement("local").debug() : "") + (scriptEntry.hasObject("delay") ? scriptEntry.getdObject("delay").debug() : "") + (scriptEntry.hasObject("id") ? scriptEntry.getdObject("id").debug() : "")); // Get the script dScript script = (dScript) scriptEntry.getObject("script"); // Get the entries List<ScriptEntry> entries; // If it's local if (scriptEntry.hasObject("local")) entries = scriptEntry.getScript().getContainer().getEntries( scriptEntry.getPlayer(), scriptEntry.getNPC(), scriptEntry.getElement("path").asString()); // If it has a path else if (scriptEntry.hasObject("path") && scriptEntry.getObject("path") != null) entries = script.getContainer().getEntries( scriptEntry.getPlayer(), scriptEntry.getNPC(), scriptEntry.getElement("path").asString()); // Else, assume standard path else entries = script.getContainer().getBaseEntries( scriptEntry.getPlayer(), scriptEntry.getNPC()); // Get the 'id' if specified String id = (scriptEntry.hasObject("id") ? (scriptEntry.getElement("id")).asString() : ScriptQueue._getNextId()); // Build the queue ScriptQueue queue; if (scriptEntry.hasObject("instant")) { queue = InstantQueue.getQueue(id).addEntries(entries); scriptEntry.setFinished(true); } else { queue = TimedQueue.getQueue(id).addEntries(entries); // Check speed of the script if a TimedQueue -- if identified, use the speed from the script. if (script != null && script.getContainer().contains("speed")) ((TimedQueue) queue).setSpeed(Duration.valueOf(script.getContainer().getString("speed")).getTicks()); } // Set any delay if (scriptEntry.hasObject("delay")) queue.delayUntil(System.currentTimeMillis() + ((Duration) scriptEntry.getObject("delay")).getMillis()); // Set any definitions if (scriptEntry.hasObject("definitions")) { int x = 1; dList definitions = (dList) scriptEntry.getObject("definitions"); String[] definition_names = null; try { definition_names = script.getContainer().getString("definitions").split("\\|"); } catch (Exception e) { } for (String definition : definitions) { String name = definition_names != null && definition_names.length >= x ? definition_names[x - 1].trim() : String.valueOf(x); queue.addDefinition(name, definition); dB.echoDebug(scriptEntry, "Adding definition %" + name + "% as " + definition); x++; } } // Setup a callback if the queue is being waited on if (scriptEntry.shouldWaitFor()) { // Record the ScriptEntry final ScriptEntry se = scriptEntry; queue.callBack(new Runnable() { @Override public void run() { se.setFinished(true); } }); } // OK, GO! queue.start(); }
public void execute(ScriptEntry scriptEntry) throws CommandExecutionException { dB.report(scriptEntry, getName(), (scriptEntry.hasObject("script") ? scriptEntry.getdObject("script").debug() : scriptEntry.getScript().debug()) + (scriptEntry.hasObject("instant") ? scriptEntry.getdObject("instant").debug() : "") + (scriptEntry.hasObject("path") ? scriptEntry.getElement("path").debug() : "") + (scriptEntry.hasObject("local") ? scriptEntry.getElement("local").debug() : "") + (scriptEntry.hasObject("delay") ? scriptEntry.getdObject("delay").debug() : "") + (scriptEntry.hasObject("id") ? scriptEntry.getdObject("id").debug() : "")); // Get the script dScript script = (dScript) scriptEntry.getObject("script"); // Get the entries List<ScriptEntry> entries; // If it's local if (scriptEntry.hasObject("local")) { entries = scriptEntry.getScript().getContainer().getEntries( scriptEntry.getPlayer(), scriptEntry.getNPC(), scriptEntry.getElement("path").asString()); script = scriptEntry.getScript(); } // If it has a path else if (scriptEntry.hasObject("path") && scriptEntry.getObject("path") != null) entries = script.getContainer().getEntries( scriptEntry.getPlayer(), scriptEntry.getNPC(), scriptEntry.getElement("path").asString()); // Else, assume standard path else entries = script.getContainer().getBaseEntries( scriptEntry.getPlayer(), scriptEntry.getNPC()); // Get the 'id' if specified String id = (scriptEntry.hasObject("id") ? (scriptEntry.getElement("id")).asString() : ScriptQueue._getNextId()); // Build the queue ScriptQueue queue; if (scriptEntry.hasObject("instant")) { queue = InstantQueue.getQueue(id).addEntries(entries); scriptEntry.setFinished(true); } else { queue = TimedQueue.getQueue(id).addEntries(entries); // Check speed of the script if a TimedQueue -- if identified, use the speed from the script. if (script != null && script.getContainer().contains("SPEED")) ((TimedQueue) queue).setSpeed(Duration.valueOf(script.getContainer().getString("SPEED", "0")).getTicks()); } // Set any delay if (scriptEntry.hasObject("delay")) queue.delayUntil(System.currentTimeMillis() + ((Duration) scriptEntry.getObject("delay")).getMillis()); // Set any definitions if (scriptEntry.hasObject("definitions")) { int x = 1; dList definitions = (dList) scriptEntry.getObject("definitions"); String[] definition_names = null; try { definition_names = script.getContainer().getString("definitions").split("\\|"); } catch (Exception e) { } for (String definition : definitions) { String name = definition_names != null && definition_names.length >= x ? definition_names[x - 1].trim() : String.valueOf(x); queue.addDefinition(name, definition); dB.echoDebug(scriptEntry, "Adding definition %" + name + "% as " + definition); x++; } } // Setup a callback if the queue is being waited on if (scriptEntry.shouldWaitFor()) { // Record the ScriptEntry final ScriptEntry se = scriptEntry; queue.callBack(new Runnable() { @Override public void run() { se.setFinished(true); } }); } // OK, GO! queue.start(); }
diff --git a/src/plugin/languageidentifier/src/test/org/apache/nutch/analysis/lang/TestLanguageIdentifier.java b/src/plugin/languageidentifier/src/test/org/apache/nutch/analysis/lang/TestLanguageIdentifier.java index 902ed411..160f4e8f 100644 --- a/src/plugin/languageidentifier/src/test/org/apache/nutch/analysis/lang/TestLanguageIdentifier.java +++ b/src/plugin/languageidentifier/src/test/org/apache/nutch/analysis/lang/TestLanguageIdentifier.java @@ -1,242 +1,242 @@ /** * Copyright 2005 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.nutch.analysis.lang; // JDK imports import java.io.InputStream; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.util.List; import java.util.Iterator; // JUnit imports import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import junit.textui.TestRunner; // Lucene imports import org.apache.lucene.analysis.Token; /** * JUnit based test of class {@link LanguageIdentifier}. * * @author Sami Siren * @author Jerome Charron - http://frutch.free.fr/ */ public class TestLanguageIdentifier extends TestCase { public TestLanguageIdentifier(String testName) { super(testName); } public static Test suite() { return new TestSuite(TestLanguageIdentifier.class); } public static void main(String[] args) { TestRunner.run(suite()); } String tokencontent1 = "testaddtoken"; String tokencontent2 = "anotherteststring"; int[] counts1 = { 3, 2, 2, 1, 1, 1, 1, 1 }; String[] chars1 = { "t", "d", "e", "a", "k", "n", "o", "s" }; /** * Test addFromToken method * */ public void testAddToken() { NGramProfile p = new NGramProfile("test", 1, 1); Token t = new Token(tokencontent1, 0, tokencontent1.length()); p.add(t); p.normalize(); testCounts(p.getSorted(), counts1); testContents(p.getSorted(), chars1); } /** * Test analyze method */ public void testAnalyze() { String tokencontent = "testmeagain"; NGramProfile p = new NGramProfile("test", 1, 1); p.analyze(new StringBuffer(tokencontent)); //test that profile size is ok, eg 9 different NGramEntries "tesmagin" assertEquals(8, p.getSorted().size()); } /** * Test addNGrams method with StringBuffer argument * */ public void testAddNGramsStringBuffer() { String tokencontent = "testmeagain"; NGramProfile p = new NGramProfile("test", 1, 1); p.add(new StringBuffer(tokencontent)); //test that profile size is ok, eg 8 different NGramEntries "tesmagin" assertEquals(8, p.getSorted().size()); } /** * test getSorted method */ public void testGetSorted() { int[] count = { 4, 3, 1 }; String[] ngram = { "a", "b", "c" }; String teststring = "AAaaBbbC"; NGramProfile p = new NGramProfile("test", 1, 1); p.analyze(new StringBuffer(teststring)); //test size of profile assertEquals(3, p.getSorted().size()); testCounts(p.getSorted(), count); testContents(p.getSorted(), ngram); } public void testGetSimilarity() { NGramProfile a = new NGramProfile("a", 1, 1); NGramProfile b = new NGramProfile("b", 1, 1); a.analyze(new StringBuffer(tokencontent1)); b.analyze(new StringBuffer(tokencontent2)); //because of rounding errors might slightly return different results assertEquals(a.getSimilarity(b), b.getSimilarity(a), 0.0000002); } public void testExactMatch() { NGramProfile a = new NGramProfile("a", 1, 1); a.analyze(new StringBuffer(tokencontent1)); assertEquals(a.getSimilarity(a), 0, 0); } public void testIO() { //Create profile and set some contents NGramProfile a = new NGramProfile("a", 1, 1); a.analyze(new StringBuffer(this.tokencontent1)); NGramProfile b = new NGramProfile("a_from_inputstream", 1, 1); //save profile ByteArrayOutputStream os = new ByteArrayOutputStream(); try { a.save(os); os.close(); } catch (Exception e) { fail(); } //load profile InputStream is = new ByteArrayInputStream(os.toByteArray()); try { b.load(is); is.close(); } catch (Exception e) { fail(); } //check it testCounts(b.getSorted(), counts1); testContents(b.getSorted(), chars1); } private void testContents(List entries, String contents[]) { int c = 0; Iterator i = entries.iterator(); while (i.hasNext()) { NGramProfile.NGramEntry nge = (NGramProfile.NGramEntry) i.next(); assertEquals(contents[c], nge.getSeq().toString()); c++; } } private void testCounts(List entries, int counts[]) { int c = 0; Iterator i = entries.iterator(); while (i.hasNext()) { NGramProfile.NGramEntry nge = (NGramProfile.NGramEntry) i.next(); System.out.println(nge); assertEquals(counts[c], nge.getCount()); c++; } } public void testIdentify() { try { long total = 0; LanguageIdentifier idfr = LanguageIdentifier.getInstance(); BufferedReader in = new BufferedReader(new InputStreamReader( this.getClass().getResourceAsStream("test-referencial.txt"))); String line = null; while((line = in.readLine()) != null) { String[] tokens = line.split(";"); if (!tokens[0].equals("")) { long start = System.currentTimeMillis(); // Identify the whole file - String lang = idfr.identify(this.getClass().getResourceAsStream(tokens[0])); + String lang = idfr.identify(this.getClass().getResourceAsStream(tokens[0]), "UTF-8"); total += System.currentTimeMillis() - start; assertEquals(tokens[1], lang); // Then, each line of the file... BufferedReader testFile = new BufferedReader( new InputStreamReader( this.getClass().getResourceAsStream(tokens[0]), "UTF-8")); String testLine = null; while((testLine = testFile.readLine()) != null) { testLine = testLine.trim(); if (testLine.length() > 256) { lang = idfr.identify(testLine); assertEquals(tokens[1], lang); } } testFile.close(); } } in.close(); System.out.println("Total Time=" + total); } catch(Exception e) { e.printStackTrace(); fail(e.toString()); } } }
true
true
public void testIdentify() { try { long total = 0; LanguageIdentifier idfr = LanguageIdentifier.getInstance(); BufferedReader in = new BufferedReader(new InputStreamReader( this.getClass().getResourceAsStream("test-referencial.txt"))); String line = null; while((line = in.readLine()) != null) { String[] tokens = line.split(";"); if (!tokens[0].equals("")) { long start = System.currentTimeMillis(); // Identify the whole file String lang = idfr.identify(this.getClass().getResourceAsStream(tokens[0])); total += System.currentTimeMillis() - start; assertEquals(tokens[1], lang); // Then, each line of the file... BufferedReader testFile = new BufferedReader( new InputStreamReader( this.getClass().getResourceAsStream(tokens[0]), "UTF-8")); String testLine = null; while((testLine = testFile.readLine()) != null) { testLine = testLine.trim(); if (testLine.length() > 256) { lang = idfr.identify(testLine); assertEquals(tokens[1], lang); } } testFile.close(); } } in.close(); System.out.println("Total Time=" + total); } catch(Exception e) { e.printStackTrace(); fail(e.toString()); } }
public void testIdentify() { try { long total = 0; LanguageIdentifier idfr = LanguageIdentifier.getInstance(); BufferedReader in = new BufferedReader(new InputStreamReader( this.getClass().getResourceAsStream("test-referencial.txt"))); String line = null; while((line = in.readLine()) != null) { String[] tokens = line.split(";"); if (!tokens[0].equals("")) { long start = System.currentTimeMillis(); // Identify the whole file String lang = idfr.identify(this.getClass().getResourceAsStream(tokens[0]), "UTF-8"); total += System.currentTimeMillis() - start; assertEquals(tokens[1], lang); // Then, each line of the file... BufferedReader testFile = new BufferedReader( new InputStreamReader( this.getClass().getResourceAsStream(tokens[0]), "UTF-8")); String testLine = null; while((testLine = testFile.readLine()) != null) { testLine = testLine.trim(); if (testLine.length() > 256) { lang = idfr.identify(testLine); assertEquals(tokens[1], lang); } } testFile.close(); } } in.close(); System.out.println("Total Time=" + total); } catch(Exception e) { e.printStackTrace(); fail(e.toString()); } }
diff --git a/webapp/lib/src/main/java/com/github/podd/impl/PoddArtifactManagerImpl.java b/webapp/lib/src/main/java/com/github/podd/impl/PoddArtifactManagerImpl.java index 46a44b7c..9e8b2c84 100644 --- a/webapp/lib/src/main/java/com/github/podd/impl/PoddArtifactManagerImpl.java +++ b/webapp/lib/src/main/java/com/github/podd/impl/PoddArtifactManagerImpl.java @@ -1,1625 +1,1625 @@ /** * */ package com.github.podd.impl; import info.aduna.iteration.Iterations; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Set; import java.util.UUID; import org.openrdf.OpenRDFException; import org.openrdf.model.Literal; import org.openrdf.model.Model; import org.openrdf.model.Resource; import org.openrdf.model.Statement; import org.openrdf.model.URI; import org.openrdf.model.Value; import org.openrdf.model.impl.LinkedHashModel; import org.openrdf.model.impl.ValueFactoryImpl; import org.openrdf.model.vocabulary.OWL; import org.openrdf.model.vocabulary.RDF; import org.openrdf.model.vocabulary.RDFS; import org.openrdf.repository.Repository; import org.openrdf.repository.RepositoryConnection; import org.openrdf.repository.RepositoryException; import org.openrdf.repository.RepositoryResult; import org.openrdf.rio.RDFFormat; import org.openrdf.rio.Rio; import org.semanticweb.owlapi.model.IRI; import org.semanticweb.owlapi.model.OWLException; import org.semanticweb.owlapi.model.OWLOntology; import org.semanticweb.owlapi.model.OWLOntologyID; import org.semanticweb.owlapi.profiles.OWLProfileReport; import org.semanticweb.owlapi.profiles.OWLProfileViolation; import org.semanticweb.owlapi.reasoner.OWLReasoner; import org.semanticweb.owlapi.rio.RioMemoryTripleSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.github.podd.api.DanglingObjectPolicy; import com.github.podd.api.DataReferenceVerificationPolicy; import com.github.podd.api.MetadataPolicy; import com.github.podd.api.PoddArtifactManager; import com.github.podd.api.PoddOWLManager; import com.github.podd.api.PoddRepositoryManager; import com.github.podd.api.PoddSchemaManager; import com.github.podd.api.PoddSesameManager; import com.github.podd.api.UpdatePolicy; import com.github.podd.api.file.DataReference; import com.github.podd.api.file.DataReferenceManager; import com.github.podd.api.file.PoddDataRepositoryManager; import com.github.podd.api.purl.PoddPurlManager; import com.github.podd.api.purl.PoddPurlReference; import com.github.podd.exception.DeleteArtifactException; import com.github.podd.exception.DisconnectedObjectException; import com.github.podd.exception.EmptyOntologyException; import com.github.podd.exception.FileReferenceVerificationFailureException; import com.github.podd.exception.InconsistentOntologyException; import com.github.podd.exception.OntologyNotInProfileException; import com.github.podd.exception.PoddException; import com.github.podd.exception.PoddRuntimeException; import com.github.podd.exception.PublishArtifactException; import com.github.podd.exception.PurlProcessorNotHandledException; import com.github.podd.exception.UnmanagedArtifactIRIException; import com.github.podd.exception.UnmanagedSchemaIRIException; import com.github.podd.utils.InferredOWLOntologyID; import com.github.podd.utils.OntologyUtils; import com.github.podd.utils.PoddObjectLabel; import com.github.podd.utils.PoddRdfConstants; import com.github.podd.utils.RdfUtility; /** * Implementation of the PODD Artifact Manager API, to manage the lifecycle for PODD Artifacts. * * @author Peter Ansell [email protected] * */ public class PoddArtifactManagerImpl implements PoddArtifactManager { private final Logger log = LoggerFactory.getLogger(this.getClass()); private DataReferenceManager dataReferenceManager; private PoddDataRepositoryManager dataRepositoryManager; private PoddOWLManager owlManager; private PoddPurlManager purlManager; private PoddSchemaManager schemaManager; private PoddRepositoryManager repositoryManager; private PoddSesameManager sesameManager; /** * */ public PoddArtifactManagerImpl() { } @Override public InferredOWLOntologyID attachFileReference(final InferredOWLOntologyID artifactId, final URI objectUri, final DataReference dataReference) throws OpenRDFException, PoddException { throw new RuntimeException("TODO: Implement attachFileReference"); } @Override public InferredOWLOntologyID attachFileReferences(final URI artifactUri, final URI versionUri, final InputStream inputStream, final RDFFormat format, final DataReferenceVerificationPolicy dataReferenceVerificationPolicy) throws OpenRDFException, IOException, OWLException, PoddException { final Model model = Rio.parse(inputStream, "", format); model.removeAll(model.filter(null, PoddRdfConstants.PODD_BASE_INFERRED_VERSION, null)); final Set<Resource> fileReferences = model.filter(null, RDF.TYPE, PoddRdfConstants.PODD_BASE_DATA_REFERENCE_TYPE).subjects(); final Collection<URI> fileReferenceObjects = new ArrayList<URI>(fileReferences.size()); for(final Resource nextFileReference : fileReferences) { if(nextFileReference instanceof URI) { fileReferenceObjects.add((URI)nextFileReference); } else { this.log.warn("Will not be updating file reference for blank node reference, will instead be creating a new file reference for it."); } } final ByteArrayOutputStream output = new ByteArrayOutputStream(8192); Rio.write(model, output, RDFFormat.RDFJSON); final Model resultModel = this.updateArtifact(artifactUri, versionUri, fileReferenceObjects, new ByteArrayInputStream(output.toByteArray()), RDFFormat.RDFJSON, UpdatePolicy.MERGE_WITH_EXISTING, DanglingObjectPolicy.REPORT, dataReferenceVerificationPolicy); return OntologyUtils.modelToOntologyIDs(resultModel).get(0); } @Override public boolean deleteArtifact(final InferredOWLOntologyID artifactId) throws PoddException { if(artifactId.getOntologyIRI() == null) { throw new PoddRuntimeException("Ontology IRI cannot be null"); } RepositoryConnection connection = null; try { connection = this.getRepositoryManager().getRepository().getConnection(); List<InferredOWLOntologyID> requestedArtifactIds = this.getSesameManager().getAllOntologyVersions(artifactId.getOntologyIRI(), connection, this.getRepositoryManager().getArtifactManagementGraph()); if(artifactId.getVersionIRI() != null) { final IRI requestedVersionIRI = artifactId.getVersionIRI(); for(final InferredOWLOntologyID nextVersion : new ArrayList<InferredOWLOntologyID>(requestedArtifactIds)) { if(requestedVersionIRI.equals(nextVersion.getVersionIRI())) { requestedArtifactIds = Arrays.asList(nextVersion); } } } connection.begin(); this.getSesameManager().deleteOntologies(requestedArtifactIds, connection, this.getRepositoryManager().getArtifactManagementGraph()); connection.commit(); return !requestedArtifactIds.isEmpty(); } catch(final OpenRDFException e) { try { if(connection != null && connection.isActive()) { connection.rollback(); } } catch(final RepositoryException e1) { this.log.error("Found error rolling back repository connection", e1); } throw new DeleteArtifactException("Repository exception occurred", e, artifactId); } finally { try { if(connection != null && connection.isOpen()) { connection.close(); } } catch(final RepositoryException e) { throw new DeleteArtifactException("Repository exception occurred", e, artifactId); } } } @Override public void exportArtifact(final InferredOWLOntologyID ontologyId, final OutputStream outputStream, final RDFFormat format, final boolean includeInferred) throws OpenRDFException, PoddException, IOException { if(ontologyId.getOntologyIRI() == null || ontologyId.getVersionIRI() == null) { throw new PoddRuntimeException("Ontology IRI and Version IRI cannot be null"); } if(includeInferred && ontologyId.getInferredOntologyIRI() == null) { throw new PoddRuntimeException("Inferred Ontology IRI cannot be null"); } List<URI> contexts; if(includeInferred) { contexts = Arrays.asList(ontologyId.getVersionIRI().toOpenRDFURI(), ontologyId.getInferredOntologyIRI() .toOpenRDFURI()); } else { contexts = Arrays.asList(ontologyId.getVersionIRI().toOpenRDFURI()); } RepositoryConnection connection = null; try { connection = this.getRepositoryManager().getRepository().getConnection(); connection.export(Rio.createWriter(format, outputStream), contexts.toArray(new Resource[] {})); } finally { if(connection != null) { connection.close(); } } } @Override public void exportObjectMetadata(final URI objectType, final OutputStream outputStream, final RDFFormat format, final boolean includeDoNotDisplayProperties, MetadataPolicy containsPropertyPolicy, final InferredOWLOntologyID artifactID) throws OpenRDFException, PoddException, IOException { RepositoryConnection connection = null; try { connection = this.getRepositoryManager().getRepository().getConnection(); final URI[] contexts = this.sesameManager.versionAndSchemaContexts(artifactID, connection, this.repositoryManager.getSchemaManagementGraph()); Model model = null; if(containsPropertyPolicy == MetadataPolicy.ONLY_CONTAINS) { model = this.sesameManager.getObjectTypeContainsMetadata(objectType, connection, contexts); } else { model = this.sesameManager.getObjectTypeMetadata(objectType, includeDoNotDisplayProperties, containsPropertyPolicy, connection, contexts); } Rio.write(model, outputStream, format); } finally { if(connection != null) { connection.close(); } } } @Override public Model fillMissingData(final InferredOWLOntologyID ontologyID, final Model inputModel) throws OpenRDFException { RepositoryConnection conn = null; try { conn = this.getRepositoryManager().getRepository().getConnection(); final URI[] contexts = this.getSesameManager().versionAndSchemaContexts(ontologyID, conn, this.getRepositoryManager().getSchemaManagementGraph()); return this.getSesameManager().fillMissingLabels(inputModel, conn, contexts); } catch(final OpenRDFException e) { try { if(conn != null && conn.isActive()) { conn.rollback(); } } catch(final RepositoryException e1) { this.log.error("Found error rolling back repository connection", e1); } throw e; } finally { try { if(conn != null && conn.isOpen()) { conn.close(); } } catch(final RepositoryException e) { throw e; } } } @Override public InferredOWLOntologyID getArtifact(final IRI artifactIRI) throws UnmanagedArtifactIRIException { return getArtifact(artifactIRI, null); } @Override public InferredOWLOntologyID getArtifact(final IRI artifactIRI, final IRI versionIRI) throws UnmanagedArtifactIRIException { RepositoryConnection repositoryConnection = null; try { repositoryConnection = this.getRepositoryManager().getRepository().getConnection(); InferredOWLOntologyID result = null; if(versionIRI != null) { result = this.getSesameManager().getOntologyVersion(versionIRI, repositoryConnection, this.getRepositoryManager().getArtifactManagementGraph()); } if(result == null) { result = this.getSesameManager().getCurrentArtifactVersion(artifactIRI, repositoryConnection, this.getRepositoryManager().getArtifactManagementGraph()); } if(result != null) { // If the result that was returned contained a different artifact IRI then throw an // exception early instead of returning inconsistent results if(!result.getOntologyIRI().equals(artifactIRI) && !result.getVersionIRI().equals(artifactIRI)) { throw new UnmanagedArtifactIRIException(artifactIRI, "Artifact IRI and Version IRI combination did not match"); } } return result; } catch(final OpenRDFException e) { throw new UnmanagedArtifactIRIException(artifactIRI, e); } finally { if(repositoryConnection != null) { try { repositoryConnection.close(); } catch(final RepositoryException e) { this.log.error("Failed to close repository connection", e); } } } } /* * (non-Javadoc) * * @see com.github.podd.api.PoddArtifactManager#getFileReferenceManager() */ @Override public DataReferenceManager getFileReferenceManager() { return this.dataReferenceManager; } @Override public Set<DataReference> getFileReferences(final InferredOWLOntologyID artifactId) { // TODO Auto-generated method stub return null; } @Override public Set<DataReference> getFileReferences(final InferredOWLOntologyID artifactId, final String alias) { // TODO Auto-generated method stub return null; } @Override public Set<DataReference> getFileReferences(final InferredOWLOntologyID artifactId, final URI objectUri) { // TODO Auto-generated method stub return null; } /* * (non-Javadoc) * * @see com.github.podd.api.PoddArtifactManager#getFileRepositoryManager() */ @Override public PoddDataRepositoryManager getFileRepositoryManager() { return this.dataRepositoryManager; } /* * (non-Javadoc) * * Wraps PoddSesameManager.getObjectDetailsForDisplay() * * @see com.github.podd.api.PoddArtifactManager#getObjectDetailsForDisplay() */ @Override public Model getObjectDetailsForDisplay(final InferredOWLOntologyID ontologyID, final URI objectUri) throws OpenRDFException { RepositoryConnection conn = null; try { conn = this.getRepositoryManager().getRepository().getConnection(); return this.getSesameManager().getObjectDetailsForDisplay(ontologyID, objectUri, conn); } finally { conn.close(); } } @Override public PoddObjectLabel getObjectLabel(final InferredOWLOntologyID ontologyID, final URI objectUri) throws OpenRDFException { RepositoryConnection conn = null; try { conn = this.getRepositoryManager().getRepository().getConnection(); return this.getSesameManager().getObjectLabel(ontologyID, objectUri, conn); } finally { conn.close(); } } /* * (non-Javadoc) * * @see com.github.podd.api.PoddArtifactManager#getObjectTypes(com.github.podd.utils. * InferredOWLOntologyID, org.openrdf.model.URI) */ @Override public List<PoddObjectLabel> getObjectTypes(final InferredOWLOntologyID artifactId, final URI objectUri) throws OpenRDFException { final List<PoddObjectLabel> results = new ArrayList<PoddObjectLabel>(); RepositoryConnection conn = null; try { conn = this.getRepositoryManager().getRepository().getConnection(); List<URI> typesList = this.getSesameManager().getObjectTypes(artifactId, objectUri, conn); for(URI objectType : typesList) { results.add(this.getSesameManager().getObjectLabel(artifactId, objectType, conn)); } } finally { conn.close(); } return results; } /* * (non-Javadoc) * * Wraps PoddSesameManager.getOrderedProperties() * * @see com.github.podd.api.PoddArtifactManager#getOrderedProperties() */ @Override public List<URI> getOrderedProperties(final InferredOWLOntologyID ontologyID, final URI objectUri, final boolean excludeContainsProperties) throws OpenRDFException { RepositoryConnection conn = null; try { conn = this.getRepositoryManager().getRepository().getConnection(); final URI[] contexts = this.getSesameManager().versionAndSchemaContexts(ontologyID, conn, this.getRepositoryManager().getSchemaManagementGraph()); return this.getSesameManager().getWeightedProperties(objectUri, excludeContainsProperties, conn, contexts); } finally { conn.close(); } } /* * (non-Javadoc) * * @see com.github.podd.api.PoddArtifactManager#getOWLManager() */ @Override public PoddOWLManager getOWLManager() { return this.owlManager; } /* * (non-Javadoc) * * @see com.github.podd.api.PoddArtifactManager#getParentDetails(com.github.podd.utils. * InferredOWLOntologyID, org.openrdf.model.URI) */ @Override public Model getParentDetails(InferredOWLOntologyID ontologyID, URI objectUri) throws OpenRDFException { RepositoryConnection conn = null; try { conn = this.getRepositoryManager().getRepository().getConnection(); final URI[] contexts = this.getSesameManager().versionAndSchemaContexts(ontologyID, conn, this.getRepositoryManager().getSchemaManagementGraph()); return this.getSesameManager().getParentDetails(objectUri, conn, contexts); } catch(final OpenRDFException e) { try { if(conn != null && conn.isActive()) { conn.rollback(); } } catch(final RepositoryException e1) { this.log.error("Found error rolling back repository connection", e1); } throw e; } finally { try { if(conn != null && conn.isOpen()) { conn.close(); } } catch(final RepositoryException e) { throw e; } } } /* * (non-Javadoc) * * @see com.github.podd.api.PoddArtifactManager#getPurlManager() */ @Override public PoddPurlManager getPurlManager() { return this.purlManager; } @Override public PoddRepositoryManager getRepositoryManager() { return this.repositoryManager; } @Override public PoddSchemaManager getSchemaManager() { return this.schemaManager; } @Override public PoddSesameManager getSesameManager() { return this.sesameManager; } @Override public List<PoddObjectLabel> getTopObjectLabels(final List<InferredOWLOntologyID> artifacts) throws OpenRDFException { final List<PoddObjectLabel> results = new ArrayList<PoddObjectLabel>(); RepositoryConnection conn = null; try { conn = this.getRepositoryManager().getRepository().getConnection(); for(final InferredOWLOntologyID artifactId : artifacts) { URI objectIRI = this.getSesameManager().getTopObjectIRI(artifactId, conn); results.add(this.getSesameManager().getObjectLabel(artifactId, objectIRI, conn)); } } finally { conn.close(); } return results; } /** * Helper method to cache schema ontologies in memory before loading statements into OWLAPI */ private void handleCacheSchemasInMemory(final RepositoryConnection permanentRepositoryConnection, final RepositoryConnection tempRepositoryConnection, final URI tempContext) throws OpenRDFException, OWLException, IOException, PoddException { final Set<IRI> importedSchemas = this.getSesameManager().getDirectImports(tempRepositoryConnection, tempContext); for(final IRI importedSchemaIRI : importedSchemas) { final InferredOWLOntologyID ontologyVersion = this.getSesameManager().getSchemaVersion(importedSchemaIRI, permanentRepositoryConnection, this.getRepositoryManager().getSchemaManagementGraph()); this.getOWLManager().cacheSchemaOntology(ontologyVersion, permanentRepositoryConnection, this.getRepositoryManager().getSchemaManagementGraph()); } } /** * Checks for dangling objects that are not linked to the artifact and deletes them if * <i>force</i> is true. * * @param artifactID * @param repositoryConnection * @param context * @param force * If true, deletes any dangling objects. If false, throws a * DisconnectedObjectException if any dangling objects are found. * @throws RepositoryException * @throws DisconnectedObjectException */ private void handleDanglingObjects(final IRI artifactID, final RepositoryConnection repositoryConnection, final URI context, final DanglingObjectPolicy policy) throws RepositoryException, DisconnectedObjectException { final Set<URI> danglingObjects = RdfUtility.findDisconnectedNodes(artifactID.toOpenRDFURI(), repositoryConnection, context); this.log.info("Found {} dangling object(s). \n {}", danglingObjects.size(), danglingObjects); if(danglingObjects.isEmpty()) { return; } if(policy.equals(DanglingObjectPolicy.REPORT)) { throw new DisconnectedObjectException(danglingObjects, "Update leads to disconnected PODD objects"); } else if(policy.equals(DanglingObjectPolicy.FORCE_CLEAN)) { for(final URI danglingObject : danglingObjects) { repositoryConnection.remove(danglingObject, null, null, context); repositoryConnection.remove(null, null, (Value)danglingObject, context); } } } /** * Helper method to handle File References in a newly loaded/updated set of statements. * * TODO: Optionally remove invalid file references or mark them as invalid using RDF * statements/OWL Classes * * @param repositoryConnection * @param context * @param policy * If true, verifies that DataReference objects are accessible from their respective * remote File Repositories * * @throws OpenRDFException * @throws PoddException */ private void handleFileReferences(final RepositoryConnection repositoryConnection, final DataReferenceVerificationPolicy policy, final URI... contexts) throws OpenRDFException, PoddException { if(this.getFileReferenceManager() == null) { return; } this.log.info("Handling File reference validation"); final Set<DataReference> fileReferenceResults = this.getFileReferenceManager().extractDataReferences(repositoryConnection, contexts); if(DataReferenceVerificationPolicy.VERIFY.equals(policy)) { try { this.dataRepositoryManager.verifyDataReferences(fileReferenceResults); } catch(final FileReferenceVerificationFailureException e) { this.log.warn("From " + fileReferenceResults.size() + " file references, " + e.getValidationFailures().size() + " failed validation."); throw e; } } } /** * Helper method to handle File References in a newly loaded/updated set of statements */ private Set<PoddPurlReference> handlePurls(final RepositoryConnection repositoryConnection, final URI context) throws PurlProcessorNotHandledException, OpenRDFException { if(this.getPurlManager() != null) { this.log.info("Handling Purl generation"); final Set<PoddPurlReference> purlResults = this.getPurlManager().extractPurlReferences(repositoryConnection, context); this.getPurlManager().convertTemporaryUris(purlResults, repositoryConnection, context); return purlResults; } return Collections.emptySet(); } /** * Helper method to check schema ontology imports and update use of ontology IRIs to version * IRIs. */ private void handleSchemaImports(final IRI ontologyIRI, final RepositoryConnection permanentRepositoryConnection, final RepositoryConnection tempRepositoryConnection, final URI tempContext) throws OpenRDFException, UnmanagedSchemaIRIException { final Set<IRI> importedSchemas = this.getSesameManager().getDirectImports(tempRepositoryConnection, tempContext); for(final IRI importedSchemaIRI : importedSchemas) { final InferredOWLOntologyID schemaOntologyID = this.getSesameManager().getSchemaVersion(importedSchemaIRI, permanentRepositoryConnection, this.getRepositoryManager().getSchemaManagementGraph()); if(!importedSchemaIRI.equals(schemaOntologyID.getVersionIRI())) { // modify import to be a specific version of the schema this.log.info("Updating import to version <{}>", schemaOntologyID.getVersionIRI()); tempRepositoryConnection.remove(ontologyIRI.toOpenRDFURI(), OWL.IMPORTS, importedSchemaIRI.toOpenRDFURI(), tempContext); tempRepositoryConnection.add(ontologyIRI.toOpenRDFURI(), OWL.IMPORTS, schemaOntologyID.getVersionIRI() .toOpenRDFURI(), tempContext); } } } /** * This helper method checks for statements with the given property and having a date-time value * with the year 1970 and updates their date-time with the given {@link Value}. * * @param repositoryConnection * @param propertyUri * @param newTimestamp * @param context * @throws OpenRDFException */ private void handleTimestamps(final RepositoryConnection repositoryConnection, final URI propertyUri, final Value newTimestamp, final URI context) throws OpenRDFException { final List<Statement> statements = Iterations.asList(repositoryConnection.getStatements(null, propertyUri, null, false, context)); for(Statement s : statements) { final Value object = s.getObject(); if(object instanceof Literal) { final int year = ((Literal)object).calendarValue().getYear(); if(year == 1970) { repositoryConnection.remove(s, context); repositoryConnection.add(s.getSubject(), s.getPredicate(), newTimestamp, context); } } } } /** * This is not an API method. QUESTION: Should this be moved to a separate utility class? * * This method takes a String terminating with a colon (":") followed by an integer and * increments this integer by one. If the input String is not of the expected format, appends * "1" to the end of the String. * * E.g.: "http://purl.org/ab/artifact:55" is converted to "http://purl.org/ab/artifact:56" * "http://purl.org/ab/artifact:5A" is converted to "http://purl.org/ab/artifact:5A1" * * @param oldVersion * @return */ public String incrementVersion(final String oldVersion) { final char versionSeparatorChar = ':'; final int positionVersionSeparator = oldVersion.lastIndexOf(versionSeparatorChar); if(positionVersionSeparator > 1) { final String prefix = oldVersion.substring(0, positionVersionSeparator); final String version = oldVersion.substring(positionVersionSeparator + 1); try { int versionInt = Integer.parseInt(version); versionInt++; return prefix + versionSeparatorChar + versionInt; } catch(final NumberFormatException e) { return oldVersion.concat("1"); } } return oldVersion.concat("1"); } private List<InferredOWLOntologyID> listArtifacts(final boolean published, final boolean unpublished) throws OpenRDFException { if(!published && !unpublished) { throw new IllegalArgumentException("Cannot choose to exclude both published and unpublished artifacts"); } final List<InferredOWLOntologyID> results = new ArrayList<InferredOWLOntologyID>(); RepositoryConnection conn = null; try { conn = this.getRepositoryManager().getRepository().getConnection(); final Collection<InferredOWLOntologyID> ontologies = this.getSesameManager().getOntologies(true, conn, this.getRepositoryManager().getArtifactManagementGraph()); for(final InferredOWLOntologyID nextOntology : ontologies) { final boolean isPublished = this.getSesameManager().isPublished(nextOntology, conn, this.getRepositoryManager().getArtifactManagementGraph()); if(isPublished) { if(published) { results.add(nextOntology); } } else if(unpublished) { results.add(nextOntology); } } } finally { if(conn != null && conn.isOpen()) { conn.close(); } } return results; } @Override public List<InferredOWLOntologyID> listPublishedArtifacts() throws OpenRDFException { return this.listArtifacts(true, false); } @Override public List<InferredOWLOntologyID> listUnpublishedArtifacts() throws OpenRDFException { return this.listArtifacts(false, true); } /* * (non-Javadoc) * * @see com.github.podd.api.PoddArtifactManager#loadArtifact(java.io.InputStream, * org.openrdf.rio.RDFFormat) */ @Override public InferredOWLOntologyID loadArtifact(final InputStream inputStream, RDFFormat format) throws OpenRDFException, PoddException, IOException, OWLException { if(inputStream == null) { throw new NullPointerException("Input stream must not be null"); } if(format == null) { format = RDFFormat.RDFXML; } // connection to the temporary repository that the artifact RDF triples will be stored while // they are initially parsed by OWLAPI. final Repository tempRepository = this.repositoryManager.getNewTemporaryRepository(); RepositoryConnection temporaryRepositoryConnection = null; RepositoryConnection permanentRepositoryConnection = null; InferredOWLOntologyID inferredOWLOntologyID = null; try { temporaryRepositoryConnection = tempRepository.getConnection(); final URI randomContext = ValueFactoryImpl.getInstance().createURI("urn:uuid:" + UUID.randomUUID().toString()); // Load the artifact RDF triples into a random context in the temp repository, which may // be shared between different uploads temporaryRepositoryConnection.add(inputStream, "", format, randomContext); this.handlePurls(temporaryRepositoryConnection, randomContext); final Repository permanentRepository = this.getRepositoryManager().getRepository(); permanentRepositoryConnection = permanentRepository.getConnection(); permanentRepositoryConnection.begin(); // Set a Version IRI for this artifact /* * Version information need not be available in uploaded artifacts (any existing values * are ignored). * * For a new artifact, a Version IRI is created based on the Ontology IRI while for a * new version of a managed artifact, the most recent version is incremented. */ final IRI ontologyIRI = this.getSesameManager().getOntologyIRI(temporaryRepositoryConnection, randomContext); if(ontologyIRI != null) { // check for managed version from artifact graph OWLOntologyID currentManagedArtifactID = null; try { currentManagedArtifactID = this.getSesameManager().getCurrentArtifactVersion(ontologyIRI, permanentRepositoryConnection, this.getRepositoryManager().getArtifactManagementGraph()); } catch(final UnmanagedArtifactIRIException e) { // ignore. indicates a new artifact is being uploaded this.log.info("This is an unmanaged artifact IRI {}", ontologyIRI); } IRI newVersionIRI = null; if(currentManagedArtifactID == null || currentManagedArtifactID.getVersionIRI() == null) { newVersionIRI = IRI.create(ontologyIRI.toString() + ":version:1"); } else { newVersionIRI = IRI.create(this.incrementVersion(currentManagedArtifactID.getVersionIRI().toString())); } // set version IRI in temporary repository this.log.info("Setting version IRI to <{}>", newVersionIRI); temporaryRepositoryConnection.remove(ontologyIRI.toOpenRDFURI(), PoddRdfConstants.OWL_VERSION_IRI, null, randomContext); temporaryRepositoryConnection.add(ontologyIRI.toOpenRDFURI(), PoddRdfConstants.OWL_VERSION_IRI, newVersionIRI.toOpenRDFURI(), randomContext); } else { throw new EmptyOntologyException(null, "Loaded ontology is empty"); } // check and update statements with default timestamp values final Value now = PoddRdfConstants.VF.createLiteral(new Date()); this.handleTimestamps(temporaryRepositoryConnection, PoddRdfConstants.PODD_BASE_CREATED_AT, now, randomContext); this.handleTimestamps(temporaryRepositoryConnection, PoddRdfConstants.PODD_BASE_LAST_MODIFIED, now, randomContext); this.handleDanglingObjects(ontologyIRI, temporaryRepositoryConnection, randomContext, DanglingObjectPolicy.REPORT); // check and ensure schema ontology imports are for version IRIs this.handleSchemaImports(ontologyIRI, permanentRepositoryConnection, temporaryRepositoryConnection, randomContext); // ensure schema ontologies are cached in memory before loading statements into OWLAPI this.handleCacheSchemasInMemory(permanentRepositoryConnection, permanentRepositoryConnection, randomContext); // TODO: This web service could be used accidentally to insert invalid file references inferredOWLOntologyID = this.loadInferStoreArtifact(temporaryRepositoryConnection, permanentRepositoryConnection, randomContext, DataReferenceVerificationPolicy.DO_NOT_VERIFY); permanentRepositoryConnection.commit(); return inferredOWLOntologyID; } catch(final Exception e) { if(temporaryRepositoryConnection != null && temporaryRepositoryConnection.isActive()) { temporaryRepositoryConnection.rollback(); } if(permanentRepositoryConnection != null && permanentRepositoryConnection.isActive()) { permanentRepositoryConnection.rollback(); } throw e; } finally { // release resources if(inferredOWLOntologyID != null) { this.getOWLManager().removeCache(inferredOWLOntologyID); } if(temporaryRepositoryConnection != null && temporaryRepositoryConnection.isOpen()) { try { temporaryRepositoryConnection.close(); } catch(final RepositoryException e) { this.log.error("Found exception closing repository connection", e); } } tempRepository.shutDown(); if(permanentRepositoryConnection != null && permanentRepositoryConnection.isOpen()) { try { permanentRepositoryConnection.close(); } catch(final RepositoryException e) { this.log.error("Found exception closing repository connection", e); } } } } /** * Helper method to load the artifact into OWLAPI from a temporary location, perform reasoning * and store in permanent repository. * * @param fileReferencePolicy */ private InferredOWLOntologyID loadInferStoreArtifact(final RepositoryConnection tempRepositoryConnection, final RepositoryConnection permanentRepositoryConnection, final URI tempContext, final DataReferenceVerificationPolicy fileReferencePolicy) throws OpenRDFException, OWLException, IOException, PoddException, OntologyNotInProfileException, InconsistentOntologyException { // load into OWLAPI this.log.debug("Loading podd artifact from temp repository: {}", tempContext); final List<Statement> statements = Iterations.asList(tempRepositoryConnection.getStatements(null, null, null, true, tempContext)); final RioMemoryTripleSource owlSource = new RioMemoryTripleSource(statements.iterator()); owlSource.setNamespaces(tempRepositoryConnection.getNamespaces()); final OWLOntology nextOntology = this.getOWLManager().loadOntology(owlSource); // Check the OWLAPI OWLOntology against an OWLProfile to make sure it is in profile final OWLProfileReport profileReport = this.getOWLManager().getReasonerProfile().checkOntology(nextOntology); if(!profileReport.isInProfile()) { this.getOWLManager().removeCache(nextOntology.getOntologyID()); if(this.log.isInfoEnabled()) { for(OWLProfileViolation violation : profileReport.getViolations()) { this.log.info(violation.toString()); } } throw new OntologyNotInProfileException(nextOntology, profileReport, "Ontology is not in required OWL Profile"); } // Use the OWLManager to create a reasoner over the ontology final OWLReasoner nextReasoner = this.getOWLManager().createReasoner(nextOntology); // Test that the ontology was consistent with this reasoner // This ensures in the case of Pellet that it is in the OWL2-DL profile if(!nextReasoner.isConsistent()) { this.getOWLManager().removeCache(nextOntology.getOntologyID()); throw new InconsistentOntologyException(nextReasoner, "Ontology is inconsistent"); } // Copy the statements to permanentRepositoryConnection this.getOWLManager().dumpOntologyToRepository(nextOntology, permanentRepositoryConnection, nextOntology.getOntologyID().getVersionIRI().toOpenRDFURI()); // NOTE: At this stage, a client could be notified, and the artifact could be streamed // back to them from permanentRepositoryConnection // Use an OWLAPI InferredAxiomGenerator together with the reasoner to create inferred // axioms to store in the database. // Serialise the inferred statements back to a different context in the permanent // repository connection. // The contexts to use within the permanent repository connection are all encapsulated // in the InferredOWLOntologyID object. final InferredOWLOntologyID inferredOWLOntologyID = this.getOWLManager().inferStatements(nextOntology, permanentRepositoryConnection); // Check file references after inferencing to accurately identify the parent object this.handleFileReferences(permanentRepositoryConnection, fileReferencePolicy, inferredOWLOntologyID .getVersionIRI().toOpenRDFURI(), inferredOWLOntologyID.getInferredOntologyIRI().toOpenRDFURI()); this.getSesameManager().updateManagedPoddArtifactVersion(inferredOWLOntologyID, true, permanentRepositoryConnection, this.getRepositoryManager().getArtifactManagementGraph()); return inferredOWLOntologyID; } /* * (non-Javadoc) * * @see com.github.podd.api.PoddArtifactManager#publishArtifact(org.semanticweb.owlapi.model. * OWLOntologyID) */ @Override public InferredOWLOntologyID publishArtifact(final InferredOWLOntologyID ontologyId) throws OpenRDFException, PublishArtifactException, UnmanagedArtifactIRIException { final IRI ontologyIRI = ontologyId.getOntologyIRI(); final IRI versionIRI = ontologyId.getVersionIRI(); if(versionIRI == null) { throw new PublishArtifactException("Could not publish artifact as version was not specified.", ontologyId); } Repository repository = null; RepositoryConnection repositoryConnection = null; try { repository = this.getRepositoryManager().getRepository(); repositoryConnection = repository.getConnection(); repositoryConnection.begin(); if(this.getSesameManager().isPublished(ontologyId, repositoryConnection, this.getRepositoryManager().getArtifactManagementGraph())) { // Cannot publish multiple versions of a single artifact throw new PublishArtifactException("Could not publish artifact as a version was already published", ontologyId); } final InferredOWLOntologyID currentVersion = this.getSesameManager().getCurrentArtifactVersion(ontologyIRI, repositoryConnection, this.getRepositoryManager().getArtifactManagementGraph()); if(!currentVersion.getVersionIRI().equals(versionIRI)) { // User must make the given artifact version the current version manually before // publishing, to ensure that work from the current version is not lost accidentally throw new PublishArtifactException( "Could not publish artifact as it was not the most current version.", ontologyId); } this.getSesameManager().setPublished(currentVersion, repositoryConnection, this.getRepositoryManager().getArtifactManagementGraph()); final InferredOWLOntologyID published = this.getSesameManager().getCurrentArtifactVersion(ontologyIRI, repositoryConnection, this.getRepositoryManager().getArtifactManagementGraph()); repositoryConnection.commit(); return published; } catch(final OpenRDFException | PublishArtifactException | UnmanagedArtifactIRIException e) { if(repositoryConnection != null && repositoryConnection.isActive()) { repositoryConnection.rollback(); } throw e; } finally { // release resources if(repositoryConnection != null && repositoryConnection.isOpen()) { try { repositoryConnection.close(); } catch(final RepositoryException e) { this.log.error("Found exception closing repository connection", e); } } } } /* * (non-Javadoc) * * @see * com.github.podd.api.PoddArtifactManager#searchForOntologyLabels(org.semanticweb.owlapi.model. * OWLOntologyID, java.lang.String, org.openrdf.model.URI[]) */ @Override public Model searchForOntologyLabels(final InferredOWLOntologyID ontologyID, final String searchTerm, final URI[] searchTypes) throws OpenRDFException { RepositoryConnection conn = null; try { conn = this.getRepositoryManager().getRepository().getConnection(); final URI[] contexts = this.getSesameManager().versionAndSchemaContexts(ontologyID, conn, this.getRepositoryManager().getSchemaManagementGraph()); return this.getSesameManager().searchOntologyLabels(searchTerm, searchTypes, 1000, 0, conn, contexts); } catch(final OpenRDFException e) { try { if(conn != null && conn.isActive()) { conn.rollback(); } } catch(final RepositoryException e1) { this.log.error("Found error rolling back repository connection", e1); } throw e; } finally { try { if(conn != null && conn.isOpen()) { conn.close(); } } catch(final RepositoryException e) { throw e; } } } /* * (non-Javadoc) * * @see * com.github.podd.api.PoddArtifactManager#setFileReferenceManager(com.github.podd.api.file. * PoddFileReferenceManager) */ @Override public void setDataReferenceManager(final DataReferenceManager fileManager) { this.dataReferenceManager = fileManager; } /* * (non-Javadoc) * * @see * com.github.podd.api.PoddArtifactManager#setFileRepositoryManager(com.github.podd.api.file * .PoddFileRepositoryManager) */ @Override public void setDataRepositoryManager(final PoddDataRepositoryManager dataRepositoryManager) { this.dataRepositoryManager = dataRepositoryManager; } /* * (non-Javadoc) * * @see * com.github.podd.api.PoddArtifactManager#setOwlManager(com.github.podd.api.PoddOWLManager) */ @Override public void setOwlManager(final PoddOWLManager owlManager) { this.owlManager = owlManager; } /* * (non-Javadoc) * * @see * com.github.podd.api.PoddArtifactManager#setPurlManager(com.github.podd.api.purl.PoddPurlManager * ) */ @Override public void setPurlManager(final PoddPurlManager purlManager) { this.purlManager = purlManager; } @Override public void setRepositoryManager(final PoddRepositoryManager repositoryManager) { this.repositoryManager = repositoryManager; } @Override public void setSchemaManager(final PoddSchemaManager schemaManager) { this.schemaManager = schemaManager; } @Override public void setSesameManager(final PoddSesameManager sesameManager) { this.sesameManager = sesameManager; } /* * (non-Javadoc) * * @see com.github.podd.api.PoddArtifactManager#updateArtifact(org.openrdf.model.URI, * java.io.InputStream, org.openrdf.rio.RDFFormat) */ @Override public Model updateArtifact(final URI artifactUri, final URI versionUri, final Collection<URI> objectUris, final InputStream inputStream, RDFFormat format, final UpdatePolicy updatePolicy, final DanglingObjectPolicy danglingObjectAction, final DataReferenceVerificationPolicy fileReferenceAction) throws OpenRDFException, IOException, OWLException, PoddException { if(inputStream == null) { throw new NullPointerException("Input stream must not be null"); } if(format == null) { format = RDFFormat.RDFXML; } // check if updating from the most current version of the artifact InferredOWLOntologyID artifactID = null; try { artifactID = this.getArtifact(IRI.create(versionUri)); } catch(final UnmanagedArtifactIRIException e) { // if the version IRI is not the most current, it is unmanaged final InferredOWLOntologyID currentArtifactID = this.getArtifact(IRI.create(artifactUri)); final String message = - "Attempting to update from an older version of an artifact. <" + versionUri - + "> has been succeeded by <" + currentArtifactID.getVersionIRI().toString() + ">"; + "Attempting to update from an older version of an artifact. [" + versionUri + + "] has been succeeded by [" + currentArtifactID.getVersionIRI().toString() + "]"; this.log.error(message); throw new UnmanagedArtifactIRIException(IRI.create(versionUri), message, e); // FIXME - handle this conflict intelligently instead of rejecting the update. } final Repository tempRepository = this.getRepositoryManager().getNewTemporaryRepository(); RepositoryConnection tempRepositoryConnection = null; RepositoryConnection permanentRepositoryConnection = null; InferredOWLOntologyID inferredOWLOntologyID = null; try { // create a temporary in-memory repository tempRepositoryConnection = tempRepository.getConnection(); tempRepositoryConnection.begin(); permanentRepositoryConnection = this.getRepositoryManager().getRepository().getConnection(); permanentRepositoryConnection.begin(); // load and copy the artifact's concrete statements to the temporary store final RepositoryResult<Statement> repoResult = permanentRepositoryConnection.getStatements(null, null, null, false, artifactID.getVersionIRI() .toOpenRDFURI()); final URI tempContext = artifactID.getVersionIRI().toOpenRDFURI(); tempRepositoryConnection.add(repoResult, tempContext); // update the artifact statements if(UpdatePolicy.REPLACE_EXISTING.equals(updatePolicy)) { // create an intermediate context and add "edit" statements to it final URI intContext = PoddRdfConstants.VF.createURI("urn:intermediate:", UUID.randomUUID().toString()); tempRepositoryConnection.add(inputStream, "", format, intContext); final Collection<URI> replaceableObjects = new ArrayList<URI>(objectUris); // If they did not send a list, we create one ourselves. if(replaceableObjects.isEmpty()) { // get all Subjects in "edit" statements final RepositoryResult<Statement> statements = tempRepositoryConnection.getStatements(null, null, null, false, intContext); final List<Statement> allEditStatements = Iterations.addAll(statements, new ArrayList<Statement>()); // remove all references to these Subjects in "main" context for(final Statement statement : allEditStatements) { if(statement.getSubject() instanceof URI) { replaceableObjects.add((URI)statement.getSubject()); } else { // We do not support replacing objects that are not referenced using // URIs, so they must stay for REPLACE_EXISTING // To remove blank node subject statements, replace the entire object // using REPLACE_ALL } } } for(final URI nextReplaceableObject : replaceableObjects) { tempRepositoryConnection.remove(nextReplaceableObject, null, null, tempContext); } // copy the "edit" statements from intermediate context into our "main" context tempRepositoryConnection.add( tempRepositoryConnection.getStatements(null, null, null, false, intContext), tempContext); } else { tempRepositoryConnection.add(inputStream, "", format, tempContext); } // check and update statements with default timestamp values final Value now = PoddRdfConstants.VF.createLiteral(new Date()); this.handleTimestamps(tempRepositoryConnection, PoddRdfConstants.PODD_BASE_CREATED_AT, now, tempContext); this.handleTimestamps(tempRepositoryConnection, PoddRdfConstants.PODD_BASE_LAST_MODIFIED, now, tempContext); this.handleDanglingObjects(artifactID.getOntologyIRI(), tempRepositoryConnection, tempContext, danglingObjectAction); final Set<PoddPurlReference> purls = this.handlePurls(tempRepositoryConnection, tempContext); final Model resultsModel = new LinkedHashModel(); // add (temp-object-URI :hasPurl PURL) statements to Model // NOTE: Using nested loops is rather inefficient, but these collections are not // expected // to have more than a handful of elements for(URI objectUri : objectUris) { for(PoddPurlReference purl : purls) { final URI tempUri = purl.getTemporaryURI(); if(objectUri.equals(tempUri)) { resultsModel.add(objectUri, PoddRdfConstants.PODD_REPLACED_TEMP_URI_WITH, purl.getPurlURI()); break; // out of inner loop } } } // this.handleFileReferences(tempRepositoryConnection, tempContext, // fileReferenceAction); // increment the version final OWLOntologyID currentManagedArtifactID = this.getSesameManager().getCurrentArtifactVersion(IRI.create(artifactUri), permanentRepositoryConnection, this.getRepositoryManager().getArtifactManagementGraph()); final IRI newVersionIRI = IRI.create(this.incrementVersion(currentManagedArtifactID.getVersionIRI().toString())); // set version IRI in temporary repository this.log.info("Setting version IRI to <{}>", newVersionIRI); tempRepositoryConnection.remove(artifactID.getOntologyIRI().toOpenRDFURI(), PoddRdfConstants.OWL_VERSION_IRI, null, tempContext); tempRepositoryConnection.add(artifactID.getOntologyIRI().toOpenRDFURI(), PoddRdfConstants.OWL_VERSION_IRI, newVersionIRI.toOpenRDFURI(), tempContext); // check and ensure schema ontology imports are for version IRIs this.handleSchemaImports(artifactID.getOntologyIRI(), permanentRepositoryConnection, tempRepositoryConnection, tempContext); // ensure schema ontologies are cached in memory before loading statements into OWLAPI this.handleCacheSchemasInMemory(permanentRepositoryConnection, tempRepositoryConnection, tempContext); inferredOWLOntologyID = this.loadInferStoreArtifact(tempRepositoryConnection, permanentRepositoryConnection, tempContext, fileReferenceAction); permanentRepositoryConnection.commit(); tempRepositoryConnection.rollback(); return OntologyUtils.ontologyIDsToModel(Arrays.asList(inferredOWLOntologyID), resultsModel); } catch(final Exception e) { if(tempRepositoryConnection != null && tempRepositoryConnection.isActive()) { tempRepositoryConnection.rollback(); } if(permanentRepositoryConnection != null && permanentRepositoryConnection.isActive()) { permanentRepositoryConnection.rollback(); } throw e; } finally { // release resources if(inferredOWLOntologyID != null) { this.getOWLManager().removeCache(inferredOWLOntologyID); } if(tempRepositoryConnection != null && tempRepositoryConnection.isOpen()) { try { tempRepositoryConnection.close(); } catch(final RepositoryException e) { this.log.error("Found exception closing repository connection", e); } } tempRepository.shutDown(); if(permanentRepositoryConnection != null && permanentRepositoryConnection.isOpen()) { try { permanentRepositoryConnection.close(); } catch(final RepositoryException e) { this.log.error("Found exception closing repository connection", e); } } } } @Override public InferredOWLOntologyID updateSchemaImports(final InferredOWLOntologyID artifactId, final Set<OWLOntologyID> oldSchemaOntologyIds, final Set<OWLOntologyID> schemaOntologyId) { throw new RuntimeException("TODO: Implement updateSchemaImport"); } }
true
true
public Model updateArtifact(final URI artifactUri, final URI versionUri, final Collection<URI> objectUris, final InputStream inputStream, RDFFormat format, final UpdatePolicy updatePolicy, final DanglingObjectPolicy danglingObjectAction, final DataReferenceVerificationPolicy fileReferenceAction) throws OpenRDFException, IOException, OWLException, PoddException { if(inputStream == null) { throw new NullPointerException("Input stream must not be null"); } if(format == null) { format = RDFFormat.RDFXML; } // check if updating from the most current version of the artifact InferredOWLOntologyID artifactID = null; try { artifactID = this.getArtifact(IRI.create(versionUri)); } catch(final UnmanagedArtifactIRIException e) { // if the version IRI is not the most current, it is unmanaged final InferredOWLOntologyID currentArtifactID = this.getArtifact(IRI.create(artifactUri)); final String message = "Attempting to update from an older version of an artifact. <" + versionUri + "> has been succeeded by <" + currentArtifactID.getVersionIRI().toString() + ">"; this.log.error(message); throw new UnmanagedArtifactIRIException(IRI.create(versionUri), message, e); // FIXME - handle this conflict intelligently instead of rejecting the update. } final Repository tempRepository = this.getRepositoryManager().getNewTemporaryRepository(); RepositoryConnection tempRepositoryConnection = null; RepositoryConnection permanentRepositoryConnection = null; InferredOWLOntologyID inferredOWLOntologyID = null; try { // create a temporary in-memory repository tempRepositoryConnection = tempRepository.getConnection(); tempRepositoryConnection.begin(); permanentRepositoryConnection = this.getRepositoryManager().getRepository().getConnection(); permanentRepositoryConnection.begin(); // load and copy the artifact's concrete statements to the temporary store final RepositoryResult<Statement> repoResult = permanentRepositoryConnection.getStatements(null, null, null, false, artifactID.getVersionIRI() .toOpenRDFURI()); final URI tempContext = artifactID.getVersionIRI().toOpenRDFURI(); tempRepositoryConnection.add(repoResult, tempContext); // update the artifact statements if(UpdatePolicy.REPLACE_EXISTING.equals(updatePolicy)) { // create an intermediate context and add "edit" statements to it final URI intContext = PoddRdfConstants.VF.createURI("urn:intermediate:", UUID.randomUUID().toString()); tempRepositoryConnection.add(inputStream, "", format, intContext); final Collection<URI> replaceableObjects = new ArrayList<URI>(objectUris); // If they did not send a list, we create one ourselves. if(replaceableObjects.isEmpty()) { // get all Subjects in "edit" statements final RepositoryResult<Statement> statements = tempRepositoryConnection.getStatements(null, null, null, false, intContext); final List<Statement> allEditStatements = Iterations.addAll(statements, new ArrayList<Statement>()); // remove all references to these Subjects in "main" context for(final Statement statement : allEditStatements) { if(statement.getSubject() instanceof URI) { replaceableObjects.add((URI)statement.getSubject()); } else { // We do not support replacing objects that are not referenced using // URIs, so they must stay for REPLACE_EXISTING // To remove blank node subject statements, replace the entire object // using REPLACE_ALL } } } for(final URI nextReplaceableObject : replaceableObjects) { tempRepositoryConnection.remove(nextReplaceableObject, null, null, tempContext); } // copy the "edit" statements from intermediate context into our "main" context tempRepositoryConnection.add( tempRepositoryConnection.getStatements(null, null, null, false, intContext), tempContext); } else { tempRepositoryConnection.add(inputStream, "", format, tempContext); } // check and update statements with default timestamp values final Value now = PoddRdfConstants.VF.createLiteral(new Date()); this.handleTimestamps(tempRepositoryConnection, PoddRdfConstants.PODD_BASE_CREATED_AT, now, tempContext); this.handleTimestamps(tempRepositoryConnection, PoddRdfConstants.PODD_BASE_LAST_MODIFIED, now, tempContext); this.handleDanglingObjects(artifactID.getOntologyIRI(), tempRepositoryConnection, tempContext, danglingObjectAction); final Set<PoddPurlReference> purls = this.handlePurls(tempRepositoryConnection, tempContext); final Model resultsModel = new LinkedHashModel(); // add (temp-object-URI :hasPurl PURL) statements to Model // NOTE: Using nested loops is rather inefficient, but these collections are not // expected // to have more than a handful of elements for(URI objectUri : objectUris) { for(PoddPurlReference purl : purls) { final URI tempUri = purl.getTemporaryURI(); if(objectUri.equals(tempUri)) { resultsModel.add(objectUri, PoddRdfConstants.PODD_REPLACED_TEMP_URI_WITH, purl.getPurlURI()); break; // out of inner loop } } } // this.handleFileReferences(tempRepositoryConnection, tempContext, // fileReferenceAction); // increment the version final OWLOntologyID currentManagedArtifactID = this.getSesameManager().getCurrentArtifactVersion(IRI.create(artifactUri), permanentRepositoryConnection, this.getRepositoryManager().getArtifactManagementGraph()); final IRI newVersionIRI = IRI.create(this.incrementVersion(currentManagedArtifactID.getVersionIRI().toString())); // set version IRI in temporary repository this.log.info("Setting version IRI to <{}>", newVersionIRI); tempRepositoryConnection.remove(artifactID.getOntologyIRI().toOpenRDFURI(), PoddRdfConstants.OWL_VERSION_IRI, null, tempContext); tempRepositoryConnection.add(artifactID.getOntologyIRI().toOpenRDFURI(), PoddRdfConstants.OWL_VERSION_IRI, newVersionIRI.toOpenRDFURI(), tempContext); // check and ensure schema ontology imports are for version IRIs this.handleSchemaImports(artifactID.getOntologyIRI(), permanentRepositoryConnection, tempRepositoryConnection, tempContext); // ensure schema ontologies are cached in memory before loading statements into OWLAPI this.handleCacheSchemasInMemory(permanentRepositoryConnection, tempRepositoryConnection, tempContext); inferredOWLOntologyID = this.loadInferStoreArtifact(tempRepositoryConnection, permanentRepositoryConnection, tempContext, fileReferenceAction); permanentRepositoryConnection.commit(); tempRepositoryConnection.rollback(); return OntologyUtils.ontologyIDsToModel(Arrays.asList(inferredOWLOntologyID), resultsModel); } catch(final Exception e) { if(tempRepositoryConnection != null && tempRepositoryConnection.isActive()) { tempRepositoryConnection.rollback(); } if(permanentRepositoryConnection != null && permanentRepositoryConnection.isActive()) { permanentRepositoryConnection.rollback(); } throw e; } finally { // release resources if(inferredOWLOntologyID != null) { this.getOWLManager().removeCache(inferredOWLOntologyID); } if(tempRepositoryConnection != null && tempRepositoryConnection.isOpen()) { try { tempRepositoryConnection.close(); } catch(final RepositoryException e) { this.log.error("Found exception closing repository connection", e); } } tempRepository.shutDown(); if(permanentRepositoryConnection != null && permanentRepositoryConnection.isOpen()) { try { permanentRepositoryConnection.close(); } catch(final RepositoryException e) { this.log.error("Found exception closing repository connection", e); } } } }
public Model updateArtifact(final URI artifactUri, final URI versionUri, final Collection<URI> objectUris, final InputStream inputStream, RDFFormat format, final UpdatePolicy updatePolicy, final DanglingObjectPolicy danglingObjectAction, final DataReferenceVerificationPolicy fileReferenceAction) throws OpenRDFException, IOException, OWLException, PoddException { if(inputStream == null) { throw new NullPointerException("Input stream must not be null"); } if(format == null) { format = RDFFormat.RDFXML; } // check if updating from the most current version of the artifact InferredOWLOntologyID artifactID = null; try { artifactID = this.getArtifact(IRI.create(versionUri)); } catch(final UnmanagedArtifactIRIException e) { // if the version IRI is not the most current, it is unmanaged final InferredOWLOntologyID currentArtifactID = this.getArtifact(IRI.create(artifactUri)); final String message = "Attempting to update from an older version of an artifact. [" + versionUri + "] has been succeeded by [" + currentArtifactID.getVersionIRI().toString() + "]"; this.log.error(message); throw new UnmanagedArtifactIRIException(IRI.create(versionUri), message, e); // FIXME - handle this conflict intelligently instead of rejecting the update. } final Repository tempRepository = this.getRepositoryManager().getNewTemporaryRepository(); RepositoryConnection tempRepositoryConnection = null; RepositoryConnection permanentRepositoryConnection = null; InferredOWLOntologyID inferredOWLOntologyID = null; try { // create a temporary in-memory repository tempRepositoryConnection = tempRepository.getConnection(); tempRepositoryConnection.begin(); permanentRepositoryConnection = this.getRepositoryManager().getRepository().getConnection(); permanentRepositoryConnection.begin(); // load and copy the artifact's concrete statements to the temporary store final RepositoryResult<Statement> repoResult = permanentRepositoryConnection.getStatements(null, null, null, false, artifactID.getVersionIRI() .toOpenRDFURI()); final URI tempContext = artifactID.getVersionIRI().toOpenRDFURI(); tempRepositoryConnection.add(repoResult, tempContext); // update the artifact statements if(UpdatePolicy.REPLACE_EXISTING.equals(updatePolicy)) { // create an intermediate context and add "edit" statements to it final URI intContext = PoddRdfConstants.VF.createURI("urn:intermediate:", UUID.randomUUID().toString()); tempRepositoryConnection.add(inputStream, "", format, intContext); final Collection<URI> replaceableObjects = new ArrayList<URI>(objectUris); // If they did not send a list, we create one ourselves. if(replaceableObjects.isEmpty()) { // get all Subjects in "edit" statements final RepositoryResult<Statement> statements = tempRepositoryConnection.getStatements(null, null, null, false, intContext); final List<Statement> allEditStatements = Iterations.addAll(statements, new ArrayList<Statement>()); // remove all references to these Subjects in "main" context for(final Statement statement : allEditStatements) { if(statement.getSubject() instanceof URI) { replaceableObjects.add((URI)statement.getSubject()); } else { // We do not support replacing objects that are not referenced using // URIs, so they must stay for REPLACE_EXISTING // To remove blank node subject statements, replace the entire object // using REPLACE_ALL } } } for(final URI nextReplaceableObject : replaceableObjects) { tempRepositoryConnection.remove(nextReplaceableObject, null, null, tempContext); } // copy the "edit" statements from intermediate context into our "main" context tempRepositoryConnection.add( tempRepositoryConnection.getStatements(null, null, null, false, intContext), tempContext); } else { tempRepositoryConnection.add(inputStream, "", format, tempContext); } // check and update statements with default timestamp values final Value now = PoddRdfConstants.VF.createLiteral(new Date()); this.handleTimestamps(tempRepositoryConnection, PoddRdfConstants.PODD_BASE_CREATED_AT, now, tempContext); this.handleTimestamps(tempRepositoryConnection, PoddRdfConstants.PODD_BASE_LAST_MODIFIED, now, tempContext); this.handleDanglingObjects(artifactID.getOntologyIRI(), tempRepositoryConnection, tempContext, danglingObjectAction); final Set<PoddPurlReference> purls = this.handlePurls(tempRepositoryConnection, tempContext); final Model resultsModel = new LinkedHashModel(); // add (temp-object-URI :hasPurl PURL) statements to Model // NOTE: Using nested loops is rather inefficient, but these collections are not // expected // to have more than a handful of elements for(URI objectUri : objectUris) { for(PoddPurlReference purl : purls) { final URI tempUri = purl.getTemporaryURI(); if(objectUri.equals(tempUri)) { resultsModel.add(objectUri, PoddRdfConstants.PODD_REPLACED_TEMP_URI_WITH, purl.getPurlURI()); break; // out of inner loop } } } // this.handleFileReferences(tempRepositoryConnection, tempContext, // fileReferenceAction); // increment the version final OWLOntologyID currentManagedArtifactID = this.getSesameManager().getCurrentArtifactVersion(IRI.create(artifactUri), permanentRepositoryConnection, this.getRepositoryManager().getArtifactManagementGraph()); final IRI newVersionIRI = IRI.create(this.incrementVersion(currentManagedArtifactID.getVersionIRI().toString())); // set version IRI in temporary repository this.log.info("Setting version IRI to <{}>", newVersionIRI); tempRepositoryConnection.remove(artifactID.getOntologyIRI().toOpenRDFURI(), PoddRdfConstants.OWL_VERSION_IRI, null, tempContext); tempRepositoryConnection.add(artifactID.getOntologyIRI().toOpenRDFURI(), PoddRdfConstants.OWL_VERSION_IRI, newVersionIRI.toOpenRDFURI(), tempContext); // check and ensure schema ontology imports are for version IRIs this.handleSchemaImports(artifactID.getOntologyIRI(), permanentRepositoryConnection, tempRepositoryConnection, tempContext); // ensure schema ontologies are cached in memory before loading statements into OWLAPI this.handleCacheSchemasInMemory(permanentRepositoryConnection, tempRepositoryConnection, tempContext); inferredOWLOntologyID = this.loadInferStoreArtifact(tempRepositoryConnection, permanentRepositoryConnection, tempContext, fileReferenceAction); permanentRepositoryConnection.commit(); tempRepositoryConnection.rollback(); return OntologyUtils.ontologyIDsToModel(Arrays.asList(inferredOWLOntologyID), resultsModel); } catch(final Exception e) { if(tempRepositoryConnection != null && tempRepositoryConnection.isActive()) { tempRepositoryConnection.rollback(); } if(permanentRepositoryConnection != null && permanentRepositoryConnection.isActive()) { permanentRepositoryConnection.rollback(); } throw e; } finally { // release resources if(inferredOWLOntologyID != null) { this.getOWLManager().removeCache(inferredOWLOntologyID); } if(tempRepositoryConnection != null && tempRepositoryConnection.isOpen()) { try { tempRepositoryConnection.close(); } catch(final RepositoryException e) { this.log.error("Found exception closing repository connection", e); } } tempRepository.shutDown(); if(permanentRepositoryConnection != null && permanentRepositoryConnection.isOpen()) { try { permanentRepositoryConnection.close(); } catch(final RepositoryException e) { this.log.error("Found exception closing repository connection", e); } } } }
diff --git a/javamelody-core/src/main/java/net/bull/javamelody/SpringDataSourceBeanPostProcessor.java b/javamelody-core/src/main/java/net/bull/javamelody/SpringDataSourceBeanPostProcessor.java index d2e290fc..eee8b1de 100644 --- a/javamelody-core/src/main/java/net/bull/javamelody/SpringDataSourceBeanPostProcessor.java +++ b/javamelody-core/src/main/java/net/bull/javamelody/SpringDataSourceBeanPostProcessor.java @@ -1,102 +1,103 @@ /* * Copyright 2008-2010 by Emeric Vernat * * This file is part of Java Melody. * * Java Melody 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. * * Java Melody 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 Java Melody. If not, see <http://www.gnu.org/licenses/>. */ package net.bull.javamelody; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import javax.sql.DataSource; import org.springframework.beans.factory.config.BeanPostProcessor; import org.springframework.jndi.JndiObjectFactoryBean; /** * Post-processor Spring pour une éventuelle DataSource défini dans le fichier xml Spring. * @author Emeric Vernat */ public class SpringDataSourceBeanPostProcessor implements BeanPostProcessor { /** {@inheritDoc} */ public Object postProcessBeforeInitialization(Object bean, String beanName) { return bean; } /** {@inheritDoc} */ - public Object postProcessAfterInitialization(final Object bean, String beanName) { + public Object postProcessAfterInitialization(final Object bean, final String beanName) { if (bean instanceof DataSource) { final DataSource dataSource = (DataSource) bean; JdbcWrapperHelper.registerSpringDataSource(beanName, dataSource); return JdbcWrapper.SINGLETON.createDataSourceProxy(beanName, dataSource); } else if (bean instanceof JndiObjectFactoryBean) { // fix issue 20 final InvocationHandler invocationHandler = new InvocationHandler() { /** {@inheritDoc} */ public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Object result = method.invoke(bean, args); if (result instanceof DataSource) { - result = JdbcWrapper.SINGLETON.createDataSourceProxy((DataSource) result); + result = JdbcWrapper.SINGLETON.createDataSourceProxy(beanName, + (DataSource) result); } return result; } }; return JdbcWrapper.createProxy(bean, invocationHandler); } // I tried here in the post-processor to fix "quartz jobs which are scheduled with spring // are not displayed in javamelody, except if there is the following property for // SchedulerFactoryBean in spring xml: // <property name="exposeSchedulerInRepository" value="true" /> ", // but I had some problem with Spring creating the scheduler // twice and so registering the scheduler in SchedulerRepository with the same name // as the one registered below (and Quartz wants not) // else if (bean != null // && "org.springframework.scheduling.quartz.SchedulerFactoryBean".equals(bean // .getClass().getName())) { // try { // // Remarque: on ajoute nous même le scheduler de Spring dans le SchedulerRepository // // de Quartz, car l'appel ici de schedulerFactoryBean.setExposeSchedulerInRepository(true) // // est trop tard et ne fonctionnerait pas // final Method method = bean.getClass().getMethod("getScheduler", (Class<?>[]) null); // final Scheduler scheduler = (Scheduler) method.invoke(bean, (Object[]) null); // // final SchedulerRepository schedulerRepository = SchedulerRepository.getInstance(); // synchronized (schedulerRepository) { // if (schedulerRepository.lookup(scheduler.getSchedulerName()) == null) { // schedulerRepository.bind(scheduler); // scheduler.addGlobalJobListener(new JobGlobalListener()); // } // } // } catch (final NoSuchMethodException e) { // // si la méthode n'existe pas (avant spring 2.5.6), alors cela marche sans rien faire // return bean; // } catch (final InvocationTargetException e) { // // tant pis // return bean; // } catch (final IllegalAccessException e) { // // tant pis // return bean; // } catch (SchedulerException e) { // // tant pis // return bean; // } // } return bean; } }
false
true
public Object postProcessAfterInitialization(final Object bean, String beanName) { if (bean instanceof DataSource) { final DataSource dataSource = (DataSource) bean; JdbcWrapperHelper.registerSpringDataSource(beanName, dataSource); return JdbcWrapper.SINGLETON.createDataSourceProxy(beanName, dataSource); } else if (bean instanceof JndiObjectFactoryBean) { // fix issue 20 final InvocationHandler invocationHandler = new InvocationHandler() { /** {@inheritDoc} */ public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Object result = method.invoke(bean, args); if (result instanceof DataSource) { result = JdbcWrapper.SINGLETON.createDataSourceProxy((DataSource) result); } return result; } }; return JdbcWrapper.createProxy(bean, invocationHandler); } // I tried here in the post-processor to fix "quartz jobs which are scheduled with spring // are not displayed in javamelody, except if there is the following property for // SchedulerFactoryBean in spring xml: // <property name="exposeSchedulerInRepository" value="true" /> ", // but I had some problem with Spring creating the scheduler // twice and so registering the scheduler in SchedulerRepository with the same name // as the one registered below (and Quartz wants not) // else if (bean != null // && "org.springframework.scheduling.quartz.SchedulerFactoryBean".equals(bean // .getClass().getName())) { // try { // // Remarque: on ajoute nous même le scheduler de Spring dans le SchedulerRepository // // de Quartz, car l'appel ici de schedulerFactoryBean.setExposeSchedulerInRepository(true) // // est trop tard et ne fonctionnerait pas // final Method method = bean.getClass().getMethod("getScheduler", (Class<?>[]) null); // final Scheduler scheduler = (Scheduler) method.invoke(bean, (Object[]) null); // // final SchedulerRepository schedulerRepository = SchedulerRepository.getInstance(); // synchronized (schedulerRepository) { // if (schedulerRepository.lookup(scheduler.getSchedulerName()) == null) { // schedulerRepository.bind(scheduler); // scheduler.addGlobalJobListener(new JobGlobalListener()); // } // } // } catch (final NoSuchMethodException e) { // // si la méthode n'existe pas (avant spring 2.5.6), alors cela marche sans rien faire // return bean; // } catch (final InvocationTargetException e) { // // tant pis // return bean; // } catch (final IllegalAccessException e) { // // tant pis // return bean; // } catch (SchedulerException e) { // // tant pis // return bean; // } // } return bean; }
public Object postProcessAfterInitialization(final Object bean, final String beanName) { if (bean instanceof DataSource) { final DataSource dataSource = (DataSource) bean; JdbcWrapperHelper.registerSpringDataSource(beanName, dataSource); return JdbcWrapper.SINGLETON.createDataSourceProxy(beanName, dataSource); } else if (bean instanceof JndiObjectFactoryBean) { // fix issue 20 final InvocationHandler invocationHandler = new InvocationHandler() { /** {@inheritDoc} */ public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Object result = method.invoke(bean, args); if (result instanceof DataSource) { result = JdbcWrapper.SINGLETON.createDataSourceProxy(beanName, (DataSource) result); } return result; } }; return JdbcWrapper.createProxy(bean, invocationHandler); } // I tried here in the post-processor to fix "quartz jobs which are scheduled with spring // are not displayed in javamelody, except if there is the following property for // SchedulerFactoryBean in spring xml: // <property name="exposeSchedulerInRepository" value="true" /> ", // but I had some problem with Spring creating the scheduler // twice and so registering the scheduler in SchedulerRepository with the same name // as the one registered below (and Quartz wants not) // else if (bean != null // && "org.springframework.scheduling.quartz.SchedulerFactoryBean".equals(bean // .getClass().getName())) { // try { // // Remarque: on ajoute nous même le scheduler de Spring dans le SchedulerRepository // // de Quartz, car l'appel ici de schedulerFactoryBean.setExposeSchedulerInRepository(true) // // est trop tard et ne fonctionnerait pas // final Method method = bean.getClass().getMethod("getScheduler", (Class<?>[]) null); // final Scheduler scheduler = (Scheduler) method.invoke(bean, (Object[]) null); // // final SchedulerRepository schedulerRepository = SchedulerRepository.getInstance(); // synchronized (schedulerRepository) { // if (schedulerRepository.lookup(scheduler.getSchedulerName()) == null) { // schedulerRepository.bind(scheduler); // scheduler.addGlobalJobListener(new JobGlobalListener()); // } // } // } catch (final NoSuchMethodException e) { // // si la méthode n'existe pas (avant spring 2.5.6), alors cela marche sans rien faire // return bean; // } catch (final InvocationTargetException e) { // // tant pis // return bean; // } catch (final IllegalAccessException e) { // // tant pis // return bean; // } catch (SchedulerException e) { // // tant pis // return bean; // } // } return bean; }
diff --git a/Web/EarlyAccessUpdate/src/main/java/EarlyAccessUpdate.java b/Web/EarlyAccessUpdate/src/main/java/EarlyAccessUpdate.java index 5581a3b..5ba48bb 100644 --- a/Web/EarlyAccessUpdate/src/main/java/EarlyAccessUpdate.java +++ b/Web/EarlyAccessUpdate/src/main/java/EarlyAccessUpdate.java @@ -1,64 +1,64 @@ import iTests.framework.utils.LogUtils; import org.swift.common.soap.confluence.ConfluenceSoapService; import org.swift.common.soap.confluence.RemotePage; import org.swift.common.soap.confluence.RemoteServerInfo; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; /** * User: nirb * Date: 5/21/13 */ public class EarlyAccessUpdate { public static void main(String[] args) throws Exception { String user = args[0]; String password = args[1]; String oldMilestone = args[2]; String newMilestone = args[3]; String oldBuildNumber = args[4]; String newBuildNumber = args[5]; String buildVersion = args[6]; String cutBuildVersion = buildVersion.substring(0, buildVersion.length()-1); String pageTitle = "GigaSpaces " + cutBuildVersion + "X Early Access"; WikiClient wikiClient = new WikiClient("http://wiki.gigaspaces.com/wiki", user, password); LogUtils.log("Connected ok."); ConfluenceSoapService service = wikiClient.getConfluenceSOAPService(); String token = wikiClient.getToken(); RemoteServerInfo info = service.getServerInfo(token); LogUtils.log("Confluence version: " + info.getMajorVersion() + "." + info.getMinorVersion()); LogUtils.log("Completed."); RemotePage page = service.getPage(token, "RN", pageTitle); String pageContent = page.getContent(); int startIndex = pageContent.indexOf("h2"); String currentVersionTextBlock = pageContent.substring(startIndex, pageContent.indexOf("h2", startIndex + 1)); Map<String, String> replaceTextMap = new HashMap<String, String>(); replaceTextMap.put(oldMilestone, newMilestone); replaceTextMap.put(oldMilestone.toUpperCase(), newMilestone.toUpperCase()); replaceTextMap.put(oldBuildNumber, newBuildNumber); for(Entry<String, String> entry : replaceTextMap.entrySet()){ pageContent = pageContent.replace(entry.getKey(), entry.getValue()); } String deckOpenning = "{deck:id=previous}"; - String cardOpenning = "{card:labal=" + buildVersion + " " + oldMilestone.toUpperCase() + "}"; + String cardOpenning = "{card:label=" + buildVersion + " " + oldMilestone.toUpperCase() + "}"; String cardClose = "{card}"; pageContent = pageContent.replace(deckOpenning, deckOpenning + "\n\n" + cardOpenning + "\n" + currentVersionTextBlock + "\n" + cardClose); page.setContent(pageContent); service.storePage(token, page); } }
true
true
public static void main(String[] args) throws Exception { String user = args[0]; String password = args[1]; String oldMilestone = args[2]; String newMilestone = args[3]; String oldBuildNumber = args[4]; String newBuildNumber = args[5]; String buildVersion = args[6]; String cutBuildVersion = buildVersion.substring(0, buildVersion.length()-1); String pageTitle = "GigaSpaces " + cutBuildVersion + "X Early Access"; WikiClient wikiClient = new WikiClient("http://wiki.gigaspaces.com/wiki", user, password); LogUtils.log("Connected ok."); ConfluenceSoapService service = wikiClient.getConfluenceSOAPService(); String token = wikiClient.getToken(); RemoteServerInfo info = service.getServerInfo(token); LogUtils.log("Confluence version: " + info.getMajorVersion() + "." + info.getMinorVersion()); LogUtils.log("Completed."); RemotePage page = service.getPage(token, "RN", pageTitle); String pageContent = page.getContent(); int startIndex = pageContent.indexOf("h2"); String currentVersionTextBlock = pageContent.substring(startIndex, pageContent.indexOf("h2", startIndex + 1)); Map<String, String> replaceTextMap = new HashMap<String, String>(); replaceTextMap.put(oldMilestone, newMilestone); replaceTextMap.put(oldMilestone.toUpperCase(), newMilestone.toUpperCase()); replaceTextMap.put(oldBuildNumber, newBuildNumber); for(Entry<String, String> entry : replaceTextMap.entrySet()){ pageContent = pageContent.replace(entry.getKey(), entry.getValue()); } String deckOpenning = "{deck:id=previous}"; String cardOpenning = "{card:labal=" + buildVersion + " " + oldMilestone.toUpperCase() + "}"; String cardClose = "{card}"; pageContent = pageContent.replace(deckOpenning, deckOpenning + "\n\n" + cardOpenning + "\n" + currentVersionTextBlock + "\n" + cardClose); page.setContent(pageContent); service.storePage(token, page); }
public static void main(String[] args) throws Exception { String user = args[0]; String password = args[1]; String oldMilestone = args[2]; String newMilestone = args[3]; String oldBuildNumber = args[4]; String newBuildNumber = args[5]; String buildVersion = args[6]; String cutBuildVersion = buildVersion.substring(0, buildVersion.length()-1); String pageTitle = "GigaSpaces " + cutBuildVersion + "X Early Access"; WikiClient wikiClient = new WikiClient("http://wiki.gigaspaces.com/wiki", user, password); LogUtils.log("Connected ok."); ConfluenceSoapService service = wikiClient.getConfluenceSOAPService(); String token = wikiClient.getToken(); RemoteServerInfo info = service.getServerInfo(token); LogUtils.log("Confluence version: " + info.getMajorVersion() + "." + info.getMinorVersion()); LogUtils.log("Completed."); RemotePage page = service.getPage(token, "RN", pageTitle); String pageContent = page.getContent(); int startIndex = pageContent.indexOf("h2"); String currentVersionTextBlock = pageContent.substring(startIndex, pageContent.indexOf("h2", startIndex + 1)); Map<String, String> replaceTextMap = new HashMap<String, String>(); replaceTextMap.put(oldMilestone, newMilestone); replaceTextMap.put(oldMilestone.toUpperCase(), newMilestone.toUpperCase()); replaceTextMap.put(oldBuildNumber, newBuildNumber); for(Entry<String, String> entry : replaceTextMap.entrySet()){ pageContent = pageContent.replace(entry.getKey(), entry.getValue()); } String deckOpenning = "{deck:id=previous}"; String cardOpenning = "{card:label=" + buildVersion + " " + oldMilestone.toUpperCase() + "}"; String cardClose = "{card}"; pageContent = pageContent.replace(deckOpenning, deckOpenning + "\n\n" + cardOpenning + "\n" + currentVersionTextBlock + "\n" + cardClose); page.setContent(pageContent); service.storePage(token, page); }
diff --git a/target_explorer/plugins/org.eclipse.tm.te.tcf.locator/src/org/eclipse/tm/te/tcf/locator/nodes/LocatorModel.java b/target_explorer/plugins/org.eclipse.tm.te.tcf.locator/src/org/eclipse/tm/te/tcf/locator/nodes/LocatorModel.java index d92ae9cae..fd7345eba 100644 --- a/target_explorer/plugins/org.eclipse.tm.te.tcf.locator/src/org/eclipse/tm/te/tcf/locator/nodes/LocatorModel.java +++ b/target_explorer/plugins/org.eclipse.tm.te.tcf.locator/src/org/eclipse/tm/te/tcf/locator/nodes/LocatorModel.java @@ -1,351 +1,355 @@ /******************************************************************************* * Copyright (c) 2011 Wind River Systems, Inc. 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: * Uwe Stieber (Wind River) - initial API and implementation *******************************************************************************/ package org.eclipse.tm.te.tcf.locator.nodes; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import org.eclipse.core.runtime.Assert; import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.PlatformObject; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.tm.tcf.protocol.IPeer; import org.eclipse.tm.tcf.protocol.Protocol; import org.eclipse.tm.tcf.services.ILocator; import org.eclipse.tm.te.tcf.core.Tcf; import org.eclipse.tm.te.tcf.core.interfaces.listeners.IChannelStateChangeListener; import org.eclipse.tm.te.tcf.locator.Scanner; import org.eclipse.tm.te.tcf.locator.activator.CoreBundleActivator; import org.eclipse.tm.te.tcf.locator.interfaces.IModelListener; import org.eclipse.tm.te.tcf.locator.interfaces.IScanner; import org.eclipse.tm.te.tcf.locator.interfaces.nodes.ILocatorModel; import org.eclipse.tm.te.tcf.locator.interfaces.nodes.IPeerModel; import org.eclipse.tm.te.tcf.locator.interfaces.preferences.IPreferenceKeys; import org.eclipse.tm.te.tcf.locator.interfaces.services.ILocatorModelLookupService; import org.eclipse.tm.te.tcf.locator.interfaces.services.ILocatorModelRefreshService; import org.eclipse.tm.te.tcf.locator.interfaces.services.ILocatorModelService; import org.eclipse.tm.te.tcf.locator.interfaces.services.ILocatorModelUpdateService; import org.eclipse.tm.te.tcf.locator.listener.ChannelStateChangeListener; import org.eclipse.tm.te.tcf.locator.listener.LocatorListener; import org.eclipse.tm.te.tcf.locator.services.LocatorModelLookupService; import org.eclipse.tm.te.tcf.locator.services.LocatorModelRefreshService; import org.eclipse.tm.te.tcf.locator.services.LocatorModelUpdateService; import org.eclipse.tm.te.tcf.locator.utils.IPAddressUtil; /** * Default locator model implementation. */ public class LocatorModel extends PlatformObject implements ILocatorModel { // The unique model id private final UUID uniqueId = UUID.randomUUID(); // Flag to mark the model disposed private boolean disposed; // The list of known peers private final Map<String, IPeerModel> peers = new HashMap<String, IPeerModel>(); // Reference to the scanner private IScanner scanner = null; // Reference to the model locator listener private ILocator.LocatorListener locatorListener = null; // Reference to the model channel state change listener private IChannelStateChangeListener channelStateChangeListener = null; // The list of registered model listeners private final List<IModelListener> modelListener = new ArrayList<IModelListener>(); // Reference to the refresh service private final ILocatorModelRefreshService refreshService = new LocatorModelRefreshService(this); // Reference to the lookup service private final ILocatorModelLookupService lookupService = new LocatorModelLookupService(this); // Reference to the update service private final ILocatorModelUpdateService updateService = new LocatorModelUpdateService(this); /** * Constructor. */ public LocatorModel() { super(); disposed = false; channelStateChangeListener = new ChannelStateChangeListener(this); Tcf.addChannelStateChangeListener(channelStateChangeListener); } /* (non-Javadoc) * @see org.eclipse.tm.te.tcf.locator.core.interfaces.nodes.ILocatorModel#addListener(org.eclipse.tm.te.tcf.locator.core.interfaces.IModelListener) */ public void addListener(IModelListener listener) { Assert.isNotNull(listener); Assert.isTrue(Protocol.isDispatchThread()); if (!modelListener.contains(listener)) modelListener.add(listener); } /* (non-Javadoc) * @see org.eclipse.tm.te.tcf.locator.core.interfaces.nodes.ILocatorModel#removeListener(org.eclipse.tm.te.tcf.locator.core.interfaces.IModelListener) */ public void removeListener(IModelListener listener) { Assert.isNotNull(listener); Assert.isTrue(Protocol.isDispatchThread()); modelListener.remove(listener); } /* (non-Javadoc) * @see org.eclipse.tm.te.tcf.locator.interfaces.nodes.ILocatorModel#getListener() */ public IModelListener[] getListener() { return modelListener.toArray(new IModelListener[modelListener.size()]); } /* (non-Javadoc) * @see org.eclipse.tm.te.tcf.locator.core.interfaces.nodes.ILocatorModel#dispose() */ public void dispose() { Assert.isTrue(Protocol.isDispatchThread()); // If already disposed, we are done immediately if (disposed) return; disposed = true; final IModelListener[] listeners = getListener(); if (listeners.length > 0) { Protocol.invokeLater(new Runnable() { public void run() { for (IModelListener listener : listeners) { listener.locatorModelDisposed(LocatorModel.this); } } }); } modelListener.clear(); if (locatorListener != null) { Protocol.getLocator().removeListener(locatorListener); locatorListener = null; } if (channelStateChangeListener != null) { Tcf.removeChannelStateChangeListener(channelStateChangeListener); channelStateChangeListener = null; } if (scanner != null) { stopScanner(); scanner = null; } peers.clear(); } /* (non-Javadoc) * @see org.eclipse.tm.te.tcf.locator.core.interfaces.nodes.ILocatorModel#isDisposed() */ public boolean isDisposed() { return disposed; } /* (non-Javadoc) * @see org.eclipse.tm.te.tcf.locator.core.interfaces.nodes.ILocatorModel#getPeers() */ public IPeerModel[] getPeers() { return peers.values().toArray(new IPeerModel[peers.values().size()]); } /* (non-Javadoc) * @see org.eclipse.core.runtime.PlatformObject#getAdapter(java.lang.Class) */ @SuppressWarnings({ "rawtypes", "unchecked" }) @Override public Object getAdapter(Class adapter) { if (adapter.isAssignableFrom(ILocator.LocatorListener.class)) { return locatorListener; } if (adapter.isAssignableFrom(IScanner.class)) { return scanner; } if (adapter.isAssignableFrom(ILocatorModelRefreshService.class)) { return refreshService; } if (adapter.isAssignableFrom(ILocatorModelLookupService.class)) { return lookupService; } if (adapter.isAssignableFrom(ILocatorModelUpdateService.class)) { return updateService; } if (adapter.isAssignableFrom(Map.class)) { return peers; } return super.getAdapter(adapter); } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public final boolean equals(Object obj) { if (obj instanceof LocatorModel) { return uniqueId.equals(((LocatorModel)obj).uniqueId); } return super.equals(obj); } /* (non-Javadoc) * @see org.eclipse.tm.te.tcf.locator.core.interfaces.nodes.ILocatorModel#getService(java.lang.Class) */ @SuppressWarnings("unchecked") public <V extends ILocatorModelService> V getService(Class<V> serviceInterface) { Assert.isNotNull(serviceInterface); return (V)getAdapter(serviceInterface); } /** * Check if the locator listener has been created and registered * to the global locator service. * <p> * <b>Note:</b> This method is not intended to be call from clients. */ public void checkLocatorListener() { Assert.isTrue(Protocol.isDispatchThread()); Assert.isNotNull(Protocol.getLocator()); if (locatorListener == null) { locatorListener = doCreateLocatorListener(this); Protocol.getLocator().addListener(locatorListener); } } /** * Creates the locator listener instance. * * @param model The parent model. Must not be <code>null</code>. * @return The locator listener instance. */ protected ILocator.LocatorListener doCreateLocatorListener(ILocatorModel model) { Assert.isNotNull(model); return new LocatorListener(model); } /* (non-Javadoc) * @see org.eclipse.tm.te.tcf.locator.core.interfaces.nodes.ILocatorModel#getScanner() */ public IScanner getScanner() { if (scanner == null) scanner = new Scanner(this); return scanner; } /* (non-Javadoc) * @see org.eclipse.tm.te.tcf.locator.core.interfaces.nodes.ILocatorModel#startScanner(long, long) */ public void startScanner(long delay, long schedule) { IScanner scanner = getScanner(); if (scanner != null) { // Pass on the schedule parameter Map<String, Object> config = new HashMap<String, Object>(scanner.getConfiguration()); config.put(IScanner.PROP_SCHEDULE, Long.valueOf(schedule)); scanner.setConfiguration(config); } // The default scanner implementation is a job. // -> schedule here if it is a job if (scanner instanceof Job) { Job job = (Job)scanner; job.setSystem(true); job.setPriority(Job.DECORATE); job.schedule(delay); } } /* (non-Javadoc) * @see org.eclipse.tm.te.tcf.locator.core.interfaces.nodes.ILocatorModel#stopScanner() */ public void stopScanner() { if (scanner != null) { // Terminate the scanner scanner.terminate(); // Reset the scanner reference scanner = null; } } /* (non-Javadoc) * @see org.eclipse.tm.te.tcf.locator.core.interfaces.nodes.ILocatorModel#validatePeerNodeForAdd(org.eclipse.tm.te.tcf.locator.core.interfaces.nodes.IPeerModel) */ public IPeerModel validatePeerNodeForAdd(IPeerModel node) { Assert.isNotNull(node); Assert.isTrue(Protocol.isDispatchThread()); // Get the peer from the peer node IPeer peer = node.getPeer(); IPeerModel result = node; // Check on the filtered by preference settings what to do boolean isFilterByAgentId = Platform.getPreferencesService().getBoolean(CoreBundleActivator.getUniqueIdentifier(), IPreferenceKeys.PREF_FILTER_BY_AGENT_ID, false, null); if (isFilterByAgentId) { // Peers are filtered by agent id. Don't add the peer node // if we have another peer node already having the same agent id String agentId = peer.getAgentID(); IPeerModel previousNode = agentId != null ? getService(ILocatorModelLookupService.class).lkupPeerModelByAgentId(agentId) : null; if (previousNode != null) { // Get the peer for the previous node IPeer previousPeer = previousNode.getPeer(); if (previousPeer != null) { // We prefer to use the peer node for the canonical IP address before // the loop back address before any other address. String loopback = IPAddressUtil.getInstance().getIPv4LoopbackAddress(); String canonical = IPAddressUtil.getInstance().getCanonicalAddress(); boolean fireListener = false; String peerIP = peer.getAttributes().get(IPeer.ATTR_IP_HOST); String previousPeerIP = previousPeer.getAttributes().get(IPeer.ATTR_IP_HOST); if (canonical != null && canonical.equals(peerIP) && !canonical.equals(previousPeerIP)) { // Remove the old node and replace it with the new new peers.remove(previousNode.getPeer().getID()); fireListener = true; } else if (loopback != null && loopback.equals(peerIP) && !loopback.equals(previousPeerIP) && (canonical == null || canonical != null && !canonical.equals(previousPeerIP))) { // Remove the old node and replace it with the new new peers.remove(previousNode.getPeer().getID()); fireListener = true; } else { - // Drop the current node - result = null; + // Drop the current node, if the ports are identical + String peerPort = peer.getAttributes().get(IPeer.ATTR_IP_PORT); + if (peerPort == null || "".equals(peerPort)) peerPort = "1534"; //$NON-NLS-1$ //$NON-NLS-2$ + String previousPeerPort = previousPeer.getAttributes().get(IPeer.ATTR_IP_PORT); + if (previousPeerPort == null || "".equals(previousPeerPort)) previousPeerPort = "1534"; //$NON-NLS-1$ //$NON-NLS-2$ + if (peerPort.equals(previousPeerPort)) result = null; } if (fireListener) { final IModelListener[] listeners = getListener(); if (listeners.length > 0) { Protocol.invokeLater(new Runnable() { public void run() { for (IModelListener listener : listeners) { listener.locatorModelChanged(LocatorModel.this); } } }); } } } } } return result; } }
true
true
public IPeerModel validatePeerNodeForAdd(IPeerModel node) { Assert.isNotNull(node); Assert.isTrue(Protocol.isDispatchThread()); // Get the peer from the peer node IPeer peer = node.getPeer(); IPeerModel result = node; // Check on the filtered by preference settings what to do boolean isFilterByAgentId = Platform.getPreferencesService().getBoolean(CoreBundleActivator.getUniqueIdentifier(), IPreferenceKeys.PREF_FILTER_BY_AGENT_ID, false, null); if (isFilterByAgentId) { // Peers are filtered by agent id. Don't add the peer node // if we have another peer node already having the same agent id String agentId = peer.getAgentID(); IPeerModel previousNode = agentId != null ? getService(ILocatorModelLookupService.class).lkupPeerModelByAgentId(agentId) : null; if (previousNode != null) { // Get the peer for the previous node IPeer previousPeer = previousNode.getPeer(); if (previousPeer != null) { // We prefer to use the peer node for the canonical IP address before // the loop back address before any other address. String loopback = IPAddressUtil.getInstance().getIPv4LoopbackAddress(); String canonical = IPAddressUtil.getInstance().getCanonicalAddress(); boolean fireListener = false; String peerIP = peer.getAttributes().get(IPeer.ATTR_IP_HOST); String previousPeerIP = previousPeer.getAttributes().get(IPeer.ATTR_IP_HOST); if (canonical != null && canonical.equals(peerIP) && !canonical.equals(previousPeerIP)) { // Remove the old node and replace it with the new new peers.remove(previousNode.getPeer().getID()); fireListener = true; } else if (loopback != null && loopback.equals(peerIP) && !loopback.equals(previousPeerIP) && (canonical == null || canonical != null && !canonical.equals(previousPeerIP))) { // Remove the old node and replace it with the new new peers.remove(previousNode.getPeer().getID()); fireListener = true; } else { // Drop the current node result = null; } if (fireListener) { final IModelListener[] listeners = getListener(); if (listeners.length > 0) { Protocol.invokeLater(new Runnable() { public void run() { for (IModelListener listener : listeners) { listener.locatorModelChanged(LocatorModel.this); } } }); } } } } } return result; }
public IPeerModel validatePeerNodeForAdd(IPeerModel node) { Assert.isNotNull(node); Assert.isTrue(Protocol.isDispatchThread()); // Get the peer from the peer node IPeer peer = node.getPeer(); IPeerModel result = node; // Check on the filtered by preference settings what to do boolean isFilterByAgentId = Platform.getPreferencesService().getBoolean(CoreBundleActivator.getUniqueIdentifier(), IPreferenceKeys.PREF_FILTER_BY_AGENT_ID, false, null); if (isFilterByAgentId) { // Peers are filtered by agent id. Don't add the peer node // if we have another peer node already having the same agent id String agentId = peer.getAgentID(); IPeerModel previousNode = agentId != null ? getService(ILocatorModelLookupService.class).lkupPeerModelByAgentId(agentId) : null; if (previousNode != null) { // Get the peer for the previous node IPeer previousPeer = previousNode.getPeer(); if (previousPeer != null) { // We prefer to use the peer node for the canonical IP address before // the loop back address before any other address. String loopback = IPAddressUtil.getInstance().getIPv4LoopbackAddress(); String canonical = IPAddressUtil.getInstance().getCanonicalAddress(); boolean fireListener = false; String peerIP = peer.getAttributes().get(IPeer.ATTR_IP_HOST); String previousPeerIP = previousPeer.getAttributes().get(IPeer.ATTR_IP_HOST); if (canonical != null && canonical.equals(peerIP) && !canonical.equals(previousPeerIP)) { // Remove the old node and replace it with the new new peers.remove(previousNode.getPeer().getID()); fireListener = true; } else if (loopback != null && loopback.equals(peerIP) && !loopback.equals(previousPeerIP) && (canonical == null || canonical != null && !canonical.equals(previousPeerIP))) { // Remove the old node and replace it with the new new peers.remove(previousNode.getPeer().getID()); fireListener = true; } else { // Drop the current node, if the ports are identical String peerPort = peer.getAttributes().get(IPeer.ATTR_IP_PORT); if (peerPort == null || "".equals(peerPort)) peerPort = "1534"; //$NON-NLS-1$ //$NON-NLS-2$ String previousPeerPort = previousPeer.getAttributes().get(IPeer.ATTR_IP_PORT); if (previousPeerPort == null || "".equals(previousPeerPort)) previousPeerPort = "1534"; //$NON-NLS-1$ //$NON-NLS-2$ if (peerPort.equals(previousPeerPort)) result = null; } if (fireListener) { final IModelListener[] listeners = getListener(); if (listeners.length > 0) { Protocol.invokeLater(new Runnable() { public void run() { for (IModelListener listener : listeners) { listener.locatorModelChanged(LocatorModel.this); } } }); } } } } } return result; }
diff --git a/deegree-services/deegree-services-csw/src/main/java/org/deegree/services/csw/getrecordbyid/GetRecordByIdKVPAdapter.java b/deegree-services/deegree-services-csw/src/main/java/org/deegree/services/csw/getrecordbyid/GetRecordByIdKVPAdapter.java index 6807eb1ba9..d9181c021c 100644 --- a/deegree-services/deegree-services-csw/src/main/java/org/deegree/services/csw/getrecordbyid/GetRecordByIdKVPAdapter.java +++ b/deegree-services/deegree-services-csw/src/main/java/org/deegree/services/csw/getrecordbyid/GetRecordByIdKVPAdapter.java @@ -1,133 +1,133 @@ //$HeadURL$ /*---------------------------------------------------------------------------- This file is part of deegree, http://deegree.org/ Copyright (C) 2001-2009 by: - Department of Geography, University of Bonn - and - lat/lon GmbH - 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 Contact information: lat/lon GmbH Aennchenstr. 19, 53177 Bonn Germany http://lat-lon.de/ Department of Geography, University of Bonn Prof. Dr. Klaus Greve Postfach 1147, 53001 Bonn Germany http://www.geographie.uni-bonn.de/deegree/ e-mail: [email protected] ----------------------------------------------------------------------------*/ package org.deegree.services.csw.getrecordbyid; import static org.deegree.protocol.csw.CSWConstants.VERSION_202; import java.net.URI; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.deegree.commons.tom.ows.Version; import org.deegree.commons.utils.kvp.InvalidParameterValueException; import org.deegree.commons.utils.kvp.KVPUtils; import org.deegree.commons.utils.kvp.MissingParameterException; import org.deegree.protocol.csw.CSWConstants.ReturnableElement; import org.deegree.protocol.csw.MetadataStoreException; import org.deegree.protocol.i18n.Messages; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Encapsulates the method for parsing a {@link GetRecordById} KVP request via Http-GET. * * @author <a href="mailto:[email protected]">Steffen Thomas</a> * @author last edited by: $Author: thomas $ * * @version $Revision: $, $Date: $ */ public class GetRecordByIdKVPAdapter { private static final Logger LOG = LoggerFactory.getLogger( GetRecordByIdKVPAdapter.class ); /** * Parses the {@link GetRecordById} kvp request and decides which version has to parse because of the requested * version * * @param normalizedKVPParams * that are requested containing all mandatory and optional parts regarding CSW spec * @return {@link GetRecordById} * @throws MetadataStoreException */ public static GetRecordById parse( Map<String, String> normalizedKVPParams, String defaultOutputFormat, String defaultOuputSchema ) { Version version = Version.parseVersion( KVPUtils.getRequired( normalizedKVPParams, "VERSION" ) ); GetRecordById result = null; if ( VERSION_202.equals( version ) ) { result = parse202( VERSION_202, normalizedKVPParams, defaultOutputFormat, defaultOuputSchema ); } else { String msg = Messages.get( "UNSUPPORTED_VERSION", version, Version.getVersionsString( VERSION_202 ) ); throw new InvalidParameterValueException( msg ); } return result; } /** * Parses the {@link GetRecordById} request on the basis of CSW version 2.0.2 * * @param version202 * at is requested, 2.0.2 * @param normalizedKVPParams * that are requested containing all mandatory and optional parts regarding CSW spec * @return {@link GetRecordById} * @throws MetadataStoreException */ private static GetRecordById parse202( Version version202, Map<String, String> normalizedKVPParams, String defaultOutputFormat, String defaultOuputSchema ) { // outputFormat (optional) String outputFormat = KVPUtils.getDefault( normalizedKVPParams, "outputFormat", defaultOutputFormat ); String elementSetNameString = KVPUtils.getDefault( normalizedKVPParams, "ELEMENTSETNAME", ReturnableElement.summary.name() ); ReturnableElement elementSetName = ReturnableElement.determineReturnableElement( elementSetNameString ); // outputSchema String String outputSchemaString = KVPUtils.getDefault( normalizedKVPParams, "OUTPUTSCHEMA", defaultOuputSchema ); URI outputSchema = URI.create( outputSchemaString ); // elementName List<String> List<String> id = new ArrayList<String>(); List<String> tmpIds = KVPUtils.splitAll( normalizedKVPParams, "ID" ); - if ( id.size() == 0 ) { + if ( tmpIds.size() == 0 ) { String msg = "No ID provided, please check the mandatory element 'id'. "; LOG.info( msg ); throw new MissingParameterException( msg ); } for ( String tmpId : tmpIds ) { if ( !id.contains( tmpId ) ) { - tmpIds.add( tmpId ); + id.add( tmpId ); } } return new GetRecordById( version202, outputFormat, elementSetName, outputSchema, id ); } }
false
true
private static GetRecordById parse202( Version version202, Map<String, String> normalizedKVPParams, String defaultOutputFormat, String defaultOuputSchema ) { // outputFormat (optional) String outputFormat = KVPUtils.getDefault( normalizedKVPParams, "outputFormat", defaultOutputFormat ); String elementSetNameString = KVPUtils.getDefault( normalizedKVPParams, "ELEMENTSETNAME", ReturnableElement.summary.name() ); ReturnableElement elementSetName = ReturnableElement.determineReturnableElement( elementSetNameString ); // outputSchema String String outputSchemaString = KVPUtils.getDefault( normalizedKVPParams, "OUTPUTSCHEMA", defaultOuputSchema ); URI outputSchema = URI.create( outputSchemaString ); // elementName List<String> List<String> id = new ArrayList<String>(); List<String> tmpIds = KVPUtils.splitAll( normalizedKVPParams, "ID" ); if ( id.size() == 0 ) { String msg = "No ID provided, please check the mandatory element 'id'. "; LOG.info( msg ); throw new MissingParameterException( msg ); } for ( String tmpId : tmpIds ) { if ( !id.contains( tmpId ) ) { tmpIds.add( tmpId ); } } return new GetRecordById( version202, outputFormat, elementSetName, outputSchema, id ); }
private static GetRecordById parse202( Version version202, Map<String, String> normalizedKVPParams, String defaultOutputFormat, String defaultOuputSchema ) { // outputFormat (optional) String outputFormat = KVPUtils.getDefault( normalizedKVPParams, "outputFormat", defaultOutputFormat ); String elementSetNameString = KVPUtils.getDefault( normalizedKVPParams, "ELEMENTSETNAME", ReturnableElement.summary.name() ); ReturnableElement elementSetName = ReturnableElement.determineReturnableElement( elementSetNameString ); // outputSchema String String outputSchemaString = KVPUtils.getDefault( normalizedKVPParams, "OUTPUTSCHEMA", defaultOuputSchema ); URI outputSchema = URI.create( outputSchemaString ); // elementName List<String> List<String> id = new ArrayList<String>(); List<String> tmpIds = KVPUtils.splitAll( normalizedKVPParams, "ID" ); if ( tmpIds.size() == 0 ) { String msg = "No ID provided, please check the mandatory element 'id'. "; LOG.info( msg ); throw new MissingParameterException( msg ); } for ( String tmpId : tmpIds ) { if ( !id.contains( tmpId ) ) { id.add( tmpId ); } } return new GetRecordById( version202, outputFormat, elementSetName, outputSchema, id ); }
diff --git a/src/main/java/com/mysema/webmin/impl/MinifierHandler.java b/src/main/java/com/mysema/webmin/impl/MinifierHandler.java index 1fb57ec..633c003 100644 --- a/src/main/java/com/mysema/webmin/impl/MinifierHandler.java +++ b/src/main/java/com/mysema/webmin/impl/MinifierHandler.java @@ -1,244 +1,245 @@ /* * Copyright (c) 2007 Mysema Ltd. * All rights reserved. * */ package com.mysema.webmin.impl; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.MalformedURLException; import java.net.URL; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.zip.GZIPOutputStream; import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.mysema.commons.lang.Assert; import com.mysema.webmin.*; import com.mysema.webmin.support.*; import com.mysema.webmin.util.CompositeInputStream; import com.mysema.webmin.util.ResourceUtil; /** * MinifierHandler provides CSS and JS minification services via the Handler interface * * @author Timo Westkamper * @version $Id$ */ public class MinifierHandler implements Handler { private static final Logger logger = LoggerFactory.getLogger(MinifierServlet.class); private final Configuration configuration; private final Map<String, Minifier> minifiers = new HashMap<String, Minifier>(); private final ServletContext servletContext; public MinifierHandler(Configuration configuration, ServletContext servletContext) { this.servletContext = Assert.notNull(servletContext); this.configuration = Assert.notNull(configuration); if (configuration.getMode() != Mode.PRODUCTION){ logger.warn("Using "+configuration.getMode()+" mode. Do not use this in production."); } if (!configuration.getMode().isMinified()){ logger.warn("Using "+configuration.getMode()+" mode. Do not use this in production."); minifiers.put("javascript", new JsImportMinifier()); minifiers.put("css", new CssImportMinifier()); }else{ if (configuration.getJavascriptCompressor().equals("jsmin")) { minifiers.put("javascript", new JsminJsMinifier()); } else { minifiers.put("javascript", new YuiJsMinifier()); } minifiers.put("css", new YuiCssMinifier()); } } private InputStream getStreamForResource( Resource resource, HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { if (resource.isForward()){ if (resource.isL10n()){ throw new IllegalArgumentException("Localization is not supported for forwarded resources"); } RequestDispatcher dispatcher = servletContext.getRequestDispatcher(resource.getPath()); MinifierRequestWrapper mreq = new MinifierRequestWrapper(req); MinifierResponseWrapper mres = new MinifierResponseWrapper(res); dispatcher.forward(mreq, mres); if (mres.getBytes() != null){ return new ByteArrayInputStream(mres.getBytes()); }else { throw new IllegalArgumentException("Forward for " + resource.getPath() + " failed"); } }else if (resource.isL10n()){ String path = resource.getPath(); path = path.substring(0, path.lastIndexOf('.')) + "_" + req.getParameter("locale") + path.substring(path.lastIndexOf('.')); if (servletContext.getResourceAsStream(path) != null){ return servletContext.getResourceAsStream(path); }else{ logger.error("Got no resource for path " + path); return servletContext.getResourceAsStream(resource.getPath()); } }else{ return servletContext.getResourceAsStream(resource.getPath()); } } public void handle(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String path = request.getRequestURI().substring(request.getContextPath().length()); int i = path.indexOf(';'); if (i > -1){ // strip jsessionid parameters etc off path = path.substring(0, i); } logger.debug("path = {}", path); Bundle bundle = configuration.getBundleByPath(path); if (bundle != null) { // content type response.setContentType("text/" + bundle.getType()); // characeter encoding String charsetEncoding = configuration.getTargetEncoding(); response.setCharacterEncoding(charsetEncoding); // last modified header long lastModified = lastModified(bundle); response.setDateHeader("Last-Modified", lastModified); // expires header (only in production mode) if (!configuration.getMode().isCached()){ response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 0); response.setHeader("Pragma", "No-cache"); }else if (bundle.getMaxage() > 0l) { logger.debug("setting expires header"); response.setDateHeader("Expires", System.currentTimeMillis()+ bundle.getMaxage() * 1000); } // check if-modified-since header long ifModifiedSince = request.getDateHeader("If-Modified-Since"); if (!configuration.getMode().isCached() || ifModifiedSince == -1 || lastModified > ifModifiedSince) { OutputStream os; String acceptEncoding = request.getHeader("Accept-Encoding"); if (configuration.isUseGzip() && acceptEncoding != null && acceptEncoding.contains("gzip")) { response.setHeader("Content-Encoding", "gzip"); os = new GZIPOutputStream(response.getOutputStream()); } else { os = response.getOutputStream(); } long start = System.currentTimeMillis(); streamBundle(bundle, os, charsetEncoding, request, response); logger.debug("created content in {} ms", System.currentTimeMillis()- start); } else { logger.debug("{} not modified", path); response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); } } else { - response.sendError(HttpServletResponse.SC_NOT_FOUND, - "No bundle found for path " + path); + response.sendError(HttpServletResponse.SC_NOT_FOUND, +// "No bundle found for path " + path); + "No bundle for requested path"); } } /** * Returns the last modified timestamp of the given Bundle * * @param bundle * @return * @throws MalformedURLException */ private long lastModified(Bundle bundle) throws MalformedURLException { long lastModified = 0l; for (Resource resource : bundle.getResources()) { if (!resource.isForward()){ URL url = servletContext.getResource(resource.getPath()); if (url == null){ throw new IllegalArgumentException("Got no resource for " + resource.getPath()); } lastModified = Math.max(lastModified, ResourceUtil.lastModified(url)); } } // round down to the nearest second since client headers are in seconds return lastModified / 1000 * 1000; } /** * * @param bundle * @param os * @param encoding * @param request * @param response * @throws Exception */ private void streamBundle(Bundle bundle, OutputStream os, String encoding, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String path = request.getParameter("path"); InputStream in; Minifier minifier; // partial bundle streaming is only supported in debug mode if (path != null && !configuration.getMode().isMinified()){ if (!path.startsWith("/")){ path = configuration.getBasePath() + path; } Resource res = bundle.getResourceForPath(path); if (res != null){ in = getStreamForResource(res, request, response); }else{ response.sendError(HttpServletResponse.SC_NOT_FOUND, "No resource for path " + path); return; } minifier = NullMinifier.DEFAULT; }else{ // unite contents List<InputStream> streams = new LinkedList<InputStream>(); for (Resource res : bundle.getResources()) { streams.add(getStreamForResource(res, request, response)); } in = new CompositeInputStream(streams); minifier = minifiers.get(bundle.getType()); } try { // uses intermediate form, to avoid HTTP 1.1 chunking ByteArrayOutputStream out = new ByteArrayOutputStream(); // minify contents minifier.minify(request, in, out, bundle, configuration); os.write(out.toByteArray()); } finally { in.close(); os.close(); } } }
true
true
public void handle(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String path = request.getRequestURI().substring(request.getContextPath().length()); int i = path.indexOf(';'); if (i > -1){ // strip jsessionid parameters etc off path = path.substring(0, i); } logger.debug("path = {}", path); Bundle bundle = configuration.getBundleByPath(path); if (bundle != null) { // content type response.setContentType("text/" + bundle.getType()); // characeter encoding String charsetEncoding = configuration.getTargetEncoding(); response.setCharacterEncoding(charsetEncoding); // last modified header long lastModified = lastModified(bundle); response.setDateHeader("Last-Modified", lastModified); // expires header (only in production mode) if (!configuration.getMode().isCached()){ response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 0); response.setHeader("Pragma", "No-cache"); }else if (bundle.getMaxage() > 0l) { logger.debug("setting expires header"); response.setDateHeader("Expires", System.currentTimeMillis()+ bundle.getMaxage() * 1000); } // check if-modified-since header long ifModifiedSince = request.getDateHeader("If-Modified-Since"); if (!configuration.getMode().isCached() || ifModifiedSince == -1 || lastModified > ifModifiedSince) { OutputStream os; String acceptEncoding = request.getHeader("Accept-Encoding"); if (configuration.isUseGzip() && acceptEncoding != null && acceptEncoding.contains("gzip")) { response.setHeader("Content-Encoding", "gzip"); os = new GZIPOutputStream(response.getOutputStream()); } else { os = response.getOutputStream(); } long start = System.currentTimeMillis(); streamBundle(bundle, os, charsetEncoding, request, response); logger.debug("created content in {} ms", System.currentTimeMillis()- start); } else { logger.debug("{} not modified", path); response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); } } else { response.sendError(HttpServletResponse.SC_NOT_FOUND, "No bundle found for path " + path); } }
public void handle(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String path = request.getRequestURI().substring(request.getContextPath().length()); int i = path.indexOf(';'); if (i > -1){ // strip jsessionid parameters etc off path = path.substring(0, i); } logger.debug("path = {}", path); Bundle bundle = configuration.getBundleByPath(path); if (bundle != null) { // content type response.setContentType("text/" + bundle.getType()); // characeter encoding String charsetEncoding = configuration.getTargetEncoding(); response.setCharacterEncoding(charsetEncoding); // last modified header long lastModified = lastModified(bundle); response.setDateHeader("Last-Modified", lastModified); // expires header (only in production mode) if (!configuration.getMode().isCached()){ response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 0); response.setHeader("Pragma", "No-cache"); }else if (bundle.getMaxage() > 0l) { logger.debug("setting expires header"); response.setDateHeader("Expires", System.currentTimeMillis()+ bundle.getMaxage() * 1000); } // check if-modified-since header long ifModifiedSince = request.getDateHeader("If-Modified-Since"); if (!configuration.getMode().isCached() || ifModifiedSince == -1 || lastModified > ifModifiedSince) { OutputStream os; String acceptEncoding = request.getHeader("Accept-Encoding"); if (configuration.isUseGzip() && acceptEncoding != null && acceptEncoding.contains("gzip")) { response.setHeader("Content-Encoding", "gzip"); os = new GZIPOutputStream(response.getOutputStream()); } else { os = response.getOutputStream(); } long start = System.currentTimeMillis(); streamBundle(bundle, os, charsetEncoding, request, response); logger.debug("created content in {} ms", System.currentTimeMillis()- start); } else { logger.debug("{} not modified", path); response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); } } else { response.sendError(HttpServletResponse.SC_NOT_FOUND, // "No bundle found for path " + path); "No bundle for requested path"); } }
diff --git a/memory_structure/src/main/java/fr/sciencespo/medialab/hci/memorystructure/util/LRUUtil.java b/memory_structure/src/main/java/fr/sciencespo/medialab/hci/memorystructure/util/LRUUtil.java index 4e46ce16..b7e51d94 100644 --- a/memory_structure/src/main/java/fr/sciencespo/medialab/hci/memorystructure/util/LRUUtil.java +++ b/memory_structure/src/main/java/fr/sciencespo/medialab/hci/memorystructure/util/LRUUtil.java @@ -1,137 +1,137 @@ package fr.sciencespo.medialab.hci.memorystructure.util; import java.util.HashSet; import java.util.Scanner; import java.util.Set; import org.apache.commons.lang.StringUtils; /** * Utility methods for LRUs. * * @author benjamin ooghe-tabanou */ public class LRUUtil { public static int PRECISION_LIMIT = 4; public static String getPrecisionLimitNode(String lru) { String[] ps = lru.split("\\|"); String n = ""; for(int i = 0; i < ps.length && i <LRUUtil.PRECISION_LIMIT; i++) { n += ps[i] + "|"; } n = n.substring(0, n.length()-1); return n; } public static boolean isPrecisionLimitNode(String lru) { return lru.split("\\|").length <= LRUUtil.PRECISION_LIMIT; } /** * Reverts an lru to an url. Scheme is stripped; a "www" host is also stripped; returns null when input is null, * empty or blank. * * @param lru to revert * @return url */ public static String revertLRU(String lru) { if(lru == null) { return null; } lru = lru.trim(); if(StringUtils.isEmpty(lru)) { return null; } String url = ""; Scanner scanner = new Scanner(lru); scanner.useDelimiter("\\|"); boolean tldDone = false; boolean removedTrailingDot = false; while(scanner.hasNext()) { String lruElement = scanner.next(); if(!lruElement.startsWith("s:")) { if(lruElement.startsWith("h:")) { if(lruElement.equals("h:localhost")) { tldDone = true; - } else if(!lruElement.equals("h:www")) { + } else { lruElement = lruElement.substring(lruElement.indexOf(':')+1); lruElement = lruElement.trim(); if(StringUtils.isNotEmpty(lruElement)) { if(tldDone) { url = url + "." + lruElement; } else { url = lruElement + "." + url; } if(!tldDone && lruElement.startsWith("h:")) { tldDone = true; } } } - } else if(lruElement.startsWith("t:") && ! (lruElement.endsWith(":80") || lruElement.endsWith(":443"))) { + } else if(lruElement.startsWith("t:") && ! (lruElement.endsWith(":80"))) { url += ":"+lruElement.substring(lruElement.indexOf(':')+1).trim(); } else { if(!removedTrailingDot && url.endsWith(".")) { url = url.substring(0, url.length() - 1); removedTrailingDot = true; } if(lruElement.startsWith("p:")) { lruElement = lruElement.substring(lruElement.indexOf(':')+1); lruElement = lruElement.trim(); url = url + "/" + lruElement; } else if(lruElement.startsWith("q:")) { lruElement = lruElement.substring(lruElement.indexOf(':')+1); lruElement = lruElement.trim(); url = url + "?" + lruElement; } else if(lruElement.startsWith("f:")) { lruElement = lruElement.substring(lruElement.indexOf(':')+1); lruElement = lruElement.trim(); url = url + "#" + lruElement; } } } } scanner.close(); if(!removedTrailingDot && url.endsWith(".")) { url = url.substring(0, url.length() - 1); } return url; } /** * Returns a set of the longest strings in a set. If the input is empty, returns a set containing the empty string. * TODO the longest token not string length * @param strings strings * @return the longest string(s) */ public static Set<String> findLongestString(Set<String> strings) { Set<String> longests = new HashSet<String>(); String longest = ""; longests.add(longest); if(strings != null) { // for each string for(String s : strings) { // if longer than longest seen before if(s.length() > longest.length()) { // clear previous results longests.clear(); // now this is the longest longest = s; // add to results longests.add(longest); } // if equal length to longest seen before else if(s.length() == longest.length()) { // add to results longests.add(s); } } } return longests; } }
false
true
public static String revertLRU(String lru) { if(lru == null) { return null; } lru = lru.trim(); if(StringUtils.isEmpty(lru)) { return null; } String url = ""; Scanner scanner = new Scanner(lru); scanner.useDelimiter("\\|"); boolean tldDone = false; boolean removedTrailingDot = false; while(scanner.hasNext()) { String lruElement = scanner.next(); if(!lruElement.startsWith("s:")) { if(lruElement.startsWith("h:")) { if(lruElement.equals("h:localhost")) { tldDone = true; } else if(!lruElement.equals("h:www")) { lruElement = lruElement.substring(lruElement.indexOf(':')+1); lruElement = lruElement.trim(); if(StringUtils.isNotEmpty(lruElement)) { if(tldDone) { url = url + "." + lruElement; } else { url = lruElement + "." + url; } if(!tldDone && lruElement.startsWith("h:")) { tldDone = true; } } } } else if(lruElement.startsWith("t:") && ! (lruElement.endsWith(":80") || lruElement.endsWith(":443"))) { url += ":"+lruElement.substring(lruElement.indexOf(':')+1).trim(); } else { if(!removedTrailingDot && url.endsWith(".")) { url = url.substring(0, url.length() - 1); removedTrailingDot = true; } if(lruElement.startsWith("p:")) { lruElement = lruElement.substring(lruElement.indexOf(':')+1); lruElement = lruElement.trim(); url = url + "/" + lruElement; } else if(lruElement.startsWith("q:")) { lruElement = lruElement.substring(lruElement.indexOf(':')+1); lruElement = lruElement.trim(); url = url + "?" + lruElement; } else if(lruElement.startsWith("f:")) { lruElement = lruElement.substring(lruElement.indexOf(':')+1); lruElement = lruElement.trim(); url = url + "#" + lruElement; } } } } scanner.close(); if(!removedTrailingDot && url.endsWith(".")) { url = url.substring(0, url.length() - 1); } return url; }
public static String revertLRU(String lru) { if(lru == null) { return null; } lru = lru.trim(); if(StringUtils.isEmpty(lru)) { return null; } String url = ""; Scanner scanner = new Scanner(lru); scanner.useDelimiter("\\|"); boolean tldDone = false; boolean removedTrailingDot = false; while(scanner.hasNext()) { String lruElement = scanner.next(); if(!lruElement.startsWith("s:")) { if(lruElement.startsWith("h:")) { if(lruElement.equals("h:localhost")) { tldDone = true; } else { lruElement = lruElement.substring(lruElement.indexOf(':')+1); lruElement = lruElement.trim(); if(StringUtils.isNotEmpty(lruElement)) { if(tldDone) { url = url + "." + lruElement; } else { url = lruElement + "." + url; } if(!tldDone && lruElement.startsWith("h:")) { tldDone = true; } } } } else if(lruElement.startsWith("t:") && ! (lruElement.endsWith(":80"))) { url += ":"+lruElement.substring(lruElement.indexOf(':')+1).trim(); } else { if(!removedTrailingDot && url.endsWith(".")) { url = url.substring(0, url.length() - 1); removedTrailingDot = true; } if(lruElement.startsWith("p:")) { lruElement = lruElement.substring(lruElement.indexOf(':')+1); lruElement = lruElement.trim(); url = url + "/" + lruElement; } else if(lruElement.startsWith("q:")) { lruElement = lruElement.substring(lruElement.indexOf(':')+1); lruElement = lruElement.trim(); url = url + "?" + lruElement; } else if(lruElement.startsWith("f:")) { lruElement = lruElement.substring(lruElement.indexOf(':')+1); lruElement = lruElement.trim(); url = url + "#" + lruElement; } } } } scanner.close(); if(!removedTrailingDot && url.endsWith(".")) { url = url.substring(0, url.length() - 1); } return url; }
diff --git a/roo/shell/src/main/java/org/springframework/roo/shell/AbstractShell.java b/roo/shell/src/main/java/org/springframework/roo/shell/AbstractShell.java index d74b3ed1..5a088463 100644 --- a/roo/shell/src/main/java/org/springframework/roo/shell/AbstractShell.java +++ b/roo/shell/src/main/java/org/springframework/roo/shell/AbstractShell.java @@ -1,606 +1,606 @@ package org.springframework.roo.shell; import static org.apache.commons.io.IOUtils.LINE_SEPARATOR; 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.net.URISyntaxException; import java.net.URL; import java.text.DateFormat; import java.util.Collection; import java.util.Date; import java.util.List; import java.util.Map.Entry; import java.util.Set; import java.util.TreeSet; import java.util.jar.JarFile; import java.util.jar.Manifest; import java.util.logging.Level; import java.util.logging.Logger; import java.util.zip.ZipEntry; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.Validate; import org.springframework.roo.shell.event.AbstractShellStatusPublisher; import org.springframework.roo.shell.event.ShellStatus; import org.springframework.roo.shell.event.ShellStatus.Status; import org.springframework.roo.support.logging.HandlerUtils; import org.springframework.roo.support.util.CollectionUtils; /** * Provides a base {@link Shell} implementation. * * @author Ben Alex */ public abstract class AbstractShell extends AbstractShellStatusPublisher implements Shell { private static final String MY_SLOT = AbstractShell.class.getName(); protected static final String ROO_PROMPT = "roo-gvNIX> "; // Public static fields; don't rename, make final, or make non-public, as // they are part of the public API, e.g. are changed by STS. public static String completionKeys = "TAB"; public static String shellPrompt = ROO_PROMPT; public static String versionInfo() { // Try to determine the bundle version String bundleVersion = null; String gitCommitHash = null; JarFile jarFile = null; try { final URL classContainer = AbstractShell.class .getProtectionDomain().getCodeSource().getLocation(); if (classContainer.toString().endsWith(".jar")) { // Attempt to obtain the "Bundle-Version" version from the // manifest jarFile = new JarFile(new File(classContainer.toURI()), false); final ZipEntry manifestEntry = jarFile .getEntry("META-INF/MANIFEST.MF"); final Manifest manifest = new Manifest( jarFile.getInputStream(manifestEntry)); bundleVersion = manifest.getMainAttributes().getValue( "Bundle-Version"); gitCommitHash = manifest.getMainAttributes().getValue( "Git-Commit-Hash"); } } catch (final IOException ignoreAndMoveOn) { } catch (final URISyntaxException ignoreAndMoveOn) { } finally { if (jarFile != null) { try { jarFile.close(); } catch (final IOException ignored) { } } } final StringBuilder sb = new StringBuilder(); if (bundleVersion != null) { sb.append(bundleVersion); } if (gitCommitHash != null && gitCommitHash.length() > 7) { if (sb.length() > 0) { sb.append(" "); } sb.append("[rev "); sb.append(gitCommitHash.substring(0, 7)); sb.append("]"); } if (sb.length() == 0) { sb.append("UNKNOWN VERSION"); } return sb.toString(); } protected final Logger logger = HandlerUtils.getLogger(getClass()); protected boolean inBlockComment; protected ExitShellRequest exitShellRequest; private Tailor tailor; @CliCommand(value = { "/*" }, help = "Start of block comment") public void blockCommentBegin() { Validate.isTrue(!inBlockComment, "Cannot open a new block comment when one already active"); inBlockComment = true; } @CliCommand(value = { "*/" }, help = "End of block comment") public void blockCommentFinish() { Validate.isTrue(inBlockComment, "Cannot close a block comment when it has not been opened"); inBlockComment = false; } @CliCommand(value = { "date" }, help = "Displays the local date and time") public String date() { return DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL) .format(new Date()); } public boolean executeCommand(final String line) { if (tailor == null) { return executeCommandImpl(line); } /* * If getTailor() is not null, then try to transform input command and * execute all outputs sequentially */ List<String> commands = null; commands = tailor.sew(line); if (CollectionUtils.isEmpty(commands)) { return executeCommandImpl(line); } for (final String command : commands) { logger.info("roo-tailor> " + command); if (!executeCommandImpl(command)) { return false; } } return true; } /** * Runs the specified command. Control will return to the caller after the * command is run. */ private boolean executeCommandImpl(String line) { // Another command was attempted setShellStatus(ShellStatus.Status.PARSING); final ExecutionStrategy executionStrategy = getExecutionStrategy(); boolean flashedMessage = false; while (executionStrategy == null || !executionStrategy.isReadyForCommands()) { // Wait try { Thread.sleep(500); } catch (final InterruptedException ignore) { } if (!flashedMessage) { flash(Level.INFO, "Please wait - still loading", MY_SLOT); flashedMessage = true; } } if (flashedMessage) { flash(Level.INFO, "", MY_SLOT); } ParseResult parseResult = null; try { // We support simple block comments; ie a single pair per line if (!inBlockComment && line.contains("/*") && line.contains("*/")) { blockCommentBegin(); final String lhs = line.substring(0, line.lastIndexOf("/*")); if (line.contains("*/")) { line = lhs + line.substring(line.lastIndexOf("*/") + 2); blockCommentFinish(); } else { line = lhs; } } if (inBlockComment) { if (!line.contains("*/")) { return true; } blockCommentFinish(); line = line.substring(line.lastIndexOf("*/") + 2); } // We also support inline comments (but only at start of line, // otherwise valid // command options like http://www.helloworld.com will fail as per // ROO-517) if (!inBlockComment && (line.trim().startsWith("//") || line.trim().startsWith( "#"))) { // # support in ROO-1116 line = ""; } // Convert any TAB characters to whitespace (ROO-527) line = line.replace('\t', ' '); if ("".equals(line.trim())) { setShellStatus(Status.EXECUTION_SUCCESS); return true; } parseResult = getParser().parse(line); if (parseResult == null) { return false; } setShellStatus(Status.EXECUTING); final Object result = executionStrategy.execute(parseResult); setShellStatus(Status.EXECUTION_RESULT_PROCESSING); if (result != null) { if (result instanceof ExitShellRequest) { exitShellRequest = (ExitShellRequest) result; // Give ProcessManager a chance to close down its threads // before the overall OSGi framework is terminated // (ROO-1938) executionStrategy.terminate(); } else if (result instanceof Iterable<?>) { for (final Object o : (Iterable<?>) result) { logger.info(o.toString()); } } else { logger.info(result.toString()); } } logCommandIfRequired(line, true); setShellStatus(Status.EXECUTION_SUCCESS, line, parseResult); return true; } catch (final RuntimeException e) { setShellStatus(Status.EXECUTION_FAILED, line, parseResult); // We rely on execution strategy to log it try { logCommandIfRequired(line, false); } catch (final Exception ignored) { } return false; } finally { setShellStatus(Status.USER_INPUT); } } /** * Execute the single line from a script. * <p> * This method can be overridden by sub-classes to pre-process script lines. */ protected boolean executeScriptLine(final String line) { return executeCommand(line); } /** * Returns any classpath resources with the given path * * @param path the path for which to search (never null) * @return <code>null</code> if the search can't be performed * @since 1.2.0 */ protected abstract Collection<URL> findResources(String path); /** * Simple implementation of {@link #flash(Level, String, String)} that * simply displays the message via the logger. It is strongly recommended * shell implementations override this method with a more effective * approach. */ public void flash(final Level level, final String message, final String slot) { Validate.notNull(level, "Level is required for a flash message"); Validate.notNull(message, "Message is required for a flash message"); Validate.notBlank(slot, "Slot name must be specified for a flash message"); if (!"".equals(message)) { logger.log(level, message); } } @CliCommand(value = { "flash test" }, help = "Tests message flashing") public void flashCustom() throws Exception { flash(Level.FINE, "Hello world", "a"); Thread.sleep(150); flash(Level.FINE, "Short world", "a"); Thread.sleep(150); flash(Level.FINE, "Small", "a"); Thread.sleep(150); flash(Level.FINE, "Downloading xyz", "b"); Thread.sleep(150); flash(Level.FINE, "", "a"); Thread.sleep(150); flash(Level.FINE, "Downloaded xyz", "b"); Thread.sleep(150); flash(Level.FINE, "System online", "c"); Thread.sleep(150); flash(Level.FINE, "System ready", "c"); Thread.sleep(150); flash(Level.FINE, "System farewell", "c"); Thread.sleep(150); flash(Level.FINE, "", "c"); Thread.sleep(150); flash(Level.FINE, "", "b"); } protected abstract ExecutionStrategy getExecutionStrategy(); public ExitShellRequest getExitShellRequest() { return exitShellRequest; } /** * Obtains the home directory for the current shell instance. * <p> * Note: calls the {@link #getHomeAsString()} method to allow subclasses to * provide the home directory location as string using different * environment-specific strategies. * <p> * If the path indicated by {@link #getHomeAsString()} exists and refers to * a directory, that directory is returned. * <p> * If the path indicated by {@link #getHomeAsString()} exists and refers to * a file, an exception is thrown. * <p> * If the path indicated by {@link #getHomeAsString()} does not exist, it * will be created as a directory. If this fails, an exception will be * thrown. * * @return the home directory for the current shell instance (which is * guaranteed to exist and be a directory) */ public File getHome() { final String rooHome = getHomeAsString(); final File f = new File(rooHome); Validate.isTrue(!f.exists() || f.exists() && f.isDirectory(), "Path '%s' must be a directory, or it must not exist", f.getAbsolutePath()); if (!f.exists()) { f.mkdirs(); } Validate.isTrue( f.exists() && f.isDirectory(), "Path '%s' is not a directory; please specify roo.home system property correctly", f.getAbsolutePath()); return f; } protected abstract String getHomeAsString(); protected abstract Parser getParser(); public String getShellPrompt() { return shellPrompt; } @CliCommand(value = { "//", ";" }, help = "Inline comment markers (start of line only)") public void inlineComment() { } /** * Allows a subclass to log the execution of a well-formed command. This is * invoked after a command has completed, and indicates whether the command * returned normally or returned an exception. Note that attempted commands * that are not well-formed (eg they are missing a mandatory argument) will * never be presented to this method, as the command execution is never * actually attempted in those cases. This method is only invoked if an * attempt is made to execute a particular command. * <p> * Implementations should consider specially handling the "script" commands, * and also indicating whether a command was successful or not. * Implementations that wish to behave consistently with other * {@link AbstractShell} subclasses are encouraged to simply override * {@link #logCommandToOutput(String)} instead, and only override this * method if you actually need to fine-tune the output logic. * * @param line the parsed line (any comments have been removed; never null) * @param successful if the command was successful or not */ protected void logCommandIfRequired(final String line, final boolean successful) { if (line.startsWith("script")) { logCommandToOutput((successful ? "// " : "// [failed] ") + line); } else { logCommandToOutput((successful ? "" : "// [failed] ") + line); } } /** * Allows a subclass to actually write the resulting logged command to some * form of output. This frees subclasses from needing to implement the logic * within {@link #logCommandIfRequired(String, boolean)}. * <p> * Implementations should invoke {@link #getExitShellRequest()} to monitor * any attempts to exit the shell and release resources such as output log * files. * * @param processedLine the line that should be appended to some type of * output (excluding the \n character) */ protected void logCommandToOutput(final String processedLine) { } /** * Opens the given script for reading * * @param script the script to read (required) * @return a non-<code>null</code> input stream */ private InputStream openScript(final File script) { try { return new BufferedInputStream(new FileInputStream(script)); } catch (final FileNotFoundException fnfe) { // Try to find the script via the classloader final Collection<URL> urls = findResources(script.getName()); // Handle search failure Validate.notNull(urls, "Unexpected error looking for '%s'", script.getName()); // Handle the search being OK but the file simply not being present Validate.notEmpty(urls, "Script '%s' not found on disk or in classpath", script); Validate.isTrue( urls.size() == 1, "More than one '%s' was found in the classpath; unable to continue", script); try { return urls.iterator().next().openStream(); } catch (final IOException e) { throw new IllegalStateException(e); } } } @CliCommand(value = { "system properties" }, help = "Shows the shell's properties") public String props() { final Set<String> data = new TreeSet<String>(); for (final Entry<Object, Object> entry : System.getProperties() .entrySet()) { data.add(entry.getKey() + " = " + entry.getValue()); } return StringUtils.join(data, LINE_SEPARATOR) + LINE_SEPARATOR; } private double round(final double valueToRound, final int numberOfDecimalPlaces) { final double multiplicationFactor = Math.pow(10, numberOfDecimalPlaces); final double interestedInZeroDPs = valueToRound * multiplicationFactor; return Math.round(interestedInZeroDPs) / multiplicationFactor; } @CliCommand(value = { "script" }, help = "Parses the specified resource file and executes its commands") public void script( @CliOption(key = { "", "file" }, help = "The file to locate and execute", mandatory = true) final File script, @CliOption(key = "lineNumbers", mandatory = false, specifiedDefaultValue = "true", unspecifiedDefaultValue = "false", help = "Display line numbers when executing the script") final boolean lineNumbers) { Validate.notNull(script, "Script file to parse is required"); final double startedNanoseconds = System.nanoTime(); final InputStream inputStream = openScript(script); try { int i = 0; for (final String line : IOUtils.readLines(inputStream)) { i++; if (lineNumbers) { logger.fine("Line " + i + ": " + line); } else { logger.fine(line); } if (!"".equals(line.trim())) { final boolean success = executeScriptLine(line); if (success && (line.trim().startsWith("q") || line.trim() .startsWith("ex"))) { break; } else if (!success) { // Abort script processing, given something went wrong throw new IllegalStateException( "Script execution aborted"); } } } } catch (final IOException e) { throw new IllegalStateException(e); } finally { IOUtils.closeQuietly(inputStream); final double executionDurationInSeconds = (System.nanoTime() - startedNanoseconds) / 1000000000D; logger.fine("Script required " + round(executionDurationInSeconds, 3) + " seconds to execute"); } } /** * Base implementation of the {@link Shell#setPromptPath(String)} method, * designed for simple shell implementations. Advanced implementations (eg * those that support ANSI codes etc) will likely want to override this * method and set the {@link #shellPrompt} variable directly. * * @param path to set (can be null or empty; must NOT be formatted in any * special way eg ANSI codes) */ public void setPromptPath(final String path) { shellPrompt = (StringUtils.isNotBlank(path) ? path + " " : "") + ROO_PROMPT; } /** * Default implementation of {@link Shell#setPromptPath(String, boolean))} * method to satisfy STS compatibility. * * @param path to set (can be null or empty) * @param overrideStyle */ public void setPromptPath(final String path, final boolean overrideStyle) { setPromptPath(path); } public void setTailor(final Tailor tailor) { this.tailor = tailor; } @CliCommand(value = { "version" }, help = "Displays shell version") public String version( @CliOption(key = "", help = "Special version flags") final String extra) { final StringBuilder sb = new StringBuilder(); if ("roorocks".equals(extra)) { sb.append(" /\\ /l").append(LINE_SEPARATOR); sb.append(" ((.Y(!").append(LINE_SEPARATOR); sb.append(" \\ |/").append(LINE_SEPARATOR); sb.append(" / 6~6,").append(LINE_SEPARATOR); sb.append(" \\ _ +-.").append(LINE_SEPARATOR); sb.append(" \\`-=--^-' \\").append(LINE_SEPARATOR); sb.append( " \\ \\ |\\--------------------------+") .append(LINE_SEPARATOR); sb.append( " _/ \\ | Thanks for loading Roo! |") .append(LINE_SEPARATOR); sb.append( " ( . Y +---------------------------+") .append(LINE_SEPARATOR); sb.append(" /\"\\ `---^--v---.").append( LINE_SEPARATOR); sb.append(" / _ `---\"T~~\\/~\\/").append( LINE_SEPARATOR); sb.append(" / \" ~\\. !").append(LINE_SEPARATOR); sb.append(" _ Y Y.~~~ /'").append(LINE_SEPARATOR); sb.append(" Y^| | | Roo 7").append(LINE_SEPARATOR); sb.append(" | l | / . /'").append(LINE_SEPARATOR); sb.append(" | `L | Y .^/ ~T").append(LINE_SEPARATOR); sb.append(" | l ! | |/ | | ____ ____ ____") .append(LINE_SEPARATOR); sb.append( " | .`\\/' | Y | ! / __ \\/ __ \\/ __ \\") .append(LINE_SEPARATOR); sb.append( " l \"~ j l j L______ / /_/ / / / / / / /") .append(LINE_SEPARATOR); sb.append( " \\,____{ __\"\" ~ __ ,\\_,\\_ / _, _/ /_/ / /_/ /") .append(LINE_SEPARATOR); sb.append(" ~~~~~~~~~~~~~~~~~~~~~~~~~~~ /_/ |_|\\____/\\____/") .append(" ").append(versionInfo()).append(LINE_SEPARATOR); return sb.toString(); } sb.append(" ____ ____ ____ ").append(LINE_SEPARATOR); sb.append(" / __ \\/ __ \\/ __ \\ ").append(LINE_SEPARATOR); sb.append(" / /_/ / / / / / / / ").append(LINE_SEPARATOR); sb.append(" / _, _/ /_/ / /_/ / ").append(" ") - .append("gvNIX 1.2.1-SNAPSHOT distribution").append(LINE_SEPARATOR); + .append("gvNIX 1.3.0-SNAPSHOT distribution").append(LINE_SEPARATOR); sb.append("/_/ |_|\\____/\\____/ ").append(" ").append(versionInfo()) .append(LINE_SEPARATOR); sb.append(LINE_SEPARATOR); return sb.toString(); } }
true
true
public void script( @CliOption(key = { "", "file" }, help = "The file to locate and execute", mandatory = true) final File script, @CliOption(key = "lineNumbers", mandatory = false, specifiedDefaultValue = "true", unspecifiedDefaultValue = "false", help = "Display line numbers when executing the script") final boolean lineNumbers) { Validate.notNull(script, "Script file to parse is required"); final double startedNanoseconds = System.nanoTime(); final InputStream inputStream = openScript(script); try { int i = 0; for (final String line : IOUtils.readLines(inputStream)) { i++; if (lineNumbers) { logger.fine("Line " + i + ": " + line); } else { logger.fine(line); } if (!"".equals(line.trim())) { final boolean success = executeScriptLine(line); if (success && (line.trim().startsWith("q") || line.trim() .startsWith("ex"))) { break; } else if (!success) { // Abort script processing, given something went wrong throw new IllegalStateException( "Script execution aborted"); } } } } catch (final IOException e) { throw new IllegalStateException(e); } finally { IOUtils.closeQuietly(inputStream); final double executionDurationInSeconds = (System.nanoTime() - startedNanoseconds) / 1000000000D; logger.fine("Script required " + round(executionDurationInSeconds, 3) + " seconds to execute"); } } /** * Base implementation of the {@link Shell#setPromptPath(String)} method, * designed for simple shell implementations. Advanced implementations (eg * those that support ANSI codes etc) will likely want to override this * method and set the {@link #shellPrompt} variable directly. * * @param path to set (can be null or empty; must NOT be formatted in any * special way eg ANSI codes) */ public void setPromptPath(final String path) { shellPrompt = (StringUtils.isNotBlank(path) ? path + " " : "") + ROO_PROMPT; } /** * Default implementation of {@link Shell#setPromptPath(String, boolean))} * method to satisfy STS compatibility. * * @param path to set (can be null or empty) * @param overrideStyle */ public void setPromptPath(final String path, final boolean overrideStyle) { setPromptPath(path); } public void setTailor(final Tailor tailor) { this.tailor = tailor; } @CliCommand(value = { "version" }, help = "Displays shell version") public String version( @CliOption(key = "", help = "Special version flags") final String extra) { final StringBuilder sb = new StringBuilder(); if ("roorocks".equals(extra)) { sb.append(" /\\ /l").append(LINE_SEPARATOR); sb.append(" ((.Y(!").append(LINE_SEPARATOR); sb.append(" \\ |/").append(LINE_SEPARATOR); sb.append(" / 6~6,").append(LINE_SEPARATOR); sb.append(" \\ _ +-.").append(LINE_SEPARATOR); sb.append(" \\`-=--^-' \\").append(LINE_SEPARATOR); sb.append( " \\ \\ |\\--------------------------+") .append(LINE_SEPARATOR); sb.append( " _/ \\ | Thanks for loading Roo! |") .append(LINE_SEPARATOR); sb.append( " ( . Y +---------------------------+") .append(LINE_SEPARATOR); sb.append(" /\"\\ `---^--v---.").append( LINE_SEPARATOR); sb.append(" / _ `---\"T~~\\/~\\/").append( LINE_SEPARATOR); sb.append(" / \" ~\\. !").append(LINE_SEPARATOR); sb.append(" _ Y Y.~~~ /'").append(LINE_SEPARATOR); sb.append(" Y^| | | Roo 7").append(LINE_SEPARATOR); sb.append(" | l | / . /'").append(LINE_SEPARATOR); sb.append(" | `L | Y .^/ ~T").append(LINE_SEPARATOR); sb.append(" | l ! | |/ | | ____ ____ ____") .append(LINE_SEPARATOR); sb.append( " | .`\\/' | Y | ! / __ \\/ __ \\/ __ \\") .append(LINE_SEPARATOR); sb.append( " l \"~ j l j L______ / /_/ / / / / / / /") .append(LINE_SEPARATOR); sb.append( " \\,____{ __\"\" ~ __ ,\\_,\\_ / _, _/ /_/ / /_/ /") .append(LINE_SEPARATOR); sb.append(" ~~~~~~~~~~~~~~~~~~~~~~~~~~~ /_/ |_|\\____/\\____/") .append(" ").append(versionInfo()).append(LINE_SEPARATOR); return sb.toString(); } sb.append(" ____ ____ ____ ").append(LINE_SEPARATOR); sb.append(" / __ \\/ __ \\/ __ \\ ").append(LINE_SEPARATOR); sb.append(" / /_/ / / / / / / / ").append(LINE_SEPARATOR); sb.append(" / _, _/ /_/ / /_/ / ").append(" ") .append("gvNIX 1.2.1-SNAPSHOT distribution").append(LINE_SEPARATOR); sb.append("/_/ |_|\\____/\\____/ ").append(" ").append(versionInfo()) .append(LINE_SEPARATOR); sb.append(LINE_SEPARATOR); return sb.toString(); } }
public void script( @CliOption(key = { "", "file" }, help = "The file to locate and execute", mandatory = true) final File script, @CliOption(key = "lineNumbers", mandatory = false, specifiedDefaultValue = "true", unspecifiedDefaultValue = "false", help = "Display line numbers when executing the script") final boolean lineNumbers) { Validate.notNull(script, "Script file to parse is required"); final double startedNanoseconds = System.nanoTime(); final InputStream inputStream = openScript(script); try { int i = 0; for (final String line : IOUtils.readLines(inputStream)) { i++; if (lineNumbers) { logger.fine("Line " + i + ": " + line); } else { logger.fine(line); } if (!"".equals(line.trim())) { final boolean success = executeScriptLine(line); if (success && (line.trim().startsWith("q") || line.trim() .startsWith("ex"))) { break; } else if (!success) { // Abort script processing, given something went wrong throw new IllegalStateException( "Script execution aborted"); } } } } catch (final IOException e) { throw new IllegalStateException(e); } finally { IOUtils.closeQuietly(inputStream); final double executionDurationInSeconds = (System.nanoTime() - startedNanoseconds) / 1000000000D; logger.fine("Script required " + round(executionDurationInSeconds, 3) + " seconds to execute"); } } /** * Base implementation of the {@link Shell#setPromptPath(String)} method, * designed for simple shell implementations. Advanced implementations (eg * those that support ANSI codes etc) will likely want to override this * method and set the {@link #shellPrompt} variable directly. * * @param path to set (can be null or empty; must NOT be formatted in any * special way eg ANSI codes) */ public void setPromptPath(final String path) { shellPrompt = (StringUtils.isNotBlank(path) ? path + " " : "") + ROO_PROMPT; } /** * Default implementation of {@link Shell#setPromptPath(String, boolean))} * method to satisfy STS compatibility. * * @param path to set (can be null or empty) * @param overrideStyle */ public void setPromptPath(final String path, final boolean overrideStyle) { setPromptPath(path); } public void setTailor(final Tailor tailor) { this.tailor = tailor; } @CliCommand(value = { "version" }, help = "Displays shell version") public String version( @CliOption(key = "", help = "Special version flags") final String extra) { final StringBuilder sb = new StringBuilder(); if ("roorocks".equals(extra)) { sb.append(" /\\ /l").append(LINE_SEPARATOR); sb.append(" ((.Y(!").append(LINE_SEPARATOR); sb.append(" \\ |/").append(LINE_SEPARATOR); sb.append(" / 6~6,").append(LINE_SEPARATOR); sb.append(" \\ _ +-.").append(LINE_SEPARATOR); sb.append(" \\`-=--^-' \\").append(LINE_SEPARATOR); sb.append( " \\ \\ |\\--------------------------+") .append(LINE_SEPARATOR); sb.append( " _/ \\ | Thanks for loading Roo! |") .append(LINE_SEPARATOR); sb.append( " ( . Y +---------------------------+") .append(LINE_SEPARATOR); sb.append(" /\"\\ `---^--v---.").append( LINE_SEPARATOR); sb.append(" / _ `---\"T~~\\/~\\/").append( LINE_SEPARATOR); sb.append(" / \" ~\\. !").append(LINE_SEPARATOR); sb.append(" _ Y Y.~~~ /'").append(LINE_SEPARATOR); sb.append(" Y^| | | Roo 7").append(LINE_SEPARATOR); sb.append(" | l | / . /'").append(LINE_SEPARATOR); sb.append(" | `L | Y .^/ ~T").append(LINE_SEPARATOR); sb.append(" | l ! | |/ | | ____ ____ ____") .append(LINE_SEPARATOR); sb.append( " | .`\\/' | Y | ! / __ \\/ __ \\/ __ \\") .append(LINE_SEPARATOR); sb.append( " l \"~ j l j L______ / /_/ / / / / / / /") .append(LINE_SEPARATOR); sb.append( " \\,____{ __\"\" ~ __ ,\\_,\\_ / _, _/ /_/ / /_/ /") .append(LINE_SEPARATOR); sb.append(" ~~~~~~~~~~~~~~~~~~~~~~~~~~~ /_/ |_|\\____/\\____/") .append(" ").append(versionInfo()).append(LINE_SEPARATOR); return sb.toString(); } sb.append(" ____ ____ ____ ").append(LINE_SEPARATOR); sb.append(" / __ \\/ __ \\/ __ \\ ").append(LINE_SEPARATOR); sb.append(" / /_/ / / / / / / / ").append(LINE_SEPARATOR); sb.append(" / _, _/ /_/ / /_/ / ").append(" ") .append("gvNIX 1.3.0-SNAPSHOT distribution").append(LINE_SEPARATOR); sb.append("/_/ |_|\\____/\\____/ ").append(" ").append(versionInfo()) .append(LINE_SEPARATOR); sb.append(LINE_SEPARATOR); return sb.toString(); } }
diff --git a/com/ai/myplugin/ShellCmdSensor.java b/com/ai/myplugin/ShellCmdSensor.java index 738aeb8..3d135a1 100644 --- a/com/ai/myplugin/ShellCmdSensor.java +++ b/com/ai/myplugin/ShellCmdSensor.java @@ -1,237 +1,237 @@ /** * User: pizuricv * Date: 12/20/12 */ package com.ai.myplugin; import com.ai.bayes.model.BayesianNetwork; import com.ai.bayes.plugins.BNSensorPlugin; import com.ai.bayes.scenario.TestResult; import com.ai.util.resource.TestSessionContext; import net.xeoh.plugins.base.annotations.PluginImplementation; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.StringTokenizer; @PluginImplementation public class ShellCmdSensor implements BNSensorPlugin{ private String command; private ArrayList<Long> threshold = new ArrayList<Long>(); private ArrayList<String> states = new ArrayList<String>(); private static final String parseString = "result="; private int exitVal = -1; private String result = "error"; private ShellCmdSensor(){}; @Override public String[] getRequiredProperties() { return new String [] {"threshold", "command"} ; } //comma separated list of thresholds @Override public void setProperty(String s, Object o) { if("threshold".endsWith(s)){ if(o instanceof String) { String input = (String) o; StringTokenizer stringTokenizer = new StringTokenizer(input, ","); int i = 0; states.add("level_"+ i++); while(stringTokenizer.hasMoreElements()){ threshold.add(Long.parseLong(stringTokenizer.nextToken())); states.add("level_"+ i++); } } else { threshold.add((Long) o); states.add("level_0"); states.add("level_1"); } Collections.reverse(threshold); } else if ("command".equals(s)){ command = o.toString(); } } @Override public Object getProperty(String s) { if("threshold".endsWith(s)){ return threshold; } else if("command".endsWith(s)){ return command; } else{ throw new RuntimeException("Property " + s + " not recognised by " + getName()); } } @Override public String getDescription() { return "Shell script, in order to parse the result correctly, add the line in the script in format result=$RES\n" + "example: \"result=5\", and 5 will be compared to the threshold\n" + "the result state is in a format level_$num, ant the number of states is the number_of_thresholds+1"; } @Override public BNSensorPlugin getNewInstance() { return new ShellCmdSensor(); } @Override public void setNodeName(String s) { } @Override public void setBayesianNetwork(BayesianNetwork bayesianNetwork) { } @Override public TestResult execute(TestSessionContext testSessionContext) { try { Runtime rt = Runtime.getRuntime(); Process process = rt.exec(command); StreamGobbler errorGobbler = new StreamGobbler(process.getErrorStream(), StdType.ERROR); StreamGobbler outputGobbler = new StreamGobbler(process.getInputStream(), StdType.OUTPUT); errorGobbler.start(); outputGobbler.start(); exitVal = process.waitFor(); System.out.println(getName() + " ExitValue: " + exitVal); return new TestResult() { { (new Runnable() { //waitForResult is not a timeout for the command itself, but how long you wait before the stream of //output data is processed, should be really fast. private int waitForResult = 3; @Override public void run() { while("error".equals(result) && waitForResult > 0) try { Thread.sleep(1000); System.out.print("."); waitForResult --; } catch (InterruptedException e) { e.printStackTrace(); break; } } } ).run(); } @Override public boolean isSuccess() { - return exitVal == 0 && !("error").equals("error"); + return exitVal == 0 && !("error").equals("command"); } @Override public String getName() { return command; } @Override public String getObserverState() { return result; } } ; } catch (Throwable t) { System.err.println(t.getLocalizedMessage()); t.printStackTrace(); throw new RuntimeException(t); } } @Override public String getName() { return "Shell sensor"; } @Override public String[] getSupportedStates() { return states.toArray(new String[states.size()]); } enum StdType { ERROR, OUTPUT } private class StreamGobbler extends Thread { InputStream is; private StdType stdType; StreamGobbler(InputStream is, StdType type) { this.is = is; this.stdType = type; } public void run() { try { InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line; while ((line = br.readLine()) != null) logLine(line, stdType); } catch (IOException ioe) { ioe.printStackTrace(); } } private void logLine(String line, StdType type) { if(type.equals(StdType.ERROR)){ System.err.println("Error executing the script >" + line); throw new RuntimeException("Error executing the script "+ getName() + " : error is "+ line); } else{ if(line.startsWith(parseString)){ System.out.println("Found result " + line); result = mapResult(line.replaceAll(parseString,"")); } else{ System.out.println(line); } } } } private String mapResult(String result) { Long res = Long.parseLong(result); int i = states.size() - 1; for(Long l : threshold){ if(res > l){ return "level_" + i; } i --; } return "level_0"; } public static void main(String []args){ ShellCmdSensor shellExecutor = (ShellCmdSensor) new ShellCmdSensor().getNewInstance(); shellExecutor.setProperty("threshold", "1,2,4,12,14"); shellExecutor.setProperty("command", "C:\\Users\\pizuricv\\MyProjects\\BayesProject\\script\\sensor.bat"); System.out.println(Arrays.toString(shellExecutor.getSupportedStates())); TestResult testResult = shellExecutor.execute(null); System.out.println(testResult.getObserverState()); shellExecutor = (ShellCmdSensor) new ShellCmdSensor().getNewInstance(); shellExecutor.setProperty("threshold", 13l); shellExecutor.setProperty("command", "C:\\Users\\pizuricv\\MyProjects\\BayesProject\\script\\sensor.bat"); System.out.println(Arrays.toString(shellExecutor.getSupportedStates())); testResult = shellExecutor.execute(null); System.out.println(testResult.getObserverState()); } }
true
true
public TestResult execute(TestSessionContext testSessionContext) { try { Runtime rt = Runtime.getRuntime(); Process process = rt.exec(command); StreamGobbler errorGobbler = new StreamGobbler(process.getErrorStream(), StdType.ERROR); StreamGobbler outputGobbler = new StreamGobbler(process.getInputStream(), StdType.OUTPUT); errorGobbler.start(); outputGobbler.start(); exitVal = process.waitFor(); System.out.println(getName() + " ExitValue: " + exitVal); return new TestResult() { { (new Runnable() { //waitForResult is not a timeout for the command itself, but how long you wait before the stream of //output data is processed, should be really fast. private int waitForResult = 3; @Override public void run() { while("error".equals(result) && waitForResult > 0) try { Thread.sleep(1000); System.out.print("."); waitForResult --; } catch (InterruptedException e) { e.printStackTrace(); break; } } } ).run(); } @Override public boolean isSuccess() { return exitVal == 0 && !("error").equals("error"); } @Override public String getName() { return command; } @Override public String getObserverState() { return result; } } ; } catch (Throwable t) { System.err.println(t.getLocalizedMessage()); t.printStackTrace(); throw new RuntimeException(t); } }
public TestResult execute(TestSessionContext testSessionContext) { try { Runtime rt = Runtime.getRuntime(); Process process = rt.exec(command); StreamGobbler errorGobbler = new StreamGobbler(process.getErrorStream(), StdType.ERROR); StreamGobbler outputGobbler = new StreamGobbler(process.getInputStream(), StdType.OUTPUT); errorGobbler.start(); outputGobbler.start(); exitVal = process.waitFor(); System.out.println(getName() + " ExitValue: " + exitVal); return new TestResult() { { (new Runnable() { //waitForResult is not a timeout for the command itself, but how long you wait before the stream of //output data is processed, should be really fast. private int waitForResult = 3; @Override public void run() { while("error".equals(result) && waitForResult > 0) try { Thread.sleep(1000); System.out.print("."); waitForResult --; } catch (InterruptedException e) { e.printStackTrace(); break; } } } ).run(); } @Override public boolean isSuccess() { return exitVal == 0 && !("error").equals("command"); } @Override public String getName() { return command; } @Override public String getObserverState() { return result; } } ; } catch (Throwable t) { System.err.println(t.getLocalizedMessage()); t.printStackTrace(); throw new RuntimeException(t); } }
diff --git a/riot/src/org/riotfamily/riot/list/ui/ListModel.java b/riot/src/org/riotfamily/riot/list/ui/ListModel.java index f0ff71b36..36d2c4a70 100644 --- a/riot/src/org/riotfamily/riot/list/ui/ListModel.java +++ b/riot/src/org/riotfamily/riot/list/ui/ListModel.java @@ -1,138 +1,140 @@ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1 * 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 Riot. * * The Initial Developer of the Original Code is * Neteye GmbH. * Portions created by the Initial Developer are Copyright (C) 2006 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Felix Gnass <[email protected]> * * ***** END LICENSE BLOCK ***** */ package org.riotfamily.riot.list.ui; import java.util.List; /** * @author Felix Gnass <[email protected]> * @since 6.4 */ public class ListModel { private String editorId; private String parentId; private List columns; private List items; private List listCommands; private int itemCommandCount; private int pages; private int pageSize; private int currentPage; private int itemsTotal; private String filterFormHtml; public ListModel(int itemsTotal, int pageSize, int currentPage) { this.itemsTotal = itemsTotal; this.pageSize = pageSize; this.currentPage = currentPage; - pages = (int) itemsTotal / pageSize + 1; - if (itemsTotal % pageSize == 0) { - pages--; + if (pageSize > 0) { + pages = (int) itemsTotal / pageSize + 1; + if (itemsTotal % pageSize == 0) { + pages--; + } } } public String getEditorId() { return this.editorId; } public void setEditorId(String editorId) { this.editorId = editorId; } public String getParentId() { return this.parentId; } public void setParentId(String parentId) { this.parentId = parentId; } public List getColumns() { return this.columns; } public void setColumns(List columns) { this.columns = columns; } public List getItems() { return this.items; } public void setItems(List items) { this.items = items; } public List getListCommands() { return this.listCommands; } public void setListCommands(List listCommands) { this.listCommands = listCommands; } public int getItemCommandCount() { return this.itemCommandCount; } public void setItemCommandCount(int itemCommandCount) { this.itemCommandCount = itemCommandCount; } public int getCurrentPage() { return this.currentPage; } public int getItemsTotal() { return this.itemsTotal; } public int getPages() { return this.pages; } public int getPageSize() { return this.pageSize; } public String getFilterFormHtml() { return this.filterFormHtml; } public void setFilterFormHtml(String filterFormHtml) { this.filterFormHtml = filterFormHtml; } }
true
true
public ListModel(int itemsTotal, int pageSize, int currentPage) { this.itemsTotal = itemsTotal; this.pageSize = pageSize; this.currentPage = currentPage; pages = (int) itemsTotal / pageSize + 1; if (itemsTotal % pageSize == 0) { pages--; } }
public ListModel(int itemsTotal, int pageSize, int currentPage) { this.itemsTotal = itemsTotal; this.pageSize = pageSize; this.currentPage = currentPage; if (pageSize > 0) { pages = (int) itemsTotal / pageSize + 1; if (itemsTotal % pageSize == 0) { pages--; } } }
diff --git a/src/keepcalm/mods/bukkit/forgeHandler/ForgeEventHandler.java b/src/keepcalm/mods/bukkit/forgeHandler/ForgeEventHandler.java index 4988dee..5fb4589 100644 --- a/src/keepcalm/mods/bukkit/forgeHandler/ForgeEventHandler.java +++ b/src/keepcalm/mods/bukkit/forgeHandler/ForgeEventHandler.java @@ -1,822 +1,822 @@ package keepcalm.mods.bukkit.forgeHandler; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import keepcalm.mods.bukkit.*; import keepcalm.mods.bukkitforge.BukkitForgePlayerCache; import keepcalm.mods.events.forgeex.BlockDestroyEvent; import keepcalm.mods.events.forgeex.CreeperExplodeEvent; import keepcalm.mods.events.forgeex.DispenseItemEvent; import keepcalm.mods.events.forgeex.LightningStrikeEvent; import keepcalm.mods.events.forgeex.LiquidFlowEvent; import keepcalm.mods.events.forgeex.PlayerDamageBlockEvent; import keepcalm.mods.events.forgeex.PlayerMoveEvent; import keepcalm.mods.events.forgeex.PlayerUseItemEvent; import keepcalm.mods.events.forgeex.PressurePlateInteractEvent; import keepcalm.mods.events.forgeex.SheepDyeEvent; import keepcalm.mods.events.forgeex.SignChangeEvent; import net.minecraft.block.Block; import net.minecraft.command.ICommandSender; import net.minecraft.entity.EntityLiving; import net.minecraft.entity.effect.EntityLightningBolt; import net.minecraft.entity.item.EntityItem; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.entity.player.EnumStatus; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemFlintAndSteel; import net.minecraft.item.ItemStack; import net.minecraft.server.MinecraftServer; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.ChunkCoordinates; import net.minecraft.util.DamageSource; import net.minecraft.util.MathHelper; import net.minecraft.util.Vec3; import net.minecraft.world.WorldServer; import net.minecraftforge.common.ForgeDirection; import net.minecraftforge.event.CommandEvent; import net.minecraftforge.event.Event.Result; import net.minecraftforge.event.ForgeSubscribe; import net.minecraftforge.event.ServerChatEvent; import net.minecraftforge.event.entity.EntityJoinWorldEvent; import net.minecraftforge.event.entity.item.ItemExpireEvent; import net.minecraftforge.event.entity.item.ItemTossEvent; import net.minecraftforge.event.entity.living.LivingAttackEvent; import net.minecraftforge.event.entity.living.LivingDeathEvent; import net.minecraftforge.event.entity.living.LivingHurtEvent; import net.minecraftforge.event.entity.living.LivingSetAttackTargetEvent; import net.minecraftforge.event.entity.player.AttackEntityEvent; import net.minecraftforge.event.entity.player.EntityItemPickupEvent; import net.minecraftforge.event.entity.player.FillBucketEvent; import net.minecraftforge.event.entity.player.PlayerInteractEvent; import net.minecraftforge.event.entity.player.PlayerSleepInBedEvent; import net.minecraftforge.event.terraingen.PopulateChunkEvent; import net.minecraftforge.event.terraingen.SaplingGrowTreeEvent; import net.minecraftforge.event.world.ChunkEvent; import net.minecraftforge.event.world.WorldEvent; import org.bukkit.Bukkit; import org.bukkit.DyeColor; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.TreeType; import org.bukkit.World; import org.bukkit.block.BlockState; import org.bukkit.command.CommandSender; import org.bukkit.craftbukkit.CraftChunk; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.craftbukkit.block.CraftBlock; import org.bukkit.craftbukkit.block.CraftBlockFake; import org.bukkit.craftbukkit.entity.CraftCreeper; import org.bukkit.craftbukkit.entity.CraftEntity; import org.bukkit.craftbukkit.entity.CraftItem; import org.bukkit.craftbukkit.entity.CraftLightningStrike; import org.bukkit.craftbukkit.entity.CraftLivingEntity; import org.bukkit.craftbukkit.entity.CraftPlayer; import org.bukkit.craftbukkit.entity.CraftSheep; import org.bukkit.craftbukkit.event.CraftEventFactory; import org.bukkit.craftbukkit.inventory.CraftItemStack; import org.bukkit.entity.LivingEntity; import org.bukkit.event.block.Action; import org.bukkit.event.block.BlockCanBuildEvent; import org.bukkit.event.block.BlockDamageEvent; import org.bukkit.event.block.BlockDispenseEvent; import org.bukkit.event.block.BlockIgniteEvent; import org.bukkit.event.block.BlockIgniteEvent.IgniteCause; import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.event.block.BlockSpreadEvent; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityDamageEvent.DamageCause; import org.bukkit.event.entity.EntityDeathEvent; import org.bukkit.event.entity.EntityExplodeEvent; import org.bukkit.event.entity.EntityTargetEvent.TargetReason; import org.bukkit.event.entity.SheepDyeWoolEvent; import org.bukkit.event.player.*; import org.bukkit.event.server.ServerCommandEvent; import org.bukkit.event.world.StructureGrowEvent; import org.bukkit.event.world.WorldInitEvent; import org.bukkit.event.world.WorldSaveEvent; import org.bukkit.event.world.WorldUnloadEvent; import org.bukkit.util.Vector; import com.google.common.base.Joiner; import com.google.common.collect.Sets; import cpw.mods.fml.common.FMLCommonHandler; /** * * @author keepcalm * * TODO: Fix up more events - Forge doesn't include all the required events. * */ public class ForgeEventHandler { public static HashMap<String, String> playerDisplayNames = new HashMap<String, String>(); private List<EntityLightningBolt> cancelled = new ArrayList<EntityLightningBolt>(); public static boolean ready = false; private final boolean isClient = FMLCommonHandler.instance().getEffectiveSide().isClient(); @ForgeSubscribe(receiveCanceled = true) public void onEntityJoinWorld(EntityJoinWorldEvent ev) { if (!ready || isClient) return; if (ev.entity instanceof EntityLiving && !(ev.entity instanceof EntityPlayer)) {// || ev.entity instanceof EntityPlayerMP) { ev.setCanceled(BukkitEventRouters.Entity.CreatureSpawn.callEvent(ev.isCanceled(), ToBukkitEvent.CreatureSpawn(ev)).isCancelled()); } } @ForgeSubscribe(receiveCanceled = true) public void onItemExpire(ItemExpireEvent ev) { if (!ready || isClient) return; BukkitEventRouters.Entity.ItemDespawn.callEvent(ev.isCanceled(), ToBukkitEvent.ItemDespawn(ev)); } @ForgeSubscribe(receiveCanceled = true) public void onItemTossEvent(ItemTossEvent ev) { if (!ready || isClient) return; BukkitEventRouters.Entity.ItemSpawn.callEvent(ev.isCanceled(), ToBukkitEvent.ItemSpawn(ev)); } @ForgeSubscribe(receiveCanceled = true) public void onLivingAttack(LivingAttackEvent ev) { if (!ready || isClient) return; EntityDamageEvent bev; if (ev.source.getSourceOfDamage() != null) { bev = new EntityDamageByEntityEvent( CraftEntity.getEntity(CraftServer.instance(), ev.source.getSourceOfDamage()), CraftEntity.getEntity(CraftServer.instance(), ev.entityLiving), getDamageCause(ev.source), ev.ammount); } else { bev = new EntityDamageEvent( CraftEntity.getEntity(CraftServer.instance(), ev.entityLiving), getDamageCause(ev.source), ev.ammount); } bev.setCancelled(ev.isCanceled()); Bukkit.getPluginManager().callEvent(bev); ev.setCanceled(bev.isCancelled()); } private DamageCause getDamageCause(DamageSource source) { return ToBukkit.damageCause(source); } @ForgeSubscribe(receiveCanceled = true) public void onLivingDeathEvent(LivingDeathEvent ev) { if (!ready || isClient) return; LivingEntity e; CraftEntity j = CraftEntity.getEntity(CraftServer.instance(), ev.entityLiving); if (!(j instanceof LivingEntity)) { e = new CraftLivingEntity(CraftServer.instance(), ev.entityLiving); } else { e = (LivingEntity) j; } List<org.bukkit.inventory.ItemStack> stacks = new ArrayList<org.bukkit.inventory.ItemStack>(); for (EntityItem i : ev.entityLiving.capturedDrops) { ItemStack vanilla = i.getEntityItem(); stacks.add(new CraftItemStack(vanilla)); } EntityDeathEvent bev = new EntityDeathEvent(e, stacks); bev.setDroppedExp(ev.entityLiving.experienceValue); Bukkit.getPluginManager().callEvent(bev); } /*@ForgeSubscribe(receiveCanceled = true) public void onLivingFall(LivingFallEvent ev) { CraftEventFactory.callE }*/ @ForgeSubscribe(receiveCanceled = true) public void onLivingDamage(LivingHurtEvent ev) { if (!ready || isClient) return; DamageCause dc = getDamageCause(ev.source); CraftEventFactory.callEntityDamageEvent(ev.source.getEntity(), ev.entity, dc, ev.ammount); } @ForgeSubscribe(receiveCanceled = true) public void onTarget(LivingSetAttackTargetEvent ev) { if (!ready || isClient) return; CraftEventFactory.callEntityTargetEvent(ev.entity, ev.target, TargetReason.CUSTOM); } /*@ForgeSubscribe(receiveCanceled = true) public void onCartCollide(MinecartCollisionEvent ev) { CraftEventFactory. }*/ /* @ForgeSubscribe(receiveCanceled = true) *//** * Only called when a player fires * Forge doesn't give us the EntityArrow. * @param ev *//* public void bowFire(ArrowLooseEvent ev) { if (!ready || isClient) return; CraftEventFactory.callEntityShootBowEvent(ev.entityPlayer, ev.bow, (EntityArrow)ev.entity, ev.charge); }*/ @ForgeSubscribe(receiveCanceled = true) public void playerVEntity(AttackEntityEvent ev) { if (!ready || isClient) return; CraftEventFactory.callEntityDamageEvent(ev.entityPlayer, ev.target, DamageCause.ENTITY_ATTACK, ev.entityPlayer.inventory.getDamageVsEntity(ev.target)); } /* @ForgeSubscribe(receiveCanceled = true) public void bonemeal(BonemealEvent ev) { }*/ @ForgeSubscribe(receiveCanceled = true) public void onPlayerInteraction(final PlayerInteractEvent ev) { if (!ready || isClient) return; if (ev.action == PlayerInteractEvent.Action.RIGHT_CLICK_BLOCK) { if (!ev.entityPlayer.isSneaking() && ev.entityPlayer.worldObj.blockHasTileEntity(ev.x, ev.y, ev.z)) { return; } if (ev.entityPlayer.inventory.getCurrentItem() == null) { return; } if (ev.entityPlayer.inventory.getCurrentItem().getItem() instanceof ItemBlock) { if (BukkitContainer.DEBUG) System.out.println("PLACE!"); final CraftItemStack itemInHand = new CraftItemStack(ev.entityPlayer.inventory.getCurrentItem()); final int blockX = ev.x + ForgeDirection.getOrientation(ev.face).offsetX; final int blockY = ev.y + ForgeDirection.getOrientation(ev.face).offsetY; final int blockZ = ev.z + ForgeDirection.getOrientation(ev.face).offsetZ; EntityPlayerMP forgePlayerMP; if (!(ev.entityPlayer instanceof EntityPlayerMP)) { forgePlayerMP = BukkitContainer.MOD_PLAYER; } else { forgePlayerMP = (EntityPlayerMP) ev.entityPlayer; } final CraftPlayer thePlayer = BukkitForgePlayerCache.getCraftPlayer(forgePlayerMP); - final CraftBlock beforeBlock = new CraftBlock(new CraftChunk(ev.entity.worldObj.getChunkFromBlockCoords(ev.x, ev.y)), blockX, blockY, blockZ); + final CraftBlock beforeBlock = new CraftBlock(new CraftChunk(ev.entity.worldObj.getChunkFromBlockCoords(blockX, blockZ)), blockX, blockY, blockZ); WorldServer world = (WorldServer) ev.entity.worldObj; int minX = world.getSpawnPoint().posX; int minY = world.getSpawnPoint().posY; int minZ = world.getSpawnPoint().posZ; int sps = MinecraftServer.getServer().getSpawnProtectionSize(); int maxX = minX + sps; int maxY = minY + sps; int maxZ = minZ + sps; AxisAlignedBB aabb = AxisAlignedBB.getBoundingBox(minX, minY, minZ, maxX, maxY, maxZ); final boolean canBuild; if (aabb.isVecInside(Vec3.fakePool.getVecFromPool(blockX, blockY, blockZ))) { canBuild = false; } else { canBuild = true; } BlockCanBuildEvent can = new BlockCanBuildEvent(beforeBlock, beforeBlock.getTypeId(), canBuild); can.setBuildable(!ev.isCanceled()); Bukkit.getPluginManager().callEvent(can); final CraftBlock placedBlock = new CraftBlockFake(new CraftChunk(ev.entity.worldObj.getChunkFromBlockCoords(ev.x, ev.y)), blockX, blockY, blockZ, itemInHand.getTypeId(), itemInHand.getDurability()); BlockPlaceEvent bev = new BlockPlaceEvent(placedBlock, beforeBlock.getState(), placedBlock, itemInHand, thePlayer, can.isBuildable()); bev.setCancelled(ev.isCanceled()); Bukkit.getPluginManager().callEvent(bev); ev.setCanceled(bev.isCancelled() || !bev.canBuild()); } else if (ev.entityPlayer.inventory.getCurrentItem().getItem() instanceof ItemFlintAndSteel) { // ignite EntityPlayerMP fp; if (!(ev.entityPlayer instanceof EntityPlayerMP)) { fp = BukkitContainer.MOD_PLAYER; } else { fp = (EntityPlayerMP) ev.entityPlayer; } BlockIgniteEvent bev = new BlockIgniteEvent(new CraftBlock(new CraftChunk(ev.entity.worldObj.getChunkFromBlockCoords(ev.x, ev.y)), ev.x, ev.y, ev.z), IgniteCause.FLINT_AND_STEEL, BukkitForgePlayerCache.getCraftPlayer(fp)); bev.setCancelled(ev.isCanceled()); Bukkit.getPluginManager().callEvent(bev); ev.setCanceled(bev.isCancelled()); } } } @ForgeSubscribe(receiveCanceled = true) public void pickUp(EntityItemPickupEvent ev) { if (!ready || isClient) return; // assume all picked up at the same time EntityPlayerMP fp; if (!(ev.entityPlayer instanceof EntityPlayerMP)) { fp = BukkitContainer.MOD_PLAYER; } else { fp = (EntityPlayerMP) ev.entityPlayer; } PlayerPickupItemEvent bev = new PlayerPickupItemEvent(BukkitForgePlayerCache.getCraftPlayer(fp), new CraftItem(CraftServer.instance(), ev.item), 0); bev.setCancelled(ev.entityLiving.captureDrops); bev.setCancelled(ev.isCanceled()); Bukkit.getPluginManager().callEvent(bev); if (bev.isCancelled()) { ev.setCanceled(true); ev.setResult(Result.DENY); } } @ForgeSubscribe(receiveCanceled = true) public void fillCraft(FillBucketEvent ev) { if (!ready || isClient) return; EntityPlayerMP fp; if (!(ev.entityPlayer instanceof EntityPlayerMP)) { fp = BukkitContainer.MOD_PLAYER; } else { fp = (EntityPlayerMP) ev.entityPlayer; } CraftBlock blk = new CraftBlock(new CraftChunk(ev.entity.worldObj.getChunkFromBlockCoords(ev.target.blockX, ev.target.blockZ)), ev.target.blockX, ev.target.blockY, ev.target.blockZ); PlayerBucketFillEvent bev = new PlayerBucketFillEvent(BukkitForgePlayerCache.getCraftPlayer(fp), blk, CraftBlock.notchToBlockFace(ev.target.sideHit), Material.BUCKET, new CraftItemStack(ev.result)); bev.setCancelled(ev.isCanceled()); Bukkit.getPluginManager().callEvent(bev); if (bev.isCancelled()) { ev.setCanceled(true); ev.setResult(Result.DENY); } } @ForgeSubscribe(receiveCanceled = true) public void interactEvent(PlayerInteractEvent ev) { if (!ready || isClient) return; org.bukkit.event.player.PlayerInteractEvent bev = BukkitEventRouters.Player.PlayerInteract.callEvent(ev.isCanceled(), ToBukkitEvent.PlayerInteract(ev)); if (bev.isCancelled()) { ev.setCanceled(true); ev.setResult(Result.DENY); } } @ForgeSubscribe(receiveCanceled = true) public void playerGoToSleep(PlayerSleepInBedEvent ev) { if (!ready || isClient) return; org.bukkit.event.player.PlayerBedEnterEvent bev = new PlayerBedEnterEvent(BukkitForgePlayerCache.getCraftPlayer((EntityPlayerMP) ev.entityPlayer), new CraftBlock(new CraftChunk(ev.entityPlayer.worldObj.getChunkFromBlockCoords(ev.x, ev.z)), ev.x, ev.y, ev.z)); bev.setCancelled(ev.isCanceled()); Bukkit.getPluginManager().callEvent(bev); if (bev.isCancelled()) { ev.setCanceled(true); ev.result = EnumStatus.OTHER_PROBLEM; } } @ForgeSubscribe(receiveCanceled = true) public void chunkLoadEvent(ChunkEvent.Load ev) { if (!ready || isClient) return; BukkitEventRouters.World.ChunkLoad.callEvent( false, ToBukkitEvent.ChunkLoad(ev) ); } @ForgeSubscribe(receiveCanceled = true) public void chunkUnloadEvent(ChunkEvent.Unload ev) { if (!ready || isClient) return; BukkitEventRouters.World.ChunkUnload.callEvent(false, ToBukkitEvent.ChunkUnload(ev)); } @ForgeSubscribe(receiveCanceled = true) public void serverChat(ServerChatEvent ev) { if (!ready) return; String newName = ev.player.username; if (playerDisplayNames.containsKey(newName)) { newName = playerDisplayNames.get(newName); } CraftPlayer whom = BukkitForgePlayerCache.getCraftPlayer(ev.player); AsyncPlayerChatEvent ev1 = new AsyncPlayerChatEvent(false, whom, ev.message, Sets.newHashSet(CraftServer.instance().getOnlinePlayers())); PlayerChatEvent bev = new PlayerChatEvent(whom, ev.message); bev.setCancelled(ev.isCanceled()); ev1.setCancelled(ev.isCanceled()); ev1 = CraftEventFactory.callEvent(ev1); bev.setCancelled(ev1.isCancelled()); bev = CraftEventFactory.callEvent(bev); String newLine = String.format(ev1.getFormat(), new Object[] { newName, ev1.getMessage() }); ev.line = newLine; ev.setCanceled(ev1.isCancelled() || bev.isCancelled()); } @ForgeSubscribe(receiveCanceled = true) public void saplingGrow(SaplingGrowTreeEvent ev) { if (!ready || isClient) return; int blockID = ev.world.getBlockId(ev.x, ev.y, ev.z); //int blockMeta = ev.world.getBlockMetadata(ev.x, ev.y, ev.z); if (Block.blocksList[blockID] == Block.sapling) { TreeType type = TreeType.TREE; StructureGrowEvent bev = new StructureGrowEvent(new Location(CraftServer.instance().getWorld(ev.world.provider.dimensionId),ev.x,ev.y,ev.z), type, false, null, new ArrayList<BlockState>()); bev.setCancelled(ev.isCanceled()); Bukkit.getPluginManager().callEvent(bev); ev.setCanceled((bev.isCancelled())); } } @ForgeSubscribe(receiveCanceled = true) public void serverCmd(CommandEvent ev) { CommandSender s; /* * TODO: Impelement more of these * EntityClientPlayerMP, * EntityOtherPlayerMP, * EntityPlayer, * EntityPlayerMP, * IntegratedServer, * MinecraftServer, * RConConsoleSource, * TileEntityCommandBlock * */ ICommandSender sender = ev.sender; if (sender instanceof EntityPlayerMP) { s = BukkitForgePlayerCache.getCraftPlayer((EntityPlayerMP) ev.sender); } else { s = Bukkit.getConsoleSender(); } if (ev.isCanceled()) { return; } ServerCommandEvent bev = new ServerCommandEvent(s, (ev.command.getCommandName() + " " + Joiner.on(' ').join(ev.parameters)).trim()); Bukkit.getPluginManager().callEvent(bev); } // used PlayerInteractEvent for this @ForgeSubscribe(receiveCanceled = true) public void tryPlaceBlock(PlayerUseItemEvent ev) { if (ev.stack.getItem() instanceof ItemBlock) { ItemBlock block = (ItemBlock) ev.stack.getItem(); CraftChunk chunk = new CraftChunk(ev.world.getChunkFromBlockCoords(ev.x, ev.z)); ChunkCoordinates spawn = ev.world.getSpawnPoint(); int spawnRadius = CraftServer.instance().getSpawnRadius(); boolean canBuild = AxisAlignedBB.getAABBPool().getAABB(spawn.posX, spawn.posY, spawn.posZ, spawn.posX + spawnRadius, spawn.posY + spawnRadius, spawn.posZ + spawnRadius).isVecInside(Vec3.createVectorHelper(ev.x, ev.y, ev.z)); CraftBlock bblock = new CraftBlock(chunk, ev.x, ev.y, ev.z); BlockCanBuildEvent bukkitEv = new BlockCanBuildEvent(bblock, block.getBlockID(), canBuild); bukkitEv.setBuildable(ev.isCanceled()); if (!bukkitEv.isBuildable() && canBuild) { // it was changed // and since we were called from AFTER the actual placement, we can just break the block. bblock.breakNaturally(); } } } @ForgeSubscribe(receiveCanceled = true) public void dispenseItem(DispenseItemEvent ev) { if (!ready || isClient) return; ItemStack item = ev.stackToDispense.copy(); item.stackSize = 1; //IRegistry dispenserRegistry = BlockDispenser.dispenseBehaviorRegistry; //IBehaviorDispenseItem theBehaviour = (IBehaviorDispenseItem) dispenserRegistry.func_82594_a(item.getItem()); BlockDispenseEvent bev = new BlockDispenseEvent( new CraftBlock( new CraftChunk(ev.blockWorld.getChunkFromBlockCoords(ev.blockX, ev.blockZ)), ev.blockX, ev.blockY, ev.blockZ), new CraftItemStack(item), new Vector()); bev.setCancelled(ev.isCanceled()); Bukkit.getPluginManager().callEvent(bev); ev.setCanceled(bev.isCancelled()); } @ForgeSubscribe(receiveCanceled = true) public void playerDamageBlock(PlayerDamageBlockEvent ev) { if (!ready || isClient) return; BlockDamageEvent bev = new BlockDamageEvent(BukkitForgePlayerCache.getCraftPlayer((EntityPlayerMP) ev.entityPlayer), new CraftBlock(new CraftChunk(ev.world.getChunkFromBlockCoords(ev.blockX, ev.blockZ)), ev.blockX, ev.blockY, ev.blockZ), new CraftItemStack(ev.entityPlayer.inventory.getCurrentItem()), ((EntityPlayerMP) ev.entityPlayer).capabilities.isCreativeMode); bev.setCancelled(ev.isCanceled()); Bukkit.getPluginManager().callEvent(bev); if (bev.isCancelled()) { ev.setCanceled(true); return; } if (bev.getInstaBreak()) { Block blck = Block.blocksList[ev.blockID]; blck.dropBlockAsItem(ev.world, ev.blockX, ev.blockY, ev.blockZ, ev.world.getBlockMetadata(ev.blockX, ev.blockY, ev.blockZ), 0); ev.world.setBlockMetadataWithNotify(ev.blockX, ev.blockY, ev.blockZ, 0, 0); //Block.blocksList[ev.blockID].breakBlock(ev.world, ev.blockX, ev.blockY, ev.blockZ, ev.blockID, ev.world.getBlockMetadata(ev.blockX, ev.blockY, ev.blockZ)); return; } } @ForgeSubscribe(receiveCanceled = true) public void blockBreakSomehow(BlockDestroyEvent ev) { // This event is breaking something with an 'already decorating' error if (!ready || isClient) return; /*BlockBreakEvent bev = new BlockBreakEvent(new CraftBlock(new CraftChunk(ev.world.getChunkFromBlockCoords(ev.x, ev.y)), ev.x, ev.y, ev.z), BukkitForgePlayerCache.getCraftPlayer(BukkitContainer.MOD_PLAYER)); bev.setCancelled(ev.isCanceled()); Bukkit.getPluginManager().callEvent(bev); ev.setCanceled(bev.isCancelled()); */ } @ForgeSubscribe(receiveCanceled = true) public void onCreeperExplode(CreeperExplodeEvent ev) { if (!ready || isClient) return; int x = MathHelper.floor_double(ev.creeper.posX); int y = MathHelper.floor_double(ev.creeper.posY); int z = MathHelper.floor_double(ev.creeper.posZ); int minX = x - ev.explosionRadius; // Shouldnt you use Math.max and Math.min? int maxX = x + ev.explosionRadius; int minY = y - ev.explosionRadius; int maxY = y + ev.explosionRadius; int minZ = z - ev.explosionRadius; int maxZ = z + ev.explosionRadius; List<org.bukkit.block.Block> blocks = new ArrayList<org.bukkit.block.Block>(); for (x = minX; x <= maxX; x++) { for (z = minZ; z <= maxZ; z++) { CraftChunk chunk = new CraftChunk(ev.creeper.worldObj.getChunkFromBlockCoords(x, z)); for (y = minY; y <= maxY; y++) { CraftBlock b = new CraftBlock(chunk, x, y, z); blocks.add(b); } } } Location loc = new Location(CraftServer.instance().getWorld(ev.creeper.worldObj.provider.dimensionId), ev.creeper.posX, ev.creeper.posY, ev.creeper.posZ); EntityExplodeEvent bev = new EntityExplodeEvent(new CraftCreeper(CraftServer.instance(), ev.creeper), loc, blocks, 1.0f); bev.setCancelled(ev.isCanceled()); Bukkit.getPluginManager().callEvent(bev); ev.setCanceled(bev.isCancelled()); } @ForgeSubscribe(receiveCanceled = true) public void liquidFlow(LiquidFlowEvent ev) { if (!ready || isClient) return; CraftBlockFake newBlk = new CraftBlockFake(new CraftChunk(ev.world.getChunkFromBlockCoords(ev.flowToX, ev.flowToZ)), ev.flowToX, ev.flowToY, ev.flowToZ, ev.liquid.blockID + 1, 0); CraftBlock source = new CraftBlock(new CraftChunk(ev.world.getChunkFromBlockCoords(ev.flowFromX, ev.flowFromZ)), ev.flowFromX, ev.flowFromY, ev.flowFromZ); BlockSpreadEvent bev = new BlockSpreadEvent(newBlk, source, newBlk.getState()); bev.setCancelled(ev.isCanceled()); Bukkit.getPluginManager().callEvent(bev); ev.setCanceled(bev.isCancelled()); } @ForgeSubscribe(receiveCanceled = true) public void onSheepDye(SheepDyeEvent ev) { if (!ready || isClient) return; SheepDyeWoolEvent bev = new SheepDyeWoolEvent(new CraftSheep(CraftServer.instance(), ev.sheep), DyeColor.getByData((byte)ev.newColour)); bev.setCancelled(ev.isCanceled()); Bukkit.getPluginManager().callEvent(bev); ev.setCanceled(bev.isCancelled()); } @ForgeSubscribe(receiveCanceled = true) public void onPlayerMove(PlayerMoveEvent ev) { if (!ready || isClient) return; if (!(ev.entityPlayer instanceof EntityPlayerMP)) return; CraftPlayer player = BukkitForgePlayerCache.getCraftPlayer(CraftServer.instance(), (EntityPlayerMP) ev.entityPlayer); Location old = new Location(CraftServer.instance().getWorld(ev.entityPlayer.worldObj.provider.dimensionId), ev.oldX, ev.oldY, ev.oldZ); Location now = new Location(CraftServer.instance().getWorld(ev.entityPlayer.worldObj.provider.dimensionId), ev.newX, ev.newY, ev.newZ); org.bukkit.event.player.PlayerMoveEvent bev = new org.bukkit.event.player.PlayerMoveEvent(player, old, now); bev.setCancelled(ev.isCanceled()); Bukkit.getPluginManager().callEvent(bev); Location to = bev.getTo(); if( to != now && !bev.isCancelled() ) { player.teleport(to, PlayerTeleportEvent.TeleportCause.UNKNOWN); } ev.setCanceled(bev.isCancelled()); } @ForgeSubscribe(receiveCanceled = true) public void onPressurePlate(PressurePlateInteractEvent ev) { if (!ready || isClient) return; if (ev.entity instanceof EntityPlayerMP) { EntityPlayerMP fp = (EntityPlayerMP) ev.entity; CraftPlayer player = BukkitForgePlayerCache.getCraftPlayer(CraftServer.instance(), (EntityPlayerMP) ev.entity); CraftItemStack item = new CraftItemStack(fp.inventory.getCurrentItem()); org.bukkit.event.player.PlayerInteractEvent bev = new org.bukkit.event.player.PlayerInteractEvent(player, Action.PHYSICAL, item, new CraftBlock(new CraftChunk(ev.world.getChunkFromBlockCoords(ev.x, ev.z)), ev.x,ev.y,ev.z), CraftBlock.notchToBlockFace(-1)); bev.setCancelled(ev.isCanceled()); Bukkit.getPluginManager().callEvent(bev); ev.setCanceled(bev.isCancelled()); } } @ForgeSubscribe(receiveCanceled = true) public void onLightningStrike(LightningStrikeEvent ev) { if (!ready || isClient) return; if (ev.bolt != null) { org.bukkit.event.weather.LightningStrikeEvent bev1 = new org.bukkit.event.weather.LightningStrikeEvent(CraftServer.instance().getWorld(ev.world.provider.dimensionId), new CraftLightningStrike(CraftServer.instance(), ev.bolt)); bev1.setCancelled(ev.isCanceled()); Bukkit.getPluginManager().callEvent(bev1); if (bev1.isCancelled()) { cancelled.add(ev.bolt); ev.setCanceled(true); return; } } if (cancelled.contains(ev.bolt)) { // same as before ev.setCanceled(true); return; } BlockIgniteEvent bev = new BlockIgniteEvent(new CraftBlock(new CraftChunk(ev.world.getChunkFromBlockCoords(ev.x, ev.z)), ev.x, ev.y, ev.z), IgniteCause.LIGHTNING, null); bev.setCancelled(ev.isCanceled()); Bukkit.getPluginManager().callEvent(bev); ev.setCanceled(bev.isCancelled()); } @ForgeSubscribe(receiveCanceled = true) public void onSignChange(SignChangeEvent ev) { if (!ready || isClient) return; if (BukkitContainer.DEBUG) System.out.println(String.format("SignChange: player %s x %s y %s z %s text %s", new Object[] {ev.signChanger.username, ev.x, ev.y, ev.z, Joiner.on(", ").join(ev.lines) })); CraftBlock theBlock = new CraftBlock( new CraftChunk(ev.signChanger.worldObj.getChunkFromBlockCoords(ev.x, ev.z)), ev.x, ev.y, ev.z ); CraftPlayer thePlayer; if (ev.signChanger instanceof EntityPlayerMP) thePlayer = BukkitForgePlayerCache.getCraftPlayer((EntityPlayerMP) ev.signChanger); else thePlayer = BukkitForgePlayerCache.getCraftPlayer(BukkitContainer.MOD_PLAYER); org.bukkit.event.block.SignChangeEvent bev = new org.bukkit.event.block.SignChangeEvent(theBlock, thePlayer, ev.lines); bev.setCancelled(ev.isCanceled()); Bukkit.getPluginManager().callEvent(bev); ev.setCanceled(bev.isCancelled()); ev.lines = bev.getLines(); } @ForgeSubscribe(receiveCanceled = true) public void worldLoadEvent(WorldEvent.Load event) { if (!ready) { return; } World w = CraftServer.instance().getWorld(event.world.provider.dimensionId); WorldInitEvent init = new WorldInitEvent(w); Bukkit.getPluginManager().callEvent(init); /*WorldLoadEvent worldLoad = new WorldLoadEvent(w); Bukkit.getPluginManager().callEvent(worldLoad); */ } @ForgeSubscribe(receiveCanceled = true) public void worldSaveEvent(WorldEvent.Save event) { if (!ready) { return; } WorldSaveEvent save = new WorldSaveEvent(CraftServer.instance().getWorld(event.world.provider.dimensionId)); Bukkit.getPluginManager().callEvent(save); } @ForgeSubscribe(receiveCanceled = true) public void worldUnloadEvent(WorldEvent.Unload event) { if (!ready) { return; } WorldUnloadEvent unload = new WorldUnloadEvent(CraftServer.instance().getWorld(event.world.provider.dimensionId)); Bukkit.getPluginManager().callEvent(unload); } @ForgeSubscribe(receiveCanceled = true) public void populateChunks(PopulateChunkEvent.Post event) { //ChunkPopulateEvent e = new ChunkPopulateEvent(new CraftChunk(event.world.getChunkFromBlockCoords(event.chunkX, event.chunkZ))); // Chunk event eventually turns into exception due to bad bukkit chunk code // Bukkit.getPluginManager().callEvent(e); } }
true
true
public void onEntityJoinWorld(EntityJoinWorldEvent ev) { if (!ready || isClient) return; if (ev.entity instanceof EntityLiving && !(ev.entity instanceof EntityPlayer)) {// || ev.entity instanceof EntityPlayerMP) { ev.setCanceled(BukkitEventRouters.Entity.CreatureSpawn.callEvent(ev.isCanceled(), ToBukkitEvent.CreatureSpawn(ev)).isCancelled()); } } @ForgeSubscribe(receiveCanceled = true) public void onItemExpire(ItemExpireEvent ev) { if (!ready || isClient) return; BukkitEventRouters.Entity.ItemDespawn.callEvent(ev.isCanceled(), ToBukkitEvent.ItemDespawn(ev)); } @ForgeSubscribe(receiveCanceled = true) public void onItemTossEvent(ItemTossEvent ev) { if (!ready || isClient) return; BukkitEventRouters.Entity.ItemSpawn.callEvent(ev.isCanceled(), ToBukkitEvent.ItemSpawn(ev)); } @ForgeSubscribe(receiveCanceled = true) public void onLivingAttack(LivingAttackEvent ev) { if (!ready || isClient) return; EntityDamageEvent bev; if (ev.source.getSourceOfDamage() != null) { bev = new EntityDamageByEntityEvent( CraftEntity.getEntity(CraftServer.instance(), ev.source.getSourceOfDamage()), CraftEntity.getEntity(CraftServer.instance(), ev.entityLiving), getDamageCause(ev.source), ev.ammount); } else { bev = new EntityDamageEvent( CraftEntity.getEntity(CraftServer.instance(), ev.entityLiving), getDamageCause(ev.source), ev.ammount); } bev.setCancelled(ev.isCanceled()); Bukkit.getPluginManager().callEvent(bev); ev.setCanceled(bev.isCancelled()); } private DamageCause getDamageCause(DamageSource source) { return ToBukkit.damageCause(source); } @ForgeSubscribe(receiveCanceled = true) public void onLivingDeathEvent(LivingDeathEvent ev) { if (!ready || isClient) return; LivingEntity e; CraftEntity j = CraftEntity.getEntity(CraftServer.instance(), ev.entityLiving); if (!(j instanceof LivingEntity)) { e = new CraftLivingEntity(CraftServer.instance(), ev.entityLiving); } else { e = (LivingEntity) j; } List<org.bukkit.inventory.ItemStack> stacks = new ArrayList<org.bukkit.inventory.ItemStack>(); for (EntityItem i : ev.entityLiving.capturedDrops) { ItemStack vanilla = i.getEntityItem(); stacks.add(new CraftItemStack(vanilla)); } EntityDeathEvent bev = new EntityDeathEvent(e, stacks); bev.setDroppedExp(ev.entityLiving.experienceValue); Bukkit.getPluginManager().callEvent(bev); } /*@ForgeSubscribe(receiveCanceled = true) public void onLivingFall(LivingFallEvent ev) { CraftEventFactory.callE }*/ @ForgeSubscribe(receiveCanceled = true) public void onLivingDamage(LivingHurtEvent ev) { if (!ready || isClient) return; DamageCause dc = getDamageCause(ev.source); CraftEventFactory.callEntityDamageEvent(ev.source.getEntity(), ev.entity, dc, ev.ammount); } @ForgeSubscribe(receiveCanceled = true) public void onTarget(LivingSetAttackTargetEvent ev) { if (!ready || isClient) return; CraftEventFactory.callEntityTargetEvent(ev.entity, ev.target, TargetReason.CUSTOM); } /*@ForgeSubscribe(receiveCanceled = true) public void onCartCollide(MinecartCollisionEvent ev) { CraftEventFactory. }*/ /* @ForgeSubscribe(receiveCanceled = true) *//** * Only called when a player fires * Forge doesn't give us the EntityArrow. * @param ev *//* public void bowFire(ArrowLooseEvent ev) { if (!ready || isClient) return; CraftEventFactory.callEntityShootBowEvent(ev.entityPlayer, ev.bow, (EntityArrow)ev.entity, ev.charge); }*/ @ForgeSubscribe(receiveCanceled = true) public void playerVEntity(AttackEntityEvent ev) { if (!ready || isClient) return; CraftEventFactory.callEntityDamageEvent(ev.entityPlayer, ev.target, DamageCause.ENTITY_ATTACK, ev.entityPlayer.inventory.getDamageVsEntity(ev.target)); } /* @ForgeSubscribe(receiveCanceled = true) public void bonemeal(BonemealEvent ev) { }*/ @ForgeSubscribe(receiveCanceled = true) public void onPlayerInteraction(final PlayerInteractEvent ev) { if (!ready || isClient) return; if (ev.action == PlayerInteractEvent.Action.RIGHT_CLICK_BLOCK) { if (!ev.entityPlayer.isSneaking() && ev.entityPlayer.worldObj.blockHasTileEntity(ev.x, ev.y, ev.z)) { return; } if (ev.entityPlayer.inventory.getCurrentItem() == null) { return; } if (ev.entityPlayer.inventory.getCurrentItem().getItem() instanceof ItemBlock) { if (BukkitContainer.DEBUG) System.out.println("PLACE!"); final CraftItemStack itemInHand = new CraftItemStack(ev.entityPlayer.inventory.getCurrentItem()); final int blockX = ev.x + ForgeDirection.getOrientation(ev.face).offsetX; final int blockY = ev.y + ForgeDirection.getOrientation(ev.face).offsetY; final int blockZ = ev.z + ForgeDirection.getOrientation(ev.face).offsetZ; EntityPlayerMP forgePlayerMP; if (!(ev.entityPlayer instanceof EntityPlayerMP)) { forgePlayerMP = BukkitContainer.MOD_PLAYER; } else { forgePlayerMP = (EntityPlayerMP) ev.entityPlayer; } final CraftPlayer thePlayer = BukkitForgePlayerCache.getCraftPlayer(forgePlayerMP); final CraftBlock beforeBlock = new CraftBlock(new CraftChunk(ev.entity.worldObj.getChunkFromBlockCoords(ev.x, ev.y)), blockX, blockY, blockZ); WorldServer world = (WorldServer) ev.entity.worldObj; int minX = world.getSpawnPoint().posX; int minY = world.getSpawnPoint().posY; int minZ = world.getSpawnPoint().posZ; int sps = MinecraftServer.getServer().getSpawnProtectionSize(); int maxX = minX + sps; int maxY = minY + sps; int maxZ = minZ + sps; AxisAlignedBB aabb = AxisAlignedBB.getBoundingBox(minX, minY, minZ, maxX, maxY, maxZ); final boolean canBuild; if (aabb.isVecInside(Vec3.fakePool.getVecFromPool(blockX, blockY, blockZ))) { canBuild = false; } else { canBuild = true; } BlockCanBuildEvent can = new BlockCanBuildEvent(beforeBlock, beforeBlock.getTypeId(), canBuild); can.setBuildable(!ev.isCanceled()); Bukkit.getPluginManager().callEvent(can); final CraftBlock placedBlock = new CraftBlockFake(new CraftChunk(ev.entity.worldObj.getChunkFromBlockCoords(ev.x, ev.y)), blockX, blockY, blockZ, itemInHand.getTypeId(), itemInHand.getDurability()); BlockPlaceEvent bev = new BlockPlaceEvent(placedBlock, beforeBlock.getState(), placedBlock, itemInHand, thePlayer, can.isBuildable()); bev.setCancelled(ev.isCanceled()); Bukkit.getPluginManager().callEvent(bev); ev.setCanceled(bev.isCancelled() || !bev.canBuild()); } else if (ev.entityPlayer.inventory.getCurrentItem().getItem() instanceof ItemFlintAndSteel) { // ignite EntityPlayerMP fp; if (!(ev.entityPlayer instanceof EntityPlayerMP)) { fp = BukkitContainer.MOD_PLAYER; } else { fp = (EntityPlayerMP) ev.entityPlayer; } BlockIgniteEvent bev = new BlockIgniteEvent(new CraftBlock(new CraftChunk(ev.entity.worldObj.getChunkFromBlockCoords(ev.x, ev.y)), ev.x, ev.y, ev.z), IgniteCause.FLINT_AND_STEEL, BukkitForgePlayerCache.getCraftPlayer(fp)); bev.setCancelled(ev.isCanceled()); Bukkit.getPluginManager().callEvent(bev); ev.setCanceled(bev.isCancelled()); } } } @ForgeSubscribe(receiveCanceled = true) public void pickUp(EntityItemPickupEvent ev) { if (!ready || isClient) return; // assume all picked up at the same time EntityPlayerMP fp; if (!(ev.entityPlayer instanceof EntityPlayerMP)) { fp = BukkitContainer.MOD_PLAYER; } else { fp = (EntityPlayerMP) ev.entityPlayer; } PlayerPickupItemEvent bev = new PlayerPickupItemEvent(BukkitForgePlayerCache.getCraftPlayer(fp), new CraftItem(CraftServer.instance(), ev.item), 0); bev.setCancelled(ev.entityLiving.captureDrops); bev.setCancelled(ev.isCanceled()); Bukkit.getPluginManager().callEvent(bev); if (bev.isCancelled()) { ev.setCanceled(true); ev.setResult(Result.DENY); } } @ForgeSubscribe(receiveCanceled = true) public void fillCraft(FillBucketEvent ev) { if (!ready || isClient) return; EntityPlayerMP fp; if (!(ev.entityPlayer instanceof EntityPlayerMP)) { fp = BukkitContainer.MOD_PLAYER; } else { fp = (EntityPlayerMP) ev.entityPlayer; } CraftBlock blk = new CraftBlock(new CraftChunk(ev.entity.worldObj.getChunkFromBlockCoords(ev.target.blockX, ev.target.blockZ)), ev.target.blockX, ev.target.blockY, ev.target.blockZ); PlayerBucketFillEvent bev = new PlayerBucketFillEvent(BukkitForgePlayerCache.getCraftPlayer(fp), blk, CraftBlock.notchToBlockFace(ev.target.sideHit), Material.BUCKET, new CraftItemStack(ev.result)); bev.setCancelled(ev.isCanceled()); Bukkit.getPluginManager().callEvent(bev); if (bev.isCancelled()) { ev.setCanceled(true); ev.setResult(Result.DENY); } } @ForgeSubscribe(receiveCanceled = true) public void interactEvent(PlayerInteractEvent ev) { if (!ready || isClient) return; org.bukkit.event.player.PlayerInteractEvent bev = BukkitEventRouters.Player.PlayerInteract.callEvent(ev.isCanceled(), ToBukkitEvent.PlayerInteract(ev)); if (bev.isCancelled()) { ev.setCanceled(true); ev.setResult(Result.DENY); } } @ForgeSubscribe(receiveCanceled = true) public void playerGoToSleep(PlayerSleepInBedEvent ev) { if (!ready || isClient) return; org.bukkit.event.player.PlayerBedEnterEvent bev = new PlayerBedEnterEvent(BukkitForgePlayerCache.getCraftPlayer((EntityPlayerMP) ev.entityPlayer), new CraftBlock(new CraftChunk(ev.entityPlayer.worldObj.getChunkFromBlockCoords(ev.x, ev.z)), ev.x, ev.y, ev.z)); bev.setCancelled(ev.isCanceled()); Bukkit.getPluginManager().callEvent(bev); if (bev.isCancelled()) { ev.setCanceled(true); ev.result = EnumStatus.OTHER_PROBLEM; } } @ForgeSubscribe(receiveCanceled = true) public void chunkLoadEvent(ChunkEvent.Load ev) { if (!ready || isClient) return; BukkitEventRouters.World.ChunkLoad.callEvent( false, ToBukkitEvent.ChunkLoad(ev) ); } @ForgeSubscribe(receiveCanceled = true) public void chunkUnloadEvent(ChunkEvent.Unload ev) { if (!ready || isClient) return; BukkitEventRouters.World.ChunkUnload.callEvent(false, ToBukkitEvent.ChunkUnload(ev)); } @ForgeSubscribe(receiveCanceled = true) public void serverChat(ServerChatEvent ev) { if (!ready) return; String newName = ev.player.username; if (playerDisplayNames.containsKey(newName)) { newName = playerDisplayNames.get(newName); } CraftPlayer whom = BukkitForgePlayerCache.getCraftPlayer(ev.player); AsyncPlayerChatEvent ev1 = new AsyncPlayerChatEvent(false, whom, ev.message, Sets.newHashSet(CraftServer.instance().getOnlinePlayers())); PlayerChatEvent bev = new PlayerChatEvent(whom, ev.message); bev.setCancelled(ev.isCanceled()); ev1.setCancelled(ev.isCanceled()); ev1 = CraftEventFactory.callEvent(ev1); bev.setCancelled(ev1.isCancelled()); bev = CraftEventFactory.callEvent(bev); String newLine = String.format(ev1.getFormat(), new Object[] { newName, ev1.getMessage() }); ev.line = newLine; ev.setCanceled(ev1.isCancelled() || bev.isCancelled()); } @ForgeSubscribe(receiveCanceled = true) public void saplingGrow(SaplingGrowTreeEvent ev) { if (!ready || isClient) return; int blockID = ev.world.getBlockId(ev.x, ev.y, ev.z); //int blockMeta = ev.world.getBlockMetadata(ev.x, ev.y, ev.z); if (Block.blocksList[blockID] == Block.sapling) { TreeType type = TreeType.TREE; StructureGrowEvent bev = new StructureGrowEvent(new Location(CraftServer.instance().getWorld(ev.world.provider.dimensionId),ev.x,ev.y,ev.z), type, false, null, new ArrayList<BlockState>()); bev.setCancelled(ev.isCanceled()); Bukkit.getPluginManager().callEvent(bev); ev.setCanceled((bev.isCancelled())); } } @ForgeSubscribe(receiveCanceled = true) public void serverCmd(CommandEvent ev) { CommandSender s; /* * TODO: Impelement more of these * EntityClientPlayerMP, * EntityOtherPlayerMP, * EntityPlayer, * EntityPlayerMP, * IntegratedServer, * MinecraftServer, * RConConsoleSource, * TileEntityCommandBlock * */ ICommandSender sender = ev.sender; if (sender instanceof EntityPlayerMP) { s = BukkitForgePlayerCache.getCraftPlayer((EntityPlayerMP) ev.sender); } else { s = Bukkit.getConsoleSender(); } if (ev.isCanceled()) { return; } ServerCommandEvent bev = new ServerCommandEvent(s, (ev.command.getCommandName() + " " + Joiner.on(' ').join(ev.parameters)).trim()); Bukkit.getPluginManager().callEvent(bev); } // used PlayerInteractEvent for this @ForgeSubscribe(receiveCanceled = true) public void tryPlaceBlock(PlayerUseItemEvent ev) { if (ev.stack.getItem() instanceof ItemBlock) { ItemBlock block = (ItemBlock) ev.stack.getItem(); CraftChunk chunk = new CraftChunk(ev.world.getChunkFromBlockCoords(ev.x, ev.z)); ChunkCoordinates spawn = ev.world.getSpawnPoint(); int spawnRadius = CraftServer.instance().getSpawnRadius(); boolean canBuild = AxisAlignedBB.getAABBPool().getAABB(spawn.posX, spawn.posY, spawn.posZ, spawn.posX + spawnRadius, spawn.posY + spawnRadius, spawn.posZ + spawnRadius).isVecInside(Vec3.createVectorHelper(ev.x, ev.y, ev.z)); CraftBlock bblock = new CraftBlock(chunk, ev.x, ev.y, ev.z); BlockCanBuildEvent bukkitEv = new BlockCanBuildEvent(bblock, block.getBlockID(), canBuild); bukkitEv.setBuildable(ev.isCanceled()); if (!bukkitEv.isBuildable() && canBuild) { // it was changed // and since we were called from AFTER the actual placement, we can just break the block. bblock.breakNaturally(); } } } @ForgeSubscribe(receiveCanceled = true) public void dispenseItem(DispenseItemEvent ev) { if (!ready || isClient) return; ItemStack item = ev.stackToDispense.copy(); item.stackSize = 1; //IRegistry dispenserRegistry = BlockDispenser.dispenseBehaviorRegistry; //IBehaviorDispenseItem theBehaviour = (IBehaviorDispenseItem) dispenserRegistry.func_82594_a(item.getItem()); BlockDispenseEvent bev = new BlockDispenseEvent( new CraftBlock( new CraftChunk(ev.blockWorld.getChunkFromBlockCoords(ev.blockX, ev.blockZ)), ev.blockX, ev.blockY, ev.blockZ), new CraftItemStack(item), new Vector()); bev.setCancelled(ev.isCanceled()); Bukkit.getPluginManager().callEvent(bev); ev.setCanceled(bev.isCancelled()); } @ForgeSubscribe(receiveCanceled = true) public void playerDamageBlock(PlayerDamageBlockEvent ev) { if (!ready || isClient) return; BlockDamageEvent bev = new BlockDamageEvent(BukkitForgePlayerCache.getCraftPlayer((EntityPlayerMP) ev.entityPlayer), new CraftBlock(new CraftChunk(ev.world.getChunkFromBlockCoords(ev.blockX, ev.blockZ)), ev.blockX, ev.blockY, ev.blockZ), new CraftItemStack(ev.entityPlayer.inventory.getCurrentItem()), ((EntityPlayerMP) ev.entityPlayer).capabilities.isCreativeMode); bev.setCancelled(ev.isCanceled()); Bukkit.getPluginManager().callEvent(bev); if (bev.isCancelled()) { ev.setCanceled(true); return; } if (bev.getInstaBreak()) { Block blck = Block.blocksList[ev.blockID]; blck.dropBlockAsItem(ev.world, ev.blockX, ev.blockY, ev.blockZ, ev.world.getBlockMetadata(ev.blockX, ev.blockY, ev.blockZ), 0); ev.world.setBlockMetadataWithNotify(ev.blockX, ev.blockY, ev.blockZ, 0, 0); //Block.blocksList[ev.blockID].breakBlock(ev.world, ev.blockX, ev.blockY, ev.blockZ, ev.blockID, ev.world.getBlockMetadata(ev.blockX, ev.blockY, ev.blockZ)); return; } } @ForgeSubscribe(receiveCanceled = true) public void blockBreakSomehow(BlockDestroyEvent ev) { // This event is breaking something with an 'already decorating' error if (!ready || isClient) return; /*BlockBreakEvent bev = new BlockBreakEvent(new CraftBlock(new CraftChunk(ev.world.getChunkFromBlockCoords(ev.x, ev.y)), ev.x, ev.y, ev.z), BukkitForgePlayerCache.getCraftPlayer(BukkitContainer.MOD_PLAYER)); bev.setCancelled(ev.isCanceled()); Bukkit.getPluginManager().callEvent(bev); ev.setCanceled(bev.isCancelled()); */ } @ForgeSubscribe(receiveCanceled = true) public void onCreeperExplode(CreeperExplodeEvent ev) { if (!ready || isClient) return; int x = MathHelper.floor_double(ev.creeper.posX); int y = MathHelper.floor_double(ev.creeper.posY); int z = MathHelper.floor_double(ev.creeper.posZ); int minX = x - ev.explosionRadius; // Shouldnt you use Math.max and Math.min? int maxX = x + ev.explosionRadius; int minY = y - ev.explosionRadius; int maxY = y + ev.explosionRadius; int minZ = z - ev.explosionRadius; int maxZ = z + ev.explosionRadius; List<org.bukkit.block.Block> blocks = new ArrayList<org.bukkit.block.Block>(); for (x = minX; x <= maxX; x++) { for (z = minZ; z <= maxZ; z++) { CraftChunk chunk = new CraftChunk(ev.creeper.worldObj.getChunkFromBlockCoords(x, z)); for (y = minY; y <= maxY; y++) { CraftBlock b = new CraftBlock(chunk, x, y, z); blocks.add(b); } } } Location loc = new Location(CraftServer.instance().getWorld(ev.creeper.worldObj.provider.dimensionId), ev.creeper.posX, ev.creeper.posY, ev.creeper.posZ); EntityExplodeEvent bev = new EntityExplodeEvent(new CraftCreeper(CraftServer.instance(), ev.creeper), loc, blocks, 1.0f); bev.setCancelled(ev.isCanceled()); Bukkit.getPluginManager().callEvent(bev); ev.setCanceled(bev.isCancelled()); } @ForgeSubscribe(receiveCanceled = true) public void liquidFlow(LiquidFlowEvent ev) { if (!ready || isClient) return; CraftBlockFake newBlk = new CraftBlockFake(new CraftChunk(ev.world.getChunkFromBlockCoords(ev.flowToX, ev.flowToZ)), ev.flowToX, ev.flowToY, ev.flowToZ, ev.liquid.blockID + 1, 0); CraftBlock source = new CraftBlock(new CraftChunk(ev.world.getChunkFromBlockCoords(ev.flowFromX, ev.flowFromZ)), ev.flowFromX, ev.flowFromY, ev.flowFromZ); BlockSpreadEvent bev = new BlockSpreadEvent(newBlk, source, newBlk.getState()); bev.setCancelled(ev.isCanceled()); Bukkit.getPluginManager().callEvent(bev); ev.setCanceled(bev.isCancelled()); } @ForgeSubscribe(receiveCanceled = true) public void onSheepDye(SheepDyeEvent ev) { if (!ready || isClient) return; SheepDyeWoolEvent bev = new SheepDyeWoolEvent(new CraftSheep(CraftServer.instance(), ev.sheep), DyeColor.getByData((byte)ev.newColour)); bev.setCancelled(ev.isCanceled()); Bukkit.getPluginManager().callEvent(bev); ev.setCanceled(bev.isCancelled()); } @ForgeSubscribe(receiveCanceled = true) public void onPlayerMove(PlayerMoveEvent ev) { if (!ready || isClient) return; if (!(ev.entityPlayer instanceof EntityPlayerMP)) return; CraftPlayer player = BukkitForgePlayerCache.getCraftPlayer(CraftServer.instance(), (EntityPlayerMP) ev.entityPlayer); Location old = new Location(CraftServer.instance().getWorld(ev.entityPlayer.worldObj.provider.dimensionId), ev.oldX, ev.oldY, ev.oldZ); Location now = new Location(CraftServer.instance().getWorld(ev.entityPlayer.worldObj.provider.dimensionId), ev.newX, ev.newY, ev.newZ); org.bukkit.event.player.PlayerMoveEvent bev = new org.bukkit.event.player.PlayerMoveEvent(player, old, now); bev.setCancelled(ev.isCanceled()); Bukkit.getPluginManager().callEvent(bev); Location to = bev.getTo(); if( to != now && !bev.isCancelled() ) { player.teleport(to, PlayerTeleportEvent.TeleportCause.UNKNOWN); } ev.setCanceled(bev.isCancelled()); } @ForgeSubscribe(receiveCanceled = true) public void onPressurePlate(PressurePlateInteractEvent ev) { if (!ready || isClient) return; if (ev.entity instanceof EntityPlayerMP) { EntityPlayerMP fp = (EntityPlayerMP) ev.entity; CraftPlayer player = BukkitForgePlayerCache.getCraftPlayer(CraftServer.instance(), (EntityPlayerMP) ev.entity); CraftItemStack item = new CraftItemStack(fp.inventory.getCurrentItem()); org.bukkit.event.player.PlayerInteractEvent bev = new org.bukkit.event.player.PlayerInteractEvent(player, Action.PHYSICAL, item, new CraftBlock(new CraftChunk(ev.world.getChunkFromBlockCoords(ev.x, ev.z)), ev.x,ev.y,ev.z), CraftBlock.notchToBlockFace(-1)); bev.setCancelled(ev.isCanceled()); Bukkit.getPluginManager().callEvent(bev); ev.setCanceled(bev.isCancelled()); } } @ForgeSubscribe(receiveCanceled = true) public void onLightningStrike(LightningStrikeEvent ev) { if (!ready || isClient) return; if (ev.bolt != null) { org.bukkit.event.weather.LightningStrikeEvent bev1 = new org.bukkit.event.weather.LightningStrikeEvent(CraftServer.instance().getWorld(ev.world.provider.dimensionId), new CraftLightningStrike(CraftServer.instance(), ev.bolt)); bev1.setCancelled(ev.isCanceled()); Bukkit.getPluginManager().callEvent(bev1); if (bev1.isCancelled()) { cancelled.add(ev.bolt); ev.setCanceled(true); return; } } if (cancelled.contains(ev.bolt)) { // same as before ev.setCanceled(true); return; } BlockIgniteEvent bev = new BlockIgniteEvent(new CraftBlock(new CraftChunk(ev.world.getChunkFromBlockCoords(ev.x, ev.z)), ev.x, ev.y, ev.z), IgniteCause.LIGHTNING, null); bev.setCancelled(ev.isCanceled()); Bukkit.getPluginManager().callEvent(bev); ev.setCanceled(bev.isCancelled()); } @ForgeSubscribe(receiveCanceled = true) public void onSignChange(SignChangeEvent ev) { if (!ready || isClient) return; if (BukkitContainer.DEBUG) System.out.println(String.format("SignChange: player %s x %s y %s z %s text %s", new Object[] {ev.signChanger.username, ev.x, ev.y, ev.z, Joiner.on(", ").join(ev.lines) })); CraftBlock theBlock = new CraftBlock( new CraftChunk(ev.signChanger.worldObj.getChunkFromBlockCoords(ev.x, ev.z)), ev.x, ev.y, ev.z ); CraftPlayer thePlayer; if (ev.signChanger instanceof EntityPlayerMP) thePlayer = BukkitForgePlayerCache.getCraftPlayer((EntityPlayerMP) ev.signChanger); else thePlayer = BukkitForgePlayerCache.getCraftPlayer(BukkitContainer.MOD_PLAYER); org.bukkit.event.block.SignChangeEvent bev = new org.bukkit.event.block.SignChangeEvent(theBlock, thePlayer, ev.lines); bev.setCancelled(ev.isCanceled()); Bukkit.getPluginManager().callEvent(bev); ev.setCanceled(bev.isCancelled()); ev.lines = bev.getLines(); }
public void onEntityJoinWorld(EntityJoinWorldEvent ev) { if (!ready || isClient) return; if (ev.entity instanceof EntityLiving && !(ev.entity instanceof EntityPlayer)) {// || ev.entity instanceof EntityPlayerMP) { ev.setCanceled(BukkitEventRouters.Entity.CreatureSpawn.callEvent(ev.isCanceled(), ToBukkitEvent.CreatureSpawn(ev)).isCancelled()); } } @ForgeSubscribe(receiveCanceled = true) public void onItemExpire(ItemExpireEvent ev) { if (!ready || isClient) return; BukkitEventRouters.Entity.ItemDespawn.callEvent(ev.isCanceled(), ToBukkitEvent.ItemDespawn(ev)); } @ForgeSubscribe(receiveCanceled = true) public void onItemTossEvent(ItemTossEvent ev) { if (!ready || isClient) return; BukkitEventRouters.Entity.ItemSpawn.callEvent(ev.isCanceled(), ToBukkitEvent.ItemSpawn(ev)); } @ForgeSubscribe(receiveCanceled = true) public void onLivingAttack(LivingAttackEvent ev) { if (!ready || isClient) return; EntityDamageEvent bev; if (ev.source.getSourceOfDamage() != null) { bev = new EntityDamageByEntityEvent( CraftEntity.getEntity(CraftServer.instance(), ev.source.getSourceOfDamage()), CraftEntity.getEntity(CraftServer.instance(), ev.entityLiving), getDamageCause(ev.source), ev.ammount); } else { bev = new EntityDamageEvent( CraftEntity.getEntity(CraftServer.instance(), ev.entityLiving), getDamageCause(ev.source), ev.ammount); } bev.setCancelled(ev.isCanceled()); Bukkit.getPluginManager().callEvent(bev); ev.setCanceled(bev.isCancelled()); } private DamageCause getDamageCause(DamageSource source) { return ToBukkit.damageCause(source); } @ForgeSubscribe(receiveCanceled = true) public void onLivingDeathEvent(LivingDeathEvent ev) { if (!ready || isClient) return; LivingEntity e; CraftEntity j = CraftEntity.getEntity(CraftServer.instance(), ev.entityLiving); if (!(j instanceof LivingEntity)) { e = new CraftLivingEntity(CraftServer.instance(), ev.entityLiving); } else { e = (LivingEntity) j; } List<org.bukkit.inventory.ItemStack> stacks = new ArrayList<org.bukkit.inventory.ItemStack>(); for (EntityItem i : ev.entityLiving.capturedDrops) { ItemStack vanilla = i.getEntityItem(); stacks.add(new CraftItemStack(vanilla)); } EntityDeathEvent bev = new EntityDeathEvent(e, stacks); bev.setDroppedExp(ev.entityLiving.experienceValue); Bukkit.getPluginManager().callEvent(bev); } /*@ForgeSubscribe(receiveCanceled = true) public void onLivingFall(LivingFallEvent ev) { CraftEventFactory.callE }*/ @ForgeSubscribe(receiveCanceled = true) public void onLivingDamage(LivingHurtEvent ev) { if (!ready || isClient) return; DamageCause dc = getDamageCause(ev.source); CraftEventFactory.callEntityDamageEvent(ev.source.getEntity(), ev.entity, dc, ev.ammount); } @ForgeSubscribe(receiveCanceled = true) public void onTarget(LivingSetAttackTargetEvent ev) { if (!ready || isClient) return; CraftEventFactory.callEntityTargetEvent(ev.entity, ev.target, TargetReason.CUSTOM); } /*@ForgeSubscribe(receiveCanceled = true) public void onCartCollide(MinecartCollisionEvent ev) { CraftEventFactory. }*/ /* @ForgeSubscribe(receiveCanceled = true) *//** * Only called when a player fires * Forge doesn't give us the EntityArrow. * @param ev *//* public void bowFire(ArrowLooseEvent ev) { if (!ready || isClient) return; CraftEventFactory.callEntityShootBowEvent(ev.entityPlayer, ev.bow, (EntityArrow)ev.entity, ev.charge); }*/ @ForgeSubscribe(receiveCanceled = true) public void playerVEntity(AttackEntityEvent ev) { if (!ready || isClient) return; CraftEventFactory.callEntityDamageEvent(ev.entityPlayer, ev.target, DamageCause.ENTITY_ATTACK, ev.entityPlayer.inventory.getDamageVsEntity(ev.target)); } /* @ForgeSubscribe(receiveCanceled = true) public void bonemeal(BonemealEvent ev) { }*/ @ForgeSubscribe(receiveCanceled = true) public void onPlayerInteraction(final PlayerInteractEvent ev) { if (!ready || isClient) return; if (ev.action == PlayerInteractEvent.Action.RIGHT_CLICK_BLOCK) { if (!ev.entityPlayer.isSneaking() && ev.entityPlayer.worldObj.blockHasTileEntity(ev.x, ev.y, ev.z)) { return; } if (ev.entityPlayer.inventory.getCurrentItem() == null) { return; } if (ev.entityPlayer.inventory.getCurrentItem().getItem() instanceof ItemBlock) { if (BukkitContainer.DEBUG) System.out.println("PLACE!"); final CraftItemStack itemInHand = new CraftItemStack(ev.entityPlayer.inventory.getCurrentItem()); final int blockX = ev.x + ForgeDirection.getOrientation(ev.face).offsetX; final int blockY = ev.y + ForgeDirection.getOrientation(ev.face).offsetY; final int blockZ = ev.z + ForgeDirection.getOrientation(ev.face).offsetZ; EntityPlayerMP forgePlayerMP; if (!(ev.entityPlayer instanceof EntityPlayerMP)) { forgePlayerMP = BukkitContainer.MOD_PLAYER; } else { forgePlayerMP = (EntityPlayerMP) ev.entityPlayer; } final CraftPlayer thePlayer = BukkitForgePlayerCache.getCraftPlayer(forgePlayerMP); final CraftBlock beforeBlock = new CraftBlock(new CraftChunk(ev.entity.worldObj.getChunkFromBlockCoords(blockX, blockZ)), blockX, blockY, blockZ); WorldServer world = (WorldServer) ev.entity.worldObj; int minX = world.getSpawnPoint().posX; int minY = world.getSpawnPoint().posY; int minZ = world.getSpawnPoint().posZ; int sps = MinecraftServer.getServer().getSpawnProtectionSize(); int maxX = minX + sps; int maxY = minY + sps; int maxZ = minZ + sps; AxisAlignedBB aabb = AxisAlignedBB.getBoundingBox(minX, minY, minZ, maxX, maxY, maxZ); final boolean canBuild; if (aabb.isVecInside(Vec3.fakePool.getVecFromPool(blockX, blockY, blockZ))) { canBuild = false; } else { canBuild = true; } BlockCanBuildEvent can = new BlockCanBuildEvent(beforeBlock, beforeBlock.getTypeId(), canBuild); can.setBuildable(!ev.isCanceled()); Bukkit.getPluginManager().callEvent(can); final CraftBlock placedBlock = new CraftBlockFake(new CraftChunk(ev.entity.worldObj.getChunkFromBlockCoords(ev.x, ev.y)), blockX, blockY, blockZ, itemInHand.getTypeId(), itemInHand.getDurability()); BlockPlaceEvent bev = new BlockPlaceEvent(placedBlock, beforeBlock.getState(), placedBlock, itemInHand, thePlayer, can.isBuildable()); bev.setCancelled(ev.isCanceled()); Bukkit.getPluginManager().callEvent(bev); ev.setCanceled(bev.isCancelled() || !bev.canBuild()); } else if (ev.entityPlayer.inventory.getCurrentItem().getItem() instanceof ItemFlintAndSteel) { // ignite EntityPlayerMP fp; if (!(ev.entityPlayer instanceof EntityPlayerMP)) { fp = BukkitContainer.MOD_PLAYER; } else { fp = (EntityPlayerMP) ev.entityPlayer; } BlockIgniteEvent bev = new BlockIgniteEvent(new CraftBlock(new CraftChunk(ev.entity.worldObj.getChunkFromBlockCoords(ev.x, ev.y)), ev.x, ev.y, ev.z), IgniteCause.FLINT_AND_STEEL, BukkitForgePlayerCache.getCraftPlayer(fp)); bev.setCancelled(ev.isCanceled()); Bukkit.getPluginManager().callEvent(bev); ev.setCanceled(bev.isCancelled()); } } } @ForgeSubscribe(receiveCanceled = true) public void pickUp(EntityItemPickupEvent ev) { if (!ready || isClient) return; // assume all picked up at the same time EntityPlayerMP fp; if (!(ev.entityPlayer instanceof EntityPlayerMP)) { fp = BukkitContainer.MOD_PLAYER; } else { fp = (EntityPlayerMP) ev.entityPlayer; } PlayerPickupItemEvent bev = new PlayerPickupItemEvent(BukkitForgePlayerCache.getCraftPlayer(fp), new CraftItem(CraftServer.instance(), ev.item), 0); bev.setCancelled(ev.entityLiving.captureDrops); bev.setCancelled(ev.isCanceled()); Bukkit.getPluginManager().callEvent(bev); if (bev.isCancelled()) { ev.setCanceled(true); ev.setResult(Result.DENY); } } @ForgeSubscribe(receiveCanceled = true) public void fillCraft(FillBucketEvent ev) { if (!ready || isClient) return; EntityPlayerMP fp; if (!(ev.entityPlayer instanceof EntityPlayerMP)) { fp = BukkitContainer.MOD_PLAYER; } else { fp = (EntityPlayerMP) ev.entityPlayer; } CraftBlock blk = new CraftBlock(new CraftChunk(ev.entity.worldObj.getChunkFromBlockCoords(ev.target.blockX, ev.target.blockZ)), ev.target.blockX, ev.target.blockY, ev.target.blockZ); PlayerBucketFillEvent bev = new PlayerBucketFillEvent(BukkitForgePlayerCache.getCraftPlayer(fp), blk, CraftBlock.notchToBlockFace(ev.target.sideHit), Material.BUCKET, new CraftItemStack(ev.result)); bev.setCancelled(ev.isCanceled()); Bukkit.getPluginManager().callEvent(bev); if (bev.isCancelled()) { ev.setCanceled(true); ev.setResult(Result.DENY); } } @ForgeSubscribe(receiveCanceled = true) public void interactEvent(PlayerInteractEvent ev) { if (!ready || isClient) return; org.bukkit.event.player.PlayerInteractEvent bev = BukkitEventRouters.Player.PlayerInteract.callEvent(ev.isCanceled(), ToBukkitEvent.PlayerInteract(ev)); if (bev.isCancelled()) { ev.setCanceled(true); ev.setResult(Result.DENY); } } @ForgeSubscribe(receiveCanceled = true) public void playerGoToSleep(PlayerSleepInBedEvent ev) { if (!ready || isClient) return; org.bukkit.event.player.PlayerBedEnterEvent bev = new PlayerBedEnterEvent(BukkitForgePlayerCache.getCraftPlayer((EntityPlayerMP) ev.entityPlayer), new CraftBlock(new CraftChunk(ev.entityPlayer.worldObj.getChunkFromBlockCoords(ev.x, ev.z)), ev.x, ev.y, ev.z)); bev.setCancelled(ev.isCanceled()); Bukkit.getPluginManager().callEvent(bev); if (bev.isCancelled()) { ev.setCanceled(true); ev.result = EnumStatus.OTHER_PROBLEM; } } @ForgeSubscribe(receiveCanceled = true) public void chunkLoadEvent(ChunkEvent.Load ev) { if (!ready || isClient) return; BukkitEventRouters.World.ChunkLoad.callEvent( false, ToBukkitEvent.ChunkLoad(ev) ); } @ForgeSubscribe(receiveCanceled = true) public void chunkUnloadEvent(ChunkEvent.Unload ev) { if (!ready || isClient) return; BukkitEventRouters.World.ChunkUnload.callEvent(false, ToBukkitEvent.ChunkUnload(ev)); } @ForgeSubscribe(receiveCanceled = true) public void serverChat(ServerChatEvent ev) { if (!ready) return; String newName = ev.player.username; if (playerDisplayNames.containsKey(newName)) { newName = playerDisplayNames.get(newName); } CraftPlayer whom = BukkitForgePlayerCache.getCraftPlayer(ev.player); AsyncPlayerChatEvent ev1 = new AsyncPlayerChatEvent(false, whom, ev.message, Sets.newHashSet(CraftServer.instance().getOnlinePlayers())); PlayerChatEvent bev = new PlayerChatEvent(whom, ev.message); bev.setCancelled(ev.isCanceled()); ev1.setCancelled(ev.isCanceled()); ev1 = CraftEventFactory.callEvent(ev1); bev.setCancelled(ev1.isCancelled()); bev = CraftEventFactory.callEvent(bev); String newLine = String.format(ev1.getFormat(), new Object[] { newName, ev1.getMessage() }); ev.line = newLine; ev.setCanceled(ev1.isCancelled() || bev.isCancelled()); } @ForgeSubscribe(receiveCanceled = true) public void saplingGrow(SaplingGrowTreeEvent ev) { if (!ready || isClient) return; int blockID = ev.world.getBlockId(ev.x, ev.y, ev.z); //int blockMeta = ev.world.getBlockMetadata(ev.x, ev.y, ev.z); if (Block.blocksList[blockID] == Block.sapling) { TreeType type = TreeType.TREE; StructureGrowEvent bev = new StructureGrowEvent(new Location(CraftServer.instance().getWorld(ev.world.provider.dimensionId),ev.x,ev.y,ev.z), type, false, null, new ArrayList<BlockState>()); bev.setCancelled(ev.isCanceled()); Bukkit.getPluginManager().callEvent(bev); ev.setCanceled((bev.isCancelled())); } } @ForgeSubscribe(receiveCanceled = true) public void serverCmd(CommandEvent ev) { CommandSender s; /* * TODO: Impelement more of these * EntityClientPlayerMP, * EntityOtherPlayerMP, * EntityPlayer, * EntityPlayerMP, * IntegratedServer, * MinecraftServer, * RConConsoleSource, * TileEntityCommandBlock * */ ICommandSender sender = ev.sender; if (sender instanceof EntityPlayerMP) { s = BukkitForgePlayerCache.getCraftPlayer((EntityPlayerMP) ev.sender); } else { s = Bukkit.getConsoleSender(); } if (ev.isCanceled()) { return; } ServerCommandEvent bev = new ServerCommandEvent(s, (ev.command.getCommandName() + " " + Joiner.on(' ').join(ev.parameters)).trim()); Bukkit.getPluginManager().callEvent(bev); } // used PlayerInteractEvent for this @ForgeSubscribe(receiveCanceled = true) public void tryPlaceBlock(PlayerUseItemEvent ev) { if (ev.stack.getItem() instanceof ItemBlock) { ItemBlock block = (ItemBlock) ev.stack.getItem(); CraftChunk chunk = new CraftChunk(ev.world.getChunkFromBlockCoords(ev.x, ev.z)); ChunkCoordinates spawn = ev.world.getSpawnPoint(); int spawnRadius = CraftServer.instance().getSpawnRadius(); boolean canBuild = AxisAlignedBB.getAABBPool().getAABB(spawn.posX, spawn.posY, spawn.posZ, spawn.posX + spawnRadius, spawn.posY + spawnRadius, spawn.posZ + spawnRadius).isVecInside(Vec3.createVectorHelper(ev.x, ev.y, ev.z)); CraftBlock bblock = new CraftBlock(chunk, ev.x, ev.y, ev.z); BlockCanBuildEvent bukkitEv = new BlockCanBuildEvent(bblock, block.getBlockID(), canBuild); bukkitEv.setBuildable(ev.isCanceled()); if (!bukkitEv.isBuildable() && canBuild) { // it was changed // and since we were called from AFTER the actual placement, we can just break the block. bblock.breakNaturally(); } } } @ForgeSubscribe(receiveCanceled = true) public void dispenseItem(DispenseItemEvent ev) { if (!ready || isClient) return; ItemStack item = ev.stackToDispense.copy(); item.stackSize = 1; //IRegistry dispenserRegistry = BlockDispenser.dispenseBehaviorRegistry; //IBehaviorDispenseItem theBehaviour = (IBehaviorDispenseItem) dispenserRegistry.func_82594_a(item.getItem()); BlockDispenseEvent bev = new BlockDispenseEvent( new CraftBlock( new CraftChunk(ev.blockWorld.getChunkFromBlockCoords(ev.blockX, ev.blockZ)), ev.blockX, ev.blockY, ev.blockZ), new CraftItemStack(item), new Vector()); bev.setCancelled(ev.isCanceled()); Bukkit.getPluginManager().callEvent(bev); ev.setCanceled(bev.isCancelled()); } @ForgeSubscribe(receiveCanceled = true) public void playerDamageBlock(PlayerDamageBlockEvent ev) { if (!ready || isClient) return; BlockDamageEvent bev = new BlockDamageEvent(BukkitForgePlayerCache.getCraftPlayer((EntityPlayerMP) ev.entityPlayer), new CraftBlock(new CraftChunk(ev.world.getChunkFromBlockCoords(ev.blockX, ev.blockZ)), ev.blockX, ev.blockY, ev.blockZ), new CraftItemStack(ev.entityPlayer.inventory.getCurrentItem()), ((EntityPlayerMP) ev.entityPlayer).capabilities.isCreativeMode); bev.setCancelled(ev.isCanceled()); Bukkit.getPluginManager().callEvent(bev); if (bev.isCancelled()) { ev.setCanceled(true); return; } if (bev.getInstaBreak()) { Block blck = Block.blocksList[ev.blockID]; blck.dropBlockAsItem(ev.world, ev.blockX, ev.blockY, ev.blockZ, ev.world.getBlockMetadata(ev.blockX, ev.blockY, ev.blockZ), 0); ev.world.setBlockMetadataWithNotify(ev.blockX, ev.blockY, ev.blockZ, 0, 0); //Block.blocksList[ev.blockID].breakBlock(ev.world, ev.blockX, ev.blockY, ev.blockZ, ev.blockID, ev.world.getBlockMetadata(ev.blockX, ev.blockY, ev.blockZ)); return; } } @ForgeSubscribe(receiveCanceled = true) public void blockBreakSomehow(BlockDestroyEvent ev) { // This event is breaking something with an 'already decorating' error if (!ready || isClient) return; /*BlockBreakEvent bev = new BlockBreakEvent(new CraftBlock(new CraftChunk(ev.world.getChunkFromBlockCoords(ev.x, ev.y)), ev.x, ev.y, ev.z), BukkitForgePlayerCache.getCraftPlayer(BukkitContainer.MOD_PLAYER)); bev.setCancelled(ev.isCanceled()); Bukkit.getPluginManager().callEvent(bev); ev.setCanceled(bev.isCancelled()); */ } @ForgeSubscribe(receiveCanceled = true) public void onCreeperExplode(CreeperExplodeEvent ev) { if (!ready || isClient) return; int x = MathHelper.floor_double(ev.creeper.posX); int y = MathHelper.floor_double(ev.creeper.posY); int z = MathHelper.floor_double(ev.creeper.posZ); int minX = x - ev.explosionRadius; // Shouldnt you use Math.max and Math.min? int maxX = x + ev.explosionRadius; int minY = y - ev.explosionRadius; int maxY = y + ev.explosionRadius; int minZ = z - ev.explosionRadius; int maxZ = z + ev.explosionRadius; List<org.bukkit.block.Block> blocks = new ArrayList<org.bukkit.block.Block>(); for (x = minX; x <= maxX; x++) { for (z = minZ; z <= maxZ; z++) { CraftChunk chunk = new CraftChunk(ev.creeper.worldObj.getChunkFromBlockCoords(x, z)); for (y = minY; y <= maxY; y++) { CraftBlock b = new CraftBlock(chunk, x, y, z); blocks.add(b); } } } Location loc = new Location(CraftServer.instance().getWorld(ev.creeper.worldObj.provider.dimensionId), ev.creeper.posX, ev.creeper.posY, ev.creeper.posZ); EntityExplodeEvent bev = new EntityExplodeEvent(new CraftCreeper(CraftServer.instance(), ev.creeper), loc, blocks, 1.0f); bev.setCancelled(ev.isCanceled()); Bukkit.getPluginManager().callEvent(bev); ev.setCanceled(bev.isCancelled()); } @ForgeSubscribe(receiveCanceled = true) public void liquidFlow(LiquidFlowEvent ev) { if (!ready || isClient) return; CraftBlockFake newBlk = new CraftBlockFake(new CraftChunk(ev.world.getChunkFromBlockCoords(ev.flowToX, ev.flowToZ)), ev.flowToX, ev.flowToY, ev.flowToZ, ev.liquid.blockID + 1, 0); CraftBlock source = new CraftBlock(new CraftChunk(ev.world.getChunkFromBlockCoords(ev.flowFromX, ev.flowFromZ)), ev.flowFromX, ev.flowFromY, ev.flowFromZ); BlockSpreadEvent bev = new BlockSpreadEvent(newBlk, source, newBlk.getState()); bev.setCancelled(ev.isCanceled()); Bukkit.getPluginManager().callEvent(bev); ev.setCanceled(bev.isCancelled()); } @ForgeSubscribe(receiveCanceled = true) public void onSheepDye(SheepDyeEvent ev) { if (!ready || isClient) return; SheepDyeWoolEvent bev = new SheepDyeWoolEvent(new CraftSheep(CraftServer.instance(), ev.sheep), DyeColor.getByData((byte)ev.newColour)); bev.setCancelled(ev.isCanceled()); Bukkit.getPluginManager().callEvent(bev); ev.setCanceled(bev.isCancelled()); } @ForgeSubscribe(receiveCanceled = true) public void onPlayerMove(PlayerMoveEvent ev) { if (!ready || isClient) return; if (!(ev.entityPlayer instanceof EntityPlayerMP)) return; CraftPlayer player = BukkitForgePlayerCache.getCraftPlayer(CraftServer.instance(), (EntityPlayerMP) ev.entityPlayer); Location old = new Location(CraftServer.instance().getWorld(ev.entityPlayer.worldObj.provider.dimensionId), ev.oldX, ev.oldY, ev.oldZ); Location now = new Location(CraftServer.instance().getWorld(ev.entityPlayer.worldObj.provider.dimensionId), ev.newX, ev.newY, ev.newZ); org.bukkit.event.player.PlayerMoveEvent bev = new org.bukkit.event.player.PlayerMoveEvent(player, old, now); bev.setCancelled(ev.isCanceled()); Bukkit.getPluginManager().callEvent(bev); Location to = bev.getTo(); if( to != now && !bev.isCancelled() ) { player.teleport(to, PlayerTeleportEvent.TeleportCause.UNKNOWN); } ev.setCanceled(bev.isCancelled()); } @ForgeSubscribe(receiveCanceled = true) public void onPressurePlate(PressurePlateInteractEvent ev) { if (!ready || isClient) return; if (ev.entity instanceof EntityPlayerMP) { EntityPlayerMP fp = (EntityPlayerMP) ev.entity; CraftPlayer player = BukkitForgePlayerCache.getCraftPlayer(CraftServer.instance(), (EntityPlayerMP) ev.entity); CraftItemStack item = new CraftItemStack(fp.inventory.getCurrentItem()); org.bukkit.event.player.PlayerInteractEvent bev = new org.bukkit.event.player.PlayerInteractEvent(player, Action.PHYSICAL, item, new CraftBlock(new CraftChunk(ev.world.getChunkFromBlockCoords(ev.x, ev.z)), ev.x,ev.y,ev.z), CraftBlock.notchToBlockFace(-1)); bev.setCancelled(ev.isCanceled()); Bukkit.getPluginManager().callEvent(bev); ev.setCanceled(bev.isCancelled()); } } @ForgeSubscribe(receiveCanceled = true) public void onLightningStrike(LightningStrikeEvent ev) { if (!ready || isClient) return; if (ev.bolt != null) { org.bukkit.event.weather.LightningStrikeEvent bev1 = new org.bukkit.event.weather.LightningStrikeEvent(CraftServer.instance().getWorld(ev.world.provider.dimensionId), new CraftLightningStrike(CraftServer.instance(), ev.bolt)); bev1.setCancelled(ev.isCanceled()); Bukkit.getPluginManager().callEvent(bev1); if (bev1.isCancelled()) { cancelled.add(ev.bolt); ev.setCanceled(true); return; } } if (cancelled.contains(ev.bolt)) { // same as before ev.setCanceled(true); return; } BlockIgniteEvent bev = new BlockIgniteEvent(new CraftBlock(new CraftChunk(ev.world.getChunkFromBlockCoords(ev.x, ev.z)), ev.x, ev.y, ev.z), IgniteCause.LIGHTNING, null); bev.setCancelled(ev.isCanceled()); Bukkit.getPluginManager().callEvent(bev); ev.setCanceled(bev.isCancelled()); } @ForgeSubscribe(receiveCanceled = true) public void onSignChange(SignChangeEvent ev) { if (!ready || isClient) return; if (BukkitContainer.DEBUG) System.out.println(String.format("SignChange: player %s x %s y %s z %s text %s", new Object[] {ev.signChanger.username, ev.x, ev.y, ev.z, Joiner.on(", ").join(ev.lines) })); CraftBlock theBlock = new CraftBlock( new CraftChunk(ev.signChanger.worldObj.getChunkFromBlockCoords(ev.x, ev.z)), ev.x, ev.y, ev.z ); CraftPlayer thePlayer; if (ev.signChanger instanceof EntityPlayerMP) thePlayer = BukkitForgePlayerCache.getCraftPlayer((EntityPlayerMP) ev.signChanger); else thePlayer = BukkitForgePlayerCache.getCraftPlayer(BukkitContainer.MOD_PLAYER); org.bukkit.event.block.SignChangeEvent bev = new org.bukkit.event.block.SignChangeEvent(theBlock, thePlayer, ev.lines); bev.setCancelled(ev.isCanceled()); Bukkit.getPluginManager().callEvent(bev); ev.setCanceled(bev.isCancelled()); ev.lines = bev.getLines(); }
diff --git a/SeriesGuide/src/com/battlelancer/seriesguide/appwidget/ListWidgetProvider.java b/SeriesGuide/src/com/battlelancer/seriesguide/appwidget/ListWidgetProvider.java index 7e9d48780..36e4a3b2b 100644 --- a/SeriesGuide/src/com/battlelancer/seriesguide/appwidget/ListWidgetProvider.java +++ b/SeriesGuide/src/com/battlelancer/seriesguide/appwidget/ListWidgetProvider.java @@ -1,150 +1,150 @@ /* * Copyright 2012 Uwe Trottmann * * 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.battlelancer.seriesguide.appwidget; import com.battlelancer.seriesguide.R; import com.battlelancer.seriesguide.enums.WidgetListType; import com.battlelancer.seriesguide.ui.EpisodeDetailsActivity; import com.battlelancer.seriesguide.ui.UpcomingRecentActivity; import com.uwetrottmann.androidutils.AndroidUtils; import android.annotation.TargetApi; import android.app.AlarmManager; import android.app.PendingIntent; import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetProvider; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.Build; import android.os.SystemClock; import android.text.format.DateUtils; import android.widget.RemoteViews; @TargetApi(11) public class ListWidgetProvider extends AppWidgetProvider { public static final String UPDATE = "com.battlelancer.seriesguide.appwidget.UPDATE"; public static final long REPETITION_INTERVAL = 5 * DateUtils.MINUTE_IN_MILLIS; @Override public void onDisabled(Context context) { super.onDisabled(context); // remove the update alarm if the last widget is gone Intent update = new Intent(UPDATE); PendingIntent pi = PendingIntent.getBroadcast(context, 195, update, 0); AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); am.cancel(pi); } @Override public void onReceive(Context context, Intent intent) { super.onReceive(context, intent); if (UPDATE.equals(intent.getAction())) { AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context); int[] appWidgetIds = appWidgetManager.getAppWidgetIds(new ComponentName(context, ListWidgetProvider.class)); appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetIds, R.id.list_view); // Toast.makeText(context, // "ListWidgets called to refresh " + Arrays.toString(appWidgetIds), // Toast.LENGTH_SHORT).show(); } } @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { // update each of the widgets with the remote adapter for (int i = 0; i < appWidgetIds.length; ++i) { // Toast.makeText(context, "Refreshing widget " + appWidgetIds[i], // Toast.LENGTH_SHORT) // .show(); RemoteViews rv = buildRemoteViews(context, appWidgetIds[i]); appWidgetManager.updateAppWidget(appWidgetIds[i], rv); } super.onUpdate(context, appWidgetManager, appWidgetIds); // set an alarm to update widgets every x mins if the device is awake Intent update = new Intent(UPDATE); PendingIntent pi = PendingIntent.getBroadcast(context, 195, update, 0); AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); am.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + REPETITION_INTERVAL, REPETITION_INTERVAL, pi); } @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) @SuppressWarnings("deprecation") public static RemoteViews buildRemoteViews(Context context, int appWidgetId) { // Here we setup the intent which points to the StackViewService // which will provide the views for this collection. Intent intent = new Intent(context, ListWidgetService.class); intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId); // When intents are compared, the extras are ignored, so we need to // embed the extras into the data so that the extras will not be // ignored. intent.setData(Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME))); RemoteViews rv = new RemoteViews(context.getPackageName(), R.layout.appwidget_v11); if (AndroidUtils.isICSOrHigher()) { rv.setRemoteAdapter(R.id.list_view, intent); } else { rv.setRemoteAdapter(appWidgetId, R.id.list_view, intent); } // The empty view is displayed when the collection has no items. It // should be a sibling of the collection view. rv.setEmptyView(R.id.list_view, R.id.empty_view); // change title based on config SharedPreferences prefs = context.getSharedPreferences(ListWidgetConfigure.PREFS_NAME, 0); int typeIndex = prefs.getInt(ListWidgetConfigure.PREF_LISTTYPE_KEY + appWidgetId, WidgetListType.UPCOMING.index); int activityTab = 0; if (typeIndex == WidgetListType.RECENT.index) { - activityTab = 0; + activityTab = 1; rv.setTextViewText(R.id.widgetTitle, context.getString(R.string.recent)); } else { - activityTab = 1; + activityTab = 0; rv.setTextViewText(R.id.widgetTitle, context.getString(R.string.upcoming)); } // Create an Intent to launch Upcoming Intent pi = new Intent(context, UpcomingRecentActivity.class); pi.putExtra(UpcomingRecentActivity.InitBundle.SELECTED_TAB, activityTab); pi.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); PendingIntent pendingIntent = PendingIntent.getActivity(context, appWidgetId, pi, PendingIntent.FLAG_UPDATE_CURRENT); rv.setOnClickPendingIntent(R.id.widget_title, pendingIntent); // Create intents for items to launch an EpisodeDetailsActivity Intent itemIntent = new Intent(context, EpisodeDetailsActivity.class); PendingIntent pendingIntentTemplate = PendingIntent.getActivity(context, 1, itemIntent, PendingIntent.FLAG_UPDATE_CURRENT); rv.setPendingIntentTemplate(R.id.list_view, pendingIntentTemplate); return rv; } }
false
true
public static RemoteViews buildRemoteViews(Context context, int appWidgetId) { // Here we setup the intent which points to the StackViewService // which will provide the views for this collection. Intent intent = new Intent(context, ListWidgetService.class); intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId); // When intents are compared, the extras are ignored, so we need to // embed the extras into the data so that the extras will not be // ignored. intent.setData(Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME))); RemoteViews rv = new RemoteViews(context.getPackageName(), R.layout.appwidget_v11); if (AndroidUtils.isICSOrHigher()) { rv.setRemoteAdapter(R.id.list_view, intent); } else { rv.setRemoteAdapter(appWidgetId, R.id.list_view, intent); } // The empty view is displayed when the collection has no items. It // should be a sibling of the collection view. rv.setEmptyView(R.id.list_view, R.id.empty_view); // change title based on config SharedPreferences prefs = context.getSharedPreferences(ListWidgetConfigure.PREFS_NAME, 0); int typeIndex = prefs.getInt(ListWidgetConfigure.PREF_LISTTYPE_KEY + appWidgetId, WidgetListType.UPCOMING.index); int activityTab = 0; if (typeIndex == WidgetListType.RECENT.index) { activityTab = 0; rv.setTextViewText(R.id.widgetTitle, context.getString(R.string.recent)); } else { activityTab = 1; rv.setTextViewText(R.id.widgetTitle, context.getString(R.string.upcoming)); } // Create an Intent to launch Upcoming Intent pi = new Intent(context, UpcomingRecentActivity.class); pi.putExtra(UpcomingRecentActivity.InitBundle.SELECTED_TAB, activityTab); pi.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); PendingIntent pendingIntent = PendingIntent.getActivity(context, appWidgetId, pi, PendingIntent.FLAG_UPDATE_CURRENT); rv.setOnClickPendingIntent(R.id.widget_title, pendingIntent); // Create intents for items to launch an EpisodeDetailsActivity Intent itemIntent = new Intent(context, EpisodeDetailsActivity.class); PendingIntent pendingIntentTemplate = PendingIntent.getActivity(context, 1, itemIntent, PendingIntent.FLAG_UPDATE_CURRENT); rv.setPendingIntentTemplate(R.id.list_view, pendingIntentTemplate); return rv; }
public static RemoteViews buildRemoteViews(Context context, int appWidgetId) { // Here we setup the intent which points to the StackViewService // which will provide the views for this collection. Intent intent = new Intent(context, ListWidgetService.class); intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId); // When intents are compared, the extras are ignored, so we need to // embed the extras into the data so that the extras will not be // ignored. intent.setData(Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME))); RemoteViews rv = new RemoteViews(context.getPackageName(), R.layout.appwidget_v11); if (AndroidUtils.isICSOrHigher()) { rv.setRemoteAdapter(R.id.list_view, intent); } else { rv.setRemoteAdapter(appWidgetId, R.id.list_view, intent); } // The empty view is displayed when the collection has no items. It // should be a sibling of the collection view. rv.setEmptyView(R.id.list_view, R.id.empty_view); // change title based on config SharedPreferences prefs = context.getSharedPreferences(ListWidgetConfigure.PREFS_NAME, 0); int typeIndex = prefs.getInt(ListWidgetConfigure.PREF_LISTTYPE_KEY + appWidgetId, WidgetListType.UPCOMING.index); int activityTab = 0; if (typeIndex == WidgetListType.RECENT.index) { activityTab = 1; rv.setTextViewText(R.id.widgetTitle, context.getString(R.string.recent)); } else { activityTab = 0; rv.setTextViewText(R.id.widgetTitle, context.getString(R.string.upcoming)); } // Create an Intent to launch Upcoming Intent pi = new Intent(context, UpcomingRecentActivity.class); pi.putExtra(UpcomingRecentActivity.InitBundle.SELECTED_TAB, activityTab); pi.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); PendingIntent pendingIntent = PendingIntent.getActivity(context, appWidgetId, pi, PendingIntent.FLAG_UPDATE_CURRENT); rv.setOnClickPendingIntent(R.id.widget_title, pendingIntent); // Create intents for items to launch an EpisodeDetailsActivity Intent itemIntent = new Intent(context, EpisodeDetailsActivity.class); PendingIntent pendingIntentTemplate = PendingIntent.getActivity(context, 1, itemIntent, PendingIntent.FLAG_UPDATE_CURRENT); rv.setPendingIntentTemplate(R.id.list_view, pendingIntentTemplate); return rv; }
diff --git a/src/robot/subsystems/HopperSubsystem.java b/src/robot/subsystems/HopperSubsystem.java index fcdd6f7..21ad6e1 100644 --- a/src/robot/subsystems/HopperSubsystem.java +++ b/src/robot/subsystems/HopperSubsystem.java @@ -1,78 +1,79 @@ package robot.subsystems; import edu.wpi.first.wpilibj.DoubleSolenoid; import edu.wpi.first.wpilibj.Solenoid; import edu.wpi.first.wpilibj.Timer; import edu.wpi.first.wpilibj.command.Subsystem; import robot.Constants; import robot.ParsableDouble; import robot.Pneumatic; import robot.commands.HopperCommand; public class HopperSubsystem extends Subsystem { Pneumatic stackDropper = new Pneumatic(new DoubleSolenoid(Constants.SOLENOID_STACK_DROPPER_ONE, Constants.SOLENOID_STACK_DROPPER_TWO)); Pneumatic stackHolder = new Pneumatic(new Solenoid(Constants.SOLENOID_STACK_HOLDER)); Pneumatic shooterLoader = new Pneumatic(new DoubleSolenoid(Constants.SOLENOID_SHOOTER_LOADER_ONE, Constants.SOLENOID_SHOOTER_LOADER_TWO)); public static ParsableDouble RELEASE_DELAY = new ParsableDouble("release_delay", 1); public static ParsableDouble STACK_HOLD_DELAY = new ParsableDouble("stack_hold_delay", 0.5); public static ParsableDouble STACK_RELEASE_DELAY = new ParsableDouble("stack_release_delay", 0.5); public static ParsableDouble FINISH_DELAY = new ParsableDouble("finish_delay", 0.5); boolean requestRelease = false; double lastReleaseTime = 0.0; double stackHoldTime = 0.0; double stackReleaseTime = 0.0; double finishTime = 0.0; public void initDefaultCommand() { setDefaultCommand(new HopperCommand()); } public void reset() { stackDropper.set(true); stackHolder.set(false); shooterLoader.set(false); } - public void update(boolean requestRelease) { + public void update(boolean requestShot) { double now = Timer.getFPGATimestamp(); - if(now - lastReleaseTime > RELEASE_DELAY.get()) { - this.requestRelease = !this.requestRelease ? true : this.requestRelease; + if(requestShot && now - lastReleaseTime > RELEASE_DELAY.get()) { + requestRelease = !requestRelease ? true : requestRelease; } if(requestRelease) { //Record the time we start holding the stack stackHoldTime = !stackHolder.get() ? now : stackHoldTime; //Hold the stack stackHolder.set(true); //If we've waited long enough after we start holding the stack if(now - stackHoldTime > STACK_HOLD_DELAY.get()) { //Drop the stack and record the time stackReleaseTime = now; stackDropper.set(false); } if(now - stackReleaseTime > STACK_RELEASE_DELAY.get()) { //When we've left enough time for the stack to drop, reset the dropper and load the shooter finishTime = now; - stackDropper.set(false); + stackDropper.set(true); shooterLoader.set(true); } if(now - finishTime > FINISH_DELAY.get()) { lastReleaseTime = now; //If we've waited long enough for the dropper and shooterLoader to do their stuff, then finish the release sequence requestRelease = false; + reset(); } } else { //Reset all pneumatics reset(); } } }
false
true
public void update(boolean requestRelease) { double now = Timer.getFPGATimestamp(); if(now - lastReleaseTime > RELEASE_DELAY.get()) { this.requestRelease = !this.requestRelease ? true : this.requestRelease; } if(requestRelease) { //Record the time we start holding the stack stackHoldTime = !stackHolder.get() ? now : stackHoldTime; //Hold the stack stackHolder.set(true); //If we've waited long enough after we start holding the stack if(now - stackHoldTime > STACK_HOLD_DELAY.get()) { //Drop the stack and record the time stackReleaseTime = now; stackDropper.set(false); } if(now - stackReleaseTime > STACK_RELEASE_DELAY.get()) { //When we've left enough time for the stack to drop, reset the dropper and load the shooter finishTime = now; stackDropper.set(false); shooterLoader.set(true); } if(now - finishTime > FINISH_DELAY.get()) { lastReleaseTime = now; //If we've waited long enough for the dropper and shooterLoader to do their stuff, then finish the release sequence requestRelease = false; } } else { //Reset all pneumatics reset(); } }
public void update(boolean requestShot) { double now = Timer.getFPGATimestamp(); if(requestShot && now - lastReleaseTime > RELEASE_DELAY.get()) { requestRelease = !requestRelease ? true : requestRelease; } if(requestRelease) { //Record the time we start holding the stack stackHoldTime = !stackHolder.get() ? now : stackHoldTime; //Hold the stack stackHolder.set(true); //If we've waited long enough after we start holding the stack if(now - stackHoldTime > STACK_HOLD_DELAY.get()) { //Drop the stack and record the time stackReleaseTime = now; stackDropper.set(false); } if(now - stackReleaseTime > STACK_RELEASE_DELAY.get()) { //When we've left enough time for the stack to drop, reset the dropper and load the shooter finishTime = now; stackDropper.set(true); shooterLoader.set(true); } if(now - finishTime > FINISH_DELAY.get()) { lastReleaseTime = now; //If we've waited long enough for the dropper and shooterLoader to do their stuff, then finish the release sequence requestRelease = false; reset(); } } else { //Reset all pneumatics reset(); } }
diff --git a/src/net/java/sip/communicator/impl/media/codec/audio/alaw/DePacketizer.java b/src/net/java/sip/communicator/impl/media/codec/audio/alaw/DePacketizer.java index ca867e0fa..f4ba9f094 100644 --- a/src/net/java/sip/communicator/impl/media/codec/audio/alaw/DePacketizer.java +++ b/src/net/java/sip/communicator/impl/media/codec/audio/alaw/DePacketizer.java @@ -1,113 +1,113 @@ /* * SIP Communicator, the OpenSource Java VoIP and Instant Messaging client. * * Distributable under LGPL license. * See terms of license at gnu.org. */ package net.java.sip.communicator.impl.media.codec.audio.alaw; import javax.media.*; import javax.media.format.*; import com.sun.media.codec.audio.*; import net.java.sip.communicator.impl.media.codec.*; /** * DePacketizer for ALAW codec * @author Damian Minkov */ public class DePacketizer extends AudioCodec { /** * Creates DePacketizer */ public DePacketizer() { inputFormats = new Format[]{new AudioFormat(Constants.ALAW_RTP)}; } /** * Returns the name of the DePacketizer * @return String */ public String getName() { return "ALAW DePacketizer"; } /** * Returns the supported output formats * @param in Format * @return Format[] */ public Format[] getSupportedOutputFormats(Format in) { if (in == null) { - return new Format[]{new AudioFormat(AudioFormat.ALAW)}; + return new Format[]{new AudioFormat("ALAW")}; } if (matches(in, inputFormats) == null) { return new Format[1]; } if (! (in instanceof AudioFormat)) { - return new Format[]{new AudioFormat(AudioFormat.ALAW)}; + return new Format[]{new AudioFormat("ALAW")}; } AudioFormat af = (AudioFormat) in; return new Format[] { new AudioFormat( - AudioFormat.ALAW, + "ALAW", af.getSampleRate(), af.getSampleSizeInBits(), af.getChannels()) }; } /** * Initializes the codec. */ public void open() {} /** * Clean up */ public void close() {} /** * decode the buffer * @param inputBuffer Buffer * @param outputBuffer Buffer * @return int */ public int process(Buffer inputBuffer, Buffer outputBuffer) { if (!checkInputBuffer(inputBuffer)) { return BUFFER_PROCESSED_FAILED; } if (isEOM(inputBuffer)) { propagateEOM(outputBuffer); return BUFFER_PROCESSED_OK; } Object outData = outputBuffer.getData(); outputBuffer.setData(inputBuffer.getData()); inputBuffer.setData(outData); outputBuffer.setLength(inputBuffer.getLength()); outputBuffer.setFormat(outputFormat); outputBuffer.setOffset(inputBuffer.getOffset()); return BUFFER_PROCESSED_OK; } }
false
true
public Format[] getSupportedOutputFormats(Format in) { if (in == null) { return new Format[]{new AudioFormat(AudioFormat.ALAW)}; } if (matches(in, inputFormats) == null) { return new Format[1]; } if (! (in instanceof AudioFormat)) { return new Format[]{new AudioFormat(AudioFormat.ALAW)}; } AudioFormat af = (AudioFormat) in; return new Format[] { new AudioFormat( AudioFormat.ALAW, af.getSampleRate(), af.getSampleSizeInBits(), af.getChannels()) }; }
public Format[] getSupportedOutputFormats(Format in) { if (in == null) { return new Format[]{new AudioFormat("ALAW")}; } if (matches(in, inputFormats) == null) { return new Format[1]; } if (! (in instanceof AudioFormat)) { return new Format[]{new AudioFormat("ALAW")}; } AudioFormat af = (AudioFormat) in; return new Format[] { new AudioFormat( "ALAW", af.getSampleRate(), af.getSampleSizeInBits(), af.getChannels()) }; }
diff --git a/ChromiumPostProcessor.java b/ChromiumPostProcessor.java index b0030e7..77a0903 100644 --- a/ChromiumPostProcessor.java +++ b/ChromiumPostProcessor.java @@ -1,79 +1,79 @@ import java.io.*; public class ChromiumPostProcessor { //These variables are user-editable static File chromium_log=new File("/home/devasia/Desktop/chromium.txt"); static File output_file=new File("/home/devasia/Desktop/chromium_report.txt"); static int stallThreshold=60; // in milliseconds static int linkSpeed=10000; //in kbps static BufferedWriter wt; static double sum=0; public static void main(String args[]) { try{ BufferedReader rd =new BufferedReader(new FileReader(chromium_log)); wt=new BufferedWriter(new FileWriter(output_file)); String line=null, log=""; while((line=rd.readLine())!=null){ if(line.startsWith("#")){ log=log+line+"\n"; } } String arr[]=log.split("\n"); for(int i=0;i<arr.length-2;i++){ if(arr[i].contains("Loading")){ double time=processLine(arr[i], arr[i+1]); log("Load Time: "+time+"ms"); } else{ double time=processLine(arr[i], arr[i+1]); sum=sum+time; if(time>stallThreshold){ log("Detected Stall of "+time+"ms between Frame "+i+" and Frame "+(i+1)); } else if(time<20){ log("Error: Detect quicken of "+time+" between Frame "+i+" and Frame "+(i+1)); } } - double avg=sum/arr.length; - log("Average Frame Delay: "+avg); } + double avg=sum/arr.length; + log("Average Frame Delay: "+avg); wt.close(); } catch (Exception e){ e.printStackTrace(); } } public static void log(String message) throws Exception{ System.out.println(message); wt.write(message+"\n"); wt.flush(); } //Wondershaper doesn't work! We need to use something else to throttle bandwidth public static void setLinkSpeed(int speed) throws Exception{ Runtime.getRuntime().exec("sudo wondershaper eth0 "+speed+" 10000"); } public static int processLine(String line1, String line2){ line1=line1.replaceAll("#FrameReady at ", ""); line1=line1.replace("#Loading at ", ""); line2=line2.replaceAll("#FrameReady at ", ""); line2=line2.replace("#Loading at ", ""); double d1=Double.parseDouble(line1); double d2=Double.parseDouble(line2); double time=d2-d1; int ret=(int) time; return ret; } }
false
true
public static void main(String args[]) { try{ BufferedReader rd =new BufferedReader(new FileReader(chromium_log)); wt=new BufferedWriter(new FileWriter(output_file)); String line=null, log=""; while((line=rd.readLine())!=null){ if(line.startsWith("#")){ log=log+line+"\n"; } } String arr[]=log.split("\n"); for(int i=0;i<arr.length-2;i++){ if(arr[i].contains("Loading")){ double time=processLine(arr[i], arr[i+1]); log("Load Time: "+time+"ms"); } else{ double time=processLine(arr[i], arr[i+1]); sum=sum+time; if(time>stallThreshold){ log("Detected Stall of "+time+"ms between Frame "+i+" and Frame "+(i+1)); } else if(time<20){ log("Error: Detect quicken of "+time+" between Frame "+i+" and Frame "+(i+1)); } } double avg=sum/arr.length; log("Average Frame Delay: "+avg); } wt.close(); } catch (Exception e){ e.printStackTrace(); } }
public static void main(String args[]) { try{ BufferedReader rd =new BufferedReader(new FileReader(chromium_log)); wt=new BufferedWriter(new FileWriter(output_file)); String line=null, log=""; while((line=rd.readLine())!=null){ if(line.startsWith("#")){ log=log+line+"\n"; } } String arr[]=log.split("\n"); for(int i=0;i<arr.length-2;i++){ if(arr[i].contains("Loading")){ double time=processLine(arr[i], arr[i+1]); log("Load Time: "+time+"ms"); } else{ double time=processLine(arr[i], arr[i+1]); sum=sum+time; if(time>stallThreshold){ log("Detected Stall of "+time+"ms between Frame "+i+" and Frame "+(i+1)); } else if(time<20){ log("Error: Detect quicken of "+time+" between Frame "+i+" and Frame "+(i+1)); } } } double avg=sum/arr.length; log("Average Frame Delay: "+avg); wt.close(); } catch (Exception e){ e.printStackTrace(); } }
diff --git a/src/main/java/me/tehbeard/BeardAch/BeardAch.java b/src/main/java/me/tehbeard/BeardAch/BeardAch.java index 0a60898..74f41de 100644 --- a/src/main/java/me/tehbeard/BeardAch/BeardAch.java +++ b/src/main/java/me/tehbeard/BeardAch/BeardAch.java @@ -1,492 +1,495 @@ package me.tehbeard.BeardAch; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Scanner; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import me.tehbeard.BeardAch.Metrics.Graph; import me.tehbeard.BeardAch.Metrics.Plotter; import me.tehbeard.BeardAch.achievement.*; import me.tehbeard.BeardAch.achievement.rewards.IReward; import me.tehbeard.BeardAch.achievement.triggers.*; import me.tehbeard.BeardAch.achievement.rewards.*; import me.tehbeard.BeardAch.commands.*; import me.tehbeard.BeardAch.dataSource.*; import me.tehbeard.BeardAch.dataSource.configurable.Configurable; import me.tehbeard.BeardAch.dataSource.configurable.IConfigurable; import me.tehbeard.BeardAch.dataSource.json.editor.EditorJSON; import me.tehbeard.BeardStat.BeardStat; import me.tehbeard.BeardStat.containers.PlayerStatManager; import me.tehbeard.utils.addons.AddonLoader; import me.tehbeard.utils.factory.ConfigurableFactory; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.command.*; import org.bukkit.plugin.java.JavaPlugin; import com.sk89q.worldguard.bukkit.WorldGuardPlugin; import de.hydrox.bukkit.DroxPerms.DroxPerms; import de.hydrox.bukkit.DroxPerms.DroxPermsAPI; public class BeardAch extends JavaPlugin { public static BeardAch self; private PlayerStatManager stats = null; private AddonLoader<IConfigurable> addonLoader; private Metrics metrics; public static int triggersMetric = 0; public static int rewardsMetric = 0; public static DroxPermsAPI droxAPI = null; private WorldGuardPlugin worldGuard; private AchievementManager achievementManager; private EditorJSON json = new EditorJSON(); /** * Load BeardAch */ @SuppressWarnings("unchecked") public void onEnable() { self = this; achievementManager = new AchievementManager(); //Load config printCon("Starting BeardAch"); /*if(!getConfig().getKeys(false).contains("achievements")){ }*/ getConfig().options().copyDefaults(true); saveConfig(); reloadConfig(); EnableBeardStat(); //check DroxPerms DroxPerms droxPerms = ((DroxPerms) this.getServer().getPluginManager().getPlugin("DroxPerms")); if (droxPerms != null) { droxAPI = droxPerms.getAPI(); } //check WorldGuard worldGuard = (WorldGuardPlugin) Bukkit.getPluginManager().getPlugin("WorldGuard"); printCon("Loading Data Adapters"); ConfigurableFactory<IDataSource,DataSourceDescriptor> dataSourceFactory = new ConfigurableFactory<IDataSource, DataSourceDescriptor>(DataSourceDescriptor.class) { @Override public String getTag(DataSourceDescriptor annotation) { return annotation.tag(); } }; dataSourceFactory.addProduct(YamlDataSource.class); dataSourceFactory.addProduct(SqlDataSource.class); dataSourceFactory.addProduct(NullDataSource.class); achievementManager.database = dataSourceFactory.getProduct(getConfig().getString("ach.database.type","")); if(achievementManager.database == null){ printError("NO SUITABLE DATABASE SELECTED!!"); printError("DISABLING PLUGIN!!"); //onDisable(); setEnabled(false); return; } printCon("Installing default triggers"); //Load installed triggers addTrigger(AchCheckTrigger.class); addTrigger(AchCountTrigger.class); addTrigger(CuboidCheckTrigger.class); addTrigger(LockedTrigger.class); addTrigger(NoAchCheckTrigger.class); addTrigger(PermCheckTrigger.class); addTrigger(StatCheckTrigger.class); addTrigger(StatWithinTrigger.class); addTrigger(EconomyTrigger.class); addTrigger(SpeedRunTrigger.class); addTrigger(CuboidKingOfTheHillTrigger.class); addTrigger(WorldGuardRegionTrigger.class); addTrigger(InteractTrigger.class); printCon("Installing default rewards"); //load installed rewards addReward(CommandReward.class); addReward(CounterReward.class); addReward(DroxSubGroupReward.class); addReward(DroxTrackReward.class); addReward(EconomyReward.class); addReward(SetGroupReward.class); addReward(TeleportReward.class); addReward(PotionReward.class); addReward(PlayerCommandReward.class); //Load built in extras InputStream bundle = getResource("bundle.properties"); if(bundle!=null){ try{ printCon("Loading bundled addons"); Scanner scanner; scanner = new Scanner(bundle); while(scanner.hasNext()){ String ln = scanner.nextLine(); String[] l = ln.split("="); if(l[0].equalsIgnoreCase("name")){ BeardAch.printCon("Loading bundled addon " + l[1]); }else if(l[0].equalsIgnoreCase("class")){ Class<?> c = getClassLoader().loadClass(l[1]); if(c!=null){ if(ITrigger.class.isAssignableFrom(c)){ triggersMetric ++; addTrigger((Class<? extends ITrigger>) c); }else if(IReward.class.isAssignableFrom(c)){ rewardsMetric ++; addReward((Class<? extends IReward>) c); } } } } scanner.close(); } catch (ClassNotFoundException e) { printCon("[PANIC] Could not load a class listed in the bundle file"); } } printCon("Preparing to load addons"); //Create addon dir if it doesn't exist File addonDir = (new File(getDataFolder(),"addons")); if(!addonDir.exists()){ addonDir.mkdir(); } //create the addon loader addonLoader = new BeardAchAddonLoader(addonDir); printCon("Loading addons"); addonLoader.loadAddons(); printCon("Writing editor settings"); new File(getDataFolder(),"editor").mkdirs(); try { json.write(new File(getDataFolder(),"editor/settings.js")); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } exportEditor(); printCon("Loading Achievements"); achievementManager.loadAchievements(); //metrics code if(!getConfig().getBoolean("general.plugin-stats-opt-out",false)){ try { metrics = new Metrics(this); //set up custom plotters for custom triggers and rewards SimplePlotter ct = new SimplePlotter("Custom Triggers"); SimplePlotter cr = new SimplePlotter("Custom Rewards"); ct.set(triggersMetric); cr.set(rewardsMetric); if(getStats()!=null){ metrics.addCustomData(new Plotter("BeardStat installed") { @Override public int getValue() { return 1; } }); } metrics.addCustomData(ct); metrics.addCustomData(cr); //total achievements on server SimplePlotter totalAchievments = new SimplePlotter("Total Achievements"); totalAchievments.set(achievementManager.getAchievementsList().size()); //Triggers per achievement Graph triggersGraph = metrics.createGraph("triggers"); for(final String trig : AchievementLoader.triggerFactory.getTags()){ SimplePlotter p = new SimplePlotter(trig + " Trigger"); for(Achievement a : achievementManager.getAchievementsList()){ for(ITrigger t : a.getTrigs()){ Configurable c = t.getClass().getAnnotation(Configurable.class); if(c!=null){ if(trig.equals(c.tag())){ p.increment(); } } } } triggersGraph.addPlotter(p); } //Rewards per achievement Graph rewardsGraph = metrics.createGraph("rewards"); for(final String reward : AchievementLoader.rewardFactory.getTags()){ SimplePlotter p = new SimplePlotter(reward + " Reward"); for(Achievement a : achievementManager.getAchievementsList()){ for(IReward r : a.getRewards()){ Configurable c = r.getClass().getAnnotation(Configurable.class); if(c!=null){ if(reward.equals(c.tag())){ p.increment(); } } } } rewardsGraph.addPlotter(p); } DataSourceDescriptor c = achievementManager.database.getClass().getAnnotation(DataSourceDescriptor.class); Graph g = metrics.createGraph("storage system"); g.addPlotter(new Plotter(c.tag() + " storage"){ @Override public int getValue() { return 1; }} ); metrics.start(); } catch (Exception e) { printCon("Could not load metrics :("); printCon("Please send the following stack trace to Tehbeard"); printCon("======================="); e.printStackTrace(); printCon("======================="); } } printCon("Starting achievement checker"); getServer().getScheduler().scheduleSyncRepeatingTask(this, new Runnable(){ public void run() { achievementManager.checkPlayers(); } }, 200L,200L); //setup events getServer().getPluginManager().registerEvents(achievementManager,this); printCon("Loading commands"); //commands getCommand("ach-reload").setExecutor(new AchReloadCommand()); getCommand("ach").setExecutor(new AchCommand()); getCommand("ach-fancy").setExecutor(new AchFancyCommand()); printCon("Loaded Version:" + getDescription().getVersion()); } /** * Unload BeardAch */ public void onDisable() { achievementManager.database.flush(); } /** * Handle unfinished commands */ @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { sender.sendMessage("COMMAND NOT IMPLEMENTED"); return true; } /** * Add a trigger * @param trigger */ public void addTrigger(Class<? extends ITrigger > trigger){ AchievementLoader.triggerFactory.addProduct(trigger); json.addTrigger(trigger); } /** * Add a reward * @param reward */ public void addReward(Class<? extends IReward > reward){ AchievementLoader.rewardFactory.addProduct(reward); json.addReward(reward); } /** * Colorises strings containing &0-f * @param msg * @return */ public static String colorise(String msg){ for(int i = 0;i<=9;i++){ msg = msg.replaceAll("&" + i, ChatColor.getByChar(""+i).toString()); } for(char i = 'a';i<='f';i++){ msg = msg.replaceAll("&" + i, ChatColor.getByChar(i).toString()); } return msg; } /** * Print error message * @param errMsg */ public static void printError(String errMsg){ self.getLogger().severe("[ERROR] " + errMsg); } /** * Print error message with an exception * @param errMsg * @param e */ public static void printError(String errMsg,Exception e){ self.getLogger().severe("[ERROR] " + errMsg); self.getLogger().severe("[ERROR] ==Stack trace dump=="); e.printStackTrace(); self.getLogger().severe("[ERROR] ==Stack trace dump=="); } /** * return the achievement manager * @return */ public AchievementManager getAchievementManager(){ return achievementManager; } /** * Try to load BeardStat */ private void EnableBeardStat(){ BeardStat bs = (BeardStat) Bukkit.getServer().getPluginManager().getPlugin("BeardStat"); if(bs!=null && bs.isEnabled()){ stats = bs.getStatManager(); } else { printError("BeardStat not installed! stat and statwithin triggers will not function!"); } } /** * Return WorldGuard instance * @return */ public WorldGuardPlugin getWorldGuard() { return worldGuard; } /** * Returns BeardStat instance * @return */ public PlayerStatManager getStats(){ return stats; } /** * Print console message * @param line */ public static void printCon(String line){ self.getLogger().info(line); } /** * Print message for debug * @param line */ public static void printDebugCon(String line){ if(self.getConfig().getBoolean("general.debug")){ printCon("[DEBUG] " + line); } } public static final int BUFFER_SIZE = 8192; private void exportEditor(){ try { ZipInputStream zis = new ZipInputStream(getResource("editor.zip")); ZipEntry entry = null; File outputDir = new File(getDataFolder(),"editor"); while((entry = zis.getNextEntry()) != null) { File outputFile = new File(outputDir,entry.getName()); - outputFile.mkdirs(); + if(entry.isDirectory()){ + outputFile.mkdirs(); + continue; + } int count; byte data[] = new byte[BUFFER_SIZE]; //write the file to the disk FileOutputStream fos = new FileOutputStream(outputFile); BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER_SIZE); while((count = zis.read(data, 0, BUFFER_SIZE)) != -1) { dest.write(data, 0, count); } //close the output streams dest.flush(); dest.close(); } } catch (IOException e) { e.printStackTrace(); } } }
false
true
private void exportEditor(){ try { ZipInputStream zis = new ZipInputStream(getResource("editor.zip")); ZipEntry entry = null; File outputDir = new File(getDataFolder(),"editor"); while((entry = zis.getNextEntry()) != null) { File outputFile = new File(outputDir,entry.getName()); outputFile.mkdirs(); int count; byte data[] = new byte[BUFFER_SIZE]; //write the file to the disk FileOutputStream fos = new FileOutputStream(outputFile); BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER_SIZE); while((count = zis.read(data, 0, BUFFER_SIZE)) != -1) { dest.write(data, 0, count); } //close the output streams dest.flush(); dest.close(); } } catch (IOException e) { e.printStackTrace(); } }
private void exportEditor(){ try { ZipInputStream zis = new ZipInputStream(getResource("editor.zip")); ZipEntry entry = null; File outputDir = new File(getDataFolder(),"editor"); while((entry = zis.getNextEntry()) != null) { File outputFile = new File(outputDir,entry.getName()); if(entry.isDirectory()){ outputFile.mkdirs(); continue; } int count; byte data[] = new byte[BUFFER_SIZE]; //write the file to the disk FileOutputStream fos = new FileOutputStream(outputFile); BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER_SIZE); while((count = zis.read(data, 0, BUFFER_SIZE)) != -1) { dest.write(data, 0, count); } //close the output streams dest.flush(); dest.close(); } } catch (IOException e) { e.printStackTrace(); } }
diff --git a/core/src/main/java/therian/operator/convert/DefaultToIteratorConverter.java b/core/src/main/java/therian/operator/convert/DefaultToIteratorConverter.java index 7055bbf..76140fb 100644 --- a/core/src/main/java/therian/operator/convert/DefaultToIteratorConverter.java +++ b/core/src/main/java/therian/operator/convert/DefaultToIteratorConverter.java @@ -1,68 +1,68 @@ /* * Copyright 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 therian.operator.convert; import java.lang.reflect.Type; import java.util.Iterator; import org.apache.commons.lang3.reflect.TypeUtils; import therian.TherianContext; import therian.buildweaver.StandardOperator; import therian.operation.Convert; import therian.operation.GetElementType; /** * Attempts to convert to {@link Iterable} and call {@link Iterable#iterator()}. */ @SuppressWarnings("rawtypes") @StandardOperator public class DefaultToIteratorConverter extends Converter<Object, Iterator> { @Override public boolean perform(TherianContext context, Convert<? extends Object, ? super Iterator> convert) { final Iterable sourceIterable = context.eval(Convert.to(Iterable.class, convert.getSourcePosition())); convert.getTargetPosition().setValue(sourceIterable.iterator()); return true; } @Override public boolean supports(TherianContext context, Convert<?, ? super Iterator> convert) { if (!super.supports(context, convert) || convert.getSourcePosition().getValue() instanceof Iterator<?>) { return false; } final Convert<?, Iterable> toIterable = Convert.to(Iterable.class, convert.getSourcePosition()); - if (context.supports(toIterable)) { + if (!context.supports(toIterable)) { return false; } final GetElementType<?> getTargetElementType = GetElementType.of(convert.getTargetPosition()); if (!context.supports(getTargetElementType)) { return false; } final Type targetElementType = context.eval(getTargetElementType); final GetElementType<?> getSourceElementType = GetElementType.of(convert.getSourcePosition()); final Type sourceElementType; if (context.supports(getSourceElementType)) { sourceElementType = context.eval(getSourceElementType); } else { sourceElementType = convert.getSourcePosition().getType(); } return TypeUtils.isAssignable(sourceElementType, targetElementType); } }
true
true
public boolean supports(TherianContext context, Convert<?, ? super Iterator> convert) { if (!super.supports(context, convert) || convert.getSourcePosition().getValue() instanceof Iterator<?>) { return false; } final Convert<?, Iterable> toIterable = Convert.to(Iterable.class, convert.getSourcePosition()); if (context.supports(toIterable)) { return false; } final GetElementType<?> getTargetElementType = GetElementType.of(convert.getTargetPosition()); if (!context.supports(getTargetElementType)) { return false; } final Type targetElementType = context.eval(getTargetElementType); final GetElementType<?> getSourceElementType = GetElementType.of(convert.getSourcePosition()); final Type sourceElementType; if (context.supports(getSourceElementType)) { sourceElementType = context.eval(getSourceElementType); } else { sourceElementType = convert.getSourcePosition().getType(); } return TypeUtils.isAssignable(sourceElementType, targetElementType); }
public boolean supports(TherianContext context, Convert<?, ? super Iterator> convert) { if (!super.supports(context, convert) || convert.getSourcePosition().getValue() instanceof Iterator<?>) { return false; } final Convert<?, Iterable> toIterable = Convert.to(Iterable.class, convert.getSourcePosition()); if (!context.supports(toIterable)) { return false; } final GetElementType<?> getTargetElementType = GetElementType.of(convert.getTargetPosition()); if (!context.supports(getTargetElementType)) { return false; } final Type targetElementType = context.eval(getTargetElementType); final GetElementType<?> getSourceElementType = GetElementType.of(convert.getSourcePosition()); final Type sourceElementType; if (context.supports(getSourceElementType)) { sourceElementType = context.eval(getSourceElementType); } else { sourceElementType = convert.getSourcePosition().getType(); } return TypeUtils.isAssignable(sourceElementType, targetElementType); }
diff --git a/anif/tools/java-src/Avy.java b/anif/tools/java-src/Avy.java index 54d28ec..d18078b 100644 --- a/anif/tools/java-src/Avy.java +++ b/anif/tools/java-src/Avy.java @@ -1,42 +1,46 @@ package net.algoviz; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import com.google.gson.Gson; public class Avy { private static int fileIndex = 0; private static PrintWriter file = null; private static Gson gson = new Gson(); public static void cmd(String name, Object ...args) { if (name.equals("start")) { if (file != null) { file.close(); } try { file = new PrintWriter(new FileWriter(String.format("%d.avy", fileIndex++))); } catch (IOException e) { // TODO: do something with the exception return; } return; } StringBuffer sb = new StringBuffer(name); - for (Object obj : args) { - sb.append(' '); - sb.append(gson.toJson(obj)); + sb.append("("); + for (int i = 0; i < args.length; i++) { + if (i > 0) { + sb.append(", "); + } + sb.append(gson.toJson(args[i])); } + sb.append(")"); file.println(sb.toString()); } public static void close() { if (file != null) { file.close(); } } }
false
true
public static void cmd(String name, Object ...args) { if (name.equals("start")) { if (file != null) { file.close(); } try { file = new PrintWriter(new FileWriter(String.format("%d.avy", fileIndex++))); } catch (IOException e) { // TODO: do something with the exception return; } return; } StringBuffer sb = new StringBuffer(name); for (Object obj : args) { sb.append(' '); sb.append(gson.toJson(obj)); } file.println(sb.toString()); }
public static void cmd(String name, Object ...args) { if (name.equals("start")) { if (file != null) { file.close(); } try { file = new PrintWriter(new FileWriter(String.format("%d.avy", fileIndex++))); } catch (IOException e) { // TODO: do something with the exception return; } return; } StringBuffer sb = new StringBuffer(name); sb.append("("); for (int i = 0; i < args.length; i++) { if (i > 0) { sb.append(", "); } sb.append(gson.toJson(args[i])); } sb.append(")"); file.println(sb.toString()); }
diff --git a/src/uk/me/parabola/mkgmap/osmstyle/RuleSet.java b/src/uk/me/parabola/mkgmap/osmstyle/RuleSet.java index 2c08a2b7..fcbe7a9f 100644 --- a/src/uk/me/parabola/mkgmap/osmstyle/RuleSet.java +++ b/src/uk/me/parabola/mkgmap/osmstyle/RuleSet.java @@ -1,219 +1,222 @@ /* * Copyright (C) 2008 Steve Ratcliffe * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * 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. * * * Author: Steve Ratcliffe * Create date: 08-Nov-2008 */ package uk.me.parabola.mkgmap.osmstyle; import java.util.Collections; import java.util.Formatter; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; import uk.me.parabola.mkgmap.osmstyle.eval.BinaryOp; import uk.me.parabola.mkgmap.osmstyle.eval.EqualsOp; import uk.me.parabola.mkgmap.osmstyle.eval.ExistsOp; import uk.me.parabola.mkgmap.osmstyle.eval.Op; import uk.me.parabola.mkgmap.osmstyle.eval.ValueOp; import uk.me.parabola.mkgmap.reader.osm.Element; import uk.me.parabola.mkgmap.reader.osm.GType; import uk.me.parabola.mkgmap.reader.osm.Rule; /** * A group of rules. Basically just a map of a tag=value strings that is used * as an index and the rule that applies for that tag,value pair. * * The main purpose is to separate out the code to add a new rule * which is moderately complex. * * @author Steve Ratcliffe */ public class RuleSet implements Rule { private final Map<String, RuleList> rules = new LinkedHashMap<String, RuleList>(); private boolean initRun; public void add(String key, RuleHolder rule) { RuleList rl = rules.get(key); if (rl == null) { rl = new RuleList(); rules.put(key, rl); } rl.add(rule); } /** * Initialise this rule set before it gets used. What we do is find all * the rules that might be needed as a result of tags being set during the * execution of other rules. */ public void init() { for (RuleList rl : rules.values()) { RuleList ruleList = new RuleList(); for (RuleHolder rh : rl) { if (rh.getChangeableTags() != null) initExtraRules(rh, ruleList); } rl.add(ruleList); } initRun = true; } /** * Initialise the extra rules that could be needed for a given rule. * Normally we search for rules by looking up the tags that are on an * element (to save having to really look through each rule). However * if an action causes a tag to be set, we might miss a rule that * would match the newly set tag. * * So we have to search for all rules that could match a newly set tag. * These get added to the rule list. * * @param rule An individual rule. * @param extraRules This is a output parameter, new rules are saved here * by this method. All rules that might be required due to actions * that set a tag. */ private void initExtraRules(RuleHolder rule, RuleList extraRules) { Set<String> tags = rule.getChangeableTags(); Set<String> moreTags = new HashSet<String>(); do { for (String t : tags) { String match = t + '='; for (Map.Entry<String, RuleList> ent : rules.entrySet()) { if (ent.getKey().startsWith(match)) { String exprstr = ent.getKey(); RuleList other = ent.getValue(); // As we are going to run this rule no matter what // tags were present, we need to add back the condition // that was represented by the key in the rule map. Op op = createExpression(exprstr); for (RuleHolder rh : other) { // There may be even more changeable tags // so add them here. - moreTags.addAll(rh.getChangeableTags()); + Set<String> changeableTags = rh.getChangeableTags(); + if (changeableTags == null) + continue; + moreTags.addAll(changeableTags); // Re-construct the rule and add it to the output list Rule r = new ExpressionSubRule(op, rh); extraRules.add(rh.createCopy(r)); } } } } // Remove the tags we already know about, and run through the others. moreTags.removeAll(tags); tags = Collections.unmodifiableSet(new HashSet<String>(moreTags)); } while (!tags.isEmpty()); } /** * Create an expression from a plain string. * @param expr The string containing an expression. * @return The compiled form of the expression. */ private Op createExpression(String expr) { String[] keyVal = expr.split("=", 2); Op op; if (keyVal[1].equals("*")) { op = new ExistsOp(); op.setFirst(new ValueOp(keyVal[0])); } else { op = new EqualsOp(); op.setFirst(new ValueOp(keyVal[0])); ((BinaryOp) op).setSecond(new ValueOp(keyVal[1])); } return op; } /** * Resolve the type for this element by running the rules in order. * * This is a very performance critical part of the style system as parts * of the code are run for every tag in the input file. * * @param el The element as read from an OSM xml file in 'tag' format. * @return A GType describing the Garmin type of the first rule that * matches. If there is no match then null is returned. */ public GType resolveType(Element el) { assert initRun; RuleList combined = new RuleList(); for (String tagKey : el) { RuleList rl = rules.get(tagKey); if (rl != null) combined.add(rl); } return combined.resolveType(el); } /** * Add all rules from the given rule set to this one. * @param rs The other rule set. */ public void addAll(RuleSet rs) { rules.putAll(rs.rules); } /** * Format the rule set. Warning: this doesn't produce a valid input * rule file. */ public String toString() { Formatter fmt = new Formatter(); for (Map.Entry<String, RuleList> ent: rules.entrySet()) { String first = ent.getKey(); RuleList r = ent.getValue(); r.dumpRules(fmt, first); } return fmt.toString(); } public Set<Map.Entry<String, RuleList>> entrySet() { return rules.entrySet(); } public Rule getRule(String key) { return rules.get(key); } public void merge(RuleSet rs) { for (Map.Entry<String, RuleList> ent : rs.rules.entrySet()) { String key = ent.getKey(); RuleList otherList = ent.getValue(); // get our list for this key and merge the lists. // if we don't already have a list then just add it. RuleList ourList = rules.get(key); if (ourList == null) { rules.put(key, otherList); } else { for (RuleHolder rh : otherList) { ourList.add(rh); } } } } }
true
true
private void initExtraRules(RuleHolder rule, RuleList extraRules) { Set<String> tags = rule.getChangeableTags(); Set<String> moreTags = new HashSet<String>(); do { for (String t : tags) { String match = t + '='; for (Map.Entry<String, RuleList> ent : rules.entrySet()) { if (ent.getKey().startsWith(match)) { String exprstr = ent.getKey(); RuleList other = ent.getValue(); // As we are going to run this rule no matter what // tags were present, we need to add back the condition // that was represented by the key in the rule map. Op op = createExpression(exprstr); for (RuleHolder rh : other) { // There may be even more changeable tags // so add them here. moreTags.addAll(rh.getChangeableTags()); // Re-construct the rule and add it to the output list Rule r = new ExpressionSubRule(op, rh); extraRules.add(rh.createCopy(r)); } } } } // Remove the tags we already know about, and run through the others. moreTags.removeAll(tags); tags = Collections.unmodifiableSet(new HashSet<String>(moreTags)); } while (!tags.isEmpty()); }
private void initExtraRules(RuleHolder rule, RuleList extraRules) { Set<String> tags = rule.getChangeableTags(); Set<String> moreTags = new HashSet<String>(); do { for (String t : tags) { String match = t + '='; for (Map.Entry<String, RuleList> ent : rules.entrySet()) { if (ent.getKey().startsWith(match)) { String exprstr = ent.getKey(); RuleList other = ent.getValue(); // As we are going to run this rule no matter what // tags were present, we need to add back the condition // that was represented by the key in the rule map. Op op = createExpression(exprstr); for (RuleHolder rh : other) { // There may be even more changeable tags // so add them here. Set<String> changeableTags = rh.getChangeableTags(); if (changeableTags == null) continue; moreTags.addAll(changeableTags); // Re-construct the rule and add it to the output list Rule r = new ExpressionSubRule(op, rh); extraRules.add(rh.createCopy(r)); } } } } // Remove the tags we already know about, and run through the others. moreTags.removeAll(tags); tags = Collections.unmodifiableSet(new HashSet<String>(moreTags)); } while (!tags.isEmpty()); }
diff --git a/cf-spring/src/main/java/cf/spring/ServiceBrokerHandler.java b/cf-spring/src/main/java/cf/spring/ServiceBrokerHandler.java index d4cb862..6afe9d0 100644 --- a/cf-spring/src/main/java/cf/spring/ServiceBrokerHandler.java +++ b/cf-spring/src/main/java/cf/spring/ServiceBrokerHandler.java @@ -1,142 +1,142 @@ /* * Copyright (c) 2013 Intellectual Reserve, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package cf.spring; import cf.service.AuthenticationException; import cf.service.BadRequestException; import cf.service.Provisioner; import cf.service.ResourceNotFoundException; import cf.service.ServiceBroker; import cf.service.ServiceBrokerException; import org.springframework.util.StreamUtils; import org.springframework.web.HttpRequestHandler; import org.springframework.web.servlet.handler.AbstractUrlHandlerMapping; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Collections; import java.util.HashSet; import java.util.Set; import java.util.regex.Matcher; /** * @author Mike Heath <[email protected]> */ public class ServiceBrokerHandler extends AbstractUrlHandlerMapping { public static class ServiceBrokerHandlerBuilder { private final ServiceBroker serviceBroker; private int order = 0; public ServiceBrokerHandlerBuilder(ServiceBroker serviceBroker) { this.serviceBroker = serviceBroker; } public ServiceBrokerHandlerBuilder(Provisioner provisioner, String authToken) { this.serviceBroker = new ServiceBroker(provisioner, authToken); } public ServiceBrokerHandlerBuilder order(int order) { this.order = order; return this; } public ServiceBrokerHandler build() { return new ServiceBrokerHandler(this); } // TODO Add URI prefix } private final ServiceBroker serviceBroker; private ServiceBrokerHandler(ServiceBrokerHandlerBuilder builder) { this.serviceBroker = builder.serviceBroker; setOrder(builder.order); registerHandlers(); } private void registerHandlers() { // Create service registerHandler("/gateway/v1/configurations", new RequestHandler("POST") { @Override protected String handleRequest(HttpServletRequest request, HttpServletResponse response, String authToken, byte[] body) throws ServiceBrokerException { return serviceBroker.createService(authToken, body); } }); - registerHandler("/gateway/v1/configurations/*", new RequestHandler("DELETE", "POST") { + registerHandler("/gateway/v1/configurations/**", new RequestHandler("DELETE", "POST") { @Override protected String handleRequest(HttpServletRequest request, HttpServletResponse response, String authToken, byte[] body) throws ServiceBrokerException { final String requestUri = request.getRequestURI(); final Matcher bindingMatcher = ServiceBroker.BINDING_PATTERN.matcher(requestUri); if (bindingMatcher.matches()) { switch (request.getMethod()) { case "DELETE": return serviceBroker.unbindService(authToken, requestUri); case "POST": return serviceBroker.bindService(authToken, body); } } final Matcher instanceMatcher = ServiceBroker.INSTANCE_PATTERN.matcher(requestUri); if (instanceMatcher.matches() && "DELETE".equals(request.getMethod())) { return serviceBroker.deleteService(authToken, requestUri); } throw new ResourceNotFoundException(); } }); } private abstract class RequestHandler implements HttpRequestHandler { private final Set<String> allowedHttpMethods = new HashSet<>(); public RequestHandler(String... allowedHttpMethods) { Collections.addAll(this.allowedHttpMethods, allowedHttpMethods); } @Override public final void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (!allowedHttpMethods.contains(request.getMethod())) { response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); return; } final String authToken = request.getHeader(ServiceBroker.VCAP_SERVICE_TOKEN_HEADER); final byte[] body = StreamUtils.copyToByteArray(request.getInputStream()); try { String responseBody = handleRequest(request, response, authToken, body); response.setContentType("application/json;charset=utf-8"); response.getWriter().write(responseBody); } catch (AuthenticationException e) { response.sendError(HttpServletResponse.SC_FORBIDDEN, e.getMessage()); } catch (BadRequestException e) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage()); } catch (ResourceNotFoundException e) { response.sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage()); } catch (Exception e) { throw new ServletException(e); } } protected abstract String handleRequest(HttpServletRequest request, HttpServletResponse response, String authToken, byte[] body) throws ServiceBrokerException; } }
true
true
private void registerHandlers() { // Create service registerHandler("/gateway/v1/configurations", new RequestHandler("POST") { @Override protected String handleRequest(HttpServletRequest request, HttpServletResponse response, String authToken, byte[] body) throws ServiceBrokerException { return serviceBroker.createService(authToken, body); } }); registerHandler("/gateway/v1/configurations/*", new RequestHandler("DELETE", "POST") { @Override protected String handleRequest(HttpServletRequest request, HttpServletResponse response, String authToken, byte[] body) throws ServiceBrokerException { final String requestUri = request.getRequestURI(); final Matcher bindingMatcher = ServiceBroker.BINDING_PATTERN.matcher(requestUri); if (bindingMatcher.matches()) { switch (request.getMethod()) { case "DELETE": return serviceBroker.unbindService(authToken, requestUri); case "POST": return serviceBroker.bindService(authToken, body); } } final Matcher instanceMatcher = ServiceBroker.INSTANCE_PATTERN.matcher(requestUri); if (instanceMatcher.matches() && "DELETE".equals(request.getMethod())) { return serviceBroker.deleteService(authToken, requestUri); } throw new ResourceNotFoundException(); } }); }
private void registerHandlers() { // Create service registerHandler("/gateway/v1/configurations", new RequestHandler("POST") { @Override protected String handleRequest(HttpServletRequest request, HttpServletResponse response, String authToken, byte[] body) throws ServiceBrokerException { return serviceBroker.createService(authToken, body); } }); registerHandler("/gateway/v1/configurations/**", new RequestHandler("DELETE", "POST") { @Override protected String handleRequest(HttpServletRequest request, HttpServletResponse response, String authToken, byte[] body) throws ServiceBrokerException { final String requestUri = request.getRequestURI(); final Matcher bindingMatcher = ServiceBroker.BINDING_PATTERN.matcher(requestUri); if (bindingMatcher.matches()) { switch (request.getMethod()) { case "DELETE": return serviceBroker.unbindService(authToken, requestUri); case "POST": return serviceBroker.bindService(authToken, body); } } final Matcher instanceMatcher = ServiceBroker.INSTANCE_PATTERN.matcher(requestUri); if (instanceMatcher.matches() && "DELETE".equals(request.getMethod())) { return serviceBroker.deleteService(authToken, requestUri); } throw new ResourceNotFoundException(); } }); }
diff --git a/nuxeo-runtime-tomcat-adapter/src/main/java/org/nuxeo/runtime/tomcat/dev/NuxeoDevWebappClassLoader.java b/nuxeo-runtime-tomcat-adapter/src/main/java/org/nuxeo/runtime/tomcat/dev/NuxeoDevWebappClassLoader.java index c3d4f3c8..299d89af 100644 --- a/nuxeo-runtime-tomcat-adapter/src/main/java/org/nuxeo/runtime/tomcat/dev/NuxeoDevWebappClassLoader.java +++ b/nuxeo-runtime-tomcat-adapter/src/main/java/org/nuxeo/runtime/tomcat/dev/NuxeoDevWebappClassLoader.java @@ -1,119 +1,121 @@ /* * (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.runtime.tomcat.dev; import java.net.URL; import java.util.ArrayList; import java.util.List; import org.apache.catalina.loader.WebappClassLoader; import org.nuxeo.osgi.application.MutableClassLoader; /** * @author <a href="mailto:[email protected]">Bogdan Stefanescu</a> */ public class NuxeoDevWebappClassLoader extends WebappClassLoader implements MutableClassLoader { public LocalClassLoader createLocalClassLoader(URL... urls) { LocalClassLoader cl = new LocalURLClassLoader(urls, this); addChildren(cl); return cl; } protected List<LocalClassLoader> children; protected volatile LocalClassLoader[] _children; public NuxeoDevWebappClassLoader() { this.children = new ArrayList<LocalClassLoader>(); } public NuxeoDevWebappClassLoader(ClassLoader parent) { super(parent); this.children = new ArrayList<LocalClassLoader>(); } public synchronized void addChildren(LocalClassLoader loader) { children.add(loader); _children = null; } public synchronized void removeChildren(ClassLoader loader) { children.remove(loader); _children = null; } public synchronized void clear() { children.clear(); _children = null; } public LocalClassLoader[] getChildren() { LocalClassLoader[] cls = _children; if (cls == null) { synchronized (this) { _children = children.toArray(new LocalClassLoader[children.size()]); cls = _children; } } return cls; } /** * Do not synchronize this method at method level to avoid deadlocks. */ @Override public Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { try { - return super.loadClass(name, resolve); + synchronized (this) { + return super.loadClass(name, resolve); + } } catch (ClassNotFoundException e) { for (LocalClassLoader cl : getChildren()) { try { return cl.loadLocalClass(name, resolve); } catch (ClassNotFoundException ee) { // do nothing } } } throw new ClassNotFoundException(name); } @Override public void addURL(URL url) { super.addURL(url); } @Override public void setParentClassLoader(ClassLoader pcl) { super.setParentClassLoader(pcl); } public ClassLoader getParentClassLoader() { return parent; } @Override public ClassLoader getClassLoader() { return this; } }
true
true
public Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { try { return super.loadClass(name, resolve); } catch (ClassNotFoundException e) { for (LocalClassLoader cl : getChildren()) { try { return cl.loadLocalClass(name, resolve); } catch (ClassNotFoundException ee) { // do nothing } } } throw new ClassNotFoundException(name); }
public Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { try { synchronized (this) { return super.loadClass(name, resolve); } } catch (ClassNotFoundException e) { for (LocalClassLoader cl : getChildren()) { try { return cl.loadLocalClass(name, resolve); } catch (ClassNotFoundException ee) { // do nothing } } } throw new ClassNotFoundException(name); }
diff --git a/Plugins/ExternalServices/Edemande/src/java/fr/capwebct/capdemat/plugins/externalservices/edemande/service/EdemandeService.java b/Plugins/ExternalServices/Edemande/src/java/fr/capwebct/capdemat/plugins/externalservices/edemande/service/EdemandeService.java index 67f3a8bba..f213ddb93 100644 --- a/Plugins/ExternalServices/Edemande/src/java/fr/capwebct/capdemat/plugins/externalservices/edemande/service/EdemandeService.java +++ b/Plugins/ExternalServices/Edemande/src/java/fr/capwebct/capdemat/plugins/externalservices/edemande/service/EdemandeService.java @@ -1,738 +1,741 @@ package fr.capwebct.capdemat.plugins.externalservices.edemande.service; import java.io.IOException; import java.io.StringReader; import java.math.BigDecimal; import java.text.DecimalFormat; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.TreeMap; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.apache.commons.lang.StringUtils; import org.apache.xmlbeans.XmlObject; import org.jaxen.JaxenException; import org.jaxen.dom.DOMXPath; import org.springframework.web.util.HtmlUtils; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import com.unilog.gda.edem.service.EnregistrerValiderFormulaireResponseDocument; import com.unilog.gda.glob.service.GestionCompteResponseDocument; import fr.capwebct.capdemat.plugins.externalservices.edemande.webservice.client.IEdemandeClient; import fr.cg95.cvq.business.document.Document; import fr.cg95.cvq.business.document.DocumentBinary; import fr.cg95.cvq.business.external.ExternalServiceTrace; import fr.cg95.cvq.business.external.TraceStatusEnum; import fr.cg95.cvq.business.request.Request; import fr.cg95.cvq.business.request.RequestDocument; import fr.cg95.cvq.business.request.RequestState; import fr.cg95.cvq.business.users.Individual; import fr.cg95.cvq.business.users.SexType; import fr.cg95.cvq.business.users.payment.ExternalAccountItem; import fr.cg95.cvq.business.users.payment.ExternalDepositAccountItem; import fr.cg95.cvq.business.users.payment.ExternalInvoiceItem; import fr.cg95.cvq.business.users.payment.PurchaseItem; import fr.cg95.cvq.exception.CvqConfigurationException; import fr.cg95.cvq.exception.CvqException; import fr.cg95.cvq.exception.CvqInvalidTransitionException; import fr.cg95.cvq.exception.CvqObjectNotFoundException; import fr.cg95.cvq.external.ExternalServiceBean; import fr.cg95.cvq.external.IExternalProviderService; import fr.cg95.cvq.external.IExternalService; import fr.cg95.cvq.permission.CvqPermissionException; import fr.cg95.cvq.service.document.IDocumentService; import fr.cg95.cvq.service.request.IRequestWorkflowService; import fr.cg95.cvq.service.request.school.IStudyGrantRequestService; import fr.cg95.cvq.util.translation.ITranslationService; import fr.cg95.cvq.xml.request.school.StudyGrantRequestDocument; import fr.cg95.cvq.xml.request.school.StudyGrantRequestDocument.StudyGrantRequest; public class EdemandeService implements IExternalProviderService { private String label; private IEdemandeClient edemandeClient; private IExternalService externalService; private IStudyGrantRequestService requestService; private IDocumentService documentService; private IRequestWorkflowService requestWorkflowService; private ITranslationService translationService; private EdemandeUploader uploader; private static final String ADDRESS_FIELDS[] = { "miCode", "moNature/miCode", "msVoie", "miBoitePostale", "msCodePostal", "msVille", "miCedex", "msPays", "msTel", "msFax", "msMail", "mbUsuel" }; private static final String SUBJECT_TRACE_SUBKEY = "subject"; private static final String ACCOUNT_HOLDER_TRACE_SUBKEY = "accountHolder"; private DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy"); @Override public String sendRequest(XmlObject requestXml) { StudyGrantRequest sgr = ((StudyGrantRequestDocument) requestXml).getStudyGrantRequest(); if (!sgr.getIsSubjectAccountHolder()) { String psCodeTiersAH = sgr.getAccountHolderEdemandeId(); if (psCodeTiersAH == null || psCodeTiersAH.trim().isEmpty()) { psCodeTiersAH = searchAccountHolder(sgr); if (psCodeTiersAH == null || psCodeTiersAH.trim().isEmpty()) { if (mustCreateAccountHolder(sgr)) { createAccountHolder(sgr); } else if (psCodeTiersAH != null) { addTrace(sgr.getId(), ACCOUNT_HOLDER_TRACE_SUBKEY, TraceStatusEnum.IN_PROGRESS, "Le tiers viré n'est pas encore créé"); } return null; } else { sgr.setAccountHolderEdemandeId(psCodeTiersAH); try { requestService.setAccountHolderEdemandeId(sgr.getId(), psCodeTiersAH); } catch (CvqException e) { // TODO } } } } String psCodeTiersS = sgr.getSubject().getIndividual().getExternalId(); if (psCodeTiersS == null || psCodeTiersS.trim().isEmpty()) { // external id (code tiers) not known locally : // either check if tiers has been created in eDemande // either ask for its creation in eDemande psCodeTiersS = searchSubject(sgr); if (psCodeTiersS == null || psCodeTiersS.trim().isEmpty()) { // tiers has not been created in eDemande ... if (mustCreateSubject(sgr)) { // ... and no request in progress so ask for its creation createSubject(sgr); } else if (psCodeTiersS != null) { // eDemande answered since psCodeTiers is not null, // and that means psCodeTiers is empty, so tiers // has not been created yet. // If psCodeTiers was null, that would mean searchIndividual // caught an exception while contacting eDemande, and // has already added a NOT_SENT trace. // FIXME BOR : is this trace really needed ? addTrace(sgr.getId(), SUBJECT_TRACE_SUBKEY, TraceStatusEnum.IN_PROGRESS, "Le tiers sujet n'est pas encore créé"); } return null; } else { // tiers has been created in eDemande, store its code locally sgr.getSubject().getIndividual().setExternalId(psCodeTiersS); externalService.setExternalId(label, sgr.getHomeFolder().getId(), sgr.getSubject().getIndividual().getId(), psCodeTiersS); } } // reaching this code means we have valid psCodeTiers (either because // they were already set since it is not the subject and account holder's first request, or because // searchIndividual returned the newly created tiers' psCodeTiers) // Try to get the external ID if we don't already know it String psCodeDemande = sgr.getEdemandeId(); if (psCodeDemande == null || psCodeDemande.trim().isEmpty()) { psCodeDemande = searchRequest(sgr, psCodeTiersS); if (psCodeDemande != null && !psCodeDemande.trim().isEmpty() && !"-1".equals(psCodeDemande)) { sgr.setEdemandeId(psCodeDemande); try { requestService.setEdemandeId(sgr.getId(), psCodeDemande); } catch (CvqException e) { // TODO } } } // (Re)send request if needed if (mustSendNewRequest(sgr)) { submitRequest(sgr, psCodeTiersS, true); } else if (mustResendRequest(sgr)) { submitRequest(sgr, psCodeTiersS, false); } // check request status String msStatut = getRequestStatus(sgr, psCodeTiersS); if (msStatut == null) { // got an exception while contacting Edemande return null; } if (msStatut.trim().isEmpty()) { addTrace(sgr.getId(), null, TraceStatusEnum.NOT_SENT, "La demande n'a pas encore été reçue"); return null; } if ("En attente de réception par la collectivité".equals(msStatut)) { return null; } else if ("A compléter ou corriger".equals(msStatut) || "A compléter".equals(msStatut) || "En erreur".equals(msStatut)) { addTrace(sgr.getId(), null, TraceStatusEnum.ERROR, msStatut); } else if ("En cours d'analyse".equals(msStatut) || "En attente d'avis externe".equals(msStatut) || "En cours d'instruction".equals(msStatut)) { addTrace(sgr.getId(), null, TraceStatusEnum.ACKNOWLEDGED, msStatut); } else if ("Accepté".equals(msStatut) || "En cours de paiement".equals(msStatut) || "Payé partiellement".equals(msStatut) || "Terminé".equals(msStatut)) { addTrace(sgr.getId(), null, TraceStatusEnum.ACCEPTED, msStatut); } else if ("Refusé".equals(msStatut)) { addTrace(sgr.getId(), null, TraceStatusEnum.REJECTED, msStatut); } return null; } private void addTrace(Long requestId, String subkey, TraceStatusEnum status, String message) { ExternalServiceTrace est = new ExternalServiceTrace(); est.setDate(new Date()); est.setKey(String.valueOf(requestId)); est.setSubkey(subkey); est.setKeyOwner("capdemat"); est.setMessage(message); est.setName(label); est.setStatus(status); try { externalService.create(est); } catch (CvqPermissionException e) { // should never happen e.printStackTrace(); } if (TraceStatusEnum.ERROR.equals(status)) { try { requestWorkflowService.updateRequestState(requestId, RequestState.UNCOMPLETE, message); } catch (CvqObjectNotFoundException e) { // TODO } catch (CvqInvalidTransitionException e) { // TODO } catch (CvqException e) { // TODO } } } /** * Search for this request's individual in eDemande. * * @return the individual's code in eDemande, an empty string if the individual is not found, * or null if there is an error while contacting eDemande. */ private String searchIndividual(StudyGrantRequest sgr, String lastName, String subkey) { Map<String, Object> model = new HashMap<String, Object>(); model.put("lastName", lastName); model.put("bankCode", sgr.getBankCode()); model.put("counterCode", sgr.getCounterCode()); model.put("accountNumber", sgr.getAccountNumber()); model.put("accountKey", sgr.getAccountKey()); try { return parseData(edemandeClient.rechercherTiers(model).getRechercherTiersResponse().getReturn(), "//resultatRechTiers/listeTiers/tiers/codeTiers"); } catch (CvqException e) { addTrace(sgr.getId(), subkey, TraceStatusEnum.NOT_SENT, e.getMessage()); return null; } } private String searchSubject(StudyGrantRequest sgr) { return searchIndividual(sgr, sgr.getSubject().getIndividual().getLastName(), SUBJECT_TRACE_SUBKEY); } private String searchAccountHolder(StudyGrantRequest sgr) { return searchIndividual(sgr, sgr.getAccountHolderLastName(), ACCOUNT_HOLDER_TRACE_SUBKEY); } private void createSubject(StudyGrantRequest sgr) { Map<String, Object> model = new HashMap<String, Object>(); model.put("lastName", sgr.getSubject().getIndividual().getLastName()); model.put("address", sgr.getSubjectInformations().getSubjectAddress()); if (sgr.getSubjectInformations().getSubjectPhone() != null && !sgr.getSubjectInformations().getSubjectPhone().trim().isEmpty()) { model.put("phone", sgr.getSubjectInformations().getSubjectPhone()); } else if (sgr.getSubjectInformations().getSubjectMobilePhone() != null && !sgr.getSubjectInformations().getSubjectMobilePhone().trim().isEmpty()) { model.put("phone", sgr.getSubjectInformations().getSubjectMobilePhone()); } model.put("email", StringUtils.defaultString(sgr.getSubjectInformations().getSubjectEmail())); if (sgr.getSubject().getAdult() != null) { model.put("title", translationService.translate("homeFolder.adult.title." + sgr.getSubject().getAdult().getTitle().toString().toLowerCase(), Locale.FRANCE)); } else { if (SexType.MALE.toString().equals(sgr.getSubject().getIndividual().getSex().toString())) { model.put("title", translationService.translate("homeFolder.adult.title.mister", Locale.FRANCE)); } else if (SexType.FEMALE.toString().equals(sgr.getSubject().getIndividual().getSex().toString())) { model.put("title", translationService.translate("homeFolder.adult.title.miss", Locale.FRANCE)); } else { model.put("title", translationService.translate("homeFolder.adult.title.unknown", Locale.FRANCE)); } } model.put("firstName", sgr.getSubject().getIndividual().getFirstName()); model.put("birthPlace", sgr.getSubject().getIndividual().getBirthPlace() != null ? StringUtils.defaultString(sgr.getSubject().getIndividual().getBirthPlace().getCity()) : ""); model.put("birthDate", formatDate(sgr.getSubjectInformations().getSubjectBirthDate())); model.put("bankCode", sgr.getBankCode()); model.put("counterCode", sgr.getCounterCode()); model.put("accountNumber", sgr.getAccountNumber()); model.put("accountKey", sgr.getAccountKey()); try { GestionCompteResponseDocument response = edemandeClient.creerTiers(model); if (!"0".equals(parseData(response.getGestionCompteResponse().getReturn(), "//Retour/codeRetour"))) { addTrace(sgr.getId(), SUBJECT_TRACE_SUBKEY, TraceStatusEnum.ERROR, parseData(response.getGestionCompteResponse().getReturn(), "//Retour/messageRetour")); } else { addTrace(sgr.getId(), SUBJECT_TRACE_SUBKEY, TraceStatusEnum.IN_PROGRESS, "Demande de création du tiers sujet"); } } catch (CvqException e) { e.printStackTrace(); addTrace(sgr.getId(), SUBJECT_TRACE_SUBKEY, TraceStatusEnum.NOT_SENT, e.getMessage()); } } private void createAccountHolder(StudyGrantRequest sgr) { Map<String, Object> model = new HashMap<String, Object>(); model.put("title", translationService.translate("homeFolder.adult.title." + sgr.getAccountHolderTitle().toString().toLowerCase(), Locale.FRANCE)); model.put("lastName", sgr.getAccountHolderLastName()); //FIXME placeholders; are these really needed ? model.put("address", sgr.getSubjectInformations().getSubjectAddress()); model.put("phone", ""); model.put("email", ""); model.put("birthPlace", ""); //ENDFIXME model.put("firstName", sgr.getAccountHolderFirstName()); model.put("birthDate", formatDate(sgr.getAccountHolderBirthDate())); model.put("bankCode", sgr.getBankCode()); model.put("counterCode", sgr.getCounterCode()); model.put("accountNumber", sgr.getAccountNumber()); model.put("accountKey", sgr.getAccountKey()); try { GestionCompteResponseDocument response = edemandeClient.creerTiers(model); if (!"0".equals(parseData(response.getGestionCompteResponse().getReturn(), "//Retour/codeRetour"))) { addTrace(sgr.getId(), ACCOUNT_HOLDER_TRACE_SUBKEY, TraceStatusEnum.ERROR, parseData(response.getGestionCompteResponse().getReturn(), "//Retour/messageRetour")); } else { addTrace(sgr.getId(), ACCOUNT_HOLDER_TRACE_SUBKEY, TraceStatusEnum.IN_PROGRESS, "Demande de création du tiers viré"); } } catch (CvqException e) { e.printStackTrace(); addTrace(sgr.getId(), ACCOUNT_HOLDER_TRACE_SUBKEY, TraceStatusEnum.NOT_SENT, e.getMessage()); } } private void submitRequest(StudyGrantRequest sgr, String psCodeTiers, boolean firstSending) { Map<String, Object> model = new HashMap<String, Object>(); String requestData = null; if (!firstSending) { try { requestData = edemandeClient.chargerDemande(psCodeTiers, sgr.getEdemandeId()).getChargerDemandeResponse().getReturn(); } catch (CvqException e) { e.printStackTrace(); addTrace(sgr.getId(), null, TraceStatusEnum.NOT_SENT, e.getMessage()); } } model.put("externalRequestId", buildExternalRequestId(sgr)); model.put("psCodeTiers", psCodeTiers); model.put("psCodeDemande", StringUtils.defaultIfEmpty(sgr.getEdemandeId(), "-1")); model.put("etatCourant", firstSending ? 2 : 1); model.put("firstName", sgr.getSubject().getIndividual().getFirstName()); model.put("lastName", sgr.getSubject().getIndividual().getLastName()); model.put("postalCode", sgr.getSubjectInformations().getSubjectAddress().getPostalCode()); model.put("city", sgr.getSubjectInformations().getSubjectAddress().getCity()); model.put("bankCode", sgr.getBankCode()); model.put("counterCode", sgr.getCounterCode()); model.put("accountNumber", sgr.getAccountNumber()); model.put("accountKey", sgr.getAccountKey()); model.put("firstRequest", sgr.getSubjectInformations().getSubjectFirstRequest()); model.put("creationDate", formatDate(sgr.getCreationDate())); model.put("taxHouseholdCityCode", sgr.getTaxHouseholdCityArray(0).getName()); model.put("taxHouseholdIncome", sgr.getTaxHouseholdIncome()); model.put("hasCROUSHelp", sgr.getHasCROUSHelp()); model.put("hasRegionalCouncilHelp", sgr.getHasRegionalCouncilHelp()); model.put("hasEuropeHelp", sgr.getHasEuropeHelp()); model.put("hasOtherHelp", sgr.getHasOtherHelp()); model.put("AlevelsDate", sgr.getALevelsInformations().getAlevelsDate()); model.put("AlevelsType", translationService.translate("sgr.property.alevels." + sgr.getALevelsInformations().getAlevels().toString().toLowerCase(), Locale.FRANCE)); model.put("currentStudiesType", + StringUtils.defaultIfEmpty(sgr.getCurrentStudiesInformations().getOtherStudiesLabel(), translationService.translate("sgr.property.currentStudies." - + sgr.getCurrentStudiesInformations().getCurrentStudies().toString(), Locale.FRANCE)); + + sgr.getCurrentStudiesInformations().getCurrentStudies().toString(), Locale.FRANCE))); model.put("currentStudiesLevel", translationService.translate("sgr.property.currentStudiesLevel." + sgr.getCurrentStudiesInformations().getCurrentStudiesLevel().toString(), Locale.FRANCE)); model.put("sandwichCourses", sgr.getCurrentStudiesInformations().getSandwichCourses()); model.put("abroadInternship", sgr.getCurrentStudiesInformations().getAbroadInternship()); model.put("abroadInternshipStartDate", formatDate(sgr.getCurrentStudiesInformations().getAbroadInternshipStartDate())); model.put("abroadInternshipEndDate", formatDate(sgr.getCurrentStudiesInformations().getAbroadInternshipEndDate())); model.put("currentSchoolName", StringUtils.defaultIfEmpty(sgr.getCurrentSchool().getCurrentSchoolNamePrecision(), sgr.getCurrentSchool().getCurrentSchoolNameArray(0).getName())); model.put("currentSchoolPostalCode", StringUtils.defaultString(sgr.getCurrentSchool().getCurrentSchoolPostalCode())); model.put("currentSchoolCity", StringUtils.defaultString(sgr.getCurrentSchool().getCurrentSchoolCity())); model.put("currentSchoolCountry", sgr.getCurrentSchool().getCurrentSchoolCountry() != null ? - sgr.getCurrentSchool().getCurrentSchoolCountry() : ""); + translationService.translate("sgr.property.currentSchoolCountry." + + sgr.getCurrentSchool().getCurrentSchoolCountry()) : ""); model.put("abroadInternshipSchoolName", sgr.getCurrentStudiesInformations().getAbroadInternship() ? sgr.getCurrentStudiesInformations().getAbroadInternshipSchoolName() : ""); model.put("abroadInternshipSchoolCountry", sgr.getCurrentStudiesInformations().getAbroadInternship() ? - sgr.getCurrentStudiesInformations().getAbroadInternshipSchoolCountry() : ""); + translationService.translate("sgr.property.abroadInternshipSchoolCountry." + + sgr.getCurrentStudiesInformations().getAbroadInternshipSchoolCountry()) : ""); model.put("distance", translationService.translate("sgr.property.distance." + sgr.getDistance().toString(), Locale.FRANCE)); List<Map<String, Object>> documents = new ArrayList<Map<String, Object>>(); model.put("documents", documents); try { if (false) for (RequestDocument requestDoc : requestService.getAssociatedDocuments(sgr.getId())) { Document document = documentService.getById(requestDoc.getDocumentId()); Map<String, Object> doc = new HashMap<String, Object>(); documents.add(doc); List<Map<String, String>> parts = new ArrayList<Map<String, String>>(); doc.put("parts", parts); int i = 1; for (DocumentBinary documentBinary : document.getDatas()) { Map<String, String> part = new HashMap<String, String>(); parts.add(part); String filename = org.springframework.util.StringUtils.arrayToDelimitedString( new String[] { "CapDemat", document.getDocumentType().getName(), String.valueOf(sgr.getId()), String.valueOf(i++) }, "-"); part.put("filename", filename); try { part.put("remotePath", uploader.upload(filename, documentBinary.getData())); } catch (Exception e) { //TODO } } } model.put("msStatut", firstSending ? "" : getRequestStatus(sgr, psCodeTiers)); model.put("millesime", firstSending ? "" : parseData(requestData, "//donneesDemande/Demande/miMillesime")); model.put("msCodext", firstSending ? "" : parseData(requestData, "//donneesDemande/Demande/msCodext")); model.put("requestTypeCode", parseData(edemandeClient.chargerTypeDemande(null).getChargerTypeDemandeResponse().getReturn(), "//typeDemande/code")); model.put("address", parseAddress((String)model.get("psCodeTiers"))); EnregistrerValiderFormulaireResponseDocument enregistrerValiderFormulaireResponseDocument = edemandeClient.enregistrerValiderFormulaire(model); if (!"0".equals(parseData(enregistrerValiderFormulaireResponseDocument.getEnregistrerValiderFormulaireResponse().getReturn(), "//Retour/codeRetour"))) { addTrace(sgr.getId(), null, TraceStatusEnum.ERROR, parseData(enregistrerValiderFormulaireResponseDocument.getEnregistrerValiderFormulaireResponse().getReturn(), "//Retour/messageRetour")); } else { addTrace(sgr.getId(), null, TraceStatusEnum.SENT, "Demande transmise"); } } catch (CvqException e) { e.printStackTrace(); addTrace(sgr.getId(), null, TraceStatusEnum.NOT_SENT, e.getMessage()); } } private String searchRequest(StudyGrantRequest sgr, String psCodeTiers) { try { return parseData(edemandeClient.rechercheDemandesTiers(psCodeTiers) .getRechercheDemandesTiersResponse().getReturn(), "//resultatRechDemandes/listeDemandes/Demande/moOrigineApsect[msIdentifiant ='" + buildExternalRequestId(sgr) + "']/../miCode"); } catch (CvqException e) { addTrace(sgr.getId(), null, TraceStatusEnum.NOT_SENT, e.getMessage()); return null; } } private String getRequestStatus(StudyGrantRequest sgr, String psCodeTiers) { try { if (sgr.getEdemandeId() == null || sgr.getEdemandeId().trim().isEmpty()) { return parseData(edemandeClient.rechercheDemandesTiers(psCodeTiers) .getRechercheDemandesTiersResponse().getReturn(), "//resultatRechDemandes/listeDemandes/Demande/moOrigineApsect[msIdentifiant ='" + buildExternalRequestId(sgr) + "']/../msStatut"); } else { return parseData(edemandeClient.chargerDemande(psCodeTiers, sgr.getEdemandeId()) .getChargerDemandeResponse().getReturn(), "//donneesDemande/Demande/msStatut"); } } catch (CvqException e) { addTrace(sgr.getId(), null, TraceStatusEnum.NOT_SENT, e.getMessage()); return null; } } public List<String> checkExternalReferential(final XmlObject requestXml) { StudyGrantRequest sgr = ((StudyGrantRequestDocument) requestXml).getStudyGrantRequest(); List<String> result = new ArrayList<String>(); try { String postalCodeAndCityCheck = edemandeClient.existenceCommunePostale(sgr.getSubjectInformations().getSubjectAddress().getPostalCode(), sgr.getSubjectInformations().getSubjectAddress().getCity()).getExistenceCommunePostaleResponse().getReturn(); if (!"0".equals(parseData(postalCodeAndCityCheck, "//FluxWebService/msCodeRet"))) { result.add(parseData(postalCodeAndCityCheck, "//FluxWebService/erreur/message")); } String bankInformationsCheck = edemandeClient.verifierRIB(sgr.getBankCode(), sgr.getCounterCode(), sgr.getAccountNumber(), sgr.getAccountKey()).getVerifierRIBResponse().getReturn(); if (!"0".equals(parseData(bankInformationsCheck, "//FluxWebService/msCodeRet"))) { result.add(parseData(bankInformationsCheck, "//FluxWebService/erreur/message")); } } catch (CvqException e) { result.add("Impossible de contacter Edemande"); } return result; } public Map<String, Object> loadExternalInformations(XmlObject requestXml) throws CvqException { StudyGrantRequest sgr = ((StudyGrantRequestDocument) requestXml).getStudyGrantRequest(); if (sgr.getSubject().getIndividual().getExternalId() == null || sgr.getSubject().getIndividual().getExternalId().trim().isEmpty() || sgr.getEdemandeId() == null || sgr.getEdemandeId().trim().isEmpty()) { return Collections.emptyMap(); } Map<String, Object> informations = new TreeMap<String, Object>(); String request = edemandeClient.chargerDemande( sgr.getSubject().getIndividual().getExternalId(), sgr.getEdemandeId()) .getChargerDemandeResponse().getReturn(); String status = getRequestStatus(sgr, sgr.getSubject().getIndividual().getExternalId()); if (status != null && !status.trim().isEmpty()) { informations.put("sgr.property.externalStatus", status); } String grantedAmount = parseData(request, "//donneesDemande/Demande/mdMtAccorde"); if (grantedAmount != null && !grantedAmount.trim().isEmpty()) { informations.put("sgr.property.grantedAmount", new DecimalFormat(translationService.translate("format.currency")) .format(new BigDecimal(grantedAmount))); } String paidAmount = parseData(request, "//donneesDemande/Demande/mdMtRealise"); if (paidAmount != null && !paidAmount.trim().isEmpty()) { informations.put("sgr.property.paidAmount", new DecimalFormat(translationService.translate("format.currency")) .format(new BigDecimal(paidAmount))); } return informations; } public void setLabel(String label) { this.label = label; } public void setEdemandeClient(IEdemandeClient edemandeClient) { this.edemandeClient = edemandeClient; } public boolean supportsConsumptions() { return false; } public boolean handlesTraces() { return true; } private Map<String, String> parseAddress(String psCodeTiers) throws CvqException { String tiers = edemandeClient.initialiserSuiviDemande(psCodeTiers).getInitialiserSuiviDemandeResponse().getReturn(); Map<String, String> address = new HashMap<String, String>(); for (String addressField : ADDRESS_FIELDS) { address.put(addressField, parseData(tiers, "//donneesTiers/tiers/mvAdresses/CTierAdresseVO/" + addressField)); } return address; } private String parseData(String returnElement, String path) throws CvqException { try { return new DOMXPath(path) .stringValueOf( DocumentBuilderFactory.newInstance().newDocumentBuilder() .parse(new InputSource(new StringReader(returnElement))) .getDocumentElement()); } catch (JaxenException e) { e.printStackTrace(); throw new CvqException("Erreur lors de la lecture de la réponse du service externe"); } catch (SAXException e) { e.printStackTrace(); throw new CvqException("Erreur lors de la lecture de la réponse du service externe"); } catch (IOException e) { e.printStackTrace(); throw new CvqException("Erreur lors de la lecture de la réponse du service externe"); } catch (ParserConfigurationException e) { e.printStackTrace(); throw new CvqException("Erreur lors de la lecture de la réponse du service externe"); } } private String buildExternalRequestId(StudyGrantRequest sgr) { return HtmlUtils.htmlEscape( org.springframework.util.StringUtils.arrayToDelimitedString( new String[] { "CapDemat", new SimpleDateFormat("yyyyMMdd").format(new Date(sgr.getCreationDate().getTimeInMillis())), sgr.getSubject().getIndividual().getFirstName(), sgr.getSubject().getIndividual().getLastName(), String.valueOf(sgr.getId()) }, "-") ); } /** * Whether or not we have to send the request. * * @return true if the request has no SENT trace (it has never been successfully sent) * or it has an error trace and no Edemande ID (it was sent and received, but rejected and must be sent as new) */ private boolean mustSendNewRequest(StudyGrantRequest sgr) { return !externalService.hasTraceWithStatus(sgr.getId(), null, label, TraceStatusEnum.SENT) || (externalService.hasTraceWithStatus(sgr.getId(), null, label, TraceStatusEnum.ERROR) && (sgr.getEdemandeId() == null || sgr.getEdemandeId().trim().isEmpty())); } /** * Whether or not we have to resend the request. * * @return true if the request has an Edemande ID (so it was already sent), * and an ERROR trace not followed by a SENT trace */ private boolean mustResendRequest(StudyGrantRequest sgr) { if (!externalService.hasTraceWithStatus(sgr.getId(), null, label, TraceStatusEnum.ERROR) || sgr.getEdemandeId() == null || sgr.getEdemandeId().trim().isEmpty()) { return false; } List<ExternalServiceTrace> traces = new ArrayList<ExternalServiceTrace>( externalService.getTraces(sgr.getId(), label)); Collections.sort(traces, new Comparator<ExternalServiceTrace>() { public int compare(ExternalServiceTrace o1, ExternalServiceTrace o2) { return o2.getDate().compareTo(o1.getDate()); } }); for (ExternalServiceTrace est : traces) { if (TraceStatusEnum.SENT.equals(est.getStatus())) { return false; } else if (TraceStatusEnum.ERROR.equals(est.getStatus())) { return true; } } // we should never execute the next line : // the above loop should have found a SENT trace and returned false, // or found the ERROR trace that IS in the list // (otherwise the first test would have succeded) // however, for compilation issues (and an hypothetic concurrent traces deletion) // we return false, to do nothing rather than doing something wrong return false; } /** * Determines if we must send an individual creation request for the request's subject * or account holder when this individual has no psCodeTiers yet. */ private boolean mustCreateIndividual(StudyGrantRequest sgr, String subkey) { if (!externalService.hasTraceWithStatus(sgr.getId(), subkey, label, TraceStatusEnum.IN_PROGRESS)) { return true; } List<ExternalServiceTrace> traces = new ArrayList<ExternalServiceTrace>( externalService.getTraces(sgr.getId(), subkey, label)); Collections.sort(traces, new Comparator<ExternalServiceTrace>() { public int compare(ExternalServiceTrace o1, ExternalServiceTrace o2) { return o2.getDate().compareTo(o1.getDate()); } }); for (ExternalServiceTrace est : traces) { if (TraceStatusEnum.IN_PROGRESS.equals(est.getStatus())) { return false; } else if (TraceStatusEnum.ERROR.equals(est.getStatus())) { return true; } } return false; } private String formatDate(Calendar calendar) { if (calendar == null) return ""; return formatter.format(new Date(calendar.getTimeInMillis())); } private boolean mustCreateAccountHolder(StudyGrantRequest sgr) { return mustCreateIndividual(sgr, ACCOUNT_HOLDER_TRACE_SUBKEY); } private boolean mustCreateSubject(StudyGrantRequest sgr) { return mustCreateIndividual(sgr, SUBJECT_TRACE_SUBKEY); } @Override public void checkConfiguration(ExternalServiceBean externalServiceBean) throws CvqConfigurationException { } @Override public void creditHomeFolderAccounts(Collection<PurchaseItem> purchaseItems, String cvqReference, String bankReference, Long homeFolderId, String externalHomeFolderId, String externalId, Date validationDate) throws CvqException { } @Override public Map<String, List<ExternalAccountItem>> getAccountsByHomeFolder(Long homeFolderId, String externalHomeFolderId, String externalId) throws CvqException { return null; } @Override public Map<Date, String> getConsumptionsByRequest(Request request, Date dateFrom, Date dateTo) throws CvqException { return null; } @Override public Map<Individual, Map<String, String>> getIndividualAccountsInformation(Long homeFolderId, String externalHomeFolderId, String externalId) throws CvqException { return null; } @Override public String getLabel() { return label; } @Override public String helloWorld() throws CvqException { return null; } @Override public void loadDepositAccountDetails(ExternalDepositAccountItem edai) throws CvqException { } @Override public void loadInvoiceDetails(ExternalInvoiceItem eii) throws CvqException { } public void setRequestService(IStudyGrantRequestService requestService) { this.requestService = requestService; } public void setDocumentService(IDocumentService documentService) { this.documentService = documentService; } public void setExternalService(IExternalService externalService) { this.externalService = externalService; } public void setRequestWorkflowService(IRequestWorkflowService requestWorkflowService) { this.requestWorkflowService = requestWorkflowService; } public void setTranslationService(ITranslationService translationService) { this.translationService = translationService; } }
false
true
private void submitRequest(StudyGrantRequest sgr, String psCodeTiers, boolean firstSending) { Map<String, Object> model = new HashMap<String, Object>(); String requestData = null; if (!firstSending) { try { requestData = edemandeClient.chargerDemande(psCodeTiers, sgr.getEdemandeId()).getChargerDemandeResponse().getReturn(); } catch (CvqException e) { e.printStackTrace(); addTrace(sgr.getId(), null, TraceStatusEnum.NOT_SENT, e.getMessage()); } } model.put("externalRequestId", buildExternalRequestId(sgr)); model.put("psCodeTiers", psCodeTiers); model.put("psCodeDemande", StringUtils.defaultIfEmpty(sgr.getEdemandeId(), "-1")); model.put("etatCourant", firstSending ? 2 : 1); model.put("firstName", sgr.getSubject().getIndividual().getFirstName()); model.put("lastName", sgr.getSubject().getIndividual().getLastName()); model.put("postalCode", sgr.getSubjectInformations().getSubjectAddress().getPostalCode()); model.put("city", sgr.getSubjectInformations().getSubjectAddress().getCity()); model.put("bankCode", sgr.getBankCode()); model.put("counterCode", sgr.getCounterCode()); model.put("accountNumber", sgr.getAccountNumber()); model.put("accountKey", sgr.getAccountKey()); model.put("firstRequest", sgr.getSubjectInformations().getSubjectFirstRequest()); model.put("creationDate", formatDate(sgr.getCreationDate())); model.put("taxHouseholdCityCode", sgr.getTaxHouseholdCityArray(0).getName()); model.put("taxHouseholdIncome", sgr.getTaxHouseholdIncome()); model.put("hasCROUSHelp", sgr.getHasCROUSHelp()); model.put("hasRegionalCouncilHelp", sgr.getHasRegionalCouncilHelp()); model.put("hasEuropeHelp", sgr.getHasEuropeHelp()); model.put("hasOtherHelp", sgr.getHasOtherHelp()); model.put("AlevelsDate", sgr.getALevelsInformations().getAlevelsDate()); model.put("AlevelsType", translationService.translate("sgr.property.alevels." + sgr.getALevelsInformations().getAlevels().toString().toLowerCase(), Locale.FRANCE)); model.put("currentStudiesType", translationService.translate("sgr.property.currentStudies." + sgr.getCurrentStudiesInformations().getCurrentStudies().toString(), Locale.FRANCE)); model.put("currentStudiesLevel", translationService.translate("sgr.property.currentStudiesLevel." + sgr.getCurrentStudiesInformations().getCurrentStudiesLevel().toString(), Locale.FRANCE)); model.put("sandwichCourses", sgr.getCurrentStudiesInformations().getSandwichCourses()); model.put("abroadInternship", sgr.getCurrentStudiesInformations().getAbroadInternship()); model.put("abroadInternshipStartDate", formatDate(sgr.getCurrentStudiesInformations().getAbroadInternshipStartDate())); model.put("abroadInternshipEndDate", formatDate(sgr.getCurrentStudiesInformations().getAbroadInternshipEndDate())); model.put("currentSchoolName", StringUtils.defaultIfEmpty(sgr.getCurrentSchool().getCurrentSchoolNamePrecision(), sgr.getCurrentSchool().getCurrentSchoolNameArray(0).getName())); model.put("currentSchoolPostalCode", StringUtils.defaultString(sgr.getCurrentSchool().getCurrentSchoolPostalCode())); model.put("currentSchoolCity", StringUtils.defaultString(sgr.getCurrentSchool().getCurrentSchoolCity())); model.put("currentSchoolCountry", sgr.getCurrentSchool().getCurrentSchoolCountry() != null ? sgr.getCurrentSchool().getCurrentSchoolCountry() : ""); model.put("abroadInternshipSchoolName", sgr.getCurrentStudiesInformations().getAbroadInternship() ? sgr.getCurrentStudiesInformations().getAbroadInternshipSchoolName() : ""); model.put("abroadInternshipSchoolCountry", sgr.getCurrentStudiesInformations().getAbroadInternship() ? sgr.getCurrentStudiesInformations().getAbroadInternshipSchoolCountry() : ""); model.put("distance", translationService.translate("sgr.property.distance." + sgr.getDistance().toString(), Locale.FRANCE)); List<Map<String, Object>> documents = new ArrayList<Map<String, Object>>(); model.put("documents", documents); try { if (false) for (RequestDocument requestDoc : requestService.getAssociatedDocuments(sgr.getId())) { Document document = documentService.getById(requestDoc.getDocumentId()); Map<String, Object> doc = new HashMap<String, Object>(); documents.add(doc); List<Map<String, String>> parts = new ArrayList<Map<String, String>>(); doc.put("parts", parts); int i = 1; for (DocumentBinary documentBinary : document.getDatas()) { Map<String, String> part = new HashMap<String, String>(); parts.add(part); String filename = org.springframework.util.StringUtils.arrayToDelimitedString( new String[] { "CapDemat", document.getDocumentType().getName(), String.valueOf(sgr.getId()), String.valueOf(i++) }, "-"); part.put("filename", filename); try { part.put("remotePath", uploader.upload(filename, documentBinary.getData())); } catch (Exception e) { //TODO } } } model.put("msStatut", firstSending ? "" : getRequestStatus(sgr, psCodeTiers)); model.put("millesime", firstSending ? "" : parseData(requestData, "//donneesDemande/Demande/miMillesime")); model.put("msCodext", firstSending ? "" : parseData(requestData, "//donneesDemande/Demande/msCodext")); model.put("requestTypeCode", parseData(edemandeClient.chargerTypeDemande(null).getChargerTypeDemandeResponse().getReturn(), "//typeDemande/code")); model.put("address", parseAddress((String)model.get("psCodeTiers"))); EnregistrerValiderFormulaireResponseDocument enregistrerValiderFormulaireResponseDocument = edemandeClient.enregistrerValiderFormulaire(model); if (!"0".equals(parseData(enregistrerValiderFormulaireResponseDocument.getEnregistrerValiderFormulaireResponse().getReturn(), "//Retour/codeRetour"))) { addTrace(sgr.getId(), null, TraceStatusEnum.ERROR, parseData(enregistrerValiderFormulaireResponseDocument.getEnregistrerValiderFormulaireResponse().getReturn(), "//Retour/messageRetour")); } else { addTrace(sgr.getId(), null, TraceStatusEnum.SENT, "Demande transmise"); } } catch (CvqException e) { e.printStackTrace(); addTrace(sgr.getId(), null, TraceStatusEnum.NOT_SENT, e.getMessage()); } }
private void submitRequest(StudyGrantRequest sgr, String psCodeTiers, boolean firstSending) { Map<String, Object> model = new HashMap<String, Object>(); String requestData = null; if (!firstSending) { try { requestData = edemandeClient.chargerDemande(psCodeTiers, sgr.getEdemandeId()).getChargerDemandeResponse().getReturn(); } catch (CvqException e) { e.printStackTrace(); addTrace(sgr.getId(), null, TraceStatusEnum.NOT_SENT, e.getMessage()); } } model.put("externalRequestId", buildExternalRequestId(sgr)); model.put("psCodeTiers", psCodeTiers); model.put("psCodeDemande", StringUtils.defaultIfEmpty(sgr.getEdemandeId(), "-1")); model.put("etatCourant", firstSending ? 2 : 1); model.put("firstName", sgr.getSubject().getIndividual().getFirstName()); model.put("lastName", sgr.getSubject().getIndividual().getLastName()); model.put("postalCode", sgr.getSubjectInformations().getSubjectAddress().getPostalCode()); model.put("city", sgr.getSubjectInformations().getSubjectAddress().getCity()); model.put("bankCode", sgr.getBankCode()); model.put("counterCode", sgr.getCounterCode()); model.put("accountNumber", sgr.getAccountNumber()); model.put("accountKey", sgr.getAccountKey()); model.put("firstRequest", sgr.getSubjectInformations().getSubjectFirstRequest()); model.put("creationDate", formatDate(sgr.getCreationDate())); model.put("taxHouseholdCityCode", sgr.getTaxHouseholdCityArray(0).getName()); model.put("taxHouseholdIncome", sgr.getTaxHouseholdIncome()); model.put("hasCROUSHelp", sgr.getHasCROUSHelp()); model.put("hasRegionalCouncilHelp", sgr.getHasRegionalCouncilHelp()); model.put("hasEuropeHelp", sgr.getHasEuropeHelp()); model.put("hasOtherHelp", sgr.getHasOtherHelp()); model.put("AlevelsDate", sgr.getALevelsInformations().getAlevelsDate()); model.put("AlevelsType", translationService.translate("sgr.property.alevels." + sgr.getALevelsInformations().getAlevels().toString().toLowerCase(), Locale.FRANCE)); model.put("currentStudiesType", StringUtils.defaultIfEmpty(sgr.getCurrentStudiesInformations().getOtherStudiesLabel(), translationService.translate("sgr.property.currentStudies." + sgr.getCurrentStudiesInformations().getCurrentStudies().toString(), Locale.FRANCE))); model.put("currentStudiesLevel", translationService.translate("sgr.property.currentStudiesLevel." + sgr.getCurrentStudiesInformations().getCurrentStudiesLevel().toString(), Locale.FRANCE)); model.put("sandwichCourses", sgr.getCurrentStudiesInformations().getSandwichCourses()); model.put("abroadInternship", sgr.getCurrentStudiesInformations().getAbroadInternship()); model.put("abroadInternshipStartDate", formatDate(sgr.getCurrentStudiesInformations().getAbroadInternshipStartDate())); model.put("abroadInternshipEndDate", formatDate(sgr.getCurrentStudiesInformations().getAbroadInternshipEndDate())); model.put("currentSchoolName", StringUtils.defaultIfEmpty(sgr.getCurrentSchool().getCurrentSchoolNamePrecision(), sgr.getCurrentSchool().getCurrentSchoolNameArray(0).getName())); model.put("currentSchoolPostalCode", StringUtils.defaultString(sgr.getCurrentSchool().getCurrentSchoolPostalCode())); model.put("currentSchoolCity", StringUtils.defaultString(sgr.getCurrentSchool().getCurrentSchoolCity())); model.put("currentSchoolCountry", sgr.getCurrentSchool().getCurrentSchoolCountry() != null ? translationService.translate("sgr.property.currentSchoolCountry." + sgr.getCurrentSchool().getCurrentSchoolCountry()) : ""); model.put("abroadInternshipSchoolName", sgr.getCurrentStudiesInformations().getAbroadInternship() ? sgr.getCurrentStudiesInformations().getAbroadInternshipSchoolName() : ""); model.put("abroadInternshipSchoolCountry", sgr.getCurrentStudiesInformations().getAbroadInternship() ? translationService.translate("sgr.property.abroadInternshipSchoolCountry." + sgr.getCurrentStudiesInformations().getAbroadInternshipSchoolCountry()) : ""); model.put("distance", translationService.translate("sgr.property.distance." + sgr.getDistance().toString(), Locale.FRANCE)); List<Map<String, Object>> documents = new ArrayList<Map<String, Object>>(); model.put("documents", documents); try { if (false) for (RequestDocument requestDoc : requestService.getAssociatedDocuments(sgr.getId())) { Document document = documentService.getById(requestDoc.getDocumentId()); Map<String, Object> doc = new HashMap<String, Object>(); documents.add(doc); List<Map<String, String>> parts = new ArrayList<Map<String, String>>(); doc.put("parts", parts); int i = 1; for (DocumentBinary documentBinary : document.getDatas()) { Map<String, String> part = new HashMap<String, String>(); parts.add(part); String filename = org.springframework.util.StringUtils.arrayToDelimitedString( new String[] { "CapDemat", document.getDocumentType().getName(), String.valueOf(sgr.getId()), String.valueOf(i++) }, "-"); part.put("filename", filename); try { part.put("remotePath", uploader.upload(filename, documentBinary.getData())); } catch (Exception e) { //TODO } } } model.put("msStatut", firstSending ? "" : getRequestStatus(sgr, psCodeTiers)); model.put("millesime", firstSending ? "" : parseData(requestData, "//donneesDemande/Demande/miMillesime")); model.put("msCodext", firstSending ? "" : parseData(requestData, "//donneesDemande/Demande/msCodext")); model.put("requestTypeCode", parseData(edemandeClient.chargerTypeDemande(null).getChargerTypeDemandeResponse().getReturn(), "//typeDemande/code")); model.put("address", parseAddress((String)model.get("psCodeTiers"))); EnregistrerValiderFormulaireResponseDocument enregistrerValiderFormulaireResponseDocument = edemandeClient.enregistrerValiderFormulaire(model); if (!"0".equals(parseData(enregistrerValiderFormulaireResponseDocument.getEnregistrerValiderFormulaireResponse().getReturn(), "//Retour/codeRetour"))) { addTrace(sgr.getId(), null, TraceStatusEnum.ERROR, parseData(enregistrerValiderFormulaireResponseDocument.getEnregistrerValiderFormulaireResponse().getReturn(), "//Retour/messageRetour")); } else { addTrace(sgr.getId(), null, TraceStatusEnum.SENT, "Demande transmise"); } } catch (CvqException e) { e.printStackTrace(); addTrace(sgr.getId(), null, TraceStatusEnum.NOT_SENT, e.getMessage()); } }
diff --git a/src/org/openstreetmap/josm/actions/PasteAction.java b/src/org/openstreetmap/josm/actions/PasteAction.java index 64ae826f..4e6cbd64 100644 --- a/src/org/openstreetmap/josm/actions/PasteAction.java +++ b/src/org/openstreetmap/josm/actions/PasteAction.java @@ -1,114 +1,118 @@ // License: GPL. Copyright 2007 by Immanuel Scholz and others // Author: David Earl package org.openstreetmap.josm.actions; import static org.openstreetmap.josm.tools.I18n.tr; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.ListIterator; import java.util.Map; import org.openstreetmap.josm.Main; import org.openstreetmap.josm.command.AddPrimitivesCommand; import org.openstreetmap.josm.data.coor.EastNorth; import org.openstreetmap.josm.data.osm.NodeData; import org.openstreetmap.josm.data.osm.PrimitiveData; import org.openstreetmap.josm.data.osm.PrimitiveDeepCopy; import org.openstreetmap.josm.data.osm.RelationData; import org.openstreetmap.josm.data.osm.RelationMemberData; import org.openstreetmap.josm.data.osm.WayData; import org.openstreetmap.josm.gui.layer.Layer; import org.openstreetmap.josm.tools.Shortcut; public final class PasteAction extends JosmAction { public PasteAction() { super(tr("Paste"), "paste", tr("Paste contents of paste buffer."), Shortcut.registerShortcut("system:paste", tr("Edit: {0}", tr("Paste")), KeyEvent.VK_V, Shortcut.GROUP_MENU), true); } public void actionPerformed(ActionEvent e) { if (!isEnabled()) return; pasteData(Main.pasteBuffer, Main.pasteSource, e); } public void pasteData(PrimitiveDeepCopy pasteBuffer, Layer source, ActionEvent e) { /* Find the middle of the pasteBuffer area */ double maxEast = -1E100, minEast = 1E100, maxNorth = -1E100, minNorth = 1E100; for (PrimitiveData data : pasteBuffer.getAll()) { if (data instanceof NodeData) { NodeData n = (NodeData)data; double east = n.getEastNorth().east(); double north = n.getEastNorth().north(); if (east > maxEast) { maxEast = east; } if (east < minEast) { minEast = east; } if (north > maxNorth) { maxNorth = north; } if (north < minNorth) { minNorth = north; } } } EastNorth mPosition; if((e.getModifiers() & ActionEvent.CTRL_MASK) ==0){ /* adjust the coordinates to the middle of the visible map area */ mPosition = Main.map.mapView.getCenter(); } else { - mPosition = Main.map.mapView.getEastNorth(Main.map.mapView.lastMEvent.getX(), Main.map.mapView.lastMEvent.getY()); + if (Main.map.mapView.lastMEvent != null) { + mPosition = Main.map.mapView.getEastNorth(Main.map.mapView.lastMEvent.getX(), Main.map.mapView.lastMEvent.getY()); + } else { + mPosition = Main.map.mapView.getCenter(); + } } double offsetEast = mPosition.east() - (maxEast + minEast)/2.0; double offsetNorth = mPosition.north() - (maxNorth + minNorth)/2.0; // Make a copy of pasteBuffer and map from old id to copied data id List<PrimitiveData> bufferCopy = new ArrayList<PrimitiveData>(); Map<Long, Long> newIds = new HashMap<Long, Long>(); for (PrimitiveData data:pasteBuffer.getAll()) { PrimitiveData copy = data.makeCopy(); copy.clearOsmId(); newIds.put(data.getId(), copy.getId()); bufferCopy.add(copy); } // Update references in copied buffer for (PrimitiveData data:bufferCopy) { if (data instanceof NodeData) { NodeData nodeData = (NodeData)data; if (Main.map.mapView.getEditLayer() == source) { nodeData.setEastNorth(nodeData.getEastNorth().add(offsetEast, offsetNorth)); } } else if (data instanceof WayData) { ListIterator<Long> it = ((WayData)data).getNodes().listIterator(); while (it.hasNext()) { it.set(newIds.get(it.next())); } } else if (data instanceof RelationData) { ListIterator<RelationMemberData> it = ((RelationData)data).getMembers().listIterator(); while (it.hasNext()) { RelationMemberData member = it.next(); it.set(new RelationMemberData(member.getRole(), member.getMemberType(), newIds.get(member.getMemberId()))); } } } /* Now execute the commands to add the duplicated contents of the paste buffer to the map */ Main.main.undoRedo.add(new AddPrimitivesCommand(bufferCopy)); //getCurrentDataSet().setSelected(osms); Main.map.mapView.repaint(); } @Override protected void updateEnabledState() { if (getCurrentDataSet() == null || Main.pasteBuffer == null) { setEnabled(false); return; } setEnabled(!Main.pasteBuffer.isEmpty()); } }
true
true
public void pasteData(PrimitiveDeepCopy pasteBuffer, Layer source, ActionEvent e) { /* Find the middle of the pasteBuffer area */ double maxEast = -1E100, minEast = 1E100, maxNorth = -1E100, minNorth = 1E100; for (PrimitiveData data : pasteBuffer.getAll()) { if (data instanceof NodeData) { NodeData n = (NodeData)data; double east = n.getEastNorth().east(); double north = n.getEastNorth().north(); if (east > maxEast) { maxEast = east; } if (east < minEast) { minEast = east; } if (north > maxNorth) { maxNorth = north; } if (north < minNorth) { minNorth = north; } } } EastNorth mPosition; if((e.getModifiers() & ActionEvent.CTRL_MASK) ==0){ /* adjust the coordinates to the middle of the visible map area */ mPosition = Main.map.mapView.getCenter(); } else { mPosition = Main.map.mapView.getEastNorth(Main.map.mapView.lastMEvent.getX(), Main.map.mapView.lastMEvent.getY()); } double offsetEast = mPosition.east() - (maxEast + minEast)/2.0; double offsetNorth = mPosition.north() - (maxNorth + minNorth)/2.0; // Make a copy of pasteBuffer and map from old id to copied data id List<PrimitiveData> bufferCopy = new ArrayList<PrimitiveData>(); Map<Long, Long> newIds = new HashMap<Long, Long>(); for (PrimitiveData data:pasteBuffer.getAll()) { PrimitiveData copy = data.makeCopy(); copy.clearOsmId(); newIds.put(data.getId(), copy.getId()); bufferCopy.add(copy); } // Update references in copied buffer for (PrimitiveData data:bufferCopy) { if (data instanceof NodeData) { NodeData nodeData = (NodeData)data; if (Main.map.mapView.getEditLayer() == source) { nodeData.setEastNorth(nodeData.getEastNorth().add(offsetEast, offsetNorth)); } } else if (data instanceof WayData) { ListIterator<Long> it = ((WayData)data).getNodes().listIterator(); while (it.hasNext()) { it.set(newIds.get(it.next())); } } else if (data instanceof RelationData) { ListIterator<RelationMemberData> it = ((RelationData)data).getMembers().listIterator(); while (it.hasNext()) { RelationMemberData member = it.next(); it.set(new RelationMemberData(member.getRole(), member.getMemberType(), newIds.get(member.getMemberId()))); } } } /* Now execute the commands to add the duplicated contents of the paste buffer to the map */ Main.main.undoRedo.add(new AddPrimitivesCommand(bufferCopy)); //getCurrentDataSet().setSelected(osms); Main.map.mapView.repaint(); }
public void pasteData(PrimitiveDeepCopy pasteBuffer, Layer source, ActionEvent e) { /* Find the middle of the pasteBuffer area */ double maxEast = -1E100, minEast = 1E100, maxNorth = -1E100, minNorth = 1E100; for (PrimitiveData data : pasteBuffer.getAll()) { if (data instanceof NodeData) { NodeData n = (NodeData)data; double east = n.getEastNorth().east(); double north = n.getEastNorth().north(); if (east > maxEast) { maxEast = east; } if (east < minEast) { minEast = east; } if (north > maxNorth) { maxNorth = north; } if (north < minNorth) { minNorth = north; } } } EastNorth mPosition; if((e.getModifiers() & ActionEvent.CTRL_MASK) ==0){ /* adjust the coordinates to the middle of the visible map area */ mPosition = Main.map.mapView.getCenter(); } else { if (Main.map.mapView.lastMEvent != null) { mPosition = Main.map.mapView.getEastNorth(Main.map.mapView.lastMEvent.getX(), Main.map.mapView.lastMEvent.getY()); } else { mPosition = Main.map.mapView.getCenter(); } } double offsetEast = mPosition.east() - (maxEast + minEast)/2.0; double offsetNorth = mPosition.north() - (maxNorth + minNorth)/2.0; // Make a copy of pasteBuffer and map from old id to copied data id List<PrimitiveData> bufferCopy = new ArrayList<PrimitiveData>(); Map<Long, Long> newIds = new HashMap<Long, Long>(); for (PrimitiveData data:pasteBuffer.getAll()) { PrimitiveData copy = data.makeCopy(); copy.clearOsmId(); newIds.put(data.getId(), copy.getId()); bufferCopy.add(copy); } // Update references in copied buffer for (PrimitiveData data:bufferCopy) { if (data instanceof NodeData) { NodeData nodeData = (NodeData)data; if (Main.map.mapView.getEditLayer() == source) { nodeData.setEastNorth(nodeData.getEastNorth().add(offsetEast, offsetNorth)); } } else if (data instanceof WayData) { ListIterator<Long> it = ((WayData)data).getNodes().listIterator(); while (it.hasNext()) { it.set(newIds.get(it.next())); } } else if (data instanceof RelationData) { ListIterator<RelationMemberData> it = ((RelationData)data).getMembers().listIterator(); while (it.hasNext()) { RelationMemberData member = it.next(); it.set(new RelationMemberData(member.getRole(), member.getMemberType(), newIds.get(member.getMemberId()))); } } } /* Now execute the commands to add the duplicated contents of the paste buffer to the map */ Main.main.undoRedo.add(new AddPrimitivesCommand(bufferCopy)); //getCurrentDataSet().setSelected(osms); Main.map.mapView.repaint(); }
diff --git a/modules/quercus/src/com/caucho/quercus/lib/regexp/PregReplaceProxy.java b/modules/quercus/src/com/caucho/quercus/lib/regexp/PregReplaceProxy.java index 375b3912c..f40173f26 100644 --- a/modules/quercus/src/com/caucho/quercus/lib/regexp/PregReplaceProxy.java +++ b/modules/quercus/src/com/caucho/quercus/lib/regexp/PregReplaceProxy.java @@ -1,158 +1,161 @@ /* * Copyright (c) 1998-2009 Caucho Technology -- all rights reserved * * This file is part of Resin(R) Open Source * * Each copy or derived work must preserve the copyright notice and this * notice unmodified. * * Resin Open Source 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. * * Resin Open Source 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, or any warranty * of NON-INFRINGEMENT. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with Resin Open Source; if not, write to the * * Free Software Foundation, Inc. * 59 Temple Place, Suite 330 * Boston, MA 02111-1307 USA * * @author Nam Nguyen */ package com.caucho.quercus.lib.regexp; import com.caucho.quercus.env.Env; import com.caucho.quercus.env.StringValue; import com.caucho.quercus.env.Value; /** * XXX: experimental */ public class PregReplaceProxy { // 5 to start seeing respectable hit rates for mediawiki private final PregReplaceResult []_results = new PregReplaceResult[5]; private int _hits; private int _total; private boolean _isPassthru; private static final int MIN_HITS = 5; private static final int MAX_TOTAL = 20; public PregReplaceProxy() { } public Value preg_replace(Env env, Regexp []regexpList, Value replacement, Value subject, long limit, Value countRef) { + return null; + /* if (_isPassthru) { return RegexpModule.preg_replace(env, regexpList, replacement, subject, limit, countRef); } else if (_total >= MAX_TOTAL && _hits < MIN_HITS) { _isPassthru = true; for (int i = 0; i < _results.length; i++) { _results[i] = null; } return RegexpModule.preg_replace(env, regexpList, replacement, subject, limit, countRef); } for (int i = 0; i < regexpList.length; i++) { if (regexpList[i].isEval()) { if (_total < MAX_TOTAL) _total++; return RegexpModule.preg_replace(env, regexpList, replacement, subject, limit, countRef); } } for (int i = 0; i < _results.length; i++) { PregReplaceResult result = _results[i]; if (result == null) { Value val = RegexpModule.preg_replace(env, regexpList, replacement, subject, limit, countRef); if (val.isNull()) { if (_total < MAX_TOTAL) _total++; return val; } _results[i] = new PregReplaceResult(regexpList, replacement, subject, limit, countRef, val); return val; } else if (result.equals(regexpList, replacement, subject, limit)) { if (_total < MAX_TOTAL) { _total++; _hits++; } return result.get(countRef); } } if (_total < MAX_TOTAL) { _total++; } return RegexpModule.preg_replace(env, regexpList, replacement, subject, limit, countRef); + */ } static class PregReplaceResult { final Regexp []_regexpList; final Value _replacement; final Value _subject; final long _limit; final Value _count; final Value _result; PregReplaceResult(Regexp []regexpList, Value replacement, Value subject, long limit, Value countRef, Value result) { _regexpList = regexpList; _replacement = replacement; _subject = subject; _limit = limit; _count = countRef.toValue(); _result = result.copy(); } public boolean equals(Regexp []regexpList, Value replacement, Value subject, long limit) { return regexpList == _regexpList && limit == _limit && replacement.equals(_replacement) && subject.equals(_subject); } public Value get(Value countRef) { countRef.set(_count); return _result.copy(); } } }
false
true
public Value preg_replace(Env env, Regexp []regexpList, Value replacement, Value subject, long limit, Value countRef) { if (_isPassthru) { return RegexpModule.preg_replace(env, regexpList, replacement, subject, limit, countRef); } else if (_total >= MAX_TOTAL && _hits < MIN_HITS) { _isPassthru = true; for (int i = 0; i < _results.length; i++) { _results[i] = null; } return RegexpModule.preg_replace(env, regexpList, replacement, subject, limit, countRef); } for (int i = 0; i < regexpList.length; i++) { if (regexpList[i].isEval()) { if (_total < MAX_TOTAL) _total++; return RegexpModule.preg_replace(env, regexpList, replacement, subject, limit, countRef); } } for (int i = 0; i < _results.length; i++) { PregReplaceResult result = _results[i]; if (result == null) { Value val = RegexpModule.preg_replace(env, regexpList, replacement, subject, limit, countRef); if (val.isNull()) { if (_total < MAX_TOTAL) _total++; return val; } _results[i] = new PregReplaceResult(regexpList, replacement, subject, limit, countRef, val); return val; } else if (result.equals(regexpList, replacement, subject, limit)) { if (_total < MAX_TOTAL) { _total++; _hits++; } return result.get(countRef); } } if (_total < MAX_TOTAL) { _total++; } return RegexpModule.preg_replace(env, regexpList, replacement, subject, limit, countRef); }
public Value preg_replace(Env env, Regexp []regexpList, Value replacement, Value subject, long limit, Value countRef) { return null; /* if (_isPassthru) { return RegexpModule.preg_replace(env, regexpList, replacement, subject, limit, countRef); } else if (_total >= MAX_TOTAL && _hits < MIN_HITS) { _isPassthru = true; for (int i = 0; i < _results.length; i++) { _results[i] = null; } return RegexpModule.preg_replace(env, regexpList, replacement, subject, limit, countRef); } for (int i = 0; i < regexpList.length; i++) { if (regexpList[i].isEval()) { if (_total < MAX_TOTAL) _total++; return RegexpModule.preg_replace(env, regexpList, replacement, subject, limit, countRef); } } for (int i = 0; i < _results.length; i++) { PregReplaceResult result = _results[i]; if (result == null) { Value val = RegexpModule.preg_replace(env, regexpList, replacement, subject, limit, countRef); if (val.isNull()) { if (_total < MAX_TOTAL) _total++; return val; } _results[i] = new PregReplaceResult(regexpList, replacement, subject, limit, countRef, val); return val; } else if (result.equals(regexpList, replacement, subject, limit)) { if (_total < MAX_TOTAL) { _total++; _hits++; } return result.get(countRef); } } if (_total < MAX_TOTAL) { _total++; } return RegexpModule.preg_replace(env, regexpList, replacement, subject, limit, countRef); */ }
diff --git a/src/org/openstreetmap/josm/gui/dialogs/RelationListDialog.java b/src/org/openstreetmap/josm/gui/dialogs/RelationListDialog.java index f0111ddc..7d3bd5fe 100644 --- a/src/org/openstreetmap/josm/gui/dialogs/RelationListDialog.java +++ b/src/org/openstreetmap/josm/gui/dialogs/RelationListDialog.java @@ -1,156 +1,156 @@ package org.openstreetmap.josm.gui.dialogs; import static org.openstreetmap.josm.tools.I18n.tr; import static org.xnap.commons.i18n.I18n.marktr; import java.awt.BorderLayout; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.Collections; import javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.ListSelectionModel; import org.openstreetmap.josm.Main; import org.openstreetmap.josm.command.DeleteCommand; import org.openstreetmap.josm.data.osm.Relation; import org.openstreetmap.josm.gui.OsmPrimitivRenderer; import org.openstreetmap.josm.gui.layer.DataChangeListener; import org.openstreetmap.josm.gui.layer.Layer; import org.openstreetmap.josm.gui.layer.OsmDataLayer; import org.openstreetmap.josm.gui.layer.Layer.LayerChangeListener; import org.openstreetmap.josm.tools.GBC; import org.openstreetmap.josm.tools.ImageProvider; /** * A dialog showing all known relations, with buttons to add, edit, and * delete them. * * We don't have such dialogs for nodes, segments, and ways, becaus those * objects are visible on the map and can be selected there. Relations are not. * * @author Frederik Ramm <[email protected]> */ public class RelationListDialog extends ToggleDialog implements LayerChangeListener, DataChangeListener { /** * The selection's list data. */ private final DefaultListModel list = new DefaultListModel(); /** * The display list. */ private JList displaylist = new JList(list); public RelationListDialog() { super(tr("Relations"), "relationlist", tr("Open a list of all relations."), KeyEvent.VK_R, 150); displaylist.setCellRenderer(new OsmPrimitivRenderer()); displaylist.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); displaylist.addMouseListener(new MouseAdapter(){ @Override public void mouseClicked(MouseEvent e) { if (e.getClickCount() < 2) return; Relation toEdit = (Relation) displaylist.getSelectedValue(); if (toEdit != null) new RelationEditor(toEdit).setVisible(true); } }); add(new JScrollPane(displaylist), BorderLayout.CENTER); JPanel buttonPanel = new JPanel(new GridBagLayout()); buttonPanel.add(createButton(marktr("New"), "addrelation", tr("Create a new relation"), -1, new ActionListener() { public void actionPerformed(ActionEvent e) { // call relation editor with null argument to create new relation new RelationEditor(null).setVisible(true); } }), GBC.std()); buttonPanel.add(createButton(marktr("Select"), "select", tr("Select this relation"), -1, new ActionListener() { public void actionPerformed(ActionEvent e) { // replace selection with the relation from the list Main.ds.setSelected((Relation)displaylist.getSelectedValue()); } }), GBC.std()); buttonPanel.add(createButton(marktr("Edit"), "edit", tr( "Open an editor for the selected relation"), -1, new ActionListener() { public void actionPerformed(ActionEvent e) { Relation toEdit = (Relation) displaylist.getSelectedValue(); if (toEdit != null) new RelationEditor(toEdit).setVisible(true); } }), GBC.std()); - buttonPanel.add(createButton("", "delete", tr("Delete the selected relation"), -1, new ActionListener() { + buttonPanel.add(createButton(" ", "delete", tr("Delete the selected relation"), -1, new ActionListener() { public void actionPerformed(ActionEvent e) { Relation toDelete = (Relation) displaylist.getSelectedValue(); if (toDelete != null) { Main.main.undoRedo.add( new DeleteCommand(Collections.singleton(toDelete))); } } }), GBC.eol()); Layer.listeners.add(this); add(buttonPanel, BorderLayout.SOUTH); } private JButton createButton(String name, String imagename, String tooltip, int mnemonic, ActionListener actionListener) { JButton b = new JButton(tr(name), ImageProvider.get("dialogs", imagename)); b.setActionCommand(name); b.addActionListener(actionListener); b.setToolTipText(tooltip); if (mnemonic >= 0) b.setMnemonic(mnemonic); b.putClientProperty("help", "Dialog/Properties/"+name); return b; } @Override public void setVisible(boolean b) { super.setVisible(b); if (b) updateList(); } public void updateList() { list.setSize(Main.ds.relations.size()); int i = 0; for (Relation e : Main.ds.relations) { if (!e.deleted && !e.incomplete) list.setElementAt(e, i++); } list.setSize(i); } public void activeLayerChange(Layer a, Layer b) { if (a instanceof OsmDataLayer && b instanceof OsmDataLayer) { ((OsmDataLayer)a).listenerDataChanged.remove(this); ((OsmDataLayer)b).listenerDataChanged.add(this); updateList(); repaint(); } } public void layerRemoved(Layer a) { if (a instanceof OsmDataLayer) { ((OsmDataLayer)a).listenerDataChanged.remove(this); } } public void layerAdded(Layer a) { if (a instanceof OsmDataLayer) { ((OsmDataLayer)a).listenerDataChanged.add(this); } } public void dataChanged(OsmDataLayer l) { updateList(); repaint(); } }
true
true
public RelationListDialog() { super(tr("Relations"), "relationlist", tr("Open a list of all relations."), KeyEvent.VK_R, 150); displaylist.setCellRenderer(new OsmPrimitivRenderer()); displaylist.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); displaylist.addMouseListener(new MouseAdapter(){ @Override public void mouseClicked(MouseEvent e) { if (e.getClickCount() < 2) return; Relation toEdit = (Relation) displaylist.getSelectedValue(); if (toEdit != null) new RelationEditor(toEdit).setVisible(true); } }); add(new JScrollPane(displaylist), BorderLayout.CENTER); JPanel buttonPanel = new JPanel(new GridBagLayout()); buttonPanel.add(createButton(marktr("New"), "addrelation", tr("Create a new relation"), -1, new ActionListener() { public void actionPerformed(ActionEvent e) { // call relation editor with null argument to create new relation new RelationEditor(null).setVisible(true); } }), GBC.std()); buttonPanel.add(createButton(marktr("Select"), "select", tr("Select this relation"), -1, new ActionListener() { public void actionPerformed(ActionEvent e) { // replace selection with the relation from the list Main.ds.setSelected((Relation)displaylist.getSelectedValue()); } }), GBC.std()); buttonPanel.add(createButton(marktr("Edit"), "edit", tr( "Open an editor for the selected relation"), -1, new ActionListener() { public void actionPerformed(ActionEvent e) { Relation toEdit = (Relation) displaylist.getSelectedValue(); if (toEdit != null) new RelationEditor(toEdit).setVisible(true); } }), GBC.std()); buttonPanel.add(createButton("", "delete", tr("Delete the selected relation"), -1, new ActionListener() { public void actionPerformed(ActionEvent e) { Relation toDelete = (Relation) displaylist.getSelectedValue(); if (toDelete != null) { Main.main.undoRedo.add( new DeleteCommand(Collections.singleton(toDelete))); } } }), GBC.eol()); Layer.listeners.add(this); add(buttonPanel, BorderLayout.SOUTH); }
public RelationListDialog() { super(tr("Relations"), "relationlist", tr("Open a list of all relations."), KeyEvent.VK_R, 150); displaylist.setCellRenderer(new OsmPrimitivRenderer()); displaylist.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); displaylist.addMouseListener(new MouseAdapter(){ @Override public void mouseClicked(MouseEvent e) { if (e.getClickCount() < 2) return; Relation toEdit = (Relation) displaylist.getSelectedValue(); if (toEdit != null) new RelationEditor(toEdit).setVisible(true); } }); add(new JScrollPane(displaylist), BorderLayout.CENTER); JPanel buttonPanel = new JPanel(new GridBagLayout()); buttonPanel.add(createButton(marktr("New"), "addrelation", tr("Create a new relation"), -1, new ActionListener() { public void actionPerformed(ActionEvent e) { // call relation editor with null argument to create new relation new RelationEditor(null).setVisible(true); } }), GBC.std()); buttonPanel.add(createButton(marktr("Select"), "select", tr("Select this relation"), -1, new ActionListener() { public void actionPerformed(ActionEvent e) { // replace selection with the relation from the list Main.ds.setSelected((Relation)displaylist.getSelectedValue()); } }), GBC.std()); buttonPanel.add(createButton(marktr("Edit"), "edit", tr( "Open an editor for the selected relation"), -1, new ActionListener() { public void actionPerformed(ActionEvent e) { Relation toEdit = (Relation) displaylist.getSelectedValue(); if (toEdit != null) new RelationEditor(toEdit).setVisible(true); } }), GBC.std()); buttonPanel.add(createButton(" ", "delete", tr("Delete the selected relation"), -1, new ActionListener() { public void actionPerformed(ActionEvent e) { Relation toDelete = (Relation) displaylist.getSelectedValue(); if (toDelete != null) { Main.main.undoRedo.add( new DeleteCommand(Collections.singleton(toDelete))); } } }), GBC.eol()); Layer.listeners.add(this); add(buttonPanel, BorderLayout.SOUTH); }
diff --git a/src/org/ktln2/android/callstat/StatisticsMap.java b/src/org/ktln2/android/callstat/StatisticsMap.java index 792e417..7523b42 100644 --- a/src/org/ktln2/android/callstat/StatisticsMap.java +++ b/src/org/ktln2/android/callstat/StatisticsMap.java @@ -1,142 +1,142 @@ package org.ktln2.android.callstat; import android.content.Context; import java.util.TreeMap; import java.util.TreeSet; import java.util.Comparator; import java.util.ArrayList; /* * Container for statistical data management. * * It's pratically a TreeMap having as key the number and as values an array * containing the duration for the calls of this contact. * * The array is actually a TreeSet so to maintain internally an ordering * and be able to know which is the shortest/longest call for each contact. */ class StatisticsMap extends TreeMap<String, CallStat> { private static final int CALL_STAT_MAP_TYPE_MIN = 0; private static final int CALL_STAT_MAP_TYPE_MAX = 1; // these will contain the duration related values private long mMin = 0, mMax = 0, mTotal = 0, mCount = 0; /* * Return the data divided using some bins. * * http://stackoverflow.com/questions/10786465/how-to-generate-bins-for-histogram-using-apache-math-3-0-in-java */ public int[] calcHistogram(Long[] values, int numBins) { final int[] result = new int[numBins]; final double binSize = (mMax - mMin)/numBins; for (double d : values) { int bin = (int) ((d - mMin) / binSize); if (bin < 0) { /* this data is smaller than min */ } else if (bin >= numBins) { /* this data point is bigger than max */ } else { result[bin] += 1; } } return result; } /* * This returns the bins used to build up the histogram. * * For now we use a resolution of 10 seconds. */ public int[] getBinsForDurations(int delta) { int number_of_bins = ((int)mMax)/delta; return calcHistogram(getAllDurations().toArray(new Long[1]), number_of_bins); } /* * Return the complete list of all the durations. */ public ArrayList<Long> getAllDurations() { ArrayList<Long> entries = new ArrayList<Long>(); for (Entry<String, CallStat> entry: entrySet()) { entries.addAll(entry.getValue().getAllDurations()); } return entries; } public void put(String key, Long value, Context context) { // update values mMin = value < mMin ? value : mMin; mMax = value > mMax ? value : mMax; mTotal += value; mCount++; CallStat set = get(key); if (set == null) { set = new CallStat(key, context); } set.add(value); // TODO: it's mandatory to update it? put(key, set); } public long getMinDuration() { return mMin; } public long getMaxDuration() { return mMax; } public long getTotalDuration() { return mTotal; } public int getTotalContacts() { return size(); } public long getTotalCalls() { return mCount; } /* * General purpouse function aimed to order the CallStat objects * with respect of different parameter. */ protected CallStat[] getCallStatOrderedBy(int type) { TreeSet<CallStat> values; Comparator comparator; switch (type) { case CALL_STAT_MAP_TYPE_MIN: comparator = new Comparator<CallStat>() { public int compare(CallStat lhs, CallStat rhs) { return (int)(lhs.getMinDuration() - rhs.getMinDuration()); } }; break; case CALL_STAT_MAP_TYPE_MAX: default: comparator = new Comparator<CallStat>() { public int compare(CallStat lhs, CallStat rhs) { - return (int)(lhs.getMaxDuration() - rhs.getMaxDuration()); + return (int)(-lhs.getMaxDuration() + rhs.getMaxDuration()); } }; break; } values = new TreeSet<CallStat>(comparator); values.addAll(values()); return values.toArray(new CallStat[1]); } public CallStat[] getCallStatOrderedByMaxDuration() { return getCallStatOrderedBy(CALL_STAT_MAP_TYPE_MAX); } }
true
true
protected CallStat[] getCallStatOrderedBy(int type) { TreeSet<CallStat> values; Comparator comparator; switch (type) { case CALL_STAT_MAP_TYPE_MIN: comparator = new Comparator<CallStat>() { public int compare(CallStat lhs, CallStat rhs) { return (int)(lhs.getMinDuration() - rhs.getMinDuration()); } }; break; case CALL_STAT_MAP_TYPE_MAX: default: comparator = new Comparator<CallStat>() { public int compare(CallStat lhs, CallStat rhs) { return (int)(lhs.getMaxDuration() - rhs.getMaxDuration()); } }; break; } values = new TreeSet<CallStat>(comparator); values.addAll(values()); return values.toArray(new CallStat[1]); }
protected CallStat[] getCallStatOrderedBy(int type) { TreeSet<CallStat> values; Comparator comparator; switch (type) { case CALL_STAT_MAP_TYPE_MIN: comparator = new Comparator<CallStat>() { public int compare(CallStat lhs, CallStat rhs) { return (int)(lhs.getMinDuration() - rhs.getMinDuration()); } }; break; case CALL_STAT_MAP_TYPE_MAX: default: comparator = new Comparator<CallStat>() { public int compare(CallStat lhs, CallStat rhs) { return (int)(-lhs.getMaxDuration() + rhs.getMaxDuration()); } }; break; } values = new TreeSet<CallStat>(comparator); values.addAll(values()); return values.toArray(new CallStat[1]); }
diff --git a/src/edu/ua/moundville/ListItems.java b/src/edu/ua/moundville/ListItems.java index 9be5a4f..2d87c16 100644 --- a/src/edu/ua/moundville/ListItems.java +++ b/src/edu/ua/moundville/ListItems.java @@ -1,171 +1,171 @@ package edu.ua.moundville; import java.util.ArrayList; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.ListActivity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import edu.ua.moundville.DBHandler.DBResult; public class ListItems extends ListActivity implements DBResult { private static final String TAG = "ListItems"; protected String selectQuery; protected ArrayList<NameValuePair> queryArgs = new ArrayList<NameValuePair>(); protected final ArrayList<String> listItems = new ArrayList<String>(); protected final ArrayList<String> listLinks = new ArrayList<String>(); protected static DBHandler db = new DBHandler(); protected int DBCase = -1; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setCase(); setupQuery(); db.sendQuery(this, queryArgs); getListView().setOnItemClickListener(new OnItemClickListener() { Intent launchActivity; public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (2 <= DBCase && DBCase <= 5) { launchActivity = new Intent(getApplicationContext(), ArtifactArticle.class); launchActivity.putExtra("artifact", listLinks.get(position)); } else { launchActivity = new Intent(getApplicationContext(), SiteArticle.class); launchActivity.putExtra("site", listLinks.get(position)); } startActivity(launchActivity); } }); } private void setCase() { DBCase = getIntent().getExtras().getInt("case"); if (DBCase <= 0 ) { /* TODO error */ } switch(DBCase) { case 2: setTitle("Style"); break; case 3: setTitle("Artifacts"); break; case 4: setTitle("Category"); break; case 5: setTitle("Time Period"); break; case 8: setTitle("All Sites"); break; default: setTitle("List"); break; } } private void setupQuery() { queryArgs.add(new BasicNameValuePair("case", String.valueOf(DBCase))); switch (DBCase) { case 2: String styleName = getIntent().getExtras().getString("style"); queryArgs.add(new BasicNameValuePair("style", styleName)); break; case 3: String siteID = getIntent().getExtras().getString("site"); queryArgs.add(new BasicNameValuePair("site", siteID)); Log.d(TAG, "siteID = " + siteID); break; case 4: String catName = getIntent().getExtras().getString("cat"); queryArgs.add(new BasicNameValuePair("cat", catName)); break; case 5: String timepd = getIntent().getExtras().getString("timepd"); queryArgs.add(new BasicNameValuePair("timepd", timepd)); break; case 8: break; // No case matched /* TODO return error code or display error toast before returning */ /* not working */ default: finish(); } } protected void launchArticle() { } public void receiveResult(JSONArray jArray) { if (jArray == null) { listItems.add("I failed :("); } else { Log.d(TAG, jArray.toString()); for (int i=0; i<jArray.length(); i++) { JSONObject obj = null; try { obj = (JSONObject) jArray.get(i); switch (DBCase) { case 2: listItems.add(obj.getString("ak_Tag_Name")); - listLinks.add(obj.getString("pk_Tag_TagID")); + listLinks.add(obj.getString("pk_Tag_Name")); break; case 3: listItems.add(obj.getString("ak_Art_Title")); listLinks.add(obj.getString("pk_Art_ArtID")); break; case 4: listItems.add(obj.getString("ak_Cat_Name")); - listLinks.add(obj.getString("pk_Cat_CatID")); + listLinks.add(obj.getString("pk_Cat_Name")); break; case 5: - listItems.add(obj.getString("ak_Time_TimeID")); + listItems.add(obj.getString("ak_Time_TimePeriod")); listLinks.add(obj.getString("pk_Time_TimePeriod")); break; case 8: listItems.add(obj.getString("ak_Site_SiteName")); listLinks.add(obj.getString("pk_Site_SiteID")); break; // No case matched /* TODO return error code or display error toast before returning */ default: Log.e(TAG, "Failed to parse return json"); finish(); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } prepareList(); } private void prepareList() { setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listItems)); } }
false
true
public void receiveResult(JSONArray jArray) { if (jArray == null) { listItems.add("I failed :("); } else { Log.d(TAG, jArray.toString()); for (int i=0; i<jArray.length(); i++) { JSONObject obj = null; try { obj = (JSONObject) jArray.get(i); switch (DBCase) { case 2: listItems.add(obj.getString("ak_Tag_Name")); listLinks.add(obj.getString("pk_Tag_TagID")); break; case 3: listItems.add(obj.getString("ak_Art_Title")); listLinks.add(obj.getString("pk_Art_ArtID")); break; case 4: listItems.add(obj.getString("ak_Cat_Name")); listLinks.add(obj.getString("pk_Cat_CatID")); break; case 5: listItems.add(obj.getString("ak_Time_TimeID")); listLinks.add(obj.getString("pk_Time_TimePeriod")); break; case 8: listItems.add(obj.getString("ak_Site_SiteName")); listLinks.add(obj.getString("pk_Site_SiteID")); break; // No case matched /* TODO return error code or display error toast before returning */ default: Log.e(TAG, "Failed to parse return json"); finish(); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } prepareList(); }
public void receiveResult(JSONArray jArray) { if (jArray == null) { listItems.add("I failed :("); } else { Log.d(TAG, jArray.toString()); for (int i=0; i<jArray.length(); i++) { JSONObject obj = null; try { obj = (JSONObject) jArray.get(i); switch (DBCase) { case 2: listItems.add(obj.getString("ak_Tag_Name")); listLinks.add(obj.getString("pk_Tag_Name")); break; case 3: listItems.add(obj.getString("ak_Art_Title")); listLinks.add(obj.getString("pk_Art_ArtID")); break; case 4: listItems.add(obj.getString("ak_Cat_Name")); listLinks.add(obj.getString("pk_Cat_Name")); break; case 5: listItems.add(obj.getString("ak_Time_TimePeriod")); listLinks.add(obj.getString("pk_Time_TimePeriod")); break; case 8: listItems.add(obj.getString("ak_Site_SiteName")); listLinks.add(obj.getString("pk_Site_SiteID")); break; // No case matched /* TODO return error code or display error toast before returning */ default: Log.e(TAG, "Failed to parse return json"); finish(); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } prepareList(); }
diff --git a/jython/src/org/python/core/PyTraceback.java b/jython/src/org/python/core/PyTraceback.java index 80983067..6943fbd3 100644 --- a/jython/src/org/python/core/PyTraceback.java +++ b/jython/src/org/python/core/PyTraceback.java @@ -1,112 +1,112 @@ // Copyright (c) Corporation for National Research Initiatives package org.python.core; import org.python.core.util.RelativeFile; /** * A python traceback object. */ public class PyTraceback extends PyObject { public PyObject tb_next; public PyFrame tb_frame; public int tb_lineno; public PyTraceback(PyFrame frame) { tb_frame = frame; if (tb_frame != null) { tb_lineno = tb_frame.getline(); } tb_next = Py.None; } public PyTraceback(PyTraceback next) { tb_next = next; if (next != null) { tb_frame = next.tb_frame.f_back; tb_lineno = tb_frame.getline(); } } private String tracebackInfo() { if (tb_frame == null || tb_frame.f_code == null) { return String.format(" (no code object) at line %s\n", tb_lineno); } String line = null; if (tb_frame.f_code.co_filename != null) { line = getLine(tb_frame.f_code.co_filename, tb_lineno); } return String.format(" File \"%.500s\", line %d, in %.500s\n%s", tb_frame.f_code.co_filename, tb_lineno, tb_frame.f_code.co_name, line == null ? "" : " " + line); } /** * Return the specified line of code from filename. * * @param filename a filename String * @param lineno the line number * @return a String line or null */ private String getLine(String filename, int lineno) { RelativeFile file = new RelativeFile(filename); if (!file.isFile() || !file.canRead()) { // XXX: We should run through sys.path until the filename is found return null; } PyFile pyFile; try { pyFile = new PyFile(tb_frame.f_code.co_filename, "U", -1); } catch (PyException pye) { return null; } String line = null; int i = 0; try { for (i = 0; i < tb_lineno; i++) { line = pyFile.readline(); if (line.equals("")) { break; } } } catch (PyException pye) { // Proceed to closing the file } try { pyFile.close(); } catch (PyException pye) { // Continue, we may have the line } - if (tb_lineno > 0 && i == tb_lineno) { + if (line != null && i == tb_lineno) { i = 0; while (i < line.length()) { char c = line.charAt(i); if (c != ' ' && c != '\t' && c != '\014') { break; } i++; } line = line.substring(i); } return line; } public void dumpStack(StringBuffer buf) { buf.append(tracebackInfo()); if (tb_next != Py.None && tb_next != this) { ((PyTraceback)tb_next).dumpStack(buf); } else if (tb_next == this) { buf.append("circularity detected!"+this+tb_next); } } public String dumpStack() { StringBuffer buf = new StringBuffer(); buf.append("Traceback (most recent call last):\n"); dumpStack(buf); return buf.toString(); } }
true
true
private String getLine(String filename, int lineno) { RelativeFile file = new RelativeFile(filename); if (!file.isFile() || !file.canRead()) { // XXX: We should run through sys.path until the filename is found return null; } PyFile pyFile; try { pyFile = new PyFile(tb_frame.f_code.co_filename, "U", -1); } catch (PyException pye) { return null; } String line = null; int i = 0; try { for (i = 0; i < tb_lineno; i++) { line = pyFile.readline(); if (line.equals("")) { break; } } } catch (PyException pye) { // Proceed to closing the file } try { pyFile.close(); } catch (PyException pye) { // Continue, we may have the line } if (tb_lineno > 0 && i == tb_lineno) { i = 0; while (i < line.length()) { char c = line.charAt(i); if (c != ' ' && c != '\t' && c != '\014') { break; } i++; } line = line.substring(i); } return line; }
private String getLine(String filename, int lineno) { RelativeFile file = new RelativeFile(filename); if (!file.isFile() || !file.canRead()) { // XXX: We should run through sys.path until the filename is found return null; } PyFile pyFile; try { pyFile = new PyFile(tb_frame.f_code.co_filename, "U", -1); } catch (PyException pye) { return null; } String line = null; int i = 0; try { for (i = 0; i < tb_lineno; i++) { line = pyFile.readline(); if (line.equals("")) { break; } } } catch (PyException pye) { // Proceed to closing the file } try { pyFile.close(); } catch (PyException pye) { // Continue, we may have the line } if (line != null && i == tb_lineno) { i = 0; while (i < line.length()) { char c = line.charAt(i); if (c != ' ' && c != '\t' && c != '\014') { break; } i++; } line = line.substring(i); } return line; }
diff --git a/Wirtschaftsplanspiel/src/Client/Entities/Player.java b/Wirtschaftsplanspiel/src/Client/Entities/Player.java index 1028878..f6fa9db 100644 --- a/Wirtschaftsplanspiel/src/Client/Entities/Player.java +++ b/Wirtschaftsplanspiel/src/Client/Entities/Player.java @@ -1,98 +1,98 @@ package Client.Entities; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.TreeMap; import common.entities.CompanyResult; public class Player implements Comparable<Player> { private int id; private String name; private List<CompanyResult> resultList = new LinkedList<CompanyResult>(); private boolean insolvent; private boolean leftGame; public Player(int ID, String Name) { id = ID; name = Name; playerDict.put(id, this); } public int getID() { return id; } public String getName() { return name; } public void becameInsolvent() { insolvent = true; } public boolean isInsolvent() { return insolvent; } public void leaveGame() { leftGame = true; } public boolean hasLeftGame() { return leftGame; } //PlayerList private static TreeMap<Integer, Player> playerDict = new TreeMap<Integer, Player>(); public static List<Player> getPlayers() { List<Player> retList = new LinkedList<Player>(); retList.addAll(playerDict.values()); return retList; } public static Player getPlayer(Integer ID) { return playerDict.get(ID); } public static void removePlayer(Integer ID) { playerDict.remove(ID); } public CompanyResult getCompanyResult(int period) { return resultList.get(period); } public void addCompanyResult(CompanyResult result) { this.resultList.add(result); } private static boolean isHost; public static void setHost(boolean value){ isHost = value; } public static boolean isHost(){ return isHost; } @Override public int compareTo(Player arg0) { double res1 = 0; for(Iterator<CompanyResult> resit = resultList.iterator(); resit.hasNext();){ res1 += resit.next().profit; } double res2 = 0; for(Iterator<CompanyResult> resit2 = arg0.resultList.iterator(); resit2.hasNext();){ res2 += resit2.next().profit; } - return Double.compare(res1, res2); + return Double.compare(res2, res1); } }
true
true
public int compareTo(Player arg0) { double res1 = 0; for(Iterator<CompanyResult> resit = resultList.iterator(); resit.hasNext();){ res1 += resit.next().profit; } double res2 = 0; for(Iterator<CompanyResult> resit2 = arg0.resultList.iterator(); resit2.hasNext();){ res2 += resit2.next().profit; } return Double.compare(res1, res2); }
public int compareTo(Player arg0) { double res1 = 0; for(Iterator<CompanyResult> resit = resultList.iterator(); resit.hasNext();){ res1 += resit.next().profit; } double res2 = 0; for(Iterator<CompanyResult> resit2 = arg0.resultList.iterator(); resit2.hasNext();){ res2 += resit2.next().profit; } return Double.compare(res2, res1); }
diff --git a/test/src/test/tmp/A.java b/test/src/test/tmp/A.java index 2d49245..e599895 100644 --- a/test/src/test/tmp/A.java +++ b/test/src/test/tmp/A.java @@ -1,12 +1,14 @@ package test.tmp; import org.testng.annotations.Test; @Test public class A extends Base { - public void a1() {} + public void a1() { + throw new RuntimeException(); + } public void a2() {} public void a3() {} }
true
true
public void a1() {}
public void a1() { throw new RuntimeException(); }
diff --git a/tools/remotetools/org.eclipse.ptp.remotetools.core/src/org/eclipse/ptp/remotetools/internal/common/AbstractRemoteExecution.java b/tools/remotetools/org.eclipse.ptp.remotetools.core/src/org/eclipse/ptp/remotetools/internal/common/AbstractRemoteExecution.java index 5c61e94db..d384229a7 100755 --- a/tools/remotetools/org.eclipse.ptp.remotetools.core/src/org/eclipse/ptp/remotetools/internal/common/AbstractRemoteExecution.java +++ b/tools/remotetools/org.eclipse.ptp.remotetools.core/src/org/eclipse/ptp/remotetools/internal/common/AbstractRemoteExecution.java @@ -1,105 +1,105 @@ /****************************************************************************** * Copyright (c) 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - Initial Implementation * *****************************************************************************/ package org.eclipse.ptp.remotetools.internal.common; import org.eclipse.ptp.remotetools.core.IRemoteOperation; import org.eclipse.ptp.remotetools.exception.CancelException; import org.eclipse.ptp.remotetools.exception.RemoteConnectionException; import org.eclipse.ptp.remotetools.internal.ssh.ExecutionManager; /** * @author Richard Maciel, Daniel Felix Ferber */ public abstract class AbstractRemoteExecution implements IRemoteOperation { /** * The execution manager that created the execution. */ private ExecutionManager executionManager; /** * The execution was canceled by the manager. */ protected boolean cancelled; /** * The execution finished by itself. */ protected boolean finished; /** * Default constructor. * <p> * It is protected because only the RemoteExecutionManager can instantiate it and pass itself as the parameters to * the constructor. * * @param remExecManager * @throws RemoteConnectionException */ public AbstractRemoteExecution(ExecutionManager executionManager) throws RemoteConnectionException { this.executionManager = executionManager; this.cancelled = false; this.finished = false; } public ExecutionManager getExecutionManager() { return executionManager; } public synchronized boolean wasCanceled() { return cancelled; } public synchronized boolean wasFinished() { return finished; } public final synchronized void cancel() { notifyCancel(); } protected synchronized void notifyCancel() { /* * By default, no logic is implemented to cancel the execution. * Only sets the cancel flag. * Notifies all waiting thread that the execution was canceled. */ cancelled = true; this.notifyAll(); } protected synchronized void notifyFinish() { /* * By default, no logic is implemented to finish the execution. * Notifies all waiting thread that the execution finished by itself. */ finished = true; this.notifyAll(); } public synchronized void waitForEndOfExecution() throws RemoteConnectionException, CancelException { /* * Block until the execution finishes or is canceled. */ - if (!finished && !cancelled) { + while (!finished && !cancelled) { try { this.wait(); } catch (InterruptedException e) { - return; + // Ignore spurious interrupts } } if (wasCanceled()) { throw new CancelException(); } } public void close() { } }
false
true
public synchronized void waitForEndOfExecution() throws RemoteConnectionException, CancelException { /* * Block until the execution finishes or is canceled. */ if (!finished && !cancelled) { try { this.wait(); } catch (InterruptedException e) { return; } } if (wasCanceled()) { throw new CancelException(); } }
public synchronized void waitForEndOfExecution() throws RemoteConnectionException, CancelException { /* * Block until the execution finishes or is canceled. */ while (!finished && !cancelled) { try { this.wait(); } catch (InterruptedException e) { // Ignore spurious interrupts } } if (wasCanceled()) { throw new CancelException(); } }
diff --git a/src/com/irr310/client/graphics/gui/UpgradeWeaponTab.java b/src/com/irr310/client/graphics/gui/UpgradeWeaponTab.java index 6b6c9fa..017e33a 100644 --- a/src/com/irr310/client/graphics/gui/UpgradeWeaponTab.java +++ b/src/com/irr310/client/graphics/gui/UpgradeWeaponTab.java @@ -1,172 +1,172 @@ package com.irr310.client.graphics.gui; import java.util.List; import java.util.Map; import org.fenggui.event.ButtonPressedEvent; import org.fenggui.event.IButtonPressedListener; import com.irr310.client.navigation.LoginManager; import com.irr310.common.Game; import com.irr310.common.event.BuyUpgradeRequestEvent; import com.irr310.common.event.QuitGameEvent; import com.irr310.common.world.upgrade.Upgrade; import com.irr310.common.world.upgrade.UpgradeOwnership; import fr.def.iss.vd2.lib_v3d.V3DColor; import fr.def.iss.vd2.lib_v3d.gui.V3DButton; import fr.def.iss.vd2.lib_v3d.gui.V3DContainer; import fr.def.iss.vd2.lib_v3d.gui.V3DGuiComponent; import fr.def.iss.vd2.lib_v3d.gui.V3DGuiComponent.GuiXAlignment; import fr.def.iss.vd2.lib_v3d.gui.V3DGuiRectangle; import fr.def.iss.vd2.lib_v3d.gui.V3DLabel; import fr.def.iss.vd2.lib_v3d.gui.V3DGuiComponent.GuiYAlignment; public class UpgradeWeaponTab extends UpgradeTab{ private V3DContainer root; private List<UpgradeOwnership> upgradesOwnership; public UpgradeWeaponTab() { super("Weapon"); upgradesOwnership = LoginManager.localPlayer.getUpgrades(); Map<String, Upgrade> availableUpgrades = Game.getInstance().getWorld().getAvailableUpgrades(); root = new V3DContainer(); int y = 10; for(Upgrade upgrade: availableUpgrades.values()) { V3DGuiComponent upgradePane = generateUpgradePane(upgrade); upgradePane.setPosition(10, y); root.add(upgradePane); y += 160; } } private V3DGuiComponent generateUpgradePane(final Upgrade upgrade) { V3DContainer pane = new V3DContainer(); pane.setSize(320, 150); V3DGuiRectangle upgradeRect = new V3DGuiRectangle(); upgradeRect.setyAlignment(GuiYAlignment.TOP); upgradeRect.setPosition(0, 0); upgradeRect.setBorderWidth(2); upgradeRect.setSize(320, 150); upgradeRect.setFillColor(V3DColor.transparent); upgradeRect.setBorderColor(GuiConstants.irrGreen); pane.add(upgradeRect); V3DLabel upgradeName = new V3DLabel(upgrade.getName()); upgradeName.setFontStyle("Ubuntu", "bold", 16); upgradeName.setColor(V3DColor.black, V3DColor.transparent); upgradeName.setPosition(5, 0); pane.add(upgradeName); int yPos = 20; V3DLabel upgradeDescription = new V3DLabel(upgrade.getGlobalDescription()); upgradeDescription.setFontStyle("Ubuntu", "", 12); upgradeDescription.setColor(V3DColor.darkgrey, V3DColor.transparent); upgradeDescription.setPosition(5, yPos); upgradeDescription.setyAlignment(GuiYAlignment.TOP); upgradeDescription.setWordWarping(true, 150); pane.add(upgradeDescription); yPos += upgradeDescription.getSize().getY(); UpgradeOwnership ownership = LoginManager.localPlayer.getUpgradeState(upgrade); int currentRank = ownership.getRank(); V3DLabel rankLabel = new V3DLabel(""+currentRank+" / "+upgrade.getMaxRank()); rankLabel.setFontStyle("Ubuntu", "bold", 24); rankLabel.setColor(V3DColor.black, V3DColor.transparent); rankLabel.setxAlignment(GuiXAlignment.RIGHT); rankLabel.setPosition(5, 5); pane.add(rankLabel); if(currentRank > 0) { V3DLabel currentRankLabel = new V3DLabel("Current rank:"); currentRankLabel.setFontStyle("Ubuntu", "bold", 12); currentRankLabel.setColor(V3DColor.black, V3DColor.transparent); currentRankLabel.setWordWarping(true, 150); currentRankLabel.setPosition(5, yPos); pane.add(currentRankLabel); yPos += currentRankLabel.getSize().getY(); - V3DLabel currentRankDescription = new V3DLabel(upgrade.getRankDescriptions().get(currentRank)); + V3DLabel currentRankDescription = new V3DLabel(upgrade.getRankDescriptions().get(currentRank-1)); currentRankDescription.setFontStyle("Ubuntu", "", 12); currentRankDescription.setColor(V3DColor.darkgrey, V3DColor.transparent); currentRankDescription.setWordWarping(true, 150); currentRankDescription.setPosition(5, yPos); pane.add(currentRankDescription); yPos += currentRankDescription.getSize().getY(); } if(currentRank < upgrade.getMaxRank()) { V3DLabel nextRankLabel = new V3DLabel("Next rank:"); nextRankLabel.setFontStyle("Ubuntu", "bold", 12); nextRankLabel.setColor(V3DColor.black, V3DColor.transparent); nextRankLabel.setWordWarping(true, 150); nextRankLabel.setPosition(5, yPos); pane.add(nextRankLabel); yPos += nextRankLabel.getSize().getY(); V3DLabel nextRankDescription = new V3DLabel(upgrade.getRankDescriptions().get(currentRank)); nextRankDescription.setFontStyle("Ubuntu", "", 12); nextRankDescription.setColor(V3DColor.darkgrey, V3DColor.transparent); nextRankDescription.setWordWarping(true, 150); nextRankDescription.setPosition(5, yPos); pane.add(nextRankDescription); yPos += nextRankDescription.getSize().getY(); final V3DButton buyButton = new V3DButton("Buy"); buyButton.setFontStyle("Ubuntu", "bold", 16); buyButton.setColor(V3DColor.white, GuiConstants.irrGreen); buyButton.setxAlignment(GuiXAlignment.RIGHT); buyButton.setyAlignment(GuiYAlignment.BOTTOM); buyButton.setPadding(5,30,30,5); buyButton.setPosition( 20,40); buyButton.getFenGUIWidget().addButtonPressedListener(new IButtonPressedListener() { @Override public void buttonPressed(ButtonPressedEvent e) { Game.getInstance().sendToAll(new BuyUpgradeRequestEvent(upgrade, LoginManager.localPlayer)); } }); pane.add(buyButton); V3DLabel buyPrice = new V3DLabel(upgrade.getPrices().get(currentRank) +" $"); buyPrice.setFontStyle("Ubuntu", "bold", 16); buyPrice.setColor(GuiConstants.irrGreen, V3DColor.transparent); buyPrice.setxAlignment(GuiXAlignment.RIGHT); buyPrice.setyAlignment(GuiYAlignment.BOTTOM); buyPrice.setPosition( 20,15); pane.add(buyPrice); } return pane; } @Override public V3DContainer getContentPane() { return root; } }
true
true
private V3DGuiComponent generateUpgradePane(final Upgrade upgrade) { V3DContainer pane = new V3DContainer(); pane.setSize(320, 150); V3DGuiRectangle upgradeRect = new V3DGuiRectangle(); upgradeRect.setyAlignment(GuiYAlignment.TOP); upgradeRect.setPosition(0, 0); upgradeRect.setBorderWidth(2); upgradeRect.setSize(320, 150); upgradeRect.setFillColor(V3DColor.transparent); upgradeRect.setBorderColor(GuiConstants.irrGreen); pane.add(upgradeRect); V3DLabel upgradeName = new V3DLabel(upgrade.getName()); upgradeName.setFontStyle("Ubuntu", "bold", 16); upgradeName.setColor(V3DColor.black, V3DColor.transparent); upgradeName.setPosition(5, 0); pane.add(upgradeName); int yPos = 20; V3DLabel upgradeDescription = new V3DLabel(upgrade.getGlobalDescription()); upgradeDescription.setFontStyle("Ubuntu", "", 12); upgradeDescription.setColor(V3DColor.darkgrey, V3DColor.transparent); upgradeDescription.setPosition(5, yPos); upgradeDescription.setyAlignment(GuiYAlignment.TOP); upgradeDescription.setWordWarping(true, 150); pane.add(upgradeDescription); yPos += upgradeDescription.getSize().getY(); UpgradeOwnership ownership = LoginManager.localPlayer.getUpgradeState(upgrade); int currentRank = ownership.getRank(); V3DLabel rankLabel = new V3DLabel(""+currentRank+" / "+upgrade.getMaxRank()); rankLabel.setFontStyle("Ubuntu", "bold", 24); rankLabel.setColor(V3DColor.black, V3DColor.transparent); rankLabel.setxAlignment(GuiXAlignment.RIGHT); rankLabel.setPosition(5, 5); pane.add(rankLabel); if(currentRank > 0) { V3DLabel currentRankLabel = new V3DLabel("Current rank:"); currentRankLabel.setFontStyle("Ubuntu", "bold", 12); currentRankLabel.setColor(V3DColor.black, V3DColor.transparent); currentRankLabel.setWordWarping(true, 150); currentRankLabel.setPosition(5, yPos); pane.add(currentRankLabel); yPos += currentRankLabel.getSize().getY(); V3DLabel currentRankDescription = new V3DLabel(upgrade.getRankDescriptions().get(currentRank)); currentRankDescription.setFontStyle("Ubuntu", "", 12); currentRankDescription.setColor(V3DColor.darkgrey, V3DColor.transparent); currentRankDescription.setWordWarping(true, 150); currentRankDescription.setPosition(5, yPos); pane.add(currentRankDescription); yPos += currentRankDescription.getSize().getY(); } if(currentRank < upgrade.getMaxRank()) { V3DLabel nextRankLabel = new V3DLabel("Next rank:"); nextRankLabel.setFontStyle("Ubuntu", "bold", 12); nextRankLabel.setColor(V3DColor.black, V3DColor.transparent); nextRankLabel.setWordWarping(true, 150); nextRankLabel.setPosition(5, yPos); pane.add(nextRankLabel); yPos += nextRankLabel.getSize().getY(); V3DLabel nextRankDescription = new V3DLabel(upgrade.getRankDescriptions().get(currentRank)); nextRankDescription.setFontStyle("Ubuntu", "", 12); nextRankDescription.setColor(V3DColor.darkgrey, V3DColor.transparent); nextRankDescription.setWordWarping(true, 150); nextRankDescription.setPosition(5, yPos); pane.add(nextRankDescription); yPos += nextRankDescription.getSize().getY(); final V3DButton buyButton = new V3DButton("Buy"); buyButton.setFontStyle("Ubuntu", "bold", 16); buyButton.setColor(V3DColor.white, GuiConstants.irrGreen); buyButton.setxAlignment(GuiXAlignment.RIGHT); buyButton.setyAlignment(GuiYAlignment.BOTTOM); buyButton.setPadding(5,30,30,5); buyButton.setPosition( 20,40); buyButton.getFenGUIWidget().addButtonPressedListener(new IButtonPressedListener() { @Override public void buttonPressed(ButtonPressedEvent e) { Game.getInstance().sendToAll(new BuyUpgradeRequestEvent(upgrade, LoginManager.localPlayer)); } }); pane.add(buyButton); V3DLabel buyPrice = new V3DLabel(upgrade.getPrices().get(currentRank) +" $"); buyPrice.setFontStyle("Ubuntu", "bold", 16); buyPrice.setColor(GuiConstants.irrGreen, V3DColor.transparent); buyPrice.setxAlignment(GuiXAlignment.RIGHT); buyPrice.setyAlignment(GuiYAlignment.BOTTOM); buyPrice.setPosition( 20,15); pane.add(buyPrice); } return pane; }
private V3DGuiComponent generateUpgradePane(final Upgrade upgrade) { V3DContainer pane = new V3DContainer(); pane.setSize(320, 150); V3DGuiRectangle upgradeRect = new V3DGuiRectangle(); upgradeRect.setyAlignment(GuiYAlignment.TOP); upgradeRect.setPosition(0, 0); upgradeRect.setBorderWidth(2); upgradeRect.setSize(320, 150); upgradeRect.setFillColor(V3DColor.transparent); upgradeRect.setBorderColor(GuiConstants.irrGreen); pane.add(upgradeRect); V3DLabel upgradeName = new V3DLabel(upgrade.getName()); upgradeName.setFontStyle("Ubuntu", "bold", 16); upgradeName.setColor(V3DColor.black, V3DColor.transparent); upgradeName.setPosition(5, 0); pane.add(upgradeName); int yPos = 20; V3DLabel upgradeDescription = new V3DLabel(upgrade.getGlobalDescription()); upgradeDescription.setFontStyle("Ubuntu", "", 12); upgradeDescription.setColor(V3DColor.darkgrey, V3DColor.transparent); upgradeDescription.setPosition(5, yPos); upgradeDescription.setyAlignment(GuiYAlignment.TOP); upgradeDescription.setWordWarping(true, 150); pane.add(upgradeDescription); yPos += upgradeDescription.getSize().getY(); UpgradeOwnership ownership = LoginManager.localPlayer.getUpgradeState(upgrade); int currentRank = ownership.getRank(); V3DLabel rankLabel = new V3DLabel(""+currentRank+" / "+upgrade.getMaxRank()); rankLabel.setFontStyle("Ubuntu", "bold", 24); rankLabel.setColor(V3DColor.black, V3DColor.transparent); rankLabel.setxAlignment(GuiXAlignment.RIGHT); rankLabel.setPosition(5, 5); pane.add(rankLabel); if(currentRank > 0) { V3DLabel currentRankLabel = new V3DLabel("Current rank:"); currentRankLabel.setFontStyle("Ubuntu", "bold", 12); currentRankLabel.setColor(V3DColor.black, V3DColor.transparent); currentRankLabel.setWordWarping(true, 150); currentRankLabel.setPosition(5, yPos); pane.add(currentRankLabel); yPos += currentRankLabel.getSize().getY(); V3DLabel currentRankDescription = new V3DLabel(upgrade.getRankDescriptions().get(currentRank-1)); currentRankDescription.setFontStyle("Ubuntu", "", 12); currentRankDescription.setColor(V3DColor.darkgrey, V3DColor.transparent); currentRankDescription.setWordWarping(true, 150); currentRankDescription.setPosition(5, yPos); pane.add(currentRankDescription); yPos += currentRankDescription.getSize().getY(); } if(currentRank < upgrade.getMaxRank()) { V3DLabel nextRankLabel = new V3DLabel("Next rank:"); nextRankLabel.setFontStyle("Ubuntu", "bold", 12); nextRankLabel.setColor(V3DColor.black, V3DColor.transparent); nextRankLabel.setWordWarping(true, 150); nextRankLabel.setPosition(5, yPos); pane.add(nextRankLabel); yPos += nextRankLabel.getSize().getY(); V3DLabel nextRankDescription = new V3DLabel(upgrade.getRankDescriptions().get(currentRank)); nextRankDescription.setFontStyle("Ubuntu", "", 12); nextRankDescription.setColor(V3DColor.darkgrey, V3DColor.transparent); nextRankDescription.setWordWarping(true, 150); nextRankDescription.setPosition(5, yPos); pane.add(nextRankDescription); yPos += nextRankDescription.getSize().getY(); final V3DButton buyButton = new V3DButton("Buy"); buyButton.setFontStyle("Ubuntu", "bold", 16); buyButton.setColor(V3DColor.white, GuiConstants.irrGreen); buyButton.setxAlignment(GuiXAlignment.RIGHT); buyButton.setyAlignment(GuiYAlignment.BOTTOM); buyButton.setPadding(5,30,30,5); buyButton.setPosition( 20,40); buyButton.getFenGUIWidget().addButtonPressedListener(new IButtonPressedListener() { @Override public void buttonPressed(ButtonPressedEvent e) { Game.getInstance().sendToAll(new BuyUpgradeRequestEvent(upgrade, LoginManager.localPlayer)); } }); pane.add(buyButton); V3DLabel buyPrice = new V3DLabel(upgrade.getPrices().get(currentRank) +" $"); buyPrice.setFontStyle("Ubuntu", "bold", 16); buyPrice.setColor(GuiConstants.irrGreen, V3DColor.transparent); buyPrice.setxAlignment(GuiXAlignment.RIGHT); buyPrice.setyAlignment(GuiYAlignment.BOTTOM); buyPrice.setPosition( 20,15); pane.add(buyPrice); } return pane; }
diff --git a/EasyMobArmory/src/main/java/com/runetooncraft/plugins/EasyMobArmory/EMAListener.java b/EasyMobArmory/src/main/java/com/runetooncraft/plugins/EasyMobArmory/EMAListener.java index 7c48f7f..b00ac42 100644 --- a/EasyMobArmory/src/main/java/com/runetooncraft/plugins/EasyMobArmory/EMAListener.java +++ b/EasyMobArmory/src/main/java/com/runetooncraft/plugins/EasyMobArmory/EMAListener.java @@ -1,250 +1,249 @@ package com.runetooncraft.plugins.EasyMobArmory; import java.util.HashMap; import net.minecraft.server.v1_6_R2.Item; import net.minecraft.server.v1_6_R2.NBTTagCompound; import net.minecraft.server.v1_6_R2.TileEntityChest; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.craftbukkit.v1_6_R2.inventory.CraftInventory; import org.bukkit.craftbukkit.v1_6_R2.inventory.CraftItemStack; import org.bukkit.entity.Cow; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.entity.Horse; import org.bukkit.entity.Pig; import org.bukkit.entity.PigZombie; import org.bukkit.entity.Player; import org.bukkit.entity.Sheep; import org.bukkit.entity.Skeleton; import org.bukkit.entity.Zombie; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.inventory.InventoryCloseEvent; import org.bukkit.event.player.PlayerInteractEntityEvent; import org.bukkit.inventory.DoubleChestInventory; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.InventoryHolder; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.SkullMeta; import com.runetooncraft.plugins.EasyMobArmory.core.Config; import com.runetooncraft.plugins.EasyMobArmory.core.InventorySerializer; import com.runetooncraft.plugins.EasyMobArmory.core.Messenger; public class EMAListener implements Listener { Config config; public static HashMap<Player, Entity> PlayerZombieDataMap = new HashMap<Player, Entity>(); public static HashMap<Player, Boolean> Armoryenabled = new HashMap<Player, Boolean>(); public EMAListener(Config config) { this.config = config; } @EventHandler public void OnPlayerEntityInteract(PlayerInteractEntityEvent event) { Entity e = event.getRightClicked(); Player p = event.getPlayer(); if(Armoryenabled.get(p) != null){ if(Armoryenabled.get(p)) { if(e.getType().equals(EntityType.ZOMBIE)) { ItemStack i = p.getItemInHand(); Zombie z = (Zombie) e; if(EMA.Helmets.contains(i)) { z.getEquipment().setHelmet(i); }else if(EMA.Chestplates.contains(i)) { z.getEquipment().setChestplate(i); }else if(EMA.Leggings.contains(i)) { z.getEquipment().setLeggings(i); }else if(EMA.Boots.contains(i)) { z.getEquipment().setBoots(i); }else if(i.getType().equals(Material.BONE)){ Inventory inv = Bukkit.createInventory(p, 9, "zombieinv"); ItemStack[] zombieinv = z.getEquipment().getArmorContents(); inv.setContents(zombieinv); inv.setItem(4, z.getEquipment().getItemInHand()); if(z.isBaby()) inv.setItem(5, new ItemStack(Material.REDSTONE)); p.openInventory(inv); PlayerZombieDataMap.put(p, z); }else{ z.getEquipment().setItemInHand(i); } }else if(e.getType().equals(EntityType.SKELETON)) { ItemStack i = p.getItemInHand(); Skeleton s = (Skeleton) e; if(EMA.Helmets.contains(i)) { s.getEquipment().setHelmet(i); }else if(EMA.Chestplates.contains(i)) { s.getEquipment().setChestplate(i); }else if(EMA.Leggings.contains(i)) { s.getEquipment().setLeggings(i); }else if(EMA.Boots.contains(i)) { s.getEquipment().setBoots(i); }else if(i.getType().equals(Material.BONE)){ Inventory inv = Bukkit.createInventory(p, 9, "skeletoninv"); ItemStack[] skeletoninv = s.getEquipment().getArmorContents(); inv.setContents(skeletoninv); inv.setItem(4, s.getEquipment().getItemInHand()); p.openInventory(inv); PlayerZombieDataMap.put(p, s); }else{ s.getEquipment().setItemInHand(i); } }else if(e.getType().equals(EntityType.PIG_ZOMBIE)) { ItemStack i = p.getItemInHand(); PigZombie pz = (PigZombie) e; if(EMA.Helmets.contains(i)) { pz.getEquipment().setHelmet(i); }else if(EMA.Chestplates.contains(i)) { pz.getEquipment().setChestplate(i); }else if(EMA.Leggings.contains(i)) { pz.getEquipment().setLeggings(i); }else if(EMA.Boots.contains(i)) { pz.getEquipment().setBoots(i); }else if(i.getType().equals(Material.BONE)){ Inventory inv = Bukkit.createInventory(p, 9, "pigzombieinv"); ItemStack[] pigzombieinv = pz.getEquipment().getArmorContents(); inv.setContents(pigzombieinv); inv.setItem(4, pz.getEquipment().getItemInHand()); if(pz.isBaby()) inv.setItem(5, new ItemStack(Material.REDSTONE)); p.openInventory(inv); PlayerZombieDataMap.put(p, pz); }else{ pz.getEquipment().setItemInHand(i); } }else if(e.getType().equals(EntityType.SHEEP)) { ItemStack i = p.getItemInHand(); Sheep sh = (Sheep) e; if(i.getType().equals(Material.BONE)) { Inventory inv = Bukkit.createInventory(p, 9, "sheepinv"); if(!sh.isAdult()) inv.setItem(5, new ItemStack(Material.REDSTONE)); if(sh.isSheared()) inv.setItem(6, new ItemStack(Material.SHEARS)); p.openInventory(inv); PlayerZombieDataMap.put(p, sh); } }else if(e.getType().equals(EntityType.PIG)) { ItemStack i = p.getItemInHand(); Pig pig = (Pig) e; if(i.getType().equals(Material.BONE)) { Inventory inv = Bukkit.createInventory(p, 9, "piginv"); if(!pig.isAdult()) inv.setItem(5, new ItemStack(Material.REDSTONE)); if(pig.hasSaddle()) inv.setItem(6, new ItemStack(Material.SADDLE)); p.openInventory(inv); PlayerZombieDataMap.put(p, pig); } }else if(e.getType().equals(EntityType.COW)) { ItemStack i = p.getItemInHand(); Cow cow = (Cow) e; if(i.getType().equals(Material.BONE)) { Inventory inv = Bukkit.createInventory(p, 9, "cowinv"); if(!cow.isAdult()) inv.setItem(5, new ItemStack(Material.REDSTONE)); p.openInventory(inv); PlayerZombieDataMap.put(p, cow); } }else if(e.getType().equals(EntityType.HORSE)) { ItemStack i = p.getItemInHand(); Horse h = (Horse) e; - Messenger.info("DEBUG! right cliked horse"); if(i.getType().equals(Material.BONE)) { - Inventory inv = Bukkit.createInventory(p, 9, "cowinv"); + Inventory inv = Bukkit.createInventory(p, 9, "horseinv"); if(!h.isAdult()) inv.setItem(5, new ItemStack(Material.REDSTONE)); if(h.isTamed()) inv.setItem(6, new ItemStack(Material.HAY_BLOCK)); if(h.isCarryingChest()) inv.setItem(7, new ItemStack(Material.CHEST)); if(h.isTamed()) { Player owner = (Player) h.getOwner(); inv.setItem(8, setOwner(new ItemStack(Material.SKULL_ITEM, 1, (short)3), p.getName())); } p.openInventory(inv); PlayerZombieDataMap.put(p, h); } } }} } @EventHandler public void OnInventoryCloseEvent(InventoryCloseEvent event) { if(Armoryenabled.get(event.getPlayer()) != null){ if(Armoryenabled.get(event.getPlayer())) { if(event.getInventory().getName().equals("zombieinv")) { Inventory i = event.getInventory(); Zombie z = (Zombie) PlayerZombieDataMap.get(event.getPlayer()); z.getEquipment().setHelmet(i.getItem(3)); z.getEquipment().setChestplate(i.getItem(2)); z.getEquipment().setLeggings(i.getItem(1)); z.getEquipment().setBoots(i.getItem(0)); z.getEquipment().setItemInHand(i.getItem(4)); if(i.contains(Material.REDSTONE)) { z.setBaby(true); }else{ z.setBaby(false); } } else if(event.getInventory().getName().equals("skeletoninv")) { Inventory i = event.getInventory(); Skeleton s = (Skeleton) PlayerZombieDataMap.get(event.getPlayer()); s.getEquipment().setHelmet(i.getItem(3)); s.getEquipment().setChestplate(i.getItem(2)); s.getEquipment().setLeggings(i.getItem(1)); s.getEquipment().setBoots(i.getItem(0)); s.getEquipment().setItemInHand(i.getItem(4)); } else if(event.getInventory().getName().equals("pigzombieinv")) { Inventory i = event.getInventory(); PigZombie pz = (PigZombie) PlayerZombieDataMap.get(event.getPlayer()); pz.getEquipment().setHelmet(i.getItem(3)); pz.getEquipment().setChestplate(i.getItem(2)); pz.getEquipment().setLeggings(i.getItem(1)); pz.getEquipment().setBoots(i.getItem(0)); pz.getEquipment().setItemInHand(i.getItem(4)); if(i.contains(Material.REDSTONE)) { pz.setBaby(true); }else{ pz.setBaby(false); } } else if(event.getInventory().getName().equals("sheepinv")) { Inventory i = event.getInventory(); Sheep sh = (Sheep) PlayerZombieDataMap.get(event.getPlayer()); if(i.contains(Material.REDSTONE)) { sh.setBaby(); }else{ sh.setAdult(); } if(i.contains(Material.SHEARS)) { sh.setSheared(true); }else{ sh.setSheared(false); } } else if(event.getInventory().getName().equals("piginv")) { Inventory i = event.getInventory(); Pig pig = (Pig) PlayerZombieDataMap.get(event.getPlayer()); if(i.contains(Material.REDSTONE)) { pig.setBaby(); }else{ pig.setAdult(); } if(i.contains(Material.SADDLE)) { pig.setSaddle(true); }else{ pig.setSaddle(false); } } else if(event.getInventory().getName().equals("cowinv")) { Inventory i = event.getInventory(); Cow cow = (Cow) PlayerZombieDataMap.get(event.getPlayer()); if(i.contains(Material.REDSTONE)) { cow.setBaby(); }else{ cow.setAdult(); } } }} } public ItemStack setOwner(ItemStack item, String owner) { SkullMeta meta = (SkullMeta) item.getItemMeta(); meta.setOwner(owner); item.setItemMeta(meta); return item; } }
false
true
public void OnPlayerEntityInteract(PlayerInteractEntityEvent event) { Entity e = event.getRightClicked(); Player p = event.getPlayer(); if(Armoryenabled.get(p) != null){ if(Armoryenabled.get(p)) { if(e.getType().equals(EntityType.ZOMBIE)) { ItemStack i = p.getItemInHand(); Zombie z = (Zombie) e; if(EMA.Helmets.contains(i)) { z.getEquipment().setHelmet(i); }else if(EMA.Chestplates.contains(i)) { z.getEquipment().setChestplate(i); }else if(EMA.Leggings.contains(i)) { z.getEquipment().setLeggings(i); }else if(EMA.Boots.contains(i)) { z.getEquipment().setBoots(i); }else if(i.getType().equals(Material.BONE)){ Inventory inv = Bukkit.createInventory(p, 9, "zombieinv"); ItemStack[] zombieinv = z.getEquipment().getArmorContents(); inv.setContents(zombieinv); inv.setItem(4, z.getEquipment().getItemInHand()); if(z.isBaby()) inv.setItem(5, new ItemStack(Material.REDSTONE)); p.openInventory(inv); PlayerZombieDataMap.put(p, z); }else{ z.getEquipment().setItemInHand(i); } }else if(e.getType().equals(EntityType.SKELETON)) { ItemStack i = p.getItemInHand(); Skeleton s = (Skeleton) e; if(EMA.Helmets.contains(i)) { s.getEquipment().setHelmet(i); }else if(EMA.Chestplates.contains(i)) { s.getEquipment().setChestplate(i); }else if(EMA.Leggings.contains(i)) { s.getEquipment().setLeggings(i); }else if(EMA.Boots.contains(i)) { s.getEquipment().setBoots(i); }else if(i.getType().equals(Material.BONE)){ Inventory inv = Bukkit.createInventory(p, 9, "skeletoninv"); ItemStack[] skeletoninv = s.getEquipment().getArmorContents(); inv.setContents(skeletoninv); inv.setItem(4, s.getEquipment().getItemInHand()); p.openInventory(inv); PlayerZombieDataMap.put(p, s); }else{ s.getEquipment().setItemInHand(i); } }else if(e.getType().equals(EntityType.PIG_ZOMBIE)) { ItemStack i = p.getItemInHand(); PigZombie pz = (PigZombie) e; if(EMA.Helmets.contains(i)) { pz.getEquipment().setHelmet(i); }else if(EMA.Chestplates.contains(i)) { pz.getEquipment().setChestplate(i); }else if(EMA.Leggings.contains(i)) { pz.getEquipment().setLeggings(i); }else if(EMA.Boots.contains(i)) { pz.getEquipment().setBoots(i); }else if(i.getType().equals(Material.BONE)){ Inventory inv = Bukkit.createInventory(p, 9, "pigzombieinv"); ItemStack[] pigzombieinv = pz.getEquipment().getArmorContents(); inv.setContents(pigzombieinv); inv.setItem(4, pz.getEquipment().getItemInHand()); if(pz.isBaby()) inv.setItem(5, new ItemStack(Material.REDSTONE)); p.openInventory(inv); PlayerZombieDataMap.put(p, pz); }else{ pz.getEquipment().setItemInHand(i); } }else if(e.getType().equals(EntityType.SHEEP)) { ItemStack i = p.getItemInHand(); Sheep sh = (Sheep) e; if(i.getType().equals(Material.BONE)) { Inventory inv = Bukkit.createInventory(p, 9, "sheepinv"); if(!sh.isAdult()) inv.setItem(5, new ItemStack(Material.REDSTONE)); if(sh.isSheared()) inv.setItem(6, new ItemStack(Material.SHEARS)); p.openInventory(inv); PlayerZombieDataMap.put(p, sh); } }else if(e.getType().equals(EntityType.PIG)) { ItemStack i = p.getItemInHand(); Pig pig = (Pig) e; if(i.getType().equals(Material.BONE)) { Inventory inv = Bukkit.createInventory(p, 9, "piginv"); if(!pig.isAdult()) inv.setItem(5, new ItemStack(Material.REDSTONE)); if(pig.hasSaddle()) inv.setItem(6, new ItemStack(Material.SADDLE)); p.openInventory(inv); PlayerZombieDataMap.put(p, pig); } }else if(e.getType().equals(EntityType.COW)) { ItemStack i = p.getItemInHand(); Cow cow = (Cow) e; if(i.getType().equals(Material.BONE)) { Inventory inv = Bukkit.createInventory(p, 9, "cowinv"); if(!cow.isAdult()) inv.setItem(5, new ItemStack(Material.REDSTONE)); p.openInventory(inv); PlayerZombieDataMap.put(p, cow); } }else if(e.getType().equals(EntityType.HORSE)) { ItemStack i = p.getItemInHand(); Horse h = (Horse) e; Messenger.info("DEBUG! right cliked horse"); if(i.getType().equals(Material.BONE)) { Inventory inv = Bukkit.createInventory(p, 9, "cowinv"); if(!h.isAdult()) inv.setItem(5, new ItemStack(Material.REDSTONE)); if(h.isTamed()) inv.setItem(6, new ItemStack(Material.HAY_BLOCK)); if(h.isCarryingChest()) inv.setItem(7, new ItemStack(Material.CHEST)); if(h.isTamed()) { Player owner = (Player) h.getOwner(); inv.setItem(8, setOwner(new ItemStack(Material.SKULL_ITEM, 1, (short)3), p.getName())); } p.openInventory(inv); PlayerZombieDataMap.put(p, h); } } }} }
public void OnPlayerEntityInteract(PlayerInteractEntityEvent event) { Entity e = event.getRightClicked(); Player p = event.getPlayer(); if(Armoryenabled.get(p) != null){ if(Armoryenabled.get(p)) { if(e.getType().equals(EntityType.ZOMBIE)) { ItemStack i = p.getItemInHand(); Zombie z = (Zombie) e; if(EMA.Helmets.contains(i)) { z.getEquipment().setHelmet(i); }else if(EMA.Chestplates.contains(i)) { z.getEquipment().setChestplate(i); }else if(EMA.Leggings.contains(i)) { z.getEquipment().setLeggings(i); }else if(EMA.Boots.contains(i)) { z.getEquipment().setBoots(i); }else if(i.getType().equals(Material.BONE)){ Inventory inv = Bukkit.createInventory(p, 9, "zombieinv"); ItemStack[] zombieinv = z.getEquipment().getArmorContents(); inv.setContents(zombieinv); inv.setItem(4, z.getEquipment().getItemInHand()); if(z.isBaby()) inv.setItem(5, new ItemStack(Material.REDSTONE)); p.openInventory(inv); PlayerZombieDataMap.put(p, z); }else{ z.getEquipment().setItemInHand(i); } }else if(e.getType().equals(EntityType.SKELETON)) { ItemStack i = p.getItemInHand(); Skeleton s = (Skeleton) e; if(EMA.Helmets.contains(i)) { s.getEquipment().setHelmet(i); }else if(EMA.Chestplates.contains(i)) { s.getEquipment().setChestplate(i); }else if(EMA.Leggings.contains(i)) { s.getEquipment().setLeggings(i); }else if(EMA.Boots.contains(i)) { s.getEquipment().setBoots(i); }else if(i.getType().equals(Material.BONE)){ Inventory inv = Bukkit.createInventory(p, 9, "skeletoninv"); ItemStack[] skeletoninv = s.getEquipment().getArmorContents(); inv.setContents(skeletoninv); inv.setItem(4, s.getEquipment().getItemInHand()); p.openInventory(inv); PlayerZombieDataMap.put(p, s); }else{ s.getEquipment().setItemInHand(i); } }else if(e.getType().equals(EntityType.PIG_ZOMBIE)) { ItemStack i = p.getItemInHand(); PigZombie pz = (PigZombie) e; if(EMA.Helmets.contains(i)) { pz.getEquipment().setHelmet(i); }else if(EMA.Chestplates.contains(i)) { pz.getEquipment().setChestplate(i); }else if(EMA.Leggings.contains(i)) { pz.getEquipment().setLeggings(i); }else if(EMA.Boots.contains(i)) { pz.getEquipment().setBoots(i); }else if(i.getType().equals(Material.BONE)){ Inventory inv = Bukkit.createInventory(p, 9, "pigzombieinv"); ItemStack[] pigzombieinv = pz.getEquipment().getArmorContents(); inv.setContents(pigzombieinv); inv.setItem(4, pz.getEquipment().getItemInHand()); if(pz.isBaby()) inv.setItem(5, new ItemStack(Material.REDSTONE)); p.openInventory(inv); PlayerZombieDataMap.put(p, pz); }else{ pz.getEquipment().setItemInHand(i); } }else if(e.getType().equals(EntityType.SHEEP)) { ItemStack i = p.getItemInHand(); Sheep sh = (Sheep) e; if(i.getType().equals(Material.BONE)) { Inventory inv = Bukkit.createInventory(p, 9, "sheepinv"); if(!sh.isAdult()) inv.setItem(5, new ItemStack(Material.REDSTONE)); if(sh.isSheared()) inv.setItem(6, new ItemStack(Material.SHEARS)); p.openInventory(inv); PlayerZombieDataMap.put(p, sh); } }else if(e.getType().equals(EntityType.PIG)) { ItemStack i = p.getItemInHand(); Pig pig = (Pig) e; if(i.getType().equals(Material.BONE)) { Inventory inv = Bukkit.createInventory(p, 9, "piginv"); if(!pig.isAdult()) inv.setItem(5, new ItemStack(Material.REDSTONE)); if(pig.hasSaddle()) inv.setItem(6, new ItemStack(Material.SADDLE)); p.openInventory(inv); PlayerZombieDataMap.put(p, pig); } }else if(e.getType().equals(EntityType.COW)) { ItemStack i = p.getItemInHand(); Cow cow = (Cow) e; if(i.getType().equals(Material.BONE)) { Inventory inv = Bukkit.createInventory(p, 9, "cowinv"); if(!cow.isAdult()) inv.setItem(5, new ItemStack(Material.REDSTONE)); p.openInventory(inv); PlayerZombieDataMap.put(p, cow); } }else if(e.getType().equals(EntityType.HORSE)) { ItemStack i = p.getItemInHand(); Horse h = (Horse) e; if(i.getType().equals(Material.BONE)) { Inventory inv = Bukkit.createInventory(p, 9, "horseinv"); if(!h.isAdult()) inv.setItem(5, new ItemStack(Material.REDSTONE)); if(h.isTamed()) inv.setItem(6, new ItemStack(Material.HAY_BLOCK)); if(h.isCarryingChest()) inv.setItem(7, new ItemStack(Material.CHEST)); if(h.isTamed()) { Player owner = (Player) h.getOwner(); inv.setItem(8, setOwner(new ItemStack(Material.SKULL_ITEM, 1, (short)3), p.getName())); } p.openInventory(inv); PlayerZombieDataMap.put(p, h); } } }} }
diff --git a/src/com/android/settings/MasterClear.java b/src/com/android/settings/MasterClear.java index 1b045eae3..29a92b106 100644 --- a/src/com/android/settings/MasterClear.java +++ b/src/com/android/settings/MasterClear.java @@ -1,229 +1,230 @@ /* * Copyright (C) 2008 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.settings; import com.android.settings.R; import android.accounts.Account; import android.accounts.AccountManager; import android.accounts.AuthenticatorDescription; import android.app.Activity; import android.app.Fragment; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.content.res.Resources; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.os.Environment; import android.preference.Preference; import android.preference.PreferenceActivity; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.CheckBox; import android.widget.LinearLayout; import android.widget.TextView; /** * Confirm and execute a reset of the device to a clean "just out of the box" * state. Multiple confirmations are required: first, a general "are you sure * you want to do this?" prompt, followed by a keyguard pattern trace if the user * has defined one, followed by a final strongly-worded "THIS WILL ERASE EVERYTHING * ON THE PHONE" prompt. If at any time the phone is allowed to go to sleep, is * locked, et cetera, then the confirmation sequence is abandoned. * * This is the initial screen. */ public class MasterClear extends Fragment { private static final String TAG = "MasterClear"; private static final int KEYGUARD_REQUEST = 55; static final String ERASE_EXTERNAL_EXTRA = "erase_sd"; private View mContentView; private Button mInitiateButton; private View mExternalStorageContainer; private CheckBox mExternalStorage; /** * Keyguard validation is run using the standard {@link ConfirmLockPattern} * component as a subactivity * @param request the request code to be returned once confirmation finishes * @return true if confirmation launched */ private boolean runKeyguardConfirmation(int request) { Resources res = getActivity().getResources(); return new ChooseLockSettingsHelper(getActivity(), this) .launchConfirmationActivity(request, res.getText(R.string.master_clear_gesture_prompt), res.getText(R.string.master_clear_gesture_explanation)); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode != KEYGUARD_REQUEST) { return; } // If the user entered a valid keyguard trace, present the final // confirmation prompt; otherwise, go back to the initial state. if (resultCode == Activity.RESULT_OK) { showFinalConfirmation(); } else { establishInitialState(); } } private void showFinalConfirmation() { Preference preference = new Preference(getActivity()); preference.setFragment(MasterClearConfirm.class.getName()); preference.setTitle(R.string.master_clear_confirm_title); preference.getExtras().putBoolean(ERASE_EXTERNAL_EXTRA, mExternalStorage.isChecked()); ((PreferenceActivity) getActivity()).onPreferenceStartFragment(null, preference); } /** * If the user clicks to begin the reset sequence, we next require a * keyguard confirmation if the user has currently enabled one. If there * is no keyguard available, we simply go to the final confirmation prompt. */ private Button.OnClickListener mInitiateListener = new Button.OnClickListener() { public void onClick(View v) { if (!runKeyguardConfirmation(KEYGUARD_REQUEST)) { showFinalConfirmation(); } } }; /** * In its initial state, the activity presents a button for the user to * click in order to initiate a confirmation sequence. This method is * called from various other points in the code to reset the activity to * this base state. * * <p>Reinflating views from resources is expensive and prevents us from * caching widget pointers, so we use a single-inflate pattern: we lazy- * inflate each view, caching all of the widget pointers we'll need at the * time, then simply reuse the inflated views directly whenever we need * to change contents. */ private void establishInitialState() { mInitiateButton = (Button) mContentView.findViewById(R.id.initiate_master_clear); mInitiateButton.setOnClickListener(mInitiateListener); mExternalStorageContainer = mContentView.findViewById(R.id.erase_external_container); mExternalStorage = (CheckBox) mContentView.findViewById(R.id.erase_external); /* * If the external storage is emulated, it will be erased with a factory * reset at any rate. There is no need to have a separate option until * we have a factory reset that only erases some directories and not * others. */ if (Environment.isExternalStorageEmulated()) { mExternalStorageContainer.setVisibility(View.GONE); final View externalOption = mContentView.findViewById(R.id.erase_external_option_text); externalOption.setVisibility(View.GONE); final View externalAlsoErased = mContentView.findViewById(R.id.also_erases_external); externalAlsoErased.setVisibility(View.VISIBLE); } else { mExternalStorageContainer.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mExternalStorage.toggle(); } }); } loadAccountList(); } private void loadAccountList() { View accountsLabel = mContentView.findViewById(R.id.accounts_label); LinearLayout contents = (LinearLayout)mContentView.findViewById(R.id.accounts); Context context = getActivity(); AccountManager mgr = AccountManager.get(context); Account[] accounts = mgr.getAccounts(); final int N = accounts.length; if (N == 0) { accountsLabel.setVisibility(View.GONE); contents.setVisibility(View.GONE); return; } LayoutInflater inflater = (LayoutInflater)context.getSystemService( Context.LAYOUT_INFLATER_SERVICE); AuthenticatorDescription[] descs = AccountManager.get(context).getAuthenticatorTypes(); final int M = descs.length; for (int i=0; i<N; i++) { Account account = accounts[i]; AuthenticatorDescription desc = null; for (int j=0; j<M; j++) { if (account.type.equals(descs[j].type)) { desc = descs[j]; break; } } if (desc == null) { Log.w(TAG, "No descriptor for account name=" + account.name + " type=" + account.type); continue; } - Drawable icon; + Drawable icon = null; try { - Context authContext = context.createPackageContext(desc.packageName, 0); - icon = authContext.getResources().getDrawable(desc.iconId); + if (desc.iconId != 0) { + Context authContext = context.createPackageContext(desc.packageName, 0); + icon = authContext.getResources().getDrawable(desc.iconId); + } } catch (PackageManager.NameNotFoundException e) { Log.w(TAG, "No icon for account type " + desc.type); - icon = null; } TextView child = (TextView)inflater.inflate(R.layout.master_clear_account, contents, false); child.setText(account.name); if (icon != null) { child.setCompoundDrawablesWithIntrinsicBounds(icon, null, null, null); } contents.addView(child); } accountsLabel.setVisibility(View.VISIBLE); contents.setVisibility(View.VISIBLE); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mContentView = inflater.inflate(R.layout.master_clear, null); establishInitialState(); return mContentView; } }
false
true
private void loadAccountList() { View accountsLabel = mContentView.findViewById(R.id.accounts_label); LinearLayout contents = (LinearLayout)mContentView.findViewById(R.id.accounts); Context context = getActivity(); AccountManager mgr = AccountManager.get(context); Account[] accounts = mgr.getAccounts(); final int N = accounts.length; if (N == 0) { accountsLabel.setVisibility(View.GONE); contents.setVisibility(View.GONE); return; } LayoutInflater inflater = (LayoutInflater)context.getSystemService( Context.LAYOUT_INFLATER_SERVICE); AuthenticatorDescription[] descs = AccountManager.get(context).getAuthenticatorTypes(); final int M = descs.length; for (int i=0; i<N; i++) { Account account = accounts[i]; AuthenticatorDescription desc = null; for (int j=0; j<M; j++) { if (account.type.equals(descs[j].type)) { desc = descs[j]; break; } } if (desc == null) { Log.w(TAG, "No descriptor for account name=" + account.name + " type=" + account.type); continue; } Drawable icon; try { Context authContext = context.createPackageContext(desc.packageName, 0); icon = authContext.getResources().getDrawable(desc.iconId); } catch (PackageManager.NameNotFoundException e) { Log.w(TAG, "No icon for account type " + desc.type); icon = null; } TextView child = (TextView)inflater.inflate(R.layout.master_clear_account, contents, false); child.setText(account.name); if (icon != null) { child.setCompoundDrawablesWithIntrinsicBounds(icon, null, null, null); } contents.addView(child); } accountsLabel.setVisibility(View.VISIBLE); contents.setVisibility(View.VISIBLE); }
private void loadAccountList() { View accountsLabel = mContentView.findViewById(R.id.accounts_label); LinearLayout contents = (LinearLayout)mContentView.findViewById(R.id.accounts); Context context = getActivity(); AccountManager mgr = AccountManager.get(context); Account[] accounts = mgr.getAccounts(); final int N = accounts.length; if (N == 0) { accountsLabel.setVisibility(View.GONE); contents.setVisibility(View.GONE); return; } LayoutInflater inflater = (LayoutInflater)context.getSystemService( Context.LAYOUT_INFLATER_SERVICE); AuthenticatorDescription[] descs = AccountManager.get(context).getAuthenticatorTypes(); final int M = descs.length; for (int i=0; i<N; i++) { Account account = accounts[i]; AuthenticatorDescription desc = null; for (int j=0; j<M; j++) { if (account.type.equals(descs[j].type)) { desc = descs[j]; break; } } if (desc == null) { Log.w(TAG, "No descriptor for account name=" + account.name + " type=" + account.type); continue; } Drawable icon = null; try { if (desc.iconId != 0) { Context authContext = context.createPackageContext(desc.packageName, 0); icon = authContext.getResources().getDrawable(desc.iconId); } } catch (PackageManager.NameNotFoundException e) { Log.w(TAG, "No icon for account type " + desc.type); } TextView child = (TextView)inflater.inflate(R.layout.master_clear_account, contents, false); child.setText(account.name); if (icon != null) { child.setCompoundDrawablesWithIntrinsicBounds(icon, null, null, null); } contents.addView(child); } accountsLabel.setVisibility(View.VISIBLE); contents.setVisibility(View.VISIBLE); }
diff --git a/src/citysdk/tourism/client/parser/DataReader.java b/src/citysdk/tourism/client/parser/DataReader.java index f97d50d..af998c7 100644 --- a/src/citysdk/tourism/client/parser/DataReader.java +++ b/src/citysdk/tourism/client/parser/DataReader.java @@ -1,713 +1,713 @@ /** * COPYRIGHT NOTICE: * * This file is part of CitySDK WP5 Tourism Java Library. * * CitySDK WP5 Tourism Java 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 3 of the License, or * (at your option) any later version. * * CitySDK WP5 Tourism Java 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 CitySDK WP5 Tourism Java Library. If not, see <http://www.gnu.org/licenses/>. * * Copyright 2013, IST */ package citysdk.tourism.client.parser; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import citysdk.tourism.client.parser.data.GeometryContent; import citysdk.tourism.client.parser.data.ImageContent; import citysdk.tourism.client.parser.data.LineContent; import citysdk.tourism.client.parser.data.LocationContent; import citysdk.tourism.client.parser.data.PointContent; import citysdk.tourism.client.parser.data.PolygonContent; import citysdk.tourism.client.poi.base.Line; import citysdk.tourism.client.poi.base.Location; import citysdk.tourism.client.poi.base.POIBaseType; import citysdk.tourism.client.poi.base.POITermType; import citysdk.tourism.client.poi.base.Point; import citysdk.tourism.client.poi.base.Polygon; import citysdk.tourism.client.poi.base.Relationship; import citysdk.tourism.client.poi.lists.ListTag; import citysdk.tourism.client.poi.single.POI; import citysdk.tourism.client.poi.single.Tag; import citysdk.tourism.client.terms.Term; /** * Used as an aid to get data from a * {@link citysdk.tourism.client.poi.single.POI}-based object. It abstract the * parsing of data and gets the information needed specified by the application * using a given set of terms or languages. In case a given language is not * found, it defaults to en_GB. * * @author Pedro Cruz * */ public class DataReader { private static final String PRICE_TERM = "X-citysdk/price"; private static final String WAITING_TERM = "X-citysdk/waiting-time"; private static final String OCCUPATION_TERM = "X-citysdk/occupation"; private static final String CALENDAR_TERM = "text/calendar"; private static final String IMAGE_TERM = "image/"; private static Locale defaultLang = new Locale("en", "GB"); /** * Sets the default locale. If locale is null, it defaults to en_GB. * * @param locale * the default locale. */ public static void setDefaultLocale(Locale locale) { if (locale == null) return; defaultLang = locale; } /** * Gets a mapping of all the available languages of a given field in the * {@link citysdk.tourism.client.poi.single.POI} object. * * @param poi * the object to get the data. * @param field * the wanted field * @return a mapping of language codes and the respective locales. */ public static Map<String, Locale> getAvailableLangs(POI poi, Field field) { if (poi == null || field == null) return null; Map<String, Locale> languages = new HashMap<String, Locale>(); List<? extends POIBaseType> fields = invokeMethod(poi, field); if (field != null) { for (POIBaseType base : fields) { if (!base.getLang().equals("")) { Locale locale = parseLocale(base.getLang()); languages.put(locale.getLanguage(), locale); } } } return languages; } /* * Invokes the respective method from the field */ @SuppressWarnings("unchecked") private static List<? extends POIBaseType> invokeMethod(POI poi, Field field) { Class<?>[] params = { POI.class }; try { Method method = DataReader.class.getDeclaredMethod( field.getField(), params); return (List<? extends POIBaseType>) method.invoke(null, new Object[] { poi }); } catch (SecurityException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } return null; } /* * Gets the labels field of a POI */ @SuppressWarnings("unused") private static List<? extends POIBaseType> getLabels(POI poi) { return poi.getLabel(); } /* * Gets the descriptions field of a POI */ @SuppressWarnings("unused") private static List<? extends POIBaseType> getDescriptions(POI poi) { return poi.getDescription(); } /* * Gets the categories field of a POI */ @SuppressWarnings("unused") private static List<? extends POIBaseType> getCategories(POI poi) { return poi.getCategory(); } /* * Parses the locale of a given string */ private static Locale parseLocale(String locale) { String[] parts = locale.replace('-', '_').split("_"); switch (parts.length) { case 3: return new Locale(parts[0], parts[1], parts[2]); case 2: return new Locale(parts[0], parts[1]); case 1: return new Locale(parts[0]); default: throw new IllegalArgumentException("Invalid locale: " + locale); } } /** * Gets the label with the given term in a given language. * * @param poi * the object to get the data. * @param term * the term used. * @param lang * the wanted language. * @return a {@link String} * containing the following: the value of the label in the given * language. If such language is not found it will return in default * language and if the default language is not present it will * return a DataContent containing null. */ public static String getLabel(POI poi, Term term, Locale lang) { if (poi == null || lang == null) return null; Locale labelLang; Locale poiLang = parseLocale(poi.getLang()); String defaultValue = null; List<POITermType> labels = poi.getLabel(); for (POITermType label : labels) { if (label.getLang().equals("")) labelLang = poiLang; else labelLang = parseLocale(label.getLang()); if (label.getTerm().equals(term.getTerm()) && labelLang.getLanguage() .equals(defaultLang.getLanguage())) { defaultValue = label.getValue(); } else if (label.getTerm().equals(term.getTerm()) && labelLang.getLanguage().equals(lang.getLanguage())) { return label.getValue(); } } return defaultValue; } /** * Gets the description in a given language. * * @param poi * the object to get the data. * @param lang * the wanted language. * @return a {@link String} * containing the following: the value of the description in the * desired language or in the default language if none found or * null. */ public static String getDescription(POI poi, Locale lang) { if (poi == null || lang == null) return null; Locale descriptionLang; Locale poiLang = parseLocale(poi.getLang()); String defaultValue = null; List<POIBaseType> descriptions = poi.getDescription(); for (POIBaseType description : descriptions) { if (description.getLang().equals("")) descriptionLang = poiLang; else descriptionLang = parseLocale(description.getLang()); if (descriptionLang.getLanguage().equals(defaultLang.getLanguage())) { defaultValue = description.getValue(); } else if (descriptionLang.getLanguage().equals(lang.getLanguage())) { return description.getValue(); } } return defaultValue; } /** * Gets the categories in a given language. * * @param poi * the object to get the data. * @param lang * the wanted language. * @return a list containing the following: the categories in the * desired language if none found or empty. */ public static List<String> getCategories(POI poi, Locale lang) { List<String> poiCategories = new ArrayList<String>(); if (poi == null || lang == null) return poiCategories; Locale categoryLang; Locale poiLang = parseLocale(poi.getLang()); List<POITermType> categories = poi.getCategory(); for (POITermType category : categories) { if (category.getLang().equals("")) categoryLang = poiLang; else categoryLang = parseLocale(category.getLang()); if (categoryLang.getLanguage().equals(lang.getLanguage())) { poiCategories.add(category.getValue()); } } return poiCategories; } /** * Gets the price in a given language. * * @param poi * the object to get the data. * @param lang * the wanted language. * @return a {@link String} * containing the following: the value of the price in the desired * language or in the default language if it was not found or null * if the default language is not present. */ public static String getPrice(POI poi, Locale lang) { return getValueWithTerm(poi, lang, PRICE_TERM); } /** * Gets the waiting time in a given language. * * @param poi * the object to get the data. * @return a {@link String} * containing the waiting time (in seconds) or null. */ public static String getWaitingTime(POI poi) { return getValueWithTerm(poi, null, WAITING_TERM); } /** * Gets the occupation in a given language. * * @param poi * the object to get the data. * @return a {@link String} * containing the occupation value (0 to 100) or null. */ public static String getOccupation(POI poi) { return getValueWithTerm(poi, null, OCCUPATION_TERM); } private static String getValueWithTerm(POI poi, Locale lang, String tag) { if (poi == null) return null; Locale descriptionLang; Locale poiLang = parseLocale(poi.getLang()); String defaultValue = null; List<POIBaseType> descriptions = poi.getDescription(); for (POIBaseType description : descriptions) { if (description.getLang().equals("")) descriptionLang = poiLang; else descriptionLang = parseLocale(description.getLang()); if (description.getType().equals(tag)) { if (lang != null && descriptionLang.getLanguage().equals( defaultLang.getLanguage())) defaultValue = description.getValue(); else if (lang == null) defaultValue = description.getValue(); } else if (description.getType().equals(tag)) { if (lang != null && descriptionLang.getLanguage().equals( lang.getLanguage())) - return new String(description.getValue()); + return description.getValue(); else if (lang == null) - return new String(description.getValue()); + return description.getValue(); } } - return new String(defaultValue); + return defaultValue; } /** * Gets all the thumbnails in 64-base bytecode or URI * * @param poi * the object to get the data. * @return a list of {@link citysdk.tourism.client.parser.data.ImageContent} * where each element contains the following: the bytecode (base-64) * or URI of the thumbnail, or an empty list if none found. */ public static List<ImageContent> getThumbnails(POI poi) { List<ImageContent> thumbnails = new ArrayList<ImageContent>(); if (poi == null) return thumbnails; ImageContent content = null; List<POITermType> links = poi.getLink(); for (POITermType link : links) { if (link.getTerm().equals(Term.LINK_TERM_ICON.getTerm())) { if (!link.getHref().equals("")) { content = new ImageContent(link.getHref()); content.isImgUri(true); thumbnails.add(content); } else if (!link.getValue().equals("")) { content = new ImageContent(link.getValue()); content.isImgByteCode(true); thumbnails.add(content); } } } return thumbnails; } /** * Gets a list of points of the POI object with the given term. * * @param poi * the object to get the data. * @param term * the term to be used. * @return a list (of * {@link citysdk.tourism.client.parser.data.GeometryContent}) * containing all geometries with the given term or an empty list. */ public static List<GeometryContent> getLocationGeometry(POI poi, Term term) { List<GeometryContent> list = new ArrayList<GeometryContent>(); if (poi == null) return list; list.addAll(getLocationPoint(poi, term)); list.addAll(getLocationLine(poi, term)); list.addAll(getLocationPolygon(poi, term)); return list; } /** * Gets a list of points of the POI object with the given term. It only * checks the {@link citysdk.tourism.client.poi.base.Point} geometry. * * @param poi * the object to get the data. * @param term * the term to be used. * @return a list (of * {@link citysdk.tourism.client.parser.data.PointContent}) * containing all points with the given term or an empty list. */ public static List<PointContent> getLocationPoint(POI poi, Term term) { List<PointContent> list = new ArrayList<PointContent>(); if (poi == null) return list; Location location = poi.getLocation(); PointContent point; if (location.hasPoints()) { List<Point> points = location.getPoint(); for (Point p : points) { if (p.getTerm().equals(term.getTerm())) { String data[] = p.getPoint().getPosList().split(" "); point = new PointContent(new String(data[0]), new String(data[1])); list.add(point); } } } return list; } /** * Gets a list of lines of the POI object with the given term. It only * checks the {@link citysdk.tourism.client.poi.base.Line} geometry. * * @param poi * the object to get the data. * @param term * the term to be used. * @return a list (of {@link citysdk.tourism.client.parser.data.LineContent} * ) containing all lines with the given term or an empty list. */ public static List<LineContent> getLocationLine(POI poi, Term term) { List<LineContent> list = new ArrayList<LineContent>(); if (poi == null) return list; Location location = poi.getLocation(); LineContent line; if (location.hasLines()) { List<Line> lines = location.getLine(); for (Line l : lines) { if (l.getTerm().equals(term.getTerm())) { String data[] = l.getLineString().getPosList().split(","); String point1[] = data[0].split(" "); String point2[] = data[1].split(" "); line = new LineContent(new LocationContent(new String( point1[0]), new String(point1[1])), new LocationContent(new String(point2[2]), new String(point2[3]))); list.add(line); } } } return list; } /** * Gets a list of polygons of the POI object with the given term. It only * checks the {@link citysdk.tourism.client.poi.base.Polygon} geometry. * * @param poi * the object to get the data. * @param term * the term to be used. * @return a list (of * {@link citysdk.tourism.client.parser.data.PolygonContent}) * containing all polygons with the given term or an empty list. */ public static List<PolygonContent> getLocationPolygon(POI poi, Term term) { List<PolygonContent> list = new ArrayList<PolygonContent>(); if (poi == null) return list; Location location = poi.getLocation(); PolygonContent polygon; if (location.hasPolygons()) { List<Polygon> polygons = location.getPolygon(); for (Polygon p : polygons) { if (p.getTerm().equals(term.getTerm())) { polygon = new PolygonContent(); String data[] = p.getSimplePolygon().getPosList() .split(","); for (int i = 0; i < data.length; i++) { String posList[] = data[i].split(" "); polygon.addLocation(new LocationContent( new String(posList[0]), new String( posList[1]))); } list.add(polygon); } } } return list; } /** * Gets the contacts in vCard format * * @param poi * the object to get the data. * @return a String in vCard format containing the information or null if none were found. */ public static String getContacts(POI poi) { if (poi == null) return null; POIBaseType address = poi.getLocation().getAddress(); if (address.getValue().equals("")) return null; else return address.getValue(); } /** * Returns an iCalendar of the given term. * * @param poi * the object to get the data. * @param term * the term to search for. * @return a String in iCalendar format with the given term or null if none were found. */ public static String getCalendar(POI poi, Term term) { if (poi == null) return null; List<POITermType> list = poi.getTime(); for (POITermType type : list) { if (type.getType().equals(CALENDAR_TERM) && type.getTerm().equals(term.getTerm())) { return type.getValue(); } } return null; } /** * Gets all the URI images of the given POI object. * * @param poi * the object to get the data. * @return the list of URIs ( * {@link citysdk.tourism.client.parser.data.ImageContent}) of the * images or an empty list if none were found. */ public static List<ImageContent> getImagesUri(POI poi) { List<ImageContent> images = new ArrayList<ImageContent>(); if (poi == null) return null; List<POITermType> links = poi.getLink(); for (POITermType link : links) { if (link.getTerm().equals(Term.LINK_TERM_RELATED.getTerm()) && link.getType().contains(IMAGE_TERM)) { ImageContent content = new ImageContent(link.getHref()); content.isImgUri(true); images.add(content); } } return images; } /** * Gets the relationship base with a given term. * * @param poi * the object to get the data. * @param term * the term used. * @return a {@link String} * containing the relationship base with the given term or null if * none was found. */ public static String getRelationshipBase(POI poi, Term term) { if (poi == null) return null; if (poi.getLocation().hasRelationships()) { List<Relationship> list = poi.getLocation().getRelationship(); for (Relationship relation : list) { if (relation.getTerm().equals(term.getTerm())) return new String(relation.getBase()); } } return null; } /** * Gets the relationship id with a given term. * * @param poi * the object to get the data. * @param term * the term used. * @return a {@link String} * containing the relationship id with the given term or null if * none was found. */ public static String getRelationshipId(POI poi, Term term) { if (poi == null) return null; if (poi.getLocation().hasRelationships()) { List<Relationship> list = poi.getLocation().getRelationship(); for (Relationship relation : list) { if (relation.getTerm().equals(term.getTerm())) { if (relation.hasTargetPOI()) return new String(relation.getTargetPOI()); else return new String(relation.getTargetEvent()); } } } return null; } /** * Returns the link with a given term. * * @param poi * the object to get the data. * @param term * the term used * @return a {@link String} * containing a link or null if none found. */ public static String getLink(POI poi, Term term) { if (poi == null) return null; List<POITermType> links = poi.getLink(); for (POITermType link : links) { if (link.getTerm().equals(term.getTerm())) { return new String(link.getHref()); } } return null; } /** * Gets the tags within the list of tags in a given language. * * @param list * the list of tags. * @param lang * the wanted language. * @return a list of tags in the given language, or an empty list if none * was found. */ public static List<String> getTags(ListTag list, Locale lang) { List<String> tagList = new ArrayList<String>(); if (list == null) return tagList; for (int i = 0; i < list.getNumTags(); i++) { Tag tag = list.get(i); List<Tag> tagValues = tag.getTags(); for (Tag t : tagValues) { if (parseLocale(t.getLang()).getLanguage().equals( lang.getLanguage())) tagList.add(new String(t.getValue())); } } return tagList; } }
false
true
private static String getValueWithTerm(POI poi, Locale lang, String tag) { if (poi == null) return null; Locale descriptionLang; Locale poiLang = parseLocale(poi.getLang()); String defaultValue = null; List<POIBaseType> descriptions = poi.getDescription(); for (POIBaseType description : descriptions) { if (description.getLang().equals("")) descriptionLang = poiLang; else descriptionLang = parseLocale(description.getLang()); if (description.getType().equals(tag)) { if (lang != null && descriptionLang.getLanguage().equals( defaultLang.getLanguage())) defaultValue = description.getValue(); else if (lang == null) defaultValue = description.getValue(); } else if (description.getType().equals(tag)) { if (lang != null && descriptionLang.getLanguage().equals( lang.getLanguage())) return new String(description.getValue()); else if (lang == null) return new String(description.getValue()); } } return new String(defaultValue); }
private static String getValueWithTerm(POI poi, Locale lang, String tag) { if (poi == null) return null; Locale descriptionLang; Locale poiLang = parseLocale(poi.getLang()); String defaultValue = null; List<POIBaseType> descriptions = poi.getDescription(); for (POIBaseType description : descriptions) { if (description.getLang().equals("")) descriptionLang = poiLang; else descriptionLang = parseLocale(description.getLang()); if (description.getType().equals(tag)) { if (lang != null && descriptionLang.getLanguage().equals( defaultLang.getLanguage())) defaultValue = description.getValue(); else if (lang == null) defaultValue = description.getValue(); } else if (description.getType().equals(tag)) { if (lang != null && descriptionLang.getLanguage().equals( lang.getLanguage())) return description.getValue(); else if (lang == null) return description.getValue(); } } return defaultValue; }
diff --git a/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/resources/ContentDescriptionManagerTest.java b/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/resources/ContentDescriptionManagerTest.java index 4240696bb..a5856ca26 100644 --- a/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/resources/ContentDescriptionManagerTest.java +++ b/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/resources/ContentDescriptionManagerTest.java @@ -1,222 +1,222 @@ /******************************************************************************* * Copyright (c) 2005 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.core.tests.resources; import java.io.ByteArrayInputStream; import java.io.InputStream; import junit.framework.Test; import junit.framework.TestSuite; import org.eclipse.core.internal.resources.ContentDescriptionManager; import org.eclipse.core.internal.resources.Workspace; import org.eclipse.core.resources.*; import org.eclipse.core.runtime.*; import org.eclipse.core.runtime.content.*; public class ContentDescriptionManagerTest extends ResourceTest { private static final String CONTENT_TYPE_RELATED_NATURE2 = "org.eclipse.core.tests.resources.contentTypeRelated2"; private static final String CONTENT_TYPE_RELATED_NATURE1 = "org.eclipse.core.tests.resources.contentTypeRelated1"; public static Test suite() { return new TestSuite(ContentDescriptionManagerTest.class); } public ContentDescriptionManagerTest(String name) { super(name); } protected InputStream projectDescriptionWithNatures(String project, String[] natures) { StringBuffer contents = new StringBuffer("<?xml version=\"1.0\" encoding=\"UTF-8\"?><projectDescription><name>" + project + "</name><natures>"); for (int i = 0; i < natures.length; i++) contents.append("<nature>" + natures[i] + "</nature>"); contents.append("</natures></projectDescription>"); return new ByteArrayInputStream(contents.toString().getBytes()); } public void testNatureContentTypeAssociation() { IContentTypeManager contentTypeManager = Platform.getContentTypeManager(); IContentType baseType = contentTypeManager.getContentType("org.eclipse.core.tests.resources.nature_associated_1"); IContentType derivedType = contentTypeManager.getContentType("org.eclipse.core.tests.resources.nature_associated_2"); assertNotNull("0.1", baseType); assertNotNull("0.2", derivedType); IProject project = getWorkspace().getRoot().getProject("proj1"); IFile file = project.getFile("file.nature-associated"); IFile descFile = project.getFile(IProjectDescription.DESCRIPTION_FILE_NAME); ensureExistsInWorkspace(file, "it really does not matter"); IContentDescription description = null; // originally, project description has no natures try { descFile.setContents(projectDescriptionWithNatures(project.getName(), new String[0]), IResource.FORCE, getMonitor()); } catch (CoreException e) { fail("1.0", e); } waitForCacheFlush(); try { description = file.getContentDescription(); } catch (CoreException e) { fail("1.1", e); } assertNotNull("1.2", description); - assertSame("1.3", derivedType, description.getContentType()); + assertSame("1.3", baseType, description.getContentType()); // change project description to include one of the natures try { descFile.setContents(projectDescriptionWithNatures(project.getName(), new String[] {CONTENT_TYPE_RELATED_NATURE1}), IResource.FORCE, getMonitor()); } catch (CoreException e) { fail("2.0", e); } waitForCacheFlush(); try { description = file.getContentDescription(); } catch (CoreException e) { fail("2.1", e); } assertNotNull("2.2", description); assertSame("2.3", baseType, description.getContentType()); // change project description to include the other nature try { descFile.setContents(projectDescriptionWithNatures(project.getName(), new String[] {CONTENT_TYPE_RELATED_NATURE2}), IResource.FORCE, getMonitor()); } catch (CoreException e) { fail("3.0", e); } waitForCacheFlush(); try { description = file.getContentDescription(); } catch (CoreException e) { fail("3.1", e); } assertNotNull("3.2", description); assertSame("3.3", derivedType, description.getContentType()); // change project description to include both of the natures try { descFile.setContents(projectDescriptionWithNatures(project.getName(), new String[] {CONTENT_TYPE_RELATED_NATURE1, CONTENT_TYPE_RELATED_NATURE2}), IResource.FORCE, getMonitor()); } catch (CoreException e) { fail("4.0", e); } waitForCacheFlush(); try { description = file.getContentDescription(); } catch (CoreException e) { fail("4.1", e); } assertNotNull("4.2", description); - assertSame("4.3", derivedType, description.getContentType()); + assertSame("4.3", baseType, description.getContentType()); // back to no natures try { descFile.setContents(projectDescriptionWithNatures(project.getName(), new String[0]), IResource.FORCE, getMonitor()); } catch (CoreException e) { fail("5.0", e); } waitForCacheFlush(); try { description = file.getContentDescription(); } catch (CoreException e) { fail("5.1", e); } assertNotNull("5.2", description); - assertSame("5.3", derivedType, description.getContentType()); + assertSame("5.3", baseType, description.getContentType()); } public void testBug79151() { IWorkspace workspace = getWorkspace(); IProject project = workspace.getRoot().getProject("MyProject"); IContentTypeManager contentTypeManager = Platform.getContentTypeManager(); IContentType xml = contentTypeManager.getContentType("org.eclipse.core.runtime.xml"); String newExtension = "xml_bug_79151"; IFile file1 = project.getFile("file.xml"); IFile file2 = project.getFile("file." + newExtension); ensureExistsInWorkspace(file1, getContents(CharsetTest.SAMPLE_XML_ISO_8859_1_ENCODING)); ensureExistsInWorkspace(file2, getContents(CharsetTest.SAMPLE_XML_US_ASCII_ENCODING)); // ensure we start in a known state ((Workspace) workspace).getContentDescriptionManager().invalidateCache(true, null); // wait for cache flush to finish waitForCacheFlush(); // cache is new at this point assertEquals("0.9", ContentDescriptionManager.EMPTY_CACHE, ((Workspace) workspace).getContentDescriptionManager().getCacheState()); IContentDescription description1a = null, description1b = null, description1c = null, description1d = null; IContentDescription description2 = null; try { description1a = file1.getContentDescription(); description2 = file2.getContentDescription(); } catch (CoreException e) { fail("1.0", e); } assertNotNull("1.1", description1a); assertEquals("1.2", xml, description1a.getContentType()); assertNull("1.3", description2); try { description1b = file1.getContentDescription(); // ensure it comes from the cache (should be the very same object) assertNotNull(" 2.0", description1b); assertSame("2.1", description1a, description1b); } catch (CoreException e) { fail("2.2", e); } try { // change the content type xml.addFileSpec(newExtension, IContentType.FILE_EXTENSION_SPEC); } catch (CoreException e) { fail("3.0", e); } try { try { description1c = file1.getContentDescription(); description2 = file2.getContentDescription(); } catch (CoreException e) { fail("4.0", e); } // ensure it does *not* come from the cache (should be a different object) assertNotNull("4.1", description1c); assertNotSame("4.2", description1a, description1c); assertEquals("4.3", xml, description1c.getContentType()); assertNotNull("4.4", description2); assertEquals("4.5", xml, description2.getContentType()); } finally { try { // dissociate the xml2 extension from the XML content type xml.removeFileSpec(newExtension, IContentType.FILE_EXTENSION_SPEC); } catch (CoreException e) { fail("4.99", e); } } try { description1d = file1.getContentDescription(); description2 = file2.getContentDescription(); } catch (CoreException e) { fail("5.0", e); } // ensure it does *not* come from the cache (should be a different object) assertNotNull("5.1", description1d); assertNotSame("5.2", description1c, description1d); assertEquals("5.3", xml, description1d.getContentType()); assertNull("5.4", description2); } /** * Blocks the calling thread until the cache flush job completes. */ protected void waitForCacheFlush() { try { Platform.getJobManager().join(ContentDescriptionManager.FAMILY_DESCRIPTION_CACHE_FLUSH, null); } catch (OperationCanceledException e) { //ignore } catch (InterruptedException e) { //ignore } } }
false
true
public void testNatureContentTypeAssociation() { IContentTypeManager contentTypeManager = Platform.getContentTypeManager(); IContentType baseType = contentTypeManager.getContentType("org.eclipse.core.tests.resources.nature_associated_1"); IContentType derivedType = contentTypeManager.getContentType("org.eclipse.core.tests.resources.nature_associated_2"); assertNotNull("0.1", baseType); assertNotNull("0.2", derivedType); IProject project = getWorkspace().getRoot().getProject("proj1"); IFile file = project.getFile("file.nature-associated"); IFile descFile = project.getFile(IProjectDescription.DESCRIPTION_FILE_NAME); ensureExistsInWorkspace(file, "it really does not matter"); IContentDescription description = null; // originally, project description has no natures try { descFile.setContents(projectDescriptionWithNatures(project.getName(), new String[0]), IResource.FORCE, getMonitor()); } catch (CoreException e) { fail("1.0", e); } waitForCacheFlush(); try { description = file.getContentDescription(); } catch (CoreException e) { fail("1.1", e); } assertNotNull("1.2", description); assertSame("1.3", derivedType, description.getContentType()); // change project description to include one of the natures try { descFile.setContents(projectDescriptionWithNatures(project.getName(), new String[] {CONTENT_TYPE_RELATED_NATURE1}), IResource.FORCE, getMonitor()); } catch (CoreException e) { fail("2.0", e); } waitForCacheFlush(); try { description = file.getContentDescription(); } catch (CoreException e) { fail("2.1", e); } assertNotNull("2.2", description); assertSame("2.3", baseType, description.getContentType()); // change project description to include the other nature try { descFile.setContents(projectDescriptionWithNatures(project.getName(), new String[] {CONTENT_TYPE_RELATED_NATURE2}), IResource.FORCE, getMonitor()); } catch (CoreException e) { fail("3.0", e); } waitForCacheFlush(); try { description = file.getContentDescription(); } catch (CoreException e) { fail("3.1", e); } assertNotNull("3.2", description); assertSame("3.3", derivedType, description.getContentType()); // change project description to include both of the natures try { descFile.setContents(projectDescriptionWithNatures(project.getName(), new String[] {CONTENT_TYPE_RELATED_NATURE1, CONTENT_TYPE_RELATED_NATURE2}), IResource.FORCE, getMonitor()); } catch (CoreException e) { fail("4.0", e); } waitForCacheFlush(); try { description = file.getContentDescription(); } catch (CoreException e) { fail("4.1", e); } assertNotNull("4.2", description); assertSame("4.3", derivedType, description.getContentType()); // back to no natures try { descFile.setContents(projectDescriptionWithNatures(project.getName(), new String[0]), IResource.FORCE, getMonitor()); } catch (CoreException e) { fail("5.0", e); } waitForCacheFlush(); try { description = file.getContentDescription(); } catch (CoreException e) { fail("5.1", e); } assertNotNull("5.2", description); assertSame("5.3", derivedType, description.getContentType()); }
public void testNatureContentTypeAssociation() { IContentTypeManager contentTypeManager = Platform.getContentTypeManager(); IContentType baseType = contentTypeManager.getContentType("org.eclipse.core.tests.resources.nature_associated_1"); IContentType derivedType = contentTypeManager.getContentType("org.eclipse.core.tests.resources.nature_associated_2"); assertNotNull("0.1", baseType); assertNotNull("0.2", derivedType); IProject project = getWorkspace().getRoot().getProject("proj1"); IFile file = project.getFile("file.nature-associated"); IFile descFile = project.getFile(IProjectDescription.DESCRIPTION_FILE_NAME); ensureExistsInWorkspace(file, "it really does not matter"); IContentDescription description = null; // originally, project description has no natures try { descFile.setContents(projectDescriptionWithNatures(project.getName(), new String[0]), IResource.FORCE, getMonitor()); } catch (CoreException e) { fail("1.0", e); } waitForCacheFlush(); try { description = file.getContentDescription(); } catch (CoreException e) { fail("1.1", e); } assertNotNull("1.2", description); assertSame("1.3", baseType, description.getContentType()); // change project description to include one of the natures try { descFile.setContents(projectDescriptionWithNatures(project.getName(), new String[] {CONTENT_TYPE_RELATED_NATURE1}), IResource.FORCE, getMonitor()); } catch (CoreException e) { fail("2.0", e); } waitForCacheFlush(); try { description = file.getContentDescription(); } catch (CoreException e) { fail("2.1", e); } assertNotNull("2.2", description); assertSame("2.3", baseType, description.getContentType()); // change project description to include the other nature try { descFile.setContents(projectDescriptionWithNatures(project.getName(), new String[] {CONTENT_TYPE_RELATED_NATURE2}), IResource.FORCE, getMonitor()); } catch (CoreException e) { fail("3.0", e); } waitForCacheFlush(); try { description = file.getContentDescription(); } catch (CoreException e) { fail("3.1", e); } assertNotNull("3.2", description); assertSame("3.3", derivedType, description.getContentType()); // change project description to include both of the natures try { descFile.setContents(projectDescriptionWithNatures(project.getName(), new String[] {CONTENT_TYPE_RELATED_NATURE1, CONTENT_TYPE_RELATED_NATURE2}), IResource.FORCE, getMonitor()); } catch (CoreException e) { fail("4.0", e); } waitForCacheFlush(); try { description = file.getContentDescription(); } catch (CoreException e) { fail("4.1", e); } assertNotNull("4.2", description); assertSame("4.3", baseType, description.getContentType()); // back to no natures try { descFile.setContents(projectDescriptionWithNatures(project.getName(), new String[0]), IResource.FORCE, getMonitor()); } catch (CoreException e) { fail("5.0", e); } waitForCacheFlush(); try { description = file.getContentDescription(); } catch (CoreException e) { fail("5.1", e); } assertNotNull("5.2", description); assertSame("5.3", baseType, description.getContentType()); }
diff --git a/kovu/teamstats/api/TeamStatsAPI.java b/kovu/teamstats/api/TeamStatsAPI.java index 4485ed4..6343d49 100644 --- a/kovu/teamstats/api/TeamStatsAPI.java +++ b/kovu/teamstats/api/TeamStatsAPI.java @@ -1,634 +1,641 @@ package kovu.teamstats.api; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.Socket; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.logging.Logger; import kovu.teamstats.api.exception.CreationNotCompleteException; import kovu.teamstats.api.exception.ServerConnectionLostException; import kovu.teamstats.api.exception.ServerOutdatedException; import kovu.teamstats.api.exception.ServerRejectionException; import kovu.teamstats.api.list.TSAList; import net.ae97.teamstats.ClientRequest; import net.ae97.teamstats.networking.Packet; import net.ae97.teamstats.networking.PacketListener; import net.ae97.teamstats.networking.PacketSender; import net.minecraft.client.Minecraft; /** * The TeamStats API class. This handles all the server-related requests. This * should be used to get info from the server. * * @author Lord_Ralex * @version 0.3 * @since 0.1 */ public final class TeamStatsAPI { private static TeamStatsAPI api; private static final String MAIN_SERVER_URL; private static final int SERVER_PORT; private final String name; private String session; private Socket connection; private final PacketListener packetListener; private final PacketSender packetSender; private final List<String> friendList = new TSAList<String>(); private final Map<String, Map<String, Object>> friendStats = new ConcurrentHashMap<String, Map<String, Object>>(); private final List<String> friendRequests = new TSAList<String>(); private final UpdaterThread updaterThread = new UpdaterThread(); private final Map<String, Object> stats = new ConcurrentHashMap<String, Object>(); private final List<String> newFriends = new TSAList<String>(); private final List<String> newRequests = new TSAList<String>(); private final List<String> newlyRemovedFriends = new TSAList<String>(); private final List<String> onlineFriends = new TSAList<String>(); private final int UPDATE_TIMER = 60; //time this means is set when sent to executor service private boolean online = false; private static final short API_VERSION = 3; private boolean was_set_up = false; private final ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor(); private final ScheduledFuture task; static { //enter the server url here where the main bouncer is MAIN_SERVER_URL = "teamstats.ae97.net"; //enter the port the bouncer runs off of here SERVER_PORT = 19325; } public TeamStatsAPI(String aName, String aSession) throws ServerRejectionException, IOException, ClassNotFoundException { name = aName; session = aSession; connection = new Socket(MAIN_SERVER_URL, SERVER_PORT); PacketSender tempSender = new PacketSender(connection.getOutputStream()); PacketListener tempListener = new PacketListener(connection.getInputStream()); tempListener.start(); Packet getServer = new Packet(ClientRequest.GETSERVER); tempSender.sendPacket(getServer); Packet p = tempListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET); tempListener.interrupt(); String SERVER_URL = null; Object o = p.getData("ip"); if (o instanceof String) { SERVER_URL = (String) o; } connection.close(); if (SERVER_URL == null || SERVER_URL.equalsIgnoreCase("NONODE")) { throw new ServerRejectionException("There is no node open"); } String link = (String) p.getData("ip"); int port = (Integer) p.getData("port"); short server_version = (Short) p.getData("version"); if (server_version != API_VERSION) { throw new ServerOutdatedException(); } connection = new Socket(link, port); packetListener = new PacketListener(connection.getInputStream()); packetSender = new PacketSender(connection.getOutputStream()); packetListener.start(); Packet pac = new Packet(ClientRequest.OPENCONNECTION); pac.addData("name", name).addData("session", session); packetSender.sendPacket(pac); Packet response = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET); boolean isAccepted = (Boolean) response.getData("reply"); if (!isAccepted) { throw new ServerRejectionException(); } task = service.scheduleAtFixedRate(updaterThread, UPDATE_TIMER, UPDATE_TIMER, TimeUnit.SECONDS); online = true; was_set_up = true; } /** * Gets the stats for each friend that is registered by the server. This can * throw an IOException if the server rejects the client communication or an * issue occurs when reading the data. * * @return Mapping of friends and their stats * @throws IOException Thrown when server fails to send data or if server * rejects communication */ public Map<String, Map<String, Object>> getFriendStats() throws IOException { wasSetup(); return friendStats; } /** * Returns the map's toString form of the friend's stats. THIS IS * DEPRECATED, REFER TO NOTES FOR NEW METHOD * * @param friendName Name of friend * @return String version of the stats * @throws IOException */ public String getFriendState(String friendName) throws IOException { wasSetup(); return friendStats.get(friendName).toString(); } /** * Gets the stats for a single friend. If the friend requested is not an * actual friend, this will return null. * * @param friendName The friend to get the stats for * @return The stats in a map * @throws IOException Thrown when server fails to send data or if server * rejects communication */ public Map<String, Object> getFriendStat(String friendName) throws IOException { wasSetup(); return friendStats.get(friendName); } /** * Gets the specific value for a certain stat for a friend. The key is the * stat name. * * @param friendName Name of friend * @param key Key of stat * @return Value of the friend's key, or null if not one * @throws IOException */ public Object getFriendStat(String friendName, String key) throws IOException { wasSetup(); key = key.toLowerCase(); Map<String, Object> stat = friendStats.get(friendName); if (stat == null) { return null; } else { return stat.get(key); } } /** * Gets all accepted friends. * * @return An array of all friends accepted * @throws IOException Thrown when server fails to send data or if server * rejects communication */ public String[] getFriends() throws IOException { wasSetup(); return friendList.toArray(new String[0]); } /** * Sends the stats to the server. This will never return false. If the * connection is rejected, this will throw an IOException. * * @param key Key to set * @param value The value for this key * @return True if connection was successful. * @throws IOException Thrown when server fails to send data or if server * rejects communication */ public boolean updateStats(String key, Object value) throws IOException { wasSetup(); stats.put(key.toLowerCase().trim(), value); return true; } /** * Sends the stats to the server. This will never return false. If the * connection is rejected, this will throw an IOException. * * @param map Map of values to set * @return True if connection was successful. * @throws IOException Thrown when server fails to send data or if server * rejects communication */ public boolean updateStats(Map<String, ? extends Object> map) throws IOException { for (String key : map.keySet()) { updateStats(key, map.get(key)); } return true; } /** * Gets a list of friend requests the user has. This will return names of * those that want to friend this user. * * @return Array of friend requests to the user * @throws IOException Thrown when server fails to send data or if server * rejects communication */ public String[] getFriendRequests() throws IOException { wasSetup(); return friendRequests.toArray(new String[0]); } /** * Requests a friend addition. This will not add them, just request that the * person add them. The return is just for the connection, not for the * friend request. * * @param name Name of friend to add/request * @return True if request was successful * @throws IOException Thrown when server fails to send data or if server * rejects communication */ public boolean addFriend(String name) throws IOException { wasSetup(); return friendList.add(name); } /** * Removes a friend. This will take place once used and any friend list will * be updated. * * @param name Name of friend to remove * @return True if connection was successful * @throws IOException Thrown when server fails to send data or if server * rejects communication */ public boolean removeFriend(String name) throws IOException { wasSetup(); return friendList.remove(name); } /** * Gets the list of new requests to this user. This will also clear the list * if true is passed. * * @param reset Whether to clear the list. True will remove the list after * returning it. * @return Names of new friend requests */ public String[] getNewFriendRequests(boolean reset) throws IOException { wasSetup(); String[] newFriendsToReturn = newRequests.toArray(new String[0]); if (reset) { newRequests.clear(); } return newFriendsToReturn; } /** * Gets the list of removed friends to this user. This will also clear the * list if true is passed. * * @param reset Whether to clear the list. True will remove the list after * returning it. * @return Names of newly removed friends */ public String[] getRemovedFriends(boolean reset) throws IOException { wasSetup(); String[] newFriendsToReturn = newlyRemovedFriends.toArray(new String[0]); if (reset) { newlyRemovedFriends.clear(); } return newFriendsToReturn; } /** * Gets the list of new friends to this user. This will also clear the list * if true is passed. * * @param reset Whether to clear the list. True will remove the list after * returning it. * @return Names of new friends */ public String[] getNewFriends(boolean reset) throws IOException { wasSetup(); String[] newFriendsToReturn = newFriends.toArray(new String[0]); if (reset) { newFriends.clear(); } return newFriendsToReturn; } /** * Gets the list of new requests to this user. This will also clear the * list. * * @return Names of new friend requests */ public String[] getNewFriendRequests() throws IOException { wasSetup(); return getNewFriendRequests(true); } /** * Gets the list of removed friends to this user. This will also clear the * list. * * @return Names of newly removed friends */ public String[] getRemovedFriends() throws IOException { wasSetup(); return getRemovedFriends(true); } /** * Gets the list of new friends to this user. This will also clear the list. * * @return Names of new friends */ public String[] getNewFriends() throws IOException { wasSetup(); return getNewFriends(true); } /** * Returns an array of friends that are online based on the cache. * * @return Array of friends who are online */ public String[] getOnlineFriends() throws IOException { wasSetup(); return onlineFriends.toArray(new String[0]); } /** * Checks to see if a particular friend is online. * * @param name Name of friend * @return True if they are online, false otherwise */ public boolean isFriendOnline(String name) throws IOException { wasSetup(); return onlineFriends.contains(name); } /** * Forces the client to update the stats and such. This forces the update * thread to run. * * @throws IOException */ public void forceUpdate() throws IOException { wasSetup(); synchronized (task) { if (!task.isDone()) { task.notify(); } else { throw new ServerConnectionLostException(); } } } /** * Checks to see if the client is still connected to the server and if the * update thread is running. * * @return True if the update thread is alive, false otherwise. * @throws IOException */ public boolean isChecking() throws IOException { wasSetup(); boolean done; synchronized (task) { done = task.isDone(); } return !done; } /** * Changes the online status of the client. This is instant to the server * and tells the server to turn the client offline. * * @param newStatus New online status * @return The new online status * @throws IOException */ public boolean changeOnlineStatus(boolean newStatus) throws IOException { wasSetup(); online = newStatus; Packet packet = new Packet(ClientRequest.CHANGEONLINE); packet.addData("session", Minecraft.getMinecraft().session.sessionId); packet.addData("online", online); packetSender.sendPacket(packet); Packet reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET); if ((Boolean) reply.getData("reply")) { return online; } else { throw new ServerRejectionException(); } } /** * Changes the online status of the client. This is instant to the server * and tells the server to turn the client offline. * * @return The new online status * @throws IOException */ public boolean changeOnlineStatus() throws IOException { wasSetup(); return changeOnlineStatus(!online); } /** * Returns a boolean where true means the API was completely setup and * connections were successful, otherwise an exception is thrown. This only * checks the initial connection, not the later connections. Use * isChecking() for that. * * @return True if API was set up. * @throws IOException If api was not created right, exception thrown */ public boolean wasSetup() throws IOException { if (was_set_up) { return true; } else { throw new CreationNotCompleteException(); } } public static void setAPI(TeamStatsAPI apiTemp) throws IllegalAccessException { if (apiTemp == null) { throw new IllegalAccessException("The API instance cannot be null"); } if (api != null) { if (api == apiTemp) { return; } else { throw new IllegalAccessException("Cannot change the API once it is set"); } } api = apiTemp; } public static TeamStatsAPI getAPI() { return api; } private class UpdaterThread implements Runnable { @Override public void run() { if (online) { try { Packet packet = new Packet(ClientRequest.GETFRIENDS); packet.addData("session", Minecraft.getMinecraft().session.sessionId); packetSender.sendPacket(packet); String[] friends; Packet reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET); if (!(Boolean) reply.getData("reply")) { throw new ServerRejectionException((String) reply.getData("reason")); } String namesList = (String) packet.getData("names"); if (namesList != null) { friends = namesList.split(" "); } else { friends = new String[0]; } //check current friend list, removing and adding name differences List<String> addFriend = new TSAList<String>(); addFriend.addAll(friendList); for (String existing : friends) { addFriend.remove(existing); } for (String name : addFriend) { packet = new Packet(ClientRequest.ADDFRIEND); packet.addData("session", Minecraft.getMinecraft().session.sessionId); packet.addData("name", name); packetSender.sendPacket(packet); reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET); if (!(Boolean) reply.getData("reply")) { throw new ServerRejectionException(); } } List<String> removeFriend = new ArrayList<String>(); removeFriend.addAll(Arrays.asList(friends)); for (String existing : friendList) { removeFriend.remove(existing); } for (String name : removeFriend) { packet = new Packet(ClientRequest.REMOVEFRIEND); packet.addData("session", Minecraft.getMinecraft().session.sessionId); packet.addData("name", name); packetSender.sendPacket(packet); reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET); if (!(Boolean) reply.getData("reply")) { throw new ServerRejectionException(); } } //send new stats for this person String pStats = ""; for (String key : stats.keySet()) { pStats += key + ":" + stats.get(key) + " "; } pStats = pStats.trim(); packet = new Packet(ClientRequest.UPDATESTATS); packet.addData("session", Minecraft.getMinecraft().session.sessionId); packet.addData("stats", pStats); reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET); if (!(Boolean) reply.getData("reply")) { throw new ServerRejectionException(); } //check friend requests packet = new Packet(ClientRequest.GETREQUESTS); packet.addData("session", Minecraft.getMinecraft().session.sessionId); packetSender.sendPacket(packet); reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET); if (!(Boolean) reply.getData("reply")) { throw new ServerRejectionException(); } String names = (String) reply.getData("names"); String[] old = friendRequests.toArray(new String[0]); friendRequests.clear(); if (names != null) { friendRequests.addAll(Arrays.asList(names.split(" "))); } if (newRequests.containsAll(Arrays.asList(old))) { } for (String name : old) { if (!newRequests.contains(name)) { newRequests.add(name); } } packet = new Packet(ClientRequest.GETFRIENDS); packet.addData("session", Minecraft.getMinecraft().session.sessionId); packetSender.sendPacket(packet); reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET); if (!(Boolean) reply.getData("reply")) { throw new ServerRejectionException(); } - List<String> updateFriends = Arrays.asList(((String) reply.getData("names")).split(" ")); + String aNameList = (String) reply.getData("names"); + List<String> updateFriends = new ArrayList<String>(); + if (aNameList != null) { + updateFriends = Arrays.asList(aNameList.split(" ")); + if (updateFriends == null) { + updateFriends = new ArrayList<String>(); + } + } for (String name : updateFriends) { if (friendList.contains(name)) { continue; } newFriends.add(name); } for (String name : friendList) { if (updateFriends.contains(name)) { continue; } newlyRemovedFriends.add(name); } friendList.clear(); friendList.addAll(updateFriends); //get stats for friends in list friendStats.clear(); onlineFriends.clear(); for (String friendName : friendList) { Packet send = new Packet(ClientRequest.GETSTATS); send.addData("session", Minecraft.getMinecraft().session.sessionId); send.addData("name", friendName); packetSender.sendPacket(send); reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET); if (!(Boolean) reply.getData("reply")) { throw new ServerRejectionException(); } String stat = (String) reply.getData("stats"); Map<String, Object> friendS = new HashMap<String, Object>(); String[] parts = stat.split(" "); for (String string : parts) { friendS.put(string.split(":")[0].toLowerCase().trim(), string.split(":")[1]); } friendStats.put(friendName, friendS); Packet send2 = new Packet(ClientRequest.GETONLINESTATUS); send2.addData("session", Minecraft.getMinecraft().session.sessionId); send2.addData("name", friendName); packetSender.sendPacket(send2); reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET); if (!(Boolean) reply.getData("reply")) { throw new ServerRejectionException(); } boolean isOnline = (Boolean) reply.getData("online"); if (isOnline) { onlineFriends.add(friendName); } } } catch (Exception ex) { synchronized (System.out) { System.out.println(ex.getMessage()); StackTraceElement[] el = ex.getStackTrace(); for (StackTraceElement e : el) { System.out.println(e.toString()); } online = false; } } } else { new ServerConnectionLostException().printStackTrace(System.out); online = false; } } } }
true
true
public void run() { if (online) { try { Packet packet = new Packet(ClientRequest.GETFRIENDS); packet.addData("session", Minecraft.getMinecraft().session.sessionId); packetSender.sendPacket(packet); String[] friends; Packet reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET); if (!(Boolean) reply.getData("reply")) { throw new ServerRejectionException((String) reply.getData("reason")); } String namesList = (String) packet.getData("names"); if (namesList != null) { friends = namesList.split(" "); } else { friends = new String[0]; } //check current friend list, removing and adding name differences List<String> addFriend = new TSAList<String>(); addFriend.addAll(friendList); for (String existing : friends) { addFriend.remove(existing); } for (String name : addFriend) { packet = new Packet(ClientRequest.ADDFRIEND); packet.addData("session", Minecraft.getMinecraft().session.sessionId); packet.addData("name", name); packetSender.sendPacket(packet); reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET); if (!(Boolean) reply.getData("reply")) { throw new ServerRejectionException(); } } List<String> removeFriend = new ArrayList<String>(); removeFriend.addAll(Arrays.asList(friends)); for (String existing : friendList) { removeFriend.remove(existing); } for (String name : removeFriend) { packet = new Packet(ClientRequest.REMOVEFRIEND); packet.addData("session", Minecraft.getMinecraft().session.sessionId); packet.addData("name", name); packetSender.sendPacket(packet); reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET); if (!(Boolean) reply.getData("reply")) { throw new ServerRejectionException(); } } //send new stats for this person String pStats = ""; for (String key : stats.keySet()) { pStats += key + ":" + stats.get(key) + " "; } pStats = pStats.trim(); packet = new Packet(ClientRequest.UPDATESTATS); packet.addData("session", Minecraft.getMinecraft().session.sessionId); packet.addData("stats", pStats); reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET); if (!(Boolean) reply.getData("reply")) { throw new ServerRejectionException(); } //check friend requests packet = new Packet(ClientRequest.GETREQUESTS); packet.addData("session", Minecraft.getMinecraft().session.sessionId); packetSender.sendPacket(packet); reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET); if (!(Boolean) reply.getData("reply")) { throw new ServerRejectionException(); } String names = (String) reply.getData("names"); String[] old = friendRequests.toArray(new String[0]); friendRequests.clear(); if (names != null) { friendRequests.addAll(Arrays.asList(names.split(" "))); } if (newRequests.containsAll(Arrays.asList(old))) { } for (String name : old) { if (!newRequests.contains(name)) { newRequests.add(name); } } packet = new Packet(ClientRequest.GETFRIENDS); packet.addData("session", Minecraft.getMinecraft().session.sessionId); packetSender.sendPacket(packet); reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET); if (!(Boolean) reply.getData("reply")) { throw new ServerRejectionException(); } List<String> updateFriends = Arrays.asList(((String) reply.getData("names")).split(" ")); for (String name : updateFriends) { if (friendList.contains(name)) { continue; } newFriends.add(name); } for (String name : friendList) { if (updateFriends.contains(name)) { continue; } newlyRemovedFriends.add(name); } friendList.clear(); friendList.addAll(updateFriends); //get stats for friends in list friendStats.clear(); onlineFriends.clear(); for (String friendName : friendList) { Packet send = new Packet(ClientRequest.GETSTATS); send.addData("session", Minecraft.getMinecraft().session.sessionId); send.addData("name", friendName); packetSender.sendPacket(send); reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET); if (!(Boolean) reply.getData("reply")) { throw new ServerRejectionException(); } String stat = (String) reply.getData("stats"); Map<String, Object> friendS = new HashMap<String, Object>(); String[] parts = stat.split(" "); for (String string : parts) { friendS.put(string.split(":")[0].toLowerCase().trim(), string.split(":")[1]); } friendStats.put(friendName, friendS); Packet send2 = new Packet(ClientRequest.GETONLINESTATUS); send2.addData("session", Minecraft.getMinecraft().session.sessionId); send2.addData("name", friendName); packetSender.sendPacket(send2); reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET); if (!(Boolean) reply.getData("reply")) { throw new ServerRejectionException(); } boolean isOnline = (Boolean) reply.getData("online"); if (isOnline) { onlineFriends.add(friendName); } } } catch (Exception ex) { synchronized (System.out) { System.out.println(ex.getMessage()); StackTraceElement[] el = ex.getStackTrace(); for (StackTraceElement e : el) { System.out.println(e.toString()); } online = false; } } } else { new ServerConnectionLostException().printStackTrace(System.out); online = false; } }
public void run() { if (online) { try { Packet packet = new Packet(ClientRequest.GETFRIENDS); packet.addData("session", Minecraft.getMinecraft().session.sessionId); packetSender.sendPacket(packet); String[] friends; Packet reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET); if (!(Boolean) reply.getData("reply")) { throw new ServerRejectionException((String) reply.getData("reason")); } String namesList = (String) packet.getData("names"); if (namesList != null) { friends = namesList.split(" "); } else { friends = new String[0]; } //check current friend list, removing and adding name differences List<String> addFriend = new TSAList<String>(); addFriend.addAll(friendList); for (String existing : friends) { addFriend.remove(existing); } for (String name : addFriend) { packet = new Packet(ClientRequest.ADDFRIEND); packet.addData("session", Minecraft.getMinecraft().session.sessionId); packet.addData("name", name); packetSender.sendPacket(packet); reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET); if (!(Boolean) reply.getData("reply")) { throw new ServerRejectionException(); } } List<String> removeFriend = new ArrayList<String>(); removeFriend.addAll(Arrays.asList(friends)); for (String existing : friendList) { removeFriend.remove(existing); } for (String name : removeFriend) { packet = new Packet(ClientRequest.REMOVEFRIEND); packet.addData("session", Minecraft.getMinecraft().session.sessionId); packet.addData("name", name); packetSender.sendPacket(packet); reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET); if (!(Boolean) reply.getData("reply")) { throw new ServerRejectionException(); } } //send new stats for this person String pStats = ""; for (String key : stats.keySet()) { pStats += key + ":" + stats.get(key) + " "; } pStats = pStats.trim(); packet = new Packet(ClientRequest.UPDATESTATS); packet.addData("session", Minecraft.getMinecraft().session.sessionId); packet.addData("stats", pStats); reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET); if (!(Boolean) reply.getData("reply")) { throw new ServerRejectionException(); } //check friend requests packet = new Packet(ClientRequest.GETREQUESTS); packet.addData("session", Minecraft.getMinecraft().session.sessionId); packetSender.sendPacket(packet); reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET); if (!(Boolean) reply.getData("reply")) { throw new ServerRejectionException(); } String names = (String) reply.getData("names"); String[] old = friendRequests.toArray(new String[0]); friendRequests.clear(); if (names != null) { friendRequests.addAll(Arrays.asList(names.split(" "))); } if (newRequests.containsAll(Arrays.asList(old))) { } for (String name : old) { if (!newRequests.contains(name)) { newRequests.add(name); } } packet = new Packet(ClientRequest.GETFRIENDS); packet.addData("session", Minecraft.getMinecraft().session.sessionId); packetSender.sendPacket(packet); reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET); if (!(Boolean) reply.getData("reply")) { throw new ServerRejectionException(); } String aNameList = (String) reply.getData("names"); List<String> updateFriends = new ArrayList<String>(); if (aNameList != null) { updateFriends = Arrays.asList(aNameList.split(" ")); if (updateFriends == null) { updateFriends = new ArrayList<String>(); } } for (String name : updateFriends) { if (friendList.contains(name)) { continue; } newFriends.add(name); } for (String name : friendList) { if (updateFriends.contains(name)) { continue; } newlyRemovedFriends.add(name); } friendList.clear(); friendList.addAll(updateFriends); //get stats for friends in list friendStats.clear(); onlineFriends.clear(); for (String friendName : friendList) { Packet send = new Packet(ClientRequest.GETSTATS); send.addData("session", Minecraft.getMinecraft().session.sessionId); send.addData("name", friendName); packetSender.sendPacket(send); reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET); if (!(Boolean) reply.getData("reply")) { throw new ServerRejectionException(); } String stat = (String) reply.getData("stats"); Map<String, Object> friendS = new HashMap<String, Object>(); String[] parts = stat.split(" "); for (String string : parts) { friendS.put(string.split(":")[0].toLowerCase().trim(), string.split(":")[1]); } friendStats.put(friendName, friendS); Packet send2 = new Packet(ClientRequest.GETONLINESTATUS); send2.addData("session", Minecraft.getMinecraft().session.sessionId); send2.addData("name", friendName); packetSender.sendPacket(send2); reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET); if (!(Boolean) reply.getData("reply")) { throw new ServerRejectionException(); } boolean isOnline = (Boolean) reply.getData("online"); if (isOnline) { onlineFriends.add(friendName); } } } catch (Exception ex) { synchronized (System.out) { System.out.println(ex.getMessage()); StackTraceElement[] el = ex.getStackTrace(); for (StackTraceElement e : el) { System.out.println(e.toString()); } online = false; } } } else { new ServerConnectionLostException().printStackTrace(System.out); online = false; } }
diff --git a/branches/kernel-1.1.x/api/src/main/java/org/sakaiproject/util/RequestFilter.java b/branches/kernel-1.1.x/api/src/main/java/org/sakaiproject/util/RequestFilter.java index abdb93dd..2b38e40e 100644 --- a/branches/kernel-1.1.x/api/src/main/java/org/sakaiproject/util/RequestFilter.java +++ b/branches/kernel-1.1.x/api/src/main/java/org/sakaiproject/util/RequestFilter.java @@ -1,1512 +1,1512 @@ /********************************************************************************** * $URL$ * $Id$ *********************************************************************************** * * Copyright (c) 2005, 2006, 2007, 2008 Sakai Foundation * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.osedu.org/licenses/ECL-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.sakaiproject.util; import java.io.File; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.security.Principal; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponseWrapper; import javax.servlet.http.HttpSession; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadBase; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.sakaiproject.component.api.ServerConfigurationService; import org.sakaiproject.event.api.UsageSession; import org.sakaiproject.event.api.UsageSessionService; import org.sakaiproject.thread_local.cover.ThreadLocalManager; import org.sakaiproject.tool.api.Session; import org.sakaiproject.tool.api.Tool; import org.sakaiproject.tool.api.ToolSession; import org.sakaiproject.tool.cover.SessionManager; /** * RequestFilter Filters all requests to Sakai tools. It is responsible for keeping the Sakai session, done using a cookie to the * end user's browser storing the user's session id. */ public class RequestFilter implements Filter { /** Our log (commons). */ private static Log M_log = LogFactory.getLog(RequestFilter.class); /** The request attribute name used to store the Sakai session. */ public static final String ATTR_SESSION = "sakai.session"; /** The request attribute name used to ask the RequestFilter to output * a client cookie at the end of the request cycle. */ public static final String ATTR_SET_COOKIE = "sakai.set.cookie"; /** The request attribute name (and value) used to indicated that the request has been filtered. */ public static final String ATTR_FILTERED = "sakai.filtered"; /** The request attribute name (and value) used to indicated that file uploads have been parsed. */ public static final String ATTR_UPLOADS_DONE = "sakai.uploads.done"; /** The request attribute name (and value) used to indicated that character encoding has been set. */ public static final String ATTR_CHARACTER_ENCODING_DONE = "sakai.character.encoding.done"; /** The request attribute name used to indicated that the *response* has been redirected. */ public static final String ATTR_REDIRECT = "sakai.redirect"; /** The request parameter name used to indicated that the request is automatic, not from a user action. */ public static final String PARAM_AUTO = "auto"; /** Config parameter to control http session handling. */ public static final String CONFIG_SESSION = "http.session"; /** Config parameter to control whether to check the request principal before any cookie to establish a session */ public static final String CONFIG_SESSION_AUTH = "sakai.session.auth"; /** Config parameter to control remote user handling. */ public static final String CONFIG_REMOTE_USER = "remote.user"; /** Config parameter to control tool placement URL en/de-coding. */ public static final String CONFIG_TOOL_PLACEMENT = "tool.placement"; /** Config parameter to control whether to set the character encoding on the request. Default is true. */ public static final String CONFIG_CHARACTER_ENCODING_ENABLED = "encoding.enabled"; /** Config parameter which to control character encoding to apply to the request. Default is UTF-8. */ public static final String CONFIG_CHARACTER_ENCODING = "encoding"; /** * Config parameter to control whether the request filter parses file uploads. Default is true. If false, the tool will need to * provide its own upload filter that executes BEFORE the Sakai request filter. */ public static final String CONFIG_UPLOAD_ENABLED = "upload.enabled"; /** * Config parameter to control the maximum allowed upload size (in MEGABYTES) from the browser.<br /> * If defined on the filter, overrides the system property. Default is 1 (one megabyte).<br /> * This is an aggregate limit on the sum of all files included in a single request.<br /> * Also used as a per-request request parameter, encoded in the URL, to set the max for that particular request. */ public static final String CONFIG_UPLOAD_MAX = "upload.max"; /** * System property to control the maximum allowed upload size (in MEGABYTES) from the browser. Default is 1 (one megabyte). This * is an aggregate limit on the sum of all files included in a single request. */ public static final String SYSTEM_UPLOAD_MAX = "sakai.content.upload.max"; /** * System property to control the maximum allowed upload size (in MEGABYTES) from any other method - system wide, request * filter, or per-request. */ public static final String SYSTEM_UPLOAD_CEILING = "sakai.content.upload.ceiling"; /** * Config parameter (in bytes) to control the threshold at which to store uploaded files on-disk (temporarily) instead of * in-memory. Default is 1024 bytes. */ public static final String CONFIG_UPLOAD_THRESHOLD = "upload.threshold"; /** * Config parameter to continue (or abort, if false) upload field processing if there's a file upload max size exceeded * exception. */ protected static final String CONFIG_CONTINUE = "upload.continueOverMax"; /** * Config parameter to treat the max upload size as for the individual files in the request (or, if false, for the entire * request). */ protected static final String CONFIG_MAX_PER_FILE = "upload.maxPerFile"; /** * Config parameter that specifies the absolute path of a temporary directory in which to store file uploads. Default is the * servlet container temporary directory. Note that this is TRANSIENT storage, used by the commons-fileupload API. The files * must be renamed or otherwise processed (by the tool through the commons-fileupload API) in order for the data to become * permenant. */ public static final String CONFIG_UPLOAD_DIR = "upload.dir"; /** System property to control the temporary directory in which to store file uploads. */ public static final String SYSTEM_UPLOAD_DIR = "sakai.content.upload.dir"; /** Config parameter to set the servlet context for context based session (overriding the servlet's context name). */ public static final String CONFIG_CONTEXT = "context"; /** sakaiHttpSession setting for don't do anything. */ protected final static int CONTAINER_SESSION = 0; /** sakaiHttpSession setting for use the sakai wide session. */ protected final static int SAKAI_SESSION = 1; /** sakaiHttpSession setting for use the context session. */ protected final static int CONTEXT_SESSION = 2; /** sakaiHttpSession setting for use the tool session, in any, else context. */ protected final static int TOOL_SESSION = 3; /** Key in the ThreadLocalManager for binding our remoteUser preference. */ protected final static String CURRENT_REMOTE_USER = "org.sakaiproject.util.RequestFilter.remote_user"; /** Key in the ThreadLocalManager for binding our http session preference. */ protected final static String CURRENT_HTTP_SESSION = "org.sakaiproject.util.RequestFilter.http_session"; /** Key in the ThreadLocalManager for binding our context id. */ protected final static String CURRENT_CONTEXT = "org.sakaiproject.util.RequestFilter.context"; /** Key in the ThreadLocalManager for access to the current http request object. */ public final static String CURRENT_HTTP_REQUEST = "org.sakaiproject.util.RequestFilter.http_request"; /** Key in the ThreadLocalManager for access to the current http response object. */ public final static String CURRENT_HTTP_RESPONSE = "org.sakaiproject.util.RequestFilter.http_response"; /** Key in the ThreadLocalManager for access to the current servlet context. */ public final static String CURRENT_SERVLET_CONTEXT = "org.sakaiproject.util.RequestFilter.servlet_context"; /** The "." character */ protected static final String DOT = "."; /** The name of the system property that will be used when setting the value of the session cookie. */ protected static final String SAKAI_SERVERID = "sakai.serverId"; /** The name of the system property that will be used when setting the name of the session cookie. */ protected static final String SAKAI_COOKIE_NAME = "sakai.cookieName"; /** The name of the system property that will be used when setting the domain of the session cookie. */ protected static final String SAKAI_COOKIE_DOMAIN = "sakai.cookieDomain"; /** The name of the Sakai property to disable setting the HttpOnly attribute on the cookie (if false). */ protected static final String SAKAI_COOKIE_HTTP_ONLY = "sakai.cookieHttpOnly"; /** The name of the Sakai property to allow passing a session id in the ATTR_SESSION request parameter */ protected static final String SAKAI_SESSION_PARAM_ALLOW = "session.parameter.allow"; /** If true, we deliver the Sakai wide session as the Http session for each request. */ protected int m_sakaiHttpSession = TOOL_SESSION; /** If true, we deliver the Sakai end user enterprise id as the remote user in each request. */ protected boolean m_sakaiRemoteUser = true; /** If true, we encode / decode the tool placement using the a URL parameter. */ protected boolean m_toolPlacement = true; /** Our contex (i.e. servlet context) id. */ protected String m_contextId = null; protected String m_characterEncoding = "UTF-8"; protected boolean m_characterEncodingEnabled = true; protected boolean m_uploadEnabled = true; protected boolean m_checkPrincipal = false; protected long m_uploadMaxSize = 1L * 1024L * 1024L; protected long m_uploadCeiling = 1L * 1024L * 1024L; protected int m_uploadThreshold = 1024; protected String m_uploadTempDir = null; protected boolean m_displayModJkWarning = true; /** Default is to abort further upload processing if the max is exceeded. */ protected boolean m_uploadContinue = false; /** Default is to treat the m_uploadMaxSize as for the entire request, not per file. */ protected boolean m_uploadMaxPerFile = false; /** The servlet context for the filter. */ protected ServletContext m_servletContext = null; /** Is this a Terracotta clustered environment? */ protected boolean TERRACOTTA_CLUSTER = false; /** Allow setting the cookie in a request parameter */ protected boolean m_sessionParamAllow = false; /** The name of the cookie we use to keep sakai session. */ protected String cookieName = "JSESSIONID"; protected String cookieDomain = null; /** Set the HttpOnly attribute on the cookie */ protected boolean m_cookieHttpOnly = true; /** * Wraps a request object so we can override some standard behavior. */ public class WrappedRequest extends HttpServletRequestWrapper { /** The Sakai session. */ protected Session m_session = null; /** Our contex (i.e. servlet context) id. */ protected String m_contextId = null; public WrappedRequest(Session s, String contextId, HttpServletRequest req) { super(req); m_session = s; m_contextId = contextId; if (m_toolPlacement) { extractPlacementFromParams(); } } public String getRemoteUser() { // use the "current" setting for this boolean remoteUser = ((Boolean) ThreadLocalManager.get(CURRENT_REMOTE_USER)).booleanValue(); if (remoteUser && (m_session != null) && (m_session.getUserEid() != null)) { return m_session.getUserEid(); } return super.getRemoteUser(); } public HttpSession getSession() { return getSession(true); } public HttpSession getSession(boolean create) { HttpSession rv = null; // use the "current" settings for this int curHttpSession = ((Integer) ThreadLocalManager.get(CURRENT_HTTP_SESSION)).intValue(); String curContext = (String) ThreadLocalManager.get(CURRENT_CONTEXT); switch (curHttpSession) { case CONTAINER_SESSION: { rv = super.getSession(create); break; } case SAKAI_SESSION: { rv = (HttpSession) m_session; break; } case CONTEXT_SESSION: { rv = (HttpSession) m_session.getContextSession(curContext); break; } case TOOL_SESSION: { rv = (HttpSession) SessionManager.getCurrentToolSession(); if (rv == null) { rv = (HttpSession) m_session.getContextSession(curContext); } break; } } return rv; } /** * Pull the specially encoded tool placement id from the request parameters. */ protected void extractPlacementFromParams() { String placementId = getParameter(Tool.PLACEMENT_ID); if (placementId != null) { setAttribute(Tool.PLACEMENT_ID, placementId); } } } /** * Wraps a response object so we can override some standard behavior. */ public class WrappedResponse extends HttpServletResponseWrapper { /** The request. */ protected HttpServletRequest m_req = null; /** Wrapped Response * */ protected HttpServletResponse m_res = null; public WrappedResponse(Session s, HttpServletRequest req, HttpServletResponse res) { super(res); m_req = req; m_res = res; } public String encodeRedirectUrl(String url) { return rewriteURL(url); } public String encodeRedirectURL(String url) { return rewriteURL(url); } public String encodeUrl(String url) { return rewriteURL(url); } public String encodeURL(String url) { return rewriteURL(url); } public void sendRedirect(String url) throws IOException { url = rewriteURL(url); m_req.setAttribute(ATTR_REDIRECT, url); super.sendRedirect(url); } /** * Rewrites the given URL to insert the current tool placement id, if any, as the start of the path * * @param url * The url to rewrite. */ protected String rewriteURL(String url) { if (m_toolPlacement) { // if we have a tool placement to add, add it String placementId = (String) m_req.getAttribute(Tool.PLACEMENT_ID); if (placementId != null) { // compute the URL root "back" to this servlet context (rel and full) StringBuilder full = new StringBuilder(); full.append(m_req.getScheme()); full.append("://"); full.append(m_req.getServerName()); if (((m_req.getServerPort() != 80) && (!m_req.isSecure())) || ((m_req.getServerPort() != 443) && (m_req.isSecure()))) { full.append(":"); full.append(m_req.getServerPort()); } StringBuilder rel = new StringBuilder(); rel.append(m_req.getContextPath()); full.append(rel.toString()); // if we match the fullUrl, or the relUrl, assume that this is a URL back to this servlet if ((url.startsWith(full.toString()) || url.startsWith(rel.toString()))) { // put the placementId in as a parameter StringBuilder newUrl = new StringBuilder(url); if (url.indexOf('?') != -1) { newUrl.append('&'); } else { newUrl.append('?'); } newUrl.append(Tool.PLACEMENT_ID); newUrl.append("="); newUrl.append(placementId); url = newUrl.toString(); } } } // Chain back so the wrapped response can encode the URL futher if needed // this is necessary for WSRP support. if (m_res != null) url = m_res.encodeURL(url); return url; } } /** * Request wrapper that exposes the parameters parsed from the multipart/mime file upload (along with parameters from the * request). */ static class WrappedRequestFileUpload extends HttpServletRequestWrapper { private Map map; /** * Constructs a wrapped response that exposes the given map of parameters. * * @param req * The request to wrap. * @param paramMap * The parameters to expose. */ public WrappedRequestFileUpload(HttpServletRequest req, Map paramMap) { super(req); map = paramMap; } public Map getParameterMap() { return map; } public String[] getParameterValues(String name) { String[] ret = null; Map map = getParameterMap(); return (String[]) map.get(name); } public String getParameter(String name) { String[] params = getParameterValues(name); if (params == null) return null; return params[0]; } public Enumeration getParameterNames() { Map map = getParameterMap(); return Collections.enumeration(map.keySet()); } } /** * Take this filter out of service. */ public void destroy() { } /** * Filter a request / response. */ public void doFilter(ServletRequest requestObj, ServletResponse responseObj, FilterChain chain) throws IOException, ServletException { StringBuffer sb = null; long startTime = System.currentTimeMillis(); // bind some preferences as "current" Boolean curRemoteUser = (Boolean) ThreadLocalManager.get(CURRENT_REMOTE_USER); Integer curHttpSession = (Integer) ThreadLocalManager.get(CURRENT_HTTP_SESSION); String curContext = (String) ThreadLocalManager.get(CURRENT_CONTEXT); ServletRequest curRequest = (ServletRequest) ThreadLocalManager.get(CURRENT_HTTP_REQUEST); ServletResponse curResponse = (ServletResponse) ThreadLocalManager.get(CURRENT_HTTP_RESPONSE); boolean cleared = false; // keep track of temp files with this request that need to be deleted on the way out List<FileItem> tempFiles = new ArrayList<FileItem>(); try { ThreadLocalManager.set(CURRENT_REMOTE_USER, Boolean.valueOf(m_sakaiRemoteUser)); ThreadLocalManager.set(CURRENT_HTTP_SESSION, Integer.valueOf(m_sakaiHttpSession)); ThreadLocalManager.set(CURRENT_CONTEXT, m_contextId); // make the servlet context available ThreadLocalManager.set(CURRENT_SERVLET_CONTEXT, m_servletContext); // we are expecting HTTP stuff if (!((requestObj instanceof HttpServletRequest) && (responseObj instanceof HttpServletResponse))) { // if not, just pass it through chain.doFilter(requestObj, responseObj); return; } HttpServletRequest req = (HttpServletRequest) requestObj; HttpServletResponse resp = (HttpServletResponse) responseObj; // check on file uploads and character encoding BEFORE checking if // this request has already been filtered, as the character encoding // and file upload handling are configurable at the tool level. // so the 2nd invokation of the RequestFilter (at the tool level) // may actually cause character encoding and file upload parsing // to happen. // handle character encoding handleCharacterEncoding(req, resp); // handle file uploads req = handleFileUpload(req, resp, tempFiles); // if we have already filtered this request, pass it on if (req.getAttribute(ATTR_FILTERED) != null) { // set the request and response for access via the thread local ThreadLocalManager.set(CURRENT_HTTP_REQUEST, req); ThreadLocalManager.set(CURRENT_HTTP_RESPONSE, resp); chain.doFilter(req, resp); } // filter the request else { if (M_log.isDebugEnabled()) { sb = new StringBuffer("http-request: "); sb.append(req.getMethod()); sb.append(" "); sb.append(req.getRequestURL()); if (req.getQueryString() != null) { sb.append("?"); sb.append(req.getQueryString()); } M_log.debug(sb); } try { // mark the request as filtered to avoid re-filtering it later in the request processing req.setAttribute(ATTR_FILTERED, ATTR_FILTERED); // some useful info ThreadLocalManager.set(ServerConfigurationService.CURRENT_SERVER_URL, serverUrl(req)); // make sure we have a session Session s = assureSession(req, resp); // pre-process request req = preProcessRequest(s, req); // detect a tool placement and set the current tool session detectToolPlacement(s, req); // pre-process response resp = preProcessResponse(s, req, resp); // set the request and response for access via the thread local ThreadLocalManager.set(CURRENT_HTTP_REQUEST, req); ThreadLocalManager.set(CURRENT_HTTP_RESPONSE, resp); // set the portal into thread local if (m_contextId != null && m_contextId.length() > 0) { ThreadLocalManager.set(ServerConfigurationService.CURRENT_PORTAL_PATH, "/" + m_contextId); } // Only synchronize on session for Terracotta. See KNL-218, KNL-75. if (TERRACOTTA_CLUSTER) { synchronized(s) { // Pass control on to the next filter or the servlet chain.doFilter(req, resp); // post-process response postProcessResponse(s, req, resp); } } else { // Pass control on to the next filter or the servlet chain.doFilter(req, resp); // post-process response postProcessResponse(s, req, resp); } // Output client cookie if requested to do so if (s != null && req.getAttribute(ATTR_SET_COOKIE) != null) { // check for existing cookie String suffix = getCookieSuffix(); Cookie c = findCookie(req, cookieName, suffix); // the cookie value we need to use String sessionId = s.getId() + DOT + suffix; // set the cookie if necessary if ((c == null) || (!c.getValue().equals(sessionId))) { c = new Cookie(cookieName, sessionId); c.setPath("/"); c.setMaxAge(-1); if (cookieDomain != null) { c.setDomain(cookieDomain); } if (req.isSecure() == true) { c.setSecure(true); } addCookie(resp, c); } } } catch (RuntimeException t) { M_log.warn("", t); throw t; } catch (IOException ioe) { M_log.warn("", ioe); throw ioe; } catch (ServletException se) { M_log.warn(se.getMessage(), se); throw se; } finally { // clear any bound current values ThreadLocalManager.clear(); cleared = true; } } } finally { if (!cleared) { // restore the "current" bindings ThreadLocalManager.set(CURRENT_REMOTE_USER, curRemoteUser); ThreadLocalManager.set(CURRENT_HTTP_SESSION, curHttpSession); ThreadLocalManager.set(CURRENT_CONTEXT, curContext); ThreadLocalManager.set(CURRENT_HTTP_REQUEST, curRequest); ThreadLocalManager.set(CURRENT_HTTP_RESPONSE, curResponse); } // delete any temp files deleteTempFiles(tempFiles); if (M_log.isDebugEnabled() && sb != null) { long elapsedTime = System.currentTimeMillis() - startTime; M_log.debug("request timing (ms): " + elapsedTime + " for " + sb); } } // retrieve the configured cookie name, if any if (System.getProperty(SAKAI_COOKIE_NAME) != null) { cookieName = System.getProperty(SAKAI_COOKIE_NAME); } // retrieve the configured cookie domain, if any - if (System.getProperty(SAKAI_COOKIE_NAME) != null) + if (System.getProperty(SAKAI_COOKIE_DOMAIN) != null) { cookieDomain = System.getProperty(SAKAI_COOKIE_DOMAIN); } } /** * If any of these files exist, delete them. * * @param tempFiles * The file items to delete. */ protected void deleteTempFiles(List<FileItem> tempFiles) { for (FileItem item : tempFiles) { item.delete(); } } /** * Place this filter into service. * * @param filterConfig * The filter configuration object */ public void init(FilterConfig filterConfig) throws ServletException { // Requesting the ServerConfigurationService here also triggers the promotion of certain // sakai.properties settings to system properties - see SakaiPropertyPromoter() ServerConfigurationService configService = org.sakaiproject.component.cover.ServerConfigurationService.getInstance(); // capture the servlet context for later user m_servletContext = filterConfig.getServletContext(); if (filterConfig.getInitParameter(CONFIG_SESSION) != null) { String s = filterConfig.getInitParameter(CONFIG_SESSION); if ("container".equalsIgnoreCase(s)) { m_sakaiHttpSession = CONTAINER_SESSION; } else if ("sakai".equalsIgnoreCase(s)) { m_sakaiHttpSession = SAKAI_SESSION; } else if ("context".equalsIgnoreCase(s)) { m_sakaiHttpSession = CONTEXT_SESSION; } else if ("tool".equalsIgnoreCase(s)) { m_sakaiHttpSession = TOOL_SESSION; } else { M_log.warn("invalid " + CONFIG_SESSION + " setting (" + s + "): not one of container, sakai, context, tool"); } } if (filterConfig.getInitParameter(CONFIG_REMOTE_USER) != null) { m_sakaiRemoteUser = Boolean.valueOf(filterConfig.getInitParameter(CONFIG_REMOTE_USER)).booleanValue(); } if (filterConfig.getInitParameter(CONFIG_SESSION_AUTH) != null) { m_checkPrincipal= "basic".equals(filterConfig.getInitParameter(CONFIG_SESSION_AUTH)); } if (filterConfig.getInitParameter(CONFIG_TOOL_PLACEMENT) != null) { m_toolPlacement = Boolean.valueOf(filterConfig.getInitParameter(CONFIG_TOOL_PLACEMENT)).booleanValue(); } if (filterConfig.getInitParameter(CONFIG_CONTEXT) != null) { m_contextId = filterConfig.getInitParameter(CONFIG_CONTEXT); } else { m_contextId = m_servletContext.getServletContextName(); if (m_contextId == null) { m_contextId = toString(); } } if (filterConfig.getInitParameter(CONFIG_CHARACTER_ENCODING) != null) { m_characterEncoding = filterConfig.getInitParameter(CONFIG_CHARACTER_ENCODING); } if (filterConfig.getInitParameter(CONFIG_CHARACTER_ENCODING_ENABLED) != null) { m_characterEncodingEnabled = Boolean.valueOf(filterConfig.getInitParameter(CONFIG_CHARACTER_ENCODING_ENABLED)) .booleanValue(); } if (filterConfig.getInitParameter(CONFIG_UPLOAD_ENABLED) != null) { m_uploadEnabled = Boolean.valueOf(filterConfig.getInitParameter(CONFIG_UPLOAD_ENABLED)).booleanValue(); } // get the maximum allowed upload size from the system property - use if not overriden, and also use as the ceiling if that // is not defined. if (System.getProperty(SYSTEM_UPLOAD_MAX) != null) { m_uploadMaxSize = Long.valueOf(System.getProperty(SYSTEM_UPLOAD_MAX)).longValue() * 1024L * 1024L; m_uploadCeiling = m_uploadMaxSize; } // if the maximum allowed upload size is configured on the filter, it overrides the system property if (filterConfig.getInitParameter(CONFIG_UPLOAD_MAX) != null) { m_uploadMaxSize = Long.valueOf(filterConfig.getInitParameter(CONFIG_UPLOAD_MAX)).longValue() * 1024L * 1024L; } // get the upload max ceiling that limits any other upload max, if defined if (System.getProperty(SYSTEM_UPLOAD_CEILING) != null) { m_uploadCeiling = Long.valueOf(System.getProperty(SYSTEM_UPLOAD_CEILING)).longValue() * 1024L * 1024L; } // get the system wide settin, if present, for the temp dir if (System.getProperty(SYSTEM_UPLOAD_DIR) != null) { m_uploadTempDir = System.getProperty(SYSTEM_UPLOAD_DIR); } // override with our configuration for temp dir, if set if (filterConfig.getInitParameter(CONFIG_UPLOAD_DIR) != null) { m_uploadTempDir = filterConfig.getInitParameter(CONFIG_UPLOAD_DIR); } if (filterConfig.getInitParameter(CONFIG_UPLOAD_THRESHOLD) != null) { m_uploadThreshold = Integer.valueOf(filterConfig.getInitParameter(CONFIG_UPLOAD_THRESHOLD)).intValue(); } if (filterConfig.getInitParameter(CONFIG_CONTINUE) != null) { m_uploadContinue = Boolean.valueOf(filterConfig.getInitParameter(CONFIG_CONTINUE)).booleanValue(); } if (filterConfig.getInitParameter(CONFIG_MAX_PER_FILE) != null) { m_uploadMaxPerFile = Boolean.valueOf(filterConfig.getInitParameter(CONFIG_MAX_PER_FILE)).booleanValue(); } // Note: if set to continue processing max exceeded uploads, we only support per-file max, not overall max if (m_uploadContinue && !m_uploadMaxPerFile) { M_log.warn("overridding " + CONFIG_MAX_PER_FILE + " setting: must be 'true' with " + CONFIG_CONTINUE + " ='true'"); m_uploadMaxPerFile = true; } String clusterTerracotta = System.getProperty("sakai.cluster.terracotta"); TERRACOTTA_CLUSTER = "true".equals(clusterTerracotta); // retrieve the configured cookie name, if any if (System.getProperty(SAKAI_COOKIE_NAME) != null) { cookieName = System.getProperty(SAKAI_COOKIE_NAME); } // retrieve the configured cookie domain, if any if (System.getProperty(SAKAI_COOKIE_DOMAIN) != null) { cookieDomain = System.getProperty(SAKAI_COOKIE_DOMAIN); } m_sessionParamAllow = configService.getBoolean(SAKAI_SESSION_PARAM_ALLOW, false); // retrieve option to enable or disable cookie HttpOnly m_cookieHttpOnly = configService.getBoolean(SAKAI_COOKIE_HTTP_ONLY, true); } /** * If setting character encoding is enabled for this filter, and there isn't already a character encoding on the request, then * set the encoding. */ protected void handleCharacterEncoding(HttpServletRequest req, HttpServletResponse resp) throws UnsupportedEncodingException { if (m_characterEncodingEnabled && req.getCharacterEncoding() == null && m_characterEncoding != null && m_characterEncoding.length() > 0 && req.getAttribute(ATTR_CHARACTER_ENCODING_DONE) == null) { req.setAttribute(ATTR_CHARACTER_ENCODING_DONE, ATTR_CHARACTER_ENCODING_DONE); req.setCharacterEncoding(m_characterEncoding); } } /** * if the filter is configured to parse file uploads, AND the request is multipart (typically a file upload), then parse the * request. * * @return If there is a file upload, and the filter handles it, return the wrapped request that has the results of the parsed * file upload. Parses the files using Apache commons-fileuplaod. Exposes the results through a wrapped request. Files * are available like: fileItem = (FileItem) request.getAttribute("myHtmlFileUploadId"); */ protected HttpServletRequest handleFileUpload(HttpServletRequest req, HttpServletResponse resp, List<FileItem> tempFiles) throws ServletException, UnsupportedEncodingException { if (!m_uploadEnabled || !ServletFileUpload.isMultipartContent(req) || req.getAttribute(ATTR_UPLOADS_DONE) != null) { return req; } // mark that the uploads have been parsed, so they aren't parsed again on this request req.setAttribute(ATTR_UPLOADS_DONE, ATTR_UPLOADS_DONE); // Result - map that will be created of request parameters, // parsed parameters, and uploaded files Map map = new HashMap(); // parse using commons-fileupload // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); // set the factory parameters: the temp dir and the keep-in-memory-if-smaller threshold if (m_uploadTempDir != null) factory.setRepository(new File(m_uploadTempDir)); if (m_uploadThreshold > 0) factory.setSizeThreshold(m_uploadThreshold); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // set the encoding String encoding = req.getCharacterEncoding(); if (encoding != null && encoding.length() > 0) upload.setHeaderEncoding(encoding); // set the max upload size long uploadMax = -1; if (m_uploadMaxSize > 0) uploadMax = m_uploadMaxSize; // check for request-scoped override to upload.max (value in megs) String override = req.getParameter(CONFIG_UPLOAD_MAX); if (override != null) { try { // get the max in bytes uploadMax = Long.parseLong(override) * 1024L * 1024L; } catch (NumberFormatException e) { M_log.warn(CONFIG_UPLOAD_MAX + " set to non-numeric: " + override); } } // limit to the ceiling if (uploadMax > m_uploadCeiling) { M_log.warn("Upload size exceeds ceiling: " + ((uploadMax / 1024L) / 1024L) + " > " + ((m_uploadCeiling / 1024L) / 1024L) + " megs"); uploadMax = m_uploadCeiling; } // to let commons-fileupload throw the exception on over-max, and also halt full processing of input fields if (!m_uploadContinue) { // TODO: when we switch to commons-fileupload 1.2 // // either per file or overall request, as configured // if (m_uploadMaxPerFile) // { // upload.setFileSizeMax(uploadMax); // } // else // { // upload.setSizeMax(uploadMax); // } upload.setSizeMax(uploadMax); } try { // parse multipart encoded parameters boolean uploadOk = true; List list = upload.parseRequest(req); for (int i = 0; i < list.size(); i++) { FileItem item = (FileItem) list.get(i); if (item.isFormField()) { String str = item.getString(encoding); Object obj = map.get(item.getFieldName()); if (obj == null) { map.put(item.getFieldName(), new String[] { str }); } else if (obj instanceof String[]) { String[] old_vals = (String[]) obj; String[] values = new String[old_vals.length + 1]; for (int i1 = 0; i1 < old_vals.length; i1++) { values[i1] = old_vals[i1]; } values[values.length - 1] = str; map.put(item.getFieldName(), values); } else if (obj instanceof String) { String[] values = new String[2]; values[0] = (String) obj; values[1] = str; map.put(item.getFieldName(), values); } } else { // collect it for delete at the end of the request tempFiles.add(item); // check the max, unless we are letting commons-fileupload throw exception on max exceeded // Note: the continue option assumes the max is per-file, not overall. if (m_uploadContinue && (item.getSize() > uploadMax)) { uploadOk = false; M_log.info("Upload size limit exceeded: " + ((uploadMax / 1024L) / 1024L)); req.setAttribute("upload.status", "size_limit_exceeded"); // TODO: for 1.2 commons-fileupload, switch this to a FileSizeLimitExceededException req.setAttribute("upload.exception", new FileUploadBase.SizeLimitExceededException("", item.getSize(), uploadMax)); req.setAttribute("upload.limit", Long.valueOf((uploadMax / 1024L) / 1024L)); } else { req.setAttribute(item.getFieldName(), item); } } } // unless we had an upload file that exceeded max, set the upload status to "ok" if (uploadOk) { req.setAttribute("upload.status", "ok"); } } catch (FileUploadBase.SizeLimitExceededException ex) { M_log.info("Upload size limit exceeded: " + ((upload.getSizeMax() / 1024L) / 1024L)); // DON'T throw an exception, instead note the exception // so that the tool down-the-line can handle the problem req.setAttribute("upload.status", "size_limit_exceeded"); req.setAttribute("upload.exception", ex); req.setAttribute("upload.limit", Long.valueOf((upload.getSizeMax() / 1024L) / 1024L)); } // TODO: put in for commons-fileupload 1.2 // catch (FileUploadBase.FileSizeLimitExceededException ex) // { // M_log.info("Upload size limit exceeded: " + ((upload.getFileSizeMax() / 1024L) / 1024L)); // // // DON'T throw an exception, instead note the exception // // so that the tool down-the-line can handle the problem // req.setAttribute("upload.status", "size_limit_exceeded"); // req.setAttribute("upload.exception", ex); // req.setAttribute("upload.limit", new Long((upload.getFileSizeMax() / 1024L) / 1024L)); // } catch (FileUploadException ex) { M_log.info("Unexpected exception in upload parsing", ex); req.setAttribute("upload.status", "exception"); req.setAttribute("upload.exception", ex); } // add any parameters that were in the URL - make sure to get multiples for (Enumeration e = req.getParameterNames(); e.hasMoreElements();) { String name = (String) e.nextElement(); String[] values = req.getParameterValues(name); map.put(name, values); } // return a wrapped response that exposes the parsed parameters and files return new WrappedRequestFileUpload(req, map); } /** * Make sure we have a Sakai session. * * @param req * The request object. * @param res * The response object. * @return The Sakai Session object. */ protected Session assureSession(HttpServletRequest req, HttpServletResponse res) { Session s = null; String sessionId = null; boolean allowSetCookieEarly = true; Cookie c = null; // automatic, i.e. not from user activity, request? boolean auto = req.getParameter(PARAM_AUTO) != null; // session id provided in a request parameter? boolean reqsession = m_sessionParamAllow && req.getParameter(ATTR_SESSION) != null; String suffix = getCookieSuffix(); // try finding a non-cookie session based on the remote user / principal // Note: use principal instead of remote user to avoid any possible confusion with the remote user set by single-signon // auth. // Principal is set by our Dav interface, which this is designed to cover. -ggolden Principal principal = req.getUserPrincipal(); if (m_checkPrincipal && (principal != null) && (principal.getName() != null)) { // set our session id to the remote user id sessionId = SessionManager.makeSessionId(req, principal); // don't supply this cookie to the client allowSetCookieEarly = false; // find the session s = SessionManager.getSession(sessionId); // if not found, make a session for this user if (s == null) { s = SessionManager.startSession(sessionId); } // Make these sessions expire after 10 minutes s.setMaxInactiveInterval(10*60); } // if no principal, check request parameter and cookie if (sessionId == null || s == null) { if (m_sessionParamAllow) { sessionId = req.getParameter(ATTR_SESSION); } // find our session id from our cookie c = findCookie(req, cookieName, suffix); if (sessionId == null && c != null) { // get our session id sessionId = c.getValue(); } if (sessionId != null) { // remove the server id suffix final int dotPosition = sessionId.indexOf(DOT); if (dotPosition > -1) { sessionId = sessionId.substring(0, dotPosition); } if (M_log.isDebugEnabled()) { M_log.debug("assureSession found sessionId in cookie: " + sessionId); } // find the session s = SessionManager.getSession(sessionId); } // ignore the session id provided in a request parameter // if the session is not authenticated if (reqsession && s != null && s.getUserId() == null) { s = null; } } // if found and not automatic, mark it as active if ((s != null) && (!auto)) { synchronized(s) { s.setActive(); } } // if missing, make one if (s == null) { s = SessionManager.startSession(); // if we have a cookie, but didn't find the session and are creating a new one, mark this if (c != null) { ThreadLocalManager.set(SessionManager.CURRENT_INVALID_SESSION, SessionManager.CURRENT_INVALID_SESSION); } } // put the session in the request attribute req.setAttribute(ATTR_SESSION, s); // set this as the current session SessionManager.setCurrentSession(s); // Now that we know the session exists, regardless of whether it's new or not, lets see if there // is a UsageSession. If so, we want to check it's serverId UsageSession us = null; // FIXME synchronizing on a changing value is a bad practice plus it is possible for s to be null according to the visible code -AZ synchronized(s) { us = (UsageSession)s.getAttribute(UsageSessionService.USAGE_SESSION_KEY); if (us != null) { // check the server instance id ServerConfigurationService configService = org.sakaiproject.component.cover.ServerConfigurationService.getInstance(); String serverInstanceId = configService.getServerIdInstance(); if ((serverInstanceId != null) && (!serverInstanceId.equals(us.getServer()))) { // Log that the UsageSession server value is changing M_log.info("UsageSession: Server change detected: Old Server=" + us.getServer() + " New Server=" + serverInstanceId); // set the new UsageSession server value us.setServer(serverInstanceId); } } } // if we had a cookie and we have no session, clear the cookie TODO: detect closed session in the request if ((s == null) && (c != null)) { // remove the cookie c = new Cookie(cookieName, ""); c.setPath("/"); c.setMaxAge(0); if (cookieDomain != null) { c.setDomain(cookieDomain); } addCookie(res, c); } // if we have a session and had no cookie, // or the cookie was to another session id, set the cookie if ((s != null) && allowSetCookieEarly) { // the cookie value we need to use sessionId = s.getId() + DOT + suffix; if ((c == null) || (!c.getValue().equals(sessionId))) { // set the cookie c = new Cookie(cookieName, sessionId); c.setPath("/"); c.setMaxAge(-1); if (cookieDomain != null) { c.setDomain(cookieDomain); } if (req.isSecure() == true) { c.setSecure(true); } addCookie(res, c); } } return s; } /** * Detect a tool placement from the URL, and if found, setup the placement attribute and current tool session based on that id. * * @param s * The sakai session. * @param req * The request, already prepared with the placement id if any. * @return The tool session. */ protected ToolSession detectToolPlacement(Session s, HttpServletRequest req) { // skip if so configured if (this.m_toolPlacement == false) return null; ToolSession toolSession = null; String placementId = (String) req.getParameter(Tool.PLACEMENT_ID); if (placementId != null) { toolSession = s.getToolSession(placementId); // put the session in the request attribute req.setAttribute(Tool.TOOL_SESSION, toolSession); // set as the current tool session SessionManager.setCurrentToolSession(toolSession); // put the placement id in the request attribute req.setAttribute(Tool.PLACEMENT_ID, placementId); } return toolSession; } /** * Pre-process the request, returning a possibly wrapped req for further processing. * * @param s * The Sakai Session. * @param req * The request object. * @return a possibly wrapped and possibly new request object for further processing. */ protected HttpServletRequest preProcessRequest(Session s, HttpServletRequest req) { req = new WrappedRequest(s, m_contextId, req); return req; } /** * Pre-process the response, returning a possibly wrapped res for further processing. * * @param s * The Sakai Session. * @param req * The request object. * @param res * The response object. * @return a possibly wrapped and possibly new response object for further processing. */ protected HttpServletResponse preProcessResponse(Session s, HttpServletRequest req, HttpServletResponse res) { res = new WrappedResponse(s, req, res); return res; } /** * Post-process the response. * * @param s * The Sakai Session. * @param req * The request object. * @param res * The response object. */ protected void postProcessResponse(Session s, HttpServletRequest req, HttpServletResponse res) { } /** * Find a cookie by this name from the request; one with a value that has the specified suffix. * * @param req * The servlet request. * @param name * The cookie name * @param suffix * The suffix string to find at the end of the found cookie value. * @return The cookie of this name in the request, or null if not found. */ protected Cookie findCookie(HttpServletRequest req, String name, String suffix) { Cookie[] cookies = req.getCookies(); if (cookies != null) { for (int i = 0; i < cookies.length; i++) { if (cookies[i].getName().equals(name)) { // If this is NOT a terracotta cluster environment // and the suffix passed in to this method is not null // then only match the cookie if the end of the cookie // value is equal to the suffix passed in. if (TERRACOTTA_CLUSTER || ((suffix == null) || cookies[i].getValue().endsWith(suffix))) { return cookies[i]; } } } } return null; } /** * Compute the URL that would return to this server based on the current request. Note: this method is a duplicate of one in the * util/Web.java * * @param req * The request. * @return The URL back to this server based on the current request. */ public static String serverUrl(HttpServletRequest req) { String transport = null; int port = 0; boolean secure = false; // if force.url.secure is set (to a https port number), use https and this port String forceSecure = System.getProperty("sakai.force.url.secure"); if (forceSecure != null) { transport = "https"; port = Integer.parseInt(forceSecure); secure = true; } // otherwise use the request scheme and port else { transport = req.getScheme(); port = req.getServerPort(); secure = req.isSecure(); } StringBuilder url = new StringBuilder(); url.append(transport); url.append("://"); url.append(req.getServerName()); if (((port != 80) && (!secure)) || ((port != 443) && secure)) { url.append(":"); url.append(port); } return url.toString(); } /** * Get cookie suffix from the serverId. * We can't do this at init time as it might not have been set yet (sakai hasn't started). * @return The cookie suffix to use. */ private String getCookieSuffix() { // compute the session cookie suffix, based on this configured server id String suffix = System.getProperty(SAKAI_SERVERID); if ((suffix == null) || (suffix.length() == 0)) { if (m_displayModJkWarning) { M_log.warn("no sakai.serverId system property set - mod_jk load balancing will not function properly"); } m_displayModJkWarning = false; suffix = "sakai"; } return suffix; } protected void addCookie(HttpServletResponse res, Cookie cookie) { if (!m_cookieHttpOnly) { // Use the standard servlet mechanism for setting the cookie res.addCookie(cookie); } else { // Set the cookie manually StringBuffer sb = new StringBuffer(); ServerCookie.appendCookieValue(sb, cookie.getVersion(), cookie.getName(), cookie.getValue(), cookie.getPath(), cookie.getDomain(), cookie.getComment(), cookie.getMaxAge(), cookie.getSecure(), m_cookieHttpOnly); res.addHeader("Set-Cookie", sb.toString()); } return; } }
true
true
public void doFilter(ServletRequest requestObj, ServletResponse responseObj, FilterChain chain) throws IOException, ServletException { StringBuffer sb = null; long startTime = System.currentTimeMillis(); // bind some preferences as "current" Boolean curRemoteUser = (Boolean) ThreadLocalManager.get(CURRENT_REMOTE_USER); Integer curHttpSession = (Integer) ThreadLocalManager.get(CURRENT_HTTP_SESSION); String curContext = (String) ThreadLocalManager.get(CURRENT_CONTEXT); ServletRequest curRequest = (ServletRequest) ThreadLocalManager.get(CURRENT_HTTP_REQUEST); ServletResponse curResponse = (ServletResponse) ThreadLocalManager.get(CURRENT_HTTP_RESPONSE); boolean cleared = false; // keep track of temp files with this request that need to be deleted on the way out List<FileItem> tempFiles = new ArrayList<FileItem>(); try { ThreadLocalManager.set(CURRENT_REMOTE_USER, Boolean.valueOf(m_sakaiRemoteUser)); ThreadLocalManager.set(CURRENT_HTTP_SESSION, Integer.valueOf(m_sakaiHttpSession)); ThreadLocalManager.set(CURRENT_CONTEXT, m_contextId); // make the servlet context available ThreadLocalManager.set(CURRENT_SERVLET_CONTEXT, m_servletContext); // we are expecting HTTP stuff if (!((requestObj instanceof HttpServletRequest) && (responseObj instanceof HttpServletResponse))) { // if not, just pass it through chain.doFilter(requestObj, responseObj); return; } HttpServletRequest req = (HttpServletRequest) requestObj; HttpServletResponse resp = (HttpServletResponse) responseObj; // check on file uploads and character encoding BEFORE checking if // this request has already been filtered, as the character encoding // and file upload handling are configurable at the tool level. // so the 2nd invokation of the RequestFilter (at the tool level) // may actually cause character encoding and file upload parsing // to happen. // handle character encoding handleCharacterEncoding(req, resp); // handle file uploads req = handleFileUpload(req, resp, tempFiles); // if we have already filtered this request, pass it on if (req.getAttribute(ATTR_FILTERED) != null) { // set the request and response for access via the thread local ThreadLocalManager.set(CURRENT_HTTP_REQUEST, req); ThreadLocalManager.set(CURRENT_HTTP_RESPONSE, resp); chain.doFilter(req, resp); } // filter the request else { if (M_log.isDebugEnabled()) { sb = new StringBuffer("http-request: "); sb.append(req.getMethod()); sb.append(" "); sb.append(req.getRequestURL()); if (req.getQueryString() != null) { sb.append("?"); sb.append(req.getQueryString()); } M_log.debug(sb); } try { // mark the request as filtered to avoid re-filtering it later in the request processing req.setAttribute(ATTR_FILTERED, ATTR_FILTERED); // some useful info ThreadLocalManager.set(ServerConfigurationService.CURRENT_SERVER_URL, serverUrl(req)); // make sure we have a session Session s = assureSession(req, resp); // pre-process request req = preProcessRequest(s, req); // detect a tool placement and set the current tool session detectToolPlacement(s, req); // pre-process response resp = preProcessResponse(s, req, resp); // set the request and response for access via the thread local ThreadLocalManager.set(CURRENT_HTTP_REQUEST, req); ThreadLocalManager.set(CURRENT_HTTP_RESPONSE, resp); // set the portal into thread local if (m_contextId != null && m_contextId.length() > 0) { ThreadLocalManager.set(ServerConfigurationService.CURRENT_PORTAL_PATH, "/" + m_contextId); } // Only synchronize on session for Terracotta. See KNL-218, KNL-75. if (TERRACOTTA_CLUSTER) { synchronized(s) { // Pass control on to the next filter or the servlet chain.doFilter(req, resp); // post-process response postProcessResponse(s, req, resp); } } else { // Pass control on to the next filter or the servlet chain.doFilter(req, resp); // post-process response postProcessResponse(s, req, resp); } // Output client cookie if requested to do so if (s != null && req.getAttribute(ATTR_SET_COOKIE) != null) { // check for existing cookie String suffix = getCookieSuffix(); Cookie c = findCookie(req, cookieName, suffix); // the cookie value we need to use String sessionId = s.getId() + DOT + suffix; // set the cookie if necessary if ((c == null) || (!c.getValue().equals(sessionId))) { c = new Cookie(cookieName, sessionId); c.setPath("/"); c.setMaxAge(-1); if (cookieDomain != null) { c.setDomain(cookieDomain); } if (req.isSecure() == true) { c.setSecure(true); } addCookie(resp, c); } } } catch (RuntimeException t) { M_log.warn("", t); throw t; } catch (IOException ioe) { M_log.warn("", ioe); throw ioe; } catch (ServletException se) { M_log.warn(se.getMessage(), se); throw se; } finally { // clear any bound current values ThreadLocalManager.clear(); cleared = true; } } } finally { if (!cleared) { // restore the "current" bindings ThreadLocalManager.set(CURRENT_REMOTE_USER, curRemoteUser); ThreadLocalManager.set(CURRENT_HTTP_SESSION, curHttpSession); ThreadLocalManager.set(CURRENT_CONTEXT, curContext); ThreadLocalManager.set(CURRENT_HTTP_REQUEST, curRequest); ThreadLocalManager.set(CURRENT_HTTP_RESPONSE, curResponse); } // delete any temp files deleteTempFiles(tempFiles); if (M_log.isDebugEnabled() && sb != null) { long elapsedTime = System.currentTimeMillis() - startTime; M_log.debug("request timing (ms): " + elapsedTime + " for " + sb); } } // retrieve the configured cookie name, if any if (System.getProperty(SAKAI_COOKIE_NAME) != null) { cookieName = System.getProperty(SAKAI_COOKIE_NAME); } // retrieve the configured cookie domain, if any if (System.getProperty(SAKAI_COOKIE_NAME) != null) { cookieDomain = System.getProperty(SAKAI_COOKIE_DOMAIN); } }
public void doFilter(ServletRequest requestObj, ServletResponse responseObj, FilterChain chain) throws IOException, ServletException { StringBuffer sb = null; long startTime = System.currentTimeMillis(); // bind some preferences as "current" Boolean curRemoteUser = (Boolean) ThreadLocalManager.get(CURRENT_REMOTE_USER); Integer curHttpSession = (Integer) ThreadLocalManager.get(CURRENT_HTTP_SESSION); String curContext = (String) ThreadLocalManager.get(CURRENT_CONTEXT); ServletRequest curRequest = (ServletRequest) ThreadLocalManager.get(CURRENT_HTTP_REQUEST); ServletResponse curResponse = (ServletResponse) ThreadLocalManager.get(CURRENT_HTTP_RESPONSE); boolean cleared = false; // keep track of temp files with this request that need to be deleted on the way out List<FileItem> tempFiles = new ArrayList<FileItem>(); try { ThreadLocalManager.set(CURRENT_REMOTE_USER, Boolean.valueOf(m_sakaiRemoteUser)); ThreadLocalManager.set(CURRENT_HTTP_SESSION, Integer.valueOf(m_sakaiHttpSession)); ThreadLocalManager.set(CURRENT_CONTEXT, m_contextId); // make the servlet context available ThreadLocalManager.set(CURRENT_SERVLET_CONTEXT, m_servletContext); // we are expecting HTTP stuff if (!((requestObj instanceof HttpServletRequest) && (responseObj instanceof HttpServletResponse))) { // if not, just pass it through chain.doFilter(requestObj, responseObj); return; } HttpServletRequest req = (HttpServletRequest) requestObj; HttpServletResponse resp = (HttpServletResponse) responseObj; // check on file uploads and character encoding BEFORE checking if // this request has already been filtered, as the character encoding // and file upload handling are configurable at the tool level. // so the 2nd invokation of the RequestFilter (at the tool level) // may actually cause character encoding and file upload parsing // to happen. // handle character encoding handleCharacterEncoding(req, resp); // handle file uploads req = handleFileUpload(req, resp, tempFiles); // if we have already filtered this request, pass it on if (req.getAttribute(ATTR_FILTERED) != null) { // set the request and response for access via the thread local ThreadLocalManager.set(CURRENT_HTTP_REQUEST, req); ThreadLocalManager.set(CURRENT_HTTP_RESPONSE, resp); chain.doFilter(req, resp); } // filter the request else { if (M_log.isDebugEnabled()) { sb = new StringBuffer("http-request: "); sb.append(req.getMethod()); sb.append(" "); sb.append(req.getRequestURL()); if (req.getQueryString() != null) { sb.append("?"); sb.append(req.getQueryString()); } M_log.debug(sb); } try { // mark the request as filtered to avoid re-filtering it later in the request processing req.setAttribute(ATTR_FILTERED, ATTR_FILTERED); // some useful info ThreadLocalManager.set(ServerConfigurationService.CURRENT_SERVER_URL, serverUrl(req)); // make sure we have a session Session s = assureSession(req, resp); // pre-process request req = preProcessRequest(s, req); // detect a tool placement and set the current tool session detectToolPlacement(s, req); // pre-process response resp = preProcessResponse(s, req, resp); // set the request and response for access via the thread local ThreadLocalManager.set(CURRENT_HTTP_REQUEST, req); ThreadLocalManager.set(CURRENT_HTTP_RESPONSE, resp); // set the portal into thread local if (m_contextId != null && m_contextId.length() > 0) { ThreadLocalManager.set(ServerConfigurationService.CURRENT_PORTAL_PATH, "/" + m_contextId); } // Only synchronize on session for Terracotta. See KNL-218, KNL-75. if (TERRACOTTA_CLUSTER) { synchronized(s) { // Pass control on to the next filter or the servlet chain.doFilter(req, resp); // post-process response postProcessResponse(s, req, resp); } } else { // Pass control on to the next filter or the servlet chain.doFilter(req, resp); // post-process response postProcessResponse(s, req, resp); } // Output client cookie if requested to do so if (s != null && req.getAttribute(ATTR_SET_COOKIE) != null) { // check for existing cookie String suffix = getCookieSuffix(); Cookie c = findCookie(req, cookieName, suffix); // the cookie value we need to use String sessionId = s.getId() + DOT + suffix; // set the cookie if necessary if ((c == null) || (!c.getValue().equals(sessionId))) { c = new Cookie(cookieName, sessionId); c.setPath("/"); c.setMaxAge(-1); if (cookieDomain != null) { c.setDomain(cookieDomain); } if (req.isSecure() == true) { c.setSecure(true); } addCookie(resp, c); } } } catch (RuntimeException t) { M_log.warn("", t); throw t; } catch (IOException ioe) { M_log.warn("", ioe); throw ioe; } catch (ServletException se) { M_log.warn(se.getMessage(), se); throw se; } finally { // clear any bound current values ThreadLocalManager.clear(); cleared = true; } } } finally { if (!cleared) { // restore the "current" bindings ThreadLocalManager.set(CURRENT_REMOTE_USER, curRemoteUser); ThreadLocalManager.set(CURRENT_HTTP_SESSION, curHttpSession); ThreadLocalManager.set(CURRENT_CONTEXT, curContext); ThreadLocalManager.set(CURRENT_HTTP_REQUEST, curRequest); ThreadLocalManager.set(CURRENT_HTTP_RESPONSE, curResponse); } // delete any temp files deleteTempFiles(tempFiles); if (M_log.isDebugEnabled() && sb != null) { long elapsedTime = System.currentTimeMillis() - startTime; M_log.debug("request timing (ms): " + elapsedTime + " for " + sb); } } // retrieve the configured cookie name, if any if (System.getProperty(SAKAI_COOKIE_NAME) != null) { cookieName = System.getProperty(SAKAI_COOKIE_NAME); } // retrieve the configured cookie domain, if any if (System.getProperty(SAKAI_COOKIE_DOMAIN) != null) { cookieDomain = System.getProperty(SAKAI_COOKIE_DOMAIN); } }
diff --git a/src/net/sf/gogui/thumbnail/Thumbnail.java b/src/net/sf/gogui/thumbnail/Thumbnail.java index 3657ae8e..07a78fc2 100644 --- a/src/net/sf/gogui/thumbnail/Thumbnail.java +++ b/src/net/sf/gogui/thumbnail/Thumbnail.java @@ -1,284 +1,276 @@ //---------------------------------------------------------------------------- // $Id$ // $Source$ //---------------------------------------------------------------------------- package net.sf.gogui.thumbnail; import java.awt.Graphics2D; import java.awt.Image; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Iterator; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import javax.imageio.IIOImage; import javax.imageio.ImageIO; import javax.imageio.ImageTypeSpecifier; import javax.imageio.ImageWriter; import javax.imageio.metadata.IIOInvalidTreeException; import javax.imageio.metadata.IIOMetadata; import javax.imageio.metadata.IIOMetadataNode; import javax.imageio.stream.ImageOutputStream; import net.sf.gogui.game.GameInformation; import net.sf.gogui.game.GameTree; import net.sf.gogui.game.NodeUtils; import net.sf.gogui.go.Board; import net.sf.gogui.go.BoardUtils; import net.sf.gogui.go.GoColor; import net.sf.gogui.go.GoPoint; import net.sf.gogui.go.Move; import net.sf.gogui.gui.GuiField; import net.sf.gogui.gui.GuiBoardDrawer; import net.sf.gogui.sgf.SgfReader; import net.sf.gogui.utils.FileUtils; import net.sf.gogui.gui.GuiUtils; import net.sf.gogui.version.Version; //---------------------------------------------------------------------------- /** Thumbnail creator. Creates thumbnails according to the freedesktop.org standard. @todo Save to temp file and rename as required by the standard. */ public final class Thumbnail { public Thumbnail(boolean verbose) { m_verbose = verbose; m_drawer = new GuiBoardDrawer(false); } public static boolean checkThumbnailSupport() { return getNormalDir().exists(); } /** Create thumbnail. Creates a small thumbnail; only if .thumbnails/normal directory already exists in home directory. @param file input The SGF file @param output The output thumbnail. Null for standard filename in ~/.thumbnails/normal */ public boolean create(File input, File output) { m_lastThumbnail = null; try { - if (! checkThumbnailSupport()) - { - // We cannot create it with the right permissions from Java - log("Thumbnail directory does not exist: " + input); - return false; - } log("File: " + input); - long lastModified = input.lastModified() / 1000L; - if (lastModified == 0L) - { - log("Could not get last modification time: " + input); - return false; - } URI uri = FileUtils.getURI(input); log("URI: " + uri); String md5 = getMD5(uri.toString()); if (m_verbose) log("MD5: " + md5); ArrayList moves = new ArrayList(); m_description = ""; Board board = readFile(input, moves); for (int i = 0; i < moves.size(); ++i) board.play((Move)moves.get(i)); int size = board.getSize(); GuiField[][] field = new GuiField[size][size]; for (int x = 0; x < size; ++x) for (int y = 0; y < size; ++y) { field[x][y] = new GuiField(); GoColor color = board.getColor(GoPoint.get(x, y)); field[x][y].setColor(color); } // Create large image and scale down, looks better than creating // small image BufferedImage image = getImage(field, 256, 256); BufferedImage normalImage = createImage(128, 128); Graphics2D graphics = normalImage.createGraphics(); Image scaledInstance = image.getScaledInstance(128, 128, Image.SCALE_SMOOTH); graphics.drawImage(scaledInstance, 0, 0, null); if (output == null) output = new File(getNormalDir(), md5 + ".png"); + long lastModified = input.lastModified() / 1000L; + if (lastModified == 0L) + { + System.err.println("Could not get last modification time: " + + input); + return false; + } writeImage(normalImage, output, uri, lastModified); return true; } catch (FileNotFoundException e) { - log("File not found: " + input); - return false; + System.err.println("File not found: " + input); } catch (IOException e) { - log(e.getMessage()); - return false; + System.err.println(e.getMessage()); } catch (NoSuchAlgorithmException e) { - log("No MD5 message digest found"); - return false; + System.err.println("No MD5 message digest found"); } catch (SgfReader.SgfError e) { - log("SGF error: " + input); - return false; + System.err.println("SGF error: " + input); } + return false; } public String getLastDescription() { return m_description; } public File getLastThumbnail() { return m_lastThumbnail; } private final boolean m_verbose; private String m_description; private File m_lastThumbnail; private final GuiBoardDrawer m_drawer; private BufferedImage createImage(int width, int height) { return new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); } private void addMeta(org.w3c.dom.Node node, String keyword, String value) { IIOMetadataNode text = new IIOMetadataNode("Text"); IIOMetadataNode textEntry = new IIOMetadataNode("TextEntry"); textEntry.setAttribute("value", value); textEntry.setAttribute("keyword", keyword); textEntry.setAttribute("encoding", "ISO-8859-1"); textEntry.setAttribute("language", "en"); textEntry.setAttribute("compression", "none"); text.appendChild(textEntry); node.appendChild(text); } private Board readFile(File file, ArrayList moves) throws FileNotFoundException, SgfReader.SgfError { FileInputStream in = new FileInputStream(file); SgfReader reader = new SgfReader(in, file.toString(), null, 0); try { in.close(); } catch (IOException e) { log(e.getMessage()); } GameTree tree = reader.getGameTree(); GameInformation gameInformation = tree.getGameInformation(); int size = gameInformation.m_boardSize; m_description = gameInformation.suggestGameName(); if (m_description == null) m_description = ""; Board board = new Board(size); net.sf.gogui.game.Node node = tree.getRoot(); while (node != null) { moves.addAll(NodeUtils.getAllAsMoves(node)); node = node.getChild(); } //if (m_verbose) // BoardUtils.print(board, System.err); return board; } private BufferedImage getImage(GuiField[][] field, int width, int height) { BufferedImage image = createImage(width, height); Graphics2D graphics = image.createGraphics(); GuiUtils.setAntiAlias(graphics); m_drawer.draw(graphics, field, width, false, false); graphics.dispose(); return image; } private static String getMD5(String string) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest digest = MessageDigest.getInstance("MD5"); byte[] md5 = digest.digest(string.getBytes("US-ASCII")); StringBuffer buffer = new StringBuffer(); for (int i = 0; i < md5.length; ++i) { buffer.append(Integer.toHexString((md5[i] >> 4) & 0x0F)); buffer.append(Integer.toHexString(md5[i] & 0x0F)); } return buffer.toString(); } private void log(String line) { if (! m_verbose) return; System.err.println(line); } private static File getNormalDir() { String home = System.getProperty("user.home", ""); return new File(new File(home, ".thumbnails"), "normal"); } private void writeImage(BufferedImage image, File file, URI uri, long lastModified) throws IOException { Iterator iter = ImageIO.getImageWritersBySuffix("png"); ImageWriter writer = (ImageWriter)iter.next(); ImageTypeSpecifier specifier = new ImageTypeSpecifier(image); IIOMetadata meta = writer.getDefaultImageMetadata(specifier, null); String formatName = "javax_imageio_1.0"; org.w3c.dom.Node node = meta.getAsTree(formatName); addMeta(node, "Thumb::URI", uri.toString()); addMeta(node, "Thumb::MTime", Long.toString(lastModified)); addMeta(node, "Thumb::Mimetype", "application/x-go-sgf"); if (! m_description.equals("")) addMeta(node, "Description", m_description); addMeta(node, "Software", "GoGui " + Version.get()); try { meta.mergeTree(formatName, node); } catch (IIOInvalidTreeException e) { assert(false); return; } ImageOutputStream ios = ImageIO.createImageOutputStream(file); writer.setOutput(ios); writer.write(null, new IIOImage(image, null, meta), null); m_lastThumbnail = file; } } //----------------------------------------------------------------------------
false
true
public boolean create(File input, File output) { m_lastThumbnail = null; try { if (! checkThumbnailSupport()) { // We cannot create it with the right permissions from Java log("Thumbnail directory does not exist: " + input); return false; } log("File: " + input); long lastModified = input.lastModified() / 1000L; if (lastModified == 0L) { log("Could not get last modification time: " + input); return false; } URI uri = FileUtils.getURI(input); log("URI: " + uri); String md5 = getMD5(uri.toString()); if (m_verbose) log("MD5: " + md5); ArrayList moves = new ArrayList(); m_description = ""; Board board = readFile(input, moves); for (int i = 0; i < moves.size(); ++i) board.play((Move)moves.get(i)); int size = board.getSize(); GuiField[][] field = new GuiField[size][size]; for (int x = 0; x < size; ++x) for (int y = 0; y < size; ++y) { field[x][y] = new GuiField(); GoColor color = board.getColor(GoPoint.get(x, y)); field[x][y].setColor(color); } // Create large image and scale down, looks better than creating // small image BufferedImage image = getImage(field, 256, 256); BufferedImage normalImage = createImage(128, 128); Graphics2D graphics = normalImage.createGraphics(); Image scaledInstance = image.getScaledInstance(128, 128, Image.SCALE_SMOOTH); graphics.drawImage(scaledInstance, 0, 0, null); if (output == null) output = new File(getNormalDir(), md5 + ".png"); writeImage(normalImage, output, uri, lastModified); return true; } catch (FileNotFoundException e) { log("File not found: " + input); return false; } catch (IOException e) { log(e.getMessage()); return false; } catch (NoSuchAlgorithmException e) { log("No MD5 message digest found"); return false; } catch (SgfReader.SgfError e) { log("SGF error: " + input); return false; } }
public boolean create(File input, File output) { m_lastThumbnail = null; try { log("File: " + input); URI uri = FileUtils.getURI(input); log("URI: " + uri); String md5 = getMD5(uri.toString()); if (m_verbose) log("MD5: " + md5); ArrayList moves = new ArrayList(); m_description = ""; Board board = readFile(input, moves); for (int i = 0; i < moves.size(); ++i) board.play((Move)moves.get(i)); int size = board.getSize(); GuiField[][] field = new GuiField[size][size]; for (int x = 0; x < size; ++x) for (int y = 0; y < size; ++y) { field[x][y] = new GuiField(); GoColor color = board.getColor(GoPoint.get(x, y)); field[x][y].setColor(color); } // Create large image and scale down, looks better than creating // small image BufferedImage image = getImage(field, 256, 256); BufferedImage normalImage = createImage(128, 128); Graphics2D graphics = normalImage.createGraphics(); Image scaledInstance = image.getScaledInstance(128, 128, Image.SCALE_SMOOTH); graphics.drawImage(scaledInstance, 0, 0, null); if (output == null) output = new File(getNormalDir(), md5 + ".png"); long lastModified = input.lastModified() / 1000L; if (lastModified == 0L) { System.err.println("Could not get last modification time: " + input); return false; } writeImage(normalImage, output, uri, lastModified); return true; } catch (FileNotFoundException e) { System.err.println("File not found: " + input); } catch (IOException e) { System.err.println(e.getMessage()); } catch (NoSuchAlgorithmException e) { System.err.println("No MD5 message digest found"); } catch (SgfReader.SgfError e) { System.err.println("SGF error: " + input); } return false; }
diff --git a/src/filius/gui/anwendungssicht/GUIApplicationTerminalWindow.java b/src/filius/gui/anwendungssicht/GUIApplicationTerminalWindow.java index 6524900..7bcade8 100644 --- a/src/filius/gui/anwendungssicht/GUIApplicationTerminalWindow.java +++ b/src/filius/gui/anwendungssicht/GUIApplicationTerminalWindow.java @@ -1,326 +1,322 @@ /* ** This file is part of Filius, a network construction and simulation software. ** ** Originally created at the University of Siegen, Institute "Didactics of ** Informatics and E-Learning" by a students' project group: ** members (2006-2007): ** André Asschoff, Johannes Bade, Carsten Dittich, Thomas Gerding, ** Nadja Haßler, Ernst Johannes Klebert, Michell Weyer ** supervisors: ** Stefan Freischlad (maintainer until 2009), Peer Stechert ** Project is maintained since 2010 by Christian Eibl <[email protected]> ** and Stefan Freischlad ** Filius 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) version 3. ** ** Filius 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 Filius. If not, see <http://www.gnu.org/licenses/>. */ package filius.gui.anwendungssicht; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Font; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.WindowEvent; import java.util.Observable; import java.util.StringTokenizer; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.ScrollPaneConstants; import javax.swing.event.InternalFrameEvent; import filius.Main; import filius.software.lokal.Terminal; import filius.software.system.Dateisystem; import java.util.ArrayList; /** * Applikationsfenster fuer ein Terminal * * @author Johannes Bade & Thomas Gerding * */ public class GUIApplicationTerminalWindow extends GUIApplicationWindow { /** * */ private static final long serialVersionUID = 1L; private JTextArea terminalField; private JPanel backPanel; private JTextField inputField; private JLabel inputLabel; private JScrollPane tpPane; private boolean jobRunning; private String enteredCommand; private String[] enteredParameters; private boolean multipleObserverEvents; ArrayList<String> terminalCommandList = new ArrayList<String>(); // für pfeil-nach-oben-holt-letzten-befehl-wieder int terminalCommandListStep = -1; - public GUIApplicationTerminalWindow(GUIDesktopPanel desktop, String appName){ + public GUIApplicationTerminalWindow(GUIDesktopPanel desktop, String appName) { super(desktop, appName); this.setMaximizable(false); this.setResizable(false); jobRunning = false; multipleObserverEvents = false; terminalField = new JTextArea(""); terminalField.setEditable(false); terminalField.setCaretColor(new Color(222,222,222)); terminalField.setForeground(new Color(222,222,222)); terminalField.setBackground(new Color(0,0,0)); terminalField.setFont(new Font("Courier New",Font.PLAIN,11)); terminalField.setFocusable(false); terminalField.setBorder(null); tpPane = new JScrollPane(terminalField); // make textfield scrollable tpPane.setBorder(null); tpPane.setBackground(new Color(0,0,0)); tpPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER); // do not show vert. scrollbar tpPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); // do not show hor. scrollbar inputField = new JTextField(""); inputField.setEditable(true); inputField.setBackground(new Color(0,0,0)); inputField.setForeground(new Color(222,222,222)); inputField.setCaretColor(new Color(222,222,222)); inputField.setBorder(null); inputField.setFont(new Font("Courier New",Font.PLAIN,11)); inputField.addKeyListener(new KeyListener() { public void keyPressed(KeyEvent e) { if(e.getKeyCode() == KeyEvent.VK_ENTER) { terminalCommandListStep = -1; // lass uns doch besser wieder von unten/vorne beginnen if(!(inputField.getText().isEmpty() || inputField.getText().replaceAll(" ", "").isEmpty())) { // only process non-empty input //Main.debug.println("DEBUG: "+getClass()+", keyPressed ('"+inputField.getText()+" + ENTER') event started"); terminalField.append("\n"+inputLabel.getText()+inputField.getText()+"\n"); StringTokenizer tk = new StringTokenizer(inputField.getText(), " "); /* Erstes Token enthaelt den Befehl*/ enteredCommand = tk.nextToken(); /* restliche Tokens werden in String Array geschrieben. * Array wird sicherheitshalber mit mindestens 3 leeren Strings gefüllt! */ enteredParameters = new String[3+tk.countTokens()]; for (int i =0; i< 3+tk.countTokens(); i++) { enteredParameters[i] = new String(); } int iti = 0; while (tk.hasMoreTokens()) { enteredParameters[iti] =tk.nextToken(); iti++; } if (enteredCommand.equals("exit")) { doDefaultCloseAction(); } else if (enteredCommand.equals("reset")) { terminalField.setText( "" ); for (int i=0; i<15; i++) { terminalField.append(" \n"); } // padding with new lines for bottom alignment of new output terminalField.append( "================================================================\n" ); terminalField.append(messages.getString("sw_terminal_msg25") + "================================================================" + "\n"); } else { inputLabel.setVisible(false); jobRunning = true; terminalCommandList.add(inputField.getText()); ((Terminal) holeAnwendung()).terminalEingabeAuswerten(enteredCommand,enteredParameters); } } else { terminalField.append("\n"); } //Main.debug.println("DEBUG: "+getClass()+", keyPressed ('"+inputField.getText()+" + ENTER') event finished"); inputField.setText(""); } if (e.getKeyCode() == KeyEvent.VK_C && e.getModifiers() == 2) { // [strg] + [c] System.out.println("INTERRUPT"); ((Terminal) holeAnwendung()).setInterrupt(true); } if (e.getKeyCode() == KeyEvent.VK_UP || e.getKeyCode() == KeyEvent.VK_DOWN) { // 38 arrow-up / 40 arrow-down if (e.getKeyCode() == KeyEvent.VK_UP) { terminalCommandListStep++; } if (e.getKeyCode() == KeyEvent.VK_DOWN) { terminalCommandListStep--; } if (terminalCommandListStep < -1) { terminalCommandListStep = -1; } if (terminalCommandListStep >= terminalCommandList.size()) { terminalCommandListStep = terminalCommandList.size() - 1; } try { if (terminalCommandListStep != -1) { inputField.setText(terminalCommandList.get(terminalCommandList.size() - 1 - terminalCommandListStep)); } else if (terminalCommandListStep == -1) { inputField.setText(""); } } catch (IndexOutOfBoundsException eis) { } } } public void keyReleased(KeyEvent arg0) { } public void keyTyped(KeyEvent arg0) { } }); inputLabel = new JLabel(">"); inputLabel.setBackground(new Color(0,0,0)); inputLabel.setForeground(new Color(222,222,222)); inputLabel.setFont(new Font("Courier New",Font.PLAIN,11)); Box terminalBox = Box.createHorizontalBox(); terminalBox.setBackground(new Color(0,0,0)); terminalBox.add(tpPane); // terminalField embedded in ScrollPane terminalBox.setBorder(BorderFactory.createEmptyBorder(5,5,1,5)); Box inputBox = Box.createHorizontalBox(); inputBox.setBackground(new Color(0,0,0)); inputBox.add(inputLabel); inputBox.add(Box.createHorizontalStrut(1)); inputBox.add(inputField); inputBox.setBorder(BorderFactory.createEmptyBorder(0,5,5,5)); backPanel = new JPanel(new BorderLayout()); backPanel.setBackground(new Color(0,0,0)); backPanel.add(terminalBox, BorderLayout.CENTER); backPanel.add(inputBox, BorderLayout.SOUTH); this.getContentPane().add(backPanel); terminalField.setText( "" ); - for (int i=0; i<12; i++) { terminalField.append(" \n"); } // padding with new lines for bottom alignment of new output - terminalField.append( "================================================================\n" ); - terminalField.append(messages.getString("sw_terminal_msg25")); - terminalField.append( "================================================================\n\n" ); try { Thread.sleep(100); } catch (InterruptedException e) {} this.tpPane.getVerticalScrollBar().setValue(this.tpPane.getVerticalScrollBar().getMaximum()); pack(); inputField.requestFocus(); this.inputLabel.setText("root "+Dateisystem.absoluterPfad(((Terminal)holeAnwendung()).getAktuellerOrdner())+"> "); } public void setMultipleObserverEvents(boolean flag) { } public void windowActivated(WindowEvent e) { } public void windowClosing(WindowEvent e) { } public void windowDeactivated(WindowEvent e) { } public void windowDeiconified(WindowEvent e) { } public void windowIconified(WindowEvent e) { } public void windowOpened(WindowEvent e) { } public void internalFrameActivated(InternalFrameEvent e) { } public void internalFrameClosed(InternalFrameEvent e) { } public void internalFrameClosing(InternalFrameEvent e) { } public void internalFrameDeactivated(InternalFrameEvent e) { } public void internalFrameDeiconified(InternalFrameEvent e) { } public void internalFrameIconified(InternalFrameEvent e) { } public void internalFrameOpened(InternalFrameEvent e) { } public void update(Observable arg0, Object arg1) { Main.debug.println("INVOKED ("+this.hashCode()+") "+getClass()+" (GUIApplicationTerminalWindow), update("+arg0+","+arg1+")"); if (arg1 == null) return; if (jobRunning) { if (arg1 instanceof Boolean) { multipleObserverEvents=((Boolean) arg1).booleanValue(); } else { // expect String this.terminalField.append(arg1.toString()); try { // mini delay to let the terminalField reliably update its new height Thread.sleep(200); } catch (InterruptedException e) {} this.tpPane.repaint(); this.tpPane.getVerticalScrollBar().setValue(this.tpPane.getVerticalScrollBar().getMaximum()); if (!multipleObserverEvents) { // is this observer call expected to be the last one for the current command, i.e., multipleOverserverEvents=false? this.inputLabel.setText("root "+Dateisystem.absoluterPfad(((Terminal)holeAnwendung()).getAktuellerOrdner())+"> "); this.inputLabel.setVisible(true); jobRunning=false; } } } } }
false
true
public GUIApplicationTerminalWindow(GUIDesktopPanel desktop, String appName){ super(desktop, appName); this.setMaximizable(false); this.setResizable(false); jobRunning = false; multipleObserverEvents = false; terminalField = new JTextArea(""); terminalField.setEditable(false); terminalField.setCaretColor(new Color(222,222,222)); terminalField.setForeground(new Color(222,222,222)); terminalField.setBackground(new Color(0,0,0)); terminalField.setFont(new Font("Courier New",Font.PLAIN,11)); terminalField.setFocusable(false); terminalField.setBorder(null); tpPane = new JScrollPane(terminalField); // make textfield scrollable tpPane.setBorder(null); tpPane.setBackground(new Color(0,0,0)); tpPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER); // do not show vert. scrollbar tpPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); // do not show hor. scrollbar inputField = new JTextField(""); inputField.setEditable(true); inputField.setBackground(new Color(0,0,0)); inputField.setForeground(new Color(222,222,222)); inputField.setCaretColor(new Color(222,222,222)); inputField.setBorder(null); inputField.setFont(new Font("Courier New",Font.PLAIN,11)); inputField.addKeyListener(new KeyListener() { public void keyPressed(KeyEvent e) { if(e.getKeyCode() == KeyEvent.VK_ENTER) { terminalCommandListStep = -1; // lass uns doch besser wieder von unten/vorne beginnen if(!(inputField.getText().isEmpty() || inputField.getText().replaceAll(" ", "").isEmpty())) { // only process non-empty input //Main.debug.println("DEBUG: "+getClass()+", keyPressed ('"+inputField.getText()+" + ENTER') event started"); terminalField.append("\n"+inputLabel.getText()+inputField.getText()+"\n"); StringTokenizer tk = new StringTokenizer(inputField.getText(), " "); /* Erstes Token enthaelt den Befehl*/ enteredCommand = tk.nextToken(); /* restliche Tokens werden in String Array geschrieben. * Array wird sicherheitshalber mit mindestens 3 leeren Strings gefüllt! */ enteredParameters = new String[3+tk.countTokens()]; for (int i =0; i< 3+tk.countTokens(); i++) { enteredParameters[i] = new String(); } int iti = 0; while (tk.hasMoreTokens()) { enteredParameters[iti] =tk.nextToken(); iti++; } if (enteredCommand.equals("exit")) { doDefaultCloseAction(); } else if (enteredCommand.equals("reset")) { terminalField.setText( "" ); for (int i=0; i<15; i++) { terminalField.append(" \n"); } // padding with new lines for bottom alignment of new output terminalField.append( "================================================================\n" ); terminalField.append(messages.getString("sw_terminal_msg25") + "================================================================" + "\n"); } else { inputLabel.setVisible(false); jobRunning = true; terminalCommandList.add(inputField.getText()); ((Terminal) holeAnwendung()).terminalEingabeAuswerten(enteredCommand,enteredParameters); } } else { terminalField.append("\n"); } //Main.debug.println("DEBUG: "+getClass()+", keyPressed ('"+inputField.getText()+" + ENTER') event finished"); inputField.setText(""); } if (e.getKeyCode() == KeyEvent.VK_C && e.getModifiers() == 2) { // [strg] + [c] System.out.println("INTERRUPT"); ((Terminal) holeAnwendung()).setInterrupt(true); } if (e.getKeyCode() == KeyEvent.VK_UP || e.getKeyCode() == KeyEvent.VK_DOWN) { // 38 arrow-up / 40 arrow-down if (e.getKeyCode() == KeyEvent.VK_UP) { terminalCommandListStep++; } if (e.getKeyCode() == KeyEvent.VK_DOWN) { terminalCommandListStep--; } if (terminalCommandListStep < -1) { terminalCommandListStep = -1; } if (terminalCommandListStep >= terminalCommandList.size()) { terminalCommandListStep = terminalCommandList.size() - 1; } try { if (terminalCommandListStep != -1) { inputField.setText(terminalCommandList.get(terminalCommandList.size() - 1 - terminalCommandListStep)); } else if (terminalCommandListStep == -1) { inputField.setText(""); } } catch (IndexOutOfBoundsException eis) { } } } public void keyReleased(KeyEvent arg0) { } public void keyTyped(KeyEvent arg0) { } }); inputLabel = new JLabel(">"); inputLabel.setBackground(new Color(0,0,0)); inputLabel.setForeground(new Color(222,222,222)); inputLabel.setFont(new Font("Courier New",Font.PLAIN,11)); Box terminalBox = Box.createHorizontalBox(); terminalBox.setBackground(new Color(0,0,0)); terminalBox.add(tpPane); // terminalField embedded in ScrollPane terminalBox.setBorder(BorderFactory.createEmptyBorder(5,5,1,5)); Box inputBox = Box.createHorizontalBox(); inputBox.setBackground(new Color(0,0,0)); inputBox.add(inputLabel); inputBox.add(Box.createHorizontalStrut(1)); inputBox.add(inputField); inputBox.setBorder(BorderFactory.createEmptyBorder(0,5,5,5)); backPanel = new JPanel(new BorderLayout()); backPanel.setBackground(new Color(0,0,0)); backPanel.add(terminalBox, BorderLayout.CENTER); backPanel.add(inputBox, BorderLayout.SOUTH); this.getContentPane().add(backPanel); terminalField.setText( "" ); for (int i=0; i<12; i++) { terminalField.append(" \n"); } // padding with new lines for bottom alignment of new output terminalField.append( "================================================================\n" ); terminalField.append(messages.getString("sw_terminal_msg25")); terminalField.append( "================================================================\n\n" ); try { Thread.sleep(100); } catch (InterruptedException e) {} this.tpPane.getVerticalScrollBar().setValue(this.tpPane.getVerticalScrollBar().getMaximum()); pack(); inputField.requestFocus(); this.inputLabel.setText("root "+Dateisystem.absoluterPfad(((Terminal)holeAnwendung()).getAktuellerOrdner())+"> "); }
public GUIApplicationTerminalWindow(GUIDesktopPanel desktop, String appName) { super(desktop, appName); this.setMaximizable(false); this.setResizable(false); jobRunning = false; multipleObserverEvents = false; terminalField = new JTextArea(""); terminalField.setEditable(false); terminalField.setCaretColor(new Color(222,222,222)); terminalField.setForeground(new Color(222,222,222)); terminalField.setBackground(new Color(0,0,0)); terminalField.setFont(new Font("Courier New",Font.PLAIN,11)); terminalField.setFocusable(false); terminalField.setBorder(null); tpPane = new JScrollPane(terminalField); // make textfield scrollable tpPane.setBorder(null); tpPane.setBackground(new Color(0,0,0)); tpPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER); // do not show vert. scrollbar tpPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); // do not show hor. scrollbar inputField = new JTextField(""); inputField.setEditable(true); inputField.setBackground(new Color(0,0,0)); inputField.setForeground(new Color(222,222,222)); inputField.setCaretColor(new Color(222,222,222)); inputField.setBorder(null); inputField.setFont(new Font("Courier New",Font.PLAIN,11)); inputField.addKeyListener(new KeyListener() { public void keyPressed(KeyEvent e) { if(e.getKeyCode() == KeyEvent.VK_ENTER) { terminalCommandListStep = -1; // lass uns doch besser wieder von unten/vorne beginnen if(!(inputField.getText().isEmpty() || inputField.getText().replaceAll(" ", "").isEmpty())) { // only process non-empty input //Main.debug.println("DEBUG: "+getClass()+", keyPressed ('"+inputField.getText()+" + ENTER') event started"); terminalField.append("\n"+inputLabel.getText()+inputField.getText()+"\n"); StringTokenizer tk = new StringTokenizer(inputField.getText(), " "); /* Erstes Token enthaelt den Befehl*/ enteredCommand = tk.nextToken(); /* restliche Tokens werden in String Array geschrieben. * Array wird sicherheitshalber mit mindestens 3 leeren Strings gefüllt! */ enteredParameters = new String[3+tk.countTokens()]; for (int i =0; i< 3+tk.countTokens(); i++) { enteredParameters[i] = new String(); } int iti = 0; while (tk.hasMoreTokens()) { enteredParameters[iti] =tk.nextToken(); iti++; } if (enteredCommand.equals("exit")) { doDefaultCloseAction(); } else if (enteredCommand.equals("reset")) { terminalField.setText( "" ); for (int i=0; i<15; i++) { terminalField.append(" \n"); } // padding with new lines for bottom alignment of new output terminalField.append( "================================================================\n" ); terminalField.append(messages.getString("sw_terminal_msg25") + "================================================================" + "\n"); } else { inputLabel.setVisible(false); jobRunning = true; terminalCommandList.add(inputField.getText()); ((Terminal) holeAnwendung()).terminalEingabeAuswerten(enteredCommand,enteredParameters); } } else { terminalField.append("\n"); } //Main.debug.println("DEBUG: "+getClass()+", keyPressed ('"+inputField.getText()+" + ENTER') event finished"); inputField.setText(""); } if (e.getKeyCode() == KeyEvent.VK_C && e.getModifiers() == 2) { // [strg] + [c] System.out.println("INTERRUPT"); ((Terminal) holeAnwendung()).setInterrupt(true); } if (e.getKeyCode() == KeyEvent.VK_UP || e.getKeyCode() == KeyEvent.VK_DOWN) { // 38 arrow-up / 40 arrow-down if (e.getKeyCode() == KeyEvent.VK_UP) { terminalCommandListStep++; } if (e.getKeyCode() == KeyEvent.VK_DOWN) { terminalCommandListStep--; } if (terminalCommandListStep < -1) { terminalCommandListStep = -1; } if (terminalCommandListStep >= terminalCommandList.size()) { terminalCommandListStep = terminalCommandList.size() - 1; } try { if (terminalCommandListStep != -1) { inputField.setText(terminalCommandList.get(terminalCommandList.size() - 1 - terminalCommandListStep)); } else if (terminalCommandListStep == -1) { inputField.setText(""); } } catch (IndexOutOfBoundsException eis) { } } } public void keyReleased(KeyEvent arg0) { } public void keyTyped(KeyEvent arg0) { } }); inputLabel = new JLabel(">"); inputLabel.setBackground(new Color(0,0,0)); inputLabel.setForeground(new Color(222,222,222)); inputLabel.setFont(new Font("Courier New",Font.PLAIN,11)); Box terminalBox = Box.createHorizontalBox(); terminalBox.setBackground(new Color(0,0,0)); terminalBox.add(tpPane); // terminalField embedded in ScrollPane terminalBox.setBorder(BorderFactory.createEmptyBorder(5,5,1,5)); Box inputBox = Box.createHorizontalBox(); inputBox.setBackground(new Color(0,0,0)); inputBox.add(inputLabel); inputBox.add(Box.createHorizontalStrut(1)); inputBox.add(inputField); inputBox.setBorder(BorderFactory.createEmptyBorder(0,5,5,5)); backPanel = new JPanel(new BorderLayout()); backPanel.setBackground(new Color(0,0,0)); backPanel.add(terminalBox, BorderLayout.CENTER); backPanel.add(inputBox, BorderLayout.SOUTH); this.getContentPane().add(backPanel); terminalField.setText( "" ); try { Thread.sleep(100); } catch (InterruptedException e) {} this.tpPane.getVerticalScrollBar().setValue(this.tpPane.getVerticalScrollBar().getMaximum()); pack(); inputField.requestFocus(); this.inputLabel.setText("root "+Dateisystem.absoluterPfad(((Terminal)holeAnwendung()).getAktuellerOrdner())+"> "); }
diff --git a/src/main/java/com/laytonsmith/PureUtilities/StringUtils.java b/src/main/java/com/laytonsmith/PureUtilities/StringUtils.java index f4d6eea8..166332db 100644 --- a/src/main/java/com/laytonsmith/PureUtilities/StringUtils.java +++ b/src/main/java/com/laytonsmith/PureUtilities/StringUtils.java @@ -1,866 +1,867 @@ package com.laytonsmith.PureUtilities; import java.math.BigInteger; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * * @author lsmith */ public final class StringUtils { private StringUtils() { // } /** * Joins a map together (using StringBuilder's { * * @see StringBuilder#append(Object)} method to "toString" the Object) * * @param map The map to concatenate * @param entryGlue The glue to use between the key and value of each pair * in the map * @param elementGlue The glue to use between each key-value element pairs * in the map * @return The concatenated string */ public static String Join(Map map, String entryGlue, String elementGlue) { return Join(map, entryGlue, elementGlue, null, null, null); } /** * Joins a map together (using StringBuilder's { * * @see StringBuilder#append(Object)} method to "toString" the Object) * * @param map The map to concatenate * @param entryGlue The glue to use between the key and value of each pair * in the map * @param elementGlue The glue to use between each key-value element pairs * in the map * @param lastElementGlue The glue for the last two elements * @param glueForTwoItems If only two items are in the map, then this glue * is used instead. If it is null, then lastElementGlue is used instead. * @param empty If the map is completely empty, this string is simply * returned. If null, an empty string is used. * @return The concatenated string */ public static String Join(Map map, String entryGlue, String elementGlue, String lastElementGlue) { return Join(map, entryGlue, elementGlue, lastElementGlue, null, null); } /** * Joins a map together (using StringBuilder's { * * @see StringBuilder#append(Object)} method to "toString" the Object) * * @param map The map to concatenate * @param entryGlue The glue to use between the key and value of each pair * in the map * @param elementGlue The glue to use between each key-value element pairs * in the map * @param lastElementGlue The glue for the last two elements * @param glueForTwoItems If only two items are in the map, then this glue * is used instead. If it is null, then lastElementGlue is used instead. * @return The concatenated string */ public static String Join(Map map, String entryGlue, String elementGlue, String lastElementGlue, String elementGlueForTwoItems) { return Join(map, entryGlue, elementGlue, lastElementGlue, elementGlueForTwoItems, null); } /** * Joins a map together (using StringBuilder's { * * @see StringBuilder#append(Object)} method to "toString" the Object) * * @param map The map to concatenate * @param entryGlue The glue to use between the key and value of each pair * in the map * @param elementGlue The glue to use between each key-value element pairs * in the map * @param lastElementGlue The glue for the last two elements * @param glueForTwoItems If only two items are in the map, then this glue * is used instead. If it is null, then lastElementGlue is used instead. * @param empty If the map is completely empty, this string is simply * returned. If null, an empty string is used. * @return The concatenated string */ public static String Join(Map map, String entryGlue, String elementGlue, String lastElementGlue, String elementGlueForTwoItems, String empty) { //Just create a list of glued together entries, then send it to the other Join method List<String> list = new ArrayList<String>(); for (Object key : map.keySet()) { StringBuilder b = new StringBuilder(); b.append(key).append(entryGlue).append(map.get(key)); list.add(b.toString()); } return Join(list, elementGlue, lastElementGlue, elementGlueForTwoItems, empty); } /** * Joins a set together (using StringBuilder's { * * @see StringBuilder#append(Object)} method to "toString" the Object) using * the specified string for glue. * @param list The set to concatenate * @param glue The glue to use * @return The concatenated string */ public static String Join(Set set, String glue) { return Join(set, glue, null, null, null); } /** * Joins a set together (using StringBuilder's { * * @see StringBuilder#append(Object)} method to "toString" the Object) using * the specified string for glue. If lastGlue is null, it is the same as * glue, but otherwise it is used to glue just the last two items together, * which is useful for sets that are being read by a human, to have a proper * conjunction at the end. * @param list The set to concatenate * @param glue The glue to use * @param lastGlue The glue for the last two elements * @return The concatenated string */ public static String Join(Set set, String glue, String lastGlue) { return Join(set, glue, lastGlue, null, null); } /** * Joins a set together (using StringBuilder's { * * @see StringBuilder#append(Object)} method to "toString" the Object) using * the specified string for glue. If lastGlue is null, it is the same as * glue, but otherwise it is used to glue just the last two items together, * which is useful for sets that are being read by a human, to have a proper * conjunction at the end. * @param list The set to concatenate * @param glue The glue to use * @param lastGlue The glue for the last two elements * @param glueForTwoItems If only two items are in the set, then this glue * is used instead. If it is null, then lastGlue is used instead. * @return The concatenated string */ public static String Join(Set set, String glue, String lastGlue, String glueForTwoItems) { return Join(set, glue, lastGlue, glueForTwoItems, null); } /** * Joins a set together (using StringBuilder's { * * @see StringBuilder#append(Object)} method to "toString" the Object) using * the specified string for glue. If lastGlue is null, it is the same as * glue, but otherwise it is used to glue just the last two items together, * which is useful for sets that are being read by a human, to have a proper * conjunction at the end. * @param list The set to concatenate * @param glue The glue to use * @param lastGlue The glue for the last two elements * @param glueForTwoItems If only two items are in the set, then this glue * is used instead. If it is null, then lastGlue is used instead. * @param empty If the set is completely empty, this string is simply * returned. If null, an empty string is used. * @return The concatenated string */ public static String Join(Set set, String glue, String lastGlue, String glueForTwoItems, String empty) { return Join(set, glue, lastGlue, glueForTwoItems, empty, null); } /** * Joins a set together (using StringBuilder's { * * @see StringBuilder#append(Object)} method to "toString" the Object) using * the specified string for glue. If lastGlue is null, it is the same as * glue, but otherwise it is used to glue just the last two items together, * which is useful for sets that are being read by a human, to have a proper * conjunction at the end. * @param list The set to concatenate * @param glue The glue to use * @param lastGlue The glue for the last two elements * @param glueForTwoItems If only two items are in the set, then this glue * is used instead. If it is null, then lastGlue is used instead. * @param empty If the set is completely empty, this string is simply * returned. If null, an empty string is used. * @return The concatenated string */ public static <T> String Join(Set<T> set, String glue, String lastGlue, String glueForTwoItems, String empty, Renderer<T> renderer) { final List<T> list = new ArrayList<T>(set); return doJoin(new ItemGetter<T>() { public T get(int index) { return list.get(index); } public int size() { return list.size(); } public boolean isEmpty() { return list.isEmpty(); } }, glue, lastGlue, glueForTwoItems, empty, renderer); } /** * Joins an array together (using StringBuilder's { * * @see StringBuilder#append(Object)} method to "toString" the Object) using * the specified string for glue. * @param list The array to concatenate * @param glue The glue to use * @return The concatenated string */ public static String Join(Object[] list, String glue) { return Join(list, glue, null, null, null); } /** * Joins an array together (using StringBuilder's { * * @see StringBuilder#append(Object)} method to "toString" the Object) using * the specified string for glue. If lastGlue is null, it is the same as * glue, but otherwise it is used to glue just the last two items together, * which is useful for lists that are being read by a human, to have a * proper conjunction at the end. * @param list The array to concatenate * @param glue The glue to use * @param lastGlue The glue for the last two elements * @return The concatenated string */ public static String Join(Object[] list, String glue, String lastGlue) { return Join(list, glue, lastGlue, null, null); } /** * Joins an array together (using StringBuilder's { * * @see StringBuilder#append(Object)} method to "toString" the Object) using * the specified string for glue. If lastGlue is null, it is the same as * glue, but otherwise it is used to glue just the last two items together, * which is useful for lists that are being read by a human, to have a * proper conjunction at the end. * @param list The array to concatenate * @param glue The glue to use * @param lastGlue The glue for the last two elements * @param glueForTwoItems If only two items are in the array, then this glue * is used instead. If it is null, then lastGlue is used instead. * @return The concatenated string */ public static String Join(Object[] list, String glue, String lastGlue, String glueForTwoItems) { return Join(list, glue, lastGlue, glueForTwoItems, null); } /** * Joins an array together (using StringBuilder's { * * @see StringBuilder#append(Object)} method to "toString" the Object) using * the specified string for glue. If lastGlue is null, it is the same as * glue, but otherwise it is used to glue just the last two items together, * which is useful for lists that are being read by a human, to have a * proper conjunction at the end. * @param list The array to concatenate * @param glue The glue to use * @param lastGlue The glue for the last two elements * @param glueForTwoItems If only two items are in the array, then this glue * is used instead. If it is null, then lastGlue is used instead. * @param empty If the array is completely empty, this string is simply * returned. If null, an empty string is used. * @return The concatenated string */ public static String Join(Object[] list, String glue, String lastGlue, String glueForTwoItems, String empty) { return Join(list, glue, lastGlue, glueForTwoItems, empty, null); } /** * Joins an array together (using StringBuilder's { * * @see StringBuilder#append(Object)} method to "toString" the Object) using * the specified string for glue. If lastGlue is null, it is the same as * glue, but otherwise it is used to glue just the last two items together, * which is useful for lists that are being read by a human, to have a * proper conjunction at the end. * @param list The array to concatenate * @param glue The glue to use * @param lastGlue The glue for the last two elements * @param glueForTwoItems If only two items are in the array, then this glue * is used instead. If it is null, then lastGlue is used instead. * @param empty If the array is completely empty, this string is simply * returned. If null, an empty string is used. * @param renderer The item renderer. This renders each item in the list, one at a time. * If null, toString will be used by default on each item. * @return The concatenated string */ public static String Join(final Object[] list, String glue, String lastGlue, String glueForTwoItems, String empty, Renderer<Object> renderer) { return doJoin(new ItemGetter<Object>() { public Object get(int index) { return list[index]; } public int size() { return list.length; } public boolean isEmpty() { return list.length == 0; } }, glue, lastGlue, glueForTwoItems, empty, renderer); } /** * Joins a list together (using StringBuilder's { * * @see StringBuilder#append(Object)} method to "toString" the Object) using * the specified string for glue. * @param list The list to concatenate * @param glue The glue to use * @return The concatenated string */ public static String Join(List list, String glue) { return Join(list, glue, null, null, null); } /** * Joins a list together (using StringBuilder's { * * @see StringBuilder#append(Object)} method to "toString" the Object) using * the specified string for glue. If lastGlue is null, it is the same as * glue, but otherwise it is used to glue just the last two items together, * which is useful for lists that are being read by a human, to have a * proper conjunction at the end. * @param list The list to concatenate * @param glue The glue to use * @param lastGlue The glue for the last two elements * @return The concatenated string */ public static String Join(List list, String glue, String lastGlue) { return Join(list, glue, lastGlue, null, null); } /** * Joins a list together (using StringBuilder's { * * @see StringBuilder#append(Object)} method to "toString" the Object) using * the specified string for glue. If lastGlue is null, it is the same as * glue, but otherwise it is used to glue just the last two items together, * which is useful for lists that are being read by a human, to have a * proper conjunction at the end. * @param list The list to concatenate * @param glue The glue to use * @param lastGlue The glue for the last two elements * @param glueForTwoItems If only two items are in the list, then this glue * is used instead. If it is null, then lastGlue is used instead. * @return The concatenated string */ public static String Join(List list, String glue, String lastGlue, String glueForTwoItems) { return Join(list, glue, lastGlue, glueForTwoItems, null); } /** * Joins a list together (using StringBuilder's { * * @see StringBuilder#append(Object)} method to "toString" the Object) using * the specified string for glue. If lastGlue is null, it is the same as * glue, but otherwise it is used to glue just the last two items together, * which is useful for lists that are being read by a human, to have a * proper conjunction at the end. * @param list The list to concatenate * @param glue The glue to use * @param lastGlue The glue for the last two elements * @param glueForTwoItems If only two items are in the list, then this glue * is used instead. If it is null, then lastGlue is used instead. * @param empty If the list is completely empty, this string is simply * returned. If null, an empty string is used. * @return The concatenated string */ public static String Join(final List list, String glue, String lastGlue, String glueForTwoItems, String empty) { return Join(list, glue, lastGlue, glueForTwoItems, empty, null); } /** * Joins a list together (using StringBuilder's { * * @see StringBuilder#append(Object)} method to "toString" the Object) using * the specified string for glue. If lastGlue is null, it is the same as * glue, but otherwise it is used to glue just the last two items together, * which is useful for lists that are being read by a human, to have a * proper conjunction at the end. * @param list The list to concatenate * @param glue The glue to use * @param lastGlue The glue for the last two elements * @param glueForTwoItems If only two items are in the list, then this glue * is used instead. If it is null, then lastGlue is used instead. * @param empty If the list is completely empty, this string is simply * returned. If null, an empty string is used. * @param renderer The item renderer. This renders each item in the list, one at a time. * If null, toString will be used by default on each item. * @return The concatenated string */ public static <T> String Join(final List<T> list, String glue, String lastGlue, String glueForTwoItems, String empty, Renderer<T> renderer) { return doJoin(new ItemGetter<T>() { public T get(int index) { return list.get(index); } public int size() { return list.size(); } public boolean isEmpty() { return list.isEmpty(); } }, glue, lastGlue, glueForTwoItems, empty, renderer); } /** * Abstracted version of the join algorithm. * @param <T> * @param items * @param glue * @param lastGlue * @param glueForTwoItems * @param empty * @param renderer * @return */ private static <T> String doJoin(ItemGetter<T> items, String glue, String lastGlue, String glueForTwoItems, String empty, Renderer<T> renderer){ if(renderer == null){ renderer = new Renderer<T>() { public String toString(T item) { if(item == null){ return "null"; } else { return item.toString(); } } }; } if (lastGlue == null) { lastGlue = glue; } if (glueForTwoItems == null) { glueForTwoItems = lastGlue; } if (items.isEmpty()) { return empty == null ? "" : empty; } else if (items.size() == 2) { StringBuilder b = new StringBuilder(); return b.append(renderer.toString(items.get(0))) .append(glueForTwoItems) .append(renderer.toString(items.get(1))).toString(); } else { StringBuilder b = new StringBuilder(); for (int i = 0; i < items.size(); i++) { T o = items.get(i); if (i != 0) { if (i == items.size() - 1) { b.append(lastGlue); } else { b.append(glue); } } b.append(renderer.toString(o)); } return b.toString(); } } private static interface ItemGetter<T> { T get(int index); int size(); boolean isEmpty(); } /** * Used to provide a renderer for each item when glueing the items * together. * @param <T> The type of each item */ public static interface Renderer<T> { /** * * @param item * @return */ String toString(T item); } private static int minimum(int a, int b, int c) { return Math.min(Math.min(a, b), c); } /** * Returns the levenshtein distance of two character sequences. For * instance, "123" and "133" would have a string distance of 1, while "123" * and "123" would be 0, since they are the same string. * * @param str1 * @param str2 * @return */ public static int LevenshteinDistance(CharSequence str1, CharSequence str2) { int[][] distance = new int[str1.length() + 1][str2.length() + 1]; for (int i = 0; i <= str1.length(); i++) { distance[i][0] = i; } for (int j = 0; j <= str2.length(); j++) { distance[0][j] = j; } for (int i = 1; i <= str1.length(); i++) { for (int j = 1; j <= str2.length(); j++) { distance[i][j] = minimum( distance[i - 1][j] + 1, distance[i][j - 1] + 1, distance[i - 1][j - 1] + ((str1.charAt(i - 1) == str2.charAt(j - 1)) ? 0 : 1)); } } return distance[str1.length()][str2.length()]; } /** * Splits an argument string into arguments. It is expected that the string: * * <code>this is "a 'quoted'" '\'string\''</code> * * would parse into 4 arguments, individually, "this", "is", "a 'quoted'", * "'string'". It essentially handles the very basic case of command line * argument parsing. * * @param args * @return */ public static List<String> ArgParser(String args) { //First, we have to tokenize the strings. Since we can have quoted arguments, we can't simply split on spaces. List<String> arguments = new ArrayList<String>(); StringBuilder buf = new StringBuilder(); boolean state_in_single_quote = false; boolean state_in_double_quote = false; for (int i = 0; i < args.length(); i++) { Character c0 = args.charAt(i); Character c1 = i + 1 < args.length() ? args.charAt(i + 1) : null; if (c0 == '\\') { - if (c1 == '\'' && state_in_single_quote + if (c1 != null + && (c1 == '\'' && state_in_single_quote || c1 == '"' && state_in_double_quote || c1 == ' ' && !state_in_double_quote && !state_in_single_quote - || c1 == '\\' && (state_in_double_quote || state_in_single_quote)) { + || c1 == '\\' && (state_in_double_quote || state_in_single_quote))) { //We are escaping the next character. Add it to the buffer instead, and //skip ahead two buf.append(c1); i++; continue; } } if (c0 == ' ') { if (!state_in_double_quote && !state_in_single_quote) { //argument split if (buf.length() != 0) { arguments.add(buf.toString()); buf = new StringBuilder(); } continue; } } if (c0 == '\'' && !state_in_double_quote) { if (state_in_single_quote) { state_in_single_quote = false; arguments.add(buf.toString()); buf = new StringBuilder(); } else { if (buf.length() != 0) { arguments.add(buf.toString()); buf = new StringBuilder(); } state_in_single_quote = true; } continue; } if (c0 == '"' && !state_in_single_quote) { if (state_in_double_quote) { state_in_double_quote = false; arguments.add(buf.toString()); buf = new StringBuilder(); } else { if (buf.length() != 0) { arguments.add(buf.toString()); buf = new StringBuilder(); } state_in_double_quote = true; } continue; } buf.append(c0); } if (buf.length() != 0) { arguments.add(buf.toString()); } return arguments; } public static String trimLeft(String str) { //If the argument is null then return empty string if (str == null) { return ""; } /* The charAt method returns the character at a particular position in a String. * We check to see if the character at position 0 (the leading character) is a space. * If it is, use substring to make a new String that starts after the space. */ int len = 0; while (str.charAt(len) == ' ') { len++; } return str.substring(len); } public static String trimRight(String str) { //If the argument is null then return empty string if (str == null) { return ""; } /* The logic for Rtrim is, While the last character in the String is a space, remove it. * In the code, take the length of the string and use it to determine if the last character is a space. */ int len = str.length(); while (len > 0 && str.charAt(len - 1) == ' ') { len--; } str = str.substring(0, len); return str; } /** * Works like String.split(), but trims each of the entries also. * * @param string * @param regex * @return */ public static String[] trimSplit(String string, String regex) { String[] split = string.split(regex); for (int i = 0; i < split.length; i++) { split[i] = split[i].trim(); } return split; } /** * Works like String.replaceFirst, but replaces the last instance instead. * * @param string * @param regex * @param replacement * @return */ public static String replaceLast(String string, String regex, String replacement) { if (regex == null) { return string; } if (string == null) { return null; } if (regex.length() > string.length()) { //It can't be contained in here return string; } Matcher m = Pattern.compile(regex).matcher(string); int start = -1; int end = -1; while (m.find()) { start = m.start(); end = m.end(); } if (start == -1 || end == -1) { //Didn't find it, return the whole string return string; } else { return string.substring(0, start) + replacement + string.substring(end, string.length()); } } /** * Convenience method for HumanReadableByteCount(bytes, true). * @param bytes * @return */ public static String HumanReadableByteCount(long bytes){ return HumanReadableByteCount(bytes, true); } /** * Returns a human readable byte count, given a byte count. * @param bytes * @param si * @return */ public static String HumanReadableByteCount(long bytes, boolean si) { int unit = si ? 1000 : 1024; if (bytes < unit) { return bytes + " B"; } int exp = (int) (Math.log(bytes) / Math.log(unit)); String pre = (si ? "kMGTPE" : "KMGTPE").charAt(exp - 1) + (si ? "" : "i"); return String.format("%.1f %sB", bytes / Math.pow(unit, exp), pre); } /** * Returns a properly agreeing subject verb clause given a count, and singular * subject. This version assumes that the plural subject can be made simply by appending * <code>s</code> to the singular subject, which is not always true. * This is useful in cases where forming a sentence * requires different wording depending on the count. Usually, you might use a fairly * complex tertiary statement, for instance: <code>String message = "There " + (count==1?"is":"are") + * " " + count + " test failure" + (count==1?"":"s");</code> This is time consuming, and easy to mess up * or accidentally reverse. Instead, you can use this function. Note that this will add <code>is</code> * or </code>are</code> for you. You need only to provide the count, singular subject, and plural subject. * If the subject cannot be made plural with just an <code>s</code>, use {@link #PluralHelper(int, java.lang.String, java.lang.String)} * instead. Usage example: * * <pre> * String message = "There " + PluralHelper(count, "test failure"); * //If count is 1: There is 1 test failure * //If count is not 1: There are 2 test failures * </pre> * * @param count The count of items * @param singular The subject of the sentence, as a singular * @return The properly formatted clause. */ public static String PluralHelper(int count, String singular){ return PluralHelper(count, singular, singular + "s"); } /** * Returns a properly agreeing subject verb clause given a count, singular * subject, and plural subject. This is useful in cases where forming a sentence * requires different wording depending on the count. Usually, you might use a fairly * complex tertiary statement, for instance: <code>String message = "There " + (count==1?"is":"are") + * " " + count + " test failure" + (count==1?"":"s");</code> This is time consuming, and easy to mess up * or accidentally reverse. Instead, you can use this function. Note that this will add <code>is</code> * or </code>are</code> for you. You need only to provide the count, singular subject, and plural subject. * If the subject can be made plural with just an <code>s</code>, use {@link #PluralHelper(int, java.lang.String)} * instead. Usage example: * * <pre> * String message = "There " + PluralHelper(count, "fish", "fish"); * //If count is 1: There is 1 fish * //If count is not 1: There are 2 fish * </pre> * * @param count The count of items * @param singular The subject of the sentence, as a singular * @param plural The subject of the sentence, as a plural * @return The properly formatted clause. */ public static String PluralHelper(int count, String singular, String plural){ return (count==1?"is":"are") + " " + count + " " + (count==1?singular:plural); } /** * For even more complex sentences, it may just be easiest to provide a template, * which will be replaced, if the count is singular or plural. Both singularTemplate * and pluralTemplate are expected to be String.format templates with a %d in them, which will * be replaced with the actual count number. If the count == 1, then the singularTemplate will * be used, else the pluralTemplate will be used. * Usage example: * * <pre> * String message = PluralTemplateHelper(count, "I will buy %d car if it has a good price", * "I will buy %d cars if they have a good price"); * </pre> * @param count The count of items * @param singularTemplate The singular template * @param pluralTemplate The plural template * @return */ public static String PluralTemplateHelper(int count, String singularTemplate, String pluralTemplate){ if(count == 1){ return String.format(singularTemplate, count); } else { return String.format(pluralTemplate, count); } } /** * This is the system newline string. For instance, on windows, this would * likely be \r\n, and unix systems would likely be \n. */ public static final String nl = System.getProperty("line.separator"); /** * This returns the system newline string. For instance, on windows, this would * likely return \r\n, and unix systems would likely return \n. * @return The system newline string. */ public static String nl(){ return nl; } /** * Multiplies a string. For instance, stringMultiply(3, "abc") would * return "abcabcabc". If count is 0, an empty string is returned, and * if count is 1, the character sequence itself is returned. * @param count The repeat count * @param s The sequence to repeat * @return The multiplied string * @throws IllegalArgumentException If count is less than 0. */ public static String stringMultiply(int count, CharSequence s){ if(count < 0){ throw new IllegalArgumentException("Count must be greater than or equal to 0"); } if(count == 0){ return ""; } if(count == 1){ return s.toString(); } //Ok, actually have to do the multiply now. StringBuilder b = new StringBuilder(); for(int i = 0; i < count; i++){ b.append(s); } return b.toString(); } /** * Given a string, returns a string that could be printed out in Java source * code. That is, all escapable characters are reversed. The returned string will * already be surrounded by quotes. * @param s * @return */ public static String toCodeString(String s){ return "\"" + s.replace("\\", "\\\\") .replace("\"", "\\\"") .replace("\n", "\\n") .replace("\t", "\\t") + "\""; } /** * Takes a byte array, and returns a string hex representation. * @param bytes * @return */ public static String toHex(byte[] bytes) { BigInteger bi = new BigInteger(1, bytes); return String.format("%0" + (bytes.length << 1) + "X", bi); } }
false
true
public static List<String> ArgParser(String args) { //First, we have to tokenize the strings. Since we can have quoted arguments, we can't simply split on spaces. List<String> arguments = new ArrayList<String>(); StringBuilder buf = new StringBuilder(); boolean state_in_single_quote = false; boolean state_in_double_quote = false; for (int i = 0; i < args.length(); i++) { Character c0 = args.charAt(i); Character c1 = i + 1 < args.length() ? args.charAt(i + 1) : null; if (c0 == '\\') { if (c1 == '\'' && state_in_single_quote || c1 == '"' && state_in_double_quote || c1 == ' ' && !state_in_double_quote && !state_in_single_quote || c1 == '\\' && (state_in_double_quote || state_in_single_quote)) { //We are escaping the next character. Add it to the buffer instead, and //skip ahead two buf.append(c1); i++; continue; } } if (c0 == ' ') { if (!state_in_double_quote && !state_in_single_quote) { //argument split if (buf.length() != 0) { arguments.add(buf.toString()); buf = new StringBuilder(); } continue; } } if (c0 == '\'' && !state_in_double_quote) { if (state_in_single_quote) { state_in_single_quote = false; arguments.add(buf.toString()); buf = new StringBuilder(); } else { if (buf.length() != 0) { arguments.add(buf.toString()); buf = new StringBuilder(); } state_in_single_quote = true; } continue; } if (c0 == '"' && !state_in_single_quote) { if (state_in_double_quote) { state_in_double_quote = false; arguments.add(buf.toString()); buf = new StringBuilder(); } else { if (buf.length() != 0) { arguments.add(buf.toString()); buf = new StringBuilder(); } state_in_double_quote = true; } continue; } buf.append(c0); } if (buf.length() != 0) { arguments.add(buf.toString()); } return arguments; }
public static List<String> ArgParser(String args) { //First, we have to tokenize the strings. Since we can have quoted arguments, we can't simply split on spaces. List<String> arguments = new ArrayList<String>(); StringBuilder buf = new StringBuilder(); boolean state_in_single_quote = false; boolean state_in_double_quote = false; for (int i = 0; i < args.length(); i++) { Character c0 = args.charAt(i); Character c1 = i + 1 < args.length() ? args.charAt(i + 1) : null; if (c0 == '\\') { if (c1 != null && (c1 == '\'' && state_in_single_quote || c1 == '"' && state_in_double_quote || c1 == ' ' && !state_in_double_quote && !state_in_single_quote || c1 == '\\' && (state_in_double_quote || state_in_single_quote))) { //We are escaping the next character. Add it to the buffer instead, and //skip ahead two buf.append(c1); i++; continue; } } if (c0 == ' ') { if (!state_in_double_quote && !state_in_single_quote) { //argument split if (buf.length() != 0) { arguments.add(buf.toString()); buf = new StringBuilder(); } continue; } } if (c0 == '\'' && !state_in_double_quote) { if (state_in_single_quote) { state_in_single_quote = false; arguments.add(buf.toString()); buf = new StringBuilder(); } else { if (buf.length() != 0) { arguments.add(buf.toString()); buf = new StringBuilder(); } state_in_single_quote = true; } continue; } if (c0 == '"' && !state_in_single_quote) { if (state_in_double_quote) { state_in_double_quote = false; arguments.add(buf.toString()); buf = new StringBuilder(); } else { if (buf.length() != 0) { arguments.add(buf.toString()); buf = new StringBuilder(); } state_in_double_quote = true; } continue; } buf.append(c0); } if (buf.length() != 0) { arguments.add(buf.toString()); } return arguments; }