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/test/system/java/org/apache/hadoop/mapred/TestDistributedCacheModifiedFile.java b/src/test/system/java/org/apache/hadoop/mapred/TestDistributedCacheModifiedFile.java index b02143202..626d5fdd1 100644 --- a/src/test/system/java/org/apache/hadoop/mapred/TestDistributedCacheModifiedFile.java +++ b/src/test/system/java/org/apache/hadoop/mapred/TestDistributedCacheModifiedFile.java @@ -1,340 +1,337 @@ /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.mapred; import java.io.DataOutputStream; import java.net.URI; import java.util.Collection; import java.util.ArrayList; import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.Log; import org.apache.hadoop.mapreduce.test.system.JTProtocol; import org.apache.hadoop.mapreduce.test.system.TTClient; import org.apache.hadoop.mapreduce.test.system.JobInfo; import org.apache.hadoop.mapreduce.test.system.TaskInfo; import org.apache.hadoop.mapreduce.test.system.MRCluster; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.mapred.UtilsForTests; import org.apache.hadoop.mapreduce.test.system.FinishTaskControlAction; import org.apache.hadoop.filecache.DistributedCache; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.permission.FsPermission; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.examples.SleepJob; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.AfterClass; import org.junit.Test; /** * Verify the Distributed Cache functionality. * This test scenario is for a distributed cache file behaviour * when it is modified before and after being * accessed by maximum two jobs. Once a job uses a distributed cache file * that file is stored in the mapred.local.dir. If the next job * uses the same file, but with differnt timestamp, then that * file is stored again. So, if two jobs choose * the same tasktracker for their job execution * then, the distributed cache file should be found twice. * * This testcase runs a job with a distributed cache file. All the * tasks' corresponding tasktracker's handle is got and checked for * the presence of distributed cache with proper permissions in the * proper directory. Next when job * runs again and if any of its tasks hits the same tasktracker, which * ran one of the task of the previous job, then that * file should be uploaded again and task should not use the old file. * This is verified. */ public class TestDistributedCacheModifiedFile { private static MRCluster cluster = null; private static FileSystem dfs = null; private static FileSystem ttFs = null; private static JobClient client = null; private static FsPermission permission = new FsPermission((short)00777); private static String uriPath = "hdfs:///tmp/test.txt"; private static final Path URIPATH = new Path(uriPath); private String distributedFileName = "test.txt"; static final Log LOG = LogFactory. getLog(TestDistributedCacheModifiedFile.class); public TestDistributedCacheModifiedFile() throws Exception { } @BeforeClass public static void setUp() throws Exception { cluster = MRCluster.createCluster(new Configuration()); cluster.setUp(); client = cluster.getJTClient().getClient(); dfs = client.getFs(); //Deleting the file if it already exists dfs.delete(URIPATH, true); Collection<TTClient> tts = cluster.getTTClients(); //Stopping all TTs for (TTClient tt : tts) { tt.kill(); tt.waitForTTStop(); } //Starting all TTs for (TTClient tt : tts) { tt.start(); tt.waitForTTStart(); } //Waiting for 5 seconds to make sure tasktrackers are ready Thread.sleep(5000); } @AfterClass public static void tearDown() throws Exception { cluster.tearDown(); dfs.delete(URIPATH, true); Collection<TTClient> tts = cluster.getTTClients(); //Stopping all TTs for (TTClient tt : tts) { tt.kill(); tt.waitForTTStop(); } //Starting all TTs for (TTClient tt : tts) { tt.start(); tt.waitForTTStart(); } } @Test /** * This tests Distributed Cache for modified file * @param none * @return void */ public void testDistributedCache() throws Exception { Configuration conf = new Configuration(cluster.getConf()); JTProtocol wovenClient = cluster.getJTClient().getProxy(); //This counter will check for count of a loop, //which might become infinite. int count = 0; //This boolean will decide whether to run job again boolean continueLoop = true; //counter for job Loop int countLoop = 0; //This counter increases with all the tasktrackers in which tasks ran int taskTrackerCounter = 0; //This will store all the tasktrackers in which tasks ran ArrayList<String> taskTrackerCollection = new ArrayList<String>(); //This boolean tells if two tasks ran onteh same tasktracker or not boolean taskTrackerFound = false; do { SleepJob job = new SleepJob(); job.setConf(conf); conf = job.setupJobConf(5, 1, 1000, 1000, 100, 100); conf.setBoolean("mapreduce.job.complete.cancel.delegation.tokens", false); //Before starting, Modify the file String input = "This will be the content of\n" + "distributed cache\n"; //Creating the path with the file DataOutputStream file = UtilsForTests.createTmpFileDFS(dfs, URIPATH, permission, input); DistributedCache.createSymlink(conf); URI uri = URI.create(uriPath); DistributedCache.addCacheFile(uri, conf); JobConf jconf = new JobConf(conf); //Controls the job till all verification is done FinishTaskControlAction.configureControlActionForJob(conf); //Submitting the job RunningJob rJob = cluster.getJTClient().getClient().submitJob(jconf); //counter for job Loop countLoop++; TTClient tClient = null; JobInfo jInfo = wovenClient.getJobInfo(rJob.getID()); LOG.info("jInfo is :" + jInfo); //Assert if jobInfo is null Assert.assertNotNull("jobInfo is null", jInfo); //Wait for the job to start running. count = 0; while (jInfo.getStatus().getRunState() != JobStatus.RUNNING) { UtilsForTests.waitFor(10000); count++; jInfo = wovenClient.getJobInfo(rJob.getID()); //If the count goes beyond a point, then break; This is to avoid //infinite loop under unforeseen circumstances. Testcase will anyway //fail later. if (count > 10) { Assert.fail("job has not reached running state for more than" + "100 seconds. Failing at this point"); } } LOG.info("job id is :" + rJob.getID().toString()); TaskInfo[] taskInfos = cluster.getJTClient().getProxy() .getTaskInfo(rJob.getID()); boolean distCacheFileIsFound; for (TaskInfo taskInfo : taskInfos) { distCacheFileIsFound = false; String[] taskTrackers = taskInfo.getTaskTrackers(); for (String taskTracker : taskTrackers) { //Formatting tasktracker to get just its FQDN taskTracker = UtilsForTests.getFQDNofTT(taskTracker); LOG.info("taskTracker is :" + taskTracker); //The tasktrackerFound variable is initialized taskTrackerFound = false; //This will be entered from the second job onwards if (countLoop > 1) { if (taskTracker != null) { continueLoop = taskTrackerCollection.contains(taskTracker); } if (continueLoop) { taskTrackerFound = true; } } //Collecting the tasktrackers if (taskTracker != null) taskTrackerCollection.add(taskTracker); //we have loopped through two times to look for task //getting submitted on same tasktrackers.The same tasktracker //for subsequent jobs was not hit maybe because of many number //of tasktrackers. So, testcase has to stop here. if (countLoop > 1) { continueLoop = false; } tClient = cluster.getTTClient(taskTracker); //tClient maybe null because the task is already dead. Ex: setup if (tClient == null) { continue; } String[] localDirs = tClient.getMapredLocalDirs(); int distributedFileCount = 0; //Go to every single path for (String localDir : localDirs) { //Public Distributed cache will always be stored under //mapre.local.dir/tasktracker/archive localDir = localDir + Path.SEPARATOR + TaskTracker.getPublicDistributedCacheDir(); LOG.info("localDir is : " + localDir); //Get file status of all the directories //and files under that path. FileStatus[] fileStatuses = tClient.listStatus(localDir, true, true); for (FileStatus fileStatus : fileStatuses) { Path path = fileStatus.getPath(); LOG.info("path is :" + path.toString()); //Checking if the received path ends with //the distributed filename distCacheFileIsFound = (path.toString()). endsWith(distributedFileName); //If file is found, check for its permission. //Since the file is found break out of loop if (distCacheFileIsFound){ LOG.info("PATH found is :" + path.toString()); distributedFileCount++; String filename = path.getName(); FsPermission fsPerm = fileStatus.getPermission(); Assert.assertTrue("File Permission is not 777", fsPerm.equals(new FsPermission("777"))); } } } LOG.debug("The distributed FileCount is :" + distributedFileCount); LOG.debug("The taskTrackerFound is :" + taskTrackerFound); // If distributed cache is modified in dfs // between two job runs, it can be present more than once // in any of the task tracker, in which job ran. if (distributedFileCount != 2 && taskTrackerFound) { Assert.fail("The distributed cache file has to be two. " + "But found was " + distributedFileCount); - } else if (distributedFileCount > 1 && !taskTrackerFound) { - Assert.fail("The distributed cache file cannot more than one." + - " But found was " + distributedFileCount); } else if (distributedFileCount < 1) Assert.fail("The distributed cache file is less than one. " + "But found was " + distributedFileCount); if (!distCacheFileIsFound) { Assert.assertEquals("The distributed cache file does not exist", distCacheFileIsFound, false); } } } //Allow the job to continue through MR control job. cluster.signalAllTasks(rJob.getID()); //Killing the job because all the verification needed //for this testcase is completed. rJob.killJob(); //Waiting for 3 seconds for cleanup to start Thread.sleep(3000); //Getting the last cleanup task's tasktracker also, as //distributed cache gets uploaded even during cleanup. TaskInfo[] myTaskInfos = wovenClient.getTaskInfo(rJob.getID()); if (myTaskInfos != null) { for(TaskInfo info : myTaskInfos) { if(info.isSetupOrCleanup()) { String[] taskTrackers = info.getTaskTrackers(); for(String taskTracker : taskTrackers) { //Formatting tasktracker to get just its FQDN taskTracker = UtilsForTests.getFQDNofTT(taskTracker); LOG.info("taskTracker is :" + taskTracker); //Collecting the tasktrackers if (taskTracker != null) taskTrackerCollection.add(taskTracker); } } } } //Making sure that the job is complete. while (jInfo != null && !jInfo.getStatus().isJobComplete()) { Thread.sleep(10000); jInfo = wovenClient.getJobInfo(rJob.getID()); } } while (continueLoop); } }
true
true
public void testDistributedCache() throws Exception { Configuration conf = new Configuration(cluster.getConf()); JTProtocol wovenClient = cluster.getJTClient().getProxy(); //This counter will check for count of a loop, //which might become infinite. int count = 0; //This boolean will decide whether to run job again boolean continueLoop = true; //counter for job Loop int countLoop = 0; //This counter increases with all the tasktrackers in which tasks ran int taskTrackerCounter = 0; //This will store all the tasktrackers in which tasks ran ArrayList<String> taskTrackerCollection = new ArrayList<String>(); //This boolean tells if two tasks ran onteh same tasktracker or not boolean taskTrackerFound = false; do { SleepJob job = new SleepJob(); job.setConf(conf); conf = job.setupJobConf(5, 1, 1000, 1000, 100, 100); conf.setBoolean("mapreduce.job.complete.cancel.delegation.tokens", false); //Before starting, Modify the file String input = "This will be the content of\n" + "distributed cache\n"; //Creating the path with the file DataOutputStream file = UtilsForTests.createTmpFileDFS(dfs, URIPATH, permission, input); DistributedCache.createSymlink(conf); URI uri = URI.create(uriPath); DistributedCache.addCacheFile(uri, conf); JobConf jconf = new JobConf(conf); //Controls the job till all verification is done FinishTaskControlAction.configureControlActionForJob(conf); //Submitting the job RunningJob rJob = cluster.getJTClient().getClient().submitJob(jconf); //counter for job Loop countLoop++; TTClient tClient = null; JobInfo jInfo = wovenClient.getJobInfo(rJob.getID()); LOG.info("jInfo is :" + jInfo); //Assert if jobInfo is null Assert.assertNotNull("jobInfo is null", jInfo); //Wait for the job to start running. count = 0; while (jInfo.getStatus().getRunState() != JobStatus.RUNNING) { UtilsForTests.waitFor(10000); count++; jInfo = wovenClient.getJobInfo(rJob.getID()); //If the count goes beyond a point, then break; This is to avoid //infinite loop under unforeseen circumstances. Testcase will anyway //fail later. if (count > 10) { Assert.fail("job has not reached running state for more than" + "100 seconds. Failing at this point"); } } LOG.info("job id is :" + rJob.getID().toString()); TaskInfo[] taskInfos = cluster.getJTClient().getProxy() .getTaskInfo(rJob.getID()); boolean distCacheFileIsFound; for (TaskInfo taskInfo : taskInfos) { distCacheFileIsFound = false; String[] taskTrackers = taskInfo.getTaskTrackers(); for (String taskTracker : taskTrackers) { //Formatting tasktracker to get just its FQDN taskTracker = UtilsForTests.getFQDNofTT(taskTracker); LOG.info("taskTracker is :" + taskTracker); //The tasktrackerFound variable is initialized taskTrackerFound = false; //This will be entered from the second job onwards if (countLoop > 1) { if (taskTracker != null) { continueLoop = taskTrackerCollection.contains(taskTracker); } if (continueLoop) { taskTrackerFound = true; } } //Collecting the tasktrackers if (taskTracker != null) taskTrackerCollection.add(taskTracker); //we have loopped through two times to look for task //getting submitted on same tasktrackers.The same tasktracker //for subsequent jobs was not hit maybe because of many number //of tasktrackers. So, testcase has to stop here. if (countLoop > 1) { continueLoop = false; } tClient = cluster.getTTClient(taskTracker); //tClient maybe null because the task is already dead. Ex: setup if (tClient == null) { continue; } String[] localDirs = tClient.getMapredLocalDirs(); int distributedFileCount = 0; //Go to every single path for (String localDir : localDirs) { //Public Distributed cache will always be stored under //mapre.local.dir/tasktracker/archive localDir = localDir + Path.SEPARATOR + TaskTracker.getPublicDistributedCacheDir(); LOG.info("localDir is : " + localDir); //Get file status of all the directories //and files under that path. FileStatus[] fileStatuses = tClient.listStatus(localDir, true, true); for (FileStatus fileStatus : fileStatuses) { Path path = fileStatus.getPath(); LOG.info("path is :" + path.toString()); //Checking if the received path ends with //the distributed filename distCacheFileIsFound = (path.toString()). endsWith(distributedFileName); //If file is found, check for its permission. //Since the file is found break out of loop if (distCacheFileIsFound){ LOG.info("PATH found is :" + path.toString()); distributedFileCount++; String filename = path.getName(); FsPermission fsPerm = fileStatus.getPermission(); Assert.assertTrue("File Permission is not 777", fsPerm.equals(new FsPermission("777"))); } } } LOG.debug("The distributed FileCount is :" + distributedFileCount); LOG.debug("The taskTrackerFound is :" + taskTrackerFound); // If distributed cache is modified in dfs // between two job runs, it can be present more than once // in any of the task tracker, in which job ran. if (distributedFileCount != 2 && taskTrackerFound) { Assert.fail("The distributed cache file has to be two. " + "But found was " + distributedFileCount); } else if (distributedFileCount > 1 && !taskTrackerFound) { Assert.fail("The distributed cache file cannot more than one." + " But found was " + distributedFileCount); } else if (distributedFileCount < 1) Assert.fail("The distributed cache file is less than one. " + "But found was " + distributedFileCount); if (!distCacheFileIsFound) { Assert.assertEquals("The distributed cache file does not exist", distCacheFileIsFound, false); } } } //Allow the job to continue through MR control job. cluster.signalAllTasks(rJob.getID()); //Killing the job because all the verification needed //for this testcase is completed. rJob.killJob(); //Waiting for 3 seconds for cleanup to start Thread.sleep(3000); //Getting the last cleanup task's tasktracker also, as //distributed cache gets uploaded even during cleanup. TaskInfo[] myTaskInfos = wovenClient.getTaskInfo(rJob.getID()); if (myTaskInfos != null) { for(TaskInfo info : myTaskInfos) { if(info.isSetupOrCleanup()) { String[] taskTrackers = info.getTaskTrackers(); for(String taskTracker : taskTrackers) { //Formatting tasktracker to get just its FQDN taskTracker = UtilsForTests.getFQDNofTT(taskTracker); LOG.info("taskTracker is :" + taskTracker); //Collecting the tasktrackers if (taskTracker != null) taskTrackerCollection.add(taskTracker); } } } } //Making sure that the job is complete. while (jInfo != null && !jInfo.getStatus().isJobComplete()) { Thread.sleep(10000); jInfo = wovenClient.getJobInfo(rJob.getID()); } } while (continueLoop); }
public void testDistributedCache() throws Exception { Configuration conf = new Configuration(cluster.getConf()); JTProtocol wovenClient = cluster.getJTClient().getProxy(); //This counter will check for count of a loop, //which might become infinite. int count = 0; //This boolean will decide whether to run job again boolean continueLoop = true; //counter for job Loop int countLoop = 0; //This counter increases with all the tasktrackers in which tasks ran int taskTrackerCounter = 0; //This will store all the tasktrackers in which tasks ran ArrayList<String> taskTrackerCollection = new ArrayList<String>(); //This boolean tells if two tasks ran onteh same tasktracker or not boolean taskTrackerFound = false; do { SleepJob job = new SleepJob(); job.setConf(conf); conf = job.setupJobConf(5, 1, 1000, 1000, 100, 100); conf.setBoolean("mapreduce.job.complete.cancel.delegation.tokens", false); //Before starting, Modify the file String input = "This will be the content of\n" + "distributed cache\n"; //Creating the path with the file DataOutputStream file = UtilsForTests.createTmpFileDFS(dfs, URIPATH, permission, input); DistributedCache.createSymlink(conf); URI uri = URI.create(uriPath); DistributedCache.addCacheFile(uri, conf); JobConf jconf = new JobConf(conf); //Controls the job till all verification is done FinishTaskControlAction.configureControlActionForJob(conf); //Submitting the job RunningJob rJob = cluster.getJTClient().getClient().submitJob(jconf); //counter for job Loop countLoop++; TTClient tClient = null; JobInfo jInfo = wovenClient.getJobInfo(rJob.getID()); LOG.info("jInfo is :" + jInfo); //Assert if jobInfo is null Assert.assertNotNull("jobInfo is null", jInfo); //Wait for the job to start running. count = 0; while (jInfo.getStatus().getRunState() != JobStatus.RUNNING) { UtilsForTests.waitFor(10000); count++; jInfo = wovenClient.getJobInfo(rJob.getID()); //If the count goes beyond a point, then break; This is to avoid //infinite loop under unforeseen circumstances. Testcase will anyway //fail later. if (count > 10) { Assert.fail("job has not reached running state for more than" + "100 seconds. Failing at this point"); } } LOG.info("job id is :" + rJob.getID().toString()); TaskInfo[] taskInfos = cluster.getJTClient().getProxy() .getTaskInfo(rJob.getID()); boolean distCacheFileIsFound; for (TaskInfo taskInfo : taskInfos) { distCacheFileIsFound = false; String[] taskTrackers = taskInfo.getTaskTrackers(); for (String taskTracker : taskTrackers) { //Formatting tasktracker to get just its FQDN taskTracker = UtilsForTests.getFQDNofTT(taskTracker); LOG.info("taskTracker is :" + taskTracker); //The tasktrackerFound variable is initialized taskTrackerFound = false; //This will be entered from the second job onwards if (countLoop > 1) { if (taskTracker != null) { continueLoop = taskTrackerCollection.contains(taskTracker); } if (continueLoop) { taskTrackerFound = true; } } //Collecting the tasktrackers if (taskTracker != null) taskTrackerCollection.add(taskTracker); //we have loopped through two times to look for task //getting submitted on same tasktrackers.The same tasktracker //for subsequent jobs was not hit maybe because of many number //of tasktrackers. So, testcase has to stop here. if (countLoop > 1) { continueLoop = false; } tClient = cluster.getTTClient(taskTracker); //tClient maybe null because the task is already dead. Ex: setup if (tClient == null) { continue; } String[] localDirs = tClient.getMapredLocalDirs(); int distributedFileCount = 0; //Go to every single path for (String localDir : localDirs) { //Public Distributed cache will always be stored under //mapre.local.dir/tasktracker/archive localDir = localDir + Path.SEPARATOR + TaskTracker.getPublicDistributedCacheDir(); LOG.info("localDir is : " + localDir); //Get file status of all the directories //and files under that path. FileStatus[] fileStatuses = tClient.listStatus(localDir, true, true); for (FileStatus fileStatus : fileStatuses) { Path path = fileStatus.getPath(); LOG.info("path is :" + path.toString()); //Checking if the received path ends with //the distributed filename distCacheFileIsFound = (path.toString()). endsWith(distributedFileName); //If file is found, check for its permission. //Since the file is found break out of loop if (distCacheFileIsFound){ LOG.info("PATH found is :" + path.toString()); distributedFileCount++; String filename = path.getName(); FsPermission fsPerm = fileStatus.getPermission(); Assert.assertTrue("File Permission is not 777", fsPerm.equals(new FsPermission("777"))); } } } LOG.debug("The distributed FileCount is :" + distributedFileCount); LOG.debug("The taskTrackerFound is :" + taskTrackerFound); // If distributed cache is modified in dfs // between two job runs, it can be present more than once // in any of the task tracker, in which job ran. if (distributedFileCount != 2 && taskTrackerFound) { Assert.fail("The distributed cache file has to be two. " + "But found was " + distributedFileCount); } else if (distributedFileCount < 1) Assert.fail("The distributed cache file is less than one. " + "But found was " + distributedFileCount); if (!distCacheFileIsFound) { Assert.assertEquals("The distributed cache file does not exist", distCacheFileIsFound, false); } } } //Allow the job to continue through MR control job. cluster.signalAllTasks(rJob.getID()); //Killing the job because all the verification needed //for this testcase is completed. rJob.killJob(); //Waiting for 3 seconds for cleanup to start Thread.sleep(3000); //Getting the last cleanup task's tasktracker also, as //distributed cache gets uploaded even during cleanup. TaskInfo[] myTaskInfos = wovenClient.getTaskInfo(rJob.getID()); if (myTaskInfos != null) { for(TaskInfo info : myTaskInfos) { if(info.isSetupOrCleanup()) { String[] taskTrackers = info.getTaskTrackers(); for(String taskTracker : taskTrackers) { //Formatting tasktracker to get just its FQDN taskTracker = UtilsForTests.getFQDNofTT(taskTracker); LOG.info("taskTracker is :" + taskTracker); //Collecting the tasktrackers if (taskTracker != null) taskTrackerCollection.add(taskTracker); } } } } //Making sure that the job is complete. while (jInfo != null && !jInfo.getStatus().isJobComplete()) { Thread.sleep(10000); jInfo = wovenClient.getJobInfo(rJob.getID()); } } while (continueLoop); }
diff --git a/SoundStream/src/com/lastcrusade/soundstream/service/PlaylistService.java b/SoundStream/src/com/lastcrusade/soundstream/service/PlaylistService.java index 81ca6fe..8f6d882 100644 --- a/SoundStream/src/com/lastcrusade/soundstream/service/PlaylistService.java +++ b/SoundStream/src/com/lastcrusade/soundstream/service/PlaylistService.java @@ -1,604 +1,604 @@ /* * Copyright 2013 The Last Crusade [email protected] * * This file is part of SoundStream. * * SoundStream 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. * * SoundStream 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 SoundStream. If not, see <http://www.gnu.org/licenses/>. */ package com.lastcrusade.soundstream.service; import java.util.ArrayList; import java.util.Collections; import java.util.List; import android.app.Service; import android.content.Context; import android.content.Intent; import android.media.AudioManager; import android.os.Binder; import android.os.IBinder; import android.util.Log; import com.lastcrusade.soundstream.R; import com.lastcrusade.soundstream.audio.AudioPlayerWithEvents; import com.lastcrusade.soundstream.audio.IPlayer; import com.lastcrusade.soundstream.audio.RemoteAudioPlayer; import com.lastcrusade.soundstream.audio.SingleFileAudioPlayer; import com.lastcrusade.soundstream.manager.PlaylistDataManager; import com.lastcrusade.soundstream.model.Playlist; import com.lastcrusade.soundstream.model.PlaylistEntry; import com.lastcrusade.soundstream.model.SongMetadata; import com.lastcrusade.soundstream.service.MessagingService.MessagingServiceBinder; import com.lastcrusade.soundstream.service.MusicLibraryService.MusicLibraryServiceBinder; import com.lastcrusade.soundstream.util.BroadcastIntent; import com.lastcrusade.soundstream.util.BroadcastRegistrar; import com.lastcrusade.soundstream.util.IBroadcastActionHandler; import com.lastcrusade.soundstream.util.SongMetadataUtils; import com.lastcrusade.soundstream.util.Toaster; /** * This service is responsible for holding the play queue and sending songs to * the SingleFileAudioPlayer */ public class PlaylistService extends Service { /** * Broadcast action used to toggle playing and pausing the current song. * * This will control the playlist service and music control. * */ public static final String ACTION_PLAY_PAUSE = PlaylistService.class .getName() + ".action.PlayPause"; /** * Broadcast action used to pause the current song. * * This will control the playlist service and music control. * */ public static final String ACTION_PAUSE = PlaylistService.class .getName() + ".action.Pause"; /** * Broadcast action used to skip the current song. * * This will control the playlist service and music control. * */ public static final String ACTION_SKIP = PlaylistService.class .getName() + ".action.Skip"; /** * Broadcast action sent when the Audio Player service is paused. */ public static final String ACTION_PAUSED_AUDIO = PlaylistService.class .getName() + ".action.PausedAudio"; /** * Broadcast action sent when the Audio Player service starts playing. */ public static final String ACTION_PLAYING_AUDIO = PlaylistService.class .getName() + ".action.PlayingAudio"; /** * Broadcast action sent when the Audio Player service is asked to skip a * song. */ public static final String ACTION_SKIPPING_AUDIO = PlaylistService.class .getName() + ".action.SkippingAudio"; /** * Broadcast action sent when the playlist gets updated */ public static final String ACTION_PLAYLIST_UPDATED = PlaylistService.class + ".action.PlaylistUpdated"; public static final String ACTION_SONG_REMOVED = PlaylistService.class + ".action.SongRemoved"; public static final String ACTION_SONG_ADDED = PlaylistService.class + ".action.SongAdded"; public static final String ACTION_SONG_PLAYING = PlaylistService.class + ".action.SongPlaying"; public static final String EXTRA_SONG = PlaylistService.class + ".extra.Song"; private static final String TAG = PlaylistService.class.getName(); /** * Class for clients to access. Because we know this service always runs in * the same process as its clients, we don't need to deal with IPC. */ public class PlaylistServiceBinder extends Binder implements ILocalBinder<PlaylistService> { public PlaylistService getService() { return PlaylistService.this; } } private BroadcastRegistrar registrar; private IPlayer mThePlayer; private SingleFileAudioPlayer mAudioPlayer; //TODO remove this when we add stop to IPlayer private Playlist mPlaylist; private Thread mDataManagerThread; private PlaylistDataManager mDataManager; private PlaylistEntry currentEntry; private boolean isLocalPlayer; private ServiceLocator<MusicLibraryService> musicLibraryLocator; private ServiceLocator<MessagingService> messagingServiceLocator; @Override public IBinder onBind(Intent intent) { messagingServiceLocator = new ServiceLocator<MessagingService>( this, MessagingService.class, MessagingServiceBinder.class); //create the local player in a separate variable, and use that // as the player until we see a host connected this.mAudioPlayer = new SingleFileAudioPlayer(this, messagingServiceLocator); //Assume we are local until we connect to a host isLocalPlayer = true; this.mThePlayer = new AudioPlayerWithEvents(this.mAudioPlayer, this); this.mPlaylist = new Playlist(); musicLibraryLocator = new ServiceLocator<MusicLibraryService>( this, MusicLibraryService.class, MusicLibraryServiceBinder.class); registerReceivers(); //start the data manager by default...it is disabled when // a host is connected startDataManager(); return new PlaylistServiceBinder(); } @Override public boolean onUnbind(Intent intent) { unregisterReceivers(); messagingServiceLocator.unbind(); return super.onUnbind(intent); } /** * Register intent receivers to control this service * */ private void registerReceivers() { this.registrar = new BroadcastRegistrar(); this.registrar .addAction(SingleFileAudioPlayer.ACTION_SONG_FINISHED, new IBroadcastActionHandler() { @Override public void onReceiveAction(Context context, Intent intent) { //NOTE: this is an indicator that the song data can be deleted...therefore, we don't //want to set the flag until after the song has been played if (currentEntry != null) { currentEntry.setPlayed(true); getMessagingService() .sendSongStatusMessage(currentEntry); currentEntry = null; } // automatically play the next song, but only if we're not paused if (!mThePlayer.isPaused()) { play(); } new BroadcastIntent(ACTION_PLAYLIST_UPDATED).send(PlaylistService.this); } }) .addAction(ConnectionService.ACTION_HOST_CONNECTED, new IBroadcastActionHandler() { @Override public void onReceiveAction(Context context, Intent intent) { mThePlayer = new AudioPlayerWithEvents( new RemoteAudioPlayer( PlaylistService.this, messagingServiceLocator), context ); isLocalPlayer = false; stopDataManager(); } }) .addAction(ConnectionService.ACTION_HOST_DISCONNECTED, new IBroadcastActionHandler() { @Override public void onReceiveAction(Context context, Intent intent) { mThePlayer = new AudioPlayerWithEvents(mAudioPlayer, PlaylistService.this); isLocalPlayer = true; currentEntry = null; startDataManager(); } }) .addAction(ConnectionService.ACTION_GUEST_CONNECTED, new IBroadcastActionHandler() { @Override public void onReceiveAction(Context context, Intent intent) { getMessagingService().sendPlaylistMessage(mPlaylist.getSongsToPlay()); } }) .addAction(MessagingService.ACTION_PAUSE_MESSAGE, new IBroadcastActionHandler() { @Override public void onReceiveAction(Context context, Intent intent) { pause(); } }) .addAction(MessagingService.ACTION_PLAY_MESSAGE, new IBroadcastActionHandler() { @Override public void onReceiveAction(Context context, Intent intent) { play(); } }) .addAction(MessagingService.ACTION_SKIP_MESSAGE, new IBroadcastActionHandler() { @Override public void onReceiveAction(Context context, Intent intent) { skip(); } }) .addAction(MessagingService.ACTION_ADD_TO_PLAYLIST_MESSAGE, new IBroadcastActionHandler() { @Override public void onReceiveAction(Context context, Intent intent) { if (!isLocalPlayer) { Log.wtf(TAG, "Received AddToPlaylistMessage on guest...these messages are only for hosts"); } String macAddress = intent.getStringExtra(MessagingService.EXTRA_ADDRESS); long songId = intent.getLongExtra( MessagingService.EXTRA_SONG_ID, SongMetadata.UNKNOWN_SONG); SongMetadata song = getMusicLibraryService().lookupSongByAddressAndId(macAddress, songId); if (song != null) { addSong(song); } else { Log.wtf(TAG, "Song with mac address " + macAddress + " and id " + songId + " not found."); } } }) .addAction(MessagingService.ACTION_BUMP_SONG_ON_PLAYLIST_MESSAGE, new IBroadcastActionHandler() { @Override public void onReceiveAction(Context context, Intent intent) { if (!isLocalPlayer) { Log.wtf(TAG, "Received BumpSongOnPlaylist on guest...these messages are only for hosts"); } String macAddress = intent.getStringExtra(MessagingService.EXTRA_ADDRESS); long songId = intent.getLongExtra( MessagingService.EXTRA_SONG_ID, SongMetadata.UNKNOWN_SONG); int entryId = intent.getIntExtra( MessagingService.EXTRA_ENTRY_ID, 0); SongMetadata song = getMusicLibraryService().lookupSongByAddressAndId(macAddress, songId); PlaylistEntry entry = mPlaylist.findEntryBySongAndId(song, entryId); if (entry != null) { bumpSong(entry); } else { Log.e(TAG, "Attempting to bump a song that is not in our playlist: " + song); } } }) .addAction(MessagingService.ACTION_REMOVE_FROM_PLAYLIST_MESSAGE, new IBroadcastActionHandler() { @Override public void onReceiveAction(Context context, Intent intent) { if (!isLocalPlayer) { Log.wtf(TAG, "Received AddToPlaylistMessage on guest...these messages are only for hosts"); } String macAddress = intent.getStringExtra(MessagingService.EXTRA_ADDRESS); long songId = intent.getLongExtra( MessagingService.EXTRA_SONG_ID, SongMetadata.UNKNOWN_SONG); int entryId = intent.getIntExtra( MessagingService.EXTRA_ENTRY_ID, 0); //NOTE: only remove if its not the currently playing song. //TODO: may need a better message back to the remote fan SongMetadata song = getMusicLibraryService().lookupSongByAddressAndId(macAddress, songId); PlaylistEntry entry = mPlaylist.findEntryBySongAndId(song, entryId); if (!isCurrentEntry(entry)) { removeSong(entry); } getMessagingService().sendPlaylistMessage(mPlaylist.getSongsToPlay()); } }) .addAction(MessagingService.ACTION_PLAYLIST_UPDATED_MESSAGE, new IBroadcastActionHandler() { @Override public void onReceiveAction(Context context, Intent intent) { if (isLocalPlayer) { Log.wtf(TAG, "Received PlaylistUpdateMessage as host...these messages are only for guests"); } List<PlaylistEntry> newList = intent.getParcelableArrayListExtra(MessagingService.EXTRA_PLAYLIST_ENTRY); mPlaylist.clear(); for (PlaylistEntry entry : newList) { mPlaylist.add(entry); } new BroadcastIntent(ACTION_PLAYLIST_UPDATED).send(PlaylistService.this); } }) .addAction(MessagingService.ACTION_SONG_STATUS_MESSAGE, new IBroadcastActionHandler() { @Override public void onReceiveAction(Context context, Intent intent) { if (isLocalPlayer) { Log.wtf(TAG, "Received SongStatusMessage as host...these messages are only for guests"); } String macAddress = intent.getStringExtra(MessagingService.EXTRA_ADDRESS); long songId = intent.getLongExtra( MessagingService.EXTRA_SONG_ID, SongMetadata.UNKNOWN_SONG); int entryId = intent.getIntExtra( MessagingService.EXTRA_ENTRY_ID, 0); boolean loaded = intent.getBooleanExtra(MessagingService.EXTRA_LOADED, false); boolean played = intent.getBooleanExtra(MessagingService.EXTRA_PLAYED, false); SongMetadata song = getMusicLibraryService().lookupSongByAddressAndId(macAddress, songId); - if (song == null) { + if (song != null) { PlaylistEntry entry = mPlaylist.findEntryBySongAndId(song, entryId); if (entry != null) { entry.setLoaded(loaded); entry.setPlayed(played); // send an intent to the fragments that the playlist is updated new BroadcastIntent(ACTION_PLAYLIST_UPDATED).send(PlaylistService.this); } else { Log.e(TAG, "Attempting to update information about a song that is not in our playlist: " + song); } } else { Log.e(TAG, "MusicLibraryService cannot find song"); } } }) .addAction(PlaylistService.ACTION_PAUSE, new IBroadcastActionHandler() { @Override public void onReceiveAction(Context context, Intent intent) { pause(); } }) .addAction(PlaylistService.ACTION_PLAY_PAUSE, new IBroadcastActionHandler() { @Override public void onReceiveAction(Context context, Intent intent) { if (mThePlayer.isPaused()) { play(); } else { pause(); } } }) .addAction(PlaylistService.ACTION_SKIP, new IBroadcastActionHandler() { @Override public void onReceiveAction(Context context, Intent intent) { skip(); } }) .addAction(AudioManager.ACTION_AUDIO_BECOMING_NOISY, new IBroadcastActionHandler() { @Override public void onReceiveAction(Context context, Intent intent) { pause(); } }) .register(this); } protected void startDataManager() { if (mDataManager == null) { mDataManager = new PlaylistDataManager(PlaylistService.this, messagingServiceLocator); mDataManagerThread = new Thread(mDataManager, PlaylistDataManager.class.getSimpleName() + " Thread"); mDataManagerThread.start(); } } protected void stopDataManager() { if (mDataManager != null) { mDataManager.stopLoading(); mDataManager = null; mDataManagerThread = null; } } private void unregisterReceivers() { this.registrar.unregister(); } private boolean isCurrentEntry(PlaylistEntry entry) { //currentSong == null before play is started, and for a brief moment between songs // (It's nulled out when the ACTION_SONG_FINISHED method is called, // and repopulated in setSong) return currentEntry != null && SongMetadataUtils.isTheSameEntry(entry, currentEntry); } public boolean isPlaying() { return this.mThePlayer.isPlaying(); } public void play() { if (this.mThePlayer.isPaused()) { this.mThePlayer.resume(); } else { boolean play = true; if(isLocalPlayer) { play = setNextSong(); } //we have stuff to play...play it and send a notification if (play) { this.mThePlayer.play(); } } } /** * Helper method to manage all of the things we need to do to set a song * to play locally (e.g. on the host). */ private boolean setNextSong() { if (!isLocalPlayer) { throw new IllegalStateException("Cannot call setSong when using a remote player"); } boolean songSet = false; //only if (mPlaylist.size() > 0) { PlaylistEntry song = mPlaylist.getNextAvailableSong(); //we've reached the end of the playlist...reset it to the beginning and try again if (song == null) { resetPlaylist(); song = mPlaylist.getNextAvailableSong(); Toaster.iToast(this, getString(R.string.playlist_finished)); } //still no available music..this means we're waiting for data to come in //...display a warning, but don't play. if (song == null) { //TODO: instead of this, we may want to repost a message to wait for the next song to be available //stop the player this.mAudioPlayer.stop(); //pop up the notice Toaster.iToast(this, getString(R.string.no_available_songs)); } else { //we have a song available to play...play it! this.currentEntry = song; this.mAudioPlayer.setSong(song); //the song has been set...indicate this in the return value songSet = true; } } else { Toaster.iToast(this, getString(R.string.playlist_empty)); } return songSet; } /** * */ private void resetPlaylist() { mPlaylist.reset(); if (isLocalPlayer) { //we may need to re-add entries to the data manager, for remote // loading for (PlaylistEntry entry : mPlaylist.getSongsToPlay()) { //add all of the entries to the load queue Log.i(TAG, entry + " is loaded? " + entry.isLoaded()); mDataManager.addToLoadQueue(entry); } } //send a message to the guests with the new playlist getMessagingService().sendPlaylistMessage(mPlaylist.getSongsToPlay()); } public void clearPlaylist() { mPlaylist.clear(); new BroadcastIntent(ACTION_PLAYLIST_UPDATED).send(this); } public void pause() { this.mThePlayer.pause(); } public void skip() { this.mThePlayer.skip(); } public void addSong(SongMetadata metadata) { addSong(new PlaylistEntry(metadata)); } public void addSong(PlaylistEntry entry) { //NOTE: the entries are shared between the playlist and the data loader...the loader // will load data into the same objects that are held in the playlist mPlaylist.add(entry); if (isLocalPlayer) { mDataManager.addToLoadQueue(entry); } new BroadcastIntent(ACTION_SONG_ADDED) .putExtra(EXTRA_SONG, entry) .send(this); // send an intent to the fragments that the playlist is updated new BroadcastIntent(ACTION_PLAYLIST_UPDATED).send(this); if (isLocalPlayer) { //send a message to the guests with the new playlist getMessagingService().sendPlaylistMessage(mPlaylist.getSongsToPlay()); } else { //send a message to the host to add this song getMessagingService().sendAddToPlaylistMessage(entry); } } public void removeSong(PlaylistEntry entry) { if (entry != null) { mPlaylist.remove(entry); //broadcast the fact that a song has been removed new BroadcastIntent(ACTION_SONG_REMOVED) .putExtra(EXTRA_SONG, entry) .send(this); //broadcast the fact that the playlist has been updated new BroadcastIntent(ACTION_PLAYLIST_UPDATED).send(this); if (isLocalPlayer) { //send a message to the guests with the new playlist getMessagingService().sendPlaylistMessage(mPlaylist.getSongsToPlay()); } else { //send a message to the host to remove this song getMessagingService().sendRemoveFromPlaylistMessage(entry); } } else { Log.e(TAG, "Attempting to remove a song that is not in our playlist: " + entry); } } public List<PlaylistEntry> getPlaylistEntries() { return Collections.unmodifiableList(new ArrayList<PlaylistEntry>(mPlaylist.getSongsToPlay())); } private IMessagingService getMessagingService() { MessagingService messagingService = null; try { messagingService = this.messagingServiceLocator.getService(); } catch (ServiceNotBoundException e) { Log.wtf(TAG, e); } return messagingService; } public void bumpSong(PlaylistEntry entry){ mPlaylist.bumpSong(entry); new BroadcastIntent(ACTION_PLAYLIST_UPDATED).send(this); if (isLocalPlayer) { //send a message to the guests with the new playlist getMessagingService().sendPlaylistMessage(mPlaylist.getSongsToPlay()); } else { //send a message to the host to remove this song getMessagingService().sendBumpSongOnPlaylistMessage(entry); } } public PlaylistEntry getCurrentEntry(){ return currentEntry; } public MusicLibraryService getMusicLibraryService() { MusicLibraryService musicLibraryService = null; try { musicLibraryService = this.musicLibraryLocator.getService(); } catch (ServiceNotBoundException e) { Log.wtf(TAG, e); } return musicLibraryService; } }
true
true
private void registerReceivers() { this.registrar = new BroadcastRegistrar(); this.registrar .addAction(SingleFileAudioPlayer.ACTION_SONG_FINISHED, new IBroadcastActionHandler() { @Override public void onReceiveAction(Context context, Intent intent) { //NOTE: this is an indicator that the song data can be deleted...therefore, we don't //want to set the flag until after the song has been played if (currentEntry != null) { currentEntry.setPlayed(true); getMessagingService() .sendSongStatusMessage(currentEntry); currentEntry = null; } // automatically play the next song, but only if we're not paused if (!mThePlayer.isPaused()) { play(); } new BroadcastIntent(ACTION_PLAYLIST_UPDATED).send(PlaylistService.this); } }) .addAction(ConnectionService.ACTION_HOST_CONNECTED, new IBroadcastActionHandler() { @Override public void onReceiveAction(Context context, Intent intent) { mThePlayer = new AudioPlayerWithEvents( new RemoteAudioPlayer( PlaylistService.this, messagingServiceLocator), context ); isLocalPlayer = false; stopDataManager(); } }) .addAction(ConnectionService.ACTION_HOST_DISCONNECTED, new IBroadcastActionHandler() { @Override public void onReceiveAction(Context context, Intent intent) { mThePlayer = new AudioPlayerWithEvents(mAudioPlayer, PlaylistService.this); isLocalPlayer = true; currentEntry = null; startDataManager(); } }) .addAction(ConnectionService.ACTION_GUEST_CONNECTED, new IBroadcastActionHandler() { @Override public void onReceiveAction(Context context, Intent intent) { getMessagingService().sendPlaylistMessage(mPlaylist.getSongsToPlay()); } }) .addAction(MessagingService.ACTION_PAUSE_MESSAGE, new IBroadcastActionHandler() { @Override public void onReceiveAction(Context context, Intent intent) { pause(); } }) .addAction(MessagingService.ACTION_PLAY_MESSAGE, new IBroadcastActionHandler() { @Override public void onReceiveAction(Context context, Intent intent) { play(); } }) .addAction(MessagingService.ACTION_SKIP_MESSAGE, new IBroadcastActionHandler() { @Override public void onReceiveAction(Context context, Intent intent) { skip(); } }) .addAction(MessagingService.ACTION_ADD_TO_PLAYLIST_MESSAGE, new IBroadcastActionHandler() { @Override public void onReceiveAction(Context context, Intent intent) { if (!isLocalPlayer) { Log.wtf(TAG, "Received AddToPlaylistMessage on guest...these messages are only for hosts"); } String macAddress = intent.getStringExtra(MessagingService.EXTRA_ADDRESS); long songId = intent.getLongExtra( MessagingService.EXTRA_SONG_ID, SongMetadata.UNKNOWN_SONG); SongMetadata song = getMusicLibraryService().lookupSongByAddressAndId(macAddress, songId); if (song != null) { addSong(song); } else { Log.wtf(TAG, "Song with mac address " + macAddress + " and id " + songId + " not found."); } } }) .addAction(MessagingService.ACTION_BUMP_SONG_ON_PLAYLIST_MESSAGE, new IBroadcastActionHandler() { @Override public void onReceiveAction(Context context, Intent intent) { if (!isLocalPlayer) { Log.wtf(TAG, "Received BumpSongOnPlaylist on guest...these messages are only for hosts"); } String macAddress = intent.getStringExtra(MessagingService.EXTRA_ADDRESS); long songId = intent.getLongExtra( MessagingService.EXTRA_SONG_ID, SongMetadata.UNKNOWN_SONG); int entryId = intent.getIntExtra( MessagingService.EXTRA_ENTRY_ID, 0); SongMetadata song = getMusicLibraryService().lookupSongByAddressAndId(macAddress, songId); PlaylistEntry entry = mPlaylist.findEntryBySongAndId(song, entryId); if (entry != null) { bumpSong(entry); } else { Log.e(TAG, "Attempting to bump a song that is not in our playlist: " + song); } } }) .addAction(MessagingService.ACTION_REMOVE_FROM_PLAYLIST_MESSAGE, new IBroadcastActionHandler() { @Override public void onReceiveAction(Context context, Intent intent) { if (!isLocalPlayer) { Log.wtf(TAG, "Received AddToPlaylistMessage on guest...these messages are only for hosts"); } String macAddress = intent.getStringExtra(MessagingService.EXTRA_ADDRESS); long songId = intent.getLongExtra( MessagingService.EXTRA_SONG_ID, SongMetadata.UNKNOWN_SONG); int entryId = intent.getIntExtra( MessagingService.EXTRA_ENTRY_ID, 0); //NOTE: only remove if its not the currently playing song. //TODO: may need a better message back to the remote fan SongMetadata song = getMusicLibraryService().lookupSongByAddressAndId(macAddress, songId); PlaylistEntry entry = mPlaylist.findEntryBySongAndId(song, entryId); if (!isCurrentEntry(entry)) { removeSong(entry); } getMessagingService().sendPlaylistMessage(mPlaylist.getSongsToPlay()); } }) .addAction(MessagingService.ACTION_PLAYLIST_UPDATED_MESSAGE, new IBroadcastActionHandler() { @Override public void onReceiveAction(Context context, Intent intent) { if (isLocalPlayer) { Log.wtf(TAG, "Received PlaylistUpdateMessage as host...these messages are only for guests"); } List<PlaylistEntry> newList = intent.getParcelableArrayListExtra(MessagingService.EXTRA_PLAYLIST_ENTRY); mPlaylist.clear(); for (PlaylistEntry entry : newList) { mPlaylist.add(entry); } new BroadcastIntent(ACTION_PLAYLIST_UPDATED).send(PlaylistService.this); } }) .addAction(MessagingService.ACTION_SONG_STATUS_MESSAGE, new IBroadcastActionHandler() { @Override public void onReceiveAction(Context context, Intent intent) { if (isLocalPlayer) { Log.wtf(TAG, "Received SongStatusMessage as host...these messages are only for guests"); } String macAddress = intent.getStringExtra(MessagingService.EXTRA_ADDRESS); long songId = intent.getLongExtra( MessagingService.EXTRA_SONG_ID, SongMetadata.UNKNOWN_SONG); int entryId = intent.getIntExtra( MessagingService.EXTRA_ENTRY_ID, 0); boolean loaded = intent.getBooleanExtra(MessagingService.EXTRA_LOADED, false); boolean played = intent.getBooleanExtra(MessagingService.EXTRA_PLAYED, false); SongMetadata song = getMusicLibraryService().lookupSongByAddressAndId(macAddress, songId); if (song == null) { PlaylistEntry entry = mPlaylist.findEntryBySongAndId(song, entryId); if (entry != null) { entry.setLoaded(loaded); entry.setPlayed(played); // send an intent to the fragments that the playlist is updated new BroadcastIntent(ACTION_PLAYLIST_UPDATED).send(PlaylistService.this); } else { Log.e(TAG, "Attempting to update information about a song that is not in our playlist: " + song); } } else { Log.e(TAG, "MusicLibraryService cannot find song"); } } }) .addAction(PlaylistService.ACTION_PAUSE, new IBroadcastActionHandler() { @Override public void onReceiveAction(Context context, Intent intent) { pause(); } }) .addAction(PlaylistService.ACTION_PLAY_PAUSE, new IBroadcastActionHandler() { @Override public void onReceiveAction(Context context, Intent intent) { if (mThePlayer.isPaused()) { play(); } else { pause(); } } }) .addAction(PlaylistService.ACTION_SKIP, new IBroadcastActionHandler() { @Override public void onReceiveAction(Context context, Intent intent) { skip(); } }) .addAction(AudioManager.ACTION_AUDIO_BECOMING_NOISY, new IBroadcastActionHandler() { @Override public void onReceiveAction(Context context, Intent intent) { pause(); } }) .register(this); }
private void registerReceivers() { this.registrar = new BroadcastRegistrar(); this.registrar .addAction(SingleFileAudioPlayer.ACTION_SONG_FINISHED, new IBroadcastActionHandler() { @Override public void onReceiveAction(Context context, Intent intent) { //NOTE: this is an indicator that the song data can be deleted...therefore, we don't //want to set the flag until after the song has been played if (currentEntry != null) { currentEntry.setPlayed(true); getMessagingService() .sendSongStatusMessage(currentEntry); currentEntry = null; } // automatically play the next song, but only if we're not paused if (!mThePlayer.isPaused()) { play(); } new BroadcastIntent(ACTION_PLAYLIST_UPDATED).send(PlaylistService.this); } }) .addAction(ConnectionService.ACTION_HOST_CONNECTED, new IBroadcastActionHandler() { @Override public void onReceiveAction(Context context, Intent intent) { mThePlayer = new AudioPlayerWithEvents( new RemoteAudioPlayer( PlaylistService.this, messagingServiceLocator), context ); isLocalPlayer = false; stopDataManager(); } }) .addAction(ConnectionService.ACTION_HOST_DISCONNECTED, new IBroadcastActionHandler() { @Override public void onReceiveAction(Context context, Intent intent) { mThePlayer = new AudioPlayerWithEvents(mAudioPlayer, PlaylistService.this); isLocalPlayer = true; currentEntry = null; startDataManager(); } }) .addAction(ConnectionService.ACTION_GUEST_CONNECTED, new IBroadcastActionHandler() { @Override public void onReceiveAction(Context context, Intent intent) { getMessagingService().sendPlaylistMessage(mPlaylist.getSongsToPlay()); } }) .addAction(MessagingService.ACTION_PAUSE_MESSAGE, new IBroadcastActionHandler() { @Override public void onReceiveAction(Context context, Intent intent) { pause(); } }) .addAction(MessagingService.ACTION_PLAY_MESSAGE, new IBroadcastActionHandler() { @Override public void onReceiveAction(Context context, Intent intent) { play(); } }) .addAction(MessagingService.ACTION_SKIP_MESSAGE, new IBroadcastActionHandler() { @Override public void onReceiveAction(Context context, Intent intent) { skip(); } }) .addAction(MessagingService.ACTION_ADD_TO_PLAYLIST_MESSAGE, new IBroadcastActionHandler() { @Override public void onReceiveAction(Context context, Intent intent) { if (!isLocalPlayer) { Log.wtf(TAG, "Received AddToPlaylistMessage on guest...these messages are only for hosts"); } String macAddress = intent.getStringExtra(MessagingService.EXTRA_ADDRESS); long songId = intent.getLongExtra( MessagingService.EXTRA_SONG_ID, SongMetadata.UNKNOWN_SONG); SongMetadata song = getMusicLibraryService().lookupSongByAddressAndId(macAddress, songId); if (song != null) { addSong(song); } else { Log.wtf(TAG, "Song with mac address " + macAddress + " and id " + songId + " not found."); } } }) .addAction(MessagingService.ACTION_BUMP_SONG_ON_PLAYLIST_MESSAGE, new IBroadcastActionHandler() { @Override public void onReceiveAction(Context context, Intent intent) { if (!isLocalPlayer) { Log.wtf(TAG, "Received BumpSongOnPlaylist on guest...these messages are only for hosts"); } String macAddress = intent.getStringExtra(MessagingService.EXTRA_ADDRESS); long songId = intent.getLongExtra( MessagingService.EXTRA_SONG_ID, SongMetadata.UNKNOWN_SONG); int entryId = intent.getIntExtra( MessagingService.EXTRA_ENTRY_ID, 0); SongMetadata song = getMusicLibraryService().lookupSongByAddressAndId(macAddress, songId); PlaylistEntry entry = mPlaylist.findEntryBySongAndId(song, entryId); if (entry != null) { bumpSong(entry); } else { Log.e(TAG, "Attempting to bump a song that is not in our playlist: " + song); } } }) .addAction(MessagingService.ACTION_REMOVE_FROM_PLAYLIST_MESSAGE, new IBroadcastActionHandler() { @Override public void onReceiveAction(Context context, Intent intent) { if (!isLocalPlayer) { Log.wtf(TAG, "Received AddToPlaylistMessage on guest...these messages are only for hosts"); } String macAddress = intent.getStringExtra(MessagingService.EXTRA_ADDRESS); long songId = intent.getLongExtra( MessagingService.EXTRA_SONG_ID, SongMetadata.UNKNOWN_SONG); int entryId = intent.getIntExtra( MessagingService.EXTRA_ENTRY_ID, 0); //NOTE: only remove if its not the currently playing song. //TODO: may need a better message back to the remote fan SongMetadata song = getMusicLibraryService().lookupSongByAddressAndId(macAddress, songId); PlaylistEntry entry = mPlaylist.findEntryBySongAndId(song, entryId); if (!isCurrentEntry(entry)) { removeSong(entry); } getMessagingService().sendPlaylistMessage(mPlaylist.getSongsToPlay()); } }) .addAction(MessagingService.ACTION_PLAYLIST_UPDATED_MESSAGE, new IBroadcastActionHandler() { @Override public void onReceiveAction(Context context, Intent intent) { if (isLocalPlayer) { Log.wtf(TAG, "Received PlaylistUpdateMessage as host...these messages are only for guests"); } List<PlaylistEntry> newList = intent.getParcelableArrayListExtra(MessagingService.EXTRA_PLAYLIST_ENTRY); mPlaylist.clear(); for (PlaylistEntry entry : newList) { mPlaylist.add(entry); } new BroadcastIntent(ACTION_PLAYLIST_UPDATED).send(PlaylistService.this); } }) .addAction(MessagingService.ACTION_SONG_STATUS_MESSAGE, new IBroadcastActionHandler() { @Override public void onReceiveAction(Context context, Intent intent) { if (isLocalPlayer) { Log.wtf(TAG, "Received SongStatusMessage as host...these messages are only for guests"); } String macAddress = intent.getStringExtra(MessagingService.EXTRA_ADDRESS); long songId = intent.getLongExtra( MessagingService.EXTRA_SONG_ID, SongMetadata.UNKNOWN_SONG); int entryId = intent.getIntExtra( MessagingService.EXTRA_ENTRY_ID, 0); boolean loaded = intent.getBooleanExtra(MessagingService.EXTRA_LOADED, false); boolean played = intent.getBooleanExtra(MessagingService.EXTRA_PLAYED, false); SongMetadata song = getMusicLibraryService().lookupSongByAddressAndId(macAddress, songId); if (song != null) { PlaylistEntry entry = mPlaylist.findEntryBySongAndId(song, entryId); if (entry != null) { entry.setLoaded(loaded); entry.setPlayed(played); // send an intent to the fragments that the playlist is updated new BroadcastIntent(ACTION_PLAYLIST_UPDATED).send(PlaylistService.this); } else { Log.e(TAG, "Attempting to update information about a song that is not in our playlist: " + song); } } else { Log.e(TAG, "MusicLibraryService cannot find song"); } } }) .addAction(PlaylistService.ACTION_PAUSE, new IBroadcastActionHandler() { @Override public void onReceiveAction(Context context, Intent intent) { pause(); } }) .addAction(PlaylistService.ACTION_PLAY_PAUSE, new IBroadcastActionHandler() { @Override public void onReceiveAction(Context context, Intent intent) { if (mThePlayer.isPaused()) { play(); } else { pause(); } } }) .addAction(PlaylistService.ACTION_SKIP, new IBroadcastActionHandler() { @Override public void onReceiveAction(Context context, Intent intent) { skip(); } }) .addAction(AudioManager.ACTION_AUDIO_BECOMING_NOISY, new IBroadcastActionHandler() { @Override public void onReceiveAction(Context context, Intent intent) { pause(); } }) .register(this); }
diff --git a/src/main/java/org/basex/gui/view/explore/ExploreArea.java b/src/main/java/org/basex/gui/view/explore/ExploreArea.java index 5bfff61dc..c15f0ccc0 100644 --- a/src/main/java/org/basex/gui/view/explore/ExploreArea.java +++ b/src/main/java/org/basex/gui/view/explore/ExploreArea.java @@ -1,349 +1,350 @@ package org.basex.gui.view.explore; import static org.basex.core.Text.*; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Graphics; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import org.basex.core.cmd.Find; import org.basex.data.Data; import org.basex.data.StatsKey; import org.basex.gui.GUIConstants; import org.basex.gui.GUIProp; import org.basex.gui.GUIConstants.Fill; import org.basex.gui.layout.BaseXBack; import org.basex.gui.layout.BaseXCombo; import org.basex.gui.layout.BaseXDSlider; import org.basex.gui.layout.BaseXLabel; import org.basex.gui.layout.BaseXLayout; import org.basex.gui.layout.BaseXPanel; import org.basex.gui.layout.BaseXTextField; import org.basex.gui.layout.TableLayout; import org.basex.index.Names; import org.basex.util.StringList; import org.basex.util.Token; import org.basex.util.TokenBuilder; import org.basex.util.TokenList; import org.basex.util.Util; import org.deepfs.fs.DeepFS; /** * This is a simple user search panel. * * @author BaseX Team 2005-11, BSD License * @author Christian Gruen * @author Bastian Lemke */ final class ExploreArea extends BaseXPanel implements ActionListener { /** Component width. */ private static final int COMPW = 150; /** Exact search pattern. */ private static final String PATEX = "[% = \"%\"]"; /** Substring search pattern. */ private static final String PATSUB = "[% contains text \"%\"]"; /** Numeric search pattern. */ private static final String PATNUM = "[% >= % and % <= %]"; /** Simple search pattern. */ private static final String PATSIMPLE = "[%]"; /** Main panel. */ private final ExploreView main; /** Main panel. */ private final BaseXBack panel; /** Query field. */ private final BaseXTextField all; /** Last Query. */ private String last = ""; /** * Default constructor. * @param m main panel */ ExploreArea(final ExploreView m) { super(m.gui); main = m; layout(new BorderLayout(0, 5)).mode(Fill.NONE); all = new BaseXTextField(gui); all.addKeyListener(main); all.addKeyListener(new KeyAdapter() { @Override public void keyReleased(final KeyEvent e) { query(false); } }); add(all, BorderLayout.NORTH); panel = new BaseXBack(GUIConstants.Fill.NONE).layout( new TableLayout(20, 2, 10, 5)); add(panel, BorderLayout.CENTER); } /** * Initializes the panel. */ void init() { panel.removeAll(); panel.revalidate(); panel.repaint(); } @Override public void paintComponent(final Graphics g) { super.paintComponent(g); final Data data = gui.context.data; if(!main.visible() || data == null) return; final boolean pi = data.meta.pathindex; if(!pi || panel.getComponentCount() != 0) { if(!pi) init(); return; } if(!pi) return; all.help(data.fs != null ? HELPSEARCHFS : HELPSEARCHXML); addKeys(gui.context.data); panel.revalidate(); panel.repaint(); } /** * Adds a text field. * @param pos position */ private void addInput(final int pos) { final BaseXTextField txt = new BaseXTextField(gui); BaseXLayout.setWidth(txt, COMPW); BaseXLayout.setHeight(txt, txt.getFont().getSize() + 11); txt.setMargin(new Insets(0, 0, 0, 10)); txt.addKeyListener(new KeyAdapter() { @Override public void keyReleased(final KeyEvent e) { query(false); } }); txt.addKeyListener(main); panel.add(txt, pos); } /** * Adds a category combobox. * @param data data reference */ private void addKeys(final Data data) { final TokenList tl = new TokenList(); final int cs = panel.getComponentCount(); final boolean fs = data.fs != null; if(fs) { tl.add(Token.token(DeepFS.S_FILE)); } else { for(int c = 0; c < cs; c += 2) { final BaseXCombo combo = (BaseXCombo) panel.getComponent(c); if(combo.getSelectedIndex() == 0) continue; final String elem = combo.getSelectedItem().toString(); if(!elem.startsWith("@")) tl.add(Token.token(elem)); } } final TokenList tmp = data.pthindex.desc(tl, data, !fs, false); final String[] keys = entries(tmp.toArray()); final BaseXCombo cm = new BaseXCombo(gui, keys); cm.addActionListener(this); cm.addKeyListener(main); if(tmp.size() == 0) cm.setEnabled(false); panel.add(cm); panel.add(new BaseXLabel("")); } /** * Adds a combobox. * @param values combobox values * @param pos position */ private void addCombo(final String[] values, final int pos) { final BaseXCombo cm = new BaseXCombo(gui, values); BaseXLayout.setWidth(cm, COMPW); cm.addActionListener(this); cm.addKeyListener(main); panel.add(cm, pos); } /** * Adds a combobox. * @param min minimum value * @param max maximum value * @param pos position * @param kb kilobyte flag * @param date date flag * @param itr integer flag */ private void addSlider(final double min, final double max, final int pos, final boolean kb, final boolean date, final boolean itr) { final BaseXDSlider sl = new BaseXDSlider(gui, min, max, this); BaseXLayout.setWidth(sl, COMPW + BaseXDSlider.LABELW); sl.kb = kb; sl.date = date; sl.itr = itr; sl.addKeyListener(main); panel.add(sl, pos); } @Override public void actionPerformed(final ActionEvent e) { if(e != null) { final Object source = e.getSource(); // find modified component int cp = 0; final int cs = panel.getComponentCount(); for(int c = 0; c < cs; ++c) if(panel.getComponent(c) == source) cp = c; if((cp & 1) == 0) { // combo box with tags/attributes final BaseXCombo combo = (BaseXCombo) source; panel.remove(cp + 1); final Data data = gui.context.data; final boolean selected = combo.getSelectedIndex() != 0; if(selected) { final String item = combo.getSelectedItem().toString(); final boolean att = item.startsWith("@"); final Names names = att ? data.atts : data.tags; final byte[] key = Token.token(att ? item.substring(1) : item); final StatsKey stat = names.stat(names.id(key)); switch(stat.kind) { case INT: addSlider(stat.min, stat.max, cp + 1, item.equals("@" + DeepFS.S_SIZE), item.equals("@" + DeepFS.S_MTIME) || item.equals("@" + DeepFS.S_CTIME) || item.equals("@" + DeepFS.S_ATIME), true); break; case DBL: addSlider(stat.min, stat.max, cp + 1, false, false, false); break; case CAT: addCombo(entries(stat.cats.keys()), cp + 1); break; case TEXT: addInput(cp + 1); break; case NONE: panel.add(new BaseXLabel(""), cp + 1); break; } } else { panel.add(new BaseXLabel(""), cp + 1); } while(cp + 2 < panel.getComponentCount()) { panel.remove(cp + 2); panel.remove(cp + 2); } if(selected) addKeys(data); panel.revalidate(); panel.repaint(); } } query(false); } /** * Runs a query. * @param force force the execution of a new query */ void query(final boolean force) { final TokenBuilder tb = new TokenBuilder(); final Data data = gui.context.data; final int cs = panel.getComponentCount(); for(int c = 0; c < cs; c += 2) { final BaseXCombo com = (BaseXCombo) panel.getComponent(c); final int k = com.getSelectedIndex(); if(k <= 0) continue; String key = com.getSelectedItem().toString(); final boolean attr = key.startsWith("@"); if(!key.contains(":") && !attr) key = "*:" + key; final Component comp = panel.getComponent(c + 1); String pattern = ""; String val1 = null; String val2 = null; if(comp instanceof BaseXTextField) { val1 = ((BaseXTextField) comp).getText(); if(!val1.isEmpty()) { if(val1.startsWith("\"")) { val1 = val1.replaceAll("\"", ""); pattern = PATEX; } else { pattern = attr && data.meta.attrindex || !attr && data.meta.textindex ? PATSUB : PATEX; } } } else if(comp instanceof BaseXCombo) { final BaseXCombo combo = (BaseXCombo) comp; if(combo.getSelectedIndex() != 0) { val1 = combo.getSelectedItem().toString(); pattern = PATEX; } } else if(comp instanceof BaseXDSlider) { final BaseXDSlider slider = (BaseXDSlider) comp; if(slider.min != slider.totMin || slider.max != slider.totMax) { final double m = slider.min; final double n = slider.max; val1 = (long) m == m ? Long.toString((long) m) : Double.toString(m); val2 = (long) n == n ? Long.toString((long) n) : Double.toString(n); pattern = PATNUM; } } if(data.fs != null && tb.size() == 0) { tb.add("//" + DeepFS.S_FILE); } if(attr) { + key = "descendant-or-self::node()/" + key; if(tb.size() == 0) tb.add("//*"); if(pattern.isEmpty()) pattern = PATSIMPLE; } else { if(data.fs != null) tb.add("[" + key); else tb.add("//" + key); key = "text()"; } tb.addExt(pattern, key, val1, key, val2); if(data.fs != null && !attr) tb.add("]"); } String qu = tb.toString(); final boolean root = gui.context.root(); final boolean rt = gui.gprop.is(GUIProp.FILTERRT); if(!qu.isEmpty() && !rt && !root) qu = "." + qu; String simple = all.getText().trim(); if(!simple.isEmpty()) { simple = Find.find(simple, gui.context, rt); qu = !qu.isEmpty() ? simple + " | " + qu : simple; } if(qu.isEmpty()) qu = rt || root ? "/" : "."; if(!force && last.equals(qu)) return; last = qu; gui.xquery(qu, false); } /** * Returns the combo box selections * and the keys of the specified set. * @param key keys * @return key array */ private String[] entries(final byte[][] key) { final StringList sl = new StringList(); sl.add(Util.info(INFOENTRIES, key.length)); for(final byte[] k : key) sl.add(Token.string(k)); sl.sort(true, true, 1); return sl.toArray(); } }
true
true
void query(final boolean force) { final TokenBuilder tb = new TokenBuilder(); final Data data = gui.context.data; final int cs = panel.getComponentCount(); for(int c = 0; c < cs; c += 2) { final BaseXCombo com = (BaseXCombo) panel.getComponent(c); final int k = com.getSelectedIndex(); if(k <= 0) continue; String key = com.getSelectedItem().toString(); final boolean attr = key.startsWith("@"); if(!key.contains(":") && !attr) key = "*:" + key; final Component comp = panel.getComponent(c + 1); String pattern = ""; String val1 = null; String val2 = null; if(comp instanceof BaseXTextField) { val1 = ((BaseXTextField) comp).getText(); if(!val1.isEmpty()) { if(val1.startsWith("\"")) { val1 = val1.replaceAll("\"", ""); pattern = PATEX; } else { pattern = attr && data.meta.attrindex || !attr && data.meta.textindex ? PATSUB : PATEX; } } } else if(comp instanceof BaseXCombo) { final BaseXCombo combo = (BaseXCombo) comp; if(combo.getSelectedIndex() != 0) { val1 = combo.getSelectedItem().toString(); pattern = PATEX; } } else if(comp instanceof BaseXDSlider) { final BaseXDSlider slider = (BaseXDSlider) comp; if(slider.min != slider.totMin || slider.max != slider.totMax) { final double m = slider.min; final double n = slider.max; val1 = (long) m == m ? Long.toString((long) m) : Double.toString(m); val2 = (long) n == n ? Long.toString((long) n) : Double.toString(n); pattern = PATNUM; } } if(data.fs != null && tb.size() == 0) { tb.add("//" + DeepFS.S_FILE); } if(attr) { if(tb.size() == 0) tb.add("//*"); if(pattern.isEmpty()) pattern = PATSIMPLE; } else { if(data.fs != null) tb.add("[" + key); else tb.add("//" + key); key = "text()"; } tb.addExt(pattern, key, val1, key, val2); if(data.fs != null && !attr) tb.add("]"); } String qu = tb.toString(); final boolean root = gui.context.root(); final boolean rt = gui.gprop.is(GUIProp.FILTERRT); if(!qu.isEmpty() && !rt && !root) qu = "." + qu; String simple = all.getText().trim(); if(!simple.isEmpty()) { simple = Find.find(simple, gui.context, rt); qu = !qu.isEmpty() ? simple + " | " + qu : simple; } if(qu.isEmpty()) qu = rt || root ? "/" : "."; if(!force && last.equals(qu)) return; last = qu; gui.xquery(qu, false); }
void query(final boolean force) { final TokenBuilder tb = new TokenBuilder(); final Data data = gui.context.data; final int cs = panel.getComponentCount(); for(int c = 0; c < cs; c += 2) { final BaseXCombo com = (BaseXCombo) panel.getComponent(c); final int k = com.getSelectedIndex(); if(k <= 0) continue; String key = com.getSelectedItem().toString(); final boolean attr = key.startsWith("@"); if(!key.contains(":") && !attr) key = "*:" + key; final Component comp = panel.getComponent(c + 1); String pattern = ""; String val1 = null; String val2 = null; if(comp instanceof BaseXTextField) { val1 = ((BaseXTextField) comp).getText(); if(!val1.isEmpty()) { if(val1.startsWith("\"")) { val1 = val1.replaceAll("\"", ""); pattern = PATEX; } else { pattern = attr && data.meta.attrindex || !attr && data.meta.textindex ? PATSUB : PATEX; } } } else if(comp instanceof BaseXCombo) { final BaseXCombo combo = (BaseXCombo) comp; if(combo.getSelectedIndex() != 0) { val1 = combo.getSelectedItem().toString(); pattern = PATEX; } } else if(comp instanceof BaseXDSlider) { final BaseXDSlider slider = (BaseXDSlider) comp; if(slider.min != slider.totMin || slider.max != slider.totMax) { final double m = slider.min; final double n = slider.max; val1 = (long) m == m ? Long.toString((long) m) : Double.toString(m); val2 = (long) n == n ? Long.toString((long) n) : Double.toString(n); pattern = PATNUM; } } if(data.fs != null && tb.size() == 0) { tb.add("//" + DeepFS.S_FILE); } if(attr) { key = "descendant-or-self::node()/" + key; if(tb.size() == 0) tb.add("//*"); if(pattern.isEmpty()) pattern = PATSIMPLE; } else { if(data.fs != null) tb.add("[" + key); else tb.add("//" + key); key = "text()"; } tb.addExt(pattern, key, val1, key, val2); if(data.fs != null && !attr) tb.add("]"); } String qu = tb.toString(); final boolean root = gui.context.root(); final boolean rt = gui.gprop.is(GUIProp.FILTERRT); if(!qu.isEmpty() && !rt && !root) qu = "." + qu; String simple = all.getText().trim(); if(!simple.isEmpty()) { simple = Find.find(simple, gui.context, rt); qu = !qu.isEmpty() ? simple + " | " + qu : simple; } if(qu.isEmpty()) qu = rt || root ? "/" : "."; if(!force && last.equals(qu)) return; last = qu; gui.xquery(qu, false); }
diff --git a/src/main/java/Main.java b/src/main/java/Main.java index 1b93bb1..4fa55fe 100644 --- a/src/main/java/Main.java +++ b/src/main/java/Main.java @@ -1,77 +1,74 @@ import net.sf.json.JSONException; import net.sf.json.JSONObject; import org.apache.commons.io.IOUtils; import scalaskel.Change; import scalaskel.ChangeService; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; public class Main extends HttpServlet { private static final String SCALASKEL = "/scalaskel/change/"; private ChangeService service = new ChangeService(); private JSONObject routes; @Override public void init() throws ServletException { InputStream stream = getClass().getClassLoader().getResourceAsStream("route.json"); try { routes = JSONObject.fromObject(IOUtils.toString(stream)); } catch (IOException e) { throw new ServletException("failed to load routes definition"); } } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { getServletContext().log("POST:" + IOUtils.toString(req.getInputStream())); resp.setStatus(HttpServletResponse.SC_CREATED); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String path = req.getPathInfo(); - // strange behavior on cloudbees tomcat compared to unit test jetty - System.out.println("getPathInfo: " +path); - System.out.println("getServletPath: " +req.getServletPath()); - if (path == null) path = "/"; - if (!path.startsWith("/")) path = "/"+path; + // tomcat don't behave like jetty + if (path == null) path = req.getServletPath(); if (path.equals("/")) { String q = req.getParameter("q"); String r; if (q == null) { r = "@see http://code-story.net"; } else { try { r = routes.getString(q); } catch(JSONException e) { r = "Désole, je ne comprends pas votre question"; resp.sendError(HttpServletResponse.SC_BAD_REQUEST); } } resp.getWriter().print(r); } else if (path.startsWith(SCALASKEL)) { int groDessimal = Integer.parseInt(path.substring(SCALASKEL.length())); resp.setContentType("application/json"); PrintWriter w = resp.getWriter(); String sep = "["; for (Change change : service.getPossibleChanges(groDessimal)) { w.print(sep); sep = ", "; w.print(change.asJson()); } w.print("]"); } } }
true
true
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String path = req.getPathInfo(); // strange behavior on cloudbees tomcat compared to unit test jetty System.out.println("getPathInfo: " +path); System.out.println("getServletPath: " +req.getServletPath()); if (path == null) path = "/"; if (!path.startsWith("/")) path = "/"+path; if (path.equals("/")) { String q = req.getParameter("q"); String r; if (q == null) { r = "@see http://code-story.net"; } else { try { r = routes.getString(q); } catch(JSONException e) { r = "Désole, je ne comprends pas votre question"; resp.sendError(HttpServletResponse.SC_BAD_REQUEST); } } resp.getWriter().print(r); } else if (path.startsWith(SCALASKEL)) { int groDessimal = Integer.parseInt(path.substring(SCALASKEL.length())); resp.setContentType("application/json"); PrintWriter w = resp.getWriter(); String sep = "["; for (Change change : service.getPossibleChanges(groDessimal)) { w.print(sep); sep = ", "; w.print(change.asJson()); } w.print("]"); } }
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String path = req.getPathInfo(); // tomcat don't behave like jetty if (path == null) path = req.getServletPath(); if (path.equals("/")) { String q = req.getParameter("q"); String r; if (q == null) { r = "@see http://code-story.net"; } else { try { r = routes.getString(q); } catch(JSONException e) { r = "Désole, je ne comprends pas votre question"; resp.sendError(HttpServletResponse.SC_BAD_REQUEST); } } resp.getWriter().print(r); } else if (path.startsWith(SCALASKEL)) { int groDessimal = Integer.parseInt(path.substring(SCALASKEL.length())); resp.setContentType("application/json"); PrintWriter w = resp.getWriter(); String sep = "["; for (Change change : service.getPossibleChanges(groDessimal)) { w.print(sep); sep = ", "; w.print(change.asJson()); } w.print("]"); } }
diff --git a/src/main/java/bakersoftware/maven_replacer_plugin/ReplacerMojo.java b/src/main/java/bakersoftware/maven_replacer_plugin/ReplacerMojo.java index 55fb726..d60f2f0 100644 --- a/src/main/java/bakersoftware/maven_replacer_plugin/ReplacerMojo.java +++ b/src/main/java/bakersoftware/maven_replacer_plugin/ReplacerMojo.java @@ -1,158 +1,162 @@ package bakersoftware.maven_replacer_plugin; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; /** * Goal replaces token with value inside file * * @goal replace * * @phase compile */ public class ReplacerMojo extends AbstractMojo implements StreamFactory { private static final String LINE_SEPARATOR = System.getProperty("line.separator"); /** * File to check and replace tokens * * @parameter expression="" */ private String file; /** * Token * * @parameter expression="" */ private String token; /** * Ignore missing files * * @parameter expression="" */ private boolean ignoreMissingFile; /** * Value to replace token with * * @parameter expression="" */ private String value; /** * Token uses regex * * @parameter expression="" */ private boolean regex = true; /** * Output to another file * * @parameter expression="" */ private String outputFile; public void execute() throws MojoExecutionException { try { if (ignoreMissingFile && !fileExists(file)) { getLog().info("Ignoring missing file"); return; } - getLog().info("Replacing " + token + " with " + value + " in " + file); + if (value != null) { + getLog().info("Replacing " + token + " with " + value + " in " + file); + } else { + getLog().info("Removing all instances of" + token + " in " + file); + } if (outputFile != null) { getLog().info("Outputting to: " + outputFile); } getTokenReplacer().replaceTokens(token, value, isRegex()); } catch (IOException e) { throw new MojoExecutionException(e.getMessage()); } } public boolean isRegex() { return regex; } public void setRegex(boolean regex) { this.regex = regex; } private boolean fileExists(String filename) { return new File(filename).exists(); } public TokenReplacer getTokenReplacer() { return new TokenReplacer(this, LINE_SEPARATOR); } public void setFile(String file) { this.file = file; } public void setToken(String token) { this.token = token; } public void setValue(String value) { this.value = value; } public void setIgnoreMissingFile(boolean ignoreMissingFile) { this.ignoreMissingFile = ignoreMissingFile; } public InputStream getNewInputStream() { try { return new FileInputStream(file); } catch (FileNotFoundException e) { throw new RuntimeException(e); } } public OutputStream getNewOutputStream() { try { if (outputFile != null) { if (!fileExists(outputFile)) { ensureFolderStructureExists(outputFile); } return new FileOutputStream(outputFile); } else { return new FileOutputStream(file); } } catch (Exception e) { throw new RuntimeException(e); } } private void ensureFolderStructureExists(String file) throws MojoExecutionException { File outputFile = new File(file); if (!outputFile.isDirectory()) { File parentPath = new File(outputFile.getParent()); if (!parentPath.exists()) { parentPath.mkdirs(); } } else { String errorMsg = "Parameter outputFile cannot be a directory: " + file; throw new MojoExecutionException(errorMsg); } } public String getOutputFile() { return outputFile; } public void setOutputFile(String outputFile) { this.outputFile = outputFile; } }
true
true
public void execute() throws MojoExecutionException { try { if (ignoreMissingFile && !fileExists(file)) { getLog().info("Ignoring missing file"); return; } getLog().info("Replacing " + token + " with " + value + " in " + file); if (outputFile != null) { getLog().info("Outputting to: " + outputFile); } getTokenReplacer().replaceTokens(token, value, isRegex()); } catch (IOException e) { throw new MojoExecutionException(e.getMessage()); } }
public void execute() throws MojoExecutionException { try { if (ignoreMissingFile && !fileExists(file)) { getLog().info("Ignoring missing file"); return; } if (value != null) { getLog().info("Replacing " + token + " with " + value + " in " + file); } else { getLog().info("Removing all instances of" + token + " in " + file); } if (outputFile != null) { getLog().info("Outputting to: " + outputFile); } getTokenReplacer().replaceTokens(token, value, isRegex()); } catch (IOException e) { throw new MojoExecutionException(e.getMessage()); } }
diff --git a/zxingorg/src/com/google/zxing/web/DecodeServlet.java b/zxingorg/src/com/google/zxing/web/DecodeServlet.java index e3245c1d..70a35556 100644 --- a/zxingorg/src/com/google/zxing/web/DecodeServlet.java +++ b/zxingorg/src/com/google/zxing/web/DecodeServlet.java @@ -1,402 +1,405 @@ /* * Copyright 2008 ZXing 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 com.google.zxing.web; import com.google.zxing.BarcodeFormat; import com.google.zxing.BinaryBitmap; import com.google.zxing.ChecksumException; import com.google.zxing.DecodeHintType; import com.google.zxing.FormatException; import com.google.zxing.LuminanceSource; import com.google.zxing.MultiFormatReader; import com.google.zxing.NotFoundException; import com.google.zxing.Reader; import com.google.zxing.ReaderException; import com.google.zxing.Result; import com.google.zxing.client.j2se.BufferedImageLuminanceSource; import com.google.zxing.common.GlobalHistogramBinarizer; import com.google.zxing.common.HybridBinarizer; import com.google.zxing.multi.GenericMultipleBarcodeReader; import com.google.zxing.multi.MultipleBarcodeReader; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.http.Header; import org.apache.http.HttpMessage; import org.apache.http.HttpResponse; import org.apache.http.HttpVersion; import org.apache.http.HttpEntity; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.conn.scheme.PlainSocketFactory; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.conn.ClientConnectionManager; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.conn.SingleClientConnManager; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpParams; import org.apache.http.params.HttpProtocolParams; import java.awt.color.CMMException; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Hashtable; import java.util.List; import java.util.Vector; import java.util.logging.Logger; import javax.imageio.ImageIO; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * {@link HttpServlet} which decodes images containing barcodes. Given a URL, it will * retrieve the image and decode it. It can also process image files uploaded via POST. * * @author Sean Owen */ public final class DecodeServlet extends HttpServlet { // No real reason to let people upload more than a 2MB image private static final long MAX_IMAGE_SIZE = 2000000L; // No real reason to deal with more than maybe 2 megapixels private static final int MAX_PIXELS = 1 << 21; private static final Logger log = Logger.getLogger(DecodeServlet.class.getName()); static final Hashtable<DecodeHintType, Object> HINTS; static final Hashtable<DecodeHintType, Object> HINTS_PURE; static { HINTS = new Hashtable<DecodeHintType, Object>(5); HINTS.put(DecodeHintType.TRY_HARDER, Boolean.TRUE); Collection<BarcodeFormat> possibleFormats = new Vector<BarcodeFormat>(); possibleFormats.add(BarcodeFormat.UPC_A); possibleFormats.add(BarcodeFormat.UPC_E); possibleFormats.add(BarcodeFormat.EAN_8); possibleFormats.add(BarcodeFormat.EAN_13); possibleFormats.add(BarcodeFormat.CODE_39); possibleFormats.add(BarcodeFormat.CODE_128); possibleFormats.add(BarcodeFormat.ITF); possibleFormats.add(BarcodeFormat.RSS14); possibleFormats.add(BarcodeFormat.QR_CODE); possibleFormats.add(BarcodeFormat.DATAMATRIX); possibleFormats.add(BarcodeFormat.PDF417); HINTS.put(DecodeHintType.POSSIBLE_FORMATS, possibleFormats); HINTS_PURE = new Hashtable<DecodeHintType, Object>(HINTS); HINTS_PURE.put(DecodeHintType.PURE_BARCODE, Boolean.TRUE); } private HttpParams params; private SchemeRegistry registry; private DiskFileItemFactory diskFileItemFactory; @Override public void init(ServletConfig servletConfig) { Logger logger = Logger.getLogger("com.google.zxing"); logger.addHandler(new ServletContextLogHandler(servletConfig.getServletContext())); params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); registry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); diskFileItemFactory = new DiskFileItemFactory(); log.info("DecodeServlet configured"); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String imageURIString = request.getParameter("u"); if (imageURIString == null || imageURIString.length() == 0) { log.fine("URI was empty"); response.sendRedirect("badurl.jspx"); return; } imageURIString = imageURIString.trim(); if (!(imageURIString.startsWith("http://") || imageURIString.startsWith("https://"))) { imageURIString = "http://" + imageURIString; } URI imageURI; try { imageURI = new URI(imageURIString); } catch (URISyntaxException urise) { log.fine("URI was not valid: " + imageURIString); response.sendRedirect("badurl.jspx"); return; } ClientConnectionManager connectionManager = new SingleClientConnManager(params, registry); HttpClient client = new DefaultHttpClient(connectionManager, params); HttpUriRequest getRequest = new HttpGet(imageURI); getRequest.addHeader("Connection", "close"); // Avoids CLOSE_WAIT socket issue? try { HttpResponse getResponse; try { getResponse = client.execute(getRequest); } catch (IllegalArgumentException iae) { // Thrown if hostname is bad or null log.fine(iae.toString()); getRequest.abort(); response.sendRedirect("badurl.jspx"); return; } catch (IOException ioe) { // Encompasses lots of stuff, including // java.net.SocketException, java.net.UnknownHostException, // javax.net.ssl.SSLPeerUnverifiedException, // org.apache.http.NoHttpResponseException, // org.apache.http.client.ClientProtocolException, log.fine(ioe.toString()); getRequest.abort(); response.sendRedirect("badurl.jspx"); return; } if (getResponse.getStatusLine().getStatusCode() != HttpServletResponse.SC_OK) { log.fine("Unsuccessful return code: " + getResponse.getStatusLine().getStatusCode()); response.sendRedirect("badurl.jspx"); return; } if (!isSizeOK(getResponse)) { log.fine("Too large"); response.sendRedirect("badimage.jspx"); return; } log.info("Decoding " + imageURI); HttpEntity entity = getResponse.getEntity(); InputStream is = entity.getContent(); try { processStream(is, request, response); } finally { entity.consumeContent(); is.close(); } } finally { connectionManager.shutdown(); } } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (!ServletFileUpload.isMultipartContent(request)) { log.fine("File upload was not multipart"); response.sendRedirect("badimage.jspx"); return; } ServletFileUpload upload = new ServletFileUpload(diskFileItemFactory); upload.setFileSizeMax(MAX_IMAGE_SIZE); // Parse the request try { for (FileItem item : (List<FileItem>) upload.parseRequest(request)) { if (!item.isFormField()) { if (item.getSize() <= MAX_IMAGE_SIZE) { log.info("Decoding uploaded file"); InputStream is = item.getInputStream(); try { processStream(is, request, response); } finally { is.close(); } } else { log.fine("Too large"); response.sendRedirect("badimage.jspx"); } break; } } } catch (FileUploadException fue) { log.fine(fue.toString()); response.sendRedirect("badimage.jspx"); } } private static void processStream(InputStream is, ServletRequest request, HttpServletResponse response) throws ServletException, IOException { BufferedImage image; try { image = ImageIO.read(is); } catch (IOException ioe) { log.fine(ioe.toString()); // Includes javax.imageio.IIOException response.sendRedirect("badimage.jspx"); return; } catch (CMMException cmme) { log.fine(cmme.toString()); // Have seen this in logs response.sendRedirect("badimage.jspx"); return; } catch (IllegalArgumentException iae) { log.fine(iae.toString()); // Have seen this in logs for some JPEGs response.sendRedirect("badimage.jspx"); return; } - if (image == null || - image.getHeight() <= 1 || image.getWidth() <= 1 || + if (image == null) { + response.sendRedirect("badimage.jspx"); + return; + } + if (image.getHeight() <= 1 || image.getWidth() <= 1 || image.getHeight() * image.getWidth() > MAX_PIXELS) { log.fine("Dimensions too large: " + image.getWidth() + 'x' + image.getHeight()); response.sendRedirect("badimage.jspx"); return; } Reader reader = new MultiFormatReader(); LuminanceSource source = new BufferedImageLuminanceSource(image); BinaryBitmap bitmap = new BinaryBitmap(new GlobalHistogramBinarizer(source)); Collection<Result> results = new ArrayList<Result>(1); ReaderException savedException = null; try { // Look for multiple barcodes MultipleBarcodeReader multiReader = new GenericMultipleBarcodeReader(reader); Result[] theResults = multiReader.decodeMultiple(bitmap, HINTS); if (theResults != null) { results.addAll(Arrays.asList(theResults)); } } catch (ReaderException re) { savedException = re; } if (results.isEmpty()) { try { // Look for pure barcode Result theResult = reader.decode(bitmap, HINTS_PURE); if (theResult != null) { results.add(theResult); } } catch (ReaderException re) { savedException = re; } } if (results.isEmpty()) { try { // Look for normal barcode in photo Result theResult = reader.decode(bitmap, HINTS); if (theResult != null) { results.add(theResult); } } catch (ReaderException re) { savedException = re; } } if (results.isEmpty()) { try { // Try again with other binarizer BinaryBitmap hybridBitmap = new BinaryBitmap(new HybridBinarizer(source)); Result theResult = reader.decode(hybridBitmap, HINTS); if (theResult != null) { results.add(theResult); } } catch (ReaderException re) { savedException = re; } } if (results.isEmpty()) { handleException(savedException, response); return; } if (request.getParameter("full") == null) { response.setContentType("text/plain"); response.setCharacterEncoding("UTF8"); Writer out = new OutputStreamWriter(response.getOutputStream(), "UTF8"); try { for (Result result : results) { out.write(result.getText()); out.write('\n'); } } finally { out.close(); } } else { request.setAttribute("results", results); request.getRequestDispatcher("decoderesult.jspx").forward(request, response); } } private static void handleException(ReaderException re, HttpServletResponse response) throws IOException { if (re instanceof NotFoundException) { log.info("Not found: " + re); response.sendRedirect("notfound.jspx"); } else if (re instanceof FormatException) { log.info("Format problem: " + re); response.sendRedirect("format.jspx"); } else if (re instanceof ChecksumException) { log.info("Checksum problem: " + re); response.sendRedirect("format.jspx"); } else { log.info("Unknown problem: " + re); response.sendRedirect("notfound.jspx"); } } private static boolean isSizeOK(HttpMessage getResponse) { Header lengthHeader = getResponse.getLastHeader("Content-Length"); if (lengthHeader != null) { long length = Long.parseLong(lengthHeader.getValue()); if (length > MAX_IMAGE_SIZE) { return false; } } return true; } @Override public void destroy() { log.config("DecodeServlet shutting down..."); } }
true
true
private static void processStream(InputStream is, ServletRequest request, HttpServletResponse response) throws ServletException, IOException { BufferedImage image; try { image = ImageIO.read(is); } catch (IOException ioe) { log.fine(ioe.toString()); // Includes javax.imageio.IIOException response.sendRedirect("badimage.jspx"); return; } catch (CMMException cmme) { log.fine(cmme.toString()); // Have seen this in logs response.sendRedirect("badimage.jspx"); return; } catch (IllegalArgumentException iae) { log.fine(iae.toString()); // Have seen this in logs for some JPEGs response.sendRedirect("badimage.jspx"); return; } if (image == null || image.getHeight() <= 1 || image.getWidth() <= 1 || image.getHeight() * image.getWidth() > MAX_PIXELS) { log.fine("Dimensions too large: " + image.getWidth() + 'x' + image.getHeight()); response.sendRedirect("badimage.jspx"); return; } Reader reader = new MultiFormatReader(); LuminanceSource source = new BufferedImageLuminanceSource(image); BinaryBitmap bitmap = new BinaryBitmap(new GlobalHistogramBinarizer(source)); Collection<Result> results = new ArrayList<Result>(1); ReaderException savedException = null; try { // Look for multiple barcodes MultipleBarcodeReader multiReader = new GenericMultipleBarcodeReader(reader); Result[] theResults = multiReader.decodeMultiple(bitmap, HINTS); if (theResults != null) { results.addAll(Arrays.asList(theResults)); } } catch (ReaderException re) { savedException = re; } if (results.isEmpty()) { try { // Look for pure barcode Result theResult = reader.decode(bitmap, HINTS_PURE); if (theResult != null) { results.add(theResult); } } catch (ReaderException re) { savedException = re; } } if (results.isEmpty()) { try { // Look for normal barcode in photo Result theResult = reader.decode(bitmap, HINTS); if (theResult != null) { results.add(theResult); } } catch (ReaderException re) { savedException = re; } } if (results.isEmpty()) { try { // Try again with other binarizer BinaryBitmap hybridBitmap = new BinaryBitmap(new HybridBinarizer(source)); Result theResult = reader.decode(hybridBitmap, HINTS); if (theResult != null) { results.add(theResult); } } catch (ReaderException re) { savedException = re; } } if (results.isEmpty()) { handleException(savedException, response); return; } if (request.getParameter("full") == null) { response.setContentType("text/plain"); response.setCharacterEncoding("UTF8"); Writer out = new OutputStreamWriter(response.getOutputStream(), "UTF8"); try { for (Result result : results) { out.write(result.getText()); out.write('\n'); } } finally { out.close(); } } else { request.setAttribute("results", results); request.getRequestDispatcher("decoderesult.jspx").forward(request, response); } }
private static void processStream(InputStream is, ServletRequest request, HttpServletResponse response) throws ServletException, IOException { BufferedImage image; try { image = ImageIO.read(is); } catch (IOException ioe) { log.fine(ioe.toString()); // Includes javax.imageio.IIOException response.sendRedirect("badimage.jspx"); return; } catch (CMMException cmme) { log.fine(cmme.toString()); // Have seen this in logs response.sendRedirect("badimage.jspx"); return; } catch (IllegalArgumentException iae) { log.fine(iae.toString()); // Have seen this in logs for some JPEGs response.sendRedirect("badimage.jspx"); return; } if (image == null) { response.sendRedirect("badimage.jspx"); return; } if (image.getHeight() <= 1 || image.getWidth() <= 1 || image.getHeight() * image.getWidth() > MAX_PIXELS) { log.fine("Dimensions too large: " + image.getWidth() + 'x' + image.getHeight()); response.sendRedirect("badimage.jspx"); return; } Reader reader = new MultiFormatReader(); LuminanceSource source = new BufferedImageLuminanceSource(image); BinaryBitmap bitmap = new BinaryBitmap(new GlobalHistogramBinarizer(source)); Collection<Result> results = new ArrayList<Result>(1); ReaderException savedException = null; try { // Look for multiple barcodes MultipleBarcodeReader multiReader = new GenericMultipleBarcodeReader(reader); Result[] theResults = multiReader.decodeMultiple(bitmap, HINTS); if (theResults != null) { results.addAll(Arrays.asList(theResults)); } } catch (ReaderException re) { savedException = re; } if (results.isEmpty()) { try { // Look for pure barcode Result theResult = reader.decode(bitmap, HINTS_PURE); if (theResult != null) { results.add(theResult); } } catch (ReaderException re) { savedException = re; } } if (results.isEmpty()) { try { // Look for normal barcode in photo Result theResult = reader.decode(bitmap, HINTS); if (theResult != null) { results.add(theResult); } } catch (ReaderException re) { savedException = re; } } if (results.isEmpty()) { try { // Try again with other binarizer BinaryBitmap hybridBitmap = new BinaryBitmap(new HybridBinarizer(source)); Result theResult = reader.decode(hybridBitmap, HINTS); if (theResult != null) { results.add(theResult); } } catch (ReaderException re) { savedException = re; } } if (results.isEmpty()) { handleException(savedException, response); return; } if (request.getParameter("full") == null) { response.setContentType("text/plain"); response.setCharacterEncoding("UTF8"); Writer out = new OutputStreamWriter(response.getOutputStream(), "UTF8"); try { for (Result result : results) { out.write(result.getText()); out.write('\n'); } } finally { out.close(); } } else { request.setAttribute("results", results); request.getRequestDispatcher("decoderesult.jspx").forward(request, response); } }
diff --git a/src/gov/nih/nci/cadsr/cdecurate/tool/ValueDomainServlet.java b/src/gov/nih/nci/cadsr/cdecurate/tool/ValueDomainServlet.java index 85f2dddf..8be30f57 100644 --- a/src/gov/nih/nci/cadsr/cdecurate/tool/ValueDomainServlet.java +++ b/src/gov/nih/nci/cadsr/cdecurate/tool/ValueDomainServlet.java @@ -1,2360 +1,2361 @@ package gov.nih.nci.cadsr.cdecurate.tool; import java.util.HashMap; import java.util.Vector; import gov.nih.nci.cadsr.cdecurate.ui.AltNamesDefsSession; import gov.nih.nci.cadsr.cdecurate.util.DataManager; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class ValueDomainServlet extends CurationServlet { public ValueDomainServlet() { } public ValueDomainServlet(HttpServletRequest req, HttpServletResponse res, ServletContext sc) { super(req, res, sc); } public void execute(ACRequestTypes reqType) throws Exception { switch (reqType){ case newVDFromMenu: doOpenCreateNewPages(); break; case newVDfromForm: doCreateVDActions(); break; case editVD: doEditVDActions(); break; case createNewVD: doOpenCreateVDPage(); break; case validateVDFromForm: doInsertVD(); break; case viewVALUEDOMAIN: doOpenViewPage(); break; case viewVDPVSTab: doViewPageTab(); break; } } /** * The doOpenCreateNewPages method will set some session attributes then forward the request to a Create page. * Called from 'service' method where reqType is 'newDEFromMenu', 'newDECFromMenu', 'newVDFromMenu' Sets some * initial session attributes. Calls 'getAC.getACList' to get the Data list from the database for the selected * context. Sets session Bean and forwards the create page for the selected component. * @throws Exception */ private void doOpenCreateNewPages() throws Exception { HttpSession session = m_classReq.getSession(); clearSessionAttributes(m_classReq, m_classRes); this.clearBuildingBlockSessionAttributes(m_classReq, m_classRes); String context = (String) session.getAttribute("sDefaultContext"); // from Login.jsp DataManager.setAttribute(session, Session_Data.SESSION_MENU_ACTION, "nothing"); DataManager.setAttribute(session, "DDEAction", "nothing"); // reset from "CreateNewDEFComp" DataManager.setAttribute(session, "sCDEAction", "nothing"); DataManager.setAttribute(session, "VDPageAction", "nothing"); DataManager.setAttribute(session, "DECPageAction", "nothing"); DataManager.setAttribute(session, "sDefaultContext", context); this.clearCreateSessionAttributes(m_classReq, m_classRes); // clear some session attributes DataManager.setAttribute(session, "originAction", "NewVDFromMenu"); DataManager.setAttribute(session, "LastMenuButtonPressed", "CreateVD"); VD_Bean m_VD = new VD_Bean(); m_VD.setVD_ASL_NAME("DRAFT NEW"); m_VD.setAC_PREF_NAME_TYPE("SYS"); DataManager.setAttribute(session, "m_VD", m_VD); VD_Bean oldVD = new VD_Bean(); oldVD.setVD_ASL_NAME("DRAFT NEW"); oldVD.setAC_PREF_NAME_TYPE("SYS"); DataManager.setAttribute(session, "oldVDBean", oldVD); EVS_Bean m_OC = new EVS_Bean(); DataManager.setAttribute(session, "m_OC", m_OC); EVS_Bean m_PC = new EVS_Bean(); DataManager.setAttribute(session, "m_PC", m_PC); EVS_Bean m_REP = new EVS_Bean(); DataManager.setAttribute(session, "m_REP", m_REP); EVS_Bean m_OCQ = new EVS_Bean(); DataManager.setAttribute(session, "m_OCQ", m_OCQ); EVS_Bean m_PCQ = new EVS_Bean(); DataManager.setAttribute(session, "m_PCQ", m_PCQ); EVS_Bean m_REPQ = new EVS_Bean(); DataManager.setAttribute(session, "m_REPQ", m_REPQ); ForwardJSP(m_classReq, m_classRes, "/CreateVDPage.jsp"); } // end of doOpenCreateNewPages /** * The doCreateVDActions method handles CreateVD or EditVD actions of the request. Called from 'service' method * where reqType is 'newVDfromForm' Calls 'doValidateVD' if the action is Validate or submit. Calls 'doSuggestionDE' * if the action is open EVS Window. * * @throws Exception */ private void doCreateVDActions() throws Exception { HttpSession session = m_classReq.getSession(); String sMenuAction = (String) m_classReq.getParameter("MenuAction"); if (sMenuAction != null) DataManager.setAttribute(session, Session_Data.SESSION_MENU_ACTION, sMenuAction); String sAction = (String) m_classReq.getParameter("pageAction"); if (sAction ==null ) sAction =""; DataManager.setAttribute(session, "VDPageAction", sAction); // store the page action in attribute String sSubAction = (String) m_classReq.getParameter("VDAction"); DataManager.setAttribute(session, "VDAction", sSubAction); String sOriginAction = (String) session.getAttribute("originAction"); //System.out.println("create vd " + sAction); /* if (sAction.equals("changeContext")) doChangeContext(req, res, "vd"); else */if (sAction.equals("validate")) { doValidateVD(); ForwardJSP(m_classReq, m_classRes, "/ValidateVDPage.jsp"); } else if (sAction.equals("submit")) doSubmitVD(); else if (sAction.equals("createPV") || sAction.equals("editPV") || sAction.equals("removePV")) doOpenCreatePVPage(m_classReq, m_classRes, sAction, "createVD"); else if (sAction.equals("removePVandParent") || sAction.equals("removeParent")) doRemoveParent(sAction, "createVD"); // else if (sAction.equals("searchPV")) // doSearchPV(m_classReq, m_classRes); else if (sAction.equals("createVM")) doOpenCreateVMPage(m_classReq, m_classRes, "vd"); else if (sAction.equals("Enum") || sAction.equals("NonEnum")) { doSetVDPage("Create"); ForwardJSP(m_classReq, m_classRes, "/CreateVDPage.jsp"); } else if (sAction.equals("clearBoxes")) { String ret = clearEditsOnPage(sOriginAction, sMenuAction); // , "vdEdits"); ForwardJSP(m_classReq, m_classRes, "/CreateVDPage.jsp"); } /* * else if (sAction.equals("refreshCreateVD")) { doSelectParentVD(req, res); ForwardJSP(req, res, * "/CreateVDPage.jsp"); return; } */else if (sAction.equals("UseSelection")) { String nameAction = "newName"; if (sMenuAction.equals("NewVDTemplate") || sMenuAction.equals("NewVDVersion")) nameAction = "appendName"; doVDUseSelection(nameAction); ForwardJSP(m_classReq, m_classRes, "/CreateVDPage.jsp"); return; } else if (sAction.equals("RemoveSelection")) { doRemoveBuildingBlocksVD(); // re work on the naming if new one VD_Bean vd = (VD_Bean) session.getAttribute("m_VD"); EVS_Bean nullEVS = null; if (!sMenuAction.equals("NewVDTemplate") && !sMenuAction.equals("NewVDVersion")) vd = (VD_Bean) this.getACNames(nullEVS, "Search", vd); // change only abbr pref name else vd = (VD_Bean) this.getACNames(nullEVS, "Remove", vd); // need to change the long name & def also DataManager.setAttribute(session, "m_VD", vd); ForwardJSP(m_classReq, m_classRes, "/CreateVDPage.jsp"); return; } else if (sAction.equals("changeNameType")) { this.doChangeVDNameType(); ForwardJSP(m_classReq, m_classRes, "/CreateVDPage.jsp"); } /* * else if (sAction.equals("CreateNonEVSRef")) { doNonEVSReference(req, res); ForwardJSP(req, res, * "/CreateVDPage.jsp"); } */else if (sAction.equals("addSelectedCon")) { doSelectVMConcept(m_classReq, m_classRes, sAction); ForwardJSP(m_classReq, m_classRes, "/CreateVDPage.jsp"); } else if (sAction.equals("sortPV")) { GetACSearch serAC = new GetACSearch(m_classReq, m_classRes, this); String sField = (String) m_classReq.getParameter("pvSortColumn"); VD_Bean vd = (VD_Bean) session.getAttribute("m_VD"); serAC.getVDPVSortedRows(vd,sField,"create",""); // call the method to sort pv attribute ForwardJSP(m_classReq, m_classRes, "/CreateVDPage.jsp"); return; } else if (sAction.equals("Store Alternate Names") || sAction.equals("Store Reference Documents")) this.doMarkACBeanForAltRef(m_classReq, m_classRes, "ValueDomain", sAction, "createAC"); // add/edit or remove contacts else if (sAction.equals("doContactUpd") || sAction.equals("removeContact")) { VD_Bean VDBean = (VD_Bean) session.getAttribute("m_VD"); // capture all page attributes m_setAC.setVDValueFromPage(m_classReq, m_classRes, VDBean); VDBean.setAC_CONTACTS(this.doContactACUpdates(m_classReq, sAction)); ForwardJSP(m_classReq, m_classRes, "/CreateVDPage.jsp"); } // open the DE page or search page with else if (sAction.equals("goBack")) { String sFor = goBackfromVD(sOriginAction, sMenuAction, "", "", "create"); ForwardJSP(m_classReq, m_classRes, sFor); } else if (sAction.equals("vdpvstab")) { DataManager.setAttribute(session, "TabFocus", "PV"); doValidateVD(); ForwardJSP(m_classReq, m_classRes, "/PermissibleValue.jsp"); } else if (sAction.equals("vddetailstab")) { DataManager.setAttribute(session, "TabFocus", "VD"); doValidateVD(); ForwardJSP(m_classReq, m_classRes, "/CreateVDPage.jsp"); } } /** * The doEditDEActions method handles EditDE actions of the request. Called from 'service' method where reqType is * 'EditVD' Calls 'ValidateDE' if the action is Validate or submit. Calls 'doSuggestionDE' if the action is open EVS * Window. * * @throws Exception */ private void doEditVDActions() throws Exception { HttpSession session = m_classReq.getSession(); String sMenuAction = (String) m_classReq.getParameter("MenuAction"); if (sMenuAction != null) DataManager.setAttribute(session, Session_Data.SESSION_MENU_ACTION, sMenuAction); String sAction = (String) m_classReq.getParameter("pageAction"); if (sAction ==null ) sAction =""; DataManager.setAttribute(session, "VDPageAction", sAction); // store the page action in attribute String sSubAction = (String) m_classReq.getParameter("VDAction"); DataManager.setAttribute(session, "VDAction", sSubAction); String sButtonPressed = (String) session.getAttribute("LastMenuButtonPressed"); String sSearchAC = (String) session.getAttribute("SearchAC"); if (sSearchAC == null) sSearchAC = ""; String sOriginAction = (String) session.getAttribute("originAction"); if (sAction.equals("submit")) doSubmitVD(); else if (sAction.equals("validate") && sOriginAction.equals("BlockEditVD")) doValidateVDBlockEdit(); else if (sAction.equals("validate")) { doValidateVD(); ForwardJSP(m_classReq, m_classRes, "/ValidateVDPage.jsp"); } else if (sAction.equals("suggestion")) doSuggestionDE(m_classReq, m_classRes); else if (sAction.equals("UseSelection")) { String nameAction = "appendName"; if (sOriginAction.equals("BlockEditVD")) nameAction = "blockName"; doVDUseSelection(nameAction); ForwardJSP(m_classReq, m_classRes, "/EditVDPage.jsp"); return; } else if (sAction.equals("RemoveSelection")) { doRemoveBuildingBlocksVD(); // re work on the naming if new one VD_Bean vd = (VD_Bean) session.getAttribute("m_VD"); EVS_Bean nullEVS = null; vd = (VD_Bean) this.getACNames(nullEVS, "Remove", vd); // change only abbr pref name DataManager.setAttribute(session, "m_VD", vd); ForwardJSP(m_classReq, m_classRes, "/EditVDPage.jsp"); return; } else if (sAction.equals("changeNameType")) { this.doChangeVDNameType(); ForwardJSP(m_classReq, m_classRes, "/EditVDPage.jsp"); } else if (sAction.equals("sortPV")) { GetACSearch serAC = new GetACSearch(m_classReq, m_classRes, this); String sField = (String) m_classReq.getParameter("pvSortColumn"); VD_Bean vd = (VD_Bean) session.getAttribute("m_VD"); serAC.getVDPVSortedRows(vd,sField,"edit",""); // call the method to sort pv attribute ForwardJSP(m_classReq, m_classRes, "/EditVDPage.jsp"); return; } else if (sAction.equals("createPV") || sAction.equals("editPV") || sAction.equals("removePV")) doOpenCreatePVPage(m_classReq, m_classRes, sAction, "editVD"); else if (sAction.equals("removePVandParent") || sAction.equals("removeParent")) doRemoveParent(sAction, "editVD"); else if (sAction.equals("addSelectedCon")) { doSelectVMConcept(m_classReq, m_classRes, sAction); ForwardJSP(m_classReq, m_classRes, "/EditVDPage.jsp"); } else if (sAction.equals("Enum") || sAction.equals("NonEnum")) { doSetVDPage("Edit"); ForwardJSP(m_classReq, m_classRes, "/EditVDPage.jsp"); } else if (sAction.equals("Store Alternate Names") || sAction.equals("Store Reference Documents")) this.doMarkACBeanForAltRef(m_classReq, m_classRes, "ValueDomain", sAction, "editAC"); // add/edit or remove contacts else if (sAction.equals("doContactUpd") || sAction.equals("removeContact")) { VD_Bean VDBean = (VD_Bean) session.getAttribute("m_VD"); // capture all page attributes m_setAC.setVDValueFromPage(m_classReq, m_classRes, VDBean); VDBean.setAC_CONTACTS(this.doContactACUpdates(m_classReq, sAction)); ForwardJSP(m_classReq, m_classRes, "/EditVDPage.jsp"); } else if (sAction.equals("clearBoxes")) { String ret = clearEditsOnPage(sOriginAction, sMenuAction); // , "vdEdits"); ForwardJSP(m_classReq, m_classRes, "/EditVDPage.jsp"); } // open the Edit DE page or search page with else if (sAction.equals("goBack")) { String sFor = goBackfromVD(sOriginAction, sMenuAction, sSearchAC, sButtonPressed, "edit"); ForwardJSP(m_classReq, m_classRes, sFor); } else if (sAction.equals("vdpvstab")) { DataManager.setAttribute(session, "TabFocus", "PV"); doValidateVD(); ForwardJSP(m_classReq, m_classRes, "/PermissibleValue.jsp"); } else if (sAction.equals("vddetailstab")) { DataManager.setAttribute(session, "TabFocus", "VD"); doValidateVD(); ForwardJSP(m_classReq, m_classRes, "/EditVDPage.jsp"); } } /** * changes the dec name type as selected * * @param sOrigin * string of origin action of the ac * @throws java.lang.Exception */ private void doChangeVDNameType() throws Exception { HttpSession session = m_classReq.getSession(); // get teh selected type from teh page VD_Bean pageVD = (VD_Bean) session.getAttribute("m_VD"); m_setAC.setVDValueFromPage(m_classReq, m_classRes, pageVD); // capture all other attributes String sSysName = pageVD.getAC_SYS_PREF_NAME(); String sAbbName = pageVD.getAC_ABBR_PREF_NAME(); String sUsrName = pageVD.getAC_USER_PREF_NAME(); String sNameType = (String) m_classReq.getParameter("rNameConv"); if (sNameType == null || sNameType.equals("")) sNameType = "SYS"; // default // get the existing preferred name to make sure earlier typed one is saved in the user String sPrefName = (String) m_classReq.getParameter("txtPreferredName"); if (sPrefName != null && !sPrefName.equals("") && !sPrefName.equals("(Generated by the System)") && !sPrefName.equals(sSysName) && !sPrefName.equals(sAbbName)) pageVD.setAC_USER_PREF_NAME(sPrefName); // store typed one in de bean // reset system generated or abbr accoring if (sNameType.equals("SYS")) { if (sSysName == null) sSysName = ""; // limit to 30 characters if (sSysName.length() > 30) sSysName = sSysName.substring(sSysName.length() - 30); pageVD.setVD_PREFERRED_NAME(sSysName); } else if (sNameType.equals("ABBR")) pageVD.setVD_PREFERRED_NAME(sAbbName); else if (sNameType.equals("USER")) pageVD.setVD_PREFERRED_NAME(sUsrName); pageVD.setAC_PREF_NAME_TYPE(sNameType); // store the type in the bean // logger.debug(pageVD.getAC_PREF_NAME_TYPE() + " pref " + pageVD.getVD_PREFERRED_NAME()); DataManager.setAttribute(session, "m_VD", pageVD); } /** * Does open editVD page action from DE page called from 'doEditDEActions' method. Calls * 'm_setAC.setDEValueFromPage' to store the DE bean for later use Using the VD idseq, calls 'SerAC.search_VD' * method to gets dec attributes to populate. stores VD bean in session and opens editVD page. goes back to editDE * page if any error. * * @throws Exception */ public void doOpenEditVDPage() throws Exception { HttpSession session = m_classReq.getSession(); DE_Bean m_DE = (DE_Bean) session.getAttribute("m_DE"); if (m_DE == null) m_DE = new DE_Bean(); // store the de values in the session m_setAC.setDEValueFromPage(m_classReq, m_classRes, m_DE); DataManager.setAttribute(session, "m_DE", m_DE); this.clearBuildingBlockSessionAttributes(m_classReq, m_classRes); String sVDID = null; String sVDid[] = m_classReq.getParameterValues("selVD"); if (sVDid != null) sVDID = sVDid[0]; // get the dec bean for this id if (sVDID != null) { Vector vList = new Vector(); GetACSearch serAC = new GetACSearch(m_classReq, m_classRes, this); serAC.doVDSearch(sVDID, "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", 0, "", "", "", "", "", "", "", "", vList); // forward editVD page with this bean if (vList.size() > 0) { for (int i = 0; i < vList.size(); i++) { VD_Bean VDBean = new VD_Bean(); VDBean = (VD_Bean) vList.elementAt(i); // check if the user has write permission String contID = VDBean.getVD_CONTE_IDSEQ(); String sUser = (String) session.getAttribute("Username"); GetACService getAC = new GetACService(m_classReq, m_classRes, this); String hasPermit = getAC.hasPrivilege("Create", sUser, "vd", contID); // forward to editVD if has write permission if (hasPermit.equals("Yes")) { String sMenuAction = (String) session.getAttribute(Session_Data.SESSION_MENU_ACTION); VDBean = serAC.getVDAttributes(VDBean, "Edit", sMenuAction); // get VD other Attributes DataManager.setAttribute(session, "m_VD", VDBean); VD_Bean oldVD = new VD_Bean(); oldVD = oldVD.cloneVD_Bean(VDBean); DataManager.setAttribute(session, "oldVDBean", oldVD); // DataManager.setAttribute(session, "oldVDBean", VDBean); ForwardJSP(m_classReq, m_classRes, "/EditVDPage.jsp"); // forward to editVD page } // go back to editDE with message if no permission else { DataManager.setAttribute(session, Session_Data.SESSION_STATUS_MESSAGE, "No edit permission in " + VDBean.getVD_CONTEXT_NAME() + " context"); ForwardJSP(m_classReq, m_classRes, "/EditDEPage.jsp"); // forward to editDE page } break; } } // display error message and back to edit DE page else { DataManager.setAttribute(session, Session_Data.SESSION_STATUS_MESSAGE, "Unable to get Existing VD attributes from the database"); ForwardJSP(m_classReq, m_classRes, "/EditDEPage.jsp"); // forward to editDE page } } // display error message and back to editDE page else { DataManager.setAttribute(session, Session_Data.SESSION_STATUS_MESSAGE, "Unable to get the VDid from the page"); ForwardJSP(m_classReq, m_classRes, "/EditDEPage.jsp"); // forward to editDE page } }// end doEditDECAction /** * Called from doCreateVDActions. Calls 'setAC.setVDValueFromPage' to set the VD data from the page. Calls * 'setAC.setValidatePageValuesVD' to validate the data. Loops through the vector vValidate to check if everything * is valid and Calls 'doInsertVD' to insert the data. If vector contains invalid fields, forwards to validation * page * * @throws Exception */ private void doSubmitVD() throws Exception { HttpSession session = m_classReq.getSession(); DataManager.setAttribute(session, "sVDAction", "validate"); VD_Bean m_VD = new VD_Bean(); EVS_Bean m_OC = new EVS_Bean(); EVS_Bean m_PC = new EVS_Bean(); EVS_Bean m_REP = new EVS_Bean(); EVS_Bean m_OCQ = new EVS_Bean(); EVS_Bean m_PCQ = new EVS_Bean(); EVS_Bean m_REPQ = new EVS_Bean(); GetACService getAC = new GetACService(m_classReq, m_classRes, this); m_setAC.setVDValueFromPage(m_classReq, m_classRes, m_VD); m_OC = (EVS_Bean) session.getAttribute("m_OC"); m_PC = (EVS_Bean) session.getAttribute("m_PC"); m_OCQ = (EVS_Bean) session.getAttribute("m_OCQ"); m_PCQ = (EVS_Bean) session.getAttribute("m_PCQ"); m_REP = (EVS_Bean) session.getAttribute("m_REP"); m_REPQ = (EVS_Bean) session.getAttribute("m_REPQ"); m_setAC.setValidatePageValuesVD(m_classReq, m_classRes, m_VD, m_OC, m_PC, m_REP, m_OCQ, m_PCQ, m_REPQ, getAC); DataManager.setAttribute(session, "m_VD", m_VD); boolean isValid = true; Vector vValidate = new Vector(); vValidate = (Vector) m_classReq.getAttribute("vValidate"); if (vValidate == null) isValid = false; else { for (int i = 0; vValidate.size() > i; i = i + 3) { String sStat = (String) vValidate.elementAt(i + 2); if (sStat.equals("Valid") == false) { isValid = false; } } } if (isValid == false) { ForwardJSP(m_classReq, m_classRes, "/ValidateVDPage.jsp"); } else { doInsertVD(); } } // end of doSumitVD /** * The doValidateVD method gets the values from page the user filled out, validates the input, then forwards results * to the Validate page Called from 'doCreateVDActions', 'doSubmitVD' method. Calls 'setAC.setVDValueFromPage' to * set the data from the page to the bean. Calls 'setAC.setValidatePageValuesVD' to validate the data. Stores 'm_VD' * bean in session. Forwards the page 'ValidateVDPage.jsp' with validation vector to display. * * @throws Exception */ private void doValidateVD() throws Exception { HttpSession session = m_classReq.getSession(); String sAction = (String) m_classReq.getParameter("pageAction"); if (sAction == null) sAction = ""; // do below for versioning to check whether these two have changed VD_Bean m_VD = (VD_Bean) session.getAttribute("m_VD"); // new VD_Bean(); EVS_Bean m_OC = new EVS_Bean(); EVS_Bean m_PC = new EVS_Bean(); EVS_Bean m_REP = new EVS_Bean(); EVS_Bean m_OCQ = new EVS_Bean(); EVS_Bean m_PCQ = new EVS_Bean(); EVS_Bean m_REPQ = new EVS_Bean(); GetACService getAC = new GetACService(m_classReq, m_classRes, this); DataManager.setAttribute(session, "VDPageAction", "validate"); // store the page action in attribute m_setAC.setVDValueFromPage(m_classReq, m_classRes, m_VD); m_OC = (EVS_Bean) session.getAttribute("m_OC"); m_PC = (EVS_Bean) session.getAttribute("m_PC"); m_OCQ = (EVS_Bean) session.getAttribute("m_OCQ"); m_PCQ = (EVS_Bean) session.getAttribute("m_PCQ"); m_REP = (EVS_Bean) session.getAttribute("m_REP"); m_REPQ = (EVS_Bean) session.getAttribute("m_REPQ"); m_setAC.setValidatePageValuesVD(m_classReq, m_classRes, m_VD, m_OC, m_PC, m_REP, m_OCQ, m_PCQ, m_REPQ, getAC); DataManager.setAttribute(session, "m_VD", m_VD); /* * if(sAction.equals("Enum") || sAction.equals("NonEnum") || sAction.equals("EnumByRef")) ForwardJSP(m_classReq, m_classRes, * "/CreateVDPage.jsp"); else if (!sAction.equals("vdpvstab") && !sAction.equals("vddetailstab")) * ForwardJSP(req, res, "/ValidateVDPage.jsp"); */} // end of doValidateVD /** * The doSetVDPage method gets the values from page the user filled out, Calls 'setAC.setVDValueFromPage' to set the * data from the page to the bean. Stores 'm_VD' bean in session. Forwards the page 'CreateVDPage.jsp' with * validation vector to display. * * @param sOrigin * origin where it is called from * * @throws Exception */ private void doSetVDPage(String sOrigin) throws Exception { try { HttpSession session = m_classReq.getSession(); String sAction = (String) m_classReq.getParameter("pageAction"); if (sAction == null) sAction = ""; // do below for versioning to check whether these two have changed VD_Bean vdBean = (VD_Bean) session.getAttribute("m_VD"); // new VD_Bean(); m_setAC.setVDValueFromPage(m_classReq, m_classRes, vdBean); // check if pvs are used in the form when type is changed to non enumerated. if (!sAction.equals("Enum")) { // get vdid from the bean // VD_Bean vdBean = (VD_Bean)session.getAttribute("m_VD"); String sVDid = vdBean.getVD_VD_IDSEQ(); boolean isExist = false; if (sOrigin.equals("Edit")) { // call function to check if relationship exists SetACService setAC = new SetACService(this); isExist = setAC.checkPVQCExists(m_classReq, m_classRes, sVDid, ""); if (isExist) { String sMsg = "Unable to change Value Domain type to Non-Enumerated " + "because one or more Permissible Values are being used in a Case Report Form. \\n" + "Please create a new version of this Value Domain to change the type to Non-Enumerated."; DataManager.setAttribute(session, Session_Data.SESSION_STATUS_MESSAGE, sMsg); vdBean.setVD_TYPE_FLAG("E"); DataManager.setAttribute(session, "m_VD", vdBean); } } // mark all the pvs as deleted to remove them while submitting. if (!isExist) { Vector<PV_Bean> vVDPVs = vdBean.getVD_PV_List(); // (Vector)session.getAttribute("VDPVList"); if (vVDPVs != null) { // set each bean as deleted to handle later Vector<PV_Bean> vRemVDPV = vdBean.getRemoved_VDPVList(); if (vRemVDPV == null) vRemVDPV = new Vector<PV_Bean>(); for (int i = 0; i < vVDPVs.size(); i++) { PV_Bean pvBean = (PV_Bean) vVDPVs.elementAt(i); vRemVDPV.addElement(pvBean); } vdBean.setRemoved_VDPVList(vRemVDPV); vdBean.setVD_PV_List(new Vector<PV_Bean>()); } } } else { // remove meta parents since it is not needed for enum types Vector<EVS_Bean> vParentCon = vdBean.getReferenceConceptList(); // (Vector)session.getAttribute("VDParentConcept"); if (vParentCon == null) vParentCon = new Vector<EVS_Bean>(); for (int i = 0; i < vParentCon.size(); i++) { EVS_Bean ePar = (EVS_Bean) vParentCon.elementAt(i); if (ePar == null) ePar = new EVS_Bean(); String parDB = ePar.getEVS_DATABASE(); // System.out.println(i + " setvdpage " + parDB); if (parDB != null && parDB.equals("NCI Metathesaurus")) { ePar.setCON_AC_SUBMIT_ACTION("DEL"); vParentCon.setElementAt(ePar, i); } } vdBean.setReferenceConceptList(vParentCon); DataManager.setAttribute(session, "m_VD", vdBean); // get back pvs associated with this vd VD_Bean oldVD = (VD_Bean) session.getAttribute("oldVDBean"); if (oldVD == null) oldVD = new VD_Bean(); if (oldVD.getVD_TYPE_FLAG() != null && oldVD.getVD_TYPE_FLAG().equals("E")) { if (oldVD.getVD_VD_IDSEQ() != null && !oldVD.getVD_VD_IDSEQ().equals("")) { // String pvAct = "Search"; String sMenu = (String) session.getAttribute(Session_Data.SESSION_MENU_ACTION); // if (sMenu.equals("NewVDTemplate")) // pvAct = "NewUsing"; // Integer pvCount = new Integer(0); vdBean.setVD_PV_List(oldVD.cloneVDPVVector(oldVD.getVD_PV_List())); vdBean.setRemoved_VDPVList(new Vector<PV_Bean>()); GetACSearch serAC = new GetACSearch(m_classReq, m_classRes, this); if (sMenu.equals("Questions")) serAC.getACQuestionValue(vdBean); } } } DataManager.setAttribute(session, "m_VD", vdBean); } catch (Exception e) { logger.error("Error - doSetVDPage " + e.toString(), e); } } // end of doValidateVD /** * makes the vd's system generated name * * @param vd * current vd bean * @param vParent * vector of seelected parents * @return modified vd bean */ public AC_Bean getSystemName(AC_Bean ac, Vector<EVS_Bean> vParent) { VD_Bean vd = (VD_Bean)ac; try { // make the system generated name String sysName = ""; for (int i = vParent.size() - 1; i > -1; i--) { EVS_Bean par = (EVS_Bean) vParent.elementAt(i); String evsDB = par.getEVS_DATABASE(); String subAct = par.getCON_AC_SUBMIT_ACTION(); if (subAct != null && !subAct.equals("DEL") && evsDB != null && !evsDB.equals("Non_EVS")) { // add the concept id to sysname if less than 20 characters if (sysName.equals("") || sysName.length() < 20) sysName += par.getCONCEPT_IDENTIFIER() + ":"; else break; } } // append vd public id and version in the end if (vd.getVD_VD_ID() != null) sysName += vd.getVD_VD_ID(); String sver = vd.getVD_VERSION(); if (sver != null && sver.indexOf(".") < 0) sver += ".0"; if (vd.getVD_VERSION() != null) sysName += "v" + sver; // limit to 30 characters if (sysName.length() > 30) sysName = sysName.substring(sysName.length() - 30); vd.setAC_SYS_PREF_NAME(sysName); // store it in vd bean // make system name preferrd name if sys was selected String selNameType = (String) m_classReq.getParameter("rNameConv"); // get it from the vd bean if null if (selNameType == null) { selNameType = vd.getVD_TYPE_NAME(); } else { // store the keyed in text in the user field for later use. String sPrefName = (String) m_classReq.getParameter("txPreferredName"); if (selNameType != null && selNameType.equals("USER") && sPrefName != null) vd.setAC_USER_PREF_NAME(sPrefName); } if (selNameType != null && selNameType.equals("SYS")) vd.setVD_PREFERRED_NAME(sysName); } catch (Exception e) { this.logger.error("ERROR - getSystemName : " + e.toString(), e); } return vd; } /** * marks the parent and/or its pvs as deleted from the session. * * @param sPVAction * @param vdPage * @throws java.lang.Exception */ private void doRemoveParent(String sPVAction, String vdPage) throws Exception { HttpSession session = m_classReq.getSession(); VD_Bean m_VD = (VD_Bean) session.getAttribute("m_VD"); // new VD_Bean(); Vector<EVS_Bean> vParentCon = m_VD.getReferenceConceptList(); // (Vector)session.getAttribute("VDParentConcept"); if (vParentCon == null) vParentCon = new Vector<EVS_Bean>(); // get the selected parent info from teh request String sParentCC = (String) m_classReq.getParameter("selectedParentConceptCode"); String sParentName = (String) m_classReq.getParameter("selectedParentConceptName"); String sParentDB = (String) m_classReq.getParameter("selectedParentConceptDB"); // for non evs parent compare the long names instead if (sParentName != null && !sParentName.equals("") && sParentDB != null && sParentDB.equals("Non_EVS")) sParentCC = sParentName; if (sParentCC != null) { for (int i = 0; i < vParentCon.size(); i++) { EVS_Bean eBean = (EVS_Bean) vParentCon.elementAt(i); if (eBean == null) eBean = new EVS_Bean(); String thisParent = eBean.getCONCEPT_IDENTIFIER(); if (thisParent == null) thisParent = ""; String thisParentName = eBean.getLONG_NAME(); if (thisParentName == null) thisParentName = ""; String thisParentDB = eBean.getEVS_DATABASE(); if (thisParentDB == null) thisParentDB = ""; // for non evs parent compare the long names instead if (sParentDB != null && sParentDB.equals("Non_EVS")) thisParent = thisParentName; // look for the matched parent from the vector to remove if (sParentCC.equals(thisParent)) { @SuppressWarnings("unused") String strHTML = ""; EVSMasterTree tree = new EVSMasterTree(m_classReq, thisParentDB, this); strHTML = tree.refreshTree(thisParentName, "false"); strHTML = tree.refreshTree("parentTree" + thisParentName, "false"); if (sPVAction.equals("removePVandParent")) { Vector<PV_Bean> vVDPVList = m_VD.getVD_PV_List(); // (Vector)session.getAttribute("VDPVList"); if (vVDPVList == null) vVDPVList = new Vector<PV_Bean>(); // loop through the vector of pvs to get matched parent for (int j = 0; j < vVDPVList.size(); j++) { PV_Bean pvBean = (PV_Bean) vVDPVList.elementAt(j); if (pvBean == null) pvBean = new PV_Bean(); EVS_Bean pvParent = (EVS_Bean) pvBean.getPARENT_CONCEPT(); if (pvParent == null) pvParent = new EVS_Bean(); String pvParCon = pvParent.getCONCEPT_IDENTIFIER(); // match the parent concept with the pv's parent concept if (thisParent.equals(pvParCon)) { pvBean.setVP_SUBMIT_ACTION("DEL"); // mark the vp as deleted // String pvID = pvBean.getPV_PV_IDSEQ(); vVDPVList.setElementAt(pvBean, j); } } m_VD.setVD_PV_List(vVDPVList); // DataManager.setAttribute(session, "VDPVList", vVDPVList); } // mark the parent as delected and leave eBean.setCON_AC_SUBMIT_ACTION("DEL"); vParentCon.setElementAt(eBean, i); break; } } } // DataManager.setAttribute(session, "VDParentConcept", vParentCon); m_VD.setReferenceConceptList(vParentCon); // make sure all other changes are stored back in vd m_setAC.setVDValueFromPage(m_classReq, m_classRes, m_VD); // make vd's system preferred name m_VD = (VD_Bean) this.getSystemName(m_VD, vParentCon); DataManager.setAttribute(session, "m_VD", m_VD); // make the selected parent in hte session empty DataManager.setAttribute(session, "SelectedParentName", ""); DataManager.setAttribute(session, "SelectedParentCC", ""); DataManager.setAttribute(session, "SelectedParentDB", ""); DataManager.setAttribute(session, "SelectedParentMetaSource", ""); // forward teh page according to vdPage if (vdPage.equals("editVD")) ForwardJSP(m_classReq, m_classRes, "/EditVDPage.jsp"); else ForwardJSP(m_classReq, m_classRes, "/CreateVDPage.jsp"); } /** * splits the vd rep term from cadsr into individual concepts * * @param sComp * name of the searched component * @param m_Bean * selected EVS bean * @param nameAction * string naming action * */ private void splitIntoConceptsVD(String sComp, EVS_Bean m_Bean,String nameAction) { try { HttpSession session = m_classReq.getSession(); // String sSelRow = ""; VD_Bean m_VD = (VD_Bean) session.getAttribute("m_VD"); if (m_VD == null) m_VD = new VD_Bean(); m_setAC.setVDValueFromPage(m_classReq, m_classRes, m_VD); Vector vRepTerm = (Vector) session.getAttribute("vRepTerm"); if (vRepTerm == null) vRepTerm = new Vector(); String sCondr = m_Bean.getCONDR_IDSEQ(); String sLongName = m_Bean.getLONG_NAME(); String sIDSEQ = m_Bean.getIDSEQ(); if (sComp.equals("RepTerm") || sComp.equals("RepQualifier")) { m_VD.setVD_REP_TERM(sLongName); m_VD.setVD_REP_IDSEQ(sIDSEQ); } // String sRepTerm = m_VD.getVD_REP_TERM(); if (sCondr != null && !sCondr.equals("")) { GetACService getAC = new GetACService(m_classReq, m_classRes, this); Vector vCon = getAC.getAC_Concepts(sCondr, null, true); if (vCon != null && vCon.size() > 0) { for (int j = 0; j < vCon.size(); j++) { EVS_Bean bean = new EVS_Bean(); bean = (EVS_Bean) vCon.elementAt(j); if (bean != null) { if (j == 0) // Primary Concept m_VD = this.addRepConcepts(nameAction, m_VD, bean, "Primary"); else // Secondary Concepts m_VD = this.addRepConcepts(nameAction, m_VD, bean, "Qualifier"); } } } } } catch (Exception e) { this.logger.error("ERROR - splitintoConceptVD : " + e.toString(), e); } } /** * this method is used to create preferred name for VD names of all three types will be stored in the bean for later * use if type is changed, it populates name according to type selected. * * @param newBean * new EVS bean to append the name to * @param nameAct * string new name or append name * @param pageVD * current vd bean * @return VD bean */ public AC_Bean getACNames(EVS_Bean newBean, String nameAct, AC_Bean pageAC) { HttpSession session = m_classReq.getSession(); VD_Bean pageVD = (VD_Bean)pageAC; if (pageVD == null) pageVD = (VD_Bean) session.getAttribute("m_VD"); // get vd object class and property names String sLongName = ""; String sPrefName = ""; String sAbbName = ""; String sDef = ""; // get the existing one if not restructuring the name but appending it if (newBean != null) { sLongName = pageVD.getVD_LONG_NAME(); if (sLongName == null) sLongName = ""; sDef = pageVD.getVD_PREFERRED_DEFINITION(); if (sDef == null) sDef = ""; } // get the typed text on to user name String selNameType = ""; if (nameAct.equals("Search") || nameAct.equals("Remove")) { selNameType = (String) m_classReq.getParameter("rNameConv"); sPrefName = (String) m_classReq.getParameter("txPreferredName"); if (selNameType != null && selNameType.equals("USER") && sPrefName != null) pageVD.setAC_USER_PREF_NAME(sPrefName); } // get the object class into the long name and abbr name String sObjClass = pageVD.getVD_OBJ_CLASS(); if (sObjClass == null) sObjClass = ""; if (!sObjClass.equals("")) { // rearrange it long name if (newBean == null) { if (!sLongName.equals("")) sLongName += " "; // add extra space if not empty sLongName += sObjClass; EVS_Bean mOC = (EVS_Bean) session.getAttribute("m_OC"); if (mOC != null) { if (!sDef.equals("")) sDef += "_"; // add definition sDef += mOC.getPREFERRED_DEFINITION(); } } if (!sAbbName.equals("")) sAbbName += "_"; // add underscore if not empty if (sObjClass.length() > 3) sAbbName += sObjClass.substring(0, 4); // truncate to 4 letters else sAbbName = sObjClass; } // get the property into the long name and abbr name String sPropClass = pageVD.getVD_PROP_CLASS(); if (sPropClass == null) sPropClass = ""; if (!sPropClass.equals("")) { // rearrange it long name if (newBean == null) { if (!sLongName.equals("")) sLongName += " "; // add extra space if not empty sLongName += sPropClass; EVS_Bean mPC = (EVS_Bean) session.getAttribute("m_PC"); if (mPC != null) { if (!sDef.equals("")) sDef += "_"; // add definition sDef += mPC.getPREFERRED_DEFINITION(); } } if (!sAbbName.equals("")) sAbbName += "_"; // add underscore if not empty if (sPropClass.length() > 3) sAbbName += sPropClass.substring(0, 4); // truncate to 4 letters else sAbbName += sPropClass; } Vector vRep = (Vector) session.getAttribute("vRepTerm"); if (vRep == null) vRep = new Vector(); // add the qualifiers first for (int i = 1; vRep.size() > i; i++) { EVS_Bean eCon = (EVS_Bean) vRep.elementAt(i); if (eCon == null) eCon = new EVS_Bean(); String conName = eCon.getLONG_NAME(); if (conName == null) conName = ""; if (!conName.equals("")) { // rearrange it long name and definition if (newBean == null) { if (!sLongName.equals("")) sLongName += " "; sLongName += conName; if (!sDef.equals("")) sDef += "_"; // add definition sDef += eCon.getPREFERRED_DEFINITION(); } if (!sAbbName.equals("")) sAbbName += "_"; if (conName.length() > 3) sAbbName += conName.substring(0, 4); // truncate to four letters else sAbbName += conName; } } // add the primary if (vRep != null && vRep.size() > 0) { EVS_Bean eCon = (EVS_Bean) vRep.elementAt(0); if (eCon == null) eCon = new EVS_Bean(); String sPrimary = eCon.getLONG_NAME(); if (sPrimary == null) sPrimary = ""; if (!sPrimary.equals("")) { // rearrange it only long name and definition if (newBean == null) { if (!sLongName.equals("")) sLongName += " "; sLongName += sPrimary; if (!sDef.equals("")) sDef += "_"; // add definition sDef += eCon.getPREFERRED_DEFINITION(); } if (!sAbbName.equals("")) sAbbName += "_"; if (sPrimary.length() > 3) sAbbName += sPrimary.substring(0, 4); // truncate to four letters else sAbbName += sPrimary; } } // truncate to 30 characters if (sAbbName != null && sAbbName.length() > 30) sAbbName = sAbbName.substring(0, 30); // add the abbr name to vd bean and page is selected pageVD.setAC_ABBR_PREF_NAME(sAbbName); // make abbr name name preferrd name if sys was selected if (selNameType != null && selNameType.equals("ABBR")) pageVD.setVD_PREFERRED_NAME(sAbbName); if (newBean != null) // appending to the existing; { String sSelectName = newBean.getLONG_NAME(); if (!sLongName.equals("")) sLongName += " "; sLongName += sSelectName; if (!sDef.equals("")) sDef += "_"; // add definition sDef += newBean.getPREFERRED_DEFINITION(); } // store the long names, definition, and usr name in vd bean if searched if (nameAct.equals("Search")) { pageVD.setVD_LONG_NAME(sLongName); pageVD.setVD_PREFERRED_DEFINITION(sDef); pageVD.setVDNAME_CHANGED(true); } return pageVD; } /** * * @param nameAction * stirng name action * */ private void doVDUseSelection(String nameAction) { try { HttpSession session = m_classReq.getSession(); String sSelRow = ""; // InsACService insAC = new InsACService(req, res, this); VD_Bean m_VD = (VD_Bean) session.getAttribute("m_VD"); if (m_VD == null) m_VD = new VD_Bean(); m_setAC.setVDValueFromPage(m_classReq, m_classRes, m_VD); Vector<EVS_Bean> vRepTerm = (Vector) session.getAttribute("vRepTerm"); if (vRepTerm == null) vRepTerm = new Vector<EVS_Bean>(); Vector vAC = new Vector(); ; EVS_Bean m_REP = new EVS_Bean(); String sComp = (String) m_classReq.getParameter("sCompBlocks"); // get rep term components if (sComp.equals("RepTerm") || sComp.equals("RepQualifier")) { sSelRow = (String) m_classReq.getParameter("selRepRow"); // vAC = (Vector)session.getAttribute("vRepResult"); vAC = (Vector) session.getAttribute("vACSearch"); if (vAC == null) vAC = new Vector(); if (sSelRow != null && !sSelRow.equals("")) { String sObjRow = sSelRow.substring(2); Integer intObjRow = new Integer(sObjRow); int intObjRow2 = intObjRow.intValue(); if (vAC.size() > intObjRow2 - 1) m_REP = (EVS_Bean) vAC.elementAt(intObjRow2); // get name value pari String sNVP = (String) m_classReq.getParameter("nvpConcept"); if (sNVP != null && !sNVP.equals("")) { m_REP.setNVP_CONCEPT_VALUE(sNVP); String sName = m_REP.getLONG_NAME(); m_REP.setLONG_NAME(sName + "::" + sNVP); m_REP.setPREFERRED_DEFINITION(m_REP.getPREFERRED_DEFINITION() + "::" + sNVP); } //System.out.println(sNVP + sComp + m_REP.getLONG_NAME()); } else { storeStatusMsg("Unable to get the selected row from the Rep Term search results."); return; } // send it back if unable to obtion the concept if (m_REP == null || m_REP.getLONG_NAME() == null) { storeStatusMsg("Unable to obtain concept from the selected row of the " + sComp + " search results.\\n" + "Please try again."); return; } // handle the primary search if (sComp.equals("RepTerm")) { if (m_REP.getEVS_DATABASE().equals("caDSR")) { // split it if rep term, add concept class to the list if evs id exists if (m_REP.getCONDR_IDSEQ() == null || m_REP.getCONDR_IDSEQ().equals("")) { if (m_REP.getCONCEPT_IDENTIFIER() == null || m_REP.getCONCEPT_IDENTIFIER().equals("")) { storeStatusMsg("This Rep Term is not associated to a concept, so the data is suspect. \\n" + "Please choose another Rep Term."); } else m_VD = this.addRepConcepts(nameAction, m_VD, m_REP, "Primary"); } else splitIntoConceptsVD(sComp, m_REP, nameAction); } else m_VD = this.addRepConcepts(nameAction, m_VD, m_REP, "Primary"); } else if (sComp.equals("RepQualifier")) { // Do this to reserve zero position in vector for primary concept if (vRepTerm.size() < 1) { EVS_Bean OCBean = new EVS_Bean(); vRepTerm.addElement(OCBean); DataManager.setAttribute(session, "vRepTerm", vRepTerm); } m_VD = this.addRepConcepts(nameAction, m_VD, m_REP, "Qualifier"); } } else { EVS_Bean eBean = this.getEVSSelRow(m_classReq); if (eBean != null && eBean.getLONG_NAME() != null) { /* if (sComp.equals("VDObjectClass")) { m_VD.setVD_OBJ_CLASS(eBean.getLONG_NAME()); DataManager.setAttribute(session, "m_OC", eBean); } else if (sComp.equals("VDPropertyClass")) { m_VD.setVD_PROP_CLASS(eBean.getLONG_NAME()); DataManager.setAttribute(session, "m_PC", eBean); } */ if (nameAction.equals("appendName")) m_VD = (VD_Bean) this.getACNames(eBean, "Search", m_VD); } } vRepTerm = (Vector) session.getAttribute("vRepTerm"); if (vRepTerm != null && vRepTerm.size() > 0){ vRepTerm = this.getMatchingThesarusconcept(vRepTerm, "Representation Term"); m_VD = this.updateRepAttribues(vRepTerm, m_VD); } DataManager.setAttribute(session, "vRepTerm", vRepTerm); // rebuild new name if not appending EVS_Bean nullEVS = null; if (nameAction.equals("newName")) m_VD = (VD_Bean) this.getACNames(nullEVS, "Search", m_VD); else if (nameAction.equals("blockName")) m_VD = (VD_Bean) this.getACNames(nullEVS, "blockName", m_VD); DataManager.setAttribute(session, "m_VD", m_VD); } catch (Exception e) { this.logger.error("ERROR - doVDUseSelection : " + e.toString(), e); } } // end of doVDUseSelection /** * adds the selected concept to the vector of concepts for property * * @param nameAction * String naming action * @param vdBean * selected DEC_Bean * @param eBean * selected EVS_Bean * @param repType * String property type (primary or qualifier) * @return DEC_Bean * @throws Exception */ @SuppressWarnings("unchecked") private VD_Bean addRepConcepts(String nameAction, VD_Bean vdBean, EVS_Bean eBean, String repType) throws Exception { HttpSession session = m_classReq.getSession(); // add the concept bean to the OC vector and store it in the vector Vector<EVS_Bean> vRepTerm = (Vector) session.getAttribute("vRepTerm"); if (vRepTerm == null) vRepTerm = new Vector<EVS_Bean>(); // get the evs user bean EVS_UserBean eUser = (EVS_UserBean) this.sessionData.EvsUsrBean; // (EVS_UserBean)session.getAttribute(EVSSearch.EVS_USER_BEAN_ARG); // //("EvsUserBean"); if (eUser == null) eUser = new EVS_UserBean(); eBean.setCON_AC_SUBMIT_ACTION("INS"); eBean.setCONTE_IDSEQ(vdBean.getVD_CONTE_IDSEQ()); String eDB = eBean.getEVS_DATABASE(); if (eDB != null && eBean.getEVS_ORIGIN() != null && eDB.equalsIgnoreCase("caDSR")) { eDB = eBean.getVocabAttr(eUser, eBean.getEVS_ORIGIN(), EVSSearch.VOCAB_NAME, EVSSearch.VOCAB_DBORIGIN); // "vocabName", // "vocabDBOrigin"); if (eDB.equals(EVSSearch.META_VALUE)) // "MetaValue")) eDB = eBean.getEVS_ORIGIN(); eBean.setEVS_DATABASE(eDB); // eBean.getEVS_ORIGIN()); } // System.out.println(eBean.getEVS_ORIGIN() + " before thes concept for REP " + eDB); // EVSSearch evs = new EVSSearch(m_classReq, m_classRes, this); //eBean = evs.getThesaurusConcept(eBean); // add to the vector and store it in the session, reset if primary and alredy existed, add otehrwise if (repType.equals("Primary") && vRepTerm.size() > 0) vRepTerm.setElementAt(eBean, 0); else vRepTerm.addElement(eBean); DataManager.setAttribute(session, "vRepTerm", vRepTerm); DataManager.setAttribute(session, "newRepTerm", "true"); // DataManager.setAttribute(session, "selRepQRow", sSelRow); // add to name if appending if (nameAction.equals("appendName")) vdBean = (VD_Bean) this.getACNames(eBean, "Search", vdBean); return vdBean; } // end addRepConcepts /** * The doValidateVD method gets the values from page the user filled out, validates the input, then forwards results * to the Validate page Called from 'doCreateVDActions', 'doSubmitVD' method. Calls 'setAC.setVDValueFromPage' to * set the data from the page to the bean. Calls 'setAC.setValidatePageValuesVD' to validate the data. Stores 'm_VD' * bean in session. Forwards the page 'ValidateVDPage.jsp' with validation vector to display. * * @throws Exception */ private void doValidateVDBlockEdit() throws Exception { HttpSession session = m_classReq.getSession(); VD_Bean m_VD = (VD_Bean) session.getAttribute("m_VD"); // new VD_Bean(); DataManager.setAttribute(session, "VDPageAction", "validate"); // store the page action in attribute m_setAC.setVDValueFromPage(m_classReq, m_classRes, m_VD); DataManager.setAttribute(session, "m_VD", m_VD); m_setAC.setValidateBlockEdit(m_classReq, m_classRes, "ValueDomain"); DataManager.setAttribute(session, "VDEditAction", "VDBlockEdit"); ForwardJSP(m_classReq, m_classRes, "/ValidateVDPage.jsp"); } // end of doValidateVD /** * The doInsertVD method to insert or update record in the database. Called from 'service' method where reqType is * 'validateVDFromForm'. Retrieves the session bean m_VD. if the action is reEditVD forwards the page back to Edit * or create pages. * * Otherwise, calls 'doUpdateVDAction' for editing the vd. calls 'doInsertVDfromDEAction' for creating the vd from * DE page. calls 'doInsertVDfromMenuAction' for creating the vd from menu . * * @throws Exception */ private void doInsertVD() throws Exception { HttpSession session = m_classReq.getSession(); // make sure that status message is empty DataManager.setAttribute(session, Session_Data.SESSION_STATUS_MESSAGE, ""); Vector vStat = new Vector(); DataManager.setAttribute(session, "vStatMsg", vStat); String sVDAction = (String) session.getAttribute("VDAction"); if (sVDAction == null) sVDAction = ""; String sVDEditAction = (String) session.getAttribute("VDEditAction"); if (sVDEditAction == null) sVDEditAction = ""; String sAction = (String) m_classReq.getParameter("ValidateVDPageAction"); // String sMenuAction = (String) session.getAttribute(Session_Data.SESSION_MENU_ACTION); // String sButtonPressed = (String) session.getAttribute("LastMenuButtonPressed"); String sOriginAction = (String) session.getAttribute("originAction"); if (sAction == null) sAction = "submitting"; // for direct submit without validating // String spageAction = (String) m_classReq.getParameter("pageAction"); if (sAction != null) { // goes back to create/edit pages from validation page if (sAction.equals("reEditVD")) { String vdfocus = (String) session.getAttribute("TabFocus"); if (vdfocus != null && vdfocus.equals("PV")) ForwardJSP(m_classReq, m_classRes, "/PermissibleValue.jsp"); else { if (sVDAction.equals("EditVD") || sVDAction.equals("BlockEdit")) ForwardJSP(m_classReq, m_classRes, "/EditVDPage.jsp"); else ForwardJSP(m_classReq, m_classRes, "/CreateVDPage.jsp"); } } else { // edit the existing vd if (sVDAction.equals("NewVD") && sOriginAction.equals("NewVDFromMenu")) doInsertVDfromMenuAction(); else if (sVDAction.equals("EditVD") && !sOriginAction.equals("BlockEditVD")) doUpdateVDAction(); else if (sVDEditAction.equals("VDBlockEdit")) doUpdateVDActionBE(); // if create new vd from create/edit DE page. else if (sOriginAction.equals("CreateNewVDfromCreateDE") || sOriginAction.equals("CreateNewVDfromEditDE")) doInsertVDfromDEAction(sOriginAction); // from the menu AND template/ version else { doInsertVDfromMenuAction(); } } } } // end of doInsertVD /** * update record in the database and display the result. Called from 'doInsertVD' method when the aciton is editing. * Retrieves the session bean m_VD. calls 'insAC.setVD' to update the database. updates the DEbean and sends back to * EditDE page if origin is form DEpage otherwise calls 'serAC.refreshData' to get the refreshed search result * forwards the page back to search page with refreshed list after updating. * * If ret is not null stores the statusMessage as error message in session and forwards the page back to * 'EditVDPage.jsp' for Edit. * * @throws Exception */ private void doUpdateVDAction() throws Exception { HttpSession session = m_classReq.getSession(); VD_Bean VDBean = (VD_Bean) session.getAttribute("m_VD"); VD_Bean oldVDBean = (VD_Bean) session.getAttribute("oldVDBean"); // String sMenu = (String) session.getAttribute(Session_Data.SESSION_MENU_ACTION); InsACService insAC = new InsACService(m_classReq, m_classRes, this); doInsertVDBlocks(null); // udpate the status message with DE name and ID storeStatusMsg("Value Domain Name : " + VDBean.getVD_LONG_NAME()); storeStatusMsg("Public ID : " + VDBean.getVD_VD_ID()); // call stored procedure to update attributes String ret = insAC.setVD("UPD", VDBean, "Edit", oldVDBean); // forward to search page with refreshed list after successful update if ((ret == null) || ret.equals("")) { this.clearCreateSessionAttributes(m_classReq, m_classRes); // clear some session attributes String sOriginAction = (String) session.getAttribute("originAction"); GetACSearch serAC = new GetACSearch(m_classReq, m_classRes, this); // forward page back to EditDE if (sOriginAction.equals("editVDfromDE") || sOriginAction.equals("EditDE")) { DE_Bean DEBean = (DE_Bean) session.getAttribute("m_DE"); if (DEBean != null) { DEBean.setDE_VD_IDSEQ(VDBean.getVD_VD_IDSEQ()); DEBean.setDE_VD_PREFERRED_NAME(VDBean.getVD_PREFERRED_NAME()); DEBean.setDE_VD_NAME(VDBean.getVD_LONG_NAME()); // reset the attributes DataManager.setAttribute(session, "originAction", ""); // add DEC Bean into DE BEan DEBean.setDE_VD_Bean(VDBean); DataManager.setAttribute(session, "m_DE", DEBean); CurationServlet deServ = (DataElementServlet) getACServlet("DataElement"); DEBean = (DE_Bean) deServ.getACNames("new", "editVD", DEBean); } ForwardJSP(m_classReq, m_classRes, "/EditDEPage.jsp"); } // go to search page with refreshed list else { VDBean.setVD_ALIAS_NAME(VDBean.getVD_PREFERRED_NAME()); // VDBean.setVD_TYPE_NAME("PRIMARY"); DataManager.setAttribute(session, Session_Data.SESSION_MENU_ACTION, "editVD"); String oldID = VDBean.getVD_VD_IDSEQ(); serAC.refreshData(m_classReq, m_classRes, null, null, VDBean, null, "Edit", oldID); ForwardJSP(m_classReq, m_classRes, "/SearchResultsPage.jsp"); } } // goes back to edit page if error occurs else { DataManager.setAttribute(session, "VDPageAction", "nothing"); ForwardJSP(m_classReq, m_classRes, "/EditVDPage.jsp"); } } /** * update record in the database and display the result. Called from 'doInsertVD' method when the aciton is editing. * Retrieves the session bean m_VD. calls 'insAC.setVD' to update the database. updates the DEbean and sends back to * EditDE page if origin is form DEpage otherwise calls 'serAC.refreshData' to get the refreshed search result * forwards the page back to search page with refreshed list after updating. * * If ret is not null stores the statusMessage as error message in session and forwards the page back to * 'EditVDPage.jsp' for Edit. * * @throws Exception */ private void doUpdateVDActionBE() throws Exception { HttpSession session = m_classReq.getSession(); VD_Bean VDBean = (VD_Bean) session.getAttribute("m_VD"); // validated edited m_VD boolean isRefreshed = false; String ret = ":"; InsACService insAC = new InsACService(m_classReq, m_classRes, this); GetACSearch serAC = new GetACSearch(m_classReq, m_classRes, this); GetACService getAC = new GetACService(m_classReq, m_classRes, this); // Vector vStatMsg = new Vector(); String sNewRep = (String) session.getAttribute("newRepTerm"); if (sNewRep == null) sNewRep = ""; //System.out.println(" new rep " + sNewRep); Vector vBERows = (Vector) session.getAttribute("vBEResult"); int vBESize = vBERows.size(); Integer vBESize2 = new Integer(vBESize); m_classReq.setAttribute("vBESize", vBESize2); String sRep_IDSEQ = ""; if (vBERows.size() > 0) { // Be sure the buffer is loaded when doing versioning. String newVersion = VDBean.getVD_VERSION(); if (newVersion == null) newVersion = ""; boolean newVers = (newVersion.equals("Point") || newVersion.equals("Whole")); if (newVers) { @SuppressWarnings("unchecked") Vector<AC_Bean> tvec = vBERows; AltNamesDefsSession.loadAsNew(this, session, tvec); } for (int i = 0; i < (vBERows.size()); i++) { // String sVD_ID = ""; //out VD_Bean VDBeanSR = new VD_Bean(); VDBeanSR = (VD_Bean) vBERows.elementAt(i); VD_Bean oldVDBean = new VD_Bean(); oldVDBean = oldVDBean.cloneVD_Bean(VDBeanSR); // String oldName = (String) VDBeanSR.getVD_PREFERRED_NAME(); // updates the data from the page into the sr bean InsertEditsIntoVDBeanSR(VDBeanSR, VDBean); // create newly selected rep term if (i == 0 && sNewRep.equals("true")) { doInsertVDBlocks(VDBeanSR); // create it sRep_IDSEQ = VDBeanSR.getVD_REP_IDSEQ(); // get rep idseq if (sRep_IDSEQ == null) sRep_IDSEQ = ""; VDBean.setVD_REP_IDSEQ(sRep_IDSEQ); // add page vd bean String sRep_Condr = VDBeanSR.getVD_REP_CONDR_IDSEQ(); // get rep condr if (sRep_Condr == null) sRep_Condr = ""; VDBean.setVD_REP_CONDR_IDSEQ(sRep_Condr); // add to page vd bean // VDBean.setVD_REP_QUAL(""); } // DataManager.setAttribute(session, "m_VD", VDBeanSR); String oldID = oldVDBean.getVD_VD_IDSEQ(); // udpate the status message with DE name and ID storeStatusMsg("Value Domain Name : " + VDBeanSR.getVD_LONG_NAME()); storeStatusMsg("Public ID : " + VDBeanSR.getVD_VD_ID()); // insert the version if (newVers) // block version { // creates new version first and updates all other attributes String strValid = m_setAC.checkUniqueInContext("Version", "VD", null, null, VDBeanSR, getAC, "version"); if (strValid != null && !strValid.equals("")) ret = "unique constraint"; else ret = insAC.setAC_VERSION(null, null, VDBeanSR, "ValueDomain"); if (ret == null || ret.equals("")) { // PVServlet pvser = new PVServlet(req, res, this); // pvser.searchVersionPV(VDBean, 0, "", ""); // get the right system name for new version String prefName = VDBeanSR.getVD_PREFERRED_NAME(); String vdID = VDBeanSR.getVD_VD_ID(); String newVer = "v" + VDBeanSR.getVD_VERSION(); String oldVer = "v" + oldVDBean.getVD_VERSION(); // replace teh version number if system generated name if (prefName.indexOf(vdID) > 0) { prefName = prefName.replaceFirst(oldVer, newVer); VDBean.setVD_PREFERRED_NAME(prefName); } // keep the value and value count stored String pvValue = VDBeanSR.getVD_Permissible_Value(); Integer pvCount = VDBeanSR.getVD_Permissible_Value_Count(); ret = insAC.setVD("UPD", VDBeanSR, "Version", oldVDBean); if (ret == null || ret.equals("")) { VDBeanSR.setVD_Permissible_Value(pvValue); VDBeanSR.setVD_Permissible_Value_Count(pvCount); serAC.refreshData(m_classReq, m_classRes, null, null, VDBeanSR, null, "Version", oldID); isRefreshed = true; // reset the appened attributes to remove all the checking of the row Vector vCheck = new Vector(); DataManager.setAttribute(session, "CheckList", vCheck); DataManager.setAttribute(session, "AppendAction", "Not Appended"); // resetEVSBeans(req, res); } } // alerady exists else if (ret.indexOf("unique constraint") >= 0) storeStatusMsg("\\t New version " + VDBeanSR.getVD_VERSION() + " already exists in the data base.\\n"); // some other problem else storeStatusMsg("\\t " + ret + " : Unable to create new version " + VDBeanSR.getVD_VERSION() + ".\\n"); } else // block edit { ret = insAC.setVD("UPD", VDBeanSR, "Edit", oldVDBean); // forward to search page with refreshed list after successful update if ((ret == null) || ret.equals("")) { serAC.refreshData(m_classReq, m_classRes, null, null, VDBeanSR, null, "Edit", oldID); isRefreshed = true; } } } AltNamesDefsSession.blockSave(this, session); } // to get the final result vector if not refreshed at all if (!(isRefreshed)) { Vector<String> vResult = new Vector<String>(); serAC.getVDResult(m_classReq, m_classRes, vResult, ""); DataManager.setAttribute(session, "results", vResult); // store the final result in the session DataManager.setAttribute(session, "VDPageAction", "nothing"); } ForwardJSP(m_classReq, m_classRes, "/SearchResultsPage.jsp"); } /** * updates bean the selected VD from the changed values of block edit. * * @param VDBeanSR * selected vd bean from search result * @param vd * VD_Bean of the changed values. * * @throws Exception */ private void InsertEditsIntoVDBeanSR(VD_Bean VDBeanSR, VD_Bean vd) throws Exception { // get all attributes of VDBean, if attribute != "" then set that attribute of VDBeanSR String sDefinition = vd.getVD_PREFERRED_DEFINITION(); if (sDefinition == null) sDefinition = ""; if (!sDefinition.equals("")) VDBeanSR.setVD_PREFERRED_DEFINITION(sDefinition); String sCD_ID = vd.getVD_CD_IDSEQ(); if (sCD_ID == null) sCD_ID = ""; if (!sCD_ID.equals("") && !sCD_ID.equals(null)) VDBeanSR.setVD_CD_IDSEQ(sCD_ID); String sCDName = vd.getVD_CD_NAME(); if (sCDName == null) sCDName = ""; if (!sCDName.equals("") && !sCDName.equals(null)) VDBeanSR.setVD_CD_NAME(sCDName); String sAslName = vd.getVD_ASL_NAME(); if (sAslName == null) sAslName = ""; if (!sAslName.equals("")) VDBeanSR.setVD_ASL_NAME(sAslName); String sDtlName = vd.getVD_DATA_TYPE(); if (sDtlName == null) sDtlName = ""; if (!sDtlName.equals("")) VDBeanSR.setVD_DATA_TYPE(sDtlName); String sMaxLength = vd.getVD_MAX_LENGTH_NUM(); if (sMaxLength == null) sMaxLength = ""; if (!sMaxLength.equals("")) VDBeanSR.setVD_MAX_LENGTH_NUM(sMaxLength); String sFormlName = vd.getVD_FORML_NAME(); // UOM Format if (sFormlName == null) sFormlName = ""; if (!sFormlName.equals("")) VDBeanSR.setVD_FORML_NAME(sFormlName); String sUomlName = vd.getVD_UOML_NAME(); if (sUomlName == null) sUomlName = ""; if (!sUomlName.equals("")) VDBeanSR.setVD_UOML_NAME(sUomlName); String sLowValue = vd.getVD_LOW_VALUE_NUM(); if (sLowValue == null) sLowValue = ""; if (!sLowValue.equals("")) VDBeanSR.setVD_LOW_VALUE_NUM(sLowValue); String sHighValue = vd.getVD_HIGH_VALUE_NUM(); if (sHighValue == null) sHighValue = ""; if (!sHighValue.equals("")) VDBeanSR.setVD_HIGH_VALUE_NUM(sHighValue); String sMinLength = vd.getVD_MIN_LENGTH_NUM(); if (sMinLength == null) sMinLength = ""; if (!sMinLength.equals("")) VDBeanSR.setVD_MIN_LENGTH_NUM(sMinLength); String sDecimalPlace = vd.getVD_DECIMAL_PLACE(); if (sDecimalPlace == null) sDecimalPlace = ""; if (!sDecimalPlace.equals("")) VDBeanSR.setVD_DECIMAL_PLACE(sDecimalPlace); String sBeginDate = vd.getVD_BEGIN_DATE(); if (sBeginDate == null) sBeginDate = ""; if (!sBeginDate.equals("")) VDBeanSR.setVD_BEGIN_DATE(sBeginDate); String sEndDate = vd.getVD_END_DATE(); if (sEndDate == null) sEndDate = ""; if (!sEndDate.equals("")) VDBeanSR.setVD_END_DATE(sEndDate); String sSource = vd.getVD_SOURCE(); if (sSource == null) sSource = ""; if (!sSource.equals("")) VDBeanSR.setVD_SOURCE(sSource); String changeNote = vd.getVD_CHANGE_NOTE(); if (changeNote == null) changeNote = ""; if (!changeNote.equals("")) VDBeanSR.setVD_CHANGE_NOTE(changeNote); // get cs-csi from the page into the DECBean for block edit Vector vAC_CS = vd.getAC_AC_CSI_VECTOR(); if (vAC_CS != null) VDBeanSR.setAC_AC_CSI_VECTOR(vAC_CS); //get the Ref docs from the page into the DEBean for block edit Vector<REF_DOC_Bean> vAC_REF_DOCS = vd.getAC_REF_DOCS(); if(vAC_REF_DOCS!=null){ Vector<REF_DOC_Bean> temp_REF_DOCS = new Vector<REF_DOC_Bean>(); for(REF_DOC_Bean refBean:vAC_REF_DOCS ) { if(refBean.getAC_IDSEQ() == VDBeanSR.getVD_VD_IDSEQ()) { temp_REF_DOCS.add(refBean); } } VDBeanSR.setAC_REF_DOCS(temp_REF_DOCS); } String sRepTerm = vd.getVD_REP_TERM(); if (sRepTerm == null) sRepTerm = ""; if (!sRepTerm.equals("")) VDBeanSR.setVD_REP_TERM(sRepTerm); String sRepCondr = vd.getVD_REP_CONDR_IDSEQ(); if (sRepCondr == null) sRepCondr = ""; if (!sRepCondr.equals("")) VDBeanSR.setVD_REP_CONDR_IDSEQ(sRepCondr); String sREP_IDSEQ = vd.getVD_REP_IDSEQ(); if (sREP_IDSEQ != null && !sREP_IDSEQ.equals("")) VDBeanSR.setVD_REP_IDSEQ(sREP_IDSEQ); /* * String sRepQual = vd.getVD_REP_QUAL(); if (sRepQual == null) sRepQual = ""; if (!sRepQual.equals("")) * VDBeanSR.setVD_REP_QUAL(sRepQual); */ String version = vd.getVD_VERSION(); String lastVersion = (String) VDBeanSR.getVD_VERSION(); int index = -1; String pointStr = "."; String strWhBegNumber = ""; int iWhBegNumber = 0; index = lastVersion.indexOf(pointStr); String strPtBegNumber = lastVersion.substring(0, index); String afterDecimalNumber = lastVersion.substring((index + 1), (index + 2)); if (index == 1) strWhBegNumber = ""; else if (index == 2) { strWhBegNumber = lastVersion.substring(0, index - 1); Integer WhBegNumber = new Integer(strWhBegNumber); iWhBegNumber = WhBegNumber.intValue(); } String strWhEndNumber = ".0"; String beforeDecimalNumber = lastVersion.substring((index - 1), (index)); String sNewVersion = ""; Integer IadNumber = new Integer(0); Integer IbdNumber = new Integer(0); String strIncADNumber = ""; String strIncBDNumber = ""; if (version == null) version = ""; else if (version.equals("Point")) { // Point new version int incrementADNumber = 0; int incrementBDNumber = 0; Integer adNumber = new Integer(afterDecimalNumber); Integer bdNumber = new Integer(strPtBegNumber); int iADNumber = adNumber.intValue(); // after decimal int iBDNumber = bdNumber.intValue(); // before decimal if (iADNumber != 9) { incrementADNumber = iADNumber + 1; IadNumber = new Integer(incrementADNumber); strIncADNumber = IadNumber.toString(); sNewVersion = strPtBegNumber + "." + strIncADNumber; // + strPtEndNumber; } else // adNumber == 9 { incrementADNumber = 0; incrementBDNumber = iBDNumber + 1; IbdNumber = new Integer(incrementBDNumber); strIncBDNumber = IbdNumber.toString(); IadNumber = new Integer(incrementADNumber); strIncADNumber = IadNumber.toString(); sNewVersion = strIncBDNumber + "." + strIncADNumber; // + strPtEndNumber; } VDBeanSR.setVD_VERSION(sNewVersion); } else if (version.equals("Whole")) { // Whole new version Integer bdNumber = new Integer(beforeDecimalNumber); int iBDNumber = bdNumber.intValue(); int incrementBDNumber = iBDNumber + 1; if (iBDNumber != 9) { IbdNumber = new Integer(incrementBDNumber); strIncBDNumber = IbdNumber.toString(); sNewVersion = strWhBegNumber + strIncBDNumber + strWhEndNumber; } else // before decimal number == 9 { int incrementWhBegNumber = iWhBegNumber + 1; Integer IWhBegNumber = new Integer(incrementWhBegNumber); String strIncWhBegNumber = IWhBegNumber.toString(); IbdNumber = new Integer(0); strIncBDNumber = IbdNumber.toString(); sNewVersion = strIncWhBegNumber + strIncBDNumber + strWhEndNumber; } VDBeanSR.setVD_VERSION(sNewVersion); } } /** * creates new record in the database and display the result. Called from 'doInsertVD' method when the aciton is * create new VD from DEPage. Retrieves the session bean m_VD. calls 'insAC.setVD' to update the database. forwards * the page back to create DE page after successful insert. * * If ret is not null stores the statusMessage as error message in session and forwards the page back to * 'createVDPage.jsp' for Edit. * * @param sOrigin * string value from where vd creation action was originated. * * @throws Exception */ private void doInsertVDfromDEAction(String sOrigin) throws Exception { HttpSession session = m_classReq.getSession(); VD_Bean VDBean = (VD_Bean) session.getAttribute("m_VD"); InsACService insAC = new InsACService(m_classReq, m_classRes, this); // GetACSearch serAC = new GetACSearch(req, res, this); // String sMenu = (String) session.getAttribute(Session_Data.SESSION_MENU_ACTION); // insert the building blocks attriubtes before inserting vd doInsertVDBlocks(null); String ret = insAC.setVD("INS", VDBean, "New", null); // updates the de bean with new vd data after successful insert and forwards to create page if ((ret == null) || ret.equals("")) { DE_Bean DEBean = (DE_Bean) session.getAttribute("m_DE"); DEBean.setDE_VD_NAME(VDBean.getVD_LONG_NAME()); DEBean.setDE_VD_IDSEQ(VDBean.getVD_VD_IDSEQ()); // add DEC Bean into DE BEan DEBean.setDE_VD_Bean(VDBean); DataManager.setAttribute(session, "m_DE", DEBean); CurationServlet deServ = (DataElementServlet) getACServlet("DataElement"); DEBean = (DE_Bean) deServ.getACNames("new", "newVD", DEBean); this.clearCreateSessionAttributes(m_classReq, m_classRes); // clear some session attributes if (sOrigin != null && sOrigin.equals("CreateNewVDfromEditDE")) ForwardJSP(m_classReq, m_classRes, "/EditDEPage.jsp"); else ForwardJSP(m_classReq, m_classRes, "/CreateDEPage.jsp"); } // goes back to create vd page if error else { DataManager.setAttribute(session, "VDPageAction", "validate"); ForwardJSP(m_classReq, m_classRes, "/CreateVDPage.jsp"); // send it back to vd page } } /** * to create rep term and qualifier value from EVS into cadsr. Retrieves the session bean * m_VD. calls 'insAC.setDECQualifier' to insert the database. * * @param VDBeanSR * dec attribute bean. * * @throws Exception */ private void doInsertVDBlocks(VD_Bean VDBeanSR) throws Exception { HttpSession session = m_classReq.getSession(); if (VDBeanSR == null) VDBeanSR = (VD_Bean) session.getAttribute("m_VD"); ValidationStatusBean repStatusBean = new ValidationStatusBean(); Vector vRepTerm = (Vector) session.getAttribute("vRepTerm"); InsACService insAC = new InsACService(m_classReq, m_classRes, this); String userName = (String)session.getAttribute("Username"); HashMap<String, String> defaultContext = (HashMap)session.getAttribute("defaultContext"); String conteIdseq= (String)defaultContext.get("idseq"); try { if ((vRepTerm != null && vRepTerm.size() > 0) && (defaultContext != null && defaultContext.size() > 0)) { repStatusBean = insAC.evsBeanCheck(vRepTerm, defaultContext, "", "Representation Term"); } // set Rep if it is null if ((vRepTerm != null && vRepTerm.size() > 0)) { if (!repStatusBean.isEvsBeanExists()) { if (repStatusBean.isCondrExists()) { VDBeanSR.setVD_REP_CONDR_IDSEQ(repStatusBean.getCondrIDSEQ()); // Create Representation Term String repIdseq = insAC.createEvsBean(userName, repStatusBean.getCondrIDSEQ(), conteIdseq, "Representation Term"); if (repIdseq != null && !repIdseq.equals("")) { VDBeanSR.setVD_REP_IDSEQ(repIdseq); } } else { // Create Condr String condrIdseq = insAC.createCondr(vRepTerm, repStatusBean.isAllConceptsExists()); String repIdseq = ""; // Create Representation Term if (condrIdseq != null && !condrIdseq.equals("")) { VDBeanSR.setVD_REP_CONDR_IDSEQ(condrIdseq); repIdseq = insAC.createEvsBean(userName, condrIdseq, conteIdseq, "Representation Term"); } if (repIdseq != null && !repIdseq.equals("")) { VDBeanSR.setVD_REP_IDSEQ(repIdseq); } } } else { if (repStatusBean.isNewVersion()) { if (repStatusBean.getEvsBeanIDSEQ() != null && !repStatusBean.getEvsBeanIDSEQ().equals("")) { String newID = ""; newID = insAC.setOC_PROP_REP_VERSION(repStatusBean.getEvsBeanIDSEQ(), "RepTerm"); if (newID != null && !newID.equals("")) { VDBeanSR.setVD_REP_CONDR_IDSEQ(repStatusBean.getCondrIDSEQ()); VDBeanSR.setVD_REP_IDSEQ(newID); } } }else{ VDBeanSR.setVD_REP_CONDR_IDSEQ(repStatusBean.getCondrIDSEQ()); VDBeanSR.setVD_REP_IDSEQ(repStatusBean.getEvsBeanIDSEQ()); } } } m_classReq.setAttribute("REP_IDSEQ", repStatusBean.getEvsBeanIDSEQ()); } catch (Exception e) { logger.error("ERROR in ValueDoaminServlet-doInsertVDBlocks : " + e.toString(), e); m_classReq.setAttribute("retcode", "Exception"); this.storeStatusMsg("\\t Exception : Unable to update or remove Representation Term."); } DataManager.setAttribute(session, "newRepTerm", ""); } /** * creates new record in the database and display the result. Called from 'doInsertVD' method when the aciton is * create new VD from Menu. Retrieves the session bean m_VD. calls 'insAC.setVD' to update the database. calls * 'serAC.refreshData' to get the refreshed search result for template/version forwards the page back to create VD * page if new VD or back to search page if template or version after successful insert. * * If ret is not null stores the statusMessage as error message in session and forwards the page back to * 'createVDPage.jsp' for Edit. * * @throws Exception */ private void doInsertVDfromMenuAction() throws Exception { HttpSession session = m_classReq.getSession(); VD_Bean VDBean = (VD_Bean) session.getAttribute("m_VD"); InsACService insAC = new InsACService(m_classReq, m_classRes, this); GetACSearch serAC = new GetACSearch(m_classReq, m_classRes, this); String sMenuAction = (String) session.getAttribute(Session_Data.SESSION_MENU_ACTION); VD_Bean oldVDBean = (VD_Bean) session.getAttribute("oldVDBean"); if (oldVDBean == null) oldVDBean = new VD_Bean(); String ret = ""; boolean isUpdateSuccess = true; doInsertVDBlocks(null); if (sMenuAction.equals("NewVDVersion")) { // udpate the status message with DE name and ID storeStatusMsg("Value Domain Name : " + VDBean.getVD_LONG_NAME()); storeStatusMsg("Public ID : " + VDBean.getVD_VD_ID()); // creates new version first ret = insAC.setAC_VERSION(null, null, VDBean, "ValueDomain"); if (ret == null || ret.equals("")) { // get pvs related to this new VD, it was created in VD_Version // TODO serAC.doPVACSearch(VDBean.getVD_VD_IDSEQ(), VDBean.getVD_LONG_NAME(), "Version"); PVServlet pvser = new PVServlet(m_classReq, m_classRes, this); pvser.searchVersionPV(VDBean, 1, "", ""); // update non evs changes Vector<EVS_Bean> vParent = VDBean.getReferenceConceptList(); // (Vector)session.getAttribute("VDParentConcept"); if (vParent != null && vParent.size() > 0) vParent = serAC.getNonEVSParent(vParent, VDBean, "versionSubmit"); // get the right system name for new version; cannot use teh api because parent concept is not updated // yet String prefName = VDBean.getVD_PREFERRED_NAME(); if (prefName == null || prefName.equalsIgnoreCase("(Generated by the System)")) { VDBean = (VD_Bean) this.getSystemName(VDBean, vParent); VDBean.setVD_PREFERRED_NAME(VDBean.getAC_SYS_PREF_NAME()); } // and updates all other attributes ret = insAC.setVD("UPD", VDBean, "Version", oldVDBean); // resetEVSBeans(req, res); if (ret != null && !ret.equals("")) { // add newly created row to searchresults and send it to edit page for update isUpdateSuccess = false; String oldID = oldVDBean.getVD_VD_IDSEQ(); String newID = VDBean.getVD_VD_IDSEQ(); String newVersion = VDBean.getVD_VERSION(); VDBean = VDBean.cloneVD_Bean(oldVDBean); VDBean.setVD_VD_IDSEQ(newID); VDBean.setVD_VERSION(newVersion); VDBean.setVD_ASL_NAME("DRAFT MOD"); // refresh the result list by inserting newly created VD serAC.refreshData(m_classReq, m_classRes, null, null, VDBean, null, "Version", oldID); } } else storeStatusMsg("\\t " + ret + " - Unable to create new version successfully."); } else { // creates new one ret = insAC.setVD("INS", VDBean, "New", oldVDBean); // create new one } if ((ret == null) || ret.equals("")) { this.clearCreateSessionAttributes(m_classReq, m_classRes); // clear some session attributes DataManager.setAttribute(session, "VDPageAction", "nothing"); DataManager.setAttribute(session, "originAction", ""); // forwards to search page with refreshed list if template or version if ((sMenuAction.equals("NewVDTemplate")) || (sMenuAction.equals("NewVDVersion"))) { DataManager.setAttribute(session, "searchAC", "ValueDomain"); DataManager.setAttribute(session, "originAction", "NewVDTemplate"); VDBean.setVD_ALIAS_NAME(VDBean.getVD_PREFERRED_NAME()); // VDBean.setVD_TYPE_NAME("PRIMARY"); String oldID = oldVDBean.getVD_VD_IDSEQ(); if (sMenuAction.equals("NewVDTemplate")) serAC.refreshData(m_classReq, m_classRes, null, null, VDBean, null, "Template", oldID); else if (sMenuAction.equals("NewVDVersion")) serAC.refreshData(m_classReq, m_classRes, null, null, VDBean, null, "Version", oldID); ForwardJSP(m_classReq, m_classRes, "/SearchResultsPage.jsp"); } // forward to create vd page with empty data if new one else { doOpenCreateNewPages(); } } // goes back to create/edit vd page if error else { DataManager.setAttribute(session, "VDPageAction", "validate"); // forward to create or edit pages if (isUpdateSuccess == false) { // insert the created NUE in the results. String oldID = oldVDBean.getVD_VD_IDSEQ(); if (sMenuAction.equals("NewVDTemplate")) serAC.refreshData(m_classReq, m_classRes, null, null, VDBean, null, "Template", oldID); ForwardJSP(m_classReq, m_classRes, "/SearchResultsPage.jsp"); } else ForwardJSP(m_classReq, m_classRes, "/CreateVDPage.jsp"); } } /** * The doOpenCreateVDPage method gets the session, gets some values from the createDE page and stores in bean m_DE, * sets some session attributes, then forwards to CreateVD page * * @throws Exception */ public void doOpenCreateVDPage() throws Exception { HttpSession session = m_classReq.getSession(); DE_Bean m_DE = (DE_Bean) session.getAttribute("m_DE"); if (m_DE == null) m_DE = new DE_Bean(); m_setAC.setDEValueFromPage(m_classReq, m_classRes, m_DE); // store VD bean DataManager.setAttribute(session, "m_DE", m_DE); // clear some session attributes this.clearCreateSessionAttributes(m_classReq, m_classRes); // reset the vd attributes VD_Bean m_VD = new VD_Bean(); m_VD.setVD_ASL_NAME("DRAFT NEW"); m_VD.setAC_PREF_NAME_TYPE("SYS"); // call the method to get the QuestValues if exists String sMenuAction = (String) session.getAttribute(Session_Data.SESSION_MENU_ACTION); if (sMenuAction.equals("Questions")) { GetACSearch serAC = new GetACSearch(m_classReq, m_classRes, this); serAC.getACQuestionValue(m_VD); // check if enumerated or not Vector vCRFval = (Vector) session.getAttribute("vQuestValue"); if (vCRFval != null && vCRFval.size() > 0) m_VD.setVD_TYPE_FLAG("E"); else m_VD.setVD_TYPE_FLAG("N"); // read property file and set the VD bean for Placeholder data String VDDefinition = NCICurationServlet.m_settings.getProperty("VDDefinition"); m_VD.setVD_PREFERRED_DEFINITION(VDDefinition); String DataType = NCICurationServlet.m_settings.getProperty("DataType"); m_VD.setVD_DATA_TYPE(DataType); String MaxLength = NCICurationServlet.m_settings.getProperty("MaxLength"); m_VD.setVD_MAX_LENGTH_NUM(MaxLength); } DataManager.setAttribute(session, "m_VD", m_VD); VD_Bean oldVD = new VD_Bean(); oldVD = oldVD.cloneVD_Bean(m_VD); DataManager.setAttribute(session, "oldVDBean", oldVD); // DataManager.setAttribute(session, "oldVDBean", m_VD); ForwardJSP(m_classReq, m_classRes, "/CreateVDPage.jsp"); } /** * * @throws Exception * */ private void doRemoveBuildingBlocksVD() throws Exception { HttpSession session = m_classReq.getSession(); String sSelRow = ""; VD_Bean m_VD = (VD_Bean) session.getAttribute("m_VD"); if (m_VD == null) m_VD = new VD_Bean(); Vector<EVS_Bean> vRepTerm = (Vector) session.getAttribute("vRepTerm"); if (vRepTerm == null) vRepTerm = new Vector<EVS_Bean>(); String sComp = (String) m_classReq.getParameter("sCompBlocks"); if (sComp == null) sComp = ""; if (sComp.equals("RepTerm")) { EVS_Bean m_REP = new EVS_Bean(); vRepTerm.setElementAt(m_REP, 0); DataManager.setAttribute(session, "vRepTerm", vRepTerm); m_VD.setVD_REP_NAME_PRIMARY(""); m_VD.setVD_REP_CONCEPT_CODE(""); m_VD.setVD_REP_EVS_CUI_ORIGEN(""); m_VD.setVD_REP_IDSEQ(""); DataManager.setAttribute(session, "RemoveRepBlock", "true"); DataManager.setAttribute(session, "newRepTerm", "true"); } else if (sComp.equals("RepQualifier")) { sSelRow = (String) m_classReq.getParameter("selRepQRow"); if (sSelRow != null && !(sSelRow.equals(""))) { Integer intObjRow = new Integer(sSelRow); int intObjRow2 = intObjRow.intValue(); if (vRepTerm.size() > (intObjRow2 + 1)) { vRepTerm.removeElementAt(intObjRow2 + 1); // add 1 so zero element not removed DataManager.setAttribute(session, "vRepTerm", vRepTerm); } // m_VD.setVD_REP_QUAL(""); Vector vRepQualifierNames = m_VD.getVD_REP_QUALIFIER_NAMES(); if (vRepQualifierNames == null) vRepQualifierNames = new Vector(); if (vRepQualifierNames.size() > intObjRow2) vRepQualifierNames.removeElementAt(intObjRow2); Vector vRepQualifierCodes = m_VD.getVD_REP_QUALIFIER_CODES(); if (vRepQualifierCodes == null) vRepQualifierCodes = new Vector(); if (vRepQualifierCodes.size() > intObjRow2) vRepQualifierCodes.removeElementAt(intObjRow2); Vector vRepQualifierDB = m_VD.getVD_REP_QUALIFIER_DB(); if (vRepQualifierDB == null) vRepQualifierDB = new Vector(); if (vRepQualifierDB.size() > intObjRow2) vRepQualifierDB.removeElementAt(intObjRow2); m_VD.setVD_REP_QUALIFIER_NAMES(vRepQualifierNames); m_VD.setVD_REP_QUALIFIER_CODES(vRepQualifierCodes); m_VD.setVD_REP_QUALIFIER_DB(vRepQualifierDB); DataManager.setAttribute(session, "RemoveRepBlock", "true"); DataManager.setAttribute(session, "newRepTerm", "true"); } } else if (sComp.equals("VDObjectClass")) { m_VD.setVD_OBJ_CLASS(""); DataManager.setAttribute(session, "m_OC", new EVS_Bean()); } else if (sComp.equals("VDPropertyClass")) { m_VD.setVD_PROP_CLASS(""); DataManager.setAttribute(session, "m_PC", new EVS_Bean()); } if (sComp.equals("RepTerm") || sComp.equals("RepQualifier")){ vRepTerm = (Vector)session.getAttribute("vRepTerm"); if (vRepTerm != null && vRepTerm.size() > 0){ vRepTerm = this.getMatchingThesarusconcept(vRepTerm, "Representation Term"); m_VD = this.updateRepAttribues(vRepTerm, m_VD); } DataManager.setAttribute(session, "vRepTerm", vRepTerm); } m_setAC.setVDValueFromPage(m_classReq, m_classRes, m_VD); DataManager.setAttribute(session, "m_VD", m_VD); } // end of doRemoveQualifier /**method to go back from vd and pv edits * @param orgAct String value for origin where vd page was opened * @param menuAct String value of menu action where this use case started * @param actype String what action is expected * @param butPress STring last button pressed * @param vdPageFrom string to check if it was PV or VD page * @return String jsp to forward the page to */ public String goBackfromVD(String orgAct, String menuAct, String actype, String butPress, String vdPageFrom) { try { //forward the page to editDE if originated from DE HttpSession session = m_classReq.getSession(); clearBuildingBlockSessionAttributes(m_classReq, m_classRes); if (vdPageFrom.equals("create")) { clearCreateSessionAttributes(m_classReq, m_classRes); if (menuAct.equals("NewVDTemplate") || menuAct.equals("NewVDVersion")) { VD_Bean VDBean = (VD_Bean)session.getAttribute(PVForm.SESSION_SELECT_VD); GetACSearch serAC = new GetACSearch(m_classReq, m_classRes, this); serAC.refreshData(m_classReq, m_classRes, null, null, VDBean, null, "Refresh", ""); return "/SearchResultsPage.jsp"; } else if (orgAct.equalsIgnoreCase("CreateNewVDfromEditDE")) return "/EditDEPage.jsp"; else return "/CreateDEPage.jsp"; } else if (vdPageFrom.equals("edit")) { if (orgAct.equalsIgnoreCase("editVDfromDE")) return "/EditDEPage.jsp"; //forward the page to search if originated from Search else if (menuAct.equalsIgnoreCase("editVD") || orgAct.equalsIgnoreCase("EditVD") || orgAct.equalsIgnoreCase("BlockEditVD") || (butPress.equals("Search") && !actype.equals("DataElement"))) { VD_Bean VDBean = (VD_Bean)session.getAttribute(PVForm.SESSION_SELECT_VD); if (VDBean == null) VDBean = new VD_Bean(); GetACSearch serAC = new GetACSearch(m_classReq, m_classRes, this); serAC.refreshData(m_classReq, m_classRes, null, null, VDBean, null, "Refresh", ""); return "/SearchResultsPage.jsp"; } else return "/EditVDPage.jsp"; } } catch (Exception e) { logger.error("ERROR - ", e); } return ""; } /** to clear the edited data from the edit and create pages * @param orgAct String value for origin where vd page was opened * @param menuAct String value of menu action where this use case started * @return String jsp to forward the page to */ public String clearEditsOnPage(String orgAct, String menuAct) { try { HttpSession session = m_classReq.getSession(); VD_Bean VDBean = (VD_Bean)session.getAttribute("oldVDBean"); //clear related the session attributes clearBuildingBlockSessionAttributes(m_classReq, m_classRes); String sVDID = VDBean.getVD_VD_IDSEQ(); Vector vList = new Vector(); //get VD's attributes from the database again GetACSearch serAC = new GetACSearch(m_classReq, m_classRes, this); if (sVDID != null && !sVDID.equals("")) serAC.doVDSearch(sVDID, "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", 0, "", "", "", "", "", "", "", "",vList); //forward editVD page with this bean if (vList.size() > 0) { VDBean = (VD_Bean)vList.elementAt(0); VDBean = serAC.getVDAttributes(VDBean, orgAct, menuAct); } else { VDBean = new VD_Bean(); VDBean.setVD_ASL_NAME("DRAFT NEW"); VDBean.setAC_PREF_NAME_TYPE("SYS"); } VD_Bean pgBean = new VD_Bean(); DataManager.setAttribute(session, PVForm.SESSION_SELECT_VD, pgBean.cloneVD_Bean(VDBean)); } catch (Exception e) { logger.error("ERROR - ", e); } return "/CreateVDPage.jsp"; } public void doOpenViewPage() throws Exception { //System.out.println("I am here open view page"); HttpSession session = m_classReq.getSession(); String acID = (String) m_classReq.getAttribute("acIdseq"); if (acID.equals("")) acID = m_classReq.getParameter("idseq"); Vector<VD_Bean> vList = new Vector<VD_Bean>(); // get DE's attributes from the database again GetACSearch serAC = new GetACSearch(m_classReq, m_classRes, this); if (acID != null && !acID.equals("")) { serAC.doVDSearch(acID, "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", 0, "", "", "", "", "", "", "", "", vList); } if (vList.size() > 0) // get all attributes { VD_Bean VDBean = (VD_Bean) vList.elementAt(0); VDBean = serAC.getVDAttributes(VDBean, "openView", "viewVD"); DataManager.setAttribute(session, "TabFocus", "VD"); m_classReq.setAttribute("viewVDId", VDBean.getIDSEQ()); String viewVD = "viewVD" + VDBean.getIDSEQ(); DataManager.setAttribute(session, viewVD, VDBean); String title = "CDE Curation View VD "+VDBean.getVD_LONG_NAME()+ " [" + VDBean.getVD_VD_ID() + "v" + VDBean.getVD_VERSION() +"]"; m_classReq.setAttribute("title", title); m_classReq.setAttribute("publicID", VDBean.getVD_VD_ID()); m_classReq.setAttribute("version", VDBean.getVD_VERSION()); m_classReq.setAttribute("IncludeViewPage", "EditVD.jsp") ; } } public void doViewPageTab() throws Exception{ String tab = m_classReq.getParameter("vdpvstab"); String from = m_classReq.getParameter("from"); String id = m_classReq.getParameter("id"); String viewVD = "viewVD" + id; HttpSession session = m_classReq.getSession(); VD_Bean VDBean = (VD_Bean)session.getAttribute(viewVD); String publicId = VDBean.getVD_VD_ID(); String version = VDBean.getVD_VERSION(); m_classReq.setAttribute("viewVDId", id); String title = "CDE Curation View VD "+VDBean.getVD_LONG_NAME()+ " [" + VDBean.getVD_VD_ID() + "v" + VDBean.getVD_VERSION() +"]"; m_classReq.setAttribute("title", title); m_classReq.setAttribute("publicID", VDBean.getVD_VD_ID()); m_classReq.setAttribute("version", VDBean.getVD_VERSION()); + DataManager.setAttribute(session, "VDAction", ""); if (from.equals("edit")){ m_classReq.getSession().setAttribute("displayErrorMessage", "Yes"); } if (tab != null && tab.equals("PV")) { DataManager.setAttribute(session, "TabFocus", "PV"); m_classReq.setAttribute("IncludeViewPage", "PermissibleValue.jsp") ; ForwardJSP(m_classReq, m_classRes, "/ViewPage.jsp"); }else{ DataManager.setAttribute(session, "TabFocus", "VD"); m_classReq.setAttribute("IncludeViewPage", "EditVD.jsp") ; ForwardJSP(m_classReq, m_classRes, "/ViewPage.jsp"); } } private VD_Bean updateRepAttribues(Vector vRep, VD_Bean vdBean) { HttpSession session = m_classReq.getSession(); // add rep primary attributes to the vd bean EVS_Bean pBean =(EVS_Bean)vRep.get(0); vdBean.setVD_REP_NAME_PRIMARY(pBean.getLONG_NAME()); vdBean.setVD_REP_CONCEPT_CODE(pBean.getCONCEPT_IDENTIFIER()); vdBean.setVD_REP_EVS_CUI_ORIGEN(pBean.getEVS_DATABASE()); vdBean.setVD_REP_IDSEQ(pBean.getIDSEQ()); DataManager.setAttribute(session, "m_REP", pBean); // update qualifier vectors vdBean.setVD_REP_QUALIFIER_NAMES(null); vdBean.setVD_REP_QUALIFIER_CODES(null); vdBean.setVD_REP_QUALIFIER_DB(null); for (int i=1; i<vRep.size();i++){ EVS_Bean eBean =(EVS_Bean)vRep.get(i); // add rep qualifiers to the vector Vector<String> vRepQualifierNames = vdBean.getVD_REP_QUALIFIER_NAMES(); if (vRepQualifierNames == null) vRepQualifierNames = new Vector<String>(); vRepQualifierNames.addElement(eBean.getLONG_NAME()); Vector<String> vRepQualifierCodes = vdBean.getVD_REP_QUALIFIER_CODES(); if (vRepQualifierCodes == null) vRepQualifierCodes = new Vector<String>(); vRepQualifierCodes.addElement(eBean.getCONCEPT_IDENTIFIER()); Vector<String> vRepQualifierDB = vdBean.getVD_REP_QUALIFIER_DB(); if (vRepQualifierDB == null) vRepQualifierDB = new Vector<String>(); vRepQualifierDB.addElement(eBean.getEVS_DATABASE()); vdBean.setVD_REP_QUALIFIER_NAMES(vRepQualifierNames); vdBean.setVD_REP_QUALIFIER_CODES(vRepQualifierCodes); vdBean.setVD_REP_QUALIFIER_DB(vRepQualifierDB); // if(vRepQualifierNames.size()>0) // vdBean.setVD_REP_QUAL((String)vRepQualifierNames.elementAt(0)); DataManager.setAttribute(session, "vRepQResult", null); DataManager.setAttribute(session, "m_REPQ", eBean); } return vdBean; } }
true
true
private void doValidateVD() throws Exception { HttpSession session = m_classReq.getSession(); String sAction = (String) m_classReq.getParameter("pageAction"); if (sAction == null) sAction = ""; // do below for versioning to check whether these two have changed VD_Bean m_VD = (VD_Bean) session.getAttribute("m_VD"); // new VD_Bean(); EVS_Bean m_OC = new EVS_Bean(); EVS_Bean m_PC = new EVS_Bean(); EVS_Bean m_REP = new EVS_Bean(); EVS_Bean m_OCQ = new EVS_Bean(); EVS_Bean m_PCQ = new EVS_Bean(); EVS_Bean m_REPQ = new EVS_Bean(); GetACService getAC = new GetACService(m_classReq, m_classRes, this); DataManager.setAttribute(session, "VDPageAction", "validate"); // store the page action in attribute m_setAC.setVDValueFromPage(m_classReq, m_classRes, m_VD); m_OC = (EVS_Bean) session.getAttribute("m_OC"); m_PC = (EVS_Bean) session.getAttribute("m_PC"); m_OCQ = (EVS_Bean) session.getAttribute("m_OCQ"); m_PCQ = (EVS_Bean) session.getAttribute("m_PCQ"); m_REP = (EVS_Bean) session.getAttribute("m_REP"); m_REPQ = (EVS_Bean) session.getAttribute("m_REPQ"); m_setAC.setValidatePageValuesVD(m_classReq, m_classRes, m_VD, m_OC, m_PC, m_REP, m_OCQ, m_PCQ, m_REPQ, getAC); DataManager.setAttribute(session, "m_VD", m_VD); /* * if(sAction.equals("Enum") || sAction.equals("NonEnum") || sAction.equals("EnumByRef")) ForwardJSP(m_classReq, m_classRes, * "/CreateVDPage.jsp"); else if (!sAction.equals("vdpvstab") && !sAction.equals("vddetailstab")) * ForwardJSP(req, res, "/ValidateVDPage.jsp"); */} // end of doValidateVD /** * The doSetVDPage method gets the values from page the user filled out, Calls 'setAC.setVDValueFromPage' to set the * data from the page to the bean. Stores 'm_VD' bean in session. Forwards the page 'CreateVDPage.jsp' with * validation vector to display. * * @param sOrigin * origin where it is called from * * @throws Exception */ private void doSetVDPage(String sOrigin) throws Exception { try { HttpSession session = m_classReq.getSession(); String sAction = (String) m_classReq.getParameter("pageAction"); if (sAction == null) sAction = ""; // do below for versioning to check whether these two have changed VD_Bean vdBean = (VD_Bean) session.getAttribute("m_VD"); // new VD_Bean(); m_setAC.setVDValueFromPage(m_classReq, m_classRes, vdBean); // check if pvs are used in the form when type is changed to non enumerated. if (!sAction.equals("Enum")) { // get vdid from the bean // VD_Bean vdBean = (VD_Bean)session.getAttribute("m_VD"); String sVDid = vdBean.getVD_VD_IDSEQ(); boolean isExist = false; if (sOrigin.equals("Edit")) { // call function to check if relationship exists SetACService setAC = new SetACService(this); isExist = setAC.checkPVQCExists(m_classReq, m_classRes, sVDid, ""); if (isExist) { String sMsg = "Unable to change Value Domain type to Non-Enumerated " + "because one or more Permissible Values are being used in a Case Report Form. \\n" + "Please create a new version of this Value Domain to change the type to Non-Enumerated."; DataManager.setAttribute(session, Session_Data.SESSION_STATUS_MESSAGE, sMsg); vdBean.setVD_TYPE_FLAG("E"); DataManager.setAttribute(session, "m_VD", vdBean); } } // mark all the pvs as deleted to remove them while submitting. if (!isExist) { Vector<PV_Bean> vVDPVs = vdBean.getVD_PV_List(); // (Vector)session.getAttribute("VDPVList"); if (vVDPVs != null) { // set each bean as deleted to handle later Vector<PV_Bean> vRemVDPV = vdBean.getRemoved_VDPVList(); if (vRemVDPV == null) vRemVDPV = new Vector<PV_Bean>(); for (int i = 0; i < vVDPVs.size(); i++) { PV_Bean pvBean = (PV_Bean) vVDPVs.elementAt(i); vRemVDPV.addElement(pvBean); } vdBean.setRemoved_VDPVList(vRemVDPV); vdBean.setVD_PV_List(new Vector<PV_Bean>()); } } } else { // remove meta parents since it is not needed for enum types Vector<EVS_Bean> vParentCon = vdBean.getReferenceConceptList(); // (Vector)session.getAttribute("VDParentConcept"); if (vParentCon == null) vParentCon = new Vector<EVS_Bean>(); for (int i = 0; i < vParentCon.size(); i++) { EVS_Bean ePar = (EVS_Bean) vParentCon.elementAt(i); if (ePar == null) ePar = new EVS_Bean(); String parDB = ePar.getEVS_DATABASE(); // System.out.println(i + " setvdpage " + parDB); if (parDB != null && parDB.equals("NCI Metathesaurus")) { ePar.setCON_AC_SUBMIT_ACTION("DEL"); vParentCon.setElementAt(ePar, i); } } vdBean.setReferenceConceptList(vParentCon); DataManager.setAttribute(session, "m_VD", vdBean); // get back pvs associated with this vd VD_Bean oldVD = (VD_Bean) session.getAttribute("oldVDBean"); if (oldVD == null) oldVD = new VD_Bean(); if (oldVD.getVD_TYPE_FLAG() != null && oldVD.getVD_TYPE_FLAG().equals("E")) { if (oldVD.getVD_VD_IDSEQ() != null && !oldVD.getVD_VD_IDSEQ().equals("")) { // String pvAct = "Search"; String sMenu = (String) session.getAttribute(Session_Data.SESSION_MENU_ACTION); // if (sMenu.equals("NewVDTemplate")) // pvAct = "NewUsing"; // Integer pvCount = new Integer(0); vdBean.setVD_PV_List(oldVD.cloneVDPVVector(oldVD.getVD_PV_List())); vdBean.setRemoved_VDPVList(new Vector<PV_Bean>()); GetACSearch serAC = new GetACSearch(m_classReq, m_classRes, this); if (sMenu.equals("Questions")) serAC.getACQuestionValue(vdBean); } } } DataManager.setAttribute(session, "m_VD", vdBean); } catch (Exception e) { logger.error("Error - doSetVDPage " + e.toString(), e); } } // end of doValidateVD /** * makes the vd's system generated name * * @param vd * current vd bean * @param vParent * vector of seelected parents * @return modified vd bean */ public AC_Bean getSystemName(AC_Bean ac, Vector<EVS_Bean> vParent) { VD_Bean vd = (VD_Bean)ac; try { // make the system generated name String sysName = ""; for (int i = vParent.size() - 1; i > -1; i--) { EVS_Bean par = (EVS_Bean) vParent.elementAt(i); String evsDB = par.getEVS_DATABASE(); String subAct = par.getCON_AC_SUBMIT_ACTION(); if (subAct != null && !subAct.equals("DEL") && evsDB != null && !evsDB.equals("Non_EVS")) { // add the concept id to sysname if less than 20 characters if (sysName.equals("") || sysName.length() < 20) sysName += par.getCONCEPT_IDENTIFIER() + ":"; else break; } } // append vd public id and version in the end if (vd.getVD_VD_ID() != null) sysName += vd.getVD_VD_ID(); String sver = vd.getVD_VERSION(); if (sver != null && sver.indexOf(".") < 0) sver += ".0"; if (vd.getVD_VERSION() != null) sysName += "v" + sver; // limit to 30 characters if (sysName.length() > 30) sysName = sysName.substring(sysName.length() - 30); vd.setAC_SYS_PREF_NAME(sysName); // store it in vd bean // make system name preferrd name if sys was selected String selNameType = (String) m_classReq.getParameter("rNameConv"); // get it from the vd bean if null if (selNameType == null) { selNameType = vd.getVD_TYPE_NAME(); } else { // store the keyed in text in the user field for later use. String sPrefName = (String) m_classReq.getParameter("txPreferredName"); if (selNameType != null && selNameType.equals("USER") && sPrefName != null) vd.setAC_USER_PREF_NAME(sPrefName); } if (selNameType != null && selNameType.equals("SYS")) vd.setVD_PREFERRED_NAME(sysName); } catch (Exception e) { this.logger.error("ERROR - getSystemName : " + e.toString(), e); } return vd; } /** * marks the parent and/or its pvs as deleted from the session. * * @param sPVAction * @param vdPage * @throws java.lang.Exception */ private void doRemoveParent(String sPVAction, String vdPage) throws Exception { HttpSession session = m_classReq.getSession(); VD_Bean m_VD = (VD_Bean) session.getAttribute("m_VD"); // new VD_Bean(); Vector<EVS_Bean> vParentCon = m_VD.getReferenceConceptList(); // (Vector)session.getAttribute("VDParentConcept"); if (vParentCon == null) vParentCon = new Vector<EVS_Bean>(); // get the selected parent info from teh request String sParentCC = (String) m_classReq.getParameter("selectedParentConceptCode"); String sParentName = (String) m_classReq.getParameter("selectedParentConceptName"); String sParentDB = (String) m_classReq.getParameter("selectedParentConceptDB"); // for non evs parent compare the long names instead if (sParentName != null && !sParentName.equals("") && sParentDB != null && sParentDB.equals("Non_EVS")) sParentCC = sParentName; if (sParentCC != null) { for (int i = 0; i < vParentCon.size(); i++) { EVS_Bean eBean = (EVS_Bean) vParentCon.elementAt(i); if (eBean == null) eBean = new EVS_Bean(); String thisParent = eBean.getCONCEPT_IDENTIFIER(); if (thisParent == null) thisParent = ""; String thisParentName = eBean.getLONG_NAME(); if (thisParentName == null) thisParentName = ""; String thisParentDB = eBean.getEVS_DATABASE(); if (thisParentDB == null) thisParentDB = ""; // for non evs parent compare the long names instead if (sParentDB != null && sParentDB.equals("Non_EVS")) thisParent = thisParentName; // look for the matched parent from the vector to remove if (sParentCC.equals(thisParent)) { @SuppressWarnings("unused") String strHTML = ""; EVSMasterTree tree = new EVSMasterTree(m_classReq, thisParentDB, this); strHTML = tree.refreshTree(thisParentName, "false"); strHTML = tree.refreshTree("parentTree" + thisParentName, "false"); if (sPVAction.equals("removePVandParent")) { Vector<PV_Bean> vVDPVList = m_VD.getVD_PV_List(); // (Vector)session.getAttribute("VDPVList"); if (vVDPVList == null) vVDPVList = new Vector<PV_Bean>(); // loop through the vector of pvs to get matched parent for (int j = 0; j < vVDPVList.size(); j++) { PV_Bean pvBean = (PV_Bean) vVDPVList.elementAt(j); if (pvBean == null) pvBean = new PV_Bean(); EVS_Bean pvParent = (EVS_Bean) pvBean.getPARENT_CONCEPT(); if (pvParent == null) pvParent = new EVS_Bean(); String pvParCon = pvParent.getCONCEPT_IDENTIFIER(); // match the parent concept with the pv's parent concept if (thisParent.equals(pvParCon)) { pvBean.setVP_SUBMIT_ACTION("DEL"); // mark the vp as deleted // String pvID = pvBean.getPV_PV_IDSEQ(); vVDPVList.setElementAt(pvBean, j); } } m_VD.setVD_PV_List(vVDPVList); // DataManager.setAttribute(session, "VDPVList", vVDPVList); } // mark the parent as delected and leave eBean.setCON_AC_SUBMIT_ACTION("DEL"); vParentCon.setElementAt(eBean, i); break; } } } // DataManager.setAttribute(session, "VDParentConcept", vParentCon); m_VD.setReferenceConceptList(vParentCon); // make sure all other changes are stored back in vd m_setAC.setVDValueFromPage(m_classReq, m_classRes, m_VD); // make vd's system preferred name m_VD = (VD_Bean) this.getSystemName(m_VD, vParentCon); DataManager.setAttribute(session, "m_VD", m_VD); // make the selected parent in hte session empty DataManager.setAttribute(session, "SelectedParentName", ""); DataManager.setAttribute(session, "SelectedParentCC", ""); DataManager.setAttribute(session, "SelectedParentDB", ""); DataManager.setAttribute(session, "SelectedParentMetaSource", ""); // forward teh page according to vdPage if (vdPage.equals("editVD")) ForwardJSP(m_classReq, m_classRes, "/EditVDPage.jsp"); else ForwardJSP(m_classReq, m_classRes, "/CreateVDPage.jsp"); } /** * splits the vd rep term from cadsr into individual concepts * * @param sComp * name of the searched component * @param m_Bean * selected EVS bean * @param nameAction * string naming action * */ private void splitIntoConceptsVD(String sComp, EVS_Bean m_Bean,String nameAction) { try { HttpSession session = m_classReq.getSession(); // String sSelRow = ""; VD_Bean m_VD = (VD_Bean) session.getAttribute("m_VD"); if (m_VD == null) m_VD = new VD_Bean(); m_setAC.setVDValueFromPage(m_classReq, m_classRes, m_VD); Vector vRepTerm = (Vector) session.getAttribute("vRepTerm"); if (vRepTerm == null) vRepTerm = new Vector(); String sCondr = m_Bean.getCONDR_IDSEQ(); String sLongName = m_Bean.getLONG_NAME(); String sIDSEQ = m_Bean.getIDSEQ(); if (sComp.equals("RepTerm") || sComp.equals("RepQualifier")) { m_VD.setVD_REP_TERM(sLongName); m_VD.setVD_REP_IDSEQ(sIDSEQ); } // String sRepTerm = m_VD.getVD_REP_TERM(); if (sCondr != null && !sCondr.equals("")) { GetACService getAC = new GetACService(m_classReq, m_classRes, this); Vector vCon = getAC.getAC_Concepts(sCondr, null, true); if (vCon != null && vCon.size() > 0) { for (int j = 0; j < vCon.size(); j++) { EVS_Bean bean = new EVS_Bean(); bean = (EVS_Bean) vCon.elementAt(j); if (bean != null) { if (j == 0) // Primary Concept m_VD = this.addRepConcepts(nameAction, m_VD, bean, "Primary"); else // Secondary Concepts m_VD = this.addRepConcepts(nameAction, m_VD, bean, "Qualifier"); } } } } } catch (Exception e) { this.logger.error("ERROR - splitintoConceptVD : " + e.toString(), e); } } /** * this method is used to create preferred name for VD names of all three types will be stored in the bean for later * use if type is changed, it populates name according to type selected. * * @param newBean * new EVS bean to append the name to * @param nameAct * string new name or append name * @param pageVD * current vd bean * @return VD bean */ public AC_Bean getACNames(EVS_Bean newBean, String nameAct, AC_Bean pageAC) { HttpSession session = m_classReq.getSession(); VD_Bean pageVD = (VD_Bean)pageAC; if (pageVD == null) pageVD = (VD_Bean) session.getAttribute("m_VD"); // get vd object class and property names String sLongName = ""; String sPrefName = ""; String sAbbName = ""; String sDef = ""; // get the existing one if not restructuring the name but appending it if (newBean != null) { sLongName = pageVD.getVD_LONG_NAME(); if (sLongName == null) sLongName = ""; sDef = pageVD.getVD_PREFERRED_DEFINITION(); if (sDef == null) sDef = ""; } // get the typed text on to user name String selNameType = ""; if (nameAct.equals("Search") || nameAct.equals("Remove")) { selNameType = (String) m_classReq.getParameter("rNameConv"); sPrefName = (String) m_classReq.getParameter("txPreferredName"); if (selNameType != null && selNameType.equals("USER") && sPrefName != null) pageVD.setAC_USER_PREF_NAME(sPrefName); } // get the object class into the long name and abbr name String sObjClass = pageVD.getVD_OBJ_CLASS(); if (sObjClass == null) sObjClass = ""; if (!sObjClass.equals("")) { // rearrange it long name if (newBean == null) { if (!sLongName.equals("")) sLongName += " "; // add extra space if not empty sLongName += sObjClass; EVS_Bean mOC = (EVS_Bean) session.getAttribute("m_OC"); if (mOC != null) { if (!sDef.equals("")) sDef += "_"; // add definition sDef += mOC.getPREFERRED_DEFINITION(); } } if (!sAbbName.equals("")) sAbbName += "_"; // add underscore if not empty if (sObjClass.length() > 3) sAbbName += sObjClass.substring(0, 4); // truncate to 4 letters else sAbbName = sObjClass; } // get the property into the long name and abbr name String sPropClass = pageVD.getVD_PROP_CLASS(); if (sPropClass == null) sPropClass = ""; if (!sPropClass.equals("")) { // rearrange it long name if (newBean == null) { if (!sLongName.equals("")) sLongName += " "; // add extra space if not empty sLongName += sPropClass; EVS_Bean mPC = (EVS_Bean) session.getAttribute("m_PC"); if (mPC != null) { if (!sDef.equals("")) sDef += "_"; // add definition sDef += mPC.getPREFERRED_DEFINITION(); } } if (!sAbbName.equals("")) sAbbName += "_"; // add underscore if not empty if (sPropClass.length() > 3) sAbbName += sPropClass.substring(0, 4); // truncate to 4 letters else sAbbName += sPropClass; } Vector vRep = (Vector) session.getAttribute("vRepTerm"); if (vRep == null) vRep = new Vector(); // add the qualifiers first for (int i = 1; vRep.size() > i; i++) { EVS_Bean eCon = (EVS_Bean) vRep.elementAt(i); if (eCon == null) eCon = new EVS_Bean(); String conName = eCon.getLONG_NAME(); if (conName == null) conName = ""; if (!conName.equals("")) { // rearrange it long name and definition if (newBean == null) { if (!sLongName.equals("")) sLongName += " "; sLongName += conName; if (!sDef.equals("")) sDef += "_"; // add definition sDef += eCon.getPREFERRED_DEFINITION(); } if (!sAbbName.equals("")) sAbbName += "_"; if (conName.length() > 3) sAbbName += conName.substring(0, 4); // truncate to four letters else sAbbName += conName; } } // add the primary if (vRep != null && vRep.size() > 0) { EVS_Bean eCon = (EVS_Bean) vRep.elementAt(0); if (eCon == null) eCon = new EVS_Bean(); String sPrimary = eCon.getLONG_NAME(); if (sPrimary == null) sPrimary = ""; if (!sPrimary.equals("")) { // rearrange it only long name and definition if (newBean == null) { if (!sLongName.equals("")) sLongName += " "; sLongName += sPrimary; if (!sDef.equals("")) sDef += "_"; // add definition sDef += eCon.getPREFERRED_DEFINITION(); } if (!sAbbName.equals("")) sAbbName += "_"; if (sPrimary.length() > 3) sAbbName += sPrimary.substring(0, 4); // truncate to four letters else sAbbName += sPrimary; } } // truncate to 30 characters if (sAbbName != null && sAbbName.length() > 30) sAbbName = sAbbName.substring(0, 30); // add the abbr name to vd bean and page is selected pageVD.setAC_ABBR_PREF_NAME(sAbbName); // make abbr name name preferrd name if sys was selected if (selNameType != null && selNameType.equals("ABBR")) pageVD.setVD_PREFERRED_NAME(sAbbName); if (newBean != null) // appending to the existing; { String sSelectName = newBean.getLONG_NAME(); if (!sLongName.equals("")) sLongName += " "; sLongName += sSelectName; if (!sDef.equals("")) sDef += "_"; // add definition sDef += newBean.getPREFERRED_DEFINITION(); } // store the long names, definition, and usr name in vd bean if searched if (nameAct.equals("Search")) { pageVD.setVD_LONG_NAME(sLongName); pageVD.setVD_PREFERRED_DEFINITION(sDef); pageVD.setVDNAME_CHANGED(true); } return pageVD; } /** * * @param nameAction * stirng name action * */ private void doVDUseSelection(String nameAction) { try { HttpSession session = m_classReq.getSession(); String sSelRow = ""; // InsACService insAC = new InsACService(req, res, this); VD_Bean m_VD = (VD_Bean) session.getAttribute("m_VD"); if (m_VD == null) m_VD = new VD_Bean(); m_setAC.setVDValueFromPage(m_classReq, m_classRes, m_VD); Vector<EVS_Bean> vRepTerm = (Vector) session.getAttribute("vRepTerm"); if (vRepTerm == null) vRepTerm = new Vector<EVS_Bean>(); Vector vAC = new Vector(); ; EVS_Bean m_REP = new EVS_Bean(); String sComp = (String) m_classReq.getParameter("sCompBlocks"); // get rep term components if (sComp.equals("RepTerm") || sComp.equals("RepQualifier")) { sSelRow = (String) m_classReq.getParameter("selRepRow"); // vAC = (Vector)session.getAttribute("vRepResult"); vAC = (Vector) session.getAttribute("vACSearch"); if (vAC == null) vAC = new Vector(); if (sSelRow != null && !sSelRow.equals("")) { String sObjRow = sSelRow.substring(2); Integer intObjRow = new Integer(sObjRow); int intObjRow2 = intObjRow.intValue(); if (vAC.size() > intObjRow2 - 1) m_REP = (EVS_Bean) vAC.elementAt(intObjRow2); // get name value pari String sNVP = (String) m_classReq.getParameter("nvpConcept"); if (sNVP != null && !sNVP.equals("")) { m_REP.setNVP_CONCEPT_VALUE(sNVP); String sName = m_REP.getLONG_NAME(); m_REP.setLONG_NAME(sName + "::" + sNVP); m_REP.setPREFERRED_DEFINITION(m_REP.getPREFERRED_DEFINITION() + "::" + sNVP); } //System.out.println(sNVP + sComp + m_REP.getLONG_NAME()); } else { storeStatusMsg("Unable to get the selected row from the Rep Term search results."); return; } // send it back if unable to obtion the concept if (m_REP == null || m_REP.getLONG_NAME() == null) { storeStatusMsg("Unable to obtain concept from the selected row of the " + sComp + " search results.\\n" + "Please try again."); return; } // handle the primary search if (sComp.equals("RepTerm")) { if (m_REP.getEVS_DATABASE().equals("caDSR")) { // split it if rep term, add concept class to the list if evs id exists if (m_REP.getCONDR_IDSEQ() == null || m_REP.getCONDR_IDSEQ().equals("")) { if (m_REP.getCONCEPT_IDENTIFIER() == null || m_REP.getCONCEPT_IDENTIFIER().equals("")) { storeStatusMsg("This Rep Term is not associated to a concept, so the data is suspect. \\n" + "Please choose another Rep Term."); } else m_VD = this.addRepConcepts(nameAction, m_VD, m_REP, "Primary"); } else splitIntoConceptsVD(sComp, m_REP, nameAction); } else m_VD = this.addRepConcepts(nameAction, m_VD, m_REP, "Primary"); } else if (sComp.equals("RepQualifier")) { // Do this to reserve zero position in vector for primary concept if (vRepTerm.size() < 1) { EVS_Bean OCBean = new EVS_Bean(); vRepTerm.addElement(OCBean); DataManager.setAttribute(session, "vRepTerm", vRepTerm); } m_VD = this.addRepConcepts(nameAction, m_VD, m_REP, "Qualifier"); } } else { EVS_Bean eBean = this.getEVSSelRow(m_classReq); if (eBean != null && eBean.getLONG_NAME() != null) { /* if (sComp.equals("VDObjectClass")) { m_VD.setVD_OBJ_CLASS(eBean.getLONG_NAME()); DataManager.setAttribute(session, "m_OC", eBean); } else if (sComp.equals("VDPropertyClass")) { m_VD.setVD_PROP_CLASS(eBean.getLONG_NAME()); DataManager.setAttribute(session, "m_PC", eBean); } */ if (nameAction.equals("appendName")) m_VD = (VD_Bean) this.getACNames(eBean, "Search", m_VD); } } vRepTerm = (Vector) session.getAttribute("vRepTerm"); if (vRepTerm != null && vRepTerm.size() > 0){ vRepTerm = this.getMatchingThesarusconcept(vRepTerm, "Representation Term"); m_VD = this.updateRepAttribues(vRepTerm, m_VD); } DataManager.setAttribute(session, "vRepTerm", vRepTerm); // rebuild new name if not appending EVS_Bean nullEVS = null; if (nameAction.equals("newName")) m_VD = (VD_Bean) this.getACNames(nullEVS, "Search", m_VD); else if (nameAction.equals("blockName")) m_VD = (VD_Bean) this.getACNames(nullEVS, "blockName", m_VD); DataManager.setAttribute(session, "m_VD", m_VD); } catch (Exception e) { this.logger.error("ERROR - doVDUseSelection : " + e.toString(), e); } } // end of doVDUseSelection /** * adds the selected concept to the vector of concepts for property * * @param nameAction * String naming action * @param vdBean * selected DEC_Bean * @param eBean * selected EVS_Bean * @param repType * String property type (primary or qualifier) * @return DEC_Bean * @throws Exception */ @SuppressWarnings("unchecked") private VD_Bean addRepConcepts(String nameAction, VD_Bean vdBean, EVS_Bean eBean, String repType) throws Exception { HttpSession session = m_classReq.getSession(); // add the concept bean to the OC vector and store it in the vector Vector<EVS_Bean> vRepTerm = (Vector) session.getAttribute("vRepTerm"); if (vRepTerm == null) vRepTerm = new Vector<EVS_Bean>(); // get the evs user bean EVS_UserBean eUser = (EVS_UserBean) this.sessionData.EvsUsrBean; // (EVS_UserBean)session.getAttribute(EVSSearch.EVS_USER_BEAN_ARG); // //("EvsUserBean"); if (eUser == null) eUser = new EVS_UserBean(); eBean.setCON_AC_SUBMIT_ACTION("INS"); eBean.setCONTE_IDSEQ(vdBean.getVD_CONTE_IDSEQ()); String eDB = eBean.getEVS_DATABASE(); if (eDB != null && eBean.getEVS_ORIGIN() != null && eDB.equalsIgnoreCase("caDSR")) { eDB = eBean.getVocabAttr(eUser, eBean.getEVS_ORIGIN(), EVSSearch.VOCAB_NAME, EVSSearch.VOCAB_DBORIGIN); // "vocabName", // "vocabDBOrigin"); if (eDB.equals(EVSSearch.META_VALUE)) // "MetaValue")) eDB = eBean.getEVS_ORIGIN(); eBean.setEVS_DATABASE(eDB); // eBean.getEVS_ORIGIN()); } // System.out.println(eBean.getEVS_ORIGIN() + " before thes concept for REP " + eDB); // EVSSearch evs = new EVSSearch(m_classReq, m_classRes, this); //eBean = evs.getThesaurusConcept(eBean); // add to the vector and store it in the session, reset if primary and alredy existed, add otehrwise if (repType.equals("Primary") && vRepTerm.size() > 0) vRepTerm.setElementAt(eBean, 0); else vRepTerm.addElement(eBean); DataManager.setAttribute(session, "vRepTerm", vRepTerm); DataManager.setAttribute(session, "newRepTerm", "true"); // DataManager.setAttribute(session, "selRepQRow", sSelRow); // add to name if appending if (nameAction.equals("appendName")) vdBean = (VD_Bean) this.getACNames(eBean, "Search", vdBean); return vdBean; } // end addRepConcepts /** * The doValidateVD method gets the values from page the user filled out, validates the input, then forwards results * to the Validate page Called from 'doCreateVDActions', 'doSubmitVD' method. Calls 'setAC.setVDValueFromPage' to * set the data from the page to the bean. Calls 'setAC.setValidatePageValuesVD' to validate the data. Stores 'm_VD' * bean in session. Forwards the page 'ValidateVDPage.jsp' with validation vector to display. * * @throws Exception */ private void doValidateVDBlockEdit() throws Exception { HttpSession session = m_classReq.getSession(); VD_Bean m_VD = (VD_Bean) session.getAttribute("m_VD"); // new VD_Bean(); DataManager.setAttribute(session, "VDPageAction", "validate"); // store the page action in attribute m_setAC.setVDValueFromPage(m_classReq, m_classRes, m_VD); DataManager.setAttribute(session, "m_VD", m_VD); m_setAC.setValidateBlockEdit(m_classReq, m_classRes, "ValueDomain"); DataManager.setAttribute(session, "VDEditAction", "VDBlockEdit"); ForwardJSP(m_classReq, m_classRes, "/ValidateVDPage.jsp"); } // end of doValidateVD /** * The doInsertVD method to insert or update record in the database. Called from 'service' method where reqType is * 'validateVDFromForm'. Retrieves the session bean m_VD. if the action is reEditVD forwards the page back to Edit * or create pages. * * Otherwise, calls 'doUpdateVDAction' for editing the vd. calls 'doInsertVDfromDEAction' for creating the vd from * DE page. calls 'doInsertVDfromMenuAction' for creating the vd from menu . * * @throws Exception */ private void doInsertVD() throws Exception { HttpSession session = m_classReq.getSession(); // make sure that status message is empty DataManager.setAttribute(session, Session_Data.SESSION_STATUS_MESSAGE, ""); Vector vStat = new Vector(); DataManager.setAttribute(session, "vStatMsg", vStat); String sVDAction = (String) session.getAttribute("VDAction"); if (sVDAction == null) sVDAction = ""; String sVDEditAction = (String) session.getAttribute("VDEditAction"); if (sVDEditAction == null) sVDEditAction = ""; String sAction = (String) m_classReq.getParameter("ValidateVDPageAction"); // String sMenuAction = (String) session.getAttribute(Session_Data.SESSION_MENU_ACTION); // String sButtonPressed = (String) session.getAttribute("LastMenuButtonPressed"); String sOriginAction = (String) session.getAttribute("originAction"); if (sAction == null) sAction = "submitting"; // for direct submit without validating // String spageAction = (String) m_classReq.getParameter("pageAction"); if (sAction != null) { // goes back to create/edit pages from validation page if (sAction.equals("reEditVD")) { String vdfocus = (String) session.getAttribute("TabFocus"); if (vdfocus != null && vdfocus.equals("PV")) ForwardJSP(m_classReq, m_classRes, "/PermissibleValue.jsp"); else { if (sVDAction.equals("EditVD") || sVDAction.equals("BlockEdit")) ForwardJSP(m_classReq, m_classRes, "/EditVDPage.jsp"); else ForwardJSP(m_classReq, m_classRes, "/CreateVDPage.jsp"); } } else { // edit the existing vd if (sVDAction.equals("NewVD") && sOriginAction.equals("NewVDFromMenu")) doInsertVDfromMenuAction(); else if (sVDAction.equals("EditVD") && !sOriginAction.equals("BlockEditVD")) doUpdateVDAction(); else if (sVDEditAction.equals("VDBlockEdit")) doUpdateVDActionBE(); // if create new vd from create/edit DE page. else if (sOriginAction.equals("CreateNewVDfromCreateDE") || sOriginAction.equals("CreateNewVDfromEditDE")) doInsertVDfromDEAction(sOriginAction); // from the menu AND template/ version else { doInsertVDfromMenuAction(); } } } } // end of doInsertVD /** * update record in the database and display the result. Called from 'doInsertVD' method when the aciton is editing. * Retrieves the session bean m_VD. calls 'insAC.setVD' to update the database. updates the DEbean and sends back to * EditDE page if origin is form DEpage otherwise calls 'serAC.refreshData' to get the refreshed search result * forwards the page back to search page with refreshed list after updating. * * If ret is not null stores the statusMessage as error message in session and forwards the page back to * 'EditVDPage.jsp' for Edit. * * @throws Exception */ private void doUpdateVDAction() throws Exception { HttpSession session = m_classReq.getSession(); VD_Bean VDBean = (VD_Bean) session.getAttribute("m_VD"); VD_Bean oldVDBean = (VD_Bean) session.getAttribute("oldVDBean"); // String sMenu = (String) session.getAttribute(Session_Data.SESSION_MENU_ACTION); InsACService insAC = new InsACService(m_classReq, m_classRes, this); doInsertVDBlocks(null); // udpate the status message with DE name and ID storeStatusMsg("Value Domain Name : " + VDBean.getVD_LONG_NAME()); storeStatusMsg("Public ID : " + VDBean.getVD_VD_ID()); // call stored procedure to update attributes String ret = insAC.setVD("UPD", VDBean, "Edit", oldVDBean); // forward to search page with refreshed list after successful update if ((ret == null) || ret.equals("")) { this.clearCreateSessionAttributes(m_classReq, m_classRes); // clear some session attributes String sOriginAction = (String) session.getAttribute("originAction"); GetACSearch serAC = new GetACSearch(m_classReq, m_classRes, this); // forward page back to EditDE if (sOriginAction.equals("editVDfromDE") || sOriginAction.equals("EditDE")) { DE_Bean DEBean = (DE_Bean) session.getAttribute("m_DE"); if (DEBean != null) { DEBean.setDE_VD_IDSEQ(VDBean.getVD_VD_IDSEQ()); DEBean.setDE_VD_PREFERRED_NAME(VDBean.getVD_PREFERRED_NAME()); DEBean.setDE_VD_NAME(VDBean.getVD_LONG_NAME()); // reset the attributes DataManager.setAttribute(session, "originAction", ""); // add DEC Bean into DE BEan DEBean.setDE_VD_Bean(VDBean); DataManager.setAttribute(session, "m_DE", DEBean); CurationServlet deServ = (DataElementServlet) getACServlet("DataElement"); DEBean = (DE_Bean) deServ.getACNames("new", "editVD", DEBean); } ForwardJSP(m_classReq, m_classRes, "/EditDEPage.jsp"); } // go to search page with refreshed list else { VDBean.setVD_ALIAS_NAME(VDBean.getVD_PREFERRED_NAME()); // VDBean.setVD_TYPE_NAME("PRIMARY"); DataManager.setAttribute(session, Session_Data.SESSION_MENU_ACTION, "editVD"); String oldID = VDBean.getVD_VD_IDSEQ(); serAC.refreshData(m_classReq, m_classRes, null, null, VDBean, null, "Edit", oldID); ForwardJSP(m_classReq, m_classRes, "/SearchResultsPage.jsp"); } } // goes back to edit page if error occurs else { DataManager.setAttribute(session, "VDPageAction", "nothing"); ForwardJSP(m_classReq, m_classRes, "/EditVDPage.jsp"); } } /** * update record in the database and display the result. Called from 'doInsertVD' method when the aciton is editing. * Retrieves the session bean m_VD. calls 'insAC.setVD' to update the database. updates the DEbean and sends back to * EditDE page if origin is form DEpage otherwise calls 'serAC.refreshData' to get the refreshed search result * forwards the page back to search page with refreshed list after updating. * * If ret is not null stores the statusMessage as error message in session and forwards the page back to * 'EditVDPage.jsp' for Edit. * * @throws Exception */ private void doUpdateVDActionBE() throws Exception { HttpSession session = m_classReq.getSession(); VD_Bean VDBean = (VD_Bean) session.getAttribute("m_VD"); // validated edited m_VD boolean isRefreshed = false; String ret = ":"; InsACService insAC = new InsACService(m_classReq, m_classRes, this); GetACSearch serAC = new GetACSearch(m_classReq, m_classRes, this); GetACService getAC = new GetACService(m_classReq, m_classRes, this); // Vector vStatMsg = new Vector(); String sNewRep = (String) session.getAttribute("newRepTerm"); if (sNewRep == null) sNewRep = ""; //System.out.println(" new rep " + sNewRep); Vector vBERows = (Vector) session.getAttribute("vBEResult"); int vBESize = vBERows.size(); Integer vBESize2 = new Integer(vBESize); m_classReq.setAttribute("vBESize", vBESize2); String sRep_IDSEQ = ""; if (vBERows.size() > 0) { // Be sure the buffer is loaded when doing versioning. String newVersion = VDBean.getVD_VERSION(); if (newVersion == null) newVersion = ""; boolean newVers = (newVersion.equals("Point") || newVersion.equals("Whole")); if (newVers) { @SuppressWarnings("unchecked") Vector<AC_Bean> tvec = vBERows; AltNamesDefsSession.loadAsNew(this, session, tvec); } for (int i = 0; i < (vBERows.size()); i++) { // String sVD_ID = ""; //out VD_Bean VDBeanSR = new VD_Bean(); VDBeanSR = (VD_Bean) vBERows.elementAt(i); VD_Bean oldVDBean = new VD_Bean(); oldVDBean = oldVDBean.cloneVD_Bean(VDBeanSR); // String oldName = (String) VDBeanSR.getVD_PREFERRED_NAME(); // updates the data from the page into the sr bean InsertEditsIntoVDBeanSR(VDBeanSR, VDBean); // create newly selected rep term if (i == 0 && sNewRep.equals("true")) { doInsertVDBlocks(VDBeanSR); // create it sRep_IDSEQ = VDBeanSR.getVD_REP_IDSEQ(); // get rep idseq if (sRep_IDSEQ == null) sRep_IDSEQ = ""; VDBean.setVD_REP_IDSEQ(sRep_IDSEQ); // add page vd bean String sRep_Condr = VDBeanSR.getVD_REP_CONDR_IDSEQ(); // get rep condr if (sRep_Condr == null) sRep_Condr = ""; VDBean.setVD_REP_CONDR_IDSEQ(sRep_Condr); // add to page vd bean // VDBean.setVD_REP_QUAL(""); } // DataManager.setAttribute(session, "m_VD", VDBeanSR); String oldID = oldVDBean.getVD_VD_IDSEQ(); // udpate the status message with DE name and ID storeStatusMsg("Value Domain Name : " + VDBeanSR.getVD_LONG_NAME()); storeStatusMsg("Public ID : " + VDBeanSR.getVD_VD_ID()); // insert the version if (newVers) // block version { // creates new version first and updates all other attributes String strValid = m_setAC.checkUniqueInContext("Version", "VD", null, null, VDBeanSR, getAC, "version"); if (strValid != null && !strValid.equals("")) ret = "unique constraint"; else ret = insAC.setAC_VERSION(null, null, VDBeanSR, "ValueDomain"); if (ret == null || ret.equals("")) { // PVServlet pvser = new PVServlet(req, res, this); // pvser.searchVersionPV(VDBean, 0, "", ""); // get the right system name for new version String prefName = VDBeanSR.getVD_PREFERRED_NAME(); String vdID = VDBeanSR.getVD_VD_ID(); String newVer = "v" + VDBeanSR.getVD_VERSION(); String oldVer = "v" + oldVDBean.getVD_VERSION(); // replace teh version number if system generated name if (prefName.indexOf(vdID) > 0) { prefName = prefName.replaceFirst(oldVer, newVer); VDBean.setVD_PREFERRED_NAME(prefName); } // keep the value and value count stored String pvValue = VDBeanSR.getVD_Permissible_Value(); Integer pvCount = VDBeanSR.getVD_Permissible_Value_Count(); ret = insAC.setVD("UPD", VDBeanSR, "Version", oldVDBean); if (ret == null || ret.equals("")) { VDBeanSR.setVD_Permissible_Value(pvValue); VDBeanSR.setVD_Permissible_Value_Count(pvCount); serAC.refreshData(m_classReq, m_classRes, null, null, VDBeanSR, null, "Version", oldID); isRefreshed = true; // reset the appened attributes to remove all the checking of the row Vector vCheck = new Vector(); DataManager.setAttribute(session, "CheckList", vCheck); DataManager.setAttribute(session, "AppendAction", "Not Appended"); // resetEVSBeans(req, res); } } // alerady exists else if (ret.indexOf("unique constraint") >= 0) storeStatusMsg("\\t New version " + VDBeanSR.getVD_VERSION() + " already exists in the data base.\\n"); // some other problem else storeStatusMsg("\\t " + ret + " : Unable to create new version " + VDBeanSR.getVD_VERSION() + ".\\n"); } else // block edit { ret = insAC.setVD("UPD", VDBeanSR, "Edit", oldVDBean); // forward to search page with refreshed list after successful update if ((ret == null) || ret.equals("")) { serAC.refreshData(m_classReq, m_classRes, null, null, VDBeanSR, null, "Edit", oldID); isRefreshed = true; } } } AltNamesDefsSession.blockSave(this, session); } // to get the final result vector if not refreshed at all if (!(isRefreshed)) { Vector<String> vResult = new Vector<String>(); serAC.getVDResult(m_classReq, m_classRes, vResult, ""); DataManager.setAttribute(session, "results", vResult); // store the final result in the session DataManager.setAttribute(session, "VDPageAction", "nothing"); } ForwardJSP(m_classReq, m_classRes, "/SearchResultsPage.jsp"); } /** * updates bean the selected VD from the changed values of block edit. * * @param VDBeanSR * selected vd bean from search result * @param vd * VD_Bean of the changed values. * * @throws Exception */ private void InsertEditsIntoVDBeanSR(VD_Bean VDBeanSR, VD_Bean vd) throws Exception { // get all attributes of VDBean, if attribute != "" then set that attribute of VDBeanSR String sDefinition = vd.getVD_PREFERRED_DEFINITION(); if (sDefinition == null) sDefinition = ""; if (!sDefinition.equals("")) VDBeanSR.setVD_PREFERRED_DEFINITION(sDefinition); String sCD_ID = vd.getVD_CD_IDSEQ(); if (sCD_ID == null) sCD_ID = ""; if (!sCD_ID.equals("") && !sCD_ID.equals(null)) VDBeanSR.setVD_CD_IDSEQ(sCD_ID); String sCDName = vd.getVD_CD_NAME(); if (sCDName == null) sCDName = ""; if (!sCDName.equals("") && !sCDName.equals(null)) VDBeanSR.setVD_CD_NAME(sCDName); String sAslName = vd.getVD_ASL_NAME(); if (sAslName == null) sAslName = ""; if (!sAslName.equals("")) VDBeanSR.setVD_ASL_NAME(sAslName); String sDtlName = vd.getVD_DATA_TYPE(); if (sDtlName == null) sDtlName = ""; if (!sDtlName.equals("")) VDBeanSR.setVD_DATA_TYPE(sDtlName); String sMaxLength = vd.getVD_MAX_LENGTH_NUM(); if (sMaxLength == null) sMaxLength = ""; if (!sMaxLength.equals("")) VDBeanSR.setVD_MAX_LENGTH_NUM(sMaxLength); String sFormlName = vd.getVD_FORML_NAME(); // UOM Format if (sFormlName == null) sFormlName = ""; if (!sFormlName.equals("")) VDBeanSR.setVD_FORML_NAME(sFormlName); String sUomlName = vd.getVD_UOML_NAME(); if (sUomlName == null) sUomlName = ""; if (!sUomlName.equals("")) VDBeanSR.setVD_UOML_NAME(sUomlName); String sLowValue = vd.getVD_LOW_VALUE_NUM(); if (sLowValue == null) sLowValue = ""; if (!sLowValue.equals("")) VDBeanSR.setVD_LOW_VALUE_NUM(sLowValue); String sHighValue = vd.getVD_HIGH_VALUE_NUM(); if (sHighValue == null) sHighValue = ""; if (!sHighValue.equals("")) VDBeanSR.setVD_HIGH_VALUE_NUM(sHighValue); String sMinLength = vd.getVD_MIN_LENGTH_NUM(); if (sMinLength == null) sMinLength = ""; if (!sMinLength.equals("")) VDBeanSR.setVD_MIN_LENGTH_NUM(sMinLength); String sDecimalPlace = vd.getVD_DECIMAL_PLACE(); if (sDecimalPlace == null) sDecimalPlace = ""; if (!sDecimalPlace.equals("")) VDBeanSR.setVD_DECIMAL_PLACE(sDecimalPlace); String sBeginDate = vd.getVD_BEGIN_DATE(); if (sBeginDate == null) sBeginDate = ""; if (!sBeginDate.equals("")) VDBeanSR.setVD_BEGIN_DATE(sBeginDate); String sEndDate = vd.getVD_END_DATE(); if (sEndDate == null) sEndDate = ""; if (!sEndDate.equals("")) VDBeanSR.setVD_END_DATE(sEndDate); String sSource = vd.getVD_SOURCE(); if (sSource == null) sSource = ""; if (!sSource.equals("")) VDBeanSR.setVD_SOURCE(sSource); String changeNote = vd.getVD_CHANGE_NOTE(); if (changeNote == null) changeNote = ""; if (!changeNote.equals("")) VDBeanSR.setVD_CHANGE_NOTE(changeNote); // get cs-csi from the page into the DECBean for block edit Vector vAC_CS = vd.getAC_AC_CSI_VECTOR(); if (vAC_CS != null) VDBeanSR.setAC_AC_CSI_VECTOR(vAC_CS); //get the Ref docs from the page into the DEBean for block edit Vector<REF_DOC_Bean> vAC_REF_DOCS = vd.getAC_REF_DOCS(); if(vAC_REF_DOCS!=null){ Vector<REF_DOC_Bean> temp_REF_DOCS = new Vector<REF_DOC_Bean>(); for(REF_DOC_Bean refBean:vAC_REF_DOCS ) { if(refBean.getAC_IDSEQ() == VDBeanSR.getVD_VD_IDSEQ()) { temp_REF_DOCS.add(refBean); } } VDBeanSR.setAC_REF_DOCS(temp_REF_DOCS); } String sRepTerm = vd.getVD_REP_TERM(); if (sRepTerm == null) sRepTerm = ""; if (!sRepTerm.equals("")) VDBeanSR.setVD_REP_TERM(sRepTerm); String sRepCondr = vd.getVD_REP_CONDR_IDSEQ(); if (sRepCondr == null) sRepCondr = ""; if (!sRepCondr.equals("")) VDBeanSR.setVD_REP_CONDR_IDSEQ(sRepCondr); String sREP_IDSEQ = vd.getVD_REP_IDSEQ(); if (sREP_IDSEQ != null && !sREP_IDSEQ.equals("")) VDBeanSR.setVD_REP_IDSEQ(sREP_IDSEQ); /* * String sRepQual = vd.getVD_REP_QUAL(); if (sRepQual == null) sRepQual = ""; if (!sRepQual.equals("")) * VDBeanSR.setVD_REP_QUAL(sRepQual); */ String version = vd.getVD_VERSION(); String lastVersion = (String) VDBeanSR.getVD_VERSION(); int index = -1; String pointStr = "."; String strWhBegNumber = ""; int iWhBegNumber = 0; index = lastVersion.indexOf(pointStr); String strPtBegNumber = lastVersion.substring(0, index); String afterDecimalNumber = lastVersion.substring((index + 1), (index + 2)); if (index == 1) strWhBegNumber = ""; else if (index == 2) { strWhBegNumber = lastVersion.substring(0, index - 1); Integer WhBegNumber = new Integer(strWhBegNumber); iWhBegNumber = WhBegNumber.intValue(); } String strWhEndNumber = ".0"; String beforeDecimalNumber = lastVersion.substring((index - 1), (index)); String sNewVersion = ""; Integer IadNumber = new Integer(0); Integer IbdNumber = new Integer(0); String strIncADNumber = ""; String strIncBDNumber = ""; if (version == null) version = ""; else if (version.equals("Point")) { // Point new version int incrementADNumber = 0; int incrementBDNumber = 0; Integer adNumber = new Integer(afterDecimalNumber); Integer bdNumber = new Integer(strPtBegNumber); int iADNumber = adNumber.intValue(); // after decimal int iBDNumber = bdNumber.intValue(); // before decimal if (iADNumber != 9) { incrementADNumber = iADNumber + 1; IadNumber = new Integer(incrementADNumber); strIncADNumber = IadNumber.toString(); sNewVersion = strPtBegNumber + "." + strIncADNumber; // + strPtEndNumber; } else // adNumber == 9 { incrementADNumber = 0; incrementBDNumber = iBDNumber + 1; IbdNumber = new Integer(incrementBDNumber); strIncBDNumber = IbdNumber.toString(); IadNumber = new Integer(incrementADNumber); strIncADNumber = IadNumber.toString(); sNewVersion = strIncBDNumber + "." + strIncADNumber; // + strPtEndNumber; } VDBeanSR.setVD_VERSION(sNewVersion); } else if (version.equals("Whole")) { // Whole new version Integer bdNumber = new Integer(beforeDecimalNumber); int iBDNumber = bdNumber.intValue(); int incrementBDNumber = iBDNumber + 1; if (iBDNumber != 9) { IbdNumber = new Integer(incrementBDNumber); strIncBDNumber = IbdNumber.toString(); sNewVersion = strWhBegNumber + strIncBDNumber + strWhEndNumber; } else // before decimal number == 9 { int incrementWhBegNumber = iWhBegNumber + 1; Integer IWhBegNumber = new Integer(incrementWhBegNumber); String strIncWhBegNumber = IWhBegNumber.toString(); IbdNumber = new Integer(0); strIncBDNumber = IbdNumber.toString(); sNewVersion = strIncWhBegNumber + strIncBDNumber + strWhEndNumber; } VDBeanSR.setVD_VERSION(sNewVersion); } } /** * creates new record in the database and display the result. Called from 'doInsertVD' method when the aciton is * create new VD from DEPage. Retrieves the session bean m_VD. calls 'insAC.setVD' to update the database. forwards * the page back to create DE page after successful insert. * * If ret is not null stores the statusMessage as error message in session and forwards the page back to * 'createVDPage.jsp' for Edit. * * @param sOrigin * string value from where vd creation action was originated. * * @throws Exception */ private void doInsertVDfromDEAction(String sOrigin) throws Exception { HttpSession session = m_classReq.getSession(); VD_Bean VDBean = (VD_Bean) session.getAttribute("m_VD"); InsACService insAC = new InsACService(m_classReq, m_classRes, this); // GetACSearch serAC = new GetACSearch(req, res, this); // String sMenu = (String) session.getAttribute(Session_Data.SESSION_MENU_ACTION); // insert the building blocks attriubtes before inserting vd doInsertVDBlocks(null); String ret = insAC.setVD("INS", VDBean, "New", null); // updates the de bean with new vd data after successful insert and forwards to create page if ((ret == null) || ret.equals("")) { DE_Bean DEBean = (DE_Bean) session.getAttribute("m_DE"); DEBean.setDE_VD_NAME(VDBean.getVD_LONG_NAME()); DEBean.setDE_VD_IDSEQ(VDBean.getVD_VD_IDSEQ()); // add DEC Bean into DE BEan DEBean.setDE_VD_Bean(VDBean); DataManager.setAttribute(session, "m_DE", DEBean); CurationServlet deServ = (DataElementServlet) getACServlet("DataElement"); DEBean = (DE_Bean) deServ.getACNames("new", "newVD", DEBean); this.clearCreateSessionAttributes(m_classReq, m_classRes); // clear some session attributes if (sOrigin != null && sOrigin.equals("CreateNewVDfromEditDE")) ForwardJSP(m_classReq, m_classRes, "/EditDEPage.jsp"); else ForwardJSP(m_classReq, m_classRes, "/CreateDEPage.jsp"); } // goes back to create vd page if error else { DataManager.setAttribute(session, "VDPageAction", "validate"); ForwardJSP(m_classReq, m_classRes, "/CreateVDPage.jsp"); // send it back to vd page } } /** * to create rep term and qualifier value from EVS into cadsr. Retrieves the session bean * m_VD. calls 'insAC.setDECQualifier' to insert the database. * * @param VDBeanSR * dec attribute bean. * * @throws Exception */ private void doInsertVDBlocks(VD_Bean VDBeanSR) throws Exception { HttpSession session = m_classReq.getSession(); if (VDBeanSR == null) VDBeanSR = (VD_Bean) session.getAttribute("m_VD"); ValidationStatusBean repStatusBean = new ValidationStatusBean(); Vector vRepTerm = (Vector) session.getAttribute("vRepTerm"); InsACService insAC = new InsACService(m_classReq, m_classRes, this); String userName = (String)session.getAttribute("Username"); HashMap<String, String> defaultContext = (HashMap)session.getAttribute("defaultContext"); String conteIdseq= (String)defaultContext.get("idseq"); try { if ((vRepTerm != null && vRepTerm.size() > 0) && (defaultContext != null && defaultContext.size() > 0)) { repStatusBean = insAC.evsBeanCheck(vRepTerm, defaultContext, "", "Representation Term"); } // set Rep if it is null if ((vRepTerm != null && vRepTerm.size() > 0)) { if (!repStatusBean.isEvsBeanExists()) { if (repStatusBean.isCondrExists()) { VDBeanSR.setVD_REP_CONDR_IDSEQ(repStatusBean.getCondrIDSEQ()); // Create Representation Term String repIdseq = insAC.createEvsBean(userName, repStatusBean.getCondrIDSEQ(), conteIdseq, "Representation Term"); if (repIdseq != null && !repIdseq.equals("")) { VDBeanSR.setVD_REP_IDSEQ(repIdseq); } } else { // Create Condr String condrIdseq = insAC.createCondr(vRepTerm, repStatusBean.isAllConceptsExists()); String repIdseq = ""; // Create Representation Term if (condrIdseq != null && !condrIdseq.equals("")) { VDBeanSR.setVD_REP_CONDR_IDSEQ(condrIdseq); repIdseq = insAC.createEvsBean(userName, condrIdseq, conteIdseq, "Representation Term"); } if (repIdseq != null && !repIdseq.equals("")) { VDBeanSR.setVD_REP_IDSEQ(repIdseq); } } } else { if (repStatusBean.isNewVersion()) { if (repStatusBean.getEvsBeanIDSEQ() != null && !repStatusBean.getEvsBeanIDSEQ().equals("")) { String newID = ""; newID = insAC.setOC_PROP_REP_VERSION(repStatusBean.getEvsBeanIDSEQ(), "RepTerm"); if (newID != null && !newID.equals("")) { VDBeanSR.setVD_REP_CONDR_IDSEQ(repStatusBean.getCondrIDSEQ()); VDBeanSR.setVD_REP_IDSEQ(newID); } } }else{ VDBeanSR.setVD_REP_CONDR_IDSEQ(repStatusBean.getCondrIDSEQ()); VDBeanSR.setVD_REP_IDSEQ(repStatusBean.getEvsBeanIDSEQ()); } } } m_classReq.setAttribute("REP_IDSEQ", repStatusBean.getEvsBeanIDSEQ()); } catch (Exception e) { logger.error("ERROR in ValueDoaminServlet-doInsertVDBlocks : " + e.toString(), e); m_classReq.setAttribute("retcode", "Exception"); this.storeStatusMsg("\\t Exception : Unable to update or remove Representation Term."); } DataManager.setAttribute(session, "newRepTerm", ""); } /** * creates new record in the database and display the result. Called from 'doInsertVD' method when the aciton is * create new VD from Menu. Retrieves the session bean m_VD. calls 'insAC.setVD' to update the database. calls * 'serAC.refreshData' to get the refreshed search result for template/version forwards the page back to create VD * page if new VD or back to search page if template or version after successful insert. * * If ret is not null stores the statusMessage as error message in session and forwards the page back to * 'createVDPage.jsp' for Edit. * * @throws Exception */ private void doInsertVDfromMenuAction() throws Exception { HttpSession session = m_classReq.getSession(); VD_Bean VDBean = (VD_Bean) session.getAttribute("m_VD"); InsACService insAC = new InsACService(m_classReq, m_classRes, this); GetACSearch serAC = new GetACSearch(m_classReq, m_classRes, this); String sMenuAction = (String) session.getAttribute(Session_Data.SESSION_MENU_ACTION); VD_Bean oldVDBean = (VD_Bean) session.getAttribute("oldVDBean"); if (oldVDBean == null) oldVDBean = new VD_Bean(); String ret = ""; boolean isUpdateSuccess = true; doInsertVDBlocks(null); if (sMenuAction.equals("NewVDVersion")) { // udpate the status message with DE name and ID storeStatusMsg("Value Domain Name : " + VDBean.getVD_LONG_NAME()); storeStatusMsg("Public ID : " + VDBean.getVD_VD_ID()); // creates new version first ret = insAC.setAC_VERSION(null, null, VDBean, "ValueDomain"); if (ret == null || ret.equals("")) { // get pvs related to this new VD, it was created in VD_Version // TODO serAC.doPVACSearch(VDBean.getVD_VD_IDSEQ(), VDBean.getVD_LONG_NAME(), "Version"); PVServlet pvser = new PVServlet(m_classReq, m_classRes, this); pvser.searchVersionPV(VDBean, 1, "", ""); // update non evs changes Vector<EVS_Bean> vParent = VDBean.getReferenceConceptList(); // (Vector)session.getAttribute("VDParentConcept"); if (vParent != null && vParent.size() > 0) vParent = serAC.getNonEVSParent(vParent, VDBean, "versionSubmit"); // get the right system name for new version; cannot use teh api because parent concept is not updated // yet String prefName = VDBean.getVD_PREFERRED_NAME(); if (prefName == null || prefName.equalsIgnoreCase("(Generated by the System)")) { VDBean = (VD_Bean) this.getSystemName(VDBean, vParent); VDBean.setVD_PREFERRED_NAME(VDBean.getAC_SYS_PREF_NAME()); } // and updates all other attributes ret = insAC.setVD("UPD", VDBean, "Version", oldVDBean); // resetEVSBeans(req, res); if (ret != null && !ret.equals("")) { // add newly created row to searchresults and send it to edit page for update isUpdateSuccess = false; String oldID = oldVDBean.getVD_VD_IDSEQ(); String newID = VDBean.getVD_VD_IDSEQ(); String newVersion = VDBean.getVD_VERSION(); VDBean = VDBean.cloneVD_Bean(oldVDBean); VDBean.setVD_VD_IDSEQ(newID); VDBean.setVD_VERSION(newVersion); VDBean.setVD_ASL_NAME("DRAFT MOD"); // refresh the result list by inserting newly created VD serAC.refreshData(m_classReq, m_classRes, null, null, VDBean, null, "Version", oldID); } } else storeStatusMsg("\\t " + ret + " - Unable to create new version successfully."); } else { // creates new one ret = insAC.setVD("INS", VDBean, "New", oldVDBean); // create new one } if ((ret == null) || ret.equals("")) { this.clearCreateSessionAttributes(m_classReq, m_classRes); // clear some session attributes DataManager.setAttribute(session, "VDPageAction", "nothing"); DataManager.setAttribute(session, "originAction", ""); // forwards to search page with refreshed list if template or version if ((sMenuAction.equals("NewVDTemplate")) || (sMenuAction.equals("NewVDVersion"))) { DataManager.setAttribute(session, "searchAC", "ValueDomain"); DataManager.setAttribute(session, "originAction", "NewVDTemplate"); VDBean.setVD_ALIAS_NAME(VDBean.getVD_PREFERRED_NAME()); // VDBean.setVD_TYPE_NAME("PRIMARY"); String oldID = oldVDBean.getVD_VD_IDSEQ(); if (sMenuAction.equals("NewVDTemplate")) serAC.refreshData(m_classReq, m_classRes, null, null, VDBean, null, "Template", oldID); else if (sMenuAction.equals("NewVDVersion")) serAC.refreshData(m_classReq, m_classRes, null, null, VDBean, null, "Version", oldID); ForwardJSP(m_classReq, m_classRes, "/SearchResultsPage.jsp"); } // forward to create vd page with empty data if new one else { doOpenCreateNewPages(); } } // goes back to create/edit vd page if error else { DataManager.setAttribute(session, "VDPageAction", "validate"); // forward to create or edit pages if (isUpdateSuccess == false) { // insert the created NUE in the results. String oldID = oldVDBean.getVD_VD_IDSEQ(); if (sMenuAction.equals("NewVDTemplate")) serAC.refreshData(m_classReq, m_classRes, null, null, VDBean, null, "Template", oldID); ForwardJSP(m_classReq, m_classRes, "/SearchResultsPage.jsp"); } else ForwardJSP(m_classReq, m_classRes, "/CreateVDPage.jsp"); } } /** * The doOpenCreateVDPage method gets the session, gets some values from the createDE page and stores in bean m_DE, * sets some session attributes, then forwards to CreateVD page * * @throws Exception */ public void doOpenCreateVDPage() throws Exception { HttpSession session = m_classReq.getSession(); DE_Bean m_DE = (DE_Bean) session.getAttribute("m_DE"); if (m_DE == null) m_DE = new DE_Bean(); m_setAC.setDEValueFromPage(m_classReq, m_classRes, m_DE); // store VD bean DataManager.setAttribute(session, "m_DE", m_DE); // clear some session attributes this.clearCreateSessionAttributes(m_classReq, m_classRes); // reset the vd attributes VD_Bean m_VD = new VD_Bean(); m_VD.setVD_ASL_NAME("DRAFT NEW"); m_VD.setAC_PREF_NAME_TYPE("SYS"); // call the method to get the QuestValues if exists String sMenuAction = (String) session.getAttribute(Session_Data.SESSION_MENU_ACTION); if (sMenuAction.equals("Questions")) { GetACSearch serAC = new GetACSearch(m_classReq, m_classRes, this); serAC.getACQuestionValue(m_VD); // check if enumerated or not Vector vCRFval = (Vector) session.getAttribute("vQuestValue"); if (vCRFval != null && vCRFval.size() > 0) m_VD.setVD_TYPE_FLAG("E"); else m_VD.setVD_TYPE_FLAG("N"); // read property file and set the VD bean for Placeholder data String VDDefinition = NCICurationServlet.m_settings.getProperty("VDDefinition"); m_VD.setVD_PREFERRED_DEFINITION(VDDefinition); String DataType = NCICurationServlet.m_settings.getProperty("DataType"); m_VD.setVD_DATA_TYPE(DataType); String MaxLength = NCICurationServlet.m_settings.getProperty("MaxLength"); m_VD.setVD_MAX_LENGTH_NUM(MaxLength); } DataManager.setAttribute(session, "m_VD", m_VD); VD_Bean oldVD = new VD_Bean(); oldVD = oldVD.cloneVD_Bean(m_VD); DataManager.setAttribute(session, "oldVDBean", oldVD); // DataManager.setAttribute(session, "oldVDBean", m_VD); ForwardJSP(m_classReq, m_classRes, "/CreateVDPage.jsp"); } /** * * @throws Exception * */ private void doRemoveBuildingBlocksVD() throws Exception { HttpSession session = m_classReq.getSession(); String sSelRow = ""; VD_Bean m_VD = (VD_Bean) session.getAttribute("m_VD"); if (m_VD == null) m_VD = new VD_Bean(); Vector<EVS_Bean> vRepTerm = (Vector) session.getAttribute("vRepTerm"); if (vRepTerm == null) vRepTerm = new Vector<EVS_Bean>(); String sComp = (String) m_classReq.getParameter("sCompBlocks"); if (sComp == null) sComp = ""; if (sComp.equals("RepTerm")) { EVS_Bean m_REP = new EVS_Bean(); vRepTerm.setElementAt(m_REP, 0); DataManager.setAttribute(session, "vRepTerm", vRepTerm); m_VD.setVD_REP_NAME_PRIMARY(""); m_VD.setVD_REP_CONCEPT_CODE(""); m_VD.setVD_REP_EVS_CUI_ORIGEN(""); m_VD.setVD_REP_IDSEQ(""); DataManager.setAttribute(session, "RemoveRepBlock", "true"); DataManager.setAttribute(session, "newRepTerm", "true"); } else if (sComp.equals("RepQualifier")) { sSelRow = (String) m_classReq.getParameter("selRepQRow"); if (sSelRow != null && !(sSelRow.equals(""))) { Integer intObjRow = new Integer(sSelRow); int intObjRow2 = intObjRow.intValue(); if (vRepTerm.size() > (intObjRow2 + 1)) { vRepTerm.removeElementAt(intObjRow2 + 1); // add 1 so zero element not removed DataManager.setAttribute(session, "vRepTerm", vRepTerm); } // m_VD.setVD_REP_QUAL(""); Vector vRepQualifierNames = m_VD.getVD_REP_QUALIFIER_NAMES(); if (vRepQualifierNames == null) vRepQualifierNames = new Vector(); if (vRepQualifierNames.size() > intObjRow2) vRepQualifierNames.removeElementAt(intObjRow2); Vector vRepQualifierCodes = m_VD.getVD_REP_QUALIFIER_CODES(); if (vRepQualifierCodes == null) vRepQualifierCodes = new Vector(); if (vRepQualifierCodes.size() > intObjRow2) vRepQualifierCodes.removeElementAt(intObjRow2); Vector vRepQualifierDB = m_VD.getVD_REP_QUALIFIER_DB(); if (vRepQualifierDB == null) vRepQualifierDB = new Vector(); if (vRepQualifierDB.size() > intObjRow2) vRepQualifierDB.removeElementAt(intObjRow2); m_VD.setVD_REP_QUALIFIER_NAMES(vRepQualifierNames); m_VD.setVD_REP_QUALIFIER_CODES(vRepQualifierCodes); m_VD.setVD_REP_QUALIFIER_DB(vRepQualifierDB); DataManager.setAttribute(session, "RemoveRepBlock", "true"); DataManager.setAttribute(session, "newRepTerm", "true"); } } else if (sComp.equals("VDObjectClass")) { m_VD.setVD_OBJ_CLASS(""); DataManager.setAttribute(session, "m_OC", new EVS_Bean()); } else if (sComp.equals("VDPropertyClass")) { m_VD.setVD_PROP_CLASS(""); DataManager.setAttribute(session, "m_PC", new EVS_Bean()); } if (sComp.equals("RepTerm") || sComp.equals("RepQualifier")){ vRepTerm = (Vector)session.getAttribute("vRepTerm"); if (vRepTerm != null && vRepTerm.size() > 0){ vRepTerm = this.getMatchingThesarusconcept(vRepTerm, "Representation Term"); m_VD = this.updateRepAttribues(vRepTerm, m_VD); } DataManager.setAttribute(session, "vRepTerm", vRepTerm); } m_setAC.setVDValueFromPage(m_classReq, m_classRes, m_VD); DataManager.setAttribute(session, "m_VD", m_VD); } // end of doRemoveQualifier /**method to go back from vd and pv edits * @param orgAct String value for origin where vd page was opened * @param menuAct String value of menu action where this use case started * @param actype String what action is expected * @param butPress STring last button pressed * @param vdPageFrom string to check if it was PV or VD page * @return String jsp to forward the page to */ public String goBackfromVD(String orgAct, String menuAct, String actype, String butPress, String vdPageFrom) { try { //forward the page to editDE if originated from DE HttpSession session = m_classReq.getSession(); clearBuildingBlockSessionAttributes(m_classReq, m_classRes); if (vdPageFrom.equals("create")) { clearCreateSessionAttributes(m_classReq, m_classRes); if (menuAct.equals("NewVDTemplate") || menuAct.equals("NewVDVersion")) { VD_Bean VDBean = (VD_Bean)session.getAttribute(PVForm.SESSION_SELECT_VD); GetACSearch serAC = new GetACSearch(m_classReq, m_classRes, this); serAC.refreshData(m_classReq, m_classRes, null, null, VDBean, null, "Refresh", ""); return "/SearchResultsPage.jsp"; } else if (orgAct.equalsIgnoreCase("CreateNewVDfromEditDE")) return "/EditDEPage.jsp"; else return "/CreateDEPage.jsp"; } else if (vdPageFrom.equals("edit")) { if (orgAct.equalsIgnoreCase("editVDfromDE")) return "/EditDEPage.jsp"; //forward the page to search if originated from Search else if (menuAct.equalsIgnoreCase("editVD") || orgAct.equalsIgnoreCase("EditVD") || orgAct.equalsIgnoreCase("BlockEditVD") || (butPress.equals("Search") && !actype.equals("DataElement"))) { VD_Bean VDBean = (VD_Bean)session.getAttribute(PVForm.SESSION_SELECT_VD); if (VDBean == null) VDBean = new VD_Bean(); GetACSearch serAC = new GetACSearch(m_classReq, m_classRes, this); serAC.refreshData(m_classReq, m_classRes, null, null, VDBean, null, "Refresh", ""); return "/SearchResultsPage.jsp"; } else return "/EditVDPage.jsp"; } } catch (Exception e) { logger.error("ERROR - ", e); } return ""; } /** to clear the edited data from the edit and create pages * @param orgAct String value for origin where vd page was opened * @param menuAct String value of menu action where this use case started * @return String jsp to forward the page to */ public String clearEditsOnPage(String orgAct, String menuAct) { try { HttpSession session = m_classReq.getSession(); VD_Bean VDBean = (VD_Bean)session.getAttribute("oldVDBean"); //clear related the session attributes clearBuildingBlockSessionAttributes(m_classReq, m_classRes); String sVDID = VDBean.getVD_VD_IDSEQ(); Vector vList = new Vector(); //get VD's attributes from the database again GetACSearch serAC = new GetACSearch(m_classReq, m_classRes, this); if (sVDID != null && !sVDID.equals("")) serAC.doVDSearch(sVDID, "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", 0, "", "", "", "", "", "", "", "",vList); //forward editVD page with this bean if (vList.size() > 0) { VDBean = (VD_Bean)vList.elementAt(0); VDBean = serAC.getVDAttributes(VDBean, orgAct, menuAct); } else { VDBean = new VD_Bean(); VDBean.setVD_ASL_NAME("DRAFT NEW"); VDBean.setAC_PREF_NAME_TYPE("SYS"); } VD_Bean pgBean = new VD_Bean(); DataManager.setAttribute(session, PVForm.SESSION_SELECT_VD, pgBean.cloneVD_Bean(VDBean)); } catch (Exception e) { logger.error("ERROR - ", e); } return "/CreateVDPage.jsp"; } public void doOpenViewPage() throws Exception { //System.out.println("I am here open view page"); HttpSession session = m_classReq.getSession(); String acID = (String) m_classReq.getAttribute("acIdseq"); if (acID.equals("")) acID = m_classReq.getParameter("idseq"); Vector<VD_Bean> vList = new Vector<VD_Bean>(); // get DE's attributes from the database again GetACSearch serAC = new GetACSearch(m_classReq, m_classRes, this); if (acID != null && !acID.equals("")) { serAC.doVDSearch(acID, "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", 0, "", "", "", "", "", "", "", "", vList); } if (vList.size() > 0) // get all attributes { VD_Bean VDBean = (VD_Bean) vList.elementAt(0); VDBean = serAC.getVDAttributes(VDBean, "openView", "viewVD"); DataManager.setAttribute(session, "TabFocus", "VD"); m_classReq.setAttribute("viewVDId", VDBean.getIDSEQ()); String viewVD = "viewVD" + VDBean.getIDSEQ(); DataManager.setAttribute(session, viewVD, VDBean); String title = "CDE Curation View VD "+VDBean.getVD_LONG_NAME()+ " [" + VDBean.getVD_VD_ID() + "v" + VDBean.getVD_VERSION() +"]"; m_classReq.setAttribute("title", title); m_classReq.setAttribute("publicID", VDBean.getVD_VD_ID()); m_classReq.setAttribute("version", VDBean.getVD_VERSION()); m_classReq.setAttribute("IncludeViewPage", "EditVD.jsp") ; } } public void doViewPageTab() throws Exception{ String tab = m_classReq.getParameter("vdpvstab"); String from = m_classReq.getParameter("from"); String id = m_classReq.getParameter("id"); String viewVD = "viewVD" + id; HttpSession session = m_classReq.getSession(); VD_Bean VDBean = (VD_Bean)session.getAttribute(viewVD); String publicId = VDBean.getVD_VD_ID(); String version = VDBean.getVD_VERSION(); m_classReq.setAttribute("viewVDId", id); String title = "CDE Curation View VD "+VDBean.getVD_LONG_NAME()+ " [" + VDBean.getVD_VD_ID() + "v" + VDBean.getVD_VERSION() +"]"; m_classReq.setAttribute("title", title); m_classReq.setAttribute("publicID", VDBean.getVD_VD_ID()); m_classReq.setAttribute("version", VDBean.getVD_VERSION()); if (from.equals("edit")){ m_classReq.getSession().setAttribute("displayErrorMessage", "Yes"); } if (tab != null && tab.equals("PV")) { DataManager.setAttribute(session, "TabFocus", "PV"); m_classReq.setAttribute("IncludeViewPage", "PermissibleValue.jsp") ; ForwardJSP(m_classReq, m_classRes, "/ViewPage.jsp"); }else{ DataManager.setAttribute(session, "TabFocus", "VD"); m_classReq.setAttribute("IncludeViewPage", "EditVD.jsp") ; ForwardJSP(m_classReq, m_classRes, "/ViewPage.jsp"); } } private VD_Bean updateRepAttribues(Vector vRep, VD_Bean vdBean) { HttpSession session = m_classReq.getSession(); // add rep primary attributes to the vd bean EVS_Bean pBean =(EVS_Bean)vRep.get(0); vdBean.setVD_REP_NAME_PRIMARY(pBean.getLONG_NAME()); vdBean.setVD_REP_CONCEPT_CODE(pBean.getCONCEPT_IDENTIFIER()); vdBean.setVD_REP_EVS_CUI_ORIGEN(pBean.getEVS_DATABASE()); vdBean.setVD_REP_IDSEQ(pBean.getIDSEQ()); DataManager.setAttribute(session, "m_REP", pBean); // update qualifier vectors vdBean.setVD_REP_QUALIFIER_NAMES(null); vdBean.setVD_REP_QUALIFIER_CODES(null); vdBean.setVD_REP_QUALIFIER_DB(null); for (int i=1; i<vRep.size();i++){ EVS_Bean eBean =(EVS_Bean)vRep.get(i); // add rep qualifiers to the vector Vector<String> vRepQualifierNames = vdBean.getVD_REP_QUALIFIER_NAMES(); if (vRepQualifierNames == null) vRepQualifierNames = new Vector<String>(); vRepQualifierNames.addElement(eBean.getLONG_NAME()); Vector<String> vRepQualifierCodes = vdBean.getVD_REP_QUALIFIER_CODES(); if (vRepQualifierCodes == null) vRepQualifierCodes = new Vector<String>(); vRepQualifierCodes.addElement(eBean.getCONCEPT_IDENTIFIER()); Vector<String> vRepQualifierDB = vdBean.getVD_REP_QUALIFIER_DB(); if (vRepQualifierDB == null) vRepQualifierDB = new Vector<String>(); vRepQualifierDB.addElement(eBean.getEVS_DATABASE()); vdBean.setVD_REP_QUALIFIER_NAMES(vRepQualifierNames); vdBean.setVD_REP_QUALIFIER_CODES(vRepQualifierCodes); vdBean.setVD_REP_QUALIFIER_DB(vRepQualifierDB); // if(vRepQualifierNames.size()>0) // vdBean.setVD_REP_QUAL((String)vRepQualifierNames.elementAt(0)); DataManager.setAttribute(session, "vRepQResult", null); DataManager.setAttribute(session, "m_REPQ", eBean); } return vdBean; } }
private void doValidateVD() throws Exception { HttpSession session = m_classReq.getSession(); String sAction = (String) m_classReq.getParameter("pageAction"); if (sAction == null) sAction = ""; // do below for versioning to check whether these two have changed VD_Bean m_VD = (VD_Bean) session.getAttribute("m_VD"); // new VD_Bean(); EVS_Bean m_OC = new EVS_Bean(); EVS_Bean m_PC = new EVS_Bean(); EVS_Bean m_REP = new EVS_Bean(); EVS_Bean m_OCQ = new EVS_Bean(); EVS_Bean m_PCQ = new EVS_Bean(); EVS_Bean m_REPQ = new EVS_Bean(); GetACService getAC = new GetACService(m_classReq, m_classRes, this); DataManager.setAttribute(session, "VDPageAction", "validate"); // store the page action in attribute m_setAC.setVDValueFromPage(m_classReq, m_classRes, m_VD); m_OC = (EVS_Bean) session.getAttribute("m_OC"); m_PC = (EVS_Bean) session.getAttribute("m_PC"); m_OCQ = (EVS_Bean) session.getAttribute("m_OCQ"); m_PCQ = (EVS_Bean) session.getAttribute("m_PCQ"); m_REP = (EVS_Bean) session.getAttribute("m_REP"); m_REPQ = (EVS_Bean) session.getAttribute("m_REPQ"); m_setAC.setValidatePageValuesVD(m_classReq, m_classRes, m_VD, m_OC, m_PC, m_REP, m_OCQ, m_PCQ, m_REPQ, getAC); DataManager.setAttribute(session, "m_VD", m_VD); /* * if(sAction.equals("Enum") || sAction.equals("NonEnum") || sAction.equals("EnumByRef")) ForwardJSP(m_classReq, m_classRes, * "/CreateVDPage.jsp"); else if (!sAction.equals("vdpvstab") && !sAction.equals("vddetailstab")) * ForwardJSP(req, res, "/ValidateVDPage.jsp"); */} // end of doValidateVD /** * The doSetVDPage method gets the values from page the user filled out, Calls 'setAC.setVDValueFromPage' to set the * data from the page to the bean. Stores 'm_VD' bean in session. Forwards the page 'CreateVDPage.jsp' with * validation vector to display. * * @param sOrigin * origin where it is called from * * @throws Exception */ private void doSetVDPage(String sOrigin) throws Exception { try { HttpSession session = m_classReq.getSession(); String sAction = (String) m_classReq.getParameter("pageAction"); if (sAction == null) sAction = ""; // do below for versioning to check whether these two have changed VD_Bean vdBean = (VD_Bean) session.getAttribute("m_VD"); // new VD_Bean(); m_setAC.setVDValueFromPage(m_classReq, m_classRes, vdBean); // check if pvs are used in the form when type is changed to non enumerated. if (!sAction.equals("Enum")) { // get vdid from the bean // VD_Bean vdBean = (VD_Bean)session.getAttribute("m_VD"); String sVDid = vdBean.getVD_VD_IDSEQ(); boolean isExist = false; if (sOrigin.equals("Edit")) { // call function to check if relationship exists SetACService setAC = new SetACService(this); isExist = setAC.checkPVQCExists(m_classReq, m_classRes, sVDid, ""); if (isExist) { String sMsg = "Unable to change Value Domain type to Non-Enumerated " + "because one or more Permissible Values are being used in a Case Report Form. \\n" + "Please create a new version of this Value Domain to change the type to Non-Enumerated."; DataManager.setAttribute(session, Session_Data.SESSION_STATUS_MESSAGE, sMsg); vdBean.setVD_TYPE_FLAG("E"); DataManager.setAttribute(session, "m_VD", vdBean); } } // mark all the pvs as deleted to remove them while submitting. if (!isExist) { Vector<PV_Bean> vVDPVs = vdBean.getVD_PV_List(); // (Vector)session.getAttribute("VDPVList"); if (vVDPVs != null) { // set each bean as deleted to handle later Vector<PV_Bean> vRemVDPV = vdBean.getRemoved_VDPVList(); if (vRemVDPV == null) vRemVDPV = new Vector<PV_Bean>(); for (int i = 0; i < vVDPVs.size(); i++) { PV_Bean pvBean = (PV_Bean) vVDPVs.elementAt(i); vRemVDPV.addElement(pvBean); } vdBean.setRemoved_VDPVList(vRemVDPV); vdBean.setVD_PV_List(new Vector<PV_Bean>()); } } } else { // remove meta parents since it is not needed for enum types Vector<EVS_Bean> vParentCon = vdBean.getReferenceConceptList(); // (Vector)session.getAttribute("VDParentConcept"); if (vParentCon == null) vParentCon = new Vector<EVS_Bean>(); for (int i = 0; i < vParentCon.size(); i++) { EVS_Bean ePar = (EVS_Bean) vParentCon.elementAt(i); if (ePar == null) ePar = new EVS_Bean(); String parDB = ePar.getEVS_DATABASE(); // System.out.println(i + " setvdpage " + parDB); if (parDB != null && parDB.equals("NCI Metathesaurus")) { ePar.setCON_AC_SUBMIT_ACTION("DEL"); vParentCon.setElementAt(ePar, i); } } vdBean.setReferenceConceptList(vParentCon); DataManager.setAttribute(session, "m_VD", vdBean); // get back pvs associated with this vd VD_Bean oldVD = (VD_Bean) session.getAttribute("oldVDBean"); if (oldVD == null) oldVD = new VD_Bean(); if (oldVD.getVD_TYPE_FLAG() != null && oldVD.getVD_TYPE_FLAG().equals("E")) { if (oldVD.getVD_VD_IDSEQ() != null && !oldVD.getVD_VD_IDSEQ().equals("")) { // String pvAct = "Search"; String sMenu = (String) session.getAttribute(Session_Data.SESSION_MENU_ACTION); // if (sMenu.equals("NewVDTemplate")) // pvAct = "NewUsing"; // Integer pvCount = new Integer(0); vdBean.setVD_PV_List(oldVD.cloneVDPVVector(oldVD.getVD_PV_List())); vdBean.setRemoved_VDPVList(new Vector<PV_Bean>()); GetACSearch serAC = new GetACSearch(m_classReq, m_classRes, this); if (sMenu.equals("Questions")) serAC.getACQuestionValue(vdBean); } } } DataManager.setAttribute(session, "m_VD", vdBean); } catch (Exception e) { logger.error("Error - doSetVDPage " + e.toString(), e); } } // end of doValidateVD /** * makes the vd's system generated name * * @param vd * current vd bean * @param vParent * vector of seelected parents * @return modified vd bean */ public AC_Bean getSystemName(AC_Bean ac, Vector<EVS_Bean> vParent) { VD_Bean vd = (VD_Bean)ac; try { // make the system generated name String sysName = ""; for (int i = vParent.size() - 1; i > -1; i--) { EVS_Bean par = (EVS_Bean) vParent.elementAt(i); String evsDB = par.getEVS_DATABASE(); String subAct = par.getCON_AC_SUBMIT_ACTION(); if (subAct != null && !subAct.equals("DEL") && evsDB != null && !evsDB.equals("Non_EVS")) { // add the concept id to sysname if less than 20 characters if (sysName.equals("") || sysName.length() < 20) sysName += par.getCONCEPT_IDENTIFIER() + ":"; else break; } } // append vd public id and version in the end if (vd.getVD_VD_ID() != null) sysName += vd.getVD_VD_ID(); String sver = vd.getVD_VERSION(); if (sver != null && sver.indexOf(".") < 0) sver += ".0"; if (vd.getVD_VERSION() != null) sysName += "v" + sver; // limit to 30 characters if (sysName.length() > 30) sysName = sysName.substring(sysName.length() - 30); vd.setAC_SYS_PREF_NAME(sysName); // store it in vd bean // make system name preferrd name if sys was selected String selNameType = (String) m_classReq.getParameter("rNameConv"); // get it from the vd bean if null if (selNameType == null) { selNameType = vd.getVD_TYPE_NAME(); } else { // store the keyed in text in the user field for later use. String sPrefName = (String) m_classReq.getParameter("txPreferredName"); if (selNameType != null && selNameType.equals("USER") && sPrefName != null) vd.setAC_USER_PREF_NAME(sPrefName); } if (selNameType != null && selNameType.equals("SYS")) vd.setVD_PREFERRED_NAME(sysName); } catch (Exception e) { this.logger.error("ERROR - getSystemName : " + e.toString(), e); } return vd; } /** * marks the parent and/or its pvs as deleted from the session. * * @param sPVAction * @param vdPage * @throws java.lang.Exception */ private void doRemoveParent(String sPVAction, String vdPage) throws Exception { HttpSession session = m_classReq.getSession(); VD_Bean m_VD = (VD_Bean) session.getAttribute("m_VD"); // new VD_Bean(); Vector<EVS_Bean> vParentCon = m_VD.getReferenceConceptList(); // (Vector)session.getAttribute("VDParentConcept"); if (vParentCon == null) vParentCon = new Vector<EVS_Bean>(); // get the selected parent info from teh request String sParentCC = (String) m_classReq.getParameter("selectedParentConceptCode"); String sParentName = (String) m_classReq.getParameter("selectedParentConceptName"); String sParentDB = (String) m_classReq.getParameter("selectedParentConceptDB"); // for non evs parent compare the long names instead if (sParentName != null && !sParentName.equals("") && sParentDB != null && sParentDB.equals("Non_EVS")) sParentCC = sParentName; if (sParentCC != null) { for (int i = 0; i < vParentCon.size(); i++) { EVS_Bean eBean = (EVS_Bean) vParentCon.elementAt(i); if (eBean == null) eBean = new EVS_Bean(); String thisParent = eBean.getCONCEPT_IDENTIFIER(); if (thisParent == null) thisParent = ""; String thisParentName = eBean.getLONG_NAME(); if (thisParentName == null) thisParentName = ""; String thisParentDB = eBean.getEVS_DATABASE(); if (thisParentDB == null) thisParentDB = ""; // for non evs parent compare the long names instead if (sParentDB != null && sParentDB.equals("Non_EVS")) thisParent = thisParentName; // look for the matched parent from the vector to remove if (sParentCC.equals(thisParent)) { @SuppressWarnings("unused") String strHTML = ""; EVSMasterTree tree = new EVSMasterTree(m_classReq, thisParentDB, this); strHTML = tree.refreshTree(thisParentName, "false"); strHTML = tree.refreshTree("parentTree" + thisParentName, "false"); if (sPVAction.equals("removePVandParent")) { Vector<PV_Bean> vVDPVList = m_VD.getVD_PV_List(); // (Vector)session.getAttribute("VDPVList"); if (vVDPVList == null) vVDPVList = new Vector<PV_Bean>(); // loop through the vector of pvs to get matched parent for (int j = 0; j < vVDPVList.size(); j++) { PV_Bean pvBean = (PV_Bean) vVDPVList.elementAt(j); if (pvBean == null) pvBean = new PV_Bean(); EVS_Bean pvParent = (EVS_Bean) pvBean.getPARENT_CONCEPT(); if (pvParent == null) pvParent = new EVS_Bean(); String pvParCon = pvParent.getCONCEPT_IDENTIFIER(); // match the parent concept with the pv's parent concept if (thisParent.equals(pvParCon)) { pvBean.setVP_SUBMIT_ACTION("DEL"); // mark the vp as deleted // String pvID = pvBean.getPV_PV_IDSEQ(); vVDPVList.setElementAt(pvBean, j); } } m_VD.setVD_PV_List(vVDPVList); // DataManager.setAttribute(session, "VDPVList", vVDPVList); } // mark the parent as delected and leave eBean.setCON_AC_SUBMIT_ACTION("DEL"); vParentCon.setElementAt(eBean, i); break; } } } // DataManager.setAttribute(session, "VDParentConcept", vParentCon); m_VD.setReferenceConceptList(vParentCon); // make sure all other changes are stored back in vd m_setAC.setVDValueFromPage(m_classReq, m_classRes, m_VD); // make vd's system preferred name m_VD = (VD_Bean) this.getSystemName(m_VD, vParentCon); DataManager.setAttribute(session, "m_VD", m_VD); // make the selected parent in hte session empty DataManager.setAttribute(session, "SelectedParentName", ""); DataManager.setAttribute(session, "SelectedParentCC", ""); DataManager.setAttribute(session, "SelectedParentDB", ""); DataManager.setAttribute(session, "SelectedParentMetaSource", ""); // forward teh page according to vdPage if (vdPage.equals("editVD")) ForwardJSP(m_classReq, m_classRes, "/EditVDPage.jsp"); else ForwardJSP(m_classReq, m_classRes, "/CreateVDPage.jsp"); } /** * splits the vd rep term from cadsr into individual concepts * * @param sComp * name of the searched component * @param m_Bean * selected EVS bean * @param nameAction * string naming action * */ private void splitIntoConceptsVD(String sComp, EVS_Bean m_Bean,String nameAction) { try { HttpSession session = m_classReq.getSession(); // String sSelRow = ""; VD_Bean m_VD = (VD_Bean) session.getAttribute("m_VD"); if (m_VD == null) m_VD = new VD_Bean(); m_setAC.setVDValueFromPage(m_classReq, m_classRes, m_VD); Vector vRepTerm = (Vector) session.getAttribute("vRepTerm"); if (vRepTerm == null) vRepTerm = new Vector(); String sCondr = m_Bean.getCONDR_IDSEQ(); String sLongName = m_Bean.getLONG_NAME(); String sIDSEQ = m_Bean.getIDSEQ(); if (sComp.equals("RepTerm") || sComp.equals("RepQualifier")) { m_VD.setVD_REP_TERM(sLongName); m_VD.setVD_REP_IDSEQ(sIDSEQ); } // String sRepTerm = m_VD.getVD_REP_TERM(); if (sCondr != null && !sCondr.equals("")) { GetACService getAC = new GetACService(m_classReq, m_classRes, this); Vector vCon = getAC.getAC_Concepts(sCondr, null, true); if (vCon != null && vCon.size() > 0) { for (int j = 0; j < vCon.size(); j++) { EVS_Bean bean = new EVS_Bean(); bean = (EVS_Bean) vCon.elementAt(j); if (bean != null) { if (j == 0) // Primary Concept m_VD = this.addRepConcepts(nameAction, m_VD, bean, "Primary"); else // Secondary Concepts m_VD = this.addRepConcepts(nameAction, m_VD, bean, "Qualifier"); } } } } } catch (Exception e) { this.logger.error("ERROR - splitintoConceptVD : " + e.toString(), e); } } /** * this method is used to create preferred name for VD names of all three types will be stored in the bean for later * use if type is changed, it populates name according to type selected. * * @param newBean * new EVS bean to append the name to * @param nameAct * string new name or append name * @param pageVD * current vd bean * @return VD bean */ public AC_Bean getACNames(EVS_Bean newBean, String nameAct, AC_Bean pageAC) { HttpSession session = m_classReq.getSession(); VD_Bean pageVD = (VD_Bean)pageAC; if (pageVD == null) pageVD = (VD_Bean) session.getAttribute("m_VD"); // get vd object class and property names String sLongName = ""; String sPrefName = ""; String sAbbName = ""; String sDef = ""; // get the existing one if not restructuring the name but appending it if (newBean != null) { sLongName = pageVD.getVD_LONG_NAME(); if (sLongName == null) sLongName = ""; sDef = pageVD.getVD_PREFERRED_DEFINITION(); if (sDef == null) sDef = ""; } // get the typed text on to user name String selNameType = ""; if (nameAct.equals("Search") || nameAct.equals("Remove")) { selNameType = (String) m_classReq.getParameter("rNameConv"); sPrefName = (String) m_classReq.getParameter("txPreferredName"); if (selNameType != null && selNameType.equals("USER") && sPrefName != null) pageVD.setAC_USER_PREF_NAME(sPrefName); } // get the object class into the long name and abbr name String sObjClass = pageVD.getVD_OBJ_CLASS(); if (sObjClass == null) sObjClass = ""; if (!sObjClass.equals("")) { // rearrange it long name if (newBean == null) { if (!sLongName.equals("")) sLongName += " "; // add extra space if not empty sLongName += sObjClass; EVS_Bean mOC = (EVS_Bean) session.getAttribute("m_OC"); if (mOC != null) { if (!sDef.equals("")) sDef += "_"; // add definition sDef += mOC.getPREFERRED_DEFINITION(); } } if (!sAbbName.equals("")) sAbbName += "_"; // add underscore if not empty if (sObjClass.length() > 3) sAbbName += sObjClass.substring(0, 4); // truncate to 4 letters else sAbbName = sObjClass; } // get the property into the long name and abbr name String sPropClass = pageVD.getVD_PROP_CLASS(); if (sPropClass == null) sPropClass = ""; if (!sPropClass.equals("")) { // rearrange it long name if (newBean == null) { if (!sLongName.equals("")) sLongName += " "; // add extra space if not empty sLongName += sPropClass; EVS_Bean mPC = (EVS_Bean) session.getAttribute("m_PC"); if (mPC != null) { if (!sDef.equals("")) sDef += "_"; // add definition sDef += mPC.getPREFERRED_DEFINITION(); } } if (!sAbbName.equals("")) sAbbName += "_"; // add underscore if not empty if (sPropClass.length() > 3) sAbbName += sPropClass.substring(0, 4); // truncate to 4 letters else sAbbName += sPropClass; } Vector vRep = (Vector) session.getAttribute("vRepTerm"); if (vRep == null) vRep = new Vector(); // add the qualifiers first for (int i = 1; vRep.size() > i; i++) { EVS_Bean eCon = (EVS_Bean) vRep.elementAt(i); if (eCon == null) eCon = new EVS_Bean(); String conName = eCon.getLONG_NAME(); if (conName == null) conName = ""; if (!conName.equals("")) { // rearrange it long name and definition if (newBean == null) { if (!sLongName.equals("")) sLongName += " "; sLongName += conName; if (!sDef.equals("")) sDef += "_"; // add definition sDef += eCon.getPREFERRED_DEFINITION(); } if (!sAbbName.equals("")) sAbbName += "_"; if (conName.length() > 3) sAbbName += conName.substring(0, 4); // truncate to four letters else sAbbName += conName; } } // add the primary if (vRep != null && vRep.size() > 0) { EVS_Bean eCon = (EVS_Bean) vRep.elementAt(0); if (eCon == null) eCon = new EVS_Bean(); String sPrimary = eCon.getLONG_NAME(); if (sPrimary == null) sPrimary = ""; if (!sPrimary.equals("")) { // rearrange it only long name and definition if (newBean == null) { if (!sLongName.equals("")) sLongName += " "; sLongName += sPrimary; if (!sDef.equals("")) sDef += "_"; // add definition sDef += eCon.getPREFERRED_DEFINITION(); } if (!sAbbName.equals("")) sAbbName += "_"; if (sPrimary.length() > 3) sAbbName += sPrimary.substring(0, 4); // truncate to four letters else sAbbName += sPrimary; } } // truncate to 30 characters if (sAbbName != null && sAbbName.length() > 30) sAbbName = sAbbName.substring(0, 30); // add the abbr name to vd bean and page is selected pageVD.setAC_ABBR_PREF_NAME(sAbbName); // make abbr name name preferrd name if sys was selected if (selNameType != null && selNameType.equals("ABBR")) pageVD.setVD_PREFERRED_NAME(sAbbName); if (newBean != null) // appending to the existing; { String sSelectName = newBean.getLONG_NAME(); if (!sLongName.equals("")) sLongName += " "; sLongName += sSelectName; if (!sDef.equals("")) sDef += "_"; // add definition sDef += newBean.getPREFERRED_DEFINITION(); } // store the long names, definition, and usr name in vd bean if searched if (nameAct.equals("Search")) { pageVD.setVD_LONG_NAME(sLongName); pageVD.setVD_PREFERRED_DEFINITION(sDef); pageVD.setVDNAME_CHANGED(true); } return pageVD; } /** * * @param nameAction * stirng name action * */ private void doVDUseSelection(String nameAction) { try { HttpSession session = m_classReq.getSession(); String sSelRow = ""; // InsACService insAC = new InsACService(req, res, this); VD_Bean m_VD = (VD_Bean) session.getAttribute("m_VD"); if (m_VD == null) m_VD = new VD_Bean(); m_setAC.setVDValueFromPage(m_classReq, m_classRes, m_VD); Vector<EVS_Bean> vRepTerm = (Vector) session.getAttribute("vRepTerm"); if (vRepTerm == null) vRepTerm = new Vector<EVS_Bean>(); Vector vAC = new Vector(); ; EVS_Bean m_REP = new EVS_Bean(); String sComp = (String) m_classReq.getParameter("sCompBlocks"); // get rep term components if (sComp.equals("RepTerm") || sComp.equals("RepQualifier")) { sSelRow = (String) m_classReq.getParameter("selRepRow"); // vAC = (Vector)session.getAttribute("vRepResult"); vAC = (Vector) session.getAttribute("vACSearch"); if (vAC == null) vAC = new Vector(); if (sSelRow != null && !sSelRow.equals("")) { String sObjRow = sSelRow.substring(2); Integer intObjRow = new Integer(sObjRow); int intObjRow2 = intObjRow.intValue(); if (vAC.size() > intObjRow2 - 1) m_REP = (EVS_Bean) vAC.elementAt(intObjRow2); // get name value pari String sNVP = (String) m_classReq.getParameter("nvpConcept"); if (sNVP != null && !sNVP.equals("")) { m_REP.setNVP_CONCEPT_VALUE(sNVP); String sName = m_REP.getLONG_NAME(); m_REP.setLONG_NAME(sName + "::" + sNVP); m_REP.setPREFERRED_DEFINITION(m_REP.getPREFERRED_DEFINITION() + "::" + sNVP); } //System.out.println(sNVP + sComp + m_REP.getLONG_NAME()); } else { storeStatusMsg("Unable to get the selected row from the Rep Term search results."); return; } // send it back if unable to obtion the concept if (m_REP == null || m_REP.getLONG_NAME() == null) { storeStatusMsg("Unable to obtain concept from the selected row of the " + sComp + " search results.\\n" + "Please try again."); return; } // handle the primary search if (sComp.equals("RepTerm")) { if (m_REP.getEVS_DATABASE().equals("caDSR")) { // split it if rep term, add concept class to the list if evs id exists if (m_REP.getCONDR_IDSEQ() == null || m_REP.getCONDR_IDSEQ().equals("")) { if (m_REP.getCONCEPT_IDENTIFIER() == null || m_REP.getCONCEPT_IDENTIFIER().equals("")) { storeStatusMsg("This Rep Term is not associated to a concept, so the data is suspect. \\n" + "Please choose another Rep Term."); } else m_VD = this.addRepConcepts(nameAction, m_VD, m_REP, "Primary"); } else splitIntoConceptsVD(sComp, m_REP, nameAction); } else m_VD = this.addRepConcepts(nameAction, m_VD, m_REP, "Primary"); } else if (sComp.equals("RepQualifier")) { // Do this to reserve zero position in vector for primary concept if (vRepTerm.size() < 1) { EVS_Bean OCBean = new EVS_Bean(); vRepTerm.addElement(OCBean); DataManager.setAttribute(session, "vRepTerm", vRepTerm); } m_VD = this.addRepConcepts(nameAction, m_VD, m_REP, "Qualifier"); } } else { EVS_Bean eBean = this.getEVSSelRow(m_classReq); if (eBean != null && eBean.getLONG_NAME() != null) { /* if (sComp.equals("VDObjectClass")) { m_VD.setVD_OBJ_CLASS(eBean.getLONG_NAME()); DataManager.setAttribute(session, "m_OC", eBean); } else if (sComp.equals("VDPropertyClass")) { m_VD.setVD_PROP_CLASS(eBean.getLONG_NAME()); DataManager.setAttribute(session, "m_PC", eBean); } */ if (nameAction.equals("appendName")) m_VD = (VD_Bean) this.getACNames(eBean, "Search", m_VD); } } vRepTerm = (Vector) session.getAttribute("vRepTerm"); if (vRepTerm != null && vRepTerm.size() > 0){ vRepTerm = this.getMatchingThesarusconcept(vRepTerm, "Representation Term"); m_VD = this.updateRepAttribues(vRepTerm, m_VD); } DataManager.setAttribute(session, "vRepTerm", vRepTerm); // rebuild new name if not appending EVS_Bean nullEVS = null; if (nameAction.equals("newName")) m_VD = (VD_Bean) this.getACNames(nullEVS, "Search", m_VD); else if (nameAction.equals("blockName")) m_VD = (VD_Bean) this.getACNames(nullEVS, "blockName", m_VD); DataManager.setAttribute(session, "m_VD", m_VD); } catch (Exception e) { this.logger.error("ERROR - doVDUseSelection : " + e.toString(), e); } } // end of doVDUseSelection /** * adds the selected concept to the vector of concepts for property * * @param nameAction * String naming action * @param vdBean * selected DEC_Bean * @param eBean * selected EVS_Bean * @param repType * String property type (primary or qualifier) * @return DEC_Bean * @throws Exception */ @SuppressWarnings("unchecked") private VD_Bean addRepConcepts(String nameAction, VD_Bean vdBean, EVS_Bean eBean, String repType) throws Exception { HttpSession session = m_classReq.getSession(); // add the concept bean to the OC vector and store it in the vector Vector<EVS_Bean> vRepTerm = (Vector) session.getAttribute("vRepTerm"); if (vRepTerm == null) vRepTerm = new Vector<EVS_Bean>(); // get the evs user bean EVS_UserBean eUser = (EVS_UserBean) this.sessionData.EvsUsrBean; // (EVS_UserBean)session.getAttribute(EVSSearch.EVS_USER_BEAN_ARG); // //("EvsUserBean"); if (eUser == null) eUser = new EVS_UserBean(); eBean.setCON_AC_SUBMIT_ACTION("INS"); eBean.setCONTE_IDSEQ(vdBean.getVD_CONTE_IDSEQ()); String eDB = eBean.getEVS_DATABASE(); if (eDB != null && eBean.getEVS_ORIGIN() != null && eDB.equalsIgnoreCase("caDSR")) { eDB = eBean.getVocabAttr(eUser, eBean.getEVS_ORIGIN(), EVSSearch.VOCAB_NAME, EVSSearch.VOCAB_DBORIGIN); // "vocabName", // "vocabDBOrigin"); if (eDB.equals(EVSSearch.META_VALUE)) // "MetaValue")) eDB = eBean.getEVS_ORIGIN(); eBean.setEVS_DATABASE(eDB); // eBean.getEVS_ORIGIN()); } // System.out.println(eBean.getEVS_ORIGIN() + " before thes concept for REP " + eDB); // EVSSearch evs = new EVSSearch(m_classReq, m_classRes, this); //eBean = evs.getThesaurusConcept(eBean); // add to the vector and store it in the session, reset if primary and alredy existed, add otehrwise if (repType.equals("Primary") && vRepTerm.size() > 0) vRepTerm.setElementAt(eBean, 0); else vRepTerm.addElement(eBean); DataManager.setAttribute(session, "vRepTerm", vRepTerm); DataManager.setAttribute(session, "newRepTerm", "true"); // DataManager.setAttribute(session, "selRepQRow", sSelRow); // add to name if appending if (nameAction.equals("appendName")) vdBean = (VD_Bean) this.getACNames(eBean, "Search", vdBean); return vdBean; } // end addRepConcepts /** * The doValidateVD method gets the values from page the user filled out, validates the input, then forwards results * to the Validate page Called from 'doCreateVDActions', 'doSubmitVD' method. Calls 'setAC.setVDValueFromPage' to * set the data from the page to the bean. Calls 'setAC.setValidatePageValuesVD' to validate the data. Stores 'm_VD' * bean in session. Forwards the page 'ValidateVDPage.jsp' with validation vector to display. * * @throws Exception */ private void doValidateVDBlockEdit() throws Exception { HttpSession session = m_classReq.getSession(); VD_Bean m_VD = (VD_Bean) session.getAttribute("m_VD"); // new VD_Bean(); DataManager.setAttribute(session, "VDPageAction", "validate"); // store the page action in attribute m_setAC.setVDValueFromPage(m_classReq, m_classRes, m_VD); DataManager.setAttribute(session, "m_VD", m_VD); m_setAC.setValidateBlockEdit(m_classReq, m_classRes, "ValueDomain"); DataManager.setAttribute(session, "VDEditAction", "VDBlockEdit"); ForwardJSP(m_classReq, m_classRes, "/ValidateVDPage.jsp"); } // end of doValidateVD /** * The doInsertVD method to insert or update record in the database. Called from 'service' method where reqType is * 'validateVDFromForm'. Retrieves the session bean m_VD. if the action is reEditVD forwards the page back to Edit * or create pages. * * Otherwise, calls 'doUpdateVDAction' for editing the vd. calls 'doInsertVDfromDEAction' for creating the vd from * DE page. calls 'doInsertVDfromMenuAction' for creating the vd from menu . * * @throws Exception */ private void doInsertVD() throws Exception { HttpSession session = m_classReq.getSession(); // make sure that status message is empty DataManager.setAttribute(session, Session_Data.SESSION_STATUS_MESSAGE, ""); Vector vStat = new Vector(); DataManager.setAttribute(session, "vStatMsg", vStat); String sVDAction = (String) session.getAttribute("VDAction"); if (sVDAction == null) sVDAction = ""; String sVDEditAction = (String) session.getAttribute("VDEditAction"); if (sVDEditAction == null) sVDEditAction = ""; String sAction = (String) m_classReq.getParameter("ValidateVDPageAction"); // String sMenuAction = (String) session.getAttribute(Session_Data.SESSION_MENU_ACTION); // String sButtonPressed = (String) session.getAttribute("LastMenuButtonPressed"); String sOriginAction = (String) session.getAttribute("originAction"); if (sAction == null) sAction = "submitting"; // for direct submit without validating // String spageAction = (String) m_classReq.getParameter("pageAction"); if (sAction != null) { // goes back to create/edit pages from validation page if (sAction.equals("reEditVD")) { String vdfocus = (String) session.getAttribute("TabFocus"); if (vdfocus != null && vdfocus.equals("PV")) ForwardJSP(m_classReq, m_classRes, "/PermissibleValue.jsp"); else { if (sVDAction.equals("EditVD") || sVDAction.equals("BlockEdit")) ForwardJSP(m_classReq, m_classRes, "/EditVDPage.jsp"); else ForwardJSP(m_classReq, m_classRes, "/CreateVDPage.jsp"); } } else { // edit the existing vd if (sVDAction.equals("NewVD") && sOriginAction.equals("NewVDFromMenu")) doInsertVDfromMenuAction(); else if (sVDAction.equals("EditVD") && !sOriginAction.equals("BlockEditVD")) doUpdateVDAction(); else if (sVDEditAction.equals("VDBlockEdit")) doUpdateVDActionBE(); // if create new vd from create/edit DE page. else if (sOriginAction.equals("CreateNewVDfromCreateDE") || sOriginAction.equals("CreateNewVDfromEditDE")) doInsertVDfromDEAction(sOriginAction); // from the menu AND template/ version else { doInsertVDfromMenuAction(); } } } } // end of doInsertVD /** * update record in the database and display the result. Called from 'doInsertVD' method when the aciton is editing. * Retrieves the session bean m_VD. calls 'insAC.setVD' to update the database. updates the DEbean and sends back to * EditDE page if origin is form DEpage otherwise calls 'serAC.refreshData' to get the refreshed search result * forwards the page back to search page with refreshed list after updating. * * If ret is not null stores the statusMessage as error message in session and forwards the page back to * 'EditVDPage.jsp' for Edit. * * @throws Exception */ private void doUpdateVDAction() throws Exception { HttpSession session = m_classReq.getSession(); VD_Bean VDBean = (VD_Bean) session.getAttribute("m_VD"); VD_Bean oldVDBean = (VD_Bean) session.getAttribute("oldVDBean"); // String sMenu = (String) session.getAttribute(Session_Data.SESSION_MENU_ACTION); InsACService insAC = new InsACService(m_classReq, m_classRes, this); doInsertVDBlocks(null); // udpate the status message with DE name and ID storeStatusMsg("Value Domain Name : " + VDBean.getVD_LONG_NAME()); storeStatusMsg("Public ID : " + VDBean.getVD_VD_ID()); // call stored procedure to update attributes String ret = insAC.setVD("UPD", VDBean, "Edit", oldVDBean); // forward to search page with refreshed list after successful update if ((ret == null) || ret.equals("")) { this.clearCreateSessionAttributes(m_classReq, m_classRes); // clear some session attributes String sOriginAction = (String) session.getAttribute("originAction"); GetACSearch serAC = new GetACSearch(m_classReq, m_classRes, this); // forward page back to EditDE if (sOriginAction.equals("editVDfromDE") || sOriginAction.equals("EditDE")) { DE_Bean DEBean = (DE_Bean) session.getAttribute("m_DE"); if (DEBean != null) { DEBean.setDE_VD_IDSEQ(VDBean.getVD_VD_IDSEQ()); DEBean.setDE_VD_PREFERRED_NAME(VDBean.getVD_PREFERRED_NAME()); DEBean.setDE_VD_NAME(VDBean.getVD_LONG_NAME()); // reset the attributes DataManager.setAttribute(session, "originAction", ""); // add DEC Bean into DE BEan DEBean.setDE_VD_Bean(VDBean); DataManager.setAttribute(session, "m_DE", DEBean); CurationServlet deServ = (DataElementServlet) getACServlet("DataElement"); DEBean = (DE_Bean) deServ.getACNames("new", "editVD", DEBean); } ForwardJSP(m_classReq, m_classRes, "/EditDEPage.jsp"); } // go to search page with refreshed list else { VDBean.setVD_ALIAS_NAME(VDBean.getVD_PREFERRED_NAME()); // VDBean.setVD_TYPE_NAME("PRIMARY"); DataManager.setAttribute(session, Session_Data.SESSION_MENU_ACTION, "editVD"); String oldID = VDBean.getVD_VD_IDSEQ(); serAC.refreshData(m_classReq, m_classRes, null, null, VDBean, null, "Edit", oldID); ForwardJSP(m_classReq, m_classRes, "/SearchResultsPage.jsp"); } } // goes back to edit page if error occurs else { DataManager.setAttribute(session, "VDPageAction", "nothing"); ForwardJSP(m_classReq, m_classRes, "/EditVDPage.jsp"); } } /** * update record in the database and display the result. Called from 'doInsertVD' method when the aciton is editing. * Retrieves the session bean m_VD. calls 'insAC.setVD' to update the database. updates the DEbean and sends back to * EditDE page if origin is form DEpage otherwise calls 'serAC.refreshData' to get the refreshed search result * forwards the page back to search page with refreshed list after updating. * * If ret is not null stores the statusMessage as error message in session and forwards the page back to * 'EditVDPage.jsp' for Edit. * * @throws Exception */ private void doUpdateVDActionBE() throws Exception { HttpSession session = m_classReq.getSession(); VD_Bean VDBean = (VD_Bean) session.getAttribute("m_VD"); // validated edited m_VD boolean isRefreshed = false; String ret = ":"; InsACService insAC = new InsACService(m_classReq, m_classRes, this); GetACSearch serAC = new GetACSearch(m_classReq, m_classRes, this); GetACService getAC = new GetACService(m_classReq, m_classRes, this); // Vector vStatMsg = new Vector(); String sNewRep = (String) session.getAttribute("newRepTerm"); if (sNewRep == null) sNewRep = ""; //System.out.println(" new rep " + sNewRep); Vector vBERows = (Vector) session.getAttribute("vBEResult"); int vBESize = vBERows.size(); Integer vBESize2 = new Integer(vBESize); m_classReq.setAttribute("vBESize", vBESize2); String sRep_IDSEQ = ""; if (vBERows.size() > 0) { // Be sure the buffer is loaded when doing versioning. String newVersion = VDBean.getVD_VERSION(); if (newVersion == null) newVersion = ""; boolean newVers = (newVersion.equals("Point") || newVersion.equals("Whole")); if (newVers) { @SuppressWarnings("unchecked") Vector<AC_Bean> tvec = vBERows; AltNamesDefsSession.loadAsNew(this, session, tvec); } for (int i = 0; i < (vBERows.size()); i++) { // String sVD_ID = ""; //out VD_Bean VDBeanSR = new VD_Bean(); VDBeanSR = (VD_Bean) vBERows.elementAt(i); VD_Bean oldVDBean = new VD_Bean(); oldVDBean = oldVDBean.cloneVD_Bean(VDBeanSR); // String oldName = (String) VDBeanSR.getVD_PREFERRED_NAME(); // updates the data from the page into the sr bean InsertEditsIntoVDBeanSR(VDBeanSR, VDBean); // create newly selected rep term if (i == 0 && sNewRep.equals("true")) { doInsertVDBlocks(VDBeanSR); // create it sRep_IDSEQ = VDBeanSR.getVD_REP_IDSEQ(); // get rep idseq if (sRep_IDSEQ == null) sRep_IDSEQ = ""; VDBean.setVD_REP_IDSEQ(sRep_IDSEQ); // add page vd bean String sRep_Condr = VDBeanSR.getVD_REP_CONDR_IDSEQ(); // get rep condr if (sRep_Condr == null) sRep_Condr = ""; VDBean.setVD_REP_CONDR_IDSEQ(sRep_Condr); // add to page vd bean // VDBean.setVD_REP_QUAL(""); } // DataManager.setAttribute(session, "m_VD", VDBeanSR); String oldID = oldVDBean.getVD_VD_IDSEQ(); // udpate the status message with DE name and ID storeStatusMsg("Value Domain Name : " + VDBeanSR.getVD_LONG_NAME()); storeStatusMsg("Public ID : " + VDBeanSR.getVD_VD_ID()); // insert the version if (newVers) // block version { // creates new version first and updates all other attributes String strValid = m_setAC.checkUniqueInContext("Version", "VD", null, null, VDBeanSR, getAC, "version"); if (strValid != null && !strValid.equals("")) ret = "unique constraint"; else ret = insAC.setAC_VERSION(null, null, VDBeanSR, "ValueDomain"); if (ret == null || ret.equals("")) { // PVServlet pvser = new PVServlet(req, res, this); // pvser.searchVersionPV(VDBean, 0, "", ""); // get the right system name for new version String prefName = VDBeanSR.getVD_PREFERRED_NAME(); String vdID = VDBeanSR.getVD_VD_ID(); String newVer = "v" + VDBeanSR.getVD_VERSION(); String oldVer = "v" + oldVDBean.getVD_VERSION(); // replace teh version number if system generated name if (prefName.indexOf(vdID) > 0) { prefName = prefName.replaceFirst(oldVer, newVer); VDBean.setVD_PREFERRED_NAME(prefName); } // keep the value and value count stored String pvValue = VDBeanSR.getVD_Permissible_Value(); Integer pvCount = VDBeanSR.getVD_Permissible_Value_Count(); ret = insAC.setVD("UPD", VDBeanSR, "Version", oldVDBean); if (ret == null || ret.equals("")) { VDBeanSR.setVD_Permissible_Value(pvValue); VDBeanSR.setVD_Permissible_Value_Count(pvCount); serAC.refreshData(m_classReq, m_classRes, null, null, VDBeanSR, null, "Version", oldID); isRefreshed = true; // reset the appened attributes to remove all the checking of the row Vector vCheck = new Vector(); DataManager.setAttribute(session, "CheckList", vCheck); DataManager.setAttribute(session, "AppendAction", "Not Appended"); // resetEVSBeans(req, res); } } // alerady exists else if (ret.indexOf("unique constraint") >= 0) storeStatusMsg("\\t New version " + VDBeanSR.getVD_VERSION() + " already exists in the data base.\\n"); // some other problem else storeStatusMsg("\\t " + ret + " : Unable to create new version " + VDBeanSR.getVD_VERSION() + ".\\n"); } else // block edit { ret = insAC.setVD("UPD", VDBeanSR, "Edit", oldVDBean); // forward to search page with refreshed list after successful update if ((ret == null) || ret.equals("")) { serAC.refreshData(m_classReq, m_classRes, null, null, VDBeanSR, null, "Edit", oldID); isRefreshed = true; } } } AltNamesDefsSession.blockSave(this, session); } // to get the final result vector if not refreshed at all if (!(isRefreshed)) { Vector<String> vResult = new Vector<String>(); serAC.getVDResult(m_classReq, m_classRes, vResult, ""); DataManager.setAttribute(session, "results", vResult); // store the final result in the session DataManager.setAttribute(session, "VDPageAction", "nothing"); } ForwardJSP(m_classReq, m_classRes, "/SearchResultsPage.jsp"); } /** * updates bean the selected VD from the changed values of block edit. * * @param VDBeanSR * selected vd bean from search result * @param vd * VD_Bean of the changed values. * * @throws Exception */ private void InsertEditsIntoVDBeanSR(VD_Bean VDBeanSR, VD_Bean vd) throws Exception { // get all attributes of VDBean, if attribute != "" then set that attribute of VDBeanSR String sDefinition = vd.getVD_PREFERRED_DEFINITION(); if (sDefinition == null) sDefinition = ""; if (!sDefinition.equals("")) VDBeanSR.setVD_PREFERRED_DEFINITION(sDefinition); String sCD_ID = vd.getVD_CD_IDSEQ(); if (sCD_ID == null) sCD_ID = ""; if (!sCD_ID.equals("") && !sCD_ID.equals(null)) VDBeanSR.setVD_CD_IDSEQ(sCD_ID); String sCDName = vd.getVD_CD_NAME(); if (sCDName == null) sCDName = ""; if (!sCDName.equals("") && !sCDName.equals(null)) VDBeanSR.setVD_CD_NAME(sCDName); String sAslName = vd.getVD_ASL_NAME(); if (sAslName == null) sAslName = ""; if (!sAslName.equals("")) VDBeanSR.setVD_ASL_NAME(sAslName); String sDtlName = vd.getVD_DATA_TYPE(); if (sDtlName == null) sDtlName = ""; if (!sDtlName.equals("")) VDBeanSR.setVD_DATA_TYPE(sDtlName); String sMaxLength = vd.getVD_MAX_LENGTH_NUM(); if (sMaxLength == null) sMaxLength = ""; if (!sMaxLength.equals("")) VDBeanSR.setVD_MAX_LENGTH_NUM(sMaxLength); String sFormlName = vd.getVD_FORML_NAME(); // UOM Format if (sFormlName == null) sFormlName = ""; if (!sFormlName.equals("")) VDBeanSR.setVD_FORML_NAME(sFormlName); String sUomlName = vd.getVD_UOML_NAME(); if (sUomlName == null) sUomlName = ""; if (!sUomlName.equals("")) VDBeanSR.setVD_UOML_NAME(sUomlName); String sLowValue = vd.getVD_LOW_VALUE_NUM(); if (sLowValue == null) sLowValue = ""; if (!sLowValue.equals("")) VDBeanSR.setVD_LOW_VALUE_NUM(sLowValue); String sHighValue = vd.getVD_HIGH_VALUE_NUM(); if (sHighValue == null) sHighValue = ""; if (!sHighValue.equals("")) VDBeanSR.setVD_HIGH_VALUE_NUM(sHighValue); String sMinLength = vd.getVD_MIN_LENGTH_NUM(); if (sMinLength == null) sMinLength = ""; if (!sMinLength.equals("")) VDBeanSR.setVD_MIN_LENGTH_NUM(sMinLength); String sDecimalPlace = vd.getVD_DECIMAL_PLACE(); if (sDecimalPlace == null) sDecimalPlace = ""; if (!sDecimalPlace.equals("")) VDBeanSR.setVD_DECIMAL_PLACE(sDecimalPlace); String sBeginDate = vd.getVD_BEGIN_DATE(); if (sBeginDate == null) sBeginDate = ""; if (!sBeginDate.equals("")) VDBeanSR.setVD_BEGIN_DATE(sBeginDate); String sEndDate = vd.getVD_END_DATE(); if (sEndDate == null) sEndDate = ""; if (!sEndDate.equals("")) VDBeanSR.setVD_END_DATE(sEndDate); String sSource = vd.getVD_SOURCE(); if (sSource == null) sSource = ""; if (!sSource.equals("")) VDBeanSR.setVD_SOURCE(sSource); String changeNote = vd.getVD_CHANGE_NOTE(); if (changeNote == null) changeNote = ""; if (!changeNote.equals("")) VDBeanSR.setVD_CHANGE_NOTE(changeNote); // get cs-csi from the page into the DECBean for block edit Vector vAC_CS = vd.getAC_AC_CSI_VECTOR(); if (vAC_CS != null) VDBeanSR.setAC_AC_CSI_VECTOR(vAC_CS); //get the Ref docs from the page into the DEBean for block edit Vector<REF_DOC_Bean> vAC_REF_DOCS = vd.getAC_REF_DOCS(); if(vAC_REF_DOCS!=null){ Vector<REF_DOC_Bean> temp_REF_DOCS = new Vector<REF_DOC_Bean>(); for(REF_DOC_Bean refBean:vAC_REF_DOCS ) { if(refBean.getAC_IDSEQ() == VDBeanSR.getVD_VD_IDSEQ()) { temp_REF_DOCS.add(refBean); } } VDBeanSR.setAC_REF_DOCS(temp_REF_DOCS); } String sRepTerm = vd.getVD_REP_TERM(); if (sRepTerm == null) sRepTerm = ""; if (!sRepTerm.equals("")) VDBeanSR.setVD_REP_TERM(sRepTerm); String sRepCondr = vd.getVD_REP_CONDR_IDSEQ(); if (sRepCondr == null) sRepCondr = ""; if (!sRepCondr.equals("")) VDBeanSR.setVD_REP_CONDR_IDSEQ(sRepCondr); String sREP_IDSEQ = vd.getVD_REP_IDSEQ(); if (sREP_IDSEQ != null && !sREP_IDSEQ.equals("")) VDBeanSR.setVD_REP_IDSEQ(sREP_IDSEQ); /* * String sRepQual = vd.getVD_REP_QUAL(); if (sRepQual == null) sRepQual = ""; if (!sRepQual.equals("")) * VDBeanSR.setVD_REP_QUAL(sRepQual); */ String version = vd.getVD_VERSION(); String lastVersion = (String) VDBeanSR.getVD_VERSION(); int index = -1; String pointStr = "."; String strWhBegNumber = ""; int iWhBegNumber = 0; index = lastVersion.indexOf(pointStr); String strPtBegNumber = lastVersion.substring(0, index); String afterDecimalNumber = lastVersion.substring((index + 1), (index + 2)); if (index == 1) strWhBegNumber = ""; else if (index == 2) { strWhBegNumber = lastVersion.substring(0, index - 1); Integer WhBegNumber = new Integer(strWhBegNumber); iWhBegNumber = WhBegNumber.intValue(); } String strWhEndNumber = ".0"; String beforeDecimalNumber = lastVersion.substring((index - 1), (index)); String sNewVersion = ""; Integer IadNumber = new Integer(0); Integer IbdNumber = new Integer(0); String strIncADNumber = ""; String strIncBDNumber = ""; if (version == null) version = ""; else if (version.equals("Point")) { // Point new version int incrementADNumber = 0; int incrementBDNumber = 0; Integer adNumber = new Integer(afterDecimalNumber); Integer bdNumber = new Integer(strPtBegNumber); int iADNumber = adNumber.intValue(); // after decimal int iBDNumber = bdNumber.intValue(); // before decimal if (iADNumber != 9) { incrementADNumber = iADNumber + 1; IadNumber = new Integer(incrementADNumber); strIncADNumber = IadNumber.toString(); sNewVersion = strPtBegNumber + "." + strIncADNumber; // + strPtEndNumber; } else // adNumber == 9 { incrementADNumber = 0; incrementBDNumber = iBDNumber + 1; IbdNumber = new Integer(incrementBDNumber); strIncBDNumber = IbdNumber.toString(); IadNumber = new Integer(incrementADNumber); strIncADNumber = IadNumber.toString(); sNewVersion = strIncBDNumber + "." + strIncADNumber; // + strPtEndNumber; } VDBeanSR.setVD_VERSION(sNewVersion); } else if (version.equals("Whole")) { // Whole new version Integer bdNumber = new Integer(beforeDecimalNumber); int iBDNumber = bdNumber.intValue(); int incrementBDNumber = iBDNumber + 1; if (iBDNumber != 9) { IbdNumber = new Integer(incrementBDNumber); strIncBDNumber = IbdNumber.toString(); sNewVersion = strWhBegNumber + strIncBDNumber + strWhEndNumber; } else // before decimal number == 9 { int incrementWhBegNumber = iWhBegNumber + 1; Integer IWhBegNumber = new Integer(incrementWhBegNumber); String strIncWhBegNumber = IWhBegNumber.toString(); IbdNumber = new Integer(0); strIncBDNumber = IbdNumber.toString(); sNewVersion = strIncWhBegNumber + strIncBDNumber + strWhEndNumber; } VDBeanSR.setVD_VERSION(sNewVersion); } } /** * creates new record in the database and display the result. Called from 'doInsertVD' method when the aciton is * create new VD from DEPage. Retrieves the session bean m_VD. calls 'insAC.setVD' to update the database. forwards * the page back to create DE page after successful insert. * * If ret is not null stores the statusMessage as error message in session and forwards the page back to * 'createVDPage.jsp' for Edit. * * @param sOrigin * string value from where vd creation action was originated. * * @throws Exception */ private void doInsertVDfromDEAction(String sOrigin) throws Exception { HttpSession session = m_classReq.getSession(); VD_Bean VDBean = (VD_Bean) session.getAttribute("m_VD"); InsACService insAC = new InsACService(m_classReq, m_classRes, this); // GetACSearch serAC = new GetACSearch(req, res, this); // String sMenu = (String) session.getAttribute(Session_Data.SESSION_MENU_ACTION); // insert the building blocks attriubtes before inserting vd doInsertVDBlocks(null); String ret = insAC.setVD("INS", VDBean, "New", null); // updates the de bean with new vd data after successful insert and forwards to create page if ((ret == null) || ret.equals("")) { DE_Bean DEBean = (DE_Bean) session.getAttribute("m_DE"); DEBean.setDE_VD_NAME(VDBean.getVD_LONG_NAME()); DEBean.setDE_VD_IDSEQ(VDBean.getVD_VD_IDSEQ()); // add DEC Bean into DE BEan DEBean.setDE_VD_Bean(VDBean); DataManager.setAttribute(session, "m_DE", DEBean); CurationServlet deServ = (DataElementServlet) getACServlet("DataElement"); DEBean = (DE_Bean) deServ.getACNames("new", "newVD", DEBean); this.clearCreateSessionAttributes(m_classReq, m_classRes); // clear some session attributes if (sOrigin != null && sOrigin.equals("CreateNewVDfromEditDE")) ForwardJSP(m_classReq, m_classRes, "/EditDEPage.jsp"); else ForwardJSP(m_classReq, m_classRes, "/CreateDEPage.jsp"); } // goes back to create vd page if error else { DataManager.setAttribute(session, "VDPageAction", "validate"); ForwardJSP(m_classReq, m_classRes, "/CreateVDPage.jsp"); // send it back to vd page } } /** * to create rep term and qualifier value from EVS into cadsr. Retrieves the session bean * m_VD. calls 'insAC.setDECQualifier' to insert the database. * * @param VDBeanSR * dec attribute bean. * * @throws Exception */ private void doInsertVDBlocks(VD_Bean VDBeanSR) throws Exception { HttpSession session = m_classReq.getSession(); if (VDBeanSR == null) VDBeanSR = (VD_Bean) session.getAttribute("m_VD"); ValidationStatusBean repStatusBean = new ValidationStatusBean(); Vector vRepTerm = (Vector) session.getAttribute("vRepTerm"); InsACService insAC = new InsACService(m_classReq, m_classRes, this); String userName = (String)session.getAttribute("Username"); HashMap<String, String> defaultContext = (HashMap)session.getAttribute("defaultContext"); String conteIdseq= (String)defaultContext.get("idseq"); try { if ((vRepTerm != null && vRepTerm.size() > 0) && (defaultContext != null && defaultContext.size() > 0)) { repStatusBean = insAC.evsBeanCheck(vRepTerm, defaultContext, "", "Representation Term"); } // set Rep if it is null if ((vRepTerm != null && vRepTerm.size() > 0)) { if (!repStatusBean.isEvsBeanExists()) { if (repStatusBean.isCondrExists()) { VDBeanSR.setVD_REP_CONDR_IDSEQ(repStatusBean.getCondrIDSEQ()); // Create Representation Term String repIdseq = insAC.createEvsBean(userName, repStatusBean.getCondrIDSEQ(), conteIdseq, "Representation Term"); if (repIdseq != null && !repIdseq.equals("")) { VDBeanSR.setVD_REP_IDSEQ(repIdseq); } } else { // Create Condr String condrIdseq = insAC.createCondr(vRepTerm, repStatusBean.isAllConceptsExists()); String repIdseq = ""; // Create Representation Term if (condrIdseq != null && !condrIdseq.equals("")) { VDBeanSR.setVD_REP_CONDR_IDSEQ(condrIdseq); repIdseq = insAC.createEvsBean(userName, condrIdseq, conteIdseq, "Representation Term"); } if (repIdseq != null && !repIdseq.equals("")) { VDBeanSR.setVD_REP_IDSEQ(repIdseq); } } } else { if (repStatusBean.isNewVersion()) { if (repStatusBean.getEvsBeanIDSEQ() != null && !repStatusBean.getEvsBeanIDSEQ().equals("")) { String newID = ""; newID = insAC.setOC_PROP_REP_VERSION(repStatusBean.getEvsBeanIDSEQ(), "RepTerm"); if (newID != null && !newID.equals("")) { VDBeanSR.setVD_REP_CONDR_IDSEQ(repStatusBean.getCondrIDSEQ()); VDBeanSR.setVD_REP_IDSEQ(newID); } } }else{ VDBeanSR.setVD_REP_CONDR_IDSEQ(repStatusBean.getCondrIDSEQ()); VDBeanSR.setVD_REP_IDSEQ(repStatusBean.getEvsBeanIDSEQ()); } } } m_classReq.setAttribute("REP_IDSEQ", repStatusBean.getEvsBeanIDSEQ()); } catch (Exception e) { logger.error("ERROR in ValueDoaminServlet-doInsertVDBlocks : " + e.toString(), e); m_classReq.setAttribute("retcode", "Exception"); this.storeStatusMsg("\\t Exception : Unable to update or remove Representation Term."); } DataManager.setAttribute(session, "newRepTerm", ""); } /** * creates new record in the database and display the result. Called from 'doInsertVD' method when the aciton is * create new VD from Menu. Retrieves the session bean m_VD. calls 'insAC.setVD' to update the database. calls * 'serAC.refreshData' to get the refreshed search result for template/version forwards the page back to create VD * page if new VD or back to search page if template or version after successful insert. * * If ret is not null stores the statusMessage as error message in session and forwards the page back to * 'createVDPage.jsp' for Edit. * * @throws Exception */ private void doInsertVDfromMenuAction() throws Exception { HttpSession session = m_classReq.getSession(); VD_Bean VDBean = (VD_Bean) session.getAttribute("m_VD"); InsACService insAC = new InsACService(m_classReq, m_classRes, this); GetACSearch serAC = new GetACSearch(m_classReq, m_classRes, this); String sMenuAction = (String) session.getAttribute(Session_Data.SESSION_MENU_ACTION); VD_Bean oldVDBean = (VD_Bean) session.getAttribute("oldVDBean"); if (oldVDBean == null) oldVDBean = new VD_Bean(); String ret = ""; boolean isUpdateSuccess = true; doInsertVDBlocks(null); if (sMenuAction.equals("NewVDVersion")) { // udpate the status message with DE name and ID storeStatusMsg("Value Domain Name : " + VDBean.getVD_LONG_NAME()); storeStatusMsg("Public ID : " + VDBean.getVD_VD_ID()); // creates new version first ret = insAC.setAC_VERSION(null, null, VDBean, "ValueDomain"); if (ret == null || ret.equals("")) { // get pvs related to this new VD, it was created in VD_Version // TODO serAC.doPVACSearch(VDBean.getVD_VD_IDSEQ(), VDBean.getVD_LONG_NAME(), "Version"); PVServlet pvser = new PVServlet(m_classReq, m_classRes, this); pvser.searchVersionPV(VDBean, 1, "", ""); // update non evs changes Vector<EVS_Bean> vParent = VDBean.getReferenceConceptList(); // (Vector)session.getAttribute("VDParentConcept"); if (vParent != null && vParent.size() > 0) vParent = serAC.getNonEVSParent(vParent, VDBean, "versionSubmit"); // get the right system name for new version; cannot use teh api because parent concept is not updated // yet String prefName = VDBean.getVD_PREFERRED_NAME(); if (prefName == null || prefName.equalsIgnoreCase("(Generated by the System)")) { VDBean = (VD_Bean) this.getSystemName(VDBean, vParent); VDBean.setVD_PREFERRED_NAME(VDBean.getAC_SYS_PREF_NAME()); } // and updates all other attributes ret = insAC.setVD("UPD", VDBean, "Version", oldVDBean); // resetEVSBeans(req, res); if (ret != null && !ret.equals("")) { // add newly created row to searchresults and send it to edit page for update isUpdateSuccess = false; String oldID = oldVDBean.getVD_VD_IDSEQ(); String newID = VDBean.getVD_VD_IDSEQ(); String newVersion = VDBean.getVD_VERSION(); VDBean = VDBean.cloneVD_Bean(oldVDBean); VDBean.setVD_VD_IDSEQ(newID); VDBean.setVD_VERSION(newVersion); VDBean.setVD_ASL_NAME("DRAFT MOD"); // refresh the result list by inserting newly created VD serAC.refreshData(m_classReq, m_classRes, null, null, VDBean, null, "Version", oldID); } } else storeStatusMsg("\\t " + ret + " - Unable to create new version successfully."); } else { // creates new one ret = insAC.setVD("INS", VDBean, "New", oldVDBean); // create new one } if ((ret == null) || ret.equals("")) { this.clearCreateSessionAttributes(m_classReq, m_classRes); // clear some session attributes DataManager.setAttribute(session, "VDPageAction", "nothing"); DataManager.setAttribute(session, "originAction", ""); // forwards to search page with refreshed list if template or version if ((sMenuAction.equals("NewVDTemplate")) || (sMenuAction.equals("NewVDVersion"))) { DataManager.setAttribute(session, "searchAC", "ValueDomain"); DataManager.setAttribute(session, "originAction", "NewVDTemplate"); VDBean.setVD_ALIAS_NAME(VDBean.getVD_PREFERRED_NAME()); // VDBean.setVD_TYPE_NAME("PRIMARY"); String oldID = oldVDBean.getVD_VD_IDSEQ(); if (sMenuAction.equals("NewVDTemplate")) serAC.refreshData(m_classReq, m_classRes, null, null, VDBean, null, "Template", oldID); else if (sMenuAction.equals("NewVDVersion")) serAC.refreshData(m_classReq, m_classRes, null, null, VDBean, null, "Version", oldID); ForwardJSP(m_classReq, m_classRes, "/SearchResultsPage.jsp"); } // forward to create vd page with empty data if new one else { doOpenCreateNewPages(); } } // goes back to create/edit vd page if error else { DataManager.setAttribute(session, "VDPageAction", "validate"); // forward to create or edit pages if (isUpdateSuccess == false) { // insert the created NUE in the results. String oldID = oldVDBean.getVD_VD_IDSEQ(); if (sMenuAction.equals("NewVDTemplate")) serAC.refreshData(m_classReq, m_classRes, null, null, VDBean, null, "Template", oldID); ForwardJSP(m_classReq, m_classRes, "/SearchResultsPage.jsp"); } else ForwardJSP(m_classReq, m_classRes, "/CreateVDPage.jsp"); } } /** * The doOpenCreateVDPage method gets the session, gets some values from the createDE page and stores in bean m_DE, * sets some session attributes, then forwards to CreateVD page * * @throws Exception */ public void doOpenCreateVDPage() throws Exception { HttpSession session = m_classReq.getSession(); DE_Bean m_DE = (DE_Bean) session.getAttribute("m_DE"); if (m_DE == null) m_DE = new DE_Bean(); m_setAC.setDEValueFromPage(m_classReq, m_classRes, m_DE); // store VD bean DataManager.setAttribute(session, "m_DE", m_DE); // clear some session attributes this.clearCreateSessionAttributes(m_classReq, m_classRes); // reset the vd attributes VD_Bean m_VD = new VD_Bean(); m_VD.setVD_ASL_NAME("DRAFT NEW"); m_VD.setAC_PREF_NAME_TYPE("SYS"); // call the method to get the QuestValues if exists String sMenuAction = (String) session.getAttribute(Session_Data.SESSION_MENU_ACTION); if (sMenuAction.equals("Questions")) { GetACSearch serAC = new GetACSearch(m_classReq, m_classRes, this); serAC.getACQuestionValue(m_VD); // check if enumerated or not Vector vCRFval = (Vector) session.getAttribute("vQuestValue"); if (vCRFval != null && vCRFval.size() > 0) m_VD.setVD_TYPE_FLAG("E"); else m_VD.setVD_TYPE_FLAG("N"); // read property file and set the VD bean for Placeholder data String VDDefinition = NCICurationServlet.m_settings.getProperty("VDDefinition"); m_VD.setVD_PREFERRED_DEFINITION(VDDefinition); String DataType = NCICurationServlet.m_settings.getProperty("DataType"); m_VD.setVD_DATA_TYPE(DataType); String MaxLength = NCICurationServlet.m_settings.getProperty("MaxLength"); m_VD.setVD_MAX_LENGTH_NUM(MaxLength); } DataManager.setAttribute(session, "m_VD", m_VD); VD_Bean oldVD = new VD_Bean(); oldVD = oldVD.cloneVD_Bean(m_VD); DataManager.setAttribute(session, "oldVDBean", oldVD); // DataManager.setAttribute(session, "oldVDBean", m_VD); ForwardJSP(m_classReq, m_classRes, "/CreateVDPage.jsp"); } /** * * @throws Exception * */ private void doRemoveBuildingBlocksVD() throws Exception { HttpSession session = m_classReq.getSession(); String sSelRow = ""; VD_Bean m_VD = (VD_Bean) session.getAttribute("m_VD"); if (m_VD == null) m_VD = new VD_Bean(); Vector<EVS_Bean> vRepTerm = (Vector) session.getAttribute("vRepTerm"); if (vRepTerm == null) vRepTerm = new Vector<EVS_Bean>(); String sComp = (String) m_classReq.getParameter("sCompBlocks"); if (sComp == null) sComp = ""; if (sComp.equals("RepTerm")) { EVS_Bean m_REP = new EVS_Bean(); vRepTerm.setElementAt(m_REP, 0); DataManager.setAttribute(session, "vRepTerm", vRepTerm); m_VD.setVD_REP_NAME_PRIMARY(""); m_VD.setVD_REP_CONCEPT_CODE(""); m_VD.setVD_REP_EVS_CUI_ORIGEN(""); m_VD.setVD_REP_IDSEQ(""); DataManager.setAttribute(session, "RemoveRepBlock", "true"); DataManager.setAttribute(session, "newRepTerm", "true"); } else if (sComp.equals("RepQualifier")) { sSelRow = (String) m_classReq.getParameter("selRepQRow"); if (sSelRow != null && !(sSelRow.equals(""))) { Integer intObjRow = new Integer(sSelRow); int intObjRow2 = intObjRow.intValue(); if (vRepTerm.size() > (intObjRow2 + 1)) { vRepTerm.removeElementAt(intObjRow2 + 1); // add 1 so zero element not removed DataManager.setAttribute(session, "vRepTerm", vRepTerm); } // m_VD.setVD_REP_QUAL(""); Vector vRepQualifierNames = m_VD.getVD_REP_QUALIFIER_NAMES(); if (vRepQualifierNames == null) vRepQualifierNames = new Vector(); if (vRepQualifierNames.size() > intObjRow2) vRepQualifierNames.removeElementAt(intObjRow2); Vector vRepQualifierCodes = m_VD.getVD_REP_QUALIFIER_CODES(); if (vRepQualifierCodes == null) vRepQualifierCodes = new Vector(); if (vRepQualifierCodes.size() > intObjRow2) vRepQualifierCodes.removeElementAt(intObjRow2); Vector vRepQualifierDB = m_VD.getVD_REP_QUALIFIER_DB(); if (vRepQualifierDB == null) vRepQualifierDB = new Vector(); if (vRepQualifierDB.size() > intObjRow2) vRepQualifierDB.removeElementAt(intObjRow2); m_VD.setVD_REP_QUALIFIER_NAMES(vRepQualifierNames); m_VD.setVD_REP_QUALIFIER_CODES(vRepQualifierCodes); m_VD.setVD_REP_QUALIFIER_DB(vRepQualifierDB); DataManager.setAttribute(session, "RemoveRepBlock", "true"); DataManager.setAttribute(session, "newRepTerm", "true"); } } else if (sComp.equals("VDObjectClass")) { m_VD.setVD_OBJ_CLASS(""); DataManager.setAttribute(session, "m_OC", new EVS_Bean()); } else if (sComp.equals("VDPropertyClass")) { m_VD.setVD_PROP_CLASS(""); DataManager.setAttribute(session, "m_PC", new EVS_Bean()); } if (sComp.equals("RepTerm") || sComp.equals("RepQualifier")){ vRepTerm = (Vector)session.getAttribute("vRepTerm"); if (vRepTerm != null && vRepTerm.size() > 0){ vRepTerm = this.getMatchingThesarusconcept(vRepTerm, "Representation Term"); m_VD = this.updateRepAttribues(vRepTerm, m_VD); } DataManager.setAttribute(session, "vRepTerm", vRepTerm); } m_setAC.setVDValueFromPage(m_classReq, m_classRes, m_VD); DataManager.setAttribute(session, "m_VD", m_VD); } // end of doRemoveQualifier /**method to go back from vd and pv edits * @param orgAct String value for origin where vd page was opened * @param menuAct String value of menu action where this use case started * @param actype String what action is expected * @param butPress STring last button pressed * @param vdPageFrom string to check if it was PV or VD page * @return String jsp to forward the page to */ public String goBackfromVD(String orgAct, String menuAct, String actype, String butPress, String vdPageFrom) { try { //forward the page to editDE if originated from DE HttpSession session = m_classReq.getSession(); clearBuildingBlockSessionAttributes(m_classReq, m_classRes); if (vdPageFrom.equals("create")) { clearCreateSessionAttributes(m_classReq, m_classRes); if (menuAct.equals("NewVDTemplate") || menuAct.equals("NewVDVersion")) { VD_Bean VDBean = (VD_Bean)session.getAttribute(PVForm.SESSION_SELECT_VD); GetACSearch serAC = new GetACSearch(m_classReq, m_classRes, this); serAC.refreshData(m_classReq, m_classRes, null, null, VDBean, null, "Refresh", ""); return "/SearchResultsPage.jsp"; } else if (orgAct.equalsIgnoreCase("CreateNewVDfromEditDE")) return "/EditDEPage.jsp"; else return "/CreateDEPage.jsp"; } else if (vdPageFrom.equals("edit")) { if (orgAct.equalsIgnoreCase("editVDfromDE")) return "/EditDEPage.jsp"; //forward the page to search if originated from Search else if (menuAct.equalsIgnoreCase("editVD") || orgAct.equalsIgnoreCase("EditVD") || orgAct.equalsIgnoreCase("BlockEditVD") || (butPress.equals("Search") && !actype.equals("DataElement"))) { VD_Bean VDBean = (VD_Bean)session.getAttribute(PVForm.SESSION_SELECT_VD); if (VDBean == null) VDBean = new VD_Bean(); GetACSearch serAC = new GetACSearch(m_classReq, m_classRes, this); serAC.refreshData(m_classReq, m_classRes, null, null, VDBean, null, "Refresh", ""); return "/SearchResultsPage.jsp"; } else return "/EditVDPage.jsp"; } } catch (Exception e) { logger.error("ERROR - ", e); } return ""; } /** to clear the edited data from the edit and create pages * @param orgAct String value for origin where vd page was opened * @param menuAct String value of menu action where this use case started * @return String jsp to forward the page to */ public String clearEditsOnPage(String orgAct, String menuAct) { try { HttpSession session = m_classReq.getSession(); VD_Bean VDBean = (VD_Bean)session.getAttribute("oldVDBean"); //clear related the session attributes clearBuildingBlockSessionAttributes(m_classReq, m_classRes); String sVDID = VDBean.getVD_VD_IDSEQ(); Vector vList = new Vector(); //get VD's attributes from the database again GetACSearch serAC = new GetACSearch(m_classReq, m_classRes, this); if (sVDID != null && !sVDID.equals("")) serAC.doVDSearch(sVDID, "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", 0, "", "", "", "", "", "", "", "",vList); //forward editVD page with this bean if (vList.size() > 0) { VDBean = (VD_Bean)vList.elementAt(0); VDBean = serAC.getVDAttributes(VDBean, orgAct, menuAct); } else { VDBean = new VD_Bean(); VDBean.setVD_ASL_NAME("DRAFT NEW"); VDBean.setAC_PREF_NAME_TYPE("SYS"); } VD_Bean pgBean = new VD_Bean(); DataManager.setAttribute(session, PVForm.SESSION_SELECT_VD, pgBean.cloneVD_Bean(VDBean)); } catch (Exception e) { logger.error("ERROR - ", e); } return "/CreateVDPage.jsp"; } public void doOpenViewPage() throws Exception { //System.out.println("I am here open view page"); HttpSession session = m_classReq.getSession(); String acID = (String) m_classReq.getAttribute("acIdseq"); if (acID.equals("")) acID = m_classReq.getParameter("idseq"); Vector<VD_Bean> vList = new Vector<VD_Bean>(); // get DE's attributes from the database again GetACSearch serAC = new GetACSearch(m_classReq, m_classRes, this); if (acID != null && !acID.equals("")) { serAC.doVDSearch(acID, "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", 0, "", "", "", "", "", "", "", "", vList); } if (vList.size() > 0) // get all attributes { VD_Bean VDBean = (VD_Bean) vList.elementAt(0); VDBean = serAC.getVDAttributes(VDBean, "openView", "viewVD"); DataManager.setAttribute(session, "TabFocus", "VD"); m_classReq.setAttribute("viewVDId", VDBean.getIDSEQ()); String viewVD = "viewVD" + VDBean.getIDSEQ(); DataManager.setAttribute(session, viewVD, VDBean); String title = "CDE Curation View VD "+VDBean.getVD_LONG_NAME()+ " [" + VDBean.getVD_VD_ID() + "v" + VDBean.getVD_VERSION() +"]"; m_classReq.setAttribute("title", title); m_classReq.setAttribute("publicID", VDBean.getVD_VD_ID()); m_classReq.setAttribute("version", VDBean.getVD_VERSION()); m_classReq.setAttribute("IncludeViewPage", "EditVD.jsp") ; } } public void doViewPageTab() throws Exception{ String tab = m_classReq.getParameter("vdpvstab"); String from = m_classReq.getParameter("from"); String id = m_classReq.getParameter("id"); String viewVD = "viewVD" + id; HttpSession session = m_classReq.getSession(); VD_Bean VDBean = (VD_Bean)session.getAttribute(viewVD); String publicId = VDBean.getVD_VD_ID(); String version = VDBean.getVD_VERSION(); m_classReq.setAttribute("viewVDId", id); String title = "CDE Curation View VD "+VDBean.getVD_LONG_NAME()+ " [" + VDBean.getVD_VD_ID() + "v" + VDBean.getVD_VERSION() +"]"; m_classReq.setAttribute("title", title); m_classReq.setAttribute("publicID", VDBean.getVD_VD_ID()); m_classReq.setAttribute("version", VDBean.getVD_VERSION()); DataManager.setAttribute(session, "VDAction", ""); if (from.equals("edit")){ m_classReq.getSession().setAttribute("displayErrorMessage", "Yes"); } if (tab != null && tab.equals("PV")) { DataManager.setAttribute(session, "TabFocus", "PV"); m_classReq.setAttribute("IncludeViewPage", "PermissibleValue.jsp") ; ForwardJSP(m_classReq, m_classRes, "/ViewPage.jsp"); }else{ DataManager.setAttribute(session, "TabFocus", "VD"); m_classReq.setAttribute("IncludeViewPage", "EditVD.jsp") ; ForwardJSP(m_classReq, m_classRes, "/ViewPage.jsp"); } } private VD_Bean updateRepAttribues(Vector vRep, VD_Bean vdBean) { HttpSession session = m_classReq.getSession(); // add rep primary attributes to the vd bean EVS_Bean pBean =(EVS_Bean)vRep.get(0); vdBean.setVD_REP_NAME_PRIMARY(pBean.getLONG_NAME()); vdBean.setVD_REP_CONCEPT_CODE(pBean.getCONCEPT_IDENTIFIER()); vdBean.setVD_REP_EVS_CUI_ORIGEN(pBean.getEVS_DATABASE()); vdBean.setVD_REP_IDSEQ(pBean.getIDSEQ()); DataManager.setAttribute(session, "m_REP", pBean); // update qualifier vectors vdBean.setVD_REP_QUALIFIER_NAMES(null); vdBean.setVD_REP_QUALIFIER_CODES(null); vdBean.setVD_REP_QUALIFIER_DB(null); for (int i=1; i<vRep.size();i++){ EVS_Bean eBean =(EVS_Bean)vRep.get(i); // add rep qualifiers to the vector Vector<String> vRepQualifierNames = vdBean.getVD_REP_QUALIFIER_NAMES(); if (vRepQualifierNames == null) vRepQualifierNames = new Vector<String>(); vRepQualifierNames.addElement(eBean.getLONG_NAME()); Vector<String> vRepQualifierCodes = vdBean.getVD_REP_QUALIFIER_CODES(); if (vRepQualifierCodes == null) vRepQualifierCodes = new Vector<String>(); vRepQualifierCodes.addElement(eBean.getCONCEPT_IDENTIFIER()); Vector<String> vRepQualifierDB = vdBean.getVD_REP_QUALIFIER_DB(); if (vRepQualifierDB == null) vRepQualifierDB = new Vector<String>(); vRepQualifierDB.addElement(eBean.getEVS_DATABASE()); vdBean.setVD_REP_QUALIFIER_NAMES(vRepQualifierNames); vdBean.setVD_REP_QUALIFIER_CODES(vRepQualifierCodes); vdBean.setVD_REP_QUALIFIER_DB(vRepQualifierDB); // if(vRepQualifierNames.size()>0) // vdBean.setVD_REP_QUAL((String)vRepQualifierNames.elementAt(0)); DataManager.setAttribute(session, "vRepQResult", null); DataManager.setAttribute(session, "m_REPQ", eBean); } return vdBean; } }
diff --git a/hk2/hk2-locator/src/main/java/org/jvnet/hk2/internal/SingletonContext.java b/hk2/hk2-locator/src/main/java/org/jvnet/hk2/internal/SingletonContext.java index 8c35bd420..d0a3fe24b 100644 --- a/hk2/hk2-locator/src/main/java/org/jvnet/hk2/internal/SingletonContext.java +++ b/hk2/hk2-locator/src/main/java/org/jvnet/hk2/internal/SingletonContext.java @@ -1,108 +1,110 @@ /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright (c) 2012 Oracle and/or its affiliates. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common Development * and Distribution License("CDDL") (collectively, the "License"). You * may not use this file except in compliance with the License. You can * obtain a copy of the License at * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html * or packager/legal/LICENSE.txt. See the License for the specific * language governing permissions and limitations under the License. * * When distributing the software, include this License Header Notice in each * file and include the License file at packager/legal/LICENSE.txt. * * GPL Classpath Exception: * Oracle designates this particular file as subject to the "Classpath" * exception as provided by Oracle in the GPL Version 2 section of the License * file that accompanied this code. * * Modifications: * If applicable, add the following below the License Header, with the fields * enclosed by brackets [] replaced by your own identifying information: * "Portions Copyright [year] [name of copyright owner]" * * Contributor(s): * If you wish your version of this file to be governed by only the CDDL or * only the GPL Version 2, indicate your decision by adding "[Contributor] * elects to include this software in this distribution under the [CDDL or GPL * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * and therefore, elected the GPL Version 2 license, then the option applies * only if the new code is made subject to such option by the copyright * holder. */ package org.jvnet.hk2.internal; import java.lang.annotation.Annotation; import javax.inject.Singleton; import org.glassfish.hk2.api.ActiveDescriptor; import org.glassfish.hk2.api.Context; import org.glassfish.hk2.api.ServiceHandle; /** * @author jwells * */ public class SingletonContext implements Context<Singleton> { /* (non-Javadoc) * @see org.glassfish.hk2.api.Context#getScope() */ @Override public Class<? extends Annotation> getScope() { return Singleton.class; } /* (non-Javadoc) * @see org.glassfish.hk2.api.Context#findOrCreate(org.glassfish.hk2.api.ActiveDescriptor, org.glassfish.hk2.api.ServiceHandle) */ @Override public <T> T findOrCreate(ActiveDescriptor<T> activeDescriptor, ServiceHandle<?> root) { if (activeDescriptor.isCacheSet()) return activeDescriptor.getCache(); - T t = activeDescriptor.create(root); - activeDescriptor.setCache(t); + synchronized(activeDescriptor) { + T t = activeDescriptor.create(root); + activeDescriptor.setCache(t); - return t; + return t; + } } /* (non-Javadoc) * @see org.glassfish.hk2.api.Context#find(org.glassfish.hk2.api.Descriptor) */ @Override public boolean containsKey(ActiveDescriptor<?> descriptor) { return descriptor.isCacheSet(); } /* (non-Javadoc) * @see org.glassfish.hk2.api.Context#isActive() */ @Override public boolean isActive() { return true; } /* (non-Javadoc) * @see org.glassfish.hk2.api.Context#supportsNullCreation() */ @Override public boolean supportsNullCreation() { return false; } /* (non-Javadoc) * @see org.glassfish.hk2.api.Context#supportsNullCreation() */ @Override public void shutdown() { } }
false
true
public <T> T findOrCreate(ActiveDescriptor<T> activeDescriptor, ServiceHandle<?> root) { if (activeDescriptor.isCacheSet()) return activeDescriptor.getCache(); T t = activeDescriptor.create(root); activeDescriptor.setCache(t); return t; }
public <T> T findOrCreate(ActiveDescriptor<T> activeDescriptor, ServiceHandle<?> root) { if (activeDescriptor.isCacheSet()) return activeDescriptor.getCache(); synchronized(activeDescriptor) { T t = activeDescriptor.create(root); activeDescriptor.setCache(t); return t; } }
diff --git a/grails-app/services/org/chai/kevin/value/ValueService.java b/grails-app/services/org/chai/kevin/value/ValueService.java index a8805cf3..500d0ee2 100644 --- a/grails-app/services/org/chai/kevin/value/ValueService.java +++ b/grails-app/services/org/chai/kevin/value/ValueService.java @@ -1,256 +1,256 @@ package org.chai.kevin.value; /* * Copyright (c) 2011, Clinton Health Access Initiative. * * 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 <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Set; import javax.persistence.Entity; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.chai.kevin.LanguageService; import org.chai.kevin.Period; import org.chai.kevin.data.Calculation; import org.chai.kevin.data.Data; import org.chai.kevin.data.DataElement; import org.chai.kevin.data.NormalizedDataElement; import org.chai.kevin.location.CalculationLocation; import org.chai.kevin.location.DataLocation; import org.chai.kevin.location.DataLocationType; import org.chai.kevin.util.Utils; import org.hibernate.Criteria; import org.hibernate.Query; import org.hibernate.SessionFactory; import org.hibernate.criterion.Conjunction; import org.hibernate.criterion.Disjunction; import org.hibernate.criterion.MatchMode; import org.hibernate.criterion.Order; import org.hibernate.criterion.Projections; import org.hibernate.criterion.Restrictions; import org.springframework.transaction.annotation.Transactional; public class ValueService { private static final Log log = LogFactory.getLog(ValueService.class); private SessionFactory sessionFactory; private LanguageService languageService; @Transactional(readOnly=false) public <T extends StoredValue> T save(T value) { log.debug("save(value="+value+")"); value.setTimestamp(new Date()); sessionFactory.getCurrentSession().saveOrUpdate(value); sessionFactory.getCurrentSession().flush(); return value; } @Transactional(readOnly=true) public <T extends DataValue> T getDataElementValue(DataElement<T> data, DataLocation dataLocation, Period period) { if (log.isDebugEnabled()) log.debug("getDataElementValue(data="+data+", period="+period+", dataLocation="+dataLocation+")"); Criteria criteria = getCriteria(data, dataLocation, period); T result = (T)criteria.uniqueResult(); if (log.isDebugEnabled()) log.debug("getDataElementValue(...)="+result); return result; } @SuppressWarnings("unchecked") @Transactional(readOnly=true) - public <T extends DataValue> List<T> searchDataElementValues(String text, DataElement<T> data, DataLocation dataLocation, Period period, Map<String, Object> params) { - if (log.isDebugEnabled()) log.debug("searchDataElementValues(text="+text+", data="+data+", period="+period+", dataLocation="+dataLocation+")"); + public <T extends DataValue> List<T> searchDataValues(String text, DataElement<T> data, DataLocation dataLocation, Period period, Map<String, Object> params) { + if (log.isDebugEnabled()) log.debug("searchDataValues(text="+text+", data="+data+", period="+period+", dataLocation="+dataLocation+")"); Criteria criteria = getCriteria(data, dataLocation, period); criteria.createAlias("location", "location"); addSortAndLimitCriteria(criteria, params); addSearchCriteria(criteria, text); List<T> result = criteria.list(); filterList(result, text); - if (log.isDebugEnabled()) log.debug("searchDataElementValues(...)="); + if (log.isDebugEnabled()) log.debug("searchDataValues(...)="); return result; } private <T extends DataValue> void filterList(List<T> list, String text) { for (String chunk : StringUtils.split(text)) { for (DataValue element : new ArrayList<T>(list)) { if (!Utils.matches(chunk, element.getLocation().getNames().get(languageService.getCurrentLanguage())) && !Utils.matches(chunk, element.getLocation().getCode())) list.remove(element); } } } private void addSearchCriteria(Criteria criteria, String text) { Conjunction textRestrictions = Restrictions.conjunction(); for (String chunk : StringUtils.split(text)) { Disjunction disjunction = Restrictions.disjunction(); disjunction.add(Restrictions.ilike("location.code", chunk, MatchMode.ANYWHERE)); disjunction.add(Restrictions.ilike("location.names.jsonText", chunk, MatchMode.ANYWHERE)); textRestrictions.add(disjunction); } criteria.add(textRestrictions); } private void addSortAndLimitCriteria(Criteria criteria, Map<String, Object> params) { if (params.containsKey("sort")) { criteria.addOrder(params.get("order").equals("asc")?Order.asc(params.get("sort")+""):Order.desc(params.get("sort")+"")); } else { criteria.addOrder(Order.asc("location.code")); } if (params.get("offset") != null) criteria.setFirstResult((Integer)params.get("offset")); if (params.get("max") != null) criteria.setMaxResults((Integer)params.get("max")); } @SuppressWarnings("unchecked") @Transactional(readOnly=true) public <T extends DataValue> List<T> listDataValues(Data<T> data, DataLocation dataLocation, Period period, Map<String, Object> params) { if (log.isDebugEnabled()) log.debug("listDataValues(data="+data+", period="+period+", dataLocation="+dataLocation+")"); Criteria criteria = getCriteria(data, dataLocation, period); criteria.createAlias("location", "location"); addSortAndLimitCriteria(criteria, params); List<T> result = criteria.list(); if (log.isDebugEnabled()) log.debug("listDataValues(...)="); return result; } public <T extends DataValue> Long countDataValues(String text, Data<T> data, DataLocation dataLocation, Period period) { if (log.isDebugEnabled()) log.debug("countDataValues(data="+data+", period="+period+", dataLocation="+dataLocation+")"); Criteria criteria = getCriteria(data, dataLocation, period); if (text != null) { criteria.createAlias("location", "location"); addSearchCriteria(criteria, text); } Long result = (Long)criteria.setProjection(Projections.count("id")).uniqueResult(); if (log.isDebugEnabled()) log.debug("countDataValues(...)="); return result; } private <T extends DataValue> Criteria getCriteria(Data<T> data, DataLocation dataLocation, Period period) { Criteria criteria = sessionFactory.getCurrentSession().createCriteria(data.getValueClass()); criteria.add(Restrictions.eq("data", data)); if (period != null) criteria.add(Restrictions.eq("period", period)); if (dataLocation != null) criteria.add(Restrictions.eq("location", dataLocation)); return criteria; } @Transactional(readOnly=true) public <T extends CalculationPartialValue> CalculationValue<T> getCalculationValue(Calculation<T> calculation, CalculationLocation location, Period period, Set<DataLocationType> types) { if (log.isDebugEnabled()) log.debug("getCalculationValue(calculation="+calculation+", period="+period+", location="+location+", types="+types+")"); List<T> partialValues = getPartialValues(calculation, location, period, types); CalculationValue<T> result = calculation.getCalculationValue(partialValues, period, location); if (log.isDebugEnabled()) log.debug("getCalculationValue(...)="+result); return result; } @SuppressWarnings("unchecked") @Transactional(readOnly=true) public <T extends CalculationPartialValue> List<T> getPartialValues(Calculation<T> calculation, CalculationLocation location, Period period) { return (List<T>)sessionFactory.getCurrentSession().createCriteria(calculation.getValueClass()) .add(Restrictions.eq("period", period)) .add(Restrictions.eq("location", location)) .add(Restrictions.eq("data", calculation)).list(); } @SuppressWarnings("unchecked") private <T extends CalculationPartialValue> List<T> getPartialValues(Calculation<T> calculation, CalculationLocation location, Period period, Set<DataLocationType> types) { return (List<T>)sessionFactory.getCurrentSession().createCriteria(calculation.getValueClass()) .add(Restrictions.eq("period", period)) .add(Restrictions.eq("location", location)) .add(Restrictions.eq("data", calculation)) .add(Restrictions.in("type", types)).list(); } @Transactional(readOnly=true) public Long getNumberOfValues(Data<?> data, Period period) { return (Long)sessionFactory.getCurrentSession().createCriteria(data.getValueClass()) .add(Restrictions.eq("data", data)) .add(Restrictions.eq("period", period)) .setProjection(Projections.count("id")) .uniqueResult(); } // if this is set readonly, it triggers an error when deleting a // data element through DataElementController.deleteEntity @Transactional(readOnly=true) public Long getNumberOfValues(Data<?> data) { return (Long)sessionFactory.getCurrentSession().createCriteria(data.getValueClass()) .add(Restrictions.eq("data", data)) .setProjection(Projections.count("id")) .uniqueResult(); } @Transactional(readOnly=true) public Long getNumberOfValues(Data<?> data, Status status, Period period) { // TODO allow Calculation here if (!(data instanceof NormalizedDataElement)) { throw new IllegalArgumentException("wrong data type"); } Criteria criteria = sessionFactory.getCurrentSession().createCriteria(data.getValueClass()) .add(Restrictions.eq("data", data)) .add(Restrictions.eq("status", status)); if (period != null) criteria.add(Restrictions.eq("period", period)); return (Long)criteria .setProjection(Projections.count("id")) .uniqueResult(); } @Transactional(readOnly=false) public void deleteValues(Data<?> data, CalculationLocation location, Period period) { String queryString = "delete from "+data.getValueClass().getAnnotation(Entity.class).name()+" where data = :data"; if (location != null) queryString += " and location = :location"; if (period != null) queryString += " and period = :period"; Query query = sessionFactory.getCurrentSession() .createQuery(queryString) .setParameter("data", data); if (location != null) query.setParameter("location", location); if (period != null) query.setParameter("period", period); query.executeUpdate(); } public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } public void setLanguageService(LanguageService languageService) { this.languageService = languageService; } }
false
true
public <T extends DataValue> List<T> searchDataElementValues(String text, DataElement<T> data, DataLocation dataLocation, Period period, Map<String, Object> params) { if (log.isDebugEnabled()) log.debug("searchDataElementValues(text="+text+", data="+data+", period="+period+", dataLocation="+dataLocation+")"); Criteria criteria = getCriteria(data, dataLocation, period); criteria.createAlias("location", "location"); addSortAndLimitCriteria(criteria, params); addSearchCriteria(criteria, text); List<T> result = criteria.list(); filterList(result, text); if (log.isDebugEnabled()) log.debug("searchDataElementValues(...)="); return result; }
public <T extends DataValue> List<T> searchDataValues(String text, DataElement<T> data, DataLocation dataLocation, Period period, Map<String, Object> params) { if (log.isDebugEnabled()) log.debug("searchDataValues(text="+text+", data="+data+", period="+period+", dataLocation="+dataLocation+")"); Criteria criteria = getCriteria(data, dataLocation, period); criteria.createAlias("location", "location"); addSortAndLimitCriteria(criteria, params); addSearchCriteria(criteria, text); List<T> result = criteria.list(); filterList(result, text); if (log.isDebugEnabled()) log.debug("searchDataValues(...)="); return result; }
diff --git a/src/java/net/sf/jabref/groups/GroupTreeCellRenderer.java b/src/java/net/sf/jabref/groups/GroupTreeCellRenderer.java index 6aa7b8db9..47330e8ea 100644 --- a/src/java/net/sf/jabref/groups/GroupTreeCellRenderer.java +++ b/src/java/net/sf/jabref/groups/GroupTreeCellRenderer.java @@ -1,155 +1,159 @@ /* All programs in this directory and subdirectories are published under the GNU General Public License as described below. 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 Further information about the GNU GPL is available at: http://www.gnu.org/copyleft/gpl.ja.html */ package net.sf.jabref.groups; import java.awt.*; import javax.swing.*; import javax.swing.tree.DefaultTreeCellRenderer; import net.sf.jabref.*; /** * Renders a GroupTreeNode using its group's getName() method, rather that its * toString() method. * * @author jzieren */ public class GroupTreeCellRenderer extends DefaultTreeCellRenderer { /** The cell over which the user is currently dragging */ protected Object highlight1Cell = null; protected Object[] highlight2Cells = null; protected Object[] highlight3Cells = null; protected Object highlightBorderCell = null; public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) { if (value == highlight1Cell) selected = true; // show as selected Component c = super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus); + // this is sometimes called from deep within somewhere, with a dummy + // value (probably for layout etc.), so we've got to check here! + if (!(value instanceof GroupTreeNode)) + return c; AbstractGroup group = ((GroupTreeNode) value).getGroup(); if (group == null || !(c instanceof JLabel)) return c; // sanity check JLabel label = (JLabel) c; if (highlightBorderCell != null && highlightBorderCell == value) label.setBorder(BorderFactory.createLineBorder(Color.BLACK)); else label.setBorder(BorderFactory.createEmptyBorder()); boolean italics = Globals.prefs.getBoolean("groupShowDynamic") && group.isDynamic(); boolean red = false; if (highlight2Cells != null) { for (int i = 0; i < highlight2Cells.length; ++i) { if (highlight2Cells[i] == value) { // label.setForeground(Color.RED); red = true; break; } } } boolean underline = false; if (highlight3Cells != null) { for (int i = 0; i < highlight3Cells.length; ++i) { if (highlight3Cells[i] == value) { underline = true; break; } } } StringBuffer sb = new StringBuffer(); sb.append("<html>"); if (red) sb.append("<font color=\"#FF0000\">"); if (underline) sb.append("<u>"); if (italics) sb.append("<i>"); sb.append(group.getName()); if (italics) sb.append("</i>"); if (underline) sb.append("</u>"); if (red) sb.append("</font>"); sb.append("</html>"); final String text = sb.toString(); if (!label.getText().equals(text)) label.setText(text); label.setToolTipText("<html>" + group.getShortDescription() + "</html>"); if (Globals.prefs.getBoolean("groupShowIcons")) { switch (group.getHierarchicalContext()) { case AbstractGroup.REFINING: if (label.getIcon() != GUIGlobals.groupRefiningIcon) label.setIcon(GUIGlobals.groupRefiningIcon); break; case AbstractGroup.INCLUDING: if (label.getIcon() != GUIGlobals.groupIncludingIcon) label.setIcon(GUIGlobals.groupIncludingIcon); break; default: if (label.getIcon() != GUIGlobals.groupRegularIcon) label.setIcon(GUIGlobals.groupRegularIcon); break; } } else { label.setIcon(null); } return c; } /** * For use when dragging: The sepcified cell is always rendered as selected. * * @param cell * The cell over which the user is currently dragging. */ void setHighlight1Cell(Object cell) { this.highlight1Cell = cell; } /** * Highlights the specified cells (in red), or disables highlight if cells == * null. */ void setHighlight2Cells(Object[] cells) { this.highlight2Cells = cells; } /** * Highlights the specified cells (by unterlining), or disables highlight if * cells == null. */ void setHighlight3Cells(Object[] cells) { this.highlight3Cells = cells; } /** * Highlights the specified cells (by drawing a border around it), * or disables highlight if highlightBorderCell == null. */ void setHighlightBorderCell(Object highlightBorderCell) { this.highlightBorderCell = highlightBorderCell; } }
true
true
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) { if (value == highlight1Cell) selected = true; // show as selected Component c = super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus); AbstractGroup group = ((GroupTreeNode) value).getGroup(); if (group == null || !(c instanceof JLabel)) return c; // sanity check JLabel label = (JLabel) c; if (highlightBorderCell != null && highlightBorderCell == value) label.setBorder(BorderFactory.createLineBorder(Color.BLACK)); else label.setBorder(BorderFactory.createEmptyBorder()); boolean italics = Globals.prefs.getBoolean("groupShowDynamic") && group.isDynamic(); boolean red = false; if (highlight2Cells != null) { for (int i = 0; i < highlight2Cells.length; ++i) { if (highlight2Cells[i] == value) { // label.setForeground(Color.RED); red = true; break; } } } boolean underline = false; if (highlight3Cells != null) { for (int i = 0; i < highlight3Cells.length; ++i) { if (highlight3Cells[i] == value) { underline = true; break; } } } StringBuffer sb = new StringBuffer(); sb.append("<html>"); if (red) sb.append("<font color=\"#FF0000\">"); if (underline) sb.append("<u>"); if (italics) sb.append("<i>"); sb.append(group.getName()); if (italics) sb.append("</i>"); if (underline) sb.append("</u>"); if (red) sb.append("</font>"); sb.append("</html>"); final String text = sb.toString(); if (!label.getText().equals(text)) label.setText(text); label.setToolTipText("<html>" + group.getShortDescription() + "</html>"); if (Globals.prefs.getBoolean("groupShowIcons")) { switch (group.getHierarchicalContext()) { case AbstractGroup.REFINING: if (label.getIcon() != GUIGlobals.groupRefiningIcon) label.setIcon(GUIGlobals.groupRefiningIcon); break; case AbstractGroup.INCLUDING: if (label.getIcon() != GUIGlobals.groupIncludingIcon) label.setIcon(GUIGlobals.groupIncludingIcon); break; default: if (label.getIcon() != GUIGlobals.groupRegularIcon) label.setIcon(GUIGlobals.groupRegularIcon); break; } } else { label.setIcon(null); } return c; }
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) { if (value == highlight1Cell) selected = true; // show as selected Component c = super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus); // this is sometimes called from deep within somewhere, with a dummy // value (probably for layout etc.), so we've got to check here! if (!(value instanceof GroupTreeNode)) return c; AbstractGroup group = ((GroupTreeNode) value).getGroup(); if (group == null || !(c instanceof JLabel)) return c; // sanity check JLabel label = (JLabel) c; if (highlightBorderCell != null && highlightBorderCell == value) label.setBorder(BorderFactory.createLineBorder(Color.BLACK)); else label.setBorder(BorderFactory.createEmptyBorder()); boolean italics = Globals.prefs.getBoolean("groupShowDynamic") && group.isDynamic(); boolean red = false; if (highlight2Cells != null) { for (int i = 0; i < highlight2Cells.length; ++i) { if (highlight2Cells[i] == value) { // label.setForeground(Color.RED); red = true; break; } } } boolean underline = false; if (highlight3Cells != null) { for (int i = 0; i < highlight3Cells.length; ++i) { if (highlight3Cells[i] == value) { underline = true; break; } } } StringBuffer sb = new StringBuffer(); sb.append("<html>"); if (red) sb.append("<font color=\"#FF0000\">"); if (underline) sb.append("<u>"); if (italics) sb.append("<i>"); sb.append(group.getName()); if (italics) sb.append("</i>"); if (underline) sb.append("</u>"); if (red) sb.append("</font>"); sb.append("</html>"); final String text = sb.toString(); if (!label.getText().equals(text)) label.setText(text); label.setToolTipText("<html>" + group.getShortDescription() + "</html>"); if (Globals.prefs.getBoolean("groupShowIcons")) { switch (group.getHierarchicalContext()) { case AbstractGroup.REFINING: if (label.getIcon() != GUIGlobals.groupRefiningIcon) label.setIcon(GUIGlobals.groupRefiningIcon); break; case AbstractGroup.INCLUDING: if (label.getIcon() != GUIGlobals.groupIncludingIcon) label.setIcon(GUIGlobals.groupIncludingIcon); break; default: if (label.getIcon() != GUIGlobals.groupRegularIcon) label.setIcon(GUIGlobals.groupRegularIcon); break; } } else { label.setIcon(null); } return c; }
diff --git a/src/de/freiburg/uni/iig/sisi/model/ModelObject.java b/src/de/freiburg/uni/iig/sisi/model/ModelObject.java index ebdd7c9..4f7f908 100644 --- a/src/de/freiburg/uni/iig/sisi/model/ModelObject.java +++ b/src/de/freiburg/uni/iig/sisi/model/ModelObject.java @@ -1,49 +1,49 @@ package de.freiburg.uni.iig.sisi.model; /** * * Small "helper" to quickly have model objects with an id and name. * @author Sebastian * */ public abstract class ModelObject { private String id; private String name; public ModelObject() { this.id = ""; this.name = ""; } public ModelObject(String id, String name) { this.id = id; this.name = name; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { - if (name != null) return name; - if (id != null) return id; + if (name != "") return name; + if (id != "") return id; return super.toString(); } }
true
true
public String toString() { if (name != null) return name; if (id != null) return id; return super.toString(); }
public String toString() { if (name != "") return name; if (id != "") return id; return super.toString(); }
diff --git a/main/src/main/java/com/bloatit/BloatitExampleDB.java b/main/src/main/java/com/bloatit/BloatitExampleDB.java index ca8252bc7..236457316 100644 --- a/main/src/main/java/com/bloatit/BloatitExampleDB.java +++ b/main/src/main/java/com/bloatit/BloatitExampleDB.java @@ -1,516 +1,528 @@ // // Copyright (c) 2011 Linkeos. // // This file is part of Elveos.org. // Elveos.org 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. // // Elveos.org 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 Elveos.org. If not, see http://www.gnu.org/licenses/. // package com.bloatit; import java.math.BigDecimal; import java.util.Locale; import java.util.UUID; import com.bloatit.common.ConfigurationManager; import com.bloatit.data.DaoBug.Level; import com.bloatit.data.DaoFeature.FeatureState; import com.bloatit.data.DaoMember.Role; import com.bloatit.data.DaoMoneyWithdrawal.State; import com.bloatit.data.DaoTeam.Right; import com.bloatit.data.SessionManager; import com.bloatit.data.exceptions.NotEnoughMoneyException; import com.bloatit.framework.FrameworkConfiguration; import com.bloatit.framework.exceptions.highlevel.ShallNotPassException; import com.bloatit.framework.mailsender.MailServer; import com.bloatit.framework.utils.datetime.DateUtils; import com.bloatit.framework.webprocessor.context.User.ActivationState; import com.bloatit.model.BankTransaction; import com.bloatit.model.Comment; import com.bloatit.model.Feature; import com.bloatit.model.FeatureFactory; import com.bloatit.model.FeatureImplementation; import com.bloatit.model.FileMetadata; import com.bloatit.model.HighlightFeature; import com.bloatit.model.Member; import com.bloatit.model.Milestone; import com.bloatit.model.MoneyWithdrawal; import com.bloatit.model.Offer; import com.bloatit.model.Software; import com.bloatit.model.Team; import com.bloatit.model.managers.FileMetadataManager; import com.bloatit.model.right.AuthToken; import com.bloatit.model.right.UnauthorizedOperationException; public class BloatitExampleDB { // NO_UCD private Software libreOffice; private final Member yoann; private final Member fred; private final Member thomas; private final Member admin; private final Member chogall; private final Member cerbere; private final Member hydre; private final Member celeste; private final Member elephantman; private final Member rataxes; private Software vlc; private Software perroquet; private Software mageia; public BloatitExampleDB() throws UnauthorizedOperationException, NotEnoughMoneyException { System.setProperty("log4J.path", ConfigurationManager.SHARE_DIR + "/log"); MailServer.getInstance().initialize(); SessionManager.beginWorkUnit(); fred = createMember("fred", "Frédéric Bertolus", Locale.FRANCE); thomas = createMember("thomas", "Thomas Guyard", Locale.FRANCE); yoann = createMember("yoann", "Yoann Plénet", Locale.US); admin = createMember("admin", "Administrator", Locale.FRANCE); admin.getDao().setRole(Role.ADMIN); chogall = createMember("chogall", "Cho'gall", Locale.UK); cerbere = createMember("cerbere", "Cerbère", Locale.KOREA); hydre = createMember("hydre", "Hydre", Locale.GERMANY); elephantman = createMember("elephantman", "ElephantMan", Locale.JAPAN); celeste = createMember("celeste", "Céleste", Locale.CHINA); rataxes = createMember("rataxes", "Rataxès", Locale.FRANCE); + AuthToken.authenticate(fred); fred.getContact().setName("Frederic Bertolus"); fred.getContact().setStreet("Le superbe appartement à gauche"); + AuthToken.authenticate(thomas); thomas.getContact().setName("Thomas Guyard"); thomas.getContact().setStreet("Le superbe appartement à gauche"); + AuthToken.authenticate(yoann); yoann.getContact().setName("Yoann Plénet"); yoann.getContact().setStreet("Le superbe appartement à gauche"); // Add avatar + AuthToken.authenticate(chogall); chogall.setAvatar(getImage(chogall, "users/chogall.png")); + AuthToken.authenticate(cerbere); cerbere.setAvatar(getImage(cerbere, "users/cerbere.png")); + AuthToken.authenticate(hydre); hydre.setAvatar(getImage(hydre, "users/hydre.png")); + AuthToken.authenticate(elephantman); elephantman.setAvatar(getImage(elephantman, "users/elephantman.png")); + AuthToken.authenticate(celeste); celeste.setAvatar(getImage(celeste, "users/celeste.png")); + AuthToken.authenticate(rataxes); rataxes.setAvatar(getImage(rataxes, "users/rataxes.png")); // Add money giveMoney(fred, 1000000); giveMoney(thomas, 2000000); giveMoney(yoann, 3000000); giveMoney(chogall, 2000); giveMoney(cerbere, 1000); giveMoney(hydre, 500); giveMoney(elephantman, 100000000); // Add withdrawal + AuthToken.authenticate(fred); withdrawMoney(fred, 1000, State.REQUESTED); withdrawMoney(fred, 2000, State.TREATED); withdrawMoney(fred, 3000, State.REFUSED); withdrawMoney(fred, 4000, State.CANCELED); withdrawMoney(fred, 5000, State.COMPLETE); + AuthToken.authenticate(yoann); withdrawMoney(yoann, 1000, State.REQUESTED); withdrawMoney(yoann, 2000, State.TREATED); withdrawMoney(yoann, 3000, State.REFUSED); withdrawMoney(yoann, 4000, State.CANCELED); withdrawMoney(yoann, 5000, State.COMPLETE); + AuthToken.authenticate(thomas); withdrawMoney(thomas, 1000, State.REQUESTED); withdrawMoney(thomas, 2000, State.TREATED); withdrawMoney(thomas, 3000, State.REFUSED); withdrawMoney(thomas, 4000, State.CANCELED); withdrawMoney(thomas, 5000, State.COMPLETE); // Add teams final Team other = new Team("other", "[email protected]", "An other team", Right.PROTECTED, yoann); AuthToken.authenticate(yoann); other.setAvatar(getImage(yoann, "teams/other.png")); final Team b219 = new Team("b219", "[email protected]", "The team for b219", Right.PROTECTED, fred); AuthToken.authenticate(fred); b219.setAvatarUnprotected(getImage(fred, "teams/b219.png")); final Team ubuntuUsers = new Team("ubuntuUsers", "[email protected]", "The team for ubuntu users", Right.PUBLIC, thomas); AuthToken.authenticate(thomas); ubuntuUsers.setAvatarUnprotected(getImage(thomas, "teams/ubuntuUsers.png")); // Generate softwares generateVlcSoftware(); generatePerroquetSoftware(); generateLibreOfficeSoftware(); generateMageiaSoftware(); // Generate features final Feature twoSubtitlesInVlcFeature = generateVlcFeatureTwoSubtitles(); final Feature addPerroquetInMageiaFeature = generateMageiaFeaturePerroquetPackage(); final Feature colorPickerFeature = generateLibreOfficeFeatureColorPicker(); final Feature libreOfficeFeatureDefaultTemplate = generateLibreOfficeFeatureDefaultTemplate(); final Feature perroquetFeatureArabicSupport = generatePerroquetFeatureArabicSupport(); final Feature mageiaFeatureRemoveEmacs = generateMageiaFeatureRemoveEmacs(); // Highlight features new HighlightFeature(twoSubtitlesInVlcFeature, 1, "Popular", DateUtils.now(), DateUtils.flyingPigDate()); new HighlightFeature(colorPickerFeature, 2, "Recent", DateUtils.now(), DateUtils.flyingPigDate()); new HighlightFeature(addPerroquetInMageiaFeature, 3, "In developement", DateUtils.now(), DateUtils.flyingPigDate()); new HighlightFeature(libreOfficeFeatureDefaultTemplate, 4, "Need your help quicky", DateUtils.now(), DateUtils.flyingPigDate()); new HighlightFeature(perroquetFeatureArabicSupport, 5, "Random", DateUtils.now(), DateUtils.flyingPigDate()); new HighlightFeature(mageiaFeatureRemoveEmacs, 6, "Success", DateUtils.now(), DateUtils.flyingPigDate()); SessionManager.endWorkUnitAndFlush(); } public void generateMageiaSoftware() { // Mageia software final String mageiaTitle = "Mageia est un fork de Mandriva Linux, reposant sur une association de type 1901 composée de contributeurs reconnus et élus pour leur travail. "; final String mageiaDescription = "http://mageia.org/fr/"; mageia = new Software("Mageia", thomas, Locale.FRANCE, mageiaTitle + mageiaDescription); mageia.setImage(getImage(yoann, "mageia.png")); } public void generateLibreOfficeSoftware() { // LibreOffice software final String libreOfficeTitle = "LibreOffice (souvent abrégé en LibO) est une suite bureautique, dérivée directement de OpenOffice.org, créée par The Document Foundation. Cet embranchement a eu lieu le 28 septembre 2010, dans la continuité du rachat de Sun Microsystems par Oracle. "; final String libreOfficeDescription = "LibreOffice is the free power-packed Open Source personal productivity suite for Windows, Macintosh and Linux, that gives you six feature-rich applications for all your document production and data processing needs: Writer, Calc, Impress, Draw, Math and Base. Support and documentation is free from our large, dedicated community of users, contributors and developers. You, too, can also get involved!" + "\n" + "http://www.libreoffice.org/"; libreOffice = new Software("LibreOffice", thomas, Locale.FRANCE, libreOfficeTitle + libreOfficeDescription); libreOffice.setImage(getImage(fred, "libreoffice.png")); } public void generatePerroquetSoftware() { // Perroquet software final String perroquetTitle = "Perroquet est un programme éducatif dont le but est d'améliorer de manière divertissant votre niveau de compréhension orale des langues étrangères "; final String perroquetDescription = "Le principe de Perroquet est d'utiliser une vidéo ou un fichier audio et les sous-titres associés pour vous faire écouter et comprendre les dialogues ou paroles. Après lui avoir indiqué les fichiers à utiliser, Perroquet va lire un morceau de la vidéo et puis la mettre en pause. Il vous indiquera alors le nombre de mot à trouver et vous devrez les taper pour pouvoir continuer la lecture. Il est possible de réécouter une séquence autant de fois que nécessaire. Si vous ne comprenez pas tout, Perroquet présente plusieurs moyen de vous aider. \n" + "http://perroquet.b219.org/"; perroquet = new Software("Perroquet", thomas, Locale.FRANCE, perroquetTitle + perroquetDescription); perroquet.setImage(getImage(fred, "perroquet.png")); } public void generateVlcSoftware() { // VLC software final String vlcTitle = "VLC is a free and open source cross-platform multimedia player and framework that plays most multimedia files as well as DVD, Audio CD, VCD, and various streaming protocols. "; final String vlcDescription = "http://www.videolan.org/vlc/"; vlc = new Software("VLC", thomas, Locale.FRANCE, vlcTitle + vlcDescription); vlc.setImage(getImage(thomas, "vlc.png")); } public Feature generateVlcFeatureTwoSubtitles() throws UnauthorizedOperationException, NotEnoughMoneyException { // Feature with offers selected, not validated and not founded final String twoSubtitlesInVlcFeatureDescription = "Offrir la possibilité d'afficher deux sous-titre à la fois dans VLC.\n" + "\n" + "Afin de m'entrainer à parler anglais et néerlandais à la fois, je souhaite pouvoir afficher les sous-titre de ces deux langues en même temps dans VLC.\n" + "Parce que je suis très gentil, si on peut afficher deux sous-titre de n'importe quelle langue ça m'ira aussi (si le néerlandais font bien sûr partis des langues supportées).\n" + "\n" + "Les fichiers de sous titre lus doivent être séparés. Je ne veux pas avoir à utiliser un logiciel quelconque qui combinera les sous titres. Je veux juste pouvoir clicker sur le bouton \"sous-titre\", cocher une case \"afficher deux sous-titre simultanément\" (wording à revoir) et voilà (ndt : en anglais dans le texte).\n" + "\n" + "Notes :\n" + "- Les sous-titres pourront être dans des formats différents.\n" + "- Les sous-titres pourront ne pas être synchronisés exactement de la même manière (un sous-titre pourra changer alors que le précédent est encore affiché)\n" + "\n" + "J'aimerais que ce soit implémenté dans la semaine, je suis en-effet en train de me préparer à un concours extrèmement complexe (le concours de la bicéphalie) qui aura lieu dans 3 semaines, et j'ai besoin d'au moins deux semaines pour maitriser parfaitement ces deux langues (j'ai pu apprendre le Chinois et l'Arabe en 3 jours auparavant, mais le néerlandais est quand même très complexe)."; final String twoSubtitlesInVlcFeatureTitle = "Afficher en même temps un sous-titre en anglais et un sous-titre en néerlandais"; final Feature twoSubtitlesInVlcFeature = FeatureFactory.createFeature(chogall, null, chogall.getLocale(), twoSubtitlesInVlcFeatureTitle, twoSubtitlesInVlcFeatureDescription, vlc); AuthToken.authenticate(cerbere); final Comment comment1 = twoSubtitlesInVlcFeature.addComment("Super idée !\n" + "J'ai exactement le même besoin mais avec 3 langues. Du coup pour être un peu générique, je propose d'avoir la possibilité de sélectionner n langues. Je connais un ami qui apprend en-effet l'araméen, le latin, le grec, l'hébreu, le le haut-sindarin et l'égyptien et qui serait sans doute preneur aussi."); AuthToken.authenticate(hydre); comment1.addComment("Je suis l'ami de Cerbère qui a posté ci-dessus et qui apprend des langues mortes. Je trouverais ça génial , mais il est indispensable de pouvoir réduire la taille du texte.\n" + "Je propose de forker cette demande pour inclure les demandes de changement (nombre de sous-titre non défini et taille des sous-titre définissable) "); AuthToken.authenticate(chogall); comment1.addComment("OK pour moi, j'aurais dû y penser dès le début, j'ai merdé, j'avais mon cerveau gauche qui avait bu trop de vodka. "); AuthToken.authenticate(elephantman); final Comment comment2 = twoSubtitlesInVlcFeature.addComment("Elle est naze votre idée, moi j'apprends une langue en 2.53 minutes (moyenne vérifiée sur un échantillon de 353 langues) du coup autant afficher un seul sous-titre à la fois"); AuthToken.authenticate(chogall); comment2.addComment("On ne peut pas vaincre un éléphant ! Abandonnons cette demande !"); final String rataxesOfferDescription = "Je vais vous le faire vite et bien. Et tout ça pour vraiment pas cher !"; AuthToken.authenticate(rataxes); final Offer rataxesOffer = twoSubtitlesInVlcFeature.addOffer(new BigDecimal("123"), rataxesOfferDescription, "GNU GPL V3", rataxes.getLocale(), DateUtils.tomorrow(), 0); AuthToken.authenticate(chogall); rataxesOffer.voteUp(); AuthToken.authenticate(hydre); rataxesOffer.voteUp(); AuthToken.authenticate(celeste); final String celesteMilestone1Description = "Oulala, ça à l'air compliqué tout ça... Je peux tout de même essayer mais je vais ramer. Je découpe le travail en 3 parties pour simplifier la tache.\n" + "Pour la première partie, je vais modifier le coeur du logiciel pour permettre d'afficher un nombre variable de sous-titre."; final Offer celesteOffer = twoSubtitlesInVlcFeature.addOffer(new BigDecimal("123"), celesteMilestone1Description, "GNU GPL V3", celeste.getLocale(), DateUtils.nowPlusSomeDays(2), 0); AuthToken.authenticate(celeste); final String celesteMilestone2Description = "Pour la 2ème partie, je vais faire les modifications d'IHM pour choisir les sous-titres et configurer leur disposition."; celesteOffer.addMilestone(new BigDecimal(1000), celesteMilestone2Description, celeste.getLocale(), DateUtils.nowPlusSomeDays(3), 0); final String celesteMilestone3Description = "Pour finir, je vais faire le packaging en tar.gz, deb, rpm et exe de la version patché pour une utilisatation immédiate. Je vais aussi proposer le patch upstream et créer un petit jeu de test fonctionnels."; celesteOffer.addMilestone(new BigDecimal(700), celesteMilestone3Description, celeste.getLocale(), DateUtils.nowPlusSomeDays(4), 0); AuthToken.authenticate(cerbere); celesteOffer.voteUp(); // Contributions AuthToken.authenticate(chogall); twoSubtitlesInVlcFeature.addContribution(new BigDecimal("800"), "On est prêts, non moi j'suis pas prêt !"); AuthToken.authenticate(cerbere); twoSubtitlesInVlcFeature.addContribution(new BigDecimal("500"), "Grrrrrr"); AuthToken.authenticate(hydre); twoSubtitlesInVlcFeature.addContribution(new BigDecimal("300"), ""); return twoSubtitlesInVlcFeature; } public Feature generateMageiaFeaturePerroquetPackage() throws UnauthorizedOperationException, NotEnoughMoneyException { // Mageia feature // Feature in development final String addPerroquetInMageiaFeatureDescription = "Le logiciel perroquet (http://perroquet.b219.org) a des paquets pour Ubuntu et ArchLinux mais pas pour Mageia.\n" + "\n" + "Le but de cette demande est de créer un paquet pour perroquet et si possible l'intégrer dans les paquets officiels de Mageia.\n" + "Le paquet devra avoir le même niveau d'intégration que celui pour Ubuntu : icones, handle sur les fichiers .perroquet, ..."; final String addPerroquetInMageiaFeaturetitle = "Make a packet for Mageia for the Perroquet software"; final Feature addPerroquetInMageiaFeature = FeatureFactory.createFeature(fred, null, fred.getLocale(), addPerroquetInMageiaFeaturetitle, addPerroquetInMageiaFeatureDescription, mageia); final String hydrePerroquetOfferDescription = "Je le fais et j'ajoute le paquet pour la première release."; AuthToken.authenticate(hydre); addPerroquetInMageiaFeature.addOffer(new BigDecimal(200), hydrePerroquetOfferDescription, "GNU GPL V3", hydre.getLocale(), DateUtils.tomorrow(), 0); // Contributions AuthToken.authenticate(hydre); addPerroquetInMageiaFeature.addContribution(new BigDecimal("10"), ""); AuthToken.authenticate(fred); addPerroquetInMageiaFeature.addContribution(new BigDecimal("230"), ""); // Add bugs setFeatureInDevelopmentState(addPerroquetInMageiaFeature); final Milestone firstMilestone = addPerroquetInMageiaFeature.getSelectedOffer().getMilestones().iterator().next(); AuthToken.authenticate(fred); firstMilestone.addBug("Ça marche pas!", "Rien ne se passe quand on click sur l'icone", fred.getLocale(), Level.FATAL); AuthToken.authenticate(elephantman); firstMilestone.addBug("Faible qualité graphique pour les éléphants", "L'icone est en vertoriel, c'est pas mal à 2 dimension mais je la trouve un peu pixélisé sur mon écran à 5 dimensions, c'est pas très très beau", elephantman.getLocale(), Level.MINOR); AuthToken.authenticate(yoann); firstMilestone.addBug("Fichier de conf système manquant", "Le fichier de conf /etc/perroquet système n'est pas placé. Il faudrait le corriger", yoann.getLocale(), Level.MAJOR); return addPerroquetInMageiaFeature; } public Feature generateLibreOfficeFeatureColorPicker() { // LibreOffice feature // Feature without offer final String colorPickerFeatureDescription = "Actuellement dans LibreOffice, il y a un lot de couleur pré-tiré moche. Si l'on veut une jolie couleur, il faut passer dans tous les menus et on arrive enfin sur un outils anti-ergonomique.\n" + "Il faudrait donc ajouter un color picker à un endroit accessible, par exemple dans le selecteur de couleur des styles."; final String colorPickerFeatureTitle = "Permettre de choisir facilement n'importe quelle couleur"; final Feature colorPickerFeature = FeatureFactory.createFeature(yoann, null, yoann.getLocale(), colorPickerFeatureTitle, colorPickerFeatureDescription, libreOffice); return colorPickerFeature; } public Feature generateLibreOfficeFeatureDefaultTemplate() throws UnauthorizedOperationException, NotEnoughMoneyException { // LibreOffice feature // Feature with offer validated but not funded final String featureDescription = "Actuellement dans LibreOffice, le template par défaut n'est pas très beau. Un jeu de template élégant inclus par défaut serait vraiment utile."; final String featureTitle = "Jolie template par défaut dans Libre Office "; final Feature feature = FeatureFactory.createFeature(yoann, null, yoann.getLocale(), featureTitle, featureDescription, libreOffice); final String offerDescription = "Je suis graphiste et j'ai justement commencé à travailler là dessus. Je propose de faire 10 templates variés"; AuthToken.authenticate(celeste); feature.addOffer(new BigDecimal(1000), offerDescription, "GNU GPL V3", celeste.getLocale(), DateUtils.tomorrow(), 0); final FeatureImplementation featureImpl = (FeatureImplementation) feature; featureImpl.getDao().setValidationDate(DateUtils.now()); // Contributions AuthToken.authenticate(chogall); feature.addContribution(new BigDecimal("10"), ""); return feature; } public Feature generatePerroquetFeatureArabicSupport() throws UnauthorizedOperationException, NotEnoughMoneyException { // LibreOffice feature // Feature with offer not validated and funded final String featureDescription = "Il faut que perroquet soit capable de gérer les langue qui vont de droite à gauche (en particulier les langues arabes) et vérifier que toutes les caractères sont bien supportés."; final String featureTitle = "Support des langues arabe"; final Feature feature = FeatureFactory.createFeature(yoann, null, yoann.getLocale(), featureTitle, featureDescription, perroquet); final String offerDescription = "Je suis graphiste et j'ai justement commencé à travailler là dessus. Je propose de faire 10 templates variés"; AuthToken.authenticate(fred); feature.addOffer(new BigDecimal(750), offerDescription, "GNU GPL V3", fred.getLocale(), DateUtils.tomorrow(), 0); // Contributions AuthToken.authenticate(yoann); feature.addContribution(new BigDecimal("760"), ""); return feature; } public Feature generateMageiaFeatureRemoveEmacs() throws UnauthorizedOperationException, NotEnoughMoneyException { // LibreOffice feature // Feature with offer not validated and not funded final String featureDescription = "Il faut absolument supprimer emacs des paquets disponible dans Mageia. En effet, le successeur d'emacs vim est maintenant mature et le logiciel emacs qui a bien servi est maintenant dépassé et encombre les paquets. Des sources indiquent aussi qu'emacs est dangereux pour la santé et qu'il peut engendrer un Syndrome du Canal Carpien. D'autre part emacs est peu accessible car il est difficilement utilisable par les personnes ne disposant que d'un seul doigt. "; final String featureTitle = "Suppression du paquet emacs déprécié"; final Feature feature = FeatureFactory.createFeature(thomas, null, thomas.getLocale(), featureTitle, featureDescription, mageia); final String offerDescription = "Oui, vive vim !"; AuthToken.authenticate(cerbere); feature.addOffer(new BigDecimal(300), offerDescription, "GNU GPL V3", cerbere.getLocale(), DateUtils.tomorrow(), 0); final FeatureImplementation featureImpl = (FeatureImplementation) feature; featureImpl.getDao().setValidationDate(DateUtils.now()); // Contributions AuthToken.authenticate(thomas); feature.addContribution(new BigDecimal("400"), ""); setFeatureInFinishedState(feature); return feature; } /** * Work only if the money is available * * @param feature */ private void setFeatureInDevelopmentState(final Feature feature) { final FeatureImplementation featureImpl = (FeatureImplementation) feature; featureImpl.getDao().setValidationDate(DateUtils.now()); } private void setFeatureInFinishedState(final Feature feature) { final FeatureImplementation featureImpl = (FeatureImplementation) feature; featureImpl.getDao().setFeatureState(FeatureState.FINISHED); } private void withdrawMoney(final Member m, final int amount, final State completion) { final MoneyWithdrawal mw = new MoneyWithdrawal(m, "GB87 BARC 2065 8244 9716 55", new BigDecimal(amount)); AuthToken.authenticate(admin); try { switch (completion) { case REQUESTED: break; case TREATED: break; case COMPLETE: mw.setTreated(); mw.setComplete(); break; case CANCELED: mw.setCanceled(); break; case REFUSED: mw.setRefused(); break; } } catch (final UnauthorizedOperationException e) { throw new ShallNotPassException("Right error in creating money withdrawal", e); } } public void giveMoney(final Member member, final int amount) throws UnauthorizedOperationException { final BankTransaction bankTransaction = new BankTransaction("money !!!", UUID.randomUUID().toString(), member, new BigDecimal(amount), new BigDecimal(amount), UUID.randomUUID().toString()); bankTransaction.getDao().setAuthorized(); bankTransaction.getDao().setValidated(); } public Member createMember(final String login, final String name, final Locale locale) throws UnauthorizedOperationException { final Member member = new Member(login, "plop", login + "@elveos.org", locale); AuthToken.authenticate(member); member.setFullname(name); member.getDao().setActivationState(ActivationState.ACTIVE); return member; } private FileMetadata getImage(final Member author, final String name) { final String path = FrameworkConfiguration.getWwwDir() + FrameworkConfiguration.getCommonsDir() + "/img/" + name; return FileMetadataManager.createFromLocalFile(author, null, path, name, "Projet's logo image"); } public static void main(final String[] args) throws UnauthorizedOperationException, NotEnoughMoneyException { System.out.println("Begining database generation"); new BloatitExampleDB(); System.out.println("Database generation ended"); System.exit(0); } }
false
true
public BloatitExampleDB() throws UnauthorizedOperationException, NotEnoughMoneyException { System.setProperty("log4J.path", ConfigurationManager.SHARE_DIR + "/log"); MailServer.getInstance().initialize(); SessionManager.beginWorkUnit(); fred = createMember("fred", "Frédéric Bertolus", Locale.FRANCE); thomas = createMember("thomas", "Thomas Guyard", Locale.FRANCE); yoann = createMember("yoann", "Yoann Plénet", Locale.US); admin = createMember("admin", "Administrator", Locale.FRANCE); admin.getDao().setRole(Role.ADMIN); chogall = createMember("chogall", "Cho'gall", Locale.UK); cerbere = createMember("cerbere", "Cerbère", Locale.KOREA); hydre = createMember("hydre", "Hydre", Locale.GERMANY); elephantman = createMember("elephantman", "ElephantMan", Locale.JAPAN); celeste = createMember("celeste", "Céleste", Locale.CHINA); rataxes = createMember("rataxes", "Rataxès", Locale.FRANCE); fred.getContact().setName("Frederic Bertolus"); fred.getContact().setStreet("Le superbe appartement à gauche"); thomas.getContact().setName("Thomas Guyard"); thomas.getContact().setStreet("Le superbe appartement à gauche"); yoann.getContact().setName("Yoann Plénet"); yoann.getContact().setStreet("Le superbe appartement à gauche"); // Add avatar chogall.setAvatar(getImage(chogall, "users/chogall.png")); cerbere.setAvatar(getImage(cerbere, "users/cerbere.png")); hydre.setAvatar(getImage(hydre, "users/hydre.png")); elephantman.setAvatar(getImage(elephantman, "users/elephantman.png")); celeste.setAvatar(getImage(celeste, "users/celeste.png")); rataxes.setAvatar(getImage(rataxes, "users/rataxes.png")); // Add money giveMoney(fred, 1000000); giveMoney(thomas, 2000000); giveMoney(yoann, 3000000); giveMoney(chogall, 2000); giveMoney(cerbere, 1000); giveMoney(hydre, 500); giveMoney(elephantman, 100000000); // Add withdrawal withdrawMoney(fred, 1000, State.REQUESTED); withdrawMoney(fred, 2000, State.TREATED); withdrawMoney(fred, 3000, State.REFUSED); withdrawMoney(fred, 4000, State.CANCELED); withdrawMoney(fred, 5000, State.COMPLETE); withdrawMoney(yoann, 1000, State.REQUESTED); withdrawMoney(yoann, 2000, State.TREATED); withdrawMoney(yoann, 3000, State.REFUSED); withdrawMoney(yoann, 4000, State.CANCELED); withdrawMoney(yoann, 5000, State.COMPLETE); withdrawMoney(thomas, 1000, State.REQUESTED); withdrawMoney(thomas, 2000, State.TREATED); withdrawMoney(thomas, 3000, State.REFUSED); withdrawMoney(thomas, 4000, State.CANCELED); withdrawMoney(thomas, 5000, State.COMPLETE); // Add teams final Team other = new Team("other", "[email protected]", "An other team", Right.PROTECTED, yoann); AuthToken.authenticate(yoann); other.setAvatar(getImage(yoann, "teams/other.png")); final Team b219 = new Team("b219", "[email protected]", "The team for b219", Right.PROTECTED, fred); AuthToken.authenticate(fred); b219.setAvatarUnprotected(getImage(fred, "teams/b219.png")); final Team ubuntuUsers = new Team("ubuntuUsers", "[email protected]", "The team for ubuntu users", Right.PUBLIC, thomas); AuthToken.authenticate(thomas); ubuntuUsers.setAvatarUnprotected(getImage(thomas, "teams/ubuntuUsers.png")); // Generate softwares generateVlcSoftware(); generatePerroquetSoftware(); generateLibreOfficeSoftware(); generateMageiaSoftware(); // Generate features final Feature twoSubtitlesInVlcFeature = generateVlcFeatureTwoSubtitles(); final Feature addPerroquetInMageiaFeature = generateMageiaFeaturePerroquetPackage(); final Feature colorPickerFeature = generateLibreOfficeFeatureColorPicker(); final Feature libreOfficeFeatureDefaultTemplate = generateLibreOfficeFeatureDefaultTemplate(); final Feature perroquetFeatureArabicSupport = generatePerroquetFeatureArabicSupport(); final Feature mageiaFeatureRemoveEmacs = generateMageiaFeatureRemoveEmacs(); // Highlight features new HighlightFeature(twoSubtitlesInVlcFeature, 1, "Popular", DateUtils.now(), DateUtils.flyingPigDate()); new HighlightFeature(colorPickerFeature, 2, "Recent", DateUtils.now(), DateUtils.flyingPigDate()); new HighlightFeature(addPerroquetInMageiaFeature, 3, "In developement", DateUtils.now(), DateUtils.flyingPigDate()); new HighlightFeature(libreOfficeFeatureDefaultTemplate, 4, "Need your help quicky", DateUtils.now(), DateUtils.flyingPigDate()); new HighlightFeature(perroquetFeatureArabicSupport, 5, "Random", DateUtils.now(), DateUtils.flyingPigDate()); new HighlightFeature(mageiaFeatureRemoveEmacs, 6, "Success", DateUtils.now(), DateUtils.flyingPigDate()); SessionManager.endWorkUnitAndFlush(); }
public BloatitExampleDB() throws UnauthorizedOperationException, NotEnoughMoneyException { System.setProperty("log4J.path", ConfigurationManager.SHARE_DIR + "/log"); MailServer.getInstance().initialize(); SessionManager.beginWorkUnit(); fred = createMember("fred", "Frédéric Bertolus", Locale.FRANCE); thomas = createMember("thomas", "Thomas Guyard", Locale.FRANCE); yoann = createMember("yoann", "Yoann Plénet", Locale.US); admin = createMember("admin", "Administrator", Locale.FRANCE); admin.getDao().setRole(Role.ADMIN); chogall = createMember("chogall", "Cho'gall", Locale.UK); cerbere = createMember("cerbere", "Cerbère", Locale.KOREA); hydre = createMember("hydre", "Hydre", Locale.GERMANY); elephantman = createMember("elephantman", "ElephantMan", Locale.JAPAN); celeste = createMember("celeste", "Céleste", Locale.CHINA); rataxes = createMember("rataxes", "Rataxès", Locale.FRANCE); AuthToken.authenticate(fred); fred.getContact().setName("Frederic Bertolus"); fred.getContact().setStreet("Le superbe appartement à gauche"); AuthToken.authenticate(thomas); thomas.getContact().setName("Thomas Guyard"); thomas.getContact().setStreet("Le superbe appartement à gauche"); AuthToken.authenticate(yoann); yoann.getContact().setName("Yoann Plénet"); yoann.getContact().setStreet("Le superbe appartement à gauche"); // Add avatar AuthToken.authenticate(chogall); chogall.setAvatar(getImage(chogall, "users/chogall.png")); AuthToken.authenticate(cerbere); cerbere.setAvatar(getImage(cerbere, "users/cerbere.png")); AuthToken.authenticate(hydre); hydre.setAvatar(getImage(hydre, "users/hydre.png")); AuthToken.authenticate(elephantman); elephantman.setAvatar(getImage(elephantman, "users/elephantman.png")); AuthToken.authenticate(celeste); celeste.setAvatar(getImage(celeste, "users/celeste.png")); AuthToken.authenticate(rataxes); rataxes.setAvatar(getImage(rataxes, "users/rataxes.png")); // Add money giveMoney(fred, 1000000); giveMoney(thomas, 2000000); giveMoney(yoann, 3000000); giveMoney(chogall, 2000); giveMoney(cerbere, 1000); giveMoney(hydre, 500); giveMoney(elephantman, 100000000); // Add withdrawal AuthToken.authenticate(fred); withdrawMoney(fred, 1000, State.REQUESTED); withdrawMoney(fred, 2000, State.TREATED); withdrawMoney(fred, 3000, State.REFUSED); withdrawMoney(fred, 4000, State.CANCELED); withdrawMoney(fred, 5000, State.COMPLETE); AuthToken.authenticate(yoann); withdrawMoney(yoann, 1000, State.REQUESTED); withdrawMoney(yoann, 2000, State.TREATED); withdrawMoney(yoann, 3000, State.REFUSED); withdrawMoney(yoann, 4000, State.CANCELED); withdrawMoney(yoann, 5000, State.COMPLETE); AuthToken.authenticate(thomas); withdrawMoney(thomas, 1000, State.REQUESTED); withdrawMoney(thomas, 2000, State.TREATED); withdrawMoney(thomas, 3000, State.REFUSED); withdrawMoney(thomas, 4000, State.CANCELED); withdrawMoney(thomas, 5000, State.COMPLETE); // Add teams final Team other = new Team("other", "[email protected]", "An other team", Right.PROTECTED, yoann); AuthToken.authenticate(yoann); other.setAvatar(getImage(yoann, "teams/other.png")); final Team b219 = new Team("b219", "[email protected]", "The team for b219", Right.PROTECTED, fred); AuthToken.authenticate(fred); b219.setAvatarUnprotected(getImage(fred, "teams/b219.png")); final Team ubuntuUsers = new Team("ubuntuUsers", "[email protected]", "The team for ubuntu users", Right.PUBLIC, thomas); AuthToken.authenticate(thomas); ubuntuUsers.setAvatarUnprotected(getImage(thomas, "teams/ubuntuUsers.png")); // Generate softwares generateVlcSoftware(); generatePerroquetSoftware(); generateLibreOfficeSoftware(); generateMageiaSoftware(); // Generate features final Feature twoSubtitlesInVlcFeature = generateVlcFeatureTwoSubtitles(); final Feature addPerroquetInMageiaFeature = generateMageiaFeaturePerroquetPackage(); final Feature colorPickerFeature = generateLibreOfficeFeatureColorPicker(); final Feature libreOfficeFeatureDefaultTemplate = generateLibreOfficeFeatureDefaultTemplate(); final Feature perroquetFeatureArabicSupport = generatePerroquetFeatureArabicSupport(); final Feature mageiaFeatureRemoveEmacs = generateMageiaFeatureRemoveEmacs(); // Highlight features new HighlightFeature(twoSubtitlesInVlcFeature, 1, "Popular", DateUtils.now(), DateUtils.flyingPigDate()); new HighlightFeature(colorPickerFeature, 2, "Recent", DateUtils.now(), DateUtils.flyingPigDate()); new HighlightFeature(addPerroquetInMageiaFeature, 3, "In developement", DateUtils.now(), DateUtils.flyingPigDate()); new HighlightFeature(libreOfficeFeatureDefaultTemplate, 4, "Need your help quicky", DateUtils.now(), DateUtils.flyingPigDate()); new HighlightFeature(perroquetFeatureArabicSupport, 5, "Random", DateUtils.now(), DateUtils.flyingPigDate()); new HighlightFeature(mageiaFeatureRemoveEmacs, 6, "Success", DateUtils.now(), DateUtils.flyingPigDate()); SessionManager.endWorkUnitAndFlush(); }
diff --git a/src/main/java/com/solidstategroup/radar/web/panels/PathologyPanel.java b/src/main/java/com/solidstategroup/radar/web/panels/PathologyPanel.java index abffc98b..80d15ac3 100644 --- a/src/main/java/com/solidstategroup/radar/web/panels/PathologyPanel.java +++ b/src/main/java/com/solidstategroup/radar/web/panels/PathologyPanel.java @@ -1,233 +1,235 @@ package com.solidstategroup.radar.web.panels; import com.solidstategroup.radar.model.enums.KidneyTransplantedNative; import com.solidstategroup.radar.model.sequenced.Pathology; import com.solidstategroup.radar.service.DemographicsManager; import com.solidstategroup.radar.service.DiagnosisManager; import com.solidstategroup.radar.service.PathologyManager; import com.solidstategroup.radar.web.components.RadarComponentFactory; import com.solidstategroup.radar.web.components.RadarRequiredDateTextField; import com.solidstategroup.radar.web.components.RadarTextFieldWithValidation; import com.solidstategroup.radar.web.models.RadarModelFactory; import com.solidstategroup.radar.web.pages.PatientPage; import org.apache.wicket.Component; import org.apache.wicket.MarkupContainer; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior; import org.apache.wicket.ajax.markup.html.AjaxLink; import org.apache.wicket.ajax.markup.html.form.AjaxSubmitLink; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.form.ChoiceRenderer; import org.apache.wicket.markup.html.form.DropDownChoice; import org.apache.wicket.markup.html.form.Form; import org.apache.wicket.markup.html.form.Radio; import org.apache.wicket.markup.html.form.RadioGroup; import org.apache.wicket.markup.html.form.TextArea; import org.apache.wicket.markup.html.form.TextField; import org.apache.wicket.markup.html.panel.ComponentFeedbackPanel; import org.apache.wicket.markup.html.panel.Panel; import org.apache.wicket.model.AbstractReadOnlyModel; import org.apache.wicket.model.CompoundPropertyModel; import org.apache.wicket.model.IModel; import org.apache.wicket.model.Model; import org.apache.wicket.model.PropertyModel; import org.apache.wicket.spring.injection.annot.SpringBean; import org.apache.wicket.validation.validator.RangeValidator; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class PathologyPanel extends Panel { @SpringBean private PathologyManager pathologyManager; @SpringBean private DemographicsManager demographicsManager; @SpringBean private DiagnosisManager diagnosisManager; public PathologyPanel(String id, final IModel<Long> radarNumberModel) { super(id); setOutputMarkupId(true); setOutputMarkupPlaceholderTag(true); // Model for tha pathology container, the pathology ID final IModel<Pathology> pathologyModel = new Model<Pathology>(); IModel pathologiesListModel = new AbstractReadOnlyModel<List>() { @Override public List getObject() { if (radarNumberModel.getObject() != null) { List list = pathologyManager.getPathologyByRadarNumber(radarNumberModel.getObject()); return !list.isEmpty() ? list : Collections.emptyList(); } return Collections.emptyList(); } }; // Container for form, so we can hide and first then show final MarkupContainer pathologyContainer = new WebMarkupContainer("pathologyContainer"); pathologyContainer.setVisible(false); pathologyContainer.setOutputMarkupId(true); pathologyContainer.setOutputMarkupPlaceholderTag(true); add(pathologyContainer); // Switcheroo final DropDownChoice<Pathology> pathologySwitcher = new DropDownChoice<Pathology>("pathologySwitcher", pathologyModel, pathologiesListModel, new ChoiceRenderer<Pathology>("biopsyDate", "id")); pathologySwitcher.setOutputMarkupId(true); pathologySwitcher.setOutputMarkupPlaceholderTag(true); add(pathologySwitcher); // Add new add(new AjaxLink("addNew") { @Override public void onClick(AjaxRequestTarget target) { pathologyContainer.setVisible(true); pathologyModel.setObject(new Pathology()); pathologySwitcher.clearInput(); target.add(pathologyContainer, pathologySwitcher); } }); // Add Ajax behaviour to switch the container on change pathologySwitcher.add(new AjaxFormComponentUpdatingBehavior("onchange") { @Override protected void onUpdate(AjaxRequestTarget target) { pathologyContainer.setVisible(true); target.add(pathologyContainer); } }); final List<Component> componentsToUpdate = new ArrayList<Component>(); componentsToUpdate.add(pathologySwitcher); // Set up model Form<Pathology> form = new Form<Pathology>("form", new CompoundPropertyModel<Pathology>(pathologyModel)) { @Override protected void onSubmit() { Pathology pathology = getModelObject(); pathology.setRadarNumber(radarNumberModel.getObject()); pathologyManager.savePathology(pathology); } }; pathologyContainer.add(form); RadarComponentFactory.getSuccessMessageLabel("successMessage", form, componentsToUpdate); RadarComponentFactory.getSuccessMessageLabel("successMessageDown", form, componentsToUpdate); RadarComponentFactory.getErrorMessageLabel("errorMessage", form, componentsToUpdate); RadarComponentFactory.getErrorMessageLabel("errorMessageDown", form, componentsToUpdate); // General details TextField<Long> radarNumber = new TextField<Long>("radarNumber", radarNumberModel); radarNumber.setEnabled(false); form.add(radarNumber); form.add(new TextField("hospitalNumber", RadarModelFactory.getHospitalNumberModel(radarNumberModel, demographicsManager))); form.add(new TextField("diagnosis", new PropertyModel(RadarModelFactory.getDiagnosisCodeModel(radarNumberModel, diagnosisManager), "abbreviation"))); form.add(new TextField("firstName", RadarModelFactory.getFirstNameModel(radarNumberModel, demographicsManager))); form.add(new TextField("surname", RadarModelFactory.getSurnameModel(radarNumberModel, demographicsManager))); form.add(new TextField("dob", RadarModelFactory.getDobModel(radarNumberModel, demographicsManager))); // Add inputs form.add(new RadarRequiredDateTextField("biopsyDate", form, componentsToUpdate)); RadioGroup<KidneyTransplantedNative> kideneyTransplant = new RadioGroup<KidneyTransplantedNative>("KidneyTransplantedNative"); kideneyTransplant.add(new Radio<KidneyTransplantedNative>("native", new Model<KidneyTransplantedNative>(KidneyTransplantedNative.NATIVE))); kideneyTransplant.add(new Radio<KidneyTransplantedNative>("txKidney", new Model<KidneyTransplantedNative>(KidneyTransplantedNative.TRANSPLANTED))); form.add(kideneyTransplant); RadioGroup<Pathology.Side> side = new RadioGroup<Pathology.Side>("side"); side.add(new Radio<Pathology.Side>("left", new Model<Pathology.Side>(Pathology.Side.LEFT))); side.add(new Radio<Pathology.Side>("right", new Model<Pathology.Side>(Pathology.Side.RIGHT))); form.add(side); form.add(new TextField("sampleLabNumber")); form.add(new TextArea("interstitalInflmatoryInfilitrate")); form.add(new TextArea("arterialAbnormalities")); form.add(new TextArea("immunohistologicalFindings")); form.add(new TextArea("electronMicroscopicFindings")); - form.add(new TextField("estimatedTubules")); - form.add(new TextField("measuredTubules")); + form.add(new RadarTextFieldWithValidation("estimatedTubules", new RangeValidator<Double>(0.0, 100.0), + form, componentsToUpdate)); + form.add(new RadarTextFieldWithValidation("measuredTubules", + new RangeValidator<Double>(0.0, 100.0), form, componentsToUpdate)); form.add(new TextArea("tubulesOtherFeature")); form.add(new TextField("imageUrl1")); form.add(new TextField("imageUrl2")); form.add(new TextField("imageUrl3")); form.add(new TextField("imageUrl4")); form.add(new TextField("imageUrl5")); form.add(new RadarTextFieldWithValidation("totalNumber", new RangeValidator<Integer>(0, 150), form, componentsToUpdate)); form.add(new RadarTextFieldWithValidation("numberSclerosed", new RangeValidator<Integer>(0, 150), form, componentsToUpdate)); form.add(new RadarTextFieldWithValidation("numberSegmentallySclerosed", new RangeValidator<Integer>(0, 150), form, componentsToUpdate)); form.add(new RadarTextFieldWithValidation("numberCellularCrescents", new RangeValidator<Integer>(0, 150), form, componentsToUpdate)); form.add(new RadarTextFieldWithValidation("numberFibrousCrescents", new RangeValidator<Integer>(0, 150), form, componentsToUpdate)); form.add(new RadarTextFieldWithValidation("numberEndocapillaryHypercelluarity", new RangeValidator<Integer>(0, 150), form, componentsToUpdate)); form.add(new RadarTextFieldWithValidation("numberFibrinoidNecrosis", new RangeValidator<Integer>(0, 150), form, componentsToUpdate)); form.add(new TextArea("otherFeature")); form.add(new TextArea("histologicalSummary")); form.add(new PathologySubmitLink("save", form) { @Override protected List<Component> getComponentsToUpdate() { return componentsToUpdate; } }); form.add(new PathologySubmitLink("saveDown", form) { @Override protected List<Component> getComponentsToUpdate() { return componentsToUpdate; } }); } @Override public boolean isVisible() { return ((PatientPage) getPage()).getCurrentTab().equals(PatientPage.CurrentTab.PATHOLOGY); } private abstract class PathologySubmitLink extends AjaxSubmitLink { protected PathologySubmitLink(String id, Form<?> form) { super(id, form); } @Override protected void onSubmit(AjaxRequestTarget target, Form<?> form) { target.add(getComponentsToUpdate().toArray(new Component[getComponentsToUpdate().size()])); } @Override protected void onError(AjaxRequestTarget target, Form<?> form) { target.add(getComponentsToUpdate().toArray(new Component[getComponentsToUpdate().size()])); ComponentFeedbackPanel a = (ComponentFeedbackPanel) getParent().get("totalNumberFeedback"); a.getFeedbackMessages(); } protected abstract List<Component> getComponentsToUpdate(); } }
true
true
public PathologyPanel(String id, final IModel<Long> radarNumberModel) { super(id); setOutputMarkupId(true); setOutputMarkupPlaceholderTag(true); // Model for tha pathology container, the pathology ID final IModel<Pathology> pathologyModel = new Model<Pathology>(); IModel pathologiesListModel = new AbstractReadOnlyModel<List>() { @Override public List getObject() { if (radarNumberModel.getObject() != null) { List list = pathologyManager.getPathologyByRadarNumber(radarNumberModel.getObject()); return !list.isEmpty() ? list : Collections.emptyList(); } return Collections.emptyList(); } }; // Container for form, so we can hide and first then show final MarkupContainer pathologyContainer = new WebMarkupContainer("pathologyContainer"); pathologyContainer.setVisible(false); pathologyContainer.setOutputMarkupId(true); pathologyContainer.setOutputMarkupPlaceholderTag(true); add(pathologyContainer); // Switcheroo final DropDownChoice<Pathology> pathologySwitcher = new DropDownChoice<Pathology>("pathologySwitcher", pathologyModel, pathologiesListModel, new ChoiceRenderer<Pathology>("biopsyDate", "id")); pathologySwitcher.setOutputMarkupId(true); pathologySwitcher.setOutputMarkupPlaceholderTag(true); add(pathologySwitcher); // Add new add(new AjaxLink("addNew") { @Override public void onClick(AjaxRequestTarget target) { pathologyContainer.setVisible(true); pathologyModel.setObject(new Pathology()); pathologySwitcher.clearInput(); target.add(pathologyContainer, pathologySwitcher); } }); // Add Ajax behaviour to switch the container on change pathologySwitcher.add(new AjaxFormComponentUpdatingBehavior("onchange") { @Override protected void onUpdate(AjaxRequestTarget target) { pathologyContainer.setVisible(true); target.add(pathologyContainer); } }); final List<Component> componentsToUpdate = new ArrayList<Component>(); componentsToUpdate.add(pathologySwitcher); // Set up model Form<Pathology> form = new Form<Pathology>("form", new CompoundPropertyModel<Pathology>(pathologyModel)) { @Override protected void onSubmit() { Pathology pathology = getModelObject(); pathology.setRadarNumber(radarNumberModel.getObject()); pathologyManager.savePathology(pathology); } }; pathologyContainer.add(form); RadarComponentFactory.getSuccessMessageLabel("successMessage", form, componentsToUpdate); RadarComponentFactory.getSuccessMessageLabel("successMessageDown", form, componentsToUpdate); RadarComponentFactory.getErrorMessageLabel("errorMessage", form, componentsToUpdate); RadarComponentFactory.getErrorMessageLabel("errorMessageDown", form, componentsToUpdate); // General details TextField<Long> radarNumber = new TextField<Long>("radarNumber", radarNumberModel); radarNumber.setEnabled(false); form.add(radarNumber); form.add(new TextField("hospitalNumber", RadarModelFactory.getHospitalNumberModel(radarNumberModel, demographicsManager))); form.add(new TextField("diagnosis", new PropertyModel(RadarModelFactory.getDiagnosisCodeModel(radarNumberModel, diagnosisManager), "abbreviation"))); form.add(new TextField("firstName", RadarModelFactory.getFirstNameModel(radarNumberModel, demographicsManager))); form.add(new TextField("surname", RadarModelFactory.getSurnameModel(radarNumberModel, demographicsManager))); form.add(new TextField("dob", RadarModelFactory.getDobModel(radarNumberModel, demographicsManager))); // Add inputs form.add(new RadarRequiredDateTextField("biopsyDate", form, componentsToUpdate)); RadioGroup<KidneyTransplantedNative> kideneyTransplant = new RadioGroup<KidneyTransplantedNative>("KidneyTransplantedNative"); kideneyTransplant.add(new Radio<KidneyTransplantedNative>("native", new Model<KidneyTransplantedNative>(KidneyTransplantedNative.NATIVE))); kideneyTransplant.add(new Radio<KidneyTransplantedNative>("txKidney", new Model<KidneyTransplantedNative>(KidneyTransplantedNative.TRANSPLANTED))); form.add(kideneyTransplant); RadioGroup<Pathology.Side> side = new RadioGroup<Pathology.Side>("side"); side.add(new Radio<Pathology.Side>("left", new Model<Pathology.Side>(Pathology.Side.LEFT))); side.add(new Radio<Pathology.Side>("right", new Model<Pathology.Side>(Pathology.Side.RIGHT))); form.add(side); form.add(new TextField("sampleLabNumber")); form.add(new TextArea("interstitalInflmatoryInfilitrate")); form.add(new TextArea("arterialAbnormalities")); form.add(new TextArea("immunohistologicalFindings")); form.add(new TextArea("electronMicroscopicFindings")); form.add(new TextField("estimatedTubules")); form.add(new TextField("measuredTubules")); form.add(new TextArea("tubulesOtherFeature")); form.add(new TextField("imageUrl1")); form.add(new TextField("imageUrl2")); form.add(new TextField("imageUrl3")); form.add(new TextField("imageUrl4")); form.add(new TextField("imageUrl5")); form.add(new RadarTextFieldWithValidation("totalNumber", new RangeValidator<Integer>(0, 150), form, componentsToUpdate)); form.add(new RadarTextFieldWithValidation("numberSclerosed", new RangeValidator<Integer>(0, 150), form, componentsToUpdate)); form.add(new RadarTextFieldWithValidation("numberSegmentallySclerosed", new RangeValidator<Integer>(0, 150), form, componentsToUpdate)); form.add(new RadarTextFieldWithValidation("numberCellularCrescents", new RangeValidator<Integer>(0, 150), form, componentsToUpdate)); form.add(new RadarTextFieldWithValidation("numberFibrousCrescents", new RangeValidator<Integer>(0, 150), form, componentsToUpdate)); form.add(new RadarTextFieldWithValidation("numberEndocapillaryHypercelluarity", new RangeValidator<Integer>(0, 150), form, componentsToUpdate)); form.add(new RadarTextFieldWithValidation("numberFibrinoidNecrosis", new RangeValidator<Integer>(0, 150), form, componentsToUpdate)); form.add(new TextArea("otherFeature")); form.add(new TextArea("histologicalSummary")); form.add(new PathologySubmitLink("save", form) { @Override protected List<Component> getComponentsToUpdate() { return componentsToUpdate; } }); form.add(new PathologySubmitLink("saveDown", form) { @Override protected List<Component> getComponentsToUpdate() { return componentsToUpdate; } }); }
public PathologyPanel(String id, final IModel<Long> radarNumberModel) { super(id); setOutputMarkupId(true); setOutputMarkupPlaceholderTag(true); // Model for tha pathology container, the pathology ID final IModel<Pathology> pathologyModel = new Model<Pathology>(); IModel pathologiesListModel = new AbstractReadOnlyModel<List>() { @Override public List getObject() { if (radarNumberModel.getObject() != null) { List list = pathologyManager.getPathologyByRadarNumber(radarNumberModel.getObject()); return !list.isEmpty() ? list : Collections.emptyList(); } return Collections.emptyList(); } }; // Container for form, so we can hide and first then show final MarkupContainer pathologyContainer = new WebMarkupContainer("pathologyContainer"); pathologyContainer.setVisible(false); pathologyContainer.setOutputMarkupId(true); pathologyContainer.setOutputMarkupPlaceholderTag(true); add(pathologyContainer); // Switcheroo final DropDownChoice<Pathology> pathologySwitcher = new DropDownChoice<Pathology>("pathologySwitcher", pathologyModel, pathologiesListModel, new ChoiceRenderer<Pathology>("biopsyDate", "id")); pathologySwitcher.setOutputMarkupId(true); pathologySwitcher.setOutputMarkupPlaceholderTag(true); add(pathologySwitcher); // Add new add(new AjaxLink("addNew") { @Override public void onClick(AjaxRequestTarget target) { pathologyContainer.setVisible(true); pathologyModel.setObject(new Pathology()); pathologySwitcher.clearInput(); target.add(pathologyContainer, pathologySwitcher); } }); // Add Ajax behaviour to switch the container on change pathologySwitcher.add(new AjaxFormComponentUpdatingBehavior("onchange") { @Override protected void onUpdate(AjaxRequestTarget target) { pathologyContainer.setVisible(true); target.add(pathologyContainer); } }); final List<Component> componentsToUpdate = new ArrayList<Component>(); componentsToUpdate.add(pathologySwitcher); // Set up model Form<Pathology> form = new Form<Pathology>("form", new CompoundPropertyModel<Pathology>(pathologyModel)) { @Override protected void onSubmit() { Pathology pathology = getModelObject(); pathology.setRadarNumber(radarNumberModel.getObject()); pathologyManager.savePathology(pathology); } }; pathologyContainer.add(form); RadarComponentFactory.getSuccessMessageLabel("successMessage", form, componentsToUpdate); RadarComponentFactory.getSuccessMessageLabel("successMessageDown", form, componentsToUpdate); RadarComponentFactory.getErrorMessageLabel("errorMessage", form, componentsToUpdate); RadarComponentFactory.getErrorMessageLabel("errorMessageDown", form, componentsToUpdate); // General details TextField<Long> radarNumber = new TextField<Long>("radarNumber", radarNumberModel); radarNumber.setEnabled(false); form.add(radarNumber); form.add(new TextField("hospitalNumber", RadarModelFactory.getHospitalNumberModel(radarNumberModel, demographicsManager))); form.add(new TextField("diagnosis", new PropertyModel(RadarModelFactory.getDiagnosisCodeModel(radarNumberModel, diagnosisManager), "abbreviation"))); form.add(new TextField("firstName", RadarModelFactory.getFirstNameModel(radarNumberModel, demographicsManager))); form.add(new TextField("surname", RadarModelFactory.getSurnameModel(radarNumberModel, demographicsManager))); form.add(new TextField("dob", RadarModelFactory.getDobModel(radarNumberModel, demographicsManager))); // Add inputs form.add(new RadarRequiredDateTextField("biopsyDate", form, componentsToUpdate)); RadioGroup<KidneyTransplantedNative> kideneyTransplant = new RadioGroup<KidneyTransplantedNative>("KidneyTransplantedNative"); kideneyTransplant.add(new Radio<KidneyTransplantedNative>("native", new Model<KidneyTransplantedNative>(KidneyTransplantedNative.NATIVE))); kideneyTransplant.add(new Radio<KidneyTransplantedNative>("txKidney", new Model<KidneyTransplantedNative>(KidneyTransplantedNative.TRANSPLANTED))); form.add(kideneyTransplant); RadioGroup<Pathology.Side> side = new RadioGroup<Pathology.Side>("side"); side.add(new Radio<Pathology.Side>("left", new Model<Pathology.Side>(Pathology.Side.LEFT))); side.add(new Radio<Pathology.Side>("right", new Model<Pathology.Side>(Pathology.Side.RIGHT))); form.add(side); form.add(new TextField("sampleLabNumber")); form.add(new TextArea("interstitalInflmatoryInfilitrate")); form.add(new TextArea("arterialAbnormalities")); form.add(new TextArea("immunohistologicalFindings")); form.add(new TextArea("electronMicroscopicFindings")); form.add(new RadarTextFieldWithValidation("estimatedTubules", new RangeValidator<Double>(0.0, 100.0), form, componentsToUpdate)); form.add(new RadarTextFieldWithValidation("measuredTubules", new RangeValidator<Double>(0.0, 100.0), form, componentsToUpdate)); form.add(new TextArea("tubulesOtherFeature")); form.add(new TextField("imageUrl1")); form.add(new TextField("imageUrl2")); form.add(new TextField("imageUrl3")); form.add(new TextField("imageUrl4")); form.add(new TextField("imageUrl5")); form.add(new RadarTextFieldWithValidation("totalNumber", new RangeValidator<Integer>(0, 150), form, componentsToUpdate)); form.add(new RadarTextFieldWithValidation("numberSclerosed", new RangeValidator<Integer>(0, 150), form, componentsToUpdate)); form.add(new RadarTextFieldWithValidation("numberSegmentallySclerosed", new RangeValidator<Integer>(0, 150), form, componentsToUpdate)); form.add(new RadarTextFieldWithValidation("numberCellularCrescents", new RangeValidator<Integer>(0, 150), form, componentsToUpdate)); form.add(new RadarTextFieldWithValidation("numberFibrousCrescents", new RangeValidator<Integer>(0, 150), form, componentsToUpdate)); form.add(new RadarTextFieldWithValidation("numberEndocapillaryHypercelluarity", new RangeValidator<Integer>(0, 150), form, componentsToUpdate)); form.add(new RadarTextFieldWithValidation("numberFibrinoidNecrosis", new RangeValidator<Integer>(0, 150), form, componentsToUpdate)); form.add(new TextArea("otherFeature")); form.add(new TextArea("histologicalSummary")); form.add(new PathologySubmitLink("save", form) { @Override protected List<Component> getComponentsToUpdate() { return componentsToUpdate; } }); form.add(new PathologySubmitLink("saveDown", form) { @Override protected List<Component> getComponentsToUpdate() { return componentsToUpdate; } }); }
diff --git a/src/main/java/be/Balor/Manager/Permissions/PermParent.java b/src/main/java/be/Balor/Manager/Permissions/PermParent.java index e9c01f9f..37359897 100644 --- a/src/main/java/be/Balor/Manager/Permissions/PermParent.java +++ b/src/main/java/be/Balor/Manager/Permissions/PermParent.java @@ -1,164 +1,164 @@ /************************************************************************ * This file is part of AdminCmd. * * AdminCmd 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. * * AdminCmd 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 AdminCmd. If not, see <http://www.gnu.org/licenses/>. ************************************************************************/ package be.Balor.Manager.Permissions; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; import org.bukkit.permissions.Permission; import org.bukkit.permissions.PermissionDefault; import be.Balor.bukkit.AdminCmd.ACPluginManager; /** * @author Balor (aka Antoine Aflalo) * */ public class PermParent extends PermChild { protected final String compareName; protected final Set<PermChild> children = new HashSet<PermChild>(); public final static PermParent ROOT = new PermParent(null, null); public final static PermParent ALONE = new PermParent(null, null); public PermParent(String perm) { this(perm, ROOT); } public PermParent(String perm, PermParent parent) { this(perm, perm == null ? null : perm.substring(0, perm.length() - 1), PermissionDefault.OP, parent); } public PermParent(String perm, String compare, PermissionDefault def, PermParent parent) { super(perm, parent, true, def); this.compareName = compare; } /** * @return the compareName */ public String getCompareName() { return compareName; } /** * @return the permName */ public String getPermName() { return permName; } /** * Add a permission Child to the Permission Parent * * @param perm * @return the PermParent (this) */ public PermParent addChild(PermChild perm) throws IllegalArgumentException { if (perm.equals(this)) throw new IllegalArgumentException("The Child can't be the parent."); children.add(perm); perm.parent = this; if (!(perm instanceof PermParent)) perm.registerPermission(); return this; } /** * Add a permission Child to the Permission Parent * * @param perm * @return the PermParent (this) */ public PermParent addChild(String perm) { PermChild child = new PermChild(perm, this); child.registerPermission(); children.add(child); return this; } /** * @return the children to be registered by the bukkit API. */ private Map<String, Boolean> getChildren() { Map<String, Boolean> childrenMap = new LinkedHashMap<String, Boolean>(); for (PermChild child : children) childrenMap.put(child.getPermName(), child.isSet()); return childrenMap; } /* * (non-Javadoc) * * @see be.Balor.Manager.Permissions.PermChild#registerPermission() */ @Override void registerPermission() { if (registered) return; + for (PermChild child : children) + child.registerPermission(); if (permName == null) return; - for (PermChild child : children) - child.registerPermission(); final Permission perm = ACPluginManager.getServer().getPluginManager() .getPermission(permName); if (perm == null) ACPluginManager.getServer().getPluginManager() .addPermission(new Permission(permName, permDefault, getChildren())); else perm.getChildren().putAll(getChildren()); registered = true; } /* * (non-Javadoc) * * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((compareName == null) ? 0 : compareName.hashCode()); return result; } /* * (non-Javadoc) * * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (!(obj instanceof PermParent)) return false; PermParent other = (PermParent) obj; if (compareName == null) { if (other.compareName != null) return false; } else if (!compareName.equals(other.compareName)) return false; return true; } }
false
true
void registerPermission() { if (registered) return; if (permName == null) return; for (PermChild child : children) child.registerPermission(); final Permission perm = ACPluginManager.getServer().getPluginManager() .getPermission(permName); if (perm == null) ACPluginManager.getServer().getPluginManager() .addPermission(new Permission(permName, permDefault, getChildren())); else perm.getChildren().putAll(getChildren()); registered = true; }
void registerPermission() { if (registered) return; for (PermChild child : children) child.registerPermission(); if (permName == null) return; final Permission perm = ACPluginManager.getServer().getPluginManager() .getPermission(permName); if (perm == null) ACPluginManager.getServer().getPluginManager() .addPermission(new Permission(permName, permDefault, getChildren())); else perm.getChildren().putAll(getChildren()); registered = true; }
diff --git a/src/com/jidesoft/plaf/basic/BasicJidePopupMenuUI.java b/src/com/jidesoft/plaf/basic/BasicJidePopupMenuUI.java index a9d14212..15b39d43 100644 --- a/src/com/jidesoft/plaf/basic/BasicJidePopupMenuUI.java +++ b/src/com/jidesoft/plaf/basic/BasicJidePopupMenuUI.java @@ -1,56 +1,56 @@ /* * @(#)BasicJidePopupMenuUI.java 12/13/2006 * * Copyright 2002 - 2006 JIDE Software Inc. All rights reserved. */ package com.jidesoft.plaf.basic; import com.jidesoft.swing.JidePopupMenu; import com.jidesoft.swing.SimpleScrollPane; import javax.swing.*; import javax.swing.plaf.ComponentUI; import javax.swing.plaf.basic.BasicPopupMenuUI; import javax.swing.plaf.basic.DefaultMenuLayout; public class BasicJidePopupMenuUI extends BasicPopupMenuUI { public BasicJidePopupMenuUI() { } @SuppressWarnings({"UnusedDeclaration"}) public static ComponentUI createUI(JComponent c) { return new BasicJidePopupMenuUI(); } @Override public Popup getPopup(JPopupMenu popupMenu, int x, int y) { Popup popup = BasicJidePopupMenuUI.addScrollPaneIfNecessary(popupMenu, x, y); return popup == null ? super.getPopup(popupMenu, x, y) : popup; } /** * Adds a scroll pane to the popup menu if the popup menu is taller than the screen boundary. * * @param popupMenu the popup menu. * @param x the x origin * @param y the y origin * @return Popup */ public static Popup addScrollPaneIfNecessary(JPopupMenu popupMenu, int x, int y) { + SimpleScrollPane contents = new SimpleScrollPane(popupMenu, SimpleScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, SimpleScrollPane.HORIZONTAL_SCROLLBAR_NEVER); if (popupMenu instanceof JidePopupMenu && popupMenu.getPreferredSize().height != ((JidePopupMenu) popupMenu).getPreferredScrollableViewportSize().height) { if (popupMenu.getLayout() instanceof DefaultMenuLayout) { popupMenu.setLayout(new BoxLayout(popupMenu, ((DefaultMenuLayout) popupMenu.getLayout()).getAxis())); } PopupFactory popupFactory = PopupFactory.getSharedInstance(); - SimpleScrollPane contents = new SimpleScrollPane(popupMenu, SimpleScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, SimpleScrollPane.HORIZONTAL_SCROLLBAR_NEVER); contents.getScrollUpButton().setOpaque(true); contents.getScrollDownButton().setOpaque(true); contents.setBorder(BorderFactory.createEmptyBorder()); return popupFactory.getPopup(popupMenu.getInvoker(), contents, x, y); } else { return null; } } }
false
true
public static Popup addScrollPaneIfNecessary(JPopupMenu popupMenu, int x, int y) { if (popupMenu instanceof JidePopupMenu && popupMenu.getPreferredSize().height != ((JidePopupMenu) popupMenu).getPreferredScrollableViewportSize().height) { if (popupMenu.getLayout() instanceof DefaultMenuLayout) { popupMenu.setLayout(new BoxLayout(popupMenu, ((DefaultMenuLayout) popupMenu.getLayout()).getAxis())); } PopupFactory popupFactory = PopupFactory.getSharedInstance(); SimpleScrollPane contents = new SimpleScrollPane(popupMenu, SimpleScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, SimpleScrollPane.HORIZONTAL_SCROLLBAR_NEVER); contents.getScrollUpButton().setOpaque(true); contents.getScrollDownButton().setOpaque(true); contents.setBorder(BorderFactory.createEmptyBorder()); return popupFactory.getPopup(popupMenu.getInvoker(), contents, x, y); } else { return null; } }
public static Popup addScrollPaneIfNecessary(JPopupMenu popupMenu, int x, int y) { SimpleScrollPane contents = new SimpleScrollPane(popupMenu, SimpleScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, SimpleScrollPane.HORIZONTAL_SCROLLBAR_NEVER); if (popupMenu instanceof JidePopupMenu && popupMenu.getPreferredSize().height != ((JidePopupMenu) popupMenu).getPreferredScrollableViewportSize().height) { if (popupMenu.getLayout() instanceof DefaultMenuLayout) { popupMenu.setLayout(new BoxLayout(popupMenu, ((DefaultMenuLayout) popupMenu.getLayout()).getAxis())); } PopupFactory popupFactory = PopupFactory.getSharedInstance(); contents.getScrollUpButton().setOpaque(true); contents.getScrollDownButton().setOpaque(true); contents.setBorder(BorderFactory.createEmptyBorder()); return popupFactory.getPopup(popupMenu.getInvoker(), contents, x, y); } else { return null; } }
diff --git a/ini/trakem2/display/Stack.java b/ini/trakem2/display/Stack.java index 45135dda..ad10811d 100644 --- a/ini/trakem2/display/Stack.java +++ b/ini/trakem2/display/Stack.java @@ -1,555 +1,556 @@ /** * */ package ini.trakem2.display; import ij.IJ; import ij.ImagePlus; import ij.process.ImageProcessor; import ini.trakem2.Project; import ini.trakem2.display.graphics.ARGBComposite; import ini.trakem2.display.graphics.AddARGBComposite; import ini.trakem2.display.graphics.ColorYCbCrComposite; import ini.trakem2.display.graphics.DifferenceARGBComposite; import ini.trakem2.display.graphics.MultiplyARGBComposite; import ini.trakem2.display.graphics.SubtractARGBComposite; import ini.trakem2.utils.M; import ini.trakem2.utils.Utils; import java.awt.AlphaComposite; import java.awt.Composite; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Polygon; import java.awt.Rectangle; import java.awt.geom.AffineTransform; import java.awt.geom.Area; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.TreeMap; import java.util.concurrent.Callable; import java.util.concurrent.Future; import mpicbg.ij.stack.InverseTransformMapping; import mpicbg.ij.util.Filter; import mpicbg.models.AffineModel2D; import mpicbg.models.AffineModel3D; import mpicbg.models.Boundable; import mpicbg.models.InvertibleCoordinateTransformList; import mpicbg.models.TranslationModel3D; import mpicbg.trakem2.transform.InvertibleCoordinateTransform; import mpicbg.util.Util; /** * @author saalfeld * */ public class Stack extends ZDisplayable { private String file_path; private double depth = -1; private double min; private double max; private InvertibleCoordinateTransform ict; final private float[] boundsMin = new float[]{ 0, 0, 0 }; final private float[] boundsMax = new float[]{ 0, 0, 0 }; private double ictScale = 1.0; /* * References cached images in Loader whose unique identifier from the * prespective of the stack are double:magnification and double:z. */ final private HashMap< SliceViewKey, Long > cachedImages = new HashMap< SliceViewKey, Long >(); final private HashMap< Long, Future< Image > > futureImages = new HashMap< Long, Future<Image> >(); private static class SliceViewKey { final double magnification; final double z; SliceViewKey( final double magnification, final double z ) { this.magnification = magnification; this.z = z; } @Override final public boolean equals( Object o ) { final SliceViewKey k = ( SliceViewKey )o; return k.magnification == magnification && k.z == z; } @Override final public int hashCode() { return 0; } } public Stack( final Project project, final String title, double x, double y, Layer initial_layer, final String file_path ) { super( project, title, x, y ); this.file_path = file_path; // ct ==> initial_layer; final ImagePlus imp = project.getLoader().fetchImagePlus( this ); /* TODO scale regarding the Calibration and shift regarding x, y and the initial_layer */ depth = imp.getNSlices(); width = imp.getWidth(); height = imp.getHeight(); min = imp.getDisplayRangeMin(); max = imp.getDisplayRangeMax(); at.translate( x, y ); boundsMin[ 0 ] = ( float )x; boundsMin[ 1 ] = ( float )y; boundsMin[ 2 ] = ( float )initial_layer.getZ(); boundsMax[ 0 ] = ( float )( x + width ); boundsMax[ 1 ] = ( float )( y + height ); boundsMax[ 2 ] = ( float )( boundsMin[ 2 ] + depth ); addToDatabase(); } /** Construct a Stack from an XML entry. */ public Stack(Project project, long id, HashMap ht, HashMap ht_links) { super(project, id, ht, ht_links); // parse specific fields final Iterator it = ht.entrySet().iterator(); while (it.hasNext()) { final Map.Entry entry = (Map.Entry)it.next(); final String key = (String)entry.getKey(); final String data = (String)entry.getValue(); if (key.equals("min")) { this.min = Double.parseDouble(data); } else if (key.equals("max")) { this.max = Double.parseDouble(data); } else if (key.equals("file_path")) { this.file_path = data; } else if (key.equals("depth")) { this.depth = Double.parseDouble(data); } } boundsMin[ 0 ] = 0; boundsMin[ 1 ] = 0; boundsMin[ 2 ] = 0; boundsMax[ 0 ] = ( float )width; boundsMax[ 1 ] = ( float )height; boundsMax[ 2 ] = ( float )depth; } public InvertibleCoordinateTransform getInvertibleCoordinateTransform() { return ict; } /* (non-Javadoc) * @see ini.trakem2.display.ZDisplayable#getFirstLayer() */ @Override public Layer getFirstLayer() { // TODO Auto-generated method stub return null; } /* (non-Javadoc) * @see ini.trakem2.display.ZDisplayable#intersects(java.awt.geom.Area, double, double) */ @Override public boolean intersects( Area area, double z_first, double z_last ) { // TODO Auto-generated method stub return false; } /* (non-Javadoc) * @see ini.trakem2.display.ZDisplayable#linkPatches() */ @Override public void linkPatches() { // TODO Auto-generated method stub } /* (non-Javadoc) * @see ini.trakem2.display.Displayable#clone(ini.trakem2.Project, boolean) */ @Override public Displayable clone( Project pr, boolean copy_id ) { // TODO Auto-generated method stub return null; } /* (non-Javadoc) * @see ini.trakem2.display.Displayable#isDeletable() */ @Override public boolean isDeletable() { // TODO Auto-generated method stub return false; } public String getFilePath(){ return this.file_path; } public long estimateImageFileSize() { if ( -1 == depth ) return IJ.maxMemory() / 2; return (long) (width * height * depth * 4); } /** * Estimate the scale of atp to apply the * appropriate smoothing to the image. */ final static private float estimateAffineScale( final AffineTransform atp ) { float d = 0; /* add */ final float aX = ( float )atp.getScaleX() + ( float )atp.getShearX(); final float aY = ( float )atp.getShearY() + ( float )atp.getScaleY(); d = Math.max( d, aX * aX + aY * aY ); /* subtract */ final float sX = ( float )atp.getScaleX() - ( float )atp.getShearX(); final float sY = ( float )atp.getShearY() - ( float )atp.getScaleY(); d = Math.max( d, sX * sX + sY * sY ); return Util.SQRT1 / ( float )Math.sqrt( d ); } @Override public void paint( final Graphics2D g, final double magnification, final boolean active, final int channels, final Layer active_layer ) { final AffineTransform atp = new AffineTransform( this.at ); //final Image image = project.getLoader().fetchImage(this,0); //Utils.log2("Patch " + id + " painted image " + image); final double currentZ = active_layer.getZ(); Image image = null; synchronized ( cachedImages ) { final SliceViewKey sliceViewKey = new SliceViewKey( magnification, currentZ ); final long imageId; Long imageIdL = cachedImages.get( sliceViewKey ); if ( imageIdL == null ) { imageId = project.getLoader().getNextTempId(); cachedImages.put( sliceViewKey, imageId ); } else { /* fetch the image from cache---still, it may be that it is not there... */ imageId = imageIdL; image = project.getLoader().getCached( cachedImages.get( sliceViewKey ), 0 ); } if ( image == null ) { /* image has to be generated */ synchronized ( futureImages ) { Future< Image > fu = futureImages.get( imageId ); if ( null == fu ) { futureImages.put( imageId, project.getLoader().doLater( new Callable< Image >() { public Image call() { final InvertibleCoordinateTransformList< mpicbg.models.InvertibleCoordinateTransform > ictl = new InvertibleCoordinateTransformList< mpicbg.models.InvertibleCoordinateTransform >(); if ( ict != null ) { + Utils.log2( "ictScale of " + getTitle() + " is " + ictScale ); ictl.add( ict ); /* Remove boundingBox shift ict ... */ final TranslationModel3D unShiftBounds = new TranslationModel3D(); unShiftBounds.set( -boundsMin[ 0 ], -boundsMin[ 1 ], 0 ); ictl.add( unShiftBounds ); if ( ictScale != 1.0 ) { final AffineModel3D unScaleXY = new AffineModel3D(); unScaleXY.set( 1.0f / ( float )ictScale, 0, 0, 0, 0, 1.0f / ( float )ictScale, 0, 0, 0, 0, 1.0f, 0 ); ictl.add( unScaleXY ); } } /* TODO remove that scale from ict and put it into atp */ final ImagePlus imp = project.getLoader().fetchImagePlus( Stack.this ); final ImageProcessor ip = imp.getStack().getProcessor( 1 ).createProcessor( ( int )Math.ceil( ( boundsMax[ 0 ] - boundsMin[ 0 ] ) / ictScale ), ( int )Math.ceil( ( boundsMax[ 1 ] - boundsMin[ 1 ] ) / ictScale ) ); final TranslationModel3D sliceShift = new TranslationModel3D(); sliceShift.set( 0, 0, ( float )-currentZ ); ictl.add( sliceShift ); final InverseTransformMapping< InvertibleCoordinateTransformList< mpicbg.models.InvertibleCoordinateTransform > > mapping = new InverseTransformMapping< InvertibleCoordinateTransformList< mpicbg.models.InvertibleCoordinateTransform > >( ictl ); mapping.mapInterpolated( imp.getStack(), ip ); final float s = estimateAffineScale( atp ); final float smoothMag = ( float )magnification / s; if ( smoothMag < 1.0f ) { Filter.smoothForScale( ip, smoothMag, 0.5f, 0.5f ); } final Image image = ip.createImage(); if ( null == image ) { Utils.log2( "Stack.paint: null image, returning" ); return null; // TEMPORARY from lazy // repaints after closing a // Project } project.getLoader().cacheAWT( imageId, image ); synchronized ( futureImages ) { futureImages.remove( imageId ); } // Display.repaint( active_layer, Stack.this ); Display.repaint( active_layer ); return image; } } ) ); } // else { // Utils.log2( "fu is not null" ); // // We don't do anything: we wait for itself to launch a // repaint event // } } } } if ( image != null) { /* Put boundShift into atp */ final AffineTransform shiftBounds = new AffineTransform( 1, 0, 0, 1, boundsMin[ 0 ], boundsMin[ 1 ] ); atp.concatenate( shiftBounds ); /* If available, incorporate the involved x,y-scale of ict in the AffineTransform */ final AffineTransform asict = new AffineTransform( ictScale, 0, 0, ictScale, 0, 0 ); atp.concatenate( asict ); final Composite original_composite = g.getComposite(); g.setComposite( getComposite() ); g.drawImage( image, atp, null ); g.setComposite( original_composite ); } } static public final void exportDTD( final StringBuffer sb_header, final HashSet hs, final String indent ) { String type = "t2_stack"; if (hs.contains(type)) return; hs.add( type ); sb_header.append(indent).append("<!ELEMENT t2_stack (").append(Displayable.commonDTDChildren()).append(",(iict_transform|iict_transform_list)?)>\n"); Displayable.exportDTD( type, sb_header, hs, indent ); sb_header.append(indent).append(TAG_ATTR1).append(type).append(" file_path CDATA #REQUIRED>\n") .append(indent).append(TAG_ATTR1).append(type).append(" depth CDATA #REQUIRED>\n"); } /** Opens and closes the tag and exports data. The image is saved in the directory provided in @param any as a String. */ public void exportXML(StringBuffer sb_body, String indent, Object any) { // TODO the Loader should handle the saving of images, not this class. String in = indent + "\t"; sb_body.append(indent).append("<t2_stack\n"); String rel_path = null; super.exportXML(sb_body, in, any); String[] RGB = Utils.getHexRGBColor(color); sb_body.append(in).append("file_path=\"").append(file_path).append("\"\n") .append(in).append("style=\"fill-opacity:").append(alpha).append(";stroke:#").append(RGB[0]).append(RGB[1]).append(RGB[2]).append(";\"\n") .append(in).append("depth=\"").append(depth).append("\"\n") .append(in).append("min=\"").append(min).append("\"\n") .append(in).append("max=\"").append(max).append("\"\n") ; sb_body.append(indent).append(">\n"); if (null != ict) { sb_body.append(ict.toXML(in)).append('\n'); } super.restXML(sb_body, in, any); sb_body.append(indent).append("</t2_stack>\n"); } @Override protected Rectangle getBounds( final Rectangle rect ) { final AffineModel2D a = new AffineModel2D(); a.set( at ); final float[] rMin = new float[]{ Float.MAX_VALUE, Float.MAX_VALUE }; final float[] rMax = new float[]{ -Float.MAX_VALUE, -Float.MAX_VALUE }; final float[] l = new float[]{ boundsMin[ 0 ], boundsMin[ 1 ] }; a.applyInPlace( l ); Util.min( rMin, l ); Util.max( rMax, l ); l[ 0 ] = boundsMin[ 0 ]; l[ 1 ] = boundsMax[ 1 ]; a.applyInPlace( l ); Util.min( rMin, l ); Util.max( rMax, l ); l[ 0 ] = boundsMax[ 0 ]; l[ 1 ] = boundsMin[ 1 ]; a.applyInPlace( l ); Util.min( rMin, l ); Util.max( rMax, l ); l[ 0 ] = boundsMax[ 0 ]; l[ 1 ] = boundsMax[ 1 ]; a.applyInPlace( l ); Util.min( rMin, l ); Util.max( rMax, l ); rect.x = ( int )rMin[ 0 ]; rect.y = ( int )rMin[ 1 ]; rect.width = ( int )Math.ceil( rMax[ 0 ] - rect.x ); rect.height = ( int )Math.ceil( rMax[ 1 ] - rect.y ); return rect; } - private void updateBounds() + private void update() { boundsMin[ 0 ] = 0; boundsMin[ 1 ] = 0; boundsMin[ 2 ] = 0; boundsMax[ 0 ] = ( float )width; boundsMax[ 1 ] = ( float )height; boundsMax[ 2 ] = ( float )depth; if ( ict == null ) { // Utils.log2( "ict is null" ); return; } else if ( Boundable.class.isInstance( ict ) ) { // Utils.log2( ict + " is a boundable" ); ( ( Boundable )ict ).estimateBounds( boundsMin, boundsMax ); // Utils.log2( ict + "its bounds are (" + boundsMin[ 0 ] + ", " + boundsMin[ 1 ] + ", " + boundsMin[ 2 ] + ") -> (" + boundsMax[ 0 ] + ", " + boundsMax[ 1 ] + ", " + boundsMax[ 2 ] + ")" ); } else { Utils.log2( ict + " is not a boundable" ); final ArrayList< Layer > layers = layer_set.getLayers(); boundsMax[ 0 ] = ( float )layer_set.width; boundsMax[ 1 ] = ( float )layer_set.height; boundsMax[ 2 ] = ( float )( layers.get( layers.size() - 1 ).getZ() - layers.get( 0 ).getZ() ); } if ( ict != null ) { if ( AffineModel3D.class.isInstance( ict ) ) { float d = 0; final float[] m = ( ( AffineModel3D )ict ).getMatrix( null ); /* add x and y */ final float axyX = m[ 0 ] + m[ 1 ]; final float axyY = m[ 4 ] + m[ 5 ]; d = Math.max( d, axyX * axyX + axyY * axyY ); /* subtract x and y */ final float sxyX = m[ 0 ] - m[ 1 ]; final float sxyY = m[ 4 ] - m[ 5 ]; d = Math.max( d, sxyX * sxyX + sxyY * sxyY ); /* add x and z */ final float axzX = m[ 0 ] + m[ 2 ]; final float axzY = m[ 4 ] + m[ 6 ]; d = Math.max( d, axzX * axzX + axzY * axzY ); /* subtract x and z */ final float sxzX = m[ 0 ] - m[ 2 ]; final float sxzY = m[ 4 ] - m[ 6 ]; d = Math.max( d, sxzX * sxzX + sxzY * sxzY ); /* add y and z */ final float ayzX = m[ 1 ] + m[ 2 ]; final float ayzY = m[ 5 ] + m[ 6 ]; d = Math.max( d, ayzX * ayzX + ayzY * ayzY ); /* subtract y and z */ final float syzX = m[ 1 ] - m[ 2 ]; final float syzY = m[ 5 ] - m[ 6 ]; d = Math.max( d, syzX * syzX + syzY * syzY ); - ictScale = Util.SQRT1 / ( float )Math.sqrt( d ); + ictScale = ( float )Math.sqrt( d ) / Util.SQRT1; } } } /** * For now, just returns the bounding box---we can refine this later */ public Polygon getPerimeter() { final Rectangle r = getBoundingBox(); return new Polygon( new int[]{ r.x, r.x + r.width, r.x + r.width, r.x }, new int[]{ r.y, r.y, r.y + r.height, r.y + r.height }, 4 ); } /** For reconstruction purposes, overwrites the present InvertibleCoordinateTransform, if any, with the given one. */ public void setInvertibleCoordinateTransformSilently( final InvertibleCoordinateTransform ict ) { Utils.log2( "insering the ict" ); this.ict = ict; - updateBounds(); + update(); } private void invalidateCache() { cachedImages.clear(); } public void setInvertibleCoordinateTransform( final InvertibleCoordinateTransform ict ) { invalidateCache(); setInvertibleCoordinateTransformSilently( ict ); } public void setAffineTransform( final AffineTransform at ) { invalidateCache(); super.setAffineTransform( at ); } }
false
true
public void paint( final Graphics2D g, final double magnification, final boolean active, final int channels, final Layer active_layer ) { final AffineTransform atp = new AffineTransform( this.at ); //final Image image = project.getLoader().fetchImage(this,0); //Utils.log2("Patch " + id + " painted image " + image); final double currentZ = active_layer.getZ(); Image image = null; synchronized ( cachedImages ) { final SliceViewKey sliceViewKey = new SliceViewKey( magnification, currentZ ); final long imageId; Long imageIdL = cachedImages.get( sliceViewKey ); if ( imageIdL == null ) { imageId = project.getLoader().getNextTempId(); cachedImages.put( sliceViewKey, imageId ); } else { /* fetch the image from cache---still, it may be that it is not there... */ imageId = imageIdL; image = project.getLoader().getCached( cachedImages.get( sliceViewKey ), 0 ); } if ( image == null ) { /* image has to be generated */ synchronized ( futureImages ) { Future< Image > fu = futureImages.get( imageId ); if ( null == fu ) { futureImages.put( imageId, project.getLoader().doLater( new Callable< Image >() { public Image call() { final InvertibleCoordinateTransformList< mpicbg.models.InvertibleCoordinateTransform > ictl = new InvertibleCoordinateTransformList< mpicbg.models.InvertibleCoordinateTransform >(); if ( ict != null ) { ictl.add( ict ); /* Remove boundingBox shift ict ... */ final TranslationModel3D unShiftBounds = new TranslationModel3D(); unShiftBounds.set( -boundsMin[ 0 ], -boundsMin[ 1 ], 0 ); ictl.add( unShiftBounds ); if ( ictScale != 1.0 ) { final AffineModel3D unScaleXY = new AffineModel3D(); unScaleXY.set( 1.0f / ( float )ictScale, 0, 0, 0, 0, 1.0f / ( float )ictScale, 0, 0, 0, 0, 1.0f, 0 ); ictl.add( unScaleXY ); } } /* TODO remove that scale from ict and put it into atp */ final ImagePlus imp = project.getLoader().fetchImagePlus( Stack.this ); final ImageProcessor ip = imp.getStack().getProcessor( 1 ).createProcessor( ( int )Math.ceil( ( boundsMax[ 0 ] - boundsMin[ 0 ] ) / ictScale ), ( int )Math.ceil( ( boundsMax[ 1 ] - boundsMin[ 1 ] ) / ictScale ) ); final TranslationModel3D sliceShift = new TranslationModel3D(); sliceShift.set( 0, 0, ( float )-currentZ ); ictl.add( sliceShift ); final InverseTransformMapping< InvertibleCoordinateTransformList< mpicbg.models.InvertibleCoordinateTransform > > mapping = new InverseTransformMapping< InvertibleCoordinateTransformList< mpicbg.models.InvertibleCoordinateTransform > >( ictl ); mapping.mapInterpolated( imp.getStack(), ip ); final float s = estimateAffineScale( atp ); final float smoothMag = ( float )magnification / s; if ( smoothMag < 1.0f ) { Filter.smoothForScale( ip, smoothMag, 0.5f, 0.5f ); } final Image image = ip.createImage(); if ( null == image ) { Utils.log2( "Stack.paint: null image, returning" ); return null; // TEMPORARY from lazy // repaints after closing a // Project } project.getLoader().cacheAWT( imageId, image ); synchronized ( futureImages ) { futureImages.remove( imageId ); } // Display.repaint( active_layer, Stack.this ); Display.repaint( active_layer ); return image; } } ) ); } // else { // Utils.log2( "fu is not null" ); // // We don't do anything: we wait for itself to launch a // repaint event // } } } } if ( image != null) { /* Put boundShift into atp */ final AffineTransform shiftBounds = new AffineTransform( 1, 0, 0, 1, boundsMin[ 0 ], boundsMin[ 1 ] ); atp.concatenate( shiftBounds ); /* If available, incorporate the involved x,y-scale of ict in the AffineTransform */ final AffineTransform asict = new AffineTransform( ictScale, 0, 0, ictScale, 0, 0 ); atp.concatenate( asict ); final Composite original_composite = g.getComposite(); g.setComposite( getComposite() ); g.drawImage( image, atp, null ); g.setComposite( original_composite ); } } static public final void exportDTD( final StringBuffer sb_header, final HashSet hs, final String indent ) { String type = "t2_stack"; if (hs.contains(type)) return; hs.add( type ); sb_header.append(indent).append("<!ELEMENT t2_stack (").append(Displayable.commonDTDChildren()).append(",(iict_transform|iict_transform_list)?)>\n"); Displayable.exportDTD( type, sb_header, hs, indent ); sb_header.append(indent).append(TAG_ATTR1).append(type).append(" file_path CDATA #REQUIRED>\n") .append(indent).append(TAG_ATTR1).append(type).append(" depth CDATA #REQUIRED>\n"); } /** Opens and closes the tag and exports data. The image is saved in the directory provided in @param any as a String. */ public void exportXML(StringBuffer sb_body, String indent, Object any) { // TODO the Loader should handle the saving of images, not this class. String in = indent + "\t"; sb_body.append(indent).append("<t2_stack\n"); String rel_path = null; super.exportXML(sb_body, in, any); String[] RGB = Utils.getHexRGBColor(color); sb_body.append(in).append("file_path=\"").append(file_path).append("\"\n") .append(in).append("style=\"fill-opacity:").append(alpha).append(";stroke:#").append(RGB[0]).append(RGB[1]).append(RGB[2]).append(";\"\n") .append(in).append("depth=\"").append(depth).append("\"\n") .append(in).append("min=\"").append(min).append("\"\n") .append(in).append("max=\"").append(max).append("\"\n") ; sb_body.append(indent).append(">\n"); if (null != ict) { sb_body.append(ict.toXML(in)).append('\n'); } super.restXML(sb_body, in, any); sb_body.append(indent).append("</t2_stack>\n"); } @Override protected Rectangle getBounds( final Rectangle rect ) { final AffineModel2D a = new AffineModel2D(); a.set( at ); final float[] rMin = new float[]{ Float.MAX_VALUE, Float.MAX_VALUE }; final float[] rMax = new float[]{ -Float.MAX_VALUE, -Float.MAX_VALUE }; final float[] l = new float[]{ boundsMin[ 0 ], boundsMin[ 1 ] }; a.applyInPlace( l ); Util.min( rMin, l ); Util.max( rMax, l ); l[ 0 ] = boundsMin[ 0 ]; l[ 1 ] = boundsMax[ 1 ]; a.applyInPlace( l ); Util.min( rMin, l ); Util.max( rMax, l ); l[ 0 ] = boundsMax[ 0 ]; l[ 1 ] = boundsMin[ 1 ]; a.applyInPlace( l ); Util.min( rMin, l ); Util.max( rMax, l ); l[ 0 ] = boundsMax[ 0 ]; l[ 1 ] = boundsMax[ 1 ]; a.applyInPlace( l ); Util.min( rMin, l ); Util.max( rMax, l ); rect.x = ( int )rMin[ 0 ]; rect.y = ( int )rMin[ 1 ]; rect.width = ( int )Math.ceil( rMax[ 0 ] - rect.x ); rect.height = ( int )Math.ceil( rMax[ 1 ] - rect.y ); return rect; } private void updateBounds() { boundsMin[ 0 ] = 0; boundsMin[ 1 ] = 0; boundsMin[ 2 ] = 0; boundsMax[ 0 ] = ( float )width; boundsMax[ 1 ] = ( float )height; boundsMax[ 2 ] = ( float )depth; if ( ict == null ) { // Utils.log2( "ict is null" ); return; } else if ( Boundable.class.isInstance( ict ) ) { // Utils.log2( ict + " is a boundable" ); ( ( Boundable )ict ).estimateBounds( boundsMin, boundsMax ); // Utils.log2( ict + "its bounds are (" + boundsMin[ 0 ] + ", " + boundsMin[ 1 ] + ", " + boundsMin[ 2 ] + ") -> (" + boundsMax[ 0 ] + ", " + boundsMax[ 1 ] + ", " + boundsMax[ 2 ] + ")" ); } else { Utils.log2( ict + " is not a boundable" ); final ArrayList< Layer > layers = layer_set.getLayers(); boundsMax[ 0 ] = ( float )layer_set.width; boundsMax[ 1 ] = ( float )layer_set.height; boundsMax[ 2 ] = ( float )( layers.get( layers.size() - 1 ).getZ() - layers.get( 0 ).getZ() ); } if ( ict != null ) { if ( AffineModel3D.class.isInstance( ict ) ) { float d = 0; final float[] m = ( ( AffineModel3D )ict ).getMatrix( null ); /* add x and y */ final float axyX = m[ 0 ] + m[ 1 ]; final float axyY = m[ 4 ] + m[ 5 ]; d = Math.max( d, axyX * axyX + axyY * axyY ); /* subtract x and y */ final float sxyX = m[ 0 ] - m[ 1 ]; final float sxyY = m[ 4 ] - m[ 5 ]; d = Math.max( d, sxyX * sxyX + sxyY * sxyY ); /* add x and z */ final float axzX = m[ 0 ] + m[ 2 ]; final float axzY = m[ 4 ] + m[ 6 ]; d = Math.max( d, axzX * axzX + axzY * axzY ); /* subtract x and z */ final float sxzX = m[ 0 ] - m[ 2 ]; final float sxzY = m[ 4 ] - m[ 6 ]; d = Math.max( d, sxzX * sxzX + sxzY * sxzY ); /* add y and z */ final float ayzX = m[ 1 ] + m[ 2 ]; final float ayzY = m[ 5 ] + m[ 6 ]; d = Math.max( d, ayzX * ayzX + ayzY * ayzY ); /* subtract y and z */ final float syzX = m[ 1 ] - m[ 2 ]; final float syzY = m[ 5 ] - m[ 6 ]; d = Math.max( d, syzX * syzX + syzY * syzY ); ictScale = Util.SQRT1 / ( float )Math.sqrt( d ); } } } /** * For now, just returns the bounding box---we can refine this later */ public Polygon getPerimeter() { final Rectangle r = getBoundingBox(); return new Polygon( new int[]{ r.x, r.x + r.width, r.x + r.width, r.x }, new int[]{ r.y, r.y, r.y + r.height, r.y + r.height }, 4 ); } /** For reconstruction purposes, overwrites the present InvertibleCoordinateTransform, if any, with the given one. */ public void setInvertibleCoordinateTransformSilently( final InvertibleCoordinateTransform ict ) { Utils.log2( "insering the ict" ); this.ict = ict; updateBounds(); } private void invalidateCache() { cachedImages.clear(); } public void setInvertibleCoordinateTransform( final InvertibleCoordinateTransform ict ) { invalidateCache(); setInvertibleCoordinateTransformSilently( ict ); } public void setAffineTransform( final AffineTransform at ) { invalidateCache(); super.setAffineTransform( at ); } }
public void paint( final Graphics2D g, final double magnification, final boolean active, final int channels, final Layer active_layer ) { final AffineTransform atp = new AffineTransform( this.at ); //final Image image = project.getLoader().fetchImage(this,0); //Utils.log2("Patch " + id + " painted image " + image); final double currentZ = active_layer.getZ(); Image image = null; synchronized ( cachedImages ) { final SliceViewKey sliceViewKey = new SliceViewKey( magnification, currentZ ); final long imageId; Long imageIdL = cachedImages.get( sliceViewKey ); if ( imageIdL == null ) { imageId = project.getLoader().getNextTempId(); cachedImages.put( sliceViewKey, imageId ); } else { /* fetch the image from cache---still, it may be that it is not there... */ imageId = imageIdL; image = project.getLoader().getCached( cachedImages.get( sliceViewKey ), 0 ); } if ( image == null ) { /* image has to be generated */ synchronized ( futureImages ) { Future< Image > fu = futureImages.get( imageId ); if ( null == fu ) { futureImages.put( imageId, project.getLoader().doLater( new Callable< Image >() { public Image call() { final InvertibleCoordinateTransformList< mpicbg.models.InvertibleCoordinateTransform > ictl = new InvertibleCoordinateTransformList< mpicbg.models.InvertibleCoordinateTransform >(); if ( ict != null ) { Utils.log2( "ictScale of " + getTitle() + " is " + ictScale ); ictl.add( ict ); /* Remove boundingBox shift ict ... */ final TranslationModel3D unShiftBounds = new TranslationModel3D(); unShiftBounds.set( -boundsMin[ 0 ], -boundsMin[ 1 ], 0 ); ictl.add( unShiftBounds ); if ( ictScale != 1.0 ) { final AffineModel3D unScaleXY = new AffineModel3D(); unScaleXY.set( 1.0f / ( float )ictScale, 0, 0, 0, 0, 1.0f / ( float )ictScale, 0, 0, 0, 0, 1.0f, 0 ); ictl.add( unScaleXY ); } } /* TODO remove that scale from ict and put it into atp */ final ImagePlus imp = project.getLoader().fetchImagePlus( Stack.this ); final ImageProcessor ip = imp.getStack().getProcessor( 1 ).createProcessor( ( int )Math.ceil( ( boundsMax[ 0 ] - boundsMin[ 0 ] ) / ictScale ), ( int )Math.ceil( ( boundsMax[ 1 ] - boundsMin[ 1 ] ) / ictScale ) ); final TranslationModel3D sliceShift = new TranslationModel3D(); sliceShift.set( 0, 0, ( float )-currentZ ); ictl.add( sliceShift ); final InverseTransformMapping< InvertibleCoordinateTransformList< mpicbg.models.InvertibleCoordinateTransform > > mapping = new InverseTransformMapping< InvertibleCoordinateTransformList< mpicbg.models.InvertibleCoordinateTransform > >( ictl ); mapping.mapInterpolated( imp.getStack(), ip ); final float s = estimateAffineScale( atp ); final float smoothMag = ( float )magnification / s; if ( smoothMag < 1.0f ) { Filter.smoothForScale( ip, smoothMag, 0.5f, 0.5f ); } final Image image = ip.createImage(); if ( null == image ) { Utils.log2( "Stack.paint: null image, returning" ); return null; // TEMPORARY from lazy // repaints after closing a // Project } project.getLoader().cacheAWT( imageId, image ); synchronized ( futureImages ) { futureImages.remove( imageId ); } // Display.repaint( active_layer, Stack.this ); Display.repaint( active_layer ); return image; } } ) ); } // else { // Utils.log2( "fu is not null" ); // // We don't do anything: we wait for itself to launch a // repaint event // } } } } if ( image != null) { /* Put boundShift into atp */ final AffineTransform shiftBounds = new AffineTransform( 1, 0, 0, 1, boundsMin[ 0 ], boundsMin[ 1 ] ); atp.concatenate( shiftBounds ); /* If available, incorporate the involved x,y-scale of ict in the AffineTransform */ final AffineTransform asict = new AffineTransform( ictScale, 0, 0, ictScale, 0, 0 ); atp.concatenate( asict ); final Composite original_composite = g.getComposite(); g.setComposite( getComposite() ); g.drawImage( image, atp, null ); g.setComposite( original_composite ); } } static public final void exportDTD( final StringBuffer sb_header, final HashSet hs, final String indent ) { String type = "t2_stack"; if (hs.contains(type)) return; hs.add( type ); sb_header.append(indent).append("<!ELEMENT t2_stack (").append(Displayable.commonDTDChildren()).append(",(iict_transform|iict_transform_list)?)>\n"); Displayable.exportDTD( type, sb_header, hs, indent ); sb_header.append(indent).append(TAG_ATTR1).append(type).append(" file_path CDATA #REQUIRED>\n") .append(indent).append(TAG_ATTR1).append(type).append(" depth CDATA #REQUIRED>\n"); } /** Opens and closes the tag and exports data. The image is saved in the directory provided in @param any as a String. */ public void exportXML(StringBuffer sb_body, String indent, Object any) { // TODO the Loader should handle the saving of images, not this class. String in = indent + "\t"; sb_body.append(indent).append("<t2_stack\n"); String rel_path = null; super.exportXML(sb_body, in, any); String[] RGB = Utils.getHexRGBColor(color); sb_body.append(in).append("file_path=\"").append(file_path).append("\"\n") .append(in).append("style=\"fill-opacity:").append(alpha).append(";stroke:#").append(RGB[0]).append(RGB[1]).append(RGB[2]).append(";\"\n") .append(in).append("depth=\"").append(depth).append("\"\n") .append(in).append("min=\"").append(min).append("\"\n") .append(in).append("max=\"").append(max).append("\"\n") ; sb_body.append(indent).append(">\n"); if (null != ict) { sb_body.append(ict.toXML(in)).append('\n'); } super.restXML(sb_body, in, any); sb_body.append(indent).append("</t2_stack>\n"); } @Override protected Rectangle getBounds( final Rectangle rect ) { final AffineModel2D a = new AffineModel2D(); a.set( at ); final float[] rMin = new float[]{ Float.MAX_VALUE, Float.MAX_VALUE }; final float[] rMax = new float[]{ -Float.MAX_VALUE, -Float.MAX_VALUE }; final float[] l = new float[]{ boundsMin[ 0 ], boundsMin[ 1 ] }; a.applyInPlace( l ); Util.min( rMin, l ); Util.max( rMax, l ); l[ 0 ] = boundsMin[ 0 ]; l[ 1 ] = boundsMax[ 1 ]; a.applyInPlace( l ); Util.min( rMin, l ); Util.max( rMax, l ); l[ 0 ] = boundsMax[ 0 ]; l[ 1 ] = boundsMin[ 1 ]; a.applyInPlace( l ); Util.min( rMin, l ); Util.max( rMax, l ); l[ 0 ] = boundsMax[ 0 ]; l[ 1 ] = boundsMax[ 1 ]; a.applyInPlace( l ); Util.min( rMin, l ); Util.max( rMax, l ); rect.x = ( int )rMin[ 0 ]; rect.y = ( int )rMin[ 1 ]; rect.width = ( int )Math.ceil( rMax[ 0 ] - rect.x ); rect.height = ( int )Math.ceil( rMax[ 1 ] - rect.y ); return rect; } private void update() { boundsMin[ 0 ] = 0; boundsMin[ 1 ] = 0; boundsMin[ 2 ] = 0; boundsMax[ 0 ] = ( float )width; boundsMax[ 1 ] = ( float )height; boundsMax[ 2 ] = ( float )depth; if ( ict == null ) { // Utils.log2( "ict is null" ); return; } else if ( Boundable.class.isInstance( ict ) ) { // Utils.log2( ict + " is a boundable" ); ( ( Boundable )ict ).estimateBounds( boundsMin, boundsMax ); // Utils.log2( ict + "its bounds are (" + boundsMin[ 0 ] + ", " + boundsMin[ 1 ] + ", " + boundsMin[ 2 ] + ") -> (" + boundsMax[ 0 ] + ", " + boundsMax[ 1 ] + ", " + boundsMax[ 2 ] + ")" ); } else { Utils.log2( ict + " is not a boundable" ); final ArrayList< Layer > layers = layer_set.getLayers(); boundsMax[ 0 ] = ( float )layer_set.width; boundsMax[ 1 ] = ( float )layer_set.height; boundsMax[ 2 ] = ( float )( layers.get( layers.size() - 1 ).getZ() - layers.get( 0 ).getZ() ); } if ( ict != null ) { if ( AffineModel3D.class.isInstance( ict ) ) { float d = 0; final float[] m = ( ( AffineModel3D )ict ).getMatrix( null ); /* add x and y */ final float axyX = m[ 0 ] + m[ 1 ]; final float axyY = m[ 4 ] + m[ 5 ]; d = Math.max( d, axyX * axyX + axyY * axyY ); /* subtract x and y */ final float sxyX = m[ 0 ] - m[ 1 ]; final float sxyY = m[ 4 ] - m[ 5 ]; d = Math.max( d, sxyX * sxyX + sxyY * sxyY ); /* add x and z */ final float axzX = m[ 0 ] + m[ 2 ]; final float axzY = m[ 4 ] + m[ 6 ]; d = Math.max( d, axzX * axzX + axzY * axzY ); /* subtract x and z */ final float sxzX = m[ 0 ] - m[ 2 ]; final float sxzY = m[ 4 ] - m[ 6 ]; d = Math.max( d, sxzX * sxzX + sxzY * sxzY ); /* add y and z */ final float ayzX = m[ 1 ] + m[ 2 ]; final float ayzY = m[ 5 ] + m[ 6 ]; d = Math.max( d, ayzX * ayzX + ayzY * ayzY ); /* subtract y and z */ final float syzX = m[ 1 ] - m[ 2 ]; final float syzY = m[ 5 ] - m[ 6 ]; d = Math.max( d, syzX * syzX + syzY * syzY ); ictScale = ( float )Math.sqrt( d ) / Util.SQRT1; } } } /** * For now, just returns the bounding box---we can refine this later */ public Polygon getPerimeter() { final Rectangle r = getBoundingBox(); return new Polygon( new int[]{ r.x, r.x + r.width, r.x + r.width, r.x }, new int[]{ r.y, r.y, r.y + r.height, r.y + r.height }, 4 ); } /** For reconstruction purposes, overwrites the present InvertibleCoordinateTransform, if any, with the given one. */ public void setInvertibleCoordinateTransformSilently( final InvertibleCoordinateTransform ict ) { Utils.log2( "insering the ict" ); this.ict = ict; update(); } private void invalidateCache() { cachedImages.clear(); } public void setInvertibleCoordinateTransform( final InvertibleCoordinateTransform ict ) { invalidateCache(); setInvertibleCoordinateTransformSilently( ict ); } public void setAffineTransform( final AffineTransform at ) { invalidateCache(); super.setAffineTransform( at ); } }
diff --git a/TheAdventure/src/se/chalmers/kangaroo/view/KangarooAnimation.java b/TheAdventure/src/se/chalmers/kangaroo/view/KangarooAnimation.java index 6b3f3a8..798d4a5 100644 --- a/TheAdventure/src/se/chalmers/kangaroo/view/KangarooAnimation.java +++ b/TheAdventure/src/se/chalmers/kangaroo/view/KangarooAnimation.java @@ -1,96 +1,96 @@ package se.chalmers.kangaroo.view; import java.awt.Graphics; import java.awt.Image; import java.awt.Toolkit; import se.chalmers.kangaroo.model.kangaroo.Kangaroo; import se.chalmers.kangaroo.model.utils.Direction; /** * A class representing the animation of the Kangaroo. * @author simonal * */ public class KangarooAnimation implements Animation { private Image rightSheet; private Image leftSheet; private String lastSheet; private int widthPerFrame; private int height; private int tick; private int currentFrame; private Kangaroo kangaroo; /** * Constructor taking the pathname and width and height of the animation. * @param pathName * @param width * @param height */ public KangarooAnimation(Kangaroo k,int width, int height) { rightSheet = Toolkit.getDefaultToolkit().getImage("resources/gfx/sheets/kangaroo_58x64_right.png"); leftSheet = Toolkit.getDefaultToolkit().getImage("resources/gfx/sheets/kangaroo_58x64_left.png"); lastSheet = "rightSheet"; currentFrame = 0; this.widthPerFrame = width; this.height = height; this.kangaroo = k; tick = 0; } /** * Draws the animation once every half second if the game is running in 60 ups. */ @Override public void drawSprite(Graphics g, int x, int y) { if (tick == 9) { tick = 0; currentFrame++; currentFrame = (currentFrame % 3); } if (kangaroo.getVerticalSpeed() != 0) { if(kangaroo.getDirection() == Direction.DIRECTION_EAST) { g.drawImage(rightSheet, (x-widthPerFrame/2)+10, y-height, (x+widthPerFrame/2)+10, y, widthPerFrame*2, 1, widthPerFrame*3, height, null, null); this.lastSheet = "rightSheet"; } else if (kangaroo.getDirection() == Direction.DIRECTION_WEST) { g.drawImage(leftSheet, x-5, y-height, x+widthPerFrame-5, y, widthPerFrame*2, 1, widthPerFrame*3, height, null, null); this.lastSheet = "leftSheet"; } else if (kangaroo.getDirection() == Direction.DIRECTION_NONE) { if(lastSheet == "leftSheet") { - g.drawImage(leftSheet, x-5, y-height, x+widthPerFrame-5, y, - 1, 1, widthPerFrame, height, null, null); + g.drawImage(leftSheet,(x-widthPerFrame/2)+15, y-height, (x+widthPerFrame/2)+15, y, + widthPerFrame*2, 1, widthPerFrame*3, height, null, null); } if(lastSheet == "rightSheet") { g.drawImage(rightSheet, (x-widthPerFrame/2)+10, y-height, (x+widthPerFrame/2)+10, y, - 1, 1, widthPerFrame, height, null, null); + widthPerFrame*2, 1, widthPerFrame*3, height, null, null); } } } else if(kangaroo.getDirection() == Direction.DIRECTION_EAST) { g.drawImage(rightSheet, (x-widthPerFrame/2)+10, y-height, (x+widthPerFrame/2)+10, y, (currentFrame * widthPerFrame), 1, (currentFrame * widthPerFrame) + widthPerFrame, height, null, null); this.lastSheet = "rightSheet"; } else if (kangaroo.getDirection() == Direction.DIRECTION_WEST) { g.drawImage(leftSheet, x-5, y-height, x+widthPerFrame-5, y, (currentFrame * widthPerFrame), 1, (currentFrame * widthPerFrame) + widthPerFrame, height, null, null); this.lastSheet = "leftSheet"; } else if (kangaroo.getDirection() == Direction.DIRECTION_NONE) { if(lastSheet == "leftSheet") { g.drawImage(leftSheet, x-5, y-height, x+widthPerFrame-5, y, 1, 1, widthPerFrame, height, null, null); } if(lastSheet == "rightSheet") { g.drawImage(rightSheet, (x-widthPerFrame/2)+10, y-height, (x+widthPerFrame/2)+10, y, 1, 1, widthPerFrame, height, null, null); } } tick++; } }
false
true
public void drawSprite(Graphics g, int x, int y) { if (tick == 9) { tick = 0; currentFrame++; currentFrame = (currentFrame % 3); } if (kangaroo.getVerticalSpeed() != 0) { if(kangaroo.getDirection() == Direction.DIRECTION_EAST) { g.drawImage(rightSheet, (x-widthPerFrame/2)+10, y-height, (x+widthPerFrame/2)+10, y, widthPerFrame*2, 1, widthPerFrame*3, height, null, null); this.lastSheet = "rightSheet"; } else if (kangaroo.getDirection() == Direction.DIRECTION_WEST) { g.drawImage(leftSheet, x-5, y-height, x+widthPerFrame-5, y, widthPerFrame*2, 1, widthPerFrame*3, height, null, null); this.lastSheet = "leftSheet"; } else if (kangaroo.getDirection() == Direction.DIRECTION_NONE) { if(lastSheet == "leftSheet") { g.drawImage(leftSheet, x-5, y-height, x+widthPerFrame-5, y, 1, 1, widthPerFrame, height, null, null); } if(lastSheet == "rightSheet") { g.drawImage(rightSheet, (x-widthPerFrame/2)+10, y-height, (x+widthPerFrame/2)+10, y, 1, 1, widthPerFrame, height, null, null); } } } else if(kangaroo.getDirection() == Direction.DIRECTION_EAST) { g.drawImage(rightSheet, (x-widthPerFrame/2)+10, y-height, (x+widthPerFrame/2)+10, y, (currentFrame * widthPerFrame), 1, (currentFrame * widthPerFrame) + widthPerFrame, height, null, null); this.lastSheet = "rightSheet"; } else if (kangaroo.getDirection() == Direction.DIRECTION_WEST) { g.drawImage(leftSheet, x-5, y-height, x+widthPerFrame-5, y, (currentFrame * widthPerFrame), 1, (currentFrame * widthPerFrame) + widthPerFrame, height, null, null); this.lastSheet = "leftSheet"; } else if (kangaroo.getDirection() == Direction.DIRECTION_NONE) { if(lastSheet == "leftSheet") { g.drawImage(leftSheet, x-5, y-height, x+widthPerFrame-5, y, 1, 1, widthPerFrame, height, null, null); } if(lastSheet == "rightSheet") { g.drawImage(rightSheet, (x-widthPerFrame/2)+10, y-height, (x+widthPerFrame/2)+10, y, 1, 1, widthPerFrame, height, null, null); } } tick++; }
public void drawSprite(Graphics g, int x, int y) { if (tick == 9) { tick = 0; currentFrame++; currentFrame = (currentFrame % 3); } if (kangaroo.getVerticalSpeed() != 0) { if(kangaroo.getDirection() == Direction.DIRECTION_EAST) { g.drawImage(rightSheet, (x-widthPerFrame/2)+10, y-height, (x+widthPerFrame/2)+10, y, widthPerFrame*2, 1, widthPerFrame*3, height, null, null); this.lastSheet = "rightSheet"; } else if (kangaroo.getDirection() == Direction.DIRECTION_WEST) { g.drawImage(leftSheet, x-5, y-height, x+widthPerFrame-5, y, widthPerFrame*2, 1, widthPerFrame*3, height, null, null); this.lastSheet = "leftSheet"; } else if (kangaroo.getDirection() == Direction.DIRECTION_NONE) { if(lastSheet == "leftSheet") { g.drawImage(leftSheet,(x-widthPerFrame/2)+15, y-height, (x+widthPerFrame/2)+15, y, widthPerFrame*2, 1, widthPerFrame*3, height, null, null); } if(lastSheet == "rightSheet") { g.drawImage(rightSheet, (x-widthPerFrame/2)+10, y-height, (x+widthPerFrame/2)+10, y, widthPerFrame*2, 1, widthPerFrame*3, height, null, null); } } } else if(kangaroo.getDirection() == Direction.DIRECTION_EAST) { g.drawImage(rightSheet, (x-widthPerFrame/2)+10, y-height, (x+widthPerFrame/2)+10, y, (currentFrame * widthPerFrame), 1, (currentFrame * widthPerFrame) + widthPerFrame, height, null, null); this.lastSheet = "rightSheet"; } else if (kangaroo.getDirection() == Direction.DIRECTION_WEST) { g.drawImage(leftSheet, x-5, y-height, x+widthPerFrame-5, y, (currentFrame * widthPerFrame), 1, (currentFrame * widthPerFrame) + widthPerFrame, height, null, null); this.lastSheet = "leftSheet"; } else if (kangaroo.getDirection() == Direction.DIRECTION_NONE) { if(lastSheet == "leftSheet") { g.drawImage(leftSheet, x-5, y-height, x+widthPerFrame-5, y, 1, 1, widthPerFrame, height, null, null); } if(lastSheet == "rightSheet") { g.drawImage(rightSheet, (x-widthPerFrame/2)+10, y-height, (x+widthPerFrame/2)+10, y, 1, 1, widthPerFrame, height, null, null); } } tick++; }
diff --git a/src/uk/org/ponder/rsf/renderer/html/HeadCollectingSCR.java b/src/uk/org/ponder/rsf/renderer/html/HeadCollectingSCR.java index 326518a..6b7d344 100644 --- a/src/uk/org/ponder/rsf/renderer/html/HeadCollectingSCR.java +++ b/src/uk/org/ponder/rsf/renderer/html/HeadCollectingSCR.java @@ -1,71 +1,72 @@ /* * Created on 18 Sep 2006 */ package uk.org.ponder.rsf.renderer.html; import java.util.HashSet; import java.util.Set; import uk.org.ponder.rsf.renderer.ComponentRenderer; import uk.org.ponder.rsf.renderer.RenderUtil; import uk.org.ponder.rsf.renderer.scr.CollectingSCR; import uk.org.ponder.rsf.template.XMLLump; import uk.org.ponder.rsf.template.XMLLumpList; import uk.org.ponder.streamutil.write.PrintOutputStream; import uk.org.ponder.xml.XMLWriter; /** * A basic collector of &lt;head&gt; material for HTML pages. Will emit all * collected &lt;style&gt; and &lt;script&gt; tags, and leave the tag in an open * condition. * * @author Antranig Basman ([email protected]) * */ public class HeadCollectingSCR implements CollectingSCR { public static final String NAME = "head-collect"; private URLRewriteSCR urlRewriteSCR; public String getName() { return NAME; } public String[] getCollectingNames() { return new String[] { "style", "script" }; } public void setURLRewriteSCR(URLRewriteSCR urlRewriteSCR) { this.urlRewriteSCR = urlRewriteSCR; } public int render(XMLLump lump, XMLLumpList collected, XMLWriter xmlw) { PrintOutputStream pos = xmlw.getInternalWriter(); RenderUtil.dumpTillLump(lump.parent.lumps, lump.lumpindex, lump.open_end.lumpindex + 1, pos); Set used = new HashSet(); for (int i = 0; i < collected.size(); ++i) { XMLLump collump = collected.lumpAt(i); String attr = URLRewriteSCR.getLinkAttribute(collump); if (attr != null) { String attrval = (String) collump.attributemap.get(attr); if (attrval != null) { String rewritten = urlRewriteSCR.resolveURL(collump.parent, attrval); + if (rewritten == null) rewritten = attrval; int qpos = rewritten.indexOf('?'); if (qpos != -1) rewritten = rewritten.substring(0, qpos); if (used.contains(rewritten)) continue; else used.add(rewritten); } } // TODO: equivalent of TagRenderContext for SCRs urlRewriteSCR.render(collump, xmlw); RenderUtil.dumpTillLump(collump.parent.lumps, collump.open_end.lumpindex + 1, collump.close_tag.lumpindex + 1, pos); } return ComponentRenderer.NESTING_TAG; } }
true
true
public int render(XMLLump lump, XMLLumpList collected, XMLWriter xmlw) { PrintOutputStream pos = xmlw.getInternalWriter(); RenderUtil.dumpTillLump(lump.parent.lumps, lump.lumpindex, lump.open_end.lumpindex + 1, pos); Set used = new HashSet(); for (int i = 0; i < collected.size(); ++i) { XMLLump collump = collected.lumpAt(i); String attr = URLRewriteSCR.getLinkAttribute(collump); if (attr != null) { String attrval = (String) collump.attributemap.get(attr); if (attrval != null) { String rewritten = urlRewriteSCR.resolveURL(collump.parent, attrval); int qpos = rewritten.indexOf('?'); if (qpos != -1) rewritten = rewritten.substring(0, qpos); if (used.contains(rewritten)) continue; else used.add(rewritten); } } // TODO: equivalent of TagRenderContext for SCRs urlRewriteSCR.render(collump, xmlw); RenderUtil.dumpTillLump(collump.parent.lumps, collump.open_end.lumpindex + 1, collump.close_tag.lumpindex + 1, pos); } return ComponentRenderer.NESTING_TAG; }
public int render(XMLLump lump, XMLLumpList collected, XMLWriter xmlw) { PrintOutputStream pos = xmlw.getInternalWriter(); RenderUtil.dumpTillLump(lump.parent.lumps, lump.lumpindex, lump.open_end.lumpindex + 1, pos); Set used = new HashSet(); for (int i = 0; i < collected.size(); ++i) { XMLLump collump = collected.lumpAt(i); String attr = URLRewriteSCR.getLinkAttribute(collump); if (attr != null) { String attrval = (String) collump.attributemap.get(attr); if (attrval != null) { String rewritten = urlRewriteSCR.resolveURL(collump.parent, attrval); if (rewritten == null) rewritten = attrval; int qpos = rewritten.indexOf('?'); if (qpos != -1) rewritten = rewritten.substring(0, qpos); if (used.contains(rewritten)) continue; else used.add(rewritten); } } // TODO: equivalent of TagRenderContext for SCRs urlRewriteSCR.render(collump, xmlw); RenderUtil.dumpTillLump(collump.parent.lumps, collump.open_end.lumpindex + 1, collump.close_tag.lumpindex + 1, pos); } return ComponentRenderer.NESTING_TAG; }
diff --git a/src/main/java/org/jboss/modcluster/mcmp/impl/DefaultMCMPHandler.java b/src/main/java/org/jboss/modcluster/mcmp/impl/DefaultMCMPHandler.java index 4702834e..e0fd5506 100644 --- a/src/main/java/org/jboss/modcluster/mcmp/impl/DefaultMCMPHandler.java +++ b/src/main/java/org/jboss/modcluster/mcmp/impl/DefaultMCMPHandler.java @@ -1,1051 +1,1051 @@ /* * JBoss, Home of Professional Open Source. * Copyright 2009, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.modcluster.mcmp.impl; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.Externalizable; import java.io.IOException; import java.io.InputStreamReader; import java.io.ObjectInput; import java.io.ObjectOutput; import java.io.OutputStreamWriter; import java.io.Serializable; import java.io.Writer; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Socket; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import javax.net.SocketFactory; import net.jcip.annotations.GuardedBy; import net.jcip.annotations.ThreadSafe; import org.jboss.logging.Logger; import org.jboss.modcluster.Strings; import org.jboss.modcluster.config.MCMPHandlerConfiguration; import org.jboss.modcluster.mcmp.MCMPConnectionListener; import org.jboss.modcluster.mcmp.MCMPHandler; import org.jboss.modcluster.mcmp.MCMPRequest; import org.jboss.modcluster.mcmp.MCMPRequestFactory; import org.jboss.modcluster.mcmp.MCMPResponseParser; import org.jboss.modcluster.mcmp.MCMPServer; import org.jboss.modcluster.mcmp.MCMPServerState; import org.jboss.modcluster.mcmp.ResetRequestSource; import org.jboss.modcluster.mcmp.MCMPServerState.State; /** * Default implementation of {@link MCMPHandler}. * * @author Jean-Frederic Clere * @author Brian Stansberry * @author Paul Ferraro */ @ThreadSafe public class DefaultMCMPHandler implements MCMPHandler { private static final String NEW_LINE = "\r\n"; protected static final Logger log = Logger.getLogger(DefaultMCMPHandler.class); // -------------------------------------------------------------- Constants // ----------------------------------------------------------------- Fields private final MCMPHandlerConfiguration config; /** Source for reset requests when we need to reset a proxy. */ private final ResetRequestSource resetRequestSource; private final MCMPRequestFactory requestFactory; private final MCMPResponseParser responseParser; private final ReadWriteLock proxiesLock = new ReentrantReadWriteLock(); private final Lock addRemoveProxiesLock = new ReentrantLock(); /** Proxies. */ @GuardedBy("proxiesLock") private final List<Proxy> proxies = new ArrayList<Proxy>(); /** Add proxy list. */ @GuardedBy("addRemoveProxiesLock") private final List<Proxy> addProxies = new ArrayList<Proxy>(); /** Remove proxy list. */ @GuardedBy("addRemoveProxiesLock") private final List<Proxy> removeProxies = new ArrayList<Proxy>(); private final AtomicBoolean established = new AtomicBoolean(false); private volatile MCMPConnectionListener connectionListener; private volatile boolean init = false; // ----------------------------------------------------------- Constructors public DefaultMCMPHandler(MCMPHandlerConfiguration config, ResetRequestSource source, MCMPRequestFactory requestFactory, MCMPResponseParser responseParser) { this.resetRequestSource = source; this.config = config; this.requestFactory = requestFactory; this.responseParser = responseParser; } // ------------------------------------------------------------ MCMPHandler /** * {@inheritDoc} * @see org.jboss.modcluster.mcmp.MCMPHandler#init(java.util.List) */ public void init(List<InetSocketAddress> initialProxies, MCMPConnectionListener connectionListener) { this.connectionListener = connectionListener; if (initialProxies != null) { Lock lock = this.proxiesLock.writeLock(); lock.lock(); try { for (InetSocketAddress initialProxy: initialProxies) { this.add(initialProxy); } this.status(false); } finally { lock.unlock(); } } this.init = true; } /** * {@inheritDoc} * @see org.jboss.modcluster.mcmp.MCMPHandler#shutdown() */ public void shutdown() { this.init = false; Lock lock = this.proxiesLock.readLock(); lock.lock(); try { for (Proxy proxy: this.proxies) { proxy.closeConnection(); } } finally { lock.unlock(); } } /** * {@inheritDoc} * @see org.jboss.modcluster.mcmp.MCMPHandler#addProxy(java.net.InetSocketAddress) */ public void addProxy(InetSocketAddress socketAddress) { this.add(socketAddress); } private Proxy add(InetSocketAddress socketAddress) { Proxy proxy = new Proxy(socketAddress, this.config); this.addRemoveProxiesLock.lock(); try { Lock lock = this.proxiesLock.readLock(); lock.lock(); try { for (Proxy candidate: this.proxies) { if (candidate.equals(proxy)) return candidate; } } finally { lock.unlock(); } for (Proxy candidate: this.addProxies) { if (candidate.equals(proxy)) return candidate; } for (Proxy candidate: this.removeProxies) { if (candidate.equals(proxy)) return candidate; } proxy.setState(Proxy.State.ERROR); this.addProxies.add(proxy); } finally { this.addRemoveProxiesLock.unlock(); } return proxy; } /** * {@inheritDoc} * @see org.jboss.modcluster.mcmp.MCMPHandler#addProxy(java.net.InetSocketAddress, boolean) */ public void addProxy(InetSocketAddress socketAddress, boolean established) { this.add(socketAddress).setEstablished(established); } /** * {@inheritDoc} * @see org.jboss.modcluster.mcmp.MCMPHandler#removeProxy(java.net.InetSocketAddress) */ public void removeProxy(InetSocketAddress socketAddress) { Proxy proxy = new Proxy(socketAddress, this.config); this.addRemoveProxiesLock.lock(); try { this.removeProxies.add(proxy); } finally { this.addRemoveProxiesLock.unlock(); } } /** * {@inheritDoc} * @see org.jboss.modcluster.mcmp.MCMPHandler#getProxyStates() */ public Set<MCMPServerState> getProxyStates() { Lock lock = this.proxiesLock.readLock(); lock.lock(); try { if (this.proxies.isEmpty()) return Collections.emptySet(); Set<MCMPServerState> result = new LinkedHashSet<MCMPServerState>(this.proxies.size()); for (Proxy proxy: this.proxies) { result.add(proxy); } return result; } finally { lock.unlock(); } } /** * {@inheritDoc} * @see org.jboss.modcluster.mcmp.MCMPHandler#isProxyHealthOK() */ public boolean isProxyHealthOK() { Lock lock = this.proxiesLock.readLock(); lock.lock(); try { for (Proxy proxy: this.proxies) { if (proxy.getState() != MCMPServerState.State.OK) { return false; } } return true; } finally { lock.unlock(); } } /** * {@inheritDoc} * @see org.jboss.modcluster.mcmp.MCMPHandler#markProxiesInError() */ public void markProxiesInError() { Lock lock = this.proxiesLock.readLock(); lock.lock(); try { for (Proxy proxy: this.proxies) { if (proxy.getState() == MCMPServerState.State.OK) { proxy.setState(Proxy.State.ERROR); } } } finally { lock.unlock(); } } /** * {@inheritDoc} * @see org.jboss.modcluster.mcmp.MCMPHandler#reset() */ public void reset() { Lock lock = this.proxiesLock.readLock(); lock.lock(); try { for (Proxy proxy: this.proxies) { if (proxy.getState() == Proxy.State.DOWN) { proxy.setState(Proxy.State.ERROR); } } } finally { lock.unlock(); } } /** * {@inheritDoc} * @see org.jboss.modcluster.mcmp.MCMPHandler#status() */ public synchronized void status() { if (this.init) { this.processPendingDiscoveryEvents(); this.status(true); } } /** * Send a periodic status request. * @param sendResetRequests if enabled, when in error state, the listener will attempt to refresh the configuration on the front end server */ private void status(boolean sendResetRequests) { Lock lock = this.proxiesLock.readLock(); lock.lock(); try { for (Proxy proxy: this.proxies) { // Attempt to reset any proxies in error if (proxy.getState() == Proxy.State.ERROR) { proxy.setState(Proxy.State.OK); String response = this.sendRequest(this.requestFactory.createInfoRequest(), proxy); if (proxy.getState() == Proxy.State.OK) { // Only notify connection listener once if (this.established.compareAndSet(false, true)) { this.connectionListener.connectionEstablished(proxy.getLocalAddress()); } if (sendResetRequests) { Map<String, Set<ResetRequestSource.VirtualHost>> parsedResponse = this.responseParser.parseInfoResponse(response); List<MCMPRequest> requests = this.resetRequestSource.getResetRequests(parsedResponse); log.trace(requests); this.sendRequests(requests); } } proxy.closeConnection(); } } } finally { lock.unlock(); } } /** * {@inheritDoc} * @see org.jboss.modcluster.mcmp.MCMPHandler#sendRequest(org.jboss.modcluster.mcmp.MCMPRequest) */ public Map<MCMPServerState, String> sendRequest(MCMPRequest request) { Map<MCMPServerState, String> map = new HashMap<MCMPServerState, String>(); Lock lock = this.proxiesLock.readLock(); lock.lock(); try { for (Proxy proxy: this.proxies) { map.put(proxy, this.sendRequest(request, proxy)); } } finally { lock.unlock(); } return map; } /** * {@inheritDoc} * @see org.jboss.modcluster.mcmp.MCMPHandler#sendRequests(java.util.List) */ public Map<MCMPServerState, List<String>> sendRequests(List<MCMPRequest> requests) { Map<MCMPServerState, List<String>> map = new HashMap<MCMPServerState, List<String>>(); Lock lock = this.proxiesLock.readLock(); lock.lock(); try { for (Proxy proxy: this.proxies) { List<String> list = new ArrayList<String>(requests.size()); for (MCMPRequest request: requests) { list.add(this.sendRequest(request, proxy)); } map.put(proxy, list); } } finally { lock.unlock(); } return map; } // ---------------------------------------------------------------- Private private void processPendingDiscoveryEvents() { this.addRemoveProxiesLock.lock(); try { // Check to add or remove proxies, and rebuild a new list if needed if (!this.addProxies.isEmpty() || !this.removeProxies.isEmpty()) { Lock lock = this.proxiesLock.writeLock(); lock.lock(); try { this.proxies.addAll(this.addProxies); this.proxies.removeAll(this.removeProxies); this.addProxies.clear(); this.removeProxies.clear(); // Reset all connections for (Proxy proxy: this.proxies) { proxy.closeConnection(); } } finally { lock.unlock(); } } } finally { this.addRemoveProxiesLock.unlock(); } } private String sendRequest(Proxy proxy, String command, String body) throws IOException { Writer writer = proxy.getConnectionWriter(); writer.append(command).append(NEW_LINE); writer.append("Content-Length: ").append(String.valueOf(body.length())).append(NEW_LINE); writer.append("User-Agent: ClusterListener/1.0").append(NEW_LINE); writer.append("Connection: Keep-Alive").append(NEW_LINE); writer.write(NEW_LINE); writer.write(body); writer.write(NEW_LINE); writer.flush(); // Read the first response line and skip the rest of the HTTP header return proxy.getConnectionReader().readLine(); } private void appendParameter(Appendable appender, String name, String value, boolean more) throws IOException { appender.append(URLEncoder.encode(name, "UTF-8")).append('=').append(URLEncoder.encode(value, "UTF-8")); if (more) { appender.append('&'); } } private String sendRequest(MCMPRequest request, Proxy proxy) { // If there was an error, do nothing until the next periodic event, where the whole configuration // will be refreshed if (proxy.getState() != Proxy.State.OK) return null; if (log.isTraceEnabled()) { log.trace(Strings.REQUEST_SEND.getString(request, proxy)); } String command = request.getRequestType().getCommand(); boolean wildcard = request.isWildcard(); String jvmRoute = request.getJvmRoute(); Map<String, String> parameters = request.getParameters(); StringBuilder bodyBuilder = new StringBuilder(); // First, encode the POST body try { if (jvmRoute != null) { this.appendParameter(bodyBuilder, "JVMRoute", jvmRoute, !parameters.isEmpty()); } Iterator<Map.Entry<String, String>> entries = parameters.entrySet().iterator(); while (entries.hasNext()) { Map.Entry<String, String> entry = entries.next(); this.appendParameter(bodyBuilder, entry.getKey(), entry.getValue(), entries.hasNext()); } } catch (IOException e) { // Error encoding URL, should not happen throw new IllegalArgumentException(e); } // Then, connect to the proxy // Generate and write request StringBuilder headBuilder = new StringBuilder(); headBuilder.append(command).append(" "); String proxyURL = this.config.getProxyURL(); if (proxyURL != null) { headBuilder.append(proxyURL); } if (headBuilder.charAt(headBuilder.length() - 1) != '/') { headBuilder.append('/'); } if (wildcard) { headBuilder.append('*'); } headBuilder.append(" HTTP/1.1\r\n"); headBuilder.append("Host: "); String head = headBuilder.toString(); String body = bodyBuilder.toString(); // Require exclusive access to proxy socket synchronized (proxy) { try { String line = null; StringBuilder proxyheadBuilder = new StringBuilder(head); proxyheadBuilder.append(proxy.getSocketAddress().getHostName() + ":" + proxy.getSocketAddress().getPort()); String proxyhead = proxyheadBuilder.toString(); try { line = sendRequest(proxy, proxyhead, body); } catch (IOException e) { // Ignore first write failure } if (line == null) { // Retry failed read/write with fresh connection proxy.closeConnection(); - line = sendRequest(proxy, head, body); + line = sendRequest(proxy, proxyhead, body); } BufferedReader reader = proxy.getConnectionReader(); // Parse the line, which is formed like HTTP/1.x YYY Message int status = 500; // String version = "0"; String message = null; String errorType = null; int contentLength = 0; boolean close = false; if (line != null) { try { int spaceIndex = line.indexOf(' '); String responseStatus = line.substring(spaceIndex + 1, line.indexOf(' ', spaceIndex + 1)); status = Integer.parseInt(responseStatus); line = reader.readLine(); while ((line != null) && (line.length() > 0)) { int colon = line.indexOf(':'); String headerName = line.substring(0, colon).trim(); String headerValue = line.substring(colon + 1).trim(); if ("version".equalsIgnoreCase(headerName)) { // version = headerValue; } else if ("type".equalsIgnoreCase(headerName)) { errorType = headerValue; } else if ("mess".equalsIgnoreCase(headerName)) { message = headerValue; } else if ("content-length".equalsIgnoreCase(headerName)) { contentLength = Integer.parseInt(headerValue); } else if ("connection".equalsIgnoreCase(headerName)) { close = "close".equalsIgnoreCase(headerValue); } line = reader.readLine(); } } catch (Exception e) { log.info(Strings.ERROR_HEADER_PARSE.getString(command), e); } } // Mark as error if the front end server did not return 200; the configuration will // be refreshed during the next periodic event if (status == 200) { if (request.getRequestType().getEstablishesServer()) { // We know the request succeeded, so if appropriate // mark the proxy as established before any possible // later exception happens proxy.setEstablished(true); } } else { if ("SYNTAX".equals(errorType)) { // Syntax error means the protocol is incorrect, which cannot be automatically fixed proxy.setState(Proxy.State.DOWN); log.error(Strings.ERROR_REQUEST_SYNTAX.getString(command, proxy, errorType, message)); } else { proxy.setState(Proxy.State.ERROR); log.error(Strings.ERROR_REQUEST_SEND_OTHER.getString(command, proxy, errorType, message)); } } if (close) { contentLength = Integer.MAX_VALUE; } else if (contentLength == 0) { return null; } // Read the request body StringBuilder result = new StringBuilder(); char[] buffer = new char[512]; while (contentLength > 0) { int bytes = reader.read(buffer, 0, (contentLength > buffer.length) ? buffer.length : contentLength); if (bytes <= 0) break; result.append(buffer, 0, bytes); contentLength -= bytes; } if (proxy.getState() == State.OK) { proxy.setIoExceptionLogged(false); } return result.toString(); } catch (IOException e) { // Most likely this is a connection error with the proxy proxy.setState(Proxy.State.ERROR); // Log it only if we haven't done so already. Don't spam the log if (proxy.isIoExceptionLogged() == false) { log.info(Strings.ERROR_REQUEST_SEND_IO.getString(command, proxy), e); proxy.setIoExceptionLogged(true); } return null; } finally { // If there's an error of any sort, or if the proxy did not return 200, it is an error if (proxy.getState() != Proxy.State.OK) { proxy.closeConnection(); } } } } /** * This class represents a front-end httpd server. */ @ThreadSafe private static class Proxy implements MCMPServerState, Serializable { /** The serialVersionUID */ private static final long serialVersionUID = 5219680414337319908L; private final InetSocketAddress socketAddress; private volatile State state = State.OK; private volatile boolean established = false; private transient final int socketTimeout; private transient final SocketFactory socketFactory; private transient volatile boolean ioExceptionLogged = false; private transient volatile InetAddress localAddress = null; @GuardedBy("Proxy.this") private transient volatile Socket socket = null; @GuardedBy("Proxy.this") private transient volatile BufferedReader reader = null; @GuardedBy("Proxy.this") private transient volatile BufferedWriter writer = null; Proxy(InetSocketAddress socketAddress, MCMPHandlerConfiguration config) { this.socketAddress = socketAddress; this.socketFactory = config.isSsl() ? new JSSESocketFactory(config) : SocketFactory.getDefault(); this.socketTimeout = config.getSocketTimeout(); } // -------------------------------------------- MCMPServerState public State getState() { return this.state; } // ----------------------------------------------------------- MCMPServer public InetSocketAddress getSocketAddress() { return this.socketAddress; } public boolean isEstablished() { return this.established; } // ------------------------------------------------------------ Overrides @Override public String toString() { return this.socketAddress.toString(); } @Override public boolean equals(Object object) { if ((object == null) || !(object instanceof MCMPServer)) return false; MCMPServer proxy = (MCMPServer) object; return this.socketAddress.equals(proxy.getSocketAddress()); } @Override public int hashCode() { return this.socketAddress.hashCode(); } // -------------------------------------------------------------- Private void setState(State state) { if (state == null) { throw new IllegalArgumentException(Strings.ERROR_ARGUMENT_NULL.getString("state")); } this.state = state; } void setEstablished(boolean established) { this.established = established; } /** * Return a reader to the proxy. */ private synchronized Socket getConnection() throws IOException { if ((this.socket == null) || this.socket.isClosed()) { this.socket = this.socketFactory.createSocket(); this.socket.connect(this.socketAddress, this.socketTimeout); this.socket.setSoTimeout(this.socketTimeout); this.localAddress = this.socket.getLocalAddress(); } return this.socket; } /** * Convenience method that returns a reader to the proxy. */ synchronized BufferedReader getConnectionReader() throws IOException { if (this.reader == null) { this.reader = new BufferedReader(new InputStreamReader(this.getConnection().getInputStream())); } return this.reader; } /** * Convenience method that returns a writer to the proxy. */ synchronized BufferedWriter getConnectionWriter() throws IOException { if (this.writer == null) { this.writer = new BufferedWriter(new OutputStreamWriter(this.getConnection().getOutputStream())); } return this.writer; } InetAddress getLocalAddress() { return this.localAddress; } /** * Close connection. */ synchronized void closeConnection() { if (this.reader != null) { try { this.reader.close(); } catch (IOException e) { // Ignore } this.reader = null; } if (this.writer != null) { try { this.writer.close(); } catch (IOException e) { // Ignore } this.writer = null; } if (this.socket != null) { if (!this.socket.isClosed()) { try { this.socket.close(); } catch (IOException e) { // Ignore } } this.socket = null; } } boolean isIoExceptionLogged() { return this.ioExceptionLogged; } void setIoExceptionLogged(boolean ioErrorLogged) { this.ioExceptionLogged = ioErrorLogged; } } static class VirtualHostImpl implements ResetRequestSource.VirtualHost, Externalizable { private final Set<String> aliases = new LinkedHashSet<String>(); private final Map<String, ResetRequestSource.Status> contexts = new HashMap<String, ResetRequestSource.Status>(); public VirtualHostImpl() { // Expose for deserialization } /** * @{inheritDoc} * @see org.jboss.modcluster.mcmp.ResetRequestSource.VirtualHost#getAliases() */ public Set<String> getAliases() { return this.aliases; } /** * @{inheritDoc} * @see org.jboss.modcluster.mcmp.ResetRequestSource.VirtualHost#getContexts() */ public Map<String, ResetRequestSource.Status> getContexts() { return this.contexts; } /** * @{inheritDoc} * @see java.io.Externalizable#readExternal(java.io.ObjectInput) */ public void readExternal(ObjectInput input) throws IOException { int aliases = input.readInt(); for (int i = 0; i < aliases; ++i) { this.aliases.add(input.readUTF()); } ResetRequestSource.Status[] stati = ResetRequestSource.Status.values(); int contexts = input.readInt(); for (int i = 0; i < contexts; ++i) { this.contexts.put(input.readUTF(), stati[input.readInt()]); } } /** * @{inheritDoc} * @see java.io.Externalizable#writeExternal(java.io.ObjectOutput) */ public void writeExternal(ObjectOutput output) throws IOException { output.writeInt(this.aliases.size()); for (String alias: this.aliases) { output.writeUTF(alias); } output.writeInt(this.contexts.size()); for (Map.Entry<String, ResetRequestSource.Status> context: this.contexts.entrySet()) { output.writeUTF(context.getKey()); output.writeInt(context.getValue().ordinal()); } } } }
true
true
private String sendRequest(MCMPRequest request, Proxy proxy) { // If there was an error, do nothing until the next periodic event, where the whole configuration // will be refreshed if (proxy.getState() != Proxy.State.OK) return null; if (log.isTraceEnabled()) { log.trace(Strings.REQUEST_SEND.getString(request, proxy)); } String command = request.getRequestType().getCommand(); boolean wildcard = request.isWildcard(); String jvmRoute = request.getJvmRoute(); Map<String, String> parameters = request.getParameters(); StringBuilder bodyBuilder = new StringBuilder(); // First, encode the POST body try { if (jvmRoute != null) { this.appendParameter(bodyBuilder, "JVMRoute", jvmRoute, !parameters.isEmpty()); } Iterator<Map.Entry<String, String>> entries = parameters.entrySet().iterator(); while (entries.hasNext()) { Map.Entry<String, String> entry = entries.next(); this.appendParameter(bodyBuilder, entry.getKey(), entry.getValue(), entries.hasNext()); } } catch (IOException e) { // Error encoding URL, should not happen throw new IllegalArgumentException(e); } // Then, connect to the proxy // Generate and write request StringBuilder headBuilder = new StringBuilder(); headBuilder.append(command).append(" "); String proxyURL = this.config.getProxyURL(); if (proxyURL != null) { headBuilder.append(proxyURL); } if (headBuilder.charAt(headBuilder.length() - 1) != '/') { headBuilder.append('/'); } if (wildcard) { headBuilder.append('*'); } headBuilder.append(" HTTP/1.1\r\n"); headBuilder.append("Host: "); String head = headBuilder.toString(); String body = bodyBuilder.toString(); // Require exclusive access to proxy socket synchronized (proxy) { try { String line = null; StringBuilder proxyheadBuilder = new StringBuilder(head); proxyheadBuilder.append(proxy.getSocketAddress().getHostName() + ":" + proxy.getSocketAddress().getPort()); String proxyhead = proxyheadBuilder.toString(); try { line = sendRequest(proxy, proxyhead, body); } catch (IOException e) { // Ignore first write failure } if (line == null) { // Retry failed read/write with fresh connection proxy.closeConnection(); line = sendRequest(proxy, head, body); } BufferedReader reader = proxy.getConnectionReader(); // Parse the line, which is formed like HTTP/1.x YYY Message int status = 500; // String version = "0"; String message = null; String errorType = null; int contentLength = 0; boolean close = false; if (line != null) { try { int spaceIndex = line.indexOf(' '); String responseStatus = line.substring(spaceIndex + 1, line.indexOf(' ', spaceIndex + 1)); status = Integer.parseInt(responseStatus); line = reader.readLine(); while ((line != null) && (line.length() > 0)) { int colon = line.indexOf(':'); String headerName = line.substring(0, colon).trim(); String headerValue = line.substring(colon + 1).trim(); if ("version".equalsIgnoreCase(headerName)) { // version = headerValue; } else if ("type".equalsIgnoreCase(headerName)) { errorType = headerValue; } else if ("mess".equalsIgnoreCase(headerName)) { message = headerValue; } else if ("content-length".equalsIgnoreCase(headerName)) { contentLength = Integer.parseInt(headerValue); } else if ("connection".equalsIgnoreCase(headerName)) { close = "close".equalsIgnoreCase(headerValue); } line = reader.readLine(); } } catch (Exception e) { log.info(Strings.ERROR_HEADER_PARSE.getString(command), e); } } // Mark as error if the front end server did not return 200; the configuration will // be refreshed during the next periodic event if (status == 200) { if (request.getRequestType().getEstablishesServer()) { // We know the request succeeded, so if appropriate // mark the proxy as established before any possible // later exception happens proxy.setEstablished(true); } } else { if ("SYNTAX".equals(errorType)) { // Syntax error means the protocol is incorrect, which cannot be automatically fixed proxy.setState(Proxy.State.DOWN); log.error(Strings.ERROR_REQUEST_SYNTAX.getString(command, proxy, errorType, message)); } else { proxy.setState(Proxy.State.ERROR); log.error(Strings.ERROR_REQUEST_SEND_OTHER.getString(command, proxy, errorType, message)); } } if (close) { contentLength = Integer.MAX_VALUE; } else if (contentLength == 0) { return null; } // Read the request body StringBuilder result = new StringBuilder(); char[] buffer = new char[512]; while (contentLength > 0) { int bytes = reader.read(buffer, 0, (contentLength > buffer.length) ? buffer.length : contentLength); if (bytes <= 0) break; result.append(buffer, 0, bytes); contentLength -= bytes; } if (proxy.getState() == State.OK) { proxy.setIoExceptionLogged(false); } return result.toString(); } catch (IOException e) { // Most likely this is a connection error with the proxy proxy.setState(Proxy.State.ERROR); // Log it only if we haven't done so already. Don't spam the log if (proxy.isIoExceptionLogged() == false) { log.info(Strings.ERROR_REQUEST_SEND_IO.getString(command, proxy), e); proxy.setIoExceptionLogged(true); } return null; } finally { // If there's an error of any sort, or if the proxy did not return 200, it is an error if (proxy.getState() != Proxy.State.OK) { proxy.closeConnection(); } } } }
private String sendRequest(MCMPRequest request, Proxy proxy) { // If there was an error, do nothing until the next periodic event, where the whole configuration // will be refreshed if (proxy.getState() != Proxy.State.OK) return null; if (log.isTraceEnabled()) { log.trace(Strings.REQUEST_SEND.getString(request, proxy)); } String command = request.getRequestType().getCommand(); boolean wildcard = request.isWildcard(); String jvmRoute = request.getJvmRoute(); Map<String, String> parameters = request.getParameters(); StringBuilder bodyBuilder = new StringBuilder(); // First, encode the POST body try { if (jvmRoute != null) { this.appendParameter(bodyBuilder, "JVMRoute", jvmRoute, !parameters.isEmpty()); } Iterator<Map.Entry<String, String>> entries = parameters.entrySet().iterator(); while (entries.hasNext()) { Map.Entry<String, String> entry = entries.next(); this.appendParameter(bodyBuilder, entry.getKey(), entry.getValue(), entries.hasNext()); } } catch (IOException e) { // Error encoding URL, should not happen throw new IllegalArgumentException(e); } // Then, connect to the proxy // Generate and write request StringBuilder headBuilder = new StringBuilder(); headBuilder.append(command).append(" "); String proxyURL = this.config.getProxyURL(); if (proxyURL != null) { headBuilder.append(proxyURL); } if (headBuilder.charAt(headBuilder.length() - 1) != '/') { headBuilder.append('/'); } if (wildcard) { headBuilder.append('*'); } headBuilder.append(" HTTP/1.1\r\n"); headBuilder.append("Host: "); String head = headBuilder.toString(); String body = bodyBuilder.toString(); // Require exclusive access to proxy socket synchronized (proxy) { try { String line = null; StringBuilder proxyheadBuilder = new StringBuilder(head); proxyheadBuilder.append(proxy.getSocketAddress().getHostName() + ":" + proxy.getSocketAddress().getPort()); String proxyhead = proxyheadBuilder.toString(); try { line = sendRequest(proxy, proxyhead, body); } catch (IOException e) { // Ignore first write failure } if (line == null) { // Retry failed read/write with fresh connection proxy.closeConnection(); line = sendRequest(proxy, proxyhead, body); } BufferedReader reader = proxy.getConnectionReader(); // Parse the line, which is formed like HTTP/1.x YYY Message int status = 500; // String version = "0"; String message = null; String errorType = null; int contentLength = 0; boolean close = false; if (line != null) { try { int spaceIndex = line.indexOf(' '); String responseStatus = line.substring(spaceIndex + 1, line.indexOf(' ', spaceIndex + 1)); status = Integer.parseInt(responseStatus); line = reader.readLine(); while ((line != null) && (line.length() > 0)) { int colon = line.indexOf(':'); String headerName = line.substring(0, colon).trim(); String headerValue = line.substring(colon + 1).trim(); if ("version".equalsIgnoreCase(headerName)) { // version = headerValue; } else if ("type".equalsIgnoreCase(headerName)) { errorType = headerValue; } else if ("mess".equalsIgnoreCase(headerName)) { message = headerValue; } else if ("content-length".equalsIgnoreCase(headerName)) { contentLength = Integer.parseInt(headerValue); } else if ("connection".equalsIgnoreCase(headerName)) { close = "close".equalsIgnoreCase(headerValue); } line = reader.readLine(); } } catch (Exception e) { log.info(Strings.ERROR_HEADER_PARSE.getString(command), e); } } // Mark as error if the front end server did not return 200; the configuration will // be refreshed during the next periodic event if (status == 200) { if (request.getRequestType().getEstablishesServer()) { // We know the request succeeded, so if appropriate // mark the proxy as established before any possible // later exception happens proxy.setEstablished(true); } } else { if ("SYNTAX".equals(errorType)) { // Syntax error means the protocol is incorrect, which cannot be automatically fixed proxy.setState(Proxy.State.DOWN); log.error(Strings.ERROR_REQUEST_SYNTAX.getString(command, proxy, errorType, message)); } else { proxy.setState(Proxy.State.ERROR); log.error(Strings.ERROR_REQUEST_SEND_OTHER.getString(command, proxy, errorType, message)); } } if (close) { contentLength = Integer.MAX_VALUE; } else if (contentLength == 0) { return null; } // Read the request body StringBuilder result = new StringBuilder(); char[] buffer = new char[512]; while (contentLength > 0) { int bytes = reader.read(buffer, 0, (contentLength > buffer.length) ? buffer.length : contentLength); if (bytes <= 0) break; result.append(buffer, 0, bytes); contentLength -= bytes; } if (proxy.getState() == State.OK) { proxy.setIoExceptionLogged(false); } return result.toString(); } catch (IOException e) { // Most likely this is a connection error with the proxy proxy.setState(Proxy.State.ERROR); // Log it only if we haven't done so already. Don't spam the log if (proxy.isIoExceptionLogged() == false) { log.info(Strings.ERROR_REQUEST_SEND_IO.getString(command, proxy), e); proxy.setIoExceptionLogged(true); } return null; } finally { // If there's an error of any sort, or if the proxy did not return 200, it is an error if (proxy.getState() != Proxy.State.OK) { proxy.closeConnection(); } } } }
diff --git a/fds/src/main/java/org/intalio/tempo/workflow/fds/core/WorkflowProcessesMessageConvertor.java b/fds/src/main/java/org/intalio/tempo/workflow/fds/core/WorkflowProcessesMessageConvertor.java index 22ca3a9a..bc5e916b 100644 --- a/fds/src/main/java/org/intalio/tempo/workflow/fds/core/WorkflowProcessesMessageConvertor.java +++ b/fds/src/main/java/org/intalio/tempo/workflow/fds/core/WorkflowProcessesMessageConvertor.java @@ -1,245 +1,244 @@ /** * Copyright (c) 2005-2006 Intalio inc. * * 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: * Intalio inc. - initial API and implementation */ package org.intalio.tempo.workflow.fds.core; import java.util.List; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.Node; import org.dom4j.QName; import org.dom4j.XPath; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Converts SOAP messages from the Workflow Processes format to user process * formats. * * @author Iwan Memruk * @version $Revision: 1172 $ * @see <a href="http://www.w3.org/TR/soap/">The SOAP specification.</a> */ public class WorkflowProcessesMessageConvertor { private static final Logger LOG = LoggerFactory.getLogger(UserProcessMessageConvertor.class); /** * The XML namespace URI of the user process which has been the message * source. <br> * The value is fetched from the message during the conversion <i>if no user * process namespace has been specified to the <code>converMessage</code> * method</i>, stored in this field, and may be used later by class users. * * @see #convertMessage(Document, String) */ private String _userProcessNamespaceUri; /** * The endpoint URL of the user process which has been the message source. * <br> * The value is fetched from the message during the conversion, stored in * this field, and may be used later by class users. <br> * Contains <code>null<code> if the processes message was a reply. */ private String _userProcessEndpoint; private String _soapAction; /** * Converts a SOAP message from the Workflow Processes format to the format * of the user process the message is targetted for. <br> * The target user process is figured out from the message payload. <br> * The conversion is done in-place. The passed <code>Document</code> * instance gets converted to the user process format and its previous * format is lost. * * @param message * The SOAP message coming from the Workflow Processes to convert * to the user process format. * @param userProcessNamespaceUri * The user process namespace URI. Should be <code>null</code> * when converting the <i>requests</i>. Must be specified when * converting the <i>replies</i>, since in this case no * information about the target user process is specified inside * the message. * @throws MessageFormatException * If the specified message has an invalid format. Note that if * this exception is thrown, <code>message</code> may have * already been partly processed and therefore should be assumed * to be corrupted. */ public void convertMessage(Document message, String userProcessNamespaceUri) throws MessageFormatException { XPath xpathSelector = DocumentHelper.createXPath("/soapenv:Envelope/soapenv:Body/soapenv:Fault"); xpathSelector.setNamespaceURIs(MessageConstants.get_nsMap()); List fault = xpathSelector.selectNodes(message); if(fault.size() != 0) { // return fault as-is LOG.error("Fault in response:\n"+message.asXML()); return; } //retrieve session - xpathSelector = DocumentHelper.createXPath("/soapenv:Envelope/soapenv:Body/ib4p:response/ib4p:taskMetaData/ib4p:session"); + xpathSelector = DocumentHelper.createXPath("/soapenv:Envelope/soapenv:Body/*[1]/ib4p:taskMetaData/ib4p:session"); xpathSelector.setNamespaceURIs(MessageConstants.get_nsMap()); List sessionNodes = xpathSelector.selectNodes(message); if (sessionNodes.size() > 0) { Element sessionElement = (Element) sessionNodes.get(0); String session = sessionElement.getText(); //remove callback xpathSelector = DocumentHelper.createXPath("/soapenv:Envelope/soapenv:Header/intalio:callback"); xpathSelector.setNamespaceURIs(MessageConstants.get_nsMap()); List callbackNodes = xpathSelector.selectNodes(message); if (callbackNodes.size() != 0) { Element wsaTo = (Element) callbackNodes.get(0); Element header = (Element)wsaTo.getParent(); header.remove(wsaTo); - sessionElement = header.addElement("session"); - sessionElement.addNamespace(null, MessageConstants.INTALIO_NS); + sessionElement = header.addElement("session", MessageConstants.INTALIO_NS); sessionElement.setText(session); } } /* fetch the user process endpoint element from the task metadata */ - xpathSelector = DocumentHelper.createXPath("/soapenv:Envelope/soapenv:Body/ib4p:response/ib4p:taskMetaData/ib4p:userProcessEndpoint"); + xpathSelector = DocumentHelper.createXPath("/soapenv:Envelope/soapenv:Body/*[1]/ib4p:taskMetaData/ib4p:userProcessEndpoint"); xpathSelector.setNamespaceURIs(MessageConstants.get_nsMap()); List userProcessEndpointNodes = xpathSelector.selectNodes(message); if (userProcessEndpointNodes.size() > 0) { /* found the user process endpoint element */ Element userProcessEndpointElement = (Element) userProcessEndpointNodes.get(0); /* save it for later use */ _userProcessEndpoint = userProcessEndpointElement.getText(); /* do we have a wsa:To element? */ xpathSelector = DocumentHelper.createXPath("//wsa:To"); xpathSelector.setNamespaceURIs(MessageConstants.get_nsMap()); List wsaToNodes = xpathSelector.selectNodes(message); if (wsaToNodes.size() != 0) { /* We have the wsa:To element. Set the correct target endpoint */ Element wsaTo = (Element) wsaToNodes.get(0); wsaTo.setText(_userProcessEndpoint); } /* do we have a addr:To element? */ xpathSelector = DocumentHelper.createXPath("//addr:To"); xpathSelector.setNamespaceURIs(MessageConstants.get_nsMap()); List addrToNodes = xpathSelector.selectNodes(message); if (addrToNodes.size() != 0) { /* We have the wsa:To element. Set the correct target endpoint */ Element wsaTo = (Element) addrToNodes.get(0); //wsaTo.removeChildren(); wsaTo.setText(_userProcessEndpoint); } } /* * If the user process namespace URI is not specified explicitly, the * userProcessNamespaceURI element must be present in the metadata * section. */ if (userProcessNamespaceUri == null) { - xpathSelector = DocumentHelper.createXPath("/soapenv:Envelope/soapenv:Body/ib4p:response/ib4p:taskMetaData/ib4p:userProcessNamespaceURI"); + xpathSelector = DocumentHelper.createXPath("/soapenv:Envelope/soapenv:Body/*[1]/ib4p:taskMetaData/ib4p:userProcessNamespaceURI"); xpathSelector.setNamespaceURIs(MessageConstants.get_nsMap()); List namespaceElementQueryResult = xpathSelector.selectNodes(message); if (namespaceElementQueryResult.size() == 0) { throw new MessageFormatException("No user process namespace specified " + "and no ib4p:userProcessNamespaceURI element present to determine those."); } Element userProcessNamespaceUriElement = (Element) namespaceElementQueryResult.get(0); userProcessNamespaceUri = userProcessNamespaceUriElement.getText(); _userProcessNamespaceUri = userProcessNamespaceUri; } - xpathSelector = DocumentHelper.createXPath("/soapenv:Envelope/soapenv:Body/ib4p:response/ib4p:taskMetaData/ib4p:userProcessCompleteSOAPAction"); + xpathSelector = DocumentHelper.createXPath("/soapenv:Envelope/soapenv:Body/*[1]/ib4p:taskMetaData/ib4p:userProcessCompleteSOAPAction"); xpathSelector.setNamespaceURIs(MessageConstants.get_nsMap()); List soapActionQueryResult = xpathSelector.selectNodes(message); if (soapActionQueryResult.size() > 0) { Element soapActionElement = (Element) soapActionQueryResult.get(0); _soapAction = soapActionElement.getText(); xpathSelector = DocumentHelper.createXPath("//addr:Action"); xpathSelector.setNamespaceURIs(MessageConstants.get_nsMap()); List actionNodes = xpathSelector.selectNodes(message); if (actionNodes.size() > 0) { Element wsaTo = (Element) actionNodes.get(0); //wsaTo.removeChildren(); wsaTo.setText(_soapAction); } } // TODO: generate a unique namespace prefix? String userProcessNamespace = "userProcess"; /* Select all elements inside the soap envelope body. */ xpathSelector = DocumentHelper.createXPath("/soapenv:Envelope/soapenv:Body//*"); xpathSelector.setNamespaceURIs(MessageConstants.get_nsMap()); List bodyNodes = xpathSelector.selectNodes(message); /* Select all elements inside the task output payload. */ - xpathSelector = DocumentHelper.createXPath("/soapenv:Envelope/soapenv:Body/ib4p:response/ib4p:taskOutput//*"); + xpathSelector = DocumentHelper.createXPath("/soapenv:Envelope/soapenv:Body/*[1]/ib4p:taskOutput//*"); xpathSelector.setNamespaceURIs(MessageConstants.get_nsMap()); List taskOutputNodes = xpathSelector.selectNodes(message); /* * Change namespace for all the elements which are inside the soap * envelope body but not inside the task output payload. */ for (int i = 0; i < bodyNodes.size(); ++i) { Node node = (Node)bodyNodes.get(i); if (! taskOutputNodes.contains(node)) { Element element = (Element) node; element.remove(element.getNamespace()); element.setQName(QName.get(element.getName(),userProcessNamespace, userProcessNamespaceUri)); } } } /** * Returns the XML namespace URI of the user process which has been the * target of the latest message processed using the * <code>convertMessage</code> method. <br> * <br> * Returns <code>null</code> if an explicit namespace URI has been * specified to the <code>convertMessage</code> method. * * @return The XML namespace URI of the user process which has been the * target of the latest message processed using the * <code>convertMessage</code> method. <code>null</code>, if * the namespace URI has been explicitly specified to the * <code>convertMessage</code> method. * @see #convertMessage(Document, String) */ public String getUserProcessNamespaceUri() { return _userProcessNamespaceUri; } /** * Returns the endpoint URL of the user process which has been the target of * the latest message processed using the <code>convertMessage</code> * method. <br> * Returns <code>null<code> if the processes message was a reply. * * @return The endpoint URL of the user process which has been the source of * the latest message processed using the * <code>convertMessage</code> method. <code>null<code> if the processed message was a reply. * @see #convertMessage(Document, String) */ public String getUserProcessEndpoint() { return _userProcessEndpoint; } public String getSoapAction() { return _soapAction; } }
false
true
public void convertMessage(Document message, String userProcessNamespaceUri) throws MessageFormatException { XPath xpathSelector = DocumentHelper.createXPath("/soapenv:Envelope/soapenv:Body/soapenv:Fault"); xpathSelector.setNamespaceURIs(MessageConstants.get_nsMap()); List fault = xpathSelector.selectNodes(message); if(fault.size() != 0) { // return fault as-is LOG.error("Fault in response:\n"+message.asXML()); return; } //retrieve session xpathSelector = DocumentHelper.createXPath("/soapenv:Envelope/soapenv:Body/ib4p:response/ib4p:taskMetaData/ib4p:session"); xpathSelector.setNamespaceURIs(MessageConstants.get_nsMap()); List sessionNodes = xpathSelector.selectNodes(message); if (sessionNodes.size() > 0) { Element sessionElement = (Element) sessionNodes.get(0); String session = sessionElement.getText(); //remove callback xpathSelector = DocumentHelper.createXPath("/soapenv:Envelope/soapenv:Header/intalio:callback"); xpathSelector.setNamespaceURIs(MessageConstants.get_nsMap()); List callbackNodes = xpathSelector.selectNodes(message); if (callbackNodes.size() != 0) { Element wsaTo = (Element) callbackNodes.get(0); Element header = (Element)wsaTo.getParent(); header.remove(wsaTo); sessionElement = header.addElement("session"); sessionElement.addNamespace(null, MessageConstants.INTALIO_NS); sessionElement.setText(session); } } /* fetch the user process endpoint element from the task metadata */ xpathSelector = DocumentHelper.createXPath("/soapenv:Envelope/soapenv:Body/ib4p:response/ib4p:taskMetaData/ib4p:userProcessEndpoint"); xpathSelector.setNamespaceURIs(MessageConstants.get_nsMap()); List userProcessEndpointNodes = xpathSelector.selectNodes(message); if (userProcessEndpointNodes.size() > 0) { /* found the user process endpoint element */ Element userProcessEndpointElement = (Element) userProcessEndpointNodes.get(0); /* save it for later use */ _userProcessEndpoint = userProcessEndpointElement.getText(); /* do we have a wsa:To element? */ xpathSelector = DocumentHelper.createXPath("//wsa:To"); xpathSelector.setNamespaceURIs(MessageConstants.get_nsMap()); List wsaToNodes = xpathSelector.selectNodes(message); if (wsaToNodes.size() != 0) { /* We have the wsa:To element. Set the correct target endpoint */ Element wsaTo = (Element) wsaToNodes.get(0); wsaTo.setText(_userProcessEndpoint); } /* do we have a addr:To element? */ xpathSelector = DocumentHelper.createXPath("//addr:To"); xpathSelector.setNamespaceURIs(MessageConstants.get_nsMap()); List addrToNodes = xpathSelector.selectNodes(message); if (addrToNodes.size() != 0) { /* We have the wsa:To element. Set the correct target endpoint */ Element wsaTo = (Element) addrToNodes.get(0); //wsaTo.removeChildren(); wsaTo.setText(_userProcessEndpoint); } } /* * If the user process namespace URI is not specified explicitly, the * userProcessNamespaceURI element must be present in the metadata * section. */ if (userProcessNamespaceUri == null) { xpathSelector = DocumentHelper.createXPath("/soapenv:Envelope/soapenv:Body/ib4p:response/ib4p:taskMetaData/ib4p:userProcessNamespaceURI"); xpathSelector.setNamespaceURIs(MessageConstants.get_nsMap()); List namespaceElementQueryResult = xpathSelector.selectNodes(message); if (namespaceElementQueryResult.size() == 0) { throw new MessageFormatException("No user process namespace specified " + "and no ib4p:userProcessNamespaceURI element present to determine those."); } Element userProcessNamespaceUriElement = (Element) namespaceElementQueryResult.get(0); userProcessNamespaceUri = userProcessNamespaceUriElement.getText(); _userProcessNamespaceUri = userProcessNamespaceUri; } xpathSelector = DocumentHelper.createXPath("/soapenv:Envelope/soapenv:Body/ib4p:response/ib4p:taskMetaData/ib4p:userProcessCompleteSOAPAction"); xpathSelector.setNamespaceURIs(MessageConstants.get_nsMap()); List soapActionQueryResult = xpathSelector.selectNodes(message); if (soapActionQueryResult.size() > 0) { Element soapActionElement = (Element) soapActionQueryResult.get(0); _soapAction = soapActionElement.getText(); xpathSelector = DocumentHelper.createXPath("//addr:Action"); xpathSelector.setNamespaceURIs(MessageConstants.get_nsMap()); List actionNodes = xpathSelector.selectNodes(message); if (actionNodes.size() > 0) { Element wsaTo = (Element) actionNodes.get(0); //wsaTo.removeChildren(); wsaTo.setText(_soapAction); } } // TODO: generate a unique namespace prefix? String userProcessNamespace = "userProcess"; /* Select all elements inside the soap envelope body. */ xpathSelector = DocumentHelper.createXPath("/soapenv:Envelope/soapenv:Body//*"); xpathSelector.setNamespaceURIs(MessageConstants.get_nsMap()); List bodyNodes = xpathSelector.selectNodes(message); /* Select all elements inside the task output payload. */ xpathSelector = DocumentHelper.createXPath("/soapenv:Envelope/soapenv:Body/ib4p:response/ib4p:taskOutput//*"); xpathSelector.setNamespaceURIs(MessageConstants.get_nsMap()); List taskOutputNodes = xpathSelector.selectNodes(message); /* * Change namespace for all the elements which are inside the soap * envelope body but not inside the task output payload. */ for (int i = 0; i < bodyNodes.size(); ++i) { Node node = (Node)bodyNodes.get(i); if (! taskOutputNodes.contains(node)) { Element element = (Element) node; element.remove(element.getNamespace()); element.setQName(QName.get(element.getName(),userProcessNamespace, userProcessNamespaceUri)); } } }
public void convertMessage(Document message, String userProcessNamespaceUri) throws MessageFormatException { XPath xpathSelector = DocumentHelper.createXPath("/soapenv:Envelope/soapenv:Body/soapenv:Fault"); xpathSelector.setNamespaceURIs(MessageConstants.get_nsMap()); List fault = xpathSelector.selectNodes(message); if(fault.size() != 0) { // return fault as-is LOG.error("Fault in response:\n"+message.asXML()); return; } //retrieve session xpathSelector = DocumentHelper.createXPath("/soapenv:Envelope/soapenv:Body/*[1]/ib4p:taskMetaData/ib4p:session"); xpathSelector.setNamespaceURIs(MessageConstants.get_nsMap()); List sessionNodes = xpathSelector.selectNodes(message); if (sessionNodes.size() > 0) { Element sessionElement = (Element) sessionNodes.get(0); String session = sessionElement.getText(); //remove callback xpathSelector = DocumentHelper.createXPath("/soapenv:Envelope/soapenv:Header/intalio:callback"); xpathSelector.setNamespaceURIs(MessageConstants.get_nsMap()); List callbackNodes = xpathSelector.selectNodes(message); if (callbackNodes.size() != 0) { Element wsaTo = (Element) callbackNodes.get(0); Element header = (Element)wsaTo.getParent(); header.remove(wsaTo); sessionElement = header.addElement("session", MessageConstants.INTALIO_NS); sessionElement.setText(session); } } /* fetch the user process endpoint element from the task metadata */ xpathSelector = DocumentHelper.createXPath("/soapenv:Envelope/soapenv:Body/*[1]/ib4p:taskMetaData/ib4p:userProcessEndpoint"); xpathSelector.setNamespaceURIs(MessageConstants.get_nsMap()); List userProcessEndpointNodes = xpathSelector.selectNodes(message); if (userProcessEndpointNodes.size() > 0) { /* found the user process endpoint element */ Element userProcessEndpointElement = (Element) userProcessEndpointNodes.get(0); /* save it for later use */ _userProcessEndpoint = userProcessEndpointElement.getText(); /* do we have a wsa:To element? */ xpathSelector = DocumentHelper.createXPath("//wsa:To"); xpathSelector.setNamespaceURIs(MessageConstants.get_nsMap()); List wsaToNodes = xpathSelector.selectNodes(message); if (wsaToNodes.size() != 0) { /* We have the wsa:To element. Set the correct target endpoint */ Element wsaTo = (Element) wsaToNodes.get(0); wsaTo.setText(_userProcessEndpoint); } /* do we have a addr:To element? */ xpathSelector = DocumentHelper.createXPath("//addr:To"); xpathSelector.setNamespaceURIs(MessageConstants.get_nsMap()); List addrToNodes = xpathSelector.selectNodes(message); if (addrToNodes.size() != 0) { /* We have the wsa:To element. Set the correct target endpoint */ Element wsaTo = (Element) addrToNodes.get(0); //wsaTo.removeChildren(); wsaTo.setText(_userProcessEndpoint); } } /* * If the user process namespace URI is not specified explicitly, the * userProcessNamespaceURI element must be present in the metadata * section. */ if (userProcessNamespaceUri == null) { xpathSelector = DocumentHelper.createXPath("/soapenv:Envelope/soapenv:Body/*[1]/ib4p:taskMetaData/ib4p:userProcessNamespaceURI"); xpathSelector.setNamespaceURIs(MessageConstants.get_nsMap()); List namespaceElementQueryResult = xpathSelector.selectNodes(message); if (namespaceElementQueryResult.size() == 0) { throw new MessageFormatException("No user process namespace specified " + "and no ib4p:userProcessNamespaceURI element present to determine those."); } Element userProcessNamespaceUriElement = (Element) namespaceElementQueryResult.get(0); userProcessNamespaceUri = userProcessNamespaceUriElement.getText(); _userProcessNamespaceUri = userProcessNamespaceUri; } xpathSelector = DocumentHelper.createXPath("/soapenv:Envelope/soapenv:Body/*[1]/ib4p:taskMetaData/ib4p:userProcessCompleteSOAPAction"); xpathSelector.setNamespaceURIs(MessageConstants.get_nsMap()); List soapActionQueryResult = xpathSelector.selectNodes(message); if (soapActionQueryResult.size() > 0) { Element soapActionElement = (Element) soapActionQueryResult.get(0); _soapAction = soapActionElement.getText(); xpathSelector = DocumentHelper.createXPath("//addr:Action"); xpathSelector.setNamespaceURIs(MessageConstants.get_nsMap()); List actionNodes = xpathSelector.selectNodes(message); if (actionNodes.size() > 0) { Element wsaTo = (Element) actionNodes.get(0); //wsaTo.removeChildren(); wsaTo.setText(_soapAction); } } // TODO: generate a unique namespace prefix? String userProcessNamespace = "userProcess"; /* Select all elements inside the soap envelope body. */ xpathSelector = DocumentHelper.createXPath("/soapenv:Envelope/soapenv:Body//*"); xpathSelector.setNamespaceURIs(MessageConstants.get_nsMap()); List bodyNodes = xpathSelector.selectNodes(message); /* Select all elements inside the task output payload. */ xpathSelector = DocumentHelper.createXPath("/soapenv:Envelope/soapenv:Body/*[1]/ib4p:taskOutput//*"); xpathSelector.setNamespaceURIs(MessageConstants.get_nsMap()); List taskOutputNodes = xpathSelector.selectNodes(message); /* * Change namespace for all the elements which are inside the soap * envelope body but not inside the task output payload. */ for (int i = 0; i < bodyNodes.size(); ++i) { Node node = (Node)bodyNodes.get(i); if (! taskOutputNodes.contains(node)) { Element element = (Element) node; element.remove(element.getNamespace()); element.setQName(QName.get(element.getName(),userProcessNamespace, userProcessNamespaceUri)); } } }
diff --git a/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/PDPage.java b/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/PDPage.java index 153bfaf..921ffae 100644 --- a/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/PDPage.java +++ b/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/PDPage.java @@ -1,863 +1,864 @@ /* * 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.pdfbox.pdmodel; import org.apache.pdfbox.cos.COSArray; import org.apache.pdfbox.cos.COSBase; import org.apache.pdfbox.cos.COSDictionary; import org.apache.pdfbox.cos.COSName; import org.apache.pdfbox.cos.COSNumber; import org.apache.pdfbox.cos.COSStream; import org.apache.pdfbox.pdfviewer.PageDrawer; import org.apache.pdfbox.pdmodel.common.COSArrayList; import org.apache.pdfbox.pdmodel.common.COSObjectable; import org.apache.pdfbox.pdmodel.common.PDMetadata; import org.apache.pdfbox.pdmodel.common.PDRectangle; import org.apache.pdfbox.pdmodel.common.PDStream; import org.apache.pdfbox.pdmodel.interactive.action.PDPageAdditionalActions; import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation; import org.apache.pdfbox.pdmodel.interactive.pagenavigation.PDThreadBead; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.awt.print.PageFormat; import java.awt.print.Printable; import java.awt.print.PrinterException; import java.awt.print.PrinterIOException; import java.io.IOException; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.List; /** * This represents a single page in a PDF document. * <p> * This class implements the {@link Printable} interface, but since PDFBox * version 1.3.0 you should be using the {@link PDPageable} adapter instead * (see <a href="https://issues.apache.org/jira/browse/PDFBOX-788">PDFBOX-788</a>). * * @author <a href="mailto:[email protected]">Ben Litchfield</a> * @version $Revision: 1.29 $ */ public class PDPage implements COSObjectable, Printable { private static final int DEFAULT_USER_SPACE_UNIT_DPI = 72; private static final float MM_TO_UNITS = 1/(10*2.54f)*DEFAULT_USER_SPACE_UNIT_DPI; /** * Fully transparent that can fall back to white when image type has no alpha. */ private static final Color TRANSPARENT_WHITE = new Color( 255, 255, 255, 0 ); private COSDictionary page; /** * A page size of LETTER or 8.5x11. */ public static final PDRectangle PAGE_SIZE_LETTER = new PDRectangle( 8.5f*DEFAULT_USER_SPACE_UNIT_DPI, 11f*DEFAULT_USER_SPACE_UNIT_DPI ); /** * A page size of A0 Paper. */ public static final PDRectangle PAGE_SIZE_A0 = new PDRectangle( 841*MM_TO_UNITS, 1189*MM_TO_UNITS ); /** * A page size of A1 Paper. */ public static final PDRectangle PAGE_SIZE_A1 = new PDRectangle( 594*MM_TO_UNITS, 841*MM_TO_UNITS ); /** * A page size of A2 Paper. */ public static final PDRectangle PAGE_SIZE_A2 = new PDRectangle( 420*MM_TO_UNITS, 594*MM_TO_UNITS ); /** * A page size of A3 Paper. */ public static final PDRectangle PAGE_SIZE_A3 = new PDRectangle( 297*MM_TO_UNITS, 420*MM_TO_UNITS ); /** * A page size of A4 Paper. */ public static final PDRectangle PAGE_SIZE_A4 = new PDRectangle( 210*MM_TO_UNITS, 297*MM_TO_UNITS ); /** * A page size of A5 Paper. */ public static final PDRectangle PAGE_SIZE_A5 = new PDRectangle( 148*MM_TO_UNITS, 210*MM_TO_UNITS ); /** * A page size of A6 Paper. */ public static final PDRectangle PAGE_SIZE_A6 = new PDRectangle( 105*MM_TO_UNITS, 148*MM_TO_UNITS ); /** * Creates a new instance of PDPage with a size of 8.5x11. */ public PDPage() { page = new COSDictionary(); page.setItem( COSName.TYPE, COSName.PAGE ); setMediaBox( PAGE_SIZE_LETTER ); } /** * Creates a new instance of PDPage. * * @param size The MediaBox or the page. */ public PDPage(PDRectangle size) { page = new COSDictionary(); page.setItem( COSName.TYPE, COSName.PAGE ); setMediaBox( size ); } /** * Creates a new instance of PDPage. * * @param pageDic The existing page dictionary. */ public PDPage( COSDictionary pageDic ) { page = pageDic; } /** * Convert this standard java object to a COS object. * * @return The cos object that matches this Java object. */ public COSBase getCOSObject() { return page; } /** * This will get the underlying dictionary that this class acts on. * * @return The underlying dictionary for this class. */ public COSDictionary getCOSDictionary() { return page; } /** * This is the parent page node. The parent is a required element of the * page. This will be null until this page is added to the document. * * @return The parent to this page. */ public PDPageNode getParent() { if( parent == null) { COSDictionary parentDic = (COSDictionary)page.getDictionaryObject( COSName.PARENT, COSName.P ); if( parentDic != null ) { parent = new PDPageNode( parentDic ); } } return parent; } private PDPageNode parent = null; /** * This will set the parent of this page. * * @param parentNode The parent to this page node. */ public void setParent( PDPageNode parentNode ) { parent = parentNode; page.setItem( COSName.PARENT, parent.getDictionary() ); } /** * This will update the last modified time for the page object. */ public void updateLastModified() { page.setDate( COSName.LAST_MODIFIED, new GregorianCalendar() ); } /** * This will get the date that the content stream was last modified. This * may return null. * * @return The date the content stream was last modified. * * @throws IOException If there is an error accessing the date information. */ public Calendar getLastModified() throws IOException { return page.getDate( COSName.LAST_MODIFIED ); } /** * This will get the resources at this page and not look up the hierarchy. * This attribute is inheritable, and findResources() should probably used. * This will return null if no resources are available at this level. * * @return The resources at this level in the hierarchy. */ public PDResources getResources() { PDResources retval = null; COSDictionary resources = (COSDictionary)page.getDictionaryObject( COSName.RESOURCES ); if( resources != null ) { retval = new PDResources( resources ); } return retval; } /** * This will find the resources for this page by looking up the hierarchy until * it finds them. * * @return The resources at this level in the hierarchy. */ public PDResources findResources() { PDResources retval = getResources(); PDPageNode parentNode = getParent(); if( retval == null && parent != null ) { retval = parentNode.findResources(); } return retval; } /** * This will set the resources for this page. * * @param resources The new resources for this page. */ public void setResources( PDResources resources ) { page.setItem( COSName.RESOURCES, resources ); } /** * A rectangle, expressed * in default user space units, defining the boundaries of the physical * medium on which the page is intended to be displayed or printed * * This will get the MediaBox at this page and not look up the hierarchy. * This attribute is inheritable, and findMediaBox() should probably used. * This will return null if no MediaBox are available at this level. * * @return The MediaBox at this level in the hierarchy. */ public PDRectangle getMediaBox() { if( mediaBox == null) { COSArray array = (COSArray)page.getDictionaryObject( COSName.MEDIA_BOX ); if( array != null ) { mediaBox = new PDRectangle( array ); } } return mediaBox; } private PDRectangle mediaBox = null; /** * This will find the MediaBox for this page by looking up the hierarchy until * it finds them. * * @return The MediaBox at this level in the hierarchy. */ public PDRectangle findMediaBox() { PDRectangle retval = getMediaBox(); if( retval == null && getParent() != null ) { retval = getParent().findMediaBox(); } return retval; } /** * This will set the mediaBox for this page. * * @param mediaBoxValue The new mediaBox for this page. */ public void setMediaBox( PDRectangle mediaBoxValue ) { this.mediaBox = mediaBoxValue; if( mediaBoxValue == null ) { page.removeItem( COSName.MEDIA_BOX ); } else { page.setItem( COSName.MEDIA_BOX, mediaBoxValue.getCOSArray() ); } } /** * A rectangle, expressed in default user space units, * defining the visible region of default user space. When the page is displayed * or printed, its contents are to be clipped (cropped) to this rectangle * and then imposed on the output medium in some implementationdefined * manner * * This will get the CropBox at this page and not look up the hierarchy. * This attribute is inheritable, and findCropBox() should probably used. * This will return null if no CropBox is available at this level. * * @return The CropBox at this level in the hierarchy. */ public PDRectangle getCropBox() { PDRectangle retval = null; COSArray array = (COSArray)page.getDictionaryObject( COSName.CROP_BOX); if( array != null ) { retval = new PDRectangle( array ); } return retval; } /** * This will find the CropBox for this page by looking up the hierarchy until * it finds them. * * @return The CropBox at this level in the hierarchy. */ public PDRectangle findCropBox() { PDRectangle retval = getCropBox(); PDPageNode parentNode = getParent(); if( retval == null && parentNode != null ) { retval = findParentCropBox( parentNode ); } //default value for cropbox is the media box if( retval == null ) { retval = findMediaBox(); } return retval; } /** * This will search for a crop box in the parent and return null if it is not * found. It will NOT default to the media box if it cannot be found. * * @param node The node */ private PDRectangle findParentCropBox( PDPageNode node ) { PDRectangle rect = node.getCropBox(); PDPageNode parentNode = node.getParent(); if( rect == null && parentNode != null ) { rect = findParentCropBox( parentNode ); } return rect; } /** * This will set the CropBox for this page. * * @param cropBox The new CropBox for this page. */ public void setCropBox( PDRectangle cropBox ) { if( cropBox == null ) { page.removeItem( COSName.CROP_BOX ); } else { page.setItem( COSName.CROP_BOX, cropBox.getCOSArray() ); } } /** * A rectangle, expressed in default user space units, defining * the region to which the contents of the page should be clipped * when output in a production environment. The default is the CropBox. * * @return The BleedBox attribute. */ public PDRectangle getBleedBox() { PDRectangle retval = null; COSArray array = (COSArray)page.getDictionaryObject( COSName.BLEED_BOX ); if( array != null ) { retval = new PDRectangle( array ); } else { retval = findCropBox(); } return retval; } /** * This will set the BleedBox for this page. * * @param bleedBox The new BleedBox for this page. */ public void setBleedBox( PDRectangle bleedBox ) { if( bleedBox == null ) { page.removeItem( COSName.BLEED_BOX ); } else { page.setItem( COSName.BLEED_BOX, bleedBox.getCOSArray() ); } } /** * A rectangle, expressed in default user space units, defining * the intended dimensions of the finished page after trimming. * The default is the CropBox. * * @return The TrimBox attribute. */ public PDRectangle getTrimBox() { PDRectangle retval = null; COSArray array = (COSArray)page.getDictionaryObject( COSName.TRIM_BOX ); if( array != null ) { retval = new PDRectangle( array ); } else { retval = findCropBox(); } return retval; } /** * This will set the TrimBox for this page. * * @param trimBox The new TrimBox for this page. */ public void setTrimBox( PDRectangle trimBox ) { if( trimBox == null ) { page.removeItem( COSName.TRIM_BOX ); } else { page.setItem( COSName.TRIM_BOX, trimBox.getCOSArray() ); } } /** * A rectangle, expressed in default user space units, defining * the extent of the page's meaningful content (including potential * white space) as intended by the page's creator The default isthe CropBox. * * @return The ArtBox attribute. */ public PDRectangle getArtBox() { PDRectangle retval = null; COSArray array = (COSArray)page.getDictionaryObject( COSName.ART_BOX ); if( array != null ) { retval = new PDRectangle( array ); } else { retval = findCropBox(); } return retval; } /** * This will set the ArtBox for this page. * * @param artBox The new ArtBox for this page. */ public void setArtBox( PDRectangle artBox ) { if( artBox == null ) { page.removeItem( COSName.ART_BOX ); } else { page.setItem( COSName.ART_BOX, artBox.getCOSArray() ); } } //todo BoxColorInfo //todo Contents /** * A value representing the rotation. This will be null if not set at this level * The number of degrees by which the page should * be rotated clockwise when displayed or printed. The value must be a multiple * of 90. * * This will get the rotation at this page and not look up the hierarchy. * This attribute is inheritable, and findRotation() should probably used. * This will return null if no rotation is available at this level. * * @return The rotation at this level in the hierarchy. */ public Integer getRotation() { Integer retval = null; COSNumber value = (COSNumber)page.getDictionaryObject( COSName.ROTATE ); if( value != null ) { retval = new Integer( value.intValue() ); } return retval; } /** * This will find the rotation for this page by looking up the hierarchy until * it finds them. * * @return The rotation at this level in the hierarchy. */ public int findRotation() { int retval = 0; Integer rotation = getRotation(); if( rotation != null ) { retval = rotation.intValue(); } else { PDPageNode parentNode = getParent(); if( parentNode != null ) { retval = parentNode.findRotation(); } } return retval; } /** * This will set the rotation for this page. * * @param rotation The new rotation for this page. */ public void setRotation( int rotation ) { page.setInt( COSName.ROTATE, rotation ); } /** * This will get the contents of the PDF Page, in the case that the contents * of the page is an array then then the entire array of streams will be * be wrapped and appear as a single stream. * * @return The page content stream. * * @throws IOException If there is an error obtaining the stream. */ public PDStream getContents() throws IOException { return PDStream.createFromCOS( page.getDictionaryObject( COSName.CONTENTS ) ); } /** * This will set the contents of this page. * * @param contents The new contents of the page. */ public void setContents( PDStream contents ) { page.setItem( COSName.CONTENTS, contents ); } /** * This will get a list of PDThreadBead objects, which are article threads in the * document. This will return an empty list of there are no thread beads. * * @return A list of article threads on this page. */ public List getThreadBeads() { COSArray beads = (COSArray)page.getDictionaryObject( COSName.B ); if( beads == null ) { beads = new COSArray(); } List<PDThreadBead> pdObjects = new ArrayList<PDThreadBead>(); for( int i=0; i<beads.size(); i++) { COSDictionary beadDic = (COSDictionary)beads.getObject( i ); PDThreadBead bead = null; //in some cases the bead is null if( beadDic != null ) { bead = new PDThreadBead( beadDic ); } pdObjects.add( bead ); } return new COSArrayList(pdObjects, beads); } /** * This will set the list of thread beads. * * @param beads A list of PDThreadBead objects or null. */ public void setThreadBeads( List<PDThreadBead> beads ) { page.setItem( COSName.B, COSArrayList.converterToCOSArray( beads ) ); } /** * Get the metadata that is part of the document catalog. This will * return null if there is no meta data for this object. * * @return The metadata for this object. */ public PDMetadata getMetadata() { PDMetadata retval = null; COSStream stream = (COSStream)page.getDictionaryObject( COSName.METADATA ); if( stream != null ) { retval = new PDMetadata( stream ); } return retval; } /** * Set the metadata for this object. This can be null. * * @param meta The meta data for this object. */ public void setMetadata( PDMetadata meta ) { page.setItem( COSName.METADATA, meta ); } /** * Convert this page to an output image with 8 bits per pixel and the double * default screen resolution. * * @return A graphical representation of this page. * * @throws IOException If there is an error drawing to the image. */ public BufferedImage convertToImage() throws IOException { //note we are doing twice as many pixels because //the default size is not really good resolution, //so create an image that is twice the size //and let the client scale it down. return convertToImage(8, 2 * DEFAULT_USER_SPACE_UNIT_DPI); } /** * Convert this page to an output image. * * @param imageType the image type (see {@link BufferedImage}.TYPE_*) * @param resolution the resolution in dpi (dots per inch) * @return A graphical representation of this page. * * @throws IOException If there is an error drawing to the image. */ public BufferedImage convertToImage(int imageType, int resolution) throws IOException { PDRectangle cropBox = findCropBox(); float widthPt = cropBox.getWidth(); float heightPt = cropBox.getHeight(); float scaling = resolution / (float)DEFAULT_USER_SPACE_UNIT_DPI; int widthPx = Math.round(widthPt * scaling); int heightPx = Math.round(heightPt * scaling); //TODO The following reduces accuracy. It should really be a Dimension2D.Float. Dimension pageDimension = new Dimension( (int)widthPt, (int)heightPt ); BufferedImage retval = null; int rotationAngle = findRotation(); // normalize the rotation angle if (rotationAngle < 0) { rotationAngle += 360; } else if (rotationAngle >= 360) { rotationAngle -= 360; } - if (rotationAngle != 0) + // swap width and height + if (rotationAngle == 90 || rotationAngle == 270) { retval = new BufferedImage( heightPx, widthPx, imageType ); } else { retval = new BufferedImage( widthPx, heightPx, imageType ); } Graphics2D graphics = (Graphics2D)retval.getGraphics(); graphics.setBackground( TRANSPARENT_WHITE ); graphics.clearRect( 0, 0, retval.getWidth(), retval.getHeight() ); if (rotationAngle != 0) { int translateX = 0; int translateY = 0; switch(rotationAngle) { case 90: translateX = retval.getWidth(); break; case 270: translateY = retval.getHeight(); break; case 180: translateX = retval.getWidth(); translateY = retval.getHeight(); break; default: break; } graphics.translate(translateX,translateY); graphics.rotate((float)Math.toRadians(rotationAngle)); } graphics.scale( scaling, scaling ); PageDrawer drawer = new PageDrawer(); drawer.drawPage( graphics, this, pageDimension ); return retval; } /** * Get the page actions. * * @return The Actions for this Page */ public PDPageAdditionalActions getActions() { COSDictionary addAct = (COSDictionary) page.getDictionaryObject(COSName.AA); if (addAct == null) { addAct = new COSDictionary(); page.setItem(COSName.AA, addAct); } return new PDPageAdditionalActions(addAct); } /** * Set the page actions. * * @param actions The actions for the page. */ public void setActions( PDPageAdditionalActions actions ) { page.setItem( COSName.AA, actions ); } /** * This will return a list of the Annotations for this page. * * @return List of the PDAnnotation objects. * * @throws IOException If there is an error while creating the annotations. */ public List getAnnotations() throws IOException { COSArrayList retval = null; COSArray annots = (COSArray)page.getDictionaryObject(COSName.ANNOTS); if (annots == null) { annots = new COSArray(); page.setItem(COSName.ANNOTS, annots); retval = new COSArrayList(new ArrayList(), annots); } else { List<PDAnnotation> actuals = new ArrayList<PDAnnotation>(); for (int i=0; i < annots.size(); i++) { COSBase item = annots.getObject(i); actuals.add( PDAnnotation.createAnnotation( item ) ); } retval = new COSArrayList(actuals, annots); } return retval; } /** * This will set the list of annotations. * * @param annots The new list of annotations. */ public void setAnnotations( List<PDAnnotation> annots ) { page.setItem( COSName.ANNOTS, COSArrayList.converterToCOSArray( annots ) ); } /** * @deprecated Use the {@link PDPageable} adapter class * {@inheritDoc} */ public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException { try { PageDrawer drawer = new PageDrawer(); PDRectangle cropBox = findCropBox(); drawer.drawPage( graphics, this, cropBox.createDimension() ); return PAGE_EXISTS; } catch( IOException io ) { throw new PrinterIOException( io ); } } /** * {@inheritDoc} */ public boolean equals( Object other ) { return other instanceof PDPage && ((PDPage)other).getCOSObject() == this.getCOSObject(); } /** * {@inheritDoc} */ public int hashCode() { return this.getCOSDictionary().hashCode(); } }
true
true
public BufferedImage convertToImage(int imageType, int resolution) throws IOException { PDRectangle cropBox = findCropBox(); float widthPt = cropBox.getWidth(); float heightPt = cropBox.getHeight(); float scaling = resolution / (float)DEFAULT_USER_SPACE_UNIT_DPI; int widthPx = Math.round(widthPt * scaling); int heightPx = Math.round(heightPt * scaling); //TODO The following reduces accuracy. It should really be a Dimension2D.Float. Dimension pageDimension = new Dimension( (int)widthPt, (int)heightPt ); BufferedImage retval = null; int rotationAngle = findRotation(); // normalize the rotation angle if (rotationAngle < 0) { rotationAngle += 360; } else if (rotationAngle >= 360) { rotationAngle -= 360; } if (rotationAngle != 0) { retval = new BufferedImage( heightPx, widthPx, imageType ); } else { retval = new BufferedImage( widthPx, heightPx, imageType ); } Graphics2D graphics = (Graphics2D)retval.getGraphics(); graphics.setBackground( TRANSPARENT_WHITE ); graphics.clearRect( 0, 0, retval.getWidth(), retval.getHeight() ); if (rotationAngle != 0) { int translateX = 0; int translateY = 0; switch(rotationAngle) { case 90: translateX = retval.getWidth(); break; case 270: translateY = retval.getHeight(); break; case 180: translateX = retval.getWidth(); translateY = retval.getHeight(); break; default: break; } graphics.translate(translateX,translateY); graphics.rotate((float)Math.toRadians(rotationAngle)); } graphics.scale( scaling, scaling ); PageDrawer drawer = new PageDrawer(); drawer.drawPage( graphics, this, pageDimension ); return retval; }
public BufferedImage convertToImage(int imageType, int resolution) throws IOException { PDRectangle cropBox = findCropBox(); float widthPt = cropBox.getWidth(); float heightPt = cropBox.getHeight(); float scaling = resolution / (float)DEFAULT_USER_SPACE_UNIT_DPI; int widthPx = Math.round(widthPt * scaling); int heightPx = Math.round(heightPt * scaling); //TODO The following reduces accuracy. It should really be a Dimension2D.Float. Dimension pageDimension = new Dimension( (int)widthPt, (int)heightPt ); BufferedImage retval = null; int rotationAngle = findRotation(); // normalize the rotation angle if (rotationAngle < 0) { rotationAngle += 360; } else if (rotationAngle >= 360) { rotationAngle -= 360; } // swap width and height if (rotationAngle == 90 || rotationAngle == 270) { retval = new BufferedImage( heightPx, widthPx, imageType ); } else { retval = new BufferedImage( widthPx, heightPx, imageType ); } Graphics2D graphics = (Graphics2D)retval.getGraphics(); graphics.setBackground( TRANSPARENT_WHITE ); graphics.clearRect( 0, 0, retval.getWidth(), retval.getHeight() ); if (rotationAngle != 0) { int translateX = 0; int translateY = 0; switch(rotationAngle) { case 90: translateX = retval.getWidth(); break; case 270: translateY = retval.getHeight(); break; case 180: translateX = retval.getWidth(); translateY = retval.getHeight(); break; default: break; } graphics.translate(translateX,translateY); graphics.rotate((float)Math.toRadians(rotationAngle)); } graphics.scale( scaling, scaling ); PageDrawer drawer = new PageDrawer(); drawer.drawPage( graphics, this, pageDimension ); return retval; }
diff --git a/eclipse/plugins/net.sf.orcc.backends/src/net/sf/orcc/backends/xlim/transform/UnaryListRemoval.java b/eclipse/plugins/net.sf.orcc.backends/src/net/sf/orcc/backends/xlim/transform/UnaryListRemoval.java index 0903faadb..7bcbb53e4 100644 --- a/eclipse/plugins/net.sf.orcc.backends/src/net/sf/orcc/backends/xlim/transform/UnaryListRemoval.java +++ b/eclipse/plugins/net.sf.orcc.backends/src/net/sf/orcc/backends/xlim/transform/UnaryListRemoval.java @@ -1,102 +1,99 @@ /* * Copyright (c) 2010-2011, IRISA * 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 IRISA 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 net.sf.orcc.backends.xlim.transform; import java.util.ArrayList; import java.util.List; import net.sf.orcc.df.Action; import net.sf.orcc.df.Pattern; import net.sf.orcc.df.Port; import net.sf.orcc.df.util.DfVisitor; import net.sf.orcc.ir.Def; import net.sf.orcc.ir.InstAssign; import net.sf.orcc.ir.InstLoad; import net.sf.orcc.ir.InstStore; import net.sf.orcc.ir.IrFactory; import net.sf.orcc.ir.TypeList; import net.sf.orcc.ir.Use; import net.sf.orcc.ir.Var; import net.sf.orcc.ir.util.IrUtil; import net.sf.orcc.util.util.EcoreHelper; import org.eclipse.emf.ecore.util.EcoreUtil; /** * This class defines an actor transformation that replace list of one element * used to stock input/output value by a scalar * * @author Herve Yviquel * */ public class UnaryListRemoval extends DfVisitor<Void> { @Override public Void caseAction(Action action) { doSwitch(action.getInputPattern()); doSwitch(action.getOutputPattern()); return null; } @Override public Void casePattern(Pattern pattern) { List<Port> ports = new ArrayList<Port>(pattern.getPorts()); for (Port port : ports) { if (pattern.getNumTokens(port) == 1) { Var var = pattern.getVariable(port); // Transform in scalar variable var.setType(((TypeList) var.getType()).getInnermostType()); // Transform load in assignment for (Use use : new ArrayList<Use>(var.getUses())) { InstLoad load = EcoreHelper.getContainerOfType(use, InstLoad.class); InstAssign assign = IrFactory.eINSTANCE.createInstAssign( load.getTarget().getVariable(), load.getSource() .getVariable()); EcoreUtil.replace(load, assign); IrUtil.delete(load); } // Transform store in assignment for (Def def : new ArrayList<Def>(var.getDefs())) { InstStore store = EcoreHelper.getContainerOfType(def, InstStore.class); - InstAssign assign = IrFactory.eINSTANCE.createInstAssign( - store.getTarget().getVariable(), store.getValue()); - EcoreUtil.replace(store, assign); - IrUtil.delete(store); + store.getIndexes().clear(); } } } return null; } }
true
true
public Void casePattern(Pattern pattern) { List<Port> ports = new ArrayList<Port>(pattern.getPorts()); for (Port port : ports) { if (pattern.getNumTokens(port) == 1) { Var var = pattern.getVariable(port); // Transform in scalar variable var.setType(((TypeList) var.getType()).getInnermostType()); // Transform load in assignment for (Use use : new ArrayList<Use>(var.getUses())) { InstLoad load = EcoreHelper.getContainerOfType(use, InstLoad.class); InstAssign assign = IrFactory.eINSTANCE.createInstAssign( load.getTarget().getVariable(), load.getSource() .getVariable()); EcoreUtil.replace(load, assign); IrUtil.delete(load); } // Transform store in assignment for (Def def : new ArrayList<Def>(var.getDefs())) { InstStore store = EcoreHelper.getContainerOfType(def, InstStore.class); InstAssign assign = IrFactory.eINSTANCE.createInstAssign( store.getTarget().getVariable(), store.getValue()); EcoreUtil.replace(store, assign); IrUtil.delete(store); } } } return null; }
public Void casePattern(Pattern pattern) { List<Port> ports = new ArrayList<Port>(pattern.getPorts()); for (Port port : ports) { if (pattern.getNumTokens(port) == 1) { Var var = pattern.getVariable(port); // Transform in scalar variable var.setType(((TypeList) var.getType()).getInnermostType()); // Transform load in assignment for (Use use : new ArrayList<Use>(var.getUses())) { InstLoad load = EcoreHelper.getContainerOfType(use, InstLoad.class); InstAssign assign = IrFactory.eINSTANCE.createInstAssign( load.getTarget().getVariable(), load.getSource() .getVariable()); EcoreUtil.replace(load, assign); IrUtil.delete(load); } // Transform store in assignment for (Def def : new ArrayList<Def>(var.getDefs())) { InstStore store = EcoreHelper.getContainerOfType(def, InstStore.class); store.getIndexes().clear(); } } } return null; }
diff --git a/src/main/java/ar/edu/itba/paw/grupo1/controller/QueryServlet.java b/src/main/java/ar/edu/itba/paw/grupo1/controller/QueryServlet.java index 8f60fb4..b2df453 100644 --- a/src/main/java/ar/edu/itba/paw/grupo1/controller/QueryServlet.java +++ b/src/main/java/ar/edu/itba/paw/grupo1/controller/QueryServlet.java @@ -1,80 +1,80 @@ package ar.edu.itba.paw.grupo1.controller; import java.io.IOException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import ar.edu.itba.paw.grupo1.ApplicationContainer; import ar.edu.itba.paw.grupo1.controller.BaseServlet; import ar.edu.itba.paw.grupo1.model.Property; import ar.edu.itba.paw.grupo1.service.PropertyService; @SuppressWarnings("serial") public class QueryServlet extends BaseServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String operation = req.getParameter("operation"); String property = req.getParameter("property"); String rangeFrom = req.getParameter("rangeFrom"); String rangeTo = req.getParameter("rangeTo"); if (operation == null && property == null && rangeFrom == null && rangeTo == null) { render(req, resp, "query.jsp", "Query"); return; } if (operation == null) { operation = "any"; } if (property == null) { property = "any"; } double parsedRangeFrom = 0; - double parsedRangeTo = 0; + double parsedRangeTo = Double.MAX_VALUE; boolean badParse = false; try { - if (rangeFrom != null) { + if (rangeFrom != null && !rangeFrom.isEmpty()) { parsedRangeFrom = Double.parseDouble(rangeFrom); } - if (rangeTo != null) { + if (rangeTo != null && !rangeTo.isEmpty()) { parsedRangeTo = Double.parseDouble(rangeTo); } } catch (NumberFormatException e) { badParse = true; } if (badParse || (rangeFrom != null && parsedRangeFrom < 0) || (rangeTo != null && parsedRangeTo < 0) || (rangeFrom != null && rangeTo != null && parsedRangeTo < parsedRangeFrom)) { req.setAttribute("invalidRange", true); render(req, resp, "query.jsp", "Query"); return; } if (rangeFrom == null) { parsedRangeFrom = 0; } if (rangeTo == null) { parsedRangeTo = Double.MAX_VALUE; } List<Property> query = ApplicationContainer.get(PropertyService.class) .query(operation, property, parsedRangeFrom, parsedRangeTo); req.setAttribute("queryResults", query); render(req, resp, "query.jsp", "Query"); } }
false
true
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String operation = req.getParameter("operation"); String property = req.getParameter("property"); String rangeFrom = req.getParameter("rangeFrom"); String rangeTo = req.getParameter("rangeTo"); if (operation == null && property == null && rangeFrom == null && rangeTo == null) { render(req, resp, "query.jsp", "Query"); return; } if (operation == null) { operation = "any"; } if (property == null) { property = "any"; } double parsedRangeFrom = 0; double parsedRangeTo = 0; boolean badParse = false; try { if (rangeFrom != null) { parsedRangeFrom = Double.parseDouble(rangeFrom); } if (rangeTo != null) { parsedRangeTo = Double.parseDouble(rangeTo); } } catch (NumberFormatException e) { badParse = true; } if (badParse || (rangeFrom != null && parsedRangeFrom < 0) || (rangeTo != null && parsedRangeTo < 0) || (rangeFrom != null && rangeTo != null && parsedRangeTo < parsedRangeFrom)) { req.setAttribute("invalidRange", true); render(req, resp, "query.jsp", "Query"); return; } if (rangeFrom == null) { parsedRangeFrom = 0; } if (rangeTo == null) { parsedRangeTo = Double.MAX_VALUE; } List<Property> query = ApplicationContainer.get(PropertyService.class) .query(operation, property, parsedRangeFrom, parsedRangeTo); req.setAttribute("queryResults", query); render(req, resp, "query.jsp", "Query"); }
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String operation = req.getParameter("operation"); String property = req.getParameter("property"); String rangeFrom = req.getParameter("rangeFrom"); String rangeTo = req.getParameter("rangeTo"); if (operation == null && property == null && rangeFrom == null && rangeTo == null) { render(req, resp, "query.jsp", "Query"); return; } if (operation == null) { operation = "any"; } if (property == null) { property = "any"; } double parsedRangeFrom = 0; double parsedRangeTo = Double.MAX_VALUE; boolean badParse = false; try { if (rangeFrom != null && !rangeFrom.isEmpty()) { parsedRangeFrom = Double.parseDouble(rangeFrom); } if (rangeTo != null && !rangeTo.isEmpty()) { parsedRangeTo = Double.parseDouble(rangeTo); } } catch (NumberFormatException e) { badParse = true; } if (badParse || (rangeFrom != null && parsedRangeFrom < 0) || (rangeTo != null && parsedRangeTo < 0) || (rangeFrom != null && rangeTo != null && parsedRangeTo < parsedRangeFrom)) { req.setAttribute("invalidRange", true); render(req, resp, "query.jsp", "Query"); return; } if (rangeFrom == null) { parsedRangeFrom = 0; } if (rangeTo == null) { parsedRangeTo = Double.MAX_VALUE; } List<Property> query = ApplicationContainer.get(PropertyService.class) .query(operation, property, parsedRangeFrom, parsedRangeTo); req.setAttribute("queryResults", query); render(req, resp, "query.jsp", "Query"); }
diff --git a/deegree-services/src/main/java/org/deegree/services/wms/StyleRegistry.java b/deegree-services/src/main/java/org/deegree/services/wms/StyleRegistry.java index abbd37910d..41a6847283 100644 --- a/deegree-services/src/main/java/org/deegree/services/wms/StyleRegistry.java +++ b/deegree-services/src/main/java/org/deegree/services/wms/StyleRegistry.java @@ -1,389 +1,398 @@ //$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.wms; import static org.deegree.services.wms.controller.sld.SLDParser.getStyles; import static org.slf4j.LoggerFactory.getLogger; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.TimerTask; import javax.xml.bind.JAXBElement; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import org.deegree.commons.utils.Pair; import org.deegree.commons.utils.log.LoggingNotes; import org.deegree.commons.xml.XMLAdapter; import org.deegree.filter.Filter; import org.deegree.rendering.r2d.se.parser.SymbologyParser; import org.deegree.rendering.r2d.se.unevaluated.Style; import org.deegree.services.jaxb.wms.DirectStyleType; import org.deegree.services.jaxb.wms.SLDStyleType; import org.slf4j.Logger; /** * <code>StyleRegistry</code> * * @author <a href="mailto:[email protected]">Andreas Schmitz</a> * @author last edited by: $Author$ * * @version $Revision$, $Date$ */ @LoggingNotes(info = "logs when style files cannot be loaded", trace = "logs stack traces", debug = "logs information about loading/reloading of style files") public class StyleRegistry extends TimerTask { private static final Logger LOG = getLogger( StyleRegistry.class ); private HashMap<String, HashMap<String, Style>> registry = new HashMap<String, HashMap<String, Style>>(); private HashMap<String, HashMap<String, Style>> legendRegistry = new HashMap<String, HashMap<String, Style>>(); private HashMap<File, Pair<Long, String>> monitoredFiles = new HashMap<File, Pair<Long, String>>(); private HashSet<String> soleStyleFiles = new HashSet<String>(); /** * @param layerName * @param style * @param clear * if true, all other styles will be removed for the layer */ public void put( String layerName, Style style, boolean clear ) { HashMap<String, Style> styles = registry.get( layerName ); if ( styles == null ) { styles = new HashMap<String, Style>(); registry.put( layerName, styles ); styles.put( "default", style ); } else if ( clear ) { styles.clear(); styles.put( "default", style ); } if ( style.getName() == null ) { LOG.debug( "Overriding default style since new style does not have name." ); styles.put( "default", style ); } else { styles.put( style.getName(), style ); } } /** * @param layerName * @param style * @param clear */ public void putLegend( String layerName, Style style, boolean clear ) { HashMap<String, Style> styles = legendRegistry.get( layerName ); if ( styles == null ) { styles = new HashMap<String, Style>(); legendRegistry.put( layerName, styles ); styles.put( "default", style ); } else if ( clear ) { styles.clear(); styles.put( "default", style ); } if ( style.getName() == null ) { LOG.debug( "Overriding default style since new style does not have name." ); styles.put( "default", style ); } else { styles.put( style.getName(), style ); } } /** * @param layerName * @param style */ public void putAsDefault( String layerName, Style style ) { HashMap<String, Style> styles = registry.get( layerName ); if ( styles == null ) { styles = new HashMap<String, Style>(); registry.put( layerName, styles ); } styles.put( "default", style ); styles.put( style.getName(), style ); } /** * @param layerName * @return null, if not available */ public Style getDefault( String layerName ) { HashMap<String, Style> styles = registry.get( layerName ); if ( styles == null ) { return null; } return styles.get( "default" ); } /** * @param layerName * @param styleName * may be null, in which case the default style will be searched for * @return null, if not available */ public Style getLegendStyle( String layerName, String styleName ) { if ( styleName == null ) { styleName = "default"; } if ( legendRegistry.get( layerName ) != null && legendRegistry.get( layerName ).containsKey( styleName ) ) { return legendRegistry.get( layerName ).get( styleName ); } return get( layerName, styleName ); } /** * @param layerName * @param styleName * @return true, if the layer has a style with the name */ public boolean hasStyle( String layerName, String styleName ) { HashMap<String, Style> styles = registry.get( layerName ); return styles != null && styles.get( styleName ) != null; } /** * @param layerName * @param styleName * @return null, if not available */ public Style get( String layerName, String styleName ) { HashMap<String, Style> styles = registry.get( layerName ); if ( styles == null ) { return null; } return styles.get( styleName ); } /** * @param layerName * @return all styles for the layer */ public ArrayList<Style> getAll( String layerName ) { HashMap<String, Style> map = registry.get( layerName ); if ( map == null ) { return new ArrayList<Style>(); } ArrayList<Style> styles = new ArrayList<Style>( map.size() ); styles.addAll( map.values() ); return styles; } private Style loadNoImport( String layerName, File file ) { XMLInputFactory fac = XMLInputFactory.newInstance(); try { LOG.debug( "Trying to load style from '{}'", file ); FileInputStream in = new FileInputStream( file ); Style sty = SymbologyParser.INSTANCE.parse( fac.createXMLStreamReader( file.toString(), in ) ); in.close(); monitoredFiles.put( file, new Pair<Long, String>( file.lastModified(), layerName ) ); return sty; } catch ( FileNotFoundException e ) { LOG.info( "Style file '{}' for layer '{}' could not be found: '{}'", new Object[] { file, layerName, e.getLocalizedMessage() } ); } catch ( XMLStreamException e ) { LOG.trace( "Stack trace:", e ); LOG.info( "Style file '{}' for layer '{}' could not be loaded: '{}'", new Object[] { file, layerName, e.getLocalizedMessage() } ); } catch ( IOException e ) { LOG.info( "IO error for style file '{}' for layer '{}': '{}'", new Object[] { file, layerName, e.getLocalizedMessage() } ); } return null; } /** * @param layerName * @param file * @return true, if actually loaded */ public boolean load( String layerName, File file ) { Style sty = loadNoImport( layerName, file ); if ( sty != null ) { put( layerName, sty, soleStyleFiles.contains( file.getName() ) ); return true; } return false; } /** * @param layerName * @param styles * @param adapter */ public void load( String layerName, List<DirectStyleType> styles, XMLAdapter adapter ) { for ( DirectStyleType sty : styles ) { try { File file = new File( adapter.resolve( sty.getFile() ).toURI() ); String name = sty.getName(); Style style = loadNoImport( layerName, file ); if ( style != null ) { if ( name != null ) { style.setName( name ); } if ( styles.size() == 1 ) { soleStyleFiles.add( file.getName() ); } put( layerName, style, false ); } } catch ( MalformedURLException e ) { LOG.trace( "Stack trace", e ); LOG.info( "Style file '{}' for layer '{}' could not be resolved.", sty.getFile(), layerName ); } catch ( URISyntaxException e ) { LOG.trace( "Stack trace", e ); LOG.info( "Style file '{}' for layer '{}' could not be resolved.", sty.getFile(), layerName ); } try { if ( sty.getLegendConfigurationFile() != null ) { LOG.debug( "Reading {} as legend configuration file.", sty.getLegendConfigurationFile() ); File file = new File( adapter.resolve( sty.getLegendConfigurationFile() ).toURI() ); String name = sty.getName(); Style style = loadNoImport( layerName, file ); if ( style != null ) { if ( name != null ) { style.setName( name ); } putLegend( layerName, style, false ); } } } catch ( MalformedURLException e ) { LOG.trace( "Stack trace", e ); LOG.info( "Style file '{}' for layer '{}' could not be resolved.", sty.getFile(), layerName ); } catch ( URISyntaxException e ) { LOG.trace( "Stack trace", e ); LOG.info( "Style file '{}' for layer '{}' could not be resolved.", sty.getFile(), layerName ); } } } /** * @param layerName * @param styles * @param adapter */ public void load( String layerName, XMLAdapter adapter, List<SLDStyleType> styles ) { for ( SLDStyleType sty : styles ) { try { File file = new File( adapter.resolve( sty.getFile() ).toURI() ); String namedLayer = sty.getNamedLayer(); LOG.debug( "Will read styles from SLD '{}', for named layer '{}'.", file, namedLayer ); Map<String, String> map = new HashMap<String, String>(); String name = null; for ( JAXBElement<String> elem : sty.getNameAndUserStyleAndLegendConfigurationFile() ) { - // TODO sth w/ the legend file if ( elem.getName().getLocalPart().equals( "Name" ) ) { name = elem.getValue(); - } else { + } else if ( elem.getName().getLocalPart().equals( "LegendConfigurationFile" ) ) { + LOG.debug( "Reading {} as legend configuration file.", elem.getValue() ); + File legendFile = new File( adapter.resolve( elem.getValue() ).toURI() ); + Style style = loadNoImport( layerName, legendFile ); + if ( style != null ) { + if ( name != null ) { + style.setName( name ); + } + putLegend( layerName, style, false ); + } + } else if ( elem.getName().getLocalPart().equals( "UserStyle" ) ) { if ( name == null ) { name = elem.getValue(); } LOG.debug( "Will load user style with name '{}', it will be known as '{}'.", elem.getValue(), name ); map.put( elem.getValue(), name ); name = null; } } XMLInputFactory fac = XMLInputFactory.newInstance(); FileInputStream is = new FileInputStream( file ); XMLStreamReader in = fac.createXMLStreamReader( file.toURI().toURL().toString(), is ); Pair<LinkedList<Filter>, LinkedList<Style>> parsedStyles = getStyles( in, namedLayer, map ); for ( Style s : parsedStyles.second ) { put( layerName, s, false ); } is.close(); } catch ( MalformedURLException e ) { LOG.trace( "Stack trace", e ); LOG.info( "Style file '{}' for layer '{}' could not be resolved.", sty.getFile(), layerName ); } catch ( FileNotFoundException e ) { LOG.trace( "Stack trace", e ); LOG.info( "Style file '{}' for layer '{}' could not be found.", sty.getFile(), layerName ); } catch ( XMLStreamException e ) { LOG.trace( "Stack trace", e ); LOG.info( "Style file '{}' for layer '{}' could not be parsed: '{}'.", new Object[] { sty.getFile(), layerName, e.getLocalizedMessage() } ); } catch ( URISyntaxException e ) { LOG.trace( "Stack trace", e ); LOG.info( "Style file '{}' for layer '{}' could not be resolved.", sty.getFile(), layerName ); } catch ( IOException e ) { LOG.trace( "Stack trace", e ); LOG.info( "Style file '{}' for layer '{}' could not be closed: '{}'.", new Object[] { sty.getFile(), layerName, e.getLocalizedMessage() } ); } } } /** * @param layerName * @param file * @param isSoleStyle * if true, all styles will be cleared upon update * @return true, if actually loaded */ public boolean register( String layerName, File file, boolean isSoleStyle ) { if ( !monitoredFiles.containsKey( file ) ) { if ( isSoleStyle ) { soleStyleFiles.add( file.getName() ); } return load( layerName, file ); } return false; } @Override public void run() { for ( File f : monitoredFiles.keySet() ) { Pair<Long, String> pair = monitoredFiles.get( f ); if ( f.lastModified() != pair.first ) { LOG.debug( "Reloading style file '{}'", f ); load( pair.second, f ); } } } }
false
true
public void load( String layerName, XMLAdapter adapter, List<SLDStyleType> styles ) { for ( SLDStyleType sty : styles ) { try { File file = new File( adapter.resolve( sty.getFile() ).toURI() ); String namedLayer = sty.getNamedLayer(); LOG.debug( "Will read styles from SLD '{}', for named layer '{}'.", file, namedLayer ); Map<String, String> map = new HashMap<String, String>(); String name = null; for ( JAXBElement<String> elem : sty.getNameAndUserStyleAndLegendConfigurationFile() ) { // TODO sth w/ the legend file if ( elem.getName().getLocalPart().equals( "Name" ) ) { name = elem.getValue(); } else { if ( name == null ) { name = elem.getValue(); } LOG.debug( "Will load user style with name '{}', it will be known as '{}'.", elem.getValue(), name ); map.put( elem.getValue(), name ); name = null; } } XMLInputFactory fac = XMLInputFactory.newInstance(); FileInputStream is = new FileInputStream( file ); XMLStreamReader in = fac.createXMLStreamReader( file.toURI().toURL().toString(), is ); Pair<LinkedList<Filter>, LinkedList<Style>> parsedStyles = getStyles( in, namedLayer, map ); for ( Style s : parsedStyles.second ) { put( layerName, s, false ); } is.close(); } catch ( MalformedURLException e ) { LOG.trace( "Stack trace", e ); LOG.info( "Style file '{}' for layer '{}' could not be resolved.", sty.getFile(), layerName ); } catch ( FileNotFoundException e ) { LOG.trace( "Stack trace", e ); LOG.info( "Style file '{}' for layer '{}' could not be found.", sty.getFile(), layerName ); } catch ( XMLStreamException e ) { LOG.trace( "Stack trace", e ); LOG.info( "Style file '{}' for layer '{}' could not be parsed: '{}'.", new Object[] { sty.getFile(), layerName, e.getLocalizedMessage() } ); } catch ( URISyntaxException e ) { LOG.trace( "Stack trace", e ); LOG.info( "Style file '{}' for layer '{}' could not be resolved.", sty.getFile(), layerName ); } catch ( IOException e ) { LOG.trace( "Stack trace", e ); LOG.info( "Style file '{}' for layer '{}' could not be closed: '{}'.", new Object[] { sty.getFile(), layerName, e.getLocalizedMessage() } ); } } }
public void load( String layerName, XMLAdapter adapter, List<SLDStyleType> styles ) { for ( SLDStyleType sty : styles ) { try { File file = new File( adapter.resolve( sty.getFile() ).toURI() ); String namedLayer = sty.getNamedLayer(); LOG.debug( "Will read styles from SLD '{}', for named layer '{}'.", file, namedLayer ); Map<String, String> map = new HashMap<String, String>(); String name = null; for ( JAXBElement<String> elem : sty.getNameAndUserStyleAndLegendConfigurationFile() ) { if ( elem.getName().getLocalPart().equals( "Name" ) ) { name = elem.getValue(); } else if ( elem.getName().getLocalPart().equals( "LegendConfigurationFile" ) ) { LOG.debug( "Reading {} as legend configuration file.", elem.getValue() ); File legendFile = new File( adapter.resolve( elem.getValue() ).toURI() ); Style style = loadNoImport( layerName, legendFile ); if ( style != null ) { if ( name != null ) { style.setName( name ); } putLegend( layerName, style, false ); } } else if ( elem.getName().getLocalPart().equals( "UserStyle" ) ) { if ( name == null ) { name = elem.getValue(); } LOG.debug( "Will load user style with name '{}', it will be known as '{}'.", elem.getValue(), name ); map.put( elem.getValue(), name ); name = null; } } XMLInputFactory fac = XMLInputFactory.newInstance(); FileInputStream is = new FileInputStream( file ); XMLStreamReader in = fac.createXMLStreamReader( file.toURI().toURL().toString(), is ); Pair<LinkedList<Filter>, LinkedList<Style>> parsedStyles = getStyles( in, namedLayer, map ); for ( Style s : parsedStyles.second ) { put( layerName, s, false ); } is.close(); } catch ( MalformedURLException e ) { LOG.trace( "Stack trace", e ); LOG.info( "Style file '{}' for layer '{}' could not be resolved.", sty.getFile(), layerName ); } catch ( FileNotFoundException e ) { LOG.trace( "Stack trace", e ); LOG.info( "Style file '{}' for layer '{}' could not be found.", sty.getFile(), layerName ); } catch ( XMLStreamException e ) { LOG.trace( "Stack trace", e ); LOG.info( "Style file '{}' for layer '{}' could not be parsed: '{}'.", new Object[] { sty.getFile(), layerName, e.getLocalizedMessage() } ); } catch ( URISyntaxException e ) { LOG.trace( "Stack trace", e ); LOG.info( "Style file '{}' for layer '{}' could not be resolved.", sty.getFile(), layerName ); } catch ( IOException e ) { LOG.trace( "Stack trace", e ); LOG.info( "Style file '{}' for layer '{}' could not be closed: '{}'.", new Object[] { sty.getFile(), layerName, e.getLocalizedMessage() } ); } } }
diff --git a/net/sf/mpxj/mpp/CompObj.java b/net/sf/mpxj/mpp/CompObj.java index cb678b8..a16bd30 100644 --- a/net/sf/mpxj/mpp/CompObj.java +++ b/net/sf/mpxj/mpp/CompObj.java @@ -1,110 +1,113 @@ /* * file: CompObj.java * author: Jon Iles * copyright: (c) Tapster Rock Limited 2002-2003 * date: 07/01/2003 */ /* * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation; either version 2.1 of the License, or (at your * option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ package net.sf.mpxj.mpp; import java.io.InputStream; import java.io.IOException; /** * This class handles reading the data found in the CompObj block * of an MPP file. The bits we can decypher allow us to determine * the file format. */ final class CompObj extends MPPComponent { /** * Constructor. Reads and processes the block data. * * @param is input stream * @throws IOException on read failure */ CompObj (InputStream is) throws IOException { int length; is.skip(28); length = readInt(is); m_applicationName = new String (readByteArray(is, length), 0, length-1); if (m_applicationName != null && m_applicationName.equals("Microsoft Project 4.0") == true) { m_fileFormat = "MSProject.MPP4"; m_applicationID = "MSProject.Project.4"; } else { length = readInt(is); m_fileFormat = new String (readByteArray(is, length), 0, length-1); length = readInt(is); - m_applicationID = new String (readByteArray(is, length), 0, length-1); + if (length > 0) + { + m_applicationID = new String (readByteArray(is, length), 0, length-1); + } } } /** * Accessor method to retrieve the application name. * * @return Name of the application */ public String getApplicationName () { return (m_applicationName); } /** * Accessor method to retrieve the application ID. * * @return Application ID */ public String getApplicationID () { return (m_applicationID); } /** * Accessor method to retrieve the file format. * * @return File format */ public String getFileFormat () { return (m_fileFormat); } /** * Application name. */ private String m_applicationName; /** * Application identifier. */ private String m_applicationID; /** * File format. */ private String m_fileFormat; }
true
true
CompObj (InputStream is) throws IOException { int length; is.skip(28); length = readInt(is); m_applicationName = new String (readByteArray(is, length), 0, length-1); if (m_applicationName != null && m_applicationName.equals("Microsoft Project 4.0") == true) { m_fileFormat = "MSProject.MPP4"; m_applicationID = "MSProject.Project.4"; } else { length = readInt(is); m_fileFormat = new String (readByteArray(is, length), 0, length-1); length = readInt(is); m_applicationID = new String (readByteArray(is, length), 0, length-1); } }
CompObj (InputStream is) throws IOException { int length; is.skip(28); length = readInt(is); m_applicationName = new String (readByteArray(is, length), 0, length-1); if (m_applicationName != null && m_applicationName.equals("Microsoft Project 4.0") == true) { m_fileFormat = "MSProject.MPP4"; m_applicationID = "MSProject.Project.4"; } else { length = readInt(is); m_fileFormat = new String (readByteArray(is, length), 0, length-1); length = readInt(is); if (length > 0) { m_applicationID = new String (readByteArray(is, length), 0, length-1); } } }
diff --git a/src/zapfmaster2000-service/src/main/java/de/kile/zapfmaster2000/rest/impl/core/push/PushServiceImpl.java b/src/zapfmaster2000-service/src/main/java/de/kile/zapfmaster2000/rest/impl/core/push/PushServiceImpl.java index 9b412425..5d056dd5 100644 --- a/src/zapfmaster2000-service/src/main/java/de/kile/zapfmaster2000/rest/impl/core/push/PushServiceImpl.java +++ b/src/zapfmaster2000-service/src/main/java/de/kile/zapfmaster2000/rest/impl/core/push/PushServiceImpl.java @@ -1,444 +1,445 @@ package de.kile.zapfmaster2000.rest.impl.core.push; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.StringRequestEntity; import org.apache.log4j.Logger; import org.codehaus.jackson.JsonFactory; import org.codehaus.jackson.JsonGenerationException; import org.codehaus.jackson.JsonGenerator; import org.codehaus.jackson.JsonProcessingException; import org.hibernate.Session; import org.hibernate.Transaction; import org.jboss.resteasy.spi.AsynchronousResponse; import com.google.gson.Gson; import de.kile.zapfmaster2000.rest.api.news.AbstractNewsResponse; import de.kile.zapfmaster2000.rest.api.push.DrawDraftKitResponse; import de.kile.zapfmaster2000.rest.api.push.LoginDraftKitResponse; import de.kile.zapfmaster2000.rest.api.push.LogoutDraftKitResponse; import de.kile.zapfmaster2000.rest.core.Zapfmaster2000Core; import de.kile.zapfmaster2000.rest.core.box.BoxService; import de.kile.zapfmaster2000.rest.core.box.BoxServiceListener; import de.kile.zapfmaster2000.rest.core.box.LoginFailureReason; import de.kile.zapfmaster2000.rest.core.challenge.ChallengeService; import de.kile.zapfmaster2000.rest.core.challenge.ChallengeServiceListener; import de.kile.zapfmaster2000.rest.core.news.NewsService; import de.kile.zapfmaster2000.rest.core.news.NewsServiceListener; import de.kile.zapfmaster2000.rest.core.push.PushService; import de.kile.zapfmaster2000.rest.core.util.NewsAdapter; import de.kile.zapfmaster2000.rest.model.zapfmaster2000.Account; import de.kile.zapfmaster2000.rest.model.zapfmaster2000.Box; import de.kile.zapfmaster2000.rest.model.zapfmaster2000.Challenge; import de.kile.zapfmaster2000.rest.model.zapfmaster2000.Challenge1v1; import de.kile.zapfmaster2000.rest.model.zapfmaster2000.Drawing; import de.kile.zapfmaster2000.rest.model.zapfmaster2000.News; import de.kile.zapfmaster2000.rest.model.zapfmaster2000.User; import de.kile.zapfmaster2000.rest.model.zapfmaster2000.Zapfmaster2000Package; public class PushServiceImpl implements PushService { private static final Logger LOGGER = Logger .getLogger(PushServiceImpl.class); /** pending responses for news pushs: AccountId -> PushQueue */ private final Map<Long, PushQueue> pendingNewsResponses = new HashMap<>(); /** pending responses for draft kit pushs: BoxId -> PushQueue */ private final Map<Long, PushQueue> pendingDraftKitReponses = new HashMap<>(); /** pending reponses for challenge pushs: UserId -> PushQueue */ private final Map<Long, PushQueue> pendingChallengeResponses = new HashMap<>(); /** pending responses for unknown rfid tag pushes: BoxId -> PushQueue */ private final Map<Long, PushQueue> pendingUnkownRfidResponses = new HashMap<>(); public PushServiceImpl(NewsService pNewsService, BoxService pBoxService, ChallengeService pChallengeService) { pNewsService.addListener(createNewsListener()); pBoxService.addListener(createBoxServiceListener()); pChallengeService.addListener(createChallengeServiceListener()); } @Override public void addNewsRequest(AsynchronousResponse pResponse, Account pAccount, String pToken) { if (!pendingNewsResponses.containsKey(pAccount.getId())) { PushQueue queue = new PushQueue(); pendingNewsResponses.put(pAccount.getId(), queue); } PushQueue queue = pendingNewsResponses.get(pAccount.getId()); assert (queue != null); queue.addRequest(pResponse); } @Override public void addDraftkitRequest(AsynchronousResponse pResponse, Box pBox, String pToken) { if (!pendingDraftKitReponses.containsKey(pBox.getId())) { PushQueue queue = new PushQueue(); pendingDraftKitReponses.put(pBox.getId(), queue); } PushQueue queue = pendingDraftKitReponses.get(pBox.getId()); assert (queue != null); queue.addRequest(pResponse); } @Override public void addChallengeRequest(AsynchronousResponse pResponse, User pUser) { if (!pendingChallengeResponses.containsKey(pUser.getId())) { PushQueue queue = new PushQueue(); pendingChallengeResponses.put(pUser.getId(), queue); } PushQueue queue = pendingChallengeResponses.get(pUser.getId()); assert (queue != null); queue.addRequest(pResponse); } @Override public void addUnkownRfidRequest(AsynchronousResponse pResponse, Box pBox) { if (!pendingUnkownRfidResponses.containsKey(pBox.getId())) { PushQueue queue = new PushQueue(); pendingUnkownRfidResponses.put(pBox.getId(), queue); } PushQueue queue = pendingUnkownRfidResponses.get(pBox.getId()); assert (queue != null); queue.addRequest(pResponse); } private NewsServiceListener createNewsListener() { return new NewsServiceListener() { @Override public void onNewsPosted(News pNews) { pushNews(pNews); } }; } private BoxServiceListener createBoxServiceListener() { return new BoxServiceListener() { @Override public void onLogout(Box pBox, User pUser) { pushLogout(pBox); } @Override public void onLoginsuccessful(Box pBox, User pUser) { pushLogin(pBox, pUser); } @Override public void onEndDrawing(Box pBox, Drawing pDrawing) { } @Override public void onDrawing(Box pBox, User pUser, double pAmount) { pushDrawing(pBox, pUser, pAmount); } @Override public void onLoginFailed(Box pBox, LoginFailureReason pReason, long pTag) { if (pReason == LoginFailureReason.INVALID_RFID_TAG) { pushInvalidRfidTag(pBox, pTag); } } }; } private ChallengeServiceListener createChallengeServiceListener() { return new ChallengeServiceListener() { @Override public void onPendingChallengeCreated(Challenge pChallenge) { pushPendingChallenge(pChallenge); } @Override public void onChallengeStarted(Challenge pChallenge) { pushChallengeStarted(pChallenge); } @Override public void onChallengeFinished(Challenge pChallenge) { } @Override public void onChallengeDeclined(Challenge pChallenge) { pushChallengeDeclined(pChallenge); } }; } private void pushNews(News pNews) { Account account = pNews.getAccount(); if (pendingNewsResponses.containsKey(account.getId())) { AbstractNewsResponse news = new NewsAdapter().adapt(pNews); Response response = Response.ok(news) .type(MediaType.APPLICATION_JSON).build(); PushQueue queue = pendingNewsResponses.get(account.getId()); queue.push(response, true); } } private void pushLogin(Box pBox, User pUser) { if (pendingDraftKitReponses.containsKey(pBox.getId())) { LoginDraftKitResponse entity = new LoginDraftKitResponse(); entity.setBoxId(pBox.getId()); entity.setImagePath(pUser.getImagePath()); entity.setUserId(pUser.getId()); entity.setUserName(pUser.getName()); Response response = Response.ok(entity) .type(MediaType.APPLICATION_JSON).build(); PushQueue queue = pendingDraftKitReponses.get(pBox.getId()); queue.push(response, true); } } private void pushDrawing(Box pBox, User pUser, double pAmount) { if (pendingDraftKitReponses.containsKey(pBox.getId())) { DrawDraftKitResponse entity = new DrawDraftKitResponse(); entity.setBoxId(pBox.getId()); entity.setImagePath(pUser.getImagePath()); entity.setUserId(pUser.getId()); entity.setUserName(pUser.getName()); entity.setAmount(pAmount); Response response = Response.ok(entity) .type(MediaType.APPLICATION_JSON).build(); PushQueue queue = pendingDraftKitReponses.get(pBox.getId()); queue.push(response, false); } } private void pushLogout(Box pBox) { if (pendingDraftKitReponses.containsKey(pBox.getId())) { LogoutDraftKitResponse entity = new LogoutDraftKitResponse(); entity.setBoxId(pBox.getId()); Response response = Response.ok(entity) .type(MediaType.APPLICATION_JSON).build(); PushQueue queue = pendingDraftKitReponses.get(pBox.getId()); queue.push(response, true); } } private void pushPendingChallenge(Challenge pChallenge) { if (pChallenge instanceof Challenge1v1) { Challenge1v1 challenge1v1 = (Challenge1v1) pChallenge; User challengee = challenge1v1.getUser2(); ChallengeRequestResponse entity = new ChallengeRequestResponse(); User challenger = challenge1v1.getUser1(); entity.setChallengerUserName(challenger.getName()); entity.setChallengerImagePath(challenger.getImagePath()); entity.setChallengerUserId(challenger.getId()); entity.setChallengeId(challenge1v1.getId()); // send via reverse ajax if (pendingChallengeResponses.containsKey(challengee.getId())) { PushQueue queue = pendingChallengeResponses.get(challengee .getId()); Response response = Response.ok(entity).build(); queue.push(response, true); } // send via gcm sendViaGcm(entity, challengee.getId()); } } private void sendViaGcm(Object entity, Long... userIds) { // collect the gcm tokens we want to send the entity to Session session = Zapfmaster2000Core.INSTANCE.getTransactionService() .getSessionFactory().getCurrentSession(); Transaction tx = session.beginTransaction(); Set<String> gcmTokens = new HashSet<>(); for (Long userId : userIds) { @SuppressWarnings("unchecked") List<String> result = session .createQuery( "SELECT t.googleCloudMessagingToken From Token t " + "WHERE t.user IS NOT NULL AND t.user.id = :userId " + "AND t.googleCloudMessagingToken IS NOT NULL") .setLong("userId", userId).list(); gcmTokens.addAll(result); } tx.commit(); if (!gcmTokens.isEmpty()) { HttpClient httpclient = new HttpClient(); PostMethod post = new PostMethod( "https://android.googleapis.com/gcm/send"); // convert entity to json ByteArrayOutputStream os = new ByteArrayOutputStream(); JsonFactory factory = new JsonFactory(); try { JsonGenerator jsonGenerator = factory.createJsonGenerator(os); jsonGenerator.writeStartObject(); jsonGenerator.writeFieldName("registration_ids"); jsonGenerator.writeStartArray(); for (String gcmToken : gcmTokens) { jsonGenerator.writeString(gcmToken); } jsonGenerator.writeEndArray(); jsonGenerator.writeFieldName("data"); - jsonGenerator.writeString(new Gson().toJson(entity)); + jsonGenerator.writeRaw(new Gson().toJson(entity)); jsonGenerator.writeEndObject(); + jsonGenerator.flush(); String json = os.toString(); - LOGGER.trace("Created json" + json); + LOGGER.debug("Created json" + json); post.setRequestHeader("Content-Length", Integer.toString(json.length())); post.setRequestHeader("Content-Type", "application/json"); post.setRequestHeader("Authorization", "key=AIzaSyAzFGj3pOuMyhQq9udWWplVbWMQFKMuS1g"); post.setRequestEntity(new StringRequestEntity(json, "application/json", null)); try { httpclient.executeMethod(post); - LOGGER.trace("gcm returned: " + post.getStatusLine()); + LOGGER.debug("gcm returned: " + post.getStatusLine()); } finally { post.releaseConnection(); } } catch (JsonGenerationException e) { LOGGER.error("Could not generate json", e); } catch (JsonProcessingException e) { LOGGER.error("Could not generate json", e); } catch (IOException e) { LOGGER.error("Could not generate json", e); } } } void pushChallengeStarted(Challenge pChallenge) { if (pChallenge instanceof Challenge1v1) { Challenge1v1 challenge1v1 = (Challenge1v1) pChallenge; Session session = Zapfmaster2000Core.INSTANCE .getTransactionService().getSessionFactory() .getCurrentSession(); Transaction tx = session.beginTransaction(); pChallenge = (Challenge) session.load( Zapfmaster2000Package.eINSTANCE.getChallenge().getName(), pChallenge.getId()); ChallengeAcceptedReponse entity = new ChallengeAcceptedReponse(); entity.setUser1Id(challenge1v1.getUser1().getId()); entity.setUser1Name(challenge1v1.getUser1().getName()); entity.setUser2Id(challenge1v1.getUser2().getId()); entity.setUser2Name(challenge1v1.getUser2().getName()); tx.commit(); Response response = Response.ok(entity).build(); // send via revese ajax if (pendingChallengeResponses.containsKey(challenge1v1.getUser1() .getId())) { PushQueue queue = pendingChallengeResponses.get(challenge1v1 .getUser1().getId()); queue.push(response, true); } if (pendingChallengeResponses.containsKey(challenge1v1.getUser2() .getId())) { PushQueue queue = pendingChallengeResponses.get(challenge1v1 .getUser2().getId()); queue.push(response, true); } // send via gcm sendViaGcm(entity, challenge1v1.getUser1().getId(), challenge1v1 .getUser2().getId()); } } private void pushChallengeDeclined(Challenge pChallenge) { if (pChallenge instanceof Challenge1v1) { Challenge1v1 challenge1v1 = (Challenge1v1) pChallenge; Session session = Zapfmaster2000Core.INSTANCE .getTransactionService().getSessionFactory() .getCurrentSession(); Transaction tx = session.beginTransaction(); pChallenge = (Challenge) session.load( Zapfmaster2000Package.eINSTANCE.getChallenge().getName(), pChallenge.getId()); ChallengeDeclinedReponse entity = new ChallengeDeclinedReponse(); entity.setUser1Id(challenge1v1.getUser1().getId()); entity.setUser1Name(challenge1v1.getUser1().getName()); entity.setUser2Id(challenge1v1.getUser2().getId()); entity.setUser2Name(challenge1v1.getUser2().getName()); tx.commit(); Response response = Response.ok(entity).build(); // send via reverse ajax if (pendingChallengeResponses.containsKey(challenge1v1.getUser1() .getId())) { PushQueue queue = pendingChallengeResponses.get(challenge1v1 .getUser1().getId()); queue.push(response, true); } if (pendingChallengeResponses.containsKey(challenge1v1.getUser2() .getId())) { PushQueue queue = pendingChallengeResponses.get(challenge1v1 .getUser2().getId()); queue.push(response, true); } // send via gcm sendViaGcm(entity, challenge1v1.getUser1().getId(), challenge1v1 .getUser2().getId()); } } private void pushInvalidRfidTag(Box pBox, long pTag) { if (pendingUnkownRfidResponses.containsKey(pBox.getId())) { PushQueue queue = pendingUnkownRfidResponses.get(pBox.getId()); Response response = Response.ok(pTag).build(); queue.push(response, false); } // else nobody cares } }
false
true
private void sendViaGcm(Object entity, Long... userIds) { // collect the gcm tokens we want to send the entity to Session session = Zapfmaster2000Core.INSTANCE.getTransactionService() .getSessionFactory().getCurrentSession(); Transaction tx = session.beginTransaction(); Set<String> gcmTokens = new HashSet<>(); for (Long userId : userIds) { @SuppressWarnings("unchecked") List<String> result = session .createQuery( "SELECT t.googleCloudMessagingToken From Token t " + "WHERE t.user IS NOT NULL AND t.user.id = :userId " + "AND t.googleCloudMessagingToken IS NOT NULL") .setLong("userId", userId).list(); gcmTokens.addAll(result); } tx.commit(); if (!gcmTokens.isEmpty()) { HttpClient httpclient = new HttpClient(); PostMethod post = new PostMethod( "https://android.googleapis.com/gcm/send"); // convert entity to json ByteArrayOutputStream os = new ByteArrayOutputStream(); JsonFactory factory = new JsonFactory(); try { JsonGenerator jsonGenerator = factory.createJsonGenerator(os); jsonGenerator.writeStartObject(); jsonGenerator.writeFieldName("registration_ids"); jsonGenerator.writeStartArray(); for (String gcmToken : gcmTokens) { jsonGenerator.writeString(gcmToken); } jsonGenerator.writeEndArray(); jsonGenerator.writeFieldName("data"); jsonGenerator.writeString(new Gson().toJson(entity)); jsonGenerator.writeEndObject(); String json = os.toString(); LOGGER.trace("Created json" + json); post.setRequestHeader("Content-Length", Integer.toString(json.length())); post.setRequestHeader("Content-Type", "application/json"); post.setRequestHeader("Authorization", "key=AIzaSyAzFGj3pOuMyhQq9udWWplVbWMQFKMuS1g"); post.setRequestEntity(new StringRequestEntity(json, "application/json", null)); try { httpclient.executeMethod(post); LOGGER.trace("gcm returned: " + post.getStatusLine()); } finally { post.releaseConnection(); } } catch (JsonGenerationException e) { LOGGER.error("Could not generate json", e); } catch (JsonProcessingException e) { LOGGER.error("Could not generate json", e); } catch (IOException e) { LOGGER.error("Could not generate json", e); } } }
private void sendViaGcm(Object entity, Long... userIds) { // collect the gcm tokens we want to send the entity to Session session = Zapfmaster2000Core.INSTANCE.getTransactionService() .getSessionFactory().getCurrentSession(); Transaction tx = session.beginTransaction(); Set<String> gcmTokens = new HashSet<>(); for (Long userId : userIds) { @SuppressWarnings("unchecked") List<String> result = session .createQuery( "SELECT t.googleCloudMessagingToken From Token t " + "WHERE t.user IS NOT NULL AND t.user.id = :userId " + "AND t.googleCloudMessagingToken IS NOT NULL") .setLong("userId", userId).list(); gcmTokens.addAll(result); } tx.commit(); if (!gcmTokens.isEmpty()) { HttpClient httpclient = new HttpClient(); PostMethod post = new PostMethod( "https://android.googleapis.com/gcm/send"); // convert entity to json ByteArrayOutputStream os = new ByteArrayOutputStream(); JsonFactory factory = new JsonFactory(); try { JsonGenerator jsonGenerator = factory.createJsonGenerator(os); jsonGenerator.writeStartObject(); jsonGenerator.writeFieldName("registration_ids"); jsonGenerator.writeStartArray(); for (String gcmToken : gcmTokens) { jsonGenerator.writeString(gcmToken); } jsonGenerator.writeEndArray(); jsonGenerator.writeFieldName("data"); jsonGenerator.writeRaw(new Gson().toJson(entity)); jsonGenerator.writeEndObject(); jsonGenerator.flush(); String json = os.toString(); LOGGER.debug("Created json" + json); post.setRequestHeader("Content-Length", Integer.toString(json.length())); post.setRequestHeader("Content-Type", "application/json"); post.setRequestHeader("Authorization", "key=AIzaSyAzFGj3pOuMyhQq9udWWplVbWMQFKMuS1g"); post.setRequestEntity(new StringRequestEntity(json, "application/json", null)); try { httpclient.executeMethod(post); LOGGER.debug("gcm returned: " + post.getStatusLine()); } finally { post.releaseConnection(); } } catch (JsonGenerationException e) { LOGGER.error("Could not generate json", e); } catch (JsonProcessingException e) { LOGGER.error("Could not generate json", e); } catch (IOException e) { LOGGER.error("Could not generate json", e); } } }
diff --git a/src/de/schildbach/pte/AbstractHafasProvider.java b/src/de/schildbach/pte/AbstractHafasProvider.java index 9836e974..3413a936 100644 --- a/src/de/schildbach/pte/AbstractHafasProvider.java +++ b/src/de/schildbach/pte/AbstractHafasProvider.java @@ -1,888 +1,890 @@ /* * Copyright 2010 the original author or authors. * * 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 de.schildbach.pte; import java.io.IOException; import java.io.InputStream; import java.net.SocketTimeoutException; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlPullParserFactory; import de.schildbach.pte.dto.Connection; import de.schildbach.pte.dto.GetConnectionDetailsResult; import de.schildbach.pte.dto.Location; import de.schildbach.pte.dto.LocationType; import de.schildbach.pte.dto.NearbyStationsResult; import de.schildbach.pte.dto.QueryConnectionsResult; import de.schildbach.pte.dto.Station; import de.schildbach.pte.util.Color; import de.schildbach.pte.util.ParserUtils; import de.schildbach.pte.util.XmlPullUtil; /** * @author Andreas Schildbach */ public abstract class AbstractHafasProvider implements NetworkProvider { private static final String DEFAULT_ENCODING = "ISO-8859-1"; private final String apiUri; private static final String prod = "hafas"; private final String accessId; public AbstractHafasProvider(final String apiUri, final String accessId) { this.apiUri = apiUri; this.accessId = accessId; } private final String wrap(final String request) { return "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>" // + "<ReqC ver=\"1.1\" prod=\"" + prod + "\" lang=\"DE\"" + (accessId != null ? " accessId=\"" + accessId + "\"" : "") + ">" // + request // + "</ReqC>"; } private static final Location parseStation(final XmlPullParser pp) { final String type = pp.getName(); if ("Station".equals(type)) { final String name = pp.getAttributeValue(null, "name").trim(); final int id = Integer.parseInt(pp.getAttributeValue(null, "externalStationNr")); final int x = Integer.parseInt(pp.getAttributeValue(null, "x")); final int y = Integer.parseInt(pp.getAttributeValue(null, "y")); return new Location(LocationType.STATION, id, y, x, name); } throw new IllegalStateException("cannot handle: " + type); } private static final Location parsePoi(final XmlPullParser pp) { final String type = pp.getName(); if ("Poi".equals(type)) { String name = pp.getAttributeValue(null, "name").trim(); if (name.equals("unknown")) name = null; final int x = Integer.parseInt(pp.getAttributeValue(null, "x")); final int y = Integer.parseInt(pp.getAttributeValue(null, "y")); return new Location(LocationType.POI, 0, y, x, name); } throw new IllegalStateException("cannot handle: " + type); } private static final Location parseAddress(final XmlPullParser pp) { final String type = pp.getName(); if ("Address".equals(type)) { String name = pp.getAttributeValue(null, "name").trim(); if (name.equals("unknown")) name = null; final int x = Integer.parseInt(pp.getAttributeValue(null, "x")); final int y = Integer.parseInt(pp.getAttributeValue(null, "y")); return new Location(LocationType.ADDRESS, 0, y, x, name); } throw new IllegalStateException("cannot handle: " + type); } private static final Location parseReqLoc(final XmlPullParser pp) { final String type = pp.getName(); if ("ReqLoc".equals(type)) { XmlPullUtil.requireAttr(pp, "type", "ADR"); final String name = pp.getAttributeValue(null, "output").trim(); return new Location(LocationType.ADDRESS, 0, 0, 0, name); } throw new IllegalStateException("cannot handle: " + type); } public List<Location> autocompleteStations(final CharSequence constraint) throws IOException { final String request = "<LocValReq id=\"req\" maxNr=\"20\"><ReqLoc match=\"" + constraint + "\" type=\"ALLTYPE\"/></LocValReq>"; // System.out.println(ParserUtils.scrape(apiUri, true, wrap(request), null, false)); InputStream is = null; try { is = ParserUtils.scrapeInputStream(apiUri, wrap(request)); final List<Location> results = new ArrayList<Location>(); final XmlPullParserFactory factory = XmlPullParserFactory.newInstance(System.getProperty(XmlPullParserFactory.PROPERTY_NAME), null); final XmlPullParser pp = factory.newPullParser(); pp.setInput(is, DEFAULT_ENCODING); assertResC(pp); XmlPullUtil.enter(pp); XmlPullUtil.require(pp, "LocValRes"); XmlPullUtil.requireAttr(pp, "id", "req"); XmlPullUtil.enter(pp); while (pp.getEventType() == XmlPullParser.START_TAG) { final String tag = pp.getName(); if ("Station".equals(tag)) results.add(parseStation(pp)); else if ("Poi".equals(tag)) results.add(parsePoi(pp)); else if ("Address".equals(tag)) results.add(parseAddress(pp)); else if ("ReqLoc".equals(tag)) /* results.add(parseReqLoc(pp)) */; else System.out.println("cannot handle tag: " + tag); XmlPullUtil.next(pp); } XmlPullUtil.exit(pp); return results; } catch (final XmlPullParserException x) { throw new RuntimeException(x); } catch (final SocketTimeoutException x) { throw new RuntimeException(x); } finally { if (is != null) is.close(); } } public QueryConnectionsResult queryConnections(Location from, Location via, Location to, final Date date, final boolean dep, final String products, final WalkSpeed walkSpeed) throws IOException { if (from.type == LocationType.ANY) { final List<Location> autocompletes = autocompleteStations(from.name); if (autocompletes.isEmpty()) return new QueryConnectionsResult(QueryConnectionsResult.Status.NO_CONNECTIONS); // TODO if (autocompletes.size() > 1) return new QueryConnectionsResult(autocompletes, null, null); from = autocompletes.get(0); } if (via != null && via.type == LocationType.ANY) { final List<Location> autocompletes = autocompleteStations(via.name); if (autocompletes.isEmpty()) return new QueryConnectionsResult(QueryConnectionsResult.Status.NO_CONNECTIONS); // TODO if (autocompletes.size() > 1) return new QueryConnectionsResult(null, autocompletes, null); via = autocompletes.get(0); } if (to.type == LocationType.ANY) { final List<Location> autocompletes = autocompleteStations(to.name); if (autocompletes.isEmpty()) return new QueryConnectionsResult(QueryConnectionsResult.Status.NO_CONNECTIONS); // TODO if (autocompletes.size() > 1) return new QueryConnectionsResult(null, null, autocompletes); to = autocompletes.get(0); } final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyyMMdd"); final DateFormat TIME_FORMAT = new SimpleDateFormat("HH:mm"); final String request = "<ConReq>" // + "<Start>" + location(from) + "<Prod bike=\"0\" couchette=\"0\" direct=\"0\" sleeper=\"0\"/></Start>" // + (via != null ? "<Via>" + location(via) + "</Via>" : "") // + "<Dest>" + location(to) + "</Dest>" // + "<ReqT a=\"" + (dep ? 0 : 1) + "\" date=\"" + DATE_FORMAT.format(date) + "\" time=\"" + TIME_FORMAT.format(date) + "\"/>" // + "<RFlags b=\"0\" chExtension=\"0\" f=\"4\" sMode=\"N\"/>" // + "</ConReq>"; // System.out.println(request); // System.out.println(ParserUtils.scrape(apiUri, true, wrap(request), null, false)); InputStream is = null; try { is = ParserUtils.scrapeInputStream(apiUri, wrap(request)); final XmlPullParserFactory factory = XmlPullParserFactory.newInstance(System.getProperty(XmlPullParserFactory.PROPERTY_NAME), null); final XmlPullParser pp = factory.newPullParser(); pp.setInput(is, DEFAULT_ENCODING); assertResC(pp); XmlPullUtil.enter(pp); XmlPullUtil.require(pp, "ConRes"); XmlPullUtil.enter(pp); if (pp.getName().equals("Err")) { final String code = XmlPullUtil.attr(pp, "code"); if (code.equals("K9380")) return QueryConnectionsResult.TOO_CLOSE; if (code.equals("K9220")) // Nearby to the given address stations could not be found return QueryConnectionsResult.NO_CONNECTIONS; if (code.equals("K890")) // No connections found return QueryConnectionsResult.NO_CONNECTIONS; throw new IllegalStateException("error " + code + " " + XmlPullUtil.attr(pp, "text")); } XmlPullUtil.require(pp, "ConResCtxt"); final String sessionId = XmlPullUtil.text(pp); XmlPullUtil.require(pp, "ConnectionList"); XmlPullUtil.enter(pp); final List<Connection> connections = new ArrayList<Connection>(); while (XmlPullUtil.test(pp, "Connection")) { final String id = XmlPullUtil.attr(pp, "id"); XmlPullUtil.enter(pp); while (pp.getName().equals("RtStateList")) XmlPullUtil.next(pp); XmlPullUtil.require(pp, "Overview"); XmlPullUtil.enter(pp); XmlPullUtil.require(pp, "Date"); final Calendar currentDate = new GregorianCalendar(); currentDate.setTime(DATE_FORMAT.parse(XmlPullUtil.text(pp))); XmlPullUtil.exit(pp); XmlPullUtil.require(pp, "ConSectionList"); XmlPullUtil.enter(pp); final List<Connection.Part> parts = new ArrayList<Connection.Part>(4); Date firstDepartureTime = null; Date lastArrivalTime = null; while (XmlPullUtil.test(pp, "ConSection")) { XmlPullUtil.enter(pp); // departure XmlPullUtil.require(pp, "Departure"); XmlPullUtil.enter(pp); XmlPullUtil.require(pp, "BasicStop"); XmlPullUtil.enter(pp); while (pp.getName().equals("StAttrList")) XmlPullUtil.next(pp); Location departure; if (pp.getName().equals("Station")) departure = parseStation(pp); else if (pp.getName().equals("Poi")) departure = parsePoi(pp); + else if (pp.getName().equals("Address")) + departure = parseAddress(pp); else throw new IllegalStateException("cannot parse: " + pp.getName()); XmlPullUtil.next(pp); XmlPullUtil.require(pp, "Dep"); XmlPullUtil.enter(pp); XmlPullUtil.require(pp, "Time"); final Date departureTime = parseTime(currentDate, XmlPullUtil.text(pp)); XmlPullUtil.require(pp, "Platform"); XmlPullUtil.enter(pp); XmlPullUtil.require(pp, "Text"); String departurePos = XmlPullUtil.text(pp).trim(); if (departurePos.length() == 0) departurePos = null; XmlPullUtil.exit(pp); XmlPullUtil.exit(pp); XmlPullUtil.exit(pp); XmlPullUtil.exit(pp); // journey String line = null; String direction = null; int min = 0; final String tag = pp.getName(); if (tag.equals("Journey")) { XmlPullUtil.enter(pp); while (pp.getName().equals("JHandle")) XmlPullUtil.next(pp); XmlPullUtil.require(pp, "JourneyAttributeList"); XmlPullUtil.enter(pp); String name = null; String category = null; String longCategory = null; while (XmlPullUtil.test(pp, "JourneyAttribute")) { XmlPullUtil.enter(pp); XmlPullUtil.require(pp, "Attribute"); final String attrName = XmlPullUtil.attr(pp, "type"); XmlPullUtil.enter(pp); final Map<String, String> attributeVariants = parseAttributeVariants(pp); XmlPullUtil.exit(pp); XmlPullUtil.exit(pp); if ("NAME".equals(attrName)) { name = attributeVariants.get("NORMAL"); } else if ("CATEGORY".equals(attrName)) { category = attributeVariants.get("NORMAL"); longCategory = attributeVariants.get("LONG"); } else if ("DIRECTION".equals(attrName)) { direction = attributeVariants.get("NORMAL"); } } XmlPullUtil.exit(pp); XmlPullUtil.exit(pp); line = _normalizeLine(category, name, longCategory); } else if (tag.equals("Walk") || tag.equals("Transfer") || tag.equals("GisRoute")) { XmlPullUtil.enter(pp); XmlPullUtil.require(pp, "Duration"); XmlPullUtil.enter(pp); XmlPullUtil.require(pp, "Time"); min = parseDuration(XmlPullUtil.text(pp).substring(3, 8)); XmlPullUtil.exit(pp); XmlPullUtil.exit(pp); } else { throw new IllegalStateException("cannot handle: " + pp.getName()); } // arrival XmlPullUtil.require(pp, "Arrival"); XmlPullUtil.enter(pp); XmlPullUtil.require(pp, "BasicStop"); XmlPullUtil.enter(pp); while (pp.getName().equals("StAttrList")) XmlPullUtil.next(pp); Location arrival; if (pp.getName().equals("Station")) arrival = parseStation(pp); else if (pp.getName().equals("Poi")) arrival = parsePoi(pp); else if (pp.getName().equals("Address")) arrival = parseAddress(pp); else throw new IllegalStateException("cannot parse: " + pp.getName()); XmlPullUtil.next(pp); XmlPullUtil.require(pp, "Arr"); XmlPullUtil.enter(pp); XmlPullUtil.require(pp, "Time"); final Date arrivalTime = parseTime(currentDate, XmlPullUtil.text(pp)); XmlPullUtil.require(pp, "Platform"); XmlPullUtil.enter(pp); XmlPullUtil.require(pp, "Text"); String arrivalPos = XmlPullUtil.text(pp).trim(); if (arrivalPos.length() == 0) arrivalPos = null; XmlPullUtil.exit(pp); XmlPullUtil.exit(pp); XmlPullUtil.exit(pp); XmlPullUtil.exit(pp); XmlPullUtil.exit(pp); if (min == 0 || line != null) { parts.add(new Connection.Trip(line, lineColors(line), 0, direction, departureTime, departurePos, departure.id, departure.name, arrivalTime, arrivalPos, arrival.id, arrival.name)); } else { if (parts.size() > 0 && parts.get(parts.size() - 1) instanceof Connection.Footway) { final Connection.Footway lastFootway = (Connection.Footway) parts.remove(parts.size() - 1); parts.add(new Connection.Footway(lastFootway.min + min, lastFootway.departureId, lastFootway.departure, arrival.id, arrival.name)); } else { parts.add(new Connection.Footway(min, departure.id, departure.name, arrival.id, arrival.name)); } } if (firstDepartureTime == null) firstDepartureTime = departureTime; lastArrivalTime = arrivalTime; } XmlPullUtil.exit(pp); XmlPullUtil.exit(pp); connections.add(new Connection(id, null, firstDepartureTime, lastArrivalTime, null, null, 0, null, 0, null, parts)); } XmlPullUtil.exit(pp); return new QueryConnectionsResult(null, from, via, to, null, null, connections); } catch (final XmlPullParserException x) { throw new RuntimeException(x); } catch (final SocketTimeoutException x) { throw new RuntimeException(x); } catch (final ParseException x) { throw new RuntimeException(x); } finally { if (is != null) is.close(); } } private final Map<String, String> parseAttributeVariants(final XmlPullParser pp) throws XmlPullParserException, IOException { final Map<String, String> attributeVariants = new HashMap<String, String>(); while (XmlPullUtil.test(pp, "AttributeVariant")) { final String type = XmlPullUtil.attr(pp, "type"); XmlPullUtil.enter(pp); XmlPullUtil.require(pp, "Text"); final String value = XmlPullUtil.text(pp).trim(); XmlPullUtil.exit(pp); attributeVariants.put(type, value); } return attributeVariants; } private static final Pattern P_TIME = Pattern.compile("(\\d+)d(\\d+):(\\d{2}):(\\d{2})"); private Date parseTime(final Calendar currentDate, final String str) { final Matcher m = P_TIME.matcher(str); if (m.matches()) { final Calendar c = new GregorianCalendar(); c.set(Calendar.YEAR, currentDate.get(Calendar.YEAR)); c.set(Calendar.MONTH, currentDate.get(Calendar.MONTH)); c.set(Calendar.DAY_OF_MONTH, currentDate.get(Calendar.DAY_OF_MONTH)); c.set(Calendar.HOUR_OF_DAY, Integer.parseInt(m.group(2))); c.set(Calendar.MINUTE, Integer.parseInt(m.group(3))); c.set(Calendar.SECOND, Integer.parseInt(m.group(4))); c.set(Calendar.MILLISECOND, 0); c.add(Calendar.DAY_OF_MONTH, Integer.parseInt(m.group(1))); return c.getTime(); } else { throw new IllegalArgumentException("cannot parse duration: " + str); } } private static final Pattern P_DURATION = Pattern.compile("(\\d+):(\\d{2})"); private final int parseDuration(final String str) { final Matcher m = P_DURATION.matcher(str); if (m.matches()) return Integer.parseInt(m.group(1)) * 60 + Integer.parseInt(m.group(2)); else throw new IllegalArgumentException("cannot parse duration: " + str); } private final String location(final Location location) { if (location.type == LocationType.STATION && location.id != 0) return "<Station externalId=\"" + location.id + "\" />"; if (location.type == LocationType.POI && (location.lat != 0 || location.lon != 0)) return "<Poi type=\"WGS84\" x=\"" + location.lon + "\" y=\"" + location.lat + "\" />"; if (location.type == LocationType.ADDRESS && (location.lat != 0 || location.lon != 0)) return "<Address type=\"WGS84\" x=\"" + location.lon + "\" y=\"" + location.lat + "\" />"; throw new IllegalArgumentException("cannot handle: " + location.toDebugString()); } private static final Pattern P_LINE_S = Pattern.compile("S\\d+"); private final String _normalizeLine(final String type, final String name, final String longCategory) { final String normalizedType = type.split(" ", 2)[0]; final String normalizedName = normalizeWhitespace(name); if ("EN".equals(normalizedType)) // EuroNight return "I" + normalizedName; if ("EC".equals(normalizedType)) // EuroCity return "I" + normalizedName; if ("ICE".equals(normalizedType)) // InterCityExpress return "I" + normalizedName; if ("IC".equals(normalizedType)) // InterCity return "I" + normalizedName; if ("ICN".equals(normalizedType)) // IC-Neigezug return "I" + normalizedName; if ("CNL".equals(normalizedType)) // CityNightLine return "I" + normalizedName; if ("OEC".equals(normalizedType)) // ÖBB EuroCity return "I" + normalizedName; if ("OIC".equals(normalizedType)) // ÖBB InterCity return "I" + normalizedName; if ("TGV".equals(normalizedType)) // Train à grande vit. return "I" + normalizedName; if ("THA".equals(normalizedType)) // Thalys return "I" + normalizedName; // if ("THALYS".equals(normalizedType)) // return "I" + normalizedName; if ("ES".equals(normalizedType)) // Eurostar Italia return "I" + normalizedName; if ("EST".equals(normalizedType)) // Eurostar return "I" + normalizedName; if ("X2".equals(normalizedType)) // X2000 Neigezug, Schweden return "I" + normalizedName; if ("RJ".equals(normalizedType)) // Railjet return "I" + normalizedName; if ("AVE".equals(normalizedType)) // Alta Velocidad ES return "I" + normalizedName; if ("ARC".equals(normalizedType)) // Arco, Spanien return "I" + normalizedName; if ("ALS".equals(normalizedType)) // Alaris, Spanien return "I" + normalizedName; if ("NZ".equals(normalizedType)) // Nacht-Zug return "I" + normalizedName; if ("R".equals(normalizedType)) // Regio return "R" + normalizedName; if ("D".equals(normalizedType)) // Schnellzug return "R" + normalizedName; if ("E".equals(normalizedType)) // Eilzug return "R" + normalizedName; if ("RE".equals(normalizedType)) // RegioExpress return "R" + normalizedName; if ("IR".equals(normalizedType)) // InterRegio return "R" + normalizedName; if ("IRE".equals(normalizedType)) // InterRegioExpress return "R" + normalizedName; if ("ATZ".equals(normalizedType)) // Autotunnelzug return "R" + normalizedName; if ("S".equals(normalizedType)) // S-Bahn return "S" + normalizedName; if (P_LINE_S.matcher(normalizedType).matches()) // diverse S-Bahnen return "S" + normalizedType; if ("Met".equals(normalizedType)) // Metro return "U" + normalizedName; if ("M".equals(normalizedType)) // Metro return "U" + normalizedName; if ("Métro".equals(normalizedType)) return "U" + normalizedName; if ("Tram".equals(normalizedType)) // Tram return "T" + normalizedName; if ("Tramway".equals(normalizedType)) return "T" + normalizedName; if ("BUS".equals(normalizedType)) // Bus return "B" + normalizedName; if ("Bus".equals(normalizedType)) // Niederflurbus return "B" + normalizedName; if ("NFB".equals(normalizedType)) // Niederflur-Bus return "B" + normalizedName; if ("Tro".equals(normalizedType)) // Trolleybus return "B" + normalizedName; if ("Taxi".equals(normalizedType)) // Taxi return "B" + normalizedName; if ("TX".equals(normalizedType)) // Taxi return "B" + normalizedName; if ("BAT".equals(normalizedType)) // Schiff return "F" + normalizedName; if ("LB".equals(normalizedType)) // Luftseilbahn return "C" + normalizedName; if ("FUN".equals(normalizedType)) // Standseilbahn return "C" + normalizedName; if ("Fun".equals(normalizedType)) // Funiculaire return "C" + normalizedName; if ("L".equals(normalizedType)) return "?" + normalizedName; if ("P".equals(normalizedType)) return "?" + normalizedName; if ("CR".equals(normalizedType)) return "?" + normalizedName; if ("TRN".equals(normalizedType)) return "?" + normalizedName; throw new IllegalStateException("cannot normalize type '" + normalizedType + "' (" + type + ") name '" + normalizedName + "' longCategory '" + longCategory + "'"); } private final static Pattern P_WHITESPACE = Pattern.compile("\\s+"); private final String normalizeWhitespace(final String str) { return P_WHITESPACE.matcher(str).replaceAll(""); } public QueryConnectionsResult queryMoreConnections(String uri) throws IOException { throw new UnsupportedOperationException(); } public GetConnectionDetailsResult getConnectionDetails(String connectionUri) throws IOException { throw new UnsupportedOperationException(); } private final static Pattern P_NEARBY_COARSE = Pattern.compile("<tr class=\"(zebra[^\"]*)\">(.*?)</tr>", Pattern.DOTALL); private final static Pattern P_NEARBY_FINE_COORDS = Pattern .compile("&REQMapRoute0\\.Location0\\.X=(-?\\d+)&REQMapRoute0\\.Location0\\.Y=(-?\\d+)&"); private final static Pattern P_NEARBY_FINE_LOCATION = Pattern.compile("[\\?&]input=(\\d+)&[^\"]*\">([^<]*)<"); protected abstract String nearbyStationUri(String stationId); public NearbyStationsResult nearbyStations(final String stationId, final int lat, final int lon, final int maxDistance, final int maxStations) throws IOException { if (stationId == null) throw new IllegalArgumentException("stationId must be given"); final List<Station> stations = new ArrayList<Station>(); final String uri = nearbyStationUri(stationId); final CharSequence page = ParserUtils.scrape(uri); String oldZebra = null; final Matcher mCoarse = P_NEARBY_COARSE.matcher(page); while (mCoarse.find()) { final String zebra = mCoarse.group(1); if (oldZebra != null && zebra.equals(oldZebra)) throw new IllegalArgumentException("missed row? last:" + zebra); else oldZebra = zebra; final Matcher mFineLocation = P_NEARBY_FINE_LOCATION.matcher(mCoarse.group(2)); if (mFineLocation.find()) { int parsedLon = 0; int parsedLat = 0; final int parsedId = Integer.parseInt(mFineLocation.group(1)); final String parsedName = ParserUtils.resolveEntities(mFineLocation.group(2)); final Matcher mFineCoords = P_NEARBY_FINE_COORDS.matcher(mCoarse.group(2)); if (mFineCoords.find()) { parsedLon = Integer.parseInt(mFineCoords.group(1)); parsedLat = Integer.parseInt(mFineCoords.group(2)); } stations.add(new Station(parsedId, parsedName, parsedLat, parsedLon, 0, null, null)); } else { throw new IllegalArgumentException("cannot parse '" + mCoarse.group(2) + "' on " + uri); } } if (maxStations == 0 || maxStations >= stations.size()) return new NearbyStationsResult(uri, stations); else return new NearbyStationsResult(uri, stations.subList(0, maxStations)); } protected static final Pattern P_NORMALIZE_LINE = Pattern.compile("([A-Za-zÄÖÜäöüßáàâéèêíìîóòôúùû/-]+)[\\s-]*(.*)"); protected final String normalizeLine(final String type, final String line) { final Matcher m = P_NORMALIZE_LINE.matcher(line); final String strippedLine = m.matches() ? m.group(1) + m.group(2) : line; final char normalizedType = normalizeType(type); if (normalizedType != 0) return normalizedType + strippedLine; throw new IllegalStateException("cannot normalize type '" + type + "' line '" + line + "'"); } protected abstract char normalizeType(String type); protected final char normalizeCommonTypes(final String ucType) { // Intercity if (ucType.equals("EC")) // EuroCity return 'I'; if (ucType.equals("EN")) // EuroNight return 'I'; if (ucType.equals("ICE")) // InterCityExpress return 'I'; if (ucType.equals("IC")) // InterCity return 'I'; if (ucType.equals("EN")) // EuroNight return 'I'; if (ucType.equals("CNL")) // CityNightLine return 'I'; if (ucType.equals("OEC")) // ÖBB-EuroCity return 'I'; if (ucType.equals("OIC")) // ÖBB-InterCity return 'I'; if (ucType.equals("RJ")) // RailJet, Österreichische Bundesbahnen return 'I'; if (ucType.equals("THA")) // Thalys return 'I'; if (ucType.equals("TGV")) // Train à Grande Vitesse return 'I'; if (ucType.equals("DNZ")) // Berlin-Saratov, Berlin-Moskva, Connections only? return 'I'; if (ucType.equals("AIR")) // Generic Flight return 'I'; if (ucType.equals("ECB")) // EC, Verona-München return 'I'; if (ucType.equals("INZ")) // Nacht return 'I'; if (ucType.equals("RHI")) // ICE return 'I'; if (ucType.equals("RHT")) // TGV return 'I'; if (ucType.equals("TGD")) // TGV return 'I'; if (ucType.equals("IRX")) // IC return 'I'; // Regional Germany if (ucType.equals("ZUG")) // Generic Train return 'R'; if (ucType.equals("R")) // Generic Regional Train return 'R'; if (ucType.equals("DPN")) // Dritter Personen Nahverkehr return 'R'; if (ucType.equals("RB")) // RegionalBahn return 'R'; if (ucType.equals("RE")) // RegionalExpress return 'R'; if (ucType.equals("IR")) // Interregio return 'R'; if (ucType.equals("IRE")) // Interregio Express return 'R'; if (ucType.equals("HEX")) // Harz-Berlin-Express, Veolia return 'R'; if (ucType.equals("WFB")) // Westfalenbahn return 'R'; if (ucType.equals("RT")) // RegioTram return 'R'; if (ucType.equals("REX")) // RegionalExpress, Österreich return 'R'; // Regional Poland if (ucType.equals("OS")) // Chop-Cierna nas Tisou return 'R'; if (ucType.equals("SP")) // Polen return 'R'; // Suburban Trains if (ucType.equals("S")) // Generic S-Bahn return 'S'; // Subway if (ucType.equals("U")) // Generic U-Bahn return 'U'; // Tram if (ucType.equals("STR")) // Generic Tram return 'T'; // Bus if (ucType.equals("BUS")) // Generic Bus return 'B'; if (ucType.equals("AST")) // Anruf-Sammel-Taxi return 'B'; if (ucType.equals("SEV")) // Schienen-Ersatz-Verkehr return 'B'; if (ucType.equals("BUSSEV")) // Schienen-Ersatz-Verkehr return 'B'; if (ucType.equals("FB")) // Luxemburg-Saarbrücken return 'B'; // Ferry if (ucType.equals("AS")) // SyltShuttle, eigentlich Autoreisezug return 'F'; return 0; } private static final Pattern P_CONNECTION_ID = Pattern.compile("co=(C\\d+-\\d+)&"); protected static String extractConnectionId(final String link) { final Matcher m = P_CONNECTION_ID.matcher(link); if (m.find()) return m.group(1); else throw new IllegalArgumentException("cannot extract id from " + link); } private static final Map<Character, int[]> LINES = new HashMap<Character, int[]>(); static { LINES.put('I', new int[] { Color.WHITE, Color.RED, Color.RED }); LINES.put('R', new int[] { Color.GRAY, Color.WHITE }); LINES.put('S', new int[] { Color.parseColor("#006e34"), Color.WHITE }); LINES.put('U', new int[] { Color.parseColor("#003090"), Color.WHITE }); LINES.put('T', new int[] { Color.parseColor("#cc0000"), Color.WHITE }); LINES.put('B', new int[] { Color.parseColor("#993399"), Color.WHITE }); LINES.put('F', new int[] { Color.BLUE, Color.WHITE }); LINES.put('?', new int[] { Color.DKGRAY, Color.WHITE }); } public final int[] lineColors(final String line) { return LINES.get(line.charAt(0)); } private void assertResC(final XmlPullParser pp) throws XmlPullParserException, IOException { if (!XmlPullUtil.jumpToStartTag(pp, null, "ResC")) throw new IOException("cannot find <ResC />"); } }
true
true
public QueryConnectionsResult queryConnections(Location from, Location via, Location to, final Date date, final boolean dep, final String products, final WalkSpeed walkSpeed) throws IOException { if (from.type == LocationType.ANY) { final List<Location> autocompletes = autocompleteStations(from.name); if (autocompletes.isEmpty()) return new QueryConnectionsResult(QueryConnectionsResult.Status.NO_CONNECTIONS); // TODO if (autocompletes.size() > 1) return new QueryConnectionsResult(autocompletes, null, null); from = autocompletes.get(0); } if (via != null && via.type == LocationType.ANY) { final List<Location> autocompletes = autocompleteStations(via.name); if (autocompletes.isEmpty()) return new QueryConnectionsResult(QueryConnectionsResult.Status.NO_CONNECTIONS); // TODO if (autocompletes.size() > 1) return new QueryConnectionsResult(null, autocompletes, null); via = autocompletes.get(0); } if (to.type == LocationType.ANY) { final List<Location> autocompletes = autocompleteStations(to.name); if (autocompletes.isEmpty()) return new QueryConnectionsResult(QueryConnectionsResult.Status.NO_CONNECTIONS); // TODO if (autocompletes.size() > 1) return new QueryConnectionsResult(null, null, autocompletes); to = autocompletes.get(0); } final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyyMMdd"); final DateFormat TIME_FORMAT = new SimpleDateFormat("HH:mm"); final String request = "<ConReq>" // + "<Start>" + location(from) + "<Prod bike=\"0\" couchette=\"0\" direct=\"0\" sleeper=\"0\"/></Start>" // + (via != null ? "<Via>" + location(via) + "</Via>" : "") // + "<Dest>" + location(to) + "</Dest>" // + "<ReqT a=\"" + (dep ? 0 : 1) + "\" date=\"" + DATE_FORMAT.format(date) + "\" time=\"" + TIME_FORMAT.format(date) + "\"/>" // + "<RFlags b=\"0\" chExtension=\"0\" f=\"4\" sMode=\"N\"/>" // + "</ConReq>"; // System.out.println(request); // System.out.println(ParserUtils.scrape(apiUri, true, wrap(request), null, false)); InputStream is = null; try { is = ParserUtils.scrapeInputStream(apiUri, wrap(request)); final XmlPullParserFactory factory = XmlPullParserFactory.newInstance(System.getProperty(XmlPullParserFactory.PROPERTY_NAME), null); final XmlPullParser pp = factory.newPullParser(); pp.setInput(is, DEFAULT_ENCODING); assertResC(pp); XmlPullUtil.enter(pp); XmlPullUtil.require(pp, "ConRes"); XmlPullUtil.enter(pp); if (pp.getName().equals("Err")) { final String code = XmlPullUtil.attr(pp, "code"); if (code.equals("K9380")) return QueryConnectionsResult.TOO_CLOSE; if (code.equals("K9220")) // Nearby to the given address stations could not be found return QueryConnectionsResult.NO_CONNECTIONS; if (code.equals("K890")) // No connections found return QueryConnectionsResult.NO_CONNECTIONS; throw new IllegalStateException("error " + code + " " + XmlPullUtil.attr(pp, "text")); } XmlPullUtil.require(pp, "ConResCtxt"); final String sessionId = XmlPullUtil.text(pp); XmlPullUtil.require(pp, "ConnectionList"); XmlPullUtil.enter(pp); final List<Connection> connections = new ArrayList<Connection>(); while (XmlPullUtil.test(pp, "Connection")) { final String id = XmlPullUtil.attr(pp, "id"); XmlPullUtil.enter(pp); while (pp.getName().equals("RtStateList")) XmlPullUtil.next(pp); XmlPullUtil.require(pp, "Overview"); XmlPullUtil.enter(pp); XmlPullUtil.require(pp, "Date"); final Calendar currentDate = new GregorianCalendar(); currentDate.setTime(DATE_FORMAT.parse(XmlPullUtil.text(pp))); XmlPullUtil.exit(pp); XmlPullUtil.require(pp, "ConSectionList"); XmlPullUtil.enter(pp); final List<Connection.Part> parts = new ArrayList<Connection.Part>(4); Date firstDepartureTime = null; Date lastArrivalTime = null; while (XmlPullUtil.test(pp, "ConSection")) { XmlPullUtil.enter(pp); // departure XmlPullUtil.require(pp, "Departure"); XmlPullUtil.enter(pp); XmlPullUtil.require(pp, "BasicStop"); XmlPullUtil.enter(pp); while (pp.getName().equals("StAttrList")) XmlPullUtil.next(pp); Location departure; if (pp.getName().equals("Station")) departure = parseStation(pp); else if (pp.getName().equals("Poi")) departure = parsePoi(pp); else throw new IllegalStateException("cannot parse: " + pp.getName()); XmlPullUtil.next(pp); XmlPullUtil.require(pp, "Dep"); XmlPullUtil.enter(pp); XmlPullUtil.require(pp, "Time"); final Date departureTime = parseTime(currentDate, XmlPullUtil.text(pp)); XmlPullUtil.require(pp, "Platform"); XmlPullUtil.enter(pp); XmlPullUtil.require(pp, "Text"); String departurePos = XmlPullUtil.text(pp).trim(); if (departurePos.length() == 0) departurePos = null; XmlPullUtil.exit(pp); XmlPullUtil.exit(pp); XmlPullUtil.exit(pp); XmlPullUtil.exit(pp); // journey String line = null; String direction = null; int min = 0; final String tag = pp.getName(); if (tag.equals("Journey")) { XmlPullUtil.enter(pp); while (pp.getName().equals("JHandle")) XmlPullUtil.next(pp); XmlPullUtil.require(pp, "JourneyAttributeList"); XmlPullUtil.enter(pp); String name = null; String category = null; String longCategory = null; while (XmlPullUtil.test(pp, "JourneyAttribute")) { XmlPullUtil.enter(pp); XmlPullUtil.require(pp, "Attribute"); final String attrName = XmlPullUtil.attr(pp, "type"); XmlPullUtil.enter(pp); final Map<String, String> attributeVariants = parseAttributeVariants(pp); XmlPullUtil.exit(pp); XmlPullUtil.exit(pp); if ("NAME".equals(attrName)) { name = attributeVariants.get("NORMAL"); } else if ("CATEGORY".equals(attrName)) { category = attributeVariants.get("NORMAL"); longCategory = attributeVariants.get("LONG"); } else if ("DIRECTION".equals(attrName)) { direction = attributeVariants.get("NORMAL"); } } XmlPullUtil.exit(pp); XmlPullUtil.exit(pp); line = _normalizeLine(category, name, longCategory); } else if (tag.equals("Walk") || tag.equals("Transfer") || tag.equals("GisRoute")) { XmlPullUtil.enter(pp); XmlPullUtil.require(pp, "Duration"); XmlPullUtil.enter(pp); XmlPullUtil.require(pp, "Time"); min = parseDuration(XmlPullUtil.text(pp).substring(3, 8)); XmlPullUtil.exit(pp); XmlPullUtil.exit(pp); } else { throw new IllegalStateException("cannot handle: " + pp.getName()); } // arrival XmlPullUtil.require(pp, "Arrival"); XmlPullUtil.enter(pp); XmlPullUtil.require(pp, "BasicStop"); XmlPullUtil.enter(pp); while (pp.getName().equals("StAttrList")) XmlPullUtil.next(pp); Location arrival; if (pp.getName().equals("Station")) arrival = parseStation(pp); else if (pp.getName().equals("Poi")) arrival = parsePoi(pp); else if (pp.getName().equals("Address")) arrival = parseAddress(pp); else throw new IllegalStateException("cannot parse: " + pp.getName()); XmlPullUtil.next(pp); XmlPullUtil.require(pp, "Arr"); XmlPullUtil.enter(pp); XmlPullUtil.require(pp, "Time"); final Date arrivalTime = parseTime(currentDate, XmlPullUtil.text(pp)); XmlPullUtil.require(pp, "Platform"); XmlPullUtil.enter(pp); XmlPullUtil.require(pp, "Text"); String arrivalPos = XmlPullUtil.text(pp).trim(); if (arrivalPos.length() == 0) arrivalPos = null; XmlPullUtil.exit(pp); XmlPullUtil.exit(pp); XmlPullUtil.exit(pp); XmlPullUtil.exit(pp); XmlPullUtil.exit(pp); if (min == 0 || line != null) { parts.add(new Connection.Trip(line, lineColors(line), 0, direction, departureTime, departurePos, departure.id, departure.name, arrivalTime, arrivalPos, arrival.id, arrival.name)); } else { if (parts.size() > 0 && parts.get(parts.size() - 1) instanceof Connection.Footway) { final Connection.Footway lastFootway = (Connection.Footway) parts.remove(parts.size() - 1); parts.add(new Connection.Footway(lastFootway.min + min, lastFootway.departureId, lastFootway.departure, arrival.id, arrival.name)); } else { parts.add(new Connection.Footway(min, departure.id, departure.name, arrival.id, arrival.name)); } } if (firstDepartureTime == null) firstDepartureTime = departureTime; lastArrivalTime = arrivalTime; } XmlPullUtil.exit(pp); XmlPullUtil.exit(pp); connections.add(new Connection(id, null, firstDepartureTime, lastArrivalTime, null, null, 0, null, 0, null, parts)); } XmlPullUtil.exit(pp); return new QueryConnectionsResult(null, from, via, to, null, null, connections); } catch (final XmlPullParserException x) { throw new RuntimeException(x); } catch (final SocketTimeoutException x) { throw new RuntimeException(x); } catch (final ParseException x) { throw new RuntimeException(x); } finally { if (is != null) is.close(); } }
public QueryConnectionsResult queryConnections(Location from, Location via, Location to, final Date date, final boolean dep, final String products, final WalkSpeed walkSpeed) throws IOException { if (from.type == LocationType.ANY) { final List<Location> autocompletes = autocompleteStations(from.name); if (autocompletes.isEmpty()) return new QueryConnectionsResult(QueryConnectionsResult.Status.NO_CONNECTIONS); // TODO if (autocompletes.size() > 1) return new QueryConnectionsResult(autocompletes, null, null); from = autocompletes.get(0); } if (via != null && via.type == LocationType.ANY) { final List<Location> autocompletes = autocompleteStations(via.name); if (autocompletes.isEmpty()) return new QueryConnectionsResult(QueryConnectionsResult.Status.NO_CONNECTIONS); // TODO if (autocompletes.size() > 1) return new QueryConnectionsResult(null, autocompletes, null); via = autocompletes.get(0); } if (to.type == LocationType.ANY) { final List<Location> autocompletes = autocompleteStations(to.name); if (autocompletes.isEmpty()) return new QueryConnectionsResult(QueryConnectionsResult.Status.NO_CONNECTIONS); // TODO if (autocompletes.size() > 1) return new QueryConnectionsResult(null, null, autocompletes); to = autocompletes.get(0); } final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyyMMdd"); final DateFormat TIME_FORMAT = new SimpleDateFormat("HH:mm"); final String request = "<ConReq>" // + "<Start>" + location(from) + "<Prod bike=\"0\" couchette=\"0\" direct=\"0\" sleeper=\"0\"/></Start>" // + (via != null ? "<Via>" + location(via) + "</Via>" : "") // + "<Dest>" + location(to) + "</Dest>" // + "<ReqT a=\"" + (dep ? 0 : 1) + "\" date=\"" + DATE_FORMAT.format(date) + "\" time=\"" + TIME_FORMAT.format(date) + "\"/>" // + "<RFlags b=\"0\" chExtension=\"0\" f=\"4\" sMode=\"N\"/>" // + "</ConReq>"; // System.out.println(request); // System.out.println(ParserUtils.scrape(apiUri, true, wrap(request), null, false)); InputStream is = null; try { is = ParserUtils.scrapeInputStream(apiUri, wrap(request)); final XmlPullParserFactory factory = XmlPullParserFactory.newInstance(System.getProperty(XmlPullParserFactory.PROPERTY_NAME), null); final XmlPullParser pp = factory.newPullParser(); pp.setInput(is, DEFAULT_ENCODING); assertResC(pp); XmlPullUtil.enter(pp); XmlPullUtil.require(pp, "ConRes"); XmlPullUtil.enter(pp); if (pp.getName().equals("Err")) { final String code = XmlPullUtil.attr(pp, "code"); if (code.equals("K9380")) return QueryConnectionsResult.TOO_CLOSE; if (code.equals("K9220")) // Nearby to the given address stations could not be found return QueryConnectionsResult.NO_CONNECTIONS; if (code.equals("K890")) // No connections found return QueryConnectionsResult.NO_CONNECTIONS; throw new IllegalStateException("error " + code + " " + XmlPullUtil.attr(pp, "text")); } XmlPullUtil.require(pp, "ConResCtxt"); final String sessionId = XmlPullUtil.text(pp); XmlPullUtil.require(pp, "ConnectionList"); XmlPullUtil.enter(pp); final List<Connection> connections = new ArrayList<Connection>(); while (XmlPullUtil.test(pp, "Connection")) { final String id = XmlPullUtil.attr(pp, "id"); XmlPullUtil.enter(pp); while (pp.getName().equals("RtStateList")) XmlPullUtil.next(pp); XmlPullUtil.require(pp, "Overview"); XmlPullUtil.enter(pp); XmlPullUtil.require(pp, "Date"); final Calendar currentDate = new GregorianCalendar(); currentDate.setTime(DATE_FORMAT.parse(XmlPullUtil.text(pp))); XmlPullUtil.exit(pp); XmlPullUtil.require(pp, "ConSectionList"); XmlPullUtil.enter(pp); final List<Connection.Part> parts = new ArrayList<Connection.Part>(4); Date firstDepartureTime = null; Date lastArrivalTime = null; while (XmlPullUtil.test(pp, "ConSection")) { XmlPullUtil.enter(pp); // departure XmlPullUtil.require(pp, "Departure"); XmlPullUtil.enter(pp); XmlPullUtil.require(pp, "BasicStop"); XmlPullUtil.enter(pp); while (pp.getName().equals("StAttrList")) XmlPullUtil.next(pp); Location departure; if (pp.getName().equals("Station")) departure = parseStation(pp); else if (pp.getName().equals("Poi")) departure = parsePoi(pp); else if (pp.getName().equals("Address")) departure = parseAddress(pp); else throw new IllegalStateException("cannot parse: " + pp.getName()); XmlPullUtil.next(pp); XmlPullUtil.require(pp, "Dep"); XmlPullUtil.enter(pp); XmlPullUtil.require(pp, "Time"); final Date departureTime = parseTime(currentDate, XmlPullUtil.text(pp)); XmlPullUtil.require(pp, "Platform"); XmlPullUtil.enter(pp); XmlPullUtil.require(pp, "Text"); String departurePos = XmlPullUtil.text(pp).trim(); if (departurePos.length() == 0) departurePos = null; XmlPullUtil.exit(pp); XmlPullUtil.exit(pp); XmlPullUtil.exit(pp); XmlPullUtil.exit(pp); // journey String line = null; String direction = null; int min = 0; final String tag = pp.getName(); if (tag.equals("Journey")) { XmlPullUtil.enter(pp); while (pp.getName().equals("JHandle")) XmlPullUtil.next(pp); XmlPullUtil.require(pp, "JourneyAttributeList"); XmlPullUtil.enter(pp); String name = null; String category = null; String longCategory = null; while (XmlPullUtil.test(pp, "JourneyAttribute")) { XmlPullUtil.enter(pp); XmlPullUtil.require(pp, "Attribute"); final String attrName = XmlPullUtil.attr(pp, "type"); XmlPullUtil.enter(pp); final Map<String, String> attributeVariants = parseAttributeVariants(pp); XmlPullUtil.exit(pp); XmlPullUtil.exit(pp); if ("NAME".equals(attrName)) { name = attributeVariants.get("NORMAL"); } else if ("CATEGORY".equals(attrName)) { category = attributeVariants.get("NORMAL"); longCategory = attributeVariants.get("LONG"); } else if ("DIRECTION".equals(attrName)) { direction = attributeVariants.get("NORMAL"); } } XmlPullUtil.exit(pp); XmlPullUtil.exit(pp); line = _normalizeLine(category, name, longCategory); } else if (tag.equals("Walk") || tag.equals("Transfer") || tag.equals("GisRoute")) { XmlPullUtil.enter(pp); XmlPullUtil.require(pp, "Duration"); XmlPullUtil.enter(pp); XmlPullUtil.require(pp, "Time"); min = parseDuration(XmlPullUtil.text(pp).substring(3, 8)); XmlPullUtil.exit(pp); XmlPullUtil.exit(pp); } else { throw new IllegalStateException("cannot handle: " + pp.getName()); } // arrival XmlPullUtil.require(pp, "Arrival"); XmlPullUtil.enter(pp); XmlPullUtil.require(pp, "BasicStop"); XmlPullUtil.enter(pp); while (pp.getName().equals("StAttrList")) XmlPullUtil.next(pp); Location arrival; if (pp.getName().equals("Station")) arrival = parseStation(pp); else if (pp.getName().equals("Poi")) arrival = parsePoi(pp); else if (pp.getName().equals("Address")) arrival = parseAddress(pp); else throw new IllegalStateException("cannot parse: " + pp.getName()); XmlPullUtil.next(pp); XmlPullUtil.require(pp, "Arr"); XmlPullUtil.enter(pp); XmlPullUtil.require(pp, "Time"); final Date arrivalTime = parseTime(currentDate, XmlPullUtil.text(pp)); XmlPullUtil.require(pp, "Platform"); XmlPullUtil.enter(pp); XmlPullUtil.require(pp, "Text"); String arrivalPos = XmlPullUtil.text(pp).trim(); if (arrivalPos.length() == 0) arrivalPos = null; XmlPullUtil.exit(pp); XmlPullUtil.exit(pp); XmlPullUtil.exit(pp); XmlPullUtil.exit(pp); XmlPullUtil.exit(pp); if (min == 0 || line != null) { parts.add(new Connection.Trip(line, lineColors(line), 0, direction, departureTime, departurePos, departure.id, departure.name, arrivalTime, arrivalPos, arrival.id, arrival.name)); } else { if (parts.size() > 0 && parts.get(parts.size() - 1) instanceof Connection.Footway) { final Connection.Footway lastFootway = (Connection.Footway) parts.remove(parts.size() - 1); parts.add(new Connection.Footway(lastFootway.min + min, lastFootway.departureId, lastFootway.departure, arrival.id, arrival.name)); } else { parts.add(new Connection.Footway(min, departure.id, departure.name, arrival.id, arrival.name)); } } if (firstDepartureTime == null) firstDepartureTime = departureTime; lastArrivalTime = arrivalTime; } XmlPullUtil.exit(pp); XmlPullUtil.exit(pp); connections.add(new Connection(id, null, firstDepartureTime, lastArrivalTime, null, null, 0, null, 0, null, parts)); } XmlPullUtil.exit(pp); return new QueryConnectionsResult(null, from, via, to, null, null, connections); } catch (final XmlPullParserException x) { throw new RuntimeException(x); } catch (final SocketTimeoutException x) { throw new RuntimeException(x); } catch (final ParseException x) { throw new RuntimeException(x); } finally { if (is != null) is.close(); } }
diff --git a/src/ecprac/era270/NeuralGenome.java b/src/ecprac/era270/NeuralGenome.java index 3049037..483bac2 100644 --- a/src/ecprac/era270/NeuralGenome.java +++ b/src/ecprac/era270/NeuralGenome.java @@ -1,26 +1,24 @@ package ecprac.era270; import java.util.Arrays; //import ecprac.torcs.genome.IGenome; public class NeuralGenome extends GenericGenome { public double fitness; // 19 because of the number of sensors public FeedForward network = new FeedForward(new double[19], 1); public String toString() { return ""; } public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof NeuralGenome)) return false; NeuralGenome other = (NeuralGenome)o; - return Arrays.equals(network.inputLayer, other.network.inputLayer) && - Arrays.equals(network.hiddenLayer, other.network.hiddenLayer) && - Arrays.equals(network.outputLayer, other.network.outputLayer); + return Arrays.equals(network.getWeights(), other.network.getWeights()); } }
true
true
public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof NeuralGenome)) return false; NeuralGenome other = (NeuralGenome)o; return Arrays.equals(network.inputLayer, other.network.inputLayer) && Arrays.equals(network.hiddenLayer, other.network.hiddenLayer) && Arrays.equals(network.outputLayer, other.network.outputLayer); }
public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof NeuralGenome)) return false; NeuralGenome other = (NeuralGenome)o; return Arrays.equals(network.getWeights(), other.network.getWeights()); }
diff --git a/src/servlets/EditQuestionServlet.java b/src/servlets/EditQuestionServlet.java index 45ec564..06aba09 100644 --- a/src/servlets/EditQuestionServlet.java +++ b/src/servlets/EditQuestionServlet.java @@ -1,72 +1,76 @@ //Created By Ilan Godik package servlets; import db.DB; import db.RealDB; import model.Answer; import model.Question; import model.User; import util.Validation.InputValidation; import util.Validation.IntValidator; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; import static util.Marking.mark; public class EditQuestionServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("UTF-8"); resp.setCharacterEncoding("UTF-8"); HttpSession session = req.getSession(); User adminUser = (User) session.getAttribute("user"); if (adminUser != null && adminUser.isAdmin) { DB db = new RealDB(); int id = Integer.parseInt(req.getParameter("id")); String question = req.getParameter("question"); String answer1 = req.getParameter("answer1"); String answer2 = req.getParameter("answer2"); String answer3 = req.getParameter("answer3"); String answer4 = req.getParameter("answer4"); String correctAnswerS = req.getParameter("correctAnswer"); InputValidation valid = new InputValidation(req, db); - int correctAnswer = 1; // Doesn't matter. + int correctAnswer = 1;// Doesn't matter!!! IntValidator validator = new IntValidator(); if (!validator.isValid(correctAnswerS)) { valid.fail("correctAnswer"); } else { correctAnswer = Integer.parseInt(correctAnswerS); if (correctAnswer < 1 || correctAnswer > 4) { valid.fail("correctAnswer"); } } if (!valid.hasFailed()) { Question q = new Question(db, id); - Question newQ = new Question(id, q.number, question, q.answer); + Question newQ = new Question(id, q.number, question, correctAnswer); newQ.save(db); - Answer a1 = new Answer(0, 1, q.id, answer1); + Answer oldA1 = new Answer(db, 1, q.id); + Answer a1 = new Answer(oldA1.id, 1, q.id, answer1); a1.save(db); - Answer a2 = new Answer(0, 2, q.id, answer2); + Answer oldA2 = new Answer(db, 2, q.id); + Answer a2 = new Answer(oldA2.id, 2, q.id, answer2); a2.save(db); - Answer a3 = new Answer(0, 3, q.id, answer3); + Answer oldA3 = new Answer(db, 3, q.id); + Answer a3 = new Answer(oldA3.id, 3, q.id, answer3); a3.save(db); - Answer a4 = new Answer(0, 4, q.id, answer4); + Answer oldA4 = new Answer(db, 4, q.id); + Answer a4 = new Answer(oldA4.id, 4, q.id, answer4); a4.save(db); mark(req, "edit-success"); } req.getRequestDispatcher("/admin/editQuestion.jsp?id=" + id).forward(req, resp); } } }
false
true
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("UTF-8"); resp.setCharacterEncoding("UTF-8"); HttpSession session = req.getSession(); User adminUser = (User) session.getAttribute("user"); if (adminUser != null && adminUser.isAdmin) { DB db = new RealDB(); int id = Integer.parseInt(req.getParameter("id")); String question = req.getParameter("question"); String answer1 = req.getParameter("answer1"); String answer2 = req.getParameter("answer2"); String answer3 = req.getParameter("answer3"); String answer4 = req.getParameter("answer4"); String correctAnswerS = req.getParameter("correctAnswer"); InputValidation valid = new InputValidation(req, db); int correctAnswer = 1; // Doesn't matter. IntValidator validator = new IntValidator(); if (!validator.isValid(correctAnswerS)) { valid.fail("correctAnswer"); } else { correctAnswer = Integer.parseInt(correctAnswerS); if (correctAnswer < 1 || correctAnswer > 4) { valid.fail("correctAnswer"); } } if (!valid.hasFailed()) { Question q = new Question(db, id); Question newQ = new Question(id, q.number, question, q.answer); newQ.save(db); Answer a1 = new Answer(0, 1, q.id, answer1); a1.save(db); Answer a2 = new Answer(0, 2, q.id, answer2); a2.save(db); Answer a3 = new Answer(0, 3, q.id, answer3); a3.save(db); Answer a4 = new Answer(0, 4, q.id, answer4); a4.save(db); mark(req, "edit-success"); } req.getRequestDispatcher("/admin/editQuestion.jsp?id=" + id).forward(req, resp); } }
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("UTF-8"); resp.setCharacterEncoding("UTF-8"); HttpSession session = req.getSession(); User adminUser = (User) session.getAttribute("user"); if (adminUser != null && adminUser.isAdmin) { DB db = new RealDB(); int id = Integer.parseInt(req.getParameter("id")); String question = req.getParameter("question"); String answer1 = req.getParameter("answer1"); String answer2 = req.getParameter("answer2"); String answer3 = req.getParameter("answer3"); String answer4 = req.getParameter("answer4"); String correctAnswerS = req.getParameter("correctAnswer"); InputValidation valid = new InputValidation(req, db); int correctAnswer = 1;// Doesn't matter!!! IntValidator validator = new IntValidator(); if (!validator.isValid(correctAnswerS)) { valid.fail("correctAnswer"); } else { correctAnswer = Integer.parseInt(correctAnswerS); if (correctAnswer < 1 || correctAnswer > 4) { valid.fail("correctAnswer"); } } if (!valid.hasFailed()) { Question q = new Question(db, id); Question newQ = new Question(id, q.number, question, correctAnswer); newQ.save(db); Answer oldA1 = new Answer(db, 1, q.id); Answer a1 = new Answer(oldA1.id, 1, q.id, answer1); a1.save(db); Answer oldA2 = new Answer(db, 2, q.id); Answer a2 = new Answer(oldA2.id, 2, q.id, answer2); a2.save(db); Answer oldA3 = new Answer(db, 3, q.id); Answer a3 = new Answer(oldA3.id, 3, q.id, answer3); a3.save(db); Answer oldA4 = new Answer(db, 4, q.id); Answer a4 = new Answer(oldA4.id, 4, q.id, answer4); a4.save(db); mark(req, "edit-success"); } req.getRequestDispatcher("/admin/editQuestion.jsp?id=" + id).forward(req, resp); } }
diff --git a/src/main/java/org/jenkinsci/plugins/multiplescms/MultiSCM.java b/src/main/java/org/jenkinsci/plugins/multiplescms/MultiSCM.java index 53c81b5..0bf835d 100644 --- a/src/main/java/org/jenkinsci/plugins/multiplescms/MultiSCM.java +++ b/src/main/java/org/jenkinsci/plugins/multiplescms/MultiSCM.java @@ -1,206 +1,206 @@ package org.jenkinsci.plugins.multiplescms; import hudson.Extension; import hudson.FilePath; import hudson.Launcher; import hudson.model.Action; import hudson.model.BuildListener; import hudson.model.Saveable; import hudson.model.TaskListener; import hudson.model.AbstractBuild; import hudson.model.AbstractProject; import hudson.model.Descriptor; import hudson.scm.ChangeLogParser; import hudson.scm.PollingResult; import hudson.scm.PollingResult.Change; import hudson.scm.SCMDescriptor; import hudson.scm.SCMRevisionState; import hudson.scm.NullSCM; import hudson.scm.SCM; import hudson.util.DescribableList; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; import net.sf.json.JSONObject; import org.apache.commons.io.FileUtils; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.export.Exported; public class MultiSCM extends SCM implements Saveable { private DescribableList<SCM,Descriptor<SCM>> scms = new DescribableList<SCM,Descriptor<SCM>>(this); @DataBoundConstructor public MultiSCM(List<SCM> scmList) throws IOException { scms.addAll(scmList); } @Exported public List<SCM> getConfiguredSCMs() { return scms.toList(); } @Override public SCMRevisionState calcRevisionsFromBuild(AbstractBuild<?, ?> build, Launcher launcher, TaskListener listener) throws IOException, InterruptedException { MultiSCMRevisionState revisionStates = new MultiSCMRevisionState(); for(SCM scm : scms) { SCMRevisionState scmState = scm.calcRevisionsFromBuild(build, launcher, listener); revisionStates.add(scm, build.getWorkspace(), build, scmState); } return revisionStates; } @Override public void buildEnvVars(AbstractBuild<?,?> build, Map<String, String> env) { for(SCM scm : scms) { try { scm.buildEnvVars(build, env); } catch(NullPointerException npe) {} } } @Override protected PollingResult compareRemoteRevisionWith( AbstractProject<?, ?> project, Launcher launcher, FilePath workspace, TaskListener listener, SCMRevisionState baseline) throws IOException, InterruptedException { MultiSCMRevisionState baselineStates = baseline instanceof MultiSCMRevisionState ? (MultiSCMRevisionState) baseline : null; MultiSCMRevisionState currentStates = new MultiSCMRevisionState(); Change overallChange = Change.NONE; for(SCM scm : scms) { SCMRevisionState scmBaseline = baselineStates != null ? baselineStates.get(scm, workspace, null) : null; PollingResult scmResult = scm.poll(project, launcher, workspace, listener, scmBaseline != null ? scmBaseline : SCMRevisionState.NONE); currentStates.add(scm, workspace, null, scmResult.remote); if(scmResult.change.compareTo(overallChange) > 0) overallChange = scmResult.change; } return new PollingResult(baselineStates, currentStates, overallChange); } @Override public boolean checkout(AbstractBuild<?, ?> build, Launcher launcher, FilePath workspace, BuildListener listener, File changelogFile) throws IOException, InterruptedException { MultiSCMRevisionState revisionState = new MultiSCMRevisionState(); build.addAction(revisionState); HashSet<Object> scmActions = new HashSet<Object>(); FileOutputStream logStream = new FileOutputStream(changelogFile); OutputStreamWriter logWriter = new OutputStreamWriter(logStream); logWriter.write(String.format("<%s>\n", MultiSCMChangeLogParser.ROOT_XML_TAG)); boolean checkoutOK = true; for(SCM scm : scms) { String changeLogPath = changelogFile.getPath() + ".temp"; File subChangeLog = new File(changeLogPath); checkoutOK = scm.checkout(build, launcher, workspace, listener, subChangeLog) && checkoutOK; List<Action> actions = build.getActions(); for(Action a : actions) { if(!scmActions.contains(a) && a instanceof SCMRevisionState) { scmActions.add(a); - revisionState.add(scm.getClass().getName(), (SCMRevisionState) a); + revisionState.add(scm, workspace, build, (SCMRevisionState) a); } } String subLogText = FileUtils.readFileToString(subChangeLog); logWriter.write(String.format("<%s scm=\"%s\">\n<![CDATA[%s]]>\n</%s>\n", MultiSCMChangeLogParser.SUB_LOG_TAG, scm.getType(), subLogText, MultiSCMChangeLogParser.SUB_LOG_TAG)); subChangeLog.delete(); } logWriter.write(String.format("</%s>\n", MultiSCMChangeLogParser.ROOT_XML_TAG)); logWriter.close(); return checkoutOK; } @Override public FilePath[] getModuleRoots(FilePath workspace, AbstractBuild build) { ArrayList<FilePath> paths = new ArrayList<FilePath>(); for(SCM scm : scms) { FilePath[] p = scm.getModuleRoots(workspace, build); for(FilePath p2 : p) paths.add(p2); } return paths.toArray(new FilePath[paths.size()]); } @Override public ChangeLogParser createChangeLogParser() { return new MultiSCMChangeLogParser(scms.toList()); } public void save() throws IOException { // TODO Auto-generated method stub } @Extension // this marker indicates Hudson that this is an implementation of an extension point. public static final class DescriptorImpl extends SCMDescriptor<MultiSCM> { public DescriptorImpl() { super(MultiSCMRepositoryBrowser.class); // TODO Auto-generated constructor stub } public List<SCMDescriptor<?>> getApplicableSCMs(AbstractProject<?, ?> project) { List<SCMDescriptor<?>> scms = new ArrayList<SCMDescriptor<?>>(); for(SCMDescriptor<?> scm : SCM._for(project)) { // Filter MultiSCM itself from the list of choices. // Theoretically it might work, but I see no practical reason to allow // nested MultiSCM configurations. if(!(scm instanceof DescriptorImpl) && !(scm instanceof NullSCM.DescriptorImpl)) scms.add(scm); } return scms; } /** * This human readable name is used in the configuration screen. */ public String getDisplayName() { return "Multiple SCMs"; } @Override public boolean configure(StaplerRequest req, JSONObject formData) throws FormException { save(); return super.configure(req,formData); } @Override public SCM newInstance(StaplerRequest req, JSONObject formData) throws FormException { return super.newInstance(req, formData); } } }
true
true
public boolean checkout(AbstractBuild<?, ?> build, Launcher launcher, FilePath workspace, BuildListener listener, File changelogFile) throws IOException, InterruptedException { MultiSCMRevisionState revisionState = new MultiSCMRevisionState(); build.addAction(revisionState); HashSet<Object> scmActions = new HashSet<Object>(); FileOutputStream logStream = new FileOutputStream(changelogFile); OutputStreamWriter logWriter = new OutputStreamWriter(logStream); logWriter.write(String.format("<%s>\n", MultiSCMChangeLogParser.ROOT_XML_TAG)); boolean checkoutOK = true; for(SCM scm : scms) { String changeLogPath = changelogFile.getPath() + ".temp"; File subChangeLog = new File(changeLogPath); checkoutOK = scm.checkout(build, launcher, workspace, listener, subChangeLog) && checkoutOK; List<Action> actions = build.getActions(); for(Action a : actions) { if(!scmActions.contains(a) && a instanceof SCMRevisionState) { scmActions.add(a); revisionState.add(scm.getClass().getName(), (SCMRevisionState) a); } } String subLogText = FileUtils.readFileToString(subChangeLog); logWriter.write(String.format("<%s scm=\"%s\">\n<![CDATA[%s]]>\n</%s>\n", MultiSCMChangeLogParser.SUB_LOG_TAG, scm.getType(), subLogText, MultiSCMChangeLogParser.SUB_LOG_TAG)); subChangeLog.delete(); } logWriter.write(String.format("</%s>\n", MultiSCMChangeLogParser.ROOT_XML_TAG)); logWriter.close(); return checkoutOK; }
public boolean checkout(AbstractBuild<?, ?> build, Launcher launcher, FilePath workspace, BuildListener listener, File changelogFile) throws IOException, InterruptedException { MultiSCMRevisionState revisionState = new MultiSCMRevisionState(); build.addAction(revisionState); HashSet<Object> scmActions = new HashSet<Object>(); FileOutputStream logStream = new FileOutputStream(changelogFile); OutputStreamWriter logWriter = new OutputStreamWriter(logStream); logWriter.write(String.format("<%s>\n", MultiSCMChangeLogParser.ROOT_XML_TAG)); boolean checkoutOK = true; for(SCM scm : scms) { String changeLogPath = changelogFile.getPath() + ".temp"; File subChangeLog = new File(changeLogPath); checkoutOK = scm.checkout(build, launcher, workspace, listener, subChangeLog) && checkoutOK; List<Action> actions = build.getActions(); for(Action a : actions) { if(!scmActions.contains(a) && a instanceof SCMRevisionState) { scmActions.add(a); revisionState.add(scm, workspace, build, (SCMRevisionState) a); } } String subLogText = FileUtils.readFileToString(subChangeLog); logWriter.write(String.format("<%s scm=\"%s\">\n<![CDATA[%s]]>\n</%s>\n", MultiSCMChangeLogParser.SUB_LOG_TAG, scm.getType(), subLogText, MultiSCMChangeLogParser.SUB_LOG_TAG)); subChangeLog.delete(); } logWriter.write(String.format("</%s>\n", MultiSCMChangeLogParser.ROOT_XML_TAG)); logWriter.close(); return checkoutOK; }
diff --git a/hangeulreader/src/se/iroiro/md/hangeulreader/HangeulReaderTest.java b/hangeulreader/src/se/iroiro/md/hangeulreader/HangeulReaderTest.java index 5bf25ab..07d973a 100644 --- a/hangeulreader/src/se/iroiro/md/hangeulreader/HangeulReaderTest.java +++ b/hangeulreader/src/se/iroiro/md/hangeulreader/HangeulReaderTest.java @@ -1,134 +1,134 @@ /** * */ package se.iroiro.md.hangeulreader; import java.awt.Font; import java.text.DateFormat; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.Date; import se.iroiro.md.hangeul.CharacterRenderer; import se.iroiro.md.hangeul.Hangeul; import se.iroiro.md.hangeul.HangeulClassifier; import se.iroiro.md.hangeul.JamoReferenceDB; /** * This class tests the classifier and displays results. * @author j * */ public class HangeulReaderTest { public static final int CHARSIZE = 200; private String makeString(char from, char to){ StringBuilder s = new StringBuilder(); for(char c = from; c <= to; c++){ s.append(c); } return s.toString(); } public String testAll(Font font, JamoReferenceDB jrdb){ return test(makeString('\uAC00','\uD7A3'), font, jrdb); } public String test(char from, char to, Font font, JamoReferenceDB jrdb){ return test(makeString(from,to), font, jrdb); } public String test(String characters, Font font, JamoReferenceDB jrdb){ - DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd H:m:ss"); + DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); StringBuilder result = new StringBuilder(); result.append("Character images rendered using font \""+font.getName()+"\" at "+CHARSIZE+"x"+CHARSIZE+" pixels.\n"); result.append("Test started: "+dateFormat.format(new Date())+"\n"); System.out.println("Preparing to scan " + (int) (characters.length()) + " characters."); HangeulClassifier hc = new HangeulClassifier(jrdb); StringBuilder matches = new StringBuilder(); StringBuilder misses = new StringBuilder(); int count = 0; boolean isMatch; System.out.println("Classifying characters rendered from font \""+font.getName()+"\"."); System.out.println("Circle (o) means a character was correctly classified,\ndash (-) means it was incorrectly classified."); for(int nn = 0; nn < characters.length(); nn++){ // CharacterRenderer.makeCharacterImage(c, CHARSIZE, CHARSIZE); char c = characters.charAt(nn); hc.newClassification(CharacterRenderer.makeCharacterImage(c, CHARSIZE, CHARSIZE, font)); Hangeul h = hc.getHangeul(); if(h != null && h.toString().charAt(0) == c){ isMatch = true; matches.append(c); }else{ isMatch = false; // if(h != null){ // misses.append(String.valueOf(c)+"-"+h.toString()+" "); // }else{ // misses.append(String.valueOf(c)+"-? "); // } misses.append(c); } if(count >= 100){ count = 0; System.out.println(); } count++; if(isMatch) System.out.print("o"); if(!isMatch) System.out.print("-"); } System.out.println(); System.out.println(); DecimalFormat df = new DecimalFormat("0.##"); int matchesc = matches.length(); result.append("Test finished: "+dateFormat.format(new Date())+"\n\n"); result.append(matchesc + " correct out of " + characters.length() + " characters (" + df.format(((matchesc*100)/(characters.length())))+" %).\n\n"); result.append("Correctly classified characters:\n"); int counter = 0; for(int i = 0; i < matches.length(); i++){ char c = matches.charAt(i); result.append(c); // Helper.p(c); if(++counter >= 80){ counter = 0; // result.append("\n"); // System.out.println(); } } result.append("\n"); // System.out.println(); if(misses.length() > 0){ result.append("\nMissed characters:\n"); // System.out.println(); // System.out.println("Missed characters:"); counter = 0; for(int i = 0; i < misses.length(); i++){ char c = misses.charAt(i); // Helper.p(c); result.append(c); if(++counter >= 80){ counter = 0; // System.out.println(); // result.append("\n"); } } // System.out.println(); } Helper.p("Done.\n"); return result.toString(); // Helper.dump(result.toString(), "/Users/j/Desktop/result.txt"); // System.out.println(); // System.out.println(); } // private void writeImage(BufferedImage img, String fileName){ // try{ // ImageIO.write(img, "png", new FileOutputStream(fileName)); // } catch (FileNotFoundException e) { // e.printStackTrace(); // } catch (IOException e) { // e.printStackTrace(); // } // } }
true
true
public String test(String characters, Font font, JamoReferenceDB jrdb){ DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd H:m:ss"); StringBuilder result = new StringBuilder(); result.append("Character images rendered using font \""+font.getName()+"\" at "+CHARSIZE+"x"+CHARSIZE+" pixels.\n"); result.append("Test started: "+dateFormat.format(new Date())+"\n"); System.out.println("Preparing to scan " + (int) (characters.length()) + " characters."); HangeulClassifier hc = new HangeulClassifier(jrdb); StringBuilder matches = new StringBuilder(); StringBuilder misses = new StringBuilder(); int count = 0; boolean isMatch; System.out.println("Classifying characters rendered from font \""+font.getName()+"\"."); System.out.println("Circle (o) means a character was correctly classified,\ndash (-) means it was incorrectly classified."); for(int nn = 0; nn < characters.length(); nn++){ // CharacterRenderer.makeCharacterImage(c, CHARSIZE, CHARSIZE); char c = characters.charAt(nn); hc.newClassification(CharacterRenderer.makeCharacterImage(c, CHARSIZE, CHARSIZE, font)); Hangeul h = hc.getHangeul(); if(h != null && h.toString().charAt(0) == c){ isMatch = true; matches.append(c); }else{ isMatch = false; // if(h != null){ // misses.append(String.valueOf(c)+"-"+h.toString()+" "); // }else{ // misses.append(String.valueOf(c)+"-? "); // } misses.append(c); } if(count >= 100){ count = 0; System.out.println(); } count++; if(isMatch) System.out.print("o"); if(!isMatch) System.out.print("-"); } System.out.println(); System.out.println(); DecimalFormat df = new DecimalFormat("0.##"); int matchesc = matches.length(); result.append("Test finished: "+dateFormat.format(new Date())+"\n\n"); result.append(matchesc + " correct out of " + characters.length() + " characters (" + df.format(((matchesc*100)/(characters.length())))+" %).\n\n"); result.append("Correctly classified characters:\n"); int counter = 0; for(int i = 0; i < matches.length(); i++){ char c = matches.charAt(i); result.append(c); // Helper.p(c); if(++counter >= 80){ counter = 0; // result.append("\n"); // System.out.println(); } } result.append("\n"); // System.out.println(); if(misses.length() > 0){ result.append("\nMissed characters:\n"); // System.out.println(); // System.out.println("Missed characters:"); counter = 0; for(int i = 0; i < misses.length(); i++){ char c = misses.charAt(i); // Helper.p(c); result.append(c); if(++counter >= 80){ counter = 0; // System.out.println(); // result.append("\n"); } } // System.out.println(); } Helper.p("Done.\n"); return result.toString(); // Helper.dump(result.toString(), "/Users/j/Desktop/result.txt"); // System.out.println(); // System.out.println(); }
public String test(String characters, Font font, JamoReferenceDB jrdb){ DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); StringBuilder result = new StringBuilder(); result.append("Character images rendered using font \""+font.getName()+"\" at "+CHARSIZE+"x"+CHARSIZE+" pixels.\n"); result.append("Test started: "+dateFormat.format(new Date())+"\n"); System.out.println("Preparing to scan " + (int) (characters.length()) + " characters."); HangeulClassifier hc = new HangeulClassifier(jrdb); StringBuilder matches = new StringBuilder(); StringBuilder misses = new StringBuilder(); int count = 0; boolean isMatch; System.out.println("Classifying characters rendered from font \""+font.getName()+"\"."); System.out.println("Circle (o) means a character was correctly classified,\ndash (-) means it was incorrectly classified."); for(int nn = 0; nn < characters.length(); nn++){ // CharacterRenderer.makeCharacterImage(c, CHARSIZE, CHARSIZE); char c = characters.charAt(nn); hc.newClassification(CharacterRenderer.makeCharacterImage(c, CHARSIZE, CHARSIZE, font)); Hangeul h = hc.getHangeul(); if(h != null && h.toString().charAt(0) == c){ isMatch = true; matches.append(c); }else{ isMatch = false; // if(h != null){ // misses.append(String.valueOf(c)+"-"+h.toString()+" "); // }else{ // misses.append(String.valueOf(c)+"-? "); // } misses.append(c); } if(count >= 100){ count = 0; System.out.println(); } count++; if(isMatch) System.out.print("o"); if(!isMatch) System.out.print("-"); } System.out.println(); System.out.println(); DecimalFormat df = new DecimalFormat("0.##"); int matchesc = matches.length(); result.append("Test finished: "+dateFormat.format(new Date())+"\n\n"); result.append(matchesc + " correct out of " + characters.length() + " characters (" + df.format(((matchesc*100)/(characters.length())))+" %).\n\n"); result.append("Correctly classified characters:\n"); int counter = 0; for(int i = 0; i < matches.length(); i++){ char c = matches.charAt(i); result.append(c); // Helper.p(c); if(++counter >= 80){ counter = 0; // result.append("\n"); // System.out.println(); } } result.append("\n"); // System.out.println(); if(misses.length() > 0){ result.append("\nMissed characters:\n"); // System.out.println(); // System.out.println("Missed characters:"); counter = 0; for(int i = 0; i < misses.length(); i++){ char c = misses.charAt(i); // Helper.p(c); result.append(c); if(++counter >= 80){ counter = 0; // System.out.println(); // result.append("\n"); } } // System.out.println(); } Helper.p("Done.\n"); return result.toString(); // Helper.dump(result.toString(), "/Users/j/Desktop/result.txt"); // System.out.println(); // System.out.println(); }
diff --git a/api/src/main/java/org/jboss/marshalling/reflect/SerializableField.java b/api/src/main/java/org/jboss/marshalling/reflect/SerializableField.java index dfe86bf..701ee18 100644 --- a/api/src/main/java/org/jboss/marshalling/reflect/SerializableField.java +++ b/api/src/main/java/org/jboss/marshalling/reflect/SerializableField.java @@ -1,170 +1,170 @@ /* * JBoss, Home of Professional Open Source * Copyright 2008, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.marshalling.reflect; import java.lang.ref.WeakReference; import java.lang.reflect.Field; import java.util.concurrent.atomic.AtomicReference; import java.security.AccessController; import java.security.PrivilegedAction; import org.jboss.marshalling.util.Kind; /** * Reflection information about a field on a serializable class. */ public final class SerializableField { // the class that the field is attached to private final WeakReference<Class<?>> classRef; // the type of the field itself private final WeakReference<Class<?>> typeRef; private final AtomicReference<WeakReference<Field>> fieldRefRef = new AtomicReference<WeakReference<Field>>(); private final String name; private final boolean unshared; private final Kind kind; private volatile boolean missing; SerializableField(Class<?> clazz, Class<?> type, String name, boolean unshared) { classRef = new WeakReference<Class<?>>(clazz); typeRef = new WeakReference<Class<?>>(type); this.name = name; this.unshared = unshared; // todo - see if a small Map is faster if (type == boolean.class) { kind = Kind.BOOLEAN; } else if (type == byte.class) { kind = Kind.BYTE; } else if (type == short.class) { kind = Kind.SHORT; } else if (type == int.class) { kind = Kind.INT; } else if (type == long.class) { kind = Kind.LONG; } else if (type == char.class) { kind = Kind.CHAR; } else if (type == float.class) { kind = Kind.FLOAT; } else if (type == double.class) { kind = Kind.DOUBLE; } else { kind = Kind.OBJECT; } } private Field lookupField() { if (missing) { return null; } final Class<?> clazz = classRef.get(); if (clazz != null) { return AccessController.doPrivileged(new PrivilegedAction<Field>() { public Field run() { try { return clazz.getDeclaredField(name); } catch (NoSuchFieldException e) { missing = true; return null; } } }); } else { throw new IllegalStateException("Class unloaded"); } } /** * Get the reflection {@code Field} for this serializable field. The resultant field will be accessible. * * @return the reflection field */ public Field getField() { final WeakReference<Field> fieldRef = fieldRefRef.get(); if (fieldRef == null) { final Field field = lookupField(); if (field != null) { fieldRefRef.compareAndSet(null, new WeakReference<Field>(field)); + AccessController.doPrivileged(new PrivilegedAction<Void>() { + public Void run() { + field.setAccessible(true); + return null; + } + }); } - AccessController.doPrivileged(new PrivilegedAction<Void>() { - public Void run() { - field.setAccessible(true); - return null; - } - }); return field; } else { final Field field = fieldRef.get(); if (field != null) { return field; } return AccessController.doPrivileged(new PrivilegedAction<Field>() { public Field run() { final Field newField = lookupField(); final WeakReference<Field> newFieldRef; if (newField == null) { newFieldRef = null; } else { newField.setAccessible(true); newFieldRef = new WeakReference<Field>(newField); } fieldRefRef.compareAndSet(fieldRef, newFieldRef); return newField; } }); } } /** * Get the name of the field. * * @return the name */ public String getName() { return name; } /** * Determine whether this field is marked as "unshared". * * @return {@code true} if the field is unshared */ public boolean isUnshared() { return unshared; } /** * Get the kind of field. * * @return the kind */ public Kind getKind() { return kind; } /** * Get the field type. * * @return the field type */ public Class<?> getType() throws ClassNotFoundException { return SerializableClass.dereference(typeRef); } }
false
true
public Field getField() { final WeakReference<Field> fieldRef = fieldRefRef.get(); if (fieldRef == null) { final Field field = lookupField(); if (field != null) { fieldRefRef.compareAndSet(null, new WeakReference<Field>(field)); } AccessController.doPrivileged(new PrivilegedAction<Void>() { public Void run() { field.setAccessible(true); return null; } }); return field; } else { final Field field = fieldRef.get(); if (field != null) { return field; } return AccessController.doPrivileged(new PrivilegedAction<Field>() { public Field run() { final Field newField = lookupField(); final WeakReference<Field> newFieldRef; if (newField == null) { newFieldRef = null; } else { newField.setAccessible(true); newFieldRef = new WeakReference<Field>(newField); } fieldRefRef.compareAndSet(fieldRef, newFieldRef); return newField; } }); } }
public Field getField() { final WeakReference<Field> fieldRef = fieldRefRef.get(); if (fieldRef == null) { final Field field = lookupField(); if (field != null) { fieldRefRef.compareAndSet(null, new WeakReference<Field>(field)); AccessController.doPrivileged(new PrivilegedAction<Void>() { public Void run() { field.setAccessible(true); return null; } }); } return field; } else { final Field field = fieldRef.get(); if (field != null) { return field; } return AccessController.doPrivileged(new PrivilegedAction<Field>() { public Field run() { final Field newField = lookupField(); final WeakReference<Field> newFieldRef; if (newField == null) { newFieldRef = null; } else { newField.setAccessible(true); newFieldRef = new WeakReference<Field>(newField); } fieldRefRef.compareAndSet(fieldRef, newFieldRef); return newField; } }); } }
diff --git a/plugins/org.eclipse.bpel.ui/src/org/eclipse/bpel/ui/editparts/BPELTrayAccessibleEditPart.java b/plugins/org.eclipse.bpel.ui/src/org/eclipse/bpel/ui/editparts/BPELTrayAccessibleEditPart.java index 6cc81d0c..9621cf92 100644 --- a/plugins/org.eclipse.bpel.ui/src/org/eclipse/bpel/ui/editparts/BPELTrayAccessibleEditPart.java +++ b/plugins/org.eclipse.bpel.ui/src/org/eclipse/bpel/ui/editparts/BPELTrayAccessibleEditPart.java @@ -1,58 +1,60 @@ /******************************************************************************* * 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.bpel.ui.editparts; import org.eclipse.bpel.common.ui.tray.TrayAccessibleEditPart; import org.eclipse.bpel.common.ui.tray.TrayEditPart; import org.eclipse.bpel.ui.adapters.ILabeledElement; import org.eclipse.bpel.ui.util.BPELUtil; import org.eclipse.swt.accessibility.AccessibleEvent; public class BPELTrayAccessibleEditPart extends TrayAccessibleEditPart { public BPELTrayAccessibleEditPart(TrayEditPart part) { super(part); } @Override public void getName(AccessibleEvent e) { String childType = null; String displayName = null; ILabeledElement labeledElement = BPELUtil.adapt(part.getModel(), ILabeledElement.class); if (labeledElement != null) { childType = labeledElement.getTypeLabel(part.getModel()); displayName = labeledElement.getLabel(part.getModel()); - if (childType != null && displayName.equals(childType)) { + // bug 327644 + // prevent possible NPE + if (childType != null && childType.equals(displayName)) { childType = null; } } else { e.result = null; return; } // return something reasonable (type followed by name if any) // or nothing at all StringBuffer concat = new StringBuffer(); if (childType != null && childType.length() > 0) concat.append(childType); if (concat.length() > 0) concat.append(" "); //$NON-NLS-1$ if (displayName != null && displayName.length() > 0) concat.append(displayName); if (concat.length() > 0) e.result = concat.toString(); else e.result = null; return; } }
true
true
public void getName(AccessibleEvent e) { String childType = null; String displayName = null; ILabeledElement labeledElement = BPELUtil.adapt(part.getModel(), ILabeledElement.class); if (labeledElement != null) { childType = labeledElement.getTypeLabel(part.getModel()); displayName = labeledElement.getLabel(part.getModel()); if (childType != null && displayName.equals(childType)) { childType = null; } } else { e.result = null; return; } // return something reasonable (type followed by name if any) // or nothing at all StringBuffer concat = new StringBuffer(); if (childType != null && childType.length() > 0) concat.append(childType); if (concat.length() > 0) concat.append(" "); //$NON-NLS-1$ if (displayName != null && displayName.length() > 0) concat.append(displayName); if (concat.length() > 0) e.result = concat.toString(); else e.result = null; return; }
public void getName(AccessibleEvent e) { String childType = null; String displayName = null; ILabeledElement labeledElement = BPELUtil.adapt(part.getModel(), ILabeledElement.class); if (labeledElement != null) { childType = labeledElement.getTypeLabel(part.getModel()); displayName = labeledElement.getLabel(part.getModel()); // bug 327644 // prevent possible NPE if (childType != null && childType.equals(displayName)) { childType = null; } } else { e.result = null; return; } // return something reasonable (type followed by name if any) // or nothing at all StringBuffer concat = new StringBuffer(); if (childType != null && childType.length() > 0) concat.append(childType); if (concat.length() > 0) concat.append(" "); //$NON-NLS-1$ if (displayName != null && displayName.length() > 0) concat.append(displayName); if (concat.length() > 0) e.result = concat.toString(); else e.result = null; return; }
diff --git a/org.orbisgis.geocatalog/src/main/java/org/orbisgis/geocatalog/Activator.java b/org.orbisgis.geocatalog/src/main/java/org/orbisgis/geocatalog/Activator.java index e5c185a24..79a8e83a1 100644 --- a/org.orbisgis.geocatalog/src/main/java/org/orbisgis/geocatalog/Activator.java +++ b/org.orbisgis.geocatalog/src/main/java/org/orbisgis/geocatalog/Activator.java @@ -1,62 +1,70 @@ package org.orbisgis.geocatalog; import java.util.ArrayList; import javax.swing.JOptionPane; import org.gdms.source.Source; import org.gdms.source.SourceManager; import org.orbisgis.CollectionUtils; import org.orbisgis.core.OrbisgisCore; import org.orbisgis.core.windows.EPWindowHelper; import org.orbisgis.geocatalog.resources.AbstractGdmsSource; import org.orbisgis.geocatalog.resources.IResource; import org.orbisgis.geocatalog.resources.NodeFilter; import org.orbisgis.pluginManager.PluginActivator; public class Activator implements PluginActivator { private ArrayList<String> memoryResources; public boolean allowStop() { GeoCatalog geoCatalog = (GeoCatalog) EPWindowHelper .getWindows("org.orbisgis.geocatalog.Window")[0]; Catalog catalog = geoCatalog.getCatalog(); IResource[] res = catalog.getTreeModel().getNodes(new NodeFilter() { public boolean accept(IResource resource) { return true; } }); memoryResources = new ArrayList<String>(); SourceManager sm = OrbisgisCore.getDSF().getSourceManager(); for (IResource resource : res) { if (resource.getResourceType() instanceof AbstractGdmsSource) { Source src = sm.getSource(resource.getName()); if ((src.getType() & SourceManager.MEMORY) == SourceManager.MEMORY) { memoryResources.add(src.getName()); } } } - String resourceList = CollectionUtils.getCommaSeparated(memoryResources - .toArray(new String[0])); + if (memoryResources.size() > 0) { + String resourceList = CollectionUtils + .getCommaSeparated(memoryResources.toArray(new String[0])); - int exit = JOptionPane.showConfirmDialog(catalog, - "The following resources are stored " - + "in memory and its content may be lost: \n" - + resourceList + ".\nDo you want to exit" - + " and probably lose the content of those sources?", - "Loose object resources?", JOptionPane.YES_NO_OPTION); + int exit = JOptionPane + .showConfirmDialog( + catalog, + "The following resources are stored " + + "in memory and its content may be lost: \n" + + resourceList + + ".\nDo you want to exit" + + " and probably lose the content of those sources?", + "Loose object resources?", + JOptionPane.YES_NO_OPTION); - return exit == JOptionPane.YES_OPTION; + return exit == JOptionPane.YES_OPTION; + } else { + return true; + } } public void start() throws Exception { } public void stop() throws Exception { } }
false
true
public boolean allowStop() { GeoCatalog geoCatalog = (GeoCatalog) EPWindowHelper .getWindows("org.orbisgis.geocatalog.Window")[0]; Catalog catalog = geoCatalog.getCatalog(); IResource[] res = catalog.getTreeModel().getNodes(new NodeFilter() { public boolean accept(IResource resource) { return true; } }); memoryResources = new ArrayList<String>(); SourceManager sm = OrbisgisCore.getDSF().getSourceManager(); for (IResource resource : res) { if (resource.getResourceType() instanceof AbstractGdmsSource) { Source src = sm.getSource(resource.getName()); if ((src.getType() & SourceManager.MEMORY) == SourceManager.MEMORY) { memoryResources.add(src.getName()); } } } String resourceList = CollectionUtils.getCommaSeparated(memoryResources .toArray(new String[0])); int exit = JOptionPane.showConfirmDialog(catalog, "The following resources are stored " + "in memory and its content may be lost: \n" + resourceList + ".\nDo you want to exit" + " and probably lose the content of those sources?", "Loose object resources?", JOptionPane.YES_NO_OPTION); return exit == JOptionPane.YES_OPTION; }
public boolean allowStop() { GeoCatalog geoCatalog = (GeoCatalog) EPWindowHelper .getWindows("org.orbisgis.geocatalog.Window")[0]; Catalog catalog = geoCatalog.getCatalog(); IResource[] res = catalog.getTreeModel().getNodes(new NodeFilter() { public boolean accept(IResource resource) { return true; } }); memoryResources = new ArrayList<String>(); SourceManager sm = OrbisgisCore.getDSF().getSourceManager(); for (IResource resource : res) { if (resource.getResourceType() instanceof AbstractGdmsSource) { Source src = sm.getSource(resource.getName()); if ((src.getType() & SourceManager.MEMORY) == SourceManager.MEMORY) { memoryResources.add(src.getName()); } } } if (memoryResources.size() > 0) { String resourceList = CollectionUtils .getCommaSeparated(memoryResources.toArray(new String[0])); int exit = JOptionPane .showConfirmDialog( catalog, "The following resources are stored " + "in memory and its content may be lost: \n" + resourceList + ".\nDo you want to exit" + " and probably lose the content of those sources?", "Loose object resources?", JOptionPane.YES_NO_OPTION); return exit == JOptionPane.YES_OPTION; } else { return true; } }
diff --git a/src/main/java/de/cismet/security/exceptions/AuthenticationCanceledException.java b/src/main/java/de/cismet/security/exceptions/AuthenticationCanceledException.java index 28426f6..92e5568 100644 --- a/src/main/java/de/cismet/security/exceptions/AuthenticationCanceledException.java +++ b/src/main/java/de/cismet/security/exceptions/AuthenticationCanceledException.java @@ -1,27 +1,27 @@ /* * AuthenticationCanceledException.java * * Created on 19. Oktober 2006, 09:19 * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package de.cismet.security.exceptions; /** * * @author Sebastian */ public class AuthenticationCanceledException extends Exception { /** Creates a new instance of AuthenticationCanceledException */ public AuthenticationCanceledException() { - super(java.util.ResourceBundle.getBundle("de/cismet/cismap/commons/GuiBundle").getString("Exception.AuthenticationCanceledException")); + super("The HTTP authentication was canceled by user"); } public AuthenticationCanceledException(String message) { super(message); } }
true
true
public AuthenticationCanceledException() { super(java.util.ResourceBundle.getBundle("de/cismet/cismap/commons/GuiBundle").getString("Exception.AuthenticationCanceledException")); }
public AuthenticationCanceledException() { super("The HTTP authentication was canceled by user"); }
diff --git a/src/main/java/com/cgbystrom/Server.java b/src/main/java/com/cgbystrom/Server.java index 1d76026..fdfaaaf 100644 --- a/src/main/java/com/cgbystrom/Server.java +++ b/src/main/java/com/cgbystrom/Server.java @@ -1,77 +1,77 @@ package com.cgbystrom; import org.jboss.netty.bootstrap.ServerBootstrap; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.channel.*; import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; import org.jboss.netty.handler.codec.http.*; import org.jboss.netty.util.CharsetUtil; import java.net.InetSocketAddress; import java.util.concurrent.Executors; import static org.jboss.netty.channel.Channels.pipeline; public class Server { public static class HttpHandler extends SimpleChannelUpstreamHandler { private static final ChannelBuffer HELLO_WORLD = ChannelBuffers.copiedBuffer("Hello world!", CharsetUtil.UTF_8); @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { HttpRequest request = (HttpRequest) e.getMessage(); HttpResponse response = new DefaultHttpResponse(request.getProtocolVersion(), HttpResponseStatus.OK); response.setContent(HELLO_WORLD); response.addHeader(HttpHeaders.Names.CONTENT_LENGTH, response.getContent().readableBytes()); if (HttpHeaders.isKeepAlive(request)) { if (request.getProtocolVersion() == HttpVersion.HTTP_1_0) { response.addHeader(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE); } e.getChannel().write(response); } else { e.getChannel().write(response).addListener(ChannelFutureListener.CLOSE); } } } public static void main(String[] args) { final HttpHandler handler = new HttpHandler(); int numThreads = 2 * Runtime.getRuntime().availableProcessors(); int backlog = 128; int port = 8080; if (System.getProperty("threads") != null) numThreads = Integer.valueOf(System.getProperty("threads")); if (System.getProperty("backlog") != null) - numThreads = Integer.valueOf(System.getProperty("backlog")); + backlog = Integer.valueOf(System.getProperty("backlog")); if (System.getProperty("port") != null) port = Integer.valueOf(System.getProperty("port")); System.out.println("Threads: " + numThreads + " (set with -Dthreads=8)"); System.out.println("Backlog: " + backlog + " (set with -Dbacklog=128)"); System.out.println(" Port: " + port + " (set with -Dport=8080)"); ServerBootstrap bootstrap = new ServerBootstrap( new NioServerSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool(), numThreads)); bootstrap.setPipelineFactory(new ChannelPipelineFactory() { @Override public ChannelPipeline getPipeline() throws Exception { ChannelPipeline pipeline = pipeline(); pipeline.addLast("decoder", new HttpRequestDecoder()); pipeline.addLast("encoder", new HttpResponseEncoder()); pipeline.addLast("handler", handler); return pipeline; } }); bootstrap.bind(new InetSocketAddress(8080)); System.out.println("Server running.."); } }
true
true
public static void main(String[] args) { final HttpHandler handler = new HttpHandler(); int numThreads = 2 * Runtime.getRuntime().availableProcessors(); int backlog = 128; int port = 8080; if (System.getProperty("threads") != null) numThreads = Integer.valueOf(System.getProperty("threads")); if (System.getProperty("backlog") != null) numThreads = Integer.valueOf(System.getProperty("backlog")); if (System.getProperty("port") != null) port = Integer.valueOf(System.getProperty("port")); System.out.println("Threads: " + numThreads + " (set with -Dthreads=8)"); System.out.println("Backlog: " + backlog + " (set with -Dbacklog=128)"); System.out.println(" Port: " + port + " (set with -Dport=8080)"); ServerBootstrap bootstrap = new ServerBootstrap( new NioServerSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool(), numThreads)); bootstrap.setPipelineFactory(new ChannelPipelineFactory() { @Override public ChannelPipeline getPipeline() throws Exception { ChannelPipeline pipeline = pipeline(); pipeline.addLast("decoder", new HttpRequestDecoder()); pipeline.addLast("encoder", new HttpResponseEncoder()); pipeline.addLast("handler", handler); return pipeline; } }); bootstrap.bind(new InetSocketAddress(8080)); System.out.println("Server running.."); }
public static void main(String[] args) { final HttpHandler handler = new HttpHandler(); int numThreads = 2 * Runtime.getRuntime().availableProcessors(); int backlog = 128; int port = 8080; if (System.getProperty("threads") != null) numThreads = Integer.valueOf(System.getProperty("threads")); if (System.getProperty("backlog") != null) backlog = Integer.valueOf(System.getProperty("backlog")); if (System.getProperty("port") != null) port = Integer.valueOf(System.getProperty("port")); System.out.println("Threads: " + numThreads + " (set with -Dthreads=8)"); System.out.println("Backlog: " + backlog + " (set with -Dbacklog=128)"); System.out.println(" Port: " + port + " (set with -Dport=8080)"); ServerBootstrap bootstrap = new ServerBootstrap( new NioServerSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool(), numThreads)); bootstrap.setPipelineFactory(new ChannelPipelineFactory() { @Override public ChannelPipeline getPipeline() throws Exception { ChannelPipeline pipeline = pipeline(); pipeline.addLast("decoder", new HttpRequestDecoder()); pipeline.addLast("encoder", new HttpResponseEncoder()); pipeline.addLast("handler", handler); return pipeline; } }); bootstrap.bind(new InetSocketAddress(8080)); System.out.println("Server running.."); }
diff --git a/src/com/android/settings/ChooseLockGeneric.java b/src/com/android/settings/ChooseLockGeneric.java index d589aa3d2..ea15f9e6e 100644 --- a/src/com/android/settings/ChooseLockGeneric.java +++ b/src/com/android/settings/ChooseLockGeneric.java @@ -1,362 +1,360 @@ /* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.settings; import android.app.Activity; import android.app.PendingIntent; import android.app.admin.DevicePolicyManager; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.preference.Preference; import android.preference.PreferenceActivity; import android.preference.PreferenceScreen; import android.security.KeyStore; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; import com.android.internal.widget.LockPatternUtils; public class ChooseLockGeneric extends PreferenceActivity { @Override public Intent getIntent() { Intent modIntent = new Intent(super.getIntent()); modIntent.putExtra(EXTRA_SHOW_FRAGMENT, ChooseLockGenericFragment.class.getName()); modIntent.putExtra(EXTRA_NO_HEADERS, true); return modIntent; } public static class ChooseLockGenericFragment extends SettingsPreferenceFragment { private static final int MIN_PASSWORD_LENGTH = 4; private static final String KEY_UNLOCK_BACKUP_INFO = "unlock_backup_info"; private static final String KEY_UNLOCK_SET_OFF = "unlock_set_off"; private static final String KEY_UNLOCK_SET_NONE = "unlock_set_none"; private static final String KEY_UNLOCK_SET_BIOMETRIC_WEAK = "unlock_set_biometric_weak"; private static final String KEY_UNLOCK_SET_PIN = "unlock_set_pin"; private static final String KEY_UNLOCK_SET_PASSWORD = "unlock_set_password"; private static final String KEY_UNLOCK_SET_PATTERN = "unlock_set_pattern"; private static final int CONFIRM_EXISTING_REQUEST = 100; private static final int FALLBACK_REQUEST = 101; private static final String PASSWORD_CONFIRMED = "password_confirmed"; private static final String CONFIRM_CREDENTIALS = "confirm_credentials"; public static final String MINIMUM_QUALITY_KEY = "minimum_quality"; private ChooseLockSettingsHelper mChooseLockSettingsHelper; private DevicePolicyManager mDPM; private KeyStore mKeyStore; private boolean mPasswordConfirmed = false; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mDPM = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE); mKeyStore = KeyStore.getInstance(); mChooseLockSettingsHelper = new ChooseLockSettingsHelper(this.getActivity()); // Defaults to needing to confirm credentials final boolean confirmCredentials = getActivity().getIntent() .getBooleanExtra(CONFIRM_CREDENTIALS, true); mPasswordConfirmed = !confirmCredentials; if (savedInstanceState != null) { mPasswordConfirmed = savedInstanceState.getBoolean(PASSWORD_CONFIRMED); } if (!mPasswordConfirmed) { ChooseLockSettingsHelper helper = new ChooseLockSettingsHelper(this.getActivity(), this); if (!helper.launchConfirmationActivity(CONFIRM_EXISTING_REQUEST, null, null)) { mPasswordConfirmed = true; // no password set, so no need to confirm updatePreferencesOrFinish(); } } else { updatePreferencesOrFinish(); } } @Override public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) { final String key = preference.getKey(); boolean handled = true; if (KEY_UNLOCK_SET_OFF.equals(key)) { updateUnlockMethodAndFinish( DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED, true); } else if (KEY_UNLOCK_SET_NONE.equals(key)) { updateUnlockMethodAndFinish( DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED, false); } else if (KEY_UNLOCK_SET_BIOMETRIC_WEAK.equals(key)) { updateUnlockMethodAndFinish( DevicePolicyManager.PASSWORD_QUALITY_BIOMETRIC_WEAK, false); }else if (KEY_UNLOCK_SET_PATTERN.equals(key)) { updateUnlockMethodAndFinish( DevicePolicyManager.PASSWORD_QUALITY_SOMETHING, false); } else if (KEY_UNLOCK_SET_PIN.equals(key)) { updateUnlockMethodAndFinish( DevicePolicyManager.PASSWORD_QUALITY_NUMERIC, false); } else if (KEY_UNLOCK_SET_PASSWORD.equals(key)) { updateUnlockMethodAndFinish( DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC, false); } else { handled = false; } return handled; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = super.onCreateView(inflater, container, savedInstanceState); final boolean onlyShowFallback = getActivity().getIntent() .getBooleanExtra(LockPatternUtils.LOCKSCREEN_BIOMETRIC_WEAK_FALLBACK, false); if (onlyShowFallback) { View header = v.inflate(getActivity(), R.layout.weak_biometric_fallback_header, null); ((ListView) v.findViewById(android.R.id.list)).addHeaderView(header, null, false); } return v; } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == CONFIRM_EXISTING_REQUEST && resultCode == Activity.RESULT_OK) { mPasswordConfirmed = true; updatePreferencesOrFinish(); } else if(requestCode == FALLBACK_REQUEST) { mChooseLockSettingsHelper.utils().deleteTempGallery(); getActivity().setResult(resultCode); finish(); } else { getActivity().setResult(Activity.RESULT_CANCELED); finish(); } } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); // Saved so we don't force user to re-enter their password if configuration changes outState.putBoolean(PASSWORD_CONFIRMED, mPasswordConfirmed); } private void updatePreferencesOrFinish() { Intent intent = getActivity().getIntent(); int quality = intent.getIntExtra(LockPatternUtils.PASSWORD_TYPE_KEY, -1); if (quality == -1) { // If caller didn't specify password quality, show UI and allow the user to choose. quality = intent.getIntExtra(MINIMUM_QUALITY_KEY, -1); quality = upgradeQuality(quality); final PreferenceScreen prefScreen = getPreferenceScreen(); if (prefScreen != null) { prefScreen.removeAll(); } addPreferencesFromResource(R.xml.security_settings_picker); disableUnusablePreferences(quality); } else { updateUnlockMethodAndFinish(quality, false); } } private int upgradeQuality(int quality) { quality = upgradeQualityForDPM(quality); quality = upgradeQualityForEncryption(quality); quality = upgradeQualityForKeyStore(quality); return quality; } private int upgradeQualityForDPM(int quality) { // Compare min allowed password quality int minQuality = mDPM.getPasswordQuality(null); if (quality < minQuality) { quality = minQuality; } return quality; } /** * Mix in "encryption minimums" to any given quality value. This prevents users * from downgrading the pattern/pin/password to a level below the minimums. * * ASSUMPTION: Setting quality is sufficient (e.g. minimum lengths will be set * appropriately.) */ private int upgradeQualityForEncryption(int quality) { int encryptionStatus = mDPM.getStorageEncryptionStatus(); boolean encrypted = (encryptionStatus == DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE) || (encryptionStatus == DevicePolicyManager.ENCRYPTION_STATUS_ACTIVATING); if (encrypted) { if (quality < CryptKeeperSettings.MIN_PASSWORD_QUALITY) { quality = CryptKeeperSettings.MIN_PASSWORD_QUALITY; } } return quality; } private int upgradeQualityForKeyStore(int quality) { if (!mKeyStore.isEmpty()) { if (quality < CredentialStorage.MIN_PASSWORD_QUALITY) { quality = CredentialStorage.MIN_PASSWORD_QUALITY; } } return quality; } /*** * Disables preferences that are less secure than required quality. * * @param quality the requested quality. */ private void disableUnusablePreferences(final int quality) { final PreferenceScreen entries = getPreferenceScreen(); final boolean onlyShowFallback = getActivity().getIntent() .getBooleanExtra(LockPatternUtils.LOCKSCREEN_BIOMETRIC_WEAK_FALLBACK, false); final boolean weakBiometricAvailable = mChooseLockSettingsHelper.utils().isBiometricWeakInstalled(); for (int i = entries.getPreferenceCount() - 1; i >= 0; --i) { Preference pref = entries.getPreference(i); if (pref instanceof PreferenceScreen) { final String key = ((PreferenceScreen) pref).getKey(); boolean enabled = true; boolean visible = true; if (KEY_UNLOCK_SET_OFF.equals(key)) { enabled = quality <= DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED; } else if (KEY_UNLOCK_SET_NONE.equals(key)) { enabled = quality <= DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED; } else if (KEY_UNLOCK_SET_BIOMETRIC_WEAK.equals(key)) { enabled = quality <= DevicePolicyManager.PASSWORD_QUALITY_BIOMETRIC_WEAK; visible = weakBiometricAvailable; // If not available, then don't show it. } else if (KEY_UNLOCK_SET_PATTERN.equals(key)) { enabled = quality <= DevicePolicyManager.PASSWORD_QUALITY_SOMETHING; } else if (KEY_UNLOCK_SET_PIN.equals(key)) { enabled = quality <= DevicePolicyManager.PASSWORD_QUALITY_NUMERIC; } else if (KEY_UNLOCK_SET_PASSWORD.equals(key)) { enabled = quality <= DevicePolicyManager.PASSWORD_QUALITY_COMPLEX; } if (!visible || (onlyShowFallback && !allowedForFallback(key))) { entries.removePreference(pref); } else if (!enabled) { pref.setSummary(R.string.unlock_set_unlock_disabled_summary); pref.setEnabled(false); } } } } /** * Check whether the key is allowed for fallback (e.g. bio sensor). Returns true if it's * supported as a backup. * * @param key * @return true if allowed */ private boolean allowedForFallback(String key) { return KEY_UNLOCK_BACKUP_INFO.equals(key) || KEY_UNLOCK_SET_PATTERN.equals(key) || KEY_UNLOCK_SET_PIN.equals(key); } private Intent getBiometricSensorIntent(int quality) { Intent fallBackIntent = new Intent().setClass(getActivity(), ChooseLockGeneric.class); fallBackIntent.putExtra(LockPatternUtils.LOCKSCREEN_BIOMETRIC_WEAK_FALLBACK, true); fallBackIntent.putExtra(CONFIRM_CREDENTIALS, false); fallBackIntent.putExtra(EXTRA_SHOW_FRAGMENT_TITLE, R.string.backup_lock_settings_picker_title); fallBackIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); Intent intent = new Intent().setClassName("com.android.facelock", "com.android.facelock.SetupFaceLock"); PendingIntent pending = PendingIntent.getActivity(getActivity(), 0, fallBackIntent, 0); intent.putExtra("PendingIntent", pending); return intent; } /** * Invokes an activity to change the user's pattern, password or PIN based on given quality * and minimum quality specified by DevicePolicyManager. If quality is * {@link DevicePolicyManager#PASSWORD_QUALITY_UNSPECIFIED}, password is cleared. * * @param quality the desired quality. Ignored if DevicePolicyManager requires more security * @param disabled whether or not to show LockScreen at all. Only meaningful when quality is * {@link DevicePolicyManager#PASSWORD_QUALITY_UNSPECIFIED} */ void updateUnlockMethodAndFinish(int quality, boolean disabled) { // Sanity check. We should never get here without confirming user's existing password. if (!mPasswordConfirmed) { throw new IllegalStateException("Tried to update password without confirming it"); } final boolean isFallback = getActivity().getIntent() .getBooleanExtra(LockPatternUtils.LOCKSCREEN_BIOMETRIC_WEAK_FALLBACK, false); quality = upgradeQuality(quality); if (quality >= DevicePolicyManager.PASSWORD_QUALITY_NUMERIC) { int minLength = mDPM.getPasswordMinimumLength(null); if (minLength < MIN_PASSWORD_LENGTH) { minLength = MIN_PASSWORD_LENGTH; } final int maxLength = mDPM.getPasswordMaximumLength(quality); Intent intent = new Intent().setClass(getActivity(), ChooseLockPassword.class); intent.putExtra(LockPatternUtils.PASSWORD_TYPE_KEY, quality); intent.putExtra(ChooseLockPassword.PASSWORD_MIN_KEY, minLength); intent.putExtra(ChooseLockPassword.PASSWORD_MAX_KEY, maxLength); intent.putExtra(CONFIRM_CREDENTIALS, false); intent.putExtra(LockPatternUtils.LOCKSCREEN_BIOMETRIC_WEAK_FALLBACK, isFallback); if(isFallback) { startActivityForResult(intent, FALLBACK_REQUEST); return; - } - else { + } else { intent.addFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT); startActivity(intent); } } else if (quality == DevicePolicyManager.PASSWORD_QUALITY_SOMETHING) { boolean showTutorial = !mChooseLockSettingsHelper.utils().isPatternEverChosen(); Intent intent = new Intent(); intent.setClass(getActivity(), showTutorial ? ChooseLockPatternTutorial.class : ChooseLockPattern.class); intent.putExtra("key_lock_method", "pattern"); intent.putExtra(CONFIRM_CREDENTIALS, false); intent.putExtra(LockPatternUtils.LOCKSCREEN_BIOMETRIC_WEAK_FALLBACK, isFallback); if(isFallback) { startActivityForResult(intent, FALLBACK_REQUEST); return; - } - else { + } else { intent.addFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT); startActivity(intent); } } else if (quality == DevicePolicyManager.PASSWORD_QUALITY_BIOMETRIC_WEAK) { Intent intent = getBiometricSensorIntent(quality); startActivity(intent); } else if (quality == DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED) { mChooseLockSettingsHelper.utils().clearLock(false); mChooseLockSettingsHelper.utils().setLockScreenDisabled(disabled); getActivity().setResult(Activity.RESULT_OK); } finish(); } } }
false
true
void updateUnlockMethodAndFinish(int quality, boolean disabled) { // Sanity check. We should never get here without confirming user's existing password. if (!mPasswordConfirmed) { throw new IllegalStateException("Tried to update password without confirming it"); } final boolean isFallback = getActivity().getIntent() .getBooleanExtra(LockPatternUtils.LOCKSCREEN_BIOMETRIC_WEAK_FALLBACK, false); quality = upgradeQuality(quality); if (quality >= DevicePolicyManager.PASSWORD_QUALITY_NUMERIC) { int minLength = mDPM.getPasswordMinimumLength(null); if (minLength < MIN_PASSWORD_LENGTH) { minLength = MIN_PASSWORD_LENGTH; } final int maxLength = mDPM.getPasswordMaximumLength(quality); Intent intent = new Intent().setClass(getActivity(), ChooseLockPassword.class); intent.putExtra(LockPatternUtils.PASSWORD_TYPE_KEY, quality); intent.putExtra(ChooseLockPassword.PASSWORD_MIN_KEY, minLength); intent.putExtra(ChooseLockPassword.PASSWORD_MAX_KEY, maxLength); intent.putExtra(CONFIRM_CREDENTIALS, false); intent.putExtra(LockPatternUtils.LOCKSCREEN_BIOMETRIC_WEAK_FALLBACK, isFallback); if(isFallback) { startActivityForResult(intent, FALLBACK_REQUEST); return; } else { intent.addFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT); startActivity(intent); } } else if (quality == DevicePolicyManager.PASSWORD_QUALITY_SOMETHING) { boolean showTutorial = !mChooseLockSettingsHelper.utils().isPatternEverChosen(); Intent intent = new Intent(); intent.setClass(getActivity(), showTutorial ? ChooseLockPatternTutorial.class : ChooseLockPattern.class); intent.putExtra("key_lock_method", "pattern"); intent.putExtra(CONFIRM_CREDENTIALS, false); intent.putExtra(LockPatternUtils.LOCKSCREEN_BIOMETRIC_WEAK_FALLBACK, isFallback); if(isFallback) { startActivityForResult(intent, FALLBACK_REQUEST); return; } else { intent.addFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT); startActivity(intent); } } else if (quality == DevicePolicyManager.PASSWORD_QUALITY_BIOMETRIC_WEAK) { Intent intent = getBiometricSensorIntent(quality); startActivity(intent); } else if (quality == DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED) { mChooseLockSettingsHelper.utils().clearLock(false); mChooseLockSettingsHelper.utils().setLockScreenDisabled(disabled); getActivity().setResult(Activity.RESULT_OK); } finish(); }
void updateUnlockMethodAndFinish(int quality, boolean disabled) { // Sanity check. We should never get here without confirming user's existing password. if (!mPasswordConfirmed) { throw new IllegalStateException("Tried to update password without confirming it"); } final boolean isFallback = getActivity().getIntent() .getBooleanExtra(LockPatternUtils.LOCKSCREEN_BIOMETRIC_WEAK_FALLBACK, false); quality = upgradeQuality(quality); if (quality >= DevicePolicyManager.PASSWORD_QUALITY_NUMERIC) { int minLength = mDPM.getPasswordMinimumLength(null); if (minLength < MIN_PASSWORD_LENGTH) { minLength = MIN_PASSWORD_LENGTH; } final int maxLength = mDPM.getPasswordMaximumLength(quality); Intent intent = new Intent().setClass(getActivity(), ChooseLockPassword.class); intent.putExtra(LockPatternUtils.PASSWORD_TYPE_KEY, quality); intent.putExtra(ChooseLockPassword.PASSWORD_MIN_KEY, minLength); intent.putExtra(ChooseLockPassword.PASSWORD_MAX_KEY, maxLength); intent.putExtra(CONFIRM_CREDENTIALS, false); intent.putExtra(LockPatternUtils.LOCKSCREEN_BIOMETRIC_WEAK_FALLBACK, isFallback); if(isFallback) { startActivityForResult(intent, FALLBACK_REQUEST); return; } else { intent.addFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT); startActivity(intent); } } else if (quality == DevicePolicyManager.PASSWORD_QUALITY_SOMETHING) { boolean showTutorial = !mChooseLockSettingsHelper.utils().isPatternEverChosen(); Intent intent = new Intent(); intent.setClass(getActivity(), showTutorial ? ChooseLockPatternTutorial.class : ChooseLockPattern.class); intent.putExtra("key_lock_method", "pattern"); intent.putExtra(CONFIRM_CREDENTIALS, false); intent.putExtra(LockPatternUtils.LOCKSCREEN_BIOMETRIC_WEAK_FALLBACK, isFallback); if(isFallback) { startActivityForResult(intent, FALLBACK_REQUEST); return; } else { intent.addFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT); startActivity(intent); } } else if (quality == DevicePolicyManager.PASSWORD_QUALITY_BIOMETRIC_WEAK) { Intent intent = getBiometricSensorIntent(quality); startActivity(intent); } else if (quality == DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED) { mChooseLockSettingsHelper.utils().clearLock(false); mChooseLockSettingsHelper.utils().setLockScreenDisabled(disabled); getActivity().setResult(Activity.RESULT_OK); } finish(); }
diff --git a/jsf-api/src/javax/faces/component/UIViewRoot.java b/jsf-api/src/javax/faces/component/UIViewRoot.java index 78327908f..8596a42af 100644 --- a/jsf-api/src/javax/faces/component/UIViewRoot.java +++ b/jsf-api/src/javax/faces/component/UIViewRoot.java @@ -1,1319 +1,1323 @@ /* * $Id: UIViewRoot.java,v 1.50.8.18 2008/04/21 20:31:24 edburns Exp $ */ /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common Development * and Distribution License("CDDL") (collectively, the "License"). You * may not use this file except in compliance with the License. You can obtain * a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html * or glassfish/bootstrap/legal/LICENSE.txt. See the License for the specific * language governing permissions and limitations under the License. * * When distributing the software, include this License Header Notice in each * file and include the License file at glassfish/bootstrap/legal/LICENSE.txt. * Sun designates this particular file as subject to the "Classpath" exception * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * Header, with the fields enclosed by brackets [] replaced by your own * identifying information: "Portions Copyrighted [year] * [name of copyright owner]" * * Contributor(s): * * If you wish your version of this file to be governed by only the CDDL or * only the GPL Version 2, indicate your decision by adding "[Contributor] * elects to include this software in this distribution under the [CDDL or GPL * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * and therefore, elected the GPL Version 2 license, then the option applies * only if the new code is made subject to such option by the copyright * holder. */ package javax.faces.component; import javax.el.ELException; import javax.el.MethodExpression; import javax.el.ValueExpression; import javax.faces.FacesException; import javax.faces.FactoryFinder; import javax.faces.context.FacesContext; import javax.faces.event.AbortProcessingException; import javax.faces.event.FacesEvent; import javax.faces.event.ComponentSystemEvent; import javax.faces.event.PhaseEvent; import javax.faces.event.PhaseId; import javax.faces.event.PhaseListener; import javax.faces.lifecycle.Lifecycle; import javax.faces.lifecycle.LifecycleFactory; import javax.faces.webapp.FacesServlet; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.ListIterator; import java.util.logging.Level; import java.util.logging.Logger; import javax.faces.event.AfterAddToParentEvent; import javax.faces.event.ComponentSystemEventListener; import javax.faces.event.ViewMapCreatedEvent; import javax.faces.event.ViewMapDestroyedEvent; /** * <p><strong class="changed_modified_2_0">UIViewRoot</strong> is the * UIComponent that represents the root of the UIComponent tree. This * component has no rendering, it just serves as the root of the * component tree, and as a place to hang per-view {@link * PhaseListener}s.</p> * <p class="changed_modified_2_0">To enable <code>UIViewRoot</code> * <code>PhaseListener</code>s to be invoked on restore view, this class * implements {@link ComponentSystemEventListener}. The restore view * phase implementation must guarantee that an {@link * AfterAddToParentEvent} is passed to this instance at the appropriate * time to indicate that the view has been completely populated. See * {@link #processEvent} for more information.</p> * <p>For each of the following lifecycle phase methods:</p> * <ul> * <li><p>{@link #processDecodes} </p></li> * <li><p>{@link #processValidators} </p></li> * <li><p>{@link #processUpdates} </p></li> * <li><p>{@link #processApplication} </p></li> * <li><p>RenderResponse, via {@link #encodeBegin} and {@link * #encodeEnd} </p></li> * </ul> * <p>Take the following action regarding * <code>PhaseListener</code>s.</p> * <ul> * <p>Initialize a state flag to <code>false</code>.</p> * <p>If {@link #getBeforePhaseListener} returns non-<code>null</code>, * invoke the listener, passing in the correct corresponding {@link * PhaseId} for this phase.</p> * <p>Upon return from the listener, call {@link * FacesContext#getResponseComplete} and {@link * FacesContext#getRenderResponse}. If either return <code>true</code> * set the internal state flag to <code>true</code>. </p> * <p>If or one or more listeners have been added by a call to {@link * #addPhaseListener}, invoke the <code>beforePhase</code> method on * each one whose {@link PhaseListener#getPhaseId} matches the current * phaseId, passing in the same <code>PhaseId</code> as in the previous * step.</p> * <p>Upon return from each listener, call {@link * FacesContext#getResponseComplete} and {@link * FacesContext#getRenderResponse}. If either return <code>true</code> * set the internal state flag to <code>true</code>. </p> * <p>Execute any processing for this phase if the internal state flag * was not set.</p> * <p>If {@link #getAfterPhaseListener} returns non-<code>null</code>, * invoke the listener, passing in the correct corresponding {@link * PhaseId} for this phase.</p> * <p/> * <p>If or one or more listeners have been added by a call to {@link * #addPhaseListener}, invoke the <code>afterPhase</code> method on each * one whose {@link PhaseListener#getPhaseId} matches the current * phaseId, passing in the same <code>PhaseId</code> as in the previous * step.</p> * <p/> * <p/> * </ul> */ public class UIViewRoot extends UIComponentBase implements ComponentSystemEventListener { // ------------------------------------------------------ Manifest Constants /** <p>The standard component type for this component.</p> */ public static final String COMPONENT_TYPE = "javax.faces.ViewRoot"; /** <p>The standard component family for this component.</p> */ public static final String COMPONENT_FAMILY = "javax.faces.ViewRoot"; /** * <p>The prefix that will be used for identifiers generated * by the <code>createUniqueId()</code> method. */ static public final String UNIQUE_ID_PREFIX = "j_id"; private static Lifecycle lifecycle; private static final Logger LOGGER = Logger.getLogger("javax.faces", "javax.faces.LogStrings"); private static final String LOCATION_IDENTIFIER_PREFIX = "javax_faces_location_"; private static final Map<String,String> LOCATION_IDENTIFIER_MAP = new HashMap<String,String>(6, 1.0f); static { LOCATION_IDENTIFIER_MAP.put("head", LOCATION_IDENTIFIER_PREFIX + "HEAD"); LOCATION_IDENTIFIER_MAP.put("form", LOCATION_IDENTIFIER_PREFIX + "FORM"); LOCATION_IDENTIFIER_MAP.put("body", LOCATION_IDENTIFIER_PREFIX + "BODY"); } // ------------------------------------------------------------ Constructors /** * <p>Create a new {@link UIViewRoot} instance with default property * values. The default implementation must call * {@link UIComponentBase#pushComponentToEL}.</p> */ public UIViewRoot() { super(); setRendererType(null); FacesContext context = FacesContext.getCurrentInstance(); pushComponentToEL(context,null); } /** * <p class="changed_added_2_0">Cause any <code>UIViewRoot</code> * {@link PhaseListener}s installed on this instance to be notified * of the restore view phase. The default implementation compares * the argument <code>event</code>'s <code>getClass()</code> with * {@link AfterAddToParentEvent}<code>.class</code> using * <code>equals()</code>. If and only if the comparison is * <code>true</code>, the default implementation must notify any * <code>UIViewRoot</code> {@link PhaseListener}s installed on this * instance that we are in the <strong>AFTER</strong> restore view * phase.</p> */ public void processEvent(ComponentSystemEvent event) throws AbortProcessingException { if (event.getClass().equals(AfterAddToParentEvent.class)) { notifyPhaseListeners(FacesContext.getCurrentInstance(), PhaseId.RESTORE_VIEW, false); } } // ------------------------------------------------------ Instance Variables private int lastId = 0; /** * <p>Set and cleared during the lifetime of a lifecycle phase. Has * no meaning between phases. If <code>true</code>, the lifecycle * processing for the current phase must not take place.</p> */ private boolean skipPhase; /** * <p>Set and cleared during the lifetime of a lifecycle phase. Has no * meaning between phases. If <code>true</code>, the * <code>MethodExpression</code> associated with <code>afterPhase</code> * will not be invoked nor will any PhaseListeners associated with this * UIViewRoot. */ private boolean beforeMethodException; /** * <p>Set and cleared during the lifetime of a lifecycle phase. Has no * meaning between phases. */ private ListIterator<PhaseListener> phaseListenerIterator; // -------------------------------------------------------------- Properties public String getFamily() { return (COMPONENT_FAMILY); } /** * <p>The render kit identifier of the {@link javax.faces.render.RenderKit} associated * wth this view.</p> */ private String renderKitId = null; /** * <p>Return the render kit identifier of the {@link * javax.faces.render.RenderKit} associated with this view. Unless * explicitly set, as in {@link * javax.faces.application.ViewHandler#createView}, the returned * value will be <code>null.</code></p> */ public String getRenderKitId() { String result; if (null != renderKitId) { result = this.renderKitId; } else { ValueExpression vb = getValueExpression("renderKitId"); FacesContext context = getFacesContext(); if (vb != null) { try { result = (String) vb.getValue(context.getELContext()); } catch (ELException e) { if (LOGGER.isLoggable(Level.SEVERE)) { LOGGER.log(Level.SEVERE, "severe.component.unable_to_process_expression", new Object[]{vb.getExpressionString(), "renderKitId"}); } result = null; } } else { result = null; } } return result; } /** * <p>Set the render kit identifier of the {@link javax.faces.render.RenderKit} * associated with this view. This method may be called at any time * between the end of <em>Apply Request Values</em> phase of the * request processing lifecycle (i.e. when events are being broadcast) * and the beginning of the <em>Render Response</em> phase.</p> * * @param renderKitId The new {@link javax.faces.render.RenderKit} identifier, * or <code>null</code> to disassociate this view with any * specific {@link javax.faces.render.RenderKit} instance */ public void setRenderKitId(String renderKitId) { this.renderKitId = renderKitId; } /** <p>The view identifier of this view.</p> */ private String viewId = null; /** <p>Return the view identifier for this view.</p> */ public String getViewId() { return (this.viewId); } /** * <p>Set the view identifier for this view.</p> * * @param viewId The new view identifier */ public void setViewId(String viewId) { this.viewId = viewId; } // ------------------------------------------------ Event Management Methods private MethodExpression beforePhase = null; private MethodExpression afterPhase = null; /** * @return the {@link MethodExpression} that will be invoked before * this view is rendered. */ public MethodExpression getBeforePhaseListener() { return beforePhase; } /** * <p><span class="changed_modified_2_0">Allow</span> an arbitrary * method to be called for the "beforePhase" event as the UIViewRoot * runs through its lifecycle. This method will be called for all * phases <span class="changed_modified_2_0">including {@link * PhaseId#RESTORE_VIEW}</span>. Unlike a true {@link * PhaseListener}, this approach doesn't allow for only receiving * {@link PhaseEvent}s for a given phase.</p> <p/> <p>The method * must conform to the signature of {@link * PhaseListener#beforePhase}.</p> * * @param newBeforePhase the {@link MethodExpression} that will be * invoked before this view is rendered. */ public void setBeforePhaseListener(MethodExpression newBeforePhase) { beforePhase = newBeforePhase; } /** * @return the {@link MethodExpression} that will be invoked after * this view is rendered. */ public MethodExpression getAfterPhaseListener() { return afterPhase; } /** * <p><span class="changed_modified_2_0">Allow</span> an arbitrary * method to be called for the "afterPhase" event as the UIViewRoot * runs through its lifecycle. This method will be called for all * phases <span class="changed_modified_2_0">including {@link * PhaseId#RESTORE_VIEW}</span>. Unlike a true {@link * PhaseListener}, this approach doesn't allow for only receiving * {@link PhaseEvent}s for a given phase.</p> <p/> <p>The method * must conform to the signature of {@link * PhaseListener#afterPhase}.</p> * * @param newAfterPhase the {@link MethodExpression} that will be * invoked after this view is rendered. */ public void setAfterPhaseListener(MethodExpression newAfterPhase) { afterPhase = newAfterPhase; } private List<PhaseListener> phaseListeners = null; public void removePhaseListener(PhaseListener toRemove) { if (null != phaseListeners) { phaseListeners.remove(toRemove); } } public void addPhaseListener(PhaseListener newPhaseListener) { if (null == phaseListeners) { //noinspection CollectionWithoutInitialCapacity phaseListeners = new ArrayList<PhaseListener>(); } phaseListeners.add(newPhaseListener); } /** * <p class="changed_added_2_0">Add argument <code>component</code>, * which is assumed to represent a resource instance, as a resource * to this view. A resource instance is rendered by a resource * <code>Renderer</code>, as described in the Standard HTML * RenderKit. The default implementation must call through to * {@link #addComponentResource(javax.faces.context.FacesContext, * javax.faces.component.UIComponent, java.lang.String)}.</p> * * <div class="changed_added_2_0"> * <p> * * @param context {@link FacesContext} for the current request * @param componentResource The {@link UIComponent} representing a * {@link javax.faces.application.Resource} instance */ public void addComponentResource(FacesContext context, UIComponent componentResource) { addComponentResource(context, componentResource, null); } /** * <p class="changed_added_2_0">Add argument <code>component</code>, * which is assumed to represent a resource instance, as a resource * to this view. A resource instance is rendered by a resource * <code>Renderer</code>, as described in the Standard HTML * RenderKit. </p> * * <div class="changed_added_2_0"> * <p> * The <code>component</code> must be added using the following algorithm: * <ul> * <li>If the <code>target</code> argument is <code>null</code>, look for a <code>target</code> * attribute on the <code>component</code>.<br> * If there is no <code>target</code> attribute, set <code>target</code> to be the default value <code>head</code></li> * <li>Call {@link #getComponentResources} to obtain the child list for the * given target.</li> * <li>Add the <code>component</code> resource to the list.</li> * </ul> * </p> * </div> * * @param context {@link FacesContext} for the current request * @param componentResource The {@link UIComponent} representing a * {@link javax.faces.application.Resource} instance * @param target The name of the facet for which the {@link UIComponent} will be added */ public void addComponentResource(FacesContext context, UIComponent componentResource, String target) { final Map<String,Object> attributes = componentResource.getAttributes(); // look for a target in the component attribute set if arg is not set. if (target == null) { target = (String) attributes.get("target"); } if (target == null) { target = "head"; } List<UIComponent> facetChildren = getComponentResources(context, target); // add the resource to the facet facetChildren.add(componentResource); } /** * <p class="changed_added_2_0">Return a <code>List</code> of * {@link UIComponent}s for the provided <code>target</code> agrument. * Each <code>component</code> in the <code>List</code> is assumed to * represent a resource instance.</p> * * <div class="changed_added_2_0"> * <p>The default implementation must use an algorithm equivalent to the * the following.</p> * <ul> * <li>Locate the facet for the <code>component</code> by calling <code>getFacet()</code> using * <code>target</code> as the argument.</li> * <li>If the facet is not found, create the facet by calling <code>context.getApplication().createComponent() * </code> using <code>javax.faces.Panel</code> as the argument</li> * <ul> * <li>Set the <code>id</code> of the facet to be <code>target</code></li> * <li>Add the facet to the facets <code>Map</code> using <code>target</code> as the key</li> * </ul> * <li>return the children of the facet</li> * </ul> * </div> * * @param target The name of the facet for which the components will be returned. * * @return A <code>List</code> of {@link UIComponent} children of the facet with the * name <code>target</code>. If no children are found for the facet, return * <code>Collections.emptyList()</code>. * * @throws NullPointerException if <code>target</code> * is <code>null</code> */ public List<UIComponent> getComponentResources(FacesContext context, String target) { if (target == null) { throw new NullPointerException(); } String location = getIdentifier(target); UIComponent facet = getFacet(location); if (facet == null) { facet = context.getApplication().createComponent("javax.faces.Panel"); facet.setId(location); getFacets().put(location, facet); } return facet.getChildren(); } /** * <p class="changed_added_2_0">Remove argument <code>component</code>, * which is assumed to represent a resource instance, as a resource * to this view.</p> * * <div class="changed_added_2_0"> * <p> * * @param context {@link FacesContext} for the current request * @param componentResource The {@link UIComponent} representing a * {@link javax.faces.application.Resource} instance */ public void removeComponentResource(FacesContext context, UIComponent componentResource) { removeComponentResource(context, componentResource, null); } /** * <p class="changed_added_2_0">Remove argument <code>component</code>, * which is assumed to represent a resource instance, as a resource * to this view. A resource instance is rendered by a resource * <code>Renderer</code>, as described in the Standard HTML * RenderKit. </p> * * <div class="changed_added_2_0"> * <p> * The <code>component</code> must be removed using the following algorithm: * <ul> * <li>If the <code>target</code> argument is <code>null</code>, look for a <code>target</code> * attribute on the <code>component</code>.<br> * If there is no <code>target</code> attribute, set <code>target</code> to be the default value <code>head</code></li> * <li>Call {@link #getComponentResources} to obtain the child list for the * given target.</li> * <li>Remove the <code>component</code> resource from the child list.</li> * </ul> * </p> * </div> * * @param context {@link FacesContext} for the current request * @param componentResource The {@link UIComponent} representing a * {@link javax.faces.application.Resource} instance * @param target The name of the facet for which the {@link UIComponent} will be added */ public void removeComponentResource(FacesContext context, UIComponent componentResource, String target) { final Map<String,Object> attributes = componentResource.getAttributes(); // look for a target in the component attribute set if arg is not set. if (target == null) { target = (String) attributes.get("target"); } if (target == null) { target = "head"; } List<UIComponent> facetChildren = getComponentResources(context, target); // add the resource to the facet facetChildren.remove(componentResource); } /** * <p>An array of Lists of events that have been queued for later * broadcast, with one List for each lifecycle phase. The list * indices match the ordinals of the PhaseId instances. This * instance is lazily instantiated. This list is * <strong>NOT</strong> part of the state that is saved and restored * for this component.</p> */ private List<List<FacesEvent>> events = null; /** * <p>Override the default {@link UIComponentBase#queueEvent} behavior to * accumulate the queued events for later broadcasting.</p> * * @param event {@link FacesEvent} to be queued * * @throws IllegalStateException if this component is not a * descendant of a {@link UIViewRoot} * @throws NullPointerException if <code>event</code> * is <code>null</code> */ public void queueEvent(FacesEvent event) { if (event == null) { throw new NullPointerException(); } // We are a UIViewRoot, so no need to check for the ISE if (events == null) { int len = PhaseId.VALUES.size(); List<List<FacesEvent>> events = new ArrayList<List<FacesEvent>>(len); for (int i = 0; i < len; i++) { events.add(new ArrayList<FacesEvent>(5)); } this.events = events; } events.get(event.getPhaseId().getOrdinal()).add(event); } /** * <p>Broadcast any events that have been queued.</p> * * @param context {@link FacesContext} for the current request * @param phaseId {@link PhaseId} of the current phase */ private void broadcastEvents(FacesContext context, PhaseId phaseId) { if (null == events) { // no events have been queued return; } boolean hasMoreAnyPhaseEvents; boolean hasMoreCurrentPhaseEvents; List<FacesEvent> eventsForPhaseId = events.get(PhaseId.ANY_PHASE.getOrdinal()); // keep iterating till we have no more events to broadcast. // This is necessary for events that cause other events to be // queued. PENDING(edburns): here's where we'd put in a check // to prevent infinite event queueing. do { // broadcast the ANY_PHASE events first if (null != eventsForPhaseId) { // We cannot use an Iterator because we will get // ConcurrentModificationException errors, so fake it while (!eventsForPhaseId.isEmpty()) { FacesEvent event = eventsForPhaseId.get(0); UIComponent source = event.getComponent(); try { this.pushComponentToEL(context, source); source.broadcast(event); } catch (AbortProcessingException e) { if (LOGGER.isLoggable(Level.SEVERE)) { UIComponent component = event.getComponent(); String id = ""; if (component != null) { id = component.getId(); if (id == null) { id = component.getClientId(context); } } LOGGER.log(Level.SEVERE, "error.component.abortprocessing_thrown", new Object[]{event.getClass().getName(), phaseId.toString(), id}); LOGGER.log(Level.SEVERE, e.toString(), e); } } finally { popComponentFromEL(context); } eventsForPhaseId.remove(0); // Stay at current position } } // then broadcast the events for this phase. if (null != (eventsForPhaseId = events.get(phaseId.getOrdinal()))) { // We cannot use an Iterator because we will get // ConcurrentModificationException errors, so fake it while (!eventsForPhaseId.isEmpty()) { FacesEvent event = eventsForPhaseId.get(0); UIComponent source = event.getComponent(); try { + this.pushComponentToEL(context, source); source.broadcast(event); } catch (AbortProcessingException ignored) { // A "return" here would abort remaining events too } + finally { + popComponentFromEL(context); + } eventsForPhaseId.remove(0); // Stay at current position } } // true if we have any more ANY_PHASE events hasMoreAnyPhaseEvents = (null != (eventsForPhaseId = events.get(PhaseId.ANY_PHASE.getOrdinal()))) && !eventsForPhaseId.isEmpty(); // true if we have any more events for the argument phaseId hasMoreCurrentPhaseEvents = (null != events.get(phaseId.getOrdinal())) && !events.get(phaseId.getOrdinal()).isEmpty(); } while (hasMoreAnyPhaseEvents || hasMoreCurrentPhaseEvents); } // ------------------------------------------------ Lifecycle Phase Handlers private void initState() { skipPhase = false; beforeMethodException = false; phaseListenerIterator = ((phaseListeners != null) ? phaseListeners.listIterator() : null); } // avoid creating the PhaseEvent if possible by doing redundant // null checks. private void notifyBefore(FacesContext context, PhaseId phaseId) { if (null != beforePhase || null != phaseListenerIterator) { notifyPhaseListeners(context, phaseId, true); } } // avoid creating the PhaseEvent if possible by doing redundant // null checks. private void notifyAfter(FacesContext context, PhaseId phaseId) { if (null != afterPhase || null != phaseListenerIterator) { notifyPhaseListeners(context, phaseId, false); } } /** * <p>Override the default {@link UIComponentBase#processDecodes} * behavior to broadcast any queued events after the default * processing has been completed and to clear out any events * for later phases if the event processing for this phase caused {@link * FacesContext#renderResponse} or {@link FacesContext#responseComplete} * to be called.</p> * * @param context {@link FacesContext} for the request we are processing * * @throws NullPointerException if <code>context</code> * is <code>null</code> */ @Override public void processDecodes(FacesContext context) { initState(); notifyBefore(context, PhaseId.APPLY_REQUEST_VALUES); try { if (!skipPhase) { super.processDecodes(context); broadcastEvents(context, PhaseId.APPLY_REQUEST_VALUES); } } finally { clearFacesEvents(context); notifyAfter(context, PhaseId.APPLY_REQUEST_VALUES); } } /** * <p>Override the default {@link UIComponentBase#encodeBegin} * behavior. If * {@link #getBeforePhaseListener} returns non-<code>null</code>, * invoke it, passing a {@link PhaseEvent} for the {@link * PhaseId#RENDER_RESPONSE} phase. If the internal list populated * by calls to {@link #addPhaseListener} is non-empty, any listeners * in that list must have their {@link PhaseListener#beforePhase} * method called, passing the <code>PhaseEvent</code>. Any errors * that occur during invocation of any of the the beforePhase * listeners must be logged and swallowed. After listeners are invoked * call superclass processing.</p> */ @Override public void encodeBegin(FacesContext context) throws IOException { initState(); notifyBefore(context, PhaseId.RENDER_RESPONSE); if (!skipPhase) { super.encodeBegin(context); } } /** * <p>Override the default {@link UIComponentBase#encodeEnd} * behavior. If {@link #getAfterPhaseListener} returns * non-<code>null</code>, invoke it, passing a {@link PhaseEvent} * for the {@link PhaseId#RENDER_RESPONSE} phase. Any errors that * occur during invocation of the afterPhase listener must be * logged and swallowed.</p> */ @Override public void encodeEnd(FacesContext context) throws IOException { super.encodeEnd(context); notifyAfter(context, PhaseId.RENDER_RESPONSE); } /** * <p>Utility method that notifies phaseListeners for the given * phaseId. Assumes that either or both the MethodExpression or * phaseListeners data structure are non-null.</p> * * @param context the context for this request * @param phaseId the {@link PhaseId} of the current phase * @param isBefore, if true, notify beforePhase listeners. Notify * afterPhase listeners otherwise. */ private void notifyPhaseListeners(FacesContext context, PhaseId phaseId, boolean isBefore) { PhaseEvent event = createPhaseEvent(context, phaseId); boolean hasPhaseMethodExpression = (isBefore && (null != beforePhase)) || (!isBefore && (null != afterPhase) && !beforeMethodException); MethodExpression expression = isBefore ? beforePhase : afterPhase; if (hasPhaseMethodExpression) { try { expression.invoke(context.getELContext(), new Object[]{event}); skipPhase = context.getResponseComplete() || context.getRenderResponse(); } catch (Exception e) { if (isBefore) { beforeMethodException = true; } if (LOGGER.isLoggable(Level.SEVERE)) { LOGGER.log(Level.SEVERE, "severe.component.unable_to_process_expression", new Object[] { expression.getExpressionString(), (isBefore ? "beforePhase" : "afterPhase")}); } return; } } if (phaseListenerIterator != null && !beforeMethodException) { while ((isBefore) ? phaseListenerIterator.hasNext() : phaseListenerIterator.hasPrevious()) { PhaseListener curListener = ((isBefore) ? phaseListenerIterator.next() : phaseListenerIterator .previous()); if (phaseId == curListener.getPhaseId() || PhaseId.ANY_PHASE == curListener.getPhaseId()) { try { if (isBefore) { curListener.beforePhase(event); } else { curListener.afterPhase(event); } skipPhase = context.getResponseComplete() || context.getRenderResponse(); } catch (Exception e) { if (isBefore && phaseListenerIterator.hasPrevious()) { phaseListenerIterator.previous(); } if (LOGGER.isLoggable(Level.SEVERE)) { LOGGER.log(Level.SEVERE, "severe.component.uiviewroot_error_invoking_phaselistener", curListener.getClass().getName()); } return; } } } } } private static PhaseEvent createPhaseEvent(FacesContext context, PhaseId phaseId) throws FacesException { if (lifecycle == null) { LifecycleFactory lifecycleFactory = (LifecycleFactory) FactoryFinder.getFactory(FactoryFinder.LIFECYCLE_FACTORY); String lifecycleId = context.getExternalContext() .getInitParameter(FacesServlet.LIFECYCLE_ID_ATTR); if (lifecycleId == null) { lifecycleId = LifecycleFactory.DEFAULT_LIFECYCLE; } lifecycle = lifecycleFactory.getLifecycle(lifecycleId); } return (new PhaseEvent(context, phaseId, lifecycle)); } /** * <p>Override the default {@link UIComponentBase#processValidators} * behavior to broadcast any queued events after the default * processing has been completed and to clear out any events * for later phases if the event processing for this phase caused {@link * FacesContext#renderResponse} or {@link FacesContext#responseComplete} * to be called.</p> * * @param context {@link FacesContext} for the request we are processing * * @throws NullPointerException if <code>context</code> * is <code>null</code> */ @Override public void processValidators(FacesContext context) { initState(); notifyBefore(context, PhaseId.PROCESS_VALIDATIONS); try { if (!skipPhase) { super.processValidators(context); broadcastEvents(context, PhaseId.PROCESS_VALIDATIONS); } } finally { clearFacesEvents(context); notifyAfter(context, PhaseId.PROCESS_VALIDATIONS); } } /** * <p>Override the default {@link UIComponentBase} behavior to broadcast * any queued events after the default processing has been completed * and to clear out any events for later phases if the event processing * for this phase caused {@link FacesContext#renderResponse} or * {@link FacesContext#responseComplete} to be called.</p> * * @param context {@link FacesContext} for the request we are processing * * @throws NullPointerException if <code>context</code> * is <code>null</code> */ @Override public void processUpdates(FacesContext context) { initState(); notifyBefore(context, PhaseId.UPDATE_MODEL_VALUES); try { if (!skipPhase) { super.processUpdates(context); broadcastEvents(context, PhaseId.UPDATE_MODEL_VALUES); } } finally { clearFacesEvents(context); notifyAfter(context, PhaseId.UPDATE_MODEL_VALUES); } } /** * <p>Broadcast any events that have been queued for the <em>Invoke * Application</em> phase of the request processing lifecycle * and to clear out any events for later phases if the event processing * for this phase caused {@link FacesContext#renderResponse} or * {@link FacesContext#responseComplete} to be called.</p> * * @param context {@link FacesContext} for the request we are processing * * @throws NullPointerException if <code>context</code> * is <code>null</code> */ public void processApplication(FacesContext context) { initState(); notifyBefore(context, PhaseId.INVOKE_APPLICATION); try { if (!skipPhase) { // NOTE - no tree walk is performed; this is a UIViewRoot-only operation broadcastEvents(context, PhaseId.INVOKE_APPLICATION); } } finally { clearFacesEvents(context); notifyAfter(context, PhaseId.INVOKE_APPLICATION); } } // clear out the events if we're skipping to render-response // or if there is a response complete signal. private void clearFacesEvents(FacesContext context) { if (context.getRenderResponse() || context.getResponseComplete()) { if (events != null) { for (List<FacesEvent> eventList : events) { if (eventList != null) { eventList.clear(); } } events = null; } } } /** * <p>Generate an identifier for a component. The identifier will * be prefixed with UNIQUE_ID_PREFIX, and will be unique within * this UIViewRoot.</p> */ public String createUniqueId() { return UNIQUE_ID_PREFIX + lastId++; } /* * <p>The locale for this view.</p> */ private Locale locale = null; /** * <p>Return the <code>Locale</code> to be used in localizing the * response being created for this view.</p> * <p/> * <p>Algorithm:</p> * <p/> * <p>If we have a <code>locale</code> ivar, return it. If we have * a value expression for "locale", get its value. If the value is * <code>null</code>, return the result of calling {@link * javax.faces.application.ViewHandler#calculateLocale}. If the * value is an instance of <code>java.util.Locale</code> return it. * If the value is a String, convert it to a * <code>java.util.Locale</code> and return it. If there is no * value expression for "locale", return the result of calling {@link * javax.faces.application.ViewHandler#calculateLocale}.</p> * * @return The current <code>Locale</code> obtained by executing the * above algorithm. */ public Locale getLocale() { Locale result = null; if (null != locale) { result = this.locale; } else { ValueExpression vb = getValueExpression("locale"); FacesContext context = getFacesContext(); if (vb != null) { Object resultLocale = null; try { resultLocale = vb.getValue(context.getELContext()); } catch (ELException e) { if (LOGGER.isLoggable(Level.SEVERE)) { LOGGER.log(Level.SEVERE, "severe.component.unable_to_process_expression", new Object[]{vb.getExpressionString(), "locale"}); } } if (null == resultLocale) { result = context.getApplication().getViewHandler() .calculateLocale(context); } else if (resultLocale instanceof Locale) { result = (Locale) resultLocale; } else if (resultLocale instanceof String) { result = getLocaleFromString((String) resultLocale); } } else { result = context.getApplication().getViewHandler() .calculateLocale(context); } } return result; } // W3C XML specification refers to IETF RFC 1766 for language code // structure, therefore the value for the xml:lang attribute should // be in the form of language or language-country or // language-country-variant. private static Locale getLocaleFromString(String localeStr) throws IllegalArgumentException { // length must be at least 2. if (null == localeStr || localeStr.length() < 2) { throw new IllegalArgumentException("Illegal locale String: " + localeStr); } Locale result = null; String lang = null; String country = null; String variant = null; char[] seps = { '-', '_' }; int inputLength = localeStr.length(); int i = 0; int j = 0; // to have a language, the length must be >= 2 if ((inputLength >= 2) && ((i = indexOfSet(localeStr, seps, 0)) == -1)) { // we have only Language, no country or variant if (2 != localeStr.length()) { throw new IllegalArgumentException("Illegal locale String: " + localeStr); } lang = localeStr.toLowerCase(); } // we have a separator, it must be either '-' or '_' if (i != -1) { lang = localeStr.substring(0, i); // look for the country sep. // to have a country, the length must be >= 5 if ((inputLength >= 5) && (-1 == (j = indexOfSet(localeStr, seps, i + 1)))) { // no further separators, length must be 5 if (inputLength != 5) { throw new IllegalArgumentException("Illegal locale String: " + localeStr); } country = localeStr.substring(i + 1); } if (j != -1) { country = localeStr.substring(i + 1, j); // if we have enough separators for language, locale, // and variant, the length must be >= 8. if (inputLength >= 8) { variant = localeStr.substring(j + 1); } else { throw new IllegalArgumentException("Illegal locale String: " + localeStr); } } } if (variant != null && country != null && lang != null) { result = new Locale(lang, country, variant); } else if (lang != null && country != null) { result = new Locale(lang, country); } else if (lang != null) { result = new Locale(lang, ""); } return result; } /** * @param str local string * @param set the substring * @param fromIndex starting index * @return starting at <code>fromIndex</code>, the index of the * first occurrence of any substring from <code>set</code> in * <code>toSearch</code>, or -1 if no such match is found */ private static int indexOfSet(String str, char[] set, int fromIndex) { int result = -1; for (int i = fromIndex, len = str.length(); i < len; i++) { for (int j = 0, innerLen = set.length; j < innerLen; j++) { if (str.charAt(i) == set[j]) { result = i; break; } } if (-1 != result) { break; } } return result; } /** * <p>Set the <code>Locale</code> to be used in localizing the * response being created for this view. </p> * * @param locale The new localization Locale */ public void setLocale(Locale locale) { this.locale = locale; // Make sure to appraise the EL of this switch in Locale. FacesContext.getCurrentInstance().getELContext().setLocale(locale); } private Map<String, Object> viewScope = null; /** * <p class="changed_added_2_0">This implementation simply calls through to {@link * #getViewMap(boolean)}, passing <code>true</code> as the argument, and * returns the result.</p> * <div class="changed_added_2_0"> * * @since 2.0 */ public Map<String, Object> getViewMap() { return getViewMap(true); } /** * <p class="changed_added_2_0">Returns a <code>Map</code> that acts as the * interface to the data store that is the "view scope", or, if this * instance does not have such a <code>Map</code> and the * <code>create</code> argument is <code>true</code>, creates one and * returns it. This map must be instantiated lazily and cached for return * from subsequent calls to this method on this <code>UIViewRoot</code> * instance. {@link javax.faces.application.Application#publishEvent} must * be called, passing {@link ViewMapCreatedEvent}<code>.class</code> as the * first argument and this <code>UIViewRoot</code> instance as the second * argument.</p> * * <p>The returned <code>Map</code> must be implemented such that calling * <code>clear()</code> on the <code>Map</code> causes {@link javax.faces.application.Application#publishEvent} to be * called, passing {@link ViewMapDestroyedEvent}<code>.class</code> * as the first argument and this <code>UIViewRoot</code> instance * as the second argument.</p> * * <p>See {@link FacesContext#setViewRoot} for the specification of when the * <code>clear()</code> method must be called.</p> * <p/> * </div> * * @param create <code>true</code> to create a new <code>Map</code> for this * instance if necessary; <code>false</code> to return * <code>null</code> if there's no current <code>Map</code>. * * @since 2.0 */ public Map<String, Object> getViewMap(boolean create) { if (create && viewScope == null) { viewScope = new ViewMap(); getFacesContext().getApplication() .publishEvent(ViewMapCreatedEvent.class, this); } return viewScope; } // ----------------------------------------------------- StateHolder Methods private Object[] values; @Override public Object saveState(FacesContext context) { if (values == null) { values = new Object[9]; } values[0] = super.saveState(context); values[1] = renderKitId; values[2] = viewId; values[3] = locale; values[4] = lastId; values[5] = saveAttachedState(context, beforePhase); values[6] = saveAttachedState(context, afterPhase); values[7] = saveAttachedState(context, phaseListeners); values[8] = saveAttachedState(context, viewScope); return (values); } @Override public void restoreState(FacesContext context, Object state) { values = (Object[]) state; super.restoreState(context, values[0]); renderKitId = (String) values[1]; viewId = (String) values[2]; locale = (Locale) values[3]; lastId = ((Integer) values[4]).intValue(); beforePhase = (MethodExpression) restoreAttachedState(context, values[5]); afterPhase = (MethodExpression) restoreAttachedState(context, values[6]); phaseListeners = TypedCollections.dynamicallyCastList((List) restoreAttachedState(context, values[7]), PhaseListener.class); //noinspection unchecked viewScope = (Map<String, Object>) restoreAttachedState(context, values[8]); } private static String getIdentifier(String target) { // check map String id = LOCATION_IDENTIFIER_MAP.get(target); if (id == null) { id = LOCATION_IDENTIFIER_PREFIX + target; LOCATION_IDENTIFIER_MAP.put(target, id); } return id; } // ----------------------------------------------------------- Inner Classes private static final class ViewMap extends HashMap<String,Object> { private static final long serialVersionUID = -1l; @Override public void clear() { FacesContext context = FacesContext.getCurrentInstance(); context.getApplication() .publishEvent(ViewMapDestroyedEvent.class, context.getViewRoot()); super.clear(); } } // END ViewMap }
false
true
private void broadcastEvents(FacesContext context, PhaseId phaseId) { if (null == events) { // no events have been queued return; } boolean hasMoreAnyPhaseEvents; boolean hasMoreCurrentPhaseEvents; List<FacesEvent> eventsForPhaseId = events.get(PhaseId.ANY_PHASE.getOrdinal()); // keep iterating till we have no more events to broadcast. // This is necessary for events that cause other events to be // queued. PENDING(edburns): here's where we'd put in a check // to prevent infinite event queueing. do { // broadcast the ANY_PHASE events first if (null != eventsForPhaseId) { // We cannot use an Iterator because we will get // ConcurrentModificationException errors, so fake it while (!eventsForPhaseId.isEmpty()) { FacesEvent event = eventsForPhaseId.get(0); UIComponent source = event.getComponent(); try { this.pushComponentToEL(context, source); source.broadcast(event); } catch (AbortProcessingException e) { if (LOGGER.isLoggable(Level.SEVERE)) { UIComponent component = event.getComponent(); String id = ""; if (component != null) { id = component.getId(); if (id == null) { id = component.getClientId(context); } } LOGGER.log(Level.SEVERE, "error.component.abortprocessing_thrown", new Object[]{event.getClass().getName(), phaseId.toString(), id}); LOGGER.log(Level.SEVERE, e.toString(), e); } } finally { popComponentFromEL(context); } eventsForPhaseId.remove(0); // Stay at current position } } // then broadcast the events for this phase. if (null != (eventsForPhaseId = events.get(phaseId.getOrdinal()))) { // We cannot use an Iterator because we will get // ConcurrentModificationException errors, so fake it while (!eventsForPhaseId.isEmpty()) { FacesEvent event = eventsForPhaseId.get(0); UIComponent source = event.getComponent(); try { source.broadcast(event); } catch (AbortProcessingException ignored) { // A "return" here would abort remaining events too } eventsForPhaseId.remove(0); // Stay at current position } } // true if we have any more ANY_PHASE events hasMoreAnyPhaseEvents = (null != (eventsForPhaseId = events.get(PhaseId.ANY_PHASE.getOrdinal()))) && !eventsForPhaseId.isEmpty(); // true if we have any more events for the argument phaseId hasMoreCurrentPhaseEvents = (null != events.get(phaseId.getOrdinal())) && !events.get(phaseId.getOrdinal()).isEmpty(); } while (hasMoreAnyPhaseEvents || hasMoreCurrentPhaseEvents); }
private void broadcastEvents(FacesContext context, PhaseId phaseId) { if (null == events) { // no events have been queued return; } boolean hasMoreAnyPhaseEvents; boolean hasMoreCurrentPhaseEvents; List<FacesEvent> eventsForPhaseId = events.get(PhaseId.ANY_PHASE.getOrdinal()); // keep iterating till we have no more events to broadcast. // This is necessary for events that cause other events to be // queued. PENDING(edburns): here's where we'd put in a check // to prevent infinite event queueing. do { // broadcast the ANY_PHASE events first if (null != eventsForPhaseId) { // We cannot use an Iterator because we will get // ConcurrentModificationException errors, so fake it while (!eventsForPhaseId.isEmpty()) { FacesEvent event = eventsForPhaseId.get(0); UIComponent source = event.getComponent(); try { this.pushComponentToEL(context, source); source.broadcast(event); } catch (AbortProcessingException e) { if (LOGGER.isLoggable(Level.SEVERE)) { UIComponent component = event.getComponent(); String id = ""; if (component != null) { id = component.getId(); if (id == null) { id = component.getClientId(context); } } LOGGER.log(Level.SEVERE, "error.component.abortprocessing_thrown", new Object[]{event.getClass().getName(), phaseId.toString(), id}); LOGGER.log(Level.SEVERE, e.toString(), e); } } finally { popComponentFromEL(context); } eventsForPhaseId.remove(0); // Stay at current position } } // then broadcast the events for this phase. if (null != (eventsForPhaseId = events.get(phaseId.getOrdinal()))) { // We cannot use an Iterator because we will get // ConcurrentModificationException errors, so fake it while (!eventsForPhaseId.isEmpty()) { FacesEvent event = eventsForPhaseId.get(0); UIComponent source = event.getComponent(); try { this.pushComponentToEL(context, source); source.broadcast(event); } catch (AbortProcessingException ignored) { // A "return" here would abort remaining events too } finally { popComponentFromEL(context); } eventsForPhaseId.remove(0); // Stay at current position } } // true if we have any more ANY_PHASE events hasMoreAnyPhaseEvents = (null != (eventsForPhaseId = events.get(PhaseId.ANY_PHASE.getOrdinal()))) && !eventsForPhaseId.isEmpty(); // true if we have any more events for the argument phaseId hasMoreCurrentPhaseEvents = (null != events.get(phaseId.getOrdinal())) && !events.get(phaseId.getOrdinal()).isEmpty(); } while (hasMoreAnyPhaseEvents || hasMoreCurrentPhaseEvents); }
diff --git a/src/org/apache/xerces/util/URI.java b/src/org/apache/xerces/util/URI.java index 950310fcc..9285416df 100644 --- a/src/org/apache/xerces/util/URI.java +++ b/src/org/apache/xerces/util/URI.java @@ -1,1994 +1,1994 @@ /* * The Apache Software License, Version 1.1 * * * Copyright (c) 1999-2003 The Apache Software Foundation. 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. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, iClick Inc., * http://www.apache.org. For more information on the Apache Software * Foundation, please see <http://www.apache.org/>. */ package org.apache.xerces.util; import java.io.IOException; import java.io.Serializable; /********************************************************************** * A class to represent a Uniform Resource Identifier (URI). This class * is designed to handle the parsing of URIs and provide access to * the various components (scheme, host, port, userinfo, path, query * string and fragment) that may constitute a URI. * <p> * Parsing of a URI specification is done according to the URI * syntax described in * <a href="http://www.ietf.org/rfc/rfc2396.txt?number=2396">RFC 2396</a>, * and amended by * <a href="http://www.ietf.org/rfc/rfc2732.txt?number=2732">RFC 2732</a>. * <p> * Every absolute URI consists of a scheme, followed by a colon (':'), * followed by a scheme-specific part. For URIs that follow the * "generic URI" syntax, the scheme-specific part begins with two * slashes ("//") and may be followed by an authority segment (comprised * of user information, host, and port), path segment, query segment * and fragment. Note that RFC 2396 no longer specifies the use of the * parameters segment and excludes the "user:password" syntax as part of * the authority segment. If "user:password" appears in a URI, the entire * user/password string is stored as userinfo. * <p> * For URIs that do not follow the "generic URI" syntax (e.g. mailto), * the entire scheme-specific part is treated as the "path" portion * of the URI. * <p> * Note that, unlike the java.net.URL class, this class does not provide * any built-in network access functionality nor does it provide any * scheme-specific functionality (for example, it does not know a * default port for a specific scheme). Rather, it only knows the * grammar and basic set of operations that can be applied to a URI. * * @version $Id$ * **********************************************************************/ public class URI implements Serializable { /******************************************************************* * MalformedURIExceptions are thrown in the process of building a URI * or setting fields on a URI when an operation would result in an * invalid URI specification. * ********************************************************************/ public static class MalformedURIException extends IOException { /****************************************************************** * Constructs a <code>MalformedURIException</code> with no specified * detail message. ******************************************************************/ public MalformedURIException() { super(); } /***************************************************************** * Constructs a <code>MalformedURIException</code> with the * specified detail message. * * @param p_msg the detail message. ******************************************************************/ public MalformedURIException(String p_msg) { super(p_msg); } } private static final byte [] fgLookupTable = new byte[128]; /** * Character Classes */ /** reserved characters ;/?:@&=+$,[] */ //RFC 2732 added '[' and ']' as reserved characters private static final int RESERVED_CHARACTERS = 0x01; /** URI punctuation mark characters: -_.!~*'() - these, combined with alphanumerics, constitute the "unreserved" characters */ private static final int MARK_CHARACTERS = 0x02; /** scheme can be composed of alphanumerics and these characters: +-. */ private static final int SCHEME_CHARACTERS = 0x04; /** userinfo can be composed of unreserved, escaped and these characters: ;:&=+$, */ private static final int USERINFO_CHARACTERS = 0x08; /** ASCII letter characters */ private static final int ASCII_ALPHA_CHARACTERS = 0x10; /** ASCII digit characters */ private static final int ASCII_DIGIT_CHARACTERS = 0x20; /** ASCII hex characters */ private static final int ASCII_HEX_CHARACTERS = 0x40; /** Path characters */ private static final int PATH_CHARACTERS = 0x80; /** Mask for alpha-numeric characters */ private static final int MASK_ALPHA_NUMERIC = ASCII_ALPHA_CHARACTERS | ASCII_DIGIT_CHARACTERS; /** Mask for unreserved characters */ private static final int MASK_UNRESERVED_MASK = MASK_ALPHA_NUMERIC | MARK_CHARACTERS; /** Mask for URI allowable characters except for % */ private static final int MASK_URI_CHARACTER = MASK_UNRESERVED_MASK | RESERVED_CHARACTERS; /** Mask for scheme characters */ private static final int MASK_SCHEME_CHARACTER = MASK_ALPHA_NUMERIC | SCHEME_CHARACTERS; /** Mask for userinfo characters */ private static final int MASK_USERINFO_CHARACTER = MASK_UNRESERVED_MASK | USERINFO_CHARACTERS; /** Mask for path characters */ private static final int MASK_PATH_CHARACTER = MASK_UNRESERVED_MASK | PATH_CHARACTERS; static { // Add ASCII Digits and ASCII Hex Numbers for (int i = '0'; i <= '9'; ++i) { fgLookupTable[i] |= ASCII_DIGIT_CHARACTERS | ASCII_HEX_CHARACTERS; } // Add ASCII Letters and ASCII Hex Numbers for (int i = 'A'; i <= 'F'; ++i) { fgLookupTable[i] |= ASCII_ALPHA_CHARACTERS | ASCII_HEX_CHARACTERS; fgLookupTable[i+0x00000020] |= ASCII_ALPHA_CHARACTERS | ASCII_HEX_CHARACTERS; } // Add ASCII Letters for (int i = 'G'; i <= 'Z'; ++i) { fgLookupTable[i] |= ASCII_ALPHA_CHARACTERS; fgLookupTable[i+0x00000020] |= ASCII_ALPHA_CHARACTERS; } // Add Reserved Characters fgLookupTable[';'] |= RESERVED_CHARACTERS; fgLookupTable['/'] |= RESERVED_CHARACTERS; fgLookupTable['?'] |= RESERVED_CHARACTERS; fgLookupTable[':'] |= RESERVED_CHARACTERS; fgLookupTable['@'] |= RESERVED_CHARACTERS; fgLookupTable['&'] |= RESERVED_CHARACTERS; fgLookupTable['='] |= RESERVED_CHARACTERS; fgLookupTable['+'] |= RESERVED_CHARACTERS; fgLookupTable['$'] |= RESERVED_CHARACTERS; fgLookupTable[','] |= RESERVED_CHARACTERS; fgLookupTable['['] |= RESERVED_CHARACTERS; fgLookupTable[']'] |= RESERVED_CHARACTERS; // Add Mark Characters fgLookupTable['-'] |= MARK_CHARACTERS; fgLookupTable['_'] |= MARK_CHARACTERS; fgLookupTable['.'] |= MARK_CHARACTERS; fgLookupTable['!'] |= MARK_CHARACTERS; fgLookupTable['~'] |= MARK_CHARACTERS; fgLookupTable['*'] |= MARK_CHARACTERS; fgLookupTable['\''] |= MARK_CHARACTERS; fgLookupTable['('] |= MARK_CHARACTERS; fgLookupTable[')'] |= MARK_CHARACTERS; // Add Scheme Characters fgLookupTable['+'] |= SCHEME_CHARACTERS; fgLookupTable['-'] |= SCHEME_CHARACTERS; fgLookupTable['.'] |= SCHEME_CHARACTERS; // Add Userinfo Characters fgLookupTable[';'] |= USERINFO_CHARACTERS; fgLookupTable[':'] |= USERINFO_CHARACTERS; fgLookupTable['&'] |= USERINFO_CHARACTERS; fgLookupTable['='] |= USERINFO_CHARACTERS; fgLookupTable['+'] |= USERINFO_CHARACTERS; fgLookupTable['$'] |= USERINFO_CHARACTERS; fgLookupTable[','] |= USERINFO_CHARACTERS; // Add Path Characters fgLookupTable[';'] |= PATH_CHARACTERS; fgLookupTable['/'] |= PATH_CHARACTERS; fgLookupTable[':'] |= PATH_CHARACTERS; fgLookupTable['@'] |= PATH_CHARACTERS; fgLookupTable['&'] |= PATH_CHARACTERS; fgLookupTable['='] |= PATH_CHARACTERS; fgLookupTable['+'] |= PATH_CHARACTERS; fgLookupTable['$'] |= PATH_CHARACTERS; fgLookupTable[','] |= PATH_CHARACTERS; } /** Stores the scheme (usually the protocol) for this URI. */ private String m_scheme = null; /** If specified, stores the userinfo for this URI; otherwise null */ private String m_userinfo = null; /** If specified, stores the host for this URI; otherwise null */ private String m_host = null; /** If specified, stores the port for this URI; otherwise -1 */ private int m_port = -1; /** If specified, stores the registry based authority for this URI; otherwise -1 */ private String m_regAuthority = null; /** If specified, stores the path for this URI; otherwise null */ private String m_path = null; /** If specified, stores the query string for this URI; otherwise null. */ private String m_queryString = null; /** If specified, stores the fragment for this URI; otherwise null */ private String m_fragment = null; private static boolean DEBUG = false; /** * Construct a new and uninitialized URI. */ public URI() { } /** * Construct a new URI from another URI. All fields for this URI are * set equal to the fields of the URI passed in. * * @param p_other the URI to copy (cannot be null) */ public URI(URI p_other) { initialize(p_other); } /** * Construct a new URI from a URI specification string. If the * specification follows the "generic URI" syntax, (two slashes * following the first colon), the specification will be parsed * accordingly - setting the scheme, userinfo, host,port, path, query * string and fragment fields as necessary. If the specification does * not follow the "generic URI" syntax, the specification is parsed * into a scheme and scheme-specific part (stored as the path) only. * * @param p_uriSpec the URI specification string (cannot be null or * empty) * * @exception MalformedURIException if p_uriSpec violates any syntax * rules */ public URI(String p_uriSpec) throws MalformedURIException { this((URI)null, p_uriSpec); } /** * Construct a new URI from a base URI and a URI specification string. * The URI specification string may be a relative URI. * * @param p_base the base URI (cannot be null if p_uriSpec is null or * empty) * @param p_uriSpec the URI specification string (cannot be null or * empty if p_base is null) * * @exception MalformedURIException if p_uriSpec violates any syntax * rules */ public URI(URI p_base, String p_uriSpec) throws MalformedURIException { initialize(p_base, p_uriSpec); } /** * Construct a new URI that does not follow the generic URI syntax. * Only the scheme and scheme-specific part (stored as the path) are * initialized. * * @param p_scheme the URI scheme (cannot be null or empty) * @param p_schemeSpecificPart the scheme-specific part (cannot be * null or empty) * * @exception MalformedURIException if p_scheme violates any * syntax rules */ public URI(String p_scheme, String p_schemeSpecificPart) throws MalformedURIException { if (p_scheme == null || p_scheme.trim().length() == 0) { throw new MalformedURIException( "Cannot construct URI with null/empty scheme!"); } if (p_schemeSpecificPart == null || p_schemeSpecificPart.trim().length() == 0) { throw new MalformedURIException( "Cannot construct URI with null/empty scheme-specific part!"); } setScheme(p_scheme); setPath(p_schemeSpecificPart); } /** * Construct a new URI that follows the generic URI syntax from its * component parts. Each component is validated for syntax and some * basic semantic checks are performed as well. See the individual * setter methods for specifics. * * @param p_scheme the URI scheme (cannot be null or empty) * @param p_host the hostname, IPv4 address or IPv6 reference for the URI * @param p_path the URI path - if the path contains '?' or '#', * then the query string and/or fragment will be * set from the path; however, if the query and * fragment are specified both in the path and as * separate parameters, an exception is thrown * @param p_queryString the URI query string (cannot be specified * if path is null) * @param p_fragment the URI fragment (cannot be specified if path * is null) * * @exception MalformedURIException if any of the parameters violates * syntax rules or semantic rules */ public URI(String p_scheme, String p_host, String p_path, String p_queryString, String p_fragment) throws MalformedURIException { this(p_scheme, null, p_host, -1, p_path, p_queryString, p_fragment); } /** * Construct a new URI that follows the generic URI syntax from its * component parts. Each component is validated for syntax and some * basic semantic checks are performed as well. See the individual * setter methods for specifics. * * @param p_scheme the URI scheme (cannot be null or empty) * @param p_userinfo the URI userinfo (cannot be specified if host * is null) * @param p_host the hostname, IPv4 address or IPv6 reference for the URI * @param p_port the URI port (may be -1 for "unspecified"; cannot * be specified if host is null) * @param p_path the URI path - if the path contains '?' or '#', * then the query string and/or fragment will be * set from the path; however, if the query and * fragment are specified both in the path and as * separate parameters, an exception is thrown * @param p_queryString the URI query string (cannot be specified * if path is null) * @param p_fragment the URI fragment (cannot be specified if path * is null) * * @exception MalformedURIException if any of the parameters violates * syntax rules or semantic rules */ public URI(String p_scheme, String p_userinfo, String p_host, int p_port, String p_path, String p_queryString, String p_fragment) throws MalformedURIException { if (p_scheme == null || p_scheme.trim().length() == 0) { throw new MalformedURIException("Scheme is required!"); } if (p_host == null) { if (p_userinfo != null) { throw new MalformedURIException( "Userinfo may not be specified if host is not specified!"); } if (p_port != -1) { throw new MalformedURIException( "Port may not be specified if host is not specified!"); } } if (p_path != null) { if (p_path.indexOf('?') != -1 && p_queryString != null) { throw new MalformedURIException( "Query string cannot be specified in path and query string!"); } if (p_path.indexOf('#') != -1 && p_fragment != null) { throw new MalformedURIException( "Fragment cannot be specified in both the path and fragment!"); } } setScheme(p_scheme); setHost(p_host); setPort(p_port); setUserinfo(p_userinfo); setPath(p_path); setQueryString(p_queryString); setFragment(p_fragment); } /** * Initialize all fields of this URI from another URI. * * @param p_other the URI to copy (cannot be null) */ private void initialize(URI p_other) { m_scheme = p_other.getScheme(); m_userinfo = p_other.getUserinfo(); m_host = p_other.getHost(); m_port = p_other.getPort(); m_regAuthority = p_other.getRegBasedAuthority(); m_path = p_other.getPath(); m_queryString = p_other.getQueryString(); m_fragment = p_other.getFragment(); } /** * Initializes this URI from a base URI and a URI specification string. * See RFC 2396 Section 4 and Appendix B for specifications on parsing * the URI and Section 5 for specifications on resolving relative URIs * and relative paths. * * @param p_base the base URI (may be null if p_uriSpec is an absolute * URI) * @param p_uriSpec the URI spec string which may be an absolute or * relative URI (can only be null/empty if p_base * is not null) * * @exception MalformedURIException if p_base is null and p_uriSpec * is not an absolute URI or if * p_uriSpec violates syntax rules */ private void initialize(URI p_base, String p_uriSpec) throws MalformedURIException { - String uriSpec = (p_uriSpec != null) ? p_uriSpec.trim() : null; + String uriSpec = p_uriSpec; int uriSpecLen = (uriSpec != null) ? uriSpec.length() : 0; if (p_base == null && uriSpecLen == 0) { throw new MalformedURIException( "Cannot initialize URI with empty parameters."); } // just make a copy of the base if spec is empty if (uriSpecLen == 0) { initialize(p_base); return; } int index = 0; // Check for scheme, which must be before '/', '?' or '#'. Also handle // names with DOS drive letters ('D:'), so 1-character schemes are not // allowed. int colonIdx = uriSpec.indexOf(':'); int slashIdx = uriSpec.indexOf('/'); int queryIdx = uriSpec.indexOf('?'); int fragmentIdx = uriSpec.indexOf('#'); if ((colonIdx < 2) || (colonIdx > slashIdx && slashIdx != -1) || (colonIdx > queryIdx && queryIdx != -1) || (colonIdx > fragmentIdx && fragmentIdx != -1)) { // A standalone base is a valid URI according to spec if (colonIdx == 0 || (p_base == null && fragmentIdx != 0)) { throw new MalformedURIException("No scheme found in URI."); } } else { initializeScheme(uriSpec); index = m_scheme.length()+1; // Neither 'scheme:' or 'scheme:#fragment' are valid URIs. if (colonIdx == uriSpecLen - 1 || uriSpec.charAt(colonIdx+1) == '#') { throw new MalformedURIException("Scheme specific part cannot be empty."); } } // Two slashes means we may have authority, but definitely means we're either // matching net_path or abs_path. These two productions are ambiguous in that // every net_path (except those containing an IPv6Reference) is an abs_path. // RFC 2396 resolves this ambiguity by applying a greedy left most matching rule. // Try matching net_path first, and if that fails we don't have authority so // then attempt to match abs_path. // // net_path = "//" authority [ abs_path ] // abs_path = "/" path_segments if (((index+1) < uriSpecLen) && (uriSpec.charAt(index) == '/' && uriSpec.charAt(index+1) == '/')) { index += 2; int startPos = index; // Authority will be everything up to path, query or fragment char testChar = '\0'; while (index < uriSpecLen) { testChar = uriSpec.charAt(index); if (testChar == '/' || testChar == '?' || testChar == '#') { break; } index++; } // Attempt to parse authority. If the section is an empty string // this is a valid server based authority, so set the host to this // value. if (index > startPos) { // If we didn't find authority we need to back up. Attempt to // match against abs_path next. if (!initializeAuthority(uriSpec.substring(startPos, index))) { index = startPos - 2; } } else { m_host = ""; } } initializePath(uriSpec, index); // Resolve relative URI to base URI - see RFC 2396 Section 5.2 // In some cases, it might make more sense to throw an exception // (when scheme is specified is the string spec and the base URI // is also specified, for example), but we're just following the // RFC specifications if (p_base != null) { // check to see if this is the current doc - RFC 2396 5.2 #2 // note that this is slightly different from the RFC spec in that // we don't include the check for query string being null // - this handles cases where the urispec is just a query // string or a fragment (e.g. "?y" or "#s") - // see <http://www.ics.uci.edu/~fielding/url/test1.html> which // identified this as a bug in the RFC if (m_path.length() == 0 && m_scheme == null && m_host == null && m_regAuthority == null) { m_scheme = p_base.getScheme(); m_userinfo = p_base.getUserinfo(); m_host = p_base.getHost(); m_port = p_base.getPort(); m_regAuthority = p_base.getRegBasedAuthority(); m_path = p_base.getPath(); if (m_queryString == null) { m_queryString = p_base.getQueryString(); } return; } // check for scheme - RFC 2396 5.2 #3 // if we found a scheme, it means absolute URI, so we're done if (m_scheme == null) { m_scheme = p_base.getScheme(); } else { return; } // check for authority - RFC 2396 5.2 #4 // if we found a host, then we've got a network path, so we're done if (m_host == null && m_regAuthority == null) { m_userinfo = p_base.getUserinfo(); m_host = p_base.getHost(); m_port = p_base.getPort(); m_regAuthority = p_base.getRegBasedAuthority(); } else { return; } // check for absolute path - RFC 2396 5.2 #5 if (m_path.length() > 0 && m_path.startsWith("/")) { return; } // if we get to this point, we need to resolve relative path // RFC 2396 5.2 #6 String path = ""; String basePath = p_base.getPath(); // 6a - get all but the last segment of the base URI path if (basePath != null && basePath.length() > 0) { int lastSlash = basePath.lastIndexOf('/'); if (lastSlash != -1) { path = basePath.substring(0, lastSlash+1); } } else if (m_path.length() > 0) { path = "/"; } // 6b - append the relative URI path path = path.concat(m_path); // 6c - remove all "./" where "." is a complete path segment index = -1; while ((index = path.indexOf("/./")) != -1) { path = path.substring(0, index+1).concat(path.substring(index+3)); } // 6d - remove "." if path ends with "." as a complete path segment if (path.endsWith("/.")) { path = path.substring(0, path.length()-1); } // 6e - remove all "<segment>/../" where "<segment>" is a complete // path segment not equal to ".." index = 1; int segIndex = -1; String tempString = null; while ((index = path.indexOf("/../", index)) > 0) { tempString = path.substring(0, path.indexOf("/../")); segIndex = tempString.lastIndexOf('/'); if (segIndex != -1) { if (!tempString.substring(segIndex).equals("..")) { path = path.substring(0, segIndex+1).concat(path.substring(index+4)); index = segIndex; } else index += 4; } else index += 4; } // 6f - remove ending "<segment>/.." where "<segment>" is a // complete path segment if (path.endsWith("/..")) { tempString = path.substring(0, path.length()-3); segIndex = tempString.lastIndexOf('/'); if (segIndex != -1) { path = path.substring(0, segIndex+1); } } m_path = path; } } /** * Initialize the scheme for this URI from a URI string spec. * * @param p_uriSpec the URI specification (cannot be null) * * @exception MalformedURIException if URI does not have a conformant * scheme */ private void initializeScheme(String p_uriSpec) throws MalformedURIException { int uriSpecLen = p_uriSpec.length(); int index = 0; String scheme = null; char testChar = '\0'; while (index < uriSpecLen) { testChar = p_uriSpec.charAt(index); if (testChar == ':' || testChar == '/' || testChar == '?' || testChar == '#') { break; } index++; } scheme = p_uriSpec.substring(0, index); if (scheme.length() == 0) { throw new MalformedURIException("No scheme found in URI."); } else { setScheme(scheme); } } /** * Initialize the authority (either server or registry based) * for this URI from a URI string spec. * * @param p_uriSpec the URI specification (cannot be null) * * @return true if the given string matched server or registry * based authority */ private boolean initializeAuthority(String p_uriSpec) { int index = 0; int start = 0; int end = p_uriSpec.length(); char testChar = '\0'; String userinfo = null; // userinfo is everything up to @ if (p_uriSpec.indexOf('@', start) != -1) { while (index < end) { testChar = p_uriSpec.charAt(index); if (testChar == '@') { break; } index++; } userinfo = p_uriSpec.substring(start, index); index++; } // host is everything up to last ':', or up to // and including ']' if followed by ':'. String host = null; start = index; boolean hasPort = false; if (index < end) { if (p_uriSpec.charAt(start) == '[') { int bracketIndex = p_uriSpec.indexOf(']', start); index = (bracketIndex != -1) ? bracketIndex : end; if (index+1 < end && p_uriSpec.charAt(index+1) == ':') { ++index; hasPort = true; } else { index = end; } } else { int colonIndex = p_uriSpec.lastIndexOf(':', end); index = (colonIndex > start) ? colonIndex : end; hasPort = (index != end); } } host = p_uriSpec.substring(start, index); int port = -1; if (host.length() > 0) { // port if (hasPort) { index++; start = index; while (index < end) { index++; } String portStr = p_uriSpec.substring(start, index); if (portStr.length() > 0) { // REVISIT: Remove this code. /** for (int i = 0; i < portStr.length(); i++) { if (!isDigit(portStr.charAt(i))) { throw new MalformedURIException( portStr + " is invalid. Port should only contain digits!"); } }**/ // REVISIT: Remove this code. // Store port value as string instead of integer. try { port = Integer.parseInt(portStr); if (port == -1) --port; } catch (NumberFormatException nfe) { port = -2; } } } } if (isValidServerBasedAuthority(host, port, userinfo)) { m_host = host; m_port = port; m_userinfo = userinfo; return true; } // Note: Registry based authority is being removed from a // new spec for URI which would obsolete RFC 2396. If the // spec is added to XML errata, processing of reg_name // needs to be removed. - mrglavas. else if (isValidRegistryBasedAuthority(p_uriSpec)) { m_regAuthority = p_uriSpec; return true; } return false; } /** * Determines whether the components host, port, and user info * are valid as a server authority. * * @param host the host component of authority * @param port the port number component of authority * @param userinfo the user info component of authority * * @return true if the given host, port, and userinfo compose * a valid server authority */ private boolean isValidServerBasedAuthority(String host, int port, String userinfo) { // Check if the host is well formed. if (!isWellFormedAddress(host)) { return false; } // Check that port is well formed if it exists. // REVISIT: There's no restriction on port value ranges, but // perform the same check as in setPort to be consistent. Pass // in a string to this method instead of an integer. if (port < -1 || port > 65535) { return false; } // Check that userinfo is well formed if it exists. if (userinfo != null) { // Userinfo can contain alphanumerics, mark characters, escaped // and ';',':','&','=','+','$',',' int index = 0; int end = userinfo.length(); char testChar = '\0'; while (index < end) { testChar = userinfo.charAt(index); if (testChar == '%') { if (index+2 >= end || !isHex(userinfo.charAt(index+1)) || !isHex(userinfo.charAt(index+2))) { return false; } index += 2; } else if (!isUserinfoCharacter(testChar)) { return false; } ++index; } } return true; } /** * Determines whether the given string is a registry based authority. * * @param authority the authority component of a URI * * @return true if the given string is a registry based authority */ private boolean isValidRegistryBasedAuthority(String authority) { int index = 0; int end = authority.length(); char testChar; while (index < end) { testChar = authority.charAt(index); // check for valid escape sequence if (testChar == '%') { if (index+2 >= end || !isHex(authority.charAt(index+1)) || !isHex(authority.charAt(index+2))) { return false; } index += 2; } // can check against path characters because the set // is the same except for '/' which we've already excluded. else if (!isPathCharacter(testChar)) { return false; } ++index; } return true; } /** * Initialize the path for this URI from a URI string spec. * * @param p_uriSpec the URI specification (cannot be null) * @param p_nStartIndex the index to begin scanning from * * @exception MalformedURIException if p_uriSpec violates syntax rules */ private void initializePath(String p_uriSpec, int p_nStartIndex) throws MalformedURIException { if (p_uriSpec == null) { throw new MalformedURIException( "Cannot initialize path from null string!"); } int index = p_nStartIndex; int start = p_nStartIndex; int end = p_uriSpec.length(); char testChar = '\0'; // path - everything up to query string or fragment if (start < end) { // RFC 2732 only allows '[' and ']' to appear in the opaque part. if (getScheme() == null || p_uriSpec.charAt(start) == '/') { // Scan path. // abs_path = "/" path_segments // rel_path = rel_segment [ abs_path ] while (index < end) { testChar = p_uriSpec.charAt(index); // check for valid escape sequence if (testChar == '%') { if (index+2 >= end || !isHex(p_uriSpec.charAt(index+1)) || !isHex(p_uriSpec.charAt(index+2))) { throw new MalformedURIException( "Path contains invalid escape sequence!"); } index += 2; } // Path segments cannot contain '[' or ']' since pchar // production was not changed by RFC 2732. else if (!isPathCharacter(testChar)) { if (testChar == '?' || testChar == '#') { break; } throw new MalformedURIException( "Path contains invalid character: " + testChar); } ++index; } } else { // Scan opaque part. // opaque_part = uric_no_slash *uric while (index < end) { testChar = p_uriSpec.charAt(index); if (testChar == '?' || testChar == '#') { break; } // check for valid escape sequence if (testChar == '%') { if (index+2 >= end || !isHex(p_uriSpec.charAt(index+1)) || !isHex(p_uriSpec.charAt(index+2))) { throw new MalformedURIException( "Opaque part contains invalid escape sequence!"); } index += 2; } // If the scheme specific part is opaque, it can contain '[' // and ']'. uric_no_slash wasn't modified by RFC 2732, which // I've interpreted as an error in the spec, since the // production should be equivalent to (uric - '/'), and uric // contains '[' and ']'. - mrglavas else if (!isURICharacter(testChar)) { throw new MalformedURIException( "Opaque part contains invalid character: " + testChar); } ++index; } } } m_path = p_uriSpec.substring(start, index); // query - starts with ? and up to fragment or end if (testChar == '?') { index++; start = index; while (index < end) { testChar = p_uriSpec.charAt(index); if (testChar == '#') { break; } if (testChar == '%') { if (index+2 >= end || !isHex(p_uriSpec.charAt(index+1)) || !isHex(p_uriSpec.charAt(index+2))) { throw new MalformedURIException( "Query string contains invalid escape sequence!"); } index += 2; } else if (!isURICharacter(testChar)) { throw new MalformedURIException( "Query string contains invalid character: " + testChar); } index++; } m_queryString = p_uriSpec.substring(start, index); } // fragment - starts with # if (testChar == '#') { index++; start = index; while (index < end) { testChar = p_uriSpec.charAt(index); if (testChar == '%') { if (index+2 >= end || !isHex(p_uriSpec.charAt(index+1)) || !isHex(p_uriSpec.charAt(index+2))) { throw new MalformedURIException( "Fragment contains invalid escape sequence!"); } index += 2; } else if (!isURICharacter(testChar)) { throw new MalformedURIException( "Fragment contains invalid character: "+testChar); } index++; } m_fragment = p_uriSpec.substring(start, index); } } /** * Get the scheme for this URI. * * @return the scheme for this URI */ public String getScheme() { return m_scheme; } /** * Get the scheme-specific part for this URI (everything following the * scheme and the first colon). See RFC 2396 Section 5.2 for spec. * * @return the scheme-specific part for this URI */ public String getSchemeSpecificPart() { StringBuffer schemespec = new StringBuffer(); if (m_host != null || m_regAuthority != null) { schemespec.append("//"); // Server based authority. if (m_host != null) { if (m_userinfo != null) { schemespec.append(m_userinfo); schemespec.append('@'); } schemespec.append(m_host); if (m_port != -1) { schemespec.append(':'); schemespec.append(m_port); } } // Registry based authority. else { schemespec.append(m_regAuthority); } } if (m_path != null) { schemespec.append((m_path)); } if (m_queryString != null) { schemespec.append('?'); schemespec.append(m_queryString); } if (m_fragment != null) { schemespec.append('#'); schemespec.append(m_fragment); } return schemespec.toString(); } /** * Get the userinfo for this URI. * * @return the userinfo for this URI (null if not specified). */ public String getUserinfo() { return m_userinfo; } /** * Get the host for this URI. * * @return the host for this URI (null if not specified). */ public String getHost() { return m_host; } /** * Get the port for this URI. * * @return the port for this URI (-1 if not specified). */ public int getPort() { return m_port; } /** * Get the registry based authority for this URI. * * @return the registry based authority (null if not specified). */ public String getRegBasedAuthority() { return m_regAuthority; } /** * Get the path for this URI (optionally with the query string and * fragment). * * @param p_includeQueryString if true (and query string is not null), * then a "?" followed by the query string * will be appended * @param p_includeFragment if true (and fragment is not null), * then a "#" followed by the fragment * will be appended * * @return the path for this URI possibly including the query string * and fragment */ public String getPath(boolean p_includeQueryString, boolean p_includeFragment) { StringBuffer pathString = new StringBuffer(m_path); if (p_includeQueryString && m_queryString != null) { pathString.append('?'); pathString.append(m_queryString); } if (p_includeFragment && m_fragment != null) { pathString.append('#'); pathString.append(m_fragment); } return pathString.toString(); } /** * Get the path for this URI. Note that the value returned is the path * only and does not include the query string or fragment. * * @return the path for this URI. */ public String getPath() { return m_path; } /** * Get the query string for this URI. * * @return the query string for this URI. Null is returned if there * was no "?" in the URI spec, empty string if there was a * "?" but no query string following it. */ public String getQueryString() { return m_queryString; } /** * Get the fragment for this URI. * * @return the fragment for this URI. Null is returned if there * was no "#" in the URI spec, empty string if there was a * "#" but no fragment following it. */ public String getFragment() { return m_fragment; } /** * Set the scheme for this URI. The scheme is converted to lowercase * before it is set. * * @param p_scheme the scheme for this URI (cannot be null) * * @exception MalformedURIException if p_scheme is not a conformant * scheme name */ public void setScheme(String p_scheme) throws MalformedURIException { if (p_scheme == null) { throw new MalformedURIException( "Cannot set scheme from null string!"); } if (!isConformantSchemeName(p_scheme)) { throw new MalformedURIException("The scheme is not conformant."); } m_scheme = p_scheme.toLowerCase(); } /** * Set the userinfo for this URI. If a non-null value is passed in and * the host value is null, then an exception is thrown. * * @param p_userinfo the userinfo for this URI * * @exception MalformedURIException if p_userinfo contains invalid * characters */ public void setUserinfo(String p_userinfo) throws MalformedURIException { if (p_userinfo == null) { m_userinfo = null; return; } else { if (m_host == null) { throw new MalformedURIException( "Userinfo cannot be set when host is null!"); } // userinfo can contain alphanumerics, mark characters, escaped // and ';',':','&','=','+','$',',' int index = 0; int end = p_userinfo.length(); char testChar = '\0'; while (index < end) { testChar = p_userinfo.charAt(index); if (testChar == '%') { if (index+2 >= end || !isHex(p_userinfo.charAt(index+1)) || !isHex(p_userinfo.charAt(index+2))) { throw new MalformedURIException( "Userinfo contains invalid escape sequence!"); } } else if (!isUserinfoCharacter(testChar)) { throw new MalformedURIException( "Userinfo contains invalid character:"+testChar); } index++; } } m_userinfo = p_userinfo; } /** * <p>Set the host for this URI. If null is passed in, the userinfo * field is also set to null and the port is set to -1.</p> * * <p>Note: This method overwrites registry based authority if it * previously existed in this URI.</p> * * @param p_host the host for this URI * * @exception MalformedURIException if p_host is not a valid IP * address or DNS hostname. */ public void setHost(String p_host) throws MalformedURIException { if (p_host == null || p_host.length() == 0) { if (p_host != null) { m_regAuthority = null; } m_host = p_host; m_userinfo = null; m_port = -1; return; } else if (!isWellFormedAddress(p_host)) { throw new MalformedURIException("Host is not a well formed address!"); } m_host = p_host; m_regAuthority = null; } /** * Set the port for this URI. -1 is used to indicate that the port is * not specified, otherwise valid port numbers are between 0 and 65535. * If a valid port number is passed in and the host field is null, * an exception is thrown. * * @param p_port the port number for this URI * * @exception MalformedURIException if p_port is not -1 and not a * valid port number */ public void setPort(int p_port) throws MalformedURIException { if (p_port >= 0 && p_port <= 65535) { if (m_host == null) { throw new MalformedURIException( "Port cannot be set when host is null!"); } } else if (p_port != -1) { throw new MalformedURIException("Invalid port number!"); } m_port = p_port; } /** * <p>Sets the registry based authority for this URI.</p> * * <p>Note: This method overwrites server based authority * if it previously existed in this URI.</p> * * @param authority the registry based authority for this URI * * @exception MalformedURIException it authority is not a * well formed registry based authority */ public void setRegBasedAuthority(String authority) throws MalformedURIException { if (authority == null) { m_regAuthority = null; return; } // reg_name = 1*( unreserved | escaped | "$" | "," | // ";" | ":" | "@" | "&" | "=" | "+" ) else if (authority.length() < 1 || !isValidRegistryBasedAuthority(authority) || authority.indexOf('/') != -1) { throw new MalformedURIException("Registry based authority is not well formed."); } m_regAuthority = authority; m_host = null; m_userinfo = null; m_port = -1; } /** * Set the path for this URI. If the supplied path is null, then the * query string and fragment are set to null as well. If the supplied * path includes a query string and/or fragment, these fields will be * parsed and set as well. Note that, for URIs following the "generic * URI" syntax, the path specified should start with a slash. * For URIs that do not follow the generic URI syntax, this method * sets the scheme-specific part. * * @param p_path the path for this URI (may be null) * * @exception MalformedURIException if p_path contains invalid * characters */ public void setPath(String p_path) throws MalformedURIException { if (p_path == null) { m_path = null; m_queryString = null; m_fragment = null; } else { initializePath(p_path, 0); } } /** * Append to the end of the path of this URI. If the current path does * not end in a slash and the path to be appended does not begin with * a slash, a slash will be appended to the current path before the * new segment is added. Also, if the current path ends in a slash * and the new segment begins with a slash, the extra slash will be * removed before the new segment is appended. * * @param p_addToPath the new segment to be added to the current path * * @exception MalformedURIException if p_addToPath contains syntax * errors */ public void appendPath(String p_addToPath) throws MalformedURIException { if (p_addToPath == null || p_addToPath.trim().length() == 0) { return; } if (!isURIString(p_addToPath)) { throw new MalformedURIException( "Path contains invalid character!"); } if (m_path == null || m_path.trim().length() == 0) { if (p_addToPath.startsWith("/")) { m_path = p_addToPath; } else { m_path = "/" + p_addToPath; } } else if (m_path.endsWith("/")) { if (p_addToPath.startsWith("/")) { m_path = m_path.concat(p_addToPath.substring(1)); } else { m_path = m_path.concat(p_addToPath); } } else { if (p_addToPath.startsWith("/")) { m_path = m_path.concat(p_addToPath); } else { m_path = m_path.concat("/" + p_addToPath); } } } /** * Set the query string for this URI. A non-null value is valid only * if this is an URI conforming to the generic URI syntax and * the path value is not null. * * @param p_queryString the query string for this URI * * @exception MalformedURIException if p_queryString is not null and this * URI does not conform to the generic * URI syntax or if the path is null */ public void setQueryString(String p_queryString) throws MalformedURIException { if (p_queryString == null) { m_queryString = null; } else if (!isGenericURI()) { throw new MalformedURIException( "Query string can only be set for a generic URI!"); } else if (getPath() == null) { throw new MalformedURIException( "Query string cannot be set when path is null!"); } else if (!isURIString(p_queryString)) { throw new MalformedURIException( "Query string contains invalid character!"); } else { m_queryString = p_queryString; } } /** * Set the fragment for this URI. A non-null value is valid only * if this is a URI conforming to the generic URI syntax and * the path value is not null. * * @param p_fragment the fragment for this URI * * @exception MalformedURIException if p_fragment is not null and this * URI does not conform to the generic * URI syntax or if the path is null */ public void setFragment(String p_fragment) throws MalformedURIException { if (p_fragment == null) { m_fragment = null; } else if (!isGenericURI()) { throw new MalformedURIException( "Fragment can only be set for a generic URI!"); } else if (getPath() == null) { throw new MalformedURIException( "Fragment cannot be set when path is null!"); } else if (!isURIString(p_fragment)) { throw new MalformedURIException( "Fragment contains invalid character!"); } else { m_fragment = p_fragment; } } /** * Determines if the passed-in Object is equivalent to this URI. * * @param p_test the Object to test for equality. * * @return true if p_test is a URI with all values equal to this * URI, false otherwise */ public boolean equals(Object p_test) { if (p_test instanceof URI) { URI testURI = (URI) p_test; if (((m_scheme == null && testURI.m_scheme == null) || (m_scheme != null && testURI.m_scheme != null && m_scheme.equals(testURI.m_scheme))) && ((m_userinfo == null && testURI.m_userinfo == null) || (m_userinfo != null && testURI.m_userinfo != null && m_userinfo.equals(testURI.m_userinfo))) && ((m_host == null && testURI.m_host == null) || (m_host != null && testURI.m_host != null && m_host.equals(testURI.m_host))) && m_port == testURI.m_port && ((m_path == null && testURI.m_path == null) || (m_path != null && testURI.m_path != null && m_path.equals(testURI.m_path))) && ((m_queryString == null && testURI.m_queryString == null) || (m_queryString != null && testURI.m_queryString != null && m_queryString.equals(testURI.m_queryString))) && ((m_fragment == null && testURI.m_fragment == null) || (m_fragment != null && testURI.m_fragment != null && m_fragment.equals(testURI.m_fragment)))) { return true; } } return false; } /** * Get the URI as a string specification. See RFC 2396 Section 5.2. * * @return the URI string specification */ public String toString() { StringBuffer uriSpecString = new StringBuffer(); if (m_scheme != null) { uriSpecString.append(m_scheme); uriSpecString.append(':'); } uriSpecString.append(getSchemeSpecificPart()); return uriSpecString.toString(); } /** * Get the indicator as to whether this URI uses the "generic URI" * syntax. * * @return true if this URI uses the "generic URI" syntax, false * otherwise */ public boolean isGenericURI() { // presence of the host (whether valid or empty) means // double-slashes which means generic uri return (m_host != null); } /** * Determine whether a scheme conforms to the rules for a scheme name. * A scheme is conformant if it starts with an alphanumeric, and * contains only alphanumerics, '+','-' and '.'. * * @return true if the scheme is conformant, false otherwise */ public static boolean isConformantSchemeName(String p_scheme) { if (p_scheme == null || p_scheme.trim().length() == 0) { return false; } if (!isAlpha(p_scheme.charAt(0))) { return false; } char testChar; int schemeLength = p_scheme.length(); for (int i = 1; i < schemeLength; ++i) { testChar = p_scheme.charAt(i); if (!isSchemeCharacter(testChar)) { return false; } } return true; } /** * Determine whether a string is syntactically capable of representing * a valid IPv4 address, IPv6 reference or the domain name of a network host. * A valid IPv4 address consists of four decimal digit groups separated by a * '.'. Each group must consist of one to three digits. See RFC 2732 Section 3, * and RFC 2373 Section 2.2, for the definition of IPv6 references. A hostname * consists of domain labels (each of which must begin and end with an alphanumeric * but may contain '-') separated & by a '.'. See RFC 2396 Section 3.2.2. * * @return true if the string is a syntactically valid IPv4 address, * IPv6 reference or hostname */ public static boolean isWellFormedAddress(String address) { if (address == null) { return false; } int addrLength = address.length(); if (addrLength == 0) { return false; } // Check if the host is a valid IPv6reference. if (address.startsWith("[")) { return isWellFormedIPv6Reference(address); } // Cannot start with a '.', '-', or end with a '-'. if (address.startsWith(".") || address.startsWith("-") || address.endsWith("-")) { return false; } // rightmost domain label starting with digit indicates IP address // since top level domain label can only start with an alpha // see RFC 2396 Section 3.2.2 int index = address.lastIndexOf('.'); if (address.endsWith(".")) { index = address.substring(0, index).lastIndexOf('.'); } if (index+1 < addrLength && isDigit(address.charAt(index+1))) { return isWellFormedIPv4Address(address); } else { // hostname = *( domainlabel "." ) toplabel [ "." ] // domainlabel = alphanum | alphanum *( alphanum | "-" ) alphanum // toplabel = alpha | alpha *( alphanum | "-" ) alphanum // RFC 2396 states that hostnames take the form described in // RFC 1034 (Section 3) and RFC 1123 (Section 2.1). According // to RFC 1034, hostnames are limited to 255 characters. if (addrLength > 255) { return false; } // domain labels can contain alphanumerics and '-" // but must start and end with an alphanumeric char testChar; int labelCharCount = 0; for (int i = 0; i < addrLength; i++) { testChar = address.charAt(i); if (testChar == '.') { if (!isAlphanum(address.charAt(i-1))) { return false; } if (i+1 < addrLength && !isAlphanum(address.charAt(i+1))) { return false; } labelCharCount = 0; } else if (!isAlphanum(testChar) && testChar != '-') { return false; } // RFC 1034: Labels must be 63 characters or less. else if (++labelCharCount > 63) { return false; } } } return true; } /** * <p>Determines whether a string is an IPv4 address as defined by * RFC 2373, and under the further constraint that it must be a 32-bit * address. Though not expressed in the grammar, in order to satisfy * the 32-bit address constraint, each segment of the address cannot * be greater than 255 (8 bits of information).</p> * * <p><code>IPv4address = 1*3DIGIT "." 1*3DIGIT "." 1*3DIGIT "." 1*3DIGIT</code></p> * * @return true if the string is a syntactically valid IPv4 address */ public static boolean isWellFormedIPv4Address(String address) { int addrLength = address.length(); char testChar; int numDots = 0; int numDigits = 0; // make sure that 1) we see only digits and dot separators, 2) that // any dot separator is preceded and followed by a digit and // 3) that we find 3 dots // // RFC 2732 amended RFC 2396 by replacing the definition // of IPv4address with the one defined by RFC 2373. - mrglavas // // IPv4address = 1*3DIGIT "." 1*3DIGIT "." 1*3DIGIT "." 1*3DIGIT // // One to three digits must be in each segment. for (int i = 0; i < addrLength; i++) { testChar = address.charAt(i); if (testChar == '.') { if ((i > 0 && !isDigit(address.charAt(i-1))) || (i+1 < addrLength && !isDigit(address.charAt(i+1)))) { return false; } numDigits = 0; if (++numDots > 3) { return false; } } else if (!isDigit(testChar)) { return false; } // Check that that there are no more than three digits // in this segment. else if (++numDigits > 3) { return false; } // Check that this segment is not greater than 255. else if (numDigits == 3) { char first = address.charAt(i-2); char second = address.charAt(i-1); if (!(first < '2' || (first == '2' && (second < '5' || (second == '5' && testChar <= '5'))))) { return false; } } } return (numDots == 3); } /** * <p>Determines whether a string is an IPv6 reference as defined * by RFC 2732, where IPv6address is defined in RFC 2373. The * IPv6 address is parsed according to Section 2.2 of RFC 2373, * with the additional constraint that the address be composed of * 128 bits of information.</p> * * <p><code>IPv6reference = "[" IPv6address "]"</code></p> * * <p>Note: The BNF expressed in RFC 2373 Appendix B does not * accurately describe section 2.2, and was in fact removed from * RFC 3513, the successor of RFC 2373.</p> * * @return true if the string is a syntactically valid IPv6 reference */ public static boolean isWellFormedIPv6Reference(String address) { int addrLength = address.length(); int index = 1; int end = addrLength-1; // Check if string is a potential match for IPv6reference. if (!(addrLength > 2 && address.charAt(0) == '[' && address.charAt(end) == ']')) { return false; } // Counter for the number of 16-bit sections read in the address. int [] counter = new int[1]; // Scan hex sequence before possible '::' or IPv4 address. index = scanHexSequence(address, index, end, counter); if (index == -1) { return false; } // Address must contain 128-bits of information. else if (index == end) { return (counter[0] == 8); } if (index+1 < end && address.charAt(index) == ':') { if (address.charAt(index+1) == ':') { // '::' represents at least one 16-bit group of zeros. if (++counter[0] > 8) { return false; } index += 2; // Trailing zeros will fill out the rest of the address. if (index == end) { return true; } } // If the second character wasn't ':', in order to be valid, // the remainder of the string must match IPv4Address, // and we must have read exactly 6 16-bit groups. else { return (counter[0] == 6) && isWellFormedIPv4Address(address.substring(index+1, end)); } } else { return false; } // 3. Scan hex sequence after '::'. int prevCount = counter[0]; index = scanHexSequence(address, index, end, counter); // We've either reached the end of the string, the address ends in // an IPv4 address, or it is invalid. scanHexSequence has already // made sure that we have the right number of bits. return (index == end) || (index != -1 && isWellFormedIPv4Address( address.substring((counter[0] > prevCount) ? index+1 : index, end))); } /** * Helper method for isWellFormedIPv6Reference which scans the * hex sequences of an IPv6 address. It returns the index of the * next character to scan in the address, or -1 if the string * cannot match a valid IPv6 address. * * @param address the string to be scanned * @param index the beginning index (inclusive) * @param end the ending index (exclusive) * @param counter a counter for the number of 16-bit sections read * in the address * * @return the index of the next character to scan, or -1 if the * string cannot match a valid IPv6 address */ private static int scanHexSequence (String address, int index, int end, int [] counter) { char testChar; int numDigits = 0; int start = index; // Trying to match the following productions: // hexseq = hex4 *( ":" hex4) // hex4 = 1*4HEXDIG for (; index < end; ++index) { testChar = address.charAt(index); if (testChar == ':') { // IPv6 addresses are 128-bit, so there can be at most eight sections. if (numDigits > 0 && ++counter[0] > 8) { return -1; } // This could be '::'. if (numDigits == 0 || ((index+1 < end) && address.charAt(index+1) == ':')) { return index; } numDigits = 0; } // This might be invalid or an IPv4address. If it's potentially an IPv4address, // backup to just after the last valid character that matches hexseq. else if (!isHex(testChar)) { if (testChar == '.' && numDigits < 4 && numDigits > 0 && counter[0] <= 6) { int back = index - numDigits - 1; return (back >= start) ? back : (back+1); } return -1; } // There can be at most 4 hex digits per group. else if (++numDigits > 4) { return -1; } } return (numDigits > 0 && ++counter[0] <= 8) ? end : -1; } /** * Determine whether a char is a digit. * * @return true if the char is betweeen '0' and '9', false otherwise */ private static boolean isDigit(char p_char) { return p_char >= '0' && p_char <= '9'; } /** * Determine whether a character is a hexadecimal character. * * @return true if the char is betweeen '0' and '9', 'a' and 'f' * or 'A' and 'F', false otherwise */ private static boolean isHex(char p_char) { return (p_char <= 'f' && (fgLookupTable[p_char] & ASCII_HEX_CHARACTERS) != 0); } /** * Determine whether a char is an alphabetic character: a-z or A-Z * * @return true if the char is alphabetic, false otherwise */ private static boolean isAlpha(char p_char) { return ((p_char >= 'a' && p_char <= 'z') || (p_char >= 'A' && p_char <= 'Z' )); } /** * Determine whether a char is an alphanumeric: 0-9, a-z or A-Z * * @return true if the char is alphanumeric, false otherwise */ private static boolean isAlphanum(char p_char) { return (p_char <= 'z' && (fgLookupTable[p_char] & MASK_ALPHA_NUMERIC) != 0); } /** * Determine whether a character is a reserved character: * ';', '/', '?', ':', '@', '&', '=', '+', '$', ',', '[', or ']' * * @return true if the string contains any reserved characters */ private static boolean isReservedCharacter(char p_char) { return (p_char <= ']' && (fgLookupTable[p_char] & RESERVED_CHARACTERS) != 0); } /** * Determine whether a char is an unreserved character. * * @return true if the char is unreserved, false otherwise */ private static boolean isUnreservedCharacter(char p_char) { return (p_char <= '~' && (fgLookupTable[p_char] & MASK_UNRESERVED_MASK) != 0); } /** * Determine whether a char is a URI character (reserved or * unreserved, not including '%' for escaped octets). * * @return true if the char is a URI character, false otherwise */ private static boolean isURICharacter (char p_char) { return (p_char <= '~' && (fgLookupTable[p_char] & MASK_URI_CHARACTER) != 0); } /** * Determine whether a char is a scheme character. * * @return true if the char is a scheme character, false otherwise */ private static boolean isSchemeCharacter (char p_char) { return (p_char <= 'z' && (fgLookupTable[p_char] & MASK_SCHEME_CHARACTER) != 0); } /** * Determine whether a char is a userinfo character. * * @return true if the char is a userinfo character, false otherwise */ private static boolean isUserinfoCharacter (char p_char) { return (p_char <= 'z' && (fgLookupTable[p_char] & MASK_USERINFO_CHARACTER) != 0); } /** * Determine whether a char is a path character. * * @return true if the char is a path character, false otherwise */ private static boolean isPathCharacter (char p_char) { return (p_char <= '~' && (fgLookupTable[p_char] & MASK_PATH_CHARACTER) != 0); } /** * Determine whether a given string contains only URI characters (also * called "uric" in RFC 2396). uric consist of all reserved * characters, unreserved characters and escaped characters. * * @return true if the string is comprised of uric, false otherwise */ private static boolean isURIString(String p_uric) { if (p_uric == null) { return false; } int end = p_uric.length(); char testChar = '\0'; for (int i = 0; i < end; i++) { testChar = p_uric.charAt(i); if (testChar == '%') { if (i+2 >= end || !isHex(p_uric.charAt(i+1)) || !isHex(p_uric.charAt(i+2))) { return false; } else { i += 2; continue; } } if (isURICharacter(testChar)) { continue; } else { return false; } } return true; } }
true
true
private void initialize(URI p_base, String p_uriSpec) throws MalformedURIException { String uriSpec = (p_uriSpec != null) ? p_uriSpec.trim() : null; int uriSpecLen = (uriSpec != null) ? uriSpec.length() : 0; if (p_base == null && uriSpecLen == 0) { throw new MalformedURIException( "Cannot initialize URI with empty parameters."); } // just make a copy of the base if spec is empty if (uriSpecLen == 0) { initialize(p_base); return; } int index = 0; // Check for scheme, which must be before '/', '?' or '#'. Also handle // names with DOS drive letters ('D:'), so 1-character schemes are not // allowed. int colonIdx = uriSpec.indexOf(':'); int slashIdx = uriSpec.indexOf('/'); int queryIdx = uriSpec.indexOf('?'); int fragmentIdx = uriSpec.indexOf('#'); if ((colonIdx < 2) || (colonIdx > slashIdx && slashIdx != -1) || (colonIdx > queryIdx && queryIdx != -1) || (colonIdx > fragmentIdx && fragmentIdx != -1)) { // A standalone base is a valid URI according to spec if (colonIdx == 0 || (p_base == null && fragmentIdx != 0)) { throw new MalformedURIException("No scheme found in URI."); } } else { initializeScheme(uriSpec); index = m_scheme.length()+1; // Neither 'scheme:' or 'scheme:#fragment' are valid URIs. if (colonIdx == uriSpecLen - 1 || uriSpec.charAt(colonIdx+1) == '#') { throw new MalformedURIException("Scheme specific part cannot be empty."); } } // Two slashes means we may have authority, but definitely means we're either // matching net_path or abs_path. These two productions are ambiguous in that // every net_path (except those containing an IPv6Reference) is an abs_path. // RFC 2396 resolves this ambiguity by applying a greedy left most matching rule. // Try matching net_path first, and if that fails we don't have authority so // then attempt to match abs_path. // // net_path = "//" authority [ abs_path ] // abs_path = "/" path_segments if (((index+1) < uriSpecLen) && (uriSpec.charAt(index) == '/' && uriSpec.charAt(index+1) == '/')) { index += 2; int startPos = index; // Authority will be everything up to path, query or fragment char testChar = '\0'; while (index < uriSpecLen) { testChar = uriSpec.charAt(index); if (testChar == '/' || testChar == '?' || testChar == '#') { break; } index++; } // Attempt to parse authority. If the section is an empty string // this is a valid server based authority, so set the host to this // value. if (index > startPos) { // If we didn't find authority we need to back up. Attempt to // match against abs_path next. if (!initializeAuthority(uriSpec.substring(startPos, index))) { index = startPos - 2; } } else { m_host = ""; } } initializePath(uriSpec, index); // Resolve relative URI to base URI - see RFC 2396 Section 5.2 // In some cases, it might make more sense to throw an exception // (when scheme is specified is the string spec and the base URI // is also specified, for example), but we're just following the // RFC specifications if (p_base != null) { // check to see if this is the current doc - RFC 2396 5.2 #2 // note that this is slightly different from the RFC spec in that // we don't include the check for query string being null // - this handles cases where the urispec is just a query // string or a fragment (e.g. "?y" or "#s") - // see <http://www.ics.uci.edu/~fielding/url/test1.html> which // identified this as a bug in the RFC if (m_path.length() == 0 && m_scheme == null && m_host == null && m_regAuthority == null) { m_scheme = p_base.getScheme(); m_userinfo = p_base.getUserinfo(); m_host = p_base.getHost(); m_port = p_base.getPort(); m_regAuthority = p_base.getRegBasedAuthority(); m_path = p_base.getPath(); if (m_queryString == null) { m_queryString = p_base.getQueryString(); } return; } // check for scheme - RFC 2396 5.2 #3 // if we found a scheme, it means absolute URI, so we're done if (m_scheme == null) { m_scheme = p_base.getScheme(); } else { return; } // check for authority - RFC 2396 5.2 #4 // if we found a host, then we've got a network path, so we're done if (m_host == null && m_regAuthority == null) { m_userinfo = p_base.getUserinfo(); m_host = p_base.getHost(); m_port = p_base.getPort(); m_regAuthority = p_base.getRegBasedAuthority(); } else { return; } // check for absolute path - RFC 2396 5.2 #5 if (m_path.length() > 0 && m_path.startsWith("/")) { return; } // if we get to this point, we need to resolve relative path // RFC 2396 5.2 #6 String path = ""; String basePath = p_base.getPath(); // 6a - get all but the last segment of the base URI path if (basePath != null && basePath.length() > 0) { int lastSlash = basePath.lastIndexOf('/'); if (lastSlash != -1) { path = basePath.substring(0, lastSlash+1); } } else if (m_path.length() > 0) { path = "/"; } // 6b - append the relative URI path path = path.concat(m_path); // 6c - remove all "./" where "." is a complete path segment index = -1; while ((index = path.indexOf("/./")) != -1) { path = path.substring(0, index+1).concat(path.substring(index+3)); } // 6d - remove "." if path ends with "." as a complete path segment if (path.endsWith("/.")) { path = path.substring(0, path.length()-1); } // 6e - remove all "<segment>/../" where "<segment>" is a complete // path segment not equal to ".." index = 1; int segIndex = -1; String tempString = null; while ((index = path.indexOf("/../", index)) > 0) { tempString = path.substring(0, path.indexOf("/../")); segIndex = tempString.lastIndexOf('/'); if (segIndex != -1) { if (!tempString.substring(segIndex).equals("..")) { path = path.substring(0, segIndex+1).concat(path.substring(index+4)); index = segIndex; } else index += 4; } else index += 4; } // 6f - remove ending "<segment>/.." where "<segment>" is a // complete path segment if (path.endsWith("/..")) { tempString = path.substring(0, path.length()-3); segIndex = tempString.lastIndexOf('/'); if (segIndex != -1) { path = path.substring(0, segIndex+1); } } m_path = path; } }
private void initialize(URI p_base, String p_uriSpec) throws MalformedURIException { String uriSpec = p_uriSpec; int uriSpecLen = (uriSpec != null) ? uriSpec.length() : 0; if (p_base == null && uriSpecLen == 0) { throw new MalformedURIException( "Cannot initialize URI with empty parameters."); } // just make a copy of the base if spec is empty if (uriSpecLen == 0) { initialize(p_base); return; } int index = 0; // Check for scheme, which must be before '/', '?' or '#'. Also handle // names with DOS drive letters ('D:'), so 1-character schemes are not // allowed. int colonIdx = uriSpec.indexOf(':'); int slashIdx = uriSpec.indexOf('/'); int queryIdx = uriSpec.indexOf('?'); int fragmentIdx = uriSpec.indexOf('#'); if ((colonIdx < 2) || (colonIdx > slashIdx && slashIdx != -1) || (colonIdx > queryIdx && queryIdx != -1) || (colonIdx > fragmentIdx && fragmentIdx != -1)) { // A standalone base is a valid URI according to spec if (colonIdx == 0 || (p_base == null && fragmentIdx != 0)) { throw new MalformedURIException("No scheme found in URI."); } } else { initializeScheme(uriSpec); index = m_scheme.length()+1; // Neither 'scheme:' or 'scheme:#fragment' are valid URIs. if (colonIdx == uriSpecLen - 1 || uriSpec.charAt(colonIdx+1) == '#') { throw new MalformedURIException("Scheme specific part cannot be empty."); } } // Two slashes means we may have authority, but definitely means we're either // matching net_path or abs_path. These two productions are ambiguous in that // every net_path (except those containing an IPv6Reference) is an abs_path. // RFC 2396 resolves this ambiguity by applying a greedy left most matching rule. // Try matching net_path first, and if that fails we don't have authority so // then attempt to match abs_path. // // net_path = "//" authority [ abs_path ] // abs_path = "/" path_segments if (((index+1) < uriSpecLen) && (uriSpec.charAt(index) == '/' && uriSpec.charAt(index+1) == '/')) { index += 2; int startPos = index; // Authority will be everything up to path, query or fragment char testChar = '\0'; while (index < uriSpecLen) { testChar = uriSpec.charAt(index); if (testChar == '/' || testChar == '?' || testChar == '#') { break; } index++; } // Attempt to parse authority. If the section is an empty string // this is a valid server based authority, so set the host to this // value. if (index > startPos) { // If we didn't find authority we need to back up. Attempt to // match against abs_path next. if (!initializeAuthority(uriSpec.substring(startPos, index))) { index = startPos - 2; } } else { m_host = ""; } } initializePath(uriSpec, index); // Resolve relative URI to base URI - see RFC 2396 Section 5.2 // In some cases, it might make more sense to throw an exception // (when scheme is specified is the string spec and the base URI // is also specified, for example), but we're just following the // RFC specifications if (p_base != null) { // check to see if this is the current doc - RFC 2396 5.2 #2 // note that this is slightly different from the RFC spec in that // we don't include the check for query string being null // - this handles cases where the urispec is just a query // string or a fragment (e.g. "?y" or "#s") - // see <http://www.ics.uci.edu/~fielding/url/test1.html> which // identified this as a bug in the RFC if (m_path.length() == 0 && m_scheme == null && m_host == null && m_regAuthority == null) { m_scheme = p_base.getScheme(); m_userinfo = p_base.getUserinfo(); m_host = p_base.getHost(); m_port = p_base.getPort(); m_regAuthority = p_base.getRegBasedAuthority(); m_path = p_base.getPath(); if (m_queryString == null) { m_queryString = p_base.getQueryString(); } return; } // check for scheme - RFC 2396 5.2 #3 // if we found a scheme, it means absolute URI, so we're done if (m_scheme == null) { m_scheme = p_base.getScheme(); } else { return; } // check for authority - RFC 2396 5.2 #4 // if we found a host, then we've got a network path, so we're done if (m_host == null && m_regAuthority == null) { m_userinfo = p_base.getUserinfo(); m_host = p_base.getHost(); m_port = p_base.getPort(); m_regAuthority = p_base.getRegBasedAuthority(); } else { return; } // check for absolute path - RFC 2396 5.2 #5 if (m_path.length() > 0 && m_path.startsWith("/")) { return; } // if we get to this point, we need to resolve relative path // RFC 2396 5.2 #6 String path = ""; String basePath = p_base.getPath(); // 6a - get all but the last segment of the base URI path if (basePath != null && basePath.length() > 0) { int lastSlash = basePath.lastIndexOf('/'); if (lastSlash != -1) { path = basePath.substring(0, lastSlash+1); } } else if (m_path.length() > 0) { path = "/"; } // 6b - append the relative URI path path = path.concat(m_path); // 6c - remove all "./" where "." is a complete path segment index = -1; while ((index = path.indexOf("/./")) != -1) { path = path.substring(0, index+1).concat(path.substring(index+3)); } // 6d - remove "." if path ends with "." as a complete path segment if (path.endsWith("/.")) { path = path.substring(0, path.length()-1); } // 6e - remove all "<segment>/../" where "<segment>" is a complete // path segment not equal to ".." index = 1; int segIndex = -1; String tempString = null; while ((index = path.indexOf("/../", index)) > 0) { tempString = path.substring(0, path.indexOf("/../")); segIndex = tempString.lastIndexOf('/'); if (segIndex != -1) { if (!tempString.substring(segIndex).equals("..")) { path = path.substring(0, segIndex+1).concat(path.substring(index+4)); index = segIndex; } else index += 4; } else index += 4; } // 6f - remove ending "<segment>/.." where "<segment>" is a // complete path segment if (path.endsWith("/..")) { tempString = path.substring(0, path.length()-3); segIndex = tempString.lastIndexOf('/'); if (segIndex != -1) { path = path.substring(0, segIndex+1); } } m_path = path; } }
diff --git a/miner/src/java/ru/brandanalyst/miner/GrabberTwitter.java b/miner/src/java/ru/brandanalyst/miner/GrabberTwitter.java index d075275..47104de 100644 --- a/miner/src/java/ru/brandanalyst/miner/GrabberTwitter.java +++ b/miner/src/java/ru/brandanalyst/miner/GrabberTwitter.java @@ -1,157 +1,160 @@ package ru.brandanalyst.miner; import org.apache.log4j.Logger; import org.springframework.jdbc.core.simple.SimpleJdbcTemplate; import ru.brandanalyst.core.db.provider.ArticleProvider; import ru.brandanalyst.core.db.provider.BrandDictionaryProvider; import ru.brandanalyst.core.db.provider.BrandProvider; import ru.brandanalyst.core.model.Article; import ru.brandanalyst.core.model.Brand; import ru.brandanalyst.core.model.BrandDictionaryItem; import ru.brandanalyst.miner.util.StringChecker; import twitter4j.*; import java.sql.Timestamp; import java.text.SimpleDateFormat; import java.util.*; import static ru.brandanalyst.core.time.TimeProperties.SINGLE_DAY; /** * Created by IntelliJ IDEA. * User: Александр Сенов * Date: 10.10.11 * Time: 14:14 */ public class GrabberTwitter extends Grabber { private static final long TIME_LIMIT = (long) 10; private static final Logger log = Logger.getLogger(GrabberTwitter.class); private static final int ISSUANCE_SIZE = 1500; private static final int PAGE_SIZE = 100; @Deprecated public void setConfig(String config) { this.config = config; //not using } public void setJdbcTemplate(SimpleJdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } public void grab(Date timeLimit) { log.info("Twitter grabber started..."); Twitter twitter = new TwitterFactory().getInstance(); List<Brand> brandList = new BrandProvider(jdbcTemplate).getAllBrands(); ArticleProvider articleProvider = new ArticleProvider(jdbcTemplate); BrandDictionaryProvider dictionaryProvider = new BrandDictionaryProvider(jdbcTemplate); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); for (Brand b : brandList) { BrandDictionaryItem dictionary = dictionaryProvider.getDictionaryItem(b.getId()); for (int i = 0; i < 50; i++) { log.info("days ago: " + i + " brand:" + b.getName()); String untilTimeLimit = dateFormat.format(new Date().getTime() - ((long) i) * SINGLE_DAY); String sinceTimeLimit = dateFormat.format(new Date().getTime() - ((long) i + 1) * SINGLE_DAY); Query query = new Query(b.getName()); query.setRpp(PAGE_SIZE); query.setSince(sinceTimeLimit); query.setUntil(untilTimeLimit); query.setLang("ru"); query.setResultType(Query.MIXED); List<Tweet> resultTweets = new LinkedList<Tweet>(); QueryResult queryResult; int pageNumber = 1; try { + int resultsOnPage; do { query.setPage(pageNumber); queryResult = twitter.search(query); + resultsOnPage = -resultTweets.size(); resultTweets.addAll(queryResult.getTweets()); + resultsOnPage += resultTweets.size(); pageNumber++; - } while (ISSUANCE_SIZE > resultTweets.size()); + } while (ISSUANCE_SIZE > resultTweets.size() && resultsOnPage >= PAGE_SIZE); } catch (TwitterException e) { log.info("tweets in day: " + resultTweets.size()); // e.printStackTrace(); } Iterator<Map.Entry<String, TweetInfo>> resultIterator = removeDuplicates(resultTweets, dictionary).entrySet().iterator(); while (resultIterator.hasNext()) { Map.Entry<String, TweetInfo> next = resultIterator.next(); articleProvider.writeArticleToDataStore(new Article(-1, b.getId(), 2, "", "", next.getKey(), getSimpleTime(next.getValue().getTime()), next.getValue().getNumLikes())); } } log.info("twitter added for brandName = " + b.getName()); } log.info("twitter grabber finished succesful."); } private Timestamp getSimpleTime(Date date) { return new Timestamp((new Date(date.getYear(), date.getMonth(), date.getDay())).getTime()); } //bad style? - very bad private Map<String, TweetInfo> removeDuplicates(List<Tweet> resultTweets, BrandDictionaryItem dictionary) { Map<String, TweetInfo> tweetsInfoMap = new HashMap<String, TweetInfo>(); Iterator<Tweet> it = resultTweets.iterator(); while (it.hasNext()) { Tweet next = it.next(); if (StringChecker.hasTerm(dictionary, next.getText())) { String str = next.getText().trim(); int index = next.getText().indexOf("http"); if (index >= 0) { str = str.substring(0, index); } if (tweetsInfoMap.containsKey(str)) { TweetInfo tweetInfo = tweetsInfoMap.get(str); tweetInfo.setNumLikes(tweetInfo.getNumLikes() + 1); tweetsInfoMap.put(str, tweetInfo); } else { TweetInfo tweetInfo = new TweetInfo(new Timestamp(next.getCreatedAt().getTime()), 1); tweetsInfoMap.put(str, tweetInfo); } } } return tweetsInfoMap; } class TweetInfo { Timestamp time; int numLikes; TweetInfo(Timestamp time, int numLikes) { this.numLikes = numLikes; this.time = time; } public Timestamp getTime() { return time; } public void setTime(Timestamp time) { this.time = time; } public int getNumLikes() { return numLikes; } public void setNumLikes(int numLikes) { this.numLikes = numLikes; } } }
false
true
public void grab(Date timeLimit) { log.info("Twitter grabber started..."); Twitter twitter = new TwitterFactory().getInstance(); List<Brand> brandList = new BrandProvider(jdbcTemplate).getAllBrands(); ArticleProvider articleProvider = new ArticleProvider(jdbcTemplate); BrandDictionaryProvider dictionaryProvider = new BrandDictionaryProvider(jdbcTemplate); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); for (Brand b : brandList) { BrandDictionaryItem dictionary = dictionaryProvider.getDictionaryItem(b.getId()); for (int i = 0; i < 50; i++) { log.info("days ago: " + i + " brand:" + b.getName()); String untilTimeLimit = dateFormat.format(new Date().getTime() - ((long) i) * SINGLE_DAY); String sinceTimeLimit = dateFormat.format(new Date().getTime() - ((long) i + 1) * SINGLE_DAY); Query query = new Query(b.getName()); query.setRpp(PAGE_SIZE); query.setSince(sinceTimeLimit); query.setUntil(untilTimeLimit); query.setLang("ru"); query.setResultType(Query.MIXED); List<Tweet> resultTweets = new LinkedList<Tweet>(); QueryResult queryResult; int pageNumber = 1; try { do { query.setPage(pageNumber); queryResult = twitter.search(query); resultTweets.addAll(queryResult.getTweets()); pageNumber++; } while (ISSUANCE_SIZE > resultTweets.size()); } catch (TwitterException e) { log.info("tweets in day: " + resultTweets.size()); // e.printStackTrace(); } Iterator<Map.Entry<String, TweetInfo>> resultIterator = removeDuplicates(resultTweets, dictionary).entrySet().iterator(); while (resultIterator.hasNext()) { Map.Entry<String, TweetInfo> next = resultIterator.next(); articleProvider.writeArticleToDataStore(new Article(-1, b.getId(), 2, "", "", next.getKey(), getSimpleTime(next.getValue().getTime()), next.getValue().getNumLikes())); } } log.info("twitter added for brandName = " + b.getName()); } log.info("twitter grabber finished succesful."); }
public void grab(Date timeLimit) { log.info("Twitter grabber started..."); Twitter twitter = new TwitterFactory().getInstance(); List<Brand> brandList = new BrandProvider(jdbcTemplate).getAllBrands(); ArticleProvider articleProvider = new ArticleProvider(jdbcTemplate); BrandDictionaryProvider dictionaryProvider = new BrandDictionaryProvider(jdbcTemplate); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); for (Brand b : brandList) { BrandDictionaryItem dictionary = dictionaryProvider.getDictionaryItem(b.getId()); for (int i = 0; i < 50; i++) { log.info("days ago: " + i + " brand:" + b.getName()); String untilTimeLimit = dateFormat.format(new Date().getTime() - ((long) i) * SINGLE_DAY); String sinceTimeLimit = dateFormat.format(new Date().getTime() - ((long) i + 1) * SINGLE_DAY); Query query = new Query(b.getName()); query.setRpp(PAGE_SIZE); query.setSince(sinceTimeLimit); query.setUntil(untilTimeLimit); query.setLang("ru"); query.setResultType(Query.MIXED); List<Tweet> resultTweets = new LinkedList<Tweet>(); QueryResult queryResult; int pageNumber = 1; try { int resultsOnPage; do { query.setPage(pageNumber); queryResult = twitter.search(query); resultsOnPage = -resultTweets.size(); resultTweets.addAll(queryResult.getTweets()); resultsOnPage += resultTweets.size(); pageNumber++; } while (ISSUANCE_SIZE > resultTweets.size() && resultsOnPage >= PAGE_SIZE); } catch (TwitterException e) { log.info("tweets in day: " + resultTweets.size()); // e.printStackTrace(); } Iterator<Map.Entry<String, TweetInfo>> resultIterator = removeDuplicates(resultTweets, dictionary).entrySet().iterator(); while (resultIterator.hasNext()) { Map.Entry<String, TweetInfo> next = resultIterator.next(); articleProvider.writeArticleToDataStore(new Article(-1, b.getId(), 2, "", "", next.getKey(), getSimpleTime(next.getValue().getTime()), next.getValue().getNumLikes())); } } log.info("twitter added for brandName = " + b.getName()); } log.info("twitter grabber finished succesful."); }
diff --git a/src/fractalFlameV3/Main.java b/src/fractalFlameV3/Main.java index 566522d..a7d2b78 100644 --- a/src/fractalFlameV3/Main.java +++ b/src/fractalFlameV3/Main.java @@ -1,220 +1,219 @@ package fractalFlameV3; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import javax.imageio.stream.FileImageInputStream; import com.google.gson.GsonBuilder; import fractalFlameV3.fractalGenome.FractalGenome; import fractalFlameV3.fractalThread.FractalThread; import fractalFlameV3.fractalThread.ThreadSignal; import processing.core.PApplet; import processing.core.PConstants; public class Main extends PApplet { static boolean fullscreen = true; int swid = 512; int shei = 512; int ss = 1; int SS_MAX = 12; int fr = 60; Histogram h; FractalGenome genome; FractalThread[] threads; ThreadSignal threadSignal; final int SYSTEM_THREADS = Runtime.getRuntime().availableProcessors(); // by running SYSTEM_THREADS - 2 threads we can hopefully avoid making the system unusalbe while // the flame is generating. There is of course a tradeoff in generation speed, which doesn't // really matter to me as I have a 12 thread system. final int maxFlameThreads = (SYSTEM_THREADS > 3) ? SYSTEM_THREADS - 2 : 1; public static final void main(final String args[]) { if (Main.fullscreen) { PApplet.main(new String[] { "--present", "fractalFlameV3.Main" }); } else { PApplet.main(new String[] { "fractalFlameV3.Main" }); } } @Override public void setup() { swid = (fullscreen) ? displayWidth : swid; shei = (fullscreen) ? displayHeight : shei; this.size(swid, shei); frameRate(fr); h = newHistogram(); genome = loadLastGenome(); threads = new FractalThread[1]; threadSignal = new ThreadSignal(); startThreads(); } private FractalGenome loadLastGenome() { String fullGenomeString = ""; GsonBuilder gb = new GsonBuilder(); try { FileReader fileReader = new FileReader("images/last.fractalgenome"); BufferedReader lastGenomeReader = new BufferedReader(fileReader); String line; while ((line = lastGenomeReader.readLine()) != null) { fullGenomeString += line; } lastGenomeReader.close(); fileReader.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return gb.create().fromJson(fullGenomeString, new FractalGenome(3, 3).getClass()); } private FractalGenome newGenome() { final FractalGenome fg = new FractalGenome(3, 10); fg.variationToggle = true; fg.finalTransformToggle = true; genome.center = true; return fg; } private Histogram newHistogram() { final Histogram h = new Histogram(swid, shei, ss); return h; } @Override public void keyPressed() { stopThreads(); - switch (key) { + switch (keyCode) { case 'h': case 'H': ss = (ss == 1) ? SS_MAX : 1; h = null; System.gc(); h = newHistogram(); System.out.println("# SS\t|\t " + ss); break; case 'r': case 'R': genome = newGenome(); h.reset(); break; case 't': case 'T': threads = new FractalThread[(threads.length == 8) ? 1 : 8]; System.out.println("# TH\t|\t " + threads.length); break; case 'f': case 'F': genome.finalTransformToggle = !genome.finalTransformToggle; System.out.println("# FT\t|\t " + genome.finalTransformToggle); h.reset(); break; case 'v': case 'V': genome.variationToggle = !genome.variationToggle; System.out.println("# VT\t|\t " + genome.variationToggle); h.reset(); break; case 's': case 'S': - String fileName = "images/" + genome.hashCode() + "_#####.bmp"; + String fileName = "images/" + genome.hashCode() + ".bmp"; saveFrame(fileName); genome.saveGsonRepresentation(); break; case 'c': case 'C': genome.resetColors(); h.reset(); break; case '+': case '=': genome.cameraXShrink /= 1.01; genome.cameraYShrink /= 1.01; h.reset(); break; case '-': case '_': genome.cameraXShrink *= 1.01; genome.cameraYShrink *= 1.01; h.reset(); break; - case (char) PConstants.UP: + case PConstants.UP: genome.cameraYOffset += .01 * genome.cameraYShrink; h.reset(); break; - case (char) PConstants.DOWN: + case PConstants.DOWN: genome.cameraYOffset -= .01 * genome.cameraYShrink; h.reset(); break; - case (char) PConstants.LEFT: + case PConstants.LEFT: genome.cameraXOffset += .01 * genome.cameraXShrink; h.reset(); break; - case (char) PConstants.RIGHT: + case PConstants.RIGHT: genome.cameraXOffset -= .01 * genome.cameraXShrink; h.reset(); break; } startThreads(); - System.out.println('c' == 27); } private void stopThreads() { threadSignal.running = false; for (final Thread t : threads) { try { t.join(); } catch (final InterruptedException e) { System.out.println(e.getLocalizedMessage()); } } } private void startThreads() { threadSignal.running = true; for (final int i : Utils.range(threads.length)) { threads[i] = new FractalThread(genome, threadSignal, h); } for (final Thread t : threads) { t.start(); } } @Override public void draw() { if (frameCount == 1) { loadPixels(); } else { h.updatePixels(pixels, genome); this.updatePixels(); } } }
false
true
public void keyPressed() { stopThreads(); switch (key) { case 'h': case 'H': ss = (ss == 1) ? SS_MAX : 1; h = null; System.gc(); h = newHistogram(); System.out.println("# SS\t|\t " + ss); break; case 'r': case 'R': genome = newGenome(); h.reset(); break; case 't': case 'T': threads = new FractalThread[(threads.length == 8) ? 1 : 8]; System.out.println("# TH\t|\t " + threads.length); break; case 'f': case 'F': genome.finalTransformToggle = !genome.finalTransformToggle; System.out.println("# FT\t|\t " + genome.finalTransformToggle); h.reset(); break; case 'v': case 'V': genome.variationToggle = !genome.variationToggle; System.out.println("# VT\t|\t " + genome.variationToggle); h.reset(); break; case 's': case 'S': String fileName = "images/" + genome.hashCode() + "_#####.bmp"; saveFrame(fileName); genome.saveGsonRepresentation(); break; case 'c': case 'C': genome.resetColors(); h.reset(); break; case '+': case '=': genome.cameraXShrink /= 1.01; genome.cameraYShrink /= 1.01; h.reset(); break; case '-': case '_': genome.cameraXShrink *= 1.01; genome.cameraYShrink *= 1.01; h.reset(); break; case (char) PConstants.UP: genome.cameraYOffset += .01 * genome.cameraYShrink; h.reset(); break; case (char) PConstants.DOWN: genome.cameraYOffset -= .01 * genome.cameraYShrink; h.reset(); break; case (char) PConstants.LEFT: genome.cameraXOffset += .01 * genome.cameraXShrink; h.reset(); break; case (char) PConstants.RIGHT: genome.cameraXOffset -= .01 * genome.cameraXShrink; h.reset(); break; } startThreads(); System.out.println('c' == 27); }
public void keyPressed() { stopThreads(); switch (keyCode) { case 'h': case 'H': ss = (ss == 1) ? SS_MAX : 1; h = null; System.gc(); h = newHistogram(); System.out.println("# SS\t|\t " + ss); break; case 'r': case 'R': genome = newGenome(); h.reset(); break; case 't': case 'T': threads = new FractalThread[(threads.length == 8) ? 1 : 8]; System.out.println("# TH\t|\t " + threads.length); break; case 'f': case 'F': genome.finalTransformToggle = !genome.finalTransformToggle; System.out.println("# FT\t|\t " + genome.finalTransformToggle); h.reset(); break; case 'v': case 'V': genome.variationToggle = !genome.variationToggle; System.out.println("# VT\t|\t " + genome.variationToggle); h.reset(); break; case 's': case 'S': String fileName = "images/" + genome.hashCode() + ".bmp"; saveFrame(fileName); genome.saveGsonRepresentation(); break; case 'c': case 'C': genome.resetColors(); h.reset(); break; case '+': case '=': genome.cameraXShrink /= 1.01; genome.cameraYShrink /= 1.01; h.reset(); break; case '-': case '_': genome.cameraXShrink *= 1.01; genome.cameraYShrink *= 1.01; h.reset(); break; case PConstants.UP: genome.cameraYOffset += .01 * genome.cameraYShrink; h.reset(); break; case PConstants.DOWN: genome.cameraYOffset -= .01 * genome.cameraYShrink; h.reset(); break; case PConstants.LEFT: genome.cameraXOffset += .01 * genome.cameraXShrink; h.reset(); break; case PConstants.RIGHT: genome.cameraXOffset -= .01 * genome.cameraXShrink; h.reset(); break; } startThreads(); }
diff --git a/editor/tools/plugins/com.google.dart.tools.debug.ui/src/com/google/dart/tools/debug/ui/launch/DartRunLastAction.java b/editor/tools/plugins/com.google.dart.tools.debug.ui/src/com/google/dart/tools/debug/ui/launch/DartRunLastAction.java index 02f4449b5..efe97c203 100644 --- a/editor/tools/plugins/com.google.dart.tools.debug.ui/src/com/google/dart/tools/debug/ui/launch/DartRunLastAction.java +++ b/editor/tools/plugins/com.google.dart.tools.debug.ui/src/com/google/dart/tools/debug/ui/launch/DartRunLastAction.java @@ -1,79 +1,81 @@ /* * Copyright (c) 2012, the Dart project authors. * * Licensed under the Eclipse Public License v1.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.eclipse.org/legal/epl-v10.html * * 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.google.dart.tools.debug.ui.launch; import com.google.dart.tools.debug.ui.internal.DartDebugUIPlugin; import com.google.dart.tools.debug.ui.internal.DartUtil; import com.google.dart.tools.debug.ui.internal.DebugErrorHandler; import com.google.dart.tools.debug.ui.internal.util.LaunchUtils; import org.eclipse.debug.core.ILaunchConfiguration; import org.eclipse.jface.action.IAction; import org.eclipse.ui.IWorkbenchWindow; import java.util.List; /** * Launches the last application to have run */ public class DartRunLastAction extends DartAbstractAction { public DartRunLastAction() { this(null, false); } public DartRunLastAction(IWorkbenchWindow window) { this(window, false); } public DartRunLastAction(IWorkbenchWindow window, boolean noMenu) { super(window, "Run", noMenu ? IAction.AS_PUSH_BUTTON : IAction.AS_DROP_DOWN_MENU); setActionDefinitionId("com.google.dart.tools.debug.ui.run.last"); setImageDescriptor(DartDebugUIPlugin.getImageDescriptor("obj16/run_exc.gif")); } public DartRunLastAction(IWorkbenchWindow window, String name, int flags) { super(window, name, flags); } @Override public void run() { try { List<ILaunchConfiguration> launches = LaunchUtils.getAllLaunches(); if (launches.size() != 0) { ILaunchConfiguration launchConfig = LaunchUtils.chooseLatest(launches); - launch(launchConfig); + if (launchConfig != null) { + launch(launchConfig); + } } else { DartRunAction dartRunAction = new DartRunAction(getWindow()); dartRunAction.run(); } } catch (Throwable exception) { // We need to defensively show all errors coming out of here - the user needs feedback as // to why their launch didn't work. DartUtil.logError(exception); DebugErrorHandler.errorDialog(window.getShell(), "Error During Launch", "Internal error during launch - please report this using the feedback mechanism!", exception); } } }
true
true
public void run() { try { List<ILaunchConfiguration> launches = LaunchUtils.getAllLaunches(); if (launches.size() != 0) { ILaunchConfiguration launchConfig = LaunchUtils.chooseLatest(launches); launch(launchConfig); } else { DartRunAction dartRunAction = new DartRunAction(getWindow()); dartRunAction.run(); } } catch (Throwable exception) { // We need to defensively show all errors coming out of here - the user needs feedback as // to why their launch didn't work. DartUtil.logError(exception); DebugErrorHandler.errorDialog(window.getShell(), "Error During Launch", "Internal error during launch - please report this using the feedback mechanism!", exception); } }
public void run() { try { List<ILaunchConfiguration> launches = LaunchUtils.getAllLaunches(); if (launches.size() != 0) { ILaunchConfiguration launchConfig = LaunchUtils.chooseLatest(launches); if (launchConfig != null) { launch(launchConfig); } } else { DartRunAction dartRunAction = new DartRunAction(getWindow()); dartRunAction.run(); } } catch (Throwable exception) { // We need to defensively show all errors coming out of here - the user needs feedback as // to why their launch didn't work. DartUtil.logError(exception); DebugErrorHandler.errorDialog(window.getShell(), "Error During Launch", "Internal error during launch - please report this using the feedback mechanism!", exception); } }
diff --git a/SoarSuite/Environments/JavaTankSoar/source/tanksoar/InputLinkManager.java b/SoarSuite/Environments/JavaTankSoar/source/tanksoar/InputLinkManager.java index ffd81ad36..beb14ac48 100644 --- a/SoarSuite/Environments/JavaTankSoar/source/tanksoar/InputLinkManager.java +++ b/SoarSuite/Environments/JavaTankSoar/source/tanksoar/InputLinkManager.java @@ -1,657 +1,657 @@ package tanksoar; import java.util.Random; import java.util.logging.*; import simulation.Simulation; import sml.Agent; import sml.FloatElement; import sml.Identifier; import sml.IntElement; import sml.StringElement; import sml.WMElement; import utilities.MapPoint; public class InputLinkManager { // public for visual agent world public final static String kEnergyID = "energy"; public final static String kHealthID = "health"; public final static String kMissilesID = "missiles"; public final static String kObstacleID = "obstacle"; public final static String kOpenID = "open"; public final static String kTankID = "tank"; private final static String kBlockedID = "blocked"; private final static String kClockID = "clock"; private final static String kColorID = "color"; private final static String kDirectionID = "direction"; private final static String kDistanceID = "distance"; private final static String kEnergyRechargerID = "energyrecharger"; private final static String kHealthRechargerID = "healthrecharger"; private final static String kIncomingID = "incoming"; private final static String kMyColorID = "my-color"; private final static String kRadarID = "radar"; private final static String kRadarDistanceID = "radar-distance"; private final static String kRadarSettingID = "radar-setting"; private final static String kRadarStatusID = "radar-status"; private final static String kRandomID = "random"; private final static String kResurrectID = "resurrect"; private final static String kRWavesID = "rwaves"; private final static String kShieldStatusID = "shield-status"; private final static String kSmellID = "smell"; private final static String kSoundID = "sound"; private final static String kXID = "x"; private final static String kYID = "y"; private final static String kBackwardID = "backward"; private final static String kForwardID = "forward"; private final static String kLeftID = "left"; private final static String kRightID = "right"; private final static String kSilentID = "silent"; private final static String kPositionID = "position"; private final static String kCenterID = "center"; public final static String kEast = "east"; public final static String kNorth = "north"; public final static String kSouth = "south"; public final static String kWest = "west"; private final static String kYes = "yes"; private final static String kNo = "no"; private final static String kOff = "off"; private final static String kOn = "on"; private final static String kNone = "none"; private Identifier m_InputLink; private Identifier m_BlockedWME; private StringElement m_BlockedBackwardWME; private StringElement m_BlockedForwardWME; private StringElement m_BlockedLeftWME; private StringElement m_BlockedRightWME; private IntElement m_ClockWME; private StringElement m_DirectionWME; private IntElement m_EnergyWME; private StringElement m_EnergyRechargerWME; private IntElement m_HealthWME; private StringElement m_HealthRechargerWME; private Identifier m_IncomingWME; private StringElement m_IncomingBackwardWME; private StringElement m_IncomingForwardWME; private StringElement m_IncomingLeftWME; private StringElement m_IncomingRightWME; private IntElement m_MissilesWME; private StringElement m_MyColorWME; private StringElement m_RadarStatusWME; private IntElement m_RadarDistanceWME; private IntElement m_RadarSettingWME; private Identifier m_RadarWME; private FloatElement m_RandomWME; private StringElement m_ResurrectWME; private Identifier m_RWavesWME; private StringElement m_RWavesBackwardWME; private StringElement m_RWavesForwardWME; private StringElement m_RWavesLeftWME; private StringElement m_RWavesRightWME; private StringElement m_ShieldStatusWME; private Identifier m_SmellWME; private StringElement m_SmellColorWME; private IntElement m_SmellDistanceWME; private StringElement m_SmellDistanceStringWME; private StringElement m_SoundWME; private IntElement m_xWME; private IntElement m_yWME; private static Logger logger = Logger.getLogger("tanksoar"); private Identifier[][] radarCellIDs = new Identifier[Tank.kRadarWidth][Tank.kRadarHeight]; private StringElement[][] radarColors = new StringElement[Tank.kRadarWidth][Tank.kRadarHeight]; private Agent m_Agent; private Tank m_Tank; private TankSoarWorld m_World; private boolean m_Reset = true; private int m_ResurrectFrame = 0; public InputLinkManager(TankSoarWorld world, Tank tank) { m_Agent = tank.getAgent(); m_World = world; m_Tank = tank; m_InputLink = m_Agent.GetInputLink(); } private void DestroyWME(WMElement wme) { assert wme != null; m_Agent.DestroyWME(wme); wme = null; } private void Update(StringElement wme, String value) { assert wme != null; assert value != null; m_Agent.Update(wme, value); } private void Update(IntElement wme, int value) { assert wme != null; m_Agent.Update(wme, value); } private void Update(FloatElement wme, float value) { assert wme != null; m_Agent.Update(wme, value); } private IntElement CreateIntWME(Identifier id, String attribute, int value) { assert id != null; assert attribute != null; return m_Agent.CreateIntWME(id, attribute, value); } private StringElement CreateStringWME(Identifier id, String attribute, String value) { assert id != null; assert attribute != null; assert value != null; return m_Agent.CreateStringWME(id, attribute, value); } private FloatElement CreateFloatWME(Identifier id, String attribute, float value) { assert id != null; assert attribute != null; return m_Agent.CreateFloatWME(id, attribute, value); } public void clear() { if (m_Reset == true) { return; } DestroyWME(m_BlockedWME); DestroyWME(m_ClockWME); DestroyWME(m_DirectionWME); DestroyWME(m_EnergyWME); DestroyWME(m_EnergyRechargerWME); DestroyWME(m_HealthWME); DestroyWME(m_HealthRechargerWME); DestroyWME(m_IncomingWME); DestroyWME(m_MissilesWME); DestroyWME(m_MyColorWME); DestroyWME(m_RadarStatusWME); DestroyWME(m_RadarDistanceWME); DestroyWME(m_RadarSettingWME); if (m_RadarWME != null) { DestroyWME(m_RadarWME); } DestroyWME(m_RandomWME); DestroyWME(m_ResurrectWME); DestroyWME(m_RWavesWME); DestroyWME(m_ShieldStatusWME); DestroyWME(m_SmellWME); DestroyWME(m_SoundWME); DestroyWME(m_xWME); DestroyWME(m_yWME); m_Agent.Commit(); clearRadar(); m_Reset = true; } void write() { MapPoint location = m_Tank.getLocation(); TankSoarCell cell = m_World.getCell(location); String energyRecharger = cell.isEnergyRecharger() ? kYes : kNo; String healthRecharger = cell.isHealthRecharger() ? kYes : kNo; if (m_Reset) { m_EnergyRechargerWME = CreateStringWME(m_InputLink, kEnergyRechargerID, energyRecharger); m_HealthRechargerWME = CreateStringWME(m_InputLink, kHealthRechargerID, healthRecharger); m_xWME = CreateIntWME(m_InputLink, kXID, location.x); m_yWME = CreateIntWME(m_InputLink, kYID, location.y); } else { if (m_Tank.recentlyMoved()) { Update(m_EnergyRechargerWME, energyRecharger); Update(m_HealthRechargerWME, healthRecharger); Update(m_xWME, location.x); Update(m_yWME, location.y); } } int currentEnergy = m_Tank.getEnergy(); int currentHealth = m_Tank.getHealth(); if (m_Reset) { m_EnergyWME = CreateIntWME(m_InputLink, kEnergyID, currentEnergy); m_HealthWME = CreateIntWME(m_InputLink, kHealthID, currentHealth); } else { if (m_EnergyWME.GetValue() != currentEnergy) { Update(m_EnergyWME, currentEnergy); } if (m_HealthWME.GetValue() != currentHealth) { Update(m_HealthWME, currentHealth); } } String shieldStatus = m_Tank.getShieldStatus() ? kOn : kOff; if (m_Reset) { m_ShieldStatusWME = CreateStringWME(m_InputLink, kShieldStatusID, shieldStatus); } else { if (!m_ShieldStatusWME.GetValue().equalsIgnoreCase(shieldStatus)) { Update(m_ShieldStatusWME, shieldStatus); } } String facing = m_Tank.getFacing(); if (m_Reset) { m_DirectionWME = CreateStringWME(m_InputLink, kDirectionID, facing); } else { if (!m_DirectionWME.GetValue().equalsIgnoreCase(facing)) { Update(m_DirectionWME, facing); } } int blocked = m_World.getBlockedByLocation(m_Tank); String blockedForward = ((blocked & m_Tank.forward()) > 0) ? kYes : kNo; String blockedBackward = ((blocked & m_Tank.backward()) > 0) ? kYes : kNo; String blockedLeft = ((blocked & m_Tank.left()) > 0) ? kYes : kNo; String blockedRight = ((blocked & m_Tank.right()) > 0) ? kYes : kNo; if (m_Reset) { m_BlockedWME = m_Agent.CreateIdWME(m_InputLink, kBlockedID); m_BlockedForwardWME = CreateStringWME(m_BlockedWME, kForwardID, blockedForward); m_BlockedBackwardWME = CreateStringWME(m_BlockedWME, kBackwardID, blockedBackward); m_BlockedLeftWME = CreateStringWME(m_BlockedWME, kLeftID, blockedLeft); m_BlockedRightWME = CreateStringWME(m_BlockedWME, kRightID, blockedRight); } else { if (m_Tank.recentlyMovedOrRotated() || !m_BlockedForwardWME.GetValue().equalsIgnoreCase(blockedForward)) { Update(m_BlockedForwardWME, blockedForward); } if (m_Tank.recentlyMovedOrRotated() || !m_BlockedBackwardWME.GetValue().equalsIgnoreCase(blockedBackward)) { Update(m_BlockedBackwardWME, blockedBackward); } if (m_Tank.recentlyMovedOrRotated() || !m_BlockedLeftWME.GetValue().equalsIgnoreCase(blockedLeft)) { Update(m_BlockedLeftWME, blockedLeft); } if (m_Tank.recentlyMovedOrRotated() || !m_BlockedRightWME.GetValue().equalsIgnoreCase(blockedRight)) { Update(m_BlockedRightWME, blockedRight); } } int incoming = m_World.getIncomingByLocation(location); String incomingForward = ((incoming & m_Tank.forward()) > 0) ? kYes : kNo; String incomingBackward = ((incoming & m_Tank.backward()) > 0) ? kYes : kNo; String incomingLeft = ((incoming & m_Tank.left()) > 0) ? kYes : kNo; String incomingRight = ((incoming & m_Tank.right()) > 0) ? kYes : kNo; if (m_Reset) { m_IncomingWME = m_Agent.CreateIdWME(m_InputLink, kIncomingID); m_IncomingBackwardWME = CreateStringWME(m_IncomingWME, kBackwardID, incomingForward); m_IncomingForwardWME = CreateStringWME(m_IncomingWME, kForwardID, incomingBackward); m_IncomingLeftWME = CreateStringWME(m_IncomingWME, kLeftID, incomingLeft); m_IncomingRightWME = CreateStringWME(m_IncomingWME, kRightID, incomingRight); } else { if (!m_IncomingForwardWME.GetValue().equalsIgnoreCase(incomingForward)) { Update(m_IncomingForwardWME, incomingForward); } if (!m_IncomingBackwardWME.GetValue().equalsIgnoreCase(incomingBackward)) { Update(m_IncomingBackwardWME, incomingBackward); } if (!m_IncomingLeftWME.GetValue().equalsIgnoreCase(incomingLeft)) { Update(m_IncomingLeftWME, incomingLeft); } if (!m_IncomingRightWME.GetValue().equalsIgnoreCase(incomingRight)) { Update(m_IncomingRightWME, incomingRight); } } // Smell Tank closestTank = m_World.getStinkyTankNear(m_Tank); String closestTankColor = (closestTank == null) ? kNone : closestTank.getColor(); int distance = (closestTank == null) ? 0 : location.getManhattanDistanceTo(closestTank.getLocation()); m_Tank.setSmell(distance, distance == 0 ? null : closestTankColor); if (m_Reset) { m_SmellWME = m_Agent.CreateIdWME(m_InputLink, kSmellID); m_SmellColorWME = CreateStringWME(m_SmellWME, kColorID, closestTankColor); if (closestTank == null) { m_SmellDistanceWME = null; m_SmellDistanceStringWME = CreateStringWME(m_SmellWME, kDistanceID, kNone); } else { m_SmellDistanceWME = CreateIntWME(m_SmellWME, kDistanceID, distance); m_SmellDistanceStringWME = null; } } else { if (!m_SmellColorWME.GetValue().equalsIgnoreCase(closestTankColor)) { Update(m_SmellColorWME, closestTankColor); } if (closestTank == null) { if (m_SmellDistanceWME != null) { DestroyWME(m_SmellDistanceWME); m_SmellDistanceWME = null; } if (m_SmellDistanceStringWME == null) { m_SmellDistanceStringWME = CreateStringWME(m_SmellWME, kDistanceID, kNone); } } else { if (m_SmellDistanceWME == null) { m_SmellDistanceWME = CreateIntWME(m_SmellWME, kDistanceID, distance); } else { if (m_SmellDistanceWME.GetValue() != distance) { Update(m_SmellDistanceWME, distance); } } if (m_SmellDistanceStringWME != null) { DestroyWME(m_SmellDistanceStringWME); m_SmellDistanceStringWME = null; } } } // Sound // if the closest tank is greater than 7 away, there is no // possibility of hearing anything int sound = 0; - if (closestTank.getLocation().getManhattanDistanceTo(m_Tank.getLocation()) > TankSoarWorld.kMaxSmellDistance) { + if ((closestTank != null) && closestTank.getLocation().getManhattanDistanceTo(m_Tank.getLocation()) <= TankSoarWorld.kMaxSmellDistance) { sound = m_World.getSoundNear(m_Tank); } String soundString; if (sound == m_Tank.forward()) { soundString = kForwardID; } else if (sound == m_Tank.backward()) { soundString = kBackwardID; } else if (sound == m_Tank.left()) { soundString = kLeftID; } else if (sound == m_Tank.right()) { soundString = kRightID; } else { if (sound > 0) { logger.warning(m_Tank.getName() + ": sound reported as more than one direction."); } soundString = kSilentID; } if (m_Reset) { m_SoundWME = CreateStringWME(m_InputLink, kSoundID, soundString); } else { if (!m_SoundWME.GetValue().equalsIgnoreCase(soundString)) { Update(m_SoundWME, soundString); } } // Missiles int missiles = m_Tank.getMissiles(); if (m_Reset) { m_MissilesWME = CreateIntWME(m_InputLink, kMissilesID, missiles); } else { if (m_MissilesWME.GetValue() != missiles) { Update(m_MissilesWME, missiles); } } // Color if (m_Reset) { m_MyColorWME = CreateStringWME(m_InputLink, kMyColorID, m_Tank.getColor()); } int worldCount = m_World.getWorldCount(); if (m_Reset) { m_ClockWME = CreateIntWME(m_InputLink, kClockID, worldCount); } else { Update(m_ClockWME, worldCount); } // Resurrect if (m_Reset) { m_ResurrectFrame = worldCount; m_ResurrectWME = CreateStringWME(m_InputLink, kResurrectID, kYes); } else { if (worldCount != m_ResurrectFrame) { if (!m_ResurrectWME.GetValue().equalsIgnoreCase(kNo)) { Update(m_ResurrectWME, kNo); } } } // Radar String radarStatus = m_Tank.getRadarStatus() ? kOn : kOff; if (m_Reset) { m_RadarStatusWME = CreateStringWME(m_InputLink, kRadarStatusID, radarStatus); if (m_Tank.getRadarStatus()) { m_RadarWME = m_Agent.CreateIdWME(m_InputLink, kRadarID); generateNewRadar(); } else { m_RadarWME = null; } m_RadarDistanceWME = CreateIntWME(m_InputLink, kRadarDistanceID, m_Tank.getRadarDistance()); m_RadarSettingWME = CreateIntWME(m_InputLink, kRadarSettingID, m_Tank.getRadarSetting()); } else { if (!m_RadarStatusWME.GetValue().equalsIgnoreCase(radarStatus)) { Update(m_RadarStatusWME, radarStatus); } if (m_Tank.getRadarStatus()) { if (m_RadarWME == null) { m_RadarWME = m_Agent.CreateIdWME(m_InputLink, kRadarID); generateNewRadar(); } else { updateRadar(); } } else { if (m_RadarWME != null) { DestroyWME(m_RadarWME); m_RadarWME = null; clearRadar(); } } if (m_RadarDistanceWME.GetValue() != m_Tank.getRadarDistance()) { Update(m_RadarDistanceWME, m_Tank.getRadarDistance()); } if (m_RadarSettingWME.GetValue() != m_Tank.getRadarSetting()) { Update(m_RadarSettingWME, m_Tank.getRadarSetting()); } } // Random float random = Simulation.random.nextFloat(); if (m_Reset) { m_RandomWME = CreateFloatWME(m_InputLink, kRandomID, random); } else { Update(m_RandomWME, random); } // RWaves int rwaves = m_Tank.getRWaves(); String rwavesForward = (rwaves & m_Tank.forward()) > 0 ? kYes : kNo; String rwavesBackward = (rwaves & m_Tank.backward()) > 0 ? kYes : kNo;; String rwavesLeft = (rwaves & m_Tank.left()) > 0 ? kYes : kNo; String rwavesRight = (rwaves & m_Tank.right()) > 0 ? kYes : kNo; if (m_Reset) { m_RWavesWME = m_Agent.CreateIdWME(m_InputLink, kRWavesID); m_RWavesForwardWME = CreateStringWME(m_RWavesWME, kForwardID, rwavesBackward); m_RWavesBackwardWME = CreateStringWME(m_RWavesWME, kBackwardID, rwavesForward); m_RWavesLeftWME = CreateStringWME(m_RWavesWME, kLeftID, rwavesLeft); m_RWavesRightWME = CreateStringWME(m_RWavesWME, kRightID, rwavesRight); } else { if (!m_RWavesForwardWME.GetValue().equalsIgnoreCase(rwavesForward)) { Update(m_RWavesForwardWME, rwavesForward); } if (!m_RWavesBackwardWME.GetValue().equalsIgnoreCase(rwavesBackward)) { Update(m_RWavesBackwardWME, rwavesBackward); } if (!m_RWavesLeftWME.GetValue().equalsIgnoreCase(rwavesLeft)) { Update(m_RWavesLeftWME, rwavesLeft); } if (!m_RWavesRightWME.GetValue().equalsIgnoreCase(rwavesRight)) { Update(m_RWavesRightWME, rwavesRight); } } m_Reset = false; m_Agent.Commit(); } private void generateNewRadar() { // logger.finest("generateNewRadar()"); TankSoarCell[][] radarCells = m_Tank.getRadarCells(); for (int j = 0; j < Tank.kRadarHeight; ++j) { boolean done = false; // String outstring = new String(); for (int i = 0; i < Tank.kRadarWidth; ++i) { // Always skip self, this screws up the tanks. if (i == 1 && j == 0) { // outstring += "s"; continue; } if (radarCells[i][j] == null) { // if center is null, we're done if (i == 1) { // outstring += "d"; done = true; break; } else { // outstring += "."; } } else { // Create a new WME radarCellIDs[i][j] = m_Agent.CreateIdWME(m_RadarWME, getCellID(radarCells[i][j])); CreateIntWME(radarCellIDs[i][j], kDistanceID, j); CreateStringWME(radarCellIDs[i][j], kPositionID, getPositionID(i)); if (radarCells[i][j].containsTank()) { radarColors[i][j] = CreateStringWME(radarCellIDs[i][j], kColorID, radarCells[i][j].getTank().getColor()); // outstring += "t"; } else { // outstring += "n"; } } } // logger.finest(outstring); if (done == true) { break; } } } private void updateRadar() { // logger.finest("updateRadar()"); TankSoarCell[][] radarCells = m_Tank.getRadarCells(); for (int i = 0; i < Tank.kRadarWidth; ++i) { // String outstring = new String(); for (int j = 0; j < Tank.kRadarHeight; ++j) { // Always skip self, this screws up the tanks. if (i == 1 && j == 0) { // outstring += "s"; continue; } if (radarCells[i][j] == null) { // Unconditionally delete the WME if (radarCellIDs[i][j] != null) { // outstring += "d"; DestroyWME(radarCellIDs[i][j]); radarCellIDs[i][j] = null; radarColors[i][j] = null; } else { // outstring += "-"; } } else { if (radarCellIDs[i][j] == null) { // Unconditionally create the WME radarCellIDs[i][j] = m_Agent.CreateIdWME(m_RadarWME, getCellID(radarCells[i][j])); CreateIntWME(radarCellIDs[i][j], kDistanceID, j); CreateStringWME(radarCellIDs[i][j], kPositionID, getPositionID(i)); if (radarCells[i][j].containsTank()) { radarColors[i][j] = CreateStringWME(radarCellIDs[i][j], kColorID, radarCells[i][j].getTank().getColor()); // outstring += "t"; } else { // outstring += "n"; } } else { // Update if relevant change if (m_Tank.recentlyMovedOrRotated() || radarCells[i][j].isModified()) { DestroyWME(radarCellIDs[i][j]); radarCellIDs[i][j] = m_Agent.CreateIdWME(m_RadarWME, getCellID(radarCells[i][j])); CreateIntWME(radarCellIDs[i][j], kDistanceID, j); CreateStringWME(radarCellIDs[i][j], kPositionID, getPositionID(i)); if (radarCells[i][j].containsTank()) { // rwaves already set //tank.setRWaves(m_Tank.backward()); radarColors[i][j] = CreateStringWME(radarCellIDs[i][j], kColorID, radarCells[i][j].getTank().getColor()); // outstring += "U"; } else { // outstring += "u"; } } else { // outstring += "."; } } } } // logger.finest(outstring); } } private void clearRadar() { // logger.finest("clearRadar()"); for (int i = 0; i < Tank.kRadarWidth; ++i) { for (int j = 0; j < Tank.kRadarHeight; ++j) { radarCellIDs[i][j] = null; radarColors[i][j] = null; } } } private String getCellID(TankSoarCell cell) { if (cell.containsTank()) { return kTankID; } if (cell.isWall()) { return kObstacleID; } if (cell.isEnergyRecharger()) { return kEnergyID; } if (cell.isHealthRecharger()) { return kHealthID; } if (cell.containsMissilePack()) { return kMissilesID; } return kOpenID; } public String getPositionID(int i) { switch (i) { case Tank.kRadarLeft: return InputLinkManager.kLeftID; default: case Tank.kRadarCenter: return InputLinkManager.kCenterID; case Tank.kRadarRight: return InputLinkManager.kRightID; } } }
true
true
void write() { MapPoint location = m_Tank.getLocation(); TankSoarCell cell = m_World.getCell(location); String energyRecharger = cell.isEnergyRecharger() ? kYes : kNo; String healthRecharger = cell.isHealthRecharger() ? kYes : kNo; if (m_Reset) { m_EnergyRechargerWME = CreateStringWME(m_InputLink, kEnergyRechargerID, energyRecharger); m_HealthRechargerWME = CreateStringWME(m_InputLink, kHealthRechargerID, healthRecharger); m_xWME = CreateIntWME(m_InputLink, kXID, location.x); m_yWME = CreateIntWME(m_InputLink, kYID, location.y); } else { if (m_Tank.recentlyMoved()) { Update(m_EnergyRechargerWME, energyRecharger); Update(m_HealthRechargerWME, healthRecharger); Update(m_xWME, location.x); Update(m_yWME, location.y); } } int currentEnergy = m_Tank.getEnergy(); int currentHealth = m_Tank.getHealth(); if (m_Reset) { m_EnergyWME = CreateIntWME(m_InputLink, kEnergyID, currentEnergy); m_HealthWME = CreateIntWME(m_InputLink, kHealthID, currentHealth); } else { if (m_EnergyWME.GetValue() != currentEnergy) { Update(m_EnergyWME, currentEnergy); } if (m_HealthWME.GetValue() != currentHealth) { Update(m_HealthWME, currentHealth); } } String shieldStatus = m_Tank.getShieldStatus() ? kOn : kOff; if (m_Reset) { m_ShieldStatusWME = CreateStringWME(m_InputLink, kShieldStatusID, shieldStatus); } else { if (!m_ShieldStatusWME.GetValue().equalsIgnoreCase(shieldStatus)) { Update(m_ShieldStatusWME, shieldStatus); } } String facing = m_Tank.getFacing(); if (m_Reset) { m_DirectionWME = CreateStringWME(m_InputLink, kDirectionID, facing); } else { if (!m_DirectionWME.GetValue().equalsIgnoreCase(facing)) { Update(m_DirectionWME, facing); } } int blocked = m_World.getBlockedByLocation(m_Tank); String blockedForward = ((blocked & m_Tank.forward()) > 0) ? kYes : kNo; String blockedBackward = ((blocked & m_Tank.backward()) > 0) ? kYes : kNo; String blockedLeft = ((blocked & m_Tank.left()) > 0) ? kYes : kNo; String blockedRight = ((blocked & m_Tank.right()) > 0) ? kYes : kNo; if (m_Reset) { m_BlockedWME = m_Agent.CreateIdWME(m_InputLink, kBlockedID); m_BlockedForwardWME = CreateStringWME(m_BlockedWME, kForwardID, blockedForward); m_BlockedBackwardWME = CreateStringWME(m_BlockedWME, kBackwardID, blockedBackward); m_BlockedLeftWME = CreateStringWME(m_BlockedWME, kLeftID, blockedLeft); m_BlockedRightWME = CreateStringWME(m_BlockedWME, kRightID, blockedRight); } else { if (m_Tank.recentlyMovedOrRotated() || !m_BlockedForwardWME.GetValue().equalsIgnoreCase(blockedForward)) { Update(m_BlockedForwardWME, blockedForward); } if (m_Tank.recentlyMovedOrRotated() || !m_BlockedBackwardWME.GetValue().equalsIgnoreCase(blockedBackward)) { Update(m_BlockedBackwardWME, blockedBackward); } if (m_Tank.recentlyMovedOrRotated() || !m_BlockedLeftWME.GetValue().equalsIgnoreCase(blockedLeft)) { Update(m_BlockedLeftWME, blockedLeft); } if (m_Tank.recentlyMovedOrRotated() || !m_BlockedRightWME.GetValue().equalsIgnoreCase(blockedRight)) { Update(m_BlockedRightWME, blockedRight); } } int incoming = m_World.getIncomingByLocation(location); String incomingForward = ((incoming & m_Tank.forward()) > 0) ? kYes : kNo; String incomingBackward = ((incoming & m_Tank.backward()) > 0) ? kYes : kNo; String incomingLeft = ((incoming & m_Tank.left()) > 0) ? kYes : kNo; String incomingRight = ((incoming & m_Tank.right()) > 0) ? kYes : kNo; if (m_Reset) { m_IncomingWME = m_Agent.CreateIdWME(m_InputLink, kIncomingID); m_IncomingBackwardWME = CreateStringWME(m_IncomingWME, kBackwardID, incomingForward); m_IncomingForwardWME = CreateStringWME(m_IncomingWME, kForwardID, incomingBackward); m_IncomingLeftWME = CreateStringWME(m_IncomingWME, kLeftID, incomingLeft); m_IncomingRightWME = CreateStringWME(m_IncomingWME, kRightID, incomingRight); } else { if (!m_IncomingForwardWME.GetValue().equalsIgnoreCase(incomingForward)) { Update(m_IncomingForwardWME, incomingForward); } if (!m_IncomingBackwardWME.GetValue().equalsIgnoreCase(incomingBackward)) { Update(m_IncomingBackwardWME, incomingBackward); } if (!m_IncomingLeftWME.GetValue().equalsIgnoreCase(incomingLeft)) { Update(m_IncomingLeftWME, incomingLeft); } if (!m_IncomingRightWME.GetValue().equalsIgnoreCase(incomingRight)) { Update(m_IncomingRightWME, incomingRight); } } // Smell Tank closestTank = m_World.getStinkyTankNear(m_Tank); String closestTankColor = (closestTank == null) ? kNone : closestTank.getColor(); int distance = (closestTank == null) ? 0 : location.getManhattanDistanceTo(closestTank.getLocation()); m_Tank.setSmell(distance, distance == 0 ? null : closestTankColor); if (m_Reset) { m_SmellWME = m_Agent.CreateIdWME(m_InputLink, kSmellID); m_SmellColorWME = CreateStringWME(m_SmellWME, kColorID, closestTankColor); if (closestTank == null) { m_SmellDistanceWME = null; m_SmellDistanceStringWME = CreateStringWME(m_SmellWME, kDistanceID, kNone); } else { m_SmellDistanceWME = CreateIntWME(m_SmellWME, kDistanceID, distance); m_SmellDistanceStringWME = null; } } else { if (!m_SmellColorWME.GetValue().equalsIgnoreCase(closestTankColor)) { Update(m_SmellColorWME, closestTankColor); } if (closestTank == null) { if (m_SmellDistanceWME != null) { DestroyWME(m_SmellDistanceWME); m_SmellDistanceWME = null; } if (m_SmellDistanceStringWME == null) { m_SmellDistanceStringWME = CreateStringWME(m_SmellWME, kDistanceID, kNone); } } else { if (m_SmellDistanceWME == null) { m_SmellDistanceWME = CreateIntWME(m_SmellWME, kDistanceID, distance); } else { if (m_SmellDistanceWME.GetValue() != distance) { Update(m_SmellDistanceWME, distance); } } if (m_SmellDistanceStringWME != null) { DestroyWME(m_SmellDistanceStringWME); m_SmellDistanceStringWME = null; } } } // Sound // if the closest tank is greater than 7 away, there is no // possibility of hearing anything int sound = 0; if (closestTank.getLocation().getManhattanDistanceTo(m_Tank.getLocation()) > TankSoarWorld.kMaxSmellDistance) { sound = m_World.getSoundNear(m_Tank); } String soundString; if (sound == m_Tank.forward()) { soundString = kForwardID; } else if (sound == m_Tank.backward()) { soundString = kBackwardID; } else if (sound == m_Tank.left()) { soundString = kLeftID; } else if (sound == m_Tank.right()) { soundString = kRightID; } else { if (sound > 0) { logger.warning(m_Tank.getName() + ": sound reported as more than one direction."); } soundString = kSilentID; } if (m_Reset) { m_SoundWME = CreateStringWME(m_InputLink, kSoundID, soundString); } else { if (!m_SoundWME.GetValue().equalsIgnoreCase(soundString)) { Update(m_SoundWME, soundString); } } // Missiles int missiles = m_Tank.getMissiles(); if (m_Reset) { m_MissilesWME = CreateIntWME(m_InputLink, kMissilesID, missiles); } else { if (m_MissilesWME.GetValue() != missiles) { Update(m_MissilesWME, missiles); } } // Color if (m_Reset) { m_MyColorWME = CreateStringWME(m_InputLink, kMyColorID, m_Tank.getColor()); } int worldCount = m_World.getWorldCount(); if (m_Reset) { m_ClockWME = CreateIntWME(m_InputLink, kClockID, worldCount); } else { Update(m_ClockWME, worldCount); } // Resurrect if (m_Reset) { m_ResurrectFrame = worldCount; m_ResurrectWME = CreateStringWME(m_InputLink, kResurrectID, kYes); } else { if (worldCount != m_ResurrectFrame) { if (!m_ResurrectWME.GetValue().equalsIgnoreCase(kNo)) { Update(m_ResurrectWME, kNo); } } } // Radar String radarStatus = m_Tank.getRadarStatus() ? kOn : kOff; if (m_Reset) { m_RadarStatusWME = CreateStringWME(m_InputLink, kRadarStatusID, radarStatus); if (m_Tank.getRadarStatus()) { m_RadarWME = m_Agent.CreateIdWME(m_InputLink, kRadarID); generateNewRadar(); } else { m_RadarWME = null; } m_RadarDistanceWME = CreateIntWME(m_InputLink, kRadarDistanceID, m_Tank.getRadarDistance()); m_RadarSettingWME = CreateIntWME(m_InputLink, kRadarSettingID, m_Tank.getRadarSetting()); } else { if (!m_RadarStatusWME.GetValue().equalsIgnoreCase(radarStatus)) { Update(m_RadarStatusWME, radarStatus); } if (m_Tank.getRadarStatus()) { if (m_RadarWME == null) { m_RadarWME = m_Agent.CreateIdWME(m_InputLink, kRadarID); generateNewRadar(); } else { updateRadar(); } } else { if (m_RadarWME != null) { DestroyWME(m_RadarWME); m_RadarWME = null; clearRadar(); } } if (m_RadarDistanceWME.GetValue() != m_Tank.getRadarDistance()) { Update(m_RadarDistanceWME, m_Tank.getRadarDistance()); } if (m_RadarSettingWME.GetValue() != m_Tank.getRadarSetting()) { Update(m_RadarSettingWME, m_Tank.getRadarSetting()); } } // Random float random = Simulation.random.nextFloat(); if (m_Reset) { m_RandomWME = CreateFloatWME(m_InputLink, kRandomID, random); } else { Update(m_RandomWME, random); } // RWaves int rwaves = m_Tank.getRWaves(); String rwavesForward = (rwaves & m_Tank.forward()) > 0 ? kYes : kNo; String rwavesBackward = (rwaves & m_Tank.backward()) > 0 ? kYes : kNo;; String rwavesLeft = (rwaves & m_Tank.left()) > 0 ? kYes : kNo; String rwavesRight = (rwaves & m_Tank.right()) > 0 ? kYes : kNo; if (m_Reset) { m_RWavesWME = m_Agent.CreateIdWME(m_InputLink, kRWavesID); m_RWavesForwardWME = CreateStringWME(m_RWavesWME, kForwardID, rwavesBackward); m_RWavesBackwardWME = CreateStringWME(m_RWavesWME, kBackwardID, rwavesForward); m_RWavesLeftWME = CreateStringWME(m_RWavesWME, kLeftID, rwavesLeft); m_RWavesRightWME = CreateStringWME(m_RWavesWME, kRightID, rwavesRight); } else { if (!m_RWavesForwardWME.GetValue().equalsIgnoreCase(rwavesForward)) { Update(m_RWavesForwardWME, rwavesForward); } if (!m_RWavesBackwardWME.GetValue().equalsIgnoreCase(rwavesBackward)) { Update(m_RWavesBackwardWME, rwavesBackward); } if (!m_RWavesLeftWME.GetValue().equalsIgnoreCase(rwavesLeft)) { Update(m_RWavesLeftWME, rwavesLeft); } if (!m_RWavesRightWME.GetValue().equalsIgnoreCase(rwavesRight)) { Update(m_RWavesRightWME, rwavesRight); } } m_Reset = false; m_Agent.Commit(); }
void write() { MapPoint location = m_Tank.getLocation(); TankSoarCell cell = m_World.getCell(location); String energyRecharger = cell.isEnergyRecharger() ? kYes : kNo; String healthRecharger = cell.isHealthRecharger() ? kYes : kNo; if (m_Reset) { m_EnergyRechargerWME = CreateStringWME(m_InputLink, kEnergyRechargerID, energyRecharger); m_HealthRechargerWME = CreateStringWME(m_InputLink, kHealthRechargerID, healthRecharger); m_xWME = CreateIntWME(m_InputLink, kXID, location.x); m_yWME = CreateIntWME(m_InputLink, kYID, location.y); } else { if (m_Tank.recentlyMoved()) { Update(m_EnergyRechargerWME, energyRecharger); Update(m_HealthRechargerWME, healthRecharger); Update(m_xWME, location.x); Update(m_yWME, location.y); } } int currentEnergy = m_Tank.getEnergy(); int currentHealth = m_Tank.getHealth(); if (m_Reset) { m_EnergyWME = CreateIntWME(m_InputLink, kEnergyID, currentEnergy); m_HealthWME = CreateIntWME(m_InputLink, kHealthID, currentHealth); } else { if (m_EnergyWME.GetValue() != currentEnergy) { Update(m_EnergyWME, currentEnergy); } if (m_HealthWME.GetValue() != currentHealth) { Update(m_HealthWME, currentHealth); } } String shieldStatus = m_Tank.getShieldStatus() ? kOn : kOff; if (m_Reset) { m_ShieldStatusWME = CreateStringWME(m_InputLink, kShieldStatusID, shieldStatus); } else { if (!m_ShieldStatusWME.GetValue().equalsIgnoreCase(shieldStatus)) { Update(m_ShieldStatusWME, shieldStatus); } } String facing = m_Tank.getFacing(); if (m_Reset) { m_DirectionWME = CreateStringWME(m_InputLink, kDirectionID, facing); } else { if (!m_DirectionWME.GetValue().equalsIgnoreCase(facing)) { Update(m_DirectionWME, facing); } } int blocked = m_World.getBlockedByLocation(m_Tank); String blockedForward = ((blocked & m_Tank.forward()) > 0) ? kYes : kNo; String blockedBackward = ((blocked & m_Tank.backward()) > 0) ? kYes : kNo; String blockedLeft = ((blocked & m_Tank.left()) > 0) ? kYes : kNo; String blockedRight = ((blocked & m_Tank.right()) > 0) ? kYes : kNo; if (m_Reset) { m_BlockedWME = m_Agent.CreateIdWME(m_InputLink, kBlockedID); m_BlockedForwardWME = CreateStringWME(m_BlockedWME, kForwardID, blockedForward); m_BlockedBackwardWME = CreateStringWME(m_BlockedWME, kBackwardID, blockedBackward); m_BlockedLeftWME = CreateStringWME(m_BlockedWME, kLeftID, blockedLeft); m_BlockedRightWME = CreateStringWME(m_BlockedWME, kRightID, blockedRight); } else { if (m_Tank.recentlyMovedOrRotated() || !m_BlockedForwardWME.GetValue().equalsIgnoreCase(blockedForward)) { Update(m_BlockedForwardWME, blockedForward); } if (m_Tank.recentlyMovedOrRotated() || !m_BlockedBackwardWME.GetValue().equalsIgnoreCase(blockedBackward)) { Update(m_BlockedBackwardWME, blockedBackward); } if (m_Tank.recentlyMovedOrRotated() || !m_BlockedLeftWME.GetValue().equalsIgnoreCase(blockedLeft)) { Update(m_BlockedLeftWME, blockedLeft); } if (m_Tank.recentlyMovedOrRotated() || !m_BlockedRightWME.GetValue().equalsIgnoreCase(blockedRight)) { Update(m_BlockedRightWME, blockedRight); } } int incoming = m_World.getIncomingByLocation(location); String incomingForward = ((incoming & m_Tank.forward()) > 0) ? kYes : kNo; String incomingBackward = ((incoming & m_Tank.backward()) > 0) ? kYes : kNo; String incomingLeft = ((incoming & m_Tank.left()) > 0) ? kYes : kNo; String incomingRight = ((incoming & m_Tank.right()) > 0) ? kYes : kNo; if (m_Reset) { m_IncomingWME = m_Agent.CreateIdWME(m_InputLink, kIncomingID); m_IncomingBackwardWME = CreateStringWME(m_IncomingWME, kBackwardID, incomingForward); m_IncomingForwardWME = CreateStringWME(m_IncomingWME, kForwardID, incomingBackward); m_IncomingLeftWME = CreateStringWME(m_IncomingWME, kLeftID, incomingLeft); m_IncomingRightWME = CreateStringWME(m_IncomingWME, kRightID, incomingRight); } else { if (!m_IncomingForwardWME.GetValue().equalsIgnoreCase(incomingForward)) { Update(m_IncomingForwardWME, incomingForward); } if (!m_IncomingBackwardWME.GetValue().equalsIgnoreCase(incomingBackward)) { Update(m_IncomingBackwardWME, incomingBackward); } if (!m_IncomingLeftWME.GetValue().equalsIgnoreCase(incomingLeft)) { Update(m_IncomingLeftWME, incomingLeft); } if (!m_IncomingRightWME.GetValue().equalsIgnoreCase(incomingRight)) { Update(m_IncomingRightWME, incomingRight); } } // Smell Tank closestTank = m_World.getStinkyTankNear(m_Tank); String closestTankColor = (closestTank == null) ? kNone : closestTank.getColor(); int distance = (closestTank == null) ? 0 : location.getManhattanDistanceTo(closestTank.getLocation()); m_Tank.setSmell(distance, distance == 0 ? null : closestTankColor); if (m_Reset) { m_SmellWME = m_Agent.CreateIdWME(m_InputLink, kSmellID); m_SmellColorWME = CreateStringWME(m_SmellWME, kColorID, closestTankColor); if (closestTank == null) { m_SmellDistanceWME = null; m_SmellDistanceStringWME = CreateStringWME(m_SmellWME, kDistanceID, kNone); } else { m_SmellDistanceWME = CreateIntWME(m_SmellWME, kDistanceID, distance); m_SmellDistanceStringWME = null; } } else { if (!m_SmellColorWME.GetValue().equalsIgnoreCase(closestTankColor)) { Update(m_SmellColorWME, closestTankColor); } if (closestTank == null) { if (m_SmellDistanceWME != null) { DestroyWME(m_SmellDistanceWME); m_SmellDistanceWME = null; } if (m_SmellDistanceStringWME == null) { m_SmellDistanceStringWME = CreateStringWME(m_SmellWME, kDistanceID, kNone); } } else { if (m_SmellDistanceWME == null) { m_SmellDistanceWME = CreateIntWME(m_SmellWME, kDistanceID, distance); } else { if (m_SmellDistanceWME.GetValue() != distance) { Update(m_SmellDistanceWME, distance); } } if (m_SmellDistanceStringWME != null) { DestroyWME(m_SmellDistanceStringWME); m_SmellDistanceStringWME = null; } } } // Sound // if the closest tank is greater than 7 away, there is no // possibility of hearing anything int sound = 0; if ((closestTank != null) && closestTank.getLocation().getManhattanDistanceTo(m_Tank.getLocation()) <= TankSoarWorld.kMaxSmellDistance) { sound = m_World.getSoundNear(m_Tank); } String soundString; if (sound == m_Tank.forward()) { soundString = kForwardID; } else if (sound == m_Tank.backward()) { soundString = kBackwardID; } else if (sound == m_Tank.left()) { soundString = kLeftID; } else if (sound == m_Tank.right()) { soundString = kRightID; } else { if (sound > 0) { logger.warning(m_Tank.getName() + ": sound reported as more than one direction."); } soundString = kSilentID; } if (m_Reset) { m_SoundWME = CreateStringWME(m_InputLink, kSoundID, soundString); } else { if (!m_SoundWME.GetValue().equalsIgnoreCase(soundString)) { Update(m_SoundWME, soundString); } } // Missiles int missiles = m_Tank.getMissiles(); if (m_Reset) { m_MissilesWME = CreateIntWME(m_InputLink, kMissilesID, missiles); } else { if (m_MissilesWME.GetValue() != missiles) { Update(m_MissilesWME, missiles); } } // Color if (m_Reset) { m_MyColorWME = CreateStringWME(m_InputLink, kMyColorID, m_Tank.getColor()); } int worldCount = m_World.getWorldCount(); if (m_Reset) { m_ClockWME = CreateIntWME(m_InputLink, kClockID, worldCount); } else { Update(m_ClockWME, worldCount); } // Resurrect if (m_Reset) { m_ResurrectFrame = worldCount; m_ResurrectWME = CreateStringWME(m_InputLink, kResurrectID, kYes); } else { if (worldCount != m_ResurrectFrame) { if (!m_ResurrectWME.GetValue().equalsIgnoreCase(kNo)) { Update(m_ResurrectWME, kNo); } } } // Radar String radarStatus = m_Tank.getRadarStatus() ? kOn : kOff; if (m_Reset) { m_RadarStatusWME = CreateStringWME(m_InputLink, kRadarStatusID, radarStatus); if (m_Tank.getRadarStatus()) { m_RadarWME = m_Agent.CreateIdWME(m_InputLink, kRadarID); generateNewRadar(); } else { m_RadarWME = null; } m_RadarDistanceWME = CreateIntWME(m_InputLink, kRadarDistanceID, m_Tank.getRadarDistance()); m_RadarSettingWME = CreateIntWME(m_InputLink, kRadarSettingID, m_Tank.getRadarSetting()); } else { if (!m_RadarStatusWME.GetValue().equalsIgnoreCase(radarStatus)) { Update(m_RadarStatusWME, radarStatus); } if (m_Tank.getRadarStatus()) { if (m_RadarWME == null) { m_RadarWME = m_Agent.CreateIdWME(m_InputLink, kRadarID); generateNewRadar(); } else { updateRadar(); } } else { if (m_RadarWME != null) { DestroyWME(m_RadarWME); m_RadarWME = null; clearRadar(); } } if (m_RadarDistanceWME.GetValue() != m_Tank.getRadarDistance()) { Update(m_RadarDistanceWME, m_Tank.getRadarDistance()); } if (m_RadarSettingWME.GetValue() != m_Tank.getRadarSetting()) { Update(m_RadarSettingWME, m_Tank.getRadarSetting()); } } // Random float random = Simulation.random.nextFloat(); if (m_Reset) { m_RandomWME = CreateFloatWME(m_InputLink, kRandomID, random); } else { Update(m_RandomWME, random); } // RWaves int rwaves = m_Tank.getRWaves(); String rwavesForward = (rwaves & m_Tank.forward()) > 0 ? kYes : kNo; String rwavesBackward = (rwaves & m_Tank.backward()) > 0 ? kYes : kNo;; String rwavesLeft = (rwaves & m_Tank.left()) > 0 ? kYes : kNo; String rwavesRight = (rwaves & m_Tank.right()) > 0 ? kYes : kNo; if (m_Reset) { m_RWavesWME = m_Agent.CreateIdWME(m_InputLink, kRWavesID); m_RWavesForwardWME = CreateStringWME(m_RWavesWME, kForwardID, rwavesBackward); m_RWavesBackwardWME = CreateStringWME(m_RWavesWME, kBackwardID, rwavesForward); m_RWavesLeftWME = CreateStringWME(m_RWavesWME, kLeftID, rwavesLeft); m_RWavesRightWME = CreateStringWME(m_RWavesWME, kRightID, rwavesRight); } else { if (!m_RWavesForwardWME.GetValue().equalsIgnoreCase(rwavesForward)) { Update(m_RWavesForwardWME, rwavesForward); } if (!m_RWavesBackwardWME.GetValue().equalsIgnoreCase(rwavesBackward)) { Update(m_RWavesBackwardWME, rwavesBackward); } if (!m_RWavesLeftWME.GetValue().equalsIgnoreCase(rwavesLeft)) { Update(m_RWavesLeftWME, rwavesLeft); } if (!m_RWavesRightWME.GetValue().equalsIgnoreCase(rwavesRight)) { Update(m_RWavesRightWME, rwavesRight); } } m_Reset = false; m_Agent.Commit(); }
diff --git a/cyklotron-ui/src/main/java/net/cyklotron/cms/modules/views/documents/ProposeDocument.java b/cyklotron-ui/src/main/java/net/cyklotron/cms/modules/views/documents/ProposeDocument.java index 805d4b5bb..d7f1c2bd5 100644 --- a/cyklotron-ui/src/main/java/net/cyklotron/cms/modules/views/documents/ProposeDocument.java +++ b/cyklotron-ui/src/main/java/net/cyklotron/cms/modules/views/documents/ProposeDocument.java @@ -1,418 +1,423 @@ package net.cyklotron.cms.modules.views.documents; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import org.jcontainer.dna.Logger; import org.objectledge.authentication.AuthenticationContext; import org.objectledge.context.Context; import org.objectledge.coral.schema.ResourceClass; import org.objectledge.coral.security.Permission; import org.objectledge.coral.security.Subject; import org.objectledge.coral.session.CoralSession; import org.objectledge.coral.store.Resource; import org.objectledge.coral.table.comparator.CreationTimeComparator; import org.objectledge.html.HTMLService; import org.objectledge.i18n.I18nContext; import org.objectledge.parameters.Parameters; import org.objectledge.parameters.RequestParameters; import org.objectledge.pipeline.ProcessingException; import org.objectledge.table.InverseFilter; import org.objectledge.table.TableColumn; import org.objectledge.table.TableFilter; import org.objectledge.table.TableState; import org.objectledge.table.TableStateManager; import org.objectledge.table.TableTool; import org.objectledge.table.generic.ListTableModel; import org.objectledge.templating.TemplatingContext; import org.objectledge.web.mvc.finders.MVCFinder; import net.cyklotron.cms.CmsData; import net.cyklotron.cms.CmsDataFactory; import net.cyklotron.cms.category.CategoryService; import net.cyklotron.cms.documents.DocumentNodeResource; import net.cyklotron.cms.documents.DocumentNodeResourceImpl; import net.cyklotron.cms.preferences.PreferencesService; import net.cyklotron.cms.related.RelatedService; import net.cyklotron.cms.site.SiteResource; import net.cyklotron.cms.skins.SkinService; import net.cyklotron.cms.structure.NavigationNodeResourceImpl; import net.cyklotron.cms.structure.StructureService; import net.cyklotron.cms.structure.internal.ProposedDocumentData; import net.cyklotron.cms.structure.table.TitleComparator; import net.cyklotron.cms.style.StyleService; import net.cyklotron.cms.workflow.AutomatonResource; import net.cyklotron.cms.workflow.StateFilter; import net.cyklotron.cms.workflow.StateResource; import net.cyklotron.cms.workflow.WorkflowService; /** * Stateful screen for propose document application. * * @author <a href="mailto:[email protected]">Pawe� Potempski</a> * @version $Id: ProposeDocument.java,v 1.12 2008-11-04 17:14:48 rafal Exp $ */ public class ProposeDocument extends BaseSkinableDocumentScreen { private final CategoryService categoryService; private final RelatedService relatedService; private final HTMLService htmlService; private final WorkflowService workflowService; private final List<String> REQUIRES_AUTHENTICATED_USER = Arrays.asList("MyDocuments", "EditDocument", "RemovalRequest", "RedactorsNote"); public ProposeDocument(org.objectledge.context.Context context, Logger logger, PreferencesService preferencesService, CmsDataFactory cmsDataFactory, StructureService structureService, StyleService styleService, SkinService skinService, MVCFinder mvcFinder, TableStateManager tableStateManager, CategoryService categoryService, RelatedService relatedService, HTMLService htmlService, WorkflowService workflowService) { super(context, logger, preferencesService, cmsDataFactory, structureService, styleService, skinService, mvcFinder, tableStateManager); this.categoryService = categoryService; this.relatedService = relatedService; this.htmlService = htmlService; this.workflowService = workflowService; } @Override public String getState() throws ProcessingException { // this method is called multiple times during rendering, so it makes sense to cache the evaluated state String state = (String) context.getAttribute(getClass().getName()+".state"); if(state == null) { Parameters parameters = RequestParameters.getRequestParameters(context); AuthenticationContext authContext = context.getAttribute(AuthenticationContext.class); CmsData cmsData = cmsDataFactory.getCmsData(context); Parameters screenConfig = cmsData.getEmbeddedScreenConfig(); long mainCategoryRoot = screenConfig.getLong("category_id_2", -1); long[] selectedCategories = parameters.getLongs("selected_categories"); state = parameters.get("state", null); if(state == null) { boolean editingEnabled = screenConfig.getBoolean("editing_enabled", false); if(editingEnabled) { if(authContext.isUserAuthenticated()) { state = "MyDocuments"; } else { state = "Anonymous"; } } else { state = "AddDocument"; } } if("AddDocument".equals(state) && mainCategoryRoot != -1 && selectedCategories.length == 0) { state = "DocumentCategory"; } context.setAttribute(getClass().getName() + ".state", state); } return state; } @Override public boolean requiresAuthenticatedUser(Context context) throws Exception { return REQUIRES_AUTHENTICATED_USER.contains(getState()); } @Override public boolean checkAccessRights(Context context) throws ProcessingException { TemplatingContext templatingContext = context.getAttribute(TemplatingContext.class); String result = (String)templatingContext.get("result"); if("exception".equals(result)) { return true; } String state = getState(); if("Anonymous".equals(state)) { return true; } try { Parameters requestParameters = context.getAttribute(RequestParameters.class); CoralSession coralSession = context.getAttribute(CoralSession.class); Subject userSubject = coralSession.getUserSubject(); if("AddDocument".equals(state) || "MyDocuments".equals(state) || "DocumentCategory".equals(state)) { Permission submitPermission = coralSession.getSecurity().getUniquePermission( "cms.structure.submit"); CmsData cmsData = cmsDataFactory.getCmsData(context); Parameters screenConfig = cmsData.getEmbeddedScreenConfig(); long parentId = screenConfig.getLong("parent_id", -1L); Resource parent = parentId != -1L ? NavigationNodeResourceImpl .getNavigationNodeResource(coralSession, parentId) : cmsData.getNode(); return userSubject.hasPermission(parent, submitPermission); } if("EditDocument".equals(state) || "RemovalRequest".equals(state) || "RedactorsNote".equals(state)) { long id = requestParameters.getLong("doc_id", -1); Resource node = NavigationNodeResourceImpl.getNavigationNodeResource(coralSession, id); Permission modifyPermission = coralSession.getSecurity().getUniquePermission( "cms.structure.modify"); Permission modifyOwnPermission = coralSession.getSecurity().getUniquePermission( "cms.structure.modify_own"); if(userSubject.hasPermission(node, modifyPermission)) { return true; } if(node.getOwner().equals(userSubject) && userSubject.hasPermission(node, modifyOwnPermission)) { return true; } + if(node.getCreatedBy().equals(userSubject) + && userSubject.hasPermission(node, modifyOwnPermission)) + { + return true; + } } return false; } catch(Exception e) { throw new ProcessingException(e); } } /** * Welcome view for the anonymous user. * <p> * Allows the user to log in, or proceed to submit a document anonymously. * </p> */ public void prepareAnonymous(Context context) { } /** * Set main category for new document. */ public void prepareDocumentCategory(Context context) throws ProcessingException { try { prepareCategories(context, true); } catch(Exception e) { throw new ProcessingException("internal errror", e); } } /** * Submitted documents list for an authenticated user. */ public void prepareMyDocuments(Context context) throws ProcessingException { try { I18nContext i18nContext = context.getAttribute(I18nContext.class); TemplatingContext templatingContext = context.getAttribute(TemplatingContext.class); CmsData cmsData = cmsDataFactory.getCmsData(context); CoralSession coralSession = context.getAttribute(CoralSession.class); String query = "FIND RESOURCE FROM documents.document_node WHERE created_by = " + coralSession.getUserSubject().getIdString() + " AND site = " + cmsData.getSite().getIdString(); List<Resource> myDocuments = (List<Resource>)coralSession.getQuery().executeQuery(query).getList(1); TableColumn<Resource> columns[] = new TableColumn[2]; columns[0] = new TableColumn<Resource>("creation.time", new CreationTimeComparator()); columns[1] = new TableColumn<Resource>("title", new TitleComparator(i18nContext.getLocale())); ListTableModel<Resource> model = new ListTableModel<Resource>(myDocuments, columns); List<TableFilter<Resource>> filters = new ArrayList<TableFilter<Resource>>(); ResourceClass navigationNodeClass = coralSession.getSchema().getResourceClass( "structure.navigation_node"); Resource cmsRoot = coralSession.getStore().getUniqueResourceByPath("/cms"); AutomatonResource automaton = workflowService.getPrimaryAutomaton(coralSession, cmsRoot, navigationNodeClass); Set<StateResource> rejectedStates = new HashSet<StateResource>(); rejectedStates.add(workflowService.getState(coralSession, automaton, "expired")); filters.add(new InverseFilter(new StateFilter(rejectedStates, true))); TableState state = tableStateManager.getState(context, this.getClass().getName()+":MyDocuments"); if(state.isNew()) { state.setTreeView(false); state.setSortColumnName("creation.time"); state.setAscSort(false); state.setPageSize(20); } templatingContext.put("table", new TableTool<Resource>(state, filters, model)); templatingContext.put("documentState", new DocumentStateTool(coralSession,logger)); } catch(Exception e) { throw new ProcessingException("internal errror", e); } } /** * Propse a new document, either anonymously or as an authenitcated user. * * @param context * @throws ProcessingException */ public void prepareAddDocument(Context context) throws ProcessingException { Parameters parameters = RequestParameters.getRequestParameters(context); CoralSession coralSession = context.getAttribute(CoralSession.class); TemplatingContext templatingContext = TemplatingContext.getTemplatingContext(context); SiteResource site = getSite(); try { // refill parameters in case we are coming back failed validation Parameters screenConfig = getScreenConfig(); ProposedDocumentData data = new ProposedDocumentData(screenConfig,logger); data.fromParameters(parameters, coralSession); data.toTemplatingContext(templatingContext); prepareCategories(context, true); // resolve parent node in case template needs it for security check CmsData cmsData = cmsDataFactory.getCmsData(context); long parentId = screenConfig.getLong("parent_id", -1L); Resource parentNode = parentId != -1L ? NavigationNodeResourceImpl .getNavigationNodeResource(coralSession, parentId) : cmsData.getNode(); templatingContext.put("parent_node", parentNode); templatingContext.put("add_captcha", screenConfig.getBoolean( "add_captcha", false)); } catch(Exception e) { screenError(getNode(), context, "Screen Error ", e); } } /** * Edit a previously submitted document. * * @param context * @throws ProcessingException */ public void prepareEditDocument(Context context) throws ProcessingException { Parameters parameters = RequestParameters.getRequestParameters(context); CoralSession coralSession = context.getAttribute(CoralSession.class); TemplatingContext templatingContext = TemplatingContext.getTemplatingContext(context); try { long docId = parameters.getLong("doc_id"); DocumentNodeResource node = DocumentNodeResourceImpl.getDocumentNodeResource(coralSession, docId); templatingContext.put("doc", node); ProposedDocumentData data = new ProposedDocumentData(getScreenConfig(),logger); if(parameters.getBoolean("form_loaded", false)) { data.fromParameters(parameters, coralSession); } else { if(node.isProposedContentDefined()) { data.fromProposal(node, coralSession); } else { data.fromNode(node, categoryService, relatedService, coralSession); data.cleanupContent(htmlService); } } data.toTemplatingContext(templatingContext); prepareCategories(context, true); } catch(Exception e) { screenError(getNode(), context, "Internal Error", e); } } /** * Send removal request previously submitted document. * * @param context * @throws ProcessingException */ public void prepareRemovalRequest(Context context) throws ProcessingException { Parameters parameters = RequestParameters.getRequestParameters(context); CoralSession coralSession = context.getAttribute(CoralSession.class); TemplatingContext templatingContext = TemplatingContext.getTemplatingContext(context); try { long docId = parameters.getLong("doc_id"); DocumentNodeResource node = DocumentNodeResourceImpl.getDocumentNodeResource( coralSession, docId); templatingContext.put("doc", node); ProposedDocumentData data = new ProposedDocumentData(getScreenConfig(),logger); if(parameters.getBoolean("form_loaded", false)) { data.fromParameters(parameters, coralSession); } else { if(node.isProposedContentDefined()) { data.fromProposal(node, coralSession); } else { data.fromNode(node, categoryService, relatedService, coralSession); data.cleanupContent(htmlService); } } data.toTemplatingContext(templatingContext); prepareCategories(context, true); } catch(Exception e) { screenError(getNode(), context, "Internal Error", e); } } /** * Receive redactor's note. * * @param context * @throws ProcessingException */ public void prepareRedactorsNote(Context context) throws ProcessingException { Parameters parameters = RequestParameters.getRequestParameters(context); CoralSession coralSession = context.getAttribute(CoralSession.class); TemplatingContext templatingContext = TemplatingContext.getTemplatingContext(context); try { long docId = parameters.getLong("doc_id"); DocumentNodeResource node = DocumentNodeResourceImpl.getDocumentNodeResource( coralSession, docId); templatingContext.put("doc", node); prepareCategories(context, true); } catch(Exception e) { screenError(getNode(), context, "Internal Error", e); } } }
true
true
public boolean checkAccessRights(Context context) throws ProcessingException { TemplatingContext templatingContext = context.getAttribute(TemplatingContext.class); String result = (String)templatingContext.get("result"); if("exception".equals(result)) { return true; } String state = getState(); if("Anonymous".equals(state)) { return true; } try { Parameters requestParameters = context.getAttribute(RequestParameters.class); CoralSession coralSession = context.getAttribute(CoralSession.class); Subject userSubject = coralSession.getUserSubject(); if("AddDocument".equals(state) || "MyDocuments".equals(state) || "DocumentCategory".equals(state)) { Permission submitPermission = coralSession.getSecurity().getUniquePermission( "cms.structure.submit"); CmsData cmsData = cmsDataFactory.getCmsData(context); Parameters screenConfig = cmsData.getEmbeddedScreenConfig(); long parentId = screenConfig.getLong("parent_id", -1L); Resource parent = parentId != -1L ? NavigationNodeResourceImpl .getNavigationNodeResource(coralSession, parentId) : cmsData.getNode(); return userSubject.hasPermission(parent, submitPermission); } if("EditDocument".equals(state) || "RemovalRequest".equals(state) || "RedactorsNote".equals(state)) { long id = requestParameters.getLong("doc_id", -1); Resource node = NavigationNodeResourceImpl.getNavigationNodeResource(coralSession, id); Permission modifyPermission = coralSession.getSecurity().getUniquePermission( "cms.structure.modify"); Permission modifyOwnPermission = coralSession.getSecurity().getUniquePermission( "cms.structure.modify_own"); if(userSubject.hasPermission(node, modifyPermission)) { return true; } if(node.getOwner().equals(userSubject) && userSubject.hasPermission(node, modifyOwnPermission)) { return true; } } return false; } catch(Exception e) { throw new ProcessingException(e); } }
public boolean checkAccessRights(Context context) throws ProcessingException { TemplatingContext templatingContext = context.getAttribute(TemplatingContext.class); String result = (String)templatingContext.get("result"); if("exception".equals(result)) { return true; } String state = getState(); if("Anonymous".equals(state)) { return true; } try { Parameters requestParameters = context.getAttribute(RequestParameters.class); CoralSession coralSession = context.getAttribute(CoralSession.class); Subject userSubject = coralSession.getUserSubject(); if("AddDocument".equals(state) || "MyDocuments".equals(state) || "DocumentCategory".equals(state)) { Permission submitPermission = coralSession.getSecurity().getUniquePermission( "cms.structure.submit"); CmsData cmsData = cmsDataFactory.getCmsData(context); Parameters screenConfig = cmsData.getEmbeddedScreenConfig(); long parentId = screenConfig.getLong("parent_id", -1L); Resource parent = parentId != -1L ? NavigationNodeResourceImpl .getNavigationNodeResource(coralSession, parentId) : cmsData.getNode(); return userSubject.hasPermission(parent, submitPermission); } if("EditDocument".equals(state) || "RemovalRequest".equals(state) || "RedactorsNote".equals(state)) { long id = requestParameters.getLong("doc_id", -1); Resource node = NavigationNodeResourceImpl.getNavigationNodeResource(coralSession, id); Permission modifyPermission = coralSession.getSecurity().getUniquePermission( "cms.structure.modify"); Permission modifyOwnPermission = coralSession.getSecurity().getUniquePermission( "cms.structure.modify_own"); if(userSubject.hasPermission(node, modifyPermission)) { return true; } if(node.getOwner().equals(userSubject) && userSubject.hasPermission(node, modifyOwnPermission)) { return true; } if(node.getCreatedBy().equals(userSubject) && userSubject.hasPermission(node, modifyOwnPermission)) { return true; } } return false; } catch(Exception e) { throw new ProcessingException(e); } }
diff --git a/src/main/java/com/drtshock/willie/command/misc/HelpCommandHandler.java b/src/main/java/com/drtshock/willie/command/misc/HelpCommandHandler.java index 0e0e979..ef857eb 100755 --- a/src/main/java/com/drtshock/willie/command/misc/HelpCommandHandler.java +++ b/src/main/java/com/drtshock/willie/command/misc/HelpCommandHandler.java @@ -1,20 +1,24 @@ package com.drtshock.willie.command.misc; import org.pircbotx.Channel; import org.pircbotx.User; import com.drtshock.willie.Willie; import com.drtshock.willie.command.Command; import com.drtshock.willie.command.CommandHandler; public class HelpCommandHandler implements CommandHandler { @Override public void handle(Willie bot, Channel channel, User sender, String[] args) { String cmdPrefix = bot.getConfig().getCommandPrefix(); for (Command command : bot.commandManager.getCommands()) { - sender.sendMessage(cmdPrefix + command.getName() + " - " + command.getHelp()); + if (command.isAdminOnly() && channel.getOps().contains(sender)) { + sender.sendMessage(cmdPrefix + command.getName() + " - " + command.getHelp()); + } else { + sender.sendMessage(cmdPrefix + command.getName() + " - " + command.getHelp()); + } } } }
true
true
public void handle(Willie bot, Channel channel, User sender, String[] args) { String cmdPrefix = bot.getConfig().getCommandPrefix(); for (Command command : bot.commandManager.getCommands()) { sender.sendMessage(cmdPrefix + command.getName() + " - " + command.getHelp()); } }
public void handle(Willie bot, Channel channel, User sender, String[] args) { String cmdPrefix = bot.getConfig().getCommandPrefix(); for (Command command : bot.commandManager.getCommands()) { if (command.isAdminOnly() && channel.getOps().contains(sender)) { sender.sendMessage(cmdPrefix + command.getName() + " - " + command.getHelp()); } else { sender.sendMessage(cmdPrefix + command.getName() + " - " + command.getHelp()); } } }
diff --git a/server-coreless/src/main/java/cybervillains/ca/KeyStoreManager.java b/server-coreless/src/main/java/cybervillains/ca/KeyStoreManager.java index 69326d35..9253307a 100755 --- a/server-coreless/src/main/java/cybervillains/ca/KeyStoreManager.java +++ b/server-coreless/src/main/java/cybervillains/ca/KeyStoreManager.java @@ -1,764 +1,764 @@ package cybervillains.ca; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.security.InvalidKeyException; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.SecureRandom; import java.security.Security; import java.security.SignatureException; import java.security.UnrecoverableKeyException; import java.security.cert.Certificate; import java.security.cert.CertificateEncodingException; import java.security.cert.CertificateException; import java.security.cert.CertificateExpiredException; import java.security.cert.CertificateNotYetValidException; import java.security.cert.CertificateParsingException; import java.security.cert.X509Certificate; import java.util.HashMap; import org.bouncycastle.jce.provider.BouncyCastleProvider; /** * This is the main entry point into the Cybervillains CA. * * This class handles generation, storage and the persistent * mapping of input to duplicated certificates and mapped public * keys. * * Default setting is to immediately persist changes to the store * by writing out the keystore and mapping file every time a new * certificate is added. This behavior can be disabled if desired, * to enhance performance or allow temporary testing without modifying * the certificate store. * *************************************************************************************** * Copyright (c) 2007, Information Security Partners, LLC * All rights reserved. * * This software licensed under the GPLv2, available in LICENSE.txt and at * http://www.gnu.org/licenses/gpl.txt * * @author Brad Hill * */ public class KeyStoreManager { private final String CERTMAP_SER_FILE = "certmap.ser"; private final String SUBJMAP_SER_FILE = "subjmap.ser"; private final String EXPORTED_CERT_NAME = "cybervillainsCA.cer"; private final char[] _keypassword = "password".toCharArray(); private final char[] _keystorepass = "password".toCharArray(); private final String _caPrivateKeystore = "cybervillainsCA.jks"; private final String _caCertAlias = "signingCert"; public static final String _caPrivKeyAlias = "signingCertPrivKey"; X509Certificate _caCert; PrivateKey _caPrivKey; KeyStore _ks; private HashMap<PublicKey, PrivateKey> _rememberedPrivateKeys; private HashMap<PublicKey, PublicKey> _mappedPublicKeys; private HashMap<String, String> _certMap; private HashMap<String, String> _subjectMap; private final String KEYMAP_SER_FILE = "keymap.ser"; private final String PUB_KEYMAP_SER_FILE = "pubkeymap.ser"; public final String RSA_KEYGEN_ALGO = "RSA"; public final String DSA_KEYGEN_ALGO = "DSA"; public final KeyPairGenerator _rsaKpg; public final KeyPairGenerator _dsaKpg; private SecureRandom _sr; private boolean persistImmediately = true; private File root; public KeyStoreManager(File root) { this.root = root; Security.insertProviderAt(new BouncyCastleProvider(), 2); _sr = new SecureRandom(); try { _rsaKpg = KeyPairGenerator.getInstance(RSA_KEYGEN_ALGO); _dsaKpg = KeyPairGenerator.getInstance(DSA_KEYGEN_ALGO); } catch(Throwable t) { throw new Error(t); } try { File privKeys = new File(root, KEYMAP_SER_FILE); if(!privKeys.exists()) { _rememberedPrivateKeys = new HashMap<PublicKey,PrivateKey>(); } else { ObjectInputStream in = new ObjectInputStream(new FileInputStream(privKeys)); // Deserialize the object _rememberedPrivateKeys = (HashMap<PublicKey,PrivateKey>)in.readObject(); in.close(); } File pubKeys = new File(root, PUB_KEYMAP_SER_FILE); if(!pubKeys.exists()) { _mappedPublicKeys = new HashMap<PublicKey,PublicKey>(); } else { ObjectInputStream in = new ObjectInputStream(new FileInputStream(pubKeys)); // Deserialize the object _mappedPublicKeys = (HashMap<PublicKey,PublicKey>)in.readObject(); in.close(); } } catch (FileNotFoundException e) { // check for file exists, won't happen. e.printStackTrace(); } catch (IOException e) { // we could correct, but this probably indicates a corruption // of the serialized file that we want to know about; likely // synchronization problems during serialization. e.printStackTrace(); throw new Error(e); } catch (ClassNotFoundException e) { // serious problem. e.printStackTrace(); throw new Error(e); } - _rsaKpg.initialize(1024, _sr); - _dsaKpg.initialize(1024, _sr); + _rsaKpg.initialize(2048, _sr); + _dsaKpg.initialize(2048, _sr); try { _ks = KeyStore.getInstance("JKS"); reloadKeystore(); } catch(FileNotFoundException fnfe) { try { createKeystore(); } catch(Exception e) { throw new Error(e); } } catch(Exception e) { throw new Error(e); } try { File file = new File(root, CERTMAP_SER_FILE); if(!file.exists()) { _certMap = new HashMap<String,String>(); } else { ObjectInputStream in = new ObjectInputStream(new FileInputStream(file)); // Deserialize the object _certMap = (HashMap<String,String>)in.readObject(); in.close(); } } catch (FileNotFoundException e) { // won't happen, check file.exists() e.printStackTrace(); } catch (IOException e) { // corrupted file, we want to know. e.printStackTrace(); throw new Error(e); } catch (ClassNotFoundException e) { // something very wrong, exit e.printStackTrace(); throw new Error(e); } try { File file = new File(root, SUBJMAP_SER_FILE); if(!file.exists()) { _subjectMap = new HashMap<String,String>(); } else { ObjectInputStream in = new ObjectInputStream(new FileInputStream(file)); // Deserialize the object _subjectMap = (HashMap<String,String>)in.readObject(); in.close(); } } catch (FileNotFoundException e) { // won't happen, check file.exists() e.printStackTrace(); } catch (IOException e) { // corrupted file, we want to know. e.printStackTrace(); throw new Error(e); } catch (ClassNotFoundException e) { // something very wrong, exit e.printStackTrace(); throw new Error(e); } } private void reloadKeystore() throws FileNotFoundException, IOException, NoSuchAlgorithmException, CertificateException, KeyStoreException, UnrecoverableKeyException { InputStream is = new FileInputStream(new File(root, _caPrivateKeystore)); if (is != null) { _ks.load(is, _keystorepass); _caCert = (X509Certificate)_ks.getCertificate(_caCertAlias); _caPrivKey = (PrivateKey)_ks.getKey(_caPrivKeyAlias, _keypassword); } } /** * Creates, writes and loads a new keystore and CA root certificate. */ protected void createKeystore() { Certificate signingCert = null; PrivateKey caPrivKey = null; if(_caCert == null || _caPrivKey == null) { try { System.out.println("Keystore or signing cert & keypair not found. Generating..."); KeyPair caKeypair = getRSAKeyPair(); caPrivKey = caKeypair.getPrivate(); signingCert = CertificateCreator.createTypicalMasterCert(caKeypair); System.out.println("Done generating signing cert"); System.out.println(signingCert); _ks.load(null, _keystorepass); _ks.setCertificateEntry(_caCertAlias, signingCert); _ks.setKeyEntry(_caPrivKeyAlias, caPrivKey, _keypassword, new Certificate[] {signingCert}); File caKsFile = new File(root, _caPrivateKeystore); OutputStream os = new FileOutputStream(caKsFile); _ks.store(os, _keystorepass); System.out.println("Wrote JKS keystore to: " + caKsFile.getAbsolutePath()); // also export a .cer that can be imported as a trusted root // to disable all warning dialogs for interception File signingCertFile = new File(root, EXPORTED_CERT_NAME); FileOutputStream cerOut = new FileOutputStream(signingCertFile); byte[] buf = signingCert.getEncoded(); System.out.println("Wrote signing cert to: " + signingCertFile.getAbsolutePath()); cerOut.write(buf); cerOut.flush(); cerOut.close(); _caCert = (X509Certificate)signingCert; _caPrivKey = caPrivKey; } catch(Exception e) { System.out.println("Fatal error creating/storing keystore or signing cert."); e.printStackTrace(); throw new Error(e); } } else { System.out.println("Successfully loaded keystore."); System.out.println(_caCert); } } /** * Stores a new certificate and its associated private key in the keystore. * @param hostname *@param cert * @param privKey @throws KeyStoreException * @throws CertificateException * @throws NoSuchAlgorithmException */ public synchronized void addCertAndPrivateKey(String hostname, final X509Certificate cert, final PrivateKey privKey) throws KeyStoreException, CertificateException, NoSuchAlgorithmException { String alias = ThumbprintUtil.getThumbprint(cert); _ks.deleteEntry(hostname); _ks.setCertificateEntry(hostname, cert); _ks.setKeyEntry(hostname, privKey, _keypassword, new Certificate[] {cert}); if(persistImmediately) { persist(); } } /** * Writes the keystore and certificate/keypair mappings to disk. * @throws KeyStoreException * @throws NoSuchAlgorithmException * @throws CertificateException */ public synchronized void persist() throws KeyStoreException, NoSuchAlgorithmException, CertificateException { try { FileOutputStream kso = new FileOutputStream(new File(root, _caPrivateKeystore)); _ks.store(kso, _keystorepass); kso.flush(); kso.close(); persistCertMap(); persistSubjectMap(); persistKeyPairMap(); persistPublicKeyMap(); } catch(IOException ioe) { ioe.printStackTrace(); } } /** * Returns the aliased certificate. Certificates are aliased by their SHA1 digest. * @see ThumbprintUtil * @param alias * @return * @throws KeyStoreException */ public synchronized X509Certificate getCertificateByAlias(final String alias) throws KeyStoreException{ return (X509Certificate)_ks.getCertificate(alias); } /** * Returns the aliased certificate. Certificates are aliased by their hostname. * @see ThumbprintUtil * @param alias * @return * @throws KeyStoreException * @throws UnrecoverableKeyException * @throws NoSuchProviderException * @throws NoSuchAlgorithmException * @throws CertificateException * @throws SignatureException * @throws CertificateNotYetValidException * @throws CertificateExpiredException * @throws InvalidKeyException * @throws CertificateParsingException */ public synchronized X509Certificate getCertificateByHostname(final String hostname) throws KeyStoreException, CertificateParsingException, InvalidKeyException, CertificateExpiredException, CertificateNotYetValidException, SignatureException, CertificateException, NoSuchAlgorithmException, NoSuchProviderException, UnrecoverableKeyException{ String alias = _subjectMap.get(getSubjectForHostname(hostname)); if(alias != null) { return (X509Certificate)_ks.getCertificate(alias); } else { return getMappedCertificateForHostname(hostname); } } /** * Gets the authority root signing cert. * @return * @throws KeyStoreException */ public synchronized X509Certificate getSigningCert() throws KeyStoreException { return _caCert; } /** * Gets the authority private signing key. * @return * @throws KeyStoreException * @throws NoSuchAlgorithmException * @throws UnrecoverableKeyException */ public synchronized PrivateKey getSigningPrivateKey() throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException { return _caPrivKey; } /** * Whether updates are immediately written to disk. * @return */ public boolean getPersistImmediately() { return persistImmediately; } /** * Whether updates are immediately written to disk. * @param persistImmediately */ public void setPersistImmediately(final boolean persistImmediately) { this.persistImmediately = persistImmediately; } /** * This method returns the duplicated certificate mapped to the passed in cert, or * creates and returns one if no mapping has yet been performed. If a naked public * key has already been mapped that matches the key in the cert, the already mapped * keypair will be reused for the mapped cert. * @param cert * @return * @throws CertificateEncodingException * @throws InvalidKeyException * @throws CertificateException * @throws CertificateNotYetValidException * @throws NoSuchAlgorithmException * @throws NoSuchProviderException * @throws SignatureException * @throws KeyStoreException * @throws UnrecoverableKeyException */ public synchronized X509Certificate getMappedCertificate(final X509Certificate cert) throws CertificateEncodingException, InvalidKeyException, CertificateException, CertificateNotYetValidException, NoSuchAlgorithmException, NoSuchProviderException, SignatureException, KeyStoreException, UnrecoverableKeyException { String thumbprint = ThumbprintUtil.getThumbprint(cert); String mappedCertThumbprint = _certMap.get(thumbprint); if(mappedCertThumbprint == null) { // Check if we've already mapped this public key from a KeyValue PublicKey mappedPk = getMappedPublicKey(cert.getPublicKey()); PrivateKey privKey; if(mappedPk == null) { PublicKey pk = cert.getPublicKey(); String algo = pk.getAlgorithm(); KeyPair kp; if(algo.equals("RSA")) { kp = getRSAKeyPair(); } else if(algo.equals("DSA")) { kp = getDSAKeyPair(); } else { throw new InvalidKeyException("Key algorithm " + algo + " not supported."); } mappedPk = kp.getPublic(); privKey = kp.getPrivate(); mapPublicKeys(cert.getPublicKey(), mappedPk); } else { privKey = getPrivateKey(mappedPk); } X509Certificate replacementCert = CertificateCreator.mitmDuplicateCertificate( cert, mappedPk, getSigningCert(), getSigningPrivateKey()); addCertAndPrivateKey(null, replacementCert, privKey); mappedCertThumbprint = ThumbprintUtil.getThumbprint(replacementCert); _certMap.put(thumbprint, mappedCertThumbprint); _certMap.put(mappedCertThumbprint, thumbprint); _subjectMap.put(replacementCert.getSubjectX500Principal().getName(), thumbprint); if(persistImmediately) { persist(); } return replacementCert; } else { return getCertificateByAlias(mappedCertThumbprint); } } /** * This method returns the mapped certificate for a hostname, or generates a "standard" * SSL server certificate issued by the CA to the supplied subject if no mapping has been * created. This is not a true duplication, just a shortcut method * that is adequate for web browsers. * * @param hostname * @return * @throws CertificateParsingException * @throws InvalidKeyException * @throws CertificateExpiredException * @throws CertificateNotYetValidException * @throws SignatureException * @throws CertificateException * @throws NoSuchAlgorithmException * @throws NoSuchProviderException * @throws KeyStoreException * @throws UnrecoverableKeyException */ public X509Certificate getMappedCertificateForHostname(String hostname) throws CertificateParsingException, InvalidKeyException, CertificateExpiredException, CertificateNotYetValidException, SignatureException, CertificateException, NoSuchAlgorithmException, NoSuchProviderException, KeyStoreException, UnrecoverableKeyException { String subject = getSubjectForHostname(hostname); String thumbprint = _subjectMap.get(subject); if(thumbprint == null) { KeyPair kp = getRSAKeyPair(); X509Certificate newCert = CertificateCreator.generateStdSSLServerCertificate(kp.getPublic(), getSigningCert(), getSigningPrivateKey(), subject); addCertAndPrivateKey(hostname, newCert, kp.getPrivate()); thumbprint = ThumbprintUtil.getThumbprint(newCert); _subjectMap.put(subject, thumbprint); if(persistImmediately) { persist(); } return newCert; } else { return getCertificateByAlias(thumbprint); } } private String getSubjectForHostname(String hostname) { //String subject = "C=USA, ST=WA, L=Seattle, O=Cybervillains, OU=CertificationAutority, CN=" + hostname + ", [email protected]"; String subject = "CN=" + hostname + ", OU=Test, O=CyberVillainsCA, L=Seattle, S=Washington, C=US"; return subject; } private synchronized void persistCertMap() { try { ObjectOutput out = new ObjectOutputStream(new FileOutputStream(new File(root, CERTMAP_SER_FILE))); out.writeObject(_certMap); out.flush(); out.close(); } catch (FileNotFoundException e) { // writing, this shouldn't happen... e.printStackTrace(); } catch (IOException e) { // big problem! e.printStackTrace(); throw new Error(e); } } private synchronized void persistSubjectMap() { try { ObjectOutput out = new ObjectOutputStream(new FileOutputStream(new File(root, SUBJMAP_SER_FILE))); out.writeObject(_subjectMap); out.flush(); out.close(); } catch (FileNotFoundException e) { // writing, this shouldn't happen... e.printStackTrace(); } catch (IOException e) { // big problem! e.printStackTrace(); throw new Error(e); } } /** * For a cert we have generated, return the private key. * @param cert * @return * @throws CertificateEncodingException * @throws KeyStoreException * @throws UnrecoverableKeyException * @throws NoSuchAlgorithmException */ public synchronized PrivateKey getPrivateKeyForLocalCert(final X509Certificate cert) throws CertificateEncodingException, KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException { String thumbprint = ThumbprintUtil.getThumbprint(cert); return (PrivateKey)_ks.getKey(thumbprint, _keypassword); } /** * Generate an RSA Key Pair * @return */ public KeyPair getRSAKeyPair() { KeyPair kp = _rsaKpg.generateKeyPair(); rememberKeyPair(kp); return kp; } /** * Generate a DSA Key Pair * @return */ public KeyPair getDSAKeyPair() { KeyPair kp = _dsaKpg.generateKeyPair(); rememberKeyPair(kp); return kp; } private synchronized void persistPublicKeyMap() { try { ObjectOutput out = new ObjectOutputStream(new FileOutputStream(new File(root, PUB_KEYMAP_SER_FILE))); out.writeObject(_mappedPublicKeys); out.flush(); out.close(); } catch (FileNotFoundException e) { // writing, won't happen e.printStackTrace(); } catch (IOException e) { // very bad e.printStackTrace(); throw new Error(e); } } private synchronized void persistKeyPairMap() { try { ObjectOutput out = new ObjectOutputStream(new FileOutputStream(new File(root, KEYMAP_SER_FILE))); out.writeObject(_rememberedPrivateKeys); out.flush(); out.close(); } catch (FileNotFoundException e) { // writing, won't happen. e.printStackTrace(); } catch (IOException e) { // very bad e.printStackTrace(); throw new Error(e); } } private synchronized void rememberKeyPair(final KeyPair kp) { _rememberedPrivateKeys.put(kp.getPublic(), kp.getPrivate()); if(persistImmediately) { persistKeyPairMap(); } } /** * Stores a public key mapping. * @param original * @param substitute */ public synchronized void mapPublicKeys(final PublicKey original, final PublicKey substitute) { _mappedPublicKeys.put(original, substitute); if(persistImmediately) { persistPublicKeyMap(); } } /** * If we get a KeyValue with a given public key, then * later see an X509Data with the same public key, we shouldn't split this * in our MITM impl. So when creating a new cert, we should check if we've already * assigned a substitute key and re-use it, and vice-versa. * @param pk * @return */ public synchronized PublicKey getMappedPublicKey(final PublicKey original) { return _mappedPublicKeys.get(original); } /** * Returns the private key for a public key we have generated. * @param pk * @return */ public synchronized PrivateKey getPrivateKey(final PublicKey pk) { return _rememberedPrivateKeys.get(pk); } public KeyStore getKeyStore() { return _ks; } }
true
true
public KeyStoreManager(File root) { this.root = root; Security.insertProviderAt(new BouncyCastleProvider(), 2); _sr = new SecureRandom(); try { _rsaKpg = KeyPairGenerator.getInstance(RSA_KEYGEN_ALGO); _dsaKpg = KeyPairGenerator.getInstance(DSA_KEYGEN_ALGO); } catch(Throwable t) { throw new Error(t); } try { File privKeys = new File(root, KEYMAP_SER_FILE); if(!privKeys.exists()) { _rememberedPrivateKeys = new HashMap<PublicKey,PrivateKey>(); } else { ObjectInputStream in = new ObjectInputStream(new FileInputStream(privKeys)); // Deserialize the object _rememberedPrivateKeys = (HashMap<PublicKey,PrivateKey>)in.readObject(); in.close(); } File pubKeys = new File(root, PUB_KEYMAP_SER_FILE); if(!pubKeys.exists()) { _mappedPublicKeys = new HashMap<PublicKey,PublicKey>(); } else { ObjectInputStream in = new ObjectInputStream(new FileInputStream(pubKeys)); // Deserialize the object _mappedPublicKeys = (HashMap<PublicKey,PublicKey>)in.readObject(); in.close(); } } catch (FileNotFoundException e) { // check for file exists, won't happen. e.printStackTrace(); } catch (IOException e) { // we could correct, but this probably indicates a corruption // of the serialized file that we want to know about; likely // synchronization problems during serialization. e.printStackTrace(); throw new Error(e); } catch (ClassNotFoundException e) { // serious problem. e.printStackTrace(); throw new Error(e); } _rsaKpg.initialize(1024, _sr); _dsaKpg.initialize(1024, _sr); try { _ks = KeyStore.getInstance("JKS"); reloadKeystore(); } catch(FileNotFoundException fnfe) { try { createKeystore(); } catch(Exception e) { throw new Error(e); } } catch(Exception e) { throw new Error(e); } try { File file = new File(root, CERTMAP_SER_FILE); if(!file.exists()) { _certMap = new HashMap<String,String>(); } else { ObjectInputStream in = new ObjectInputStream(new FileInputStream(file)); // Deserialize the object _certMap = (HashMap<String,String>)in.readObject(); in.close(); } } catch (FileNotFoundException e) { // won't happen, check file.exists() e.printStackTrace(); } catch (IOException e) { // corrupted file, we want to know. e.printStackTrace(); throw new Error(e); } catch (ClassNotFoundException e) { // something very wrong, exit e.printStackTrace(); throw new Error(e); } try { File file = new File(root, SUBJMAP_SER_FILE); if(!file.exists()) { _subjectMap = new HashMap<String,String>(); } else { ObjectInputStream in = new ObjectInputStream(new FileInputStream(file)); // Deserialize the object _subjectMap = (HashMap<String,String>)in.readObject(); in.close(); } } catch (FileNotFoundException e) { // won't happen, check file.exists() e.printStackTrace(); } catch (IOException e) { // corrupted file, we want to know. e.printStackTrace(); throw new Error(e); } catch (ClassNotFoundException e) { // something very wrong, exit e.printStackTrace(); throw new Error(e); } }
public KeyStoreManager(File root) { this.root = root; Security.insertProviderAt(new BouncyCastleProvider(), 2); _sr = new SecureRandom(); try { _rsaKpg = KeyPairGenerator.getInstance(RSA_KEYGEN_ALGO); _dsaKpg = KeyPairGenerator.getInstance(DSA_KEYGEN_ALGO); } catch(Throwable t) { throw new Error(t); } try { File privKeys = new File(root, KEYMAP_SER_FILE); if(!privKeys.exists()) { _rememberedPrivateKeys = new HashMap<PublicKey,PrivateKey>(); } else { ObjectInputStream in = new ObjectInputStream(new FileInputStream(privKeys)); // Deserialize the object _rememberedPrivateKeys = (HashMap<PublicKey,PrivateKey>)in.readObject(); in.close(); } File pubKeys = new File(root, PUB_KEYMAP_SER_FILE); if(!pubKeys.exists()) { _mappedPublicKeys = new HashMap<PublicKey,PublicKey>(); } else { ObjectInputStream in = new ObjectInputStream(new FileInputStream(pubKeys)); // Deserialize the object _mappedPublicKeys = (HashMap<PublicKey,PublicKey>)in.readObject(); in.close(); } } catch (FileNotFoundException e) { // check for file exists, won't happen. e.printStackTrace(); } catch (IOException e) { // we could correct, but this probably indicates a corruption // of the serialized file that we want to know about; likely // synchronization problems during serialization. e.printStackTrace(); throw new Error(e); } catch (ClassNotFoundException e) { // serious problem. e.printStackTrace(); throw new Error(e); } _rsaKpg.initialize(2048, _sr); _dsaKpg.initialize(2048, _sr); try { _ks = KeyStore.getInstance("JKS"); reloadKeystore(); } catch(FileNotFoundException fnfe) { try { createKeystore(); } catch(Exception e) { throw new Error(e); } } catch(Exception e) { throw new Error(e); } try { File file = new File(root, CERTMAP_SER_FILE); if(!file.exists()) { _certMap = new HashMap<String,String>(); } else { ObjectInputStream in = new ObjectInputStream(new FileInputStream(file)); // Deserialize the object _certMap = (HashMap<String,String>)in.readObject(); in.close(); } } catch (FileNotFoundException e) { // won't happen, check file.exists() e.printStackTrace(); } catch (IOException e) { // corrupted file, we want to know. e.printStackTrace(); throw new Error(e); } catch (ClassNotFoundException e) { // something very wrong, exit e.printStackTrace(); throw new Error(e); } try { File file = new File(root, SUBJMAP_SER_FILE); if(!file.exists()) { _subjectMap = new HashMap<String,String>(); } else { ObjectInputStream in = new ObjectInputStream(new FileInputStream(file)); // Deserialize the object _subjectMap = (HashMap<String,String>)in.readObject(); in.close(); } } catch (FileNotFoundException e) { // won't happen, check file.exists() e.printStackTrace(); } catch (IOException e) { // corrupted file, we want to know. e.printStackTrace(); throw new Error(e); } catch (ClassNotFoundException e) { // something very wrong, exit e.printStackTrace(); throw new Error(e); } }
diff --git a/src/main/java/com/concursive/connect/web/modules/messages/portlets/composePrivateMessage/SavePrivateMessageAction.java b/src/main/java/com/concursive/connect/web/modules/messages/portlets/composePrivateMessage/SavePrivateMessageAction.java index 6953842..8b98345 100644 --- a/src/main/java/com/concursive/connect/web/modules/messages/portlets/composePrivateMessage/SavePrivateMessageAction.java +++ b/src/main/java/com/concursive/connect/web/modules/messages/portlets/composePrivateMessage/SavePrivateMessageAction.java @@ -1,178 +1,179 @@ /* * ConcourseConnect * Copyright 2009 Concursive Corporation * http://www.concursive.com * * This file is part of ConcourseConnect, an open source social business * software and community platform. * * Concursive ConcourseConnect is free software: you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, version 3 of the License. * * Under the terms of the GNU Affero General Public License you must release the * complete source code for any application that uses any part of ConcourseConnect * (system header files and libraries used by the operating system are excluded). * These terms must be included in any work that has ConcourseConnect components. * If you are developing and distributing open source applications under the * GNU Affero General Public License, then you are free to use ConcourseConnect * under the GNU Affero General Public License. * * If you are deploying a web site in which users interact with any portion of * ConcourseConnect over a network, the complete source code changes must be made * available. For example, include a link to the source archive directly from * your web site. * * For OEMs, ISVs, SIs and VARs who distribute ConcourseConnect with their * products, and do not license and distribute their source code under the GNU * Affero General Public License, Concursive provides a flexible commercial * license. * * To anyone in doubt, we recommend the commercial license. Our commercial license * is competitively priced and will eliminate any confusion about how * ConcourseConnect can be used and distributed. * * ConcourseConnect 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 Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License * along with ConcourseConnect. If not, see <http://www.gnu.org/licenses/>. * * Attribution Notice: ConcourseConnect is an Original Work of software created * by Concursive Corporation */ package com.concursive.connect.web.modules.messages.portlets.composePrivateMessage; import com.concursive.commons.text.StringUtils; import com.concursive.commons.web.mvc.beans.GenericBean; import com.concursive.connect.Constants; import com.concursive.connect.web.modules.blog.dao.BlogPost; import com.concursive.connect.web.modules.login.dao.User; import com.concursive.connect.web.modules.login.utils.UserUtils; import com.concursive.connect.web.modules.members.dao.TeamMemberList; import com.concursive.connect.web.modules.messages.dao.PrivateMessage; import com.concursive.connect.web.modules.profile.dao.Project; import com.concursive.connect.web.portal.IPortletAction; import com.concursive.connect.web.portal.PortalUtils; import static com.concursive.connect.web.portal.PortalUtils.*; import javax.portlet.ActionRequest; import javax.portlet.ActionResponse; import javax.portlet.PortletException; import java.sql.Connection; import java.sql.SQLException; import java.sql.Timestamp; import javax.portlet.PortletSession; import nl.captcha.Captcha; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Action for saving a user's review * * @author Kailash Bhoopalam * @created December 22, 2008 */ public class SavePrivateMessageAction implements IPortletAction { private static Log LOG = LogFactory.getLog(SavePrivateMessageAction.class); public GenericBean processAction(ActionRequest request, ActionResponse response) throws Exception { // Determine the project container to use Project project = findProject(request); if (project == null) { throw new Exception("Project is null"); } // Check the user's permissions User user = getUser(request); if (!user.isLoggedIn()) { throw new PortletException("User needs to be logged in"); } // Determine the database connection to use Connection db = getConnection(request); // Track replies to previous messages PrivateMessage inboxPrivateMessage = null; // Populate all values from the request PrivateMessage privateMessage = (PrivateMessage) PortalUtils.getFormBean(request, PrivateMessage.class); if (privateMessage.getLinkModuleId() != Constants.PROJECT_MESSAGES_FILES) { privateMessage.setProjectId(project.getId()); int linkProjectId = getLinkProjectId(db, privateMessage.getLinkItemId(), privateMessage.getLinkModuleId()); if (linkProjectId == -1) { linkProjectId = project.getId(); } privateMessage.setLinkProjectId(linkProjectId); } else { //reply to a message from the inbox, so the project id needs to be the profile of user who sent the message inboxPrivateMessage = new PrivateMessage(db, privateMessage.getLinkItemId()); int profileProjectIdOfEnteredByUser = UserUtils.loadUser(inboxPrivateMessage.getEnteredBy()).getProfileProjectId(); privateMessage.setProjectId(profileProjectIdOfEnteredByUser); privateMessage.setParentId(inboxPrivateMessage.getId()); //update the last reply date of the message inboxPrivateMessage.setLastReplyDate(new Timestamp(System.currentTimeMillis())); } privateMessage.setEnteredBy(user.getId()); // Validate the form if (!StringUtils.hasText(privateMessage.getBody())) { privateMessage.getErrors().put("bodyError", "Message body is required"); return privateMessage; } - // Check for captcha if going to another user that is not a friend - if (privateMessage.getProjectId() > -1) { + // Check for captcha if this is a direct message (not a reply) + if (privateMessage.getLinkModuleId() != Constants.PROJECT_MESSAGES_FILES && + privateMessage.getProjectId() > -1) { if (privateMessage.getProject().getProfile() && !TeamMemberList.isOnTeam(db, privateMessage.getProjectId(), user.getId())) { LOG.debug("Verifying the captcha..."); String captcha = request.getParameter("captcha"); PortletSession session = request.getPortletSession(); Captcha captchaValue = (Captcha) session.getAttribute(Captcha.NAME); session.removeAttribute(Captcha.NAME); if (captchaValue == null || captcha == null || !captchaValue.isCorrect(captcha)) { privateMessage.getErrors().put("captchaError", "Text did not match image"); return privateMessage; } } } else { LOG.debug("Captcha not required"); } // Insert the private message boolean inserted = privateMessage.insert(db); if (inserted) { // Update the message replied to if (inboxPrivateMessage != null && inboxPrivateMessage.getId() != -1) { inboxPrivateMessage.update(db); } // Send email notice PortalUtils.processInsertHook(request, privateMessage); } // Close the panel, everything went well String ctx = request.getContextPath(); response.sendRedirect(ctx + "/close_panel_refresh.jsp"); return null; } /** * Gets the project Id for the related item. * E.g, A message sent to a profile of a user can refer to the blog the user has written in a business, organization or any other profile * * @param linkItemId * @param linkModuleId * @return */ private int getLinkProjectId(Connection db, int linkItemId, int linkModuleId) throws SQLException { int linkProjectId = -1; if (linkModuleId == Constants.PROJECT_BLOG_FILES) { BlogPost blogPost = new BlogPost(db, linkItemId); linkProjectId = blogPost.getProjectId(); } return linkProjectId; } }
true
true
public GenericBean processAction(ActionRequest request, ActionResponse response) throws Exception { // Determine the project container to use Project project = findProject(request); if (project == null) { throw new Exception("Project is null"); } // Check the user's permissions User user = getUser(request); if (!user.isLoggedIn()) { throw new PortletException("User needs to be logged in"); } // Determine the database connection to use Connection db = getConnection(request); // Track replies to previous messages PrivateMessage inboxPrivateMessage = null; // Populate all values from the request PrivateMessage privateMessage = (PrivateMessage) PortalUtils.getFormBean(request, PrivateMessage.class); if (privateMessage.getLinkModuleId() != Constants.PROJECT_MESSAGES_FILES) { privateMessage.setProjectId(project.getId()); int linkProjectId = getLinkProjectId(db, privateMessage.getLinkItemId(), privateMessage.getLinkModuleId()); if (linkProjectId == -1) { linkProjectId = project.getId(); } privateMessage.setLinkProjectId(linkProjectId); } else { //reply to a message from the inbox, so the project id needs to be the profile of user who sent the message inboxPrivateMessage = new PrivateMessage(db, privateMessage.getLinkItemId()); int profileProjectIdOfEnteredByUser = UserUtils.loadUser(inboxPrivateMessage.getEnteredBy()).getProfileProjectId(); privateMessage.setProjectId(profileProjectIdOfEnteredByUser); privateMessage.setParentId(inboxPrivateMessage.getId()); //update the last reply date of the message inboxPrivateMessage.setLastReplyDate(new Timestamp(System.currentTimeMillis())); } privateMessage.setEnteredBy(user.getId()); // Validate the form if (!StringUtils.hasText(privateMessage.getBody())) { privateMessage.getErrors().put("bodyError", "Message body is required"); return privateMessage; } // Check for captcha if going to another user that is not a friend if (privateMessage.getProjectId() > -1) { if (privateMessage.getProject().getProfile() && !TeamMemberList.isOnTeam(db, privateMessage.getProjectId(), user.getId())) { LOG.debug("Verifying the captcha..."); String captcha = request.getParameter("captcha"); PortletSession session = request.getPortletSession(); Captcha captchaValue = (Captcha) session.getAttribute(Captcha.NAME); session.removeAttribute(Captcha.NAME); if (captchaValue == null || captcha == null || !captchaValue.isCorrect(captcha)) { privateMessage.getErrors().put("captchaError", "Text did not match image"); return privateMessage; } } } else { LOG.debug("Captcha not required"); } // Insert the private message boolean inserted = privateMessage.insert(db); if (inserted) { // Update the message replied to if (inboxPrivateMessage != null && inboxPrivateMessage.getId() != -1) { inboxPrivateMessage.update(db); } // Send email notice PortalUtils.processInsertHook(request, privateMessage); } // Close the panel, everything went well String ctx = request.getContextPath(); response.sendRedirect(ctx + "/close_panel_refresh.jsp"); return null; }
public GenericBean processAction(ActionRequest request, ActionResponse response) throws Exception { // Determine the project container to use Project project = findProject(request); if (project == null) { throw new Exception("Project is null"); } // Check the user's permissions User user = getUser(request); if (!user.isLoggedIn()) { throw new PortletException("User needs to be logged in"); } // Determine the database connection to use Connection db = getConnection(request); // Track replies to previous messages PrivateMessage inboxPrivateMessage = null; // Populate all values from the request PrivateMessage privateMessage = (PrivateMessage) PortalUtils.getFormBean(request, PrivateMessage.class); if (privateMessage.getLinkModuleId() != Constants.PROJECT_MESSAGES_FILES) { privateMessage.setProjectId(project.getId()); int linkProjectId = getLinkProjectId(db, privateMessage.getLinkItemId(), privateMessage.getLinkModuleId()); if (linkProjectId == -1) { linkProjectId = project.getId(); } privateMessage.setLinkProjectId(linkProjectId); } else { //reply to a message from the inbox, so the project id needs to be the profile of user who sent the message inboxPrivateMessage = new PrivateMessage(db, privateMessage.getLinkItemId()); int profileProjectIdOfEnteredByUser = UserUtils.loadUser(inboxPrivateMessage.getEnteredBy()).getProfileProjectId(); privateMessage.setProjectId(profileProjectIdOfEnteredByUser); privateMessage.setParentId(inboxPrivateMessage.getId()); //update the last reply date of the message inboxPrivateMessage.setLastReplyDate(new Timestamp(System.currentTimeMillis())); } privateMessage.setEnteredBy(user.getId()); // Validate the form if (!StringUtils.hasText(privateMessage.getBody())) { privateMessage.getErrors().put("bodyError", "Message body is required"); return privateMessage; } // Check for captcha if this is a direct message (not a reply) if (privateMessage.getLinkModuleId() != Constants.PROJECT_MESSAGES_FILES && privateMessage.getProjectId() > -1) { if (privateMessage.getProject().getProfile() && !TeamMemberList.isOnTeam(db, privateMessage.getProjectId(), user.getId())) { LOG.debug("Verifying the captcha..."); String captcha = request.getParameter("captcha"); PortletSession session = request.getPortletSession(); Captcha captchaValue = (Captcha) session.getAttribute(Captcha.NAME); session.removeAttribute(Captcha.NAME); if (captchaValue == null || captcha == null || !captchaValue.isCorrect(captcha)) { privateMessage.getErrors().put("captchaError", "Text did not match image"); return privateMessage; } } } else { LOG.debug("Captcha not required"); } // Insert the private message boolean inserted = privateMessage.insert(db); if (inserted) { // Update the message replied to if (inboxPrivateMessage != null && inboxPrivateMessage.getId() != -1) { inboxPrivateMessage.update(db); } // Send email notice PortalUtils.processInsertHook(request, privateMessage); } // Close the panel, everything went well String ctx = request.getContextPath(); response.sendRedirect(ctx + "/close_panel_refresh.jsp"); return null; }
diff --git a/src/main/java/mmo/Core/MMOPlugin.java b/src/main/java/mmo/Core/MMOPlugin.java index 074c296..2722812 100644 --- a/src/main/java/mmo/Core/MMOPlugin.java +++ b/src/main/java/mmo/Core/MMOPlugin.java @@ -1,875 +1,878 @@ /* * This file is part of mmoMinecraft (https://github.com/mmoMinecraftDev). * * mmoMinecraft 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 mmo.Core; import com.avaje.ebean.EbeanServer; import com.avaje.ebean.EbeanServerFactory; import com.avaje.ebean.config.DataSourceConfig; import com.avaje.ebean.config.ServerConfig; import com.avaje.ebean.config.dbplatform.SQLitePlatform; import com.avaje.ebeaninternal.api.SpiEbeanServer; import com.avaje.ebeaninternal.server.ddl.DdlGenerator; import com.avaje.ebeaninternal.server.lib.sql.TransactionIsolation; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.io.StringReader; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.net.URLConnection; import java.util.ArrayList; import java.util.BitSet; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.logging.Level; import java.util.logging.Logger; import mmo.Core.events.MMOHUDEvent; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.Server; import org.bukkit.command.CommandSender; import org.bukkit.entity.HumanEntity; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.event.Event; import org.bukkit.plugin.PluginDescriptionFile; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.util.config.Configuration; import org.getspout.spoutapi.SpoutManager; import org.getspout.spoutapi.gui.Container; import org.getspout.spoutapi.gui.GenericContainer; import org.getspout.spoutapi.gui.WidgetAnchor; import org.getspout.spoutapi.player.SpoutPlayer; public abstract class MMOPlugin extends JavaPlugin { /** * mmoSupport() BitSet values */ public final int MMO_PLAYER = 1; // Calls onSpoutCraftPlayer() when someone joins or after onEnable public final int MMO_NO_CONFIG = 2; // No config file used for this plugin public final int MMO_AUTO_EXTRACT = 3; // Has *.png files inside the plugin.jar /** * Variables */ private MMOPluginDatabase database; protected PluginDescriptionFile description; protected Configuration cfg; protected PluginManager pm; protected Server server; protected Logger logger; protected String title; protected String prefix; protected static MMOPlugin mmoCore; protected MMOPlugin plugin; public static boolean hasSpout = false; public int version = 0, revision = 0; public boolean update = false; // If there's an update available @Override public void onEnable() { if (this instanceof MMOCore) { mmoCore = (MMOCore) this; } plugin = this; logger = Logger.getLogger("Minecraft"); description = getDescription(); server = getServer(); pm = server.getPluginManager(); title = description.getName().replace("^mmo", ""); prefix = ChatColor.GREEN + "[" + ChatColor.AQUA + title + ChatColor.GREEN + "] " + ChatColor.WHITE; hasSpout = server.getPluginManager().isPluginEnabled("Spout"); String oldVersion[] = description.getVersion().split("\\."); if (oldVersion.length == 2) { version = Integer.parseInt(oldVersion[0]); revision = Integer.parseInt(oldVersion[1]); } else { log("Unable to determine version!"); } /** * Move mmoPlugin/* to mmoCore/* */ if (getDataFolder().exists()) { try { for (File from : getDataFolder().listFiles()) { String name = from.getName(); boolean isConfig = false; if (name.equalsIgnoreCase("config.yml")) { isConfig = true; name = description.getName() + ".yml"; } if ((isConfig || this != mmoCore) && !from.renameTo(new File(mmoCore.getDataFolder(), name))) { log("Unable to move file: " + from.getName()); } } getDataFolder().delete(); } catch (Exception e) { } } log("Enabled " + description.getFullName()); BitSet support = mmoSupport(new BitSet()); if (!support.get(MMO_NO_CONFIG)) { cfg = new Configuration(new File(mmoCore.getDataFolder() + File.separator + description.getName() + ".yml")); - cfg.setHeader("#" + title + " Configuration"); + cfg.load(); loadConfiguration(cfg); - cfg.save(); + if (!cfg.getKeys().isEmpty()) { + cfg.setHeader("#" + title + " Configuration"); + cfg.save(); + } } if (hasSpout) { if (support.get(MMO_PLAYER)) { MMOCore.support_mmo_player.add(this); } if (support.get(MMO_AUTO_EXTRACT)) { try { boolean found = false; JarFile jar = new JarFile(getFile()); Enumeration entries = jar.entries(); while (entries.hasMoreElements()) { JarEntry file = (JarEntry) entries.nextElement(); String name = file.getName(); if (name.matches(".*\\.png$|^config.yml$")) { if (!found) { new File(mmoCore.getDataFolder() + File.separator + description.getName() + File.separator).mkdir(); found = true; } File f = new File(mmoCore.getDataFolder() + File.separator + description.getName() + File.separator + name); if (!f.exists()) { InputStream is = jar.getInputStream(file); FileOutputStream fos = new FileOutputStream(f); while (is.available() > 0) { fos.write(is.read()); } fos.close(); is.close(); } SpoutManager.getFileManager().addToCache(plugin, f); } } } catch (Exception e) { } } } } @Override public void onDisable() { log("Disabled " + description.getFullName()); } /** * Load the configuration - don't save or anything... * @param cfg */ public void loadConfiguration(Configuration cfg) { } /** * Supply a bitfield of shortcuts for MMOPlugin to handle * @return */ public BitSet mmoSupport(BitSet support) { return support; } /** * Called when any player joins - need to return MMO_PLAYER from mmoSupport() * @param player */ public void onPlayerJoin(Player player) { } /** * Called for every Spoutcraft player on /reload and PlayerJoin - need to return MMO_PLAYER from mmoSupport() * @param player */ public void onSpoutCraftPlayer(SpoutPlayer player) { } /** * Called for every *NON* Spoutcraft player on /reload and PlayerJoin - need to return MMO_PLAYER from mmoSupport() * @param player */ public void onNormalPlayer(Player player) { } /** * Called when any player quits or is kicked - need to return MMO_PLAYER from mmoSupport() * @param player */ public void onPlayerQuit(Player player) { } /** * Send a message to the log * @param text A format style string * @param args */ public void log(String text, Object... args) { logger.log(Level.INFO, "[" + description.getName() + "] " + String.format(text, args)); } /** * Return the fill pathname for an auto-extracted file * @param name * @return */ public String getResource(String name) { return this.getDataFolder() + File.separator + name; } /** * Pop up a Party "achievement" message * @param name The player to tell * @param msg The message to send (max 23 chars) */ public void notify(String name, String msg, Object... args) { this.notify(server.getPlayer(name), msg, Material.SIGN, args); } /** * Pop up a Party "achievement" message * @param name The player to tell * @param msg The message to send (max 23 chars) * @param icon The material to use */ public void notify(String name, String msg, Material icon, Object... args) { this.notify(server.getPlayer(name), msg, icon, args); } /** * Pop up a Party "achievement" message for multiple players * @param players The player to tell * @param msg The message to send (max 23 chars) */ public void notify(List<Player> players, String msg, Object... args) { for (Player player : players) { this.notify(player, msg, Material.SIGN, args); } } /** * Pop up a Party "achievement" message for multiple players * @param players The player to tell * @param msg The message to send (max 23 chars) */ public void notify(List<Player> players, String msg, Material icon, Object... args) { for (Player player : players) { this.notify(player, msg, icon, args); } } /** * Pop up a Party "achievement" message * @param player The player to tell * @param msg The message to send (max 23 chars) */ public void notify(Player player, String msg, Object... args) { this.notify(player, msg, Material.SIGN, args); } /** * Pop up a Party "achievement" message * @param player The player to tell * @param msg The message to send (max 23 chars) * @param icon The material to use */ public void notify(Player player, String msg, Material icon, Object... args) { if (hasSpout && player != null) { try { SpoutManager.getPlayer(player).sendNotification(title, String.format(msg, args), icon); } catch (Exception e) { // Bad format->Object type } } } /** * Send a message to one person by name. * @param prefix Whether to show the plugin name * @param name The player to message * @param msg The message to send */ public void sendMessage(String name, String msg, Object... args) { sendMessage(true, server.getPlayer(name), msg, args); } /** * Send a message to multiple people. * @param prefix Whether to show the plugin name * @param players The Players to message * @param msg The message to send */ public void sendMessage(List<Player> players, String msg, Object... args) { for (Player player : players) { sendMessage(true, player, msg, args); } } /** * Send a message to one person. * @param prefix Whether to show the plugin name * @param player The Player to message * @param msg The message to send */ public void sendMessage(CommandSender player, String msg, Object... args) { sendMessage(true, player, msg, args); } /** * Send a message to one person by name. * @param name The player to message * @param msg The message to send */ public void sendMessage(boolean prefix, String name, String msg, Object... args) { sendMessage(prefix, server.getPlayer(name), msg, args); } /** * Send a message to multiple people. * @param players The Players to message * @param msg The message to send */ public void sendMessage(boolean prefix, List<CommandSender> players, String msg, Object... args) { for (CommandSender player : players) { sendMessage(prefix, player, msg, args); } } /** * Send a message to one person. * @param player The Player to message * @param msg The message to send */ public void sendMessage(boolean prefix, CommandSender player, String msg, Object... args) { if (player != null) { try { for (String line : String.format(msg, args).split("\n")) { player.sendMessage((prefix ? this.prefix : "") + line); } } catch (Exception e) { // Bad format->Object type } } } /** * Get the container for use by this plugin, anchor and position can be overridden by options. * @return */ public Container getContainer(SpoutPlayer player, String anchorName, int offsetX, int offsetY) { WidgetAnchor anchor = WidgetAnchor.SCALE; if ("TOP_LEFT".equalsIgnoreCase(anchorName)) { anchor = WidgetAnchor.TOP_LEFT; } else if ("TOP_CENTER".equalsIgnoreCase(anchorName)) { anchor = WidgetAnchor.TOP_CENTER; offsetX -= 213; } else if ("TOP_RIGHT".equalsIgnoreCase(anchorName)) { anchor = WidgetAnchor.TOP_RIGHT; offsetX = -427 - offsetX; } else if ("CENTER_LEFT".equalsIgnoreCase(anchorName)) { anchor = WidgetAnchor.CENTER_LEFT; offsetY -= 120; } else if ("CENTER_CENTER".equalsIgnoreCase(anchorName)) { anchor = WidgetAnchor.CENTER_CENTER; offsetX -= 213; offsetY -= 120; } else if ("CENTER_RIGHT".equalsIgnoreCase(anchorName)) { anchor = WidgetAnchor.CENTER_RIGHT; offsetX = -427 - offsetX; offsetY -= 120; } else if ("BOTTOM_LEFT".equalsIgnoreCase(anchorName)) { anchor = WidgetAnchor.BOTTOM_LEFT; offsetY = -240 - offsetY; } else if ("BOTTOM_CENTER".equalsIgnoreCase(anchorName)) { anchor = WidgetAnchor.BOTTOM_CENTER; offsetX -= 213; offsetY = -240 - offsetY; } else if ("BOTTOM_RIGHT".equalsIgnoreCase(anchorName)) { anchor = WidgetAnchor.BOTTOM_RIGHT; offsetX = -427 - offsetX; offsetY = -240 - offsetY; } MMOHUDEventEvent event = new MMOHUDEventEvent(player, plugin, anchor, offsetX, offsetY); pm.callEvent(event); Container container = (Container) new GenericContainer().setAlign(event.anchor).setAnchor(event.anchor).setFixed(true).setX(event.offsetX).setY(event.offsetY).setWidth(427).setHeight(240); player.getMainScreen().attachWidget(this, container); return container; } /** * Spout-safe version of setGlobalTitle * @param target * @param title */ public void setTitle(LivingEntity target, String title) { if (hasSpout && target != null) { SpoutManager.getAppearanceManager().setGlobalTitle(target, title); } } /** * Spout-safe version of setPlayerTitle * @param player * @param target * @param title */ public void setTitle(Player player, LivingEntity target, String title) { if (hasSpout && player != null && target != null) { SpoutManager.getAppearanceManager().setPlayerTitle(SpoutManager.getPlayer(player), target, title); } } /** * Spout-safe version of setGlobalCloak * @param target * @param url */ public void setCloak(HumanEntity target, String url) { if (hasSpout && target != null) { SpoutManager.getAppearanceManager().setGlobalCloak(target, url); } } /** * Spout-safe version of setPlayerCloak * @param player * @param target * @param url */ public void setCloak(Player player, HumanEntity target, String url) { if (hasSpout && player != null && target != null) { SpoutManager.getAppearanceManager().setPlayerCloak(SpoutManager.getPlayer(player), target, url); } } /** * Spout-safe version of setGlobalCloak * @param target * @param url */ public void setSkin(HumanEntity target, String url) { if (hasSpout && target != null) { SpoutManager.getAppearanceManager().setGlobalSkin(target, url); } } /** * Spout-safe version of setPlayerCloak * @param player * @param target * @param url */ public void setSkin(Player player, HumanEntity target, String url) { if (hasSpout && player != null && target != null) { SpoutManager.getAppearanceManager().setPlayerSkin(SpoutManager.getPlayer(player), target, url); } } @Override public EbeanServer getDatabase() { if (database == null) { database = new MMOPluginDatabase(); database.initializeDatabase( MMOCore.config_database_driver, MMOCore.config_database_url, MMOCore.config_database_username, MMOCore.config_database_password, MMOCore.config_database_isolation, MMOCore.config_database_logging, MMOCore.config_database_rebuild); } return database.getDatabase(); } protected void beforeDropDatabase() { } protected void afterCreateDatabase() { } /** * Used to alter the HUD item locations */ private class MMOHUDEventEvent extends Event implements MMOHUDEvent { Player player; MMOPlugin plugin; WidgetAnchor anchor; int offsetX, offsetY; public MMOHUDEventEvent(Player player, MMOPlugin plugin, WidgetAnchor anchor, int offsetX, int offsetY) { super("mmoHUDEvent"); this.player = player; this.plugin = plugin; this.anchor = anchor; this.offsetX = offsetX; this.offsetY = offsetY; } @Override public Player getPlayer() { return player; } @Override public MMOPlugin getPlugin() { return plugin; } @Override public WidgetAnchor getAnchor() { return anchor; } @Override public int getOffsetX() { return offsetX; } @Override public void setOffsetX(int offsetX) { this.offsetX = offsetX; } @Override public int getOffsetY() { return offsetY; } @Override public void setOffsetY(int offsetY) { this.offsetY = offsetY; } } /* * MMOPluginDatabase by Lennard Fonteijn - http://www.lennardf1989.com/ * http://forums.bukkit.org/threads/24987/ * There may be alterations to more easily fit mmoMinecraft ;-) */ private class MMOPluginDatabase { private ClassLoader classLoader; private Level loggerLevel; private boolean usingSQLite; private ServerConfig serverConfig; private EbeanServer ebeanServer; /** * Create an instance of MMOPluginDatabase * @param javaPlugin Plugin instancing this database */ public MMOPluginDatabase() { //Try to get the ClassLoader of the plugin using Reflection try { //Find the "getClassLoader" method and make it "public" instead of "protected" Method method = JavaPlugin.class.getDeclaredMethod("getClassLoader"); method.setAccessible(true); //Store the ClassLoader this.classLoader = (ClassLoader) method.invoke(plugin); } catch (Exception ex) { throw new RuntimeException("Failed to retrieve the ClassLoader of the plugin using Reflection", ex); } } /** * Initialize the database using the passed arguments * * @param driver Database-driver to use. For example: org.sqlite.JDBC * @param url Location of the database. For example: jdbc:sqlite:{DIR}{NAME}.db * @param username Username required to access the database * @param password Password belonging to the username, may be empty * @param isolation Isolation type. For example: SERIALIZABLE, also see TransactionIsolation * @param logging If set to false, all logging will be disabled * @param rebuild If set to true, all tables will be dropped and recreated. Be sure to create a backup before doing so! */ public void initializeDatabase(String driver, String url, String username, String password, String isolation, boolean logging, boolean rebuild) { //Logging needs to be set back to the original level, no matter what happens try { //Disable all logging disableDatabaseLogging(logging); //Prepare the database prepareDatabase(driver, url, username, password, isolation); //Load the database loadDatabase(); //Create all tables installDatabase(rebuild); } catch (Exception ex) { throw new RuntimeException("An exception has occured while initializing the database", ex); } finally { //Enable all logging enableDatabaseLogging(logging); } } private void prepareDatabase(String driver, String url, String username, String password, String isolation) { //Setup the data source DataSourceConfig ds = new DataSourceConfig(); ds.setDriver(driver); ds.setUrl(replaceDatabaseString(url)); ds.setUsername(username); ds.setPassword(password); ds.setIsolationLevel(TransactionIsolation.getLevel(isolation)); //Setup the server configuration ServerConfig sc = new ServerConfig(); sc.setDefaultServer(false); sc.setRegister(false); sc.setName(ds.getUrl().replaceAll("[^a-zA-Z0-9]", "")); //Get all persistent classes List<Class<?>> classes = plugin.getDatabaseClasses(); //Do a sanity check first if (classes.isEmpty()) { //Exception: There is no use in continuing to load this database throw new RuntimeException("Database has been enabled, but no classes are registered to it"); } //Register them with the EbeanServer sc.setClasses(classes); //Check if the SQLite JDBC supplied with Bukkit is being used if (ds.getDriver().equalsIgnoreCase("org.sqlite.JDBC")) { //Remember the database is a SQLite-database usingSQLite = true; //Modify the platform, as SQLite has no AUTO_INCREMENT field sc.setDatabasePlatform(new SQLitePlatform()); sc.getDatabasePlatform().getDbDdlSyntax().setIdentity(""); } //Finally the data source sc.setDataSourceConfig(ds); //Store the ServerConfig serverConfig = sc; } private void loadDatabase() { //Declare a few local variables for later use ClassLoader currentClassLoader = null; Field cacheField = null; boolean cacheValue = true; try { //Store the current ClassLoader, so it can be reverted later currentClassLoader = Thread.currentThread().getContextClassLoader(); //Set the ClassLoader to Plugin ClassLoader Thread.currentThread().setContextClassLoader(classLoader); //Get a reference to the private static "defaultUseCaches"-field in URLConnection cacheField = URLConnection.class.getDeclaredField("defaultUseCaches"); //Make it accessible, store the default value and set it to false cacheField.setAccessible(true); cacheValue = cacheField.getBoolean(null); cacheField.setBoolean(null, false); //Setup Ebean based on the configuration ebeanServer = EbeanServerFactory.create(serverConfig); } catch (Exception ex) { throw new RuntimeException("Failed to create a new instance of the EbeanServer", ex); } finally { //Revert the ClassLoader back to its original value if (currentClassLoader != null) { Thread.currentThread().setContextClassLoader(currentClassLoader); } //Revert the "defaultUseCaches"-field in URLConnection back to its original value try { if (cacheField != null) { cacheField.setBoolean(null, cacheValue); } } catch (Exception e) { System.out.println("Failed to revert the \"defaultUseCaches\"-field back to its original value, URLConnection-caching remains disabled."); } } } private void installDatabase(boolean rebuild) { //Check if the database has to be rebuild if (!rebuild) { return; } //Create a DDL generator SpiEbeanServer serv = (SpiEbeanServer) ebeanServer; DdlGenerator gen = serv.getDdlGenerator(); //Check if the database already (partially) exists boolean databaseExists = false; List<Class<?>> classes = plugin.getDatabaseClasses(); for (int i = 0; i < classes.size(); i++) { try { //Do a simple query which only throws an exception if the table does not exist ebeanServer.find(classes.get(i)).findRowCount(); //Query passed without throwing an exception, a database therefore already exists databaseExists = true; break; } catch (Exception ex) { //Do nothing } } //Fire "before drop" event try { beforeDropDatabase(); } catch (Exception ex) { //If the database exists, dropping has to be canceled to prevent data-loss if (databaseExists) { throw new RuntimeException("An unexpected exception occured", ex); } } //Generate a DropDDL-script gen.runScript(true, gen.generateDropDdl()); //If SQLite is being used, the database has to reloaded to release all resources if (usingSQLite) { loadDatabase(); } //Generate a CreateDDL-script if (usingSQLite) { //If SQLite is being used, the CreateDLL-script has to be validated and potentially fixed to be valid gen.runScript(false, validateCreateDDLSqlite(gen.generateCreateDdl())); } else { gen.runScript(false, gen.generateCreateDdl()); } //Fire "after create" event try { afterCreateDatabase(); } catch (Exception ex) { throw new RuntimeException("An unexpected exception occured", ex); } } private String replaceDatabaseString(String input) { input = input.replaceAll("\\{DIR\\}", mmoCore.getDataFolder().getPath().replaceAll("\\\\", "/") + "/"); input = input.replaceAll("\\{NAME\\}", plugin.getDescription().getName().replaceAll("[^\\w_-]", "")); return input; } private String validateCreateDDLSqlite(String oldScript) { try { //Create a BufferedReader out of the potentially invalid script BufferedReader scriptReader = new BufferedReader(new StringReader(oldScript)); //Create an array to store all the lines List<String> scriptLines = new ArrayList<String>(); //Create some additional variables for keeping track of tables HashMap<String, Integer> foundTables = new HashMap<String, Integer>(); String currentTable = null; int tableOffset = 0; //Loop through all lines String currentLine; while ((currentLine = scriptReader.readLine()) != null) { //Trim the current line to remove trailing spaces currentLine = currentLine.trim(); //Add the current line to the rest of the lines scriptLines.add(currentLine.trim()); //Check if the current line is of any use if (currentLine.startsWith("create table")) { //Found a table, so get its name and remember the line it has been encountered on currentTable = currentLine.split(" ", 4)[2]; foundTables.put(currentLine.split(" ", 3)[2], scriptLines.size() - 1); } else if (currentLine.startsWith(";") && currentTable != null && !currentTable.equals("")) { //Found the end of a table definition, so update the entry int index = scriptLines.size() - 1; foundTables.put(currentTable, index); //Remove the last ")" from the previous line String previousLine = scriptLines.get(index - 1); previousLine = previousLine.substring(0, previousLine.length() - 1); scriptLines.set(index - 1, previousLine); //Change ";" to ");" on the current line scriptLines.set(index, ");"); //Reset the table-tracker currentTable = null; } else if (currentLine.startsWith("alter table")) { //Found a potentially unsupported action String[] alterTableLine = currentLine.split(" ", 4); if (alterTableLine[3].startsWith("add constraint")) { //Found an unsupported action: ALTER TABLE using ADD CONSTRAINT String[] addConstraintLine = alterTableLine[3].split(" ", 4); //Check if this line can be fixed somehow if (addConstraintLine[3].startsWith("foreign key")) { //Calculate the index of last line of the current table int tableLastLine = foundTables.get(alterTableLine[2]) + tableOffset; //Add a "," to the previous line scriptLines.set(tableLastLine - 1, scriptLines.get(tableLastLine - 1) + ","); //Add the constraint as a new line - Remove the ";" on the end String constraintLine = String.format("%s %s %s", addConstraintLine[1], addConstraintLine[2], addConstraintLine[3]); scriptLines.add(tableLastLine, constraintLine.substring(0, constraintLine.length() - 1)); //Remove this line and raise the table offset because a line has been inserted scriptLines.remove(scriptLines.size() - 1); tableOffset++; } else { //Exception: This line cannot be fixed but is known the be unsupported by SQLite throw new RuntimeException("Unsupported action encountered: ALTER TABLE using ADD CONSTRAINT with " + addConstraintLine[3]); } } } } //Turn all the lines back into a single string String newScript = ""; for (String newLine : scriptLines) { newScript += newLine + "\n"; } //Print the new script System.out.println(newScript); //Return the fixed script return newScript; } catch (Exception ex) { //Exception: Failed to fix the DDL or something just went plain wrong throw new RuntimeException("Failed to validate the CreateDDL-script for SQLite", ex); } } private void disableDatabaseLogging(boolean logging) { //If logging is allowed, nothing has to be changed if (logging) { return; } //Retrieve the level of the root logger loggerLevel = Logger.getLogger("").getLevel(); //Set the level of the root logger to OFF Logger.getLogger("").setLevel(Level.OFF); } private void enableDatabaseLogging(boolean logging) { //If logging is allowed, nothing has to be changed if (logging) { return; } //Set the level of the root logger back to the original value Logger.getLogger("").setLevel(loggerLevel); } /** * Method called before the loaded database is being dropped */ protected void beforeDropDatabase() { plugin.beforeDropDatabase(); } /** * Method called after the loaded database has been created */ protected void afterCreateDatabase() { plugin.afterCreateDatabase(); } /** * Get the instance of the EbeanServer * * @return EbeanServer Instance of the EbeanServer */ public EbeanServer getDatabase() { return ebeanServer; } } }
false
true
public void onEnable() { if (this instanceof MMOCore) { mmoCore = (MMOCore) this; } plugin = this; logger = Logger.getLogger("Minecraft"); description = getDescription(); server = getServer(); pm = server.getPluginManager(); title = description.getName().replace("^mmo", ""); prefix = ChatColor.GREEN + "[" + ChatColor.AQUA + title + ChatColor.GREEN + "] " + ChatColor.WHITE; hasSpout = server.getPluginManager().isPluginEnabled("Spout"); String oldVersion[] = description.getVersion().split("\\."); if (oldVersion.length == 2) { version = Integer.parseInt(oldVersion[0]); revision = Integer.parseInt(oldVersion[1]); } else { log("Unable to determine version!"); } /** * Move mmoPlugin/* to mmoCore/* */ if (getDataFolder().exists()) { try { for (File from : getDataFolder().listFiles()) { String name = from.getName(); boolean isConfig = false; if (name.equalsIgnoreCase("config.yml")) { isConfig = true; name = description.getName() + ".yml"; } if ((isConfig || this != mmoCore) && !from.renameTo(new File(mmoCore.getDataFolder(), name))) { log("Unable to move file: " + from.getName()); } } getDataFolder().delete(); } catch (Exception e) { } } log("Enabled " + description.getFullName()); BitSet support = mmoSupport(new BitSet()); if (!support.get(MMO_NO_CONFIG)) { cfg = new Configuration(new File(mmoCore.getDataFolder() + File.separator + description.getName() + ".yml")); cfg.setHeader("#" + title + " Configuration"); loadConfiguration(cfg); cfg.save(); } if (hasSpout) { if (support.get(MMO_PLAYER)) { MMOCore.support_mmo_player.add(this); } if (support.get(MMO_AUTO_EXTRACT)) { try { boolean found = false; JarFile jar = new JarFile(getFile()); Enumeration entries = jar.entries(); while (entries.hasMoreElements()) { JarEntry file = (JarEntry) entries.nextElement(); String name = file.getName(); if (name.matches(".*\\.png$|^config.yml$")) { if (!found) { new File(mmoCore.getDataFolder() + File.separator + description.getName() + File.separator).mkdir(); found = true; } File f = new File(mmoCore.getDataFolder() + File.separator + description.getName() + File.separator + name); if (!f.exists()) { InputStream is = jar.getInputStream(file); FileOutputStream fos = new FileOutputStream(f); while (is.available() > 0) { fos.write(is.read()); } fos.close(); is.close(); } SpoutManager.getFileManager().addToCache(plugin, f); } } } catch (Exception e) { } } } }
public void onEnable() { if (this instanceof MMOCore) { mmoCore = (MMOCore) this; } plugin = this; logger = Logger.getLogger("Minecraft"); description = getDescription(); server = getServer(); pm = server.getPluginManager(); title = description.getName().replace("^mmo", ""); prefix = ChatColor.GREEN + "[" + ChatColor.AQUA + title + ChatColor.GREEN + "] " + ChatColor.WHITE; hasSpout = server.getPluginManager().isPluginEnabled("Spout"); String oldVersion[] = description.getVersion().split("\\."); if (oldVersion.length == 2) { version = Integer.parseInt(oldVersion[0]); revision = Integer.parseInt(oldVersion[1]); } else { log("Unable to determine version!"); } /** * Move mmoPlugin/* to mmoCore/* */ if (getDataFolder().exists()) { try { for (File from : getDataFolder().listFiles()) { String name = from.getName(); boolean isConfig = false; if (name.equalsIgnoreCase("config.yml")) { isConfig = true; name = description.getName() + ".yml"; } if ((isConfig || this != mmoCore) && !from.renameTo(new File(mmoCore.getDataFolder(), name))) { log("Unable to move file: " + from.getName()); } } getDataFolder().delete(); } catch (Exception e) { } } log("Enabled " + description.getFullName()); BitSet support = mmoSupport(new BitSet()); if (!support.get(MMO_NO_CONFIG)) { cfg = new Configuration(new File(mmoCore.getDataFolder() + File.separator + description.getName() + ".yml")); cfg.load(); loadConfiguration(cfg); if (!cfg.getKeys().isEmpty()) { cfg.setHeader("#" + title + " Configuration"); cfg.save(); } } if (hasSpout) { if (support.get(MMO_PLAYER)) { MMOCore.support_mmo_player.add(this); } if (support.get(MMO_AUTO_EXTRACT)) { try { boolean found = false; JarFile jar = new JarFile(getFile()); Enumeration entries = jar.entries(); while (entries.hasMoreElements()) { JarEntry file = (JarEntry) entries.nextElement(); String name = file.getName(); if (name.matches(".*\\.png$|^config.yml$")) { if (!found) { new File(mmoCore.getDataFolder() + File.separator + description.getName() + File.separator).mkdir(); found = true; } File f = new File(mmoCore.getDataFolder() + File.separator + description.getName() + File.separator + name); if (!f.exists()) { InputStream is = jar.getInputStream(file); FileOutputStream fos = new FileOutputStream(f); while (is.available() > 0) { fos.write(is.read()); } fos.close(); is.close(); } SpoutManager.getFileManager().addToCache(plugin, f); } } } catch (Exception e) { } } } }
diff --git a/iudex-simhash/src/main/java/iudex/simhash/brutefuzzy/FuzzyList64.java b/iudex-simhash/src/main/java/iudex/simhash/brutefuzzy/FuzzyList64.java index 76bd7aa2..5cd1d20e 100644 --- a/iudex-simhash/src/main/java/iudex/simhash/brutefuzzy/FuzzyList64.java +++ b/iudex-simhash/src/main/java/iudex/simhash/brutefuzzy/FuzzyList64.java @@ -1,154 +1,154 @@ /* * Copyright (c) 2010 David Kellum * * 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 iudex.simhash.brutefuzzy; import java.util.Collection; /** * A linked array, brute-force scan implementation of FuzzySet64. */ public final class FuzzyList64 implements FuzzySet64 { public FuzzyList64( int capacity, final int thresholdBits ) { // Use ... 1, 2, 4, 8k bytes list segments. // The -8 (*8 = 64 bytes) is for size of this + array overhead // (see below) to keep complete segment at page boundary size. if( capacity > ( ( 1024 - 8 ) * 2 ) ) capacity = 1024 - 8; else if( capacity > ( ( 512 - 8 ) * 2 ) ) capacity = 512 - 8; else if( capacity > ( ( 256 - 8 ) * 3/2 ) ) capacity = 256 - 8; else if( capacity > ( ( 128 - 8 ) * 3/2 ) ) capacity = 128 - 8; else if( capacity > ( ( 64 - 8 ) * 3/2 ) ) capacity = 64 - 8; else if( capacity > ( ( 32 - 8 ) * 3/2 ) ) capacity = 32 - 8; else capacity = 0; if( capacity > 0 ) { _set = new long[ capacity ]; } _thresholdBits = thresholdBits; } public boolean addIfNotFound( final long key ) { final boolean vacant = ! find( key ); if( vacant ) store( key ); return vacant; } public boolean find( final long key ) { final int end = _length; final long[] set = _set; for( int i = 0; i < end; ++i ) { if ( fuzzyMatch( set[i], key ) ) return true; } if( _next != null ) return _next.find( key ); return false; } public boolean findAll( final long key, final Collection<Long> matches ) { boolean exactMatch = false; final int end = _length; final long[] set = _set; for( int i = 0; i < end; ++i ) { if ( fuzzyMatch( set[i], key ) ) { matches.add( set[i] ); if( set[i] == key ) exactMatch = true; } } if( _next != null ) { if( _next.findAll( key, matches ) ) exactMatch = true; } return exactMatch; } public boolean addFindAll( long key, Collection<Long> matches ) { boolean exactMatch = findAll( key, matches ); if( ! exactMatch ) store( key ); return exactMatch; } public boolean remove( final long key ) { boolean found = false; final int end = _length; final long[] set = _set; for( int i = 0; i < end; ++i ) { if ( set[i] == key ) { if( _length - i - 1 > 0 ) { System.arraycopy( set, i + 1, set, i, _length - i - 1 ); } --_length; found = true; break; } } if( !found && ( _next != null ) ) { found = _next.remove( key ); } return found; } public boolean fuzzyMatch( final long a, final long b ) { final long xor = a ^ b; int diff = Integer.bitCount( (int) xor ); if( diff <= _thresholdBits ) { diff += Integer.bitCount( (int) ( xor >> 32 ) ); return ( diff <= _thresholdBits ); } return false; } void store( final long key ) { if( _length < _set.length ) { _set[ _length++ ] = key; } else { - // Start chaining at 2048 total segment size + // Start chaining at 1024 total segment size if( ( _set.length < ( 128 - 8 ) ) ) { long[] snew = new long[ _set.length * 2 + 8 ]; System.arraycopy( _set, 0, snew, 0, _length ); _set = snew; _set[ _length++ ] = key; } else { if( _next == null ) { _next = new FuzzyList64( _set.length, _thresholdBits ); } _next.store( key ); } } } //x86_64 size: (this: 2 * 8 ) + 4 + 8 + 4 + 8 + // (array: 3*8 ) = 8 * 8 = 64 bytes private final int _thresholdBits; private static final long[] EMPTY_SET = {}; private long[] _set = EMPTY_SET; private int _length = 0; private FuzzyList64 _next = null; }
true
true
void store( final long key ) { if( _length < _set.length ) { _set[ _length++ ] = key; } else { // Start chaining at 2048 total segment size if( ( _set.length < ( 128 - 8 ) ) ) { long[] snew = new long[ _set.length * 2 + 8 ]; System.arraycopy( _set, 0, snew, 0, _length ); _set = snew; _set[ _length++ ] = key; } else { if( _next == null ) { _next = new FuzzyList64( _set.length, _thresholdBits ); } _next.store( key ); } } }
void store( final long key ) { if( _length < _set.length ) { _set[ _length++ ] = key; } else { // Start chaining at 1024 total segment size if( ( _set.length < ( 128 - 8 ) ) ) { long[] snew = new long[ _set.length * 2 + 8 ]; System.arraycopy( _set, 0, snew, 0, _length ); _set = snew; _set[ _length++ ] = key; } else { if( _next == null ) { _next = new FuzzyList64( _set.length, _thresholdBits ); } _next.store( key ); } } }
diff --git a/Enduro/src/gui/Gui.java b/Enduro/src/gui/Gui.java index 4b5b877..3406531 100644 --- a/Enduro/src/gui/Gui.java +++ b/Enduro/src/gui/Gui.java @@ -1,157 +1,157 @@ package gui; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.Font; import java.awt.Toolkit; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.io.File; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import members.Time; import sort.Formater; @SuppressWarnings("serial") public class Gui extends JFrame { // This number +1 is the number of lines of text kept in memory. private static final int maxNrOfEntriesShown = 3; private JPanel controlNorthPanel; private JScrollPane textCenterPanel; private JTextArea textArea; private JTextField textField; private Font bigFont; private GuiPrinter printer; private Dimension screenSize; /** * A simple frame for entering times of racers. * * @param output * The file to write the entries to. */ public Gui(String output) { screenSize = Toolkit.getDefaultToolkit().getScreenSize(); bigFont = new Font("Times New Roman", Font.BOLD, screenSize.height / 7); setLayout(new BorderLayout()); controlNorthPanelSetUp(); textCentralPanelSetUp(); setTitle("ENDURO"); printer = new GuiPrinter(output); setDefaultCloseOperation(EXIT_ON_CLOSE); setResizable(false); setVisible(true); pack(); - if (!new File(output).exists()) { - Object[] options = { "Startstation", "Slutstation" }; - int choice = JOptionPane.showOptionDialog(this, - "Startstation eller slutstation?", "Stationsval", - JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, - null, options, options[0]); - printer.writeLine(Formater.formatColumns(Formater.START_NR, - choice == 0 ? Formater.START_TIME : Formater.FINISH_TIME)); - // setTitle("ENDURO - " + options[choice]); - } else { - } + // if (!new File(output).exists()) { + // Object[] options = { "Startstation", "Slutstation" }; + // int choice = JOptionPane.showOptionDialog(this, + // "Startstation eller slutstation?", "Stationsval", + // JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, + // null, options, options[0]); + // printer.writeLine(Formater.formatColumns(Formater.START_NR, + // choice == 0 ? Formater.START_TIME : Formater.FINISH_TIME)); + // // setTitle("ENDURO - " + options[choice]); + // } else { + // } setSize(screenSize); } /** * Sets up the upper bar and its formatting. */ private void controlNorthPanelSetUp() { // Format dimensions int textFieldLength = (screenSize.width / 3) / bigFont.getSize(); Dimension buttonDimension = new Dimension(screenSize.width / 3, screenSize.height / 7); // Add the Panel controlNorthPanel = new JPanel(); add(controlNorthPanel, BorderLayout.NORTH); // Create text field textField = new JTextField(textFieldLength); textField.setFont(bigFont); addRespondToKey(); controlNorthPanel.add(textField, BorderLayout.WEST); // Create the button (separate class) controlNorthPanel.add(new RegisterButton(this, buttonDimension), BorderLayout.EAST); } /** * Makes the enter key have the same function as the button. */ private void addRespondToKey() { textField.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent evt) { if (evt.getKeyCode() == KeyEvent.VK_ENTER) { register(); } } }); } /** * Sets up the central text field showing recent entries. */ private void textCentralPanelSetUp() { // Format and create text area. this.textArea = new JTextArea(6, 12); textArea.setFont(bigFont); textArea.setFocusable(false); textArea.setEditable(false); // Add the panel textCenterPanel = new JScrollPane(textArea); add(textCenterPanel, BorderLayout.CENTER); } /** * Tells the program to read the textField and write to file etc. */ public void register() { // Read and then flush the textField String comNr = textField.getText(); textField.setText(""); // Format the new entry. Time t = Time.fromCurrentTime(); String temp = Formater.formatColumns(comNr, t); // Print to file printer.writeLine(temp); // Add the entry to the top of the recent list. String[] temprows = textArea.getText().split("\\n"); for (int i = 0; i < temprows.length && i < maxNrOfEntriesShown; i++) { temp = temp + "\n" + temprows[i]; } textArea.setText(temp); // Finishing updates textField.requestFocus(); textArea.invalidate(); repaint(); } }
true
true
public Gui(String output) { screenSize = Toolkit.getDefaultToolkit().getScreenSize(); bigFont = new Font("Times New Roman", Font.BOLD, screenSize.height / 7); setLayout(new BorderLayout()); controlNorthPanelSetUp(); textCentralPanelSetUp(); setTitle("ENDURO"); printer = new GuiPrinter(output); setDefaultCloseOperation(EXIT_ON_CLOSE); setResizable(false); setVisible(true); pack(); if (!new File(output).exists()) { Object[] options = { "Startstation", "Slutstation" }; int choice = JOptionPane.showOptionDialog(this, "Startstation eller slutstation?", "Stationsval", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); printer.writeLine(Formater.formatColumns(Formater.START_NR, choice == 0 ? Formater.START_TIME : Formater.FINISH_TIME)); // setTitle("ENDURO - " + options[choice]); } else { } setSize(screenSize); }
public Gui(String output) { screenSize = Toolkit.getDefaultToolkit().getScreenSize(); bigFont = new Font("Times New Roman", Font.BOLD, screenSize.height / 7); setLayout(new BorderLayout()); controlNorthPanelSetUp(); textCentralPanelSetUp(); setTitle("ENDURO"); printer = new GuiPrinter(output); setDefaultCloseOperation(EXIT_ON_CLOSE); setResizable(false); setVisible(true); pack(); // if (!new File(output).exists()) { // Object[] options = { "Startstation", "Slutstation" }; // int choice = JOptionPane.showOptionDialog(this, // "Startstation eller slutstation?", "Stationsval", // JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, // null, options, options[0]); // printer.writeLine(Formater.formatColumns(Formater.START_NR, // choice == 0 ? Formater.START_TIME : Formater.FINISH_TIME)); // // setTitle("ENDURO - " + options[choice]); // } else { // } setSize(screenSize); }
diff --git a/UncodinCommon/src/in/uncod/android/media/widget/ImagePicker.java b/UncodinCommon/src/in/uncod/android/media/widget/ImagePicker.java index 417bae1..375eacd 100644 --- a/UncodinCommon/src/in/uncod/android/media/widget/ImagePicker.java +++ b/UncodinCommon/src/in/uncod/android/media/widget/ImagePicker.java @@ -1,244 +1,246 @@ package in.uncod.android.media.widget; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import android.widget.ImageView; import android.widget.ImageButton; import android.view.ViewGroup; import android.view.View.OnClickListener; import android.view.View; import android.view.LayoutInflater; import android.provider.MediaStore; import android.os.Environment; import android.os.Bundle; import android.net.Uri; import android.graphics.Bitmap; import android.content.Intent; import android.content.DialogInterface.OnCancelListener; import android.content.DialogInterface; import android.app.ProgressDialog; import android.app.Activity; import in.uncod.android.R; import in.uncod.android.graphics.BitmapManager; import in.uncod.android.media.widget.ImagePicker.ImagePickerListener.EditCancelCallback; /** * A simple image picker */ public class ImagePicker extends AbstractMediaPickerFragment implements OnClickListener { private static final int REQCODE_GET_IMAGE = 0; private static final int REQCODE_CAPTURE_IMAGE = 1; private ImageView mImageThumbnail; private ImageButton mCameraButton; private ImageButton mGalleryButton; private ImageButton mEditButton; private ImagePickerListener mImagePickerListener; private Bitmap tempBitmap = null; private File mTempDirectory; private static String mCurrentPhotoPath; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ViewGroup layoutRoot = (ViewGroup) inflater.inflate(R.layout.image_picker, container, false); mImageThumbnail = (ImageView) layoutRoot.findViewById(R.id.image_thumbnail); mCameraButton = (ImageButton) layoutRoot.findViewById(R.id.camera_button); mCameraButton.setOnClickListener(this); mGalleryButton = (ImageButton) layoutRoot.findViewById(R.id.gallery_button); mGalleryButton.setOnClickListener(this); mEditButton = (ImageButton) layoutRoot.findViewById(R.id.edit_button); mEditButton.setOnClickListener(this); mEditButton.setEnabled(false); + //If content was set before the fragments createView was called then update the content if (tempBitmap != null) { mImageThumbnail.setImageBitmap(tempBitmap); + mEditButton.setEnabled(true); tempBitmap = null; } if (savedInstanceState != null) { if (savedInstanceState.containsKey("image")) { mCurrentPhotoPath = savedInstanceState.getString("image"); } } return layoutRoot; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); mTempDirectory = getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putString("image", mCurrentPhotoPath); } @Override public void onClick(View v) { if (v == mGalleryButton) { launchImagePicker(); } else if (v == mCameraButton) { launchCameraPicker(); } else if (v == mEditButton) { // Create progress dialog final ProgressDialog dlg = ProgressDialog.show(getActivity(), getResources() .getResourceEntryName(R.string.loading), null, true); dlg.setCancelable(true); dlg.show(); mImagePickerListener.prepareForEdit(new ImageEditCancelCallback(dlg)); } } /** * Publishes an intent to get an image */ public void launchImagePicker() { Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); intent = Intent.createChooser(intent, "Select an image source"); startActivityForResult(intent, REQCODE_GET_IMAGE); } public void launchCameraPicker() { File file = null; try { file = createImageFile(); Intent intent = new Intent(); intent.setAction(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file)); intent = Intent.createChooser(intent, "Select an image source"); startActivityForResult(intent, REQCODE_CAPTURE_IMAGE); } catch (IOException e) { e.printStackTrace(); } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQCODE_CAPTURE_IMAGE) { if (resultCode == Activity.RESULT_OK) { Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE); Uri contentUri = Uri.parse("file://" + mCurrentPhotoPath); mediaScanIntent.setData(contentUri); getActivity().sendBroadcast(mediaScanIntent); new UpdateMedia().execute(contentUri); } } else { super.onActivityResult(requestCode, resultCode, data); } } private File createImageFile() throws IOException { // Create an image file name String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); String imageFileName = timeStamp + "_"; File image = File.createTempFile(imageFileName, ".jpg", mTempDirectory); mCurrentPhotoPath = image.getAbsolutePath(); return image; } @Override protected File mediaChanged(Uri mediaUri) { if (mImagePickerListener != null) { return mImagePickerListener.imageChanged(mediaUri); } return null; } @Override protected String getProgressTitle() { return "Loading Image"; } @Override public void updateMediaPreview(File mediaFile) { final Bitmap b = BitmapManager.loadBitmapScaled(mediaFile, 240); if (b != null && mImageThumbnail != null) { runOnUiThread(new Runnable() { @Override public void run() { mImageThumbnail.setImageBitmap(b); mEditButton.setEnabled(true); } }); } else { tempBitmap = b; } } public void setOnImageChangedListener(ImagePickerListener listener) { mImagePickerListener = listener; } private class ImageEditCancelCallback extends EditCancelCallback { private final ProgressDialog dlg; private boolean mCanceled = false; private ImageEditCancelCallback(ProgressDialog dlg) { this.dlg = dlg; if (dlg != null) { dlg.setOnCancelListener(new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { mCanceled = true; } }); } } public void cancel(boolean isCanceling) { if (dlg != null) { dlg.dismiss(); } if (!isCanceling && !mCanceled) { mImagePickerListener.launchEditor(); } else { mImagePickerListener.editingCanceled(); } } } public interface ImagePickerListener { public class EditCancelCallback { public void cancel(boolean isCancelling) { } } public File imageChanged(Uri imageUri); public void editingCanceled(); public void launchEditor(); public void prepareForEdit(EditCancelCallback callback); public File getCurrentImage(); } }
false
true
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ViewGroup layoutRoot = (ViewGroup) inflater.inflate(R.layout.image_picker, container, false); mImageThumbnail = (ImageView) layoutRoot.findViewById(R.id.image_thumbnail); mCameraButton = (ImageButton) layoutRoot.findViewById(R.id.camera_button); mCameraButton.setOnClickListener(this); mGalleryButton = (ImageButton) layoutRoot.findViewById(R.id.gallery_button); mGalleryButton.setOnClickListener(this); mEditButton = (ImageButton) layoutRoot.findViewById(R.id.edit_button); mEditButton.setOnClickListener(this); mEditButton.setEnabled(false); if (tempBitmap != null) { mImageThumbnail.setImageBitmap(tempBitmap); tempBitmap = null; } if (savedInstanceState != null) { if (savedInstanceState.containsKey("image")) { mCurrentPhotoPath = savedInstanceState.getString("image"); } } return layoutRoot; }
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ViewGroup layoutRoot = (ViewGroup) inflater.inflate(R.layout.image_picker, container, false); mImageThumbnail = (ImageView) layoutRoot.findViewById(R.id.image_thumbnail); mCameraButton = (ImageButton) layoutRoot.findViewById(R.id.camera_button); mCameraButton.setOnClickListener(this); mGalleryButton = (ImageButton) layoutRoot.findViewById(R.id.gallery_button); mGalleryButton.setOnClickListener(this); mEditButton = (ImageButton) layoutRoot.findViewById(R.id.edit_button); mEditButton.setOnClickListener(this); mEditButton.setEnabled(false); //If content was set before the fragments createView was called then update the content if (tempBitmap != null) { mImageThumbnail.setImageBitmap(tempBitmap); mEditButton.setEnabled(true); tempBitmap = null; } if (savedInstanceState != null) { if (savedInstanceState.containsKey("image")) { mCurrentPhotoPath = savedInstanceState.getString("image"); } } return layoutRoot; }
diff --git a/raven-log4j/src/test/java/net/kencochrane/raven/log4j/SentryAppenderNGTest.java b/raven-log4j/src/test/java/net/kencochrane/raven/log4j/SentryAppenderNGTest.java index 400212d3..fd0121c1 100644 --- a/raven-log4j/src/test/java/net/kencochrane/raven/log4j/SentryAppenderNGTest.java +++ b/raven-log4j/src/test/java/net/kencochrane/raven/log4j/SentryAppenderNGTest.java @@ -1,129 +1,129 @@ package net.kencochrane.raven.log4j; import com.google.common.base.Joiner; import mockit.Expectations; import mockit.Injectable; import mockit.Mocked; import mockit.Verifications; import net.kencochrane.raven.Raven; import net.kencochrane.raven.event.Event; import net.kencochrane.raven.event.EventBuilder; import net.kencochrane.raven.event.interfaces.ExceptionInterface; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.spi.LoggingEvent; import org.hamcrest.Matchers; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.util.Collections; import java.util.Date; import java.util.UUID; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; public class SentryAppenderNGTest { private SentryAppender sentryAppender; @Mocked private Raven mockRaven = null; @Injectable private Logger mockLogger = null; @BeforeMethod public void setUp() { sentryAppender = new SentryAppender(mockRaven); } @Test - public void testSimpleMesageLogging() throws Exception { + public void testSimpleMessageLogging() throws Exception { final String loggerName = UUID.randomUUID().toString(); final String message = UUID.randomUUID().toString(); final String threadName = UUID.randomUUID().toString(); final Date date = new Date(1373883196416L); new Expectations() {{ onInstance(mockLogger).getName(); result = loggerName; }}; sentryAppender.append(new LoggingEvent(null, mockLogger, date.getTime(), Level.INFO, message, threadName, null, null, null, null)); new Verifications() {{ Event event; mockRaven.runBuilderHelpers(withAny(new EventBuilder())); mockRaven.sendEvent(event = withCapture()); assertThat(event.getMessage(), is(message)); assertThat(event.getLogger(), is(loggerName)); assertThat(event.getExtra(), Matchers.<String, Object>hasEntry(SentryAppender.THREAD_NAME, threadName)); assertThat(event.getTimestamp(), is(date)); }}; } @Test public void testLevelConversion() throws Exception { assertLevelConverted(Event.Level.DEBUG, Level.TRACE); assertLevelConverted(Event.Level.DEBUG, Level.DEBUG); assertLevelConverted(Event.Level.INFO, Level.INFO); assertLevelConverted(Event.Level.WARNING, Level.WARN); assertLevelConverted(Event.Level.ERROR, Level.ERROR); assertLevelConverted(Event.Level.FATAL, Level.FATAL); } private void assertLevelConverted(final Event.Level expectedLevel, Level level) throws Exception { sentryAppender.append(new LoggingEvent(null, mockLogger, 0, level, null, null)); new Verifications() {{ Event event; mockRaven.sendEvent(event = withCapture()); assertThat(event.getLevel(), is(expectedLevel)); }}; } @Test public void testExceptionLogging() throws Exception { final Exception exception = new Exception(UUID.randomUUID().toString()); sentryAppender.append(new LoggingEvent(null, mockLogger, 0, Level.ERROR, null, exception)); new Verifications() {{ Event event; Throwable throwable; mockRaven.sendEvent(event = withCapture()); ExceptionInterface exceptionInterface = (ExceptionInterface) event.getSentryInterfaces() .get(ExceptionInterface.EXCEPTION_INTERFACE); throwable = exceptionInterface.getThrowable(); assertThat(throwable.getMessage(), is(exception.getMessage())); assertThat(throwable.getStackTrace(), is(exception.getStackTrace())); }}; } @Test public void testMdcAddedToExtra() throws Exception { final String extraKey = UUID.randomUUID().toString(); final String extraValue = UUID.randomUUID().toString(); sentryAppender.append(new LoggingEvent(null, mockLogger, 0, Level.ERROR, null, null, null, null, null, Collections.singletonMap(extraKey, extraValue))); new Verifications() {{ Event event; mockRaven.sendEvent(event = withCapture()); assertThat(event.getExtra(), Matchers.<String, Object>hasEntry(extraKey, extraValue)); }}; } @Test public void testNdcAddedToExtra() throws Exception { final String ndcEntries = Joiner.on(' ').join(UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID()); sentryAppender.append(new LoggingEvent(null, mockLogger, 0, Level.ERROR, null, null, null, ndcEntries, null, null)); new Verifications() {{ Event event; mockRaven.sendEvent(event = withCapture()); assertThat(event.getExtra(), Matchers.<String, Object>hasEntry(SentryAppender.LOG4J_NDC, ndcEntries)); }}; } }
true
true
public void testSimpleMesageLogging() throws Exception { final String loggerName = UUID.randomUUID().toString(); final String message = UUID.randomUUID().toString(); final String threadName = UUID.randomUUID().toString(); final Date date = new Date(1373883196416L); new Expectations() {{ onInstance(mockLogger).getName(); result = loggerName; }}; sentryAppender.append(new LoggingEvent(null, mockLogger, date.getTime(), Level.INFO, message, threadName, null, null, null, null)); new Verifications() {{ Event event; mockRaven.runBuilderHelpers(withAny(new EventBuilder())); mockRaven.sendEvent(event = withCapture()); assertThat(event.getMessage(), is(message)); assertThat(event.getLogger(), is(loggerName)); assertThat(event.getExtra(), Matchers.<String, Object>hasEntry(SentryAppender.THREAD_NAME, threadName)); assertThat(event.getTimestamp(), is(date)); }}; }
public void testSimpleMessageLogging() throws Exception { final String loggerName = UUID.randomUUID().toString(); final String message = UUID.randomUUID().toString(); final String threadName = UUID.randomUUID().toString(); final Date date = new Date(1373883196416L); new Expectations() {{ onInstance(mockLogger).getName(); result = loggerName; }}; sentryAppender.append(new LoggingEvent(null, mockLogger, date.getTime(), Level.INFO, message, threadName, null, null, null, null)); new Verifications() {{ Event event; mockRaven.runBuilderHelpers(withAny(new EventBuilder())); mockRaven.sendEvent(event = withCapture()); assertThat(event.getMessage(), is(message)); assertThat(event.getLogger(), is(loggerName)); assertThat(event.getExtra(), Matchers.<String, Object>hasEntry(SentryAppender.THREAD_NAME, threadName)); assertThat(event.getTimestamp(), is(date)); }}; }
diff --git a/src/org/hackystat/sensor/xmldata/XmlDataController.java b/src/org/hackystat/sensor/xmldata/XmlDataController.java index d98e399..5dccd68 100644 --- a/src/org/hackystat/sensor/xmldata/XmlDataController.java +++ b/src/org/hackystat/sensor/xmldata/XmlDataController.java @@ -1,172 +1,176 @@ package org.hackystat.sensor.xmldata; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.hackystat.sensor.xmldata.option.OptionFactory; import org.hackystat.sensor.xmldata.option.OptionHandler; import org.hackystat.sensorshell.SensorProperties; /** * The class which parses the command-line arguments specified by the user, * validates the created options and their parameters, and executes the options. * @author Austen Ito * */ public class XmlDataController { /** True if the verbose mode is on, false if verbose mode is turned off. */ private boolean isVerbose = false; /** The sensor data type name used by all data sent to the sensorbase. */ private String sdtName = ""; /** The class that manages the options created from the user's arguments. */ private OptionHandler optionHandler = null; /** The class which encapsulates the firing of messages. */ private MessageDelegate messageDelegate = null; /** The list of command-line arguments. */ private List<String> arguments = new ArrayList<String>(); /** True if all command-line arguments have been parsed correctly. */ private boolean hasParsed = true; /** * Constructs this controller with the classes that help manage the * command-line arguments and message capabilities. */ public XmlDataController() { this.optionHandler = new OptionHandler(this); this.messageDelegate = new MessageDelegate(this); } /** * This method parses the specified command-line arguments and creates * options, which can be validated and executed. */ private void processArguments() { Map<String, List<String>> optionToArgs = new HashMap<String, List<String>>(); String currentOption = ""; // Iterate through all -option <arguments>... pairings to build a mapping of // option -> arguments. for (String argument : this.arguments) { // If the current string is an option flag, create a new mapping. if (this.optionHandler.isOption(argument)) { if (optionToArgs.containsKey(argument)) { - String msg = "The option, " + argument + ", may not have duplicates."; - this.fireMessage(msg); + this.fireMessage("The option, " + argument + ", may not have duplicates."); this.hasParsed = false; break; } optionToArgs.put(argument, new ArrayList<String>()); currentOption = argument; } // Else, add the argument to the option flag list. else { List<String> args = optionToArgs.get(currentOption); + if (args == null) { + this.fireMessage("The argument, " + argument + ", is not supported."); + this.hasParsed = false; + break; + } args.add(argument); optionToArgs.put(currentOption, args); } } // Next, let's create the options using the command-line information. for (Entry<String, List<String>> entry : optionToArgs.entrySet()) { String optionName = entry.getKey(); List<String> optionParams = entry.getValue(); this.optionHandler.addOption(OptionFactory.getInstance(this, optionName, optionParams)); } // Finally, process the options, which may instance variables. this.optionHandler.processOptions(); } /** * Processes the command-line arguments and creates the objects that can be * executed. * @param arguments the specified list of command-line arguments. */ public void processArguments(List<String> arguments) { this.arguments = arguments; this.optionHandler.clearOptions(); this.processArguments(); } /** Executes all of the options specified by the user */ public void execute() { if (this.hasParsed && this.optionHandler.isOptionsValid() && this.optionHandler.hasRequiredOptions()) { this.optionHandler.execute(); } } /** * Displays the specified message. The same message is displayed even if the * verbose option is enabled. * @param message the specified message to display. */ public void fireMessage(String message) { this.messageDelegate.fireMessage(message); } /** * Displays the specified message if verbose mode is enabled. * @param message the specified message to display. */ public void fireVerboseMessage(String message) { this.messageDelegate.fireVerboseMessage(message); } /** * Displays the specified message is verbose mode is disabled or the verbose * message if verbose mode is enabled. * @param message the specified message. * @param verboseMessage the specified verbose message. */ public void fireMessage(String message, String verboseMessage) { this.messageDelegate.fireMessage(message, verboseMessage); } /** * Sets the sdt name specified by the user. If this sdt string is set, all * entries processed by this controller without an sdt attribute will use the * specified sdt string. * @param sdtName the specified sdt name. */ public void setSdtName(String sdtName) { this.sdtName = sdtName; } /** * Returns the sensor data type name that is associated with all data sent via * sensorshell to the sensorbase. * @return the sensor data type name. */ public String getSdtName() { return this.sdtName; } /** * Returns true if verbose mode is enabled, false if not. * @return true if verbose mode is on, false if not. */ public boolean isVerbose() { return this.isVerbose; } /** * Enables the verbosity of this controller if true, disables if false. * @param isVerbose true to enable verbose mode, false to disable. */ public void setVerbose(boolean isVerbose) { this.isVerbose = isVerbose; } /** * Returns the hackystat host stored in the sensor properties file. * @return the hackystat host string. */ public String getHost() { SensorProperties properties = new SensorProperties(); return properties.getHackystatHost(); } }
false
true
private void processArguments() { Map<String, List<String>> optionToArgs = new HashMap<String, List<String>>(); String currentOption = ""; // Iterate through all -option <arguments>... pairings to build a mapping of // option -> arguments. for (String argument : this.arguments) { // If the current string is an option flag, create a new mapping. if (this.optionHandler.isOption(argument)) { if (optionToArgs.containsKey(argument)) { String msg = "The option, " + argument + ", may not have duplicates."; this.fireMessage(msg); this.hasParsed = false; break; } optionToArgs.put(argument, new ArrayList<String>()); currentOption = argument; } // Else, add the argument to the option flag list. else { List<String> args = optionToArgs.get(currentOption); args.add(argument); optionToArgs.put(currentOption, args); } } // Next, let's create the options using the command-line information. for (Entry<String, List<String>> entry : optionToArgs.entrySet()) { String optionName = entry.getKey(); List<String> optionParams = entry.getValue(); this.optionHandler.addOption(OptionFactory.getInstance(this, optionName, optionParams)); } // Finally, process the options, which may instance variables. this.optionHandler.processOptions(); }
private void processArguments() { Map<String, List<String>> optionToArgs = new HashMap<String, List<String>>(); String currentOption = ""; // Iterate through all -option <arguments>... pairings to build a mapping of // option -> arguments. for (String argument : this.arguments) { // If the current string is an option flag, create a new mapping. if (this.optionHandler.isOption(argument)) { if (optionToArgs.containsKey(argument)) { this.fireMessage("The option, " + argument + ", may not have duplicates."); this.hasParsed = false; break; } optionToArgs.put(argument, new ArrayList<String>()); currentOption = argument; } // Else, add the argument to the option flag list. else { List<String> args = optionToArgs.get(currentOption); if (args == null) { this.fireMessage("The argument, " + argument + ", is not supported."); this.hasParsed = false; break; } args.add(argument); optionToArgs.put(currentOption, args); } } // Next, let's create the options using the command-line information. for (Entry<String, List<String>> entry : optionToArgs.entrySet()) { String optionName = entry.getKey(); List<String> optionParams = entry.getValue(); this.optionHandler.addOption(OptionFactory.getInstance(this, optionName, optionParams)); } // Finally, process the options, which may instance variables. this.optionHandler.processOptions(); }
diff --git a/atlas-utils/src/main/java/uk/ac/ebi/gxa/utils/NumberFormatUtil.java b/atlas-utils/src/main/java/uk/ac/ebi/gxa/utils/NumberFormatUtil.java index 152a392d7..e570e4956 100644 --- a/atlas-utils/src/main/java/uk/ac/ebi/gxa/utils/NumberFormatUtil.java +++ b/atlas-utils/src/main/java/uk/ac/ebi/gxa/utils/NumberFormatUtil.java @@ -1,53 +1,53 @@ package uk.ac.ebi.gxa.utils; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Number format utilities * * @author rpetry */ public class NumberFormatUtil { // P-values with exponents less than MIN_EXPONENT are shown as '< 10 <sup>-10</sup>' private static final Integer MIN_EXPONENT = -10; private static final String LESS_THAN = "< "; private static final String E = "E"; private static final String ZERO = "0"; private static final String TEN = "10"; private static final String MULTIPLY_HTML_CODE = " &#0215 "; private static final String E_PATTERN = "#.##" + E + ZERO; private static final String SUP_PRE = "<span style=\"vertical-align: super;\">"; private static final String SUP_POST = "</span>"; /** * @param number P-value * @return number, formatted as 'mantissa ? 10<sup>exponent</sup>' (and '0' when mantissa == 0) * N.B. P-values with exponents less than MIN_EXPONENT are shown as '< 10 <sup>-10</sup>' */ public static String prettyFloatFormat(Float number) { DecimalFormat df = new DecimalFormat(E_PATTERN); // Examples values of auxFormat: 6.2E-3, 0E0 String auxFormat = df.format((double) number); // We now convert this format to 6.2*10<sup>-3</sup> (and 0 in the case of 0E0 specifically) List<String> formatParts = new ArrayList<String>(Arrays.asList(auxFormat.split(E))); String mantissa = formatParts.get(0); // in 6.2E-3, mantissa = 6.2 Integer exponent = Integer.parseInt(formatParts.get(1)); // // in 6.2E-3, exponent= -3 String pre = mantissa + MULTIPLY_HTML_CODE; // e.g 6.2 * 10 - if (mantissa.equals(ZERO) && exponent.equals(ZERO)) { + if (mantissa.equals(ZERO) && exponent == 0) { // if the auxFormat == '0E0' return ZERO; } else if (exponent < MIN_EXPONENT) { // if number < 10E-10, forget its mantissa and show it simply as '< 10<sup>-10</sup>' pre = LESS_THAN; exponent = MIN_EXPONENT; } return pre + TEN + SUP_PRE + exponent + SUP_POST; } }
true
true
public static String prettyFloatFormat(Float number) { DecimalFormat df = new DecimalFormat(E_PATTERN); // Examples values of auxFormat: 6.2E-3, 0E0 String auxFormat = df.format((double) number); // We now convert this format to 6.2*10<sup>-3</sup> (and 0 in the case of 0E0 specifically) List<String> formatParts = new ArrayList<String>(Arrays.asList(auxFormat.split(E))); String mantissa = formatParts.get(0); // in 6.2E-3, mantissa = 6.2 Integer exponent = Integer.parseInt(formatParts.get(1)); // // in 6.2E-3, exponent= -3 String pre = mantissa + MULTIPLY_HTML_CODE; // e.g 6.2 * 10 if (mantissa.equals(ZERO) && exponent.equals(ZERO)) { // if the auxFormat == '0E0' return ZERO; } else if (exponent < MIN_EXPONENT) { // if number < 10E-10, forget its mantissa and show it simply as '< 10<sup>-10</sup>' pre = LESS_THAN; exponent = MIN_EXPONENT; } return pre + TEN + SUP_PRE + exponent + SUP_POST; }
public static String prettyFloatFormat(Float number) { DecimalFormat df = new DecimalFormat(E_PATTERN); // Examples values of auxFormat: 6.2E-3, 0E0 String auxFormat = df.format((double) number); // We now convert this format to 6.2*10<sup>-3</sup> (and 0 in the case of 0E0 specifically) List<String> formatParts = new ArrayList<String>(Arrays.asList(auxFormat.split(E))); String mantissa = formatParts.get(0); // in 6.2E-3, mantissa = 6.2 Integer exponent = Integer.parseInt(formatParts.get(1)); // // in 6.2E-3, exponent= -3 String pre = mantissa + MULTIPLY_HTML_CODE; // e.g 6.2 * 10 if (mantissa.equals(ZERO) && exponent == 0) { // if the auxFormat == '0E0' return ZERO; } else if (exponent < MIN_EXPONENT) { // if number < 10E-10, forget its mantissa and show it simply as '< 10<sup>-10</sup>' pre = LESS_THAN; exponent = MIN_EXPONENT; } return pre + TEN + SUP_PRE + exponent + SUP_POST; }
diff --git a/src/com/redhat/ceylon/compiler/tools/LanguageCompiler.java b/src/com/redhat/ceylon/compiler/tools/LanguageCompiler.java index 7df206d70..59454a5f9 100755 --- a/src/com/redhat/ceylon/compiler/tools/LanguageCompiler.java +++ b/src/com/redhat/ceylon/compiler/tools/LanguageCompiler.java @@ -1,322 +1,322 @@ /* * Copyright (c) 1999, 2006, Oracle and/or its affiliates. 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. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.redhat.ceylon.compiler.tools; import java.io.File; import java.io.IOException; import java.util.Queue; import javax.tools.JavaFileObject; import org.antlr.runtime.ANTLRStringStream; import org.antlr.runtime.CommonTokenStream; import org.antlr.runtime.tree.CommonTree; import com.redhat.ceylon.compiler.codegen.CeylonEnter; import com.redhat.ceylon.compiler.codegen.CeylonFileObject; import com.redhat.ceylon.compiler.codegen.CeylonModelLoader; import com.redhat.ceylon.compiler.codegen.Gen2; import com.redhat.ceylon.compiler.typechecker.analyzer.ModuleBuilder; import com.redhat.ceylon.compiler.typechecker.context.PhasedUnit; import com.redhat.ceylon.compiler.typechecker.context.PhasedUnits; import com.redhat.ceylon.compiler.typechecker.io.VFS; import com.redhat.ceylon.compiler.typechecker.io.VirtualFile; import com.redhat.ceylon.compiler.typechecker.parser.CeylonLexer; import com.redhat.ceylon.compiler.typechecker.parser.CeylonParser; import com.redhat.ceylon.compiler.typechecker.parser.LexError; import com.redhat.ceylon.compiler.typechecker.parser.ParseError; import com.redhat.ceylon.compiler.typechecker.parser.RecognitionError; import com.redhat.ceylon.compiler.typechecker.tree.Builder; import com.redhat.ceylon.compiler.typechecker.tree.CustomBuilder; import com.redhat.ceylon.compiler.typechecker.tree.Tree.CompilationUnit; import com.sun.tools.javac.comp.AttrContext; import com.sun.tools.javac.comp.Env; import com.sun.tools.javac.main.JavaCompiler; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.JCTree.JCAnnotation; import com.sun.tools.javac.tree.JCTree.JCClassDecl; import com.sun.tools.javac.tree.JCTree.JCCompilationUnit; import com.sun.tools.javac.util.Context; import com.sun.tools.javac.util.Context.SourceLanguage.Language; import com.sun.tools.javac.util.Convert; import com.sun.tools.javac.util.List; import com.sun.tools.javac.util.Options; import com.sun.tools.javac.util.Pair; import com.sun.tools.javac.util.Position; import com.sun.tools.javac.util.Position.LineMap; public class LanguageCompiler extends JavaCompiler { /** The context key for the phasedUnits. */ protected static final Context.Key<PhasedUnits> phasedUnitsKey = new Context.Key<PhasedUnits>(); /** The context key for the ceylon context. */ protected static final Context.Key<com.redhat.ceylon.compiler.typechecker.context.Context> ceylonContextKey = new Context.Key<com.redhat.ceylon.compiler.typechecker.context.Context>(); private final Gen2 gen; private final PhasedUnits phasedUnits; private final com.redhat.ceylon.compiler.typechecker.context.Context ceylonContext; private final VFS vfs; private CeylonModelLoader modelLoader; /** Get the PhasedUnits instance for this context. */ public static PhasedUnits getPhasedUnitsInstance(Context context) { PhasedUnits phasedUnits = context.get(phasedUnitsKey); if (phasedUnits == null) { phasedUnits = new PhasedUnits(getCeylonContextInstance(context)); context.put(phasedUnitsKey, phasedUnits); } return phasedUnits; } /** Get the Ceylon context instance for this context. */ public static com.redhat.ceylon.compiler.typechecker.context.Context getCeylonContextInstance(Context context) { com.redhat.ceylon.compiler.typechecker.context.Context ceylonContext = context.get(ceylonContextKey); if (ceylonContext == null) { ceylonContext = new com.redhat.ceylon.compiler.typechecker.context.Context(new VFS()); context.put(ceylonContextKey, ceylonContext); } return ceylonContext; } /** Get the JavaCompiler instance for this context. */ public static JavaCompiler instance(Context context) { Options options = Options.instance(context); options.put("-Xprefer", "source"); // make sure it's registered CeylonEnter.instance(context); JavaCompiler instance = context.get(compilerKey); if (instance == null) instance = new LanguageCompiler(context); return instance; } public LanguageCompiler(Context context) { super(context); ceylonContext = getCeylonContextInstance(context); vfs = ceylonContext.getVfs(); phasedUnits = getPhasedUnitsInstance(context); try { gen = Gen2.getInstance(context); } catch (Exception e) { throw new RuntimeException(e); } modelLoader = CeylonModelLoader.instance(context); } /** * Parse contents of file. * @param filename The name of the file to be parsed. */ public JCTree.JCCompilationUnit parse(JavaFileObject filename) { JavaFileObject prev = log.useSource(filename); try { JCTree.JCCompilationUnit t; if (filename.getName().endsWith(".java")) { t = parse(filename, readSource(filename)); } else { t = ceylonParse(filename, readSource(filename)); } if (t.endPositions != null) log.setEndPosTable(filename, t.endPositions); return t; } finally { log.useSource(prev); } } protected JCCompilationUnit parse(JavaFileObject filename, CharSequence readSource) { // FIXME if (filename instanceof CeylonFileObject) return ceylonParse(filename, readSource); else return super.parse(filename, readSource); } private JCCompilationUnit ceylonParse(JavaFileObject filename, CharSequence readSource) { try { String source = readSource.toString(); ANTLRStringStream input = new ANTLRStringStream(source); CeylonLexer lexer = new CeylonLexer(input); CommonTokenStream tokens = new CommonTokenStream(lexer); CeylonParser parser = new CeylonParser(tokens); CeylonParser.compilationUnit_return r = parser.compilationUnit(); char[] chars = source.toCharArray(); LineMap map = Position.makeLineMap(chars, chars.length, false); java.util.List<LexError> lexerErrors = lexer.getErrors(); for (LexError le : lexerErrors) { printError(le, le.getMessage(lexer), chars, map); } java.util.List<ParseError> parserErrors = parser.getErrors(); for (ParseError pe : parserErrors) { printError(pe, pe.getMessage(parser), chars, map); } CommonTree t = (CommonTree) r.getTree(); if (lexer.getNumberOfSyntaxErrors() != 0) { log.error("ceylon.lexer.failed"); } else if (parser.getNumberOfSyntaxErrors() != 0) { log.error("ceylon.parser.failed"); } else { Builder builder = new CustomBuilder(); CompilationUnit cu = builder.buildCompilationUnit(t); ModuleBuilder moduleBuilder = phasedUnits.getModuleBuilder(); File sourceFile = new File(filename.toString()); // FIXME: temporary solution VirtualFile file = vfs.getFromFile(sourceFile); VirtualFile srcDir = vfs.getFromFile(getSrcDir(sourceFile)); // FIXME: this is bad in many ways String pkgName = getPackage(filename); - com.redhat.ceylon.compiler.typechecker.model.Package p = modelLoader.findOrCreatePackage(modelLoader.findOrCreateModule(pkgName), pkgName); + com.redhat.ceylon.compiler.typechecker.model.Package p = modelLoader.findOrCreatePackage(modelLoader.findOrCreateModule(pkgName), pkgName == null ? "" : pkgName); PhasedUnit phasedUnit = new PhasedUnit(file, srcDir, cu, p, moduleBuilder, ceylonContext); phasedUnits.addPhasedUnit(file, phasedUnit); gen.setMap(map); return gen.makeJCCompilationUnitPlaceholder(cu, filename, pkgName); } } catch (Exception e) { throw new RuntimeException(e); } JCCompilationUnit result = make.TopLevel(List.<JCAnnotation> nil(), null, List.<JCTree> of(make.Erroneous())); result.sourcefile = filename; return result; } // FIXME: this function is terrible, possibly refactor it with getPackage? private File getSrcDir(File sourceFile) { String name; try { name = sourceFile.getCanonicalPath(); } catch (IOException e) { // FIXME throw new RuntimeException(e); } String[] prefixes = ((CeyloncFileManager) fileManager).getSourcePath(); System.err.println("Prefixes: " + prefixes.length + " name: " + name); for (String prefix : prefixes) { if (prefix != null) { File prefixFile = new File(prefix); String path; try { path = prefixFile.getCanonicalPath(); } catch (IOException e) { // FIXME throw new RuntimeException(e); } System.err.println("Prefix: " + path); if (name.startsWith(path)) { return prefixFile; } } } throw new RuntimeException("Failed to find source prefix for " + name); } private String getPackage(JavaFileObject file){ String[] prefixes = ((CeyloncFileManager) fileManager).getSourcePath(); // Figure out the package name by stripping the "-src" prefix and // extracting // the package part of the fullname. for (String prefix : prefixes) { if (prefix != null && file.toString().startsWith(prefix)) { String fullname = file.toString().substring(prefix.length()); assert fullname.endsWith(".ceylon"); fullname = fullname.substring(0, fullname.length() - ".ceylon".length()); fullname = fullname.replace(File.separator, "."); if(fullname.startsWith(".")) fullname = fullname.substring(1); String packageName = Convert.packagePart(fullname); if (!packageName.equals("")) return packageName; } } return null; } private void printError(RecognitionError le, String message, char[] chars, LineMap map) { int lineStart = map.getStartPosition(le.getLine()); int lineEnd = lineStart; // find the end of the line for (; lineEnd < chars.length && chars[lineEnd] != '\n' && chars[lineEnd] != '\r'; lineEnd++) ; String line = new String(chars, lineStart, lineEnd - lineStart); System.out.println(message); System.out.println("Near:"); System.out.println(line); for (int i = 0; i < le.getCharacterInLine(); i++) System.out.print('-'); System.out.println('^'); } public Env<AttrContext> attribute(Env<AttrContext> env) { if (env.toplevel.sourcefile instanceof CeylonFileObject) { try { Context.SourceLanguage.push(Language.CEYLON); return super.attribute(env); } finally { Context.SourceLanguage.pop(); } } return super.attribute(env); } protected JavaFileObject genCode(Env<AttrContext> env, JCClassDecl cdef) throws IOException { if (env.toplevel.sourcefile instanceof CeylonFileObject) { try { Context.SourceLanguage.push(Language.CEYLON); return super.genCode(env, cdef); } finally { Context.SourceLanguage.pop(); } } return super.genCode(env, cdef); } protected void desugar(final Env<AttrContext> env, Queue<Pair<Env<AttrContext>, JCClassDecl>> results) { if (env.toplevel.sourcefile instanceof CeylonFileObject) { try { Context.SourceLanguage.push(Language.CEYLON); super.desugar(env, results); return; } finally { Context.SourceLanguage.pop(); } } super.desugar(env, results); } }
true
true
private JCCompilationUnit ceylonParse(JavaFileObject filename, CharSequence readSource) { try { String source = readSource.toString(); ANTLRStringStream input = new ANTLRStringStream(source); CeylonLexer lexer = new CeylonLexer(input); CommonTokenStream tokens = new CommonTokenStream(lexer); CeylonParser parser = new CeylonParser(tokens); CeylonParser.compilationUnit_return r = parser.compilationUnit(); char[] chars = source.toCharArray(); LineMap map = Position.makeLineMap(chars, chars.length, false); java.util.List<LexError> lexerErrors = lexer.getErrors(); for (LexError le : lexerErrors) { printError(le, le.getMessage(lexer), chars, map); } java.util.List<ParseError> parserErrors = parser.getErrors(); for (ParseError pe : parserErrors) { printError(pe, pe.getMessage(parser), chars, map); } CommonTree t = (CommonTree) r.getTree(); if (lexer.getNumberOfSyntaxErrors() != 0) { log.error("ceylon.lexer.failed"); } else if (parser.getNumberOfSyntaxErrors() != 0) { log.error("ceylon.parser.failed"); } else { Builder builder = new CustomBuilder(); CompilationUnit cu = builder.buildCompilationUnit(t); ModuleBuilder moduleBuilder = phasedUnits.getModuleBuilder(); File sourceFile = new File(filename.toString()); // FIXME: temporary solution VirtualFile file = vfs.getFromFile(sourceFile); VirtualFile srcDir = vfs.getFromFile(getSrcDir(sourceFile)); // FIXME: this is bad in many ways String pkgName = getPackage(filename); com.redhat.ceylon.compiler.typechecker.model.Package p = modelLoader.findOrCreatePackage(modelLoader.findOrCreateModule(pkgName), pkgName); PhasedUnit phasedUnit = new PhasedUnit(file, srcDir, cu, p, moduleBuilder, ceylonContext); phasedUnits.addPhasedUnit(file, phasedUnit); gen.setMap(map); return gen.makeJCCompilationUnitPlaceholder(cu, filename, pkgName); } } catch (Exception e) { throw new RuntimeException(e); } JCCompilationUnit result = make.TopLevel(List.<JCAnnotation> nil(), null, List.<JCTree> of(make.Erroneous())); result.sourcefile = filename; return result; }
private JCCompilationUnit ceylonParse(JavaFileObject filename, CharSequence readSource) { try { String source = readSource.toString(); ANTLRStringStream input = new ANTLRStringStream(source); CeylonLexer lexer = new CeylonLexer(input); CommonTokenStream tokens = new CommonTokenStream(lexer); CeylonParser parser = new CeylonParser(tokens); CeylonParser.compilationUnit_return r = parser.compilationUnit(); char[] chars = source.toCharArray(); LineMap map = Position.makeLineMap(chars, chars.length, false); java.util.List<LexError> lexerErrors = lexer.getErrors(); for (LexError le : lexerErrors) { printError(le, le.getMessage(lexer), chars, map); } java.util.List<ParseError> parserErrors = parser.getErrors(); for (ParseError pe : parserErrors) { printError(pe, pe.getMessage(parser), chars, map); } CommonTree t = (CommonTree) r.getTree(); if (lexer.getNumberOfSyntaxErrors() != 0) { log.error("ceylon.lexer.failed"); } else if (parser.getNumberOfSyntaxErrors() != 0) { log.error("ceylon.parser.failed"); } else { Builder builder = new CustomBuilder(); CompilationUnit cu = builder.buildCompilationUnit(t); ModuleBuilder moduleBuilder = phasedUnits.getModuleBuilder(); File sourceFile = new File(filename.toString()); // FIXME: temporary solution VirtualFile file = vfs.getFromFile(sourceFile); VirtualFile srcDir = vfs.getFromFile(getSrcDir(sourceFile)); // FIXME: this is bad in many ways String pkgName = getPackage(filename); com.redhat.ceylon.compiler.typechecker.model.Package p = modelLoader.findOrCreatePackage(modelLoader.findOrCreateModule(pkgName), pkgName == null ? "" : pkgName); PhasedUnit phasedUnit = new PhasedUnit(file, srcDir, cu, p, moduleBuilder, ceylonContext); phasedUnits.addPhasedUnit(file, phasedUnit); gen.setMap(map); return gen.makeJCCompilationUnitPlaceholder(cu, filename, pkgName); } } catch (Exception e) { throw new RuntimeException(e); } JCCompilationUnit result = make.TopLevel(List.<JCAnnotation> nil(), null, List.<JCTree> of(make.Erroneous())); result.sourcefile = filename; return result; }
diff --git a/src/com/github/bjarneh/simple/mime/Content.java b/src/com/github/bjarneh/simple/mime/Content.java index b20516f..2d9f567 100644 --- a/src/com/github/bjarneh/simple/mime/Content.java +++ b/src/com/github/bjarneh/simple/mime/Content.java @@ -1,98 +1,98 @@ // Copyright © 2012 bjarneh // // 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.github.bjarneh.simple.mime; import java.net.URL; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.charset.Charset; import java.util.HashMap; import java.util.Scanner; import com.github.bjarneh.utilz.Handy; /** * Returns MIME types based on file endings. * * @author [email protected] * @version 1.0 */ public class Content{ HashMap<String, String> mapping; String defaultCharset = "utf-8"; public Content() throws IOException { mapping = new HashMap<String, String>(); defaultCharset = Charset.defaultCharset().displayName(); load(); } private void load() throws IOException { String path = Handy.fromSlash("resources/txt/mime.types"); URL url = getClass().getClassLoader().getResource(path); Scanner scanner = new Scanner(url.openStream()); String line; String[] tokens; while( scanner.hasNextLine() ){ line = scanner.nextLine(); line = line.replaceFirst("#.*", "").trim(); tokens = line.split("\\s+"); if( tokens.length > 1 ){ if( tokens[0].startsWith("text/") ){ - tokens[0] = tokens[0] +";charset" + defaultCharset; + tokens[0] = tokens[0] +";charset=" + defaultCharset; } for(int i = 1; i < tokens.length; i++){ mapping.put(tokens[i], tokens[0]); } } } scanner.close(); } /** * Find mime type based on file ending. * * @param path the path to a file * @return a fitting mimetype for path name */ public String type(String path){ String mimetype = null; String suf = Handy.suffix(path); if( suf != null ){ mimetype = mapping.get(suf); } return (mimetype != null)? mimetype : "application/octet-stream"; } /** * Find mime type based on file ending. * * @param file the File object used * @return a fitting mimetype for file (based on file ending) */ public String type(File file){ return type(file.getName()); } }
true
true
private void load() throws IOException { String path = Handy.fromSlash("resources/txt/mime.types"); URL url = getClass().getClassLoader().getResource(path); Scanner scanner = new Scanner(url.openStream()); String line; String[] tokens; while( scanner.hasNextLine() ){ line = scanner.nextLine(); line = line.replaceFirst("#.*", "").trim(); tokens = line.split("\\s+"); if( tokens.length > 1 ){ if( tokens[0].startsWith("text/") ){ tokens[0] = tokens[0] +";charset" + defaultCharset; } for(int i = 1; i < tokens.length; i++){ mapping.put(tokens[i], tokens[0]); } } } scanner.close(); }
private void load() throws IOException { String path = Handy.fromSlash("resources/txt/mime.types"); URL url = getClass().getClassLoader().getResource(path); Scanner scanner = new Scanner(url.openStream()); String line; String[] tokens; while( scanner.hasNextLine() ){ line = scanner.nextLine(); line = line.replaceFirst("#.*", "").trim(); tokens = line.split("\\s+"); if( tokens.length > 1 ){ if( tokens[0].startsWith("text/") ){ tokens[0] = tokens[0] +";charset=" + defaultCharset; } for(int i = 1; i < tokens.length; i++){ mapping.put(tokens[i], tokens[0]); } } } scanner.close(); }
diff --git a/mydlp-ui-dao/src/main/java/com/mydlp/ui/dao/RevisionDAOImpl.java b/mydlp-ui-dao/src/main/java/com/mydlp/ui/dao/RevisionDAOImpl.java index d256dc14..5a441562 100644 --- a/mydlp-ui-dao/src/main/java/com/mydlp/ui/dao/RevisionDAOImpl.java +++ b/mydlp-ui-dao/src/main/java/com/mydlp/ui/dao/RevisionDAOImpl.java @@ -1,82 +1,82 @@ package com.mydlp.ui.dao; import java.util.List; import org.hibernate.criterion.DetachedCriteria; import org.hibernate.criterion.Order; import org.hibernate.criterion.Projections; import org.hibernate.criterion.Restrictions; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import com.mydlp.ui.domain.Revision; @Repository("revisionDAO") @Transactional public class RevisionDAOImpl extends AbstractPolicyDAO implements RevisionDAO { @SuppressWarnings("unchecked") @Override public List<Revision> getRevisions(Integer offset, Integer limit) { DetachedCriteria criteria = DetachedCriteria.forClass(Revision.class) .addOrder(Order.desc("id")); return criteria.getExecutableCriteria(getSession()) .setFirstResult(offset) .setMaxResults(limit) .list(); } @Override public Long getRevisionCount() { DetachedCriteria criteria = DetachedCriteria.forClass(Revision.class) .setProjection(Projections.rowCount()); @SuppressWarnings("unchecked") List<Long> returnList = getHibernateTemplate().findByCriteria(criteria); return DAOUtil.getSingleResult(returnList); } @SuppressWarnings("unchecked") @Override public List<Revision> getNamedRevisions(Integer offset, Integer limit) { DetachedCriteria criteria = DetachedCriteria.forClass(Revision.class) .add(Restrictions.isNotNull("name")) .addOrder(Order.desc("id")); return criteria.getExecutableCriteria(getSession()) .setFirstResult(offset) .setMaxResults(limit) .list(); } @Override public Long getNamedRevisionCount() { DetachedCriteria criteria = DetachedCriteria.forClass(Revision.class) .setProjection(Projections.rowCount()) .add(Restrictions.isNotNull("name")); @SuppressWarnings("unchecked") List<Long> returnList = getHibernateTemplate().findByCriteria(criteria); return DAOUtil.getSingleResult(returnList); } @Override public void save(Revision revision) { getHibernateTemplate().saveOrUpdate(revision); } @Override public Long getRevisionIndex(Revision revision) { if (revision == null || revision.getId() == null) return 0L; DetachedCriteria criteria = DetachedCriteria.forClass(Revision.class) .addOrder(Order.desc("id")); @SuppressWarnings("unchecked") - Revision firstRevision = DAOUtil.getSingleResult(criteria.getExecutableCriteria(getSession()) + Revision firstRevision = (Revision) DAOUtil.getSingleResult(criteria.getExecutableCriteria(getSession()) .setMaxResults(1) .list()); return new Long(firstRevision.getId() - revision.getId()); } }
true
true
public Long getRevisionIndex(Revision revision) { if (revision == null || revision.getId() == null) return 0L; DetachedCriteria criteria = DetachedCriteria.forClass(Revision.class) .addOrder(Order.desc("id")); @SuppressWarnings("unchecked") Revision firstRevision = DAOUtil.getSingleResult(criteria.getExecutableCriteria(getSession()) .setMaxResults(1) .list()); return new Long(firstRevision.getId() - revision.getId()); }
public Long getRevisionIndex(Revision revision) { if (revision == null || revision.getId() == null) return 0L; DetachedCriteria criteria = DetachedCriteria.forClass(Revision.class) .addOrder(Order.desc("id")); @SuppressWarnings("unchecked") Revision firstRevision = (Revision) DAOUtil.getSingleResult(criteria.getExecutableCriteria(getSession()) .setMaxResults(1) .list()); return new Long(firstRevision.getId() - revision.getId()); }
diff --git a/src/test/java/endtoend/AuctionSniperEndToEndITCase.java b/src/test/java/endtoend/AuctionSniperEndToEndITCase.java index 3c9624b..7262ac2 100644 --- a/src/test/java/endtoend/AuctionSniperEndToEndITCase.java +++ b/src/test/java/endtoend/AuctionSniperEndToEndITCase.java @@ -1,93 +1,93 @@ package endtoend; import org.junit.After; import org.junit.Test; public class AuctionSniperEndToEndITCase { private final FakeAuctionServer auction = new FakeAuctionServer("item-54321"); private final FakeAuctionServer auction2 = new FakeAuctionServer("item-65432"); private final ApplicationRunner application = new ApplicationRunner(); @Test public void sniperJoinAuctionUntilAuctionCloses() throws Exception { auction.startSellingItem(); application.startBiddingIn(auction); auction.hasReceivedJoinRequestFrom(ApplicationRunner.SNIPER_XMPP_ID); auction.announceClosed(); application.showsSniperHasLostAuction(auction, 0, 0); } @Test public void sniperMakesAHigherBidButLoses() throws Exception{ auction.startSellingItem(); application.startBiddingIn(auction); auction.hasReceivedJoinRequestFrom(ApplicationRunner.SNIPER_XMPP_ID); auction.reportPrice(1000, 98, "other bidder"); application.hasShownSniperIsBidding(auction, 1000, 1098); //last price, last bid auction.hasReceivedBid(1098, ApplicationRunner.SNIPER_XMPP_ID); auction.announceClosed(); application.showsSniperHasLostAuction(auction, 1000, 1098); } @Test public void sniperWinsAnAuctionByBiddingHigher() throws Exception{ auction.startSellingItem(); application.startBiddingIn(auction); auction.hasReceivedJoinRequestFrom(ApplicationRunner.SNIPER_XMPP_ID); auction.reportPrice(1000, 98, "other bidder"); application.hasShownSniperIsBidding(auction, 1000, 1098); //last price, last bid auction.hasReceivedBid(1098, ApplicationRunner.SNIPER_XMPP_ID); auction.reportPrice(1098, 97, ApplicationRunner.SNIPER_XMPP_ID); application.hasShownSniperIsWinning(auction, 1098); //winning bid auction.announceClosed(); application.showsSniperHasWonAuction(auction, 1098); //last price } @Test public void sniperBidsForMultipleItems() throws Exception{ auction.startSellingItem(); auction2.startSellingItem(); application.startBiddingIn(auction, auction2); auction.hasReceivedJoinRequestFrom(ApplicationRunner.SNIPER_XMPP_ID); auction2.hasReceivedJoinRequestFrom(ApplicationRunner.SNIPER_XMPP_ID); auction.reportPrice(1000, 98, "other bidder"); auction.hasReceivedBid(1098, ApplicationRunner.SNIPER_XMPP_ID); auction2.reportPrice(500, 21, "other bidder"); auction2.hasReceivedBid(521, ApplicationRunner.SNIPER_XMPP_ID); auction.reportPrice(1098, 97, ApplicationRunner.SNIPER_XMPP_ID); - auction.reportPrice(521, 22, ApplicationRunner.SNIPER_XMPP_ID); + auction2.reportPrice(521, 22, ApplicationRunner.SNIPER_XMPP_ID); application.hasShownSniperIsWinning(auction, 1098); //winning bid application.hasShownSniperIsWinning(auction2, 521); //winning bid auction.announceClosed(); auction2.announceClosed(); application.showsSniperHasWonAuction(auction, 1098); //last price application.showsSniperHasWonAuction(auction2, 521); //last price } @After public void stopAuction(){ auction.stop(); auction2.stop(); } @After public void stopApplication(){ application.stop(); } }
true
true
public void sniperBidsForMultipleItems() throws Exception{ auction.startSellingItem(); auction2.startSellingItem(); application.startBiddingIn(auction, auction2); auction.hasReceivedJoinRequestFrom(ApplicationRunner.SNIPER_XMPP_ID); auction2.hasReceivedJoinRequestFrom(ApplicationRunner.SNIPER_XMPP_ID); auction.reportPrice(1000, 98, "other bidder"); auction.hasReceivedBid(1098, ApplicationRunner.SNIPER_XMPP_ID); auction2.reportPrice(500, 21, "other bidder"); auction2.hasReceivedBid(521, ApplicationRunner.SNIPER_XMPP_ID); auction.reportPrice(1098, 97, ApplicationRunner.SNIPER_XMPP_ID); auction.reportPrice(521, 22, ApplicationRunner.SNIPER_XMPP_ID); application.hasShownSniperIsWinning(auction, 1098); //winning bid application.hasShownSniperIsWinning(auction2, 521); //winning bid auction.announceClosed(); auction2.announceClosed(); application.showsSniperHasWonAuction(auction, 1098); //last price application.showsSniperHasWonAuction(auction2, 521); //last price }
public void sniperBidsForMultipleItems() throws Exception{ auction.startSellingItem(); auction2.startSellingItem(); application.startBiddingIn(auction, auction2); auction.hasReceivedJoinRequestFrom(ApplicationRunner.SNIPER_XMPP_ID); auction2.hasReceivedJoinRequestFrom(ApplicationRunner.SNIPER_XMPP_ID); auction.reportPrice(1000, 98, "other bidder"); auction.hasReceivedBid(1098, ApplicationRunner.SNIPER_XMPP_ID); auction2.reportPrice(500, 21, "other bidder"); auction2.hasReceivedBid(521, ApplicationRunner.SNIPER_XMPP_ID); auction.reportPrice(1098, 97, ApplicationRunner.SNIPER_XMPP_ID); auction2.reportPrice(521, 22, ApplicationRunner.SNIPER_XMPP_ID); application.hasShownSniperIsWinning(auction, 1098); //winning bid application.hasShownSniperIsWinning(auction2, 521); //winning bid auction.announceClosed(); auction2.announceClosed(); application.showsSniperHasWonAuction(auction, 1098); //last price application.showsSniperHasWonAuction(auction2, 521); //last price }
diff --git a/pace-server/src/main/java/com/pace/settings/ui/MDBDatasourceFieldFactory.java b/pace-server/src/main/java/com/pace/settings/ui/MDBDatasourceFieldFactory.java index 3f46ebec..e1dc7336 100644 --- a/pace-server/src/main/java/com/pace/settings/ui/MDBDatasourceFieldFactory.java +++ b/pace-server/src/main/java/com/pace/settings/ui/MDBDatasourceFieldFactory.java @@ -1,159 +1,159 @@ package com.pace.settings.ui; import javax.swing.Icon; import com.pace.settings.PaceSettingsConstants; import com.vaadin.data.Item; import com.vaadin.terminal.Resource; import com.vaadin.terminal.ThemeResource; import com.vaadin.ui.Button; import com.vaadin.ui.ComboBox; import com.vaadin.ui.Component; import com.vaadin.ui.Embedded; import com.vaadin.ui.Field; import com.vaadin.ui.Label; import com.vaadin.ui.TextField; /** * MDB Datasource Field Factory * * @author JMilliron * */ public class MDBDatasourceFieldFactory extends PaceSettingsDefaultFieldFactory { private static final String CONNECTION_STRING_INPUT_PROMPT = "EDSDomain=Essbase;EDSUrl=http://localhost:13080/aps/JAPI;Server=?;User=?;Password=?;Application=?;Database=?"; private static final long serialVersionUID = 2885762876258153110L; public static final String NAME = "name"; public static final String CONNECTION_STRING = "connectionString"; public static final String META_DATA_SERVICE_PROVIDER = "metaDataServiceProvider"; public static final String DATA_SERVICE_PROVIDER = "dataServiceProvider"; public static final String TOOL_TIP = "connectionToolTip"; private ComboBox metaDataServiceProviderComboBox = new ComboBox(); private ComboBox dataServiceProviderComboBox = new ComboBox(); private String connectionStringTooltip = null; public String getConnectionStringTooltip() { return connectionStringTooltip; } public MDBDatasourceFieldFactory() { formOrderList.add(NAME); formOrderList.add(TOOL_TIP); formOrderList.add(CONNECTION_STRING); formOrderList.add(META_DATA_SERVICE_PROVIDER); formOrderList.add(DATA_SERVICE_PROVIDER); requiredFieldSet.add(NAME); requiredFieldSet.add(META_DATA_SERVICE_PROVIDER); - requiredFieldSet.add(TOOL_TIP); + //requiredFieldSet.add(TOOL_TIP); requiredFieldSet.add(DATA_SERVICE_PROVIDER); requiredFieldSet.add(CONNECTION_STRING); captionMap.put(NAME, "Name"); captionMap.put(META_DATA_SERVICE_PROVIDER, "Meta Data Service Provider"); captionMap.put(TOOL_TIP, ""); captionMap.put(DATA_SERVICE_PROVIDER, "Data Service Provider"); captionMap.put(CONNECTION_STRING, "Connection String"); metaDataServiceProviderComboBox.setNewItemsAllowed(false); metaDataServiceProviderComboBox.setNullSelectionAllowed(false); metaDataServiceProviderComboBox.addItem("com.pace.mdb.essbase.EsbMetaData"); dataServiceProviderComboBox.setNewItemsAllowed(false); dataServiceProviderComboBox.setNullSelectionAllowed(false); dataServiceProviderComboBox.addItem("com.pace.mdb.essbase.EsbData"); String tab = "&nbsp;&nbsp;&nbsp;&nbsp;"; StringBuilder connectionStringTooltipStringBuilder = new StringBuilder("=================================<p>"); connectionStringTooltipStringBuilder.append("EDS/APS/HPS connection url examples<p>"); connectionStringTooltipStringBuilder.append("=================================<p><p>"); connectionStringTooltipStringBuilder.append("EDS 7.x, APS 9.0.x to 9.2.x:<p>"); connectionStringTooltipStringBuilder.append(tab + "EDSUrl=tcpip://pchiadg1:5001<p>"); connectionStringTooltipStringBuilder.append(tab + "EDSUrl=http://localhost:11080/eds/EssbaseEnterprise<p><p>"); connectionStringTooltipStringBuilder.append("APS 9.3.x:<p>"); connectionStringTooltipStringBuilder.append(tab + "EDSUrl=http://localhost:13080/aps/JAPI<p><p>"); connectionStringTooltipStringBuilder.append("HPS 11.1.x and above:<p>"); connectionStringTooltipStringBuilder.append(tab + "EDSUrl=Embedded<p>"); connectionStringTooltipStringBuilder.append("EDSUrl=http://localhost:13080/aps/JAPI<p><p>"); connectionStringTooltipStringBuilder.append("Connection String Example:<p>"); connectionStringTooltipStringBuilder.append(tab + "EDSDomain=Essbase;EDSUrl=http://localhost:13080/aps/JAPI;Server=localhost;User=admin;Password=password;Application=Titan;Database=Titan<p>"); connectionStringTooltip = connectionStringTooltipStringBuilder.toString(); } @Override public Field createField(Item item, Object propertyId, Component uiContext) { Field field = super.createField(item, propertyId, uiContext); if ( propertyId.equals(CONNECTION_STRING)) { field.setHeight("3em"); field.setWidth("95%"); TextField tf = (TextField) field; tf.setInputPrompt(CONNECTION_STRING_INPUT_PROMPT); } else if ( propertyId.equals(META_DATA_SERVICE_PROVIDER) ) { metaDataServiceProviderComboBox.setCaption(field.getCaption()); metaDataServiceProviderComboBox.setRequired(requiredFieldSet.contains(propertyId)); metaDataServiceProviderComboBox.setWidth(PaceSettingsConstants.COMMON_FIELD_WIDTH_25_EM); return metaDataServiceProviderComboBox; } else if ( propertyId.equals(DATA_SERVICE_PROVIDER) ) { dataServiceProviderComboBox.setCaption(field.getCaption()); dataServiceProviderComboBox.setRequired(requiredFieldSet.contains(propertyId)); dataServiceProviderComboBox.setWidth(PaceSettingsConstants.COMMON_FIELD_WIDTH_25_EM); return dataServiceProviderComboBox; } else if(propertyId.equals(TOOL_TIP)) { field.setReadOnly(true); field.setIcon(new ThemeResource("icons/32/questionmark1.png")); field.setDescription(getConnectionStringTooltip()); TextField lf = (TextField)field; } return field; } }
true
true
public MDBDatasourceFieldFactory() { formOrderList.add(NAME); formOrderList.add(TOOL_TIP); formOrderList.add(CONNECTION_STRING); formOrderList.add(META_DATA_SERVICE_PROVIDER); formOrderList.add(DATA_SERVICE_PROVIDER); requiredFieldSet.add(NAME); requiredFieldSet.add(META_DATA_SERVICE_PROVIDER); requiredFieldSet.add(TOOL_TIP); requiredFieldSet.add(DATA_SERVICE_PROVIDER); requiredFieldSet.add(CONNECTION_STRING); captionMap.put(NAME, "Name"); captionMap.put(META_DATA_SERVICE_PROVIDER, "Meta Data Service Provider"); captionMap.put(TOOL_TIP, ""); captionMap.put(DATA_SERVICE_PROVIDER, "Data Service Provider"); captionMap.put(CONNECTION_STRING, "Connection String"); metaDataServiceProviderComboBox.setNewItemsAllowed(false); metaDataServiceProviderComboBox.setNullSelectionAllowed(false); metaDataServiceProviderComboBox.addItem("com.pace.mdb.essbase.EsbMetaData"); dataServiceProviderComboBox.setNewItemsAllowed(false); dataServiceProviderComboBox.setNullSelectionAllowed(false); dataServiceProviderComboBox.addItem("com.pace.mdb.essbase.EsbData"); String tab = "&nbsp;&nbsp;&nbsp;&nbsp;"; StringBuilder connectionStringTooltipStringBuilder = new StringBuilder("=================================<p>"); connectionStringTooltipStringBuilder.append("EDS/APS/HPS connection url examples<p>"); connectionStringTooltipStringBuilder.append("=================================<p><p>"); connectionStringTooltipStringBuilder.append("EDS 7.x, APS 9.0.x to 9.2.x:<p>"); connectionStringTooltipStringBuilder.append(tab + "EDSUrl=tcpip://pchiadg1:5001<p>"); connectionStringTooltipStringBuilder.append(tab + "EDSUrl=http://localhost:11080/eds/EssbaseEnterprise<p><p>"); connectionStringTooltipStringBuilder.append("APS 9.3.x:<p>"); connectionStringTooltipStringBuilder.append(tab + "EDSUrl=http://localhost:13080/aps/JAPI<p><p>"); connectionStringTooltipStringBuilder.append("HPS 11.1.x and above:<p>"); connectionStringTooltipStringBuilder.append(tab + "EDSUrl=Embedded<p>"); connectionStringTooltipStringBuilder.append("EDSUrl=http://localhost:13080/aps/JAPI<p><p>"); connectionStringTooltipStringBuilder.append("Connection String Example:<p>"); connectionStringTooltipStringBuilder.append(tab + "EDSDomain=Essbase;EDSUrl=http://localhost:13080/aps/JAPI;Server=localhost;User=admin;Password=password;Application=Titan;Database=Titan<p>"); connectionStringTooltip = connectionStringTooltipStringBuilder.toString(); }
public MDBDatasourceFieldFactory() { formOrderList.add(NAME); formOrderList.add(TOOL_TIP); formOrderList.add(CONNECTION_STRING); formOrderList.add(META_DATA_SERVICE_PROVIDER); formOrderList.add(DATA_SERVICE_PROVIDER); requiredFieldSet.add(NAME); requiredFieldSet.add(META_DATA_SERVICE_PROVIDER); //requiredFieldSet.add(TOOL_TIP); requiredFieldSet.add(DATA_SERVICE_PROVIDER); requiredFieldSet.add(CONNECTION_STRING); captionMap.put(NAME, "Name"); captionMap.put(META_DATA_SERVICE_PROVIDER, "Meta Data Service Provider"); captionMap.put(TOOL_TIP, ""); captionMap.put(DATA_SERVICE_PROVIDER, "Data Service Provider"); captionMap.put(CONNECTION_STRING, "Connection String"); metaDataServiceProviderComboBox.setNewItemsAllowed(false); metaDataServiceProviderComboBox.setNullSelectionAllowed(false); metaDataServiceProviderComboBox.addItem("com.pace.mdb.essbase.EsbMetaData"); dataServiceProviderComboBox.setNewItemsAllowed(false); dataServiceProviderComboBox.setNullSelectionAllowed(false); dataServiceProviderComboBox.addItem("com.pace.mdb.essbase.EsbData"); String tab = "&nbsp;&nbsp;&nbsp;&nbsp;"; StringBuilder connectionStringTooltipStringBuilder = new StringBuilder("=================================<p>"); connectionStringTooltipStringBuilder.append("EDS/APS/HPS connection url examples<p>"); connectionStringTooltipStringBuilder.append("=================================<p><p>"); connectionStringTooltipStringBuilder.append("EDS 7.x, APS 9.0.x to 9.2.x:<p>"); connectionStringTooltipStringBuilder.append(tab + "EDSUrl=tcpip://pchiadg1:5001<p>"); connectionStringTooltipStringBuilder.append(tab + "EDSUrl=http://localhost:11080/eds/EssbaseEnterprise<p><p>"); connectionStringTooltipStringBuilder.append("APS 9.3.x:<p>"); connectionStringTooltipStringBuilder.append(tab + "EDSUrl=http://localhost:13080/aps/JAPI<p><p>"); connectionStringTooltipStringBuilder.append("HPS 11.1.x and above:<p>"); connectionStringTooltipStringBuilder.append(tab + "EDSUrl=Embedded<p>"); connectionStringTooltipStringBuilder.append("EDSUrl=http://localhost:13080/aps/JAPI<p><p>"); connectionStringTooltipStringBuilder.append("Connection String Example:<p>"); connectionStringTooltipStringBuilder.append(tab + "EDSDomain=Essbase;EDSUrl=http://localhost:13080/aps/JAPI;Server=localhost;User=admin;Password=password;Application=Titan;Database=Titan<p>"); connectionStringTooltip = connectionStringTooltipStringBuilder.toString(); }
diff --git a/src/org/meta_environment/rascal/interpreter/Evaluator.java b/src/org/meta_environment/rascal/interpreter/Evaluator.java index 9760fe03e4..4eeea6af7c 100644 --- a/src/org/meta_environment/rascal/interpreter/Evaluator.java +++ b/src/org/meta_environment/rascal/interpreter/Evaluator.java @@ -1,4137 +1,4137 @@ package org.meta_environment.rascal.interpreter; import java.io.IOException; import java.io.Writer; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.Map; import java.util.Map.Entry; import org.eclipse.imp.pdb.facts.IBool; import org.eclipse.imp.pdb.facts.IConstructor; import org.eclipse.imp.pdb.facts.IInteger; import org.eclipse.imp.pdb.facts.IList; import org.eclipse.imp.pdb.facts.IListWriter; import org.eclipse.imp.pdb.facts.IMap; import org.eclipse.imp.pdb.facts.IMapWriter; import org.eclipse.imp.pdb.facts.INode; import org.eclipse.imp.pdb.facts.IReal; import org.eclipse.imp.pdb.facts.IRelation; import org.eclipse.imp.pdb.facts.IRelationWriter; import org.eclipse.imp.pdb.facts.ISet; import org.eclipse.imp.pdb.facts.ISetWriter; import org.eclipse.imp.pdb.facts.ISourceLocation; import org.eclipse.imp.pdb.facts.IString; import org.eclipse.imp.pdb.facts.ITuple; import org.eclipse.imp.pdb.facts.IValue; import org.eclipse.imp.pdb.facts.IValueFactory; import org.eclipse.imp.pdb.facts.IWriter; import org.eclipse.imp.pdb.facts.exceptions.UndeclaredFieldException; import org.eclipse.imp.pdb.facts.type.Type; import org.eclipse.imp.pdb.facts.type.TypeFactory; import org.eclipse.imp.pdb.facts.type.TypeStore; import org.meta_environment.rascal.ast.ASTFactory; import org.meta_environment.rascal.ast.AbstractAST; import org.meta_environment.rascal.ast.Bound; import org.meta_environment.rascal.ast.Case; import org.meta_environment.rascal.ast.Catch; import org.meta_environment.rascal.ast.Declaration; import org.meta_environment.rascal.ast.Declarator; import org.meta_environment.rascal.ast.Expression; import org.meta_environment.rascal.ast.Field; import org.meta_environment.rascal.ast.FunctionDeclaration; import org.meta_environment.rascal.ast.FunctionModifier; import org.meta_environment.rascal.ast.Import; import org.meta_environment.rascal.ast.Module; import org.meta_environment.rascal.ast.Name; import org.meta_environment.rascal.ast.NullASTVisitor; import org.meta_environment.rascal.ast.QualifiedName; import org.meta_environment.rascal.ast.Replacement; import org.meta_environment.rascal.ast.Statement; import org.meta_environment.rascal.ast.Strategy; import org.meta_environment.rascal.ast.Toplevel; import org.meta_environment.rascal.ast.Assignable.Constructor; import org.meta_environment.rascal.ast.Assignable.FieldAccess; import org.meta_environment.rascal.ast.ClosureAsFunction.Evaluated; import org.meta_environment.rascal.ast.Declaration.Alias; import org.meta_environment.rascal.ast.Declaration.Annotation; import org.meta_environment.rascal.ast.Declaration.Data; import org.meta_environment.rascal.ast.Declaration.Function; import org.meta_environment.rascal.ast.Declaration.Rule; import org.meta_environment.rascal.ast.Declaration.Tag; import org.meta_environment.rascal.ast.Declaration.Variable; import org.meta_environment.rascal.ast.Declaration.View; import org.meta_environment.rascal.ast.Expression.Addition; import org.meta_environment.rascal.ast.Expression.All; import org.meta_environment.rascal.ast.Expression.Ambiguity; import org.meta_environment.rascal.ast.Expression.And; import org.meta_environment.rascal.ast.Expression.Any; import org.meta_environment.rascal.ast.Expression.Bracket; import org.meta_environment.rascal.ast.Expression.CallOrTree; import org.meta_environment.rascal.ast.Expression.Closure; import org.meta_environment.rascal.ast.Expression.ClosureCall; import org.meta_environment.rascal.ast.Expression.Composition; import org.meta_environment.rascal.ast.Expression.Comprehension; import org.meta_environment.rascal.ast.Expression.Division; import org.meta_environment.rascal.ast.Expression.Equivalence; import org.meta_environment.rascal.ast.Expression.FieldProject; import org.meta_environment.rascal.ast.Expression.FieldUpdate; import org.meta_environment.rascal.ast.Expression.FunctionAsValue; import org.meta_environment.rascal.ast.Expression.GreaterThan; import org.meta_environment.rascal.ast.Expression.GreaterThanOrEq; import org.meta_environment.rascal.ast.Expression.IfDefinedOtherwise; import org.meta_environment.rascal.ast.Expression.Implication; import org.meta_environment.rascal.ast.Expression.In; import org.meta_environment.rascal.ast.Expression.Intersection; import org.meta_environment.rascal.ast.Expression.IsDefined; import org.meta_environment.rascal.ast.Expression.LessThan; import org.meta_environment.rascal.ast.Expression.LessThanOrEq; import org.meta_environment.rascal.ast.Expression.Lexical; import org.meta_environment.rascal.ast.Expression.List; import org.meta_environment.rascal.ast.Expression.Literal; import org.meta_environment.rascal.ast.Expression.Location; import org.meta_environment.rascal.ast.Expression.Match; import org.meta_environment.rascal.ast.Expression.Modulo; import org.meta_environment.rascal.ast.Expression.Negation; import org.meta_environment.rascal.ast.Expression.Negative; import org.meta_environment.rascal.ast.Expression.NoMatch; import org.meta_environment.rascal.ast.Expression.NonEmptyBlock; import org.meta_environment.rascal.ast.Expression.NotIn; import org.meta_environment.rascal.ast.Expression.OperatorAsValue; import org.meta_environment.rascal.ast.Expression.Or; import org.meta_environment.rascal.ast.Expression.Product; import org.meta_environment.rascal.ast.Expression.Range; import org.meta_environment.rascal.ast.Expression.Set; import org.meta_environment.rascal.ast.Expression.StepRange; import org.meta_environment.rascal.ast.Expression.Subscript; import org.meta_environment.rascal.ast.Expression.Subtraction; import org.meta_environment.rascal.ast.Expression.TransitiveClosure; import org.meta_environment.rascal.ast.Expression.TransitiveReflexiveClosure; import org.meta_environment.rascal.ast.Expression.Tuple; import org.meta_environment.rascal.ast.Expression.TypedVariable; import org.meta_environment.rascal.ast.Expression.ValueProducerWithStrategy; import org.meta_environment.rascal.ast.Expression.Visit; import org.meta_environment.rascal.ast.Expression.VoidClosure; import org.meta_environment.rascal.ast.FunctionDeclaration.Abstract; import org.meta_environment.rascal.ast.Header.Parameters; import org.meta_environment.rascal.ast.IntegerLiteral.DecimalIntegerLiteral; import org.meta_environment.rascal.ast.Literal.Boolean; import org.meta_environment.rascal.ast.Literal.Integer; import org.meta_environment.rascal.ast.Literal.Real; import org.meta_environment.rascal.ast.LocalVariableDeclaration.Default; import org.meta_environment.rascal.ast.Rule.Arbitrary; import org.meta_environment.rascal.ast.Rule.Guarded; import org.meta_environment.rascal.ast.Rule.Replacing; import org.meta_environment.rascal.ast.Statement.Assert; import org.meta_environment.rascal.ast.Statement.AssertWithMessage; import org.meta_environment.rascal.ast.Statement.Assignment; import org.meta_environment.rascal.ast.Statement.Block; import org.meta_environment.rascal.ast.Statement.Break; import org.meta_environment.rascal.ast.Statement.Continue; import org.meta_environment.rascal.ast.Statement.DoWhile; import org.meta_environment.rascal.ast.Statement.EmptyStatement; import org.meta_environment.rascal.ast.Statement.Fail; import org.meta_environment.rascal.ast.Statement.For; import org.meta_environment.rascal.ast.Statement.GlobalDirective; import org.meta_environment.rascal.ast.Statement.IfThen; import org.meta_environment.rascal.ast.Statement.IfThenElse; import org.meta_environment.rascal.ast.Statement.Insert; import org.meta_environment.rascal.ast.Statement.Solve; import org.meta_environment.rascal.ast.Statement.Switch; import org.meta_environment.rascal.ast.Statement.Throw; import org.meta_environment.rascal.ast.Statement.Try; import org.meta_environment.rascal.ast.Statement.TryFinally; import org.meta_environment.rascal.ast.Statement.VariableDeclaration; import org.meta_environment.rascal.ast.Statement.While; import org.meta_environment.rascal.ast.Toplevel.DefaultVisibility; import org.meta_environment.rascal.ast.Toplevel.GivenVisibility; import org.meta_environment.rascal.ast.Visit.DefaultStrategy; import org.meta_environment.rascal.ast.Visit.GivenStrategy; import org.meta_environment.rascal.interpreter.LazySet.LazyInsert; import org.meta_environment.rascal.interpreter.LazySet.LazyUnion; import org.meta_environment.rascal.interpreter.asserts.Ambiguous; import org.meta_environment.rascal.interpreter.asserts.ImplementationError; import org.meta_environment.rascal.interpreter.asserts.NotYetImplemented; import org.meta_environment.rascal.interpreter.control_exceptions.Failure; import org.meta_environment.rascal.interpreter.control_exceptions.Return; import org.meta_environment.rascal.interpreter.env.Environment; import org.meta_environment.rascal.interpreter.env.GlobalEnvironment; import org.meta_environment.rascal.interpreter.env.JavaFunction; import org.meta_environment.rascal.interpreter.env.Lambda; import org.meta_environment.rascal.interpreter.env.ModuleEnvironment; import org.meta_environment.rascal.interpreter.env.RascalFunction; import org.meta_environment.rascal.interpreter.load.FromResourceLoader; import org.meta_environment.rascal.interpreter.load.IModuleLoader; import org.meta_environment.rascal.interpreter.result.Result; import org.meta_environment.rascal.interpreter.staticErrors.ArityError; import org.meta_environment.rascal.interpreter.staticErrors.MissingModifierError; import org.meta_environment.rascal.interpreter.staticErrors.ModuleNameMismatchError; import org.meta_environment.rascal.interpreter.staticErrors.SyntaxError; import org.meta_environment.rascal.interpreter.staticErrors.UndeclaredAnnotationError; import org.meta_environment.rascal.interpreter.staticErrors.UndeclaredFieldError; import org.meta_environment.rascal.interpreter.staticErrors.UndeclaredFunctionError; import org.meta_environment.rascal.interpreter.staticErrors.UndeclaredModuleError; import org.meta_environment.rascal.interpreter.staticErrors.UnexpectedTypeError; import org.meta_environment.rascal.interpreter.staticErrors.UnguardedFailError; import org.meta_environment.rascal.interpreter.staticErrors.UnguardedInsertError; import org.meta_environment.rascal.interpreter.staticErrors.UnguardedReturnError; import org.meta_environment.rascal.interpreter.staticErrors.UninitializedVariableError; import org.meta_environment.rascal.interpreter.staticErrors.UnsupportedOperationError; public class Evaluator extends NullASTVisitor<Result> { final IValueFactory vf; final TypeFactory tf = TypeFactory.getInstance(); private final TypeEvaluator te = TypeEvaluator.getInstance(); private final java.util.ArrayDeque<Environment> callStack; private final GlobalEnvironment heap; private final java.util.ArrayDeque<ModuleEnvironment> scopeStack; private final JavaBridge javaBridge; private final boolean LAZY = false; enum DIRECTION {BottomUp, TopDown}; // Parameters for traversing trees enum FIXEDPOINT {Yes, No}; enum PROGRESS {Continuing, Breaking}; private Statement currentStatement; // used in runtime errormessages private Profiler profiler; private boolean doProfiling = true; // TODO: can we remove this? protected MatchPattern lastPattern; // The most recent pattern applied in a match // For the benefit of string matching. private TypeDeclarationEvaluator typeDeclarator = new TypeDeclarationEvaluator(); private java.util.List<IModuleLoader> loaders; private java.util.List<ClassLoader> classLoaders; public Evaluator(IValueFactory f, ASTFactory astFactory, Writer errorWriter, ModuleEnvironment scope) { this(f, astFactory, errorWriter, scope, new GlobalEnvironment()); } public Evaluator(IValueFactory f, ASTFactory astFactory, Writer errorWriter, ModuleEnvironment scope, GlobalEnvironment heap) { this.vf = f; this.heap = heap; this.callStack = new ArrayDeque<Environment>(); this.callStack.push(scope); this.scopeStack = new ArrayDeque<ModuleEnvironment>(); this.scopeStack.push(scope); this.loaders = new LinkedList<IModuleLoader>(); this.classLoaders = new LinkedList<ClassLoader>(); this.javaBridge = new JavaBridge(errorWriter, classLoaders); // library loaders.add(new FromResourceLoader(this.getClass(), "StandardLibrary")); // everything rooted at the src directory loaders.add(new FromResourceLoader(this.getClass())); // load Java classes from the current jar (for the standard library) classLoaders.add(getClass().getClassLoader()); } private void checkPoint(Environment env) { env.checkPoint(); } private void rollback(Environment env) { env.rollback(); } private void commit(Environment env) { env.commit(); } public void setCurrentStatement(Statement currentStatement) { this.currentStatement = currentStatement; } public Statement getCurrentStatement() { return currentStatement; } private Environment peek() { return this.callStack.peek(); } public void addModuleLoader(IModuleLoader loader) { loaders.add(loader); } public void addClassLoader(ClassLoader loader) { classLoaders.add(loader); } /** * Evaluate a statement * @param stat * @return */ public IValue eval(Statement stat) { try { if(doProfiling){ profiler = new Profiler(this); profiler.start(); } Result r = stat.accept(this); if(r != null){ if(doProfiling){ profiler.pleaseStop(); profiler.report(); } return r.getValue(); } else { throw new ImplementationError("Not yet implemented: " + stat.toString()); } } catch (Return e){ throw new UnguardedReturnError(stat); } catch (Failure e){ throw new UnguardedFailError(stat); } catch (org.meta_environment.rascal.interpreter.control_exceptions.Insert e){ throw new UnguardedInsertError(stat); } } /** * Evaluate a declaration * @param declaration * @return */ public IValue eval(Declaration declaration) { Result r = declaration.accept(this); if(r != null){ return r.getValue(); } else { throw new NotYetImplemented(declaration.toString()); } } /** * Evaluate an import * @param imp * @return */ public IValue eval(org.meta_environment.rascal.ast.Import imp) { Result r = imp.accept(this); if(r != null){ return r.getValue(); } else { throw new ImplementationError("Not yet implemented: " + imp.getTree()); } } /* First a number of general utility methods */ /* * Return an evaluation result that is already in normal form, * i.e., all potential rules have already been applied to it. */ Result normalizedResult(Type t, IValue v){ Map<Type, Type> bindings = peek().getTypeBindings(); Type instance; if (bindings.size() > 0) { instance = t.instantiate(peek().getStore(), bindings); } else { instance = t; } if (v != null) { checkType(v.getType(), instance); } return new Result(instance, v); } /* * Return an evaluation result that may need normalization. */ Result result(Type t, IValue v) { Map<Type, Type> bindings = peek().getTypeBindings(); Type instance; if (bindings.size() > 0) { instance = t.instantiate(peek().getStore(), bindings); } else { instance = t; } if (v != null) { checkType(v.getType(), instance); // rewrite rules do not change the declared type return new Result(instance, applyRules(v)); } return new Result(instance, v); } // TODO: package visibility? Result result(IValue v) { return new Result(v.getType(), applyRules(v)); } private IValue applyRules(IValue v) { //System.err.println("applyRules(" + v + ")"); // we search using the run-time type of a value Type typeToSearchFor = v.getType(); if (typeToSearchFor.isAbstractDataType()) { typeToSearchFor = ((IConstructor) v).getConstructorType(); } java.util.List<org.meta_environment.rascal.ast.Rule> rules = heap.getRules(typeToSearchFor); if(rules.isEmpty()){ return v; } TraverseResult tr = traverse(v, new CasesOrRules(rules), DIRECTION.BottomUp, PROGRESS.Continuing, FIXEDPOINT.No); /* innermost is achieved by repeated applications of applyRules * when intermediate results are produced. */ return tr.value; } private void pop() { callStack.pop(); } private void push() { callStack.push(new Environment(peek())); } private Result result() { return new Result(null, null); } private void checkType(Type given, Type expected) { if (expected == org.meta_environment.rascal.interpreter.env.Lambda.getClosureType()) { return; } if (!given.isSubtypeOf(expected)){ throw new UnexpectedTypeError(expected, given, getCurrentStatement()); } } // Ambiguity ................................................... @Override public Result visitExpressionAmbiguity(Ambiguity x) { throw new Ambiguous(x.toString()); } @Override public Result visitStatementAmbiguity( org.meta_environment.rascal.ast.Statement.Ambiguity x) { throw new Ambiguous(x.toString()); } // Modules ------------------------------------------------------------- @Override public Result visitImportDefault( org.meta_environment.rascal.ast.Import.Default x) { // TODO support for full complexity of import declarations String name = x.getModule().getName().toString(); if (name.startsWith("\\")) { name = name.substring(1); } if (!heap.existsModule(name)) { Module module = loadModule(x, name); if (!getModuleName(module).equals(name)) { throw new ModuleNameMismatchError(getModuleName(module), name, x.getModule()); } module.accept(this); } scopeStack.peek().addImport(name, heap.getModule(name, x)); return result(); } private Module loadModule(org.meta_environment.rascal.ast.Import.Default x, String name) { for (IModuleLoader loader : loaders) { try { return loader.loadModule(name); } catch (IOException e) { // this happens regularly } } throw RuntimeExceptionFactory.moduleNotFound(vf.string(name)); } @Override public Result visitModuleDefault( org.meta_environment.rascal.ast.Module.Default x) { String name = getModuleName(x); if (!heap.existsModule(name)) { ModuleEnvironment env = new ModuleEnvironment(name); scopeStack.push(env); callStack.push(env); // such that declarations end up in the module scope try { x.getHeader().accept(this); java.util.List<Toplevel> decls = x.getBody().getToplevels(); typeDeclarator.evaluateDeclarations(decls, peek()); for (Toplevel l : decls) { l.accept(this); } // only after everything was successful add the module heap.addModule(env); } finally { scopeStack.pop(); callStack.pop(); } } return result(); } private String getModuleName( Module module) { String name = module.getHeader().getName().toString(); if (name.startsWith("\\")) { name = name.substring(1); } return name; } @Override public Result visitHeaderDefault( org.meta_environment.rascal.ast.Header.Default x) { visitImports(x.getImports()); return result(); } @Override public Result visitDeclarationAlias(Alias x) { typeDeclarator.declareAlias(x, peek()); return result(); } @Override public Result visitDeclarationData(Data x) { typeDeclarator.declareConstructor(x, peek()); return result(); } private void visitImports(java.util.List<Import> imports) { for (Import i : imports) { i.accept(this); } } @Override public Result visitHeaderParameters(Parameters x) { visitImports(x.getImports()); return result(); } @Override public Result visitToplevelDefaultVisibility(DefaultVisibility x) { Result r = x.getDeclaration().accept(this); r.setPublic(false); return r; } @Override public Result visitToplevelGivenVisibility(GivenVisibility x) { Result r = x.getDeclaration().accept(this); r.setPublic(x.getVisibility().isPublic()); return r; } @Override public Result visitDeclarationFunction(Function x) { return x.getFunctionDeclaration().accept(this); } @Override public Result visitDeclarationVariable(Variable x) { Type declaredType = te.eval(x.getType(), scopeStack.peek()); Result r = result(); for (org.meta_environment.rascal.ast.Variable var : x.getVariables()) { if (var.isUnInitialized()) { throw new UninitializedVariableError(var.toString(), var); } else { Result v = var.getInitial().accept(this); if(v.getType().isSubtypeOf(declaredType)){ // TODO: do we actually want to instantiate the locally bound type parameters? Map<Type,Type> bindings = new HashMap<Type,Type>(); declaredType.match(v.getType(), bindings); declaredType = declaredType.instantiate(peek().getStore(), bindings); r = normalizedResult(declaredType, v.getValue()); scopeStack.peek().storeVariable(var.getName(), r); } else { throw new UnexpectedTypeError(declaredType, v.getType(), var); } } } return r; } @Override public Result visitDeclarationAnnotation(Annotation x) { Type annoType = te.eval(x.getAnnoType(), scopeStack.peek()); String name = x.getName().toString(); Type onType = te.eval(x.getOnType(), scopeStack.peek()); scopeStack.peek().declareAnnotation(onType, name, annoType); return result(); } private Type evalType(org.meta_environment.rascal.ast.Type type) { return te.eval(type, peek()); } @Override public Result visitDeclarationView(View x) { // TODO implement throw new NotYetImplemented("Views"); } @Override public Result visitDeclarationRule(Rule x) { return x.getRule().accept(this); } @Override public Result visitRuleArbitrary(Arbitrary x) { MatchPattern pv = x.getPattern().accept(makePatternEvaluator()); heap.storeRule(pv.getType(scopeStack.peek()), x); return result(); } private AbstractPatternEvaluator makePatternEvaluator() { return new AbstractPatternEvaluator(vf, peek(), peek(), this); } @Override public Result visitRuleReplacing(Replacing x) { MatchPattern pv = x.getPattern().accept(makePatternEvaluator()); //System.err.println("visitRule: " + pv.getType(this)); heap.storeRule(pv.getType(scopeStack.peek()), x); return result(); } @Override public Result visitRuleGuarded(Guarded x) { //TODO adapt to new scheme Result result = x.getRule().getPattern().getPattern().accept(this); Type expected = evalType(x.getType()); Type got = result.getType(); if (!got.isSubtypeOf(expected)) { throw new UnexpectedTypeError(expected, got, x); } return x.getRule().accept(this); } @Override public Result visitDeclarationTag(Tag x) { throw new NotYetImplemented("tags"); } // Variable Declarations ----------------------------------------------- @Override public Result visitLocalVariableDeclarationDefault(Default x) { // TODO deal with dynamic variables return x.getDeclarator().accept(this); } @Override public Result visitDeclaratorDefault( org.meta_environment.rascal.ast.Declarator.Default x) { Type declaredType = evalType(x.getType()); Result r = result(); for (org.meta_environment.rascal.ast.Variable var : x.getVariables()) { if (var.isUnInitialized()) { // variable declaration without initialization r = result(declaredType, null); peek().storeVariable(var.getName(), r); } else { // variable declaration with initialization Result v = var.getInitial().accept(this); if(v.getType().isSubtypeOf(declaredType)){ // TODO: do we actually want to instantiate the locally bound type parameters? Map<Type,Type> bindings = new HashMap<Type,Type>(); declaredType.match(v.getType(), bindings); declaredType = declaredType.instantiate(peek().getStore(), bindings); r = result(declaredType, v.getValue()); peek().storeVariable(var.getName(), r); } else { throw new UnexpectedTypeError(declaredType, v.getType(), var); } } } return r; } // Function calls and node constructors @Override public Result visitClosureAsFunctionEvaluated(Evaluated x) { Expression expr = x.getExpression(); if (expr.isQualifiedName()) { } return result(vf.string(Names.name(Names.lastName(expr.getQualifiedName())))); } @Override public Result visitExpressionClosureCall(ClosureCall x) { Result func = x.getClosure().getExpression().accept(this); java.util.List<org.meta_environment.rascal.ast.Expression> args = x.getArguments(); IValue[] actuals = new IValue[args.size()]; Type[] types = new Type[args.size()]; for (int i = 0; i < args.size(); i++) { Result resultElem = args.get(i).accept(this); types[i] = resultElem.getType(); actuals[i] = resultElem.getValue(); } Type actualTypes = tf.tupleType(types); if (func.getType() == Lambda.getClosureType()) { Lambda lambda = (Lambda) func.getValue(); try { pushCallFrame(lambda.getEnv()); return lambda.call(actuals, actualTypes, peek()); } finally { pop(); } } else { throw new ImplementationError("Lambda's should have the closure type"); } } @Override public Result visitExpressionCallOrTree(CallOrTree x) { java.util.List<org.meta_environment.rascal.ast.Expression> args = x.getArguments(); QualifiedName name = x.getQualifiedName(); IValue[] actuals = new IValue[args.size()]; Type[] types = new Type[args.size()]; for (int i = 0; i < args.size(); i++) { Result resultElem = args.get(i).accept(this); types[i] = resultElem.getType(); actuals[i] = resultElem.getValue(); } Type signature = tf.tupleType(types); if (isTreeConstructorName(name, signature)) { return constructTree(name, actuals, signature); } else { return call(name, actuals, signature); } } private Result call(QualifiedName name, IValue[] actuals, Type actualTypes) { String moduleName = Names.moduleName(name); Environment env; if (moduleName == null) { env = peek(); } else { env = peek().getImport(moduleName); if (env == null) { throw new UndeclaredModuleError(moduleName, name); } } Lambda func = env.getFunction(Names.name(Names.lastName(name)), actualTypes); if (func != null) { try { pushCallFrame(func.getEnv()); return func.call(actuals, actualTypes, peek()); } finally { pop(); } } undefinedFunctionException(name, actualTypes); return null; } private void pushCallFrame(Environment env) { callStack.push(new Environment(env)); } private void undefinedFunctionException(QualifiedName name, Type actualTypes) { StringBuffer sb = new StringBuffer(); String sep = ""; for(int i = 0; i < actualTypes.getArity(); i++){ sb.append(sep); sep = ", "; sb.append(actualTypes.getFieldType(i).toString()); } throw new UndeclaredFunctionError(name + "(" + sb.toString() + ")", name); } private boolean isTreeConstructorName(QualifiedName name, Type signature) { return peek().isTreeConstructorName(name, signature); } /** * A top-down algorithm is needed to type check a constructor call since the * result type of constructors can be overloaded. We bring down the expected type * of each argument. * @param expected * @param functionName * @param args * @return * * TODO: code does not deal with import structure, rather data def's are global. */ private Result constructTree(QualifiedName functionName, IValue[] actuals, Type signature) { String sort; String cons; cons = Names.consName(functionName); sort = Names.sortName(functionName); Type candidate = null; if (sort != null) { Type sortType = peek().getAbstractDataType(sort); if (sortType != null) { candidate = peek().getConstructor(sortType, cons, signature); } else { return result(tf.nodeType(), vf.node(cons, actuals)); } } candidate = peek().getConstructor(cons, signature); if (candidate != null) { Map<Type,Type> localBindings = new HashMap<Type,Type>(); candidate.getFieldTypes().match(tf.tupleType(actuals), localBindings); return result(candidate.getAbstractDataType().instantiate(new TypeStore(), localBindings), candidate.make(vf, actuals)); } return result(tf.nodeType(), vf.node(cons, actuals)); } @Override public Result visitExpressionFunctionAsValue(FunctionAsValue x) { return x.getFunction().accept(this); } @Override public Result visitFunctionAsValueDefault( org.meta_environment.rascal.ast.FunctionAsValue.Default x) { Name name = x.getName(); //TODO is this a bug, what if name was overloaded? //TODO add support for typed function names Lambda func = peek().getFunction(Names.name(name), tf.voidType()); if (func == null) { throw new UndeclaredFunctionError(Names.name(name), x); } return func; } private boolean hasJavaModifier(FunctionDeclaration func) { java.util.List<FunctionModifier> mods = func.getSignature().getModifiers().getModifiers(); for (FunctionModifier m : mods) { if (m.isJava()) { return true; } } return false; } @Override public Result visitFunctionBodyDefault( org.meta_environment.rascal.ast.FunctionBody.Default x) { Result result = result(); for (Statement statement : x.getStatements()) { setCurrentStatement(statement); result = statement.accept(this); } return result; } // Statements --------------------------------------------------------- @Override public Result visitStatementAssert(Assert x) { Result r = x.getExpression().accept(this); if (!r.getType().equals(tf.boolType())) { throw new UnexpectedTypeError(tf.boolType(), r.getType(), x); } if(r.getValue().isEqual(vf.bool(false))) { throw RuntimeExceptionFactory.assertionFailed(); } return r; } @Override public Result visitStatementAssertWithMessage(AssertWithMessage x) { Result r = x.getExpression().accept(this); if (!r.getType().equals(tf.boolType())) { throw new UnexpectedTypeError(tf.boolType(),r.getType(), x); } if(r.getValue().isEqual(vf.bool(false))){ String str = x.getMessage().toString(); IString msg = vf.string(unescape(str, x)); throw RuntimeExceptionFactory.assertionFailed(msg); } return r; } @Override public Result visitStatementVariableDeclaration(VariableDeclaration x) { return x.getDeclaration().accept(this); } @Override public Result visitStatementExpression(Statement.Expression x) { setCurrentStatement(x); return x.getExpression().accept(this); } @Override public Result visitStatementFunctionDeclaration( org.meta_environment.rascal.ast.Statement.FunctionDeclaration x) { return x.getFunctionDeclaration().accept(this); } // TODO?? package visibility?? Result assignVariable(QualifiedName name, Result right){ Environment env = getEnv(name); Result previous = env.getVariable(name); if (previous != null) { if (right.getType().isSubtypeOf(previous.getType())) { right.setType(previous.getType()); } else { throw new UnexpectedTypeError(previous.getType(), right.getType(), null); } } env.storeVariable(name, right); return right; } private Environment getEnv(QualifiedName name) { String moduleName = Names.moduleName(name); Environment env; if (moduleName == null) { env = peek(); } else { env = peek().getImport(moduleName); } return env; } @Override public Result visitExpressionSubscript(Subscript x) { Result expr = x.getExpression().accept(this); Type exprType = expr.getType(); int nSubs = x.getSubscripts().size(); if (exprType.isRelationType()) { int relArity = exprType.getArity(); if(nSubs >= relArity){ throw new ArityError(exprType, nSubs, x); } Result subscriptResult[] = new Result[nSubs]; Type subscriptType[] = new Type[nSubs]; boolean subscriptIsSet[] = new boolean[nSubs]; for(int i = 0; i < nSubs; i++){ subscriptResult[i] = x.getSubscripts().get(i).accept(this); subscriptType[i] = subscriptResult[i].getType(); } boolean yieldSet = (relArity - nSubs) == 1; Type resFieldType[] = new Type[relArity - nSubs]; for (int i = 0; i < relArity; i++) { Type relFieldType = exprType.getFieldType(i); if(i < nSubs){ if(subscriptType[i].isSetType() && subscriptType[i].getElementType().isSubtypeOf(relFieldType)){ subscriptIsSet[i] = true; } else if(subscriptType[i].isSubtypeOf(relFieldType)){ subscriptIsSet[i] = false; } else { throw new UnexpectedTypeError(relFieldType, subscriptType[i], x); } } else { resFieldType[i - nSubs] = relFieldType; } } Type resultType; ISetWriter wset = null; IRelationWriter wrel = null; if(yieldSet){ resultType = tf.setType(resFieldType[0]); wset = resultType.writer(vf); } else { resultType = tf.relType(resFieldType); wrel = resultType.writer(vf); } for (IValue v : ((IRelation) expr.getValue())) { ITuple tup = (ITuple) v; boolean allEqual = true; for(int k = 0; k < nSubs; k++){ if(subscriptIsSet[k] && ((ISet) subscriptResult[k].getValue()).contains(tup.get(k))){ /* ok */ } else if (tup.get(k).isEqual(subscriptResult[k].getValue())){ /* ok */ } else { allEqual = false; } } if (allEqual) { IValue args[] = new IValue[relArity - nSubs]; for (int i = nSubs; i < relArity; i++) { args[i - nSubs] = tup.get(i); } if(yieldSet){ wset.insert(args[0]); } else { wrel.insert(vf.tuple(args)); } } } return normalizedResult(resultType, yieldSet ? wset.done() : wrel.done()); } if (nSubs > 1){ throw new SyntaxError("No more than one subscript allowed on " + exprType, x.getLocation()); } Result subs = x.getSubscripts().get(0).accept(this); Type subsBase = subs.getType(); if (exprType.isMapType() && subsBase.isSubtypeOf(exprType.getKeyType())) { Type valueType = exprType.getValueType(); IValue v = ((IMap) expr.getValue()).get(subs.getValue()); if(v == null){ - throw RuntimeExceptionFactory.noSuchKey(v); + throw RuntimeExceptionFactory.noSuchKey(subs.getValue()); } return normalizedResult(valueType,v); } if(!subsBase.isIntegerType()){ throw new UnexpectedTypeError(tf.integerType(), subsBase, x); } int index = ((IInteger) subs.getValue()).intValue(); if (exprType.isListType()) { Type elementType = exprType.getElementType(); try { IValue element = ((IList) expr.getValue()).get(index); return normalizedResult(elementType, element); } catch (java.lang.IndexOutOfBoundsException e) { throw RuntimeExceptionFactory.indexOutOfBounds((IInteger) subs.getValue()); } } if (exprType.isAbstractDataType()) { if(index >= ((IConstructor) expr.getValue()).arity()){ throw RuntimeExceptionFactory.indexOutOfBounds((IInteger) subs.getValue()); } Type elementType = ((IConstructor) expr.getValue()).getConstructorType().getFieldType(index); IValue element = ((IConstructor) expr.getValue()).get(index); return normalizedResult(elementType, element); } if (exprType.isNodeType()) { if(index >= ((INode) expr.getValue()).arity()){ throw RuntimeExceptionFactory.indexOutOfBounds((IInteger) subs.getValue()); } Type elementType = tf.valueType(); IValue element = ((INode) expr.getValue()).get(index); return normalizedResult(elementType, element); } if (exprType.isTupleType()) { try { Type elementType = exprType.getFieldType(index); IValue element = ((ITuple) expr.getValue()).get(index); return normalizedResult(elementType, element); } catch (ArrayIndexOutOfBoundsException e){ throw RuntimeExceptionFactory.indexOutOfBounds((IInteger) subs.getValue()); } } throw new UnsupportedOperationError("subscript", exprType, x); } @Override public Result visitExpressionFieldAccess( org.meta_environment.rascal.ast.Expression.FieldAccess x) { Result expr = x.getExpression().accept(this); String field = x.getField().toString(); if (expr.getType().isTupleType()) { Type tuple = expr.getType(); if (!tuple.hasFieldNames()) { throw new UndeclaredFieldError(field, tuple, x); } try { return normalizedResult(tuple.getFieldType(field), ((ITuple) expr.getValue()).get(tuple.getFieldIndex(field))); } catch (UndeclaredFieldException e){ throw new UndeclaredFieldError(field, tuple, x.getField()); } } else if (expr.getType().isRelationType()) { Type tuple = expr.getType().getFieldTypes(); try { ISetWriter w = vf.setWriter(tuple.getFieldType(field)); for (IValue e : (ISet) expr.getValue()) { w.insert(((ITuple) e).get(tuple.getFieldIndex(field))); } return result(tf.setType(tuple.getFieldType(field)), w.done()); } catch (UndeclaredFieldException e) { throw new UndeclaredFieldError(field, tuple, x); } } else if (expr.getType().isAbstractDataType() || expr.getType().isConstructorType()) { Type node = ((IConstructor) expr.getValue()).getConstructorType(); if (!expr.getType().hasField(field, callStack.peek().getStore())) { throw new UndeclaredFieldError(field, expr.getType(), x); } if (!node.hasField(field)) { throw new UndeclaredFieldError(field, expr.getType(), x); } int index = node.getFieldIndex(field); return normalizedResult(node.getFieldType(index),((IConstructor) expr.getValue()).get(index)); } else if(expr.getType().isSourceLocationType()){ ISourceLocation loc = (ISourceLocation) expr.getValue(); if(field.equals("length")){ return result(tf.integerType(), vf.integer(loc.getLength())); } else if(field.equals("offset")){ return result(tf.integerType(), vf.integer(loc.getOffset())); } else if(field.equals("beginLine")){ return result(tf.integerType(), vf.integer(loc.getBeginLine())); } else if(field.equals("beginColumn")){ return result(tf.integerType(), vf.integer(loc.getBeginColumn())); } else if(field.equals("endLine")){ return result(tf.integerType(), vf.integer(loc.getEndLine())); } else if(field.equals("endColumn")){ return result(tf.integerType(), vf.integer(loc.getEndColumn())); } else if(field.equals("url")){ return result(tf.stringType(), vf.string(loc.getURL().toString())); } else { throw new UndeclaredFieldError(field, tf.sourceLocationType(), x); } } throw new UndeclaredFieldError(field, expr.getType(), x); } private boolean duplicateIndices(int indices[]){ for(int i = 0; i < indices.length; i ++){ for(int j = 0; j < indices.length; j++){ if(i != j && indices[i] == indices[j]){ return true; } } } return false; } @Override public Result visitExpressionFieldProject(FieldProject x) { Result base = x.getExpression().accept(this); java.util.List<Field> fields = x.getFields(); int nFields = fields.size(); int selectedFields[] = new int[nFields]; if(base.getType().isTupleType()){ Type fieldTypes[] = new Type[nFields]; for(int i = 0 ; i < nFields; i++){ Field f = fields.get(i); if(f.isIndex()){ selectedFields[i] = ((IInteger) f.getFieldIndex().accept(this).getValue()).intValue(); } else { String fieldName = f.getFieldName().toString(); try { selectedFields[i] = base.getType().getFieldIndex(fieldName); } catch (UndeclaredFieldException e){ throw new UndeclaredFieldError(fieldName, base.getType(), x); } } if (selectedFields[i] < 0 || selectedFields[i] > base.getType().getArity()) { throw RuntimeExceptionFactory.indexOutOfBounds(vf.integer(i)); } fieldTypes[i] = base.getType().getFieldType(selectedFields[i]); } if(duplicateIndices(selectedFields)){ // TODO: what does it matter if there are duplicate indices??? throw new ImplementationError("Duplicate fields in projection"); } Type resultType = nFields == 1 ? fieldTypes[0] : tf.tupleType(fieldTypes); return result(resultType, ((ITuple)base.getValue()).select(selectedFields)); } if(base.getType().isRelationType()){ Type fieldTypes[] = new Type[nFields]; for(int i = 0 ; i < nFields; i++){ Field f = fields.get(i); if(f.isIndex()){ selectedFields[i] = ((IInteger) f.getFieldIndex().accept(this).getValue()).intValue(); } else { String fieldName = f.getFieldName().toString(); try { selectedFields[i] = base.getType().getFieldIndex(fieldName); } catch (Exception e){ throw new UndeclaredFieldError(fieldName, base.getType(), x); } } if(selectedFields[i] < 0 || selectedFields[i] > base.getType().getArity()) { throw RuntimeExceptionFactory.indexOutOfBounds(vf.integer(i)); } fieldTypes[i] = base.getType().getFieldType(selectedFields[i]); } if(duplicateIndices(selectedFields)){ // TODO: what does it matter if there are duplicate indices? Duplicate // field names may be a problem, but not this. throw new ImplementationError("Duplicate fields in projection"); } Type resultType = nFields == 1 ? tf.setType(fieldTypes[0]) : tf.relType(fieldTypes); return result(resultType, ((IRelation)base.getValue()).select(selectedFields)); } throw new UnsupportedOperationError("projection", base.getType(), x); } @Override public Result visitStatementEmptyStatement(EmptyStatement x) { return result(); } @Override public Result visitStatementFail(Fail x) { if (x.getFail().isWithLabel()) { throw new Failure(x.getFail().getLabel().toString()); } else { throw new Failure(); } } @Override public Result visitStatementReturn( org.meta_environment.rascal.ast.Statement.Return x) { org.meta_environment.rascal.ast.Return r = x.getRet(); if (r.isWithExpression()) { throw new Return(x.getRet().getExpression().accept(this)); } else { throw new Return(result(tf.voidType(), null)); } } @Override public Result visitStatementBreak(Break x) { throw new NotYetImplemented(x.toString()); // TODO } @Override public Result visitStatementContinue(Continue x) { throw new NotYetImplemented(x.toString()); // TODO } @Override public Result visitStatementGlobalDirective(GlobalDirective x) { throw new NotYetImplemented(x.toString()); // TODO } @Override public Result visitStatementThrow(Throw x) { throw new org.meta_environment.rascal.interpreter.control_exceptions.Throw(x.getExpression().accept(this).getValue()); } @Override public Result visitStatementTry(Try x) { return evalStatementTry(x.getBody(), x.getHandlers(), null); } @Override public Result visitStatementTryFinally(TryFinally x) { return evalStatementTry(x.getBody(), x.getHandlers(), x.getFinallyBody()); } private Result evalStatementTry(Statement body, java.util.List<Catch> handlers, Statement finallyBody){ Result res = result(); try { res = body.accept(this); } catch (org.meta_environment.rascal.interpreter.control_exceptions.Throw e){ IValue eValue = e.getException(); for (Catch c : handlers){ if(c.isDefault()){ res = c.getBody().accept(this); break; } try { push(); if(matchAndEval(eValue, c.getPattern(), c.getBody())){ break; } } finally { pop(); } } } finally { if (finallyBody != null) { finallyBody.accept(this); } } return res; } @Override public Result visitStatementVisit( org.meta_environment.rascal.ast.Statement.Visit x) { return x.getVisit().accept(this); } @Override public Result visitStatementInsert(Insert x) { throw new org.meta_environment.rascal.interpreter.control_exceptions.Insert(x.getExpression().accept(this)); } @Override public Result visitStatementAssignment(Assignment x) { Result right = x.getExpression().accept(this); return x.getAssignable().accept(new AssignableEvaluator(peek(), x.getOperator(), right, this)); } @Override public Result visitStatementBlock(Block x) { Result r = result(); try { push(); for (Statement stat : x.getStatements()) { setCurrentStatement(stat); r = stat.accept(this); } } finally { pop(); } return r; } @Override public Result visitAssignableVariable( org.meta_environment.rascal.ast.Assignable.Variable x) { return peek().getVariable(x.getQualifiedName(),x.getQualifiedName().toString()); } @Override public Result visitAssignableFieldAccess(FieldAccess x) { Result receiver = x.getReceiver().accept(this); String label = x.getField().toString(); if (receiver.getType().isTupleType()) { IValue result = ((ITuple) receiver.getValue()).get(label); Type type = ((ITuple) receiver.getValue()).getType().getFieldType(label); return normalizedResult(type, result); } else if (receiver.getType().isConstructorType() || receiver.getType().isAbstractDataType()) { IConstructor cons = (IConstructor) receiver.getValue(); Type node = cons.getConstructorType(); if (!receiver.getType().hasField(label)) { throw new UndeclaredFieldError(label, receiver.getType(), x); } if (!node.hasField(label)) { throw new UndeclaredFieldError(label, receiver.getValueType(), x); } int index = node.getFieldIndex(label); return normalizedResult(node.getFieldType(index), cons.get(index)); } else { throw new UndeclaredFieldError(label, receiver.getType(), x); } } @Override public Result visitAssignableAnnotation( org.meta_environment.rascal.ast.Assignable.Annotation x) { Result receiver = x.getReceiver().accept(this); String label = x.getAnnotation().toString(); if (!callStack.peek().declaresAnnotation(receiver.getType(), label)) { throw new UndeclaredAnnotationError(label, receiver.getType(), x); } Type type = callStack.peek().getAnnotationType(receiver.getType(), label); IValue value = ((IConstructor) receiver.getValue()).getAnnotation(label); return normalizedResult(type, value); } @Override public Result visitAssignableConstructor(Constructor x) { throw new ImplementationError("Constructor assignable does not represent a value"); } @Override public Result visitAssignableIfDefined( org.meta_environment.rascal.ast.Assignable.IfDefined x) { throw new ImplementationError("ifdefined assignable does not represent a value"); } @Override public Result visitAssignableSubscript( org.meta_environment.rascal.ast.Assignable.Subscript x) { Result receiver = x.getReceiver().accept(this); Result subscript = x.getSubscript().accept(this); if (receiver.getType().isListType()) { if (subscript.getType().isIntegerType()) { IList list = (IList) receiver.getValue(); IValue result = list.get(((IInteger) subscript.getValue()).intValue()); Type type = receiver.getType().getElementType(); return normalizedResult(type, result); } throw new UnexpectedTypeError(tf.integerType(), subscript.getDeclaredType(), x); } else if (receiver.getType().isMapType()) { Type keyType = receiver.getType().getKeyType(); if (subscript.getType().isSubtypeOf(keyType)) { IValue result = ((IMap) receiver.getValue()).get(subscript.getValue()); Type type = receiver.getType().getValueType(); return normalizedResult(type, result); } throw new UnexpectedTypeError(keyType, subscript.getDeclaredType(), x); } // TODO implement other subscripts throw new UnsupportedOperationError("subscript", receiver.getType(), x); } @Override public Result visitAssignableTuple( org.meta_environment.rascal.ast.Assignable.Tuple x) { throw new ImplementationError("Tuple in assignable does not represent a value:" + x); } @Override public Result visitAssignableAmbiguity( org.meta_environment.rascal.ast.Assignable.Ambiguity x) { throw new Ambiguous(x.toString()); } @Override public Result visitFunctionDeclarationDefault( org.meta_environment.rascal.ast.FunctionDeclaration.Default x) { Lambda lambda; boolean varArgs = x.getSignature().getParameters().isVarArgs(); if (hasJavaModifier(x)) { lambda = new JavaFunction(this, x, varArgs, peek(), javaBridge); } else { if (!x.getBody().isDefault()) { throw new MissingModifierError("java", x); } lambda = new RascalFunction(this, x, varArgs, peek()); } String name = Names.name(x.getSignature().getName()); peek().storeFunction(name, lambda); return lambda; } @Override public Result visitFunctionDeclarationAbstract(Abstract x) { Lambda lambda; boolean varArgs = x.getSignature().getParameters().isVarArgs(); if (hasJavaModifier(x)) { lambda = new org.meta_environment.rascal.interpreter.env.JavaMethod(this, x, varArgs, peek(), javaBridge); } else { throw new MissingModifierError("java", x); } String name = Names.name(x.getSignature().getName()); peek().storeFunction(name, lambda); return lambda; } @Override public Result visitStatementIfThenElse(IfThenElse x) { elseBranch: do { push(); // For the benefit of variables bound in the condition try { for (org.meta_environment.rascal.ast.Expression expr : x.getConditions()) { Result cval = expr.accept(this); if (!cval.getType().isBoolType()) { throw new UnexpectedTypeError(tf.boolType(), cval.getType(), x); } if (cval.getValue().isEqual(vf.bool(false))) { break elseBranch; } // condition is true: continue } return x.getThenStatement().accept(this); } finally { pop(); // Remove any bindings due to condition evaluation. } } while (false); return x.getElseStatement().accept(this); } @Override public Result visitStatementIfThen(IfThen x) { push(); // For the benefit of variables bound in the condition try { for (org.meta_environment.rascal.ast.Expression expr : x.getConditions()) { Result cval = expr.accept(this); if (!cval.getType().isBoolType()) { throw new UnexpectedTypeError(tf.boolType(),cval.getType(), x); } if (cval.getValue().isEqual(vf.bool(false))) { return result(); } } return x.getThenStatement().accept(this); } finally { pop(); } } @Override public Result visitStatementWhile(While x) { org.meta_environment.rascal.ast.Expression expr = x.getCondition(); Result statVal = result(); do { push(); try { Result cval = expr.accept(this); if (!cval.getType().isBoolType()) { throw new UnexpectedTypeError(tf.boolType(),cval.getType(), x); } if (cval.getValue().isEqual(vf.bool(false))) { return statVal; } statVal = x.getBody().accept(this); } finally { pop(); } } while (true); } @Override public Result visitStatementDoWhile(DoWhile x) { org.meta_environment.rascal.ast.Expression expr = x.getCondition(); do { Result result = x.getBody().accept(this); push(); try { Result cval = expr.accept(this); if (!cval.getType().isBoolType()) { throw new UnexpectedTypeError(tf.boolType(),cval.getType(), x); } if (cval.getValue().isEqual(vf.bool(false))) { return result; } } finally { pop(); } } while (true); } @Override public Result visitExpressionMatch(Match x) { return new MatchEvaluator(x.getPattern(), x.getExpression(), true, peek(), this).next(); } @Override public Result visitExpressionNoMatch(NoMatch x) { return new MatchEvaluator(x.getPattern(), x.getExpression(), false, peek(), this).next(); } // ----- General method for matching -------------------------------------------------- protected MatchPattern evalPattern(org.meta_environment.rascal.ast.Expression pat){ AbstractPatternEvaluator pe = makePatternEvaluator(); if(pe.isPattern(pat)){ return pat.accept(pe); } else { RegExpPatternEvaluator re = new RegExpPatternEvaluator(vf, peek()); if(re.isRegExpPattern(pat)){ return pat.accept(re); } else { // TODO how can this happen? throw new ImplementationError("Pattern expected instead of " + pat); } } } // TODO remove dead code // private boolean matchOne(IValue subj, org.meta_environment.rascal.ast.Expression pat){ // //System.err.println("matchOne: subj=" + subj + ", pat= " + pat); // MatchPattern mp = evalPattern(pat); // lastPattern = mp; // mp.initMatch(subj, this); // return mp.next(); // } // Expressions ----------------------------------------------------------- @Override public Result visitExpressionLiteral(Literal x) { return x.getLiteral().accept(this); } @Override public Result visitLiteralInteger(Integer x) { return x.getIntegerLiteral().accept(this); } @Override public Result visitLiteralReal(Real x) { String str = x.getRealLiteral().toString(); return result(vf.real(str)); } @Override public Result visitLiteralBoolean(Boolean x) { String str = x.getBooleanLiteral().toString(); return result(vf.bool(str.equals("true"))); } @Override public Result visitLiteralString( org.meta_environment.rascal.ast.Literal.String x) { String str = x.getStringLiteral().toString(); return result(vf.string(unescape(str, x))); } private String unescape(String str, AbstractAST ast) { byte[] bytes = str.getBytes(); StringBuffer result = new StringBuffer(); for (int i = 1; i < bytes.length - 1; i++) { char b = (char) bytes[i]; switch (b) { /* * Replace <var> by var's value. */ case '<': StringBuffer var = new StringBuffer(); char varchar; while((varchar = (char) bytes[++i]) != '>'){ var.append(varchar); } Result val = peek().getVariable(ast, var.toString()); String replacement; if(val == null || val.getValue() == null) { throw new UninitializedVariableError(var.toString(), ast); } else { if(val.getType().isStringType()){ replacement = ((IString)val.getValue()).getValue(); } else { replacement = val.getValue().toString(); } } // replacement = replacement.replaceAll("<", "\\\\<"); TODO: maybe we need this after all? result.append(replacement); continue; case '\\': switch (bytes[++i]) { case '\\': b = '\\'; break; case 'n': b = '\n'; break; case '"': b = '"'; break; case 't': b = '\t'; break; case 'b': b = '\b'; break; case 'f': b = '\f'; break; case 'r': b = '\r'; break; case '<': b = '<'; break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': b = (char) (bytes[i] - '0'); if (i < bytes.length - 1 && Character.isDigit(bytes[i+1])) { b = (char) (b * 8 + (bytes[++i] - '0')); if (i < bytes.length - 1 && Character.isDigit(bytes[i+1])) { b = (char) (b * 8 + (bytes[++i] - '0')); } } break; case 'u': // TODO unicode escape break; default: b = '\\'; } } result.append(b); } return result.toString(); } @Override public Result visitIntegerLiteralDecimalIntegerLiteral( DecimalIntegerLiteral x) { String str = x.getDecimal().toString(); return result(vf.integer(str)); } @Override public Result visitExpressionQualifiedName( org.meta_environment.rascal.ast.Expression.QualifiedName x) { if (isTreeConstructorName(x.getQualifiedName(), tf.tupleEmpty())) { return constructTree(x.getQualifiedName(), new IValue[0], tf.tupleType(new Type[0])); } else { Result result = peek().getVariable(x.getQualifiedName()); if (result != null && result.getValue() != null) { return result; } else { throw new UninitializedVariableError(x.getQualifiedName().toString(), x); } } } @Override public Result visitExpressionList(List x) { java.util.List<org.meta_environment.rascal.ast.Expression> elements = x .getElements(); Type elementType = tf.voidType(); java.util.List<IValue> results = new ArrayList<IValue>(); for (org.meta_environment.rascal.ast.Expression expr : elements) { Result resultElem = expr.accept(this); if(resultElem.getType().isListType() && !expr.isList() && elementType.isSubtypeOf(resultElem.getType().getElementType())){ /* * Splice elements in list if element types permit this */ for(IValue val : ((IList) resultElem.getValue())){ elementType = elementType.lub(val.getType()); results.add(val); } } else { elementType = elementType.lub(resultElem.getType()); results.add(results.size(), resultElem.getValue()); } } Type resultType = tf.listType(elementType); IListWriter w = resultType.writer(vf); w.appendAll(results); return result(resultType, w.done()); } @Override public Result visitExpressionSet(Set x) { java.util.List<org.meta_environment.rascal.ast.Expression> elements = x .getElements(); Type elementType = tf.voidType(); java.util.List<IValue> results = new ArrayList<IValue>(); for (org.meta_environment.rascal.ast.Expression expr : elements) { Result resultElem = expr.accept(this); if(resultElem.getType().isSetType() && !expr.isSet() && elementType.isSubtypeOf(resultElem.getType().getElementType())){ /* * Splice the elements in the set if element types permit this. */ for(IValue val : ((ISet) resultElem.getValue())){ elementType = elementType.lub(val.getType()); results.add(val); } } else { elementType = elementType.lub(resultElem.getType()); results.add(results.size(), resultElem.getValue()); } } Type resultType = tf.setType(elementType); ISetWriter w = resultType.writer(vf); w.insertAll(results); return result(resultType, w.done()); } @Override public Result visitExpressionMap( org.meta_environment.rascal.ast.Expression.Map x) { java.util.List<org.meta_environment.rascal.ast.Mapping> mappings = x .getMappings(); Map<IValue,IValue> result = new HashMap<IValue,IValue>(); Type keyType = tf.voidType(); Type valueType = tf.voidType(); for (org.meta_environment.rascal.ast.Mapping mapping : mappings) { Result keyResult = mapping.getFrom().accept(this); Result valueResult = mapping.getTo().accept(this); keyType = keyType.lub(keyResult.getType()); valueType = valueType.lub(valueResult.getType()); result.put(keyResult.getValue(), valueResult.getValue()); } Type type = tf.mapType(keyType, valueType); IMapWriter w = type.writer(vf); w.putAll(result); return result(type, w.done()); } @Override public Result visitExpressionNonEmptyBlock(NonEmptyBlock x) { return new Lambda(x, this, tf.voidType(), "", tf.tupleEmpty(), false, x.getStatements(), peek()); } @Override public Result visitExpressionTuple(Tuple x) { java.util.List<org.meta_environment.rascal.ast.Expression> elements = x .getElements(); IValue[] values = new IValue[elements.size()]; Type[] types = new Type[elements.size()]; for (int i = 0; i < elements.size(); i++) { Result resultElem = elements.get(i).accept(this); types[i] = resultElem.getType(); values[i] = resultElem.getValue(); } return result(tf.tupleType(types), vf.tuple(values)); } @Override public Result visitExpressionGetAnnotation( org.meta_environment.rascal.ast.Expression.GetAnnotation x) { Result base = x.getExpression().accept(this); String annoName = x.getName().toString(); Type annoType = callStack.peek().getAnnotationType(base.getType(), annoName); if (annoType == null) { throw new UndeclaredAnnotationError(annoName ,base.getType(), x); } IValue annoValue = ((IConstructor) base.getValue()).getAnnotation(annoName); if (annoValue == null) { throw RuntimeExceptionFactory.noSuchAnnotation(annoName); } return result(annoType, annoValue); } @Override public Result visitExpressionSetAnnotation( org.meta_environment.rascal.ast.Expression.SetAnnotation x) { Result base = x.getExpression().accept(this); String annoName = x.getName().toString(); Result anno = x.getValue().accept(this); Type annoType = callStack.peek().getAnnotationType(base.getType(), annoName); if (annoType == null) { throw new UndeclaredAnnotationError(annoName ,base.getType(), x); } if(!anno.getType().isSubtypeOf(annoType)){ throw new UnexpectedTypeError(annoType, anno.getType(), x); } IValue annotatedBase = ((IConstructor) base.getValue()).setAnnotation(annoName, anno.getValue()); return result(base.getType(), annotatedBase); } public static void widenArgs(Result left, Result right) { TypeFactory tf = TypeFactory.getInstance(); Type leftValType = left.getValueType(); Type rightValType = right.getValueType(); if (leftValType.isIntegerType() && rightValType.isRealType()) { if(left.getType().isIntegerType()){ left.setType(tf.realType()); } left.setValue(((IInteger) left.getValue()).toReal()); } else if (leftValType.isRealType() && rightValType.isIntegerType()) { if(right.getType().isIntegerType()){ right.setType(tf.realType()); } right.setValue(((IInteger) right.getValue()).toReal()); } /*else if(left.getType().isConstructorType()){ left.getType() = left.getType().getAbstractDataType(); } else if(right.getType().isConstructorType()){ right.getType() = right.getType().getAbstractDataType(); } */ } @Override public Result visitExpressionAddition(Addition x) { Result left = x.getLhs().accept(this); Result right = x.getRhs().accept(this); widenArgs(left, right); Type resultType = left.getType().lub(right.getType()); //System.err.println("left=" + left + "; right=" + right + "; resulType=" + resultType); // Integer if (left.getType().isIntegerType() && right.getType().isIntegerType()) { return result(((IInteger) left.getValue()).add((IInteger) right.getValue())); } //Real if (left.getType().isRealType() && right.getType().isRealType()) { return result(((IReal) left.getValue()).add((IReal) right.getValue())); } //String if (left.getType().isStringType() && right.getType().isStringType()) { return result(vf.string(((IString) left.getValue()).getValue() + ((IString) right.getValue()).getValue())); } //List if (left.getType().isListType()){ if(right.getType().isListType()) { return result(resultType, ((IList) left.getValue()) .concat((IList) right.getValue())); } if(right.getType().isSubtypeOf(left.getType().getElementType())){ return result(left.getType(), ((IList)left.getValue()).append(right.getValue())); } } if (right.getType().isListType()){ if(left.getType().isSubtypeOf(right.getType().getElementType())){ return result(right.getType(), ((IList)right.getValue()).insert(left.getValue())); } } //Relation if (left.getType().isRelationType() && right.getType().isRelationType()) { if(LAZY) return result(resultType, new LazyUnion(((ISet) left.getValue()), (ISet) right.getValue())); else return result(resultType, ((ISet) left.getValue()) .union((ISet) right.getValue())); } //Set if (left.getType().isSetType()){ if(right.getType().isSetType()) { if(LAZY) return result(resultType, new LazyUnion(((ISet) left.getValue()), (ISet) right.getValue())); else return result(resultType, ((ISet) left.getValue()) .union((ISet) right.getValue())); } if(right.getType().isSubtypeOf(left.getType().getElementType())){ if(LAZY) return result(left.getType(), new LazyInsert((ISet)left.getValue(), right.getValue())); else return result(left.getType(), ((ISet)left.getValue()).insert(right.getValue())); } } if (right.getType().isSetType()){ if(left.getType().isSubtypeOf(right.getType().getElementType())){ if(LAZY) return result(right.getType(), new LazyInsert((ISet)right.getValue(), left.getValue())); return result(right.getType(), ((ISet)right.getValue()).insert(left.getValue())); } } //Map if (left.getType().isMapType() && right.getType().isMapType()) { return result(resultType, ((IMap) left.getValue()) //TODO: is this the right operation? .join((IMap) right.getValue())); } //Tuple if(left.getType().isTupleType() && right.getType().isTupleType()) { Type leftType = left.getType(); Type rightType = right.getType(); int leftArity = leftType.getArity(); int rightArity = rightType.getArity(); int newArity = leftArity + rightArity; Type fieldTypes[] = new Type[newArity]; String fieldNames[] = new String[newArity]; IValue fieldValues[] = new IValue[newArity]; for(int i = 0; i < leftArity; i++){ fieldTypes[i] = leftType.getFieldType(i); fieldNames[i] = leftType.getFieldName(i); fieldValues[i] = ((ITuple) left.getValue()).get(i); } for(int i = 0; i < rightArity; i++){ fieldTypes[leftArity + i] = rightType.getFieldType(i); fieldNames[leftArity + i] = rightType.getFieldName(i); fieldValues[leftArity + i] = ((ITuple) right.getValue()).get(i); } //TODO: avoid null fieldnames for(int i = 0; i < newArity; i++){ if(fieldNames[i] == null){ fieldNames[i] = "f" + String.valueOf(i); } } Type newTupleType = tf.tupleType(fieldTypes, fieldNames); return result(newTupleType, vf.tuple(fieldValues)); } throw new UnsupportedOperationError("+", left.getType(), right.getType(),x); } @Override public Result visitExpressionSubtraction(Subtraction x) { Result left = x.getLhs().accept(this); Result right = x.getRhs().accept(this); Type resultType = left.getType().lub(right.getType()); widenArgs(left, right); // Integer if (left.getType().isIntegerType() && right.getType().isIntegerType()) { return result(((IInteger) left.getValue()).subtract((IInteger) right.getValue())); } // Real if (left.getType().isRealType() && right.getType().isRealType()) { return result(((IReal) left.getValue()).subtract((IReal) right.getValue())); } // List if (left.getType().isListType() && right.getType().isListType()) { IListWriter w = left.getType().writer(vf); IList listLeft = (IList)left.getValue(); IList listRight = (IList)right.getValue(); int lenLeft = listLeft.length(); int lenRight = listRight.length(); for(int i = lenLeft-1; i > 0; i--) { boolean found = false; IValue leftVal = listLeft.get(i); for(int j = 0; j < lenRight; j++){ if(leftVal.isEqual(listRight.get(j))){ found = true; break; } } if(!found){ w.insert(leftVal); } } return result(left.getType(), w.done()); } // Set if (left.getType().isSetType()){ if(right.getType().isSetType()) { return result(resultType, ((ISet) left.getValue()) .subtract((ISet) right.getValue())); } if(right.getType().isSubtypeOf(left.getType().getElementType())){ return result(left.getType(), ((ISet)left.getValue()) .subtract(vf.set(right.getValue()))); } } // Map if (left.getType().isMapType() && right.getType().isMapType()) { return result(resultType, ((IMap) left.getValue()) .remove((IMap) right.getValue())); } //Relation if (left.getType().isRelationType() && right.getType().isRelationType()) { return result(resultType, ((ISet) left.getValue()) .subtract((ISet) right.getValue())); } throw new UnsupportedOperationError("-", left.getType(), right.getType(),x); } @Override public Result visitExpressionNegative(Negative x) { Result arg = x.getArgument().accept(this); if (arg.getType().isIntegerType()) { return result(((IInteger) arg.getValue()).negate()); } else if (arg.getType().isRealType()) { return result(((IReal) arg.getValue()).negate()); } else { throw new UnsupportedOperationError("-", arg.getType(), x); } } @Override public Result visitExpressionProduct(Product x) { Result left = x.getLhs().accept(this); Result right = x.getRhs().accept(this); widenArgs(left, right); //Integer if (left.getType().isIntegerType() && right.getType().isIntegerType()) { return result(((IInteger) left.getValue()).multiply((IInteger) right.getValue())); } //Real else if (left.getType().isRealType() && right.getType().isRealType()) { return result(((IReal) left.getValue()).multiply((IReal) right.getValue())); } // List else if (left.getType().isListType() && right.getType().isListType()){ Type leftElementType = left.getType().getElementType(); Type rightElementType = right.getType().getElementType(); Type resultType = tf.listType(tf.tupleType(leftElementType, rightElementType)); IListWriter w = resultType.writer(vf); for(IValue v1 : (IList) left.getValue()){ for(IValue v2 : (IList) right.getValue()){ w.append(vf.tuple(v1, v2)); } } return result(resultType, w.done()); } // Relation else if(left.getType().isRelationType() && right.getType().isRelationType()){ Type leftElementType = left.getType().getElementType(); Type rightElementType = right.getType().getElementType(); int leftArity = leftElementType.getArity(); int rightArity = rightElementType.getArity(); int newArity = leftArity + rightArity; Type fieldTypes[] = new Type[newArity]; String fieldNames[] = new String[newArity]; for(int i = 0; i < leftArity; i++){ fieldTypes[i] = leftElementType.getFieldType(i); fieldNames[i] = leftElementType.getFieldName(i); } for(int i = 0; i < rightArity; i++){ fieldTypes[leftArity + i] = rightElementType.getFieldType(i); fieldNames[leftArity + i] = rightElementType.getFieldName(i); } // TODO: avoid empty field names for(int i = 0; i < newArity; i++){ if(fieldNames[i] == null){ fieldNames[i] = "f" + String.valueOf(i); } } Type resElementType = tf.tupleType(fieldTypes, fieldNames); Type resultType = tf.relTypeFromTuple(resElementType); IRelationWriter w = resultType.writer(vf); for(IValue v1 : (IRelation) left.getValue()){ IValue elementValues[] = new IValue[newArity]; for(int i = 0; i < leftArity; i++){ elementValues[i] = ((ITuple) v1).get(i); } for(IValue v2 : (IRelation) right.getValue()){ for(int i = 0; i <rightArity; i++){ elementValues[leftArity + i] = ((ITuple) v2).get(i); } w.insert(vf.tuple(elementValues)); } } return result(resultType, w.done()); } //Set else if (left.getType().isSetType() && right.getType().isSetType()){ Type leftElementType = left.getType().getElementType(); Type rightElementType = right.getType().getElementType(); Type resultType = tf.relType(leftElementType, rightElementType); IRelationWriter w = resultType.writer(vf); for(IValue v1 : (ISet) left.getValue()){ for(IValue v2 : (ISet) right.getValue()){ w.insert(vf.tuple(v1, v2)); } } return result(resultType, w.done()); } else { throw new UnsupportedOperationError("*", left.getType(), right.getType(),x); } } @Override public Result visitExpressionDivision(Division x) { Result left = x.getLhs().accept(this); Result right = x.getRhs().accept(this); widenArgs(left, right); try { //Integer if (left.getType().isIntegerType() && right.getType().isIntegerType()) { return result(((IInteger) left.getValue()).divide((IInteger) right.getValue())); } // Real else if (left.getType().isRealType() && right.getType().isRealType()) { // TODO magic constant 80*80 should dissappear when Tijs is done return result(((IReal) left.getValue()).divide((IReal) right.getValue(), 80*80)); } else { throw new UnsupportedOperationError("/", left.getType(), right.getType(),x); } } catch (ArithmeticException e){ // TODO throw better exception throw new ImplementationError(e.getMessage()); } } @Override public Result visitExpressionModulo(Modulo x) { Result left = x.getLhs().accept(this); Result right = x.getRhs().accept(this); if (left.getType().isIntegerType() && right.getType().isIntegerType()) { return result(((IInteger) left.getValue()).remainder((IInteger) right.getValue())); } else { throw new UnsupportedOperationError("%", left.getType(), right.getType(),x); } } @Override public Result visitExpressionBracket(Bracket x) { return x.getExpression().accept(this); } @Override public Result visitExpressionIntersection(Intersection x) { Result left = x.getLhs().accept(this); Result right = x.getRhs().accept(this); Type resultType = left.getType().lub(right.getType()); //Set if (left.getType().isSetType() && right.getType().isSetType()) { return result(resultType, ((ISet) left.getValue()) .intersect((ISet) right.getValue())); } //Map else if (left.getType().isMapType() && right.getType().isMapType()) { return result(resultType, ((IMap) left.getValue()) .common((IMap) right.getValue())); } //Relation else if (left.getType().isRelationType() && right.getType().isRelationType()) { return result(resultType, ((ISet) left.getValue()) .intersect((ISet) right.getValue())); } else { throw new UnsupportedOperationError("&", left.getType() , right.getType(), x); } } @Override public Result visitExpressionOr(Or x) { return new OrEvaluator(x, this).next(); } @Override public Result visitExpressionAnd(And x) { return new AndEvaluator(x, this).next(); } @Override public Result visitExpressionNegation(Negation x) { return new NegationEvaluator(x, this).next(); } @Override public Result visitExpressionImplication(Implication x) { return new ImplicationEvaluator(x, this).next(); } @Override public Result visitExpressionEquivalence(Equivalence x) { return new EquivalenceEvaluator(x, this).next(); } // TODO factor out into Result or a subclass thereof public static boolean equals(Result left, Result right){ widenArgs(left, right); //System.err.println("equals: left=" + left + ", right=" + right + " comparable=" + left.getType().comparable(right.getType())); if (left.getType().comparable(right.getType())) { return compare(left, right) == 0; } else { return false; //TODO; type error } } @Override public Result visitExpressionEquals( org.meta_environment.rascal.ast.Expression.Equals x) { Result left = x.getLhs().accept(this); Result right = x.getRhs().accept(this); widenArgs(left, right); /* if (!left.getType().comparable(right.getType())) { throw new RascalTypeError("Arguments of equals have incomparable types: " + left.getType() + " and " + right.getType(), x); } */ return result(vf.bool(equals(left, right))); } @Override public Result visitExpressionOperatorAsValue(OperatorAsValue x) { // TODO throw new NotYetImplemented(x); } @Override public Result visitExpressionLocation(Location x){ String urlText = x.getUrl().toString(); Result length = x.getLength().accept(this); int iLength = ((IInteger) length.getValue()).intValue(); Result offset = x.getOffset().accept(this); int iOffset = ((IInteger) offset.getValue()).intValue(); Result beginLine = x.getBeginLine().accept(this); int iBeginLine = ((IInteger) beginLine.getValue()).intValue(); Result endLine = x.getEndLine().accept(this); int iEndLine = ((IInteger) endLine.getValue()).intValue(); Result beginColumn = x.getBeginColumn().accept(this); int iBeginColumn = ((IInteger) beginColumn.getValue()).intValue(); Result endColumn = x.getEndColumn().accept(this); int iEndColumn = ((IInteger) endColumn.getValue()).intValue(); try { URL url = new URL(urlText); ISourceLocation r = vf.sourceLocation(url, iOffset, iLength, iBeginLine, iEndLine, iBeginColumn, iEndColumn); return result(tf.sourceLocationType(), r); } catch (MalformedURLException e){ throw new SyntaxError("URL", x.getLocation()); } } @Override public Result visitExpressionClosure(Closure x) { Type formals = te.eval(x.getParameters(), peek()); Type returnType = evalType(x.getType()); return new Lambda(x, this, returnType, "", formals, x.getParameters().isVarArgs(), x.getStatements(), peek()); } @Override public Result visitExpressionVoidClosure(VoidClosure x) { Type formals = te.eval(x.getParameters(), peek()); return new Lambda(x, this, tf.voidType(), "", formals, x.getParameters().isVarArgs(), x.getStatements(), peek()); } @Override public Result visitExpressionFieldUpdate(FieldUpdate x) { Result expr = x.getExpression().accept(this); Result repl = x.getReplacement().accept(this); String name = x.getKey().toString(); try { if (expr.getType().isTupleType()) { Type tuple = expr.getType(); Type argType = tuple.getFieldType(name); ITuple value = (ITuple) expr.getValue(); checkType(repl.getType(), argType); return result(expr.getType(), value.set(name, repl.getValue())); } else if (expr.getType().isAbstractDataType() || expr.getType().isConstructorType()) { Type node = ((IConstructor) expr.getValue()).getConstructorType(); if (!node.hasField(name)) { throw new UndeclaredFieldError(name, expr.getValueType(), x); } int index = node.getFieldIndex(name); checkType(repl.getType(), node.getFieldType(index)); return result(expr.getType(), ((IConstructor) expr.getValue()).set(index, repl.getValue())); } else if (expr.getType().isSourceLocationType()){ ISourceLocation loc = (ISourceLocation) expr.getValue(); return sourceLocationFieldUpdate(loc, name, repl.getValue(),repl.getType(), x); } else { throw new UnsupportedOperationError("Field update", expr.getType(), x); } } catch (UndeclaredFieldException e) { // TODO I don't think that this should ever happen (ImplementationError?) throw new UndeclaredFieldError(e.getLabel(), expr.getType(), x); } } protected Result sourceLocationFieldUpdate(ISourceLocation loc, String field, IValue value, Type type, AbstractAST x){ int iLength = loc.getLength(); int iOffset = loc.getOffset(); int iBeginLine = loc.getBeginLine(); int iBeginColumn = loc.getBeginColumn(); int iEndLine = loc.getEndLine(); int iEndColumn = loc.getEndColumn(); String urlText = loc.getURL().toString(); if(field.equals("url")){ if(!type.isStringType()) throw new UnexpectedTypeError(tf.stringType(), type, x); urlText = ((IString) value).getValue(); } else { if(!type.isIntegerType()) { throw new UnexpectedTypeError(tf.integerType(), type, x); } if(field.equals("length")){ iLength = ((IInteger) value).intValue(); } else if(field.equals("offset")){ iOffset = ((IInteger) value).intValue(); } else if(field.equals("beginLine")){ iBeginLine = ((IInteger) value).intValue(); } else if(field.equals("beginColumn")){ iBeginColumn = ((IInteger) value).intValue(); } else if(field.equals("endLine")){ iEndLine = ((IInteger) value).intValue(); } else if(field.equals("endColumn")){ iEndColumn = ((IInteger) value).intValue(); } else { throw new UndeclaredFieldError(field, tf.sourceLocationType(), x); } } try { URL url = new URL(urlText); ISourceLocation nloc = vf.sourceLocation(url, iOffset, iLength, iBeginLine, iEndLine, iBeginColumn, iEndColumn); return result(tf.sourceLocationType(), nloc); } catch (MalformedURLException e) { throw new SyntaxError("URL", x.getLocation()); } catch (IllegalArgumentException e) { throw RuntimeExceptionFactory.illegalArgument(); } } @Override public Result visitExpressionLexical(Lexical x) { throw new NotYetImplemented(x);// TODO } @Override public Result visitExpressionRange(Range x) { IListWriter w = vf.listWriter(tf.integerType()); Result from = x.getFirst().accept(this); Result to = x.getLast().accept(this); if (!from.getType().isIntegerType()) { throw new UnexpectedTypeError(tf.integerType(), from.getType(), x.getFirst()); } if (!to.getType().isIntegerType()) { throw new UnexpectedTypeError(tf.integerType(), to.getType(), x.getLast()); } IInteger iFrom = ((IInteger) from.getValue()); IInteger iTo = ((IInteger) to.getValue()); IInteger one = vf.integer(1); if (iTo.less(iFrom).getValue()) { while (iFrom.greaterEqual(iTo).getValue()) { w.append(iFrom); iFrom = iFrom.subtract(one); } } else { while (iFrom.lessEqual(iTo).getValue()) { w.append(iFrom); iFrom = iFrom.add(one); } } return result(tf.listType(tf.integerType()), w.done()); } @Override public Result visitExpressionStepRange(StepRange x) { IListWriter w = vf.listWriter(tf.integerType()); Result from = x.getFirst().accept(this); Result to = x.getLast().accept(this); Result second = x.getSecond().accept(this); if (!from.getType().isIntegerType()) { throw new UnexpectedTypeError(tf.integerType(), from.getType(), x.getFirst()); } if (!to.getType().isIntegerType()) { throw new UnexpectedTypeError(tf.integerType(), to.getType(), x.getLast()); } if (!second.getType().isIntegerType()) { throw new UnexpectedTypeError(tf.integerType(), second.getType(), x.getSecond()); } IInteger iFrom = ((IInteger) from.getValue()); IInteger iSecond = ((IInteger) second.getValue()); IInteger iTo = ((IInteger) to.getValue()); IInteger diff = iSecond.subtract(iFrom); if (iFrom.lessEqual(iTo).getValue() && diff.greater(vf.integer(0)).getValue()) { do { w.append(iFrom); iFrom = iFrom.add(diff); } while (iFrom.lessEqual(iTo).getValue()); } else if(iFrom.greaterEqual(iTo).getValue() && diff.less(vf.integer(0)).getValue()) { do { w.append(iFrom); iFrom = iFrom.add(diff); } while (iFrom.greaterEqual(iTo).getValue()); } return result(tf.listType(tf.integerType()), w.done()); } @Override public Result visitExpressionTypedVariable(TypedVariable x) { throw new SyntaxError("Typed variable outside matching context", x.getLocation()); } private boolean matchAndEval(IValue subject, org.meta_environment.rascal.ast.Expression pat, Statement stat){ MatchPattern mp = evalPattern(pat); mp.initMatch(subject, peek()); lastPattern = mp; //System.err.println("matchAndEval: subject=" + subject + ", pat=" + pat); try { push(); // Create a separate scope for match and statement peek().storeVariable("subject", result(subject.getType(), subject)); while(mp.hasNext()){ //System.err.println("matchAndEval: mp.hasNext()==true"); if(mp.next()){ //System.err.println("matchAndEval: mp.next()==true"); try { checkPoint(peek()); //System.err.println(stat.toString()); stat.accept(this); commit(peek()); return true; } catch (Failure e){ //System.err.println("failure occurred"); rollback(peek()); } } } } finally { pop(); } return false; } private boolean matchEvalAndReplace(IValue subject, org.meta_environment.rascal.ast.Expression pat, java.util.List<Expression> conditions, Expression replacementExpr){ MatchPattern mp = evalPattern(pat); mp.initMatch(subject, peek()); lastPattern = mp; //System.err.println("matchEvalAndReplace: subject=" + subject + ", pat=" + pat + ", conditions=" + conditions); try { push(); // Create a separate scope for match and statement while(mp.hasNext()){ //System.err.println("mp.hasNext()==true; mp=" + mp); if(mp.next()){ try { boolean trueConditions = true; for(Expression cond : conditions){ //System.err.println("cond = " + cond); if(!cond.accept(this).isTrue()){ trueConditions = false; break; } } if(trueConditions){ throw new org.meta_environment.rascal.interpreter.control_exceptions.Insert(replacementExpr.accept(this)); } } catch (Failure e){ //System.err.println("failure occurred"); } } } } finally { pop(); } return false; } @Override public Result visitStatementSwitch(Switch x) { Result subject = x.getExpression().accept(this); for(Case cs : x.getCases()){ if(cs.isDefault()){ return cs.getStatement().accept(this); } org.meta_environment.rascal.ast.Rule rule = cs.getRule(); if(rule.isArbitrary() && matchAndEval(subject.getValue(), rule.getPattern(), rule.getStatement())){ return result(); } else if(rule.isGuarded()) { org.meta_environment.rascal.ast.Type tp = rule.getType(); Type t = evalType(tp); if(subject.getType().isSubtypeOf(t) && matchAndEval(subject.getValue(), rule.getPattern(), rule.getStatement())){ return result(); } } else if(rule.isReplacing()){ throw new NotYetImplemented(rule); } } return null; } @Override public Result visitExpressionVisit(Visit x) { return x.getVisit().accept(this); } /* * TraverseResult contains the value returned by a traversal * and a changed flag that indicates whether the value itself or * any of its children has been changed during the traversal. */ class TraverseResult { boolean matched; // Some rule matched; IValue value; // Result of the boolean changed; // Original subject has been changed TraverseResult(boolean someMatch, IValue value){ this.matched = someMatch; this.value = value; this.changed = false; } TraverseResult(IValue value){ this.matched = false; this.value = value; this.changed = false; } TraverseResult(IValue value, boolean changed){ this.matched = true; this.value = value; this.changed = changed; } TraverseResult(boolean someMatch, IValue value, boolean changed){ this.matched = someMatch; this.value = value; this.changed = changed; } } /* * CaseOrRule is the union of a Case or a Rule and allows the sharing of * traversal code for both. */ class CasesOrRules { private java.util.List<Case> cases; private java.util.List<org.meta_environment.rascal.ast.Rule> rules; @SuppressWarnings("unchecked") CasesOrRules(java.util.List<?> casesOrRules){ if(casesOrRules.get(0) instanceof Case){ this.cases = (java.util.List<Case>) casesOrRules; } else { rules = (java.util.List<org.meta_environment.rascal.ast.Rule>)casesOrRules; } } public boolean hasRules(){ return rules != null; } public boolean hasCases(){ return cases != null; } public int length(){ return (cases != null) ? cases.size() : rules.size(); } public java.util.List<Case> getCases(){ return cases; } public java.util.List<org.meta_environment.rascal.ast.Rule> getRules(){ return rules; } } private TraverseResult traverse(IValue subject, CasesOrRules casesOrRules, DIRECTION direction, PROGRESS progress, FIXEDPOINT fixedpoint) { //System.err.println("traverse: subject=" + subject + ", casesOrRules=" + casesOrRules); do { TraverseResult tr = traverseOnce(subject, casesOrRules, direction, progress); if(fixedpoint == FIXEDPOINT.Yes){ if (!tr.changed) { return tr; } subject = tr.value; } else { return tr; } } while (true); } /* * StringReplacement represents a single replacement in the subject string. */ private class StringReplacement { int start; int end; String replacement; StringReplacement(int start, int end, String repl){ this.start = start; this.end = end; replacement = repl; } @Override public String toString(){ return "StringReplacement(" + start + ", " + end + ", " + replacement + ")"; } } /* * singleCase returns a single case or rules if casesOrRueles has length 1 and null otherwise. */ private Object singleCase(CasesOrRules casesOrRules){ if(casesOrRules.length() == 1){ if(casesOrRules.hasCases()){ return casesOrRules.getCases().get(0); } else { return casesOrRules.getRules().get(0); } } return null; } /* * traverString implements a visit of a string subject and applies the set of cases * for all substrings of the subject. At the end, all replacements are applied and the modified * subject is returned. */ private TraverseResult traverseString(IString subject, CasesOrRules casesOrRules){ String subjectString = subject.getValue(); int len = subjectString.length(); java.util.List<StringReplacement> replacements = new ArrayList<StringReplacement>(); boolean matched = false; boolean changed = false; int cursor = 0; Case cs = (Case) singleCase(casesOrRules); RegExpPatternEvaluator re = new RegExpPatternEvaluator(vf, peek()); if(cs != null && cs.isRule() && re.isRegExpPattern(cs.getRule().getPattern())){ /* * In the frequently occurring case that there is one case with a regexp as pattern, * we can delegate all the work to the regexp matcher. */ org.meta_environment.rascal.ast.Rule rule = cs.getRule(); Expression patexp = rule.getPattern(); MatchPattern mp = evalPattern(patexp); mp.initMatch(subject, peek()); try { push(); // a separate scope for match and statement/replacement while(mp.hasNext()){ if(mp.next()){ try { if(rule.isReplacing()){ Replacement repl = rule.getReplacement(); boolean trueConditions = true; if(repl.isConditional()){ for(Expression cond : repl.getConditions()){ Result res = cond.accept(this); if(!res.isTrue()){ // TODO: How about alternatives? trueConditions = false; break; } } } if(trueConditions){ throw new org.meta_environment.rascal.interpreter.control_exceptions.Insert(repl.getReplacementExpression().accept(this)); } } else { rule.getStatement().accept(this); } } catch (org.meta_environment.rascal.interpreter.control_exceptions.Insert e){ changed = true; IValue repl = e.getValue().getValue(); if(repl.getType().isStringType()){ int start = ((RegExpPatternValue) mp).getStart(); int end = ((RegExpPatternValue) mp).getEnd(); replacements.add(new StringReplacement(start, end, ((IString)repl).getValue())); } else { throw new UnexpectedTypeError(tf.stringType(),repl.getType(), rule); } } catch (Failure e){ //System.err.println("failure occurred"); } } } } finally { pop(); } } else { /* * In all other cases we generate subsequent substrings subject[0,len], subject[1,len] ... * and try to match all the cases. * Performance issue: we create a lot of garbage by producing all these substrings. */ while(cursor < len){ //System.err.println("cursor = " + cursor); try { TraverseResult tr = applyCasesOrRules(vf.string(subjectString.substring(cursor, len)), casesOrRules); matched |= tr.matched; changed |= tr.changed; //System.err.println("matched=" + matched + ", changed=" + changed); cursor++; } catch (org.meta_environment.rascal.interpreter.control_exceptions.Insert e){ IValue repl = e.getValue().getValue(); if(repl.getType().isStringType()){ int start; int end; if(lastPattern instanceof RegExpPatternValue){ start = ((RegExpPatternValue)lastPattern).getStart(); end = ((RegExpPatternValue)lastPattern).getEnd(); } else if(lastPattern instanceof AbstractPatternLiteral){ start = 0; end = ((IString)repl).getValue().length(); } else { throw new SyntaxError("Illegal pattern " + lastPattern + " in string visit", getCurrentStatement().getLocation()); } replacements.add(new StringReplacement(cursor + start, cursor + end, ((IString)repl).getValue())); matched = changed = true; cursor += end; } else { throw new UnexpectedTypeError(tf.stringType(),repl.getType(), getCurrentStatement()); } } } } if(!changed){ return new TraverseResult(matched, subject, changed); } /* * The replacements are now known. Create a version of the subject with all replacement applied. */ StringBuffer res = new StringBuffer(); cursor = 0; for(StringReplacement sr : replacements){ for( ;cursor < sr.start; cursor++){ res.append(subjectString.charAt(cursor)); } cursor = sr.end; res.append(sr.replacement); } for( ; cursor < len; cursor++){ res.append(subjectString.charAt(cursor)); } return new TraverseResult(matched, vf.string(res.toString()), changed); } /* * traverseOnce: traverse an arbitrary IVAlue once. Implements the strategies bottomup/topdown. */ private TraverseResult traverseOnce(IValue subject, CasesOrRules casesOrRules, DIRECTION direction, PROGRESS progress){ Type subjectType = subject.getType(); boolean matched = false; boolean changed = false; IValue result = subject; //System.err.println("traverseOnce: " + subject + ", type=" + subject.getType()); if(subjectType.isStringType()){ return traverseString((IString) subject, casesOrRules); } if(direction == DIRECTION.TopDown){ TraverseResult tr = traverseTop(subject, casesOrRules); matched |= tr.matched; changed |= tr.changed; if((progress == PROGRESS.Breaking) && changed){ return tr; } subject = tr.value; } if(subjectType.isAbstractDataType()){ IConstructor cons = (IConstructor)subject; if(cons.arity() == 0){ result = subject; } else { IValue args[] = new IValue[cons.arity()]; for(int i = 0; i < cons.arity(); i++){ TraverseResult tr = traverseOnce(cons.get(i), casesOrRules, direction, progress); matched |= tr.matched; changed |= tr.changed; args[i] = tr.value; } IConstructor rcons = vf.constructor(cons.getConstructorType(), args); result = rcons.setAnnotations(cons.getAnnotations()); } } else if(subjectType.isNodeType()){ INode node = (INode)subject; if(node.arity() == 0){ result = subject; } else { IValue args[] = new IValue[node.arity()]; for(int i = 0; i < node.arity(); i++){ TraverseResult tr = traverseOnce(node.get(i), casesOrRules, direction, progress); matched |= tr.matched; changed |= tr.changed; args[i] = tr.value; } result = vf.node(node.getName(), args).setAnnotations(node.getAnnotations()); } } else if(subjectType.isListType()){ IList list = (IList) subject; int len = list.length(); if(len > 0){ IListWriter w = list.getType().writer(vf); for(int i = len - 1; i >= 0; i--){ TraverseResult tr = traverseOnce(list.get(i), casesOrRules, direction, progress); matched |= tr.matched; changed |= tr.changed; w.insert(tr.value); } result = w.done(); } else { result = subject; } } else if(subjectType.isSetType()){ ISet set = (ISet) subject; if(!set.isEmpty()){ ISetWriter w = set.getType().writer(vf); for(IValue v : set){ TraverseResult tr = traverseOnce(v, casesOrRules, direction, progress); matched |= tr.matched; changed |= tr.changed; w.insert(tr.value); } result = w.done(); } else { result = subject; } } else if (subjectType.isMapType()) { IMap map = (IMap) subject; if(!map.isEmpty()){ IMapWriter w = map.getType().writer(vf); Iterator<Entry<IValue,IValue>> iter = map.entryIterator(); while (iter.hasNext()) { Entry<IValue,IValue> entry = iter.next(); TraverseResult tr = traverseOnce(entry.getKey(), casesOrRules, direction, progress); matched |= tr.matched; changed |= tr.changed; IValue newKey = tr.value; tr = traverseOnce(entry.getValue(), casesOrRules, direction, progress); matched |= tr.matched; changed |= tr.changed; IValue newValue = tr.value; w.put(newKey, newValue); } result = w.done(); } else { result = subject; } } else if(subjectType.isTupleType()){ ITuple tuple = (ITuple) subject; int arity = tuple.arity(); IValue args[] = new IValue[arity]; for(int i = 0; i < arity; i++){ TraverseResult tr = traverseOnce(tuple.get(i), casesOrRules, direction, progress); matched |= tr.matched; changed |= tr.changed; args[i] = tr.value; } result = vf.tuple(args); } else { result = subject; } if(direction == DIRECTION.BottomUp){ if((progress == PROGRESS.Breaking) && changed){ return new TraverseResult(matched, result, changed); } else { TraverseResult tr = traverseTop(result, casesOrRules); matched |= tr.matched; changed |= tr.changed; return new TraverseResult(matched, tr.value, changed); } } return new TraverseResult(matched,result,changed); } /** * Replace an old subject by a new one as result of an insert statement. */ private TraverseResult replacement(IValue oldSubject, IValue newSubject){ return new TraverseResult(true, newSubject, true); } /** * Loop over all cases or rules. */ private TraverseResult applyCasesOrRules(IValue subject, CasesOrRules casesOrRules) { if(casesOrRules.hasCases()){ for (Case cs : casesOrRules.getCases()) { if (cs.isDefault()) { cs.getStatement().accept(this); return new TraverseResult(true,subject); } else { TraverseResult tr = applyOneRule(subject, cs.getRule()); if(tr.matched){ //System.err.println(" *** matches ***"); return tr; } } } } else { //System.err.println("hasRules"); for(org.meta_environment.rascal.ast.Rule rule : casesOrRules.getRules()){ //System.err.println(rule); TraverseResult tr = applyOneRule(subject, rule); //System.err.println("rule fails"); if(tr.matched){ //System.err.println(" *** matches ***"); return tr; } } } //System.err.println("applyCasesorRules does not match"); return new TraverseResult(subject); } /* * traverseTop: traverse the outermost symbol of the subject. */ private TraverseResult traverseTop(IValue subject, CasesOrRules casesOrRules) { //System.err.println("traversTop(" + subject + ")"); try { return applyCasesOrRules(subject, casesOrRules); } catch (org.meta_environment.rascal.interpreter.control_exceptions.Insert e) { return replacement(subject, e.getValue().getValue()); } } /* * applyOneRule: try to apply one rule to the subject. */ private TraverseResult applyOneRule(IValue subject, org.meta_environment.rascal.ast.Rule rule) { //System.err.println("applyOneRule: subject=" + subject + ", type=" + subject.getType() + ", rule=" + rule); if (rule.isArbitrary()){ if(matchAndEval(subject, rule.getPattern(), rule.getStatement())) { return new TraverseResult(true, subject); } } else if (rule.isGuarded()) { org.meta_environment.rascal.ast.Type tp = rule.getType(); Type type = evalType(tp); rule = rule.getRule(); if (subject.getType().isSubtypeOf(type) && matchAndEval(subject, rule.getPattern(), rule.getStatement())) { return new TraverseResult(true, subject); } } else if (rule.isReplacing()) { Replacement repl = rule.getReplacement(); java.util.List<Expression> conditions = repl.isConditional() ? repl.getConditions() : new ArrayList<Expression>(); if(matchEvalAndReplace(subject, rule.getPattern(), conditions, repl.getReplacementExpression())){ return new TraverseResult(true, subject); } } else { throw new ImplementationError("Impossible case in rule"); } return new TraverseResult(subject); } @Override public Result visitVisitDefaultStrategy(DefaultStrategy x) { IValue subject = x.getSubject().accept(this).getValue(); java.util.List<Case> cases = x.getCases(); TraverseResult tr = traverse(subject, new CasesOrRules(cases), DIRECTION.BottomUp, PROGRESS.Continuing, FIXEDPOINT.No); return normalizedResult(tr.value.getType(), tr.value); } @Override public Result visitVisitGivenStrategy(GivenStrategy x) { IValue subject = x.getSubject().accept(this).getValue(); Type subjectType = subject.getType(); if(subjectType.isConstructorType()){ subjectType = subjectType.getAbstractDataType(); } java.util.List<Case> cases = x.getCases(); Strategy s = x.getStrategy(); DIRECTION direction = DIRECTION.BottomUp; PROGRESS progress = PROGRESS.Continuing; FIXEDPOINT fixedpoint = FIXEDPOINT.No; if(s.isBottomUp()){ direction = DIRECTION.BottomUp; } else if(s.isBottomUpBreak()){ direction = DIRECTION.BottomUp; progress = PROGRESS.Breaking; } else if(s.isInnermost()){ direction = DIRECTION.BottomUp; fixedpoint = FIXEDPOINT.Yes; } else if(s.isTopDown()){ direction = DIRECTION.TopDown; } else if(s.isTopDownBreak()){ direction = DIRECTION.TopDown; progress = PROGRESS.Breaking; } else if(s.isOutermost()){ direction = DIRECTION.TopDown; fixedpoint = FIXEDPOINT.Yes; } else { throw new ImplementationError("Unknown strategy " + s); } TraverseResult tr = traverse(subject, new CasesOrRules(cases), direction, progress, fixedpoint); return normalizedResult(subjectType, tr.value); } @Override public Result visitExpressionNonEquals( org.meta_environment.rascal.ast.Expression.NonEquals x) { Result left = x.getLhs().accept(this); Result right = x.getRhs().accept(this); if (!left.getType().comparable(right.getType())) { throw new UnexpectedTypeError(left.getType(), right.getType(), x); } return result(vf.bool(compare(left, right) != 0)); } // TODO distribute over subclasses of Result public static int compare(Result left, Result right){ // compare must use run-time types because it is complete for all types // even if statically two values have type 'value' but one is an int 1 // and the other is Real 1.0 they must be equal. // TODO distribute this method over subclasses of Result, // IntegerResult to MapResult which implement equals and compare and add and // subtract, etc. widenArgs(left, right); Type leftType = left.getValueType(); Type rightType = right.getValueType(); if (leftType.isBoolType() && rightType.isBoolType()) { boolean lb = ((IBool) left.getValue()).getValue(); boolean rb = ((IBool) right.getValue()).getValue(); return (lb == rb) ? 0 : ((!lb && rb) ? -1 : 1); } if (left.getType().isIntegerType() && rightType.isIntegerType()) { return ((IInteger) left.getValue()).compare((IInteger) right.getValue()); } if (leftType.isRealType() && rightType.isRealType()) { return ((IReal) left.getValue()).compare((IReal) right.getValue()); } if (leftType.isStringType() && rightType.isStringType()) { return ((IString) left.getValue()).compare((IString) right.getValue()); } if (leftType.isListType() && rightType.isListType()) { return compareList(((IList) left.getValue()).iterator(), ((IList) left.getValue()).length(), ((IList) right.getValue()).iterator(), ((IList) right.getValue()).length()); } if (leftType.isSetType() && rightType.isSetType()) { return compareSet((ISet) left.getValue(), (ISet) right.getValue()); } if (leftType.isMapType() && rightType.isMapType()) { return compareMap((IMap) left.getValue(), (IMap) right.getValue()); } if (leftType.isTupleType() && rightType.isTupleType()) { return compareList(((ITuple) left.getValue()).iterator(), ((ITuple) left.getValue()).arity(), ((ITuple) right.getValue()).iterator(), ((ITuple) right.getValue()).arity()); } if (leftType.isRelationType() && rightType.isRelationType()) { return compareSet((ISet) left.getValue(), (ISet) right.getValue()); } if (leftType.isNodeType() && rightType.isNodeType()) { return compareNode((INode) left.getValue(), (INode) right.getValue()); } if (leftType.isAbstractDataType() && rightType.isAbstractDataType()) { return compareNode((INode) left.getValue(), (INode) right.getValue()); } if(leftType.isSourceLocationType() && rightType.isSourceLocationType()){ return compareSourceLocation((ISourceLocation) left.getValue(), (ISourceLocation) right.getValue()); } // VoidType // ValueType return leftType.toString().compareTo(rightType.toString()); } private static int compareNode(INode left, INode right){ String leftName = left.getName().toString(); String rightName = right.getName().toString(); int compare = leftName.compareTo(rightName); if(compare != 0){ return compare; } return compareList(left.iterator(), left.arity(), right.iterator(), right.arity()); } private static int compareSourceLocation(ISourceLocation leftSL, ISourceLocation rightSL){ if(leftSL.equals(rightSL)) return 0; if(leftSL.getURL().equals(rightSL.getURL())){ int lBeginLine = leftSL.getBeginLine(); int rBeginLine = rightSL.getBeginLine(); int lEndLine = leftSL.getEndLine(); int rEndLine = rightSL.getEndLine(); int lBeginColumn = leftSL.getBeginColumn(); int rBeginColumn = rightSL.getBeginColumn(); int lEndColumn = leftSL.getEndColumn(); int rEndColumn = rightSL.getEndColumn(); if((lBeginLine > rBeginLine || (lBeginLine == rBeginLine && lBeginColumn > rBeginColumn)) && (lEndLine < rEndLine || ((lEndLine == rEndLine) && lEndColumn < rEndColumn))){ return -1; } else { return 1; } } else { return leftSL.getURL().toString().compareTo(rightSL.getURL().toString()); } } private static int compareSet(ISet value1, ISet value2) { //System.err.println("compareSet: value1=" + value1 + ", value2=" + value2 + "isEqual=" + value1.isEqual(value2)); if (value1.isEqual(value2)) { return 0; } else if (value1.isSubsetOf(value2)) { return -1; } else { return 1; } } private static int compareMap(IMap value1, IMap value2) { if (value1.isEqual(value2)) { return 0; } else if (value1.isSubMap(value2)) { return -1; } else { return 1; } } private static int compareList(Iterator<IValue> left, int leftLen, Iterator<IValue> right, int rightLen){ if(leftLen == 0){ return rightLen == 0 ? 0 : -1; } if(rightLen == 0){ return 1; } int m = (leftLen > rightLen) ? rightLen : leftLen; int compare = 0; for(int i = 0; i < m; i++){ IValue leftVal = left.next(); IValue rightVal = right.next(); Result vl = new Result(leftVal.getType(), leftVal); Result vr = new Result(rightVal.getType(), rightVal); int c = compare(vl, vr); if (c < 0 || c > 0) { return c; } } if(compare == 0 && leftLen != rightLen){ compare = leftLen < rightLen ? -1 : 1; } return compare; } @Override public Result visitExpressionLessThan(LessThan x) { Result left = x.getLhs().accept(this); Result right = x.getRhs().accept(this); return result(vf.bool(compare(left, right) < 0)); } @Override public Result visitExpressionLessThanOrEq(LessThanOrEq x) { Result left = x.getLhs().accept(this); Result right = x.getRhs().accept(this); return result(vf.bool(compare(left, right) <= 0)); } @Override public Result visitExpressionGreaterThan(GreaterThan x) { Result left = x.getLhs().accept(this); Result right = x.getRhs().accept(this); return result(vf.bool(compare(left, right) > 0)); } @Override public Result visitExpressionGreaterThanOrEq(GreaterThanOrEq x) { Result left = x.getLhs().accept(this); Result right = x.getRhs().accept(this); return result(vf.bool(compare(left, right) >= 0)); } @Override public Result visitExpressionIfThenElse( org.meta_environment.rascal.ast.Expression.IfThenElse x) { Result cval = x.getCondition().accept(this); if (cval.getType().isBoolType()) { if (cval.getValue().isEqual(vf.bool(true))) { return x.getThenExp().accept(this); } } else { throw new UnexpectedTypeError(tf.boolType(),cval.getType(), x); } return x.getElseExp().accept(this); } @Override public Result visitExpressionIfDefinedOtherwise(IfDefinedOtherwise x) { // TODO add type checking on which types is this operator allowed? try { return x.getLhs().accept(this); } catch (UninitializedVariableError e) { Result res = x.getRhs().accept(this); return res; } } @Override public Result visitExpressionIsDefined(IsDefined x) { // TODO add type checking on which types is this operator allowed? try { x.getArgument().accept(this); // wait for exception return result(tf.boolType(), vf.bool(true)); } catch (UninitializedVariableError e) { return result(tf.boolType(), vf.bool(false)); } } private boolean in(org.meta_environment.rascal.ast.Expression expression, org.meta_environment.rascal.ast.Expression expression2){ Result left = expression.accept(this); Result right = expression2.accept(this); //List if(right.getType().isListType() && left.getType().isSubtypeOf(right.getType().getElementType())){ IList lst = (IList) right.getValue(); IValue val = left.getValue(); for(int i = 0; i < lst.length(); i++){ if(lst.get(i).isEqual(val)) return true; } return false; //Set } else if(right.getType().isSetType() && left.getType().isSubtypeOf(right.getType().getElementType())){ return ((ISet) right.getValue()).contains(left.getValue()); //Map } else if(right.getType().isMapType() && left.getType().isSubtypeOf(right.getType().getValueType())){ return ((IMap) right.getValue()).containsValue(left.getValue()); //Relation } else if(right.getType().isRelationType() && left.getType().isSubtypeOf(right.getType().getElementType())){ return ((ISet) right.getValue()).contains(left.getValue()); } else { throw new UnsupportedOperationError("in" , left.getType(), right.getType(), expression2); } } @Override public Result visitExpressionIn(In x) { return result(vf.bool(in(x.getLhs(), x.getRhs()))); } @Override public Result visitExpressionNotIn(NotIn x) { return result(vf.bool(!in(x.getLhs(), x.getRhs()))); } @Override public Result visitExpressionComposition(Composition x) { Result left = x.getLhs().accept(this); Result right = x.getRhs().accept(this); //Relation if(left.getType().isRelationType() && right.getType().isRelationType()){ Type leftrelType = left.getType(); Type rightrelType = right.getType(); int leftArity = leftrelType.getArity(); int rightArity = rightrelType.getArity(); if ((leftArity == 0 || leftArity == 2) && (rightArity == 0 || rightArity ==2 )) { Type resultType = leftrelType.compose(rightrelType); return result(resultType, ((IRelation) left.getValue()) .compose((IRelation) right.getValue())); } } throw new UnsupportedOperationError("o" , left.getType(), right.getType(), x); } private Result closure(AbstractAST expression, boolean reflexive) { Result res = expression.accept(this); //Relation if (res.getType().isRelationType() && res.getType().getArity() < 3) { Type relType = res.getType(); Type fieldType1 = relType.getFieldType(0); Type fieldType2 = relType.getFieldType(1); if (fieldType1.comparable(fieldType2)) { Type lub = fieldType1.lub(fieldType2); Type resultType = relType.hasFieldNames() ? tf.relType(lub, relType.getFieldName(0), lub, relType.getFieldName(1)) : tf.relType(lub,lub); return result(resultType, reflexive ? ((IRelation) res.getValue()).closureStar() : ((IRelation) res.getValue()).closure()); } } throw new UnsupportedOperationError("*", res.getType(), expression); } @Override public Result visitExpressionTransitiveClosure(TransitiveClosure x) { return closure(x.getArgument(), false); } @Override public Result visitExpressionTransitiveReflexiveClosure( TransitiveReflexiveClosure x) { return closure(x.getArgument(), true); } // Comprehensions ---------------------------------------------------- @Override public Result visitExpressionComprehension(Comprehension x) { push(); try { return x.getComprehension().accept(this); } finally { pop(); } } /* @Override public Result visitGeneratorExpression( org.meta_environment.rascal.ast.Generator.Expression x) { return new GeneratorEvaluator(x, this).next(); } */ @Override public Result visitExpressionValueProducer( org.meta_environment.rascal.ast.Expression.ValueProducer x) { return new GeneratorEvaluator(x, this); } @Override public Result visitExpressionValueProducerWithStrategy( ValueProducerWithStrategy x) { return new GeneratorEvaluator(x, this); } class GeneratorEvaluator extends Result { private boolean isValueProducer; private boolean firstTime = true; private org.meta_environment.rascal.ast.Expression expr; private MatchPattern pat; private org.meta_environment.rascal.ast.Expression patexpr; private Evaluator evaluator; private Iterator<?> iterator; GeneratorEvaluator(Expression g, Evaluator ev){ make(g, ev); } void make(Expression vp, Evaluator ev){ if(vp.isValueProducer() || vp.isValueProducerWithStrategy()){ evaluator = ev; isValueProducer = true; pat = evalPattern(vp.getPattern()); patexpr = vp.getExpression(); Result r = patexpr.accept(ev); // List if(r.getType().isListType()){ if(vp.hasStrategy()) { throw new UnsupportedOperationError(vp.toString(), r.getType(), vp); } iterator = ((IList) r.getValue()).iterator(); // Set } else if(r.getType().isSetType()){ if(vp.hasStrategy()) { throw new UnsupportedOperationError(vp.toString(), r.getType(), vp); } iterator = ((ISet) r.getValue()).iterator(); // Map } else if(r.getType().isMapType()){ if(vp.hasStrategy()) { throw new UnsupportedOperationError(vp.toString(), r.getType(), vp); } iterator = ((IMap) r.getValue()).iterator(); // Node and ADT } else if(r.getType().isNodeType() || r.getType().isAbstractDataType()){ boolean bottomup = true; if(vp.hasStrategy()){ Strategy strat = vp.getStrategy(); if(strat.isTopDown()){ bottomup = false; } else if(strat.isBottomUp()){ bottomup = true; } else { throw new UnsupportedOperationError(vp.toString(), r.getType(), vp); } } iterator = new INodeReader((INode) r.getValue(), bottomup); } else if(r.getType().isStringType()){ if(vp.hasStrategy()) { throw new UnsupportedOperationError(vp.getStrategy().toString(), r.getType(), vp.getStrategy()); } iterator = new SingleIValueIterator(r.getValue()); } else { throw new ImplementationError("Unimplemented expression type " + r.getType() + " in generator"); } } else { evaluator = ev; isValueProducer = false; expr = vp; } } @Override public Type getType(){ return TypeFactory.getInstance().boolType(); } @Override public Type getValueType(){ return TypeFactory.getInstance().boolType(); } @Override public boolean hasNext(){ if(isValueProducer){ return pat.hasNext() || iterator.hasNext(); } else { return firstTime; } } @Override public Result next(){ if(isValueProducer){ //System.err.println("getNext, trying pat " + pat); /* * First, explore alternatives that remain to be matched by the current pattern */ while(pat.hasNext()){ if(pat.next()){ //System.err.println("return true"); return new Result(this, true); } } /* * Next, fetch a new data element (if any) and create a new pattern. */ while(iterator.hasNext()){ IValue v = (IValue) iterator.next(); //System.err.println("getNext, try next from value iterator: " + v); pat.initMatch(v, peek()); while(pat.hasNext()){ if(pat.next()){ //System.err.println("return true"); return new Result(this,true); } } } //System.err.println("return false"); return normalizedResult(tf.boolType(), vf.bool(false)); } else { if(firstTime){ /* Evaluate expression only once */ firstTime = false; Result v = expr.accept(evaluator); if(v.getType().isBoolType() && v.getValue() != null){ // FIXME: if result is of type void, you get a null pointer here. if (v.getValue().isEqual(vf.bool(true))) { //if(v.isTrue()){ return result(tf.boolType(), vf.bool(true)); } return result(tf.boolType(), vf.bool(false)); } else { throw new UnexpectedTypeError(tf.boolType(), v.getType(), expr); } } else { // TODO: why false here? Shouldn't we save the first-time eval result? return result(tf.boolType(), vf.bool(false)); } } } @Override public void remove() { throw new ImplementationError("remove() not implemented for GeneratorEvaluator"); } } /* * ComprehensionWriter provides a uniform framework for writing elements * to a list/set/map during the evaluation of a list/set/map comprehension. */ private abstract class ComprehensionWriter { protected Type elementType1; protected Type elementType2; protected Type resultType; protected org.meta_environment.rascal.ast.Expression resultExpr1; protected org.meta_environment.rascal.ast.Expression resultExpr2; protected IWriter writer; protected Evaluator ev; ComprehensionWriter( org.meta_environment.rascal.ast.Expression resultExpr1, org.meta_environment.rascal.ast.Expression resultExpr2, Evaluator ev){ this.ev = ev; this.resultExpr1 = resultExpr1; this.resultExpr2 = resultExpr2; this.writer = null; } public void check(Result r, Type t, String kind, org.meta_environment.rascal.ast.Expression expr){ if(!r.getType().isSubtypeOf(t)){ throw new UnexpectedTypeError(t, r.getType() , expr); } } public abstract void append(); public abstract Result done(); } private class ListComprehensionWriter extends ComprehensionWriter { ListComprehensionWriter( org.meta_environment.rascal.ast.Expression resultExpr1, Evaluator ev) { super(resultExpr1, null, ev); } @Override public void append() { Result r1 = resultExpr1.accept(ev); if (writer == null) { elementType1 = r1.getType(); resultType = tf.listType(elementType1); writer = resultType.writer(vf); } check(r1, elementType1, "list", resultExpr1); elementType1 = elementType1.lub(r1.getType()); ((IListWriter) writer).append(r1.getValue()); } @Override public Result done() { return (writer == null) ? result(tf.listType(tf.voidType()), vf .list()) : result(tf.listType(elementType1), writer.done()); } } private class SetComprehensionWriter extends ComprehensionWriter { SetComprehensionWriter( org.meta_environment.rascal.ast.Expression resultExpr1, Evaluator ev) { super(resultExpr1, null, ev); } @Override public void append() { Result r1 = resultExpr1.accept(ev); if (writer == null) { elementType1 = r1.getType(); resultType = tf.setType(elementType1); writer = resultType.writer(vf); } check(r1, elementType1, "set", resultExpr1); elementType1 = elementType1.lub(r1.getType()); ((ISetWriter) writer).insert(r1.getValue()); } @Override public Result done() { return (writer == null) ? result(tf.setType(tf.voidType()), vf .set()) : result(tf.setType(elementType1), writer.done()); } } private class MapComprehensionWriter extends ComprehensionWriter { MapComprehensionWriter( org.meta_environment.rascal.ast.Expression resultExpr1, org.meta_environment.rascal.ast.Expression resultExpr2, Evaluator ev) { super(resultExpr1, resultExpr2, ev); } @Override public void append() { Result r1 = resultExpr1.accept(ev); Result r2 = resultExpr2.accept(ev); if (writer == null) { elementType1 = r1.getType(); elementType2 = r2.getType(); resultType = tf.mapType(elementType1, elementType2); writer = resultType.writer(vf); } check(r1, elementType1, "map", resultExpr1); check(r2, elementType2, "map", resultExpr2); ((IMapWriter) writer).put(r1.getValue(), r2.getValue()); } @Override public Result done() { return (writer == null) ? result(tf.mapType(tf.voidType(), tf .voidType()), vf.map(tf.voidType(), tf.voidType())) : result(tf.mapType(elementType1, elementType2), writer .done()); } } /* * The common comprehension evaluator */ private Result evalComprehension(java.util.List<Expression> generators, ComprehensionWriter w){ int size = generators.size(); GeneratorEvaluator[] gens = new GeneratorEvaluator[size]; int i = 0; gens[0] = new GeneratorEvaluator(generators.get(0), this); while (i >= 0 && i < size){ if (gens[i].hasNext() && gens[i].next().isTrue()) { if(i == size - 1){ w.append(); } else { i++; gens[i] = new GeneratorEvaluator(generators.get(i), this); } } else { i--; } } return w.done(); } @Override public Result visitComprehensionList(org.meta_environment.rascal.ast.Comprehension.List x) { return evalComprehension( x.getGenerators(), new ListComprehensionWriter(x.getResult(), this)); } @Override public Result visitComprehensionSet( org.meta_environment.rascal.ast.Comprehension.Set x) { return evalComprehension( x.getGenerators(), new SetComprehensionWriter(x.getResult(), this)); } @Override public Result visitComprehensionMap( org.meta_environment.rascal.ast.Comprehension.Map x) { return evalComprehension( x.getGenerators(), new MapComprehensionWriter(x.getFrom(), x.getTo(), this)); } @Override public Result visitStatementFor(For x) { Statement body = x.getBody(); java.util.List<Expression> generators = x.getGenerators(); int size = generators.size(); GeneratorEvaluator[] gens = new GeneratorEvaluator[size]; Result result = result(); int i = 0; gens[0] = new GeneratorEvaluator(generators.get(0), this); while(i >= 0 && i < size){ if(gens[i].hasNext() && gens[i].next().isTrue()){ if(i == size - 1){ result = body.accept(this); } else { i++; gens[i] = new GeneratorEvaluator(generators.get(i), this); } } else { i--; } } return result; } @Override public Result visitExpressionAny(Any x) { java.util.List<Expression> generators = x.getGenerators(); int size = generators.size(); GeneratorEvaluator[] gens = new GeneratorEvaluator[size]; int i = 0; gens[0] = new GeneratorEvaluator(generators.get(0), this); while (i >= 0 && i < size) { if (gens[i].hasNext() && gens[i].next().isTrue()) { if (i == size - 1) { return result(vf.bool(true)); } else { i++; gens[i] = new GeneratorEvaluator(generators.get(i), this); } } else { i--; } } return result(vf.bool(false)); } @Override public Result visitExpressionAll(All x) { java.util.List<Expression> producers = x.getGenerators(); int size = producers.size(); GeneratorEvaluator[] gens = new GeneratorEvaluator[size]; int i = 0; gens[0] = new GeneratorEvaluator(producers.get(0), this); while (i >= 0 && i < size) { if (gens[i].hasNext()) { if (!gens[i].next().isTrue()) { return result(vf.bool(false)); } if (i < size - 1) { i++; gens[i] = new GeneratorEvaluator(producers.get(i), this); } } else { i--; } } return result(vf.bool(true)); } // ------------ solve ----------------------------------------- @Override public Result visitStatementSolve(Solve x) { java.util.ArrayList<org.meta_environment.rascal.ast.Variable> vars = new java.util.ArrayList<org.meta_environment.rascal.ast.Variable>(); for(Declarator d : x.getDeclarations()){ for(org.meta_environment.rascal.ast.Variable v : d.getVariables()){ vars.add(v); } d.accept(this); } IValue currentValue[] = new IValue[vars.size()]; for(int i = 0; i < vars.size(); i++){ org.meta_environment.rascal.ast.Variable v = vars.get(i); currentValue[i] = peek().getVariable(v, Names.name(v.getName())).getValue(); } Statement body = x.getBody(); int max = 1000; Bound bound= x.getBound(); if(bound.isDefault()){ Result res = bound.getExpression().accept(this); if(!res.getType().isIntegerType()){ throw new UnexpectedTypeError(tf.integerType(),res.getType(), x); } max = ((IInteger)res.getValue()).intValue(); if(max <= 0){ throw RuntimeExceptionFactory.indexOutOfBounds((IInteger) res.getValue()); } } Result bodyResult = null; boolean change = true; int iterations = 0; while (change && iterations < max){ change = false; iterations++; bodyResult = body.accept(this); for(int i = 0; i < vars.size(); i++){ org.meta_environment.rascal.ast.Variable var = vars.get(i); Result v = peek().getVariable(var, Names.name(var.getName())); if(currentValue[i] == null || !v.getValue().isEqual(currentValue[i])){ change = true; currentValue[i] = v.getValue(); } } } return bodyResult; } }
true
true
public Result visitExpressionSubscript(Subscript x) { Result expr = x.getExpression().accept(this); Type exprType = expr.getType(); int nSubs = x.getSubscripts().size(); if (exprType.isRelationType()) { int relArity = exprType.getArity(); if(nSubs >= relArity){ throw new ArityError(exprType, nSubs, x); } Result subscriptResult[] = new Result[nSubs]; Type subscriptType[] = new Type[nSubs]; boolean subscriptIsSet[] = new boolean[nSubs]; for(int i = 0; i < nSubs; i++){ subscriptResult[i] = x.getSubscripts().get(i).accept(this); subscriptType[i] = subscriptResult[i].getType(); } boolean yieldSet = (relArity - nSubs) == 1; Type resFieldType[] = new Type[relArity - nSubs]; for (int i = 0; i < relArity; i++) { Type relFieldType = exprType.getFieldType(i); if(i < nSubs){ if(subscriptType[i].isSetType() && subscriptType[i].getElementType().isSubtypeOf(relFieldType)){ subscriptIsSet[i] = true; } else if(subscriptType[i].isSubtypeOf(relFieldType)){ subscriptIsSet[i] = false; } else { throw new UnexpectedTypeError(relFieldType, subscriptType[i], x); } } else { resFieldType[i - nSubs] = relFieldType; } } Type resultType; ISetWriter wset = null; IRelationWriter wrel = null; if(yieldSet){ resultType = tf.setType(resFieldType[0]); wset = resultType.writer(vf); } else { resultType = tf.relType(resFieldType); wrel = resultType.writer(vf); } for (IValue v : ((IRelation) expr.getValue())) { ITuple tup = (ITuple) v; boolean allEqual = true; for(int k = 0; k < nSubs; k++){ if(subscriptIsSet[k] && ((ISet) subscriptResult[k].getValue()).contains(tup.get(k))){ /* ok */ } else if (tup.get(k).isEqual(subscriptResult[k].getValue())){ /* ok */ } else { allEqual = false; } } if (allEqual) { IValue args[] = new IValue[relArity - nSubs]; for (int i = nSubs; i < relArity; i++) { args[i - nSubs] = tup.get(i); } if(yieldSet){ wset.insert(args[0]); } else { wrel.insert(vf.tuple(args)); } } } return normalizedResult(resultType, yieldSet ? wset.done() : wrel.done()); } if (nSubs > 1){ throw new SyntaxError("No more than one subscript allowed on " + exprType, x.getLocation()); } Result subs = x.getSubscripts().get(0).accept(this); Type subsBase = subs.getType(); if (exprType.isMapType() && subsBase.isSubtypeOf(exprType.getKeyType())) { Type valueType = exprType.getValueType(); IValue v = ((IMap) expr.getValue()).get(subs.getValue()); if(v == null){ throw RuntimeExceptionFactory.noSuchKey(v); } return normalizedResult(valueType,v); } if(!subsBase.isIntegerType()){ throw new UnexpectedTypeError(tf.integerType(), subsBase, x); } int index = ((IInteger) subs.getValue()).intValue(); if (exprType.isListType()) { Type elementType = exprType.getElementType(); try { IValue element = ((IList) expr.getValue()).get(index); return normalizedResult(elementType, element); } catch (java.lang.IndexOutOfBoundsException e) { throw RuntimeExceptionFactory.indexOutOfBounds((IInteger) subs.getValue()); } } if (exprType.isAbstractDataType()) { if(index >= ((IConstructor) expr.getValue()).arity()){ throw RuntimeExceptionFactory.indexOutOfBounds((IInteger) subs.getValue()); } Type elementType = ((IConstructor) expr.getValue()).getConstructorType().getFieldType(index); IValue element = ((IConstructor) expr.getValue()).get(index); return normalizedResult(elementType, element); } if (exprType.isNodeType()) { if(index >= ((INode) expr.getValue()).arity()){ throw RuntimeExceptionFactory.indexOutOfBounds((IInteger) subs.getValue()); } Type elementType = tf.valueType(); IValue element = ((INode) expr.getValue()).get(index); return normalizedResult(elementType, element); } if (exprType.isTupleType()) { try { Type elementType = exprType.getFieldType(index); IValue element = ((ITuple) expr.getValue()).get(index); return normalizedResult(elementType, element); } catch (ArrayIndexOutOfBoundsException e){ throw RuntimeExceptionFactory.indexOutOfBounds((IInteger) subs.getValue()); } } throw new UnsupportedOperationError("subscript", exprType, x); }
public Result visitExpressionSubscript(Subscript x) { Result expr = x.getExpression().accept(this); Type exprType = expr.getType(); int nSubs = x.getSubscripts().size(); if (exprType.isRelationType()) { int relArity = exprType.getArity(); if(nSubs >= relArity){ throw new ArityError(exprType, nSubs, x); } Result subscriptResult[] = new Result[nSubs]; Type subscriptType[] = new Type[nSubs]; boolean subscriptIsSet[] = new boolean[nSubs]; for(int i = 0; i < nSubs; i++){ subscriptResult[i] = x.getSubscripts().get(i).accept(this); subscriptType[i] = subscriptResult[i].getType(); } boolean yieldSet = (relArity - nSubs) == 1; Type resFieldType[] = new Type[relArity - nSubs]; for (int i = 0; i < relArity; i++) { Type relFieldType = exprType.getFieldType(i); if(i < nSubs){ if(subscriptType[i].isSetType() && subscriptType[i].getElementType().isSubtypeOf(relFieldType)){ subscriptIsSet[i] = true; } else if(subscriptType[i].isSubtypeOf(relFieldType)){ subscriptIsSet[i] = false; } else { throw new UnexpectedTypeError(relFieldType, subscriptType[i], x); } } else { resFieldType[i - nSubs] = relFieldType; } } Type resultType; ISetWriter wset = null; IRelationWriter wrel = null; if(yieldSet){ resultType = tf.setType(resFieldType[0]); wset = resultType.writer(vf); } else { resultType = tf.relType(resFieldType); wrel = resultType.writer(vf); } for (IValue v : ((IRelation) expr.getValue())) { ITuple tup = (ITuple) v; boolean allEqual = true; for(int k = 0; k < nSubs; k++){ if(subscriptIsSet[k] && ((ISet) subscriptResult[k].getValue()).contains(tup.get(k))){ /* ok */ } else if (tup.get(k).isEqual(subscriptResult[k].getValue())){ /* ok */ } else { allEqual = false; } } if (allEqual) { IValue args[] = new IValue[relArity - nSubs]; for (int i = nSubs; i < relArity; i++) { args[i - nSubs] = tup.get(i); } if(yieldSet){ wset.insert(args[0]); } else { wrel.insert(vf.tuple(args)); } } } return normalizedResult(resultType, yieldSet ? wset.done() : wrel.done()); } if (nSubs > 1){ throw new SyntaxError("No more than one subscript allowed on " + exprType, x.getLocation()); } Result subs = x.getSubscripts().get(0).accept(this); Type subsBase = subs.getType(); if (exprType.isMapType() && subsBase.isSubtypeOf(exprType.getKeyType())) { Type valueType = exprType.getValueType(); IValue v = ((IMap) expr.getValue()).get(subs.getValue()); if(v == null){ throw RuntimeExceptionFactory.noSuchKey(subs.getValue()); } return normalizedResult(valueType,v); } if(!subsBase.isIntegerType()){ throw new UnexpectedTypeError(tf.integerType(), subsBase, x); } int index = ((IInteger) subs.getValue()).intValue(); if (exprType.isListType()) { Type elementType = exprType.getElementType(); try { IValue element = ((IList) expr.getValue()).get(index); return normalizedResult(elementType, element); } catch (java.lang.IndexOutOfBoundsException e) { throw RuntimeExceptionFactory.indexOutOfBounds((IInteger) subs.getValue()); } } if (exprType.isAbstractDataType()) { if(index >= ((IConstructor) expr.getValue()).arity()){ throw RuntimeExceptionFactory.indexOutOfBounds((IInteger) subs.getValue()); } Type elementType = ((IConstructor) expr.getValue()).getConstructorType().getFieldType(index); IValue element = ((IConstructor) expr.getValue()).get(index); return normalizedResult(elementType, element); } if (exprType.isNodeType()) { if(index >= ((INode) expr.getValue()).arity()){ throw RuntimeExceptionFactory.indexOutOfBounds((IInteger) subs.getValue()); } Type elementType = tf.valueType(); IValue element = ((INode) expr.getValue()).get(index); return normalizedResult(elementType, element); } if (exprType.isTupleType()) { try { Type elementType = exprType.getFieldType(index); IValue element = ((ITuple) expr.getValue()).get(index); return normalizedResult(elementType, element); } catch (ArrayIndexOutOfBoundsException e){ throw RuntimeExceptionFactory.indexOutOfBounds((IInteger) subs.getValue()); } } throw new UnsupportedOperationError("subscript", exprType, x); }
diff --git a/org.eclipse.mylyn.context.ui/src/org/eclipse/mylyn/internal/context/ui/TaskListInterestSorter.java b/org.eclipse.mylyn.context.ui/src/org/eclipse/mylyn/internal/context/ui/TaskListInterestSorter.java index f2c2c877f..062f9076a 100644 --- a/org.eclipse.mylyn.context.ui/src/org/eclipse/mylyn/internal/context/ui/TaskListInterestSorter.java +++ b/org.eclipse.mylyn.context.ui/src/org/eclipse/mylyn/internal/context/ui/TaskListInterestSorter.java @@ -1,232 +1,236 @@ /******************************************************************************* * Copyright (c) 2004, 2007 Mylyn project committers 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 *******************************************************************************/ package org.eclipse.mylyn.internal.context.ui; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerSorter; import org.eclipse.mylyn.internal.tasks.core.ScheduledTaskContainer; import org.eclipse.mylyn.internal.tasks.core.UncategorizedTaskContainer; import org.eclipse.mylyn.internal.tasks.core.UnmatchedTaskContainer; import org.eclipse.mylyn.internal.tasks.ui.views.TaskKeyComparator; import org.eclipse.mylyn.internal.tasks.ui.views.TaskListTableSorter; import org.eclipse.mylyn.tasks.core.AbstractTask; import org.eclipse.mylyn.tasks.core.AbstractTaskContainer; import org.eclipse.mylyn.tasks.ui.TasksUiPlugin; /** * @author Mik Kersten */ public class TaskListInterestSorter extends ViewerSorter { private final TaskKeyComparator taskKeyComparator = new TaskKeyComparator(); @Override public int compare(Viewer compareViewer, Object o1, Object o2) { // OrphanedTasksContainer localArchive = TasksUiPlugin.getTaskListManager().getTaskList().getOrphanContainer( // LocalRepositoryConnector.REPOSITORY_URL); // if (o1 == localArchive && o2 instanceof AbstractTaskContainer) { // return -1; // } else if (o1 instanceof AbstractTaskContainer && o2 == localArchive) { // return 1; // } if (o1 instanceof AbstractTaskContainer && o2 instanceof UnmatchedTaskContainer) { return -1; } else if (o2 instanceof AbstractTaskContainer && o1 instanceof UnmatchedTaskContainer) { return 1; } if (o1 instanceof ScheduledTaskContainer && o2 instanceof ScheduledTaskContainer) { ScheduledTaskContainer dateRangeTaskContainer1 = (ScheduledTaskContainer) o1; ScheduledTaskContainer dateRangeTaskContainer2 = (ScheduledTaskContainer) o2; if (dateRangeTaskContainer1.isCaptureFloating() && !dateRangeTaskContainer2.isCaptureFloating()) { return 1; } else if (!dateRangeTaskContainer1.isCaptureFloating() && dateRangeTaskContainer2.isCaptureFloating()) { return -1; } return -1 * dateRangeTaskContainer2.getStart().compareTo(dateRangeTaskContainer1.getStart()); } else if (o1 instanceof AbstractTaskContainer && o2 instanceof ScheduledTaskContainer) { return -1; } else if (o1 instanceof ScheduledTaskContainer && o2 instanceof AbstractTaskContainer) { return 1; } if (o1 instanceof UncategorizedTaskContainer && o2 instanceof AbstractTaskContainer) { return -1; } else if (o1 instanceof AbstractTaskContainer && o2 instanceof UncategorizedTaskContainer) { return 1; } if (!(o1 instanceof AbstractTask) && o2 instanceof AbstractTask) { return 1; } if (!(o1 instanceof AbstractTask)) {//o1 instanceof AbstractTaskContainer || o1 instanceof AbstractRepositoryQuery) { if (!(o2 instanceof AbstractTask)) {//o2 instanceof AbstractTaskContainer || o2 instanceof AbstractRepositoryQuery) { return ((AbstractTaskContainer) o1).getSummary().compareToIgnoreCase( ((AbstractTaskContainer) o2).getSummary()); } else { return -1; } } else if (o1 instanceof AbstractTaskContainer) { if (!(o2 instanceof AbstractTask)) {//o2 instanceof AbstractTaskContainer || o2 instanceof AbstractRepositoryQuery) { return -1; } else if (o2 instanceof AbstractTaskContainer) { AbstractTaskContainer element1 = (AbstractTaskContainer) o1; AbstractTaskContainer element2 = (AbstractTaskContainer) o2; AbstractTask task1 = null; AbstractTask task2 = null; if (element1 instanceof AbstractTask) { task1 = (AbstractTask) element1; } if (element2 instanceof AbstractTask) { task2 = (AbstractTask) element2; } if (task1 == null && task2 == null) { return comparePrioritiesAndKeys(element1, element2); } else if (task1 == null) { return 1; } else if (task2 == null) { return -1; } int complete = compareCompleted(task1, task2); if (complete != 0) { return complete; } else { int due = compareDueDates(task1, task2); if (due != 0) { return due; } else { int today = compareScheduledDate(task1, task2); if (today == 0) { return comparePrioritiesAndKeys(element1, element2); } else { return today; } } } } } return 0; } private int compareDueDates(AbstractTask task1, AbstractTask task2) { if (TasksUiPlugin.getTaskActivityManager().isOverdue(task1) && !TasksUiPlugin.getTaskActivityManager().isOverdue(task2)) { return -1; } else if (!TasksUiPlugin.getTaskActivityManager().isOverdue(task1) && TasksUiPlugin.getTaskActivityManager().isOverdue(task2)) { return 1; } return 0; } private int compareScheduledDate(AbstractTask task1, AbstractTask task2) { if (task1.internalIsFloatingScheduledDate() && !task2.internalIsFloatingScheduledDate()) { return 1; } else if (!task1.internalIsFloatingScheduledDate() && task2.internalIsFloatingScheduledDate()) { return -1; + } else if (task1.internalIsFloatingScheduledDate() && task2.internalIsFloatingScheduledDate()) { + if (task1.getScheduledForDate() != null && task2.getScheduledForDate() != null) { + return 0; + } } if (isToday(task1) && !isToday(task2)) { return -1; } else if (!isToday(task1) && isToday(task2)) { return 1; } else { return 0; } } private boolean isToday(AbstractTask task) { return task.isPastReminder() || TasksUiPlugin.getTaskActivityManager().isScheduledForToday(task); } // private int compareThisWeek(AbstractTask task1, AbstractTask task2) { // if (TasksUiPlugin.getTaskActivityManager().isScheduledForThisWeek(task1) // && !TasksUiPlugin.getTaskActivityManager().isScheduledForThisWeek(task2)) { // return 1; // } else if (!TasksUiPlugin.getTaskActivityManager().isScheduledForThisWeek(task1) // && TasksUiPlugin.getTaskActivityManager().isScheduledForThisWeek(task2)) { // return -1; // } else { // return 0; // } // } private int compareCompleted(AbstractTask task1, AbstractTask task2) { if (task1.isCompleted() && !task2.isCompleted()) { return 1; } else if (!task1.isCompleted() && task2.isCompleted()) { return -1; } else { return 0; } } // private int compareOverScheduled(AbstractTask task1, AbstractTask task2) { // if (task1.isPastReminder() && !task2.isPastReminder()) { // return -1; // } else if (!task1.isPastReminder() && task2.isPastReminder()) { // return 1; // } else { // return 0; // } // } // // private int compareScheduledToday(AbstractTask task1, AbstractTask task2) { // if (TasksUiPlugin.getTaskActivityManager().isScheduledForToday(task1) // && !TasksUiPlugin.getTaskActivityManager().isScheduledForToday(task2)) { // return -1; // } else if (!TasksUiPlugin.getTaskActivityManager().isScheduledForToday(task1) // && TasksUiPlugin.getTaskActivityManager().isScheduledForToday(task2)) { // return 1; // } else { // return 0; // } // } // private int compareChanges(ITask task1, ITask task2) { // if (TaskListInterestFilter.hasChanges(task1) && // !TaskListInterestFilter.hasChanges(task2)) { // return 1; // } else if (!TaskListInterestFilter.hasChanges(task1) && // TaskListInterestFilter.hasChanges(task2)) { // return -1; // } else { // return 0; // } // } private int comparePrioritiesAndKeys(AbstractTaskContainer element1, AbstractTaskContainer element2) { int priority = comparePriorities(element1, element2); if (priority != 0) { return priority; } int description = compareKeys(element1, element2); if (description != 0) { return description; } return 0; } private int compareKeys(AbstractTaskContainer element1, AbstractTaskContainer element2) { return taskKeyComparator.compare(TaskListTableSorter.getSortableFromElement(element1), TaskListTableSorter.getSortableFromElement(element2)); } private int comparePriorities(AbstractTaskContainer element1, AbstractTaskContainer element2) { return element1.getPriority().compareTo(element2.getPriority()); } }
true
true
public int compare(Viewer compareViewer, Object o1, Object o2) { // OrphanedTasksContainer localArchive = TasksUiPlugin.getTaskListManager().getTaskList().getOrphanContainer( // LocalRepositoryConnector.REPOSITORY_URL); // if (o1 == localArchive && o2 instanceof AbstractTaskContainer) { // return -1; // } else if (o1 instanceof AbstractTaskContainer && o2 == localArchive) { // return 1; // } if (o1 instanceof AbstractTaskContainer && o2 instanceof UnmatchedTaskContainer) { return -1; } else if (o2 instanceof AbstractTaskContainer && o1 instanceof UnmatchedTaskContainer) { return 1; } if (o1 instanceof ScheduledTaskContainer && o2 instanceof ScheduledTaskContainer) { ScheduledTaskContainer dateRangeTaskContainer1 = (ScheduledTaskContainer) o1; ScheduledTaskContainer dateRangeTaskContainer2 = (ScheduledTaskContainer) o2; if (dateRangeTaskContainer1.isCaptureFloating() && !dateRangeTaskContainer2.isCaptureFloating()) { return 1; } else if (!dateRangeTaskContainer1.isCaptureFloating() && dateRangeTaskContainer2.isCaptureFloating()) { return -1; } return -1 * dateRangeTaskContainer2.getStart().compareTo(dateRangeTaskContainer1.getStart()); } else if (o1 instanceof AbstractTaskContainer && o2 instanceof ScheduledTaskContainer) { return -1; } else if (o1 instanceof ScheduledTaskContainer && o2 instanceof AbstractTaskContainer) { return 1; } if (o1 instanceof UncategorizedTaskContainer && o2 instanceof AbstractTaskContainer) { return -1; } else if (o1 instanceof AbstractTaskContainer && o2 instanceof UncategorizedTaskContainer) { return 1; } if (!(o1 instanceof AbstractTask) && o2 instanceof AbstractTask) { return 1; } if (!(o1 instanceof AbstractTask)) {//o1 instanceof AbstractTaskContainer || o1 instanceof AbstractRepositoryQuery) { if (!(o2 instanceof AbstractTask)) {//o2 instanceof AbstractTaskContainer || o2 instanceof AbstractRepositoryQuery) { return ((AbstractTaskContainer) o1).getSummary().compareToIgnoreCase( ((AbstractTaskContainer) o2).getSummary()); } else { return -1; } } else if (o1 instanceof AbstractTaskContainer) { if (!(o2 instanceof AbstractTask)) {//o2 instanceof AbstractTaskContainer || o2 instanceof AbstractRepositoryQuery) { return -1; } else if (o2 instanceof AbstractTaskContainer) { AbstractTaskContainer element1 = (AbstractTaskContainer) o1; AbstractTaskContainer element2 = (AbstractTaskContainer) o2; AbstractTask task1 = null; AbstractTask task2 = null; if (element1 instanceof AbstractTask) { task1 = (AbstractTask) element1; } if (element2 instanceof AbstractTask) { task2 = (AbstractTask) element2; } if (task1 == null && task2 == null) { return comparePrioritiesAndKeys(element1, element2); } else if (task1 == null) { return 1; } else if (task2 == null) { return -1; } int complete = compareCompleted(task1, task2); if (complete != 0) { return complete; } else { int due = compareDueDates(task1, task2); if (due != 0) { return due; } else { int today = compareScheduledDate(task1, task2); if (today == 0) { return comparePrioritiesAndKeys(element1, element2); } else { return today; } } } } } return 0; } private int compareDueDates(AbstractTask task1, AbstractTask task2) { if (TasksUiPlugin.getTaskActivityManager().isOverdue(task1) && !TasksUiPlugin.getTaskActivityManager().isOverdue(task2)) { return -1; } else if (!TasksUiPlugin.getTaskActivityManager().isOverdue(task1) && TasksUiPlugin.getTaskActivityManager().isOverdue(task2)) { return 1; } return 0; } private int compareScheduledDate(AbstractTask task1, AbstractTask task2) { if (task1.internalIsFloatingScheduledDate() && !task2.internalIsFloatingScheduledDate()) { return 1; } else if (!task1.internalIsFloatingScheduledDate() && task2.internalIsFloatingScheduledDate()) { return -1; } if (isToday(task1) && !isToday(task2)) { return -1; } else if (!isToday(task1) && isToday(task2)) { return 1; } else { return 0; } } private boolean isToday(AbstractTask task) { return task.isPastReminder() || TasksUiPlugin.getTaskActivityManager().isScheduledForToday(task); } // private int compareThisWeek(AbstractTask task1, AbstractTask task2) { // if (TasksUiPlugin.getTaskActivityManager().isScheduledForThisWeek(task1) // && !TasksUiPlugin.getTaskActivityManager().isScheduledForThisWeek(task2)) { // return 1; // } else if (!TasksUiPlugin.getTaskActivityManager().isScheduledForThisWeek(task1) // && TasksUiPlugin.getTaskActivityManager().isScheduledForThisWeek(task2)) { // return -1; // } else { // return 0; // } // } private int compareCompleted(AbstractTask task1, AbstractTask task2) { if (task1.isCompleted() && !task2.isCompleted()) { return 1; } else if (!task1.isCompleted() && task2.isCompleted()) { return -1; } else { return 0; } } // private int compareOverScheduled(AbstractTask task1, AbstractTask task2) { // if (task1.isPastReminder() && !task2.isPastReminder()) { // return -1; // } else if (!task1.isPastReminder() && task2.isPastReminder()) { // return 1; // } else { // return 0; // } // } // // private int compareScheduledToday(AbstractTask task1, AbstractTask task2) { // if (TasksUiPlugin.getTaskActivityManager().isScheduledForToday(task1) // && !TasksUiPlugin.getTaskActivityManager().isScheduledForToday(task2)) { // return -1; // } else if (!TasksUiPlugin.getTaskActivityManager().isScheduledForToday(task1) // && TasksUiPlugin.getTaskActivityManager().isScheduledForToday(task2)) { // return 1; // } else { // return 0; // } // } // private int compareChanges(ITask task1, ITask task2) { // if (TaskListInterestFilter.hasChanges(task1) && // !TaskListInterestFilter.hasChanges(task2)) { // return 1; // } else if (!TaskListInterestFilter.hasChanges(task1) && // TaskListInterestFilter.hasChanges(task2)) { // return -1; // } else { // return 0; // } // } private int comparePrioritiesAndKeys(AbstractTaskContainer element1, AbstractTaskContainer element2) { int priority = comparePriorities(element1, element2); if (priority != 0) { return priority; } int description = compareKeys(element1, element2); if (description != 0) { return description; } return 0; } private int compareKeys(AbstractTaskContainer element1, AbstractTaskContainer element2) { return taskKeyComparator.compare(TaskListTableSorter.getSortableFromElement(element1), TaskListTableSorter.getSortableFromElement(element2)); } private int comparePriorities(AbstractTaskContainer element1, AbstractTaskContainer element2) { return element1.getPriority().compareTo(element2.getPriority()); } }
public int compare(Viewer compareViewer, Object o1, Object o2) { // OrphanedTasksContainer localArchive = TasksUiPlugin.getTaskListManager().getTaskList().getOrphanContainer( // LocalRepositoryConnector.REPOSITORY_URL); // if (o1 == localArchive && o2 instanceof AbstractTaskContainer) { // return -1; // } else if (o1 instanceof AbstractTaskContainer && o2 == localArchive) { // return 1; // } if (o1 instanceof AbstractTaskContainer && o2 instanceof UnmatchedTaskContainer) { return -1; } else if (o2 instanceof AbstractTaskContainer && o1 instanceof UnmatchedTaskContainer) { return 1; } if (o1 instanceof ScheduledTaskContainer && o2 instanceof ScheduledTaskContainer) { ScheduledTaskContainer dateRangeTaskContainer1 = (ScheduledTaskContainer) o1; ScheduledTaskContainer dateRangeTaskContainer2 = (ScheduledTaskContainer) o2; if (dateRangeTaskContainer1.isCaptureFloating() && !dateRangeTaskContainer2.isCaptureFloating()) { return 1; } else if (!dateRangeTaskContainer1.isCaptureFloating() && dateRangeTaskContainer2.isCaptureFloating()) { return -1; } return -1 * dateRangeTaskContainer2.getStart().compareTo(dateRangeTaskContainer1.getStart()); } else if (o1 instanceof AbstractTaskContainer && o2 instanceof ScheduledTaskContainer) { return -1; } else if (o1 instanceof ScheduledTaskContainer && o2 instanceof AbstractTaskContainer) { return 1; } if (o1 instanceof UncategorizedTaskContainer && o2 instanceof AbstractTaskContainer) { return -1; } else if (o1 instanceof AbstractTaskContainer && o2 instanceof UncategorizedTaskContainer) { return 1; } if (!(o1 instanceof AbstractTask) && o2 instanceof AbstractTask) { return 1; } if (!(o1 instanceof AbstractTask)) {//o1 instanceof AbstractTaskContainer || o1 instanceof AbstractRepositoryQuery) { if (!(o2 instanceof AbstractTask)) {//o2 instanceof AbstractTaskContainer || o2 instanceof AbstractRepositoryQuery) { return ((AbstractTaskContainer) o1).getSummary().compareToIgnoreCase( ((AbstractTaskContainer) o2).getSummary()); } else { return -1; } } else if (o1 instanceof AbstractTaskContainer) { if (!(o2 instanceof AbstractTask)) {//o2 instanceof AbstractTaskContainer || o2 instanceof AbstractRepositoryQuery) { return -1; } else if (o2 instanceof AbstractTaskContainer) { AbstractTaskContainer element1 = (AbstractTaskContainer) o1; AbstractTaskContainer element2 = (AbstractTaskContainer) o2; AbstractTask task1 = null; AbstractTask task2 = null; if (element1 instanceof AbstractTask) { task1 = (AbstractTask) element1; } if (element2 instanceof AbstractTask) { task2 = (AbstractTask) element2; } if (task1 == null && task2 == null) { return comparePrioritiesAndKeys(element1, element2); } else if (task1 == null) { return 1; } else if (task2 == null) { return -1; } int complete = compareCompleted(task1, task2); if (complete != 0) { return complete; } else { int due = compareDueDates(task1, task2); if (due != 0) { return due; } else { int today = compareScheduledDate(task1, task2); if (today == 0) { return comparePrioritiesAndKeys(element1, element2); } else { return today; } } } } } return 0; } private int compareDueDates(AbstractTask task1, AbstractTask task2) { if (TasksUiPlugin.getTaskActivityManager().isOverdue(task1) && !TasksUiPlugin.getTaskActivityManager().isOverdue(task2)) { return -1; } else if (!TasksUiPlugin.getTaskActivityManager().isOverdue(task1) && TasksUiPlugin.getTaskActivityManager().isOverdue(task2)) { return 1; } return 0; } private int compareScheduledDate(AbstractTask task1, AbstractTask task2) { if (task1.internalIsFloatingScheduledDate() && !task2.internalIsFloatingScheduledDate()) { return 1; } else if (!task1.internalIsFloatingScheduledDate() && task2.internalIsFloatingScheduledDate()) { return -1; } else if (task1.internalIsFloatingScheduledDate() && task2.internalIsFloatingScheduledDate()) { if (task1.getScheduledForDate() != null && task2.getScheduledForDate() != null) { return 0; } } if (isToday(task1) && !isToday(task2)) { return -1; } else if (!isToday(task1) && isToday(task2)) { return 1; } else { return 0; } } private boolean isToday(AbstractTask task) { return task.isPastReminder() || TasksUiPlugin.getTaskActivityManager().isScheduledForToday(task); } // private int compareThisWeek(AbstractTask task1, AbstractTask task2) { // if (TasksUiPlugin.getTaskActivityManager().isScheduledForThisWeek(task1) // && !TasksUiPlugin.getTaskActivityManager().isScheduledForThisWeek(task2)) { // return 1; // } else if (!TasksUiPlugin.getTaskActivityManager().isScheduledForThisWeek(task1) // && TasksUiPlugin.getTaskActivityManager().isScheduledForThisWeek(task2)) { // return -1; // } else { // return 0; // } // } private int compareCompleted(AbstractTask task1, AbstractTask task2) { if (task1.isCompleted() && !task2.isCompleted()) { return 1; } else if (!task1.isCompleted() && task2.isCompleted()) { return -1; } else { return 0; } } // private int compareOverScheduled(AbstractTask task1, AbstractTask task2) { // if (task1.isPastReminder() && !task2.isPastReminder()) { // return -1; // } else if (!task1.isPastReminder() && task2.isPastReminder()) { // return 1; // } else { // return 0; // } // } // // private int compareScheduledToday(AbstractTask task1, AbstractTask task2) { // if (TasksUiPlugin.getTaskActivityManager().isScheduledForToday(task1) // && !TasksUiPlugin.getTaskActivityManager().isScheduledForToday(task2)) { // return -1; // } else if (!TasksUiPlugin.getTaskActivityManager().isScheduledForToday(task1) // && TasksUiPlugin.getTaskActivityManager().isScheduledForToday(task2)) { // return 1; // } else { // return 0; // } // } // private int compareChanges(ITask task1, ITask task2) { // if (TaskListInterestFilter.hasChanges(task1) && // !TaskListInterestFilter.hasChanges(task2)) { // return 1; // } else if (!TaskListInterestFilter.hasChanges(task1) && // TaskListInterestFilter.hasChanges(task2)) { // return -1; // } else { // return 0; // } // } private int comparePrioritiesAndKeys(AbstractTaskContainer element1, AbstractTaskContainer element2) { int priority = comparePriorities(element1, element2); if (priority != 0) { return priority; } int description = compareKeys(element1, element2); if (description != 0) { return description; } return 0; } private int compareKeys(AbstractTaskContainer element1, AbstractTaskContainer element2) { return taskKeyComparator.compare(TaskListTableSorter.getSortableFromElement(element1), TaskListTableSorter.getSortableFromElement(element2)); } private int comparePriorities(AbstractTaskContainer element1, AbstractTaskContainer element2) { return element1.getPriority().compareTo(element2.getPriority()); } }
diff --git a/modules/dCache/org/dcache/chimera/namespace/ChimeraOsmStorageInfoExtractor.java b/modules/dCache/org/dcache/chimera/namespace/ChimeraOsmStorageInfoExtractor.java index d07f3f6919..c62c2506ef 100644 --- a/modules/dCache/org/dcache/chimera/namespace/ChimeraOsmStorageInfoExtractor.java +++ b/modules/dCache/org/dcache/chimera/namespace/ChimeraOsmStorageInfoExtractor.java @@ -1,299 +1,302 @@ /* * $Id: ChimeraOsmStorageInfoExtractor.java,v 1.8 2007-08-24 08:22:59 tigran Exp $ */ package org.dcache.chimera.namespace; import java.io.BufferedReader; import java.io.CharArrayReader; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.StringTokenizer; import org.dcache.chimera.FileNotFoundHimeraFsException; import org.dcache.chimera.FsInode; import org.dcache.chimera.FsInode_TAG; import org.dcache.chimera.ChimeraFsException; import org.dcache.chimera.StorageGenericLocation; import org.dcache.chimera.StorageLocatable; import org.dcache.chimera.posix.Stat; import org.dcache.chimera.store.AccessLatency; import org.dcache.chimera.store.InodeStorageInformation; import org.dcache.chimera.store.RetentionPolicy; import diskCacheV111.util.CacheException; import diskCacheV111.util.FileNotFoundCacheException; import diskCacheV111.util.HsmLocation; import diskCacheV111.util.HsmLocationExtractorFactory; import diskCacheV111.vehicles.OSMStorageInfo; import diskCacheV111.vehicles.StorageInfo; public class ChimeraOsmStorageInfoExtractor implements ChimeraStorageInfoExtractable { /* * (non-Javadoc) * * @see diskCacheV111.util.StorageInfoExtractable#getStorageInfo(java.lang.String, * diskCacheV111.util.PnfsId) */ public StorageInfo getStorageInfo(FsInode inode) throws CacheException { if( !inode.exists() ) { throw new FileNotFoundCacheException(inode.toString() + " does not exists"); } StorageInfo info; if (inode.isDirectory()) { info = getDirStorageInfo(inode); } else { info = getFileStorageInfo(inode); } return info; } private static StorageInfo getFileStorageInfo(FsInode inode) throws CacheException { OSMStorageInfo info = null; Stat stat = null; FsInode level2 = new FsInode(inode.getFs(), inode.toString(), 2); try { List<StorageLocatable> locations = inode.getFs().getInodeLocations(inode, StorageGenericLocation.TAPE ); if ( locations.isEmpty() ) { info = (OSMStorageInfo) getDirStorageInfo(inode); AccessLatency al = inode.getFs().getAccessLatency(inode); /* * currently storage class and AL and RP are asymmetric: * storage class of the file is bound to directory as log as file is not stored on tape, * while AL and RP are bound to file */ if(al != null) { info.setAccessLatency(diskCacheV111.util.AccessLatency.getAccessLatency(al.getId())); } RetentionPolicy rp = inode.getFs().getRetentionPolicy(inode); if( rp != null ) { info.setRetentionPolicy(diskCacheV111.util.RetentionPolicy.getRetentionPolicy(rp.getId())); } } else { InodeStorageInformation inodeStorageInfo = inode.getFs().getSorageInfo(inode); info = new OSMStorageInfo( inodeStorageInfo.storageGroup(), inodeStorageInfo.storageSubGroup() ); info.setIsNew(false); info.setAccessLatency(diskCacheV111.util.AccessLatency.getAccessLatency( inodeStorageInfo.accessLatency().getId() ) ); info.setRetentionPolicy(diskCacheV111.util.RetentionPolicy.getRetentionPolicy( inodeStorageInfo.retentionPolicy().getId() ) ); for(StorageLocatable location: locations) { if( location.isOnline() ) { try { info.addLocation( new URI(location.location()) ); } catch (URISyntaxException e) { // bad URI } } } } } catch (ChimeraFsException e) { throw new CacheException(e.getMessage()); } try { stat = inode.stat(); }catch( ChimeraFsException hfe) { throw new CacheException(hfe.getMessage()); } info.setFileSize(stat.getSize()); info.setIsNew((stat.getSize() == 0) && (!level2.exists())); return info; } private static StorageInfo getDirStorageInfo(FsInode inode) throws CacheException { FsInode dirInode = null; if (!inode.isDirectory()) { dirInode = inode.getParent(); } else { dirInode = inode; } StorageInfo si = null; try { String[] OSMTemplate = getTag(dirInode, "OSMTemplate"); + if (OSMTemplate == null) { + throw new CacheException(37, "OSMTemplate tag not found"); + } HashMap<String, String> hash = new HashMap<String, String>(); for ( String line: OSMTemplate) { StringTokenizer st = new StringTokenizer(line); if (st.countTokens() < 2) continue; hash.put(st.nextToken(), st.nextToken()); } String store = hash.get("StoreName"); if (store == null) { throw new CacheException(37, "StoreName not found in template"); } String [] sGroup = getTag(dirInode, "sGroup"); if( sGroup == null ) { throw new CacheException(37, "sGroup tag not found"); } String gr = sGroup[0].trim(); OSMStorageInfo info = new OSMStorageInfo(store, gr); info.addKeys(hash); // overwrite hsm type with hsmInstance tag String[] hsmInstance = getTag(dirInode, "hsmInstance"); if( hsmInstance != null ) { info.setHsm( hsmInstance[0].toLowerCase().trim()); } String[] cacheClass = getTag(dirInode, "cacheClass"); if( cacheClass != null ) { info.setCacheClass( cacheClass[0].toLowerCase().trim()); } si = info; String[] accessLatency = getTag(dirInode, "AccessLatency"); String[] retentionPolicy = getTag(dirInode, "RetentionPolicy"); String [] spaceToken = getTag(dirInode, "WriteToken"); /* * if Access latency and/or retention policy is defined for a directory * apply it to the file and make it persistent, while it's a file attribute and directory * tag is default value only */ if(accessLatency != null) { try { info.setAccessLatency( diskCacheV111.util.AccessLatency.getAccessLatency(accessLatency[0].trim())); info.isSetAccessLatency(true); }catch(IllegalArgumentException iae) { // TODO: do we fail here or not? } } if(retentionPolicy != null) { try { info.setRetentionPolicy( diskCacheV111.util.RetentionPolicy.getRetentionPolicy(retentionPolicy[0].trim())); info.isSetRetentionPolicy(true); }catch(IllegalArgumentException iae) { // TODO: do we fail here or not? } } if( spaceToken != null ) { info.setKey("writeToken", spaceToken[0].trim()); } } catch (IOException e) { throw new CacheException(e.getMessage()); } return si; } /* * (non-Javadoc) * * @see diskCacheV111.util.StorageInfoExtractable#setStorageInfo(java.lang.String, * diskCacheV111.util.PnfsId, diskCacheV111.vehicles.StorageInfo, int) */ public void setStorageInfo(FsInode inode, StorageInfo dCacheStorageInfo, int arg3) throws CacheException { try { if( dCacheStorageInfo.isSetAccessLatency() ) { AccessLatency accessLatency = AccessLatency.valueOf(dCacheStorageInfo.getAccessLatency().getId()); inode.getFs().setAccessLatency(inode, accessLatency); } if( dCacheStorageInfo.isSetRetentionPolicy() ) { RetentionPolicy retentionPolicy = RetentionPolicy.valueOf( dCacheStorageInfo.getRetentionPolicy().getId()); inode.getFs().setRetentionPolicy(inode, retentionPolicy); } if(dCacheStorageInfo.isSetAddLocation() ) { List<URI> locationURIs = dCacheStorageInfo.locations(); for(URI location : locationURIs) { HsmLocation hsmLocation = HsmLocationExtractorFactory.extractorOf(location); inode.getFs().addInodeLocation(inode, StorageGenericLocation.TAPE, hsmLocation.location().toString()); } } }catch(FileNotFoundHimeraFsException e) { throw new FileNotFoundCacheException(e.getMessage()); }catch(ChimeraFsException he ) { throw new CacheException(he.getMessage() ); } } /** * * get content of a virtual file named .(tag)(&lt;tagname&gt;) * * @param dirInode inode of directory * @param tag tag name * @return array of strings corresponding to lines of tag file or null if tag does not exist * @throws IOException */ private static String[] getTag(FsInode dirInode, String tag) throws IOException { FsInode_TAG tagInode = new FsInode_TAG(dirInode.getFs(), dirInode .toString(), tag); if( !tagInode.exists() ) { return null; } byte[] buff = new byte[256]; int len = tagInode.read(0, buff, 0, buff.length); if( len < 0 ) { return null; } List<String> lines = new ArrayList<String>(); CharArrayReader ca = new CharArrayReader(new String(buff, 0, len) .toCharArray()); BufferedReader br = new BufferedReader(ca); String line = null; while ((line = br.readLine()) != null) { lines.add(line); } return lines.toArray(new String[lines.size()]); } }
true
true
private static StorageInfo getDirStorageInfo(FsInode inode) throws CacheException { FsInode dirInode = null; if (!inode.isDirectory()) { dirInode = inode.getParent(); } else { dirInode = inode; } StorageInfo si = null; try { String[] OSMTemplate = getTag(dirInode, "OSMTemplate"); HashMap<String, String> hash = new HashMap<String, String>(); for ( String line: OSMTemplate) { StringTokenizer st = new StringTokenizer(line); if (st.countTokens() < 2) continue; hash.put(st.nextToken(), st.nextToken()); } String store = hash.get("StoreName"); if (store == null) { throw new CacheException(37, "StoreName not found in template"); } String [] sGroup = getTag(dirInode, "sGroup"); if( sGroup == null ) { throw new CacheException(37, "sGroup tag not found"); } String gr = sGroup[0].trim(); OSMStorageInfo info = new OSMStorageInfo(store, gr); info.addKeys(hash); // overwrite hsm type with hsmInstance tag String[] hsmInstance = getTag(dirInode, "hsmInstance"); if( hsmInstance != null ) { info.setHsm( hsmInstance[0].toLowerCase().trim()); } String[] cacheClass = getTag(dirInode, "cacheClass"); if( cacheClass != null ) { info.setCacheClass( cacheClass[0].toLowerCase().trim()); } si = info; String[] accessLatency = getTag(dirInode, "AccessLatency"); String[] retentionPolicy = getTag(dirInode, "RetentionPolicy"); String [] spaceToken = getTag(dirInode, "WriteToken"); /* * if Access latency and/or retention policy is defined for a directory * apply it to the file and make it persistent, while it's a file attribute and directory * tag is default value only */ if(accessLatency != null) { try { info.setAccessLatency( diskCacheV111.util.AccessLatency.getAccessLatency(accessLatency[0].trim())); info.isSetAccessLatency(true); }catch(IllegalArgumentException iae) { // TODO: do we fail here or not? } } if(retentionPolicy != null) { try { info.setRetentionPolicy( diskCacheV111.util.RetentionPolicy.getRetentionPolicy(retentionPolicy[0].trim())); info.isSetRetentionPolicy(true); }catch(IllegalArgumentException iae) { // TODO: do we fail here or not? } } if( spaceToken != null ) { info.setKey("writeToken", spaceToken[0].trim()); } } catch (IOException e) { throw new CacheException(e.getMessage()); } return si; }
private static StorageInfo getDirStorageInfo(FsInode inode) throws CacheException { FsInode dirInode = null; if (!inode.isDirectory()) { dirInode = inode.getParent(); } else { dirInode = inode; } StorageInfo si = null; try { String[] OSMTemplate = getTag(dirInode, "OSMTemplate"); if (OSMTemplate == null) { throw new CacheException(37, "OSMTemplate tag not found"); } HashMap<String, String> hash = new HashMap<String, String>(); for ( String line: OSMTemplate) { StringTokenizer st = new StringTokenizer(line); if (st.countTokens() < 2) continue; hash.put(st.nextToken(), st.nextToken()); } String store = hash.get("StoreName"); if (store == null) { throw new CacheException(37, "StoreName not found in template"); } String [] sGroup = getTag(dirInode, "sGroup"); if( sGroup == null ) { throw new CacheException(37, "sGroup tag not found"); } String gr = sGroup[0].trim(); OSMStorageInfo info = new OSMStorageInfo(store, gr); info.addKeys(hash); // overwrite hsm type with hsmInstance tag String[] hsmInstance = getTag(dirInode, "hsmInstance"); if( hsmInstance != null ) { info.setHsm( hsmInstance[0].toLowerCase().trim()); } String[] cacheClass = getTag(dirInode, "cacheClass"); if( cacheClass != null ) { info.setCacheClass( cacheClass[0].toLowerCase().trim()); } si = info; String[] accessLatency = getTag(dirInode, "AccessLatency"); String[] retentionPolicy = getTag(dirInode, "RetentionPolicy"); String [] spaceToken = getTag(dirInode, "WriteToken"); /* * if Access latency and/or retention policy is defined for a directory * apply it to the file and make it persistent, while it's a file attribute and directory * tag is default value only */ if(accessLatency != null) { try { info.setAccessLatency( diskCacheV111.util.AccessLatency.getAccessLatency(accessLatency[0].trim())); info.isSetAccessLatency(true); }catch(IllegalArgumentException iae) { // TODO: do we fail here or not? } } if(retentionPolicy != null) { try { info.setRetentionPolicy( diskCacheV111.util.RetentionPolicy.getRetentionPolicy(retentionPolicy[0].trim())); info.isSetRetentionPolicy(true); }catch(IllegalArgumentException iae) { // TODO: do we fail here or not? } } if( spaceToken != null ) { info.setKey("writeToken", spaceToken[0].trim()); } } catch (IOException e) { throw new CacheException(e.getMessage()); } return si; }
diff --git a/frontend/grisu-client/src/main/java/org/vpac/grisu/frontend/control/login/LoginManager.java b/frontend/grisu-client/src/main/java/org/vpac/grisu/frontend/control/login/LoginManager.java index 5009d6d6..9fa867d1 100644 --- a/frontend/grisu-client/src/main/java/org/vpac/grisu/frontend/control/login/LoginManager.java +++ b/frontend/grisu-client/src/main/java/org/vpac/grisu/frontend/control/login/LoginManager.java @@ -1,255 +1,255 @@ package org.vpac.grisu.frontend.control.login; import java.io.File; import java.io.IOException; import java.lang.reflect.Method; import java.net.URL; import java.security.PrivateKey; import java.security.Security; import java.security.cert.X509Certificate; import org.apache.commons.httpclient.protocol.Protocol; import org.apache.commons.httpclient.protocol.ProtocolSocketFactory; import org.apache.commons.lang.StringUtils; import org.apache.commons.ssl.HttpSecureProtocol; import org.apache.commons.ssl.TrustMaterial; import org.apache.log4j.Logger; import org.globus.gsi.GlobusCredential; import org.ietf.jgss.GSSCredential; import org.vpac.grisu.control.ServiceInterface; import org.vpac.grisu.control.exceptions.ServiceInterfaceException; import org.vpac.grisu.settings.Environment; import org.vpac.grisu.utils.GrisuPluginFilenameFilter; import org.vpac.security.light.control.CertificateFiles; import org.vpac.security.light.plainProxy.PlainProxy; import au.org.arcs.jcommons.dependencies.ClasspathHacker; import au.org.arcs.jcommons.dependencies.DependencyManager; import au.org.arcs.jcommons.utils.ArcsSecurityProvider; public class LoginManager { static final Logger myLogger = Logger.getLogger(LoginManager.class .getName()); /** * One-for-all method to login to a Grisu backend. * * Specify nothing except the loginParams (without the myproxy username & * password) in order to use a local proxy. If you specify the password in * addition to that the local x509 cert will be used to create a local proxy * which in turn will be used to login to the Grisu backend. * * If you specify the myproxy username & password in the login params those * will be used for a simple myproxy login to the backend. * * In order to use shibboleth login, you need to specify the password, the * idp-username and the name of the idp. * * @param password * the password or null * @param username * the shib-username or null * @param idp * the name of the idp or null * @param loginParams * the login parameters * @return the serviceinterface * @throws LoginException * if the login doesn't succeed * @throws IOException * if necessary plugins couldn't be downloaded/stored in the * .grisu/plugins folder */ public static ServiceInterface login(GlobusCredential cred, char[] password, String username, String idp, LoginParams loginParams) throws LoginException { DependencyManager.initArcsCommonJavaLibDir(); DependencyManager.checkForBouncyCastleDependency(); - Security - .addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); +// Security +// .addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); java.security.Security.addProvider(new ArcsSecurityProvider()); java.security.Security.setProperty("ssl.TrustManagerFactory.algorithm", "TrustAllCertificates"); try { addPluginsToClasspath(); } catch (IOException e2) { // TODO Auto-generated catch block myLogger.warn(e2); throw new RuntimeException(e2); } try { CertificateFiles.copyCACerts(); } catch (Exception e1) { // e1.printStackTrace(); myLogger.warn(e1); } // do the cacert thingy try { URL cacertURL = LoginManager.class.getResource("/ipsca.pem"); HttpSecureProtocol protocolSocketFactory = new HttpSecureProtocol(); TrustMaterial trustMaterial = null; trustMaterial = new TrustMaterial(cacertURL); // We can use setTrustMaterial() instead of addTrustMaterial() // if we want to remove // HttpSecureProtocol's default trust of TrustMaterial.CACERTS. protocolSocketFactory.addTrustMaterial(trustMaterial); // Maybe we want to turn off CN validation (not recommended!): protocolSocketFactory.setCheckHostname(false); Protocol protocol = new Protocol("https", (ProtocolSocketFactory) protocolSocketFactory, 443); Protocol.registerProtocol("https", protocol); } catch (Exception e) { e.printStackTrace(); } String serviceInterfaceUrl = loginParams.getServiceInterfaceUrl(); if ("Local".equals(serviceInterfaceUrl) || "Dummy".equals(serviceInterfaceUrl)) { DependencyManager .checkForVersionedDependency( "org.vpac.grisu.control.serviceInterfaces.LocalServiceInterface", 1, 1, "https://code.arcs.org.au/hudson/job/Grisu-SNAPSHOT/org.vpac.grisu$grisu-core/lastSuccessfulBuild/artifact/org.vpac.grisu/grisu-core/0.3-SNAPSHOT/local-backend.jar", new File(Environment.getGrisuPluginDirectory(), "local-backend.jar")); } else if (serviceInterfaceUrl.startsWith("http")) { // assume xfire -- that needs to get smarter later on DependencyManager .checkForVersionedDependency( "org.vpac.grisu.client.control.XFireServiceInterfaceCreator", 1, 1, "https://code.arcs.org.au/hudson/job/Grisu-connectors-SNAPSHOT-binaries/lastSuccessfulBuild/artifact/frontend-modules/xfire-frontend/target/xfire-frontend.jar", new File(Environment.getGrisuPluginDirectory(), "xfire-frontend.jar")); // also try to use client side mds DependencyManager .checkForVersionedDependency( "org.vpac.grisu.frontend.info.clientsidemds.ClientSideGrisuRegistry", 1, 1, "https://code.arcs.org.au/hudson/job/Grisu-SNAPSHOT-binaries/lastSuccessfulBuild/artifact/frontend/client-side-mds/target/client-side-mds.jar", new File(Environment.getGrisuPluginDirectory(), "client-side-mds.jar")); } if (StringUtils.isBlank(username)) { if (StringUtils.isBlank(loginParams.getMyProxyUsername())) { if (cred != null) { try { return LoginHelpers.globusCredentialLogin(loginParams, cred); } catch (Exception e) { throw new LoginException("Could not login: " + e.getLocalizedMessage(), e); } } else if (password == null || password.length == 0) { // means certificate auth try { // means try to load local proxy if (loginParams == null) { return LoginHelpers.defaultLocalProxyLogin(); } else { return LoginHelpers .defaultLocalProxyLogin(loginParams); } } catch (Exception e) { throw new LoginException("Could not login: " + e.getLocalizedMessage(), e); } } else { // means to create local proxy try { return LoginHelpers.localProxyLogin(password, loginParams); } catch (ServiceInterfaceException e) { throw new LoginException("Could not login: " + e.getLocalizedMessage(), e); } } } else { // means myproxy login try { return LoginHelpers.myProxyLogin(loginParams); } catch (ServiceInterfaceException e) { throw new LoginException("Could not login: " + e.getLocalizedMessage(), e); } } } else { try { // means shib login DependencyManager.checkForArcsGsiDependency(1, 1, true); GSSCredential slcsproxy = slcsMyProxyInit(username, password, idp); return LoginHelpers.gssCredentialLogin(loginParams, slcsproxy); } catch (Exception e) { e.printStackTrace(); throw new LoginException("Could not do slcs login: " + e.getLocalizedMessage(), e); } } } public static GSSCredential slcsMyProxyInit(String username, char[] password, String idp) throws Exception { try { Class slcsClass = Class.forName("au.org.arcs.auth.slcs.SLCS"); Object slcsObject = slcsClass.newInstance(); Method initMethod = slcsClass.getMethod("init", String.class, char[].class, String.class); initMethod.invoke(slcsObject, username, password, idp); Method getCredMethod = slcsClass.getMethod("getCertificate"); X509Certificate cert = (X509Certificate) getCredMethod .invoke(slcsObject); Method getKeyMethod = slcsClass.getMethod("getPrivateKey"); PrivateKey privateKey = (PrivateKey) getKeyMethod .invoke(slcsObject); GSSCredential cred = PlainProxy.init(cert, privateKey, 24 * 7); return cred; } catch (Exception e) { e.printStackTrace(); throw e; } } public static void addPluginsToClasspath() throws IOException { ClasspathHacker.initFolder(new File(Environment .getGrisuPluginDirectory()), new GrisuPluginFilenameFilter()); } }
true
true
public static ServiceInterface login(GlobusCredential cred, char[] password, String username, String idp, LoginParams loginParams) throws LoginException { DependencyManager.initArcsCommonJavaLibDir(); DependencyManager.checkForBouncyCastleDependency(); Security .addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); java.security.Security.addProvider(new ArcsSecurityProvider()); java.security.Security.setProperty("ssl.TrustManagerFactory.algorithm", "TrustAllCertificates"); try { addPluginsToClasspath(); } catch (IOException e2) { // TODO Auto-generated catch block myLogger.warn(e2); throw new RuntimeException(e2); } try { CertificateFiles.copyCACerts(); } catch (Exception e1) { // e1.printStackTrace(); myLogger.warn(e1); } // do the cacert thingy try { URL cacertURL = LoginManager.class.getResource("/ipsca.pem"); HttpSecureProtocol protocolSocketFactory = new HttpSecureProtocol(); TrustMaterial trustMaterial = null; trustMaterial = new TrustMaterial(cacertURL); // We can use setTrustMaterial() instead of addTrustMaterial() // if we want to remove // HttpSecureProtocol's default trust of TrustMaterial.CACERTS. protocolSocketFactory.addTrustMaterial(trustMaterial); // Maybe we want to turn off CN validation (not recommended!): protocolSocketFactory.setCheckHostname(false); Protocol protocol = new Protocol("https", (ProtocolSocketFactory) protocolSocketFactory, 443); Protocol.registerProtocol("https", protocol); } catch (Exception e) { e.printStackTrace(); } String serviceInterfaceUrl = loginParams.getServiceInterfaceUrl(); if ("Local".equals(serviceInterfaceUrl) || "Dummy".equals(serviceInterfaceUrl)) { DependencyManager .checkForVersionedDependency( "org.vpac.grisu.control.serviceInterfaces.LocalServiceInterface", 1, 1, "https://code.arcs.org.au/hudson/job/Grisu-SNAPSHOT/org.vpac.grisu$grisu-core/lastSuccessfulBuild/artifact/org.vpac.grisu/grisu-core/0.3-SNAPSHOT/local-backend.jar", new File(Environment.getGrisuPluginDirectory(), "local-backend.jar")); } else if (serviceInterfaceUrl.startsWith("http")) { // assume xfire -- that needs to get smarter later on DependencyManager .checkForVersionedDependency( "org.vpac.grisu.client.control.XFireServiceInterfaceCreator", 1, 1, "https://code.arcs.org.au/hudson/job/Grisu-connectors-SNAPSHOT-binaries/lastSuccessfulBuild/artifact/frontend-modules/xfire-frontend/target/xfire-frontend.jar", new File(Environment.getGrisuPluginDirectory(), "xfire-frontend.jar")); // also try to use client side mds DependencyManager .checkForVersionedDependency( "org.vpac.grisu.frontend.info.clientsidemds.ClientSideGrisuRegistry", 1, 1, "https://code.arcs.org.au/hudson/job/Grisu-SNAPSHOT-binaries/lastSuccessfulBuild/artifact/frontend/client-side-mds/target/client-side-mds.jar", new File(Environment.getGrisuPluginDirectory(), "client-side-mds.jar")); } if (StringUtils.isBlank(username)) { if (StringUtils.isBlank(loginParams.getMyProxyUsername())) { if (cred != null) { try { return LoginHelpers.globusCredentialLogin(loginParams, cred); } catch (Exception e) { throw new LoginException("Could not login: " + e.getLocalizedMessage(), e); } } else if (password == null || password.length == 0) { // means certificate auth try { // means try to load local proxy if (loginParams == null) { return LoginHelpers.defaultLocalProxyLogin(); } else { return LoginHelpers .defaultLocalProxyLogin(loginParams); } } catch (Exception e) { throw new LoginException("Could not login: " + e.getLocalizedMessage(), e); } } else { // means to create local proxy try { return LoginHelpers.localProxyLogin(password, loginParams); } catch (ServiceInterfaceException e) { throw new LoginException("Could not login: " + e.getLocalizedMessage(), e); } } } else { // means myproxy login try { return LoginHelpers.myProxyLogin(loginParams); } catch (ServiceInterfaceException e) { throw new LoginException("Could not login: " + e.getLocalizedMessage(), e); } } } else { try { // means shib login DependencyManager.checkForArcsGsiDependency(1, 1, true); GSSCredential slcsproxy = slcsMyProxyInit(username, password, idp); return LoginHelpers.gssCredentialLogin(loginParams, slcsproxy); } catch (Exception e) { e.printStackTrace(); throw new LoginException("Could not do slcs login: " + e.getLocalizedMessage(), e); } } }
public static ServiceInterface login(GlobusCredential cred, char[] password, String username, String idp, LoginParams loginParams) throws LoginException { DependencyManager.initArcsCommonJavaLibDir(); DependencyManager.checkForBouncyCastleDependency(); // Security // .addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); java.security.Security.addProvider(new ArcsSecurityProvider()); java.security.Security.setProperty("ssl.TrustManagerFactory.algorithm", "TrustAllCertificates"); try { addPluginsToClasspath(); } catch (IOException e2) { // TODO Auto-generated catch block myLogger.warn(e2); throw new RuntimeException(e2); } try { CertificateFiles.copyCACerts(); } catch (Exception e1) { // e1.printStackTrace(); myLogger.warn(e1); } // do the cacert thingy try { URL cacertURL = LoginManager.class.getResource("/ipsca.pem"); HttpSecureProtocol protocolSocketFactory = new HttpSecureProtocol(); TrustMaterial trustMaterial = null; trustMaterial = new TrustMaterial(cacertURL); // We can use setTrustMaterial() instead of addTrustMaterial() // if we want to remove // HttpSecureProtocol's default trust of TrustMaterial.CACERTS. protocolSocketFactory.addTrustMaterial(trustMaterial); // Maybe we want to turn off CN validation (not recommended!): protocolSocketFactory.setCheckHostname(false); Protocol protocol = new Protocol("https", (ProtocolSocketFactory) protocolSocketFactory, 443); Protocol.registerProtocol("https", protocol); } catch (Exception e) { e.printStackTrace(); } String serviceInterfaceUrl = loginParams.getServiceInterfaceUrl(); if ("Local".equals(serviceInterfaceUrl) || "Dummy".equals(serviceInterfaceUrl)) { DependencyManager .checkForVersionedDependency( "org.vpac.grisu.control.serviceInterfaces.LocalServiceInterface", 1, 1, "https://code.arcs.org.au/hudson/job/Grisu-SNAPSHOT/org.vpac.grisu$grisu-core/lastSuccessfulBuild/artifact/org.vpac.grisu/grisu-core/0.3-SNAPSHOT/local-backend.jar", new File(Environment.getGrisuPluginDirectory(), "local-backend.jar")); } else if (serviceInterfaceUrl.startsWith("http")) { // assume xfire -- that needs to get smarter later on DependencyManager .checkForVersionedDependency( "org.vpac.grisu.client.control.XFireServiceInterfaceCreator", 1, 1, "https://code.arcs.org.au/hudson/job/Grisu-connectors-SNAPSHOT-binaries/lastSuccessfulBuild/artifact/frontend-modules/xfire-frontend/target/xfire-frontend.jar", new File(Environment.getGrisuPluginDirectory(), "xfire-frontend.jar")); // also try to use client side mds DependencyManager .checkForVersionedDependency( "org.vpac.grisu.frontend.info.clientsidemds.ClientSideGrisuRegistry", 1, 1, "https://code.arcs.org.au/hudson/job/Grisu-SNAPSHOT-binaries/lastSuccessfulBuild/artifact/frontend/client-side-mds/target/client-side-mds.jar", new File(Environment.getGrisuPluginDirectory(), "client-side-mds.jar")); } if (StringUtils.isBlank(username)) { if (StringUtils.isBlank(loginParams.getMyProxyUsername())) { if (cred != null) { try { return LoginHelpers.globusCredentialLogin(loginParams, cred); } catch (Exception e) { throw new LoginException("Could not login: " + e.getLocalizedMessage(), e); } } else if (password == null || password.length == 0) { // means certificate auth try { // means try to load local proxy if (loginParams == null) { return LoginHelpers.defaultLocalProxyLogin(); } else { return LoginHelpers .defaultLocalProxyLogin(loginParams); } } catch (Exception e) { throw new LoginException("Could not login: " + e.getLocalizedMessage(), e); } } else { // means to create local proxy try { return LoginHelpers.localProxyLogin(password, loginParams); } catch (ServiceInterfaceException e) { throw new LoginException("Could not login: " + e.getLocalizedMessage(), e); } } } else { // means myproxy login try { return LoginHelpers.myProxyLogin(loginParams); } catch (ServiceInterfaceException e) { throw new LoginException("Could not login: " + e.getLocalizedMessage(), e); } } } else { try { // means shib login DependencyManager.checkForArcsGsiDependency(1, 1, true); GSSCredential slcsproxy = slcsMyProxyInit(username, password, idp); return LoginHelpers.gssCredentialLogin(loginParams, slcsproxy); } catch (Exception e) { e.printStackTrace(); throw new LoginException("Could not do slcs login: " + e.getLocalizedMessage(), e); } } }
diff --git a/nuxeo-platform-commandline-executor/src/main/java/org/nuxeo/ecm/platform/commandline/executor/service/CommandLineExecutorComponent.java b/nuxeo-platform-commandline-executor/src/main/java/org/nuxeo/ecm/platform/commandline/executor/service/CommandLineExecutorComponent.java index dc2f03a1a..2131021e5 100644 --- a/nuxeo-platform-commandline-executor/src/main/java/org/nuxeo/ecm/platform/commandline/executor/service/CommandLineExecutorComponent.java +++ b/nuxeo-platform-commandline-executor/src/main/java/org/nuxeo/ecm/platform/commandline/executor/service/CommandLineExecutorComponent.java @@ -1,201 +1,201 @@ /* * (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: * Nuxeo - initial API and implementation * * $Id$ * */ package org.nuxeo.ecm.platform.commandline.executor.service; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.nuxeo.ecm.platform.commandline.executor.api.CmdParameters; import org.nuxeo.ecm.platform.commandline.executor.api.CommandAvailability; import org.nuxeo.ecm.platform.commandline.executor.api.CommandLineExecutorService; import org.nuxeo.ecm.platform.commandline.executor.api.CommandNotAvailable; import org.nuxeo.ecm.platform.commandline.executor.api.ExecResult; import org.nuxeo.ecm.platform.commandline.executor.service.cmdtesters.CommandTestResult; import org.nuxeo.ecm.platform.commandline.executor.service.cmdtesters.CommandTester; import org.nuxeo.ecm.platform.commandline.executor.service.executors.Executor; import org.nuxeo.ecm.platform.commandline.executor.service.executors.ShellExecutor; import org.nuxeo.runtime.model.ComponentContext; import org.nuxeo.runtime.model.ComponentInstance; import org.nuxeo.runtime.model.DefaultComponent; /** * POJO implementation of the {@link CommandLineExecutorService} interface. Also * handles the Extension Point logic. * * @author tiry */ public class CommandLineExecutorComponent extends DefaultComponent implements CommandLineExecutorService { public static final String EP_ENV = "environment"; public static final String EP_CMD = "command"; public static final String EP_CMDTESTER = "commandTester"; public static final String DEFAULT_TESTER = "SystemPathTester"; public static final String DEFAULT_EXECUTOR = "ShellExecutor"; protected static Map<String, CommandLineDescriptor> commandDescriptors = new HashMap<String, CommandLineDescriptor>(); protected static EnvironementDescriptor env = new EnvironementDescriptor(); protected static Map<String, CommandTester> testers = new HashMap<String, CommandTester>(); protected static Map<String, Executor> executors = new HashMap<String, Executor>(); private static final Log log = LogFactory.getLog(CommandLineExecutorComponent.class); @Override public void activate(ComponentContext context) throws Exception { commandDescriptors = new HashMap<String, CommandLineDescriptor>(); env = new EnvironementDescriptor(); testers = new HashMap<String, CommandTester>(); executors = new HashMap<String, Executor>(); executors.put(DEFAULT_EXECUTOR, new ShellExecutor()); } @Override public void deactivate(ComponentContext context) throws Exception { commandDescriptors = null; env = null; testers = null; executors = null; } @Override public void registerContribution(Object contribution, String extensionPoint, ComponentInstance contributor) throws Exception { if (EP_ENV.equals(extensionPoint)) { env.merge((EnvironementDescriptor) contribution); } else if (EP_CMD.equals(extensionPoint)) { CommandLineDescriptor desc = (CommandLineDescriptor) contribution; + String name = desc.getName(); - log.debug("Registering command " + desc.getName()); + log.debug("Registering command: " + name); if (!desc.isEnabled()) { - commandDescriptors.remove(desc.getName()); - log.info("Command " + desc.getName() - + " is configured to not be enabled "); + commandDescriptors.remove(name); + log.info("Command configured to not be enabled: " + name); } String testerName = desc.getTester(); if (testerName == null) { testerName = DEFAULT_TESTER; - log.debug("Using default tester for command " + desc.getName()); + log.debug("Using default tester for command: " + name); } CommandTester tester = testers.get(testerName); boolean cmdAvailable = false; if (tester == null) { - log.error("Unable to find tester " + testerName + " command " - + desc.getName() + " will not be avalaible"); + log.error("Unable to find tester '" + testerName + + "', command will not be avalaible: " + name); } else { - log.debug("testing command " + desc.getName() + " with tester " - + testerName); + log.debug("Using tester '" + testerName + "' for command: " + + name); CommandTestResult testResult = tester.test(desc); cmdAvailable = testResult.succeed(); if (cmdAvailable) { - log.info("Command " + desc.getName() + " is avalaible"); + log.info("Registered command: " + name); } else { - log.warn("Command " + desc.getName() + " is NOT avalaible " - + testResult.getErrorMessage()); + log.warn("Command not available: " + name + " (" + + testResult.getErrorMessage() + ')'); desc.setInstallErrorMessage(testResult.getErrorMessage()); } } desc.setAvalaible(cmdAvailable); - commandDescriptors.put(desc.getName(), desc); + commandDescriptors.put(name, desc); } else if (EP_CMDTESTER.equals(extensionPoint)) { CommandTesterDescriptor desc = (CommandTesterDescriptor) contribution; CommandTester tester = (CommandTester) desc.getTesterClass() .newInstance(); testers.put(desc.getName(), tester); } } @Override public void unregisterContribution(Object contribution, String extensionPoint, ComponentInstance contributor) throws Exception { } /* * Service interface * */ public ExecResult execCommand(String commandName, CmdParameters params) throws CommandNotAvailable { CommandAvailability availability = getCommandAvailability(commandName); if (!availability.isAvailable()) { throw new CommandNotAvailable(availability); } CommandLineDescriptor cmdDesc = commandDescriptors.get(commandName); Executor executor = executors.get(cmdDesc.getExecutor()); return executor.exec(cmdDesc, params); } public CommandAvailability getCommandAvailability(String commandName) { if (!commandDescriptors.containsKey(commandName)) { return new CommandAvailability(commandName + " is not a registred command"); } CommandLineDescriptor desc = commandDescriptors.get(commandName); if (desc.isAvalaible()) { return new CommandAvailability(); } else { return new CommandAvailability(desc.getInstallationDirective(), desc.getInstallErrorMessage()); } } public List<String> getRegistredCommands() { List<String> cmds = new ArrayList<String>(); cmds.addAll(commandDescriptors.keySet()); return cmds; } public List<String> getAvailableCommands() { List<String> cmds = new ArrayList<String>(); for (String cmdName : commandDescriptors.keySet()) { CommandLineDescriptor cmd = commandDescriptors.get(cmdName); if (cmd.isAvalaible()) { cmds.add(cmdName); } } return cmds; } // ****************************************** // for testing public static CommandLineDescriptor getCommandDescriptor(String commandName) { return commandDescriptors.get(commandName); } }
false
true
public void registerContribution(Object contribution, String extensionPoint, ComponentInstance contributor) throws Exception { if (EP_ENV.equals(extensionPoint)) { env.merge((EnvironementDescriptor) contribution); } else if (EP_CMD.equals(extensionPoint)) { CommandLineDescriptor desc = (CommandLineDescriptor) contribution; log.debug("Registering command " + desc.getName()); if (!desc.isEnabled()) { commandDescriptors.remove(desc.getName()); log.info("Command " + desc.getName() + " is configured to not be enabled "); } String testerName = desc.getTester(); if (testerName == null) { testerName = DEFAULT_TESTER; log.debug("Using default tester for command " + desc.getName()); } CommandTester tester = testers.get(testerName); boolean cmdAvailable = false; if (tester == null) { log.error("Unable to find tester " + testerName + " command " + desc.getName() + " will not be avalaible"); } else { log.debug("testing command " + desc.getName() + " with tester " + testerName); CommandTestResult testResult = tester.test(desc); cmdAvailable = testResult.succeed(); if (cmdAvailable) { log.info("Command " + desc.getName() + " is avalaible"); } else { log.warn("Command " + desc.getName() + " is NOT avalaible " + testResult.getErrorMessage()); desc.setInstallErrorMessage(testResult.getErrorMessage()); } } desc.setAvalaible(cmdAvailable); commandDescriptors.put(desc.getName(), desc); } else if (EP_CMDTESTER.equals(extensionPoint)) { CommandTesterDescriptor desc = (CommandTesterDescriptor) contribution; CommandTester tester = (CommandTester) desc.getTesterClass() .newInstance(); testers.put(desc.getName(), tester); } }
public void registerContribution(Object contribution, String extensionPoint, ComponentInstance contributor) throws Exception { if (EP_ENV.equals(extensionPoint)) { env.merge((EnvironementDescriptor) contribution); } else if (EP_CMD.equals(extensionPoint)) { CommandLineDescriptor desc = (CommandLineDescriptor) contribution; String name = desc.getName(); log.debug("Registering command: " + name); if (!desc.isEnabled()) { commandDescriptors.remove(name); log.info("Command configured to not be enabled: " + name); } String testerName = desc.getTester(); if (testerName == null) { testerName = DEFAULT_TESTER; log.debug("Using default tester for command: " + name); } CommandTester tester = testers.get(testerName); boolean cmdAvailable = false; if (tester == null) { log.error("Unable to find tester '" + testerName + "', command will not be avalaible: " + name); } else { log.debug("Using tester '" + testerName + "' for command: " + name); CommandTestResult testResult = tester.test(desc); cmdAvailable = testResult.succeed(); if (cmdAvailable) { log.info("Registered command: " + name); } else { log.warn("Command not available: " + name + " (" + testResult.getErrorMessage() + ')'); desc.setInstallErrorMessage(testResult.getErrorMessage()); } } desc.setAvalaible(cmdAvailable); commandDescriptors.put(name, desc); } else if (EP_CMDTESTER.equals(extensionPoint)) { CommandTesterDescriptor desc = (CommandTesterDescriptor) contribution; CommandTester tester = (CommandTester) desc.getTesterClass() .newInstance(); testers.put(desc.getName(), tester); } }
diff --git a/pact/pact-runtime/src/main/java/eu/stratosphere/pact/runtime/task/CrossTask.java b/pact/pact-runtime/src/main/java/eu/stratosphere/pact/runtime/task/CrossTask.java index 5d7540930..3f1160a2b 100644 --- a/pact/pact-runtime/src/main/java/eu/stratosphere/pact/runtime/task/CrossTask.java +++ b/pact/pact-runtime/src/main/java/eu/stratosphere/pact/runtime/task/CrossTask.java @@ -1,728 +1,736 @@ /*********************************************************************************************************************** * * Copyright (C) 2010 by the Stratosphere project (http://stratosphere.eu) * * 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 eu.stratosphere.pact.runtime.task; import java.io.IOException; import java.util.Iterator; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import eu.stratosphere.nephele.execution.librarycache.LibraryCacheManager; import eu.stratosphere.nephele.io.BipartiteDistributionPattern; import eu.stratosphere.nephele.io.DistributionPattern; import eu.stratosphere.nephele.io.PointwiseDistributionPattern; import eu.stratosphere.nephele.io.RecordDeserializer; import eu.stratosphere.nephele.io.RecordReader; import eu.stratosphere.nephele.io.RecordWriter; import eu.stratosphere.nephele.services.ServiceException; import eu.stratosphere.nephele.services.iomanager.IOManager; import eu.stratosphere.nephele.services.memorymanager.MemoryAllocationException; import eu.stratosphere.nephele.services.memorymanager.MemoryManager; import eu.stratosphere.nephele.template.AbstractTask; import eu.stratosphere.pact.common.stub.CrossStub; import eu.stratosphere.pact.common.type.Key; import eu.stratosphere.pact.common.type.KeyValuePair; import eu.stratosphere.pact.common.type.Value; import eu.stratosphere.pact.runtime.resettable.BlockResettableIterator; import eu.stratosphere.pact.runtime.resettable.SpillingResettableIterator; import eu.stratosphere.pact.runtime.serialization.KeyValuePairDeserializer; import eu.stratosphere.pact.runtime.task.util.LastRepeatableIterator; import eu.stratosphere.pact.runtime.task.util.NepheleReaderIterator; import eu.stratosphere.pact.runtime.task.util.OutputCollector; import eu.stratosphere.pact.runtime.task.util.OutputEmitter; import eu.stratosphere.pact.runtime.task.util.SerializationCopier; import eu.stratosphere.pact.runtime.task.util.TaskConfig; import eu.stratosphere.pact.runtime.task.util.TaskConfig.LocalStrategy; /** * Cross task which is executed by a Nephele task manager. The task has two * inputs and one or multiple outputs. It is provided with a CrossStub * implementation. * <p> * The CrossTask builds the Cartesian product of the pairs of its two inputs. Each element (pair of pairs) is handed to * the <code>cross()</code> method of the CrossStub. * * @see eu.stratosphere.pact.common.stub.CrossStub * @author Fabian Hueske */ @SuppressWarnings({"unchecked", "rawtypes"}) public class CrossTask extends AbstractTask { // obtain CrossTask logger private static final Log LOG = LogFactory.getLog(CrossTask.class); // the minimal amount of memory for the task to operate private static final long MIN_REQUIRED_MEMORY = 1 * 1024 * 1024; // reader for first input private Iterator<KeyValuePair<Key, Value>> input1; // reader for second input private Iterator<KeyValuePair<Key, Value>> input2; // output collector private OutputCollector<Key, Value> output; // cross stub implementation instance private CrossStub stub; // task config including stub parameters private TaskConfig config; // spilling resettable iterator for inner input private SpillingResettableIterator<KeyValuePair<Key, Value>> spillingResetIt = null; private BlockResettableIterator<KeyValuePair<Key, Value>> blockResetIt = null; // the memory dedicated to the sorter private long availableMemory; // cancel flag private volatile boolean taskCanceled = false; /** * {@inheritDoc} */ @Override public void registerInputOutput() { if (LOG.isDebugEnabled()) LOG.debug(getLogString("Start registering input and output")); // Initialize stub implementation initStub(); // Initialize input reader initInputReaders(); // Initializes output writers and collector initOutputCollector(); if (LOG.isDebugEnabled()) LOG.debug(getLogString("Finished registering input and output")); } /** * {@inheritDoc} */ @Override public void invoke() throws Exception { if (LOG.isInfoEnabled()) LOG.info(getLogString("Start PACT code")); // inner reader for nested loops final Iterator<KeyValuePair<Key, Value>> innerInput; // outer reader for nested loops final Iterator<KeyValuePair<Key, Value>> outerInput; // assign inner and outer readers according to local strategy decision if (config.getLocalStrategy() == LocalStrategy.NESTEDLOOP_BLOCKED_OUTER_SECOND || config.getLocalStrategy() == LocalStrategy.NESTEDLOOP_STREAMED_OUTER_SECOND) { innerInput = this.input1; outerInput = this.input2; } else if (config.getLocalStrategy() == LocalStrategy.NESTEDLOOP_BLOCKED_OUTER_FIRST || config.getLocalStrategy() == LocalStrategy.NESTEDLOOP_STREAMED_OUTER_FIRST) { innerInput = this.input2; outerInput = this.input1; } else { throw new RuntimeException("Invalid local strategy for CROSS: " + config.getLocalStrategy()); } // obtain memory manager from task manager final MemoryManager memoryManager = getEnvironment().getMemoryManager(); // obtain IO manager from task manager final IOManager ioManager = getEnvironment().getIOManager(); // run nested loops strategy according to local strategy decision if (config.getLocalStrategy() == LocalStrategy.NESTEDLOOP_BLOCKED_OUTER_FIRST || config.getLocalStrategy() == LocalStrategy.NESTEDLOOP_BLOCKED_OUTER_SECOND) { // run blocked nested loop strategy runBlocked(memoryManager, ioManager, innerInput, outerInput); } else { // run streaming nested loop strategy (this is an opportunistic // choice!) runStreamed(memoryManager, ioManager, innerInput, outerInput); } if(!this.taskCanceled) { if (LOG.isInfoEnabled()) LOG.info(getLogString("Finished PACT code")); } else { if (LOG.isWarnEnabled()) LOG.warn(getLogString("PACT code cancelled")); } } /* (non-Javadoc) * @see eu.stratosphere.nephele.template.AbstractInvokable#cancel() */ @Override public void cancel() throws Exception { this.taskCanceled = true; if (this.spillingResetIt != null) { this.spillingResetIt.abort(); } if (this.blockResetIt != null) { this.blockResetIt.close(); this.blockResetIt = null; } if (LOG.isWarnEnabled()) LOG.warn(getLogString("Cancelling PACT code")); } /** * Initializes the stub implementation and configuration. * * @throws RuntimeException * Throws if instance of stub implementation can not be * obtained. */ private void initStub() throws RuntimeException { // obtain task configuration (including stub parameters) this.config = new TaskConfig(getRuntimeConfiguration()); // set up memory and I/O parameters this.availableMemory = this.config.getMemorySize(); // test minimum memory requirements long strategyMinMem = 0; switch (this.config.getLocalStrategy()) { case NESTEDLOOP_BLOCKED_OUTER_FIRST: case NESTEDLOOP_BLOCKED_OUTER_SECOND: case NESTEDLOOP_STREAMED_OUTER_FIRST: case NESTEDLOOP_STREAMED_OUTER_SECOND: strategyMinMem = MIN_REQUIRED_MEMORY; break; } if (this.availableMemory < strategyMinMem) { throw new RuntimeException( "The Cross task was initialized with too little memory for local strategy "+ config.getLocalStrategy()+" : " + this.availableMemory + " bytes." + "Required is at least " + strategyMinMem + " bytes."); } try { // obtain stub implementation class ClassLoader cl = LibraryCacheManager.getClassLoader(getEnvironment().getJobID()); Class<? extends CrossStub> stubClass = config.getStubClass(CrossStub.class, cl); // obtain stub implementation instance this.stub = stubClass.newInstance(); // configure stub instance this.stub.configure(this.config.getStubParameters()); } catch (IOException ioe) { throw new RuntimeException("Library cache manager could not be instantiated.", ioe); } catch (ClassNotFoundException cnfe) { throw new RuntimeException("Stub implementation class was not found.", cnfe); } catch (InstantiationException ie) { throw new RuntimeException("Stub implementation could not be instanciated.", ie); } catch (IllegalAccessException iae) { throw new RuntimeException("Stub implementations nullary constructor is not accessible.", iae); } } /** * Initializes the input readers of the CrossTask. * * @throws RuntimeException * Thrown if an input ship strategy was provided. */ private void initInputReaders() throws RuntimeException { // create RecordDeserializer for first input RecordDeserializer<KeyValuePair<Key, Value>> deserializer1 = new KeyValuePairDeserializer<Key, Value>(stub .getFirstInKeyType(), stub.getFirstInValueType()); // create RecordDeserializer for second input RecordDeserializer<KeyValuePair<Key, Value>> deserializer2 = new KeyValuePairDeserializer<Key, Value>(stub .getSecondInKeyType(), stub.getSecondInValueType()); // determine distribution pattern of first input (id=0) DistributionPattern dp1 = null; switch (config.getInputShipStrategy(0)) { case FORWARD: // forward requires Pointwise DP dp1 = new PointwiseDistributionPattern(); break; case PARTITION_HASH: // partition requires Bipartite DP dp1 = new BipartiteDistributionPattern(); break; case BROADCAST: // broadcast requires Bipartite DP dp1 = new BipartiteDistributionPattern(); break; case SFR: // sfr requires Bipartite DP dp1 = new BipartiteDistributionPattern(); break; default: throw new RuntimeException("No input ship strategy provided for first input of CrossTask."); } // determine distribution pattern of second input (id=1) DistributionPattern dp2 = null; switch (config.getInputShipStrategy(1)) { case FORWARD: // forward requires Pointwise DP dp2 = new PointwiseDistributionPattern(); break; case PARTITION_HASH: // partition requires Bipartite DP dp2 = new BipartiteDistributionPattern(); break; case BROADCAST: // broadcast requires Bipartite DP dp2 = new BipartiteDistributionPattern(); break; case SFR: // sfr requires Bipartite DP dp2 = new BipartiteDistributionPattern(); break; default: throw new RuntimeException("No input ship strategy provided for second input of CrossTask."); } // create reader of first input this.input1 = new NepheleReaderIterator<KeyValuePair<Key, Value>>(new RecordReader<KeyValuePair<Key, Value>>(this, deserializer1, dp1)); // create reader of second input this.input2 = new NepheleReaderIterator<KeyValuePair<Key, Value>>(new RecordReader<KeyValuePair<Key, Value>>(this, deserializer2, dp2)); } /** * Creates a writer for each output. Creates an OutputCollector which * forwards its input to all writers. */ private void initOutputCollector() { boolean fwdCopyFlag = false; // create output collector this.output = new OutputCollector<Key, Value>(); // create a writer for each output for (int i = 0; i < this.config.getNumOutputs(); i++) { // obtain OutputEmitter from output ship strategy OutputEmitter oe = new OutputEmitter(this.config.getOutputShipStrategy(i)); // create writer RecordWriter<KeyValuePair<Key, Value>> writer; writer = new RecordWriter<KeyValuePair<Key, Value>>(this, (Class<KeyValuePair<Key, Value>>) (Class<?>) KeyValuePair.class, oe); // add writer to output collector // the first writer does not need to send a copy // all following must send copies // TODO smarter decision are possible here, e.g. decide which channel may not need to copy, ... this.output.addWriter(writer, fwdCopyFlag); fwdCopyFlag = true; } } /** * Runs a blocked nested loop strategy to build the Cartesian product and * call the <code>cross()</code> method of the CrossStub implementation. The * outer side is read using a BlockResettableIterator. The inner side is * read using a SpillingResettableIterator. * * @see eu.stratosphere.pact.runtime.resettable.SpillingResettableIterator * @see eu.stratosphere.pact.runtime.resettable.BlockResettableIterator * @param memoryManager * The task manager's memory manager. * @param ioManager * The task manager's IO manager * @param innerReader * The inner reader of the nested loops. * @param outerReader * The outer reader of the nested loops. * @throws RuntimeException * Throws a RuntimeException if something fails during * execution. */ private void runBlocked(MemoryManager memoryManager, IOManager ioManager, Iterator<KeyValuePair<Key, Value>> innerReader, Iterator<KeyValuePair<Key, Value>> outerReader) throws Exception { // spilling iterator for inner side SpillingResettableIterator<KeyValuePair<Key, Value>> innerInput = null; // blocked iterator for outer side BlockResettableIterator<KeyValuePair<Key, Value>> outerInput = null; try { final boolean firstInputIsOuter; // obtain iterators according to local strategy decision if (this.config.getLocalStrategy() == LocalStrategy.NESTEDLOOP_BLOCKED_OUTER_SECOND) { // obtain spilling iterator (inner side) for first input try { innerInput = new SpillingResettableIterator<KeyValuePair<Key, Value>>(memoryManager, ioManager, innerReader, this.availableMemory / 2, new KeyValuePairDeserializer<Key, Value>(stub.getFirstInKeyType(), stub .getFirstInValueType()), this); this.spillingResetIt = innerInput; } catch (MemoryAllocationException mae) { throw new RuntimeException("Unable to obtain SpillingResettableIterator for first input", mae); } // obtain blocked iterator (outer side) for second input try { outerInput = new BlockResettableIterator<KeyValuePair<Key, Value>>(memoryManager, outerReader, this.availableMemory / 2, 1, new KeyValuePairDeserializer<Key, Value>(stub.getSecondInKeyType(), stub.getSecondInValueType()), this); this.blockResetIt = outerInput; } catch (MemoryAllocationException mae) { throw new RuntimeException("Unable to obtain BlockResettableIterator for second input", mae); } firstInputIsOuter = false; } else if (this.config.getLocalStrategy() == LocalStrategy.NESTEDLOOP_BLOCKED_OUTER_FIRST) { // obtain spilling iterator (inner side) for second input try { innerInput = new SpillingResettableIterator<KeyValuePair<Key, Value>>(memoryManager, ioManager, innerReader, this.availableMemory / 2, new KeyValuePairDeserializer<Key, Value>(stub.getSecondInKeyType(), stub.getSecondInValueType()), this); this.spillingResetIt = innerInput; } catch (MemoryAllocationException mae) { throw new RuntimeException("Unable to obtain SpillingResettableIterator for second input", mae); } // obtain blocked iterator (outer side) for second input try { outerInput = new BlockResettableIterator<KeyValuePair<Key, Value>>(memoryManager, outerReader, this.availableMemory / 2, 1, new KeyValuePairDeserializer<Key, Value>(stub.getFirstInKeyType(), stub .getFirstInValueType()), this); this.blockResetIt = outerInput; } catch (MemoryAllocationException mae) { throw new RuntimeException("Unable to obtain BlockResettableIterator for first input", mae); } firstInputIsOuter = true; } else { throw new RuntimeException("Invalid local strategy for CrossTask: " + config.getLocalStrategy()); } // open spilling resettable iterator try { innerInput.open(); } catch (ServiceException se) { throw new RuntimeException("Unable to open SpillingResettableIterator", se); } catch (IOException ioe) { throw new RuntimeException("Unable to open SpillingResettableIterator", ioe); } catch (InterruptedException ie) { throw new RuntimeException("Unable to open SpillingResettableIterator", ie); } // check if task was canceled while data was read if (this.taskCanceled) return; // open blocked resettable iterator outerInput.open(); if (LOG.isDebugEnabled()) { LOG.debug(getLogString("SpillingResettable iterator obtained")); LOG.debug(getLogString("BlockResettable iterator obtained")); } // open stub implementation this.stub.open(); boolean moreOuterBlocks = false; if (innerInput.hasNext()) { // avoid painful work when one input is empty do { // loop over the spilled resettable iterator while (!this.taskCanceled && innerInput.hasNext()) { // get inner pair KeyValuePair<Key, Value> innerPair = innerInput.next(); // loop over the pairs in the current memory block while (!this.taskCanceled && outerInput.hasNext()) { // get outer pair KeyValuePair<Key, Value> outerPair = outerInput.next(); // call cross() method of CrossStub depending on local strategy if(firstInputIsOuter) { stub.cross(outerPair.getKey(), outerPair.getValue(), innerPair.getKey(), innerPair.getValue(), output); } else { stub.cross(innerPair.getKey(), innerPair.getValue(), outerPair.getKey(), outerPair.getValue(), output); } innerPair = innerInput.repeatLast(); } // reset the memory block iterator to the beginning of the // current memory block (outer side) outerInput.reset(); } // reset the spilling resettable iterator (inner side) moreOuterBlocks = outerInput.nextBlock(); if(moreOuterBlocks) { innerInput.reset(); } } while (!this.taskCanceled && moreOuterBlocks); + } else { + // inner input is empty, clear outer input to close channel + LOG.debug("Inner input is empty, we must clear the outer input as well to close the channel"); + do { + while(outerInput.hasNext()) { + outerInput.next(); + } + } while(outerInput.nextBlock()); } // close stub implementation this.stub.close(); } catch (Exception ex) { // drop, if the task was canceled if (!this.taskCanceled) { LOG.error(getLogString("Unexpected ERROR in PACT code")); throw ex; } } finally { Throwable t1 = null, t2 = null; try { if(innerInput != null) { innerInput.close(); } } catch (Throwable t) { LOG.warn(t); t1 = t; } try { if(outerInput != null) { outerInput.close(); } } catch (Throwable t) { LOG.warn(t); t2 = t; } if(t1 != null) throw new RuntimeException("Error closing SpillingResettableIterator.", t1); if(t2 != null) throw new RuntimeException("Error closung BlockResettableIterator.", t2); } } /** * Runs a streamed nested loop strategy to build the Cartesian product and * call the <code>cross()</code> method of the CrossStub implementation. * The outer side is read directly from the input reader. The inner side is * read and reseted using a SpillingResettableIterator. * * @see eu.stratosphere.pact.runtime.resettable.SpillingResettableIterator * @param memoryManager * The task manager's memory manager. * @param ioManager * The task manager's IO manager * @param innerReader * The inner reader of the nested loops. * @param outerReader * The outer reader of the nested loops. * @throws RuntimeException * Throws a RuntimeException if something fails during * execution. */ private void runStreamed(MemoryManager memoryManager, IOManager ioManager, Iterator<KeyValuePair<Key, Value>> innerReader, final Iterator<KeyValuePair<Key, Value>> outerReader) throws Exception { // obtain streaming iterator for outer side // streaming is achieved by simply wrapping the input reader of the outer side // obtain SpillingResettableIterator for inner side SpillingResettableIterator<KeyValuePair<Key, Value>> innerInput = null; RepeatableIterator outerInput = null; try { final boolean firstInputIsOuter; if(config.getLocalStrategy() == LocalStrategy.NESTEDLOOP_STREAMED_OUTER_FIRST) { // obtain spilling resettable iterator for first input try { innerInput = new SpillingResettableIterator<KeyValuePair<Key, Value>>(memoryManager, ioManager, innerReader, this.availableMemory, new KeyValuePairDeserializer<Key, Value>(stub.getSecondInKeyType(), stub .getSecondInValueType()), this); spillingResetIt = innerInput; } catch (MemoryAllocationException mae) { throw new RuntimeException("Unable to obtain SpillingResettable iterator for inner side.", mae); } // obtain repeatable iterator for second input outerInput = new RepeatableIterator(outerReader, stub.getFirstInKeyType(), stub.getFirstInValueType()); firstInputIsOuter = true; } else if(config.getLocalStrategy() == LocalStrategy.NESTEDLOOP_STREAMED_OUTER_SECOND) { // obtain spilling resettable iterator for second input try { innerInput = new SpillingResettableIterator<KeyValuePair<Key, Value>>(memoryManager, ioManager, innerReader, this.availableMemory, new KeyValuePairDeserializer<Key, Value>(stub.getFirstInKeyType(), stub .getFirstInValueType()), this); spillingResetIt = innerInput; } catch (MemoryAllocationException mae) { throw new RuntimeException("Unable to obtain SpillingResettable iterator for inner side.", mae); } // obtain repeatable iterator for first input outerInput = new RepeatableIterator(outerReader, stub.getSecondInKeyType(), stub.getSecondInValueType()); firstInputIsOuter = false; } else { throw new RuntimeException("Invalid local strategy for CrossTask: " + config.getLocalStrategy()); } // open spilling resettable iterator try { innerInput.open(); } catch (ServiceException se) { throw new RuntimeException("Unable to open SpillingResettable iterator for inner side.", se); } catch (IOException ioe) { throw new RuntimeException("Unable to open SpillingResettable iterator for inner side.", ioe); } catch (InterruptedException ie) { throw new RuntimeException("Unable to open SpillingResettable iterator for inner side.", ie); } if (this.taskCanceled) return; if (LOG.isDebugEnabled()) LOG.debug(getLogString("Resetable iterator obtained")); // open stub implementation stub.open(); // if (config.getLocalStrategy() == LocalStrategy.NESTEDLOOP_STREAMED_OUTER_SECOND) { // read streamed iterator of outer side while (!this.taskCanceled && outerInput.hasNext()) { // get outer pair KeyValuePair outerPair = outerInput.next(); // read spilled iterator of inner side while (!this.taskCanceled && innerInput.hasNext()) { // get inner pair KeyValuePair innerPair = innerInput.next(); // call cross() method of CrossStub depending on local strategy if(firstInputIsOuter) { stub.cross(outerPair.getKey(), outerPair.getValue(), innerPair.getKey(), innerPair.getValue(), output); } else { stub.cross(innerPair.getKey(), innerPair.getValue(), outerPair.getKey(), outerPair.getValue(), output); } outerPair = outerInput.repeatLast(); } // reset spilling resettable iterator of inner side if(!this.taskCanceled && outerInput.hasNext()) { innerInput.reset(); } } // close stub implementation stub.close(); } catch (Exception ex) { // drop, if the task was canceled if (!this.taskCanceled) { LOG.error(getLogString("Unexpected ERROR in PACT code")); throw ex; } } finally { // close spilling resettable iterator if(innerInput != null) { innerInput.close(); } } } // -------------------------------------------------------------------------------------------- /** * Utility class that turns a standard {@link java.util.Iterator} for key/value pairs into a * {@link LastRepeatableIterator}. */ private static final class RepeatableIterator implements LastRepeatableIterator<KeyValuePair<Key, Value>> { private final SerializationCopier<KeyValuePair<Key, Value>> copier = new SerializationCopier<KeyValuePair<Key,Value>>(); private final KeyValuePairDeserializer<Key, Value> deserializer; private final Iterator<KeyValuePair<Key,Value>> input; public RepeatableIterator(Iterator<KeyValuePair<Key,Value>> input, Class<Key> keyClass, Class<Value> valClass) { this.input = input; this.deserializer = new KeyValuePairDeserializer<Key, Value>(keyClass, valClass); } @Override public boolean hasNext() { return this.input.hasNext(); } @Override public KeyValuePair<Key, Value> next() { KeyValuePair<Key,Value> pair = this.input.next(); // serialize pair this.copier.setCopy(pair); return pair; } @Override public void remove() { throw new UnsupportedOperationException(); } @Override public KeyValuePair<Key, Value> repeatLast() { KeyValuePair<Key,Value> pair = this.deserializer.getInstance(); this.copier.getCopy(pair); return pair; } } // -------------------------------------------------------------------------------------------- /** * Utility function that composes a string for logging purposes. The string includes the given message and * the index of the task in its task group together with the number of tasks in the task group. * * @param message The main message for the log. * @return The string ready for logging. */ private String getLogString(String message) { StringBuilder bld = new StringBuilder(128); bld.append(message); bld.append(':').append(' '); bld.append(this.getEnvironment().getTaskName()); bld.append(' ').append('('); bld.append(this.getEnvironment().getIndexInSubtaskGroup() + 1); bld.append('/'); bld.append(this.getEnvironment().getCurrentNumberOfSubtasks()); bld.append(')'); return bld.toString(); } }
true
true
private void runBlocked(MemoryManager memoryManager, IOManager ioManager, Iterator<KeyValuePair<Key, Value>> innerReader, Iterator<KeyValuePair<Key, Value>> outerReader) throws Exception { // spilling iterator for inner side SpillingResettableIterator<KeyValuePair<Key, Value>> innerInput = null; // blocked iterator for outer side BlockResettableIterator<KeyValuePair<Key, Value>> outerInput = null; try { final boolean firstInputIsOuter; // obtain iterators according to local strategy decision if (this.config.getLocalStrategy() == LocalStrategy.NESTEDLOOP_BLOCKED_OUTER_SECOND) { // obtain spilling iterator (inner side) for first input try { innerInput = new SpillingResettableIterator<KeyValuePair<Key, Value>>(memoryManager, ioManager, innerReader, this.availableMemory / 2, new KeyValuePairDeserializer<Key, Value>(stub.getFirstInKeyType(), stub .getFirstInValueType()), this); this.spillingResetIt = innerInput; } catch (MemoryAllocationException mae) { throw new RuntimeException("Unable to obtain SpillingResettableIterator for first input", mae); } // obtain blocked iterator (outer side) for second input try { outerInput = new BlockResettableIterator<KeyValuePair<Key, Value>>(memoryManager, outerReader, this.availableMemory / 2, 1, new KeyValuePairDeserializer<Key, Value>(stub.getSecondInKeyType(), stub.getSecondInValueType()), this); this.blockResetIt = outerInput; } catch (MemoryAllocationException mae) { throw new RuntimeException("Unable to obtain BlockResettableIterator for second input", mae); } firstInputIsOuter = false; } else if (this.config.getLocalStrategy() == LocalStrategy.NESTEDLOOP_BLOCKED_OUTER_FIRST) { // obtain spilling iterator (inner side) for second input try { innerInput = new SpillingResettableIterator<KeyValuePair<Key, Value>>(memoryManager, ioManager, innerReader, this.availableMemory / 2, new KeyValuePairDeserializer<Key, Value>(stub.getSecondInKeyType(), stub.getSecondInValueType()), this); this.spillingResetIt = innerInput; } catch (MemoryAllocationException mae) { throw new RuntimeException("Unable to obtain SpillingResettableIterator for second input", mae); } // obtain blocked iterator (outer side) for second input try { outerInput = new BlockResettableIterator<KeyValuePair<Key, Value>>(memoryManager, outerReader, this.availableMemory / 2, 1, new KeyValuePairDeserializer<Key, Value>(stub.getFirstInKeyType(), stub .getFirstInValueType()), this); this.blockResetIt = outerInput; } catch (MemoryAllocationException mae) { throw new RuntimeException("Unable to obtain BlockResettableIterator for first input", mae); } firstInputIsOuter = true; } else { throw new RuntimeException("Invalid local strategy for CrossTask: " + config.getLocalStrategy()); } // open spilling resettable iterator try { innerInput.open(); } catch (ServiceException se) { throw new RuntimeException("Unable to open SpillingResettableIterator", se); } catch (IOException ioe) { throw new RuntimeException("Unable to open SpillingResettableIterator", ioe); } catch (InterruptedException ie) { throw new RuntimeException("Unable to open SpillingResettableIterator", ie); } // check if task was canceled while data was read if (this.taskCanceled) return; // open blocked resettable iterator outerInput.open(); if (LOG.isDebugEnabled()) { LOG.debug(getLogString("SpillingResettable iterator obtained")); LOG.debug(getLogString("BlockResettable iterator obtained")); } // open stub implementation this.stub.open(); boolean moreOuterBlocks = false; if (innerInput.hasNext()) { // avoid painful work when one input is empty do { // loop over the spilled resettable iterator while (!this.taskCanceled && innerInput.hasNext()) { // get inner pair KeyValuePair<Key, Value> innerPair = innerInput.next(); // loop over the pairs in the current memory block while (!this.taskCanceled && outerInput.hasNext()) { // get outer pair KeyValuePair<Key, Value> outerPair = outerInput.next(); // call cross() method of CrossStub depending on local strategy if(firstInputIsOuter) { stub.cross(outerPair.getKey(), outerPair.getValue(), innerPair.getKey(), innerPair.getValue(), output); } else { stub.cross(innerPair.getKey(), innerPair.getValue(), outerPair.getKey(), outerPair.getValue(), output); } innerPair = innerInput.repeatLast(); } // reset the memory block iterator to the beginning of the // current memory block (outer side) outerInput.reset(); } // reset the spilling resettable iterator (inner side) moreOuterBlocks = outerInput.nextBlock(); if(moreOuterBlocks) { innerInput.reset(); } } while (!this.taskCanceled && moreOuterBlocks); } // close stub implementation this.stub.close(); } catch (Exception ex) { // drop, if the task was canceled if (!this.taskCanceled) { LOG.error(getLogString("Unexpected ERROR in PACT code")); throw ex; } } finally { Throwable t1 = null, t2 = null; try { if(innerInput != null) { innerInput.close(); } } catch (Throwable t) { LOG.warn(t); t1 = t; } try { if(outerInput != null) { outerInput.close(); } } catch (Throwable t) { LOG.warn(t); t2 = t; } if(t1 != null) throw new RuntimeException("Error closing SpillingResettableIterator.", t1); if(t2 != null) throw new RuntimeException("Error closung BlockResettableIterator.", t2); } }
private void runBlocked(MemoryManager memoryManager, IOManager ioManager, Iterator<KeyValuePair<Key, Value>> innerReader, Iterator<KeyValuePair<Key, Value>> outerReader) throws Exception { // spilling iterator for inner side SpillingResettableIterator<KeyValuePair<Key, Value>> innerInput = null; // blocked iterator for outer side BlockResettableIterator<KeyValuePair<Key, Value>> outerInput = null; try { final boolean firstInputIsOuter; // obtain iterators according to local strategy decision if (this.config.getLocalStrategy() == LocalStrategy.NESTEDLOOP_BLOCKED_OUTER_SECOND) { // obtain spilling iterator (inner side) for first input try { innerInput = new SpillingResettableIterator<KeyValuePair<Key, Value>>(memoryManager, ioManager, innerReader, this.availableMemory / 2, new KeyValuePairDeserializer<Key, Value>(stub.getFirstInKeyType(), stub .getFirstInValueType()), this); this.spillingResetIt = innerInput; } catch (MemoryAllocationException mae) { throw new RuntimeException("Unable to obtain SpillingResettableIterator for first input", mae); } // obtain blocked iterator (outer side) for second input try { outerInput = new BlockResettableIterator<KeyValuePair<Key, Value>>(memoryManager, outerReader, this.availableMemory / 2, 1, new KeyValuePairDeserializer<Key, Value>(stub.getSecondInKeyType(), stub.getSecondInValueType()), this); this.blockResetIt = outerInput; } catch (MemoryAllocationException mae) { throw new RuntimeException("Unable to obtain BlockResettableIterator for second input", mae); } firstInputIsOuter = false; } else if (this.config.getLocalStrategy() == LocalStrategy.NESTEDLOOP_BLOCKED_OUTER_FIRST) { // obtain spilling iterator (inner side) for second input try { innerInput = new SpillingResettableIterator<KeyValuePair<Key, Value>>(memoryManager, ioManager, innerReader, this.availableMemory / 2, new KeyValuePairDeserializer<Key, Value>(stub.getSecondInKeyType(), stub.getSecondInValueType()), this); this.spillingResetIt = innerInput; } catch (MemoryAllocationException mae) { throw new RuntimeException("Unable to obtain SpillingResettableIterator for second input", mae); } // obtain blocked iterator (outer side) for second input try { outerInput = new BlockResettableIterator<KeyValuePair<Key, Value>>(memoryManager, outerReader, this.availableMemory / 2, 1, new KeyValuePairDeserializer<Key, Value>(stub.getFirstInKeyType(), stub .getFirstInValueType()), this); this.blockResetIt = outerInput; } catch (MemoryAllocationException mae) { throw new RuntimeException("Unable to obtain BlockResettableIterator for first input", mae); } firstInputIsOuter = true; } else { throw new RuntimeException("Invalid local strategy for CrossTask: " + config.getLocalStrategy()); } // open spilling resettable iterator try { innerInput.open(); } catch (ServiceException se) { throw new RuntimeException("Unable to open SpillingResettableIterator", se); } catch (IOException ioe) { throw new RuntimeException("Unable to open SpillingResettableIterator", ioe); } catch (InterruptedException ie) { throw new RuntimeException("Unable to open SpillingResettableIterator", ie); } // check if task was canceled while data was read if (this.taskCanceled) return; // open blocked resettable iterator outerInput.open(); if (LOG.isDebugEnabled()) { LOG.debug(getLogString("SpillingResettable iterator obtained")); LOG.debug(getLogString("BlockResettable iterator obtained")); } // open stub implementation this.stub.open(); boolean moreOuterBlocks = false; if (innerInput.hasNext()) { // avoid painful work when one input is empty do { // loop over the spilled resettable iterator while (!this.taskCanceled && innerInput.hasNext()) { // get inner pair KeyValuePair<Key, Value> innerPair = innerInput.next(); // loop over the pairs in the current memory block while (!this.taskCanceled && outerInput.hasNext()) { // get outer pair KeyValuePair<Key, Value> outerPair = outerInput.next(); // call cross() method of CrossStub depending on local strategy if(firstInputIsOuter) { stub.cross(outerPair.getKey(), outerPair.getValue(), innerPair.getKey(), innerPair.getValue(), output); } else { stub.cross(innerPair.getKey(), innerPair.getValue(), outerPair.getKey(), outerPair.getValue(), output); } innerPair = innerInput.repeatLast(); } // reset the memory block iterator to the beginning of the // current memory block (outer side) outerInput.reset(); } // reset the spilling resettable iterator (inner side) moreOuterBlocks = outerInput.nextBlock(); if(moreOuterBlocks) { innerInput.reset(); } } while (!this.taskCanceled && moreOuterBlocks); } else { // inner input is empty, clear outer input to close channel LOG.debug("Inner input is empty, we must clear the outer input as well to close the channel"); do { while(outerInput.hasNext()) { outerInput.next(); } } while(outerInput.nextBlock()); } // close stub implementation this.stub.close(); } catch (Exception ex) { // drop, if the task was canceled if (!this.taskCanceled) { LOG.error(getLogString("Unexpected ERROR in PACT code")); throw ex; } } finally { Throwable t1 = null, t2 = null; try { if(innerInput != null) { innerInput.close(); } } catch (Throwable t) { LOG.warn(t); t1 = t; } try { if(outerInput != null) { outerInput.close(); } } catch (Throwable t) { LOG.warn(t); t2 = t; } if(t1 != null) throw new RuntimeException("Error closing SpillingResettableIterator.", t1); if(t2 != null) throw new RuntimeException("Error closung BlockResettableIterator.", t2); } }
diff --git a/modules/resin/src/com/caucho/amber/field/EntityManyToOneField.java b/modules/resin/src/com/caucho/amber/field/EntityManyToOneField.java index f3a819c41..bbeba88c8 100644 --- a/modules/resin/src/com/caucho/amber/field/EntityManyToOneField.java +++ b/modules/resin/src/com/caucho/amber/field/EntityManyToOneField.java @@ -1,1033 +1,1033 @@ /* * Copyright (c) 1998-2006 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 Scott Ferguson */ package com.caucho.amber.field; import com.caucho.amber.AmberRuntimeException; import com.caucho.amber.cfg.*; import com.caucho.amber.expr.AmberExpr; import com.caucho.amber.expr.ManyToOneExpr; import com.caucho.amber.expr.PathExpr; import com.caucho.amber.query.QueryParser; import com.caucho.amber.table.Column; import com.caucho.amber.table.ForeignColumn; import com.caucho.amber.table.LinkColumns; import com.caucho.amber.table.Table; import com.caucho.amber.type.*; import com.caucho.bytecode.JAnnotation; import com.caucho.config.ConfigException; import com.caucho.java.JavaWriter; import com.caucho.log.Log; import com.caucho.util.CharBuffer; import com.caucho.util.L10N; import javax.persistence.CascadeType; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.logging.Logger; /** * Represents a many-to-one link pointing to an entity. */ public class EntityManyToOneField extends CascadableField { private static final L10N L = new L10N(EntityManyToOneField.class); private static final Logger log = Log.open(EntityManyToOneField.class); private LinkColumns _linkColumns; private RelatedType _targetType; private int _targetLoadIndex; private DependentEntityOneToOneField _targetField; private PropertyField _aliasField; private boolean _isInsert = true; private boolean _isUpdate = true; private boolean _isSourceCascadeDelete; private boolean _isTargetCascadeDelete; private Object _joinColumnsAnn[]; private HashMap<String, JoinColumnConfig> _joinColumnMap = null; public EntityManyToOneField(RelatedType relatedType, String name, CascadeType[] cascadeType) throws ConfigException { super(relatedType, name, cascadeType); } public EntityManyToOneField(RelatedType relatedType, String name) throws ConfigException { this(relatedType, name, null); } public EntityManyToOneField(RelatedType relatedType) { super(relatedType); } /** * Sets the target type. */ public void setType(Type targetType) { if (! (targetType instanceof RelatedType)) throw new AmberRuntimeException(L.l("many-to-one requires an entity target at '{0}'", targetType)); _targetType = (RelatedType) targetType; } /** * Returns the source type as * entity or mapped-superclass. */ public RelatedType getRelatedType() { return (RelatedType) getSourceType(); } /** * Returns the target type as * entity or mapped-superclass. */ public RelatedType getEntityTargetType() { return _targetType; } /** * Returns the foreign type. */ public String getForeignTypeName() { //return ((KeyColumn) getColumn()).getType().getForeignTypeName(); return getEntityTargetType().getForeignTypeName(); } /** * Set true if deletes cascade to the target. */ public void setTargetCascadeDelete(boolean isCascadeDelete) { _isTargetCascadeDelete = isCascadeDelete; } /** * Set true if deletes cascade to the source. */ public void setSourceCascadeDelete(boolean isCascadeDelete) { _isSourceCascadeDelete = isCascadeDelete; } /** * Set true if deletes cascade to the target. */ public boolean isTargetCascadeDelete() { return _isTargetCascadeDelete; } /** * Set true if deletes cascade to the source. */ public boolean isSourceCascadeDelete() { return _isSourceCascadeDelete; } /** * Sets the join column annotations. */ public void setJoinColumns(Object joinColumnsAnn[]) { _joinColumnsAnn = joinColumnsAnn; } /** * Gets the join column annotations. */ public Object[] getJoinColumns() { return _joinColumnsAnn; } /** * Sets the join column map. */ public void setJoinColumnMap(HashMap<String, JoinColumnConfig> joinColumnMap) { _joinColumnMap = joinColumnMap; } /** * Gets the join column map. */ public HashMap<String, JoinColumnConfig> getJoinColumnMap() { return _joinColumnMap; } /** * Sets the join columns. */ public void setLinkColumns(LinkColumns linkColumns) { _linkColumns = linkColumns; } /** * Gets the columns. */ public LinkColumns getLinkColumns() { return _linkColumns; } /** * Sets the target field. */ public void setTargetField(DependentEntityOneToOneField field) { _targetField = field; } /** * Sets any alias field. */ public void setAliasField(PropertyField alias) { _aliasField = alias; } /** * Initializes the field. */ public void init() throws ConfigException { init(getRelatedType()); } /** * Initializes the field. */ public void init(RelatedType relatedType) throws ConfigException { Table sourceTable = relatedType.getTable(); if (sourceTable == null || ! relatedType.getPersistenceUnit().isJPA()) { // jpa/0ge3, ejb/0602 super.init(); _targetLoadIndex = relatedType.getLoadGroupIndex(); return; } int n = 0; if (_joinColumnMap != null) n = _joinColumnMap.size(); ArrayList<ForeignColumn> foreignColumns = new ArrayList<ForeignColumn>(); RelatedType parentType = _targetType; ArrayList<Column> targetIdColumns = _targetType.getId().getColumns(); while (targetIdColumns.size() == 0) { parentType = parentType.getParentType(); if (parentType == null) break; targetIdColumns = parentType.getId().getColumns(); } for (Column keyColumn : targetIdColumns) { String columnName; if (getRelatedType().getPersistenceUnit().isJPA()) columnName = getName().toUpperCase() + '_' + keyColumn.getName(); else { // ejb/0602 columnName = keyColumn.getName(); } boolean nullable = true; boolean unique = false; if (n > 0) { JoinColumnConfig joinColumn; if (n == 1) { joinColumn = (JoinColumnConfig) _joinColumnMap.values().toArray()[0]; } else joinColumn = _joinColumnMap.get(keyColumn.getName()); if (joinColumn != null) { columnName = joinColumn.getName(); nullable = joinColumn.getNullable(); unique = joinColumn.getUnique(); } } else { JAnnotation joinAnn = BaseConfigIntrospector.getJoinColumn(_joinColumnsAnn, keyColumn.getName()); if (joinAnn != null) { columnName = joinAnn.getString("name"); nullable = joinAnn.getBoolean("nullable"); unique = joinAnn.getBoolean("unique"); } } ForeignColumn foreignColumn; foreignColumn = sourceTable.createForeignColumn(columnName, keyColumn); foreignColumn.setNotNull(! nullable); foreignColumn.setUnique(unique); foreignColumns.add(foreignColumn); } LinkColumns linkColumns = new LinkColumns(sourceTable, _targetType.getTable(), foreignColumns); setLinkColumns(linkColumns); super.init(); Id id = getEntityTargetType().getId(); ArrayList<Column> keys = id.getColumns(); if (_linkColumns == null) { ArrayList<ForeignColumn> columns = new ArrayList<ForeignColumn>(); for (int i = 0; i < keys.size(); i++) { Column key = keys.get(i); String name; if (keys.size() == 1) name = getName(); else name = getName() + "_" + key.getName(); columns.add(sourceTable.createForeignColumn(name, key)); } _linkColumns = new LinkColumns(relatedType.getTable(), _targetType.getTable(), columns); } if (relatedType.getId() != null) { // resolve any alias for (AmberField field : relatedType.getId().getKeys()) { if (field instanceof PropertyField) { PropertyField prop = (PropertyField) field; for (ForeignColumn column : _linkColumns.getColumns()) { if (prop.getColumn().getName().equals(column.getName())) _aliasField = prop; } } } } _targetLoadIndex = relatedType.getLoadGroupIndex(); // nextLoadGroupIndex(); _linkColumns.setTargetCascadeDelete(isTargetCascadeDelete()); _linkColumns.setSourceCascadeDelete(isSourceCascadeDelete()); } /** * Generates the post constructor initialization. */ public void generatePostConstructor(JavaWriter out) throws IOException { out.println(getSetterName() + "(" + generateSuperGetter() + ");"); } /** * Creates the expression for the field. */ public AmberExpr createExpr(QueryParser parser, PathExpr parent) { return new ManyToOneExpr(parent, _linkColumns); } /** * Gets the column corresponding to the target field. */ public ForeignColumn getColumn(Column targetColumn) { return _linkColumns.getSourceColumn(targetColumn); } /** * Generates the insert. */ public void generateInsertColumns(ArrayList<String> columns) { if (_isInsert && _aliasField == null) _linkColumns.generateInsert(columns); } /** * Generates the select clause. */ public String generateLoadSelect(Table table, String id) { if (_aliasField != null) return null; if (_linkColumns == null) { // jpa/0ge3 return null; } if (_linkColumns.getSourceTable() != table) return null; else return _linkColumns.generateSelectSQL(id); } /** * Generates the select clause. */ public String generateSelect(String id) { if (_aliasField != null) return null; return _linkColumns.generateSelectSQL(id); } /** * Generates the update set clause */ public void generateUpdate(CharBuffer sql) { if (_aliasField != null) return; if (_isUpdate) { sql.append(_linkColumns.generateUpdateSQL()); } } /** * Generates any prologue. */ public void generatePrologue(JavaWriter out, HashSet<Object> completedSet) throws IOException { super.generatePrologue(out, completedSet); out.println(); Id id = getEntityTargetType().getId(); out.println("protected transient " + id.getForeignTypeName() + " __caucho_field_" + getName() + ";"); if (_aliasField == null) { id.generatePrologue(out, completedSet, getName()); } } /** * Generates the linking for a join */ public void generateJoin(CharBuffer cb, String sourceTable, String targetTable) { cb.append(_linkColumns.generateJoin(sourceTable, targetTable)); } /** * Generates loading code */ public int generateLoad(JavaWriter out, String rs, String indexVar, int index) throws IOException { if (_aliasField != null) return index; out.print("__caucho_field_" + getName() + " = "); index = getEntityTargetType().getId().generateLoadForeign(out, rs, indexVar, index, getName()); out.println(";"); /* // ejb/0a06 String proxy = "aConn.loadProxy(\"" + getEntityTargetType().getName() + "\", __caucho_field_" + getName() + ")"; proxy = "(" + getEntityTargetType().getProxyClass().getName() + ") " + proxy; out.println(generateSuperSetter(proxy) + ";"); */ // commented out jpa/0l40 // out.println(generateSuperSetter("null") + ";"); int group = _targetLoadIndex / 64; long mask = (1L << (_targetLoadIndex % 64)); //out.println("__caucho_loadMask_" + group + " &= ~" + mask + "L;"); return index; } /** * Generates loading code */ public int generateLoadEager(JavaWriter out, String rs, String indexVar, int index) throws IOException { if (! isLazy()) { int group = _targetLoadIndex / 64; long mask = (1L << (_targetLoadIndex % 64)); String loadVar = "__caucho_loadMask_" + group; // commented out jpa/0l40 // out.println(loadVar + " |= " + mask + "L;"); String javaType = getJavaTypeName(); // jpa/0o05 String indexS = "_" + group + "_" + index; generateLoadProperty(out, indexS, "aConn"); } return ++index; } /** * Generates the set property. */ public void generateGetProperty(JavaWriter out) throws IOException { String javaType = getJavaTypeName(); int group = _targetLoadIndex / 64; long mask = (1L << (_targetLoadIndex % 64)); String loadVar = "__caucho_loadMask_" + group; out.println(); out.println("public " + javaType + " __caucho_item_" + getGetterName() + "(com.caucho.amber.manager.AmberConnection aConn)"); out.println("{"); out.pushDepth(); out.println("if (aConn != null) {"); out.pushDepth(); String index = "_" + (_targetLoadIndex / 64); index += "_" + (1L << (_targetLoadIndex % 64)); if (_aliasField == null) { out.println("__caucho_load_" + getLoadGroupIndex() + "(aConn);"); } out.println(loadVar + " |= " + mask + "L;"); generateLoadProperty(out, index, "aConn"); out.println("return v"+index+";"); out.popDepth(); out.println("}"); out.println("return null;"); out.popDepth(); out.println("}"); out.println(); out.println("public " + javaType + " " + getGetterName() + "()"); out.println("{"); out.pushDepth(); String dirtyVar = "__caucho_dirtyMask_" + (getIndex() / 64); long dirtyMask = (1L << (getIndex() % 64)); // jpa/0h08: do not use cached item when field is dirty. out.println("boolean isDirtyField = (" + dirtyVar + " & " + dirtyMask + "L) != 0L;"); // jpa/0h07: detached entity fields must not be loaded. out.println("if (__caucho_session != null && __caucho_item != null && ! isDirtyField) {"); out.pushDepth(); // ejb/06h0 String extClassName = getRelatedType().getInstanceClassName(); // getRelatedType().getName() + "__ResinExt"; out.println(extClassName + " item = (" + extClassName + ") __caucho_item.getEntity();"); out.println("item.__caucho_item_" + getGetterName() + "(__caucho_session);"); generateCopyLoadObject(out, "super", "item", getLoadGroupIndex()); // out.println("__caucho_loadMask_" + group + " |= " + mask + "L;"); // out.println("__caucho_loadMask_" + group + " |= item.__caucho_loadMask_" + group + ";"); // mask + "L;"); out.println("__caucho_loadMask_" + group + " |= item.__caucho_loadMask_" + group + " & " + mask + "L;"); out.popDepth(); out.println("}"); out.println("else"); out.pushDepth(); out.print("if (__caucho_session != null && "); out.println("(" + loadVar + " & " + mask + "L) == 0) {"); out.pushDepth(); out.println("return __caucho_item_" + getGetterName() + "(__caucho_session);"); out.popDepth(); out.println("}"); out.popDepth(); out.println(); out.println("return " + generateSuperGetter() + ";"); out.popDepth(); out.println("}"); } /** * Generates the set property. */ public void generateLoadProperty(JavaWriter out, String index, String session) throws IOException { String javaType = getJavaTypeName(); // jpa/0o04 out.println(session + ".addEntity(this);"); // ejb/06h0 if (isAbstract()) { String proxy = "aConn.loadProxy(\"" + getEntityTargetType().getName() + "\", __caucho_field_" + getName() + ")"; proxy = getEntityTargetType().getProxyClass().getName() + " v" + index + " = (" + getEntityTargetType().getProxyClass().getName() + ") " + proxy + ";"; out.println(proxy); out.println(generateSuperSetter("v" + index) + ";"); } else { String targetType = _targetType.getBeanClass().getName(); out.print(targetType + " v"+index+" = (" + targetType + ") "+session+".find(" + targetType + ".class, "); if (_aliasField == null) { out.print("__caucho_field_" + getName()); } else { out.print(_aliasField.generateGet("super")); } out.println(");"); out.println(generateSuperSetter("v" + index) + ";"); } } /** * Updates the cached copy. */ public void generateCopyUpdateObject(JavaWriter out, String dst, String src, int updateIndex) throws IOException { // jpa/0s29 // if (getIndex() == updateIndex) { // order matters: ejb/06gc String var = "__caucho_field_" + getName(); out.println(generateAccessor(dst, var) + " = " + generateAccessor(src, var) + ";"); String value = generateGet(src); out.println(generateSet(dst, value) + ";"); // } } /** * Updates the cached copy. */ public void generateCopyLoadObject(JavaWriter out, String dst, String src, int updateIndex) throws IOException { // order matters: jpa/0h08, jpa/0h09 String value = generateGet(src); out.println(generateSet(dst, value) + ";"); // jpa/0o05 // if (getLoadGroupIndex() == updateIndex) { // order matters: ejb/06gc String var = "__caucho_field_" + getName(); out.println(generateAccessor(dst, var) + " = " + generateAccessor(src, var) + ";"); // jpa/0o05 if (! dst.equals("super")) { // || isLazy())) { out.println("((" + getRelatedType().getInstanceClassName() + ") " + dst + ")." + generateSuperSetter(generateSuperGetter()) + ";"); } // jpa/0o05 // } // commented out: jpa/0s29 // if (_targetLoadIndex == updateIndex) { // ejb/0h20 // } /* if (_targetLoadIndex == updateIndex) { // ejb/0a06 String value = generateGet(src); out.println(generateSet(dst, value) + ";"); } */ } private String generateAccessor(String src, String var) { if (src.equals("super")) return var; else return "((" + getRelatedType().getInstanceClassName() + ") " + src + ")." + var; } /** * Generates the set property. */ public void generateSetProperty(JavaWriter out) throws IOException { // ejb/06gc - updates with EJB 2.0 Id id = getEntityTargetType().getId(); String var = "__caucho_field_" + getName(); String keyType = getEntityTargetType().getId().getForeignTypeName(); out.println(); out.println("public void " + getSetterName() + "(" + getJavaTypeName() + " v)"); out.println("{"); out.pushDepth(); int group = getLoadGroupIndex() / 64; long loadMask = (1L << (getLoadGroupIndex() % 64)); String loadVar = "__caucho_loadMask_" + group; if (_aliasField == null) { out.println("if ((" + loadVar + " & " + loadMask + "L) == 0 && __caucho_session != null) {"); // ejb/0602 out.println(" __caucho_load_" + group + "(__caucho_session);"); out.println(); // jpa/0j5f out.println(" if (__caucho_session.isInTransaction())"); out.println(" __caucho_session.makeTransactional((com.caucho.amber.entity.Entity) this);"); out.println("}"); out.println(); out.println("if (v == null) {"); out.println(" if (" + var + " == null) {"); out.println(" " + generateSuperSetter("null") + ";"); out.println(" return;"); out.println(" }"); out.println(); out.println(" " + var + " = null;"); out.println("} else {"); out.pushDepth(); out.print(keyType + " key = "); RelatedType targetType = getEntityTargetType(); if (targetType.isEJBProxy(getJavaTypeName())) { // To handle EJB local objects. out.print(id.generateGetProxyKey("v")); } else { String v = "((" + getEntityTargetType().getInstanceClassName()+ ") v)"; out.print(id.toObject(id.generateGetProperty(v))); } out.println(";"); out.println(); out.println("if (key.equals(" + var + ")) {"); out.println(" " + generateSuperSetter("v") + ";"); out.println(" return;"); out.println("}"); out.println(); out.println(var + " = key;"); out.popDepth(); out.println("}"); out.println(); out.println(generateSuperSetter("v") + ";"); out.println(); out.println("if (__caucho_session != null) {"); out.pushDepth(); String dirtyVar = "__caucho_dirtyMask_" + (getIndex() / 64); long dirtyMask = (1L << (getIndex() % 64)); out.println(dirtyVar + " |= " + dirtyMask + "L;"); out.println(loadVar + " |= " + loadMask + "L;"); out.println("__caucho_session.update((com.caucho.amber.entity.Entity) this);"); out.println("__caucho_session.addCompletion(__caucho_home.createManyToOneCompletion(\"" + getName() + "\", (com.caucho.amber.entity.Entity) this, v));"); out.println(); out.popDepth(); out.println("}"); } else { out.println("throw new IllegalStateException(\"aliased field cannot be set\");"); } out.popDepth(); out.println("}"); } /** * Generates the flush check for this child. */ public boolean generateFlushCheck(JavaWriter out) throws IOException { // ejb/06bi if (! getRelatedType().getPersistenceUnit().isJPA()) return false; String getter = generateSuperGetter(); out.println("if (" + getter + " != null) {"); out.pushDepth(); String relatedEntity = "((com.caucho.amber.entity.Entity) " + getter + ")"; - out.println("com.caucho.amber.entity.EntityState state = " + relatedEntity + ".__caucho_getEntityState();"); + out.println("com.caucho.amber.entity.EntityState otherState = " + relatedEntity + ".__caucho_getEntityState();"); // jpa/0j5e as a negative test. out.println("if (" + relatedEntity + ".__caucho_getConnection() == null) {"); out.pushDepth(); // jpa/0j5c as a positive test. - out.println("if (! __caucho_state.isManaged())"); + out.println("if (__caucho_state.isManaged() && ! otherState.isManaged())"); String errorString = ("(\"amber flush: unable to flush " + getRelatedType().getName() + "[\" + __caucho_getPrimaryKey() + \"] "+ "with non-managed dependent relationship many-to-one to "+ getEntityTargetType().getName() + "\")"); out.println(" throw new IllegalStateException" + errorString + ";"); out.popDepth(); out.println("}"); out.popDepth(); out.println("}"); return true; } /** * Generates the set clause. */ public void generateSet(JavaWriter out, String pstmt, String index, String source) throws IOException { if (_aliasField != null) return; if (source == null) { throw new NullPointerException(); } String var = "__caucho_field_" + getName(); if (! source.equals("this") && ! source.equals("super")) var = source + "." + var; if (! (isAbstract() && getRelatedType().getPersistenceUnit().isJPA())) { // jpa/1004, ejb/06bi out.println("if (" + var + " != null) {"); } else if (isCascade(CascadeType.PERSIST)) { // jpa/0h09 out.println("if (" + var + " != null) {"); } else { // jpa/0j58: avoids breaking FK constraints. // The "one" end in the many-to-one relationship. String amberVar = getFieldName(); out.println("com.caucho.amber.entity.EntityState " + amberVar + "_state = (" + var + " == null) ? "); out.println("com.caucho.amber.entity.EntityState.TRANSIENT : "); out.println("((com.caucho.amber.entity.Entity) " + amberVar + ")."); out.println("__caucho_getEntityState();"); out.println("if (" + amberVar + "_state.isTransactional()) {"); } out.pushDepth(); Id id = getEntityTargetType().getId(); ArrayList<IdField> keys = id.getKeys(); if (keys.size() == 1) { IdField key = keys.get(0); key.getType().generateSet(out, pstmt, index, key.getType().generateCastFromObject(var)); } else { for (int i = 0; i < keys.size(); i++) { IdField key = keys.get(i); key.getType().generateSet(out, pstmt, index, key.generateGetKeyProperty(var)); } } out.popDepth(); out.println("} else {"); out.pushDepth(); for (int i = 0; i < keys.size(); i++) { IdField key = keys.get(i); key.getType().generateSetNull(out, pstmt, index); } out.popDepth(); out.println("}"); } /** * Generates loading cache */ public void generateUpdateFromObject(JavaWriter out, String obj) throws IOException { String var = "__caucho_field_" + getName(); out.println(var + " = " + obj + "." + var + ";"); } /** * Generates code for foreign entity create/delete */ public void generateInvalidateForeign(JavaWriter out) throws IOException { out.println("if (\"" + _targetType.getTable().getName() + "\".equals(table)) {"); out.pushDepth(); String loadVar = "__caucho_loadMask_" + (_targetLoadIndex / 64); out.println(loadVar + " = 0L;"); out.popDepth(); out.println("}"); } /** * Generates any pre-delete code */ public void generatePreDelete(JavaWriter out) throws IOException { if (! isTargetCascadeDelete()) return; String var = "caucho_field_" + getName(); out.println(getJavaTypeName() + " " + var + " = " + getGetterName() + "();"); } /** * Generates any pre-delete code */ public void generatePostDelete(JavaWriter out) throws IOException { if (! isTargetCascadeDelete()) return; String var = "caucho_field_" + getName(); out.println("if (" + var + " != null) {"); out.println(" try {"); // out.println(" __caucho_session.delete(" + var + ");"); out.println(" " + var + ".remove();"); out.println(" } catch (Exception e) {"); out.println(" throw com.caucho.amber.AmberRuntimeException.create(e);"); out.println(" }"); out.println("}"); } }
false
true
public void generateCopyLoadObject(JavaWriter out, String dst, String src, int updateIndex) throws IOException { // order matters: jpa/0h08, jpa/0h09 String value = generateGet(src); out.println(generateSet(dst, value) + ";"); // jpa/0o05 // if (getLoadGroupIndex() == updateIndex) { // order matters: ejb/06gc String var = "__caucho_field_" + getName(); out.println(generateAccessor(dst, var) + " = " + generateAccessor(src, var) + ";"); // jpa/0o05 if (! dst.equals("super")) { // || isLazy())) { out.println("((" + getRelatedType().getInstanceClassName() + ") " + dst + ")." + generateSuperSetter(generateSuperGetter()) + ";"); } // jpa/0o05 // } // commented out: jpa/0s29 // if (_targetLoadIndex == updateIndex) { // ejb/0h20 // } /* if (_targetLoadIndex == updateIndex) { // ejb/0a06 String value = generateGet(src); out.println(generateSet(dst, value) + ";"); } */ } private String generateAccessor(String src, String var) { if (src.equals("super")) return var; else return "((" + getRelatedType().getInstanceClassName() + ") " + src + ")." + var; } /** * Generates the set property. */ public void generateSetProperty(JavaWriter out) throws IOException { // ejb/06gc - updates with EJB 2.0 Id id = getEntityTargetType().getId(); String var = "__caucho_field_" + getName(); String keyType = getEntityTargetType().getId().getForeignTypeName(); out.println(); out.println("public void " + getSetterName() + "(" + getJavaTypeName() + " v)"); out.println("{"); out.pushDepth(); int group = getLoadGroupIndex() / 64; long loadMask = (1L << (getLoadGroupIndex() % 64)); String loadVar = "__caucho_loadMask_" + group; if (_aliasField == null) { out.println("if ((" + loadVar + " & " + loadMask + "L) == 0 && __caucho_session != null) {"); // ejb/0602 out.println(" __caucho_load_" + group + "(__caucho_session);"); out.println(); // jpa/0j5f out.println(" if (__caucho_session.isInTransaction())"); out.println(" __caucho_session.makeTransactional((com.caucho.amber.entity.Entity) this);"); out.println("}"); out.println(); out.println("if (v == null) {"); out.println(" if (" + var + " == null) {"); out.println(" " + generateSuperSetter("null") + ";"); out.println(" return;"); out.println(" }"); out.println(); out.println(" " + var + " = null;"); out.println("} else {"); out.pushDepth(); out.print(keyType + " key = "); RelatedType targetType = getEntityTargetType(); if (targetType.isEJBProxy(getJavaTypeName())) { // To handle EJB local objects. out.print(id.generateGetProxyKey("v")); } else { String v = "((" + getEntityTargetType().getInstanceClassName()+ ") v)"; out.print(id.toObject(id.generateGetProperty(v))); } out.println(";"); out.println(); out.println("if (key.equals(" + var + ")) {"); out.println(" " + generateSuperSetter("v") + ";"); out.println(" return;"); out.println("}"); out.println(); out.println(var + " = key;"); out.popDepth(); out.println("}"); out.println(); out.println(generateSuperSetter("v") + ";"); out.println(); out.println("if (__caucho_session != null) {"); out.pushDepth(); String dirtyVar = "__caucho_dirtyMask_" + (getIndex() / 64); long dirtyMask = (1L << (getIndex() % 64)); out.println(dirtyVar + " |= " + dirtyMask + "L;"); out.println(loadVar + " |= " + loadMask + "L;"); out.println("__caucho_session.update((com.caucho.amber.entity.Entity) this);"); out.println("__caucho_session.addCompletion(__caucho_home.createManyToOneCompletion(\"" + getName() + "\", (com.caucho.amber.entity.Entity) this, v));"); out.println(); out.popDepth(); out.println("}"); } else { out.println("throw new IllegalStateException(\"aliased field cannot be set\");"); } out.popDepth(); out.println("}"); } /** * Generates the flush check for this child. */ public boolean generateFlushCheck(JavaWriter out) throws IOException { // ejb/06bi if (! getRelatedType().getPersistenceUnit().isJPA()) return false; String getter = generateSuperGetter(); out.println("if (" + getter + " != null) {"); out.pushDepth(); String relatedEntity = "((com.caucho.amber.entity.Entity) " + getter + ")"; out.println("com.caucho.amber.entity.EntityState state = " + relatedEntity + ".__caucho_getEntityState();"); // jpa/0j5e as a negative test. out.println("if (" + relatedEntity + ".__caucho_getConnection() == null) {"); out.pushDepth(); // jpa/0j5c as a positive test. out.println("if (! __caucho_state.isManaged())"); String errorString = ("(\"amber flush: unable to flush " + getRelatedType().getName() + "[\" + __caucho_getPrimaryKey() + \"] "+ "with non-managed dependent relationship many-to-one to "+ getEntityTargetType().getName() + "\")"); out.println(" throw new IllegalStateException" + errorString + ";"); out.popDepth(); out.println("}"); out.popDepth(); out.println("}"); return true; } /** * Generates the set clause. */ public void generateSet(JavaWriter out, String pstmt, String index, String source) throws IOException { if (_aliasField != null) return; if (source == null) { throw new NullPointerException(); } String var = "__caucho_field_" + getName(); if (! source.equals("this") && ! source.equals("super")) var = source + "." + var; if (! (isAbstract() && getRelatedType().getPersistenceUnit().isJPA())) { // jpa/1004, ejb/06bi out.println("if (" + var + " != null) {"); } else if (isCascade(CascadeType.PERSIST)) { // jpa/0h09 out.println("if (" + var + " != null) {"); } else { // jpa/0j58: avoids breaking FK constraints. // The "one" end in the many-to-one relationship. String amberVar = getFieldName(); out.println("com.caucho.amber.entity.EntityState " + amberVar + "_state = (" + var + " == null) ? "); out.println("com.caucho.amber.entity.EntityState.TRANSIENT : "); out.println("((com.caucho.amber.entity.Entity) " + amberVar + ")."); out.println("__caucho_getEntityState();"); out.println("if (" + amberVar + "_state.isTransactional()) {"); } out.pushDepth(); Id id = getEntityTargetType().getId(); ArrayList<IdField> keys = id.getKeys(); if (keys.size() == 1) { IdField key = keys.get(0); key.getType().generateSet(out, pstmt, index, key.getType().generateCastFromObject(var)); } else { for (int i = 0; i < keys.size(); i++) { IdField key = keys.get(i); key.getType().generateSet(out, pstmt, index, key.generateGetKeyProperty(var)); } } out.popDepth(); out.println("} else {"); out.pushDepth(); for (int i = 0; i < keys.size(); i++) { IdField key = keys.get(i); key.getType().generateSetNull(out, pstmt, index); } out.popDepth(); out.println("}"); } /** * Generates loading cache */ public void generateUpdateFromObject(JavaWriter out, String obj) throws IOException { String var = "__caucho_field_" + getName(); out.println(var + " = " + obj + "." + var + ";"); } /** * Generates code for foreign entity create/delete */ public void generateInvalidateForeign(JavaWriter out) throws IOException { out.println("if (\"" + _targetType.getTable().getName() + "\".equals(table)) {"); out.pushDepth(); String loadVar = "__caucho_loadMask_" + (_targetLoadIndex / 64); out.println(loadVar + " = 0L;"); out.popDepth(); out.println("}"); } /** * Generates any pre-delete code */ public void generatePreDelete(JavaWriter out) throws IOException { if (! isTargetCascadeDelete()) return; String var = "caucho_field_" + getName(); out.println(getJavaTypeName() + " " + var + " = " + getGetterName() + "();"); } /** * Generates any pre-delete code */ public void generatePostDelete(JavaWriter out) throws IOException { if (! isTargetCascadeDelete()) return; String var = "caucho_field_" + getName(); out.println("if (" + var + " != null) {"); out.println(" try {"); // out.println(" __caucho_session.delete(" + var + ");"); out.println(" " + var + ".remove();"); out.println(" } catch (Exception e) {"); out.println(" throw com.caucho.amber.AmberRuntimeException.create(e);"); out.println(" }"); out.println("}"); } }
public void generateCopyLoadObject(JavaWriter out, String dst, String src, int updateIndex) throws IOException { // order matters: jpa/0h08, jpa/0h09 String value = generateGet(src); out.println(generateSet(dst, value) + ";"); // jpa/0o05 // if (getLoadGroupIndex() == updateIndex) { // order matters: ejb/06gc String var = "__caucho_field_" + getName(); out.println(generateAccessor(dst, var) + " = " + generateAccessor(src, var) + ";"); // jpa/0o05 if (! dst.equals("super")) { // || isLazy())) { out.println("((" + getRelatedType().getInstanceClassName() + ") " + dst + ")." + generateSuperSetter(generateSuperGetter()) + ";"); } // jpa/0o05 // } // commented out: jpa/0s29 // if (_targetLoadIndex == updateIndex) { // ejb/0h20 // } /* if (_targetLoadIndex == updateIndex) { // ejb/0a06 String value = generateGet(src); out.println(generateSet(dst, value) + ";"); } */ } private String generateAccessor(String src, String var) { if (src.equals("super")) return var; else return "((" + getRelatedType().getInstanceClassName() + ") " + src + ")." + var; } /** * Generates the set property. */ public void generateSetProperty(JavaWriter out) throws IOException { // ejb/06gc - updates with EJB 2.0 Id id = getEntityTargetType().getId(); String var = "__caucho_field_" + getName(); String keyType = getEntityTargetType().getId().getForeignTypeName(); out.println(); out.println("public void " + getSetterName() + "(" + getJavaTypeName() + " v)"); out.println("{"); out.pushDepth(); int group = getLoadGroupIndex() / 64; long loadMask = (1L << (getLoadGroupIndex() % 64)); String loadVar = "__caucho_loadMask_" + group; if (_aliasField == null) { out.println("if ((" + loadVar + " & " + loadMask + "L) == 0 && __caucho_session != null) {"); // ejb/0602 out.println(" __caucho_load_" + group + "(__caucho_session);"); out.println(); // jpa/0j5f out.println(" if (__caucho_session.isInTransaction())"); out.println(" __caucho_session.makeTransactional((com.caucho.amber.entity.Entity) this);"); out.println("}"); out.println(); out.println("if (v == null) {"); out.println(" if (" + var + " == null) {"); out.println(" " + generateSuperSetter("null") + ";"); out.println(" return;"); out.println(" }"); out.println(); out.println(" " + var + " = null;"); out.println("} else {"); out.pushDepth(); out.print(keyType + " key = "); RelatedType targetType = getEntityTargetType(); if (targetType.isEJBProxy(getJavaTypeName())) { // To handle EJB local objects. out.print(id.generateGetProxyKey("v")); } else { String v = "((" + getEntityTargetType().getInstanceClassName()+ ") v)"; out.print(id.toObject(id.generateGetProperty(v))); } out.println(";"); out.println(); out.println("if (key.equals(" + var + ")) {"); out.println(" " + generateSuperSetter("v") + ";"); out.println(" return;"); out.println("}"); out.println(); out.println(var + " = key;"); out.popDepth(); out.println("}"); out.println(); out.println(generateSuperSetter("v") + ";"); out.println(); out.println("if (__caucho_session != null) {"); out.pushDepth(); String dirtyVar = "__caucho_dirtyMask_" + (getIndex() / 64); long dirtyMask = (1L << (getIndex() % 64)); out.println(dirtyVar + " |= " + dirtyMask + "L;"); out.println(loadVar + " |= " + loadMask + "L;"); out.println("__caucho_session.update((com.caucho.amber.entity.Entity) this);"); out.println("__caucho_session.addCompletion(__caucho_home.createManyToOneCompletion(\"" + getName() + "\", (com.caucho.amber.entity.Entity) this, v));"); out.println(); out.popDepth(); out.println("}"); } else { out.println("throw new IllegalStateException(\"aliased field cannot be set\");"); } out.popDepth(); out.println("}"); } /** * Generates the flush check for this child. */ public boolean generateFlushCheck(JavaWriter out) throws IOException { // ejb/06bi if (! getRelatedType().getPersistenceUnit().isJPA()) return false; String getter = generateSuperGetter(); out.println("if (" + getter + " != null) {"); out.pushDepth(); String relatedEntity = "((com.caucho.amber.entity.Entity) " + getter + ")"; out.println("com.caucho.amber.entity.EntityState otherState = " + relatedEntity + ".__caucho_getEntityState();"); // jpa/0j5e as a negative test. out.println("if (" + relatedEntity + ".__caucho_getConnection() == null) {"); out.pushDepth(); // jpa/0j5c as a positive test. out.println("if (__caucho_state.isManaged() && ! otherState.isManaged())"); String errorString = ("(\"amber flush: unable to flush " + getRelatedType().getName() + "[\" + __caucho_getPrimaryKey() + \"] "+ "with non-managed dependent relationship many-to-one to "+ getEntityTargetType().getName() + "\")"); out.println(" throw new IllegalStateException" + errorString + ";"); out.popDepth(); out.println("}"); out.popDepth(); out.println("}"); return true; } /** * Generates the set clause. */ public void generateSet(JavaWriter out, String pstmt, String index, String source) throws IOException { if (_aliasField != null) return; if (source == null) { throw new NullPointerException(); } String var = "__caucho_field_" + getName(); if (! source.equals("this") && ! source.equals("super")) var = source + "." + var; if (! (isAbstract() && getRelatedType().getPersistenceUnit().isJPA())) { // jpa/1004, ejb/06bi out.println("if (" + var + " != null) {"); } else if (isCascade(CascadeType.PERSIST)) { // jpa/0h09 out.println("if (" + var + " != null) {"); } else { // jpa/0j58: avoids breaking FK constraints. // The "one" end in the many-to-one relationship. String amberVar = getFieldName(); out.println("com.caucho.amber.entity.EntityState " + amberVar + "_state = (" + var + " == null) ? "); out.println("com.caucho.amber.entity.EntityState.TRANSIENT : "); out.println("((com.caucho.amber.entity.Entity) " + amberVar + ")."); out.println("__caucho_getEntityState();"); out.println("if (" + amberVar + "_state.isTransactional()) {"); } out.pushDepth(); Id id = getEntityTargetType().getId(); ArrayList<IdField> keys = id.getKeys(); if (keys.size() == 1) { IdField key = keys.get(0); key.getType().generateSet(out, pstmt, index, key.getType().generateCastFromObject(var)); } else { for (int i = 0; i < keys.size(); i++) { IdField key = keys.get(i); key.getType().generateSet(out, pstmt, index, key.generateGetKeyProperty(var)); } } out.popDepth(); out.println("} else {"); out.pushDepth(); for (int i = 0; i < keys.size(); i++) { IdField key = keys.get(i); key.getType().generateSetNull(out, pstmt, index); } out.popDepth(); out.println("}"); } /** * Generates loading cache */ public void generateUpdateFromObject(JavaWriter out, String obj) throws IOException { String var = "__caucho_field_" + getName(); out.println(var + " = " + obj + "." + var + ";"); } /** * Generates code for foreign entity create/delete */ public void generateInvalidateForeign(JavaWriter out) throws IOException { out.println("if (\"" + _targetType.getTable().getName() + "\".equals(table)) {"); out.pushDepth(); String loadVar = "__caucho_loadMask_" + (_targetLoadIndex / 64); out.println(loadVar + " = 0L;"); out.popDepth(); out.println("}"); } /** * Generates any pre-delete code */ public void generatePreDelete(JavaWriter out) throws IOException { if (! isTargetCascadeDelete()) return; String var = "caucho_field_" + getName(); out.println(getJavaTypeName() + " " + var + " = " + getGetterName() + "();"); } /** * Generates any pre-delete code */ public void generatePostDelete(JavaWriter out) throws IOException { if (! isTargetCascadeDelete()) return; String var = "caucho_field_" + getName(); out.println("if (" + var + " != null) {"); out.println(" try {"); // out.println(" __caucho_session.delete(" + var + ");"); out.println(" " + var + ".remove();"); out.println(" } catch (Exception e) {"); out.println(" throw com.caucho.amber.AmberRuntimeException.create(e);"); out.println(" }"); out.println("}"); } }
diff --git a/schedulemanager/src/main/java/cours/ulaval/glo4003/controller/model/SectionModel.java b/schedulemanager/src/main/java/cours/ulaval/glo4003/controller/model/SectionModel.java index e354605..12469fa 100644 --- a/schedulemanager/src/main/java/cours/ulaval/glo4003/controller/model/SectionModel.java +++ b/schedulemanager/src/main/java/cours/ulaval/glo4003/controller/model/SectionModel.java @@ -1,260 +1,260 @@ package cours.ulaval.glo4003.controller.model; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang.StringUtils; import cours.ulaval.glo4003.domain.Section; import cours.ulaval.glo4003.domain.TeachMode; import cours.ulaval.glo4003.domain.Time; import cours.ulaval.glo4003.domain.TimeDedicated; import cours.ulaval.glo4003.domain.TimeSlot; import cours.ulaval.glo4003.domain.TimeSlot.DayOfWeek; public class SectionModel { private static final String VENDREDI = "Vendredi"; private static final String JEUDI = "Jeudi"; private static final String MERCREDI = "Mercredi"; private static final String MARDI = "Mardi"; private static final String LUNDI = "Lundi"; private static final Map<String, DayOfWeek> daysAssociations; private static final Map<DayOfWeek, String> inverseDaysAssociations; static { Map<String, DayOfWeek> days = new HashMap<String, DayOfWeek>(); days.put(LUNDI, DayOfWeek.MONDAY); days.put(MARDI, DayOfWeek.TUESDAY); days.put(MERCREDI, DayOfWeek.WEDNESDAY); days.put(JEUDI, DayOfWeek.THURSDAY); days.put(VENDREDI, DayOfWeek.FRIDAY); daysAssociations = Collections.unmodifiableMap(days); Map<DayOfWeek, String> inverseDays = new HashMap<DayOfWeek, String>(); inverseDays.put(DayOfWeek.MONDAY, LUNDI); inverseDays.put(DayOfWeek.TUESDAY, MARDI); inverseDays.put(DayOfWeek.WEDNESDAY, MERCREDI); inverseDays.put(DayOfWeek.THURSDAY, JEUDI); inverseDays.put(DayOfWeek.FRIDAY, VENDREDI); inverseDaysAssociations = Collections.unmodifiableMap(inverseDays); } private String acronym; private List<String> days; private String labDay; private String group; private Integer hoursInClass = 0; private Integer hoursAtHome = 0; private Integer hoursInLab = 0; private String laboTimeSlotStart; private String laboTimeSlotEnd; private String nrc; private String personInCharge; private List<String> teachers; private String teachMode; private List<String> timeSlotStarts; private List<String> timeSlotEnds; public SectionModel() { initialize(); this.nrc = NRCGenerator.generate(); } public SectionModel(Section section) { initialize(); this.nrc = section.getNrc(); this.group = section.getGroup(); this.personInCharge = section.getPersonInCharge(); this.teachers = section.getTeachers(); this.teachMode = section.getTeachMode().toString(); this.acronym = section.getCourseAcronym(); TimeDedicated timeDedicated = section.getTimeDedicated(); this.hoursInClass = timeDedicated.getCourseHours(); this.hoursInLab = timeDedicated.getLabHours(); this.hoursAtHome = timeDedicated.getOthersHours(); TimeSlot timeSlot = section.getLabTimeSlot(); this.laboTimeSlotStart = timeSlot.getStartTime().toString(); this.laboTimeSlotEnd = timeSlot.getEndTime().toString(); this.labDay = inverseDaysAssociations.get(timeSlot.getDayOfWeek()); for (TimeSlot slot : section.getCourseTimeSlots()) { this.days.add(inverseDaysAssociations.get(slot.getDayOfWeek())); - this.timeSlotStarts.add(timeSlot.getStartTime().toString()); - this.timeSlotEnds.add(timeSlot.getEndTime().toString()); + this.timeSlotStarts.add(slot.getStartTime().toString()); + this.timeSlotEnds.add(slot.getEndTime().toString()); } } public Section convertToSection() { Section section = new Section(); section.setCourseAcronym(acronym); section.setGroup(group); section.setNrc(nrc.toString()); section.setPersonInCharge(personInCharge); section.setTeachers(teachers); section.setTeachMode(TeachMode.valueOf(teachMode)); section.setLabTimeSlot(new TimeSlot()); TimeDedicated timeDedicated = new TimeDedicated(hoursInClass, hoursInLab, hoursAtHome); section.setTimeDedicated(timeDedicated); if (StringUtils.isNotEmpty(labDay) && StringUtils.isNotEmpty(laboTimeSlotStart) && StringUtils.isNotEmpty(laboTimeSlotEnd)) { TimeSlot labTimeSlot = convertTimeSlot(labDay, laboTimeSlotStart, laboTimeSlotEnd); section.setLabTimeSlot(labTimeSlot); } List<TimeSlot> timeSlots = new ArrayList<TimeSlot>(); for (int i = 0; i < timeSlotStarts.size(); i++) { timeSlots.add(convertTimeSlot(days.get(i), timeSlotStarts.get(i), timeSlotEnds.get(i))); } section.setCourseTimeSlots(timeSlots); return section; } private TimeSlot convertTimeSlot(String day, String start, String end) { TimeSlot timeSlot = new TimeSlot(); String[] hoursMinStart = start.split(":"); Time startTime = new Time(new Integer(hoursMinStart[0]), new Integer(hoursMinStart[1])); String[] hoursMinEnd = end.split(":"); Time endTime = new Time(new Integer(hoursMinEnd[0]), new Integer(hoursMinEnd[1])); timeSlot.setStartTime(startTime); timeSlot.setEndTime(endTime); timeSlot.setDayOfWeek(daysAssociations.get(day)); return timeSlot; } public String getAcronym() { return acronym; } public void setAcronym(String acronym) { this.acronym = acronym; } public List<String> getDays() { return days; } public void setDays(List<String> days) { this.days = days; } public String getGroup() { return group; } public void setGroup(String group) { this.group = group; } public Integer getHoursInClass() { return hoursInClass; } public void setHoursInClass(Integer hoursInClass) { this.hoursInClass = hoursInClass; } public Integer getHoursAtHome() { return hoursAtHome; } public void setHoursAtHome(Integer hoursAtHome) { this.hoursAtHome = hoursAtHome; } public Integer getHoursInLab() { return hoursInLab; } public void setHoursInLab(Integer hoursInLab) { this.hoursInLab = hoursInLab; } public String getLaboTimeSlotStart() { return laboTimeSlotStart; } public void setLaboTimeSlotStart(String laboTimeSlotStart) { this.laboTimeSlotStart = laboTimeSlotStart; } public String getLaboTimeSlotEnd() { return laboTimeSlotEnd; } public void setLaboTimeSlotEnd(String laboTimeSlotEnd) { this.laboTimeSlotEnd = laboTimeSlotEnd; } public String getPersonInCharge() { return personInCharge; } public void setPersonInCharge(String personInCharge) { this.personInCharge = personInCharge; } public List<String> getTeachers() { return teachers; } public void setTeachers(List<String> teachers) { this.teachers = teachers; } public String getTeachMode() { return teachMode; } public void setTeachMode(String teachMode) { this.teachMode = teachMode; } public List<String> getTimeSlotStarts() { return timeSlotStarts; } public void setTimeSlotStarts(List<String> timeSlotStarts) { this.timeSlotStarts = timeSlotStarts; } public List<String> getTimeSlotEnds() { return timeSlotEnds; } public void setTimeSlotEnds(List<String> timeSlotEnds) { this.timeSlotEnds = timeSlotEnds; } public String getLabDay() { return labDay; } public void setLabDay(String labDays) { this.labDay = labDays; } public String getNrc() { return nrc; } public void setNrc(String nrc) { this.nrc = nrc; } private void initialize() { this.days = new ArrayList<String>(); this.timeSlotStarts = new ArrayList<String>(); this.timeSlotEnds = new ArrayList<String>(); } }
true
true
public SectionModel(Section section) { initialize(); this.nrc = section.getNrc(); this.group = section.getGroup(); this.personInCharge = section.getPersonInCharge(); this.teachers = section.getTeachers(); this.teachMode = section.getTeachMode().toString(); this.acronym = section.getCourseAcronym(); TimeDedicated timeDedicated = section.getTimeDedicated(); this.hoursInClass = timeDedicated.getCourseHours(); this.hoursInLab = timeDedicated.getLabHours(); this.hoursAtHome = timeDedicated.getOthersHours(); TimeSlot timeSlot = section.getLabTimeSlot(); this.laboTimeSlotStart = timeSlot.getStartTime().toString(); this.laboTimeSlotEnd = timeSlot.getEndTime().toString(); this.labDay = inverseDaysAssociations.get(timeSlot.getDayOfWeek()); for (TimeSlot slot : section.getCourseTimeSlots()) { this.days.add(inverseDaysAssociations.get(slot.getDayOfWeek())); this.timeSlotStarts.add(timeSlot.getStartTime().toString()); this.timeSlotEnds.add(timeSlot.getEndTime().toString()); } }
public SectionModel(Section section) { initialize(); this.nrc = section.getNrc(); this.group = section.getGroup(); this.personInCharge = section.getPersonInCharge(); this.teachers = section.getTeachers(); this.teachMode = section.getTeachMode().toString(); this.acronym = section.getCourseAcronym(); TimeDedicated timeDedicated = section.getTimeDedicated(); this.hoursInClass = timeDedicated.getCourseHours(); this.hoursInLab = timeDedicated.getLabHours(); this.hoursAtHome = timeDedicated.getOthersHours(); TimeSlot timeSlot = section.getLabTimeSlot(); this.laboTimeSlotStart = timeSlot.getStartTime().toString(); this.laboTimeSlotEnd = timeSlot.getEndTime().toString(); this.labDay = inverseDaysAssociations.get(timeSlot.getDayOfWeek()); for (TimeSlot slot : section.getCourseTimeSlots()) { this.days.add(inverseDaysAssociations.get(slot.getDayOfWeek())); this.timeSlotStarts.add(slot.getStartTime().toString()); this.timeSlotEnds.add(slot.getEndTime().toString()); } }
diff --git a/project/src/no/ntnu/fp/gui/EventView.java b/project/src/no/ntnu/fp/gui/EventView.java index 857d818..45f6cba 100644 --- a/project/src/no/ntnu/fp/gui/EventView.java +++ b/project/src/no/ntnu/fp/gui/EventView.java @@ -1,154 +1,153 @@ package no.ntnu.fp.gui; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.util.Date; import no.ntnu.fp.model.Employee; import javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JTextArea; import javax.swing.JTextField; import no.ntnu.fp.model.Employee; public class EventView extends JFrame{ JList participantList; JComponent eventTitle, fromField, toField, participantsField, roomBox, descriptionBox; JButton saveButton, cancelButton, deletebutton, acceptButton, declineButton; JPanel eventPanel; GridBagConstraints gbc; DefaultListModel listModel; ParticipantRenderer renderer; Employee user; public EventView(){ gbc = new GridBagConstraints(); gbc.insets = new Insets(5, 5, 5, 5); // user = EventController.getEmplyee(); eventPanel = new JPanel(); eventPanel.setLayout(new GridBagLayout()); createPanel(); this.add(eventPanel); this.pack(); } @SuppressWarnings("unused") private void createPanel(){ Employee hans = new Employee("Hans", "heihei", new Date(1998,2,2), Employee.Gender.MALE); Employee geir = new Employee("Geir", "heihei", new Date(1998,2,2), Employee.Gender.MALE); Employee bjarne = new Employee("Bjarne", "heihei", new Date(1998,2,2), Employee.Gender.MALE); Employee arne = new Employee("Arne", "heihei", new Date(1998,2,2), Employee.Gender.MALE); renderer = new ParticipantRenderer(); listModel = new DefaultListModel(); -// participantList = new JList(listModel); - participantList = new JList(); -// participantList.setCellRenderer(renderer); + participantList = new JList(listModel); + participantList.setCellRenderer(renderer); listModel.addElement(bjarne); listModel.addElement(hans); listModel.addElement(geir); listModel.addElement(arne); participantList.setPreferredSize(new Dimension(200, 200)); //skal sjekke om brukeren er eventmanager if(true){ eventTitle = new JTextField("Title", 23); fromField = new JTextField("From", 10); toField = new JTextField("to", 10); roomBox = new JComboBox(); descriptionBox = new JTextArea("Description"); saveButton = new JButton("Save"); cancelButton = new JButton("Cancel"); deletebutton = new JButton("Delete"); participantsField = new JTextField("Participants", 23); roomBox.setPreferredSize(new Dimension(275, 25)); descriptionBox.setPreferredSize(new Dimension(200, 100)); gbc.gridx = 0; gbc.gridy = 7; gbc.gridwidth = 1; gbc.gridheight = 1; eventPanel.add(saveButton, gbc); gbc.gridx = 2; gbc.gridy = 7; gbc.gridwidth = 1; gbc.gridheight = 1; eventPanel.add(cancelButton, gbc); gbc.gridx = 4; gbc.gridy = 7; gbc.gridwidth = 1; gbc.gridheight = 1; eventPanel.add(deletebutton, gbc); } else{ eventTitle = new JLabel(); fromField = new JLabel(); toField = new JLabel(); roomBox = new JLabel(); descriptionBox = new JTextArea(); acceptButton = new JButton("Accept"); declineButton = new JButton("Decline"); participantsField = new JLabel(); eventPanel.add(acceptButton); eventPanel.add(declineButton); descriptionBox.setEnabled(false); } gbc.gridx = 0; gbc.gridy = 0; gbc.gridwidth = 2; eventPanel.add(eventTitle, gbc); gbc.gridx = 0; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; eventPanel.add(fromField, gbc); gbc.gridx = 1; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; eventPanel.add(toField, gbc); gbc.gridx = 0; gbc.gridy = 2; gbc.gridwidth = 2; gbc.gridheight = 1; eventPanel.add(roomBox, gbc); gbc.gridx = 0; gbc.gridy = 3; gbc.gridwidth = 2; eventPanel.add(participantsField, gbc); gbc.gridx = 0; gbc.gridy = 4; gbc.gridheight = 2; gbc.gridwidth = 2; eventPanel.add(descriptionBox, gbc); gbc.gridx = 3; gbc.gridy = 0; gbc.gridwidth = 3; gbc.gridheight = 6; eventPanel.add(participantList, gbc); } public static void main(String[] args){ JFrame frame = new EventView(); frame.setVisible(true); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(EXIT_ON_CLOSE); } }
true
true
private void createPanel(){ Employee hans = new Employee("Hans", "heihei", new Date(1998,2,2), Employee.Gender.MALE); Employee geir = new Employee("Geir", "heihei", new Date(1998,2,2), Employee.Gender.MALE); Employee bjarne = new Employee("Bjarne", "heihei", new Date(1998,2,2), Employee.Gender.MALE); Employee arne = new Employee("Arne", "heihei", new Date(1998,2,2), Employee.Gender.MALE); renderer = new ParticipantRenderer(); listModel = new DefaultListModel(); // participantList = new JList(listModel); participantList = new JList(); // participantList.setCellRenderer(renderer); listModel.addElement(bjarne); listModel.addElement(hans); listModel.addElement(geir); listModel.addElement(arne); participantList.setPreferredSize(new Dimension(200, 200)); //skal sjekke om brukeren er eventmanager if(true){ eventTitle = new JTextField("Title", 23); fromField = new JTextField("From", 10); toField = new JTextField("to", 10); roomBox = new JComboBox(); descriptionBox = new JTextArea("Description"); saveButton = new JButton("Save"); cancelButton = new JButton("Cancel"); deletebutton = new JButton("Delete"); participantsField = new JTextField("Participants", 23); roomBox.setPreferredSize(new Dimension(275, 25)); descriptionBox.setPreferredSize(new Dimension(200, 100)); gbc.gridx = 0; gbc.gridy = 7; gbc.gridwidth = 1; gbc.gridheight = 1; eventPanel.add(saveButton, gbc); gbc.gridx = 2; gbc.gridy = 7; gbc.gridwidth = 1; gbc.gridheight = 1; eventPanel.add(cancelButton, gbc); gbc.gridx = 4; gbc.gridy = 7; gbc.gridwidth = 1; gbc.gridheight = 1; eventPanel.add(deletebutton, gbc); } else{ eventTitle = new JLabel(); fromField = new JLabel(); toField = new JLabel(); roomBox = new JLabel(); descriptionBox = new JTextArea(); acceptButton = new JButton("Accept"); declineButton = new JButton("Decline"); participantsField = new JLabel(); eventPanel.add(acceptButton); eventPanel.add(declineButton); descriptionBox.setEnabled(false); } gbc.gridx = 0; gbc.gridy = 0; gbc.gridwidth = 2; eventPanel.add(eventTitle, gbc); gbc.gridx = 0; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; eventPanel.add(fromField, gbc); gbc.gridx = 1; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; eventPanel.add(toField, gbc); gbc.gridx = 0; gbc.gridy = 2; gbc.gridwidth = 2; gbc.gridheight = 1; eventPanel.add(roomBox, gbc); gbc.gridx = 0; gbc.gridy = 3; gbc.gridwidth = 2; eventPanel.add(participantsField, gbc); gbc.gridx = 0; gbc.gridy = 4; gbc.gridheight = 2; gbc.gridwidth = 2; eventPanel.add(descriptionBox, gbc); gbc.gridx = 3; gbc.gridy = 0; gbc.gridwidth = 3; gbc.gridheight = 6; eventPanel.add(participantList, gbc); }
private void createPanel(){ Employee hans = new Employee("Hans", "heihei", new Date(1998,2,2), Employee.Gender.MALE); Employee geir = new Employee("Geir", "heihei", new Date(1998,2,2), Employee.Gender.MALE); Employee bjarne = new Employee("Bjarne", "heihei", new Date(1998,2,2), Employee.Gender.MALE); Employee arne = new Employee("Arne", "heihei", new Date(1998,2,2), Employee.Gender.MALE); renderer = new ParticipantRenderer(); listModel = new DefaultListModel(); participantList = new JList(listModel); participantList.setCellRenderer(renderer); listModel.addElement(bjarne); listModel.addElement(hans); listModel.addElement(geir); listModel.addElement(arne); participantList.setPreferredSize(new Dimension(200, 200)); //skal sjekke om brukeren er eventmanager if(true){ eventTitle = new JTextField("Title", 23); fromField = new JTextField("From", 10); toField = new JTextField("to", 10); roomBox = new JComboBox(); descriptionBox = new JTextArea("Description"); saveButton = new JButton("Save"); cancelButton = new JButton("Cancel"); deletebutton = new JButton("Delete"); participantsField = new JTextField("Participants", 23); roomBox.setPreferredSize(new Dimension(275, 25)); descriptionBox.setPreferredSize(new Dimension(200, 100)); gbc.gridx = 0; gbc.gridy = 7; gbc.gridwidth = 1; gbc.gridheight = 1; eventPanel.add(saveButton, gbc); gbc.gridx = 2; gbc.gridy = 7; gbc.gridwidth = 1; gbc.gridheight = 1; eventPanel.add(cancelButton, gbc); gbc.gridx = 4; gbc.gridy = 7; gbc.gridwidth = 1; gbc.gridheight = 1; eventPanel.add(deletebutton, gbc); } else{ eventTitle = new JLabel(); fromField = new JLabel(); toField = new JLabel(); roomBox = new JLabel(); descriptionBox = new JTextArea(); acceptButton = new JButton("Accept"); declineButton = new JButton("Decline"); participantsField = new JLabel(); eventPanel.add(acceptButton); eventPanel.add(declineButton); descriptionBox.setEnabled(false); } gbc.gridx = 0; gbc.gridy = 0; gbc.gridwidth = 2; eventPanel.add(eventTitle, gbc); gbc.gridx = 0; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; eventPanel.add(fromField, gbc); gbc.gridx = 1; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; eventPanel.add(toField, gbc); gbc.gridx = 0; gbc.gridy = 2; gbc.gridwidth = 2; gbc.gridheight = 1; eventPanel.add(roomBox, gbc); gbc.gridx = 0; gbc.gridy = 3; gbc.gridwidth = 2; eventPanel.add(participantsField, gbc); gbc.gridx = 0; gbc.gridy = 4; gbc.gridheight = 2; gbc.gridwidth = 2; eventPanel.add(descriptionBox, gbc); gbc.gridx = 3; gbc.gridy = 0; gbc.gridwidth = 3; gbc.gridheight = 6; eventPanel.add(participantList, gbc); }
diff --git a/stage/0/gloop/Runner.java b/stage/0/gloop/Runner.java index 87dcb7d..2f565ac 100644 --- a/stage/0/gloop/Runner.java +++ b/stage/0/gloop/Runner.java @@ -1,141 +1,141 @@ // -*- mode: Java; c-basic-offset: 3; tab-width: 8; indent-tabs-mode: nil -*- // Copyright (C) 2008 Andreas Krey, Ulm, Germany <[email protected]> package gloop; public class Runner { private String [] strings; private byte [] code; private int entry; private static final Object nullval = new Object () { public String toString () { return "nullval"; } }; public Runner (String [] str, byte [] a, int e) { strings = str; code = a; entry = e; } private static class Frame { public Frame stat; public Frame dyn; public int base; // Number of saved stack cells public Object [] data; public int pc; } private static class Fun { public Frame ctx; public int start; public int nargs; } public void run () { Object [] stack = new Object [100]; /// XXX Need some measure... int sp = 0; int pc = entry; Object acc = null; Frame tmp = null; int param = 0; Frame fp = new Frame (); fp.base = 0; fp.data = new Object [100]; fp.pc = -1; while (true) { int c = code [pc ++] & 255; if (c >= 240) { - param = (param << 16) | (c & 15); + param = (param << 4) | (c & 15); continue; } String op = Code.getCode (c); for (int i = 0; i < sp; i ++) { System.out.print (" " + stack [i]); } System.out.println (" * " + acc); if (param != 0) { System.out.println (" [" + (pc - 1) + "] op=" + op + " (" + param + ")"); } else { System.out.println (" [" + (pc - 1) + "] op=" + op); } if (op == "nop") { } else if (op == "up") { for (tmp = fp; param > 0; param --) { tmp = tmp.stat; } } else if (op == "lstore") { fp.data [param + fp.base] = acc; param = 0; } else if (op == "store") { tmp.data [param + tmp.base] = acc; param = 0; } else if (op == "lload") { acc = fp.data [param + fp.base]; param = 0; } else if (op == "load") { acc = tmp.data [param + tmp.base]; param = 0; } else if (op == "print") { System.out.println ("PRINT: " + acc); } else if (op == "strval") { acc = strings [param]; param = 0; } else if (op == "numval") { acc = new Integer (param); param = 0; } else if (op == "nullval") { acc = nullval; } else if (op == "fun") { Fun f = new Fun (); f.ctx = fp; f.start = ((Integer)acc).intValue (); f.nargs = param; param = 0; acc = f; } else if (op == "push") { stack [sp ++ ] = acc; } else if (op == "swap") { Object h = acc; acc = stack [sp - 1]; stack [sp - 1] = h; } else if (op == "mult") { acc = new Integer (((Integer)acc).intValue () * ((Integer)stack [-- sp]).intValue ()); } else if (op == "call") { Fun a = (Fun)acc; Frame f = new Frame (); if (a.nargs != param) { throw new IllegalArgumentException ("mismatching arg count"); } f.data = new Object [100]; f.pc = pc; f.base = sp - param; // We take the params from the stack! f.dyn = fp; f.stat = a.ctx; for (int i = 0; i < sp; i ++) { System.out.println ("COPY " + stack [i]); f.data [i] = stack [i]; } pc = a.start; sp = 0; param = 0; fp = f; } else if (op == "ret") { pc = fp.pc; sp = 0; for (int i = 0; i < fp.base; i ++) { stack [sp ++] = fp.data [i]; } fp = fp.dyn; } else if (op == "stop") { break; } else { throw new IllegalArgumentException ("unknown op " + op + " (" + c + ")"); } } } }
true
true
public void run () { Object [] stack = new Object [100]; /// XXX Need some measure... int sp = 0; int pc = entry; Object acc = null; Frame tmp = null; int param = 0; Frame fp = new Frame (); fp.base = 0; fp.data = new Object [100]; fp.pc = -1; while (true) { int c = code [pc ++] & 255; if (c >= 240) { param = (param << 16) | (c & 15); continue; } String op = Code.getCode (c); for (int i = 0; i < sp; i ++) { System.out.print (" " + stack [i]); } System.out.println (" * " + acc); if (param != 0) { System.out.println (" [" + (pc - 1) + "] op=" + op + " (" + param + ")"); } else { System.out.println (" [" + (pc - 1) + "] op=" + op); } if (op == "nop") { } else if (op == "up") { for (tmp = fp; param > 0; param --) { tmp = tmp.stat; } } else if (op == "lstore") { fp.data [param + fp.base] = acc; param = 0; } else if (op == "store") { tmp.data [param + tmp.base] = acc; param = 0; } else if (op == "lload") { acc = fp.data [param + fp.base]; param = 0; } else if (op == "load") { acc = tmp.data [param + tmp.base]; param = 0; } else if (op == "print") { System.out.println ("PRINT: " + acc); } else if (op == "strval") { acc = strings [param]; param = 0; } else if (op == "numval") { acc = new Integer (param); param = 0; } else if (op == "nullval") { acc = nullval; } else if (op == "fun") { Fun f = new Fun (); f.ctx = fp; f.start = ((Integer)acc).intValue (); f.nargs = param; param = 0; acc = f; } else if (op == "push") { stack [sp ++ ] = acc; } else if (op == "swap") { Object h = acc; acc = stack [sp - 1]; stack [sp - 1] = h; } else if (op == "mult") { acc = new Integer (((Integer)acc).intValue () * ((Integer)stack [-- sp]).intValue ()); } else if (op == "call") { Fun a = (Fun)acc; Frame f = new Frame (); if (a.nargs != param) { throw new IllegalArgumentException ("mismatching arg count"); } f.data = new Object [100]; f.pc = pc; f.base = sp - param; // We take the params from the stack! f.dyn = fp; f.stat = a.ctx; for (int i = 0; i < sp; i ++) { System.out.println ("COPY " + stack [i]); f.data [i] = stack [i]; } pc = a.start; sp = 0; param = 0; fp = f; } else if (op == "ret") { pc = fp.pc; sp = 0; for (int i = 0; i < fp.base; i ++) { stack [sp ++] = fp.data [i]; } fp = fp.dyn; } else if (op == "stop") { break; } else { throw new IllegalArgumentException ("unknown op " + op + " (" + c + ")"); } } }
public void run () { Object [] stack = new Object [100]; /// XXX Need some measure... int sp = 0; int pc = entry; Object acc = null; Frame tmp = null; int param = 0; Frame fp = new Frame (); fp.base = 0; fp.data = new Object [100]; fp.pc = -1; while (true) { int c = code [pc ++] & 255; if (c >= 240) { param = (param << 4) | (c & 15); continue; } String op = Code.getCode (c); for (int i = 0; i < sp; i ++) { System.out.print (" " + stack [i]); } System.out.println (" * " + acc); if (param != 0) { System.out.println (" [" + (pc - 1) + "] op=" + op + " (" + param + ")"); } else { System.out.println (" [" + (pc - 1) + "] op=" + op); } if (op == "nop") { } else if (op == "up") { for (tmp = fp; param > 0; param --) { tmp = tmp.stat; } } else if (op == "lstore") { fp.data [param + fp.base] = acc; param = 0; } else if (op == "store") { tmp.data [param + tmp.base] = acc; param = 0; } else if (op == "lload") { acc = fp.data [param + fp.base]; param = 0; } else if (op == "load") { acc = tmp.data [param + tmp.base]; param = 0; } else if (op == "print") { System.out.println ("PRINT: " + acc); } else if (op == "strval") { acc = strings [param]; param = 0; } else if (op == "numval") { acc = new Integer (param); param = 0; } else if (op == "nullval") { acc = nullval; } else if (op == "fun") { Fun f = new Fun (); f.ctx = fp; f.start = ((Integer)acc).intValue (); f.nargs = param; param = 0; acc = f; } else if (op == "push") { stack [sp ++ ] = acc; } else if (op == "swap") { Object h = acc; acc = stack [sp - 1]; stack [sp - 1] = h; } else if (op == "mult") { acc = new Integer (((Integer)acc).intValue () * ((Integer)stack [-- sp]).intValue ()); } else if (op == "call") { Fun a = (Fun)acc; Frame f = new Frame (); if (a.nargs != param) { throw new IllegalArgumentException ("mismatching arg count"); } f.data = new Object [100]; f.pc = pc; f.base = sp - param; // We take the params from the stack! f.dyn = fp; f.stat = a.ctx; for (int i = 0; i < sp; i ++) { System.out.println ("COPY " + stack [i]); f.data [i] = stack [i]; } pc = a.start; sp = 0; param = 0; fp = f; } else if (op == "ret") { pc = fp.pc; sp = 0; for (int i = 0; i < fp.base; i ++) { stack [sp ++] = fp.data [i]; } fp = fp.dyn; } else if (op == "stop") { break; } else { throw new IllegalArgumentException ("unknown op " + op + " (" + c + ")"); } } }
diff --git a/standalone/src/main/java/org/jboss/as/console/client/domain/groups/deployment/DeploymentStep1.java b/standalone/src/main/java/org/jboss/as/console/client/domain/groups/deployment/DeploymentStep1.java index 248b1804..636f60fb 100644 --- a/standalone/src/main/java/org/jboss/as/console/client/domain/groups/deployment/DeploymentStep1.java +++ b/standalone/src/main/java/org/jboss/as/console/client/domain/groups/deployment/DeploymentStep1.java @@ -1,137 +1,137 @@ /* * JBoss, Home of Professional Open Source * Copyright <YEAR> Red Hat Inc. and/or its affiliates and other contributors * as indicated by the @author tags. All rights reserved. * See the copyright.txt in the distribution for a * full listing of individual contributors. * * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU Lesser General Public License, v. 2.1. * This program is distributed in the hope that it will be useful, but WITHOUT A * 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, * v.2.1 along with this distribution; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ package org.jboss.as.console.client.domain.groups.deployment; import com.allen_sauer.gwt.log.client.Log; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.json.client.JSONObject; import com.google.gwt.json.client.JSONParser; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.FileUpload; import com.google.gwt.user.client.ui.FormPanel; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.VerticalPanel; import com.google.gwt.user.client.ui.Widget; import org.jboss.as.console.client.Console; import org.jboss.as.console.client.core.BootstrapContext; import org.jboss.as.console.client.widgets.ContentGroupLabel; import org.jboss.as.console.client.widgets.DefaultButton; import org.jboss.dmr.client.Base64; /** * @author Heiko Braun * @date 4/8/11 */ public class DeploymentStep1 { private NewDeploymentWizard wizard; public DeploymentStep1(NewDeploymentWizard wizard) { this.wizard = wizard; } public Widget asWidget() { VerticalPanel layout = new VerticalPanel(); layout.getElement().setAttribute("style", "width:95%; margin:15px;"); // Create a FormPanel and point it at a service. final FormPanel form = new FormPanel(); String url = Console.MODULES.getBootstrapContext().getProperty(BootstrapContext.DEPLOYMENT_API); form.setAction(url); form.setEncoding(FormPanel.ENCODING_MULTIPART); form.setMethod(FormPanel.METHOD_POST); // Create a panel to hold all of the form widgets. VerticalPanel panel = new VerticalPanel(); panel.getElement().setAttribute("style", "width:100%"); form.setWidget(panel); // Create a FileUpload widget. final FileUpload upload = new FileUpload(); upload.setName("uploadFormElement"); panel.add(upload); // Add a 'submit' button. Label cancel = new Label("Cancel"); cancel.setStyleName("html-link"); cancel.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { wizard.getPresenter().closeDialoge(); } }); Button submit = new DefaultButton("Next &rsaquo;&rsaquo;", new ClickHandler() { @Override public void onClick(ClickEvent event) { form.submit(); } }); HorizontalPanel options = new HorizontalPanel(); options.getElement().setAttribute("style", "margin-top:10px;width:100%"); HTML spacer = new HTML("&nbsp;"); options.add(spacer); options.add(submit); options.add(spacer); options.add(cancel); cancel.getElement().getParentElement().setAttribute("style","vertical-align:middle"); submit.getElement().getParentElement().setAttribute("align", "right"); submit.getElement().getParentElement().setAttribute("width", "100%"); panel.add(options); // Add an event handler to the form. form.addSubmitCompleteHandler(new FormPanel.SubmitCompleteHandler() { @Override public void onSubmitComplete(FormPanel.SubmitCompleteEvent event) { String html = event.getResults(); // Step 1: upload content, retrieve hash value try { // TODO: dirty, but mostly because of the Formpanel limitaions String json = html.substring(html.indexOf(">")+1, html.lastIndexOf("<")); JSONObject response = JSONParser.parseLenient(json).isObject(); JSONObject result = response.get("result").isObject(); String hash= result.get("BYTES_VALUE").isString().stringValue(); // step2: assign name and group wizard.onUploadComplete(upload.getFilename(), hash); } catch (Exception e) { - Log.error("Failed to decode response", e); + Log.error("Failed to decode response: "+html, e); } } }); layout.add(new HTML("<h3>Step 1/2: Deployment Selection</h3>")); layout.add(new HTML("Please chose a file that you want to deploy.")); layout.add(form); return layout; } }
true
true
public Widget asWidget() { VerticalPanel layout = new VerticalPanel(); layout.getElement().setAttribute("style", "width:95%; margin:15px;"); // Create a FormPanel and point it at a service. final FormPanel form = new FormPanel(); String url = Console.MODULES.getBootstrapContext().getProperty(BootstrapContext.DEPLOYMENT_API); form.setAction(url); form.setEncoding(FormPanel.ENCODING_MULTIPART); form.setMethod(FormPanel.METHOD_POST); // Create a panel to hold all of the form widgets. VerticalPanel panel = new VerticalPanel(); panel.getElement().setAttribute("style", "width:100%"); form.setWidget(panel); // Create a FileUpload widget. final FileUpload upload = new FileUpload(); upload.setName("uploadFormElement"); panel.add(upload); // Add a 'submit' button. Label cancel = new Label("Cancel"); cancel.setStyleName("html-link"); cancel.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { wizard.getPresenter().closeDialoge(); } }); Button submit = new DefaultButton("Next &rsaquo;&rsaquo;", new ClickHandler() { @Override public void onClick(ClickEvent event) { form.submit(); } }); HorizontalPanel options = new HorizontalPanel(); options.getElement().setAttribute("style", "margin-top:10px;width:100%"); HTML spacer = new HTML("&nbsp;"); options.add(spacer); options.add(submit); options.add(spacer); options.add(cancel); cancel.getElement().getParentElement().setAttribute("style","vertical-align:middle"); submit.getElement().getParentElement().setAttribute("align", "right"); submit.getElement().getParentElement().setAttribute("width", "100%"); panel.add(options); // Add an event handler to the form. form.addSubmitCompleteHandler(new FormPanel.SubmitCompleteHandler() { @Override public void onSubmitComplete(FormPanel.SubmitCompleteEvent event) { String html = event.getResults(); // Step 1: upload content, retrieve hash value try { // TODO: dirty, but mostly because of the Formpanel limitaions String json = html.substring(html.indexOf(">")+1, html.lastIndexOf("<")); JSONObject response = JSONParser.parseLenient(json).isObject(); JSONObject result = response.get("result").isObject(); String hash= result.get("BYTES_VALUE").isString().stringValue(); // step2: assign name and group wizard.onUploadComplete(upload.getFilename(), hash); } catch (Exception e) { Log.error("Failed to decode response", e); } } }); layout.add(new HTML("<h3>Step 1/2: Deployment Selection</h3>")); layout.add(new HTML("Please chose a file that you want to deploy.")); layout.add(form); return layout; }
public Widget asWidget() { VerticalPanel layout = new VerticalPanel(); layout.getElement().setAttribute("style", "width:95%; margin:15px;"); // Create a FormPanel and point it at a service. final FormPanel form = new FormPanel(); String url = Console.MODULES.getBootstrapContext().getProperty(BootstrapContext.DEPLOYMENT_API); form.setAction(url); form.setEncoding(FormPanel.ENCODING_MULTIPART); form.setMethod(FormPanel.METHOD_POST); // Create a panel to hold all of the form widgets. VerticalPanel panel = new VerticalPanel(); panel.getElement().setAttribute("style", "width:100%"); form.setWidget(panel); // Create a FileUpload widget. final FileUpload upload = new FileUpload(); upload.setName("uploadFormElement"); panel.add(upload); // Add a 'submit' button. Label cancel = new Label("Cancel"); cancel.setStyleName("html-link"); cancel.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { wizard.getPresenter().closeDialoge(); } }); Button submit = new DefaultButton("Next &rsaquo;&rsaquo;", new ClickHandler() { @Override public void onClick(ClickEvent event) { form.submit(); } }); HorizontalPanel options = new HorizontalPanel(); options.getElement().setAttribute("style", "margin-top:10px;width:100%"); HTML spacer = new HTML("&nbsp;"); options.add(spacer); options.add(submit); options.add(spacer); options.add(cancel); cancel.getElement().getParentElement().setAttribute("style","vertical-align:middle"); submit.getElement().getParentElement().setAttribute("align", "right"); submit.getElement().getParentElement().setAttribute("width", "100%"); panel.add(options); // Add an event handler to the form. form.addSubmitCompleteHandler(new FormPanel.SubmitCompleteHandler() { @Override public void onSubmitComplete(FormPanel.SubmitCompleteEvent event) { String html = event.getResults(); // Step 1: upload content, retrieve hash value try { // TODO: dirty, but mostly because of the Formpanel limitaions String json = html.substring(html.indexOf(">")+1, html.lastIndexOf("<")); JSONObject response = JSONParser.parseLenient(json).isObject(); JSONObject result = response.get("result").isObject(); String hash= result.get("BYTES_VALUE").isString().stringValue(); // step2: assign name and group wizard.onUploadComplete(upload.getFilename(), hash); } catch (Exception e) { Log.error("Failed to decode response: "+html, e); } } }); layout.add(new HTML("<h3>Step 1/2: Deployment Selection</h3>")); layout.add(new HTML("Please chose a file that you want to deploy.")); layout.add(form); return layout; }
diff --git a/core-client/src/main/java/org/glassfish/jersey/client/ClientRequest.java b/core-client/src/main/java/org/glassfish/jersey/client/ClientRequest.java index 2ecd5ae44..22eaf6999 100644 --- a/core-client/src/main/java/org/glassfish/jersey/client/ClientRequest.java +++ b/core-client/src/main/java/org/glassfish/jersey/client/ClientRequest.java @@ -1,512 +1,512 @@ /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright (c) 2012-2013 Oracle and/or its affiliates. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common Development * and Distribution License("CDDL") (collectively, the "License"). You * may not use this file except in compliance with the License. You can * obtain a copy of the License at * http://glassfish.java.net/public/CDDL+GPL_1_1.html * or packager/legal/LICENSE.txt. See the License for the specific * language governing permissions and limitations under the License. * * When distributing the software, include this License Header Notice in each * file and include the License file at packager/legal/LICENSE.txt. * * GPL Classpath Exception: * Oracle designates this particular file as subject to the "Classpath" * exception as provided by Oracle in the GPL Version 2 section of the License * file that accompanied this code. * * Modifications: * If applicable, add the following below the License Header, with the fields * enclosed by brackets [] replaced by your own identifying information: * "Portions Copyright [year] [name of copyright owner]" * * Contributor(s): * If you wish your version of this file to be governed by only the CDDL or * only the GPL Version 2, indicate your decision by adding "[Contributor] * elects to include this software in this distribution under the [CDDL or GPL * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * and therefore, elected the GPL Version 2 license, then the option applies * only if the new code is made subject to such option by the copyright * holder. */ package org.glassfish.jersey.client; import java.io.IOException; import java.io.OutputStream; import java.net.URI; import java.util.Collection; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import javax.ws.rs.client.ClientRequestContext; import javax.ws.rs.core.CacheControl; import javax.ws.rs.core.Configuration; import javax.ws.rs.core.Cookie; import javax.ws.rs.core.GenericType; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Variant; import javax.ws.rs.ext.ReaderInterceptor; import javax.ws.rs.ext.WriterInterceptor; import org.glassfish.jersey.client.internal.LocalizationMessages; import org.glassfish.jersey.internal.MapPropertiesDelegate; import org.glassfish.jersey.internal.PropertiesDelegate; import org.glassfish.jersey.message.MessageBodyWorkers; import org.glassfish.jersey.message.internal.OutboundMessageContext; import com.google.common.base.Preconditions; /** * Jersey client request context. * * @author Marek Potociar (marek.potociar at oracle.com) */ public class ClientRequest extends OutboundMessageContext implements ClientRequestContext { // Request-scoped configuration instance private final ClientConfig clientConfig; // Request-scoped properties delegate private final PropertiesDelegate propertiesDelegate; // Absolute request URI private URI requestUri; // Request method private String httpMethod; // Request filter chain execution aborting response private Response abortResponse; // Entity providers private MessageBodyWorkers workers; // Flag indicating whether the request is asynchronous private boolean asynchronous; // true if writeEntity() was already called private boolean entityWritten; // writer interceptors used to write the request private Iterable<WriterInterceptor> writerInterceptors; // reader interceptors used to write the request private Iterable<ReaderInterceptor> readerInterceptors; private static final Logger LOGGER = Logger.getLogger(ClientRequest.class.getName()); /** * Create new Jersey client request context. * * @param requestUri request Uri. * @param clientConfig request configuration. * @param propertiesDelegate properties delegate. */ protected ClientRequest( URI requestUri, ClientConfig clientConfig, PropertiesDelegate propertiesDelegate) { clientConfig.checkClient(); this.requestUri = requestUri; this.clientConfig = clientConfig; this.propertiesDelegate = propertiesDelegate; } /** * Copy constructor. * * @param original original instance. */ public ClientRequest(ClientRequest original) { super(original); this.requestUri = original.requestUri; this.httpMethod = original.httpMethod; this.workers = original.workers; this.clientConfig = original.clientConfig.snapshot(); this.asynchronous = original.isAsynchronous(); this.readerInterceptors = original.readerInterceptors; this.writerInterceptors = original.writerInterceptors; this.propertiesDelegate = new MapPropertiesDelegate(original.propertiesDelegate); } @Override public Object getProperty(String name) { return propertiesDelegate.getProperty(name); } @Override public Collection<String> getPropertyNames() { return propertiesDelegate.getPropertyNames(); } @Override public void setProperty(String name, Object object) { propertiesDelegate.setProperty(name, object); } @Override public void removeProperty(String name) { propertiesDelegate.removeProperty(name); } /** * Get the underlying properties delegate. * * @return underlying properties delegate. */ PropertiesDelegate getPropertiesDelegate() { return propertiesDelegate; } /** * Get the underlying client runtime. * * @return underlying client runtime. */ ClientRuntime getClientRuntime() { return clientConfig.getRuntime(); } @Override public URI getUri() { return requestUri; } @Override public void setUri(URI uri) { this.requestUri = uri; } @Override public String getMethod() { return httpMethod; } @Override public void setMethod(String method) { this.httpMethod = method; } @Override public JerseyClient getClient() { return clientConfig.getClient(); } @Override public void abortWith(Response response) { this.abortResponse = response; } /** * Get the request filter chain aborting response if set, or {@code null} otherwise. * * @return request filter chain aborting response if set, or {@code null} otherwise. */ public Response getAbortResponse() { return abortResponse; } @Override public Configuration getConfiguration() { return clientConfig.getRuntime().getConfig(); } /** * Get internal client configuration state. * * @return internal client configuration state. */ ClientConfig getClientConfig() { return clientConfig; } @Override public Map<String, Cookie> getCookies() { return super.getRequestCookies(); } /** * Get the message body workers associated with the request. * * @return message body workers. */ public MessageBodyWorkers getWorkers() { return workers; } /** * Set the message body workers associated with the request. * * @param workers message body workers. */ public void setWorkers(MessageBodyWorkers workers) { this.workers = workers; } /** * Add new accepted types to the message headers. * * @param types accepted types to be added. */ public void accept(MediaType... types) { getHeaders().addAll(HttpHeaders.ACCEPT, (Object[]) types); } /** * Add new accepted types to the message headers. * * @param types accepted types to be added. */ public void accept(String... types) { getHeaders().addAll(HttpHeaders.ACCEPT, (Object[]) types); } /** * Add new accepted languages to the message headers. * * @param locales accepted languages to be added. */ public void acceptLanguage(Locale... locales) { getHeaders().addAll(HttpHeaders.ACCEPT_LANGUAGE, (Object[]) locales); } /** * Add new accepted languages to the message headers. * * @param locales accepted languages to be added. */ public void acceptLanguage(String... locales) { getHeaders().addAll(HttpHeaders.ACCEPT_LANGUAGE, (Object[]) locales); } /** * Add new cookie to the message headers. * * @param cookie cookie to be added. */ public void cookie(Cookie cookie) { getHeaders().add(HttpHeaders.COOKIE, cookie); } /** * Add new cache control entry to the message headers. * * @param cacheControl cache control entry to be added. */ public void cacheControl(CacheControl cacheControl) { getHeaders().add(HttpHeaders.CACHE_CONTROL, cacheControl); } /** * Set message encoding. * * @param encoding message encoding to be set. */ public void encoding(String encoding) { if (encoding == null) { getHeaders().remove(HttpHeaders.CONTENT_ENCODING); } else { getHeaders().putSingle(HttpHeaders.CONTENT_ENCODING, encoding); } } /** * Set message language. * * @param language message language to be set. */ public void language(String language) { if (language == null) { getHeaders().remove(HttpHeaders.CONTENT_LANGUAGE); } else { getHeaders().putSingle(HttpHeaders.CONTENT_LANGUAGE, language); } } /** * Set message language. * * @param language message language to be set. */ public void language(Locale language) { if (language == null) { getHeaders().remove(HttpHeaders.CONTENT_LANGUAGE); } else { getHeaders().putSingle(HttpHeaders.CONTENT_LANGUAGE, language); } } /** * Set message content type. * * @param type message content type to be set. */ public void type(MediaType type) { setMediaType(type); } /** * Set message content type. * * @param type message content type to be set. */ public void type(String type) { type(type == null ? null : MediaType.valueOf(type)); } /** * Set message content variant (type, language and encoding). * * @param variant message content content variant (type, language and encoding) * to be set. */ public void variant(Variant variant) { if (variant == null) { type((MediaType) null); language((String) null); encoding(null); } else { type(variant.getMediaType()); language(variant.getLanguage()); encoding(variant.getEncoding()); } } /** * Returns true if the request is called asynchronously using {@link javax.ws.rs.client.AsyncInvoker} * * @return True if the request is asynchronous; false otherwise. */ public boolean isAsynchronous() { return asynchronous; } /** * Sets the flag indicating whether the request is called asynchronously using {@link javax.ws.rs.client.AsyncInvoker}. * * @param async True if the request is asynchronous; false otherwise. */ void setAsynchronous(boolean async) { asynchronous = async; } /** * Enable a buffering of serialized entity. The buffering will be configured from runtime configuration * associated with this request. The property determining the size of the buffer * is {@link org.glassfish.jersey.CommonProperties#CONTENT_LENGTH_BUFFER}. * <p/> * The buffering functionality is by default disabled and could be enabled by calling this method. In this case * this method must be called before first bytes are written to the {@link #getEntityStream() entity stream}. * */ public void enableBuffering() { enableBuffering(getConfiguration()); } /** * Write (serialize) the entity set in this request into the {@link #getEntityStream() entity stream}. The method * use {@link javax.ws.rs.ext.WriterInterceptor writer interceptors} and {@link javax.ws.rs.ext.MessageBodyWriter * message body writer}. * <p/> * This method modifies the state of this request and therefore it can be called only once per request life cycle otherwise * IllegalStateException is thrown. * <p/> * Note that {@link #setStreamProvider(org.glassfish.jersey.message.internal.OutboundMessageContext.StreamProvider)} * and optionally {@link #enableBuffering()} must be called before calling this method. * * @throws IOException In the case of IO error. */ public void writeEntity() throws IOException { Preconditions.checkState(!entityWritten, LocalizationMessages.REQUEST_ENTITY_ALREADY_WRITTEN()); entityWritten = true; ensureMediaType(); final GenericType<?> entityType = new GenericType(getEntityType()); OutputStream entityStream = null; try { entityStream = workers.writeTo( getEntity(), entityType.getRawType(), entityType.getType(), getEntityAnnotations(), getMediaType(), getHeaders(), getPropertiesDelegate(), getEntityStream(), writerInterceptors); setEntityStream(entityStream); } finally { if (entityStream != null) { try { entityStream.close(); } catch (IOException ex) { LOGGER.log(Level.FINE, LocalizationMessages.ERROR_CLOSING_OUTPUT_STREAM(), ex); } } try { commitStream(); } catch (IOException e) { - LOGGER.log(Level.SEVERE, LocalizationMessages.ERROR_COMMITTING_OUTPUT_STREAM()); + LOGGER.log(Level.SEVERE, LocalizationMessages.ERROR_COMMITTING_OUTPUT_STREAM(), e); } } } private void ensureMediaType() { if (getMediaType() == null) { // Content-Type is not present choose a default type final GenericType<?> entityType = new GenericType(getEntityType()); final List<MediaType> mediaTypes = workers.getMessageBodyWriterMediaTypes( entityType.getRawType(), entityType.getType(), getEntityAnnotations()); setMediaType(getMediaType(mediaTypes)); } } private MediaType getMediaType(List<MediaType> mediaTypes) { if (mediaTypes.isEmpty()) { return MediaType.APPLICATION_OCTET_STREAM_TYPE; } else { MediaType mediaType = mediaTypes.get(0); if (mediaType.isWildcardType() || mediaType.isWildcardSubtype()) { mediaType = MediaType.APPLICATION_OCTET_STREAM_TYPE; } return mediaType; } } /** * Set writer interceptors for this request. * @param writerInterceptors Writer interceptors in the interceptor execution order. */ void setWriterInterceptors(Iterable<WriterInterceptor> writerInterceptors) { this.writerInterceptors = writerInterceptors; } /** * Get writer interceptors of this request. * @return Writer interceptors in the interceptor execution order. */ public Iterable<WriterInterceptor> getWriterInterceptors() { return writerInterceptors; } /** * Get reader interceptors of this request. * @return Reader interceptors in the interceptor execution order. */ public Iterable<ReaderInterceptor> getReaderInterceptors() { return readerInterceptors; } /** * Set reader interceptors for this request. * @param readerInterceptors Reader interceptors in the interceptor execution order. */ void setReaderInterceptors(Iterable<ReaderInterceptor> readerInterceptors) { this.readerInterceptors = readerInterceptors; } }
true
true
public void writeEntity() throws IOException { Preconditions.checkState(!entityWritten, LocalizationMessages.REQUEST_ENTITY_ALREADY_WRITTEN()); entityWritten = true; ensureMediaType(); final GenericType<?> entityType = new GenericType(getEntityType()); OutputStream entityStream = null; try { entityStream = workers.writeTo( getEntity(), entityType.getRawType(), entityType.getType(), getEntityAnnotations(), getMediaType(), getHeaders(), getPropertiesDelegate(), getEntityStream(), writerInterceptors); setEntityStream(entityStream); } finally { if (entityStream != null) { try { entityStream.close(); } catch (IOException ex) { LOGGER.log(Level.FINE, LocalizationMessages.ERROR_CLOSING_OUTPUT_STREAM(), ex); } } try { commitStream(); } catch (IOException e) { LOGGER.log(Level.SEVERE, LocalizationMessages.ERROR_COMMITTING_OUTPUT_STREAM()); } } }
public void writeEntity() throws IOException { Preconditions.checkState(!entityWritten, LocalizationMessages.REQUEST_ENTITY_ALREADY_WRITTEN()); entityWritten = true; ensureMediaType(); final GenericType<?> entityType = new GenericType(getEntityType()); OutputStream entityStream = null; try { entityStream = workers.writeTo( getEntity(), entityType.getRawType(), entityType.getType(), getEntityAnnotations(), getMediaType(), getHeaders(), getPropertiesDelegate(), getEntityStream(), writerInterceptors); setEntityStream(entityStream); } finally { if (entityStream != null) { try { entityStream.close(); } catch (IOException ex) { LOGGER.log(Level.FINE, LocalizationMessages.ERROR_CLOSING_OUTPUT_STREAM(), ex); } } try { commitStream(); } catch (IOException e) { LOGGER.log(Level.SEVERE, LocalizationMessages.ERROR_COMMITTING_OUTPUT_STREAM(), e); } } }
diff --git a/modules/plugin/geotiff/src/main/java/org/geotools/gce/geotiff/GeoTiffReader.java b/modules/plugin/geotiff/src/main/java/org/geotools/gce/geotiff/GeoTiffReader.java index 57da9adc2..df0796bc7 100644 --- a/modules/plugin/geotiff/src/main/java/org/geotools/gce/geotiff/GeoTiffReader.java +++ b/modules/plugin/geotiff/src/main/java/org/geotools/gce/geotiff/GeoTiffReader.java @@ -1,680 +1,680 @@ /* * GeoTools - The Open Source Java GIS Toolkit * http://geotools.org * * (C) 2005-2008, Open Source Geospatial Foundation (OSGeo) * * 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; * version 2.1 of the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. */ /* * NOTICE OF RELEASE TO THE PUBLIC DOMAIN * * This work was created by employees of the USDA Forest Service's * Fire Science Lab for internal use. It is therefore ineligible for * copyright under title 17, section 105 of the United States Code. You * may treat it as you would treat any public domain work: it may be used, * changed, copied, or redistributed, with or without permission of the * authors, for free or for compensation. You may not claim exclusive * ownership of this code because it is already owned by everyone. Use this * software entirely at your own risk. No warranty of any kind is given. * * A copy of 17-USC-105 should have accompanied this distribution in the file * 17USC105.html. If not, you may access the law via the US Government's * public websites: * - http://www.copyright.gov/title17/92chap1.html#105 * - http://www.gpoaccess.gov/uscode/ (enter "17USC105" in the search box.) */ package org.geotools.gce.geotiff; import it.geosolutions.imageioimpl.plugins.tiff.TIFFImageReaderSpi; import java.awt.Color; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.geom.AffineTransform; import java.awt.image.ColorModel; import java.awt.image.SampleModel; import java.awt.image.renderable.ParameterBlock; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.nio.channels.FileChannel; import java.util.HashMap; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import javax.imageio.ImageIO; import javax.imageio.ImageReadParam; import javax.imageio.ImageReader; import javax.imageio.metadata.IIOMetadata; import javax.imageio.stream.ImageInputStream; import javax.media.jai.JAI; import javax.media.jai.PlanarImage; import javax.media.jai.RenderedOp; import org.geotools.coverage.Category; import org.geotools.coverage.GridSampleDimension; import org.geotools.coverage.TypeMap; import org.geotools.coverage.grid.GridCoverage2D; import org.geotools.coverage.grid.GridEnvelope2D; import org.geotools.coverage.grid.GridGeometry2D; import org.geotools.coverage.grid.io.AbstractGridCoverage2DReader; import org.geotools.coverage.grid.io.AbstractGridFormat; import org.geotools.coverage.grid.io.OverviewPolicy; import org.geotools.coverage.grid.io.imageio.geotiff.GeoTiffIIOMetadataDecoder; import org.geotools.coverage.grid.io.imageio.geotiff.GeoTiffMetadata2CRSAdapter; import org.geotools.data.DataSourceException; import org.geotools.data.DataUtilities; import org.geotools.data.PrjFileReader; import org.geotools.data.WorldFileReader; import org.geotools.factory.Hints; import org.geotools.geometry.GeneralEnvelope; import org.geotools.referencing.CRS; import org.geotools.referencing.operation.matrix.XAffineTransform; import org.geotools.referencing.operation.transform.ProjectiveTransform; import org.geotools.resources.i18n.Vocabulary; import org.geotools.resources.i18n.VocabularyKeys; import org.geotools.resources.image.ImageUtilities; import org.geotools.util.NumberRange; import org.opengis.coverage.ColorInterpretation; import org.opengis.coverage.grid.Format; import org.opengis.coverage.grid.GridCoverage; import org.opengis.coverage.grid.GridCoverageReader; import org.opengis.geometry.Envelope; import org.opengis.parameter.GeneralParameterValue; import org.opengis.parameter.ParameterValue; import org.opengis.referencing.FactoryException; import org.opengis.referencing.ReferenceIdentifier; import org.opengis.referencing.crs.CoordinateReferenceSystem; import org.opengis.referencing.operation.MathTransform; import org.opengis.referencing.operation.TransformException; /** * this class is responsible for exposing the data and the Georeferencing * metadata available to the Geotools library. This reader is heavily based on * the capabilities provided by the ImageIO tools and JAI libraries. * * * @author Bryce Nordgren, USDA Forest Service * @author Simone Giannecchini * @since 2.1 * @source $URL: * http://svn.geotools.org/geotools/branches/coverages_branch/trunk/gt/plugin/geotiff/src/org/geotools/gce/geotiff/GeoTiffReader.java $ */ @SuppressWarnings("deprecation") public final class GeoTiffReader extends AbstractGridCoverage2DReader implements GridCoverageReader { /** Logger for the {@link GeoTiffReader} class. */ private Logger LOGGER = org.geotools.util.logging.Logging.getLogger(GeoTiffReader.class.toString()); /** SPI for creating tiff readers in ImageIO tools */ private final static TIFFImageReaderSpi readerSPI = new TIFFImageReaderSpi(); /** Decoder for the GeoTiff metadata. */ private GeoTiffIIOMetadataDecoder metadata; /** Adapter for the GeoTiff crs. */ private GeoTiffMetadata2CRSAdapter gtcs; private double noData = Double.NaN; /** * Creates a new instance of GeoTiffReader * * @param input * the GeoTiff file * @throws DataSourceException */ public GeoTiffReader(Object input) throws DataSourceException { this(input, new Hints(Hints.FORCE_LONGITUDE_FIRST_AXIS_ORDER, Boolean.TRUE)); } /** * Creates a new instance of GeoTiffReader * * @param input * the GeoTiff file * @param uHints * user-supplied hints TODO currently are unused * @throws DataSourceException */ public GeoTiffReader(Object input, Hints uHints) throws DataSourceException { super(input,uHints); // ///////////////////////////////////////////////////////////////////// // // Forcing longitude first since the geotiff specification seems to // assume that we have first longitude the latitude. // // ///////////////////////////////////////////////////////////////////// if (uHints != null) { // prevent the use from reordering axes this.hints.remove(Hints.FORCE_LONGITUDE_FIRST_AXIS_ORDER); this.hints.add(new Hints(Hints.FORCE_LONGITUDE_FIRST_AXIS_ORDER,Boolean.TRUE)); } // ///////////////////////////////////////////////////////////////////// // // Set the source being careful in case it is an URL pointing to a file // // ///////////////////////////////////////////////////////////////////// try { // setting source if (input instanceof URL) { final URL sourceURL = (URL) input; source = DataUtilities.urlToFile(sourceURL); } closeMe = true; // ///////////////////////////////////////////////////////////////////// // // Get a stream in order to read from it for getting the basic // information for this coverage // // ///////////////////////////////////////////////////////////////////// if ((source instanceof InputStream)|| (source instanceof ImageInputStream)) closeMe = false; if(source instanceof ImageInputStream ) inStream=(ImageInputStream) source; else{ inStreamSPI=ImageUtilities.getImageInputStreamSPI(source); if (inStreamSPI == null) throw new IllegalArgumentException("No input stream for the provided source"); inStream = inStreamSPI.createInputStreamInstance(source, ImageIO.getUseCache(), ImageIO.getCacheDirectory()); } if (inStream == null) throw new IllegalArgumentException("No input stream for the provided source"); // ///////////////////////////////////////////////////////////////////// // // Informations about multiple levels and such // // ///////////////////////////////////////////////////////////////////// getHRInfo(this.hints); // ///////////////////////////////////////////////////////////////////// // // Coverage name // // ///////////////////////////////////////////////////////////////////// coverageName = source instanceof File ? ((File) source).getName(): "geotiff_coverage"; final int dotIndex = coverageName.lastIndexOf('.'); if (dotIndex != -1 && dotIndex != coverageName.length()) coverageName = coverageName.substring(0, dotIndex); } catch (IOException e) { throw new DataSourceException(e); }finally{ // ///////////////////////////////////////////////////////////////////// // // Freeing streams // // ///////////////////////////////////////////////////////////////////// if (closeMe&&inStream!=null)// try{ inStream.close(); }catch (Throwable t) { } } } /** * Collect georeferencing information about this geotiff. * * @param hints * @throws DataSourceException */ private void getHRInfo(Hints hints) throws DataSourceException { ImageReader reader = null; try { // // // // Get a reader for this format // // // reader = readerSPI.createReaderInstance(); // // // // get the METADATA // // // inStream.mark(); reader.setInput(inStream); final IIOMetadata iioMetadata = reader.getImageMetadata(0); metadata = new GeoTiffIIOMetadataDecoder(iioMetadata); - gtcs = (GeoTiffMetadata2CRSAdapter) GeoTiffMetadata2CRSAdapter.get(hints); + gtcs = new GeoTiffMetadata2CRSAdapter(hints); // // // // get the CRS INFO // // // final Object tempCRS = this.hints.get(Hints.DEFAULT_COORDINATE_REFERENCE_SYSTEM); if (tempCRS != null) { this.crs = (CoordinateReferenceSystem) tempCRS; if (LOGGER.isLoggable(Level.FINE)) LOGGER.log(Level.FINE, "Using forced coordinate reference system"); } else { // check metadata first if (metadata.hasGeoKey()&& gtcs != null) crs = gtcs.createCoordinateSystem(metadata); if (crs == null) crs = getCRS(source); } if (crs == null){ if(LOGGER.isLoggable(Level.WARNING)) LOGGER.warning("Coordinate Reference System is not available"); crs = AbstractGridFormat.getDefaultCRS(); } if (metadata.hasNoData()) noData = metadata.getNoData(); // // // // get the dimension of the hr image and build the model as well as // computing the resolution // // numOverviews = reader.getNumImages(true) - 1; int hrWidth = reader.getWidth(0); int hrHeight = reader.getHeight(0); final Rectangle actualDim = new Rectangle(0, 0, hrWidth, hrHeight); originalGridRange = new GridEnvelope2D(actualDim); if (gtcs != null&& metadata!=null&& (metadata.hasModelTrasformation()||(metadata.hasPixelScales()&&metadata.hasTiePoints()))) { this.raster2Model = GeoTiffMetadata2CRSAdapter.getRasterToModel(metadata); } else { this.raster2Model = parseWorldFile(source); } if (this.raster2Model == null) { throw new DataSourceException("Raster to Model Transformation is not available"); } final AffineTransform tempTransform = new AffineTransform( (AffineTransform) raster2Model); tempTransform.translate(-0.5, -0.5); originalEnvelope = CRS.transform(ProjectiveTransform.create(tempTransform), new GeneralEnvelope(actualDim)); originalEnvelope.setCoordinateReferenceSystem(crs); // /// // // setting the higher resolution available for this coverage // // /// highestRes = new double[2]; highestRes[0] = XAffineTransform.getScaleX0(tempTransform); highestRes[1] = XAffineTransform.getScaleY0(tempTransform); // // // // get information for the successive images // // // if (numOverviews >= 1) { overViewResolutions = new double[numOverviews][2]; for (int i = 0; i < numOverviews; i++) { overViewResolutions[i][0] = (highestRes[0] * this.originalGridRange.getSpan(0)) / reader.getWidth(i + 1); overViewResolutions[i][1] = (highestRes[1] * this.originalGridRange.getSpan(1)) / reader.getHeight(i + 1); } } else overViewResolutions = null; } catch (Throwable e) { throw new DataSourceException(e); } finally { if (reader != null) try { reader.dispose(); } catch (Throwable t) { } if (inStream != null) try { inStream.reset(); } catch (Throwable t) { } } } /** * @see org.opengis.coverage.grid.GridCoverageReader#getFormat() */ public Format getFormat() { return new GeoTiffFormat(); } /** * This method reads in the TIFF image, constructs an appropriate CRS, * determines the math transform from raster to the CRS model, and * constructs a GridCoverage. * * @param params * currently ignored, potentially may be used for hints. * * @return grid coverage represented by the image * * @throws IOException * on any IO related troubles */ @SuppressWarnings("unchecked") public GridCoverage2D read(GeneralParameterValue[] params) throws IOException { GeneralEnvelope requestedEnvelope = null; Rectangle dim = null; OverviewPolicy overviewPolicy=null; if (params != null) { // // Checking params // if (params != null) { for (int i = 0; i < params.length; i++) { final ParameterValue param = (ParameterValue) params[i]; final ReferenceIdentifier name = param.getDescriptor().getName(); if (name.equals(AbstractGridFormat.READ_GRIDGEOMETRY2D.getName())) { final GridGeometry2D gg = (GridGeometry2D) param.getValue(); requestedEnvelope = new GeneralEnvelope((Envelope) gg.getEnvelope2D()); dim = gg.getGridRange2D().getBounds(); continue; } if (name.equals(AbstractGridFormat.OVERVIEW_POLICY.getName())) { overviewPolicy=(OverviewPolicy) param.getValue(); continue; } } } } // // set params // Integer imageChoice = new Integer(0); final ImageReadParam readP = new ImageReadParam(); try { imageChoice = setReadParams(overviewPolicy, readP,requestedEnvelope, dim); } catch (TransformException e) { new DataSourceException(e); } // ///////////////////////////////////////////////////////////////////// // // IMAGE READ OPERATION // // ///////////////////////////////////////////////////////////////////// // final ImageReader reader = readerSPI.createReaderInstance(); // final ImageInputStream inStream = ImageIO // .createImageInputStream(source); // reader.setInput(inStream); final Hints newHints = (Hints) hints.clone(); // if (!reader.isImageTiled(imageChoice.intValue())) { // final Dimension tileSize = ImageUtilities.toTileSize(new Dimension( // reader.getWidth(imageChoice.intValue()), reader // .getHeight(imageChoice.intValue()))); // final ImageLayout layout = new ImageLayout(); // layout.setTileGridXOffset(0); // layout.setTileGridYOffset(0); // layout.setTileHeight(tileSize.height); // layout.setTileWidth(tileSize.width); // newHints.add(new RenderingHints(JAI.KEY_IMAGE_LAYOUT, layout)); // } // inStream.close(); // reader.reset(); final ParameterBlock pbjRead = new ParameterBlock(); pbjRead.add(inStreamSPI!=null?inStreamSPI.createInputStreamInstance(source, ImageIO.getUseCache(), ImageIO.getCacheDirectory()):ImageIO.createImageInputStream(source)); pbjRead.add(imageChoice); pbjRead.add(Boolean.FALSE); pbjRead.add(Boolean.FALSE); pbjRead.add(Boolean.FALSE); pbjRead.add(null); pbjRead.add(null); pbjRead.add(readP); pbjRead.add( readerSPI.createReaderInstance()); final RenderedOp coverageRaster=JAI.create("ImageRead", pbjRead, (RenderingHints) newHints); // ///////////////////////////////////////////////////////////////////// // // BUILDING COVERAGE // // ///////////////////////////////////////////////////////////////////// // I need to calculate a new transformation (raster2Model) // between the cropped image and the required // adjustedRequestEnvelope final int ssWidth = coverageRaster.getWidth(); final int ssHeight = coverageRaster.getHeight(); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "Coverage read: width = " + ssWidth+ " height = " + ssHeight); } // // // // setting new coefficients to define a new affineTransformation // to be applied to the grid to world transformation // ----------------------------------------------------------------------------------- // // With respect to the original envelope, the obtained planarImage // needs to be rescaled. The scaling factors are computed as the // ratio between the cropped source region sizes and the read // image sizes. // // // final double scaleX = originalGridRange.getSpan(0) / (1.0 * ssWidth); final double scaleY = originalGridRange.getSpan(1) / (1.0 * ssHeight); final AffineTransform tempRaster2Model = new AffineTransform((AffineTransform) raster2Model); tempRaster2Model.concatenate(new AffineTransform(scaleX, 0, 0, scaleY, 0, 0)); return createCoverage(coverageRaster, ProjectiveTransform.create((AffineTransform) tempRaster2Model)); } /** * Returns the geotiff metadata for this geotiff file. * * @return the metadata */ public GeoTiffIIOMetadataDecoder getMetadata() { return metadata; } /** * Creates a {@link GridCoverage} for the provided {@link PlanarImage} using * the {@link #raster2Model} that was provided for this coverage. * * <p> * This method is vital when working with coverages that have a raster to * model transformation that is not a simple scale and translate. * * @param image * contains the data for the coverage to create. * @param raster2Model * is the {@link MathTransform} that maps from the raster space * to the model space. * @return a {@link GridCoverage} * @throws IOException */ protected final GridCoverage2D createCoverage(PlanarImage image, MathTransform raster2Model) throws IOException { //creating bands final SampleModel sm = image.getSampleModel(); final ColorModel cm = image.getColorModel(); final int numBands = sm.getNumBands(); final GridSampleDimension[] bands = new GridSampleDimension[numBands]; // setting bands names. Category noDataCategory = null; final Map<String, Double> properties = new HashMap<String, Double>(); if (!Double.isNaN(noData)){ noDataCategory = new Category(Vocabulary .formatInternational(VocabularyKeys.NODATA), new Color[] { new Color(0, 0, 0, 0) }, NumberRange .create(noData, noData), NumberRange .create(noData, noData)); properties.put("GC_NODATA", new Double(noData)); } for (int i = 0; i < numBands; i++) { final ColorInterpretation colorInterpretation=TypeMap.getColorInterpretation(cm, i); if(colorInterpretation==null) throw new IOException("Unrecognized sample dimension type"); Category[] categories = null; if (noDataCategory != null) categories = new Category[]{noDataCategory}; bands[i] = new GridSampleDimension(colorInterpretation.name(),categories,null).geophysics(true); } // creating coverage if (raster2Model != null) { return coverageFactory.create(coverageName, image, crs,raster2Model, bands, null, properties); } return coverageFactory.create(coverageName, image, new GeneralEnvelope(originalEnvelope), bands, null, properties); } private CoordinateReferenceSystem getCRS(Object source) { CoordinateReferenceSystem crs = null; if (source instanceof File || (source instanceof URL && (((URL) source).getProtocol() == "file"))) { // getting name for the prj file final String sourceAsString; if (source instanceof File) { sourceAsString = ((File) source).getAbsolutePath(); } else { String auth = ((URL) source).getAuthority(); String path = ((URL) source).getPath(); if (auth != null && !auth.equals("")) { sourceAsString = "//" + auth + path; } else { sourceAsString = path; } } final int index = sourceAsString.lastIndexOf("."); final StringBuilder base = new StringBuilder(sourceAsString .substring(0, index)).append(".prj"); // does it exist? final File prjFile = new File(base.toString()); if (prjFile.exists()) { // it exists then we have top read it PrjFileReader projReader = null; FileInputStream instream=null; try { instream=new FileInputStream(prjFile); final FileChannel channel = instream.getChannel(); projReader = new PrjFileReader(channel); crs = projReader.getCoordinateReferenceSystem(); } catch (FileNotFoundException e) { // warn about the error but proceed, it is not fatal // we have at least the default crs to use LOGGER.log(Level.INFO, e.getLocalizedMessage(), e); } catch (IOException e) { // warn about the error but proceed, it is not fatal // we have at least the default crs to use LOGGER.log(Level.INFO, e.getLocalizedMessage(), e); } catch (FactoryException e) { // warn about the error but proceed, it is not fatal // we have at least the default crs to use LOGGER.log(Level.INFO, e.getLocalizedMessage(), e); } finally { if (projReader != null) try { projReader.close(); } catch (IOException e) { // warn about the error but proceed, it is not fatal // we have at least the default crs to use LOGGER .log(Level.FINE, e.getLocalizedMessage(),e); } if (instream != null) try { instream.close(); } catch (IOException e) { // warn about the error but proceed, it is not fatal // we have at least the default crs to use LOGGER.log(Level.FINE, e.getLocalizedMessage(),e); } } } } return crs; } /** * @throws IOException */ static MathTransform parseWorldFile(Object source) throws IOException { MathTransform raster2Model = null; // TODO: Add support for FileImageInputStreamExt // TODO: Check for WorldFile on URL beside the actual connection. if (source instanceof File) { final File sourceFile = ((File) source); String parentPath = sourceFile.getParent(); String filename = sourceFile.getName(); final int i = filename.lastIndexOf('.'); filename = (i == -1) ? filename : filename.substring(0, i); // getting name and extension final String base = (parentPath != null) ? new StringBuilder( parentPath).append(File.separator).append(filename) .toString() : filename; // We can now construct the baseURL from this string. File file2Parse = new File(new StringBuilder(base).append(".wld") .toString()); if (file2Parse.exists()) { final WorldFileReader reader = new WorldFileReader(file2Parse); raster2Model = reader.getTransform(); } else { // looking for another extension file2Parse = new File(new StringBuilder(base).append(".tfw") .toString()); if (file2Parse.exists()) { // parse world file final WorldFileReader reader = new WorldFileReader( file2Parse); raster2Model = reader.getTransform(); } } } return raster2Model; } /** * Number of coverages for this reader is 1 * * @return the number of coverages for this reader. */ @Override public int getGridCoverageCount() { return 1; } }
true
true
private void getHRInfo(Hints hints) throws DataSourceException { ImageReader reader = null; try { // // // // Get a reader for this format // // // reader = readerSPI.createReaderInstance(); // // // // get the METADATA // // // inStream.mark(); reader.setInput(inStream); final IIOMetadata iioMetadata = reader.getImageMetadata(0); metadata = new GeoTiffIIOMetadataDecoder(iioMetadata); gtcs = (GeoTiffMetadata2CRSAdapter) GeoTiffMetadata2CRSAdapter.get(hints); // // // // get the CRS INFO // // // final Object tempCRS = this.hints.get(Hints.DEFAULT_COORDINATE_REFERENCE_SYSTEM); if (tempCRS != null) { this.crs = (CoordinateReferenceSystem) tempCRS; if (LOGGER.isLoggable(Level.FINE)) LOGGER.log(Level.FINE, "Using forced coordinate reference system"); } else { // check metadata first if (metadata.hasGeoKey()&& gtcs != null) crs = gtcs.createCoordinateSystem(metadata); if (crs == null) crs = getCRS(source); } if (crs == null){ if(LOGGER.isLoggable(Level.WARNING)) LOGGER.warning("Coordinate Reference System is not available"); crs = AbstractGridFormat.getDefaultCRS(); } if (metadata.hasNoData()) noData = metadata.getNoData(); // // // // get the dimension of the hr image and build the model as well as // computing the resolution // // numOverviews = reader.getNumImages(true) - 1; int hrWidth = reader.getWidth(0); int hrHeight = reader.getHeight(0); final Rectangle actualDim = new Rectangle(0, 0, hrWidth, hrHeight); originalGridRange = new GridEnvelope2D(actualDim); if (gtcs != null&& metadata!=null&& (metadata.hasModelTrasformation()||(metadata.hasPixelScales()&&metadata.hasTiePoints()))) { this.raster2Model = GeoTiffMetadata2CRSAdapter.getRasterToModel(metadata); } else { this.raster2Model = parseWorldFile(source); } if (this.raster2Model == null) { throw new DataSourceException("Raster to Model Transformation is not available"); } final AffineTransform tempTransform = new AffineTransform( (AffineTransform) raster2Model); tempTransform.translate(-0.5, -0.5); originalEnvelope = CRS.transform(ProjectiveTransform.create(tempTransform), new GeneralEnvelope(actualDim)); originalEnvelope.setCoordinateReferenceSystem(crs); // /// // // setting the higher resolution available for this coverage // // /// highestRes = new double[2]; highestRes[0] = XAffineTransform.getScaleX0(tempTransform); highestRes[1] = XAffineTransform.getScaleY0(tempTransform); // // // // get information for the successive images // // // if (numOverviews >= 1) { overViewResolutions = new double[numOverviews][2]; for (int i = 0; i < numOverviews; i++) { overViewResolutions[i][0] = (highestRes[0] * this.originalGridRange.getSpan(0)) / reader.getWidth(i + 1); overViewResolutions[i][1] = (highestRes[1] * this.originalGridRange.getSpan(1)) / reader.getHeight(i + 1); } } else overViewResolutions = null; } catch (Throwable e) { throw new DataSourceException(e); } finally { if (reader != null) try { reader.dispose(); } catch (Throwable t) { } if (inStream != null) try { inStream.reset(); } catch (Throwable t) { } } }
private void getHRInfo(Hints hints) throws DataSourceException { ImageReader reader = null; try { // // // // Get a reader for this format // // // reader = readerSPI.createReaderInstance(); // // // // get the METADATA // // // inStream.mark(); reader.setInput(inStream); final IIOMetadata iioMetadata = reader.getImageMetadata(0); metadata = new GeoTiffIIOMetadataDecoder(iioMetadata); gtcs = new GeoTiffMetadata2CRSAdapter(hints); // // // // get the CRS INFO // // // final Object tempCRS = this.hints.get(Hints.DEFAULT_COORDINATE_REFERENCE_SYSTEM); if (tempCRS != null) { this.crs = (CoordinateReferenceSystem) tempCRS; if (LOGGER.isLoggable(Level.FINE)) LOGGER.log(Level.FINE, "Using forced coordinate reference system"); } else { // check metadata first if (metadata.hasGeoKey()&& gtcs != null) crs = gtcs.createCoordinateSystem(metadata); if (crs == null) crs = getCRS(source); } if (crs == null){ if(LOGGER.isLoggable(Level.WARNING)) LOGGER.warning("Coordinate Reference System is not available"); crs = AbstractGridFormat.getDefaultCRS(); } if (metadata.hasNoData()) noData = metadata.getNoData(); // // // // get the dimension of the hr image and build the model as well as // computing the resolution // // numOverviews = reader.getNumImages(true) - 1; int hrWidth = reader.getWidth(0); int hrHeight = reader.getHeight(0); final Rectangle actualDim = new Rectangle(0, 0, hrWidth, hrHeight); originalGridRange = new GridEnvelope2D(actualDim); if (gtcs != null&& metadata!=null&& (metadata.hasModelTrasformation()||(metadata.hasPixelScales()&&metadata.hasTiePoints()))) { this.raster2Model = GeoTiffMetadata2CRSAdapter.getRasterToModel(metadata); } else { this.raster2Model = parseWorldFile(source); } if (this.raster2Model == null) { throw new DataSourceException("Raster to Model Transformation is not available"); } final AffineTransform tempTransform = new AffineTransform( (AffineTransform) raster2Model); tempTransform.translate(-0.5, -0.5); originalEnvelope = CRS.transform(ProjectiveTransform.create(tempTransform), new GeneralEnvelope(actualDim)); originalEnvelope.setCoordinateReferenceSystem(crs); // /// // // setting the higher resolution available for this coverage // // /// highestRes = new double[2]; highestRes[0] = XAffineTransform.getScaleX0(tempTransform); highestRes[1] = XAffineTransform.getScaleY0(tempTransform); // // // // get information for the successive images // // // if (numOverviews >= 1) { overViewResolutions = new double[numOverviews][2]; for (int i = 0; i < numOverviews; i++) { overViewResolutions[i][0] = (highestRes[0] * this.originalGridRange.getSpan(0)) / reader.getWidth(i + 1); overViewResolutions[i][1] = (highestRes[1] * this.originalGridRange.getSpan(1)) / reader.getHeight(i + 1); } } else overViewResolutions = null; } catch (Throwable e) { throw new DataSourceException(e); } finally { if (reader != null) try { reader.dispose(); } catch (Throwable t) { } if (inStream != null) try { inStream.reset(); } catch (Throwable t) { } } }
diff --git a/site-manage-tool/tool/src/java/org/sakaiproject/site/tool/SiteAction.java b/site-manage-tool/tool/src/java/org/sakaiproject/site/tool/SiteAction.java index 8ad60ae6..f0597096 100644 --- a/site-manage-tool/tool/src/java/org/sakaiproject/site/tool/SiteAction.java +++ b/site-manage-tool/tool/src/java/org/sakaiproject/site/tool/SiteAction.java @@ -1,11003 +1,11007 @@ /********************************************************************************** * $URL$ * $Id$ *********************************************************************************** * * Copyright (c) 2003, 2004, 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.site.tool; import java.io.IOException; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.URL; import java.text.Collator; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.Iterator; import java.util.Locale; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Properties; import java.util.concurrent.ConcurrentHashMap; import java.util.Random; import java.util.Set; import java.util.Vector; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.velocity.tools.generic.SortTool; import org.sakaiproject.alias.api.Alias; import org.sakaiproject.alias.cover.AliasService; import org.sakaiproject.archive.api.ImportMetadata; import org.sakaiproject.archive.cover.ArchiveService; import org.sakaiproject.authz.api.AuthzGroup; import org.sakaiproject.authz.api.AuthzPermissionException; import org.sakaiproject.authz.api.GroupNotDefinedException; import org.sakaiproject.authz.api.Member; import org.sakaiproject.authz.api.PermissionsHelper; import org.sakaiproject.authz.api.Role; import org.sakaiproject.authz.api.SecurityAdvisor; import org.sakaiproject.authz.api.SecurityAdvisor.SecurityAdvice; import org.sakaiproject.authz.cover.AuthzGroupService; import org.sakaiproject.authz.cover.SecurityService; import org.sakaiproject.cheftool.Context; import org.sakaiproject.cheftool.JetspeedRunData; import org.sakaiproject.cheftool.PagedResourceActionII; import org.sakaiproject.cheftool.PortletConfig; import org.sakaiproject.cheftool.RunData; import org.sakaiproject.cheftool.VelocityPortlet; import org.sakaiproject.cheftool.api.Menu; import org.sakaiproject.cheftool.api.MenuItem; import org.sakaiproject.cheftool.menu.MenuEntry; import org.sakaiproject.cheftool.menu.MenuImpl; import org.sakaiproject.component.cover.ComponentManager; import org.sakaiproject.component.cover.ServerConfigurationService; import org.sakaiproject.content.api.ContentHostingService; import org.sakaiproject.content.api.ContentCollection; import org.sakaiproject.content.api.ContentResource; import org.sakaiproject.content.api.ContentEntity; import org.sakaiproject.coursemanagement.api.AcademicSession; import org.sakaiproject.coursemanagement.api.CourseOffering; import org.sakaiproject.coursemanagement.api.CourseSet; import org.sakaiproject.coursemanagement.api.Enrollment; import org.sakaiproject.coursemanagement.api.EnrollmentSet; import org.sakaiproject.coursemanagement.api.Membership; import org.sakaiproject.coursemanagement.api.Section; import org.sakaiproject.coursemanagement.api.exception.IdNotFoundException; import org.sakaiproject.email.cover.EmailService; import org.sakaiproject.entity.api.Entity; import org.sakaiproject.entity.api.EntityProducer; import org.sakaiproject.entity.api.EntityPropertyNotDefinedException; import org.sakaiproject.entity.api.EntityPropertyTypeException; import org.sakaiproject.entity.api.EntityTransferrer; import org.sakaiproject.entity.api.Reference; import org.sakaiproject.entity.api.ResourceProperties; import org.sakaiproject.entity.api.ResourcePropertiesEdit; import org.sakaiproject.entity.cover.EntityManager; import org.sakaiproject.event.api.SessionState; import org.sakaiproject.event.cover.EventTrackingService; import org.sakaiproject.exception.IdInvalidException; import org.sakaiproject.exception.IdUnusedException; import org.sakaiproject.exception.IdUsedException; import org.sakaiproject.exception.ImportException; import org.sakaiproject.exception.PermissionException; import org.sakaiproject.exception.TypeException; import org.sakaiproject.exception.ServerOverloadException; import org.sakaiproject.id.cover.IdManager; import org.sakaiproject.importer.api.ImportDataSource; import org.sakaiproject.importer.api.ImportService; import org.sakaiproject.importer.api.SakaiArchive; import org.sakaiproject.javax.PagingPosition; import org.sakaiproject.site.api.Group; import org.sakaiproject.site.api.Site; import org.sakaiproject.site.api.SitePage; import org.sakaiproject.site.api.ToolConfiguration; import org.sakaiproject.site.api.SiteService.SortType; import org.sakaiproject.site.cover.SiteService; import org.sakaiproject.sitemanage.api.model.*; import org.sakaiproject.site.util.SiteSetupQuestionFileParser; import org.sakaiproject.site.util.Participant; import org.sakaiproject.site.util.SiteParticipantHelper; import org.sakaiproject.site.util.SiteConstants; import org.sakaiproject.site.util.SiteComparator; import org.sakaiproject.site.util.ToolComparator; import org.sakaiproject.sitemanage.api.SectionField; import org.sakaiproject.sitemanage.api.SiteHelper; import org.sakaiproject.time.api.Time; import org.sakaiproject.time.api.TimeBreakdown; import org.sakaiproject.time.cover.TimeService; import org.sakaiproject.tool.api.Tool; import org.sakaiproject.tool.api.ToolException; import org.sakaiproject.tool.api.ToolSession; import org.sakaiproject.tool.cover.SessionManager; import org.sakaiproject.tool.cover.ToolManager; import org.sakaiproject.user.api.User; import org.sakaiproject.user.api.UserAlreadyDefinedException; import org.sakaiproject.user.api.UserEdit; import org.sakaiproject.user.api.UserIdInvalidException; import org.sakaiproject.user.api.UserNotDefinedException; import org.sakaiproject.user.api.UserPermissionException; import org.sakaiproject.user.cover.UserDirectoryService; import org.sakaiproject.util.ArrayUtil; import org.sakaiproject.util.FileItem; import org.sakaiproject.util.FormattedText; import org.sakaiproject.util.ParameterParser; import org.sakaiproject.util.ResourceLoader; import org.sakaiproject.util.SortedIterator; import org.sakaiproject.util.StringUtil; import org.sakaiproject.util.Validator; /** * <p> * SiteAction controls the interface for worksite setup. * </p> */ public class SiteAction extends PagedResourceActionII { /** Our log (commons). */ private static Log M_log = LogFactory.getLog(SiteAction.class); private ContentHostingService m_contentHostingService = (ContentHostingService) ComponentManager.get("org.sakaiproject.content.api.ContentHostingService"); private ImportService importService = org.sakaiproject.importer.cover.ImportService .getInstance(); /** portlet configuration parameter values* */ /** Resource bundle using current language locale */ private static ResourceLoader rb = new ResourceLoader("sitesetupgeneric"); private org.sakaiproject.coursemanagement.api.CourseManagementService cms = (org.sakaiproject.coursemanagement.api.CourseManagementService) ComponentManager .get(org.sakaiproject.coursemanagement.api.CourseManagementService.class); private org.sakaiproject.authz.api.GroupProvider groupProvider = (org.sakaiproject.authz.api.GroupProvider) ComponentManager .get(org.sakaiproject.authz.api.GroupProvider.class); private org.sakaiproject.authz.api.AuthzGroupService authzGroupService = (org.sakaiproject.authz.api.AuthzGroupService) ComponentManager .get(org.sakaiproject.authz.api.AuthzGroupService.class); private org.sakaiproject.sitemanage.api.SectionFieldProvider sectionFieldProvider = (org.sakaiproject.sitemanage.api.SectionFieldProvider) ComponentManager .get(org.sakaiproject.sitemanage.api.SectionFieldProvider.class); private org.sakaiproject.sitemanage.api.AffiliatedSectionProvider affiliatedSectionProvider = (org.sakaiproject.sitemanage.api.AffiliatedSectionProvider) ComponentManager .get(org.sakaiproject.sitemanage.api.AffiliatedSectionProvider.class); private ContentHostingService contentHostingService = (ContentHostingService) ComponentManager.get("org.sakaiproject.content.api.ContentHostingService"); private static org.sakaiproject.sitemanage.api.model.SiteSetupQuestionService questionService = (org.sakaiproject.sitemanage.api.model.SiteSetupQuestionService) ComponentManager .get(org.sakaiproject.sitemanage.api.model.SiteSetupQuestionService.class); private static final String SITE_MODE_SITESETUP = "sitesetup"; private static final String SITE_MODE_SITEINFO = "siteinfo"; private static final String SITE_MODE_HELPER = "helper"; private static final String SITE_MODE_HELPER_DONE = "helper.done"; private static final String STATE_SITE_MODE = "site_mode"; protected final static String[] TEMPLATE = { "-list",// 0 "-type", "-newSiteInformation", "-editFeatures", "", "-addParticipant", "", "", "-siteDeleteConfirm", "", "-newSiteConfirm",// 10 "", "-siteInfo-list",// 12 "-siteInfo-editInfo", "-siteInfo-editInfoConfirm", "-addRemoveFeatureConfirm",// 15 "", "", "-siteInfo-editAccess", "", "",// 20 "", "", "", "", "",// 25 "-modifyENW", "-importSites", "-siteInfo-import", "-siteInfo-duplicate", "",// 30 "",// 31 "",// 32 "",// 33 "",// 34 "",// 35 "-newSiteCourse",// 36 "-newSiteCourseManual",// 37 "",// 38 "",// 39 "",// 40 "",// 41 "-gradtoolsConfirm",// 42 "-siteInfo-editClass",// 43 "-siteInfo-addCourseConfirm",// 44 "-siteInfo-importMtrlMaster", // 45 -- htripath for import // material from a file "-siteInfo-importMtrlCopy", // 46 "-siteInfo-importMtrlCopyConfirm", "-siteInfo-importMtrlCopyConfirmMsg", // 48 "",//"-siteInfo-group", // 49 moved to the group helper "",//"-siteInfo-groupedit", // 50 moved to the group helper "",//"-siteInfo-groupDeleteConfirm", // 51, moved to the group helper "", "-findCourse", // 53 "-questions", // 54 "",// 55 "",// 56 "",// 57 "-siteInfo-importSelection", //58 "-siteInfo-importMigrate", //59 "-importSitesMigrate" //60 }; /** Name of state attribute for Site instance id */ private static final String STATE_SITE_INSTANCE_ID = "site.instance.id"; /** Name of state attribute for Site Information */ private static final String STATE_SITE_INFO = "site.info"; /** Name of state attribute for CHEF site type */ private static final String STATE_SITE_TYPE = "site-type"; /** Name of state attribute for possible site types */ private static final String STATE_SITE_TYPES = "site_types"; private static final String STATE_DEFAULT_SITE_TYPE = "default_site_type"; private static final String STATE_PUBLIC_CHANGEABLE_SITE_TYPES = "changeable_site_types"; private static final String STATE_PUBLIC_SITE_TYPES = "public_site_types"; private static final String STATE_PRIVATE_SITE_TYPES = "private_site_types"; private static final String STATE_DISABLE_JOINABLE_SITE_TYPE = "disable_joinable_site_types"; // Names of state attributes corresponding to properties of a site private final static String PROP_SITE_CONTACT_EMAIL = "contact-email"; private final static String PROP_SITE_CONTACT_NAME = "contact-name"; private final static String PROP_SITE_TERM = "term"; private final static String PROP_SITE_TERM_EID = "term_eid"; /** * Name of the state attribute holding the site list column list is sorted * by */ private static final String SORTED_BY = "site.sorted.by"; /** Name of the state attribute holding the site list column to sort by */ private static final String SORTED_ASC = "site.sort.asc"; /** State attribute for list of sites to be deleted. */ private static final String STATE_SITE_REMOVALS = "site.removals"; /** Name of the state attribute holding the site list View selected */ private static final String STATE_VIEW_SELECTED = "site.view.selected"; /** Names of lists related to tools */ private static final String STATE_TOOL_REGISTRATION_LIST = "toolRegistrationList"; private static final String STATE_TOOL_REGISTRATION_SELECTED_LIST = "toolRegistrationSelectedList"; private static final String STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST = "toolRegistrationOldSelectedList"; private static final String STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME = "toolRegistrationOldSelectedHome"; private static final String STATE_TOOL_EMAIL_ADDRESS = "toolEmailAddress"; private static final String STATE_TOOL_HOME_SELECTED = "toolHomeSelected"; private static final String STATE_PROJECT_TOOL_LIST = "projectToolList"; private final static String STATE_MULTIPLE_TOOL_ID_SET = "multipleToolIdSet"; private final static String STATE_MULTIPLE_TOOL_ID_TITLE_MAP = "multipleToolIdTitleMap"; private final static String STATE_MULTIPLE_TOOL_CONFIGURATION = "multipleToolConfiguration"; private final static String SITE_DEFAULT_LIST = ServerConfigurationService .getString("site.types"); private final static String STATE_SITE_QUEST_UNIQNAME = "site_quest_uniqname"; private static final String STATE_SITE_ADD_COURSE = "canAddCourse"; // %%% get rid of the IdAndText tool lists and just use ToolConfiguration or // ToolRegistration lists // %%% same for CourseItems // Names for other state attributes that are lists private final static String STATE_WORKSITE_SETUP_PAGE_LIST = "wSetupPageList"; // the // list // of // site // pages // consistent // with // Worksite // Setup // page // patterns /** * The name of the state form field containing additional information for a * course request */ private static final String FORM_ADDITIONAL = "form.additional"; /** %%% in transition from putting all form variables in state */ private final static String FORM_TITLE = "form_title"; private final static String FORM_URL_BASE = "form_url_base"; private final static String FORM_URL_ALIAS = "form_url_alias"; private final static String FORM_URL_ALIAS_FULL = "form_url_alias_full"; private final static String FORM_DESCRIPTION = "form_description"; private final static String FORM_HONORIFIC = "form_honorific"; private final static String FORM_INSTITUTION = "form_institution"; private final static String FORM_SUBJECT = "form_subject"; private final static String FORM_PHONE = "form_phone"; private final static String FORM_EMAIL = "form_email"; private final static String FORM_REUSE = "form_reuse"; private final static String FORM_RELATED_CLASS = "form_related_class"; private final static String FORM_RELATED_PROJECT = "form_related_project"; private final static String FORM_NAME = "form_name"; private final static String FORM_SHORT_DESCRIPTION = "form_short_description"; private final static String FORM_ICON_URL = "iconUrl"; /** site info edit form variables */ private final static String FORM_SITEINFO_TITLE = "siteinfo_title"; private final static String FORM_SITEINFO_TERM = "siteinfo_term"; private final static String FORM_SITEINFO_DESCRIPTION = "siteinfo_description"; private final static String FORM_SITEINFO_SHORT_DESCRIPTION = "siteinfo_short_description"; private final static String FORM_SITEINFO_SKIN = "siteinfo_skin"; private final static String FORM_SITEINFO_INCLUDE = "siteinfo_include"; private final static String FORM_SITEINFO_ICON_URL = "siteinfo_icon_url"; private final static String FORM_SITEINFO_CONTACT_NAME = "siteinfo_contact_name"; private final static String FORM_SITEINFO_CONTACT_EMAIL = "siteinfo_contact_email"; private final static String FORM_WILL_NOTIFY = "form_will_notify"; /** Context action */ private static final String CONTEXT_ACTION = "SiteAction"; /** The name of the Attribute for display template index */ private static final String STATE_TEMPLATE_INDEX = "site.templateIndex"; /** State attribute for state initialization. */ private static final String STATE_INITIALIZED = "site.initialized"; /** State attribute for state initialization. */ private static final String STATE_TEMPLATE_SITE = "site.templateSite"; /** The action for menu */ private static final String STATE_ACTION = "site.action"; /** The user copyright string */ private static final String STATE_MY_COPYRIGHT = "resources.mycopyright"; /** The copyright character */ private static final String COPYRIGHT_SYMBOL = "copyright (c)"; /** The null/empty string */ private static final String NULL_STRING = ""; /** The state attribute alerting user of a sent course request */ private static final String REQUEST_SENT = "site.request.sent"; /** The state attributes in the make public vm */ private static final String STATE_JOINABLE = "state_joinable"; private static final String STATE_JOINERROLE = "state_joinerRole"; /** the list of selected user */ private static final String STATE_SELECTED_USER_LIST = "state_selected_user_list"; private static final String STATE_SELECTED_PARTICIPANT_ROLES = "state_selected_participant_roles"; private static final String STATE_SELECTED_PARTICIPANTS = "state_selected_participants"; private static final String STATE_PARTICIPANT_LIST = "state_participant_list"; private static final String STATE_ADD_PARTICIPANTS = "state_add_participants"; /** for changing participant roles */ private static final String STATE_CHANGEROLE_SAMEROLE = "state_changerole_samerole"; private static final String STATE_CHANGEROLE_SAMEROLE_ROLE = "state_changerole_samerole_role"; /** for remove user */ private static final String STATE_REMOVEABLE_USER_LIST = "state_removeable_user_list"; private static final String STATE_IMPORT = "state_import"; private static final String STATE_IMPORT_SITES = "state_import_sites"; private static final String STATE_IMPORT_SITE_TOOL = "state_import_site_tool"; /** for navigating between sites in site list */ private static final String STATE_SITES = "state_sites"; private static final String STATE_PREV_SITE = "state_prev_site"; private static final String STATE_NEXT_SITE = "state_next_site"; /** for course information */ private final static String STATE_TERM_COURSE_LIST = "state_term_course_list"; private final static String STATE_TERM_COURSE_HASH = "state_term_course_hash"; private final static String STATE_TERM_SELECTED = "state_term_selected"; private final static String STATE_INSTRUCTOR_SELECTED = "state_instructor_selected"; private final static String STATE_FUTURE_TERM_SELECTED = "state_future_term_selected"; private final static String STATE_ADD_CLASS_PROVIDER = "state_add_class_provider"; private final static String STATE_ADD_CLASS_PROVIDER_CHOSEN = "state_add_class_provider_chosen"; private final static String STATE_ADD_CLASS_MANUAL = "state_add_class_manual"; private final static String STATE_AUTO_ADD = "state_auto_add"; private final static String STATE_MANUAL_ADD_COURSE_NUMBER = "state_manual_add_course_number"; private final static String STATE_MANUAL_ADD_COURSE_FIELDS = "state_manual_add_course_fields"; public final static String PROP_SITE_REQUEST_COURSE = "site-request-course-sections"; public final static String SITE_PROVIDER_COURSE_LIST = "site_provider_course_list"; public final static String SITE_MANUAL_COURSE_LIST = "site_manual_course_list"; private final static String STATE_SUBJECT_AFFILIATES = "site.subject.affiliates"; private final static String STATE_ICONS = "icons"; // site template used to create a UM Grad Tools student site public static final String SITE_GTS_TEMPLATE = "!gtstudent"; // the type used to identify a UM Grad Tools student site public static final String SITE_TYPE_GRADTOOLS_STUDENT = "GradToolsStudent"; // list of UM Grad Tools site types for editing public static final String GRADTOOLS_SITE_TYPES = "gradtools_site_types"; public static final String SITE_DUPLICATED = "site_duplicated"; public static final String SITE_DUPLICATED_NAME = "site_duplicated_named"; // used for site creation wizard title public static final String SITE_CREATE_TOTAL_STEPS = "site_create_total_steps"; public static final String SITE_CREATE_CURRENT_STEP = "site_create_current_step"; // types of site whose title can be editable public static final String TITLE_EDITABLE_SITE_TYPE = "title_editable_site_type"; // maximum length of a site title private static final String STATE_SITE_TITLE_MAX = "site_title_max_length"; // types of site where site view roster permission is editable public static final String EDIT_VIEW_ROSTER_SITE_TYPE = "edit_view_roster_site_type"; // htripath : for import material from file - classic import private static final String ALL_ZIP_IMPORT_SITES = "allzipImports"; private static final String FINAL_ZIP_IMPORT_SITES = "finalzipImports"; private static final String DIRECT_ZIP_IMPORT_SITES = "directzipImports"; private static final String CLASSIC_ZIP_FILE_NAME = "classicZipFileName"; private static final String SESSION_CONTEXT_ID = "sessionContextId"; // page size for worksite setup tool private static final String STATE_PAGESIZE_SITESETUP = "state_pagesize_sitesetup"; // page size for site info tool private static final String STATE_PAGESIZE_SITEINFO = "state_pagesize_siteinfo"; private static final String IMPORT_DATA_SOURCE = "import_data_source"; // Special tool id for Home page private static final String SITE_INFORMATION_TOOL="sakai.iframe.site"; private static final String STATE_CM_LEVELS = "site.cm.levels"; private static final String STATE_CM_LEVEL_OPTS = "site.cm.level_opts"; private static final String STATE_CM_LEVEL_SELECTIONS = "site.cm.level.selections"; private static final String STATE_CM_SELECTED_SECTION = "site.cm.selectedSection"; private static final String STATE_CM_REQUESTED_SECTIONS = "site.cm.requested"; private static final String STATE_CM_SELECTED_SECTIONS = "site.cm.selectedSections"; private static final String STATE_PROVIDER_SECTION_LIST = "site_provider_section_list"; private static final String STATE_CM_CURRENT_USERID = "site_cm_current_userId"; private static final String STATE_CM_AUTHORIZER_LIST = "site_cm_authorizer_list"; private static final String STATE_CM_AUTHORIZER_SECTIONS = "site_cm_authorizer_sections"; private String cmSubjectCategory; private boolean warnedNoSubjectCategory = false; // the string marks the protocol part in url private static final String PROTOCOL_STRING = "://"; private static final String TOOL_ID_SUMMARY_CALENDAR = "sakai.summary.calendar"; // the string for course site type private static final String STATE_COURSE_SITE_TYPE = "state_course_site_type"; private static final String SITE_TEMPLATE_PREFIX = "template"; private static final String STATE_TYPE_SELECTED = "state_type_selected"; // the template index after exist the question mode private static final String STATE_SITE_SETUP_QUESTION_NEXT_TEMPLATE = "state_site_setup_question_next_template"; // SAK-12912, the answers to site setup questions private static final String STATE_SITE_SETUP_QUESTION_ANSWER = "state_site_setup_question_answer"; // SAK-13389, the non-official participant private static final String ADD_NON_OFFICIAL_PARTICIPANT = "add_non_official_participant"; // the list of visited templates private static final String STATE_VISITED_TEMPLATES = "state_visited_templates"; private String STATE_GROUP_HELPER_ID = "state_group_helper_id"; // used in the configuration file to specify which tool attributes are configurable through WSetup tool, and what are the default value for them. private String CONFIG_TOOL_ATTRIBUTE = "wsetup.config.tool.attribute_"; private String CONFIG_TOOL_ATTRIBUTE_DEFAULT = "wsetup.config.tool.attribute.default_"; /** * what is the main tool id within Home page? * @param state * @param siteType * @return */ private String getHomeToolId(SessionState state) { String rv = ""; String siteType = state.getAttribute(STATE_SITE_TYPE) != null? (String) state.getAttribute(STATE_SITE_TYPE):""; Set categories = new HashSet(); categories.add(siteType); Set toolRegistrationList = ToolManager.findTools(categories, null); if (siteType.equalsIgnoreCase("myworkspace")) { // first try with the myworkspace information tool if (ToolManager.getTool("sakai.iframe.myworkspace") != null) rv = "sakai.iframe.myworkspace"; if (rv.equals("")) { // try again with MOTD tool if (ToolManager.getTool("sakai.motd") != null) rv = "sakai.motd"; } } else { // try the site information tool if (ToolManager.getTool("sakai.iframe.site") != null) rv = "sakai.iframe.site"; } return rv; } /** * Populate the state object, if needed. */ protected void initState(SessionState state, VelocityPortlet portlet, JetspeedRunData rundata) { // Cleanout if the helper has been asked to start afresh. if (state.getAttribute(SiteHelper.SITE_CREATE_START) != null) { cleanState(state); cleanStateHelper(state); // Removed from possible previous invokations. state.removeAttribute(SiteHelper.SITE_CREATE_START); state.removeAttribute(SiteHelper.SITE_CREATE_CANCELLED); state.removeAttribute(SiteHelper.SITE_CREATE_SITE_ID); } super.initState(state, portlet, rundata); // store current userId in state User user = UserDirectoryService.getCurrentUser(); String userId = user.getEid(); state.setAttribute(STATE_CM_CURRENT_USERID, userId); PortletConfig config = portlet.getPortletConfig(); // types of sites that can either be public or private String changeableTypes = StringUtil.trimToNull(config .getInitParameter("publicChangeableSiteTypes")); if (state.getAttribute(STATE_PUBLIC_CHANGEABLE_SITE_TYPES) == null) { if (changeableTypes != null) { state .setAttribute(STATE_PUBLIC_CHANGEABLE_SITE_TYPES, new ArrayList(Arrays.asList(changeableTypes .split(",")))); } else { state.setAttribute(STATE_PUBLIC_CHANGEABLE_SITE_TYPES, new Vector()); } } // type of sites that are always public String publicTypes = StringUtil.trimToNull(config .getInitParameter("publicSiteTypes")); if (state.getAttribute(STATE_PUBLIC_SITE_TYPES) == null) { if (publicTypes != null) { state.setAttribute(STATE_PUBLIC_SITE_TYPES, new ArrayList( Arrays.asList(publicTypes.split(",")))); } else { state.setAttribute(STATE_PUBLIC_SITE_TYPES, new Vector()); } } // types of sites that are always private String privateTypes = StringUtil.trimToNull(config .getInitParameter("privateSiteTypes")); if (state.getAttribute(STATE_PRIVATE_SITE_TYPES) == null) { if (privateTypes != null) { state.setAttribute(STATE_PRIVATE_SITE_TYPES, new ArrayList( Arrays.asList(privateTypes.split(",")))); } else { state.setAttribute(STATE_PRIVATE_SITE_TYPES, new Vector()); } } // default site type String defaultType = StringUtil.trimToNull(config .getInitParameter("defaultSiteType")); if (state.getAttribute(STATE_DEFAULT_SITE_TYPE) == null) { if (defaultType != null) { state.setAttribute(STATE_DEFAULT_SITE_TYPE, defaultType); } else { state.setAttribute(STATE_PRIVATE_SITE_TYPES, new Vector()); } } // certain type(s) of site cannot get its "joinable" option set if (state.getAttribute(STATE_DISABLE_JOINABLE_SITE_TYPE) == null) { if (ServerConfigurationService .getStrings("wsetup.disable.joinable") != null) { state.setAttribute(STATE_DISABLE_JOINABLE_SITE_TYPE, new ArrayList(Arrays.asList(ServerConfigurationService .getStrings("wsetup.disable.joinable")))); } else { state.setAttribute(STATE_DISABLE_JOINABLE_SITE_TYPE, new Vector()); } } // course site type if (state.getAttribute(STATE_COURSE_SITE_TYPE) == null) { state.setAttribute(STATE_COURSE_SITE_TYPE, ServerConfigurationService.getString("courseSiteType", "course")); } if (state.getAttribute(STATE_TOP_PAGE_MESSAGE) == null) { state.setAttribute(STATE_TOP_PAGE_MESSAGE, new Integer(0)); } // skins if any if (state.getAttribute(STATE_ICONS) == null) { setupIcons(state); } if (state.getAttribute(GRADTOOLS_SITE_TYPES) == null) { List gradToolsSiteTypes = new Vector(); if (ServerConfigurationService.getStrings("gradToolsSiteType") != null) { gradToolsSiteTypes = new ArrayList(Arrays .asList(ServerConfigurationService .getStrings("gradToolsSiteType"))); } state.setAttribute(GRADTOOLS_SITE_TYPES, gradToolsSiteTypes); } if (ServerConfigurationService.getStrings("titleEditableSiteType") != null) { state.setAttribute(TITLE_EDITABLE_SITE_TYPE, new ArrayList(Arrays .asList(ServerConfigurationService .getStrings("titleEditableSiteType")))); } else { state.setAttribute(TITLE_EDITABLE_SITE_TYPE, new Vector()); } if (state.getAttribute(EDIT_VIEW_ROSTER_SITE_TYPE) == null) { List siteTypes = new Vector(); if (ServerConfigurationService.getStrings("editViewRosterSiteType") != null) { siteTypes = new ArrayList(Arrays .asList(ServerConfigurationService .getStrings("editViewRosterSiteType"))); } state.setAttribute(EDIT_VIEW_ROSTER_SITE_TYPE, siteTypes); } if (state.getAttribute(STATE_SITE_MODE) == null) { // get site tool mode from tool registry String site_mode = config.getInitParameter(STATE_SITE_MODE); // When in helper mode we don't have if (site_mode == null) { site_mode = SITE_MODE_HELPER; } state.setAttribute(STATE_SITE_MODE, site_mode); } } // initState /** * cleanState removes the current site instance and it's properties from * state */ private void cleanState(SessionState state) { state.removeAttribute(STATE_SITE_INSTANCE_ID); state.removeAttribute(STATE_SITE_INFO); state.removeAttribute(STATE_SITE_TYPE); state.removeAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST); state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME); state.removeAttribute(STATE_TOOL_EMAIL_ADDRESS); state.removeAttribute(STATE_TOOL_HOME_SELECTED); state.removeAttribute(STATE_SELECTED_USER_LIST); state.removeAttribute(STATE_JOINABLE); state.removeAttribute(STATE_JOINERROLE); state.removeAttribute(STATE_SITE_QUEST_UNIQNAME); state.removeAttribute(STATE_IMPORT); state.removeAttribute(STATE_IMPORT_SITES); state.removeAttribute(STATE_IMPORT_SITE_TOOL); // remove those state attributes related to course site creation state.removeAttribute(STATE_TERM_COURSE_LIST); state.removeAttribute(STATE_TERM_COURSE_HASH); state.removeAttribute(STATE_TERM_SELECTED); state.removeAttribute(STATE_INSTRUCTOR_SELECTED); state.removeAttribute(STATE_FUTURE_TERM_SELECTED); state.removeAttribute(STATE_ADD_CLASS_PROVIDER); state.removeAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN); state.removeAttribute(STATE_ADD_CLASS_MANUAL); state.removeAttribute(STATE_AUTO_ADD); state.removeAttribute(STATE_MANUAL_ADD_COURSE_NUMBER); state.removeAttribute(STATE_MANUAL_ADD_COURSE_FIELDS); state.removeAttribute(SITE_CREATE_TOTAL_STEPS); state.removeAttribute(SITE_CREATE_CURRENT_STEP); state.removeAttribute(STATE_PROVIDER_SECTION_LIST); state.removeAttribute(STATE_CM_LEVELS); state.removeAttribute(STATE_CM_LEVEL_SELECTIONS); state.removeAttribute(STATE_CM_SELECTED_SECTION); state.removeAttribute(STATE_CM_REQUESTED_SECTIONS); state.removeAttribute(STATE_CM_CURRENT_USERID); state.removeAttribute(STATE_CM_AUTHORIZER_LIST); state.removeAttribute(STATE_CM_AUTHORIZER_SECTIONS); state.removeAttribute(FORM_ADDITIONAL); // don't we need to clean this // too? -daisyf state.removeAttribute(STATE_TEMPLATE_SITE); state.removeAttribute(STATE_TYPE_SELECTED); state.removeAttribute(STATE_SITE_SETUP_QUESTION_ANSWER); state.removeAttribute(STATE_SITE_SETUP_QUESTION_NEXT_TEMPLATE); } // cleanState /** * Fire up the permissions editor */ public void doPermissions(RunData data, Context context) { // get into helper mode with this helper tool startHelper(data.getRequest(), "sakai.permissions.helper"); SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); String contextString = ToolManager.getCurrentPlacement().getContext(); String siteRef = SiteService.siteReference(contextString); // if it is in Worksite setup tool, pass the selected site's reference if (state.getAttribute(STATE_SITE_MODE) != null && ((String) state.getAttribute(STATE_SITE_MODE)) .equals(SITE_MODE_SITESETUP)) { if (state.getAttribute(STATE_SITE_INSTANCE_ID) != null) { Site s = getStateSite(state); if (s != null) { siteRef = s.getReference(); } } } // setup for editing the permissions of the site for this tool, using // the roles of this site, too state.setAttribute(PermissionsHelper.TARGET_REF, siteRef); // ... with this description state.setAttribute(PermissionsHelper.DESCRIPTION, rb .getString("setperfor") + " " + SiteService.getSiteDisplay(contextString)); // ... showing only locks that are prpefixed with this state.setAttribute(PermissionsHelper.PREFIX, "site."); } // doPermissions /** * Build the context for normal display */ public String buildMainPanelContext(VelocityPortlet portlet, Context context, RunData data, SessionState state) { rb = new ResourceLoader("sitesetupgeneric"); context.put("tlang", rb); // TODO: what is all this doing? if we are in helper mode, we are // already setup and don't get called here now -ggolden /* * String helperMode = (String) * state.getAttribute(PermissionsAction.STATE_MODE); if (helperMode != * null) { Site site = getStateSite(state); if (site != null) { if * (site.getType() != null && ((List) * state.getAttribute(EDIT_VIEW_ROSTER_SITE_TYPE)).contains(site.getType())) { * context.put("editViewRoster", Boolean.TRUE); } else { * context.put("editViewRoster", Boolean.FALSE); } } else { * context.put("editViewRoster", Boolean.FALSE); } // for new, don't * show site.del in Permission page context.put("hiddenLock", * "site.del"); * * String template = PermissionsAction.buildHelperContext(portlet, * context, data, state); if (template == null) { addAlert(state, * rb.getString("theisa")); } else { return template; } } */ String template = null; context.put("action", CONTEXT_ACTION); // updatePortlet(state, portlet, data); if (state.getAttribute(STATE_INITIALIZED) == null) { init(portlet, data, state); } String indexString = (String) state.getAttribute(STATE_TEMPLATE_INDEX); // update the visited template list with the current template index addIntoStateVisitedTemplates(state, indexString); template = buildContextForTemplate(getPrevVisitedTemplate(state), Integer.valueOf(indexString), portlet, context, data, state); return template; } // buildMainPanelContext /** * add index into the visited template indices list * @param state * @param index */ private void addIntoStateVisitedTemplates(SessionState state, String index) { List<String> templateIndices = (List<String>) state.getAttribute(STATE_VISITED_TEMPLATES); if (templateIndices.size() == 0 || !templateIndices.contains(index)) { // this is to prevent from page refreshing accidentally updates the list templateIndices.add(index); state.setAttribute(STATE_VISITED_TEMPLATES, templateIndices); } } /** * remove the last index * @param state */ private void removeLastIndexInStateVisitedTemplates(SessionState state) { List<String> templateIndices = (List<String>) state.getAttribute(STATE_VISITED_TEMPLATES); if (templateIndices!=null && templateIndices.size() > 0) { // this is to prevent from page refreshing accidentally updates the list templateIndices.remove(templateIndices.size()-1); state.setAttribute(STATE_VISITED_TEMPLATES, templateIndices); } } private String getPrevVisitedTemplate(SessionState state) { List<String> templateIndices = (List<String>) state.getAttribute(STATE_VISITED_TEMPLATES); if (templateIndices != null && templateIndices.size() >1 ) { return templateIndices.get(templateIndices.size()-2); } else { return null; } } /** * whether template indexed has been visited * @param state * @param templateIndex * @return */ private boolean isTemplateVisited(SessionState state, String templateIndex) { boolean rv = false; List<String> templateIndices = (List<String>) state.getAttribute(STATE_VISITED_TEMPLATES); if (templateIndices != null && templateIndices.size() >0 ) { rv = templateIndices.contains(templateIndex); } return rv; } /** * Build the context for each template using template_index parameter passed * in a form hidden field. Each case is associated with a template. (Not all * templates implemented). See String[] TEMPLATES. * * @param index * is the number contained in the template's template_index */ private String buildContextForTemplate(String preIndex, int index, VelocityPortlet portlet, Context context, RunData data, SessionState state) { String realmId = ""; String site_type = ""; String sortedBy = ""; String sortedAsc = ""; ParameterParser params = data.getParameters(); context.put("tlang", rb); context.put("alertMessage", state.getAttribute(STATE_MESSAGE)); // the last visited template index if (preIndex != null) context.put("backIndex", preIndex); context.put("templateIndex", String.valueOf(index)); // If cleanState() has removed SiteInfo, get a new instance into state SiteInfo siteInfo = new SiteInfo(); if (state.getAttribute(STATE_SITE_INFO) != null) { siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO); } else { state.setAttribute(STATE_SITE_INFO, siteInfo); } // Lists used in more than one template // Access List roles = new Vector(); // the hashtables for News and Web Content tools Hashtable newsTitles = new Hashtable(); Hashtable newsUrls = new Hashtable(); Hashtable wcTitles = new Hashtable(); Hashtable wcUrls = new Hashtable(); List toolRegistrationList = new Vector(); List toolRegistrationSelectedList = new Vector(); ResourceProperties siteProperties = null; // for showing site creation steps if (state.getAttribute(SITE_CREATE_TOTAL_STEPS) != null) { context.put("totalSteps", state .getAttribute(SITE_CREATE_TOTAL_STEPS)); } if (state.getAttribute(SITE_CREATE_CURRENT_STEP) != null) { context.put("step", state.getAttribute(SITE_CREATE_CURRENT_STEP)); } String hasGradSites = ServerConfigurationService.getString( "withDissertation", Boolean.FALSE.toString()); context.put("cms", cms); // course site type context.put("courseSiteType", state.getAttribute(STATE_COURSE_SITE_TYPE)); //can the user create course sites? context.put(STATE_SITE_ADD_COURSE, SiteService.allowAddCourseSite()); Site site = getStateSite(state); // get alias base path String aliasBaseUrl = ServerConfigurationService.getPortalUrl() + Entity.SEPARATOR + "site" + Entity.SEPARATOR; switch (index) { case 0: /* * buildContextForTemplate chef_site-list.vm * */ // site types List sTypes = (List) state.getAttribute(STATE_SITE_TYPES); // make sure auto-updates are enabled Hashtable views = new Hashtable(); if (SecurityService.isSuperUser()) { views.put(rb.getString("java.allmy"), rb .getString("java.allmy")); views.put(rb.getString("java.my") + " " + rb.getString("java.sites"), rb.getString("java.my")); for (int sTypeIndex = 0; sTypeIndex < sTypes.size(); sTypeIndex++) { String type = (String) sTypes.get(sTypeIndex); views.put(type + " " + rb.getString("java.sites"), type); } if (hasGradSites.equalsIgnoreCase("true")) { views.put(rb.getString("java.gradtools") + " " + rb.getString("java.sites"), rb .getString("java.gradtools")); } if (state.getAttribute(STATE_VIEW_SELECTED) == null) { state.setAttribute(STATE_VIEW_SELECTED, rb .getString("java.allmy")); } context.put("superUser", Boolean.TRUE); } else { context.put("superUser", Boolean.FALSE); views.put(rb.getString("java.allmy"), rb .getString("java.allmy")); // if there is a GradToolsStudent choice inside boolean remove = false; if (hasGradSites.equalsIgnoreCase("true")) { try { // the Grad Tools site option is only presented to // GradTools Candidates String userId = StringUtil.trimToZero(SessionManager .getCurrentSessionUserId()); // am I a grad student? if (!isGradToolsCandidate(userId)) { // not a gradstudent remove = true; } } catch (Exception e) { remove = true; M_log.warn(this + "buildContextForTemplate chef_site-list.vm list GradToolsStudent sites", e); } } else { // not support for dissertation sites remove = true; } // do not show this site type in views // sTypes.remove(new String(SITE_TYPE_GRADTOOLS_STUDENT)); for (int sTypeIndex = 0; sTypeIndex < sTypes.size(); sTypeIndex++) { String type = (String) sTypes.get(sTypeIndex); if (!type.equals(SITE_TYPE_GRADTOOLS_STUDENT)) { views .put(type + " " + rb.getString("java.sites"), type); } } if (!remove) { views.put(rb.getString("java.gradtools") + " " + rb.getString("java.sites"), rb .getString("java.gradtools")); } // default view if (state.getAttribute(STATE_VIEW_SELECTED) == null) { state.setAttribute(STATE_VIEW_SELECTED, rb .getString("java.allmy")); } } context.put("views", views); if (state.getAttribute(STATE_VIEW_SELECTED) != null) { context.put("viewSelected", (String) state .getAttribute(STATE_VIEW_SELECTED)); } String search = (String) state.getAttribute(STATE_SEARCH); context.put("search_term", search); sortedBy = (String) state.getAttribute(SORTED_BY); if (sortedBy == null) { state.setAttribute(SORTED_BY, SortType.TITLE_ASC.toString()); sortedBy = SortType.TITLE_ASC.toString(); } sortedAsc = (String) state.getAttribute(SORTED_ASC); if (sortedAsc == null) { sortedAsc = Boolean.TRUE.toString(); state.setAttribute(SORTED_ASC, sortedAsc); } if (sortedBy != null) context.put("currentSortedBy", sortedBy); if (sortedAsc != null) context.put("currentSortAsc", sortedAsc); String portalUrl = ServerConfigurationService.getPortalUrl(); context.put("portalUrl", portalUrl); List sites = prepPage(state); state.setAttribute(STATE_SITES, sites); context.put("sites", sites); context.put("totalPageNumber", new Integer(totalPageNumber(state))); context.put("searchString", state.getAttribute(STATE_SEARCH)); context.put("form_search", FORM_SEARCH); context.put("formPageNumber", FORM_PAGE_NUMBER); context.put("prev_page_exists", state .getAttribute(STATE_PREV_PAGE_EXISTS)); context.put("next_page_exists", state .getAttribute(STATE_NEXT_PAGE_EXISTS)); context.put("current_page", state.getAttribute(STATE_CURRENT_PAGE)); // put the service in the context (used for allow update calls on // each site) context.put("service", SiteService.getInstance()); context.put("sortby_title", SortType.TITLE_ASC.toString()); context.put("sortby_type", SortType.TYPE_ASC.toString()); context.put("sortby_createdby", SortType.CREATED_BY_ASC.toString()); context.put("sortby_publish", SortType.PUBLISHED_ASC.toString()); context.put("sortby_createdon", SortType.CREATED_ON_ASC.toString()); // top menu bar Menu bar = new MenuImpl(portlet, data, (String) state .getAttribute(STATE_ACTION)); if (SiteService.allowAddSite(null)) { bar.add(new MenuEntry(rb.getString("java.new"), "doNew_site")); } bar.add(new MenuEntry(rb.getString("java.revise"), null, true, MenuItem.CHECKED_NA, "doGet_site", "sitesForm")); bar.add(new MenuEntry(rb.getString("java.delete"), null, true, MenuItem.CHECKED_NA, "doMenu_site_delete", "sitesForm")); context.put("menu", bar); // default to be no pageing context.put("paged", Boolean.FALSE); Menu bar2 = new MenuImpl(portlet, data, (String) state .getAttribute(STATE_ACTION)); // add the search commands addSearchMenus(bar2, state); context.put("menu2", bar2); pagingInfoToContext(state, context); return (String) getContext(data).get("template") + TEMPLATE[0]; case 1: /* * buildContextForTemplate chef_site-type.vm * */ if (hasGradSites.equalsIgnoreCase("true")) { context.put("withDissertation", Boolean.TRUE); try { // the Grad Tools site option is only presented to UM grad // students String userId = StringUtil.trimToZero(SessionManager .getCurrentSessionUserId()); // am I a UM grad student? Boolean isGradStudent = new Boolean( isGradToolsCandidate(userId)); context.put("isGradStudent", isGradStudent); // if I am a UM grad student, do I already have a Grad Tools // site? boolean noGradToolsSite = true; if (hasGradToolsStudentSite(userId)) noGradToolsSite = false; context .put("noGradToolsSite", new Boolean(noGradToolsSite)); } catch (Exception e) { M_log.warn(this + "buildContextForTemplate chef_site-type.vm ", e); } } else { context.put("withDissertation", Boolean.FALSE); } List types = (List) state.getAttribute(STATE_SITE_TYPES); context.put("siteTypes", types); // put selected/default site type into context String typeSelected = (String) state.getAttribute(STATE_TYPE_SELECTED); context.put("typeSelected", state.getAttribute(STATE_TYPE_SELECTED) != null?state.getAttribute(STATE_TYPE_SELECTED):types.get(0)); setTermListForContext(context, state, true); // true => only // upcoming terms setSelectedTermForContext(context, state, STATE_TERM_SELECTED); // template site - Denny setTemplateListForContext(context, state); return (String) getContext(data).get("template") + TEMPLATE[1]; case 2: /* * buildContextForTemplate chef_site-newSiteInformation.vm * */ context.put("siteTypes", state.getAttribute(STATE_SITE_TYPES)); String siteType = (String) state.getAttribute(STATE_SITE_TYPE); context.put("type", siteType); context.put("siteTitleEditable", Boolean.valueOf(siteTitleEditable(state, siteType))); if (siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { context.put("isCourseSite", Boolean.TRUE); context.put("isProjectSite", Boolean.FALSE); if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null) { context.put("selectedProviderCourse", state .getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN)); } List<SectionObject> cmRequestedList = (List<SectionObject>) state .getAttribute(STATE_CM_REQUESTED_SECTIONS); if (cmRequestedList != null) { context.put("cmRequestedSections", cmRequestedList); } List<SectionObject> cmAuthorizerSectionList = (List<SectionObject>) state .getAttribute(STATE_CM_AUTHORIZER_SECTIONS); if (cmAuthorizerSectionList != null) { context .put("cmAuthorizerSections", cmAuthorizerSectionList); } if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) { int number = ((Integer) state .getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)) .intValue(); context.put("manualAddNumber", new Integer(number - 1)); context.put("manualAddFields", state .getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS)); } else { if (courseManagementIsImplemented()) { } else { context.put("templateIndex", "37"); } } // whether to show course skin selection choices or not courseSkinSelection(context, state, null, siteInfo); } else { context.put("isCourseSite", Boolean.FALSE); if (siteType.equalsIgnoreCase("project")) { context.put("isProjectSite", Boolean.TRUE); } if (StringUtil.trimToNull(siteInfo.iconUrl) != null) { context.put(FORM_ICON_URL, siteInfo.iconUrl); } } if (state.getAttribute(SiteHelper.SITE_CREATE_SITE_TITLE) != null) { context.put("titleEditableSiteType", Boolean.FALSE); siteInfo.title = (String)state.getAttribute(SiteHelper.SITE_CREATE_SITE_TITLE); } else { context.put("titleEditableSiteType", state .getAttribute(TITLE_EDITABLE_SITE_TYPE)); } context.put(FORM_TITLE, siteInfo.title); context.put(FORM_URL_BASE, aliasBaseUrl); context.put(FORM_URL_ALIAS, siteInfo.url_alias); context.put(FORM_SHORT_DESCRIPTION, siteInfo.short_description); context.put(FORM_DESCRIPTION, siteInfo.description); // defalt the site contact person to the site creator if (siteInfo.site_contact_name.equals(NULL_STRING) && siteInfo.site_contact_email.equals(NULL_STRING)) { User user = UserDirectoryService.getCurrentUser(); siteInfo.site_contact_name = user.getDisplayName(); siteInfo.site_contact_email = user.getEmail(); } context.put("form_site_contact_name", siteInfo.site_contact_name); context.put("form_site_contact_email", siteInfo.site_contact_email); // those manual inputs context.put("form_requiredFields", sectionFieldProvider .getRequiredFields()); context.put("fieldValues", state .getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS)); return (String) getContext(data).get("template") + TEMPLATE[2]; case 3: /* * buildContextForTemplate chef_site-editFeatures.vm * */ String type = (String) state.getAttribute(STATE_SITE_TYPE); if (type != null && type.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { context.put("isCourseSite", Boolean.TRUE); context.put("isProjectSite", Boolean.FALSE); } else { context.put("isCourseSite", Boolean.FALSE); if (type.equalsIgnoreCase("project")) { context.put("isProjectSite", Boolean.TRUE); } } List requiredTools = ServerConfigurationService.getToolsRequired(type); // look for legacy "home" tool context.put("defaultTools", replaceHomeToolId(state, requiredTools)); toolRegistrationSelectedList = (List) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); // If this is the first time through, check for tools // which should be selected by default. List defaultSelectedTools = ServerConfigurationService.getDefaultTools(type); defaultSelectedTools = replaceHomeToolId(state, defaultSelectedTools); if (toolRegistrationSelectedList == null) { toolRegistrationSelectedList = new Vector(defaultSelectedTools); } context.put(STATE_TOOL_REGISTRATION_SELECTED_LIST, toolRegistrationSelectedList); boolean myworkspace_site = false; // Put up tool lists filtered by category List siteTypes = (List) state.getAttribute(STATE_SITE_TYPES); if (siteTypes.contains(type)) { myworkspace_site = false; } if (site != null && SiteService.isUserSite(site.getId()) || (type != null && type.equalsIgnoreCase("myworkspace"))) { myworkspace_site = true; type = "myworkspace"; } context.put("myworkspace_site", new Boolean(myworkspace_site)); context.put(STATE_TOOL_REGISTRATION_LIST, state.getAttribute(STATE_TOOL_REGISTRATION_LIST)); // titles for multiple tool instances context.put(STATE_MULTIPLE_TOOL_ID_TITLE_MAP, state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP )); // The Home tool checkbox needs special treatment to be selected // by // default. Boolean checkHome = (Boolean) state.getAttribute(STATE_TOOL_HOME_SELECTED); if (checkHome == null) { if ((defaultSelectedTools != null) && defaultSelectedTools.contains(getHomeToolId(state))) { checkHome = Boolean.TRUE; } } context.put("check_home", checkHome); // get the email alias when an Email Archive tool has been selected String channelReference = site!=null?mailArchiveChannelReference(site.getId()):""; List aliases = AliasService.getAliases(channelReference, 1, 1); if (aliases.size() > 0) { state.setAttribute(STATE_TOOL_EMAIL_ADDRESS, ((Alias) aliases .get(0)).getId()); } if (state.getAttribute(STATE_TOOL_EMAIL_ADDRESS) != null) { context.put("emailId", state .getAttribute(STATE_TOOL_EMAIL_ADDRESS)); } context.put("serverName", ServerConfigurationService .getServerName()); context.put("sites", SiteService.getSites( org.sakaiproject.site.api.SiteService.SelectionType.UPDATE, null, null, null, SortType.TITLE_ASC, null)); context.put("import", state.getAttribute(STATE_IMPORT)); context.put("importSites", state.getAttribute(STATE_IMPORT_SITES)); if (site != null) { context.put("SiteTitle", site.getTitle()); context.put("existSite", Boolean.TRUE); context.put("backIndex", "12"); // back to site info list page } else { context.put("existSite", Boolean.FALSE); context.put("backIndex", "2"); // back to new site information page } context.put("homeToolId", getHomeToolId(state)); return (String) getContext(data).get("template") + TEMPLATE[3]; case 5: /* * buildContextForTemplate chef_site-addParticipant.vm * */ context.put("title", site.getTitle()); roles = getRoles(state); context.put("roles", roles); siteType = (String) state.getAttribute(STATE_SITE_TYPE); context.put("isCourseSite", siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))?Boolean.TRUE:Boolean.FALSE); // Note that (for now) these strings are in both sakai.properties // and sitesetupgeneric.properties context.put("officialAccountSectionTitle", ServerConfigurationService .getString("officialAccountSectionTitle")); context.put("officialAccountName", ServerConfigurationService .getString("officialAccountName")); context.put("officialAccountLabel", ServerConfigurationService .getString("officialAccountLabel")); String pickerAction = ServerConfigurationService.getString("officialAccountPickerAction"); if (pickerAction != null && !"".equals(pickerAction)) { context.put("hasPickerDefined", Boolean.TRUE); context.put("officialAccountPickerLabel", ServerConfigurationService .getString("officialAccountPickerLabel")); context.put("officialAccountPickerAction", pickerAction); } if (state.getAttribute("officialAccountValue") != null) { context.put("officialAccountValue", (String) state .getAttribute("officialAccountValue")); } // whether to show the non-official participant section or not String addNonOfficialParticipant = (String) state.getAttribute(ADD_NON_OFFICIAL_PARTICIPANT); if (addNonOfficialParticipant != null) { if (addNonOfficialParticipant.equalsIgnoreCase("true")) { context.put("nonOfficialAccount", Boolean.TRUE); context.put("nonOfficialAccountSectionTitle", ServerConfigurationService .getString("nonOfficialAccountSectionTitle")); context.put("nonOfficialAccountName", ServerConfigurationService .getString("nonOfficialAccountName")); context.put("nonOfficialAccountLabel", ServerConfigurationService .getString("nonOfficialAccountLabel")); if (state.getAttribute("nonOfficialAccountValue") != null) { context.put("nonOfficialAccountValue", (String) state .getAttribute("nonOfficialAccountValue")); } } else { context.put("nonOfficialAccount", Boolean.FALSE); } } if (state.getAttribute("form_same_role") != null) { context.put("form_same_role", ((Boolean) state .getAttribute("form_same_role")).toString()); } else { context.put("form_same_role", Boolean.TRUE.toString()); } context.put("backIndex", "12"); return (String) getContext(data).get("template") + TEMPLATE[5]; case 8: /* * buildContextForTemplate chef_site-siteDeleteConfirm.vm * */ String site_title = NULL_STRING; String[] removals = (String[]) state .getAttribute(STATE_SITE_REMOVALS); List remove = new Vector(); String user = SessionManager.getCurrentSessionUserId(); String workspace = SiteService.getUserSiteId(user); if (removals != null && removals.length != 0) { for (int i = 0; i < removals.length; i++) { String id = (String) removals[i]; if (!(id.equals(workspace))) { try { site_title = SiteService.getSite(id).getTitle(); } catch (IdUnusedException e) { M_log.warn(this + "buildContextForTemplate chef_site-siteDeleteConfirm.vm - IdUnusedException " + id, e); addAlert(state, rb.getString("java.sitewith") + " " + id + " " + rb.getString("java.couldnt") + " "); } if (SiteService.allowRemoveSite(id)) { try { Site removeSite = SiteService.getSite(id); remove.add(removeSite); } catch (IdUnusedException e) { M_log.warn(this + ".buildContextForTemplate chef_site-siteDeleteConfirm.vm: IdUnusedException", e); } } else { addAlert(state, site_title + " " + rb.getString("java.couldntdel") + " "); } } else { addAlert(state, rb.getString("java.yourwork")); } } if (remove.size() == 0) { addAlert(state, rb.getString("java.click")); } } context.put("removals", remove); return (String) getContext(data).get("template") + TEMPLATE[8]; case 10: /* * buildContextForTemplate chef_site-newSiteConfirm.vm * */ siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO); siteType = (String) state.getAttribute(STATE_SITE_TYPE); if (siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { context.put("isCourseSite", Boolean.TRUE); context.put("disableCourseSelection", ServerConfigurationService.getString("disable.course.site.skin.selection", "false").equals("true")?Boolean.TRUE:Boolean.FALSE); context.put("isProjectSite", Boolean.FALSE); if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null) { context.put("selectedProviderCourse", state .getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN)); } if (state.getAttribute(STATE_CM_AUTHORIZER_SECTIONS) != null) { context.put("selectedAuthorizerCourse", state .getAttribute(STATE_CM_AUTHORIZER_SECTIONS)); } if (state.getAttribute(STATE_CM_REQUESTED_SECTIONS) != null) { context.put("selectedRequestedCourse", state .getAttribute(STATE_CM_REQUESTED_SECTIONS)); } if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) { int number = ((Integer) state .getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)) .intValue(); context.put("manualAddNumber", new Integer(number - 1)); context.put("manualAddFields", state .getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS)); } context.put("skins", state.getAttribute(STATE_ICONS)); if (StringUtil.trimToNull(siteInfo.getIconUrl()) != null) { context.put("selectedIcon", siteInfo.getIconUrl()); } } else { context.put("isCourseSite", Boolean.FALSE); if (siteType != null && siteType.equalsIgnoreCase("project")) { context.put("isProjectSite", Boolean.TRUE); } if (StringUtil.trimToNull(siteInfo.iconUrl) != null) { context.put("iconUrl", siteInfo.iconUrl); } } if (StringUtil.trimToNull(siteInfo.getUrlAlias()) != null) { String urlAliasFull = aliasBaseUrl + siteInfo.getUrlAlias(); context.put(FORM_URL_ALIAS_FULL, urlAliasFull); } context.put("title", siteInfo.title); context.put("description", siteInfo.description); context.put("short_description", siteInfo.short_description); context.put("siteContactName", siteInfo.site_contact_name); context.put("siteContactEmail", siteInfo.site_contact_email); siteType = (String) state.getAttribute(STATE_SITE_TYPE); toolRegistrationSelectedList = (List) state .getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); context.put(STATE_TOOL_REGISTRATION_SELECTED_LIST, toolRegistrationSelectedList); // String toolId's context.put(STATE_TOOL_REGISTRATION_LIST, state .getAttribute(STATE_TOOL_REGISTRATION_LIST)); // %%% use Tool // all info related to multiple tools multipleToolIntoContext(context, state); context.put("check_home", state .getAttribute(STATE_TOOL_HOME_SELECTED)); context .put("emailId", state .getAttribute(STATE_TOOL_EMAIL_ADDRESS)); context.put("serverName", ServerConfigurationService .getServerName()); context.put("include", new Boolean(siteInfo.include)); context.put("published", new Boolean(siteInfo.published)); context.put("joinable", new Boolean(siteInfo.joinable)); context.put("joinerRole", siteInfo.joinerRole); context.put("importSiteTools", state .getAttribute(STATE_IMPORT_SITE_TOOL)); context.put("siteService", SiteService.getInstance()); // those manual inputs context.put("form_requiredFields", sectionFieldProvider .getRequiredFields()); context.put("fieldValues", state .getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS)); return (String) getContext(data).get("template") + TEMPLATE[10]; case 12: /* * buildContextForTemplate chef_site-siteInfo-list.vm * */ context.put("userDirectoryService", UserDirectoryService .getInstance()); try { siteProperties = site.getProperties(); siteType = site.getType(); if (siteType != null) { state.setAttribute(STATE_SITE_TYPE, siteType); } if (site.getProviderGroupId() != null) { M_log.debug("site has provider"); context.put("hasProviderSet", Boolean.TRUE); } else { M_log.debug("site has no provider"); context.put("hasProviderSet", Boolean.FALSE); } boolean isMyWorkspace = false; if (SiteService.isUserSite(site.getId())) { if (SiteService.getSiteUserId(site.getId()).equals( SessionManager.getCurrentSessionUserId())) { isMyWorkspace = true; context.put("siteUserId", SiteService .getSiteUserId(site.getId())); } } context.put("isMyWorkspace", Boolean.valueOf(isMyWorkspace)); String siteId = site.getId(); if (state.getAttribute(STATE_ICONS) != null) { List skins = (List) state.getAttribute(STATE_ICONS); for (int i = 0; i < skins.size(); i++) { MyIcon s = (MyIcon) skins.get(i); if (!StringUtil .different(s.getUrl(), site.getIconUrl())) { context.put("siteUnit", s.getName()); break; } } } context.put("siteIcon", site.getIconUrl()); context.put("siteTitle", site.getTitle()); context.put("siteDescription", site.getDescription()); context.put("siteJoinable", new Boolean(site.isJoinable())); if (site.isPublished()) { context.put("published", Boolean.TRUE); } else { context.put("published", Boolean.FALSE); context.put("owner", site.getCreatedBy().getSortName()); } Time creationTime = site.getCreatedTime(); if (creationTime != null) { context.put("siteCreationDate", creationTime .toStringLocalFull()); } boolean allowUpdateSite = SiteService.allowUpdateSite(siteId); context.put("allowUpdate", Boolean.valueOf(allowUpdateSite)); boolean allowUpdateGroupMembership = SiteService .allowUpdateGroupMembership(siteId); context.put("allowUpdateGroupMembership", Boolean .valueOf(allowUpdateGroupMembership)); boolean allowUpdateSiteMembership = SiteService .allowUpdateSiteMembership(siteId); context.put("allowUpdateSiteMembership", Boolean .valueOf(allowUpdateSiteMembership)); Menu b = new MenuImpl(portlet, data, (String) state .getAttribute(STATE_ACTION)); if (allowUpdateSite) { // top menu bar if (!isMyWorkspace) { b.add(new MenuEntry(rb.getString("java.editsite"), "doMenu_edit_site_info")); } b.add(new MenuEntry(rb.getString("java.edittools"), "doMenu_edit_site_tools")); // if the page order helper is available, not // stealthed and not hidden, show the link if (notStealthOrHiddenTool("sakai-site-pageorder-helper")) { // in particular, need to check site types for showing the tool or not if (isPageOrderAllowed(siteType)) { b.add(new MenuEntry(rb.getString("java.orderpages"), "doPageOrderHelper")); } } } if (allowUpdateSiteMembership) { // show add participant menu if (!isMyWorkspace) { // if the add participant helper is available, not // stealthed and not hidden, show the link if (notStealthOrHiddenTool("sakai-site-manage-participant-helper")) { b.add(new MenuEntry(rb.getString("java.addp"), "doParticipantHelper")); } // show the Edit Class Roster menu if (ServerConfigurationService.getBoolean("site.setup.allow.editRoster", true) && siteType != null && siteType.equals((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { b.add(new MenuEntry(rb.getString("java.editc"), "doMenu_siteInfo_editClass")); } } } if (allowUpdateGroupMembership) { // show Manage Groups menu if (!isMyWorkspace && (ServerConfigurationService .getString("wsetup.group.support") == "" || ServerConfigurationService .getString("wsetup.group.support") .equalsIgnoreCase(Boolean.TRUE.toString()))) { // show the group toolbar unless configured // to not support group // if the manage group helper is available, not // stealthed and not hidden, show the link - if (setHelper("wsetup.groupHelper", "sakai-site-manage-group-helper", state, STATE_GROUP_HELPER_ID)) { + // read the helper name from configuration variable: wsetup.group.helper.name + // the default value is: "sakai-site-manage-group-section-role-helper" + // the older version of group helper which is not section/role aware is named:"sakai-site-manage-group-helper" + String groupHelper = ServerConfigurationService.getString("wsetup.group.helper.name", "sakai-site-manage-group-section-role-helper"); + if (setHelper("wsetup.groupHelper", groupHelper, state, STATE_GROUP_HELPER_ID)) { b.add(new MenuEntry(rb.getString("java.group"), "doManageGroupHelper")); } } } if (allowUpdateSite) { if (!isMyWorkspace) { List gradToolsSiteTypes = (List) state .getAttribute(GRADTOOLS_SITE_TYPES); boolean isGradToolSite = false; if (siteType != null && gradToolsSiteTypes.contains(siteType)) { isGradToolSite = true; } if (siteType == null || siteType != null && !isGradToolSite) { // hide site access for GRADTOOLS // type of sites b.add(new MenuEntry( rb.getString("java.siteaccess"), "doMenu_edit_site_access")); } if (siteType == null || siteType != null && !isGradToolSite) { // hide site duplicate and import // for GRADTOOLS type of sites if (SiteService.allowAddSite(null)) { b.add(new MenuEntry(rb.getString("java.duplicate"), "doMenu_siteInfo_duplicate")); } List updatableSites = SiteService .getSites( org.sakaiproject.site.api.SiteService.SelectionType.UPDATE, null, null, null, SortType.TITLE_ASC, null); // import link should be visible even if only one // site if (updatableSites.size() > 0) { //a configuration param for showing/hiding Import From Site with Clean Up String importFromSite = ServerConfigurationService.getString("clean.import.site",Boolean.TRUE.toString()); if (importFromSite.equalsIgnoreCase("true")) { b.add(new MenuEntry( rb.getString("java.import"), "doMenu_siteInfo_importSelection")); } else { b.add(new MenuEntry( rb.getString("java.import"), "doMenu_siteInfo_import")); } // a configuration param for // showing/hiding import // from file choice String importFromFile = ServerConfigurationService .getString("site.setup.import.file", Boolean.TRUE.toString()); if (importFromFile.equalsIgnoreCase("true")) { // htripath: June // 4th added as per // Kris and changed // desc of above b.add(new MenuEntry(rb .getString("java.importFile"), "doAttachmentsMtrlFrmFile")); } } } } } if (b.size() > 0) { // add the menus to vm context.put("menu", b); } if (((String) state.getAttribute(STATE_SITE_MODE)) .equalsIgnoreCase(SITE_MODE_SITESETUP)) { // editing from worksite setup tool context.put("fromWSetup", Boolean.TRUE); if (state.getAttribute(STATE_PREV_SITE) != null) { context.put("prevSite", state .getAttribute(STATE_PREV_SITE)); } if (state.getAttribute(STATE_NEXT_SITE) != null) { context.put("nextSite", state .getAttribute(STATE_NEXT_SITE)); } } else { context.put("fromWSetup", Boolean.FALSE); } // allow view roster? boolean allowViewRoster = SiteService.allowViewRoster(siteId); if (allowViewRoster) { context.put("viewRoster", Boolean.TRUE); } else { context.put("viewRoster", Boolean.FALSE); } // set participant list if (allowUpdateSite || allowViewRoster || allowUpdateSiteMembership) { Collection participantsCollection = getParticipantList(state); sortedBy = (String) state.getAttribute(SORTED_BY); sortedAsc = (String) state.getAttribute(SORTED_ASC); if (sortedBy == null) { state.setAttribute(SORTED_BY, SiteConstants.SORTED_BY_PARTICIPANT_NAME); sortedBy = SiteConstants.SORTED_BY_PARTICIPANT_NAME; } if (sortedAsc == null) { sortedAsc = Boolean.TRUE.toString(); state.setAttribute(SORTED_ASC, sortedAsc); } if (sortedBy != null) context.put("currentSortedBy", sortedBy); if (sortedAsc != null) context.put("currentSortAsc", sortedAsc); context.put("participantListSize", new Integer(participantsCollection.size())); context.put("participantList", prepPage(state)); pagingInfoToContext(state, context); } context.put("include", Boolean.valueOf(site.isPubView())); // site contact information String contactName = siteProperties .getProperty(PROP_SITE_CONTACT_NAME); String contactEmail = siteProperties .getProperty(PROP_SITE_CONTACT_EMAIL); if (contactName == null && contactEmail == null) { User u = site.getCreatedBy(); String email = u.getEmail(); if (email != null) { contactEmail = u.getEmail(); } contactName = u.getDisplayName(); } if (contactName != null) { context.put("contactName", contactName); } if (contactEmail != null) { context.put("contactEmail", contactEmail); } if (siteType != null && siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { context.put("isCourseSite", Boolean.TRUE); coursesIntoContext(state, context, site); context.put("term", siteProperties .getProperty(PROP_SITE_TERM)); } else { context.put("isCourseSite", Boolean.FALSE); } } catch (Exception e) { M_log.warn(this + " buildContextForTemplate chef_site-siteInfo-list.vm ", e); } roles = getRoles(state); context.put("roles", roles); // will have the choice to active/inactive user or not String activeInactiveUser = ServerConfigurationService.getString( "activeInactiveUser", Boolean.FALSE.toString()); if (activeInactiveUser.equalsIgnoreCase("true")) { context.put("activeInactiveUser", Boolean.TRUE); } else { context.put("activeInactiveUser", Boolean.FALSE); } context.put("groupsWithMember", site .getGroupsWithMember(UserDirectoryService.getCurrentUser() .getId())); return (String) getContext(data).get("template") + TEMPLATE[12]; case 13: /* * buildContextForTemplate chef_site-siteInfo-editInfo.vm * */ siteProperties = site.getProperties(); context.put("title", state.getAttribute(FORM_SITEINFO_TITLE)); context.put("siteTitleEditable", Boolean.valueOf(siteTitleEditable(state, site.getType()))); context.put("type", site.getType()); context.put("titleMaxLength", state.getAttribute(STATE_SITE_TITLE_MAX)); siteType = (String) state.getAttribute(STATE_SITE_TYPE); if (siteType != null && siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { context.put("isCourseSite", Boolean.TRUE); // whether to show course skin selection choices or not courseSkinSelection(context, state, site, null); setTermListForContext(context, state, true); // true->only future terms if (state.getAttribute(FORM_SITEINFO_TERM) == null) { String currentTerm = site.getProperties().getProperty( PROP_SITE_TERM); if (currentTerm != null) { state.setAttribute(FORM_SITEINFO_TERM, currentTerm); } } setSelectedTermForContext(context, state, FORM_SITEINFO_TERM); } else { context.put("isCourseSite", Boolean.FALSE); if (state.getAttribute(FORM_SITEINFO_ICON_URL) == null && StringUtil.trimToNull(site.getIconUrl()) != null) { state.setAttribute(FORM_SITEINFO_ICON_URL, site .getIconUrl()); } if (state.getAttribute(FORM_SITEINFO_ICON_URL) != null) { context.put("iconUrl", state .getAttribute(FORM_SITEINFO_ICON_URL)); } } context.put("description", state .getAttribute(FORM_SITEINFO_DESCRIPTION)); context.put("short_description", state .getAttribute(FORM_SITEINFO_SHORT_DESCRIPTION)); context.put("form_site_contact_name", state .getAttribute(FORM_SITEINFO_CONTACT_NAME)); context.put("form_site_contact_email", state .getAttribute(FORM_SITEINFO_CONTACT_EMAIL)); return (String) getContext(data).get("template") + TEMPLATE[13]; case 14: /* * buildContextForTemplate chef_site-siteInfo-editInfoConfirm.vm * */ siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO); siteProperties = site.getProperties(); siteType = (String) state.getAttribute(STATE_SITE_TYPE); if (siteType != null && siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { context.put("isCourseSite", Boolean.TRUE); context.put("disableCourseSelection", ServerConfigurationService.getString("disable.course.site.skin.selection", "false").equals("true")?Boolean.TRUE:Boolean.FALSE); context.put("siteTerm", state.getAttribute(FORM_SITEINFO_TERM)); } else { context.put("isCourseSite", Boolean.FALSE); } context.put("oTitle", site.getTitle()); context.put("title", siteInfo.title); context.put("description", siteInfo.description); context.put("oDescription", site.getDescription()); context.put("short_description", siteInfo.short_description); context.put("oShort_description", site.getShortDescription()); context.put("skin", siteInfo.iconUrl); context.put("oSkin", site.getIconUrl()); context.put("skins", state.getAttribute(STATE_ICONS)); context.put("oIcon", site.getIconUrl()); context.put("icon", siteInfo.iconUrl); context.put("include", siteInfo.include); context.put("oInclude", Boolean.valueOf(site.isPubView())); context.put("name", siteInfo.site_contact_name); context.put("oName", siteProperties.getProperty(PROP_SITE_CONTACT_NAME)); context.put("email", siteInfo.site_contact_email); context.put("oEmail", siteProperties.getProperty(PROP_SITE_CONTACT_EMAIL)); return (String) getContext(data).get("template") + TEMPLATE[14]; case 15: /* * buildContextForTemplate chef_site-addRemoveFeatureConfirm.vm * */ context.put("title", site.getTitle()); site_type = (String) state.getAttribute(STATE_SITE_TYPE); myworkspace_site = false; if (SiteService.isUserSite(site.getId())) { if (SiteService.getSiteUserId(site.getId()).equals( SessionManager.getCurrentSessionUserId())) { myworkspace_site = true; site_type = "myworkspace"; } } context.put(STATE_TOOL_REGISTRATION_LIST, state .getAttribute(STATE_TOOL_REGISTRATION_LIST)); context.put("check_home", state .getAttribute(STATE_TOOL_HOME_SELECTED)); context.put("selectedTools", orderToolIds(state, checkNullSiteType(state, site), (List) state .getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST))); context.put("oldSelectedTools", state .getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST)); context.put("oldSelectedHome", state .getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME)); context.put("continueIndex", "12"); if (state.getAttribute(STATE_TOOL_EMAIL_ADDRESS) != null) { context.put("emailId", state .getAttribute(STATE_TOOL_EMAIL_ADDRESS)); } context.put("serverName", ServerConfigurationService .getServerName()); // all info related to multiple tools multipleToolIntoContext(context, state); return (String) getContext(data).get("template") + TEMPLATE[15]; case 18: /* * buildContextForTemplate chef_siteInfo-editAccess.vm * */ List publicChangeableSiteTypes = (List) state .getAttribute(STATE_PUBLIC_CHANGEABLE_SITE_TYPES); List unJoinableSiteTypes = (List) state .getAttribute(STATE_DISABLE_JOINABLE_SITE_TYPE); if (site != null) { // editing existing site context.put("site", site); siteType = state.getAttribute(STATE_SITE_TYPE) != null ? (String) state .getAttribute(STATE_SITE_TYPE) : null; if (siteType != null && publicChangeableSiteTypes.contains(siteType)) { context.put("publicChangeable", Boolean.TRUE); } else { context.put("publicChangeable", Boolean.FALSE); } context.put("include", Boolean.valueOf(site.isPubView())); if (siteType != null && !unJoinableSiteTypes.contains(siteType)) { // site can be set as joinable context.put("disableJoinable", Boolean.FALSE); if (state.getAttribute(STATE_JOINABLE) == null) { state.setAttribute(STATE_JOINABLE, Boolean.valueOf(site .isJoinable())); } if (state.getAttribute(STATE_JOINERROLE) == null || state.getAttribute(STATE_JOINABLE) != null && ((Boolean) state.getAttribute(STATE_JOINABLE)) .booleanValue()) { state.setAttribute(STATE_JOINERROLE, site .getJoinerRole()); } if (state.getAttribute(STATE_JOINABLE) != null) { context.put("joinable", state .getAttribute(STATE_JOINABLE)); } if (state.getAttribute(STATE_JOINERROLE) != null) { context.put("joinerRole", state .getAttribute(STATE_JOINERROLE)); } } else { // site cannot be set as joinable context.put("disableJoinable", Boolean.TRUE); } context.put("roles", getRoles(state)); } else { siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO); if (siteInfo.site_type != null && publicChangeableSiteTypes .contains(siteInfo.site_type)) { context.put("publicChangeable", Boolean.TRUE); } else { context.put("publicChangeable", Boolean.FALSE); } context.put("include", Boolean.valueOf(siteInfo.getInclude())); context.put("published", Boolean.valueOf(siteInfo .getPublished())); if (siteInfo.site_type != null && !unJoinableSiteTypes.contains(siteInfo.site_type)) { // site can be set as joinable context.put("disableJoinable", Boolean.FALSE); context.put("joinable", Boolean.valueOf(siteInfo.joinable)); context.put("joinerRole", siteInfo.joinerRole); } else { // site cannot be set as joinable context.put("disableJoinable", Boolean.TRUE); } // the template site, if using one Site templateSite = (Site) state.getAttribute(STATE_TEMPLATE_SITE); // use the type's template, if defined String realmTemplate = "!site.template"; // if create based on template, use the roles from the template if (templateSite != null) { realmTemplate = SiteService.siteReference(templateSite.getId()); } else if (siteInfo.site_type != null) { realmTemplate = realmTemplate + "." + siteInfo.site_type; } try { AuthzGroup r = AuthzGroupService.getAuthzGroup(realmTemplate); context.put("roles", r.getRoles()); } catch (GroupNotDefinedException e) { try { AuthzGroup rr = AuthzGroupService.getAuthzGroup("!site.template"); context.put("roles", rr.getRoles()); } catch (GroupNotDefinedException ee) { } } // new site, go to confirmation page context.put("continue", "10"); siteType = (String) state.getAttribute(STATE_SITE_TYPE); if (siteType != null && siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { context.put("isCourseSite", Boolean.TRUE); context.put("isProjectSite", Boolean.FALSE); } else { context.put("isCourseSite", Boolean.FALSE); if (siteType.equalsIgnoreCase("project")) { context.put("isProjectSite", Boolean.TRUE); } } } return (String) getContext(data).get("template") + TEMPLATE[18]; case 26: /* * buildContextForTemplate chef_site-modifyENW.vm * */ site_type = (String) state.getAttribute(STATE_SITE_TYPE); boolean existingSite = site != null ? true : false; if (existingSite) { // revising a existing site's tool context.put("existingSite", Boolean.TRUE); context.put("continue", "15"); } else { // new site context.put("existingSite", Boolean.FALSE); context.put("continue", "18"); } context.put("function", "eventSubmit_doAdd_features"); context.put(STATE_TOOL_REGISTRATION_LIST, state .getAttribute(STATE_TOOL_REGISTRATION_LIST)); toolRegistrationSelectedList = (List) state .getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); context.put(STATE_TOOL_REGISTRATION_SELECTED_LIST, toolRegistrationSelectedList); // String toolId's // all info related to multiple tools multipleToolIntoContext(context, state); context.put("toolManager", ToolManager.getInstance()); String emailId = (String) state.getAttribute(STATE_TOOL_EMAIL_ADDRESS); if (emailId != null) { context.put("emailId", emailId); } context.put("serverName", ServerConfigurationService .getServerName()); context.put("oldSelectedTools", state .getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST)); context.put("homeToolId", getHomeToolId(state)); return (String) getContext(data).get("template") + TEMPLATE[26]; case 27: /* * buildContextForTemplate chef_site-importSites.vm * */ existingSite = site != null ? true : false; site_type = (String) state.getAttribute(STATE_SITE_TYPE); if (existingSite) { // revising a existing site's tool context.put("continue", "12"); context.put("totalSteps", "2"); context.put("step", "2"); context.put("currentSite", site); } else { // new site, go to edit access page if (fromENWModifyView(state)) { context.put("continue", "26"); } else { context.put("continue", "18"); } } context.put("existingSite", Boolean.valueOf(existingSite)); context.put(STATE_TOOL_REGISTRATION_LIST, state .getAttribute(STATE_TOOL_REGISTRATION_LIST)); context.put("selectedTools", orderToolIds(state, site_type, (List) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST))); // String toolId's context.put("importSites", state.getAttribute(STATE_IMPORT_SITES)); context.put("importSitesTools", state .getAttribute(STATE_IMPORT_SITE_TOOL)); context.put("check_home", state .getAttribute(STATE_TOOL_HOME_SELECTED)); context.put("importSupportedTools", importTools()); return (String) getContext(data).get("template") + TEMPLATE[27]; case 60: /* * buildContextForTemplate chef_site-importSitesMigrate.vm * */ existingSite = site != null ? true : false; site_type = (String) state.getAttribute(STATE_SITE_TYPE); if (existingSite) { // revising a existing site's tool context.put("continue", "12"); context.put("back", "28"); context.put("totalSteps", "2"); context.put("step", "2"); context.put("currentSite", site); } else { // new site, go to edit access page context.put("back", "3"); if (fromENWModifyView(state)) { context.put("continue", "26"); } else { context.put("continue", "18"); } } // get the tool id list List<String> toolIdList = new Vector<String>(); if (existingSite) { // list all site tools which are displayed on its own page List<SitePage> sitePages = site.getPages(); if (sitePages != null) { for (SitePage page: sitePages) { List<ToolConfiguration> pageToolsList = page.getTools(0); // we only handle one tool per page case if ( page.getLayout() == SitePage.LAYOUT_SINGLE_COL && pageToolsList.size() == 1) { toolIdList.add(pageToolsList.get(0).getToolId()); } } } } else { // during site creation toolIdList = (List<String>) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); } state.setAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST, toolIdList); // order it SortedIterator iToolIdList = new SortedIterator(getToolsAvailableForImport(state, toolIdList).iterator(),new ToolComparator()); Hashtable<String, String> toolTitleTable = new Hashtable<String, String>(); for(;iToolIdList.hasNext();) { String toolId = (String) iToolIdList.next(); try { String toolTitle = ToolManager.getTool(toolId).getTitle(); toolTitleTable.put(toolId, toolTitle); } catch (Exception e) { Log.info("chef", this + " buildContexForTemplate case 60: cannot get tool title for " + toolId + e.getMessage()); } } context.put("selectedTools", toolTitleTable); // String toolId's context.put("importSites", state.getAttribute(STATE_IMPORT_SITES)); context.put("importSitesTools", state .getAttribute(STATE_IMPORT_SITE_TOOL)); context.put("check_home", state .getAttribute(STATE_TOOL_HOME_SELECTED)); context.put("importSupportedTools", importTools()); return (String) getContext(data).get("template") + TEMPLATE[60]; case 28: /* * buildContextForTemplate chef_siteinfo-import.vm * */ context.put("currentSite", site); context.put("importSiteList", state .getAttribute(STATE_IMPORT_SITES)); context.put("sites", SiteService.getSites( org.sakaiproject.site.api.SiteService.SelectionType.UPDATE, null, null, null, SortType.TITLE_ASC, null)); return (String) getContext(data).get("template") + TEMPLATE[28]; case 58: /* * buildContextForTemplate chef_siteinfo-importSelection.vm * */ context.put("currentSite", site); context.put("importSiteList", state .getAttribute(STATE_IMPORT_SITES)); context.put("sites", SiteService.getSites( org.sakaiproject.site.api.SiteService.SelectionType.UPDATE, null, null, null, SortType.TITLE_ASC, null)); return (String) getContext(data).get("template") + TEMPLATE[58]; case 59: /* * buildContextForTemplate chef_siteinfo-importMigrate.vm * */ context.put("currentSite", site); context.put("importSiteList", state .getAttribute(STATE_IMPORT_SITES)); context.put("sites", SiteService.getSites( org.sakaiproject.site.api.SiteService.SelectionType.UPDATE, null, null, null, SortType.TITLE_ASC, null)); return (String) getContext(data).get("template") + TEMPLATE[59]; case 29: /* * buildContextForTemplate chef_siteinfo-duplicate.vm * */ context.put("siteTitle", site.getTitle()); String sType = site.getType(); if (sType != null && sType.equals((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { context.put("isCourseSite", Boolean.TRUE); context.put("currentTermId", site.getProperties().getProperty( PROP_SITE_TERM)); setTermListForContext(context, state, true); // true upcoming only } else { context.put("isCourseSite", Boolean.FALSE); } if (state.getAttribute(SITE_DUPLICATED) == null) { context.put("siteDuplicated", Boolean.FALSE); } else { context.put("siteDuplicated", Boolean.TRUE); context.put("duplicatedName", state .getAttribute(SITE_DUPLICATED_NAME)); } return (String) getContext(data).get("template") + TEMPLATE[29]; case 36: /* * buildContextForTemplate chef_site-newSiteCourse.vm */ // SAK-9824 Boolean enableCourseCreationForUser = ServerConfigurationService.getBoolean("site.enableCreateAnyUser", Boolean.FALSE); context.put("enableCourseCreationForUser", enableCourseCreationForUser); if (site != null) { context.put("site", site); context.put("siteTitle", site.getTitle()); setTermListForContext(context, state, true); // true -> upcoming only List providerCourseList = (List) state .getAttribute(SITE_PROVIDER_COURSE_LIST); coursesIntoContext(state, context, site); AcademicSession t = (AcademicSession) state .getAttribute(STATE_TERM_SELECTED); context.put("term", t); if (t != null) { String userId = UserDirectoryService.getCurrentUser().getEid(); List courses = prepareCourseAndSectionListing(userId, t .getEid(), state); if (courses != null && courses.size() > 0) { Vector notIncludedCourse = new Vector(); // remove included sites for (Iterator i = courses.iterator(); i.hasNext();) { CourseObject c = (CourseObject) i.next(); if (providerCourseList == null || providerCourseList != null && !providerCourseList.contains(c.getEid())) { notIncludedCourse.add(c); } } state.setAttribute(STATE_TERM_COURSE_LIST, notIncludedCourse); } else { state.removeAttribute(STATE_TERM_COURSE_LIST); } } // step number used in UI state.setAttribute(SITE_CREATE_CURRENT_STEP, new Integer("1")); } else { // need to include both list 'cos STATE_CM_AUTHORIZER_SECTIONS // contains sections that doens't belongs to current user and // STATE_ADD_CLASS_PROVIDER_CHOSEN contains section that does - // v2.4 daisyf if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null || state.getAttribute(STATE_CM_AUTHORIZER_SECTIONS) != null) { List<String> providerSectionList = (List<String>) state .getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN); if (providerSectionList != null) { /* List list1 = prepareSectionObject(providerSectionList, (String) state .getAttribute(STATE_CM_CURRENT_USERID)); */ context.put("selectedProviderCourse", providerSectionList); } List<SectionObject> authorizerSectionList = (List<SectionObject>) state .getAttribute(STATE_CM_AUTHORIZER_SECTIONS); if (authorizerSectionList != null) { List authorizerList = (List) state .getAttribute(STATE_CM_AUTHORIZER_LIST); //authorizerList is a list of SectionObject /* String userId = null; if (authorizerList != null) { userId = (String) authorizerList.get(0); } List list2 = prepareSectionObject( authorizerSectionList, userId); */ ArrayList list2 = new ArrayList(); for (int i=0; i<authorizerSectionList.size();i++){ SectionObject so = (SectionObject)authorizerSectionList.get(i); list2.add(so.getEid()); } context.put("selectedAuthorizerCourse", list2); } } if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) { context.put("selectedManualCourse", Boolean.TRUE); } context.put("term", (AcademicSession) state .getAttribute(STATE_TERM_SELECTED)); context.put("currentUserId", (String) state .getAttribute(STATE_CM_CURRENT_USERID)); context.put("form_additional", (String) state .getAttribute(FORM_ADDITIONAL)); context.put("authorizers", getAuthorizers(state)); } if (((String) state.getAttribute(STATE_SITE_MODE)) .equalsIgnoreCase(SITE_MODE_SITESETUP)) { context.put("backIndex", "1"); } else if (((String) state.getAttribute(STATE_SITE_MODE)) .equalsIgnoreCase(SITE_MODE_SITEINFO)) { context.put("backIndex", ""); } List ll = (List) state.getAttribute(STATE_TERM_COURSE_LIST); context.put("termCourseList", state .getAttribute(STATE_TERM_COURSE_LIST)); // added for 2.4 -daisyf context.put("campusDirectory", getCampusDirectory()); context.put("userId", (String) state .getAttribute(STATE_INSTRUCTOR_SELECTED)); /* * for measuring how long it takes to load sections java.util.Date * date = new java.util.Date(); M_log.debug("***2. finish at: * "+date); M_log.debug("***3. userId:"+(String) state * .getAttribute(STATE_INSTRUCTOR_SELECTED)); */ return (String) getContext(data).get("template") + TEMPLATE[36]; case 37: /* * buildContextForTemplate chef_site-newSiteCourseManual.vm */ if (site != null) { context.put("site", site); context.put("siteTitle", site.getTitle()); coursesIntoContext(state, context, site); } buildInstructorSectionsList(state, params, context); context.put("form_requiredFields", sectionFieldProvider .getRequiredFields()); context.put("form_additional", siteInfo.additional); context.put("form_title", siteInfo.title); context.put("form_description", siteInfo.description); context.put("officialAccountName", ServerConfigurationService .getString("officialAccountName", "")); context.put("value_uniqname", state .getAttribute(STATE_SITE_QUEST_UNIQNAME)); int number = 1; if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) { number = ((Integer) state .getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)) .intValue(); context.put("currentNumber", new Integer(number)); } context.put("currentNumber", new Integer(number)); context.put("listSize", number>0?new Integer(number - 1):0); if (state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS) != null && ((List) state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS)).size() > 0) { context.put("fieldValues", state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS)); } if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null) { List l = (List) state .getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN); context.put("selectedProviderCourse", l); context.put("size", new Integer(l.size() - 1)); } if (state.getAttribute(STATE_CM_REQUESTED_SECTIONS) != null) { List l = (List) state .getAttribute(STATE_CM_REQUESTED_SECTIONS); context.put("cmRequestedSections", l); } if (state.getAttribute(STATE_SITE_MODE).equals(SITE_MODE_SITEINFO)) { context.put("editSite", Boolean.TRUE); context.put("cmSelectedSections", state.getAttribute(STATE_CM_SELECTED_SECTIONS)); } if (site == null) { if (state.getAttribute(STATE_AUTO_ADD) != null) { context.put("autoAdd", Boolean.TRUE); } } isFutureTermSelected(state); context.put("isFutureTerm", state .getAttribute(STATE_FUTURE_TERM_SELECTED)); context.put("weeksAhead", ServerConfigurationService.getString( "roster.available.weeks.before.term.start", "0")); return (String) getContext(data).get("template") + TEMPLATE[37]; case 42: /* * buildContextForTemplate chef_site-gradtoolsConfirm.vm * */ siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO); context.put("title", siteInfo.title); context.put("description", siteInfo.description); context.put("short_description", siteInfo.short_description); toolRegistrationList = (Vector) state .getAttribute(STATE_PROJECT_TOOL_LIST); toolRegistrationSelectedList = (List) state .getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); context.put(STATE_TOOL_REGISTRATION_SELECTED_LIST, toolRegistrationSelectedList); // String toolId's context.put(STATE_TOOL_REGISTRATION_LIST, toolRegistrationList); // %%% // use // Tool context.put("check_home", state .getAttribute(STATE_TOOL_HOME_SELECTED)); context .put("emailId", state .getAttribute(STATE_TOOL_EMAIL_ADDRESS)); context.put("serverName", ServerConfigurationService .getServerName()); context.put("include", new Boolean(siteInfo.include)); return (String) getContext(data).get("template") + TEMPLATE[42]; case 43: /* * buildContextForTemplate chef_siteInfo-editClass.vm * */ bar = new MenuImpl(portlet, data, (String) state .getAttribute(STATE_ACTION)); if (SiteService.allowAddSite(null)) { bar.add(new MenuEntry(rb.getString("java.addclasses"), "doMenu_siteInfo_addClass")); } context.put("menu", bar); context.put("siteTitle", site.getTitle()); coursesIntoContext(state, context, site); return (String) getContext(data).get("template") + TEMPLATE[43]; case 44: /* * buildContextForTemplate chef_siteInfo-addCourseConfirm.vm * */ context.put("siteTitle", site.getTitle()); coursesIntoContext(state, context, site); context.put("providerAddCourses", state .getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN)); if (state.getAttribute(STATE_CM_SELECTED_SECTIONS) != null) { context.put("cmSelectedSections", state.getAttribute(STATE_CM_SELECTED_SECTIONS)); } if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) { int addNumber = ((Integer) state .getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)) .intValue() - 1; context.put("manualAddNumber", new Integer(addNumber)); context.put("requestFields", state .getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS)); context.put("backIndex", "37"); } else { context.put("backIndex", "36"); } // those manual inputs context.put("form_requiredFields", sectionFieldProvider .getRequiredFields()); context.put("fieldValues", state .getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS)); return (String) getContext(data).get("template") + TEMPLATE[44]; // htripath - import materials from classic case 45: /* * buildContextForTemplate chef_siteInfo-importMtrlMaster.vm * */ return (String) getContext(data).get("template") + TEMPLATE[45]; case 46: /* * buildContextForTemplate chef_siteInfo-importMtrlCopy.vm * */ // this is for list display in listbox context .put("allZipSites", state .getAttribute(ALL_ZIP_IMPORT_SITES)); context.put("finalZipSites", state .getAttribute(FINAL_ZIP_IMPORT_SITES)); // zip file // context.put("zipreffile",state.getAttribute(CLASSIC_ZIP_FILE_NAME)); return (String) getContext(data).get("template") + TEMPLATE[46]; case 47: /* * buildContextForTemplate chef_siteInfo-importMtrlCopyConfirm.vm * */ context.put("finalZipSites", state .getAttribute(FINAL_ZIP_IMPORT_SITES)); return (String) getContext(data).get("template") + TEMPLATE[47]; case 48: /* * buildContextForTemplate chef_siteInfo-importMtrlCopyConfirm.vm * */ context.put("finalZipSites", state .getAttribute(FINAL_ZIP_IMPORT_SITES)); return (String) getContext(data).get("template") + TEMPLATE[48]; // case 49, 50, 51 have been implemented in helper mode case 53: { /* * build context for chef_site-findCourse.vm */ AcademicSession t = (AcademicSession) state .getAttribute(STATE_TERM_SELECTED); List cmLevels = (List) state.getAttribute(STATE_CM_LEVELS), selections = (List) state .getAttribute(STATE_CM_LEVEL_SELECTIONS); if (cmLevels == null) { cmLevels = getCMLevelLabels(); } SectionObject selectedSect = (SectionObject) state .getAttribute(STATE_CM_SELECTED_SECTION); List<SectionObject> requestedSections = (List<SectionObject>) state .getAttribute(STATE_CM_REQUESTED_SECTIONS); if (courseManagementIsImplemented() && cms != null) { context.put("cmsAvailable", new Boolean(true)); } int cmLevelSize = 0; if (cms == null || !courseManagementIsImplemented() || cmLevels == null || cmLevels.size() < 1) { // TODO: redirect to manual entry: case #37 } else { cmLevelSize = cmLevels.size(); Object levelOpts[] = state.getAttribute(STATE_CM_LEVEL_OPTS) == null?new Object[cmLevelSize]:(Object[])state.getAttribute(STATE_CM_LEVEL_OPTS); int numSelections = 0; if (selections != null) { numSelections = selections.size(); // execution will fall through these statements based on number of selections already made if (numSelections == cmLevelSize - 1) { levelOpts[numSelections] = getCMSections((String) selections.get(numSelections-1)); } else if (numSelections == cmLevelSize - 2) { levelOpts[numSelections] = getCMCourseOfferings((String) selections.get(numSelections-1), t.getEid()); } else if (numSelections < cmLevelSize) { levelOpts[numSelections] = sortCmObject(cms.findCourseSets((String) cmLevels.get(numSelections==0?0:numSelections-1))); } // always set the top level levelOpts[0] = sortCmObject(cms.findCourseSets((String) cmLevels.get(0))); // clean further element inside the array for (int i = numSelections + 1; i<cmLevelSize; i++) { levelOpts[i] = null; } } context.put("cmLevelOptions", Arrays.asList(levelOpts)); state.setAttribute(STATE_CM_LEVEL_OPTS, levelOpts); } if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null) { context.put("selectedProviderCourse", state .getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN)); } if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) { int courseInd = ((Integer) state .getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)) .intValue(); context.put("manualAddNumber", new Integer(courseInd - 1)); context.put("manualAddFields", state .getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS)); } context.put("term", (AcademicSession) state .getAttribute(STATE_TERM_SELECTED)); context.put("cmLevels", cmLevels); context.put("cmLevelSelections", selections); context.put("selectedCourse", selectedSect); context.put("cmRequestedSections", requestedSections); if (state.getAttribute(STATE_SITE_MODE).equals(SITE_MODE_SITEINFO)) { context.put("editSite", Boolean.TRUE); context.put("cmSelectedSections", state.getAttribute(STATE_CM_SELECTED_SECTIONS)); } if (((String) state.getAttribute(STATE_SITE_MODE)) .equalsIgnoreCase(SITE_MODE_SITESETUP)) { if (state.getAttribute(STATE_TERM_COURSE_LIST) != null) { context.put("backIndex", "36"); } else { context.put("backIndex", "1"); } } else if (((String) state.getAttribute(STATE_SITE_MODE)).equalsIgnoreCase(SITE_MODE_SITEINFO)) { context.put("backIndex", "36"); } context.put("authzGroupService", AuthzGroupService.getInstance()); return (String) getContext(data).get("template") + TEMPLATE[53]; } case 54: /* * build context for chef_site-questions.vm */ SiteTypeQuestions siteTypeQuestions = questionService.getSiteTypeQuestions((String) state.getAttribute(STATE_SITE_TYPE)); if (siteTypeQuestions != null) { context.put("questionSet", siteTypeQuestions); context.put("userAnswers", state.getAttribute(STATE_SITE_SETUP_QUESTION_ANSWER)); } context.put("continueIndex", state.getAttribute(STATE_SITE_SETUP_QUESTION_NEXT_TEMPLATE)); return (String) getContext(data).get("template") + TEMPLATE[54]; } // should never be reached return (String) getContext(data).get("template") + TEMPLATE[0]; } /** * just in case there is still a notion of "home" for Home tool * change it to more proper home tool id * @param state * @param toolIdList * @return */ private List replaceHomeToolId(SessionState state, List toolIdList) { if (toolIdList != null && toolIdList.contains("home")) { toolIdList.remove("home"); toolIdList.add(getHomeToolId(state)); } return toolIdList; } // replaceHomeToolId /** * whether the PageOrderHelper is allowed to be shown in this site type * @param siteType * @return */ private boolean isPageOrderAllowed(String siteType) { boolean rv = true; String hidePageOrderSiteTypes = ServerConfigurationService.getString("hide.pageorder.site.types", ""); if ( hidePageOrderSiteTypes.length() != 0) { if (new ArrayList<String>(Arrays.asList(StringUtil.split(hidePageOrderSiteTypes, ","))).contains(siteType)) { rv = false; } } return rv; } private void multipleToolIntoContext(Context context, SessionState state) { // titles for multiple tool instances context.put(STATE_MULTIPLE_TOOL_ID_SET, state.getAttribute(STATE_MULTIPLE_TOOL_ID_SET )); context.put(STATE_MULTIPLE_TOOL_ID_TITLE_MAP, state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP )); context.put(STATE_MULTIPLE_TOOL_CONFIGURATION, state.getAttribute(STATE_MULTIPLE_TOOL_CONFIGURATION)); } /** * show course site skin selection or not * @param context * @param state * @param site * @param siteInfo */ private void courseSkinSelection(Context context, SessionState state, Site site, SiteInfo siteInfo) { // Display of appearance icon/url list with course site based on // "disable.course.site.skin.selection" value set with // sakai.properties file. // The setting defaults to be false. context.put("disableCourseSelection", ServerConfigurationService.getString("disable.course.site.skin.selection", "false").equals("true")?Boolean.TRUE:Boolean.FALSE); context.put("skins", state.getAttribute(STATE_ICONS)); if (state.getAttribute(FORM_SITEINFO_SKIN) != null) { context.put("selectedIcon", state.getAttribute(FORM_SITEINFO_SKIN)); } else { if (site != null && site.getIconUrl() != null) { context.put("selectedIcon", site.getIconUrl()); } else if (siteInfo != null && StringUtil.trimToNull(siteInfo.getIconUrl()) != null) { context.put("selectedIcon", siteInfo.getIconUrl()); } } } /** * Launch the Page Order Helper Tool -- for ordering, adding and customizing * pages * * @see case 12 * */ public void doPageOrderHelper(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // pass in the siteId of the site to be ordered (so it can configure // sites other then the current site) SessionManager.getCurrentToolSession().setAttribute( HELPER_ID + ".siteId", ((Site) getStateSite(state)).getId()); // launch the helper startHelper(data.getRequest(), "sakai-site-pageorder-helper"); } /** * Launch the participant Helper Tool -- for adding participant * * @see case 12 * */ public void doParticipantHelper(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // pass in the siteId of the site to be ordered (so it can configure // sites other then the current site) SessionManager.getCurrentToolSession().setAttribute( HELPER_ID + ".siteId", ((Site) getStateSite(state)).getId()); // launch the helper startHelper(data.getRequest(), "sakai-site-manage-participant-helper"); } /** * Launch the Manage Group helper Tool -- for adding, editing and deleting groups * */ public void doManageGroupHelper(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // pass in the siteId of the site to be ordered (so it can configure // sites other then the current site) SessionManager.getCurrentToolSession().setAttribute( HELPER_ID + ".siteId", ((Site) getStateSite(state)).getId()); // launch the helper startHelper(data.getRequest(), (String) state.getAttribute(STATE_GROUP_HELPER_ID));//"sakai-site-manage-group-helper"); } public boolean setHelper(String helperName, String defaultHelperId, SessionState state, String stateHelperString) { String helperId = ServerConfigurationService.getString(helperName, defaultHelperId); // if the state variable regarding the helper is not set yet, set it with the configured helper id if (state.getAttribute(stateHelperString) == null) { state.setAttribute(stateHelperString, helperId); } if (notStealthOrHiddenTool(helperId)) { return true; } return false; } // htripath: import materials from classic /** * Master import -- for import materials from a file * * @see case 45 * */ public void doAttachmentsMtrlFrmFile(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // state.setAttribute(FILE_UPLOAD_MAX_SIZE, // ServerConfigurationService.getString("content.upload.max", "1")); state.setAttribute(STATE_TEMPLATE_INDEX, "45"); } // doImportMtrlFrmFile /** * Handle File Upload request * * @see case 46 * @throws Exception */ public void doUpload_Mtrl_Frm_File(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); List allzipList = new Vector(); List finalzipList = new Vector(); List directcopyList = new Vector(); // see if the user uploaded a file FileItem fileFromUpload = null; String fileName = null; fileFromUpload = data.getParameters().getFileItem("file"); String max_file_size_mb = ServerConfigurationService.getString( "content.upload.max", "1"); int max_bytes = 1024 * 1024; try { max_bytes = Integer.parseInt(max_file_size_mb) * 1024 * 1024; } catch (Exception e) { // if unable to parse an integer from the value // in the properties file, use 1 MB as a default max_file_size_mb = "1"; max_bytes = 1024 * 1024; M_log.warn(this + ".doUpload_Mtrl_Frm_File: wrong setting of content.upload.max = " + max_file_size_mb, e); } if (fileFromUpload == null) { // "The user submitted a file to upload but it was too big!" addAlert(state, rb.getString("importFile.size") + " " + max_file_size_mb + "MB " + rb.getString("importFile.exceeded")); } else if (fileFromUpload.getFileName() == null || fileFromUpload.getFileName().length() == 0) { addAlert(state, rb.getString("importFile.choosefile")); } else { byte[] fileData = fileFromUpload.get(); if (fileData.length >= max_bytes) { addAlert(state, rb.getString("size") + " " + max_file_size_mb + "MB " + rb.getString("importFile.exceeded")); } else if (fileData.length > 0) { if (importService.isValidArchive(fileData)) { ImportDataSource importDataSource = importService .parseFromFile(fileData); Log.info("chef", "Getting import items from manifest."); List lst = importDataSource.getItemCategories(); if (lst != null && lst.size() > 0) { Iterator iter = lst.iterator(); while (iter.hasNext()) { ImportMetadata importdata = (ImportMetadata) iter .next(); // Log.info("chef","Preparing import // item '" + importdata.getId() + "'"); if ((!importdata.isMandatory()) && (importdata.getFileName() .endsWith(".xml"))) { allzipList.add(importdata); } else { directcopyList.add(importdata); } } } // set Attributes state.setAttribute(ALL_ZIP_IMPORT_SITES, allzipList); state.setAttribute(FINAL_ZIP_IMPORT_SITES, finalzipList); state.setAttribute(DIRECT_ZIP_IMPORT_SITES, directcopyList); state.setAttribute(CLASSIC_ZIP_FILE_NAME, fileName); state.setAttribute(IMPORT_DATA_SOURCE, importDataSource); state.setAttribute(STATE_TEMPLATE_INDEX, "46"); } else { // uploaded file is not a valid archive addAlert(state, rb.getString("importFile.invalidfile")); } } } } // doImportMtrlFrmFile /** * Handle addition to list request * * @param data */ public void doAdd_MtrlSite(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); List zipList = (List) state.getAttribute(ALL_ZIP_IMPORT_SITES); List fnlList = (List) state.getAttribute(FINAL_ZIP_IMPORT_SITES); List importSites = new ArrayList(Arrays.asList(params .getStrings("addImportSelected"))); for (int i = 0; i < importSites.size(); i++) { String value = (String) importSites.get(i); fnlList.add(removeItems(value, zipList)); } state.setAttribute(ALL_ZIP_IMPORT_SITES, zipList); state.setAttribute(FINAL_ZIP_IMPORT_SITES, fnlList); state.setAttribute(STATE_TEMPLATE_INDEX, "46"); } // doAdd_MtrlSite /** * Helper class for Add and remove * * @param value * @param items * @return */ public ImportMetadata removeItems(String value, List items) { ImportMetadata result = null; for (int i = 0; i < items.size(); i++) { ImportMetadata item = (ImportMetadata) items.get(i); if (value.equals(item.getId())) { result = (ImportMetadata) items.remove(i); break; } } return result; } /** * Handle the request for remove * * @param data */ public void doRemove_MtrlSite(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); List zipList = (List) state.getAttribute(ALL_ZIP_IMPORT_SITES); List fnlList = (List) state.getAttribute(FINAL_ZIP_IMPORT_SITES); List importSites = new ArrayList(Arrays.asList(params .getStrings("removeImportSelected"))); for (int i = 0; i < importSites.size(); i++) { String value = (String) importSites.get(i); zipList.add(removeItems(value, fnlList)); } state.setAttribute(ALL_ZIP_IMPORT_SITES, zipList); state.setAttribute(FINAL_ZIP_IMPORT_SITES, fnlList); state.setAttribute(STATE_TEMPLATE_INDEX, "46"); } // doAdd_MtrlSite /** * Handle the request for copy * * @param data */ public void doCopyMtrlSite(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); List fnlList = (List) state.getAttribute(FINAL_ZIP_IMPORT_SITES); state.setAttribute(FINAL_ZIP_IMPORT_SITES, fnlList); state.setAttribute(STATE_TEMPLATE_INDEX, "47"); } // doCopy_MtrlSite /** * Handle the request for Save * * @param data * @throws ImportException */ public void doSaveMtrlSite(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); String siteId = (String) state.getAttribute(STATE_SITE_INSTANCE_ID); List fnlList = (List) state.getAttribute(FINAL_ZIP_IMPORT_SITES); List directList = (List) state.getAttribute(DIRECT_ZIP_IMPORT_SITES); ImportDataSource importDataSource = (ImportDataSource) state .getAttribute(IMPORT_DATA_SOURCE); // combine the selected import items with the mandatory import items fnlList.addAll(directList); Log.info("chef", "doSaveMtrlSite() about to import " + fnlList.size() + " top level items"); Log.info("chef", "doSaveMtrlSite() the importDataSource is " + importDataSource.getClass().getName()); if (importDataSource instanceof SakaiArchive) { Log.info("chef", "doSaveMtrlSite() our data source is a Sakai format"); ((SakaiArchive) importDataSource).buildSourceFolder(fnlList); Log.info("chef", "doSaveMtrlSite() source folder is " + ((SakaiArchive) importDataSource).getSourceFolder()); ArchiveService.merge(((SakaiArchive) importDataSource) .getSourceFolder(), siteId, null); } else { importService.doImportItems(importDataSource .getItemsForCategories(fnlList), siteId); } // remove attributes state.removeAttribute(ALL_ZIP_IMPORT_SITES); state.removeAttribute(FINAL_ZIP_IMPORT_SITES); state.removeAttribute(DIRECT_ZIP_IMPORT_SITES); state.removeAttribute(CLASSIC_ZIP_FILE_NAME); state.removeAttribute(SESSION_CONTEXT_ID); state.removeAttribute(IMPORT_DATA_SOURCE); state.setAttribute(STATE_TEMPLATE_INDEX, "48"); // state.setAttribute(STATE_TEMPLATE_INDEX, "28"); } // doSave_MtrlSite public void doSaveMtrlSiteMsg(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // remove attributes state.removeAttribute(ALL_ZIP_IMPORT_SITES); state.removeAttribute(FINAL_ZIP_IMPORT_SITES); state.removeAttribute(DIRECT_ZIP_IMPORT_SITES); state.removeAttribute(CLASSIC_ZIP_FILE_NAME); state.removeAttribute(SESSION_CONTEXT_ID); state.setAttribute(STATE_TEMPLATE_INDEX, "12"); } // htripath-end /** * Handle the site search request. */ public void doSite_search(RunData data, Context context) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // read the search form field into the state object String search = StringUtil.trimToNull(data.getParameters().getString( FORM_SEARCH)); // set the flag to go to the prev page on the next list if (search == null) { state.removeAttribute(STATE_SEARCH); } else { state.setAttribute(STATE_SEARCH, search); } } // doSite_search /** * Handle a Search Clear request. */ public void doSite_search_clear(RunData data, Context context) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // clear the search state.removeAttribute(STATE_SEARCH); } // doSite_search_clear private void coursesIntoContext(SessionState state, Context context, Site site) { List providerCourseList = SiteParticipantHelper.getProviderCourseList((String) state.getAttribute(STATE_SITE_INSTANCE_ID)); if (providerCourseList != null && providerCourseList.size() > 0) { state.setAttribute(SITE_PROVIDER_COURSE_LIST, providerCourseList); String sectionTitleString = ""; for(int i = 0; i < providerCourseList.size(); i++) { String sectionId = (String) providerCourseList.get(i); try { Section s = cms.getSection(sectionId); sectionTitleString = (i>0)?sectionTitleString + "<br />" + s.getTitle():s.getTitle(); } catch (Exception e) { M_log.warn(this + ".coursesIntoContext " + e.getMessage() + " sectionId=" + sectionId, e); } } context.put("providedSectionTitle", sectionTitleString); context.put("providerCourseList", providerCourseList); } // put manual requested courses into context courseListFromStringIntoContext(state, context, site, STATE_CM_REQUESTED_SECTIONS, STATE_CM_REQUESTED_SECTIONS, "cmRequestedCourseList"); // put manual requested courses into context courseListFromStringIntoContext(state, context, site, PROP_SITE_REQUEST_COURSE, SITE_MANUAL_COURSE_LIST, "manualCourseList"); } private void courseListFromStringIntoContext(SessionState state, Context context, Site site, String site_prop_name, String state_attribute_string, String context_string) { String courseListString = StringUtil.trimToNull(site.getProperties().getProperty(site_prop_name)); if (courseListString != null) { List courseList = new Vector(); if (courseListString.indexOf("+") != -1) { courseList = new ArrayList(Arrays.asList(courseListString.split("\\+"))); } else { courseList.add(courseListString); } if (state_attribute_string.equals(STATE_CM_REQUESTED_SECTIONS)) { // need to construct the list of SectionObjects List<SectionObject> soList = new Vector(); for (int i=0; i<courseList.size();i++) { String courseEid = (String) courseList.get(i); try { Section s = cms.getSection(courseEid); if (s!=null) soList.add(new SectionObject(s)); } catch (Exception e) { M_log.warn(this + ".courseListFromStringIntoContext: cannot find section " + courseEid, e); } } if (soList.size() > 0) state.setAttribute(STATE_CM_REQUESTED_SECTIONS, soList); } else { // the list is of String objects state.setAttribute(state_attribute_string, courseList); } } context.put(context_string, state.getAttribute(state_attribute_string)); } /** * buildInstructorSectionsList Build the CourseListItem list for this * Instructor for the requested Term * */ private void buildInstructorSectionsList(SessionState state, ParameterParser params, Context context) { // Site information // The sections of the specified term having this person as Instructor context.put("providerCourseSectionList", state .getAttribute("providerCourseSectionList")); context.put("manualCourseSectionList", state .getAttribute("manualCourseSectionList")); context.put("term", (AcademicSession) state .getAttribute(STATE_TERM_SELECTED)); setTermListForContext(context, state, true); //-> future terms only context.put(STATE_TERM_COURSE_LIST, state .getAttribute(STATE_TERM_COURSE_LIST)); context.put("tlang", rb); } // buildInstructorSectionsList /** * {@inheritDoc} */ protected int sizeResources(SessionState state) { int size = 0; String search = ""; String userId = SessionManager.getCurrentSessionUserId(); // if called from the site list page if (((String) state.getAttribute(STATE_TEMPLATE_INDEX)).equals("0")) { search = StringUtil.trimToNull((String) state .getAttribute(STATE_SEARCH)); if (SecurityService.isSuperUser()) { // admin-type of user String view = (String) state.getAttribute(STATE_VIEW_SELECTED); if (view != null) { if (view.equals(rb.getString("java.allmy"))) { // search for non-user sites, using // the criteria size = SiteService .countSites( org.sakaiproject.site.api.SiteService.SelectionType.NON_USER, null, search, null); } else if (view.equals(rb.getString("java.my"))) { // search for a specific user site // for the particular user id in the // criteria - exact match only try { SiteService.getSite(SiteService .getUserSiteId(search)); size++; } catch (IdUnusedException e) { } } else if (view.equalsIgnoreCase(rb .getString("java.gradtools"))) { // search for gradtools sites size = SiteService .countSites( org.sakaiproject.site.api.SiteService.SelectionType.NON_USER, state .getAttribute(GRADTOOLS_SITE_TYPES), search, null); } else { // search for specific type of sites size = SiteService .countSites( org.sakaiproject.site.api.SiteService.SelectionType.NON_USER, view, search, null); } } } else { Site userWorkspaceSite = null; try { userWorkspaceSite = SiteService.getSite(SiteService .getUserSiteId(userId)); } catch (IdUnusedException e) { M_log.warn(this + "sizeResources, template index = 0: Cannot find user " + SessionManager.getCurrentSessionUserId() + "'s My Workspace site.", e); } String view = (String) state.getAttribute(STATE_VIEW_SELECTED); if (view != null) { if (view.equals(rb.getString("java.allmy"))) { view = null; // add my workspace if any if (userWorkspaceSite != null) { if (search != null) { if (userId.indexOf(search) != -1) { size++; } } else { size++; } } size += SiteService .countSites( org.sakaiproject.site.api.SiteService.SelectionType.ACCESS, null, search, null); } else if (view.equalsIgnoreCase(rb .getString("java.gradtools"))) { // search for gradtools sites size += SiteService .countSites( org.sakaiproject.site.api.SiteService.SelectionType.ACCESS, state .getAttribute(GRADTOOLS_SITE_TYPES), search, null); } else { // search for specific type of sites size += SiteService .countSites( org.sakaiproject.site.api.SiteService.SelectionType.ACCESS, view, search, null); } } } } // for SiteInfo list page else if (state.getAttribute(STATE_TEMPLATE_INDEX).toString().equals( "12")) { Collection l = (Collection) state.getAttribute(STATE_PARTICIPANT_LIST); size = (l != null) ? l.size() : 0; } return size; } // sizeResources /** * {@inheritDoc} */ protected List readResourcesPage(SessionState state, int first, int last) { String search = StringUtil.trimToNull((String) state .getAttribute(STATE_SEARCH)); // if called from the site list page if (((String) state.getAttribute(STATE_TEMPLATE_INDEX)).equals("0")) { // get sort type SortType sortType = null; String sortBy = (String) state.getAttribute(SORTED_BY); boolean sortAsc = (new Boolean((String) state .getAttribute(SORTED_ASC))).booleanValue(); if (sortBy.equals(SortType.TITLE_ASC.toString())) { sortType = sortAsc ? SortType.TITLE_ASC : SortType.TITLE_DESC; } else if (sortBy.equals(SortType.TYPE_ASC.toString())) { sortType = sortAsc ? SortType.TYPE_ASC : SortType.TYPE_DESC; } else if (sortBy.equals(SortType.CREATED_BY_ASC.toString())) { sortType = sortAsc ? SortType.CREATED_BY_ASC : SortType.CREATED_BY_DESC; } else if (sortBy.equals(SortType.CREATED_ON_ASC.toString())) { sortType = sortAsc ? SortType.CREATED_ON_ASC : SortType.CREATED_ON_DESC; } else if (sortBy.equals(SortType.PUBLISHED_ASC.toString())) { sortType = sortAsc ? SortType.PUBLISHED_ASC : SortType.PUBLISHED_DESC; } if (SecurityService.isSuperUser()) { // admin-type of user String view = (String) state.getAttribute(STATE_VIEW_SELECTED); if (view != null) { if (view.equals(rb.getString("java.allmy"))) { // search for non-user sites, using the // criteria return SiteService .getSites( org.sakaiproject.site.api.SiteService.SelectionType.NON_USER, null, search, null, sortType, new PagingPosition(first, last)); } else if (view.equalsIgnoreCase(rb.getString("java.my"))) { // search for a specific user site for // the particular user id in the // criteria - exact match only List rv = new Vector(); try { Site userSite = SiteService.getSite(SiteService .getUserSiteId(search)); rv.add(userSite); } catch (IdUnusedException e) { } return rv; } else if (view.equalsIgnoreCase(rb .getString("java.gradtools"))) { // search for gradtools sites return SiteService .getSites( org.sakaiproject.site.api.SiteService.SelectionType.NON_USER, state .getAttribute(GRADTOOLS_SITE_TYPES), search, null, sortType, new PagingPosition(first, last)); } else { // search for a specific site return SiteService .getSites( org.sakaiproject.site.api.SiteService.SelectionType.ANY, view, search, null, sortType, new PagingPosition(first, last)); } } } else { List rv = new Vector(); Site userWorkspaceSite = null; String userId = SessionManager.getCurrentSessionUserId(); try { userWorkspaceSite = SiteService.getSite(SiteService .getUserSiteId(userId)); } catch (IdUnusedException e) { M_log.warn(this + "readResourcesPage template index = 0 :Cannot find user " + SessionManager.getCurrentSessionUserId() + "'s My Workspace site.", e); } String view = (String) state.getAttribute(STATE_VIEW_SELECTED); if (view != null) { if (view.equals(rb.getString("java.allmy"))) { view = null; // add my workspace if any if (userWorkspaceSite != null) { if (search != null) { if (userId.indexOf(search) != -1) { rv.add(userWorkspaceSite); } } else { rv.add(userWorkspaceSite); } } rv .addAll(SiteService .getSites( org.sakaiproject.site.api.SiteService.SelectionType.ACCESS, null, search, null, sortType, new PagingPosition(first, last))); } else if (view.equalsIgnoreCase(rb .getString("java.gradtools"))) { // search for a specific user site for // the particular user id in the // criteria - exact match only rv .addAll(SiteService .getSites( org.sakaiproject.site.api.SiteService.SelectionType.ACCESS, state .getAttribute(GRADTOOLS_SITE_TYPES), search, null, sortType, new PagingPosition(first, last))); } else { rv .addAll(SiteService .getSites( org.sakaiproject.site.api.SiteService.SelectionType.ACCESS, view, search, null, sortType, new PagingPosition(first, last))); } } return rv; } } // if in Site Info list view else if (state.getAttribute(STATE_TEMPLATE_INDEX).toString().equals( "12")) { List participants = (state.getAttribute(STATE_PARTICIPANT_LIST) != null) ? collectionToList((Collection) state.getAttribute(STATE_PARTICIPANT_LIST)): new Vector(); String sortedBy = (String) state.getAttribute(SORTED_BY); String sortedAsc = (String) state.getAttribute(SORTED_ASC); Iterator sortedParticipants = null; if (sortedBy != null) { sortedParticipants = new SortedIterator(participants .iterator(), new SiteComparator(sortedBy, sortedAsc)); participants.clear(); while (sortedParticipants.hasNext()) { participants.add(sortedParticipants.next()); } } PagingPosition page = new PagingPosition(first, last); page.validate(participants.size()); participants = participants.subList(page.getFirst() - 1, page.getLast()); return participants; } return null; } // readResourcesPage /** * get the selected tool ids from import sites */ private boolean select_import_tools(ParameterParser params, SessionState state) { // has the user selected any tool for importing? boolean anyToolSelected = false; Hashtable importTools = new Hashtable(); // the tools for current site List selectedTools = (List) state .getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); // String // toolId's for (int i = 0; i < selectedTools.size(); i++) { // any tools chosen from import sites? String toolId = (String) selectedTools.get(i); if (params.getStrings(toolId) != null) { importTools.put(toolId, new ArrayList(Arrays.asList(params .getStrings(toolId)))); if (!anyToolSelected) { anyToolSelected = true; } } } state.setAttribute(STATE_IMPORT_SITE_TOOL, importTools); return anyToolSelected; } // select_import_tools /** * Is it from the ENW edit page? * * @return ture if the process went through the ENW page; false, otherwise */ private boolean fromENWModifyView(SessionState state) { boolean fromENW = false; List oTools = (List) state .getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST); List toolList = (List) state .getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); for (int i = 0; i < toolList.size() && !fromENW; i++) { String toolId = (String) toolList.get(i); if (toolId.equals("sakai.mailbox") || isMultipleInstancesAllowed(findOriginalToolId(state, toolId))) { if (oTools == null) { // if during site creation proces fromENW = true; } else if (!oTools.contains(toolId)) { // if user is adding either EmailArchive tool, News tool or // Web Content tool, go to the Customize page for the tool fromENW = true; } } } return fromENW; } /** * doNew_site is called when the Site list tool bar New... button is clicked * */ public void doNew_site(RunData data) throws Exception { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // start clean cleanState(state); List siteTypes = (List) state.getAttribute(STATE_SITE_TYPES); if (siteTypes != null) { state.setAttribute(STATE_TEMPLATE_INDEX, "1"); } } // doNew_site /** * doMenu_site_delete is called when the Site list tool bar Delete button is * clicked * */ public void doMenu_site_delete(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); if (params.getStrings("selectedMembers") == null) { addAlert(state, rb.getString("java.nosites")); state.setAttribute(STATE_TEMPLATE_INDEX, "0"); return; } String[] removals = (String[]) params.getStrings("selectedMembers"); state.setAttribute(STATE_SITE_REMOVALS, removals); // present confirm delete template state.setAttribute(STATE_TEMPLATE_INDEX, "8"); } // doMenu_site_delete public void doSite_delete_confirmed(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); if (params.getStrings("selectedMembers") == null) { M_log .warn("SiteAction.doSite_delete_confirmed selectedMembers null"); state.setAttribute(STATE_TEMPLATE_INDEX, "0"); // return to the // site list return; } List chosenList = new ArrayList(Arrays.asList(params .getStrings("selectedMembers"))); // Site id's of checked // sites if (!chosenList.isEmpty()) { for (ListIterator i = chosenList.listIterator(); i.hasNext();) { String id = (String) i.next(); String site_title = NULL_STRING; try { site_title = SiteService.getSite(id).getTitle(); } catch (IdUnusedException e) { M_log.warn(this + ".doSite_delete_confirmed - IdUnusedException " + id, e); addAlert(state, rb.getString("java.sitewith") + " " + id + " " + rb.getString("java.couldnt") + " "); } if (SiteService.allowRemoveSite(id)) { try { Site site = SiteService.getSite(id); site_title = site.getTitle(); SiteService.removeSite(site); } catch (IdUnusedException e) { M_log.warn(this +".doSite_delete_confirmed - IdUnusedException " + id, e); addAlert(state, rb.getString("java.sitewith") + " " + site_title + "(" + id + ") " + rb.getString("java.couldnt") + " "); } catch (PermissionException e) { M_log.warn(this + ".doSite_delete_confirmed - PermissionException, site " + site_title + "(" + id + ").", e); addAlert(state, site_title + " " + rb.getString("java.dontperm") + " "); } } else { M_log.warn(this + ".doSite_delete_confirmed - allowRemoveSite failed for site "+ id); addAlert(state, site_title + " " + rb.getString("java.dontperm") + " "); } } } state.setAttribute(STATE_TEMPLATE_INDEX, "0"); // return to the site // list // TODO: hard coding this frame id is fragile, portal dependent, and // needs to be fixed -ggolden // schedulePeerFrameRefresh("sitenav"); scheduleTopRefresh(); } // doSite_delete_confirmed /** * get the Site object based on SessionState attribute values * * @return Site object related to current state; null if no such Site object * could be found */ protected Site getStateSite(SessionState state) { Site site = null; if (state.getAttribute(STATE_SITE_INSTANCE_ID) != null) { try { site = SiteService.getSite((String) state .getAttribute(STATE_SITE_INSTANCE_ID)); } catch (Exception ignore) { } } return site; } // getStateSite /** * do called when "eventSubmit_do" is in the request parameters to c is * called from site list menu entry Revise... to get a locked site as * editable and to go to the correct template to begin DB version of writes * changes to disk at site commit whereas XML version writes at server * shutdown */ public void doGet_site(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); // check form filled out correctly if (params.getStrings("selectedMembers") == null) { addAlert(state, rb.getString("java.nosites")); state.setAttribute(STATE_TEMPLATE_INDEX, "0"); return; } List chosenList = new ArrayList(Arrays.asList(params .getStrings("selectedMembers"))); // Site id's of checked // sites String siteId = ""; if (!chosenList.isEmpty()) { if (chosenList.size() != 1) { addAlert(state, rb.getString("java.please")); state.setAttribute(STATE_TEMPLATE_INDEX, "0"); return; } siteId = (String) chosenList.get(0); getReviseSite(state, siteId); state.setAttribute(SORTED_BY, SiteConstants.SORTED_BY_PARTICIPANT_NAME); state.setAttribute(SORTED_ASC, Boolean.TRUE.toString()); } // reset the paging info resetPaging(state); if (((String) state.getAttribute(STATE_SITE_MODE)) .equalsIgnoreCase(SITE_MODE_SITESETUP)) { state.setAttribute(STATE_PAGESIZE_SITESETUP, state .getAttribute(STATE_PAGESIZE)); } Hashtable h = (Hashtable) state.getAttribute(STATE_PAGESIZE_SITEINFO); if (!h.containsKey(siteId)) { // when first entered Site Info, set the participant list size to // 200 as default state.setAttribute(STATE_PAGESIZE, new Integer(200)); // update h.put(siteId, new Integer(200)); state.setAttribute(STATE_PAGESIZE_SITEINFO, h); } else { // restore the page size in site info tool state.setAttribute(STATE_PAGESIZE, h.get(siteId)); } } // doGet_site /** * do called when "eventSubmit_do" is in the request parameters to c */ public void doMenu_site_reuse(RunData data) throws Exception { // called from chef_site-list.vm after a site has been selected from // list // create a new Site object based on selected Site object and put in // state // SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(STATE_TEMPLATE_INDEX, "1"); } // doMenu_site_reuse /** * do called when "eventSubmit_do" is in the request parameters to c */ public void doMenu_site_revise(RunData data) throws Exception { // called from chef_site-list.vm after a site has been selected from // list // get site as Site object, check SiteCreationStatus and SiteType of // site, put in state, and set STATE_TEMPLATE_INDEX correctly // set mode to state_mode_site_type SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(STATE_TEMPLATE_INDEX, "1"); } // doMenu_site_revise /** * doView_sites is called when "eventSubmit_doView_sites" is in the request * parameters */ public void doView_sites(RunData data) throws Exception { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); state.setAttribute(STATE_VIEW_SELECTED, params.getString("view")); state.setAttribute(STATE_TEMPLATE_INDEX, "0"); resetPaging(state); } // doView_sites /** * do called when "eventSubmit_do" is in the request parameters to c */ public void doView(RunData data) throws Exception { // called from chef_site-list.vm with a select option to build query of // sites // // SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(STATE_TEMPLATE_INDEX, "1"); } // doView /** * do called when "eventSubmit_do" is in the request parameters to c */ public void doSite_type(RunData data) { /* * for measuring how long it takes to load sections java.util.Date date = * new java.util.Date(); M_log.debug("***1. start preparing * section:"+date); */ SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); int index = Integer.valueOf(params.getString("templateIndex")) .intValue(); actionForTemplate("continue", index, params, state); String type = StringUtil.trimToNull(params.getString("itemType")); int totalSteps = 0; if (type == null) { addAlert(state, rb.getString("java.select") + " "); } else { state.setAttribute(STATE_TYPE_SELECTED, type); setNewSiteType(state, type); if (type.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { User user = UserDirectoryService.getCurrentUser(); String currentUserId = user.getEid(); String userId = params.getString("userId"); if (userId == null || "".equals(userId)) { userId = currentUserId; } else { // implies we are trying to pick sections owned by other // users. Currently "select section by user" page only // take one user per sitte request - daisy's note 1 ArrayList<String> list = new ArrayList(); list.add(userId); state.setAttribute(STATE_CM_AUTHORIZER_LIST, list); } state.setAttribute(STATE_INSTRUCTOR_SELECTED, userId); String academicSessionEid = params.getString("selectTerm"); AcademicSession t = cms.getAcademicSession(academicSessionEid); state.setAttribute(STATE_TERM_SELECTED, t); if (t != null) { List sections = prepareCourseAndSectionListing(userId, t .getEid(), state); isFutureTermSelected(state); if (sections != null && sections.size() > 0) { state.setAttribute(STATE_TERM_COURSE_LIST, sections); state.setAttribute(STATE_TEMPLATE_INDEX, "36"); state.setAttribute(STATE_AUTO_ADD, Boolean.TRUE); } else { state.removeAttribute(STATE_TERM_COURSE_LIST); Boolean skipCourseSectionSelection = ServerConfigurationService.getBoolean("wsetup.skipCourseSectionSelection", Boolean.FALSE); if (!skipCourseSectionSelection.booleanValue() && courseManagementIsImplemented()) { state.setAttribute(STATE_TEMPLATE_INDEX, "53"); } else { state.setAttribute(STATE_TEMPLATE_INDEX, "37"); } } } else { // not course type state.setAttribute(STATE_TEMPLATE_INDEX, "37"); totalSteps = 5; } } else if (type.equals("project")) { totalSteps = 4; state.setAttribute(STATE_TEMPLATE_INDEX, "2"); } else if (type.equals(SITE_TYPE_GRADTOOLS_STUDENT)) { // if a GradTools site use pre-defined site info and exclude // from public listing SiteInfo siteInfo = new SiteInfo(); if (state.getAttribute(STATE_SITE_INFO) != null) { siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO); } User currentUser = UserDirectoryService.getCurrentUser(); siteInfo.title = rb.getString("java.grad") + " - " + currentUser.getId(); siteInfo.description = rb.getString("java.gradsite") + " " + currentUser.getDisplayName(); siteInfo.short_description = rb.getString("java.grad") + " - " + currentUser.getId(); siteInfo.include = false; state.setAttribute(STATE_SITE_INFO, siteInfo); // skip directly to confirm creation of site state.setAttribute(STATE_TEMPLATE_INDEX, "42"); } else { state.setAttribute(STATE_TEMPLATE_INDEX, "2"); } // get the user selected template getSelectedTemplate(state, params, type); } if (state.getAttribute(SITE_CREATE_TOTAL_STEPS) == null) { state.setAttribute(SITE_CREATE_TOTAL_STEPS, new Integer(totalSteps)); } if (state.getAttribute(SITE_CREATE_CURRENT_STEP) == null) { state.setAttribute(SITE_CREATE_CURRENT_STEP, new Integer(1)); } redirectToQuestionVM(state, type); } // doSite_type /** * see whether user selected any template * @param state * @param params * @param type */ private void getSelectedTemplate(SessionState state, ParameterParser params, String type) { String templateSiteId = params.getString("selectTemplate" + type); if (templateSiteId != null) { Site templateSite = null; try { templateSite = SiteService.getSite(templateSiteId); // save the template site in state state.setAttribute(STATE_TEMPLATE_SITE, templateSite); // the new site type is based on the template site setNewSiteType(state, templateSite.getType()); }catch (Exception e) { // should never happened, as the list of templates are generated // from existing sites M_log.warn(this + ".doSite_type" + e.getClass().getName(), e); } // grab site info from template SiteInfo siteInfo = new SiteInfo(); if (state.getAttribute(STATE_SITE_INFO) != null) { siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO); } // copy information from template site siteInfo.description = templateSite.getDescription(); siteInfo.short_description = templateSite.getShortDescription(); siteInfo.iconUrl = templateSite.getIconUrl(); siteInfo.infoUrl = templateSite.getInfoUrl(); siteInfo.joinable = templateSite.isJoinable(); siteInfo.joinerRole = templateSite.getJoinerRole(); //siteInfo.include = false; List<String> toolIdsSelected = new Vector<String>(); List pageList = templateSite.getPages(); if (!((pageList == null) || (pageList.size() == 0))) { for (ListIterator i = pageList.listIterator(); i.hasNext();) { SitePage page = (SitePage) i.next(); List pageToolList = page.getTools(); if (pageToolList != null && pageToolList.size() > 0) { Tool tConfig = ((ToolConfiguration) pageToolList.get(0)).getTool(); if (tConfig != null) { toolIdsSelected.add(tConfig.getId()); } } } } state.setAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST, toolIdsSelected); state.setAttribute(STATE_SITE_INFO, siteInfo); } } /** * Depend on the setup question setting, redirect the site setup flow * @param state * @param type */ private void redirectToQuestionVM(SessionState state, String type) { // SAK-12912: check whether there is any setup question defined SiteTypeQuestions siteTypeQuestions = questionService.getSiteTypeQuestions(type); if (siteTypeQuestions != null) { List questionList = siteTypeQuestions.getQuestions(); if (questionList != null && !questionList.isEmpty()) { // there is at least one question defined for this type if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_SITE_SETUP_QUESTION_NEXT_TEMPLATE, state.getAttribute(STATE_TEMPLATE_INDEX)); state.setAttribute(STATE_TEMPLATE_INDEX, "54"); } } } } /** * Determine whether the selected term is considered of "future term" * @param state * @param t */ private void isFutureTermSelected(SessionState state) { AcademicSession t = (AcademicSession) state.getAttribute(STATE_TERM_SELECTED); int weeks = 0; Calendar c = (Calendar) Calendar.getInstance().clone(); try { weeks = Integer .parseInt(ServerConfigurationService .getString( "roster.available.weeks.before.term.start", "0")); c.add(Calendar.DATE, weeks * 7); } catch (Exception ignore) { } if (t.getStartDate() != null && c.getTimeInMillis() < t.getStartDate().getTime()) { // if a future term is selected state.setAttribute(STATE_FUTURE_TERM_SELECTED, Boolean.TRUE); } else { state.setAttribute(STATE_FUTURE_TERM_SELECTED, Boolean.FALSE); } } public void doChange_user(RunData data) { doSite_type(data); } // doChange_user /** * */ private void removeSection(SessionState state, ParameterParser params) { // v2.4 - added by daisyf // RemoveSection - remove any selected course from a list of // provider courses // check if any section need to be removed removeAnyFlagedSection(state, params); SiteInfo siteInfo = new SiteInfo(); if (state.getAttribute(STATE_SITE_INFO) != null) { siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO); } List providerChosenList = (List) state .getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN); collectNewSiteInfo(siteInfo, state, params, providerChosenList); // next step //state.setAttribute(SITE_CREATE_CURRENT_STEP, new Integer(2)); } /** * dispatch to different functions based on the option value in the * parameter */ public void doManual_add_course(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String option = params.getString("option"); if (option.equalsIgnoreCase("change") || option.equalsIgnoreCase("add")) { readCourseSectionInfo(state, params); String uniqname = StringUtil.trimToNull(params .getString("uniqname")); state.setAttribute(STATE_SITE_QUEST_UNIQNAME, uniqname); updateSiteInfo(params, state); if (option.equalsIgnoreCase("add")) { if (state.getAttribute(STATE_FUTURE_TERM_SELECTED) != null && !((Boolean) state .getAttribute(STATE_FUTURE_TERM_SELECTED)) .booleanValue()) { // if a future term is selected, do not check authorization // uniqname if (uniqname == null) { addAlert(state, rb.getString("java.author") + " " + ServerConfigurationService .getString("officialAccountName") + ". "); } else { // in case of multiple instructors List instructors = new ArrayList(Arrays.asList(uniqname.split(","))); for (Iterator iInstructors = instructors.iterator(); iInstructors.hasNext();) { String eid = StringUtil.trimToZero((String) iInstructors.next()); try { UserDirectoryService.getUserByEid(eid); } catch (UserNotDefinedException e) { addAlert( state, rb.getString("java.validAuthor1") + " " + ServerConfigurationService .getString("officialAccountName") + " " + rb.getString("java.validAuthor2")); M_log.warn(this + ".doManual_add_course: cannot find user with eid=" + eid, e); } } } } if (state.getAttribute(STATE_MESSAGE) == null) { if (getStateSite(state) == null) { state.setAttribute(STATE_TEMPLATE_INDEX, "2"); } else { state.setAttribute(STATE_TEMPLATE_INDEX, "44"); } } updateCurrentStep(state, true); } } else if (option.equalsIgnoreCase("back")) { doBack(data); if (state.getAttribute(STATE_MESSAGE) == null) { updateCurrentStep(state, false); } } else if (option.equalsIgnoreCase("cancel")) { if (getStateSite(state) == null) { doCancel_create(data); } else { doCancel(data); } } else if (option.equalsIgnoreCase("removeSection")) { // remove selected section removeSection(state, params); } } // doManual_add_course /** * dispatch to different functions based on the option value in the * parameter */ public void doSite_information(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String option = params.getString("option"); if (option.equalsIgnoreCase("continue")) { doContinue(data); // if create based on template, skip the feature selection Site templateSite = (Site) state.getAttribute(STATE_TEMPLATE_SITE); if (templateSite != null) { state.setAttribute(STATE_TEMPLATE_INDEX, "18"); } } else if (option.equalsIgnoreCase("back")) { doBack(data); } else if (option.equalsIgnoreCase("cancel")) { if (getStateSite(state) == null) { doCancel_create(data); } else { doCancel(data); } } else if (option.equalsIgnoreCase("removeSection")) { // remove selected section removeSection(state, params); } } // doSite_information /** * read the input information of subject, course and section in the manual * site creation page */ private void readCourseSectionInfo(SessionState state, ParameterParser params) { String option = params.getString("option"); int oldNumber = 1; if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) { oldNumber = ((Integer) state .getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)).intValue(); } // read the user input int validInputSites = 0; boolean validInput = true; List multiCourseInputs = new Vector(); for (int i = 0; i < oldNumber; i++) { List requiredFields = sectionFieldProvider.getRequiredFields(); List aCourseInputs = new Vector(); int emptyInputNum = 0; // iterate through all required fields for (int k = 0; k < requiredFields.size(); k++) { SectionField sectionField = (SectionField) requiredFields .get(k); String fieldLabel = sectionField.getLabelKey(); String fieldInput = StringUtil.trimToZero(params .getString(fieldLabel + i)); sectionField.setValue(fieldInput); aCourseInputs.add(sectionField); if (fieldInput.length() == 0) { // is this an empty String input? emptyInputNum++; } } // is any input invalid? if (emptyInputNum == 0) { // valid if all the inputs are not empty multiCourseInputs.add(validInputSites++, aCourseInputs); } else if (emptyInputNum == requiredFields.size()) { // ignore if all inputs are empty if (option.equalsIgnoreCase("change")) { multiCourseInputs.add(validInputSites++, aCourseInputs); } } else { // input invalid validInput = false; } } // how many more course/section to include in the site? if (option.equalsIgnoreCase("change")) { if (params.getString("number") != null) { int newNumber = Integer.parseInt(params.getString("number")); state.setAttribute(STATE_MANUAL_ADD_COURSE_NUMBER, new Integer(oldNumber + newNumber)); List requiredFields = sectionFieldProvider.getRequiredFields(); for (int j = 0; j < newNumber; j++) { // add a new course input List aCourseInputs = new Vector(); // iterate through all required fields for (int m = 0; m < requiredFields.size(); m++) { aCourseInputs = sectionFieldProvider.getRequiredFields(); } multiCourseInputs.add(aCourseInputs); } } } state.setAttribute(STATE_MANUAL_ADD_COURSE_FIELDS, multiCourseInputs); if (!option.equalsIgnoreCase("change")) { if (!validInput || validInputSites == 0) { // not valid input addAlert(state, rb.getString("java.miss")); } // valid input, adjust the add course number state.setAttribute(STATE_MANUAL_ADD_COURSE_NUMBER, new Integer( validInputSites)); } // set state attributes state.setAttribute(FORM_ADDITIONAL, StringUtil.trimToZero(params .getString("additional"))); SiteInfo siteInfo = new SiteInfo(); if (state.getAttribute(STATE_SITE_INFO) != null) { siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO); } List providerCourseList = (List) state .getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN); // store the manually requested sections in one site property if ((providerCourseList == null || providerCourseList.size() == 0) && multiCourseInputs.size() > 0) { AcademicSession t = (AcademicSession) state .getAttribute(STATE_TERM_SELECTED); String sectionEid = sectionFieldProvider.getSectionEid(t.getEid(), (List) multiCourseInputs.get(0)); // default title String title = sectionFieldProvider.getSectionTitle(t.getEid(), (List) multiCourseInputs.get(0)); try { title = cms.getSection(sectionEid).getTitle(); } catch (IdNotFoundException e) { // cannot find section, use the default title M_log.warn(this + ":readCourseSectionInfo: cannot find section with eid=" + sectionEid); } siteInfo.title = title; } state.setAttribute(STATE_SITE_INFO, siteInfo); } // readCourseSectionInfo /** * * @param state * @param type */ private void setNewSiteType(SessionState state, String type) { state.setAttribute(STATE_SITE_TYPE, type); // start out with fresh site information SiteInfo siteInfo = new SiteInfo(); siteInfo.site_type = type; siteInfo.published = true; state.setAttribute(STATE_SITE_INFO, siteInfo); // set tool registration list setToolRegistrationList(state, type); } /** * Set the state variables for tool registration list basd on site type * @param state * @param type */ private void setToolRegistrationList(SessionState state, String type) { state.removeAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST); state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME); state.removeAttribute(STATE_MULTIPLE_TOOL_ID_SET); // get the tool id set which allows for multiple instances Set multipleToolIdSet = new HashSet(); Hashtable multipleToolConfiguration = new Hashtable<String, Hashtable<String, String>>(); // get registered tools list Set categories = new HashSet(); categories.add(type); Set toolRegistrations = ToolManager.findTools(categories, null); if ((toolRegistrations == null || toolRegistrations.size() == 0) && state.getAttribute(STATE_DEFAULT_SITE_TYPE) != null) { // use default site type and try getting tools again type = (String) state.getAttribute(STATE_DEFAULT_SITE_TYPE); categories.clear(); categories.add(type); toolRegistrations = ToolManager.findTools(categories, null); } List tools = new Vector(); SortedIterator i = new SortedIterator(toolRegistrations.iterator(), new ToolComparator()); for (; i.hasNext();) { // form a new Tool Tool tr = (Tool) i.next(); MyTool newTool = new MyTool(); newTool.title = tr.getTitle(); newTool.id = tr.getId(); newTool.description = tr.getDescription(); tools.add(newTool); String originalToolId = findOriginalToolId(state, tr.getId()); if (isMultipleInstancesAllowed(originalToolId)) { // of a tool which allows multiple instances multipleToolIdSet.add(tr.getId()); // get the configuration for multiple instance Hashtable<String, String> toolConfigurations = getMultiToolConfiguration(originalToolId); multipleToolConfiguration.put(tr.getId(), toolConfigurations); } } state.setAttribute(STATE_TOOL_REGISTRATION_LIST, tools); state.setAttribute(STATE_MULTIPLE_TOOL_ID_SET, multipleToolIdSet); state.setAttribute(STATE_MULTIPLE_TOOL_CONFIGURATION, multipleToolConfiguration); } /** * Set the field on which to sort the list of students * */ public void doSort_roster(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // get the field on which to sort the student list ParameterParser params = data.getParameters(); String criterion = params.getString("criterion"); // current sorting sequence String asc = ""; if (!criterion.equals(state.getAttribute(SORTED_BY))) { state.setAttribute(SORTED_BY, criterion); asc = Boolean.TRUE.toString(); state.setAttribute(SORTED_ASC, asc); } else { // current sorting sequence asc = (String) state.getAttribute(SORTED_ASC); // toggle between the ascending and descending sequence if (asc.equals(Boolean.TRUE.toString())) { asc = Boolean.FALSE.toString(); } else { asc = Boolean.TRUE.toString(); } state.setAttribute(SORTED_ASC, asc); } } // doSort_roster /** * Set the field on which to sort the list of sites * */ public void doSort_sites(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // call this method at the start of a sort for proper paging resetPaging(state); // get the field on which to sort the site list ParameterParser params = data.getParameters(); String criterion = params.getString("criterion"); // current sorting sequence String asc = ""; if (!criterion.equals(state.getAttribute(SORTED_BY))) { state.setAttribute(SORTED_BY, criterion); asc = Boolean.TRUE.toString(); state.setAttribute(SORTED_ASC, asc); } else { // current sorting sequence asc = (String) state.getAttribute(SORTED_ASC); // toggle between the ascending and descending sequence if (asc.equals(Boolean.TRUE.toString())) { asc = Boolean.FALSE.toString(); } else { asc = Boolean.TRUE.toString(); } state.setAttribute(SORTED_ASC, asc); } state.setAttribute(SORTED_BY, criterion); } // doSort_sites /** * doContinue is called when "eventSubmit_doContinue" is in the request * parameters */ public void doContinue(RunData data) { // Put current form data in state and continue to the next template, // make any permanent changes SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); int index = Integer.valueOf(params.getString("templateIndex")) .intValue(); // Let actionForTemplate know to make any permanent changes before // continuing to the next template String direction = "continue"; String option = params.getString("option"); actionForTemplate(direction, index, params, state); if (state.getAttribute(STATE_MESSAGE) == null) { if (index == 36 && ("add").equals(option)) { // this is the Add extra Roster(s) case after a site is created state.setAttribute(STATE_TEMPLATE_INDEX, "44"); } else if (params.getString("continue") != null) { state.setAttribute(STATE_TEMPLATE_INDEX, params .getString("continue")); } } }// doContinue /** * handle with continue add new course site options * */ public void doContinue_new_course(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String option = data.getParameters().getString("option"); if (option.equals("continue")) { doContinue(data); } else if (option.equals("cancel")) { doCancel_create(data); } else if (option.equals("back")) { doBack(data); } else if (option.equals("cancel")) { doCancel_create(data); } else if (option.equalsIgnoreCase("change")) { // change term String termId = params.getString("selectTerm"); AcademicSession t = cms.getAcademicSession(termId); state.setAttribute(STATE_TERM_SELECTED, t); isFutureTermSelected(state); } else if (option.equalsIgnoreCase("cancel_edit")) { // cancel doCancel(data); } else if (option.equalsIgnoreCase("add")) { isFutureTermSelected(state); // continue doContinue(data); } } // doContinue_new_course /** * doBack is called when "eventSubmit_doBack" is in the request parameters * Pass parameter to actionForTemplate to request action for backward * direction */ public void doBack(RunData data) { // Put current form data in state and return to the previous template SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); int currentIndex = Integer.parseInt((String) state .getAttribute(STATE_TEMPLATE_INDEX)); state.setAttribute(STATE_TEMPLATE_INDEX, params.getString("back")); // Let actionForTemplate know not to make any permanent changes before // continuing to the next template String direction = "back"; actionForTemplate(direction, currentIndex, params, state); // remove the last template index from the list removeLastIndexInStateVisitedTemplates(state); }// doBack /** * doFinish is called when a site has enough information to be saved as an * unpublished site */ public void doFinish(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_TEMPLATE_INDEX, params .getString("continue")); int index = Integer.valueOf(params.getString("templateIndex")) .intValue(); actionForTemplate("continue", index, params, state); addNewSite(params, state); Site site = getStateSite(state); Site templateSite = (Site) state.getAttribute(STATE_TEMPLATE_SITE); if (templateSite == null) { // normal site creation: add the features. saveFeatures(params, state, site); } else { // create based on template: skip add features, and copying all the contents from the tools in template site importToolContent(site.getId(), templateSite.getId(), site, true); } // for course sites String siteType = (String) state.getAttribute(STATE_SITE_TYPE); if (siteType != null && siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { String siteId = site.getId(); ResourcePropertiesEdit rp = site.getPropertiesEdit(); AcademicSession term = null; if (state.getAttribute(STATE_TERM_SELECTED) != null) { term = (AcademicSession) state .getAttribute(STATE_TERM_SELECTED); rp.addProperty(PROP_SITE_TERM, term.getTitle()); rp.addProperty(PROP_SITE_TERM_EID, term.getEid()); } // update the site and related realm based on the rosters chosen or requested updateCourseSiteSections(state, siteId, rp, term); } // commit site commitSite(site); // transfer site content from template site if (templateSite != null) { sendTemplateUseNotification(site, UserDirectoryService.getCurrentUser(), templateSite); } String siteId = (String) state.getAttribute(STATE_SITE_INSTANCE_ID); // now that the site exists, we can set the email alias when an // Email Archive tool has been selected setSiteAlias(state, siteId); // save user answers saveSiteSetupQuestionUserAnswers(state, siteId); // TODO: hard coding this frame id is fragile, portal dependent, and // needs to be fixed -ggolden // schedulePeerFrameRefresh("sitenav"); scheduleTopRefresh(); resetPaging(state); // clean state variables cleanState(state); if (SITE_MODE_HELPER.equals(state.getAttribute(STATE_SITE_MODE))) { state.setAttribute(SiteHelper.SITE_CREATE_SITE_ID, site.getId()); state.setAttribute(STATE_SITE_MODE, SITE_MODE_HELPER_DONE); } state.setAttribute(STATE_TEMPLATE_INDEX, "0"); } }// doFinish /** * set site mail alias * @param state * @param siteId */ private void setSiteAlias(SessionState state, String siteId) { List oTools = (List) state.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST); if (oTools == null || (oTools!=null && !oTools.contains("sakai.mailbox"))) { // set alias only if the email archive tool is newly added String alias = StringUtil.trimToNull((String) state .getAttribute(STATE_TOOL_EMAIL_ADDRESS)); if (alias != null) { String channelReference = mailArchiveChannelReference(siteId); try { AliasService.setAlias(alias, channelReference); } catch (IdUsedException ee) { addAlert(state, rb.getString("java.alias") + " " + alias + " " + rb.getString("java.exists")); M_log.warn(this + ".setSiteAlias: " + rb.getString("java.alias") + " " + alias + " " + rb.getString("java.exists"), ee); } catch (IdInvalidException ee) { addAlert(state, rb.getString("java.alias") + " " + alias + " " + rb.getString("java.isinval")); M_log.warn(this + ".setSiteAlias: " + rb.getString("java.alias") + " " + alias + " " + rb.getString("java.isinval"), ee); } catch (PermissionException ee) { addAlert(state, rb.getString("java.addalias") + " "); M_log.warn(this + ".setSiteAlias: " + rb.getString("java.addalias") + ee); } } } } /** * save user answers * @param state * @param siteId */ private void saveSiteSetupQuestionUserAnswers(SessionState state, String siteId) { // update the database with user answers to SiteSetup questions if (state.getAttribute(STATE_SITE_SETUP_QUESTION_ANSWER) != null) { Set<SiteSetupUserAnswer> userAnswers = (Set<SiteSetupUserAnswer>) state.getAttribute(STATE_SITE_SETUP_QUESTION_ANSWER); for(Iterator<SiteSetupUserAnswer> aIterator = userAnswers.iterator(); aIterator.hasNext();) { SiteSetupUserAnswer userAnswer = aIterator.next(); userAnswer.setSiteId(siteId); // save to db questionService.saveSiteSetupUserAnswer(userAnswer); } } } /** * Update course site and related realm based on the roster chosen or requested * @param state * @param siteId * @param rp * @param term */ private void updateCourseSiteSections(SessionState state, String siteId, ResourcePropertiesEdit rp, AcademicSession term) { // whether this is in the process of editing a site? boolean editingSite = ((String)state.getAttribute(STATE_SITE_MODE)).equals(SITE_MODE_SITEINFO)?true:false; List providerCourseList = (List) state .getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN); int manualAddNumber = 0; if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) { manualAddNumber = ((Integer) state .getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)) .intValue(); } List<SectionObject> cmRequestedSections = (List<SectionObject>) state .getAttribute(STATE_CM_REQUESTED_SECTIONS); List<SectionObject> cmAuthorizerSections = (List<SectionObject>) state .getAttribute(STATE_CM_AUTHORIZER_SECTIONS); String realm = SiteService.siteReference(siteId); if ((providerCourseList != null) && (providerCourseList.size() != 0)) { try { AuthzGroup realmEdit = AuthzGroupService .getAuthzGroup(realm); String providerRealm = buildExternalRealm(siteId, state, providerCourseList, StringUtil.trimToNull(realmEdit.getProviderGroupId())); realmEdit.setProviderGroupId(providerRealm); AuthzGroupService.save(realmEdit); } catch (GroupNotDefinedException e) { M_log.warn(this + ".updateCourseSiteSections: IdUnusedException, not found, or not an AuthzGroup object", e); addAlert(state, rb.getString("java.realm")); } // catch (AuthzPermissionException e) // { // M_log.warn(this + " PermissionException, user does not // have permission to edit AuthzGroup object."); // addAlert(state, rb.getString("java.notaccess")); // return; // } catch (Exception e) { addAlert(state, this + rb.getString("java.problem")); M_log.warn(this + ".updateCourseSiteSections: " + rb.getString("java.problem"), e); } sendSiteNotification(state, providerCourseList); } if (manualAddNumber != 0) { // set the manual sections to the site property String manualSections = rp.getProperty(PROP_SITE_REQUEST_COURSE) != null?rp.getProperty(PROP_SITE_REQUEST_COURSE)+"+":""; // manualCourseInputs is a list of a list of SectionField List manualCourseInputs = (List) state .getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS); // but we want to feed a list of a list of String (input of // the required fields) for (int j = 0; j < manualAddNumber; j++) { manualSections = manualSections.concat( sectionFieldProvider.getSectionEid( term.getEid(), (List) manualCourseInputs.get(j))) .concat("+"); } // trim the trailing plus sign manualSections = trimTrailingString(manualSections, "+"); rp.addProperty(PROP_SITE_REQUEST_COURSE, manualSections); // send request sendSiteRequest(state, "new", manualAddNumber, manualCourseInputs, "manual"); } if (cmRequestedSections != null && cmRequestedSections.size() > 0 || state.getAttribute(STATE_CM_SELECTED_SECTIONS) != null) { // set the cmRequest sections to the site property String cmRequestedSectionString = ""; if (!editingSite) { // but we want to feed a list of a list of String (input of // the required fields) for (int j = 0; j < cmRequestedSections.size(); j++) { cmRequestedSectionString = cmRequestedSectionString.concat(( cmRequestedSections.get(j)).eid).concat("+"); } // trim the trailing plus sign cmRequestedSectionString = trimTrailingString(cmRequestedSectionString, "+"); sendSiteRequest(state, "new", cmRequestedSections.size(), cmRequestedSections, "cmRequest"); } else { cmRequestedSectionString = rp.getProperty(STATE_CM_REQUESTED_SECTIONS) != null ? (String) rp.getProperty(STATE_CM_REQUESTED_SECTIONS):""; // get the selected cm section if (state.getAttribute(STATE_CM_SELECTED_SECTIONS) != null ) { List<SectionObject> cmSelectedSections = (List) state.getAttribute(STATE_CM_SELECTED_SECTIONS); if (cmRequestedSectionString.length() != 0) { cmRequestedSectionString = cmRequestedSectionString.concat("+"); } for (int j = 0; j < cmSelectedSections.size(); j++) { cmRequestedSectionString = cmRequestedSectionString.concat(( cmSelectedSections.get(j)).eid).concat("+"); } // trim the trailing plus sign cmRequestedSectionString = trimTrailingString(cmRequestedSectionString, "+"); sendSiteRequest(state, "new", cmSelectedSections.size(), cmSelectedSections, "cmRequest"); } } // update site property if (cmRequestedSectionString.length() > 0) { rp.addProperty(STATE_CM_REQUESTED_SECTIONS, cmRequestedSectionString); } else { rp.removeProperty(STATE_CM_REQUESTED_SECTIONS); } } } /** * Trim the trailing occurance of specified string * @param cmRequestedSectionString * @param trailingString * @return */ private String trimTrailingString(String cmRequestedSectionString, String trailingString) { if (cmRequestedSectionString.endsWith(trailingString)) { cmRequestedSectionString = cmRequestedSectionString.substring(0, cmRequestedSectionString.lastIndexOf(trailingString)); } return cmRequestedSectionString; } /** * buildExternalRealm creates a site/realm id in one of three formats, for a * single section, for multiple sections of the same course, or for a * cross-listing having multiple courses * * @param sectionList * is a Vector of CourseListItem * @param id * The site id */ private String buildExternalRealm(String id, SessionState state, List<String> providerIdList, String existingProviderIdString) { String realm = SiteService.siteReference(id); if (!AuthzGroupService.allowUpdate(realm)) { addAlert(state, rb.getString("java.rosters")); return null; } List<String> allProviderIdList = new Vector<String>(); // see if we need to keep existing provider settings if (existingProviderIdString != null) { allProviderIdList.addAll(Arrays.asList(groupProvider.unpackId(existingProviderIdString))); } // update the list with newly added providers allProviderIdList.addAll(providerIdList); if (allProviderIdList == null || allProviderIdList.size() == 0) return null; String[] providers = new String[allProviderIdList.size()]; providers = (String[]) allProviderIdList.toArray(providers); String providerId = groupProvider.packId(providers); return providerId; } // buildExternalRealm /** * Notification sent when a course site needs to be set up by Support * */ private void sendSiteRequest(SessionState state, String request, int requestListSize, List requestFields, String fromContext) { User cUser = UserDirectoryService.getCurrentUser(); String sendEmailToRequestee = null; StringBuilder buf = new StringBuilder(); // get the request email from configuration String requestEmail = getSetupRequestEmailAddress(); if (requestEmail != null) { String officialAccountName = ServerConfigurationService .getString("officialAccountName", ""); SiteInfo siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO); Site site = getStateSite(state); String id = site.getId(); String title = site.getTitle(); Time time = TimeService.newTime(); String local_time = time.toStringLocalTime(); String local_date = time.toStringLocalDate(); AcademicSession term = null; boolean termExist = false; if (state.getAttribute(STATE_TERM_SELECTED) != null) { termExist = true; term = (AcademicSession) state .getAttribute(STATE_TERM_SELECTED); } String productionSiteName = ServerConfigurationService .getServerName(); String from = NULL_STRING; String to = NULL_STRING; String headerTo = NULL_STRING; String replyTo = NULL_STRING; String message_subject = NULL_STRING; String content = NULL_STRING; String sessionUserName = cUser.getDisplayName(); String additional = NULL_STRING; if (request.equals("new")) { additional = siteInfo.getAdditional(); } else { additional = (String) state.getAttribute(FORM_ADDITIONAL); } boolean isFutureTerm = false; if (state.getAttribute(STATE_FUTURE_TERM_SELECTED) != null && ((Boolean) state .getAttribute(STATE_FUTURE_TERM_SELECTED)) .booleanValue()) { isFutureTerm = true; } // message subject if (termExist) { message_subject = rb.getString("java.sitereqfrom") + " " + sessionUserName + " " + rb.getString("java.for") + " " + term.getEid(); } else { message_subject = rb.getString("java.official") + " " + sessionUserName; } // there is no offical instructor for future term sites String requestId = (String) state .getAttribute(STATE_SITE_QUEST_UNIQNAME); if (!isFutureTerm) { // To site quest account - the instructor of record's if (requestId != null) { // in case of multiple instructors List instructors = new ArrayList(Arrays.asList(requestId.split(","))); for (Iterator iInstructors = instructors.iterator(); iInstructors.hasNext();) { String instructorId = (String) iInstructors.next(); try { User instructor = UserDirectoryService.getUserByEid(instructorId); rb.setContextLocale(rb.getLocale(instructor.getId())); // reset buf.setLength(0); to = instructor.getEmail(); from = requestEmail; headerTo = to; replyTo = requestEmail; buf.append(rb.getString("java.hello") + " \n\n"); buf.append(rb.getString("java.receiv") + " " + sessionUserName + ", "); buf.append(rb.getString("java.who") + "\n"); if (termExist) { buf.append(term.getTitle()); } // requested sections if (fromContext.equals("manual")) { addRequestedSectionIntoNotification(state, requestFields, buf); } else if (fromContext.equals("cmRequest")) { addRequestedCMSectionIntoNotification(state, requestFields, buf); } buf.append("\n" + rb.getString("java.sitetitle") + "\t" + title + "\n"); buf.append(rb.getString("java.siteid") + "\t" + id); buf.append("\n\n" + rb.getString("java.according") + " " + sessionUserName + " " + rb.getString("java.record")); buf.append(" " + rb.getString("java.canyou") + " " + sessionUserName + " " + rb.getString("java.assoc") + "\n\n"); buf.append(rb.getString("java.respond") + " " + sessionUserName + rb.getString("java.appoint") + "\n\n"); buf.append(rb.getString("java.thanks") + "\n"); buf.append(productionSiteName + " " + rb.getString("java.support")); content = buf.toString(); // send the email EmailService.send(from, to, message_subject, content, headerTo, replyTo, null); // revert back the local setting to default rb.setContextLocale(Locale.getDefault()); } catch (Exception e) { sendEmailToRequestee = sendEmailToRequestee == null?instructorId:sendEmailToRequestee.concat(", ").concat(instructorId); } } } } // To Support from = cUser.getEmail(); // set locale to system default rb.setContextLocale(Locale.getDefault()); to = requestEmail; headerTo = requestEmail; replyTo = cUser.getEmail(); buf.setLength(0); buf.append(rb.getString("java.to") + "\t\t" + productionSiteName + " " + rb.getString("java.supp") + "\n"); buf.append("\n" + rb.getString("java.from") + "\t" + sessionUserName + "\n"); if (request.equals("new")) { buf.append(rb.getString("java.subj") + "\t" + rb.getString("java.sitereq") + "\n"); } else { buf.append(rb.getString("java.subj") + "\t" + rb.getString("java.sitechreq") + "\n"); } buf.append(rb.getString("java.date") + "\t" + local_date + " " + local_time + "\n\n"); if (request.equals("new")) { buf.append(rb.getString("java.approval") + " " + productionSiteName + " " + rb.getString("java.coursesite") + " "); } else { buf.append(rb.getString("java.approval2") + " " + productionSiteName + " " + rb.getString("java.coursesite") + " "); } if (termExist) { buf.append(term.getTitle()); } if (requestListSize > 1) { buf.append(" " + rb.getString("java.forthese") + " " + requestListSize + " " + rb.getString("java.sections") + "\n\n"); } else { buf.append(" " + rb.getString("java.forthis") + "\n\n"); } // requested sections if (fromContext.equals("manual")) { addRequestedSectionIntoNotification(state, requestFields, buf); } else if (fromContext.equals("cmRequest")) { addRequestedCMSectionIntoNotification(state, requestFields, buf); } buf.append(rb.getString("java.name") + "\t" + sessionUserName + " (" + officialAccountName + " " + cUser.getEid() + ")\n"); buf.append(rb.getString("java.email") + "\t" + replyTo + "\n\n"); buf.append(rb.getString("java.sitetitle") + "\t" + title + "\n"); buf.append(rb.getString("java.siteid") + "\t" + id + "\n"); buf.append(rb.getString("java.siteinstr") + "\n" + additional + "\n\n"); if (!isFutureTerm) { if (sendEmailToRequestee == null) { buf.append(rb.getString("java.authoriz") + " " + requestId + " " + rb.getString("java.asreq")); } else { buf.append(rb.getString("java.thesiteemail") + " " + sendEmailToRequestee + " " + rb.getString("java.asreq")); } } content = buf.toString(); EmailService.send(from, to, message_subject, content, headerTo, replyTo, null); // To the Instructor from = requestEmail; to = cUser.getEmail(); // set the locale to individual receipient's setting rb.setContextLocale(rb.getLocale(cUser.getId())); headerTo = to; replyTo = to; buf.setLength(0); buf.append(rb.getString("java.isbeing") + " "); buf.append(rb.getString("java.meantime") + "\n\n"); buf.append(rb.getString("java.copy") + "\n\n"); buf.append(content); buf.append("\n" + rb.getString("java.wish") + " " + requestEmail); content = buf.toString(); EmailService.send(from, to, message_subject, content, headerTo, replyTo, null); // revert the locale to system default rb.setContextLocale(Locale.getDefault()); state.setAttribute(REQUEST_SENT, new Boolean(true)); } // if } // sendSiteRequest private void addRequestedSectionIntoNotification(SessionState state, List requestFields, StringBuilder buf) { // what are the required fields shown in the UI List requiredFields = state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS) != null ?(List) state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS):new Vector(); for (int i = 0; i < requiredFields.size(); i++) { List requiredFieldList = (List) requestFields .get(i); for (int j = 0; j < requiredFieldList.size(); j++) { SectionField requiredField = (SectionField) requiredFieldList .get(j); buf.append(requiredField.getLabelKey() + "\t" + requiredField.getValue() + "\n"); } } } private void addRequestedCMSectionIntoNotification(SessionState state, List cmRequestedSections, StringBuilder buf) { // what are the required fields shown in the UI for (int i = 0; i < cmRequestedSections.size(); i++) { SectionObject so = (SectionObject) cmRequestedSections.get(i); buf.append(so.getTitle() + "(" + so.getEid() + ")" + so.getCategory() + "\n"); } } /** * Notification sent when a course site is set up automatcally * */ private void sendSiteNotification(SessionState state, List notifySites) { // get the request email from configuration String requestEmail = getSetupRequestEmailAddress(); if (requestEmail != null) { // send emails Site site = getStateSite(state); String id = site.getId(); String title = site.getTitle(); Time time = TimeService.newTime(); String local_time = time.toStringLocalTime(); String local_date = time.toStringLocalDate(); String term_name = ""; if (state.getAttribute(STATE_TERM_SELECTED) != null) { term_name = ((AcademicSession) state .getAttribute(STATE_TERM_SELECTED)).getEid(); } String message_subject = rb.getString("java.official") + " " + UserDirectoryService.getCurrentUser().getDisplayName() + " " + rb.getString("java.for") + " " + term_name; String from = NULL_STRING; String to = NULL_STRING; String headerTo = NULL_STRING; String replyTo = NULL_STRING; String sender = UserDirectoryService.getCurrentUser() .getDisplayName(); String userId = StringUtil.trimToZero(SessionManager .getCurrentSessionUserId()); try { userId = UserDirectoryService.getUserEid(userId); } catch (UserNotDefinedException e) { M_log.warn(this + ".sendSiteNotification:" + rb.getString("user.notdefined") + " " + userId, e); } // To Support //set local to default rb.setContextLocale(Locale.getDefault()); from = UserDirectoryService.getCurrentUser().getEmail(); to = requestEmail; headerTo = requestEmail; replyTo = UserDirectoryService.getCurrentUser().getEmail(); StringBuilder buf = new StringBuilder(); buf.append("\n" + rb.getString("java.fromwork") + " " + ServerConfigurationService.getServerName() + " " + rb.getString("java.supp") + ":\n\n"); buf.append(rb.getString("java.off") + " '" + title + "' (id " + id + "), " + rb.getString("java.wasset") + " "); buf.append(sender + " (" + userId + ", " + rb.getString("java.email2") + " " + replyTo + ") "); buf.append(rb.getString("java.on") + " " + local_date + " " + rb.getString("java.at") + " " + local_time + " "); buf.append(rb.getString("java.for") + " " + term_name + ", "); int nbr_sections = notifySites.size(); if (nbr_sections > 1) { buf.append(rb.getString("java.withrost") + " " + Integer.toString(nbr_sections) + " " + rb.getString("java.sections") + "\n\n"); } else { buf.append(" " + rb.getString("java.withrost2") + "\n\n"); } for (int i = 0; i < nbr_sections; i++) { String course = (String) notifySites.get(i); buf.append(rb.getString("java.course2") + " " + course + "\n"); } String content = buf.toString(); EmailService.send(from, to, message_subject, content, headerTo, replyTo, null); } // if } // sendSiteNotification /** * doCancel called when "eventSubmit_doCancel_create" is in the request * parameters to c */ public void doCancel_create(RunData data) { // Don't put current form data in state, just return to the previous // template SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); removeAddClassContext(state); state.setAttribute(STATE_TEMPLATE_INDEX, "0"); if (SITE_MODE_HELPER.equals(state.getAttribute(STATE_SITE_MODE))) { state.setAttribute(STATE_SITE_MODE, SITE_MODE_HELPER_DONE); state.setAttribute(SiteHelper.SITE_CREATE_CANCELLED, Boolean.TRUE); } else { state.setAttribute(STATE_TEMPLATE_INDEX, "0"); } resetVisitedTemplateListToIndex(state, (String) state.getAttribute(STATE_TEMPLATE_INDEX)); } // doCancel_create /** * doCancel called when "eventSubmit_doCancel" is in the request parameters * to c int index = Integer.valueOf(params.getString * ("templateIndex")).intValue(); */ public void doCancel(RunData data) { // Don't put current form data in state, just return to the previous // template SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); state.removeAttribute(STATE_MESSAGE); String currentIndex = (String) state.getAttribute(STATE_TEMPLATE_INDEX); String backIndex = params.getString("back"); state.setAttribute(STATE_TEMPLATE_INDEX, backIndex); if (currentIndex.equals("3")) { state.removeAttribute(STATE_TOOL_EMAIL_ADDRESS); state.removeAttribute(STATE_MESSAGE); removeEditToolState(state); } else if (currentIndex.equals("13") || currentIndex.equals("14")) { // clean state attributes state.removeAttribute(FORM_SITEINFO_TITLE); state.removeAttribute(FORM_SITEINFO_DESCRIPTION); state.removeAttribute(FORM_SITEINFO_SHORT_DESCRIPTION); state.removeAttribute(FORM_SITEINFO_SKIN); state.removeAttribute(FORM_SITEINFO_INCLUDE); state.removeAttribute(FORM_SITEINFO_ICON_URL); state.setAttribute(STATE_TEMPLATE_INDEX, "12"); } else if (currentIndex.equals("15")) { params = data.getParameters(); state.setAttribute(STATE_TEMPLATE_INDEX, params .getString("cancelIndex")); removeEditToolState(state); } // htripath: added 'currentIndex.equals("45")' for import from file // cancel else if (currentIndex.equals("45")) { state.setAttribute(STATE_TEMPLATE_INDEX, "12"); } else if (currentIndex.equals("3")) { // from adding class if (((String) state.getAttribute(STATE_SITE_MODE)) .equalsIgnoreCase(SITE_MODE_SITESETUP)) { state.setAttribute(STATE_TEMPLATE_INDEX, "0"); } else if (((String) state.getAttribute(STATE_SITE_MODE)) .equalsIgnoreCase(SITE_MODE_SITEINFO)) { state.setAttribute(STATE_TEMPLATE_INDEX, "18"); } } else if (currentIndex.equals("27") || currentIndex.equals("28") || currentIndex.equals("59") || currentIndex.equals("60")) { // from import if (((String) state.getAttribute(STATE_SITE_MODE)) .equalsIgnoreCase(SITE_MODE_SITESETUP)) { // worksite setup if (getStateSite(state) == null) { // in creating new site process state.setAttribute(STATE_TEMPLATE_INDEX, "0"); } else { // in editing site process state.setAttribute(STATE_TEMPLATE_INDEX, "12"); } } else if (((String) state.getAttribute(STATE_SITE_MODE)) .equalsIgnoreCase(SITE_MODE_SITEINFO)) { // site info state.setAttribute(STATE_TEMPLATE_INDEX, "12"); } state.removeAttribute(STATE_IMPORT_SITE_TOOL); state.removeAttribute(STATE_IMPORT_SITES); } else if (currentIndex.equals("26")) { if (((String) state.getAttribute(STATE_SITE_MODE)) .equalsIgnoreCase(SITE_MODE_SITESETUP) && getStateSite(state) == null) { // from creating site state.setAttribute(STATE_TEMPLATE_INDEX, "0"); } else { // from revising site state.setAttribute(STATE_TEMPLATE_INDEX, "12"); } removeEditToolState(state); } else if (currentIndex.equals("37") || currentIndex.equals("44") || currentIndex.equals("53") || currentIndex.equals("36")) { // cancel back to edit class view state.removeAttribute(STATE_TERM_SELECTED); removeAddClassContext(state); state.setAttribute(STATE_TEMPLATE_INDEX, "43"); } // if all fails to match else if (isTemplateVisited(state, "12")) { // go to site info list view state.setAttribute(STATE_TEMPLATE_INDEX, "12"); } else { // go to WSetup list view state.setAttribute(STATE_TEMPLATE_INDEX, "0"); } resetVisitedTemplateListToIndex(state, (String) state.getAttribute(STATE_TEMPLATE_INDEX)); } // doCancel /** * doMenu_customize is called when "eventSubmit_doBack" is in the request * parameters Pass parameter to actionForTemplate to request action for * backward direction */ public void doMenu_customize(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(STATE_TEMPLATE_INDEX, "15"); }// doMenu_customize /** * doBack_to_list cancels an outstanding site edit, cleans state and returns * to the site list * */ public void doBack_to_list(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); Site site = getStateSite(state); if (site != null) { Hashtable h = (Hashtable) state .getAttribute(STATE_PAGESIZE_SITEINFO); h.put(site.getId(), state.getAttribute(STATE_PAGESIZE)); state.setAttribute(STATE_PAGESIZE_SITEINFO, h); } // restore the page size for Worksite setup tool if (state.getAttribute(STATE_PAGESIZE_SITESETUP) != null) { state.setAttribute(STATE_PAGESIZE, state .getAttribute(STATE_PAGESIZE_SITESETUP)); state.removeAttribute(STATE_PAGESIZE_SITESETUP); } cleanState(state); setupFormNamesAndConstants(state); state.setAttribute(STATE_TEMPLATE_INDEX, "0"); // reset resetVisitedTemplateListToIndex(state, "0"); } // doBack_to_list /** * reset to sublist with index as the last item * @param state * @param index */ private void resetVisitedTemplateListToIndex(SessionState state, String index) { if (state.getAttribute(STATE_VISITED_TEMPLATES) != null) { List<String> l = (List<String>) state.getAttribute(STATE_VISITED_TEMPLATES); if (l != null && l.indexOf(index) >=0 && l.indexOf(index) < l.size()) { state.setAttribute(STATE_VISITED_TEMPLATES, l.subList(0, l.indexOf(index)+1)); } } } /** * do called when "eventSubmit_do" is in the request parameters to c */ public void doAdd_custom_link(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); if ((params.getString("name")) == null || (params.getString("url") == null)) { Tool tr = ToolManager.getTool("sakai.iframe"); Site site = getStateSite(state); SitePage page = site.addPage(); page.setTitle(params.getString("name")); // the visible label on // the tool menu ToolConfiguration tool = page.addTool(); tool.setTool("sakai.iframe", tr); tool.setTitle(params.getString("name")); commitSite(site); } else { addAlert(state, rb.getString("java.reqmiss")); state.setAttribute(STATE_TEMPLATE_INDEX, params .getString("templateIndex")); } } // doAdd_custom_link /** * toolId might be of form original tool id concatenated with number * find whether there is an counterpart in the the multipleToolIdSet * @param state * @param toolId * @return */ private String findOriginalToolId(SessionState state, String toolId) { // treat home tool differently if (toolId.equals(getHomeToolId(state))) { return toolId; } else { Set categories = new HashSet(); categories.add((String) state.getAttribute(STATE_SITE_TYPE)); Set toolRegistrationList = ToolManager.findTools(categories, null); String rv = null; if (toolRegistrationList != null) { for (Iterator i=toolRegistrationList.iterator(); rv == null && i.hasNext();) { Tool tool = (Tool) i.next(); String tId = tool.getId(); rv = originalToolId(toolId, tId); } } return rv; } } private String originalToolId(String toolId, String toolRegistrationId) { String rv = null; if (toolId.indexOf(toolRegistrationId) != -1) { // the multiple tool id format is of TOOL_IDx, where x is an intger >= 1 if (toolId.endsWith(toolRegistrationId)) { rv = toolRegistrationId; } else { String suffix = toolId.substring(toolId.indexOf(toolRegistrationId) + toolRegistrationId.length()); try { Integer.parseInt(suffix); rv = toolRegistrationId; } catch (Exception e) { // not the right tool id M_log.debug(this + ".findOriginalToolId not matchign tool id = " + toolRegistrationId + " original tool id=" + toolId + e.getMessage(), e); } } } return rv; } /** * Read from tool registration whether multiple registration is allowed for this tool * @param toolId * @return */ private boolean isMultipleInstancesAllowed(String toolId) { Tool tool = ToolManager.getTool(toolId); if (tool != null) { Properties tProperties = tool.getRegisteredConfig(); return (tProperties.containsKey("allowMultipleInstances") && tProperties.getProperty("allowMultipleInstances").equalsIgnoreCase(Boolean.TRUE.toString()))?true:false; } return false; } private Hashtable<String, String> getMultiToolConfiguration(String toolId) { Hashtable<String, String> rv = new Hashtable<String, String>(); // read from configuration file ArrayList<String> attributes=new ArrayList<String>(); String attributesConfig = ServerConfigurationService.getString(CONFIG_TOOL_ATTRIBUTE + toolId); if ( attributesConfig != null && attributesConfig.length() > 0) { attributes = new ArrayList(Arrays.asList(attributesConfig.split(","))); } else { if (toolId.equals("sakai.news")) { // default setting for News tool attributes.add("channel-url"); } else if (toolId.equals("sakai.iframe")) { // default setting for Web Content tool attributes.add("source"); } } ArrayList<String> defaultValues =new ArrayList<String>(); String defaultValueConfig = ServerConfigurationService.getString(CONFIG_TOOL_ATTRIBUTE_DEFAULT + toolId); if ( defaultValueConfig != null && defaultValueConfig.length() > 0) { defaultValues = new ArrayList(Arrays.asList(defaultValueConfig.split(","))); } else { if (toolId.equals("sakai.news")) { // default value defaultValues.add("http://www.sakaiproject.org/news-rss-feed"); } else if (toolId.equals("sakai.iframe")) { // default setting for Web Content tool defaultValues.add("http://"); } } if (attributes != null && attributes.size() > 0) { for (int i = 0; i<attributes.size();i++) { rv.put(attributes.get(i), defaultValues.get(i)); } } return rv; } /** * doSave_revised_features */ public void doSave_revised_features(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); Site site = getStateSite(state); saveFeatures(params, state, site); String id = site.getId(); // now that the site exists, we can set the email alias when an Email // Archive tool has been selected setSiteAlias(state, id); if (state.getAttribute(STATE_MESSAGE) == null) { // clean state variables state.removeAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST); state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME); state.removeAttribute(STATE_MULTIPLE_TOOL_ID_SET); state.removeAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP); state.setAttribute(STATE_SITE_INSTANCE_ID, id); state.setAttribute(STATE_TEMPLATE_INDEX, params .getString("continue")); } // refresh the whole page scheduleTopRefresh(); } // doSave_revised_features /** * doMenu_add_participant */ public void doMenu_add_participant(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.removeAttribute(STATE_SELECTED_USER_LIST); state.setAttribute(STATE_TEMPLATE_INDEX, "5"); } // doMenu_add_participant /** * doMenu_siteInfo_addParticipant */ public void doMenu_siteInfo_addParticipant(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.removeAttribute(STATE_SELECTED_USER_LIST); if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_TEMPLATE_INDEX, "5"); } } // doMenu_siteInfo_addParticipant /** * doMenu_siteInfo_cancel_access */ public void doMenu_siteInfo_cancel_access(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.removeAttribute(STATE_SELECTED_USER_LIST); state.setAttribute(STATE_TEMPLATE_INDEX, "12"); } // doMenu_siteInfo_cancel_access /** * doMenu_siteInfo_importSelection */ public void doMenu_siteInfo_importSelection(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // get the tools siteToolsIntoState(state); if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_TEMPLATE_INDEX, "58"); } } // doMenu_siteInfo_importSelection /** * doMenu_siteInfo_import */ public void doMenu_siteInfo_import(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // get the tools siteToolsIntoState(state); if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_TEMPLATE_INDEX, "28"); } } // doMenu_siteInfo_import public void doMenu_siteInfo_importMigrate(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // get the tools siteToolsIntoState(state); if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_TEMPLATE_INDEX, "59"); } } // doMenu_siteInfo_importMigrate /** * doMenu_siteInfo_editClass */ public void doMenu_siteInfo_editClass(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(STATE_TEMPLATE_INDEX, "43"); } // doMenu_siteInfo_editClass /** * doMenu_siteInfo_addClass */ public void doMenu_siteInfo_addClass(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); Site site = getStateSite(state); String termEid = site.getProperties().getProperty(PROP_SITE_TERM_EID); if (termEid == null) { // no term eid stored, need to get term eid from the term title String termTitle = site.getProperties().getProperty(PROP_SITE_TERM); List asList = cms.getAcademicSessions(); if (termTitle != null && asList != null) { boolean found = false; for (int i = 0; i<asList.size() && !found; i++) { AcademicSession as = (AcademicSession) asList.get(i); if (as.getTitle().equals(termTitle)) { termEid = as.getEid(); site.getPropertiesEdit().addProperty(PROP_SITE_TERM_EID, termEid); try { SiteService.save(site); } catch (Exception e) { M_log.warn(this + ".doMenu_siteinfo_addClass: " + e.getMessage() + site.getId(), e); } found=true; } } } } state.setAttribute(STATE_TERM_SELECTED, cms.getAcademicSession(termEid)); try { List sections = prepareCourseAndSectionListing(UserDirectoryService.getCurrentUser().getEid(), cms.getAcademicSession(termEid).getEid(), state); isFutureTermSelected(state); if (sections != null && sections.size() > 0) state.setAttribute(STATE_TERM_COURSE_LIST, sections); } catch (Exception e) { M_log.warn(this + ".doMenu_siteinfo_addClass: " + e.getMessage() + termEid, e); } state.setAttribute(STATE_TEMPLATE_INDEX, "36"); } // doMenu_siteInfo_addClass /** * doMenu_siteInfo_duplicate */ public void doMenu_siteInfo_duplicate(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_TEMPLATE_INDEX, "29"); } } // doMenu_siteInfo_import /** * doMenu_edit_site_info * */ public void doMenu_edit_site_info(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); Site Site = getStateSite(state); ResourceProperties siteProperties = Site.getProperties(); state.setAttribute(FORM_SITEINFO_TITLE, Site.getTitle()); String site_type = (String) state.getAttribute(STATE_SITE_TYPE); if (site_type != null && !site_type.equalsIgnoreCase("myworkspace")) { state.setAttribute(FORM_SITEINFO_INCLUDE, Boolean.valueOf( Site.isPubView()).toString()); } state.setAttribute(FORM_SITEINFO_DESCRIPTION, Site.getDescription()); state.setAttribute(FORM_SITEINFO_SHORT_DESCRIPTION, Site .getShortDescription()); state.setAttribute(FORM_SITEINFO_SKIN, Site.getIconUrl()); if (Site.getIconUrl() != null) { state.setAttribute(FORM_SITEINFO_SKIN, Site.getIconUrl()); } // site contact information String contactName = siteProperties.getProperty(PROP_SITE_CONTACT_NAME); String contactEmail = siteProperties .getProperty(PROP_SITE_CONTACT_EMAIL); if (contactName == null && contactEmail == null) { String creatorId = siteProperties .getProperty(ResourceProperties.PROP_CREATOR); try { User u = UserDirectoryService.getUser(creatorId); String email = u.getEmail(); if (email != null) { contactEmail = u.getEmail(); } contactName = u.getDisplayName(); } catch (UserNotDefinedException e) { } } if (contactName != null) { state.setAttribute(FORM_SITEINFO_CONTACT_NAME, contactName); } if (contactEmail != null) { state.setAttribute(FORM_SITEINFO_CONTACT_EMAIL, contactEmail); } if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_TEMPLATE_INDEX, "13"); } } // doMenu_edit_site_info /** * doMenu_edit_site_tools * */ public void doMenu_edit_site_tools(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // get the tools siteToolsIntoState(state); if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_TEMPLATE_INDEX, "3"); } } // doMenu_edit_site_tools /** * doMenu_edit_site_access * */ public void doMenu_edit_site_access(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_TEMPLATE_INDEX, "18"); } } // doMenu_edit_site_access /** * Back to worksite setup's list view * */ public void doBack_to_site_list(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.removeAttribute(STATE_SELECTED_USER_LIST); state.removeAttribute(STATE_SITE_TYPE); state.removeAttribute(STATE_SITE_INSTANCE_ID); state.setAttribute(STATE_TEMPLATE_INDEX, "0"); // reset resetVisitedTemplateListToIndex(state, "0"); } // doBack_to_site_list /** * doSave_site_info * */ public void doSave_siteInfo(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); Site Site = getStateSite(state); ResourcePropertiesEdit siteProperties = Site.getPropertiesEdit(); String site_type = (String) state.getAttribute(STATE_SITE_TYPE); SiteInfo siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO); if (siteTitleEditable(state, site_type)) { Site.setTitle(siteInfo.title); } Site.setDescription(siteInfo.description); Site.setShortDescription(siteInfo.short_description); if (site_type != null) { if (site_type.equals((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { // set icon url for course setAppearance(state, Site, siteInfo.iconUrl); } else { // set icon url for others Site.setIconUrl(siteInfo.iconUrl); } } // site contact information String contactName = siteInfo.site_contact_name; if (contactName != null) { siteProperties.addProperty(PROP_SITE_CONTACT_NAME, contactName); } String contactEmail = siteInfo.site_contact_email; if (contactEmail != null) { siteProperties.addProperty(PROP_SITE_CONTACT_EMAIL, contactEmail); } if (state.getAttribute(STATE_MESSAGE) == null) { try { SiteService.save(Site); } catch (IdUnusedException e) { // TODO: } catch (PermissionException e) { // TODO: } // clean state attributes state.removeAttribute(FORM_SITEINFO_TITLE); state.removeAttribute(FORM_SITEINFO_DESCRIPTION); state.removeAttribute(FORM_SITEINFO_SHORT_DESCRIPTION); state.removeAttribute(FORM_SITEINFO_SKIN); state.removeAttribute(FORM_SITEINFO_INCLUDE); state.removeAttribute(FORM_SITEINFO_CONTACT_NAME); state.removeAttribute(FORM_SITEINFO_CONTACT_EMAIL); // back to site info view state.setAttribute(STATE_TEMPLATE_INDEX, "12"); // refresh the whole page scheduleTopRefresh(); } } // doSave_siteInfo /** * Check to see whether the site's title is editable or not * @param state * @param site_type * @return */ private boolean siteTitleEditable(SessionState state, String site_type) { return site_type != null && (!site_type.equals((String) state.getAttribute(STATE_COURSE_SITE_TYPE)) || (state.getAttribute(TITLE_EDITABLE_SITE_TYPE) != null && ((List) state.getAttribute(TITLE_EDITABLE_SITE_TYPE)).contains(site_type))); } /** * init * */ private void init(VelocityPortlet portlet, RunData data, SessionState state) { state.setAttribute(STATE_ACTION, "SiteAction"); setupFormNamesAndConstants(state); if (state.getAttribute(STATE_PAGESIZE_SITEINFO) == null) { state.setAttribute(STATE_PAGESIZE_SITEINFO, new Hashtable()); } if (SITE_MODE_SITESETUP.equalsIgnoreCase((String) state.getAttribute(STATE_SITE_MODE))) { state.setAttribute(STATE_TEMPLATE_INDEX, "0"); } else if (SITE_MODE_HELPER.equalsIgnoreCase((String) state.getAttribute(STATE_SITE_MODE))) { state.setAttribute(STATE_TEMPLATE_INDEX, "1"); } else if (SITE_MODE_SITEINFO.equalsIgnoreCase((String) state.getAttribute(STATE_SITE_MODE))){ String siteId = ToolManager.getCurrentPlacement().getContext(); getReviseSite(state, siteId); Hashtable h = (Hashtable) state .getAttribute(STATE_PAGESIZE_SITEINFO); if (!h.containsKey(siteId)) { // update h.put(siteId, new Integer(200)); state.setAttribute(STATE_PAGESIZE_SITEINFO, h); state.setAttribute(STATE_PAGESIZE, new Integer(200)); } } if (state.getAttribute(STATE_SITE_TYPES) == null) { PortletConfig config = portlet.getPortletConfig(); // all site types (SITE_DEFAULT_LIST overrides tool config) String t = StringUtil.trimToNull(SITE_DEFAULT_LIST); if ( t == null ) t = StringUtil.trimToNull(config.getInitParameter("siteTypes")); if (t != null) { List types = new ArrayList(Arrays.asList(t.split(","))); if (cms == null) { // if there is no CourseManagementService, disable the process of creating course site String courseType = ServerConfigurationService.getString("courseSiteType", (String) state.getAttribute(STATE_COURSE_SITE_TYPE)); types.remove(courseType); } state.setAttribute(STATE_SITE_TYPES, types); } else { t = (String)state.getAttribute(SiteHelper.SITE_CREATE_SITE_TYPES); if (t != null) { state.setAttribute(STATE_SITE_TYPES, new ArrayList(Arrays .asList(t.split(",")))); } else { state.setAttribute(STATE_SITE_TYPES, new Vector()); } } } // need to watch out for the config question.xml existence. // read the file and put it to backup folder. if (SiteSetupQuestionFileParser.isConfigurationXmlAvailable()) { SiteSetupQuestionFileParser.updateConfig(); } // show UI for adding non-official participant(s) or not // if nonOfficialAccount variable is set to be false inside sakai.properties file, do not show the UI section for adding them. // the setting defaults to be true if (state.getAttribute(ADD_NON_OFFICIAL_PARTICIPANT) == null) { state.setAttribute(ADD_NON_OFFICIAL_PARTICIPANT, ServerConfigurationService.getString("nonOfficialAccount", "true")); } if (state.getAttribute(STATE_VISITED_TEMPLATES) == null) { List<String> templates = new Vector<String>(); if (((String) state.getAttribute(STATE_SITE_MODE)).equalsIgnoreCase(SITE_MODE_SITESETUP)) { templates.add("0"); // the default page of WSetup tool } else if (((String) state.getAttribute(STATE_SITE_MODE)).equalsIgnoreCase(SITE_MODE_SITEINFO)) { templates.add("12");// the default page of Site Info tool } state.setAttribute(STATE_VISITED_TEMPLATES, templates); } if (state.getAttribute(STATE_SITE_TITLE_MAX) == null) { int siteTitleMaxLength = ServerConfigurationService.getInt("site.title.maxlength", 20); state.setAttribute(STATE_SITE_TITLE_MAX, siteTitleMaxLength); } } // init public void doNavigate_to_site(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); String siteId = StringUtil.trimToNull(data.getParameters().getString( "option")); if (siteId != null) { getReviseSite(state, siteId); } else { doBack_to_list(data); } } // doNavigate_to_site /** * Get site information for revise screen */ private void getReviseSite(SessionState state, String siteId) { if (state.getAttribute(STATE_SELECTED_USER_LIST) == null) { state.setAttribute(STATE_SELECTED_USER_LIST, new Vector()); } List sites = (List) state.getAttribute(STATE_SITES); try { Site site = SiteService.getSite(siteId); state.setAttribute(STATE_SITE_INSTANCE_ID, site.getId()); if (sites != null) { int pos = -1; for (int index = 0; index < sites.size() && pos == -1; index++) { if (((Site) sites.get(index)).getId().equals(siteId)) { pos = index; } } // has any previous site in the list? if (pos > 0) { state.setAttribute(STATE_PREV_SITE, sites.get(pos - 1)); } else { state.removeAttribute(STATE_PREV_SITE); } // has any next site in the list? if (pos < sites.size() - 1) { state.setAttribute(STATE_NEXT_SITE, sites.get(pos + 1)); } else { state.removeAttribute(STATE_NEXT_SITE); } } String type = site.getType(); if (type == null) { if (state.getAttribute(STATE_DEFAULT_SITE_TYPE) != null) { type = (String) state.getAttribute(STATE_DEFAULT_SITE_TYPE); } } state.setAttribute(STATE_SITE_TYPE, type); } catch (IdUnusedException e) { M_log.warn(this + ".getReviseSite: " + e.toString() + " site id = " + siteId, e); } // one site has been selected state.setAttribute(STATE_TEMPLATE_INDEX, "12"); } // getReviseSite /** * doUpdate_participant * */ public void doUpdate_participant(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); Site s = getStateSite(state); String realmId = SiteService.siteReference(s.getId()); if (AuthzGroupService.allowUpdate(realmId) || SiteService.allowUpdateSiteMembership(s.getId())) { try { AuthzGroup realmEdit = AuthzGroupService.getAuthzGroup(realmId); // does the site has maintain type user(s) before updating // participants? String maintainRoleString = realmEdit.getMaintainRole(); boolean hadMaintainUser = !realmEdit.getUsersHasRole( maintainRoleString).isEmpty(); // update participant roles List participants = collectionToList((Collection) state.getAttribute(STATE_PARTICIPANT_LIST)); // remove all roles and then add back those that were checked for (int i = 0; i < participants.size(); i++) { String id = null; // added participant Participant participant = (Participant) participants.get(i); id = participant.getUniqname(); if (id != null) { // get the newly assigned role String inputRoleField = "role" + id; String roleId = params.getString(inputRoleField); // only change roles when they are different than before if (roleId != null) { // get the grant active status boolean activeGrant = true; String activeGrantField = "activeGrant" + id; if (params.getString(activeGrantField) != null) { activeGrant = params .getString(activeGrantField) .equalsIgnoreCase("true") ? true : false; } boolean fromProvider = !participant.isRemoveable(); if (fromProvider && !roleId.equals(participant.getRole())) { fromProvider = false; } realmEdit.addMember(id, roleId, activeGrant, fromProvider); } } } // remove selected users if (params.getStrings("selectedUser") != null) { List removals = new ArrayList(Arrays.asList(params .getStrings("selectedUser"))); state.setAttribute(STATE_SELECTED_USER_LIST, removals); for (int i = 0; i < removals.size(); i++) { String rId = (String) removals.get(i); try { User user = UserDirectoryService.getUser(rId); realmEdit.removeMember(user.getId()); } catch (UserNotDefinedException e) { M_log.warn(this + ".doUpdate_participant: IdUnusedException " + rId + ". ", e); } } } if (hadMaintainUser && realmEdit.getUsersHasRole(maintainRoleString) .isEmpty()) { // if after update, the "had maintain type user" status // changed, show alert message and don't save the update addAlert(state, rb .getString("sitegen.siteinfolist.nomaintainuser") + maintainRoleString + "."); } else { AuthzGroupService.save(realmEdit); // post event about the participant update EventTrackingService.post(EventTrackingService.newEvent(SiteService.SECURE_UPDATE_SITE_MEMBERSHIP, realmEdit.getId(),false)); // then update all related group realms for the role doUpdate_related_group_participants(s, realmId); } } catch (GroupNotDefinedException e) { addAlert(state, rb.getString("java.problem2")); M_log.warn(this + ".doUpdate_participant: IdUnusedException " + s.getTitle() + "(" + realmId + "). ", e); } catch (AuthzPermissionException e) { addAlert(state, rb.getString("java.changeroles")); M_log.warn(this + ".doUpdate_participant: PermissionException " + s.getTitle() + "(" + realmId + "). ", e); } } } // doUpdate_participant /** * update realted group realm setting according to parent site realm changes * @param s * @param realmId */ private void doUpdate_related_group_participants(Site s, String realmId) { Collection groups = s.getGroups(); if (groups != null) { try { for (Iterator iGroups = groups.iterator(); iGroups.hasNext();) { Group g = (Group) iGroups.next(); try { Set gMembers = g.getMembers(); for (Iterator iGMembers = gMembers.iterator(); iGMembers.hasNext();) { Member gMember = (Member) iGMembers.next(); String gMemberId = gMember.getUserId(); Member siteMember = s.getMember(gMemberId); if ( siteMember == null) { // user has been removed from the site g.removeMember(gMemberId); } else { // check for Site Info-managed groups: don't change roles for other groups (e.g. section-managed groups) String gProp = g.getProperties().getProperty(SiteConstants.GROUP_PROP_WSETUP_CREATED); // if there is a difference between the role setting, remove the entry from group and add it back with correct role, all are marked "not provided" if (gProp != null && gProp.equals(Boolean.TRUE.toString()) && !g.getUserRole(gMemberId).equals(siteMember.getRole())) { Role siteRole = siteMember.getRole(); if (g.getRole(siteRole.getId()) == null) { // in case there is no matching role as that in the site, create such role and add it to the user g.addRole(siteRole.getId(), siteRole); } g.removeMember(gMemberId); g.addMember(gMemberId, siteRole.getId(), siteMember.isActive(), false); } } } // post event about the participant update EventTrackingService.post(EventTrackingService.newEvent(SiteService.SECURE_UPDATE_GROUP_MEMBERSHIP, g.getId(),false)); } catch (Exception ee) { M_log.warn(this + ".doUpdate_related_group_participants: " + ee.getMessage() + g.getId(), ee); } } // commit, save the site SiteService.save(s); } catch (Exception e) { M_log.warn(this + ".doUpdate_related_group_participants: " + e.getMessage() + s.getId(), e); } } } /** * doUpdate_site_access * */ public void doUpdate_site_access(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); Site sEdit = getStateSite(state); ParameterParser params = data.getParameters(); String publishUnpublish = params.getString("publishunpublish"); String include = params.getString("include"); String joinable = params.getString("joinable"); if (sEdit != null) { // editing existing site // publish site or not if (publishUnpublish != null && publishUnpublish.equalsIgnoreCase("publish")) { sEdit.setPublished(true); } else { sEdit.setPublished(false); } // site public choice if (include != null) { // if there is pubview input, use it sEdit.setPubView(include.equalsIgnoreCase("true") ? true : false); } else if (state.getAttribute(STATE_SITE_TYPE) != null) { String type = (String) state.getAttribute(STATE_SITE_TYPE); List publicSiteTypes = (List) state .getAttribute(STATE_PUBLIC_SITE_TYPES); List privateSiteTypes = (List) state .getAttribute(STATE_PRIVATE_SITE_TYPES); if (publicSiteTypes.contains(type)) { // sites are always public sEdit.setPubView(true); } else if (privateSiteTypes.contains(type)) { // site are always private sEdit.setPubView(false); } } else { sEdit.setPubView(false); } // publish site or not if (joinable != null && joinable.equalsIgnoreCase("true")) { state.setAttribute(STATE_JOINABLE, Boolean.TRUE); sEdit.setJoinable(true); String joinerRole = StringUtil.trimToNull(params .getString("joinerRole")); if (joinerRole != null) { state.setAttribute(STATE_JOINERROLE, joinerRole); sEdit.setJoinerRole(joinerRole); } else { state.setAttribute(STATE_JOINERROLE, ""); addAlert(state, rb.getString("java.joinsite") + " "); } } else { state.setAttribute(STATE_JOINABLE, Boolean.FALSE); state.removeAttribute(STATE_JOINERROLE); sEdit.setJoinable(false); sEdit.setJoinerRole(null); } if (state.getAttribute(STATE_MESSAGE) == null) { commitSite(sEdit); state.setAttribute(STATE_TEMPLATE_INDEX, "12"); // TODO: hard coding this frame id is fragile, portal dependent, // and needs to be fixed -ggolden // schedulePeerFrameRefresh("sitenav"); scheduleTopRefresh(); state.removeAttribute(STATE_JOINABLE); state.removeAttribute(STATE_JOINERROLE); } } else { // adding new site if (state.getAttribute(STATE_SITE_INFO) != null) { SiteInfo siteInfo = (SiteInfo) state .getAttribute(STATE_SITE_INFO); if (publishUnpublish != null && publishUnpublish.equalsIgnoreCase("publish")) { siteInfo.published = true; } else { siteInfo.published = false; } // site public choice if (include != null) { siteInfo.include = include.equalsIgnoreCase("true") ? true : false; } else if (StringUtil.trimToNull(siteInfo.site_type) != null) { String type = StringUtil.trimToNull(siteInfo.site_type); List publicSiteTypes = (List) state .getAttribute(STATE_PUBLIC_SITE_TYPES); List privateSiteTypes = (List) state .getAttribute(STATE_PRIVATE_SITE_TYPES); if (publicSiteTypes.contains(type)) { // sites are always public siteInfo.include = true; } else if (privateSiteTypes.contains(type)) { // site are always private siteInfo.include = false; } } else { siteInfo.include = false; } // joinable site or not if (joinable != null && joinable.equalsIgnoreCase("true")) { siteInfo.joinable = true; String joinerRole = StringUtil.trimToNull(params .getString("joinerRole")); if (joinerRole != null) { siteInfo.joinerRole = joinerRole; } else { addAlert(state, rb.getString("java.joinsite") + " "); } } else { siteInfo.joinable = false; siteInfo.joinerRole = null; } state.setAttribute(STATE_SITE_INFO, siteInfo); } if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_TEMPLATE_INDEX, "10"); updateCurrentStep(state, true); } } } // doUpdate_site_access /** * /* Actions for vm templates under the "chef_site" root. This method is * called by doContinue. Each template has a hidden field with the value of * template-index that becomes the value of index for the switch statement * here. Some cases not implemented. */ private void actionForTemplate(String direction, int index, ParameterParser params, SessionState state) { // Continue - make any permanent changes, Back - keep any data entered // on the form boolean forward = direction.equals("continue") ? true : false; SiteInfo siteInfo = new SiteInfo(); switch (index) { case 0: /* * actionForTemplate chef_site-list.vm * */ break; case 1: /* * actionForTemplate chef_site-type.vm * */ break; case 2: /* * actionForTemplate chef_site-newSiteInformation.vm * */ updateSiteInfo(params, state); siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO); // alerts after clicking Continue but not Back if (forward) { if (StringUtil.trimToNull(siteInfo.title) == null) { addAlert(state, rb.getString("java.reqfields")); state.setAttribute(STATE_TEMPLATE_INDEX, "2"); return; } } else { // removing previously selected template site state.removeAttribute(STATE_TEMPLATE_SITE); } updateSiteAttributes(state); if (state.getAttribute(STATE_MESSAGE) == null) { updateCurrentStep(state, forward); } break; case 3: /* * actionForTemplate chef_site-editFeatures.vm * */ if (forward) { // editing existing site or creating a new one? Site site = getStateSite(state); getFeatures(params, state, site==null?"18":"15"); if (state.getAttribute(STATE_MESSAGE) == null && site==null) { updateCurrentStep(state, forward); } } break; case 5: /* * actionForTemplate chef_site-addParticipant.vm * */ /*if (forward) { checkAddParticipant(params, state); } else { // remove related state variables removeAddParticipantContext(state); }*/ break; case 8: /* * actionForTemplate chef_site-siteDeleteConfirm.vm * */ break; case 10: /* * actionForTemplate chef_site-newSiteConfirm.vm * */ if (!forward) { if (state.getAttribute(STATE_MESSAGE) == null) { updateCurrentStep(state, false); } } break; case 12: /* * actionForTemplate chef_site_siteInfo-list.vm * */ break; case 13: /* * actionForTemplate chef_site_siteInfo-editInfo.vm * */ if (forward) { updateSiteInfo(params, state); if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_TEMPLATE_INDEX, "14"); } } break; case 14: /* * actionForTemplate chef_site_siteInfo-editInfoConfirm.vm * */ break; case 15: /* * actionForTemplate chef_site_siteInfo-addRemoveFeatureConfirm.vm * */ break; case 18: /* * actionForTemplate chef_siteInfo-editAccess.vm * */ if (!forward) { if (state.getAttribute(STATE_MESSAGE) == null) { updateCurrentStep(state, false); } } break; case 24: /* * actionForTemplate * chef_site-siteInfo-editAccess-globalAccess-confirm.vm * */ break; case 26: /* * actionForTemplate chef_site-modifyENW.vm * */ updateSelectedToolList(state, params, true); if (state.getAttribute(STATE_MESSAGE) == null) { updateCurrentStep(state, forward); } break; case 27: /* * actionForTemplate chef_site-importSites.vm * */ if (forward) { Site existingSite = getStateSite(state); if (existingSite != null) { // revising a existing site's tool if (select_import_tools(params, state)) { Hashtable importTools = (Hashtable) state .getAttribute(STATE_IMPORT_SITE_TOOL); List selectedTools = (List) state .getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); importToolIntoSite(selectedTools, importTools, existingSite); existingSite = getStateSite(state); // refresh site for // WC and News if (state.getAttribute(STATE_MESSAGE) == null) { commitSite(existingSite); state.removeAttribute(STATE_IMPORT_SITE_TOOL); state.removeAttribute(STATE_IMPORT_SITES); } } else { // show alert and remain in current page addAlert(state, rb.getString("java.toimporttool")); } } else { // new site select_import_tools(params, state); } } else { // read form input about import tools select_import_tools(params, state); } if (state.getAttribute(STATE_MESSAGE) == null) { updateCurrentStep(state, forward); } break; case 60: /* * actionForTemplate chef_site-importSitesMigrate.vm * */ if (forward) { Site existingSite = getStateSite(state); if (existingSite != null) { // revising a existing site's tool if (select_import_tools(params, state)) { Hashtable importTools = (Hashtable) state .getAttribute(STATE_IMPORT_SITE_TOOL); List selectedTools = (List) state .getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); // Remove all old contents before importing contents from new site importToolIntoSiteMigrate(selectedTools, importTools, existingSite); existingSite = getStateSite(state); // refresh site for // WC and News if (state.getAttribute(STATE_MESSAGE) == null) { commitSite(existingSite); state.removeAttribute(STATE_IMPORT_SITE_TOOL); state.removeAttribute(STATE_IMPORT_SITES); } } else { // show alert and remain in current page addAlert(state, rb.getString("java.toimporttool")); } } else { // new site select_import_tools(params, state); } } else { // read form input about import tools select_import_tools(params, state); } if (state.getAttribute(STATE_MESSAGE) == null) { updateCurrentStep(state, forward); } break; case 28: /* * actionForTemplate chef_siteinfo-import.vm * */ if (forward) { if (params.getStrings("importSites") == null) { addAlert(state, rb.getString("java.toimport") + " "); state.removeAttribute(STATE_IMPORT_SITES); } else { List importSites = new ArrayList(Arrays.asList(params .getStrings("importSites"))); Hashtable sites = new Hashtable(); for (index = 0; index < importSites.size(); index++) { try { Site s = SiteService.getSite((String) importSites .get(index)); sites.put(s, new Vector()); } catch (IdUnusedException e) { } } state.setAttribute(STATE_IMPORT_SITES, sites); } } break; case 58: /* * actionForTemplate chef_siteinfo-importSelection.vm * */ break; case 59: /* * actionForTemplate chef_siteinfo-import.vm * */ if (forward) { if (params.getStrings("importSites") == null) { addAlert(state, rb.getString("java.toimport") + " "); state.removeAttribute(STATE_IMPORT_SITES); } else { List importSites = new ArrayList(Arrays.asList(params .getStrings("importSites"))); Hashtable sites = new Hashtable(); for (index = 0; index < importSites.size(); index++) { try { Site s = SiteService.getSite((String) importSites .get(index)); sites.put(s, new Vector()); } catch (IdUnusedException e) { } } state.setAttribute(STATE_IMPORT_SITES, sites); } // validate the alias if (StringUtil.trimToNull(siteInfo.url_alias) != null && !siteInfo.url_alias.equals(NULL_STRING)) { try { AliasService.getTarget(siteInfo.url_alias); addAlert(state, rb.getString("java.alias") + " " + siteInfo.url_alias + " " + rb.getString("java.exists")); state.setAttribute(STATE_TEMPLATE_INDEX, "2"); return; } catch (IdUnusedException e) { // Do nothing. We want the alias to be unused. } } } break; case 29: /* * actionForTemplate chef_siteinfo-duplicate.vm * */ if (forward) { if (state.getAttribute(SITE_DUPLICATED) == null) { if (StringUtil.trimToNull(params.getString("title")) == null) { addAlert(state, rb.getString("java.dupli") + " "); } else { String title = params.getString("title"); state.setAttribute(SITE_DUPLICATED_NAME, title); String nSiteId = IdManager.createUuid(); try { String oSiteId = (String) state .getAttribute(STATE_SITE_INSTANCE_ID); Site site = SiteService.addSite(nSiteId, getStateSite(state)); // get the new site icon url if (site.getIconUrl() != null) { site.setIconUrl(transferSiteResource(oSiteId, nSiteId, site.getIconUrl())); } try { SiteService.save(site); } catch (IdUnusedException e) { // TODO: } catch (PermissionException e) { // TODO: } try { site = SiteService.getSite(nSiteId); // set title site.setTitle(title); // import tool content importToolContent(nSiteId, oSiteId, site, false); } catch (Exception e1) { // if goes here, IdService // or SiteService has done // something wrong. M_log.warn(this + ".actionForTemplate chef_siteinfo-duplicate: " + e1 + ":" + nSiteId + "when duplicating site", e1); } if (site.getType().equals((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { // for course site, need to // read in the input for // term information String termId = StringUtil.trimToNull(params .getString("selectTerm")); if (termId != null) { AcademicSession term = cms.getAcademicSession(termId); if (term != null) { ResourcePropertiesEdit rp = site.getPropertiesEdit(); rp.addProperty(PROP_SITE_TERM, term.getTitle()); rp.addProperty(PROP_SITE_TERM_EID, term.getEid()); } else { M_log.warn("termId=" + termId + " not found"); } } } try { SiteService.save(site); if (site.getType().equals((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { // also remove the provider id attribute if any String realm = SiteService.siteReference(site.getId()); try { AuthzGroup realmEdit = AuthzGroupService.getAuthzGroup(realm); realmEdit.setProviderGroupId(null); AuthzGroupService.save(realmEdit); } catch (GroupNotDefinedException e) { M_log.warn(this + ".actionForTemplate chef_siteinfo-duplicate: IdUnusedException, not found, or not an AuthzGroup object "+ realm, e); addAlert(state, rb.getString("java.realm")); } catch (Exception e) { addAlert(state, this + rb.getString("java.problem")); M_log.warn(this + ".actionForTemplate chef_siteinfo-duplicate: " + rb.getString("java.problem"), e); } } } catch (IdUnusedException e) { // TODO: } catch (PermissionException e) { // TODO: } // TODO: hard coding this frame id // is fragile, portal dependent, and // needs to be fixed -ggolden // schedulePeerFrameRefresh("sitenav"); scheduleTopRefresh(); state.setAttribute(SITE_DUPLICATED, Boolean.TRUE); } catch (IdInvalidException e) { addAlert(state, rb.getString("java.siteinval")); M_log.warn(this + ".actionForTemplate chef_siteinfo-duplicate: " + rb.getString("java.siteinval") + " site id = " + nSiteId, e); } catch (IdUsedException e) { addAlert(state, rb.getString("java.sitebeenused")); M_log.warn(this + ".actionForTemplate chef_siteinfo-duplicate: " + rb.getString("java.sitebeenused") + " site id = " + nSiteId, e); } catch (PermissionException e) { addAlert(state, rb.getString("java.allowcreate")); M_log.warn(this + ".actionForTemplate chef_siteinfo-duplicate: " + rb.getString("java.allowcreate") + " site id = " + nSiteId, e); } } } if (state.getAttribute(STATE_MESSAGE) == null) { // site duplication confirmed state.removeAttribute(SITE_DUPLICATED); state.removeAttribute(SITE_DUPLICATED_NAME); // return to the list view state.setAttribute(STATE_TEMPLATE_INDEX, "12"); } } break; case 33: break; case 36: /* * actionForTemplate chef_site-newSiteCourse.vm */ if (forward) { List providerChosenList = new Vector(); if (params.getStrings("providerCourseAdd") == null) { state.removeAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN); if (params.getString("manualAdds") == null) { addAlert(state, rb.getString("java.manual") + " "); } } if (state.getAttribute(STATE_MESSAGE) == null) { // The list of courses selected from provider listing if (params.getStrings("providerCourseAdd") != null) { providerChosenList = new ArrayList(Arrays.asList(params .getStrings("providerCourseAdd"))); // list of // course // ids String userId = (String) state .getAttribute(STATE_INSTRUCTOR_SELECTED); String currentUserId = (String) state .getAttribute(STATE_CM_CURRENT_USERID); if (userId == null || (userId != null && userId .equals(currentUserId))) { state.setAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN, providerChosenList); state.removeAttribute(STATE_CM_AUTHORIZER_SECTIONS); state.removeAttribute(FORM_ADDITIONAL); state.removeAttribute(STATE_CM_AUTHORIZER_LIST); } else { // STATE_CM_AUTHORIZER_SECTIONS are SectionObject, // so need to prepare it // also in this page, u can pick either section from // current user OR // sections from another users but not both. - // daisy's note 1 for now // till we are ready to add more complexity List sectionObjectList = prepareSectionObject( providerChosenList, userId); state.setAttribute(STATE_CM_AUTHORIZER_SECTIONS, sectionObjectList); state .removeAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN); // set special instruction & we will keep // STATE_CM_AUTHORIZER_LIST String additional = StringUtil.trimToZero(params .getString("additional")); state.setAttribute(FORM_ADDITIONAL, additional); } } collectNewSiteInfo(siteInfo, state, params, providerChosenList); } // next step state.setAttribute(SITE_CREATE_CURRENT_STEP, new Integer(2)); } break; case 38: break; case 39: break; case 42: /* * actionForTemplate chef_site-gradtoolsConfirm.vm * */ break; case 43: /* * actionForTemplate chef_site-editClass.vm * */ if (forward) { if (params.getStrings("providerClassDeletes") == null && params.getStrings("manualClassDeletes") == null && params.getStrings("cmRequestedClassDeletes") == null && !direction.equals("back")) { addAlert(state, rb.getString("java.classes")); } if (params.getStrings("providerClassDeletes") != null) { // build the deletions list List providerCourseList = (List) state .getAttribute(SITE_PROVIDER_COURSE_LIST); List providerCourseDeleteList = new ArrayList(Arrays .asList(params.getStrings("providerClassDeletes"))); for (ListIterator i = providerCourseDeleteList .listIterator(); i.hasNext();) { providerCourseList.remove((String) i.next()); } state.setAttribute(SITE_PROVIDER_COURSE_LIST, providerCourseList); } if (params.getStrings("manualClassDeletes") != null) { // build the deletions list List manualCourseList = (List) state .getAttribute(SITE_MANUAL_COURSE_LIST); List manualCourseDeleteList = new ArrayList(Arrays .asList(params.getStrings("manualClassDeletes"))); for (ListIterator i = manualCourseDeleteList.listIterator(); i .hasNext();) { manualCourseList.remove((String) i.next()); } state.setAttribute(SITE_MANUAL_COURSE_LIST, manualCourseList); } if (params.getStrings("cmRequestedClassDeletes") != null) { // build the deletions list List<SectionObject> cmRequestedCourseList = (List) state.getAttribute(STATE_CM_REQUESTED_SECTIONS); List<String> cmRequestedCourseDeleteList = new ArrayList(Arrays.asList(params.getStrings("cmRequestedClassDeletes"))); for (ListIterator i = cmRequestedCourseDeleteList.listIterator(); i .hasNext();) { String sectionId = (String) i.next(); try { SectionObject so = new SectionObject(cms.getSection(sectionId)); SectionObject soFound = null; for (Iterator j = cmRequestedCourseList.iterator(); soFound == null && j.hasNext();) { SectionObject k = (SectionObject) j.next(); if (k.eid.equals(sectionId)) { soFound = k; } } if (soFound != null) cmRequestedCourseList.remove(soFound); } catch (Exception e) { M_log.warn( this + e.getMessage() + sectionId, e); } } state.setAttribute(STATE_CM_REQUESTED_SECTIONS, cmRequestedCourseList); } updateCourseClasses(state, new Vector(), new Vector()); } break; case 44: if (forward) { AcademicSession a = (AcademicSession) state.getAttribute(STATE_TERM_SELECTED); Site site = getStateSite(state); ResourcePropertiesEdit pEdit = site.getPropertiesEdit(); // update the course site property and realm based on the selection updateCourseSiteSections(state, site.getId(), pEdit, a); try { SiteService.save(site); } catch (Exception e) { M_log.warn(this + ".actionForTemplate chef_siteinfo-addCourseConfirm: " + e.getMessage() + site.getId(), e); } removeAddClassContext(state); } break; case 54: if (forward) { // store answers to site setup questions if (getAnswersToSetupQuestions(params, state)) { state.setAttribute(STATE_TEMPLATE_INDEX, state.getAttribute(STATE_SITE_SETUP_QUESTION_NEXT_TEMPLATE)); } } break; } }// actionFor Template /** * This is used to update exsiting site attributes with encoded site id in it. A new resource item is added to new site when needed * * @param oSiteId * @param nSiteId * @param siteAttribute * @return the new migrated resource url */ private String transferSiteResource(String oSiteId, String nSiteId, String siteAttribute) { String rv = ""; String accessUrl = ServerConfigurationService.getAccessUrl(); if (siteAttribute!= null && siteAttribute.indexOf(oSiteId) != -1 && accessUrl != null) { // stripe out the access url, get the relative form of "url" Reference ref = EntityManager.newReference(siteAttribute.replaceAll(accessUrl, "")); try { ContentResource resource = m_contentHostingService.getResource(ref.getId()); // the new resource ContentResource nResource = null; String nResourceId = resource.getId().replaceAll(oSiteId, nSiteId); try { nResource = m_contentHostingService.getResource(nResourceId); } catch (Exception n2Exception) { // copy the resource then try { nResourceId = m_contentHostingService.copy(resource.getId(), nResourceId); nResource = m_contentHostingService.getResource(nResourceId); } catch (Exception n3Exception) { } } // get the new resource url rv = nResource != null?nResource.getUrl(false):""; } catch (Exception refException) { M_log.warn(this + ":transferSiteResource: cannot find resource with ref=" + ref.getReference() + " " + refException.getMessage()); } } return rv; } /** * * @param nSiteId * @param oSiteId * @param site */ private void importToolContent(String nSiteId, String oSiteId, Site site, boolean bypassSecurity) { // import tool content if (bypassSecurity) { // importing from template, bypass the permission checking: // temporarily allow the user to read and write from assignments (asn.revise permission) SecurityService.pushAdvisor(new SecurityAdvisor() { public SecurityAdvice isAllowed(String userId, String function, String reference) { return SecurityAdvice.ALLOWED; } }); } List pageList = site.getPages(); if (!((pageList == null) || (pageList.size() == 0))) { for (ListIterator i = pageList .listIterator(); i.hasNext();) { SitePage page = (SitePage) i.next(); List pageToolList = page.getTools(); if (!(pageToolList == null || pageToolList.size() == 0)) { Tool tool = ((ToolConfiguration) pageToolList.get(0)).getTool(); String toolId = tool != null?tool.getId():""; if (toolId.equalsIgnoreCase("sakai.resources")) { // handle // resource // tool // specially transferCopyEntities( toolId, m_contentHostingService .getSiteCollection(oSiteId), m_contentHostingService .getSiteCollection(nSiteId)); } else if (toolId.equalsIgnoreCase(SITE_INFORMATION_TOOL)) { // handle Home tool specially, need to update the site infomration display url if needed String newSiteInfoUrl = transferSiteResource(oSiteId, nSiteId, site.getInfoUrl()); site.setInfoUrl(newSiteInfoUrl); } else { // other // tools transferCopyEntities(toolId, oSiteId, nSiteId); } } } } if (bypassSecurity) { SecurityService.clearAdvisors(); } } /** * get user answers to setup questions * @param params * @param state * @return */ protected boolean getAnswersToSetupQuestions(ParameterParser params, SessionState state) { boolean rv = true; String answerString = null; String answerId = null; Set userAnswers = new HashSet(); SiteTypeQuestions siteTypeQuestions = questionService.getSiteTypeQuestions((String) state.getAttribute(STATE_SITE_TYPE)); if (siteTypeQuestions != null) { List<SiteSetupQuestion> questions = siteTypeQuestions.getQuestions(); for (Iterator i = questions.iterator(); i.hasNext();) { SiteSetupQuestion question = (SiteSetupQuestion) i.next(); // get the selected answerId answerId = params.get(question.getId()); if (question.isRequired() && answerId == null) { rv = false; addAlert(state, rb.getString("sitesetupquestion.alert")); } else if (answerId != null) { SiteSetupQuestionAnswer answer = questionService.getSiteSetupQuestionAnswer(answerId); if (answer != null) { if (answer.getIsFillInBlank()) { // need to read the text input instead answerString = params.get("fillInBlank_" + answerId); } SiteSetupUserAnswer uAnswer = questionService.newSiteSetupUserAnswer(); uAnswer.setAnswerId(answerId); uAnswer.setAnswerString(answerString); uAnswer.setQuestionId(question.getId()); uAnswer.setUserId(SessionManager.getCurrentSessionUserId()); //update the state variable userAnswers.add(uAnswer); } } } state.setAttribute(STATE_SITE_SETUP_QUESTION_ANSWER, userAnswers); } return rv; } /** * update current step index within the site creation wizard * * @param state * The SessionState object * @param forward * Moving forward or backward? */ private void updateCurrentStep(SessionState state, boolean forward) { if (state.getAttribute(SITE_CREATE_CURRENT_STEP) != null) { int currentStep = ((Integer) state .getAttribute(SITE_CREATE_CURRENT_STEP)).intValue(); if (forward) { state.setAttribute(SITE_CREATE_CURRENT_STEP, new Integer( currentStep + 1)); } else { state.setAttribute(SITE_CREATE_CURRENT_STEP, new Integer( currentStep - 1)); } } } /** * remove related state variable for adding class * * @param state * SessionState object */ private void removeAddClassContext(SessionState state) { // remove related state variables state.removeAttribute(STATE_ADD_CLASS_MANUAL); state.removeAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN); state.removeAttribute(STATE_MANUAL_ADD_COURSE_NUMBER); state.removeAttribute(STATE_MANUAL_ADD_COURSE_FIELDS); state.removeAttribute(STATE_SITE_QUEST_UNIQNAME); state.removeAttribute(STATE_AUTO_ADD); state.removeAttribute(SITE_CREATE_TOTAL_STEPS); state.removeAttribute(SITE_CREATE_CURRENT_STEP); state.removeAttribute(STATE_IMPORT_SITE_TOOL); state.removeAttribute(STATE_IMPORT_SITES); state.removeAttribute(STATE_CM_REQUESTED_SECTIONS); state.removeAttribute(STATE_CM_SELECTED_SECTIONS); sitePropertiesIntoState(state); } // removeAddClassContext private void updateCourseClasses(SessionState state, List notifyClasses, List requestClasses) { List providerCourseSectionList = (List) state.getAttribute(SITE_PROVIDER_COURSE_LIST); List manualCourseSectionList = (List) state.getAttribute(SITE_MANUAL_COURSE_LIST); List<SectionObject> cmRequestedCourseList = (List) state.getAttribute(STATE_CM_REQUESTED_SECTIONS); Site site = getStateSite(state); String id = site.getId(); String realmId = SiteService.siteReference(id); if ((providerCourseSectionList == null) || (providerCourseSectionList.size() == 0)) { // no section access so remove Provider Id try { AuthzGroup realmEdit1 = AuthzGroupService .getAuthzGroup(realmId); realmEdit1.setProviderGroupId(NULL_STRING); AuthzGroupService.save(realmEdit1); } catch (GroupNotDefinedException e) { M_log.warn(this + ".updateCourseClasses: IdUnusedException, " + site.getTitle() + "(" + realmId + ") not found, or not an AuthzGroup object", e); addAlert(state, rb.getString("java.cannotedit")); return; } catch (AuthzPermissionException e) { M_log.warn(this + ".updateCourseClasses: PermissionException, user does not have permission to edit AuthzGroup object " + site.getTitle() + "(" + realmId + "). ", e); addAlert(state, rb.getString("java.notaccess")); return; } } if ((providerCourseSectionList != null) && (providerCourseSectionList.size() != 0)) { // section access so rewrite Provider Id, don't need the current realm provider String String externalRealm = buildExternalRealm(id, state, providerCourseSectionList, null); try { AuthzGroup realmEdit2 = AuthzGroupService .getAuthzGroup(realmId); realmEdit2.setProviderGroupId(externalRealm); AuthzGroupService.save(realmEdit2); } catch (GroupNotDefinedException e) { M_log.warn(this + ".updateCourseClasses: IdUnusedException, " + site.getTitle() + "(" + realmId + ") not found, or not an AuthzGroup object", e); addAlert(state, rb.getString("java.cannotclasses")); return; } catch (AuthzPermissionException e) { M_log.warn(this + ".updateCourseClasses: PermissionException, user does not have permission to edit AuthzGroup object " + site.getTitle() + "(" + realmId + "). ", e); addAlert(state, rb.getString("java.notaccess")); return; } } // the manual request course into properties setSiteSectionProperty(manualCourseSectionList, site, PROP_SITE_REQUEST_COURSE); // the cm request course into properties setSiteSectionProperty(cmRequestedCourseList, site, STATE_CM_REQUESTED_SECTIONS); // clean the related site groups // if the group realm provider id is not listed for the site, remove the related group for (Iterator iGroups = site.getGroups().iterator(); iGroups.hasNext();) { Group group = (Group) iGroups.next(); try { AuthzGroup gRealm = AuthzGroupService.getAuthzGroup(group.getReference()); String gProviderId = StringUtil.trimToNull(gRealm.getProviderGroupId()); if (gProviderId != null) { if ((manualCourseSectionList== null && cmRequestedCourseList == null) || (manualCourseSectionList != null && !manualCourseSectionList.contains(gProviderId) && cmRequestedCourseList == null) || (manualCourseSectionList == null && cmRequestedCourseList != null && !cmRequestedCourseList.contains(gProviderId)) || (manualCourseSectionList != null && !manualCourseSectionList.contains(gProviderId) && cmRequestedCourseList != null && !cmRequestedCourseList.contains(gProviderId))) { AuthzGroupService.removeAuthzGroup(group.getReference()); } } } catch (Exception e) { M_log.warn(this + ".updateCourseClasses: cannot remove authzgroup : " + group.getReference(), e); } } if (state.getAttribute(STATE_MESSAGE) == null) { commitSite(site); } else { } if (requestClasses != null && requestClasses.size() > 0 && state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) { try { // send out class request notifications sendSiteRequest(state, "change", ((Integer) state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)).intValue(), (List<SectionObject>) state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS), "manual"); } catch (Exception e) { M_log.warn(this +".updateCourseClasses:" + e.toString(), e); } } if (notifyClasses != null && notifyClasses.size() > 0) { try { // send out class access confirmation notifications sendSiteNotification(state, notifyClasses); } catch (Exception e) { M_log.warn(this + ".updateCourseClasses:" + e.toString(), e); } } } // updateCourseClasses private void setSiteSectionProperty(List courseSectionList, Site site, String propertyName) { if ((courseSectionList != null) && (courseSectionList.size() != 0)) { // store the requested sections in one site property String sections = ""; for (int j = 0; j < courseSectionList.size();) { sections = sections + (String) courseSectionList.get(j); j++; if (j < courseSectionList.size()) { sections = sections + "+"; } } ResourcePropertiesEdit rp = site.getPropertiesEdit(); rp.addProperty(propertyName, sections); } else { ResourcePropertiesEdit rp = site.getPropertiesEdit(); rp.removeProperty(propertyName); } } /** * Sets selected roles for multiple users * * @param params * The ParameterParser object * @param listName * The state variable */ private void getSelectedRoles(SessionState state, ParameterParser params, String listName) { Hashtable pSelectedRoles = (Hashtable) state .getAttribute(STATE_SELECTED_PARTICIPANT_ROLES); if (pSelectedRoles == null) { pSelectedRoles = new Hashtable(); } List userList = (List) state.getAttribute(listName); for (int i = 0; i < userList.size(); i++) { String userId = null; if (listName.equalsIgnoreCase(STATE_ADD_PARTICIPANTS)) { userId = ((Participant) userList.get(i)).getUniqname(); } else if (listName.equalsIgnoreCase(STATE_SELECTED_USER_LIST)) { userId = (String) userList.get(i); } if (userId != null) { String rId = StringUtil.trimToNull(params.getString("role" + userId)); if (rId == null) { addAlert(state, rb.getString("java.rolefor") + " " + userId + ". "); pSelectedRoles.remove(userId); } else { pSelectedRoles.put(userId, rId); } } } state.setAttribute(STATE_SELECTED_PARTICIPANT_ROLES, pSelectedRoles); } // getSelectedRoles /** * dispatch function for changing participants roles */ public void doSiteinfo_edit_role(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String option = params.getString("option"); // dispatch if (option.equalsIgnoreCase("same_role_true")) { state.setAttribute(STATE_CHANGEROLE_SAMEROLE, Boolean.TRUE); state.setAttribute(STATE_CHANGEROLE_SAMEROLE_ROLE, params .getString("role_to_all")); } else if (option.equalsIgnoreCase("same_role_false")) { state.setAttribute(STATE_CHANGEROLE_SAMEROLE, Boolean.FALSE); state.removeAttribute(STATE_CHANGEROLE_SAMEROLE_ROLE); if (state.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES) == null) { state.setAttribute(STATE_SELECTED_PARTICIPANT_ROLES, new Hashtable()); } } else if (option.equalsIgnoreCase("continue")) { doContinue(data); } else if (option.equalsIgnoreCase("back")) { doBack(data); } else if (option.equalsIgnoreCase("cancel")) { doCancel(data); } } // doSiteinfo_edit_globalAccess /** * dispatch function for changing site global access */ public void doSiteinfo_edit_globalAccess(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String option = params.getString("option"); // dispatch if (option.equalsIgnoreCase("joinable")) { state.setAttribute("form_joinable", Boolean.TRUE); state.setAttribute("form_joinerRole", getStateSite(state) .getJoinerRole()); } else if (option.equalsIgnoreCase("unjoinable")) { state.setAttribute("form_joinable", Boolean.FALSE); state.removeAttribute("form_joinerRole"); } else if (option.equalsIgnoreCase("continue")) { doContinue(data); } else if (option.equalsIgnoreCase("cancel")) { doCancel(data); } } // doSiteinfo_edit_globalAccess /** * save changes to site global access */ public void doSiteinfo_save_globalAccess(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); Site s = getStateSite(state); boolean joinable = ((Boolean) state.getAttribute("form_joinable")) .booleanValue(); s.setJoinable(joinable); if (joinable) { // set the joiner role String joinerRole = (String) state.getAttribute("form_joinerRole"); s.setJoinerRole(joinerRole); } if (state.getAttribute(STATE_MESSAGE) == null) { // release site edit commitSite(s); state.setAttribute(STATE_TEMPLATE_INDEX, "18"); } } // doSiteinfo_save_globalAccess /** * updateSiteAttributes * */ private void updateSiteAttributes(SessionState state) { SiteInfo siteInfo = new SiteInfo(); if (state.getAttribute(STATE_SITE_INFO) != null) { siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO); } else { M_log .warn("SiteAction.updateSiteAttributes STATE_SITE_INFO == null"); return; } Site site = getStateSite(state); if (site != null) { if (StringUtil.trimToNull(siteInfo.title) != null) { site.setTitle(siteInfo.title); } if (siteInfo.description != null) { site.setDescription(siteInfo.description); } site.setPublished(siteInfo.published); setAppearance(state, site, siteInfo.iconUrl); site.setJoinable(siteInfo.joinable); if (StringUtil.trimToNull(siteInfo.joinerRole) != null) { site.setJoinerRole(siteInfo.joinerRole); } // Make changes and then put changed site back in state String id = site.getId(); try { SiteService.save(site); } catch (IdUnusedException e) { // TODO: } catch (PermissionException e) { // TODO: } if (SiteService.allowUpdateSite(id)) { try { SiteService.getSite(id); state.setAttribute(STATE_SITE_INSTANCE_ID, id); } catch (IdUnusedException e) { M_log.warn(this + ".updateSiteAttributes: IdUnusedException " + siteInfo.getTitle() + "(" + id + ") not found", e); } } // no permission else { addAlert(state, rb.getString("java.makechanges")); M_log.warn(this + ".updateSiteAttributes: PermissionException " + siteInfo.getTitle() + "(" + id + ")"); } } } // updateSiteAttributes /** * %%% legacy properties, to be removed */ private void updateSiteInfo(ParameterParser params, SessionState state) { SiteInfo siteInfo = new SiteInfo(); if (state.getAttribute(STATE_SITE_INFO) != null) { siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO); } siteInfo.site_type = (String) state.getAttribute(STATE_SITE_TYPE); if (params.getString("title") != null) { siteInfo.title = params.getString("title"); } if (params.getString("description") != null) { StringBuilder alertMsg = new StringBuilder(); String description = params.getString("description"); siteInfo.description = FormattedText.processFormattedText(description, alertMsg); } if (params.getString("short_description") != null) { siteInfo.short_description = params.getString("short_description"); } if (params.getString("additional") != null) { siteInfo.additional = params.getString("additional"); } if (params.getString("iconUrl") != null) { siteInfo.iconUrl = Validator.escapeHtml(params.getString("iconUrl")); } else if (params.getString("skin") != null) { siteInfo.iconUrl = params.getString("skin"); } if (params.getString("joinerRole") != null) { siteInfo.joinerRole = params.getString("joinerRole"); } if (params.getString("joinable") != null) { boolean joinable = params.getBoolean("joinable"); siteInfo.joinable = joinable; if (!joinable) siteInfo.joinerRole = NULL_STRING; } if (params.getString("itemStatus") != null) { siteInfo.published = Boolean .valueOf(params.getString("itemStatus")).booleanValue(); } // site contact information String name = StringUtil .trimToZero(params.getString("siteContactName")); siteInfo.site_contact_name = name; String email = StringUtil.trimToZero(params .getString("siteContactEmail")); if (email != null) { String[] parts = email.split("@"); if (email.length() > 0 && (email.indexOf("@") == -1 || parts.length != 2 || parts[0].length() == 0 || !Validator .checkEmailLocal(parts[0]))) { // invalid email addAlert(state, email + " " + rb.getString("java.invalid") + rb.getString("java.theemail")); } siteInfo.site_contact_email = email; } String alias = params.getString("url_alias"); if (alias != null) { try { alias = java.net.URLEncoder.encode(params.getString("url_alias"), "UTF-8"); siteInfo.url_alias = alias; try { AliasService.getTarget(alias); // the alias has been used addAlert(state, rb.getString("java.alias") + " " + alias + " " + rb.getString("java.exists")); } catch (IdUnusedException ee) { // wanted situation: the alias has not been used } } catch (java.io.UnsupportedEncodingException e) { // log exception M_log.warn( this + " error of encoding url alias " + alias ); } } state.setAttribute(STATE_SITE_INFO, siteInfo); // check for site title length if (siteInfo.title.length() > SiteConstants.SITE_GROUP_TITLE_LIMIT) { addAlert(state, rb.getString("site_group_title_length_limit_1") + SiteConstants.SITE_GROUP_TITLE_LIMIT + " " + rb.getString("site_group_title_length_limit_2")); } } // updateSiteInfo /** * getParticipantList * */ private Collection getParticipantList(SessionState state) { List members = new Vector(); String siteId = (String) state.getAttribute(STATE_SITE_INSTANCE_ID); List providerCourseList = null; providerCourseList = SiteParticipantHelper.getProviderCourseList(siteId); if (providerCourseList != null && providerCourseList.size() > 0) { state.setAttribute(SITE_PROVIDER_COURSE_LIST, providerCourseList); } Collection participants = SiteParticipantHelper.prepareParticipants(siteId, providerCourseList); state.setAttribute(STATE_PARTICIPANT_LIST, participants); return participants; } // getParticipantList /** * getRoles * */ private List getRoles(SessionState state) { List roles = new Vector(); String realmId = SiteService.siteReference((String) state .getAttribute(STATE_SITE_INSTANCE_ID)); try { AuthzGroup realm = AuthzGroupService.getAuthzGroup(realmId); roles.addAll(realm.getRoles()); Collections.sort(roles); } catch (GroupNotDefinedException e) { M_log.warn( this + ".getRoles: IdUnusedException " + realmId, e); } return roles; } // getRoles private void addSynopticTool(SitePage page, String toolId, String toolTitle, String layoutHint) { // Add synoptic announcements tool ToolConfiguration tool = page.addTool(); Tool reg = ToolManager.getTool(toolId); tool.setTool(toolId, reg); tool.setTitle(toolTitle); tool.setLayoutHints(layoutHint); } private void saveFeatures(ParameterParser params, SessionState state, Site site) { // get the list of Worksite Setup configured pages List wSetupPageList = state.getAttribute(STATE_WORKSITE_SETUP_PAGE_LIST)!=null?(List) state.getAttribute(STATE_WORKSITE_SETUP_PAGE_LIST):new Vector(); Set multipleToolIdSet = (Set) state.getAttribute(STATE_MULTIPLE_TOOL_ID_SET); // get the map of titles of multiple tool instances Map multipleToolIdTitleMap = state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP) != null? (Map) state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP):new HashMap(); WorksiteSetupPage wSetupPage = new WorksiteSetupPage(); WorksiteSetupPage wSetupHome = new WorksiteSetupPage(); List pageList = new Vector(); // declare some flags used in making decisions about Home, whether to // add, remove, or do nothing boolean hasHome = false; boolean homeInWSetupPageList = false; List chosenList = (List) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); // if features were selected, diff wSetupPageList and chosenList to get // page adds and removes // boolean values for adding synoptic views boolean hasAnnouncement = false; boolean hasSchedule = false; boolean hasChat = false; boolean hasDiscussion = false; boolean hasEmail = false; boolean hasSiteInfo = false; boolean hasMessageCenter = false; // tools to be imported from other sites? Hashtable importTools = null; if (state.getAttribute(STATE_IMPORT_SITE_TOOL) != null) { importTools = (Hashtable) state.getAttribute(STATE_IMPORT_SITE_TOOL); } // Home tool chosen? if (chosenList.contains(getHomeToolId(state))) { // add home tool later hasHome = true; } // order the id list chosenList = orderToolIds(state, checkNullSiteType(state, site), chosenList); // Special case - Worksite Setup Home comes from a hardcoded checkbox on // the vm template rather than toolRegistrationList // see if Home was chosen for (ListIterator j = chosenList.listIterator(); j.hasNext();) { String choice = (String) j.next(); if (choice.equals("sakai.mailbox")) { hasEmail = true; String alias = StringUtil.trimToNull((String) state .getAttribute(STATE_TOOL_EMAIL_ADDRESS)); if (alias != null) { if (!Validator.checkEmailLocal(alias)) { addAlert(state, rb.getString("java.theemail")); } else { try { String channelReference = mailArchiveChannelReference(site .getId()); // first, clear any alias set to this channel AliasService.removeTargetAliases(channelReference); // check // to // see // whether // the // alias // has // been // used try { String target = AliasService.getTarget(alias); if (target != null) { addAlert(state, rb .getString("java.emailinuse") + " "); } } catch (IdUnusedException ee) { try { AliasService.setAlias(alias, channelReference); } catch (IdUsedException exception) { } catch (IdInvalidException exception) { } catch (PermissionException exception) { } } } catch (PermissionException exception) { } } } } else if (choice.equals("sakai.announcements")) { hasAnnouncement = true; } else if (choice.equals("sakai.schedule")) { hasSchedule = true; } else if (choice.equals("sakai.chat")) { hasChat = true; } else if (choice.equals("sakai.discussion")) { hasDiscussion = true; } else if (choice.equals("sakai.messages") || choice.equals("sakai.forums") || choice.equals("sakai.messagecenter")) { hasMessageCenter = true; } else if (choice.equals("sakai.siteinfo")) { hasSiteInfo = true; } } // see if Home and/or Help in the wSetupPageList (can just check title // here, because we checked patterns before adding to the list) for (ListIterator i = wSetupPageList.listIterator(); !homeInWSetupPageList && i.hasNext();) { wSetupPage = (WorksiteSetupPage) i.next(); if (wSetupPage.getToolId().equals(getHomeToolId(state))) { homeInWSetupPageList = true; } } if (hasHome) { SitePage page = null; // Were the synoptic views of Announcement, Discussioin, Chat // existing before the editing boolean hadAnnouncement = false, hadDiscussion = false, hadChat = false, hadSchedule = false, hadMessageCenter = false; if (homeInWSetupPageList) { if (!SiteService.isUserSite(site.getId())) { // for non-myworkspace site, if Home is chosen and Home is // in the wSetupPageList, remove synoptic tools WorksiteSetupPage homePage = new WorksiteSetupPage(); for (ListIterator i = wSetupPageList.listIterator(); i .hasNext();) { WorksiteSetupPage comparePage = (WorksiteSetupPage) i .next(); if ((comparePage.getToolId()).equals(getHomeToolId(state))) { homePage = comparePage; } } page = site.getPage(homePage.getPageId()); List toolList = page.getTools(); List removeToolList = new Vector(); // get those synoptic tools for (ListIterator iToolList = toolList.listIterator(); iToolList .hasNext();) { ToolConfiguration tool = (ToolConfiguration) iToolList .next(); Tool t = tool.getTool(); if (t!= null) { if (t.getId().equals("sakai.synoptic.announcement")) { hadAnnouncement = true; if (!hasAnnouncement) { removeToolList.add(tool);// if Announcement // tool isn't // selected, remove // the synotic // Announcement } } else if (t.getId().equals(TOOL_ID_SUMMARY_CALENDAR)) { hadSchedule = true; if (!hasSchedule || !notStealthOrHiddenTool(TOOL_ID_SUMMARY_CALENDAR)) { // if Schedule tool isn't selected, or the summary calendar tool is stealthed or hidden, remove the synotic Schedule removeToolList.add(tool); } } else if (t.getId().equals("sakai.synoptic.discussion")) { hadDiscussion = true; if (!hasDiscussion) { removeToolList.add(tool);// if Discussion // tool isn't // selected, remove // the synoptic // Discussion } } else if (t.getId().equals("sakai.synoptic.chat")) { hadChat = true; if (!hasChat) { removeToolList.add(tool);// if Chat tool // isn't selected, // remove the // synoptic Chat } } else if (t.getId().equals("sakai.synoptic.messagecenter")) { hadMessageCenter = true; if (!hasMessageCenter) { removeToolList.add(tool);// if Messages and/or Forums tools // isn't selected, // remove the // synoptic Message Center tool } } } } // remove those synoptic tools for (ListIterator rToolList = removeToolList.listIterator(); rToolList .hasNext();) { page.removeTool((ToolConfiguration) rToolList.next()); } } } else { // if Home is chosen and Home is not in wSetupPageList, add Home // to site and wSetupPageList page = site.addPage(); page.setTitle(rb.getString("java.home")); wSetupHome.pageId = page.getId(); wSetupHome.pageTitle = page.getTitle(); wSetupHome.toolId = getHomeToolId(state); wSetupPageList.add(wSetupHome); // Add worksite information tool ToolConfiguration tool = page.addTool(); Tool reg = ToolManager.getTool(SITE_INFORMATION_TOOL); tool.setTool(SITE_INFORMATION_TOOL, reg); tool.setTitle(reg.getTitle()); tool.setLayoutHints("0,0"); } if (!SiteService.isUserSite(site.getId())) { // add synoptical tools to home tool in non-myworkspace site try { if (hasAnnouncement && !hadAnnouncement) { // Add synoptic announcements tool addSynopticTool(page, "sakai.synoptic.announcement", rb .getString("java.recann"), "0,1"); } if (hasDiscussion && !hadDiscussion) { // Add synoptic discussion tool addSynopticTool(page, "sakai.synoptic.discussion", rb .getString("java.recdisc"), "1,1"); } if (hasChat && !hadChat) { // Add synoptic chat tool addSynopticTool(page, "sakai.synoptic.chat", rb .getString("java.recent"), "2,1"); } if (hasSchedule && !hadSchedule) { // Add synoptic schedule tool if not stealth or hidden if (notStealthOrHiddenTool(TOOL_ID_SUMMARY_CALENDAR)) addSynopticTool(page, TOOL_ID_SUMMARY_CALENDAR, rb .getString("java.reccal"), "3,1"); } if (hasMessageCenter && !hadMessageCenter) { // Add synoptic Message Center addSynopticTool(page, "sakai.synoptic.messagecenter", rb .getString("java.recmsg"), "4,1"); } if (hasAnnouncement || hasDiscussion || hasChat || hasSchedule || hasMessageCenter) { page.setLayout(SitePage.LAYOUT_DOUBLE_COL); } else { page.setLayout(SitePage.LAYOUT_SINGLE_COL); } } catch (Exception e) { M_log.warn(this + ".saveFeatures: " + e.getMessage() + " site id = " + site.getId(), e); } } } // add Home // if Home is in wSetupPageList and not chosen, remove Home feature from // wSetupPageList and site if (!hasHome && homeInWSetupPageList) { // remove Home from wSetupPageList WorksiteSetupPage removePage = new WorksiteSetupPage(); for (ListIterator i = wSetupPageList.listIterator(); i.hasNext();) { WorksiteSetupPage comparePage = (WorksiteSetupPage) i.next(); if (comparePage.getToolId().equals(getHomeToolId(state))) { removePage = comparePage; } } SitePage siteHome = site.getPage(removePage.getPageId()); site.removePage(siteHome); wSetupPageList.remove(removePage); } // declare flags used in making decisions about whether to add, remove, // or do nothing boolean inChosenList; boolean inWSetupPageList; Set categories = new HashSet(); categories.add((String) state.getAttribute(STATE_SITE_TYPE)); Set toolRegistrationSet = ToolManager.findTools(categories, null); // first looking for any tool for removal Vector removePageIds = new Vector(); for (ListIterator k = wSetupPageList.listIterator(); k.hasNext();) { wSetupPage = (WorksiteSetupPage) k.next(); String pageToolId = wSetupPage.getToolId(); // use page id + tool id for multiple tool instances if (isMultipleInstancesAllowed(findOriginalToolId(state, pageToolId))) { pageToolId = wSetupPage.getPageId() + pageToolId; } inChosenList = false; for (ListIterator j = chosenList.listIterator(); j.hasNext();) { String toolId = (String) j.next(); if (pageToolId.equals(toolId)) { inChosenList = true; } } if (!inChosenList) { removePageIds.add(wSetupPage.getPageId()); } } for (int i = 0; i < removePageIds.size(); i++) { // if the tool exists in the wSetupPageList, remove it from the site String removeId = (String) removePageIds.get(i); SitePage sitePage = site.getPage(removeId); site.removePage(sitePage); // and remove it from wSetupPageList for (ListIterator k = wSetupPageList.listIterator(); k.hasNext();) { wSetupPage = (WorksiteSetupPage) k.next(); if (!wSetupPage.getPageId().equals(removeId)) { wSetupPage = null; } } if (wSetupPage != null) { wSetupPageList.remove(wSetupPage); } } // then looking for any tool to add for (ListIterator j = orderToolIds(state, (String) state.getAttribute(STATE_SITE_TYPE), chosenList) .listIterator(); j.hasNext();) { String toolId = (String) j.next(); // Is the tool in the wSetupPageList? inWSetupPageList = false; for (ListIterator k = wSetupPageList.listIterator(); k.hasNext();) { wSetupPage = (WorksiteSetupPage) k.next(); String pageToolId = wSetupPage.getToolId(); // use page Id + toolId for multiple tool instances if (isMultipleInstancesAllowed(findOriginalToolId(state, pageToolId))) { pageToolId = wSetupPage.getPageId() + pageToolId; } if (pageToolId.equals(toolId)) { inWSetupPageList = true; // but for tool of multiple instances, need to change the title if (isMultipleInstancesAllowed(findOriginalToolId(state, toolId))) { SitePage pEdit = (SitePage) site .getPage(wSetupPage.pageId); pEdit.setTitle((String) multipleToolIdTitleMap.get(toolId)); List toolList = pEdit.getTools(); for (ListIterator jTool = toolList.listIterator(); jTool .hasNext();) { ToolConfiguration tool = (ToolConfiguration) jTool .next(); String tId = tool.getTool().getId(); if (isMultipleInstancesAllowed(findOriginalToolId(state, tId))) { // set tool title tool.setTitle((String) multipleToolIdTitleMap.get(toolId)); // save tool configuration saveMultipleToolConfiguration(state, tool, toolId); } } } } } if (inWSetupPageList) { // if the tool already in the list, do nothing so to save the // option settings } else { // if in chosen list but not in wSetupPageList, add it to the // site (one tool on a page) Tool toolRegFound = null; for (Iterator i = toolRegistrationSet.iterator(); i.hasNext();) { Tool toolReg = (Tool) i.next(); if (toolId.indexOf(toolReg.getId()) != -1) { toolRegFound = toolReg; } } if (toolRegFound != null) { // we know such a tool, so add it WorksiteSetupPage addPage = new WorksiteSetupPage(); SitePage page = site.addPage(); addPage.pageId = page.getId(); if (isMultipleInstancesAllowed(findOriginalToolId(state, toolId))) { // set tool title page.setTitle((String) multipleToolIdTitleMap.get(toolId)); } else { // other tools with default title page.setTitle(toolRegFound.getTitle()); } page.setLayout(SitePage.LAYOUT_SINGLE_COL); ToolConfiguration tool = page.addTool(); tool.setTool(toolRegFound.getId(), toolRegFound); addPage.toolId = toolId; wSetupPageList.add(addPage); // set tool title if (isMultipleInstancesAllowed(findOriginalToolId(state, toolId))) { // set tool title tool.setTitle((String) multipleToolIdTitleMap.get(toolId)); // save tool configuration saveMultipleToolConfiguration(state, tool, toolId); } else { tool.setTitle(toolRegFound.getTitle()); } } } } // for // reorder Home and Site Info only if the site has not been customized order before if (!site.isCustomPageOrdered()) { // the steps for moving page within the list int moves = 0; if (hasHome) { SitePage homePage = null; // Order tools - move Home to the top - first find it pageList = site.getPages(); if (pageList != null && pageList.size() != 0) { for (ListIterator i = pageList.listIterator(); i.hasNext();) { SitePage page = (SitePage) i.next(); if (pageHasToolId(page.getTools(), getHomeToolId(state))) { homePage = page; break; } } } if (homePage != null) { moves = pageList.indexOf(homePage); for (int n = 0; n < moves; n++) { homePage.moveUp(); } } } // if Site Info is newly added, more it to the last if (hasSiteInfo) { SitePage siteInfoPage = null; pageList = site.getPages(); String[] toolIds = { "sakai.siteinfo" }; if (pageList != null && pageList.size() != 0) { for (ListIterator i = pageList.listIterator(); siteInfoPage == null && i.hasNext();) { SitePage page = (SitePage) i.next(); int s = page.getTools(toolIds).size(); if (s > 0) { siteInfoPage = page; break; } } if (siteInfoPage != null) { // move home from it's index to the first position moves = pageList.indexOf(siteInfoPage); for (int n = moves; n < pageList.size(); n++) { siteInfoPage.moveDown(); } } } } } // if there is no email tool chosen if (!hasEmail) { state.removeAttribute(STATE_TOOL_EMAIL_ADDRESS); } // commit commitSite(site); // import importToolIntoSite(chosenList, importTools, site); } // saveFeatures /** * Save configuration values for multiple tool instances */ private void saveMultipleToolConfiguration(SessionState state, ToolConfiguration tool, String toolId) { // get the configuration of multiple tool instance Hashtable<String, Hashtable<String, String>> multipleToolConfiguration = state.getAttribute(STATE_MULTIPLE_TOOL_CONFIGURATION) != null?(Hashtable<String, Hashtable<String, String>>) state.getAttribute(STATE_MULTIPLE_TOOL_CONFIGURATION):new Hashtable<String, Hashtable<String, String>>(); // set tool attributes Hashtable<String, String> attributes = multipleToolConfiguration.get(toolId); if (attributes != null) { for(String attribute : attributes.keySet()) { String attributeValue = attributes.get(attribute); // if we have a value if (attributeValue != null) { // if this value is not the same as the tool's registered, set it in the placement if (!attributeValue.equals(tool.getTool().getRegisteredConfig().getProperty(attribute))) { tool.getPlacementConfig().setProperty(attribute, attributeValue); } // otherwise clear it else { tool.getPlacementConfig().remove(attribute); } } // if no value else { tool.getPlacementConfig().remove(attribute); } } } } /** * Is the tool stealthed or hidden * @param toolId * @return */ private boolean notStealthOrHiddenTool(String toolId) { return (ToolManager.getTool(toolId) != null && !ServerConfigurationService .getString( "[email protected]") .contains(toolId) && !ServerConfigurationService .getString( "[email protected]") .contains(toolId)); } /** * getFeatures gets features for a new site * */ private void getFeatures(ParameterParser params, SessionState state, String continuePageIndex) { List idsSelected = new Vector(); List existTools = state.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST) == null? new Vector():(List) state.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST); // to reset the state variable of the multiple tool instances Set multipleToolIdSet = state.getAttribute(STATE_MULTIPLE_TOOL_ID_SET) != null? (Set) state.getAttribute(STATE_MULTIPLE_TOOL_ID_SET):new HashSet(); // get the map of titles of multiple tool instances Map multipleToolIdTitleMap = state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP) != null? (Map) state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP):new HashMap(); boolean goToToolConfigPage = false; boolean homeSelected = false; // Add new pages and tools, if any if (params.getStrings("selectedTools") == null) { addAlert(state, rb.getString("atleastonetool")); } else { List l = new ArrayList(Arrays.asList(params .getStrings("selectedTools"))); // toolId's & titles of // chosen tools for (int i = 0; i < l.size(); i++) { String toolId = (String) l.get(i); if (toolId.equals(getHomeToolId(state))) { homeSelected = true; idsSelected.add(toolId); } else { String originId = findOriginalToolId(state, toolId); if (isMultipleInstancesAllowed(originId)) { // if user is adding either EmailArchive tool, News tool // or Web Content tool, go to the Customize page for the // tool if (!existTools.contains(toolId)) { goToToolConfigPage = true; if (!multipleToolIdSet.contains(toolId)) multipleToolIdSet.add(toolId); if (!multipleToolIdTitleMap.containsKey(toolId)) multipleToolIdTitleMap.put(toolId, ToolManager.getTool(originId).getTitle()); } } else if (toolId.equals("sakai.mailbox") && !existTools.contains(toolId)) { // get the email alias when an Email Archive tool // has been selected goToToolConfigPage = true; String channelReference = mailArchiveChannelReference((String) state .getAttribute(STATE_SITE_INSTANCE_ID)); List aliases = AliasService.getAliases( channelReference, 1, 1); if (aliases.size() > 0) { state.setAttribute(STATE_TOOL_EMAIL_ADDRESS, ((Alias) aliases.get(0)).getId()); } } idsSelected.add(toolId); } } state.setAttribute(STATE_TOOL_HOME_SELECTED, new Boolean( homeSelected)); } state.setAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST, idsSelected); // List of ToolRegistration toolId's // in case of import String importString = params.getString("import"); if (importString != null && importString.equalsIgnoreCase(Boolean.TRUE.toString())) { state.setAttribute(STATE_IMPORT, Boolean.TRUE); List importSites = new Vector(); if (params.getStrings("importSites") != null) { importSites = new ArrayList(Arrays.asList(params .getStrings("importSites"))); } if (importSites.size() == 0) { addAlert(state, rb.getString("java.toimport") + " "); } else { Hashtable sites = new Hashtable(); for (int index = 0; index < importSites.size(); index++) { try { Site s = SiteService.getSite((String) importSites .get(index)); if (!sites.containsKey(s)) { sites.put(s, new Vector()); } } catch (IdUnusedException e) { } } state.setAttribute(STATE_IMPORT_SITES, sites); } } else { state.removeAttribute(STATE_IMPORT); } // of // ToolRegistration // toolId's if (state.getAttribute(STATE_MESSAGE) == null) { if (state.getAttribute(STATE_IMPORT) != null) { // go to import tool page state.setAttribute(STATE_TEMPLATE_INDEX, "27"); } else if (goToToolConfigPage) { // go to the configuration page for multiple instances of tools state.setAttribute(STATE_TEMPLATE_INDEX, "26"); } else { // go to next page state.setAttribute(STATE_TEMPLATE_INDEX, continuePageIndex); } state.setAttribute(STATE_MULTIPLE_TOOL_ID_SET, multipleToolIdSet); state.setAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP, multipleToolIdTitleMap); } } // getFeatures // import tool content into site private void importToolIntoSite(List toolIds, Hashtable importTools, Site site) { if (importTools != null) { // import resources first boolean resourcesImported = false; for (int i = 0; i < toolIds.size() && !resourcesImported; i++) { String toolId = (String) toolIds.get(i); if (toolId.equalsIgnoreCase("sakai.resources") && importTools.containsKey(toolId)) { List importSiteIds = (List) importTools.get(toolId); for (int k = 0; k < importSiteIds.size(); k++) { String fromSiteId = (String) importSiteIds.get(k); String toSiteId = site.getId(); String fromSiteCollectionId = m_contentHostingService .getSiteCollection(fromSiteId); String toSiteCollectionId = m_contentHostingService .getSiteCollection(toSiteId); transferCopyEntities(toolId, fromSiteCollectionId, toSiteCollectionId); resourcesImported = true; } } } // import other tools then for (int i = 0; i < toolIds.size(); i++) { String toolId = (String) toolIds.get(i); if (!toolId.equalsIgnoreCase("sakai.resources") && importTools.containsKey(toolId)) { List importSiteIds = (List) importTools.get(toolId); for (int k = 0; k < importSiteIds.size(); k++) { String fromSiteId = (String) importSiteIds.get(k); String toSiteId = site.getId(); transferCopyEntities(toolId, fromSiteId, toSiteId); } } } } } // importToolIntoSite private void importToolIntoSiteMigrate(List toolIds, Hashtable importTools, Site site) { if (importTools != null) { // import resources first boolean resourcesImported = false; for (int i = 0; i < toolIds.size() && !resourcesImported; i++) { String toolId = (String) toolIds.get(i); if (toolId.equalsIgnoreCase("sakai.resources") && importTools.containsKey(toolId)) { List importSiteIds = (List) importTools.get(toolId); for (int k = 0; k < importSiteIds.size(); k++) { String fromSiteId = (String) importSiteIds.get(k); String toSiteId = site.getId(); String fromSiteCollectionId = m_contentHostingService .getSiteCollection(fromSiteId); String toSiteCollectionId = m_contentHostingService .getSiteCollection(toSiteId); transferCopyEntitiesMigrate(toolId, fromSiteCollectionId, toSiteCollectionId); resourcesImported = true; } } } // import other tools then for (int i = 0; i < toolIds.size(); i++) { String toolId = (String) toolIds.get(i); if (!toolId.equalsIgnoreCase("sakai.resources") && importTools.containsKey(toolId)) { List importSiteIds = (List) importTools.get(toolId); for (int k = 0; k < importSiteIds.size(); k++) { String fromSiteId = (String) importSiteIds.get(k); String toSiteId = site.getId(); transferCopyEntitiesMigrate(toolId, fromSiteId, toSiteId); } } } } } // importToolIntoSiteMigrate public void saveSiteStatus(SessionState state, boolean published) { Site site = getStateSite(state); site.setPublished(published); } // saveSiteStatus public void commitSite(Site site, boolean published) { site.setPublished(published); try { SiteService.save(site); } catch (IdUnusedException e) { // TODO: } catch (PermissionException e) { // TODO: } } // commitSite public void commitSite(Site site) { try { SiteService.save(site); } catch (IdUnusedException e) { // TODO: } catch (PermissionException e) { // TODO: } }// commitSite private Vector removeDuplicateParticipants(List pList, SessionState state) { // check the uniqness of list member Set s = new HashSet(); Set uniqnameSet = new HashSet(); Vector rv = new Vector(); for (int i = 0; i < pList.size(); i++) { Participant p = (Participant) pList.get(i); if (!uniqnameSet.contains(p.getUniqname())) { // no entry for the account yet rv.add(p); uniqnameSet.add(p.getUniqname()); } else { // found duplicates s.add(p.getUniqname()); } } if (!s.isEmpty()) { int count = 0; String accounts = ""; for (Iterator i = s.iterator(); i.hasNext();) { if (count == 0) { accounts = (String) i.next(); } else { accounts = accounts + ", " + (String) i.next(); } count++; } if (count == 1) { addAlert(state, rb.getString("add.duplicatedpart.single") + accounts + "."); } else { addAlert(state, rb.getString("add.duplicatedpart") + accounts + "."); } } return rv; } private String getSetupRequestEmailAddress() { String from = ServerConfigurationService.getString("setup.request", null); if (from == null) { from = "postmaster@".concat(ServerConfigurationService .getServerName()); M_log.warn(this + " - no 'setup.request' in configuration, using: "+ from); } return from; } /** * addNewSite is called when the site has enough information to create a new * site * */ private void addNewSite(ParameterParser params, SessionState state) { if (getStateSite(state) != null) { // There is a Site in state already, so use it rather than creating // a new Site return; } // If cleanState() has removed SiteInfo, get a new instance into state SiteInfo siteInfo = new SiteInfo(); if (state.getAttribute(STATE_SITE_INFO) != null) { siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO); } String id = StringUtil.trimToNull(siteInfo.getSiteId()); if (id == null) { // get id id = IdManager.createUuid(); siteInfo.site_id = id; } state.setAttribute(STATE_SITE_INFO, siteInfo); if (state.getAttribute(STATE_MESSAGE) == null) { try { Site site = null; // if create based on template, Site templateSite = (Site) state.getAttribute(STATE_TEMPLATE_SITE); if (templateSite != null) { site = SiteService.addSite(id, templateSite); } else { site = SiteService.addSite(id, siteInfo.site_type); } // add current user as the maintainer site.addMember(UserDirectoryService.getCurrentUser().getId(), site.getMaintainRole(), true, false); String title = StringUtil.trimToNull(siteInfo.title); String description = siteInfo.description; setAppearance(state, site, siteInfo.iconUrl); site.setDescription(description); if (title != null) { site.setTitle(title); } site.setType(siteInfo.site_type); ResourcePropertiesEdit rp = site.getPropertiesEdit(); site.setShortDescription(siteInfo.short_description); site.setPubView(siteInfo.include); site.setJoinable(siteInfo.joinable); site.setJoinerRole(siteInfo.joinerRole); site.setPublished(siteInfo.published); // site contact information rp.addProperty(PROP_SITE_CONTACT_NAME, siteInfo.site_contact_name); rp.addProperty(PROP_SITE_CONTACT_EMAIL, siteInfo.site_contact_email); state.setAttribute(STATE_SITE_INSTANCE_ID, site.getId()); // create an alias for the site if (!siteInfo.url_alias.equals(NULL_STRING)) { String alias = siteInfo.url_alias; String siteReference = site.getReference(); try { AliasService.setAlias(alias, siteReference); // In case of failure, return to the confirmation page // with an error and undo the site creation we've done so far } catch (IdUsedException ee) { addAlert(state, rb.getString("java.alias") + " " + alias + " " + rb.getString("java.exists")); } catch (IdInvalidException ee) { addAlert(state, rb.getString("java.alias") + " " + alias + " " + rb.getString("java.isinval")); } catch (PermissionException ee) { M_log.warn(SessionManager.getCurrentSessionUserId() + " does not have permission to add alias. "); } } // commit newly added site in order to enable related realm commitSite(site); } catch (IdUsedException e) { addAlert(state, rb.getString("java.sitewithid") + " " + id + " " + rb.getString("java.exists")); M_log.warn(this + ".addNewSite: " + rb.getString("java.sitewithid") + " " + id + " " + rb.getString("java.exists"), e); state.setAttribute(STATE_TEMPLATE_INDEX, params.getString("templateIndex")); return; } catch (IdInvalidException e) { addAlert(state, rb.getString("java.thesiteid") + " " + id + " " + rb.getString("java.notvalid")); M_log.warn(this + ".addNewSite: " + rb.getString("java.thesiteid") + " " + id + " " + rb.getString("java.notvalid"), e); state.setAttribute(STATE_TEMPLATE_INDEX, params.getString("templateIndex")); return; } catch (PermissionException e) { addAlert(state, rb.getString("java.permission") + " " + id + "."); M_log.warn(this + ".addNewSite: " + rb.getString("java.permission") + " " + id + ".", e); state.setAttribute(STATE_TEMPLATE_INDEX, params.getString("templateIndex")); return; } } } // addNewSite private void sendTemplateUseNotification(Site site, User currentUser, Site templateSite) { // send an email to track who are using the template String from = getSetupRequestEmailAddress(); // send it to the email archive of the template site // TODO: need a better way to get the email archive address //String domain = from.substring(from.indexOf('@')); String templateEmailArchive = templateSite.getId() + "@" + ServerConfigurationService.getServerName(); String to = templateEmailArchive; String headerTo = templateEmailArchive; String replyTo = templateEmailArchive; String message_subject = templateSite.getId() + ": copied by " + currentUser.getDisplayId (); if (from != null && templateEmailArchive != null) { StringBuffer buf = new StringBuffer(); buf.setLength(0); // email body buf.append("Dear template maintainer,\n\n"); buf.append("Congratulations!\n\n"); buf.append("The following user just created a new site based on your template.\n\n"); buf.append("Template name: " + templateSite.getTitle() + "\n"); buf.append("User : " + currentUser.getDisplayName() + " (" + currentUser.getDisplayId () + ")\n"); buf.append("Date : " + new java.util.Date() + "\n"); buf.append("New site Id : " + site.getId() + "\n"); buf.append("New site name: " + site.getTitle() + "\n\n"); buf.append("Cheers,\n"); buf.append("Alliance Team\n"); String content = buf.toString(); EmailService.send(from, to, message_subject, content, headerTo, replyTo, null); } } /** * created based on setTermListForContext - Denny * @param context * @param state */ private void setTemplateListForContext(Context context, SessionState state) { Hashtable<String, List<Site>> templateList = new Hashtable<String, List<Site>>(); // find all template sites. // need to have a default OOTB template site definition to faciliate testing without changing the sakai.properties file. String[] siteTemplates = siteTemplates = StringUtil.split(ServerConfigurationService.getString("site.templates", "template"), ","); for (String siteTemplateId:siteTemplates) { try { Site siteTemplate = SiteService.getSite(siteTemplateId); if (siteTemplate != null) { // get the type of template String type = siteTemplate.getType(); if (type != null) { // populate the list according to template site type List<Site> subTemplateList = new Vector<Site>(); if (templateList.containsKey(type)) { subTemplateList = templateList.get(type); } subTemplateList.add(siteTemplate); templateList.put(type, subTemplateList); } } } catch (IdUnusedException e) { M_log.info(this + ".setTemplateListForContext: cannot find site with id " + siteTemplateId); } } context.put("templateList", templateList); } // setTemplateListForContext /** * %%% legacy properties, to be cleaned up * */ private void sitePropertiesIntoState(SessionState state) { try { Site site = getStateSite(state); SiteInfo siteInfo = new SiteInfo(); if (site != null) { // set from site attributes siteInfo.title = site.getTitle(); siteInfo.description = site.getDescription(); siteInfo.iconUrl = site.getIconUrl(); siteInfo.infoUrl = site.getInfoUrl(); siteInfo.joinable = site.isJoinable(); siteInfo.joinerRole = site.getJoinerRole(); siteInfo.published = site.isPublished(); siteInfo.include = site.isPubView(); siteInfo.short_description = site.getShortDescription(); } siteInfo.additional = ""; state.setAttribute(STATE_SITE_TYPE, siteInfo.site_type); state.setAttribute(STATE_SITE_INFO, siteInfo); } catch (Exception e) { M_log.warn(this + ".sitePropertiesIntoState: " + e.getMessage(), e); } } // sitePropertiesIntoState /** * pageMatchesPattern returns tool id if a SitePage matches a WorkSite Setuppattern * otherwise return null * @param state * @param page * @return */ private String pageMatchesPattern(SessionState state, SitePage page) { List pageToolList = page.getTools(); // if no tools on the page, return false if (pageToolList == null || pageToolList.size() == 0) { return null; } // don't compare tool properties, which may be changed using Options List toolList = new Vector(); int count = pageToolList.size(); // check Home tool first if (pageHasToolId(pageToolList, getHomeToolId(state))) return getHomeToolId(state); // Other than Home page, no other page is allowed to have more than one tool within. Otherwise, WSetup/Site Info tool won't handle it if (count != 1) { return null; } // if the page layout doesn't match, return false else if (page.getLayout() != SitePage.LAYOUT_SINGLE_COL) { return null; } else { // for the case where the page has one tool ToolConfiguration toolConfiguration = (ToolConfiguration) pageToolList.get(0); toolList = (List) state.getAttribute(STATE_TOOL_REGISTRATION_LIST); if (pageToolList != null || pageToolList.size() != 0) { // if tool attributes don't match, return false String match = null; for (ListIterator i = toolList.listIterator(); i.hasNext();) { MyTool tool = (MyTool) i.next(); if (toolConfiguration.getTitle() != null) { if (toolConfiguration.getTool() != null && toolConfiguration.getTool().getId().indexOf( tool.getId()) != -1) { match = tool.getId(); } } } return match; } } return null; } // pageMatchesPattern /** * check whether the page tool list contains certain toolId * @param pageToolList * @param toolId * @return */ private boolean pageHasToolId(List pageToolList, String toolId) { for (Iterator iPageToolList = pageToolList.iterator(); iPageToolList.hasNext();) { ToolConfiguration toolConfiguration = (ToolConfiguration) iPageToolList.next(); Tool t = toolConfiguration.getTool(); if (t != null && toolId.equals(toolConfiguration.getTool().getId())) { return true; } } return false; } /** * siteToolsIntoState is the replacement for siteToolsIntoState_ Make a list * of pages and tools that match WorkSite Setup configurations into state */ private void siteToolsIntoState(SessionState state) { // get the map of titles of multiple tool instances Map multipleToolIdTitleMap = state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP) != null? (Map) state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP):new HashMap(); String wSetupTool = NULL_STRING; List wSetupPageList = new Vector(); Site site = getStateSite(state); List pageList = site.getPages(); // Put up tool lists filtered by category String type = checkNullSiteType(state, site); if (type == null) { M_log.warn(this + ": - unknown STATE_SITE_TYPE"); } else { state.setAttribute(STATE_SITE_TYPE, type); } // set tool registration list setToolRegistrationList(state, type); List toolRegList = (List) state.getAttribute(STATE_TOOL_REGISTRATION_LIST); // for the selected tools boolean check_home = false; Vector idSelected = new Vector(); if (!((pageList == null) || (pageList.size() == 0))) { for (ListIterator i = pageList.listIterator(); i.hasNext();) { SitePage page = (SitePage) i.next(); // collect the pages consistent with Worksite Setup patterns wSetupTool = pageMatchesPattern(state, page); if (wSetupTool != null) { if (wSetupTool.equals(getHomeToolId(state))) { check_home = true; } else { if (isMultipleInstancesAllowed(findOriginalToolId(state, wSetupTool))) { String mId = page.getId() + wSetupTool; idSelected.add(mId); multipleToolIdTitleMap.put(mId, page.getTitle()); MyTool newTool = new MyTool(); newTool.title = ToolManager.getTool(wSetupTool).getTitle(); newTool.id = mId; newTool.selected = false; boolean hasThisMultipleTool = false; int j = 0; for (; j < toolRegList.size() && !hasThisMultipleTool; j++) { MyTool t = (MyTool) toolRegList.get(j); if (t.getId().equals(wSetupTool)) { hasThisMultipleTool = true; newTool.description = t.getDescription(); } } if (hasThisMultipleTool) { toolRegList.add(j - 1, newTool); } else { toolRegList.add(newTool); } } else { idSelected.add(wSetupTool); } } WorksiteSetupPage wSetupPage = new WorksiteSetupPage(); wSetupPage.pageId = page.getId(); wSetupPage.pageTitle = page.getTitle(); wSetupPage.toolId = wSetupTool; wSetupPageList.add(wSetupPage); } } } state.setAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP, multipleToolIdTitleMap); state.setAttribute(STATE_TOOL_HOME_SELECTED, new Boolean(check_home)); state.setAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST, idSelected); // List state.setAttribute(STATE_TOOL_REGISTRATION_LIST, toolRegList); // of // ToolRegistration // toolId's state.setAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST,idSelected); // List of ToolRegistration toolId's state.setAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME, Boolean.valueOf(check_home)); state.setAttribute(STATE_WORKSITE_SETUP_PAGE_LIST, wSetupPageList); } // siteToolsIntoState /** * adjust site type * @param state * @param site * @return */ private String checkNullSiteType(SessionState state, Site site) { String type = site.getType(); if (type == null) { if (SiteService.isUserSite(site.getId())) { type = "myworkspace"; } else if (state.getAttribute(STATE_DEFAULT_SITE_TYPE) != null) { // for those sites without type, use the tool set for default // site type type = (String) state.getAttribute(STATE_DEFAULT_SITE_TYPE); } } return type; } /** * reset the state variables used in edit tools mode * * @state The SessionState object */ private void removeEditToolState(SessionState state) { state.removeAttribute(STATE_TOOL_HOME_SELECTED); state.removeAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); // List // of // ToolRegistration // toolId's state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST); // List // of // ToolRegistration // toolId's state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME); state.removeAttribute(STATE_WORKSITE_SETUP_PAGE_LIST); state.removeAttribute(STATE_MULTIPLE_TOOL_ID_SET); //state.removeAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP); } private List orderToolIds(SessionState state, String type, List toolIdList) { List rv = new Vector(); if (state.getAttribute(STATE_TOOL_HOME_SELECTED) != null && ((Boolean) state.getAttribute(STATE_TOOL_HOME_SELECTED)) .booleanValue()) { rv.add(getHomeToolId(state)); } // look for null site type if (type == null && state.getAttribute(STATE_DEFAULT_SITE_TYPE) != null) { type = (String) state.getAttribute(STATE_DEFAULT_SITE_TYPE); } if (type != null && toolIdList != null) { Set categories = new HashSet(); categories.add(type); Set tools = ToolManager.findTools(categories, null); SortedIterator i = new SortedIterator(tools.iterator(), new ToolComparator()); for (; i.hasNext();) { String tool_id = ((Tool) i.next()).getId(); for (ListIterator j = toolIdList.listIterator(); j.hasNext();) { String toolId = (String) j.next(); String rToolId = originalToolId(toolId, tool_id); if (rToolId != null) { rv.add(toolId); } } } } return rv; } // orderToolIds private void setupFormNamesAndConstants(SessionState state) { TimeBreakdown timeBreakdown = (TimeService.newTime()).breakdownLocal(); String mycopyright = COPYRIGHT_SYMBOL + " " + timeBreakdown.getYear() + ", " + UserDirectoryService.getCurrentUser().getDisplayName() + ". All Rights Reserved. "; state.setAttribute(STATE_MY_COPYRIGHT, mycopyright); state.setAttribute(STATE_SITE_INSTANCE_ID, null); state.setAttribute(STATE_INITIALIZED, Boolean.TRUE.toString()); SiteInfo siteInfo = new SiteInfo(); Participant participant = new Participant(); participant.name = NULL_STRING; participant.uniqname = NULL_STRING; participant.active = true; state.setAttribute(STATE_SITE_INFO, siteInfo); state.setAttribute("form_participantToAdd", participant); state.setAttribute(FORM_ADDITIONAL, NULL_STRING); // legacy state.setAttribute(FORM_HONORIFIC, "0"); state.setAttribute(FORM_REUSE, "0"); state.setAttribute(FORM_RELATED_CLASS, "0"); state.setAttribute(FORM_RELATED_PROJECT, "0"); state.setAttribute(FORM_INSTITUTION, "0"); // sundry form variables state.setAttribute(FORM_PHONE, ""); state.setAttribute(FORM_EMAIL, ""); state.setAttribute(FORM_SUBJECT, ""); state.setAttribute(FORM_DESCRIPTION, ""); state.setAttribute(FORM_TITLE, ""); state.setAttribute(FORM_NAME, ""); state.setAttribute(FORM_SHORT_DESCRIPTION, ""); } // setupFormNamesAndConstants /** * setupSkins * */ private void setupIcons(SessionState state) { List icons = new Vector(); String[] iconNames = null; String[] iconUrls = null; String[] iconSkins = null; // get icon information if (ServerConfigurationService.getStrings("iconNames") != null) { iconNames = ServerConfigurationService.getStrings("iconNames"); } if (ServerConfigurationService.getStrings("iconUrls") != null) { iconUrls = ServerConfigurationService.getStrings("iconUrls"); } if (ServerConfigurationService.getStrings("iconSkins") != null) { iconSkins = ServerConfigurationService.getStrings("iconSkins"); } if ((iconNames != null) && (iconUrls != null) && (iconSkins != null) && (iconNames.length == iconUrls.length) && (iconNames.length == iconSkins.length)) { for (int i = 0; i < iconNames.length; i++) { MyIcon s = new MyIcon(StringUtil.trimToNull((String) iconNames[i]), StringUtil.trimToNull((String) iconUrls[i]), StringUtil .trimToNull((String) iconSkins[i])); icons.add(s); } } state.setAttribute(STATE_ICONS, icons); } private void setAppearance(SessionState state, Site edit, String iconUrl) { // set the icon edit.setIconUrl(iconUrl); if (iconUrl == null) { // this is the default case - no icon, no (default) skin edit.setSkin(null); return; } // if this icon is in the config appearance list, find a skin to set List icons = (List) state.getAttribute(STATE_ICONS); for (Iterator i = icons.iterator(); i.hasNext();) { Object icon = (Object) i.next(); if (icon instanceof MyIcon && !StringUtil.different(((MyIcon) icon).getUrl(), iconUrl)) { edit.setSkin(((MyIcon) icon).getSkin()); return; } } } /** * A dispatch funtion when selecting course features */ public void doAdd_features(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String option = params.getString("option"); // to reset the state variable of the multiple tool instances Set multipleToolIdSet = state.getAttribute(STATE_MULTIPLE_TOOL_ID_SET) != null? (Set) state.getAttribute(STATE_MULTIPLE_TOOL_ID_SET):new HashSet(); // get the map of titles of multiple tool instances Map multipleToolIdTitleMap = state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP) != null? (Map) state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP):new HashMap(); // editing existing site or creating a new one? Site site = getStateSite(state); // dispatch if (option.startsWith("add_")) { // this could be format of originalToolId plus number of multiplication String addToolId = option.substring("add_".length(), option.length()); // find the original tool id String originToolId = findOriginalToolId(state, addToolId); if (originToolId != null) { Tool tool = ToolManager.getTool(originToolId); if (tool != null) { insertTool(state, originToolId, tool.getTitle(), tool.getDescription(), Integer.parseInt(params.getString("num_"+ addToolId))); updateSelectedToolList(state, params, false); state.setAttribute(STATE_TEMPLATE_INDEX, "26"); } } } else if (option.equalsIgnoreCase("import")) { // import or not updateSelectedToolList(state, params, false); String importSites = params.getString("import"); if (importSites != null && importSites.equalsIgnoreCase(Boolean.TRUE.toString())) { state.setAttribute(STATE_IMPORT, Boolean.TRUE); if (importSites.equalsIgnoreCase(Boolean.TRUE.toString())) { state.removeAttribute(STATE_IMPORT); state.removeAttribute(STATE_IMPORT_SITES); state.removeAttribute(STATE_IMPORT_SITE_TOOL); } } else { state.removeAttribute(STATE_IMPORT); } } else if (option.equalsIgnoreCase("continue")) { // continue updateSelectedToolList(state, params, false); doContinue(data); } else if (option.equalsIgnoreCase("back")) { // back doBack(data); } else if (option.equalsIgnoreCase("cancel")) { if (site == null) { // cancel doCancel_create(data); } else { // cancel editing doCancel(data); } } } // doAdd_features /** * update the selected tool list * * @param params * The ParameterParser object * @param updateConfigVariables * Need to update configuration variables */ private void updateSelectedToolList(SessionState state, ParameterParser params, boolean updateConfigVariables) { List selectedTools = new ArrayList(Arrays.asList(params .getStrings("selectedTools"))); Set multipleToolIdSet = (Set) state.getAttribute(STATE_MULTIPLE_TOOL_ID_SET); Map multipleToolIdTitleMap = state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP) != null? (Map) state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP):new HashMap(); Hashtable<String, Hashtable<String, String>> multipleToolConfiguration = state.getAttribute(STATE_MULTIPLE_TOOL_CONFIGURATION) != null?(Hashtable<String, Hashtable<String, String>>) state.getAttribute(STATE_MULTIPLE_TOOL_CONFIGURATION):new Hashtable<String, Hashtable<String, String>>(); Vector<String> idSelected = (Vector<String>) state.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST); boolean has_home = false; String emailId = null; for (int i = 0; i < selectedTools.size(); i++) { String id = (String) selectedTools.get(i); if (id.equalsIgnoreCase(getHomeToolId(state))) { has_home = true; } else if (id.equalsIgnoreCase("sakai.mailbox")) { if ( updateConfigVariables ) { // if Email archive tool is selected, check the email alias emailId = StringUtil.trimToNull(params.getString("emailId")); if (emailId == null) { addAlert(state, rb.getString("java.emailarchive") + " "); } else { if (!Validator.checkEmailLocal(emailId)) { addAlert(state, rb.getString("java.theemail")); } else { // check to see whether the alias has been used by // other sites try { String target = AliasService.getTarget(emailId); if (target != null) { if (state .getAttribute(STATE_SITE_INSTANCE_ID) != null) { String siteId = (String) state .getAttribute(STATE_SITE_INSTANCE_ID); String channelReference = mailArchiveChannelReference(siteId); if (!target.equals(channelReference)) { // the email alias is not used by // current site addAlert(state, rb.getString("java.emailinuse") + " "); } } else { addAlert(state, rb.getString("java.emailinuse") + " "); } } } catch (IdUnusedException ee) { } } } state.setAttribute(STATE_TOOL_EMAIL_ADDRESS, emailId); } } else if (isMultipleInstancesAllowed(findOriginalToolId(state, id)) && (idSelected != null && !idSelected.contains(id) || idSelected == null) && updateConfigVariables) { // newly added mutliple instances String title = StringUtil.trimToNull(params.getString("title_" + id)); if (title != null) { // save the titles entered multipleToolIdTitleMap.put(id, title); } // get the attribute input Hashtable<String, String> attributes = multipleToolConfiguration.get(id); if (attributes == null) { // if missing, get the default setting for original id attributes = multipleToolConfiguration.get(findOriginalToolId(state, id)); } if (attributes != null) { for(Enumeration<String> e = attributes.keys(); e.hasMoreElements();) { String attribute = e.nextElement(); String attributeInput = StringUtil.trimToNull(params.getString(attribute + "_" + id)); if (attributeInput != null) { // save the attribute input attributes.put(attribute, attributeInput); } } multipleToolConfiguration.put(id, attributes); } // update the state objects state.setAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP, multipleToolIdTitleMap); state.setAttribute(STATE_MULTIPLE_TOOL_CONFIGURATION, multipleToolConfiguration); } } state.setAttribute(STATE_TOOL_HOME_SELECTED, new Boolean(has_home)); } // updateSelectedToolList /** * find the tool in the tool list and insert another tool instance to the list * @param state * @param toolId * @param defaultTitle * @param defaultDescription * @param insertTimes */ private void insertTool(SessionState state, String toolId, String defaultTitle, String defaultDescription, int insertTimes) { // the list of available tools List toolList = (List) state.getAttribute(STATE_TOOL_REGISTRATION_LIST); List oTools = state.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST) == null? new Vector():(List) state.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST); // get the map of titles of multiple tool instances Map multipleToolIdTitleMap = state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP) != null? (Map) state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP):new HashMap(); // get the attributes of multiple tool instances Hashtable<String, Hashtable<String, String>> multipleToolConfiguration = state.getAttribute(STATE_MULTIPLE_TOOL_CONFIGURATION) != null?(Hashtable<String, Hashtable<String, String>>) state.getAttribute(STATE_MULTIPLE_TOOL_CONFIGURATION):new Hashtable<String, Hashtable<String, String>>(); int toolListedTimes = 0; int index = 0; int insertIndex = 0; while (index < toolList.size()) { MyTool tListed = (MyTool) toolList.get(index); if (tListed.getId().indexOf(toolId) != -1 && !oTools.contains(tListed.getId())) { toolListedTimes++; } if (toolListedTimes > 0 && insertIndex == 0) { // update the insert index insertIndex = index; } index++; } List toolSelected = (List) state .getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); // insert multiple tools for (int i = 0; i < insertTimes; i++) { toolSelected.add(toolId + toolListedTimes); // We need to insert a specific tool entry only if all the specific // tool entries have been selected String newToolId = toolId + toolListedTimes; MyTool newTool = new MyTool(); newTool.title = defaultTitle; newTool.id = newToolId; newTool.description = defaultDescription; toolList.add(insertIndex, newTool); toolListedTimes++; // add title multipleToolIdTitleMap.put(newTool.id, defaultTitle); // get the attribute input Hashtable<String, String> attributes = multipleToolConfiguration.get(newToolId); if (attributes == null) { // if missing, get the default setting for original id attributes = new Hashtable<String, String>(); Hashtable<String, String> oAttributes = multipleToolConfiguration.get(findOriginalToolId(state, newToolId)); // add the entry for the newly added tool if (attributes != null) { attributes = (Hashtable<String, String>) oAttributes.clone(); multipleToolConfiguration.put(newToolId, attributes); } } } state.setAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP, multipleToolIdTitleMap); state.setAttribute(STATE_MULTIPLE_TOOL_CONFIGURATION, multipleToolConfiguration); state.setAttribute(STATE_TOOL_REGISTRATION_LIST, toolList); state.setAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST, toolSelected); } // insertTool /** * * set selected participant role Hashtable */ private void setSelectedParticipantRoles(SessionState state) { List selectedUserIds = (List) state .getAttribute(STATE_SELECTED_USER_LIST); List participantList = collectionToList((Collection) state.getAttribute(STATE_PARTICIPANT_LIST)); List selectedParticipantList = new Vector(); Hashtable selectedParticipantRoles = new Hashtable(); if (!selectedUserIds.isEmpty() && participantList != null) { for (int i = 0; i < participantList.size(); i++) { String id = ""; Object o = (Object) participantList.get(i); if (o.getClass().equals(Participant.class)) { // get participant roles id = ((Participant) o).getUniqname(); selectedParticipantRoles.put(id, ((Participant) o) .getRole()); } if (selectedUserIds.contains(id)) { selectedParticipantList.add(participantList.get(i)); } } } state.setAttribute(STATE_SELECTED_PARTICIPANT_ROLES, selectedParticipantRoles); state .setAttribute(STATE_SELECTED_PARTICIPANTS, selectedParticipantList); } // setSelectedParticipantRol3es public class MyIcon { protected String m_name = null; protected String m_url = null; protected String m_skin = null; public MyIcon(String name, String url, String skin) { m_name = name; m_url = url; m_skin = skin; } public String getName() { return m_name; } public String getUrl() { return m_url; } public String getSkin() { return m_skin; } } // a utility class for working with ToolConfigurations and ToolRegistrations // %%% convert featureList from IdAndText to Tool so getFeatures item.id = // chosen-feature.id is a direct mapping of data public class MyTool { public String id = NULL_STRING; public String title = NULL_STRING; public String description = NULL_STRING; public boolean selected = false; public String getId() { return id; } public String getTitle() { return title; } public String getDescription() { return description; } public boolean getSelected() { return selected; } } /* * WorksiteSetupPage is a utility class for working with site pages * configured by Worksite Setup * */ public class WorksiteSetupPage { public String pageId = NULL_STRING; public String pageTitle = NULL_STRING; public String toolId = NULL_STRING; public String getPageId() { return pageId; } public String getPageTitle() { return pageTitle; } public String getToolId() { return toolId; } } // WorksiteSetupPage public class SiteInfo { public String site_id = NULL_STRING; // getId of Resource public String external_id = NULL_STRING; // if matches site_id // connects site with U-M // course information public String site_type = ""; public String iconUrl = NULL_STRING; public String infoUrl = NULL_STRING; public boolean joinable = false; public String joinerRole = NULL_STRING; public String title = NULL_STRING; // the short name of the site public String url_alias = NULL_STRING; // the url alias for the site public String short_description = NULL_STRING; // the short (20 char) // description of the // site public String description = NULL_STRING; // the longer description of // the site public String additional = NULL_STRING; // additional information on // crosslists, etc. public boolean published = false; public boolean include = true; // include the site in the Sites index; // default is true. public String site_contact_name = NULL_STRING; // site contact name public String site_contact_email = NULL_STRING; // site contact email public String getSiteId() { return site_id; } public String getSiteType() { return site_type; } public String getTitle() { return title; } public String getDescription() { return description; } public String getIconUrl() { return iconUrl; } public String getInfoUrll() { return infoUrl; } public boolean getJoinable() { return joinable; } public String getJoinerRole() { return joinerRole; } public String getAdditional() { return additional; } public boolean getPublished() { return published; } public boolean getInclude() { return include; } public String getSiteContactName() { return site_contact_name; } public String getSiteContactEmail() { return site_contact_email; } public void setUrlAlias(String urlAlias) { this.url_alias = urlAlias; } public String getUrlAlias() { return url_alias; } } // SiteInfo // dissertation tool related /** * doFinish_grad_tools is called when creation of a Grad Tools site is * confirmed */ public void doFinish_grad_tools(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); // set up for the coming template state.setAttribute(STATE_TEMPLATE_INDEX, params.getString("continue")); int index = Integer.valueOf(params.getString("templateIndex")) .intValue(); actionForTemplate("continue", index, params, state); // add the pre-configured Grad Tools tools to a new site addGradToolsFeatures(state); // TODO: hard coding this frame id is fragile, portal dependent, and // needs to be fixed -ggolden // schedulePeerFrameRefresh("sitenav"); scheduleTopRefresh(); resetPaging(state); }// doFinish_grad_tools /** * addGradToolsFeatures adds features to a new Grad Tools student site * */ private void addGradToolsFeatures(SessionState state) { Site edit = null; Site template = null; // get a unique id String id = IdManager.createUuid(); // get the Grad Tools student site template try { template = SiteService.getSite(SITE_GTS_TEMPLATE); } catch (Exception e) { M_log.warn(this + ".addGradToolsFeatures:" + e.getMessage() + SITE_GTS_TEMPLATE, e); } if (template != null) { // create a new site based on the template try { edit = SiteService.addSite(id, template); } catch (Exception e) { M_log.warn(this + ".addGradToolsFeatures:" + " add/edit site id=" + id, e); } // set the tab, etc. if (edit != null) { SiteInfo siteInfo = (SiteInfo) state .getAttribute(STATE_SITE_INFO); edit.setShortDescription(siteInfo.short_description); edit.setTitle(siteInfo.title); edit.setPublished(true); edit.setPubView(false); edit.setType(SITE_TYPE_GRADTOOLS_STUDENT); // ResourcePropertiesEdit rpe = edit.getPropertiesEdit(); try { SiteService.save(edit); } catch (Exception e) { M_log.warn(this + ".addGradToolsFeatures:" + " commitEdit site id=" + id, e); } // now that the site and realm exist, we can set the email alias // set the GradToolsStudent site alias as: // gradtools-uniqname@servername String alias = "gradtools-" + SessionManager.getCurrentSessionUserId(); String channelReference = mailArchiveChannelReference(id); try { AliasService.setAlias(alias, channelReference); } catch (IdUsedException ee) { addAlert(state, rb.getString("java.alias") + " " + alias + " " + rb.getString("java.exists")); M_log.warn(this + ".addGradToolsFeatures:" + rb.getString("java.alias") + " " + alias + " " + rb.getString("java.exists"), ee); } catch (IdInvalidException ee) { addAlert(state, rb.getString("java.alias") + " " + alias + " " + rb.getString("java.isinval")); M_log.warn(this + ".addGradToolsFeatures:" + rb.getString("java.alias") + " " + alias + " " + rb.getString("java.isinval"), ee); } catch (PermissionException ee) { M_log.warn(this + ".addGradToolsFeatures:" + SessionManager.getCurrentSessionUserId() + " does not have permission to add alias. ", ee); } } } } // addGradToolsFeatures /** * handle with add site options * */ public void doAdd_site_option(RunData data) { String option = data.getParameters().getString("option"); if (option.equals("finish")) { doFinish(data); } else if (option.equals("cancel")) { doCancel_create(data); } else if (option.equals("back")) { doBack(data); } } // doAdd_site_option /** * handle with duplicate site options * */ public void doDuplicate_site_option(RunData data) { String option = data.getParameters().getString("option"); if (option.equals("duplicate")) { doContinue(data); } else if (option.equals("cancel")) { doCancel(data); } else if (option.equals("finish")) { doContinue(data); } } // doDuplicate_site_option /** * Special check against the Dissertation service, which might not be * here... * * @return */ protected boolean isGradToolsCandidate(String userId) { // DissertationService.isCandidate(userId) - but the hard way Object service = ComponentManager .get("org.sakaiproject.api.app.dissertation.DissertationService"); if (service == null) return false; // the method signature Class[] signature = new Class[1]; signature[0] = String.class; // the method name String methodName = "isCandidate"; // find a method of this class with this name and signature try { Method method = service.getClass().getMethod(methodName, signature); // the parameters Object[] args = new Object[1]; args[0] = userId; // make the call Boolean rv = (Boolean) method.invoke(service, args); return rv.booleanValue(); } catch (Throwable t) { } return false; } /** * User has a Grad Tools student site * * @return */ protected boolean hasGradToolsStudentSite(String userId) { boolean has = false; int n = 0; try { n = SiteService.countSites( org.sakaiproject.site.api.SiteService.SelectionType.UPDATE, SITE_TYPE_GRADTOOLS_STUDENT, null, null); if (n > 0) has = true; } catch (Exception e) { M_log.warn(this + ".addGradToolsStudentSite:" + e.getMessage(), e); } return has; }// hasGradToolsStudentSite /** * Get the mail archive channel reference for the main container placement * for this site. * * @param siteId * The site id. * @return The mail archive channel reference for this site. */ protected String mailArchiveChannelReference(String siteId) { Object m = ComponentManager .get("org.sakaiproject.mailarchive.api.MailArchiveService"); if (m != null) { return "/mailarchive"+Entity.SEPARATOR+"channel"+Entity.SEPARATOR+siteId+Entity.SEPARATOR+SiteService.MAIN_CONTAINER; } else { return ""; } } /** * Transfer a copy of all entites from another context for any entity * producer that claims this tool id. * * @param toolId * The tool id. * @param fromContext * The context to import from. * @param toContext * The context to import into. */ protected void transferCopyEntities(String toolId, String fromContext, String toContext) { // TODO: used to offer to resources first - why? still needed? -ggolden // offer to all EntityProducers for (Iterator i = EntityManager.getEntityProducers().iterator(); i .hasNext();) { EntityProducer ep = (EntityProducer) i.next(); if (ep instanceof EntityTransferrer) { try { EntityTransferrer et = (EntityTransferrer) ep; // if this producer claims this tool id if (ArrayUtil.contains(et.myToolIds(), toolId)) { et.transferCopyEntities(fromContext, toContext, new Vector()); } } catch (Throwable t) { M_log.warn(this + ".transferCopyEntities: Error encountered while asking EntityTransfer to transferCopyEntities from: " + fromContext + " to: " + toContext, t); } } } } protected void transferCopyEntitiesMigrate(String toolId, String fromContext, String toContext) { for (Iterator i = EntityManager.getEntityProducers().iterator(); i .hasNext();) { EntityProducer ep = (EntityProducer) i.next(); if (ep instanceof EntityTransferrer) { try { EntityTransferrer et = (EntityTransferrer) ep; // if this producer claims this tool id if (ArrayUtil.contains(et.myToolIds(), toolId)) { et.transferCopyEntities(fromContext, toContext, new Vector(), true); } } catch (Throwable t) { M_log.warn( "Error encountered while asking EntityTransfer to transferCopyEntities from: " + fromContext + " to: " + toContext, t); } } } } /** * @return Get a list of all tools that support the import (transfer copy) * option */ protected Set importTools() { HashSet rv = new HashSet(); // offer to all EntityProducers for (Iterator i = EntityManager.getEntityProducers().iterator(); i .hasNext();) { EntityProducer ep = (EntityProducer) i.next(); if (ep instanceof EntityTransferrer) { EntityTransferrer et = (EntityTransferrer) ep; String[] tools = et.myToolIds(); if (tools != null) { for (int t = 0; t < tools.length; t++) { rv.add(tools[t]); } } } } return rv; } /** * @param state * @return Get a list of all tools that should be included as options for * import */ protected List getToolsAvailableForImport(SessionState state, List<String> toolIdList) { // The Web Content and News tools do not follow the standard rules for // import // Even if the current site does not contain the tool, News and WC will // be // an option if the imported site contains it boolean displayWebContent = false; boolean displayNews = false; Set importSites = ((Hashtable) state.getAttribute(STATE_IMPORT_SITES)) .keySet(); Iterator sitesIter = importSites.iterator(); while (sitesIter.hasNext()) { Site site = (Site) sitesIter.next(); if (site.getToolForCommonId("sakai.iframe") != null) displayWebContent = true; if (site.getToolForCommonId("sakai.news") != null) displayNews = true; } if (displayWebContent && !toolIdList.contains("sakai.iframe")) toolIdList.add("sakai.iframe"); if (displayNews && !toolIdList.contains("sakai.news")) toolIdList.add("sakai.news"); return toolIdList; } // getToolsAvailableForImport private void setTermListForContext(Context context, SessionState state, boolean upcomingOnly) { List terms; if (upcomingOnly) { terms = cms != null?cms.getCurrentAcademicSessions():null; } else { // get all terms = cms != null?cms.getAcademicSessions():null; } if (terms != null && terms.size() > 0) { context.put("termList", terms); } } // setTermListForContext private void setSelectedTermForContext(Context context, SessionState state, String stateAttribute) { if (state.getAttribute(stateAttribute) != null) { context.put("selectedTerm", state.getAttribute(stateAttribute)); } } // setSelectedTermForContext /** * rewrote for 2.4 * * @param userId * @param academicSessionEid * @param courseOfferingHash * @param sectionHash */ private void prepareCourseAndSectionMap(String userId, String academicSessionEid, HashMap courseOfferingHash, HashMap sectionHash) { // looking for list of courseOffering and sections that should be // included in // the selection list. The course offering must be offered // 1. in the specific academic Session // 2. that the specified user has right to attach its section to a // course site // map = (section.eid, sakai rolename) if (groupProvider == null) { M_log.warn("Group provider not found"); return; } Map map = groupProvider.getGroupRolesForUser(userId); if (map == null) return; Set keys = map.keySet(); Set roleSet = getRolesAllowedToAttachSection(); for (Iterator i = keys.iterator(); i.hasNext();) { String sectionEid = (String) i.next(); String role = (String) map.get(sectionEid); if (includeRole(role, roleSet)) { Section section = null; getCourseOfferingAndSectionMap(academicSessionEid, courseOfferingHash, sectionHash, sectionEid, section); } } // now consider those user with affiliated sections List affiliatedSectionEids = affiliatedSectionProvider.getAffiliatedSectionEids(userId, academicSessionEid); if (affiliatedSectionEids != null) { for (int k = 0; k < affiliatedSectionEids.size(); k++) { String sectionEid = (String) affiliatedSectionEids.get(k); Section section = null; getCourseOfferingAndSectionMap(academicSessionEid, courseOfferingHash, sectionHash, sectionEid, section); } } } // prepareCourseAndSectionMap private void getCourseOfferingAndSectionMap(String academicSessionEid, HashMap courseOfferingHash, HashMap sectionHash, String sectionEid, Section section) { try { section = cms.getSection(sectionEid); } catch (IdNotFoundException e) { M_log.warn(this + ".getCourseOfferingAndSectionMap:" + " cannot find section id=" + sectionEid, e); } if (section != null) { String courseOfferingEid = section.getCourseOfferingEid(); CourseOffering courseOffering = cms .getCourseOffering(courseOfferingEid); String sessionEid = courseOffering.getAcademicSession() .getEid(); if (academicSessionEid.equals(sessionEid)) { // a long way to the conclusion that yes, this course // offering // should be included in the selected list. Sigh... // -daisyf ArrayList sectionList = (ArrayList) sectionHash .get(courseOffering.getEid()); if (sectionList == null) { sectionList = new ArrayList(); } sectionList.add(new SectionObject(section)); sectionHash.put(courseOffering.getEid(), sectionList); courseOfferingHash.put(courseOffering.getEid(), courseOffering); } } } /** * for 2.4 * * @param role * @return */ private boolean includeRole(String role, Set roleSet) { boolean includeRole = false; for (Iterator i = roleSet.iterator(); i.hasNext();) { String r = (String) i.next(); if (r.equals(role)) { includeRole = true; break; } } return includeRole; } // includeRole protected Set getRolesAllowedToAttachSection() { // Use !site.template.[site_type] String azgId = "!site.template.course"; AuthzGroup azgTemplate; try { azgTemplate = AuthzGroupService.getAuthzGroup(azgId); } catch (GroupNotDefinedException e) { M_log.warn(this + ".getRolesAllowedToAttachSection: Could not find authz group " + azgId, e); return new HashSet(); } Set roles = azgTemplate.getRolesIsAllowed("site.upd"); roles.addAll(azgTemplate.getRolesIsAllowed("realm.upd")); return roles; } // getRolesAllowedToAttachSection /** * Here, we will preapre two HashMap: 1. courseOfferingHash stores * courseOfferingId and CourseOffering 2. sectionHash stores * courseOfferingId and a list of its Section We sorted the CourseOffering * by its eid & title and went through them one at a time to construct the * CourseObject that is used for the displayed in velocity. Each * CourseObject will contains a list of CourseOfferingObject(again used for * vm display). Usually, a CourseObject would only contain one * CourseOfferingObject. A CourseObject containing multiple * CourseOfferingObject implies that this is a cross-listing situation. * * @param userId * @param academicSessionEid * @return */ private List prepareCourseAndSectionListing(String userId, String academicSessionEid, SessionState state) { // courseOfferingHash = (courseOfferingEid, vourseOffering) // sectionHash = (courseOfferingEid, list of sections) HashMap courseOfferingHash = new HashMap(); HashMap sectionHash = new HashMap(); prepareCourseAndSectionMap(userId, academicSessionEid, courseOfferingHash, sectionHash); // courseOfferingHash & sectionHash should now be filled with stuffs // put section list in state for later use state.setAttribute(STATE_PROVIDER_SECTION_LIST, getSectionList(sectionHash)); ArrayList offeringList = new ArrayList(); Set keys = courseOfferingHash.keySet(); for (Iterator i = keys.iterator(); i.hasNext();) { CourseOffering o = (CourseOffering) courseOfferingHash .get((String) i.next()); offeringList.add(o); } Collection offeringListSorted = sortOffering(offeringList); ArrayList resultedList = new ArrayList(); // use this to keep track of courseOffering that we have dealt with // already // this is important 'cos cross-listed offering is dealt with together // with its // equivalents ArrayList dealtWith = new ArrayList(); for (Iterator j = offeringListSorted.iterator(); j.hasNext();) { CourseOffering o = (CourseOffering) j.next(); if (!dealtWith.contains(o.getEid())) { // 1. construct list of CourseOfferingObject for CourseObject ArrayList l = new ArrayList(); CourseOfferingObject coo = new CourseOfferingObject(o, (ArrayList) sectionHash.get(o.getEid())); l.add(coo); // 2. check if course offering is cross-listed Set set = cms.getEquivalentCourseOfferings(o.getEid()); if (set != null) { for (Iterator k = set.iterator(); k.hasNext();) { CourseOffering eo = (CourseOffering) k.next(); if (courseOfferingHash.containsKey(eo.getEid())) { // => cross-listed, then list them together CourseOfferingObject coo_equivalent = new CourseOfferingObject( eo, (ArrayList) sectionHash.get(eo.getEid())); l.add(coo_equivalent); dealtWith.add(eo.getEid()); } } } CourseObject co = new CourseObject(o, l); dealtWith.add(o.getEid()); resultedList.add(co); } } return resultedList; } // prepareCourseAndSectionListing /** * Sort CourseOffering by order of eid, title uisng velocity SortTool * * @param offeringList * @return */ private Collection sortOffering(ArrayList offeringList) { return sortCmObject(offeringList); /* * List propsList = new ArrayList(); propsList.add("eid"); * propsList.add("title"); SortTool sort = new SortTool(); return * sort.sort(offeringList, propsList); */ } // sortOffering /** * sort any Cm object such as CourseOffering, CourseOfferingObject, * SectionObject provided object has getter & setter for eid & title * * @param list * @return */ private Collection sortCmObject(List list) { if (list != null) { List propsList = new ArrayList(); propsList.add("eid"); propsList.add("title"); SortTool sort = new SortTool(); return sort.sort(list, propsList); } else { return list; } } // sortCmObject /** * this object is used for displaying purposes in chef_site-newSiteCourse.vm */ public class SectionObject { public Section section; public String eid; public String title; public String category; public String categoryDescription; public boolean isLecture; public boolean attached; public String authorizer; public SectionObject(Section section) { this.section = section; this.eid = section.getEid(); this.title = section.getTitle(); this.category = section.getCategory(); this.categoryDescription = cms .getSectionCategoryDescription(section.getCategory()); if ("01.lct".equals(section.getCategory())) { this.isLecture = true; } else { this.isLecture = false; } Set set = authzGroupService.getAuthzGroupIds(section.getEid()); if (set != null && !set.isEmpty()) { this.attached = true; } else { this.attached = false; } } public Section getSection() { return section; } public String getEid() { return eid; } public String getTitle() { return title; } public String getCategory() { return category; } public String getCategoryDescription() { return categoryDescription; } public boolean getIsLecture() { return isLecture; } public boolean getAttached() { return attached; } public String getAuthorizer() { return authorizer; } public void setAuthorizer(String authorizer) { this.authorizer = authorizer; } } // SectionObject constructor /** * this object is used for displaying purposes in chef_site-newSiteCourse.vm */ public class CourseObject { public String eid; public String title; public List courseOfferingObjects; public CourseObject(CourseOffering offering, List courseOfferingObjects) { this.eid = offering.getEid(); this.title = offering.getTitle(); this.courseOfferingObjects = courseOfferingObjects; } public String getEid() { return eid; } public String getTitle() { return title; } public List getCourseOfferingObjects() { return courseOfferingObjects; } } // CourseObject constructor /** * this object is used for displaying purposes in chef_site-newSiteCourse.vm */ public class CourseOfferingObject { public String eid; public String title; public List sections; public CourseOfferingObject(CourseOffering offering, List unsortedSections) { List propsList = new ArrayList(); propsList.add("category"); propsList.add("eid"); SortTool sort = new SortTool(); this.sections = new ArrayList(); if (unsortedSections != null) { this.sections = (List) sort.sort(unsortedSections, propsList); } this.eid = offering.getEid(); this.title = offering.getTitle(); } public String getEid() { return eid; } public String getTitle() { return title; } public List getSections() { return sections; } } // CourseOfferingObject constructor /** * get campus user directory for dispaly in chef_newSiteCourse.vm * * @return */ private String getCampusDirectory() { return ServerConfigurationService.getString( "site-manage.campusUserDirectory", null); } // getCampusDirectory private void removeAnyFlagedSection(SessionState state, ParameterParser params) { List all = new ArrayList(); List providerCourseList = (List) state .getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN); if (providerCourseList != null && providerCourseList.size() > 0) { all.addAll(providerCourseList); } List manualCourseList = (List) state .getAttribute(SITE_MANUAL_COURSE_LIST); if (manualCourseList != null && manualCourseList.size() > 0) { all.addAll(manualCourseList); } for (int i = 0; i < all.size(); i++) { String eid = (String) all.get(i); String field = "removeSection" + eid; String toRemove = params.getString(field); if ("true".equals(toRemove)) { // eid is in either providerCourseList or manualCourseList // either way, just remove it if (providerCourseList != null) providerCourseList.remove(eid); if (manualCourseList != null) manualCourseList.remove(eid); } } List<SectionObject> requestedCMSections = (List<SectionObject>) state .getAttribute(STATE_CM_REQUESTED_SECTIONS); if (requestedCMSections != null) { for (int i = 0; i < requestedCMSections.size(); i++) { SectionObject so = (SectionObject) requestedCMSections.get(i); String field = "removeSection" + so.getEid(); String toRemove = params.getString(field); if ("true".equals(toRemove)) { requestedCMSections.remove(so); } } if (requestedCMSections.size() == 0) state.removeAttribute(STATE_CM_REQUESTED_SECTIONS); } List<SectionObject> authorizerSections = (List<SectionObject>) state .getAttribute(STATE_CM_AUTHORIZER_SECTIONS); if (authorizerSections != null) { for (int i = 0; i < authorizerSections.size(); i++) { SectionObject so = (SectionObject) authorizerSections.get(i); String field = "removeSection" + so.getEid(); String toRemove = params.getString(field); if ("true".equals(toRemove)) { authorizerSections.remove(so); } } if (authorizerSections.size() == 0) state.removeAttribute(STATE_CM_AUTHORIZER_SECTIONS); } // if list is empty, set to null. This is important 'cos null is // the indication that the list is empty in the code. See case 2 on line // 1081 if (manualCourseList != null && manualCourseList.size() == 0) manualCourseList = null; if (providerCourseList != null && providerCourseList.size() == 0) providerCourseList = null; } private void collectNewSiteInfo(SiteInfo siteInfo, SessionState state, ParameterParser params, List providerChosenList) { if (state.getAttribute(STATE_MESSAGE) == null) { siteInfo = new SiteInfo(); if (state.getAttribute(STATE_SITE_INFO) != null) { siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO); } // site title is the title of the 1st section selected - // daisyf's note if (providerChosenList != null && providerChosenList.size() >= 1) { String title = prepareTitle((List) state .getAttribute(STATE_PROVIDER_SECTION_LIST), providerChosenList); siteInfo.title = title; } state.setAttribute(STATE_SITE_INFO, siteInfo); if (params.getString("manualAdds") != null && ("true").equals(params.getString("manualAdds"))) { // if creating a new site state.setAttribute(STATE_TEMPLATE_INDEX, "37"); state.setAttribute(STATE_MANUAL_ADD_COURSE_NUMBER, new Integer( 1)); } else if (params.getString("findCourse") != null && ("true").equals(params.getString("findCourse"))) { state.setAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN, providerChosenList); prepFindPage(state); } else { // no manual add state.removeAttribute(STATE_MANUAL_ADD_COURSE_NUMBER); state.removeAttribute(STATE_MANUAL_ADD_COURSE_FIELDS); state.removeAttribute(STATE_SITE_QUEST_UNIQNAME); if (getStateSite(state) != null) { // if revising a site, go to the confirmation // page of adding classes //state.setAttribute(STATE_TEMPLATE_INDEX, "37"); } else { // if creating a site, go the the site // information entry page state.setAttribute(STATE_TEMPLATE_INDEX, "2"); } } } } /** * By default, courseManagement is implemented * * @return */ private boolean courseManagementIsImplemented() { boolean returnValue = true; String isImplemented = ServerConfigurationService.getString( "site-manage.courseManagementSystemImplemented", "true"); if (("false").equals(isImplemented)) returnValue = false; return returnValue; } private List getCMSections(String offeringEid) { if (offeringEid == null || offeringEid.trim().length() == 0) return null; if (cms != null) { Set sections = cms.getSections(offeringEid); Collection c = sortCmObject(new ArrayList(sections)); return (List) c; } return new ArrayList(0); } private List getCMCourseOfferings(String subjectEid, String termID) { if (subjectEid == null || subjectEid.trim().length() == 0 || termID == null || termID.trim().length() == 0) return null; if (cms != null) { Set offerings = cms.getCourseOfferingsInCourseSet(subjectEid);// , // termID); ArrayList returnList = new ArrayList(); Iterator coIt = offerings.iterator(); while (coIt.hasNext()) { CourseOffering co = (CourseOffering) coIt.next(); AcademicSession as = co.getAcademicSession(); if (as != null && as.getEid().equals(termID)) returnList.add(co); } Collection c = sortCmObject(returnList); return (List) c; } return new ArrayList(0); } private List<String> getCMLevelLabels() { List<String> rv = new Vector<String>(); Set courseSets = cms.getCourseSets(); String currentLevel = ""; rv = addCategories(rv, courseSets); // course and section exist in the CourseManagementService rv.add(rb.getString("cm.level.course")); rv.add(rb.getString("cm.level.section")); return rv; } /** * a recursive function to add courseset categories * @param rv * @param courseSets */ private List<String> addCategories(List<String> rv, Set courseSets) { if (courseSets != null) { for (Iterator i = courseSets.iterator(); i.hasNext();) { // get the CourseSet object level CourseSet cs = (CourseSet) i.next(); String level = cs.getCategory(); if (!rv.contains(level)) { rv.add(level); } try { // recursively add child categories rv = addCategories(rv, cms.getChildCourseSets(cs.getEid())); } catch (IdNotFoundException e) { // current CourseSet not found } } } return rv; } private void prepFindPage(SessionState state) { final List cmLevels = getCMLevelLabels(), selections = (List) state .getAttribute(STATE_CM_LEVEL_SELECTIONS); int lvlSz = 0; if (cmLevels == null || (lvlSz = cmLevels.size()) < 1) { // TODO: no cm levels configured, redirect to manual add return; } if (selections != null && selections.size() == lvlSz) { Section sect = cms.getSection((String) selections.get(selections .size() - 1)); SectionObject so = new SectionObject(sect); state.setAttribute(STATE_CM_SELECTED_SECTION, so); } else state.removeAttribute(STATE_CM_SELECTED_SECTION); state.setAttribute(STATE_CM_LEVELS, cmLevels); state.setAttribute(STATE_CM_LEVEL_SELECTIONS, selections); // check the configuration setting for choosing next screen Boolean skipCourseSectionSelection = ServerConfigurationService.getBoolean("wsetup.skipCourseSectionSelection", Boolean.FALSE); if (!skipCourseSectionSelection.booleanValue()) { // go to the course/section selection page state.setAttribute(STATE_TEMPLATE_INDEX, "53"); } else { // skip the course/section selection page, go directly into the manually create course page state.setAttribute(STATE_TEMPLATE_INDEX, "37"); } } private void addRequestedSection(SessionState state) { SectionObject so = (SectionObject) state .getAttribute(STATE_CM_SELECTED_SECTION); String uniqueName = (String) state .getAttribute(STATE_SITE_QUEST_UNIQNAME); if (so == null) return; so.setAuthorizer(uniqueName); if (getStateSite(state) == null) { // creating new site List<SectionObject> requestedSections = (List<SectionObject>) state.getAttribute(STATE_CM_REQUESTED_SECTIONS); if (requestedSections == null) { requestedSections = new ArrayList<SectionObject>(); } // don't add duplicates if (!requestedSections.contains(so)) requestedSections.add(so); // if the title has not yet been set and there is just // one section, set the title to that section's EID if (requestedSections.size() == 1) { SiteInfo siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO); if (siteInfo == null) { siteInfo = new SiteInfo(); } if (siteInfo.title == null || siteInfo.title.trim().length() == 0) { siteInfo.title = so.getEid(); } state.setAttribute(STATE_SITE_INFO, siteInfo); } state.setAttribute(STATE_CM_REQUESTED_SECTIONS, requestedSections); state.removeAttribute(STATE_CM_SELECTED_SECTION); } else { // editing site state.setAttribute(STATE_CM_SELECTED_SECTION, so); List<SectionObject> cmSelectedSections = (List<SectionObject>) state.getAttribute(STATE_CM_SELECTED_SECTIONS); if (cmSelectedSections == null) { cmSelectedSections = new ArrayList<SectionObject>(); } // don't add duplicates if (!cmSelectedSections.contains(so)) cmSelectedSections.add(so); state.setAttribute(STATE_CM_SELECTED_SECTIONS, cmSelectedSections); state.removeAttribute(STATE_CM_SELECTED_SECTION); } state.removeAttribute(STATE_CM_LEVEL_SELECTIONS); } public void doFind_course(RunData data) { final SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); final ParameterParser params = data.getParameters(); final String option = params.get("option"); if (option != null) { if ("continue".equals(option)) { String uniqname = StringUtil.trimToNull(params .getString("uniqname")); state.setAttribute(STATE_SITE_QUEST_UNIQNAME, uniqname); if (state.getAttribute(STATE_FUTURE_TERM_SELECTED) != null && !((Boolean) state .getAttribute(STATE_FUTURE_TERM_SELECTED)) .booleanValue()) { // if a future term is selected, do not check authorization // uniqname if (uniqname == null) { addAlert(state, rb.getString("java.author") + " " + ServerConfigurationService .getString("officialAccountName") + ". "); } else { try { UserDirectoryService.getUserByEid(uniqname); addRequestedSection(state); } catch (UserNotDefinedException e) { addAlert(state, rb.getString("java.validAuthor1") + " " + ServerConfigurationService.getString("officialAccountName") + " " + rb.getString("java.validAuthor2")); M_log.warn(this + ".doFind_course:" + rb.getString("java.validAuthor1") + " " + ServerConfigurationService.getString("officialAccountName") + " " + rb.getString("java.validAuthor2"), e); } } } else { addRequestedSection(state); } if (state.getAttribute(STATE_MESSAGE) == null) { if (getStateSite(state) == null) { state.setAttribute(STATE_TEMPLATE_INDEX, "2"); } else { state.setAttribute(STATE_TEMPLATE_INDEX, "44"); } } doContinue(data); return; } else if ("back".equals(option)) { doBack(data); return; } else if ("cancel".equals(option)) { if (getStateSite(state) == null) { doCancel_create(data);// cancel from new site creation } else { doCancel(data);// cancel from site info editing } return; } else if (option.equals("add")) { addRequestedSection(state); return; } else if (option.equals("manual")) { // TODO: send to case 37 state.setAttribute(STATE_TEMPLATE_INDEX, "37"); state.setAttribute(STATE_MANUAL_ADD_COURSE_NUMBER, new Integer( 1)); return; } else if (option.equals("remove")) removeAnyFlagedSection(state, params); } final List selections = new ArrayList(3); int cmLevel = getCMLevelLabels().size(); String deptChanged = params.get("deptChanged"); if ("true".equals(deptChanged)) { // when dept changes, remove selection on courseOffering and // courseSection cmLevel = 1; } for (int i = 0; i < cmLevel; i++) { String val = params.get("idField_" + i); if (val == null || val.trim().length() < 1) { break; } selections.add(val); } state.setAttribute(STATE_CM_LEVEL_SELECTIONS, selections); prepFindPage(state); } /** * return the title of the 1st section in the chosen list that has an * enrollment set. No discrimination on section category * * @param sectionList * @param chosenList * @return */ private String prepareTitle(List sectionList, List chosenList) { String title = null; HashMap map = new HashMap(); for (Iterator i = sectionList.iterator(); i.hasNext();) { SectionObject o = (SectionObject) i.next(); map.put(o.getEid(), o.getSection()); } for (int j = 0; j < chosenList.size(); j++) { String eid = (String) chosenList.get(j); Section s = (Section) map.get(eid); // we will always has a title regardless but we prefer it to be the // 1st section on the chosen list that has an enrollment set if (j == 0) { title = s.getTitle(); } if (s.getEnrollmentSet() != null) { title = s.getTitle(); break; } } return title; } // prepareTitle /** * return an ArrayList of SectionObject * * @param sectionHash * contains an ArrayList collection of SectionObject * @return */ private ArrayList getSectionList(HashMap sectionHash) { ArrayList list = new ArrayList(); // values is an ArrayList of section Collection c = sectionHash.values(); for (Iterator i = c.iterator(); i.hasNext();) { ArrayList l = (ArrayList) i.next(); list.addAll(l); } return list; } private String getAuthorizers(SessionState state) { String authorizers = ""; ArrayList list = (ArrayList) state .getAttribute(STATE_CM_AUTHORIZER_LIST); if (list != null) { for (int i = 0; i < list.size(); i++) { if (i == 0) { authorizers = (String) list.get(i); } else { authorizers = authorizers + ", " + list.get(i); } } } return authorizers; } private List prepareSectionObject(List sectionList, String userId) { ArrayList list = new ArrayList(); if (sectionList != null) { for (int i = 0; i < sectionList.size(); i++) { String sectionEid = (String) sectionList.get(i); Section s = cms.getSection(sectionEid); SectionObject so = new SectionObject(s); so.setAuthorizer(userId); list.add(so); } } return list; } /** * change collection object to list object * @param c * @return */ private List collectionToList(Collection c) { List rv = new Vector(); if (c!=null) { for (Iterator i = c.iterator(); i.hasNext();) { rv.add(i.next()); } } return rv; } protected void toolModeDispatch(String methodBase, String methodExt, HttpServletRequest req, HttpServletResponse res) throws ToolException { ToolSession toolSession = SessionManager.getCurrentToolSession(); SessionState state = getState(req); if (SITE_MODE_HELPER_DONE.equals(state.getAttribute(STATE_SITE_MODE))) { String url = (String) SessionManager.getCurrentToolSession().getAttribute(Tool.HELPER_DONE_URL); SessionManager.getCurrentToolSession().removeAttribute(Tool.HELPER_DONE_URL); // TODO: Implement cleanup. cleanState(state); // Helper cleanup. cleanStateHelper(state); if (M_log.isDebugEnabled()) { M_log.debug("Sending redirect to: "+ url); } try { res.sendRedirect(url); } catch (IOException e) { M_log.warn("Problem sending redirect to: "+ url, e); } return; } else { super.toolModeDispatch(methodBase, methodExt, req, res); } } private void cleanStateHelper(SessionState state) { state.removeAttribute(STATE_SITE_MODE); state.removeAttribute(STATE_TEMPLATE_INDEX); state.removeAttribute(STATE_INITIALIZED); } }
true
true
private String buildContextForTemplate(String preIndex, int index, VelocityPortlet portlet, Context context, RunData data, SessionState state) { String realmId = ""; String site_type = ""; String sortedBy = ""; String sortedAsc = ""; ParameterParser params = data.getParameters(); context.put("tlang", rb); context.put("alertMessage", state.getAttribute(STATE_MESSAGE)); // the last visited template index if (preIndex != null) context.put("backIndex", preIndex); context.put("templateIndex", String.valueOf(index)); // If cleanState() has removed SiteInfo, get a new instance into state SiteInfo siteInfo = new SiteInfo(); if (state.getAttribute(STATE_SITE_INFO) != null) { siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO); } else { state.setAttribute(STATE_SITE_INFO, siteInfo); } // Lists used in more than one template // Access List roles = new Vector(); // the hashtables for News and Web Content tools Hashtable newsTitles = new Hashtable(); Hashtable newsUrls = new Hashtable(); Hashtable wcTitles = new Hashtable(); Hashtable wcUrls = new Hashtable(); List toolRegistrationList = new Vector(); List toolRegistrationSelectedList = new Vector(); ResourceProperties siteProperties = null; // for showing site creation steps if (state.getAttribute(SITE_CREATE_TOTAL_STEPS) != null) { context.put("totalSteps", state .getAttribute(SITE_CREATE_TOTAL_STEPS)); } if (state.getAttribute(SITE_CREATE_CURRENT_STEP) != null) { context.put("step", state.getAttribute(SITE_CREATE_CURRENT_STEP)); } String hasGradSites = ServerConfigurationService.getString( "withDissertation", Boolean.FALSE.toString()); context.put("cms", cms); // course site type context.put("courseSiteType", state.getAttribute(STATE_COURSE_SITE_TYPE)); //can the user create course sites? context.put(STATE_SITE_ADD_COURSE, SiteService.allowAddCourseSite()); Site site = getStateSite(state); // get alias base path String aliasBaseUrl = ServerConfigurationService.getPortalUrl() + Entity.SEPARATOR + "site" + Entity.SEPARATOR; switch (index) { case 0: /* * buildContextForTemplate chef_site-list.vm * */ // site types List sTypes = (List) state.getAttribute(STATE_SITE_TYPES); // make sure auto-updates are enabled Hashtable views = new Hashtable(); if (SecurityService.isSuperUser()) { views.put(rb.getString("java.allmy"), rb .getString("java.allmy")); views.put(rb.getString("java.my") + " " + rb.getString("java.sites"), rb.getString("java.my")); for (int sTypeIndex = 0; sTypeIndex < sTypes.size(); sTypeIndex++) { String type = (String) sTypes.get(sTypeIndex); views.put(type + " " + rb.getString("java.sites"), type); } if (hasGradSites.equalsIgnoreCase("true")) { views.put(rb.getString("java.gradtools") + " " + rb.getString("java.sites"), rb .getString("java.gradtools")); } if (state.getAttribute(STATE_VIEW_SELECTED) == null) { state.setAttribute(STATE_VIEW_SELECTED, rb .getString("java.allmy")); } context.put("superUser", Boolean.TRUE); } else { context.put("superUser", Boolean.FALSE); views.put(rb.getString("java.allmy"), rb .getString("java.allmy")); // if there is a GradToolsStudent choice inside boolean remove = false; if (hasGradSites.equalsIgnoreCase("true")) { try { // the Grad Tools site option is only presented to // GradTools Candidates String userId = StringUtil.trimToZero(SessionManager .getCurrentSessionUserId()); // am I a grad student? if (!isGradToolsCandidate(userId)) { // not a gradstudent remove = true; } } catch (Exception e) { remove = true; M_log.warn(this + "buildContextForTemplate chef_site-list.vm list GradToolsStudent sites", e); } } else { // not support for dissertation sites remove = true; } // do not show this site type in views // sTypes.remove(new String(SITE_TYPE_GRADTOOLS_STUDENT)); for (int sTypeIndex = 0; sTypeIndex < sTypes.size(); sTypeIndex++) { String type = (String) sTypes.get(sTypeIndex); if (!type.equals(SITE_TYPE_GRADTOOLS_STUDENT)) { views .put(type + " " + rb.getString("java.sites"), type); } } if (!remove) { views.put(rb.getString("java.gradtools") + " " + rb.getString("java.sites"), rb .getString("java.gradtools")); } // default view if (state.getAttribute(STATE_VIEW_SELECTED) == null) { state.setAttribute(STATE_VIEW_SELECTED, rb .getString("java.allmy")); } } context.put("views", views); if (state.getAttribute(STATE_VIEW_SELECTED) != null) { context.put("viewSelected", (String) state .getAttribute(STATE_VIEW_SELECTED)); } String search = (String) state.getAttribute(STATE_SEARCH); context.put("search_term", search); sortedBy = (String) state.getAttribute(SORTED_BY); if (sortedBy == null) { state.setAttribute(SORTED_BY, SortType.TITLE_ASC.toString()); sortedBy = SortType.TITLE_ASC.toString(); } sortedAsc = (String) state.getAttribute(SORTED_ASC); if (sortedAsc == null) { sortedAsc = Boolean.TRUE.toString(); state.setAttribute(SORTED_ASC, sortedAsc); } if (sortedBy != null) context.put("currentSortedBy", sortedBy); if (sortedAsc != null) context.put("currentSortAsc", sortedAsc); String portalUrl = ServerConfigurationService.getPortalUrl(); context.put("portalUrl", portalUrl); List sites = prepPage(state); state.setAttribute(STATE_SITES, sites); context.put("sites", sites); context.put("totalPageNumber", new Integer(totalPageNumber(state))); context.put("searchString", state.getAttribute(STATE_SEARCH)); context.put("form_search", FORM_SEARCH); context.put("formPageNumber", FORM_PAGE_NUMBER); context.put("prev_page_exists", state .getAttribute(STATE_PREV_PAGE_EXISTS)); context.put("next_page_exists", state .getAttribute(STATE_NEXT_PAGE_EXISTS)); context.put("current_page", state.getAttribute(STATE_CURRENT_PAGE)); // put the service in the context (used for allow update calls on // each site) context.put("service", SiteService.getInstance()); context.put("sortby_title", SortType.TITLE_ASC.toString()); context.put("sortby_type", SortType.TYPE_ASC.toString()); context.put("sortby_createdby", SortType.CREATED_BY_ASC.toString()); context.put("sortby_publish", SortType.PUBLISHED_ASC.toString()); context.put("sortby_createdon", SortType.CREATED_ON_ASC.toString()); // top menu bar Menu bar = new MenuImpl(portlet, data, (String) state .getAttribute(STATE_ACTION)); if (SiteService.allowAddSite(null)) { bar.add(new MenuEntry(rb.getString("java.new"), "doNew_site")); } bar.add(new MenuEntry(rb.getString("java.revise"), null, true, MenuItem.CHECKED_NA, "doGet_site", "sitesForm")); bar.add(new MenuEntry(rb.getString("java.delete"), null, true, MenuItem.CHECKED_NA, "doMenu_site_delete", "sitesForm")); context.put("menu", bar); // default to be no pageing context.put("paged", Boolean.FALSE); Menu bar2 = new MenuImpl(portlet, data, (String) state .getAttribute(STATE_ACTION)); // add the search commands addSearchMenus(bar2, state); context.put("menu2", bar2); pagingInfoToContext(state, context); return (String) getContext(data).get("template") + TEMPLATE[0]; case 1: /* * buildContextForTemplate chef_site-type.vm * */ if (hasGradSites.equalsIgnoreCase("true")) { context.put("withDissertation", Boolean.TRUE); try { // the Grad Tools site option is only presented to UM grad // students String userId = StringUtil.trimToZero(SessionManager .getCurrentSessionUserId()); // am I a UM grad student? Boolean isGradStudent = new Boolean( isGradToolsCandidate(userId)); context.put("isGradStudent", isGradStudent); // if I am a UM grad student, do I already have a Grad Tools // site? boolean noGradToolsSite = true; if (hasGradToolsStudentSite(userId)) noGradToolsSite = false; context .put("noGradToolsSite", new Boolean(noGradToolsSite)); } catch (Exception e) { M_log.warn(this + "buildContextForTemplate chef_site-type.vm ", e); } } else { context.put("withDissertation", Boolean.FALSE); } List types = (List) state.getAttribute(STATE_SITE_TYPES); context.put("siteTypes", types); // put selected/default site type into context String typeSelected = (String) state.getAttribute(STATE_TYPE_SELECTED); context.put("typeSelected", state.getAttribute(STATE_TYPE_SELECTED) != null?state.getAttribute(STATE_TYPE_SELECTED):types.get(0)); setTermListForContext(context, state, true); // true => only // upcoming terms setSelectedTermForContext(context, state, STATE_TERM_SELECTED); // template site - Denny setTemplateListForContext(context, state); return (String) getContext(data).get("template") + TEMPLATE[1]; case 2: /* * buildContextForTemplate chef_site-newSiteInformation.vm * */ context.put("siteTypes", state.getAttribute(STATE_SITE_TYPES)); String siteType = (String) state.getAttribute(STATE_SITE_TYPE); context.put("type", siteType); context.put("siteTitleEditable", Boolean.valueOf(siteTitleEditable(state, siteType))); if (siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { context.put("isCourseSite", Boolean.TRUE); context.put("isProjectSite", Boolean.FALSE); if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null) { context.put("selectedProviderCourse", state .getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN)); } List<SectionObject> cmRequestedList = (List<SectionObject>) state .getAttribute(STATE_CM_REQUESTED_SECTIONS); if (cmRequestedList != null) { context.put("cmRequestedSections", cmRequestedList); } List<SectionObject> cmAuthorizerSectionList = (List<SectionObject>) state .getAttribute(STATE_CM_AUTHORIZER_SECTIONS); if (cmAuthorizerSectionList != null) { context .put("cmAuthorizerSections", cmAuthorizerSectionList); } if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) { int number = ((Integer) state .getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)) .intValue(); context.put("manualAddNumber", new Integer(number - 1)); context.put("manualAddFields", state .getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS)); } else { if (courseManagementIsImplemented()) { } else { context.put("templateIndex", "37"); } } // whether to show course skin selection choices or not courseSkinSelection(context, state, null, siteInfo); } else { context.put("isCourseSite", Boolean.FALSE); if (siteType.equalsIgnoreCase("project")) { context.put("isProjectSite", Boolean.TRUE); } if (StringUtil.trimToNull(siteInfo.iconUrl) != null) { context.put(FORM_ICON_URL, siteInfo.iconUrl); } } if (state.getAttribute(SiteHelper.SITE_CREATE_SITE_TITLE) != null) { context.put("titleEditableSiteType", Boolean.FALSE); siteInfo.title = (String)state.getAttribute(SiteHelper.SITE_CREATE_SITE_TITLE); } else { context.put("titleEditableSiteType", state .getAttribute(TITLE_EDITABLE_SITE_TYPE)); } context.put(FORM_TITLE, siteInfo.title); context.put(FORM_URL_BASE, aliasBaseUrl); context.put(FORM_URL_ALIAS, siteInfo.url_alias); context.put(FORM_SHORT_DESCRIPTION, siteInfo.short_description); context.put(FORM_DESCRIPTION, siteInfo.description); // defalt the site contact person to the site creator if (siteInfo.site_contact_name.equals(NULL_STRING) && siteInfo.site_contact_email.equals(NULL_STRING)) { User user = UserDirectoryService.getCurrentUser(); siteInfo.site_contact_name = user.getDisplayName(); siteInfo.site_contact_email = user.getEmail(); } context.put("form_site_contact_name", siteInfo.site_contact_name); context.put("form_site_contact_email", siteInfo.site_contact_email); // those manual inputs context.put("form_requiredFields", sectionFieldProvider .getRequiredFields()); context.put("fieldValues", state .getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS)); return (String) getContext(data).get("template") + TEMPLATE[2]; case 3: /* * buildContextForTemplate chef_site-editFeatures.vm * */ String type = (String) state.getAttribute(STATE_SITE_TYPE); if (type != null && type.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { context.put("isCourseSite", Boolean.TRUE); context.put("isProjectSite", Boolean.FALSE); } else { context.put("isCourseSite", Boolean.FALSE); if (type.equalsIgnoreCase("project")) { context.put("isProjectSite", Boolean.TRUE); } } List requiredTools = ServerConfigurationService.getToolsRequired(type); // look for legacy "home" tool context.put("defaultTools", replaceHomeToolId(state, requiredTools)); toolRegistrationSelectedList = (List) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); // If this is the first time through, check for tools // which should be selected by default. List defaultSelectedTools = ServerConfigurationService.getDefaultTools(type); defaultSelectedTools = replaceHomeToolId(state, defaultSelectedTools); if (toolRegistrationSelectedList == null) { toolRegistrationSelectedList = new Vector(defaultSelectedTools); } context.put(STATE_TOOL_REGISTRATION_SELECTED_LIST, toolRegistrationSelectedList); boolean myworkspace_site = false; // Put up tool lists filtered by category List siteTypes = (List) state.getAttribute(STATE_SITE_TYPES); if (siteTypes.contains(type)) { myworkspace_site = false; } if (site != null && SiteService.isUserSite(site.getId()) || (type != null && type.equalsIgnoreCase("myworkspace"))) { myworkspace_site = true; type = "myworkspace"; } context.put("myworkspace_site", new Boolean(myworkspace_site)); context.put(STATE_TOOL_REGISTRATION_LIST, state.getAttribute(STATE_TOOL_REGISTRATION_LIST)); // titles for multiple tool instances context.put(STATE_MULTIPLE_TOOL_ID_TITLE_MAP, state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP )); // The Home tool checkbox needs special treatment to be selected // by // default. Boolean checkHome = (Boolean) state.getAttribute(STATE_TOOL_HOME_SELECTED); if (checkHome == null) { if ((defaultSelectedTools != null) && defaultSelectedTools.contains(getHomeToolId(state))) { checkHome = Boolean.TRUE; } } context.put("check_home", checkHome); // get the email alias when an Email Archive tool has been selected String channelReference = site!=null?mailArchiveChannelReference(site.getId()):""; List aliases = AliasService.getAliases(channelReference, 1, 1); if (aliases.size() > 0) { state.setAttribute(STATE_TOOL_EMAIL_ADDRESS, ((Alias) aliases .get(0)).getId()); } if (state.getAttribute(STATE_TOOL_EMAIL_ADDRESS) != null) { context.put("emailId", state .getAttribute(STATE_TOOL_EMAIL_ADDRESS)); } context.put("serverName", ServerConfigurationService .getServerName()); context.put("sites", SiteService.getSites( org.sakaiproject.site.api.SiteService.SelectionType.UPDATE, null, null, null, SortType.TITLE_ASC, null)); context.put("import", state.getAttribute(STATE_IMPORT)); context.put("importSites", state.getAttribute(STATE_IMPORT_SITES)); if (site != null) { context.put("SiteTitle", site.getTitle()); context.put("existSite", Boolean.TRUE); context.put("backIndex", "12"); // back to site info list page } else { context.put("existSite", Boolean.FALSE); context.put("backIndex", "2"); // back to new site information page } context.put("homeToolId", getHomeToolId(state)); return (String) getContext(data).get("template") + TEMPLATE[3]; case 5: /* * buildContextForTemplate chef_site-addParticipant.vm * */ context.put("title", site.getTitle()); roles = getRoles(state); context.put("roles", roles); siteType = (String) state.getAttribute(STATE_SITE_TYPE); context.put("isCourseSite", siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))?Boolean.TRUE:Boolean.FALSE); // Note that (for now) these strings are in both sakai.properties // and sitesetupgeneric.properties context.put("officialAccountSectionTitle", ServerConfigurationService .getString("officialAccountSectionTitle")); context.put("officialAccountName", ServerConfigurationService .getString("officialAccountName")); context.put("officialAccountLabel", ServerConfigurationService .getString("officialAccountLabel")); String pickerAction = ServerConfigurationService.getString("officialAccountPickerAction"); if (pickerAction != null && !"".equals(pickerAction)) { context.put("hasPickerDefined", Boolean.TRUE); context.put("officialAccountPickerLabel", ServerConfigurationService .getString("officialAccountPickerLabel")); context.put("officialAccountPickerAction", pickerAction); } if (state.getAttribute("officialAccountValue") != null) { context.put("officialAccountValue", (String) state .getAttribute("officialAccountValue")); } // whether to show the non-official participant section or not String addNonOfficialParticipant = (String) state.getAttribute(ADD_NON_OFFICIAL_PARTICIPANT); if (addNonOfficialParticipant != null) { if (addNonOfficialParticipant.equalsIgnoreCase("true")) { context.put("nonOfficialAccount", Boolean.TRUE); context.put("nonOfficialAccountSectionTitle", ServerConfigurationService .getString("nonOfficialAccountSectionTitle")); context.put("nonOfficialAccountName", ServerConfigurationService .getString("nonOfficialAccountName")); context.put("nonOfficialAccountLabel", ServerConfigurationService .getString("nonOfficialAccountLabel")); if (state.getAttribute("nonOfficialAccountValue") != null) { context.put("nonOfficialAccountValue", (String) state .getAttribute("nonOfficialAccountValue")); } } else { context.put("nonOfficialAccount", Boolean.FALSE); } } if (state.getAttribute("form_same_role") != null) { context.put("form_same_role", ((Boolean) state .getAttribute("form_same_role")).toString()); } else { context.put("form_same_role", Boolean.TRUE.toString()); } context.put("backIndex", "12"); return (String) getContext(data).get("template") + TEMPLATE[5]; case 8: /* * buildContextForTemplate chef_site-siteDeleteConfirm.vm * */ String site_title = NULL_STRING; String[] removals = (String[]) state .getAttribute(STATE_SITE_REMOVALS); List remove = new Vector(); String user = SessionManager.getCurrentSessionUserId(); String workspace = SiteService.getUserSiteId(user); if (removals != null && removals.length != 0) { for (int i = 0; i < removals.length; i++) { String id = (String) removals[i]; if (!(id.equals(workspace))) { try { site_title = SiteService.getSite(id).getTitle(); } catch (IdUnusedException e) { M_log.warn(this + "buildContextForTemplate chef_site-siteDeleteConfirm.vm - IdUnusedException " + id, e); addAlert(state, rb.getString("java.sitewith") + " " + id + " " + rb.getString("java.couldnt") + " "); } if (SiteService.allowRemoveSite(id)) { try { Site removeSite = SiteService.getSite(id); remove.add(removeSite); } catch (IdUnusedException e) { M_log.warn(this + ".buildContextForTemplate chef_site-siteDeleteConfirm.vm: IdUnusedException", e); } } else { addAlert(state, site_title + " " + rb.getString("java.couldntdel") + " "); } } else { addAlert(state, rb.getString("java.yourwork")); } } if (remove.size() == 0) { addAlert(state, rb.getString("java.click")); } } context.put("removals", remove); return (String) getContext(data).get("template") + TEMPLATE[8]; case 10: /* * buildContextForTemplate chef_site-newSiteConfirm.vm * */ siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO); siteType = (String) state.getAttribute(STATE_SITE_TYPE); if (siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { context.put("isCourseSite", Boolean.TRUE); context.put("disableCourseSelection", ServerConfigurationService.getString("disable.course.site.skin.selection", "false").equals("true")?Boolean.TRUE:Boolean.FALSE); context.put("isProjectSite", Boolean.FALSE); if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null) { context.put("selectedProviderCourse", state .getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN)); } if (state.getAttribute(STATE_CM_AUTHORIZER_SECTIONS) != null) { context.put("selectedAuthorizerCourse", state .getAttribute(STATE_CM_AUTHORIZER_SECTIONS)); } if (state.getAttribute(STATE_CM_REQUESTED_SECTIONS) != null) { context.put("selectedRequestedCourse", state .getAttribute(STATE_CM_REQUESTED_SECTIONS)); } if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) { int number = ((Integer) state .getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)) .intValue(); context.put("manualAddNumber", new Integer(number - 1)); context.put("manualAddFields", state .getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS)); } context.put("skins", state.getAttribute(STATE_ICONS)); if (StringUtil.trimToNull(siteInfo.getIconUrl()) != null) { context.put("selectedIcon", siteInfo.getIconUrl()); } } else { context.put("isCourseSite", Boolean.FALSE); if (siteType != null && siteType.equalsIgnoreCase("project")) { context.put("isProjectSite", Boolean.TRUE); } if (StringUtil.trimToNull(siteInfo.iconUrl) != null) { context.put("iconUrl", siteInfo.iconUrl); } } if (StringUtil.trimToNull(siteInfo.getUrlAlias()) != null) { String urlAliasFull = aliasBaseUrl + siteInfo.getUrlAlias(); context.put(FORM_URL_ALIAS_FULL, urlAliasFull); } context.put("title", siteInfo.title); context.put("description", siteInfo.description); context.put("short_description", siteInfo.short_description); context.put("siteContactName", siteInfo.site_contact_name); context.put("siteContactEmail", siteInfo.site_contact_email); siteType = (String) state.getAttribute(STATE_SITE_TYPE); toolRegistrationSelectedList = (List) state .getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); context.put(STATE_TOOL_REGISTRATION_SELECTED_LIST, toolRegistrationSelectedList); // String toolId's context.put(STATE_TOOL_REGISTRATION_LIST, state .getAttribute(STATE_TOOL_REGISTRATION_LIST)); // %%% use Tool // all info related to multiple tools multipleToolIntoContext(context, state); context.put("check_home", state .getAttribute(STATE_TOOL_HOME_SELECTED)); context .put("emailId", state .getAttribute(STATE_TOOL_EMAIL_ADDRESS)); context.put("serverName", ServerConfigurationService .getServerName()); context.put("include", new Boolean(siteInfo.include)); context.put("published", new Boolean(siteInfo.published)); context.put("joinable", new Boolean(siteInfo.joinable)); context.put("joinerRole", siteInfo.joinerRole); context.put("importSiteTools", state .getAttribute(STATE_IMPORT_SITE_TOOL)); context.put("siteService", SiteService.getInstance()); // those manual inputs context.put("form_requiredFields", sectionFieldProvider .getRequiredFields()); context.put("fieldValues", state .getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS)); return (String) getContext(data).get("template") + TEMPLATE[10]; case 12: /* * buildContextForTemplate chef_site-siteInfo-list.vm * */ context.put("userDirectoryService", UserDirectoryService .getInstance()); try { siteProperties = site.getProperties(); siteType = site.getType(); if (siteType != null) { state.setAttribute(STATE_SITE_TYPE, siteType); } if (site.getProviderGroupId() != null) { M_log.debug("site has provider"); context.put("hasProviderSet", Boolean.TRUE); } else { M_log.debug("site has no provider"); context.put("hasProviderSet", Boolean.FALSE); } boolean isMyWorkspace = false; if (SiteService.isUserSite(site.getId())) { if (SiteService.getSiteUserId(site.getId()).equals( SessionManager.getCurrentSessionUserId())) { isMyWorkspace = true; context.put("siteUserId", SiteService .getSiteUserId(site.getId())); } } context.put("isMyWorkspace", Boolean.valueOf(isMyWorkspace)); String siteId = site.getId(); if (state.getAttribute(STATE_ICONS) != null) { List skins = (List) state.getAttribute(STATE_ICONS); for (int i = 0; i < skins.size(); i++) { MyIcon s = (MyIcon) skins.get(i); if (!StringUtil .different(s.getUrl(), site.getIconUrl())) { context.put("siteUnit", s.getName()); break; } } } context.put("siteIcon", site.getIconUrl()); context.put("siteTitle", site.getTitle()); context.put("siteDescription", site.getDescription()); context.put("siteJoinable", new Boolean(site.isJoinable())); if (site.isPublished()) { context.put("published", Boolean.TRUE); } else { context.put("published", Boolean.FALSE); context.put("owner", site.getCreatedBy().getSortName()); } Time creationTime = site.getCreatedTime(); if (creationTime != null) { context.put("siteCreationDate", creationTime .toStringLocalFull()); } boolean allowUpdateSite = SiteService.allowUpdateSite(siteId); context.put("allowUpdate", Boolean.valueOf(allowUpdateSite)); boolean allowUpdateGroupMembership = SiteService .allowUpdateGroupMembership(siteId); context.put("allowUpdateGroupMembership", Boolean .valueOf(allowUpdateGroupMembership)); boolean allowUpdateSiteMembership = SiteService .allowUpdateSiteMembership(siteId); context.put("allowUpdateSiteMembership", Boolean .valueOf(allowUpdateSiteMembership)); Menu b = new MenuImpl(portlet, data, (String) state .getAttribute(STATE_ACTION)); if (allowUpdateSite) { // top menu bar if (!isMyWorkspace) { b.add(new MenuEntry(rb.getString("java.editsite"), "doMenu_edit_site_info")); } b.add(new MenuEntry(rb.getString("java.edittools"), "doMenu_edit_site_tools")); // if the page order helper is available, not // stealthed and not hidden, show the link if (notStealthOrHiddenTool("sakai-site-pageorder-helper")) { // in particular, need to check site types for showing the tool or not if (isPageOrderAllowed(siteType)) { b.add(new MenuEntry(rb.getString("java.orderpages"), "doPageOrderHelper")); } } } if (allowUpdateSiteMembership) { // show add participant menu if (!isMyWorkspace) { // if the add participant helper is available, not // stealthed and not hidden, show the link if (notStealthOrHiddenTool("sakai-site-manage-participant-helper")) { b.add(new MenuEntry(rb.getString("java.addp"), "doParticipantHelper")); } // show the Edit Class Roster menu if (ServerConfigurationService.getBoolean("site.setup.allow.editRoster", true) && siteType != null && siteType.equals((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { b.add(new MenuEntry(rb.getString("java.editc"), "doMenu_siteInfo_editClass")); } } } if (allowUpdateGroupMembership) { // show Manage Groups menu if (!isMyWorkspace && (ServerConfigurationService .getString("wsetup.group.support") == "" || ServerConfigurationService .getString("wsetup.group.support") .equalsIgnoreCase(Boolean.TRUE.toString()))) { // show the group toolbar unless configured // to not support group // if the manage group helper is available, not // stealthed and not hidden, show the link if (setHelper("wsetup.groupHelper", "sakai-site-manage-group-helper", state, STATE_GROUP_HELPER_ID)) { b.add(new MenuEntry(rb.getString("java.group"), "doManageGroupHelper")); } } } if (allowUpdateSite) { if (!isMyWorkspace) { List gradToolsSiteTypes = (List) state .getAttribute(GRADTOOLS_SITE_TYPES); boolean isGradToolSite = false; if (siteType != null && gradToolsSiteTypes.contains(siteType)) { isGradToolSite = true; } if (siteType == null || siteType != null && !isGradToolSite) { // hide site access for GRADTOOLS // type of sites b.add(new MenuEntry( rb.getString("java.siteaccess"), "doMenu_edit_site_access")); } if (siteType == null || siteType != null && !isGradToolSite) { // hide site duplicate and import // for GRADTOOLS type of sites if (SiteService.allowAddSite(null)) { b.add(new MenuEntry(rb.getString("java.duplicate"), "doMenu_siteInfo_duplicate")); } List updatableSites = SiteService .getSites( org.sakaiproject.site.api.SiteService.SelectionType.UPDATE, null, null, null, SortType.TITLE_ASC, null); // import link should be visible even if only one // site if (updatableSites.size() > 0) { //a configuration param for showing/hiding Import From Site with Clean Up String importFromSite = ServerConfigurationService.getString("clean.import.site",Boolean.TRUE.toString()); if (importFromSite.equalsIgnoreCase("true")) { b.add(new MenuEntry( rb.getString("java.import"), "doMenu_siteInfo_importSelection")); } else { b.add(new MenuEntry( rb.getString("java.import"), "doMenu_siteInfo_import")); } // a configuration param for // showing/hiding import // from file choice String importFromFile = ServerConfigurationService .getString("site.setup.import.file", Boolean.TRUE.toString()); if (importFromFile.equalsIgnoreCase("true")) { // htripath: June // 4th added as per // Kris and changed // desc of above b.add(new MenuEntry(rb .getString("java.importFile"), "doAttachmentsMtrlFrmFile")); } } } } } if (b.size() > 0) { // add the menus to vm context.put("menu", b); } if (((String) state.getAttribute(STATE_SITE_MODE)) .equalsIgnoreCase(SITE_MODE_SITESETUP)) { // editing from worksite setup tool context.put("fromWSetup", Boolean.TRUE); if (state.getAttribute(STATE_PREV_SITE) != null) { context.put("prevSite", state .getAttribute(STATE_PREV_SITE)); } if (state.getAttribute(STATE_NEXT_SITE) != null) { context.put("nextSite", state .getAttribute(STATE_NEXT_SITE)); } } else { context.put("fromWSetup", Boolean.FALSE); } // allow view roster? boolean allowViewRoster = SiteService.allowViewRoster(siteId); if (allowViewRoster) { context.put("viewRoster", Boolean.TRUE); } else { context.put("viewRoster", Boolean.FALSE); } // set participant list if (allowUpdateSite || allowViewRoster || allowUpdateSiteMembership) { Collection participantsCollection = getParticipantList(state); sortedBy = (String) state.getAttribute(SORTED_BY); sortedAsc = (String) state.getAttribute(SORTED_ASC); if (sortedBy == null) { state.setAttribute(SORTED_BY, SiteConstants.SORTED_BY_PARTICIPANT_NAME); sortedBy = SiteConstants.SORTED_BY_PARTICIPANT_NAME; } if (sortedAsc == null) { sortedAsc = Boolean.TRUE.toString(); state.setAttribute(SORTED_ASC, sortedAsc); } if (sortedBy != null) context.put("currentSortedBy", sortedBy); if (sortedAsc != null) context.put("currentSortAsc", sortedAsc); context.put("participantListSize", new Integer(participantsCollection.size())); context.put("participantList", prepPage(state)); pagingInfoToContext(state, context); } context.put("include", Boolean.valueOf(site.isPubView())); // site contact information String contactName = siteProperties .getProperty(PROP_SITE_CONTACT_NAME); String contactEmail = siteProperties .getProperty(PROP_SITE_CONTACT_EMAIL); if (contactName == null && contactEmail == null) { User u = site.getCreatedBy(); String email = u.getEmail(); if (email != null) { contactEmail = u.getEmail(); } contactName = u.getDisplayName(); } if (contactName != null) { context.put("contactName", contactName); } if (contactEmail != null) { context.put("contactEmail", contactEmail); } if (siteType != null && siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { context.put("isCourseSite", Boolean.TRUE); coursesIntoContext(state, context, site); context.put("term", siteProperties .getProperty(PROP_SITE_TERM)); } else { context.put("isCourseSite", Boolean.FALSE); } } catch (Exception e) { M_log.warn(this + " buildContextForTemplate chef_site-siteInfo-list.vm ", e); } roles = getRoles(state); context.put("roles", roles); // will have the choice to active/inactive user or not String activeInactiveUser = ServerConfigurationService.getString( "activeInactiveUser", Boolean.FALSE.toString()); if (activeInactiveUser.equalsIgnoreCase("true")) { context.put("activeInactiveUser", Boolean.TRUE); } else { context.put("activeInactiveUser", Boolean.FALSE); } context.put("groupsWithMember", site .getGroupsWithMember(UserDirectoryService.getCurrentUser() .getId())); return (String) getContext(data).get("template") + TEMPLATE[12]; case 13: /* * buildContextForTemplate chef_site-siteInfo-editInfo.vm * */ siteProperties = site.getProperties(); context.put("title", state.getAttribute(FORM_SITEINFO_TITLE)); context.put("siteTitleEditable", Boolean.valueOf(siteTitleEditable(state, site.getType()))); context.put("type", site.getType()); context.put("titleMaxLength", state.getAttribute(STATE_SITE_TITLE_MAX)); siteType = (String) state.getAttribute(STATE_SITE_TYPE); if (siteType != null && siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { context.put("isCourseSite", Boolean.TRUE); // whether to show course skin selection choices or not courseSkinSelection(context, state, site, null); setTermListForContext(context, state, true); // true->only future terms if (state.getAttribute(FORM_SITEINFO_TERM) == null) { String currentTerm = site.getProperties().getProperty( PROP_SITE_TERM); if (currentTerm != null) { state.setAttribute(FORM_SITEINFO_TERM, currentTerm); } } setSelectedTermForContext(context, state, FORM_SITEINFO_TERM); } else { context.put("isCourseSite", Boolean.FALSE); if (state.getAttribute(FORM_SITEINFO_ICON_URL) == null && StringUtil.trimToNull(site.getIconUrl()) != null) { state.setAttribute(FORM_SITEINFO_ICON_URL, site .getIconUrl()); } if (state.getAttribute(FORM_SITEINFO_ICON_URL) != null) { context.put("iconUrl", state .getAttribute(FORM_SITEINFO_ICON_URL)); } } context.put("description", state .getAttribute(FORM_SITEINFO_DESCRIPTION)); context.put("short_description", state .getAttribute(FORM_SITEINFO_SHORT_DESCRIPTION)); context.put("form_site_contact_name", state .getAttribute(FORM_SITEINFO_CONTACT_NAME)); context.put("form_site_contact_email", state .getAttribute(FORM_SITEINFO_CONTACT_EMAIL)); return (String) getContext(data).get("template") + TEMPLATE[13]; case 14: /* * buildContextForTemplate chef_site-siteInfo-editInfoConfirm.vm * */ siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO); siteProperties = site.getProperties(); siteType = (String) state.getAttribute(STATE_SITE_TYPE); if (siteType != null && siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { context.put("isCourseSite", Boolean.TRUE); context.put("disableCourseSelection", ServerConfigurationService.getString("disable.course.site.skin.selection", "false").equals("true")?Boolean.TRUE:Boolean.FALSE); context.put("siteTerm", state.getAttribute(FORM_SITEINFO_TERM)); } else { context.put("isCourseSite", Boolean.FALSE); } context.put("oTitle", site.getTitle()); context.put("title", siteInfo.title); context.put("description", siteInfo.description); context.put("oDescription", site.getDescription()); context.put("short_description", siteInfo.short_description); context.put("oShort_description", site.getShortDescription()); context.put("skin", siteInfo.iconUrl); context.put("oSkin", site.getIconUrl()); context.put("skins", state.getAttribute(STATE_ICONS)); context.put("oIcon", site.getIconUrl()); context.put("icon", siteInfo.iconUrl); context.put("include", siteInfo.include); context.put("oInclude", Boolean.valueOf(site.isPubView())); context.put("name", siteInfo.site_contact_name); context.put("oName", siteProperties.getProperty(PROP_SITE_CONTACT_NAME)); context.put("email", siteInfo.site_contact_email); context.put("oEmail", siteProperties.getProperty(PROP_SITE_CONTACT_EMAIL)); return (String) getContext(data).get("template") + TEMPLATE[14]; case 15: /* * buildContextForTemplate chef_site-addRemoveFeatureConfirm.vm * */ context.put("title", site.getTitle()); site_type = (String) state.getAttribute(STATE_SITE_TYPE); myworkspace_site = false; if (SiteService.isUserSite(site.getId())) { if (SiteService.getSiteUserId(site.getId()).equals( SessionManager.getCurrentSessionUserId())) { myworkspace_site = true; site_type = "myworkspace"; } } context.put(STATE_TOOL_REGISTRATION_LIST, state .getAttribute(STATE_TOOL_REGISTRATION_LIST)); context.put("check_home", state .getAttribute(STATE_TOOL_HOME_SELECTED)); context.put("selectedTools", orderToolIds(state, checkNullSiteType(state, site), (List) state .getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST))); context.put("oldSelectedTools", state .getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST)); context.put("oldSelectedHome", state .getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME)); context.put("continueIndex", "12"); if (state.getAttribute(STATE_TOOL_EMAIL_ADDRESS) != null) { context.put("emailId", state .getAttribute(STATE_TOOL_EMAIL_ADDRESS)); } context.put("serverName", ServerConfigurationService .getServerName()); // all info related to multiple tools multipleToolIntoContext(context, state); return (String) getContext(data).get("template") + TEMPLATE[15]; case 18: /* * buildContextForTemplate chef_siteInfo-editAccess.vm * */ List publicChangeableSiteTypes = (List) state .getAttribute(STATE_PUBLIC_CHANGEABLE_SITE_TYPES); List unJoinableSiteTypes = (List) state .getAttribute(STATE_DISABLE_JOINABLE_SITE_TYPE); if (site != null) { // editing existing site context.put("site", site); siteType = state.getAttribute(STATE_SITE_TYPE) != null ? (String) state .getAttribute(STATE_SITE_TYPE) : null; if (siteType != null && publicChangeableSiteTypes.contains(siteType)) { context.put("publicChangeable", Boolean.TRUE); } else { context.put("publicChangeable", Boolean.FALSE); } context.put("include", Boolean.valueOf(site.isPubView())); if (siteType != null && !unJoinableSiteTypes.contains(siteType)) { // site can be set as joinable context.put("disableJoinable", Boolean.FALSE); if (state.getAttribute(STATE_JOINABLE) == null) { state.setAttribute(STATE_JOINABLE, Boolean.valueOf(site .isJoinable())); } if (state.getAttribute(STATE_JOINERROLE) == null || state.getAttribute(STATE_JOINABLE) != null && ((Boolean) state.getAttribute(STATE_JOINABLE)) .booleanValue()) { state.setAttribute(STATE_JOINERROLE, site .getJoinerRole()); } if (state.getAttribute(STATE_JOINABLE) != null) { context.put("joinable", state .getAttribute(STATE_JOINABLE)); } if (state.getAttribute(STATE_JOINERROLE) != null) { context.put("joinerRole", state .getAttribute(STATE_JOINERROLE)); } } else { // site cannot be set as joinable context.put("disableJoinable", Boolean.TRUE); } context.put("roles", getRoles(state)); } else { siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO); if (siteInfo.site_type != null && publicChangeableSiteTypes .contains(siteInfo.site_type)) { context.put("publicChangeable", Boolean.TRUE); } else { context.put("publicChangeable", Boolean.FALSE); } context.put("include", Boolean.valueOf(siteInfo.getInclude())); context.put("published", Boolean.valueOf(siteInfo .getPublished())); if (siteInfo.site_type != null && !unJoinableSiteTypes.contains(siteInfo.site_type)) { // site can be set as joinable context.put("disableJoinable", Boolean.FALSE); context.put("joinable", Boolean.valueOf(siteInfo.joinable)); context.put("joinerRole", siteInfo.joinerRole); } else { // site cannot be set as joinable context.put("disableJoinable", Boolean.TRUE); } // the template site, if using one Site templateSite = (Site) state.getAttribute(STATE_TEMPLATE_SITE); // use the type's template, if defined String realmTemplate = "!site.template"; // if create based on template, use the roles from the template if (templateSite != null) { realmTemplate = SiteService.siteReference(templateSite.getId()); } else if (siteInfo.site_type != null) { realmTemplate = realmTemplate + "." + siteInfo.site_type; } try { AuthzGroup r = AuthzGroupService.getAuthzGroup(realmTemplate); context.put("roles", r.getRoles()); } catch (GroupNotDefinedException e) { try { AuthzGroup rr = AuthzGroupService.getAuthzGroup("!site.template"); context.put("roles", rr.getRoles()); } catch (GroupNotDefinedException ee) { } } // new site, go to confirmation page context.put("continue", "10"); siteType = (String) state.getAttribute(STATE_SITE_TYPE); if (siteType != null && siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { context.put("isCourseSite", Boolean.TRUE); context.put("isProjectSite", Boolean.FALSE); } else { context.put("isCourseSite", Boolean.FALSE); if (siteType.equalsIgnoreCase("project")) { context.put("isProjectSite", Boolean.TRUE); } } } return (String) getContext(data).get("template") + TEMPLATE[18]; case 26: /* * buildContextForTemplate chef_site-modifyENW.vm * */ site_type = (String) state.getAttribute(STATE_SITE_TYPE); boolean existingSite = site != null ? true : false; if (existingSite) { // revising a existing site's tool context.put("existingSite", Boolean.TRUE); context.put("continue", "15"); } else { // new site context.put("existingSite", Boolean.FALSE); context.put("continue", "18"); } context.put("function", "eventSubmit_doAdd_features"); context.put(STATE_TOOL_REGISTRATION_LIST, state .getAttribute(STATE_TOOL_REGISTRATION_LIST)); toolRegistrationSelectedList = (List) state .getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); context.put(STATE_TOOL_REGISTRATION_SELECTED_LIST, toolRegistrationSelectedList); // String toolId's // all info related to multiple tools multipleToolIntoContext(context, state); context.put("toolManager", ToolManager.getInstance()); String emailId = (String) state.getAttribute(STATE_TOOL_EMAIL_ADDRESS); if (emailId != null) { context.put("emailId", emailId); } context.put("serverName", ServerConfigurationService .getServerName()); context.put("oldSelectedTools", state .getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST)); context.put("homeToolId", getHomeToolId(state)); return (String) getContext(data).get("template") + TEMPLATE[26]; case 27: /* * buildContextForTemplate chef_site-importSites.vm * */ existingSite = site != null ? true : false; site_type = (String) state.getAttribute(STATE_SITE_TYPE); if (existingSite) { // revising a existing site's tool context.put("continue", "12"); context.put("totalSteps", "2"); context.put("step", "2"); context.put("currentSite", site); } else { // new site, go to edit access page if (fromENWModifyView(state)) { context.put("continue", "26"); } else { context.put("continue", "18"); } } context.put("existingSite", Boolean.valueOf(existingSite)); context.put(STATE_TOOL_REGISTRATION_LIST, state .getAttribute(STATE_TOOL_REGISTRATION_LIST)); context.put("selectedTools", orderToolIds(state, site_type, (List) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST))); // String toolId's context.put("importSites", state.getAttribute(STATE_IMPORT_SITES)); context.put("importSitesTools", state .getAttribute(STATE_IMPORT_SITE_TOOL)); context.put("check_home", state .getAttribute(STATE_TOOL_HOME_SELECTED)); context.put("importSupportedTools", importTools()); return (String) getContext(data).get("template") + TEMPLATE[27]; case 60: /* * buildContextForTemplate chef_site-importSitesMigrate.vm * */ existingSite = site != null ? true : false; site_type = (String) state.getAttribute(STATE_SITE_TYPE); if (existingSite) { // revising a existing site's tool context.put("continue", "12"); context.put("back", "28"); context.put("totalSteps", "2"); context.put("step", "2"); context.put("currentSite", site); } else { // new site, go to edit access page context.put("back", "3"); if (fromENWModifyView(state)) { context.put("continue", "26"); } else { context.put("continue", "18"); } } // get the tool id list List<String> toolIdList = new Vector<String>(); if (existingSite) { // list all site tools which are displayed on its own page List<SitePage> sitePages = site.getPages(); if (sitePages != null) { for (SitePage page: sitePages) { List<ToolConfiguration> pageToolsList = page.getTools(0); // we only handle one tool per page case if ( page.getLayout() == SitePage.LAYOUT_SINGLE_COL && pageToolsList.size() == 1) { toolIdList.add(pageToolsList.get(0).getToolId()); } } } } else { // during site creation toolIdList = (List<String>) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); } state.setAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST, toolIdList); // order it SortedIterator iToolIdList = new SortedIterator(getToolsAvailableForImport(state, toolIdList).iterator(),new ToolComparator()); Hashtable<String, String> toolTitleTable = new Hashtable<String, String>(); for(;iToolIdList.hasNext();) { String toolId = (String) iToolIdList.next(); try { String toolTitle = ToolManager.getTool(toolId).getTitle(); toolTitleTable.put(toolId, toolTitle); } catch (Exception e) { Log.info("chef", this + " buildContexForTemplate case 60: cannot get tool title for " + toolId + e.getMessage()); } } context.put("selectedTools", toolTitleTable); // String toolId's context.put("importSites", state.getAttribute(STATE_IMPORT_SITES)); context.put("importSitesTools", state .getAttribute(STATE_IMPORT_SITE_TOOL)); context.put("check_home", state .getAttribute(STATE_TOOL_HOME_SELECTED)); context.put("importSupportedTools", importTools()); return (String) getContext(data).get("template") + TEMPLATE[60]; case 28: /* * buildContextForTemplate chef_siteinfo-import.vm * */ context.put("currentSite", site); context.put("importSiteList", state .getAttribute(STATE_IMPORT_SITES)); context.put("sites", SiteService.getSites( org.sakaiproject.site.api.SiteService.SelectionType.UPDATE, null, null, null, SortType.TITLE_ASC, null)); return (String) getContext(data).get("template") + TEMPLATE[28]; case 58: /* * buildContextForTemplate chef_siteinfo-importSelection.vm * */ context.put("currentSite", site); context.put("importSiteList", state .getAttribute(STATE_IMPORT_SITES)); context.put("sites", SiteService.getSites( org.sakaiproject.site.api.SiteService.SelectionType.UPDATE, null, null, null, SortType.TITLE_ASC, null)); return (String) getContext(data).get("template") + TEMPLATE[58]; case 59: /* * buildContextForTemplate chef_siteinfo-importMigrate.vm * */ context.put("currentSite", site); context.put("importSiteList", state .getAttribute(STATE_IMPORT_SITES)); context.put("sites", SiteService.getSites( org.sakaiproject.site.api.SiteService.SelectionType.UPDATE, null, null, null, SortType.TITLE_ASC, null)); return (String) getContext(data).get("template") + TEMPLATE[59]; case 29: /* * buildContextForTemplate chef_siteinfo-duplicate.vm * */ context.put("siteTitle", site.getTitle()); String sType = site.getType(); if (sType != null && sType.equals((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { context.put("isCourseSite", Boolean.TRUE); context.put("currentTermId", site.getProperties().getProperty( PROP_SITE_TERM)); setTermListForContext(context, state, true); // true upcoming only } else { context.put("isCourseSite", Boolean.FALSE); } if (state.getAttribute(SITE_DUPLICATED) == null) { context.put("siteDuplicated", Boolean.FALSE); } else { context.put("siteDuplicated", Boolean.TRUE); context.put("duplicatedName", state .getAttribute(SITE_DUPLICATED_NAME)); } return (String) getContext(data).get("template") + TEMPLATE[29]; case 36: /* * buildContextForTemplate chef_site-newSiteCourse.vm */ // SAK-9824 Boolean enableCourseCreationForUser = ServerConfigurationService.getBoolean("site.enableCreateAnyUser", Boolean.FALSE); context.put("enableCourseCreationForUser", enableCourseCreationForUser); if (site != null) { context.put("site", site); context.put("siteTitle", site.getTitle()); setTermListForContext(context, state, true); // true -> upcoming only List providerCourseList = (List) state .getAttribute(SITE_PROVIDER_COURSE_LIST); coursesIntoContext(state, context, site); AcademicSession t = (AcademicSession) state .getAttribute(STATE_TERM_SELECTED); context.put("term", t); if (t != null) { String userId = UserDirectoryService.getCurrentUser().getEid(); List courses = prepareCourseAndSectionListing(userId, t .getEid(), state); if (courses != null && courses.size() > 0) { Vector notIncludedCourse = new Vector(); // remove included sites for (Iterator i = courses.iterator(); i.hasNext();) { CourseObject c = (CourseObject) i.next(); if (providerCourseList == null || providerCourseList != null && !providerCourseList.contains(c.getEid())) { notIncludedCourse.add(c); } } state.setAttribute(STATE_TERM_COURSE_LIST, notIncludedCourse); } else { state.removeAttribute(STATE_TERM_COURSE_LIST); } } // step number used in UI state.setAttribute(SITE_CREATE_CURRENT_STEP, new Integer("1")); } else { // need to include both list 'cos STATE_CM_AUTHORIZER_SECTIONS // contains sections that doens't belongs to current user and // STATE_ADD_CLASS_PROVIDER_CHOSEN contains section that does - // v2.4 daisyf if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null || state.getAttribute(STATE_CM_AUTHORIZER_SECTIONS) != null) { List<String> providerSectionList = (List<String>) state .getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN); if (providerSectionList != null) { /* List list1 = prepareSectionObject(providerSectionList, (String) state .getAttribute(STATE_CM_CURRENT_USERID)); */ context.put("selectedProviderCourse", providerSectionList); } List<SectionObject> authorizerSectionList = (List<SectionObject>) state .getAttribute(STATE_CM_AUTHORIZER_SECTIONS); if (authorizerSectionList != null) { List authorizerList = (List) state .getAttribute(STATE_CM_AUTHORIZER_LIST); //authorizerList is a list of SectionObject /* String userId = null; if (authorizerList != null) { userId = (String) authorizerList.get(0); } List list2 = prepareSectionObject( authorizerSectionList, userId); */ ArrayList list2 = new ArrayList(); for (int i=0; i<authorizerSectionList.size();i++){ SectionObject so = (SectionObject)authorizerSectionList.get(i); list2.add(so.getEid()); } context.put("selectedAuthorizerCourse", list2); } } if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) { context.put("selectedManualCourse", Boolean.TRUE); } context.put("term", (AcademicSession) state .getAttribute(STATE_TERM_SELECTED)); context.put("currentUserId", (String) state .getAttribute(STATE_CM_CURRENT_USERID)); context.put("form_additional", (String) state .getAttribute(FORM_ADDITIONAL)); context.put("authorizers", getAuthorizers(state)); } if (((String) state.getAttribute(STATE_SITE_MODE)) .equalsIgnoreCase(SITE_MODE_SITESETUP)) { context.put("backIndex", "1"); } else if (((String) state.getAttribute(STATE_SITE_MODE)) .equalsIgnoreCase(SITE_MODE_SITEINFO)) { context.put("backIndex", ""); } List ll = (List) state.getAttribute(STATE_TERM_COURSE_LIST); context.put("termCourseList", state .getAttribute(STATE_TERM_COURSE_LIST)); // added for 2.4 -daisyf context.put("campusDirectory", getCampusDirectory()); context.put("userId", (String) state .getAttribute(STATE_INSTRUCTOR_SELECTED)); /* * for measuring how long it takes to load sections java.util.Date * date = new java.util.Date(); M_log.debug("***2. finish at: * "+date); M_log.debug("***3. userId:"+(String) state * .getAttribute(STATE_INSTRUCTOR_SELECTED)); */ return (String) getContext(data).get("template") + TEMPLATE[36]; case 37: /* * buildContextForTemplate chef_site-newSiteCourseManual.vm */ if (site != null) { context.put("site", site); context.put("siteTitle", site.getTitle()); coursesIntoContext(state, context, site); } buildInstructorSectionsList(state, params, context); context.put("form_requiredFields", sectionFieldProvider .getRequiredFields()); context.put("form_additional", siteInfo.additional); context.put("form_title", siteInfo.title); context.put("form_description", siteInfo.description); context.put("officialAccountName", ServerConfigurationService .getString("officialAccountName", "")); context.put("value_uniqname", state .getAttribute(STATE_SITE_QUEST_UNIQNAME)); int number = 1; if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) { number = ((Integer) state .getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)) .intValue(); context.put("currentNumber", new Integer(number)); } context.put("currentNumber", new Integer(number)); context.put("listSize", number>0?new Integer(number - 1):0); if (state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS) != null && ((List) state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS)).size() > 0) { context.put("fieldValues", state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS)); } if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null) { List l = (List) state .getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN); context.put("selectedProviderCourse", l); context.put("size", new Integer(l.size() - 1)); } if (state.getAttribute(STATE_CM_REQUESTED_SECTIONS) != null) { List l = (List) state .getAttribute(STATE_CM_REQUESTED_SECTIONS); context.put("cmRequestedSections", l); } if (state.getAttribute(STATE_SITE_MODE).equals(SITE_MODE_SITEINFO)) { context.put("editSite", Boolean.TRUE); context.put("cmSelectedSections", state.getAttribute(STATE_CM_SELECTED_SECTIONS)); } if (site == null) { if (state.getAttribute(STATE_AUTO_ADD) != null) { context.put("autoAdd", Boolean.TRUE); } } isFutureTermSelected(state); context.put("isFutureTerm", state .getAttribute(STATE_FUTURE_TERM_SELECTED)); context.put("weeksAhead", ServerConfigurationService.getString( "roster.available.weeks.before.term.start", "0")); return (String) getContext(data).get("template") + TEMPLATE[37]; case 42: /* * buildContextForTemplate chef_site-gradtoolsConfirm.vm * */ siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO); context.put("title", siteInfo.title); context.put("description", siteInfo.description); context.put("short_description", siteInfo.short_description); toolRegistrationList = (Vector) state .getAttribute(STATE_PROJECT_TOOL_LIST); toolRegistrationSelectedList = (List) state .getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); context.put(STATE_TOOL_REGISTRATION_SELECTED_LIST, toolRegistrationSelectedList); // String toolId's context.put(STATE_TOOL_REGISTRATION_LIST, toolRegistrationList); // %%% // use // Tool context.put("check_home", state .getAttribute(STATE_TOOL_HOME_SELECTED)); context .put("emailId", state .getAttribute(STATE_TOOL_EMAIL_ADDRESS)); context.put("serverName", ServerConfigurationService .getServerName()); context.put("include", new Boolean(siteInfo.include)); return (String) getContext(data).get("template") + TEMPLATE[42]; case 43: /* * buildContextForTemplate chef_siteInfo-editClass.vm * */ bar = new MenuImpl(portlet, data, (String) state .getAttribute(STATE_ACTION)); if (SiteService.allowAddSite(null)) { bar.add(new MenuEntry(rb.getString("java.addclasses"), "doMenu_siteInfo_addClass")); } context.put("menu", bar); context.put("siteTitle", site.getTitle()); coursesIntoContext(state, context, site); return (String) getContext(data).get("template") + TEMPLATE[43]; case 44: /* * buildContextForTemplate chef_siteInfo-addCourseConfirm.vm * */ context.put("siteTitle", site.getTitle()); coursesIntoContext(state, context, site); context.put("providerAddCourses", state .getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN)); if (state.getAttribute(STATE_CM_SELECTED_SECTIONS) != null) { context.put("cmSelectedSections", state.getAttribute(STATE_CM_SELECTED_SECTIONS)); } if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) { int addNumber = ((Integer) state .getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)) .intValue() - 1; context.put("manualAddNumber", new Integer(addNumber)); context.put("requestFields", state .getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS)); context.put("backIndex", "37"); } else { context.put("backIndex", "36"); } // those manual inputs context.put("form_requiredFields", sectionFieldProvider .getRequiredFields()); context.put("fieldValues", state .getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS)); return (String) getContext(data).get("template") + TEMPLATE[44]; // htripath - import materials from classic case 45: /* * buildContextForTemplate chef_siteInfo-importMtrlMaster.vm * */ return (String) getContext(data).get("template") + TEMPLATE[45]; case 46: /* * buildContextForTemplate chef_siteInfo-importMtrlCopy.vm * */ // this is for list display in listbox context .put("allZipSites", state .getAttribute(ALL_ZIP_IMPORT_SITES)); context.put("finalZipSites", state .getAttribute(FINAL_ZIP_IMPORT_SITES)); // zip file // context.put("zipreffile",state.getAttribute(CLASSIC_ZIP_FILE_NAME)); return (String) getContext(data).get("template") + TEMPLATE[46]; case 47: /* * buildContextForTemplate chef_siteInfo-importMtrlCopyConfirm.vm * */ context.put("finalZipSites", state .getAttribute(FINAL_ZIP_IMPORT_SITES)); return (String) getContext(data).get("template") + TEMPLATE[47]; case 48: /* * buildContextForTemplate chef_siteInfo-importMtrlCopyConfirm.vm * */ context.put("finalZipSites", state .getAttribute(FINAL_ZIP_IMPORT_SITES)); return (String) getContext(data).get("template") + TEMPLATE[48]; // case 49, 50, 51 have been implemented in helper mode case 53: { /* * build context for chef_site-findCourse.vm */ AcademicSession t = (AcademicSession) state .getAttribute(STATE_TERM_SELECTED); List cmLevels = (List) state.getAttribute(STATE_CM_LEVELS), selections = (List) state .getAttribute(STATE_CM_LEVEL_SELECTIONS); if (cmLevels == null) { cmLevels = getCMLevelLabels(); } SectionObject selectedSect = (SectionObject) state .getAttribute(STATE_CM_SELECTED_SECTION); List<SectionObject> requestedSections = (List<SectionObject>) state .getAttribute(STATE_CM_REQUESTED_SECTIONS); if (courseManagementIsImplemented() && cms != null) { context.put("cmsAvailable", new Boolean(true)); } int cmLevelSize = 0; if (cms == null || !courseManagementIsImplemented() || cmLevels == null || cmLevels.size() < 1) { // TODO: redirect to manual entry: case #37 } else { cmLevelSize = cmLevels.size(); Object levelOpts[] = state.getAttribute(STATE_CM_LEVEL_OPTS) == null?new Object[cmLevelSize]:(Object[])state.getAttribute(STATE_CM_LEVEL_OPTS); int numSelections = 0; if (selections != null) { numSelections = selections.size(); // execution will fall through these statements based on number of selections already made if (numSelections == cmLevelSize - 1) { levelOpts[numSelections] = getCMSections((String) selections.get(numSelections-1)); } else if (numSelections == cmLevelSize - 2) { levelOpts[numSelections] = getCMCourseOfferings((String) selections.get(numSelections-1), t.getEid()); } else if (numSelections < cmLevelSize) { levelOpts[numSelections] = sortCmObject(cms.findCourseSets((String) cmLevels.get(numSelections==0?0:numSelections-1))); } // always set the top level levelOpts[0] = sortCmObject(cms.findCourseSets((String) cmLevels.get(0))); // clean further element inside the array for (int i = numSelections + 1; i<cmLevelSize; i++) { levelOpts[i] = null; } } context.put("cmLevelOptions", Arrays.asList(levelOpts)); state.setAttribute(STATE_CM_LEVEL_OPTS, levelOpts); } if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null) { context.put("selectedProviderCourse", state .getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN)); } if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) { int courseInd = ((Integer) state .getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)) .intValue(); context.put("manualAddNumber", new Integer(courseInd - 1)); context.put("manualAddFields", state .getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS)); } context.put("term", (AcademicSession) state .getAttribute(STATE_TERM_SELECTED)); context.put("cmLevels", cmLevels); context.put("cmLevelSelections", selections); context.put("selectedCourse", selectedSect); context.put("cmRequestedSections", requestedSections); if (state.getAttribute(STATE_SITE_MODE).equals(SITE_MODE_SITEINFO)) { context.put("editSite", Boolean.TRUE); context.put("cmSelectedSections", state.getAttribute(STATE_CM_SELECTED_SECTIONS)); } if (((String) state.getAttribute(STATE_SITE_MODE)) .equalsIgnoreCase(SITE_MODE_SITESETUP)) { if (state.getAttribute(STATE_TERM_COURSE_LIST) != null) { context.put("backIndex", "36"); } else { context.put("backIndex", "1"); } } else if (((String) state.getAttribute(STATE_SITE_MODE)).equalsIgnoreCase(SITE_MODE_SITEINFO)) { context.put("backIndex", "36"); } context.put("authzGroupService", AuthzGroupService.getInstance()); return (String) getContext(data).get("template") + TEMPLATE[53]; } case 54: /* * build context for chef_site-questions.vm */ SiteTypeQuestions siteTypeQuestions = questionService.getSiteTypeQuestions((String) state.getAttribute(STATE_SITE_TYPE)); if (siteTypeQuestions != null) { context.put("questionSet", siteTypeQuestions); context.put("userAnswers", state.getAttribute(STATE_SITE_SETUP_QUESTION_ANSWER)); } context.put("continueIndex", state.getAttribute(STATE_SITE_SETUP_QUESTION_NEXT_TEMPLATE)); return (String) getContext(data).get("template") + TEMPLATE[54]; } // should never be reached return (String) getContext(data).get("template") + TEMPLATE[0]; }
private String buildContextForTemplate(String preIndex, int index, VelocityPortlet portlet, Context context, RunData data, SessionState state) { String realmId = ""; String site_type = ""; String sortedBy = ""; String sortedAsc = ""; ParameterParser params = data.getParameters(); context.put("tlang", rb); context.put("alertMessage", state.getAttribute(STATE_MESSAGE)); // the last visited template index if (preIndex != null) context.put("backIndex", preIndex); context.put("templateIndex", String.valueOf(index)); // If cleanState() has removed SiteInfo, get a new instance into state SiteInfo siteInfo = new SiteInfo(); if (state.getAttribute(STATE_SITE_INFO) != null) { siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO); } else { state.setAttribute(STATE_SITE_INFO, siteInfo); } // Lists used in more than one template // Access List roles = new Vector(); // the hashtables for News and Web Content tools Hashtable newsTitles = new Hashtable(); Hashtable newsUrls = new Hashtable(); Hashtable wcTitles = new Hashtable(); Hashtable wcUrls = new Hashtable(); List toolRegistrationList = new Vector(); List toolRegistrationSelectedList = new Vector(); ResourceProperties siteProperties = null; // for showing site creation steps if (state.getAttribute(SITE_CREATE_TOTAL_STEPS) != null) { context.put("totalSteps", state .getAttribute(SITE_CREATE_TOTAL_STEPS)); } if (state.getAttribute(SITE_CREATE_CURRENT_STEP) != null) { context.put("step", state.getAttribute(SITE_CREATE_CURRENT_STEP)); } String hasGradSites = ServerConfigurationService.getString( "withDissertation", Boolean.FALSE.toString()); context.put("cms", cms); // course site type context.put("courseSiteType", state.getAttribute(STATE_COURSE_SITE_TYPE)); //can the user create course sites? context.put(STATE_SITE_ADD_COURSE, SiteService.allowAddCourseSite()); Site site = getStateSite(state); // get alias base path String aliasBaseUrl = ServerConfigurationService.getPortalUrl() + Entity.SEPARATOR + "site" + Entity.SEPARATOR; switch (index) { case 0: /* * buildContextForTemplate chef_site-list.vm * */ // site types List sTypes = (List) state.getAttribute(STATE_SITE_TYPES); // make sure auto-updates are enabled Hashtable views = new Hashtable(); if (SecurityService.isSuperUser()) { views.put(rb.getString("java.allmy"), rb .getString("java.allmy")); views.put(rb.getString("java.my") + " " + rb.getString("java.sites"), rb.getString("java.my")); for (int sTypeIndex = 0; sTypeIndex < sTypes.size(); sTypeIndex++) { String type = (String) sTypes.get(sTypeIndex); views.put(type + " " + rb.getString("java.sites"), type); } if (hasGradSites.equalsIgnoreCase("true")) { views.put(rb.getString("java.gradtools") + " " + rb.getString("java.sites"), rb .getString("java.gradtools")); } if (state.getAttribute(STATE_VIEW_SELECTED) == null) { state.setAttribute(STATE_VIEW_SELECTED, rb .getString("java.allmy")); } context.put("superUser", Boolean.TRUE); } else { context.put("superUser", Boolean.FALSE); views.put(rb.getString("java.allmy"), rb .getString("java.allmy")); // if there is a GradToolsStudent choice inside boolean remove = false; if (hasGradSites.equalsIgnoreCase("true")) { try { // the Grad Tools site option is only presented to // GradTools Candidates String userId = StringUtil.trimToZero(SessionManager .getCurrentSessionUserId()); // am I a grad student? if (!isGradToolsCandidate(userId)) { // not a gradstudent remove = true; } } catch (Exception e) { remove = true; M_log.warn(this + "buildContextForTemplate chef_site-list.vm list GradToolsStudent sites", e); } } else { // not support for dissertation sites remove = true; } // do not show this site type in views // sTypes.remove(new String(SITE_TYPE_GRADTOOLS_STUDENT)); for (int sTypeIndex = 0; sTypeIndex < sTypes.size(); sTypeIndex++) { String type = (String) sTypes.get(sTypeIndex); if (!type.equals(SITE_TYPE_GRADTOOLS_STUDENT)) { views .put(type + " " + rb.getString("java.sites"), type); } } if (!remove) { views.put(rb.getString("java.gradtools") + " " + rb.getString("java.sites"), rb .getString("java.gradtools")); } // default view if (state.getAttribute(STATE_VIEW_SELECTED) == null) { state.setAttribute(STATE_VIEW_SELECTED, rb .getString("java.allmy")); } } context.put("views", views); if (state.getAttribute(STATE_VIEW_SELECTED) != null) { context.put("viewSelected", (String) state .getAttribute(STATE_VIEW_SELECTED)); } String search = (String) state.getAttribute(STATE_SEARCH); context.put("search_term", search); sortedBy = (String) state.getAttribute(SORTED_BY); if (sortedBy == null) { state.setAttribute(SORTED_BY, SortType.TITLE_ASC.toString()); sortedBy = SortType.TITLE_ASC.toString(); } sortedAsc = (String) state.getAttribute(SORTED_ASC); if (sortedAsc == null) { sortedAsc = Boolean.TRUE.toString(); state.setAttribute(SORTED_ASC, sortedAsc); } if (sortedBy != null) context.put("currentSortedBy", sortedBy); if (sortedAsc != null) context.put("currentSortAsc", sortedAsc); String portalUrl = ServerConfigurationService.getPortalUrl(); context.put("portalUrl", portalUrl); List sites = prepPage(state); state.setAttribute(STATE_SITES, sites); context.put("sites", sites); context.put("totalPageNumber", new Integer(totalPageNumber(state))); context.put("searchString", state.getAttribute(STATE_SEARCH)); context.put("form_search", FORM_SEARCH); context.put("formPageNumber", FORM_PAGE_NUMBER); context.put("prev_page_exists", state .getAttribute(STATE_PREV_PAGE_EXISTS)); context.put("next_page_exists", state .getAttribute(STATE_NEXT_PAGE_EXISTS)); context.put("current_page", state.getAttribute(STATE_CURRENT_PAGE)); // put the service in the context (used for allow update calls on // each site) context.put("service", SiteService.getInstance()); context.put("sortby_title", SortType.TITLE_ASC.toString()); context.put("sortby_type", SortType.TYPE_ASC.toString()); context.put("sortby_createdby", SortType.CREATED_BY_ASC.toString()); context.put("sortby_publish", SortType.PUBLISHED_ASC.toString()); context.put("sortby_createdon", SortType.CREATED_ON_ASC.toString()); // top menu bar Menu bar = new MenuImpl(portlet, data, (String) state .getAttribute(STATE_ACTION)); if (SiteService.allowAddSite(null)) { bar.add(new MenuEntry(rb.getString("java.new"), "doNew_site")); } bar.add(new MenuEntry(rb.getString("java.revise"), null, true, MenuItem.CHECKED_NA, "doGet_site", "sitesForm")); bar.add(new MenuEntry(rb.getString("java.delete"), null, true, MenuItem.CHECKED_NA, "doMenu_site_delete", "sitesForm")); context.put("menu", bar); // default to be no pageing context.put("paged", Boolean.FALSE); Menu bar2 = new MenuImpl(portlet, data, (String) state .getAttribute(STATE_ACTION)); // add the search commands addSearchMenus(bar2, state); context.put("menu2", bar2); pagingInfoToContext(state, context); return (String) getContext(data).get("template") + TEMPLATE[0]; case 1: /* * buildContextForTemplate chef_site-type.vm * */ if (hasGradSites.equalsIgnoreCase("true")) { context.put("withDissertation", Boolean.TRUE); try { // the Grad Tools site option is only presented to UM grad // students String userId = StringUtil.trimToZero(SessionManager .getCurrentSessionUserId()); // am I a UM grad student? Boolean isGradStudent = new Boolean( isGradToolsCandidate(userId)); context.put("isGradStudent", isGradStudent); // if I am a UM grad student, do I already have a Grad Tools // site? boolean noGradToolsSite = true; if (hasGradToolsStudentSite(userId)) noGradToolsSite = false; context .put("noGradToolsSite", new Boolean(noGradToolsSite)); } catch (Exception e) { M_log.warn(this + "buildContextForTemplate chef_site-type.vm ", e); } } else { context.put("withDissertation", Boolean.FALSE); } List types = (List) state.getAttribute(STATE_SITE_TYPES); context.put("siteTypes", types); // put selected/default site type into context String typeSelected = (String) state.getAttribute(STATE_TYPE_SELECTED); context.put("typeSelected", state.getAttribute(STATE_TYPE_SELECTED) != null?state.getAttribute(STATE_TYPE_SELECTED):types.get(0)); setTermListForContext(context, state, true); // true => only // upcoming terms setSelectedTermForContext(context, state, STATE_TERM_SELECTED); // template site - Denny setTemplateListForContext(context, state); return (String) getContext(data).get("template") + TEMPLATE[1]; case 2: /* * buildContextForTemplate chef_site-newSiteInformation.vm * */ context.put("siteTypes", state.getAttribute(STATE_SITE_TYPES)); String siteType = (String) state.getAttribute(STATE_SITE_TYPE); context.put("type", siteType); context.put("siteTitleEditable", Boolean.valueOf(siteTitleEditable(state, siteType))); if (siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { context.put("isCourseSite", Boolean.TRUE); context.put("isProjectSite", Boolean.FALSE); if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null) { context.put("selectedProviderCourse", state .getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN)); } List<SectionObject> cmRequestedList = (List<SectionObject>) state .getAttribute(STATE_CM_REQUESTED_SECTIONS); if (cmRequestedList != null) { context.put("cmRequestedSections", cmRequestedList); } List<SectionObject> cmAuthorizerSectionList = (List<SectionObject>) state .getAttribute(STATE_CM_AUTHORIZER_SECTIONS); if (cmAuthorizerSectionList != null) { context .put("cmAuthorizerSections", cmAuthorizerSectionList); } if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) { int number = ((Integer) state .getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)) .intValue(); context.put("manualAddNumber", new Integer(number - 1)); context.put("manualAddFields", state .getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS)); } else { if (courseManagementIsImplemented()) { } else { context.put("templateIndex", "37"); } } // whether to show course skin selection choices or not courseSkinSelection(context, state, null, siteInfo); } else { context.put("isCourseSite", Boolean.FALSE); if (siteType.equalsIgnoreCase("project")) { context.put("isProjectSite", Boolean.TRUE); } if (StringUtil.trimToNull(siteInfo.iconUrl) != null) { context.put(FORM_ICON_URL, siteInfo.iconUrl); } } if (state.getAttribute(SiteHelper.SITE_CREATE_SITE_TITLE) != null) { context.put("titleEditableSiteType", Boolean.FALSE); siteInfo.title = (String)state.getAttribute(SiteHelper.SITE_CREATE_SITE_TITLE); } else { context.put("titleEditableSiteType", state .getAttribute(TITLE_EDITABLE_SITE_TYPE)); } context.put(FORM_TITLE, siteInfo.title); context.put(FORM_URL_BASE, aliasBaseUrl); context.put(FORM_URL_ALIAS, siteInfo.url_alias); context.put(FORM_SHORT_DESCRIPTION, siteInfo.short_description); context.put(FORM_DESCRIPTION, siteInfo.description); // defalt the site contact person to the site creator if (siteInfo.site_contact_name.equals(NULL_STRING) && siteInfo.site_contact_email.equals(NULL_STRING)) { User user = UserDirectoryService.getCurrentUser(); siteInfo.site_contact_name = user.getDisplayName(); siteInfo.site_contact_email = user.getEmail(); } context.put("form_site_contact_name", siteInfo.site_contact_name); context.put("form_site_contact_email", siteInfo.site_contact_email); // those manual inputs context.put("form_requiredFields", sectionFieldProvider .getRequiredFields()); context.put("fieldValues", state .getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS)); return (String) getContext(data).get("template") + TEMPLATE[2]; case 3: /* * buildContextForTemplate chef_site-editFeatures.vm * */ String type = (String) state.getAttribute(STATE_SITE_TYPE); if (type != null && type.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { context.put("isCourseSite", Boolean.TRUE); context.put("isProjectSite", Boolean.FALSE); } else { context.put("isCourseSite", Boolean.FALSE); if (type.equalsIgnoreCase("project")) { context.put("isProjectSite", Boolean.TRUE); } } List requiredTools = ServerConfigurationService.getToolsRequired(type); // look for legacy "home" tool context.put("defaultTools", replaceHomeToolId(state, requiredTools)); toolRegistrationSelectedList = (List) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); // If this is the first time through, check for tools // which should be selected by default. List defaultSelectedTools = ServerConfigurationService.getDefaultTools(type); defaultSelectedTools = replaceHomeToolId(state, defaultSelectedTools); if (toolRegistrationSelectedList == null) { toolRegistrationSelectedList = new Vector(defaultSelectedTools); } context.put(STATE_TOOL_REGISTRATION_SELECTED_LIST, toolRegistrationSelectedList); boolean myworkspace_site = false; // Put up tool lists filtered by category List siteTypes = (List) state.getAttribute(STATE_SITE_TYPES); if (siteTypes.contains(type)) { myworkspace_site = false; } if (site != null && SiteService.isUserSite(site.getId()) || (type != null && type.equalsIgnoreCase("myworkspace"))) { myworkspace_site = true; type = "myworkspace"; } context.put("myworkspace_site", new Boolean(myworkspace_site)); context.put(STATE_TOOL_REGISTRATION_LIST, state.getAttribute(STATE_TOOL_REGISTRATION_LIST)); // titles for multiple tool instances context.put(STATE_MULTIPLE_TOOL_ID_TITLE_MAP, state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP )); // The Home tool checkbox needs special treatment to be selected // by // default. Boolean checkHome = (Boolean) state.getAttribute(STATE_TOOL_HOME_SELECTED); if (checkHome == null) { if ((defaultSelectedTools != null) && defaultSelectedTools.contains(getHomeToolId(state))) { checkHome = Boolean.TRUE; } } context.put("check_home", checkHome); // get the email alias when an Email Archive tool has been selected String channelReference = site!=null?mailArchiveChannelReference(site.getId()):""; List aliases = AliasService.getAliases(channelReference, 1, 1); if (aliases.size() > 0) { state.setAttribute(STATE_TOOL_EMAIL_ADDRESS, ((Alias) aliases .get(0)).getId()); } if (state.getAttribute(STATE_TOOL_EMAIL_ADDRESS) != null) { context.put("emailId", state .getAttribute(STATE_TOOL_EMAIL_ADDRESS)); } context.put("serverName", ServerConfigurationService .getServerName()); context.put("sites", SiteService.getSites( org.sakaiproject.site.api.SiteService.SelectionType.UPDATE, null, null, null, SortType.TITLE_ASC, null)); context.put("import", state.getAttribute(STATE_IMPORT)); context.put("importSites", state.getAttribute(STATE_IMPORT_SITES)); if (site != null) { context.put("SiteTitle", site.getTitle()); context.put("existSite", Boolean.TRUE); context.put("backIndex", "12"); // back to site info list page } else { context.put("existSite", Boolean.FALSE); context.put("backIndex", "2"); // back to new site information page } context.put("homeToolId", getHomeToolId(state)); return (String) getContext(data).get("template") + TEMPLATE[3]; case 5: /* * buildContextForTemplate chef_site-addParticipant.vm * */ context.put("title", site.getTitle()); roles = getRoles(state); context.put("roles", roles); siteType = (String) state.getAttribute(STATE_SITE_TYPE); context.put("isCourseSite", siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))?Boolean.TRUE:Boolean.FALSE); // Note that (for now) these strings are in both sakai.properties // and sitesetupgeneric.properties context.put("officialAccountSectionTitle", ServerConfigurationService .getString("officialAccountSectionTitle")); context.put("officialAccountName", ServerConfigurationService .getString("officialAccountName")); context.put("officialAccountLabel", ServerConfigurationService .getString("officialAccountLabel")); String pickerAction = ServerConfigurationService.getString("officialAccountPickerAction"); if (pickerAction != null && !"".equals(pickerAction)) { context.put("hasPickerDefined", Boolean.TRUE); context.put("officialAccountPickerLabel", ServerConfigurationService .getString("officialAccountPickerLabel")); context.put("officialAccountPickerAction", pickerAction); } if (state.getAttribute("officialAccountValue") != null) { context.put("officialAccountValue", (String) state .getAttribute("officialAccountValue")); } // whether to show the non-official participant section or not String addNonOfficialParticipant = (String) state.getAttribute(ADD_NON_OFFICIAL_PARTICIPANT); if (addNonOfficialParticipant != null) { if (addNonOfficialParticipant.equalsIgnoreCase("true")) { context.put("nonOfficialAccount", Boolean.TRUE); context.put("nonOfficialAccountSectionTitle", ServerConfigurationService .getString("nonOfficialAccountSectionTitle")); context.put("nonOfficialAccountName", ServerConfigurationService .getString("nonOfficialAccountName")); context.put("nonOfficialAccountLabel", ServerConfigurationService .getString("nonOfficialAccountLabel")); if (state.getAttribute("nonOfficialAccountValue") != null) { context.put("nonOfficialAccountValue", (String) state .getAttribute("nonOfficialAccountValue")); } } else { context.put("nonOfficialAccount", Boolean.FALSE); } } if (state.getAttribute("form_same_role") != null) { context.put("form_same_role", ((Boolean) state .getAttribute("form_same_role")).toString()); } else { context.put("form_same_role", Boolean.TRUE.toString()); } context.put("backIndex", "12"); return (String) getContext(data).get("template") + TEMPLATE[5]; case 8: /* * buildContextForTemplate chef_site-siteDeleteConfirm.vm * */ String site_title = NULL_STRING; String[] removals = (String[]) state .getAttribute(STATE_SITE_REMOVALS); List remove = new Vector(); String user = SessionManager.getCurrentSessionUserId(); String workspace = SiteService.getUserSiteId(user); if (removals != null && removals.length != 0) { for (int i = 0; i < removals.length; i++) { String id = (String) removals[i]; if (!(id.equals(workspace))) { try { site_title = SiteService.getSite(id).getTitle(); } catch (IdUnusedException e) { M_log.warn(this + "buildContextForTemplate chef_site-siteDeleteConfirm.vm - IdUnusedException " + id, e); addAlert(state, rb.getString("java.sitewith") + " " + id + " " + rb.getString("java.couldnt") + " "); } if (SiteService.allowRemoveSite(id)) { try { Site removeSite = SiteService.getSite(id); remove.add(removeSite); } catch (IdUnusedException e) { M_log.warn(this + ".buildContextForTemplate chef_site-siteDeleteConfirm.vm: IdUnusedException", e); } } else { addAlert(state, site_title + " " + rb.getString("java.couldntdel") + " "); } } else { addAlert(state, rb.getString("java.yourwork")); } } if (remove.size() == 0) { addAlert(state, rb.getString("java.click")); } } context.put("removals", remove); return (String) getContext(data).get("template") + TEMPLATE[8]; case 10: /* * buildContextForTemplate chef_site-newSiteConfirm.vm * */ siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO); siteType = (String) state.getAttribute(STATE_SITE_TYPE); if (siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { context.put("isCourseSite", Boolean.TRUE); context.put("disableCourseSelection", ServerConfigurationService.getString("disable.course.site.skin.selection", "false").equals("true")?Boolean.TRUE:Boolean.FALSE); context.put("isProjectSite", Boolean.FALSE); if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null) { context.put("selectedProviderCourse", state .getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN)); } if (state.getAttribute(STATE_CM_AUTHORIZER_SECTIONS) != null) { context.put("selectedAuthorizerCourse", state .getAttribute(STATE_CM_AUTHORIZER_SECTIONS)); } if (state.getAttribute(STATE_CM_REQUESTED_SECTIONS) != null) { context.put("selectedRequestedCourse", state .getAttribute(STATE_CM_REQUESTED_SECTIONS)); } if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) { int number = ((Integer) state .getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)) .intValue(); context.put("manualAddNumber", new Integer(number - 1)); context.put("manualAddFields", state .getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS)); } context.put("skins", state.getAttribute(STATE_ICONS)); if (StringUtil.trimToNull(siteInfo.getIconUrl()) != null) { context.put("selectedIcon", siteInfo.getIconUrl()); } } else { context.put("isCourseSite", Boolean.FALSE); if (siteType != null && siteType.equalsIgnoreCase("project")) { context.put("isProjectSite", Boolean.TRUE); } if (StringUtil.trimToNull(siteInfo.iconUrl) != null) { context.put("iconUrl", siteInfo.iconUrl); } } if (StringUtil.trimToNull(siteInfo.getUrlAlias()) != null) { String urlAliasFull = aliasBaseUrl + siteInfo.getUrlAlias(); context.put(FORM_URL_ALIAS_FULL, urlAliasFull); } context.put("title", siteInfo.title); context.put("description", siteInfo.description); context.put("short_description", siteInfo.short_description); context.put("siteContactName", siteInfo.site_contact_name); context.put("siteContactEmail", siteInfo.site_contact_email); siteType = (String) state.getAttribute(STATE_SITE_TYPE); toolRegistrationSelectedList = (List) state .getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); context.put(STATE_TOOL_REGISTRATION_SELECTED_LIST, toolRegistrationSelectedList); // String toolId's context.put(STATE_TOOL_REGISTRATION_LIST, state .getAttribute(STATE_TOOL_REGISTRATION_LIST)); // %%% use Tool // all info related to multiple tools multipleToolIntoContext(context, state); context.put("check_home", state .getAttribute(STATE_TOOL_HOME_SELECTED)); context .put("emailId", state .getAttribute(STATE_TOOL_EMAIL_ADDRESS)); context.put("serverName", ServerConfigurationService .getServerName()); context.put("include", new Boolean(siteInfo.include)); context.put("published", new Boolean(siteInfo.published)); context.put("joinable", new Boolean(siteInfo.joinable)); context.put("joinerRole", siteInfo.joinerRole); context.put("importSiteTools", state .getAttribute(STATE_IMPORT_SITE_TOOL)); context.put("siteService", SiteService.getInstance()); // those manual inputs context.put("form_requiredFields", sectionFieldProvider .getRequiredFields()); context.put("fieldValues", state .getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS)); return (String) getContext(data).get("template") + TEMPLATE[10]; case 12: /* * buildContextForTemplate chef_site-siteInfo-list.vm * */ context.put("userDirectoryService", UserDirectoryService .getInstance()); try { siteProperties = site.getProperties(); siteType = site.getType(); if (siteType != null) { state.setAttribute(STATE_SITE_TYPE, siteType); } if (site.getProviderGroupId() != null) { M_log.debug("site has provider"); context.put("hasProviderSet", Boolean.TRUE); } else { M_log.debug("site has no provider"); context.put("hasProviderSet", Boolean.FALSE); } boolean isMyWorkspace = false; if (SiteService.isUserSite(site.getId())) { if (SiteService.getSiteUserId(site.getId()).equals( SessionManager.getCurrentSessionUserId())) { isMyWorkspace = true; context.put("siteUserId", SiteService .getSiteUserId(site.getId())); } } context.put("isMyWorkspace", Boolean.valueOf(isMyWorkspace)); String siteId = site.getId(); if (state.getAttribute(STATE_ICONS) != null) { List skins = (List) state.getAttribute(STATE_ICONS); for (int i = 0; i < skins.size(); i++) { MyIcon s = (MyIcon) skins.get(i); if (!StringUtil .different(s.getUrl(), site.getIconUrl())) { context.put("siteUnit", s.getName()); break; } } } context.put("siteIcon", site.getIconUrl()); context.put("siteTitle", site.getTitle()); context.put("siteDescription", site.getDescription()); context.put("siteJoinable", new Boolean(site.isJoinable())); if (site.isPublished()) { context.put("published", Boolean.TRUE); } else { context.put("published", Boolean.FALSE); context.put("owner", site.getCreatedBy().getSortName()); } Time creationTime = site.getCreatedTime(); if (creationTime != null) { context.put("siteCreationDate", creationTime .toStringLocalFull()); } boolean allowUpdateSite = SiteService.allowUpdateSite(siteId); context.put("allowUpdate", Boolean.valueOf(allowUpdateSite)); boolean allowUpdateGroupMembership = SiteService .allowUpdateGroupMembership(siteId); context.put("allowUpdateGroupMembership", Boolean .valueOf(allowUpdateGroupMembership)); boolean allowUpdateSiteMembership = SiteService .allowUpdateSiteMembership(siteId); context.put("allowUpdateSiteMembership", Boolean .valueOf(allowUpdateSiteMembership)); Menu b = new MenuImpl(portlet, data, (String) state .getAttribute(STATE_ACTION)); if (allowUpdateSite) { // top menu bar if (!isMyWorkspace) { b.add(new MenuEntry(rb.getString("java.editsite"), "doMenu_edit_site_info")); } b.add(new MenuEntry(rb.getString("java.edittools"), "doMenu_edit_site_tools")); // if the page order helper is available, not // stealthed and not hidden, show the link if (notStealthOrHiddenTool("sakai-site-pageorder-helper")) { // in particular, need to check site types for showing the tool or not if (isPageOrderAllowed(siteType)) { b.add(new MenuEntry(rb.getString("java.orderpages"), "doPageOrderHelper")); } } } if (allowUpdateSiteMembership) { // show add participant menu if (!isMyWorkspace) { // if the add participant helper is available, not // stealthed and not hidden, show the link if (notStealthOrHiddenTool("sakai-site-manage-participant-helper")) { b.add(new MenuEntry(rb.getString("java.addp"), "doParticipantHelper")); } // show the Edit Class Roster menu if (ServerConfigurationService.getBoolean("site.setup.allow.editRoster", true) && siteType != null && siteType.equals((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { b.add(new MenuEntry(rb.getString("java.editc"), "doMenu_siteInfo_editClass")); } } } if (allowUpdateGroupMembership) { // show Manage Groups menu if (!isMyWorkspace && (ServerConfigurationService .getString("wsetup.group.support") == "" || ServerConfigurationService .getString("wsetup.group.support") .equalsIgnoreCase(Boolean.TRUE.toString()))) { // show the group toolbar unless configured // to not support group // if the manage group helper is available, not // stealthed and not hidden, show the link // read the helper name from configuration variable: wsetup.group.helper.name // the default value is: "sakai-site-manage-group-section-role-helper" // the older version of group helper which is not section/role aware is named:"sakai-site-manage-group-helper" String groupHelper = ServerConfigurationService.getString("wsetup.group.helper.name", "sakai-site-manage-group-section-role-helper"); if (setHelper("wsetup.groupHelper", groupHelper, state, STATE_GROUP_HELPER_ID)) { b.add(new MenuEntry(rb.getString("java.group"), "doManageGroupHelper")); } } } if (allowUpdateSite) { if (!isMyWorkspace) { List gradToolsSiteTypes = (List) state .getAttribute(GRADTOOLS_SITE_TYPES); boolean isGradToolSite = false; if (siteType != null && gradToolsSiteTypes.contains(siteType)) { isGradToolSite = true; } if (siteType == null || siteType != null && !isGradToolSite) { // hide site access for GRADTOOLS // type of sites b.add(new MenuEntry( rb.getString("java.siteaccess"), "doMenu_edit_site_access")); } if (siteType == null || siteType != null && !isGradToolSite) { // hide site duplicate and import // for GRADTOOLS type of sites if (SiteService.allowAddSite(null)) { b.add(new MenuEntry(rb.getString("java.duplicate"), "doMenu_siteInfo_duplicate")); } List updatableSites = SiteService .getSites( org.sakaiproject.site.api.SiteService.SelectionType.UPDATE, null, null, null, SortType.TITLE_ASC, null); // import link should be visible even if only one // site if (updatableSites.size() > 0) { //a configuration param for showing/hiding Import From Site with Clean Up String importFromSite = ServerConfigurationService.getString("clean.import.site",Boolean.TRUE.toString()); if (importFromSite.equalsIgnoreCase("true")) { b.add(new MenuEntry( rb.getString("java.import"), "doMenu_siteInfo_importSelection")); } else { b.add(new MenuEntry( rb.getString("java.import"), "doMenu_siteInfo_import")); } // a configuration param for // showing/hiding import // from file choice String importFromFile = ServerConfigurationService .getString("site.setup.import.file", Boolean.TRUE.toString()); if (importFromFile.equalsIgnoreCase("true")) { // htripath: June // 4th added as per // Kris and changed // desc of above b.add(new MenuEntry(rb .getString("java.importFile"), "doAttachmentsMtrlFrmFile")); } } } } } if (b.size() > 0) { // add the menus to vm context.put("menu", b); } if (((String) state.getAttribute(STATE_SITE_MODE)) .equalsIgnoreCase(SITE_MODE_SITESETUP)) { // editing from worksite setup tool context.put("fromWSetup", Boolean.TRUE); if (state.getAttribute(STATE_PREV_SITE) != null) { context.put("prevSite", state .getAttribute(STATE_PREV_SITE)); } if (state.getAttribute(STATE_NEXT_SITE) != null) { context.put("nextSite", state .getAttribute(STATE_NEXT_SITE)); } } else { context.put("fromWSetup", Boolean.FALSE); } // allow view roster? boolean allowViewRoster = SiteService.allowViewRoster(siteId); if (allowViewRoster) { context.put("viewRoster", Boolean.TRUE); } else { context.put("viewRoster", Boolean.FALSE); } // set participant list if (allowUpdateSite || allowViewRoster || allowUpdateSiteMembership) { Collection participantsCollection = getParticipantList(state); sortedBy = (String) state.getAttribute(SORTED_BY); sortedAsc = (String) state.getAttribute(SORTED_ASC); if (sortedBy == null) { state.setAttribute(SORTED_BY, SiteConstants.SORTED_BY_PARTICIPANT_NAME); sortedBy = SiteConstants.SORTED_BY_PARTICIPANT_NAME; } if (sortedAsc == null) { sortedAsc = Boolean.TRUE.toString(); state.setAttribute(SORTED_ASC, sortedAsc); } if (sortedBy != null) context.put("currentSortedBy", sortedBy); if (sortedAsc != null) context.put("currentSortAsc", sortedAsc); context.put("participantListSize", new Integer(participantsCollection.size())); context.put("participantList", prepPage(state)); pagingInfoToContext(state, context); } context.put("include", Boolean.valueOf(site.isPubView())); // site contact information String contactName = siteProperties .getProperty(PROP_SITE_CONTACT_NAME); String contactEmail = siteProperties .getProperty(PROP_SITE_CONTACT_EMAIL); if (contactName == null && contactEmail == null) { User u = site.getCreatedBy(); String email = u.getEmail(); if (email != null) { contactEmail = u.getEmail(); } contactName = u.getDisplayName(); } if (contactName != null) { context.put("contactName", contactName); } if (contactEmail != null) { context.put("contactEmail", contactEmail); } if (siteType != null && siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { context.put("isCourseSite", Boolean.TRUE); coursesIntoContext(state, context, site); context.put("term", siteProperties .getProperty(PROP_SITE_TERM)); } else { context.put("isCourseSite", Boolean.FALSE); } } catch (Exception e) { M_log.warn(this + " buildContextForTemplate chef_site-siteInfo-list.vm ", e); } roles = getRoles(state); context.put("roles", roles); // will have the choice to active/inactive user or not String activeInactiveUser = ServerConfigurationService.getString( "activeInactiveUser", Boolean.FALSE.toString()); if (activeInactiveUser.equalsIgnoreCase("true")) { context.put("activeInactiveUser", Boolean.TRUE); } else { context.put("activeInactiveUser", Boolean.FALSE); } context.put("groupsWithMember", site .getGroupsWithMember(UserDirectoryService.getCurrentUser() .getId())); return (String) getContext(data).get("template") + TEMPLATE[12]; case 13: /* * buildContextForTemplate chef_site-siteInfo-editInfo.vm * */ siteProperties = site.getProperties(); context.put("title", state.getAttribute(FORM_SITEINFO_TITLE)); context.put("siteTitleEditable", Boolean.valueOf(siteTitleEditable(state, site.getType()))); context.put("type", site.getType()); context.put("titleMaxLength", state.getAttribute(STATE_SITE_TITLE_MAX)); siteType = (String) state.getAttribute(STATE_SITE_TYPE); if (siteType != null && siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { context.put("isCourseSite", Boolean.TRUE); // whether to show course skin selection choices or not courseSkinSelection(context, state, site, null); setTermListForContext(context, state, true); // true->only future terms if (state.getAttribute(FORM_SITEINFO_TERM) == null) { String currentTerm = site.getProperties().getProperty( PROP_SITE_TERM); if (currentTerm != null) { state.setAttribute(FORM_SITEINFO_TERM, currentTerm); } } setSelectedTermForContext(context, state, FORM_SITEINFO_TERM); } else { context.put("isCourseSite", Boolean.FALSE); if (state.getAttribute(FORM_SITEINFO_ICON_URL) == null && StringUtil.trimToNull(site.getIconUrl()) != null) { state.setAttribute(FORM_SITEINFO_ICON_URL, site .getIconUrl()); } if (state.getAttribute(FORM_SITEINFO_ICON_URL) != null) { context.put("iconUrl", state .getAttribute(FORM_SITEINFO_ICON_URL)); } } context.put("description", state .getAttribute(FORM_SITEINFO_DESCRIPTION)); context.put("short_description", state .getAttribute(FORM_SITEINFO_SHORT_DESCRIPTION)); context.put("form_site_contact_name", state .getAttribute(FORM_SITEINFO_CONTACT_NAME)); context.put("form_site_contact_email", state .getAttribute(FORM_SITEINFO_CONTACT_EMAIL)); return (String) getContext(data).get("template") + TEMPLATE[13]; case 14: /* * buildContextForTemplate chef_site-siteInfo-editInfoConfirm.vm * */ siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO); siteProperties = site.getProperties(); siteType = (String) state.getAttribute(STATE_SITE_TYPE); if (siteType != null && siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { context.put("isCourseSite", Boolean.TRUE); context.put("disableCourseSelection", ServerConfigurationService.getString("disable.course.site.skin.selection", "false").equals("true")?Boolean.TRUE:Boolean.FALSE); context.put("siteTerm", state.getAttribute(FORM_SITEINFO_TERM)); } else { context.put("isCourseSite", Boolean.FALSE); } context.put("oTitle", site.getTitle()); context.put("title", siteInfo.title); context.put("description", siteInfo.description); context.put("oDescription", site.getDescription()); context.put("short_description", siteInfo.short_description); context.put("oShort_description", site.getShortDescription()); context.put("skin", siteInfo.iconUrl); context.put("oSkin", site.getIconUrl()); context.put("skins", state.getAttribute(STATE_ICONS)); context.put("oIcon", site.getIconUrl()); context.put("icon", siteInfo.iconUrl); context.put("include", siteInfo.include); context.put("oInclude", Boolean.valueOf(site.isPubView())); context.put("name", siteInfo.site_contact_name); context.put("oName", siteProperties.getProperty(PROP_SITE_CONTACT_NAME)); context.put("email", siteInfo.site_contact_email); context.put("oEmail", siteProperties.getProperty(PROP_SITE_CONTACT_EMAIL)); return (String) getContext(data).get("template") + TEMPLATE[14]; case 15: /* * buildContextForTemplate chef_site-addRemoveFeatureConfirm.vm * */ context.put("title", site.getTitle()); site_type = (String) state.getAttribute(STATE_SITE_TYPE); myworkspace_site = false; if (SiteService.isUserSite(site.getId())) { if (SiteService.getSiteUserId(site.getId()).equals( SessionManager.getCurrentSessionUserId())) { myworkspace_site = true; site_type = "myworkspace"; } } context.put(STATE_TOOL_REGISTRATION_LIST, state .getAttribute(STATE_TOOL_REGISTRATION_LIST)); context.put("check_home", state .getAttribute(STATE_TOOL_HOME_SELECTED)); context.put("selectedTools", orderToolIds(state, checkNullSiteType(state, site), (List) state .getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST))); context.put("oldSelectedTools", state .getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST)); context.put("oldSelectedHome", state .getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME)); context.put("continueIndex", "12"); if (state.getAttribute(STATE_TOOL_EMAIL_ADDRESS) != null) { context.put("emailId", state .getAttribute(STATE_TOOL_EMAIL_ADDRESS)); } context.put("serverName", ServerConfigurationService .getServerName()); // all info related to multiple tools multipleToolIntoContext(context, state); return (String) getContext(data).get("template") + TEMPLATE[15]; case 18: /* * buildContextForTemplate chef_siteInfo-editAccess.vm * */ List publicChangeableSiteTypes = (List) state .getAttribute(STATE_PUBLIC_CHANGEABLE_SITE_TYPES); List unJoinableSiteTypes = (List) state .getAttribute(STATE_DISABLE_JOINABLE_SITE_TYPE); if (site != null) { // editing existing site context.put("site", site); siteType = state.getAttribute(STATE_SITE_TYPE) != null ? (String) state .getAttribute(STATE_SITE_TYPE) : null; if (siteType != null && publicChangeableSiteTypes.contains(siteType)) { context.put("publicChangeable", Boolean.TRUE); } else { context.put("publicChangeable", Boolean.FALSE); } context.put("include", Boolean.valueOf(site.isPubView())); if (siteType != null && !unJoinableSiteTypes.contains(siteType)) { // site can be set as joinable context.put("disableJoinable", Boolean.FALSE); if (state.getAttribute(STATE_JOINABLE) == null) { state.setAttribute(STATE_JOINABLE, Boolean.valueOf(site .isJoinable())); } if (state.getAttribute(STATE_JOINERROLE) == null || state.getAttribute(STATE_JOINABLE) != null && ((Boolean) state.getAttribute(STATE_JOINABLE)) .booleanValue()) { state.setAttribute(STATE_JOINERROLE, site .getJoinerRole()); } if (state.getAttribute(STATE_JOINABLE) != null) { context.put("joinable", state .getAttribute(STATE_JOINABLE)); } if (state.getAttribute(STATE_JOINERROLE) != null) { context.put("joinerRole", state .getAttribute(STATE_JOINERROLE)); } } else { // site cannot be set as joinable context.put("disableJoinable", Boolean.TRUE); } context.put("roles", getRoles(state)); } else { siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO); if (siteInfo.site_type != null && publicChangeableSiteTypes .contains(siteInfo.site_type)) { context.put("publicChangeable", Boolean.TRUE); } else { context.put("publicChangeable", Boolean.FALSE); } context.put("include", Boolean.valueOf(siteInfo.getInclude())); context.put("published", Boolean.valueOf(siteInfo .getPublished())); if (siteInfo.site_type != null && !unJoinableSiteTypes.contains(siteInfo.site_type)) { // site can be set as joinable context.put("disableJoinable", Boolean.FALSE); context.put("joinable", Boolean.valueOf(siteInfo.joinable)); context.put("joinerRole", siteInfo.joinerRole); } else { // site cannot be set as joinable context.put("disableJoinable", Boolean.TRUE); } // the template site, if using one Site templateSite = (Site) state.getAttribute(STATE_TEMPLATE_SITE); // use the type's template, if defined String realmTemplate = "!site.template"; // if create based on template, use the roles from the template if (templateSite != null) { realmTemplate = SiteService.siteReference(templateSite.getId()); } else if (siteInfo.site_type != null) { realmTemplate = realmTemplate + "." + siteInfo.site_type; } try { AuthzGroup r = AuthzGroupService.getAuthzGroup(realmTemplate); context.put("roles", r.getRoles()); } catch (GroupNotDefinedException e) { try { AuthzGroup rr = AuthzGroupService.getAuthzGroup("!site.template"); context.put("roles", rr.getRoles()); } catch (GroupNotDefinedException ee) { } } // new site, go to confirmation page context.put("continue", "10"); siteType = (String) state.getAttribute(STATE_SITE_TYPE); if (siteType != null && siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { context.put("isCourseSite", Boolean.TRUE); context.put("isProjectSite", Boolean.FALSE); } else { context.put("isCourseSite", Boolean.FALSE); if (siteType.equalsIgnoreCase("project")) { context.put("isProjectSite", Boolean.TRUE); } } } return (String) getContext(data).get("template") + TEMPLATE[18]; case 26: /* * buildContextForTemplate chef_site-modifyENW.vm * */ site_type = (String) state.getAttribute(STATE_SITE_TYPE); boolean existingSite = site != null ? true : false; if (existingSite) { // revising a existing site's tool context.put("existingSite", Boolean.TRUE); context.put("continue", "15"); } else { // new site context.put("existingSite", Boolean.FALSE); context.put("continue", "18"); } context.put("function", "eventSubmit_doAdd_features"); context.put(STATE_TOOL_REGISTRATION_LIST, state .getAttribute(STATE_TOOL_REGISTRATION_LIST)); toolRegistrationSelectedList = (List) state .getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); context.put(STATE_TOOL_REGISTRATION_SELECTED_LIST, toolRegistrationSelectedList); // String toolId's // all info related to multiple tools multipleToolIntoContext(context, state); context.put("toolManager", ToolManager.getInstance()); String emailId = (String) state.getAttribute(STATE_TOOL_EMAIL_ADDRESS); if (emailId != null) { context.put("emailId", emailId); } context.put("serverName", ServerConfigurationService .getServerName()); context.put("oldSelectedTools", state .getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST)); context.put("homeToolId", getHomeToolId(state)); return (String) getContext(data).get("template") + TEMPLATE[26]; case 27: /* * buildContextForTemplate chef_site-importSites.vm * */ existingSite = site != null ? true : false; site_type = (String) state.getAttribute(STATE_SITE_TYPE); if (existingSite) { // revising a existing site's tool context.put("continue", "12"); context.put("totalSteps", "2"); context.put("step", "2"); context.put("currentSite", site); } else { // new site, go to edit access page if (fromENWModifyView(state)) { context.put("continue", "26"); } else { context.put("continue", "18"); } } context.put("existingSite", Boolean.valueOf(existingSite)); context.put(STATE_TOOL_REGISTRATION_LIST, state .getAttribute(STATE_TOOL_REGISTRATION_LIST)); context.put("selectedTools", orderToolIds(state, site_type, (List) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST))); // String toolId's context.put("importSites", state.getAttribute(STATE_IMPORT_SITES)); context.put("importSitesTools", state .getAttribute(STATE_IMPORT_SITE_TOOL)); context.put("check_home", state .getAttribute(STATE_TOOL_HOME_SELECTED)); context.put("importSupportedTools", importTools()); return (String) getContext(data).get("template") + TEMPLATE[27]; case 60: /* * buildContextForTemplate chef_site-importSitesMigrate.vm * */ existingSite = site != null ? true : false; site_type = (String) state.getAttribute(STATE_SITE_TYPE); if (existingSite) { // revising a existing site's tool context.put("continue", "12"); context.put("back", "28"); context.put("totalSteps", "2"); context.put("step", "2"); context.put("currentSite", site); } else { // new site, go to edit access page context.put("back", "3"); if (fromENWModifyView(state)) { context.put("continue", "26"); } else { context.put("continue", "18"); } } // get the tool id list List<String> toolIdList = new Vector<String>(); if (existingSite) { // list all site tools which are displayed on its own page List<SitePage> sitePages = site.getPages(); if (sitePages != null) { for (SitePage page: sitePages) { List<ToolConfiguration> pageToolsList = page.getTools(0); // we only handle one tool per page case if ( page.getLayout() == SitePage.LAYOUT_SINGLE_COL && pageToolsList.size() == 1) { toolIdList.add(pageToolsList.get(0).getToolId()); } } } } else { // during site creation toolIdList = (List<String>) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); } state.setAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST, toolIdList); // order it SortedIterator iToolIdList = new SortedIterator(getToolsAvailableForImport(state, toolIdList).iterator(),new ToolComparator()); Hashtable<String, String> toolTitleTable = new Hashtable<String, String>(); for(;iToolIdList.hasNext();) { String toolId = (String) iToolIdList.next(); try { String toolTitle = ToolManager.getTool(toolId).getTitle(); toolTitleTable.put(toolId, toolTitle); } catch (Exception e) { Log.info("chef", this + " buildContexForTemplate case 60: cannot get tool title for " + toolId + e.getMessage()); } } context.put("selectedTools", toolTitleTable); // String toolId's context.put("importSites", state.getAttribute(STATE_IMPORT_SITES)); context.put("importSitesTools", state .getAttribute(STATE_IMPORT_SITE_TOOL)); context.put("check_home", state .getAttribute(STATE_TOOL_HOME_SELECTED)); context.put("importSupportedTools", importTools()); return (String) getContext(data).get("template") + TEMPLATE[60]; case 28: /* * buildContextForTemplate chef_siteinfo-import.vm * */ context.put("currentSite", site); context.put("importSiteList", state .getAttribute(STATE_IMPORT_SITES)); context.put("sites", SiteService.getSites( org.sakaiproject.site.api.SiteService.SelectionType.UPDATE, null, null, null, SortType.TITLE_ASC, null)); return (String) getContext(data).get("template") + TEMPLATE[28]; case 58: /* * buildContextForTemplate chef_siteinfo-importSelection.vm * */ context.put("currentSite", site); context.put("importSiteList", state .getAttribute(STATE_IMPORT_SITES)); context.put("sites", SiteService.getSites( org.sakaiproject.site.api.SiteService.SelectionType.UPDATE, null, null, null, SortType.TITLE_ASC, null)); return (String) getContext(data).get("template") + TEMPLATE[58]; case 59: /* * buildContextForTemplate chef_siteinfo-importMigrate.vm * */ context.put("currentSite", site); context.put("importSiteList", state .getAttribute(STATE_IMPORT_SITES)); context.put("sites", SiteService.getSites( org.sakaiproject.site.api.SiteService.SelectionType.UPDATE, null, null, null, SortType.TITLE_ASC, null)); return (String) getContext(data).get("template") + TEMPLATE[59]; case 29: /* * buildContextForTemplate chef_siteinfo-duplicate.vm * */ context.put("siteTitle", site.getTitle()); String sType = site.getType(); if (sType != null && sType.equals((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { context.put("isCourseSite", Boolean.TRUE); context.put("currentTermId", site.getProperties().getProperty( PROP_SITE_TERM)); setTermListForContext(context, state, true); // true upcoming only } else { context.put("isCourseSite", Boolean.FALSE); } if (state.getAttribute(SITE_DUPLICATED) == null) { context.put("siteDuplicated", Boolean.FALSE); } else { context.put("siteDuplicated", Boolean.TRUE); context.put("duplicatedName", state .getAttribute(SITE_DUPLICATED_NAME)); } return (String) getContext(data).get("template") + TEMPLATE[29]; case 36: /* * buildContextForTemplate chef_site-newSiteCourse.vm */ // SAK-9824 Boolean enableCourseCreationForUser = ServerConfigurationService.getBoolean("site.enableCreateAnyUser", Boolean.FALSE); context.put("enableCourseCreationForUser", enableCourseCreationForUser); if (site != null) { context.put("site", site); context.put("siteTitle", site.getTitle()); setTermListForContext(context, state, true); // true -> upcoming only List providerCourseList = (List) state .getAttribute(SITE_PROVIDER_COURSE_LIST); coursesIntoContext(state, context, site); AcademicSession t = (AcademicSession) state .getAttribute(STATE_TERM_SELECTED); context.put("term", t); if (t != null) { String userId = UserDirectoryService.getCurrentUser().getEid(); List courses = prepareCourseAndSectionListing(userId, t .getEid(), state); if (courses != null && courses.size() > 0) { Vector notIncludedCourse = new Vector(); // remove included sites for (Iterator i = courses.iterator(); i.hasNext();) { CourseObject c = (CourseObject) i.next(); if (providerCourseList == null || providerCourseList != null && !providerCourseList.contains(c.getEid())) { notIncludedCourse.add(c); } } state.setAttribute(STATE_TERM_COURSE_LIST, notIncludedCourse); } else { state.removeAttribute(STATE_TERM_COURSE_LIST); } } // step number used in UI state.setAttribute(SITE_CREATE_CURRENT_STEP, new Integer("1")); } else { // need to include both list 'cos STATE_CM_AUTHORIZER_SECTIONS // contains sections that doens't belongs to current user and // STATE_ADD_CLASS_PROVIDER_CHOSEN contains section that does - // v2.4 daisyf if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null || state.getAttribute(STATE_CM_AUTHORIZER_SECTIONS) != null) { List<String> providerSectionList = (List<String>) state .getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN); if (providerSectionList != null) { /* List list1 = prepareSectionObject(providerSectionList, (String) state .getAttribute(STATE_CM_CURRENT_USERID)); */ context.put("selectedProviderCourse", providerSectionList); } List<SectionObject> authorizerSectionList = (List<SectionObject>) state .getAttribute(STATE_CM_AUTHORIZER_SECTIONS); if (authorizerSectionList != null) { List authorizerList = (List) state .getAttribute(STATE_CM_AUTHORIZER_LIST); //authorizerList is a list of SectionObject /* String userId = null; if (authorizerList != null) { userId = (String) authorizerList.get(0); } List list2 = prepareSectionObject( authorizerSectionList, userId); */ ArrayList list2 = new ArrayList(); for (int i=0; i<authorizerSectionList.size();i++){ SectionObject so = (SectionObject)authorizerSectionList.get(i); list2.add(so.getEid()); } context.put("selectedAuthorizerCourse", list2); } } if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) { context.put("selectedManualCourse", Boolean.TRUE); } context.put("term", (AcademicSession) state .getAttribute(STATE_TERM_SELECTED)); context.put("currentUserId", (String) state .getAttribute(STATE_CM_CURRENT_USERID)); context.put("form_additional", (String) state .getAttribute(FORM_ADDITIONAL)); context.put("authorizers", getAuthorizers(state)); } if (((String) state.getAttribute(STATE_SITE_MODE)) .equalsIgnoreCase(SITE_MODE_SITESETUP)) { context.put("backIndex", "1"); } else if (((String) state.getAttribute(STATE_SITE_MODE)) .equalsIgnoreCase(SITE_MODE_SITEINFO)) { context.put("backIndex", ""); } List ll = (List) state.getAttribute(STATE_TERM_COURSE_LIST); context.put("termCourseList", state .getAttribute(STATE_TERM_COURSE_LIST)); // added for 2.4 -daisyf context.put("campusDirectory", getCampusDirectory()); context.put("userId", (String) state .getAttribute(STATE_INSTRUCTOR_SELECTED)); /* * for measuring how long it takes to load sections java.util.Date * date = new java.util.Date(); M_log.debug("***2. finish at: * "+date); M_log.debug("***3. userId:"+(String) state * .getAttribute(STATE_INSTRUCTOR_SELECTED)); */ return (String) getContext(data).get("template") + TEMPLATE[36]; case 37: /* * buildContextForTemplate chef_site-newSiteCourseManual.vm */ if (site != null) { context.put("site", site); context.put("siteTitle", site.getTitle()); coursesIntoContext(state, context, site); } buildInstructorSectionsList(state, params, context); context.put("form_requiredFields", sectionFieldProvider .getRequiredFields()); context.put("form_additional", siteInfo.additional); context.put("form_title", siteInfo.title); context.put("form_description", siteInfo.description); context.put("officialAccountName", ServerConfigurationService .getString("officialAccountName", "")); context.put("value_uniqname", state .getAttribute(STATE_SITE_QUEST_UNIQNAME)); int number = 1; if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) { number = ((Integer) state .getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)) .intValue(); context.put("currentNumber", new Integer(number)); } context.put("currentNumber", new Integer(number)); context.put("listSize", number>0?new Integer(number - 1):0); if (state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS) != null && ((List) state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS)).size() > 0) { context.put("fieldValues", state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS)); } if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null) { List l = (List) state .getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN); context.put("selectedProviderCourse", l); context.put("size", new Integer(l.size() - 1)); } if (state.getAttribute(STATE_CM_REQUESTED_SECTIONS) != null) { List l = (List) state .getAttribute(STATE_CM_REQUESTED_SECTIONS); context.put("cmRequestedSections", l); } if (state.getAttribute(STATE_SITE_MODE).equals(SITE_MODE_SITEINFO)) { context.put("editSite", Boolean.TRUE); context.put("cmSelectedSections", state.getAttribute(STATE_CM_SELECTED_SECTIONS)); } if (site == null) { if (state.getAttribute(STATE_AUTO_ADD) != null) { context.put("autoAdd", Boolean.TRUE); } } isFutureTermSelected(state); context.put("isFutureTerm", state .getAttribute(STATE_FUTURE_TERM_SELECTED)); context.put("weeksAhead", ServerConfigurationService.getString( "roster.available.weeks.before.term.start", "0")); return (String) getContext(data).get("template") + TEMPLATE[37]; case 42: /* * buildContextForTemplate chef_site-gradtoolsConfirm.vm * */ siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO); context.put("title", siteInfo.title); context.put("description", siteInfo.description); context.put("short_description", siteInfo.short_description); toolRegistrationList = (Vector) state .getAttribute(STATE_PROJECT_TOOL_LIST); toolRegistrationSelectedList = (List) state .getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); context.put(STATE_TOOL_REGISTRATION_SELECTED_LIST, toolRegistrationSelectedList); // String toolId's context.put(STATE_TOOL_REGISTRATION_LIST, toolRegistrationList); // %%% // use // Tool context.put("check_home", state .getAttribute(STATE_TOOL_HOME_SELECTED)); context .put("emailId", state .getAttribute(STATE_TOOL_EMAIL_ADDRESS)); context.put("serverName", ServerConfigurationService .getServerName()); context.put("include", new Boolean(siteInfo.include)); return (String) getContext(data).get("template") + TEMPLATE[42]; case 43: /* * buildContextForTemplate chef_siteInfo-editClass.vm * */ bar = new MenuImpl(portlet, data, (String) state .getAttribute(STATE_ACTION)); if (SiteService.allowAddSite(null)) { bar.add(new MenuEntry(rb.getString("java.addclasses"), "doMenu_siteInfo_addClass")); } context.put("menu", bar); context.put("siteTitle", site.getTitle()); coursesIntoContext(state, context, site); return (String) getContext(data).get("template") + TEMPLATE[43]; case 44: /* * buildContextForTemplate chef_siteInfo-addCourseConfirm.vm * */ context.put("siteTitle", site.getTitle()); coursesIntoContext(state, context, site); context.put("providerAddCourses", state .getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN)); if (state.getAttribute(STATE_CM_SELECTED_SECTIONS) != null) { context.put("cmSelectedSections", state.getAttribute(STATE_CM_SELECTED_SECTIONS)); } if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) { int addNumber = ((Integer) state .getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)) .intValue() - 1; context.put("manualAddNumber", new Integer(addNumber)); context.put("requestFields", state .getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS)); context.put("backIndex", "37"); } else { context.put("backIndex", "36"); } // those manual inputs context.put("form_requiredFields", sectionFieldProvider .getRequiredFields()); context.put("fieldValues", state .getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS)); return (String) getContext(data).get("template") + TEMPLATE[44]; // htripath - import materials from classic case 45: /* * buildContextForTemplate chef_siteInfo-importMtrlMaster.vm * */ return (String) getContext(data).get("template") + TEMPLATE[45]; case 46: /* * buildContextForTemplate chef_siteInfo-importMtrlCopy.vm * */ // this is for list display in listbox context .put("allZipSites", state .getAttribute(ALL_ZIP_IMPORT_SITES)); context.put("finalZipSites", state .getAttribute(FINAL_ZIP_IMPORT_SITES)); // zip file // context.put("zipreffile",state.getAttribute(CLASSIC_ZIP_FILE_NAME)); return (String) getContext(data).get("template") + TEMPLATE[46]; case 47: /* * buildContextForTemplate chef_siteInfo-importMtrlCopyConfirm.vm * */ context.put("finalZipSites", state .getAttribute(FINAL_ZIP_IMPORT_SITES)); return (String) getContext(data).get("template") + TEMPLATE[47]; case 48: /* * buildContextForTemplate chef_siteInfo-importMtrlCopyConfirm.vm * */ context.put("finalZipSites", state .getAttribute(FINAL_ZIP_IMPORT_SITES)); return (String) getContext(data).get("template") + TEMPLATE[48]; // case 49, 50, 51 have been implemented in helper mode case 53: { /* * build context for chef_site-findCourse.vm */ AcademicSession t = (AcademicSession) state .getAttribute(STATE_TERM_SELECTED); List cmLevels = (List) state.getAttribute(STATE_CM_LEVELS), selections = (List) state .getAttribute(STATE_CM_LEVEL_SELECTIONS); if (cmLevels == null) { cmLevels = getCMLevelLabels(); } SectionObject selectedSect = (SectionObject) state .getAttribute(STATE_CM_SELECTED_SECTION); List<SectionObject> requestedSections = (List<SectionObject>) state .getAttribute(STATE_CM_REQUESTED_SECTIONS); if (courseManagementIsImplemented() && cms != null) { context.put("cmsAvailable", new Boolean(true)); } int cmLevelSize = 0; if (cms == null || !courseManagementIsImplemented() || cmLevels == null || cmLevels.size() < 1) { // TODO: redirect to manual entry: case #37 } else { cmLevelSize = cmLevels.size(); Object levelOpts[] = state.getAttribute(STATE_CM_LEVEL_OPTS) == null?new Object[cmLevelSize]:(Object[])state.getAttribute(STATE_CM_LEVEL_OPTS); int numSelections = 0; if (selections != null) { numSelections = selections.size(); // execution will fall through these statements based on number of selections already made if (numSelections == cmLevelSize - 1) { levelOpts[numSelections] = getCMSections((String) selections.get(numSelections-1)); } else if (numSelections == cmLevelSize - 2) { levelOpts[numSelections] = getCMCourseOfferings((String) selections.get(numSelections-1), t.getEid()); } else if (numSelections < cmLevelSize) { levelOpts[numSelections] = sortCmObject(cms.findCourseSets((String) cmLevels.get(numSelections==0?0:numSelections-1))); } // always set the top level levelOpts[0] = sortCmObject(cms.findCourseSets((String) cmLevels.get(0))); // clean further element inside the array for (int i = numSelections + 1; i<cmLevelSize; i++) { levelOpts[i] = null; } } context.put("cmLevelOptions", Arrays.asList(levelOpts)); state.setAttribute(STATE_CM_LEVEL_OPTS, levelOpts); } if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null) { context.put("selectedProviderCourse", state .getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN)); } if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) { int courseInd = ((Integer) state .getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)) .intValue(); context.put("manualAddNumber", new Integer(courseInd - 1)); context.put("manualAddFields", state .getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS)); } context.put("term", (AcademicSession) state .getAttribute(STATE_TERM_SELECTED)); context.put("cmLevels", cmLevels); context.put("cmLevelSelections", selections); context.put("selectedCourse", selectedSect); context.put("cmRequestedSections", requestedSections); if (state.getAttribute(STATE_SITE_MODE).equals(SITE_MODE_SITEINFO)) { context.put("editSite", Boolean.TRUE); context.put("cmSelectedSections", state.getAttribute(STATE_CM_SELECTED_SECTIONS)); } if (((String) state.getAttribute(STATE_SITE_MODE)) .equalsIgnoreCase(SITE_MODE_SITESETUP)) { if (state.getAttribute(STATE_TERM_COURSE_LIST) != null) { context.put("backIndex", "36"); } else { context.put("backIndex", "1"); } } else if (((String) state.getAttribute(STATE_SITE_MODE)).equalsIgnoreCase(SITE_MODE_SITEINFO)) { context.put("backIndex", "36"); } context.put("authzGroupService", AuthzGroupService.getInstance()); return (String) getContext(data).get("template") + TEMPLATE[53]; } case 54: /* * build context for chef_site-questions.vm */ SiteTypeQuestions siteTypeQuestions = questionService.getSiteTypeQuestions((String) state.getAttribute(STATE_SITE_TYPE)); if (siteTypeQuestions != null) { context.put("questionSet", siteTypeQuestions); context.put("userAnswers", state.getAttribute(STATE_SITE_SETUP_QUESTION_ANSWER)); } context.put("continueIndex", state.getAttribute(STATE_SITE_SETUP_QUESTION_NEXT_TEMPLATE)); return (String) getContext(data).get("template") + TEMPLATE[54]; } // should never be reached return (String) getContext(data).get("template") + TEMPLATE[0]; }
diff --git a/nuxeo-drive-server/nuxeo-drive-core/src/main/java/org/nuxeo/drive/listener/NuxeoDriveCacheInvalidationListener.java b/nuxeo-drive-server/nuxeo-drive-core/src/main/java/org/nuxeo/drive/listener/NuxeoDriveCacheInvalidationListener.java index 15811a53..864344cd 100644 --- a/nuxeo-drive-server/nuxeo-drive-core/src/main/java/org/nuxeo/drive/listener/NuxeoDriveCacheInvalidationListener.java +++ b/nuxeo-drive-server/nuxeo-drive-core/src/main/java/org/nuxeo/drive/listener/NuxeoDriveCacheInvalidationListener.java @@ -1,54 +1,54 @@ /* * (C) Copyright 2012 Nuxeo SA (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: * Olivier Grisel <[email protected]> */ package org.nuxeo.drive.listener; import org.nuxeo.drive.service.NuxeoDriveManager; import org.nuxeo.ecm.core.api.ClientException; import org.nuxeo.ecm.core.api.IdRef; import org.nuxeo.ecm.core.api.LifeCycleConstants; import org.nuxeo.ecm.core.event.Event; import org.nuxeo.ecm.core.event.EventListener; import org.nuxeo.ecm.core.event.impl.DocumentEventContext; import org.nuxeo.runtime.api.Framework; /** * Notify the NuxeoDriveManager service in case of document deletions so as to * make it possible to invalidate any cache. */ public class NuxeoDriveCacheInvalidationListener implements EventListener { @Override public void handleEvent(Event event) throws ClientException { DocumentEventContext docCtx; if (event.getContext() instanceof DocumentEventContext) { docCtx = (DocumentEventContext) event.getContext(); } else { // not interested in event that are not related to documents return; } String transition = (String) docCtx.getProperty(LifeCycleConstants.TRANSTION_EVENT_OPTION_TRANSITION); if (transition != null - && !LifeCycleConstants.DELETE_TRANSITION.equals(transition)) { + && !(LifeCycleConstants.DELETE_TRANSITION.equals(transition) || LifeCycleConstants.UNDELETE_TRANSITION.equals(transition))) { // not interested in lifecycle transitions that are not related to // document deletion return; } NuxeoDriveManager driveManager = Framework.getLocalService(NuxeoDriveManager.class); driveManager.handleFolderDeletion((IdRef) docCtx.getSourceDocument().getRef()); } }
true
true
public void handleEvent(Event event) throws ClientException { DocumentEventContext docCtx; if (event.getContext() instanceof DocumentEventContext) { docCtx = (DocumentEventContext) event.getContext(); } else { // not interested in event that are not related to documents return; } String transition = (String) docCtx.getProperty(LifeCycleConstants.TRANSTION_EVENT_OPTION_TRANSITION); if (transition != null && !LifeCycleConstants.DELETE_TRANSITION.equals(transition)) { // not interested in lifecycle transitions that are not related to // document deletion return; } NuxeoDriveManager driveManager = Framework.getLocalService(NuxeoDriveManager.class); driveManager.handleFolderDeletion((IdRef) docCtx.getSourceDocument().getRef()); }
public void handleEvent(Event event) throws ClientException { DocumentEventContext docCtx; if (event.getContext() instanceof DocumentEventContext) { docCtx = (DocumentEventContext) event.getContext(); } else { // not interested in event that are not related to documents return; } String transition = (String) docCtx.getProperty(LifeCycleConstants.TRANSTION_EVENT_OPTION_TRANSITION); if (transition != null && !(LifeCycleConstants.DELETE_TRANSITION.equals(transition) || LifeCycleConstants.UNDELETE_TRANSITION.equals(transition))) { // not interested in lifecycle transitions that are not related to // document deletion return; } NuxeoDriveManager driveManager = Framework.getLocalService(NuxeoDriveManager.class); driveManager.handleFolderDeletion((IdRef) docCtx.getSourceDocument().getRef()); }
diff --git a/txtfnnl-uima/src/main/java/txtfnnl/uima/collection/AnnotationLineWriter.java b/txtfnnl-uima/src/main/java/txtfnnl/uima/collection/AnnotationLineWriter.java index 3c55871..e988716 100644 --- a/txtfnnl-uima/src/main/java/txtfnnl/uima/collection/AnnotationLineWriter.java +++ b/txtfnnl-uima/src/main/java/txtfnnl/uima/collection/AnnotationLineWriter.java @@ -1,308 +1,312 @@ package txtfnnl.uima.collection; import java.io.IOException; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang.StringUtils; import org.apache.uima.UimaContext; import org.apache.uima.analysis_component.AnalysisComponent; import org.apache.uima.analysis_engine.AnalysisEngineProcessException; import org.apache.uima.cas.CAS; import org.apache.uima.cas.CASException; import org.apache.uima.cas.FSIterator; import org.apache.uima.cas.FSMatchConstraint; import org.apache.uima.jcas.JCas; import org.apache.uima.jcas.cas.FSArray; import org.apache.uima.jcas.tcas.Annotation; import org.apache.uima.resource.ResourceInitializationException; import org.apache.uima.util.Level; import org.uimafit.descriptor.ConfigurationParameter; import txtfnnl.uima.cas.Property; import txtfnnl.uima.tcas.TextAnnotation; import txtfnnl.uima.tcas.TokenAnnotation; /** * A CAS consumer that writes out a particular annotation type, where each line represents a hit * and the found data. * * @see TextWriter * @author Florian Leitner */ public class AnnotationLineWriter extends TextWriter { /** * If <code>true</code> (the default), line-breaks within covered text will be replaced with * white-spaces. */ public static final String PARAM_REPLACE_NEWLINES = "ReplaceNewlines"; @ConfigurationParameter(name = PARAM_REPLACE_NEWLINES, defaultValue = "true") private Boolean replaceNewlines; /** * If <code>true</code> (the default), tabulators within covered text will be replaced with * white-spaces. */ public static final String PARAM_REPLACE_TABS = "ReplaceTabulators"; @ConfigurationParameter(name = PARAM_REPLACE_TABS, defaultValue = "true") private Boolean replaceTabs; /** * If <code>true</code> the token before and after the annotation are shown, as well as any * prefix and suffix, as word-before TAB prefix TAB annotation TAB suffix TAB word-after instead * of just the annotation. */ public static final String PARAM_PRINT_SURROUNDINGS = "PrintSurroundings"; @ConfigurationParameter(name = PARAM_PRINT_SURROUNDINGS, defaultValue = "false") private Boolean printSurroundings; /** * If <code>true</code> the matching token's PoS tag of the annotation is added as a row after * the annotation itself. */ public static final String PARAM_PRINT_POS_TAG = "PrintPosTag"; @ConfigurationParameter(name = PARAM_PRINT_POS_TAG, defaultValue = "false") private Boolean printPosTag; public static final String PARAM_ANNOTATOR_URI = "AnnotatorUri"; @ConfigurationParameter(name = PARAM_ANNOTATOR_URI) private String annotatorUri; public static final String PARAM_ANNOTATION_NAMESPACE = "AnnotationNamespace"; @ConfigurationParameter(name = PARAM_ANNOTATION_NAMESPACE) private String annotationNs; public static final String PARAM_ANNOTATION_ID = "AnnotationId"; @ConfigurationParameter(name = PARAM_ANNOTATION_ID) private String annotationId; static final String LINEBREAK = System.getProperty("line.separator"); private static NumberFormat decimals = DecimalFormat.getInstance(); { decimals.setMaximumFractionDigits(5); decimals.setMinimumFractionDigits(5); } public static class Builder extends TextWriter.Builder { protected Builder(Class<? extends AnalysisComponent> klass) { super(klass); } public Builder() { super(AnnotationLineWriter.class); } public Builder maintainNewlines() { setOptionalParameter(PARAM_REPLACE_NEWLINES, false); return this; } public Builder maintainTabulators() { setOptionalParameter(PARAM_REPLACE_TABS, false); return this; } public Builder setAnnotatorUri(String uri) { setOptionalParameter(PARAM_ANNOTATOR_URI, uri); return this; } public Builder setAnnotationNamespace(String ns) { setOptionalParameter(PARAM_ANNOTATION_NAMESPACE, ns); return this; } public Builder setAnnotationId(String id) { setOptionalParameter(PARAM_ANNOTATION_ID, id); return this; } public Builder printSurroundings() { setOptionalParameter(PARAM_PRINT_SURROUNDINGS, true); return this; } public Builder printPosTag() { setOptionalParameter(PARAM_PRINT_POS_TAG, true); return this; } } public static Builder configure() { return new Builder(); } @Override public void initialize(UimaContext ctx) throws ResourceInitializationException { super.initialize(ctx); logger.log(Level.CONFIG, "constraint: '" + annotatorUri + "@" + annotationNs + ":" + annotationId + "'"); } private static final int BEFORE = 0; private static final int PREFIX = 1; private static final int SUFFIX = 3; private static final int AFTER = 4; @Override public void process(CAS cas) throws AnalysisEngineProcessException { JCas textJCas; try { textJCas = cas.getJCas(); setStream(textJCas); } catch (CASException e1) { throw new AnalysisEngineProcessException(e1); } catch (final IOException e2) { throw new AnalysisEngineProcessException(e2); } FSMatchConstraint cons = TextAnnotation.makeConstraint(textJCas, annotatorUri, annotationNs, annotationId); FSIterator<Annotation> annotationIter = textJCas.createFilteredIterator( TextAnnotation.getIterator(textJCas), cons); TokenAnnotation[] tokens = new TokenAnnotation[5]; List<TokenAnnotation> allTokens = new ArrayList<TokenAnnotation>(); if (printSurroundings || printPosTag) { FSIterator<Annotation> it = TokenAnnotation.getIterator(textJCas); while (it.hasNext()) allTokens.add((TokenAnnotation) it.next()); } int allTokensIdx = 0; int allTokensLen = allTokens.size(); tokens[2] = null; int annCount = 0; while (annotationIter.hasNext()) { final TextAnnotation ann = (TextAnnotation) annotationIter.next(); annCount++; String text = ann.getCoveredText(); if (replaceTabs) text = text.replace('\t', ' '); String posTag = null; if (printSurroundings) { String[] surrounding = new String[] { "", "", text, "", "" }; TokenAnnotation beforeTok = null; int idx = allTokensIdx; while (idx < allTokensLen) { TokenAnnotation tok = allTokens.get(idx++); if (isBefore(tok, ann)) { beforeTok = tok; allTokensIdx = idx - 1; } else { String txt = tok.getCoveredText(); if (isSurrounding(tok, ann)) { surrounding[PREFIX] = txt.substring(0, ann.getBegin() - tok.getBegin()); surrounding[SUFFIX] = txt.substring(ann.getEnd() - tok.getBegin()); posTag = tok.getPos(); } else if (isAtBegin(tok, ann)) { surrounding[PREFIX] = txt.substring(0, ann.getBegin() - tok.getBegin()); posTag = tok.getPos(); } else if (isAtEnd(tok, ann)) { surrounding[SUFFIX] = txt.substring(ann.getEnd() - tok.getBegin()); if (posTag == null) posTag = tok.getPos(); } else if (isAfter(tok, ann)) { surrounding[AFTER] = txt; break; // done! } else if (isEnclosed(tok, ann)) { if (posTag == null) posTag = tok.getPos(); // "inner" token - do nothing (otherwise) } else { this.logger.log(Level.WARNING, "token position %s undetermined relative to annotation %s", new String[] { tok.getOffset().toString(), ann.getOffset().toString() }); break; } if (beforeTok != null) { surrounding[BEFORE] = beforeTok.getCoveredText(); beforeTok = null; } } } if (replaceTabs) for (int i = 0; i < surrounding.length; ++i) surrounding[i] = surrounding[i].replace('\t', ' '); text = StringUtils.join(surrounding, '\t'); } // end printSurroundings if (printPosTag) { if (posTag == null) { int idx = allTokensIdx; while (idx < allTokensLen) { TokenAnnotation tok = allTokens.get(idx++); if (isSurrounding(tok, ann)) { posTag = tok.getPos(); allTokensIdx = idx - 1; break; } else if (isAtBegin(tok, ann)) { posTag = tok.getPos(); allTokensIdx = idx - 1; break; } else if (isBefore(tok, ann)) { // continue searching } else { break; } } } if (posTag == null) posTag = "NULL"; text = String.format("%s\t%s", text, posTag); } // end printPosTag if (replaceNewlines) text = text.replace('\n', ' '); try { write(text); write('\t'); + write(ann.getOffset().toString()); + write('\t'); if (annotatorUri == null) write(ann.getAnnotator()); if (annotatorUri == null && annotationNs == null) write('@'); else if (annotatorUri == null) write('\t'); if (annotationNs == null) write(ann.getNamespace()); if (annotationNs == null && annotationId == null) write(':'); else if (annotationNs == null) write('\t'); if (annotationId == null) { write(ann.getIdentifier()); write('\t'); } FSArray props = ann.getProperties(); - for (int i = 0; i < props.size(); i++) { - Property p = (Property) props.get(i); - if (p.getName().contains(" ")) { + if (props != null) { + for (int i = 0; i < props.size(); i++) { + Property p = (Property) props.get(i); + if (p.getName().contains(" ")) { + write('"'); + write(p.getName()); + write('"'); + } else { + write(p.getName()); + } + write('='); write('"'); - write(p.getName()); + write(replaceNewlines ? p.getValue().replace('\n', ' ') : p.getValue()); write('"'); - } else { - write(p.getName()); + write('\t'); } - write('='); - write('"'); - write(replaceNewlines ? p.getValue().replace('\n', ' ') : p.getValue()); - write('"'); - write('\t'); } write(decimals.format(ann.getConfidence())); write(LINEBREAK); } catch (final IOException e) { throw new AnalysisEngineProcessException(e); } } try { unsetStream(); } catch (final IOException e) { throw new AnalysisEngineProcessException(e); } logger.log(Level.FINE, "wrote {0} annotations", annCount); } private static boolean isBefore(TokenAnnotation tok, TextAnnotation ann) { return tok.getEnd() <= ann.getBegin(); } private static boolean isSurrounding(TokenAnnotation tok, TextAnnotation ann) { return tok.getBegin() < ann.getBegin() && tok.getEnd() > ann.getEnd(); } private static boolean isEnclosed(TokenAnnotation tok, TextAnnotation ann) { return tok.getBegin() >= ann.getBegin() && tok.getEnd() <= ann.getEnd(); } private static boolean isAtBegin(TokenAnnotation tok, TextAnnotation ann) { return tok.getEnd() > ann.getBegin() && tok.getBegin() < ann.getBegin(); } private static boolean isAtEnd(TokenAnnotation tok, TextAnnotation ann) { return tok.getBegin() < ann.getEnd() && tok.getEnd() > ann.getEnd(); } private static boolean isAfter(TokenAnnotation tok, TextAnnotation ann) { return tok.getBegin() >= ann.getEnd(); } }
false
true
public void process(CAS cas) throws AnalysisEngineProcessException { JCas textJCas; try { textJCas = cas.getJCas(); setStream(textJCas); } catch (CASException e1) { throw new AnalysisEngineProcessException(e1); } catch (final IOException e2) { throw new AnalysisEngineProcessException(e2); } FSMatchConstraint cons = TextAnnotation.makeConstraint(textJCas, annotatorUri, annotationNs, annotationId); FSIterator<Annotation> annotationIter = textJCas.createFilteredIterator( TextAnnotation.getIterator(textJCas), cons); TokenAnnotation[] tokens = new TokenAnnotation[5]; List<TokenAnnotation> allTokens = new ArrayList<TokenAnnotation>(); if (printSurroundings || printPosTag) { FSIterator<Annotation> it = TokenAnnotation.getIterator(textJCas); while (it.hasNext()) allTokens.add((TokenAnnotation) it.next()); } int allTokensIdx = 0; int allTokensLen = allTokens.size(); tokens[2] = null; int annCount = 0; while (annotationIter.hasNext()) { final TextAnnotation ann = (TextAnnotation) annotationIter.next(); annCount++; String text = ann.getCoveredText(); if (replaceTabs) text = text.replace('\t', ' '); String posTag = null; if (printSurroundings) { String[] surrounding = new String[] { "", "", text, "", "" }; TokenAnnotation beforeTok = null; int idx = allTokensIdx; while (idx < allTokensLen) { TokenAnnotation tok = allTokens.get(idx++); if (isBefore(tok, ann)) { beforeTok = tok; allTokensIdx = idx - 1; } else { String txt = tok.getCoveredText(); if (isSurrounding(tok, ann)) { surrounding[PREFIX] = txt.substring(0, ann.getBegin() - tok.getBegin()); surrounding[SUFFIX] = txt.substring(ann.getEnd() - tok.getBegin()); posTag = tok.getPos(); } else if (isAtBegin(tok, ann)) { surrounding[PREFIX] = txt.substring(0, ann.getBegin() - tok.getBegin()); posTag = tok.getPos(); } else if (isAtEnd(tok, ann)) { surrounding[SUFFIX] = txt.substring(ann.getEnd() - tok.getBegin()); if (posTag == null) posTag = tok.getPos(); } else if (isAfter(tok, ann)) { surrounding[AFTER] = txt; break; // done! } else if (isEnclosed(tok, ann)) { if (posTag == null) posTag = tok.getPos(); // "inner" token - do nothing (otherwise) } else { this.logger.log(Level.WARNING, "token position %s undetermined relative to annotation %s", new String[] { tok.getOffset().toString(), ann.getOffset().toString() }); break; } if (beforeTok != null) { surrounding[BEFORE] = beforeTok.getCoveredText(); beforeTok = null; } } } if (replaceTabs) for (int i = 0; i < surrounding.length; ++i) surrounding[i] = surrounding[i].replace('\t', ' '); text = StringUtils.join(surrounding, '\t'); } // end printSurroundings if (printPosTag) { if (posTag == null) { int idx = allTokensIdx; while (idx < allTokensLen) { TokenAnnotation tok = allTokens.get(idx++); if (isSurrounding(tok, ann)) { posTag = tok.getPos(); allTokensIdx = idx - 1; break; } else if (isAtBegin(tok, ann)) { posTag = tok.getPos(); allTokensIdx = idx - 1; break; } else if (isBefore(tok, ann)) { // continue searching } else { break; } } } if (posTag == null) posTag = "NULL"; text = String.format("%s\t%s", text, posTag); } // end printPosTag if (replaceNewlines) text = text.replace('\n', ' '); try { write(text); write('\t'); if (annotatorUri == null) write(ann.getAnnotator()); if (annotatorUri == null && annotationNs == null) write('@'); else if (annotatorUri == null) write('\t'); if (annotationNs == null) write(ann.getNamespace()); if (annotationNs == null && annotationId == null) write(':'); else if (annotationNs == null) write('\t'); if (annotationId == null) { write(ann.getIdentifier()); write('\t'); } FSArray props = ann.getProperties(); for (int i = 0; i < props.size(); i++) { Property p = (Property) props.get(i); if (p.getName().contains(" ")) { write('"'); write(p.getName()); write('"'); } else { write(p.getName()); } write('='); write('"'); write(replaceNewlines ? p.getValue().replace('\n', ' ') : p.getValue()); write('"'); write('\t'); } write(decimals.format(ann.getConfidence())); write(LINEBREAK); } catch (final IOException e) { throw new AnalysisEngineProcessException(e); } } try { unsetStream(); } catch (final IOException e) { throw new AnalysisEngineProcessException(e); } logger.log(Level.FINE, "wrote {0} annotations", annCount); }
public void process(CAS cas) throws AnalysisEngineProcessException { JCas textJCas; try { textJCas = cas.getJCas(); setStream(textJCas); } catch (CASException e1) { throw new AnalysisEngineProcessException(e1); } catch (final IOException e2) { throw new AnalysisEngineProcessException(e2); } FSMatchConstraint cons = TextAnnotation.makeConstraint(textJCas, annotatorUri, annotationNs, annotationId); FSIterator<Annotation> annotationIter = textJCas.createFilteredIterator( TextAnnotation.getIterator(textJCas), cons); TokenAnnotation[] tokens = new TokenAnnotation[5]; List<TokenAnnotation> allTokens = new ArrayList<TokenAnnotation>(); if (printSurroundings || printPosTag) { FSIterator<Annotation> it = TokenAnnotation.getIterator(textJCas); while (it.hasNext()) allTokens.add((TokenAnnotation) it.next()); } int allTokensIdx = 0; int allTokensLen = allTokens.size(); tokens[2] = null; int annCount = 0; while (annotationIter.hasNext()) { final TextAnnotation ann = (TextAnnotation) annotationIter.next(); annCount++; String text = ann.getCoveredText(); if (replaceTabs) text = text.replace('\t', ' '); String posTag = null; if (printSurroundings) { String[] surrounding = new String[] { "", "", text, "", "" }; TokenAnnotation beforeTok = null; int idx = allTokensIdx; while (idx < allTokensLen) { TokenAnnotation tok = allTokens.get(idx++); if (isBefore(tok, ann)) { beforeTok = tok; allTokensIdx = idx - 1; } else { String txt = tok.getCoveredText(); if (isSurrounding(tok, ann)) { surrounding[PREFIX] = txt.substring(0, ann.getBegin() - tok.getBegin()); surrounding[SUFFIX] = txt.substring(ann.getEnd() - tok.getBegin()); posTag = tok.getPos(); } else if (isAtBegin(tok, ann)) { surrounding[PREFIX] = txt.substring(0, ann.getBegin() - tok.getBegin()); posTag = tok.getPos(); } else if (isAtEnd(tok, ann)) { surrounding[SUFFIX] = txt.substring(ann.getEnd() - tok.getBegin()); if (posTag == null) posTag = tok.getPos(); } else if (isAfter(tok, ann)) { surrounding[AFTER] = txt; break; // done! } else if (isEnclosed(tok, ann)) { if (posTag == null) posTag = tok.getPos(); // "inner" token - do nothing (otherwise) } else { this.logger.log(Level.WARNING, "token position %s undetermined relative to annotation %s", new String[] { tok.getOffset().toString(), ann.getOffset().toString() }); break; } if (beforeTok != null) { surrounding[BEFORE] = beforeTok.getCoveredText(); beforeTok = null; } } } if (replaceTabs) for (int i = 0; i < surrounding.length; ++i) surrounding[i] = surrounding[i].replace('\t', ' '); text = StringUtils.join(surrounding, '\t'); } // end printSurroundings if (printPosTag) { if (posTag == null) { int idx = allTokensIdx; while (idx < allTokensLen) { TokenAnnotation tok = allTokens.get(idx++); if (isSurrounding(tok, ann)) { posTag = tok.getPos(); allTokensIdx = idx - 1; break; } else if (isAtBegin(tok, ann)) { posTag = tok.getPos(); allTokensIdx = idx - 1; break; } else if (isBefore(tok, ann)) { // continue searching } else { break; } } } if (posTag == null) posTag = "NULL"; text = String.format("%s\t%s", text, posTag); } // end printPosTag if (replaceNewlines) text = text.replace('\n', ' '); try { write(text); write('\t'); write(ann.getOffset().toString()); write('\t'); if (annotatorUri == null) write(ann.getAnnotator()); if (annotatorUri == null && annotationNs == null) write('@'); else if (annotatorUri == null) write('\t'); if (annotationNs == null) write(ann.getNamespace()); if (annotationNs == null && annotationId == null) write(':'); else if (annotationNs == null) write('\t'); if (annotationId == null) { write(ann.getIdentifier()); write('\t'); } FSArray props = ann.getProperties(); if (props != null) { for (int i = 0; i < props.size(); i++) { Property p = (Property) props.get(i); if (p.getName().contains(" ")) { write('"'); write(p.getName()); write('"'); } else { write(p.getName()); } write('='); write('"'); write(replaceNewlines ? p.getValue().replace('\n', ' ') : p.getValue()); write('"'); write('\t'); } } write(decimals.format(ann.getConfidence())); write(LINEBREAK); } catch (final IOException e) { throw new AnalysisEngineProcessException(e); } } try { unsetStream(); } catch (final IOException e) { throw new AnalysisEngineProcessException(e); } logger.log(Level.FINE, "wrote {0} annotations", annCount); }
diff --git a/beam-pixel-extraction/src/main/java/org/esa/beam/pixex/visat/PixelExtractionDialog.java b/beam-pixel-extraction/src/main/java/org/esa/beam/pixex/visat/PixelExtractionDialog.java index dd8f53996..9400e1304 100644 --- a/beam-pixel-extraction/src/main/java/org/esa/beam/pixex/visat/PixelExtractionDialog.java +++ b/beam-pixel-extraction/src/main/java/org/esa/beam/pixex/visat/PixelExtractionDialog.java @@ -1,213 +1,215 @@ /* * Copyright (C) 2010 Brockmann Consult GmbH ([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 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.beam.pixex.visat; import com.bc.ceres.binding.PropertyContainer; import com.bc.ceres.core.ProgressMonitor; import com.bc.ceres.swing.progress.ProgressMonitorSwingWorker; import org.esa.beam.framework.dataio.ProductIO; import org.esa.beam.framework.datamodel.Product; import org.esa.beam.framework.gpf.GPF; import org.esa.beam.framework.gpf.OperatorSpiRegistry; import org.esa.beam.framework.gpf.annotations.ParameterDescriptorFactory; import org.esa.beam.framework.gpf.ui.DefaultAppContext; import org.esa.beam.framework.ui.AppContext; import org.esa.beam.framework.ui.ModalDialog; import org.esa.beam.pixex.PixExOp; import javax.swing.AbstractButton; import javax.swing.JDialog; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTabbedPane; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.border.EmptyBorder; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import java.awt.Component; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ExecutionException; class PixelExtractionDialog extends ModalDialog { private final Map<String, Object> parameterMap; private final AppContext appContext; private final PixelExtractionIOForm ioForm; private final PixelExtractionParametersForm parametersForm; PixelExtractionDialog(AppContext appContext, String title) { super(appContext.getApplicationWindow(), title, ID_OK | ID_CLOSE | ID_HELP, "pixelExtraction"); this.appContext = appContext; AbstractButton button = getButton(ID_OK); button.setText("Extract"); button.setMnemonic('E'); parameterMap = new HashMap<String, Object>(); final PropertyContainer propertyContainer = createParameterMap(parameterMap); ioForm = new PixelExtractionIOForm(appContext, propertyContainer); ioForm.setInputChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { final Product[] sourceProducts = ioForm.getSourceProducts(); if (sourceProducts.length > 0) { parametersForm.setActiveProduct(sourceProducts[0]); + return; } else { if(parameterMap.containsKey("inputPaths")) { final File[] inputPaths = (File[]) parameterMap.get("inputPaths"); - try { - Product firstProduct = null; - File file = PixExOp.getParsedInputPaths(inputPaths)[0]; - if (file.isDirectory()) { - for (File subFile : file.listFiles()) { - firstProduct = ProductIO.readProduct(subFile); - if(firstProduct != null) { - break; + if(inputPaths.length > 0) { + try { + Product firstProduct = null; + File file = PixExOp.getParsedInputPaths(inputPaths)[0]; + if (file.isDirectory()) { + for (File subFile : file.listFiles()) { + firstProduct = ProductIO.readProduct(subFile); + if(firstProduct != null) { + break; + } } + } else { + firstProduct = ProductIO.readProduct(file); } - } else { - firstProduct = ProductIO.readProduct(file); + parametersForm.setActiveProduct(firstProduct); + return; + } catch (IOException ignore) { } - parametersForm.setActiveProduct(firstProduct); - } catch (IOException ignore) { - parametersForm.setActiveProduct(null); } - } else { - parametersForm.setActiveProduct(null); } } + parametersForm.setActiveProduct(null); } }); parametersForm = new PixelExtractionParametersForm(appContext, propertyContainer); final JPanel ioPanel = ioForm.getPanel(); ioPanel.setBorder(new EmptyBorder(4, 4, 4, 4)); final JPanel parametersPanel = parametersForm.getPanel(); parametersPanel.setBorder(new EmptyBorder(4, 4, 4, 4)); JTabbedPane tabbedPanel = new JTabbedPane(); tabbedPanel.addTab("Input/Output", ioPanel); tabbedPanel.addTab("Parameters", parametersPanel); setContent(tabbedPanel); } @Override protected void onOK() { parameterMap.put("coordinates", parametersForm.getCoordinates()); parameterMap.put("expression", parametersForm.getExpression()); parameterMap.put("timeDifference", parametersForm.getAllowedTimeDifference()); parameterMap.put("exportExpressionResult", parametersForm.isExportExpressionResultSelected()); ProgressMonitorSwingWorker worker = new MyProgressMonitorSwingWorker(getParent(), "Creating output file(s)..."); worker.executeWithBlocking(); } @Override public void close() { super.close(); ioForm.clear(); } @Override public int show() { ioForm.setSelectedProduct(appContext.getSelectedProduct()); return super.show(); } private static PropertyContainer createParameterMap(Map<String, Object> map) { ParameterDescriptorFactory parameterDescriptorFactory = new ParameterDescriptorFactory(); final PropertyContainer container = PropertyContainer.createMapBacked(map, PixExOp.class, parameterDescriptorFactory); container.setDefaultValues(); return container; } private class MyProgressMonitorSwingWorker extends ProgressMonitorSwingWorker<Void, Void> { protected MyProgressMonitorSwingWorker(Component parentComponent, String title) { super(parentComponent, title); } @Override protected Void doInBackground(ProgressMonitor pm) throws Exception { pm.beginTask("Computing pixel values...", -1); AbstractButton runButton = getButton(ID_OK); runButton.setEnabled(false); try { GPF.createProduct("PixEx", parameterMap, ioForm.getSourceProducts()); pm.worked(1); } finally { pm.done(); } return null; } @Override protected void done() { try { get(); Object outputDir = parameterMap.get("outputDir"); String message; if (outputDir != null) { message = String.format( "The pixel extraction tool has run successfully and written the result file(s) to %s.", outputDir.toString()); } else { message = "The pixel extraction tool has run successfully and written the result file to to std.out."; } JOptionPane.showMessageDialog(getJDialog(), message); } catch (InterruptedException ignore) { } catch (ExecutionException e) { appContext.handleError(e.getMessage(), e); } finally { AbstractButton runButton = getButton(ID_OK); runButton.setEnabled(true); } } } public static void main(String[] args) throws Exception { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); final DefaultAppContext context = new DefaultAppContext("dev0"); final OperatorSpiRegistry registry = GPF.getDefaultInstance().getOperatorSpiRegistry(); registry.addOperatorSpi(new PixExOp.Spi()); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { final PixelExtractionDialog dialog = new PixelExtractionDialog(context, "Pixel Extraction") { @Override protected void onClose() { System.exit(0); } }; dialog.getJDialog().setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); dialog.show(); } }); } }
false
true
PixelExtractionDialog(AppContext appContext, String title) { super(appContext.getApplicationWindow(), title, ID_OK | ID_CLOSE | ID_HELP, "pixelExtraction"); this.appContext = appContext; AbstractButton button = getButton(ID_OK); button.setText("Extract"); button.setMnemonic('E'); parameterMap = new HashMap<String, Object>(); final PropertyContainer propertyContainer = createParameterMap(parameterMap); ioForm = new PixelExtractionIOForm(appContext, propertyContainer); ioForm.setInputChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { final Product[] sourceProducts = ioForm.getSourceProducts(); if (sourceProducts.length > 0) { parametersForm.setActiveProduct(sourceProducts[0]); } else { if(parameterMap.containsKey("inputPaths")) { final File[] inputPaths = (File[]) parameterMap.get("inputPaths"); try { Product firstProduct = null; File file = PixExOp.getParsedInputPaths(inputPaths)[0]; if (file.isDirectory()) { for (File subFile : file.listFiles()) { firstProduct = ProductIO.readProduct(subFile); if(firstProduct != null) { break; } } } else { firstProduct = ProductIO.readProduct(file); } parametersForm.setActiveProduct(firstProduct); } catch (IOException ignore) { parametersForm.setActiveProduct(null); } } else { parametersForm.setActiveProduct(null); } } } }); parametersForm = new PixelExtractionParametersForm(appContext, propertyContainer); final JPanel ioPanel = ioForm.getPanel(); ioPanel.setBorder(new EmptyBorder(4, 4, 4, 4)); final JPanel parametersPanel = parametersForm.getPanel(); parametersPanel.setBorder(new EmptyBorder(4, 4, 4, 4)); JTabbedPane tabbedPanel = new JTabbedPane(); tabbedPanel.addTab("Input/Output", ioPanel); tabbedPanel.addTab("Parameters", parametersPanel); setContent(tabbedPanel); }
PixelExtractionDialog(AppContext appContext, String title) { super(appContext.getApplicationWindow(), title, ID_OK | ID_CLOSE | ID_HELP, "pixelExtraction"); this.appContext = appContext; AbstractButton button = getButton(ID_OK); button.setText("Extract"); button.setMnemonic('E'); parameterMap = new HashMap<String, Object>(); final PropertyContainer propertyContainer = createParameterMap(parameterMap); ioForm = new PixelExtractionIOForm(appContext, propertyContainer); ioForm.setInputChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { final Product[] sourceProducts = ioForm.getSourceProducts(); if (sourceProducts.length > 0) { parametersForm.setActiveProduct(sourceProducts[0]); return; } else { if(parameterMap.containsKey("inputPaths")) { final File[] inputPaths = (File[]) parameterMap.get("inputPaths"); if(inputPaths.length > 0) { try { Product firstProduct = null; File file = PixExOp.getParsedInputPaths(inputPaths)[0]; if (file.isDirectory()) { for (File subFile : file.listFiles()) { firstProduct = ProductIO.readProduct(subFile); if(firstProduct != null) { break; } } } else { firstProduct = ProductIO.readProduct(file); } parametersForm.setActiveProduct(firstProduct); return; } catch (IOException ignore) { } } } } parametersForm.setActiveProduct(null); } }); parametersForm = new PixelExtractionParametersForm(appContext, propertyContainer); final JPanel ioPanel = ioForm.getPanel(); ioPanel.setBorder(new EmptyBorder(4, 4, 4, 4)); final JPanel parametersPanel = parametersForm.getPanel(); parametersPanel.setBorder(new EmptyBorder(4, 4, 4, 4)); JTabbedPane tabbedPanel = new JTabbedPane(); tabbedPanel.addTab("Input/Output", ioPanel); tabbedPanel.addTab("Parameters", parametersPanel); setContent(tabbedPanel); }
diff --git a/src/main/java/net/loadingchunks/plugins/AuthenticItem/AuthenticItem/AuthenticItemCommandExecutor.java b/src/main/java/net/loadingchunks/plugins/AuthenticItem/AuthenticItem/AuthenticItemCommandExecutor.java index cfc3a59..1b3e08f 100644 --- a/src/main/java/net/loadingchunks/plugins/AuthenticItem/AuthenticItem/AuthenticItemCommandExecutor.java +++ b/src/main/java/net/loadingchunks/plugins/AuthenticItem/AuthenticItem/AuthenticItemCommandExecutor.java @@ -1,124 +1,124 @@ package net.loadingchunks.plugins.AuthenticItem.AuthenticItem; /* This file is part of AuthenticItem Foobar 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. Foobar 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 Foobar. If not, see <http://www.gnu.org/licenses/>. */ import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.craftbukkit.inventory.CraftItemStack; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; public class AuthenticItemCommandExecutor implements CommandExecutor { private AuthenticItem plugin; public AuthenticItemCommandExecutor(AuthenticItem plugin) { this.plugin = plugin; } @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if (command.getName().equalsIgnoreCase("authentic")) { if(!sender.hasPermission("aitem.authentic")) { sender.sendMessage("You do not have permission to use this command."); return true; } ArrayList<String> authentictypes = new ArrayList<String>(); for(AuthenticTypes t : AuthenticTypes.values()) { authentictypes.add(t.toString() + ChatColor.RESET); } if(args.length > 0) { if(!(sender instanceof Player)) { sender.sendMessage("You must be in-game to use this command."); return false; } try { AuthenticTypes.valueOf(args[0].toUpperCase()); // Worst check ever. } catch (Exception e) { sender.sendMessage("Invalid type given."); sender.sendMessage("Valid types: " + Arrays.toString(authentictypes.toArray())); return false; } Player p = (Player)sender; CraftItemStack hand = (CraftItemStack)p.getInventory().getItemInHand(); if(hand == null || hand.getTypeId() == 0) { sender.sendMessage("You are't holding anything."); return true; } AItem item = new AItem(hand); item.setPlugin(plugin); if(item.itemstack == null) this.plugin.getLogger().warning("Uh oh! The item stack is empty!"); if(item.getDisplayName() == null) { sender.sendMessage("You must rename this item first."); return true; } item.setAuthentic(args[0].toUpperCase()); String disp = item.getDisplayName(); for(AuthenticTypes rem : AuthenticTypes.values()) { disp = disp.replace(rem.toString() + " ", ""); } disp = ChatColor.stripColor(disp); item.setDisplayName(AuthenticTypes.valueOf(args[0].toUpperCase()) + " " + disp + ChatColor.RESET); CraftItemStack cstack = new CraftItemStack(item.getStack()); - cstack.setDurability((short)2000); + cstack.setDurability((short)-5000); p.getInventory().setItemInHand(cstack); sender.sendMessage("Item: " + item.getDisplayName()); return true; } else { sender.sendMessage("Please specify a trait type for this item."); sender.sendMessage("Valid types: " + Arrays.toString(authentictypes.toArray())); return false; } } return false; } }
true
true
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if (command.getName().equalsIgnoreCase("authentic")) { if(!sender.hasPermission("aitem.authentic")) { sender.sendMessage("You do not have permission to use this command."); return true; } ArrayList<String> authentictypes = new ArrayList<String>(); for(AuthenticTypes t : AuthenticTypes.values()) { authentictypes.add(t.toString() + ChatColor.RESET); } if(args.length > 0) { if(!(sender instanceof Player)) { sender.sendMessage("You must be in-game to use this command."); return false; } try { AuthenticTypes.valueOf(args[0].toUpperCase()); // Worst check ever. } catch (Exception e) { sender.sendMessage("Invalid type given."); sender.sendMessage("Valid types: " + Arrays.toString(authentictypes.toArray())); return false; } Player p = (Player)sender; CraftItemStack hand = (CraftItemStack)p.getInventory().getItemInHand(); if(hand == null || hand.getTypeId() == 0) { sender.sendMessage("You are't holding anything."); return true; } AItem item = new AItem(hand); item.setPlugin(plugin); if(item.itemstack == null) this.plugin.getLogger().warning("Uh oh! The item stack is empty!"); if(item.getDisplayName() == null) { sender.sendMessage("You must rename this item first."); return true; } item.setAuthentic(args[0].toUpperCase()); String disp = item.getDisplayName(); for(AuthenticTypes rem : AuthenticTypes.values()) { disp = disp.replace(rem.toString() + " ", ""); } disp = ChatColor.stripColor(disp); item.setDisplayName(AuthenticTypes.valueOf(args[0].toUpperCase()) + " " + disp + ChatColor.RESET); CraftItemStack cstack = new CraftItemStack(item.getStack()); cstack.setDurability((short)2000); p.getInventory().setItemInHand(cstack); sender.sendMessage("Item: " + item.getDisplayName()); return true; } else { sender.sendMessage("Please specify a trait type for this item."); sender.sendMessage("Valid types: " + Arrays.toString(authentictypes.toArray())); return false; } } return false; }
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if (command.getName().equalsIgnoreCase("authentic")) { if(!sender.hasPermission("aitem.authentic")) { sender.sendMessage("You do not have permission to use this command."); return true; } ArrayList<String> authentictypes = new ArrayList<String>(); for(AuthenticTypes t : AuthenticTypes.values()) { authentictypes.add(t.toString() + ChatColor.RESET); } if(args.length > 0) { if(!(sender instanceof Player)) { sender.sendMessage("You must be in-game to use this command."); return false; } try { AuthenticTypes.valueOf(args[0].toUpperCase()); // Worst check ever. } catch (Exception e) { sender.sendMessage("Invalid type given."); sender.sendMessage("Valid types: " + Arrays.toString(authentictypes.toArray())); return false; } Player p = (Player)sender; CraftItemStack hand = (CraftItemStack)p.getInventory().getItemInHand(); if(hand == null || hand.getTypeId() == 0) { sender.sendMessage("You are't holding anything."); return true; } AItem item = new AItem(hand); item.setPlugin(plugin); if(item.itemstack == null) this.plugin.getLogger().warning("Uh oh! The item stack is empty!"); if(item.getDisplayName() == null) { sender.sendMessage("You must rename this item first."); return true; } item.setAuthentic(args[0].toUpperCase()); String disp = item.getDisplayName(); for(AuthenticTypes rem : AuthenticTypes.values()) { disp = disp.replace(rem.toString() + " ", ""); } disp = ChatColor.stripColor(disp); item.setDisplayName(AuthenticTypes.valueOf(args[0].toUpperCase()) + " " + disp + ChatColor.RESET); CraftItemStack cstack = new CraftItemStack(item.getStack()); cstack.setDurability((short)-5000); p.getInventory().setItemInHand(cstack); sender.sendMessage("Item: " + item.getDisplayName()); return true; } else { sender.sendMessage("Please specify a trait type for this item."); sender.sendMessage("Valid types: " + Arrays.toString(authentictypes.toArray())); return false; } } return false; }
diff --git a/app/controllers/PageController.java b/app/controllers/PageController.java index b83fddc..0aae29c 100644 --- a/app/controllers/PageController.java +++ b/app/controllers/PageController.java @@ -1,83 +1,83 @@ package controllers; import java.util.Arrays; import java.util.Locale; import java.util.Set; import java.util.TreeSet; import models.Page; import models.PageRef; import models.Tag; import play.data.validation.Validation; import play.mvc.Controller; import play.mvc.With; /** * * @author waxzce * @author keruspe */ @With(Secure.class) public class PageController extends Controller { public static void newPage(String otherUrlId) { render(otherUrlId); } public static void doNewPage() { String urlId = params.get("linkto.otherUrlId"); Page page = null; PageRef pageRef = null; - if (urlId != null && urlId.equals("")) + if (urlId != null && !urlId.equals("")) page = Page.getPageByUrlId(urlId); if (page != null) pageRef = page.pageReference; else pageRef = PageController.doNewPageRef(params.get("pageReference.tags")); urlId = params.get("page.urlId"); page = new Page(); page.pageReference = pageRef; page.urlId = urlId; page.title = params.get("page.title"); page.content = params.get("page.content"); page.language = params.get("page.language", Locale.class); page.published = (params.get("page.published") == null) ? Boolean.FALSE : Boolean.TRUE; validation.valid(page); if (Validation.hasErrors()) { params.flash(); // add http parameters to the flash scope Validation.keep(); // keep the errors for the next request PageController.newPage(""); } page.pageReference.save(); page.save(); if (page.published) PageViewer.page(urlId); else PageViewer.page("index"); } private static PageRef doNewPageRef(String tagsString) { PageRef pageRef = new PageRef(); Set<Tag> tags = new TreeSet<Tag>(); if (!tagsString.isEmpty()) { for (String tag : Arrays.asList(tagsString.split(","))) { tags.add(Tag.findOrCreateByName(tag)); } } pageRef.tags = tags; validation.valid(pageRef); if (Validation.hasErrors()) { params.flash(); // add http parameters to the flash scope Validation.keep(); // keep the errors for the next request PageController.newPage(""); } return pageRef; } }
true
true
public static void doNewPage() { String urlId = params.get("linkto.otherUrlId"); Page page = null; PageRef pageRef = null; if (urlId != null && urlId.equals("")) page = Page.getPageByUrlId(urlId); if (page != null) pageRef = page.pageReference; else pageRef = PageController.doNewPageRef(params.get("pageReference.tags")); urlId = params.get("page.urlId"); page = new Page(); page.pageReference = pageRef; page.urlId = urlId; page.title = params.get("page.title"); page.content = params.get("page.content"); page.language = params.get("page.language", Locale.class); page.published = (params.get("page.published") == null) ? Boolean.FALSE : Boolean.TRUE; validation.valid(page); if (Validation.hasErrors()) { params.flash(); // add http parameters to the flash scope Validation.keep(); // keep the errors for the next request PageController.newPage(""); } page.pageReference.save(); page.save(); if (page.published) PageViewer.page(urlId); else PageViewer.page("index"); }
public static void doNewPage() { String urlId = params.get("linkto.otherUrlId"); Page page = null; PageRef pageRef = null; if (urlId != null && !urlId.equals("")) page = Page.getPageByUrlId(urlId); if (page != null) pageRef = page.pageReference; else pageRef = PageController.doNewPageRef(params.get("pageReference.tags")); urlId = params.get("page.urlId"); page = new Page(); page.pageReference = pageRef; page.urlId = urlId; page.title = params.get("page.title"); page.content = params.get("page.content"); page.language = params.get("page.language", Locale.class); page.published = (params.get("page.published") == null) ? Boolean.FALSE : Boolean.TRUE; validation.valid(page); if (Validation.hasErrors()) { params.flash(); // add http parameters to the flash scope Validation.keep(); // keep the errors for the next request PageController.newPage(""); } page.pageReference.save(); page.save(); if (page.published) PageViewer.page(urlId); else PageViewer.page("index"); }
diff --git a/src/test/java/org/elasticsearch/common/lucene/search/XBooleanFilterTests.java b/src/test/java/org/elasticsearch/common/lucene/search/XBooleanFilterTests.java index fabdb0f10f6..d41d4dc585b 100644 --- a/src/test/java/org/elasticsearch/common/lucene/search/XBooleanFilterTests.java +++ b/src/test/java/org/elasticsearch/common/lucene/search/XBooleanFilterTests.java @@ -1,516 +1,516 @@ package org.elasticsearch.common.lucene.search; import org.apache.lucene.analysis.core.KeywordAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.document.StringField; import org.apache.lucene.index.*; import org.apache.lucene.queries.FilterClause; import org.apache.lucene.queries.TermFilter; import org.apache.lucene.search.*; import org.apache.lucene.store.Directory; import org.apache.lucene.util.FixedBitSet; import org.elasticsearch.common.lucene.Lucene; import org.elasticsearch.test.ElasticsearchLuceneTestCase; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static org.apache.lucene.search.BooleanClause.Occur.*; import static org.hamcrest.core.IsEqual.equalTo; /** */ public class XBooleanFilterTests extends ElasticsearchLuceneTestCase { private Directory directory; private AtomicReader reader; private static final char[] distinctValues = new char[] {'a', 'b', 'c', 'd', 'v','z','y'}; @Before public void setup() throws Exception { super.setUp(); char[][] documentMatrix = new char[][] { {'a', 'b', 'c', 'd', 'v'}, {'a', 'b', 'c', 'd', 'z'}, {'a', 'a', 'a', 'a', 'x'} }; List<Document> documents = new ArrayList<Document>(documentMatrix.length); for (char[] fields : documentMatrix) { Document document = new Document(); for (int i = 0; i < fields.length; i++) { document.add(new StringField(Integer.toString(i), String.valueOf(fields[i]), Field.Store.NO)); } documents.add(document); } directory = newDirectory(); IndexWriter w = new IndexWriter(directory, new IndexWriterConfig(Lucene.VERSION, new KeywordAnalyzer())); w.addDocuments(documents); w.close(); reader = SlowCompositeReaderWrapper.wrap(DirectoryReader.open(directory)); } @After public void tearDown() throws Exception { reader.close(); directory.close(); super.tearDown(); } @Test public void testWithTwoClausesOfEachOccur_allFixedBitsetFilters() throws Exception { List<XBooleanFilter> booleanFilters = new ArrayList<XBooleanFilter>(); booleanFilters.add(createBooleanFilter( newFilterClause(0, 'a', MUST, false), newFilterClause(1, 'b', MUST, false), newFilterClause(2, 'c', SHOULD, false), newFilterClause(3, 'd', SHOULD, false), newFilterClause(4, 'e', MUST_NOT, false), newFilterClause(5, 'f', MUST_NOT, false) )); booleanFilters.add(createBooleanFilter( newFilterClause(4, 'e', MUST_NOT, false), newFilterClause(5, 'f', MUST_NOT, false), newFilterClause(0, 'a', MUST, false), newFilterClause(1, 'b', MUST, false), newFilterClause(2, 'c', SHOULD, false), newFilterClause(3, 'd', SHOULD, false) )); booleanFilters.add(createBooleanFilter( newFilterClause(2, 'c', SHOULD, false), newFilterClause(3, 'd', SHOULD, false), newFilterClause(4, 'e', MUST_NOT, false), newFilterClause(5, 'f', MUST_NOT, false), newFilterClause(0, 'a', MUST, false), newFilterClause(1, 'b', MUST, false) )); for (XBooleanFilter booleanFilter : booleanFilters) { FixedBitSet result = new FixedBitSet(reader.maxDoc()); result.or(booleanFilter.getDocIdSet(reader.getContext(), reader.getLiveDocs()).iterator()); assertThat(result.cardinality(), equalTo(2)); assertThat(result.get(0), equalTo(true)); assertThat(result.get(1), equalTo(true)); assertThat(result.get(2), equalTo(false)); } } @Test public void testWithTwoClausesOfEachOccur_allBitsBasedFilters() throws Exception { List<XBooleanFilter> booleanFilters = new ArrayList<XBooleanFilter>(); booleanFilters.add(createBooleanFilter( newFilterClause(0, 'a', MUST, true), newFilterClause(1, 'b', MUST, true), newFilterClause(2, 'c', SHOULD, true), newFilterClause(3, 'd', SHOULD, true), newFilterClause(4, 'e', MUST_NOT, true), newFilterClause(5, 'f', MUST_NOT, true) )); booleanFilters.add(createBooleanFilter( newFilterClause(4, 'e', MUST_NOT, true), newFilterClause(5, 'f', MUST_NOT, true), newFilterClause(0, 'a', MUST, true), newFilterClause(1, 'b', MUST, true), newFilterClause(2, 'c', SHOULD, true), newFilterClause(3, 'd', SHOULD, true) )); booleanFilters.add(createBooleanFilter( newFilterClause(2, 'c', SHOULD, true), newFilterClause(3, 'd', SHOULD, true), newFilterClause(4, 'e', MUST_NOT, true), newFilterClause(5, 'f', MUST_NOT, true), newFilterClause(0, 'a', MUST, true), newFilterClause(1, 'b', MUST, true) )); for (XBooleanFilter booleanFilter : booleanFilters) { FixedBitSet result = new FixedBitSet(reader.maxDoc()); result.or(booleanFilter.getDocIdSet(reader.getContext(), reader.getLiveDocs()).iterator()); assertThat(result.cardinality(), equalTo(2)); assertThat(result.get(0), equalTo(true)); assertThat(result.get(1), equalTo(true)); assertThat(result.get(2), equalTo(false)); } } @Test public void testWithTwoClausesOfEachOccur_allFilterTypes() throws Exception { List<XBooleanFilter> booleanFilters = new ArrayList<XBooleanFilter>(); booleanFilters.add(createBooleanFilter( newFilterClause(0, 'a', MUST, true), newFilterClause(1, 'b', MUST, false), newFilterClause(2, 'c', SHOULD, true), newFilterClause(3, 'd', SHOULD, false), newFilterClause(4, 'e', MUST_NOT, true), newFilterClause(5, 'f', MUST_NOT, false) )); booleanFilters.add(createBooleanFilter( newFilterClause(4, 'e', MUST_NOT, true), newFilterClause(5, 'f', MUST_NOT, false), newFilterClause(0, 'a', MUST, true), newFilterClause(1, 'b', MUST, false), newFilterClause(2, 'c', SHOULD, true), newFilterClause(3, 'd', SHOULD, false) )); booleanFilters.add(createBooleanFilter( newFilterClause(2, 'c', SHOULD, true), newFilterClause(3, 'd', SHOULD, false), newFilterClause(4, 'e', MUST_NOT, true), newFilterClause(5, 'f', MUST_NOT, false), newFilterClause(0, 'a', MUST, true), newFilterClause(1, 'b', MUST, false) )); for (XBooleanFilter booleanFilter : booleanFilters) { FixedBitSet result = new FixedBitSet(reader.maxDoc()); result.or(booleanFilter.getDocIdSet(reader.getContext(), reader.getLiveDocs()).iterator()); assertThat(result.cardinality(), equalTo(2)); assertThat(result.get(0), equalTo(true)); assertThat(result.get(1), equalTo(true)); assertThat(result.get(2), equalTo(false)); } booleanFilters.clear(); booleanFilters.add(createBooleanFilter( newFilterClause(0, 'a', MUST, false), newFilterClause(1, 'b', MUST, true), newFilterClause(2, 'c', SHOULD, false), newFilterClause(3, 'd', SHOULD, true), newFilterClause(4, 'e', MUST_NOT, false), newFilterClause(5, 'f', MUST_NOT, true) )); booleanFilters.add(createBooleanFilter( newFilterClause(4, 'e', MUST_NOT, false), newFilterClause(5, 'f', MUST_NOT, true), newFilterClause(0, 'a', MUST, false), newFilterClause(1, 'b', MUST, true), newFilterClause(2, 'c', SHOULD, false), newFilterClause(3, 'd', SHOULD, true) )); booleanFilters.add(createBooleanFilter( newFilterClause(2, 'c', SHOULD, false), newFilterClause(3, 'd', SHOULD, true), newFilterClause(4, 'e', MUST_NOT, false), newFilterClause(5, 'f', MUST_NOT, true), newFilterClause(0, 'a', MUST, false), newFilterClause(1, 'b', MUST, true) )); for (XBooleanFilter booleanFilter : booleanFilters) { FixedBitSet result = new FixedBitSet(reader.maxDoc()); result.or(booleanFilter.getDocIdSet(reader.getContext(), reader.getLiveDocs()).iterator()); assertThat(result.cardinality(), equalTo(2)); assertThat(result.get(0), equalTo(true)); assertThat(result.get(1), equalTo(true)); assertThat(result.get(2), equalTo(false)); } } @Test public void testWithTwoClausesOfEachOccur_singleClauseOptimisation() throws Exception { List<XBooleanFilter> booleanFilters = new ArrayList<XBooleanFilter>(); booleanFilters.add(createBooleanFilter( newFilterClause(1, 'b', MUST, true) )); for (XBooleanFilter booleanFilter : booleanFilters) { FixedBitSet result = new FixedBitSet(reader.maxDoc()); result.or(booleanFilter.getDocIdSet(reader.getContext(), reader.getLiveDocs()).iterator()); assertThat(result.cardinality(), equalTo(2)); assertThat(result.get(0), equalTo(true)); assertThat(result.get(1), equalTo(true)); assertThat(result.get(2), equalTo(false)); } booleanFilters.clear(); booleanFilters.add(createBooleanFilter( newFilterClause(1, 'c', MUST_NOT, true) )); for (XBooleanFilter booleanFilter : booleanFilters) { FixedBitSet result = new FixedBitSet(reader.maxDoc()); result.or(booleanFilter.getDocIdSet(reader.getContext(), reader.getLiveDocs()).iterator()); assertThat(result.cardinality(), equalTo(3)); assertThat(result.get(0), equalTo(true)); assertThat(result.get(1), equalTo(true)); assertThat(result.get(2), equalTo(true)); } booleanFilters.clear(); booleanFilters.add(createBooleanFilter( newFilterClause(2, 'c', SHOULD, true) )); for (XBooleanFilter booleanFilter : booleanFilters) { FixedBitSet result = new FixedBitSet(reader.maxDoc()); result.or(booleanFilter.getDocIdSet(reader.getContext(), reader.getLiveDocs()).iterator()); assertThat(result.cardinality(), equalTo(2)); assertThat(result.get(0), equalTo(true)); assertThat(result.get(1), equalTo(true)); assertThat(result.get(2), equalTo(false)); } } @Test public void testOnlyShouldClauses() throws Exception { List<XBooleanFilter> booleanFilters = new ArrayList<XBooleanFilter>(); // 2 slow filters // This case caused: https://github.com/elasticsearch/elasticsearch/issues/2826 booleanFilters.add(createBooleanFilter( newFilterClause(1, 'a', SHOULD, true), newFilterClause(1, 'b', SHOULD, true) )); // 2 fast filters booleanFilters.add(createBooleanFilter( newFilterClause(1, 'a', SHOULD, false), newFilterClause(1, 'b', SHOULD, false) )); // 1 fast filters, 1 slow filter booleanFilters.add(createBooleanFilter( newFilterClause(1, 'a', SHOULD, true), newFilterClause(1, 'b', SHOULD, false) )); for (XBooleanFilter booleanFilter : booleanFilters) { FixedBitSet result = new FixedBitSet(reader.maxDoc()); result.or(booleanFilter.getDocIdSet(reader.getContext(), reader.getLiveDocs()).iterator()); assertThat(result.cardinality(), equalTo(3)); assertThat(result.get(0), equalTo(true)); assertThat(result.get(1), equalTo(true)); assertThat(result.get(2), equalTo(true)); } } @Test public void testOnlyMustClauses() throws Exception { List<XBooleanFilter> booleanFilters = new ArrayList<XBooleanFilter>(); // Slow filters booleanFilters.add(createBooleanFilter( newFilterClause(3, 'd', MUST, true), newFilterClause(3, 'd', MUST, true) )); // 2 fast filters booleanFilters.add(createBooleanFilter( newFilterClause(3, 'd', MUST, false), newFilterClause(3, 'd', MUST, false) )); // 1 fast filters, 1 slow filter booleanFilters.add(createBooleanFilter( newFilterClause(3, 'd', MUST, true), newFilterClause(3, 'd', MUST, false) )); for (XBooleanFilter booleanFilter : booleanFilters) { FixedBitSet result = new FixedBitSet(reader.maxDoc()); result.or(booleanFilter.getDocIdSet(reader.getContext(), reader.getLiveDocs()).iterator()); assertThat(result.cardinality(), equalTo(2)); assertThat(result.get(0), equalTo(true)); assertThat(result.get(1), equalTo(true)); assertThat(result.get(2), equalTo(false)); } } @Test public void testOnlyMustNotClauses() throws Exception { List<XBooleanFilter> booleanFilters = new ArrayList<XBooleanFilter>(); // Slow filters booleanFilters.add(createBooleanFilter( newFilterClause(1, 'a', MUST_NOT, true), newFilterClause(1, 'a', MUST_NOT, true) )); // 2 fast filters booleanFilters.add(createBooleanFilter( newFilterClause(1, 'a', MUST_NOT, false), newFilterClause(1, 'a', MUST_NOT, false) )); // 1 fast filters, 1 slow filter booleanFilters.add(createBooleanFilter( newFilterClause(1, 'a', MUST_NOT, true), newFilterClause(1, 'a', MUST_NOT, false) )); for (XBooleanFilter booleanFilter : booleanFilters) { FixedBitSet result = new FixedBitSet(reader.maxDoc()); result.or(booleanFilter.getDocIdSet(reader.getContext(), reader.getLiveDocs()).iterator()); assertThat(result.cardinality(), equalTo(2)); assertThat(result.get(0), equalTo(true)); assertThat(result.get(1), equalTo(true)); assertThat(result.get(2), equalTo(false)); } } @Test public void testNonMatchingSlowShouldWithMatchingMust() throws Exception { XBooleanFilter booleanFilter = createBooleanFilter( newFilterClause(0, 'a', MUST, false), newFilterClause(0, 'b', SHOULD, true) ); DocIdSet docIdSet = booleanFilter.getDocIdSet(reader.getContext(), reader.getLiveDocs()); assertThat(docIdSet, equalTo(null)); } @Test public void testSlowShouldClause_atLeastOneShouldMustMatch() throws Exception { XBooleanFilter booleanFilter = createBooleanFilter( newFilterClause(0, 'a', MUST, false), newFilterClause(1, 'a', SHOULD, true) ); FixedBitSet result = new FixedBitSet(reader.maxDoc()); result.or(booleanFilter.getDocIdSet(reader.getContext(), reader.getLiveDocs()).iterator()); assertThat(result.cardinality(), equalTo(1)); assertThat(result.get(0), equalTo(false)); assertThat(result.get(1), equalTo(false)); assertThat(result.get(2), equalTo(true)); booleanFilter = createBooleanFilter( newFilterClause(0, 'a', MUST, false), newFilterClause(1, 'a', SHOULD, true), newFilterClause(4, 'z', SHOULD, true) ); result = new FixedBitSet(reader.maxDoc()); result.or(booleanFilter.getDocIdSet(reader.getContext(), reader.getLiveDocs()).iterator()); assertThat(result.cardinality(), equalTo(2)); assertThat(result.get(0), equalTo(false)); assertThat(result.get(1), equalTo(true)); assertThat(result.get(2), equalTo(true)); } @Test // See issue: https://github.com/elasticsearch/elasticsearch/issues/4130 public void testOneFastMustNotOneFastShouldAndOneSlowShould() throws Exception { XBooleanFilter booleanFilter = createBooleanFilter( newFilterClause(4, 'v', MUST_NOT, false), newFilterClause(4, 'z', SHOULD, false), newFilterClause(4, 'x', SHOULD, true) ); FixedBitSet result = new FixedBitSet(reader.maxDoc()); result.or(booleanFilter.getDocIdSet(reader.getContext(), reader.getLiveDocs()).iterator()); assertThat(result.cardinality(), equalTo(2)); assertThat(result.get(0), equalTo(false)); assertThat(result.get(1), equalTo(true)); assertThat(result.get(2), equalTo(true)); } @Test public void testOneFastShouldClauseAndOneSlowShouldClause() throws Exception { XBooleanFilter booleanFilter = createBooleanFilter( newFilterClause(4, 'z', SHOULD, false), newFilterClause(4, 'x', SHOULD, true) ); FixedBitSet result = new FixedBitSet(reader.maxDoc()); result.or(booleanFilter.getDocIdSet(reader.getContext(), reader.getLiveDocs()).iterator()); assertThat(result.cardinality(), equalTo(2)); assertThat(result.get(0), equalTo(false)); assertThat(result.get(1), equalTo(true)); assertThat(result.get(2), equalTo(true)); } @Test public void testOneMustClauseOneFastShouldClauseAndOneSlowShouldClause() throws Exception { XBooleanFilter booleanFilter = createBooleanFilter( newFilterClause(0, 'a', MUST, false), newFilterClause(4, 'z', SHOULD, false), newFilterClause(4, 'x', SHOULD, true) ); FixedBitSet result = new FixedBitSet(reader.maxDoc()); result.or(booleanFilter.getDocIdSet(reader.getContext(), reader.getLiveDocs()).iterator()); assertThat(result.cardinality(), equalTo(2)); assertThat(result.get(0), equalTo(false)); assertThat(result.get(1), equalTo(true)); assertThat(result.get(2), equalTo(true)); } private static FilterClause newFilterClause(int field, char character, BooleanClause.Occur occur, boolean slowerBitsBackedFilter) { Filter filter; if (slowerBitsBackedFilter) { filter = new PrettyPrintFieldCacheTermsFilter(String.valueOf(field), String.valueOf(character)); } else { Term term = new Term(String.valueOf(field), String.valueOf(character)); filter = new TermFilter(term); } return new FilterClause(filter, occur); } private static XBooleanFilter createBooleanFilter(FilterClause... clauses) { XBooleanFilter booleanFilter = new XBooleanFilter(); for (FilterClause clause : clauses) { booleanFilter.add(clause); } return booleanFilter; } @Test public void testRandom() throws IOException { int iterations = atLeast(400); // don't worry that is fast! for (int iter = 0; iter < iterations; iter++) { int numClauses = 1 + random().nextInt(10); FilterClause[] clauses = new FilterClause[numClauses]; BooleanQuery topLevel = new BooleanQuery(); BooleanQuery orQuery = new BooleanQuery(); boolean hasMust = false; boolean hasShould = false; boolean hasMustNot = false; for(int i = 0; i < numClauses; i++) { int field = random().nextInt(5); char value = distinctValues[random().nextInt(distinctValues.length)]; switch(random().nextInt(10)) { case 9: case 8: case 7: case 6: case 5: hasMust = true; clauses[i] = newFilterClause(field, value, MUST, random().nextBoolean()); topLevel.add(new BooleanClause(new TermQuery(new Term(String.valueOf(field), String.valueOf(value))), MUST)); break; case 4: case 3: case 2: case 1: hasShould = true; clauses[i] = newFilterClause(field, value, SHOULD, random().nextBoolean()); orQuery.add(new BooleanClause(new TermQuery(new Term(String.valueOf(field), String.valueOf(value))), SHOULD)); break; case 0: hasMustNot = true; clauses[i] = newFilterClause(field, value, MUST_NOT, random().nextBoolean()); topLevel.add(new BooleanClause(new TermQuery(new Term(String.valueOf(field), String.valueOf(value))), MUST_NOT)); break; } } if (orQuery.getClauses().length > 0) { topLevel.add(new BooleanClause(orQuery, MUST)); } if (hasMustNot && !hasMust && !hasShould) { // pure negative topLevel.add(new BooleanClause(new MatchAllDocsQuery(), MUST)); } XBooleanFilter booleanFilter = createBooleanFilter(clauses); FixedBitSet leftResult = new FixedBitSet(reader.maxDoc()); FixedBitSet rightResult = new FixedBitSet(reader.maxDoc()); DocIdSet left = booleanFilter.getDocIdSet(reader.getContext(), reader.getLiveDocs()); DocIdSet right = new QueryWrapperFilter(topLevel).getDocIdSet(reader.getContext(), reader.getLiveDocs()); if (left == null || right == null) { if (left == null && right != null) { assertThat(errorMsg(clauses, topLevel), (right.iterator() == null ? DocIdSetIterator.NO_MORE_DOCS : right.iterator().nextDoc()), equalTo(DocIdSetIterator.NO_MORE_DOCS)); } if (left != null && right == null) { assertThat(errorMsg(clauses, topLevel), (left.iterator() == null ? DocIdSetIterator.NO_MORE_DOCS : left.iterator().nextDoc()), equalTo(DocIdSetIterator.NO_MORE_DOCS)); } } else { DocIdSetIterator leftIter = left.iterator(); DocIdSetIterator rightIter = right.iterator(); if (leftIter != null) { leftResult.or(leftIter); } if (rightIter != null) { rightResult.or(rightIter); } - assertThat(leftResult.cardinality(), equalTo(leftResult.cardinality())); + assertThat(leftResult.cardinality(), equalTo(rightResult.cardinality())); for (int i = 0; i < reader.maxDoc(); i++) { assertThat(errorMsg(clauses, topLevel) + " -- failed at index " + i, leftResult.get(i), equalTo(rightResult.get(i))); } } } } private String errorMsg(FilterClause[] clauses, BooleanQuery query) { return query.toString() + " vs. " + Arrays.toString(clauses); } public static final class PrettyPrintFieldCacheTermsFilter extends FieldCacheTermsFilter { private final String value; private final String field; public PrettyPrintFieldCacheTermsFilter(String field, String value) { super(field, value); this.field = field; this.value = value; } @Override public String toString() { return "SLOW(" + field + ":" + value + ")"; } } }
true
true
public void testRandom() throws IOException { int iterations = atLeast(400); // don't worry that is fast! for (int iter = 0; iter < iterations; iter++) { int numClauses = 1 + random().nextInt(10); FilterClause[] clauses = new FilterClause[numClauses]; BooleanQuery topLevel = new BooleanQuery(); BooleanQuery orQuery = new BooleanQuery(); boolean hasMust = false; boolean hasShould = false; boolean hasMustNot = false; for(int i = 0; i < numClauses; i++) { int field = random().nextInt(5); char value = distinctValues[random().nextInt(distinctValues.length)]; switch(random().nextInt(10)) { case 9: case 8: case 7: case 6: case 5: hasMust = true; clauses[i] = newFilterClause(field, value, MUST, random().nextBoolean()); topLevel.add(new BooleanClause(new TermQuery(new Term(String.valueOf(field), String.valueOf(value))), MUST)); break; case 4: case 3: case 2: case 1: hasShould = true; clauses[i] = newFilterClause(field, value, SHOULD, random().nextBoolean()); orQuery.add(new BooleanClause(new TermQuery(new Term(String.valueOf(field), String.valueOf(value))), SHOULD)); break; case 0: hasMustNot = true; clauses[i] = newFilterClause(field, value, MUST_NOT, random().nextBoolean()); topLevel.add(new BooleanClause(new TermQuery(new Term(String.valueOf(field), String.valueOf(value))), MUST_NOT)); break; } } if (orQuery.getClauses().length > 0) { topLevel.add(new BooleanClause(orQuery, MUST)); } if (hasMustNot && !hasMust && !hasShould) { // pure negative topLevel.add(new BooleanClause(new MatchAllDocsQuery(), MUST)); } XBooleanFilter booleanFilter = createBooleanFilter(clauses); FixedBitSet leftResult = new FixedBitSet(reader.maxDoc()); FixedBitSet rightResult = new FixedBitSet(reader.maxDoc()); DocIdSet left = booleanFilter.getDocIdSet(reader.getContext(), reader.getLiveDocs()); DocIdSet right = new QueryWrapperFilter(topLevel).getDocIdSet(reader.getContext(), reader.getLiveDocs()); if (left == null || right == null) { if (left == null && right != null) { assertThat(errorMsg(clauses, topLevel), (right.iterator() == null ? DocIdSetIterator.NO_MORE_DOCS : right.iterator().nextDoc()), equalTo(DocIdSetIterator.NO_MORE_DOCS)); } if (left != null && right == null) { assertThat(errorMsg(clauses, topLevel), (left.iterator() == null ? DocIdSetIterator.NO_MORE_DOCS : left.iterator().nextDoc()), equalTo(DocIdSetIterator.NO_MORE_DOCS)); } } else { DocIdSetIterator leftIter = left.iterator(); DocIdSetIterator rightIter = right.iterator(); if (leftIter != null) { leftResult.or(leftIter); } if (rightIter != null) { rightResult.or(rightIter); } assertThat(leftResult.cardinality(), equalTo(leftResult.cardinality())); for (int i = 0; i < reader.maxDoc(); i++) { assertThat(errorMsg(clauses, topLevel) + " -- failed at index " + i, leftResult.get(i), equalTo(rightResult.get(i))); } } } }
public void testRandom() throws IOException { int iterations = atLeast(400); // don't worry that is fast! for (int iter = 0; iter < iterations; iter++) { int numClauses = 1 + random().nextInt(10); FilterClause[] clauses = new FilterClause[numClauses]; BooleanQuery topLevel = new BooleanQuery(); BooleanQuery orQuery = new BooleanQuery(); boolean hasMust = false; boolean hasShould = false; boolean hasMustNot = false; for(int i = 0; i < numClauses; i++) { int field = random().nextInt(5); char value = distinctValues[random().nextInt(distinctValues.length)]; switch(random().nextInt(10)) { case 9: case 8: case 7: case 6: case 5: hasMust = true; clauses[i] = newFilterClause(field, value, MUST, random().nextBoolean()); topLevel.add(new BooleanClause(new TermQuery(new Term(String.valueOf(field), String.valueOf(value))), MUST)); break; case 4: case 3: case 2: case 1: hasShould = true; clauses[i] = newFilterClause(field, value, SHOULD, random().nextBoolean()); orQuery.add(new BooleanClause(new TermQuery(new Term(String.valueOf(field), String.valueOf(value))), SHOULD)); break; case 0: hasMustNot = true; clauses[i] = newFilterClause(field, value, MUST_NOT, random().nextBoolean()); topLevel.add(new BooleanClause(new TermQuery(new Term(String.valueOf(field), String.valueOf(value))), MUST_NOT)); break; } } if (orQuery.getClauses().length > 0) { topLevel.add(new BooleanClause(orQuery, MUST)); } if (hasMustNot && !hasMust && !hasShould) { // pure negative topLevel.add(new BooleanClause(new MatchAllDocsQuery(), MUST)); } XBooleanFilter booleanFilter = createBooleanFilter(clauses); FixedBitSet leftResult = new FixedBitSet(reader.maxDoc()); FixedBitSet rightResult = new FixedBitSet(reader.maxDoc()); DocIdSet left = booleanFilter.getDocIdSet(reader.getContext(), reader.getLiveDocs()); DocIdSet right = new QueryWrapperFilter(topLevel).getDocIdSet(reader.getContext(), reader.getLiveDocs()); if (left == null || right == null) { if (left == null && right != null) { assertThat(errorMsg(clauses, topLevel), (right.iterator() == null ? DocIdSetIterator.NO_MORE_DOCS : right.iterator().nextDoc()), equalTo(DocIdSetIterator.NO_MORE_DOCS)); } if (left != null && right == null) { assertThat(errorMsg(clauses, topLevel), (left.iterator() == null ? DocIdSetIterator.NO_MORE_DOCS : left.iterator().nextDoc()), equalTo(DocIdSetIterator.NO_MORE_DOCS)); } } else { DocIdSetIterator leftIter = left.iterator(); DocIdSetIterator rightIter = right.iterator(); if (leftIter != null) { leftResult.or(leftIter); } if (rightIter != null) { rightResult.or(rightIter); } assertThat(leftResult.cardinality(), equalTo(rightResult.cardinality())); for (int i = 0; i < reader.maxDoc(); i++) { assertThat(errorMsg(clauses, topLevel) + " -- failed at index " + i, leftResult.get(i), equalTo(rightResult.get(i))); } } } }
diff --git a/Osm2GpsMid/src/de/ueller/osmToGpsMid/model/name/Names.java b/Osm2GpsMid/src/de/ueller/osmToGpsMid/model/name/Names.java index 8357feab..ae532162 100644 --- a/Osm2GpsMid/src/de/ueller/osmToGpsMid/model/name/Names.java +++ b/Osm2GpsMid/src/de/ueller/osmToGpsMid/model/name/Names.java @@ -1,242 +1,242 @@ /** * OSM2GpsMid * * * @version $Revision$ ($Name$) * * Copyright (C) 2007 Harald Mueller */ package de.ueller.osmToGpsMid.model.name; import java.util.Collection; import java.util.SortedMap; import java.util.SortedSet; import java.util.TreeMap; import java.util.TreeSet; import java.util.NoSuchElementException; import de.ueller.osmToGpsMid.model.Entity; import de.ueller.osmToGpsMid.model.Node; import de.ueller.osmToGpsMid.model.Way; import de.ueller.osmToGpsMid.model.POIdescription; import de.ueller.osmToGpsMid.model.WayDescription; import de.ueller.osmToGpsMid.Configuration; /** * @author hmueller * */ public class Names { // if true, index all nodes with addr:housenumber, regardless of whether there's a housenumberindex element private static boolean allAddrTags = false; private TreeMap<String,Name> names1; private TreeMap<String,Name> housenumbers1; private TreeSet<Name> canons; private TreeSet<Name> wordCanons; private TreeSet<Name> wholeWordCanons; private TreeSet<Name> houseNumberCanons; public Names() { names1=new TreeMap<String,Name>(String.CASE_INSENSITIVE_ORDER); housenumbers1=new TreeMap<String,Name>(String.CASE_INSENSITIVE_ORDER); canons=new TreeSet<Name>(new CaononComperator()); wordCanons=new TreeSet<Name>(new CaononComperator()); wholeWordCanons=new TreeSet<Name>(new CaononComperator()); houseNumberCanons=new TreeSet<Name>(new CaononComperator()); } public void calcNameIndex(){ int index=0; for (Name mapName : names1.values()) { // System.out.println(mapName+ " idx="+index); mapName.setIndex(index++);; } } public Collection<Name> getNames(){ return names1.values(); } public void addName(Entity w, WayRedirect wayRedirect) { if (w.getName() == null ) return; if (w.getName().trim().length() == 0){ return; } boolean houseNumber = false; if (w instanceof Node) { - byte type = (byte) ((Node) w).getType(Configuration.getConfiguration()); + short type = (short) ((Node) w).getType(Configuration.getConfiguration()); POIdescription poiDesc = Configuration.getConfiguration().getpoiDesc(type); //System.out.println("Testing node "+ w + " type " + type + " poiDesc = " + poiDesc); if (poiDesc != null && poiDesc.houseNumberIndex) { houseNumber = true; //System.out.println("Setting houseNumber = true for node "+ w); } } if (w instanceof Way) { - byte type = (byte) ((Way) w).getType(Configuration.getConfiguration()); + short type = (short) ((Way) w).getType(Configuration.getConfiguration()); WayDescription wayDesc = Configuration.getConfiguration().getWayDesc(type); //System.out.println("Testing way "+ w + " type " + type + "wayDesc = " + wayDesc); if (wayDesc != null && wayDesc.houseNumberIndex) { //System.out.println("Setting houseNumber = true for way "+ w); houseNumber = true; } } Name mn =new Name(w); // System.out.println("adding name:" + mn.getName()); if (names1.containsKey(mn.getName())){ // System.out.println("name already there:" + mn); Name mnNext=new Name(w.getName()+"\0"); SortedMap<String,Name> subSet=names1.subMap(mn.getName(), mnNext.getName()); Name mnExist=subSet.get(subSet.firstKey()); long redirect = mnExist.addEntity(w); //System.out.println("Way add gave redirect " + redirect); if (redirect != (long) 0) { Way way = (Way) w; //System.out.println("Will do way redirect from id " + way.id // + " to id " + redirect); Long id = new Long (way.id); Long target = new Long (redirect); wayRedirect.put(id, target); } } else { names1.put(mn.getName(),mn); } if (!houseNumber) { //System.out.println("adding to wholename canon, !houseNumber: " + mn); if (! canons.add(mn)){ //System.out.println("canon already there:" + mn); Name mnNext=new Name(w.getName()+"\0"); mnNext.setCanon( mn.getCanon()); try { SortedSet<Name> subSet=canons.tailSet(mnNext); Name mnExist=subSet.first(); if (mnExist != null) { // System.out.println("mnExist:" + mnExist); mnExist.addEntity(w); } } catch (NoSuchElementException e) { // System.out.println("no such element exc. in canons.add"); } } } // TODO: add whole word index, only add some entities (like housenumbers) to whole word idx // should add also stopwords // add to word index; don't add housenumbers when housenumberindex element is used String [] words = mn.getName().split("[ ;,.()]"); String [] housenumbers = words; if (allAddrTags && (w instanceof Node)) { Node n = (Node) w; if (n.hasHouseNumberTag()) { housenumbers = w.getAttribute("addr:housenumber").split("[ ;,.()]"); } } if (!houseNumber) { for (String word : words) { if (word.length() == 0) { //System.out.println("Empty word"); continue; } mn = new Name(word); //System.out.println("adding word:" + mn); mn.addEntity(w); if (! wordCanons.add(mn)){ //System.out.println("wordCanon already there:" + mn); Name mnNext=new Name(word+"\0"); mnNext.setCanon( mn.getCanon()); try { SortedSet<Name> subSet=wordCanons.tailSet(mnNext); Name mnExist=subSet.first(); if (mnExist != null) { // System.out.println("mnExist:" + mnExist); // Trouble? Adds to nameidx? mnExist.addEntity(w); } } catch (NoSuchElementException e) { // System.out.println("no such element exc. in wordCanons.add"); } } } } // add to housenumber index if (houseNumber || allAddrTags) { //System.out.println("Adding to housenumber index: Entity: " + w); for (String word : housenumbers) { //System.out.println("Word: " + word); if (word.length() == 0) { //System.out.println("Empty word"); continue; } mn = new Name(word); //System.out.println("adding word:" + mn); mn.addEntity(w); if (! houseNumberCanons.add(mn)){ // System.out.println("wordCanon already there:" + mn); Name mnNext=new Name(word+"\0"); mnNext.setCanon( mn.getCanon()); try { SortedSet<Name> subSet=houseNumberCanons.tailSet(mnNext); Name mnExist=subSet.first(); if (mnExist != null) { // System.out.println("mnExist:" + mnExist); // Trouble? Adds to nameidx? mnExist.addEntity(w); } } catch (NoSuchElementException e) { // System.out.println("no such element exc. in houseNumberCanons.add"); } } } } } public TreeSet<Name> getCanons() { return canons; } public TreeSet<Name> getWordCanons() { return wordCanons; } public TreeSet<Name> getWholeWordCanons() { return wholeWordCanons; } public TreeSet<Name> getHouseNumberCanons() { return houseNumberCanons; } /** * @return */ public int getNameIdx(String name) { if (name == null) { return -1; } Name nm = names1.get(name); if (nm != null) { return nm.getIndex(); } System.out.println("ERROR: Did not find name in name idx: \"" + name + "\""); return -1; } public int getEqualCount(String s1, String s2){ if (s1== null || s2 == null) return 0; int l1=s1.length(); int l2=s2.length(); int l=(l1 < l2)? l1 : l2; for (int loop=0; loop < l;loop++){ if (s1.charAt(loop) != s2.charAt(loop)) return loop; } return l; } }
false
true
public void addName(Entity w, WayRedirect wayRedirect) { if (w.getName() == null ) return; if (w.getName().trim().length() == 0){ return; } boolean houseNumber = false; if (w instanceof Node) { byte type = (byte) ((Node) w).getType(Configuration.getConfiguration()); POIdescription poiDesc = Configuration.getConfiguration().getpoiDesc(type); //System.out.println("Testing node "+ w + " type " + type + " poiDesc = " + poiDesc); if (poiDesc != null && poiDesc.houseNumberIndex) { houseNumber = true; //System.out.println("Setting houseNumber = true for node "+ w); } } if (w instanceof Way) { byte type = (byte) ((Way) w).getType(Configuration.getConfiguration()); WayDescription wayDesc = Configuration.getConfiguration().getWayDesc(type); //System.out.println("Testing way "+ w + " type " + type + "wayDesc = " + wayDesc); if (wayDesc != null && wayDesc.houseNumberIndex) { //System.out.println("Setting houseNumber = true for way "+ w); houseNumber = true; } } Name mn =new Name(w); // System.out.println("adding name:" + mn.getName()); if (names1.containsKey(mn.getName())){ // System.out.println("name already there:" + mn); Name mnNext=new Name(w.getName()+"\0"); SortedMap<String,Name> subSet=names1.subMap(mn.getName(), mnNext.getName()); Name mnExist=subSet.get(subSet.firstKey()); long redirect = mnExist.addEntity(w); //System.out.println("Way add gave redirect " + redirect); if (redirect != (long) 0) { Way way = (Way) w; //System.out.println("Will do way redirect from id " + way.id // + " to id " + redirect); Long id = new Long (way.id); Long target = new Long (redirect); wayRedirect.put(id, target); } } else { names1.put(mn.getName(),mn); } if (!houseNumber) { //System.out.println("adding to wholename canon, !houseNumber: " + mn); if (! canons.add(mn)){ //System.out.println("canon already there:" + mn); Name mnNext=new Name(w.getName()+"\0"); mnNext.setCanon( mn.getCanon()); try { SortedSet<Name> subSet=canons.tailSet(mnNext); Name mnExist=subSet.first(); if (mnExist != null) { // System.out.println("mnExist:" + mnExist); mnExist.addEntity(w); } } catch (NoSuchElementException e) { // System.out.println("no such element exc. in canons.add"); } } } // TODO: add whole word index, only add some entities (like housenumbers) to whole word idx // should add also stopwords // add to word index; don't add housenumbers when housenumberindex element is used String [] words = mn.getName().split("[ ;,.()]"); String [] housenumbers = words; if (allAddrTags && (w instanceof Node)) { Node n = (Node) w; if (n.hasHouseNumberTag()) { housenumbers = w.getAttribute("addr:housenumber").split("[ ;,.()]"); } } if (!houseNumber) { for (String word : words) { if (word.length() == 0) { //System.out.println("Empty word"); continue; } mn = new Name(word); //System.out.println("adding word:" + mn); mn.addEntity(w); if (! wordCanons.add(mn)){ //System.out.println("wordCanon already there:" + mn); Name mnNext=new Name(word+"\0"); mnNext.setCanon( mn.getCanon()); try { SortedSet<Name> subSet=wordCanons.tailSet(mnNext); Name mnExist=subSet.first(); if (mnExist != null) { // System.out.println("mnExist:" + mnExist); // Trouble? Adds to nameidx? mnExist.addEntity(w); } } catch (NoSuchElementException e) { // System.out.println("no such element exc. in wordCanons.add"); } } } } // add to housenumber index if (houseNumber || allAddrTags) { //System.out.println("Adding to housenumber index: Entity: " + w); for (String word : housenumbers) { //System.out.println("Word: " + word); if (word.length() == 0) { //System.out.println("Empty word"); continue; } mn = new Name(word); //System.out.println("adding word:" + mn); mn.addEntity(w); if (! houseNumberCanons.add(mn)){ // System.out.println("wordCanon already there:" + mn); Name mnNext=new Name(word+"\0"); mnNext.setCanon( mn.getCanon()); try { SortedSet<Name> subSet=houseNumberCanons.tailSet(mnNext); Name mnExist=subSet.first(); if (mnExist != null) { // System.out.println("mnExist:" + mnExist); // Trouble? Adds to nameidx? mnExist.addEntity(w); } } catch (NoSuchElementException e) { // System.out.println("no such element exc. in houseNumberCanons.add"); } } } } }
public void addName(Entity w, WayRedirect wayRedirect) { if (w.getName() == null ) return; if (w.getName().trim().length() == 0){ return; } boolean houseNumber = false; if (w instanceof Node) { short type = (short) ((Node) w).getType(Configuration.getConfiguration()); POIdescription poiDesc = Configuration.getConfiguration().getpoiDesc(type); //System.out.println("Testing node "+ w + " type " + type + " poiDesc = " + poiDesc); if (poiDesc != null && poiDesc.houseNumberIndex) { houseNumber = true; //System.out.println("Setting houseNumber = true for node "+ w); } } if (w instanceof Way) { short type = (short) ((Way) w).getType(Configuration.getConfiguration()); WayDescription wayDesc = Configuration.getConfiguration().getWayDesc(type); //System.out.println("Testing way "+ w + " type " + type + "wayDesc = " + wayDesc); if (wayDesc != null && wayDesc.houseNumberIndex) { //System.out.println("Setting houseNumber = true for way "+ w); houseNumber = true; } } Name mn =new Name(w); // System.out.println("adding name:" + mn.getName()); if (names1.containsKey(mn.getName())){ // System.out.println("name already there:" + mn); Name mnNext=new Name(w.getName()+"\0"); SortedMap<String,Name> subSet=names1.subMap(mn.getName(), mnNext.getName()); Name mnExist=subSet.get(subSet.firstKey()); long redirect = mnExist.addEntity(w); //System.out.println("Way add gave redirect " + redirect); if (redirect != (long) 0) { Way way = (Way) w; //System.out.println("Will do way redirect from id " + way.id // + " to id " + redirect); Long id = new Long (way.id); Long target = new Long (redirect); wayRedirect.put(id, target); } } else { names1.put(mn.getName(),mn); } if (!houseNumber) { //System.out.println("adding to wholename canon, !houseNumber: " + mn); if (! canons.add(mn)){ //System.out.println("canon already there:" + mn); Name mnNext=new Name(w.getName()+"\0"); mnNext.setCanon( mn.getCanon()); try { SortedSet<Name> subSet=canons.tailSet(mnNext); Name mnExist=subSet.first(); if (mnExist != null) { // System.out.println("mnExist:" + mnExist); mnExist.addEntity(w); } } catch (NoSuchElementException e) { // System.out.println("no such element exc. in canons.add"); } } } // TODO: add whole word index, only add some entities (like housenumbers) to whole word idx // should add also stopwords // add to word index; don't add housenumbers when housenumberindex element is used String [] words = mn.getName().split("[ ;,.()]"); String [] housenumbers = words; if (allAddrTags && (w instanceof Node)) { Node n = (Node) w; if (n.hasHouseNumberTag()) { housenumbers = w.getAttribute("addr:housenumber").split("[ ;,.()]"); } } if (!houseNumber) { for (String word : words) { if (word.length() == 0) { //System.out.println("Empty word"); continue; } mn = new Name(word); //System.out.println("adding word:" + mn); mn.addEntity(w); if (! wordCanons.add(mn)){ //System.out.println("wordCanon already there:" + mn); Name mnNext=new Name(word+"\0"); mnNext.setCanon( mn.getCanon()); try { SortedSet<Name> subSet=wordCanons.tailSet(mnNext); Name mnExist=subSet.first(); if (mnExist != null) { // System.out.println("mnExist:" + mnExist); // Trouble? Adds to nameidx? mnExist.addEntity(w); } } catch (NoSuchElementException e) { // System.out.println("no such element exc. in wordCanons.add"); } } } } // add to housenumber index if (houseNumber || allAddrTags) { //System.out.println("Adding to housenumber index: Entity: " + w); for (String word : housenumbers) { //System.out.println("Word: " + word); if (word.length() == 0) { //System.out.println("Empty word"); continue; } mn = new Name(word); //System.out.println("adding word:" + mn); mn.addEntity(w); if (! houseNumberCanons.add(mn)){ // System.out.println("wordCanon already there:" + mn); Name mnNext=new Name(word+"\0"); mnNext.setCanon( mn.getCanon()); try { SortedSet<Name> subSet=houseNumberCanons.tailSet(mnNext); Name mnExist=subSet.first(); if (mnExist != null) { // System.out.println("mnExist:" + mnExist); // Trouble? Adds to nameidx? mnExist.addEntity(w); } } catch (NoSuchElementException e) { // System.out.println("no such element exc. in houseNumberCanons.add"); } } } } }
diff --git a/src/com/android/email/activity/MailboxListFragment.java b/src/com/android/email/activity/MailboxListFragment.java index 2d18799b..51c1a787 100644 --- a/src/com/android/email/activity/MailboxListFragment.java +++ b/src/com/android/email/activity/MailboxListFragment.java @@ -1,305 +1,310 @@ /* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.email.activity; import com.android.email.Email; import com.android.email.RefreshManager; import com.android.email.Utility; import android.app.Activity; import android.app.ListFragment; import android.app.LoaderManager.LoaderCallbacks; import android.content.Loader; import android.database.Cursor; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; import java.security.InvalidParameterException; /** * This fragment presents a list of mailboxes for a given account. The "API" includes the * following elements which must be provided by the host Activity. * * - call bindActivityInfo() to provide the account ID and set callbacks * - provide callbacks for onOpen and onRefresh * - pass-through implementations of onCreateContextMenu() and onContextItemSelected() (temporary) * * TODO Restoring ListView state -- don't do this when changing accounts */ public class MailboxListFragment extends ListFragment implements OnItemClickListener { private static final String BUNDLE_KEY_ACCOUNT_ID = "MailboxListFragment.state.selected_mailbox_id"; private static final String BUNDLE_LIST_STATE = "MailboxListFragment.state.listState"; private static final int LOADER_ID_MAILBOX_LIST = 1; private long mLastLoadedAccountId = -1; private long mAccountId = -1; private long mSelectedMailboxId = -1; // UI Support private Activity mActivity; private MailboxesAdapter mListAdapter; private Callback mCallback = EmptyCallback.INSTANCE; private final MyLoaderCallbacks mMyLoaderCallbacks = new MyLoaderCallbacks(); private ListView mListView; private boolean mOpenRequested; private boolean mResumed; private Utility.ListStateSaver mSavedListState; /** * Callback interface that owning activities must implement */ public interface Callback { public void onMailboxSelected(long accountId, long mailboxId); } private static class EmptyCallback implements Callback { public static final Callback INSTANCE = new EmptyCallback(); @Override public void onMailboxSelected(long accountId, long mailboxId) { } } /** * Called to do initial creation of a fragment. This is called after * {@link #onAttach(Activity)} and before {@link #onActivityCreated(Bundle)}. */ @Override public void onCreate(Bundle savedInstanceState) { if (Email.DEBUG_LIFECYCLE && Email.DEBUG) { Log.d(Email.LOG_TAG, "MailboxListFragment onCreate"); } super.onCreate(savedInstanceState); mActivity = getActivity(); mListAdapter = new MailboxesAdapter(mActivity); if (savedInstanceState != null) { restoreInstanceState(savedInstanceState); } } @Override public void onActivityCreated(Bundle savedInstanceState) { if (Email.DEBUG_LIFECYCLE && Email.DEBUG) { Log.d(Email.LOG_TAG, "MailboxListFragment onActivityCreated"); } super.onActivityCreated(savedInstanceState); mListView = getListView(); mListView.setOnItemClickListener(this); mListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); registerForContextMenu(mListView); } public void setCallback(Callback callback) { mCallback = (callback == null) ? EmptyCallback.INSTANCE : callback; } /** * @param accountId the account we're looking at */ public void openMailboxes(long accountId) { if (Email.DEBUG_LIFECYCLE && Email.DEBUG) { Log.d(Email.LOG_TAG, "MailboxListFragment openMailboxes"); } if (accountId == -1) { throw new InvalidParameterException(); } if (mAccountId == accountId) { return; } mOpenRequested = true; mAccountId = accountId; if (mResumed) { startLoading(); } } public void setSelectedMailbox(long mailboxId) { mSelectedMailboxId = mailboxId; if (mResumed) { highlightSelectedMailbox(); } } /** * Called when the Fragment is visible to the user. */ @Override public void onStart() { if (Email.DEBUG_LIFECYCLE && Email.DEBUG) { Log.d(Email.LOG_TAG, "MailboxListFragment onStart"); } super.onStart(); } /** * Called when the fragment is visible to the user and actively running. */ @Override public void onResume() { if (Email.DEBUG_LIFECYCLE && Email.DEBUG) { Log.d(Email.LOG_TAG, "MailboxListFragment onResume"); } super.onResume(); mResumed = true; // If we're recovering from the stopped state, we don't have to reload. // (when mOpenRequested = false) if (mAccountId != -1 && mOpenRequested) { startLoading(); } } @Override public void onPause() { if (Email.DEBUG_LIFECYCLE && Email.DEBUG) { Log.d(Email.LOG_TAG, "MailboxListFragment onPause"); } mResumed = false; super.onPause(); mSavedListState = new Utility.ListStateSaver(getListView()); } /** * Called when the Fragment is no longer started. */ @Override public void onStop() { if (Email.DEBUG_LIFECYCLE && Email.DEBUG) { Log.d(Email.LOG_TAG, "MailboxListFragment onStop"); } super.onStop(); } /** * Called when the fragment is no longer in use. */ @Override public void onDestroy() { if (Email.DEBUG_LIFECYCLE && Email.DEBUG) { Log.d(Email.LOG_TAG, "MailboxListFragment onDestroy"); } super.onDestroy(); } @Override public void onSaveInstanceState(Bundle outState) { if (Email.DEBUG_LIFECYCLE && Email.DEBUG) { Log.d(Email.LOG_TAG, "MailboxListFragment onSaveInstanceState"); } super.onSaveInstanceState(outState); outState.putLong(BUNDLE_KEY_ACCOUNT_ID, mSelectedMailboxId); outState.putParcelable(BUNDLE_LIST_STATE, new Utility.ListStateSaver(getListView())); } private void restoreInstanceState(Bundle savedInstanceState) { mSelectedMailboxId = savedInstanceState.getLong(BUNDLE_KEY_ACCOUNT_ID); mSavedListState = savedInstanceState.getParcelable(BUNDLE_LIST_STATE); } private void startLoading() { if (Email.DEBUG_LIFECYCLE && Email.DEBUG) { Log.d(Email.LOG_TAG, "MailboxListFragment startLoading"); } mOpenRequested = false; // Clear the list. (ListFragment will show the "Loading" animation) setListShown(false); // If we've already loaded for a different account, discard the previous result and // start loading again. // We don't want to use restartLoader(), because if the Loader is retained, we *do* want to // reuse the previous result. if ((mLastLoadedAccountId != -1) && (mLastLoadedAccountId != mAccountId)) { getLoaderManager().stopLoader(LOADER_ID_MAILBOX_LIST); } getLoaderManager().initLoader(LOADER_ID_MAILBOX_LIST, null, mMyLoaderCallbacks); } private class MyLoaderCallbacks implements LoaderCallbacks<Cursor> { @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { if (Email.DEBUG_LIFECYCLE && Email.DEBUG) { Log.d(Email.LOG_TAG, "MailboxListFragment onCreateLoader"); } return MailboxesAdapter.createLoader(getActivity(), mAccountId, MailboxesAdapter.MODE_NORMAL); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { if (Email.DEBUG_LIFECYCLE && Email.DEBUG) { Log.d(Email.LOG_TAG, "MailboxListFragment onLoadFinished"); } mLastLoadedAccountId = mAccountId; // Save list view state (primarily scroll position) final ListView lv = getListView(); final Utility.ListStateSaver lss; if (mSavedListState != null) { lss = mSavedListState; mSavedListState = null; } else { lss = new Utility.ListStateSaver(lv); } - // Set the adapter. - mListAdapter.changeCursor(cursor); - setListAdapter(mListAdapter); - setListShown(true); - highlightSelectedMailbox(); + if (cursor.getCount() == 0) { + mListAdapter.changeCursor(null); + setListShown(false); + } else { + // Set the adapter. + mListAdapter.changeCursor(cursor); + setListAdapter(mListAdapter); + setListShown(true); + highlightSelectedMailbox(); + } // Restore the state lss.restore(lv); } } public void onItemClick(AdapterView<?> parent, View view, int position, long id) { mCallback.onMailboxSelected(mAccountId, id); } public void onRefresh() { if (mAccountId != -1) { RefreshManager.getInstance(getActivity()).refreshMailboxList(mAccountId); } } /** * Highlight the selected mailbox. */ private void highlightSelectedMailbox() { if (mSelectedMailboxId == -1) { // No mailbox selected mListView.clearChoices(); return; } final int count = mListView.getCount(); for (int i = 0; i < count; i++) { if (mListView.getItemIdAtPosition(i) == mSelectedMailboxId) { mListView.setItemChecked(i, true); break; } } } }
true
true
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { if (Email.DEBUG_LIFECYCLE && Email.DEBUG) { Log.d(Email.LOG_TAG, "MailboxListFragment onLoadFinished"); } mLastLoadedAccountId = mAccountId; // Save list view state (primarily scroll position) final ListView lv = getListView(); final Utility.ListStateSaver lss; if (mSavedListState != null) { lss = mSavedListState; mSavedListState = null; } else { lss = new Utility.ListStateSaver(lv); } // Set the adapter. mListAdapter.changeCursor(cursor); setListAdapter(mListAdapter); setListShown(true); highlightSelectedMailbox(); // Restore the state lss.restore(lv); }
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { if (Email.DEBUG_LIFECYCLE && Email.DEBUG) { Log.d(Email.LOG_TAG, "MailboxListFragment onLoadFinished"); } mLastLoadedAccountId = mAccountId; // Save list view state (primarily scroll position) final ListView lv = getListView(); final Utility.ListStateSaver lss; if (mSavedListState != null) { lss = mSavedListState; mSavedListState = null; } else { lss = new Utility.ListStateSaver(lv); } if (cursor.getCount() == 0) { mListAdapter.changeCursor(null); setListShown(false); } else { // Set the adapter. mListAdapter.changeCursor(cursor); setListAdapter(mListAdapter); setListShown(true); highlightSelectedMailbox(); } // Restore the state lss.restore(lv); }
diff --git a/src/AdditionalBuildcraftObjects/PipeLiquidsValve.java b/src/AdditionalBuildcraftObjects/PipeLiquidsValve.java index affc992..bb8aea4 100644 --- a/src/AdditionalBuildcraftObjects/PipeLiquidsValve.java +++ b/src/AdditionalBuildcraftObjects/PipeLiquidsValve.java @@ -1,198 +1,198 @@ /** * Copyright (C) 2011 Flow86 * * AdditionalBuildcraftObjects is open-source. * * It is distributed under the terms of my Open Source License. * It grants rights to read, modify, compile or run the code. * It does *NOT* grant the right to redistribute this software or its * modifications in any form, binary or source, except if expressively * granted by the copyright holder. */ package net.minecraft.src.AdditionalBuildcraftObjects; import net.minecraft.src.Block; import net.minecraft.src.TileEntity; import net.minecraft.src.World; import net.minecraft.src.buildcraft.api.API; import net.minecraft.src.buildcraft.api.ILiquidContainer; import net.minecraft.src.buildcraft.api.IPowerReceptor; import net.minecraft.src.buildcraft.api.Orientations; import net.minecraft.src.buildcraft.api.Position; import net.minecraft.src.buildcraft.api.PowerProvider; import net.minecraft.src.buildcraft.api.TileNetworkData; import net.minecraft.src.buildcraft.core.ILiquid; import net.minecraft.src.buildcraft.core.RedstonePowerProvider; import net.minecraft.src.buildcraft.core.Utils; import net.minecraft.src.buildcraft.transport.Pipe; import net.minecraft.src.buildcraft.transport.PipeLogicWood; import net.minecraft.src.buildcraft.transport.PipeTransportLiquids; import net.minecraft.src.buildcraft.transport.TileGenericPipe; public class PipeLiquidsValve extends Pipe implements IPowerReceptor, IABOSolid { PowerProvider powerProvider; public @TileNetworkData int liquidToExtract; private final int closedTexture = 0 * 16 + 0; private final int closedSideTexture = closedTexture + 2; private final int openTexture = 0 * 16 + 1; private final int openSideTexture = openTexture + 2; private int nextTexture = closedTexture; public PipeLiquidsValve(int itemID) { super(new PipeTransportLiquids(), new PipeLogicValve(), itemID); ((PipeTransportLiquids)transport).flowRate = 80; ((PipeTransportLiquids)transport).travelDelay = 2; powerProvider = new RedstonePowerProvider(); powerProvider.configure(25, 1, 64, 1, 64); powerProvider.configurePowerPerdition(64, 1); } @Override public void prepareTextureFor(Orientations connection) { int metadata = worldObj.getBlockMetadata(xCoord, yCoord, zCoord); if (connection == Orientations.Unknown || metadata != connection.ordinal()) { nextTexture = ((PipeLogicValve) logic).isPowered() ? openTexture : closedTexture; } else { nextTexture = ((PipeLogicValve) logic).isPowered() ? openSideTexture : closedSideTexture; } } public int liquidIDtoBlockID(int liquidID) { if (liquidID == Block.waterStill.blockID) { return Block.waterMoving.blockID; } else if (liquidID == Block.lavaStill.blockID) { return Block.lavaMoving.blockID; } for(Block b : Block.blocksList) { if(b instanceof ILiquid) { if(liquidID == ((ILiquid)b).stillLiquidId()) { return b.blockID; } } } return 0; } boolean isLiquidBlock(int liquid, int x, int y, int z) { int blockID = worldObj.getBlockId( x, y, z ); if(blockID == 0) return false; return (liquid == Utils.liquidId(blockID)); } @Override public void updateEntity() { super.updateEntity(); if (worldObj.isBlockIndirectlyGettingPowered(xCoord, yCoord, zCoord)) { - powerProvider.receiveEnergy(1, Orientations.Unknown); + powerProvider.receiveEnergy(1, Orientations.YNeg); } int meta = worldObj.getBlockMetadata(xCoord, yCoord, zCoord); if (liquidToExtract > 0 && meta < 6) { Position pos = new Position(xCoord, yCoord, zCoord, Orientations.values()[meta]); pos.moveForwards(1); TileEntity tile = worldObj.getBlockTileEntity((int) pos.x, (int) pos.y, (int) pos.z); if (tile instanceof ILiquidContainer) { ILiquidContainer container = (ILiquidContainer) tile; int flowRate = ((PipeTransportLiquids) transport).flowRate; int extracted = container.empty(liquidToExtract > flowRate ? flowRate : liquidToExtract, false); pos.moveBackwards(2); TileEntity tile2 = worldObj.getBlockTileEntity((int) pos.x, (int) pos.y, (int) pos.z); if( (tile2 == null || !isPipeConnected(tile2)) && (worldObj.isAirBlock((int) pos.x, (int) pos.y, (int) pos.z) || isLiquidBlock(container.getLiquidId(), (int) pos.x, (int) pos.y, (int) pos.z))) { int blockID = liquidIDtoBlockID(container.getLiquidId()); int flowDecay = extracted / 10; if(worldObj.getBlockId((int) pos.x, (int) pos.y, (int) pos.z) == blockID) { flowDecay += worldObj.getBlockMetadata((int) pos.x, (int) pos.y, (int) pos.z); if(flowDecay > 14) flowDecay = 14; } worldObj.setBlockAndMetadataWithNotify((int) pos.x, (int) pos.y, (int) pos.z, blockID, flowDecay); worldObj.markBlocksDirty((int) pos.x, (int) pos.y, (int) pos.z, (int) pos.x, (int) pos.y, (int) pos.z); worldObj.markBlockNeedsUpdate((int) pos.x, (int) pos.y, (int) pos.z); } else extracted = ((PipeTransportLiquids) transport).fill(pos.orientation, extracted, container.getLiquidId(), true); container.empty(extracted, true); liquidToExtract -= extracted; } } } @Override public int getMainBlockTexture() { return nextTexture; } @Override public void setPowerProvider(PowerProvider provider) { // powerProvider = provider; } @Override public PowerProvider getPowerProvider() { return powerProvider; } @Override public void doWork() { if (powerProvider.useEnergy(1, 1, false) < 1) return; int meta = worldObj.getBlockMetadata(xCoord, yCoord, zCoord); if (meta > 5) { return; } Position pos = new Position(xCoord, yCoord, zCoord, Orientations.values()[meta]); pos.moveForwards(1); int blockId = worldObj.getBlockId((int) pos.x, (int) pos.y, (int) pos.z); TileEntity tile = worldObj.getBlockTileEntity((int) pos.x, (int) pos.y, (int) pos.z); if (tile == null || !(tile instanceof ILiquidContainer) || PipeLogicWood.isExcludedFromExtraction(Block.blocksList[blockId])) { return; } if (tile instanceof ILiquidContainer && !(tile instanceof TileGenericPipe)) { if (liquidToExtract <= API.BUCKET_VOLUME) { liquidToExtract += powerProvider.useEnergy(1, 1, true) * API.BUCKET_VOLUME; // sendNetworkUpdate(); } } } @Override public int powerRequest() { return getPowerProvider().maxEnergyReceived; } @Override public boolean isBlockSolidOnSide(World world, int i, int j, int k, int side) { // TODO: only allow specific sides return true; } }
true
true
public void updateEntity() { super.updateEntity(); if (worldObj.isBlockIndirectlyGettingPowered(xCoord, yCoord, zCoord)) { powerProvider.receiveEnergy(1, Orientations.Unknown); } int meta = worldObj.getBlockMetadata(xCoord, yCoord, zCoord); if (liquidToExtract > 0 && meta < 6) { Position pos = new Position(xCoord, yCoord, zCoord, Orientations.values()[meta]); pos.moveForwards(1); TileEntity tile = worldObj.getBlockTileEntity((int) pos.x, (int) pos.y, (int) pos.z); if (tile instanceof ILiquidContainer) { ILiquidContainer container = (ILiquidContainer) tile; int flowRate = ((PipeTransportLiquids) transport).flowRate; int extracted = container.empty(liquidToExtract > flowRate ? flowRate : liquidToExtract, false); pos.moveBackwards(2); TileEntity tile2 = worldObj.getBlockTileEntity((int) pos.x, (int) pos.y, (int) pos.z); if( (tile2 == null || !isPipeConnected(tile2)) && (worldObj.isAirBlock((int) pos.x, (int) pos.y, (int) pos.z) || isLiquidBlock(container.getLiquidId(), (int) pos.x, (int) pos.y, (int) pos.z))) { int blockID = liquidIDtoBlockID(container.getLiquidId()); int flowDecay = extracted / 10; if(worldObj.getBlockId((int) pos.x, (int) pos.y, (int) pos.z) == blockID) { flowDecay += worldObj.getBlockMetadata((int) pos.x, (int) pos.y, (int) pos.z); if(flowDecay > 14) flowDecay = 14; } worldObj.setBlockAndMetadataWithNotify((int) pos.x, (int) pos.y, (int) pos.z, blockID, flowDecay); worldObj.markBlocksDirty((int) pos.x, (int) pos.y, (int) pos.z, (int) pos.x, (int) pos.y, (int) pos.z); worldObj.markBlockNeedsUpdate((int) pos.x, (int) pos.y, (int) pos.z); } else extracted = ((PipeTransportLiquids) transport).fill(pos.orientation, extracted, container.getLiquidId(), true); container.empty(extracted, true); liquidToExtract -= extracted; } } }
public void updateEntity() { super.updateEntity(); if (worldObj.isBlockIndirectlyGettingPowered(xCoord, yCoord, zCoord)) { powerProvider.receiveEnergy(1, Orientations.YNeg); } int meta = worldObj.getBlockMetadata(xCoord, yCoord, zCoord); if (liquidToExtract > 0 && meta < 6) { Position pos = new Position(xCoord, yCoord, zCoord, Orientations.values()[meta]); pos.moveForwards(1); TileEntity tile = worldObj.getBlockTileEntity((int) pos.x, (int) pos.y, (int) pos.z); if (tile instanceof ILiquidContainer) { ILiquidContainer container = (ILiquidContainer) tile; int flowRate = ((PipeTransportLiquids) transport).flowRate; int extracted = container.empty(liquidToExtract > flowRate ? flowRate : liquidToExtract, false); pos.moveBackwards(2); TileEntity tile2 = worldObj.getBlockTileEntity((int) pos.x, (int) pos.y, (int) pos.z); if( (tile2 == null || !isPipeConnected(tile2)) && (worldObj.isAirBlock((int) pos.x, (int) pos.y, (int) pos.z) || isLiquidBlock(container.getLiquidId(), (int) pos.x, (int) pos.y, (int) pos.z))) { int blockID = liquidIDtoBlockID(container.getLiquidId()); int flowDecay = extracted / 10; if(worldObj.getBlockId((int) pos.x, (int) pos.y, (int) pos.z) == blockID) { flowDecay += worldObj.getBlockMetadata((int) pos.x, (int) pos.y, (int) pos.z); if(flowDecay > 14) flowDecay = 14; } worldObj.setBlockAndMetadataWithNotify((int) pos.x, (int) pos.y, (int) pos.z, blockID, flowDecay); worldObj.markBlocksDirty((int) pos.x, (int) pos.y, (int) pos.z, (int) pos.x, (int) pos.y, (int) pos.z); worldObj.markBlockNeedsUpdate((int) pos.x, (int) pos.y, (int) pos.z); } else extracted = ((PipeTransportLiquids) transport).fill(pos.orientation, extracted, container.getLiquidId(), true); container.empty(extracted, true); liquidToExtract -= extracted; } } }
diff --git a/core/src/main/java/org/apache/mahout/cf/taste/impl/eval/IRStatisticsImpl.java b/core/src/main/java/org/apache/mahout/cf/taste/impl/eval/IRStatisticsImpl.java index f6aadae1..f82f9584 100644 --- a/core/src/main/java/org/apache/mahout/cf/taste/impl/eval/IRStatisticsImpl.java +++ b/core/src/main/java/org/apache/mahout/cf/taste/impl/eval/IRStatisticsImpl.java @@ -1,89 +1,89 @@ /** * 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.io.Serializable; import org.apache.mahout.cf.taste.eval.IRStatistics; import com.google.common.base.Preconditions; public final class IRStatisticsImpl implements IRStatistics, Serializable { private final double precision; private final double recall; private final double fallOut; private final double ndcg; private final double reach; IRStatisticsImpl(double precision, double recall, double fallOut, double ndcg, double reach) { Preconditions.checkArgument(precision >= 0.0 && precision <= 1.0, "Illegal precision: " + precision); Preconditions.checkArgument(recall >= 0.0 && recall <= 1.0, "Illegal recall: " + recall); Preconditions.checkArgument(fallOut >= 0.0 && fallOut <= 1.0, "Illegal fallOut: " + fallOut); - Preconditions.checkArgument(fallOut >= 0.0 && fallOut <= 1.0, "Illegal nDCG: " + ndcg); - Preconditions.checkArgument(reach >= 0.0 && reach <= 1.0, "Illegal reach: " + ndcg); + Preconditions.checkArgument(ndcg >= 0.0 && ndcg <= 1.0, "Illegal nDCG: " + ndcg); + Preconditions.checkArgument(reach >= 0.0 && reach <= 1.0, "Illegal reach: " + reach); this.precision = precision; this.recall = recall; this.fallOut = fallOut; this.ndcg = ndcg; this.reach = reach; } @Override public double getPrecision() { return precision; } @Override public double getRecall() { return recall; } @Override public double getFallOut() { return fallOut; } @Override public double getF1Measure() { return getFNMeasure(1.0); } @Override public double getFNMeasure(double n) { double sum = n * precision + recall; return sum == 0.0 ? Double.NaN : (1.0 + n) * precision * recall / sum; } @Override public double getNormalizedDiscountedCumulativeGain() { return ndcg; } @Override public double getReach() { return reach; } @Override public String toString() { return "IRStatisticsImpl[precision:" + precision + ",recall:" + recall + ",fallOut:" + fallOut + ",nDCG:" + ndcg + ",reach:" + reach + ']'; } }
true
true
IRStatisticsImpl(double precision, double recall, double fallOut, double ndcg, double reach) { Preconditions.checkArgument(precision >= 0.0 && precision <= 1.0, "Illegal precision: " + precision); Preconditions.checkArgument(recall >= 0.0 && recall <= 1.0, "Illegal recall: " + recall); Preconditions.checkArgument(fallOut >= 0.0 && fallOut <= 1.0, "Illegal fallOut: " + fallOut); Preconditions.checkArgument(fallOut >= 0.0 && fallOut <= 1.0, "Illegal nDCG: " + ndcg); Preconditions.checkArgument(reach >= 0.0 && reach <= 1.0, "Illegal reach: " + ndcg); this.precision = precision; this.recall = recall; this.fallOut = fallOut; this.ndcg = ndcg; this.reach = reach; }
IRStatisticsImpl(double precision, double recall, double fallOut, double ndcg, double reach) { Preconditions.checkArgument(precision >= 0.0 && precision <= 1.0, "Illegal precision: " + precision); Preconditions.checkArgument(recall >= 0.0 && recall <= 1.0, "Illegal recall: " + recall); Preconditions.checkArgument(fallOut >= 0.0 && fallOut <= 1.0, "Illegal fallOut: " + fallOut); Preconditions.checkArgument(ndcg >= 0.0 && ndcg <= 1.0, "Illegal nDCG: " + ndcg); Preconditions.checkArgument(reach >= 0.0 && reach <= 1.0, "Illegal reach: " + reach); this.precision = precision; this.recall = recall; this.fallOut = fallOut; this.ndcg = ndcg; this.reach = reach; }
diff --git a/gwt20/modules/atmosphere-gwt20-client/src/main/java/org/atmosphere/gwt20/client/AtmosphereClientTimeoutHandler.java b/gwt20/modules/atmosphere-gwt20-client/src/main/java/org/atmosphere/gwt20/client/AtmosphereClientTimeoutHandler.java index 80107bd8..cd86a087 100644 --- a/gwt20/modules/atmosphere-gwt20-client/src/main/java/org/atmosphere/gwt20/client/AtmosphereClientTimeoutHandler.java +++ b/gwt20/modules/atmosphere-gwt20-client/src/main/java/org/atmosphere/gwt20/client/AtmosphereClientTimeoutHandler.java @@ -1,24 +1,24 @@ /* * Copyright 2013 Jeanfrancois Arcand * * 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.atmosphere.gwt20.client; /** * * @author Jeanfrancois Arcand */ public interface AtmosphereClientTimeoutHandler { - public void onClientTimeout(AtmosphereRequest response); + public void onClientTimeout(AtmosphereRequest request); }
true
true
public void onClientTimeout(AtmosphereRequest response);
public void onClientTimeout(AtmosphereRequest request);
diff --git a/ggj_2013/src/sound/BeatTrack.java b/ggj_2013/src/sound/BeatTrack.java index eed0f68..0a1005b 100644 --- a/ggj_2013/src/sound/BeatTrack.java +++ b/ggj_2013/src/sound/BeatTrack.java @@ -1,85 +1,86 @@ package sound; import game.GameControl; import java.util.ArrayList; import java.util.List; public class BeatTrack { private boolean[] beats = new boolean[32]; private List<BeatListener> listeners; private boolean playing = false; private long startTime; private int beatIndex; private long beatTime; private long endTime; private int loopsLeft = 1; public static long DELAY = 1287; /** * Creates a BeatTrack based on the code. The code consists of 0's and 1's, where * 0 corresponds to an eighth rest and 1 corresponds to an eighth beat. * @param code - A string that tells when to make a heartbeat. */ public BeatTrack(String code) { listeners = new ArrayList<BeatListener>(); char[] c = code.toCharArray(); for (int i=0;i<32;i++) { if (c[i] == '0') { beats[i] = false; } else { beats[i] = true; } } } public void addBeatListener(BeatListener listener) { listeners.add(listener); } public void play(long time) { startTime = time; endTime = startTime + 16*429L; playing = true; beatIndex = 0; } public void update(long currentTime) { if (playing) { if (currentTime >= beatTime) { getNextBeat(); for (BeatListener listener : listeners) { listener.beat(); } } if (currentTime >= endTime) { if (loopsLeft > 0) { play(currentTime); loopsLeft--; } else { for (BeatListener listener : listeners) { listener.endOfTrack(); } + playing = false; } } } } private void getNextBeat() { beatIndex++; while (beatIndex < 32 && beats[beatIndex] == false) { beatIndex++; } if (beats[beatIndex]) { beatTime = startTime + beatIndex*429; } } }
true
true
public void update(long currentTime) { if (playing) { if (currentTime >= beatTime) { getNextBeat(); for (BeatListener listener : listeners) { listener.beat(); } } if (currentTime >= endTime) { if (loopsLeft > 0) { play(currentTime); loopsLeft--; } else { for (BeatListener listener : listeners) { listener.endOfTrack(); } } } } }
public void update(long currentTime) { if (playing) { if (currentTime >= beatTime) { getNextBeat(); for (BeatListener listener : listeners) { listener.beat(); } } if (currentTime >= endTime) { if (loopsLeft > 0) { play(currentTime); loopsLeft--; } else { for (BeatListener listener : listeners) { listener.endOfTrack(); } playing = false; } } } }
diff --git a/src/edu/vanderbilt/vm/guide/util/JsonUtils.java b/src/edu/vanderbilt/vm/guide/util/JsonUtils.java index 82cfc83..b0de913 100644 --- a/src/edu/vanderbilt/vm/guide/util/JsonUtils.java +++ b/src/edu/vanderbilt/vm/guide/util/JsonUtils.java @@ -1,32 +1,34 @@ package edu.vanderbilt.vm.guide.util; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.InputStream; import java.io.InputStreamReader; import org.json.JSONArray; import android.content.Context; import android.net.Uri; public class JsonUtils { /** * Because this is just a class for static utility methods, this * class should not be instantiated. */ private JsonUtils() { throw new AssertionError("Do not instantiate this class."); } public static JSONArray readJSONArrayFromFile(Uri uri, Context context) throws FileNotFoundException { InputStream in = context.getContentResolver().openInputStream(uri); BufferedReader buf = new BufferedReader(new InputStreamReader(in)); + return null; + // incomplete code } }
true
true
public static JSONArray readJSONArrayFromFile(Uri uri, Context context) throws FileNotFoundException { InputStream in = context.getContentResolver().openInputStream(uri); BufferedReader buf = new BufferedReader(new InputStreamReader(in)); }
public static JSONArray readJSONArrayFromFile(Uri uri, Context context) throws FileNotFoundException { InputStream in = context.getContentResolver().openInputStream(uri); BufferedReader buf = new BufferedReader(new InputStreamReader(in)); return null; // incomplete code }
diff --git a/src/com/android/gallery3d/photoeditor/filters/DoodleFilter.java b/src/com/android/gallery3d/photoeditor/filters/DoodleFilter.java index 3c4bbf7..b40f458 100644 --- a/src/com/android/gallery3d/photoeditor/filters/DoodleFilter.java +++ b/src/com/android/gallery3d/photoeditor/filters/DoodleFilter.java @@ -1,88 +1,88 @@ /* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.gallery3d.photoeditor.filters; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Path; import android.graphics.RectF; import android.media.effect.Effect; import android.media.effect.EffectContext; import android.media.effect.EffectFactory; import com.android.gallery3d.photoeditor.Photo; import com.android.gallery3d.photoeditor.actions.DoodlePaint; import java.util.Vector; /** * Doodle filter applied to the image. */ public class DoodleFilter extends Filter { private static class ColorPath { private final int color; private final Path path; ColorPath(int color, Path path) { this.color = color; this.path = path; } } private final Vector<ColorPath> doodles = new Vector<ColorPath>(); /** * Signals once at least a doodle drawn within photo bounds; this filter is regarded as invalid * (no-op on the photo) until not all its doodling is out of bounds. */ public void setDoodledInPhotoBounds() { validate(); } /** * The path coordinates used here should range from 0 to 1. */ public void addPath(Path path, int color) { doodles.add(new ColorPath(color, path)); } @Override public void process(EffectContext context, Photo src, Photo dst) { Bitmap bitmap = Bitmap.createBitmap(src.width(), src.height(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); Matrix matrix = new Matrix(); matrix.setRectToRect(new RectF(0, 0, 1, 1), new RectF(0, 0, bitmap.getWidth(), bitmap.getHeight()), Matrix.ScaleToFit.FILL); Path drawingPath = new Path(); Paint paint = new DoodlePaint(); for (ColorPath doodle : doodles) { paint.setColor(doodle.color); drawingPath.set(doodle.path); drawingPath.transform(matrix); canvas.drawPath(drawingPath, paint); } - Effect effect = getEffect(context, EffectFactory.EFFECT_DOODLE); + Effect effect = getEffect(context, EffectFactory.EFFECT_BITMAPOVERLAY); effect.setParameter("doodle", bitmap); effect.apply(src.texture(), src.width(), src.height(), dst.texture()); } }
true
true
public void process(EffectContext context, Photo src, Photo dst) { Bitmap bitmap = Bitmap.createBitmap(src.width(), src.height(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); Matrix matrix = new Matrix(); matrix.setRectToRect(new RectF(0, 0, 1, 1), new RectF(0, 0, bitmap.getWidth(), bitmap.getHeight()), Matrix.ScaleToFit.FILL); Path drawingPath = new Path(); Paint paint = new DoodlePaint(); for (ColorPath doodle : doodles) { paint.setColor(doodle.color); drawingPath.set(doodle.path); drawingPath.transform(matrix); canvas.drawPath(drawingPath, paint); } Effect effect = getEffect(context, EffectFactory.EFFECT_DOODLE); effect.setParameter("doodle", bitmap); effect.apply(src.texture(), src.width(), src.height(), dst.texture()); }
public void process(EffectContext context, Photo src, Photo dst) { Bitmap bitmap = Bitmap.createBitmap(src.width(), src.height(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); Matrix matrix = new Matrix(); matrix.setRectToRect(new RectF(0, 0, 1, 1), new RectF(0, 0, bitmap.getWidth(), bitmap.getHeight()), Matrix.ScaleToFit.FILL); Path drawingPath = new Path(); Paint paint = new DoodlePaint(); for (ColorPath doodle : doodles) { paint.setColor(doodle.color); drawingPath.set(doodle.path); drawingPath.transform(matrix); canvas.drawPath(drawingPath, paint); } Effect effect = getEffect(context, EffectFactory.EFFECT_BITMAPOVERLAY); effect.setParameter("doodle", bitmap); effect.apply(src.texture(), src.width(), src.height(), dst.texture()); }
diff --git a/GlassLine/src/engine/brandonCF/agents/ConShuttle.java b/GlassLine/src/engine/brandonCF/agents/ConShuttle.java index 3b4cd27..b475469 100644 --- a/GlassLine/src/engine/brandonCF/agents/ConShuttle.java +++ b/GlassLine/src/engine/brandonCF/agents/ConShuttle.java @@ -1,198 +1,198 @@ package engine.brandonCF.agents; import java.util.ArrayList; import java.util.Collections; import java.util.List; import transducer.TChannel; import transducer.TEvent; import transducer.Transducer; import engine.agent.Agent; import engine.agent.shared.Glass; import engine.agent.shared.Interfaces.ConveyorFamily; import engine.agent.shared.Interfaces.Machine; public class ConShuttle extends Agent implements ConveyorFamily { public enum Status {normal, waiting, send}; private class GlassPacket { public Glass g; public Status status; public GlassPacket(Glass g) { this.g = g; status = Status.normal; } } private List<GlassPacket> glass = Collections.synchronizedList(new ArrayList<GlassPacket>()); private Integer[] number; ConveyorFamily con; Machine mac; boolean canSend, notified, conMoving, released, overRide; public ConShuttle(String name, Transducer t, int num) { super(name, t); number = new Integer[1]; number[0] = num; transducer.register(this, TChannel.CONVEYOR); transducer.register(this, TChannel.SENSOR); canSend = true; notified = false; conMoving = true; released = false; transducer.fireEvent(TChannel.CONVEYOR, TEvent.CONVEYOR_DO_START, number); overRide = false; } @Override public void msgSpaceAvailable() { // TODO Auto-generated method stub print("Next Open"); canSend = true; stateChanged(); } @Override public void msgHereIsGlass(Glass g) { this.glass.add(new GlassPacket(g)); print(name.toString() +" received glass"); notified = false; stateChanged(); } public void msgOverRideStop() { overRide = true; stateChanged(); } public void msgOverRideStart() { overRide = false; stateChanged(); } //scheduler @Override public boolean pickAndExecuteAnAction() { // TODO Auto-generated method stub if(!overRide) { if(glass.size()>0)//if there are packets, try to do something { if(glass.get(0).status == Status.send)//if you can send { if(canSend){ sendGlass(glass.get(0)); //return true; } else//*/ { stopConveyor(); return false; } } if(notified ==false & conMoving & released)//if i haven't notified & the conveyor is moving is not stopped { msgMac(); return true; } } else { msgMac(); } } return false; } //actions private void stopConveyor() { transducer.fireEvent(TChannel.CONVEYOR, TEvent.CONVEYOR_DO_STOP, number); conMoving = false; } private void msgMac() { mac.msgSpaceAvailable(); print(name.toString() +" Space Open"); notified = true; released = false; } private void sendGlass(GlassPacket glassPacket) { canSend = false; con.msgHereIsGlass(glassPacket.g);//send the glass glass.remove(glassPacket);//remove from list //if(conMoving!= true) { transducer.fireEvent(TChannel.CONVEYOR, TEvent.CONVEYOR_DO_START, number); conMoving = true; } print(name.toString() +" sent glass"); print(""+notified); print(""+released); print(""+ glass.size()); stateChanged(); } @Override public void eventFired(TChannel channel, TEvent event, Object[] args) { // TODO Auto-generated method stub if(channel == TChannel.SENSOR & event == TEvent.SENSOR_GUI_RELEASED) { if(args[0].equals(number[0] *2))//if second sensor { //released = true; //stateChanged(); } // if(args[0].equals(number[0] *2+1))//if second sensor // { // glass.get(0).status = Status.send; // stateChanged(); // } } - if(channel == TChannel.SENSOR & event == TEvent.SENSOR_GUI_PRESSED) { + if(channel == TChannel.SENSOR & event == TEvent.SENSOR_GUI_RELEASED) { if(args[0].equals(number[0] *2+1))//if second sensor { released = true; glass.get(0).status = Status.send; stateChanged(); } } /*if(channel == TChannel.CONVEYOR & event == TEvent.CONVEYOR_BREAK) { if(args[0].equals(number[0])) { msgOverRideStop(); } } if(channel == TChannel.CONVEYOR & event == TEvent.CONVEYOR_FIX) { if(args[0].equals(number[0])) { msgOverRideStart(); } }*/ } public void setConveyor(ConveyorFamily c) { con = c; } public void setMachine(Machine m) { mac = m; } }
true
true
public void eventFired(TChannel channel, TEvent event, Object[] args) { // TODO Auto-generated method stub if(channel == TChannel.SENSOR & event == TEvent.SENSOR_GUI_RELEASED) { if(args[0].equals(number[0] *2))//if second sensor { //released = true; //stateChanged(); } // if(args[0].equals(number[0] *2+1))//if second sensor // { // glass.get(0).status = Status.send; // stateChanged(); // } } if(channel == TChannel.SENSOR & event == TEvent.SENSOR_GUI_PRESSED) { if(args[0].equals(number[0] *2+1))//if second sensor { released = true; glass.get(0).status = Status.send; stateChanged(); } } /*if(channel == TChannel.CONVEYOR & event == TEvent.CONVEYOR_BREAK) { if(args[0].equals(number[0])) { msgOverRideStop(); } } if(channel == TChannel.CONVEYOR & event == TEvent.CONVEYOR_FIX) { if(args[0].equals(number[0])) { msgOverRideStart(); } }*/ }
public void eventFired(TChannel channel, TEvent event, Object[] args) { // TODO Auto-generated method stub if(channel == TChannel.SENSOR & event == TEvent.SENSOR_GUI_RELEASED) { if(args[0].equals(number[0] *2))//if second sensor { //released = true; //stateChanged(); } // if(args[0].equals(number[0] *2+1))//if second sensor // { // glass.get(0).status = Status.send; // stateChanged(); // } } if(channel == TChannel.SENSOR & event == TEvent.SENSOR_GUI_RELEASED) { if(args[0].equals(number[0] *2+1))//if second sensor { released = true; glass.get(0).status = Status.send; stateChanged(); } } /*if(channel == TChannel.CONVEYOR & event == TEvent.CONVEYOR_BREAK) { if(args[0].equals(number[0])) { msgOverRideStop(); } } if(channel == TChannel.CONVEYOR & event == TEvent.CONVEYOR_FIX) { if(args[0].equals(number[0])) { msgOverRideStart(); } }*/ }
diff --git a/emailcommon/src/com/android/emailcommon/Device.java b/emailcommon/src/com/android/emailcommon/Device.java index 889139ac..ba93062e 100644 --- a/emailcommon/src/com/android/emailcommon/Device.java +++ b/emailcommon/src/com/android/emailcommon/Device.java @@ -1,110 +1,112 @@ /* /* * 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.emailcommon; import android.content.Context; import android.telephony.TelephonyManager; import android.util.Log; import com.android.emailcommon.utility.Utility; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class Device { private static String sDeviceId = null; /** * EAS requires a unique device id, so that sync is possible from a variety of different * devices (e.g. the syncKey is specific to a device) If we're on an emulator or some other * device that doesn't provide one, we can create it as android<n> where <n> is system time. * This would work on a real device as well, but it would be better to use the "real" id if * it's available */ static public synchronized String getDeviceId(Context context) throws IOException { if (sDeviceId == null) { sDeviceId = getDeviceIdInternal(context); } return sDeviceId; } static private String getDeviceIdInternal(Context context) throws IOException { if (context == null) { throw new IllegalStateException("getDeviceId requires a Context"); } File f = context.getFileStreamPath("deviceName"); BufferedReader rdr = null; String id; if (f.exists()) { if (f.canRead()) { rdr = new BufferedReader(new FileReader(f), 128); id = rdr.readLine(); rdr.close(); if (id == null) { // It's very bad if we read a null device id; let's delete that file if (!f.delete()) { Log.e(Logging.LOG_TAG, "Can't delete null deviceName file; try overwrite."); } + } else { + return id; } } else { Log.w(Logging.LOG_TAG, f.getAbsolutePath() + ": File exists, but can't read?" + " Trying to remove."); if (!f.delete()) { Log.w(Logging.LOG_TAG, "Remove failed. Tring to overwrite."); } } } BufferedWriter w = new BufferedWriter(new FileWriter(f), 128); final String consistentDeviceId = getConsistentDeviceId(context); if (consistentDeviceId != null) { // Use different prefix from random IDs. id = "androidc" + consistentDeviceId; } else { id = "android" + System.currentTimeMillis(); } w.write(id); w.close(); return id; } /** * @return Device's unique ID if available. null if the device has no unique ID. */ public static String getConsistentDeviceId(Context context) { final String deviceId; try { TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); if (tm == null) { return null; } deviceId = tm.getDeviceId(); if (deviceId == null) { return null; } } catch (Exception e) { Log.d(Logging.LOG_TAG, "Error in TelephonyManager.getDeviceId(): " + e.getMessage()); return null; } return Utility.getSmallHash(deviceId); } }
true
true
static private String getDeviceIdInternal(Context context) throws IOException { if (context == null) { throw new IllegalStateException("getDeviceId requires a Context"); } File f = context.getFileStreamPath("deviceName"); BufferedReader rdr = null; String id; if (f.exists()) { if (f.canRead()) { rdr = new BufferedReader(new FileReader(f), 128); id = rdr.readLine(); rdr.close(); if (id == null) { // It's very bad if we read a null device id; let's delete that file if (!f.delete()) { Log.e(Logging.LOG_TAG, "Can't delete null deviceName file; try overwrite."); } } } else { Log.w(Logging.LOG_TAG, f.getAbsolutePath() + ": File exists, but can't read?" + " Trying to remove."); if (!f.delete()) { Log.w(Logging.LOG_TAG, "Remove failed. Tring to overwrite."); } } } BufferedWriter w = new BufferedWriter(new FileWriter(f), 128); final String consistentDeviceId = getConsistentDeviceId(context); if (consistentDeviceId != null) { // Use different prefix from random IDs. id = "androidc" + consistentDeviceId; } else { id = "android" + System.currentTimeMillis(); } w.write(id); w.close(); return id; }
static private String getDeviceIdInternal(Context context) throws IOException { if (context == null) { throw new IllegalStateException("getDeviceId requires a Context"); } File f = context.getFileStreamPath("deviceName"); BufferedReader rdr = null; String id; if (f.exists()) { if (f.canRead()) { rdr = new BufferedReader(new FileReader(f), 128); id = rdr.readLine(); rdr.close(); if (id == null) { // It's very bad if we read a null device id; let's delete that file if (!f.delete()) { Log.e(Logging.LOG_TAG, "Can't delete null deviceName file; try overwrite."); } } else { return id; } } else { Log.w(Logging.LOG_TAG, f.getAbsolutePath() + ": File exists, but can't read?" + " Trying to remove."); if (!f.delete()) { Log.w(Logging.LOG_TAG, "Remove failed. Tring to overwrite."); } } } BufferedWriter w = new BufferedWriter(new FileWriter(f), 128); final String consistentDeviceId = getConsistentDeviceId(context); if (consistentDeviceId != null) { // Use different prefix from random IDs. id = "androidc" + consistentDeviceId; } else { id = "android" + System.currentTimeMillis(); } w.write(id); w.close(); return id; }
diff --git a/webapp/WEB-INF/classes/org/makumba/parade/init/ParadeProperties.java b/webapp/WEB-INF/classes/org/makumba/parade/init/ParadeProperties.java index 1f5b283..2d33dcd 100644 --- a/webapp/WEB-INF/classes/org/makumba/parade/init/ParadeProperties.java +++ b/webapp/WEB-INF/classes/org/makumba/parade/init/ParadeProperties.java @@ -1,53 +1,53 @@ package org.makumba.parade.init; import java.io.File; import java.io.FileInputStream; import java.util.LinkedList; import java.util.List; import java.util.Properties; import java.util.StringTokenizer; import org.apache.log4j.Logger; public class ParadeProperties { static public String paradeBase = "." + java.io.File.separator; static String fileName = paradeBase + "parade.properties"; private static Properties config; static public String paradeBaseRelativeToTomcatWebapps = ".." + File.separator + ".."; static Logger logger = Logger.getLogger(ParadeProperties.class.getName()); static { try { config = new Properties(); config.load(new FileInputStream(fileName)); } catch (Throwable t) { logger.error("Error while loading parade.properties",t); } } public static String getProperty(String configProperty) { return config.getProperty(configProperty); } public static List getElements(String configProperty) { List l = new LinkedList(); String s = getProperty(configProperty); if(s == null) - s = "noSuchProperty"; + return null; StringTokenizer st = new StringTokenizer(s,","); while(st.hasMoreElements()) { l.add(((String)st.nextToken()).trim()); } return l; } }
true
true
public static List getElements(String configProperty) { List l = new LinkedList(); String s = getProperty(configProperty); if(s == null) s = "noSuchProperty"; StringTokenizer st = new StringTokenizer(s,","); while(st.hasMoreElements()) { l.add(((String)st.nextToken()).trim()); } return l; }
public static List getElements(String configProperty) { List l = new LinkedList(); String s = getProperty(configProperty); if(s == null) return null; StringTokenizer st = new StringTokenizer(s,","); while(st.hasMoreElements()) { l.add(((String)st.nextToken()).trim()); } return l; }
diff --git a/src/main/java/cc/redberry/core/transformations/ApplyIndexMapping.java b/src/main/java/cc/redberry/core/transformations/ApplyIndexMapping.java index c43d3cb..c17e0f4 100644 --- a/src/main/java/cc/redberry/core/transformations/ApplyIndexMapping.java +++ b/src/main/java/cc/redberry/core/transformations/ApplyIndexMapping.java @@ -1,206 +1,207 @@ /* * Redberry: symbolic tensor computations. * * Copyright (c) 2010-2012: * Stanislav Poslavsky <[email protected]> * Bolotin Dmitriy <[email protected]> * * This file is part of Redberry. * * Redberry 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. * * Redberry 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 Redberry. If not, see <http://www.gnu.org/licenses/>. */ package cc.redberry.core.transformations; import cc.redberry.core.indexgenerator.IndexGenerator; import cc.redberry.core.indexmapping.IndexMapping; import cc.redberry.core.indexmapping.IndexMappingBuffer; import cc.redberry.core.indexmapping.IndexMappingBufferRecord; import cc.redberry.core.indices.Indices; import cc.redberry.core.indices.IndicesUtils; import cc.redberry.core.indices.SimpleIndices; import cc.redberry.core.tensor.*; import cc.redberry.core.tensor.iterator.TraverseGuide; import cc.redberry.core.tensor.iterator.TraverseState; import cc.redberry.core.tensor.iterator.TreeTraverseIterator; import cc.redberry.core.utils.ArraysUtils; import cc.redberry.core.utils.IntArrayList; import cc.redberry.core.utils.TensorUtils; import java.util.Arrays; import java.util.Map; import java.util.Set; /** * * @author Dmitry Bolotin * @author Stanislav Poslavsky */ public final class ApplyIndexMapping implements Transformation { private final int[] from, to, forbidden; public ApplyIndexMapping(int[] from, int[] to, int[] forbidden) { this.from = from.clone(); this.to = to.clone(); this.forbidden = forbidden; } @Override public Tensor transform(Tensor t) { checkConsistent(t, from); return applyIndexMapping(t, from, to, forbidden); } private static void checkConsistent(Tensor tensor, final int[] from) { int[] freeIndices = tensor.getIndices().getFreeIndices().getAllIndices().copy(); Arrays.sort(freeIndices); int[] _from = from.clone(); Arrays.sort(_from); if (!Arrays.equals(freeIndices, _from)) throw new IllegalArgumentException("From indices are not equal to free indices of tensor."); } public static Tensor applyIndexMapping(Tensor tensor, int[] from, int[] to, int[] forbidden) { checkConsistent(tensor, from); return unsafeApplyIndexMappingFromClonedSource(tensor, from.clone(), to.clone(), forbidden); } public static Tensor applyIndexMapping(Tensor tensor, IndexMappingBuffer buffer) { return applyIndexMapping(tensor, buffer, new int[0]); } public static Tensor applyIndexMapping(Tensor tensor, IndexMappingBuffer buffer, int[] forbidden) { Map<Integer, IndexMappingBufferRecord> map = buffer.getMap(); int[] from = new int[map.size()], to = new int[map.size()]; int count = 0; IndexMappingBufferRecord record; for (Map.Entry<Integer, IndexMappingBufferRecord> entry : map.entrySet()) { from[count] = entry.getKey(); record = entry.getValue(); to[count++] = record.getIndexName() ^ (record.isContracted() ? 0x80000000 : 0); } final int[] freeIndices = tensor.getIndices().getFreeIndices().getAllIndices().copy(); for (int i = 0; i < freeIndices.length; ++i) freeIndices[i] = IndicesUtils.getNameWithType(freeIndices[i]); Arrays.sort(freeIndices); int[] _from = from.clone(); Arrays.sort(_from); if (!Arrays.equals(freeIndices, _from)) throw new IllegalArgumentException("From indices are not equal to free indices of tensor."); return unsafeApplyIndexMappingFromSortedClonedSource(tensor, from, to, forbidden); } public static Tensor renameDummy(Tensor tensor, int[] forbidden) { return renameDummy(tensor, forbidden.clone()); } public static Tensor renameDummyFromClonedSource(Tensor tensor, int[] forbidden) { int[] from = tensor.getIndices().getFreeIndices().getAllIndices().copy(); for (int i = from.length - 1; i >= 0; --i) from[i] = IndicesUtils.getNameWithType(from[i]); return unsafeApplyIndexMappingFromSortedClonedSource(tensor, from, from, forbidden); } public static Tensor unsafeApplyIndexMappingFromClonedSource(Tensor tensor, int[] from, int[] to, int[] forbidden) { int i, rawState; for (i = from.length - 1; i >= 0; --i) { rawState = IndicesUtils.getRawStateInt(from[i]); from[i] ^= rawState; to[i] ^= rawState; } ArraysUtils.quickSort(from, to); return unsafeApplyIndexMappingFromSortedClonedSource(tensor, from, to, forbidden); } public static Tensor unsafeApplyIndexMappingFromSortedClonedSource( Tensor tensor, int[] from, int[] to, int[] forbidden) { Set<Integer> dummyIndices = TensorUtils.getAllIndices(tensor); //extracting contracted only Indices indices = tensor.getIndices().getFreeIndices(); int i; for (i = indices.size() - 1; i >= 0; --i) dummyIndices.remove(IndicesUtils.getNameWithType(indices.get(i))); int[] allForbidden = new int[to.length + forbidden.length]; System.arraycopy(to, 0, allForbidden, 0, to.length); System.arraycopy(forbidden, 0, allForbidden, to.length, forbidden.length); for (i = allForbidden.length - 1; i >= 0; --i) allForbidden[i] = IndicesUtils.getNameWithType(allForbidden[i]); IntArrayList fromL = new IntArrayList(from.length), toL = new IntArrayList(to.length); fromL.addAll(from); toL.addAll(to); int[] forbiddenGeneratorIndices = new int[allForbidden.length + dummyIndices.size()]; System.arraycopy(allForbidden, 0, forbiddenGeneratorIndices, 0, allForbidden.length); i = allForbidden.length - 1; for (Integer index : dummyIndices) forbiddenGeneratorIndices[++i] = index; + Arrays.sort(allForbidden); IndexGenerator generator = new IndexGenerator(forbiddenGeneratorIndices);//also sorts allForbidden array for (Integer index : dummyIndices) if (Arrays.binarySearch(allForbidden, index) >= 0 && Arrays.binarySearch(from, index) < 0) { fromL.add(index); toL.add(generator.generate(IndicesUtils.getType(index))); } int[] _from = fromL.toArray(), _to = toL.toArray(); ArraysUtils.quickSort(_from, _to); return applyIndexMapping(tensor, new IndexMapper(_from, _to)); } private static Tensor applyIndexMapping(Tensor tensor, IndexMapper mapper) { TreeTraverseIterator iterator = new TreeTraverseIterator(tensor, TraverseGuide.EXCEPT_FUNCTIONS_AND_FIELDS); TraverseState state; SimpleIndices oldIndices, newIndices; SimpleTensor simpleTensor; while ((state = iterator.next()) != null) { if (state == TraverseState.Leaving) continue; if (!(iterator.current() instanceof SimpleTensor)) continue; simpleTensor = (SimpleTensor) iterator.current(); oldIndices = simpleTensor.getIndices(); newIndices = oldIndices.applyIndexMapping(mapper); if (oldIndices != newIndices) if (simpleTensor instanceof TensorField) iterator.set(UnsafeTensors.unsafeSetIndicesToField((TensorField) simpleTensor, newIndices)); else iterator.set(UnsafeTensors.unsafeSetIndicesToSimpleTensor(simpleTensor, newIndices)); } return iterator.result(); } private final static class IndexMapper implements IndexMapping { private final int[] from, to; public IndexMapper(int[] from, int[] to) { this.from = from; this.to = to; } @Override public int map(int index) { int position = Arrays.binarySearch(from, IndicesUtils.getNameWithType(index)); if (position < 0) return index; return IndicesUtils.getRawStateInt(index) ^ to[position]; } } }
true
true
public static Tensor unsafeApplyIndexMappingFromSortedClonedSource( Tensor tensor, int[] from, int[] to, int[] forbidden) { Set<Integer> dummyIndices = TensorUtils.getAllIndices(tensor); //extracting contracted only Indices indices = tensor.getIndices().getFreeIndices(); int i; for (i = indices.size() - 1; i >= 0; --i) dummyIndices.remove(IndicesUtils.getNameWithType(indices.get(i))); int[] allForbidden = new int[to.length + forbidden.length]; System.arraycopy(to, 0, allForbidden, 0, to.length); System.arraycopy(forbidden, 0, allForbidden, to.length, forbidden.length); for (i = allForbidden.length - 1; i >= 0; --i) allForbidden[i] = IndicesUtils.getNameWithType(allForbidden[i]); IntArrayList fromL = new IntArrayList(from.length), toL = new IntArrayList(to.length); fromL.addAll(from); toL.addAll(to); int[] forbiddenGeneratorIndices = new int[allForbidden.length + dummyIndices.size()]; System.arraycopy(allForbidden, 0, forbiddenGeneratorIndices, 0, allForbidden.length); i = allForbidden.length - 1; for (Integer index : dummyIndices) forbiddenGeneratorIndices[++i] = index; IndexGenerator generator = new IndexGenerator(forbiddenGeneratorIndices);//also sorts allForbidden array for (Integer index : dummyIndices) if (Arrays.binarySearch(allForbidden, index) >= 0 && Arrays.binarySearch(from, index) < 0) { fromL.add(index); toL.add(generator.generate(IndicesUtils.getType(index))); } int[] _from = fromL.toArray(), _to = toL.toArray(); ArraysUtils.quickSort(_from, _to); return applyIndexMapping(tensor, new IndexMapper(_from, _to)); }
public static Tensor unsafeApplyIndexMappingFromSortedClonedSource( Tensor tensor, int[] from, int[] to, int[] forbidden) { Set<Integer> dummyIndices = TensorUtils.getAllIndices(tensor); //extracting contracted only Indices indices = tensor.getIndices().getFreeIndices(); int i; for (i = indices.size() - 1; i >= 0; --i) dummyIndices.remove(IndicesUtils.getNameWithType(indices.get(i))); int[] allForbidden = new int[to.length + forbidden.length]; System.arraycopy(to, 0, allForbidden, 0, to.length); System.arraycopy(forbidden, 0, allForbidden, to.length, forbidden.length); for (i = allForbidden.length - 1; i >= 0; --i) allForbidden[i] = IndicesUtils.getNameWithType(allForbidden[i]); IntArrayList fromL = new IntArrayList(from.length), toL = new IntArrayList(to.length); fromL.addAll(from); toL.addAll(to); int[] forbiddenGeneratorIndices = new int[allForbidden.length + dummyIndices.size()]; System.arraycopy(allForbidden, 0, forbiddenGeneratorIndices, 0, allForbidden.length); i = allForbidden.length - 1; for (Integer index : dummyIndices) forbiddenGeneratorIndices[++i] = index; Arrays.sort(allForbidden); IndexGenerator generator = new IndexGenerator(forbiddenGeneratorIndices);//also sorts allForbidden array for (Integer index : dummyIndices) if (Arrays.binarySearch(allForbidden, index) >= 0 && Arrays.binarySearch(from, index) < 0) { fromL.add(index); toL.add(generator.generate(IndicesUtils.getType(index))); } int[] _from = fromL.toArray(), _to = toL.toArray(); ArraysUtils.quickSort(_from, _to); return applyIndexMapping(tensor, new IndexMapper(_from, _to)); }
diff --git a/java/src/org/jruby/jubilee/JubileeVerticle.java b/java/src/org/jruby/jubilee/JubileeVerticle.java index 80e6020..0019a24 100644 --- a/java/src/org/jruby/jubilee/JubileeVerticle.java +++ b/java/src/org/jruby/jubilee/JubileeVerticle.java @@ -1,67 +1,67 @@ package org.jruby.jubilee; import org.jruby.Ruby; import org.jruby.runtime.builtin.IRubyObject; import org.vertx.java.core.Handler; import org.vertx.java.core.http.HttpServer; import org.vertx.java.core.http.HttpServerRequest; import org.vertx.java.core.json.JsonArray; import org.vertx.java.core.json.JsonObject; import org.vertx.java.platform.Verticle; import org.vertx.java.platform.impl.WrappedVertx; import java.io.IOException; /** * Created by isaiah on 23/01/2014. */ public class JubileeVerticle extends Verticle { private Ruby ruby; @Override public void start() { JsonObject config = container.config(); HttpServer httpServer = vertx.createHttpServer(); ruby = config.getValue("ruby"); IRubyObject rackApplication; final RackApplication app; boolean ssl =config.getBoolean("ssl"); if (config.containsField("rackapp")) rackApplication = config.getValue("rackapp"); else { String rackup = config.getString("rackup"); String rackScript = "require 'rack'\n" + "require 'jubilee'\n" + "app, _ = Rack::Builder.parse_file('" + rackup + "')\n"; - if (config.containsField("quiet") && config.getString("environment").equals("development")) { + if (!config.getBoolean("quiet") && config.getString("environment").equals("development")) { rackScript += "logger = STDOUT\n" + - "Rack::CommonLogger.new(@app, logger)\n"; + "app = Rack::CommonLogger.new(app, logger)\n"; } rackScript += "Jubilee::Application.new(app)\n"; rackApplication = ruby.evalScriptlet(rackScript); } try { app = new RackApplication((WrappedVertx) vertx, ruby.getCurrentContext(), rackApplication, ssl); httpServer.setAcceptBacklog(10000); httpServer.requestHandler(new Handler<HttpServerRequest>() { public void handle(final HttpServerRequest req) { app.call(req); } }); if (config.containsField("event_bus")) { JsonArray allowAll = new JsonArray(); allowAll.add(new JsonObject()); vertx.createSockJSServer(httpServer).bridge(config.getObject("event_bus"), allowAll, allowAll); } if (ssl) httpServer.setSSL(true).setKeyStorePath(config.getString("keystore_path")) .setKeyStorePassword(config.getString("keystore_password")); httpServer.listen(config.getInteger("port"), config.getString("host")); } catch (IOException e) { container.logger().fatal("Failed to create RackApplication"); } } @Override public void stop() { this.ruby.tearDown(false); } }
false
true
public void start() { JsonObject config = container.config(); HttpServer httpServer = vertx.createHttpServer(); ruby = config.getValue("ruby"); IRubyObject rackApplication; final RackApplication app; boolean ssl =config.getBoolean("ssl"); if (config.containsField("rackapp")) rackApplication = config.getValue("rackapp"); else { String rackup = config.getString("rackup"); String rackScript = "require 'rack'\n" + "require 'jubilee'\n" + "app, _ = Rack::Builder.parse_file('" + rackup + "')\n"; if (config.containsField("quiet") && config.getString("environment").equals("development")) { rackScript += "logger = STDOUT\n" + "Rack::CommonLogger.new(@app, logger)\n"; } rackScript += "Jubilee::Application.new(app)\n"; rackApplication = ruby.evalScriptlet(rackScript); } try { app = new RackApplication((WrappedVertx) vertx, ruby.getCurrentContext(), rackApplication, ssl); httpServer.setAcceptBacklog(10000); httpServer.requestHandler(new Handler<HttpServerRequest>() { public void handle(final HttpServerRequest req) { app.call(req); } }); if (config.containsField("event_bus")) { JsonArray allowAll = new JsonArray(); allowAll.add(new JsonObject()); vertx.createSockJSServer(httpServer).bridge(config.getObject("event_bus"), allowAll, allowAll); } if (ssl) httpServer.setSSL(true).setKeyStorePath(config.getString("keystore_path")) .setKeyStorePassword(config.getString("keystore_password")); httpServer.listen(config.getInteger("port"), config.getString("host")); } catch (IOException e) { container.logger().fatal("Failed to create RackApplication"); } }
public void start() { JsonObject config = container.config(); HttpServer httpServer = vertx.createHttpServer(); ruby = config.getValue("ruby"); IRubyObject rackApplication; final RackApplication app; boolean ssl =config.getBoolean("ssl"); if (config.containsField("rackapp")) rackApplication = config.getValue("rackapp"); else { String rackup = config.getString("rackup"); String rackScript = "require 'rack'\n" + "require 'jubilee'\n" + "app, _ = Rack::Builder.parse_file('" + rackup + "')\n"; if (!config.getBoolean("quiet") && config.getString("environment").equals("development")) { rackScript += "logger = STDOUT\n" + "app = Rack::CommonLogger.new(app, logger)\n"; } rackScript += "Jubilee::Application.new(app)\n"; rackApplication = ruby.evalScriptlet(rackScript); } try { app = new RackApplication((WrappedVertx) vertx, ruby.getCurrentContext(), rackApplication, ssl); httpServer.setAcceptBacklog(10000); httpServer.requestHandler(new Handler<HttpServerRequest>() { public void handle(final HttpServerRequest req) { app.call(req); } }); if (config.containsField("event_bus")) { JsonArray allowAll = new JsonArray(); allowAll.add(new JsonObject()); vertx.createSockJSServer(httpServer).bridge(config.getObject("event_bus"), allowAll, allowAll); } if (ssl) httpServer.setSSL(true).setKeyStorePath(config.getString("keystore_path")) .setKeyStorePassword(config.getString("keystore_password")); httpServer.listen(config.getInteger("port"), config.getString("host")); } catch (IOException e) { container.logger().fatal("Failed to create RackApplication"); } }
diff --git a/git-server/src/jetbrains/buildServer/buildTriggers/vcs/git/GitServerUtil.java b/git-server/src/jetbrains/buildServer/buildTriggers/vcs/git/GitServerUtil.java index 29716f7..be8f566 100644 --- a/git-server/src/jetbrains/buildServer/buildTriggers/vcs/git/GitServerUtil.java +++ b/git-server/src/jetbrains/buildServer/buildTriggers/vcs/git/GitServerUtil.java @@ -1,134 +1,134 @@ /* * Copyright 2000-2010 JetBrains s.r.o. * * 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 jetbrains.buildServer.buildTriggers.vcs.git; import jetbrains.buildServer.vcs.VcsException; import org.eclipse.jgit.lib.*; import org.eclipse.jgit.transport.URIish; import java.io.File; /** * Utilities for server part of the plugin */ public class GitServerUtil { /** * Amount of characters displayed for in the display version of revision number */ public static final int DISPLAY_VERSION_AMOUNT = 40; /** * User name for the system user */ public static final String SYSTEM_USER = "[email protected]"; /** * Max size of cached file */ public static final int MAX_CACHED_FILE = 16 * 1024; /** * Ensures that a bare repository exists at the specified path. * If it does not, the directory is attempted to be created. * * @param dir the path to the directory to init * @param remote the remote URL * @return a connection to repository * @throws jetbrains.buildServer.vcs.VcsException if the there is a problem with accessing VCS */ public static Repository getRepository(File dir, URIish remote) throws VcsException { WindowCacheConfig cfg = new WindowCacheConfig(); cfg.setDeltaBaseCacheLimit(MAX_CACHED_FILE); WindowCache.reconfigure(cfg); if (dir.exists() && !dir.isDirectory()) { throw new VcsException("The specified path is not a directory: " + dir); } try { Repository r = new Repository(dir); if (!new File(dir, "config").exists()) { r.create(true); final RepositoryConfig config = r.getConfig(); config.setString("teamcity", null, "remote", remote.toString()); config.save(); } else { final RepositoryConfig config = r.getConfig(); final String existingRemote = config.getString("teamcity", null, "remote"); if (existingRemote != null && !remote.toString().equals(existingRemote)) { throw new VcsException( "The specified directory " + dir + " is already used for another remote " + existingRemote + - " and cannot be used for others. Please specify the other directory explicitly."); + " and cannot be used for others (" + remote.toString() + "). Please specify the other directory explicitly."); } } return r; } catch (Exception ex) { throw new VcsException("The repository at " + dir + " cannot be opened or created: " + ex, ex); } } /** * Make version from commit object * * @param c the commit object * @return the version string */ public static String makeVersion(Commit c) { return GitUtils.makeVersion(c.getCommitId().name(), c.getCommitter().getWhen().getTime()); } /** * Get user for the commit * * @param s the vcs root settings * @param c the commit * @return the user name */ public static String getUser(Settings s, Commit c) { final PersonIdent a = c.getAuthor(); switch (s.getUsernameStyle()) { case NAME: return a.getName(); case EMAIL: return a.getEmailAddress(); case FULL: return a.getName() + " <" + a.getEmailAddress() + ">"; case USERID: String email = a.getEmailAddress(); final int i = email.lastIndexOf("@"); return email.substring(0, i > 0 ? i : email.length()); default: throw new IllegalStateException("Unsupported username style: " + s.getUsernameStyle()); } } /** * Create display version for the commit * * @param c the commit to examine * @return the display version */ public static String displayVersion(Commit c) { return displayVersion(c.getCommitId().name()); } /** * Create display version for the commit * * @param version the version to examine * @return the display version */ public static String displayVersion(String version) { return version.substring(0, DISPLAY_VERSION_AMOUNT); } }
true
true
public static Repository getRepository(File dir, URIish remote) throws VcsException { WindowCacheConfig cfg = new WindowCacheConfig(); cfg.setDeltaBaseCacheLimit(MAX_CACHED_FILE); WindowCache.reconfigure(cfg); if (dir.exists() && !dir.isDirectory()) { throw new VcsException("The specified path is not a directory: " + dir); } try { Repository r = new Repository(dir); if (!new File(dir, "config").exists()) { r.create(true); final RepositoryConfig config = r.getConfig(); config.setString("teamcity", null, "remote", remote.toString()); config.save(); } else { final RepositoryConfig config = r.getConfig(); final String existingRemote = config.getString("teamcity", null, "remote"); if (existingRemote != null && !remote.toString().equals(existingRemote)) { throw new VcsException( "The specified directory " + dir + " is already used for another remote " + existingRemote + " and cannot be used for others. Please specify the other directory explicitly."); } } return r; } catch (Exception ex) { throw new VcsException("The repository at " + dir + " cannot be opened or created: " + ex, ex); } }
public static Repository getRepository(File dir, URIish remote) throws VcsException { WindowCacheConfig cfg = new WindowCacheConfig(); cfg.setDeltaBaseCacheLimit(MAX_CACHED_FILE); WindowCache.reconfigure(cfg); if (dir.exists() && !dir.isDirectory()) { throw new VcsException("The specified path is not a directory: " + dir); } try { Repository r = new Repository(dir); if (!new File(dir, "config").exists()) { r.create(true); final RepositoryConfig config = r.getConfig(); config.setString("teamcity", null, "remote", remote.toString()); config.save(); } else { final RepositoryConfig config = r.getConfig(); final String existingRemote = config.getString("teamcity", null, "remote"); if (existingRemote != null && !remote.toString().equals(existingRemote)) { throw new VcsException( "The specified directory " + dir + " is already used for another remote " + existingRemote + " and cannot be used for others (" + remote.toString() + "). Please specify the other directory explicitly."); } } return r; } catch (Exception ex) { throw new VcsException("The repository at " + dir + " cannot be opened or created: " + ex, ex); } }
diff --git a/NoItem/src/net/worldoftomorrow/nala/ni/Configuration.java b/NoItem/src/net/worldoftomorrow/nala/ni/Configuration.java index 383db8f..603cd8a 100644 --- a/NoItem/src/net/worldoftomorrow/nala/ni/Configuration.java +++ b/NoItem/src/net/worldoftomorrow/nala/ni/Configuration.java @@ -1,342 +1,342 @@ package net.worldoftomorrow.nala.ni; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.plugin.Plugin; public class Configuration { private Log log = new Log(); private Plugin plugin = null; Configuration(NoItem plugin){ this.plugin = plugin; } //Define the configuration name// private String config = "config.yml"; private OutputStream os = null; private File configFile = null; private PrintWriter writer = null; private static FileConfiguration conf = new YamlConfiguration(); private boolean loaded = false; //--------CONFIG DEFAULTS--------// private boolean eNotifyPlayer = true; private boolean eNotifyAdmins = true; private boolean eStopToolUse = true; private boolean eNotifyNoUse = true; private boolean eNotifyNoBrew = true; private boolean eNotifyNoHold = true; private boolean eNotifyNoWear = true; private boolean eStopCrafting = true; private boolean eStopItemPickup = true; private boolean eStopPotionBrew = true; private boolean eStopItemHold = true; private boolean eStopWear = true; private boolean ePerItemPermissions = true; private boolean eDebugging = false; private String ePluginChannel = "main"; private String ePlayerMessage = "This item (%i) is not allowed."; private String eAdminMessage = "Player %n tried to get item %i @ %x, %y, %z in the world %w."; private String eNoUseMessage = "You are not allowed to use this tool!"; private String eNoBrewMessage = "You are not allowed to brew that potion!"; private String eNoHoldMessage = "You are not allowed to hold that!"; private String eNoWearMessage = "You are not allowed to wear that!"; private List<String> eDisallowedItems = new ArrayList<String>(); private List<String> eDisallowedPotionRecipes = new ArrayList<String>(); private int configVersion = 5; //----METHODS----// public void load(){ if(!loaded){ this.makePluginDir(); if(!this.confExists()){ this.makeConfig(); } int ccv = plugin.getConfig().getInt("ConfigurationVersion"); if(ccv < configVersion){ //Update the configuration if it is old. if(ccv != 0){ //This check is to see if the configuration is blank, which would be bad to copy the options from. this.copyConfigOptions(); } try { os = new FileOutputStream(new File(plugin.getDataFolder(), config)); writer = new PrintWriter(os); this.writeConfig(writer); } catch (FileNotFoundException e) { e.printStackTrace(); } } configFile = new File(plugin.getDataFolder(), config); conf = YamlConfiguration.loadConfiguration(configFile); loaded = true; } else { configFile = new File(plugin.getDataFolder(), config); conf = YamlConfiguration.loadConfiguration(configFile); loaded = true; } } private void makePluginDir(){ if(!plugin.getDataFolder().exists()){ plugin.getDataFolder().mkdirs(); } } private void makeConfig(){ File conf = new File(plugin.getDataFolder(), config); if(!conf.exists()){ try { conf.createNewFile(); log.log("Empty configuration file has been created."); } catch (IOException e) { log.log("IOException: Could not create configuration..", e); } } } private boolean confExists(){ File conf = new File(plugin.getDataFolder(), config); return conf.exists(); } private void writeConfig(PrintWriter writer){ if(writer != null){ //----WRITE THE CONFIGURATION ONE LINE AT A TIME----// writer.println("# Notify Message Variables:"); writer.println("# %n = player name"); writer.println("# %i = item id"); writer.println("# %x = X location"); writer.println("# %y = Y location"); writer.println("# %z = Z location"); writer.println("# %w = world"); writer.println("Notify:"); writer.println(" Player: " + eNotifyPlayer); writer.println(" PlayerMessage: " + ePlayerMessage); writer.println(" Admins: " + eNotifyAdmins); writer.println(" AdminMessage: " + eAdminMessage); writer.println(" NoUse: " + eNotifyNoUse); writer.println(" NoUseMessage: " + eNoUseMessage); writer.println(" NoBrew: " + eNotifyNoBrew); writer.println(" NoBrewMessage: " + eNoBrewMessage); writer.println(" NoHold: " + eNotifyNoHold); writer.println(" NoHoldMessage: " + eNoHoldMessage); writer.println(" NoWear: " + eNotifyNoWear); - writer.println(" NoWearMessage:" + eNoWearMessage); + writer.println(" NoWearMessage: " + eNoWearMessage); writer.println(""); writer.println("# Blocked items list ( itemID:DamageValue ) "); writer.println("DisallowedItems:"); if(eDisallowedItems.isEmpty()){ writer.println(" - '5'"); writer.println(" - '5:1'"); writer.println(" - '5:2'"); } else { for(String item : eDisallowedItems){ writer.println(" - '" + item + "'"); } } writer.println(""); writer.println("# To block a potion, you must enter the damage value of the potion and ingredient needed."); writer.println("# Recipes can be found here: http://www.minecraftwiki.net/wiki/Brewing"); writer.println("# Here are a few potions:"); writer.println(""); writer.println("# Water Bottle - 0"); writer.println("# Awkward Potion - 16"); writer.println("# Thick Potion - 32"); writer.println("# Mundane Potion (Extended) - 64"); writer.println("# Mundane Potion - 8192"); writer.println("# Potion of Regeneration (2:00) - 8193"); writer.println("# Potion of Regeneration (8:00) - 8257"); writer.println("# Potion of Regeneration II - 8225"); writer.println("# Potion of Swiftness(3:00) - 8194"); writer.println("# Potion of Swiftness (8:00) - 8258"); writer.println("# Potion of Swiftness II - 8226"); writer.println("# Potion of Fire Resistance (3:00) - 8195"); writer.println("# Potion of Fire Resistance (8:00) - 8259"); writer.println("# Potion of Fire Resistance (reverted) - 8227"); writer.println(""); writer.println("# The rest can be found here: http://www.minecraftwiki.net/wiki/Potions#Base_Potions"); writer.println(""); writer.println("# Here are are the Ingredients:"); writer.println(""); writer.println("# Nether Wart - 372"); writer.println("# Glowstone Dust - 348"); writer.println("# Redstone Dust - 331"); writer.println("# Fermented Spider Eye - 376"); writer.println("# Magma Cream - 378"); writer.println("# Sugar - 353"); writer.println("# Glistering Melon - 382"); writer.println("# Spider Eye - 375"); writer.println("# Ghast Tear - 370"); writer.println("# Blaze Powder - 377"); writer.println("# Gun Powder - 289"); writer.println(""); writer.println("# Default example is 0:372 which would block the Awkward Potion"); writer.println("DisallowedPotionRecipes:"); if(eDisallowedPotionRecipes.isEmpty()){ writer.println(" - '0:372'"); } else { for(String recipe : eDisallowedPotionRecipes){ writer.println(" - '" + recipe + "'"); } } writer.println(""); writer.println("#Use these to turn off individual features"); writer.println("StopCrafting: " + eStopCrafting); writer.println("StopItemPickup: " + eStopItemPickup); writer.println("StopPotionBrew: " + eStopPotionBrew); writer.println("StopToolUse: " + eStopToolUse); writer.println("StopItemHold: " + eStopItemHold); writer.println("StopArmourWear: " + eStopWear); writer.println(""); writer.println("# Permissions:"); writer.println("# 'noitem.nocraft.<item#>[.datavalue]' or"); writer.println("# 'noitem.nopickup.<item#>[.datavalue]' or"); writer.println("# 'noitem.nobrew.<potionDV>.<IngredientID>'"); writer.println("# 'noitem.nouse.<tool# OR toolname>' (i.e. noitem.nouse.diamondaxe)"); writer.println("# 'noitem.allitems' overrides ALL ( DisallowedItems and PerItemPermissions )"); writer.println("PerItemPermissions: " + ePerItemPermissions); writer.println(""); writer.println("#Don't turn this on unless you like getting spammed with messages!"); writer.println("Debugging: " + eDebugging); writer.println(""); writer.println("# This is to change whether you recieve update notifications"); writer.println("# for recommended builds or for development builds. (main/dev)"); writer.println("PluginChannel: " + ePluginChannel); writer.println(""); writer.println("ConfigurationVersion: " + configVersion); writer.close(); } } private void copyConfigOptions(){ configFile = new File(plugin.getDataFolder(), config); conf = YamlConfiguration.loadConfiguration(configFile); //--------SET CONFIG OPTIONS TO WHAT SERVER HAS SELECTED--------// this.eNotifyPlayer = conf.getBoolean("Notify.Player"); this.eNotifyAdmins = conf.getBoolean("Notify.Admins"); this.eStopCrafting = conf.getBoolean("StopCrafting"); this.eStopItemPickup = conf.getBoolean("StopItemPickup"); this.eStopPotionBrew = conf.getBoolean("StopPotionBrew"); this.eStopItemHold = conf.getBoolean("StopItemHold"); this.ePerItemPermissions = conf.getBoolean("PerItemPermissions"); this.eDebugging = conf.getBoolean("Debugging"); this.eStopToolUse = conf.getBoolean("StopToolUse"); this.eNotifyNoUse = conf.getBoolean("Notify.NoUse"); this.eNotifyNoBrew = conf.getBoolean("Notify.NoBrew"); this.eNoBrewMessage = conf.getString("Notify.NoBrewMessage"); if(configVersion >= 4){ this.ePluginChannel = conf.getString("PluginChannel"); } if(configVersion >= 5){ this.eStopWear = conf.getBoolean("StopArmourWear"); this.eNoWearMessage = conf.getString("Notify.NoWearMessage"); this.eNotifyNoWear = conf.getBoolean("Notify.NoWear"); } this.ePlayerMessage = conf.getString("Notify.PlayerMessage"); this.eAdminMessage = conf.getString("Notify.AdminMessage"); this.eNoUseMessage = conf.getString("Notify.NoUseMessage"); this.eDisallowedItems = conf.getStringList("DisallowedItems"); this.eDisallowedPotionRecipes = conf.getStringList("DisallowedPotionRecipes"); } //----GETTERS----// //Notify// public static boolean notifyPlayer(){ return Configuration.conf.getBoolean("Notify.Player"); } public static boolean notifyAdmins(){ return Configuration.conf.getBoolean("Notify.Admins"); } public static boolean notifyNoUse(){ return Configuration.conf.getBoolean("Notify.NoUse"); } public static boolean notifyNoBrew(){ return Configuration.conf.getBoolean("Notify.NoBrew"); } public static boolean notifyNoHold(){ return Configuration.conf.getBoolean("Notify.NoHold"); } public static boolean notfiyNoWear(){ return Configuration.conf.getBoolean("Notify.NoWear"); } //Stop// public static boolean stopCrafting(){ return Configuration.conf.getBoolean("StopCrafting"); } public static boolean stopItemPickup(){ return Configuration.conf.getBoolean("StopItemPickup"); } public static boolean stopPotionBrew(){ return Configuration.conf.getBoolean("StopPotionBrew"); } public static boolean stopToolUse(){ return Configuration.conf.getBoolean("StopToolUse"); } public static boolean stopItemHold(){ return Configuration.conf.getBoolean("StopItemHold"); } public static boolean stopArmourWear(){ return Configuration.conf.getBoolean("StopArmourWear"); } //Misc// public static boolean debugging(){ return Configuration.conf.getBoolean("Debugging"); } public static boolean perItemPerms(){ return Configuration.conf.getBoolean("PerItemPermissions"); } public static String pluginChannel(){ return Configuration.conf.getString("PluginChannel"); } //Message// public static String playerMessage(){ return Configuration.conf.getString("Notify.PlayerMessage"); } public static String adminMessage(){ return Configuration.conf.getString("Notify.AdminMessage"); } public static String noUseMessage(){ return Configuration.conf.getString("Notify.NoUseMessage"); } public static String noBrewMessage(){ return Configuration.conf.getString("Notify.NoBrewMessage"); } public static String noHoldMessage(){ return Configuration.conf.getString("Notify.NoHoldMessage"); } public static String noWearMessage(){ return Configuration.conf.getString("Notify.NoWearMessage"); } //Lists// public static List<String> disallowedItems(){ return Configuration.conf.getStringList("DisallowedItems"); } public static List<String> disallowedPotions(){ return Configuration.conf.getStringList("DisallowedPotionRecipes"); } }
true
true
private void writeConfig(PrintWriter writer){ if(writer != null){ //----WRITE THE CONFIGURATION ONE LINE AT A TIME----// writer.println("# Notify Message Variables:"); writer.println("# %n = player name"); writer.println("# %i = item id"); writer.println("# %x = X location"); writer.println("# %y = Y location"); writer.println("# %z = Z location"); writer.println("# %w = world"); writer.println("Notify:"); writer.println(" Player: " + eNotifyPlayer); writer.println(" PlayerMessage: " + ePlayerMessage); writer.println(" Admins: " + eNotifyAdmins); writer.println(" AdminMessage: " + eAdminMessage); writer.println(" NoUse: " + eNotifyNoUse); writer.println(" NoUseMessage: " + eNoUseMessage); writer.println(" NoBrew: " + eNotifyNoBrew); writer.println(" NoBrewMessage: " + eNoBrewMessage); writer.println(" NoHold: " + eNotifyNoHold); writer.println(" NoHoldMessage: " + eNoHoldMessage); writer.println(" NoWear: " + eNotifyNoWear); writer.println(" NoWearMessage:" + eNoWearMessage); writer.println(""); writer.println("# Blocked items list ( itemID:DamageValue ) "); writer.println("DisallowedItems:"); if(eDisallowedItems.isEmpty()){ writer.println(" - '5'"); writer.println(" - '5:1'"); writer.println(" - '5:2'"); } else { for(String item : eDisallowedItems){ writer.println(" - '" + item + "'"); } } writer.println(""); writer.println("# To block a potion, you must enter the damage value of the potion and ingredient needed."); writer.println("# Recipes can be found here: http://www.minecraftwiki.net/wiki/Brewing"); writer.println("# Here are a few potions:"); writer.println(""); writer.println("# Water Bottle - 0"); writer.println("# Awkward Potion - 16"); writer.println("# Thick Potion - 32"); writer.println("# Mundane Potion (Extended) - 64"); writer.println("# Mundane Potion - 8192"); writer.println("# Potion of Regeneration (2:00) - 8193"); writer.println("# Potion of Regeneration (8:00) - 8257"); writer.println("# Potion of Regeneration II - 8225"); writer.println("# Potion of Swiftness(3:00) - 8194"); writer.println("# Potion of Swiftness (8:00) - 8258"); writer.println("# Potion of Swiftness II - 8226"); writer.println("# Potion of Fire Resistance (3:00) - 8195"); writer.println("# Potion of Fire Resistance (8:00) - 8259"); writer.println("# Potion of Fire Resistance (reverted) - 8227"); writer.println(""); writer.println("# The rest can be found here: http://www.minecraftwiki.net/wiki/Potions#Base_Potions"); writer.println(""); writer.println("# Here are are the Ingredients:"); writer.println(""); writer.println("# Nether Wart - 372"); writer.println("# Glowstone Dust - 348"); writer.println("# Redstone Dust - 331"); writer.println("# Fermented Spider Eye - 376"); writer.println("# Magma Cream - 378"); writer.println("# Sugar - 353"); writer.println("# Glistering Melon - 382"); writer.println("# Spider Eye - 375"); writer.println("# Ghast Tear - 370"); writer.println("# Blaze Powder - 377"); writer.println("# Gun Powder - 289"); writer.println(""); writer.println("# Default example is 0:372 which would block the Awkward Potion"); writer.println("DisallowedPotionRecipes:"); if(eDisallowedPotionRecipes.isEmpty()){ writer.println(" - '0:372'"); } else { for(String recipe : eDisallowedPotionRecipes){ writer.println(" - '" + recipe + "'"); } } writer.println(""); writer.println("#Use these to turn off individual features"); writer.println("StopCrafting: " + eStopCrafting); writer.println("StopItemPickup: " + eStopItemPickup); writer.println("StopPotionBrew: " + eStopPotionBrew); writer.println("StopToolUse: " + eStopToolUse); writer.println("StopItemHold: " + eStopItemHold); writer.println("StopArmourWear: " + eStopWear); writer.println(""); writer.println("# Permissions:"); writer.println("# 'noitem.nocraft.<item#>[.datavalue]' or"); writer.println("# 'noitem.nopickup.<item#>[.datavalue]' or"); writer.println("# 'noitem.nobrew.<potionDV>.<IngredientID>'"); writer.println("# 'noitem.nouse.<tool# OR toolname>' (i.e. noitem.nouse.diamondaxe)"); writer.println("# 'noitem.allitems' overrides ALL ( DisallowedItems and PerItemPermissions )"); writer.println("PerItemPermissions: " + ePerItemPermissions); writer.println(""); writer.println("#Don't turn this on unless you like getting spammed with messages!"); writer.println("Debugging: " + eDebugging); writer.println(""); writer.println("# This is to change whether you recieve update notifications"); writer.println("# for recommended builds or for development builds. (main/dev)"); writer.println("PluginChannel: " + ePluginChannel); writer.println(""); writer.println("ConfigurationVersion: " + configVersion); writer.close(); } }
private void writeConfig(PrintWriter writer){ if(writer != null){ //----WRITE THE CONFIGURATION ONE LINE AT A TIME----// writer.println("# Notify Message Variables:"); writer.println("# %n = player name"); writer.println("# %i = item id"); writer.println("# %x = X location"); writer.println("# %y = Y location"); writer.println("# %z = Z location"); writer.println("# %w = world"); writer.println("Notify:"); writer.println(" Player: " + eNotifyPlayer); writer.println(" PlayerMessage: " + ePlayerMessage); writer.println(" Admins: " + eNotifyAdmins); writer.println(" AdminMessage: " + eAdminMessage); writer.println(" NoUse: " + eNotifyNoUse); writer.println(" NoUseMessage: " + eNoUseMessage); writer.println(" NoBrew: " + eNotifyNoBrew); writer.println(" NoBrewMessage: " + eNoBrewMessage); writer.println(" NoHold: " + eNotifyNoHold); writer.println(" NoHoldMessage: " + eNoHoldMessage); writer.println(" NoWear: " + eNotifyNoWear); writer.println(" NoWearMessage: " + eNoWearMessage); writer.println(""); writer.println("# Blocked items list ( itemID:DamageValue ) "); writer.println("DisallowedItems:"); if(eDisallowedItems.isEmpty()){ writer.println(" - '5'"); writer.println(" - '5:1'"); writer.println(" - '5:2'"); } else { for(String item : eDisallowedItems){ writer.println(" - '" + item + "'"); } } writer.println(""); writer.println("# To block a potion, you must enter the damage value of the potion and ingredient needed."); writer.println("# Recipes can be found here: http://www.minecraftwiki.net/wiki/Brewing"); writer.println("# Here are a few potions:"); writer.println(""); writer.println("# Water Bottle - 0"); writer.println("# Awkward Potion - 16"); writer.println("# Thick Potion - 32"); writer.println("# Mundane Potion (Extended) - 64"); writer.println("# Mundane Potion - 8192"); writer.println("# Potion of Regeneration (2:00) - 8193"); writer.println("# Potion of Regeneration (8:00) - 8257"); writer.println("# Potion of Regeneration II - 8225"); writer.println("# Potion of Swiftness(3:00) - 8194"); writer.println("# Potion of Swiftness (8:00) - 8258"); writer.println("# Potion of Swiftness II - 8226"); writer.println("# Potion of Fire Resistance (3:00) - 8195"); writer.println("# Potion of Fire Resistance (8:00) - 8259"); writer.println("# Potion of Fire Resistance (reverted) - 8227"); writer.println(""); writer.println("# The rest can be found here: http://www.minecraftwiki.net/wiki/Potions#Base_Potions"); writer.println(""); writer.println("# Here are are the Ingredients:"); writer.println(""); writer.println("# Nether Wart - 372"); writer.println("# Glowstone Dust - 348"); writer.println("# Redstone Dust - 331"); writer.println("# Fermented Spider Eye - 376"); writer.println("# Magma Cream - 378"); writer.println("# Sugar - 353"); writer.println("# Glistering Melon - 382"); writer.println("# Spider Eye - 375"); writer.println("# Ghast Tear - 370"); writer.println("# Blaze Powder - 377"); writer.println("# Gun Powder - 289"); writer.println(""); writer.println("# Default example is 0:372 which would block the Awkward Potion"); writer.println("DisallowedPotionRecipes:"); if(eDisallowedPotionRecipes.isEmpty()){ writer.println(" - '0:372'"); } else { for(String recipe : eDisallowedPotionRecipes){ writer.println(" - '" + recipe + "'"); } } writer.println(""); writer.println("#Use these to turn off individual features"); writer.println("StopCrafting: " + eStopCrafting); writer.println("StopItemPickup: " + eStopItemPickup); writer.println("StopPotionBrew: " + eStopPotionBrew); writer.println("StopToolUse: " + eStopToolUse); writer.println("StopItemHold: " + eStopItemHold); writer.println("StopArmourWear: " + eStopWear); writer.println(""); writer.println("# Permissions:"); writer.println("# 'noitem.nocraft.<item#>[.datavalue]' or"); writer.println("# 'noitem.nopickup.<item#>[.datavalue]' or"); writer.println("# 'noitem.nobrew.<potionDV>.<IngredientID>'"); writer.println("# 'noitem.nouse.<tool# OR toolname>' (i.e. noitem.nouse.diamondaxe)"); writer.println("# 'noitem.allitems' overrides ALL ( DisallowedItems and PerItemPermissions )"); writer.println("PerItemPermissions: " + ePerItemPermissions); writer.println(""); writer.println("#Don't turn this on unless you like getting spammed with messages!"); writer.println("Debugging: " + eDebugging); writer.println(""); writer.println("# This is to change whether you recieve update notifications"); writer.println("# for recommended builds or for development builds. (main/dev)"); writer.println("PluginChannel: " + ePluginChannel); writer.println(""); writer.println("ConfigurationVersion: " + configVersion); writer.close(); } }
diff --git a/src/org/apache/xerces/impl/xs/traversers/XSDAttributeTraverser.java b/src/org/apache/xerces/impl/xs/traversers/XSDAttributeTraverser.java index 73bd5fdbc..4109dce8e 100644 --- a/src/org/apache/xerces/impl/xs/traversers/XSDAttributeTraverser.java +++ b/src/org/apache/xerces/impl/xs/traversers/XSDAttributeTraverser.java @@ -1,440 +1,440 @@ /* * The Apache Software License, Version 1.1 * * * Copyright (c) 2001, 2002 The Apache Software Foundation. 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. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 2001, International * Business Machines, Inc., http://www.apache.org. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ package org.apache.xerces.impl.xs.traversers; import org.apache.xerces.impl.dv.XSSimpleType; import org.apache.xerces.impl.dv.ValidatedInfo; import org.apache.xerces.impl.dv.InvalidDatatypeValueException; import org.apache.xerces.impl.validation.ValidationContext; import org.apache.xerces.util.SymbolTable; import org.apache.xerces.impl.xs.SchemaGrammar; import org.apache.xerces.impl.xs.SchemaSymbols; import org.apache.xerces.impl.xs.XSAttributeDecl; import org.apache.xerces.impl.xs.XSAttributeUse; import org.apache.xerces.impl.xs.XSElementDecl; import org.apache.xerces.impl.xs.XSTypeDecl; import org.apache.xerces.xni.QName; import org.apache.xerces.util.DOMUtil; import org.apache.xerces.util.SymbolTable; import org.apache.xerces.impl.xs.util.XInt; import org.apache.xerces.impl.validation.ValidationState; import org.w3c.dom.Element; /** * The attribute declaration schema component traverser. * * <attribute * default = string * fixed = string * form = (qualified | unqualified) * id = ID * name = NCName * ref = QName * type = QName * use = (optional | prohibited | required) : optional * {any attributes with non-schema namespace . . .}> * Content: (annotation?, (simpleType?)) * </attribute> * * @author Sandy Gao, IBM * @author Neeraj Bajaj, Sun Microsystems, inc. * @version $Id$ */ class XSDAttributeTraverser extends XSDAbstractTraverser { public XSDAttributeTraverser (XSDHandler handler, XSAttributeChecker gAttrCheck) { super(handler, gAttrCheck); } protected XSAttributeUse traverseLocal(Element attrDecl, XSDocumentInfo schemaDoc, SchemaGrammar grammar) { // General Attribute Checking Object[] attrValues = fAttrChecker.checkAttributes(attrDecl, false, schemaDoc); String defaultAtt = (String) attrValues[XSAttributeChecker.ATTIDX_DEFAULT]; String fixedAtt = (String) attrValues[XSAttributeChecker.ATTIDX_FIXED]; String nameAtt = (String) attrValues[XSAttributeChecker.ATTIDX_NAME]; QName refAtt = (QName) attrValues[XSAttributeChecker.ATTIDX_REF]; XInt useAtt = (XInt) attrValues[XSAttributeChecker.ATTIDX_USE]; // get 'attribute declaration' XSAttributeDecl attribute = null; if (attrDecl.getAttributeNode(SchemaSymbols.ATT_REF) != null) { if (refAtt != null) { attribute = (XSAttributeDecl)fSchemaHandler.getGlobalDecl(schemaDoc, XSDHandler.ATTRIBUTE_TYPE, refAtt, attrDecl); Element child = DOMUtil.getFirstChildElement(attrDecl); if (child != null && DOMUtil.getLocalName(child).equals(SchemaSymbols.ELT_ANNOTATION)) { traverseAnnotationDecl(child, attrValues, false, schemaDoc); child = DOMUtil.getNextSiblingElement(child); } if (child != null) { reportSchemaError("src-attribute.3.2", new Object[]{refAtt}, child); } // for error reporting nameAtt = refAtt.localpart; } else { attribute = null; } } else { attribute = traverseNamedAttr(attrDecl, attrValues, schemaDoc, grammar, false); } // get 'value constraint' short consType = XSAttributeDecl.NO_CONSTRAINT; if (defaultAtt != null) { consType = XSAttributeDecl.DEFAULT_VALUE; } else if (fixedAtt != null) { consType = XSAttributeDecl.FIXED_VALUE; defaultAtt = fixedAtt; fixedAtt = null; } XSAttributeUse attrUse = null; if (attribute != null) { if (fSchemaHandler.fDeclPool !=null) { attrUse = fSchemaHandler.fDeclPool.getAttributeUse(); } else { attrUse = new XSAttributeUse(); } attrUse.fAttrDecl = attribute; attrUse.fUse = useAtt.shortValue(); attrUse.fConstraintType = consType; if (defaultAtt != null) { attrUse.fDefault = new ValidatedInfo(); attrUse.fDefault.normalizedValue = defaultAtt; } } fAttrChecker.returnAttrArray(attrValues, schemaDoc); //src-attribute // 1 default and fixed must not both be present. if (defaultAtt != null && fixedAtt != null) { reportSchemaError("src-attribute.1", new Object[]{nameAtt}, attrDecl); } // 2 If default and use are both present, use must have the actual value optional. if (consType == XSAttributeDecl.DEFAULT_VALUE && useAtt != null && useAtt.intValue() != SchemaSymbols.USE_OPTIONAL) { reportSchemaError("src-attribute.2", new Object[]{nameAtt}, attrDecl); } // a-props-correct if (defaultAtt != null && attrUse != null) { // 2 if there is a {value constraint}, the canonical lexical representation of its value must be valid with respect to the {type definition} as defined in String Valid (3.14.4). fValidationState.setNamespaceSupport(schemaDoc.fNamespaceSupport); if (!checkDefaultValid(attrUse)) { reportSchemaError ("a-props-correct.2", new Object[]{nameAtt, defaultAtt}, attrDecl); } // 3 If the {type definition} is or is derived from ID then there must not be a {value constraint}. if (attribute.fType.isIDType() ) { reportSchemaError ("a-props-correct.3", new Object[]{nameAtt}, attrDecl); } // check 3.5.6 constraint // Attribute Use Correct // 2 If the {attribute declaration} has a fixed {value constraint}, then if the attribute use itself has a {value constraint}, it must also be fixed and its value must match that of the {attribute declaration}'s {value constraint}. if (attrUse.fAttrDecl.getConstraintType() == XSAttributeDecl.FIXED_VALUE && attrUse.fConstraintType != XSAttributeDecl.NO_CONSTRAINT) { if (attrUse.fConstraintType != XSAttributeDecl.FIXED_VALUE || - attrUse.fAttrDecl.fType.isEqual(attrUse.fAttrDecl.fDefault.actualValue, - attrUse.fDefault.actualValue)) { + !attrUse.fAttrDecl.fType.isEqual(attrUse.fAttrDecl.fDefault.actualValue, + attrUse.fDefault.actualValue)) { reportSchemaError ("au-props-correct.2", new Object[]{nameAtt}, attrDecl); } } } return attrUse; } protected XSAttributeDecl traverseGlobal(Element attrDecl, XSDocumentInfo schemaDoc, SchemaGrammar grammar) { // General Attribute Checking Object[] attrValues = fAttrChecker.checkAttributes(attrDecl, true, schemaDoc); XSAttributeDecl attribute = traverseNamedAttr(attrDecl, attrValues, schemaDoc, grammar, true); fAttrChecker.returnAttrArray(attrValues, schemaDoc); if (attribute != null) attribute.setIsGlobal(); return attribute; } /** * Traverse a globally declared attribute. * * @param attrDecl * @param attrValues * @param schemaDoc * @param grammar * @param isGlobal * @return the attribute declaration index */ XSAttributeDecl traverseNamedAttr(Element attrDecl, Object[] attrValues, XSDocumentInfo schemaDoc, SchemaGrammar grammar, boolean isGlobal) { String defaultAtt = (String) attrValues[XSAttributeChecker.ATTIDX_DEFAULT]; String fixedAtt = (String) attrValues[XSAttributeChecker.ATTIDX_FIXED]; XInt formAtt = (XInt) attrValues[XSAttributeChecker.ATTIDX_FORM]; String nameAtt = (String) attrValues[XSAttributeChecker.ATTIDX_NAME]; QName typeAtt = (QName) attrValues[XSAttributeChecker.ATTIDX_TYPE]; // Step 1: get declaration information XSAttributeDecl attribute = null; if (fSchemaHandler.fDeclPool !=null) { attribute = fSchemaHandler.fDeclPool.getAttributeDecl(); } else { attribute = new XSAttributeDecl(); } // get 'name' if (nameAtt != null) attribute.fName = fSymbolTable.addSymbol(nameAtt); // get 'target namespace' if (isGlobal) { attribute.fTargetNamespace = schemaDoc.fTargetNamespace; } else if (formAtt != null) { if (formAtt.intValue() == SchemaSymbols.FORM_QUALIFIED) attribute.fTargetNamespace = schemaDoc.fTargetNamespace; else attribute.fTargetNamespace = null; } else if (schemaDoc.fAreLocalAttributesQualified) { attribute.fTargetNamespace = schemaDoc.fTargetNamespace; } else { attribute.fTargetNamespace = null; } // get 'value constraint' // for local named attribute, value constraint is absent if (isGlobal) { if (fixedAtt != null) { attribute.fDefault = new ValidatedInfo(); attribute.fDefault.normalizedValue = fixedAtt; attribute.setConstraintType(XSElementDecl.FIXED_VALUE); } else if (defaultAtt != null) { attribute.fDefault = new ValidatedInfo(); attribute.fDefault.normalizedValue = defaultAtt; attribute.setConstraintType(XSElementDecl.DEFAULT_VALUE); } else { attribute.setConstraintType(XSElementDecl.NO_CONSTRAINT); } } // get 'annotation' Element child = DOMUtil.getFirstChildElement(attrDecl); if (child != null && DOMUtil.getLocalName(child).equals(SchemaSymbols.ELT_ANNOTATION)) { traverseAnnotationDecl(child, attrValues, false, schemaDoc); child = DOMUtil.getNextSiblingElement(child); } // get 'type definition' XSSimpleType attrType = null; boolean haveAnonType = false; // Handle Anonymous type if there is one if (child != null) { String childName = DOMUtil.getLocalName(child); if (childName.equals(SchemaSymbols.ELT_SIMPLETYPE)) { attrType = fSchemaHandler.fSimpleTypeTraverser.traverseLocal(child, schemaDoc, grammar); haveAnonType = true; child = DOMUtil.getNextSiblingElement(child); } } // Handler type attribute if (attrType == null && typeAtt != null) { XSTypeDecl type = (XSTypeDecl)fSchemaHandler.getGlobalDecl(schemaDoc, XSDHandler.TYPEDECL_TYPE, typeAtt, attrDecl); if (type != null && type.getXSType() == XSTypeDecl.SIMPLE_TYPE) attrType = (XSSimpleType)type; else reportSchemaError("src-resolve", new Object[]{typeAtt.rawname, "simpleType definition"}, attrDecl); } if (attrType == null) { attrType = SchemaGrammar.fAnySimpleType; } attribute.fType = attrType; // Step 2: register attribute decl to the grammar if (isGlobal && nameAtt != null) grammar.addGlobalAttributeDecl(attribute); // Step 3: check against schema for schemas // required attributes if (nameAtt == null) { if (isGlobal) reportSchemaError("s4s-att-must-appear", new Object[]{SchemaSymbols.ELT_ATTRIBUTE, SchemaSymbols.ATT_NAME}, attrDecl); else reportSchemaError("src-attribute.3.1", null, attrDecl); nameAtt = NO_NAME; } // element if (child != null) { reportSchemaError("s4s-elt-must-match", new Object[]{nameAtt, "(annotation?, (simpleType?))"}, child); } // Step 4: check 3.2.3 constraints // src-attribute // 1 default and fixed must not both be present. if (defaultAtt != null && fixedAtt != null) { reportSchemaError("src-attribute.1", new Object[]{nameAtt}, attrDecl); } // 2 If default and use are both present, use must have the actual value optional. // This is checked in "traverse" method // 3 If the item's parent is not <schema>, then all of the following must be true: // 3.1 One of ref or name must be present, but not both. // This is checked in XSAttributeChecker // 3.2 If ref is present, then all of <simpleType>, form and type must be absent. // Attributes are checked in XSAttributeChecker, elements are checked in "traverse" method // 4 type and <simpleType> must not both be present. if (haveAnonType && (typeAtt != null)) { reportSchemaError( "src-attribute.4", new Object[]{nameAtt}, attrDecl); } // Step 5: check 3.2.6 constraints // check for NOTATION type checkNotationType(nameAtt, attrType, attrDecl); // a-props-correct // 2 if there is a {value constraint}, the canonical lexical representation of its value must be valid with respect to the {type definition} as defined in String Valid (3.14.4). if (attribute.fDefault != null) { fValidationState.setNamespaceSupport(schemaDoc.fNamespaceSupport); if (!checkDefaultValid(attribute)) { reportSchemaError ("a-props-correct.2", new Object[]{nameAtt, defaultAtt}, attrDecl); } } // 3 If the {type definition} is or is derived from ID then there must not be a {value constraint}. if (attribute.fDefault != null) { if (attrType.isIDType() ) { reportSchemaError ("a-props-correct.3", new Object[]{nameAtt}, attrDecl); } } // no-xmlns // The {name} of an attribute declaration must not match xmlns. if (nameAtt != null && nameAtt.equals(SchemaSymbols.XMLNS)) { reportSchemaError("no-xmlns", null, attrDecl); } // no-xsi // The {target namespace} of an attribute declaration, whether local or top-level, must not match http://www.w3.org/2001/XMLSchema-instance (unless it is one of the four built-in declarations given in the next section). if (attribute.fTargetNamespace != null && attribute.fTargetNamespace.equals(SchemaSymbols.URI_XSI)) { reportSchemaError("no-xsi", new Object[]{SchemaSymbols.URI_XSI}, attrDecl); } return attribute; } // return whether the constraint value is valid for the given type boolean checkDefaultValid(XSAttributeDecl attribute) { boolean ret = true; try { //set the actual value attribute.fType.validate(attribute.fDefault.normalizedValue, fValidationState, attribute.fDefault); } catch (InvalidDatatypeValueException ide) { ret = false; } return ret; } // return whether the constraint value is valid for the given type boolean checkDefaultValid(XSAttributeUse attrUse) { boolean ret = true; try { //set the actual value attrUse.fAttrDecl.fType.validate(attrUse.fDefault.normalizedValue, fValidationState, attrUse.fDefault); } catch (InvalidDatatypeValueException ide) { ret = false; } return ret; } }
true
true
protected XSAttributeUse traverseLocal(Element attrDecl, XSDocumentInfo schemaDoc, SchemaGrammar grammar) { // General Attribute Checking Object[] attrValues = fAttrChecker.checkAttributes(attrDecl, false, schemaDoc); String defaultAtt = (String) attrValues[XSAttributeChecker.ATTIDX_DEFAULT]; String fixedAtt = (String) attrValues[XSAttributeChecker.ATTIDX_FIXED]; String nameAtt = (String) attrValues[XSAttributeChecker.ATTIDX_NAME]; QName refAtt = (QName) attrValues[XSAttributeChecker.ATTIDX_REF]; XInt useAtt = (XInt) attrValues[XSAttributeChecker.ATTIDX_USE]; // get 'attribute declaration' XSAttributeDecl attribute = null; if (attrDecl.getAttributeNode(SchemaSymbols.ATT_REF) != null) { if (refAtt != null) { attribute = (XSAttributeDecl)fSchemaHandler.getGlobalDecl(schemaDoc, XSDHandler.ATTRIBUTE_TYPE, refAtt, attrDecl); Element child = DOMUtil.getFirstChildElement(attrDecl); if (child != null && DOMUtil.getLocalName(child).equals(SchemaSymbols.ELT_ANNOTATION)) { traverseAnnotationDecl(child, attrValues, false, schemaDoc); child = DOMUtil.getNextSiblingElement(child); } if (child != null) { reportSchemaError("src-attribute.3.2", new Object[]{refAtt}, child); } // for error reporting nameAtt = refAtt.localpart; } else { attribute = null; } } else { attribute = traverseNamedAttr(attrDecl, attrValues, schemaDoc, grammar, false); } // get 'value constraint' short consType = XSAttributeDecl.NO_CONSTRAINT; if (defaultAtt != null) { consType = XSAttributeDecl.DEFAULT_VALUE; } else if (fixedAtt != null) { consType = XSAttributeDecl.FIXED_VALUE; defaultAtt = fixedAtt; fixedAtt = null; } XSAttributeUse attrUse = null; if (attribute != null) { if (fSchemaHandler.fDeclPool !=null) { attrUse = fSchemaHandler.fDeclPool.getAttributeUse(); } else { attrUse = new XSAttributeUse(); } attrUse.fAttrDecl = attribute; attrUse.fUse = useAtt.shortValue(); attrUse.fConstraintType = consType; if (defaultAtt != null) { attrUse.fDefault = new ValidatedInfo(); attrUse.fDefault.normalizedValue = defaultAtt; } } fAttrChecker.returnAttrArray(attrValues, schemaDoc); //src-attribute // 1 default and fixed must not both be present. if (defaultAtt != null && fixedAtt != null) { reportSchemaError("src-attribute.1", new Object[]{nameAtt}, attrDecl); } // 2 If default and use are both present, use must have the actual value optional. if (consType == XSAttributeDecl.DEFAULT_VALUE && useAtt != null && useAtt.intValue() != SchemaSymbols.USE_OPTIONAL) { reportSchemaError("src-attribute.2", new Object[]{nameAtt}, attrDecl); } // a-props-correct if (defaultAtt != null && attrUse != null) { // 2 if there is a {value constraint}, the canonical lexical representation of its value must be valid with respect to the {type definition} as defined in String Valid (3.14.4). fValidationState.setNamespaceSupport(schemaDoc.fNamespaceSupport); if (!checkDefaultValid(attrUse)) { reportSchemaError ("a-props-correct.2", new Object[]{nameAtt, defaultAtt}, attrDecl); } // 3 If the {type definition} is or is derived from ID then there must not be a {value constraint}. if (attribute.fType.isIDType() ) { reportSchemaError ("a-props-correct.3", new Object[]{nameAtt}, attrDecl); } // check 3.5.6 constraint // Attribute Use Correct // 2 If the {attribute declaration} has a fixed {value constraint}, then if the attribute use itself has a {value constraint}, it must also be fixed and its value must match that of the {attribute declaration}'s {value constraint}. if (attrUse.fAttrDecl.getConstraintType() == XSAttributeDecl.FIXED_VALUE && attrUse.fConstraintType != XSAttributeDecl.NO_CONSTRAINT) { if (attrUse.fConstraintType != XSAttributeDecl.FIXED_VALUE || attrUse.fAttrDecl.fType.isEqual(attrUse.fAttrDecl.fDefault.actualValue, attrUse.fDefault.actualValue)) { reportSchemaError ("au-props-correct.2", new Object[]{nameAtt}, attrDecl); } } } return attrUse; }
protected XSAttributeUse traverseLocal(Element attrDecl, XSDocumentInfo schemaDoc, SchemaGrammar grammar) { // General Attribute Checking Object[] attrValues = fAttrChecker.checkAttributes(attrDecl, false, schemaDoc); String defaultAtt = (String) attrValues[XSAttributeChecker.ATTIDX_DEFAULT]; String fixedAtt = (String) attrValues[XSAttributeChecker.ATTIDX_FIXED]; String nameAtt = (String) attrValues[XSAttributeChecker.ATTIDX_NAME]; QName refAtt = (QName) attrValues[XSAttributeChecker.ATTIDX_REF]; XInt useAtt = (XInt) attrValues[XSAttributeChecker.ATTIDX_USE]; // get 'attribute declaration' XSAttributeDecl attribute = null; if (attrDecl.getAttributeNode(SchemaSymbols.ATT_REF) != null) { if (refAtt != null) { attribute = (XSAttributeDecl)fSchemaHandler.getGlobalDecl(schemaDoc, XSDHandler.ATTRIBUTE_TYPE, refAtt, attrDecl); Element child = DOMUtil.getFirstChildElement(attrDecl); if (child != null && DOMUtil.getLocalName(child).equals(SchemaSymbols.ELT_ANNOTATION)) { traverseAnnotationDecl(child, attrValues, false, schemaDoc); child = DOMUtil.getNextSiblingElement(child); } if (child != null) { reportSchemaError("src-attribute.3.2", new Object[]{refAtt}, child); } // for error reporting nameAtt = refAtt.localpart; } else { attribute = null; } } else { attribute = traverseNamedAttr(attrDecl, attrValues, schemaDoc, grammar, false); } // get 'value constraint' short consType = XSAttributeDecl.NO_CONSTRAINT; if (defaultAtt != null) { consType = XSAttributeDecl.DEFAULT_VALUE; } else if (fixedAtt != null) { consType = XSAttributeDecl.FIXED_VALUE; defaultAtt = fixedAtt; fixedAtt = null; } XSAttributeUse attrUse = null; if (attribute != null) { if (fSchemaHandler.fDeclPool !=null) { attrUse = fSchemaHandler.fDeclPool.getAttributeUse(); } else { attrUse = new XSAttributeUse(); } attrUse.fAttrDecl = attribute; attrUse.fUse = useAtt.shortValue(); attrUse.fConstraintType = consType; if (defaultAtt != null) { attrUse.fDefault = new ValidatedInfo(); attrUse.fDefault.normalizedValue = defaultAtt; } } fAttrChecker.returnAttrArray(attrValues, schemaDoc); //src-attribute // 1 default and fixed must not both be present. if (defaultAtt != null && fixedAtt != null) { reportSchemaError("src-attribute.1", new Object[]{nameAtt}, attrDecl); } // 2 If default and use are both present, use must have the actual value optional. if (consType == XSAttributeDecl.DEFAULT_VALUE && useAtt != null && useAtt.intValue() != SchemaSymbols.USE_OPTIONAL) { reportSchemaError("src-attribute.2", new Object[]{nameAtt}, attrDecl); } // a-props-correct if (defaultAtt != null && attrUse != null) { // 2 if there is a {value constraint}, the canonical lexical representation of its value must be valid with respect to the {type definition} as defined in String Valid (3.14.4). fValidationState.setNamespaceSupport(schemaDoc.fNamespaceSupport); if (!checkDefaultValid(attrUse)) { reportSchemaError ("a-props-correct.2", new Object[]{nameAtt, defaultAtt}, attrDecl); } // 3 If the {type definition} is or is derived from ID then there must not be a {value constraint}. if (attribute.fType.isIDType() ) { reportSchemaError ("a-props-correct.3", new Object[]{nameAtt}, attrDecl); } // check 3.5.6 constraint // Attribute Use Correct // 2 If the {attribute declaration} has a fixed {value constraint}, then if the attribute use itself has a {value constraint}, it must also be fixed and its value must match that of the {attribute declaration}'s {value constraint}. if (attrUse.fAttrDecl.getConstraintType() == XSAttributeDecl.FIXED_VALUE && attrUse.fConstraintType != XSAttributeDecl.NO_CONSTRAINT) { if (attrUse.fConstraintType != XSAttributeDecl.FIXED_VALUE || !attrUse.fAttrDecl.fType.isEqual(attrUse.fAttrDecl.fDefault.actualValue, attrUse.fDefault.actualValue)) { reportSchemaError ("au-props-correct.2", new Object[]{nameAtt}, attrDecl); } } } return attrUse; }
diff --git a/closure/closure-compiler/src/com/google/javascript/jscomp/DefaultPassConfig.java b/closure/closure-compiler/src/com/google/javascript/jscomp/DefaultPassConfig.java index 06e4c425..95b554bf 100644 --- a/closure/closure-compiler/src/com/google/javascript/jscomp/DefaultPassConfig.java +++ b/closure/closure-compiler/src/com/google/javascript/jscomp/DefaultPassConfig.java @@ -1,1834 +1,1834 @@ /* * Copyright 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Charsets; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.google.common.io.Files; import com.google.javascript.jscomp.NodeTraversal.Callback; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.Token; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.text.ParseException; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; /** * Pass factories and meta-data for native JSCompiler passes. * * @author [email protected] (Nick Santos) */ // TODO(nicksantos): This needs state for a variety of reasons. Some of it // is to satisfy the existing API. Some of it is because passes really do // need to share state in non-trivial ways. This should be audited and // cleaned up. public class DefaultPassConfig extends PassConfig { /* For the --mark-as-compiled pass */ private static final String COMPILED_CONSTANT_NAME = "COMPILED"; /* Constant name for Closure's locale */ private static final String CLOSURE_LOCALE_CONSTANT_NAME = "goog.LOCALE"; // Compiler errors when invalid combinations of passes are run. static final DiagnosticType TIGHTEN_TYPES_WITHOUT_TYPE_CHECK = DiagnosticType.error("JSC_TIGHTEN_TYPES_WITHOUT_TYPE_CHECK", "TightenTypes requires type checking. Please use --check_types."); static final DiagnosticType CANNOT_USE_PROTOTYPE_AND_VAR = DiagnosticType.error("JSC_CANNOT_USE_PROTOTYPE_AND_VAR", "Rename prototypes and inline variables cannot be used together"); // Miscellaneous errors. static final DiagnosticType REPORT_PATH_IO_ERROR = DiagnosticType.error("JSC_REPORT_PATH_IO_ERROR", "Error writing compiler report to {0}"); private static final DiagnosticType INPUT_MAP_PROP_PARSE = DiagnosticType.error("JSC_INPUT_MAP_PROP_PARSE", "Input property map parse error: {0}"); private static final DiagnosticType INPUT_MAP_VAR_PARSE = DiagnosticType.error("JSC_INPUT_MAP_VAR_PARSE", "Input variable map parse error: {0}"); /** * A global namespace to share across checking passes. * TODO(nicksantos): This is a hack until I can get the namespace into * the symbol table. */ private GlobalNamespace namespaceForChecks = null; /** * A type-tightener to share across optimization passes. */ private TightenTypes tightenTypes = null; /** Names exported by goog.exportSymbol. */ private Set<String> exportedNames = null; /** * Ids for cross-module method stubbing, so that each method has * a unique id. */ private CrossModuleMethodMotion.IdGenerator crossModuleIdGenerator = new CrossModuleMethodMotion.IdGenerator(); /** * Keys are arguments passed to getCssName() found during compilation; values * are the number of times the key appeared as an argument to getCssName(). */ private Map<String, Integer> cssNames = null; /** The variable renaming map */ private VariableMap variableMap = null; /** The property renaming map */ private VariableMap propertyMap = null; /** The naming map for anonymous functions */ private VariableMap anonymousFunctionNameMap = null; /** Fully qualified function names and globally unique ids */ private FunctionNames functionNames = null; public DefaultPassConfig(CompilerOptions options) { super(options); } @Override State getIntermediateState() { return new State( cssNames == null ? null : Maps.newHashMap(cssNames), exportedNames == null ? null : Collections.unmodifiableSet(exportedNames), crossModuleIdGenerator, variableMap, propertyMap, anonymousFunctionNameMap, functionNames); } @Override void setIntermediateState(State state) { this.cssNames = state.cssNames == null ? null : Maps.newHashMap(state.cssNames); this.exportedNames = state.exportedNames == null ? null : Sets.newHashSet(state.exportedNames); this.crossModuleIdGenerator = state.crossModuleIdGenerator; this.variableMap = state.variableMap; this.propertyMap = state.propertyMap; this.anonymousFunctionNameMap = state.anonymousFunctionNameMap; this.functionNames = state.functionNames; } @Override protected List<PassFactory> getChecks() { List<PassFactory> checks = Lists.newArrayList(); if (options.nameAnonymousFunctionsOnly) { if (options.anonymousFunctionNaming == AnonymousFunctionNamingPolicy.MAPPED) { checks.add(nameMappedAnonymousFunctions); } else if (options.anonymousFunctionNaming == AnonymousFunctionNamingPolicy.UNMAPPED) { checks.add(nameUnmappedAnonymousFunctions); } return checks; } if (options.checkSuspiciousCode) { checks.add(suspiciousCode); } if (options.checkControlStructures) { checks.add(checkControlStructures); } if (options.checkRequires.isOn()) { checks.add(checkRequires); } if (options.checkProvides.isOn()) { checks.add(checkProvides); } // The following passes are more like "preprocessor" passes. // It's important that they run before most checking passes. // Perhaps this method should be renamed? if (options.generateExports) { checks.add(generateExports); } if (options.exportTestFunctions) { checks.add(exportTestFunctions); } if (options.closurePass) { checks.add(closurePrimitives.makeOneTimePass()); } if (options.closurePass && options.checkMissingGetCssNameLevel.isOn()) { checks.add(closureCheckGetCssName); } if (options.closurePass) { checks.add(closureReplaceGetCssName); } if (options.syntheticBlockStartMarker != null) { // This pass must run before the first fold constants pass. checks.add(createSyntheticBlocks); } // All passes must run the variable check. This synthesizes // variables later so that the compiler doesn't crash. It also // checks the externs file for validity. If you don't want to warn // about missing variable declarations, we shut that specific // error off. WarningsGuard warningsGuard = options.getWarningsGuard(); if (!options.checkSymbols && (warningsGuard == null || !warningsGuard.disables( DiagnosticGroups.CHECK_VARIABLES))) { options.setWarningLevel(DiagnosticGroups.CHECK_VARIABLES, CheckLevel.OFF); } checks.add(checkVars); if (options.checkShadowVars.isOn()) { checks.add(checkShadowVars); } if (options.aggressiveVarCheck.isOn()) { checks.add(checkVariableReferences); } // This pass should run before types are assigned. if (options.processObjectPropertyString) { checks.add(objectPropertyStringPreprocess); } // DiagnosticGroups override the plain checkTypes option. if (options.enables(DiagnosticGroups.CHECK_TYPES)) { options.checkTypes = true; } else if (options.disables(DiagnosticGroups.CHECK_TYPES)) { options.checkTypes = false; } // Type-checking already does more accurate method arity checking, so don't // do legacy method arity checking unless checkTypes is OFF. if (options.checkTypes) { checks.add(resolveTypes.makeOneTimePass()); checks.add(inferTypes.makeOneTimePass()); checks.add(checkTypes.makeOneTimePass()); } else { if (options.checkFunctions.isOn()) { checks.add(checkFunctions); } if (options.checkMethods.isOn()) { checks.add(checkMethods); } } if (options.checkUnreachableCode.isOn() || (options.checkTypes && options.checkMissingReturn.isOn())) { checks.add(checkControlFlow); } // CheckAccessControls only works if check types is on. if (options.enables(DiagnosticGroups.ACCESS_CONTROLS) && options.checkTypes) { checks.add(checkAccessControls); } if (options.checkGlobalNamesLevel.isOn()) { checks.add(checkGlobalNames); } if (options.checkUndefinedProperties.isOn() || options.checkUnusedPropertiesEarly) { checks.add(checkSuspiciousProperties); } if (options.checkCaja || options.checkEs5Strict) { checks.add(checkStrictMode); } // Defines in code always need to be processed. checks.add(processDefines); if (options.instrumentationTemplate != null || options.recordFunctionInformation) { checks.add(computeFunctionNames); } assertAllOneTimePasses(checks); return checks; } @Override protected List<PassFactory> getOptimizations() { List<PassFactory> passes = Lists.newArrayList(); // TODO(nicksantos): The order of these passes makes no sense, and needs // to be re-arranged. if (options.runtimeTypeCheck) { passes.add(runtimeTypeCheck); } passes.add(createEmptyPass("beforeStandardOptimizations")); if (!options.idGenerators.isEmpty()) { passes.add(replaceIdGenerators); } // Optimizes references to the arguments variable. if (options.optimizeArgumentsArray) { passes.add(optimizeArgumentsArray); } // Remove all parameters that are constants or unused. if (options.optimizeParameters) { passes.add(removeUselessParameters); } // Abstract method removal works best on minimally modified code, and also // only needs to run once. if (options.closurePass && options.removeAbstractMethods) { passes.add(removeAbstractMethods); } // Collapsing properties can undo constant inlining, so we do this before // the main optimization loop. if (options.collapseProperties) { passes.add(collapseProperties); } // Tighten types based on actual usage. if (options.tightenTypes) { passes.add(tightenTypesBuilder); } // Property disambiguation should only run once and needs to be done // soon after type checking, both so that it can make use of type // information and so that other passes can take advantage of the renamed // properties. if (options.disambiguateProperties) { passes.add(disambiguateProperties); } if (options.computeFunctionSideEffects) { passes.add(markPureFunctions); } else if (options.markNoSideEffectCalls) { // TODO(user) The properties that this pass adds to CALL and NEW // AST nodes increase the AST's in-memory size. Given that we are // already running close to our memory limits, we could run into // trouble if we end up using the @nosideeffects annotation a lot // or compute @nosideeffects annotations by looking at function // bodies. It should be easy to propagate @nosideeffects // annotations as part of passes that depend on this property and // store the result outside the AST (which would allow garbage // collection once the pass is done). passes.add(markNoSideEffectCalls); } if (options.chainCalls) { passes.add(chainCalls); } // Constant checking must be done after property collapsing because // property collapsing can introduce new constants (e.g. enum values). if (options.inlineConstantVars) { passes.add(checkConsts); } // The Caja library adds properties to Object.prototype, which breaks // most for-in loops. This adds a check to each loop that skips // any property matching /___$/. if (options.ignoreCajaProperties) { passes.add(ignoreCajaProperties); } assertAllOneTimePasses(passes); if (options.smartNameRemoval || options.reportPath != null) { passes.addAll(getCodeRemovingPasses()); passes.add(smartNamePass); } // TODO(user): This forces a first crack at crossModuleCodeMotion // before devirtualization. Once certain functions are devirtualized, // it confuses crossModuleCodeMotion ability to recognized that // it is recursive. // TODO(user): This is meant for a temporary quick win. // In the future, we might want to improve our analysis in // CrossModuleCodeMotion so we don't need to do this. if (options.crossModuleCodeMotion) { passes.add(crossModuleCodeMotion); } // Method devirtualization benefits from property disambiguiation so // it should run after that pass but before passes that do // optimizations based on global names (like cross module code motion // and inline functions). Smart Name Removal does better if run before // this pass. if (options.devirtualizePrototypeMethods) { passes.add(devirtualizePrototypeMethods); } if (options.customPasses != null) { passes.add(getCustomPasses( CustomPassExecutionTime.BEFORE_OPTIMIZATION_LOOP)); } passes.add(createEmptyPass("beforeMainOptimizations")); passes.addAll(getMainOptimizationLoop()); passes.add(createEmptyPass("beforeModuleMotion")); if (options.crossModuleCodeMotion) { passes.add(crossModuleCodeMotion); } if (options.crossModuleMethodMotion) { passes.add(crossModuleMethodMotion); } passes.add(createEmptyPass("afterModuleMotion")); // Some optimizations belong outside the loop because running them more // than once would either have no benefit or be incorrect. if (options.customPasses != null) { passes.add(getCustomPasses( CustomPassExecutionTime.AFTER_OPTIMIZATION_LOOP)); } if (options.flowSensitiveInlineVariables) { passes.add(flowSensitiveInlineVariables); // After inlining some of the variable uses, some variables are unused. // Re-run remove unused vars to clean it up. if (options.removeUnusedVars) { passes.add(removeUnusedVars); } } if (options.collapseAnonymousFunctions) { passes.add(collapseAnonymousFunctions); } // Move functions before extracting prototype member declarations. if (options.moveFunctionDeclarations) { passes.add(moveFunctionDeclarations); } if (options.anonymousFunctionNaming == AnonymousFunctionNamingPolicy.MAPPED) { passes.add(nameMappedAnonymousFunctions); } // The mapped name anonymous function pass makes use of information that // the extract prototype member declarations pass removes so the former // happens before the latter. // // Extracting prototype properties screws up the heuristic renaming // policies, so never run it when those policies are requested. if (options.extractPrototypeMemberDeclarations && (options.propertyRenaming != PropertyRenamingPolicy.HEURISTIC && options.propertyRenaming != PropertyRenamingPolicy.AGGRESSIVE_HEURISTIC)) { passes.add(extractPrototypeMemberDeclarations); } if (options.coalesceVariableNames) { passes.add(coalesceVariableNames); } if (options.ambiguateProperties && (options.propertyRenaming == PropertyRenamingPolicy.ALL_UNQUOTED)) { passes.add(ambiguateProperties); } if (options.propertyRenaming != PropertyRenamingPolicy.OFF) { passes.add(renameProperties); } // Reserve global names added to the "windows" object. if (options.reserveRawExports) { passes.add(gatherRawExports); } // This comes after property renaming because quoted property names must // not be renamed. if (options.convertToDottedProperties) { passes.add(convertToDottedProperties); } // Property renaming must happen before this pass runs since this // pass may convert dotted properties into quoted properties. It // is beneficial to run before alias strings, alias keywords and // variable renaming. if (options.rewriteFunctionExpressions) { passes.add(rewriteFunctionExpressions); } // This comes after converting quoted property accesses to dotted property // accesses in order to avoid aliasing property names. if (!options.aliasableStrings.isEmpty() || options.aliasAllStrings) { passes.add(aliasStrings); } if (options.aliasExternals) { passes.add(aliasExternals); } if (options.aliasKeywords) { passes.add(aliasKeywords); } if (options.collapseVariableDeclarations) { passes.add(collapseVariableDeclarations); } passes.add(denormalize); if (options.instrumentationTemplate != null) { passes.add(instrumentFunctions); } if (options.variableRenaming != VariableRenamingPolicy.ALL) { // If we're leaving some (or all) variables with their old names, // then we need to undo any of the markers we added for distinguishing - // local variables ("$$1") or constants ("$$constant"). + // local variables ("$$1"). passes.add(invertContextualRenaming); } if (options.variableRenaming != VariableRenamingPolicy.OFF) { passes.add(renameVars); } // This pass should run after names stop changing. if (options.processObjectPropertyString) { passes.add(objectPropertyStringPostprocess); } if (options.labelRenaming) { passes.add(renameLabels); } if (options.anonymousFunctionNaming == AnonymousFunctionNamingPolicy.UNMAPPED) { passes.add(nameUnmappedAnonymousFunctions); } // Safety check if (options.checkSymbols) { passes.add(sanityCheckVars); } return passes; } /** Creates the passes for the main optimization loop. */ private List<PassFactory> getMainOptimizationLoop() { List<PassFactory> passes = Lists.newArrayList(); if (options.inlineGetters) { passes.add(inlineGetters); } passes.addAll(getCodeRemovingPasses()); if (options.inlineFunctions || options.inlineLocalFunctions) { passes.add(inlineFunctions); } if (options.removeUnusedVars) { if (options.deadAssignmentElimination) { passes.add(deadAssignmentsElimination); } passes.add(removeUnusedVars); } assertAllLoopablePasses(passes); return passes; } /** Creates several passes aimed at removing code. */ private List<PassFactory> getCodeRemovingPasses() { List<PassFactory> passes = Lists.newArrayList(); if (options.inlineVariables || options.inlineLocalVariables) { passes.add(inlineVariables); } else if (options.inlineConstantVars) { passes.add(inlineConstants); } if (options.removeConstantExpressions) { passes.add(removeConstantExpressions); } if (options.foldConstants) { // These used to be one pass. passes.add(minimizeExitPoints); passes.add(foldConstants); } if (options.removeDeadCode) { passes.add(removeUnreachableCode); } if (options.removeUnusedPrototypeProperties) { passes.add(removeUnusedPrototypeProperties); } assertAllLoopablePasses(passes); return passes; } /** * Checks for code that is probably wrong (such as stray expressions). */ // TODO(bolinfest): Write a CompilerPass for this. final PassFactory suspiciousCode = new PassFactory("suspiciousCode", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { List<Callback> sharedCallbacks = Lists.newArrayList(); sharedCallbacks.add(new CheckAccidentalSemicolon(CheckLevel.WARNING)); sharedCallbacks.add(new CheckSideEffects(CheckLevel.WARNING)); if (options.checkGlobalThisLevel.isOn()) { sharedCallbacks.add( new CheckGlobalThis(compiler, options.checkGlobalThisLevel)); } return combineChecks(compiler, sharedCallbacks); } }; /** Verify that all the passes are one-time passes. */ private void assertAllOneTimePasses(List<PassFactory> passes) { for (PassFactory pass : passes) { Preconditions.checkState(pass.isOneTimePass()); } } /** Verify that all the passes are multi-run passes. */ private void assertAllLoopablePasses(List<PassFactory> passes) { for (PassFactory pass : passes) { Preconditions.checkState(!pass.isOneTimePass()); } } /** Checks for validity of the control structures. */ private final PassFactory checkControlStructures = new PassFactory("checkControlStructures", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new ControlStructureCheck(compiler); } }; /** Checks that all constructed classes are goog.require()d. */ private final PassFactory checkRequires = new PassFactory("checkRequires", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new CheckRequiresForConstructors(compiler, options.checkRequires); } }; /** Makes sure @constructor is paired with goog.provides(). */ private final PassFactory checkProvides = new PassFactory("checkProvides", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new CheckProvides(compiler, options.checkProvides); } }; private static final DiagnosticType GENERATE_EXPORTS_ERROR = DiagnosticType.error( "JSC_GENERATE_EXPORTS_ERROR", "Exports can only be generated if export symbol/property " + "functions are set."); /** Generates exports for @export annotations. */ private final PassFactory generateExports = new PassFactory("generateExports", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { CodingConvention convention = compiler.getCodingConvention(); if (convention.getExportSymbolFunction() != null && convention.getExportPropertyFunction() != null) { return new GenerateExports(compiler, convention.getExportSymbolFunction(), convention.getExportPropertyFunction()); } else { return new ErrorPass(compiler, GENERATE_EXPORTS_ERROR); } } }; /** Generates exports for functions associated with JSUnit. */ private final PassFactory exportTestFunctions = new PassFactory("exportTestFunctions", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { CodingConvention convention = compiler.getCodingConvention(); if (convention.getExportSymbolFunction() != null) { return new ExportTestFunctions(compiler, convention.getExportSymbolFunction()); } else { return new ErrorPass(compiler, GENERATE_EXPORTS_ERROR); } } }; /** Raw exports processing pass. */ final PassFactory gatherRawExports = new PassFactory("gatherRawExports", false) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { final GatherRawExports pass = new GatherRawExports( compiler); return new CompilerPass() { @Override public void process(Node externs, Node root) { pass.process(externs, root); if (exportedNames == null) { exportedNames = Sets.newHashSet(); } exportedNames.addAll(pass.getExportedVariableNames()); } }; } }; /** Closure pre-processing pass. */ @SuppressWarnings("deprecation") final PassFactory closurePrimitives = new PassFactory("processProvidesAndRequires", false) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { final ProcessClosurePrimitives pass = new ProcessClosurePrimitives( compiler, options.brokenClosureRequiresLevel, options.rewriteNewDateGoogNow); return new CompilerPass() { @Override public void process(Node externs, Node root) { pass.process(externs, root); exportedNames = pass.getExportedVariableNames(); } }; } }; /** Checks that CSS class names are wrapped in goog.getCssName */ private final PassFactory closureCheckGetCssName = new PassFactory("checkMissingGetCssName", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { String blacklist = options.checkMissingGetCssNameBlacklist; Preconditions.checkState(blacklist != null && !blacklist.isEmpty(), "Not checking use of goog.getCssName because of empty blacklist."); return new CheckMissingGetCssName( compiler, options.checkMissingGetCssNameLevel, blacklist); } }; /** * Processes goog.getCssName. The cssRenamingMap is used to lookup * replacement values for the classnames. If null, the raw class names are * inlined. */ private final PassFactory closureReplaceGetCssName = new PassFactory("renameCssNames", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { return new CompilerPass() { @Override public void process(Node externs, Node jsRoot) { Map<String, Integer> newCssNames = null; if (options.gatherCssNames) { newCssNames = Maps.newHashMap(); } (new ReplaceCssNames(compiler, newCssNames)).process( externs, jsRoot); cssNames = newCssNames; } }; } }; /** * Creates synthetic blocks to prevent FoldConstants from moving code * past markers in the source. */ private final PassFactory createSyntheticBlocks = new PassFactory("createSyntheticBlocks", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new CreateSyntheticBlocks(compiler, options.syntheticBlockStartMarker, options.syntheticBlockEndMarker); } }; /** Local constant folding */ static final PassFactory foldConstants = new PassFactory("foldConstants", false) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new FoldConstants(compiler); } }; /** Checks that all variables are defined. */ private final PassFactory checkVars = new PassFactory("checkVars", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new VarCheck(compiler); } }; /** Checks that no vars are illegally shadowed. */ private final PassFactory checkShadowVars = new PassFactory("variableShadowDeclarationCheck", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new VariableShadowDeclarationCheck( compiler, options.checkShadowVars); } }; /** Checks that references to variables look reasonable. */ private final PassFactory checkVariableReferences = new PassFactory("checkVariableReferences", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new VariableReferenceCheck( compiler, options.aggressiveVarCheck); } }; /** Pre-process goog.testing.ObjectPropertyString. */ private final PassFactory objectPropertyStringPreprocess = new PassFactory("ObjectPropertyStringPreprocess", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new ObjectPropertyStringPreprocess(compiler); } }; /** Checks number of args passed to functions. */ private final PassFactory checkFunctions = new PassFactory("checkFunctions", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new FunctionCheck(compiler, options.checkFunctions); } }; /** Checks number of args passed to methods. */ private final PassFactory checkMethods = new PassFactory("checkMethods", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new MethodCheck(compiler, options.checkMethods); } }; /** Creates a typed scope and adds types to the type registry. */ final PassFactory resolveTypes = new PassFactory("resolveTypes", false) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new GlobalTypeResolver(compiler); } }; /** Rusn type inference. */ private final PassFactory inferTypes = new PassFactory("inferTypes", false) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { return new CompilerPass() { @Override public void process(Node externs, Node root) { Preconditions.checkNotNull(topScope); Preconditions.checkNotNull(typedScopeCreator); makeTypeInference(compiler).process(externs, root); } }; } }; /** Checks type usage */ private final PassFactory checkTypes = new PassFactory("checkTypes", false) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { return new CompilerPass() { @Override public void process(Node externs, Node root) { Preconditions.checkNotNull(topScope); Preconditions.checkNotNull(typedScopeCreator); TypeCheck check = makeTypeCheck(compiler); check.process(externs, root); compiler.getErrorManager().setTypedPercent(check.getTypedPercent()); } }; } }; /** * Checks possible execution paths of the program for problems: missing return * statements and dead code. */ private final PassFactory checkControlFlow = new PassFactory("checkControlFlow", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { List<Callback> callbacks = Lists.newArrayList(); if (options.checkUnreachableCode.isOn()) { callbacks.add( new CheckUnreachableCode(compiler, options.checkUnreachableCode)); } if (options.checkMissingReturn.isOn() && options.checkTypes) { callbacks.add( new CheckMissingReturn(compiler, options.checkMissingReturn)); } return combineChecks(compiler, callbacks); } }; /** Checks access controls. Depends on type-inference. */ private final PassFactory checkAccessControls = new PassFactory("checkAccessControls", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new CheckAccessControls(compiler); } }; /** Executes the given callbacks with a {@link CombinedCompilerPass}. */ private static CompilerPass combineChecks(AbstractCompiler compiler, List<Callback> callbacks) { Preconditions.checkArgument(callbacks.size() > 0); Callback[] array = callbacks.toArray(new Callback[callbacks.size()]); return new CombinedCompilerPass(compiler, array); } /** A compiler pass that resolves types in the global scope. */ private class GlobalTypeResolver implements CompilerPass { private final AbstractCompiler compiler; GlobalTypeResolver(AbstractCompiler compiler) { this.compiler = compiler; } @Override public void process(Node externs, Node root) { if (topScope == null) { typedScopeCreator = new MemoizedScopeCreator(new TypedScopeCreator(compiler)); topScope = typedScopeCreator.createScope(root.getParent(), null); } else { compiler.getTypeRegistry().resolveTypesInScope(topScope); } } } /** Checks global name usage. */ private final PassFactory checkGlobalNames = new PassFactory("Check names", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { return new CompilerPass() { @Override public void process(Node externs, Node jsRoot) { // Create a global namespace for analysis by check passes. // Note that this class does all heavy computation lazily, // so it's OK to create it here. namespaceForChecks = new GlobalNamespace(compiler, jsRoot); new CheckGlobalNames(compiler, options.checkGlobalNamesLevel) .injectNamespace(namespaceForChecks).process(externs, jsRoot); } }; } }; /** Checks for properties that are not read or written */ private final PassFactory checkSuspiciousProperties = new PassFactory("checkSuspiciousProperties", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new SuspiciousPropertiesCheck( compiler, options.checkUndefinedProperties, options.checkUnusedPropertiesEarly ? CheckLevel.WARNING : CheckLevel.OFF); } }; /** Checks that the code is ES5 or Caja compliant. */ private final PassFactory checkStrictMode = new PassFactory("checkStrictMode", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new StrictModeCheck(compiler, !options.checkSymbols, // don't check variables twice !options.checkCaja); // disable eval check if not Caja } }; /** Override @define-annotated constants. */ final PassFactory processDefines = new PassFactory("processDefines", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { return new CompilerPass() { @Override public void process(Node externs, Node jsRoot) { Map<String, Node> replacements = getAdditionalReplacements(options); replacements.putAll(options.getDefineReplacements()); new ProcessDefines(compiler, replacements) .injectNamespace(namespaceForChecks).process(externs, jsRoot); // Kill the namespace in the other class // so that it can be garbage collected after all passes // are through with it. namespaceForChecks = null; } }; } }; /** Checks that all constants are not modified */ private final PassFactory checkConsts = new PassFactory("checkConsts", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new ConstCheck(compiler); } }; /** Computes the names of functions for later analysis. */ private final PassFactory computeFunctionNames = new PassFactory("computeFunctionNames", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return ((functionNames = new FunctionNames(compiler))); } }; /** Skips Caja-private properties in for-in loops */ private final PassFactory ignoreCajaProperties = new PassFactory("ignoreCajaProperties", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new IgnoreCajaProperties(compiler); } }; /** Inserts runtime type assertions for debugging. */ private final PassFactory runtimeTypeCheck = new PassFactory("runtimeTypeCheck", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new RuntimeTypeCheck(compiler, options.runtimeTypeCheckLogFunction); } }; /** Generates unique ids. */ private final PassFactory replaceIdGenerators = new PassFactory("replaceIdGenerators", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new ReplaceIdGenerators(compiler, options.idGenerators); } }; /** Optimizes the "arguments" array. */ private final PassFactory optimizeArgumentsArray = new PassFactory("optimizeArgumentsArray", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new OptimizeArgumentsArray(compiler); } }; /** Removes unused or constant formal parameters. */ private final PassFactory removeUselessParameters = new PassFactory("optimizeParameters", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { return new CompilerPass() { @Override public void process(Node externs, Node root) { NameReferenceGraphConstruction c = new NameReferenceGraphConstruction(compiler); c.process(externs, root); (new OptimizeParameters(compiler, c.getNameReferenceGraph())).process( externs, root); } }; } }; /** Remove variables set to goog.abstractMethod. */ private final PassFactory removeAbstractMethods = new PassFactory("removeAbstractMethods", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { return new GoogleCodeRemoval(compiler); } }; /** Collapses names in the global scope. */ private final PassFactory collapseProperties = new PassFactory("collapseProperties", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new CollapseProperties( compiler, options.collapsePropertiesOnExternTypes, !isInliningForbidden()); } }; /** * Try to infer the actual types, which may be narrower * than the declared types. */ private final PassFactory tightenTypesBuilder = new PassFactory("tightenTypes", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { if (!options.checkTypes) { return new ErrorPass(compiler, TIGHTEN_TYPES_WITHOUT_TYPE_CHECK); } tightenTypes = new TightenTypes(compiler); return tightenTypes; } }; /** Devirtualize property names based on type information. */ private final PassFactory disambiguateProperties = new PassFactory("disambiguateProperties", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { if (tightenTypes == null) { return DisambiguateProperties.forJSTypeSystem(compiler); } else { return DisambiguateProperties.forConcreteTypeSystem( compiler, tightenTypes); } } }; /** * Chain calls to functions that return this. */ private final PassFactory chainCalls = new PassFactory("chainCalls", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new ChainCalls(compiler); } }; /** * Rewrite instance methods as static methods, to make them easier * to inline. */ private final PassFactory devirtualizePrototypeMethods = new PassFactory("devirtualizePrototypeMethods", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new DevirtualizePrototypeMethods(compiler); } }; /** * Look for function calls that are pure, and annotate them * that way. */ private final PassFactory markPureFunctions = new PassFactory("markPureFunctions", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new PureFunctionMarker( compiler, options.debugFunctionSideEffectsPath, false); } }; /** * Look for function calls that have no side effects, and annotate them * that way. */ private final PassFactory markNoSideEffectCalls = new PassFactory("markNoSideEffectCalls", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new MarkNoSideEffectCalls(compiler); } }; /** Inlines variables heuristically. */ private final PassFactory inlineVariables = new PassFactory("inlineVariables", false) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { if (isInliningForbidden()) { // In old renaming schemes, inlining a variable can change whether // or not a property is renamed. This is bad, and those old renaming // schemes need to die. return new ErrorPass(compiler, CANNOT_USE_PROTOTYPE_AND_VAR); } else { InlineVariables.Mode mode; if (options.inlineVariables) { mode = InlineVariables.Mode.ALL; } else if (options.inlineLocalVariables) { mode = InlineVariables.Mode.LOCALS_ONLY; } else { throw new IllegalStateException("No variable inlining option set."); } return new InlineVariables(compiler, mode, true); } } }; /** Inlines variables that are marked as constants. */ private final PassFactory inlineConstants = new PassFactory("inlineConstants", false) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new InlineVariables( compiler, InlineVariables.Mode.CONSTANTS_ONLY, true); } }; /** * Simplify expressions by removing the parts that have no side effects. */ private final PassFactory removeConstantExpressions = new PassFactory("removeConstantExpressions", false) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new RemoveConstantExpressions(compiler); } }; /** * Perform local control flow optimizations. */ private final PassFactory minimizeExitPoints = new PassFactory("minimizeExitPoints", false) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new MinimizeExitPoints(compiler); } }; /** * Use data flow analysis to remove dead branches. */ private final PassFactory removeUnreachableCode = new PassFactory("removeUnreachableCode", false) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new UnreachableCodeElimination(compiler, true); } }; /** * Remove prototype properties that do not appear to be used. */ private final PassFactory removeUnusedPrototypeProperties = new PassFactory("removeUnusedPrototypeProperties", false) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new RemoveUnusedPrototypeProperties( compiler, options.removeUnusedPrototypePropertiesInExterns, !options.removeUnusedVars); } }; /** * Process smart name processing - removes unused classes and does referencing * starting with minimum set of names. */ private final PassFactory smartNamePass = new PassFactory("smartNamePass", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { return new CompilerPass() { @Override public void process(Node externs, Node root) { NameAnalyzer na = new NameAnalyzer(compiler, false); na.process(externs, root); String reportPath = options.reportPath; if (reportPath != null) { try { Files.write(na.getHtmlReport(), new File(reportPath), Charsets.UTF_8); } catch (IOException e) { compiler.report(JSError.make(REPORT_PATH_IO_ERROR, reportPath)); } } if (options.smartNameRemoval) { na.removeUnreferenced(); } } }; } }; /** Inlines simple methods, like getters */ private PassFactory inlineGetters = new PassFactory("inlineGetters", false) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new InlineGetters(compiler); } }; /** Kills dead assignments. */ private PassFactory deadAssignmentsElimination = new PassFactory("deadAssignmentsElimination", false) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new DeadAssignmentsElimination(compiler); } }; /** Inlines function calls. */ private PassFactory inlineFunctions = new PassFactory("inlineFunctions", false) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { boolean enableBlockInlining = !isInliningForbidden(); return new InlineFunctions( compiler, compiler.getUniqueNameIdSupplier(), options.inlineFunctions, options.inlineLocalFunctions, options.inlineAnonymousFunctionExpressions, enableBlockInlining, options.decomposeExpressions); } }; /** Removes variables that are never used. */ private PassFactory removeUnusedVars = new PassFactory("removeUnusedVars", false) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { boolean preserveAnonymousFunctionNames = options.anonymousFunctionNaming != AnonymousFunctionNamingPolicy.OFF; return new RemoveUnusedVars( compiler, options.removeUnusedVarsInGlobalScope, preserveAnonymousFunctionNames); } }; /** * Move global symbols to a deeper common module */ private PassFactory crossModuleCodeMotion = new PassFactory("crossModuleCodeMotion", false) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new CrossModuleCodeMotion(compiler, compiler.getModuleGraph()); } }; /** * Move methods to a deeper common module */ private PassFactory crossModuleMethodMotion = new PassFactory("crossModuleMethodMotion", false) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new CrossModuleMethodMotion( compiler, crossModuleIdGenerator, // Only move properties in externs if we're not treating // them as exports. options.removeUnusedPrototypePropertiesInExterns); } }; /** A data-flow based variable inliner. */ private final PassFactory flowSensitiveInlineVariables = new PassFactory("flowSensitiveInlineVariables", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new FlowSensitiveInlineVariables(compiler); } }; /** Uses register-allocation algorithms to use fewer variables. */ private final PassFactory coalesceVariableNames = new PassFactory("coalesceVariableNames", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new CoalesceVariableNames(compiler, options.generatePseudoNames); } }; /** * Some simple, local collapses (e.g., {@code var x; var y;} becomes * {@code var x,y;}. */ private final PassFactory collapseVariableDeclarations = new PassFactory("collapseVariableDeclarations", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { compiler.setUnnormalized(); return new CollapseVariableDeclarations(compiler); } }; /** * Extracts common sub-expressions. */ private final PassFactory extractPrototypeMemberDeclarations = new PassFactory("extractPrototypeMemberDeclarations", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new ExtractPrototypeMemberDeclarations(compiler); } }; /** Rewrites common function definitions to be more compact. */ private final PassFactory rewriteFunctionExpressions = new PassFactory("rewriteFunctionExpressions", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new FunctionRewriter(compiler); } }; /** Collapses functions to not use the VAR keyword. */ private final PassFactory collapseAnonymousFunctions = new PassFactory("collapseAnonymousFunctions", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new CollapseAnonymousFunctions(compiler); } }; /** Moves function declarations to the top, to simulate actual hoisting. */ private final PassFactory moveFunctionDeclarations = new PassFactory("moveFunctionDeclarations", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new MoveFunctionDeclarations(compiler); } }; private final PassFactory nameUnmappedAnonymousFunctions = new PassFactory("nameAnonymousFunctions", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new NameAnonymousFunctions(compiler); } }; private final PassFactory nameMappedAnonymousFunctions = new PassFactory("nameAnonymousFunctions", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { return new CompilerPass() { @Override public void process(Node externs, Node root) { NameAnonymousFunctionsMapped naf = new NameAnonymousFunctionsMapped(compiler); naf.process(externs, root); anonymousFunctionNameMap = naf.getFunctionMap(); } }; } }; /** Alias external symbols. */ private final PassFactory aliasExternals = new PassFactory("aliasExternals", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new AliasExternals(compiler, compiler.getModuleGraph(), options.unaliasableGlobals, options.aliasableGlobals); } }; /** * Alias string literals with global variables, to avoid creating lots of * transient objects. */ private final PassFactory aliasStrings = new PassFactory("aliasStrings", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new AliasStrings( compiler, compiler.getModuleGraph(), options.aliasAllStrings ? null : options.aliasableStrings, options.aliasStringsBlacklist, options.outputJsStringUsage); } }; /** Aliases common keywords (true, false) */ private final PassFactory aliasKeywords = new PassFactory("aliasKeywords", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new AliasKeywords(compiler); } }; /** Handling for the ObjectPropertyString primitive. */ private final PassFactory objectPropertyStringPostprocess = new PassFactory("ObjectPropertyStringPostprocess", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new ObjectPropertyStringPostprocess(compiler); } }; /** * Renames properties so that the two properties that never appear on * the same object get the same name. */ private final PassFactory ambiguateProperties = new PassFactory("ambiguateProperties", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new AmbiguateProperties( compiler, options.anonymousFunctionNaming.getReservedCharacters()); } }; /** Denormalize the AST for code generation. */ private final PassFactory denormalize = new PassFactory("denormalize", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { compiler.setUnnormalized(); return new Denormalize(compiler); } }; /** Inverting name normalization. */ private final PassFactory invertContextualRenaming = new PassFactory("invertNames", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return MakeDeclaredNamesUnique.getContextualRenameInverter(compiler); } }; /** * Renames properties. */ private final PassFactory renameProperties = new PassFactory("renameProperties", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { VariableMap map = null; if (options.inputPropertyMapSerialized != null) { try { map = VariableMap.fromBytes(options.inputPropertyMapSerialized); } catch (ParseException e) { return new ErrorPass(compiler, JSError.make(INPUT_MAP_PROP_PARSE, e.getMessage())); } } final VariableMap prevPropertyMap = map; return new CompilerPass() { @Override public void process(Node externs, Node root) { propertyMap = runPropertyRenaming( compiler, prevPropertyMap, externs, root); } }; } }; private VariableMap runPropertyRenaming( AbstractCompiler compiler, VariableMap prevPropertyMap, Node externs, Node root) { char[] reservedChars = options.anonymousFunctionNaming.getReservedCharacters(); switch (options.propertyRenaming) { case HEURISTIC: RenamePrototypes rproto = new RenamePrototypes(compiler, false, reservedChars, prevPropertyMap); rproto.process(externs, root); return rproto.getPropertyMap(); case AGGRESSIVE_HEURISTIC: RenamePrototypes rproto2 = new RenamePrototypes(compiler, true, reservedChars, prevPropertyMap); rproto2.process(externs, root); return rproto2.getPropertyMap(); case ALL_UNQUOTED: RenameProperties rprop = new RenameProperties( compiler, options.generatePseudoNames, prevPropertyMap, reservedChars); rprop.process(externs, root); return rprop.getPropertyMap(); default: throw new IllegalStateException( "Unrecognized property renaming policy"); } } /** Renames variables. */ private final PassFactory renameVars = new PassFactory("renameVars", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { VariableMap map = null; if (options.inputVariableMapSerialized != null) { try { map = VariableMap.fromBytes(options.inputVariableMapSerialized); } catch (ParseException e) { return new ErrorPass(compiler, JSError.make(INPUT_MAP_VAR_PARSE, e.getMessage())); } } final VariableMap prevVariableMap = map; return new CompilerPass() { @Override public void process(Node externs, Node root) { variableMap = runVariableRenaming( compiler, prevVariableMap, externs, root); } }; } }; private VariableMap runVariableRenaming( AbstractCompiler compiler, VariableMap prevVariableMap, Node externs, Node root) { char[] reservedChars = options.anonymousFunctionNaming.getReservedCharacters(); boolean preserveAnonymousFunctionNames = options.anonymousFunctionNaming != AnonymousFunctionNamingPolicy.OFF; RenameVars rn = new RenameVars( compiler, options.renamePrefix, options.variableRenaming == VariableRenamingPolicy.LOCAL, preserveAnonymousFunctionNames, options.generatePseudoNames, prevVariableMap, reservedChars, exportedNames); rn.process(externs, root); return rn.getVariableMap(); } /** Renames labels */ private final PassFactory renameLabels = new PassFactory("renameLabels", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new RenameLabels(compiler); } }; /** Convert bracket access to dot access */ private final PassFactory convertToDottedProperties = new PassFactory("convertToDottedProperties", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new ConvertToDottedProperties(compiler); } }; /** Checks that all variables are defined. */ private final PassFactory sanityCheckVars = new PassFactory("sanityCheckVars", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new VarCheck(compiler, true); } }; /** Adds instrumentations according to an instrumentation template. */ private final PassFactory instrumentFunctions = new PassFactory("instrumentFunctions", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { return new CompilerPass() { @Override public void process(Node externs, Node root) { try { FileReader templateFile = new FileReader(options.instrumentationTemplate); (new InstrumentFunctions( compiler, functionNames, options.instrumentationTemplate, options.appNameStr, templateFile)).process(externs, root); } catch (IOException e) { compiler.report( JSError.make(AbstractCompiler.READ_ERROR, options.instrumentationTemplate)); } } }; } }; /** * Create a no-op pass that can only run once. Used to break up loops. */ private static PassFactory createEmptyPass(String name) { return new PassFactory(name, true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { return runInSerial(); } }; } /** * Runs custom passes that are designated to run at a particular time. */ private PassFactory getCustomPasses( final CustomPassExecutionTime executionTime) { return new PassFactory("runCustomPasses", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { return runInSerial(options.customPasses.get(executionTime)); } }; } /** * All inlining is forbidden in heuristic renaming mode, because inlining * will ruin the invariants that it depends on. */ private boolean isInliningForbidden() { return options.propertyRenaming == PropertyRenamingPolicy.HEURISTIC || options.propertyRenaming == PropertyRenamingPolicy.AGGRESSIVE_HEURISTIC; } /** Create a compiler pass that runs the given passes in serial. */ private static CompilerPass runInSerial(final CompilerPass ... passes) { return runInSerial(Lists.newArrayList(passes)); } /** Create a compiler pass that runs the given passes in serial. */ private static CompilerPass runInSerial( final Collection<CompilerPass> passes) { return new CompilerPass() { @Override public void process(Node externs, Node root) { for (CompilerPass pass : passes) { pass.process(externs, root); } } }; } @VisibleForTesting static Map<String, Node> getAdditionalReplacements( CompilerOptions options) { Map<String, Node> additionalReplacements = Maps.newHashMap(); if (options.markAsCompiled || options.closurePass) { additionalReplacements.put(COMPILED_CONSTANT_NAME, new Node(Token.TRUE)); } if (options.closurePass && options.locale != null) { additionalReplacements.put(CLOSURE_LOCALE_CONSTANT_NAME, Node.newString(options.locale)); } return additionalReplacements; } /** A compiler pass that marks pure functions. */ private static class PureFunctionMarker implements CompilerPass { private final AbstractCompiler compiler; private final String reportPath; private final boolean useNameReferenceGraph; PureFunctionMarker(AbstractCompiler compiler, String reportPath, boolean useNameReferenceGraph) { this.compiler = compiler; this.reportPath = reportPath; this.useNameReferenceGraph = useNameReferenceGraph; } @Override public void process(Node externs, Node root) { DefinitionProvider definitionProvider = null; if (useNameReferenceGraph) { NameReferenceGraphConstruction graphBuilder = new NameReferenceGraphConstruction(compiler); graphBuilder.process(externs, root); definitionProvider = graphBuilder.getNameReferenceGraph(); } else { SimpleDefinitionFinder defFinder = new SimpleDefinitionFinder(compiler); defFinder.process(externs, root); definitionProvider = defFinder; } PureFunctionIdentifier pureFunctionIdentifier = new PureFunctionIdentifier(compiler, definitionProvider); pureFunctionIdentifier.process(externs, root); if (reportPath != null) { try { Files.write(pureFunctionIdentifier.getDebugReport(), new File(reportPath), Charsets.UTF_8); } catch (IOException e) { throw new RuntimeException(e); } } } } }
true
true
protected List<PassFactory> getOptimizations() { List<PassFactory> passes = Lists.newArrayList(); // TODO(nicksantos): The order of these passes makes no sense, and needs // to be re-arranged. if (options.runtimeTypeCheck) { passes.add(runtimeTypeCheck); } passes.add(createEmptyPass("beforeStandardOptimizations")); if (!options.idGenerators.isEmpty()) { passes.add(replaceIdGenerators); } // Optimizes references to the arguments variable. if (options.optimizeArgumentsArray) { passes.add(optimizeArgumentsArray); } // Remove all parameters that are constants or unused. if (options.optimizeParameters) { passes.add(removeUselessParameters); } // Abstract method removal works best on minimally modified code, and also // only needs to run once. if (options.closurePass && options.removeAbstractMethods) { passes.add(removeAbstractMethods); } // Collapsing properties can undo constant inlining, so we do this before // the main optimization loop. if (options.collapseProperties) { passes.add(collapseProperties); } // Tighten types based on actual usage. if (options.tightenTypes) { passes.add(tightenTypesBuilder); } // Property disambiguation should only run once and needs to be done // soon after type checking, both so that it can make use of type // information and so that other passes can take advantage of the renamed // properties. if (options.disambiguateProperties) { passes.add(disambiguateProperties); } if (options.computeFunctionSideEffects) { passes.add(markPureFunctions); } else if (options.markNoSideEffectCalls) { // TODO(user) The properties that this pass adds to CALL and NEW // AST nodes increase the AST's in-memory size. Given that we are // already running close to our memory limits, we could run into // trouble if we end up using the @nosideeffects annotation a lot // or compute @nosideeffects annotations by looking at function // bodies. It should be easy to propagate @nosideeffects // annotations as part of passes that depend on this property and // store the result outside the AST (which would allow garbage // collection once the pass is done). passes.add(markNoSideEffectCalls); } if (options.chainCalls) { passes.add(chainCalls); } // Constant checking must be done after property collapsing because // property collapsing can introduce new constants (e.g. enum values). if (options.inlineConstantVars) { passes.add(checkConsts); } // The Caja library adds properties to Object.prototype, which breaks // most for-in loops. This adds a check to each loop that skips // any property matching /___$/. if (options.ignoreCajaProperties) { passes.add(ignoreCajaProperties); } assertAllOneTimePasses(passes); if (options.smartNameRemoval || options.reportPath != null) { passes.addAll(getCodeRemovingPasses()); passes.add(smartNamePass); } // TODO(user): This forces a first crack at crossModuleCodeMotion // before devirtualization. Once certain functions are devirtualized, // it confuses crossModuleCodeMotion ability to recognized that // it is recursive. // TODO(user): This is meant for a temporary quick win. // In the future, we might want to improve our analysis in // CrossModuleCodeMotion so we don't need to do this. if (options.crossModuleCodeMotion) { passes.add(crossModuleCodeMotion); } // Method devirtualization benefits from property disambiguiation so // it should run after that pass but before passes that do // optimizations based on global names (like cross module code motion // and inline functions). Smart Name Removal does better if run before // this pass. if (options.devirtualizePrototypeMethods) { passes.add(devirtualizePrototypeMethods); } if (options.customPasses != null) { passes.add(getCustomPasses( CustomPassExecutionTime.BEFORE_OPTIMIZATION_LOOP)); } passes.add(createEmptyPass("beforeMainOptimizations")); passes.addAll(getMainOptimizationLoop()); passes.add(createEmptyPass("beforeModuleMotion")); if (options.crossModuleCodeMotion) { passes.add(crossModuleCodeMotion); } if (options.crossModuleMethodMotion) { passes.add(crossModuleMethodMotion); } passes.add(createEmptyPass("afterModuleMotion")); // Some optimizations belong outside the loop because running them more // than once would either have no benefit or be incorrect. if (options.customPasses != null) { passes.add(getCustomPasses( CustomPassExecutionTime.AFTER_OPTIMIZATION_LOOP)); } if (options.flowSensitiveInlineVariables) { passes.add(flowSensitiveInlineVariables); // After inlining some of the variable uses, some variables are unused. // Re-run remove unused vars to clean it up. if (options.removeUnusedVars) { passes.add(removeUnusedVars); } } if (options.collapseAnonymousFunctions) { passes.add(collapseAnonymousFunctions); } // Move functions before extracting prototype member declarations. if (options.moveFunctionDeclarations) { passes.add(moveFunctionDeclarations); } if (options.anonymousFunctionNaming == AnonymousFunctionNamingPolicy.MAPPED) { passes.add(nameMappedAnonymousFunctions); } // The mapped name anonymous function pass makes use of information that // the extract prototype member declarations pass removes so the former // happens before the latter. // // Extracting prototype properties screws up the heuristic renaming // policies, so never run it when those policies are requested. if (options.extractPrototypeMemberDeclarations && (options.propertyRenaming != PropertyRenamingPolicy.HEURISTIC && options.propertyRenaming != PropertyRenamingPolicy.AGGRESSIVE_HEURISTIC)) { passes.add(extractPrototypeMemberDeclarations); } if (options.coalesceVariableNames) { passes.add(coalesceVariableNames); } if (options.ambiguateProperties && (options.propertyRenaming == PropertyRenamingPolicy.ALL_UNQUOTED)) { passes.add(ambiguateProperties); } if (options.propertyRenaming != PropertyRenamingPolicy.OFF) { passes.add(renameProperties); } // Reserve global names added to the "windows" object. if (options.reserveRawExports) { passes.add(gatherRawExports); } // This comes after property renaming because quoted property names must // not be renamed. if (options.convertToDottedProperties) { passes.add(convertToDottedProperties); } // Property renaming must happen before this pass runs since this // pass may convert dotted properties into quoted properties. It // is beneficial to run before alias strings, alias keywords and // variable renaming. if (options.rewriteFunctionExpressions) { passes.add(rewriteFunctionExpressions); } // This comes after converting quoted property accesses to dotted property // accesses in order to avoid aliasing property names. if (!options.aliasableStrings.isEmpty() || options.aliasAllStrings) { passes.add(aliasStrings); } if (options.aliasExternals) { passes.add(aliasExternals); } if (options.aliasKeywords) { passes.add(aliasKeywords); } if (options.collapseVariableDeclarations) { passes.add(collapseVariableDeclarations); } passes.add(denormalize); if (options.instrumentationTemplate != null) { passes.add(instrumentFunctions); } if (options.variableRenaming != VariableRenamingPolicy.ALL) { // If we're leaving some (or all) variables with their old names, // then we need to undo any of the markers we added for distinguishing // local variables ("$$1") or constants ("$$constant"). passes.add(invertContextualRenaming); } if (options.variableRenaming != VariableRenamingPolicy.OFF) { passes.add(renameVars); } // This pass should run after names stop changing. if (options.processObjectPropertyString) { passes.add(objectPropertyStringPostprocess); } if (options.labelRenaming) { passes.add(renameLabels); } if (options.anonymousFunctionNaming == AnonymousFunctionNamingPolicy.UNMAPPED) { passes.add(nameUnmappedAnonymousFunctions); } // Safety check if (options.checkSymbols) { passes.add(sanityCheckVars); } return passes; }
protected List<PassFactory> getOptimizations() { List<PassFactory> passes = Lists.newArrayList(); // TODO(nicksantos): The order of these passes makes no sense, and needs // to be re-arranged. if (options.runtimeTypeCheck) { passes.add(runtimeTypeCheck); } passes.add(createEmptyPass("beforeStandardOptimizations")); if (!options.idGenerators.isEmpty()) { passes.add(replaceIdGenerators); } // Optimizes references to the arguments variable. if (options.optimizeArgumentsArray) { passes.add(optimizeArgumentsArray); } // Remove all parameters that are constants or unused. if (options.optimizeParameters) { passes.add(removeUselessParameters); } // Abstract method removal works best on minimally modified code, and also // only needs to run once. if (options.closurePass && options.removeAbstractMethods) { passes.add(removeAbstractMethods); } // Collapsing properties can undo constant inlining, so we do this before // the main optimization loop. if (options.collapseProperties) { passes.add(collapseProperties); } // Tighten types based on actual usage. if (options.tightenTypes) { passes.add(tightenTypesBuilder); } // Property disambiguation should only run once and needs to be done // soon after type checking, both so that it can make use of type // information and so that other passes can take advantage of the renamed // properties. if (options.disambiguateProperties) { passes.add(disambiguateProperties); } if (options.computeFunctionSideEffects) { passes.add(markPureFunctions); } else if (options.markNoSideEffectCalls) { // TODO(user) The properties that this pass adds to CALL and NEW // AST nodes increase the AST's in-memory size. Given that we are // already running close to our memory limits, we could run into // trouble if we end up using the @nosideeffects annotation a lot // or compute @nosideeffects annotations by looking at function // bodies. It should be easy to propagate @nosideeffects // annotations as part of passes that depend on this property and // store the result outside the AST (which would allow garbage // collection once the pass is done). passes.add(markNoSideEffectCalls); } if (options.chainCalls) { passes.add(chainCalls); } // Constant checking must be done after property collapsing because // property collapsing can introduce new constants (e.g. enum values). if (options.inlineConstantVars) { passes.add(checkConsts); } // The Caja library adds properties to Object.prototype, which breaks // most for-in loops. This adds a check to each loop that skips // any property matching /___$/. if (options.ignoreCajaProperties) { passes.add(ignoreCajaProperties); } assertAllOneTimePasses(passes); if (options.smartNameRemoval || options.reportPath != null) { passes.addAll(getCodeRemovingPasses()); passes.add(smartNamePass); } // TODO(user): This forces a first crack at crossModuleCodeMotion // before devirtualization. Once certain functions are devirtualized, // it confuses crossModuleCodeMotion ability to recognized that // it is recursive. // TODO(user): This is meant for a temporary quick win. // In the future, we might want to improve our analysis in // CrossModuleCodeMotion so we don't need to do this. if (options.crossModuleCodeMotion) { passes.add(crossModuleCodeMotion); } // Method devirtualization benefits from property disambiguiation so // it should run after that pass but before passes that do // optimizations based on global names (like cross module code motion // and inline functions). Smart Name Removal does better if run before // this pass. if (options.devirtualizePrototypeMethods) { passes.add(devirtualizePrototypeMethods); } if (options.customPasses != null) { passes.add(getCustomPasses( CustomPassExecutionTime.BEFORE_OPTIMIZATION_LOOP)); } passes.add(createEmptyPass("beforeMainOptimizations")); passes.addAll(getMainOptimizationLoop()); passes.add(createEmptyPass("beforeModuleMotion")); if (options.crossModuleCodeMotion) { passes.add(crossModuleCodeMotion); } if (options.crossModuleMethodMotion) { passes.add(crossModuleMethodMotion); } passes.add(createEmptyPass("afterModuleMotion")); // Some optimizations belong outside the loop because running them more // than once would either have no benefit or be incorrect. if (options.customPasses != null) { passes.add(getCustomPasses( CustomPassExecutionTime.AFTER_OPTIMIZATION_LOOP)); } if (options.flowSensitiveInlineVariables) { passes.add(flowSensitiveInlineVariables); // After inlining some of the variable uses, some variables are unused. // Re-run remove unused vars to clean it up. if (options.removeUnusedVars) { passes.add(removeUnusedVars); } } if (options.collapseAnonymousFunctions) { passes.add(collapseAnonymousFunctions); } // Move functions before extracting prototype member declarations. if (options.moveFunctionDeclarations) { passes.add(moveFunctionDeclarations); } if (options.anonymousFunctionNaming == AnonymousFunctionNamingPolicy.MAPPED) { passes.add(nameMappedAnonymousFunctions); } // The mapped name anonymous function pass makes use of information that // the extract prototype member declarations pass removes so the former // happens before the latter. // // Extracting prototype properties screws up the heuristic renaming // policies, so never run it when those policies are requested. if (options.extractPrototypeMemberDeclarations && (options.propertyRenaming != PropertyRenamingPolicy.HEURISTIC && options.propertyRenaming != PropertyRenamingPolicy.AGGRESSIVE_HEURISTIC)) { passes.add(extractPrototypeMemberDeclarations); } if (options.coalesceVariableNames) { passes.add(coalesceVariableNames); } if (options.ambiguateProperties && (options.propertyRenaming == PropertyRenamingPolicy.ALL_UNQUOTED)) { passes.add(ambiguateProperties); } if (options.propertyRenaming != PropertyRenamingPolicy.OFF) { passes.add(renameProperties); } // Reserve global names added to the "windows" object. if (options.reserveRawExports) { passes.add(gatherRawExports); } // This comes after property renaming because quoted property names must // not be renamed. if (options.convertToDottedProperties) { passes.add(convertToDottedProperties); } // Property renaming must happen before this pass runs since this // pass may convert dotted properties into quoted properties. It // is beneficial to run before alias strings, alias keywords and // variable renaming. if (options.rewriteFunctionExpressions) { passes.add(rewriteFunctionExpressions); } // This comes after converting quoted property accesses to dotted property // accesses in order to avoid aliasing property names. if (!options.aliasableStrings.isEmpty() || options.aliasAllStrings) { passes.add(aliasStrings); } if (options.aliasExternals) { passes.add(aliasExternals); } if (options.aliasKeywords) { passes.add(aliasKeywords); } if (options.collapseVariableDeclarations) { passes.add(collapseVariableDeclarations); } passes.add(denormalize); if (options.instrumentationTemplate != null) { passes.add(instrumentFunctions); } if (options.variableRenaming != VariableRenamingPolicy.ALL) { // If we're leaving some (or all) variables with their old names, // then we need to undo any of the markers we added for distinguishing // local variables ("$$1"). passes.add(invertContextualRenaming); } if (options.variableRenaming != VariableRenamingPolicy.OFF) { passes.add(renameVars); } // This pass should run after names stop changing. if (options.processObjectPropertyString) { passes.add(objectPropertyStringPostprocess); } if (options.labelRenaming) { passes.add(renameLabels); } if (options.anonymousFunctionNaming == AnonymousFunctionNamingPolicy.UNMAPPED) { passes.add(nameUnmappedAnonymousFunctions); } // Safety check if (options.checkSymbols) { passes.add(sanityCheckVars); } return passes; }
diff --git a/hazelcast/src/main/java/com/hazelcast/map/operation/MapReplicationOperation.java b/hazelcast/src/main/java/com/hazelcast/map/operation/MapReplicationOperation.java index 844d3e899f..a4e64913c4 100644 --- a/hazelcast/src/main/java/com/hazelcast/map/operation/MapReplicationOperation.java +++ b/hazelcast/src/main/java/com/hazelcast/map/operation/MapReplicationOperation.java @@ -1,192 +1,192 @@ /* * Copyright (c) 2008-2013, Hazelcast, 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 com.hazelcast.map.operation; import com.hazelcast.config.MapConfig; import com.hazelcast.map.MapContainer; import com.hazelcast.map.MapService; import com.hazelcast.map.PartitionContainer; import com.hazelcast.map.RecordStore; import com.hazelcast.map.record.Record; import com.hazelcast.map.record.RecordReplicationInfo; import com.hazelcast.nio.ObjectDataInput; import com.hazelcast.nio.ObjectDataOutput; import com.hazelcast.nio.serialization.Data; import com.hazelcast.nio.serialization.SerializationService; import com.hazelcast.spi.AbstractOperation; import com.hazelcast.util.Clock; import com.hazelcast.util.scheduler.ScheduledEntry; import java.io.IOException; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Map.Entry; import java.util.Set; /** * @author mdogan 7/24/12 */ public class MapReplicationOperation extends AbstractOperation { private Map<String, Set<RecordReplicationInfo>> data; private Map<String, Boolean> mapInitialLoadInfo; public MapReplicationOperation() { } public MapReplicationOperation(PartitionContainer container, int partitionId, int replicaIndex) { this.setPartitionId(partitionId).setReplicaIndex(replicaIndex); SerializationService ss = container.getMapService().getSerializationService(); data = new HashMap<String, Set<RecordReplicationInfo>>(container.getMaps().size()); mapInitialLoadInfo = new HashMap<String, Boolean>(container.getMaps().size()); for (Entry<String, RecordStore> entry : container.getMaps().entrySet()) { RecordStore recordStore = entry.getValue(); MapContainer mapContainer = recordStore.getMapContainer(); final MapConfig mapConfig = mapContainer.getMapConfig(); if (mapConfig.getTotalBackupCount() < replicaIndex) { continue; } String name = entry.getKey(); // adding if initial data is loaded for the only maps that has mapstore behind if(mapContainer.getStore() != null) { mapInitialLoadInfo.put(name, recordStore.isLoaded()); } // now prepare data to migrate records - Set<RecordReplicationInfo> recordSet = new HashSet<RecordReplicationInfo>(); + Set<RecordReplicationInfo> recordSet = new HashSet<RecordReplicationInfo>(recordStore.size()); for (Entry<Data, Record> recordEntry : recordStore.getReadonlyRecordMap().entrySet()) { Data key = recordEntry.getKey(); Record record = recordEntry.getValue(); RecordReplicationInfo recordReplicationInfo; if (replicaIndex == 0) { recordReplicationInfo = createScheduledRecordState(mapContainer, recordEntry, key); } else { recordReplicationInfo = new RecordReplicationInfo(record.getKey(), ss.toData(record.getValue()), record.getStatistics()); } recordSet.add(recordReplicationInfo); } data.put(name, recordSet); } } private RecordReplicationInfo createScheduledRecordState(MapContainer mapContainer, Entry<Data, Record> recordEntry, Data key) { ScheduledEntry idleScheduledEntry = mapContainer.getIdleEvictionScheduler() == null ? null : mapContainer.getIdleEvictionScheduler().cancel(key); long idleDelay = idleScheduledEntry == null ? -1 : findDelayMillis(idleScheduledEntry); ScheduledEntry ttlScheduledEntry = mapContainer.getTtlEvictionScheduler() == null ? null : mapContainer.getTtlEvictionScheduler().cancel(key); long ttlDelay = ttlScheduledEntry == null ? -1 : findDelayMillis(ttlScheduledEntry); ScheduledEntry writeScheduledEntry = mapContainer.getMapStoreWriteScheduler() == null ? null : mapContainer.getMapStoreWriteScheduler().cancel(key); long writeDelay = writeScheduledEntry == null ? -1 : findDelayMillis(writeScheduledEntry); ScheduledEntry deleteScheduledEntry = mapContainer.getMapStoreDeleteScheduler() == null ? null : mapContainer.getMapStoreDeleteScheduler().cancel(key); long deleteDelay = deleteScheduledEntry == null ? -1 : findDelayMillis(deleteScheduledEntry); Record record = recordEntry.getValue(); SerializationService ss = mapContainer.getMapService().getSerializationService(); return new RecordReplicationInfo(record.getKey(), ss.toData(record.getValue()), record.getStatistics(), idleDelay, ttlDelay, writeDelay, deleteDelay); } public void run() { MapService mapService = getService(); if (data != null) { for (Entry<String, Set<RecordReplicationInfo>> dataEntry : data.entrySet()) { Set<RecordReplicationInfo> recordReplicationInfos = dataEntry.getValue(); final String mapName = dataEntry.getKey(); RecordStore recordStore = mapService.getRecordStore(getPartitionId(), mapName); for (RecordReplicationInfo recordReplicationInfo : recordReplicationInfos) { Data key = recordReplicationInfo.getKey(); Record newRecord = mapService.createRecord(mapName, key, recordReplicationInfo.getValue(), -1, false); newRecord.setStatistics(recordReplicationInfo.getStatistics()); recordStore.putRecord(key, newRecord); if (recordReplicationInfo.getIdleDelayMillis() >= 0) { mapService.scheduleIdleEviction(mapName, key, recordReplicationInfo.getIdleDelayMillis()); } if (recordReplicationInfo.getTtlDelayMillis() >= 0) { mapService.scheduleTtlEviction(mapName, newRecord, recordReplicationInfo.getTtlDelayMillis()); } if (recordReplicationInfo.getMapStoreWriteDelayMillis() >= 0) { mapService.scheduleMapStoreWrite(mapName, key, newRecord.getValue(), recordReplicationInfo.getMapStoreWriteDelayMillis()); } if (recordReplicationInfo.getMapStoreDeleteDelayMillis() >= 0) { mapService.scheduleMapStoreDelete(mapName, key, recordReplicationInfo.getMapStoreDeleteDelayMillis()); } } } } if(mapInitialLoadInfo != null) { for (String mapName : mapInitialLoadInfo.keySet()) { RecordStore recordStore = mapService.getRecordStore(getPartitionId(), mapName); recordStore.setLoaded(mapInitialLoadInfo.get(mapName)); } } } private long findDelayMillis(ScheduledEntry entry) { return Math.max(0, entry.getScheduledDelayMillis() - (Clock.currentTimeMillis() - entry.getScheduleTime())); } public String getServiceName() { return MapService.SERVICE_NAME; } protected void readInternal(final ObjectDataInput in) throws IOException { int size = in.readInt(); data = new HashMap<String, Set<RecordReplicationInfo>>(size); for (int i = 0; i < size; i++) { String name = in.readUTF(); int mapSize = in.readInt(); Set<RecordReplicationInfo> recordReplicationInfos = new HashSet<RecordReplicationInfo>(mapSize); for (int j = 0; j < mapSize; j++) { RecordReplicationInfo recordReplicationInfo = in.readObject(); recordReplicationInfos.add(recordReplicationInfo); } data.put(name, recordReplicationInfos); } size = in.readInt(); mapInitialLoadInfo = new HashMap<String, Boolean>(size); for (int i = 0; i < size; i++) { String name = in.readUTF(); boolean loaded = in.readBoolean(); mapInitialLoadInfo.put(name, loaded); } } protected void writeInternal(final ObjectDataOutput out) throws IOException { out.writeInt(data.size()); for (Entry<String, Set<RecordReplicationInfo>> mapEntry : data.entrySet()) { out.writeUTF(mapEntry.getKey()); Set<RecordReplicationInfo> recordReplicationInfos = mapEntry.getValue(); out.writeInt(recordReplicationInfos.size()); for (RecordReplicationInfo recordReplicationInfo : recordReplicationInfos) { out.writeObject(recordReplicationInfo); } } out.writeInt(mapInitialLoadInfo.size()); for (Entry<String, Boolean> entry : mapInitialLoadInfo.entrySet()) { out.writeUTF(entry.getKey()); out.writeBoolean(entry.getValue()); } } public boolean isEmpty() { return data == null || data.isEmpty(); } }
true
true
public MapReplicationOperation(PartitionContainer container, int partitionId, int replicaIndex) { this.setPartitionId(partitionId).setReplicaIndex(replicaIndex); SerializationService ss = container.getMapService().getSerializationService(); data = new HashMap<String, Set<RecordReplicationInfo>>(container.getMaps().size()); mapInitialLoadInfo = new HashMap<String, Boolean>(container.getMaps().size()); for (Entry<String, RecordStore> entry : container.getMaps().entrySet()) { RecordStore recordStore = entry.getValue(); MapContainer mapContainer = recordStore.getMapContainer(); final MapConfig mapConfig = mapContainer.getMapConfig(); if (mapConfig.getTotalBackupCount() < replicaIndex) { continue; } String name = entry.getKey(); // adding if initial data is loaded for the only maps that has mapstore behind if(mapContainer.getStore() != null) { mapInitialLoadInfo.put(name, recordStore.isLoaded()); } // now prepare data to migrate records Set<RecordReplicationInfo> recordSet = new HashSet<RecordReplicationInfo>(); for (Entry<Data, Record> recordEntry : recordStore.getReadonlyRecordMap().entrySet()) { Data key = recordEntry.getKey(); Record record = recordEntry.getValue(); RecordReplicationInfo recordReplicationInfo; if (replicaIndex == 0) { recordReplicationInfo = createScheduledRecordState(mapContainer, recordEntry, key); } else { recordReplicationInfo = new RecordReplicationInfo(record.getKey(), ss.toData(record.getValue()), record.getStatistics()); } recordSet.add(recordReplicationInfo); } data.put(name, recordSet); } }
public MapReplicationOperation(PartitionContainer container, int partitionId, int replicaIndex) { this.setPartitionId(partitionId).setReplicaIndex(replicaIndex); SerializationService ss = container.getMapService().getSerializationService(); data = new HashMap<String, Set<RecordReplicationInfo>>(container.getMaps().size()); mapInitialLoadInfo = new HashMap<String, Boolean>(container.getMaps().size()); for (Entry<String, RecordStore> entry : container.getMaps().entrySet()) { RecordStore recordStore = entry.getValue(); MapContainer mapContainer = recordStore.getMapContainer(); final MapConfig mapConfig = mapContainer.getMapConfig(); if (mapConfig.getTotalBackupCount() < replicaIndex) { continue; } String name = entry.getKey(); // adding if initial data is loaded for the only maps that has mapstore behind if(mapContainer.getStore() != null) { mapInitialLoadInfo.put(name, recordStore.isLoaded()); } // now prepare data to migrate records Set<RecordReplicationInfo> recordSet = new HashSet<RecordReplicationInfo>(recordStore.size()); for (Entry<Data, Record> recordEntry : recordStore.getReadonlyRecordMap().entrySet()) { Data key = recordEntry.getKey(); Record record = recordEntry.getValue(); RecordReplicationInfo recordReplicationInfo; if (replicaIndex == 0) { recordReplicationInfo = createScheduledRecordState(mapContainer, recordEntry, key); } else { recordReplicationInfo = new RecordReplicationInfo(record.getKey(), ss.toData(record.getValue()), record.getStatistics()); } recordSet.add(recordReplicationInfo); } data.put(name, recordSet); } }
diff --git a/src/main/java/net/nexisonline/spade/populators/SedimentGenerator.java b/src/main/java/net/nexisonline/spade/populators/SedimentGenerator.java index 739af8b..2af82d5 100644 --- a/src/main/java/net/nexisonline/spade/populators/SedimentGenerator.java +++ b/src/main/java/net/nexisonline/spade/populators/SedimentGenerator.java @@ -1,123 +1,123 @@ package net.nexisonline.spade.populators; import java.util.HashMap; import java.util.Map; import java.util.Random; import net.nexisonline.spade.SpadeConf; import net.nexisonline.spade.SpadeLogging; import net.nexisonline.spade.SpadePlugin; import org.bukkit.Chunk; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.block.Biome; import org.bukkit.util.config.ConfigurationNode; /** * Converted from MineEdit * @author Rob * */ public class SedimentGenerator extends SpadeEffectGenerator { private int waterHeight; public SedimentGenerator(SpadePlugin plugin, Map<String,Object> node, long seed) { super(plugin, node, seed); waterHeight = SpadeConf.getInt(node,"water-height",63); } public static SpadeEffectGenerator getInstance(SpadePlugin plugin, Map n, long seed) { Map<String,Object> node = (Map<String,Object>)n; return new SedimentGenerator(plugin,node,seed); } private int topBlockY(Chunk blocks, int x, int z) { int y = 127; for(; y>0 && !blockIsSolid((byte) blocks.getBlock(x,y,z).getTypeId()); --y) {} return y; } private boolean blockIsSolid(byte b) { Material mat = Material.getMaterial(b); return mat!=Material.AIR && mat!=Material.WATER && mat!=Material.STATIONARY_WATER && mat!=Material.LAVA && mat!=Material.STATIONARY_LAVA; } @Override public Map<String, Object> getConfiguration() { Map<String,Object> cfg = new HashMap<String,Object>(); cfg.put("water-height",waterHeight); return cfg; } @Override public void populate(World world, Random rand, Chunk chunk) { SpadeLogging.info(String.format("Generating sediment in chunk (%d,%d)",chunk.getX(),chunk.getZ())); int YH = 128; for (int x = 0; x < 16; x++) { for (int z = 0; z < 16; z++) { //int H=Math.max(Math.min(topBlockY(chunk, x, z),127),16); /*int nextH=0; if(x!=15) nextH=Math.max(Math.min(topBlockY(chunk, x+1, z),127),16); else nextH=Math.max(Math.min(topBlockY(chunk, x-1, z),127),16); */ boolean HavePloppedGrass = false; for (int y = 127; y > 0; y--) { byte supportBlock = (byte) chunk.getBlock(x, y-1, z).getTypeId(); byte thisblock = (byte) chunk.getBlock(x, y, z).getTypeId(); // Ensure there's going to be stuff holding us up. if (thisblock == Material.STONE.getId() && supportBlock==Material.STONE.getId()) { - int depth= 10*(y/128);/*/nextH*/; + int depth= 6;//10*(y/128);/*/nextH*/; if (y + depth >= YH) continue; int ddt = chunk.getBlock(x, y+depth, z).getTypeId(); - Biome bt = Biome.RAINFOREST; // TODO Figure out how to get a biome. + Biome bt = chunk.getBlock(x, y, z).getBiome(); switch (ddt) { case 0: // Air case 8: // Water case 9: // Water if (bt == Biome.TUNDRA) { thisblock=(byte) Material.SAND.getId(); } else { if (y - depth <= waterHeight) { if ((bt == Biome.TAIGA || bt == Biome.SEASONAL_FOREST || bt == Biome.TUNDRA) && y > waterHeight) { thisblock=(byte) ((HavePloppedGrass) ? Material.DIRT.getId() : Material.GRASS.getId()); } else { thisblock=(byte) (Material.SAND.getId()); } } else thisblock= (byte) ((HavePloppedGrass) ? Material.DIRT.getId() : Material.GRASS.getId()); } chunk.getBlock(x, y, z).setTypeId(thisblock); if (!HavePloppedGrass) HavePloppedGrass = true; break; default: y = 0; break; } } } } } } }
false
true
public void populate(World world, Random rand, Chunk chunk) { SpadeLogging.info(String.format("Generating sediment in chunk (%d,%d)",chunk.getX(),chunk.getZ())); int YH = 128; for (int x = 0; x < 16; x++) { for (int z = 0; z < 16; z++) { //int H=Math.max(Math.min(topBlockY(chunk, x, z),127),16); /*int nextH=0; if(x!=15) nextH=Math.max(Math.min(topBlockY(chunk, x+1, z),127),16); else nextH=Math.max(Math.min(topBlockY(chunk, x-1, z),127),16); */ boolean HavePloppedGrass = false; for (int y = 127; y > 0; y--) { byte supportBlock = (byte) chunk.getBlock(x, y-1, z).getTypeId(); byte thisblock = (byte) chunk.getBlock(x, y, z).getTypeId(); // Ensure there's going to be stuff holding us up. if (thisblock == Material.STONE.getId() && supportBlock==Material.STONE.getId()) { int depth= 10*(y/128);/*/nextH*/; if (y + depth >= YH) continue; int ddt = chunk.getBlock(x, y+depth, z).getTypeId(); Biome bt = Biome.RAINFOREST; // TODO Figure out how to get a biome. switch (ddt) { case 0: // Air case 8: // Water case 9: // Water if (bt == Biome.TUNDRA) { thisblock=(byte) Material.SAND.getId(); } else { if (y - depth <= waterHeight) { if ((bt == Biome.TAIGA || bt == Biome.SEASONAL_FOREST || bt == Biome.TUNDRA) && y > waterHeight) { thisblock=(byte) ((HavePloppedGrass) ? Material.DIRT.getId() : Material.GRASS.getId()); } else { thisblock=(byte) (Material.SAND.getId()); } } else thisblock= (byte) ((HavePloppedGrass) ? Material.DIRT.getId() : Material.GRASS.getId()); } chunk.getBlock(x, y, z).setTypeId(thisblock); if (!HavePloppedGrass) HavePloppedGrass = true; break; default: y = 0; break; } } } } } }
public void populate(World world, Random rand, Chunk chunk) { SpadeLogging.info(String.format("Generating sediment in chunk (%d,%d)",chunk.getX(),chunk.getZ())); int YH = 128; for (int x = 0; x < 16; x++) { for (int z = 0; z < 16; z++) { //int H=Math.max(Math.min(topBlockY(chunk, x, z),127),16); /*int nextH=0; if(x!=15) nextH=Math.max(Math.min(topBlockY(chunk, x+1, z),127),16); else nextH=Math.max(Math.min(topBlockY(chunk, x-1, z),127),16); */ boolean HavePloppedGrass = false; for (int y = 127; y > 0; y--) { byte supportBlock = (byte) chunk.getBlock(x, y-1, z).getTypeId(); byte thisblock = (byte) chunk.getBlock(x, y, z).getTypeId(); // Ensure there's going to be stuff holding us up. if (thisblock == Material.STONE.getId() && supportBlock==Material.STONE.getId()) { int depth= 6;//10*(y/128);/*/nextH*/; if (y + depth >= YH) continue; int ddt = chunk.getBlock(x, y+depth, z).getTypeId(); Biome bt = chunk.getBlock(x, y, z).getBiome(); switch (ddt) { case 0: // Air case 8: // Water case 9: // Water if (bt == Biome.TUNDRA) { thisblock=(byte) Material.SAND.getId(); } else { if (y - depth <= waterHeight) { if ((bt == Biome.TAIGA || bt == Biome.SEASONAL_FOREST || bt == Biome.TUNDRA) && y > waterHeight) { thisblock=(byte) ((HavePloppedGrass) ? Material.DIRT.getId() : Material.GRASS.getId()); } else { thisblock=(byte) (Material.SAND.getId()); } } else thisblock= (byte) ((HavePloppedGrass) ? Material.DIRT.getId() : Material.GRASS.getId()); } chunk.getBlock(x, y, z).setTypeId(thisblock); if (!HavePloppedGrass) HavePloppedGrass = true; break; default: y = 0; break; } } } } } }
diff --git a/src/main/java/no/uio/master/autoscale/agent/AutoscaleAgent.java b/src/main/java/no/uio/master/autoscale/agent/AutoscaleAgent.java index a7c8159..1562bc0 100644 --- a/src/main/java/no/uio/master/autoscale/agent/AutoscaleAgent.java +++ b/src/main/java/no/uio/master/autoscale/agent/AutoscaleAgent.java @@ -1,42 +1,42 @@ package no.uio.master.autoscale.agent; import java.io.IOException; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import no.uio.master.autoscale.agent.config.Config; import no.uio.master.autoscale.agent.service.AutoscaleAgentServer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Initial startup of autocale-agent implementation.<br> * This class is only used for initial setup of the daemon. * @author andreas * */ public class AutoscaleAgent { private static Logger LOG = LoggerFactory.getLogger(AutoscaleAgent.class); private static ScheduledExecutorService executor; private static AutoscaleAgentServer server; private static int INTERVALL_TIMER = Config.intervall_timer; public static void main(String[] args) { - LOG.debug("Autoscale agent invoked..."); + LOG.info("Autoscale agent invoked..."); try { server = new AutoscaleAgentServer(); } catch (IOException e) { LOG.error("Failed to initialize agent server"); } executor = Executors.newSingleThreadScheduledExecutor(); executor.scheduleAtFixedRate(server, 0, INTERVALL_TIMER, TimeUnit.SECONDS); LOG.debug("Invoked"); } }
true
true
public static void main(String[] args) { LOG.debug("Autoscale agent invoked..."); try { server = new AutoscaleAgentServer(); } catch (IOException e) { LOG.error("Failed to initialize agent server"); } executor = Executors.newSingleThreadScheduledExecutor(); executor.scheduleAtFixedRate(server, 0, INTERVALL_TIMER, TimeUnit.SECONDS); LOG.debug("Invoked"); }
public static void main(String[] args) { LOG.info("Autoscale agent invoked..."); try { server = new AutoscaleAgentServer(); } catch (IOException e) { LOG.error("Failed to initialize agent server"); } executor = Executors.newSingleThreadScheduledExecutor(); executor.scheduleAtFixedRate(server, 0, INTERVALL_TIMER, TimeUnit.SECONDS); LOG.debug("Invoked"); }
diff --git a/dspace-api/src/main/java/org/dspace/browse/ItemCounter.java b/dspace-api/src/main/java/org/dspace/browse/ItemCounter.java index cb2b8d0a0..5af58b8f8 100644 --- a/dspace-api/src/main/java/org/dspace/browse/ItemCounter.java +++ b/dspace-api/src/main/java/org/dspace/browse/ItemCounter.java @@ -1,291 +1,291 @@ /* * ItemCounter.java * * Copyright (c) 2002-2007, 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.browse; import org.apache.log4j.Logger; import org.dspace.content.Community; import org.dspace.content.Collection; import org.dspace.core.Context; import org.dspace.content.DSpaceObject; import org.dspace.core.ConfigurationManager; import java.sql.SQLException; /** * This class provides a standard interface to all item counting * operations for communities and collections. It can be run from the * command line to prepare the cached data if desired, simply by * running: * * java org.dspace.browse.ItemCounter * * It can also be invoked via its standard API. In the event that * the data cache is not being used, this class will return direct * real time counts of content. * * @author Richard Jones * */ public class ItemCounter { /** Log4j logger */ private static Logger log = Logger.getLogger(ItemCounter.class); /** DAO to use to store and retrieve data */ private ItemCountDAO dao; /** DSpace Context */ private Context context; /** * method invoked by CLI which will result in the number of items * in each community and collection being cached. These counts will * not update themselves until this is run again. * * @param args */ public static void main(String[] args) throws ItemCountException { ItemCounter ic = new ItemCounter(); ic.buildItemCounts(); ic.completeContext(); } /** * Construct a new item counter which will create its own * DSpace Context * * @throws ItemCountException */ public ItemCounter() throws ItemCountException { try { this.context = new Context(); this.dao = ItemCountDAOFactory.getInstance(this.context); } catch (SQLException e) { log.error("caught exception: ", e); throw new ItemCountException(e); } } /** * Construct a new item counter which will use the give DSpace Context * * @param context * @throws ItemCountException */ public ItemCounter(Context context) throws ItemCountException { this.context = context; this.dao = ItemCountDAOFactory.getInstance(this.context); } /** * Complete the context being used by this class. This exists so that * instances of this class which created their own instance of the * DSpace Context can also terminate it. For Context object which were * passed in by the constructor, the caller is responsible for * either calling this method themselves or completing the context * when they need to. * * @throws ItemCountException */ public void completeContext() throws ItemCountException { try { this.context.complete(); } catch (SQLException e) { log.error("caught exception: ", e); throw new ItemCountException(e); } } /** * This method does the grunt work of drilling through and iterating * over all of the communities and collections in the system and * obtaining and caching the item counts for each one. * * @throws ItemCountException */ public void buildItemCounts() throws ItemCountException { try { Community[] tlc = Community.findAllTop(context); for (int i = 0; i < tlc.length; i++) { count(tlc[i]); } } catch (SQLException e) { log.error("caught exception: ", e); throw new ItemCountException(e); } } /** * Get the count of the items in the given container. If the configuration * value webui.strengths.cache is equal to 'true' this will return the * cached value if it exists. If it is equal to 'false' it will count * the number of items in the container in real time * * @param dso * @return * @throws ItemCountException * @throws SQLException */ public int getCount(DSpaceObject dso) throws ItemCountException { boolean useCache = ConfigurationManager.getBooleanProperty("webui.strengths.cache"); if (useCache) { return dao.getCount(dso); } // if we make it this far, we need to manually count if (dso instanceof Collection) { try { return ((Collection) dso).countItems(); } catch (SQLException e) { log.error("caught exception: ", e); throw new ItemCountException(e); } } if (dso instanceof Community) { try { - return ((Collection) dso).countItems(); + return ((Community) dso).countItems(); } catch (SQLException e) { log.error("caught exception: ", e); throw new ItemCountException(e); } } return 0; } /** * Remove any cached data for the given container * * @param dso * @throws ItemCountException */ public void remove(DSpaceObject dso) throws ItemCountException { dao.remove(dso); } /** * count and cache the number of items in the community. This * will include all sub-communities and collections in the * community. It will also recurse into sub-communities and * collections and call count() on them also. * * Therefore, the count the contents of the entire system, it is * necessary just to call this method on each top level community * * @param community * @throws ItemCountException */ private void count(Community community) throws ItemCountException { try { // first count the community we are in int count = community.countItems(); dao.communityCount(community, count); // now get the sub-communities Community[] scs = community.getSubcommunities(); for (int i = 0; i < scs.length; i++) { count(scs[i]); } // now get the collections Collection[] cols = community.getCollections(); for (int i = 0; i < cols.length; i++) { count(cols[i]); } } catch (SQLException e) { log.error("caught exception: ", e); throw new ItemCountException(e); } } /** * count and cache the number of items in the given collection * * @param collection * @throws ItemCountException */ private void count(Collection collection) throws ItemCountException { try { int ccount = collection.countItems(); dao.collectionCount(collection, ccount); } catch (SQLException e) { log.error("caught exception: ", e); throw new ItemCountException(e); } } }
true
true
public int getCount(DSpaceObject dso) throws ItemCountException { boolean useCache = ConfigurationManager.getBooleanProperty("webui.strengths.cache"); if (useCache) { return dao.getCount(dso); } // if we make it this far, we need to manually count if (dso instanceof Collection) { try { return ((Collection) dso).countItems(); } catch (SQLException e) { log.error("caught exception: ", e); throw new ItemCountException(e); } } if (dso instanceof Community) { try { return ((Collection) dso).countItems(); } catch (SQLException e) { log.error("caught exception: ", e); throw new ItemCountException(e); } } return 0; }
public int getCount(DSpaceObject dso) throws ItemCountException { boolean useCache = ConfigurationManager.getBooleanProperty("webui.strengths.cache"); if (useCache) { return dao.getCount(dso); } // if we make it this far, we need to manually count if (dso instanceof Collection) { try { return ((Collection) dso).countItems(); } catch (SQLException e) { log.error("caught exception: ", e); throw new ItemCountException(e); } } if (dso instanceof Community) { try { return ((Community) dso).countItems(); } catch (SQLException e) { log.error("caught exception: ", e); throw new ItemCountException(e); } } return 0; }